tods-competition-factory 2.0.0-alpha.0 → 3.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- function t(){return"2.0.0-alpha.0"}function e(t,e){return t-e}function n(t){return"number"==typeof t?parseInt(t.toString()):parseInt(t)}function r(t){return!isNaN(t)&&(t&&0==(t&t-1))}function i(t){if(!t.length)return;const n=[...t].sort(e),r=Math.floor(n.length/2);return n.length%2?n[r]:(n[r-1]+n[r])/2}function a(t){return isNaN(t)?0:t%2&&t+1||t}function o(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function s(t){return!isNaN(parseFloat(t))}function c(t){const e=n(t);if(!isNaN(e))return 0!==e&&1==(e&-e)}function u(t){if(isNaN(t))return!1;for(;!r(t);)t++;return t}function d(t,e){return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t}function p(t){return Number.isSafeInteger("string"==typeof t?+t:t)}function l(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=l(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 m(t){return t?.filter(((t,e,n)=>n.lastIndexOf(t)===e))}function f(t){return t.map((t=>[Math.random(),t])).sort(((t,e)=>t[0]-e[0])).map((t=>t[1]))}function h(t){return p(t)?t:1/0}function g(t){return t.reduce(((t,e)=>(t[e]||(t[e]=0),t[e]++,t)),{})}function I(t){return Object.keys(t).reduce(((e,n)=>{const r=t[n];return e[r]?e[r].push(n):e[r]=[n],e}),{})}function U(t,e,n){return n.indexOf(t)===e}function S(t){return t.filter(U)}function y(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function v(t){return t[Math.floor(Math.random()*t.length)]}function w(t,e){return Array.from({length:e-t},((e,n)=>n+t))}function T(t,e){return e.reduce(((e,n,r)=>(n===t&&e.push(r),e)),[])}function P(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 D(t,e){return Array.isArray(t)&&Array.isArray(e)?t.filter((t=>!e.includes(t))):[]}function b(t,e){return!(!Array.isArray(t)||!Array.isArray(e))&&t.some((t=>e.includes(t)))}function N(t,e){return t.reduce(((t,n,r)=>{const i=Math.floor(r/e);return t[i]=[].concat(t[i]||[],n),t}),[])}function R(t){return t.reduce(((t,e)=>!isNaN(parseInt(e))&&t),!0)}function M(t){return t.reduce(((t,e)=>isNaN(parseInt(e))&&t),!0)}function A(t,e,n){return 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}),[])}const E={success:!0},C={SUCCESS:E,ERROR:"error"},O={message:"Chronological error; time violation.",code:"ANACHRONISM"},F={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},k={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},x={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},_={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},L={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},B={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},V={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},j={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},G={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},q={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},$={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},W={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},H={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},z={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},Y={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},K={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},J={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Z={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},X={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},Q={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},tt={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},et={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},nt={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},rt={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},it={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},at={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},ot={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},st={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},ct={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},ut={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},dt={message:"Invalid action",code:"ERR_INVALID_ACTION"},pt={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},lt={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},mt={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},ft={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},ht={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},gt={message:"Existing round",code:"ERR_EXISTING_ROUND"},It={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},Ut={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},St={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},yt={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},vt={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},wt={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"},Tt={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},Pt={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},Dt={message:"Event exists",code:"ERR_EXISTING_EVENT"},bt={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},Nt={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Rt={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},Mt={message:"Missing stage",code:"ERR_MISSING_STAGE"},At={message:"Invalid stage",code:"ERR_INVALID_STAGE"},Et={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},Ct={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},Ot={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},Ft={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},kt={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},xt={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},_t={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},Lt={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Bt={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Vt={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},jt={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},Gt={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},qt={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},$t={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},Wt={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},Ht={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},zt={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},Yt={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},Kt={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Jt={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},Zt={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},Xt={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},Qt={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},te={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},ee={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},ne={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},re={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},ie={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},ae={message:"Missing value",code:"ERR_MISSING_VALUE"},oe={message:"Missing date",code:"ERR_MISSING_DATE"},se={message:"No valid dates",code:"ERR_NO_VALID_DATES"},ce={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},ue={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},de={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},pe={message:"Invalid Date",code:"ERR_INVALID_DATE"},le={message:"Invalid time",code:"ERR_INVALID_TIME"},me={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"},fe={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},he={message:"Invalid score",code:"ERR_INVALID_SCORE"},ge={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"},Ie={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},Ue={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},Se={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},ye={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},ve={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},we={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},Te={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},Pe={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},De={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},be={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},Ne={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Re={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},Me={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},Ae={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},Ee={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},Ce={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},Oe={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},Fe={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},ke={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},xe={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},_e={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Le={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},Be={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},Ve={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},je={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},Ge={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},qe={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},$e={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},We={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},He={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},ze={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},Ye={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},Ke={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},Je={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},Ze={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},Xe={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},Qe={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},tn={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},en={message:"Court exists",code:"ERR_EXISTING_COURT"},nn={message:"Venue exists",code:"ERR_EXISTING_VENUE"},rn={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},an={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},on={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},sn={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},cn={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},un={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},dn={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},pn={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},ln={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},mn={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},fn={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},hn={message:"Missing context",code:"ERR_MISSING_CONTEXT"},gn={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},In={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},Un={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},Sn={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},yn={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},vn={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},wn={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},Tn={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},Pn={message:"Invalid object",code:"ERR_INVALID_OBJECT"},Dn={message:"Invalid gender",code:"ERR_INVALID_GENDER"},bn={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},Nn={message:"Invalid values",code:"ERR_INVALID_VALUES"},Rn={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},Mn={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},An={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},En={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},Cn={message:"Value unchanged",code:"ABORT_UNCHANGED"},On={message:"Not found",code:"ERR_NOT_FOUND"},Fn={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},kn={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},xn={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},_n={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},Ln={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},Bn={message:"Existing stage",code:"ERR_EXISTING_STAGE"},Vn={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},jn={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},Gn={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},qn={message:"Scores present",code:"ERR_SCORES_PRESENT"},$n={ANACHRONISM:O,CANNOT_CHANGE_WINNING_SIDE:ve,CANNOT_MODIFY_TIEFORMAT:Ue,CANNOT_MODIFY_PARTICIPANT_TYPE:Se,CANNOT_REMOVE_MAIN_STRUCTURE:F,CANNOT_REMOVE_PARTICIPANTS:ye,COURT_EXISTS:en,COURT_NOT_FOUND:tn,DRAW_DEFINITION_NOT_FOUND:q,DRAW_ID_EXISTS:ot,DRAW_POSITION_ACTIVE:X,DRAW_POSITION_ASSIGNED:z,DRAW_POSITION_NOT_CLEARED:K,DRAW_POSITION_NOT_FOUND:{message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},DRAW_SIZE_MISMATCH:rt,DUPLICATE_VALUE:Rn,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:He,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:We,EVENT_EXISTS:Dt,EVENT_NOT_FOUND:Pt,EXISTING_DRAW_DEFINITIONS:G,EXISTING_END_TIME:sn,EXISTING_FLIGHT:kn,EXISTING_MATCHUP_ID:Ln,EXISTING_OUTCOME:_n,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Le,EXISTING_PARTICIPANT:Be,EXISTING_POLICY_TYPE:te,EXISTING_PROFILE:xn,EXISTING_ROUND:gt,EXISTING_STAGE:Bn,EXISTING_STRUCTURE:Vn,INCOMPATIBLE_MATCHUP_STATUS:xt,INCOMPLETE_SOURCE_STRUCTURE:W,INSUFFICIENT_DRAW_POSITIONS:Ke,INVALID_ACTION:dt,INVALID_ASSIGNMENT:pt,INVALID_BOOKINGS:ce,INVALID_CATEGORY:bn,INVALID_COLLECTION_DEFINITION:Tn,INVALID_CONFIGURATION:wn,INVALID_DATE_AVAILABILITY:ue,INVALID_DATE:pe,INVALID_DRAW_DEFINITION:V,INVALID_DRAW_POSITION_FOR_SEEDING:H,INVALID_DRAW_POSITION:Q,INVALID_DRAW_SIZE:nt,INVALID_END_TIME:on,INVALID_ENTRIES:Nt,INVALID_EVENT_TYPE:wt,INVALID_GAME_SCORES:fe,INVALID_GENDER:Dn,INVALID_MATCHUP_FORMAT:Bt,INVALID_MATCHUP_STATUS:_t,INVALID_MATCHUP_STATUS_BYE:Ot,INVALID_MATCHUP:Yt,INVALID_OBJECT:Pn,INVALID_PARTICIPANT_ID:Te,INVALID_PARTICIPANT_IDS:Pe,INVALID_PARTICIPANT_ROLE:De,INVALID_PARTICIPANT_SEEDING:st,INVALID_PARTICIPANT_TYPE:be,INVALID_PARTICIPANT:we,INVALID_POLICY_DEFINITION:Qt,INVALID_RECORDS:k,INVALID_SCALE_ITEM:In,INVALID_SEED_NUMBER:mt,INVALID_SEED_POSITION:ft,INVALID_SET_NUMBER:{message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},INVALID_SIDE_NUMBER:ne,INVALID_SCORE:he,INVALID_STAGE:At,INVALID_START_TIME:un,INVALID_STRUCTURE:$,INVALID_STOP_TIME:cn,INVALID_TIE_FORMAT:Lt,INVALID_TIME:le,INVALID_TIME_ITEM:pn,INVALID_TOURNAMENT_DATES:me,INVALID_TOURNAMENT_RECORD:L,INVALID_VALUES:Nn,INVALID_WINNING_SIDE:ge,MATCHUP_NOT_FOUND:Wt,METHOD_NOT_FOUND:jn,MISSING_ASSIGNMENTS:Rt,MISSING_ASYNC_STATE_PROVIDER:ln,MISSING_AVOIDANCE_POLICY:Zt,MISSING_COLLECTION_DEFINITION:jt,MISSING_COURT_ID:ie,MISSING_COURTS_INFO:Qe,MISSING_DATE_AVAILABILITY:de,MISSING_DATE:oe,MISSING_DRAW_DEFINITION:j,MISSING_DRAW_ID:at,MISSING_DRAW_POSITION:tt,MISSING_DRAW_POSITIONS:Z,MISSING_DRAW_SIZE:it,MISSING_ENTRIES:bt,MISSING_EVENT:Tt,MISSING_MATCHUP_FORMAT:Vt,MISSING_MATCHUP_ID:qt,MISSING_MATCHUP_IDS:$t,MISSING_MATCHUP:zt,MISSING_MATCHUPS:Ht,MISSING_PARTICIPANT_COUNT:ke,MISSING_PARTICIPANT_ID:Ae,MISSING_PARTICIPANT_IDS:Fe,MISSING_PARTICIPANT_ROLE:Ne,MISSING_PARTICIPANT:Re,MISSING_PARTICIPANTS:Me,MISSING_PENALTY_ID:Ze,MISSING_PENALTY_TYPE:Je,MISSING_PERSON_DETAILS:_e,MISSING_POLICY_ATTRIBUTES:Xt,MISSING_POLICY_DEFINITION:Jt,MISSING_POLICY_TYPE:Kt,MISSING_POSITION_ASSIGNMENTS:Ct,MISSING_ROUND_NUMBER:{message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},MISSING_SCHEDULE:gn,MISSING_SCORING_POLICY:{message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},MISSING_SEED_ASSIGNMENTS:lt,MISSING_SEEDCOUNT_THRESHOLDS:ut,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:re,MISSING_SIDE_NUMBER:{message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},MISSING_STAGE:Mt,MISSING_STRUCTURE_ID:It,MISSING_STRUCTURE:yt,MISSING_STRUCTURES:St,MISSING_TARGET_LINK:ht,MISSING_TIE_FORMAT:Gt,MISSING_TIME_ITEM:mn,MISSING_TIME_ITEMS:fn,MISSING_TOURNAMENT_ID:B,MISSING_TOURNAMENT_RECORD:_,MISSING_TOURNAMENT_RECORDS:x,MISSING_VALUE:ae,MISSING_VENUE_ID:an,MODIFICATIONS_FAILED:Un,NO_CANDIDATES:vn,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:Ye,NO_MODIFICATIONS_APPLIED:Sn,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:ze,NO_PARTICIPANT_REMOVED:Oe,NO_VALID_ACTIONS:An,NO_VALID_ATTRIBUTES:En,NO_VALID_DATES:se,NOT_FOUND:On,NOT_IMPLEMENTED:Fn,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:Ve,PARTICIPANT_ID_EXISTS:Ce,PARTICIPANT_NOT_CHECKED_IN:xe,PARTICIPANT_NOT_FOUND:Ee,PARTICIPANT_PAIR_EXISTS:{message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},PENALTY_NOT_FOUND:Xe,POLICY_NOT_ATTACHED:{message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},POLICY_NOT_FOUND:ee,SCHEDULE_NOT_CLEARED:Y,SCHEDULED_MATCHUPS:Gn,SCORES_PRESENT:qn,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:ct,STAGE_SEQUENCE_LIMIT:Et,STRUCTURE_NOT_FOUND:Ut,TEAM_NOT_FOUND:Mn,UNABLE_TO_ASSIGN_COURT:yn,UNLINKED_STRUCTURES:vt,UNRECOGNIZED_DRAW_TYPE:J,UNRECOGNIZED_MATCHUP_FORMAT:kt,UNRECOGNIZED_MATCHUP_STATUS:Ft,VALUE_UNCHANGED:Cn,VENUE_EXISTS:nn},Wn={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]};var Hn={addNotice:function({topic:t,payload:e,key:n}){if("string"!=typeof t||"object"!=typeof e)return;Wn.disableNotifications||(Wn.modified=!0);if(Wn.disableNotifications||!Wn.subscriptions[t])return;n&&(Wn.notices=Wn.notices.filter((e=>!(e.topic===t&&e.key===n))));return Wn.notices.push({topic:t,payload:e,key:n}),{...E}},callListener:function({topic:t,notices:e}){const n=Wn.subscriptions[t];n&&"function"==typeof n&&n(e)},cycleMutationStatus:function(){const t=Wn.modified;return Wn.modified=!1,t},deleteNotice:function({topic:t,key:e}){Wn.notices=Wn.notices.filter((n=>(!t||n.topic===t)&&n.key!==e))},deleteNotices:function(){Wn.notices=[]},disableNotifications:function(){Wn.disableNotifications=!0},enableNotifications:function(){Wn.disableNotifications=!1},getMethods:Yn,getNotices:function({topic:t}){const e=Wn.notices.filter((e=>e.topic===t)).map((t=>t.payload));return e.length&&e},getTopics:function(){return{topics:Object.keys(Wn.subscriptions)}},getTournamentId:zn,getTournamentRecord:function(t){return Wn.tournamentRecords[t]},getTournamentRecords:function(){return Wn.tournamentRecords},removeTournamentRecord:function(t){if("string"!=typeof t)return{error:Nn};if(!Wn.tournamentRecords[t])return{error:On};delete Wn.tournamentRecords[t];const e=Object.keys(Wn.tournamentRecords);1===e.length?Wn.tournamentId=e[0]:e.length||(Wn.tournamentId=void 0);return{success:!0}},setMethods:function(t){return Object.keys(t).forEach((e=>{"function"==typeof t[e]&&(Wn.methods[e]=t[e])})),{...E}},setSubscriptions:function(t){return"object"!=typeof t.subscriptions?{error:Nn}:(Object.keys(t.subscriptions).forEach((e=>{Wn.subscriptions[e]=t.subscriptions[e]})),{...E})},setTournamentId:function(t){if(!t)return Wn.tournamentId=void 0,{success:!0};return Wn.tournamentRecords[t]?(Wn.tournamentId=t,{success:!0}):{error:_}},setTournamentRecord:function(t){const e=t?.tournamentId;return e?(Wn.tournamentRecords[e]=t,{success:!0}):{error:L}},setTournamentRecords:function(t){Wn.tournamentRecords=t;const e=Object.keys(t);1===e.length?Wn.tournamentId=e[0]:e.length||(Wn.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:zn(),params:JSON.stringify(n),engine:t,methodName:e,error:i}),{error:i}}};function zn(){return Wn.tournamentId}function Yn(){return Wn.methods??{}}const Kn={tournamentFactoryVersion:"0.0.0",timers:{default:{elapsedTime:0}},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},deepCopy:!0};let Jn=Hn;const Zn=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function Xn(t){if("object"!=typeof t)throw new Error("Global state provider can not be undefined or null");if(P(Object.keys(t),Zn).length!==Zn.length)throw new Error("Global state provider is missing required methods");return Jn=t,{success:!0}}function Qn(t){return t&&"object"==typeof t?"object"==typeof Kn.devContext&&(Object.keys(t).every((e=>Kn.devContext?.[e]===t[e]))&&Kn.devContext):Kn.devContext??!1}function tr(t){"function"==typeof t?Kn.globalLog=t:delete Kn.globalLog}function er(t){Kn.devContext=t}function nr(){Jn.enableNotifications()}function rr(t,e){"boolean"==typeof t&&(Kn.deepCopy=t),"object"==typeof e&&(Array.isArray(e.ignore)&&(Kn.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(Kn.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(Kn.deepCopyAttributes.stringify=e.stringify),e.threshold&&(Kn.deepCopyAttributes.threshold=e.threshold))}function ir(){return{enabled:Kn.deepCopy,...Kn.deepCopyAttributes}}function ar(t){return t?.subscriptions?Jn.setSubscriptions({subscriptions:t.subscriptions}):{error:ae,info:"missing subscriptions"}}function or(){return Jn.cycleMutationStatus()}function sr(t){return Jn.addNotice(t)}function cr(){return Jn.getMethods()}function ur(t){return Jn.getNotices(t)}function dr({key:t,topic:e}){return Jn.deleteNotice({key:t,topic:e})}function pr(){return Jn.deleteNotices()}function lr(){return Jn.getTopics()}async function mr(t){return Jn.callListener(t)}function fr(){return Jn.getTournamentId()}function hr(t){return Jn.getTournamentRecord(t)}function gr(){return Jn.getTournamentRecords()}function Ir(t){return Jn.setTournamentRecords(t)}function Ur(t){return Jn.setTournamentId(t)}function Sr(){return Jn}function yr({engineName:t,methodName:e,params:n,err:r}){return("function"==typeof Jn.handleCaughtError&&Jn.handleCaughtError||Hn.handleCaughtError)({engineName:t,methodName:e,params:n,err:r})}function vr(t,e,n,r){if("object"!=typeof t||null===t)return t;const i=ir();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=>vr(t)))}:{[e]:r?t[e]:vr(t[e])})))}function wr({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,vr(t)),!e||e?.error||e?.success||Object.assign(e,{...E}),e??{success:!0}}const Tr="element required",Pr="missing name";function Dr(t){if(!t||"object"!=typeof t)return{error:ae};if(t.element&&"object"!=typeof t?.element)return{error:Nn};if(!t?.name)return{error:ae,info:Pr};if(!t?.element){if(t.discover&&t.tournamentRecords){for(const e of Object.keys(t.tournamentRecords)){const n=Dr({element:t.tournamentRecords[e],name:t.name});if(n.error)return wr({result:n,stack:"removeExtension"})}return{...E}}return{error:ae,info:Tr}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter((e=>e?.name!==t.name)),{...E}):{...E,info:On}}function br({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 Nr(t){if("object"!=typeof t)return{error:ae};const e="addExtension";if(t?.element&&"object"!=typeof t.element)return wr({result:{error:Nn},stack:e});if(!br({extension:t.extension}))return wr({result:{error:Nn,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=Nr({extension:t.extension,element:n});if(r.error)return wr({result:r,stack:e})}return{...E}}return wr({result:{error:ae},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),{...E}}const Rr="extensionQueries";function Mr({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:On}}return wr({result:{error:ae},stack:Rr})}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:On}}const Ar="DYNAMIC",Er="RANKING",Cr="RATING",Or="SCALE",Fr="SEEDING",kr={RANKING:Er,RATING:Cr,SCALE:Or,SEEDING:Fr};function xr({participant:t}){const e=t.timeItems?.filter((({itemType:t})=>t?.startsWith(Or)&&[Er,Cr,Fr].includes(t.split(".")[1]))),n={ratings:{},rankings:{},seedings:{}};if(e?.length){const t=t=>e.filter((e=>e?.itemType===t)).sort(((t,e)=>new Date(t.createdAt||void 0).getTime()-new Date(e.createdAt||void 0).getTime())).pop(),r=m(e.map((({itemType:t})=>t)));for(const e of r){const r=t(e);if(r){const[,t,e,i,a]=r.itemType.split("."),o=a?`${i}.${a}`:i,s=(t===Fr?"seedings":t===Er&&"rankings")||"ratings";n[s][e]||(n[s][e]=[]),n[s][e].push({scaleValue:r.itemValue,scaleDate:r.itemDate,scaleName:o})}}}return{...E,...n}}function _r(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 Lr=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,Br=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Vr=/^([\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?$/,jr=/^([\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 Gr(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=ri(t.scheduledTime)),!e)return;const n=ni(t.scheduledTime);let r=ri(e);return r&&n&&(r+=`T${n}`),r}function qr(t){if("object"!=typeof t||Array.isArray(t))return!1;return"[object Date]"===Object.prototype.toString.call(t)}function $r(t){const e="string"==typeof t?t?.split(" "):[];return!(t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase()))&&!(t&&!jr.test(oi(t,!0,!0)))}function Wr(t){return Xr(t)||Lr.test(t)}const Hr=t=>{const e=Kr(t)||Xr(t)?new Date(t):new Date,n=e.getUTCMonth()+1,r=n<10?`0${n}`:`${n}`;return`${e.getUTCFullYear()}-${mi(r)}-${mi(e.getUTCDate())}`};function zr(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 Yr(t){const e=t?new Date(t):new Date,n=e.getTimezoneOffset();return new Date(e.getTime()-60*n*1e3)}function Kr(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 Jr(t,e){if(!Wr(t)||!Wr(e))return[];const n=ri(t)+"T00:00",r=ri(e)+"T00:00",i=new Date(n),a=new Date(r);const o=[];let s=0;if(Kr(a)&&Kr(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=>zr(t)))}const Zr=/^([+-]?\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 Xr(t){return"string"==typeof t&&Zr.test(t)}function Qr(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 ti(t){const e=ni(t);if(!e)return 0;const[n,r]=e.split(":").map((t=>parseInt(t)));return 60*n+r}function ei(t){return Qr(t)?t.split(":").slice(0,2).map(mi).join(":"):void 0}function ni(t){return Xr(t)&&t.indexOf("T")>0?ei(t.split("T").reverse()[0]):ei(t)}function ri(t){return Xr(t)||Vr.test(t)?t.split("T")[0]:void 0}function ii(t,e){const n=new Date(t);return n.setDate(n.getDate()+e),ri(n.toISOString())}function ai(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 oi(t,e,n){const r=ri(t),i=ni(t),a=r?i:t;return t?e&&(r&&n&&t||function(t){const e=ai(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(mi).join(":")}(a))||function(t){const e=ai(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 si(t,e){const n=ai(t),r=ai(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 ci(t,e=7){const n=ri(t)+"T00:00",r=new Date(n);return zr(new Date(r.setDate(r.getDate()+e)))}function ui(t,e=void 0){const[n,r]=(t||"00:00").split(":").map(mi),i=Yr(e).setHours(n,r,0,0);return Yr(i)}function di(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 pi(t,e){const n=ni(t);if(!n)return"00:00";const r=isNaN(e)?0:e;return ni(li(ui(n),r).toISOString())}function li(t,e){const n=new Date(t);return new Date(n.getTime()+6e4*e)}function mi(t){return t.toString()[1]?t:"0"+t}function fi(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 hi={addDays:ci,addWeek:function(t){return ci(t)},addMinutesToTimeString:pi,convertTime:oi,getIsoDateString:Gr,getUTCdateString:Hr,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(mi).join(":")}(e.getSeconds()+60*e.getMinutes()+3600*e.getHours(),{displaySeconds:!1})},extractDate:ri,extractTime:ni,formatDate:zr,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())),zr(i,n)},isISODateString:Xr,isDate:Kr,isTimeString:Qr,offsetDate:Yr,offsetTime:function(t){return Yr(t).getTime()},sameDay:fi,timeStringMinutes:ti,timeToDate:ui,timeUTC:function(t){const e=Kr(t)||Xr(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())},validTimeValue:$r,validDateString:Lr,timeValidation:jr,dateValidation:Vr};function gi(t,e,n,r,i=0){if(Sr().makeDeepCopy)return Sr().makeDeepCopy(t,e,n,r);const a=ir(),{stringify:o,toJSON:s,ignore:c,modulate:u}=a||{};if(!a?.enabled&&!n||"object"!=typeof t||"function"==typeof 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)||"function"==typeof c&&!c(t))),l=(t,e)=>{d[t]="function"==typeof e?.toString?e.toString():JSON.stringify(e)};for(const a of p){const c=t[a],p="function"==typeof u?u(c):void 0;if(void 0!==p)d[a]=p;else if(e&&"extensions"===a&&Array.isArray(c)){const t=Ii(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)&&"function"==typeof c?.toJSON?d[a]=c.toJSON():null===c?d[a]=void 0:qr(c)?d[a]=new Date(c).toISOString():d[a]=gi(c,e,n,r,i+1)}return d}function Ii(t){return t?.map((t=>{const{name:e,value:n}=t;return e&&n&&{[`_${e}`]:n}})).filter(Boolean)}const Ui="voluntaryConsolation",Si="competitiveBands",yi="roundRobinTally",vi="positionActions",wi="matchUpActions",Ti="rankingPoints",Pi="roundNaming",Di="participant",bi="progression",Ni="scheduling",Ri="avoidance",Mi="scoring",Ai="seeding",Ei="feedIn",Ci="draws",Oi={POLICY_TYPE_VOLUNTARY_CONSOLATION:Ui,POLICY_TYPE_COMPETITIVE_BANDS:Si,POLICY_TYPE_ROUND_ROBIN_TALLY:yi,POLICY_TYPE_POSITION_ACTIONS:vi,POLICY_TYPE_MATCHUP_ACTIONS:wi,POLICY_TYPE_RANKING_POINTS:Ti,POLICY_TYPE_ROUND_NAMING:Pi,POLICY_TYPE_PARTICIPANT:Di,POLICY_TYPE_PROGRESSION:bi,POLICY_TYPE_SCHEDULING:Ni,POLICY_TYPE_AVOIDANCE:Ri,POLICY_TYPE_DISPLAY:"display",POLICY_TYPE_FEED_IN:Ei,POLICY_TYPE_SCORING:Mi,POLICY_TYPE_SEEDING:Ai,POLICY_TYPE_AUDIT:"audit",POLICY_TYPE_DRAWS:Ci};function Fi({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:n,participantId:r,internalUse:i,personId:a}){const o=gi(t.find((t=>r&&t.participantId===r||a&&t.person&&t.person.personId===a)),!1,i);if(o){const t=e?.[Di];if(n?.withScaleValues){const{ratings:t,rankings:e}=xr({participant:o});o.rankings=e,o.ratings=t}if(t?.participant)return _r({template:t.participant,source:o})}return o}function ki(t){return t&&"object"==typeof t?t.tournamentRecord?Nr({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:_}:{error:ae}}function xi(t){return t&&"object"==typeof t?t.drawDefinition?Nr({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:q}:{error:ae}}function _i(t){return t&&"object"==typeof t?t.event?Nr({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:Pt}:{error:ae}}function Li(t){return t&&"object"==typeof t?t.tournamentRecord?Dr({element:t.tournamentRecord,name:t.name}):{error:_}:{error:ae}}function Bi(t){return t&&"object"==typeof t?t?.event?Dr({element:t.event,name:t.name}):{error:Pt}:{error:ae}}const Vi="appliedPolicies",ji="positionActions",Gi="context",qi="delegatedOutcome",$i="disabled",Wi="disableLinks",Hi="disableAutoCalc",zi="drawDeletions",Yi="entryProfile",Ki="flightProfile",Ji="groupingAttribute",Zi="lineUps",Xi="linkedTournamentsIds",Qi="matchUpHistory",ta="participantRepresentatives",ea="personRequests",na="rankingPoints",ra="roundTarget",ia="scheduleLimits",aa="scheduleTiming",oa="schedulingProfile",sa="subOrder",ca="tally",ua="tieFormatModification",da={ACTIVE_SUSPENSION:"activeSuspension",APPLIED_POLICIES:Vi,AUDIT_POSITION_ACTIONS:ji,CONTEXT:Gi,DELEGATED_OUTCOME:qi,DISABLED:$i,DISABLE_LINKS:Wi,DISABLE_AUTO_CALC:Hi,DRAW_DELETIONS:zi,DRAW_PROFILE:"drawProfile",ENTRY_PROFILE:Yi,EVENT_PROFILE:"eventProfile",EVENT_WITHDRAWAL_REQUESTS:"eventWithdrawalRequests",FLIGHT_PROFILE:Ki,GROUPING_ATTRIBUTE:Ji,LINEUPS:Zi,LINKED_TOURNAMENTS:Xi,MATCHUP_HISTORY:Qi,PARTICIPANT_REPRESENTATIVES:ta,PERSON_REQUESTS:ea,RANKING_POINTS:na,ROUND_TARGET:ra,SCHEDULE_LIMITS:ia,SCHEDULE_TIMING:aa,SCHEDULING_PROFILE:oa,STATUS_DETAIL:"statusDetail",SUB_ORDER:sa,TALLY:ca,TIE_FORMAT_MODIFICATIONS:ua,FACTORY:"factory"},pa=[qi,$i,Wi,Ki,Zi,Qi,ta,ea,ra,ia,aa,oa,sa,ca];function la({element:t,accessor:e}){if("string"!=typeof e)return{values:[]};const n=gi(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}function ma(t){return"function"==typeof t}function fa(t){return"string"==typeof t}function ha(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function ga(t,e){if(!ha(t)||!ha(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 Ia(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(ha).map((t=>t[e]&&{[t[e]]:t})).filter(Boolean)):{}}const Ua=t=>e=>t&&"object"==typeof e?Array.isArray(t)&&t.map((t=>({[t]:la({element:e,accessor:t})?.value})))||"object"==typeof t&&Object.keys(t).map((t=>({[t]:la({element:e,accessor:t})?.value})))||("string"==typeof t&&la({element:e,accessor:t}))?.value:void 0;function Sa(t){return Array.isArray(t)?t.length+t.map(Sa).reduce(((t,e)=>t+e),0):"object"==typeof t&&null!==t?Object.keys(t).length+Object.keys(t).map((e=>Sa(t[e]))).reduce(((t,e)=>t+e),0):0}function ya({tournamentRecords:t}){return{tournamentIds:ha(t)?Object.keys(t):[],...E}}const va={linkTournaments:function({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:x};const e=ya({tournamentRecords:t}),{tournamentIds:n}=e;if(n?.length>1){return Nr({tournamentRecords:t,discover:!0,extension:{name:Xi,value:{tournamentIds:n}}})}return{...E}},unlinkTournament:function({tournamentRecords:t,tournamentId:e}){if("object"!=typeof t)return{error:Nn};if(!e)return{error:B};const n=ya({tournamentRecords:t}),{tournamentIds:r}=n;if(!r.includes(e))return{error:B};let i;return r.every((n=>{const r=t[n],{extension:a}=Mr({element:r,name:Xi});if(!a)return!0;const o=a?.value?.tournamentIds||[];if(!o?.length||1===o.length&&o.includes(e)||n===e){const t=Li({name:Xi,tournamentRecord:r});return t.error&&(i=t.error),t.success}const s=o.filter((t=>t!==e));a.value={tournamentIds:s};const c=ki({tournamentRecord:r,extension:a});return c.error&&(i=c.error),c.success})),i?{error:i}:{...E}},unlinkTournaments:function({tournamentRecords:t}){return"object"==typeof t&&Object.keys(t).length?wr({result:Dr({name:Xi,tournamentRecords:t,discover:!0}),stack:"unlinkTournaments"}):{error:x}}},wa=t=>e=>t[e],Ta=(t=[])=>t.map(ba).filter(Boolean),Pa=(t=[])=>t.map(Da).filter(Boolean),Da=(t={})=>wa(t)("participantId"),ba=(t={})=>wa(t)("matchUpId");const Na="ABANDONED",Ra="AWAITING_RESULT",Ma="BYE",Aa="CANCELLED",Ea="COMPLETED",Ca="DEAD_RUBBER",Oa="DEFAULTED",Fa="DOUBLE_DEFAULT",ka="DOUBLE_WALKOVER",xa="IN_PROGRESS",_a="INCOMPLETE",La="NOT_PLAYED",Ba="RETIRED",Va="SUSPENDED",ja="TO_BE_PLAYED",Ga="WALKOVER",qa=[Ra,Ea,Oa,xa,_a,Ba,Va],$a=[Ra,Ea,Oa,ka,Fa,xa,_a,Ba,Va,Ga],Wa=[Na,Ra,Ma,Aa,Ea,Ca,Oa,ka,Fa,xa,_a,La,Ba,Va,ja,Ga],Ha=[Ma,ka,Fa,Ea,Oa,Ba,Ga],za=[Na,Ra,Aa,Ca,xa,_a,La,Va,ja,void 0],Ya=[Aa,Na,Ea,Ca,Oa,ka,Fa,Ba,Ga],Ka=[Na,Ea,Oa,ka,Fa,xa,Ba,Ga],Ja=[xa,_a,Va,ja],Za={ABANDONED:Na,AWAITING_RESULT:Ra,BYE:Ma,CANCELLED:Aa,COMPLETED:Ea,DEAD_RUBBER:Ca,DEFAULTED:Oa,DOUBLE_WALKOVER:ka,DOUBLE_DEFAULT:Fa,IN_PROGRESS:xa,INCOMPLETE:_a,NOT_PLAYED:La,RETIRED:Ba,SUSPENDED:Va,TO_BE_PLAYED:ja,WALKOVER:Ga},Xa="MAIN",Qa="QUALIFYING",to="CONSOLATION",eo="VOLUNTARY_CONSOLATION",no="PLAY_OFF",ro=[Xa,Qa,to,no,eo],io={[Qa]:1,[Xa]:2,[no]:3,[to]:3,[eo]:4},ao="finishingPositions",oo="aggregateEventStructures",so={[Xa]:1,[no]:2,[to]:3,[Qa]:4,[eo]:5},co={[no]:1,[Xa]:2,[to]:3,[Qa]:4,[eo]:5},uo="CLUSTER",po="WATERFALL",lo="ITEM",mo="CONTAINER",fo="DRAW",ho="RANDOM",go="TOP_DOWN",Io="BOTTOM_UP",Uo="POSITION",So="WINNER",yo="LOSER",vo="FIRST_MATCHUP",wo="AD_HOC",To="FEED_IN",Po="COMPASS",Do="OLYMPIC",bo="SINGLE_ELIMINATION",No="DOUBLE_ELIMINATION",Ro="FIRST_MATCH_LOSER_CONSOLATION",Mo="FIRST_ROUND_LOSER_CONSOLATION",Ao="LUCKY_DRAW",Eo="CURTIS_CONSOLATION",Co="CURTIS_CONSOLATION",Oo="FEED_IN_CHAMPIONSHIP_TO_SF",Fo="FEED_IN_CHAMPIONSHIP_TO_SF",ko="FEED_IN_CHAMPIONSHIP_TO_QF",xo="FEED_IN_CHAMPIONSHIP_TO_QF",_o="FEED_IN_CHAMPIONSHIP_TO_R16",Lo="FEED_IN_CHAMPIONSHIP_TO_R16",Bo="MODIFIED_FEED_IN_CHAMPIONSHIP",Vo="MODIFIED_FEED_IN_CHAMPIONSHIP",jo="FEED_IN_CHAMPIONSHIP",Go="ROUND_ROBIN",qo="ROUND_ROBIN_WITH_PLAYOFF",$o="DECIDER",Wo="BACKDRAW",Ho={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"}},zo={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},Yo="WIN_RATIO",Ko="ROUND_OUTCOME",Jo=[Po,Eo,xo,Lo,Fo,jo,ko,_o,Oo,Ro,Mo,Ao,Vo,Do,no,qo],Zo={MAIN:Xa,QUALIFYING:Qa,CONSOLATION:to,ITEM:lo,CONTAINER:mo,FIRST_MATCHUP:vo,WINNER:So,LOSER:yo,AD_HOC:wo,FEED_IN:To,FLEX_ROUNDS:"AD_HOC",COMPASS:Po,PLAY_OFF:no,OLYMPIC:Do,KNOCKOUT:"SINGLE_ELIMINATION",SINGLE_ELIMINATION:bo,DOUBLE_ELIMINATION:No,CURTIS:Eo,FICSF:Oo,FICQF:ko,FICR16:_o,MFIC:Bo,VOLUNTARY_CONSOLATION:eo,FIRST_MATCH_LOSER_CONSOLATION:Ro,FIRST_ROUND_LOSER_CONSOLATION:Mo,MODIFIED_FEED_IN_CHAMPIONSHIP:Vo,FEED_IN_CHAMPIONSHIP_TO_R16:Lo,FEED_IN_CHAMPIONSHIP_TO_QF:xo,FEED_IN_CHAMPIONSHIP_TO_SF:Fo,FEED_IN_CHAMPIONSHIP:jo,LUCKY_DRAW:Ao,ROUND_ROBIN_WITH_PLAYOFF:qo,ROUND_ROBIN:Go,DECIDER:$o,BACKDRAW:Wo,COMPASS_ATTRIBUTES:Ho,OLYMPIC_ATTRIBUTES:zo,DRAW:fo,RANDOM:ho,TOP_DOWN:go,BOTTOM_UP:Io,WATERFALL:po,WIN_RATIO:Yo,ROUND_OUTCOME:Ko,MULTI_STRUCTURE_DRAWS:Jo,generatedDrawTypes:[wo,Po,Eo,No,xo,Lo,Fo,jo,To,Ro,Mo,Ao,Vo,Do,no,Go,qo,bo],stageOrder:io,finishOrder:so,AGGREGATE_EVENT_STRUCTURES:oo,FINISHING_POSITIONS:ao};function Xo(t,e,n){const r=t=>Mr({element:t,name:ra})?.extension?.value,i=n?.deprioritizeCompleted,a=n?.mode===oo&&co,o=n?.mode===ao&&so,s=o||a||io,c=t=>(t=>t?.stage===Xa&&1===t?.stageSequence)(t)?-1:s[t?.stage],u=t=>t?.matchUps.every((({matchUpStatus:t})=>Ya.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)||(Qo(t)||0)-(Qo(e)||0)}function Qo(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 ts({drawDefinition:t,structureId:e}){if(!t)return{error:j};if(!e)return{error:It};const{structures:n}=es({drawDefinition:t}),r=n?.map((t=>t.structures?[...t.structures].concat(t):t)).flat(),i=r?.find((t=>t.structureId===e));if(!i)return{error:Ut};return{structure:i,containingStructure:i.structureType===lo?r?.find((t=>t.structures?.some((t=>t.structureId===e)))):void 0}}function es({withStageGrouping:t,drawDefinition:e,stageSequences:n,stageSequence:r,roundTarget:i,sortConfig:a,stages:o,stage:s}){const c=!e&&j||!e?.structures&&St||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=Mr({element:t,name:ra})?.extension?.value;return!i||i===e})).sort(((t,e)=>Xo(t,e,a)))??[],d=t?Object.assign({},...ro.map((t=>{const e=u?.filter((e=>e.stage===t));return e?.length&&{[t]:e}})).filter(Boolean)):{};return{structures:u,stageStructures:d}}function ns({drawDefinition:t}){if(!t)return{error:j};const e={};return{allPositionedParticipantIds:(t.structures||[]).map((t=>{const n=t.stage;e[n]||(e[n]=[]);const{positionAssignments:r}=rs({structure:t}),i=r?.map(Ua("participantId")).filter(Boolean)??[];return e[n].push(...i),i})).flat(),stagePositionedParticipantIds:e}}function rs({drawDefinition:t,structureId:e,structure:n}){let r,i=[];if(!n){if(!t)return{positionAssignments:i,error:j};if(({structure:n,error:r}=ts({drawDefinition:t,structureId:e})),r)return{positionAssignments:i,error:r}}return n.structures?i=[].concat(...n.structures.map((t=>rs({structure:t}).positionAssignments))):n.positionAssignments?i=n.positionAssignments:r=Ct,{positionAssignments:i,error:r}}function is({drawDefinition:t,structureId:e,structure:n}){const r=rs({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 as="addDrawDefinition",os="addMatchUps",ss="addParticipants",cs="addScaleItems",us="addVenue",ds="audit",ps="deleteParticipants",ls="deleteVenue",ms="deletedDrawIds",fs="deletedMatchUpIds",hs="modifyDrawDefinition",gs="modifyDrawEntries",Is="modifyEventEntries",Us="modifyMatchUp",Ss="modifyParticipants",ys="modifyPositionAssignments",vs="modifySeedAssignments",ws="modifyTournamentDetail",Ts="modifyVenue",Ps="mutations",Ds="publishEvent",bs="publishEventSeeding",Ns="publishOrderOfPlay",Rs="unPublishEvent",Ms="unPublishEventSeeding",As="unPublishOrderOfPlay",Es="updateInContextMatchUp",Cs={ADD_DRAW_DEFINITION:as,ADD_MATCHUPS:os,ADD_PARTICIPANTS:ss,ADD_SCALE_ITEMS:cs,ADD_VENUE:us,AUDIT:ds,DELETE_PARTICIPANTS:ps,DELETE_VENUE:ls,DELETED_DRAW_IDS:ms,DELETED_MATCHUP_IDS:fs,MODIFY_DRAW_DEFINITION:hs,MODIFY_DRAW_ENTRIES:gs,MODIFY_EVENT_ENTRIES:Is,MODIFY_MATCHUP:Us,MODIFY_PARTICIPANTS:Ss,MODIFY_POSITION_ASSIGNMENTS:ys,MODIFY_SEED_ASSIGNMENTS:vs,MODIFY_TOURNAMENT_DETAIL:ws,MODIFY_VENUE:Ts,MUTATIONS:Ps,PUBLISH_EVENT_SEEDING:bs,PUBLISH_EVENT:Ds,PUBLISH_ORDER_OF_PLAY:Ns,UNPUBLISH_EVENT_SEEDING:Ms,UNPUBLISH_EVENT:Rs,UNPUBLISH_ORDER_OF_PLAY:As,UPDATE_INCONTEXT_MATCHUP:Es};function Os(t,e){if(!t)return{error:j};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)})),{...E}}function Fs({drawDefinition:t,tournamentId:e,matchUps:n,eventId:r}){return t&&Os(t),sr({payload:{matchUps:n,tournamentId:e,eventId:r},topic:os}),{...E}}function ks({drawDefinition:t,tournamentId:e,matchUpIds:n,eventId:r,action:i}){t&&Os(t),sr({topic:fs,payload:{tournamentId:e,matchUpIds:n,eventId:r,action:i}});for(const t of n)dr({key:t});return{...E}}function xs({drawDefinition:t,tournamentId:e,structureId:n,context:r,eventId:i,matchUp:a}){if(!a)return console.log(zt),{error:zt};if(t){Ls({drawDefinition:t,structureIds:n?[n]:void 0,tournamentId:e,eventId:i})}return sr({topic:Us,payload:{matchUp:a,tournamentId:e,context:r},key:a.matchUpId}),{...E}}function _s({tournamentId:t,eventId:e,drawDefinition:n}){return n?(Os(n),sr({payload:{drawDefinition:n,tournamentId:t,eventId:e},topic:as,key:n.drawId}),{...E}):(console.log(j),{error:j})}function Ls({drawDefinition:t,tournamentId:e,structureIds:n,eventId:r}){return t?(Os(t,n),sr({payload:{tournamentId:e,eventId:r,drawDefinition:t},topic:hs,key:t.drawId}),{...E}):{error:j}}function Bs({drawDefinition:t,tournamentId:e,structure:n,eventId:r}){if(!t)return{error:j};if(!n)return{error:yt};const i=n.seedAssignments,a=n.structureId;return sr({payload:{tournamentId:e,eventId:r,drawId:t.drawId,structureId:a,seedAssignments:i},topic:vs,key:t.drawId}),Ls({structureIds:[a],drawDefinition:t,tournamentId:e,eventId:r}),{...E}}function Vs({drawDefinition:t,tournamentId:e,structure:n,event:r}){if(!t)return{error:j};if(!n)return{error:yt};const i=rs({structure:n}),a=n.structureId,o=t.drawId,s=r?.eventId;return sr({topic:ys,payload:{positionAssignments:i,tournamentId:e,structureId:a,eventId:s,drawId:o},key:a}),Ls({structureIds:[a],drawDefinition:t,tournamentId:e,eventId:s}),{...E}}function js({drawPositions:t,structure:e}){if([Qa,Xa].includes(e.stage)&&1===e.stageSequence)return;const{positionAssignments:n}=rs({structure:e}),r=n?.filter((({drawPosition:e})=>t?.includes(e)));r?.forEach((t=>{Nr({element:t,extension:{name:Wi,value:!0}})}))}function Gs({drawDefinition:t,positionAction:e}){const{extension:n}=Mr({name:ji,element:t}),r=Array.isArray(n?.value)?n?.value??[]:[];if(!r?.length){const e=t.structures.find((t=>t.stage===Xa));if(e){const t=rs({structure:e}).positionAssignments?.map((({drawPosition:t,participantId:e,bye:n,qualifier:r})=>({drawPosition:t,participantId:e,qualifier:r,bye:n})));r.push({name:"initialMainAssignments",initialAssignments:t})}}Nr({element:t,extension:{name:ji,value:r.concat(e)}})}function qs({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 $s(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 Ws({matchUpStatus:t}){return Ha.includes(t)}function Hs({matchUpStatus:t}){return za.includes(t)}function zs({matchUpStatus:t,winningSide:e,tieMatchUps:n,sides:r,score:i}){const a=r?.find((({participantId:t})=>t)),o=n?.filter(zs)?.length;return $s({score:i})||o||e&&a||t&&function({matchUpStatus:t}){return Ka.includes(t)}({matchUpStatus:t})&&![Oa,Ga,xa].includes(t)}const Ys="SINGLES",Ks="SINGLES",Js="DOUBLES",Zs="DOUBLES",Xs="TEAM",Qs="TEAM",tc={SINGLES_MATCHUP:Ys,SINGLES:Ks,DOUBLES_MATCHUP:Js,DOUBLES:Zs,TEAM_MATCHUP:Xs,TEAM:Qs};function ec(t){const{sides:e,matchUpType:n}=t||{},r=t.potentialParticipants?.length?t.potentialParticipants.flat().map((t=>n===Zs?t?.individualParticipantIds||[]:t.participantId)).flat():[],i=(e||[]).map((t=>n===Zs&&(t?.participant?.individualParticipantIds||[])||t?.participantId&&[t.participantId]||[])).flat();return{individualParticipantIds:i.concat(r).flat(),enteredIndividualParticipantIds:i,potentialIndividualParticipantIds:r}}function nc(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}const rc="SIGN_IN_STATUS",ic="SIGNED_OUT",ac="SIGNED_IN",oc="TEAM",sc="INDIVIDUAL",cc="GROUP",uc="PAIR",dc="TEAM",pc={TEAM_PARTICIPANT:oc,INDIVIDUAL:sc,GROUP:cc,TEAM:dc,PAIR:uc},lc={INDIVIDUAL:sc,GROUP:cc,PAIR:uc,TEAM:dc,SIGN_IN_STATUS:rc,SIGNED_OUT:ic,SIGNED_IN:ac};function mc({participantsProfile:t,participants:e=[],deepCopy:n}){const r=new Map,i=!1!==n?gi(e,t?.convertExtensions,!0):e,a=i.filter((t=>t.participantType===dc)),o=i.filter((t=>t.participantType===cc)),s=i.filter((t=>t.participantType===uc));return i.forEach((t=>{if(t.participantType===sc){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 fc({groupedOrder:t,roundPositionsCount:n}){if(!t||t?.length<=n)return t;const r=N(t,t.length/n).map((t=>t.reduce(((t,e)=>t+e)))),i=r.slice().sort(e);return r.map((t=>i.indexOf(t)+1))}function hc({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:n,drawDefinition:r,targetLink:i}){if(!i)return{error:ht};const{target:{structureId:a,feedProfile:o,groupedOrder:s,roundNumber:c,positionInterleave:u}}=i,{structure:d}=ts({drawDefinition:r,structureId:a}),{positionAssignments:p}=rs({structure:d}),l=e?.filter((t=>t.structureId===d?.structureId)),m=l.filter((t=>t.roundNumber===c&&!t.matchUpTieId)),f=m.length,h=w(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 S=h,y=h[I-1];const v=fc({groupedOrder:s,roundPositionsCount:h.length}),T=v?.length||1;if(T<=h.length){const t=N(h,f/T);o===Io&&t.forEach((t=>t.reverse())),S=v?.length&&v?.map((e=>t[e-1])).flat()||S}o===go?y=S[I-1]:o===Io?((!v?.length||T>h.length)&&(I=m.length+1-I),y=S[I-1]):o===ho&&Qn()&&console.log(Fn,{feedProfile:o});const P=y&&m.reduce(((t,e)=>e.roundPosition===y?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 b=p?.find((({drawPosition:t})=>t===D));if(b){const{extension:t}=Mr({element:b,name:Wi});if(t?.value)return{disabledDrawPosition:D}}return{matchUp:P,targetDrawPosition:D,matchUpDrawPositionIndex:U}}function gc({finishingPositions:t,linkCondition:e,linkType:n,source:r}){const i=r.find((r=>{const i=!r.source?.finishingPositions||!t||b(t,r.source?.finishingPositions);return e===r.linkCondition&&i&&r.linkType===n}));return[So,yo].includes(i?.linkType)&&!i?.source?.roundNumber?wr({result:{error:Nn},stack:"getTargetLink",context:i}):i}function Ic({drawDefinition:t,structureId:e,roundNumber:n}){if(!t)return{error:j};if(!e)return{error:It};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 Uc({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}=ts({structureId:a?.structureId,drawDefinition:r}),s=o?.finishingPosition;return s===Ko?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:j};if(!n)return{error:It};const{links:r}=Ic({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=gc({source:c,linkType:So}),d=gc({linkCondition:vo,linkType:yo,source:c});let p=gc({source:c,linkType:yo});const l=d&&p;p||(p=d);const m=u?.target?.feedProfile,f=p?.target?.feedProfile,h=d?.target?.feedProfile;let g,I,U,S,y,v,w,T,P,D;if(e&&(a||o)&&(w=a&&m!==fo&&t.find((({matchUpId:t})=>t===a)),S=o&&f!==fo&&t.find((({matchUpId:t})=>t===o)),w||S))return{matchUp:i,targetLinks:{loserTargetLink:p,winnerTargetLink:u},targetMatchUps:{loserMatchUp:S,winnerMatchUp:w}};const{roundPosition:b}=i;D=D||t.filter((t=>t.structureId===r.structureId));const N=D.reduce(((t,e)=>e.roundNumber!==i.roundNumber||e.matchUpTieId?t:t+1),0);p&&!S&&f!==fo&&({matchUpDrawPositionIndex:v,targetDrawPosition:y,matchUp:S}=hc({targetLink:p,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:b,drawDefinition:n}));l&&h!==fo&&({matchUpDrawPositionIndex:U,targetDrawPosition:I,matchUp:g}=hc({targetLink:d,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:b,drawDefinition:n}));u&&!w&&m!==fo&&({matchUpDrawPositionIndex:P,targetDrawPosition:T,matchUp:w}=hc({targetLink:u,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:b,drawDefinition:n}));w||(D=D||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:D,matchUp:i})));return vr({matchUp:i,targetLinks:{loserTargetLink:p,winnerTargetLink:u,byeTargetLink:d},targetMatchUps:{winnerMatchUpDrawPositionIndex:P,loserMatchUpDrawPositionIndex:v,byeMatchUpDrawPositionIndex:U,winnerTargetDrawPosition:T,loserTargetDrawPosition:y,byeTargetDrawPosition:I,winnerMatchUp:w,loserMatchUp:S,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 Sc(t){if(!ha(t))return!1;const{matchUpId:e,drawPositions:n}=t,r="string"==typeof e,i=!n||Array.isArray(n)&&n.length<=2&&n.every((t=>p(t)||null==t));return r&&i}function yc(t){return!!Array.isArray(t)&&t.every(Sc)}function vc({matchUps:t=[],interpolate:i}){if(!yc(t))return{roundMatchUps:[],error:Nn};const a=t.reduce(((t,e)=>{const r="string"==typeof e.roundNumber?n(e.roundNumber):e.roundNumber;return!e.roundNumber||t.includes(r)?t:t.concat(r)}),[]).sort(e).map((n=>{const r=t.filter((t=>t.roundNumber===n)),i=r.find((({matchUpType:t})=>t===Qs))?r.filter((({matchUpType:t})=>t===Qs)):r;return{[n]:(a=i,a.sort(((t,n)=>e(t.roundPosition,n.roundPosition))))};var a})),o=t.reduce(((t,e)=>{const r="string"==typeof e.roundNumber?n(e.roundNumber):e.roundNumber;return t[r]||(t[r]=vr({abbreviatedRoundName:e.abbreviatedRoundName,finishingRound:e.finishingRound,roundName:e.roundName})),t}),{}),s=Object.assign({},...a);if(i){const t=Math.max(...Object.keys(s).map((t=>n(t))).filter((t=>!isNaN(t)))),e=s[t]?.length;if(e>1&&r(e)){const n=t+1;w(n,n+e/2).forEach(((t,n)=>{s[t]=w(0,e/(2+2*n)).map((()=>({})))}))}}let c=0;const u=Object.assign({},...Object.keys(s).map((t=>{const e=s[t]?.length,n=s[t]?.filter((t=>!Ya.includes(t.matchUpStatus)&&!t.score?.scoreStringSide1))?.length,r=e&&e===n;return c=Math.max(c,e),{[t]:{matchUpsCount:e,inactiveCount:n,inactiveRound:r}}})));let d=0,p=0;const l=Object.keys(s).map((t=>n(t))).filter((t=>!isNaN(t)));l.forEach((t=>{const n=s[t].sort(((t,e)=>t.roundPosition-e.roundPosition)),r=n.map((t=>t?.drawPositions||[])).flat();if(u[t].roundNumber=t,u[t].roundFactor=u[t].matchUpsCount?c/u[t].matchUpsCount:1,u[t].finishingRound=o[t]?.finishingRound,u[t].roundName=o[t]?.roundName,u[t].abbreviatedRoundName=o[t]?.abbreviatedRoundName,u[t].finishingPositionRange=s[t]?.[0]?.finishingPositionRange,1!==t&&u[t-1]){const r=u[t-1],i=r.drawPositions,a=r.matchUpsCount/u[t].matchUpsCount,o=N(i,a),s=n.map((n=>{const{roundPosition:r}=n,a=[...n.drawPositions||[],void 0,void 0].slice(0,2);if(!r)return a;const s=a?.filter(Boolean)||[];if(!s?.length)return[void 0,void 0];if(t<3&&2===s?.length)return a?.slice().sort(e);const c=P(i,s).length!==s?.length;if(s?.length&&c)return 1===s?.length?[s[0],void 0]:a?.slice().sort(e);const u=2*(r-1);return o.slice(u,u+2).map((t=>s?.find((e=>t.includes(e)))))}));u[t].drawPositions=s?.flat(),u[t].pairedDrawPositions=s}else{const n=r.sort(e),i=N(n,2);u[t].drawPositions=n,u[t].pairedDrawPositions=i}u[t+1]&&u[t+1].matchUpsCount===u[t].matchUpsCount&&(u[t+1].feedRound=!0,u[t+1].feedRoundIndex=p,u[t].preFeedRound=!0,p+=1),u[t]&&!u[t].feedRound&&(u[t].roundIndex=d,d+=1)}));const m=!!Object.values(u).find((({matchUpsCount:t})=>!r(t)));return{hasNoRoundPositions:t.some((t=>!t.roundPosition)),roundsNotPowerOf2:m,maxMatchUpsCount:c,roundMatchUps:s,roundNumbers:l,roundProfile:u,...E}}function wc({drawDefinition:t,inContextDrawMatchUps:r}){const i={};return r.forEach((a=>{const{matchUpId:o,structureId:s,drawPositions:c=[]}=a,{structure:u}=ts({drawDefinition:t,structureId:s});if(u?.finishingPosition===Yo){const{roundNumber:t}=a,r=t&&n(t)+1,i=u.matchUps??[],{roundMatchUps:o}=vc({matchUps:i});if(r&&o?.[r]){const t=[...c].sort(e).map(((t,e)=>{const n=o[r].find((e=>e.drawPositions?.includes(t)));return{matchUpId:n?.matchUpId,roundNumber:r,schedule:n?.schedule,sideNumber:e+1,structureName:u.structureName}}));Object.assign(a,{sidesTo:t})}}else{const e=Uc({useTargetMatchUpIds:!0,inContextDrawMatchUps:r,inContextMatchUp:a,drawDefinition:t,matchUpId:o});let{winnerMatchUp:n}=e.targetMatchUps;const{loserMatchUp:s}=e.targetMatchUps;!a.winnerMatchUpId&&n&&(a.winnerMatchUpId=n.matchUpId),!a.loserMatchUpId&&s&&(a.loserMatchUpId=s.matchUpId);const c=Pc({upcomingMatchUp:n});let u=Pc({upcomingMatchUp:s});if(a.matchUpStatus!==Ma&&s?.matchUpStatus===Ma){const{matchUp:e}=Tc({matchUp:s,drawDefinition:t,inContextDrawMatchUps:r})||{};u=e&&Pc({upcomingMatchUp:e})||u}const p=a.schedule?.timeAfterRecovery;if(p){if(c?.schedule?.scheduledTime){ti(c.schedule.scheduledTime)<ti(p)&&(i[c.matchUpId]=a.matchUpId,c.schedule.scheduleConflict=a.matchUpId)}if(u?.schedule?.scheduledTime){ti(u.schedule.scheduledTime)<ti(p)&&(i[u.matchUpId]=a.matchUpId,u.schedule.scheduleConflict=a.matchUpId)}}if(Object.assign(a,{winnerTo:c,loserTo:u}),a.drawPositions?.filter(Boolean).length){const t=e.targetLinks?.loserTargetLink,i=t?.linkCondition===vo,o=(d=a,d?.sides?.map((({participant:t,participantId:e,qualifier:n})=>t||e&&{participantId:e}||n&&{qualifier:n})).filter(Boolean)||[]);if(o.length){const t=Pa(n?.sides),a=Pa(s?.sides),c=o.find((({participantId:e})=>t.includes(e)))?[]:o,u=o.find((({participantId:t})=>a.includes(t)))?[]:o;s&&i&&u.length<2&&u.push({bye:!0,tbd:!0}),c?.length&&n&&(!e.targetMatchUpIds&&n&&(n=r.find((({matchUpId:t})=>t===n.matchUpId))),n.potentialParticipants||(n.potentialParticipants=[]),n.potentialParticipants.push(c)),u?.length&&s&&(e.targetMatchUpIds||(n=r.find((({matchUpId:t})=>t===s.matchUpId))),s.potentialParticipants||(s.potentialParticipants=[]),s.potentialParticipants.push(u))}}}var d})),Object.keys(i).length&&r.forEach((t=>{Object.keys(i).includes(t.matchUpId)&&(t.schedule.scheduleConflict=i[t.matchUpId])})),{scheduleConflictMatchUpIds:i}}function Tc({matchUp:t,drawDefinition:e,inContextDrawMatchUps:n}){const{matchUpId:r,matchUpStatus:i,structureId:a}=t||{};if(!t||!a||t?.matchUpStatus===ja)return{matchUp:t};if(i===Ma){let i;if(t.winnerMatchUpId)i=n.find((({matchUpId:e})=>e===t.winnerMatchUpId));else{const t=Uc({inContextDrawMatchUps:n,drawDefinition:e,matchUpId:r});({winnerMatchUp:i}=t?.targetMatchUps||{})}return Tc({matchUp:i,drawDefinition:e,inContextDrawMatchUps:n})}return{matchUp:void 0}}function Pc(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 Dc({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:n,drawDefinition:r,structure:i,event:a}){if(!Array.isArray(e))return{error:Kt};const o={};return n&&s(n),a&&s(a),r&&s(r),i&&s(i),{appliedPolicies:o,...E};function s(n){const r=n?.extensions,i=r?.find((t=>t.name===Vi))?.value;if(i)for(const n of Object.keys(i))(t?e.includes(n):!e.length||e.includes(n))&&(o[n]=gi(i[n],!1,!0))}}function bc({policyTypes:t=[],tournamentRecord:e,drawDefinition:n,structure:r,event:i}){if(!Array.isArray(t))return{error:Kt};const{appliedPolicies:a}=Dc({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:ee.message}}const Nc="WALKOVER",Rc="RETIRED",Mc="COMPETITIVE",Ac="ROUTINE",Ec="DECISIVE",Cc="winRatio",Oc={[Si]:{policyName:"Competitive Bands Default",profileBands:{[Ec]:20,[Ac]:50}}};function Fc({policyDefinitions:t,tournamentRecord:e,contextProfile:n,drawDefinition:r,event:i}){const a={policies:{}};if(!n)return a;const o=bc({tournamentRecord:e,drawDefinition:r,event:i}).policyDefinitions;if(n.withCompetitiveness){const e=t?.[Si]??o?.[Si]??Oc[Si];a.policies[Si]=e}return a}function kc({drawDefinition:t}){if("object"!=typeof t)return{error:V};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&&[to,no].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 xc({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 _c({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(gi(t,!0,!0),{containerStructureId:n,structureId:e,structureName:a}))):i})).flat();return(i?.matchUps||[]).concat(...a)}function Lc({matchUp:t}){return!!t&&(Ya.includes(t?.matchUpStatus)||t?.winningSide)}function Bc({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 Vc({tournamentParticipants:t,tournamentRecord:e,participantIds:n}){const r="getPairedParticipant";if(!t&&!e)return{error:_};if(!Array.isArray(n)||n.length>2)return{error:Pe};if(!n.length)return wr({result:{error:Fe},stack:r});const i=(t=t??e?.participants??[]).filter((t=>t.participantType===uc&&P(n,t.individualParticipantIds).length===n.length&&t.individualParticipantIds.length===n.length)),a=i[0];if(!a)return wr({result:{error:Ee},stack:r});const o=gi(i.slice(1),!1,!0);return{participant:gi(a),duplicatedPairParticipants:o,...E}}function jc({drawDefinition:t,participantId:e}){if("object"!=typeof t)return{error:j};if("string"!=typeof e)return{error:Ae};const{extension:n}=Mr({element:t,name:Zi});return{lineUp:(n?.value||{})[e]}}function Gc({drawDefinition:t,attributes:e}){let{extension:n}=Mr({element:t,name:Yi});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:Yi,value:r},xi({drawDefinition:t,extension:n}),{entryProfile:r}}function qc({drawDefinition:t}){const{extension:e}=Mr({element:t,name:Yi});return{entryProfile:e?.value||{}}}const $c="ALTERNATE",Wc="CONFIRMED",Hc="DIRECT_ACCEPTANCE",zc="FEED_IN",Yc="JUNIOR_EXEMPT",Kc="LUCKY_LOSER",Jc="ORGANISER_ACCEPTANCE",Zc="QUALIFIER",Xc="SPECIAL_EXEMPT",Qc="UNGROUPED",tu="UNPAIRED",eu="WILDCARD",nu="WITHDRAWN",ru=[Wc,Hc,Yc,Jc,Xc],iu=[zc,Kc,Zc],au=[Wc,Hc,zc,Yc,Jc,Xc,eu],ou=[Wc,Hc,Yc,Kc,Zc,Jc,Xc,eu],su=[$c,Wc,Hc,zc,Yc,Kc,Jc,Zc,"REGISTERED",Xc,Qc,tu,eu,nu],cu={ALTERNATE:$c,CONFIRMED:Wc,DIRECT_ACCEPTANCE:Hc,DIRECT_ENTRY_STATUSES:au,DRAW_SPECIFIC_STATUSES:iu,EQUIVALENT_ACCEPTANCE_STATUSES:ru,FEED_IN:zc,JUNIOR_EXEMPT:Yc,LUCKY_LOSER:Kc,ORGANISER_ACCEPTANCE:Jc,QUALIFIER:Zc,SPECIAL_EXEMPT:Xc,STRUCTURE_SELECTED_STATUSES:ou,UNGROUPED:Qc,UNPAIRED:tu,VALID_ENTRY_STATUSES:su,WILDCARD:eu,WITHDRAWN:nu};function uu({stage:t,drawDefinition:e}){const{entryProfile:n}=qc({drawDefinition:e}),r=Object.keys(n).includes(t);if(!r&&ro.includes(t)){return Gc({drawDefinition:e,attributes:[{[t]:{drawSize:void 0,alternates:!0}}]}),!0}return r}function du({stage:t,drawDefinition:e,entryStatus:n}){return e.entries.reduce(((e,r)=>r.entryStage===t&&r.entryStatus===n?e+1:e),0)}function pu({provisionalPositioning:t,placementGroup:n,drawDefinition:r,stageSequence:i,entryStatuses:a,structureId:o,roundTarget:s,stages:c,stage:u}){const d=r.entries?.reduce(((t,e)=>{const n=Mr({name:ra,element:e})?.extension?.value,r=u&&e.entryStage===u||c?.length&&e.entryStage&&c.includes(e.entryStage),o=!a||e.entryStatus&&a.includes(e.entryStatus),d=e.entryStageSequence??1;return r&&(!i||d===i)&&o&&(!s||!n||s===n)?t.concat(e):t}),[])??[];if(o&&u===no){const{playoffEntries:i,error:a}=function({provisionalPositioning:t,drawDefinition:n,structureId:r}){const i=[],a=(n.links??[]).find((t=>t.linkType===Uo&&t.target.structureId===r));if(a){const{finishingPositions:r,structureId:o}=a.source,{structure:s}=ts({drawDefinition:n,structureId:o});if(s?.structureType===mo){(s.structures??[]).forEach((n=>{const a=n.positionAssignments??[],{structureId:o}=n,s=o,c=Object.assign({},...a.map((t=>{const{participantId:e}=t,n=Mr({element:t,name:ca}).extension?.value;return n&&e?{[e]:n}:void 0})).filter(Boolean)),u=Object.keys(c).reduce(((e,n)=>{const r=c[n],i=r.groupOrder||t&&r.provisionalOrder;return e.includes(i)||e.push(i),e}),[]),d=u.length===Object.keys(c).length,p=Object.keys(c).filter((e=>{const n=c[e],i=n.groupOrder||t&&n.provisionalOrder;return r?.includes(i)}));t&&!d||p.forEach((n=>{const a=c[n],{groupOrder:o,provisionalOrder:u,GEMscore:d}=a,p=o||t&&u,l=(r??[]).sort(e).indexOf(p)+1;i.push({entryStage:no,entryStatus:zc,placementGroup:l,groupingValue:s,participantId:n,GEMscore:d})}))}))}}return{playoffEntries:i}}({provisionalPositioning:t,drawDefinition:r,structureId:o});return a&&console.log("playoff entries error"),(i?.length?i:d).filter((t=>!n||t.placementGroup===n))}return d}function lu({provisionalPositioning:t,returnAllProxies:e,drawDefinition:n,structureId:r,structure:i}){let a,o=[];i||({structure:i,error:a}=ts({drawDefinition:n,structureId:r}));const s=rs({structure:i}).positionAssignments;if(a||!i)return{seedAssignments:[],error:Ut};r||(r=i.structureId);const{stage:c,stageSequence:u}=i,d=c===no&&n&&pu({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=lt;return{seedAssignments:o,stageSequence:u,seedLimit:i.seedLimit??i?.positionAssignments?.length,stage:c,error:a}}const mu=(t,e)=>(t||0)+(e||0);function fu(t,e){const n=Array.isArray(t)?t[0]:t;return isNaN(n)&&Nc||n<=e[Ec]&&Ec||n<=e[Ac]&&Ac||Mc}function hu({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(mu)&&(n[r[0]>r[1]?0:1]+=1),{sets:e,games:n,score:t}}function gu(t){const e=Math.min(...t.games),n=Math.max(...t.games);return Math.round(e/n*100)}function Iu(t){return t.map(gu).sort().map((t=>parseFloat(t.toFixed(2))))}function Uu({tournamentRecord:t,drawDefinition:e,policyType:n,structure:r,event:i}){if(!t)return{error:_};const{appliedPolicies:a}=Dc({tournamentRecord:t,drawDefinition:e,structure:r,event:i});return a?.[n]?{policy:a[n]}:{info:ee?.message}}function Su({tournamentRecord:t,profileBands:e,matchUp:n}){if(!n)return{error:zt};const{score:r,winningSide:i}=n;if(!i)return{error:Nn};const a=!e&&t&&Uu({policyType:Si,tournamentRecord:t}).policy,o=e||a?.profileBands||Oc[Si].profileBands,s=Iu([hu({score:r})]),c=fu(s,o),u=Array.isArray(s)?s[0]:s;return{...E,competitiveness:c,pctSpread:u}}function yu({matchUp:t}){if(!t)return{error:zt};if(t&&!t.sides)return{error:Yt};if(t&&!t.hasContext)return{error:hn};const e=(t.sides??[])?.map((t=>t?.participantId)).filter(Boolean),n=t.sides?.filter((t=>t.participant?.participantType===sc)).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:m(i.concat(e)).filter(Boolean)??[],individualParticipantIds:i,sideParticipantIds:e,...E}}const vu="CHECK_IN",wu="CHECK_OUT",Tu="SCHEDULE.ASSIGNMENT.VENUE",Pu="SCHEDULE.ALLOCATION.COURTS",Du="SCHEDULE.ASSIGNMENT.COURT",bu="SCHEDULE.COURT.ORDER",Nu="SCHEDULE.DATE",Ru="SCHEDULE.ASSIGN.OFFICIAL",Mu="SCHEDULE.TIME.SCHEDULED",Au="SCHEDULE.TIME.START",Eu="SCHEDULE.TIME.STOP",Cu="SCHEDULE.TIME.RESUME",Ou="SCHEDULE.TIME.END",Fu="SCHEDULE.TIME.MODIFIERS",ku="TO_BE_ANNOUNCED",xu="NEXT_AVAILABLE",_u="FOLLOWED_BY",Lu="AFTER_REST",Bu="RAIN_DELAY",Vu=[ku,xu,_u,Lu,Bu],ju="SCALE",Gu="RATING",qu="RANKING",$u="SEEDING",Wu="PUBLISH",Hu="PUBLIC",zu="STATUS",Yu={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:Vu,AFTER_REST:Lu,ALLOCATE_COURTS:Pu,ASSIGN_COURT:Du,ASSIGN_OFFICIAL:Ru,ASSIGN_VENUE:Tu,CHECK_IN:vu,CHECK_OUT:wu,COMPLETED_DATE:"COMPLETED.DATE",COURT_ORDER:bu,ELIGIBILITY:"ELIGIBILITY",END_TIME:Ou,FOLLOWED_BY:_u,MEDICAL:"MEDICAL",MODIFICATION:"MODIFICATION",NEXT_AVAILABLE:xu,NOT_BEFORE:"NOT_BEFORE",OTHER:"other",PENALTY:"PENALTY",PUBLIC:Hu,PUBLISH:Wu,RANKING:qu,RATING:Gu,RAIN_DELAY:Bu,REGISTRATION:"REGISTRATION",RESUME_TIME:Cu,RETRIEVAL:"RETRIEVAL",SCALE:ju,SCHEDULE:"SCHEDULE",SCHEDULED_DATE:Nu,SCHEDULED_TIME:Mu,SEEDING:$u,START_TIME:Au,STATUS:zu,STOP_TIME:Eu,SUSPENSION:"SUSPENSION",TIME_MODIFIERS:Fu,TO_BE_ANNOUNCED:ku};function Ku({matchUp:t}){if(!t)return{error:zt};if(!t.hasContext)return{error:hn};if(!t.sides||2!==t.sides.filter(Boolean).length)return{error:Yt};const{nestedIndividualParticipantIds:e,allRelevantParticipantIds:n,sideParticipantIds:r}=yu({matchUp:t}),i=(t.timeItems??[]).filter((t=>t?.itemType&&[vu,wu].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===vu));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,...E}}function Ju(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 Zu(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 Xu({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)}function Qu({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}=Uu({policyType:Ni,tournamentRecord:t,event:r}),a=t?Mr({element:t,name:aa}).extension:void 0,o=a?.value,s=r&&Mr({name:aa,element:r}).extension,c=s?.value;return{scheduleTiming:{tournamentScheduling:o,eventScheduling:c,categoryName:e,categoryType:n,policy:i}}}const td="SINGLES",ed="SINGLES",nd="DOUBLES",rd="DOUBLES",id="TEAM",ad="TEAM",od={AGE:"AGE",BOTH:"BOTH",DOUBLES:nd,DOUBLES_EVENT:rd,RATING:"RATING",SINGLES:td,SINGLES_EVENT:ed,TEAM_EVENT:ad,TEAM:id},sd="DOUBLES_SINGLES",cd="SINGLES_DOUBLES",ud="total",dd="participantConflict",pd="matchUpConflict",ld="ISSUE_IDS",md="CONFLICT",fd="WARNING",hd="ERROR",gd="ISSUE",Id="STATE",Ud={SINGLES_DOUBLES:cd,DOUBLES_SINGLES:sd,TOTAL:ud,CONFLICT_MATCHUP_ORDER:pd,CONFLICT_PARTICIPANTS:dd,SCHEDULE_ISSUE_IDS:ld,SCHEDULE_CONFLICT:md,SCHEDULE_WARNING:fd,SCHEDULE_ERROR:hd,SCHEDULE_ISSUE:gd,SCHEDULE_STATE:Id};function Sd({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:n,matchUpFormat:r,categoryName:i,categoryType:a,eventType:o,event:s}){if(!n)return{error:_};o=o??s?.eventType??ed;const c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=Qu({tournamentRecord:n,categoryName:i,categoryType:a,event:s});return yd({eventType:o,timingDetails:{...u,matchUpFormat:r,categoryType:a,defaultTiming:c}})}function yd({timingDetails:t,eventType:e}){const n=function({matchUpFormat:t,categoryName:e,categoryType:n,defaultTiming:r,tournamentScheduling:i,eventScheduling:a,policy:o}){return Xu({categoryName:e,categoryType:n,timesBlockArray:[a?.matchUpAverageTimes&&Ju({...a,matchUpFormat:t}),i?.matchUpAverageTimes&&Ju({...i,matchUpFormat:t}),o?.matchUpAverageTimes&&Ju({...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 Xu({categoryName:a,categoryType:o,timesBlockArray:[e?.matchUpRecoveryTimes&&Zu({...e,averageMinutes:n,matchUpFormat:i}),t?.matchUpRecoveryTimes&&Zu({...t,averageMinutes:n,matchUpFormat:i}),s?.matchUpRecoveryTimes&&Zu({...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=e===ed?cd:sd;return{averageMinutes:i,recoveryMinutes:s,typeChangeRecoveryMinutes:a?.minutes&&(o?.includes(c)&&a.minutes[c]||s)}}function vd(t){return t.createdAt?new Date(t.createdAt).getTime():0}function wd({visibilityThreshold:t,timeItems:e,itemType:n}){const r=e.filter((e=>e&&e.itemType===n&&(!t||vd(e)<new Date(t).getTime()))).sort(((t,e)=>vd(t)-vd(e))).pop(),i=r&&vd(r);return{itemValue:r?.itemValue,timeStamp:i}}function Td({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=wd({timeItems:r?.timeItems||[],itemType:Mu,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{scheduledTime:i}:n}function Pd({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=wd({timeItems:r?.timeItems||[],itemType:Nu,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{scheduledDate:i}:n}function Dd({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=wd({timeItems:r?.timeItems||[],itemType:Pu,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{allocatedCourts:gi(i,!1,!0)}:n}function bd({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=wd({timeItems:r?.timeItems||[],itemType:Du,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{courtId:i}:n}function Nd({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=wd({timeItems:r?.timeItems||[],itemType:Tu,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{venueId:i}:n}function Rd({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:x};return{linkedTournamentIds:Object.assign({},...Object.keys(t).map((e=>{const n=t[e],r=n?.tournamentId,{extension:i}=Mr({element:n,name:Xi});return{[e]:(i?.value?.tournamentIds||[]).filter((t=>t!==r))}})))}}function Md(){const t=[];for(let e=0;e<256;e++)t[e]=(e<16?"0":"")+e.toString(16);const e=4294967295*Math.random()|0,n=4294967295*Math.random()|0,r=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return t[255&e]+t[e>>8&255]+t[e>>16&255]+t[e>>24&255]+"-"+t[255&n]+t[n>>8&255]+"-"+t[n>>16&15|64]+t[n>>24&255]+"-"+t[63&r|128]+t[r>>8&255]+"-"+t[r>>16&255]+t[r>>24&255]+t[255&i]+t[i>>8&255]+t[i>>16&255]+t[i>>24&255]}function Ad(t){const{disableNotice:e,venue:n,context:r}=t;if("object"!=typeof n)return{error:Nn};const i=nc(t);let a;n.venueId||(n.venueId=Md());for(const t of Object.values(i)){const e=Ed({disableNotice:!0,tournamentRecord:t,context:r,venue:n});if(e?.error)return e;a=e.venue}return e||sr({topic:us,payload:{venue:n}}),vr({...E,venue:a})}function Ed({tournamentRecord:t,disableNotice:e,context:n,venue:r}){if(!t)return{error:_};if(!r)return{error:ae,info:"missing venue"};t.venues||(t.venues=[]),r.venueId||(r.venueId=Md());if(t.venues.reduce(((t,e)=>t||e.venueId===r.venueId),void 0))return{error:nn};if(n){Nr({element:r,extension:{value:n,name:Gi}})}return t.venues.push(r),e||sr({payload:{venue:r,tournamentId:t.tournamentId},topic:us}),{...E,venue:gi(r)}}function Cd({tournamentRecords:t,tournamentRecord:e,venueId:n}){if(!e)return{error:_};if(!n)return{error:an};const r=(e.venues??[]).reduce(((t,e)=>e.venueId===n?e:t),void 0);if(!r&&t){const i=(Rd({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(const a of i){const i=Cd({tournamentRecord:t[a],venueId:n});if(i.success&&i.venue)return Ad({tournamentRecord:e,venue:i.venue}),{...E,venue:r}}}return r?{...E,venue:r}:{error:rn}}function Od({tournamentRecords:t,tournamentRecord:e,courtId:n}){if(!e)return{error:_};if(!n)return{error:ie};let r,i;if((e.venues??[]).forEach((t=>{(t.courts??[]).forEach((e=>{e.courtId===n&&(r=e,i=t)}))})),r)return{...E,court:r,venue:i};if(t){const a=(Rd({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(const o of a){const a=Od({tournamentRecord:t[o],courtId:n});if(a.success)return a.venue&&Ad({tournamentRecord:e,venue:a.venue}),{...E,court:r,venue:i}}}return wr({result:{error:tn},stack:"findCourt"})}function Fd({tournamentRecord:t,internalUse:e,courtId:n}){if(!t)return{error:_};if(!n)return{error:ie};const r=Od({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{...E,courtInfo:gi(i,!1,e)}}function kd({tournamentRecord:t,venueId:e}){if(!t)return{error:_};if(!e)return{error:an};const n=Cd({tournamentRecord:t,venueId:e});if(n.error)return n;const r=(n.venue?.courts??[]).map((e=>(({courtInfo:t})=>({...t}))(Fd({courtId:e.courtId,internalUse:!0,tournamentRecord:t})))),i=n.venue&&(({venueId:t,venueName:e,venueAbbreviation:n})=>({venueAbbreviation:n,venueName:e,venueId:t}))(n.venue),a=i&&{...i,courtsInfo:r};return{...E,venueData:gi(a,!1,!0)}}function xd({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=wd({timeItems:r?.timeItems||[],itemType:Fu,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{timeModifiers:i}:n}function _d(t){if(Br.test(t)){const e=Hr();return new Date(`${e}T${t}`)}return new Date(t)}function Ld(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 Bd({event:t,eventId:e}){if(!t)return{error:Tt};const n=Mr({name:Ki,element:t}),r=n?.extension,i=e?gi(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 Vd(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&&Bd({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,...wr({result:{error:Pt},stack:i})}}return{event:void 0,drawDefinition:void 0,...wr({result:{error:q},context:{drawId:r,eventId:n},stack:i})}}function jd({scheduleVisibilityFilters:t,afterRecoveryTimes:e,tournamentRecord:n,usePublishState:r,scheduleTiming:i,matchUpFormat:a,publishStatus:o,matchUpType:s,matchUp:c,event:u}){if(!c)return{error:zt};if(e&&!c.matchUpType&&!s&&(u||n)&&c.drawId){let t=u?.drawDefinitions?.find((t=>t.drawId===c.drawId));!t&&n&&({drawDefinition:t,event:u}=Vd({tournamentRecord:n,drawId:c.drawId}));const e=c.structureId&&t?.structures?.find((({structureId:t})=>t===c.structureId));s=e?.matchUpType||t?.matchUpType||u?.eventType!==id&&u?.eventType}const{milliseconds:d,time:p}=function({matchUp:t}){if(!t)return{error:zt};if(!t.timeItems)return{error:fn};const e=t.timeItems.filter((t=>[Au,Eu,Cu,Ou].includes(t?.itemType))).sort(((t,e)=>_d(t.itemValue).getTime()-_d(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 Au:n=0;break;case Ou:if(t.lastValue&&[Au,Cu].includes(t.lastType)){const r=_d(e.itemValue).getTime()-_d(t.lastValue).getTime();n=t.milliseconds+r}else n=t.milliseconds;break;case Eu:if([Au,"SCHECULE.TIME.RESUME"].includes(t.lastType)){const r=_d(e.itemValue).getTime()-_d(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([Au,Cu].includes(n.lastType)){const t=(new Date).getTime()-_d(n.lastValue).getTime();n.milliseconds+=t}return{milliseconds:n.milliseconds,time:Ld(n.milliseconds),relevantTimeItems:e}}({matchUp:c}),{startTime:l}=function({matchUp:t}){const e=t=>t.createdAt?new Date(t.createdAt).getTime():0,n=(t?.timeItems||[]).reduce(((t,n)=>{const r=n.itemType===Au&&n;return r&&(!t||e(r)<e(t))?r:t}),void 0),r=n?.itemValue;return{startTime:r}}({matchUp:c}),{endTime: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===Ou&&n;return r&&(!t||e(r)>e(t))?r:t}),void 0),r=n?.itemValue;return{endTime:r}}({matchUp:c});let f;const{visibilityThreshold:h,eventIds:g,drawIds:I}=t??{};if(g&&!g.includes(c.eventId)||I&&!I.includes(c.drawId))f=vr({milliseconds:d,startTime:l,endTime:m,time:p});else{const t={matchUp:c,visibilityThreshold:h},{allocatedCourts:r}=Dd(t),{scheduledTime:o}=Td(t);let{scheduledDate:u}=Pd(t);const{venueId:g}=Nd(t),{courtId:I}=bd(t),{courtOrder:U}=function({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=wd({timeItems:r?.timeItems||[],itemType:bu,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{courtOrder:i}:n}(t),{timeModifiers:S}=xd(t);let y,v,w,T,P;const D=c.matchUpType??s;if(i&&o&&e&&D){const t={matchUpFormat:c.matchUpFormat??a,...i};({averageMinutes:v=0,recoveryMinutes:w=0,typeChangeRecoveryMinutes:T=0}=yd({timingDetails:t,eventType:D})),(v||w)&&(y=m?pi(ni(m),w):pi(o,v+w)),T&&(P=m?pi(ni(m),T):pi(o,v+T))}!u&&o&&(u=ri(o));const b=Gr({scheduledDate:u,scheduledTime:o}),N={},R=(n&&g&&kd({tournamentRecord:n,venueId:g}))?.venueData||{};g&&(N[g]=R);const{venueName:M,venueAbbreviation:A,courtsInfo:E}=R,C=I&&E?.find((t=>t.courtId===I)),O=C?.courtName;for(const t of r||[]){if(!n)break;t.venueId&&!N[t.venueid]&&(N[t.venueId]=kd({venueId:t.venueId,tournamentRecord:n})?.venueData);const e=N[t.venueId];t.venueName=e?.venueName;const r=e?.courtsInfo?.find((e=>e.courtId===t.courtId));t.courtName=r?.courtName}f=vr({typeChangeTimeAfterRecovery:P,timeAfterRecovery:y,scheduledDate:u,scheduledTime:o,isoDateString:b,allocatedCourts:r,timeModifiers:S,venueAbbreviation:A,venueName:M,venueId:g,courtOrder:U,courtName:O,courtId:I,typeChangeRecoveryMinutes:T,recoveryMinutes:w,averageMinutes:v,milliseconds:d,startTime:l,endTime:m,time:p})}const{scheduledDate:U}=Pd({matchUp:c}),{scheduledTime:S}=Td({matchUp:c});if(r&&o?.displaySettings?.draws){const t=o.displaySettings.draws,e=(t?.[c.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){f=_r({source:f,template:Object.assign({},...Object.keys(f).map((t=>({[t]:!0}))),t)})}}}return{schedule:f,endDate:c.matchUpStatus&&Ya.includes(c.matchUpStatus)&&(ri(m)||ri(U)||ri(S))||void 0}}function Gd(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 qd({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 $d({drawDefinition:t,structure:e,matchUp:n,event:r}){return{tieFormat:qd({item:n,drawDefinition:t,structure:e,event:r})||qd({item:e,drawDefinition:t,structure:e,event:r})||Gd(t)||Gd(r)}}function Wd(t){if(!Array.isArray(t))return"";const e=t.filter(s);if(!e.length)return"";return m([Math.min(...e),Math.max(...e)]).join("-")}const Hd="timed",zd="NOAD",Yd="SET",Kd={S:"normal",F:"final"};function Jd(t){if("string"==typeof t){const e=t.startsWith("T")&&Hd||t.startsWith(Yd)&&Yd||"";if(e===Hd){const e=tp(t);if(e)return{simplified:!0,setFormat:e,bestOf:1}}if(e===Yd)return function(t){const e=t.split("-"),n=np(e[0].slice(3)),r=1===n||n%2!=0?n:void 0,i=1!==n&&n%2==0?n:void 0,a=e&&Zd(e[1]),o=e&&Zd(e[2]),s=a&&a.timed||o&&o.timed,c=r&&r<6||s&&i,u=!e[2]||o,d=a,p=vr({setFormat:a,exactly:i,bestOf:r});o&&(p.finalSetFormat=o);if(c&&d&&u)return p}(t)}}function Zd(t){if(":"===t?.[1]){const e=t.split(":"),n=Kd[e[0]],r=e[1];if(n&&r){if(r.startsWith("TB")){const t=Qd(r);return!1!==t&&("object"==typeof t?{tiebreakSet:t}:void 0)}if(r.startsWith("T"))return tp(r);const e=t.match(/^[FS]:(\d+)([A-Za-z]*)/),n=e&&ep(e[2])||!1,i=!e?.[2]||n,a=e?np(e[1]):void 0,o=Xd(r),s=!1!==o,c=s&&o||a,u=Qd(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 Xd(t,e=!0){const n=t?.indexOf("@")>0&&t.split("@");if(n){return(e?np(n[1]):n[1])||!1}}function Qd(t){if(t){if(t.startsWith("TB")){const e=Xd(t,!1),n=t.match(/^TB(\d+)([A-Za-z]*)/),r=n?.[1],i=n&&ep(n[2]),a=!n?.[2]||i,o=np(r);if(o&&a){const t={tiebreakTo:o};return e&&"string"==typeof e&&!p(e)&&(t.modifier=e),i&&(t.NoAD=!0),t}return!1}return!1}}function tp(t){const e=t.slice(1),n=e.match(/^(\d+)(@?[A-Za-z]*)/),r=np(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 ep(t){return t&&t.indexOf(zd)>=0}function np(t){return isNaN(Number(t))?0:Number(t)}function rp(t){const{matchUps:e,isCollectionMatchUp:n,excludeMatchUpStatuses:r,matchUpStatuses:i,hasWinningSide:a,matchUpFormats:o,roundPositions:s,matchUpFormat:c,collectionIds:u,isMatchUpTie:d,roundNumbers:p,matchUpIds:l,roundNames:m,stageSequences:f,scheduledDates:h,scheduledDate:g,participantIds:I,processContext:U,tournamentIds:S,matchUpTypes:y,structureIds:v,readyToScore:w,courtIds:T,eventIds:P,venueIds:D,drawIds:b,stages:N,filterMatchUpIds:R=!0,filterMatchUpTypes:M=!0}=t,A=Array.isArray(I)?I.filter(Boolean):[],E=Array.isArray(i)?i.filter(Boolean):[],C=Array.isArray(r)?r.filter(Boolean):[],O=Array.isArray(N)?N.filter(Boolean):[],F=Array.isArray(f)?f.filter(Boolean):[],k=Array.isArray(u)?u.filter(Boolean):[],x=Array.isArray(m)?m.filter(Boolean):[],_=Array.isArray(p)?p.filter(Boolean):[],L=Array.isArray(s)?s.filter(Boolean):[],B=Array.isArray(l)&&R?l.filter(Boolean):[],V=Array.isArray(y)&&M?y.filter(Boolean):[],j=Array.isArray(T)?T.filter(Boolean):[],G=Array.isArray(D)?D.filter(Boolean):[],q=Array.isArray(o)&&o.filter(Boolean)||"string"==typeof c&&[c]||[],$=Array.isArray(h)&&h.filter(Boolean)||"string"==typeof g&&g.length&&[g]||[],W=Array.isArray(S)?S.filter(Boolean):[],H=Array.isArray(P)?P.filter(Boolean):[],z=Array.isArray(b)?b.filter(Boolean):[],Y=Array.isArray(v)?v.filter(Boolean):[];return e.filter((t=>{if(w&&t.matchUpType!==Xs&&!t.readyToScore)return!1;if(t.winningSide&&a&&![1,2].includes(t.winningSide))return!1;if(void 0!==d){if(d&&!t.tieMatchUps)return!1;if(!d&&t.tieMatchUps)return!1}if(void 0!==n){if(n&&!t.collectionId)return!1;if(!n&&t.collectionId)return!1}if(O.length&&!O.includes(t.stage))return!1;if(F.length&&!F.includes(t.stageSequence))return!1;if(k.length&&(!t.collectionId||!k.includes(t.collectionId)))return!1;if(x.length&&(!t.roundName||!x.includes(t.roundName)))return!1;if(_.length&&(!t.roundNumber||!_.includes(t.roundNumber)))return!1;if(L.length&&(!t.roundPosition||!L.includes(t.roundPosition)))return!1;if(E.length&&(!t.matchUpStatus||!E.includes(t.matchUpStatus)))return!1;if(C.length&&t.matchUpStatus&&C.includes(t.matchUpStatus))return!1;if(B.length&&!B.includes(t.matchUpId))return!1;if(V.length&&(!t.matchUpType||!V.includes(t.matchUpType)))return!1;if(q.length&&(!t.matchUpFormat||!q.includes(t.matchUpFormat)))return!1;if($?.length){const{scheduledTime:e}=Td({matchUp:t}),{scheduledDate:n}=Pd({matchUp:t}),r=ri(e)||n;if(!$.find((t=>fi(t,r))))return!1}if(j.length){const{courtId:e}=bd({matchUp:t}),{allocatedCourts:n}=Dd({matchUp:t}),r=n?.map((({courtId:t})=>t));if(!j.filter(Boolean).includes(e)||r?.includes(e))return!1}if(G.length){const{venueId:e}=Nd({matchUp:t});if(!G.filter(Boolean).includes(e))return!1}if(U){if(W.length&&!W.includes(t.tournamentId))return!1;if(H.length&&!H.includes(t.eventId))return!1;if(z.length&&!z.includes(t.drawId))return!1;if(Y.length&&!Y.includes(t.structureId))return!1;if(A.length){const e=t.sides?.map((({participantId:t})=>t)).filter(Boolean)??[];if(!A.some((t=>e.includes(t))))return!1}}return!0}))}function ip({roundsNotPowerOf2:t,drawDefinition:e,structure:n,matchUps:r}){if(!n)return!1;r=r??n.matchUps??[],t=t??vc({matchUps:r}).roundsNotPowerOf2;const i=!!n.positionAssignments?.find((({drawPosition:t})=>t))||!!r?.find((({drawPositions:t})=>t?.length));return(!e?.drawType||e.drawType!==Ao)&&!n?.structures&&t&&i}function ap({drawDefinition:t,structure:e}){if(!e)return!1;const n=e.matchUps||e.roundMatchUps&&Object.values(e.roundMatchUps).flat(),r=n?.find((t=>t?.roundPosition)),i=n?.find((t=>t?.drawPositions?.length));return!(e?.structures||e?.stage===eo||t?.drawType&&t.drawType!==wo||r||i)}const op={[Pi]:{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:{[Xa]:"",[no]:"P",[Qa]:"Q",[to]:"C"}}};const sp="tournamentRecords",cp="policyDefinitions",up="tournamentRecord",dp="drawDefinition",pp="matchUpFormat",lp="participantId",mp="scheduleDates",fp="structureId",hp="matchUpIds",gp="structures",Ip="matchUpId",Up="inContext",Sp="structure",yp="courtIds",vp="venueIds",wp="matchUps",Tp="courtId",Pp="eventId",Dp="matchUp",bp="drawId",Np="error",Rp="event",Mp="param",Ap="object",Ep="array",Cp="validate",Op="invalid",Fp="_ofType",kp="_oneOf",xp={[sp]:x,[up]:_,[cp]:Jt,[dp]:j,[lp]:Ae,tournamentId:B,[fp]:It,[hp]:$t,[gp]:St,[Ip]:qt,[Sp]:yt,[Tp]:ie,[wp]:Ht,[Dp]:zt,[yp]:ae,[vp]:ae,[bp]:at,[Pp]:Tt,[Rp]:Pt},_p={[sp]:Ap,[cp]:Ap,[up]:Ap,[dp]:Ap,[mp]:Ep,[hp]:Ep,[gp]:Ep,[Sp]:Ap,[yp]:Ep,[vp]:Ep,[wp]:Ep,[Dp]:Ap,[Rp]:Ap};function Lp(t,e,n){if(!t&&!ha(t))return{error:Nn};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:Nn};const{paramError:r,errorParam:i}=function(t,e){let n;const r=e.find((({_ofType:e,_oneOf:r,_anyOf:i,validate:a,...o})=>{const s=r&&function(t,e){if(!e)return;const n=Bp(t,e);return 1!==n.length?{error:Nn}:n.reduce(((t,e)=>({...t,[e]:!0})),{})}(t,r);if(s?.error)return s.error;s&&Object.assign(o,s);const c=i&&function(t,e){if(!e)return;const n=Bp(t,e).filter((e=>t[e]));return n.length<1?{error:Nn}:n.reduce(((t,e)=>({...t,[e]:!0})),{})}(t,i);if(c?.error)return c.error;c&&Object.assign(o,c);const u=Object.keys(o).filter((t=>"boolean"==typeof o[t])),d=u.find((r=>{const i=!ma(a)&&(void 0===t[r]||function(t,e,n){if(n=n||_p[e]||"string","array"===n)return!Array.isArray(t[e]);return typeof t[e]!==n}(t,r,e)),o=i||a&&!function(t,e){return!ma(e)||e(t)}(t[r],a);return o&&(n=r),o}));return!u.length||d}));return{paramError:r,errorParam:n}}(t,e);if(!r)return{valid:!0};return wr({info:{param:i},result:{error:void 0===t[i]?xp[i]||Nn:r.validate&&r.invalid||Nn},stack:n})}function Bp(t,e){return P(Object.keys(t),Object.keys(e))}function Vp(t){const e=Lp(t,[{[Dp]:!0}]);if(e.error)return e;const n=t?.matchUp;let r=n?.matchUpType;if(!r&&n?.sides?.length){const t=n.sides.find((({participant:t})=>t)),e=t?.participant,i=e?.participantType;r=i===sc&&Ks||i===uc&&Zs||i===dc&&dc||void 0}return{matchUpType:r}}function jp({drawPositionCollectionAssignment:t,positionAssignments:e,displaySideNumber:n,seedAssignments:r,drawPosition:i,isFeedRound:a,sideNumber:o}){const s=e.find((t=>t.drawPosition&&t.drawPosition===i)),c=t?t[i]?.participantId:s?.participantId,u=s?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})}else r.bye&&Object.assign(a,{bye:!0});r.qualifier&&Object.assign(a,{qualifier:!0});return a}({displaySideNumber:n,seedAssignments:r,participantId:c,assignment:s,sideNumber:o}):{};a&&(1===o?Object.assign(u,{participantFed:!0}):Object.assign(u,{participantAdvanced:!0}));const d=t?.[i]?.teamParticipant,p=t?.[i]?.participant,l=t?.[i]?.substitutions;return p&&Object.assign(u,{participant:p}),l&&Object.assign(u,{substitutions:l}),d&&Object.assign(u,{teamParticipant:d}),u}const Gp="ANY",qp="MALE",$p="MIXED",Wp="OTHER",Hp="FEMALE",zp={ANY:Gp,MALE:qp,FEMALE:Hp,MIXED:$p,OTHER:Wp};function Yp({scheduleVisibilityFilters:t,tournamentAppliedPolicies:r,provisionalPositioning:i,tournamentParticipants:a,afterRecoveryTimes:o,policyDefinitions:s,tournamentRecord:c,seedAssignments:u,usePublishState:d,contextFilters:l,contextContent:f,matchUpFilters:h,participantMap:g,scheduleTiming:I,contextProfile:U,drawDefinition:S,publishStatus:y,context:v={},exitProfiles:T,matchUpsMap:P,structure:D,inContext:A,event:E}){let C={},O={};if(a=a??c?.participants,!D)return{collectionPositionMatchUps:C,error:yt,roundMatchUps:O,matchUps:[]};const F=Array.isArray(h?.eventIds)?h?.eventIds.filter(Boolean):[],k=Array.isArray(h?.structureIds)?h?.structureIds.filter(Boolean):[],x=Array.isArray(h?.drawIds)?h?.drawIds.filter(Boolean):[],_=!v?.eventId||!F?.length&&!l?.eventIds?.filter(Boolean).length||F?.includes(v.eventId)||l?.eventIds?.includes(v.eventId),L=!k?.length||k.includes(D.structureId),B=!S||!x?.length||x.includes(S.drawId);if(!_||!L||!B)return{collectionPositionMatchUps:C,roundMatchUps:O,matchUps:[]};U&&!f&&(f=Fc({tournamentRecord:c,contextProfile:U,drawDefinition:S}));const{appliedPolicies:V}=Dc({drawDefinition:S}),G={...r,...V,...s},q=G?.scoring?.structures,$=D.stage&&q?.stage&&q?.stage[D.stage],W=D.stageSequence&&$?.stageSequence&&$.stageSequence[D.stageSequence],H=G?.scoring?.requireAllPositionsAssigned||$?.requireAllPositionsAssigned||W?.requireAllPositionsAssigned;P||(P=xc({drawDefinition:S,structure:D}));const{positionAssignments:z,allPositionsAssigned:Y}=is({structure:D}),K=!H||Y,{seedAssignments:J}=lu({provisionalPositioning:i,drawDefinition:S,structure:D});u=u??J;const{roundOffset:Z,structureId:X,structureName:Q,stage:tt,stageSequence:et}=D,{drawId:nt,drawName:rt,drawType:it}=S??{};T=T||S&&kc({drawDefinition:S}).exitProfiles;const at=T?.[X],ot=at?.length&&(at[0].split("-").map((t=>parseInt(t))).reduce(((t,e)=>t+e))||0),st=!!D.structures;let ct=_c({matchUpsMap:P,structureId:X,inContext:A});const ut=G?.[Pi],dt=function({roundNamingPolicy:t,drawDefinition:e,structure:n,matchUps:r}){const{roundProfile:i,roundMatchUps:a}=vc({matchUps:r}),{structureAbbreviation:o,stage:s}=n,c=ap({structure:n}),u=ip({structure:n}),d=n.structures,p={},l=op[Pi],m=n.stage===Qa,f=m?Math.max(...(e?.structures??[]).filter((t=>t.stage===Qa)).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||{},S=t?.affixes?.preFeedRound||l.affixes.preFeedRound,y=t?.affixes?.roundNumber||l.affixes.roundNumber,v=(t?.namingConventions||l.namingConventions).round,w=s&&s!==Xa?s[0]:"",T=t?.stageConstants||l.stageConstants,P=`${g}${s&&T?.[s]||w}${h}`,D=i?Object.keys(i):[],b=m&&T?.[Qa]?`${T?.[Qa]}-`:"";if(d||c||u)Object.assign(p,...D.map((t=>({[t]:{roundName:`${b}${v} ${t}`,abbreviatedRoundName:`${y}${t}`}}))));else{const e=m&&(t?.qualifyingFinishMap||l?.qualifyingFinishMap||{});Object.assign(p,...D.map((t=>{if(!i?.[t])return;const{matchUpsCount:n,preFeedRound:r}=i[t],a=2*n,s=e?.[i?.[t].finishingRound]||e&&`${y}${a}`||I[n]||`${y}${a}`,c=r?`-${S}`:"",u=[P,o,`${s}${c}`].filter(Boolean).join("-"),d=U[n]||`${y}${a}`;return{[t]:{abbreviatedRoundName:[P,o,`${d}${c}`].filter(Boolean).join("-"),roundName:u}}})))}return{roundNamingProfile:p,roundProfile:i,roundMatchUps:a}}({roundNamingPolicy:ut,drawDefinition:S,structure:D,matchUps:ct}),{roundNamingProfile:pt,roundProfile:lt}=dt;if(O=dt?.roundMatchUps??[],h&&(ct=rp({matchUps:ct,...h,filterMatchUpTypes:!1,filterMatchUpIds:!1})),A){const{sourceDrawPositionRanges:n}=function({drawDefinition:t,structureId:e,matchUpsMap:n}){if(!t)return{error:j};if(!e)return{error:It};const{structure:r}=ts({drawDefinition:t,structureId:e});if(r?.stage!==to)return{error:At,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=>({[t]:vc({matchUps:_c({structureId:t,matchUpsMap:n})}).roundProfile})))),c=_c({matchUpsMap:n,structureId:e}),{roundProfile:u}=vc({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=fc({roundPositionsCount:g.length,groupedOrder:i}),U=I?.length||1;if(U<=h){const t=N(g,p.length/U);r===Io&&t.forEach((t=>t.reverse())),g=I?.length&&I?.map((e=>t[e-1])).flat()||g}let S=N(g,f);if(I?.length||r!==Io||S.reverse(),a){const t=w(0,a.interleave).map((()=>{})),e=w(0,a.offset).map((()=>{}));S=S.map((e=>[e,...t])),S.unshift(e),S=S.flat(1);const n=S.length-a.offset;S=S.slice(0,n)}d[o]||(d[o]={});const y=u?.[o],v=y?.feedRound?2:1;S.forEach(((t,e)=>{const n=1+e*v;d[o][n]||(d[o][n]=Wd(t))}))})),{sourceDrawPositionRanges:d}}({drawDefinition:S,matchUpsMap:P,structureId:X}),r=S?function({drawDefinition:t,roundProfile:n,structureId:r,matchUpsMap:i}){if(!t)return{error:j};if(!r)return{error:It};if(!n){const t=_c({matchUpsMap:i,structureId:r});if(({roundProfile:n}=vc({matchUps:t})),!n)return{error:ae}}const a=(Math.min(...n?.[1]?.drawPositions??[])||1)-1,o=Object.keys(n);return{drawPositionsRanges:Object.assign({},...(o||[]).map((t=>{const r=n?.[t]?.matchUpsCount,i=n?.[1]?.drawPositions??[],s=N(i,i.length/r),c=s.map(Wd),u=s.map((t=>t.map((t=>t-a)))).map(Wd),d=o.map((e=>{if(e>t)return;const i=n?.[e]?.drawPositions??[];return N(i,i.length/r)})).filter(Boolean),p=w(0,r).map((t=>d.map((e=>e[t])).flat().filter(Boolean).sort(e))).map((t=>m(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(Wd).join(", ");var e})),f=Object.assign({},...w(0,r).map((t=>({[t+1]:{firstRoundDrawPositionsRange:c[t],firstRoundOffsetDrawPositionsRange:u[t],possibleDrawPositions:p[t],drawPositionsRange:l[t]}}))));return{[t]:f}})))}}({drawDefinition:S,roundProfile:lt,matchUpsMap:P,structureId:X}).drawPositionsRanges:void 0;ct=ct.map((e=>mt({scheduleVisibilityFilters:t,sourceDrawPositionRanges:n,drawPositionsRanges:r,roundNamingProfile:pt,initialRoundOfPlay:ot,appliedPolicies:G,usePublishState:d,publishStatus:y,isRoundRobin:st,roundProfile:lt,matchUp:e,event:E})));const i=ct?.filter((t=>Array.isArray(t.tieMatchUps)));i.forEach((t=>{const e=t.tieMatchUps;ct=ct.concat(...e)})),l&&(ct=rp({processContext:!0,...l,matchUps:ct}))}else{const t=ct?.filter((t=>Array.isArray(t.tieMatchUps)));t.forEach((t=>{const e=t.tieMatchUps;ct=ct.concat(...e)}))}return h&&(ct=rp({matchUps:ct,...h,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(h?.matchUpTypes||h?.matchUpIds)&&(ct=rp({matchUpTypes:h.matchUpTypes,matchUpIds:h.matchUpIds,matchUps:ct})),(h?.matchUpTypes||h?.matchUpIds||A)&&(O=vc({matchUps:ct}).roundMatchUps??[]),$d({drawDefinition:S,structure:D,event:E})?.tieFormat&&({collectionPositionMatchUps:C}=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:ct})),{collectionPositionMatchUps:C,roundMatchUps:O,roundProfile:lt,matchUpsMap:P,matchUps:ct};function mt({scheduleVisibilityFilters:t,sourceDrawPositionRanges:r,drawPositionsRanges:i,initialRoundOfPlay:s,additionalContext:d,roundNamingProfile:l,tieDrawPositions:h,appliedPolicies:y,isCollectionBye:w,usePublishState:T,publishStatus:P,matchUpTieId:N,isRoundRobin:A,roundProfile:E,sideLineUps:C,matchUp:O,event:F}){d=d??{};const k=$d({drawDefinition:S,structure:D,matchUp:O,event:F})?.tieFormat,x=k?.collectionDefinitions,_=O.collectionId&&x?.find((t=>t.collectionId===O.collectionId)),L=O.collectionId?_?.matchUpFormat:O.matchUpFormat??D?.matchUpFormat??S?.matchUpFormat??F?.matchUpFormat,B=O.matchUpType||_?.matchUpType||D?.matchUpType||S?.matchUpType||F?.eventType!==id&&F?.eventType,V=w?Ma:O.matchUpStatus,{schedule:j,endDate:G}=jd({scheduleVisibilityFilters:t,afterRecoveryTimes:o,tournamentRecord:c,usePublishState:T,scheduleTiming:I,matchUpFormat:L,publishStatus:P,matchUpType:B,matchUp:O,event:F}),q=h??O.drawPositions??[],{collectionPosition:$,collectionId:W,roundPosition:H}=O,Y=O.roundNumber??d.roundNumber,J=W?function({tournamentParticipants:t,positionAssignments:e,collectionPosition:n,drawPositions:r=[],participantMap:i,drawDefinition:a,collectionId:o,sideLineUps:s,matchUpType:c}){if(!o||!n)return;const u=r?.map((r=>{const u=e.find((t=>t.drawPosition===r))?.participantId,d=s?.find((t=>t?.drawPosition===r)),p=d?.teamParticipant||u&&i?.[u]?.participant||t?.find((({participantId:t})=>t===u)),l=d?.lineUp||jc({participantId:u,drawDefinition:a})?.lineUp,{assignedParticipantIds:m,substitutions:f}=Bc({collectionPosition:n,collectionId:o,lineUp:l});if(c!==Zs){const t=m?.[0];return t&&{[r]:{participantId:t,teamParticipant:p,substitutions:f}}}if(m?.length<=2){const e=i?.[m[0]]?.pairIdMap?.[m[1]],n=e&&i[e]?.participant||Vc({participantIds:m,tournamentParticipants:t}).participant,a=n?.participantId;return{[r]:{participantId:a,teamParticipant:p,substitutions:f}}}if(m?.length>2)return{[r]:{teamParticipant:p,substitutions:f}}})).filter(Boolean)||{};return Object.assign({},...u)}({tournamentParticipants:a,positionAssignments:z,collectionPosition:$,drawDefinition:S,participantMap:g,drawPositions:q,collectionId:W,sideLineUps:C,matchUpType:B}):void 0,at=l?.[Y]?.roundName||d.roundName,ot=l?.[Y]?.abbreviatedRoundName||d.abbreviatedRoundName,st=E?.[Y]?.feedRound,ct=E?.[Y]?.preFeedRound,ut=E?.[Y]?.roundFactor,dt=i?.[Y],pt=H?dt?.[H]:void 0,lt=r?.[Y],ft=_?.category?{...v?.category||{},..._.category}:v?.category??F?.category,ht=O.processCodes?.length&&O.processCodes||_?.processCodes?.length&&_?.processCodes||D?.processCodes?.length&&D?.processCodes||S?.processCodes?.length&&S?.processCodes||F?.processCodes?.length&&F?.processCodes||c?.processCodes,gt=U?.withCompetitiveness&&Su({...f,matchUp:O}),It=O.finishingPositionRange??d.finishingPositionRange,Ut=t=>vr(t,void 0,!0),St={...Ut(v),...Ut({matchUpFormat:O.matchUpType===id?void 0:L,tieFormat:O.matchUpType!==id?void 0:k,gender:_?.gender??F?.gender,roundOfPlay:tt!==Qa&&p(s)&&s+(Y||0),endDate:O.endDate??G,discipline:F?.discipline,category:ft,finishingPositionRange:It,abbreviatedRoundName:ot,drawPositionsRange:pt,competitiveProfile:gt,structureName:Q,stageSequence:et,drawPositions:q,matchUpStatus:V,processCodes:ht,isRoundRobin:A,matchUpTieId:N,preFeedRound:ct,matchUpType:B,roundFactor:ut,roundOffset:Z,structureId:X,roundNumber:Y,feedRound:st,roundName:at,drawName:rt,drawType:it,schedule:j,drawId:nt,stage:tt}),...gi(Ut(O),!0,!0)};if(L&&O.score?.scoreStringSide1){const t=Jd(L),{bestOf:e,finalSetFormat:n,setFormat:r}=t??{};(n?.tiebreakSet||r?.tiebreakSet||r?.timed)&&(St.score.sets=St.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(q)){const{orderedDrawPositions:t,displayOrder:r}=function({drawPositions:t,roundProfile:r,roundNumber:i}){const a=[void 0,void 0];if(M(t))return{orderedDrawPositions:a,displayOrder:a};const o=r?.[i],s=o?.pairedDrawPositions,c=s?.find((e=>b(e||[],t.filter(Boolean))))??a,u=o?.feedRound;if(R(t)){const n=[...t].sort(e);return{orderedDrawPositions:2===n.length?n:c,displayOrder:u?n:c}}if(u){const e=[t.find((t=>!isNaN(n(t)))),void 0];return{orderedDrawPositions:e,displayOrder:e}}return{orderedDrawPositions:c,displayOrder:c}}({drawPositions:q,roundProfile:E,roundNumber:Y}),i=E?.[Y]?.feedRound,a=r[0]!==t[0],o=t.concat(void 0,void 0).slice(0,2).map(((t,e)=>{const n=e+1,r=jp({drawPositionCollectionAssignment:J,positionAssignments:z,displaySideNumber:a?3-n:n,seedAssignments:u,drawPosition:t,isFeedRound:i,sideNumber:n}),o=O.sides?.find((t=>t.sideNumber===n)),s=H?2*(H-1)+e+1:void 0;return Ut({sourceDrawPositionRange:s?lt?.[s]:void 0,...o,...r})}));Object.assign(St,gi({sides:o},!0,!0))}if(a&&St.sides){const t=y?.[Di],e=e=>{const n=g?.[e]?.participant;return n&&_r({template:t?.participant,source:n})};if(St.sides.filter(Boolean).forEach((t=>{if(t.participantId){const n=gi(e(t.participantId)||a&&Fi({policyDefinitions:y,participantId:t.participantId,tournamentParticipants:a,internalUse:!0,contextProfile:U}),void 0,!0);if(n){if(S?.entries){const e=S.entries.find((e=>e.participantId===t.participantId));e?.entryStatus&&(n.entryStatus=e.entryStatus),e?.entryStage&&(n.entryStage=e.entryStage)}Object.assign(t,{participant:n})}}if(t?.participant?.individualParticipantIds?.length&&!t.participant.individualParticipants?.length){const n=t.participant.individualParticipantIds.map((t=>e(t)||a&&Fi({policyDefinitions:y,tournamentParticipants:a,internalUse:!0,contextProfile:U,participantId:t})));Object.assign(t.participant,{individualParticipants:n})}})),!St.matchUpType){const{matchUpType:t}=Vp({matchUp:St});t&&Object.assign(St,{matchUpType:t})}if(U?.inferGender&&(!St.gender||St.gender===$p)&&2===St.sides?.length&&St.matchUpType!==id){const t=St.sides.map((t=>{if(St.matchUpType===Ks)return t.participant?.person?.sex;if(2===t.participant?.individualParticipants?.length){const e=m(t.participant.individualParticipants.map((t=>t.person?.sex))).filter(Boolean);if(1===e.length)return e[0]}}));if(2===t.filter(Boolean).length&&1===m(t).length){const e=t[0];St.inferredGender=e}}}if(St.tieMatchUps){const e=St.matchUpStatus===Ma,n=St.sides?.map((({participant:t,drawPosition:e,sideNumber:n,lineUp:r})=>{const i=t?.participantType===id&&t;return{teamParticipant:i&&vr({participantRoleResponsibilities:i.participantRoleResponsibilities,participantOtherName:i.participanOthertName,participantName:i.participantName,participantId:i.participantId,teamId:i.teamId}),drawPosition:e,sideNumber:n,lineUp:r}}));St.tieMatchUps=St.tieMatchUps.map((a=>{const o=St.matchUpId,c=St.finishingPositionRange;return mt({tieDrawPositions:q,scheduleVisibilityFilters:t,sourceDrawPositionRanges:r,sideLineUps:n,drawPositionsRanges:i,initialRoundOfPlay:s,roundNamingProfile:l,additionalContext:{finishingPositionRange:c,abbreviatedRoundName:ot,roundNumber:Y,roundName:at},appliedPolicies:y,isCollectionBye:e,usePublishState:T,publishStatus:P,matchUpTieId:o,isRoundRobin:A,roundProfile:E,matchUp:a,event:F})}))}const yt=St.sides&&2===St.sides.filter((t=>t?.participantId)).length,vt=!St.winningSide,wt=K&&yt&&vt;if(Object.assign(St,{readyToScore:wt,hasContext:!0}),yt){const{allParticipantsCheckedIn:t,checkedInParticipantIds:e}=Ku({matchUp:St});Object.assign(St,{allParticipantsCheckedIn:t,checkedInParticipantIds:e})}return Array.isArray(U?.exclude)&&U?.exclude.forEach((t=>delete St[t])),St}}function Kp({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:n,tournamentParticipants:r,afterRecoveryTimes:i,policyDefinitions:a,tournamentRecord:o,usePublishState:s,matchUpFilters:c,contextFilters:u,contextContent:d,participantMap:p,scheduleTiming:l,publishStatus:m,contextProfile:f,drawDefinition:h,exitProfiles:g,matchUpsMap:I,structureId:U,inContext:S,structure:y,context:v,event:w}){!y&&U&&({structure:y}=ts({drawDefinition:h,structureId:U}));const T=Yp({tournamentAppliedPolicies:n,scheduleVisibilityFilters:e,tournamentParticipants:r,afterRecoveryTimes:i,policyDefinitions:a,tournamentRecord:o,usePublishState:s,matchUpFilters:c,contextFilters:u,contextContent:d,participantMap:p,scheduleTiming:l,publishStatus:m,contextProfile:f,drawDefinition:h,exitProfiles:g,matchUpsMap:I,structure:y,inContext:S,context:v,event:w}),P=[],D=[],b=[],N=[],R=[];if(T.error)return T;const{matchUps:M}=T,{assignedPositions:A}=is({structure:y}),E=A?.filter((t=>t.participantId)).map((t=>t.drawPosition));let C;return M.filter((t=>{const e=1===c?.matchUpTypes?.length&&c.matchUpTypes[0]===Qs;return!(t.matchUpType!==Qs&&e)})).forEach((e=>{if(e.matchUpStatus===Na)return void P.push(e);e.matchUpType===Qs&&(C=!0);const n=e.collectionId,r=n&&e.sides?.every((t=>t.participantId)),i=!n&&2===e.drawPositions?.filter(Boolean).length,a=!n&&e.drawPositions?.every((t=>E?.includes(t))),o=A?.filter((t=>t.bye)).map((t=>t.drawPosition)),s=!n&&e.drawPositions?.find((t=>o?.includes(t))),c=Ja.includes(e.matchUpStatus)&&(r||i&&(!t||a));return s?R.push(e):Lc({matchUp:e})?D.push(e):c?b.push(e):N.push(e)})),{includesTeamMatchUps:C,abandonedMatchUps:P,completedMatchUps:D,upcomingMatchUps:b,pendingMatchUps:N,byeMatchUps:R,structure:y}}function Jp(t){Object.assign(t,{requireParticipants:!1});const e=Zp(t);if(e.error)return wr({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 Zp(t){if(!t?.drawDefinition)return{error:j};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:S,inContext:y,context:v,event:w}=t;let T,P=[],D=[],b=[],N=[],R=[];I&&!n&&(n=Fc({policyDefinitions:u,tournamentRecord:d,contextProfile:I,event:w})),!e?.length&&d&&(e=d?.participants,(y||s?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:T}=mc({participants:e,participantsProfile:s})));const{structures:M}=es({drawDefinition:U});if(!M)return{error:Ut};r||(r=xc({drawDefinition:U}));const A=U&&kc({drawDefinition:U}).exitProfiles;M.forEach((t=>{const{byeMatchUps:s=[],pendingMatchUps:T=[],upcomingMatchUps:M=[],completedMatchUps:E=[],abandonedMatchUps:C=[]}=Kp({matchUpFilters:S?void 0:m,contextFilters:S?void 0:l,inContext:y||S||l,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:t,context:v,event:w});P=P.concat(...C),D=D.concat(...E),b=b.concat(...M),N=N.concat(...T),R=R.concat(...s)}));const C=t=>m||S||l?(m&&(t=rp({matchUps:t,...m})),l&&(t=rp({matchUps:t,...l,processContext:!0})),t):t,O={abandonedMatchUps:C(P),completedMatchUps:C(D),upcomingMatchUps:C(b),pendingMatchUps:C(N),byeMatchUps:C(R),matchUpsMap:r,...E,groupInfo:T};if(S){const t="object"==typeof S||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:e,completed:n,upcoming:r,pending:i,bye:a}=t;wc({inContextDrawMatchUps:[].concat(...e&&P||[],...n&&D||[],...r&&b||[],...i&&N||[],...a&&R||[]),drawDefinition:U})}return O}function Xp({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:n,roundsCount:r,roundLimit:i,matchUps:a,lucky:o,fmlc:s}){if(!yc(a))return[];const{roundProfile:c,roundNumbers:u=[]}=vc({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(Ua("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=w(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=Qn({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 Qp({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:n}){if(!e)return{error:j};const r={loserMatchUpIds:{},winnerMatchUpIds:{}};t||({matchUps:t,matchUpsMap:n}=Jp({inContext:!0,drawDefinition:e,matchUpsMap:n}));const i=n?.drawMatchUps.some((t=>t.finishingPositionRange));if(!i&&1===e?.structures?.length&&!e?.structures[0].structures){Xp({matchUps:n?.drawMatchUps??[]})}return(t??[]).filter((({collectionId:t})=>!t)).forEach((i=>{const{matchUpId:a,structureId:o}=i,s=Uc({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:a}),{winnerMatchUp:c,loserMatchUp:u}=s.targetMatchUps,d=c?.matchUpId,p=u?.matchUpId,l=_c({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 tl(t){return t&&void 0!==String.fromCodePoint?t.toUpperCase().replace(/./g,(t=>String.fromCodePoint(t.charCodeAt(0)+127397))):t}const el=[{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 nl({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=el.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 rl(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:Ee}}function il({returnPreviousValues:t,itemSubTypes:e,itemType:n,element:r}){if(!r)return{error:ae,info:Tr};if(e&&!Array.isArray(e))return{error:Nn,context:{itemSubTypes:e}};if(!Array.isArray(r.timeItems))return{error:fn};const i=r.timeItems.filter((t=>t?.itemType===n)).filter((t=>!e?.length||e.some((e=>t?.itemSubTypes?.includes(e))))).sort(((t,e)=>new Date(t.createdAt||void 0).getTime()-new Date(e.createdAt||void 0).getTime())),a=i.pop();if(a){const e={timeItem:a,...E};return t&&Object.assign(e,{previousItems:i}),e}return{info:On}}function al({returnPreviousValues:t,itemSubTypes:e,itemType:n,event:r}){if(!r)return{error:Tt};if(!r.timeItems)return{info:On};const{timeItem:i,previousItems:a,info:o}=il({returnPreviousValues:t,element:r,itemSubTypes:e,itemType:n});return i&&{timeItem:i,previousItems:a}||{info:o}}function ol({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:n,itemType:r}){if(!e)return{error:_};if(!e.timeItems)return{info:On};const{timeItem:i,previousItems:a,info:o}=il({element:e,returnPreviousValues:t,itemSubTypes:n,itemType:r});return i&&{timeItem:i,previousItems:a}||{info:o}}const sl={[cc]:"groupParticipantIds",[uc]:"pairParticipantIds",[dc]:"teamParticipantIds"},cl={[cc]:"groups",[dc]:"teams"};function ul({withIndividualParticipants:t,convertExtensions:e,tournamentRecord:n,withSignInStatus:r,withScaleValues:i,internalUse:a,withISO2:o,withIOC:s}){const c={};for(const t of n.participants??[]){const e=t?.participantId;e&&ll({participantMap:c,participantId:e})}for(const t of n.participants??[]){const n=gi(t,e,a),{participantId:u,individualParticipantIds:d,participantType:p}=n;if(Object.assign(c[u].participant,n),d&&pl({individualParticipantIds:d,participantCopy:n,participantMap:c,participantType:p,participantId:u}),r&&(c[u].participant.signedIn=dl(n)),i){const{ratings:t,rankings:e,seedings:r}=xr({participant:n});c[u].participant.seedings=r,c[u].participant.rankings=e,c[u].participant.ratings=t}(s||o)&&nl({participant:c[u].participant,withISO2:o,withIOC:s})}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?_r({template:e,source:i}):i)}}}}({participantMap:c,template:ha(t)?t:void 0})}return{participantMap:c}}function dl(t){const{timeItem:e}=il({itemType:rc,element:t});return e?.itemValue===ac}function pl({individualParticipantIds:t,participantCopy:e,participantMap:n,participantType:r,participantId:i}){for(const a of t){const o=n[a].participant;if(o[sl[r]].push(i),[dc,cc].includes(r)){const{participantRoleResponsibilities:t,participantOtherName:n,participantName:i,participantId:a,teamId:s}=e;o[cl[r]].push({participantRoleResponsibilities:t,participantOtherName:n,participantName:i,participantId:a,teamId:s})}if(r===uc){const e=t.find((t=>t!==a));n[a].pairIdMap[i]=e,n[a].pairIdMap[e]=i}}}function ll({participantMap:t,participantId:e}){if(t[e])return;const n={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:{[Ks]:{...n},[Zs]:{...n},[dc]:{...n},...n}}}function ml({participantsProfile:t,useParticipantMap:e,tournamentRecord:n,contextProfile:r,inContext:i}){if(e){const e=ul({...t,...r,tournamentRecord:n})?.participantMap;return{participantMap:e}}let a,o=gi(n.participants,!1,!0)||[];if((t?.withIOC||t?.withISO2)&&o.forEach((e=>nl({participant:e,...t}))),(i||t?.withGroupings)&&o?.length&&({participantsWithGroupings:o,groupInfo:a}=mc({participantsProfile:t,deepCopy:!1,participants:o})),t?.withScaleValues&&o?.length)for(const t of o){const{ratings:e,rankings:n}=xr({participant:t});t.rankings=n,t.ratings=e}return{participants:o,groupInfo:a}}function fl(t){let{participants:e=[],contextContent:n,participantMap:r}=t;const{scheduleVisibilityFilters:i,tournamentAppliedPolicies:a,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:d,contextFilters:p,contextProfile:l,matchUpFilters:m,nextMatchUps:f,inContext:h,context:g,event:I}=t;if(!I)return{error:Tt};const{eventId:U,eventName:S,endDate:y,category:v,gender:w,matchUpFormat:T}=I,P={...g,...vr({indoorOutDoor:I.indoorOutdoor??d?.indoorOutdoor,surfaceCategory:I.surfaceCategory??d?.surfaceCategory,endDate:I.endDate??d?.endDate,tournamentId:d?.tournamentId,matchUpFormat:T,eventName:S,category:v,gender:w,eventId:U})};let D;if(y&&(P.endDate=y),l&&!n&&(n=Fc({policyDefinitions:c,tournamentRecord:d,contextProfile:l,event:I})),!e?.length&&!r&&d){const t=ml({participantsProfile:o,useParticipantMap:u,policyDefinitions:c,tournamentRecord:d,contextProfile:l,inContext:h});r=t.participantMap,e=t.participants??[],D=t.groupInfo}const b=I.drawDefinitions??[],N=Qu({tournamentRecord:d,event:I}).scheduleTiming;return{matchUps:b.flatMap((t=>{const{matchUps:u}=Jp({tournamentParticipants:e,tournamentAppliedPolicies:a,scheduleVisibilityFilters:i,context:P,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:d,contextFilters:p,contextProfile:l,drawDefinition:t,contextContent:n,matchUpFilters:m,participantMap:r,scheduleTiming:N,nextMatchUps:f,inContext:h,event:I});return u??[]})),groupInfo:D}}function hl(t){if(!t?.tournamentRecord)return{error:_};let{participantMap:e,participants:n}=t;const{scheduleVisibilityFilters:r,participantsProfile:i,afterRecoveryTimes:a,useParticipantMap:o,policyDefinitions:s,tournamentRecord:c,inContext:u=!0,contextProfile:d,matchUpFilters:p,contextFilters:l,nextMatchUps:m,context:f}=t,h=t.tournamentId??c.tournamentId,g=c?.events??[];n||({participants:n,participantMap:e}=ml({participantsProfile:i,useParticipantMap:o,policyDefinitions:s,tournamentRecord:c,contextProfile:d,inContext:u}));const{appliedPolicies:I}=Dc({tournamentRecord:c}),U={...f,tournamentId:h,indoorOutDoor:c.indoorOutdoor,surfaceCategory:c.surfaceCategory,endDate:c.endDate},S=Fc({policyDefinitions:s,tournamentRecord:c,contextProfile:d});return{matchUps:g.flatMap((t=>(U.eventDrawsCount=t.drawDefinitions?.length??0,fl({context:U,scheduleVisibilityFilters:r,tournamentAppliedPolicies:I,participantsProfile:i,afterRecoveryTimes:a,policyDefinitions:s,tournamentRecord:c,contextContent:S,contextFilters:l,contextProfile:d,matchUpFilters:p,participantMap:e,nextMatchUps:m,participants:n,inContext:u,event:t}).matchUps??[]))).concat(...c.matchUps??[])}}function gl({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:n,tournamentRecords:r,policyDefinitions:i,matchUpFilters:a,contextFilters:o,nextMatchUps:s,inContext:c}){if("object"!=typeof r||!Object.keys(r).length)return{error:x};return{matchUps:Object.keys(r).map((u=>{const d=r[u];return hl({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:n,policyDefinitions:i,tournamentRecord:d,matchUpFilters:a,contextFilters:o,nextMatchUps:s,inContext:c}).matchUps??[]})).flat()}}function Il(t,e){return function(t,e){return(io[t?.stage]||0)-(io[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 Ul(t){let{participants:e,participantMap:n,contextContent:r}=t;const{scheduleVisibilityFilters:i,tournamentAppliedPolicies:a,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:d,contextFilters:p,contextProfile:l,drawDefinition:m,matchUpFilters:f,nextMatchUps:h,inContext:g,context:I,event:U}=t,{eventId:S,eventName:y,eventType:v,category:w,gender:T,matchUpFormat:P}=U??{},D={...I,eventId:S,eventType:v,eventName:y,category:w,gender:T,matchUpFormat:P,indoorOutDoor:U?.indoorOutdoor??d?.indoorOutdoor,surfaceCategory:U?.surfaceCategory??d?.surfaceCategory,endDate:U?.endDate};let b;e?.length||n||!d||({participants:e=[],participantMap:n,groupInfo:b}=ml({participantsProfile:o,useParticipantMap:u,policyDefinitions:c,tournamentRecord:d,contextProfile:l,inContext:g})),l&&!r&&(r=Fc({policyDefinitions:c,tournamentRecord:d,contextProfile:l,drawDefinition:m,event:U}));return{...Jp({context:D,tournamentAppliedPolicies:a,scheduleVisibilityFilters:i,tournamentParticipants:e,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:d,drawDefinition:m,contextContent:r,contextFilters:p,contextProfile:l,matchUpFilters:f,participantMap:n,nextMatchUps:h,inContext:g,event:U}),groupInfo:b}}function Sl(t){let e=nc(t);const n=t.matchUps??[];let r=t.drawIds??[];const{includeParticipantDependencies:i,tournamentRecord:a,drawDefinition:o}=t;if(!Array.isArray(n))return{error:Ht};if(!Array.isArray(r))return{error:at};const s=t.matchUpIds?.length?t.matchUpIds:n.map((t=>t.matchUpId));if(!Array.isArray(s))return{error:$t};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)),[]).filter((({linkType:t})=>t===Uo));let f=n;if(m.length){f=gl({nextMatchUps:!0,tournamentRecords:e}).matchUps;const t=m.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 f??[]){const n=e.containerStructureId||e.structureId;t.includes(n)&&c[n].push(e.matchUpId)}}const h=t=>{u[t]||(u[t]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},p[t]=[])},g=(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)))},I=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(h(t),i){const{individualParticipantIds:e}=ec(n);u[t].participantIds=e}r&&(h(r),g(t,r),p[r].push(t)),a&&(h(a),g(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])h(e),g(e,t),p[e].push(t)}}}};if(o)Qp({drawDefinition:o}),f?.length||(f=Ul({drawDefinition:o}).matchUps),I(f);else{if(f?.length||(f=gl({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=f?.filter((e=>e.drawId===t)).sort(Il),r=n?.find((({roundPosition:t})=>!t));if(!r){const r=n?.find((({tournamentId:t})=>t)),{drawDefinition:i}=Vd({tournamentRecord:e[r?.tournamentId],drawId:t});i&&Qp({drawDefinition:i})}I(n)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:p,matchUps:f,...E}}function yl(t){const{drawDefinition:n,findContainer:r,structureId:i,event:a}=t;let o=t.structure;const{containedStructures:s}=qs({drawDefinition:n}),c=i&&s[i]||[];if(!o){const t=ts({drawDefinition:n,structureId:i});if(t.error)return t;o=r?t.containingStructure??t.structure:t.structure}if(ap({drawDefinition:n,structure:o}))return{structure:o,isAdHoc:!0,error:Q};const{matchUps:u}=Jp({inContext:!0,matchUpFilters:{isCollectionMatchUp:!1},drawDefinition:n,event:a}),d=u?.filter((t=>t.structureId===i||c.includes(t.structureId))),{matchUpDependencies:p}=Sl({drawIds:[n.drawId],matchUps:u,drawDefinition:n}),l=[],f=[],h={},g=[];for(const t of u??[]){if(t.structureId===i||c.includes(t.structureId)){f.push(...t.drawPositions??[]);const e=t.roundNumber;for(const n of(t.drawPositions??[]).filter(Boolean))(!h[n]||e&&h[n]>e)&&(h[n]=e)}zs(t)&&(g.push(t),l.push(t.matchUpId,...p?.[t?.matchUpId]?.matchUpIds||[]))}const I=m(f.filter(Boolean)).sort(e),U=m(l),S=m(d?.map((({matchUpId:t,drawPositions:e})=>U.includes(t)?e:[])).flat().filter(Boolean)).sort(e),{positionAssignments:y}=rs({drawDefinition:n,structure:o}),v=y?.filter((t=>t.bye)).map((t=>t.drawPosition)),w=y?.filter((t=>t.qualifier)).map((t=>t.drawPosition)),T=I?.filter((t=>!S.includes(t)))||[];return{allDrawPositions:I,inContextStructureMatchUps:d,drawPositionInitialRounds:h,activeDependentMatchUpIds:U,qualifyingDrawPositions:w,inactiveDrawPositions:T,positionAssignments:y,activeDrawPositions:S,byeDrawPositions:v,activeMatchUps:g,structure:o}}function vl({drawPosition:t,matchUps:n=[]}){return{initialRoundNumber:n.filter((({drawPositions:e})=>t&&e?.includes(t))).map((({roundNumber:t})=>t)).sort(e)[0]}}const wl={reset:"",bright:"",dim:"",red:"",brightred:"",green:"",brightgreen:"",yellow:"",brightyellow:"",blue:"",brightblue:"",lightblue:"",magenta:"",brightmagenta:"",cyan:"",brightcyan:"",white:"",brightwhite:""},Tl=[];function Pl(t,e){"string"==typeof t&&(t={method:t}),(e||Qn())&&Tl.push(t)}function Dl(t){const e=function(t){const e=Tl.slice();return t&&(Tl.length=0),e}(t),n=e.map((t=>{const{color:e,keyColors:n,method:r,newline:i}=t,a=Object.keys(wl).includes(e)?wl[e]:wl.cyan,o=Object.keys(t).filter((t=>!["color","keyColors","method","newline"].includes(t))).map((e=>{const r=n&&Object.keys(n).includes(e)&&wl[n[e]]?wl[n[e]]:wl.brightwhite;return`${wl.white}${e}: ${r}${t[e]}`})).join(", ");return[i?"\n":"",a,r,r?.length<15?"\t\t":"\t",wl.white,o,wl.reset,"\n"].join("")}));n?.length&&console.log(...n)}function bl({provisionalPositioning:t,isPositionAction:e,tournamentRecord:n,drawDefinition:r,drawPosition:i,matchUpsMap:a,structureId:o,structure:s,event:c}){if(!r)return{error:j};if(s||({structure:s}=ts({drawDefinition:r,structureId:o})),!s)return{error:Ut};o||({structureId:o}=s);const u="assignDrawPositionBye";Pl({method:u,color:"cyan",drawPosition:i}),a||(a=xc({drawDefinition:r}));const{positionAssignments:d}=rs({structure:s}),{activeDrawPositions:p}=yl({drawDefinition:r,structureId:o}),l=d?.find((t=>t.drawPosition===i));if(l?.bye)return{...E};const m=p?.includes(i);if(m)return{error:X};const f=d?.find((t=>t.drawPosition===i));if(!f)return{error:Q};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{...E};if(h&&!g)return wr({result:{error:z},stack:u});const U=Jp({inContext:!0,drawDefinition:r,matchUpsMap:a}).matchUps??[],{matchUps:S}=Yp({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)&&Rl({eventId:i?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:r})}))}({tournamentRecord:n,drawDefinition:r,drawPosition:i,matchUps:S}),Vs({tournamentId:n?.tournamentId,drawDefinition:r,structure:s,event:c}),Nl({assignedParticipantId:I,isPositionAction:e,drawDefinition:r,drawPosition:i,structureId:o,stack:u});const{roundProfile:y,roundMatchUps:v}=vc({matchUps:S}),w=y&&Object.keys(y).map((t=>parseInt(t))).reverse(),T=w?.find((t=>y?.[t].drawPositions?.includes(i))),P=T?v?.[T].find((({drawPositions:t})=>t?.includes(i))):void 0;P&&Rl({tournamentRecord:n,drawDefinition:r,matchUp:P,event:c});const D=P?.drawPositions?.find((t=>t!==i));if(P&&D){const t=Ml({sourceDrawPositions:P.drawPositions,matchUpId:P.matchUpId,inContextDrawMatchUps:U,drawPositionToAdvance:D,tournamentRecord:n,drawDefinition:r,matchUpsMap:a});if(t.error)return t}return Vs({tournamentId:n?.tournamentId,drawDefinition:r,structure:s,event:c}),Nl({assignedParticipantId:I,isPositionAction:e,drawDefinition:r,drawPosition:i,structureId:o,stack:u})}function Nl({assignedParticipantId:t,isPositionAction:e,drawDefinition:n,drawPosition:r,structureId:i,stack:a}){if(e){Gs({drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:r,structureId:i,name:a}})}return wr({result:{...E},stack:a})}function Rl({tournamentRecord:t,drawDefinition:e,eventId:n,matchUp:r,event:i}){Object.assign(r,{matchUpStatus:Ma,score:void 0,winningSide:void 0}),xs({tournamentId:t?.tournamentId,eventId:n??i?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:r})}function Ml({drawPositionToAdvance:t,inContextDrawMatchUps:n,sourceDrawPositions:r,tournamentRecord:i,drawDefinition:a,matchUpsMap:o,matchUpId:s,event:c}){Pl({method:"advanceDrawPosition",color:"cyan",drawPositionToAdvance:t});const u=o.drawMatchUps.find((t=>t.matchUpId===s)),d=n.find((t=>t.matchUpId===s)),p=d?.structureId,{structure:l}=ts({drawDefinition:a,structureId:p}),{positionAssignments:m}=rs({structure:l}),f=m?.filter((t=>t.bye)).map((t=>t.drawPosition)),h=u?.drawPositions?.find((e=>e!==t)),g=h&&f?.includes(h),{targetLinks:{loserTargetLink:I},targetMatchUps:{loserMatchUp:U,winnerMatchUp:S,loserTargetDrawPosition:y}}=Uc({inContextDrawMatchUps:n,drawDefinition:a,matchUpId:s});if(S&&S.structureId===l?.structureId&&function({drawPositionToAdvance:t,inContextDrawMatchUps:n,sourceDrawPositions:r,tournamentRecord:i,drawDefinition:a,winnerMatchUp:o,matchUpsMap:s,event:c}){const u="advanceWinner",d=s.drawMatchUps.find((t=>t.matchUpId===o.matchUpId)),p=n.find((t=>t.matchUpId===o.matchUpId)),l=p?.structureId,{structure:m}=ts({drawDefinition:a,structureId:l}),{positionAssignments:f}=rs({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))),S=f?.find((({drawPosition:e})=>e===t)),y=r?.find((e=>e!==t)),v=y&&U?.find((({drawPosition:t})=>t===y)),w=v?.bye,T=g&&w;T&&console.log({isByeAdvancedBye:T});if(I?.length>1&&g&&!w)return wr({result:{error:z},stack:u});const P=I?.find((e=>e!==t));let D=T;const b=[...(d.drawPositions||[]).filter(Boolean),void 0,void 0].slice(0,2),N=b.map((e=>!e&&!D||e===t?(D=!0,t):e)).sort(e);if(!D)return console.log("@@@@@@@",{advancingAssignmentIsBye:S,drawPositionToAdvance:t,existingAssignments:U}),wr({result:{error:z},stack:u});const R=f?.find((({drawPosition:t})=>t===P))?.bye,M=f?.find((({drawPosition:e})=>e===t))?.bye,A=M||R?Ma:ja;Object.assign(d,{matchUpStatus:A,score:void 0,winningSide:void 0,drawPositions:N});const E=d.drawPositions.find((t=>!b.includes(t)));Pl({method:u,color:"brightyellow",changedDrawPosition:E,pairedDrawPositionIsBye:R,drawPositionIsBye:M}),xs({tournamentId:i?.tournamentId,matchUp:d,eventId:c?.eventId,context:u,drawDefinition:a});const{targetLinks:{loserTargetLink:C},targetMatchUps:{loserMatchUp:O,loserTargetDrawPosition:F}}=Uc({matchUpId:o.matchUpId,inContextDrawMatchUps:n,drawDefinition:a});if(R||M){const e=R?t:P;if(e)Ml({drawPositionToAdvance:e,matchUpId:o.matchUpId,inContextDrawMatchUps:n,tournamentRecord:i,drawDefinition:a,matchUpsMap:s});else if(M&&C&&O)if(O.feedRound)Al({loserTargetDrawPosition:F,tournamentRecord:i,loserTargetLink:C,drawDefinition:a,loserMatchUp:O,matchUpsMap:s});else{const t=1-o.roundPosition%2,e=O.drawPositions[t],n=bl({structureId:C.target.structureId,drawPosition:e,tournamentRecord:i,drawDefinition:a,event:c});if(n.error);}}}({drawPositionToAdvance:t,inContextDrawMatchUps:n,sourceDrawPositions:r,tournamentRecord:i,drawDefinition:a,winnerMatchUp:S,matchUpsMap:o,event:c}),U&&g&&U.structureId!==l?.structureId){const{roundNumber:t}=U;if(1===t){const t=bl({structureId:I.target.structureId,drawPosition:y,tournamentRecord:i,drawDefinition:a,event:c});if(t.error)return t}else Al({loserTargetDrawPosition:y,tournamentRecord:i,loserTargetLink:I,drawDefinition:a,loserMatchUp:U,matchUpsMap:o,event:c})}return{...E}}function Al({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:n,drawDefinition:r,loserMatchUp:i,matchUpsMap:a,event:o}){const{roundNumber:s}=i;Pl({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});const c=(a?.mappedMatchUps||{})[i.structureId].matchUps,{initialRoundNumber:u}=vl({drawPosition:t,matchUps:c});if(u===s){const i=bl({structureId:n.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:r,event:o});if(i.error)return i}}function El({positionAssignments:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:r,structure:i,event:a}){const{matchUps:o}=Yp({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?Ma:ja;Object.assign(r,{matchUpStatus:t}),xs({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:a?.eventId,drawDefinition:n,matchUp:r})}}))}function Cl(t){let{inContextDrawMatchUps:e,participantId:n,drawPosition:r}=t;const{tournamentRecord:i,drawDefinition:a,structureId:o,matchUpsMap:s,event:c}=t,{structure:u}=ts({drawDefinition:a,structureId:o}),d=(is({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:tt};n||(n=d?.participantId);const{activeDrawPositions:p}=yl({drawDefinition:a,structureId:o});if(p.includes(r))return{error:X};e||({matchUps:e}=Jp({inContext:!0,drawDefinition:a,matchUpsMap:s}));return Ol({inContextDrawMatchUps:e,tournamentRecord:i,drawDefinition:a,structureId:o,drawPosition:r,matchUpsMap:s,event:c}).drawPositionCleared?(Vs({tournamentId:i?.tournamentId,drawDefinition:a,structure:u,event:c}),{...E,participantId:n}):{error:K}}function Ol({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:i,matchUpsMap:a,structureId:o,event:s}){const{structure:c}=ts({drawDefinition:r,structureId:o});if(!c)return{error:Ut};const u=is({drawDefinition:r,structure:c}).positionAssignments||[],d=u.some((t=>{if(t.drawPosition===i)return delete t.participantId,delete t.qualifier,delete t.bye,!0}));if(c.structureType===mo)return El({positionAssignments:u,tournamentRecord:e,drawDefinition:r,matchUpsMap:a,structure:c}),{drawPositionCleared:d,...E};const{matchUps:p}=Yp({drawDefinition:r,matchUpFilters:{isCollectionMatchUp:!1},matchUpsMap:a,structure:c,event:s}),{roundProfile:l,roundMatchUps:m}=vc({matchUps:p}),f=l&&Object.keys(l),h=f?.map((t=>n(t)));let g=i;const I=h?.map((t=>{const e=l?.[t],n=e?.pairedDrawPositions?.find((t=>t.includes(g))),r=n?.find((t=>t!==g)),i=u.find((t=>t.drawPosition===r)),a=l?.[t+1],o=i?.bye,s=a?.pairedDrawPositions?.find((t=>t.includes(r))),c=o&&s&&a&&a.drawPositions?.includes(r),d=n&&{pairedDrawPositionByeAdvancedPair:!c&&s,pairedDrawPosition:r,targetDrawPosition:g,relevantPair:n,roundNumber:t};return c&&(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:n,targetDrawPosition:d,relevantPair:p})=>{const l=m?.[n].find((t=>b(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}=ts({drawDefinition:r,structureId:o});if(!s)return{error:Ut};if(s.structureType===mo)return;i=i||xc({drawDefinition:r});const c=i?.mappedMatchUps||{},u=c[o].matchUps,{initialRoundNumber:d}=vl({drawPosition:e,matchUps:u}),p=u?.filter((t=>t.roundNumber>=a&&t.roundNumber!==d&&t.drawPositions?.includes(e))),l=rs({drawDefinition:r,structureId:o}).positionAssignments??[];p?.forEach((a=>Fl({drawPosition:e,targetMatchUp:a,inContextDrawMatchUps:t,positionAssignments:l,tournamentRecord:n,drawDefinition:r,matchUpsMap:i,structure:s})))}({inContextDrawMatchUps:t,targetDrawPosition:d,tournamentRecord:e,drawDefinition:r,structureId:o,roundNumber:n,matchUpsMap:a}),Fl({inContextDrawMatchUps:t,positionAssignments:u,tournamentRecord:e,drawDefinition:r,targetMatchUp:l,drawPosition:i,matchUpsMap:a,structure:c,event:s}))})),{tasks:U,drawPositionCleared:d,positionAssignments:u}}function Fl({inContextDrawMatchUps:t,positionAssignments:e,tournamentRecord:n,drawDefinition:r,targetMatchUp:i,drawPosition:a,matchUpsMap:o,structure:s,event:c}){const u="removeDrawPosition",d=i.drawPositions?.slice(),p=i.matchUpStatus,l=i.winningSide,m=(o=o??xc({drawDefinition:r})).mappedMatchUps[s.structureId].matchUps,{initialRoundNumber:f}=vl({drawPosition:a,matchUps:m});if(i.roundNumber&&f&&i.roundNumber>f){const t=(i.drawPositions??[]).map((t=>t===a?void 0:t));i.drawPositions=t}if(i.matchUpType===Qs){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,xs({tournamentId:n?.tournamentId,context:`${u}-TEAM`,eventId:c?.eventId,matchUp:i,drawDefinition:r}))}const h=Uc({matchUpId:i.matchUpId,inContextDrawMatchUps:t,drawDefinition:r}),{targetLinks:{winnerTargetLink:g},targetMatchUps:{loserMatchUp:I,winnerMatchUp:U,loserMatchUpDrawPositionIndex:S}}=h,y=e.filter((({drawPosition:t})=>i.drawPositions?.includes(t))).filter((t=>t.bye)).length,v=y&&Ma||i.matchUpStatus&&[Oa,Ga].includes(i.matchUpStatus)&&i.matcHUpStatus||2===i.drawPositions?.length&&ja||void 0;i.matchUpStatus=v,i.matchUpStatus&&[Ga,Oa].includes(i.matchUpStatus)&&(i.winningSide=void 0);const w=d?.find((t=>!i.drawPositions?.includes(t)));if(d?.includes(a)&&p===i.matchUpStatus&&l===i.winningSide||(w&&Pl({method:u,color:"brightyellow",removedDrawPosition:w}),xs({tournamentId:n?.tournamentId,eventId:c?.eventId,matchUp:i,context:`${u}-${a}`,drawDefinition:r})),I&&I.structureId!==h.matchUp.structureId&&!y){const{drawPositions:e,roundNumber:i}=I;if(1===i){const i=e[S];Ol({structureId:I.structureId,drawPosition:i,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:r,matchUpsMap:o})}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}=ts({structureId:i.structureId,drawDefinition:r}),{positionAssignments:c}=rs({structure:s}),u=c?.find((e=>e.drawPosition===t));if(u?.bye){const s=Cl({drawPosition:t,structureId:i.structureId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,matchUpsMap:a,event:o});if(s.error)return s}return{...E}}({loserMatchUpDrawPosition:i,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:r,loserMatchUp:I,matchUpsMap:o,event:c});if(a.error)return wr({result:a,stack:u});const s=(o?.mappedMatchUps||{})[I.structureId].matchUps,{initialRoundNumber:d}=vl({drawPosition:i,matchUps:s});1===d&&(Pl({method:u,color:"brightyellow",loserMatchUpDrawPosition:i}),Ol({structureId:I.structureId,drawPosition:i,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:r,matchUpsMap:o}))}}return U&&U.structureId!==h.matchUp.structureId&&g.target.feedProfile,{...E}}function kl({drawDefinition:t,stages:e}){if(!t)return{error:j};const n=m((t?.structures??[]).filter((t=>!e?.length||t.stage&&e.includes(t.stage))).map((t=>{const{positionAssignments:e}=rs({structure:t});return e?e.map(Ua("participantId")):[]})).flat().filter(Boolean));return{...E,assignedParticipantIds:n}}function xl(t){const e=(t?.entries??[]).filter(Boolean).reduce(((t,e)=>{const{entryStage:n,entryStatus:r}=e,i=`_${n||Xa}${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 _l(t){return[tu,Qc].includes(t)}function Ll({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:Te,method:"modifyEntriesStatus",participantIds:i};if(!r&&!p)return{error:Tt};if(a&&!su.includes(a))return{error:je};if(o&&!ro.includes(o))return{error:At};const l="modifyEntriesStatus",m=[];if(!a&&!s)return wr({result:{error:ae},info:"Missing entryStatus",stack:l});if(s&&!br({extension:s,requiredAttributes:["name"]}))return wr({result:{error:Nn},info:"Invalid extension",context:{extension:s},stack:l});const f=[];p?.drawDefinitions?.forEach((t=>{const e=kl({stages:d&&[d],drawDefinition:t}).assignedParticipantIds??[];f.push(...e)}));const h=n?.participants??[];if(!i.every((t=>{const e=Fi({tournamentParticipants:h,participantId:t})?.participantType;return!(e&&[uc,oc].includes(e)&&_l(a)||a&&p?.eventType&&e===sc&&[nd,ad].includes(p.eventType)&&[$c,...ru].includes(a))})))return{error:je};const g=p&&Bd({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)&&!(ru.includes(t.entryStatus)&&ru.includes(a)))(t)&&!e)&&(a&&(t.entryStatus=a,delete t.entryPosition),o&&(t.entryStage=o,delete t.entryPosition),s&&(s.value?Nr({element:t,extension:s}):Dr({element:t,name:s.name})),!0)))?{...E}:{error:Le}},S=({flight:t,drawDefinition:e})=>{p&&(p.entries=xl({entries:p.entries??[]})),t&&(t.drawEntries=xl({entries:t.drawEntries})),e&&(e.entries=xl({entries:e.entries}))},y=t=>{const{flight:e,drawDefinition:n}=t,r="updateDrawEntries";if(e){const t=U(e.drawEntries);if(t.error)return wr({result:t,stack:r})}if(n){const t=U(n.entries);if(t.error)return wr({result:t,stack:r});m.includes(n.drawId)||m.push(n.drawId)}return{...E}},v=p?.entries?.find((({entryPosition:t})=>t))??(I?.drawEntries?.find((({entryPosition:t})=>t))||r?.entries?.find((({entryPosition:t})=>t)));if(t&&!v&&S({flight:I,drawDefinition:r}),I||r){const t=y({flight:I,drawDefinition:r});if(t.error)return wr({result:t,stack:l})}const w=p?.drawDefinitions?.map((({drawId:t})=>t))??[],T=g?.flights?.filter((t=>!w.includes(t.drawId)))||[];for(const t of T){const e=t&&y({flight:t});if(e?.error)return wr({result:e,stack:l})}const P=1===g?.flights?.length&&(p?.drawDefinitions?.length??0)<=g?.flights?.length;if(!I&&!r&&a&&iu.includes(a))return{error:He};if(!I&&!r||a===nu||c&&P){const t=U(p?.entries);if(t?.error)return wr({result:t,stack:l});let e;if(a===nu&&(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 wr({result:{error:e},stack:l})}t&&S({flight:I,drawDefinition:r});for(const t of p?.drawDefinitions??[])m.length&&!m.includes(t.drawId)||Ls({tournamentId:n.tournamentId,eventId:p?.eventId,drawDefinition:t});return{...E}}function Bl(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===Ma||e[n].scheduleItems.push({...d,scheduledDate:ri(d?.scheduledDate),scheduledTime:ni(d?.scheduledTime),checkScoreHasValue:$s({score:l}),matchUpStatus:r,roundPosition:i,structureId:a,matchUpType:o,roundNumber:s,matchUpId:c,potential:u,drawId:p})}function Vl({requireTimeStamp:t,scaleAttributes:e,participant:n}){if(!n)return{error:Re};if(!ha(e))return{error:Nn};if(n.timeItems||(n.timeItems=[]),Array.isArray(n.timeItems)){const{accessor:r,scaleType:i,eventType:a,scaleName:o}=e,s=[Or,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))).pop();if(c){const[t,e,n,i]=c.itemType?.split(".")??[];if(t!==Or)return{error:In};const a=r&&la({element:c.itemValue,accessor:r}),o=a?.value||c.itemValue,s={eventType:n,scaleDate:c.itemDate,scaleValue:o,scaleName:i,scaleType:e};return{...E,scaleItem:s}}}return{...E,scaleItem:void 0}}function jl({publishedSeeding:t,usePublishState:e,withSeeding:n,participant:r,event:i}){const a={},o=t=>[Or,Fr,i.eventType,t].join("."),s=Object.assign({},...(r.timeItems||[]).filter((({itemType:t})=>t.split(".")[1]===Fr)).map((({itemType:t,itemValue:e})=>({[t]:e})))),c=(t?.stageSeedingScaleNames&&Object.values(t?.stageSeedingScaleNames)||Array.isArray(t?.seedingScaleNames)&&t.seedingScaleNames||[]).map(o),u=P(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=Vl({scaleAttributes:{eventType:i.eventType,scaleType:Fr,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 Gl({event:t,status:e=Hu}){const n=`${Wu}.${zu}`;return al({itemType:n,event:t})?.timeItem?.itemValue?.[e]}function ql({drawDetails:t,drawId:e}){const n=t?.[e]?.publishingDetail;return n?.published}function $l({event:t}){const e=Gl({event:t});if(e){const t={published:void 0,seedingScaleNames:[],drawIds:[]};e.seeding&&Object.assign(t,e.seeding);const{drawDetails:n,drawIds:r}=e;return{publishedDrawIds:n&&Object.keys(n).filter((t=>ql({drawDetails:n,drawId:t})))||r||[],publishedSeeding:t}}}function Wl({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({},...Ii(p)):{},m=Object.assign(l,{entryPosition:d,entryStatus:c,entryStage:u,ranking:o,eventId:a});n.events[a]=vr(m,!1,!1,!0),r&&(e&&(n.events[a].seedAssignments=e),i&&(n.events[a].seedValue=i))}function Hl(t,e){return(t||"").localeCompare(e||"")}function zl({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===Ga&&(f.walkoverWinCount+=1),i===Oa&&(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 Yl(t){const{withScheduleItems:e,scheduleAnalysis:n,withTeamMatchUps:r,participantMap:i,withOpponents:a,withMatchUps:o,withEvents:s,withDraws:c,finishingPositionRange:u,finishingRound:d,matchUpStatus:p,stageSequence:l,roundNumber:m,structureId:f,score:h,stage:g,withRankingProfile:I,tieWinningSide:U,roundPosition:S,matchUpTieId:y,matchUpSides:v,collectionId:w,matchUpType:T,winningSide:P,matchUpId:D,schedule:b,eventId:N,drawId:R,sides:M}=t,A=a&&2===M?.length&&Object.assign({},...M.map((({sideNumber:t},e)=>{const n=M[1-e].participantId;return t&&{[t]:n}})).filter(Boolean));for(const t of M){const{participantId:M,sideNumber:E,bye:C}=t;if(C)continue;const O=P===E,F=t=>{const e=i[t]?.participant,n=e?.participantType,r=[{participantId:t,participantType:n}];if(n!==oc)for(const t of e?.individualParticipantIds||[]){const e=i[t]?.participant;r.push({participantType:e?.participantType,participantId:t})}return r},k=(t,r)=>{if(o){if(i[t].matchUps[D]={participantWon:O,matchUpType:T,structureId:f,sideNumber:E,matchUpId:D,eventId:N,drawId:R,stage:g},a){const e=F(r);i[t].matchUps[D].opponentParticipantInfo=e}w&&(i[t].matchUps[D].collectionId=w)}a&&r&&(i[t].opponents[r]={participantId:r,matchUpId:D,eventId:N,drawId:R}),I&&zl({finishingPositionRange:u,participantMap:i,participantWon:O,finishingRound:d,matchUpStatus:p,participantId:t,stageSequence:l,roundNumber:m,structureId:f,matchUpId:D,drawId:R,stage:g}),(n||e)&&Bl({participantMap:i,participantId:t,matchUpStatus:p,roundPosition:S,matchUpType:T,roundNumber:m,structureId:f,matchUpId:D,schedule:b,drawId:R,score:h})},x=({participant:t,partnerParticipantId:e})=>{const n=(t,e)=>{t&&(t.partnerParticipantIds||(t.partnerParticipantIds=[]),t.partnerParticipantIds.includes(e)||t.partnerParticipantIds.push(e))};c&&n(t?.draws?.[R],e),s&&n(t?.events?.[N],e),o&&n(t?.matchUps?.[D],e)};if(M&&i[M]){const t=A?.[E];k(M,t);const e=i[M]?.participant.participantType===uc,n=i[M]?.participant.individualParticipantIds||[];if(y){if(r){const t=t=>i[t].matchUps[y]={participantWon:U===E,matchUpId:y,matchUpType:Qs,sideNumber:E};t(M),n.forEach(t)}if(c&&!i[M].draws[R]){const t=v.find((t=>t.sideNumber===E))?.participant?.participantId,e=i[t]?.draws?.[R]?.entryStatus,r=t=>i[t].draws[R]={entryStatus:e,eventId:N,drawId:R};r(M),n.forEach(r)}}if(e&&(n.forEach((e=>i[e]&&k(e,t))),n.forEach(((t,e)=>{const r=n[1-e],a=i[t];a&&x({participant:a,partnerParticipantId:r})})),s&&v)){const t=v.find((t=>t.sideNumber===E))?.participant?.participantId;if(t){const e=i[t]?.events[N];e?(i[M].events[N]={...e},n.forEach((t=>i[t].events[N]={...e}))):console.log("Missing teamEntry",{eventId:N,teamParticipantId:t})}}if(P){const t=t=>{O?(i[t].counters[T].wins+=1,i[t].counters.wins+=1,p===Ga&&(i[t].counters[T].walkoverWins+=1,i[t].counters.walkoverWins+=1),p===Oa&&(i[t].counters[T].defaultWins+=1,i[t].counters.defaultWins+=1)):(i[t].counters[T].losses+=1,i[t].counters.losses+=1,p===Ga&&(i[t].counters[T].walkovers+=1,i[t].counters.walkovers+=1),p===Oa&&(i[t].counters[T].defaults+=1,i[t].counters.defaults+=1))};t(M),n.forEach(t)}}}}function Kl({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:f,genders:h}=t,g=Jl(f)&&e?.events?.filter((t=>f?.includes(t.eventId)))||e?.events||[],I=i&&function({drawEntryStatuses:t,tournamentEvents:e}){const n=({entryStatus:e})=>!Array.isArray(t)||t.includes(e);return m(e.reduce(((t,e)=>{const{flightProfile:r}=Bd({event:e}),i=r?.flights?.map((({drawEntries:t})=>Array.isArray(t)?t.filter(n).map(Da):[])).flat()||[],a=e.drawDefinitions?.map((({entries:t})=>t?t.filter(n).map(Da):[]))||[];return t.concat(...i,...a)}),[]))}({drawEntryStatuses:i,tournamentEvents:g}),U=o&&function({eventEntryStatuses:t,tournamentEvents:e}){return m(e.reduce(((e,n)=>{const r=(n.entries||[]).filter((({entryStatus:e})=>!Array.isArray(t)||t.includes(e))).map(Da);return e.concat(...r)}),[]))}({eventEntryStatuses:o,tournamentEvents:g}),S=void 0!==a&&[!0,!1].includes(a)&&g.reduce(((t,e)=>t.concat(...(e.drawDefinitions||[]).map((t=>ns({drawDefinition:t}).allPositionedParticipantIds)).filter(Boolean))),[]),y=t=>r?.reduce(((e,n)=>{const{accessor:r,value:i}=n,{values:a}=la({element:t,accessor:r});return e&&a?.includes(i)}),!0);if(n=n?.filter((t=>{const e=il({element:t,itemType:rc})?.timeItem?.itemValue,{participantRoleResponsibilities:n,participantType:i,participantRole:o,participantId:m,person:f}=t,g=Array.isArray(h)&&h?.length&&f?.sex&&h.includes(f.sex);return l?h&&g||a&&S.includes(m)||!1===a&&!S.includes(m)||I?.includes(m)||U?.includes(m)||d?.includes(m)||p&&e===p||u&&i&&Jl(u)&&u.includes(i)||s&&o&&Jl(s)&&s.includes(o)||c&&Jl(n)&&Jl(c)&&c.find((t=>n?.includes(t)))||r?.length&&Jl(r)&&y(t):(!h||g)&&(void 0===a||a&&S.includes(m)||!1===a&&!S.includes(m))&&(!I||I.includes(m))&&(!U||U.includes(m))&&(!d||d.includes(m))&&(!p||e===p)&&(!u||i&&Jl(u)&&u.includes(i))&&(!s||o&&Jl(s)&&s.includes(o))&&(!c||Jl(n)&&Jl(c)&&c.find((t=>n?.includes(t))))&&(!r?.length||Jl(r)&&y(t))})),g.length&&f){const t=g.filter((t=>f.includes(t.eventId))).map((t=>{const n=(t.entries||[]).map((t=>t.participantId));if(t.eventType===td)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 Jl(t){return t&&Array.isArray(t)&&t.length}function Zl(t){const{withIndividualParticipants:e,participantFilters:n={},withPotentialMatchUps:r,withRankingProfile:i,convertExtensions:a,policyDefinitions:o,withScheduleItems:s,tournamentRecord:c,scheduleAnalysis:u,withSignInStatus:d,withTeamMatchUps:p,withScaleValues:l,usePublishState:f,contextProfile:h,withStatistics:g,withOpponents:I,withMatchUps:U,internalUse:S,withSeeding:y,withEvents:v,withDraws:w,withISO2:T,withIOC:P}=t;if(!c)return{error:_};(U||i)&&Sl({tournamentRecord:c});let{participantMap:D}=ul({convertExtensions:a,tournamentRecord:c,withSignInStatus:d,withScaleValues:l,internalUse:S,withISO2:T,withIOC:P});const b=function(t){const{participantFilters:e,convertExtensions:n,policyDefinitions:r,tournamentRecord:i,usePublishState:a,contextProfile:o,participantMap:s,withPotentialMatchUps:c,withRankingProfile:u,withScheduleItems:d,scheduleAnalysis:p,withTeamMatchUps:l,withStatistics:f,withOpponents:h,withMatchUps:g,withSeeding:I,withEvents:U,withDraws:S}=t,y=e?.participantIds,v=t=>{const e=[t];return s[t]?.participant.individualParticipantIds?.forEach((t=>e.push(t))),e.some((t=>!y?.length||y.includes(t)))?e:[]},w={withMatchUps:g||u,withEvents:U||u,withDraws:S||u,withPotentialMatchUps:c,withRankingProfile:u,withScheduleItems:d,scheduleAnalysis:p,withTeamMatchUps:l,withStatistics:f,participantMap:s,withOpponents:h,withSeeding:I},T=[],P={},D=[],b={},N={},R={},M=({eventType:t,scaleNames:e,participantId:n})=>s[n].participant?.rankings?.[t]?.find((t=>e.includes(t.scaleName)))?.scaleValue;for(const t of i?.events||[]){if(e?.eventIds&&!e.eventIds.includes(t.eventId))continue;const{drawDefinitions:y=[],extensions:T=[],eventType:A,eventName:E,category:C,entries:O,eventId:F,gender:k}=t,{flightProfile:x}=Bd({event:t}),_=x?.flights??[],L=$l({event:t}),B=L?.publishedSeeding;if(L&&(b[F]=L),U||I||u){const e=n?Object.assign({},...Ii(T)):{};N[F]={...e,eventName:E,eventType:A,category:C,eventId:F,gender:k};const r=[C?.categoryName,C?.ageCategoryCode].filter(Boolean);for(const e of O){const{participantId:i}=e;if(!i||!s[i])continue;const o=M({eventType:A,scaleNames:r,participantId:i});let c,u;if(I){const e=s[i].participant;({seedAssignments:c,seedValue:u}=jl({publishedSeeding:B,usePublishState:a,withSeeding:I,participant:e,event:t}))}const d=t=>{if(s[t]?.events?.[F])return;const r=s[t];Wl({convertExtensions:n,seedAssignments:c,participant:r,withSeeding:I,seedValue:u,eventId:F,ranking:o,entry:e})};d(i),(s[i].participant.individualParticipantIds||[]).forEach(d)}}const V=b?.[F]?.publishedSeeding;if(S||u||I){const t=t=>t?Object.assign({},...t.map((({participantId:t,seedValue:e,seedNumber:n})=>({[t]:{seedValue:e,seedNumber:n}})))):void 0,e=m([...y.map(Ua("drawId")),..._.map(Ua("drawId"))]);for(const n of e){const e=y.find((t=>t.drawId===n)),r=_?.find((t=>t.drawId===n)),i=e?.entries||r?.drawEntries,{structures:o=[],drawOrder:c,drawName:d,drawType:p}=e??{},l=r?.flightNumber,m=[C?.categoryName,C?.ageCategoryCode].filter(Boolean),f=(e?.structures||[]).sort(((t,e)=>Xo(t,e))).map((({structureId:t,structures:e})=>[t,...(e||[]).map((({structureId:t})=>t))])).flat(1/0);let h,g,U,v,w=0;const T=o.filter((({stage:t,stageSequence:e})=>t===Xa&&1===e||t===Qa)).flatMap((t=>{const{seedAssignments:e,stageSequence:n,stage:r}=t,{positionAssignments:i}=rs({structure:t});return r===Xa?(w=i?.length??0,U=i,v=e):1===n&&(h=i,g=e),i})).map((({participantId:t})=>t)).filter(Boolean),P=t(v),D=t(g),b=e?i.filter((({participantId:t})=>T.includes(t))):i,N=!a||V?.published&&(0===V?.drawIds?.length||V?.drawIds?.includes(n));for(const t of b){const{entryStatus:e,entryStage:r,entryPosition:i,participantId:a}=t,o=M({participantId:a,scaleNames:m,eventType:A}),c=t=>{if(s[t].draws?.[n])return;const c=I&&N,d=c?{}:void 0,p=c?P?.[a]?.seedValue||P?.[a]?.seedNumber:void 0,l=p?P?.[a]:void 0,m=c?D?.[a]?.seedValue||D?.[a]?.seedNumber:void 0,f=m?D?.[a]:void 0;d&&p&&(d[Xa]=l),d&&m&&(d[Qa]=f);const h=p||m;h&&(s[t].participant.seedings[A]||(s[t].participant.seedings[A]=[]),l&&s[t].participant.seedings[A].push({...l,scaleName:n}),f&&s[t].participant.seedings[A].push({...f,scaleName:n}),d&&(s[t].events[F].seedAssignments||(s[t].events[F].seedAssignments={}),Object.keys(d).forEach((e=>s[t].events[F].seedAssignments[e]=d[e])))),(S||u)&&(s[t].draws[n]=vr({seedAssignments:d,entryPosition:i,entryStatus:e,entryStage:r,seedValue:h,eventId:F,ranking:o,drawId:n},!1,!1,!0))};if(![Qc,tu].includes(e)){c(a);const t=s[a].participant.individualParticipantIds||[];t?.forEach(c)}}const E=(e?.structures??[]).reduce(((t,e)=>(t.includes(e.stage)||t.push(e.stage),t)),[]),O=(e?.links??[]).length;R[n]={qualifyingPositionAssignments:h,qualifyingSeedAssignments:g,mainPositionAssignments:U,qualifyingSeedingMap:D,mainSeedAssignments:v,orderedStructureIds:f,mainSeedingMap:P,flightNumber:l,linksCount:O,drawOrder:c,drawName:d,drawType:p,drawSize:w,drawId:n,stages:E}}}if(u||p||l||f||h||g||S){const e=!!p||c,n=fl({afterRecoveryTimes:!!p,policyDefinitions:r,tournamentRecord:i,inContext:!0,contextProfile:o,participantMap:s,nextMatchUps:e,event:t})?.matchUps??[];for(const t of n){const{finishingPositionRange:n,potentialParticipants:r,tieMatchUps:a=[],sides:o=[],winningSide:c,matchUpType:u,matchUpId:l,eventId:m,drawId:f,collectionId:h,stageSequence:g,finishingRound:I,matchUpStatus:U,roundPosition:S,roundNumber:y,structureId:T,schedule:D,score:b,stage:N}=t;P[l]=t;const R={finishingPositionRange:n,finishingRound:I,stageSequence:g,roundPosition:S,collectionId:h,roundNumber:y,structureId:T,schedule:D,eventId:m,drawId:f,score:b,stage:N};Yl({...R,...w,matchUpStatus:U,winningSide:c,matchUpType:u,matchUpId:l,sides:o});for(const t of a){const{winningSide:e,sides:n=[],matchUpId:r,matchUpStatus:i,matchUpType:a}=t;Yl({...R,...w,winningSide:e,tieWinningSide:c,matchUpTieId:l,matchUpId:r,sides:n,matchUpSides:o,matchUpStatus:i,matchUpType:a})}if(Array.isArray(r)&&(e||p||d)){const t=r.flat().map(Ua("participantId")).filter(Boolean);t?.forEach((t=>{const e=v(t);e?.forEach((t=>{s[t]&&(s[t].potentialMatchUps[l]=vr({tournamentId:i?.tournamentId,matchUpId:l,eventId:m,drawId:f}))})),(p||d)&&Bl({potential:!0,participantMap:s,participantId:t,matchUpStatus:U,roundPosition:S,structureId:T,matchUpType:u,roundNumber:y,matchUpId:l,schedule:D,drawId:f,score:b})}))}}D.push(...n)}}if(f||u||p){const t=Object.values(s);for(const e of t){const{wins:t,losses:n,[Ks]:{wins:r,losses:i},[Zs]:{wins:a,losses:o}}=e.counters,c=(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(f&&(c(Cc,t,n),c(`${Cc}.${Ks}`,r,i),c(`${Cc}.${Zs}`,a,o)),u){const t=(t=[])=>Math.abs(t[0]-t[1]);for(const n of Object.keys(e.draws)){const{orderedStructureIds:r=[],flightNumber:i}=R[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!==Qa;s&&(o+=1);const c=s?o:void 0;return vr({...r,participationOrder:c,flightNumber:i})})).filter(Boolean);e.draws[n]&&(e.draws[n].finishingPositionRange=a,e.draws[n].structureParticipation=s)}}}if(p){const t=ha(p)?p.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(si)));for(const a of n){const{typeChangeTimeAfterRecovery:n,timeAfterRecovery:o,scheduledDate:s,scheduledTime:c}=a,u=i[s],d=ti(c);for(const i of u){if(i.matchUpId===a.matchUpId||[Ga,Oa].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=ti(i.scheduledTime),l=Math.abs(p-d),m=p>=d;if((t&&!isNaN(t)?l<=t:m&&ti(i.scheduledTime)<ti(s))&&(!u||!c)&&m){const t=[a.matchUpId,i.matchUpId].sort(Hl).join("|");e.scheduleConflicts[t]={priorScheduledMatchUpId:a.matchUpId,matchUpIdWithConflict:i.matchUpId}}}}const a=e.participant.participantId;Object.keys(e.scheduleConflicts).length&&T.push(a),s[a].scheduleConflicts=e.scheduleConflicts}}}return{participantIdsWithConflicts:T,eventsPublishStatuses:b,derivedEventInfo:N,derivedDrawInfo:R,mappedMatchUps:P,participantMap:s,matchUps:D}}({withMatchUps:U??i,withEvents:v??i,withDraws:w??i,withPotentialMatchUps:r,participantFilters:n,withRankingProfile:i,convertExtensions:a,withScheduleItems:s,policyDefinitions:o,tournamentRecord:c,scheduleAnalysis:u,withTeamMatchUps:p,usePublishState:f,withStatistics:g,participantMap:D,withOpponents:I,contextProfile:h,withSeeding:y}),{participantIdsWithConflicts:N,eventsPublishStatuses:R,derivedEventInfo:M,derivedDrawInfo:A,mappedMatchUps:C}=b,O=b.matchUps;D=b.participantMap;const F=u??r,k=({potentialMatchUps:t,scheduleConflicts:e,scheduleItems:n,participant:r,statistics:a,opponents:o,matchUps:c,events:d,draws:p})=>{const l=Object.values(p),m=Object.values(o);return I&&l?.forEach((t=>{t.opponents=m.filter((e=>e.drawId===t.drawId))})),vr({...r,scheduleConflicts:u?Object.values(e):void 0,draws:w||i?l:void 0,events:v||i?Object.values(d):void 0,matchUps:U||i?Object.values(c):void 0,opponents:I?m:void 0,potentialMatchUps:F?Object.values(t):void 0,statistics:g?Object.values(a):void 0,scheduleItems:s?n:void 0},!1,!1,!0)},x=new Map;for(const t of Object.keys(D))x.set(t,k(D[t]));const L=[...x.values()],B=o?.[Di],V=B?.participant,j=Kl({participants:L,participantFilters:n,tournamentRecord:c});if(e){const t=ha(e)?e:void 0;for(const e of j)for(const n of e.individualParticipantIds??[]){e.individualParticipants||(e.individualParticipants=[]);const r=x.get(n);e.individualParticipants.push(t?_r({template:t,source:r}):r)}}return{participantIdsWithConflicts:N,eventsPublishStatuses:R,derivedEventInfo:M,derivedDrawInfo:A,mappedMatchUps:C,participantMap:D,participants:V?j.map((t=>_r({source:t,template:V}))):j,...E,matchUps:O}}function Xl({participantId:t,drawDefinition:e,entryStatus:n,entryStage:r}){if(!e)return{error:j};const i=e.entries?.find((e=>!(e.participantId!==t||n&&n!==e.entryStatus||r&&r!==e.entryStage)));return t&&i}function Ql(t){const{provisionalPositioning:e,drawDefinition:n,stageSequence:r,structureId:i,stage:a}=t;if(!n)return{error:j};const{entryProfile:o}=qc({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}=ts({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=ts({structureId:t.source.structureId,drawDefinition:n})?.structure;if(r?.stage===Qa){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=Yp({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 tm({stage:t,drawDefinition:e}){const{entryProfile:n}=qc({drawDefinition:e});return n?.[t]?.drawSize||0}function em({stage:t,drawDefinition:e}){return Boolean(t===eo||uu({stage:t,drawDefinition:e})&&tm({stage:t,drawDefinition:e}))}function nm({entryStatus:t=Hc,drawDefinition:e,stageSequence:n,stage:r}){if(t===$c)return function({stage:t,drawDefinition:e}){const{entryProfile:n}=qc({drawDefinition:e});return n[t]?.alternates||0}({stage:r,drawDefinition:e})?{positionsAvailable:1/0,...E}:{error:We};const i=function(t){const{provisionalPositioning:e,drawDefinition:n,stageSequence:r,stage:i}=t,a=tm({stage:i,drawDefinition:n}),{qualifiersCount:o}=Ql({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}=qc({drawDefinition:e});return n[t]?.wildcardsCount||0}({drawDefinition:e,stage:r}),o=du({entryStatus:eu,drawDefinition:e,stage:r}),s=o+du({entryStatus:Hc,drawDefinition:e,stage:r}),c=i-s;return r!==eo&&s>=i?{error:ze}:t===eu?o<a?{...E}:{error:ze}:{positionsAvailable:c,...E}}function rm(t){const{entryStatus:e=Hc,entryStageSequence:n,entryStage:r=Xa,ignoreStageSpace:i,drawDefinition:a,entryPosition:o,participant:s,roundTarget:c,extensions:u,extension:d,drawType:p}=t,l="addDrawEntry";if(!a)return{error:j};if(!r)return{error:Mt};if(p!==wo&&!em({stage:r,drawDefinition:a}))return wr({result:{error:At},stack:l});const m=nm({stageSequence:n,stage:r,drawDefinition:a,entryStatus:e});if(!i&&!m.success)return{error:m.error};if(d&&!br({extension:d}))return wr({result:{error:Nn},info:"Invalid extension",context:{extension:d},stack:l});const f=t.participantId||s?.participantId;if(!f)return wr({result:{error:Ae},stack:l});const h=e===Kc&&Xl({participantId:f,drawDefinition:a,entryStatus:e}),g=r===eo&&Xl({participantId:f,drawDefinition:a,entryStage:r}),I=e!==Kc&&r!==eo&&Xl({drawDefinition:a,participantId:f});if(I||h||g)return wr({context:{invalidEntry:I,invalidLuckyLoser:h,invalidVoluntaryConsolation:g},result:{error:Be},stack:l});const U=vr({entryStageSequence:n,participantId:f,entryPosition:o,entryStatus:e,entryStage:r,extensions:u});return d&&Nr({element:U,extension:d}),c&&Nr({extension:{name:"roundEntry",value:c},element:U}),a.entries||(a.entries=[]),a.entries.push(U),Ls({drawDefinition:a}),{...E}}function im({autoEntryPositions:t=!0,entryStageSequence:e,ignoreStageSpace:n,drawDefinition:r,participantIds:i,entryStatus:a,roundTarget:o,entryStage:s,extension:c,drawId:u,event:d}){if(!i?.length)return{error:Fe};if(!d)return{error:Pt};if(!u)return{error:at};const p=(d.entries||[]).map(Da);if(i.filter((t=>!p.includes(t))).length)return{error:bt};if(r){const u=function(t){const{entryStatus:e=Hc,stage:n=Xa,autoEntryPositions:r=!0,ignoreStageSpace:i,drawDefinition:a,participantIds:o,stageSequence:s,roundTarget:c,extension:u}=t;if(!n)return{error:Mt};if(!a)return{error:j};if(!Array.isArray(o))return{error:Pe};if(!em({stage:n,drawDefinition:a}))return{error:At};if(u&&!br({extension:u}))return wr({result:{error:Nn},info:"Invalid extension",context:{extension:u},stack:"addDrawEntries"});const d=nm({drawDefinition:a,stageSequence:s,entryStatus:e,stage:n});if(!i&&!d.success)return{error:d.error};const p=d.positionsAvailable??0;if(!i&&n!==eo&&p<o.length)return{error:Ve};const l=o.reduce(((t,r)=>{const i=e===Kc&&Xl({participantId:r,drawDefinition:a,entryStatus:e}),o=n===eo&&Xl({entryStage:n,drawDefinition:a,participantId:r});return e!==Kc&&n!==eo&&Xl({drawDefinition:a,participantId:r})||i||o?t.concat(r):t}),[]);return o.filter((t=>t&&!l.includes(t))).forEach((t=>{const r={entryStageSequence:s,entryStage:n,participantId:t,entryStatus:e};u&&Nr({element:r,extension:u}),c&&Nr({extension:{name:ra,value:c},element:r}),a.entries||(a.entries=[]),a.entries.push(r)})),r&&(a.entries=xl({entries:a.entries})),Ls({drawDefinition:a}),l?.length?{info:"some participantIds could not be added",participantIdsNotAdded:l,...E}:{...E}}({stageSequence:e,autoEntryPositions:t,stage:s,ignoreStageSpace:n,drawDefinition:r,participantIds:i,entryStatus:a,roundTarget:o,extension:c});if(u.error)return u}const{flightProfile:l}=Bd({event:d}),m=l?.flights.find((t=>t.drawId===u));return m?.drawEntries&&(i.forEach((t=>{const e=a===Kc&&am({participantId:t,entryStatus:a,flight:m}),n=s===eo&&am({participantId:t,entryStage:s,flight:m});a!==Kc&&s!==eo&&am({flight:m,participantId:t})||e||n||m.drawEntries.push({participantId:t,entryStatus:a,entryStage:s})})),t&&(m.drawEntries=xl({entries:m.drawEntries}))),{...E}}function am({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 om({autoEntryPositions:t=!0,participantIds:e=[],entryStatuses:n,stage:r,event:i}){const a="removeEventEntries";if(!i?.eventId)return{error:Tt};if(!Array.isArray(e)||e.some((t=>!fa(t))))return wr({result:{error:Te},stack:a});const o=(i.drawDefinitions??[]).flatMap((t=>kl({drawDefinition:t}).assignedParticipantIds??[])),s=(n?.length&&i.entries?.filter((t=>t.entryStatus&&n.includes(t.entryStatus)))||[]).map(Ua("participantId")).filter((t=>!o.includes(t))),c=(r&&i.entries?.filter((t=>t.entryStage&&t.entryStage===r))||[]).map(Ua("participantId")).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=P(s,c):s.length?e=s:c.length&&(e=c),e?.length&&o.some((t=>e.includes(t))))return wr({result:{error:Le},stack:a});if(!e?.length)return{...E,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=xl({entries:i.entries}));const{flightProfile:d}=Bd({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)))})),{...E,participantIdsRemoved:u}}const sm={[wi]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}};function cm(t){const{entryStatus:e=Hc,autoEntryPositions:n=!0,enforceGender:r=!0,participantIds:i=[],entryStageSequence:a,policyDefinitions:o,entryStage:s=Xa,tournamentRecord:c,ignoreStageSpace:u,drawDefinition:d,roundTarget:p,extensions:l,extension:m,drawId:f,event:h}=t,g="addEventEntries";if(!h)return{error:Tt};if(!i?.length)return wr({result:{error:Fe},stack:g});if(!h?.eventId)return{error:Pt};const I=Dc({tournamentRecord:c,event:h}).appliedPolicies??{},U=o?.[wi]??I?.[wi]??sm[wi],S=!1!==(r??U?.participants?.enforceGender),y=[],v=[];if(l&&(!Array.isArray(l)||!l.every((t=>br({extension:t}))))||m&&!br({extension:m}))return wr({context:vr({extension:m,extensions:l}),result:{error:Nn},info:"Invalid extension(s)",stack:g});const w=!!c,T=[];let P;const D=c?.participants?.filter((t=>{if(!i.includes(t.participantId))return!1;const n=h.eventType===Ks&&t.participantType===sc&&!_l(e),r=h.eventType===Zs&&t.participantType===uc;return!(!n||h.gender&&S&&![$p,Gp].includes(h.gender)&&h.gender!==t.person?.sex)||(!(!r||_l(e))||(!(h.eventType!==Zs||t.participantType!==sc||!_l(e))||(n&&h.gender&&S&&![$p,Gp].includes(h.gender)&&h.gender!==t.person?.sex?(T.push({participantId:t.participantId,sex:t.person?.sex}),!1):h.eventType===dc&&(t.participantType===dc||_l(e)&&t.participantType===sc))))})).map((t=>t.participantId))??[],b=i.filter((t=>!w||D.includes(t)));h.entries||(h.entries=[]);const N=h.entries.map((t=>t.participantId||t.participant?.participantId));if(b.forEach((t=>{if(!N.includes(t)){const n=vr({participantId:t,entryStatus:e,entryStage:s,extensions:l});m&&Nr({element:n,extension:m}),p&&Nr({extension:{name:ra,value:p},element:n}),a&&(n.entryStageSequence=a),y.push(n.participantId),h.entries?.push(n)}})),f&&!_l(s)){const t=im({participantIds:b,autoEntryPositions:n,entryStageSequence:a,ignoreStageSpace:u,drawDefinition:d,entryStatus:e,roundTarget:p,entryStage:s,extension:m,drawId:f,event:h});t.error&&(P=t.error)}if(h.eventType&&[rd,ad].includes(h.eventType)){const t=(h.entries||[]).map((t=>t.participantId)),e=(h.entries||[]).filter((t=>_l(t.entryStatus))).map((t=>t.participantId)),n=(c?.participants??[]).filter((e=>t.includes(e.participantId)&&e.participantType&&[uc,dc].includes(e.participantType))).map((t=>t.individualParticipantIds)).flat(1/0),r=e.filter((t=>n.includes(t)));r.length&&(v.push(...r),om({participantIds:r,autoEntryPositions:!1,event:h}))}if(b.length!==i.length)return wr({context:{mismatchedGender:T,gender:h.gender},result:{error:Pe},stack:g});n&&(h.entries=xl({entries:h.entries||[]}));const R=y.length-v.length;return wr({result:{...E,addedEntriesCount:R},stack:g,info:P})}const um="COMPETITOR",dm="OFFICIAL",pm="OTHER",lm={ADMINISTRATION:"ADMINISTRATION",CAPTAIN:"CAPTAIN",COACH:"COACH",COMPETITOR:um,MEDIA:"MEDIA",MEDICAL:"MEDICAL",OFFICIAL:dm,OTHER:pm,SECURITY:"SECURITY"};function mm({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:n,tournamentRecord:r,suppressErrors:i}){const a="removeIndividualParticipantIds";if(!r)return wr({result:{error:_},stack:a});if(!n||!e)return wr({result:{error:ae},stack:a});const o=(r.participants??[]).find((t=>t.participantId===n));if(!o)return wr({result:{error:Ee},stack:a});if(![dc,cc].includes(o.participantType))return wr({result:{participantType:o.participantType,error:be},stack:a});const s=fm({individualParticipantIds:e,groupingParticipant:o,tournamentRecord:r,suppressErrors:i}),{removed:c,error:u}=s;if(u)return wr({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)));cm({participantIds:n,entryStatus:Qc,tournamentRecord:r,event:t})}}return c&&sr({topic:Ss,payload:{tournamentId:r.tournamentId,participants:[o]}}),{...E,...s}}function fm({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}=Zl({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||$s({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}=Mr({element:i,name:Zi}),a=t?.value[e.participantId];t&&a&&(t.value[e.participantId]=a.filter((t=>t.participantId!==r)),Nr({element:i,extension:t}),_s({drawDefinition:i}));const o=Ul({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)),xs({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:ye}||l}function hm({participantRole:t=um,individualParticipantIds:e=[],groupingTypes:n=[oc,cc],tournamentRecord:r}){if(!r)return{error:_};const i=r.participants??[],{participants:a,mappedMatchUps:o}=Zl({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}=fm({groupingParticipant:t,individualParticipantIds:e,tournamentRecord:r,mappedMatchUps:o,participants:a});n&&s++})),s?E:{error:Oe}}function gm(t){if(!t?.tournamentRecord)return{error:_};if(!t?.participantIds?.length)return{error:Fe};const{addIndividualParticipantsToEvents:e,tournamentRecord:n,participantIds:r}=t,i=n.participants?.length||0;if(!i)return{...E};const a=(n.events||[])?.filter((({eventType:t})=>t===id)).map((t=>t?.drawDefinitions?.map((({drawId:t})=>t)))).flat(1/0),o=Zl({participantFilters:{participantIds:r},tournamentRecord:n,withDraws:!0}).participants??[],s=a?.length&&P((hl({matchUpFilters:{drawIds:a,matchUpTypes:[Zs]},tournamentRecord:n}).matchUps??[]).map((({sides:t})=>t?.map((({participantId:t})=>t)))).flat().filter(Boolean),r),c=o.filter((t=>t.draws?.filter((t=>(!a?.length||!a?.includes(t.drawId))&&t.positionAssignments)).length));if(s?.length||c.length)return{error:Le};const u={},d={};for(const t of n.events||[]){const e=om({participantIds:r,event:t});if(e.error)return e;u[t.eventId]=e.participantIdsRemoved}n.participants=n.participants.filter((t=>{const n=r.includes(t.participantId)||t.participantType===uc&&t.individualParticipantIds.some((t=>r.includes(t)));if(!n&&t.participantType===id&&t.individualParticipantIds.some((t=>r.includes(t)))&&(t.individualParticipantIds=t.individualParticipantIds.filter((t=>!r.includes(t)))),n&&e&&[uc,dc].includes(t.participantType))for(const e of t.individualParticipantIds||[])r.includes(e)||(d[t.participantId]||(d[t.participantId]=[]),d[t.participantId].push(e));return!n}));const p=i-n.participants.length;if(hm({individualParticipantIds:r,tournamentRecord:n}),e)for(const t of n.events||[]){cm({participantIds:u[t.eventId].map((t=>d[t]||[])).flat(),entryStatus:Qc,tournamentRecord:n,event:t})}return p&&sr({payload:{participantIds:r,tournamentId:n.tournamentId},topic:ps}),p?{...E,participantsRemovedCount:p}:{error:ye}}function Im({selected:t=!0,drawDefinition:e,entryStatuses:n,drawId:r,event:i,stage:a}){let o=i.entries??[];if(r){const{flightProfile:t}=Bd({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&&ou.includes(e.entryStatus))));return{entries:o,stageEntries:s}}function Um({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:i,stage:a,event:o}){const s="destroyGroupEntry";if(!e)return{error:_};if(!r)return wr({result:{error:Ae},stack:s});if(!o)return{error:Tt};if(!o.eventType||![rd,ad].includes(o.eventType))return wr({result:{error:wt},stack:s});const c=e.participants??[],u=c.find((t=>t.participantId===r));if(!u)return wr({result:{error:Ee},stack:s});if(!u.participantType||![uc,oc].includes(u.participantType)||u.participantType===oc&&o.eventType!==ad||u.participantType===uc&&o.eventType!==rd)return{error:be};const d=(o.entries??[]).find((t=>t.participantId===r));if(!d)return{error:Ge};const{stageEntries:p}=Im({selected:!1,drawDefinition:n,drawId:i,event:o,stage:a}),l=p.map(Da),m=c.filter((({participantId:t})=>l.includes(t))).map((({individualParticipantIds:t})=>t)).flat().filter(Boolean),f=u.individualParticipantIds?.filter((t=>1===T(t,m).length));let h,g=om({participantIds:[r],event:o});if(g.error)return g;if(f?.length&&(g=cm({participantIds:f,entryStatus:Qc,entryStage:d.entryStage,tournamentRecord:e,drawDefinition:n,drawId:i,event:o}),g.error))return g;if(t){gm({participantIds:[r],tournamentRecord:e}).success&&(h=!0)}return{...E,participantRemoved:h}}function Sm({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:i,event:a}){return Um({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:i,event:a})}function ym(t){const{tournamentRecord:e,replaceWithBye:n,drawDefinition:r,destroyPair:i,entryStatus:a,matchUpsMap:o,drawId:s}=t,c="removeDrawPositionAssignment",u=Cl(t);if(u.error)return wr({result:u,stack:c});const{participantId:d}=u,{drawPosition:p,event:l,structureId:m}=t;if([$c,nu].includes(a)&&d){const{tournamentRecord:e}=t,{participant:n}=rl({tournamentRecord:e,participantId:d}),{participantType:o,individualParticipantIds:u}=n??{};if(i&&o===uc){const t=Sm({tournamentRecord:e,drawDefinition:r,participantId:d,event:l});if(t.error)return wr({result:t,stack:c});u&&Ll({participantIds:u,tournamentRecord:e,drawDefinition:r,entryStatus:a,drawId:s,event:l})}else Ll({participantIds:[d],tournamentRecord:e,drawDefinition:r,entryStatus:a,drawId:s,event:l})}if(n){const t=bl({tournamentRecord:e,drawDefinition:r,drawPosition:p,structureId:m,matchUpsMap:o,event:l});if(t.error)return wr({result:t,stack:c})}const{structure:f}=ts({drawDefinition:r,structureId:m});js({structure:f,drawPositions:[p]});return Gs({drawDefinition:r,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:n,drawPosition:p,entryStatus:a,structureId:m}}),u}function vm(t){return fa(t)?t.split(" ").map((t=>t.split("").map(((t,e)=>e?t.toLowerCase():t.toUpperCase())).join(""))).join(" "):t}function wm(t){return fa(t)?vm(t.replace(/_/g," ")):t}const Tm=({finishingPosition:t=Ko,qualifyingRoundNumber:e,structureAbbreviation:n,seedAssignments:r=[],stageSequence:i=1,structureOrder:a,seedingProfile:o,matchUpFormat:s,structureType:c,structureName:u,matchUpType:d,matchUps:p=[],structureId:l,roundOffset:f,roundLimit:h,stageOrder:g,structures:I,stage:U})=>{const S={structureId:l??Md(),structureAbbreviation:n,finishingPosition:t,seedAssignments:r,matchUpFormat:s,stageSequence:i,structureName:u};a&&(S.structureOrder=a),c&&(S.structureType=c),o&&("string"==typeof o?S.seedingProfile=o:"object"==typeof o&&"string"==typeof o.positioning&&(S.seedingProfile=o.positioning)),d&&(S.matchUpType=d),f&&(S.roundOffset=f),g&&(S.stageOrder=g),h&&(S.roundLimit=h),U&&(S.stage=U),e&&(S.qualifyingRoundNumber=e);const y=p.flatMap((({drawPositions:t})=>t)).filter(Boolean);return I?S.structures=I:(S.matchUps=p,S.positionAssignments=m(y).sort(((t,e)=>t-e)).map((t=>({drawPosition:t})))),S};function Pm({structureName:t=wm(eo),structureAbbreviation:e,drawDefinition:n,matchUpType:r,structureId:i}){if(!n)return{error:j};const a=Tm({stage:eo,structureAbbreviation:e,structureName:t,matchUps:[],structureId:i,matchUpType:r});return n.structures||(n.structures=[]),n.structures.push(a),Ls({drawDefinition:n,structureIds:[a.structureId]}),{...E}}function Dm({tournamentRecord:t,drawDefinition:e,stage:n=Xa,structureId:r,structure:i}){if(!t)return{error:_};if(!i&&!e)return{error:j};if(i||r||1!==e?.structures?.filter((t=>t.stage===n)).length||(i=e.structures.find((t=>t.stage===n))),!i&&!r)return{error:It};const{error:a,positionAssignments:o}=rs({drawDefinition:e,structureId:r,structure:i});return{positionAssignments:o??[],structureId:i?.structureId,error:a}}function bm({schedulingProfile:t,venueIds:e,eventIds:n,drawIds:r}){const i=[],a=t?.map((t=>{const a=ri(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 Nm({tournamentRecords:t,schedulingProfile:e}){if(!e)return{valid:!0};if(!Array.isArray(e))return{valid:!1,error:Nn};const{venueIds:n,tournamentsMap:i}=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]={};(e?.events||[]).forEach((t=>{const e=t.eventId;o.push(e),n[u][e]={},(t.drawDefinitions||[]).forEach((t=>{const r=t.drawId;s.push(r),n[u][e][r]={};const{structures:i}=es({drawDefinition:t});(i||[]).forEach((t=>{const i=t.structureId,{matchUps:o}=Yp({structure:t}),{roundMatchUps:s}=vc({matchUps:o}),c=s&&Object.keys(s).map((t=>parseInt(t)));n[u][e][r][i]=c,a.push(i),t.structures?.length&&t.structures.forEach((t=>{a.push(t.structureId),n[u][e][r][t.structureId]=c}))}))}))}))}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 a,o;const s=e.every((t=>{const{scheduleDate:e,venues:s}=t;return!!Wr(e)&&s.every((t=>{const{venueId:e,rounds:s}=t;if("string"!=typeof e)return o="venueId should be a string",!1;if(!Array.isArray(s))return o="rounds should be an array",!1;if(!n.includes(e))return a=rn,!1;return!!s.every((t=>{if(!t)return o="empty round",!1;const{roundSegment:e,tournamentId:n,structureId:a,roundNumber:s,eventId:c,drawId:u}=t,d=i?.[n]?.[c]?.[u]?.[a],l=d?.includes(s);l||(o="Invalid rounds");const{segmentNumber:m,segmentsCount:f}=e||{},h=!e||p(m)&&r(f)&&m<=f;return h||(o="Invalid segment"),l&&h}))}))}));return s||a||(a=Nn),{valid:!!s,error:a,info:o}}function Rm({convertExtensions:t,ignoreDisabled:e,venue:n,court:r}){const i={...gi(r,t,!0),venueId:n.venueId},{extension:a}=Mr({name:$i,element:r});if(e&&a){const t=ha(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 Mm({dates:t=[],extension:e}){if(!e)return!1;if("boolean"==typeof e.value&&e.value)return!0;if(!t.length)return!1;const n=ha(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 Am(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}=Mr({name:$i,element:t});if(e?.value)continue}o.includes(t.venueId)||(u.push(gi(t,e,!0)),o.push(t.venueId));for(const r of t.courts??[])if(!s.includes(r.courtId)){if(n){const{extension:t}=Mr({name:$i,element:r});if(Mm({extension:t,dates:i}))continue}const{inContextCourt:a}=Rm({convertExtensions:e,ignoreDisabled:n,venue:t,court:r});c.push(a),s.push(r.courtId)}}})),{courts:c,venues:u,...E}}function Em({tournamentRecords:t,requireCourts:e,dates:n}){if("object"!=typeof t||!Object.keys(t).length)return{error:x};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:x};const i=gi(e.venues??[],t).filter((t=>{if(!n)return t;const{extension:e}=Mr({name:$i,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}=Mr({name:$i,element:t});return Mm({extension:e,dates:r})})).filter(Boolean).map((e=>{const{inContextCourt:r}=Rm({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 Cm(t){const e=Lp(t,[{[sp]:!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 Om({tournamentRecords:t,tournamentRecord:e}){if("object"!=typeof t||!Object.keys(t).length)return{error:x};const{extension:n}=Mr({element:e,name:oa,tournamentRecords:t,discover:!0});let r=n?.value||[];if(r.length){const{venueIds:n}=Em({requireCourts:!0,tournamentRecords:t}),{eventIds:i,drawIds:a}=Cm({tournamentRecords:t}),{updatedSchedulingProfile:o,modifications:s,issues:c}=bm({schedulingProfile:r,venueIds:n,eventIds:i,drawIds:a});if(s){r=o;const n=Fm({tournamentRecords:t,tournamentRecord:e,schedulingProfile:r});return n.error?n:{schedulingProfile:r,modifications:s,issues:c}}}return{schedulingProfile:r,modifications:0}}function Fm({tournamentRecords:t,tournamentRecord:e,schedulingProfile:n}){const r=Nm({tournamentRecords:t,schedulingProfile:n});if(r.error)return r;if(!n)return Dr({element:e,name:oa,tournamentRecords:t,discover:!0});return Nr({tournamentRecords:t,discover:!0,extension:{name:oa,value:n}})}function km(t){const{tournamentRecord:e}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!t.schedulingProfile){const{modifications:t,issues:r}=Om({tournamentRecords:n,tournamentRecord:e});return{success:!t,modifications:t,issues:r}}const{venueIds:r}=Em({tournamentRecords:n}),{eventIds:i,drawIds:a}=Cm({tournamentRecords:n}),{updatedSchedulingProfile:o,modifications:s,issues:c}=bm({schedulingProfile:t.schedulingProfile,venueIds:r,eventIds:i,drawIds:a});return s?{...Fm({schedulingProfile:o,tournamentRecords:n}),modifications:s,issues:c}:{...E,modifications:s,issues:c}}function xm(t){const{duplicateValues:e=!0,creationTime:n=!0,removePriorValues:r,timeItem:i,element:a}=t;if(!i)return{error:mn};if(!a)return{error:ae,info:Tr};const o=i&&Object.keys(i),s=["itemType","itemValue"];if(!(s.filter((t=>o.includes(t))).length===s.length))return{error:pn};if(a.timeItems){const{itemType:t,itemSubTypes:n,itemValue:r}=i,o=t&&il({itemSubTypes:n,itemType:t,element:a})?.timeItem;if(o&&JSON.stringify(o?.itemValue)===JSON.stringify(r)&&!e)return{...E}}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),{...E}}function _m({creationTime:t=!0,removePriorValues:e,tournamentRecord:n,duplicateValues:r,participantId:i,timeItem:a}){if(!n)return{error:_};if(!i)return{error:Ae};const o=rl({tournamentRecord:n,participantId:i});return o.error?o:xm({element:o.participant,removePriorValues:e,duplicateValues:r,creationTime:t,timeItem:a})}function Lm(t){const{removePriorValues:e,tournamentRecord:n,duplicateValues:r,creationTime:i,timeItem:a}=t;return n?xm({element:n,removePriorValues:e,duplicateValues:r,creationTime:i,timeItem:a}):{error:_}}function Bm(t){const{removePriorValues:e,duplicateValues:n,creationTime:r,timeItem:i,event:a}=t;return a?xm({removePriorValues:e,duplicateValues:n,element:a,creationTime:r,timeItem:i}):{error:Pt}}function Vm({removePriorValues:t=!0,status:e=Hu,statusObject:n,event:r}){if(!ha(n))return{error:Nn};const i=Gl({event:r,status:e}),a=`${Wu}.${zu}`;return Bm({timeItem:{itemValue:{[e]:{...i,...n}},itemType:a},removePriorValues:t,event:r})}function jm({tournamentRecord:t}){if(!t)return{error:_};const e=(({tournamentId:t,tournamentRank:e,tournamentStatus:n,formalName:r,tournamentName:i,promotionalName:a,onlineResources:o,localTimeZone:s,startDate:c,endDate:u,hostCountryCode:d,tournamentContacts:p,tournamentAddresses:l})=>({tournamentId:t,tournamentRank:e,tournamentStatus:n,formalName:r,tournamentName:i,promotionalName:a,onlineResources:o,localTimeZone:s,startDate:c,endDate:u,hostCountryCode:d,tournamentContacts:p,tournamentAddresses:l}))(t);return{...E,tournamentInfo:gi(e,!1,!0)}}function Gm({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[Io,go,ho,po].includes(t.target.feedProfile)?(r?.targets.push(n),s?.sources.push(e)):t.target.feedProfile===fo&&(s?.drawSources.push(e),r?.drawTargets.push(n)),o[n]=o[n]||t.target.feedProfile===fo,a[n]=m([...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===Qa){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;w(0,Math.ceil(u/2)).forEach((()=>{s=w(0,u).map((t=>{const e=s[t],n=s.reduce(((t,n)=>b(e,n)?t.concat(...n):t),[])||[];return m(e.concat(...n))}))}));const d=s[0],p=s.slice(1).reduce(((t,e)=>{return t&&P(n=e,d).length===n.length;var n}),!0),l=[d].filter(Boolean),f=[d].filter(Boolean);e.forEach((t=>{const{structureId:e,stage:n}=t;l.find((t=>t.includes(e)))||(l.push([e]),n!==eo&&f.push([e]))}));const h=p&&1===f.length;return n?.length||1!==e.length||i(e[0].structureId),{structureProfiles:Object.fromEntries(r),allStructuresLinked:h,maxQualifyingDepth:c,sourceStructureIds:a,hasDrawFeedProfile:o,structureGroups:l}}function qm(t){const{tournamentParticipants:e=[],includePositionAssignments:n,policyDefinitions:r,tournamentRecord:i,inContext:a=!0,usePublishState:o,drawDefinition:s,publishStatus:c,noDeepCopy:u,sortConfig:d,context:p,event:l}=t;if(!s)return{error:j};const m=(({matchUpFormat:t,updatedAt:e,drawType:n,drawName:r,drawId:i})=>({matchUpFormat:t,updatedAt:e,drawName:r,drawType:n,drawId:i}))(s);let f,h;const{allStructuresLinked:g,sourceStructureIds:I,hasDrawFeedProfile:U,structureGroups:S}=Gm({drawDefinition:s});if(!g)return{error:vt};let y=!1,v=!1;const w=S.map((t=>{const u={},g=t.map((t=>{const{structure:e}=ts({drawDefinition:s,structureId:t}),{seedAssignments:n}=lu({drawDefinition:s,structure:e});return e?.stage===Xa&&1===e.stageSequence&&(f=n),e?.stage===Qa&&1===e.stageSequence&&(h=n),e})).sort(((t,e)=>Xo(t,e,d))).map((t=>{if(!t)return;const n=t?.structureId;let d=[];t.stage&&[Xa,to,no].includes(t.stage)&&(d=f),t?.stage===Qa&&(d=h);const{matchUps:g,roundMatchUps:S,roundProfile:w}=Yp({seedAssignments:t?.seedAssignments?.length?void 0:d,context:{drawId:m.drawId,...p},tournamentParticipants:e,policyDefinitions:r,tournamentRecord:i,usePublishState:o,publishStatus:c,drawDefinition:s,inContext:a,structure:t,event:l}),{positionAssignments:T}=rs({structure:t}),P=T?.filter(Ua(lp)).map((t=>{v=!0;const{drawPosition:e,participantId:n}=t,{extension:r}=Mr({element:t,name:ca});return r&&{drawPosition:e,participantId:n,participantResult:r.value}})).filter((t=>t?.participantResult)),D=t?(({stageSequence:t,structureName:e,structureType:n,matchUpFormat:r,stage:i})=>({stageSequence:t,structureName:e,structureType:n,matchUpFormat:r,stage:i}))(t):{};D.sourceStructureIds=I[n],D.hasDrawFeedProfile=U[n],D.positionAssignments=T,D.structureActive=g.reduce(((t,e)=>{const n=[Ea,Aa,Oa,Ba,Ga,xa,Fa,ka].includes(e.matchUpStatus);return t||n||!!e.winningSide||!!e.score?.scoreStringSide1}),!1);const b=g.reduce(((t,e)=>t&&[Ma,Ea,Ba,Ga,Oa,Na].includes(e.matchUpStatus)),!!g.length);return D.structureCompleted=b,u[n]=b,D.structureActive&&(y=!0),{...D,participantResults:P,seedAssignments:d,roundMatchUps:S,roundProfile:w,structureId:n}}));return g.forEach((t=>{n||delete t.positionAssignments,t.sourceStructuresComplete=t.sourceStructureIds?.every((t=>u[t]))})),g})).flat();return m.drawActive=y,m.participantPlacements=v,m.drawGenerated=w?.reduce(((t,e)=>t||!!e?.roundMatchUps),!1),m.drawCompleted=w?.reduce(((t,e)=>t&&e.structureCompleted),!0),{structures:u?w:gi(w,!1,!0),drawInfo:u?m:gi(m,!1,!0),...E}}function $m(t){const{includePositionAssignments:e,tournamentRecord:n,participantsProfile:r,policyDefinitions:i,usePublishState:a,status:o=Hu,sortConfig:s,event:c}=t,u=gi(n,!1,!0),d=gi(c,!1,!0);if(!u)return{error:_};if(!d)return{error:Tt};const{eventId:l}=d,{tournamentId:m,endDate:f}=u,h=Gl({event:d,status:o}),{participants:g}=Zl({withGroupings:!0,withEvents:!1,withDraws:!1,...r,tournamentRecord:u}),I=(d.drawDefinitions||[]).filter((({drawId:t})=>!a||(h.drawDetails?h.drawDetails[t]?.publishingDetail?.published:!h.drawIds||h.drawIds.includes(t)))).map((t=>(({drawInfo:t,structures:e})=>({...t,structures:e}))(qm({context:{eventId:l,tournamentId:m,endDate:f},includePositionAssignments:e,tournamentParticipants:g,noDeepCopy:!0,policyDefinitions:i,tournamentRecord:u,usePublishState:a,drawDefinition:t,publishStatus:h,sortConfig:s,event:d})))).map((({structures:t,...e})=>{const n=t?.filter((({stage:t,structureId:n})=>(({structureId:t,drawId:e})=>{if(!a)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(!a)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(!a)return e;const n=h?.drawDetails?.[t]?.structureDetails?.[e.structureId]?.roundLimit;if(p(n)){const t=w(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)),{tournamentInfo:U}=jm({tournamentRecord:u}),S={tournamentInfo:U,venuesData:(u.venues||[]).map((t=>(({venueData:t})=>({...t}))(kd({tournamentRecord:u,venueId:t.venueId})))),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})=>({eventId:t,eventName:e,eventType:n,eventLevel:r,surfaceCategory:i,matchUpFormat:a,category:o,gender:s,startDate:c,endDate:u,ballType:d,discipline:p}))(d),drawsData:I};return S.eventInfo.publish=h,{...E,eventData:S}}function Wm(t){const{includePositionAssignments:e,removePriorValues:n,tournamentRecord:r,status:i=Hu,event:a,drawIdsToRemove:o,drawIdsToAdd:s}=t;if(!r)return{error:_};if(!a)return{error:Tt};const{appliedPolicies:c}=Dc({tournamentRecord:r,event:a}),u={...c,...t.policyDefinitions},d=a.drawDefinitions?.map((({drawId:t})=>t))??[],p=t.drawDetails?Object.keys(t.drawDetails):[],l=p.length?[]:t.drawIds,m=(s??[]).concat(...o??[],...l??[],...p),f=m.filter((t=>!d.includes(t)));if(f.length)return wr({result:{error:q},context:{invalidDrawIds:f}});const h=Gl({event:a,status:i}),g=h?.drawDetails||{};for(const e of d)if(m.length&&!m.includes(e)||(o?.includes(e)||l?.length&&!l.includes(e)?g[e]={...g[e],publishingDetail:{published:!1}}:(s?.includes(e)||l?.includes(e)||!l?.length)&&(g[e]={...g[e],publishingDetail:{published:!0}})),t.drawDetails?.[e]){const n=t.drawDetails[e];let r=n.structureDetails??g[e].structureDetails;const i=n.stageDetails??g[e].stageDetails??{},{structureIdsToRemove:o=[],structureIdsToAdd:s=[],publishingDetail:c={},stagesToRemove:u=[],stagesToAdd:d=[]}=n;if((s||d)&&(c.published=!0),g[e]={publishingDetail:c,structureDetails:r,stageDetails:i},s.length||o.length){const t=(a.drawDefinitions?.find((t=>t.drawId===e))?.structures??[]).map((({structureId:t})=>t)),n=(s??[]).concat(o??[]).filter((e=>!t.includes(e)));if(n.length)return wr({result:{error:Ut},context:{invalidStructureIds:n}});r=r??{};for(const e of t)o.includes(e)?r[e]={published:!1}:r[e]={published:!0};g[e].structureDetails=r}const p=(a.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)&&(g[e].stageDetails=i)}Vm({statusObject:{drawDetails:g},removePriorValues:n,status:i,event:a});const{eventData:I}=$m({includePositionAssignments:e,usePublishState:!0,tournamentRecord:r,policyDefinitions:u,event:a});return sr({payload:{eventData:I,tournamentId:r.tournamentId},topic:Ds}),{...E,eventData:I}}const Hm="deleteDrawDefinitions",zm="autoSchedulingAudit",Ym="deleteEvents",Km={AUTO_SCHEDULING_AUDIT:zm,DELETE_EVENTS:Ym,DELETE_DRAW_DEFINITIONS:Hm};function Jm(t){if(!t.tournamentRecord)return{error:_};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}=Dc({tournamentRecord:a,event:r}),d={...u,...t.policyDefinitions},p=Array.isArray(n)?n[0]:void 0;if(!r){const t=Vd({tournamentRecord:a,eventId:s,drawId:p});if(t.error)return t;r=t.event}const l=[],m=[],f=[];if(!r?.drawDefinitions)return wr({info:"event has no drawDefinition",result:{...E},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 wr({info:"nothing to do; no matching drawIds in event.",result:{...E},stack:e});const g=gi(Bd({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?.[Mi]?.allowDeletionWithScoresPresent?.drawDefinitions,S=Gl({event:r})??{};let y,v=S.drawIds??(S.drawDetails&&Object.keys(S.drawDetails))??[];const w=[],T=r.drawDefinitions.filter((t=>{if(n.includes(t.drawId)){const e=Ul({event:r,drawDefinition:t})?.matchUps??[];if(e.some((({score:t})=>$s({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=>ou.includes(t.entryStatus)))),v.includes(n)&&(v=v.filter((t=>t!==n)),y=!0);const d=es({stageSequence:1,drawDefinition:t,stage:Xa})?.structures?.[0],p=d?Dm({structureId:d.structureId,tournamentRecord:a,drawDefinition:t}):void 0,h=p?.positionAssignments?.map(I),S=es({stage:Qa,drawDefinition:t})?.structures,T=S?.length?S.map((e=>{const n=e.stageSequence,r=Dm({structureId:e.structureId,tournamentRecord:a,drawDefinition:t}),i=r?.positionAssignments.map(I);return{positionAssignments:i,stageSequence:n}})):void 0,P={action:Hm,payload:{drawDefinitions:[t],eventId:s??r?.eventId,auditData:o}};f.push(P),l.push(vr({tournamentId:a.tournamentId,eventId:s??r?.eventId,qualifyingPositionAssignments:T,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 wr({context:{drawIdsWithScoresPresent:w},result:{error:qn},stack:e});if(r.drawDefinitions=T,g){_i({event:r,extension:{name:Ki,value:g}})}if(km({tournamentRecord:a}),y){const t={};for(const e of v)t[e]=S.drawDetails?.[e]??{published:!0};const e=Vm({statusObject:{drawDetails:t},event:r});if(e.error)return{error:e.error}}if(f.length&&sr({topic:ds,payload:f}),m.length&&ks({tournamentId:a?.tournamentId,matchUpIds:m}),n.forEach((t=>{!function({tournamentId:t,eventId:e,drawId:n}){sr({payload:{drawId:n,tournamentId:t,eventId:e},topic:ms,key:n}),dr({key:n})}({drawId:t})})),function({event:t,deletedDrawsDetail:e,auditData:n}){const{extension:r}=Mr({name:zi,element:t}),i={...n,deletedDrawsDetail:e},a={name:zi,value:Array.isArray(r?.value)?r?.value.concat(i):[i]};Nr({element:t,extension:a})}({event:r,deletedDrawsDetail:l,auditData:o}),i&&y){const t=Wm({drawIdsToRemove:n,policyDefinitions:d,tournamentRecord:a,event:r});if(t.error)return{...E,info:t.error}}return{...E}}function Zm({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find((t=>t.matchUpId===e))}}function Xm({tournamentParticipants:t,afterRecoveryTimes:e,contextContent:n,contextProfile:r,drawDefinition:i,matchUpsMap:a,matchUpId:o,inContext:s,context:c,event:u}){if(!i)return{error:j};if(!o)return{error:qt};if("string"!=typeof o)return{error:Nn};const{structures:d=[]}=es({drawDefinition:i});r&&!n&&(n=Fc({contextProfile:r,drawDefinition:i}));for(const p of d){const{matchUps:d}=Yp({tournamentParticipants:t,afterRecoveryTimes:e,contextContent:n,drawDefinition:i,contextProfile:r,matchUpsMap:a,inContext:s,structure:p,context:c,event:u}),{matchUp:l}=Zm({matchUps:d,matchUpId:o});if(l)return{matchUp:l,structure:p}}return{error:Wt}}function Qm(t){let{sourceMatchUp:e}=t;const{targetMatchUp:n,structure:r,matchUpsMap:i,drawPosition:a}=t,o=n.roundNumber>1&&n.roundNumber-1,s=_c({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:[ka,Fa].includes(p)}}function tf({structureId:t,matchUpsMap:e,matchUp:n}){const r=n?.roundPosition,i=r+(r%2?1:-1);return{pairedPreviousMatchUp:_c({matchUpsMap:e,structureId:t}).find((({roundNumber:t,roundPosition:e})=>t===n?.roundNumber&&e===i))}}function ef({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:n,matchUpsMap:r,matchUp:i}){const a=t.find((t=>t.matchUpId===n)),{pairedPreviousMatchUp:o}=tf({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=fa(t)||!isNaN(t)?{code:t}:t;return n.sideNumber===s?{...n,previousMatchUpStatus:e}:n}))}}function nf({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 rf({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}=Mr({element:i,name:Zi}),d=gi((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)}xs({tournamentId:r?.tournamentId,context:"updateSidLineUp",eventId:o?.eventId,drawDefinition:i,matchUp:a})}function af({inContextDrawMatchUps:t,sourceMatchUpStatus:n,tournamentRecord:r,sourceMatchUpId:i,drawDefinition:a,matchUpStatus:o,drawPosition:s,matchUpsMap:c,matchUpId:u,event:d}){const p="assignMatchUpDrawPosition";c||(c=xc({drawDefinition:a})),t||(t=Jp({inContext:!0,drawDefinition:a,matchUpsMap:c}).matchUps??[]);const l=t.find((t=>t.matchUpId===u)),m=l?.structureId,f=a?.structures?.find((t=>t.structureId===m));if(!f)return{error:Ut};const h=c?.drawMatchUps?.find((t=>t.matchUpId===u)),g=h?.drawPositions??[],{positionAdded:I,positionAssigned:U,updatedDrawPositions:S}=function({drawPosition:t,drawPositions:n}){let r=!1,i=!!n?.includes(t);return{updatedDrawPositions:i?n||[]:[...n,void 0,void 0].slice(0,2).map((e=>e||i?e:(i=!0,r=!0,t))).sort(e).filter(Boolean),positionAdded:r,positionAssigned:i}}({drawPosition:s,drawPositions:g}),{positionAssignments:y}=rs({drawDefinition:a,structure:f}),v=y?.filter((t=>S.includes(t.drawPosition))),w=v?.find((({bye:t})=>t)),T=h?.matchUpStatus&&[Ga,Oa].includes(h.matchUpStatus)&&S.filter(Boolean).length<2;if(o=w&&Ma||o||T&&h.matchUpStatus||h?.matchUpStatus&&[ka,Fa].includes(h.matchUpStatus)&&h.matchUpStatus||ja,h&&I){t=Jp({inContext:!0,drawDefinition:a,matchUpsMap:c}).matchUps??[];const e=T&&nf({inContextDrawMatchUps:t,drawPosition:s,matchUpId:u})||void 0;h?.matchUpStatusCodes&&ef({inContextDrawMatchUps:t,sourceMatchUpStatus:n,sourceMatchUpId:i,matchUpsMap:c,matchUp:h}),Object.assign(h,{drawPositions:S,winningSide:e,matchUpStatus:o}),xs({tournamentId:r?.tournamentId,eventId:l?.eventId,context:p,drawDefinition:a,matchUp:h})}const P=Uc({inContextDrawMatchUps:t,inContextMatchUp:l,drawDefinition:a,matchUpId:u}),{targetMatchUps:{winnerMatchUp:D,loserMatchUp:N,loserTargetDrawPosition:R},targetLinks:{loserTargetLink:M}}=P,A=_c({structureId:f.structureId,matchUpsMap:c});if(U&&w){if(D)if([Ma,ka,Fa].includes(o)){const e=af({matchUpId:D.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:a,drawPosition:s,matchUpsMap:c});if(e.error)return e}else{const{structureId:t}=D;t!==f.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(D&&l&&!l.feedRound){const{pairedPreviousMatchUpIsDoubleExit:e}=Qm({targetMatchUp:h,drawPosition:s,matchUpsMap:c,structure:f});if(e){const e=af({matchUpId:D.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:a,drawPosition:s,matchUpsMap:c});if(e.error)return e}}if(h?.matchUpType===Qs){const e=t?.find((({matchUpId:t})=>t===h.matchUpId)),n=(e?.sides??[]).reduce(((t,e,n)=>e.drawPosition===s?n:t),void 0),i=y?.find((t=>t.drawPosition===s))?.participantId;i&&void 0!==n&&rf({inContextTargetMatchUp:e,drawPositionSideIndex:n,teamParticipantId:i,tournamentRecord:r,drawDefinition:a,matchUp:h})}if(M?.linkCondition===vo&&2===S.filter(Boolean).length&&!w){if(A.filter((({drawPositions:t,roundNumber:e})=>1===e&&b(t,S))).every((({matchUpStatus:t})=>[Ea,Ba].includes(t)))&&N){const{structureId:t}=N,e=bl({drawPosition:R,tournamentRecord:r,drawDefinition:a,structureId:t,matchUpsMap:c,event:d});if(e.error)return e}}return U?{...E}:wr({result:{error:z},context:{drawPosition:s},stack:p})}function of(t){if(!t)return 1/0;if(p(t))return n(t);const e=t.split("-")[0];return p(e)?n(e):1/0}function sf({drawPositions:t}){const e=[].concat(...t.map((e=>t.filter((t=>t!==e)).map((t=>[e,t]))))),n=m(e.map(cf)).map((t=>t.split("|").map((t=>+t))));return{groupMatchUps:e,uniqueMatchUpGroupings:n}}function cf(t){return[...t].sort(e).join("|")}function uf({groupSize:t,drawPositionOffset:e}){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=>cf(t.map((t=>t+e)))))))}const df={getRoundRobinGroupMatchUps:sf,determineRoundNumber:function({rounds:t,hash:e}){return t.reduce(((t,n,r)=>n.includes(e)?r+1:t),void 0)},drawPositionsHash:cf,groupRounds:uf};function pf(t){const{groupNameBase:e="Group",playoffAttributes:n,stageSequence:r=1,structureOptions:i,appliedPolicies:a,seedingProfile:o,stage:s=Xa,matchUpType:c,roundTarget:u,structureId:d,groupNames:p,drawSize:l,idPrefix:m,isMock:f,uuids:h}=t,g=t.structureName??n?.[0]?.name??wm(Xa),{groupCount:I,groupSize:U}=function({appliedPolicies:t,structureOptions:e,drawSize:n}){let r=e?.groupSize;const i=e?.groupSizeLimit||8,{validGroupSizes:a}=lf({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:i,appliedPolicies:a,drawSize:l}),S=Yo;let y;const v=w(1,I+1).map((t=>{const n=function({structureOrder:t,matchUpType:e,groupSize:n,drawSize:r,idPrefix:i,isMock:a,uuids:o}){const s=(t-1)*n,c=w(1+s,n+1+s),{uniqueMatchUpGroupings:u}=sf({drawPositions:c}),d=uf({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(cf(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()||Md()}({structureOrder:t,drawPositions:n,roundNumber:s,idPrefix:i,uuids:o}),d={matchUpStatus:s?ja:Ma,matchUpType:e,finishingPositionRange:{winner:c,loser:c},drawPositions:n,roundNumber:s,matchUpId:u};return a&&(d.isMock=!0),d}}({groupSize:U,structureOrder:t,matchUpType:c,drawSize:l,idPrefix:m,isMock:f});y=Math.max(...n.map((({roundNumber:t})=>t)));const r=p?.[t-1]??`${e} ${t}`;return Tm({structureId:h?.pop(),structureType:lo,finishingPosition:S,structureOrder:t,structureName:r,matchUps:n})})),T=Tm({structureId:d??h?.pop(),structureType:mo,finishingPosition:S,seedingProfile:o,structureName:g,stageSequence:r,structures:v,stage:s});return u&&Nr({extension:{name:ra,value:u},element:T}),{structures:[T],maxRoundNumber:y,groupCount:I,links:[],groupSize:U,...E}}function lf({drawSize:t,groupSizeLimit:e=10}){const n=w(3,e+1).filter((e=>{const n=Math.ceil(t/e),r=n*e-t,i=Math.ceil(t/n),a=Math.ceil(r/n);return(!r||r<e)&&i===e&&i>=3&&a<2}));return{...E,validGroupSizes:n}}function mf(t){const{roundRobinGroupsCount:e,participantsCount:n,cluster:r}=t;if(!p(n))return{seedBlocks:void 0,...wr({result:{error:Nn},context:{participantsCount:n},stack:"getSeedBlocks"})};const i=u(n);if(e){const t=Math.min(e,i),n=[];let r=1;for(w(0,t).forEach((()=>{n.push([r]),r++}));r<i;){const e=w(r,r+t);r+=t,n.push(e)}return{...E,seedBlocks:n}}const a=w(1,i+1),o=[];let s=i/2;for(;s>1;){const t=N(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,b(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 d=w(0,20).map((t=>Math.pow(2,t)));d.unshift(1);const l=d.indexOf(i);let m=0;const f=[];return w(0,l).forEach((t=>{f.push(o.slice(m,m+d[t])),m+=d[t]})),{...E,seedBlocks:f}}function ff({roundRobinGroupsCount:t,drawSize:e}){const n="getSeedGroups";if(!p(e))return{seedGroups:void 0,...wr({result:{error:Nn},context:{drawSize:e},stack:n})};if(t){if(!p(t))return{seedGroups:void 0,...wr({context:{roundRobinGroupsCount:t},result:{error:Nn},stack:n})};let r=1;return{seedGroups:w(0,Math.floor(e/t)).map((()=>{const e=w(r,r+t);return r+=t,e}))}}{const{seedBlocks:n}=mf({participantsCount:e,roundRobinGroupsCount:t});let r=0;return{seedGroups:(n||[]).map((t=>(t||[]).map((()=>(r+=1,r)))))}}}function hf({positioning:t,size:n}){const r=function({size:t}){const n=[t];let r=t;for(;r/2===Math.floor(r/2);)r/=2,n.push(r);return n.includes(1)||n.push(1),n.sort(e),n.reverse(),n}({size:n}),i=[],a=[],o=t=>t[0],s=(e,n)=>(t===uo&&n%2?(t=>t[t.length-1])(e):o(e))||o(e),c=(t,e)=>{if(t.every((t=>!a.includes(t)))){const n=s(t,e);return a.push(n),n}},u=t=>{const e=t.filter((t=>!a.includes(t)));if(e.length)return a.push(...e),e},d=(t,e)=>{const n=s(t,e);if(!a.includes(n))return a.push(n),n},p=w(1,n+1);for(const t of r)if(1===t){const t=N(p,2),e=t.map(c).filter(Boolean);e.length&&i.push(e);const n=t.flatMap(u).filter(Boolean);n.length&&i.push(n)}else{const e=N(p,t).map(d).filter(Boolean);e.length&&i.push(e)}return{divisions:r,divisionGroupings:i}}function gf({provisionalPositioning:t,returnAllProxies:e,appliedPolicies:n,seedingProfile:r,drawDefinition:i,allPositions:a,structure:o}){let s=[];if(!o)return{error:yt};const{matchUps:c,roundMatchUps:u}=Yp({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:o}),{seedAssignments:d}=lu({provisionalPositioning:t,returnAllProxies:e,drawDefinition:i,structure:o}),{positionAssignments:p}=is({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,S=h.filter((t=>t.filter((t=>t<=m)).length)),{stage:y,structureType:v,roundLimit:T}=o,P=v===mo,D=!P&&h?.length,b=!P&&y===Qa&&T,R=S.flat(1/0),M=D?R?.length:0,A=a?l:m,E=ip({drawDefinition:i,structure:o,matchUps:c}),C=E?0:!D&&A||A&&R.length<A&&A-R.length||0;if(b){const t=o?.matchUps?o.matchUps.filter((({roundNumber:t})=>t===o.roundLimit)).length:0,e=g.length/t;if(D);else{const t=yf(r),n=N(g,e);let i=1;const a=w(0,n[0].length).map((()=>{const t=w(i,i+n.length);return i+=n.length,t}));({validSeedBlocks:s}=If({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=rs({structure:e})?.positionAssignments,o=yf(t),s=a?.length??0,{seedGroups:c}=ff({roundRobinGroupsCount:i,drawSize:s});return If({drawPositionBlocks:r.map((t=>rs({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=S.map((t=>({seedNumbers:t,drawPositions:t})));else if(E){N(g,2).map(((t,e)=>({drawPositions:[t[0]],seedNumbers:[e+1]}))).forEach((t=>s.push(t)))}if(!P&&!E&&!b){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}=mf({cluster:yf(i)===uo,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:M,seedCountGoal:C,seedingProfile:r,baseDrawSize:U});t.forEach((t=>s.push(t)))}const O=s.flatMap((t=>t.drawPositions)).reduce(((t,e)=>g?.includes(e)&&t),!0);return E||D||P||O?{isLuckyStructure:E,validSeedBlocks:s,isContainer:P,isFeedIn:D}:{error:ft,validSeedBlocks:[],isContainer:P,isFeedIn:D}}function If({drawPositionBlocks:t,positioning:e,seedGroups:n,nonRandom:r}){const i=[],{divisionGroupings:a}=hf({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!==po?d=r?d:f(d):s%2&&d.reverse();const p=d.find((t=>!o.includes(t)));p&&(o.push(p),i.push({seedNumbers:[n],drawPositions:[p]}))}))})),{validSeedBlocks:i}}function Uf({appliedPolicies:t,drawDefinition:e,seedBlockInfo:n,drawPosition:r,structureId:i,seedNumber:a}){const{structure:o}=ts({drawDefinition:e,structureId:i});t||(t=Dc({drawDefinition:e}).appliedPolicies);let s=n?.validSeedBlocks;if(!s&&o&&(s=gf({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 Sf(t){const{provisionalPositioning:e,drawDefinition:n,seedingProfile:r,seedBlockInfo:i,structureId:a,randomize:o}=t,{structure:s}=ts({drawDefinition:n,structureId:a}),{seedAssignments:c}=lu({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,drawDefinition:n,structure:s}),{positionAssignments:u}=is({structure:s}),d=u?.filter((t=>t.participantId??t.bye??t.qualifier)),p=d?.map((t=>t.drawPosition)).filter(Boolean),{appliedPolicies:l}=Dc({drawDefinition:n}),m=(i?.validSeedBlocks||s&&gf({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],h=c?.map((t=>t.participantId)).filter(Boolean),g=u?.map((t=>t.participantId)).filter(Boolean),I=h?.filter((t=>g?.includes(t))),U=h?.filter((t=>!g?.includes(t))),S=c?.filter((t=>U?.includes(t.participantId))),y=c?.filter((t=>!t.participantId)),v=(S?.length&&S.length>0?S.length:y?.length??0)&&m?.drawPositions.filter((t=>!p?.includes(t)))||[],w=o?f(v):v,T=[],P=w.map((()=>{const t=function(t,e){const n=t.filter((t=>!e.includes(t.participantId))),r=Math.min(...n.map((t=>of(t.seedValue)))),i=n.filter((t=>of(t.seedValue)===r));return f(i).pop()}(S,T),e=t?.participantId;return e&&T.push(e),e})).filter(Boolean),D=c?.filter((t=>I?.includes(t.participantId))).map((t=>t.seedNumber)),b=(m?.seedNumbers||[]).filter((t=>!D?.includes(t))),N=c?.filter((t=>b.includes(t.seedNumber))).map((t=>t.participantId)),R=l?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:m,unplacedSeedParticipantIds:void 0===R||R?P:N,unplacedSeedNumbers:b,unfilledPositions:w,unplacedSeedAssignments:S}}function yf(t){return"string"==typeof t?t:"object"==typeof t?t.positioning:void 0}function vf({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}=ts({drawDefinition:n,structureId:o}),{positionAssignments:m}=is({structure:l}),f=lu({provisionalPositioning:t,drawDefinition:n,structure:l}).seedAssignments,h=f.map((t=>t.seedNumber)),g=Xl({drawDefinition:n,participantId:i});if(i&&!g)return wr({result:{error:Te},context:{participantId:i},stack:p});const I=d?Bd({event:d}).flightProfile?.flights?.length:0,U=I&&I>1,S=m?.find((t=>t.participantId===i)),y=S?.drawPosition;if(y){if(!Uf({drawPosition:y,drawDefinition:n,seedBlockInfo:a,structureId:o,seedNumber:s}))return wr({result:{error:H},context:{assignedDrawPosition:y},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?(Bs({tournamentId:e?.tournamentId,drawDefinition:n,structure:l,eventId:u}),{...E}):wr({result:{error:mt},stack:p})}function wf({inContextDrawMatchUps:t,drawDefinition:e,assignments:n,matchUpsMap:r,structure:i}){const a=qs({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)&&P(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 Tf({lineUp:t}){if(!Array.isArray(t))return;const e={};return m(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}=Bc({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 Pf(t){return`${t} must be an array`}function Df({lineUp:t,tieFormat:e}){const n=[];if(!Array.isArray(t))return n.push(Pf("lineUp")),{valid:!1,errors:n,error:Nn};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(Pf("collectionAssignments")),!1):(n.push("Missing participantId"),!1)})),i=m(t.map(Da)).length===t.length;i||n.push("Duplicated participantId(s)");return{valid:r&&i,errors:n,error:n.length?Nn:void 0}}function bf({drawDefinition:t,participantId:e,tieFormat:n,lineUp:r}){if("object"!=typeof t)return{error:j};if("string"!=typeof e)return{error:Ae};const i=Df({lineUp:r,tieFormat:n});if(!i.valid)return i;const{extension:a}=Mr({element:t,name:Zi}),o=a?.value||{};o[e]=Tf({lineUp:r});return Nr({element:t,extension:{name:Zi,value:o}}),_s({drawDefinition:t}),{...E}}function Nf({inContextDrawMatchUps:t,inheritance:e=!0,tournamentRecord:n,drawDefinition:r,matchUpsMap:i,assignments:a,structure:o,event:s}){if(!r)return{error:j};const{drawPositions:c,matchUps:u,targetMatchUps:d}=wf({inContextDrawMatchUps:t,matchUpsMap:i,assignments:a,structure:o});for(const t of d)t.matchUpType===Xs&&(t.sides??[]).forEach(((i,a)=>{if(i?.drawPosition&&c?.includes(i.drawPosition)){const o=u.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&&bf({drawDefinition:r,participantId:n,lineUp:[],tieFormat:e})}xs({tournamentId:n?.tournamentId,context:"resetLineUps",eventId:s?.eventId,drawDefinition:r,matchUp:o})}}}));return{...E}}function Rf({provisionalPositioning:t,inContextDrawMatchUps:e,isQualifierPosition:n,sourceMatchUpStatus:r,tournamentRecord:i,drawDefinition:a,seedingProfile:o,participantId:s,seedBlockInfo:c,drawPosition:u,matchUpsMap:d,structureId:p,event:l}){const m="assignDrawPosition";if(!s&&!n)return wr({result:{error:Ae},stack:m});d=d??xc({drawDefinition:a}),e||({matchUps:e}=Jp({inContext:!0,drawDefinition:a,matchUpsMap:d}));const f=ts({drawDefinition:a,structureId:p});if(f.error)return wr({result:f,stack:m});const{structure:h}=f;if(!h)return{error:Ut};if(ap({drawDefinition:a,structure:h}))return wr({result:{error:Yt},stack:m});const{seedAssignments:g}=lu({provisionalPositioning:t,drawDefinition:a,structure:h}),I=g?.find((t=>t.participantId===s)),U=I?.seedNumber,{appliedPolicies:S}=Dc({tournamentRecord:i,drawDefinition:a,structure:h,event:l});if(U){if(!Uf({seedNumber:U,appliedPolicies:S,drawDefinition:a,seedBlockInfo:c,drawPosition:u,structureId:p}))return wr({result:{error:H},context:{drawPosition:u},stack:m})}const y=is({structure:h}).positionAssignments||[],v=y?.find((t=>t.drawPosition===u));if(!v)return wr({result:{error:Q},context:{drawPosition:u},stack:m});const w=y?.map(Da).includes(s);if(w)return wr({result:{error:Le},context:{drawPosition:u},stack:m});const{containsParticipant:T,containsBye:P}=function(t){const e=t.bye,n=t.qualifier,r=t.participantId;return{containsBye:e,containsQualifier:n,containsParticipant:r,filled:e||n||r}}(v);if(P){const t=Cl({inContextDrawMatchUps:e,tournamentRecord:i,drawDefinition:a,drawPosition:u,structureId:p,matchUpsMap:d,event:l});if(t.error)return wr({result:t,stack:m})}if(T&&v.participantId!==s){const{activeDrawPositions:t}=yl({drawDefinition:a,structureId:p});if(t.includes(u))return wr({result:{error:X},stack:m});Nf({assignments:[v],inContextDrawMatchUps:e,tournamentRecord:i,drawDefinition:a,matchUpsMap:d,structure:h})}if(v.participantId=s,n&&(v.qualifier=!0),(h?.stageSequence||0)>1||h.stage&&[to,no].includes(h.stage)){const e=h.stage===Qa?Qa:Xa,n=a.structures?.find((t=>t?.stage===e&&1===t?.stageSequence)),r=(n?.seedAssignments??[]).find((t=>t.participantId===s));if(r?.participantId){const{participantId:e,seedNumber:n,seedValue:s}=r;vf({eventId:l?.eventId,provisionalPositioning:t,tournamentRecord:i,drawDefinition:a,seedingProfile:o,participantId:e,seedNumber:n,seedValue:s,structureId:p,event:l})}}if(h.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}=Yp({provisionalPositioning:t,matchUpFilters:u,drawDefinition:i,matchUpsMap:o,structure:s,event:c}),{roundMatchUps:p}=vc({matchUps:d}),{initialRoundNumber:l}=vl({drawPosition:a,matchUps:d}),m=l&&p?.[l].find((t=>t.drawPositions?.includes(a)));if(m){const t=af({matchUpId:m.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:r,drawDefinition:i,drawPosition:a,matchUpsMap:o});if(t.error)return wr({stack:"assignDrawPositionToMatchUps",context:{drawPosition:a},result:t})}}({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:i,drawDefinition:a,drawPosition:u,matchUpsMap:d,structure:h,event:l});else{El({positionAssignments:y,tournamentRecord:i,drawDefinition:a,matchUpsMap:d,structure:h});const{drawPositions:t,matchUps:n,targetMatchUps:r}=wf({assignments:[v],inContextDrawMatchUps:e,drawDefinition:a,matchUpsMap:d,structure:h});if(t&&1===n?.length&&n[0].matchUpType===Qs){const e=(r?.[0].sides??[]).reduce(((e,n,r)=>t?.includes(n.drawPosition)?r:e),void 0);rf({inContextTargetMatchUp:r[0],teamParticipantId:s,matchUp:n[0],drawPositionSideIndex:e,tournamentRecord:i,drawDefinition:a})}}return Vs({tournamentId:i?.tournamentId,drawDefinition:a,structure:h,event:l}),{positionAssignments:y,...E}}function Mf(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:j};let{inContextDrawMatchUps:p,matchUpsMap:l}=t;l||(l=xc({drawDefinition:a}),Object.assign(t,{matchUpsMap:l})),p||(({matchUps:p}=Jp({inContext:!0,drawDefinition:a,matchUpsMap:l})),Object.assign(t,{inContextDrawMatchUps:p}));const{positionAssignments:m}=rs({drawDefinition:a,structureId:c}),f=m?.find((t=>t.drawPosition===s));if(f?.participantId){const t=f.participantId,e=Rf({inContextDrawMatchUps:p,tournamentRecord:i,drawDefinition:a,participantId:o,drawPosition:s,structureId:c,matchUpsMap:l,event:u});return e.success?U({removedParticipantId:t}):wr({result:e,stack:d})}const h=Cl({inContextDrawMatchUps:p,tournamentRecord:i,drawDefinition:a,drawPosition:s,structureId:c,matchUpsMap:l,event:u});if(h.error)return wr({result:h,stack:d});const g=h.participantId,I=Rf({inContextDrawMatchUps:p,isQualifierPosition:n,tournamentRecord:i,drawDefinition:a,participantId:o,drawPosition:s,structureId:c,matchUpsMap:l,event:u});return I.success?U({removedParticipantId:g}):wr({result:I,stack:d});function U({removedParticipantId:t}){const{structure:n}=ts({drawDefinition:a,structureId:c});js({drawPositions:[s],structure:n});return Gs({drawDefinition:a,positionAction:{[e]:o,name:r,drawPosition:s,structureId:c}}),wr({context:{removedParticipantId:t},result:{...E},stack:d})}}function Af(t){Object.assign(t,{inContext:!0});const{matchUp:e,error:n}=Ef(t);return{matchUp:gi(e,!0,!0),error:n}}function Ef({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:_};if("string"!=typeof s)return{error:qt};if(!a||!p){const t=(hl({tournamentRecord:n,nextMatchUps:o}).matchUps??[]).find((t=>t.matchUpId===s));if(!t)return{error:Wt};({eventId:u,drawId:d}=t),({event:p,drawDefinition:a}=Vd({tournamentRecord:n,eventId:u,drawId:d}))}if(!a)return{error:q};i&&!r&&(r=Fc({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=[]}=ml({participantsProfile:t,tournamentRecord:n,contextProfile:i,inContext:c});if(o){const t=(Ul({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:Wt};const n=a?.structures?.find((e=>e.structureId===t.structureId));return{drawDefinition:a,structure:n,matchUp:t}}{const{matchUp:t,structure:n}=Xm({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 Cf(t,e){if(!ha(t))return{error:Nn};if(!Array.isArray(e))return{error:Nn};const n={};for(const{param:r,error:i,attr:a}of e){const e=Of({params:t,param:r,attr:a,error:i});if(e?.error)return e;n[r]=e}return n}function Of({params:t,param:e,attr:n,error:r}){if(e===Sp&&ha(t.drawDefinition)&&fa(t.structureId)){const e=(t.drawDefinition.structures??[]).find((({structureId:e})=>e===t.structureId));return!e.length&&r?{error:r}:{structure:e}}if(e===Dp){const e=Ef({...t,...n});return e.error&&r?{...e,error:r}:e}return{error:On,info:{param:e}}}function Ff({removePriorValues:t,tournamentRecord:e,duplicateValues:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:o,event:s}){const{matchUp:c}=Xm({drawDefinition:r,event:s,matchUpId:a});if(!c)return{error:Wt};const u=xm({removePriorValues:t,element:c,duplicateValues:n,timeItem:o});return i||xs({tournamentId:e?.tournamentId,eventId:s?.eventId,context:"addTimeItem",drawDefinition:r,matchUp:c}),u}function kf(t){const e=Lp(t,[{[up]:!0},{[dp]:!0},{[lp]:!0},{[Ip]:!0}]);if(e.error)return e;const n=Cf(t,[{[Mp]:Dp,attr:{[Up]:!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&&Ka.includes(c)||c&&Ya.includes(c)||$s({score:u}))return{error:dt};const d=Ku({matchUp:s});if(d?.error)return d;const{checkedInParticipantIds:p,allRelevantParticipantIds:l}=d??{};if(!l?.includes(a))return{error:Te};if(!p?.includes(a))return{error:xe};const m=yu({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=>{Ff({drawDefinition:i,matchUpId:o,timeItem:{itemType:wu,itemValue:t}})}));return Ff({tournamentRecord:r,drawDefinition:i,matchUpId:o,timeItem:{itemValue:a,itemType:wu}})}function xf(t){const e=Lp(t,[{[up]:!0},{[dp]:!0},{[lp]:!0},{[Ip]:!0}]);if(e[Np])return e;const n=Cf(t,[{[Mp]:Dp,attr:{[Up]:!0}}]);if(n[Np])return n;const{tournamentRecord:r,drawDefinition:i,participantId:a,matchUpId:o}=t,s=Ku({matchUp:n?.matchUp?.matchUp});if(s?.error)return s;const{checkedInParticipantIds:c,allRelevantParticipantIds:u}=s??{};if(c?.includes(a))return{...E};if(!u?.includes(a))return{[Np]:Te};return Ff({tournamentRecord:r,drawDefinition:i,matchUpId:o,timeItem:{itemValue:a,itemType:vu}})}function _f(t){const e=Lp(t,[{[lp]:!0,[dp]:!0,[Ip]:!0}]);if(e.error)return e;const n=t.tournamentId??t.activeTournamentId,r=t.tournamentRecord??(n&&t.tournamentRecords?.[n]),{participantId:i,matchUpId:a,drawDefinition:o}=t;if(!r)return{error:_};const s=Cf(t,[{[Mp]:Dp,[Np]:Wt}]),c=s.matchUp?.matchUp;if(!c)return{error:Wt};const{checkedInParticipantIds:u=[]}=Ku({matchUp:c});return i&&u.includes(i)?kf({tournamentRecord:r,drawDefinition:o,participantId:i,matchUpId:a,matchUp:c}):xf({tournamentRecord:r,drawDefinition:o,participantId:i,matchUpId:a,matchUp:c})}function Lf({tournamentRecord:t,drawDefinition:e,tieMatchUpId:n,event:r}){if(!t)return{error:_};if(!e)return{error:at};if(!r)return{error:Pt};const i=xc({drawDefinition:e}),{matchUp:a}=Xm({matchUpId:n,drawDefinition:e,matchUpsMap:i});if(!a)return{error:Wt};const{matchUp:o,structure:s}=Xm({tournamentParticipants:t.participants,matchUpId:n,inContext:!0,drawDefinition:e,matchUpsMap:i,event:r});if(!o)return{error:Wt};const{collectionPosition:c,drawPositions:u,collectionId:d,matchUpTieId:p,matchUpType:l}=o;if(l&&![Ks,Zs].includes(l))return{error:Yt};const{positionAssignments:m}=rs({structure:s}),f=m?.filter((t=>u?.includes(t.drawPosition))),h=f?.map(Ua("participantId")),{participants:g}=Zl({tournamentRecord:t,participantFilters:{participantTypes:[dc],participantIds:h}}),{matchUp:I}=Xm({matchUpId:p,drawDefinition:e,matchUpsMap:i}),{matchUp:U}=Xm({matchUpId:p,inContext:!0,drawDefinition:e,matchUpsMap:i}),S=$d({matchUp:I,drawDefinition:e,structure:s,event:r})?.tieFormat;return{inContextDualMatchUp:U,inContextTieMatchUp:o,relevantAssignments:f,collectionPosition:c,teamParticipants:g,collectionId:d,matchUpType:l,dualMatchUp:I,tieMatchUp:a,tieFormat:S,structure:s,...E}}function Bf(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:_};if(!o)return wr({result:{error:Re},stack:e});o.participantId||(o.participantId=Md()),s.participants||(s.participants=[]);const{participantId:c,individualParticipantIds:u}=o;if(s.participants.reduce(((t,e)=>e.participantId===c||t),!1))return{error:Ce};const{participantType:d,participantRole:p}=o;if(!d||!Object.keys(pc).includes(d))return{error:be,participantType:d};if(!p)return{error:Ne};const l=s.participants||[],m=l.filter((t=>t.participantType===sc)).map((t=>t.participantId));if(d!==sc&&o.person)return{error:Nn,person:o.person};if(u&&!Array.isArray(u))return{error:Nn,individualParticipantIds:u};if(d===uc){if(o.person)return{error:Nn,person:o.person};if(!o.individualParticipantIds)return wr({result:{error:Fe},stack:e});if(2!==o.individualParticipantIds.length&&!a)return wr({info:"PAIR must be 2 individualParticipantIds",result:{error:Pe},stack:e});{const t=l.filter((t=>t.participantType===sc)).map((t=>t.participantId));if(!Array.isArray(o.individualParticipantIds))return wr({result:{error:Pe},stack:e});if(!o.individualParticipantIds.reduce(((e,n)=>t.includes(n)&&e),!0))return wr({result:{error:Pe},stack:e})}const t=l.filter((t=>t.participantType===uc)).map((t=>({individualParticipantIds:t.individualParticipantIds,participant:t}))),i=o.participantType===uc&&t.find((t=>2===P(t.individualParticipantIds,o.individualParticipantIds).length));if(i&&!n)return{...E,existingParticipant:!0,participant:r&&gi(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===sc){if(!o.person?.standardFamilyName||!o.person?.standardGivenName)return{error:_e};if(!o.participantName){const t=`${o.person.standardFamilyName.toUpperCase()}, ${o.person.standardGivenName}`;o.participantName=t}}else{if(!d||![dc,cc].includes(d))return{error:be};if(u||(o.individualParticipantIds=[]),o.individualParticipantIds?.length)for(const t of o.individualParticipantIds){if("string"!=typeof t)return wr({result:{participantId:t,error:Nn},stack:e});if(!m.includes(t))return wr({result:{participantId:t,error:Ee},stack:e})}}s.participants.push(o),i||sr({payload:{tournamentId:s.tournamentId,participants:[o]},topic:ss});return vr({participant:r&&gi(o),...E})}function Vf({inContextDualMatchUp:t,drawDefinition:e,tournamentId:n,dualMatchUp:r,eventId:i}){if(r){t||(t=Xm({matchUpId:r.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);const{extension:a}=Mr({element:e,name:Zi}),o=gi(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}})),xs({context:"ensureSidLineUps",matchUp:r,drawDefinition:e,tournamentId:n,eventId:i})}}function jf(t){const e=Lf(t);if(e.error)return e;const n="replaceTieMatchUpParticipantid",{existingParticipantId:r,tournamentRecord:i,newParticipantId:a,drawDefinition:o,substitution:s,event:c}=t;if(!r||!a)return wr({result:{error:Ae},stack:n});if(r===a)return{...E};const{inContextDualMatchUp:u,inContextTieMatchUp:d,collectionPosition:p,collectionId:l,dualMatchUp:f,tieMatchUp:h,tieFormat:g}=e,I=d?.matchUpType,U=d?.sides?.find((t=>t.participant?.participantId===r||t.participant?.individualParticipantIds?.includes(r)));if(!U)return{error:Ee};const S=Zl({tournamentRecord:i,participantFilters:{participantIds:[r,a]}})?.participants??[];if(2!==S.length)return wr({result:{error:Ae},stack:n});if(S[0].participantType!==S[1].participantType)return wr({result:{error:be},stack:n});const{appliedPolicies:y}=Dc({tournamentRecord:i,drawDefinition:o,event:c}),v=t.policyDefinitions?.[wi]??y?.[wi]??sm[wi],w=S.find((({participantId:t})=>t===a));if(!1!==(t.enforceGender??v?.participants?.enforceGender)&&[qp,Hp].includes(d?.gender)&&d?.gender!==w?.person?.sex)return{error:we,info:"Gender mismatch"};const T=v?.processCodes?.substitution;Vf({tournamentId:i.tournamentId,eventId:c.eventId,inContextDualMatchUp:u,drawDefinition:o,dualMatchUp:f});const P=f?.sides?.find((({sideNumber:t})=>t===U.sideNumber));if(!P)return wr({result:{sideNumber:U.sideNumber,existingParticipantId:r,error:On},stack:n});const D=d?.sides?.flatMap((t=>t.participant?.individualParticipantIds||t.participant?.participantId||[]));if(D?.includes(a))return wr({result:{error:Be},stack:n});const b=u?.sides?.find((({sideNumber:t})=>t===U.sideNumber))?.participantId,N=P.lineUp,R=N?.find((({participantId:t})=>a===t)),M=N?.reduce(((t,e)=>e.substitutionOrder>t?e.substitutionOrder:t),0),A=N?.map((t=>{const e=gi(t,!1,!0);if(![r,a].includes(e.participantId))return e;if(!s&&[r,a].includes(e.participantId)&&(e.collectionAssignments=e.collectionAssignments?.filter((t=>!(t.collectionPosition===p&&t.collectionId===l)))),s&&r===e.participantId&&(e.collectionAssignments=e.collectionAssignments.map((t=>t.collectionPosition===p&&t.collectionId===l&&void 0===t.substitutionOrder?{...t,substitutionOrder:M}:t))),e.participantId===a){e.collectionAssignments||(e.collectionAssignments=[]);const t={collectionId:l,collectionPosition:p};s&&(t.previousParticipantId=r,t.substitutionOrder=(M??0)+1),e.collectionAssignments.push(t)}return e}))??[];if(!R){const t={collectionId:l,collectionPosition:p};s&&(t.substitutionOrder=(M??0)+1,t.previousParticipantId=r);const e={collectionAssignments:[t],participantId:a};A.push(e)}const C=I===Zs,{assignedParticipantIds:O}=Bc({lineUp:N,collectionPosition:p,collectionId:l}),{assignedParticipantIds:F}=Bc({lineUp:A,collectionPosition:p,collectionId:l});if(P.lineUp=A,b&&g){const t=bf({participantId:b,lineUp:A,drawDefinition:o,tieFormat:g});if(t.error)return wr({result:t,stack:n})}else console.log("team participantId not found");let k,x;if(C){const{tournamentRecord:e}=t;let r=Vc({participantIds:F,tournamentRecord:e});if(!r.participant){const t=Bf({returnParticipant:!0,pairOverride:!0,tournamentRecord:e,participant:{participantRole:um,individualParticipantIds:F,participantType:uc}});if(t.error)return wr({result:t,stack:n});k=t.participant?.participantId}r=Vc({participantIds:O,tournamentRecord:e});const i=r.participant?.participantId;if(i){gm({participantIds:[i],tournamentRecord:e}).success&&(x=i)}}if(s||1===U.substitutions?.length){if(s)T&&h&&(h.processCodes=m([...h?.processCodes??[],...T]));else for(const t of T||[]){const e=h?.processCodes?.lastIndexOf(t);void 0!==e&&h?.processCodes?.splice(e,1)}h&&xs({tournamentId:i?.tournamentId,matchUp:h,context:n,drawDefinition:o})}return f&&xs({tournamentId:i?.tournamentId,matchUp:f,context:n,drawDefinition:o}),{...E,modifiedLineUp:A,participantRemoved:x,participantAdded:k}}function Gf({collectionPosition:t,teamParticipantId:e,dualMatchUpSide:n,drawDefinition:r,participantIds:i,collectionId:a}){if(!a||!t||!Array.isArray(i))return{modifiedLineUp:n?.lineUp||[],error:Nn};const o=n?.lineUp||jc({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 qf({individualParticipantIds:t,groupingParticipantId:e,removeFromOtherTeams:n,tournamentRecord:r}){const i="addIndividualParticipantIds";if(!r)return wr({result:{error:_},stack:i});if(!e||!t)return wr({result:{error:ae},stack:i});const a=r.participants??[],o=a.find((t=>t.participantId===e));if(!o)return wr({result:{error:Ee},stack:i});if(o?.participantType&&![dc,cc].includes(o.participantType))return wr({context:{participantType:o.participantType},result:{error:be},stack:i});const s=t.filter((t=>{const e=a.find((e=>e.participantId===t));return e?.participantType!==sc}));if(s.length)return wr({result:{error:Pe,invalidParticipantIds:s},stack:i});o.individualParticipantIds||(o.individualParticipantIds=[]);const c=o.individualParticipantIds,u=t.filter((t=>!c.includes(t)));u.length&&(n&&hm({individualParticipantIds:u,tournamentRecord:r}),o.individualParticipantIds=o.individualParticipantIds.concat(...u));const{topics:d}=lr();if(d.includes(Ss)){const t=a.find((({participantId:t})=>t===e));sr({topic:Ss,payload:{participants:[t]}})}return function({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}){const r=(n.events||[]).filter((t=>t?.eventType===id&&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}=Bd({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:gi(o,!1,!0),added:u.length,...E}}function $f(t){const{updateParticipantName:e=!0,groupingParticipantId:n,removeFromOtherTeams:r,tournamentRecord:i,pairOverride:a,participant:o}=t;if(!i)return{error:_};if(!o)return{error:Re};if(!o.participantId)return Bf({tournamentRecord:i,participant:o});const{participant:s}=rl({participantId:o.participantId,tournamentRecord:i});if(!s)return Bf({tournamentRecord:i,participant:o});const{participantRoleResponsibilties:c,individualParticipantIds:u,participantOtherName:d,participantName:p,participantRole:l,participantType:m,onlineResources:f,contacts:h,person:g}=o;if(m&&s.participantType!==m)return{error:Se};const I={};if(h&&(I.contacts=h),f&&(I.onlineResources=f),p&&"string"==typeof p&&(I.participantName=p),d&&"string"==typeof d&&(I.participantOtherName=d),Array.isArray(u)){const{participants:t}=Zl({participantFilters:{participantTypes:[sc]},tournamentRecord:i}),n=t?.map(Da);if(n){const r=u.filter((t=>"string"==typeof t&&n.includes(t)));([cc,Qs].includes(m||s.participantType)||m===uc&&(2===r.length||a))&&(I.individualParticipantIds=r),s.participantType===pc.PAIR&&e&&(I.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:I}))}}return Object.keys(lm).includes(l)&&(I.participantRole=l),Object.keys(pc).includes(m)&&(I.participantType=m),Array.isArray(c)&&(I.participantRoleResponsibilties=c),s.participantType===pc.INDIVIDUAL&&g&&function({updateParticipantName:t,existingParticipant:e,newValues:n,person:r}){const i={},{standardFamilyName:a,standardGivenName:o,nationalityCode:s,personId:c,sex:u}=r;u&&Object.keys(zp).includes(u)&&(i.sex=u);let d;c&&"string"==typeof c&&(i.personId=c);s&&"string"==typeof s&&(p=s,el.flatMap((({iso:t,ioc:e})=>[t,e])).filter(Boolean).includes(p)||""===s)&&(i.nationalityCode=s);var p;a&&"string"==typeof a&&a.length>1&&(i.standardFamilyName=a,d=!0);o&&"string"==typeof o&&o.length>1&&(i.standardGivenName=o,d=!0);if(d&&t){const t=`${i.standardGivenName} ${i.standardFamilyName}`;n.participantName=t}Object.assign(e.person,i)}({updateParticipantName:e,existingParticipant:s,newValues:I,person:g}),Object.assign(s,vr(I)),n&&qf({individualParticipantIds:[s.participantId],groupingParticipantId:n,removeFromOtherTeams:r,tournamentRecord:i}),sr({topic:Ss,payload:{tournamentId:i.tournamentId,participants:[s]}}),{participant:gi(s),...E}}function Wf(t){const e=Lf(t);if(e.error)return e;const n="assignTieMatchUpParticipantId";let r=t.teamParticipantId;const{tournamentRecord:i,drawDefinition:a,participantId:o,event:s}=t;if(!o)return wr({result:{error:Ae},stack:n});if(t.sideNumber&&![1,2].includes(t.sideNumber))return wr({result:{error:ne},stack:n});const{inContextDualMatchUp:c,inContextTieMatchUp:u,relevantAssignments:d,collectionPosition:p,teamParticipants:l,collectionId:m,matchUpType:f,dualMatchUp:h,tieFormat:g}=e,I=u?.sides?.flatMap((t=>t.participant?.individualParticipantIds||t.participant?.participantId||[]));if(I?.includes(o))return wr({result:{...E},stack:n});r=r??(t.sideNumber?c?.sides?.find((e=>e.sideNumber===t.sideNumber))?.participantId:void 0);const U=Zl({participantFilters:{participantIds:[o]},tournamentRecord:i})?.participants?.[0];if(!U)return wr({result:{error:Ee},stack:n});const{appliedPolicies:S}=Dc({tournamentRecord:i,drawDefinition:a,event:s}),y=t.policyDefinitions?.[wi]??S?.[wi]??sm[wi];if(!1!==(t.enforceGender??y?.participants?.enforceGender)&&[qp,Hp].includes(u?.gender)&&u?.gender!==U.person?.sex)return{error:we,info:"Gender mismatch"};const{individualParticipantIds:v,participantType:w}=U;if(f===Ks&&w!==sc)return{error:be};const T=w===sc?[o]:v,P=r&&l?.find((({participantId:t})=>t===r))||l?.find((({individualParticipantIds:t})=>b(T,t)));if(!P)return{error:Mn};if(r||(r=P.participantId),!r)return{error:Ee};const D=d?.find((t=>t.participantId===P?.participantId)),N=D?.drawPosition,R=u?.sides?.find((t=>t.drawPosition===N)),M=t.sideNumber??R?.sideNumber;if(!g)return{error:Gt};const A=g.collectionDefinitions?.find((t=>t.collectionId===m));if(!A)return{error:jt};Vf({tournamentId:i.tournamentId,eventId:s.eventId,inContextDualMatchUp:c,drawDefinition:a,dualMatchUp:h});const C=h?.sides?.find((t=>t.sideNumber===M)),O=u?.sides?.find((t=>t.sideNumber===M)),F=C?.lineUp??jc({participantId:r,drawDefinition:a})?.lineUp,k=F?.filter((t=>t.collectionAssignments?.find((t=>t.collectionPosition===p&&t.collectionId===m&&!t.previousParticipantId)))),x=k?.map((t=>t?.participantId)),_=x?.length>1&&x||(w===uc?U.individualParticipantIds:[o]),L=Gf({collectionPosition:p,teamParticipantId:r,dualMatchUpSide:C,drawDefinition:a,participantIds:_,collectionId:m});if(L.error)return wr({result:L,stack:n});const{modifiedLineUp:B}=L;let V;if(f===Zs){if(w!==uc){let t=Hf({collectionPosition:p,teamParticipantId:r,drawDefinition:a,modifiedLineUp:B,participantId:o,collectionId:m,tieFormat:g});if(t?.error)return wr({result:t,stack:n});if(t=function({side:t}){let e;if(t.participant){const n=t.participant.individualParticipantIds||[];if(1===n.filter(Boolean).length){const{participant:t}=Vc({participantIds:n,tournamentRecord:i});n.push(o);const{participant:r}=Vc({participantIds:n,tournamentRecord:i});if(!r&&t){t.individualParticipantIds=n;const e=$f({pairOverride:!0,tournamentRecord:i,participant:t});if(e.error)return e}else e=t?.participantId}}else{const t=Bf({participant:{individualParticipantIds:[o],participantRole:um,participantType:uc},pairOverride:!0,tournamentRecord:i});if(t.error)return t}return{...E,deletedParticipantId:e}}({side:O}),t.error)return t;V=t.deletedParticipantId,C&&(C.lineUp=B),h&&xs({tournamentId:i?.tournamentId,matchUp:h,context:n,drawDefinition:a})}else if(w===uc)for(const t of _)Hf({collectionPosition:p,teamParticipantId:r,drawDefinition:a,modifiedLineUp:B,participantId:t,collectionId:m,tieFormat:g})}else{const t=Hf({collectionPosition:p,teamParticipantId:r,drawDefinition:a,modifiedLineUp:B,participantId:o,collectionId:m,tieFormat:g});if(t?.error)return t}if(C&&(C.lineUp=B),h&&xs({tournamentId:i?.tournamentId,matchUp:h,context:n,drawDefinition:a}),V){const{error:t}=gm({participantIds:[V],tournamentRecord:i});t&&console.log("cleanup")}return{...E,modifiedLineUp:B}}function Hf({collectionPosition:t,teamParticipantId:e,drawDefinition:n,modifiedLineUp:r,participantId:i,collectionId:a,tieFormat:o}){const s=jc({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 bf({participantId:e,lineUp:r,drawDefinition:n,tieFormat:o})}function zf({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!==m(r).length?(n.push("collectionPositions are not unique"),{errors:n}):{...E}}function Yf(t){if(t)return gi(t,!1,!0)}function Kf({collectionGroups:t=[]}){const e=Object.assign({},...t.filter((t=>p(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=>n(t)))}}function Jf({collectionDefinitions:t=[],collectionGroups:e=[]}){let n=0;const{groupValueNumbers:r}=Kf({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,l=a&&r.includes(a);if(p(d||u))i=!0;else{if(l)continue;if("number"==typeof o&&p(o))n+=o;else if(t?.length)for(const e of t)n+=e.matchUpValue;else"number"==typeof c&&p(c)&&(n+=(s??0)*c)}}for(const t of e)n+=t.groupValue??0;if(i||!n)return{aggregateValue:!0};return{valueGoal:Math.floor(n/2)+1}}function Zf({drawDefinition:t,structureId:e,matchUpId:n,structure:r,matchUp:i,eventId:a,event:o}){const s="getTieFormat";let c;if(e=r?.structureId??e,((n=i?.matchUpId??n)||e)&&!t)return{error:j};if(a&&o)c=Gd(o);else if(n){if(t&&(!i||!r)){const e=Xm({drawDefinition:t,matchUpId:n});if(e.error)return e;if(e.matchUp?.matchUpType!==Xs)return wr({result:{error:Yt},stack:s});r||(r=e.structure),i||(i=e.matchUp)}c=qd({item:i,drawDefinition:t,structure:r,event:o})||qd({item:r,drawDefinition:t,structure:r,event:o})||Gd(t)||Gd(o)}else if(t&&e){if(!r){const n=ts({drawDefinition:t,structureId:e});if(n.error)return n;r=n?.structure}c=qd({item:r,drawDefinition:t,structure:r,event:o})||Gd(t)||Gd(o)}else c=Gd(t)||Gd(o);return c?{...E,structure:r,tieFormat:c,matchUp:i}:wr({result:{error:Gt},stack:s})}function Xf(t,e){if((t?.bestOf||t?.exactly)&&t?.setFormat)return function(t,e){const n=Qf(t.bestOf)||void 0,r=Qf(t.exactly)||void 0,i=n||r;if(t.setFormat?.timed&&t.simplified&&1===i)return th(t.setFormat);const a=i&&`${Yd}${i}`||"",o=eh(t.setFormat,e),s=o&&`S:${o}`||"",c=eh(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 Qf(t){return!isNaN(Number(t))&&Number(t)}function th(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function eh(t,e){if("object"==typeof t&&Object.keys(t).length){if(t.timed)return th(t);if(t.tiebreakSet)return nh(t.tiebreakSet);const n=Qf(t.setTo);if(n){const r=t.NoAD&&zd||"",i=nh(t.tiebreakFormat),a=i&&`/${i}`||"",o=Qf(t.tiebreakAt);if(!1!==i)return`${n}${r}${a}${o&&(o!==n||e)&&`@${o}`||""}`}}}function nh(t){if(t){if("object"!=typeof t||t.tiebreakTo){if("object"==typeof t&&Qf(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?zd:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}return!1}return""}}function rh(t){if("string"!=typeof t)return!1;const e=Jd(t),n=t.match(/-S:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),r=n?.[1],i=n?.[2],a=n?.[3],o=t.match(/-F:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),s=o?.[1],c=o?.[2],u=o?.[3];return Xf(e,!!(n&&i&&r===a||o&&c&&s===u))===t}const ih="MIXED events can not contain mixed singles or { gender: ANY } collections",ah="events with { gender: ANY } can not contain MIXED singles collections";function oh(t){const e="tieFormatGenderValidityCheck",{referenceGender:n,matchUpType:r,gender:i}=t;return n&&i&&[qp,Hp].includes(n)&&n!==i?wr({result:{valid:!1,error:Dn},context:{gender:i},stack:e}):n===$p&&(i===Gp||i===$p&&r!==Zs)?wr({result:{error:Dn,valid:!1},info:ih,stack:e}):n===Gp&&i===$p&&r!==Zs?wr({result:{error:Dn,valid:!1},info:ah,stack:e}):{valid:!0}}const sh=(t,e)=>t.filter(Boolean).every((t=>typeof t===e)),ch=t=>t.filter(Boolean).every(s);function uh(t){const e=t.category;if("object"!=typeof e)return{error:bn};let{ageCategoryCode:n,ageMaxDate:r,ageMinDate:i,ageMax:a,ageMin:o}=e;const s=e.categoryName;let c;if(!sh([n,r,i,s],"string")||!ch([a,o]))return{error:bn};const u=t.consideredDate??ri((new Date).toLocaleDateString("sv"));if(!Wr(u))return{error:pe};const[d]=u.split("-").slice(0,3).map((t=>parseInt(t))),p=ii(u,-1),[l,m]=p.split("-").slice(1,3).map((t=>parseInt(t))),f=`${mi(l)}-${mi(m)}`,h=ii(u,1),[g,I]=h.split("-").slice(1,3).map((t=>parseInt(t))),U=`${mi(g)}-${mi(I)}`;let S=o&&ii(u,-365*o),y=a&&ii(u,-365*a);const v=[],w=t=>!v.includes(t)&&v.push(t);n=n??s;const T=/^([UO]?)(\d{1,2})([UO]?)$/,P=/^C(\d{1,2})-(\d{1,2})$/,D=n?.includes("-"),b=D&&n?.match(P),N=n?.match(T),R=(t,e)=>`${t}-${e}`,M=t=>{const r=R(d-t-1,U);e.ageMin&&e.ageMin>t&&w(`Invalid submitted ageMin: ${o}`),e.ageMax&&e.ageMax>t&&w(`Invalid submitted ageMax: ${a}`),e.ageMinDate&&e.ageMinDate!==r&&w(`Invalid submitted ageMinDate: ${i}`),i=r,n&&(e.ageMax&&e.ageMax!==t&&(w(`Invalid submitted ageMax: ${a}`),S=void 0),a=t)},A=t=>{const i=R(d-t,f);e.ageMaxDate&&e.ageMaxDate!==i&&w(`Invalid submitted ageMaxDate: ${r}`),r=i,n&&(e.ageMin&&e.ageMin!==t+1&&(w(`Invalid submitted ageMin: ${o}`),S=void 0),o=t+1)},E=t=>{const[s,c,u]=(t.match(T)||[]).slice(1),p=parseInt(c);"U"===s?(e.ageMaxDate&&e.ageMaxDate!==r&&w(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),(t=>{const r=R(d-t,U);e.ageMinDate&&e.ageMinDate!==r&&w(`Invalid submitted ageMinDate: ${i}`),i=r,n&&(e.ageMax&&e.ageMax!==t-1&&(w(`Invalid submitted ageMax: ${a}`),y=void 0),a=t-1)})(p)):"O"===s&&A(p),"U"===u?(e.ageMaxDate&&e.ageMaxDate!==r&&w(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),M(p)):"O"===u&&(t=>{const i=R(d-t-1,f);e.ageMaxDate&&e.ageMaxDate!==i&&w(`Invalid submitted ageMaxDate: ${r}`),r=i,n&&(e.ageMin&&e.ageMin!==t&&(w(`Invalid submitted ageMin: ${o}`),S=void 0),o=t)})(p),r=r??S,i=i??y};if(b){if(r=void 0,i=void 0,a=void 0,o=void 0,e.ageMin){const t=d-e.ageMin;r=R(t,f)}if(e.ageMax){const t=d-e.ageMax-1;i=R(t,U)}const[t,s]=(n?.match(P)??[]).slice(1).map((t=>parseInt(t)));t<=s?(o=t,a=s,c=!0):w(`Invalid combined age range ${n}`)}else D?n?.split("-").forEach(E):N?E(n):(o&&A(o),a&&M(a));a&&e.ageMin&&e.ageMin>a&&(w(`Invalid submitted ageMin: ${e.ageMin}`),o=void 0);const C=vr({consideredDate:u,combinedAge:c,ageMaxDate:r,ageMinDate:i,ageMax:a,ageMin:o});return v.length&&(C.errors=v),C}function dh({category:t}){if(!ha(t))return{error:Nn};const e=uh({category:t});if(e.error)return{error:e};const{ratingMax:n,ratingMin:r}=t;return n&&!s(n)?wr({result:{error:Nn},context:{ratingMax:n}}):r&&!s(r)?wr({result:{error:Nn},context:{ratingMin:r}}):{...e}}function ph({childCategory:t,withDetails:e,category:n}){const r=dh({category:n}),i=dh({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=vr({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}const lh={isValid:rh,isValidMatchUpFormat:rh,stringify:Xf,parse:Jd};function mh({checkCategory:t=!0,collectionDefinition:e,checkCollectionIds:n,checkGender:r=!0,referenceCategory:i,referenceGender:a,event:o}){a=a??o?.gender;const s="validateCollectionDefinition",c=[];if("object"!=typeof e)return c.push(`collectionDefinition must be an object: ${e}`),wr({result:{errors:c,error:Pn},stack:s});const{collectionValueProfiles:u,collectionGroupNumber:d,collectionValue:l,collectionId:m,matchUpCount:f,matchUpFormat:h,matchUpValue:g,matchUpType:I,scoreValue:U,setValue:S,category:y,gender:v}=e;n&&"string"!=typeof m&&c.push(`collectionId is not type string: ${m}`),"number"!=typeof f&&c.push(`matchUpCount is not type number: ${f}`),I&&![Ks,Zs].includes(I)&&c.push(`matchUpType must be SINGLES or DOUBLES: ${I}`);if(1!==[!!u?.length].concat([g,l,U,S].map(p)).filter(Boolean).length&&c.push("Missing value definition for matchUps: matchUpValue, collectionValue, or collectionValueProfiles"),g&&"number"!=typeof g&&c.push(`matchUpValue is not type number: ${g}`),l&&"number"!=typeof l&&c.push(`collectionValue is not type number: ${l}`),u&&f){const t=zf({collectionValueProfiles:u,matchUpCount:f});t.errors&&c.push(...t.errors)}if(d&&"number"!=typeof d&&c.push(`collectionGroupNumber is not type number: ${l}`),h&&!lh.isValidMatchUpFormat(h)&&c.push(`Invalid matchUpFormat: ${h}`),r){const t=oh({referenceGender:a,matchUpType:I,gender:v});if(t.error)return wr({context:{referenceGender:a,gender:v},result:t,stack:s})}if(t&&i&&y){const t=ph({category:i,childCategory:y});if(!t.valid)return wr({result:{error:bn},context:t,stack:s})}return c.length?wr({result:{errors:c,error:Tn},stack:s}):{valid:!0}}function fh(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=[];if(!t||!i||"object"!=typeof i)return s.push("tieFormat must be an object"),wr({result:{error:Lt},context:{tieFormat:i,errors:s},stack:o});if("object"!=typeof i.winCriteria)return s.push("tieFormat.winCriteria must be an object"),wr({result:{error:Lt},context:{tieFormat:i,errors:s},stack:o});if(!Array.isArray(i.collectionDefinitions))return s.push(Pf("tieFormat.collectionDefinitions")),wr({result:{error:Lt},context:{tieFormat:i,errors:s},stack:o});let c;const u=i.collectionDefinitions.every((i=>{const{setValue:o,scoreValue:u,collectionValue:d}=i;!o&&!u||d||(c=!0);const{valid:p,errors:l}=mh({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)})),d="number"==typeof i.winCriteria?.valueGoal&&i.winCriteria?.valueGoal>0&&!c||i.winCriteria?.aggregateValue;if(!d&&!i.winCriteria?.aggregateValue)return c?s.push("aggregateValue is required"):s.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),wr({context:{tieFormat:i,errors:s,aggregateValueImperative:c},result:{error:Lt},stack:o});const p=i.collectionDefinitions.map((({collectionId:t})=>t)),l=!r||p.length===m(p).length,f=u&&d&&l;return f?{valid:f,errors:s}:wr({result:{error:Lt},context:{tieFormat:i,errors:s},stack:o})}function hh({tieFormat:t,isMock:e,uuids:n}){const{collectionDefinitions:r}=t??{};return{tieMatchUps:(r??[]).map((t=>gh({collectionDefinition:t,uuids:n,isMock:e}))).filter(Boolean).flat()}}function gh({collectionPositionOffset:t=0,collectionDefinition:e,matchUpsLimit:n,isMock:r,uuids:i}){const{matchUpCount:a,matchUpType:o,collectionId:s,processCodes:c}=e||{};return w(0,n??a??0).map((e=>{const n=t+e+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:i?.pop()??Md(),matchUpStatus:ja,collectionPosition:n,collectionId:s,processCodes:c,matchUpType:o,isMock:r}}))}function Ih(t){if(!t)return{};const e=[],n=t.tieFormatName,r=t.collectionDefinitions?.map((t=>{const{matchUpType:n,matchUpFormat:r,matchUpCount:i,category:a,gender:o}=t;e.includes(r)||e.push(r);const s=a?.ageCategoryCode;return[i,n===Js?"D":"S",s,r,o].join(";")})).join("|");return{tieFormatName:t&&n||"UNNAMED",matchUpFormats:e,tieFormatDesc:r}}function Uh({considerations:t={},descendant:e,ancestor:n}){const r={},i={},{matchUpFormats:a,tieFormatDesc:o}=Ih(e),{matchUpFormats:s,tieFormatDesc:c}=Ih(n),u=m((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})))),f=Object.assign({},...(n?.collectionDefinitions||[]).map((t=>({[t.collectionId]:t}))));r.collectionIds=D(Object.keys(l),Object.keys(f)),i.collectionIds=D(Object.keys(f),Object.keys(l)),r.collectionsValue=Sh(l),i.collectionsValue=Sh(f),r.groupsCount=n?.collectionGroups?.length??(0-(e?.collectionGroups?.length??0)||0),i.groupsCount=r.groupsCount?-1*r.groupsCount:0;const h=r.collectionsValue.totalValue-i.collectionsValue.totalValue,g=r.collectionsValue.totalMatchUps-i.collectionsValue.totalMatchUps,I=i.collectionsValue.assignmentValues.length!==r.collectionsValue.assignmentValues.length,U=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))))})),S=d||p||c!==o||I||U||0!==h,y=[...i.collectionsValue.invalidValues,...r.collectionsValue.invalidValues],v=y.length&&y;return{matchUpFormatDifferences:u,matchUpCountDifference:g,descendantDifferences:r,ancestorDifferences:i,orderDifference:p,valueDifference:h,nameDifference:d,descendantDesc:o,ancestorDesc:c,...E,different:S,invalid:v}}function Sh(t){const e=[],n=[];let r=0;return{totalValue:Object.keys(t).sort(Hl).reduce(((i,a)=>{const o=t[a],{collectionValueProfiles:s,collectionValue:c,matchUpCount:u,matchUpValue:d,scoreValue:l,setValue:m}=o,f={collectionValueProfiles:s,collectionValue:c,matchUpValue:d,scoreValue:l,setValue:m},h=Object.keys(f).filter((t=>![void 0,null].includes(f[t])));1!==h.length&&e.push({collectionId:a});const g=h[0];if(g){const t="collectionValueProfiles"===g?Object.values(s):f[g];n.push({valueKey:g,value:t})}return r+=u,s?i+s.reduce(((t,e)=>t+e.value),0):u?p(d)?i+d*u:p(l)?i+l*u:p(m)?i+m*u:i+c:i}),0),totalMatchUps:r,invalidValues:e,assignmentValues:n}}function yh({matchUp:t,updateInProgressMatchUps:e}){return!t.winningSide&&![Ya].includes(t.matchUpStatus)&&(e||t.matchUpStatus!==xa&&!$s(t))}function vh({from:t,to:e}){const n=Object.keys(t),r=P(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 wh({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===ja)).map(Ua("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 Th({drawDefinition:t,auditData:e}){const{extension:n}=Mr({name:ua,element:t});Nr({element:t,extension:{name:ua,value:Array.isArray(n?.value)?n?.value.concat(e):[e]}})}function Ph({updateInProgressMatchUps:t=!1,tournamentRecord:e,collectionOrder:n,collectionName:r,tieFormatName:i,drawDefinition:a,matchUpFormat:o,matchUpCount:s,collectionId:c,matchUpType:u,structureId:d,matchUpId:l,category:m,eventId:f,gender:h,event:I,collectionValueProfiles:U,collectionValue:S,matchUpValue:y,scoreValue:v,setValue:w}){const T="modifyCollectionDefinition";if(o&&!rh(o))return wr({result:{error:Nn},context:{matchUpFormat:o},stack:T});if(r&&"string"!=typeof r)return wr({result:{error:Nn},context:{collectionName:r},stack:T});if(h&&!Object.values(zp).includes(h))return wr({result:{error:Nn},context:{gender:h},stack:T});if(m&&"object"!=typeof m)return wr({result:{error:Nn},context:{category:m},stack:T});const D={collectionValueProfiles:U,collectionValue:S,matchUpValue:y,scoreValue:v,setValue:w};if(!(Object.values(D).filter(Boolean).length||n||r||o||s||u))return wr({result:{error:ae},stack:T});if(Object.values(D).filter(Boolean).length>1)return wr({info:"Only one value assignment allowed per collectionDefinition",result:{error:Nn},stack:T});let b=Zf({drawDefinition:a,structureId:d,matchUpId:l,eventId:f,event:I});if(b.error)return wr({result:b,stack:T});const{matchUp:N,structure:R,tieFormat:M}=b,A=Yf(M),C=M?.collectionDefinitions.find((t=>t.collectionId===c)),O=A?.collectionDefinitions.find((t=>t.collectionId===c));if(!C)return wr({info:"source collectionDefinition",result:{error:On},context:{collectionId:c},stack:T});const F=S??y??v??w;if(U){const t=zf({matchUpCount:s??C?.matchUpCount??0,collectionValueProfiles:U});if(t.errors)return wr({result:{error:Nn},info:t.errors,stack:T})}else if(F&&!p(F))return wr({result:{error:Nn},info:"value is not an integer",context:{value:F},stack:T});const k=U&&(!C.collectionValueProfiles||(x=C.collectionValueProfiles,_=U,!(P(Object.keys(x),Object.keys(_)).length===Object.keys(x).length&&P(Object.values(x),Object.values(_)).length===Object.values(x).length)));var x,_;const L=[];if((p(S)&&C.collectionValue!==S||p(y)&&C.matchUpValue!==y||p(v)&&C.scoreValue!==v||p(w)&&C.setValue!==w||k)&&(O.collectionValueProfiles=void 0,O.collectionValue=void 0,O.matchUpValue=void 0,O.scoreValue=void 0,O.setValue=void 0,Object.assign(O,D),L.push({collectionId:c,...vr(D)})),(p(v)||p(w))&&O.collectionGroupNumber){const t=O.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:c,change:"collectionGroupNumber removed"})}const{aggregateValue:B,valueGoal:V}=Jf(A),G=vr({aggregateValue:B,valueGoal:V});if(G.aggregateValue===M?.winCriteria.aggregateValue&&G.valueGoal===M?.winCriteria.valueGoal||(A.winCriteria=G,L.push({collectionId:c,winCriteria:G})),p(n)&&C.collectionOrder!==n&&(O.collectionOrder=n,L.push({collectionId:c,collectionOrder:n})),r&&C.collectionName!==r&&(O.collectionName=r,L.push({collectionId:c,collectionName:r})),o&&C.matchUpFormat!==o&&(O.matchUpFormat=o,L.push({collectionId:c,matchUpFormat:o})),p(s)&&C.matchUpCount!==s&&(O.matchUpCount=s,L.push({collectionId:c,matchUpCount:s})),u&&C.matchUpType!==u)return wr({result:{error:Fn},context:{matchUpType:u},stack:T});m&&C.category!==m&&(O.category=m,L.push({collectionId:c,category:m})),h&&C.gender!==h&&(O.gender=h,L.push({collectionId:c,gender:h}));const q=vr(A);if(b=fh({tieFormat:q}),b.error)return wr({result:b,stack:T});if(!L.length)return wr({result:{...E,modifications:L}});if(M?.tieFormatName!==i?(q.tieFormatName=i,L.push({tieFormatName:i})):L.length&&(delete q.tieFormatName,L.push("tieFormatName removed: modifications without new tieFormatName")),b=function({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:n,structure:r,tieFormat:i,eventId:a,matchUp:o,event:s,uuids:c}){const u="updateTieFormat",d=e?.tournamentId;let p=0,l=0,m=0,f=0;const h=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 vh({from:e,to:h}).equivalent},U=Zf({drawDefinition:n})?.tieFormat,S=Zf({event:s})?.tieFormat;if(s&&a){for(const t of s.drawDefinitions??[])y({drawDefinition:t});s.tieFormat=Yf(i),f+=1}else if(o){if(!o.tieMatchUps)return wr({result:{error:Yt},stack:u});const e=g(o.tieMatchUps?.map((({collectionId:t})=>t))),r=vh({to:h,from:e}),{changes:a,changesArePossible:p,cannotChangeReaon:m}=wh({matchUp:o,check:r});if(r.equivalent){if(!yh({matchUp:o,updateInProgressMatchUps:t}))return wr({result:{error:Ue},info:"matchUp is IN_PROGRESS or COMPLETE",stack:u});o.tieFormat=Yf(i),f+=1}else{if(!p)return wr({context:{collectionMap:h,matchUpMap:e},result:{error:Lt},info:m||"specified changes not possible",stack:u});w({tieFormat:i,matchUp:o,changes:a,uuids:c})}l+=1,xs({eventId:s?.eventId,context:u,drawDefinition:n,tournamentId:d,matchUp:o})}else if(r){const t=U??S,e=v({inheritedTieFormat:t,structure:r})?.modifiedMatchUpsCount;e&&(l+=e,p+=1,f+=1);const a=!r.tieFormat||Uh({ancestor:r.tieFormat,descendant:i}).different;a&&(r.tieFormat=Yf(i),p+=1,f+=1),(e||a)&&n&&Ls({structureIds:[r.structureId],eventId:s?.eventId,drawDefinition:n})}else{if(!n)return{error:j};y({drawDefinition:n}),n.tieFormat=Yf(i),f+=1}return{modifiedStructuresCount:p,modifiedMatchUpsCount:l,addedMatchUpsCount:m,modifiedCount:f,...E,tieFormat:i};function y({drawDefinition:t}){const e=t.structures||[],n=[];for(const t of e){if(t.tieFormat)continue;const e=S,r=v({inheritedTieFormat:e,structure:t})?.modifiedMatchUpsCount;if(r){p+=1,l+=r;const e=t.structureId;n.push(e)}}return Ls({structureIds:n,eventId:s?.eventId,drawDefinition:t}),n.length}function v({inheritedTieFormat:r,structure:o}){let s=0;const d=Yp({matchUpFilters:{matchUpTypes:[Qs]},structure:o})?.matchUps||[];for(const o of d){const d=yh({matchUp:o,updateInProgressMatchUps:t});let p=!1;const l=vh({from:g(o.tieMatchUps?.map((({collectionId:t})=>t))),to:h});if(l.equivalent)o.tieFormat&&I(o)&&d&&(o.tieFormat=Yf(i),p=!0);else{const{changes:t,changesArePossible:e}=wh({matchUp:o,check:l});if(e&&!o.tieFormat)w({changes:t,matchUp:o,tieFormat:i,uuids:c});else{if(!r)return wr({result:{error:Gt},stack:u});(!o.tieFormat||Uh({ancestor:r,descendant:o.tieFormat}).different)&&(o.tieFormat=r,p=!0)}}p&&(s+=1,xs({tournamentId:e?.tournamentId,drawDefinition:n,context:u,eventId:a,matchUp:o}))}return{modifiedMatchUpsCount:s}}function w({uuids:t,matchUp:e,tieFormat:r,changes:i}){e.tieFormat=Yf(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(Ua("collectionPosition"))),a=r.collectionDefinitions.find((t=>t.collectionId===n.collectionId)),o=gh({matchUpsLimit:n.countChange,collectionPositionOffset:i,collectionDefinition:a,uuids:t});s.push(...gi(o,!1,!0)),m+=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&&Fs({matchUps:s,drawDefinition:n,tournamentId:d,eventId:a}),o.length&&ks({matchUpIds:o,action:"updateTieFormat",drawDefinition:n,tournamentId:d,eventId:a}),{matchUpIdsRemoved:o,matchUpsAdded:s}}}({tieFormat:q,updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:a,structure:R,eventId:f,matchUp:N,event:I}),!b.error){const{appliedPolicies:t}=Dc({tournamentRecord:e});if(t?.audit?.[ua]){Th({drawDefinition:a,auditData:vr({collectionDefinition:O,drawId:a?.drawId,action:T,structureId:d,matchUpId:l,eventId:f})})}}return wr({result:{...b,modifications:L},stack:T})}function Dh({tournamentRecord:t,drawDefinition:e,drawPositions:n,structureId:r,event:i}){if(!e)return{error:j};if(!r)return{error:It};if(2!==n?.length)return{error:Nn,drawPositions:n};const a=xc({drawDefinition:e}),{matchUps:o}=Jp({inContext:!0,drawDefinition:e,matchUpsMap:a}),{structure:s}=ts({drawDefinition:e,structureId:r});if(!s)return{error:Ut};let c;if(c=s.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{...E};if(2===s.filter((({qualifier:t})=>t)).length)return{...E};Nf({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)bh({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:s,matchUpsMap:i,structure:a,event:o});else{const t=gi(s,!1,!0);s.forEach(((e,n)=>{const r=t[1-n].participantId;e.qualifier=t[1-n].qualifier,e.participantId=r}))}return{...E}}({inContextDrawMatchUps:o,tournamentRecord:t,drawDefinition:e,drawPositions:n,matchUpsMap:a,structure:s,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:Nn,structure:a,info:"Missing positionAssignments"};if(2===s.filter((({bye:t})=>t)).length)return{...E};if(2===s.filter((({qualifier:t})=>t)).length)return{...E};const c=s.some((({qualifier:t})=>t));return s.some((({bye:t})=>t))&&!c?bh({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;return{[n]:{...r[1-e],drawPosition:n}}})));return a.positionAssignments=a.positionAssignments.map((t=>s[t.drawPosition]||t)),Nf({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:i,assignments:r,structure:a,event:o}),{...E}}({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:s,matchUpsMap:i,structure:a,event:o})}({inContextDrawMatchUps:o,tournamentRecord:t,drawDefinition:e,drawPositions:n,matchUpsMap:a,structure:s,event:i}),c.error)return c;js({structure:s,drawPositions:n});if(Gs({drawDefinition:e,positionAction:{name:"swapDrawPositionAssignments",drawPositions:n,structureId:r}}),Vs({tournamentId:t?.tournamentId,drawDefinition:e,structure:s,event:i}),i.eventType===ad){const r=Yp({matchUpFilters:{matchUpTypes:[Xs]},inContext:!0,structure:s}).matchUps.filter((t=>t.drawPositions?.some((t=>n.includes(t))))),a=Yp({structure:s,matchUpFilters:{matchUpTypes:[Xs]}}).matchUps;r.forEach((r=>{(r.sides||[]).forEach((o=>{const s=o?.drawPosition;if(n.includes(s)){const n=o.participantId,c=a.find((({matchUpId:t})=>t===r.matchUpId)),u=r?.sides?.reduce(((t,e,n)=>e.drawPosition===s?n:t),void 0);rf({inContextTargetMatchUp:r,drawPositionSideIndex:u,teamParticipantId:n,tournamentRecord:t,drawDefinition:e,matchUp:c,event:i})}}))}))}return Ls({drawDefinition:e,structureIds:[r]}),{...E}}function bh({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=ym({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:l,matchUpsMap:i});return m.error?m:(m=ym({drawPosition:p,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:l,matchUpsMap:i}),m.error?m:(bl({drawPosition:p,tournamentRecord:e,drawDefinition:n,structureId:l,matchUpsMap:i,event:o}),m=Rf({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:l,participantId:d,matchUpsMap:i,event:o}),m.error?m:{...E}))}function Nh({drawDefinition:t,structureId:e}){if(!t)return{error:j};const{structure:n}=ts({drawDefinition:t,structureId:e}),r=(t?.links||[]).filter((t=>t.source?.structureId===e)).map((t=>t.target?.structureId));return{playoffStructures:(t?.structures||[]).filter((t=>r.includes(t.structureId))),structure:n}}function Rh({withStageGrouping:t,stageSequences:e,stageSequence:n,roundTarget:r,stages:i,event:a,stage:o}){if(!a)return{error:Tt};const s={},c=[];for(const u of a.drawDefinitions||[]){const{structures:a,stageStructures:d}=es({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 Mh(t){if(!t?.drawDefinition)return!1;const e=Kp(t),n=e?.includesTeamMatchUps;let{completedMatchUps:r,pendingMatchUps:i,upcomingMatchUps:a}=e||{};n&&(r=r?.filter((({matchUpType:t})=>t===Qs)),i=i?.filter((({matchUpType:t})=>t===Qs)),a=a?.filter((({matchUpType:t})=>t===Qs)));return!!(r?.length&&!i?.length&&!a?.length)}function Ah({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=Ah({accessors:a,significantCharacters:t,value:e});r.push(...n)}))}else if(n=n[i],a.length){const e=Ah({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 Eh({policyAttributes:t,idCollections:e,participants:n,participant:r}){if(!Array.isArray(t))return{error:Xt};if(!r)return{error:Re};const i=[];t.forEach((t=>{const{directive:a,groupings:o,key:s,significantCharacters:c}=t||{};if(s){const t=s.split(".");i.push(...Ah({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:m(i)}}function Ch({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}=Eh({participants:e,policyAttributes:n,idCollections:r,participant:a});return{...t,values:o}}))}function Oh({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 Fh(t){const{unfilledPositions:e,chunkedDrawPositions:n}=t,r=Oh(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=kh(e);return!t.includes(n)}}(n),a=n.filter((t=>!i.includes(t))).filter((t=>{const e=kh(t);return!r[e]?.includesGroupsToAvoid}));return{unassigned:n,unpaired:i,pairedNoConflict:a}}))}function kh(t){return Number(t%2?t+1:t-1)}function xh({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=Oh(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}):Fh({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 _h({positionAssignments:t,participantIds:e}){const n=t.map((t=>t.participantId));return e.filter((t=>!n.includes(t)))}function Lh({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=_h({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=v(n?s:Object.keys(a));return{participantId:(i=t&&a[i]?.length?i:c)&&a[i]?v(a[i]):v(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=xh({positionAssignments:t,isRoundRobin:c,selectedParticipantGroups:m,participantIdGroups:n,drawPositionChunks:r,unfilledPositions:d}),{unassigned:h,unpaired:g,pairedNoConflict:I}=f,U=I?.length&&I[0],S=g?.length&&g[0],w=a&&U?U:S,T=a?S:U,P=w?.length&&w||T?.length&&T;let D;if(P?.length){const t=y(P);D=y(t)}else{const t=y(h[0]);D=y(t)}return{newGroupKey:l,selectedParticipantId:p,targetDrawPosition:D}}function Bh({isRoundRobin:t,groupedParticipants:e}){const n=[];return t?e.forEach((t=>{const e=t.map((t=>t.drawPosition)),{uniqueMatchUpGroupings:r}=sf({drawPositions:e}),i=Object.assign({},...t.map((t=>({[t.drawPosition]:t}))));r.forEach((e=>{b(i[e[0]].values||[],i[e[1]].values||[])&&(n.push(e),t.conflict=!0)}))})):e.forEach((t=>{b(t[0]?.values||[],t[1]?.values||[])&&(n.push(t),t.conflict=!0)})),n}function Vh({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=Bh({isRoundRobin:i,groupedParticipants:[[r,o]]}),c=t.find((t=>t.drawPosition===e)),u=Bh({isRoundRobin:i,groupedParticipants:[[c,o]]});return!s.length&&!u.length}));if(o.length)return{drawPosition:r.drawPosition,possibleDrawPositions:o}})).filter(Boolean)})).flat(1)}function jh(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=gi(e,!1,!0).filter((t=>!t.qualifier)),f=e.filter((t=>!t.participantId&&(!t.bye||i?.includes(t.drawPosition)))).map((t=>t.drawPosition));w(0,r).forEach((()=>{const{newGroupKey:e,selectedParticipantId:n,targetDrawPosition:r}=Lh({...t,candidatePositionAssignments:m,allGroups:c,groupKey:d});d=e,m.forEach((t=>{t.drawPosition===r&&(t.participantId=n)}))}));let h=Ch({candidatePositionAssignments:m,participantsWithGroupings:n,policyAttributes:o,idCollections:s}),g=N(h,p),I=Bh({groupedParticipants:g,isRoundRobin:l}),U=0;for(;U<20&&I.length;){const t=Vh({positionedParticipants:h,potentialDrawPositions:f,avoidanceConflicts:I,drawPositionGroups:a,isRoundRobin:l});if(t.length){const e=Gh({candidatePositionAssignments:m,swapOptions:t});e.error&&console.log({result:e}),h=Ch({candidatePositionAssignments:m,participantsWithGroupings:n,policyAttributes:o,idCollections:s}),g=N(h,p),I=Bh({groupedParticipants:g,isRoundRobin:l}),U++}else U=20}return m.forEach((t=>{if(t.bye&&t.participantId){const t=pt;u.push(t)}if(t.qualifier&&t.participantId){const t=pt;u.push(t)}})),{positionAssignments:m,conflicts:I.length,groupedParticipants:g,errors:u}}function Gh({candidatePositionAssignments:t,swapOptions:e}){const n=y(e);if(!n)return{error:{message:"No swap options"}};const r=n.drawPosition,i=y(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),{...E}}function qh({provisionalPositioning:t,unseededParticipantIds:n,inContextDrawMatchUps:i,unseededByePositions:a,tournamentRecord:s,drawDefinition:c,seedBlockInfo:u,participants:d,matchUpsMap:p,structureId:l,avoidance:m,drawSize:f,event:h}){if(!m)return{error:Zt};const{candidatesCount:g=1,policyAttributes:I,targetDivisions:U}=m;let{roundsToSeparate:S}=m;const y="randomUnseededSeparation",{structure:v}=ts({drawDefinition:c,structureId:l}),{matchUps:T}=Yp({provisionalPositioning:t,matchUpsMap:p,structure:v,event:h});if(U&&r(U)&&!S){const t=function(t){if(!r(t))return!1;let e=t,n=1;for(;2!==e;)n+=1,e/=2;return n}(U)||0,e=T.reduce(((t,e)=>e.roundNumber>t?e.roundNumber:t),0);S=e<t?1:e-t+1}const{positionAssignments:P}=is({structure:v}),D=mc({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:d}).participantsWithGroupings,b=P?.filter((t=>!t.participantId)),R=P?.map((t=>t.drawPosition)),M=v?.structureType===mo,A=M?{structure:v,matchUps:T,allDrawPositions:R,roundsToSeparate:S}:{matchUps:T,allDrawPositions:R,roundsToSeparate:S},{drawPositionGroups:C,drawPositionChunks:O}=M?function(t){const{structure:{structures:e}}=t,n=e.map((t=>t.positionAssignments.map((t=>t.drawPosition))));return{drawPositionGroups:n,drawPositionChunks:[n]}}(A):function({allDrawPositions:t,roundsToSeparate:n,matchUps:r}){const i=r.filter((t=>1===t.roundNumber)).map((t=>t.drawPositions)),a=i.flat().sort(e),s=Math.max(...a),c=t.filter((t=>t>s)),u=a.length,d=w(2===u?1:2,u).filter((t=>t===o(t))),p=d.slice(0,n||d.length).reverse(),l=p.map((t=>N(a,t)));c.length&&console.log({fedDrawPositions:c});return{drawPositionGroups:i,drawPositionChunks:l}}(A),F={groupParticipants:d.filter((t=>t.participantType===cc)).map((t=>t.participantId)),teamParticipants:d.filter((t=>t.participantType===dc)).map((t=>t.participantId)),pairParticipants:d.filter((t=>t.participantType===uc)).map((t=>t.participantId))},k=function({targetParticipantIds:t,policyAttributes:e,idCollections:n,participants:r}){if(!Array.isArray(e))return{error:Xt};if(!Array.isArray(r))return{error:Me};const i={};return t.forEach((t=>{const a=r.find((e=>e.participantId===t)),{values:o}=Eh({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:n,policyAttributes:I,idCollections:F,participants:d});if(k.error)return wr({result:k,stack:y});const x=Object.assign({},...n.map((t=>{const e=Object.keys(k).filter((e=>(k[e]??[]).includes(t)));return{[t]:e}}))),_=_h({participantIds:n,positionAssignments:P});if(_.length>(b?.length||0))return{error:Ke};let L;const B=_.length,V=w(0,g).map((()=>jh({initialPositionAssignments:P,participantsWithGroupings:D,unseededParticipantIds:n,opponentsToPlaceCount:B,pairedPriority:!1,unseededByePositions:a,participantIdGroups:x,drawPositionChunks:O,drawPositionGroups:C,policyAttributes:I,idCollections:F,allGroups:k,drawSize:f})));if(L=V.reduce(((t,e)=>!t||(e.conflicts||0)<(t.conflicts||0)?e:t),void 0),!L||L.conflicts){const t=w(0,g).map((()=>jh({initialPositionAssignments:P,participantsWithGroupings:D,unseededParticipantIds:n,opponentsToPlaceCount:B,pairedPriority:!0,unseededByePositions:a,participantIdGroups:x,drawPositionChunks:O,drawPositionGroups:C,policyAttributes:I,idCollections:F,allGroups:k,drawSize:f})));L=V.concat(...t).filter((t=>!t.errors?.length)).reduce(((t,e)=>!t||(e.conflicts||0)<(t.conflicts||0)?e:t),void 0)}if(!L)return{error:vn};const j=(rs({structure:v})?.positionAssignments??[]).filter((t=>t.participantId)).map((t=>t.participantId)),G=L.positionAssignments.filter((t=>!j.includes(t.participantId)));for(const t of G)if(t.bye){const e=bl({tournamentRecord:s,drawDefinition:c,seedBlockInfo:u,structureId:l,matchUpsMap:p,event:h,...t});if(e.error)return wr({result:e,stack:y})}else if(t.participantId){const e=Rf({automaticPlacement:!0,inContextDrawMatchUps:i,tournamentRecord:s,drawDefinition:c,seedBlockInfo:u,structureId:l,matchUpsMap:p,event:h,...t});if(e.error)return wr({result:e,stack:y,context:{assignment:t}})}return{...E}}function $h({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}=ts({drawDefinition:a,structureId:u})),u||({structureId:u}=d);const{positionAssignments:m}=is({structure:d}),{seedAssignments:h}=lu({provisionalPositioning:t,drawDefinition:a,structure:d}),g=h?.map((t=>t.participantId)).filter(Boolean),{stage:I,stageSequence:U}=d,S=I===Qa?Mr({element:d,name:ra})?.extension?.value:void 0,y=pu({provisionalPositioning:t,drawDefinition:a,stageSequence:U,entryStatuses:au,structureId:u,roundTarget:S,stage:I}),v=y.filter((t=>!g?.includes(t.participantId))).map((t=>t.participantId)),w=m?.filter((t=>!t.participantId&&!t.bye&&!t.qualifier)).map((t=>t.drawPosition));if(!r&&v.length>(w?.length||0))return wr({result:{error:Ke},context:{unseededParticipantsCount:v.length,unfilledDrawPositionsCount:w?.length},stack:"positionUnseededParticipants"});const{appliedPolicies:T}=Dc({tournamentRecord:i,drawDefinition:a,event:l});let P=T?.[Ri];if(d.stage===no){const t=y.reduce(((t,e)=>(t[e.groupingValue]||(t[e.groupingValue]=[]),t[e.groupingValue].push(e.participantId),t)),{});Object.keys(t).length&&(P||(P={policyName:"Playoff Avoidance"}),P.policyAttributes||(P.policyAttributes=[]),P.policyAttributes.push({groupings:t}))}return P&&s?qh({provisionalPositioning:t,unseededParticipantIds:v,inContextDrawMatchUps:e,unseededByePositions:n,tournamentRecord:i,drawDefinition:a,seedBlockInfo:o,participants:s,matchUpsMap:c,structureId:u,avoidance:P,drawSize:p,entries:y}):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?f(r):r.reverse();for(const r of e){const e=l.pop();if(!i||e){const i=Rf({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 wr({result:i,stack:"randomUnseededDistribution"})}}return{...E}}({provisionalPositioning:t,unseededParticipantIds:v,inContextDrawMatchUps:e,unfilledDrawPositions:w,multipleStructures:r,tournamentRecord:i,drawDefinition:a,seedBlockInfo:o,structureId:u,matchUpsMap:c,drawSize:p,event:l})}function Wh(t){const e=t.structure??ts(t).structure,r="positionQualifiers",i=[];if(e.stage===to)return wr({result:{error:At},stack:r});const{unplacedRoundQualifierCounts:a,positionAssignments:o,roundDrawPositions:s}=function({drawDefinition:t,structure:e,structureId:r}){e||({structure:e}=ts({drawDefinition:t,structureId:r}));r||({structureId:r}=e);const{positionAssignments:i}=is({structure:e}),{stage:a,stageSequence:o}=e,{qualifiersCount:s,roundQualifiersCounts:c}=Ql({drawDefinition:t,stageSequence:o,structureId:r,stage:a}),u=(c?Object.keys(c):[]).map((t=>n(t))),{matchUps:d}=Yp({structure:e}),{roundProfile:p}=vc({matchUps:d}),l=Object.assign({},...u.filter((t=>p?.[t])).map((t=>({[t]:p?.[t]?.drawPositions?.filter(Boolean)??[]})))),m=i?.filter((t=>t.qualifier)).map((t=>t.drawPosition)),f=s-(m?.length??0),h=m?.length,g=Object.assign({},...u.map((t=>{const e=i?.filter((e=>e.qualifier&&l[t]?.drawPositions?.includes(e.drawPosition))).map((t=>t.drawPosition));return{[t]:(c?.[t]??0)-(e?.length??0)}})));return{unplacedRoundQualifierCounts:g,unplacedQualifiersCount:f,placedQualifiersCount:h,roundQualifiersCounts:c,positionAssignments:i,roundDrawPositions:l,qualifiersCount:s}}(t);for(const t of Object.keys(a)){const e=o?.filter((e=>s[t].includes(e.drawPosition)&&!e.participantId&&!e.qualifier&&!e.bye)).map((t=>t.drawPosition));if(a[t]>(e||0))return wr({result:{error:Ye},context:{unfilledDrawPositions:e},stack:r});w(0,a[t]).forEach((()=>{const t=y(e);i.push(t),o?.forEach((e=>{e.drawPosition===t&&(e.qualifier=!0,delete e.participantId,delete e.bye)}))}))}return{...E,qualifierDrawPositions:i}}function Hh({orderedSortedFirstRoundSeededDrawPositions:t,validSeedBlocks:e,byesToPlace:n}){const r=[];e.forEach((e=>{if(n-r.length>e.drawPositions.length)r.push(...e.drawPositions);else{const n=Yh(N(e.drawPositions,2));let i,a=t[r.length];for(;i=zh(n,a);)r.push(i),a=t[r.length]}}));const i=r.map((t=>Array.isArray(t)?f(t):t)).flat(1/0);if(c(n)){if(e.map((t=>t.seedNumbers[0])).includes(n))return t}return i}function zh(t,e){if(Array.isArray(t)&&2!==t.length)return t.pop();if(!Array.isArray(t[0]))return t.includes(e)?t.indexOf(e)?t.pop():t.shift():Math.round(Math.random())?t.pop():t.shift();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 zh(e?n:t[Math.round(Math.random())],e)}return zh(n<r?t[1]:t[0],e)}function Yh(t){const e=Math.floor(t.length/2);return t.length>2?[Yh(t.slice(0,e)),Yh(t.slice(e))]:t}function Kh({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:n,drawDefinition:r,seedingProfile:i,seedBlockInfo:a,byesToPlace:o,structure:s}){a||(a=gf({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}=is({structure:n}),{seedAssignments:i}=lu({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})??[],f=m([].concat(...e.map((t=>t.drawPositions)))),h=l.filter((t=>f.includes(t.drawPosition))),g=(t,e)=>of(t.seedValue)-of(e.seedValue),I=p.reduce(((t,e)=>{const n=h.filter((t=>e.drawPositions?.includes(t.drawPosition))).sort(g);return t.concat(...n)}),[]).map((t=>t.drawPosition)),U=Hh({orderedSortedFirstRoundSeededDrawPositions:I,validSeedBlocks:p,byesToPlace:o});return{strictSeedOrderByePositions:Jh({orderedSeedDrawPositions:I,relevantMatchUps:e}).slice(0,o),blockSeedOrderByePositions:Jh({orderedSeedDrawPositions:U,relevantMatchUps:e}).slice(0,o),isLuckyStructure:u,positionedSeeds:l,isContainer:d,isFeedIn:c}}function Jh({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 Zh({provisionalPositioning:t,tournamentRecord:n,appliedPolicies:r,drawDefinition:i,seedBlockInfo:a,seedingProfile:o,matchUpsMap:s,structureId:c,structure:u,seedLimit:d,seedsOnly:p,event:l}){u||({structure:u}=ts({drawDefinition:i,structureId:c})),c||(c=u?.structureId);const h=!(u?.structures??u?.stage===Qa),{byesCount:g,placedByes:I,relevantMatchUps:U}=function({provisionalPositioning:t,drawDefinition:e,matchUpsMap:n,structure:r,event:i}){const{matchUps:a,roundMatchUps:o}=Yp({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=pu({entryStatuses:ou,provisionalPositioning:t,drawDefinition:e,stageSequence:m,structureId:p,stage:l}),{qualifiersCount:h}=Ql({provisionalPositioning:t,drawDefinition:e,stageSequence:m,structureId:p,stage:l}),g=f.length+h,{positionAssignments:I,unassignedPositions:U}=is({structure:r}),S=U?.map((t=>t.drawPosition)),y=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=>S?.includes(t))),T=I?.length;let P=T?T-g:0;return P>d&&1===r.stageSequence&&r.stage!==to&&(P=d),{placedByes:y,byesCount:P,relevantMatchUps:u,placedByePositions:v,roundMatchUps:o,positionsToAvoidDoubleBye:w}}({provisionalPositioning:t,drawDefinition:i,matchUpsMap:s,structure:u,event:l}),S=g-(I||0);if(S<=0)return{...E};const{strictSeedOrderByePositions:y,blockSeedOrderByePositions:v,isLuckyStructure:w,isFeedIn:T}=Kh({provisionalPositioning:t,relevantMatchUps:U,appliedPolicies:r,drawDefinition:i,seedingProfile:o,seedBlockInfo:a,byesToPlace:S,structure:u}),P=u?.structureType&&[mo,lo].includes(u.structureType)&&r?.seeding?.containerByesIgnoreSeeding,D=h&&v?.length?v:y;let{unseededByePositions:b}=function({provisionalPositioning:t,seedOrderByePositions:n,isLuckyStructure:r,appliedPolicies:i,drawDefinition:a,seedLimit:o,structure:s,isFeedIn:c}){const u=i?.seeding?.seedingProfile,d=s.stage===Qa,{positionAssignments:p}=is({structure:s}),l=p?.filter((t=>t.participantId)).map((t=>t.drawPosition)),{matchUps:h,roundMatchUps:g}=Yp({provisionalPositioning:t,matchUpFilters:{isCollectionMatchUp:!1},structure:s}),I=g?.[1]||[],U=s.structureType===mo?h:I,S=m([].concat(...U.map((t=>t.drawPositions)))),y=Math.min(...S)-1,v=l?.filter((t=>S.includes(t))),w=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=f(n),[u,d]=!i||s?[n[o],n[1-o]]:[c[0],c[1]];return{greaterHalf:u,lesserHalf:d}},T=t=>{const{greaterHalf:e,lesserHalf:n}=w(t),{greaterHalf:r,lesserHalf:i}=w(e),a=f(r.flat(1/0)).pop();return{newlyFilteredChunks:[...n,...i,r.flat().filter((t=>t!==a))],drawPosition:a}},P=t=>!v?.includes(t),D=t=>{let n=N(t.sort(e),Math.ceil(t.length/4)).map((t=>t.filter(P)));const r=[].concat(...n.flat(1/0)).length,i=[];for(let t=0;t<r;t++){const{newlyFilteredChunks:t,drawPosition:e}=T(n);i.push(e),n=t}return i},{validSeedBlocks:b}=gf({provisionalPositioning:t,allPositions:!0,appliedPolicies:i,drawDefinition:a,structure:s}),R=b?.map((t=>t.drawPositions?.map((t=>t+y))));let M;if(c){const t=S.length,{seedBlocks:e}=mf({cluster:yf(u)===uo,participantsCount:t});M=e.map((t=>t.map((t=>t+y)))).map(D).filter((t=>t.length))}else M=d?R?.map((t=>t.filter(P))):R?.map(D).filter((t=>t.length));const A=U.map((t=>t.drawPositions)).map((t=>t?.sort(((t,e)=>t-e)))).filter((t=>t?.[0]+1===t?.[1])),E=t=>A.reduce(((e,n)=>n.includes(t)?n.reduce(((e,n)=>n!==t?n:e),void 0):e),void 0);let C=M.map((t=>t.map(E))).flat(1/0).filter(P).filter((t=>!n.includes(t))).filter(Boolean);if(d&&!s.structures){const t=o%4,e=C.slice(0,t),n=g[s.roundLimit]?.length,r=N(C.slice(t),n).map(f).flat();C=e.concat(r)}return{unseededByePositions:C}}({provisionalPositioning:t,seedOrderByePositions:D,isLuckyStructure:w,appliedPolicies:r,drawDefinition:i,seedLimit:d,structure:u,isFeedIn:T});let R=[].concat(...D);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=[])}P&&(R=f(R),Qn({ignoreSeededByes:P})&&console.log({byePositions:R}));const M=R.slice(0,S);for(const e of M){const r=bl({provisionalPositioning:t,tournamentRecord:n,drawDefinition:i,drawPosition:e,matchUpsMap:s,structureId:c,structure:u,event:l});if(r?.error)return r}return{...E,unseededByePositions:b,byeDrawPositions:M}}function Xh({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}=ts({drawDefinition:a,structureId:d})),d||(d=l?.structureId),r||(r=Dc({drawDefinition:a}).appliedPolicies),!i){const e=l&&gf({provisionalPositioning:t,appliedPolicies:r,drawDefinition:a,seedingProfile:o,structure:l});e?.error&&h.push(e.error),i=e?.validSeedBlocks}return w(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}=Sf({provisionalPositioning:t,randomize:!0,drawDefinition:r,seedingProfile:i,seedBlockInfo:a,structureId:s,event:u}),{appliedPolicies:l}=Dc({drawDefinition:r}),{avoidance:m}=l??{};const f=[];for(const o of d){const d=p.pop();if(!d)return{error:tt};f.push(d);const l=Rf({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{...E,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}:{...E,seedPositions:f}}function Qh({applyPositioning:t=!0,provisionalPositioning:e,inContextDrawMatchUps:n,multipleStructures:r,placeByes:i=!0,tournamentRecord:a,appliedPolicies:o,placementGroup:s,drawDefinition:c,seedingProfile:u,structureId:d,matchUpsMap:p,seedLimit:l,seedsOnly:m,drawType:f,drawSize:h,event:g}){const I=[];t||(Jn.disableNotifications(),c=gi(c,!1,!0));const U=e=>(t||nr(),wr({result:e,stack:"automatedPositioning"})),S=ts({drawDefinition:c,structureId:d});if(S.error)return U(S);const y=S.structure;if(!y)return{error:Ut};o||(o=Dc({drawDefinition:c,structure:y,event:g})?.appliedPolicies);const{qualifiersCount:v}=Ql({stageSequence:y.stageSequence,provisionalPositioning:e,stage:y.stage,drawDefinition:c,structureId:d}),w=au,T=pu({stageSequence:y.stageSequence,provisionalPositioning:e,stage:y.stage,placementGroup:s,drawDefinition:c,entryStatuses:w,structureId:d});if(!T?.length&&!v)return P={...E},t||nr(),P;var P;p=p??xc({drawDefinition:c}),n||({matchUps:n}=Jp({inContext:!0,drawDefinition:c,matchUpsMap:p}));let D=[];const b=gf({provisionalPositioning:e,appliedPolicies:o,drawDefinition:c,seedingProfile:u,structure:y});if(b.error)return b;const{validSeedBlocks:N}=b;I.push({validSeedBlocks:N});const R=a?Zl({withIndividualParticipants:!0,tournamentRecord:a})?.participants:[];if(yf(y.seedingProfile||u)===po){let t=i?Zh({provisionalPositioning:e,tournamentRecord:a,appliedPolicies:o,drawDefinition:c,seedBlockInfo:b,matchUpsMap:p,structure:y,seedLimit:l,seedsOnly:m,event:g}):void 0;if(t?.error)return U(t);D=t.unseededByePositions,I.push({action:"positionByes",unseededByePositions:D});if(t=Xh({seedingProfile:y.seedingProfile?{positioning:y.seedingProfile}:u,provisionalPositioning:e,inContextDrawMatchUps:n,tournamentRecord:a,appliedPolicies:o,validSeedBlocks:N,drawDefinition:c,seedBlockInfo:b,participants:R,matchUpsMap:p,structure:y,event:g}),t.error)return U(t);I.push({seedPositions:t.seedPositions,action:"positionSeedBlocks"})}else{if(f!==Ao){const t=Xh({seedingProfile:y.seedingProfile?{positioning:y.seedingProfile}:u,provisionalPositioning:e,inContextDrawMatchUps:n,tournamentRecord:a,appliedPolicies:o,validSeedBlocks:N,drawDefinition:c,seedBlockInfo:b,participants:R,matchUpsMap:p,structure:y,event:g});if(t.error)return U(t);I.push({action:"positionSeedBlocks",seedPositions:t.seedPositions})}const t=i?Zh({provisionalPositioning:e,tournamentRecord:a,appliedPolicies:o,drawDefinition:c,seedBlockInfo:b,matchUpsMap:p,structure:y,seedLimit:l,seedsOnly:m,event:g}):void 0;if(t?.error)return U(t);D=t?.unseededByePositions,I.push({action:"positionByes",byeDrawPositions:t?.byeDrawPositions,unseededByePositions:D})}const M={};if(!m){let t=Wh({inContextDrawMatchUps:n,tournamentRecord:a,appliedPolicies:o,validSeedBlocks:N,drawDefinition:c,seedBlockInfo:b,participants:R,matchUpsMap:p,structure:y});if(t.error)return U(t);if(t.conflicts&&(M.qualifierConflicts=t.conflicts),I.push({action:"positionQualifiers",qualifierDrawPositions:t.qualifierDrawPositions}),t=$h({provisionalPositioning:e,inContextDrawMatchUps:n,unseededByePositions:D,multipleStructures:r,tournamentRecord:a,drawDefinition:c,seedBlockInfo:b,participants:R,matchUpsMap:p,structureId:d,structure:y,drawSize:h,event:g}),t.error)return U(t);t.conflicts&&(M.unseededConflicts=t.conflicts),I.push({action:"positionUnseededParticipants"})}const{positionAssignments:A}=rs({drawDefinition:c,structure:y});return Ls({drawDefinition:c,structureIds:[d]}),t||nr(),{positionAssignments:A,conflicts:M,...E,positioningReport:I}}function tg(t){const{applyPositioning:e=!0,provisionalPositioning:n,tournamentRecord:r,drawDefinition:i,seedingProfile:a,structureId:o,placeByes:s,seedsOnly:c,event:u}=t;if(!u)return{error:Pt};if(!i)return{error:q};if(!Mh({drawDefinition:i,structureId:o})&&!n)return{error:W};const d=Nh({drawDefinition:i,structureId:o}).playoffStructures?.sort(((t,e)=>Qo(t)-Qo(e))),p=[],l=[];if(d)for(const t of d){const{structureId:o}=t,u=Qh({structureId:o,provisionalPositioning:n,applyPositioning:e,tournamentRecord:r,drawDefinition:i,seedingProfile:a,placeByes:s,seedsOnly:c});if(u.error)return u;u.positionAssignments&&p.push({positionAssignments:u.positionAssignments,structureId:o}),u.positioningReport&&l.push(u.positioningReport)}return{...E,structurePositionAssignments:p,positioningReports:l}}function eg({drawDefinition:t,matchUpsMap:e,structureId:n}){const r=ts({drawDefinition:t,structureId:n});if(r.error)return wr({result:r});const{matchUps:i}=Yp({structure:r.structure,matchUpsMap:e});return{...vc({matchUps:i}),matchUps:i,matchUpsMap:e}}function ng({finishingPositions:t,drawDefinition:e,structureId:n}){const{roundProfile:r}=eg({drawDefinition:e,structureId:n}),i=r&&Object.keys(r);return i?.reduce(((e,n)=>(rg(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 w(n,(r||n)+1).includes(t)})({position:t,rangeDefinition:r})&&(e[t]={roundNumber:n})}))})),e)),{})}function rg(t){return[m(t?.finishingPositionRange?.loser||[]),m(t?.finishingPositionRange?.winner||[])]}function ig(t){return rg(t).map((t=>w(t[0],t[1]&&t[1]+1||t[0]+1)))}function ag({drawDefinition:t,structureIds:n,matchUpsMap:r}){if(n&&!Array.isArray(n))return{error:Nn,context:{structureIds:n}};if(!t)return{error:j};const i=(n=n??(t.structures??[]).filter((t=>t.stage!==Qa)).map((({structureId:t})=>t))).map((e=>{const{roundProfile:n}=eg({drawDefinition:t,matchUpsMap:r,structureId:e}),i=n&&Object.values(n);return i?.map(ig).flat()})).flat(),a=i.filter((t=>1===t?.length)).sort(e).flat();return{positionsNotPlayedOff:m(i.flat()).filter((t=>!a.includes(t))),positionsPlayedOff:a}}function og({excludeRoundNumbers:t=[],playoffPositions:r=[],drawDefinition:i,structureId:a}){if(!i)return{error:j};if(!a)return{error:It};if(!r)return{error:ae,info:"missing playoffPositions"};const o=ag({drawDefinition:i});if(o.error)return o;const s=o.positionsPlayedOff,c=ng({finishingPositions:r.filter((t=>!s.includes(t))),drawDefinition:i,structureId:a}),u=Object.values(c).reduce(((t,e)=>t.includes(e.roundNumber)?t:t.concat(e.roundNumber)),[]).map((t=>n(t))).filter((e=>!t.includes(e))),d=ng({finishingPositions:s,drawDefinition:i,structureId:a}),p=d?Object.values(d).reduce(((t,e)=>t.includes(e.roundNumber)?t:t.concat(e.roundNumber)),[]).map((t=>n(t))):[],l=u.filter((t=>!p.includes(t))).sort(e),{roundProfile:m}=eg({drawDefinition:i,structureId:a}),f=l.map((t=>{const e=m?.[t].finishingPositionRange.loser,[n,r]=e??[0,0];return w(n,(r||n)+1)})).flat().sort(e),{playoffRoundsRanges:h}=function({playoffSourceRounds:t,roundProfile:e}){const n=t.map((t=>{const n=e[t].finishingPositionRange.loser,[r,i]=n,a=w(r,(i||r)+1);return{finishingPositionRange:n.join("-"),finishingPositions:a,roundNumber:t}}));return{playoffRoundsRanges:n}}({playoffSourceRounds:l,roundProfile:m}),g=[...l,...p];return{playoffPositionsReturned:f,playedOffSourceRounds:p,playoffRoundsRanges:h,playoffSourceRounds:l,sourceRounds:g,roundProfile:m}}function sg({drawDefinition:t,structureId:e}){if(!t)return{error:j};const{matchUps:n,matchUpsMap:r}=Ul({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:i,positionsPlayedOff:a}=ag({drawDefinition:t,matchUpsMap:r}),{structures:o}=es({drawDefinition:t}),s=o.filter((t=>!e&&t.stage!==eo||t.structureId===e)),c={};for(const e of s){const r=e?.structureId,a=cg({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 cg({playoffPositions:t,drawDefinition:n,structure:r,matchUps:i}){const a=r?.structureId,{links:o}=Ic({drawDefinition:n,structureId:a});if(r.structureType===mo||r.structures){const t=rs({structure:r})?.positionAssignments?.length,e=r.structures.length,s=(t??0)/e,c=o.source?.flatMap((({source:t})=>t?.finishingPositions||[]))||[],u=w(1,s+1).filter((t=>!c.includes(t))),d=i.find((t=>t.containerStructureId===a&&t.finishingPositionRange))?.finishingPositionRange?.winner||[0,1],p=o?.source.map((({target:t})=>t.structureId)),{positionsPlayedOff:l,positionsNotPlayedOff:m}=ag({structureIds:p,drawDefinition:n}),f=[...l??[],...m],h=w(d[0],d[1]+1).filter((t=>!f.includes(t))),g=N(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:e,groupSize:s}}const s=o?.source?.filter((t=>t.linkCondition!==vo)).map((t=>t.source?.roundNumber))||[],c=o?.source?.filter((t=>t.linkCondition===vo)).map((t=>t.source?.roundNumber))||[],{playoffSourceRounds:u,playoffRoundsRanges:d,roundProfile:p,error:l}=og({excludeRoundNumbers:s,playoffPositions:t,drawDefinition:n,structureId:a});for(const t of c){const e=o?.source.find((e=>e.source.roundNumber===t)),n=e?.target.roundNumber,r=e?.target.structureId,a=i.filter((({roundNumber:t,structureId:e})=>e===r&&t===n)),s=a.filter((({sides:t})=>t.find((t=>t.participantFed&&!t.participantId)))).length;if(u&&s===a.length){u.push(t);const e=p?.[t]?.finishingPositionRange?.loser;if(e){const n=Math.min(...e),r=n+s,i=w(n,r),a={finishingPositionRange:[n,r-1].join("-"),finishingPositions:i,roundNumber:t};d.push(a)}}}return u&&u.sort(e),d.sort(((t,e)=>t.roundNumber-e.roundNumber)),{playoffRounds:u,playoffRoundsRanges:d,error:l}}function ug(t){return sg(t)}function dg({drawDefinition:t}){const{maxQualifyingDepth:e,structureProfiles:n}=Gm({drawDefinition:t});for(const r of t.structures){const t=n[r.structureId];t.distanceFromMain&&(r.stageSequence=e+1-t.distanceFromMain)}return{...E}}function pg({tournamentRecord:t,drawDefinition:e,structure:n,link:r}){if(!t)return{error:_};if(!e)return{error:j};const i=function({drawDefinition:t,tournamentId:e,structure:n,eventId:r,link:i}){if(!t)return{error:j};if(!n)return{error:yt};if(!i)return{error:ht};const a=i.target.structureId,o=ts({drawDefinition:t,structureId:a});if(o.error)return wr({stack:"attachQualifyingStructure",context:{targetStructureId:a},result:o});t.structures||(t.structures=[]);t.links||(t.links=[]);t.structures.push(n),t.links.push(i),dg({drawDefinition:t});const s=Yp({structure:n})?.matchUps||[];return Fs({drawDefinition:t,tournamentId:e,matchUps:s,eventId:r}),Ls({drawDefinition:t,structureIds:[n.structureId]}),{...E}}({tournamentId:t.tournamentId,drawDefinition:e,structure:n,link:r});if(i.error)return i;return Lm({tournamentRecord:t,timeItem:{itemType:"attachQualifyingStructures",itemValue:{structureId:n.structureId,drawId:e.drawId}}}),i}const lg="SET3-S:6/TB7",mg="SET3-S:6/TB7-F:TB10",fg={FORMAT_STANDARD:lg,FORMAT_STANDARD_NOAD:"SET3-S:6NOAD",FORMAT_ATP_DOUBLES:mg,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"};function hg({winningSide:t,matchUpFormat:e=lg,matchUpStatus:n,tallyPolicy:r,score:i}){const a=[0,0],o=i?.sets,s="number"==typeof t&&t-1,c=Jd(e),u=Ug(c?.bestOf??1);if("number"==typeof s&&(n===Oa&&r?.setsCreditForDefaults||n===Ga&&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===Ba&&(+a[1-s]===u&&(a[1-s]-=1),r?.setsCreditForRetirements&&(a[s]=u)),a}function gg({matchUpFormat:t=lg,winningSide:e,matchUpStatus:r,tallyPolicy:i,score:a}){const{sets:o}=a||{};if(!o)return[0,0];const s="number"==typeof e&&e-1,c=Jd(t),u=Ug(c?.bestOf??1),d=c?.setFormat?.tiebreakAt||0,p=[[],[]];if("number"==typeof s&&(r===Oa&&i?.gamesCreditForDefaults||r===Ga&&i?.gamesCreditForWalkovers)){const t=u*(c?.setFormat?.setTo||0);p[s].push(t)}else o.forEach(((t,e)=>{const r=(t.setNumber||e+1)>u&&c?.finalSetFormat?"finalSetFormat":"setFormat",a=c?.[r]?.based,o=c?.[r].tiebreakSet,{side1Score:s,side2Score:d}=t;yg(a)&&(p[0].push(n(s||0)),p[1].push(n(d||0))),o&&t.winningSide&&!1!==i?.gamesCreditForTiebreakSets&&p[t.winningSide-1].push(1)}));if(r===Ba&&"number"==typeof s){const a=o.length>u&&c?.finalSetFormat?"finalSetFormat":"setFormat",l=c?.[a];if(yg(l.based)){const a=l?.setTo||0,m=t=>{if(c&&""!==t)return+t==d-1||+t===d?n(d||0)+1:+t<d?a:d},f=hg({winningSide:e,score:{sets:o},matchUpStatus:r,matchUpFormat:t,tallyPolicy:i});if(p.map((t=>t[s]<=t[1-s])).reduce(((t,e)=>t+(e?1:0)),0)>f[1-s]){const t=p[s].length,e=m(p[1-s][t-1]);e&&(p[s][t-1]=e)}u>p[s].length&&i?.gamesCreditForRetirements&&p[s].push(a)}}return[p[0].reduce(((t,e)=>t+e),0),p[1].reduce(((t,e)=>t+e),0)]}function Ig({matchUpFormat:t,score:e}){const r=t?Jd(t):void 0,i=Ug(r?.bestOf??1),a=[0,0],o=[0,0];return e?.sets?.forEach(((t,e)=>{const s=(t.setNumber||e+1)>i&&r?.finalSetFormat?"finalSetFormat":"setFormat",c=r?.[s]?.based;if(Sg(c)){const{side1Score:e,side2Score:r}=t;e&&(o[0]+=n(e||0)),r&&(o[1]+=n(r||0))}else t.side1TiebreakScore&&(o[0]+=n(t.side1TiebreakScore||0)),t.side2TiebreakScore&&(o[1]+=n(t.side2TiebreakScore||0)),(t.side1TiebreakScore||t.side2TiebreakScore)&&t.winningSide&&(a[t.winningSide-1]+=1)})),{pointsTally:o,tiebreaksTally:a}}function Ug(t){return t&&Math.ceil(t/2)||1}function Sg(t){return"P"===t}function yg(t){return!Sg(t)}function vg({participantIds:t,matchUpFormat:e,tallyPolicy:n,perPlayer:r,matchUps:i}){const a={},o=n?.excludeMatchUpStatuses||[],s=i.filter((e=>(e.tieMatchUps||!o.includes(e.matchUpStatus))&&(!t?.length||2===P(t,[Pg(e,0),Pg(e,1)]).length))),c=s.flatMap((({score:t,tieMatchUps:e})=>e?e.filter((({matchUpStatus:t})=>!o.includes(t))).flatMap((({score:t})=>t?.sets?.length??0)):t?.sets?.length??0)).reduce(((t,e)=>t+e),0);for(const t of s){const{matchUpStatus:i,tieMatchUps:o,tieFormat:s,score:c,winningSide:u,sides:d}=t,p=s&&t._disableAutoCalc&&s.collectionDefinitions.every((({scoreValue:t})=>t)),l=u&&wg(t),m=u&&Tg(t);if(l||m)if(Dg(a,l),Dg(a,m),o?.length){r=0;for(const t of o){const{matchUpType:e}=t,r=e===Zs,i=e===Ks;t.winningSide&&(t.winningSide===u?(l&&(a[l].tieMatchUpsWon+=1,i&&(a[l].tieSinglesWon+=1),r&&(a[l].tieDoublesWon+=1)),m&&(a[m].tieMatchUpsLost+=1,i&&(a[m].tieSinglesLost+=1),r&&(a[m].tieDoublesLost+=1))):t.winningSide!==u&&(m&&(a[m].tieMatchUpsWon+=1,i&&(a[m].tieSinglesWon+=1),r&&(a[m].tieDoublesWon+=1)),l&&(a[l].tieMatchUpsLost+=1,i&&(a[l].tieSinglesLost+=1),r&&(a[l].tieDoublesLost+=1)))),Ng({matchUpFormat:t.matchUpFormat,matchUpStatus:t.matchUpStatus,score:t.score,winningParticipantId:l,losingParticipantId:m,participantResults:a,isTieMatchUp:!0,manualGamesOverride:p,tallyPolicy:n,winningSide:u})}Rg({winningParticipantId:l,losingParticipantId:m,participantResults:a,matchUpStatus:i})}else Ng({matchUpFormat:t.matchUpFormat??e,isTieMatchUp:void 0,winningParticipantId:l,manualGamesOverride:p,losingParticipantId:m,participantResults:a,matchUpStatus:i,tallyPolicy:n,winningSide:u,score:c});else if(i&&Ya.includes(i)){const e=Pg(t,0),n=Pg(t,1);e&&(Dg(a,e),a[e].matchUpsCancelled+=1),n&&(Dg(a,n),a[n].matchUpsCancelled+=1)}else if(o?.length){r=0;for(const t of o){if(t.winningSide){const e=d?.find((({sideNumber:e})=>e===t.winningSide))?.participantId,n=d?.find((({sideNumber:e})=>e===t.winningSide))?.participantId;e&&n&&(Dg(a,e),Dg(a,n),a[e].tieMatchUpsWon+=1,a[n].tieMatchUpsLost+=1,t.matchUpType===Ks?(a[e].tieSinglesWon+=1,a[n].tieSinglesLost+=1):t.matchUpType===Zs&&(a[e].tieDoublesWon+=1,a[n].tieDoublesLost+=1))}bg({score:t.score,manualGamesOverride:p,participantResults:a,sides:d})}}else bg({manualGamesOverride:p,participantResults:a,score:c,sides:d});if(p){const t=d?.find((({sideNumber:t})=>1===t))?.participantId,e=d?.find((({sideNumber:t})=>2===t))?.participantId;Dg(a,t),Dg(a,e);const n=c?.sets?.reduce(((t,e)=>t+(e?.side1Score??0)),0),r=c?.sets?.reduce(((t,e)=>t+(e.side2Score??0)),0);t&&(a[t].gamesWon+=n,a[t].gamesLost+=r),e&&(a[e].gamesWon+=r,a[e].gamesLost+=n)}}return function({participantResults:t,matchUpFormat:e,tallyPolicy:n,perPlayer:r,totalSets:i}){const a=e&&Jd(e)||{},o=a.bestOf,s=o&&Math.ceil(o/2)||1,c=a.setFormat?.setTo;Object.keys(t).forEach((e=>{const a=t[e].setsWon,o=t[e].setsLost,u=n?.groupTotalSetsPlayed?i:r*(s||0)||a+o;let d=Math.round(a/u*1e3)/1e3;(d===1/0||isNaN(d))&&(d=u);const p=t[e].tieMatchUpsWon,l=p+t[e].tieMatchUpsLost;let m=Math.round(p/l*1e3)/1e3;(m===1/0||isNaN(m))&&(m=p);const f=t[e].matchUpsWon,h=f+t[e].matchUpsLost;let g=Math.round(f/h*1e3)/1e3;(g===1/0||isNaN(g))&&(g=f);const I=t[e].gamesWon||0,U=t[e].gamesLost||0,S=(r||0)*(s||0)*(c||0),y=Math.max(S,I+U);let v=Math.round(I/y*1e3)/1e3;(v===1/0||isNaN(v))&&(v=0);let w=Math.round(t[e].pointsWon/t[e].pointsLost*1e3)/1e3;(w===1/0||isNaN(w))&&(w=0),t[e].setsWon=a,t[e].setsLost=o,t[e].setsPct=d,t[e].tieMatchUpsWon=p,t[e].tieMatchUpsPct=m,t[e].matchUpsPct=g,t[e].gamesWon=I,t[e].gamesLost=U,t[e].gamesPct=v,t[e].pointsPct=w,t[e].result=`${t[e].matchUpsWon}/${t[e].matchUpsLost}`}))}({participantResults:a,matchUpFormat:e,tallyPolicy:n,perPlayer:r,totalSets:c}),{participantResults:a}}function wg(t){return Pg(t,t.winningSide-1)}function Tg(t){return Pg(t,1-(t.winningSide-1))}function Pg(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 Dg(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,retirements:0,setsLost:0,setsWon:0,tieSinglesWon:0,tieSinglesLost:0,tieDoublesWon:0,tieDoublesLost:0,tieMatchUpsLost:0,tieMatchUpsWon:0,victories:[],walkovers:0})}function bg({manualGamesOverride:t,participantResults:e,score:r,sides:i}){const{sets:a}=r||{},o=[[],[]],s=[0,0];for(const t of a||[]){const{winningSide:e,side1Score:r,side2Score:i}=t;e&&(s[e-1]+=1),o[0].push(n(r||0)),o[1].push(n(i||0))}const c=[o[0].reduce(((t,e)=>t+e),0),o[1].reduce(((t,e)=>t+e),0)];i.forEach(((n,r)=>{const{participantId:i}=n;i&&(Dg(e,i),e[i].setsWon+=s[r],e[i].setsLost+=s[1-r],t||(e[i].gamesWon+=c[r],e[i].gamesLost+=c[1-r]))}))}function Ng({winningParticipantId:t,losingParticipantId:e,participantResults:n,manualGamesOverride:r,matchUpFormat:i,matchUpStatus:a,isTieMatchUp:o,tallyPolicy:s,winningSide:c,score:u}){const d=c&&c-1,p=1-d;o||Rg({winningParticipantId:t,losingParticipantId:e,participantResults:n,matchUpStatus:a});const l=hg({matchUpStatus:a,matchUpFormat:i,tallyPolicy:s,winningSide:c,score:u}),m=gg({matchUpStatus:a,matchUpFormat:i,tallyPolicy:s,winningSide:c,score:u}),{pointsTally:f}=Ig({score:u,matchUpFormat:i});t&&(n[t].setsWon+=l[d],n[t].setsLost+=l[p],r||(n[t].gamesWon+=m[d],n[t].gamesLost+=m[p]),n[t].pointsWon+=f[d],n[t].pointsLost+=f[p]),e&&(n[e].setsWon+=l[p],n[e].setsLost+=l[d],r||(n[e].gamesWon+=m[p],n[e].gamesLost+=m[d]),n[e].pointsWon+=f[p],n[e].pointsLost+=f[d])}function Rg({winningParticipantId:t,losingParticipantId:e,participantResults:n,matchUpStatus:r}){e&&(r===Ga&&(n[e].walkovers+=1),r===Oa&&(n[e].defaults+=1),r===Ba&&(n[e].retirements+=1),[Oa,Ba,Ga].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 Mg({participantResults:t,participantIds:e,attribute:n}){return Ag({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 Ag(t){return(t.participantIds||Object.keys(t.participantResults)).reduce(((e,n,r)=>(e.push({participantId:n,i:r,results:t.participantResults[n]}),e)),[])}const Eg=[{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}],Cg={matchUpsPct:20,tieMatchUpsPct:16,setsPct:12,gamesPct:8,pointsPct:4};function Og(t){const{requireCompletion:e=!0,participantResults:n,subOrderMap:r,tallyPolicy:i}=t,a=[];if(e&&!function({participantResults:t,participantsCount:e}){const n=Ag({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=Mg({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=Fg({participantIds:e,...t});return a.push(...n.report??[]),n.order})).flat(1/0);let u,d=1;c.forEach(((t,e)=>{e&&(t.resolved||u&&!t.resolved)&&(d+=1),u=t.resolved,t.resolved?(t.position=e+1,d=t.position):t.position=d}));const p=g(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(Cg).filter((t=>i.GEMscore.includes(t))):Object.keys(Cg);return e.map((e=>(t[e]||0)*Math.pow(10,Cg[e].toFixed(3)))).reduce(((t,e)=>t+e),0)}(o);const s=p[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 Fg({participantResults:t,disableHeadToHead:e,participantIds:n,matchUpFormat:r,tallyPolicy:i,matchUps:a}){const o=[],c=[];let u;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 c.push({attribute:"head2Head",participantIds:n,headToHeadWinner:t}),{order:[e],headToHeadWinner:t,report:c}}}const d=(i?.tallyDirectives||Eg).filter((t=>{const e=!(s(t.maxParticipants)&&n?.length>t.maxParticipants);return e||o.push(t),e}));return o.length&&c.push({excludedDirectives:o,participantIds:n}),d.every((({attribute:t,reversed:e,idsFilter:o,disableHeadToHead:s})=>(u=function({disableHeadToHead:t,participantIds:e,matchUpFormat:n,tallyPolicy:r,attribute:i,idsFilter:a,matchUps:o,reversed:s}){const{participantResults:c}=vg({participantIds:a&&e,matchUpFormat:n,tallyPolicy:r,matchUps:o}),u=Mg({participantResults:c,participantIds:e,attribute:i}),d=[{attribute:i,reversed:s,groups:u,idsFilter:a}];let p;return Object.keys(u).length>1&&e.length&&(p=Object.keys(u).map((t=>parseFloat(t))).sort(((t,e)=>s?t-e:e-t)).map((t=>u[t])).map((e=>{const i=Fg({participantResults:c,disableHeadToHead:t,participantIds:e,matchUpFormat:n,tallyPolicy:r,matchUps:o});return d.push(...i.report??[]),i.order})).flat(1/0)),{order:p,report:d}}({disableHeadToHead:s,participantIds:n,matchUpFormat:r,tallyPolicy:i,attribute:t,idsFilter:o,matchUps:a,reversed:e}),c.push(u.report),!u.order))),u.order?{order:u.order,report:c}:{order:n?.map((t=>({participantId:t}))),report:c}}function kg({policyDefinitions:t,generateReport:e,matchUpFormat:n,matchUps:r=[],subOrderMap:i,perPlayer:a}){if(!yc(r))return{error:Ht};if(1!==r.reduce(((t,{structureId:e})=>t.includes(e)?t:t.concat(e)),[]).length)return{error:Nn,info:"Maximum one structureId"};const o=r.filter((t=>t&&t.matchUpStatus!==Ma)),s=o.length&&m(o.map((({drawPositions:t})=>t)).flat()).length,c=o.filter((t=>Lc({matchUp:t}))).length===o.length;c||(a=0);const u=r.every((({matchUpType:t,tieMatchUps:e})=>t===Qs&&e.every((t=>Lc({matchUp:t}))))),d=t?.[yi],p=r.filter((t=>Lc({matchUp:t})||t.matchUpType===Qs)),{participantResults:l}=vg({matchUps:p,matchUpFormat:n,tallyPolicy:d,perPlayer:a});let f,h;const{groupOrder:g,report:I}=Og({matchUps:p,participantResults:l,participantsCount:s,matchUpFormat:n,tallyPolicy:d,subOrderMap:i});if(c&&g)f=I,h=g,g.forEach((t=>{const{participantId:e,groupOrder:n,rankOrder:r,subOrder:i,ties:a,GEMscore:o}=t,s=l[e];Object.assign(s,{groupOrder:n,rankOrder:r,GEMscore:o,subOrder:i,ties:a})}));else{const{groupOrder:t,report:e}=Og({requireCompletion:!1,participantResults:l,participantsCount:s,matchUpFormat:n,tallyPolicy:d,subOrderMap:i,matchUps:r});f=e,h=t,t&&t.forEach((t=>{const{participantId:e,groupOrder:n,GEMscore:r}=t,i=l[e];Object.assign(i,{provisionalOrder:n,GEMscore:r})}))}const U={completedTieMatchUps:u,readableReport:"",participantResults:l,bracketComplete:c,order:[],report:f};if((c||u)&&(U.order=h),e||Qn({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:r,report:f,order:h});Qn({tally:!0})&&console.log(t),U.readableReport=t}return U}function xg({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=>Ya.includes(t.matchUpStatus))),{collectionValueProfiles:u,collectionGroupNumber:d,collectionValue:l,matchUpValue:m,winCriteria:f,scoreValue:h,setValue:g}=t,I=d&&e.includes(d),U=[0,0];if(a.forEach((t=>{t.winningSide&&(U[t.winningSide-1]+=1)})),p(m)?a.forEach((t=>{t.winningSide&&(o[t.winningSide-1]+=m)})):p(g)?a.forEach((t=>{t.score?.sets?.forEach((t=>{t.winningSide&&(o[t.winningSide-1]+=g)}))})):p(h)?a.forEach((t=>{t.score?.sets?.forEach((e=>{const{side1TiebreakScore:n=0,side2TiebreakScore:r=0,side1Score:i=0,side2Score:a=0}=e;(t.matchUpStatus===Ea||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});p(r)&&(o[e.winningSide-1]+=r)}})),p(l)){let e;if(f?.aggregateValue)c&&(p(m||g||h)&&o[0]!==o[1]?e=o[0]>o[1]?1:2:U[0]!==U[1]&&(e=U[0]>U[1]?1:2));else if(f?.valueGoal)e=o.reduce(((t,e,n)=>e>=f.valueGoal?n+1:t),0);else{const n=Math.floor(t.matchUpCount/2)+1;e=U.reduce(((t,e,r)=>e>=n?r+1:t),0)}e&&(I?n[d].values[e-1]+=l:s[e-1]+=l)}else I?(n[d].values[0]+=o[0]||0,n[d].values[1]+=o[1]||0):s=o;I?(n[d].sideWins[0]+=U[0]||0,n[d].sideWins[1]+=U[1]||0,n[d].allGroupMatchUpsCompleted=n[d].allGroupMatchUpsCompleted&&c,n[d].matchUpsCount+=a.length):s.forEach(((t,e)=>r[e]+=t||0))}function _g(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:Nn};if(!o)return{error:zt};const c=$d({matchUp:o,drawDefinition:r,structure:a,event:s})?.tieFormat||t?.tieFormat;if(!c)return{error:Gt};const u=fh({tieFormat:c});if(u.error)return u;const d=c?.collectionDefinitions||[],p=o?.tieMatchUps??[],l=[0,0],{groupValueGroups:m,groupValueNumbers:f}=Kf(c);for(const t of d)xg({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 S;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));S=e?.sideNumber}else if(e){p.every((t=>t.matchUpStatus&&Ya.includes(t.matchUpStatus)||t.winningSide))&&h[0]!==h[1]&&(S=h[0]>h[1]?1:2)}if(!S&&n){const t=o.matchUpId,e=o.hasContext?o:i?.drawMatchUps?.[t]||r&&Xm({inContext:!0,drawDefinition:r,matchUpId:t})?.matchUp;if(e){const{completedTieMatchUps:t,order:n}=kg({matchUps:[e]});if(t&&n?.length){const t=n[0].participantId;S=e.sides.find((({participantId:e})=>e===t))?.sideNumber}}}}return S&&(g.winningSide=S),{scoreStringSide1:I,scoreStringSide2:U,winningSide:S,set:g}}const Lg={matchUpStatus:ja,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function Bg({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&&Ma||[Oa,Ga].includes(u.matchUpStatus)&&u.matchUpStatus||ja,[Ga,Oa].includes(u.matchUpStatus)&&(u.winningSide=void 0),u.matchUpStatusCodes&&ef({inContextDrawMatchUps:t,sourceMatchUpStatus:n,sourceMatchUpId:a,matchUpsMap:c,matchUp:u}),xs({tournamentId:i?.tournamentId,eventId:d?.eventId,context:`removeSubsequentDrawPosition-${r}`,drawDefinition:o,matchUp:u}),{...E}}function Vg({tournamentRecords:t,eventId:e,drawId:n}){const{tournamentIdMap:r}=Cm({tournamentRecords:t});return(r?Object.keys(r):[]).find((t=>e&&r?.[t].includes(e)||n&&r?.[t].includes(n)))}function jg({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:i,matchUps:a,event:o}){if(!yc(a))return{error:Nn};if(!t)return{error:Nn};const{policyDefinitions:s}=bc({policyTypes:[yi],tournamentRecord:e,drawDefinition:r,event:o}),{subOrderMap:c}=function({positionAssignments:t}){const e=(t||[]).filter(Ua(lp)).map((t=>{const{extension:e}=Mr({element:t,name:sa}),r=n(e?.value),i=!isNaN(r)&&r;return i&&{participantId:t.participantId,subOrder:i}})).filter(Boolean),r=g(e.map((({subOrder:t})=>t)));return{subOrderMap:Object.assign({},...e.filter((({subOrder:t})=>1===r[t])).map((({participantId:t,subOrder:e})=>({[t]:e}))))}}({positionAssignments:t}),u=kg({policyDefinitions:s,matchUpFormat:i,subOrderMap:c,matchUps:a});if(u.error)return u;const{participantResults:d,bracketComplete:p,report:l}=u,m=Object.keys(d);return t.forEach((t=>{const{participantId:e}=t;if(m.includes(e)){Nr({element:t,extension:{value:d[e],name:ca}}),d[e].ties||Dr({element:t,name:sa})}else Dr({element:t,name:ca}),Dr({element:t,name:sa})})),Ls({drawDefinition:r}),{...E,participantResults:d,bracketComplete:p,report:l}}function Gg(t){return"object"!=typeof t?{error:ae}:"object"!=typeof t.element?{error:Nn}:t.notes?"string"==typeof t.notes||t.notes?.testing?(Object.assign(t.element,{notes:t.notes}),{...E}):{error:Nn}:{error:ae}}function qg({matchUpStatusCodes:t,removeWinningSide:e,tournamentRecord:n,drawDefinition:r,matchUpFormat:i,matchUpStatus:a,removeScore:o,winningSide:s,matchUpId:c,matchUp:u,event:d,notes:p,score:l}){const f="modifyMatchUpScore";let h;const g=u.matchUpType===Qs;if(g&&r){if(c&&u.matchUpId!==c){const t=Xm({drawDefinition:r,matchUpId:c,event:d});if(!t.matchUp)return{error:Wt};({matchUp:u,structure:h}=t)}}else u.matchUpId!==c&&console.log("!!!!!");a&&[Ga,ka].includes(a)||o?Object.assign(u,{...Lg}):l&&(u.score=l);const I=a&&u?.matchUpStatus===Oa&&a!==Oa;let U;if(a&&(u.matchUpStatus=a),i&&(u.matchUpFormat=i),t&&(u.matchUpStatusCodes=t),s&&(u.winningSide=s),e&&(u.winningSide=void 0),!h&&r&&({structure:h}=Xm({drawDefinition:r,matchUpId:c,event:d})),!a||u.winningSide||!$s(u)||Ya.includes(a)||[Ra,Va].includes(a)||(u.matchUpStatus=xa),I&&u?.processCodes?.length||a===Oa){const t=Dc({tournamentRecord:n,drawDefinition:r,structure:h,event:d})?.appliedPolicies;U=t?.[Mi]?.processCodes?.incompleteAssignmentsOnDefault}if(!u.collectionId){const t=h?.structureType===mo,e=ap({drawDefinition:r,structure:h});if(ip({drawDefinition:r,structure:h})||e||t){const a=(t=>{i=g?"SET1-S:T100":i??u.matchUpFormat??t?.matchUpFormat??r?.matchUpFormat??d?.matchUpFormat;const a=g?{matchUpTypes:[Qs]}:void 0,{matchUps:o}=Yp({afterRecoveryTimes:!1,tournamentRecord:n,inContext:!0,matchUpFilters:a,drawDefinition:r,structure:t,event:d});return e&&(t.positionAssignments=m(o.flatMap((t=>(t.sides??[]).map((t=>t.participantId)))).filter(Boolean)).map((t=>({participantId:t})))),jg({positionAssignments:t.positionAssignments,tournamentRecord:n,drawDefinition:r,matchUpFormat:i,matchUps:o,event:d})})(t&&h.structures.find((t=>t?.matchUps.find((t=>t.matchUpId===c))))||h);if(a.error)return wr({result:a,stack:f})}}if(p){const t=Gg({element:u,notes:p});if(t.error)return wr({result:t,stack:f})}const S=n?.tournamentId,y=lr().topics.includes(Es),v=(y||U)&&xc({drawDefinition:r}),w=v&&Jp({matchUpFilters:{matchUpIds:[c]},nextMatchUps:!0,tournamentRecord:n,inContext:!0,drawDefinition:r,matchUpsMap:v}).matchUps?.[0];if(y&&w&&function({tournamentId:t,inContextMatchUp:e}){e&&sr({payload:{inContextMatchUp:e,tournamentId:t},topic:Es,key:e.matchUpId})}({tournamentId:S,inContextMatchUp:w}),Array.isArray(U)&&w&&!w.sides?.every((({participantId:t})=>t)))if(a===Oa)u.processCodes=m([...u.processCodes??[],...U]);else for(const t of U||[]){const e=t&&u?.processCodes?.lastIndexOf(t);u?.processCodes?.splice(e,1)}return xs({eventId:d?.eventId,context:f,drawDefinition:r,tournamentId:S,matchUp:u}),{...E}}function $g(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&&Vg({tournamentRecords:c,...t});const d=u&&c[u];if(!d)return{error:_};const p=Xm({drawDefinition:n,event:s,matchUpId:o});if(p.error)return p;if(!p.matchUp)return{error:Wt};const{matchUp:l,structure:m}=p;if(!l.tieMatchUps)return{error:Yt};Vf({tournamentId:d?.tournamentId,eventId:s?.eventId,dualMatchUp:l,drawDefinition:n});const{extension:f}=Mr({name:Hi,element:l});if(f?.value){if(!i)return{...E,score:l.score};Dr({element:l,name:Hi})}const h=$d({drawDefinition:n,structure:m,matchUp:l,event:s})?.tieFormat;l.tieFormat=Yf(h);const g=_g({drawDefinition:n,matchUpsMap:a,structure:m,matchUp:l,event:s}),{winningSide:I,set:U,scoreStringSide1:S,scoreStringSide2:y}=g,v=U?.side1Score||U?.side2Score;if(e&&!l.score&&!v)return{...E};const w={scoreStringSide1:S,scoreStringSide2:y,sets:U?[U]:[]},T=I&&[1,2].includes(I),P=T&&Ea||zs({matchUpStatus:r??l.matchUpStatus,tieMatchUps:l.tieMatchUps,winningSide:l.winningSide,score:w})&&xa||ja,D=!(!l.winningSide||T),b=l.tieMatchUps.find((({score:t,winningSide:e,matchUpStatus:n})=>t?.sets?.length&&(t.sets[0].side1Score||t.sets[0].side2Score)||n&&Ya.includes(n)||e));let N;if(l.tieFormat&&!T&&!b){const t=$d({drawDefinition:n,structure:m,event:s})?.tieFormat;t&&JSON.stringify(h)===JSON.stringify(t)&&(l.tieFormatId=void 0,l.tieFormat=void 0,N=!0)}return qg({matchUpStatus:P,score:w,removeWinningSide:D,tournamentRecord:d,drawDefinition:n,removeScore:i,winningSide:I,matchUpId:o,matchUp:l,event:s}),{...E,score:w,removeWinningSide:D,tieFormatRemoved:N,winningSide:I}}function Wg(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=ap({drawDefinition:i,structure:d}),{drawPositions:f,winningSide:h}=c.matchUp||{};if(!m&&!f)return{error:Z};const{targetLinks:{loserTargetLink:g,winnerTargetLink:I,byeTargetLink:U},targetMatchUps:{loserMatchUp:S,winnerMatchUp:y,byeMatchUp:v}}=c,w=qg({...t,matchUpStatus:a||ja,removeWinningSide:!0});if(w.error)return w;let T;if(l){const{matchUpTieId:n,matchUpsMap:a}=t;if(T=$g({matchUpId:n,tournamentRecord:r,drawDefinition:i,matchUpsMap:a,event:p}),!e&&!T.removeWinningSide)return{...E}}if(m)return{...E};const{matchUps:P}=Yp({afterRecoveryTimes:!1,inContext:!0,drawDefinition:i,matchUpsMap:o,structure:d}),{positionAssignments:D}=is({structure:d}),N=h-1,R=1-N,M=f[N],A=f[R],{winnerParticipantId:C,loserParticipantId:O}=D?.reduce(((t,e)=>(e.drawPosition===A&&(t.loserParticipantId=e.participantId),e.drawPosition===M&&(t.winnerParticipantId=e.participantId),t)),{winnerParticipantId:void 0,loserParticipantId:void 0})||{},F=P.filter((t=>t.drawPositions?.includes(A)));if(y&&Hg({sourceMatchUpStatus:a,sourceMatchUpId:u,inContextDrawMatchUps:n,winningDrawPosition:M,winnerParticipantId:C,tournamentRecord:r,winnerTargetLink:I,drawDefinition:i,winnerMatchUp:y,dualMatchUp:s,matchUpsMap:o}),S){const{winnerHadMatchUpStatus:t}=function({matchUpStatuses:t=[Ma,Ga,Oa],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:b(o||[],t),winnerMatchUpStatuses:o,loserHadMatchUpStatus:b(s||[],t),loserMatchUpStatuses:s}}({drawPositionMatchUps:F,loserDrawPosition:A,sourceMatchUps:P}),e=g.linkCondition;if(t&&e===vo){zg({targetLink:g,inContextDrawMatchUps:n,drawDefinition:i,drawPosition:Math.min(...S.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}=ts({drawDefinition:a,structureId:p});if(!l)return{error:Ut};const{positionAssignments:m}=is({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,xs({tournamentId:n?.tournamentId,eventId:u?.eventId,matchUp:e,context:d,drawDefinition:a}))}return{...E}}({sourceMatchUpStatus:a,sourceMatchUpId:u,loserParticipantId:O,tournamentRecord:r,loserTargetLink:g,drawDefinition:i,loserMatchUp:S,dualMatchUp:s,matchUpsMap:o,event:p});if(c.error)return c}if(v){zg({sourceMatchUpId:u,targetLink:U,inContextDrawMatchUps:n,drawDefinition:i,drawPosition:Math.min(...v.drawPositions),matchUpsMap:o,event:p})}const k=T&&{tieMatchUpResult:T};return{...E,...k}}function Hg({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}=ts({drawDefinition:s,structureId:t});if(!e)return{error:Ut};const{positionAssignments:n}=is({structure:e});e.seedAssignments=(e.seedAssignments??[]).filter((t=>t.participantId!==r));const o=n?.find((t=>t.participantId===r)),d=o?.drawPosition,{matchUps:l}=Yp({drawDefinition:s,structure:e,event:p}),m=g(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&&xs({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}=ts({drawDefinition:a,structureId:o});if(p?.structureType===mo)return{...E};u=u??xc({drawDefinition:a});const l=(u?.mappedMatchUps||{})[o].matchUps,{initialRoundNumber:m}=vl({drawPosition:n,matchUps:l}),f=l?.filter((t=>t.roundNumber>=c&&t.roundNumber!==m&&t.drawPositions?.includes(n))),{positionAssignments:h}=rs({drawDefinition:a,structureId:o});for(const o of f??[])Bg({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}),{...E}}function zg({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,matchUpsMap:i,targetLink:a,event:o}){return Cl({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:i,drawPosition:r,structureId:a.target.structureId,event:o}),{...E}}function Yg(t){const{tournamentRecord:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:i,targetData:a,structure:o,event:s}=t,c="doubleExitAdvancement";if(o.structureType===mo)return wr({result:{...E},stack:c});const{matchUp:u,targetMatchUps:d,targetLinks:p}=a,{loserMatchUp:l,winnerMatchUp:m,loserTargetDrawPosition:f}=d;if(l&&l.matchUpStatus!==Ma){const{loserTargetLink:a}=p;if(n?.progression?.doubleExitPropagateBye){const t=Jg({loserTargetDrawPosition:f,tournamentRecord:e,loserTargetLink:a,drawDefinition:r,loserMatchUp:l,matchUpsMap:i,event:s});if(t.error)return wr({result:t,stack:c})}else{const{feedRound:n,drawPositions:r,matchUpId:i}=l,a=n?2:2-r.indexOf(f),o=Kg({...t,targetMatchUp:l,walkoverWinningSide:a,tournamentRecord:e,sourceMatchUp:u,matchUpId:i});if(o.error)return wr({result:o,stack:c})}}if(m){const n=Kg({...t,matchUpId:m.matchUpId,targetMatchUp:m,tournamentRecord:e,sourceMatchUp:u});if(n.error)return wr({result:n,stack:c})}return wr({result:{...E},stack:c})}function Kg(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===Fa?Fa:ka,u=t.matchUpStatus===Fa?Oa:Ga,d="conditionallyAdvanceDrawPosition",p=o.drawMatchUps.find((t=>t.matchUpId===a.matchUpId));if(!p)return{error:zt};const l=i?.drawPositions||[];let m=p.drawPositions?.filter(Boolean);const f=i?.structureId===a.structureId;if(f&&b(l,m)&&(m=m.filter((t=>!l.includes(t)))),f&&m.length>1)return wr({result:{error:z},stack:d});const{pairedPreviousMatchUpIsDoubleExit:h,pairedPreviousMatchUp:g}=Qm(t),I=Uc({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),{targetMatchUps:U,targetLinks:S}=I,{loserTargetDrawPosition:y,winnerMatchUp:v,loserMatchUp:w}=U;if(w){const{loserTargetLink:t}=S,e=Jg({loserTargetDrawPosition:y,loserMatchUp:w,tournamentRecord:n,loserTargetLink:t,drawDefinition:r,matchUpsMap:o});if(e.error)return wr({result:e,stack:d})}const T=p.drawPositions?.filter(Boolean)||[],P=1===T.length,D=t.walkoverWinningSide||P&&nf({drawPosition:T[0],matchUpId:a.matchUpId,inContextDrawMatchUps:e})||void 0,N=[Ga,Oa].includes(p.matchUpStatus)&&!T.length,R=1===p.finishingRound,M=N&&!R?c:u,A=e.find((t=>t.matchUpId===g.matchUpId));let C,O=[];i&&(i?.structureId===A?.structureId?C=i.roundPosition<g?.roundPosition?1:2:a.feedRound?C=i.structureId===a.structureId?2:1:D&&(C=3-D));const F=t.matchUpStatus,k=g?.matchUpStatus;1===C?O=[{matchUpStatus:Zg(F),previousMatchUpStatus:F,sideNumber:1},{matchUpStatus:Zg(k),previousMatchUpStatus:k,sideNumber:2}]:2===C&&(O=[{matchUpStatus:Zg(k),previousMatchUpStatus:k,sideNumber:1},{matchUpStatus:Zg(F),previousMatchUpStatus:F,sideNumber:2}]),O.length&&(O=O.map((t=>vr(t))));const x=qg({...t,matchUp:p,winningSide:D,matchUpStatusCodes:O,matchUpStatus:M});if(x.error)return wr({result:x,stack:d});if(N)return Yg({...t,matchUpStatus:M,targetData:I});if(!v)return wr({result:{...E},stack:d});const _=2===m.length?m[D-1]:m[0],{positionAssignments:L}=rs({structure:s}),B=L?.find((t=>t.drawPosition===_)),V=o.drawMatchUps.find((t=>t.matchUpId===v.matchUpId)),j=V?.drawPositions?.filter(Boolean),G=1===j.length;if(_){if(B?.bye){const n=Uc({matchUpId:V.matchUpId,inContextDrawMatchUps:e,drawDefinition:r});if(G){const t=j.filter(Boolean)[0],n=nf({drawPosition:t,matchUpId:V.matchUpId,inContextDrawMatchUps:e}),i=qg({matchUpId:V.matchUpId,matchUp:V,matchUpStatus:u,matchUpStatusCodes:[],removeScore:!0,drawDefinition:r,winningSide:n});return i.error?wr({result:i,stack:d}):Ml({drawPositionToAdvance:t,matchUpId:V.matchUpId,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:o})}if([Ga,Oa].includes(v.matchUpStatus)){const e=Yg({...t,matchUpId:V.matchUpId,matchUpStatus:M,targetData:n});if(e.error)return wr({result:e,stack:d})}return wr({result:{...E},stack:d})}return af({matchUpId:v.matchUpId,drawPosition:_,inContextDrawMatchUps:e,drawDefinition:r})}if(h){if(!V)return{error:zt};if(G){const t=j[0],n=nf({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawPosition:t});console.log("existing drawPosition is winningSide",{walkoverWinningSide:n})}const n=[Ga,Oa].includes(V.matchUpStatus)?u:c,i=qg({matchUpId:V.matchUpId,matchUp:V,matchUpStatusCodes:[],removeScore:!0,drawDefinition:r,matchUpStatus:n});if(i.error)return wr({result:i,stack:d});if(n===c){const e=Yg({...t,matchUpId:a.matchUpId,matchUpStatus:n,targetData:I});if(e.error)return e}}return wr({result:{...E},stack:d})}function Jg(t){const{loserTargetDrawPosition:e,tournamentRecord:n,loserTargetLink:r,drawDefinition:i,matchUpsMap:a,event:o}=t,s=r?.target?.structureId,{structure:c}=ts({drawDefinition:i,structureId:s});return c?bl({drawPosition:e,tournamentRecord:n,drawDefinition:i,structureId:s,matchUpsMap:a,event:o}):{error:yt}}function Zg(t){return t===ka?Ga:t===Fa?Oa:t}function Xg(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===Ma,c=a.winningSide,u=[ka,Fa].includes(r),d=Ws({matchUpStatus:r}),p=Hs({matchUpStatus:r}),l=!d&&!p,m=t.matchUpTieId||c&&d&&!u,f=c&&u;return l&&{error:Ft}||m&&Qg(t)||f&&function(t){const e=Wg(t);return e.error?e:Yg(t)}(t)||c&&Wg(t)||p&&qg({...t,removeScore:[Aa,Ga].includes(r),matchUpStatus:r||ja})||s&&function({tournamentRecord:t,drawDefinition:e,structure:n,matchUp:r}){const i="attemptToSetMatchUpStatusBYE";if(r?.winningSide)return wr({result:{error:_t},context:{matchUpStatus:Ma},stack:i});const{positionAssignments:a}=is({structure:n}),o=a?.filter((t=>t.bye)).map((t=>t.drawPosition)),s=r.drawPositions?.some((t=>o?.includes(t)));return s?(r.matchUpStatus=Ma,r.matchUpStatusCodes=[],xs({tournamentId:t?.tournamentId,context:i,drawDefinition:e,matchUp:r}),{...E}):wr({result:{error:Ot},info:"matchUp does not include BYE",stack:i})}({tournamentRecord:e,drawDefinition:n,structure:i,matchUp:a})||!d&&{error:Ft}||u&&function(t){const e=Qg({...t,removeScore:!0});return e.error?e:Yg(t)}(t)||o&&Qg(t)||wr({result:{error:_t},stack:"attemptToSetMatchUpStatus"})}function Qg(t){const e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){const n=Wg(t);if(n.error)return wr({result:n,stack:e})}const n=Boolean(t.matchUp.collectionId),r=qg(t);if(n){const{matchUpTieId:n,drawDefinition:i,matchUpsMap:a}=t,o=$g({tournamentRecord:t.tournamentRecord,matchUpId:n,event:t.event,drawDefinition:i,matchUpsMap:a});if(o.error)return wr({result:o,stack:e});Object.assign(r,{tieMatchUpResult:o})}return wr({result:r,stack:e})}function tI({drawDefinition:t,structure:e,matchUp:n}){const r=[];if(e.finishingPosition===Yo){if(Mh({drawDefinition:t,structure:e})){const{structureIds:i}=function({drawDefinition:t,structure:e,matchUp:n}){const{drawPositions:r}=n,{positionAssignments:i}=rs({drawDefinition:t,structure:e}),a=i?.filter((({drawPosition:t})=>r?.includes(t))),o=a?.map((t=>{const{extension:e}=Mr({element:t,name:ca});return e?.value?.groupOrder})),{containerStructures:s}=qs({drawDefinition:t}),c=s[e.structureId],u=Ic({drawDefinition:t,structureId:c})?.links?.source,d=u?.filter((t=>b(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 eI(t){const{dualWinningSideChange:e,matchUpStatusCodes:n,tournamentRecord:r,drawDefinition:i,matchUpFormat:a,matchUpStatus:o,winningSide:s,matchUpId:c,structure:u,matchUp:d,event:p,score:l}=t,m=Ws({matchUpStatus:o})||[Aa,Na].includes(o)&&e,f=Boolean(d.collectionId),h=ap({drawDefinition:i,structure:u}),g=f||h||function({structure:t,matchUp:e}){const{drawPositions:n}=e,{positionAssignments:r}=is({structure:t}),i=r?.filter((t=>n?.includes(t.drawPosition)&&t.participantId));return 2===i?.length}({structure:u,matchUp:d});if(!g)return{error:Rt};const I=[Ga].includes(o);return wr({result:qg({matchUpStatusCodes:m&&n||[],matchUpStatus:m&&o||Ea,tournamentRecord:r,drawDefinition:i,matchUpFormat:a,removeScore:I,winningSide:s,matchUpId:c,matchUp:d,event:p,score:l}),stack:"attemptToModifyScore"})}function nI(t){const n=eI(t);if(n.error)return n;const r=Ws({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:i,projectedWinningSide:a,inContextDrawMatchUps:o,tournamentRecord:s,drawDefinition:c,matchUpStatus:u,dualMatchUp:d,matchUpsMap:p,winningSide:l,targetData:m,matchUpId:f,structure:h,matchUp:g,event:I}=t,U="directParticipants",S=Boolean(g.collectionId),y=ap({drawDefinition:c,structure:h});let v,w=g.drawPositions;if(S){const{matchUpTieId:e,matchUpsMap:n}=t,r=$g({matchUpId:e,tournamentRecord:s,drawDefinition:c,matchUpsMap:n,event:I});v=r&&{tieMatchUpResult:r};const a=o.find((({matchUpId:t})=>t===e));if(w=a?.drawPositions,!i)return wr({result:{...E,...v},stack:U})}if(y)return wr({result:{...E,...v},stack:U});if(!w)return wr({result:{error:Z},stack:U});{const t=a?a-1:l-1,n=1-t,i=w[t],h=w[n],{targetLinks:{loserTargetLink:g,winnerTargetLink:S,byeTargetLink:y},targetMatchUps:{winnerMatchUpDrawPositionIndex:v,loserMatchUpDrawPositionIndex:T,winnerMatchUp:P,loserMatchUp:D,byeMatchUp:b}}=m;if(P){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=ts({structureId:f,drawDefinition:c});if(h.error)return h;const{structure:g}=h,{positionAssignments:I}=is({structureId:f,drawDefinition:c}),U=I?.find((t=>t.drawPosition===i)),S=U?.participantId,y=o.target.structureId,{positionAssignments:v}=is({structureId:y,drawDefinition:c}),w=v?.find((t=>t.participantId===S)),T=w?.drawPosition,P=v?.filter((t=>{const e=n.includes(t.drawPosition),r=!t.participantId&&!t.bye&&!t.qualifier;return e&&r})).map((t=>t.drawPosition)),D=P?.includes(d);if(S&&1===o.target.roundNumber&&D)Rf({drawPosition:d,participantId:S,structureId:y,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:a,drawDefinition:c,matchUpsMap:p,event:l});else if(S&&P?.length){const t=P.pop();t&&Rf({participantId:S,structureId:y,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:a,drawDefinition:c,drawPosition:t,matchUpsMap:p,event:l})}else if(T){const t=af({drawPosition:T,matchUpId:u.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:a,sourceMatchUpId:s,drawDefinition:c,matchUpsMap:p});if(t.error)return wr({result:t,stack:m})}else if(g?.stage!==Qa){const t="winner target position unavaiallble";return console.log(t),{error:t}}if(g?.seedAssignments&&g.structureId!==y){const t=g.seedAssignments.find((({participantId:t})=>t===S)),e=t?.participantId;t&&e&&vf({eventId:u?.eventId,structureId:y,...t,tournamentRecord:a,drawDefinition:c,participantId:e})}}else{const t=af({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=>({...i.sides?.find((e=>e.sideNumber===t))||{},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=Tf({lineUp:e}),xs({tournamentId:a?.tournamentId,eventId:u?.eventId,matchUp:i,context:m,drawDefinition:c})}}}return{...E}}({sourceMatchUpStatus:r&&u||Ea,winnerMatchUpDrawPositionIndex:v,sourceMatchUpId:f,inContextDrawMatchUps:o,projectedWinningSide:a,winningDrawPosition:i,tournamentRecord:s,winnerTargetLink:S,drawDefinition:c,winnerMatchUp:P,dualMatchUp:d,matchUpsMap:p,event:I});if(t.error)return wr({result:t,stack:U})}if(D){const t=function(t){const{loserMatchUpDrawPositionIndex:n,inContextDrawMatchUps:r,projectedWinningSide:i,sourceMatchUpStatus:a,loserDrawPosition:o,tournamentRecord:s,loserTargetLink:c,drawDefinition:u,loserMatchUp:d,dualMatchUp:p,matchUpsMap:l,event:m}=t,f="directLoser",h=c.linkCondition,g=d.drawPositions||[],I=h===vo&&2===d.roundNumber&&Math.min(...g.filter(Boolean)),U=I||g[n],S=I||g[1-n],y=c.source.structureId,{structure:v}=ts({structureId:y,drawDefinition:u}),{matchUps:w}=Yp({afterRecoveryTimes:!1,inContext:!0,drawDefinition:u,structure:v,event:m}),T=w.filter((t=>t.drawPositions?.includes(o))).filter((t=>{const e=t.sides.find((t=>t.drawPosition===o)),n=t.matchUpStatus===Ga||t.matchUpStatus===Oa&&!$s(t);return e?.sideNumber===t.winningSide&&!n})),P=h===vo&&0===T.length,{positionAssignments:D}=is({structureId:y,drawDefinition:u}),b=D?.find((t=>t.drawPosition===o)),N=b?.participantId,R=c.target.structureId,{positionAssignments:M}=is({structureId:R,drawDefinition:u}),A=M?.filter((({drawPosition:t})=>g.includes(t))),C=A?.some((t=>t.participantId===N));if(C)return{...E};const O=A?.filter((t=>{const e=g.includes(t.drawPosition),n=!t.participantId&&!t.bye&&!t.qualifier;return e&&n})).map((t=>t.drawPosition)),F=O?.includes(U),k=c.target.roundNumber>1&&O?.length,x=1===c.target.roundNumber&&F;if(I){const t=function(){const t="loserLinkFedFMLC";return wr(P?{result:L(),stack:t}:{result:_(),stack:t})}();if(t.error)return wr({result:t,stack:f})}else if(x){const t=L();if(t.error)return wr({result:t,stack:f})}else{if(!N||!k)return wr({result:{error:Q},context:{loserDrawPosition:o,loserTargetLink:c},stack:f});{O.sort(e);const t=O[0],n=Rf({participantId:N,structureId:R,drawPosition:t,inContextDrawMatchUps:r,sourceMatchUpStatus:a,tournamentRecord:s,drawDefinition:u,matchUpsMap:l,event:m});if(n.error)return wr({result:n,stack:f})}}if(v?.seedAssignments&&v.structureId!==R){const t=v.seedAssignments.find((({participantId:t})=>t===N)),e=t?.participantId;t&&e&&vf({eventId:d?.eventId,structureId:R,...t,tournamentRecord:s,drawDefinition:u,participantId:e})}if(p&&i){const t=p.sides?.find((t=>t.sideNumber===3-i));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)),o=[1,2].map((t=>({...a.sides?.find((e=>e.sideNumber===t))||{},sideNumber:t})));a.sides=o;const c=a.sides.find((t=>t.sideNumber===i));c&&(c.lineUp=Tf({lineUp:t.lineUp}),xs({tournamentId:s?.tournamentId,matchUp:a,context:f,drawDefinition:u,eventId:n}))}}return{...E};function _(){return wr({result:bl({drawPosition:S,structureId:R,tournamentRecord:s,drawDefinition:u,event:m}),stack:"assignLoserPositionBye"})}function L(){return wr({result:N?Rf({drawPosition:U,participantId:N,structureId:R,inContextDrawMatchUps:r,sourceMatchUpStatus:a,tournamentRecord:s,drawDefinition:u,matchUpsMap:l,event:m}):{error:Ae},stack:"assignLoserDrawPosition"})}}({sourceMatchUpStatus:r&&u||Ea,loserMatchUpDrawPositionIndex:T,sourceMatchUpId:f,inContextDrawMatchUps:o,projectedWinningSide:a,loserDrawPosition:h,tournamentRecord:s,loserTargetLink:g,drawDefinition:c,loserMatchUp:D,winningSide:l,matchUpsMap:p,dualMatchUp:d,event:I});if(t.error)return wr({result:t,stack:U})}if(b){const t=b.drawPositions||[],e=bl({drawPosition:Math.min(...t.filter(Boolean)),structureId:y.target.structureId,tournamentRecord:s,drawDefinition:c,event:I});if(e.error)return wr({result:e,stack:U})}}return wr({result:{...E,...v},stack:U})}function rI(t){const{inContextDrawMatchUps:e,targetData:n,drawDefinition:r,relevantLink:i}=t;if(i?.linkCondition===vo&&n?.matchUp?.matchUpStatus===Ma)return!1;const{targetMatchUps:{loserMatchUp:a,winnerMatchUp:o},targetLinks:s}=n,c=[Oa,Ga].includes(a?.matchUpStatus),u=o?.drawPositions?.filter(Boolean).length||0;if(a?.winningSide&&!c||o?.winningSide&&2===u&&(!o.feedRound||![Ga,Oa].includes(o?.matchUpStatus)))return!0;const d=a&&Uc({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),p=o&&Uc({matchUpId:o.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),l=d&&rI({relevantLink:s?.loserTargetLink,targetData:d,inContextDrawMatchUps:e,drawDefinition:r});return!(!(p&&rI({targetData:p,inContextDrawMatchUps:e,drawDefinition:r}))&&!l)}function iI(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 eI(t);if(u.winningSide&&u.winningSide!==s){const{connectedStructureIds:e}=tI({drawDefinition:a,structure:c,matchUp:u});e.length&&(console.log({connectedStructureIds:e}),n=!0);const r=Wg(t);if(r.error)return r}const d=nI(t);if(d.error)return wr({result:d,stack:e});let p,l;return t.qualifierChanging&&r?.[bi]?.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===fo){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===ja&&!rI({inContextDrawMatchUps:n,drawDefinition:i,targetData:Uc({matchUpId:c.matchUpId,inContextDrawMatchUps:n,drawDefinition:i})})){const{structure:n}=ts({structureId:c.structureId,drawDefinition:i}),o=rs({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]))}Vs({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:i,structure:n}),e=!0}}}return{...E,qualifierReplaced:e}}(t).qualifierReplaced),t.qualifierAdvancing&&r?.[bi]?.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===fo){const s=r.sides.find((({sideNumber:t})=>t===a))?.participantId,c=v(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===ja&&!rI({inContextDrawMatchUps:n,drawDefinition:i,targetData:Uc({matchUpId:c.matchUpId,inContextDrawMatchUps:n,drawDefinition:i})})){const n=c.sides.find((t=>t.qualifier&&!t.participantId))?.drawPosition,{structure:r}=ts({structureId:c.structureId,drawDefinition:i});if(!r)return{error:Ut};const a=rs({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]))}Vs({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:i,structure:r}),e=!0}}}return{...E,qualifierPlaced:e}}(t).qualifierPlaced),wr({result:vr({...E,...d,connectedStructures:n,qualifierReplaced:p,qualifierPlaced:l}),stack:e})}const aI={drawPositionToRemove:"green",iteration:"brightred",winner:"green",loser:"brightred"};function oI(t){const{inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:i,targetData:a,matchUp:o}=t;let{iteration:s=0}=t;s+=1;const c="removeDoubleExit";Pl({method:c,color:"brightyellow",iteration:s,keyColors:aI});const{targetLinks:{loserTargetLink:u},targetMatchUps:{loserMatchUp:d,winnerMatchUp:p,loserTargetDrawPosition:l}}=a;if(p&&p.matchUpStatus!==Ma){const{stage:e,roundNumber:n,roundPosition:r}=p;Pl({winner:"winner",stage:e,roundNumber:n,roundPosition:r,keyColors:aI}),sI({...t,targetMatchUp:p,sourceMatchUp:o,iteration:s})}if(d&&d.matchUpStatus!==Ma){const a=e.find((({matchUpId:t})=>t===d.matchUpId)),{structure:o}=ts({drawDefinition:r,structureId:a.structureId}),{stage:p,roundNumber:m,roundPosition:f,feedRound:h}=d;if(Pl({loser:"loser",stage:p,roundNumber:m,roundPosition:f,keyColors:aI,feedRound:h}),n?.progression?.doubleExitPropagateBye)zg({drawPosition:l,targetLink:u,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:i});else{const e=sI({...t,structure:o,targetMatchUp:d,iteration:s});if(e.error)return wr({result:e,stack:c})}}return wr({result:{...E},stack:c})}function sI(t){const{inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,sourceMatchUp:i,targetMatchUp:a,matchUpsMap:o,structure:s,iteration:c}=t,u="conditionallyRemoveDrawPosition";Pl({method:u});const d=Uc({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=tf({structureId:s.structureId,matchUp:i,matchUpsMap:o})?.pairedPreviousMatchUp,m=[ka,Fa].includes(f?.matchUpStatus),g=f?.drawPositions?.filter(Boolean)||[];if([...Ya,Ma].includes(f?.matchUpStatus)||f?.winningSide){const t=i.drawPositions||[];let e=a.drawPositions?.filter(Boolean);b(t,e)&&(e=e?.filter((e=>!t.includes(e))));h=t.concat(g).find((t=>e?.includes(t)))}}else h=P(a?.drawPositions||[],p?.drawPositions||[])?.[0];if(p&&h){const{stage:t,roundNumber:n,roundPosition:i}=p;Pl({method:"removeDirectedWinner",drawPositionToRemove:h,keyColors:aI,color:"brightgreen",stage:t,roundNumber:n,roundPosition:i}),Hg({winningDrawPosition:h,winnerMatchUp:p,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:o})}let I=oI({targetData:d,matchUp:a,inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:o,structure:s,iteration:c});if(I.error)return wr({result:I,stack:u});const U=function({pairedPreviousDoubleExit:t,noContextTargetMatchUp:e}){return e.matchUpStatus===Ma?Ma:t?[Fa,Oa].includes(e?.matchUpStatus)?Oa:Ga:ja}({pairedPreviousDoubleExit:m,noContextTargetMatchUp:l}),S=!m;return I=qg({...t,matchUpStatus:U,removeScore:S,score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},removeWinningSide:!0,matchUp:l,matchUpId:a.matchUpId,matchUpStatusCodes:[]}),I.error?wr({result:I,stack:u}):{...E}}function cI(t){const{matchUp:e,matchUpStatus:n,score:r,winningSide:i}=t,a="noDownStreamDependencies";if([ka,Fa].includes(e?.matchUpStatus)&&![ka,Fa].includes(n)){const e=oI(t);if(e.error)return wr({result:e,stack:a})}const o=n===ka,s=$s({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&&Jd(e),{setFormat:a,finalSetFormat:o,bestOf:s}=i??{},c=s&&r===s&&o||a;return c?.timed||!1}(t.inContextMatchUp),u=t.removeScore||!c&&![_a,Na].includes(n||_a),d=t.isCollectionMatchUp&&t.dualMatchUp.winningSide&&!t.projectedWinningSide||e.winningSide&&!i&&!$s({score:r}),p=n&&n!==ja,l=n=>{let r;const{structure:i,drawDefinition:a,dualMatchUp:o,disableAutoCalc:s}=t;if(o?._disableAutoCalc&&!1!==s)return eI(t);const{connectedStructureIds:c}=tI({drawDefinition:a,structure:i,matchUp:e});c.length&&(console.log({connectedStructureIds:c}),r=!0),Object.assign(t,{removeScore:n});const u=Wg(t);if(u.error)return u;if(t.removingQualifier&&t.appliedPolicies?.[bi]?.autoRemoveQualifiers){const e=function(t){let e;const{inContextDrawMatchUps:n,inContextMatchUp:r,drawDefinition:i}=t,a=t.targetData.targetLinks?.winnerTargetLink;if(a.target.feedProfile===fo){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===ja&&!rI({inContextDrawMatchUps:n,drawDefinition:i,targetData:Uc({matchUpId:s.matchUpId,inContextDrawMatchUps:n,drawDefinition:i})})){const{structure:n}=ts({structureId:s.structureId,drawDefinition:i}),r=rs({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]))}Vs({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:i,structure:n}),e=!0}}}return{qualifierRemoved:e}}(t);return{...E,connectedStructures:r,...e}}return{...E,connectedStructures:r}};if(d&&i&&t.isCollectionMatchUp)return uI(t);const m=[Aa,Na].includes(n)&&t.dualWinningSideChange;return wr({result:(i||m)&&iI(t)||s&&l(u)||p&&Xg(t)||d&&l(u)||e&&uI({...t,removeScore:!0})||{...E},stack:a})}function uI(t){if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){const e=Wg(t);if(e.error)return e}const e=qg({...t});if(t.isCollectionMatchUp){const{matchUpTieId:e,drawDefinition:n,event:r,matchUpsMap:i}=t,{removeWinningSide:a}=$g({tournamentRecord:t.tournamentRecord,matchUpId:e,drawDefinition:n,matchUpsMap:i,event:r});a&&console.log("REMOVE WINNING SIDE")}return wr({result:e,stack:"scoreModification"})}function dI({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,courtDayDate:a,matchUpId:o,courtIds:s}){if(!n&&!e)return{error:_};if(!o)return{error:qt};const c=Xm({drawDefinition:r,matchUpId:o});if(c.error)return c;if(c?.matchUp?.matchUpType!==Xs)return{error:Yt};if(!(void 0===s||Array.isArray(s)&&s.length&&s.every((t=>"string"==typeof t))))return{error:Nn,context:{courtIds:s}};let u;if(s){const t=Am({tournamentRecords:e||n&&{[n.tournamentId]:n}});if(t.error)return t;const r=t.courts?.filter((t=>s.includes(t.courtId)));if(r?.length!==s.length)return{error:Nn,context:{courtIds:s}};u=r?.map((t=>({venueId:t.venueId,courtId:t.courtId})))}return Ff({duplicateValues:!1,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o,timeItem:{itemType:Pu,itemDate:a,itemValue:u}})}function pI({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,venueId:o}){if(!n)return{error:_};if(!a)return{error:qt};if(o){const t=Cd({tournamentRecords:e,tournamentRecord:n,venueId:o});if(t.error)return t}return Ff({duplicateValues:!1,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:{itemType:Tu,itemValue:o}})}function lI({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,courtDayDate:a,matchUpId:o,courtId:s}){if(!n&&!e)return{error:_};if(!o)return{error:qt};if(s){const t=Od({tournamentRecords:e,tournamentRecord:n,courtId:s});if(t.error)return t;const a=t.venue?.venueId;pI({tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o,venueId:a})}return Ff({duplicateValues:!1,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o,timeItem:{itemType:Du,itemDate:a,itemValue:s}})}function mI(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 wr({result:{error:qt},stack:e});if(!$r(s))return wr({result:{error:le},stack:e});if(!n){const t=Xm({drawDefinition:a,matchUpId:c});if(t.error)return wr({result:t,stack:e});n=t.matchUp}const u=ri(s),d=Pd({matchUp:n}).scheduledDate,p=u&&!d,l=xd({matchUp:n}).timeModifiers||[];if(l?.length){const t=fI({disableNotice:!0,removePriorValues:r,tournamentRecord:i,timeModifiers:[],drawDefinition:a,matchUpId:c,matchUp:n});if(t?.error)return wr({result:t,stack:e})}const m=oi(s,!0,p);return Ff({duplicateValues:!1,removePriorValues:r,tournamentRecord:i,drawDefinition:a,disableNotice:o,matchUpId:c,timeItem:{itemType:Mu,itemValue:m}})}function fI({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,timeModifiers:i,matchUpId:a,matchUp:o}){const s="addMatchUpTimeModifiers";if(!a)return wr({result:{error:qt},stack:s});if(void 0!==i&&!Array.isArray(i))return wr({info:Pf("timeModifiers"),result:{error:Nn},stack:s});if(!o){const t=Xm({drawDefinition:n,matchUpId:a});if(t.error)return wr({result:t,stack:s});o=t.matchUp}let c=xd({matchUp:o}).timeModifiers||[];const u=i.filter((t=>!c.includes(t)));if(i.length&&!u.length)return{...E};if(u.some((t=>Vu.includes(t)))){c=c.filter((t=>!Vu.includes(t)));const r=mI({disableNotice:!0,removePriorValues:t,scheduledTime:"",tournamentRecord:e,drawDefinition:n,matchUpId:a});if(r.error)return wr({result:r,stack:s})}const d=i?.length?[...u,...c]:void 0;return Ff({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:a,timeItem:{itemType:Fu,itemValue:d}})}function hI(t,e){const n=Br.test(t)?t:ni(t),r=ri(t)||ri(e)||zr(new Date);return new Date(`${r}T${n}`).getTime()}function gI({errorOnAnachronism:t=!1,checkChronology:e=!0,matchUpDependencies:n,inContextMatchUps:r,removePriorValues:i,tournamentRecords:a,tournamentRecord:o,drawDefinition:s,disableNotice:c,drawMatchUps:u,matchUpId:d,schedule:l,event:m}){if(!l)return{error:ae,info:"Missing schedule"};if(!s)return{error:j};if(!d)return{error:qt};const f="addMatchUpScheduleItems";let h,g;if(u)h=u.find((t=>t.matchUpId===d));else{const t=Xm({drawDefinition:s,event:m,matchUpId:d});if(t.error)return t;h=t.matchUp}const{endTime:I,courtId:U,courtIds:S,courtOrder:y,resumeTime:v,scheduledDate:w,scheduledTime:T,startTime:P,stopTime:D,timeModifiers:b,venueId:N}=l;!e||n&&r||({matchUpDependencies:n,matchUps:r}=Sl({drawDefinition:s}));const R=n?.[d]?.matchUpIds;if(l.scheduledDate&&e&&R){const e=r?.filter((t=>(t.schedule?.scheduledDate||ri(t.schedule?.scheduledTime))&&R.includes(t.matchUpId))).map((({schedule:t})=>{const e=Gr(t);return new Date(e).getTime()}));if(e?.length){const n=Gr(l),r=new Date(n).getTime();if(Math.max(...e)>=r){if(t)return wr({result:{error:O},stack:f});g=O}}}if(void 0!==w){const t=II({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,scheduledDate:w,matchUpId:d});if(t?.error)return wr({result:t,stack:f,context:{scheduledDate:w}})}if(void 0!==T){const t=mI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,scheduledTime:T,matchUpId:d,matchUp:h});if(t?.error)return wr({result:t,stack:f,context:{scheduledTime:T}})}if(void 0!==P){const t=SI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,matchUpId:d,startTime:P,event:m});if(t?.error)return wr({result:t,stack:f,context:{startTime:P}})}if(void 0!==D){const t=vI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,matchUpId:d,stopTime:D,event:m});if(t?.error)return wr({result:t,stack:f,context:{stopTime:D}})}if(void 0!==v){const t=wI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,resumeTime:v,matchUpId:d,event:m});if(t?.error)return wr({result:t,stack:f,context:{resumeTime:v}})}if(void 0!==I){const t=yI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,matchUpId:d,endTime:I,event:m});if(t?.error)return wr({result:t,stack:f,context:{endTime:I}})}if(void 0!==S){const t=dI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,matchUpId:d,courtIds:S});if(t?.error)return wr({result:t,stack:f,context:{courtIds:S}})}if(void 0!==U&&void 0!==w){const t=lI({courtDayDate:w,disableNotice:!0,removePriorValues:i,tournamentRecords:a,tournamentRecord:o,drawDefinition:s,matchUpId:d,courtId:U});if(t?.error)return wr({result:t,stack:f,context:{courtId:U}})}if(void 0!==N){const t=pI({disableNotice:!0,removePriorValues:i,tournamentRecords:a,tournamentRecord:o,drawDefinition:s,matchUpId:d,venueId:N});if(t?.error)return wr({result:t,stack:f,context:{venueId:N}})}if(void 0!==y&&p(y)){const t=UI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,courtOrder:y,matchUpId:d});if(t?.error)return wr({result:t,stack:f,context:{courtOrder:y}})}if(void 0!==b){const t=fI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,timeModifiers:b,matchUpId:d,matchUp:h});if(t?.error)return wr({result:t,stack:f,context:{timeModifiers:b}})}return c||xs({tournamentId:o?.tournamentId,eventId:m?.eventId,context:f,drawDefinition:s,matchUp:h}),g?{...E,warnings:[g]}:{...E}}function II({scheduledDate:t,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a}){if(!a)return{error:qt};const o=t&&Vr.test(t);if(t&&!o)return{error:pe};return Ff({duplicateValues:!1,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:{itemValue:ri(t),itemType:Nu}})}function UI({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:i,courtOrder:a,matchUpId:o}){if(!o)return{error:qt};if(a&&!p(a))return{error:Nn,info:"courtOrder must be numeric"};const s=a&&n(a);return Ff({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:i,matchUpId:o,timeItem:{itemType:bu,itemValue:s}})}function SI({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,startTime:a,event:o}){if(!i)return{error:qt};if(!$r(a))return{error:le};const{matchUp:s}=Xm({drawDefinition:n,event:o,matchUpId:i}),{scheduledDate:c}=Pd({matchUp:s}),u=(s?.timeItems??[]).filter((t=>[Eu,Cu,Ou].includes(t?.itemType))).map((t=>hI(t.itemValue,c))).reduce(((t,e)=>!t||e<t?e:t),void 0);if(!u||hI(a,c)<u){s?.timeItems&&(s.timeItems=s.timeItems.filter((t=>t.itemType!==Au)));const o=oi(a,!0,!0);return Ff({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,timeItem:{itemType:Au,itemValue:o}})}return{error:un}}function yI({validateTimeSeries:t=!0,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,endTime:o,event:s}){if(!a)return{error:qt};if(!$r(o))return{error:le};const{matchUp:c}=Xm({drawDefinition:r,event:s,matchUpId:a}),{scheduledDate:u}=Pd({matchUp:c}),d=(c?.timeItems??[]).filter((t=>[Au,Cu,Eu].includes(t?.itemType))).map((t=>hI(t.itemValue,u))).reduce(((t,e)=>!t||e>t?e:t),void 0);if(!t||!d||hI(o,u)>d){c?.timeItems&&(c.timeItems=c.timeItems.filter((t=>t.itemType!==Ou)));const t=oi(o,!0,!0);return Ff({duplicateValues:!1,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:{itemType:Ou,itemValue:t}})}return{error:on}}function vI({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,stopTime:a,event:o}){if(!i)return{error:qt};if(!$r(a))return{error:le};const{matchUp:s}=Xm({drawDefinition:n,event:o,matchUpId:i}),{scheduledDate:c}=Pd({matchUp:s}),u=s?.timeItems??[];if(u.reduce(((t,e)=>e.itemType===Ou||t),void 0))return{error:sn};const d=u.filter((t=>[Au,Cu,Eu].includes(t?.itemType))).sort(((t,e)=>hI(t.itemValue,c)-hI(e.itemValue,c))),p=d[d.length-1],l=p&&p.itemType===Eu,m=d.filter((t=>!l||t.createdAt!==p.createdAt)).map((t=>hI(t.itemValue,c))).reduce(((t,e)=>!t||e>t?e:t),void 0);if(hI(a,c)>m){if(s?.timeItems&&l){const t=p.createdAt;s.timeItems=s.timeItems.filter((e=>e.createdAt!==t))}return Ff({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,timeItem:{itemValue:oi(a,!0,!0),itemType:Eu}})}return{error:cn}}function wI({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,resumeTime:i,matchUpId:a,event:o}){if(!a)return{error:qt};if(!$r(i))return{error:le};const{matchUp:s}=Xm({drawDefinition:n,event:o,matchUpId:a}),{scheduledDate:c}=Pd({matchUp:s}),u=s?.timeItems??[];if(u.reduce(((t,e)=>e.itemType===Ou||t),void 0))return{error:sn};const d=u.filter((t=>[Au,Cu,Eu].includes(t?.itemType))).sort(((t,e)=>hI(t.itemValue,c)-hI(e.itemValue,c))),p=d[d.length-1],l=p&&p.itemType===Cu,m=d.filter((t=>!l||t.createdAt!==p.createdAt)).map((t=>hI(t.itemValue,c))).reduce(((t,e)=>!t||e>t?e:t),void 0);if(hI(i,c)>m){if(s?.timeItems&&l){const t=p.createdAt;s.timeItems=s.timeItems.filter((e=>e.createdAt!==t))}return Ff({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:a,timeItem:{itemValue:oi(i,!0,!0),itemType:Cu}})}return{error:dn}}function TI({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:n,winningSide:r,score:i}){if("object"!=typeof i)return{error:Nn};const{sets:a,scoreStringSide1:o,scoreStringSide2:s}=i,c="scoreString must be a string!";if(void 0!==o&&"string"!=typeof o)return{error:Nn,info:c};if(void 0!==s&&"string"!=typeof s)return{error:Nn,info:c};if(void 0!==a&&!Array.isArray(a))return{error:Nn,info:Pf("sets")};if(a?.length){const o=a.map((t=>t?.setNumber)).filter(Boolean);if(o.length!==m(o).length)return{error:Nn,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!==t)))).every((t=>t.every((t=>p(t))))))return{error:Nn,info:"non-numeric values"};if(![c,s].filter((t=>void 0!==t)).every((t=>p(t))))return{error:Nn,info:"non-numeric values"};if(s&&![1,2].includes(s))return{error:Nn,info:"winningSide must be 1 or 2"}}const{valid:s}=function({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;return n?(t[n-1]++,t):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?Jd(e):void 0,l=Math.max(...o),m=g(o)[l],f=p?.bestOf,h=f&&Math.ceil(f/2)||1,I=n??t,U=I&&[Oa,Ba,Ga].includes(I),S=!p||!a.length||a.every(((t,e)=>{const n=e+1,r=n===f,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:h,setFormat:g}=p,I=r&&h||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}}return!I.setTo||!(!I.noTiebreak&&l>I.setTo+1)})),y=(!e||l===h)&&1===m&&o.indexOf(l)+1||void 0;return{valid:S&&(r&&u>d&&r===y||!r&&!y||U)}}({existingMatchUpStatus:t,matchUpStatus:n,matchUpFormat:e,winningSide:r,score:i});if(!s)return{error:he,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}function PI(t){const e="setMatchUpStatus";t.matchUpStatus&&[Ga,ka].includes(t.matchUpStatus)&&(t.score=void 0);const{allowChangePropagation:n,disableScoreValidation:r,tournamentRecords:i,tournamentRecord:a,disableAutoCalc:o,enableAutoCalc:s,drawDefinition:c,matchUpStatus:u,winningSide:d,matchUpId:p,event:l,score:m}=t;if(!c)return{error:j};if(u&&[Aa,_a,Na,ja].includes(u)&&d)return{error:Nn,winningSide:d,matchUpStatus:u};if(![void 0,...Wa].includes(u))return wr({result:{error:_t},info:"matchUpStatus does not exist",stack:"setMatchUpStatus"});const f=xc({drawDefinition:c}),{matchUps:h}=Jp({nextMatchUps:!0,inContext:!0,drawDefinition:c,matchUpsMap:f,event:l}),g=f.drawMatchUps.find((t=>t.matchUpId===p)),I=h?.find((t=>t.matchUpId===p));if(!g||!h)return{error:Wt};if((g.winningSide||d)&&u===Ma)return{context:"Cannot have Bye with winningSide",error:xt,matchUpStatus:u};const U=I?.structureId,{structure:S}=ts({drawDefinition:c,structureId:U}),y=I?.drawPositions?.filter(Boolean);let v;if(g.matchUpType===Qs){if(o)Nr({extension:{name:Hi,value:!0},element:g});else if(s){const e=g.winningSide;Dr({name:Hi,element:g});const{winningSide:n,scoreStringSide1:r,scoreStringSide2:i,set:a}=_g({drawDefinition:c,matchUpsMap:f,structure:S,matchUp:g,event:l}),o={scoreStringSide1:r,scoreStringSide2:i,sets:a?[a]:[]};v=n!==e,Object.assign(t,{winningSide:n,dualWinningSideChange:v,projectedWinningSide:n,score:o})}Vf({tournamentId:a?.tournamentId,inContextDualMatchUp:I,eventId:l?.eventId,drawDefinition:c,dualMatchUp:g})}if(g.matchUpType===Qs&&u&&[Ra].includes(u))return{error:Nn,info:"Not supported for matchUpType: TEAM"};const w=I?.matchUpTieId,T=Uc({matchUpId:w||p,inContextDrawMatchUps:h,drawDefinition:c});if(m&&g.matchUpType!==Qs&&!r){const t=g.matchUpFormat??S?.matchUpFormat??c?.matchUpFormat??l?.matchUpFormat,e=TI({existingMatchUpStatus:g.matchUpStatus,matchUpFormat:t,matchUpStatus:u,winningSide:d,score:m});if(e.error)return e}const P=g?.sides?[]:rs({drawDefinition:c,structureId:U}).positionAssignments,D=2===g.sides?.map((t=>t.participantId)).filter(Boolean).length||2===y?.length&&P?.filter((t=>y.includes(t.drawPosition))).every((t=>t.participantId));if(u&&$a.includes(u)&&!D)return wr({info:"present in participantRequiredMatchUpStatuses",context:{matchUpStatus:u,bothSideParticipants:D},result:{error:_t}});const b=Dc({policyTypes:[bi],tournamentRecord:a,drawDefinition:c,event:l})?.appliedPolicies??{};"object"==typeof t.policyDefinitions&&Object.assign(b,t.policyDefinitions);const N=I?.stage===Qa&&1===I.finishingRound,R=N&&d,M=N&&g.winningSide&&!d&&(!t.matchUpStatus||t.matchUpStatus&&Hs({matchUpStatus:t.matchUpStatus}))&&(!t.outcome||!$s({outcome:t.outcome})),A=R&&d!==g.winningSide&&g.winningSide;if(Object.assign(t,{inContextDrawMatchUps:h,qualifierAdvancing:R,qualifierChanging:A,removingQualifier:M,inContextMatchUp:I,appliedPolicies:b,matchUpTieId:w,matchUpsMap:f,targetData:T,structure:S,matchUp:g}),w){const{matchUp:e}=Xm({matchUpId:w,inContext:!0,drawDefinition:c,matchUpsMap:f,event:l});if(e){const n=$d({matchUp:e,drawDefinition:c,structure:S,event:l})?.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=gi(i,void 0,!0);for(const t of d?.tieMatchUps||[])t.matchUpId===s.matchUpId&&(t.winningSide=r,t.score=u,$s({score:u})||e?e&&(t.matchUpStatus=e):Object.assign(t,{...Lg}));a=a??$d({matchUp:s,structure:o,drawDefinition:t,event:c})?.tieFormat;const{winningSide:p}=_g({matchUp:d,drawDefinition:t,matchUpsMap:n,structure:o,tieFormat:a,event:c});return{projectedWinningSide:p}}({drawDefinition:c,matchUpStatus:u,dualMatchUp:e,matchUpsMap:f,winningSide:d,tieFormat:n,structure:S,matchUp:g,event:l,score:m});v=r!==e.winningSide,Object.assign(t,{isCollectionMatchUp:!0,dualWinningSideChange:v,projectedWinningSide:r,matchUpTieId:w,dualMatchUp:e,tieFormat:n})}}const E=rI(t),C=Ws({matchUpStatus:u});if(!w){if(E&&!d&&(u&&Hs({matchUpStatus:u})||u&&[ka,Fa].includes(u)))return{error:xt,activeDownstream:E,winningSide:d};if(d&&d===g.winningSide&&u&&!C)return{context:"winningSide must include directing matchUpStatus",error:xt,directingMatchUpStatus:C,matchUpStatus:u}}const{schedule:O}=t;if(O){const t=gI({disableNotice:!0,tournamentRecords:i,tournamentRecord:a,drawDefinition:c,matchUpId:p,schedule:O});if(t.error)return t}const F=g.matchUpType!==Qs&&!v&&d&&g.winningSide&&g.winningSide!==d;if(n&&F&&g.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}=Yp(t),m=l.filter((({drawPositions:t,roundNumber:e})=>t?.includes(c)&&e>a));Qn({changeWinner:!0})&&console.log({existingWinnerSubsequentMatchUps:m}),m.forEach((n=>{n.drawPositions=n.drawPositions?.map((t=>t===c?d:t))||[],xs({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,S=[I?.target.structureId,U?.target?.structureId].filter(Boolean);return i.structures.filter((({stage:t,structureId:e})=>t!==f&&S.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}=rs({structure:t}),n=e?.find((({participantId:t})=>t===u)),r=e?.find((({participantId:t})=>t===p));n&&(n.participantId=p),r&&(r.participantId=u)})),qg(t)}(t);const k=d&&!w||t.projectedWinningSide;Pl({method:e,activeDownstream:E,matchUpWinner:k,winningSide:d});const x=!E&&cI(t)||k&&function(t){const{matchUp:e,winningSide:n,matchUpTieId:r,dualWinningSideChange:i}=t;return n===e.winningSide||r&&!i?DI(t):wr({stack:"winningSideWithDownstreamDependencies",result:{error:ve},context:{winningSide:n,matchUp:e}})}(t)||C&&DI(t)||{error:An};return wr({result:x,stack:e})}function DI(t){const{tournamentRecord:e,matchUp:n,event:r}=t,i=t.isCollectionMatchUp&&n.winningSide&&!t.winningSide&&!$s({score:t.score}),a=t.isCollectionMatchUp?t.matchUpStatus||i&&ja||Ea:t.matchUpStatus||Ea,o=t.removeScore||[Aa,Ga].includes(a)&&![_a,Na].includes(a),s=qg({...t,matchUpStatus:a,removeWinningSide:i,removeScore:o});if(s.error)return s;if(t.isCollectionMatchUp){const{matchUpTieId:n,drawDefinition:i,matchUpsMap:a}=t,o=$g({matchUpId:n,tournamentRecord:e,drawDefinition:i,matchUpsMap:a,event:r});if(o.error)return o;Object.assign(s,{tieMatchUpResult:o})}return s}function bI({event:t,orderedDrawIdsMap:e}){if("object"!=typeof t)return{error:Tt};if(!e)return{error:ae,info:"Missing drawIdsOrderMap"};if("object"!=typeof e)return{error:Nn,info:"orderedDrawIdsMap must be an object"};const n=Object.values(e);if(!n.every((t=>!isNaN(t))))return{error:Nn,info:"drawOrder must be numeric"};if(m(n).length!==n.length)return{error:Nn,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&&P(n,r).length!==n.length)return{error:Nn,info:"Missing drawIds"};t.drawDefinitions.forEach((t=>{t.drawOrder=e[t.drawId]}))}const{flightProfile:r}=Bd({event:t});return r?.flights?.forEach((t=>{t.flightNumber=e[t.drawId]})),{...E}}function NI({tournamentRecord:t,event:e}){if(!t)return{error:_};if(!e)return{error:Tt};const{flightProfile:n}=Bd({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?bI({event:e,orderedDrawIdsMap:r}):{...E}}function RI({drawDefinition:t,timeItem:e}){if(!t)return{error:q};if(!e)return{error:mn};const n=e&&Object.keys(e),r=["itemType","itemValue"];if(!(r.filter((t=>n.includes(t))).length===r.length))return{error:pn};t.timeItems||(t.timeItems=[]);const i=(new Date).toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),_s({drawDefinition:t}),{...E}}function MI({stageSequence:t=1,drawDefinition:e,drawSize:n,stage:r}){if(!e)return{error:j};if(!uu({drawDefinition:e,stage:r}))return{error:At};const i=function({stage:t,drawDefinition:e}){return au.reduce(((n,r)=>(du({drawDefinition:e,entryStatus:r,stage:t})||0)+n),0)}({drawDefinition:e,stage:r}),{qualifiersCount:a}=Ql({drawDefinition:e,stageSequence:t,stage:r});if(n<i+a)return{error:rt};const{entryProfile:o}=Gc({attributes:[{[r]:{drawSize:n}}],drawDefinition:e});return Ls({drawDefinition:e}),{...E,entryProfile:o}}function AI({qualifiersCount:t=0,drawDefinition:e,stage:n}){return e?uu({drawDefinition:e,stage:n})?n!==Xa?{error:rt,info:"qualifiersCount can only be set for main stage"}:(Gc({attributes:[{[n]:{qualifiersCount:t}}],drawDefinition:e}),Ls({drawDefinition:e}),{...E}):{error:At}:{error:j}}function EI({updateInProgressMatchUps:t,originalValueGoal:e,tournamentRecord:n,wasAggregateValue:r,tieFormatName:i,drawDefinition:a,structureId:o,structure:s,tieFormat:c,matchUpId:u,matchUp:d,eventId:p,event:l}){const{aggregateValue:m,valueGoal:f}=Jf(c);c.winCriteria=vr({aggregateValue:m,valueGoal:f}),(e&&e!==f||m&&!r)&&(i?c.tieFormatName=i:delete c.tieFormatName);const{targetMatchUps:h}=function({updateInProgressMatchUps:t,drawDefinition:e,structureId:n,structure:r,matchUpId:i,matchUp:a}){let o=[];return i&&a?o=[a]:n&&r?o=Yp({matchUpFilters:{matchUpTypes:[Qs]},structure:r})?.matchUps??[]:e&&(o=Ul({matchUpFilters:{matchUpTypes:[Qs]},drawDefinition:e})?.matchUps??[]),{targetMatchUps:o.filter((e=>!e.winningSide&&e.matchUpStatus!==Ea&&(t||e.matchUpStatus!==xa&&!$s(e))))}}({updateInProgressMatchUps:t,drawDefinition:a,structureId:o,structure:s,matchUpId:u,matchUp:d});!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=Yf(i)),t){const t=$g({matchUpId:o.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,drawDefinition:n,event:a});if(t.error)return t;s=t.score}r&&!s&&xs({tournamentId:e?.tournamentId,context:"updateTargetTeamMatchUps",eventId:a?.eventId,matchUp:o,drawDefinition:n})}}({updateInProgressMatchUps:t,tournamentRecord:n,targetMatchUps:h,drawDefinition:a,tieFormat:c,event:l});const g=vr(c),I=fh({tieFormat:g});if(I.error)return I;if(p&&l)l.tieFormat=g;else if(u&&d)d.tieFormat=c;else if(s)s.tieFormat=g;else if(a)a.tieFormat=g;else if(!d||!a)return{error:j};return Ls({drawDefinition:a,eventId:l?.eventId}),{...E}}function CI({tieFormat:t,orderMap:e}){const n=Yf(t);return n.collectionDefinitions.forEach((t=>{const n=e[t.collectionId];n&&(t.collectionOrder=n)})),n.collectionDefinitions.sort(((t,e)=>h(t.collectionOrder)-h(e.collectionOrder))),n}function OI({tournamentRecord:t,structureIds:e,orderMap:n,event:r}){const i=CI({tieFormat:r.tieFormat,orderMap:n});e?.length||(r.tieFormat=i);for(const i of r.drawDefinitions??[])FI({tournamentRecord:t,drawDefinition:i,structureIds:e,orderMap:n,event:r})}function FI({tournamentRecord:t,drawDefinition:e,structureIds:n,orderMap:r,event:i}){const a=CI({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=CI({tieFormat:a.tieFormat??e.tieFormat??i?.tieFormat,orderMap:r})),kI({eventId:i?.eventId,tournamentRecord:t,drawDefinition:e,structure:a,orderMap:r}),o.push(a.structureId));Ls({drawDefinition:e,structureIds:o})}function kI({tournamentRecord:t,drawDefinition:e,structure:n,orderMap:r,eventId:i}){const a=Yp({matchUpFilters:{matchUpTypes:[Qs]},structure:n})?.matchUps;for(const n of a)n.tieFormat&&(n.tieFormat=CI({tieFormat:n.tieFormat,orderMap:r}),xs({tournamentId:t?.tournamentId,drawDefinition:e,eventId:i,matchUp:n}))}function xI({updateInProgressMatchUps:t=!0,tieFormatComparison:e,tournamentRecord:n,drawDefinition:r,tieFormatName:i,collectionId:a,structureId:o,matchUpId:s,eventId:c,matchUp:u,event:d}){const p="removeCollectionDefinition";let l=u?void 0:Zf({drawDefinition:r,structureId:o,matchUpId:s,eventId:c,event:d});if(l?.error)return wr({result:l,stack:p});const m=l?.structure;u=u??l?.matchUp;const f=l?.tieFormat,h=Yf(f);if(l=fh({tieFormat:h}),l.error)return wr({result:l,stack:p});const g=h?.collectionDefinitions?.find((t=>t.collectionId===a));if(!g)return wr({result:{error:On,collectionId:a}});h.collectionDefinitions=h.collectionDefinitions.filter((t=>t.collectionId!==a)),g.collectionGroupNumber&&(h.collectionDefinitions=h.collectionDefinitions.map((t=>{const{collectionGroupNumber:e,...n}=t;return n})),h.collectionGroups=h.collectionGroups.filter((({groupNumber:t})=>t!==g.collectionGroupNumber)));const{aggregateValue:I,valueGoal:U}=Jf(h);h.winCriteria=vr({aggregateValue:I,valueGoal:U});const S=f?.winCriteria.valueGoal,y=f?.winCriteria.aggregateValue;(S&&S!==U||I&&!y)&&(i?h.tieFormatName=i:delete h.tieFormatName);let v=[];s&&u?v=[u]:o&&m?v=Yp({matchUpFilters:{matchUpTypes:[Qs]},structure:m})?.matchUps??[]:r?v=Ul({matchUpFilters:{matchUpTypes:[Qs]},drawDefinition:r})?.matchUps??[]:d&&(v=fl({matchUpFilters:{matchUpTypes:[Qs]},drawDefinition:r})?.matchUps??[]);const w=(v||[]).filter((n=>{const r=n.tieMatchUps?.filter((t=>t.collectionId===a)),i=r?.some($s),o=!(!e||!n.tieFormat)&&Uh({descendant:n.tieFormat,ancestor:h})?.different;return t&&!i||!n.winningSide&&n.matchUpStatus!==Ea&&(t||n.matchUpStatus!==xa&&!$s(n)&&!o)}));if(!w.length)return{error:Sn};if(s&&u&&t){const t=u.tieMatchUps?.filter((t=>t.collectionId===a));for(const e of t??[]){let t=PI({matchUpId:e.matchUpId,tieMatchUpId:u?.matchUpId,winningSide:void 0,removeScore:!0,tournamentRecord:n,drawDefinition:r,event:d});if(t.error)return t;if(t=Xm({drawDefinition:r,matchUpId:s}),t.error)return t;u=t?.matchUp}}const T=[];for(const e of w){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=Yf(h)),t){const t=$g({matchUpId:e.matchUpId,exitWhenNoValues:!0,tournamentRecord:n,drawDefinition:r,event:d});if(t.error)return t}xs({tournamentId:n?.tournamentId,eventId:d?.eventId,drawDefinition:r,context:p,matchUp:e})}T.length&&ks({tournamentId:n?.tournamentId,matchUpIds:T,eventId:d?.eventId,drawDefinition:r});const P=vr(h);if(l=fh({tieFormat:P}),l.error)return wr({result:l,stack:p});if(c&&d)d.tieFormat=P;else if(s&&u)u.tieFormat=P;else if(m)m.tieFormat=P;else if(r)r.tieFormat=P;else if(!u||!r)return{error:j};Ls({drawDefinition:r,eventId:d?.eventId});const{appliedPolicies:D}=Dc({tournamentRecord:n});if(D?.audit?.[ua]){Th({drawDefinition:r,auditData:vr({drawId:r?.drawId,action:p,collectionId:a,structureId:o,matchUpId:s,eventId:c})})}return{tieFormat:P,deletedMatchUpIds:T,targetMatchUps:w,...E}}function _I({targetEntryRound:t=1,finishingPositions:e,sourceRoundNumber:n,sourceStructureId:r,targetStructureId:i,linkType:a=So}){if(!r||!i)return{error:It};return{link:vr({linkType:a,source:{roundNumber:n,structureId:r,finishingPositions:e},target:{feedProfile:fo,roundNumber:t,structureId:i}})}}function LI({roundPosition:t,roundNumber:e,idPrefix:n,uuids:r}){return n?`${n}-${e}-${t}`:r?.pop()||Md()}function BI({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:LI({roundPosition:d,roundNumber:n,idPrefix:i,uuids:o})};u.push(f);const h={drawPositions:f.children.map((t=>t?.drawPosition)).filter(Boolean),matchUpStatus:ja,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 VI({finishingPositionOffset:t,finishingPositionLimit:e,qualifyingRoundNumber:n,qualifyingPositions:i,matchUpType:a,roundLimit:o,idPrefix:s,drawSize:c,isMock:u,uuids:d}){if(isNaN(c)||c<2||i&&c<=i)return{matchUps:[],roundsCount:0};if(i&&(!r(c)||c%i)){let t=i;for(;t<c;)t*=2;c=t}const p=i&&!(c%2)&&(!isNaN(i)||n&&!isNaN(n))&&(c/i===Math.round(c/i)||n&&c/n===Math.round(c/n));if(!r(c)&&!p)return{matchUps:[],roundsCount:0};const l=w(1,c+1).map((t=>({drawPosition:t})));let m,f=[],h=1;for(({roundNodes:m,matchUps:f}=BI({matchUpType:a,roundNumber:h,idPrefix:s,matchUps:f,isMock:u,nodes:l,uuids:d})),h++,o=o??n;m.length>1;)i&&m.length===i&&(o=h-1),({roundNodes:m,matchUps:f}=BI({nodes:m,matchUpType:a,roundNumber:h,idPrefix:s,matchUps:f,isMock:u,uuids:d})),h++;const g=h-1;return f=Xp({finishingPositionOffset:t,finishingPositionLimit:e,roundsCount:g,roundLimit:o,matchUps:f}),o?f=f.filter((t=>o&&(t.roundNumber??0)<=o)):o=h-1,{drawSize:c,matchUps:f,roundsCount:g,roundLimit:o}}function jI(t){const e="generateQualifyingStructure";if(!t.drawDefinition)return wr({result:{error:j},stack:e});if(t.drawSize&&!p(t.drawSize)||t.participantsCount&&!p(t.participantsCount)||t.qualifyingPositions&&!p(t.qualifyingPositions))return wr({result:{error:Nn},stack:e});let n=t.drawSize??a(t.participantsCount);const{qualifyingRoundNumber:r,qualifyingPositions:i,targetStructureId:o,structureOptions:s,appliedPolicies:c,drawDefinition:u,matchUpFormat:d,structureName:l,structureId:m,roundTarget:f,drawType:h,idPrefix:g,isMock:I,uuids:U}=t;if(!t.drawSize)return wr({result:{error:it},context:{drawSize:n},stack:e});if(i&&i>=t.drawSize)return wr({result:{error:Nn},context:{drawSize:n,qualifyingPositions:i},stack:e});let S,y,v,w,T,P=0;const{structureProfiles:D}=Gm({drawDefinition:u}),b=D[o];if(!b)return wr({result:{error:Ut},context:{targetStructureId:o},stack:e});const N=u.matchUpType,R=f?`${f}-`:"",M=b.stage===Qa,A=c?.[Pi]?.namingConventions?.pre??op[Pi]?.namingConventions?.pre,C=M&&A?`${A}-`:"",O=l??(R?`${C}${wm(Qa)} ${R}`:`${C}${wm(Qa)}`);if(h===Go){const{maxRoundNumber:t,structures:e,groupCount:r}=pf({structureName:l??O,structureId:m??U?.pop(),stage:Qa,structureOptions:s,appliedPolicies:c,stageSequence:1,matchUpType:N,roundTarget:f,idPrefix:g,drawSize:n,isMock:I,uuids:U});P=r,S=t,v=e[0],T=[1]}else({drawSize:n,matchUps:w,roundLimit:S,roundsCount:y}=VI({qualifyingRoundNumber:r,qualifyingPositions:i,matchUpType:N,idPrefix:g,drawSize:n,isMock:I,uuids:U})),S||(S=y),v=Tm({structureName:l??O,structureId:m??U?.pop(),qualifyingRoundNumber:S,stage:Qa,matchUpFormat:d,stageSequence:1,matchUpType:N,roundLimit:S,matchUps:w}),f&&Nr({extension:{name:ra,value:f},element:v}),P=w?.filter((t=>t.roundNumber===S))?.length;const F=h===Go?Uo:So,k=v&&S&&_I({sourceStructureId:v.structureId,sourceRoundNumber:S,targetStructureId:o,finishingPositions:T,linkType:F})?.link;return{qualifyingDrawPositionsCount:n,qualifiersCount:P,...E,structure:v,link:k}}function GI(t){let e=t.structureIds;const{tournamentRecord:n,drawDefinition:r,matchUpFormat:i,structureId:a,matchUpId:o,event:s}=t;if(!r)return{error:j};if(!i)return{error:Vt};if(!rh(i))return{error:kt};if(o){const t=Xm({drawDefinition:r,matchUpId:o,event:s});if(t.error)return t;if(!t.matchUp)return{error:Wt};const e=t.matchUp;if(e?.matchUpType===id)return{error:Yt,info:"Cannot set matchUpFormat when { matchUpType: TEAM }"};e.matchUpFormat=i,xs({tournamentId:n?.tournamentId,eventId:s?.eventId,context:"setMatchUpFormat",drawDefinition:r,matchUp:e})}else if(Array.isArray(e)){if(s?.eventType===id)return{error:wt};for(const t of e){const e=ts({drawDefinition:r,structureId:t});if(e.error)return e;if(!e.structure)return{error:Ut};e.structure.matchUpFormat=i}}else if(a){if(s?.eventType===id)return{error:wt};const t=ts({drawDefinition:r,structureId:a});if(t.error)return t;if(!t.structure)return{error:Ut};t.structure.matchUpFormat=i}else r&&(r.matchUpFormat=i);return e=e??(a?[a]:void 0),Ls({drawDefinition:r,structureIds:e}),{...E}}function qI({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=w(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=LI({roundPosition:f.roundPosition,roundNumber:n,idPrefix:i,uuids:s}),g={roundPosition:f.roundPosition,drawPositions:[d],matchUpStatus:ja,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 $I(t){const e=t.drawSize;let{feedRoundsProfile:n,feedRounds:r=0,skipRounds:i=0,baseDrawSize:a}=t;const{linkFedFinishingRoundNumbers:s,finishingPositionOffset:c,linkFedRoundNumbers:u,feedsFromFinal:d,isConsolation:p,matchUpType:l,idPrefix:m,isMock:f,uuids:h,fmlc:I}=t;a=a??function(t){const e=o(t);return e>t?e/2:e}(e);const U=function({drawSize:t}){const e=Math.ceil(Math.log(t)/Math.log(2));return w(0,e).reverse().map((t=>Math.pow(2,t)))}({drawSize:a}),S=U.length;let y=0;if(n?.length)y=n.reduce(((t,e)=>t+e),0);else if(e){let t=e-a;n=U.filter((e=>e<=t&&(t-=e,!0))),y=n.reduce(((t,e)=>t+e),0),r=n.length}else i>=S?r=0:d&&(r=S-d,i=0),n=U.filter(((t,e)=>d&&!r||r&&e>=i+r||e<i?0:t)),y=n.reduce(((t,e)=>t+e),0),r=n.length;const v=[...U,...n].sort(((t,e)=>e-t)),T=v.length,P=[...(u??[]).map((t=>t-1)),...(s??[]).map((t=>T-t))].map((t=>v[t])).reduce(((t,e)=>t+e),0);y-=P;let D,b=0,N=[],R=1;let M=w(0,a).map(((t,e)=>({drawPosition:e+1+y}))),A=y+1;for(const t of U){if(({roundNodes:D,matchUps:N}=BI({matchUpType:l,roundNumber:R,idPrefix:m,matchUps:N,isMock:f,nodes:M,uuids:h})),R++,n.includes(t)){const e=w(0,g(n)[t]),r=T+1-R,i=s?.includes(r)??u?.includes(R);e.forEach((()=>{const t=!i&&A||void 0;({roundNodes:D,matchUps:N,drawPosition:A}=qI({drawPosition:t,nodes:D,matchUpType:l,roundNumber:R,idPrefix:m,matchUps:N,isMock:f,uuids:h,fed:b})),R++,b+=1}))}M=D}T!==R-1&&console.log("ERROR");N=Xp({finishingPositionOffset:p?a-y:c,positionsFed:y,roundsCount:T,matchUps:N,fmlc:I});const E=D?.length?D[0]:D;return E&&(E.roundNumber=R-1,E.matchUps=N),{draw:E,matchUps:N,roundsCount:T}}function WI(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=Xa,drawSize:g,idPrefix:I,isMock:U,uuids:S}=t;if(!(!o||!u||o?.[c])||g<2||f&&s>f)return{};const y=[],v=[],T=[],P=t.matchUpType??l?.matchUpType,D=e+1,b=`${D}-${e+g}`,N=o?.[c],R=r&&`${r} `||"",M=o?.[b]??i?.[b],A=t.structureName||M?.name||N?.name&&(n?`${R}${N?.name}`:N.name)||`${R}${b}`,C=M?.abbreviation??N?.abbreviation,O=t.structureId??N?.structureId??S?.pop(),F={idPrefix:I&&`${I}-${A}-RP`,finishingPositionOffset:e,matchUpType:P,drawSize:g,isMock:U,uuids:S},{matchUps:k}=m?$I(F):VI(F),x=Tm({structureAbbreviation:C,stageSequence:s,structureName:A,matchUpType:P,roundOffset:p,structureId:O,matchUps:k,stage:h});y.push(...k),v.push(x);const _=Math.ceil(Math.log(g)/Math.log(2)),L=d?Math.min(d-p,_):!a||D<a?_:0;return g>2&&w(1,L+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:w,structureId:D,matchUps:b,links:N}=WI({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:S,stage:h});if(x.structureId&&D){const e={linkType:yo,source:{roundNumber:t,structureId:x.structureId},target:{roundNumber:1,feedProfile:go,structureId:D}};N&&x&&N.push(e),N?.length&&T.push(...N)}w?.length&&v.push(...w);b?.length&&y.push(...b);return{structureId:D,childLinks:N,structures:v}}(t))),{structureId:x.structureId,matchUps:y,structureName:A,structures:v,links:T,...E}}function HI(t){const{finishingPositionOffset:e=0,playoffAttributes:n,stageSequence:r=1,staggeredEntry:i,structureName:a,stage:o=Xa,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?$I(m):VI(m),h=Tm({structureName:a||n?.[0]?.name||wm(Xa),structureId:c||l?.pop(),stageSequence:r,matchUpType:s,matchUps:f,stage:o}),g=[h],I=[];if(d>2){const r=d/2,{matchUps:i}=VI({finishingPositionOffset:e+r,idPrefix:u&&`${u}-c`,drawSize:r,matchUpType:s,isMock:p}),o=wm(to),c=n?.["0-1"]?.name??t.consolationStructureName??(a?`${a} ${o}`:o),m=Tm({structureName:c,matchUps:i,structureId:l?.pop(),stage:to,stageSequence:1,matchUpType:s});g.push(m);const f={linkType:yo,source:{roundNumber:1,structureId:h.structureId},target:{roundNumber:1,feedProfile:go,structureId:m.structureId}};I.push(f)}return{...E,structures:g,links:I}}function zI({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 w(1+e,r+1+e).map((r=>{const i=c&&c[r-1]?c[r-1]:r%2?go:Io,u=r-e<=2?r-e:2*(r-e-2)+2,d={linkType:yo,source:{roundNumber:r,structureId:n.structureId},target:{feedProfile:i,roundNumber:u,structureId:t.structureId}},p=s[r-1];return p&&(d.target.groupedOrder=p),Qn()&&(d.source.structureName=n.structureName,d.target.structureName=t.structureName),2===r&&a&&(d.linkCondition=vo,d.target.feedProfile=go),o.includes(u)?d:void 0})).filter(Boolean)}function YI(t){const{playoffStructureNameBase:e,finishingPositionOffset:n,stageSequence:r=1,playoffAttributes:i,structureNameMap:a,staggeredEntry:o,stage:s=Xa,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?$I(f):VI(f),I=t.structureName??i?.[0]?.name??wm(Xa),U=Tm({structureId:u||m?.pop(),structureName:I,stageSequence:r,matchUpType:c,matchUps:h,stage:s}),S=[U],y=[];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}=$I({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||`${wm(to)} ${d+1}`,I=r?.[g]||g,U=t?`${t} ${I}`:I,S=Tm({matchUps:m,stage:to,structureName:U,stageSequence:e,matchUpType:a,structureId:o});return{consolationStructure:S,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});S.push(o);return{consolationStructure:o,links:zI({consolationStructure:o,roundsCount:2,mainStructure:U,roundOffset:t})}})),n=t.map((t=>t.links)).flat();if(y.push(...n),d>=4&&d<=16||d>32){const{matchUps:t}=VI({idPrefix:p&&`${p}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:l}),n=i?.["3-4"]?.name??wm(no),r=a?.[n]||n,o=e?`${e} ${r}`:r,s=Tm({structureId:m?.pop(),matchUps:t,stageSequence:2,stage:no,structureName:o,matchUpType:c}),u={linkType:yo,source:{roundNumber:g-1,structureId:U.structureId},target:{structureId:s.structureId,feedProfile:go,roundNumber:1}};S.push(s),y.push(u)}}return{structures:S,links:y,...E}}function KI(t){const{finishingPositionOffset:e,stageSequence:n=1,playoffAttributes:r,policyDefinitions:i,feedsFromFinal:a,staggeredEntry:o,structureName:s,stage:c=Xa,structureId:u,matchUpType:d,skipRounds:p,feedRounds:l,idPrefix:m,drawSize:f,isMock:h,uuids:g,fmlc:I}=t,U=t.feedPolicy||i?.[Ei],S={finishingPositionOffset:e,matchUpType:d,skipRounds:p,drawSize:f,idPrefix:m,isMock:h,uuids:g},{matchUps:y}=o?$I(S):VI(S),v=Tm({structureName:s||r?.[0]?.name||wm(Xa),structureId:u||g?.pop(),stageSequence:n,matchUpType:d,matchUps:y,stage:c}),w=[v],T=[],P=f/2,{matchUps:D,roundsCount:b}=$I({finishingPositionOffset:P,idPrefix:m&&`${m}-c`,isConsolation:!0,feedsFromFinal:a,baseDrawSize:P,matchUpType:d,feedRounds:l,skipRounds:p,isMock:h,uuids:g,fmlc:I});if(f>2){const e=r?.["0-1"]?.name??wm(to),n=t.playoffStructureNameBase?`${t.playoffStructureNameBase} ${e}`:e,i=Tm({matchUps:D,structureId:g?.pop(),stage:to,stageSequence:1,structureName:n,matchUpType:d});w.push(i);const a=zI({consolationStructure:i,mainStructure:v,roundsCount:b,feedPolicy:U,fmlc:I});T.push(...a)}return{...E,structures:w,links:T}}function JI({requireSequential:t=!0,playoffMatchUpFormat:n,playoffAttributes:r,sourceStructureId:i,policyDefinitions:a,stageSequence:o,drawDefinition:s,playoffGroups:c,matchUpType:d,feedPolicy:p,groupCount:l,idPrefix:m,isMock:f,uuids:h}){p=p||a?.[Ei];const g="processPlayoffGroups";let I=0;const U=[],S=[],y=[],{error:v,positionRangeMap:w}=function({playoffGroups:t,drawDefinition:e,structureId:n}){if(!e)return{error:j};if("string"!=typeof n||!Array.isArray(t))return{error:Nn};const r=t.map((({finishingPositions:t})=>t)).flat(),i=sg({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:i,drawDefinition:s,playoffGroups:c});if(v)return wr({result:{error:v},stack:g});if(!(!w||c?.every((n=>{const{finishingPositions:r=[]}=n;if(!r.length)return!1;const i=r.sort(e).map(((t,e)=>(r[e+1]||t)-t)).every((t=>t<2));return(!t||i)&&r.every((t=>w[t]))}))))return wr({context:{validFinishingPositions:Object.values(w)},result:{error:Nn},stack:g});for(const t of c){const e=t.finishingPositions,s=w&&e.map((t=>w[t]?.finishingPositions)).flat(),c=l*e.length,g=u(c),v=2===g&&bo||t.drawType||bo;s&&(I=Math.min(...s)-1);const T=s&&`${Math.min(...s)}-${Math.max(...s)}`,P=t.structureName||T&&t.playoffAttributes?.[T]?.name||t.playoffAttributes?.[0]?.name,D={...{addNameBaseToAttributeName:t.addNameBaseToAttributeName,playoffStructureNameBase:t.playoffStructureNameBase,finishingPositionNaming:t.finishingPositionNaming,finishingPositionLimit:t.finishingPositionLimit,structureId:t.structureId??h?.pop(),playoffAttributes:t.playoffAttributes,structureNameMap:t.structureNameMap,sequenceLimit:t.sequenceLimit,structureName:P},idPrefix:m&&`${m}-po`,appliedPolicies:a,finishingPositionOffset:I,stage:no,stageSequence:o,matchUpType:d,drawSize:g,isMock:f,uuids:h},b=({playoffStructures:t,playoffLinks:n})=>{const[r]=t,a=ZI({playoffStructureId:r.structureId,finishingPositions:e,sourceStructureId:i});y.push(a),y.push(...n),S.push(...t),U.push({structureId:r.structureId,finishingPositions:e}),I+=c};if(v===bo){const{matchUps:r}=VI({finishingPositionLimit:I+c,idPrefix:m&&`${m}-po`,finishingPositionOffset:I,matchUpType:d,drawSize:g,isMock:f,uuids:h}),a=Tm({structureId:t.structureId??h?.pop(),matchUpFormat:n,stage:no,structureName:P,stageSequence:o,matchUps:r});S.push(a);const s=ZI({playoffStructureId:a.structureId,finishingPositions:e,sourceStructureId:i});y.push(s),I+=c,U.push({structureId:a.structureId,finishingPositions:e})}else if([Po,Do,no].includes(v)){const n={playoffAttributes:t.playoffAttributes??r,playoffStructureNameBase:t.playoffStructureNameBase,structureId:t.structureId??h?.pop(),structureName:t.structureName,idPrefix:m&&`${m}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:I,stage:no,roundOffset:0,stageSequence:o,drawSize:g,isMock:f,uuids:h};v===Po?Object.assign(n,{playoffAttributes:t?.playoffAttributes??r??Ho,roundOffsetLimit:3}):v===Do&&Object.assign(n,{playoffAttributes:t?.playoffAttributes??r??zo,roundOffsetLimit:2});const a=WI(n);if(a.error)return a;if(a.links?.length&&y.push(...a.links),a.structures?.length&&S.push(...a.structures),S.sort(Xo),a.structureId){const t=ZI({playoffStructureId:a.structureId,finishingPositions:e,sourceStructureId:i});y.push(t),U.push({structureId:a.structureId,finishingPositions:e})}I+=c}else if([Ro,jo,Lo,xo,Fo,Vo].includes(v)){const n=[h?.pop(),h?.pop()],r={playoffStructureNameBase:t.playoffStructureNameBase,structureId:t.structureId??h?.pop(),playoffAttributes:t.playoffAttributes,idPrefix:m&&`${m}-po`,finishingPositionOffset:I,uuids:n,stage:no,structureName:P,matchUpType:d,feedPolicy:p,drawSize:g,isMock:f},a={[Ro]:{fmlc:!0,feedRounds:1},[Vo]:{feedRounds:1},[Lo]:{feedsFromFinal:3},[xo]:{feedsFromFinal:2},[Fo]:{feedsFromFinal:1}};Object.assign(r,a[v]||{});const{structures:o,links:s}=KI(r),[u]=o,l=ZI({playoffStructureId:u.structureId,finishingPositions:e,sourceStructureId:i});y.push(l),y.push(...s),S.push(...o),U.push({structureId:u.structureId,finishingPositions:e}),I+=c}else if([Go].includes(v)){const{structures:e,links:n}=pf({...D,structureOptions:t.structureOptions||{groupSize:4}});b({playoffStructures:e,playoffLinks:n})}else if([Mo].includes(v)){const{structures:t,links:e}=HI(D);b({playoffStructures:t,playoffLinks:e})}else if([Co].includes(v)){const{structures:t,links:e}=YI(D);b({playoffStructures:t,playoffLinks:e})}else if([wo].includes(v)){b({playoffStructures:[Tm({structureId:t.structureId??h?.pop(),structureName:t.structureName,finishingPosition:Cc,stage:no,stageSequence:o,matchUps:[]})],playoffLinks:[]})}}return{finishingPositionTargets:U,positionRangeMap:w,structures:S,links:y}}function ZI({playoffStructureId:t,finishingPositions:e,sourceStructureId:n}){return{linkType:Uo,source:{structureId:n,finishingPositions:e},target:{structureId:t,feedProfile:fo,roundNumber:1}}}function XI(t){const e="genPlayoffStructure";if(!t.drawDefinition)return wr({result:{error:j},stack:e});const r=sg(t);if(r.error)return wr({result:r,stack:e});const{structureId:i,addNameBaseToAttributeName:a,playoffStructureNameBase:o,finishingPositionNaming:s,finishingPositionLimit:c,playoffAttributes:u,playoffPositions:d,roundOffsetLimit:p,tournamentRecord:l,exitProfileLimit:m,roundProfiles:f,roundNumbers:h,idPrefix:g,isMock:I,event:U,uuids:S}=t,y=gi(t.drawDefinition,!1,!0),{structure:v}=ts({structureId:i,drawDefinition:y});if(!v)return wr({result:{error:Ut},stack:e});if(v.structureType===mo||v.structures)return function(t){const e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return wr({result:{error:ae},info:"playoffGroups required",stack:e});const{sourceStructureId:n,requireSequential:r,tournamentRecord:i,drawDefinition:a,playoffGroups:o,groupCount:s,groupSize:c,event:u}=t,{structures:d=[],links:p=[],finishingPositionTargets:l,positionRangeMap:m,error:f}=JI({requireSequential:r,sourceStructureId:n,playoffGroups:o,groupCount:s,groupSize:c,...t});if(f)return{error:f};const h=l?.map((({finishingPositions:t})=>t)).flat().map((t=>m[t].finishingPositions)).flat();a.structures.push(...d),a.links.push(...p);const{matchUps:g,matchUpsMap:I}=Jp({inContext:!0,drawDefinition:a}),U=d.map((({structureId:t})=>t)),S=g?.filter((({structureId:t})=>U.includes(t))).map(ba),y=I?.drawMatchUps?.filter((({matchUpId:t})=>S?.includes(t)));if(y?.length){const e=$d({drawDefinition:a,event:u})?.tieFormat;e&&y.forEach((n=>{const{tieMatchUps:r}=hh({isMock:t.isMock,tieFormat:e});Object.assign(n,{tieMatchUps:r,matchUpType:Xs})}))}const{positionAssignments:v}=rs({structureId:n,drawDefinition:a}),w={};v?.forEach((t=>{const e=Mr({element:t,name:ca}),n=e?.extension?.value,r=n?.groupOrder;r&&(w[r]||(w[r]=[]),w[r].push(t.participantId))}));const T=tg({provisionalPositioning:t.provisionalPositioning,structureId:n,applyPositioning:!0,event:t.event,tournamentRecord:i,drawDefinition:a});return T.error&&T.error?.code!==W.code?wr({result:T,stack:e}):{structures:d,links:p,positionsPlayedOff:h,drawDefinition:a,...E}}({sourceStructureId:v.structureId,...t,...r,drawDefinition:y});const{playoffRoundsRanges:w,playoffRounds:T}=r,{playoffPositionsReturned:P,error:D,playoffSourceRounds:b,playoffRoundsRanges:N}=og(t);if(D)return wr({result:{error:D},stack:e});const R=f?.length&&Object.assign({},...f),M=h||"object"==typeof f&&f.map((t=>Object.keys(t))).flat(),A=Array.isArray(M)&&M.map((t=>!isNaN(t)&&n(t))).filter(Boolean);if(A){if(!Array.isArray(A))return wr({result:{error:Nn},context:{validRoundNumbers:A},stack:e});A.forEach((t=>{if(!T?.includes(t))return wr({result:{error:Nn},context:{roundNumber:t},stack:e})}))}d&&d.forEach((t=>{if(!P?.includes(t))return wr({result:{error:Nn},context:{playoffPosition:t},stack:e})}));const C=A||b,O=A?w:N,F=[],k=[];for(const t of C??[]){const n=O?.find((e=>e.roundNumber===t));if(!n)return wr({result:{error:Nn},context:{roundNumber:t},stack:e});const r=n.finishingPositions.length,d=Math.min(...n.finishingPositions)-1,l=2,f=t&&R?.[t]&&l+R[t]-1,h=WI({exitProfile:`0-${t}`,addNameBaseToAttributeName:a,playoffStructureNameBase:o,finishingPositionOffset:d,playoffAttributes:u,exitProfileLimit:m,stage:no,roundOffset:0,drawDefinition:y,sequenceLimit:f,stageSequence:l,drawSize:r,idPrefix:g,isMock:I,uuids:S,finishingPositionNaming:s,finishingPositionLimit:c,roundOffsetLimit:p});if(h.error)return wr({result:h,stack:e});const{structures:U,links:v}=h;if(U?.length&&F.push(...U),v?.length&&k.push(...v),h.structureId&&t){const e={linkType:yo,source:{structureId:i,roundNumber:t},target:{structureId:h.structureId,feedProfile:go,roundNumber:1}};k.push(e)}}if(!F.length)return wr({result:{error:Nn},info:"No structures generated",stack:e});y.structures.push(...F),y.links.push(...k);const{matchUps:x,matchUpsMap:_}=Jp({inContext:!0,drawDefinition:y}),L=F.map((({structureId:t})=>t)),B=x?.filter((({structureId:t})=>L.includes(t))).map(ba),V=_?.drawMatchUps?.filter((({matchUpId:t})=>B?.includes(t)));if(V?.length){const t=$d({drawDefinition:y,event:U})?.tieFormat;t&&V.forEach((e=>{const{tieMatchUps:n}=hh({tieFormat:t,isMock:I});Object.assign(e,{tieMatchUps:n,matchUpType:Qs})}))}const G=x?.filter((t=>Lc({matchUp:t})&&t.structureId===i));G?.forEach((t=>{const{matchUpId:e,score:n,winningSide:r}=t,i=Uc({inContextDrawMatchUps:x,drawDefinition:y,matchUpId:e}),a=nI({inContextDrawMatchUps:x,tournamentRecord:l,drawDefinition:y,matchUpsMap:_,winningSide:r,targetData:i,matchUpId:e,structure:v,matchUp:t,score:n,event:U});a.error&&console.log(a.error)}));const q=x?.filter((t=>t.matchUpStatus===Ma&&t.structureId===i));q?.forEach((t=>{const{matchUpId:e}=t,n=Uc({inContextDrawMatchUps:x,drawDefinition:y,matchUpId:e}),{targetLinks:{loserTargetLink:r},targetMatchUps:{loserMatchUpDrawPositionIndex:i,loserMatchUp:a}}=n;if(r&&a){const t=r.target.structureId,e=bl({drawPosition:a.drawPositions[i],structureId:t,tournamentRecord:l,drawDefinition:y,event:U});e.error&&console.log(e.error)}}));const $=[],H=Qp({inContextDrawMatchUps:x,drawDefinition:y,matchUpsMap:_}).goesToMap,{structure:z}=ts({drawDefinition:t.drawDefinition,structureId:i}),{matchUps:Y}=Yp({structure:z});return Y.forEach((n=>{const r=H?.loserMatchUpIds[n.matchUpId];if(r&&n.loserMatchUpId!==r){n.loserMatchUpId=r;const i={tournamentId:l?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:n};$.push(i)}const i=H?.winnerMatchUpIds[n.matchUpId];if(i&&n.winnerMatchUpId!==i){n.winnerMatchUpId=i;const r={tournamentId:l?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:n};$.push(r)}})),{structures:F,matchUpModifications:$,links:k,drawDefinition:y,...E}}function QI(t){return tU({...t,itemType:"attachPlayoffStructures"})}function tU({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:n,drawDefinition:r,structures:i,links:a=[],event:o}){const s="attachStructures";if(!r)return{error:j};if(!Array.isArray(i)||!Array.isArray(a))return wr({result:{error:Nn},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 wr({result:{error:Vn},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),Qp({drawDefinition:r});const m=i.map((t=>Yp({structure:t})?.matchUps||[])).flat();Fs({tournamentId:n?.tournamentId,eventId:o?.eventId,drawDefinition:r,matchUps:m});const f=i.map((({structureId:t})=>t));if(Ls({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,xs(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(Ua("structureId"));if(n){xm({element:n,timeItem:{itemValue:{structureIds:f,drawId:r.drawId},itemType:t}})}return{...E,addedStructureIds:h}}function eU(t){const{structures:e,links:n,matchUpModifications:r,error:i}=XI(t);if(i)return{error:i};const a=t.drawDefinition;return QI({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:r,drawDefinition:a,structures:e,links:n})}function nU(t){const{winnerFirst:e=!0,addOutcomeString:n,reversed:r=!1,matchUpStatus:i,matchUpFormat:a,autoComplete:o,winningSide:c,sets:u}=t;if(!u)return{error:ae,info:"missing sets"};const d=a&&Jd(a),{bestOf:p,finalSetFormat:l,setFormat:m}=d??{},f=r||!(!e||!c||1===c),h=n?function({matchUpStatus:t}){const e={[Ba]:"RET",[Ga]:"WO",[Fa]:"DF/DF",[ka]:"WO/WO",[Va]:"SUS",[Na]:"ABN",[Oa]:"DEF",[Ca]:"DR"};return t&&e[t]||""}({matchUpStatus:i}):"",g=u?.sort(rU).map((function(t){const e=p&&t.setNumber===p&&l?l:m,n=e?.tiebreakSet||(h=t,!(s(h?.side1Score)||s(h?.side2Score))&&(t=>s(t?.side1TiebreakScore)||s(t?.side2TiebreakScore))(t)),{side1Score:r,side2Score:i,side1TiebreakScore:a,side2TiebreakScore:c}=t,u=a||(s(a)||o?0:""),d=c||(s(c)||o?0:"");var h;if(n){return`[${(f?[d,u]:[u,d]).join("-")}]`}const g=Math.min(u,d),I=g?`(${g})`:"",U=r||(s(r)||o?0:""),S=i||(s(i)||o?0:"");let y=f?`${[S,U].join("-")}${I}`:`${[U,S].join("-")}${I}`;["-"," "].includes(y)&&(y="");return y})).filter(Boolean).join(" ")||"";return h?2===c?`${h} ${g}`:`${g} ${h}`:g}function rU(t,e){return t.setNumber-e.setNumber}function iU(t){const{matchUpFormat:e,matchUpStatus:n,winningSide:r,score:i}=t;if(!i)return{sets:[]};const a=i.sets||[];let o=nU({winnerFirst:!1,matchUpFormat:e,matchUpStatus:n,sets:a}),s=nU({winnerFirst:!1,reversed:!0,matchUpFormat:e,matchUpStatus:n,sets:a});const c=nU({matchUpFormat:e,matchUpStatus:n,winningSide:r,sets:a}),u=o===c?s:o;return r&&(o=1===r?c:u,s=2===r?c:u),{score:{sets:a,scoreStringSide1:o,scoreStringSide2:s}}}function aU(t){const e=nc(t);if(!t.drawDefinition){const n=t.tournamentRecord??(t.tournamentId&&e[t.tournamentId]);t.tournamentRecord||(t.tournamentRecord=n);const r=Vd({eventId:t.eventId,drawId:t.drawId,tournamentRecord:n});if(r.error)return r;r.drawDefinition&&(t.drawDefinition=r.drawDefinition),t.event=r.event}const{policyDefinitions:n,tournamentRecord:r,disableAutoCalc:i,enableAutoCalc:a,drawDefinition:o,matchUpFormat:s,matchUpId:c,schedule:u,event:d,notes:p}=t;if(!o)return{error:at};if(!c)return{error:qt};const{policy:l}=Uu({policyType:Mi,tournamentRecord:r,event:d}),m=void 0!==t.allowChangePropagation&&t.allowChangePropagation||void 0!==l?.allowChangePropagation&&l.allowChangePropagation||void 0,{outcome:f}=t;if(s){const t=GI({tournamentRecord:r,drawDefinition:o,matchUpFormat:s,matchUpId:c,event:d});if(t.error)return t}if(f?.score?.sets&&!f.score.scoreStringSide1){const{score:t}=iU(f);f.score=t,f.score.sets=f.score.sets.filter((t=>t.side1Score||t.side2Score||t.side1TiebreakScore||t.side2TiebreakScore))}return PI({matchUpStatusCodes:f?.matchUpStatusCodes,matchUpStatus:f?.matchUpStatus,winningSide:f?.winningSide,allowChangePropagation:m,score:f?.score,tournamentRecords:e,policyDefinitions:n,tournamentRecord:r,disableAutoCalc:i,enableAutoCalc:a,drawDefinition:o,matchUpFormat:s,matchUpId:c,schedule:u,event:d,notes:p})}function oU({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=Dc({tournamentRecord:r,drawDefinition:s,event:h}).appliedPolicies??{},U=i?.[wi]??I?.[wi];a=a??U?.participants?.enforceCategory;const S=!1!==(u??U?.participants?.enforceGender),y=!(!(n??h?.category)||!1===a),v=!(!(o??h?.gender)||!S),w=mh({referenceCategory:n??h?.category,collectionDefinition:e,referenceGender:o,checkCategory:y,checkGender:v,event:h});if(w.error)return wr({result:w,stack:g});let T=l?.tieFormat?void 0:Zf({drawDefinition:s,structureId:d,matchUpId:p,eventId:m,event:h});if(T?.error)return wr({result:{error:T.error},stack:g});const P=T?.structure;l=l??T?.matchUp;const D=l?.tieFormat??T?.tieFormat,b=Yf(D);if(T=fh({tieFormat:b}),T?.error)return wr({result:{error:T.error},stack:g});if(e.collectionId){if(b.collectionDefinitions.map((({collectionId:t})=>t)).includes(e.collectionId))return wr({context:{collectionId:e.collectionId},result:{error:Rn}})}else e.collectionId=Md();b.collectionDefinitions.push(e),b.collectionDefinitions.sort(((t,e)=>(t.collectionOrder||0)-(e.collectionOrder||0))).forEach(((t,e)=>t.collectionOrder=e+1));const{aggregateValue:N,valueGoal:R}=Jf(b);b.winCriteria=vr({aggregateValue:N,valueGoal:R});const M=D?.winCriteria.valueGoal,A=D?.winCriteria.aggregateValue;(M&&M!==R||N&&!A)&&(c?b.tieFormatName=c:delete b.tieFormatName);const C=[],O=[];let F=[];const k=vr(b);if(T=fh({tieFormat:k}),T?.error)return wr({result:{error:T.error},stack:g});if(m&&h){h.tieFormat=k;for(const n of h.drawDefinitions??[])if(!n.tieFormat)for(const r of n.structures??[]){if(r.tieFormat)continue;const n=sU({updateInProgressMatchUps:t,collectionDefinition:e,structure:r,uuids:f});O.push(...n.newMatchUps),F.push(...n.targetMatchUps),C.push(r.structureId)}cU({modifiedMatchUps:F,eventId:h?.eventId,modifiedStructureIds:C,tournamentRecord:r,drawDefinition:s,addedMatchUps:O,stack:g})}else if(d&&P){P.tieFormat=k;const n=sU({updateInProgressMatchUps:t,collectionDefinition:e,structure:P,uuids:f});O.push(...n.newMatchUps),F=n.targetMatchUps,cU({modifiedMatchUps:F,eventId:h?.eventId,modifiedStructureIds:C,tournamentRecord:r,drawDefinition:s,addedMatchUps:O,stack:g})}else if(p&&l){if(!yh({matchUp:l,updateInProgressMatchUps:t}))return wr({result:{error:Ue},stack:g});l.tieFormat=k;const n=gh({collectionDefinition:e,uuids:f});Array.isArray(l.tieMatchUps)||(l.tieMatchUps=[]),l.tieMatchUps.push(...n),O.push(...n),cU({modifiedMatchUps:[l],eventId:h?.eventId,modifiedStructureIds:C,tournamentRecord:r,drawDefinition:s,addedMatchUps:O,stack:g})}else{if(!s)return{error:j};s.tieFormat=k;for(const n of s.structures??[]){const r=sU({updateInProgressMatchUps:t,collectionDefinition:e,structure:n,uuids:f});C.push(n.structureId),O.push(...r.newMatchUps),F.push(...r.targetMatchUps)}cU({modifiedMatchUps:F,eventId:h?.eventId,tournamentRecord:r,drawDefinition:s,addedMatchUps:O,stack:g})}if(I?.audit?.[ua]){Th({drawDefinition:s,auditData:vr({drawId:s?.drawId,collectionDefinition:e,action:g,structureId:d,matchUpId:p,eventId:m})})}return{tieFormat:k,targetMatchUps:F,addedMatchUps:O,...E}}function sU({updateInProgressMatchUps:t,collectionDefinition:e,structure:n,uuids:r}){const i=[],a=Yp({matchUpFilters:{matchUpTypes:[Qs]},structure:n})?.matchUps,o=a.filter((e=>yh({matchUp:e,updateInProgressMatchUps:t})&&!e.tieFormat));for(const t of o){const n=gh({collectionDefinition:e,uuids:r});Array.isArray(t.tieMatchUps)||(t.tieMatchUps=[]),t.tieMatchUps.push(...n),i.push(...n)}return{newMatchUps:i,targetMatchUps:o}}function cU({modifiedStructureIds:t,tournamentRecord:e,modifiedMatchUps:n,drawDefinition:r,addedMatchUps:i,eventId:a,stack:o}){Fs({tournamentId:e?.tournamentId,matchUps:i,drawDefinition:r,eventId:a}),n?.forEach((t=>{xs({tournamentId:e?.tournamentId,drawDefinition:r,context:o,matchUp:t,eventId:a})})),Ls({structureIds:t,drawDefinition:r,eventId:a})}function uU(t){const e=Lp(t,[{_anyOf:{[sp]:!0,[up]:!0,[dp]:!0,[Rp]:!0},[cp]:!0}]);if(e.error)return e;const n=[],r=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(r){const e=dU(t,r);if(e.error)return e;n.push(...e?.applied??[]),t.drawDefinition&&Ls({drawDefinition:t.drawDefinition,tournamentId:t.tournamentId})}else{if(!t.tournamentRecords)return{error:_};{const e=Object.keys(t.tournamentRecords);if(!e.length)return{error:_};for(const r of e){const e=dU(t,t.tournamentRecords[r]);if(e.error)return e;n.push(...e?.applied??[])}}}return n.length?{...E,applied:n}:{error:te}}function dU(t,e){const n=Dc(t).appliedPolicies??{};e.extensions||(e.extensions=[]);const r=[],i=Object.keys(t.policyDefinitions);if(!i.length)return{error:Jt};for(const e of i)if(!n[e]||t.allowReplacement){const i=t.policyDefinitions[e];if(!i)continue;if(!ha(i))return{error:Nn};const{policyName:a,...o}=i;if(!o||!Object.keys(o).length||a&&!fa(a))return{error:Nn};n[e]=t.policyDefinitions[e],r.push(e)}if(r?.length){return{...Nr({element:e,extension:{name:Vi,value:n}}),applied:r}}return{applied:r,error:te}}function pU({tournamentRecord:t,drawDefinition:e,flightProfile:n,drawName:r,drawId:i,event:a}){if(!r||"string"!=typeof r)return wr({result:{error:Nn},context:{drawName:r}});n||(n=Bd({event:a}).flightProfile);const o=n?.flights?.find((t=>t.drawId===i));if(o){o.drawName=r;_i({event:a,extension:{name:Ki,value:{...n,flights:n.flights}}})}return e&&(e.drawName=r,Ls({tournamentId:t?.tournamentId,drawDefinition:e})),o||e?{...E,flight:o}:{error:j}}function lU(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}=Vd({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=aU({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{...E}}function mU({tournamentRecord:t}){if(!t)return{error:_};const e={positionsNoOutcomes:[],canBePruned:[],matchPlay:[],inactive:[],drawAnalysis:{}},r={},i=t.events?.map((t=>{const e=t.eventId;return r[e]=t,(t?.drawDefinitions||[]).map((t=>({drawDefinition:t,eventId:e})))})).flat().filter(Boolean);return i.forEach((({drawDefinition:t,eventId:i})=>{let a=0,o=0,s=0;const{allStructuresLinked:c}=Gm({drawDefinition:t}),u=r[i],d=(t?.structures||[]).map((e=>{const{stage:n,stageSequence:r,structureId:i}=e,c=io[n],{inContextStructureMatchUps:d}=yl({drawDefinition:t,structure:e,event:u}),p=d?.filter((({winningSide:t})=>t)),l=p.filter(Boolean).length||0;o+=l,s+=d.length-o;const m=Math.max(p.filter((({roundNumber:t})=>1===t)).map((({roundPosition:t})=>t))),{positionAssignments:f}=rs({structure:e}),h=f?.filter((({participantId:t})=>t));a+=h?.length??0;const g=(f?.length??0)-(h?.length??0),{roundMatchUps:I,roundProfile:U,roundNumbers:S,maxMatchUpsCount:y}=vc({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))),T=U&&Object.values(U).every((t=>t.inactiveRound));return{positionsAssignedCount:h?.length??0,maxWinningSideFirstRoundPosition:m,unassignedPositionsCount:g,inactiveStructure:T,maxMatchUpsCount:y,inactiveRounds:w,roundMatchUps:I,activeRounds:v,roundNumbers:S,roundProfile:U,structureId:i,stageSequence:r,orderNumber:c,stage:n}})),p=d.find((t=>2===t.orderNumber&&1===t.stageSequence)),l=d.filter((({inactiveStructure:t})=>!t)).length,{links:m}=Ic({structureId:p.structureId,drawDefinition:t}),f=1===n(p.activeRounds[0])&&1===p.activeRounds.length&&1===l,h=d?.every((({inactiveStructure:t})=>t)),g=!m.length&&p.activeRounds.length&&(p.roundProfile[1].inactiveCount||p.inactiveRounds.length),I=t.drawId;a&&!o&&e.positionsNoOutcomes.push(I),h&&e.inactive.push(I),f&&e.matchPlay.push(I),g&&e.canBePruned.push(I);const U={matchUpsWithWinningSideCount:o,matchUpsNoOutcomeCount:s,positionsAssignedCount:a,allStructuresLinked:c,structuresData:d,inactiveDraw:h,isMatchPlay:f,drawId:I};e.drawAnalysis[I]=U})),{...E,drawsAnalysis:e}}function fU({tournamentRecord:t,drawDefinition:e,structureId:n,matchUps:r}){if("object"!=typeof e)return{error:j};if(n||1!==e.structures?.length||(n=e.structures?.[0]?.structureId),"string"!=typeof n)return{error:It};if(!yc(r))return{error:Nn,info:Pf("matchUps")};const i=e.structures?.find((t=>t.structureId===n));if(!i)return{error:Ut};const a=i?.matchUps,o=a.find((t=>!!t.roundPosition));if(i.structures||o||i.finishingPosition===Ko)return{error:$};return b(hl({tournamentRecord:t,inContext:!1})?.matchUps?.map(ba)??[],r.map(ba))?{error:Ln,info:"One or more matchUpIds already present in tournamentRecord"}:(i.matchUps.push(...r),Fs({tournamentId:t?.tournamentId,drawDefinition:e,matchUps:r}),Ls({drawDefinition:e,structureIds:[n]}),{...E})}function hU(t){const{flight:e,suppressNotifications:r,modifyEventEntries:i,existingDrawCount:a,allowReplacement:o,checkEntryStatus:s,tournamentRecord:c,drawDefinition:u,event:d}=t;if(!u)return{error:j};if(!d)return{error:Tt};d.drawDefinitions||(d.drawDefinitions=[]);const{drawId:p,drawName:l,entries:m}=u,{entries:f}=d;let h=0;if(void 0!==a&&a!==d.drawDefinitions.length)return{error:Nn,info:"drawDefintions count mismatch"};const{flightProfile:g}=Bd({event:d}),I=e&&g?.flights?.find((t=>t.flightNumber===e.flightNumber)),U=g?.links?.find((t=>t?.target?.drawId===p))?.source?.drawId;if(U&&!d.drawDefinitions.find((t=>t.drawId===U)))return wr({result:{error:j},info:{sourceDrawId:U}});if(I&&I.drawId!==u.drawId)return wr({result:{error:V},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})),y=!s||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 wr({result:{error:V},context:{drawEntriesPresentInFlight:S,matchingEventEntries:y,relevantFlight:I},info:"Draw entries are not present in flight or do not match entryStatuses"});if(i&&m?.filter(Boolean).forEach((t=>{if(t?.entryStatus&&ou.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&&!y)return wr({result:{info:"Draw entries do not match event entryStatuses",context:{matchingEventEntries:y,eventEntries:f},error:V}});const v=g?.flights?.map((({flightNumber:t})=>!isNaN(t)&&n(t)))?.filter(Boolean)||[],w=d.drawDefinitions.map((({drawOrder:t})=>t&&n(t)))?.filter(Boolean)||[];let T=Math.max(0,...w,...v)+1;const P=g?.flights?.find((t=>t.drawId===p));let D;if(P){P.drawName=u.drawName,D={name:Ki,value:{...g,flights:g.flights}};const t=P.flightNumber;t&&!w.includes(t)?T=t:P.flightNumber=T}else{const t=g?.flights||[];t.push({manuallyAdded:!0,flightNumber:T,drawEntries:m,drawName:l,drawId:p}),D={name:Ki,value:{...g||{},flights:t}}}_i({event:d,extension:D}),Object.assign(u,{drawOrder:T});const b=d.drawDefinitions.find((t=>t.drawId===p)),N=c?.tournamentId,R=d.eventId;if(b){if(!o)return{error:ot};const t=Ul({drawDefinition:b})?.matchUps,e=t?.map(ba)??[],n=Ul({drawDefinition:u})?.matchUps;if(!r){e?.length&&ks({matchUpIds:e,action:"modifyDrawDefinition",tournamentId:N,eventId:R}),n?.length&&Fs({matchUps:n,tournamentId:N,eventId:R}),d.drawDefinitions=d.drawDefinitions.map((t=>t.drawId===p?u:t));const t=u.structures?.map((({structureId:t})=>t));Ls({drawDefinition:u,tournamentId:N,structureIds:t,eventId:R})}}else if(d.drawDefinitions.push(u),!r){const{matchUps:t}=Ul({drawDefinition:u,event:d});t&&Fs({tournamentId:c?.tournamentId,matchUps:t}),_s({drawDefinition:u,tournamentId:N,eventId:R})}return{...E,modifiedEventEntryStatusCount:h}}function gU({allowDuplicateParticipantIdPairs:t,returnParticipants:e,participants:n,tournamentRecord:r}){if(!r)return{error:_};r.participants||(r.participants=[]);const i=r.participants.map((t=>t.participantId))||[];n.forEach((t=>{t.participantId||(t.participantId=Md())}));const a=n.filter((t=>!i.includes(t.participantId))),o=n.filter((t=>i.includes(t.participantId))),s=a.filter((t=>t.participantType===sc)),c=a.filter((t=>t.participantType!==sc)),u=s.concat(...c),d=[];if(u.length){for(const e of u){const n=Bf({allowDuplicateParticipantIdPairs:t,returnParticipant:!0,disableNotice:!0,tournamentRecord:r,participant:e});if(n.error)return n;n.success&&!n.existingParticipant&&d.push(n.participant)}d.length&&sr({topic:ss,payload:{tournamentId:r.tournamentId,participants:d}});const n={participants:e&&gi(d),addedCount:d.length,...E};return o.length&&Object.assign(n,{notAdded:o,info:Be}),vr(n)}return{info:"No new participants to add",addedCount:0,...E}}function IU({deleteExisting:t,event:e,flightProfile:n}){const r="attachFlightProfile";if(!n)return wr({result:{error:ae},stack:r});if(!e)return wr({result:{error:Tt},stack:r});const{flightProfile:i}=Bd({event:e});if(i&&!t)return wr({result:{error:xn},stack:r});if(e.drawDefinitions?.length)return wr({result:{error:G},stack:r});return _i({event:e,extension:{name:Ki,value:n}}),{flightProfile:gi(n,!1,!0),...E}}function UU({tournamentRecord:t,scaleAttributes:e,drawDefinition:n,entryStatuses:r,drawId:i,event:a,stage:o}){if(!a)return{error:Tt};if(r&&!Array.isArray(r))return wr({result:{error:Nn},info:Pf("entryStatus"),stack:"removeScaleValues"});let s=a.entries;if(i){const{flightProfile:t}=Bd({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:_};if(!n)return{error:Fe};if(!e)return{error:ae,info:"scaleAttributes required"};const{scaleType:r,eventType:i,scaleName:a}=e,o=[ju,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)))})),{...E}}({tournamentRecord:t,scaleAttributes:e,participantIds:(s||[]).filter((t=>(!o||!t.entryStage||t.entryStage===o)&&(!r||r.includes(t.entryStatus)))).map(Da)})}function SU(t){const e="resetTieFormat",{drawDefinition:n,event:r,uuids:i}=t,a=Lp(t,[{[up]:!0,[Ip]:!0}],e);if(a.error)return a;const o=Cf(t,[{[Mp]:Dp}]);if(o[Np])return o;const s=t.tournamentRecord?.tournamentId,{matchUp:c,structure:u}=o?.matchUp??{};if(!c?.tieMatchUps)return wr({result:{error:Yt},info:"Must be a TEAM matchUp",stack:e});if(!c.tieFormat)return{...E};const d=$d({structure:u,drawDefinition:n,event:r})?.tieFormat;if(!d)return wr({result:{error:On},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===ja?1:0)-(e.matchUpStatus===ja?1:0))),m.push(...r.slice(0,e)),p.push(...r.slice(3).map(ba));else if(m.push(...r),r.length<e){const n=gh({collectionDefinition:t,matchUpsLimit:e-r.length,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),Fs({eventId:r?.eventId,matchUps:f,drawDefinition:n,tournamentId:s})),p.length&&ks({matchUpIds:p,eventId:r?.eventId,drawDefinition:n,tournamentId:s}),c&&(c.tieMatchUps=m,c.tieFormatId=void 0,c.tieFormat=void 0,xs({structureId:u?.structureId,eventId:r?.eventId,context:e,drawDefinition:n,tournamentId:s,matchUp:c})),{...E,newMatchUps:f,deletedMatchUpIds:p}}function yU({participantIdPairings:t,matchUpIds:e=[],drawDefinition:n,matchUpsCount:r,roundNumber:i,structureId:a,newRound:o}){if("object"!=typeof n)return{error:j};if(a||1!==n.structures?.length||(a=n.structures?.[0]?.structureId),"string"!=typeof a)return{error:It};const s=n.structures?.find((t=>t.structureId===a));if(!s)return{error:Ut};let c;const u=s.matchUps??[],d=u?.reduce(((t,e)=>(e.roundPosition&&(c=!0),(e?.roundNumber||0)>t?e.roundNumber:t)),0);if(!r){const t=n?.entries?.filter((t=>{const e=t.entryStatus;return ou.includes(e)}))??[],e=Math.floor(t?.length/2)||1;if(o)r=e;else{const t=i??d??1,n=e-(s.matchUps?.filter((e=>e.roundNumber===t))?.length??0);n>0&&(r=n)}}if(t&&!Array.isArray(t)||r&&!p(r)||e&&!Array.isArray(e)||!t&&!r)return{error:Nn,info:"matchUpsCount or pairings error"};if(s.structures||c||s.finishingPosition===Ko)return{error:$};if(i&&i-1>(d||0))return{error:Nn,info:"roundNumber error"};const l=i??(o&&(d??0)+1||d||1);t=t??w(0,r).map((()=>({participantIds:[void 0,void 0]})));const m=t?.map((t=>{const n=t?.participantIds??[void 0,void 0];n.push(void 0,void 0);const r=n.slice(0,2).map(((t,e)=>vr({sideNumber:e+1,participantId:t})));return{matchUpId:e.pop()??Md(),roundNumber:l,matchUpStatus:ja,sides:r}}));return{matchUpsCount:m?.length??0,matchUps:m,...E}}function vU(t){return t.participantIdPairings.map((({participantIds:t})=>t.sort().join("|"))).sort().join("/")}function wU({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=TU(e,r),a=n[i];s.push({participantIds:t,value:a}),c+=n[i]}));N(t,a).map((t=>f(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=TU(n,i),o=r[a];return o>t?o:t}),0),d=s.reduce(((t,e)=>{const[n,r]=e.participantIds,a=TU(n,r),o=i[a];return o>t?o:t}),0);return{value:c,participantIdPairings:s,maxDelta:u,maxDiff:d}}function TU(t,e){return[t,e].sort(Hl).join("|")}function PU({participantIds:t}){const e={},n=[];t.forEach((r=>{e[r]=t.filter((t=>t!==r)),e[r].forEach((t=>{const e=TU(t,r);n.includes(e)||n.push(e)}))}));const r=Object.assign({},...n.map((t=>({[t]:0}))));return{uniquePairings:n,possiblePairings:e,deltaObjects:r}}const DU="ELO",bU="NTRP",NU="WTN",RU={ELO:DU,NTRP:bU,TRN:"TRN",UTR:"UTR",WTN:NU},MU={[DU]:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!0},[bU]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!0,range:[1,7]},UTR:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!0,range:[1,16]},[NU]:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!1,decimalsCount:2,range:[40,1]}},AU=0;function EU({tournamentParticipants:t,adHocRatings:e={},possiblePairings:n,uniquePairings:r,maxIterations:i,deltaObjects:a,valueObjects:o,eventType:s,scaleName:c,salted:u}){r.forEach((n=>{const r=function({tournamentParticipants:t,adHocRatings:e,eventType:n,scaleName:r,pairing:i}){const a=MU[r]?.defaultInitialization??AU;return i.split("|").map((r=>{if(n===nd){const n=t?.find((t=>t.participantId===r))?.individualParticipantIds;return n?n?.map((t=>e[t]||a)):2*a}return e[r]||a}))}({tournamentParticipants:t,adHocRatings:e,scaleName:c,eventType:s,pairing:n}),i="number"==typeof u&&u||.5,d=u&&(Math.round(Math.random())?i:-1*i)||0,p=Math.abs(r[0]-r[1])+d,l=Math.abs(r[0]-r[1]);a[n]=l,o[n]||(o[n]=0),o[n]+=p?Math.pow(p,2):0}));const d=r.map((t=>({pairing:t,value:o[t]}))).sort(((t,e)=>t.value-e.value)),{pairingValues:p}=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=TU(t,n);return{opponent:n,value:e[r]}}return{pairingValues:n}}({possiblePairings:n,valueObjects:o}),{candidate:l,candidatesCount:m,deltaCandidate:f,iterations:h}=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=wU({actorsCount:o.length,valueSortedPairings:e,pairingValueMap:a,deltaObjects:i,valueObjects:r}),u=[vU(c)];s.push(c);let d,p=c.value,l=c,m=0,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=TU(t,n.opponent);if(!g.includes(c)){const d=wU({stipulated:[[t,n.opponent]],actorsCount:o.length,valueSortedPairings:e,pairingValueMap:a,deltaObjects:i,valueObjects:r});if(!u.includes(vU(d))){u.push(vU(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=y(s);return{candidatesCount:m,deltaCandidate:l,maxIterations:t,iterations:f,candidate:I}}({valueSortedPairings:d,maxIterations:i,pairingValues:p,deltaObjects:a,valueObjects:o}),{participantIdPairings:g}=l;return{participantIdPairings:g,candidatesCount:m,deltaCandidate:f,iterations:h,candidate:l}}const CU=100,OU=100,FU=4e3;function kU({encounterValue:t=CU,sameTeamValue:e=OU,maxIterations:n=FU,generateMatchUps:r=!0,tournamentParticipants:i,participantIds:a,drawDefinition:o,adHocRatings:s,structureId:c,salted:u=.5,matchUpIds:d,eventType:p,structure:l,scaleName:m}){if(!o)return{error:j};if(!l&&!c)return{error:Ut};if(l||(l=ts({drawDefinition:o,structureId:c}).structure),!ha(l))return{error:yt};if(!a?.length)return{error:Fe};const{encounters:f}=function({matchUps:t}){const e=[];for(const n of t){const t=n.sides.map(Ua("participantId"));if(2===t.length){const[n,r]=t,i=TU(n,r);e.includes(i)||e.push(i)}}return{encounters:e}}({matchUps:l?.matchUps??[]}),h={};for(const e of f)h[e]||(h[e]=0),h[e]+=t;const g=i?.filter((({participantType:t})=>t===dc));if(g)for(const t of g){const n=t.individualParticipantIds??[],{uniquePairings:r}=PU({participantIds:n});for(const t of r)h[t]||(h[t]=0),h[t]+=e}const{uniquePairings:I,possiblePairings:U,deltaObjects:S}=PU({participantIds:a}),y={tournamentParticipants:i,possiblePairings:U,drawDefinition:o,participantIds:a,uniquePairings:I,maxIterations:n,adHocRatings:s,deltaObjects:S,valueObjects:h,eventType:p,scaleName:m,structure:l,salted:u},{candidatesCount:v,participantIdPairings:w,iterations:T,candidate:P}=EU(y);if(!v)return{error:vn};let D;if(r){const t=yU({structureId:l?.structureId,participantIdPairings:w,newRound:!0,drawDefinition:o,matchUpIds:d});if(t.error)return t;D=t.matchUps}const{maxDelta:b,maxDiff:N}=P;return{...E,participantIdPairings:w,candidatesCount:v,iterations:T,matchUps:D,maxDelta:b,maxDiff:N}}function xU({tournamentParticipants:t,restrictEntryStatus:e,adHocRatings:n={},generateMatchUps:r,tournamentRecord:i,participantIds:a,encounterValue:o,sameTeamValue:s,drawDefinition:c,scaleAccessor:u,maxIterations:d,structureId:p,matchUpIds:l,scaleName:m,eventType:f,salted:h,event:g}){if("object"!=typeof c||c.drawType&&c.drawType!==wo)return{error:V};if(!Array.isArray(c?.entries)&&a&&!Array.isArray(a))return{error:Nn,info:"Missing Entries"};f=f??g?.eventType;const I=c?.entries?.filter((t=>{const n=t.entryStatus;return!e||ou.includes(n)})).map(Da);if(a){const t=a.filter((t=>!I?.includes(t)));if(t?.length)return wr({result:{error:Te},info:{invalidParticipantIds:t}})}else a=I;if(!p){const t=c?.structures?.filter((t=>1===t.stageSequence))?.reduce(((t,e)=>{const n=e.stage&&io[e.stage];return ap({drawDefinition:c,structure:e})&&n>(io[t?.stage]||1)?e:t}),void 0);p=t?.structureId}const U=c?.structures?.find((t=>t.structureId===p));if(!U)return{error:Ut};if(!ap({drawDefinition:c,structure:U}))return{error:V};t=t??i.participants??[];for(const e of a??[]){const r=t?.find((t=>t.participantId===e));let i=_U({scaleName:`${m}.${Ar}`,scaleAccessor:u,participant:r,eventType:f});!i&&m&&(i=_U({scaleAccessor:u,participant:r,scaleName:m,eventType:f})),i&&!n[e]&&(n[e]=i)}return kU({tournamentParticipants:t,generateMatchUps:r,participantIds:a,encounterValue:o,sameTeamValue:s,drawDefinition:c,maxIterations:d,adHocRatings:n,matchUpIds:l,structure:U,eventType:f,salted:h})}function _U({scaleType:t=Cr,scaleAccessor:e,participant:n,scaleName:r,eventType:i}){const a=n&&Vl({scaleAttributes:{eventType:i??ed,scaleType:t,scaleName:r},participant:n}),o=a?.scaleItem?.scaleValue;return e&&ha(o)?o[e]:o}function LU({participantsCount:t,participantCount:e}){if(!(t=t??e))return{error:Nn};const n=u(t);return n?{drawSize:n}:wr({result:{error:Nn},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function BU(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=bc({tournamentRecord:a,drawDefinition:o,event:s});if(t.error)return wr({result:t,stack:c});n=t.policyDefinitions}const d=p(u);if(u&&!d)return wr({result:{error:Nn},context:{participantsCount:u},stack:c});if(i&&!d)return wr({result:{error:ke},stack:c});if(isNaN(r)){if(!u)return wr({result:{error:it},stack:c});({drawSize:r}=LU({participantsCount:u}))}const l=i&&u||r;if(l&&l>r)return{error:Ve};const m=n?.[Ai];if(!m)return{error:Qt};const f=m.seedsCountThresholds;if(!f)return{error:ut};void 0!==m.drawSizeProgression&&(e=m.drawSizeProgression);return{seedsCount:f.filter((t=>e?t.drawSize<=r:r===t.drawSize)).reduce(((t,e)=>u&&u>=e.minimumParticipantCount?e.seedsCount:t),0)}}function VU({policyDefinitions:t,drawDefinition:e,drawSize:n,drawId:r,event:i,stage:a}){if(!i)return{error:Tt};const{entries:o,stageEntries:s}=Im({drawDefinition:e,drawId:r,stage:a,event:i}),c=s.length,{drawSize:u}=LU({participantsCount:c}),d=BU({drawSize:n??u,participantsCount:c,policyDefinitions:t});if(d.error)return wr({result:d,stack:"getEntriesAndSeedsCount"});const{seedsCount:p}=d;return{entries:o,seedsCount:p,stageEntries:s}}function jU({scaleAttributes:t,scaledEntries:e,stageEntries:n,seedsCount:r,scaleName:i}){if(!t)return{error:ae,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:Fr,scaleName:i,scaleDate:o}],participantId:e})))}}function GU(t){const{tournamentRecord:e,scaleAttributes:n,participantId:r}=t,i=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!r)return{error:Ae};const{participant:a,tournamentId:o}=rl({tournamentRecords:i,tournamentRecord:e,participantId:r});return a?{...Vl({participant:a,scaleAttributes:n}),tournamentId:o}:{error:Ee}}function qU({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:n,scaleSortMethod:r,stageSequence:i,entries:a,event:o,stage:s}){if(!e)return{error:_};return{scaledEntries:(a=a??o?.entries??[]).filter((t=>(!s||!t.entryStage||t.entryStage===s)&&(!i||!t.entryStageSequence||t.entryStageSequence===i)&&ou.includes(t.entryStatus))).map((t=>{const{participantId:r}=t,{scaleItem:i}=GU({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 $U({qualifyingPositions:t,drawEntries:e=[],drawName:r,drawId:i,event:a,stage:o}){const s="addFlight";if(!a)return wr({result:{error:Tt},stack:s});if(!r)return wr({result:{error:ae},stack:s});if(e?.length){const t=(a.entries??[]).map(Ua("participantId")),n=e.map(Ua("participantId"));if(P(n,t).length!==n.length)return wr({result:{error:Nn},stack:s})}const c=Bd({event:a})?.flightProfile,u=c?.flights?.map((({flightNumber:t})=>!isNaN(t)&&n(t)))?.filter(Boolean)||[],d=Math.max(0,...u)+1,p={drawId:i||Md(),flightNumber:d,drawEntries:e,drawName:r};o&&(p.stage=o),t&&(p.qualifyingPositions=t);if((c?.flights||[]).find((({drawId:t})=>t===p.drawId)))return wr({result:{error:kn},stack:s});const l=(c?.flights||[]).concat(p);return _i({event:a,extension:{name:Ki,value:{...c||{},flights:l}}})}var WU={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}},HU={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}},zU={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}},YU={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}},KU={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}},JU={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}},ZU={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}},XU={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}},QU={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}},tS={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}]},eS={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}},nS={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}},rS={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}},iS={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}},aS={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}},oS={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}},sS={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 cS="COLLEGE_DEFAULT",uS="COLLEGE_JUCO",dS="COLLEGE_D3",pS="DOMINANT_DUO",lS="DOMINANT_DUO_MIXED",mS="LAVER_CUP",fS="TEAM_DOUBLES_3_AGGREGATION",hS="TIME_TENNIS_DUAL",gS="TIME_TENNIS_PRO_CIRCUIT",IS="USTA_BREWER_CUP",US="USTA_OZAKI_CUP",SS="USTA_COLLEGE",yS="USTA_GOLD_TEAM_CHALLENGE",vS="USTA_LEVEL_1",wS="USTA_INTERSECTIONAL",TS="USTA_SECTION_BATTLE",PS="USTA_SOUTHERN_LEVEL_5",DS="USTA_TOC",bS="USTA_WTT_ITT",NS="USTA_ZONAL",RS={COLLEGE_D3:dS,COLLEGE_DEFAULT:cS,COLLEGE_JUCO:uS,DOMINANT_DUO:pS,DOMINANT_DUO_MIXED:lS,LAVER_CUP:mS,TEAM_DOUBLES_3_AGGREGATION:fS,TIME_TENNIS_DUAL:hS,TIME_TENNIS_PRO_CIRCUIT:gS,USTA_BREWER_CUP:IS,USTA_OZAKI_CUP:US,USTA_COLLEGE:SS,USTA_GOLD_TEAM_CHALLENGE:yS,USTA_INTERSECTIONAL:wS,USTA_LEVEL_1:vS,USTA_SECTION_BATTLE:TS,USTA_SOUTHERN_LEVEL_5:PS,USTA_TOC:DS,USTA_WTT_ITT:bS,USTA_ZONAL:NS},MS="STANDARD",AS={[MS]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[dS]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1,matchUpFormat:"SET1-S:8/TB7@7"},singles:{matchUpFormat:lg,matchUpCount:6,matchUpValue:1},tieFormatName:dS,valueGoal:5},[cS]:{hydrate:!0,doubles:{matchUpCount:3,collectionValue:1,matchUpFormat:lg},singles:{matchUpCount:6,matchUpValue:1,matchUpFormat:lg},tieFormatName:cS,valueGoal:4},[uS]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1,matchUpFormat:"SET1-S:8/TB7"},singles:{matchUpCount:6,matchUpValue:1,matchUpFormat:lg},tieFormatName:uS,valueGoal:5},[mS]:oS,[pS]:eS,[lS]:ZU,[fS]:HU,[hS]:XU,[gS]:JU,[IS]:QU,[US]:tS,[SS]:nS,[yS]:WU,[wS]:KU,[vS]:rS,[TS]:YU,[PS]:zU,[bS]:iS,[DS]:sS,[NS]:aS},ES=t=>{const e=t?.namedFormat&&Object.keys(AS).includes(t.namedFormat)?t.namedFormat:MS,n=Array.isArray(t?.uuids)?t?.uuids:[];let r;const{category:i,gender:a}=t?.event??{},o=gi(AS[e],!1,!0);return o.hydrate?(r={winCriteria:{valueGoal:o.valueGoal},collectionDefinitions:[{collectionId:n?.pop()??Md(),matchUpFormat:mg,collectionName:"Doubles",matchUpType:Zs,...o.doubles},{collectionId:n?.pop()??Md(),matchUpFormat:lg,collectionName:"Singles",matchUpType:Ks,...o.singles}]},o.tieFormatName&&(r.tieFormatName=o.tieFormatName)):(o.collectionDefinitions.forEach((t=>t.collectionId=Md())),r=o),t?.hydrateCollections&&r.collectionDefinitions.forEach((t=>{i&&!t.category&&(t.category=i),a&&!t.gender&&(t.gender=a)})),r};const CS={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:eS,DOMINANT_DUO_MIXED:ZU,LAVER_CUP:oS,TEAM_DOUBLES_3_AGGREGATION:HU,TIME_TENNIS_DUAL:XU,TIME_TENNIS_PRO_CIRCUIT:JU,USTA_BREWER_CUP:QU,USTA_OZAKI_CUP:tS,USTA_COLLEGE:nS,USTA_GOLD_TEAM_CHALLENGE:WU,USTA_INTERSECTIONAL:KU,USTA_LEVEL_1:rS,USTA_SECTION_BATTLE:YU,USTA_SOUTHERN_LEVEL_5:zU,USTA_TOC:sS,USTA_WTT_ITT:iS,USTA_ZONAL:aS};function OS({suppressNotifications:t,tournamentRecord:e,internalUse:n,event:r}){if(!e)return{error:_};if(e.events||(e.events=[]),!r)return{error:Tt};const{startDate:i,endDate:a}=e;if(!n&&(r.entries?.length||r.drawDefinitions?.length)){const t=vr({drawDefinitions:!!r.drawDefinitions?.length,entries:!!r.entries?.length});return{info:"entries/drawDefinitions cannot exist",error:Nn,context:t}}const o={eventType:ed,drawDefinitions:[],entries:[],startDate:i,endDate:a,...r};if(r.eventType===ad)if(r.tieFormat){const t=fh({tieFormat:r.tieFormat});if(t.error)return t}else if(r.tieFormatName){if(!CS[r.tieFormatName])return{context:{tieFormatName:r.tieFormatName},error:Nn};const t=ES({namedFormat:r.tieFormatName});o.tieFormat=t}o.eventId||(o.eventId=Md());if(e.events.reduce(((t,e)=>t||e.eventId===o.eventId),void 0))return{error:Dt};{const n=o;if(e.events.push(n),!t){const{topics:t}=lr();if(t.includes(os)){const t=fl({event:r}).matchUps??[];Fs({tournamentId:e?.tournamentId,eventId:r.eventId,matchUps:t})}for(const t of r.drawDefinitions||[])_s({drawDefinition:t})}return{...E,event:o}}}function FS({tournamentRecord:t,drawDefinition:e,participantIds:n,stageSequence:r,stage:i=Xa,eventId:a,event:o}){if(!t)return{error:_};if(!Array.isArray(n))return{error:Nn,participantIds:n};if(!o)return{error:Tt};if(o){const t=kS({element:o,participantIds:n,stageSequence:r,stage:i});if(t.error)return t}if(e){const t=kS({element:e,participantIds:n,stageSequence:r,stage:i});if(t.error)return a?wr({context:{drawPromotionError:t.error,drawId:e.drawId},result:{...E},stack:"promoteAlternates"}):t}return{...E}}function kS({participantIds:t,stageSequence:e,element:r,stage:i}){const a=(r.entries||[]).filter((t=>t.entryStatus===$c)),o=(r.entries||[]).filter((e=>t.includes(e.participantId))),s=a.reduce(((t,e)=>{const{entryPosition:n}=e;return isNaN(n)&&t||(!t||n<t.entryPosition)&&e||t}),void 0),c=o.length?o:[s].filter(Boolean);if(!c?.length)return{error:Ge};const u=c.filter((({entryStatus:t})=>t!==$c));if(u.length)return{error:je,invalidEntryStatus:u};const d=c.filter((({entryStage:t})=>t&&t!==i));if(d.length)return{error:qe,invalidStage:d};const p=e&&c.filter((t=>t.stageSequence!==e));if(p?.length)return{error:$e,invalidStageSequence:p};for(const t of c){t.entryStatus=Hc;const e=t?.entryPosition;isNaN(e)||r.entries.forEach((t=>{t.entryStatus===$c&&t.entryPosition>e&&(t.entryPosition=t.entryPosition-1)}));const i=Math.max(...r.entries.filter((t=>t.entryStatus===Hc&&!isNaN(t.entryPosition))).map((({entryPosition:t})=>n(t||0))),0);t.entryPosition=i||0}return{...E}}function xS({tournamentRecord:t,drawDefinition:e,participantId:n,entryPosition:r,skipRefresh:i,event:a}){if(!t)return{error:_};if(!n)return wr({result:{error:Ae},stack:"setEntryPositions"});if(void 0!==r&&!Number.isSafeInteger(r))return{error:Nn,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=xl({entries:a.entries})),e?.entries&&(o(e),e.entries=xl({entries:e.entries}))),{...E}}function _S({tournamentRecord:t,event:e,startDate:n}){if(!t)return{error:_};if(!e)return{error:Tt};if(!Vr.test(n))return{error:pe};const r=BS(t);if(r.error)return r;const{tournamentStartDate:i,tournamentEndDate:a}=r,o=new Date(ri(n)).getTime();if(!i||!a||o<i||o>a)return{error:pe};const s=e.endDate&&new Date(ri(e.endDate));return s&&o>s&&(e.endDate=n),e.startDate=n,{...E}}function LS({tournamentRecord:t,event:e,endDate:n}){if(!t)return{error:_};if(!e)return{error:Tt};if(!Vr.test(n))return{error:pe};const r=BS(t);if(r.error)return r;const{tournamentStartDate:i,tournamentEndDate:a}=r,o=new Date(ri(n)).getTime();if(!i||!a||o<i||o>a)return{error:pe};const s=e.startDate&&new Date(ri(e.startDate));return s&&o<s&&(e.startDate=n),e.endDate=n,{...E}}function BS(t){const{startDate:e,endDate:n}=t;return Vr.test(e)&&Vr.test(n)?{tournamentStartDate:new Date(ri(e)).getTime(),tournamentEndDate:new Date(ri(n)).getTime()}:wr({result:{error:me},context:{startDate:e,endDate:n}})}const VS={addAdHocMatchUps:fU,addCollectionDefinition:oU,addCollectionGroup:function({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 wr({result:{error:ae},stack:p});let l=c?void 0:Zf({drawDefinition:r,structureId:o,matchUpId:s,eventId:u,event:d});if(l?.error)return wr({result:l,stack:p});const m=l?.structure;c=c||l?.matchUp;const f=l?.tieFormat,h=f?.winCriteria.valueGoal,g=Yf(f);if(l=fh({tieFormat:g}),l.error)return wr({result:l,stack:p});for(const t of g.collectionDefinitions){const{collectionId:e,collectionGroupNumber:n}=t;if(n&&i.includes(e))return wr({info:"collectionIds cannot be part of other collectionGroups",result:{error:Nn},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],EI({updateInProgressMatchUps:t,originalValueGoal:h,tournamentRecord:e,drawDefinition:r,tieFormatName:a,structureId:o,structure:m,tieFormat:g,matchUpId:s,matchUp:c,eventId:u,event:d})},addDrawDefinition:hU,addDrawDefinitionTimeItem:RI,addDrawEntries:im,addEvent:OS,addEventEntries:cm,addEventEntryPairs:function({allowDuplicateParticipantIdPairs:t,entryStage:e=Xa,entryStatus:n=$c,participantIdPairs:r=[],tournamentRecord:i,drawDefinition:a,event:o,uuids:s}){if(!i)return{error:_};if(!o)return{error:Tt};if(o.eventType!==Zs)return{error:wt};const c=[],u=new Map;for(const t of i.participants??[]){const{participantType:e,participantId:n,person:r,individualParticipantIds:i}=t;e===sc&&r?.sex?u.set(n,r.sex):e===uc&&i&&c.push(i)}const d=r.filter((t=>{if(2!==t.length)return!0;if(!u.has(t[0])||!u.has(t[1]))return!0;if(!o.gender||o.gender===Gp)return!1;const e=t.map((t=>u.get(t)));let n=o.gender===qp&&(e[0]!==qp||e[1]!==qp)||o.gender===Hp&&(e[0]!==Hp||e[1]!==Hp);return o.gender===$p&&(e.sort(Hl),e[0]===Hp&&e[1]===qp||(n=!0)),n}));if(d.length)return{error:Pe,invalidParticipantIdPairs:d};const p=r.map((t=>({participantId:s?.pop()??Md(),participantRole:um,individualParticipantIds:t,participantType:uc}))),l=t?p:p.filter((t=>!c.find((e=>2===P(e,t.individualParticipantIds).length))));let m,f=[];if(l){const e=gU({allowDuplicateParticipantIdPairs:t,participants:l,returnParticipants:!0,tournamentRecord:i});if(e.error)return e;f=e.participants||[],m=e.info}const h=cm({participantIds:r.map((t=>{const e=f.find((e=>2===P(e.individualParticipantIds,t).length));if(e)return e;const{participant:n}=Vc({tournamentRecord:i,participantIds:t});return n})).map((t=>t.participantId)),tournamentRecord:i,drawDefinition:a,entryStatus:n,entryStage:e,event:o});return l.length&&sr({payload:{participants:l},topic:ss}),{...h,info:m,newParticipantIds:l.map(Da)}},addFlight:$U,addPlayoffStructures:eU,addQualifyingStructure:function(t){const e=t.tournamentRecord;if(!e)return{error:_};const n=function(t){if(!t.drawDefinition)return{error:j};if(!t.targetStructureId)return{error:It};const e=jI(t);if(e.error)return e;const{structure:n,link:r}=e;return n&&r?pg({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,structure:n,link:r}):{error:Nn}}(t);if(n.error)return n;const{qualifyingRoundNumber:r,qualifyingPositions:i,targetStructureId:a,drawDefinition:o,structureName:s,matchUpType:c,drawSize:u,drawType:d}=t;return Lm({tournamentRecord:e,timeItem:{itemType:"addQualifyingStructures",itemValue:vr({drawId:o.drawId,qualifyingRoundNumber:r,qualifyingPositions:i,targetStructureId:a,structureName:s,matchUpType:c,drawSize:u,drawType:d})}}),n},addVoluntaryConsolationStage:function(t){return function({drawDefinition:t,drawSize:e}){if(!t)return{error:j};const n=MI({stage:eo,stageSequence:1,drawDefinition:t,drawSize:e});return n.error?n:(Ls({drawDefinition:t}),{...E})}(t)},addVoluntaryConsolationStructure:Pm,aggregateTieFormats:function({tournamentRecord:t}){if(!t)return{error:_};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){Uh({descendant:t.tieFormat,ancestor:e}).different||(n=e.tieFormatId)}if(n)t.tieFormatId=n,delete t.tieFormat;else{const n=gi(t.tieFormat,void 0,!0);n.tieFormatId||(n.tieFormatId=Md()),t.tieFormatId=n.tieFormatId,delete t.tieFormat,r.push(n),e+=1}},a=n.eventType;i({tieFormat:n.tieFormat,eventType:a});for(const t of n.drawDefinitions??[]){i({tieFormat:t.tieFormat,eventType:a});for(const e of t.structures??[])i({tieFormat:e.tieFormat,eventType:a})}const o=(e,r)=>{const i=c.matchUps?.find((t=>t.matchUpId===e));i&&(i.tieFormatId=r,delete i.tieFormat,xs({tournamentId:t?.tournamentId,eventId:n.eventId,matchUp:i}))},s=t=>{const n=gi(t.tieFormat,void 0,!0);n.tieFormatId||(n.tieFormatId=Md()),r.push(n),e+=1,o(t.matchUpId,n.tieFormatId)},c=fl({matchUpFilters:{matchUpTypes:[Xs]},event:n}),u=c.matchUps??[];for(const t of u){let e;for(const n of r){t.tieFormat&&Uh({descendant:t.tieFormat,ancestor:n}).different||(e=n.tieFormatId)}e?o(t.matchUpId,e):s(t)}r.length&&(n.tieFormats=r)}return{...E,addedCount:e}},alternateDrawPositionAssignment:function(t){return function({alternateParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i}){return Mf({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i})}(t)},applyLineUps:function({tournamentRecord:t,drawDefinition:e,matchUpId:n,lineUps:r,event:i}){if(!t)return{error:_};if(!e)return{error:q};if("string"!=typeof n)return{error:Yt};if(!Array.isArray(r))return{error:Nn,lineUps:r};const a=t.participants||[];let o=Xm({tournamentParticipants:a,inContext:!0,drawDefinition:e,matchUpId:n});if(o.error)return o;if(!o.matchUp)return{error:Wt};const{matchUp:s,structure:c}=o,{drawPositions:u,matchUpType:d}=s;if(d!==Qs)return{error:Yt};if(!u?.length)return{error:Z};const p=$d({matchUp:s,drawDefinition:e,structure:c,event:i})?.tieFormat,l={};for(const e of r){if(!Array.isArray(e))return{error:Nn,lineUp:e};const n={},r=[];for(const t of e){if("object"!=typeof t)return{error:Nn,lineUpAssignment:t};const{participantId:e,collectionAssignments:i=[]}=t;if(!Array.isArray(i))return{error:Nn,collectionAssignments:i};const o=a.find((t=>t.participantId===e));if(!o)return{error:Ee};if(o.participantType!==sc)return{error:be};const c=s.sides?.find((t=>t.participant?.individualParticipantIds?.includes(e)))?.sideNumber;c&&r.push(c);for(const t of i){if("object"!=typeof t)return{error:Nn,collectionAssignment:t};const{collectionId:r,collectionPosition:i}=t,a=p?.collectionDefinitions?.find((t=>t.collectionId===r));if(!a)return{error:Nn,collectionId:r};const o=`${r}-${i}`;n[o]||(n[o]=[]);const s=n[o].length;if(a.matchUpType===Ks&&s||a.matchUpType===Zs&&s>1)return{info:"Excessive collectionPosition assignments",error:Nn};n[o].push(e)}}const i=Object.values(n);for(const e of i)if(2===e.length){const{participant:n}=Vc({tournamentParticipants:a,participantIds:e});if(!n){const n=Bf({participant:{participantType:uc,participantRole:um,individualParticipantIds:e},pairOverride:!0,tournamentRecord:t});if(n.error)return n}}const o=g(r),c=((o[1]||0)>(o[2]||0)?1:(o[2]||0)>(o[1]||0)&&2)||void 0,u=Object.keys(l).map((t=>parseInt(t)));c&&!u.includes(c)&&(l[c]=e)}if(!Object.keys(l).length)return{error:Cn};if(o=Xm({drawDefinition:e,matchUpId:n}),o.error)return o;if(!o.matchUp)return{error:Wt};const{matchUp:m}=o;m.sides||(m.sides=[]);for(const t of[1,2]){const e=m.sides.find((e=>e.sideNumber===t)),n=l[t];n&&(e?e.lineUp=n:m.sides.push({lineUp:n,sideNumber:t}))}return xs({tournamentId:t?.tournamentId,context:"applyLineUps",drawDefinition:e,matchUp:m}),{...E}},assignDrawPosition:function({tournamentRecord:t,drawDefinition:e,participantId:n,drawPosition:r,structureId:i,qualifier:a,event:o,bye:s}){if(!e)return{error:j};if(!r)return{error:tt};if(!i)return{error:It};if(s){const n=bl({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:i,event:o});if(n.error)return n}else{if(a)return{error:Fn};{const a=Rf({tournamentRecord:t,drawDefinition:e,participantId:n,drawPosition:r,structureId:i,event:o});if(a.error)return a}}return{...E}},assignDrawPositionBye:bl,assignMatchUpSideParticipant:function({tournamentRecord:t,drawDefinition:e,participantId:n,sideNumber:r,matchUpId:i,event:a}){if(n&&"string"!=typeof n)return{error:Te};if(!e)return{error:j};if(!i)return{error:qt};const o=void 0===r;if(o&&(r=1),![1,2].includes(r))return wr({result:{error:Nn,context:{sideNumber:r}}});const{matchUp:s,structure:c}=Xm({drawDefinition:e,matchUpId:i,event:a});if(!s)return{error:Wt};if(!!(c?.structures||e.drawType&&e.drawType!==wo||c?.matchUps?.find((({roundPosition:t})=>!!t))))return{error:et};if(!n&&(s?.score?.scoreStringSide1||Ya.includes(s?.matchUpstatus)||s?.matchUpStatus&&[ka,Fa].includes(s.matchUpStatus)))return{error:ye,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);xs({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:s})}return{...E,sidesSwapped:o}},assignSeedPositions:function(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:Rt};if(!r)return{error:_};if(!c)return{error:at};const p=lu({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!==S(g).length)return{error:st};for(const t of h){const n=vf({...t,provisionalPositioning:e,tournamentRecord:r,drawDefinition:i,seedingProfile:a,structureId:o,event:u});if(n?.error)return n;n?.success&&d++}return d?{...E,modifications:d}:{error:Sn}},assignTieMatchUpParticipantId:Wf,attachConsolationStructures:function(t){return tU({...t,itemType:"attachConsolationStructures"})},attachFlightProfile:IU,attachPlayoffStructures:QI,attachQualifyingStructure:pg,attachStructures:tU,automatedPlayoffPositioning:tg,automatedPositioning:Qh,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=VU({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:Nn};const h=qU({tournamentRecord:t,scaleAttributes:r,scaleSortMethod:d,sortDescending:u,entries:l,stage:c}).scaledEntries??[],{scaleItemsWithParticipantIds:g}=jU({scaleAttributes:r,scaledEntries:h,stageEntries:f,seedsCount:m,scaleName:i});return{scaleItemsWithParticipantIds:g}},bulkMatchUpStatusUpdate:function(t){if(!t?.outcomes)return{error:ae};if(!Array.isArray(t.outcomes))return{error:ae,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:_};const i=n.filter((e=>e.tournamentId===t));if(i.length){const t=lU({outcomes:i,tournamentRecord:r});if(t.error)return t}}return{...E}},checkInParticipant:xf,checkOutParticipant:kf,deleteAdHocMatchUps:function({tournamentRecord:t,matchUpIds:e=[],drawDefinition:n,structureId:r,event:i}){if("object"!=typeof n)return{error:j};if("string"!=typeof r)return{error:It};if(!Array.isArray(e))return{error:Nn};const a=n.structures?.find((t=>t.structureId===r));if(!a)return{error:Ut};const o=a?.matchUps,s=o?.find((t=>!!t.roundPosition));if(a.structures||s||a.finishingPosition===Ko)return{error:$};const c=[],u=o?.filter((({matchUpId:t,score:n})=>($s({score:n})&&c.push(t),e.includes(t))))??[],d=u.map(Ua("matchUpId"));if(d.length){a.matchUps=(a.matchUps??[]).filter((({matchUpId:t})=>!d.includes(t))),ks({tournamentId:t?.tournamentId,matchUpIds:d,action:"deleteAdHocMatchUps",eventId:i?.eventId,drawDefinition:n});const e=function(t,e=1){return Array.isArray(t)&&t.every(p)?w(Math.min(...t,e),Math.max(...t)+1).filter((e=>!t.includes(e))):[]}(m(a.matchUps.map(Ua("roundNumber"))));if(e.length){e.reverse();for(const r of e)a.matchUps.forEach((e=>{e.roundNumber&&e.roundNumber>r&&(e.roundNumber-=1,xs({tournamentId:t?.tournamentId,context:["adHoc round deletion"],eventId:i?.eventId,drawDefinition:n,matchUp:e}))}))}if(c.length){a.positionAssignments=m(a.matchUps.flatMap((t=>(t.sides??[]).map((t=>t.participantId)))).filter(Boolean)).map((t=>({participantId:t})));const e=a?.matchUpFormat??n?.matchUpFormat??i?.matchUpFormat,r=jg({positionAssignments:a.positionAssignments,matchUps:a.matchUps,tournamentRecord:t,drawDefinition:n,matchUpFormat:e,event:i});r.error&&console.log(r)}Ls({structureIds:[r],eventId:i?.eventId,drawDefinition:n})}return{...E}},deleteDrawDefinitions:Jm,deleteEvents:function({removePairParticipants:t,tournamentRecord:e,eventIds:n}){if(!e)return{error:_};if(!e.events)return{error:Pt};if(!Array.isArray(n))return{error:ae,info:Pf("drawIds")};const r=[],i=[],a=[],o=[];if(e.events=(e.events||[]).filter((t=>{if(n.includes(t.eventId)){const n={action:Ym,payload:{events:[t]}};r.push(n),i.push({tournamentId:e.tournamentId,eventName:t.eventName,eventType:t.eventType,category:t.category,eventId:t.eventId,gender:t.gender})}const s=t.eventType===nd?(t.entries||[]).map((({entryStatus:t,participantId:e})=>t!==Qc&&e)).filter(Boolean):[],c=n.includes(t.eventId);return c?o.push(...s):a.push(...s),!c})),t){const t=o.filter((t=>!a.includes(t)));e.participants=e.participants.filter((({participantId:e})=>!t.includes(e)))}if(km({tournamentRecord:e}),r.length){sr({topic:ds,payload:r});Lm({tournamentRecord:e,timeItem:{itemType:Ym,itemValue:i}})}return{...E}},deleteFlightAndFlightDraw:function({autoPublish:t=!0,tournamentRecord:e,auditData:n,drawId:r,event:i,force:a}){if(!e)return{error:_};if(!r)return{error:at};if(!i)return{error:Tt};const{flightProfile:o}=Bd({event:i});if(o){const t=o.flights?.find((t=>t.drawId===r));if(t){const t=o.flights.filter((t=>t.drawId!==r));_i({event:i,extension:{name:Ki,value:{...o,flights:t}}})}}const s=i.drawDefinitions?.find((t=>t.drawId===r));if(s){const o=Jm({drawIds:[r],eventId:i.eventId,tournamentRecord:e,autoPublish:t,auditData:n,event:i,force:a});if(o.error)return o}return NI({tournamentRecord:e,event:i})},deleteFlightProfileAndFlightDraws:function({autoPublish:t=!0,tournamentRecord:e,auditData:n,event:r,force:i}){if(!e)return{error:_};if(!r)return{error:Tt};const{flightProfile:a}=Bd({event:r});if(a){const o=a.flights?.map((({drawId:t})=>t)).filter(Boolean),s=Jm({eventId:r.eventId,tournamentRecord:e,autoPublish:t,auditData:n,drawIds:o,event:r,force:i});return s.error?s:Bi({event:r,name:Ki})}return{...E}},destroyPairEntries:function(t){if(!t.tournamentRecord)return{error:_};const{participantIds:e,...n}=t;let r=0;const i=[];for(const t of e){const e=Um({participantId:t,...n});e.success&&(r+=1),e.error&&i.push(e.error)}return r?{destroyedCount:r,...E}:{error:i}},destroyPairEntry:Sm,disableTieAutoCalc:function({drawDefinition:t,matchUpId:e,event:n}){if(!t)return{error:j};const{matchUp:r}=Xm({drawDefinition:t,matchUpId:e,event:n});return Nr({extension:{name:Hi,value:!0},element:r})},drawMatic:function(t){const e=t.tournamentRecord?.participants;return Object.assign(t,{tournamentParticipants:e}),xU(t)},enableTieAutoCalc:function({tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r}){if(!e)return{error:j};const{matchUp:i}=Xm({drawDefinition:e,matchUpId:n,event:r});return i?.matchUpType!==Xs?{error:Yt}:PI({enableAutoCalc:!0,tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r})},getAvailablePlayoffProfiles:ug,getAvailablePlayoffRounds:ug,luckyLoserDrawPositionAssignment:function(t){return function({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i}){return Mf({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i})}(t)},modifyCollectionDefinition:Ph,modifyDrawDefinition:function({tournamentRecord:t,drawDefinition:e,drawUpdates:n,drawId:r,event:i}){if(!ha(n))return{error:Nn};const a=Bd({event:i}).flightProfile,o=n.drawName&&pU({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:j};if(s){_i({event:i,extension:{name:Ki,value:{...a,flights:a.flights}}})}return e&&(n.policyDefinitions&&uU({policyDefinitions:n.policyDefinitions,drawDefinition:e}),Ls({tournamentId:t?.tournamentId,drawDefinition:e})),{...E}},modifyDrawName:pU,modifyEntriesStatus:Ll,modifyEvent:function({tournamentRecord:t,eventUpdates:e,eventId:n,event:r}){const i="modifyEvent";if(!t)return wr({result:{error:_},stack:i});if(!fa(n))return wr({result:{error:Tt},context:{eventId:n},stack:i});if(!ha(e))return wr({result:{error:Nn},context:{eventUpdates:e},stack:i});const a=r?.entries?.filter((({entryStatus:t})=>{const e=t;return[...ou,$c].includes(e)})).map((({participantId:t})=>t))??[],o=a?Zl({participantFilters:{participantIds:a},withIndividualParticipants:!0,tournamentRecord:t}).participants??[]:[],s=[],c=o.reduce(((t,e)=>{const n=e.person?.sex?[e.person.sex]:e.individualParticpants?.map((t=>t.person?.sex))||[];return s.push(...n),t.includes(e.participantType)?t:t.concat(e.participantType)}),[]),u=m(s),d=!u.length||[$p,Gp].includes(e.gender??"")||1===u.length&&u[0]===e.gender;if(e.gender&&!d)return wr({context:{gender:e.gender,validGender:d},result:{error:Nn},stack:i});const p=(c.includes(id)&&[id]||c.includes(sc)&&[td]||c.includes(uc)&&[nd]||[nd,td,id]).includes(e.eventType??"");return e.eventType&&!p?wr({context:{participantType:e.eventType,validEventType:p},result:{error:Nn},stack:i}):(e.eventType&&(r.eventType=e.eventType),e.eventName&&(r.eventName=e.eventName),e.gender&&(r.gender=e.gender),{...E})},modifyEventEntries:function({entryStatus:t=Hc,unpairedParticipantIds:e=[],participantIdPairs:n=[],entryStage:r=Xa,tournamentRecord:i,event:a}){if(!i)return{error:_};if(!a)return{error:Tt};const o=i.participants??[],s=o.filter((t=>t.participantType===sc)).map((t=>t.participantId)),c=e.concat(...n).flat(1/0).filter((t=>!s.includes(t)));if(c.length)return{error:Pe,invalidParticipantIds:c};const u=n.filter((t=>2!==t.length));if(u.length)return{error:Pe,invalidParticipantIdPairs:u};const d=o.filter((t=>t.participantType===uc)).map((t=>t.individualParticipantIds)),p=gU({participants:n.filter((t=>!d.find((e=>2===P(e,t).length)))).map((t=>({participantType:uc,participantRole:um,individualParticipantIds:t}))),tournamentRecord:i});if(p.error)return p;const l=n.map((t=>{const{participant:e}=Vc({tournamentRecord:i,participantIds:t});return e})).map((e=>({participantId:e,entryStatus:t,entryStage:r}))),m=e.map((t=>({entryStatus:Qc,participantId:t,entryStage:r})));return a.entries=(a.entries??[]).filter((t=>t.entryStage===r)),a.entries=a.entries.concat(...l,...m),{...E}},modifyPairAssignment:function({replacementIndividualParticipantId:t,existingIndividualParticipantId:e,tournamentRecord:n,drawDefinition:r,participantId:i,event:a,uuids:o}){if(!a)return{error:Tt};if(a?.eventType!==nd)return{error:wt};if(o&&!Array.isArray(o))return{error:Nn};if(!n)return{error:_};if(![t,e,i].every((t=>"string"==typeof t)))return{error:Ae};if(!(a?.entries?.filter((({entryStatus:t})=>[Qc,tu].includes(t))).map((({participantId:t})=>t))||[]).includes(t))return{error:Te};const s=(n.participants||[]).find((t=>t.participantId===i));if(s?.participantType!==uc)return{error:we,participant:s};const c=s.individualParticipantIds,u=[t,...c.filter((t=>t!==e))],{participant:d}=Vc({participantIds:u,tournamentRecord:n});let p;if(d)p=d.participantId;else{const t=Bf({participant:{participantId:o?.pop(),participantRole:um,individualParticipantIds:u,participantType:uc},returnParticipant:!0,tournamentRecord:n});if(t.error)return t;p=t.participant.participantId}const{flightProfile:l}=Bd({event:a});if(r){const t=l?.flights?.find((({drawId:t})=>t===r.drawId));t&&(t.drawEntries=t.drawEntries.map((t=>t.participantId===i?{...t,participantId:p}:t))),r.entries=r.entries.map((t=>t.participantId===i?{...t,participantId:p}:t));for(const t of r.structures||[])if(t.positionAssignments)t.positionAssignments=t.positionAssignments.map((t=>t.participantId===i?{...t,participantId:p}:t));else if(t.structures)for(const e of t.structures)e.positionAssignments=e.positionAssignments.map((t=>t.participantId===i?{...t,participantId:p}:t))}a.entries=a.entries.map((n=>n.participantId===i&&{...n,participantId:p}||n.participantId===t&&{...n,participantId:e}||n));const m=n.events.some((({entries:t,eventId:e,drawDefinitions:n})=>a.eventId===e?n.some((({drawId:t,entries:e})=>t!==r?.drawId&&e?.find((t=>t.participantId===i)))):t?.find((t=>t.participantId===i))));if(!m){const t=gm({addIndividualParticipantsToEvents:!1,participantIds:[i],tournamentRecord:n});if(t.error)return t}return{...E,participantOtherEntries:m,newPairParticipantId:p}},modifySeedAssignment:function({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:i,seedValue:a,event:o}){return t?(t.participants||[]).find((t=>t.participantId===r))?function({validation:t=!0,tournamentRecord:e,drawDefinition:r,participantId:i,structureId:a,seedValue:o,event:c}){if(!r)return{error:j};if(!a)return{error:It};const{structure:u}=ts({drawDefinition:r,structureId:a});if(!u)return{error:Ut};if(!(!t||s(o)||void 0===o||""===o||"string"==typeof o&&o.split("-").every((t=>s(t)&&n(t)>0))))return{error:Nn};const{seedAssignments:d}=lu({drawDefinition:r,structure:u}),p=d?.map((t=>t.seedNumber)),l=d?.find((t=>t.participantId===i));if(l){const t="string"==typeof o?o.includes("-")&&o.split("-").map((t=>parseInt(t))).join("-")||parseInt(o)>0&&parseInt(o)||"":o&&o>0&&o||"";l.seedValue=t}else{const t={seedNumber:Math.max(0,...p||[])+1,participantId:i};o&&(t.seedValue=o),u.seedAssignments||(u.seedAssignments=[]),u.seedAssignments.push(t)}return Bs({tournamentId:e?.tournamentId,eventId:c?.eventId,drawDefinition:r,structure:u}),{...E}}({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:i,seedValue:a,event:o}):{error:Te}:{error:_}},modifyTieFormat:function({updateInProgressMatchUps:t=!1,tieFormatComparison:e,modifiedTieFormat:n,tournamentRecord:r,drawDefinition:i,structureId:a,matchUpId:o,eventId:s,uuids:c,event:u}){const d="modifyTieFormat";if(!fh({tieFormat:n}).valid)return wr({result:{error:Lt},info:"falied validation",stack:d});const p=Zf({drawDefinition:i,structureId:a,matchUpId:o,eventId:s,event:u});if(p.error)return wr({result:p,stack:d});const{matchUp:l,tieFormat:m}=p,f=Yf(m),g=Uh({descendant:n,ancestor:f});if(g.invalid)return wr({context:{invalid:g.invalid},result:{error:Lt},stack:d});if(!g?.different)return wr({result:{...E},info:"Nothing to do",stack:d});const I=f.collectionDefinitions.map((({collectionId:t})=>t)),U=n.collectionDefinitions.map((({collectionId:t})=>t)),S=I.filter((t=>!U.includes(t))),y=n.collectionDefinitions.filter((({collectionId:t})=>!I.includes(t))),v=y.map(Ua("collectionId")),w=[];let T;const P=n.tieFormatName;for(const e of n.collectionDefinitions){if(v.includes(e.collectionId))continue;const n=Ph({updateInProgressMatchUps:t,...e,tournamentRecord:r,tieFormatName:P,drawDefinition:i,structureId:a,matchUpId:o,eventId:s,event:u});if(n.modifications&&w.push(...n.modifications),n.error)return wr({result:n,stack:d});n.tieFormat&&(T=n.tieFormat)}for(const e of y){const n=oU({updateInProgressMatchUps:t,collectionDefinition:e,tournamentRecord:r,drawDefinition:i,tieFormatName:P,structureId:a,matchUpId:o,matchUp:l,eventId:s,uuids:c,event:u});if(n.error)return wr({result:n,stack:d});n.tieFormat&&(T=n.tieFormat)}for(const n of S){const c=xI({updateInProgressMatchUps:t,tieFormatComparison:e,tournamentRecord:r,drawDefinition:i,tieFormatName:P,collectionId:n,structureId:a,matchUpId:o,eventId:s,matchUp:l,event:u});if(c.error)return wr({result:c,stack:d});c.tieFormat&&(T=c.tieFormat)}return m?.tieFormatName!==P?(T.tieFormatName=P,w.push({tieFormatName:P})):(w.length||v.length||S.length)&&(delete T.tieFormatName,w.push("tieFormatName removed: modifications without new tieFormatName")),T.collectionDefinitions=T.collectionDefinitions.sort(((t,e)=>h(t.collectionOrder)-h(e.collectionOrder))).map(((t,e)=>({...t,collectionOrder:e+1}))),{processedTieFormat:Yf(T),modifications:w,...E}},orderCollectionDefinitions:function({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=>p(t))))return wr({result:{error:Nn},context:{orderMap:i}});if(a&&s?.tieFormat)OI({tournamentRecord:t,event:s,orderMap:i});else if(r){const n=e&&Xm({drawDefinition:e,matchUpId:r});if(n?.error)return n;if(!(o=n.matchUp))return{error:zt};o?.tieFormat&&(o.tieFormat=CI({tieFormat:o.tieFormat,orderMap:i}),xs({tournamentId:t?.tournamentId,eventId:s?.eventId,drawDefinition:e,matchUp:o}))}else if(n){const r=ts({drawDefinition:e,structureId:n});if(r.error)return r;const a=r.structure;if(a?.tieFormat)a.tieFormat=CI({tieFormat:a.tieFormat,orderMap:i}),kI({eventId:s?.eventId,tournamentRecord:t,drawDefinition:e,structure:a,orderMap:i}),Ls({drawDefinition:e,structureIds:[a.structureId]});else if(e.tieFormat)FI({structureIds:[n],tournamentRecord:t,drawDefinition:e,orderMap:i,event:s});else{if(!s?.tieFormat)return{error:On};OI({structureIds:[n],tournamentRecord:t,orderMap:i,event:s})}}else{if(!e?.tieFormat)return{error:On};FI({tournamentRecord:t,drawDefinition:e,orderMap:i,event:s})}return{...E}},promoteAlternate:function(t){const{participantId:e}=t;return e&&"string"!=typeof e?{error:Nn,participantId:e}:FS({...t,participantIds:[e].filter(Boolean)})},promoteAlternates:FS,pruneDrawDefinition:function({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:n,drawId:r}){if(!e)return{error:_};if(!n)return{error:j};let i=[];const{drawsAnalysis:a}=mU({tournamentRecord:e});if(a.canBePruned.includes(r)){const o=a.matchPlay.includes(r),s=a.drawAnalysis[r],{structures:[c]}=es({stageSequence:1,drawDefinition:n,stage:Xa}),u=s.structuresData.find((({structureId:t})=>c.structureId===t)),d=c.matchUps??[];i=d.sort(((t,e)=>t.roundPosition-e.roundPosition)).filter((({roundNumber:t})=>!u.inactiveRounds.includes(t)));const p=i.map(ba),l=d.map(ba).filter((t=>!p.includes(t)));if(o){const e=i.sort(((t,e)=>t.roundPosition-e.roundPosition)).filter((({roundNumber:t})=>!u.inactiveRounds.includes(t))).filter((({winningSide:t})=>t)),n=e.map(ba),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}ks({tournamentId:e?.tournamentId,matchUpIds:l,drawDefinition:n}),Ls({drawDefinition:n})}return{...E,matchUps:i}},qualifierDrawPositionAssignment:function(t){return function({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i}){return Mf({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i})}(t)},refreshEventDrawOrder:NI,removeCollectionDefinition:xI,removeCollectionGroup:function({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:ae};if(isNaN(e))return{error:Nn};const d="removeCollectionGroup";let p=s?void 0:Zf({drawDefinition:r,structureId:a,matchUpId:o,eventId:c,event:u});if(p?.error)return wr({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=Yf(m);if(p=fh({tieFormat:g}),p.error)return wr({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=EI({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}=Dc({tournamentRecord:n});if(t?.audit?.[ua]){Th({drawDefinition:r,auditData:vr({drawId:r?.drawId,collectionGroupNumber:e,action:d,structureId:a,matchUpId:o,eventId:c})})}}return wr({result:{...p,modifiedCollectionIds:I},stack:d})},removeDelegatedOutcome:function({drawDefinition:t,event:e,matchUpId:n}){if(!t)return{error:j};if(!n)return{error:qt};const{matchUp:r}=Xm({drawDefinition:t,event:e,matchUpId:n});return r?Dr({name:qi,element:r}):{error:Wt}},removeDrawEntries:function({autoEntryPositions:t=!0,participantIds:e,drawDefinition:n,drawId:r,stages:i,event:a}){if(!a)return{error:Tt};if(!r)return{error:at};if(!e?.length)return{error:Fe};if(b(kl({drawDefinition:n,stages:i}).assignedParticipantIds??[],e))return{error:Le};const o=t=>{const n=t.participantId;return!e.includes(n)},{flightProfile:s}=Bd({event:a}),c=s?.flights?.find((t=>t.drawId===r));return c?.drawEntries&&(c.drawEntries=c.drawEntries.filter(o),t&&(c.drawEntries=xl({entries:c.drawEntries}))),n?.entries&&(n.entries=n.entries.filter(o),t&&(n.entries=xl({entries:n.entries}))),{...E}},removeDrawPositionAssignment:ym,removeEventEntries:om,removeMatchUpSideParticipant:function({tournamentRecord:t,drawDefinition:e,sideNumber:n,matchUpId:r,event:i}){if(!t)return{error:_};if(!e)return{error:j};if(!r)return{error:qt};if(!n)return{error:ae};if(![1,2].includes(n))return{error:Nn,sideNumber:n};const{matchUp:a,structure:o}=Xm({drawDefinition:e,matchUpId:r,event:i});return a?o?.structures||e.drawType&&e.drawType!==wo||o?.matchUps?.find((({roundPosition:t})=>!!t))?{error:et}:(a.sides?.forEach((t=>{t.sideNumber===n&&delete t.participantId})),xs({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:a}),{...E}):{error:Wt}},removeRoundMatchUps:function({removeCompletedMatchUps:t,tournamentRecord:n,drawDefinition:r,structureId:i,roundNumber:a,event:o}){if(!n)return{error:_};if(!r)return{error:j};if(!a)return wr({result:{error:ae},info:"roundNumber required"});const s=ts({drawDefinition:r,structureId:i});if(s.error)return s;const c=s.structure;return c?.structures?{error:$}:ap({drawDefinition:r,structure:c})?function({removeCompletedMatchUps:t,drawDefinition:n,tournamentId:r,roundNumber:i,structure:a,eventId:o}){const s=a?.matchUps??[],c=[];let u=!1;if(s.reduce(((t,e)=>{const n=e?.roundNumber;return n?t.includes(n)?t:t.concat(n):t}),[]).sort(e).includes(i)){const e=s.filter((e=>{const n=e.roundNumber===i&&(!Ya.includes(e.matchUpStatus)||t);return n&&c.push(e.matchUpId),!n}));if(c.length){ks({matchUpIds:c,drawDefinition:n,tournamentId:r,eventId:o});e.some((t=>t.roundNumber===i))||(e.forEach((t=>{t.roundNumber>i&&(t.roundNumber-=1,xs({drawDefinition:n,tournamentId:r,eventId:o,matchUp:t}))})),u=!0),a.matchUps=e}}return{deletedMatchUpsCount:c.length,roundRemoved:u,...E}}({tournamentId:n.tournamentId,removeCompletedMatchUps:t,eventId:o.eventId,drawDefinition:r,roundNumber:a,structure:c}):(console.log("not implemented"),{...E})},removeScaleValues:UU,removeSeededParticipant:function({tournamentRecord:t,drawDefinition:e,participantId:n,structureId:r}){const i="removeSeededParticipant";if(!t)return{error:_};if(!e)return{error:j};const a=(e.structures??[]).find((t=>t.structureId===r));if(!a)return wr({result:{error:Ut},stack:i});if(!a.stage||![Xa,Qa].includes(a.stage)||a.stage===Xa&&1!==a.stageSequence)return wr({result:{error:$},stack:i});const o=a.seedAssignments?.find((t=>t.participantId===n));return o?{...E}:wr({info:"participant not seeded",result:{error:On},context:{participantId:n}})},removeSeeding:function({tournamentRecord:t,drawDefinition:e,entryStatuses:n,scaleName:r,drawId:i,event:a,stage:o}){return t?a?(r=r||a.category?.categoryName||a.category?.ageCategoryCode,UU({tournamentRecord:t,scaleAttributes:{eventType:a.eventType,scaleType:Fr,scaleName:r},drawDefinition:e,entryStatuses:n,drawId:i,event:a,stage:o})):{error:Tt}:{error:_}},removeStructure:function({tournamentRecord:t,drawDefinition:e,structureId:n,event:r,force:i}){if("string"!=typeof n)return{error:Nn};if(!e)return{error:j};if(!n)return{error:It};const a=e.structures??[],o=[],s=a.find((t=>t.structureId===n));if(!s)return{error:Ut};if(Yp({structure:s}).matchUps.some((({score:t})=>$s({score:t})))){const n=Dc({tournamentRecord:t,drawDefinition:e,structure:s,event:r})?.appliedPolicies;if(!(i??n?.[Mi]?.allowDeletionWithScoresPresent?.structures))return{error:qn}}const c=a.find((({stage:t,stageSequence:e})=>t===Xa&&1===e)),u=n===c?.structureId,d=a.filter((({stage:t})=>t===Qa)).map(Ua("structureId"));if(u&&!d.length)return{error:F};const p=a.map(Ua("structureId")),l=[],m=d.includes(n),f=new Map;p.forEach((t=>{return f.set(t,m?(n=t,e.links?.map((t=>d.includes(t.source.structureId)&&t.target.structureId===n&&t.source.structureId)).filter(Boolean)??[]):(t=>e.links?.map((e=>e.source.structureId===t&&e.target.structureId!==c?.structureId&&e.target.structureId)).filter(Boolean)??[])(t));var n}));const h=u?f.get(n):[n];for(;h?.length;){const t=h.pop(),{structure:r}=ts({structureId:t,drawDefinition:e}),{matchUps:i}=Yp({structure:r}),a=Ta(i);l.push(...a),e.links=e.links?.filter((e=>e.source.structureId!==t&&e.target.structureId!==t))??[],(!u||u&&d.length||t!==n)&&(e.structures=(e.structures??[]).filter((e=>(t&&t===e.structureId&&o.push(t),e.structureId!==t))));const s=t&&f.get(t)?.filter((t=>t!==c?.structureId||n===c.structureId));s?.length&&h.push(...s)}const{matchUps:g}=Jp({drawDefinition:e});if(g?.forEach((t=>{t.winnerMatchUpId&&l.includes(t.winnerMatchUpId)&&delete t.winnerMatchUpId,t.loserMatchUpId&&l.includes(t.loserMatchUpId)&&delete t.loserMatchUpId})),u){const t=(c.matchUps??[])?.map(Ua("matchUpId"));l.push(...t),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return m&&dg({drawDefinition:e}),ks({tournamentId:t?.tournamentId,matchUpIds:l,action:"removeStructure",eventId:r?.eventId,drawDefinition:e}),Ls({drawDefinition:e,eventId:r?.eventId}),{...E,removedMatchUpIds:l,removedStructureIds:o}},removeTieMatchUpParticipantId:function(t){const{tournamentRecord:e,drawDefinition:n,participantId:r,event:i}=t,a="removeTieMatchUpParticiapantId";if(!r)return wr({result:{error:Ae},stack:a});const o=Lf(t);if(o.error)return o;const{appliedPolicies:s}=Dc({tournamentRecord:e,drawDefinition:n,event:i}),c=t.policyDefinitions?.[wi]??s?.[wi]??sm[wi],u=c?.processCodes?.substitution,{inContextDualMatchUp:d,inContextTieMatchUp:p,relevantAssignments:l,collectionPosition:m,teamParticipants:f,collectionId:h,matchUpType:g,dualMatchUp:I,tieMatchUp:U,tieFormat:S}=o;if(!I)return wr({result:{error:zt},stack:a});const y=p?.sides?.find((t=>t.participant?.participantId===r||t.participant?.individualParticipantIds?.includes(r)));if(!y)return wr({result:{error:Ee},stack:a});if(!y.substitutions?.length&&($s({score:p?.score})||p?.winningSide))return wr({result:{error:_n},stack:a});const v=d?.sides?.find((({sideNumber:t})=>t===y.sideNumber))?.participantId;if(!v)return wr({result:{error:Ee},stack:a});const w=Zl({participantFilters:{participantIds:[r]},tournamentRecord:e})?.participants?.[0];if(!w)return wr({result:{error:Ee},stack:a});if(g===Ks&&w.participantType===uc)return wr({result:{error:we},stack:a});const T=w.participantType===sc?[r]:w.individualParticipantIds;Vf({tournamentId:e.tournamentId,eventId:i.eventId,inContextDualMatchUp:d,drawDefinition:n,dualMatchUp:I});let P=I.sides?.find((({sideNumber:t})=>t===y.sideNumber));if(!P&&(I.sides?.filter((({lineUp:t})=>!t)).length||0)<2){const t=f?.map((({participantId:t})=>({drawPosition:l?.find((e=>e.participantId===t))?.drawPosition,teamParticipantId:t})));P=I.sides?.find((e=>t?.find((({drawPosition:t})=>t===e.drawPosition))?.teamParticipantId===v))}if(!P)return wr({result:{error:Ee,context:{participantId:r}}});const{modifiedLineUp:D,previousParticipantIds:b}=Gf({collectionPosition:m,teamParticipantId:v,dualMatchUpSide:P,participantIds:T,drawDefinition:n,collectionId:h});if(P.lineUp=D,v&&S&&bf({participantId:v,lineUp:D,drawDefinition:n,tieFormat:S}),g===Zs&&w.participantType===sc){const t=p?.sides?.find((t=>t.sideNumber===P?.sideNumber)),{participantId:n}=t??{},i=n&&Zl({participantFilters:{participantIds:[n]},tournamentRecord:e,withDraws:!0})?.participants?.[0];if(!i)return wr({result:{error:Ee},stack:a});{const t=i?.individualParticipantIds?.filter((t=>t!==r))??[];if(b&&t.push(...b),t.length>2)return wr({result:{error:Pe},stack:a});if(i.draws?.length){if(1===t.length){const{participant:n}=Vc({participantIds:t,tournamentRecord:e});if(!n){const n=Bf({participant:{participantRole:um,individualParticipantIds:t,participantType:uc},pairOverride:!0,tournamentRecord:e});if(n.error)return wr({result:n,stack:a})}}}else if(t.length){i.individualParticipantIds=t;const n=$f({participant:i,pairOverride:!0,tournamentRecord:e});if(n.error)return wr({result:n,stack:a})}else{const t=gm({participantIds:[n],tournamentRecord:e});t.error&&console.log("cleanup",{result:t})}}}if(1===y.substitutions?.length){const t=p?.sides?.find((t=>t.sideNumber!==y.sideNumber));if(!t?.substitutions?.length&&U?.processCodes?.length){for(const t of u||[]){const e=U.processCodes.lastIndexOf(t);U.processCodes.splice(e,1)}xs({tournamentId:e?.tournamentId,matchUp:U,context:a,drawDefinition:n})}}return xs({tournamentId:e?.tournamentId,matchUp:I,context:a,drawDefinition:n}),{...E,modifiedLineUp:D}},renameStructures:function({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:Nn};if(!t)return{error:j};const n=Object.assign({},...e.map((t=>{if(!ha(t))return;const{structureId:e,structureName:n}=t||{};return e&&n?{[e]:n}:void 0})).filter(Boolean));if(!Object.values(n).length)return{error:ae};for(const e of t.structures||[]){const t=n[e.structureId];t&&(e.structureName=t)}return{...E}},replaceTieMatchUpParticipantId:jf,resetDrawDefinition:function({tournamentRecord:t,removeScheduling:e,drawDefinition:n}){if(!n)return{error:j};const r=xc({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&&[Qa,Xa].includes(s)||(a.positionAssignments=o.map((t=>(delete t.participantId,t))),a.seedAssignments=[]);const{matchUps:u}=Yp({afterRecoveryTimes:!1,inContext:!0,matchUpsMap:r,structure:a});for(const r of u){const{matchUpId:a,roundNumber:o,sides:s}=r,c=i(a);if(c){if(delete c.extensions,delete c.notes,c.matchUpStatus!==Ma&&Object.assign(c,Lg),o&&o>1&&c.drawPositions){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&&![Pu,Du,Tu,Ru,Nu,Mu].includes(t.itemType)))),xs({tournamentId:t?.tournamentId,context:"resetDrawDefiniton",drawDefinition:n,matchUp:c})}}}return Ls({drawDefinition:n,structureIds:(n.structures||[]).map((({structureId:t})=>t))}),{...E}},resetMatchUpLineUps:function({inheritance:t=!0,tournamentRecord:e,drawDefinition:n,matchUpId:r,event:i}){if(!n)return{error:j};const a=Xm({drawDefinition:n,matchUpId:r})?.matchUp;if(!a?.tieMatchUps)return{error:Yt};const o=Xm({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&&bf({drawDefinition:n,participantId:e,lineUp:[],tieFormat:t})}xs({tournamentId:e?.tournamentId,context:"resetMatchUpLineUps",eventId:i?.eventId,drawDefinition:n,matchUp:a})})),{...E,modificationsCount:s}},resetScorecard:function(t){const{tournamentRecord:e,drawDefinition:n,matchUpId:r,event:i}=t,a="resetScorecard";if(!n)return wr({result:{error:j},stack:a});if(!r)return wr({result:{error:qt},stack:a});if(!fa(r))return wr({result:{error:Nn,matchUpId:r},stack:a});const o=xc({drawDefinition:n}),{matchUps:s}=Jp({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:Wt};if(c.matchUpType!==ad)return{error:Yt};const d=Uc({inContextDrawMatchUps:s,drawDefinition:n,matchUpId:r}),p=u?.structureId,{structure:l}=ts({drawDefinition:n,structureId:p});if(Object.assign(t,{inContextDrawMatchUps:s,inContextMatchUp:u,matchUpsMap:o,targetData:d,structure:l,matchUp:c}),rI(t))return{error:ve};if(c.tieMatchUps?.length)for(const t of c.tieMatchUps){const o=PI({matchUpId:t.matchUpId,matchUpTieId:r,winningSide:void 0,removeScore:!0,tournamentRecord:e,drawDefinition:n,event:i});if(o.error)return wr({result:o,stack:a})}const m=$g({event:t.event,removeScore:!0,tournamentRecord:e,drawDefinition:n,matchUpsMap:o,matchUpId:r});if(m.error)return wr({result:m,stack:a});if(t.tiebreakReset&&!m.tieFormatRemoved){const t=$d({drawDefinition:n,structure:l,event:i})?.tieFormat;if(c.tieFormat&&t){const{matchUpCountDifference:a,descendantDifferences:o,ancestorDifferences:s,valueDifference:u}=Uh({descendant:c.tieFormat,ancestor:t});if(1===o.collectionIds.length&&!s.collectionIds.length&&!s.groupsCount&&1===a&&1===u){const t=SU({tournamentRecord:e,drawDefinition:n,matchUpId:r,event:i});if(t.error)return t}}}return{...E}},resetTieFormat:SU,resetVoluntaryConsolationStructure:function({tournamentRecord:t,drawDefinition:e,resetEntries:n,event:r}){if(!e)return{error:j};const i=e.structures?.find((t=>t.stage===eo));if(!i)return{error:Ut};const a=i.matchUps?.map((({matchUpId:t})=>t))||[];return i.positionAssignments=[],i.seedAssignments=[],i.matchUps=[],ks({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:a,drawDefinition:e}),n&&(e.entries=e.entries.filter((t=>t.entryStage!==eo))),Ls({tournamentId:t?.tournamentId,eventId:r?.eventId,drawDefinition:e,structureIds:[i.structureId]}),{...E}},setDelegatedOutcome:function(t){return function({drawDefinition:t,matchUpId:e,outcome:n,matchUp:r}){if(!r&&!t)return{error:j};if(!n)return{error:ae,info:"missing outcome"};if(!r&&!e)return{error:zt};if(!r){const n=Xm({drawDefinition:t,matchUpId:e});if(n.error)return n;r=n.matchUp}return"object"==typeof n&&n.score?.scoreStringSide1&&n.score?.scoreStringSide2?Nr({element:r,extension:{name:qi,value:n}}):{error:Nn}}(t)},setDrawParticipantRepresentativeIds:function({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:q};if(!Array.isArray(t))return{error:Nn};const n=Pa(e?.entries||[]);return t.length&&P(t,n).length<t.length?{error:Nn}:xi({drawDefinition:e,extension:{name:ta,value:t}})},setEntryPosition:xS,setEntryPositions:function({tournamentRecord:t,entryPositions:e,drawDefinition:n,event:r}){if(!t)return{error:_};if(!Array.isArray(e))return{error:Nn};for(const i of e){const{participantId:e,entryPosition:a}=i,o=xS({skipRefresh:!0,tournamentRecord:t,drawDefinition:n,participantId:e,entryPosition:a,event:r});if(o.error)return o}return r?.entries&&(r.entries=xl({entries:r.entries})),n?.entries&&(n.entries=xl({entries:n.entries})),{...E}},setEventDates:function({tournamentRecord:t,event:e,startDate:n,endDate:r}){if(!t)return{error:_};if(!e)return{error:Tt};if(!n&&!r)return{error:ae,info:"missing date"};if(n&&!Vr.test(n))return{error:pe};if(r&&!Vr.test(r))return{error:pe};if(n&&r){if(new Date(ri(n))>new Date(ri(r)))return{error:Nn}}if(n){const r=_S({tournamentRecord:t,event:e,startDate:n});if(r.error)return r}if(r){const n=LS({tournamentRecord:t,event:e,endDate:r});if(n.error)return n}return{...E}},setEventEndDate:LS,setEventStartDate:_S,setMatchUpFormat:function(t){const e="setMatchUpFormat",{tournamentRecord:n,drawDefinition:r,scheduledDates:i,stageSequences:a,matchUpFormat:o,structureId:s,eventType:c,matchUpId:u,eventId:d,stages:p,drawId:l,event:m,force:f}=t;if(!n)return{error:_};if(!o)return{error:Vt};if(o&&!rh(o))return wr({result:{error:kt,matchUpFormat:o},stack:e});if(i&&!Array.isArray(i))return wr({result:{error:Nn,scheduledDates:i},stack:e});if(c&&![td,nd].includes(c))return wr({result:{error:wt},stack:e});let h=0;const g=t.structureIds||s&&[s].filter(Boolean)||[],I=t.eventIds||d&&[d].filter(Boolean)||[],U=t.drawIds||l&&[l].filter(Boolean)||[];if((s||g?.length)&&!r)return wr({result:{error:j},stack:e});if(l&&u&&r){const t=GI({tournamentRecord:n,drawDefinition:r,matchUpFormat:o,structureIds:g,structureId:s,matchUpId:u});if(t.error)return t;h+=1}const S=t=>{const r=[];for(const s of t.structures||[]){if(Array.isArray(p)&&!p.includes(s.stage)||Array.isArray(a)&&!a.includes(s.stageSequence)||g?.length&&!g.includes(s.structureId))continue;g?.length&&s.matchUpFormat!==o&&(s.matchUpFormat=o,r.push(s.structureId),h+=1);const c=(f||i)&&Yp({matchUpFilters:{matchUpStatuses:[ja]},structure:s}).matchUps,u=i&&Yp({matchUpFilters:{matchUpStatuses:[ja]},contextFilters:{scheduledDates:i},afterRecoveryTimes:!1,inContext:!0,structure:s}).matchUps;if(c?.length){const r=u?u.map(ba):c.map(ba);for(const a of c)r.includes(a.matchUpId)&&(a.matchUpFormat=i?.length?o:void 0,xs({tournamentId:n?.tournamentId,eventId:m?.eventId,context:e,drawDefinition:t,matchUp:a}))}}return r.length||t.matchUpFormat===o||(t.matchUpFormat=o,h+=1),r};for(const t of n.events||[])if(!(I?.length&&!I.includes(t.eventId)||c&&c!==t.eventType||c===id))if(Array.isArray(a)||Array.isArray(p)||g?.length||U?.length)for(const e of t.drawDefinitions||[]){if(Array.isArray(U)&&!U.includes(e.drawId))continue;Ls({structureIds:S(e),drawDefinition:e})}else t.matchUpFormat!==o&&(t.matchUpFormat=o,h+=1);return h?{...E,modificationsCount:h}:{...E,info:Sn}},setMatchUpStatus:aU,setOrderOfFinish:function(t){return function({drawDefinition:t,finishingOrder:e}){if(!t)return{error:j};const n="setOrderOfFinish";if(!Array.isArray(e))return wr({info:Pf("finishingOrder"),result:{error:Nn},stack:n});const{completedMatchUps:r,matchUpsMap:i}=Zp({inContext:!0,drawDefinition:t}),a=r?.map(ba)??[],o=e.map(ba),{matchUpTypes:s,roundNumbers:c,structureIds:u,matchUpTieIds:d}=(r??[]).filter((({matchUpId:t})=>o.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(s.length>1||d.length>1||c.length>1||u.length>1)return wr({info:"matchUpType, structureId and roundNumber must be equivalent",result:{error:Nn},stack:n});let l,m;const f={},h=[],g=[],I=e.every((({orderOfFinish:t,matchUpId:e})=>(h.push(e),t&&g.push(t),f[e]=t,l=a.includes(e),m=void 0===t||p(t)&&Math.floor(t)>0,l&&m)));if(!I)return wr({result:{error:l?Nn:_t},info:(l?!m&&"orderOfFinish must be integer > 0 or undefined":"matchUps must be completed")||void 0,stack:n});const U=r?.filter((t=>t.structureId===u[0]&&t.roundNumber===c[0]&&t.matchUpType===s[0]&&t.matchUpTieId===d[0]&&!h.includes(t.matchUpId)));for(const t of U??[]){const{orderOfFinish:e}=t||{};if(e){if(!p(e))return wr({context:{orderOfFinish:e,matchUp:t},result:{error:Nn},stack:n});g.push(e)}}if(S(g).length!==g.length||Math.max(...g)>g.length)return wr({info:"Values not unique or greater than expected number of values",result:{error:Nn},stack:n});if(u.length){const e=Kp({matchUpFilters:{matchUpIds:o},structureId:u[0],drawDefinition:t,matchUpsMap:i});if(e.error)return wr({result:e,stack:n});e.completedMatchUps?.forEach((t=>t.orderOfFinish=f[t.matchUpId]))}return{...E}}(t)},setPositionAssignments:function(t){return function({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:n,drawDefinition:r,event:i}){if(!r)return{error:j};if(!Array.isArray(t))return{error:Nn};for(const a of t){const{structureId:t,positionAssignments:o}=a;if(!o)continue;const s=ts({drawDefinition:r,structureId:t});if(s.error)return s;const c=s.structure;if(!c)return{error:Ut};const u=rs({structure:c}).positionAssignments?.map((({drawPosition:t})=>t)),d=o?.map((({drawPosition:t})=>t));if(P(u,d).length!==u?.length)return wr({result:{error:Nn},info:"drawPositions do not match",stack:"setPositionAssignments"});const p=xc({drawDefinition:r}),{matchUps:l}=Jp({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=bl({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=Rf({provisionalPositioning:e,inContextDrawMatchUps:l,tournamentRecord:n,drawDefinition:r,participantId:u,drawPosition:s,matchUpsMap:p,structureId:t,event:i});if(a?.error)return a}}Vs({tournamentId:n?.tournamentId,drawDefinition:r,structure:c,event:i})}const a=t.map((({structureId:t})=>t));return Ls({tournamentId:n?.tournamentId,eventId:i?.eventId,drawDefinition:r,structureIds:a}),{...E}}(t)},setStructureOrder:function({drawDefinition:t,orderMap:e}){return t?("object"==typeof e&&Object.values(e).every((t=>p(t)))||wr({result:{error:Nn},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)=>h(t.structureOrder)-h(e.structureOrder))),{...E}):{error:j}},setSubOrder:function({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:r,subOrder:i,event:a}){if(!e)return{error:j};if(!r)return{error:It};if(!n)return{error:tt};const{structure:o}=ts({drawDefinition:e,structureId:r});if(!o)return{error:Ut};let s=o;o.structures&&o.structureType===mo&&(s=o.structures?.find((t=>t.positionAssignments?.find((t=>t.drawPosition===n)))));const c=s?.positionAssignments,u=c?.find((t=>t.drawPosition===n));u&&Nr({element:u,extension:{name:sa,value:i}});const d=(a?.eventType===Qs||e.matchUpType===Qs||(a?.tieFormat??e?.tieFormat??o?.tieFormat))&&{matchUpTypes:[Qs]},{matchUps:p}=Yp({structure:s,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:d,event:a});return jg({positionAssignments:c,tournamentRecord:t,drawDefinition:e,matchUpFormat:o?.matchUpFormat??e.matchUpFormat,matchUps:p,event:a}),Ls({drawDefinition:e,structureIds:[r]}),{...E}},substituteParticipant:function(t){return function({substituteParticipantId:t,existingParticipantId:e,tournamentRecord:n,drawDefinition:r,sideNumber:i,matchUpId:a,event:o}){const s="substituteParticipant";if(!r)return{error:j};if(!a)return{error:qt};if(!e||!t)return wr({result:{error:Ae},stack:s});const{matchUp:c}=Xm({drawDefinition:r,matchUpId:a,event:o});if(!c)return{error:Wt};if(!c.collectionId)return wr({result:{error:Yt},stack:s});const u=xc({drawDefinition:r}),{matchUps:d}=Jp({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:Te};const f=m.participant?.individualParticipants?.map(Da).filter((t=>t!==e));return f?.includes(t)?jf({newParticipantId:t,tieMatchUpId:a,existingParticipantId:e,substitution:!0,tournamentRecord:n,drawDefinition:r,event:o}):wr({result:{error:Te},stack:s})}(t)},swapDrawPositionAssignments:function(t){return Dh(t)},toggleParticipantCheckInState:_f,updateDrawIdsOrder:bI,updateTeamLineUp:bf,updateTieMatchUpScore:$g,withdrawParticipantAtDrawPosition:function(t){return Object.assign(t,{entryStatus:nu}),ym(t)}};function jS({qualifyingProfiles:t,appliedPolicies:e,idPrefix:n,isMock:r,uuids:i}){const o=[],s=[],c=[],u=(t,e)=>t.stageSequence-e.stageSequence,d=(t,e)=>t.roundTarget-e.roundTarget;let l,m=0,f=0,h=1;for(const g of t.sort(d)){const d=g.structureProfiles||[];h=g.roundTarget||h;let I,U,S,y=1,v=0;for(const o of(d||[]).sort(u)){let u=a(o.drawSize||o.participantsCount);const{qualifyingRoundNumber:f,structureOptions:g,matchUpFormat:w,structureName:T,structureId:P,drawType:D}=o,b=o.matchUpType,N=o.qualifyingPositions||GS({drawSize:u,qualifyingRoundNumber:f});let R,M,A;if(!p(u))return wr({result:{error:it},stack:"generateQualifyingSTructures"});const E=t.length>1?`${h}-`:"",C=d.length>1||E?y:"",O=T||(E||C?`${wm(Qa)} ${E}${C}`:wm(Qa));if(D===Go){const{structures:t,groupCount:a,maxRoundNumber:s}=pf({structureName:o.structureName||O,structureId:P||i?.pop(),stage:Qa,structureOptions:g,appliedPolicies:e,stageSequence:y,matchUpType:b,roundTarget:h,drawSize:u,idPrefix:n,isMock:r,uuids:i});v=a,R=s,M=t[0],l=[1]}else({drawSize:u,matchUps:A,roundLimit:R}=VI({qualifyingRoundNumber:f,qualifyingPositions:N,matchUpType:b,drawSize:u,idPrefix:n,isMock:r,uuids:i})),M=Tm({structureName:o.structureName||O,structureId:P||i?.pop(),qualifyingRoundNumber:R,stage:Qa,matchUpFormat:w,stageSequence:y,matchUpType:b,roundLimit:R,matchUps:A}),h&&Nr({extension:{name:ra,value:h},element:M}),v=A?.filter((t=>t.roundNumber===R))?.length||0;if(y>1){const{link:t}=_I({sourceStructureId:U,sourceRoundNumber:I,targetStructureId:M.structureId,finishingPositions:S===Uo?[1]:void 0,linkType:S});c.push(t),m+=(u||0)-v}else m+=u||0;S=D===Go?Uo:So,U=M.structureId,I=R,s.push(M),y+=1}f+=v,o.push({qualifiersCount:v,finalQualifyingRoundNumber:I,finalQualifyingStructureId:U,finishingPositions:l,roundTarget:h,linkType:S}),h+=1}return{qualifiersCount:f,qualifyingDrawPositionsCount:m,qualifyingDetails:o,structures:s,...E,links:c}}function GS({drawSize:t,qualifyingRoundNumber:e}){let n=t,r=0;for(;r<e;)n=Math.floor(n/2),r+=1;return n}function qS({structureName:t,matchUpType:e,idPrefix:n,drawSize:r,isMock:i,uuids:a}){const o=[],{matchUps:s}=$I({linkFedFinishingRoundNumbers:[1],drawSize:r+1,matchUpType:e,idPrefix:n,isMock:i}),c=Tm({structureName:t||wm(Xa),structureId:a?.pop(),stageSequence:1,stage:Xa,matchUpType:e,matchUps:s});o.push(c);const u=r/2,{matchUps:d}=$I({finishingPositionOffset:u,idPrefix:n&&`${n}-c`,drawSize:r-1,isConsolation:!0,matchUpType:e,isMock:i,uuids:a}),p=Tm({structureName:wm(Wo),matchUps:d,structureId:a?.pop(),stage:to,stageSequence:2,matchUpType:e});o.push(p);const{matchUps:l}=VI({idPrefix:n&&`${n}-p1t2`,drawSize:2,matchUpType:e,isMock:i}),m=Tm({structureName:wm($o),matchUps:l,structureId:a?.pop(),stageSequence:3,stage:no,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?go:Io;return{linkType:yo,source:{roundNumber:1+i,structureId:t.structureId},target:{feedProfile:a,roundNumber:n,structureId:e.structureId}}})),{linkType:So,source:{roundNumber:a,structureId:e.structureId},target:{feedProfile:go,roundNumber:i,structureId:t.structureId}},{linkType:So,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:go,roundNumber:1,structureId:n.structureId}},{linkType:yo,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:go,roundNumber:1,structureId:n.structureId}}]}({mainStructure:c,consolationStructure:p,deciderStructure:m});return{structures:o,links:f,...E}}function $S(t){const{qualifyingRoundNumber:e,finishingPositionOffset:i,qualifyingPositions:a,matchUpType:o,idPrefix:s,drawSize:c,isMock:u,uuids:d}=t;if(!p(c)||c<2)return{matchUps:[],roundsCount:0};if(r(c))return VI(t);const l=function(t){const e=n(t);let r=e%2?e+1:e;const i=!!(Math.ceil(r/2)%2),a=[{participantsCount:r,preFeedRound:i}];for(;r>2;){const t=Math.ceil(r/2),e=1===t,n=!(e||!(t%2));r=!e&&n?t+1:t;const i=!!(2!==r&&Math.ceil(r/2)%2);a.push({participantsCount:r,preFeedRound:i,feedRound:n})}return a}(c),m=l.shift(),f=w(1,(m?.participantsCount||0)+1).map((t=>({drawPosition:t})));let h=[],g=1;({matchUps:h}=BI({roundNumber:g,matchUpType:o,idPrefix:s,matchUps:h,isMock:u,nodes:f,uuids:d})),g++;let I=t.roundLimit||e;for(const t of l){const e=t.participantsCount/2,n=w(1,e+1);a&&e===a&&(I=g-1);const r=n.map((t=>{const e=LI({roundPosition:t,roundNumber:g,idPrefix:s,uuids:d});return{roundPosition:t,roundNumber:g,matchUpId:e}}));h.push(...r),g++}const U=g-1;return h=Xp({finishingPositionOffset:i,lucky:!0,roundsCount:U,roundLimit:I,matchUps:h}),I&&(h=h.filter((t=>t.roundNumber<=I))),{matchUps:h,roundsCount:U,roundLimit:I}}function WS(t){const{playoffAttributes:e,stageSequence:n=1,structureId:r,stage:i=Xa,matchUpType:a,drawSize:o,uuids:s}=t,{appliedPolicies:c}=Dc(t),u=t.policyDefinitions?.[Ei]||c?.[Ei];t.skipRounds=t.skipRounds||o<=4&&(u?.feedMainFinal?0:1)||0;const d=t.structureName??e?.[0]?.name??wm(Xa),p={[wo]:()=>({structures:[Tm({structureId:r||s?.pop(),finishingPosition:Yo,stageSequence:n,structureName:d,matchUps:[],matchUpType:a,stage:i})],links:[],...E}),[Ao]:()=>{const{matchUps:e}=$S(t);return{structures:[Tm({structureId:r||s?.pop(),stageSequence:n,structureName:d,matchUpType:a,matchUps:e,stage:i})],links:[],...E}},[bo]:()=>(()=>{const{matchUps:e}=VI(t);return{structures:[Tm({structureId:r||s?.pop(),stageSequence:n,structureName:d,matchUpType:a,matchUps:e,stage:i})],links:[],...E}})(),[No]:()=>qS(t),[Po]:()=>WI({...t,roundOffsetLimit:3,playoffAttributes:e??Ho}),[Do]:()=>WI({...t,roundOffsetLimit:2,playoffAttributes:e??zo}),[no]:()=>WI(t),[To]:()=>{const{matchUps:t}=$I({drawSize:o,uuids:s,matchUpType:a});return{structures:[Tm({structureId:r||s?.pop(),stageSequence:n,structureName:d,matchUpType:a,stage:Xa,matchUps:t})],links:[],...E}},[Mo]:()=>HI(t),[Ro]:()=>KI({...t,feedRounds:1,fmlc:!0}),[Bo]:()=>KI({...t,feedRounds:1}),[Oo]:()=>KI({...t,feedsFromFinal:1}),[ko]:()=>KI({...t,feedsFromFinal:2}),[_o]:()=>KI({...t,feedsFromFinal:3}),[jo]:()=>KI(t),[Eo]:()=>YI(t),[Go]:()=>pf(t),[qo]:()=>function(t){const{drawDefinition:e,structureOptions:n,requireSequential:r}=t,i={structureName:wm(Xa),...t,stage:Xa},{structures:a,groupCount:o,groupSize:s}=pf(i);if(o<1)return{error:wn};const c=n?.playoffGroups||[{finishingPositions:[1],structureName:wm(no)}],[u]=a,{structures:d,links:p}=JI({sourceStructureId:u.structureId,requireSequential:r,drawDefinition:e,playoffGroups:c,groupCount:o,groupSize:s,...t});return d&&a.push(...d),{...E,structures:a,links:p}}(t)};return{generators:p}}function HS(t){const{enforceMinimumDrawSize:e=!0,overwriteExisting:i,appliedPolicies:a,staggeredEntry:o,drawDefinition:s,tieFormat:c,drawSize:u,isMock:d,uuids:p}=t||{},l=t.drawTypeCoercion??a?.[Ci]?.drawTypeCoercion??!0,m="generateDrawStructuresAndLinks";let f=l&&2===t.drawSize&&bo||t.drawType||bo;const h=[],g=[],I=t?.matchUpType??Ks,U=s?.structures?.filter((({stage:t})=>t===Qa));U&&h.push(...U);const S=U?.map((({structureId:t})=>t)),y=s?.structures?.find((({stage:t,stageSequence:e})=>t===Xa&&1===e)),v=s?.links?.filter((t=>t.target.structureId===y?.structureId&&S?.includes(t.source.structureId))),w=(t,e)=>{if(t.linkType===Uo&&e?.structures){const n=t.source.finishingPositions||[];return e.structures.length*n.length}if(t.linkType===So&&e?.matchUps?.length){const n=t.source.roundNumber;return e.matchUps.filter((({roundNumber:t})=>t===n)).length}},T=U?.map((t=>{const e=v?.find((e=>e.target.structureId===t.structureId)),n=rs({structure:t})?.positionAssignments?.length??0;if(!e)return n;const r=e?.source.structureId,i=s.structures?.find((t=>t.structureId===r));return n-(w(e,i)||0)})).filter(Boolean).reduce(((t,e)=>t+e),0),P=v?.map((t=>{const e=t.source.structureId,n=U?.find((t=>t.structureId===e));return w(t,n)})).filter(Boolean).reduce(((t,e)=>t+e),0),D=!(!y||y?.matchUps?.length);if(U?.length&&!D)return{error:Bn};const b=!U?.length&&t.qualifyingProfiles,N=b?.length&&jS({idPrefix:t.idPrefix,qualifyingProfiles:b,appliedPolicies:a,isMock:d,uuids:p});if(N?.error)return N;const{qualifyingDrawPositionsCount:R,qualifyingDetails:M,qualifiersCount:A}=N||{qualifyingDrawPositionsCount:T,qualifiersCount:P};R&&(N?.structures&&h.push(...N.structures),N?.links&&g.push(...N.links)),Object.assign(t,vr({drawSize:u,matchUpType:I,tieFormat:c}));const C=f!==wo&&(!u||isNaN(u)||u<2||!o&&![To,Ao].includes(f)&&([qo,Go].includes(f)&&u<3||![Go,qo].includes(f)&&!r(u)));if(C&&!R)return wr({context:{drawSize:u,invalidDrawSize:C},result:{error:nt},stack:m});const O=Jo.includes(f);if(u&&n(u)<4&&O)if(l)f=bo;else if(e)return wr({context:{enforceMinimumDrawSize:e,invalidDrawSize:C,drawSize:u,drawType:f},result:{error:nt},stack:m});const{generators:F,error:k}=WS(t);if(k)return{error:k};const x=F[f];if(!x)return{error:J};const _=x?.();if(_.error)return _;const{structures:L,links:B}=_;if(L?.length){const t=L.find((({stage:t,stageSequence:e})=>t===Xa&&1===e));if(y&&t)if(D){const e=t.structureId;if(t.structureId=y.structureId,B?.length)for(const t of B)t.source.structureId===e&&(t.source.structureId=y.structureId),t.target.structureId===e&&(t.target.structureId=y.structureId)}else if(!i)return{error:Bn};h.push(...L)}h.sort(Xo),B?.length&&g.push(...B);const V=_.structures.find((({stage:t,stageSequence:e})=>t===Xa&&1===e));for(const t of M||[]){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&&g.push(o)}return v&&g.push(...v),{...E,qualifyingResult:{qualifyingDrawPositionsCount:R,qualifiersCount:A},structures:h,links:g}}function zS(t){const{modifyOriginal:e=!0,stageSequence:n=1,isMock:r}=t||{},i="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return wr({result:{error:j},stack:i});const a=e?t.drawDefinition:gi(t.drawDefinition,!1,!0);let{tieFormat:o,matchUpType:s}=t;if(o){const t=fh({tieFormat:o});if(t.error)return t}o=Yf(o??$d({drawDefinition:a})?.tieFormat),s=s??(a.matchUpType||Ks),t.tieFormat=o,t.matchUpType=s;const c=tm({drawDefinition:a,stage:Xa});t.drawSize=t.drawSize??c,!c&&t.drawSize&&MI({drawSize:t.drawSize,drawDefinition:a,stageSequence:n,stage:Xa});const u=xc({drawDefinition:a}).drawMatchUps.map(ba),d=HS(t);if(d.error)return wr({result:d,stack:i});const{structures:p,links:l,qualifyingResult:m}=d;a.structures=p,a.links=l;const f=Math.max(t.qualifiersCount??0,m?.qualifiersCount||0);if(m?.qualifyingDrawPositionsCount){if(!tm({stage:Qa,drawDefinition:a})){const t=MI({drawSize:m.qualifyingDrawPositionsCount,stage:Qa,drawDefinition:a});if(t.error)return t}}if(f){const t=AI({qualifiersCount:f,drawDefinition:a,stage:Xa});if(t.error)return t}const h=t.drawSize??c;Object.assign(t,vr({drawSize:h,matchUpType:s,tieFormat:o}));const{matchUps:g,matchUpsMap:I}=Jp({drawDefinition:a});o&&g?.forEach((t=>{if(!u.includes(t.matchUpId)){const{tieMatchUps:e}=hh({tieFormat:o,isMock:r});Object.assign(t,{tieMatchUps:e,matchUpType:s})}}));const{inContextDrawMatchUps:U}=Qp({drawDefinition:a,matchUpsMap:I});return Ls({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:a}),{inContextDrawMatchUps:U,drawDefinition:a,matchUpsMap:I,...E,structures:p,matchUps:g,links:l}}function YS({tournamentRecord:t,categoryName:e,categoryType:n}){if(!t)return{error:_};const{appliedPolicies:r}=Dc({tournamentRecord:t}),i=r?.[Ci];return(i?.allowedDrawTypes||[]).filter((({categoryNames:t,categoryTypes:r})=>!e&&!r||e&&t?.includes(e)||n&&r?.includes(n)))}function KS({consideredEntries:t,policyDefinitions:e,tournamentRecord:n,appliedPolicies:r,participantMap:i,enforceGender:a,participants:o,event:s}){if(o&&i||!n||({participants:o,participantMap:i}=Zl({tournamentRecord:n})),!o)return{error:Me};if(!Array.isArray(o))return{error:Nn};if(!s)return{error:Tt};const c=e?.[wi]??r?.[wi]??sm[wi],u=!1!==(a??c?.participants?.enforceGender),{eventType:d,gender:p}=s,l=d===rd,f=d===ad&&dc||l&&uc||sc,h=Object.assign({},...(t??s.entries??[]).map((t=>({[t.participantId]:t.entryStatus})))),g=Object.keys(h),I=o.filter((t=>g.includes(t.participantId))).filter((t=>{const e=h[t.participantId],n=d&&[rd,ad].includes(d)&&t.participantType===sc&&(_l(e)||e===nu),r=t.participantType!==f&&!n,a=!r&&l&&m(t?.individualParticipantIds?.map((t=>i?.[t]?.participant?.person?.sex)).filter(Boolean)??[]),o=!p||!a?.length||Gp===p||[qp,Hp].includes(p)&&a[0]===p||$p===p&&(1==a.length&&1===t.individualParticipantIds?.length||2===a.length),s=t?.person?.sex,c=!t?.person||!p||[Gp,$p].includes(p)||[qp,Hp].includes(p)&&s===p;return r||!(!u||o&&c)}));if(I.length){const t=I.map((t=>t.participantId));return{error:Nt,invalidParticipantIds:t}}return{...E,valid:!0}}const JS=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});function ZS(t){const e="prepareStage";let{seedsCount:n}=t;const r=t.preparedStructureIds||[],{provisionalPositioning:i,inContextDrawMatchUps:a,tournamentRecord:o,appliedPolicies:s,qualifyingOnly:c,drawDefinition:u,seedingProfile:d,matchUpsMap:l,automated:m,placeByes:f,drawType:h,drawSize:g,entries:I,event:U,enforcePolicyLimits:S=!0,seedAssignmentProfile:y,seedByRanking:v=!0,seededParticipants:T,assignSeedsCount:P,seedingScaleName:D,stageSequence:b=1,roundTarget:N,stage:R}=t,M=U?.eventType,A=I.filter((t=>{const e=Mr({name:ra,element:t})?.extension?.value;return(!t.entryStage||t.entryStage===R)&&(!b||!t.entryStageSequence||t.entryStageSequence===b)&&(!N||!e||e===N)&&au.includes(t.entryStatus)}));T&&(n=T.length),n>g&&(n=g),n>A.length&&(n=A.length);const{structures:C}=es({drawDefinition:u,stageSequence:b,roundTarget:N,stage:R}),O=(C?.length||0)>1,F=C?.find((({structureId:t})=>!r.includes(t)));if(!F)return wr({result:{error:Ut},stack:e});const k=F?.structureId,x=F?gf({provisionalPositioning:i,appliedPolicies:s,drawDefinition:u,seedingProfile:d,structure:F}):void 0,{seedLimit:_}=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=ts({drawDefinition:o,structureId:c});if(d.error)return d;const l=d.structure;if(!l)return{error:Ut};const{positionAssignments:m}=is({structure:l}),f=m?.length||0;if(u>f)return{error:ct};const h=l.structures?.length,g=p(s?.groupSeedingThreshold)&&s?.groupSeedingThreshold,I=ff({roundRobinGroupsCount:h,drawSize:f})?.seedGroups,{seedsCount:U}=BU({policyDefinitions:a,requireParticipantCount:t,drawSizeProgression:n,participantsCount:r,drawSize:f});return U&&a?.[Ai]&&u>U&&e&&(u=U),l.seedLimit=u,l.seedAssignments=w(1,u+1).map((t=>{const e=I?.find((e=>e.includes(t))),n=e&&Math.min(...e);return{participantId:void 0,seedNumber:t,seedValue:g&&t>=g?n:t}})),Ls({drawDefinition:o,structureIds:[c]}),{...E,seedLimit:u}}({participantsCount:A.length,enforcePolicyLimits:S,appliedPolicies:s,drawDefinition:u,seedingProfile:d,structureId:k,seedsCount:n});_&&_<n&&(n=_);const L=I.map(Da);if(T)T.filter((({participantId:t})=>L.includes(t))).filter((t=>!t.seedNumber||t.seedNumber<=T.length)).sort(((t,e)=>t.seedNumber<e.seedNumber?-1:t.seedNumber<e.seedNumber?1:0)).forEach((t=>{const{participantId:e,seedNumber:n,seedValue:r}=t;vf({provisionalPositioning:i,tournamentRecord:o,drawDefinition:u,seedingProfile:d,participantId:e,seedBlockInfo:x,structureId:k,seedNumber:n,seedValue:r,event:U})}));else if(U||D){const{categoryName:t,ageCategoryCode:e}=U?.category||{},r={scaleType:Fr,scaleName:D||t||e||U.eventId,eventType:M};let{scaledEntries:a}=qU({scaleAttributes:r,tournamentRecord:o,stageSequence:b,entries:I,stage:R});if(!a?.length&&v){const n={scaleName:t||e,scaleType:Er,eventType:M};({scaledEntries:a}=qU({scaleAttributes:n,tournamentRecord:o,stageSequence:b,entries:I,stage:R}))}const s=a?.length??0;s<n&&(n=s),a?.filter((({participantId:t})=>L.includes(t))).slice(0,P||n).forEach(((t,e)=>{const n=e+1,{participantId:r,scaleValue:a}=t;vf({provisionalPositioning:i,tournamentRecord:o,drawDefinition:u,seedingProfile:d,participantId:r,structureId:k,seedNumber:n,seedValue:y?.[n]||a||n,event:U})}))}let B,V,j=[];if(!1!==m&&h!==wo&&(!c||R===Qa)){const t="object"==typeof m&&m.seedsOnly,n=Qh({inContextDrawMatchUps:a,multipleStructures:O,tournamentRecord:o,appliedPolicies:s,drawDefinition:u,seedingProfile:d,structureId:k,matchUpsMap:l,placeByes:f,seedLimit:_,seedsOnly:t,drawSize:g,drawType:h,event:U});if(n.conflicts&&(j=n?.conflicts),B=n?.positionAssignments,V=n?.positioningReport,n.error)return wr({result:n,stack:e})}return{positionAssignments:B,positioningReport:V,stageEntries:A,structureId:k,seedsCount:n,conflicts:j}}const XS={[Ai]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[qo]:{positioning:po},[Go]:{positioning:po}},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 QS(t){const e="generateDrawDefinition",{considerEventEntries:r=!0,ignoreAllowedDrawTypes:i,voluntaryConsolation:a,hydrateCollections:o,ignoreStageSpace:s,tournamentRecord:c,qualifyingOnly:d,tieFormatName:l,drawEntries:m,placeByes:f,event:h}=t,g=Dc({tournamentRecord:c,event:h}).appliedPolicies??{},I=gi(t.policyDefinitions??{},!1,!0),U=(t.drawTypeCoercion??I?.[Ci]?.drawTypeCoercion??g?.[Ci]?.drawTypeCoercion??!0)&&2===t.drawSize&&bo||t.drawType||bo,S=I?.[Ai]??g?.[Ai],y=t.seedingProfile??S?.seedingProfile?.drawTypes?.[U]??S?.seedingProfile;t.seedingProfile&&(I[Ai]||(I[Ai]={...XS[Ai]}),I[Ai].seedingProfile=y);const{participants:v,participantMap:T}=Zl({withIndividualParticipants:!0,convertExtensions:!0,internalUse:!0,tournamentRecord:c}),P=t.enforceGender??I?.[wi]?.participants?.enforceGender??g?.[wi]?.participants?.enforceGender,D=!i&&c&&YS({tournamentRecord:c,categoryType:h?.category?.categoryType,categoryName:h?.category?.categoryName});if(D?.length&&!D.includes(U))return wr({result:{error:et},stack:e});const b=h?.entries?.filter((t=>t.entryStatus&&[...ou,Zc].includes(t.entryStatus)))??[],N=(d&&[]||m||(r?b:[])).filter((({entryStage:t})=>!t||t===Xa)),R=h&&v&&KS({consideredEntries:N,appliedPolicies:g,participantMap:T,enforceGender:P,participants:v,event:h});if(R?.error)return wr({result:R,stack:e});const M=!t.drawSize&&N.length&&![wo,No,To,Go,qo].includes(U)&&u(N.length)||t.drawSize&&p(t.drawSize)&&n(t.drawSize)||!1;if(isNaN(M)&&U!==wo)return wr({result:{error:it},stack:e});let A="number"!=typeof t.seedsCount?n(t.seedsCount??0):t.seedsCount??0;const C=h?.eventType,O=t.matchUpType??C,F=t.drawId?h?.drawDefinitions?.find((e=>e.drawId===t.drawId)):void 0;let{tieFormat:k,matchUpFormat:x}=t;if(O===Qs&&C===Qs){const t=F?.structures?.find((({stage:t})=>t===Xa))?.tieFormat;k=k||t||l&&h?.tieFormat?.tieFormatName===l&&h.tieFormat||l&&ES({namedFormat:l,hydrateCollections:o,event:h})||h?.tieFormat||ES({event:h,hydrateCollections:o}),x=void 0}else x||(k=void 0,h?.matchUpFormat||(x=lg));if(k){const t=fh({gender:h?.gender,enforceGender:P,tieFormat:k});if(t.error)return wr({result:t,stack:e})}if(t.drawId&&"string"!=typeof t.drawId)return wr({result:{error:Nn},stack:e});F&&U!==F.drawType&&(F.drawType=U);let _=F??function(t){const{drawId:e=Md(),processCodes:n,matchUpType:r,drawType:i}=t??{},a=JS();return Object.assign(a,{processCodes:n,matchUpType:r,drawType:i,drawId:e})}({drawType:U,drawId:t.drawId,processCodes:t.processCodes});if(x||k){if(!(x&&h?.matchUpFormat===x||h?.tieFormat&&k&&JSON.stringify(h.tieFormat)===JSON.stringify(k))){if(k){const t=function({tieFormat:t}){const e=fh({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(const e of t.collectionDefinitions)e.collectionId||(e.collectionId=Md());return{tieFormat:t}}({tieFormat:k});if(t.error)return wr({result:t,stack:e});_.tieFormat=t.tieFormat??k}else if(x){const t=GI({tournamentRecord:c,drawDefinition:_,matchUpFormat:x,event:h});if(t.error)return{error:t.error,info:"matchUpFormat or tieFormat error"}}O&&(_.matchUpType=O)}}const L={[Ri]:g[Ri]};if(I){if("object"!=typeof I)return wr({info:"policyDefinitions must be an object",result:{error:Nn},stack:e});for(const t of Object.keys(I))JSON.stringify(g?.[t])!==JSON.stringify(I[t])&&(L[t]=I[t]);Object.keys(L).length&&(uU({policyDefinitions:L,drawDefinition:_}),Object.assign(g,L))}else L.avoidance&&uU({drawDefinition:_,policyDefinitions:L});g[Ai]||I[Ai]||(uU({policyDefinitions:XS,drawDefinition:_}),Object.assign(g,XS));let B=F?.structures?.find((t=>t.stage===Xa&&1===t.stageSequence))?.structureId;const V=m??b,j=[];let G,q=[];const $=t.qualifyingPlaceholder&&!t.qualifyingProfiles?.length&&!F,W=F?F.structures?.filter((t=>t.stage===Qa)):[],H=1===W?.length&&!W[0].matchUps?.length&&W[0].structureId;if(H){const e=t.qualifyingProfiles,n=e?.length?jS({idPrefix:t.idPrefix,isMock:t.isMock,uuids:t.uuids,qualifyingProfiles:e,appliedPolicies:g}):void 0;if(n?.error)return n;_.structures=_.structures?.filter((({structureId:t})=>t!==H)),_.links=_.links?.filter((({source:t})=>t.structureId!==H));const{qualifiersCount:r,qualifyingDrawPositionsCount:i,qualifyingDetails:a}=n??{};i&&(n?.structures&&_.structures?.push(...n.structures),n?.links&&_.links?.push(...n.links));const o=_.structures?.find((({stage:t,stageSequence:e})=>t===Xa&&1===e)),{qualifiersCount:s}=Ql({stageSequence:1,drawDefinition:_,structureId:B,stage:Xa});let c=AI({qualifiersCount:Math.max(r??0,s??0),drawDefinition:_,stage:Xa});if(c.error)return c;if(c=MI({drawSize:i,stage:Qa,drawDefinition:_}),c.error)return c;for(const t of(m??[]).filter((({entryStage:t})=>t===Qa))){rm({...t,entryStage:t.entryStage??Xa,drawDefinition:_})}for(const t of a||[]){const{finalQualifyingRoundNumber:e,finalQualifyingStructureId:n,roundTarget:r,finishingPositions:i,linkType:a}=t,s=o&&_I({targetStructureId:o.structureId,sourceStructureId:n,sourceRoundNumber:e,finishingPositions:i,targetEntryRound:r,linkType:a})?.link;if(s?.error)return s;s&&(_.links||(_.links=[]),_.links.push(s))}G={drawDefinition:_}}else{if(G=zS({...t,modifyOriginal:!1,tournamentRecord:c,appliedPolicies:g,drawDefinition:_,matchUpFormat:x,matchUpType:O,tieFormat:k,drawSize:M}),G.error)return wr({result:G,stack:e});_=G.drawDefinition;for(const t of V){if(m&&t.entryStage&&t.entryStage!==Xa)continue;const n=rm({...t,ignoreStageSpace:s??U===wo,entryStage:t.entryStage??Xa,drawDefinition:_,drawType:U});if(m&&n.error)return wr({result:n,stack:e})}U===Ao&&(A=0);const n=ZS({...G,...t,qualifyingOnly:!M||d,appliedPolicies:g,drawDefinition:_,seedingProfile:y,participants:v,stage:Xa,seedsCount:A,placeByes:f,drawSize:M,entries:V});if(n.error&&!n.conflicts)return n;if(n.positioningReport?.length&&j.push({[Xa]:n.positioningReport}),B=n.structureId,n.conflicts&&(q=n.conflicts),U===wo&&t.roundsCount){const e=h?.entries?.filter((({entryStage:t,entryStatus:e})=>(!t||t===Xa)&&e&&ou.includes(e))),n=e?.map(Ua("participantId")),r=e?Math.floor(e.length/2):0;w(1,t.roundsCount+1).forEach((()=>{if(t.automated){const{restrictEntryStatus:e,generateMatchUps:r,structureId:i,matchUpIds:a,scaleName:o}=t.drawMatic??{},s=xU({eventType:t.drawMatic?.eventType??O,generateMatchUps:r??!0,restrictEntryStatus:e,tournamentRecord:c,participantIds:n,drawDefinition:_,structureId:i,matchUpIds:a,scaleName:o}).matchUps;fU({tournamentRecord:c,drawDefinition:_,structureId:i,matchUps:s})}else{const{matchUps:t}=yU({newRound:!0,drawDefinition:_,matchUpsCount:r});fU({tournamentRecord:c,drawDefinition:_,structureId:B,matchUps:t})}}))}}const z=[];if(t.qualifyingProfiles){const n=(t,e)=>t.stageSequence-e.stageSequence,r=(t,e)=>t.roundTarget-e.roundTarget,i=[];let a=1;t.qualifyingProfiles.sort(r);for(const r of t.qualifyingProfiles){if(!Array.isArray(r.structureProfiles))return wr({info:Pf("structureProfiles"),result:{error:ae},stack:e});a=r.roundTarget||a;const o=r.structureProfiles?.sort(n)||[];let s=1;for(const e of o){const{qualifyingRoundNumber:n,qualifyingPositions:r,seededParticipants:o,seedingScaleName:c,seedsCount:u=0,seedByRanking:p,placeByes:l,drawSize:m}=e,f=ZS({...G,...t,seedingProfile:e.seedingProfile??y,stageSequence:s,qualifyingRoundNumber:n,preparedStructureIds:i,qualifyingPositions:r,seededParticipants:o,stage:Qa,seedingScaleName:c,appliedPolicies:g,drawDefinition:_,qualifyingOnly:d,seedByRanking:p,participants:v,roundTarget:a,seedsCount:u,placeByes:l,drawSize:m,entries:V});if(f.error)return f;f.structureId&&i.push(f.structureId),s+=1,f.conflicts?.length&&z.push(...f.conflicts),f.positioningReport?.length&&j.push({[Qa]:f.positioningReport})}a+=1}}else if(B&&$){const t=Tm({structureName:wm(Qa),stage:Qa}),{link:e}=_I({sourceStructureId:t.structureId,targetStructureId:B,sourceRoundNumber:0,linkType:Uo});_.structures||(_.structures=[]),_.structures.push(t),_.links||(_.links=[]),_.links.push(e)}return _.drawName=t.drawName??(U&&wm(U)),"object"==typeof a&&M>=4&&Pm({...a,drawDefinition:_,matchUpType:O}),{existingDrawDefinition:!!F,qualifyingConflicts:z,positioningReports:j,drawDefinition:_,structureId:B,...E,conflicts:q}}const ty="splitWaterfall",ey="splitShuttle",ny={SPLIT_LEVEL_BASED:"splitLevelBased",SPLIT_WATERFALL:ty,SPLIT_SHUTTLE:ey};const ry="ASC",iy="DESC",ay={ASC:"ASC",ASCENDING:ry,DESC:"DESC",DESCENDING:iy};function oy(t){let{tieFormat:e}=t;const{useDefaultEventRanking:n,tournamentRecord:r,drawDefinition:i,scaleAccessor:a,singlesOnly:o,attach:c,event:u}=t;if(u?.eventType!==ad)return{error:wt};if(!r)return{error:_};if(!e&&!i)return{error:q};if(e=e??$d({drawDefinition:i,event:u})?.tieFormat,fh({tieFormat:e}).error)return{error:Lt};if("object"!=typeof a&&!n)return{error:Nn,context:{scaleAccessor:a}};const d={},p=(i?.entries??u?.entries??[]).filter((t=>t?.entryStatus===Hc)).map(Da),{participants:l=[]}=Zl({withIndividualParticipants:!0,withScaleValues:!0,tournamentRecord:r}),m=l.filter((({participantId:t})=>p.includes(t))),f=u?.category?.categoryName??u?.category?.ageCategoryCode,{scaleName:h=f,scaleType:g=Er,sortOrder:I,accessor:U}=a||{},S=g===Er?"rankings":"ratings";const y=(t,e)=>{let r=t[S]?.[e];if(!r&&n&&(r=t[S]?.[Ys]),Array.isArray(r)){const t=r.find((t=>t.scaleName===h))?.scaleValue;if(s(t))return t;if(U&&"object"==typeof t)return t[U]}return 0},v=(t,e,n)=>{const r=I===iy?t:e;return y(I===iy?e:t,n)-y(r,n)},T=(t,e)=>v(t,e,Ys),P=(t,e)=>v(t,e,Js),D=[],b=e?.collectionDefinitions??[];for(const t of m){const e=t.individualParticipants?.sort(T)??[],n=o?e:t.individualParticipants?.sort(P)??[],r={};for(const t of b){const i=[],{collectionId:a,matchUpCount:o,matchUpType:s,gender:c}=t,u=s===Ys;w(0,o).forEach((t=>{const o=u?e:n??[],s=t+1,d=[];w(0,u?1:2).forEach((t=>{const e=o?.find((e=>{const n=c&&([qp,Hp].includes(c)&&c||c===$p&&[qp,Hp][t]);return!(n&&n!==e.person?.sex||i.includes(e.participantId))}))?.participantId;e&&(d.push(e),i.push(e),r[e]||(r[e]=[]),r[e].push({collectionPosition:s,collectionId:a}))})),u||D.push(d)}))}const i=Object.keys(r).map((t=>({collectionAssignments:r[t],participantId:t})));d[t.participantId]=i}const N=[];for(const t of D){const{participant:e}=Vc({tournamentParticipants:l,participantIds:t});if(!e){const e={individualParticipantIds:t,participantRole:um,participantType:uc};N.push(e)}}if(c){for(;N.length;)Bf({participant:N.pop(),tournamentRecord:r});Nr({element:i,extension:{name:Zi,value:d}})}return{...E,lineUps:d,participantsToAdd:N}}function sy({court:t,date:e}){const n=e&&t.dateAvailability.find((t=>fi(t.date,e))),r=t.dateAvailability.find((t=>!t.date));return n||r}function cy({includeBookingTypes:t=[],courtDate:e}){const n=[];let r=ui(e.startTime);(e.bookings||[]).filter((e=>!e.bookingType||!t.includes(e.bookingType))).sort(((t,e)=>ei(t.startTime).localeCompare(ei(e.startTime)))).forEach((t=>{const e={startTime:ni(r.toISOString()),endTime:t.startTime};ui(t.startTime)>r&&n.push(e),ui(t.endTime)>r&&(r=ui(t.endTime))}));const i={startTime:ni(r.toISOString()),endTime:e.endTime};return ui(e.endTime)>r&&n.push(i),n}function uy(t){const{averageMatchUpMinutes:e,includeBookingTypes:n,periodStart:r,date:i}=t,a=t.courts,o=ui(r),s=li(o,e),{enoughTime:c}=function({averageMatchUpMinutes:t,includeBookingTypes:e,periodStartTime:n,periodEndTime:r}){function i(e){const i=ui(e.startTime),a=ui(e.endTime);return!(i>n)&&(!(a<r)&&di(n,a)>=t)}return{enoughTime:t=>!!cy({includeBookingTypes:e,courtDate:t}).filter(i).length}}({averageMatchUpMinutes:e,includeBookingTypes:n,periodStartTime:o,periodEndTime:s});return{availableToScheduleCount:(a?.filter((t=>{if(!Array.isArray(t.dateAvailability))return!1;const e=sy({date:i,court:t});return!(!e||!c(e))}))||[]).length}}function dy(t){const{startTime:e="8:00",endTime:n="20:30",count:r=10,date:i}=t??{};return w(0,r).map((()=>({dateAvailability:[{date:i,startTime:e,endTime:n}]})))}function py(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:Nn,courts:a};if(!Array.isArray(o))return{error:ce};if(!Wr(i))return{error:pe};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=sy({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]},...gi(u,!1,!0),...o].filter(Boolean),startTime:d,endTime:p,date:l}}}));c.sort(((t,e)=>ti(t.startTime)-ti(e.startTime)));const d=[];for(const t of c){const{startTime:e,endTime:n,averageMinutes:i,recoveryMinutes:a,matchUpId:o}=t,s=ti(e),c=ti(n),p=u.map((t=>{const e=cy({courtDate:t.dateAvailability});return{courtName:t.courtName,courtId:t.courtId,timeSlots:e}})).flat().reduce(((t,{courtId:e,courtName:n,timeSlots:i})=>{let a;return i.find((({startTime:e,endTime:n})=>{a=ti(e)-s;const i=s>=ti(e);return c<=ti(n)&&0!==t.startDifference&&((0===a||a+r>=0)&&(void 0===t.startDifference||a<t.startDifference)||i)}))?{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 ly({averageMatchUpMinutes:t,periodLength:e=30,recoveryMinutes:n}){const r=(t||90)+(n||0);return e>r?r:e||30}function my({scheduleDate:t,startTime:e,endTime:n,courts:r}){const i=(e?"startTime":n&&"endTime")||void 0;return r.reduce(((r,a)=>{const o=sy({date:t,court:a}),s=i&&(o?.[i]||a[i]);return s&&(!r||e&&ti(s)<ti(r)||n&&ti(s)>ti(r))?s:r}),void 0)}function fy(t){let{date:e=Hr(),startTime:r="08:00",endTime:i="19:00",periodLength:a,courts:o}=t;const{calculateStartTimeFromCourts:s=!0,remainingScheduleTimes:c,averageMatchUpMinutes:u,clearScheduleDates:d,courtsCount:p,bookings:l}=t;a=a||ly({averageMatchUpMinutes:u}),e=ri(e),r=ni(r),i=ni(i);let m=0,f=0,h=0,g=0,I=0;!o&&p&&(o=dy({startTime:r,endTime:i,count:p,date:e}));const{virtualCourts:U}=py({remainingScheduleTimes:c,clearScheduleDates:d,scheduleDate:e,periodLength:a,bookings:l,courts:o}),{firstTimeSlotStartTime:S}=function({averageMinutes:t,startTime:e,endTime:n,courts:r,date:i}){let a;if(e=e||my({courts:r,scheduleDate:i,startTime:!0}),n=n||my({courts:r,scheduleDate:i,endTime:!0}),e&&n){const o=ui(e),s=ui(n);for(const e of r||[])Array.isArray(e.dateAvailability)&&cy({courtDate:sy({court:e,date:i})}).forEach((e=>{const n=ui(e.startTime),r=ui(e.endTime);if(n>s||n<o)return!1;if(r<o)return!1;if(di(n,r)>=t){const t=ni(n.toISOString());(!a||t<a)&&(a=t)}}))}return{firstTimeSlotStartTime:a}}({averageMinutes:u,courts:U,startTime:r,endTime:i,date:e});s&&S&&(r=S||r);const y=ti(r),v=ti(i)-y,T=w(0,Math.floor(v/a)+1).map((t=>{const r=function(t){let e=Math.floor(t/60);const n=t-60*e;return e>23&&(e%=24),[mi(e),mi(n)].join(":")}(y+t*a),{availableToScheduleCount:i}=uy({courts:U||[],averageMatchUpMinutes:u,periodStart:r,date:e}),o=i>f?i-f:0;I+=t?i:0;const s=t?I/t:i,c=t?a*s/u*(t-1)+s:s,d=i?f&&c-m||o:0;m=c,f=i,h+=d;const p=n(h)-g;return g+=p,{periodStart:r,add:p,availableToScheduleCount:i,newCourts:o,totalMatchUps:g}}));return{scheduleTimes:T.reduce(((t,e)=>{const n=w(0,e.add).map((()=>({scheduleTime:e.periodStart})));return t.concat(...n)}),[]).flat(),timingProfile:T,totalMatchUps:g}}const hy={garman:{getCourtsAvailableAtPeriodStart:uy,generateTimeSlots:cy,getScheduleTimes:fy,courtGenerator:dy},generateAdHocMatchUps:yU,generateAndPopulatePlayoffStructures:XI,generateDrawDefinition:QS,generateDrawMaticRound:kU,generateDrawStructuresAndLinks:HS,generateDrawTypeAndModifyDrawDefinition:zS,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:Tt};const h=l.entries??[],{flightProfile:g}=Bd({event:l});if(g&&n&&!o)return{error:xn};const I=t.scaledEntries??qU({tournamentRecord:r,scaleAttributes:i,scaleSortMethod:a,sortDescending:s,event:l,stage:m}).scaledEntries,U=I.map(Da),S=f(h.filter((({participantId:t})=>!U.includes(t))).filter((t=>(!m||!t.entryStage||t.entryStage===m)&&(!t.entryStatus||au.includes(t.entryStatus))))),y=I.concat(...S),v=y.length;let T=N(y,Math.ceil(v/u));d===ty?T=A(y,u):d===ey&&(T=A(y,u,!0));const P={scaleAttributes:i,splitMethod:d,flights:w(0,u).map((t=>{const n=t+1;return{flightNumber:n,drawId:p?.pop()??Md(),drawEntries:(r=T[t],(r||[]).map((({participantId:t,scaleValue:e})=>{const n=h.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}))};if(n){const t=IU({flightProfile:P,deleteExisting:o,event:l});return{splitEntries:Qn()&&T||void 0,...t}}return{flightProfile:P,...E}},generateLineUps:oy,generateQualifyingStructure:jI,generateSeedingScaleItems:jU,generateVoluntaryConsolation:function(t){const{drawType:e=bo,attachConsolation:n=!0,applyPositioning:r=!0,tournamentRecord:i,staggeredEntry:a,automated:o,placeByes:s,isMock:c,event:d}=t;let p=t?.drawDefinition;if(!p)return{error:j};const l=eo,m=pu({stageSequence:1,drawDefinition:p,stage:l}),f=[Go,No,qo].includes(e)?m.length:u(m.length);if(!a&&e===To&&m.length<2||e===Go&&m.length<3)return{error:nt};let{tieFormat:h,matchUpType:g}=t;if(h){const t=fh({tieFormat:h});if(t.error)return t}h=Yf(h??$d({drawDefinition:p})?.tieFormat),g=g??p.matchUpType??Ks;const{structures:I}=es({stageSequence:1,drawDefinition:p,stage:l});if(I.length>1)return{error:Et};if(I?.[0]?.matchUps?.length)return{error:Vn};const U=I?.[0]?.structureId;Object.assign(t,vr({structureName:t.structureName??wm(eo),structureId:U,matchUpType:g,tieFormat:h,drawSize:f,stage:l}));const S=WS(t);if(S.error)return S;const y=S.generators[e];if(!y)return{error:J};const v=y?.();if(v.error)return v;const{structures:w,links:T}=v,P=w.map((t=>Yp({structure:t}).matchUps)).flat();h&&P.forEach((t=>{const{tieMatchUps:e}=hh({tieFormat:h,isMock:c});Object.assign(t,{tieMatchUps:e,matchUpType:g})})),r&&n||(p=gi(p,!1,!0)),p.links||(p.links=[]),T.length&&p.links.push(...T);const D=w.map((({structureId:t})=>t));p.structures||(p.structures=[]);const b=p.structures.map((({structureId:t})=>t));p.structures=p.structures.map((t=>D.includes(t.structureId)?w.find((({structureId:e})=>e===t.structureId)):t));const N=w.filter((({structureId:t})=>!b.includes(t)));return N.length&&p.structures.push(...N),o&&Qh({seedingProfile:t.seedingProfile,applyPositioning:r,tournamentRecord:i,drawDefinition:p,structureId:U,placeByes:s,drawSize:f,event:d}),n&&Ls({drawDefinition:p}),{links:T,structures:w,...E}}};var gy=[{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"}],Iy=["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 Uy({count:t=1,participantsCount:e=32}={}){const n=f(Iy),r=n.slice(0,t);return{cities:w(0,e).map((e=>e<Math.min(t,n.length)?r[e]:v(r)))}}function Sy({count:t=1,participantsCount:e=32}={}){const n=f(gy),r=n.slice(0,t).map((t=>Object.keys(t))).flat();return{states:w(0,e).map((e=>e<Math.min(t,n.length)?r[e]:v(r)))}}function yy({count:t=1,participantsCount:e=32}={}){const n=w(0,t).map((()=>w(0,5).map((()=>d(0,9))).join("")));return{postalCodes:w(0,e).map((e=>e<t?n[e]:v(n)))}}var vy={lastNames:["Abbey","Assange","Ahern","Ampleforth","Atreides","Austen","Bach","Banks","Barrington","Batty","Bauers","Beals","Beer","Bennett","Berry","Bonaparte","Brockovich","Bukowski","Cassidy","Catton","Calvino","Carson","Chip","Constant","Crane","Crowne","Cummings","Curie","Dallas","Diamond","Deckard","Drazic","Dunbar","Earhart","Eisenstein","Eldritch","Elliot","Escher","Eyre","Faulkner","Fukuoka","Godel","Goldstein","Greer","Hedges","Herbert","Holmgren","Humperdinck","Huxley","Illich","Jeffers","Jensen","Jevons","Johnson","Johnstone","Jovovich","Kingsnorth","Langer","Fernwright","Fuller","Le Guin","Lem","Lovelace","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","Wormwood"],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","Bill","Bruce","Charles","Chris","Darwin","David","Derrick","Edward","Emmanuel","Ernst","Estlin","Fezzik","Filby","Frank","Frito","George","Glen","Helmholtz","Inigo","Italo","Ivan","James","Jared","Joe","Johann","Julian","John Michael","Jonathan","Korben","Kirkpatrick","Kurt","Lief","Malachi","Mark","Masanobu","Maurits","Michael","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 wy(t){const{count:e=100,sex:n}=t||{};if(!e||n&&![qp,Hp].includes(n))return{personData:[],error:Nn};const r=Math.ceil(1.3*e),{lastNames:i,firstFemale:a,firstMale:o}=vy,s=el.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=w(0,c).flatMap((()=>{const t=gi(i,!1,!0);return w(0,i.length).map((()=>y(t)))})),l=w(0,u).flatMap((()=>{const t=gi(a,!1,!0);return w(0,a.length).map((()=>y(t)))})),m=w(0,d).flatMap((()=>{const t=gi(o,!1,!0);return w(0,o.length).map((()=>y(t)))})),f={};for(let t=0;t<r;t++){const t=p.pop(),e=n||v([qp,Hp]),r=e===qp?m.pop():l.pop(),i=v(s);f[`${r}${t}`]={nationalityCode:i,sex:e,firstName:r,lastName:t}}return{personData:Object.values(f).slice(0,e)}}function Ty(t){let e=t?.count||1;const{personExtensions:r,consideredDate:i,isMock:a=!0,gendersCount:o,personData:s,category:c,sex:u}=t||{};if(isNaN(e))return{error:Nn};const d=o?.[qp]||u===qp&&e||0,p=o?.[Hp]||u===Hp&&e||0;e=Math.max(e,d+p);const l=e-(d+p),m=[...d&&wy({count:d,sex:qp}).personData||[],...p&&wy({count:p,sex:Hp}).personData||[],...l&&wy({count:l}).personData||[]];let h=m.filter((t=>!u||d&&p||t.sex===u));const g=[];if(Array.isArray(s)){const t=s.filter((t=>"string"==typeof t.firstName&&("string"==typeof t.lastName&&(!(t.sex&&![qp,Hp].includes(t.sex))&&(!(t.nationalityCode&&("string"!=typeof t.nationalityCode||t.nationalityCode.length>3||!el.find((({iso:e,ioc:n})=>[e,n].includes(t.nationalityCode)))))&&(t.nationalityCode&&g.push(t.nationalityCode),!0))))));if(!t.length)return{error:Nn};h=t}const I=s?h:f(h);if(I.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===qp?(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:[]});w(0,e-I.length).forEach((()=>{const e=u||v([qp,Hp]),o=v(a),s={firstName:v(e===qp?t:r),lastName:v(e===qp?n:i),sex:e,nationalityCode:o};I.push(s)}))}const{ageMinDate:U,ageMaxDate:S}=uh({consideredDate:i,category:c}),T=n(U?.slice(0,4)||0)||n(S?.slice(0,4)||0)-3,P=n(S?.slice(0,4)||0)||n(U?.slice(0,4)||0)+3,D=(U||S)&&[T,P],b=I.slice(0,e).map(((t,e)=>{const[n,i]=D||[],o=D&&y(w(n,i)),s=y(w(0,365)),c=o&&function(t,e,n){const r=new Date(t,0);return zr(new Date(r.setDate(e)),n)}(o,s);return Object.assign(vr({extensions:r||[{name:"regionCode",value:e+1}],birthDate:c,isMock:a}),t)}));return{persons:b.length&&b||I[0],nationalityCodes:g}}function Py(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 Dy=["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","Sparkle Soul Tribe","Stacked Deck","Cross Stringers","The Emergence","Total Demolition","Touch and Go","Upside Downers","Vertically Challenged","Visual Spectacle"];function by({nameRoot:t="TEAM",count:e=1}={}){const n=f(Dy).slice(0,e);return n.length<e&&w(0,e-n.length).forEach((e=>n.push(`${t} ${e+1}`))),{names:n}}const Ny=t=>{const{isSide1:e,lowValue:r,setTo:i,tiebreakAt:a,NoAD:o}=t;if(void 0===r)return!1;let s,c=n(r);c?.toString().length>2&&(c=parseInt(c.toString().slice(0,2))),a&&a<i&&c>a&&(c=a),s=o&&!a?c<i?i:i-1:c+1<i&&i||a&&a<i&&c===a&&i||!a&&c+2||i+1;return[e?c:s,e?s:c]},Ry=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 My({tiebreakTo:t=7,scoreString:e}){return e.split(" ").filter(Boolean).map(((e,n)=>function({set:e,setNumber:n}){const r=e?.startsWith("[")&&e.split("[")[1].split("]")[0].split("-").map((t=>parseInt(t))),i=e.includes("(")&&e.split("(")[0]||e.includes("[")&&e.split("[")[0]||e,a=!r&&i.split("-").map((t=>parseInt(t))),o=r?(r[0]>r[1]?1:r[0]<r[1]&&2)||void 0:(a[0]>a[1]?1:a[0]<a[1]&&2)||void 0,s=e.includes("(")?e.split("(")[1].split(")")[0]:void 0,c=(s&&Ry({lowValue:s,isSide1:2===o,tiebreakTo:t}))??[],[u,d]=a||[],[p,l]=r||c||[];return{side1Score:u,side2Score:d,side1TiebreakScore:p,side2TiebreakScore:l,winningSide:o,setNumber:n}}({set:e,setNumber:n+1})))}function Ay(t){const{matchUpFormat:e,matchUpStatus:n,winningSide:r,scoreString:i}=t;if(!i)return{outcome:{...Lg,winningSide:r,matchUpStatus:n}};if(r&&![1,2,void 0].includes(r))return{error:Nn,winningSide:r};const a=i&&My({scoreString:i}),o={},s=nU({sets:a,matchUpFormat:e}),c=nU({sets:a,reversed:!0,matchUpFormat:e});return 2===r?(o.scoreStringSide1=c,o.scoreStringSide2=s):(o.scoreStringSide1=s,o.scoreStringSide2=c),o.sets=My({scoreString:o.scoreStringSide1}),vr({outcome:{matchUpStatus:n,winningSide:r,score:o}})}function Ey({tournamentRecords:t,tournamentId:e}){if("object"!=typeof t||!Object.keys(t).length)return{error:x};let n;return Object.keys(t).filter((t=>!e||t===e)).forEach((e=>{const r=t[e],{matchUpDailyLimits:i}=function(t){const e=Lp(t,[{[up]:!0}]);if(e.error)return e;const{tournamentRecord:n}=t,{policy:r}=Uu({policyType:Ni,tournamentRecord:n}),{extension:i}=Mr({element:n,name:ia}),a=i?.value?.dailyLimits,o=r?.defaultDailyLimits;return{matchUpDailyLimits:a||o}}({tournamentRecord:r});n=i})),{matchUpDailyLimits:n}}function Cy({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 Oy({tournamentRecords:t,tournamentRecord:e,tournamentId:n,drawId:r}){if(!e&&!t)return{error:_};if(!r)return{error:at};if(!e&&t){if("string"!=typeof n&&!(n=Vg({tournamentRecords:t,drawId:r})))return{error:B};if(!(e=t[n]))return{error:_}}const i=e&&Vd({tournamentRecord:e,drawId:r});return i?.drawDefinition?{drawDefinition:i.drawDefinition,event:i.event,tournamentRecord:e,...E}:wr({result:{error:q},stack:"findDrawDefinition"})}function Fy({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:e,timeAfterRecovery:n,matchUp:r}){const{individualParticipantIds:i}=ec(r);n=n??r.schedule?.timeAfterRecovery;const a=e=>{t[e]||(t[e]=[]),t[e]=m(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 ky({individualParticipantProfiles:t,participantId:e}){t[e]||(t[e]={typeChangeTimeAfterRecovery:void 0,timeAfterRecovery:void 0,priorMatchUpType:void 0,potentialRecovery:{},potentialCounted:{},potentialBookings:{},bookings:[],counters:{}})}function xy({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,typeChangeRecoveryMinutes:r,averageMatchUpMinutes:i=0,matchUpNotBeforeTimes:a,matchUpDependencies:o,recoveryMinutes:s=0,scheduleTime:c,matchUp:u}){const d=ni(u?.schedule?.endTime),p=d?pi(d,n(s)):pi(c,n(i)+n(s)),l=r&&(d?pi(ni(d),r):pi(c,n(i)+n(r))),m=o?.[u.matchUpId]?.participantIds||[],f=(u.roundPosition&&t[u.matchUpId]||[]).flat();m.forEach((t=>{ky({individualParticipantProfiles:e,participantId:t});const n=e[t].priorMatchUpType!==u.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:u.drawId,recoveryValue:n,participantId:t,scheduleTime:c}):(e[t].timeAfterRecovery=n,e[t].bookings.push({scheduleTime:c,timeAfterRecovery:n}))})),Fy({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:a,timeAfterRecovery:p,matchUp:u})}function _y({matchUpScheduleTimes:t,matchUpDependencies:e,scheduleTime:n,matchUpId:r,details:i}){let a;const o=i.minutesMap?.[r]?.recoveryMinutes,s=i.minutesMap?.[r]?.averageMinutes,c=pi(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||ti(r)<ti(e.scheduleTime)?i:e}),{});e.scheduleTime&&ti(c)>ti(e.scheduleTime)&&(a=e)}return{scheduledDependent:a}}const Ly="DO_NOT_SCHEDULE",By={DO_NOT_SCHEDULE:Ly};function Vy({averageMatchUpMinutes:t=90,requestConflicts:e={},potentials:n=!0,personRequests:r,scheduleTime:i,scheduleDate:a,matchUp:o}){const s=function(t){const{sides:e,matchUpType:n}=t||{};return(e||[]).map((t=>n===Zs&&(t?.participant?.individualParticipants||[])||t?.participant&&[t.participant]||[])).flat()}(o).map((({person:t})=>t?.personId));if(n){const t=(o?.potentialParticipants||[]).flat().map((({person:t})=>t?.personId));s.push(...t)}const c=s.map((t=>r[t]?.map((e=>({...e,personId:t}))))).filter(Boolean).flat().filter((t=>t.requestType===Ly&&fi(a,t.date))),u=[],d=o?.matchUpId,p=ui(ni(i),ri(a)),l=ni(li(p,t).toISOString());for(const t of c){const{requestId:n,startTime:r,endTime:a}=t;(i>r&&i<a||l>r&&l<a)&&(u.push({matchUpId:d,request:t,scheduleTime:i}),e[n]?(e[n].scheduleTimes.includes(i)||e[n].scheduleTimes.push(i),e[n].matchUpIds.includes(d)||e[n].matchUpIds.push(d)):e[n]={request:t,scheduleTimes:[i],matchUpIds:[d]})}return{conflicts:u}}function jy({defaultRecoveryMinutes:t=0,defaultAverageMinutes:e,tournamentRecords:n,matchUpFormat:r,categoryName:i,categoryType:a,tournamentId:o,eventType:s,eventId:c}){if(!rh(r))return{error:kt};let u;return Object.keys(n).filter((t=>!o||t===o)).forEach((t=>{if(u)return;const e=n[t],o=c?Vd({tournamentRecord:e,eventId:c})?.event:void 0;return u=Sd({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 Gy({scheduleCompletedMatchUps:t,containedStructureIds:e,tournamentRecords:n,periodLength:i=30,matchUps:a,rounds:o}){if("object"!=typeof n)return{error:x};if(!Array.isArray(o))return{error:ae,info:Pf("rounds")};const s={},c=[];o.sort(((t,e)=>(t.sortOrder??0)-(e.sortOrder??0))),e=e??Object.assign({},...Object.values(n).map((t=>qs({tournamentRecord:t}).containedStructures))),a||({matchUps:a}=gl({nextMatchUps:!0,tournamentRecords:n}));let u=0;const d={},l={},m={},f=o.flatMap((o=>{const f=o.periodLength||i,h=[];e?.[o.structureId]?h.push(...e[o.structureId]):h.push(o.structureId);let g=a?rp({tournamentIds:[o.tournamentId],roundNumbers:[o.roundNumber],matchUpIds:o.matchUpIds,eventIds:[o.eventId],drawIds:[o.drawId],processContext:!0,structureIds:h,matchUps:a}).sort(Il):[];const{segmentNumber:I,segmentsCount:U}=o.roundSegment||{};if(p(I)&&r(g?.length)&&r(U)&&I>0&&I<=U&&U<g?.length&&!o.matchUpIds?.length){const t=g.length/U,e=t*(I-1);g=g.slice(e,e+t)}const S=n[o.tournamentId],y=Vd({drawId:o.drawId,tournamentRecord:S}).event,v=[];for(const t of g){const e=t.matchUpFormat;e&&(s[e]||(s[e]=[],s[e].push(t)),v.push(e))}for(const e of v){const{eventType:r,category:i}=y??{},{categoryName:a,ageCategoryCode:s}=i??{},{typeChangeRecoveryMinutes:p,recoveryMinutes:h,averageMinutes:I,error:U}=jy({categoryName:a??s,categoryType:i?.categoryType,tournamentId:o.tournamentId,eventId:o.eventId,tournamentRecords:n,matchUpFormat:e,eventType:r});if(U)return{error:U,round:o};const S=g.filter((e=>(t||!Ya.includes(e.matchUpStatus))&&e.matchUpStatus!==Ma)).map(ba);S.forEach((t=>{m[t]={typeChangeRecoveryMinutes:p,recoveryMinutes:h,averageMinutes:I},d[t]=h,l[t]=I})),c.push(...S),u=Math.max(I||0,u);return{roundPeriodLength:f,recoveryMinutes:h,averageMinutes:I,matchUpIds:S,hash:`${I}|${f}`}}}));return{scheduledRoundsDetails:f,greatestAverageMinutes:u,matchUpFormatCohorts:s,recoveryMinutesMap:d,averageMinutesMap:l,orderedMatchUpIds:c,minutesMap:m,...E}}function qy({scheduledRoundsDetails:t,greatestAverageMinutes:e,garmanSinglePass:n}){const r=[];let i,a,o,s,c=[];for(const u of t.filter(Boolean))s||(s=u.hash),(u.hash===s||n)&&(c=c.concat(u.matchUpIds)),u.hash===s||n||(s=u.hash,r.push({averageMinutes:o,recoveryMinutes:a,roundPeriodLength:i,matchUpIds:c}),c=u.matchUpIds),o=n?e:u.averageMinutes,a=u.recoveryMinutes,i=u.roundPeriodLength;return c.length&&r.push({matchUpIds:c,roundPeriodLength:i,recoveryMinutes:a,averageMinutes:o}),{groupedRounds:r}}function $y({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUp:n,value:r}){const{matchUpType:i}=n,{individualParticipantIds:a}=ec(n),o=(t[n.matchUpId]||[]).filter((t=>!b(t,a))).flat();[...a,...o].forEach((t=>{if(ky({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[ud]?a[ud]+=r:r>0&&(a[ud]=r),o.includes(t)&&(e[t].potentialCounted[n.drawId]=!0)}}))}const Wy=({scheduleAttributes:t=["scheduledDate","scheduledTime"],schedule:e={}})=>!!Object.keys(e).filter((e=>t.includes(e))).filter((t=>e[t])).length;function Hy({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===Ma;return n&&l.push({tournamentId:t.tournamentId,matchUpId:t.matchUpId}),!n&&Wy({schedule:e})&&(!u||t.schedule.scheduledDate===u)})),n=i.map(ba));const m=Array.isArray(c)?c.includes(u):c,f=m?[]:p.filter((({matchUpId:t})=>n.includes(t)));for(const n of f){$y({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;xy({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 zy({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:e,dateScheduledMatchUpIds:n,matchUpNotBeforeTimes:r,matchUpScheduleTimes:i,orderedMatchUpIds:a,clearDate:o,matchUps:s}){const c=Object.keys(i),u=a.map((t=>s.find((e=>e.matchUpId===t)))).filter(Boolean).filter((t=>{const r=!o&&(n.includes(t.matchUpId)||c.includes(t.matchUpId)),i=[Ma,Oa,Ea,Na,Ba,Ga,ka,Fa].includes(t?.matchUpStatus);return e||!r&&!t.winningSide&&!i})),{matchUpMap:d}=u.reduce(((e,n)=>{const{drawId:i,tournamentId:a}=n;return e.matchUpMap[a]||(e.matchUpMap[a]={}),e.matchUpMap[a][i]?e.matchUpMap[a][i].push(n):e.matchUpMap[a][i]=[n],Fy({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:r,matchUp:n}),e}),{matchUpMap:{}});return{matchUpsToSchedule:u,matchUpMap:d}}function Yy({defaultRecoveryMinutes:t=0,averageMatchUpMinutes:e=90,dateScheduledMatchUps:n,tournamentRecords:r,venueIds:i=[],periodLength:a,scheduleDate:o,matchUps:s}){if("object"!=typeof r)return{error:x};if(!yc(s)&&!Array.isArray(n))return{error:Ht};a=a??ly({recoveryMinutes:t,averageMatchUpMinutes:e});const c=Object.assign({},...Object.values(r).map((t=>(t.events??[]).map((e=>{const{scheduleTiming:n}=Qu({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 Wy({schedule:e})&&(!o||t.schedule.scheduledDate===o)})));const d=n?.filter((t=>(!i.length||i.includes(t.schedule.venueId))&&t.matchUpStatus!==Ma)),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}=yd({timingDetails:s,eventType:o}),{courtId:l,venueId:m}=e,f=ni(e.scheduledTime),h=pi(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 Ky({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:x};s=s??ly({recoveryMinutes:n,averageMatchUpMinutes:r});const{courts:m,venues:f}=Am({dates:[c],ignoreDisabled:!0,tournamentRecords:a}),h=m?.filter((t=>!d||d.includes(t.venueId)))??[];u=u??my({courts:h,scheduleDate:c,startTime:!0}),l=l??my({courts:h,scheduleDate:c,endTime:!0});const{bookings:g,dateScheduledMatchUps:I}=Yy({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:S}=fy(U),y=1===d?.length&&d[0]||1===f?.length&&f[0].venueId||void 0,v=I?.map(Ua("matchUpId"));return{dateScheduledMatchUpIds:v,dateScheduledMatchUps:I,scheduleTimes:S,venueId:y}}function Jy({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 S of f){const{rounds:f=[],venueId:y}=S,{scheduledRoundsDetails:v,greatestAverageMinutes:w,orderedMatchUpIds:T,minutesMap:P}=Gy({scheduleCompletedMatchUps:n,containedStructureIds:r,tournamentRecords:c,periodLength:u,matchUps:l,rounds:f});U.push(...T??[]);const{groupedRounds:D}=qy({scheduledRoundsDetails:v,greatestAverageMinutes:w,garmanSinglePass:!0});let b,N,R=[];p&&({scheduleTimes:R,dateScheduledMatchUpIds:b,dateScheduledMatchUps:N}=Ky({averageMatchUpMinutes:D[0]?.averageMinutes,scheduleDate:ri(d),venueIds:[S.venueId],clearScheduleDates:s,tournamentRecords:c,periodLength:u,matchUps:l}));const M=Hy({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:b,greatestAverageMinutes:w,matchUpNotBeforeTimes:i,matchUpScheduleTimes:a,matchUpDependencies:o,clearScheduleDates:s,scheduleDate:d,minutesMap:P,matchUps:l});({dateScheduledMatchUpIds:b,dateScheduledMatchUps:N}=M);const{byeScheduledMatchUpDetails:A,clearDate:E}=M;A?.length&&I.push(...A);const{matchUpsToSchedule:C,matchUpMap:O}=zy({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:n,dateScheduledMatchUpIds:b,matchUpNotBeforeTimes:i,matchUpScheduleTimes:a,orderedMatchUpIds:T,clearDate:E,matchUps:l}),F=m.filter((t=>t.venueId===y));h[y]={previousRemainingScheduleTimes:[],courtsCount:F.length,greatestAverageMinutes:w,scheduledRoundsDetails:v,dateScheduledMatchUps:N,matchUpsToSchedule:C,scheduleTimes:R,groupedRounds:D,venueCourts:F,minutesMap:P,matchUpMap:O},s||g.push(...b)}return{allDateScheduledByeMatchUpDetails:I,allDateScheduledMatchUpIds:g,venueScheduledRoundDetails:h,allDateMatchUpIds:U}}function Zy({individualParticipantProfiles:t,matchUpNotBeforeTimes:e,matchUpDependencies:r,scheduleTime:i,matchUp:a,details:o}){const s=(r?.[a.matchUpId]?.participantIds||[]).flat(),c=o?.minutesMap?.[a.matchUpId]?.averageMinutes||0,u=o?.minutesMap?.[a.matchUpId]?.recoveryMinutes||0,d=s.every((e=>{ky({individualParticipantProfiles:t,participantId:e});const r=t[e];if(!r.timeAfterRecovery)return!0;const o=ni(a?.schedule?.endTime),s=o?pi(o,n(u)):pi(i,n(c)+n(u));return!!![...Object.keys(r.potentialBookings).filter((t=>t!==a.drawId)).map((t=>r.potentialBookings[t])).flat(),...r.bookings].find((t=>function(t,e){const n=ti(t.scheduleTime),r=ti(t.timeAfterRecovery),i=ti(e.scheduleTime),a=ti(e.timeAfterRecovery),o=n>i&&n<a,s=i>n&&i<r,c=r>i&&r<a,u=a>n&&a<r;return vr({hasOverlap:n===i||r===a||o||c||s||u,startAisContained:o,endAisContained:c,startBisContained:s,endBisContained:u},!0)}({scheduleTime:i,timeAfterRecovery:s},t).hasOverlap))})),p=e[a.matchUpId],l=p?di(ui(p),ui(i),!1):0;return{enoughTime:d&&l>=0}}function Xy({individualParticipantProfiles:t,matchUpPotentialParticipantIds:e,matchUpDailyLimits:n={},matchUp:r}){const{matchUpId:i,matchUpType:a}=r,{enteredIndividualParticipantIds:o}=ec(r),s=(r.roundPosition&&e[i]||[]).flat(),c=m(o.concat(...s));c.forEach((e=>{ky({individualParticipantProfiles:t,participantId:e})}));return{participantIdsAtLimit:c.filter((e=>{const r=t[e];if(r)return[a,ud].find((t=>{const e=r.counters?.[t]||0,i=n[t]||0;return e&&i&&e>=i}))})),relevantParticipantIds:c}}function Qy({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:_};if(!(c||u&&Array.isArray(u)))return{error:$t};if(!(c||d&&"object"==typeof d))return{error:gn};let p;const l=[];let m=0;if(r&&!i){const t=Sl({tournamentRecords:o,tournamentRecord:s});i=t.matchUpDependencies,p=t.matchUps}p||(p=hl({tournamentRecord:s})?.matchUps??[]);const f=p.reduce(((n,r)=>{const{matchUpId:i,drawId:a,matchUpStatus:o}=r;return!e&&o===Ma||!t&&Ya.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}=Oy({tournamentRecord:s,drawId:t});if(!e)continue;const g=f[t].filter((t=>u?.includes(t)??h?.includes(t))),I=Ul({inContext:!1,drawDefinition:e}).matchUps;for(const t of g){const u=gI({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?{...E,scheduled:m,warnings:l}:{...E,scheduled:m}}function tv(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 Qy(t);const d=Lp(t,[{[sp]:!0},{[kp]:{matchUpContextIds:!0,matchUpDetails:!0},[Op]:Nn,[Fp]:Ep}]);if(d.error)return d;if((!c||i)&&!u)return{error:ae,info:"schedule is required"};const p=[];let l=0;const{matchUpDependencies:m}=Sl({tournamentRecords:o});for(const t of Object.values(o)){const{tournamentId:d}=t,f=i?.filter((t=>t.tournamentId===d)).map(ba),h=c?.filter((t=>t?.tournamentId===d));if(f?.length||h?.length){const i=Qy({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?{...E,scheduled:l,warnings:p}:{...E,scheduled:l}}function ev({autoSchedulingAudit:t,tournamentRecords:e}){sr({topic:ds,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:zm,itemValue:i};for(const t of Object.values(e))Lm({tournamentRecord:t,timeItem:a})}function nv(t){const{tournamentRecords:e,requestType:n}=t,r=Lp(t,[{[sp]:!0}]);if(r.error)return r;const i={};for(const t of Object.values(e)){const{extension:e}=Mr({element:t,name:ea}),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,...E}}function rv({averageMinutes:t,startTime:e,endTime:n,court:r,date:i}){if(!Array.isArray(r.dateAvailability))return{error:ae,stack:"getEarliestCourtTime"};const a=my({scheduleDate:i,courts:[r],startTime:!0}),o=my({scheduleDate:i,courts:[r],endTime:!0});e=e||a,n=n||o;const s=cy({courtDate:sy({court:r,date:i})}),c=ui(e),u=ui(n);return{earliestCourtTime:s.reduce(((e,n)=>{const r=ui(n.startTime),i=ui(n.endTime);if(r>u||i<c)return e;const a=c>r?c:r;if(di(a,i)>=t){const t=ni(a.toISOString());(!e||t<e)&&(e=t)}return e}),void 0),courtStartTime:a,courtEndTime:o}}function iv(t){const{scheduleAttributes:e=["scheduledDate","scheduledTime"],ignoreMatchUpStatuses:n=Ya,scheduledDates:r,venueIds:i}=t,a=nc(t),o=ha(a)?Object.values(a).map((({tournamentId:t})=>t)).filter(Boolean):[];if(!o?.length)return{error:x};let s=0;for(const t of o){const o=av({ignoreMatchUpStatuses:n,scheduleAttributes:e,tournamentRecord:a[t],scheduledDates:r,venueIds:i});if(o.error)return o;s+=o.clearedScheduleCount||0}return{...E,clearedScheduleCount:s}}function av({scheduleAttributes:t=["scheduledDate","scheduledTime"],ignoreMatchUpStatuses:e=Ya,tournamentRecord:n,scheduledDates:r,venueIds:i=[]}){if("object"!=typeof n)return{error:_};if(!Array.isArray(e)||!Array.isArray(i))return{error:Nn};i.length&&t.push("venueId");const a=(hl({matchUpFilters:{scheduledDates:r},tournamentRecord:n}).matchUps??[]).filter((n=>n.matchUpStatus&&!e.includes(n.matchUpStatus)&&Wy({schedule:n.schedule,scheduleAttributes:t})&&(!i?.length||i.includes(n.schedule.venueId)))).map(ba),o=hl({tournamentRecord:n,inContext:!1}).matchUps??[];let s=0;for(const t of o)a.includes(t.matchUpId)&&(t.timeItems=(t.timeItems??[]).filter((t=>t?.itemType&&![Pu,Du,Tu,Nu,Mu].includes(t?.itemType))),s+=1);return{...E,clearedScheduleCount:s}}function ov(t){const{checkPotentialRequestConflicts:e=!0,scheduleCompletedMatchUps:n,clearScheduleDates:r,scheduleDates:i=[],tournamentRecords:a,periodLength:o,useGarman:s,dryRun:c,pro:u}=t,d=Lp(t,[{[sp]:!0},{[Cp]:t=>!t||Array.isArray(t)&&t.every(Wr),[mp]:!0,[Fp]:Ep}]);if(d.error)return d;const p=Om({tournamentRecords:a});if(p.error)return p;if(!p.schedulingProfile.length)return{...E};const{modifications:l,issues:m=[],schedulingProfile:f=[]}=p,h=Object.assign({},...Object.values(a).map((t=>qs({tournamentRecord:t}).containedStructures))),g=i.map((t=>{if(Wr(t))return ri(t)})).filter(Boolean),I=f.map((t=>t.scheduleDate)).map((t=>Wr(t)&&ri(t))).filter((t=>t&&(!i.length||g.includes(t))));if(!I.length)return{error:se};if(r&&!c){iv({tournamentRecords:a,scheduledDates:Array.isArray(r)?r:[]})}const U=Am({ignoreDisabled:!1,tournamentRecords:a}).courts,{matchUps:S}=gl({matchUpFilters:{matchUpTypes:[Ks,Zs]},afterRecoveryTimes:!0,nextMatchUps:!0,tournamentRecords:a}),{matchUpDependencies:y}=Sl({includeParticipantDependencies:!0,tournamentRecords:a,matchUps:S}),{matchUpDailyLimits:v}=Ey({tournamentRecords:a}),{personRequests:w}=nv({requestType:Ly,tournamentRecords:a}),T={schedulingProfileModifications:l,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:n,schedulingProfileIssues:m,dateSchedulingProfiles:f.filter((t=>{const e=ri(t?.scheduleDate);return I.includes(e)})).sort(((t,e)=>new Date(t.scheduleDate).getTime()-new Date(e.scheduleDate).getTime())),containedStructureIds:h,matchUpDependencies:y,matchUpDailyLimits:v,clearScheduleDates:r,tournamentRecords:a,schedulingProfile:f,personRequests:w,periodLength:o,useGarman:s,matchUps:S,dryRun:c,courts:U};return u?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={},S={},y={},v={},w={},T={},P={};for(const t of i??[]){const r=ri(t?.scheduleDate),i=t?.venues||[],p={},D={},b=(t,e)=>{t.forEach((t=>{const n=D[t].counters;n[e]?n[e]+=1:n[e]=1,n[ud]?n[ud]+=1:n[ud]=1}))};g[r]={},I[r]={},v[r]=[],w[r]=[],T[r]=[],P[r]=[];const N={};m?.forEach((t=>{t.schedule?.scheduledDate&&fi(r,ri(t.schedule.scheduledDate))&&Fy({matchUpPotentialParticipantIds:p,matchUpNotBeforeTimes:N,matchUp:t})}));const{allDateScheduledByeMatchUpDetails:R,allDateScheduledMatchUpIds:M,venueScheduledRoundDetails:A,allDateMatchUpIds:E}=Jy({matchUpPotentialParticipantIds:p,individualParticipantProfiles:D,scheduleCompletedMatchUps:n,containedStructureIds:a,matchUpNotBeforeTimes:N,matchUpScheduleTimes:y,matchUpDependencies:o,clearScheduleDates:c,tournamentRecords:u,periodLength:d,scheduleDate:r,matchUps:m,courts:f,venues:i}),C=m?.filter((({matchUpId:t})=>M.includes(t))),{bookings:O}=Yy({dateScheduledMatchUps:C,tournamentRecords:u,scheduleDate:r,periodLength:d}),{virtualCourts:F}=py({scheduleDate:r,periodLength:d,bookings:O,courts:f}),k=F?.reduce(((t,e)=>{const{earliestCourtTime:n,courtEndTime:i}=rv({date:r,averageMinutes:0,court:e});return(!t.startTime||ui(n)<ui(t.startTime))&&(t.startTime=n),(!t.endTime||ui(i)>ui(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}=Xy({matchUpPotentialParticipantIds:p,individualParticipantProfiles:D,matchUpDailyLimits:s,matchUp:i});if(h.length){w[r].includes(m)||w[r].push(m);continue}const{dependenciesScheduled:T,remainingDependencies:R}=Cy({matchUpScheduleTimes:y,matchUpDependencies:o,allDateMatchUpIds:E,matchUp:i});if(!T){I[r][m]||(I[r][m]=[]),I[r][m].push({remainingDependencies:R});continue}const M=[],A=F?.reduce(((t,a)=>{if(c.includes(a.courtId))return t;const{earliestCourtTime:s}=rv({averageMinutes:n.greatestAverageMinutes,startTime:x,date:r,court:a});if(t.scheduleTime&&ti(s)>=ti(t.scheduleTime))return t;const{scheduledDependent:u}=_y({matchUpScheduleTimes:y,matchUpDependencies:o,scheduleTime:s,matchUpId:m,details:n});if(u)return t;const{enoughTime:d}=Zy({individualParticipantProfiles:D,matchUpNotBeforeTimes:N,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}=Vy({potentials:e,averageMatchUpMinutes:h,requestConflicts:P,personRequests:l,scheduleTime:s,scheduleDate:r,matchUp:i});if(I?.length)return M.push(...I),!1;b(v,f);const U=n.minutesMap?.[m]?.recoveryMinutes;return xy({matchUpPotentialParticipantIds:p,individualParticipantProfiles:D,matchUpNotBeforeTimes:N,averageMatchUpMinutes:h,matchUpDependencies:o,recoveryMinutes:U,scheduleTime:s,matchUp:i}),(!t.scheduleTime||ti(s)<ti(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;y[m]=i,S[m]=o,a.push(m),c.push(o);const s=i,u=pi(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 M?.length&&(U[r]||(U[r]=[]),U[r].push(...M))}c.length!==n.courtsCount&&a.length!==n.courtsCount&&n.matchUpsToSchedule.length||(u=!0),n.matchUpsToSchedule.length&&a<n.courtsCount&&(ui(x)<ui(k.endTime)?x=pi(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}=Oy({tournamentRecord:n,drawId:i});a&&e[t][i].forEach((({matchUpId:t})=>{const e=y[t],i=S[t];if(e){const o=e.split(":").map(mi).join(":"),s=`${ri(r)}T${o}`;h||(mI({drawDefinition:a,scheduledTime:s,matchUpId:t}),lI({courtDayDate:r,tournamentRecords:u,tournamentRecord:n,drawDefinition:a,matchUpId:t,courtId:i})),v[r].push(t)}}))}))})),T[r]=A[t].matchUpsToSchedule.map(ba)}!h&&R?.length&&tv({matchUpDetails:R,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 D=(i??[]).map((({scheduleDate:t})=>t)),b={timeStamp:Date.now(),overLimitMatchUpIds:w,scheduledMatchUpIds:v,schedulingProfile:p,noTimeMatchUpIds:T,requestConflicts:P,scheduledDates:D};return ev({tournamentRecords:u,autoSchedulingAudit:b}),{...E,schedulingProfileModifications:t,schedulingProfileIssues:r,dateSchedulingProfiles:i,recoveryTimeDeferredMatchUpIds:g,dependencyDeferredMatchUpIds:I,matchUpScheduleTimes:y,overLimitMatchUpIds:w,scheduledMatchUpIds:v,noTimeMatchUpIds:T,requestConflicts:P,scheduledDates:D}}(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={},S={},y={},v={},w={},T={},P={},D={};for(const t of i){const r=ri(t?.scheduleDate),i=t?.venues||[],d={},b={},N=(t,e)=>{t.forEach((t=>{const n=b[t].counters;n[e]?n[e]+=1:n[e]=1,n[ud]?n[ud]+=1:n[ud]=1}))};U[r]={},S[r]={},g[r]={},I[r]={},w[r]=[],T[r]=[],P[r]=[],D[r]=[];const R={};m.forEach((t=>{t.schedule?.scheduledDate&&fi(r,ri(t.schedule.scheduledDate))&&Fy({matchUpPotentialParticipantIds:d,matchUpNotBeforeTimes:R,matchUp:t})}));const{allDateScheduledByeMatchUpDetails:M,venueScheduledRoundDetails:A,allDateMatchUpIds:E}=Jy({matchUpPotentialParticipantIds:d,individualParticipantProfiles:b,scheduleCompletedMatchUps:n,containedStructureIds:a,matchUpNotBeforeTimes:R,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}=Xy({matchUpPotentialParticipantIds:d,individualParticipantProfiles:b,matchUpDailyLimits:s,matchUp:t});if(u.length)return T[r].includes(n)||T[r].push(n),!1;const{scheduledDependent:m}=_y({matchUpScheduleTimes:v,matchUpDependencies:o,scheduleTime:a,matchUpId:n,details:i});if(m)return!1;const{dependenciesScheduled:f,remainingDependencies:h}=Cy({matchUpScheduleTimes:v,matchUpDependencies:o,allDateMatchUpIds:E,matchUp:t});if(!f)return S[r][n]||(S[r][n]=[]),S[r][n].push({scheduleTime:a,remainingDependencies:h}),!1;const{enoughTime:g}=Zy({individualParticipantProfiles:b,matchUpNotBeforeTimes:R,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}=Vy({potentials:e,averageMatchUpMinutes:I,requestConflicts:D,personRequests:p,scheduleTime:a,scheduleDate:r,matchUp:t});if(w?.length)return y[r]||(y[r]=[]),y[r].push(...w),!1;N(l,c);const P=i.minutesMap?.[n]?.recoveryMinutes;return xy({matchUpPotentialParticipantIds:d,individualParticipantProfiles:b,matchUpNotBeforeTimes:R,averageMatchUpMinutes:I,matchUpDependencies:o,recoveryMinutes:P,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}=Oy({tournamentRecord:i,drawId:a});o&&e[n][a].forEach((({matchUpId:e})=>{const n=v[e];if(n){const a=n.split(":").map(mi).join(":"),s=`${ri(r)}T${a}`;h?w[r].push(e):(mI({drawDefinition:o,scheduledTime:s,matchUpId:e}).success&&w[r].push(e),t&&pI({tournamentRecord:i,drawDefinition:o,matchUpId:e,venueId:t}))}}))}))})),P[r]=A[t].matchUpsToSchedule.map(ba),g[r][t]=A[t].scheduleTimes.sort(((t,e)=>ti(t.scheduleTime)-ti(e.scheduleTime)))}!h&&M?.length&&tv({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=>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)),N={timeStamp:Date.now(),overLimitMatchUpIds:T,scheduledMatchUpIds:w,schedulingProfile:d,noTimeMatchUpIds:P,requestConflicts:D,scheduledDates:b};return ev({tournamentRecords:u,autoSchedulingAudit:N}),{...E,schedulingProfileModifications:t,schedulingProfileIssues:r,scheduleTimesRemaining:g,dateSchedulingProfiles:i,skippedScheduleTimes:I,recoveryTimeDeferredMatchUpIds:U,dependencyDeferredMatchUpIds:S,matchUpScheduleTimes:v,overLimitMatchUpIds:T,scheduledMatchUpIds:w,noTimeMatchUpIds:P,requestConflicts:D,scheduledDates:b}}(T)}function sv(t){const e=t||{};return e.tournamentId||(e.tournamentId=Md()),(!e.startDate||Xr(e.startDate)||Lr.test(e.startDate))&&(!e.endDate||Xr(e.endDate)||Lr.test(e.endDate))?(e.extensions&&(e.extensions=e.extensions.filter(br)),{...e}):{error:pe}}function cv({addParticipants:t=!0,participantAttribute:e,tournamentRecord:n,personAttribute:r,teamNames:i,accessor:a,uuids:o}){if(!n)return{error:_};const s={},c=(n.participants??[]).filter((({participantType:t,participantRole:e})=>t===sc&&e===um));let u=0;for(const t of c){const n=a&&la({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()??Md(),individualParticipantIds:[],participantRole:um,participantType:dc};const t={value:r??e,name:Ji};Nr({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!==dc)return;if(t.participantRole!==um)return;const{extension:e}=Mr({name:Ji,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?(sr({payload:{tournamentId:n.tournamentId,participants:m},topic:ss}),{...E,participantsAdded:l}):m.length?{...E,newParticipants:m}:{error:Ie}}function uv(t){let{rankingRange:e,scaledParticipantsCount:n}=t;const{ratingsParameters:r=MU,valuesInstanceLimit:i,consideredDate:a,category:o,nationalityCodesCount:c,nationalityCodeType:u,nationalityCodes:p,participantsCount:m=32,participantType:h,personIds:g,idPrefix:I,uuids:U,personExtensions:S,addressProps:y,gendersCount:v,matchUpType:T,personData:P,sex:D,inContext:b,withISO2:N,withIOC:R,scaleAllParticipants:M}=t,A=h===uc||T===Js,E=h===dc||T===dc;!e||Array.isArray(e)&&e.every((t=>s(t)))&&2===e.length||(e=void 0),n=M?m:n;e=e||[1,n&&n>1e3?n:1e3],e[1]+=1;const C=m*(A?2:E?8:1),O=Ty({count:C,personExtensions:S,consideredDate:a,gendersCount:v,personData:P,category:o,sex:D});if(O.error)return O;const{nationalityCodes:F,persons:k}=O;let x=[],_=[],L=[],B=[];if("object"==typeof o){const{categoryName:t,ageCategoryCode:i,ratingType:a}=o;if((t||i)&&!a){const[t,r]=e||[];if(_=f(w(t,r)).slice(0,n||d(20,30)),[uc,dc].includes(h)){const[t,r]=e||[];x=f(w(t,r)).slice(0,n||d(20,30))}}if(a&&r[a]){const{ratingMax:t,ratingMin:e,ratingAttributes:i}=o,s={...r[a],...i||{}},{attributes:c={},decimalsCount:u,accessors:p,range:m,step:f}=s,g=t=>{const e={};for(const n of Object.keys(t)||{}){const r=t[n];if("object"==typeof r&&r.generator){const{range:t}=r,[i,a]=t.slice().sort();e[n]=d(i,a)}else e[n]=r}return e},I=m[0]>m[1]?2:.5,[U,S]=m.slice().sort(),y=()=>w(0,2e3).map((()=>l(U,S,I,f,u))).filter((n=>(!t||n<=t)&&(!e||n>=e))).slice(0,n||d(20,30)).map((t=>p?Object.assign({},...p.map((e=>({[e]:t}))),g(c)):t));L=y(),[uc,dc].includes(h)&&(B=y())}}const V=el.filter((t=>"IOC"===u&&t.ioc||t.iso));const{postalCodesProfile:j,postalCodesCount:G,statesProfile:q,citiesProfile:$,citiesCount:W,statesCount:H}=y||{},z=t=>Object.keys(t).map((t=>w(0,q[t]).map((()=>t)))).flat(),Y={cities:$&&z($)||y?.cities||Uy({count:W||C,participantsCount:C}).cities,states:q&&z(q)||y?.states||Sy({count:H||C,participantsCount:C}).states,postalCodes:j&&z(j)||y?.postalCodes||yy({count:G||C,participantsCount:C}).postalCodes},K=function(t){const e=Math.ceil(C/t);return i&&e>i?Math.ceil(C/i):t}(c),J=K?f(V).slice(0,c):p?V.filter((t=>p.includes(t.iso))):V,Z=f(w(0,Math.ceil(C/(K||1))).map((()=>J)).flat(1/0)),X=by({count:m}).names;return{participants:w(0,m).map((t=>{const e=A?2:E?8:1,n=w(0,e).map((n=>function(t){const e=k[t],{nationalityCode:n,participantExtensions:r,participantTimeItems:i,extensions:a,firstName:s,birthDate:c,lastName:d,personId:p,sex:l}=e||{},m=s||"GivenName",f=d||"FamilyName",h=`${m} ${f}`,S=Z[t],y=F?.length&&n||S&&("IOC"===u?S.ioc||S.iso:S.iso||S.ioc)||n;!Z?.length||y||n||console.log("%c Invalid Nationality Code",{participantIndex:t,country:S});const v=Py({...Y,participantIndex:t,nationalityCode:y}),w=vr({participantId:pv({participantType:sc,index:t,idPrefix:I,uuids:U}),extensions:r,timeItems:i,participantRole:um,participantType:sc,participantName:h,person:{addresses:[v],personId:p||g?.length&&g[t]||Md(),standardFamilyName:f,standardGivenName:m,nationalityCode:y,extensions:a,birthDate:Wr(c)?c:void 0,sex:l}});if(R&&y){const t=el.find((({iso:t})=>t===y));t?.ioc&&(w.person.iocNationalityCode=t.ioc),t?.label&&(w.person.countryName=t.label)}if(N&&y){const t=el.find((({iso:t})=>t===y));t?.iso2&&(w.person.iso2NationalityCode=t.iso2),t?.label&&(w.person.countryName=t.label)}if(o){const e=_[t],n=x[t];dv({scaleValue:e,eventType:ed,scaleType:Er,participant:w,category:o}),dv({scaleValue:n,eventType:rd,scaleType:Er,participant:w,category:o});const r=L[t],i=B[t];dv({scaleValue:r,eventType:ed,scaleType:Cr,participant:w,category:o}),dv({scaleValue:i,eventType:rd,scaleType:Cr,participant:w,category:o})}return w}(t*e+n))),r=n.map((t=>t.participantId)),i=n.map((t=>t.person.standardFamilyName)).join("/"),a=A?uc:dc,s={participantId:pv({participantType:a,idPrefix:I,index:t,uuids:U}),participantRole:um,participantName:A?i:X[t],individualParticipantIds:r,participantType:a};return b&&(s.individualParticipants=n),A||E?[s,...n]:n})).flat()}}function dv({scaleValue:t,participant:e,eventType:n,scaleType:r,category:i}){const a=i.categoryName||i.ratingType||i.ageCategoryCode,o={itemValue:t,itemType:[Or,r,n,a].join(".")};a&&t&&(e.timeItems||(e.timeItems=[]),e.timeItems.push(o))}function pv({idPrefix:t,participantType:e,index:n,uuids:r}){return t?`${t}-${e===sc?"I":"P"}-${n}`:r?.pop()||Md()}function lv({alternatesCount:t=0,tieFormatName:e,tieFormat:n,drawSize:r}){let i=0,a=0,o=0,s=0;const c={},u={[qp]:0,[Hp]:0,[$p]:0,[Wp]:0,[Gp]:0};n="object"==typeof n?n:ES({namedFormat:e}),n?.collectionDefinitions?.filter(Boolean).forEach((t=>{const{category:e,collectionId:n,matchUpType:r,matchUpCount:d,gender:p}=t;if([qp,Hp].includes(p)){const t=d*(r===Zs?2:1);u[p]<t&&(u[p]=t)}else p===$p&&(u[qp]<d&&(u[qp]=d),u[Hp]<d&&(u[Hp]=d));if(e){const t=JSON.stringify(e);c[t]=e}if(n||(t.collectionId=Md()),r===Zs){const t=d;s+=d,i=Math.max(i,t)}if(r===Ks){const t=d;o+=d,a=Math.max(a,t)}}));const d=Object.keys(c).length?Math.max(o,2*s):Math.max(a,2*i);return{maxDoublesDraw:i*(r+t),maxSinglesDraw:a*(r+t),teamSize:d,genders:u}}function mv({participantsProfile:t,tournamentRecord:e,eventProfiles:n,drawProfiles:r,startDate:i,uuids:a}){const{participantsCount:o,participantType:s,largestTeamDraw:c,largestTeamSize:u,gendersCount:d}=function({participantsProfile:t,eventProfiles:e,drawProfiles:n}){let{participantsCount:r,participantType:i=sc}=t||{};const a=r||0,o={[Hp]:0,[$p]:0,[Wp]:0,[qp]:0,[Gp]: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===nd,g=i===id,I=Boolean(e||f===Qa||l||m);if(g){d=Math.max(d,r+t),a="object"==typeof a?a:ES({namedFormat:n});const{teamSize:e,maxDoublesDraw:i,maxSinglesDraw:p,genders:l}=lv({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=uc),(r||a)<m&&(r=m),r&&s&&[uc,id].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=uv({uuids:a,...t,consideredDate:i,participantsCount:o,participantType:s,gendersCount:d}).participants;let m=0,f=gU({tournamentRecord:e,participants:l});if(f.error)return f;if(m+=f.addedCount,p){const t=cv({tournamentRecord:e,...p});if(t.error)return t}const h=l.filter((({participantType:t})=>t===sc)).map(Da);return f=gU({participants:w(0,c).map((t=>{const e=h.slice(t*u,(t+1)*u);return{participantName:`Team ${t+1}`,participantRole:um,participantType:dc,participantId:Md(),individualParticipantIds:e}})),tournamentRecord:e}),f.error?f:(m+=f.addedCount,{addedCount:m,...E})}const fv=()=>({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});function hv(t){return parseInt(t)}function gv({startTime:t="",endTime:e=""}={}){if(!(t&&e&&jr.test(t)&&jr.test(e)))return!1;const[n,r]=t.split(":").map(hv),[i,a]=e.split(":").map(hv);return!(i<n)&&!(n===i&&a<r)}function Iv(t,e){const[n,r]=t.startTime.split(":").map(hv),[i,a]=e.startTime.split(":").map(hv);return n<i?-1:n>i?1:r<a?-1:r>a?1:0}function Uv({dateAvailability:t}){if(!t)return{error:de};if(!Array.isArray(t))return{error:ue};const e="Times must be 24 hour => 00:00";for(const n of t){if("object"!=typeof n)return{error:ue};const{date:t,startTime:r,endTime:i,bookings:a=[]}=n;if(!r||!i)return{error:ue};if(t&&!Vr.test(t))return{error:pe,dateAvailability:{date:t},info:"Dates must be formated => YYYY-MM-DD"};if(!jr.test(r))return{error:le,dateAvailability:{startTime:r},info:e};if(!jr.test(i))return{error:le,dateAvailability:{endTime:i},info:e};if(r===i)return{error:le,dateAvailability:{startTime:r,endTime:i},info:"startTime and endTime are equivalent"};if(!gv({startTime:r,endTime:i}))return{error:le,dateAvailability:{startTime:r,endTime:i},info:"endTime must be after startTime"};if(a){if(!Array.isArray(a))return{error:ce};for(const t of a){if("object"!=typeof t)return{error:ce};const{startTime:n,endTime:r}=t;if(!jr.test(n))return{error:le,booking:{startTime:n},info:e};if(!jr.test(r))return{error:le,booking:{endTime:r},info:e};if(n===r)return{error:le,dateAvailability:{startTime:n,endTime:r},info:"startTime and endTime are equivalent"};if(!gv({startTime:n,endTime:r}))return{error:le,dateAvailability:{startTime:n,endTime:r},info:"endTime must be after startTime"}}}}return{valid:!0}}function Sv({tournamentRecord:t,disableNotice:e,venueId:n,courtId:r,court:i}){const{venue:a}=Cd({tournamentRecord:t,venueId:n});if(!a)return{error:rn};a.courts||(a.courts=[]);const o={...fv(),venueId:n,courtId:r};o.courtId||(o.courtId=Md());if(a.courts.some((t=>t.courtId===o.courtId)))return{error:en};{const r=(i?.dateAvailability||[]).map((t=>({...t,date:ri(t.date),startTime:ni(t.startTime),endTime:ni(t.endTime),bookings:t.bookings?.map((({startTime:t,endTime:e,bookingType:n})=>({startTime:ni(t),endTime:ni(e),bookingType:n})))}))),s=Object.keys(o);for(const t of s)if(i?.[t])if("dateAvailability"===t){const t=Uv({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||sr({payload:{venue:a,tournamentId:t.tournamentId},topic:Ts,key:a.venueId}),{...E,court:gi(o),venueId:n}}}function yv(t){const{tournamentRecord:e,venueId:n}=t;if("string"!=typeof n||!n)return{error:an};const r=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},i=[];let a;for(const e of Object.values(r)){const{venue:r}=Cd({tournamentRecord:e,venueId:n});if(r){const n=vv({...t,tournamentRecord:e});for(const t of n?.courts??[])i.push(t?.courtId);if(n.error)return n;a=!0}}return a?{...E,courtIds:i}:{error:rn}}function vv({courtNameRoot:t="Court",dateAvailability:e=[],venueAbbreviationRoot:n,tournamentRecord:r,courtNames:i=[],courtTimings:a,courtsCount:o,startTime:c,courtIds:u,endTime:d,idPrefix:p,venueId:l,dates:m}){if(!l)return{error:an};const f=Cd({tournamentRecord:r,venueId:l});if(f.error)return f;const{venue:h}=f;if(!s(o)||!i)return{error:Qe};const g=w(0,o=o??i.length).map((r=>{const o=a?.[r],s=o?m.map((t=>({date:zr(t),startTime:c,endTime:d,...o}))):e;return o&&c&&d&&s.push({startTime:c,endTime:d}),{courtName:i[r]||n&&h?.venueAbbreviation&&`${h?.venueAbbreviation} ${r+1}`||`${t} ${r+1}`,dateAvailability:s}})).map(((t,e)=>{const n=u?.pop()||p&&`${p}-${e+1}`;return Sv({disableNotice:!0,tournamentRecord:r,courtId:n,venueId:l,court:t})})).map((t=>t.court)).filter(Boolean);return g.length!==o?wr({info:"not all courts could be generated",result:{error:Nn}}):(h&&sr({payload:{venue:h,tournamentId:r.tournamentId},topic:Ts,key:h.venueId}),{...E,courts:gi(g)})}function wv({tournamentRecord:t,venueProfiles:e,uuids:n}){const{startDate:r,endDate:i}=t,a=[];for(const[o,s]of e.entries()){const{venueAbbreviation:e,venueId:c=n?.pop()??Md(),dateAvailability:u,startTime:d="07:00",endTime:p="19:00",courtTimings:l,courtsCount:m,courtNames:f,venueName:h,idPrefix:g,courtIds:I}=s,U=Ad({tournamentRecord:t,venue:{venueName:h||`Venue ${o+1}`,venueAbbreviation:e,venueId:c}});if(U.error)return U;a.push(c);const S=Jr(r,i),y=!Array.isArray(u)&&[{startTime:d,endTime:p}].concat(S.map((t=>({date:zr(t),startTime:d,endTime:p})))),v=yv({dateAvailability:u||y,tournamentRecord:t,courtTimings:l,courtsCount:m,courtNames:f,startTime:d,idPrefix:g,courtIds:I,endTime:p,venueId:c,dates:S});if(v.error)return v}return a}function Tv({drawProfiles:t,category:e,gender:n}){const r={},i=t?.reduce(((t,i)=>{const{qualifyingPositions:a=0,participantsCount:o=0,uniqueParticipants:s,stage:c=Xa,drawSize:u=0}=i||{};Object.keys(t).includes(c)||(t[c]=0);const d=(o||u)-a;return s||n||e||c===Qa?(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 Pv({allUniqueParticipantIds:t,stageParticipantsCount:e,eventParticipantType:n,targetParticipants:r}){const i=e[Xa]||0,a=e[Qa]||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)}}}function Dv(t){const{removePriorValues:e,tournamentRecord:n,participantId:r,scaleItem:i}=t;let a,o;if(!bv({scaleItem:i}))return{error:In};if(r&&Array.isArray(n.participants)&&(o=n.participants.find((t=>t.participantId===r)),o)){const t=Nv({removePriorValues:e,participant:o,scaleItem:i});if(t.error)return t;a=!t.valueChanged;const{topics:r}=lr();r.includes(Ss)&&sr({topic:Ss,payload:{tournamentId:n.tournamentId,participants:[o]}})}return a&&{...E,info:Cn,existingValue:i?.scaleValue}||o&&{...E,newValue:i?.scaleValue}||{error:Ee}}function bv({scaleItem:t}){const e=t&&Object.keys(t),n=["scaleType","eventType","scaleName"];return!!(n.filter((t=>e?.includes(t))).length===n.length)}function Nv({removePriorValues:t,participant:e,scaleItem:n}){if(!e)return{error:Re};const r=n&&Object.keys(n),i=["scaleType","eventType","scaleName"];if(!(i.filter((t=>r.includes(t)&&n[t])).length===i.length))return{error:In};const a=(new Date).toISOString();e.timeItems||(e.timeItems=[]);const{scaleItem:o}=Vl({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=[Or,r,i,o].join("."),c=vr({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{...E,valueChanged:c,newValue:n.scaleValue}}function Rv({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:n,setObject:r}){if(!r)return;const i=Mv({set:r}),a=function({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:n,isTiebreakSet:r,isDecidingSet:i,set:a}){if(!a)return{error:ae,info:"missing set"};e=e||n&&Jd(n);const o=i&&e.finalSetFormat||e?.setFormat||{},{side1Score:s,side2Score:c}=a,{setTo:u,tiebreakAt:d,tiebreakFormat:p}=o,l=p?.NoAd,m=Mv({set:a}),f=Math.abs(s-c),h=s>=u||c>=u,g=r||s>=u&&c>=u||d&&d<u&&(s===d||c===d),I=t||g&&(1===m&&a.side1TiebreakScore>a.side2TiebreakScore||2===m&&a.side2TiebreakScore>a.side1TiebreakScore),U=g&&(d&&!r||r&&l)?1:2,S=f>=U;return(h&&(S||g)||r)&&(!g||I)}({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:n,set:r});return a&&i||void 0}function Mv({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 Av(t){const{setObject:e,matchUpScoringFormat:n}=t;if(!e)return{error:re};const{setNumber:r}=e||{},{bestOf:i}=n||{},a=!(!r||!i||r!==i),o=a&&n?.finalSetFormat||n?.setFormat,s=!!o?.tiebreakSet,c=!!o?.timed,u=!s&&!c,d=!!(r&&i&&r<=i),p=[e?.side1Score,e?.side2Score],l=[e?.side1PointScore,e?.side2PointScore],m=[e?.side1TiebreakScore,e?.side2TiebreakScore],f=p.filter((t=>void 0!==t)).length,h=l.filter((t=>void 0!==t)).length,g=m.filter((t=>void 0!==t)).length,I=p?.filter((t=>!isNaN(t))).length,U=m?.filter((t=>!isNaN(t))).length,{tiebreakAt:S}=o||{},y=S&&2===p.filter((t=>t>=S)).length,v=y&&((p[0]>p[1]?1:p[1]>p[0]&&2)||void 0),w=!(!U||I),T=!!e?.winningSide,{error:P,result:D}=function({setObject:t,setFormat:e,sideGameScores:n,sideTiebreakScores:r}){if(!t)return{result:!1,error:re};const i=!!e?.tiebreakSet,a=!!e?.timed;if(!e||i||a)return{result:!1,error:Nn};const o=2===n?.filter((t=>!isNaN(t))).length;if(!o)return{result:!1,error:fe};const{setTo:s,tiebreakAt:c,tiebreakFormat:u,NoAD:d}=e||{},p=!(!s||!n?.find((t=>t>=s)));if(!p)return{result:!1,error:fe};const l=[1,2].includes(t?.winningSide);if(!t||!l)return{result:!1,error:ge};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,S=2===r?.filter((t=>!isNaN(t))).length,y=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(!S)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(!y||!v||y<v)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};const n=y-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 T=d?1:2,P=g>=s-1,D=I&&P&&!w&&I<T;if(D)return{result:!1,error:{message:"invalid winning game scoreString (3)"}};if(I>T&&h>s)return{result:!1,error:{message:"invalid winning game scoreString (4)"}};return{result:!0}}({setObject:e,setFormat:o,sideGameScores:p,sideTiebreakScores:m}),{error:b,result:N}=function({setObject:t,setFormat:e,sideTiebreakScores:n}){if(!t)return{result:!1,error:re};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:ge};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}}({setObject:e,setFormat:o,sideTiebreakScores:m}),R=u&&!w&&D||s&&w&&N,M={expectTiebreakSet:s,expectTimedSet:c,hasTiebreakCondition:y,isCompletedSet:T,isDecidingSet:a,isTiebreakSet:w,isValidSet:d&&!(s&&!w)&&!(u&&w)&&(!T||R),isValidSetNumber:d,isValidSetOutcome:R,leadingSide:v,setFormat:o,sideGameScores:p,sideGameScoresCount:f,sidePointScores:l,sidePointScoresCount:h,sideTiebreakScores:m,sideTiebreakScoresCount:g,winningSide:Rv({isDecidingSet:a,isTiebreakSet:w,matchUpScoringFormat:n,setObject:e})};return void 0!==e?.winningSide&&(w?(M.isValidTiebreakSetOutcome=N,N||(M.tiebreakSetError=b)):(M.isValidStandardSetOutcome=D,D||(M.standardSetError=P))),M}function Ev(t){const{matchUp:e,sideNumber:n,setNumber:r,isTiebreakValue:i,isPointValue:a}=t||{};let{matchUpFormat:o}=t||{};if(!e)return{error:zt};o=o||e?.matchUpFormat;const s=Jd(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)||[],I=!!(d&&r&&h?.reduce(((t,e)=>(!e||!e.side1Score&&!e.side2Score&&!e.side1TiebreakScore&&!e.side2TiebreakScore&&!e.side1PointScore&&!e.side2PointScore)&&t),!0)),U=r<=d&&u.find((t=>t.setNumber===r)),S=U&&Av({setObject:U,matchUpScoringFormat:s}),{isCompletedSet:y,sideGameScores:v,sideTiebreakScores:w}=S||{},T=!!(U&&!y&&I||r&&r===d+1&&!c),P=[1,2].includes(n),D=P?n-1:0,b=U&&P&&(!i&&!a&&void 0!==v[D]&&v[D]||i&&void 0!==w[D]&&w[D]),N=!!b,R=m?.map((t=>Av({setObject:t,matchUpScoringFormat:s}).isValidSetOutcome)).reduce(((t,e)=>t&&e),!0),M=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=M[E],F=M[C],k=Math.max(...M),x=g(M)[k],{bestOf:_}=s||{},L=k===(_&&Math.ceil(_/2)||1)&&1===x&&M.indexOf(k)+1||void 0,B=O>F&&A===L;return{completedSetsHaveValidOutcomes:R,validMatchUpWinningSide:B,calculatedWinningSide:L,matchUpScoringFormat:s,validMatchUpOutcome:L&&R&&B,isLastSetWithValues:I,completedSetsCount:f,isCompletedMatchUp:c,isValidSideNumber:P,hasExistingValue:N,existingValue:b,isExistingSet:l,isActiveSet:T,...S}}const Cv={[Ga]:2,[ka]:1,[Fa]:1,[Ba]:1,[Oa]:4};function Ov(t){let{defaultWithScorePercent:e=2,winningSide:n}=t;const{matchUpStatusProfile:r=Cv,matchUpFormat:i=lg,pointsPerMinute:a=1,sideWeight:o=4}=t;if(!rh(i))return{error:Bt};if("object"!=typeof r)return{error:Nn};if(e>100&&(e=100),isNaN(e)||isNaN(a)||isNaN(o))return{error:Nn};const s=Object.keys(r).filter((t=>Object.keys(Za).includes(t)&&t!==Ea));if(Object.keys(s).reduce(((t,e)=>t+r[e]),0)>100)return{error:Nn,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=d(1,100),p=(c.valueMap.find((t=>u<=t[0]))??[100,Ea])[1],l={sets:[],scoreStringSide1:"",side2ScoreString:""};if([Ga,Oa].includes(p)){n=n||d(1,2);const t={score:l,winningSide:n,matchUpStatus:p};if(!(p===Oa&&d(1,100)>100-e))return{outcome:t}}else if([ka,Fa].includes(p))return{outcome:{score:l,matchUpStatus:p}};const m=Jd(i),{bestOf:f,setFormat:h,finalSetFormat:g}=m??{},I=[],U=d(0,1),S=n?[n-1]:[...w(0,o).map((()=>U)),1-U],v=[Ba,Oa,_a,Va].includes(p)&&(y(w(1,f))||1);let T;for(const t of w(1,(f??0)+1)){const e=t===f,{set:n,incomplete:r,winningSideNumber:o}=Fv({incomplete:v===t,matchUpStatus:p,pointsPerMinute:a,setFormat:e&&g||h,setNumber:t,weightedRange:S});if(I.push(n),r){T=o;break}if(Ev({matchUp:{score:{sets:I},matchUpFormat:i}}).calculatedWinningSide)break}const P=Ev({matchUp:{score:{sets:I},matchUpFormat:i}}),D=T?n||T:P.calculatedWinningSide,{score:b}=iU({score:{sets:I},winningSide:D,matchUpStatus:p});return{outcome:{score:b,winningSide:D,matchUpStatus:p}}}function Fv({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:p,timed:l,minutes:m}=i,f=d(0,t.length-1),h=t[f];let g;if(l){const i=m*e,a=Math.round(.2*i),s=i+y([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];h&&u.reverse(),g=t[f]+1;let p=(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}),Ya.includes(n)?{set:o,incomplete:r,winningSideNumber:g}:{set:o,incomplete:r}}p||(u[d(0,1)]+=1),p=u[0]>u[1]?1:2,p!==g&&u.reverse();const[l,I]=u;return Object.assign(o,{side1Score:l,side2Score:I,winningSide:g}),{set:o}}if(r)return o.side1Score=d(0,u),o.side2Score=d(0,u),Ya.includes(n)&&(g=t[f]+1),{set:o,incomplete:r,winningSideNumber:g};{const e=w(1,s+1).map((t=>w(0,s+2-t).map((()=>t)))).flat(),n=e[d(0,e.length-1)],r=s&&Ny({isSide1:!0,tiebreakAt:u,lowValue:n,setTo:s}),a=!r,l=1===t.length&&t[f]+1;if(!a){if(l){(r[0]>r[1]?1:2)!==l&&r.reverse()}else h&&r.reverse();const[t,e]=r;Object.assign(o,{side1Score:t,side2Score:e})}const m=Av({matchUpScoringFormat:{setFormat:i},setObject:o});let g;if(m.hasTiebreakCondition||a){const{NoAD:t,tiebreakTo:e}=c||p||{},n=w(1,e+1).map((t=>w(0,e+2-t).map((()=>t)))).flat(),r=n[d(0,n.length-1)],i=Ry({isSide1:!0,tiebreakNoAd:t,tiebreakTo:e,lowValue:r});if(i)if(a){const t=i[0]>i[1]?1:2;l?t!==l&&i.reverse():h&&i.reverse(),[o.side1TiebreakScore,o.side2TiebreakScore]=i,g=(i[0]>i[1]?1:i[1]>i[0]&&2)||void 0}else 2===m.leadingSide?[o.side1TiebreakScore,o.side2TiebreakScore]=i:[o.side2TiebreakScore,o.side1TiebreakScore]=i}o.winningSide=m.winningSide||m.leadingSide||l||g}return{set:o}}function kv(t){const{matchUpStatusProfile:e,completeAllMatchUps:n,randomWinningSide:r,tournamentRecord:i,completionGoal:a,drawDefinition:o,event:s}=t;if(!o)return{error:j};const c=t.matchUpFormat||o.matchUpFormat||s?.matchUpFormat,u=o.structures.slice().sort(Xo);let d=0;const{matchUps:p,matchUpsMap:l}=Jp({contextFilters:{stages:[Xa,Qa]},matchUpFilters:{matchUpTypes:[Qs],roundNumbers:[1]},inContext:!0,drawDefinition:o});if(p?.length){const t=s?.category?.ageCategoryCode||s?.category?.categoryName;if(t){const e=oy({singlesOnly:!0,tournamentRecord:i,drawDefinition:o,scaleAccessor:{scaleName:t,sortOrder:ry,scaleType:Er},event:s});if(e.error)return e;const{lineUps:n,participantsToAdd:r}=e;gU({tournamentRecord:i,participants:r});Nr({element:o,extension:{name:Zi,value:n}})}else{const t=p[0]?.structureId,{positionAssignments:e}=rs({drawDefinition:o,structureId:t});if(e?.length){const{participants:t}=Zl({participantFilters:{participantTypes:[Qs]},tournamentRecord:i}),n=n=>{const r=n.tieMatchUps.filter((({matchUpType:t})=>t===Ks)),a=n.tieMatchUps.filter((({matchUpType:t})=>t===Zs));r.forEach(((n,r)=>{const a=n.matchUpId;n.sides.forEach((n=>{const{drawPosition:c}=n,u=t?.find((t=>{const{participantId:n}=t,r=e.find((t=>t.participantId===n));return r?.drawPosition===c}));if(u){const t=u.individualParticipantIds?.[r];t&&Wf({teamParticipantId:u.participantId,participantId:t,tournamentRecord:i,drawDefinition:o,tieMatchUpId:a,event:s})}}))})),a.forEach(((n,r)=>{const a=n.matchUpId;n.sides.forEach((n=>{const{drawPosition:c}=n,u=t?.find((t=>{const{participantId:n}=t,r=e.find((t=>t.participantId===n));return r?.drawPosition===c}));if(u){const t=u.individualParticipantIds?.slice(2*r,2*r+2);t?.forEach((t=>{Wf({teamParticipantId:u.participantId,participantId:t,tournamentRecord:i,drawDefinition:o,tieMatchUpId:a,event:s})}))}}))}))};p.forEach(n)}}}const m="string"==typeof n&&n,f=m&&Ea;for(const t of u){if(d>=a)break;const{matchUps:n}=Yp({matchUpFilters:{matchUpTypes:[Zs,Ks]},afterRecoveryTimes:!1,tournamentRecord:i,inContext:!0,drawDefinition:o,matchUpsMap:l,structure:t,event:s}),u=n.filter((({winningSide:t})=>!t)).sort(Il).map(ba);for(const n of u){if(!isNaN(a)&&d>=a)break;const{matchUps:u}=Yp({matchUpFilters:{matchUpTypes:[Zs,Ks]},afterRecoveryTimes:!1,tournamentRecord:i,inContext:!0,drawDefinition:o,matchUpsMap:l,structure:t,event:s}),p=u.find((t=>t.matchUpId===n)),h=[ka,Fa].includes(p.matchUpStatus);if(p?.readyToScore&&!h){const t=_v({winningSide:!r&&1,matchUpStatusProfile:e,tournamentRecord:i,drawDefinition:o,targetMatchUp:p,matchUpFormat:c,matchUpStatus:f,scoreString:m,event:s});if(t?.error)return t;d+=1}}}return{...E,completedCount:d}}function xv(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===Ma)return;const{matchUpId:p}=a||{},{outcome:l}=Ay({matchUpFormat:s,matchUpStatus:o,scoreString:c,winningSide:u});return e&&(l.matchUpStatusCodes=e),aU({tournamentRecord:r,policyDefinitions:n,drawDefinition:i,matchUpFormat:s,matchUpId:p,outcome:l,event:d})}function _v(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 xv(t);const{matchUpId:p}=s||{},{outcome:l}=Ov({matchUpStatusProfile:e,matchUpFormat:o,winningSide:u});return aU({policyDefinitions:r,tournamentRecord:n,drawDefinition:i,matchUpFormat:o,matchUpId:p,outcome:l,event:d})}function Lv({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:n,tournamentRecord:r,drawProfiles:i,event:a}){const o=Bd({event:a}).flightProfile,{eventName:s,eventType:c,category:u}=a,{startDate:d}=r,p=[],l=u?.categoryName||u?.ageCategoryCode||u?.ratingType,m=a.drawDefinitions?.map((({drawId:t})=>t));if(Array.isArray(o?.flights))for(const[u,f]of o.flights.entries()){const{drawId:o,stage:h,drawName:g,drawEntries:I}=f;p.push(f.drawId);const U=i[u],{seedsCount:S,generate:y=!0}=U||{};if(y){const p=I.filter(Ua(lp)).map(Ua(lp)),f=l||s;if(r&&S&&S<=p.length){w(1,S+1).forEach(((t,e)=>{const n={scaleValue:t,scaleName:f,scaleType:Fr,eventType:c,scaleDate:d},i=p[e];Dv({tournamentRecord:r,participantId:i,scaleItem:n})}))}if(m?.includes(o))break;let y=QS({...U,matchUpType:c,seedingScaleName:f,tournamentRecord:r,isMock:!0,drawEntries:I,drawName:g,drawId:o,event:a,stage:h});if(y.error)return{error:y.error,drawIds:[]};const{drawDefinition:v}=y;if(!v)return{error:q};const T=i[u]?.drawExtensions;if(Array.isArray(T)&&T.filter(br).forEach((t=>Nr({element:v,extension:t}))),y=hU({suppressNotifications:!0,tournamentRecord:r,drawDefinition:v,event:a}),y.error)return{error:y.error,drawIds:[]};if(U?.withPlayoffs){const t=v.structures?.[0].structureId,e=eU({idPrefix:U.idPrefix,...U.withPlayoffs,tournamentRecord:r,drawDefinition:v,isMock:!0,structureId:t,event:a});if(e?.error)return e}const P=U?.completionGoal;if(!(!1===U?.automated)&&(e||P)){const i=U?.matchUpFormat,o=kv({completeAllMatchUps:!P&&e,matchUpStatusProfile:t,randomWinningSide:n,tournamentRecord:r,completionGoal:P,drawDefinition:v,matchUpFormat:i,event:a});if(o.error)return{error:o.error,drawIds:[]};const s=o.completedCount;if(U?.drawType===qo){const o=v.structures?.find((t=>t.stage===Xa));if(!o)return{error:Ut};let c=tg({structureId:o.structureId,tournamentRecord:r,drawDefinition:v,event:a});if(c.error)return{error:c.error,drawIds:[]};if(c=kv({completeAllMatchUps:!P&&e,completionGoal:P?P?P-(s??0):void 0:void 0,matchUpStatusProfile:t,randomWinningSide:n,tournamentRecord:r,drawDefinition:v,matchUpFormat:i,event:a}),c.error)return{error:c.error,drawIds:[]}}}}}return{...E,drawIds:p}}function Bv(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=p===td&&sc||p===nd&&uc||p,m=n[Xa]||0,f=n[Qa]||0,h=a.drawProfiles?.length?m+f:a.participantsProfile?.participantsCount??0,g=[qp,Hp].includes(d)?d:void 0,I=e?.idPrefix?`E-${o}-${e?.idPrefix}`:void 0,{participants:U}=uv({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}),S=gU({tournamentRecord:i,participants:U});if(S.error)return S;const y=U?.filter((({participantType:t})=>t===l)),v=U?.map(Da);return{uniqueDrawParticipants:y,uniqueParticipantIds:v}}function Vv({autoEntryPositions:t,tournamentRecord:e,drawParticipants:n,drawProfile:r,event:i}){const{drawType:a=bo,qualifyingPositions:o=0,stage:s=Xa,drawSize:c=0,drawName:u,drawId:d}=r,p=c-o,l=n.slice(0,p).map(Da);if(l.length){const n=cm({participantIds:l,autoEntryPositions:t,entryStage:s,tournamentRecord:e,event:i});if(n.error)return n}const m=$U({drawName:u||a,qualifyingPositions:o,drawEntries:l.map((t=>({entryStatus:Hc,entryStage:s,participantId:t}))),drawId:d,event:i,stage:s});return m.error?m:{...E}}function jv({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=Xa,drawSize:l=0}=u,m=l-i,f=d||o||a||p===Qa,h=f?t.slice(c,c+m):n[p||Xa]||[];f&&(c+=m);const g=Vv({autoEntryPositions:e,drawParticipants:h,tournamentRecord:r,drawProfile:u,event:s});if(g.error)return g}return{...E}}function Gv(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,uuids:m}=t;let f=d.gender,h=d.eventName;const{eventType:g=td,policyDefinitions:I,drawProfiles:U=[],eventExtensions:S,surfaceCategory:y,tieFormatName:v,processCodes:w,discipline:T,eventLevel:P,timeItems:D,ballType:b,category:N}=d,R=d.eventId||Md(),M=d.tieFormat||(g===id?ES({namedFormat:v,event:{eventId:R,category:N,gender:f},hydrateCollections:o}):void 0),A=u.participants;for(const t of U)!f&&t.gender&&(f=t?.gender);const{stageParticipantsCount:E,uniqueParticipantsCount:C,uniqueParticipantStages:O}=Tv({drawProfiles:U,category:N,gender:f}),F=g===td&&sc||g===nd&&uc||g,{uniqueDrawParticipants:k=[],uniqueParticipantIds:x=[]}=O?Bv({event:{eventType:g,category:N,gender:f},uniqueParticipantsCount:C,participantsProfile:r,ratingsParameters:c,tournamentRecord:u,eventProfile:d,eventIndex:p,uuids:m}):{};let{eventAttributes:_}=d;"object"!=typeof _&&(_={});const L=N?.categoryName||N?.ageCategoryCode||N?.ratingType;h=h||L||"Generated Event";const B={..._,surfaceCategory:y,processCodes:w,discipline:T,eventLevel:P,eventName:h,eventType:g,tieFormat:M,ballType:b,category:N,eventId:R,gender:f};if(S?.length&&Array.isArray(S)){const t=S.filter(br);t?.length&&Object.assign(B,{extensions:t})}if(Array.isArray(D)&&D.forEach((t=>Bm({event:G,timeItem:t}))),"object"==typeof I)for(const t of Object.keys(I))uU({policyDefinitions:{[t]:I[t]},event:B});let V;B.category&&(B.category.categoryName=L);const j=OS({suppressNotifications:!1,internalUse:!0,tournamentRecord:u,event:B});if(j.error)return j;const G=j?.event,{stageParticipants:q}=Pv({allUniqueParticipantIds:e,stageParticipantsCount:E,eventParticipantType:F,targetParticipants:A});if(U?.length){const t=jv({uniqueDrawParticipants:k,autoEntryPositions:a,stageParticipants:q,tournamentRecord:u,drawProfiles:U,category:N,gender:f,event:G});if(t.error)return t;const e=Lv({matchUpStatusProfile:n,completeAllMatchUps:i,randomWinningSide:s,tournamentRecord:u,drawProfiles:U,event:G});if(e.error)return e;V=e.drawIds}else if(d?.participantsProfile?.participantsCount){const t=k.map(Ua("participantId"));if(t.length){const e=cm({participantIds:t,autoEntryPositions:a,tournamentRecord:u,entryStage:Xa,event:G});if(e.error)return e}}return l&&Wm({tournamentRecord:u,event:G}),{drawIds:V,eventId:R,uniqueParticipantIds:x}}function qv({tournamentRecords:t}){if(!ha(t))return{error:x};const e=Object.keys(t??{}).reduce(((e,n)=>{const r=t[n],{tournamentInfo:{startDate:i,endDate:a}}=jm({tournamentRecord:r}),o=i&&new Date(ri(i));(!e.startDate||o&&o<e.startDate)&&(e.startDate=o);const s=a&&new Date(ri(a));return(!e.endDate||s&&s>e.endDate)&&(e.endDate=s),e}),{startDate:void 0,endDate:void 0}),n=e.startDate&&ri(e.startDate.toISOString()),r=e.endDate&&ri(e.endDate.toISOString());return n&&r?{startDate:n,endDate:r}:{error:oe}}function $v({tournamentRecords:t,scheduleDate:e,venueId:n,round:r}){if(!Wr(e))return{error:pe};const{extension:i}=Mr({name:oa,tournamentRecords:t,discover:!0}),a=i?.value||[];let o=a.find((t=>fi(e,t.scheduleDate)));if(!o){const{startDate:n,endDate:r}=qv({tournamentRecords:t}),i=new Date(e);if(n&&i<new Date(n)||r&&i>new Date(r))return{error:pe};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=>ha(t[e])?u(t[e]):t[e])).flat().join("|");if(s.rounds.find((t=>u(t)===u(r))))return wr({result:{error:gt},stack:"addSchedulingProfileRound"});s.rounds.push(r);const d=Fm({tournamentRecords:t,schedulingProfile:a});return d.error?d:{...E}}function Wv(t){const{allUniqueParticipantIds:e=[],participantsProfile:n={},matchUpStatusProfile:r,completeAllMatchUps:i,autoEntryPositions:o,hydrateCollections:s,randomWinningSide:c,ratingsParameters:u,tournamentRecord:d,isMock:p=!0,drawProfile:l,startDate:m,drawIndex:f,uuids:h}=t,g=gi(l,!1,!0),{excessParticipantAlternates:I=!0,matchUpFormat:U=lg,drawType:S=bo,tournamentAlternates:y=0,alternatesCount:v=0,qualifyingPositions:T,qualifyingProfiles:D,generate:b=!0,eventExtensions:N,drawExtensions:R,completionGoal:M,tieFormatName:A,seedsCount:C,timeItems:O,drawName:F,category:k,idPrefix:x,publish:_,gender:L,stage:B}=g,V=g.drawSize||(g.ignoreDefaults?void 0:32),j=g.eventId||Md(),G=l.eventType||l.matchUpType||td,$=G===nd?uc:sc,W="object"==typeof l.tieFormat&&l.tieFormat||G===dc&&ES({namedFormat:A,event:{eventId:j,category:k,gender:L},hydrateCollections:s})||void 0,H=k?.categoryName||k?.ageCategoryCode||k?.ratingType,z=l.eventName||H||`Generated ${G}`;let Y=d?.participants||[];const K=(D?.map((t=>t.structureProfiles||[])).flat().reduce(((t,e)=>t+(!e.participantsCount||e.participantsCount>e.drawSize?e.drawSize:e.participantsCount||0)),0)||0)*($===uc?2:1),J=(!l.participantsCount||l.participantsCount>V?V:l.participantsCount)||0,Z={eventName:z,eventType:G,tieFormat:W,category:k,eventId:j,gender:L};Array.isArray(O)&&O.forEach((t=>Bm({event:Z,timeItem:t})));let{eventAttributes:X}=l;if("object"!=typeof X&&(X={}),Object.assign(Z,X),N?.length&&Array.isArray(N)){const t=N.filter(br);t?.length&&Object.assign(Z,{extensions:t})}const Q=[];if(K||l.uniqueParticipants||!d||L||k){const t=(J||0)+v+K;let e=t;const r={[qp]:0,[Hp]:0};let i,a;G===dc&&(({teamSize:i,genders:a}=lv({alternatesCount:v,tieFormatName:A,tieFormat:W,drawSize:V})),Object.keys(a).forEach((t=>{[qp,Hp].includes(t)&&a[t]&&(r[t]=V*a[t])})),e=i*((V||0)+K));const o=n?.idPrefix?`D-${f}-${n?.idPrefix}`:void 0,s=uv({...n,scaledParticipantsCount:l.scaledParticipantsCount||n.scaledParticipantsCount,participantsCount:e,consideredDate:d?.startDate,sex:L||n?.sex,rankingRange:l.rankingRange,uuids:l.uuids||h,ratingsParameters:u,participantType:$,gendersCount:r,idPrefix:o,category:k}).participants;if(Z.category&&(Z.category.categoryName=H),d){const t=gU({participants:s,tournamentRecord:d});if(t.error)return t}if(s.forEach((({participantId:t})=>Q.push(t))),Y=s,G===dc){const e=a[qp]?s.filter((({participantType:t,person:e})=>t===sc&&e?.sex===qp)).map(Da):[],n=a[Hp]?s.filter((({participantType:t,person:e})=>t===sc&&e?.sex===Hp)).map(Da):[],r=s.filter((({participantType:t})=>t===sc)).map(Da).filter((t=>!e.includes(t)&&!n.includes(t))),o=i-(a[qp]+a[Hp]);let c=0,u=0,p=0;const l=w(0,t).map((t=>{const i=n.slice(c,c+a[Hp]),s=e.slice(u,u+a[qp]),d=r.slice(p,p+o);return c+=a[Hp],u+=a[qp],p+=o,{individualParticipantIds:[...i,...s,...d],participantOtherName:`TM${t+1}`,participantName:`Team ${t+1}`,participantRole:um,participantType:dc,participantId:Md()}})),m=gU({participants:l,tournamentRecord:d});if(!m.success)return m;Y=l}}const tt=t=>{const{participantType:e}=t;return G===td&&e===sc||(G===nd&&e===uc||G===dc&&e===dc)},et=t=>!l.gender||(t.person?.sex===l.gender||t.individualParticipantIds?.some((t=>{const e=Y.find((e=>e.participantId===t));return e&&et(e)}))),nt=Y.filter(tt).filter(et).filter((({participantId:t})=>!e.includes(t))),rt=nt.slice(0,J).map((t=>t.participantId));if(p&&rt?.length){const t=cm({autoEntryPositions:o,entryStage:B,tournamentRecord:d,participantIds:rt,event:Z});if(t.error)return t}const it=K?nt.slice(J,J+K).map((t=>t.participantId)):0;if(p&&it?.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,s=1;for(const c of i.structureProfiles.sort(n)){const n=(c.drawSize||a(c.participantsCount))-(r||0),i=it.slice(t,t+n),u=cm({entryStage:Qa,entryStageSequence:s,autoEntryPositions:o,tournamentRecord:d,participantIds:i,roundTarget:e,event:Z});if(u.error)return u;r=c.qualifyingPositions,t+=n,s+=1}e+=1}}const at=I&&d?.participants?.filter((({participantId:t})=>!rt.includes(t))).filter(tt).filter(et).slice(0,v||V-J||y).map((t=>t.participantId));if(p&&at?.length){const t=cm({participantIds:at,autoEntryPositions:!1,entryStatus:$c,tournamentRecord:d,event:Z});if(t.error)return t.error}const ot=H||z;if(d&&C&&C<=rt.length){w(1,C+1).forEach(((t,e)=>{const n={scaleName:ot,scaleDate:m,scaleType:$u,scaleValue:t,eventType:G},r=rt[e];Dv({tournamentRecord:d,participantId:r,scaleItem:n})}))}const st=QS({...gi(l,!1,!0),tournamentRecord:d,seedingScaleName:ot,matchUpFormat:U,eventId:j,isMock:p,event:Z});if(st.error)return st;if(!st.drawDefinition)return{error:q};const{drawDefinition:ct}=st,ut=ct.drawId;if(Array.isArray(R)&&R.filter(br).forEach((t=>Nr({element:ct,extension:t}))),b){if(hU({drawDefinition:ct,event:Z,suppressNotifications:!0}),l.withPlayoffs){const t=ct.structures?.[0].structureId,e=eU({...l.withPlayoffs,tournamentRecord:d,drawDefinition:ct,structureId:t,idPrefix:x,isMock:p,event:Z});if(e?.error)return e}const t=!1===l.automated;if(p&&!t){const t=t=>{const e=kv({completeAllMatchUps:t.completeAllMatchUps,completionGoal:t.completionGoal,matchUpStatusProfile:r,randomWinningSide:c,tournamentRecord:d,drawDefinition:ct,matchUpFormat:U,event:Z});if(e.error)return e;const n=e.completedCount;if(S===qo){const t=ct.structures?.find((t=>t.stage===Xa));if(!t)return{error:Ut};tg({structureId:t.structureId,tournamentRecord:d,drawDefinition:ct,event:Z});const e=kv({completionGoal:M?M?M-(n??0):void 0:void 0,matchUpStatusProfile:r,completeAllMatchUps:i,randomWinningSide:c,tournamentRecord:d,drawDefinition:ct,matchUpFormat:U,event:Z});if(e.error)return e}};if(M&&t({completionGoal:M}),l.outcomes){const{matchUps:t}=Ul({inContext:!0,drawDefinition:ct,event:Z});for(const e of l.outcomes){const{matchUpStatus:n=Ea,matchUpStatusCodes:r,stageSequence:i=1,matchUpIndex:a=0,structureOrder:o,matchUpFormat:s,drawPositions:c,roundPosition:u,stage:p=Xa,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!==P(c,t.drawPositions).length))),U=I?.[a],S=xv({matchUpStatusCodes:r,tournamentRecord:d,drawDefinition:ct,targetMatchUp:U,matchUpFormat:s,matchUpStatus:n,scoreString:f,winningSide:m});if(S?.error)return S}}i&&t({completeAllMatchUps:i})}_&&Wm({tournamentRecord:d,event:Z})}else{const t=$U({drawEntries:ct.entries,drawName:F||S,qualifyingPositions:T,drawId:ut,event:Z,stage:B});if(t.error)return t}return{...E,event:vr(Z),uniqueParticipantIds:Q,targetParticipants:Y,drawDefinition:ct,eventId:j,drawId:ut}}const Hv=["Mock Tournament","CourtHive Challenge","Racket Rally","Generated Tournament","Factory Follies","Open Competition"];function zv(){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 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 "}const Yv={generateOutcomeFromScoreString:Ay,anonymizeTournamentRecord:function({keepExtensions:t=[],anonymizeParticipantNames:e=!0,tournamentRecord:n,tournamentName:r,personIds:i=[],tournamentId:a}){if(!n)return{error:_};const o=Array.isArray(t)?pa.concat(...t):pa,s=e=>Array.isArray(t)?e?.extensions?.filter((t=>o.includes(t.name))):e?.extensions,c={};n.extensions=s(n);const u=a||Md();c[n.tournamentId]=u,n.tournamentId=u,n.createdAt=(new Date).toISOString(),n.tournamentName=r||`Anonymized: ${zr(new Date)}`,delete n.parentOrganisation;for(const t of n.participants||[]){const e=Md();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.extensions=s(t),t.venueName=`Venue #${d}`,t.venueAbbreviation=`V${d}`;const e=Md();c[t.venueId]=e,d+=1}let p=1;for(const t of n.events||[]){t.extensions=s(t);const e=Md();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=Md();if(c[e.drawId]=t,e.drawId=t,Array.isArray(e.entries))for(const t of e.entries)t.participantId=c[t.participantId];const n=t=>{t.extensions=s(t);const e=Md();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||[])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}=Mr({name:Ki,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||zr(new Date),m=(n.participants||[]).filter((({participantType:t})=>t===sc)),f=m.reduce(((t,e)=>{const n=e.person?.sex;return[qp,Hp].includes(n)?t[n]+=1:t[Wp]+=1,t}),{[qp]:0,[Hp]:0,[Wp]:0}),h=Object.assign({},...Object.keys(f).map((t=>({[t]:Ty({category:{ageCategoryCode:"O18"},count:f[t],addressProps:{citiesCount:10},personExtensions:[],consideredDate:l,sex:t})?.persons||[]})))),g={[qp]:0,[Hp]:0,[Wp]: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:[]}),S=U.postalCodes.length,y=U.cities.length,v=U.states.length,{cities:w}=Uy({count:y||I,participantsCount:I}),{states:T}=Sy({count:v||I,participantsCount:I}),{postalCodes:P}=yy({count:S||I,participantsCount:I}),D={cities:w,states:T,postalCodes:P};m.forEach(((t,n)=>{const r=t?.person,a=r?.sex||Wp,o=ri(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=Py({...D,participantIndex:n,nationalityCode:d.nationalityCode});d.addresses=[t]}d.personId=i?.[n]||Md(),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===uc)).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===dc)),N=by({count:b.length}).names;b.forEach(((t,e)=>{t.participantName=N[e]}));const R=(n.participants||[]).filter((({participantType:t})=>t===cc)),M=by({count:R.length,nameRoot:"Group"}).names;R.forEach(((t,e)=>{t.participantName=M[e]}));const{extension:A}=Mr({element:n,name:oa});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:C}=Mr({element:n,name:ea});return Array.isArray(C?.value)&&C?.value.forEach((t=>{t.personId=c[t.personId]})),{...E}},generateTournamentRecord:function(t){let{tournamentAttributes:e,startDate:n,endDate:r}=t;const{tournamentName:i=y(Hv),ratingsParameters:a=MU,scheduleCompletedMatchUps:o,tournamentExtensions:s,matchUpStatusProfile:c,completeAllMatchUps:u,participantsProfile:d,autoEntryPositions:p,hydrateCollections:l,randomWinningSide:f,policyDefinitions:h,schedulingProfile:g,periodLength:I,autoSchedule:U,eventProfiles:S,venueProfiles:v,drawProfiles:w,uuids:T}=t;if(n&&!Wr(n)||r&&!Wr(r))return{error:pe};if(S&&!Array.isArray(S))return{error:Nn};if(!n){const t=new Date;n=zr(r??t),r=zr(t.setDate(t.getDate()+7))}if(!r){const t=new Date(n);r=zr(t.setDate(t.getDate()+7))}"object"!=typeof e&&(e={});const D=sv({...e,tournamentName:i,startDate:n,endDate:r});if(s?.length&&Array.isArray(s)){const t=s.filter((t=>br({extension:t})));t?.length&&Object.assign(D,{extensions:t,isMock:!0})}if("object"==typeof h)for(const t of Object.keys(h))uU({policyDefinitions:{[t]:h[t]},tournamentRecord:D});const b=mv({participantsProfile:d,tournamentRecord:D,eventProfiles:S,drawProfiles:w,startDate:n,uuids:T});if(!b.success)return b;const N=[],R=[],M=[];if(Array.isArray(w)){let t=0;for(const e of w){let r=Wv({allUniqueParticipantIds:N,matchUpStatusProfile:c,participantsProfile:d,completeAllMatchUps:u,autoEntryPositions:p,hydrateCollections:l,randomWinningSide:f,ratingsParameters:a,tournamentRecord:D,isMock:!0,drawProfile:e,startDate:n,drawIndex:t,uuids:T});if(r.error)return r;const{drawId:i,eventId:o,event:s,uniqueParticipantIds:m}=r;if(r=OS({suppressNotifications:!1,internalUse:!0,tournamentRecord:D,event:s}),r.error)return r;i&&M.push(i),R.push(o),m?.length&&N.push(...m),t+=1}}if(S){let t=0;for(const e of S){const r=Gv({allUniqueParticipantIds:N,matchUpStatusProfile:c,participantsProfile:d,completeAllMatchUps:u,autoEntryPositions:p,hydrateCollections:l,randomWinningSide:f,ratingsParameters:a,tournamentRecord:D,eventProfile:e,eventIndex:t,startDate:n,uuids:T});if(r.error)return r;const{eventId:i,drawIds:o,uniqueParticipantIds:s}=r;o&&M.push(...o),R.push(i),s?.length&&N.push(...s),t+=1}}const A=v?.length?wv({tournamentRecord:D,venueProfiles:v,uuids:T}):[];let C,O={};if(g){const t=function({schedulingProfile:t,tournamentRecord:e}){if("object"!=typeof t)return{error:Nn};const n=qs({tournamentRecord:e}).containedStructures,r=hl({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!==P(n,e).length&&(m(n).length!==m(e).length||P(n,e).length!==m(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=$v({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:g,tournamentRecord:D});if(t.error)return t;if(C=t.scheduledRounds,U){const{tournamentId:t}=D;O=ov({scheduleCompletedMatchUps:o,tournamentRecords:{[t]:D},periodLength:I})}}return or(),vr({...E,tournamentRecord:D,scheduledRounds:C,schedulerResult:O,eventIds:R,venueIds:A,drawIds:M})},modifyTournamentRecord:function(t){const{ratingsParameters:e=MU,participantsProfile:n={},matchUpStatusProfile:r,completeAllMatchUps:i,autoEntryPositions:a,hydrateCollections:o,randomWinningSide:s,schedulingProfile:c,tournamentRecord:u,eventProfiles:d,periodLength:p,venueProfiles:l,autoSchedule:m,drawProfiles:f,uuids:h}=t;if(!u)return{error:_};const g=[],I=[],U=[];d?.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 y=mv({startDate:u.startDate,participantsProfile:n,tournamentRecord:u,eventProfiles:d,drawProfiles:f,uuids:h});if(!y.success)return y;if(d){let t=u.events?.length||0;for(const e of d){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=p===td&&sc||p===nd&&uc||p;if(l){const{stageParticipantsCount:m,uniqueParticipantsCount:I,uniqueParticipantStages:S}=Tv({drawProfiles:l,category:d,gender:t}),{uniqueDrawParticipants:y=[],uniqueParticipantIds:v=[]}=S?Bv({event:{eventType:p,category:d,gender:t},uniqueParticipantsCount:I,participantsProfile:n,ratingsParameters:o,tournamentRecord:u,eventProfile:e,uuids:h}):{};g.push(...v);const{stageParticipants:w}=Pv({targetParticipants:u.participants||[],allUniqueParticipantIds:g,stageParticipantsCount:m,eventParticipantType:f});let T=jv({uniqueDrawParticipants:y,autoEntryPositions:a,stageParticipants:w,tournamentRecord:u,drawProfiles:l,category:d,gender:t,event:c});if(T.error)return T;if(T=Lv({matchUpStatusProfile:r,completeAllMatchUps:i,randomWinningSide:s,tournamentRecord:u,drawProfiles:l,event:c}),T.error)return T;U.push(...T.drawIds)}m&&Wm({tournamentRecord:u,event:c})}else{const c=Gv({startDate:u.startDate,allUniqueParticipantIds:g,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:i,autoEntryPositions:a,randomWinningSide:s,ratingsParameters:o,tournamentRecord:u,eventProfile:e,eventIndex:t,uuids:h});if(c.error)return c;const{eventId:d,drawIds:p,uniqueParticipantIds:l}=c;p&&U.push(...p),I.push(d),l?.length&&g.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=Wv({startDate:u.startDate,allUniqueParticipantIds:g,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:i,autoEntryPositions:a,hydrateCollections:o,randomWinningSide:s,ratingsParameters:e,tournamentRecord:u,drawProfile:c,drawIndex:t,uuids:h});if(d.error)return d;const{drawId:p,eventId:l,event:m,uniqueParticipantIds:f}=d;if(d=OS({tournamentRecord:u,event:m,internalUse:!0}),d.error)return d;p&&U.push(p),I.push(l),f?.length&&g.push(...f),t+=1}}const v=l?.length?wv({tournamentRecord:u,venueProfiles:l}):[];let w={};if(c?.length){const t=Fm({tournamentRecords:{[u.tournamentId]:u},schedulingProfile:c});if(t.error)return t;if(m){const{tournamentId:t}=u;w=ov({tournamentRecords:{[t]:u},periodLength:p})}}return{totalParticipantsCount:u.participants.length,scheduledRounds:undefined,schedulerResult:w,...E,eventIds:I,venueIds:v,drawIds:U}},generateEventWithDraw:Wv,generateParticipants:uv,parseScoreString:My,generateOutcome:Ov,credits:zv};function Kv({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=vm(e?.standardGivenName??""),s=vm(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 Jv({participantMap:t,participant:e,formats:n}){const{participantType:r,individualParticipantIds:i,person:a}=e,o=r&&n[r];if(r!==oc&&o){const{personFormat:n,doublesJoiner:s}=o;r===sc&&(e.participantName=Kv({person:a,personFormat:n})),r===uc&&(e.participantName=i?.map((e=>{const r=t[e]?.person;return Kv({person:r,personFormat:n})})).filter(Boolean).join(s??"/"))}}function Zv({tournamentRecord:t,penaltyId:e}){if(!t)return{error:_};if(!e)return{error:Ze};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&&sr({topic:Ss,payload:{tournamentId:t.tournamentId,participants:n}}),r?{...E,penalty:r}:{error:Xe}}const Xv=({penaltyId:t=Md()}={})=>({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 Qv({tournamentRecord:t,modifications:e,penaltyId:n}){if(!t)return{error:_};if(!e)return{error:Nn,modifications:e};if(!n)return{error:Ze};const r=t?.participants??[],i=Object.keys(Xv()).filter((t=>"penaltyId"!==t)),a=Object.keys(e).filter((t=>i.includes(t)));if(!a.length)return{error:En};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&&sr({topic:Ss,payload:{tournamentId:t.tournamentId,participants:s}}),o?{...E,penalty:o}:{error:Xe}}function tw(t,e,n){if(!t&&e)return e;if(t&&!e)return t;if("object"!=typeof t||"object"!=typeof e)return t;return m(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=m(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]=tw(t[i],e[i],n):r[i]=e[i];else r[i]=e[i];else r[i]=t[i];return r}),{})}function ew({refereeParticipantId:t,tournamentRecord:e,participantIds:n,penaltyCode:r,penaltyType:i,extensions:a,penaltyId:o,matchUpId:s,issuedAt:c,notes:u}){if(!e)return{error:_};if(!n)return{error:Ae};if(!i)return{error:Je};const d=(e?.participants??[]).filter((t=>n.includes(t.participantId)));if(!d.length)return{error:Ee};const p=(new Date).toISOString(),l=Object.assign(Xv({penaltyId:o}),{refereeParticipantId:t,penaltyCode:r,penaltyType:i,matchUpId:s,notes:u,issuedAt:c,createdAt:p});return Array.isArray(a)&&a.forEach((t=>Nr({element:l,extension:t}))),d.forEach((t=>{t.penalties||(t.penalties=[]),t.penalties.push(l)})),sr({topic:Ss,payload:{tournamentId:e.tournamentId,participants:d}}),{...E,penaltyId:l.penaltyId}}const nw={addIndividualParticipantIds:qf,addParticipant:Bf,addParticipants:gU,addPenalty:function(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=Zl({tournamentRecord:e}).participants??[],a=r?.map(Ua("participantId")).filter((t=>n.includes(t)));if(a.length){i=ew({...t,penaltyId:t.penaltyId??i,tournamentRecord:e,participantIds:a}).penaltyId}}return i?{...E,penaltyId:i}:{error:Ee}},addPersons:function({participantRole:t=um,tournamentRecord:e,persons:n}){if(!e)return{error:_};if(!Array.isArray(n))return{error:Nn};if(!Object.keys(lm).includes(t))return{error:De};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=Md()),i.push(t.personId),t)));let o=0,s=0,c=gU({participants:a.map((e=>{return vr({extensions:e.participantExtensions,timeItems:e.participantTimeItems,participantType:sc,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=Zl({participantFilters:{participantTypes:[sc]},tournamentRecord:e})?.participants??[];if(t===um&&n.filter((({pairedPersons:t})=>t)).forEach((({personId:t,pairedPersons:e})=>{Array.isArray(e)&&e.forEach((e=>{const n=[t,e.personId].map((t=>Fi({tournamentParticipants:d,personId:t}))).filter(Boolean);if(2===n.length){const t=n.map(Da);u.push(vr({extensions:e.participantExtensions,timeItems:e.timeItems,participantRole:um,individualParticipantIds:t,participantType:uc}))}}))})),u.length){if(c=gU({participants:u,tournamentRecord:e}),c.error)return c;o=c.addedCount||0}const p=s+o;return{...E,addedCount:p,newPersonIds:i}},createGroupParticipant:function({individualParticipantIds:t=[],participantRoleResponsibilities:e,participantRole:n=pm,tournamentRecord:r,participantId:i,groupName:a}){if(!r)return{error:_};if(!a)return{error:ae,info:"Missing groupName"};if(!Array.isArray(t))return{info:"Invalid individualParticipantIds",error:Nn};const o=(Zl({participantFilters:{participantTypes:[sc]},tournamentRecord:r}).participants??[]).map((t=>t.participantId));for(const e of t)if(!o.includes(e))return{error:be,participantId:e};const s=vr({participantId:i||Md(),participantRoleResponsibilities:e,participantName:a,individualParticipantIds:t,participantType:cc,participantRole:n}),c=Bf({participant:s,tournamentRecord:r});if(c.error)return c;const{topics:u}=lr();return u.includes(ss)&&sr({topic:ss,payload:{tournamentId:r.tournamentId,participants:[s]}}),{...E,participant:gi(s)}},createTeamsFromParticipantAttributes:cv,deleteParticipants:gm,filterParticipants:Kl,mergeParticipants:function({participants:t=[],tournamentRecord:e,arraysToMerge:n}){if(!e)return{error:_};e.participants||(e.participants=[]);const r=t.filter(Ua(lp)).map((t=>({[t.participantId]:t}))),i=Object.assign({},...r),a=[];e.participants=e.participants.map((t=>{if(i[t.participantId]){const e=tw(t,i[t.participantId],n);return a.push(e),e}return t}));const o=e.participants.map(Ua(lp))||[],s=t.filter((({participantId:t})=>!o.includes(t))),{topics:c}=lr();return s.length&&(e.participants=e.participants.concat(...s),c.includes(ss)&&sr({topic:ss,payload:{participants:s}})),a.length&&c.includes(Ss)&&sr({topic:Ss,payload:{tournamentId:e.tournamentId,participants:a}}),{modifiedParticipantsCount:a.length,newParticipantsCount:s.length,...E}},modifyIndividualParticipantIds:function({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}){const r="modifyIndividualParticipantIds";if(!n)return wr({result:{error:_},stack:r});if(!e||!t)return wr({result:{error:ae},stack:r});const i=n.participants||[],a=i.find((t=>t.participantId===e));if(!a)return wr({result:{error:Ee},stack:r});if(![dc,cc].includes(a.participantType))return wr({result:{error:be},context:{participantType:a.participantType},stack:r});const o=t.filter((t=>{const e=i.find((e=>e.participantId===t));return e?.participantType!==sc}));if(o.length)return wr({result:{error:Pe,invalidParticipantIds:o},stack:r});const s=a.individualParticipantIds||[],c=t.filter((t=>!s.includes(t))),u=s.filter((e=>!t.includes(e))),d=qf({individualParticipantIds:c,groupingParticipantId:e,tournamentRecord:n});if(d.error)return wr({result:d,stack:r});const p=mm({individualParticipantIds:u,groupingParticipantId:e,tournamentRecord:n});if(p.error)return wr({result:p,stack:r});const{topics:l}=lr();if(l.includes(Ss)){const t=i.find((({participantId:t})=>t===e));sr({topic:Ss,payload:{tournamentId:n.tournamentId,participants:[t]}})}return{...d,...p}},modifyParticipant:$f,modifyParticipantName:function({tournamentRecord:t,participantName:e,participantId:n}){if(!t)return{error:_};if(!n)return{error:Ae};if(!e)return{error:ae,info:"Missing participantName"};const{participant:r}=rl({tournamentRecord:t,participantId:n});if(!r)return{error:Ee};r.participantName=e;const{topics:i}=lr();return i.includes(Ss)&&sr({topic:Ss,payload:{tournamentId:t.tournamentId,participants:[r]}}),{...E}},modifyParticipantOtherName:function({tournamentRecord:t,participantId:e,participantOtherName:n}){if(!t)return{error:_};if(!e)return{error:Ae};const{participant:r}=rl({tournamentRecord:t,participantId:e});if(!r)return{error:Ee};r.participantOtherName=n;const{topics:i}=lr();return i.includes(Ss)&&sr({topic:Ss,payload:{tournamentId:t.tournamentId,participants:[r]}}),{...E}},modifyParticipantsSignInStatus:function({tournamentRecord:t,participantIds:e,signInState:n}){if(!t)return{error:_};if(!Array.isArray(e))return{error:ae};if(![ac,ic].includes(n))return{error:Nn,signInState:n};const r=t.participants||[];if(!r.length)return{error:Me};const i=r.map(Da),a=e.filter((t=>!i.includes(t)));if(a.length)return{error:Nn,context:{invalidParticipantIds:a}};const o=[],s=(new Date).toISOString();for(const i of r){const{participantId:r}=i;if(e.includes(r)){const e=_m({duplicateValues:!1,tournamentRecord:t,participantId:r,timeItem:{itemType:rc,itemValue:n,createdAt:s}});if(e.error)return e;o.push(i)}}const{topics:c}=lr();return o.length&&c.includes(Ss)&&sr({topic:Ss,payload:{tournamentId:t.tournamentId,participants:o}}),{...E}},modifyPenalty:function(t){const{tournamentRecords:e}=t;if("object"!=typeof e||!Object.keys(e).length)return{error:x};for(const n of Object.values(e)){const e=Qv({...t,tournamentRecord:n});if(e.error&&e.error!==Xe)return e;if(e.success)return e}return{error:Xe}},regenerateParticipantNames:function({tournamentRecord:t,formats:e}){if(!t)return{error:_};if(!ha(e))return{error:ae};const n=t.participants??[],r=Ia(n,"participantId");for(const t of n)Jv({participant:t,participantMap:r,formats:e});return{...E}},removeIndividualParticipantIds:mm,removeParticipantIdsFromAllTeams:hm,removePenalty:function(t){const{tournamentRecords:e}=t;if("object"!=typeof e||!Object.keys(e).length)return{error:x};for(const n of Object.values(e)){const e=Zv({...t,tournamentRecord:n});if(e.error&&e.error!==Xe)return e}return{...E}},scaledTeamAssignment:function({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:l}){if(!o)return{error:_};if(!Array.isArray(a)&&!p(u)&&!d||!p(r)||i&&!Array.isArray(i)||s&&("object"!=typeof s||!Object.keys(s).length))return{error:Nn};if(!s&&!i.length||!i&&(!e||!s))return{error:ae,info:"Missing scaling details"};if(d&&!a){if(l?.eventType!==ad)return{error:wt};a=l?.entries?.filter((({entryStatus:t})=>t===Hc)).map(Da)}if(!a?.length&&!u)return{info:"Missing teamParticipantIds or teamsCount",error:ae};let m=e??i.map((({participantId:t})=>t));n&&(a?.reverse(),r+=1),r>(a?.length||0)-1&&(r=0);const f=a?.slice(r).concat(...a.slice(0,r))??[],h=[];for(const t of o.participants??[]){const{participantId:e,participantType:n}=t;if(f.includes(e)){if(n!==oc)return{error:be,participant:t};h.push(t)}}if(u&&h.length<u){const t=c??"Team",e=w(0,u-(h?.length||0)).map((e=>({participantName:`${t} ${e+1}`,participantType:oc,participantRole:um}))),{participants:n=[]}=gU({participants:e,returnParticipants:!0,tournamentRecord:o}),r=n.map(Da),i=o.participants?.filter((({participantId:t})=>r.includes(t)))??[];h.push(...i)}if(!h.length)return{error:Mn};if(t)for(const t of h)t.individualParticipantIds=[];else{const t=h.map((t=>t)).flat();e?.length?m=m.filter((e=>!t.includes(e))):i=i?.filter((({participantId:e})=>!t.includes(e)))}if(!e?.length&&!i?.length)return{error:vn,info:"Nothing to be done"};if(!i.length){for(const t of o.participants??[]){const{participantId:e,participantType:n}=t;if(!m.includes(e))continue;if(n!==sc)return{error:be,participant:t};const r=Vl({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:Ee}}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:Nn,scaledParticipant:t};let g=0;for(;g<i.length;){for(const t of h){if(g+1>i.length)break;const e=i[g];t.individualParticipantIds.push(e.participantId),g++}h.reverse()}const I=h.map(Da);for(const t of o.events??[]){if(t.eventType!==ad)continue;const e=(t.entries??[]).filter((t=>I.includes(t.participantId)));for(const n of e){const e=n.participantId,r=h.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}=Bd({event:t});(a?.flights||[]).forEach((t=>{t.drawEntries=(t.drawEntries||[]).filter((t=>!i.includes(t.participantId)))}))}}return{...E,scaledParticipants:i}},setParticipantScaleItem:Dv,setParticipantScaleItems:function(t){const{scaleItemsWithParticipantIds:e=[],removePriorValues:n,tournamentRecord:r,auditData:i,context:a}=t;if(!r)return{error:_};if(!r.participants)return{error:Me};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(!bv({scaleItem:n}))return{error:In};Array.isArray(s[e])||(s[e]=[]),s[e].push(n)}}r.participants.forEach((t=>{const{participantId:e}=t||{};Array.isArray(s[e])&&s[e].forEach((e=>{Nv({participant:t,scaleItem:e,removePriorValues:n}),c.push(t),o++}))}));const u=o?void 0:Sn,{topics:d}=lr();if(d.includes(Ss)&&o&&sr({topic:Ss,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:cs,itemValue:n};if(i&&(a.itemSubTypes=i),e||t){const{drawDefinition:n,event:i}=Vd({tournamentRecord:r,eventId:t,drawId:e});e&&RI({drawDefinition:n,timeItem:a}),t&&Bm({event:i,timeItem:a})}else Lm({tournamentRecord:r,timeItem:a})}}return i&&d.includes(ds)&&sr({topic:ds,payload:i}),vr({...E,modificationsApplied:o,info:u})}};function rw(t,e){const n=Dc(t).appliedPolicies??{};if(n[t.policyType]){if(delete n[t.policyType],Object.keys(n).length){Nr({element:e,extension:{name:Vi,value:n}})}else Dr({element:e,name:Vi});return{...E}}return{error:ee}}const iw={attachPolicies:uU,removePolicy:function(t){const e=Lp(t,[{policyType:!0,_anyOf:{[sp]:!0,[up]:!0,[dp]:!0,[Rp]:!0}}]);if(e.error)return e;let n;const r=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(r)return rw(t,r);if(!t.tournamentRecords)return{error:_};{const e=Object.keys(t.tournamentRecords);if(!e.length)return{error:_};for(const r of e){const e=rw(t,t.tournamentRecords[r]);if(e.error)return e;n=!0}}return n?{...E}:{error:ee}}};function aw({removePriorValues:t=!0,tournamentRecord:e,status:n=Hu}){if(!e)return{error:_};const r=`${Wu}.${zu}`,{timeItem:i}=il({element:e,itemType:r}),a=i?.itemValue||{[n]:{}};a[n]&&delete a[n].orderOfPlay;return xm({timeItem:{itemValue:a,itemType:r},element:e,removePriorValues:t}),sr({topic:As,payload:{tournamentId:e.tournamentId}}),{...E}}function ow({scheduledDates:t=[],removePriorValues:e,tournamentRecord:n,status:r=Hu,eventIds:i=[]}){if(!n)return{error:_};const a=`${Wu}.${zu}`,{timeItem:o}=il({element:n,itemType:a}),s=o?.itemValue||{[r]:{}};s[r].orderOfPlay={published:!0,scheduledDates:t,eventIds:i};return xm({timeItem:{itemValue:s,itemType:a},element:n,removePriorValues:e}),sr({topic:Ns,payload:{tournamentId:n.tournamentId,scheduledDates:t,eventIds:i}}),{...E}}const sw={getTournamentInfo:jm,getVenueData:kd,getCourtInfo:Fd,getAllEventData:function({tournamentRecord:t,policyDefinitions:e}){if(!t)return{error:_};const n=t.events||[],r=t?.participants||[],{tournamentInfo:i}=jm({tournamentRecord:t}),{venues:a}=Am({tournamentRecord:t});return{allEventData:{tournamentInfo:i,venuesData:a,eventsData:n.map((n=>{const{eventId:i}=n,a=(({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}))(n),o=Qu({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}=Zp({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=Gl({event:n});return Object.assign(a,{drawsData:s,publish:c}),a}))}}},getEventData:$m,getDrawData:qm,unPublishEventSeeding:function({removePriorValues:t=!0,seedingScaleNames:e,tournamentRecord:n,status:r=Hu,drawIds:i,stages:a,event:o}){if(!n)return{error:_};if(!o)return{error:Tt};const s=Gl({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),Vm({statusObject:{seeding:n},removePriorValues:t,status:r,event:o})}return sr({topic:Ms,payload:{tournamentId:n.tournamentId,eventId:o.eventId}}),{...E}},publishEventSeeding:function({removePriorValues:t=!0,stageSeedingScaleNames:e,seedingScaleNames:n,tournamentRecord:r,status:i=Hu,drawIds:a=[],event:o}){if(!r)return{error:_};if(!o)return{error:Tt};const s=Gl({event:o,status:i}),c=(s?.seeding?.seedingScaleNames||n)&&{...s?.seeding?.seedingScaleNames,...n};return Vm({statusObject:{seeding:vr({stageSeedingScaleNames:(s?.seeding?.stageSeedingScaleNames||e)&&{...s?.seeding?.stageSeedingScaleNames,...e},seedingScaleNames:c,published:!0,drawIds:a})},removePriorValues:t,status:i,event:o}),sr({topic:bs,payload:{tournamentId:r.tournamentId,eventId:o.eventId,drawIds:a}}),{...E}},setEventDisplay:function({removePriorValues:t,tournamentRecord:e,displaySettings:n,status:r=Hu,event:i}){if(!e)return wr({result:{error:_}});if(!i)return wr({result:{error:Tt}});if(!ha(n))return wr({result:{error:ae}});if(ha(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=>ga(e.attributes,t.attributes)));e?.dates&&t.dates?e.dates.push(...t.dates):r.push(t)}n.draws[t].scheduleDetails=r}}const a=Vm({statusObject:{displaySettings:n},removePriorValues:t,status:r,event:i});return a.error?a:{...E}},unPublishEvent:function({removePriorValues:t=!0,tournamentRecord:e,status:n=Hu,event:r}){if(!e)return{error:_};if(!r)return{error:Tt};const i=`${Wu}.${zu}`,{timeItem:a}=al({itemType:i,event:r}),o=a?.itemValue||{[n]:{}};return delete o[n].structureIds,delete o[n].drawDetails,delete o[n].drawIds,Bm({event:r,timeItem:{itemValue:o,itemType:i},removePriorValues:t}),Vm({statusObject:{structureIds:void 0,drawIds:void 0,seeding:void 0},removePriorValues:t,status:n,event:r}),sr({topic:Rs,payload:{tournamentId:e.tournamentId,eventId:r.eventId}}),{eventId:r.eventId,...E}},publishEvent:Wm,unPublishOrderOfPlay:function(t){const e=t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{};if(!Object.keys(e).length)return{error:x};for(const n of Object.values(e)){const e=aw({tournamentRecord:n,...t});if(e.error)return e}return{...E}},publishOrderOfPlay:function(t){const e=nc(t);if(!Object.keys(e).length)return{error:x};for(const n of Object.values(e)){const e=ow({tournamentRecord:n,...t});if(e.error)return e}return{...E}}};function cw({tournamentRecords:t,extensionName:e}){if("object"!=typeof t||!Object.keys(t).length)return{error:x};const n=[];let r;for(const i of Object.values(t)){const{extension:t}=Mr({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}=Mr({name:e,element:t});i&&n.push({params:{eventId:r,extension:i},method:"addEventExtension"})}}return{methods:n}}const uw="ADULT",dw="JUNIOR",pw="WHEELCHAIR",lw={[Ni]:{allowModificationWhenMatchUpsScheduled:{courts:!1,venues:!1},defaultTimes:{averageTimes:[{categoryNames:[],minutes:{default:90}}],recoveryTimes:[{minutes:{[Zs]:30,default:60}}]},defaultDailyLimits:{[Ks]:2,[Zs]:2,total:3},matchUpAverageTimes:[{matchUpFormatCodes:[lg],averageTimes:[{categoryNames:[],minutes:{default:90}},{categoryTypes:[pw],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:[uw,pw],minutes:{default:60,[Zs]:30}},{categoryTypes:[dw],minutes:{default:60,[Zs]: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:[uw,pw],minutes:{default:30}},{categoryTypes:[dw],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:[uw,dw],minutes:{default:30}},{categoryTypes:[pw],minutes:{default:15}}]},{matchUpFormatCodes:["SET1-S:TB10"],recoveryTimes:[{categoryNames:[],minutes:{default:15}}]}],matchUpDailyLimits:[]}};function mw(t){const e=Lp(t,[{[up]:!0},{[Op]:kt,[Cp]:rh,[pp]:!0}]);if(e.error)return e;const{tournamentRecord:n,matchUpFormat:r,event:i}=t,{extension:a}=Mr({name:aa,element:i}),o=a?.value,{extension:s}=Mr({element:n,name:aa}),c=s?.value,u=[o?.matchUpAverageTimes&&Ju({...o,matchUpFormat:r}),c?.matchUpAverageTimes&&Ju({...c,matchUpFormat:r})].find((t=>t));return{matchUpFormat:r,recoveryTimes:[o?.matchUpRecoveryTimes&&Zu({...o,matchUpFormat:r}),c?.matchUpRecoveryTimes&&Zu({...c,matchUpFormat:r})].find((t=>t)),averageTimes:u}}function fw({tournamentRecord:t}){if(!t)return{error:_};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 hw({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&&ri(e.scheduledDate)||e.scheduledTime&&ri(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&&ni(e.scheduledTime)||"noScheduledTime";o[n]||(o[n]=[]),o[n].push(t)}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 gw({courtPrefix:t="C|",minRowsCount:e,courtsData:n}){if(!Array.isArray(n))return{error:Nn};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=w(0,e?Math.max(e,r):r).map((t=>({matchUps:w(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}))))))}}function Iw(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:S}=t;if(!S)return{error:Tt};const{eventId:y,eventName:v,endDate:w}=S,T={...U,...vr({eventId:y,eventName:v,endDate:w??d?.endDate,tournamentId:g??d?.tournamentId,indoorOutDoor:S.indoorOutdoor??d?.indoorOutdoor,surfaceCategory:S.surfaceCategory??d?.surfaceCategory})};let P;!e&&d&&({participants:e,participantMap:r,groupInfo:P}=ml({participantsProfile:o,policyDefinitions:c,useParticipantMap:u,tournamentRecord:d,contextProfile:f,inContext:I})),f&&!n&&(n=Fc({policyDefinitions:c,tournamentRecord:d,contextProfile:f,event:S}));const D=Gl({event:S});return{...(S.drawDefinitions??[]).reduce(((t,u)=>{const g=Zp({context:T,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:D,contextProfile:f,drawDefinition:u,nextMatchUps:h,inContext:I,event:S}),U=Object.keys(g);return U?.forEach((e=>{Array.isArray(g[e])&&(t[e]||(t[e]=[]),t[e]=t[e].concat(g[e]))})),t}),{}),...E,groupInfo:P}}function Uw(t){if(!t?.tournamentRecord)return{error:_};let e=t.contextContent;const{scheduleVisibilityFilters:n,participantsProfile:r,afterRecoveryTimes:i,policyDefinitions:a,useParticipantMap:o,tournamentRecord:s,inContext:c=!0,usePublishState:u,contextFilters:d,matchUpFilters:p,contextProfile:l,nextMatchUps:m,context:f}=t,h=t.tournamentId??s.tournamentId,g=s?.events??[],{participants:I,participantMap:U,groupInfo:S}=ml({participantsProfile:r,policyDefinitions:a,useParticipantMap:o,tournamentRecord:s,contextProfile:l,inContext:c});l&&!e&&(e=Fc({policyDefinitions:a,tournamentRecord:s,contextProfile:l}));const{appliedPolicies:y}=Dc({tournamentRecord:s}),v=d?.eventIds??[];return{...g.filter((t=>!v.includes(t.eventId))).map((t=>{const o=Bd({event:t}).flightProfile;return Iw({context:{eventDrawsCount:o?.flights?.length||t.drawDefinitions?.length||0,...f},tournamentAppliedPolicies:y,scheduleVisibilityFilters:n,participantsProfile:r,afterRecoveryTimes:i,policyDefinitions:a,tournamentRecord:s,usePublishState:u,contextFilters:d,contextProfile:l,contextContent:e,matchUpFilters:p,participantMap:U,participants:I,tournamentId:h,nextMatchUps:m,inContext:c,event:t})})).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]),t.matchUpsCount+=e[n].length)})),t}),{matchUpsCount:0}),groupInfo:S}}function Sw({scheduleVisibilityFilters:t,participantsProfile:e,tournamentRecords:n,policyDefinitions:r,usePublishState:i,matchUpFilters:a,contextFilters:o,nextMatchUps:s,inContext:c}){if("object"!=typeof n||!Object.keys(n).length)return{error:x};const u=Object.keys(n).map((u=>{const d=n[u];return Uw({scheduleVisibilityFilters:t,participantsProfile:e,policyDefinitions:r,tournamentRecord:d,usePublishState:i,matchUpFilters:a,contextFilters:o,nextMatchUps:s,inContext:c})})),d={};return{...u.reduce(((t,e)=>(Object.keys(e).forEach((n=>{Array.isArray(e[n])&&(t[n]||(t[n]=[]),t[n]=t[n].concat(e[n])),"groupInfo"===n&&Object.assign(d,e[n])})),t)),{}),groupInfo:d}}function yw(t){if("object"!=typeof t?.tournamentRecords||!Object.keys(t?.tournamentRecords).length)return{error:x};const{courts:e,venues:n}=Am(t),r=Om(t).schedulingProfile,{sortDateMatchUps:i=!0,courtCompletedMatchUps:a,alwaysReturnCompleted:o,activeTournamentId:s,tournamentRecords:c,withCourtGridRows:u,minCourtGridRows:d,usePublishState:p,status:l=Hu,sortCourtsData:m}=t,f=p?ol({tournamentRecord:c[s??fr()],itemType:`${Wu}.${zu}`}).timeItem?.itemValue?.[l]:void 0,h=o?Sw({...t,matchUpFilters:{...t.matchUpFilters,matchUpStatuses:[Ea]},contextFilters:t.contextFilters}).completedMatchUps:[];if(p&&(!f||!Object.keys(f).length))return{completedMatchUps:h,dateMatchUps:[],courtsData:[],venues:n};let g,I;p&&({drawIds:g,detailsMap:I}=function({tournamentRecords:t}){const e=[],n={};for(const r of Object.values(t))for(const t of r.events??[]){const r=Gl({event:t}),i=r?.drawDetails;ha(i)?(Object.assign(n,i),e.push(...Object.keys(i).filter((t=>ql({drawId:t,drawDetails:i}))))):r?.drawIds?.length&&e.push(...r.drawIds)}return{drawIds:e,detailsMap:n}}({tournamentRecords:c})),g?.length&&(t.contextFilters||(t.contextFilters={}),t.contextFilters?.drawIds?t.contextFilters.drawIds=t.contextFilters.drawIds.filter((t=>g.includes(t))):t.contextFilters.drawIds=g),f?.eventIds?.length&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters?.eventIds&&t.matchUpFilters.eventIds.length?t.matchUpFilters.eventIds=t.matchUpFilters.eventIds.filter((t=>f.eventIds.includes(t))):t.matchUpFilters.eventIds=f.eventIds),f?.scheduledDates?.length&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters.scheduledDates&&t.matchUpFilters.scheduledDates.length?t.matchUpFilters.scheduledDates=t.matchUpFilters.scheduledDates.filter((t=>f.scheduledDates.includes(t))):t.matchUpFilters.scheduledDates=f.scheduledDates),o&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters?.excludeMatchUpStatuses?.length?t.matchUpFilters.excludeMatchUpStatuses.includes(Ea)||t.matchUpFilters.excludeMatchUpStatuses.push(Ea):t.matchUpFilters.excludeMatchUpStatuses=[Ea]);const{completedMatchUps:U,upcomingMatchUps:S,pendingMatchUps:y,groupInfo:v}=Sw({...t,matchUpFilters:t.matchUpFilters,contextFilters:t.contextFilters});let w=[...S??[],...y??[]];I&&Object.keys(I).length&&(w=w.filter((t=>{const{drawId:e,structureId:n,stage:r}=t;if(!I[e])return!1;if(I[e].stageDetails){const t=Object.keys(I[e].stageDetails),n=t.filter((t=>!I[e].stageDetails[t].published)),i=t.filter((t=>I[e].stageDetails[t].published));return(!n.length||!n.includes(r))&&(!(!i.length||!i.includes(r))||n.length&&!n.includes(r)&&!i.length)}if(I[e].structureDetails){const t=Object.keys(I[e].structureDetails),r=t.filter((t=>!I[e].structureDetails[t].published)),i=t.filter((t=>I[e].structureDetails[t].published));return(!r.length||!r.includes(n))&&(!(!i.length||!i.includes(n))||r.length&&!r.includes(n)&&!i.length)}return!0})));const T=i?hw({matchUps:w,schedulingProfile:r}):w,P=e?.map((t=>{const e=function({courtId:t}){const e=(a?T.concat(U??[]):T).filter((e=>e.schedule?.courtId===t||e.schedule?.allocatedCourts?.map((({courtId:t})=>t)).includes(t)));return m?hw({matchUps:e,schedulingProfile:r}):e}(t);return{surfaceCategory:t?.surfaceCategory??"",matchUps:e,...t}})),D={completedMatchUps:o?h:U,dateMatchUps:T,courtsData:P,groupInfo:v,venues:n};if(u){const{rows:t,courtPrefix:e}=gw({minRowsCount:d,courtsData:P});D.courtPrefix=e,D.rows=t}return{...D,...E}}function vw({targetRoundNumber:t,finishingPosition:e,drawDefinition:n,structureId:r,linkType:i}){const{links:a}=Ic({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}=ts({structureId:r,drawDefinition:n});if(!e||i?.finishingPosition===e)return t})).filter(Boolean);return{sourceStructureIds:o.map((({source:t})=>t.structureId)),relevantLinks:o}}const ww="qualifierDrawPositionAssignment",Tw="alternateDrawPositionAssignment",Pw="luckyLoserDrawPositionAssignment",Dw="removeDrawPositionAssignment",bw="swapDrawPositionAssignments",Nw="modifyPairAssignment",Rw="assignDrawPosition",Mw="assignDrawPositionBye",Aw="addPenalty",Ew="MODIFY_PAIR",Cw="QUALIFIER",Ow="ALTERNATE",Fw="WITHDRAW",kw="ASSIGN",xw="REMOVE",_w="LUCKY",Lw="REMOVE_SEED",Bw="SWAP",Vw="NICKNAME",jw="SEED_VALUE",Gw="PENALTY",qw="BYE",$w={MODIFY_PAIR_ASSIGNMENT:Ew,QUALIFYING_PARTICIPANT:Cw,ALTERNATE_PARTICIPANT:Ow,WITHDRAW_PARTICIPANT:Fw,ASSIGN_PARTICIPANT:kw,LUCKY_PARTICIPANT:_w,REMOVE_ASSIGNMENT:xw,SWAP_PARTICIPANTS:Bw,ADD_NICKNAME:Vw,REMOVE_SEED:Lw,ADD_PENALTY:Gw,ASSIGN_BYE:qw,SEED_VALUE:jw};function Ww({restrictQualifyingAlternates:t,structure:e,entry:n}){const{stage:r}=e;if(!n.entryStage||n.entryStage===r||r===Qa&&!t||n.entryStage===Xa&&r===to)return!0}function Hw(t,e){return t.bye||of(t.seedValue)<of(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function zw({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}=Yp({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:l,event:f}),S=U.filter((({drawPositions:t})=>b(t,I))),y=Object.assign({},...S.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))),T=Object.assign({},...w.map((t=>({[t.participantId]:t})))),P=g.map((t=>{const e=T?.[t.participantId],n=y[t.drawPosition];return vr({...t,participant:o?gi(e,!1,!0):void 0,sourceDrawPositionRange:n})}));if(P.length){return{validSwapAction:{payload:{drawId:m,structureId:p,drawPositions:[d]},willDisableLinks:e,method:bw,type:Bw,availableAssignments:P}}}return{}}const Yw={[vi]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[Qa,Xa],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[Vw,Gw,Cw,jw],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}},Kw="positionAction",Jw="matchUpAction";function Zw({actionType:t=Kw,appliedPolicies:e,drawDefinition:n,structure:r}){const i=t===Kw&&vi||t===Jw&&wi,a=t===Kw&&Yw||t===Jw&&sm,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 Xw({activePositionOverrides:t,activeDrawPositions:e,action:n}){return!(!n||!t.includes(n))||!e.length}function Qw({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 tT({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 eT="replaceTieMatchUpParticipantId",nT="assignTieMatchUpParticipantId",rT="removeTieMatchUpParticipantId",iT="assignMatchUpSideParticipant",aT="removeMatchUpSideParticipant",oT="substituteParticipant",sT="REMOVE_SUBSTITUTION",cT="REPLACE_PARTICIPANT",uT="REMOVE_PARTICIPANT",dT="setMatchUpStatus",pT="SUBSTITUTION",lT="SCHEDULE",mT="REFEREE",fT="STATUS",hT="START",gT="SCORE",IT="END",UT={REPLACE_TEAM_POSITION_METHOD:eT,ASSIGN_TEAM_POSITION_METHOD:nT,REMOVE_TEAM_POSITION_METHOD:rT,REPLACE_PARTICIPANT:cT,SUBSTITUTION_METHOD:oT,REMOVE_SUBSTITUTION:sT,REMOVE_PARTICIPANT:uT,SCHEDULE_METHOD:dT,SUBSTITUTION:pT,SCHEDULE:lT,PENALTY:"PENALTY",REFEREE:mT,STATUS:fT,SCORE:gT,START:hT,END:IT};function ST(t){if(!t)return{error:Nn};let e,n;const{restrictAdHocRoundParticipants:r=!0,policyDefinitions:i,enforceGender:a,participantId:o,sideNumber:s,matchUpId:c}=t,u=t.tournamentRecord??(t.tournamentId&&fa(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:_};if(!c||!fa(c))return{error:qt};if(s&&![1,2].includes(s))return wr({result:{error:Nn},context:{sideNumber:s}});if(!e){const t=(hl({tournamentRecord:u}).matchUps??[]).find((t=>t.matchUpId===c));n=(u?.events??[]).find((e=>e.eventId===t?.eventId)),e=(n?.drawDefinitions??[]).find((e=>e.drawId===t?.drawId))}if(!e)return{error:j};const d=Zl({tournamentRecord:u,withIndividualParticipants:!0}).participants,{drawId:p}=e,{matchUp:l,structure:f}=Xm({drawDefinition:e,matchUpId:c,event:n});if(!l)return{error:Wt};const h=Dc({tournamentRecord:u,drawDefinition:e,structure:f,event:n}).appliedPolicies??{};Object.assign(h,i??{});const g=h?.[vi]?.otherFlightEntries,I=h?.[wi]??sm[wi],U=ap({drawDefinition:e,structure:f}),{enabledStructures:S}=Zw({actionType:Jw,appliedPolicies:h,drawDefinition:e,structure:f}),{policyActions:y}=Qw({enabledStructures:S,drawDefinition:e,structure:f}),v=t.matchUpsMap??xc({drawDefinition:e}),w=t.inContextDrawMatchUps??Jp({tournamentParticipants:d,inContext:!0,drawDefinition:e,matchUpsMap:v,event:n}).matchUps,T=w?.find((t=>t.matchUpId===c)),P=s&&T?.sides?.find((t=>t.sideNumber===s)),D=T?.sides?.map((t=>t.participantId||t.participant?.participantid)).filter(Boolean)??[],{assignedPositions:b,allPositionsAssigned:N}=is({structure:f}),{structureId:R}=f??{},M=[];if(!R)return{validActions:M};if(U){const t=(f?.matchUps??[]).filter((({roundNumber:t})=>t===l.roundNumber)),i=e?.entries?.filter((({entryStatus:t})=>t&&au.includes(t))).map(Da)??[],a=t.map((t=>(t.sides??[]).flatMap(Da))).flat().filter(Boolean),o=i.filter((t=>!(D.includes(t)||r&&a.includes(t)))),u=d?.filter((t=>o?.includes(t.participantId))).map((t=>gi(t,void 0,!0)));u?.forEach((t=>{const n=(e.entries??[]).find((e=>e.participantId===t.participantId));t.entryPosition=n?.entryPosition})),o.length&&M.push({payload:{drawId:p,matchUpId:c,structureId:R,sideNumber:s},method:iT,type:kw,availableParticipantIds:o,participantsAvailable:u});const h=function({eventEntries:t,structure:e}){const n=t=>t.entryStatus===$c&&Ww({structure:e,entry:t}),r=(t,e)=>(t.entryPosition||1/0)-(e.entryPosition||1/0);return t.filter(n).sort(r).map(Da)}({eventEntries:n?.entries??[],structure:f});let I=m(i.concat(h));if(g){const t=n?Bd({event:n}):void 0,e=t?.flights?.filter((t=>t.drawId!==p)).flatMap((t=>t.drawEntries.filter((t=>t.participantId&&![nu,Qc,tu].includes(t.entryStatus))).map((({participantId:t})=>t)))).filter(Boolean);e?.length&&I.push(...e)}I=I.filter((t=>!(D.includes(t)||o.includes(t)||r&&a.includes(t))));const U=d?.filter((t=>I.includes(t.participantId))).map((t=>gi(t,void 0,!0)));if(U?.forEach((t=>{const n=(e.entries??[]).find((e=>e.participantId===t.participantId));t.entryPosition=n?.entryPosition})),U?.sort(((t,e)=>(t.entryPosition||1/0)-(e.entryPosition||1/0))),I.length&&M.push({payload:{drawId:p,matchUpId:c,structureId:R,sideNumber:s},availableParticipantIds:I,participantsAvailable:U,method:iT,type:$c}),!$s(l)&&s){const t=l.sides?.find((t=>t.sideNumber===s));t?.participantId&&M.push({payload:{drawId:p,matchUpId:c,structureId:R,sideNumber:s},method:aT,type:uT})}}const A=Mh({drawDefinition:e,structure:f}),E=b?.filter((t=>t.participantId)).map((t=>t.drawPosition)),C=b?.filter((t=>t.bye)).map((t=>t.drawPosition)),O=l.collectionId,F=l.matchUpStatus===Ma||!O&&l.drawPositions?.reduce(((t,e)=>C?.includes(e)||t),!1);if(F)return{validActions:M,isByeMatchUp:F};tT({policyActions:y,action:mT})&&M.push({type:mT,payload:{matchUpId:c}});const k=!Ws({matchUpStatus:l.matchUpStatus}),x=h?.scoring?.structures,L=f?.stage&&x?.stage&&x?.stage[f.stage],B=f?.stageSequence&&L?.stageSequence&&L.stageSequence[f.stageSequence],V=!(h?.scoring?.requireAllPositionsAssigned||L?.requireAllPositionsAssigned||B?.requireAllPositionsAssigned)||N,G=l.sides&&2===l.sides.filter((t=>t?.participantId)).length,q=l.matchUpStatus&&[ka,Fa].includes(l.matchUpStatus),$=Uc({inContextDrawMatchUps:w,drawDefinition:e,matchUpId:c}),W=rI({inContextDrawMatchUps:w,drawDefinition:e,targetData:$}),H=(2===T?.drawPositions?.length&&T.drawPositions.every((t=>E?.includes(t)))&&2===T?.sides?.length&&T.sides.every((({participantId:t})=>t))||G)&&!(q&&W),z={method:Aw,type:Gw,payload:{drawId:p,matchUpId:c,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};if(k&&M.push({payload:{drawId:p,matchUpId:c,schedule:{}},method:dT,type:lT}),tT({policyActions:y,action:Gw})&&(P?.participant||!s&&D?.length)&&M.push(z),k&&H&&M.push({type:fT}),V&&H){const{matchUpId:t,matchUpFormat:e}=l,n={drawId:p,matchUpId:t,matchUpFormat:e,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};M.push({info:"set outcome and winningSide",method:dT,type:gT,payload:n}),tT({policyActions:y,action:hT})&&M.push({type:hT}),tT({policyActions:y,action:IT})&&M.push({type:IT})}if(O&&T){const t=T.sides?.find((t=>t.participant)),e=T.gender===$p&&T.sideNumber&&1===T.sides?.filter((t=>t.particiapntId)).length&&t?.participant?.person?.sex,n=T.matchUpType,r=!1!==(a??I?.participants?.enforceGender)?T.gender:void 0,u=T.sides?.flatMap((t=>t.participant?.individualParticipants||t.participant)).filter(Boolean),d=u?.map(Da),m=T.sides?.filter((t=>!s||t.sideNumber===s)).flatMap((t=>t.participant?.individualParticipants||t.participant)).filter(Boolean),f=m?.map(Da),h=w?.find((t=>t.matchUpId===T.matchUpTieId)),g=h?.sides?.map((t=>t.participant?.individualParticipants.filter((({participantId:t,person:n})=>!f?.includes(t)&&(!r||r===Gp||n.sex===r||r===$p&&!e||e&&n.sex!==e))))),U=s?g?.[s-1]:g?.map(((t,e)=>({participants:t,sideNumber:e+1}))),S=s?g?.[s-1]?.map(Da):g?.map(((t,e)=>({participants:t?.map(Da),sideNumber:e+1}))),v=s&&(n===Ys&&!f?.length||n===Js&&(f?.length??0)<2)||!s&&(n===Ys&&(f?.length??0)<2||n===Js&&(f?.length??0)<4),b=S?.filter((t=>!d?.includes(t))),N=U?.filter((({participantId:t})=>b.includes(t)));if(v&&b?.length&&M.push({availableParticipantIds:b,method:nT,availableParticipants:N,type:kw,payload:{participantId:void 0,tieMatchUpId:c,drawId:p}}),!f?.length||$s(l)&&!P?.substitutions?.length||M.push({method:rT,type:uT,existingParticipantIds:f,payload:{participantId:void 0,tieMatchUpId:c,drawId:p}}),N?.length&&(!s&&f?.length||s&&P?.participant)&&M.push({availableParticipantIds:b,method:eT,availableParticipants:N,type:cT,existingParticipantIds:f,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:c,drawId:p}}),tT({policyActions:y,action:sT})&&P?.substitutions?.length){const t=P.participant?.participantType===sc&&[P.participantId]||P.participant?.participantType===uc&&P.participant.individualParticipantIds||[],e=P.substitutions.map((t=>t.participantId)).filter((e=>t.includes(e)));o&&!e.includes(o)||M.push({method:rT,type:sT,substitutedParticipantIds:e,payload:{participantId:void 0,tieMatchUpId:c,drawId:p}})}const R=i?.[wi],A=R?.substituteWithoutScore,E=R?.substituteAfterCompleted;if(tT({policyActions:y,action:pT})&&2===D.length&&(!s&&f?.length||s&&P?.participant)&&(A||$s(l))&&(E||l.matchUpStatus&&!Ya.includes(l.matchUpStatus))&&m?.length&&U.length){const t=m.map(Da);M.push({info:"list of team players available for substitution",method:oT,availableParticipantIds:S,existingParticipantIds:t,availableParticipants:U,existingParticipants:m,type:pT,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:s,matchUpId:c,drawId:p}})}}return{structureIsComplete:A,validActions:M,isDoubleExit:q}}function yT({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}=vT({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}=vT({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 vT({singlesForDoubles:t,valueAccessor:e,matchUpType:n,participant:r,scaleName:i}){const a=t?Ks:n,o=r?.rankings?.[a]?.find((t=>t.scaleName===i)),s=r?.ratings?.[a]?.find((t=>t.scaleName===i)),c=(s||o)?.scaleValue;return{scaleValue:c,value:e?c?.[e]:c}}function wT(t){const e=t.participants?.filter((({participantType:t})=>t===dc)),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 TT(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 vr({structureId:u,roundSegment:n,tournamentId:i,roundNumber:a,eventId:s,drawId:c,id:d})}function PT({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=g(e.map((({matchUpFormat:t})=>t)));let p=0;return Object.keys(d).forEach((e=>{const n=d[e],i=jy({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 DT(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||Ya.includes(e))).length||0,i=t.filter((({schedule:t,matchUpStatus:e})=>t?.scheduledDate&&t?.scheduledTime&&e!==Ma)).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 bT({tournamentRecords:t,schedulingProfile:e,tournamentRecord:n,withRoundId:r}){if(n&&!t){if("object"!=typeof n)return{error:L};t={[n.tournamentId]:n}}if(e){const n=Nm({tournamentRecords:t,schedulingProfile:e});if(n.error)return n}if(!e&&t){const n=Om({tournamentRecords:t});if(n.error)return n;e=n.schedulingProfile}if(!e)return{error:On};const i={};return{profileRounds:e.map((({venues:t,scheduleDate:e})=>t.map((({rounds:t})=>t.map((t=>{const n=TT(t);return n.roundSegment?.segmentsCount&&(i[n.id]=n.roundSegment.segmentsCount),vr({id:r?n.id:void 0,scheduleDate:e,...n})})))))).flat(1/0),segmentedRounds:i}}const{stageOrder:NT}=Zo;function RT(t,e){return t.eventName.localeCompare(e.eventName)||t.eventId.localeCompare(e.eventId)||(NT[t?.stage]||0)-(NT[e?.stage]||0)||e.matchUpsCount-t.matchUpsCount||`${t.stageSequence}-${t.roundNumber}-${t.minFinishingSum}`.localeCompare(`${e.stageSequence}-${e.roundNumber}-${e.minFinishingSum}`)}const MT={allCompetitionMatchUps:gl,allDrawMatchUps:Ul,allEventMatchUps:fl,allTournamentMatchUps:hl,analyzeDraws:mU,analyzeMatchUp:Ev,analyzeTournament:function({tournamentRecord:t}){if(!t)return{error:_};const{drawsAnalysis:e}=mU({tournamentRecord:t}),n={isDual:wT(t),drawsAnalysis:e};return{...E,analysis:n}},bulkUpdatePublishedEventIds:function({tournamentRecord:t,outcomes:e}){if(!t)return{error:_};if(!e?.length)return{error:ae,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=Gl({event:t}),{drawDetails:r,drawIds:i}=e??{},{eventId:a}=t;return n[a].filter((t=>{const n=r?Object.keys(e.drawDetails).filter((t=>ql({drawId:t,drawDetails:r}))):[];return i?.includes(t)||n.includes(t)})).length})).map((t=>t.eventId)),eventIdPublishedDrawIdsMap:n}},categoryCanContain:ph,checkMatchUpIsComplete:Lc,checkValidEntries:KS,competitionScheduleMatchUps:yw,credits:zv,drawMatchUps:function({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:S,event:y}){const{eventId:v,eventName:w,endDate:T}=y??{},P={...S,...vr({eventId:v,eventName:w,endDate:T??y?.endDate??s?.endDate,tournamentId:I??s?.tournamentId,indoorOutDoor:y?.indoorOutdoor??s?.indoorOutdoor,surfaceCategory:y?.surfaceCategory??s?.surfaceCategory})};let D;return!t?.length&&s&&({participants:t,participantMap:l,groupInfo:D}=ml({participantsProfile:r,policyDefinitions:a,useParticipantMap:o,tournamentRecord:s,contextProfile:f,inContext:U})),y&&f&&!d&&(d=Fc({policyDefinitions:a,tournamentRecord:s,contextProfile:f,drawDefinition:h,event:y})),{...Zp({context:P,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:y}),groupInfo:D}},eventMatchUps:Iw,findDrawDefinition:function({tournamentRecord:t,drawDefinition:e}){return t?e?{drawDefinition:gi(e)}:{error:at}:{error:_}},findExtension:Mr,findMatchUp:Af,findParticipant:function(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:ae,stack:"publicFindParticipant"};let s,c;for(const t of Object.values(o)){c=t.tournamentId;if(s=Fi({tournamentParticipants:t.participants||[],internalUse:!0,policyDefinitions:n,contextProfile:r,participantId:i,personId:a}),s)break}return{participant:s,tournamentId:c,...E}},findPolicy:Uu,getAllDrawMatchUps:Jp,getAllowedDrawTypes:YS,getAllowedMatchUpFormats:function({tournamentRecord:t,categoryName:e,categoryType:n}){if(!t)return{error:_};const{appliedPolicies:r}=Dc({tournamentRecord:t}),i=r?.[Mi];return(i?.matchUpFormats||[]).filter((({categoryNames:t,categoryTypes:r})=>!e&&!r||e&&t?.includes(e)||n&&r?.includes(n)))},getAppliedPolicies:Dc,getAssignedParticipantIds:kl,getCompetitionDateRange:qv,getCompetitionMatchUps:Sw,getCompetitionParticipants:function(t){const{tournamentRecords:e}=t||{};if("object"!=typeof e||!Object.keys(e).length)return{error:x};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}=Zl({...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,...E,matchUps:o}},getCompetitionPenalties:function({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:x};const e=[];for(const n of Object.values(t)){const{penalties:t}=fw({tournamentRecord:n});e.push(...t??[])}return{penalties:e}},getCompetitionVenues:Em,getCourts:function({tournamentRecord:t,venueId:e,venueIds:n}){return t?{courts:(t.venues||[]).filter((t=>e?t.venueId===e:!n||n.includes(t.venueId))).map((t=>{const{venueId:e}=t,n=gi(t.courts||[]);return n.forEach((t=>Object.assign(t,{venueId:e}))),n})).flat()}:{error:_}},getDrawDefinitionTimeItem:function({returnPreviousValues:t,drawDefinition:e,itemSubTypes:n,itemType:r}){if(!e)return{error:at};if(!e.timeItems)return{info:On};const{timeItem:i,previousItems:a,info:o}=il({element:e,returnPreviousValues:t,itemSubTypes:n,itemType:r});return i&&{timeItem:i,previousItems:a}||{info:o}},getDrawParticipantRepresentativeIds:function({drawDefinition:t}){const e=Mr({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value||[]}},getEligibleVoluntaryConsolationParticipants:function({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:j};const f=[Xa,no];n&&f.push(Qa);const h=m?.eventType?{matchUpTypes:[m.eventType]}:void 0,g=s?.matchUpType?{matchUpTypes:[s.matchUpType]}:void 0,I=e&&m?fl({contextFilters:{stages:f},matchUpFilters:h,tournamentRecord:o,inContext:!0,event:m})?.matchUps??[]:Ul({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:o,inContext:!0,drawDefinition:s})?.matchUps??[],U=pu({stage:eo,drawDefinition:s}).map((({participantId:t})=>t)),S={},y={},v={},w={};i||(i=bc({policyTypes:[Ui],tournamentRecord:o,drawDefinition:s,event:m}).policyDefinitions);const T=i?.[Ui];t=t.length&&t||T?.excludedMatchUpStatuses||[],e=e??T?.includeEventParticipants,p=p??T?.allEntries,r=r??T?.finishingRoundLimit,a=a??T?.roundNumberLimit,c=c??T?.matchUpsLimit,void 0===u&&(u=void 0===T?.requirePlay||T.requirePlay),void 0===d&&(d=void 0===T?.requireLoss||T.requireLoss),l=l??T?.winsLimit;for(const e of I){if(u&&e.winningSide&&![1,2].includes(e.winningSide)&&e.matchUpStatus!==ka)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!==ka||u||(y[r]=n.participant,S[r]||(S[r]=0),e.matchUpStatus&&t.includes(e.matchUpStatus)||(S[r]+=1)))})),n?.participant){const r=n.participant.participantId;y[r]=n.participant,S[r]||(S[r]=0),e.matchUpStatus&&!t.includes(e.matchUpStatus)&&(S[r]+=1)}if(i?.participant){const n=i.participant.participantId;w[n]||(w[n]=0),w[n]+=1,S[n]||(S[n]=0),e.matchUpStatus&&!t.includes(e.matchUpStatus)&&(S[n]+=1)}}const P=o?.participants&&!u&&!d&&p,D=P?((e&&m?m.entries:s.entries)??[]).filter((t=>![nu,Qc].includes(t.entryStatus))).map((({participantId:t})=>t)):[],b=Object.keys(y);return{eligibleParticipants:(P?(o?.participants??[]).filter((({participantId:t})=>D.includes(t))):d&&Object.values(y)||Object.values(v)).filter((t=>{return e=t.participantId,(!d||b.includes(e))&&(t=>!u||(S[t]||0)>=0)(t.participantId)&&(t=>!l||(w[t]||0)<=l)(t.participantId)&&(t=>!c||S[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,...E}},getEntriesAndSeedsCount:VU,getEvent:function({tournamentRecord:t,drawDefinition:e,context:n,event:r}){if(!t)return{error:_};if(!r)return{error:Tt};const i=gi(r);return n&&Object.assign(i,n),vr({drawDefinition:e&&i.drawDefinitions?.find((({drawId:t})=>e.drawId===t)),event:i})},getEventMatchUpFormatTiming:function({tournamentRecord:t,matchUpFormats:e,categoryType:n,event:r}){if(!r)return{error:Tt};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)&&rh(n?.matchUpFormat))return t.push(n.matchUpFormat),n})).filter(Boolean)}else{const{policy:e}=Uu({policyType:Mi,tournamentRecord:t,event:r});if(e?.matchUpFormats)a=e?.matchUpFormats;else{const{extension:t}=Mr({name:aa,element:r});let e,n;({matchUpAverageTimes:e,matchUpRecoveryTimes:n}=t?.value?t.value:lw[Ni]),a=m([...(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;return s?vr({eventMatchUpFormatTiming:a.map((({matchUpFormat:e,description:i})=>({matchUpFormat:e,description:i,...Sd({tournamentRecord:t,matchUpFormat:e,categoryName:u,categoryType:n,eventType:o,event:r})}))),info:i}):{error:Tt}},getEventProperties:function({tournamentRecord:t,event:e}){if(!t)return{error:_};if(!e)return{error:Tt};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:$u,eventType:a,scaleName:i};const d=Vl({participant:t,scaleAttributes:o})?.scaleItem?.scaleValue;o={scaleType:qu,eventType:a,scaleName:i};const p=Vl({participant:t,scaleAttributes:o})?.scaleItem?.scaleValue;o={scaleType:Gu,eventType:a,scaleName:i};const l=Vl({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}},getEvents:function({tournamentRecord:t,withScaleValues:e,scaleEventType:n,inContext:r,eventIds:a,drawIds:o,context:s}){if(!t)return{error:_};const{tournamentId:c}=t,u=(t.events??[]).filter((({eventId:t})=>!a||Array.isArray(a)&&a.includes(t))).map((t=>{const e=t.drawDefinitions?.map(Ua("drawId"));if(o?.length&&!P(o,e).length)return;const n=gi(t);return r&&Object.assign(n,{tournamentId:c}),s&&Object.assign(n,s),n})).filter(Boolean),d={};if(e){const e=Zl({withScaleValues:!0,tournamentRecord:t}).participantMap,r=t=>t.reduce(((t,e)=>t+parseFloat(e)),0);for(const t of u){const a=n??t.eventType,s=t.eventId;d[s]||(d[s]={ratingsStats:{},ratings:{},ranking:{},draws:{}});const c=(t.entries??[]).filter((({entryStatus:t})=>ou.includes(t))).map(Ua(lp)),u=t=>{if(t?.ratings?.[a])for(const e of t?.ratings?.[a]??[]){const t=e.scaleName;d[s].ratings[t]||(d[s].ratings[t]=[]);const n=MU[t]?.accessor;if(n){const r=parseFloat(e.scaleValue?.[n]);r&&d[s].ratings[t].push(r)}}if(t?.rankings?.[a])for(const e of t?.rankings?.[a]??[]){const t=e.scaleName;d[s].ranking[t]||(d[s].ranking[t]=[]),e.scaleValue&&d[s].ranking[t].push(e.scaleValue)}};for(const t of c){const n=e?.[t]?.participant;if(n?.participantType!==sc)for(const t of n?.individualParticipantIds??[]){const n=e?.[t]?.participant;u(n)}else u(n)}const p=d[s].ratings;for(const t of Object.keys(p)){const e=p[t];if(!e.length)continue;const n=i(e)?.toFixed(2);d[s].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 l=(t,n)=>{const r=e=>{if(d[s].draws?.[t]&&e?.ratings?.[a])for(const n of e?.ratings?.[a]??[]){const e=n.scaleName;d[s].draws[t]?.ratings[e]||(d[s].draws[t].ratings[e]=[]);const r=MU[e]?.accessor;if(r){const i=parseFloat(n.scaleValue?.[r]);i&&d[s].draws[t].ratings[e].push(i)}}if(d[s].draws?.[t]&&e?.rankings?.[a])for(const n of e?.rankings?.[a]??[]){const e=n.scaleName;d[s].draws[t]?.ranking[e]||(d[s].draws[t].ranking[e]=[]);const r=n.scaleValue;r&&d[s].draws[t].ranking[e].push(r)}};for(const t of n.filter(Boolean)){const n=e?.[t]?.participant;if(n?.participantType!==sc)for(const t of n?.individualParticipantIds??[]){const n=e?.[t]?.participant;r(n)}else r(n)}},m=[],f=t=>o?.length&&o.includes(t)||m.includes(t);for(const e of t.drawDefinitions??[]){const t=e.drawId;if(f(t))continue;const n=kl({drawDefinition:e}).assignedParticipantIds??[];d[s].draws[t]||(d[s].draws[t]={ratingsStats:{},ratings:{},ranking:{}}),m.push(t),l(t,n)}const h=Bd({event:t}).flightProfile;for(const t of h?.flights??[]){const e=t.drawId;if(f(e))continue;l(e,t.drawEntries.map(Ua(lp)))}for(const t of m){const e=d[s].draws[t].ratings;for(const n of Object.keys(e)){const a=e[n];if(!a.length)continue;const o=i(a)?.toFixed(2);d[s].draws[t].ratingsStats[n]={avg:parseFloat((r(a)/a.length).toFixed(2)),median:o?parseFloat(o):void 0,max:Math.max(...a),min:Math.min(...a)}}}}}return vr({eventScaleValues:d,events:u,...E})},getEventStructures:Rh,getEventTimeItem:al,getFlightProfile:Bd,getLinkedTournamentIds:Rd,getMatchUpCompetitiveProfile:Su,getMatchUpDailyLimits:Ey,getMatchUpDailyLimitsUpdate:function({tournamentRecords:t}){return cw({extensionName:ia,tournamentRecords:t})},getMatchUpDependencies:Sl,getMatchUpFormat:function(t){const{structureId:e,matchUpId:n,event:r}=t;let i=t.drawDefinition;const a=Lp(t,[{[up]:!0},{_anyOf:{[fp]:!0,[Ip]:!0,[bp]:!0,[Rp]:!0}}]);if(a[Np])return a;const o=Cf(t,[{[Mp]:Dp,[Np]:ae}]),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:at};const t=ts({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}},getMatchUpFormatTiming:Sd,getMatchUpFormatTimingUpdate:function({tournamentRecords:t}){return cw({extensionName:aa,tournamentRecords:t})},getMatchUpScheduleDetails:jd,getMatchUpsStats:function({profileBands:t,tournamentRecord:e,matchUps:n}){if(!yc(n))return{error:Ht};const r=!t&&Uu({policyType:Si,tournamentRecord:e}).policy,i=t||r?.profileBands||Oc[Si].profileBands,a=n.filter((({winningSide:t})=>t)),o=Iu(a.map(hu)).reduce(((t,e)=>((t,e)=>(t[fu(e,i)]+=1,t))(t,e)),{[Mc]:0,[Ac]:0,[Ec]:0,[Nc]:0}),s=Object.keys(o).reduce(((t,e)=>(o[e]||0)+t),0),c=Object.keys(o).map((t=>({[t]:100*parseFloat((o[t]/s).toFixed(4))}))),u=a.filter((({matchUpStatus:t})=>t===Rc)).length;return c.push({[Rc]:100*parseFloat((u/s).toFixed(4))}),{competitiveBands:Object.assign({},...c),...E}},getMatchUpType:Vp,getMaxEntryPosition:function(t){const{entries:e=[],entryStatus:r,stage:i}=t;return Math.max(...e.filter((t=>!(i&&i!==t.entryStage||r&&t.entryStatus!==r||isNaN(t.entryPosition)))).map((({entryPosition:t})=>n(t||0))),0)},getModifiedMatchUpFormatTiming:mw,getPairedParticipant:Vc,getParticipantEventDetails:function({tournamentRecord:t,participantId:e}){if(!t)return{error:_};if(!e)return{error:Ae};const n=[e].concat((t.participants??[]).filter((t=>t?.participantType&&[dc,uc].includes(t.participantType)&&t.individualParticipantIds?.includes(e))).map((t=>t.participantId)));return{eventDetails:(t.events??[]).filter((t=>b((t?.entries??[]).map((t=>t.participantId)),n))).map((t=>({eventName:t.eventName,eventId:t.eventId})))}},getParticipantIdFinishingPositions:function({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:n}){if(!n)return{error:j};const{participantIds:r,participantIdMatchUps:i}=function({tournamentParticipants:t,drawDefinition:e,event:n}){if(!e)return{error:j};const r=gi(Jp({tournamentParticipants:t,inContext:!0,drawDefinition:e,event:n}).matchUps,!1,!0),i=m(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=>[Ea,Ma].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)},getParticipantMembership:function({tournamentRecord:t,participantId:e}){if(!t)return{error:_};if(!e)return{error:Ae};const{participants:n}=Zl({participantFilters:{participantTypes:[dc,uc,cc]},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}),{})},getParticipants:Zl,getParticipantScaleItem:GU,getParticipantSchedules:function({participantFilters:t={},tournamentRecord:e}){if(!e)return{error:_};if("object"!=typeof t)return{error:Pn,context:{participantFilters:t}};const n=hl({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=Sl({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)))),...E}},getParticipantSignInStatus:function({tournamentRecord:t,participantId:e}){if(!t)return{error:_};if(!e)return{error:Ae};const{participant:n}=rl({tournamentRecord:t,participantId:e});if(!n)return{error:Ee};const{timeItem:r}=il({itemType:rc,element:n});return r&&r.itemValue===ac&&ac},getParticipantTimeItem:function({returnPreviousValues:t,tournamentRecord:e,participantId:n,itemSubTypes:r,itemType:i}){if(!e)return{error:_};if(!n)return{error:Ae};const a=rl({tournamentRecord:e,participantId:n});if(a.error)return a;const{participant:o}=a;if(!o?.timeItems)return{info:On};const{timeItem:s,previousItems:c,info:u}=il({element:a.participant,returnPreviousValues:t,itemSubTypes:r,itemType:i});return s&&{timeItem:s,previousItems:c}||{info:u}},getPersonRequests:nv,getPolicyDefinitions:bc,getPositionAssignments:Dm,getPredictiveAccuracy:function(t){let{matchUps:e}=t;const{singlesForDoubles:n,tournamentRecord:r,drawDefinition:i,excludeMargin:a,exclusionRule:o,zoneDoubling:s,matchUpType:c,scaleName:u,eventId:d,zonePct:l,drawId:m,event:f}=t;if(!r&&!e)return{error:_};if(c&&![Ks,Zs].includes(c))return{error:Nn,info:{matchUpType:c}};if(e&&!yc(e))return{error:Nn,context:{matchUps:e}};const h=MU[u],g=h?.ascending??t.ascending??!1,I=h?.accessor??t.valueAccessor,U=Array.isArray(h?.range)?Math.abs(h.range[0]-h.range[1]):0,S=p(l)&&U?(l??0)*U:t.zoneMargin??U,y={withScaleValues:!0,withCompetitiveness:!0},v={matchUpTypes:c?[c]:[Ks,Zs]},w=r?.participants;e?.[0]?.hasContext?m?e=e.filter((t=>t.drawId===m)):d&&(e=e.filter((t=>t.eventId===d))):void 0===e&&(e=m&&!i&&[]||!m&&d&&!f&&[]||m&&Ul({inContext:!0,drawDefinition:i,contextFilters:v,contextProfile:y,participants:w})?.matchUps||!m&&d&&fl({inContext:!0,contextFilters:v,contextProfile:y,participants:w,event:f})?.matchUps||hl({tournamentRecord:r,contextFilters:v,contextProfile:y})?.matchUps||[]),c&&(e=e.filter((t=>t.matchUpType===c)));const T=e.filter((({winningSide:t,score:e,sides:n,matchUpStatus:r})=>![Ba,Oa,Ga,Ca,Na].includes(r??"")&&$s({score:e})&&2===n?.length&&t)),P=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:ae};const p=d-1,l=yT({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:a,exclusionRule:o,valueAccessor:I,ascending:g,scaleName:u}),D=s&&c!==Ks?2*(S||0):S,b=S?T.map((({competitiveProfile:t,matchUpType:e,score:r,sides:i})=>{const a=yT({singlesForDoubles:n,valueAccessor:I,matchUpType:e,scaleName:u,sides:i}),o=Math.abs(a[0].value-a[1].value);return{competitiveness:t?.competitiveness,valuesGap:o,score:r}})).filter((({valuesGap:t})=>t<=D)):[],N=function({zoneData:t}){const e={[Mc]:[],[Ac]:[],[Ec]:[]};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:b}),R=N&&[].concat(Object.values(N)).flat().length,M=R&&Object.assign({},...Object.keys(N).map((t=>({[t]:Math.round(1e4*N[t].length/R)/100})))),A=T.length-(b?.length||0);return{...E,relevantMatchUps:T,zoneDistribution:M,zoneData:b,accuracy:P,nonZone:A}},getRoundMatchUps:vc,getRounds:function({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:Nn,inContextMatchUps:r};if(o&&!i){if("object"!=typeof o)return{error:L};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:x};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)&&bT({tournamentRecords:i,schedulingProfile:a})||{},U=t&&Object.assign({},...I.map((t=>({[t.id]:t})))),S=r||i&&gl({tournamentRecords:i,matchUpFilters:c})?.matchUps||[],y=[],v=S&&Object.values(S.reduce(((t,e)=>{const n=TT(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:S,drawId:y}=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:S,drawId:y}}}),{})).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 N(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}=DT(a),f=PT({matchUps:t.matchUps,tournamentRecords:i,events:h,round:t});return vr({...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}=DT(t.matchUps),p=PT({matchUps:t.matchUps,tournamentRecords:i,events:h,round:t});return vr({...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=ri(t),n=d?r.id:TT(r).id;if(e&&U[n]&&ri(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),S=g&&I,v=!p||l?.validVenueIds.includes(p),w=s&&c&&v&&S;return w||y.push(r),w})).sort(RT)||[];return{...E,rounds:v,excludedRounds:y}},getScaledEntries:qU,getScheduledRoundsDetails:Gy,getSchedulingProfileIssues:function(t){const{scheduleDates:e=[],tournamentRecords:n,periodLength:r=30}=t??{};if("object"!=typeof n)return{error:L};if(!Array.isArray(e))return{error:Nn};if(!e.every(Wr))return{error:pe};const i=[];let a=0;const o={},{schedulingProfile:s}=Om({tournamentRecords:n});if(!s)return{issues:i,...E};const{matchUps:c}=gl({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}=Gy({tournamentRecords:n,periodLength:r,matchUps:c,rounds:e}),{matchUpDependencies:l}=Sl({tournamentRecords:n,matchUps:c}),f=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=P(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=f(t),r=m(e.map(f));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,...E}},getSeedsCount:BU,getStructureSeedAssignments:lu,getTeamLineUp:jc,getTieFormat:function({tournamentRecord:t,drawDefinition:e,structureId:n,matchUpId:r,structure:i,eventId:a,drawId:o,event:s}){if(!t)return{error:_};if(!(o||s||n||r))return wr({result:{error:ae},stack:"getTieFormat"});a&&!s&&(s=t.events?.find((t=>t.eventId===a)));const c=Af({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:at};const t=ts({drawDefinition:e,structureId:n});if(t.error)return t;i=t.structure}const u=(i?.tieFormat||i?.tieFormatId)&&$d({structure:i,drawDefinition:e,event:s})?.tieFormat,d=(e?.tieFormat||e?.tieFormatId)&&$d({drawDefinition:e,event:s})?.tieFormat,p=$d({event:s})?.tieFormat,l=$d({matchUp:c?.matchUp,drawDefinition:e,structure:i,event:s})?.tieFormat;return{...E,matchUp:c?.matchUp,structureDefaultTieFormat:Yf(u),eventDefaultTieFormat:Yf(p),drawDefaultTieFormat:Yf(d),tieFormat:Yf(l),structure:i}},getTournamentIds:ya,getTournamentPenalties:fw,getTournamentPersons:function({tournamentRecord:t,participantFilters:e}){if(!t)return{error:_};let n=t.participants||[];e&&(n=Kl({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)}},getTournamentStructures:function({withStageGrouping:t,tournamentRecord:e,stageSequences:n,stageSequence:r,roundTarget:i,stages:a,stage:o}){if(!e)return{error:_};const s={},c=[];for(const u of e.events||[]){const{structures:e,stageStructures:d}=Rh({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}},getTournamentTimeItem:ol,getVenuesAndCourts:Am,getVenuesReport:function({ignoreDisabled:t=!0,tournamentRecords:e,tournamentId:n,venueIds:r=[],dates:i=[]}){if(!Array.isArray(i))return{error:Nn,dates:i};if(!Array.isArray(r))return{error:Nn,venueIds:r};if(!(e&&Object.keys(e).filter((t=>!n||t===n))||[]).length)return{error:x};if(!i.every(Wr))return{error:pe};const a=Am({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}=gl({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&&cy({courtDate:r}),a=i?.reduce(((t,e)=>{const{startTime:n,endTime:r}=e;return t+(ti(r)-ti(n))}),0);a&&(s+=1),e+=a}const c=n.filter((({schedule:e})=>e.venueId===r&&fi(t,e.scheduledDate)));c.forEach((({schedule:t})=>{const e=ni(t.scheduledTime),n=ti(pi(e,t.averageMinutes))-ti(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}},isValidForQualifying:function({structureId:t,drawDefinition:e}){if(!e)return{error:j};if(!fa(t))return{error:Nn};const n=Ic({drawDefinition:e,structureId:t});if(n.error)return n;const r=n.links.target.flatMap((t=>t.target.feedProfile)).filter(Boolean),i=!P([Io,go,ho,po],r).length;return{...E,valid:i}},isValidMatchUpFormat:rh,matchUpActions:ST,participantScaleItem:Vl,participantScheduledMatchUps:function({scheduleAttributes:t=["scheduledDate","scheduledTime"],matchUps:e=[]}){if(!yc(e))return{error:Ht};if(!Array.isArray(t))return{error:Nn};const n=e.filter(Boolean).filter((({schedule:e})=>Wy({schedule:e,scheduleAttributes:t}))).reduce(((t,e)=>{const{schedule:n}=e,r=ri(n?.scheduledDate),i=ni(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)=>si(ni(t.schedule?.scheduledTime),ni(e.schedule?.scheduledTime))))})),{...E,scheduledMatchUps:n}},positionActions:function(t){const{policyDefinitions:e,returnParticipants:n=!0,provisionalPositioning:r,tournamentRecord:i,drawDefinition:a,drawPosition:o,event:s}=t;if(!s)return{error:Tt};if(!a)return{error:j};if(!t.structureId)return{error:It};const c=t.tournamentParticipants??(i&&Zl({withIndividualParticipants:!0,tournamentRecord:i}).participants)??[];let u=ts({structureId:t.structureId,drawDefinition:a});if(u.error)return u;const d=u.containingStructure||u.structure;if(!d)return{error:Ut};const p=d.structureId;if(u=yl({drawDefinition:a,structureId:p}),void 0===o&&!u.isAdHoc)return{error:tt};if(u.isAdHoc)return ST(t);if(u.error)return u;const{drawPositionInitialRounds:l,inactiveDrawPositions:f,activeDrawPositions:h,byeDrawPositions:g}=u,I=Dc({tournamentRecord:i,drawDefinition:a,structure:d,event:s}).appliedPolicies??{};Object.assign(I,e??{});const{actionsPolicy:U,enabledStructures:S,actionsDisabled:y}=Zw({actionType:Kw,appliedPolicies:I,drawDefinition:a,structure:d}),v=U?.activePositionOverrides||[],{sourceStructureIds:w}=vw({finishingPosition:Yo,targetRoundNumber:1,linkType:Uo,drawDefinition:a,structureId:p})||{};let T;w?.length&&(T=w.reduce(((t,e)=>Mh({structureId:e,drawDefinition:a})&&t),!0));const P=w.length,D=w.length&&!T,{policyActions:b}=Qw({enabledStructures:S,drawDefinition:a,structure:d}),N=![Qa,Xa].includes(d.stage)||1!==d.stageSequence,{drawId:R}=a,M=[],{assignedPositions:A,positionAssignments:E}=is({structure:d}),C=A?.find((t=>t.drawPosition===o)),O=E?.map((t=>t.drawPosition));if(!O?.includes(o))return{error:Q};const{stage:F,stageSequence:k}=d,x=[F];F===to&&x.push(Xa),F===Xa&&x.push(to);const _=pu({entryStatuses:au,provisionalPositioning:r,drawDefinition:a,stageSequence:k,structureId:p,stages:x}),L=kl({drawDefinition:a,stages:x}).assignedParticipantIds??[],B=_.filter((t=>!L.includes(t.participantId))).map((t=>t.participantId)),V=g.includes(o),G=h.includes(o);if(y)return{hasPositionAssigned:!!C,info:"Actions Disabled for structure",isActiveDrawPosition:G,isDrawPosition:!0,validActions:[],isByePosition:V};if(tT({policyActions:b,action:kw})&&!G&&E&&!D&&(!C||V)){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:f,event:h}){const{drawId:g}=u,I=[];let U,S,y=[];const v=c?.[Ai]?.validSeedPositions?.ignore;if(!v){const t=Sf({provisionalPositioning:r,returnAllProxies:!0,randomize:!0,drawDefinition:u,seedingProfile:d,structureId:f,event:h});({unplacedSeedParticipantIds:U,unplacedSeedAssignments:S,unfilledPositions:y}=t)}if(y?.length||(y=o.filter((t=>!t.participantId&&!t.bye&&!t.qualifier)).map((t=>t.drawPosition))),p||I.push({payload:{drawId:g,structureId:f,drawPosition:l,isPositionAction:!0},willDisableLinks:n,method:Mw,type:qw}),a&&v){const e=o.map((t=>t.participantId)).filter(Boolean),r={structureIds:t},{completedMatchUps:a}=Zp({inContext:!0,matchUpFilters:r,drawDefinition:u}),c=m((a??[]).filter((({matchUpType:t})=>h?.eventType!==id||t===id))?.map((({sides:t})=>t?.map(Ua("participantId")))).flat().filter((t=>t&&!e.includes(t)))),d=s?i?.filter((t=>c?.includes(t.participantId))).map((t=>gi(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&&I.push(vr({payload:{drawId:g,structureId:f,drawPosition:l},willDisableLinks:n,method:Rw,type:kw,availableParticipantIds:c,participantsAvailable:d})),{validAssignmentActions:I}}if(y.includes(l)||p){let t;if(S?.length){const e=S.filter((t=>U?.includes(t.participantId)));e.sort(Hw),t=e.map((t=>t.participantId))}else t=e;const r=s?i?.filter((e=>t.includes(e.participantId))).map((t=>gi(t,void 0,!0))):void 0;r?.length&&I.push(vr({payload:{drawId:g,structureId:f,drawPosition:l},willDisableLinks:n,method:Rw,type:kw,availableParticipantIds:t,participantsAvailable:r}))}return{validAssignmentActions:I}}({positionSourceStructureIds:w,unassignedParticipantIds:B,possiblyDisablingAction:N,isWinRatioFedStructure:P,tournamentParticipants:c,positionAssignments:E,returnParticipants:n,appliedPolicies:I,drawDefinition:a,isByePosition:V,drawPosition:o,structureId:p,event:s});t?.forEach((t=>M.push(t)))}if(tT({policyActions:b,action:Cw})){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?.[vi],h=!f?.disableRoundRestrictions&&t[o],g=f?.requireCompletedStructures,{sourceStructureIds:I,relevantLinks:U}=vw({targetRoundNumber:h,linkType:So,drawDefinition:a,structureId:s})||{};I?.length&&l.push(...I);const{sourceStructureIds:S,relevantLinks:y}=vw({targetRoundNumber:h,linkType:Uo,drawDefinition:a,structureId:s})||{};S?.length&&l.push(...S);for(const t of U){const n=a.structures?.find((e=>e.structureId===t.source.structureId));if(n?.stage!==Qa)continue;const i=Mh({structureId:t.source.structureId,drawDefinition:a});if(!g||i){const t=n.qualifyingRoundNumber,{matchUps:i}=Yp({matchUpFilters:{roundNumbers:[t],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===Ma&&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 y){const n=a.structures?.find((e=>e.structureId===t.source.structureId));if(n?.stage!==Qa)continue;const i=Mh({structureId:t.source.structureId,drawDefinition:a});if(!g||i){const{positionAssignments:t}=rs({structure:n}),i=t?.map((t=>{const e=t.participantId,n=Mr({element:t,name:ca}).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(vr({payload:{qualifyingParticipantId:void 0,drawPosition:o,structureId:s,drawId:c},method:ww,type:Cw,qualifyingParticipantIds:d,qualifyingParticipants:r?u:void 0})),{validAssignmentActions:p,sourceStructureIds:l}}({drawPositionInitialRounds:l,tournamentParticipants:c,positionAssignments:E,returnParticipants:n,appliedPolicies:I,drawDefinition:a,drawPosition:o,structureId:p,drawId:R});t?.forEach((t=>M.push(t)))}const{participantId:q}=C||{},$=q&&c.find((t=>t.participantId===q));if(C){tT({policyActions:b,action:xw})&&!G&&(M.push({type:xw,method:Dw,payload:{drawId:R,structureId:p,drawPosition:o},willDisableLinks:N}),V||M.push({type:Fw,method:"withdrawParticipantAtDrawPosition",payload:{drawId:R,structureId:p,drawPosition:o},willDisableLinks:N}),tT({policyActions:b,action:qw})&&!V&&M.push({type:qw,method:Dw,payload:{drawId:R,structureId:p,drawPosition:o,replaceWithBye:!0},willDisableLinks:N}));const t=d.stage===Qa||d.stage===Xa&&1===d.stageSequence;if(!V&&Xw({activePositionOverrides:v,activeDrawPositions:h,action:jw})&&tT({policyActions:b,action:jw})&&Uf({drawDefinition:a,structureId:p,drawPosition:o})&&t){const{seedAssignments:t}=lu({returnAllProxies:!0,drawDefinition:a,structure:d}),{seedNumber:e,seedValue:n}=t?.find((t=>t.participantId===q))??{};M.push({type:jw,method:"modifySeedAssignment",participant:$,seedNumber:e,payload:{drawId:R,structureId:p,participantId:q,seedValue:n}})}if(!V&&Xw({activePositionOverrides:v,activeDrawPositions:h,action:Lw})&&tT({policyActions:b,action:Lw})&&Uf({drawDefinition:a,structureId:p,drawPosition:o})&&t){const{seedAssignments:t}=lu({returnAllProxies:!0,drawDefinition:a,structure:d}),{seedNumber:e}=t?.find((t=>t.participantId===q))??{};M.push({method:"removeSeededParticipant",type:Lw,participant:$,seedNumber:e,payload:{participantId:q,structureId:p,drawId:R}})}if(!V&&q){if(tT({policyActions:b,action:Gw})){const t={type:Gw,method:Aw,participant:$,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:R}};M.push(t)}if(tT({policyActions:b,action:Vw})){const t={type:Vw,method:"modifyParticipantOtherName",participant:$,payload:{participantId:q,otherName:void 0}};M.push(t)}}if(tT({policyActions:b,action:Bw})){const{validSwapAction:t}=zw({possiblyDisablingAction:N,tournamentParticipants:c,inactiveDrawPositions:f,activeDrawPositions:h,positionAssignments:E,returnParticipants:n,byeDrawPositions:g,drawDefinition:a,isByePosition:V,drawPosition:o,structureId:p,structure:d,drawId:R});t&&M.push(t)}}if(tT({policyActions:b,action:Ow})&&!D){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 f=c.find((t=>t.type===kw))?.availableParticipantIds,h=a?.[vi]?.otherFlightEntries,g=a?.[vi]?.restrictQualifyingAlternates,I=(o.entries??[]).filter((({entryStage:t})=>!g||(d.stage===Qa?t===Qa:t!==Qa))).sort(((t,e)=>(t.entryPosition??1/0)-(e.entryPosition??1/0))).map((({participantId:t})=>t)).filter(Boolean),{allPositionedParticipantIds:U}=ns({drawDefinition:o}),S=r.map((t=>t.participantId)).filter(Boolean),y=I.filter((t=>d.stage&&[Qa,Xa,no].includes(d.stage)?!U?.includes(t):!S.includes(t))),v=(l?.entries??[]).filter((t=>t.entryStatus===$c&&Ww({restrictQualifyingAlternates:g,structure:d,entry:t})&&(d.stage&&[Qa,Xa,no].includes(d.stage)?!U?.includes(t.participantId):!S.includes(t.participantId)))).sort(((t,e)=>(t.entryPosition??1/0)-(e.entryPosition??1/0))).map((t=>t.participantId));let w=m(y.concat(v));if(h){const t=l?Bd({event:l}).flightProfile:void 0,e=t?.flights?.filter((t=>t.drawId!==p)).map((t=>t.drawEntries.filter((t=>t.participantId&&![nu,Qc,tu].includes(t.entryStatus)&&!I.includes(t.participantId))).map((({participantId:t})=>t)))).flat().filter(Boolean);e?.length&&w.push(...e)}f?.length&&(w=w.filter((t=>!f.includes(t))));const T=i?t?.filter((t=>w.includes(t.participantId))):void 0;if(T?.forEach((t=>{const e=(o.entries??[]).find((e=>e.participantId===t.participantId));t.entryPosition=e?.entryPosition})),T?.sort(((t,e)=>(t.entryPosition||1/0)-(e.entryPosition||1/0))),w.length)return{validAlternatesAction:vr({payload:{drawId:p,structureId:u,drawPosition:s},willDisableLinks:e,method:Tw,availableAlternatesParticipantIds:w,type:Ow,availableAlternates:T})};return{}}({possiblyDisablingAction:N,tournamentParticipants:c,positionAssignments:E,activeDrawPositions:h,returnParticipants:n,appliedPolicies:I,drawDefinition:a,drawPosition:o,validActions:M,structureId:p,structure:d,drawId:R,event:s});t&&M.push(t)}if(tT({policyActions:b,action:_w})&&!D&&E){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}=ts({structureId:e,drawDefinition:o}),r={};if(n?.finishingPosition===Ko&&(1!==l?.length||1!==m?.length)){const{matchUps:t}=Yp({drawDefinition:o,structure:u,event:p}),{initialRoundNumber:e}=vl({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}=Kp({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!==id||t===id))).map((({winningSide:t,sides:e})=>t&&e?.[1-(t-1)])).map(Ua("participantId")).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:_w,method:Pw,availableLuckyLosers:g,availableLuckyLoserParticipantIds:f,willDisableLinks:n,payload:{drawId:d,structureId:c,drawPosition:s}}};return{}}({sourceStructuresComplete:T,possiblyDisablingAction:N,isWinRatioFedStructure:P,tournamentParticipants:c,activeDrawPositions:h,positionAssignments:E,drawDefinition:a,drawPosition:o,structureId:p,structure:d,drawId:R});t&&M.push(t)}if($?.participantType===uc&&tT({policyActions:b,action:Ew})){const{validModifyAssignedPairAction:t}=function({tournamentParticipants:t,returnParticipants:e,drawPosition:n,participant:r,drawId:i,event:a}){const o=a?.entries?.filter((({entryStatus:t})=>[Qc,tu].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:vr({payload:{participantId:r.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:n,drawId:i},method:Nw,availableIndividualParticipantIds:o,availableIndividualParticipants:s,existingIndividualParticipantIds:a,existingIndividualParticipants:c,type:Ew},!1,!1,!0)}}return{}}({tournamentParticipants:c,returnParticipants:n,drawPosition:o,participant:$,drawId:R,event:s});t&&M.push(t)}return{hasPositionAssigned:!!C,isActiveDrawPosition:G,isDrawPosition:!0,isByePosition:V,validActions:M}},tallyParticipantResults:kg,tournamentMatchUps:Uw,validateCollectionDefinition:mh,validateLineUp:Df,validMatchUp:Sc,validMatchUps:yc};function AT({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===NU)),o=a?.scaleValue,{wtnRating:s,confidence:c}=o||{};return{timeStamp:a?.scaleDate,personOtherId:r,confidence:c,wtnRating:s,personId:n,tennisId:i}}function ET({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=>AT({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}}const CT={getStructureReports:function({firstFlightOnly:t=!0,extensionProfiles:e,tournamentRecord:n}){if(!n)return{error:B};const r={},i=Object.assign({},...(e??[]).map((({name:t,label:e,accessor:r})=>{const i=Mr({element:n,name:t})?.extension?.value;return{[e||t]:r?la({element:i,accessor:r})?.value:i}}))),a=n?.tournamentId,o=hl({participantsProfile:{withScaleValues:!0},tournamentRecord:n}).matchUps??[],s=t=>{const e=il({itemType:cs,itemSubTypes:[Fr],element:{timeItems:t}})?.timeItem;return e?.itemValue?.scaleBasis},c=n?.events?.flatMap((({timeItems:e,drawDefinitions:n=[],extensions:c,eventType:u,eventId:d,category:p})=>{const l=c?.find((t=>t.name===Ki)),m=l?.value?.flights?.map((t=>({[t.drawId]:t.flightNumber}))),f=m&&Object.assign({},...m),h=c?.find((t=>t.name===zi))?.value?.length||0,g=Object.values(f),I=f&&Math.min(...g),U=s(e);return r[d]={totalPositionManipulations:0,maxPositionManipulations:0,generatedDrawsCount:0,drawDeletionsCount:h,seedingBasis:U?JSON.stringify(U):void 0,tournamentId:a,eventId:d},n.filter((e=>!t||!m||f[e.drawId]===I)).flatMap((t=>{const{matchUpFormat:e,tieFormat:n,timeItems:c,extensions:l,structures:m,drawType:h,drawId:g}=t,{matchUpFormatCounts:I,matchUpsCount:S,avgConfidence:y,pctNoRating:v,avgWTN:w}=ET({eventType:u,matchUps:o,drawId:g}),T=s(c)||U,P=function({extensions:t}){return t?.find((({name:t})=>t===ji))?.value?.slice(1)}({extensions:l}),D=P?.length||0;return r[d].totalPositionManipulations+=D,r[d].generatedDrawsCount+=1,D>r[d].maxPositionManipulations&&(r[d].maxPositionManipulations=D),m?.filter((t=>1===t.stageSequence&&[Qa,Xa,to,no].includes(t.stage))).map((t=>{const r=[Xa,no].includes(t.stage)?o.find((e=>e.structureId===t.structureId&&1===e.finishingRound&&e.winningSide)):void 0,s=r?.sides?.find((t=>t.sideNumber===r.winningSide)),c=s?.participant,l=c?.participantType===oc&&c.participantId,m=c?.participantType===uc?c.individualParticipants:[],U=AT({participant:m?.[0]||c,eventType:u}),{personId:D,personOtherId:b,tennisId:N,confidence:R,wtnRating:M}=U||{},A=AT({participant:m?.[1],eventType:u}),{personId:E,personOtherId:C,tennisId:O,confidence:F,wtnRating:k}=A||{},{ageCategoryCode:x,categoryName:_,subType:L}=p??{},B=t.matchUpFormat||e,V=(I[B]||0)/S*100,{tieFormatName:j,tieFormatDesc:G}=Ih(n),{tieFormatName:q,tieFormatDesc:$}=Ih(t.tieFormat),W=G===$,H=!W&&q,z=t.tieFormat&&!W&&$,Y=P?.filter((e=>e.structureId===t.structureId))?.length||0;return{...i,tournamentId:a,eventId:d,structureId:t.structureId,drawId:g,eventType:u,category:L,categoryName:_,ageCategoryCode:x,flightNumber:f[g],drawType:h,stage:t.stage,seedingBasis:T?JSON.stringify(T):void 0,winningPersonId:D,winningPersonOtherId:b,winningPersonTennisId:N,winningPersonWTNrating:M,winningPersonWTNconfidence:R,winningPerson2Id:E,winningPerson2OtherId:C,winningPerson2TennisId:O,winningPerson2WTNrating:k,winningPerson2WTNconfidence:F,winningTeamId:l,positionManipulations:Y,pctNoRating:v,matchUpFormat:B,pctInitialMatchUpFormat:V,matchUpsCount:S,drawTieFormatName:j,drawTieFormatDesc:G,tieFormatName:H,tieFormatDesc:z,avgConfidence:y,avgWTN:w}}))}))}));return{eventStructureReports:Object.values(r),structureReports:c}},getEntryStatusReports:function({tournamentRecord:t}){if(!t)return{error:_};const e=t.tournamentId,{participantMap:n}=Zl({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:t,withDraws:!0}),r=(hl({matchUpFilters:{matchUpTypes:[Ys,Js]},tournamentRecord:t}).matchUps??[]).flatMap((({sides:t,matchUpType:e})=>t?.flatMap((t=>e===Js?t?.participant?.individualParticipantIds:t?.participant?.participantId||t.participantId)).filter(Boolean))).filter(Boolean),i=[],a={},o={},s={};let c=0;const u=({id:t,entry:r,eventId:o,eventType:s})=>{const{qualifyingSeeding:c,mainSeeding:u,entryStatus:d,entryStage:p,drawId:l}=r;a[t]||(a[t]=[]);const{participant:m,events:f}=n?.[t]??{},h=AT({participant:m,eventType:s}),g=f?.[o]?.ranking;d===Fw&&i.push(t),a[t].push({participantType:m?.participantType,participantId:t,tournamentId:e,eventType:s,eventId:o,drawId:l,entryStatus:d,entryStage:p,...h,ranking:g,mainSeeding:u,qualifyingSeeding:c})};for(const i of t.events??[]){const t={},a=e=>{t[e]||(t[e]={count:0}),t[e].count+=1},{drawDefinitions:d=[],eventType:p,eventId:l}=i,m=d.flatMap((t=>{const{drawId:e,entries:r}=t;c+=1;const i=(t.structures??[]).filter((({stage:t,stageSequence:e})=>t===Xa&&1===e||t===Qa)).flatMap((({positionAssignments:t})=>t)).filter(Boolean).map((({participantId:t})=>t));return r?.filter((({participantId:t})=>i.includes(t))).map((t=>{const{participantId:r,entryStatus:i,entryStage:o}=t;a(i);const s=n?.[r]?.draws?.[e]?.seedAssignments?.[Xa],c=n?.[r]?.draws?.[e]?.seedAssignments?.[Qa];return{qualifyingSeeding:c,participantId:r,mainSeeding:s,entryStatus:i,entryStage:o,drawId:e}}))})),f=t=>{const e=t.participantId,i=n?.[e].participant.individualParticipantIds?.filter((t=>r.includes(t)));return e&&{[e]:{individualParticipantIds:i}}};p===rd?(()=>{const t=Object.assign({},...m.map(f).filter(Boolean));m.forEach((e=>{t[e.participantId].individualParticipantIds.forEach((t=>{u({id:t,eventType:p,eventId:l,entry:e})}))}))})():m.forEach((t=>{u({id:t?.participantId,eventType:p,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})),s[l]={tournamentId:e,eventId:l,entries:m,entryStatuses:t};const g=Object.assign({},...ou.flatMap((e=>[{[e+"_count"]:t[e]?.count},{[e+"_pct"]:t[e]?.pct}])));o[l]={tournamentId:e,eventId:l,...g}}const d=Object.values(n??{}).filter((({participant:{participantType:t,participantRole:e}})=>t===sc&&e===um)),p=d.filter((({participant:t})=>!r.includes(t.participantId))).map((({participant:t})=>t.participantId)),l={nonParticipatingEntriesCount:p.length,individualParticipantsCount:d.length,eventsCount:Object.values(s).length,nonParticipatingParticipantIds:p,drawDefinitionsCount:c,tournamentId:e};return{entryStatusReports:Object.values(o).flat(),participantEntryReports:Object.values(a).flat(),eventReports:Object.values(s).flat(),withDrawnParticipantIds:i,tournamentEntryReport:l}},getParticipantStats:function({withCompetitiveProfiles:t,opponentParticipantId:e,withIndividualStats:n,teamParticipantId:r,tournamentRecord:i,withScaleValues:a,tallyPolicy:o,matchUps:s}){if(!i)return{error:_};if(s&&!Array.isArray(s))return{error:Yt};if(s=s??hl({tournamentRecord:i,participantsProfile:a?{withScaleValues:a}:void 0}).matchUps,!s?.length)return{error:Ht};const c=[];e&&c.push(e),r&&c.push(r);const u=Zl({participantFilters:c.length?{participantIds:c}:{participantTypes:[oc]},tournamentRecord:i}).participants??[];if(!u.every((({participantType:t})=>t===oc)))return{error:Pe};c.length||c.push(...u.map(Ua("participantId")));const d=new Map,p=new Map,l=new Map,m=new Map,f=(t,e="")=>p.get(t)||p.set(t,{participantName:e,participantId:t,competitorIds:[],competitiveness:{},matchUpStatuses:{},tiebreaks:[0,0],matchUps:[0,0],points:[0,0],games:[0,0],sets:[0,0]})&&p.get(t);for(const t of u){const{participantId:e,individualParticipantIds:n}=t;m.set(e,n??[]),f(e,t.participantName)}if(r&&!m.get(r))return wr({result:{error:Ee},context:{teamParticipantId:r}});if(e&&!m.get(e))return wr({result:{error:Ee},context:{opponentParticipantId:e}});const h=[],g=t=>{const i=[[],[]];for(const e of t){const t=e.participant;if(t?.participantName){d.set(t.participantId,{participantName:t.participantName,ratings:t.ratings});const e=p.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||P(e,t.participant?.individualParticipantIds).length===t.participant?.individualParticipantIds?.length)&&t.participant.individualParticipantIds;if(m.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=p.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:m.get(r),side:t})||a({individualParticipantIds:m.get(e),side:t})))))&&o(r,m.get(r))}else for(const[t,e]of m)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 s){if(!ha(e))return{error:Yt};const{matchUpStatus:n,matchUpFormat:r,matchUpType:i,winningSide:a,score:s,sides:c}=e;if(!c||!s||i===Xs||n===Ma)continue;const u=g(c);if(!u.filter(Boolean).length)continue;const p=t&&a&&Su({matchUp:e})?.competitiveness;h.push(e);const l=hg({matchUpStatus:n,matchUpFormat:r,tallyPolicy:o,winningSide:a,score:s}),m=gg({matchUpStatus:n,matchUpFormat:r,tallyPolicy:o,winningSide:a,score:s}),{pointsTally:I,tiebreaksTally:U}=Ig({matchUpFormat:r,score:s});u.forEach(((t,e)=>{for(const r of t){const t=d.get(r)?.participantName,i=f(r,t);if(i){const t=(t,e)=>e.forEach(((e,n)=>i[t][n]+=e)),r=e?[...U].reverse():U,o=e?[...I].reverse():I,s=e?[...m].reverse():m,c=e?[...l].reverse():l;if(t("tiebreaks",r),t("points",o),t("games",s),t("sets",c),a){const t=a-1===e?0:1;i.matchUps[t]+=1}if(p){const t=p.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 I=["tiebreaks","matchUps","points","games","sets"],U=["competitive","routine","decisive"],S=new Map,y=(t,e)=>(t??0)+(e??0);for(const[t,e]of p.entries()){for(const n of I){const r=e[n].reduce(y);if(r){const i=e[n][0]/r,a=`${n}Ratio`,o=parseFloat(i.toFixed(2));e[a]=o,l.set(t,!0),S.has(a)||S.set(a,[]),S.get(a)?.push(o)}}for(const t of U){const n=e.competitiveness?.[t]?.reduce(y);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 p.values())for(const n of I){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 v={relevantMatchUps:h,...E};return r?(v.teamStats=p.get(r),e&&(v.opponentStats=p.get(e))):v.participatingTeamsCount=l.size,v.allParticipantStats=[...p.values()],v}};function OT(t=0){const e=new Date;return e.setHours(e.getHours()+t),e.getTime().toString(36).slice(-6).toUpperCase()}function FT({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===Ly&&(e=ri(e),n=ni(n),r=ni(r),e&&n&&r)?{date:e,startTime:n,endTime:r,requestType:t.requestType}:t})).filter(Boolean);for(const n of r)n.requestId=OT(),t[e].push(n);return{mergeCount:r.length}}function kT(t){const{tournamentRecords:e,personRequests:n}=t,r=Lp(t,[{[sp]:!0}]);if(r.error)return r;if(!n)return{...E};const i=Object.values(e);for(const t of i){const e=t.participants??[],r=[];for(const t of Object.keys(n))if(Fi({tournamentParticipants:e,personId:t})){const e=n[t];e.length&&r.push({personId:t,requests:e})}if(Object.keys(r).length){Nr({element:t,extension:{value:r,name:ea}})}}return{...E}}function xT({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:x};o=o??ly({recoveryMinutes:e,averageMatchUpMinutes:n});const{courts:p,venues:l}=Am({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||fi(s,t.date))),r=n?.startTime??e.startTime;return r&&(!t||ti(r)<ti(t))?r:t}),void 0)),d||(d=m?.reduce(((t,e)=>{const n=e.dateAvailability?.find((t=>!t.date||fi(s,t.date))),r=n?.endTime??e.endTime;return r&&(!t||ti(r)>ti(t))?r:t}),void 0));const f=Object.values(a),h=Object.assign({},...f.map((t=>(t.events??[]).map((e=>{const{scheduleTiming:n}=Qu({tournamentRecord:t,event:e});return{[e.eventId]:{event:e,scheduleTiming:n}}})))).flat()),g=yw({sortDateMatchUps:!1,tournamentRecords:a,matchUpFilters:{scheduledDate:s,venueIds:u}}),I=g?.dateMatchUps??[],U=g?.completedMatchUps??[],S=[];S.push(...I),S.push(...U);const y={averageTimes:[{minutes:{default:n}}],recoveryTimes:[{minutes:{default:e}}]},v=S?.map((({eventId:t,schedule:e,matchUpFormat:n})=>{const{event:r,scheduleTiming:i}=h[t],a=r?.eventType,s={...i,defaultTiming:y,matchUpFormat:n},{averageMinutes:c,recoveryMinutes:u}=yd({eventType:a,timingDetails:s}),{courtId:d,venueId:p}=e,l=ni(e.scheduledTime),m=pi(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:T}=fy(w);return{venueId:1===u?.length&&u[0]||1===l?.length&&l[0].venueId||void 0,scheduleTimes:T,dateScheduledMatchUpIds:S.map(ba)}}function _T(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:x};const s=Object.keys(o).filter((t=>!i||i===t));if(i&&!s.includes(i))return{error:Nn};let c;for(const t of s){const i=o[t],{event:s}=Vd({tournamentRecord:i,eventId:a});a&&s&&(c=!0);const u=LT({tournamentRecord:i,event:s,matchUpFormat:e,averageTimes:r,recoveryTimes:n});if(u.error)return u}return!a||c?{...E}:{error:Pt}}function LT({tournamentRecord:t,recoveryTimes:e,matchUpFormat:n,averageTimes:r,event:i}){if(!t)return{error:_};if(r&&!Array.isArray(r))return{error:Nn};if(e&&!Array.isArray(e))return{error:Nn};const a=aa;if(i){const{extension:t}=Mr({element:i,name:a});Nr({element:i,extension:{name:a,value:BT({...t?.value||{},matchUpFormat:n,averageTimes:r,recoveryTimes:e})}})}else{const{extension:i}=Mr({element:t,name:a});Nr({extension:{name:a,value:BT({...i?.value||{},matchUpFormat:n,averageTimes:r,recoveryTimes:e})},element:t})}return{...E}}function BT(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 VT({event:t}){return Bi({event:t,name:aa})}function jT({tournamentRecord:t,scheduleChange:e,matchUpIds:n,dryRun:r}){if(!t)return{error:_};if(!n||!Array.isArray(n))return{error:$t};if("object"!=typeof e)return{error:Nn};const i=[],a=[],{minutesChange:o,daysChange:s}=e;if(!o&&!s)return{...E};if(o&&isNaN(o))return{error:Nn};if(s&&isNaN(s))return{error:Nn};const{matchUps:c}=hl({matchUpFilters:{matchUpIds:n},tournamentRecord:t}),u=c?.filter((t=>Wy({schedule:t.schedule}))).filter((t=>(({matchUpStatus:t})=>!Ya.includes(t))({matchUpStatus:t.matchUpStatus})));if(!u?.length)return{...E};const{tournamentInfo:d}=jm({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=Oy({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=ii(ri(m),s),f=new Date(g)<new Date(p)||new Date(g)>new Date(l)}if(o&&c){const t=ri(c),e=ti(ni(c))+o;if(f=e<0||e>1440,!f){const e=pi(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=mI({scheduledTime:h,drawDefinition:d,matchUpId:t});if(e.error)return e}if(g){const e=II({scheduledDate:g,drawDefinition:d,matchUpId:t});if(e.error)return e}}(h||g)&&i.push(t)}}}const f=hl({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{...E,rescheduled:h,notRescheduled:g,allRescheduled:I}}const GT={addMatchUpCourtOrder:UI,addMatchUpEndTime:yI,addMatchUpOfficial:function({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,participantId:i,officialType:a,matchUpId:o}){if(!o)return{error:qt};if(!i)return{error:Ae};if(e){if(!Fi({tournamentParticipants:Zl({tournamentRecord:e,participantFilters:{participantTypes:[sc],participantRoles:[dm]}}).participants??[],participantId:i}))return{error:Ee}}const s={itemType:"SCHEDULE.ASSIGNMENT.OFFICIAL",itemValue:i};return a&&(s.itemSubTypes=[a]),Ff({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:o,timeItem:s})},addMatchUpResumeTime:wI,addMatchUpScheduledDate:II,addMatchUpScheduledTime:mI,addMatchUpScheduleItems:gI,addMatchUpStartTime:SI,addMatchUpStopTime:vI,addPersonRequests:function(t){const{tournamentRecords:e,personId:n,requests:r}=t,i=Lp(t,[{[sp]:!0,personId:!0},{requests:!0,[Fp]:Ep,[Op]:Nn}]);if(i.error)return i;const{personRequests:a}=nv({tournamentRecords:e}),{mergeCount:o}=FT({personRequests:a,personId:n,requests:r});return o&&a?kT({tournamentRecords:e,personRequests:a}):{error:Nn}},addSchedulingProfileRound:$v,allocateTeamMatchUpCourts:dI,assignMatchUpCourt:lI,assignMatchUpVenue:pI,bulkRescheduleMatchUps:function(t){const{scheduleChange:e,matchUpIds:n,dryRun:r}=t;if(!n||!Array.isArray(n))return{error:$t};if("object"!=typeof e)return{error:Nn};const i=nc(t),a=[];let o=[];for(const t of Object.values(i)){const i=jT({tournamentRecord:t,scheduleChange:e,matchUpIds:n,dryRun:r});if(i.error)return i;Array.isArray(i.notRescheduled)&&o.push(...i.notRescheduled);const s=Ta(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{...E,rescheduled:a,notRescheduled:o,allRescheduled:s}},bulkScheduleMatchUps:tv,bulkScheduleTournamentMatchUps:Qy,bulkUpdateCourtAssignments:function(t){const{courtDayDate:e}=t,n=Lp(t,[{[sp]:!0},{courtAssignments:!0,[Fp]:Ep,[Op]:ae}]);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[sp][n];if(!a)return i={error:_},!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}=Vd({tournamentRecord:a,drawId:t});return n?(o[t].every((t=>{const{matchUpId:r,courtId:o}=t,s=lI({tournamentRecord:a,drawDefinition:n,courtDayDate:e,matchUpId:r,courtId:o});if(s.success)return s?.success;i={error:yn}})),!0):(i={error:j},!1)}))})),i||E},calculateScheduleTimes:xT,clearMatchUpSchedule:function({scheduleAttributes:t=[Pu,Du,Tu,Nu,Mu,Au,Ou,Cu,Eu],tournamentRecord:e,drawDefinition:n,matchUpId:r}){const i=n?Ul({matchUpFilters:{matchUpIds:[r]},inContext:!1,drawDefinition:n}).matchUps?.[0]:hl({matchUpFilters:{matchUpIds:[r]},tournamentRecord:e,inContext:!1}).matchUps?.[0];if(!i)return{error:Wt};const a=(i.timeItems??[]).filter((e=>e?.itemType&&!t.includes(e?.itemType)));return i.timeItems=a,xs({tournamentId:e.tournamentId,context:"clearMatchUpSchedule",drawDefinition:n,matchUp:i}),{...E}},clearScheduledMatchUps:iv,courtGridRows:gw,findCourt:function(t){return gi(Od(t),!1,!0)},findMatchUpFormatTiming:jy,findVenue:Cd,generateBookings:Yy,generateVirtualCourts:py,getProfileRounds:bT,getSchedulingProfile:Om,matchUpScheduleChange:function(t){const e="matchUpScheduleChange",{tournamentRecords:n}=t;if("object"!=typeof n||!Object.keys(n).length)return{error:x};const{sourceMatchUpContextIds:r,targetMatchUpContextIds:i,sourceCourtId:a,targetCourtId:o,courtDayDate:s}=t||{},{drawId:c,matchUpId:u,tournamentId:d}=r||{},{drawId:p,matchUpId:l,tournamentId:m}=i||{};if(!u&&!l)return wr({result:{error:ae},stack:e});const{matchUps:f}=gl({matchUpFilters:{matchUpIds:[u,l].filter(Boolean),drawIds:[c,p].filter(Boolean)},tournamentRecords:t.tournamentRecords}),h=f?.find((({matchUpId:t})=>t===u)),g=f?.find((({matchUpId:t})=>t===l));let I=0;if(o&&u&&!l){const t=U({tournamentId:d,matchUpId:u,courtId:o,matchUp:h,drawId:c,tournamentRecords:n,sourceCourtId:a,courtDayDate:s});if(t?.success&&I++,t.error)return wr({result:t,stack:e})}else{if(!(a&&o&&u&&l))return{error:ae};{const t=U({tournamentId:d,matchUpId:u,courtId:o,matchUp:h,drawId:c,tournamentRecords:n,sourceCourtId:a,courtDayDate:s});if(t.success&&I++,t.error)return wr({result:t,stack:e,info:"source"});const r=U({tournamentId:m,sourceCourtId:o,matchUpId:l,matchUp:g,courtId:a,drawId:p,tournamentRecords:n,courtDayDate:s});if(r.success&&I++,r.error)return wr({result:r,stack:e,info:"target"})}}return I?E:wr({result:{error:Sn},stack:e});function U(t){const{tournamentRecords:e,tournamentId:n,matchUp:r,drawId:i}=t,a=e[n],{drawDefinition:o}=Oy({tournamentRecord:a,drawId:i});return r.matchUpType===Qs?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 dI({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,courtDayDate:a,matchUpId:o,courtIds:u})}({...t,tournamentRecord:a,drawDefinition:o}):lI({...t,tournamentRecord:a,drawDefinition:o})}},modifyEventMatchUpFormatTiming:function(t){const{tournamentRecord:e,recoveryMinutes:r,averageMinutes:i,matchUpFormat:a,categoryType:o,eventId:s,event:c}=t;if(!e)return{error:_};if(!rh(a))return{error:Nn};if(!c)return{error:Tt};const{averageTimes:u=[],recoveryTimes:d=[]}=mw({tournamentRecord:e,matchUpFormat:a,event:c}),p=c.category,l=p?.categoryName||p?.ageCategoryCode||c?.eventId;let m={categoryNames:[l],minutes:{}};const f={categoryNames:[l],minutes:{}},h=t=>{if(t.categoryTypes?.includes(o)&&console.log("encountered:",{categoryType:o}),!t.categoryNames?.includes(l)||(t.categoryNames=t.categoryNames.filter((t=>t!==l)),m={minutes:t.minutes,categoryNames:[l]},t.categoryNames.length))return t},g=i&&!isNaN(n(i)),I=r&&!isNaN(n(r)),U=u.map(h).filter((t=>t?.categoryNames?.length)),S=d.map(h).filter((t=>t?.categoryNames?.length));return g&&(Object.assign(m.minutes,{[c?.eventType||Ks]:i}),U.push(m)),I&&(Object.assign(f.minutes,{[c?.eventType||Ks]:r}),S.push(f)),g||I?_T({averageTimes:g&&U,recoveryTimes:I&&S,tournamentRecord:e,matchUpFormat:a,eventId:s,event:c}):{error:Nn}},modifyMatchUpFormatTiming:_T,modifyPersonRequests:function(t){const{tournamentRecords:e,requests:n,personId:r}=t,i=Lp(t,[{[sp]:!0},{requests:!0,[Fp]:Ep,[Op]:Nn}]);if(i.error)return i;const a=n.map((({requestId:t})=>t)).filter(Boolean),{personRequests:o}=nv({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&&FT({personRequests:o,personId:r,requests:c}),kT({tournamentRecords:e,personRequests:o})},proAutoSchedule:function({scheduleCompletedMatchUps:t,tournamentRecords:e,scheduledDate:n,matchUps:r}){if(!yc(r))return{error:Nn};if(r.some((({hasContext:t})=>!t)))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:hn};let i=yw({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(ha(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=>ha(t)&&!t.matchUpId));return t.concat({matchUpIds:n,availableCourts:i,rowId:e.rowId,participantIds:r})}),[]);r.filter((({matchUpStatus:e})=>e&&e!==Ma&&(t||!Ya.includes(e)))).sort(Il);const u=Sl({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=tv({tournamentRecords:e,matchUpDetails:l});const m=r;return{...i,scheduled:d,notScheduled:m}},proConflicts:function({tournamentRecords:t,matchUps:e}){if(!yc(e))return{error:Ht};if(e.some((({matchUpId:t,hasContext:e})=>t&&!e)))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:hn};const r=w(1,Math.max(...e.map((({schedule:t})=>t?.courtOrder||1)).map((t=>n(t))))+1).map((t=>e.filter((e=>n(e.schedule?.courtOrder)===t)))),i={},a={},o={};r.flat().filter(Boolean).sort(Il).forEach((({schedule:t})=>delete t[Id]));const s=Sl({includeParticipantDependencies:!0,tournamentRecords:t,drawIds:m(e.map((({drawId:t})=>t)))}).matchUpDependencies,c=r.map(((t,e)=>t.reduce(((t,n)=>{if(!n.matchUpId)return t;const{matchUpId:r,winnerMatchUpId:c,loserMatchUpId:u,schedule:d,sides:p,potentialParticipants:l}=n,m=d?.courtId;i[r]=e,a[m]=[],t.matchUpIds.push(r),o[r]=n;const f=s[r].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:[]}))),u=c.map((()=>[])),d=(t,e,n,r)=>{if(!o[t].schedule[Id]){o[t].schedule[Id]=e,o[t].schedule[ld]=r,u[i[t]].push({matchUpId:t,issueType:n,issueIds:r,issue:e});const s=o[t].schedule.courtId;a[s]||(a[s]=[]),a[s].push({matchUpId:t,issue:e,issueType:n,issueIds:r})}};return c.forEach(((t,e)=>{const n=e?c[e-1]:void 0,r=c.slice(e+1),i={},a=g(t.participantIds),u=Object.keys(a).filter((t=>a[t]>1)),p=t.matchUpIds.filter((t=>s[t].participantIds.some((t=>u.includes(t)))));p.forEach((t=>{i[t]||(i[t]={}),i[t][md]||(i[t][md]=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=>s[t].participantIds.includes(e)));r.forEach((t=>{i[t]||(i[t]={}),i[t][fd]||(i[t][fd]=r.filter((e=>e!==t)))}))})),t.matchUpIds.forEach((e=>{const a=s[e].matchUpIds;for(const t of r){const n=t.matchUpIds.filter((t=>a.includes(t)));n?.length&&(n.forEach((t=>d(t,hd,pd,[e]))),d(e,hd,pd,n))}if(i[e]?.[md]&&d(e,md,dd,i[e][md]),t.sourceMatchUpIds.includes(e)){const n=t.matchUpIds.filter((t=>s[t].matchUpIds.includes(e)));d(e,md,pd,n),t.matchUpIds.filter((t=>s[t].matchUpIds.includes(e))).forEach((t=>d(t,md,pd,[e])))}const c=n?.matchUpIds?.filter((t=>{return n=t,s[e].sources.reduce(((t,e,r)=>e.includes(n)&&r+1||t),0)>1;var n}));if(c?.length&&(d(e,gd,pd,c),c.forEach((t=>d(t,gd,pd,[e])))),i[e]?.[fd]&&d(e,fd,dd,i[e][fd]),n?.targetMatchUpIds?.includes(e)){const t=o[e].schedule.courtId,r=a.filter((t=>n.matchUpIds.includes(t)));r.some((e=>o[e].schedule.courtId===t))||(r.forEach((t=>d(t,fd,pd,[e]))),d(e,fd,pd,r))}}))})),{courtIssues:a,rowIssues:u}},removeEventMatchUpFormatTiming:function(t){if(t.event)return VT({event:t.event});{t.tournamentRecord&&!t.tournamentRecords&&(t.tournamentRecords={[t.tournamentRecord.tournamentId]:t.tournamentRecord});const e=Lp(t,[{[sp]:!0,[Pp]:!0}]);if(e.error)return e;const{tournamentRecords:n,eventId:r}=t;for(const t of Object.values(n??{})){const{event:e}=Vd({tournamentRecord:t,eventId:r});if(e)return VT({event:e})}}return{error:Pt}},removeMatchUpCourtAssignment:function(t){const e=Lp(t,[{[sp]:!0}]);if(e.error)return e;const{removePriorValues:n,tournamentRecords:r,tournamentId:i,courtDayDate:a,matchUpId:o,courtId:s,drawId:c}=t,u=r[i];if(!u)return{error:_};const{drawDefinition:d,event:p}=Oy({tournamentRecord:u,drawId:c});if(!d)return{error:j};const l=Xm({drawDefinition:d,event:p,matchUpId:o});if(l.error)return l;if(l?.matchUp?.matchUpType===Xs){const{itemValue:t}=wd({timeItems:l.matchUp.timeItems??[],itemType:Pu}),e=s&&t.filter((t=>t.courtId!==s));return Ff({duplicateValues:!1,removePriorValues:n,tournamentRecord:u,drawDefinition:d,matchUpId:o,timeItem:{itemType:Pu,itemValue:e}})}return lI({tournamentRecord:u,drawDefinition:d,courtDayDate:a,courtId:"",matchUpId:o})},removePersonRequests:function(t){const{tournamentRecords:e,requestType:n,requestId:r,personId:i,date:a}=t,o=Lp(t,[{[sp]:!0}]);if(o.error)return o;const{personRequests:s}=nv({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?kT({tournamentRecords:e,personRequests:s}):Dr({name:ea,tournamentRecords:e,discover:!0})},reorderUpcomingMatchUps:function(t){const e="reorderUpcomingMatchUps",{tournamentRecords:n}=t;if("object"!=typeof n||!Object.keys(n).length)return wr({result:{error:x},stack:e});const{matchUpsContextIds:r,firstToLast:i}=t;if(!r)return wr({result:{error:ae},stack:e});const a=r?.length;if(!a)return{...E};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}=Oy({tournamentRecord:a,drawId:i});return o?mI({drawDefinition:o,scheduledTime:e,matchUpId:r}):{error:q}}({tournamentId:s,scheduledTime:r[d].schedule.scheduledTime,matchUpId:u,drawId:c});if(!p.success)return p;o++})),o===a?E:wr({result:{error:Un},stack:e})},scheduleMatchUps:function(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:S}=t,y=Lp(t,[{[sp]:!0,[hp]:!0},{[Cp]:Wr,[Op]:pe,scheduleDate:!0},{[Cp]:t=>!t||!isNaN(t),averageMatchUpMinutes:!0,[Op]:Nn,recoveryMinutes:!0,periodLength:!0}]);if(y.error)return y;const v=t.competitionMatchUps??gl({nextMatchUps:!0,tournamentRecords:e}).matchUps??[],w=t.matchUpDependencies??Sl({includeParticipantDependencies:!0,matchUps:v,tournamentRecords:e}).matchUpDependencies;v.forEach((t=>{t.schedule?.scheduledDate&&fi(f,ri(t.schedule.scheduledDate))&&Fy({matchUpPotentialParticipantIds:o,matchUpNotBeforeTimes:c,matchUp:t})}));const T=h.map((t=>v.find((e=>e.matchUpId===t)))).filter(Boolean),{venueId:P,scheduleTimes:D,dateScheduledMatchUpIds:b}=xT({tournamentRecords:e,remainingScheduleTimes:p,startTime:ni(I),endTime:ni(U),scheduleDate:ri(f),averageMatchUpMinutes:r,clearScheduleDates:l,periodLength:m,venueIds:g}),N={},R=[],M={},A={},C={},O=v.filter((({matchUpId:t})=>b?.includes(t)));O.forEach((t=>{$y({matchUpPotentialParticipantIds:o,individualParticipantProfiles:s,matchUp:t,value:1});const e=t.schedule?.scheduledTime;if(e){M[t.matchUpId]=e;const n=a?.[t.matchUpId];xy({recoveryMinutes:n||i,matchUpPotentialParticipantIds:o,individualParticipantProfiles:s,matchUpNotBeforeTimes:c,averageMatchUpMinutes:r,matchUpDependencies:w,scheduleTime:e,matchUp:t})}}));let F=T.filter((t=>{const e=b?.includes(t.matchUpId),n=[Ma,Oa,Ea,Na,Ba,Ga].includes(t?.matchUpStatus);return!e&&!t.winningSide&&!n}));const{matchUpMap:k,overLimitMatchUpIds:x,participantIdsAtLimit:_}=F.reduce(((t,e)=>{const{drawId:n,tournamentId:r,matchUpType:i}=e,{participantIdsAtLimit:a,relevantParticipantIds:d}=Xy({individualParticipantProfiles:s,matchUpPotentialParticipantIds:o,matchUpDailyLimits:u,matchUp:e});return a?.length?(t.overLimitMatchUpIds.push(e.matchUpId),t.participantIdsAtLimit.push(...a),t):(d.forEach((t=>{ky({individualParticipantProfiles:s,participantId:t});const e=s[t].counters;e[i]?e[i]+=1:e[i]=1,e[ud]?e[ud]+=1:e[ud]=1})),t.matchUpMap[r]||(t.matchUpMap[r]={}),t.matchUpMap[r][n]?t.matchUpMap[r][n].push(e):t.matchUpMap[r][n]=[e],Fy({matchUpPotentialParticipantIds:o,matchUpNotBeforeTimes:c,matchUp:e}),t)}),{matchUpMap:{},overLimitMatchUpIds:[],participantIdsAtLimit:[]});F=F.filter((({matchUpId:t})=>!x.includes(t)));let L=0;const B=D?.length??0,{personRequests:V}=nv({tournamentRecords:e,requestType:Ly});for(;D?.length&&F.length&&L<=B;){L++;const{scheduleTime:t}=D.shift(),e=F.find((e=>{const{matchUpId:u}=e,{dependenciesScheduled:p,remainingDependencies:l}=Cy({matchUpScheduleTimes:M,matchUpDependencies:w,allDateMatchUpIds:n,matchUp:e});if(!p)return C[u]||(C[u]=[]),C[u].push({scheduleTime:t,remainingDependencies:l}),!1;const{enoughTime:m}=Zy({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}=Vy({potentials:d,averageMatchUpMinutes:r,requestConflicts:N,personRequests:V,scheduleTime:t,scheduleDate:f,matchUp:e});if(h?.length)return!1;const g=a?.[e.matchUpId];return xy({recoveryMinutes:g||i,matchUpPotentialParticipantIds:o,individualParticipantProfiles:s,matchUpNotBeforeTimes:c,averageMatchUpMinutes:r,matchUpDependencies:w,scheduleTime:t,matchUp:e}),M[e.matchUpId]=t,!0}));F=F.filter((({matchUpId:t})=>t!==e?.matchUpId)),e||R.push(t)}F.forEach((t=>{$y({individualParticipantProfiles:s,matchUpPotentialParticipantIds:o,value:-1,matchUp:t})}));const j=[];Object.keys(k).forEach((t=>{const n=e[t];n&&Object.keys(k[t]).forEach((r=>{const{drawDefinition:i}=Oy({tournamentRecord:n,drawId:r});if(i){k[t][r].forEach((({matchUpId:t})=>{const r=M[t];if(r){const a=r.split(":").map(mi).join(":"),o=`${ri(f)}T${a}`;if(S)j.push(t);else{mI({drawDefinition:i,matchUpId:t,scheduledTime:o}).success&&j.push(t),P&&pI({tournamentRecords:e,tournamentRecord:n,drawDefinition:i,matchUpId:t,venueId:P})}}}))}}))}));const G=Ta(F);return{...E,requestConflicts:Object.values(N),remainingScheduleTimes:D?.map((({scheduleTime:t})=>t)),individualParticipantProfiles:s,matchUpNotBeforeTimes:c,participantIdsAtLimit:_,skippedScheduleTimes:R,overLimitMatchUpIds:x,scheduledMatchUpIds:j,noTimeMatchUpIds:G,recoveryTimeDeferred:A,dependencyDeferred:C}},scheduleProfileRounds:ov,setMatchUpDailyLimits:function(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:x};if("object"!=typeof r)return{error:Pn};const a=Object.keys(i).filter((t=>!n||n===t));if(n&&!a.includes(n))return{error:Nn};for(const t of a){const e=Nr({element:i[t],extension:{name:ia,value:{dailyLimits:r}}});if(e.error)return e}return{...E}},setSchedulingProfile:Fm,toggleParticipantCheckInState:_f,validateSchedulingProfile:Nm},qT="\\d+-\\d+",$T="\\d+-\\d+\\(\\d+\\)",WT="\\[\\d+-\\d+\\]",HT=new RegExp(`(${qT}),`,"g"),zT=new RegExp(`(${$T}),`,"g"),YT=[qT,$T,WT,"\\d+-\\d+\\(\\d+-\\d+\\)"],KT=["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=>YT[t])).join(" ");return new RegExp(`^${e}$`)}));function JT(t){return!t||KT.some((e=>e.test(t)))}function ZT(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function XT(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 QT(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 tP(t){return 2===t.length?t.split("").join("-"):([", ",",","/"," "].forEach((e=>t=t.split(e).join("-"))),t=t.replace(/-{2,}/,"-"))}function eP(t){return t.startsWith("(")&&t.endsWith(")")}function nP(t){if(!/^[\d-]+(\(\d\))*$/.test(t))return t;const e=T("-",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 rP({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=s(t)&&parseInt(t),c=void 0!==r[0]&&void 0!==r[1];if(s(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(c&&1===e.length&&s(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]}c&&o()}}return{sets:n}}function iP(t){const e=t.indexOf("1"),n=t.split(""),r=n.every((t=>!isNaN(t)));if(r&&3===t.length&&0===e){const t=QT(n,e);if(t)return t}if(r&&7===t.length&&e>3){const t=QT(n.slice(4),e-4);if(t)return`${n[0]}-${n[1]} ${n[2]}-${n[3]} ${t}`}}function aP(t){let{score:e}=t;const{applied:n,matchUpStatus:r}=t,i=e?.toString().split(""),a=i?.every((t=>s(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)));if(rP({score:e}),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=iP(e);t&&e!==t&&n.push("parsedSuperPattern"),e=t??e}else{const r=N(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=g(i),s=g(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 oP(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 sP={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 I=()=>{h=g(t.split("")),l=h["("]===(h[")"]||0)+1,p=(h["("]||0)+1===h[")"],m=h["["]===h["]"]+1,f=l&&!m};I();const U=/(\d+-\d+\(\d+)0,/;if(U.test(t)){const[e]=t.match(U).slice(1);t=t.replace(U,e+")")}if(h["("]===h[")"]&&h["("]>1){const e=t.split(")(").join(") (").split(" ");t=e.every(eP)?e.map((t=>{const e=t.slice(1,t.length-1);return e.length>2?e:t})).join(" "):e.join(" ")}I();const S=/[A-Za-z]+/.test(t),y=/\d+/.test(t);if(!S&&!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)+")",I()),1!==h["("]||h[")"]||"("!==t[0]||(t+=")",I()),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("")}I()}if(h[")"]>(h["("]||0)&&")"===t[0]&&(t="("+t.slice(1),I()),f&&(t.endsWith(9)||/\d+0$/.test(t))&&(t=t.slice(0,t.length-1)+")",I()),!f||t.endsWith(")")&&!t.startsWith("((")||(t+=")",I()),f){let e="",n=0;for(const r of t.split(""))"("===r&&(n?e+=")":n+=1),")"===r&&(n-=1),e+=r;t=e}if(I(),m&&!l&&(t+="]"),t.includes("([")&&t.includes("])")&&(t=t.split("([").join("[").split("])").join("]"),I()),/\(\d+0$/.test(t)&&(t=t.slice(0,t.length-1)+")"),I(),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),I()),/^\([\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,I())}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(ZT);let a=0,o="";for(const t of i){const n=T(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":XT(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=T("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;!XT(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(WT).test(t)?"super":new RegExp($T).test(t)&&"tiebreak")||new RegExp(qT).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(")")),[HT,zT].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(nP).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=>s(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=QT(t.split(""),n);return e.push("getSuper"),r}}else{const{score:n,applied:r}=aP({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=nP(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 S=/(.*)\s(1\d)\s(\d+)$/;if(S.test(t)){const[n,r,i]=t.match(S).slice(1);n.replace(/\D/g,"").length>=4&&(t=n+` ${r}${i}`,e.push("spaceSeparatedSuperPattern"))}const y=/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/g;for(const n of t.match(y)||[]){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)&&iP(t)){return{score:iP(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(XT(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(s(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=QT(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 XT(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:aP,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=nP(tP(r));t=t.replace(e,`(${a})`).trim()}const a=new RegExp(/\[[\d,/ ]+\]/g),o=t.match(a);o?.forEach((e=>{const n=tP(e.match(/^\[(.*)\]$/)[1]);t=t.replace(e,`(${n}) `).trim()}));const c=[")(","), (",") (",")[",") [","](","] ("];if(t.startsWith("(")&&[")","]"].some((e=>t.endsWith(e)))&&c.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(",")||ZT(t))),i=n.every((t=>t.includes("/")||ZT(t))),a=n.every((t=>t.includes("-")||ZT(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 u=g(t.split(""));1===u["("]&&1===u[")"]&&t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,t.length-1),1===u["-"]&&XT(t)&&s(e?.removed)&&(t+=`(${e.removed})`,e.removed=void 0));const d=/\(\)/g;return d.test(t)&&(t=t.replace(d,"").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($T).test(t)){const n=t.slice(3),r=t.slice(0,3),i=r.split("-");if(!XT(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&&s(t))return t.split("").join("-");t=nP(t);const a=(new RegExp(`^${WT}$`).test(t)?"super":new RegExp(`^${$T}$`).test(t)&&"tiebreak")||new RegExp(`^${qT}$`).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:c,setWinners:u,totalSets:d}=oP(t);if(1===d&&"6"===n?.removed&&(t+=" 6-0"),t.split(" ").length>2&&Math.max(...c)>=2&&u[0]===u[1]&&(t=t.split(" ").slice(0,2).join(" ")),Math.max(...c)>2){const e=[0,0];t=t.split(" ").map(((t,n)=>(e[u[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}=oP(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=>s(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:rP,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 cP={};const uP=["handleNumeric","handleWalkover","handleRetired","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],dP=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];function pP({analysis:t,set:e}){const n=mP({set:e}),{isDecidingSet:r,isTiebreakSet:i,matchUpScoringFormat:a}=t;return lP({matchUpScoringFormat:a,isDecidingSet:r,isTiebreakSet:i,set:e})&&n}function lP(t){let e=t.matchUpScoringFormat;const{ignoreTiebreak:n=!1,matchUpFormat:r,isTiebreakSet:i,isDecidingSet:a,set:o}=t;if(!o)return{error:ae};e=e||r;const s=a&&e.finalSetFormat||e?.setFormat||{},{side1Score:c,side2Score:u}=o,{NoAD:d,setTo:p,tiebreakAt:l,tiebreakFormat:m}=s,f=m?.NoAd,h=mP({set:o}),g=Math.abs(c-u),I=c>=p||u>=p,U=i||c>=p&&u>=p||l&&l<p&&(c===l||u===l),S=n||U&&(1===h&&o.side1TiebreakScore>o.side2TiebreakScore||2===h&&o.side2TiebreakScore>o.side1TiebreakScore);return(I&&(g>=(d||U&&(l&&!i||i&&f)?1:2)||U)||i)&&(!U||S)}function mP({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}}const fP=" ",hP="DEF",gP="WO",IP="ABN",UP="SUS",SP="RET",yP="INT",vP=[SP,hP,gP,"WO/WO",IP,UP,yP],wP="DEFAULTED",TP="WALKOVER",PP="ABANDONED",DP="SUSPENDED",bP="RETIRED",NP="INTERRUPTED",RP=[bP,wP,TP],MP="()",AP="[]",EP=["up","left","shift+tab"],CP=["enter","down","tab","right"],OP="backspace",FP="r",kP="s",xP="a",_P="d",LP="w",BP="i",VP=[FP,_P,LP,xP,kP,BP],jP="space",GP=["[","("],qP=[...EP,...CP,jP,"]"],$P="-",WP="-",HP=["/"],zP=["0","1","2","3","4","5","6","7","8","9"].concat(VP),YP=zP.map((t=>`shift+${t}`)),KP=[$P,OP].concat(qP,HP),JP=[zP,YP,KP].join(","),ZP=[JP,EP,CP,["=","+","num_1","num_2","shift+=","shift+-"]].join(",");[].concat(...zP,...zP,...KP,...zP,...zP,...zP,...zP,...zP,...zP);const XP={OUTCOMEKEYS:VP,SIDE1KEYS:zP,SIDE2KEYS:YP,MODIFIERS:KP,PROMPT:"Enter Score",MOVEUP:EP,MOVEDOWN:CP,HOTKEYS:ZP};function QP({scoreString:t,lowSide:e,outcome:n}){if(({scoreString:t}=tD({scoreString:t})),2===e){return t+((t&&t[t.length-1])!==fP?fP:"")+n}return n+fP+t}function tD({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(const n of vP){const r=t?.indexOf(n);0===r?t=t.slice(n.length+1).trim()+fP:r>0&&(t=t.slice(0,r)),r>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function eD({analysis:t,scoreString:e,sets:n,lowSide:r}){let i,a;if(!e)return{scoreString:e,sets:n};const{scoreString:o,removed:s}=tD({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}=nD({brackets:AP,scoreString:e}),f=function(t){const e=t.split("");return e.reduce(((t,e,n)=>(e.match(/\d+/g)&&t.push(n),t)),[]).pop()}(e);if(f>=0){i=e.slice(0,f);const{isTiebreakEntry:o}=nD({brackets:MP,scoreString:i}),{lastOpenBracketIndex:s,isTiebreakEntry:u}=nD({brackets:AP,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(WP),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(WP)}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 nD({brackets:t=MP,scoreString:e}){if(!e)return{};const[n,r]=t.split(""),i=e.split(""),a=Math.max(...T(n,i));return{isTiebreakEntry:a>Math.max(...T(r,i)),lastOpenBracketIndex:a}}function rD(t){const{lowValue:e=0,NoAD:n=!1,tiebreakTo:r}=t||{};return e+1>=r?e+(n?1:2):parseInt(r)}function iD({matchUpFormat:t,matchUpStatus:e,winningSide:n,sets:r}){const i=Jd(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 RP.includes(e)&&n&&(c=n),{matchUpWinningSide:c}}function aD({lowSide:t,value:e,sets:n,scoreString:r,winningSide:i,matchUpStatus:a}){let o;return e===FP?r?(o=!0,r=QP({scoreString:r,lowSide:t,outcome:SP}),i=2===t?1:2,a=bP):(o=!0,r=QP({scoreString:r,lowSide:t,outcome:hP}),i=2===t?1:2,a=wP):e===_P?(o=!0,r=QP({scoreString:r,lowSide:t,outcome:hP}),i=2===t?1:2,a=wP):e===LP?(o=!0,n=[],r=gP,i=2===t?1:2,a=TP):e===kP&&r?(o=!0,r=QP({scoreString:r,lowSide:t,outcome:UP}),a=DP,i=void 0):e===xP?(o=!0,r=QP({scoreString:r,lowSide:t,outcome:IP}),a=PP,i=void 0):e===BP&&r&&(o=!0,r=QP({scoreString:r,lowSide:t,outcome:yP}),a=NP,i=void 0),{updated:o,sets:n,scoreString:r,matchUpStatus:a,winningSide:i}}function oD({matchUpFormat:t,scoreString:e,winningSide:n,value:r,sets:i}){const a=(i?.filter((t=>t?.winningSide))?.length||0)+(n?0:1),o=Jd(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}=nD({brackets:MP,scoreString:e}),{isTiebreakEntry:m}=nD({brackets:AP,scoreString:e}),f=l||m,h=!!c.tiebreakSet,g=e?.[e.length-1]?.trim(),I=e&&!isNaN(g),U=!f&&g===$P,S=l&&GP.includes(g),y=m&&GP.includes(g),v=m&&g===WP,w=e?.split(""),[P]=AP.split(""),D=w&&Math.max(...T(P,w)),b=w&&Math.max(...T(WP,w)),N=w&&b>D,R=i[i.length-1]?.winningSide,M=i?.length&&!R,A=vP.find((t=>e?.indexOf(t)>=0)),E=!isNaN(r),C=r===jP,O=qP.includes(r),F=e?.split("").find((t=>GP.includes(t))),k=O&&m&&!y&&(v||!function({scoreString:t}){if(!t)return!1;const e=t&&t[t.length-1].trim(),n=t&&!isNaN(e),[r,i]=AP.split(""),a=t.split(""),o=Math.max(...T(r,a)),s=Math.max(...T(i,a)),c=Math.max(...T(WP,a));return n&&o>s&&c>o}({scoreString:e}));return{isTiebreakSetValue:h&&E,matchUpScoringFormat:o,setNumber:a,setFormat:c,matchTiebreakHasJoiner:N,isGameScoreEntry:M,isSpace:C,isCloser:O,isTiebreakCloser:O&&F&&f&&I,isDecidingSet:s,isTiebreakSet:h,isTimedSet:u,isNumericEnding:I,isNumericValue:E,hasOpener:F,hasOutcome:A,finalSet:d,finalSetIsComplete:p,lastSetIsComplete:R,isInvalidSetTiebreakValue:C&&f&&S,isInvalidMatchTiebreakValue:k,isTiebreakEntry:f,isSetTiebreakEntry:l,isMatchTiebreakEntry:m,isIncompleteSetScore:U,isIncompleteSetTiebreak:S,isIncompleteMatchTiebreak:y,isPartialMatchTiebreakValue:v}}function sD({matchUp:t}){const{extension:e}=Mr({name:Qi,element:t});if(!e)return{error:On};const{history:n=[],undoHistory:r=[]}=e.value;return{history:n,undoHistory:r,...E}}function cD({undoHistory:t,history:e,matchUp:n}){return Nr({element:n,extension:{value:{history:e,undoHistory:t},name:Qi}})}const uD={analyzeSet:Av,checkScoreHasValue:$s,checkSetIsComplete:lP,generateScoreString:nU,generateTieMatchUpScore:_g,getSetComplement:Ny,getTiebreakComplement:Ry,isValidMatchUpFormat:rh,keyValueScore:function(t){let{lowSide:e=1,value:r}=t,{scoreString:i,sets:a,winningSide:o,matchUpStatus:s}=t;const{matchUpFormat:c,shiftFirst:u,auto:d=!0}=t;let p,l;const m=u&&2===e||!u&&1===e;if(!JP.includes(r))return{updated:!1,info:"invalid key"};u&&(e=3-e);const{matchUpWinningSide:f}=iD({sets:a,winningSide:o,matchUpStatus:s,matchUpFormat:c});o=f;const h=oD({value:r,winningSide:o,scoreString:i,sets:a,matchUpFormat:c});if(HP.includes(r)&&(r=$P),h.hasOpener&&h.isTiebreakEntry&&!h.isTiebreakSet&&m&&0===n(r)&&(h.isTiebreakCloser=!0),qP.includes(r)&&h.hasOpener&&(r=""),qP.includes(r)&&(r=jP),h.lastSetIsComplete){const t=i?.length&&i[i.length-1];i&&" "!==t&&(i+=" ")}if(h.isTimedSet)({info:l,sets:a,scoreString:i,updated:p,matchUpStatus:s,winningSide:o}=function(t){let{sets:e,info:r,scoreString:i,winningSide:a,matchUpStatus:o}=t;const{analysis:s,lowSide:c,value:u}=t;let d,p;e?.length||u===OP||(e=[{setNumber:1}]);const l=e.length-1;if(VP.includes(u)){const t=e[e.length-1]||{},{side1Score:n,side2Score:p}=t;n&&!p?r="missing side2Score":s.finalSetIsComplete||a?r="final set is already complete":s.isIncompleteSetScore?r="incomplete set scoreString":s.isIncompleteSetScore||({sets:e,scoreString:i,winningSide:a,matchUpStatus:o,updated:d}=aD({lowSide:c,value:u,sets:e,scoreString:i,matchUpStatus:o,winningSide:a}))}else if(u===OP){if(({scoreString:i,sets:e,outcomeRemoved:p}=eD({analysis:s,scoreString:i,sets:e})),""===i?.trim()&&(i=i.trim()),i||(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}))}}o=void 0,a=void 0,d=!0}else if(s.hasOutcome)r="has outcome";else{if(a)return{sets:e,scoreString:i,winningSide:a,matchUpStatus:o,updated:!1,info:"matchUp is complete"};if(u===jP){const t=e[e.length-1]||{},{side1Score:n,side2Score:r}=t,o=(n>r?1:r>n&&2)||void 0;!o||a||s.isIncompleteSetScore||(e[e.length-1].winningSide=o,e.push({setNumber:e.length+1}),i+=" ",d=!0)}else if(u===$P&&void 0!==e[l].side1Score&&void 0===e[l].side2Score&&i&&s.isNumericEnding)i+="-",e[l].side2Score=0,o=void 0,a=void 0,d=!0;else if(!isNaN(u)){let t;if(void 0===e[l].side2Score){const r=n((e[l].side1Score||0).toString()+u).toString().slice(0,2);e[l].side1Score=n(r),t=e[l].side1Score.toString(),d=!0}else{const r=n((e[l].side2Score||0).toString()+u).toString().slice(0,2);e[l].side2Score=n(r),t=[e[l].side1Score,e[l].side2Score].join("-"),d=!0}if(d){const n=(e.slice(0,l)||[]).filter((t=>t)).map((t=>{const{side1Score:e,side2Score:n}=t;return[e,n].join("-")})).join(" ");i=n?n+" "+t:t}}}return{sets:e,scoreString:i,winningSide:a,matchUpStatus:o,info:r,updated:d}}({analysis:h,lowSide:e,scoreString:i,sets:a,matchUpStatus:s,winningSide:o,value:r}));else if(VP.includes(r))h.finalSetIsComplete||o?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:r}):({sets:a,scoreString:i,matchUpStatus:s,winningSide:o,updated:p}=aD({lowSide:e,sets:a,scoreString:i,matchUpStatus:s,winningSide:o,value:r}));else if(r===OP)p=!0,({scoreString:i,sets:a}=eD({analysis:h,scoreString:i,sets:a,lowSide:e})),i||(a=[]),s=void 0,o=void 0;else if(h.hasOutcome)l="has outcome";else if(r!==$P||h.isMatchTiebreakEntry)if(r===WP&&h.isMatchTiebreakEntry&&!h.isSetTiebreakEntry)h.matchTiebreakHasJoiner?l="existing joiner":h.isNumericEnding&&(p=!0,i+=WP);else if([$P,WP].includes(r))l="invalid location for joiner";else{if(o)return{updated:!1,info:"matchUp is complete"};if(h.isIncompleteSetScore)h.isNumericValue&&({sets:a,scoreString:i,updated:p}=function({analysis:t,scoreString:e,sets:r,value:i}){let a;if(!r?.length)return{sets:[]};const o=r[r.length-1];i=n(i);const{validSide2Score:s,requiresTiebreak:c}=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:o,value:i});if(s){a=!0,e=(e||"")+i,o.side2Score=i;const n=pP({analysis:t,set:r[r.length-1]});o.winningSide=n||void 0,c?e+=MP.split("")[0]:t.isDecidingSet||(e+=fP)}return{sets:r,scoreString:e,updated:a}}({analysis:h,scoreString:i,sets:a,value:r}));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?MP:AP,e=t.split("").reverse()[0],n=t.split("")[0],r=a[a.length-1],{tiebreakFormat:o}=h.setFormat,{tiebreakTo:s,NoAD:c}=o||{},u=mP({set:r});if(!h.isTiebreakSet){const t=parseInt(i.split(n).reverse()[0]),e=rD({lowValue:t,tiebreakTo:s,NoAD:c});1===u?(r.side1TiebreakScore=e,r.side2TiebreakScore=t):(r.side1TiebreakScore=t,r.side2TiebreakScore=e)}i=(i||"")+e,h.isDecidingSet||(i+=fP);const d=pP({analysis:h,set:r});r.winningSide=d||void 0,p=!0}else if(h.isTiebreakSetValue)({info:l,scoreString:i,sets:a,updated:p}=function({analysis:t,auto:e,lowSide:r,scoreString:i="",sets:a,value:o}){let s,c;const{tiebreakSet:{tiebreakTo:u,NoAD:d}}=t.setFormat,[p]=AP.split("");if(t.isMatchTiebreakEntry||(i+=p),a[t.setNumber-1]){const{lastOpenBracketIndex:t}=nD({brackets:AP,scoreString:i}),p=(i.slice((t??0)+1)+(e?"":o)).split(WP);if((p[r-1]?.length||0)>=2)c="tiebreak digit limit";else if(e){1===r&&(p[0]=(p[0]||"")+o),2===r&&(p[1]=(p[1]||"")+o);const e=[p[0]||0,p[1]||0].map((t=>n(t))),c=1===r?1:0;e[c]=e[1-c]+(d?1:2),e[c]<u&&(e[c]=u);const l=a[a.length-1];l.side1TiebreakScore=e[0],l.side2TiebreakScore=e[1],i=i.slice(0,(t??0)+1),i+=e.join(WP),s=!0}else{const t=[p[0]||0,p[1]||0].map((t=>n(t))),e=a[a.length-1];e.side1TiebreakScore=t[0],e.side2TiebreakScore=t[1],i+=o,s=!0}}else{const t=rD({lowValue:n(o||0),tiebreakTo:u,NoAD:d}),e=[n(o),t];2===r&&e.reverse();const c={side1TiebreakScore:e[0],side2TiebreakScore:e[1],setNumber:a?.length+1||1};a.push(c),i+=e.join(WP),s=!0}return{info:c,scoreString:i,sets:a,updated:s}}({analysis:h,auto:d,lowSide:e,scoreString:i,sets:a,value:r}));else if(h.isSetTiebreakEntry){const[t]=MP.split(""),e=Math.max(...T(t,i.split(""))),a=i.slice(e+1),o=a&&0===n(a),s=n(a?a+r:r),{tiebreakFormat:c}=h.setFormat,{tiebreakTo:u,NoAD:d}=c||{};!o&&a.length<2?d&&s>u-1?l="invalid low value for NoAD tiebreak":(p=!0,i=(i||"")+r):l=o?"tiebreak begins with zero":"tiebreak digit limit"}else if(h.isCloser)l=`invalid key: ${r}`;else if(h.isGameScoreEntry)l="game scoreString entry";else if(h.lastSetIsComplete||!a.length){p=!0;const{scoreString:t,set:o}=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=MP.split("")[0];n=(n||"")+(u.join($P)+(s?d:fP));const p={side1Score:u[0],side2Score:u[1]},l=pP({analysis:t,set:p});return p.winningSide=l||void 0,{scoreString:n,set:p}}({analysis:h,lowSide:e,scoreString:i,value:n(r)});o&&(o.setNumber=a?.length+1||1),a=a?.concat(o).filter(Boolean)||[o],i=t||void 0}else console.log("error: unknown outcome")}else(!h.isSetTiebreakEntry||h.isSetTiebreakEntry&&!h.isNumericEnding)&&(p=!0,({scoreString:i,sets:a}=eD({analysis:h,scoreString:i,sets:a,lowSide:e})),s=void 0);if(p){a=a?.filter(Boolean);const{matchUpWinningSide:t}=iD({sets:a,winningSide:o,matchUpStatus:s,matchUpFormat:c});return o=t,!t||s&&![ja,_a].includes(s)?!i||o||[DP,PP,NP].includes(s)||(s=void 0):(s="COMPLETED",a=a.filter((t=>{const{side1Score:e,side2Score:n,side1TiebreakScore:r,side2TiebreakScore:i}=t;return e||n||r||i}))),{updated:p,scoreString:i,sets:a,winningSide:o,matchUpStatus:s,info:l}}return{updated:p,scoreString:i,sets:a,winningSide:o,matchUpStatus:s,info:l}},parseMatchUpFormat:Jd,reverseScore:function(t){if(!t?.score)return{error:ae};const{sets:e}=t.score,n=e.map((t=>{const{side1TiebreakScore:e,side2TiebreakScore:n,winningSide:r,side1Score:i,side2Score:a,setNumber:o}=t;return vr({winningSide:r?3-r:void 0,side1TiebreakScore:n,side2TiebreakScore:e,side1Score:a,side2Score:i,setNumber:o})}));return{reversedScore:{sets:n,scoreStringSide1:nU({sets:n}),scoreStringSide2:nU({sets:n,reversed:!0})},...E}},stringifyMatchUpFormat:Xf,tidyScore:function(t){if(!t.score)return{error:Nn};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=sP[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(uP);let h=JT(m);return h||(m=e.toString().replace(/\D/g,""),d?.removed&&(d.removed=void 0),f(dP),h=JT(m),h||(m="")),l.forEach((t=>{cP[t]||(cP[t]=0),cP[t]+=1})),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:d,isValid:h,score:m}},updateTieMatchUpScore:$g,validateScore:TI,validateTieFormat:fh,calculateHistoryScore:function(t){if(!t)return{error:ae};const{matchUp:e,updateScore:n}=t;if(!e)return{error:zt};const r=sD({matchUp:e})?.history||[];if(!Array.isArray(r))return{error:Nn,info:"history is not an array"};const{matchUpFormat:i}=e;if(!i)return{error:Vt};if(!rh(i))return{error:Bt};const a=Jd(i),{bestOf:o,finalSetFormat:s,setFormat:c}=a,u=["0","15","30","40","A","G"],d={sets:[]};let l,m,f=[],h=[0,0],g=1,I=0,U=0;const S=t=>[1,2].includes(t),y=()=>(I+=1,{winningSide:void 0,side1Score:0,side2Score:0,setNumber:I,games:[]});let v={winningSide:void 0,side1Score:"",side2Score:"",shots:[]},w={winningSide:void 0,points:[]},T=y(),P=0;for(const t of r){P+=1,m=d.sets.length+1===o;const e=m&&s?s:c,{tiebreakAt:n,setTo:r,NoAD:i,tiebbreakFormat:a}=e,I=T.side1Score===n&&T.side1Score===T.side2Score,D=!!e.tiebreakSet,b=D?e.tiebreakSet:a,{tiebreakTo:N,NoAD:R}=b||{},M=()=>{l=void 0,h=[0,0],g=3-g,T.side1TiebreakScore=0,T.side2TiebreakScore=0,T.side1PointScore="",T.side2PointScore="",U=0},A=t=>{T.winningSide=t;const{s:e,...n}=T;d.sets.push(n),v={winningSide:void 0,side1Score:"",side2Score:"",shots:[]},w={winningSide:void 0,points:[]},T=y(),M()},E=t=>{w.winningSide=t;const{g:e,...n}=w;T.games.push(n),v={winningSide:void 0,side1Score:"",side2Score:"",shots:[]},w={winningSide:void 0,points:[]},M();T[`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:[]},U=0;const r=t-1;if(I||D){h[r]+=1,l=h.reduce(((t,e)=>t+e))%4/4>.5?g:3-g,T[`side${t}TiebreakScore`]=h[r],T[`side${3-t}TiebreakScore`]=h[1-r];const e=R?1:2;if(h[r]>=N&&h[r]>=h[1-r]+e)return E(t),{gameCompleted:!0}}else if(4===h[1-r]&&3===h[r]?h[1-r]-=1:h[r]+=1,T.side1PointScore=u[h[0]],T.side2PointScore=u[h[1]],5===h[r]||4===h[r]&&h[1-r]<3||i&&4===h[r])return E(t),{gameCompleted:!0}};if(S(t.srv)&&(g=t.srv),["p","s","g","o"].includes(t.u)&&f.push(t.u),t.shotOutcome){v.shots.push(t);if("SERVE"===t.shotType&&["OUT","NET"].includes(t.shotOutcome)&&(U+=1),2===U){C(3-g)}}if(S(t.p)||p(t.pointNumber)){const e=C(t.winningSide||t.p);if(e?.gameCompleted)continue}if(S(t.g)||p(t.gameNumber)){const e=t.winningSide||t.g;w.winningSide=e;const n=`side${e}Score`,a=`side${3-e}Score`;f.length&&(f.includes("p"),f=[]),E(e);if(T[n]===r&&T[n]-T[a]>=(i?1:2)&&(A(e),m))break}if(S(t.s)||p(t.setNumber)){if(A(t.winningSide||t.s),f.length&&(f.includes("p"),f.includes("g"),f=[]),m)break}}return P!==r.length&&console.log({error:"Match completed with excess history"}),(T.side1Score||T.side2Score||T.games.length||T.side1TiebreakScore||T.side2TiebreakScore)&&d.sets.push(T),d.scoreStringSide1=nU({...d,matchUpFormat:i}),d.scoreStringSide2=nU({...d,matchUpFormat:i,reversed:!0}),g=l||g,n&&(e.score=d),{...E,servingSide:g,score:d}},setServingSide:function({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:ne};const{history:n=[]}=sD({matchUp:t});return n.push({srv:e}),cD({matchUp:t,history:n})},clearHistory:function({matchUp:t}){return cD({matchUp:t})},addPoint:function({matchUp:t,point:e}){if(!e)return{error:ae};if("object"!=typeof e)return{error:Nn,context:{point:e}};const{history:n=[]}=sD({matchUp:t});return n.push(e),cD({matchUp:t,history:n})},addGame:function({matchUp:t,game:e}){if("object"!=typeof e)return{error:Nn,context:{game:e}};const{history:n=[]}=sD({matchUp:t});return n.push(e),cD({matchUp:t,history:n})},addShot:function({matchUp:t,shot:e}){if("object"!=typeof e)return{error:ae};const{history:n=[]}=sD({matchUp:t});return n.push(e),cD({matchUp:t,history:n})},addSet:function({matchUp:t,set:e}){if("object"!=typeof e)return{error:ae};const{history:n=[]}=sD({matchUp:t});return n.push(e),cD({matchUp:t,history:n})},redo:function({matchUp:t}){const{history:e=[],undoHistory:n=[]}=sD({matchUp:t});return n.length&&e.push(n.pop()),cD({matchUp:t,history:e,undoHistory:n})},undo:function({matchUp:t}){const{history:e=[],undoHistory:n=[]}=sD({matchUp:t});return n.push(e.pop()),cD({matchUp:t,history:e,undoHistory:n})},umo:{scoreboard:()=>{},addPoints:()=>{},addPoint:()=>{}}},dD={ABANDONED:"ABANDONED",ACTIVE:"ACTIVE",CANCELLED:"CANCELLED",COMPLETED:"COMPLETED",IN_PROGRESS:"IN_PROGRESS"};function pD({tournamentRecord:t,startDate:e,endDate:n}){if(!t)return{error:_};if(e&&!Vr.test(e)||n&&!Vr.test(n))return{error:pe};if(!e&&!n)return{error:oe};if(n&&e&&new Date(n)<new Date(e))return{error:Nn};let r;(e&&t.startDate&&new Date(e)>new Date(t.startDate)||n&&t.endDate&&new Date(n)<new Date(t.endDate))&&(r=!0),e&&(t.startDate=e),n&&(t.endDate=n),e&&t.endDate&&new Date(e)>new Date(t.endDate)&&(t.endDate=e),n&&t.startDate&&new Date(n)<new Date(t.startDate)&&(t.startDate=n);const i=r&&function({tournamentRecord:t}){const e=hl({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(!iv({scheduledDates:i,tournamentRecord:t}).clearedScheduleCount)return{error:Y}}return{unscheduledMatchUpIds:a}}({tournamentRecord:t})?.unscheduledMatchUpIds;return function({tournamentRecord:t}){if(!t)return{error:_};const{startDate:e,endDate:n}=t,r=Jr(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=ti(t.startTime),r=ti(t.endTime);return e.startTime&&ti(e.startTime)<n&&(t.startTime=e.startTime),e.endTime&&ti(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:t}),sr({topic:ws,payload:{startDate:e,endDate:n}}),{...E,unscheduledMatchUpIds:i}}const lD={addDrawDefinitionExtension:xi,addEventExtension:_i,addEventTimeItem:Bm,addExtension:Nr,addNotes:Gg,addOnlineResource:function({tournamentRecord:t,onlineResource:e,organisationId:n,participantId:r,personId:i,courtId:a,venueId:o}){if(!t)return{error:_};if(!ha(e))return{error:ae};if(3!==P(Object.keys(e),["resourceSubType","resourceType","identifier"]).length)return wr({result:{error:Pn},context:{onlineResource:e}});if(n){if(t.parentOrganisation?.parentOrganisationId!==n)return wr({result:{error:On}});t.parentOrganisation.onlineResources||(t.parentOrganisation.onlineResources=[]),t.parentOrganisation.onlineResources.push(e)}else if(r||i){const n=(t.participants??[]).find((t=>i&&t.person?.personId===i||t.participantId===r));if(!n)return wr(i?{result:{error:On}}:{result:{error:Ee}});if(i){if(n.person?.personId!==i)return wr({result:{error:we}});n.person.onlineResources||(n.person.onlineResources=[]),n.person.onlineResources.push(e)}else n.onlineResources||(n.onlineResources=[]),n.onlineResources.push(e)}else if(a){const n=(t.venues??[]).filter((t=>!o||t.venueId===o)).flatMap((t=>(t.courts??[]).filter((t=>t.courtId===a))))?.[0];if(!n)return wr({result:{error:tn}});n.onlineResources||(n.onlineResources=[]),n.onlineResources.push(e)}else if(o){const n=(t.venues??[]).find((t=>t.venueId===o));if(!n)return wr({result:{error:rn}});n.onlineResources||(n.onlineResources=[]),n.onlineResources.push(e)}else t.onlineResources||(t.onlineResources=[]),t.onlineResources.push(e);return{...E}},addParticipantExtension:function(t){if(!t||"object"!=typeof t)return{error:ae};if(!t.participantId)return{error:Ae};const e=t.tournamentRecord?.participants||[],n=Fi({participantId:t.participantId,tournamentParticipants:e});return n?Nr({creationTime:t.creationTime,extension:t.extension,element:n}):{error:Ee}},addParticipantTimeItem:_m,addTimeItem:xm,addTournamentExtension:ki,addTournamentTimeItem:Lm,getProfileRounds:bT,removeDrawDefinitionExtension:function(t){return t&&"object"==typeof t?t.drawDefinition?Dr({element:t.drawDefinition,name:t.name}):{error:q}:{error:ae}},removeEventExtension:Bi,removeExtension:Dr,removeNotes:function(t){return"object"!=typeof t?{error:ae}:"object"!=typeof t.element?{error:Nn}:(t.element.notes&&delete t.element.notes,{...E})},removeParticipantExtension:function(t){if(!t||"object"!=typeof t)return{error:ae};if(!t.participantId)return{error:Ae};const e=t.tournamentRecord?.participants||[],n=Fi({participantId:t.participantId,tournamentParticipants:e});return n?Dr({element:n,name:t.name}):{error:Ee}},removeTournamentExtension:Li,setTournamentCategories:function({tournamentRecord:t,categories:e}){return t?(e=(e||[]).filter((t=>t.categoryName&&t.type)),t.tournamentCategories=e,{...E}):{error:_}},setTournamentDates:pD,setTournamentEndDate:function({tournamentRecord:t,endDate:e}){return pD({tournamentRecord:t,endDate:e})},setTournamentName:function({tournamentRecord:t,promotionalName:e,tournamentName:n,formalName:r}){return t?(n&&(t.tournamentName=n),e&&(t.promotionalName=e),r&&(t.formalName=r),t.promotionalName===t.tournamentName&&delete t.promotionalName,t.formalName===t.tournamentName&&delete t.formalName,{...E}):{error:_}},setTournamentNotes:function({tournamentRecord:t,notes:e}){return t?Gg({element:t,notes:e}):{error:_}},setTournamentStartDate:function({tournamentRecord:t,startDate:e}){return pD({tournamentRecord:t,startDate:e})},setTournamentStatus:function({tournamentRecord:t,status:e}){return t?e&&!Object.keys(dD).includes(e)?{error:Nn,info:"Unknown status"}:(t.tournamentStatus=e,{...E}):{error:_}}};const mD=["collectionId","collectionPosition","drawPositions","extensions","finishingPositionRange","finishingRound","isMock","matchUpId","matchUpStatus","matchUpStatusCodes","orderOfFinish","processCodes","roundNumber","tieFormat","tieMatchUps","roundPosition","score","sides","winnerMatchUpId","loserMatchUpId","matchUpDuration","winningSide"];function fD(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,fD(t[i],e,n.concat(i)))),{})}const hD={allNumeric:R,allPlayoffPositionsFilled:function(t){const{drawDefinition:e,structureId:n}=t;if(!e)return{error:j};const{playoffStructures:r}=Nh({drawDefinition:e,structureId:n});if(!r?.length)return!1;const i=e?.entries?.filter((t=>t?.entryStatus&&ou.includes(t.entryStatus)))?.length??0;let a=0;return(r||[]).reduce(((t,e)=>{const n=rs({structure:e}).positionAssignments??[],r=n?.filter((t=>(t.participantId&&a++,t?.bye??t?.participantId))).length;return!(!r||!t)}),!!r.length)||a===i},attributeFilter:_r,calculateWinCriteria:Jf,chunkArray:N,chunkByNth:A,chunkSizeProfile:function t(e,[n,...r]){return e.length?[e.slice(0,n),...t(e.slice(n),[...r,n])]:[]},compareTieFormats:Uh,constantToString:wm,countValues:function(t){return I(g(t))},createMap:Ia,dateRange:Jr,dateTime:hi,definedAttributes:vr,dehydrateMatchUps:function({tournamentRecord:t}){if(!t)return{error:_};if("object"!=typeof t||!t.tournamentId)return{error:Nn};const{matchUps:e}=hl({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))mD.includes(t)||delete n[t];n.sides&&n.drawPositions&&!n.tieMatchUps&&delete n.sides,o&&(n.matchUpFormat=o)}}(e,n)}return{...E}},extractAttributes:Ua,flattenJSON:fD,generateHashCode:function(t){if(null===t||"object"!=typeof t)return;const e=JSON.stringify(t),n=Sa(t),r=e.split("").reduce(((t,e)=>t+e.charCodeAt(0)),0);return[e.length,n,r].map((t=>t.toString(36))).join("")},generateRange:w,generateTimeCode:OT,getCategoryAgeDetails:uh,getMatchUpContextIds:function({matchUps:t,matchUpId:e}){if(!yc(t))return{error:Nn};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}},getScaleValues:xr,getSeedingThresholds:function({roundRobinGroupsCount:t,participantsCount:e}){if(t){const{validGroupSizes:n}=lf({drawSize:e}),r=n?.map((t=>Math.ceil(e/t)));if(!r?.includes(t))return wr({context:{roundRobinGroupsCount:t},result:{error:Nn}})}const{seedGroups:n}=ff({drawSize:e,roundRobinGroupsCount:t}),r=n?.map((t=>Math.min(...t)))||[];return{...E,seedingThresholds:r}},getTimeItem:il,getValidGroupSizes:lf,groupValues:I,hasAttributeValues:t=>e=>Object.keys(t).every((n=>e[n]===t[n])),instanceCount:g,intersection:P,isAdHoc:ap,isCompletedStructure:Mh,isConvertableInteger:p,isNumeric:s,isOdd:c,isPowerOf2:r,JSON2CSV:function(t,e){if(e&&"object"!=typeof e)return Nn;let{columnTransform:n={}}=e||{};const{includeTransformAccessors:r,includeHeaderRow:i=!0,returnTransformedJSON:a,removeEmptyColumns:o,onlyHeaderRow:c,columnAccessors:u=[],functionMap:d={},columnMap:p={},valuesMap:l={},context:m={},delimiter:f='"',columnJoiner:h=",",rowJoiner:g="\r\n",keyJoiner:I="."}=e||{};if(!Array.isArray(t)||!Array.isArray(u)||"object"!=typeof m||"object"!=typeof p||"object"!=typeof n||"object"!=typeof d||"object"!=typeof l||"string"!=typeof h||"string"!=typeof g||"string"!=typeof I||"string"!=typeof f)return Nn;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=>fD(t,I))),S=Object.values(n).flat();r&&u.push(...S);const y=U.reduce(((t,e)=>Object.keys(e).every((e=>!t.includes(e)&&t.push(e)||!0))&&t),[]).filter((t=>!u?.length||u.includes(t))),v=Object.assign({},...Object.keys(n).reverse().map((t=>n[t].map((e=>({[e]:t}))).flat())).flat()),w=y.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(p).forEach((t=>!w.includes(t)&&w.unshift(t))),Object.keys(n).forEach((t=>!w.includes(t)&&w.unshift(t))),"object"==typeof m&&Object.keys(m).forEach((t=>!w.includes(t)&&w.unshift(t)));let T=w.map((t=>p[t]||t));if(c)return[T];const P=t=>`${f}${t}${f}`,D=[];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])||m?.[r]||"",s=l[r]?.[o]||o,c="function"==typeof d[r]?d[r](s):s;return e[r]=P(c),c&&(D[i]=(D[i]||0)+1),e}),{}))));const N=o&&[...D].map(((t,e)=>!t&&e)).filter(s).reverse();if(N){const t=t=>t.filter(((t,e)=>!N.includes(e)));b=b.map(t),T=t(T)}const R=b.map((t=>t.join(h)));return a?R.map((t=>{const e=t.split(h);return Object.assign({},...e.map(((t,e)=>({[T[e]]:t}))))})):i?[T.map(P).join(h),...R].join(g):R.join(g)},makeDeepCopy:gi,matchUpSort:Il,nearestPowerOf2:o,nextPowerOf2:u,noNulls:function(t){return t?.map((t=>null===t?void 0:t))},noNumeric:M,numericSort:e,occurrences:function(t,e){return e.reduce(((t,e)=>(t[e]=1+t[e]||1,t)),{})[t]||0},overlap:b,randomMember:v,randomPop:y,roundRobinGroups:df,shuffleArray:f,structureSort:Xo,subSort:function(t,e,n,r){return[].concat(...t.slice(0,e),...t.slice(e,e+n).sort(r),...t.slice(e+n,t.length))},tieFormatGenderValidityCheck:oh,undefinedToNull:function t(e,n){if(void 0===e)return null;if("object"!=typeof 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:m,UUID:Md,UUIDS:function(t=1){return w(0,t).map(Md)},validateCategory:dh,visualizeScheduledMatchUps:function({scheduledMatchUps:t,showGlobalLog:e}){Tl.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=>{Pl({color:"blue",method:"draw",structure:r[e],keyColors:{structure:"magenta"}},!0);const n=t.filter((t=>t.structureId===e)),i=vc({matchUps:n})?.roundMatchUps||[];Object.keys(i).forEach((t=>{Pl({roundNumber:t,keyColors:{roundNumber:"brightcyan"}},!0),i[t].forEach((({matchUpId:t,schedule:e})=>{Pl({matchUpId:t,time:ni(e.scheduledTime),date:e.scheduledDate,venue:e.venueId,keyColors:{time:"brightcyan",date:"brightcyan",matchUpId:"yellow",venue:"magenta"}},!0)}))}))})),e&&Dl()}},gD=hD;function ID(t){if(!t?.tournamentRecord&&!Array.isArray(t?.venueMatchUps))return{error:_};if(!t?.courtId)return{error:ie};const{scheduleVisibilityFilters:e,tournamentRecord:n,matchUpFilters:r,venueMatchUps:i,courtId:a}=t,{schedulingProfile:o}=Om({tournamentRecord:n});if(Array.isArray(i))return{matchUps:c({matchUps:i,courtId:a})};const{matchUps:s}=hl({scheduleVisibilityFilters:e,tournamentRecord:n,matchUpFilters:r});return{matchUps:c({matchUps:s,courtId:a})};function c({matchUps:t,courtId:e}){return hw({matchUps:t.filter((t=>{const n=t.schedule?.allocatedCourts?.map((({courtId:t})=>t));return t.schedule?.courtId===e||n?.includes(e)})),schedulingProfile:o})}}function UD({tournamentRecord:t,dateAvailability:e,disableNotice:n,venueMatchUps:r,courtId:i,force:a}){if(!t)return{error:_};if(!i)return{error:ie};const o=Uv({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(Iv);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(di(ui(n),ui(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=Od({tournamentRecord:t,courtId:i});if(u.error)return u;const{court:d,venue:p}=u,{matchUps:l}=ID({tournamentRecord:t,venueMatchUps:r,courtId:i});if(l?.length){const e=Dc({tournamentRecord:t})?.appliedPolicies,n=a??e?.[Ni]?.allowDeletionWithScoresPresent?.courts,r=[];r.length&&(n||console.log("throw error: scheduled court matchUps",r.length))}return d&&(d.dateAvailability=e,!n&&p&&sr({payload:{venue:p,tournamentId:t.tournamentId},topic:Ts,key:p.venueId})),{...E,totalMergeCount:c}}function SD({matchUpsCount:t=0}){return{error:Gn,info:`Schedule would be deleted from ${t} ${1===t?"matchUp":"matchUps"}; use { force: true }`}}function yD({tournamentRecord:t,drawDefinition:e,matchUpId:n,drawId:r}){if(!n)return{error:qt};if(!e&&!r)return{error:at};let i;if(!e){if(!t)return{error:_};({drawDefinition:e}=Vd({tournamentRecord:t,drawId:r}))}if(e)({matchUp:i}=Xm({drawDefinition:e,matchUpId:n}));else{if(!t)return{error:_};const e=hl({tournamentRecord:t,inContext:!1}).matchUps??[];({matchUp:i}=Zm({matchUps:e,matchUpId:n}))}if(!i)return{error:Wt};if(i.timeItems){i.timeItems.find((t=>[Du,Pu].includes(t.itemType)))&&(i.timeItems=i.timeItems.filter((({itemType:t})=>![Du,Pu].includes(t))),xs({tournamentId:t?.tournamentId,context:"removeCourtAssignment",drawDefinition:e,matchUp:i}))}return{...E}}function vD(t){if("string"!=typeof t?.venueId)return{error:an};const{tournamentRecord:e,venueId:n,force:r}=t,i=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!Object.keys(i).length)return{error:_};const a=gl({tournamentRecords:i,contextFilters:{venueIds:[n]}}).matchUps??[],o=Dc({tournamentRecord:e})?.appliedPolicies,s=r??o?.[Ni]?.allowDeletionWithScoresPresent?.venues;if(a.length&&!s)return SD({matchUpsCount:a.length});for(const t of Object.values(i)){for(const e of a){const n=yD({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&&sr({payload:{venueId:n,tournamentId:t.tournamentId},topic:ls,key:n})}return km({tournamentRecords:i}),{...E}}function wD({tournamentRecord:t,courtIds:e,dates:n}){const r=!Array.isArray(n)||!n.length||{dates:n},i=t=>Nr({extension:{value:r,name:$i},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{...E}}function TD({tournamentRecord:t,venueIds:e}){for(const n of t.venues||[])if(e?.includes(n.venueId)){const t=Nr({creationTime:!1,element:n,extension:{name:$i,value:!0}});if(t.error)return t}return{...E}}function PD({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}=Mr({element:t,name:$i});if(e){const n=e.value;Array.isArray(n.dates)&&(n.dates=n.dates.filter((t=>!r.includes(t)))),Nr({extension:{name:$i,value:n},creationTime:!1,element:t})}}else Dr({element:t,name:$i});return{...E}}function DD({tournamentRecord:t,disableNotice:e,courtId:n,force:r}){const i=Od({tournamentRecord:t,courtId:n});if(i.error)return i;const a=i.venue,{matchUps:o}=ID({tournamentRecord:t,courtId:n}),s=Dc({tournamentRecord:t})?.appliedPolicies,c=r??s?.[Ni]?.allowDeletionWithScoresPresent?.courts;if(o?.length&&!c)return SD({matchUpsCount:o.length});for(const e of o??[]){const n=yD({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||sr({payload:{venue:a,tournamentId:t.tournamentId},topic:Ts,key:a.venueId})),{...E}}function bD(t){const{disableNotice:e,modifications:n,courtId:r,force:i,venueMatchUps:a}=t,o=nc(t);if(!Object.keys(o).length)return{error:x};let s;for(const t of Object.values(o)){const o=ND({tournamentRecord:t,disableNotice:e,venueMatchUps:a,modifications:n,courtId:r,force:i});if(o?.error)return o;s=!0}return s?{...E}:undefined}function ND({tournamentRecord:t,disableNotice:e,venueMatchUps:n,modifications:r,courtId:i,force:a}){if(!t)return{error:_};if(!i)return{error:ie};if(!r||"object"!=typeof r)return{error:Pn};const o=Od({tournamentRecord:t,courtId:i});if(o.error)return o;const{venue:s,court:c}=o,u=Object.keys(fv()).filter((t=>"courtId"!==t));if(!Object.keys(r).filter((t=>u.includes(t))).length)return{error:En};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=UD({dateAvailability:r.dateAvailability,tournamentRecord:t,venueMatchUps:n,disableNotice:e,courtId:i,force:a});if(o.error)return o}return e||sr({payload:{venue:s,tournamentId:t.tournamentId},topic:Ts,key:s?.venueId}),{...E,court:gi(c)}}const RD=()=>({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,addresses:[],contacts:[],courts:[],roles:[]});function MD({tournamentRecord:t,modifications:e,venueId:n,force:r}){if(!t)return{error:_};if(!e||"object"!=typeof e)return{error:Pn};if(!n)return{error:an};const i=Dc({tournamentRecord:t})?.appliedPolicies,a=r??i?.[Ni]?.allowDeletionWithScoresPresent?.venues,{matchUps:o}=function({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:n,venueId:r}){if(!e)return{error:_};if(!r)return{error:an};const{schedulingProfile:i}=Om({tournamentRecord:e}),{matchUps:a}=hl({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:n});return{matchUps:function({matchUps:t,venueId:e}){return hw({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})}}({tournamentRecord:t,venueId:n}),s=Cd({tournamentRecord:t,venueId:n});if(s.error)return s;const c=s.venue,u=Object.keys(RD()).filter((t=>"venueId"!==t));if(!Object.keys(e).filter((t=>u.includes(t))).length)return{error:En};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=l.filter((t=>!m.includes(t))),h=[];if(f.length){const e=c?.courts?.filter((t=>f.includes(t.courtId))),n=e?.map((e=>{const n=ID({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 SD({matchUpsCount:n});c.courts=c.courts?.filter((t=>m.includes(t.courtId))),Qy({schedule:{courtId:"",scheduledDate:""},matchUpDetails:h,removePriorValues:!0,tournamentRecord:t})}if(e.courts)for(const i of e.courts){const{courtId:e}=i||{};let a=bD({modifications:i,disableNotice:!0,tournamentRecord:t,venueMatchUps:o,courtId:e,force:r});if(a.error===tn&&(a=Sv({disableNotice:!0,tournamentRecord:t,venueId:n,court:i})),a.error)return a}return km({tournamentRecord:t}),c&&sr({payload:{venue:c,tournamentId:t.tournamentId},topic:Ts,key:c?.venueId}),{...E,venue:gi(c)}}const AD={addCourt:Sv,addCourts:yv,addVenue:Ad,deleteCourt:function(t){const{courtId:e,disableNotice:n,force:r}=t,i=nc(t),a=Lp(t,[{[sp]:!0,[Tp]:!0}]);if(a.error)return a;let o,s;for(const t of Object.values(i)){if(s=DD({tournamentRecord:t,disableNotice:n,courtId:e,force:r}),s.error&&s.error!==tn)return s;s.success&&(o=!0)}return o?{...E}:s},deleteVenue:vD,deleteVenues:function({tournamentRecord:t,venueIds:e,force:n}){if(!t)return{error:_};if(!Array.isArray(e))return{error:Nn};for(const r of t.venues||[]){const{venueId:i}=r;if(e.includes(i)){const{venueId:e}=r,i=vD({tournamentRecord:t,venueId:e,force:n});if(i.error)return i}}return{...E}},disableCourts:function(t){const{courtIds:e,dates:n}=t,r=nc(t),i=Lp(t,[{[sp]:!0,[yp]:!0}]);if(i.error)return i;for(const t of Object.values(r))wD({tournamentRecord:t,courtIds:e,dates:n});return{...E}},disableVenues:function(t){const{tournamentRecords:e,tournamentId:n,venueIds:r}=t,i=Lp(t,[{[sp]:!0,[vp]:!0}]);if(i.error)return i;const a=Object.keys(e).filter((t=>!n||t===n));for(const t of a){TD({tournamentRecord:e[t],venueIds:r})}return{...E}},enableCourts:function(t){const e=nc(t),n=[{[sp]:!0}];!t.enableAll&&n.push({[yp]:!0});const r=Lp(t,n);if(r.error)return r;const{enableAll:i,courtIds:a,dates:o}=t;for(const t of Object.values(e))PD({tournamentRecord:t,courtIds:a,enableAll:i,dates:o});return{...E}},enableVenues:function(t){const e=nc(t),n=[{[sp]:!0}];!t.enableAll&&n.push({[vp]:!0});const r=Lp(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))&&Dr({element:e,name:$i});return{...E}},findVenue:function({convertExtensions:t,...e}){const{tournamentRecords:n,tournamentRecord:r,venueId:i}=e;return gi(Cd({tournamentRecords:n,tournamentRecord:r,venueId:i}),t,!0)},modifyCourt:bD,modifyCourtAvailability:UD,modifyVenue:function(t){const{modifications:e,venueId:n,force:r}=t,i=nc(t);if(!Object.keys(i).length)return{error:x};if("string"!=typeof n)return{error:an};let a,o;for(const t of Object.values(i)){const i=MD({tournamentRecord:t,modifications:e,venueId:n,force:r});if(i.success&&(o=!0),i.error&&(a=i.error),i.error&&i.error!==rn)return i}return km({tournamentRecords:i}),o?{...E}:{error:a}}},ED={competitionGovernor:va,eventGovernor:VS,generationGovernor:hy,matchUpFormatGovernor:lh,mocksGovernor:Yv,participantGovernor:nw,policyGovernor:iw,publishingGovernor:sw,queryGovernor:MT,reportGovernor:CT,scheduleGovernor:GT,scoreGovernor:uD,tournamentGovernor:lD,utilitiesGovernor:hD,venueGovernor:AD},CD={};function OD(t){const{mutationStatus:e,tournamentId:n,directives:r,timeStamp:i}=t||{},{topics:a}=lr();for(const t of[...a].sort(xD)){const e=ur({topic:t});e&&mr({topic:t,notices:e})}e&&i&&a.includes(Ps)&&mr({notices:[{tournamentId:n,directives:r,timeStamp:i}],topic:Ps})}async function FD(t){const{mutationStatus:e,tournamentId:n,directives:r,timeStamp:i}=t||{},{topics:a}=lr();for(const t of[...a].sort(xD)){const e=ur({topic:t});e&&await mr({topic:t,notices:e})}e&&i&&a.includes(Ps)&&mr({notices:[{tournamentId:n,directives:r,timeStamp:i}],topic:Ps})}const kD={[Ms]:5,[Rs]:5,[As]:5,[vs]:5,[ys]:5,[hs]:5,[gs]:5,[Is]:5,[Us]:1,[Es]:1,[Ss]:5,[Ts]:5,[fs]:4,[ps]:4,[ls]:4,[ms]:4,[os]:3,[as]:2};function xD(t,e){return(kD[e]||0)-(kD[t]||0)}const{FACTORY:_D}=da;function LD({timeStamp:t}){const e=gr(),n=or();return n&&Object.values(e).forEach((e=>{!function({tournamentRecord:t,value:e}){const{extension:n}=Mr({element:t,name:_D});Nr({element:t,extension:{name:_D,value:{...n?.value,...e}}})}({tournamentRecord:e,value:{version:"2.0.0-alpha.0",timeStamp:t}})})),n}function BD({engineType:t,methodName:e,elapsed:n,params:r,result:i}){const a=Qn();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&&function(t,e){if(Kn.globalLog)try{Kn.globalLog({engine:t,log:e})}catch(n){console.log("globalLog error",n),console.log(t,e),tr()}else console.log(t,e)}(t,o)}function VD({methodName:t,params:e,start:n}){const r={error:jn,methodName:t};return BD({result:r,methodName:t,elapsed:n?Date.now()-n:0,params:e,engineType:"sync"}),r}function jD(t,e,n,r,i){delete t.success,delete t.error;const a=Date.now(),o=fr();if(n&&(n.activeTournamentId=o),n?.sandboxTournament&&!n?.sandboxTournament.tournamentId)return{error:Nn};const s=n?.sandboxTournament||hr(o),c=n?.sandboxTournament?{[n?.sandboxTournament.tournamentId]:n.sandboxTournament}:gr(),u=n?function(t,e){if(!1===e._middleware)return e;if(e.tournamentId&&!t[e.tournamentId])return{error:_};const n=e.drawId||e.matchUp?.drawId;if(n){const{event:r,drawDefinition:i,tournamentId:a}=Vd({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}=Vd({eventId:e.eventId,tournamentRecords:t});if(!n)return{error:Pt};e.tournamentId=r,e.event=n}const r=e.tournamentId??fr();if(!r&&e)return e;const i=t[r];return r&&!i?{error:_}:i?(e.tournamentRecord=i,e):e}(c,n):void 0;if(u?.error)return u;const d=function({tournamentRecords:t,tournamentRecord:e,params:n,methodName:r,method:i}){if(Qn())return i({tournamentRecords:t,tournamentRecord:e,...n});try{return i({tournamentRecords:t,tournamentRecord:e,...n})}catch(t){return yr({engineName:"engine",methodName:r,params:n,err:t})}}({params:u,tournamentRecords:c,tournamentRecord:s,methodName:r,method:e});return BD({result:d,methodName:r,elapsed:Date.now()-a,params:n,engineType:i}),d}function GD(t,e=!0){return"object"!=typeof t||Array.isArray(t)?{error:Pn}:t?.tournamentId?(n=e?gi(t):t,Jn.setTournamentRecord(n)):{error:Nn};var n}function qD(t,e=!0){if("object"!=typeof t)return{error:Pn};if(Ur(),Array.isArray(t)){if(!(t.filter((t=>t?.tournamentId)).length===t.length))return{error:k};t=Object.assign({},...t.map((t=>({[t.tournamentId]:t}))))}else if(t?.tournamentId)Ur((t={[t.tournamentId]:t}).tournamentId);else{if(!Object.keys(t).every((e=>t[e].tournamentId===e)))return{error:k}}return Ir(e?gi(t):t)}async function $D(t,e){if(!ha(e))return{error:Nn};const n=Object.values(e).filter(ma).length;if(n>1)return{error:Nn};const r=n?Object.keys(e).find((t=>ma(e[t]))):fa(e.method)&&e.method;if(!r)return{error:Nn};const{[r]:i,...a}=e,o=e?.params||{...a},s=o.rollbackOnError&&gi(gr(),!1,!0),c=i||t[r]||Yn()[r];if(!c)return VD({methodName:r,params:o});const u=await jD(t,c,o,r,"async")??{};u?.error&&s&&qD(s);const d=Date.now(),p=LD({timeStamp:d}),l=u?.success&&!0!==o?.delayNotify&&!0!==o?.doNotNotify;return l&&await FD({directives:[{method:c,params:o}],mutationStatus:p,timeStamp:d}),(l||!u?.success||o?.doNotNotify)&&pr(),u}function WD(t,e,n){if(!ha(n))return{error:Nn};var r;!(r=n)||("object"!=typeof r||Jn.setMethods(r));return Object.keys(n).filter((t=>ma(n[t]))).forEach((r=>{t[r]=i=>{const a=()=>e(t,{[r]:n[r],...i});if(Qn())return a();try{return a()}catch(t){yr({engineName:"engine",methodName:r,params:i,err:t})}}})),{...E,...t}}function HD(t,e){return e?.error?(t.error=e.error,t.success=!1):(t.error=void 0,t.success=!0),t}function zD(t,e){t.importMethods=n=>WD(t,e,n),t.getTournament=t=>function(t){const{convertExtensions:e=!1,removeExtensions:n=!1}=t??{},r=t?.tournamentId??fr();return"string"!=typeof r?{}:{tournamentRecord:gi(hr(r),e,!1,n)}}(t),t.getState=t=>function({convertExtensions:t,removeExtensions:e}){const n=gr();return{tournamentId:fr(),tournamentRecords:gi(n,t,!1,e)}}({convertExtensions:t?.convertExtensions,removeExtensions:t?.removeExtensions}),t.version=()=>"2.0.0-alpha.0",t.reset=()=>(Ir({}),HD(t)),t.devContext=e=>(er(e),HD(t)),t.getDevContext=t=>Qn(t),t.newTournamentRecord=(t={})=>{const e=sv(t),n=e.tournamentId;return e.error?e:(GD(e),Ur(n),{...E,tournamentId:n})},t.setState=(e,n,r)=>{rr(n,r);const i=qD(e,n);return HD(t,i)},t.setTournamentId=t=>Ur(t),t.setTournamentRecord=(e,n,r)=>{rr(n,r);const i=GD(e,n);return HD(t,i)},t.removeTournamentRecord=e=>{const n=function(t){return Jn.removeTournamentRecord(t)}(e);return HD(t,n)},t.removeUnlinkedTournamentRecords=()=>{const e=function(){const t=gr(),{extension:e}=Mr({name:Xi,tournamentRecords:t,discover:!0}),n=e?.value?.tournamentIds||[];return Object.keys(t).forEach((e=>{n.includes(e)||delete t[e]})),Ir(t)}();return HD(t,e)}}function YD(t){const e=function(){if(Jn.createInstanceState){try{Jn.createInstanceState()}catch(t){return{error:t}}return{success:!0}}return{error:ln}}();if(e.error&&!t)return e;const n={executionQueue:(t,e)=>async function(t,e,n){if(!Array.isArray(e))return{error:Nn};const r=cr(),i=Date.now(),a=n&&gi(gr(),!1,!0),o=[];for(const n of e){if("object"!=typeof n)return{error:Nn};const{method:e,params:s}=n;if(!r[e])return VD({methodName:e,start:i,params:s});const c=jD(t,r[e],s,e,"async");if(c?.error)return a&&qD(a),{...c,rolledBack:!!a};o.push({...c,methodName:e})}const s=Date.now();return FD({directives:e,mutationStatus:LD({timeStamp:s}),timeStamp:s}),pr(),{success:o.every((t=>t.success)),results:o}}(n,t,e),execute:t=>$D(n,t)};return zD(n,$D),n}function KD(t,e){if(!ha(e))return{error:Nn};const n=Object.values(e).filter(ma).length;if(n>1)return{error:Nn};const r=n?Object.keys(e).find((t=>ma(e[t]))):fa(e.method)&&e.method;if(!r)return{error:Nn};const{[r]:i,...a}=e,o=e?.params||{...a},s=i||t[r]||Yn()[r];return s?jD(t,s,o,r,"ask"):VD({methodName:r,params:o})}const JD=(()=>{const t={execute:e=>KD(t,e)};return zD(t,KD),t})();function ZD(t,e){if(!ha(e))return{error:Nn};const n=Object.values(e).filter(ma).length;if(n>1)return{error:Nn};const r=n?Object.keys(e).find((t=>ma(e[t]))):fa(e.method)&&e.method;if(!r)return{error:Nn};const{[r]:i,...a}=e,o=e?.params||{...a},s=o.rollbackOnError&&gi(gr(),!1,!0),c=i||t[r]||Yn()[r];if(!c)return VD({methodName:r,params:o});const u=jD(t,c,o,r,"sync")??{};u?.error&&s&&qD(s);const d=Date.now(),p=LD({timeStamp:d}),l=u?.success&&!0!==o?.delayNotify&&!0!==o?.doNotNotify;return l&&OD({directives:[{method:c,params:o}],mutationStatus:p,timeStamp:d}),(l||!u?.success||o?.doNotNotify)&&pr(),u}const XD=(()=>{const t={executionQueue:(e,n)=>function(t,e,n){if(!Array.isArray(e))return{error:Nn};const r=cr(),i=Date.now(),a=n&&gi(gr(),!1,!0),o=[];for(const n of e){if("object"!=typeof n)return{error:Nn};const{method:e,params:s}=n;if(!r[e])return VD({methodName:e,start:i,params:s});const c=jD(t,r[e],s,e,"sync");if(c?.error)return a&&qD(a),{...c,rolledBack:!!a};o.push({...c,methodName:e})}const s=Date.now();return OD({directives:e,mutationStatus:LD({timeStamp:s}),timeStamp:s}),pr(),{success:o.every((t=>t.success)),results:o}}(t,e,n),execute:e=>ZD(t,e)};return zD(t,ZD),t})(),QD={...va,...nw,...sw,...hy,...lD,...GT,...iw,...CT,...VS,...MT,...uD,...AD};XD.importMethods(QD);const tb=XD,eb=XD;let nb,rb={};function ib(t,e=!0){if(!t)return{error:ae};if("object"!=typeof t)return{error:Pn};if(t.matchUpId)nb=t.matchUpId,rb[nb]=e?gi(t):t;else if(Array.isArray(t))for(const n of t.reverse())n.matchUpId&&(rb[n.matchUpId]=e?gi(n):n,nb||(nb=n.matchUpId));else for(const n of Object.values(t))n.matchUpId&&(rb[n.matchUpId]=e?gi(n):n,nb||(nb=n.matchUpId));return e?gi(t):t}const ab=(()=>{const t={getState:t=>function(t){return gi(rb[nb],t?.convertExtensions,!1,t?.removeExtensions)}(t),version:()=>"2.0.0-alpha.0",reset:()=>(nb=void 0,rb={},{...E}),drawId:void 0,error:void 0,success:!1,devContext:e=>(er(e),t),setState:(e,n,r)=>{rr(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}(ib(e))}};return function(n){n.forEach((n=>{Object.keys(n).forEach((r=>{t[r]=t=>{if(Qn())return e({params:t,governor:n,methodName:r});try{return e({params:t,governor:n,methodName:r})}catch(e){yr({engineName:"matchUpEngine",methodName:r,params:t,err:e})}}}))}))}([uD]),t;function e({params:e,governor:n,methodName:r}){t.error=void 0,t.success=!1;const i=e?.matchUp||rb[nb],a=e?.matchUps||Object.values(rb),o=e?.rollbackOnError&&gi(i,!1,!0);e={...e,matchUpId:i?.matchUpId,matchUps:a,matchUp:i};const s=n[r](e);if(s?.error)return o&&ib(o),{...s,rolledBack:!!o};const c=s?.success&&!0!==e?.delayNotify&&!0!==e?.doNotNotify;return c&&OD(),(c||!s?.success||e?.doNotNotify)&&pr(),s}})();let ob=!1;const sb=(()=>{const t={version:()=>"2.0.0-alpha.0",setDeepCopy:(e,n)=>(rr(e,n),t),devContext:e=>(er(e),ob=!0,t)};return function(e){e.forEach((e=>{Object.keys(e).forEach((n=>{t[n]=t=>{try{return function(t,e){const n=t({...e});n?.error||OD();pr(),ob&&(er(!1),ob=!1);return n}(e[n],t)}catch(e){let r;"string"==typeof e?r=e.toUpperCase():e instanceof Error&&(r=e.message),console.log("ERROR",{params:JSON.stringify(t),method:n,error:r})}}}))}))}([Yv]),t})();function cb(t,e){return t&&e&&Array.isArray(e)&&e[t-1]||"object"==typeof e&&e[t]}function ub(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,m=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))));return{awardProfile:m}}function db({participantWon:t,flightNumber:e,valueObj:n,drawSize:r,flights:i,level:a}){const o=(t,e)=>{const n=t?.value||t?.v||(p(t)?t:0),r=cb(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||p(r)&&r||n}};let s,c,u,d,l=0;const m=(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!==m&&(t=t?.[m],i=i?.[m],a=a?.[m]),c=o(t,e).value,u=o(i,e).value,d=o(a,e).value,l=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!==m&&(t=t?.[m],i=i?.[m]),c=o(t,e).value,d=o(i,e).value,l=c||d,s=c?t.requireWin:i?.requireWin}else p(n)&&void 0===m&&(l=n);return e&&i?.pct?.[e]&&(l=Math.round(l*i.pct[e])),{awardPoints:l,requireWin:s}}const pb={getTournamentPoints:function({participantFilters:t,policyDefinitions:e,tournamentRecord:n,saveRankings:r,level:i}){if(!n)return{error:_};const{policyDefinitions:a}=bc({policyTypes:[Ti],tournamentRecord:n}),o=e?.[Ti]??a?.[Ti];if(!o)return{error:Jt};const s=o.awardProfiles;let c=o.requireWinFirstRound;const u=o.requireWinForPoints,{participants:d,derivedEventInfo:p,derivedDrawInfo:l,mappedMatchUps:f}=Zl({withRankingProfile:!0,participantFilters:t,tournamentRecord:n}),h=d?.filter((t=>t.draws?.length)),g={},I={},U={};for(const t of h??[]){const{participantType:e,participantId:r,person:a,draws:o}=t;for(const d of o){const{drawId:o,structureParticipation:h,eventId:S}=d,y=p[S],v=l[o],w=v?.drawType,{category:T,eventType:P}=y||{},D=d.startDate||y.startDate||n.startDate,b=d.endDate||y.endDate||n.endDate;if(P===ad&&r!==oc)continue;let N;if(s){let n,d=u,p=0,l=0,S=0;for(const a of h){const{finishingPositionRange:o,participationOrder:u,participantWon:h,flightNumber:g,rankingStage:I,winCount:U}=a;p+=U||0;const y=v?.drawSize,{awardProfile:R}=ub({awardProfiles:s,participation:a,eventType:P,startDate:D,category:T,drawSize:y,drawType:w,endDate:b,level:i});if(R){if(!y)continue;const t=Array.isArray(o)&&Math.max(...o),e=m(o||[]).join("-"),r=t&&I!==Qa&&o?.includes(y);void 0!==R.requireWinForPoints&&(d=R.requireWinForPoints),void 0!==R.requireWinFirstRound&&(c=R.requireWinFirstRound);const{finishingPositionPoints:a={},finishingPositionRanges:s,finishingRound:p,pointsPerWin:f,flights:v}=R,w=Array.isArray(R.perWinPoints)?R.perWinPoints?.find((t=>t.participationOrders?.includes(u))):R.perWinPoints,T=a.participationOrders;let P,D=0;if((!T||T.includes(u))&&s&&t){const e=s[t];e&&({awardPoints:D,requireWin:P}=db({flightNumber:g,valueObj:e,drawSize:y,flights:v,level:i}))}if(!D&&p&&1===u&&t){const e=p[t];e&&({awardPoints:D,requireWin:P}=db({participantWon:h,flightNumber:g,valueObj:e,drawSize:y,flights:v,level:i}))}if(r&&void 0!==c&&(d=c),void 0!==P&&(d=P),D>l&&(!d||U)&&(l=D,n=t),!D&&f&&U&&(S+=U*f,n=e),!D&&U&&w){const t=cb(i,w?.level);t?S+=U*t:w.value&&(S+=U*w.value)}}if(N=l+S,e===oc){const e=(t.matchUps||[]).filter((({structureId:t})=>t===a.structureId));for(const{matchUpId:t}of e){const e=f[t],n=e.sides.find((t=>t.participantId===r)).sideNumber;if(e.winningSice===n)for(const t of e.tieMatchUps)t.winningSide}}}if(S||l){const t={winCount:p,positionPoints:l,rangeAccessor:n,perWinPoints:S,eventType:P,drawId:o,points:N},i=a?.personId;i?(g[i]||(g[i]=[]),g[i].push(t)):e===uc?(U[r]||(U[r]=[]),U[r].push(t)):e===oc&&(I[r]||(I[r]=[]),I[r].push(t))}}}}if(r){Nr({element:n,extension:{name:na,value:{personPoints:g,teamPoints:I,pairPoints:U}}})}return{participantsWithOutcomes:h,personPoints:g,pairPoints:U,teamPoints:I,...E}}};const lb={nSpread:400,diffThreshold:.125,kCalc:t=>250/Math.pow(t+5,.4),kMultiplier:function(t=3,e=2){const n=t/e;return isNaN(n)?lb.kDefault():n},kDefault:()=>1};function mb(t){let{winnerRating:e,loserRating:n,ratingRange:r}=t;const{ratings:i=MU,winnerCountables:a=1,loserCountables:o=0,ratingType:s=DU,maxCountables:c,countables:u}=t||{},d=i?.[s];if(!d)return{error:ae};r=d.range||r,e=e||d.defaultInitialization,n=n||d.defaultInitialization;const p=r[0]>r[1],l=d.decimalsCount||0,m=p?r.slice().reverse():r,f=(t,e)=>parseFloat(e)>=Math.min(...t)&&parseFloat(e)<=Math.max(...t);f(r,e)&&f(r,n)||(f(r,e)||(e=d.defaultInitialization),f(r,n)||(n=d.defaultInitialization));const h=({value:t,sourceRange:e,targetRange:n})=>(t-e[0])*(n[1]-n[0])/(e[1]-e[0])+n[0],g=h({targetRange:MU[DU].range,sourceRange:m,value:p?r[0]-e:e}),I=h({targetRange:MU[DU].range,sourceRange:m,value:p?r[0]-n:n}),U=(t,e)=>1/(1+Math.pow(10,(e-t)/lb.nSpread)),S=U(g,I),y=U(I,g),v=lb.kCalc(a),w=lb.kCalc(o),T=lb.kMultiplier(c,u),P=g+T*v*(1-S),D=I+T*w*(0-y),b=h({sourceRange:MU[DU].range,value:P,targetRange:m}),N=h({sourceRange:MU[DU].range,value:D,targetRange:m}),R=p?r[0]-b:b;let M=parseFloat(parseFloat(R).toFixed(l));const A=p?r[0]-N:N;let E=parseFloat(parseFloat(A).toFixed(l));const C=Math.max(...r)?Math.abs(e-n)/Math.max(...r):0;return(b>N&&C>lb.diffThreshold||M<0||E<0)&&(M=e,E=n),{newWinnerRating:M,newLoserRating:E}}const fb={calculateNewRatings:mb,generateDynamicRatings:function({removePriorValues:t=!0,tournamentRecord:e,ratingType:n=DU,considerGames:r,matchUpIds:i,asDynamic:a}){if(!e)return{error:_};if(!Array.isArray(i))return{error:Ht};if("string"!=typeof n)return{error:Nn,ratingType:n};if(!MU[n])return{error:Nn};const o=MU[n],{accessor:s}=o,c={},u=hl({matchUpFilters:{matchUpIds:i,matchUpStatuses:Ya},tournamentRecord:e,inContext:!0}).matchUps??[];u.sort(Il);for(const i of u){const{endDate:o,matchUpFormat:u,score:p,sides:l,winningSide:m}=i,f=i.matchUpType,h={eventType:f,scaleName:n,scaleType:Cr},g=`${n}.${Ar}`,I={scaleName:g,eventType:f,scaleType:Cr},U=Object.assign({},...(l??[]).map((t=>{const{sideNumber:e,participant:n}=t;return e&&{[e]:[n?.participantId,...n?.individualParticipantIds??[]].filter(Boolean).flat()}}))),S=a?g:n,y=Object.assign({},...Object.values(U).flat().map((t=>{const{scaleItem:n}=GU({scaleAttributes:I,tournamentRecord:e,participantId:t}),{scaleItem:r}=GU({tournamentRecord:e,scaleAttributes:h,participantId:t});return t&&{[t]:n??r??{scaleName:S,eventType:f,scaleDate:o,scaleType:Cr,scaleValue:s?{[s]:void 0}:void 0}}}))),v=u?Jd(u):{},w=v?.bestOf||1,T=r?w&(v?.setsTo||1):w,P=p?.sets&&(d=p.sets,d?.reduce(((t,e)=>(e.winningSide&&(t[e.winningSide-1]+=1),t)),[0,0])||[0,0])||1===m&&[1,0]||[0,1],D=m?U[m]:[],b=m?U[3-m]:[];for(const r of D){const i=y[r]?.scaleValue,a="object"==typeof i?i[s]:i;for(const o of b){const c=y[o]?.scaleValue,u="object"==typeof c?c[s]:c,d=m?P[m]:[0,0],p=m?P[3-m]:[0,0],{newWinnerRating:l,newLoserRating:f}=mb({winnerCountables:d,loserCountables:p,maxCountables:T,winnerRating:a,loserRating:u,ratingType:n}),h=s?{...i,[s]:l}:l,g=s?{...c,[s]:f}:f;y[r].scaleValue=h,y[o].scaleValue=g;let I=Dv({participantId:r,removePriorValues:t,tournamentRecord:e,scaleItem:{...y[r],scaleName:S}});if(I.error)return I;if(I=Dv({participantId:o,removePriorValues:t,tournamentRecord:e,scaleItem:{...y[o],scaleName:S}}),I.error)return I}}Object.assign(c,y)}var d;const p=u.map((({matchUpId:t})=>t));return{...E,modifiedScaleValues:c,processedMatchUpIds:p}}},hb={...pb,...fb};XD.importMethods(hb);const gb=XD,Ib={ratingsParameters:MU,matchUpFormats:fg,countryToFlag:tl,tieFormats:CS,countries:el,policies:{POLICY_AVOIDANCE_COUNTRY:{[Ri]:{roundsToSeparate:void 0,policyName:"Nationality Code",policyAttributes:[{key:"person.nationalityCode"},{key:"individualParticipants.person.nationalityCode"}]}},POLICY_POSITION_ACTIONS_DEFAULT:Yw,POLICY_POSITION_ACTIONS_DISABLED:{[vi]:{policyName:"positionActionsDisabled",enabledStructures:!1}},POLICY_POSITION_ACTIONS_NO_MOVEMENT:{[vi]:{policyName:"positionActionsNoMovement",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[jw,Vw,Gw],disabledActions:[]}]}},POLICY_POSITION_ACTIONS_UNRESTRICTED:{[vi]:{policyName:"positionActionsUnrestricted",enabledStructures:[],otherFlightEntries:!0,disableRoundRestrictions:!0,activePositionOverrides:[jw,Lw]}},POLICY_PRIVACY_DEFAULT:{[Di]:{policyName:"Participant Privacy Policy",participant:{contacts:!1,individualParticipants:{onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,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,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:op,POLICY_SCHEDULING_DEFAULT:lw,POLICY_SCORING_DEFAULT:{[Mi]:{defaultMatchUpFormat:lg,allowDeletionWithScoresPresent:{drawDefinitions:!1,structures:!1},requireAllPositionsAssigned:!1,processCodes:{incompleteAssignmentsOnDefault:["RANKING.IGNORE"]},stage:{[Xa]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}}}},POLICY_SCORING_USTA:{[Mi]:{requireAllPositionsAssigned:!1,stage:{[Xa]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},defaultMatchUpFormat:lg,matchUpFormats:[{description:"Best of 3 tiebreak sets",matchUpFormat:lg,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"}]}},POLICY_SEEDING_ITF:{[Ai]:{seedingProfile:{positioning:uo},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:XS},flagIOC:function(t){return tl(Object.assign({},...el.filter((t=>t.ioc)).map((t=>({[t.ioc]:t.iso}))))[t])}},Ub={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"},Sb={CLAY:"CLAY",HARD:"HARD",GRASS:"GRASS",CARPET:"CARPET",ARTIFICIAL:"ARTIFICIAL"},yb={INDOOR:"INDOOR",OUTDOOR:"OUTDOOR"},vb={activeMatchUpStatuses:Ka,auditConstants:Km,completedMatchUpStatuses:Ya,directingMatchUpStatuses:Ha,drawDefinitionConstants:Zo,entryStatusConstants:cu,errorConditionConstants:$n,eventConstants:od,extensionConstants:da,flightConstants:ny,genderConstants:zp,keyValueConstants:XP,matchUpActionConstants:UT,matchUpStatusConstants:Za,matchUpTypes:tc,nonDirectingMatchUpStatuses:za,participantConstants:lc,participantRoles:lm,particicipantsRequiredMatchUpStatuses:$a,participantTypes:pc,penaltyConstants:Ub,policyConstants:Oi,positionActionConstants:$w,ratingConstants:RU,recoveryTimeRequiredMatchUpStatuses:qa,requestConstants:By,resultConstants:C,scaleConstants:kr,scheduleConstants:Ud,sortingConstants:ay,surfaceConstants:Sb,tieFormatConstants:RS,timeItemConstants:Yu,topicConstants:Cs,tournamentConstants:dD,upcomingMatchUpStatuses:Ja,validMatchUpStatuses:Wa,venueConstants:yb};export{JD as askEngine,YD as asyncEngine,tb as competitionEngine,pr as deleteNotices,Zo as drawDefinitionConstants,cu as entryStatusConstants,$n as errorConditionConstants,od as eventConstants,vb as factoryConstants,Ib as fixtures,ny as flightConstants,CD as forge,zp as genderConstants,ur as getNotices,ED as governors,XP as keyValueConstants,UT as matchUpActionConstants,ab as matchUpEngine,lh as matchUpFormatCode,Za as matchUpStatusConstants,tc as matchUpTypes,sb as mocksEngine,lc as participantConstants,lm as participantRoles,pc as participantTypes,Ub as penaltyConstants,Oi as policyConstants,$w as positionActionConstants,C as resultConstants,kr as scaleConstants,gb as scaleEngine,uD as scoreGovernor,rr as setDeepCopy,er as setDevContext,tr as setGlobalLog,Xn as setStateProvider,ar as setSubscriptions,Sb as surfaceConstants,XD as syncEngine,Yu as timeItemConstants,eb as tournamentEngine,gD as utilities,yb as venueConstants,t as version};
1
+ function t(){return"3.0.0-alpha.0"}function e(t,e){return t-e}function n(t){return"number"==typeof t?parseInt(t.toString()):parseInt(t)}function r(t){return!isNaN(t)&&(t&&0==(t&t-1))}function i(t){if(!t.length)return;const n=[...t].sort(e),r=Math.floor(n.length/2);return n.length%2?n[r]:(n[r-1]+n[r])/2}function a(t){return isNaN(t)?0:t%2&&t+1||t}function o(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function s(t){return!isNaN(parseFloat(t))}function c(t){const e=n(t);if(!isNaN(e))return 0!==e&&1==(e&-e)}function u(t){if(isNaN(t))return!1;for(;!r(t);)t++;return t}function d(t,e){return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t}function p(t){return Number.isSafeInteger("string"==typeof t?+t:t)}function l(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=l(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 m(t){return t?.filter(((t,e,n)=>n.lastIndexOf(t)===e))}function f(t){return t.map((t=>[Math.random(),t])).sort(((t,e)=>t[0]-e[0])).map((t=>t[1]))}function h(t){return p(t)?t:1/0}function g(t){return t.reduce(((t,e)=>(t[e]||(t[e]=0),t[e]++,t)),{})}function I(t){return Object.keys(t).reduce(((e,n)=>{const r=t[n];return e[r]?e[r].push(n):e[r]=[n],e}),{})}function U(t,e,n){return n.indexOf(t)===e}function S(t){return t.filter(U)}function y(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function v(t){return t[Math.floor(Math.random()*t.length)]}function w(t,e){return Array.from({length:e-t},((e,n)=>n+t))}function T(t,e){return e.reduce(((e,n,r)=>(n===t&&e.push(r),e)),[])}function P(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 D(t,e){return Array.isArray(t)&&Array.isArray(e)?t.filter((t=>!e.includes(t))):[]}function b(t,e){return!(!Array.isArray(t)||!Array.isArray(e))&&t.some((t=>e.includes(t)))}function N(t,e){return t.reduce(((t,n,r)=>{const i=Math.floor(r/e);return t[i]=[].concat(t[i]||[],n),t}),[])}function R(t){return t.reduce(((t,e)=>!isNaN(parseInt(e))&&t),!0)}function M(t){return t.reduce(((t,e)=>isNaN(parseInt(e))&&t),!0)}function A(t,e,n){return 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}),[])}const E={success:!0},C={SUCCESS:E,ERROR:"error"},O={message:"Chronological error; time violation.",code:"ANACHRONISM"},F={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},k={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},x={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},_={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},L={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},B={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},V={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},j={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},G={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},q={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},$={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},W={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},H={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},z={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},Y={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},K={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},J={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Z={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},X={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},Q={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},tt={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},et={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},nt={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},rt={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},it={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},at={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},ot={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},st={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},ct={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},ut={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},dt={message:"Invalid action",code:"ERR_INVALID_ACTION"},pt={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},lt={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},mt={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},ft={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},ht={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},gt={message:"Existing round",code:"ERR_EXISTING_ROUND"},It={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},Ut={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},St={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},yt={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},vt={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},wt={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"},Tt={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},Pt={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},Dt={message:"Event exists",code:"ERR_EXISTING_EVENT"},bt={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},Nt={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Rt={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},Mt={message:"Missing stage",code:"ERR_MISSING_STAGE"},At={message:"Invalid stage",code:"ERR_INVALID_STAGE"},Et={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},Ct={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},Ot={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},Ft={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},kt={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},xt={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},_t={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},Lt={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Bt={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Vt={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},jt={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},Gt={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},qt={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},$t={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},Wt={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},Ht={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},zt={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},Yt={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},Kt={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Jt={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},Zt={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},Xt={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},Qt={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},te={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},ee={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},ne={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},re={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},ie={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},ae={message:"Missing value",code:"ERR_MISSING_VALUE"},oe={message:"Missing date",code:"ERR_MISSING_DATE"},se={message:"No valid dates",code:"ERR_NO_VALID_DATES"},ce={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},ue={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},de={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},pe={message:"Invalid Date",code:"ERR_INVALID_DATE"},le={message:"Invalid time",code:"ERR_INVALID_TIME"},me={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"},fe={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},he={message:"Invalid score",code:"ERR_INVALID_SCORE"},ge={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"},Ie={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},Ue={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},Se={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},ye={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},ve={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},we={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},Te={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},Pe={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},De={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},be={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},Ne={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Re={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},Me={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},Ae={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},Ee={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},Ce={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},Oe={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},Fe={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},ke={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},xe={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},_e={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Le={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},Be={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},Ve={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},je={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},Ge={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},qe={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},$e={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},We={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},He={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},ze={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},Ye={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},Ke={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},Je={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},Ze={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},Xe={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},Qe={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},tn={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},en={message:"Court exists",code:"ERR_EXISTING_COURT"},nn={message:"Venue exists",code:"ERR_EXISTING_VENUE"},rn={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},an={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},on={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},sn={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},cn={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},un={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},dn={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},pn={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},ln={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},mn={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},fn={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},hn={message:"Missing context",code:"ERR_MISSING_CONTEXT"},gn={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},In={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},Un={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},Sn={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},yn={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},vn={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},wn={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},Tn={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},Pn={message:"Invalid object",code:"ERR_INVALID_OBJECT"},Dn={message:"Invalid gender",code:"ERR_INVALID_GENDER"},bn={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},Nn={message:"Invalid values",code:"ERR_INVALID_VALUES"},Rn={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},Mn={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},An={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},En={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},Cn={message:"Value unchanged",code:"ABORT_UNCHANGED"},On={message:"Not found",code:"ERR_NOT_FOUND"},Fn={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},kn={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},xn={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},_n={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},Ln={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},Bn={message:"Existing stage",code:"ERR_EXISTING_STAGE"},Vn={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},jn={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},Gn={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},qn={message:"Scores present",code:"ERR_SCORES_PRESENT"},$n={ANACHRONISM:O,CANNOT_CHANGE_WINNING_SIDE:ve,CANNOT_MODIFY_TIEFORMAT:Ue,CANNOT_MODIFY_PARTICIPANT_TYPE:Se,CANNOT_REMOVE_MAIN_STRUCTURE:F,CANNOT_REMOVE_PARTICIPANTS:ye,COURT_EXISTS:en,COURT_NOT_FOUND:tn,DRAW_DEFINITION_NOT_FOUND:q,DRAW_ID_EXISTS:ot,DRAW_POSITION_ACTIVE:X,DRAW_POSITION_ASSIGNED:z,DRAW_POSITION_NOT_CLEARED:K,DRAW_POSITION_NOT_FOUND:{message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},DRAW_SIZE_MISMATCH:rt,DUPLICATE_VALUE:Rn,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:He,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:We,EVENT_EXISTS:Dt,EVENT_NOT_FOUND:Pt,EXISTING_DRAW_DEFINITIONS:G,EXISTING_END_TIME:sn,EXISTING_FLIGHT:kn,EXISTING_MATCHUP_ID:Ln,EXISTING_OUTCOME:_n,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Le,EXISTING_PARTICIPANT:Be,EXISTING_POLICY_TYPE:te,EXISTING_PROFILE:xn,EXISTING_ROUND:gt,EXISTING_STAGE:Bn,EXISTING_STRUCTURE:Vn,INCOMPATIBLE_MATCHUP_STATUS:xt,INCOMPLETE_SOURCE_STRUCTURE:W,INSUFFICIENT_DRAW_POSITIONS:Ke,INVALID_ACTION:dt,INVALID_ASSIGNMENT:pt,INVALID_BOOKINGS:ce,INVALID_CATEGORY:bn,INVALID_COLLECTION_DEFINITION:Tn,INVALID_CONFIGURATION:wn,INVALID_DATE_AVAILABILITY:ue,INVALID_DATE:pe,INVALID_DRAW_DEFINITION:V,INVALID_DRAW_POSITION_FOR_SEEDING:H,INVALID_DRAW_POSITION:Q,INVALID_DRAW_SIZE:nt,INVALID_END_TIME:on,INVALID_ENTRIES:Nt,INVALID_EVENT_TYPE:wt,INVALID_GAME_SCORES:fe,INVALID_GENDER:Dn,INVALID_MATCHUP_FORMAT:Bt,INVALID_MATCHUP_STATUS:_t,INVALID_MATCHUP_STATUS_BYE:Ot,INVALID_MATCHUP:Yt,INVALID_OBJECT:Pn,INVALID_PARTICIPANT_ID:Te,INVALID_PARTICIPANT_IDS:Pe,INVALID_PARTICIPANT_ROLE:De,INVALID_PARTICIPANT_SEEDING:st,INVALID_PARTICIPANT_TYPE:be,INVALID_PARTICIPANT:we,INVALID_POLICY_DEFINITION:Qt,INVALID_RECORDS:k,INVALID_SCALE_ITEM:In,INVALID_SEED_NUMBER:mt,INVALID_SEED_POSITION:ft,INVALID_SET_NUMBER:{message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},INVALID_SIDE_NUMBER:ne,INVALID_SCORE:he,INVALID_STAGE:At,INVALID_START_TIME:un,INVALID_STRUCTURE:$,INVALID_STOP_TIME:cn,INVALID_TIE_FORMAT:Lt,INVALID_TIME:le,INVALID_TIME_ITEM:pn,INVALID_TOURNAMENT_DATES:me,INVALID_TOURNAMENT_RECORD:L,INVALID_VALUES:Nn,INVALID_WINNING_SIDE:ge,MATCHUP_NOT_FOUND:Wt,METHOD_NOT_FOUND:jn,MISSING_ASSIGNMENTS:Rt,MISSING_ASYNC_STATE_PROVIDER:ln,MISSING_AVOIDANCE_POLICY:Zt,MISSING_COLLECTION_DEFINITION:jt,MISSING_COURT_ID:ie,MISSING_COURTS_INFO:Qe,MISSING_DATE_AVAILABILITY:de,MISSING_DATE:oe,MISSING_DRAW_DEFINITION:j,MISSING_DRAW_ID:at,MISSING_DRAW_POSITION:tt,MISSING_DRAW_POSITIONS:Z,MISSING_DRAW_SIZE:it,MISSING_ENTRIES:bt,MISSING_EVENT:Tt,MISSING_MATCHUP_FORMAT:Vt,MISSING_MATCHUP_ID:qt,MISSING_MATCHUP_IDS:$t,MISSING_MATCHUP:zt,MISSING_MATCHUPS:Ht,MISSING_PARTICIPANT_COUNT:ke,MISSING_PARTICIPANT_ID:Ae,MISSING_PARTICIPANT_IDS:Fe,MISSING_PARTICIPANT_ROLE:Ne,MISSING_PARTICIPANT:Re,MISSING_PARTICIPANTS:Me,MISSING_PENALTY_ID:Ze,MISSING_PENALTY_TYPE:Je,MISSING_PERSON_DETAILS:_e,MISSING_POLICY_ATTRIBUTES:Xt,MISSING_POLICY_DEFINITION:Jt,MISSING_POLICY_TYPE:Kt,MISSING_POSITION_ASSIGNMENTS:Ct,MISSING_ROUND_NUMBER:{message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},MISSING_SCHEDULE:gn,MISSING_SCORING_POLICY:{message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},MISSING_SEED_ASSIGNMENTS:lt,MISSING_SEEDCOUNT_THRESHOLDS:ut,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:re,MISSING_SIDE_NUMBER:{message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},MISSING_STAGE:Mt,MISSING_STRUCTURE_ID:It,MISSING_STRUCTURE:yt,MISSING_STRUCTURES:St,MISSING_TARGET_LINK:ht,MISSING_TIE_FORMAT:Gt,MISSING_TIME_ITEM:mn,MISSING_TIME_ITEMS:fn,MISSING_TOURNAMENT_ID:B,MISSING_TOURNAMENT_RECORD:_,MISSING_TOURNAMENT_RECORDS:x,MISSING_VALUE:ae,MISSING_VENUE_ID:an,MODIFICATIONS_FAILED:Un,NO_CANDIDATES:vn,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:Ye,NO_MODIFICATIONS_APPLIED:Sn,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:ze,NO_PARTICIPANT_REMOVED:Oe,NO_VALID_ACTIONS:An,NO_VALID_ATTRIBUTES:En,NO_VALID_DATES:se,NOT_FOUND:On,NOT_IMPLEMENTED:Fn,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:Ve,PARTICIPANT_ID_EXISTS:Ce,PARTICIPANT_NOT_CHECKED_IN:xe,PARTICIPANT_NOT_FOUND:Ee,PARTICIPANT_PAIR_EXISTS:{message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},PENALTY_NOT_FOUND:Xe,POLICY_NOT_ATTACHED:{message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},POLICY_NOT_FOUND:ee,SCHEDULE_NOT_CLEARED:Y,SCHEDULED_MATCHUPS:Gn,SCORES_PRESENT:qn,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:ct,STAGE_SEQUENCE_LIMIT:Et,STRUCTURE_NOT_FOUND:Ut,TEAM_NOT_FOUND:Mn,UNABLE_TO_ASSIGN_COURT:yn,UNLINKED_STRUCTURES:vt,UNRECOGNIZED_DRAW_TYPE:J,UNRECOGNIZED_MATCHUP_FORMAT:kt,UNRECOGNIZED_MATCHUP_STATUS:Ft,VALUE_UNCHANGED:Cn,VENUE_EXISTS:nn},Wn={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]};var Hn={addNotice:function({topic:t,payload:e,key:n}){if("string"!=typeof t||"object"!=typeof e)return;Wn.disableNotifications||(Wn.modified=!0);if(Wn.disableNotifications||!Wn.subscriptions[t])return;n&&(Wn.notices=Wn.notices.filter((e=>!(e.topic===t&&e.key===n))));return Wn.notices.push({topic:t,payload:e,key:n}),{...E}},callListener:function({topic:t,notices:e}){const n=Wn.subscriptions[t];n&&"function"==typeof n&&n(e)},cycleMutationStatus:function(){const t=Wn.modified;return Wn.modified=!1,t},deleteNotice:function({topic:t,key:e}){Wn.notices=Wn.notices.filter((n=>(!t||n.topic===t)&&n.key!==e))},deleteNotices:function(){Wn.notices=[]},disableNotifications:function(){Wn.disableNotifications=!0},enableNotifications:function(){Wn.disableNotifications=!1},getMethods:Yn,getNotices:function({topic:t}){const e=Wn.notices.filter((e=>e.topic===t)).map((t=>t.payload));return e.length&&e},getTopics:function(){return{topics:Object.keys(Wn.subscriptions)}},getTournamentId:zn,getTournamentRecord:function(t){return Wn.tournamentRecords[t]},getTournamentRecords:function(){return Wn.tournamentRecords},removeTournamentRecord:function(t){if("string"!=typeof t)return{error:Nn};if(!Wn.tournamentRecords[t])return{error:On};delete Wn.tournamentRecords[t];const e=Object.keys(Wn.tournamentRecords);1===e.length?Wn.tournamentId=e[0]:e.length||(Wn.tournamentId=void 0);return{success:!0}},setMethods:function(t){return Object.keys(t).forEach((e=>{"function"==typeof t[e]&&(Wn.methods[e]=t[e])})),{...E}},setSubscriptions:function(t){return"object"!=typeof t.subscriptions?{error:Nn}:(Object.keys(t.subscriptions).forEach((e=>{Wn.subscriptions[e]=t.subscriptions[e]})),{...E})},setTournamentId:function(t){if(!t)return Wn.tournamentId=void 0,{success:!0};return Wn.tournamentRecords[t]?(Wn.tournamentId=t,{success:!0}):{error:_}},setTournamentRecord:function(t){const e=t?.tournamentId;return e?(Wn.tournamentRecords[e]=t,{success:!0}):{error:L}},setTournamentRecords:function(t){Wn.tournamentRecords=t;const e=Object.keys(t);1===e.length?Wn.tournamentId=e[0]:e.length||(Wn.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:zn(),params:JSON.stringify(n),engine:t,methodName:e,error:i}),{error:i}}};function zn(){return Wn.tournamentId}function Yn(){return Wn.methods??{}}const Kn={tournamentFactoryVersion:"0.0.0",timers:{default:{elapsedTime:0}},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},deepCopy:!0};let Jn=Hn;const Zn=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function Xn(t){if("object"!=typeof t)throw new Error("Global state provider can not be undefined or null");if(P(Object.keys(t),Zn).length!==Zn.length)throw new Error("Global state provider is missing required methods");return Jn=t,{success:!0}}function Qn(t){return t&&"object"==typeof t?"object"==typeof Kn.devContext&&(Object.keys(t).every((e=>Kn.devContext?.[e]===t[e]))&&Kn.devContext):Kn.devContext??!1}function tr(t){"function"==typeof t?Kn.globalLog=t:delete Kn.globalLog}function er(t){Kn.devContext=t}function nr(){Jn.enableNotifications()}function rr(t,e){"boolean"==typeof t&&(Kn.deepCopy=t),"object"==typeof e&&(Array.isArray(e.ignore)&&(Kn.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(Kn.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(Kn.deepCopyAttributes.stringify=e.stringify),e.threshold&&(Kn.deepCopyAttributes.threshold=e.threshold))}function ir(){return{enabled:Kn.deepCopy,...Kn.deepCopyAttributes}}function ar(t){return t?.subscriptions?Jn.setSubscriptions({subscriptions:t.subscriptions}):{error:ae,info:"missing subscriptions"}}function or(){return Jn.cycleMutationStatus()}function sr(t){return Jn.addNotice(t)}function cr(){return Jn.getMethods()}function ur(t){return Jn.getNotices(t)}function dr({key:t,topic:e}){return Jn.deleteNotice({key:t,topic:e})}function pr(){return Jn.deleteNotices()}function lr(){return Jn.getTopics()}async function mr(t){return Jn.callListener(t)}function fr(){return Jn.getTournamentId()}function hr(t){return Jn.getTournamentRecord(t)}function gr(){return Jn.getTournamentRecords()}function Ir(t){return Jn.setTournamentRecords(t)}function Ur(t){return Jn.setTournamentId(t)}function Sr(){return Jn}function yr({engineName:t,methodName:e,params:n,err:r}){return("function"==typeof Jn.handleCaughtError&&Jn.handleCaughtError||Hn.handleCaughtError)({engineName:t,methodName:e,params:n,err:r})}function vr(t,e,n,r){if("object"!=typeof t||null===t)return t;const i=ir();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=>vr(t)))}:{[e]:r?t[e]:vr(t[e])})))}function wr({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,vr(t)),!e||e?.error||e?.success||Object.assign(e,{...E}),e??{success:!0}}const Tr="element required",Pr="missing name";function Dr(t){if(!t||"object"!=typeof t)return{error:ae};if(t.element&&"object"!=typeof t?.element)return{error:Nn};if(!t?.name)return{error:ae,info:Pr};if(!t?.element){if(t.discover&&t.tournamentRecords){for(const e of Object.keys(t.tournamentRecords)){const n=Dr({element:t.tournamentRecords[e],name:t.name});if(n.error)return wr({result:n,stack:"removeExtension"})}return{...E}}return{error:ae,info:Tr}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter((e=>e?.name!==t.name)),{...E}):{...E,info:On}}function br({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 Nr(t){if("object"!=typeof t)return{error:ae};const e="addExtension";if(t?.element&&"object"!=typeof t.element)return wr({result:{error:Nn},stack:e});if(!br({extension:t.extension}))return wr({result:{error:Nn,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=Nr({extension:t.extension,element:n});if(r.error)return wr({result:r,stack:e})}return{...E}}return wr({result:{error:ae},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),{...E}}const Rr="extensionQueries";function Mr({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:On}}return wr({result:{error:ae},stack:Rr})}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:On}}const Ar="DYNAMIC",Er="RANKING",Cr="RATING",Or="SCALE",Fr="SEEDING",kr={RANKING:Er,RATING:Cr,SCALE:Or,SEEDING:Fr};function xr({participant:t}){const e=t.timeItems?.filter((({itemType:t})=>t?.startsWith(Or)&&[Er,Cr,Fr].includes(t.split(".")[1]))),n={ratings:{},rankings:{},seedings:{}};if(e?.length){const t=t=>e.filter((e=>e?.itemType===t)).sort(((t,e)=>new Date(t.createdAt||void 0).getTime()-new Date(e.createdAt||void 0).getTime())).pop(),r=m(e.map((({itemType:t})=>t)));for(const e of r){const r=t(e);if(r){const[,t,e,i,a]=r.itemType.split("."),o=a?`${i}.${a}`:i,s=(t===Fr?"seedings":t===Er&&"rankings")||"ratings";n[s][e]||(n[s][e]=[]),n[s][e].push({scaleValue:r.itemValue,scaleDate:r.itemDate,scaleName:o})}}}return{...E,...n}}function _r(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 Lr=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,Br=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Vr=/^([\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?$/,jr=/^([\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 Gr(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=ri(t.scheduledTime)),!e)return;const n=ni(t.scheduledTime);let r=ri(e);return r&&n&&(r+=`T${n}`),r}function qr(t){if("object"!=typeof t||Array.isArray(t))return!1;return"[object Date]"===Object.prototype.toString.call(t)}function $r(t){const e="string"==typeof t?t?.split(" "):[];return!(t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase()))&&!(t&&!jr.test(oi(t,!0,!0)))}function Wr(t){return Xr(t)||Lr.test(t)}const Hr=t=>{const e=Kr(t)||Xr(t)?new Date(t):new Date,n=e.getUTCMonth()+1,r=n<10?`0${n}`:`${n}`;return`${e.getUTCFullYear()}-${mi(r)}-${mi(e.getUTCDate())}`};function zr(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 Yr(t){const e=t?new Date(t):new Date,n=e.getTimezoneOffset();return new Date(e.getTime()-60*n*1e3)}function Kr(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 Jr(t,e){if(!Wr(t)||!Wr(e))return[];const n=ri(t)+"T00:00",r=ri(e)+"T00:00",i=new Date(n),a=new Date(r);const o=[];let s=0;if(Kr(a)&&Kr(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=>zr(t)))}const Zr=/^([+-]?\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 Xr(t){return"string"==typeof t&&Zr.test(t)}function Qr(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 ti(t){const e=ni(t);if(!e)return 0;const[n,r]=e.split(":").map((t=>parseInt(t)));return 60*n+r}function ei(t){return Qr(t)?t.split(":").slice(0,2).map(mi).join(":"):void 0}function ni(t){return Xr(t)&&t.indexOf("T")>0?ei(t.split("T").reverse()[0]):ei(t)}function ri(t){return Xr(t)||Vr.test(t)?t.split("T")[0]:void 0}function ii(t,e){const n=new Date(t);return n.setDate(n.getDate()+e),ri(n.toISOString())}function ai(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 oi(t,e,n){const r=ri(t),i=ni(t),a=r?i:t;return t?e&&(r&&n&&t||function(t){const e=ai(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(mi).join(":")}(a))||function(t){const e=ai(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 si(t,e){const n=ai(t),r=ai(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 ci(t,e=7){const n=ri(t)+"T00:00",r=new Date(n);return zr(new Date(r.setDate(r.getDate()+e)))}function ui(t,e=void 0){const[n,r]=(t||"00:00").split(":").map(mi),i=Yr(e).setHours(n,r,0,0);return Yr(i)}function di(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 pi(t,e){const n=ni(t);if(!n)return"00:00";const r=isNaN(e)?0:e;return ni(li(ui(n),r).toISOString())}function li(t,e){const n=new Date(t);return new Date(n.getTime()+6e4*e)}function mi(t){return t.toString()[1]?t:"0"+t}function fi(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 hi={addDays:ci,addWeek:function(t){return ci(t)},addMinutesToTimeString:pi,convertTime:oi,getIsoDateString:Gr,getUTCdateString:Hr,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(mi).join(":")}(e.getSeconds()+60*e.getMinutes()+3600*e.getHours(),{displaySeconds:!1})},extractDate:ri,extractTime:ni,formatDate:zr,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())),zr(i,n)},isISODateString:Xr,isDate:Kr,isTimeString:Qr,offsetDate:Yr,offsetTime:function(t){return Yr(t).getTime()},sameDay:fi,timeStringMinutes:ti,timeToDate:ui,timeUTC:function(t){const e=Kr(t)||Xr(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())},validTimeValue:$r,validDateString:Lr,timeValidation:jr,dateValidation:Vr};function gi(t,e,n,r,i=0){if(Sr().makeDeepCopy)return Sr().makeDeepCopy(t,e,n,r);const a=ir(),{stringify:o,toJSON:s,ignore:c,modulate:u}=a||{};if(!a?.enabled&&!n||"object"!=typeof t||"function"==typeof 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)||"function"==typeof c&&!c(t))),l=(t,e)=>{d[t]="function"==typeof e?.toString?e.toString():JSON.stringify(e)};for(const a of p){const c=t[a],p="function"==typeof u?u(c):void 0;if(void 0!==p)d[a]=p;else if(e&&"extensions"===a&&Array.isArray(c)){const t=Ii(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)&&"function"==typeof c?.toJSON?d[a]=c.toJSON():null===c?d[a]=void 0:qr(c)?d[a]=new Date(c).toISOString():d[a]=gi(c,e,n,r,i+1)}return d}function Ii(t){return t?.map((t=>{const{name:e,value:n}=t;return e&&n&&{[`_${e}`]:n}})).filter(Boolean)}const Ui="voluntaryConsolation",Si="competitiveBands",yi="roundRobinTally",vi="positionActions",wi="matchUpActions",Ti="rankingPoints",Pi="roundNaming",Di="participant",bi="progression",Ni="scheduling",Ri="avoidance",Mi="scoring",Ai="seeding",Ei="feedIn",Ci="draws",Oi={POLICY_TYPE_VOLUNTARY_CONSOLATION:Ui,POLICY_TYPE_COMPETITIVE_BANDS:Si,POLICY_TYPE_ROUND_ROBIN_TALLY:yi,POLICY_TYPE_POSITION_ACTIONS:vi,POLICY_TYPE_MATCHUP_ACTIONS:wi,POLICY_TYPE_RANKING_POINTS:Ti,POLICY_TYPE_ROUND_NAMING:Pi,POLICY_TYPE_PARTICIPANT:Di,POLICY_TYPE_PROGRESSION:bi,POLICY_TYPE_SCHEDULING:Ni,POLICY_TYPE_AVOIDANCE:Ri,POLICY_TYPE_DISPLAY:"display",POLICY_TYPE_FEED_IN:Ei,POLICY_TYPE_SCORING:Mi,POLICY_TYPE_SEEDING:Ai,POLICY_TYPE_AUDIT:"audit",POLICY_TYPE_DRAWS:Ci};function Fi({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:n,participantId:r,internalUse:i,personId:a}){const o=gi(t.find((t=>r&&t.participantId===r||a&&t.person&&t.person.personId===a)),!1,i);if(o){const t=e?.[Di];if(n?.withScaleValues){const{ratings:t,rankings:e}=xr({participant:o});o.rankings=e,o.ratings=t}if(t?.participant)return _r({template:t.participant,source:o})}return o}function ki(t){return t&&"object"==typeof t?t.tournamentRecord?Nr({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:_}:{error:ae}}function xi(t){return t&&"object"==typeof t?t.drawDefinition?Nr({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:q}:{error:ae}}function _i(t){return t&&"object"==typeof t?t.event?Nr({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:Pt}:{error:ae}}function Li(t){return t&&"object"==typeof t?t.tournamentRecord?Dr({element:t.tournamentRecord,name:t.name}):{error:_}:{error:ae}}function Bi(t){return t&&"object"==typeof t?t?.event?Dr({element:t.event,name:t.name}):{error:Pt}:{error:ae}}const Vi="appliedPolicies",ji="positionActions",Gi="context",qi="delegatedOutcome",$i="disabled",Wi="disableLinks",Hi="disableAutoCalc",zi="drawDeletions",Yi="entryProfile",Ki="flightProfile",Ji="groupingAttribute",Zi="lineUps",Xi="linkedTournamentsIds",Qi="matchUpHistory",ta="participantRepresentatives",ea="personRequests",na="rankingPoints",ra="roundTarget",ia="scheduleLimits",aa="scheduleTiming",oa="schedulingProfile",sa="subOrder",ca="tally",ua="tieFormatModification",da={ACTIVE_SUSPENSION:"activeSuspension",APPLIED_POLICIES:Vi,AUDIT_POSITION_ACTIONS:ji,CONTEXT:Gi,DELEGATED_OUTCOME:qi,DISABLED:$i,DISABLE_LINKS:Wi,DISABLE_AUTO_CALC:Hi,DRAW_DELETIONS:zi,DRAW_PROFILE:"drawProfile",ENTRY_PROFILE:Yi,EVENT_PROFILE:"eventProfile",EVENT_WITHDRAWAL_REQUESTS:"eventWithdrawalRequests",FLIGHT_PROFILE:Ki,GROUPING_ATTRIBUTE:Ji,LINEUPS:Zi,LINKED_TOURNAMENTS:Xi,MATCHUP_HISTORY:Qi,PARTICIPANT_REPRESENTATIVES:ta,PERSON_REQUESTS:ea,RANKING_POINTS:na,ROUND_TARGET:ra,SCHEDULE_LIMITS:ia,SCHEDULE_TIMING:aa,SCHEDULING_PROFILE:oa,STATUS_DETAIL:"statusDetail",SUB_ORDER:sa,TALLY:ca,TIE_FORMAT_MODIFICATIONS:ua,FACTORY:"factory"},pa=[qi,$i,Wi,Ki,Zi,Qi,ta,ea,ra,ia,aa,oa,sa,ca];function la({element:t,accessor:e}){if("string"!=typeof e)return{values:[]};const n=gi(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}function ma(t){return"function"==typeof t}function fa(t){return"string"==typeof t}function ha(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function ga(t,e){if(!ha(t)||!ha(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 Ia(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(ha).map((t=>t[e]&&{[t[e]]:t})).filter(Boolean)):{}}const Ua=t=>e=>t&&"object"==typeof e?Array.isArray(t)&&t.map((t=>({[t]:la({element:e,accessor:t})?.value})))||"object"==typeof t&&Object.keys(t).map((t=>({[t]:la({element:e,accessor:t})?.value})))||("string"==typeof t&&la({element:e,accessor:t}))?.value:void 0;function Sa(t){return Array.isArray(t)?t.length+t.map(Sa).reduce(((t,e)=>t+e),0):"object"==typeof t&&null!==t?Object.keys(t).length+Object.keys(t).map((e=>Sa(t[e]))).reduce(((t,e)=>t+e),0):0}function ya({tournamentRecords:t}){return{tournamentIds:ha(t)?Object.keys(t):[],...E}}const va={linkTournaments:function({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:x};const e=ya({tournamentRecords:t}),{tournamentIds:n}=e;if(n?.length>1){return Nr({tournamentRecords:t,discover:!0,extension:{name:Xi,value:{tournamentIds:n}}})}return{...E}},unlinkTournament:function({tournamentRecords:t,tournamentId:e}){if("object"!=typeof t)return{error:Nn};if(!e)return{error:B};const n=ya({tournamentRecords:t}),{tournamentIds:r}=n;if(!r.includes(e))return{error:B};let i;return r.every((n=>{const r=t[n],{extension:a}=Mr({element:r,name:Xi});if(!a)return!0;const o=a?.value?.tournamentIds||[];if(!o?.length||1===o.length&&o.includes(e)||n===e){const t=Li({name:Xi,tournamentRecord:r});return t.error&&(i=t.error),t.success}const s=o.filter((t=>t!==e));a.value={tournamentIds:s};const c=ki({tournamentRecord:r,extension:a});return c.error&&(i=c.error),c.success})),i?{error:i}:{...E}},unlinkTournaments:function({tournamentRecords:t}){return"object"==typeof t&&Object.keys(t).length?wr({result:Dr({name:Xi,tournamentRecords:t,discover:!0}),stack:"unlinkTournaments"}):{error:x}}},wa=t=>e=>t[e],Ta=(t=[])=>t.map(ba).filter(Boolean),Pa=(t=[])=>t.map(Da).filter(Boolean),Da=(t={})=>wa(t)("participantId"),ba=(t={})=>wa(t)("matchUpId");const Na="ABANDONED",Ra="AWAITING_RESULT",Ma="BYE",Aa="CANCELLED",Ea="COMPLETED",Ca="DEAD_RUBBER",Oa="DEFAULTED",Fa="DOUBLE_DEFAULT",ka="DOUBLE_WALKOVER",xa="IN_PROGRESS",_a="INCOMPLETE",La="NOT_PLAYED",Ba="RETIRED",Va="SUSPENDED",ja="TO_BE_PLAYED",Ga="WALKOVER",qa=[Ra,Ea,Oa,xa,_a,Ba,Va],$a=[Ra,Ea,Oa,ka,Fa,xa,_a,Ba,Va,Ga],Wa=[Na,Ra,Ma,Aa,Ea,Ca,Oa,ka,Fa,xa,_a,La,Ba,Va,ja,Ga],Ha=[Ma,ka,Fa,Ea,Oa,Ba,Ga],za=[Na,Ra,Aa,Ca,xa,_a,La,Va,ja,void 0],Ya=[Aa,Na,Ea,Ca,Oa,ka,Fa,Ba,Ga],Ka=[Na,Ea,Oa,ka,Fa,xa,Ba,Ga],Ja=[xa,_a,Va,ja],Za={ABANDONED:Na,AWAITING_RESULT:Ra,BYE:Ma,CANCELLED:Aa,COMPLETED:Ea,DEAD_RUBBER:Ca,DEFAULTED:Oa,DOUBLE_WALKOVER:ka,DOUBLE_DEFAULT:Fa,IN_PROGRESS:xa,INCOMPLETE:_a,NOT_PLAYED:La,RETIRED:Ba,SUSPENDED:Va,TO_BE_PLAYED:ja,WALKOVER:Ga},Xa="MAIN",Qa="QUALIFYING",to="CONSOLATION",eo="VOLUNTARY_CONSOLATION",no="PLAY_OFF",ro=[Xa,Qa,to,no,eo],io={[Qa]:1,[Xa]:2,[no]:3,[to]:3,[eo]:4},ao="finishingPositions",oo="aggregateEventStructures",so={[Xa]:1,[no]:2,[to]:3,[Qa]:4,[eo]:5},co={[no]:1,[Xa]:2,[to]:3,[Qa]:4,[eo]:5},uo="CLUSTER",po="WATERFALL",lo="ITEM",mo="CONTAINER",fo="DRAW",ho="RANDOM",go="TOP_DOWN",Io="BOTTOM_UP",Uo="POSITION",So="WINNER",yo="LOSER",vo="FIRST_MATCHUP",wo="AD_HOC",To="FEED_IN",Po="COMPASS",Do="OLYMPIC",bo="SINGLE_ELIMINATION",No="DOUBLE_ELIMINATION",Ro="FIRST_MATCH_LOSER_CONSOLATION",Mo="FIRST_ROUND_LOSER_CONSOLATION",Ao="LUCKY_DRAW",Eo="CURTIS_CONSOLATION",Co="CURTIS_CONSOLATION",Oo="FEED_IN_CHAMPIONSHIP_TO_SF",Fo="FEED_IN_CHAMPIONSHIP_TO_SF",ko="FEED_IN_CHAMPIONSHIP_TO_QF",xo="FEED_IN_CHAMPIONSHIP_TO_QF",_o="FEED_IN_CHAMPIONSHIP_TO_R16",Lo="FEED_IN_CHAMPIONSHIP_TO_R16",Bo="MODIFIED_FEED_IN_CHAMPIONSHIP",Vo="MODIFIED_FEED_IN_CHAMPIONSHIP",jo="FEED_IN_CHAMPIONSHIP",Go="ROUND_ROBIN",qo="ROUND_ROBIN_WITH_PLAYOFF",$o="DECIDER",Wo="BACKDRAW",Ho={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"}},zo={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},Yo="WIN_RATIO",Ko="ROUND_OUTCOME",Jo=[Po,Eo,xo,Lo,Fo,jo,ko,_o,Oo,Ro,Mo,Ao,Vo,Do,no,qo],Zo={MAIN:Xa,QUALIFYING:Qa,CONSOLATION:to,ITEM:lo,CONTAINER:mo,FIRST_MATCHUP:vo,WINNER:So,LOSER:yo,AD_HOC:wo,FEED_IN:To,FLEX_ROUNDS:"AD_HOC",COMPASS:Po,PLAY_OFF:no,OLYMPIC:Do,KNOCKOUT:"SINGLE_ELIMINATION",SINGLE_ELIMINATION:bo,DOUBLE_ELIMINATION:No,CURTIS:Eo,FICSF:Oo,FICQF:ko,FICR16:_o,MFIC:Bo,VOLUNTARY_CONSOLATION:eo,FIRST_MATCH_LOSER_CONSOLATION:Ro,FIRST_ROUND_LOSER_CONSOLATION:Mo,MODIFIED_FEED_IN_CHAMPIONSHIP:Vo,FEED_IN_CHAMPIONSHIP_TO_R16:Lo,FEED_IN_CHAMPIONSHIP_TO_QF:xo,FEED_IN_CHAMPIONSHIP_TO_SF:Fo,FEED_IN_CHAMPIONSHIP:jo,LUCKY_DRAW:Ao,ROUND_ROBIN_WITH_PLAYOFF:qo,ROUND_ROBIN:Go,DECIDER:$o,BACKDRAW:Wo,COMPASS_ATTRIBUTES:Ho,OLYMPIC_ATTRIBUTES:zo,DRAW:fo,RANDOM:ho,TOP_DOWN:go,BOTTOM_UP:Io,WATERFALL:po,WIN_RATIO:Yo,ROUND_OUTCOME:Ko,MULTI_STRUCTURE_DRAWS:Jo,generatedDrawTypes:[wo,Po,Eo,No,xo,Lo,Fo,jo,To,Ro,Mo,Ao,Vo,Do,no,Go,qo,bo],stageOrder:io,finishOrder:so,AGGREGATE_EVENT_STRUCTURES:oo,FINISHING_POSITIONS:ao};function Xo(t,e,n){const r=t=>Mr({element:t,name:ra})?.extension?.value,i=n?.deprioritizeCompleted,a=n?.mode===oo&&co,o=n?.mode===ao&&so,s=o||a||io,c=t=>(t=>t?.stage===Xa&&1===t?.stageSequence)(t)?-1:s[t?.stage],u=t=>t?.matchUps.every((({matchUpStatus:t})=>Ya.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)||(Qo(t)||0)-(Qo(e)||0)}function Qo(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 ts({drawDefinition:t,structureId:e}){if(!t)return{error:j};if(!e)return{error:It};const{structures:n}=es({drawDefinition:t}),r=n?.map((t=>t.structures?[...t.structures].concat(t):t)).flat(),i=r?.find((t=>t.structureId===e));if(!i)return{error:Ut};return{structure:i,containingStructure:i.structureType===lo?r?.find((t=>t.structures?.some((t=>t.structureId===e)))):void 0}}function es({withStageGrouping:t,drawDefinition:e,stageSequences:n,stageSequence:r,roundTarget:i,sortConfig:a,stages:o,stage:s}){const c=!e&&j||!e?.structures&&St||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=Mr({element:t,name:ra})?.extension?.value;return!i||i===e})).sort(((t,e)=>Xo(t,e,a)))??[],d=t?Object.assign({},...ro.map((t=>{const e=u?.filter((e=>e.stage===t));return e?.length&&{[t]:e}})).filter(Boolean)):{};return{structures:u,stageStructures:d}}function ns({drawDefinition:t}){if(!t)return{error:j};const e={};return{allPositionedParticipantIds:(t.structures||[]).map((t=>{const n=t.stage;e[n]||(e[n]=[]);const{positionAssignments:r}=rs({structure:t}),i=r?.map(Ua("participantId")).filter(Boolean)??[];return e[n].push(...i),i})).flat(),stagePositionedParticipantIds:e}}function rs({drawDefinition:t,structureId:e,structure:n}){let r,i=[];if(!n){if(!t)return{positionAssignments:i,error:j};if(({structure:n,error:r}=ts({drawDefinition:t,structureId:e})),r)return{positionAssignments:i,error:r}}return n.structures?i=[].concat(...n.structures.map((t=>rs({structure:t}).positionAssignments))):n.positionAssignments?i=n.positionAssignments:r=Ct,{positionAssignments:i,error:r}}function is({drawDefinition:t,structureId:e,structure:n}){const r=rs({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 as="addDrawDefinition",os="addMatchUps",ss="addParticipants",cs="addScaleItems",us="addVenue",ds="audit",ps="deleteParticipants",ls="deleteVenue",ms="deletedDrawIds",fs="deletedMatchUpIds",hs="modifyDrawDefinition",gs="modifyDrawEntries",Is="modifyEventEntries",Us="modifyMatchUp",Ss="modifyParticipants",ys="modifyPositionAssignments",vs="modifySeedAssignments",ws="modifyTournamentDetail",Ts="modifyVenue",Ps="mutations",Ds="publishEvent",bs="publishEventSeeding",Ns="publishOrderOfPlay",Rs="unPublishEvent",Ms="unPublishEventSeeding",As="unPublishOrderOfPlay",Es="updateInContextMatchUp",Cs={ADD_DRAW_DEFINITION:as,ADD_MATCHUPS:os,ADD_PARTICIPANTS:ss,ADD_SCALE_ITEMS:cs,ADD_VENUE:us,AUDIT:ds,DELETE_PARTICIPANTS:ps,DELETE_VENUE:ls,DELETED_DRAW_IDS:ms,DELETED_MATCHUP_IDS:fs,MODIFY_DRAW_DEFINITION:hs,MODIFY_DRAW_ENTRIES:gs,MODIFY_EVENT_ENTRIES:Is,MODIFY_MATCHUP:Us,MODIFY_PARTICIPANTS:Ss,MODIFY_POSITION_ASSIGNMENTS:ys,MODIFY_SEED_ASSIGNMENTS:vs,MODIFY_TOURNAMENT_DETAIL:ws,MODIFY_VENUE:Ts,MUTATIONS:Ps,PUBLISH_EVENT_SEEDING:bs,PUBLISH_EVENT:Ds,PUBLISH_ORDER_OF_PLAY:Ns,UNPUBLISH_EVENT_SEEDING:Ms,UNPUBLISH_EVENT:Rs,UNPUBLISH_ORDER_OF_PLAY:As,UPDATE_INCONTEXT_MATCHUP:Es};function Os(t,e){if(!t)return{error:j};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)})),{...E}}function Fs({drawDefinition:t,tournamentId:e,matchUps:n,eventId:r}){return t&&Os(t),sr({payload:{matchUps:n,tournamentId:e,eventId:r},topic:os}),{...E}}function ks({drawDefinition:t,tournamentId:e,matchUpIds:n,eventId:r,action:i}){t&&Os(t),sr({topic:fs,payload:{tournamentId:e,matchUpIds:n,eventId:r,action:i}});for(const t of n)dr({key:t});return{...E}}function xs({drawDefinition:t,tournamentId:e,structureId:n,context:r,eventId:i,matchUp:a}){if(!a)return console.log(zt),{error:zt};if(t){Ls({drawDefinition:t,structureIds:n?[n]:void 0,tournamentId:e,eventId:i})}return sr({topic:Us,payload:{matchUp:a,tournamentId:e,context:r},key:a.matchUpId}),{...E}}function _s({tournamentId:t,eventId:e,drawDefinition:n}){return n?(Os(n),sr({payload:{drawDefinition:n,tournamentId:t,eventId:e},topic:as,key:n.drawId}),{...E}):(console.log(j),{error:j})}function Ls({drawDefinition:t,tournamentId:e,structureIds:n,eventId:r}){return t?(Os(t,n),sr({payload:{tournamentId:e,eventId:r,drawDefinition:t},topic:hs,key:t.drawId}),{...E}):{error:j}}function Bs({drawDefinition:t,tournamentId:e,structure:n,eventId:r}){if(!t)return{error:j};if(!n)return{error:yt};const i=n.seedAssignments,a=n.structureId;return sr({payload:{tournamentId:e,eventId:r,drawId:t.drawId,structureId:a,seedAssignments:i},topic:vs,key:t.drawId}),Ls({structureIds:[a],drawDefinition:t,tournamentId:e,eventId:r}),{...E}}function Vs({drawDefinition:t,tournamentId:e,structure:n,event:r}){if(!t)return{error:j};if(!n)return{error:yt};const i=rs({structure:n}),a=n.structureId,o=t.drawId,s=r?.eventId;return sr({topic:ys,payload:{positionAssignments:i,tournamentId:e,structureId:a,eventId:s,drawId:o},key:a}),Ls({structureIds:[a],drawDefinition:t,tournamentId:e,eventId:s}),{...E}}function js({drawPositions:t,structure:e}){if([Qa,Xa].includes(e.stage)&&1===e.stageSequence)return;const{positionAssignments:n}=rs({structure:e}),r=n?.filter((({drawPosition:e})=>t?.includes(e)));r?.forEach((t=>{Nr({element:t,extension:{name:Wi,value:!0}})}))}function Gs({drawDefinition:t,positionAction:e}){const{extension:n}=Mr({name:ji,element:t}),r=Array.isArray(n?.value)?n?.value??[]:[];if(!r?.length){const e=t.structures.find((t=>t.stage===Xa));if(e){const t=rs({structure:e}).positionAssignments?.map((({drawPosition:t,participantId:e,bye:n,qualifier:r})=>({drawPosition:t,participantId:e,qualifier:r,bye:n})));r.push({name:"initialMainAssignments",initialAssignments:t})}}Nr({element:t,extension:{name:ji,value:r.concat(e)}})}function qs({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 $s(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 Ws({matchUpStatus:t}){return Ha.includes(t)}function Hs({matchUpStatus:t}){return za.includes(t)}function zs({matchUpStatus:t,winningSide:e,tieMatchUps:n,sides:r,score:i}){const a=r?.find((({participantId:t})=>t)),o=n?.filter(zs)?.length;return $s({score:i})||o||e&&a||t&&function({matchUpStatus:t}){return Ka.includes(t)}({matchUpStatus:t})&&![Oa,Ga,xa].includes(t)}const Ys="SINGLES",Ks="SINGLES",Js="DOUBLES",Zs="DOUBLES",Xs="TEAM",Qs="TEAM",tc={SINGLES_MATCHUP:Ys,SINGLES:Ks,DOUBLES_MATCHUP:Js,DOUBLES:Zs,TEAM_MATCHUP:Xs,TEAM:Qs};function ec(t){const{sides:e,matchUpType:n}=t||{},r=t.potentialParticipants?.length?t.potentialParticipants.flat().map((t=>n===Zs?t?.individualParticipantIds||[]:t.participantId)).flat():[],i=(e||[]).map((t=>n===Zs&&(t?.participant?.individualParticipantIds||[])||t?.participantId&&[t.participantId]||[])).flat();return{individualParticipantIds:i.concat(r).flat(),enteredIndividualParticipantIds:i,potentialIndividualParticipantIds:r}}function nc(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}const rc="SIGN_IN_STATUS",ic="SIGNED_OUT",ac="SIGNED_IN",oc="TEAM",sc="INDIVIDUAL",cc="GROUP",uc="PAIR",dc="TEAM",pc={TEAM_PARTICIPANT:oc,INDIVIDUAL:sc,GROUP:cc,TEAM:dc,PAIR:uc},lc={INDIVIDUAL:sc,GROUP:cc,PAIR:uc,TEAM:dc,SIGN_IN_STATUS:rc,SIGNED_OUT:ic,SIGNED_IN:ac};function mc({participantsProfile:t,participants:e=[],deepCopy:n}){const r=new Map,i=!1!==n?gi(e,t?.convertExtensions,!0):e,a=i.filter((t=>t.participantType===dc)),o=i.filter((t=>t.participantType===cc)),s=i.filter((t=>t.participantType===uc));return i.forEach((t=>{if(t.participantType===sc){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 fc({groupedOrder:t,roundPositionsCount:n}){if(!t||t?.length<=n)return t;const r=N(t,t.length/n).map((t=>t.reduce(((t,e)=>t+e)))),i=r.slice().sort(e);return r.map((t=>i.indexOf(t)+1))}function hc({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:n,drawDefinition:r,targetLink:i}){if(!i)return{error:ht};const{target:{structureId:a,feedProfile:o,groupedOrder:s,roundNumber:c,positionInterleave:u}}=i,{structure:d}=ts({drawDefinition:r,structureId:a}),{positionAssignments:p}=rs({structure:d}),l=e?.filter((t=>t.structureId===d?.structureId)),m=l.filter((t=>t.roundNumber===c&&!t.matchUpTieId)),f=m.length,h=w(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 S=h,y=h[I-1];const v=fc({groupedOrder:s,roundPositionsCount:h.length}),T=v?.length||1;if(T<=h.length){const t=N(h,f/T);o===Io&&t.forEach((t=>t.reverse())),S=v?.length&&v?.map((e=>t[e-1])).flat()||S}o===go?y=S[I-1]:o===Io?((!v?.length||T>h.length)&&(I=m.length+1-I),y=S[I-1]):o===ho&&Qn()&&console.log(Fn,{feedProfile:o});const P=y&&m.reduce(((t,e)=>e.roundPosition===y?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 b=p?.find((({drawPosition:t})=>t===D));if(b){const{extension:t}=Mr({element:b,name:Wi});if(t?.value)return{disabledDrawPosition:D}}return{matchUp:P,targetDrawPosition:D,matchUpDrawPositionIndex:U}}function gc({finishingPositions:t,linkCondition:e,linkType:n,source:r}){const i=r.find((r=>{const i=!r.source?.finishingPositions||!t||b(t,r.source?.finishingPositions);return e===r.linkCondition&&i&&r.linkType===n}));return[So,yo].includes(i?.linkType)&&!i?.source?.roundNumber?wr({result:{error:Nn},stack:"getTargetLink",context:i}):i}function Ic({drawDefinition:t,structureId:e,roundNumber:n}){if(!t)return{error:j};if(!e)return{error:It};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 Uc({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}=ts({structureId:a?.structureId,drawDefinition:r}),s=o?.finishingPosition;return s===Ko?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:j};if(!n)return{error:It};const{links:r}=Ic({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=gc({source:c,linkType:So}),d=gc({linkCondition:vo,linkType:yo,source:c});let p=gc({source:c,linkType:yo});const l=d&&p;p||(p=d);const m=u?.target?.feedProfile,f=p?.target?.feedProfile,h=d?.target?.feedProfile;let g,I,U,S,y,v,w,T,P,D;if(e&&(a||o)&&(w=a&&m!==fo&&t.find((({matchUpId:t})=>t===a)),S=o&&f!==fo&&t.find((({matchUpId:t})=>t===o)),w||S))return{matchUp:i,targetLinks:{loserTargetLink:p,winnerTargetLink:u},targetMatchUps:{loserMatchUp:S,winnerMatchUp:w}};const{roundPosition:b}=i;D=D||t.filter((t=>t.structureId===r.structureId));const N=D.reduce(((t,e)=>e.roundNumber!==i.roundNumber||e.matchUpTieId?t:t+1),0);p&&!S&&f!==fo&&({matchUpDrawPositionIndex:v,targetDrawPosition:y,matchUp:S}=hc({targetLink:p,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:b,drawDefinition:n}));l&&h!==fo&&({matchUpDrawPositionIndex:U,targetDrawPosition:I,matchUp:g}=hc({targetLink:d,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:b,drawDefinition:n}));u&&!w&&m!==fo&&({matchUpDrawPositionIndex:P,targetDrawPosition:T,matchUp:w}=hc({targetLink:u,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:b,drawDefinition:n}));w||(D=D||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:D,matchUp:i})));return vr({matchUp:i,targetLinks:{loserTargetLink:p,winnerTargetLink:u,byeTargetLink:d},targetMatchUps:{winnerMatchUpDrawPositionIndex:P,loserMatchUpDrawPositionIndex:v,byeMatchUpDrawPositionIndex:U,winnerTargetDrawPosition:T,loserTargetDrawPosition:y,byeTargetDrawPosition:I,winnerMatchUp:w,loserMatchUp:S,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 Sc(t){if(!ha(t))return!1;const{matchUpId:e,drawPositions:n}=t,r="string"==typeof e,i=!n||Array.isArray(n)&&n.length<=2&&n.every((t=>p(t)||null==t));return r&&i}function yc(t){return!!Array.isArray(t)&&t.every(Sc)}function vc({matchUps:t=[],interpolate:i}){if(!yc(t))return{roundMatchUps:[],error:Nn};const a=t.reduce(((t,e)=>{const r="string"==typeof e.roundNumber?n(e.roundNumber):e.roundNumber;return!e.roundNumber||t.includes(r)?t:t.concat(r)}),[]).sort(e).map((n=>{const r=t.filter((t=>t.roundNumber===n)),i=r.find((({matchUpType:t})=>t===Qs))?r.filter((({matchUpType:t})=>t===Qs)):r;return{[n]:(a=i,a.sort(((t,n)=>e(t.roundPosition,n.roundPosition))))};var a})),o=t.reduce(((t,e)=>{const r="string"==typeof e.roundNumber?n(e.roundNumber):e.roundNumber;return t[r]||(t[r]=vr({abbreviatedRoundName:e.abbreviatedRoundName,finishingRound:e.finishingRound,roundName:e.roundName})),t}),{}),s=Object.assign({},...a);if(i){const t=Math.max(...Object.keys(s).map((t=>n(t))).filter((t=>!isNaN(t)))),e=s[t]?.length;if(e>1&&r(e)){const n=t+1;w(n,n+e/2).forEach(((t,n)=>{s[t]=w(0,e/(2+2*n)).map((()=>({})))}))}}let c=0;const u=Object.assign({},...Object.keys(s).map((t=>{const e=s[t]?.length,n=s[t]?.filter((t=>!Ya.includes(t.matchUpStatus)&&!t.score?.scoreStringSide1))?.length,r=e&&e===n;return c=Math.max(c,e),{[t]:{matchUpsCount:e,inactiveCount:n,inactiveRound:r}}})));let d=0,p=0;const l=Object.keys(s).map((t=>n(t))).filter((t=>!isNaN(t)));l.forEach((t=>{const n=s[t].sort(((t,e)=>t.roundPosition-e.roundPosition)),r=n.map((t=>t?.drawPositions||[])).flat();if(u[t].roundNumber=t,u[t].roundFactor=u[t].matchUpsCount?c/u[t].matchUpsCount:1,u[t].finishingRound=o[t]?.finishingRound,u[t].roundName=o[t]?.roundName,u[t].abbreviatedRoundName=o[t]?.abbreviatedRoundName,u[t].finishingPositionRange=s[t]?.[0]?.finishingPositionRange,1!==t&&u[t-1]){const r=u[t-1],i=r.drawPositions,a=r.matchUpsCount/u[t].matchUpsCount,o=N(i,a),s=n.map((n=>{const{roundPosition:r}=n,a=[...n.drawPositions||[],void 0,void 0].slice(0,2);if(!r)return a;const s=a?.filter(Boolean)||[];if(!s?.length)return[void 0,void 0];if(t<3&&2===s?.length)return a?.slice().sort(e);const c=P(i,s).length!==s?.length;if(s?.length&&c)return 1===s?.length?[s[0],void 0]:a?.slice().sort(e);const u=2*(r-1);return o.slice(u,u+2).map((t=>s?.find((e=>t.includes(e)))))}));u[t].drawPositions=s?.flat(),u[t].pairedDrawPositions=s}else{const n=r.sort(e),i=N(n,2);u[t].drawPositions=n,u[t].pairedDrawPositions=i}u[t+1]&&u[t+1].matchUpsCount===u[t].matchUpsCount&&(u[t+1].feedRound=!0,u[t+1].feedRoundIndex=p,u[t].preFeedRound=!0,p+=1),u[t]&&!u[t].feedRound&&(u[t].roundIndex=d,d+=1)}));const m=!!Object.values(u).find((({matchUpsCount:t})=>!r(t)));return{hasNoRoundPositions:t.some((t=>!t.roundPosition)),roundsNotPowerOf2:m,maxMatchUpsCount:c,roundMatchUps:s,roundNumbers:l,roundProfile:u,...E}}function wc({drawDefinition:t,inContextDrawMatchUps:r}){const i={};return r.forEach((a=>{const{matchUpId:o,structureId:s,drawPositions:c=[]}=a,{structure:u}=ts({drawDefinition:t,structureId:s});if(u?.finishingPosition===Yo){const{roundNumber:t}=a,r=t&&n(t)+1,i=u.matchUps??[],{roundMatchUps:o}=vc({matchUps:i});if(r&&o?.[r]){const t=[...c].sort(e).map(((t,e)=>{const n=o[r].find((e=>e.drawPositions?.includes(t)));return{matchUpId:n?.matchUpId,roundNumber:r,schedule:n?.schedule,sideNumber:e+1,structureName:u.structureName}}));Object.assign(a,{sidesTo:t})}}else{const e=Uc({useTargetMatchUpIds:!0,inContextDrawMatchUps:r,inContextMatchUp:a,drawDefinition:t,matchUpId:o});let{winnerMatchUp:n}=e.targetMatchUps;const{loserMatchUp:s}=e.targetMatchUps;!a.winnerMatchUpId&&n&&(a.winnerMatchUpId=n.matchUpId),!a.loserMatchUpId&&s&&(a.loserMatchUpId=s.matchUpId);const c=Pc({upcomingMatchUp:n});let u=Pc({upcomingMatchUp:s});if(a.matchUpStatus!==Ma&&s?.matchUpStatus===Ma){const{matchUp:e}=Tc({matchUp:s,drawDefinition:t,inContextDrawMatchUps:r})||{};u=e&&Pc({upcomingMatchUp:e})||u}const p=a.schedule?.timeAfterRecovery;if(p){if(c?.schedule?.scheduledTime){ti(c.schedule.scheduledTime)<ti(p)&&(i[c.matchUpId]=a.matchUpId,c.schedule.scheduleConflict=a.matchUpId)}if(u?.schedule?.scheduledTime){ti(u.schedule.scheduledTime)<ti(p)&&(i[u.matchUpId]=a.matchUpId,u.schedule.scheduleConflict=a.matchUpId)}}if(Object.assign(a,{winnerTo:c,loserTo:u}),a.drawPositions?.filter(Boolean).length){const t=e.targetLinks?.loserTargetLink,i=t?.linkCondition===vo,o=(d=a,d?.sides?.map((({participant:t,participantId:e,qualifier:n})=>t||e&&{participantId:e}||n&&{qualifier:n})).filter(Boolean)||[]);if(o.length){const t=Pa(n?.sides),a=Pa(s?.sides),c=o.find((({participantId:e})=>t.includes(e)))?[]:o,u=o.find((({participantId:t})=>a.includes(t)))?[]:o;s&&i&&u.length<2&&u.push({bye:!0,tbd:!0}),c?.length&&n&&(!e.targetMatchUpIds&&n&&(n=r.find((({matchUpId:t})=>t===n.matchUpId))),n.potentialParticipants||(n.potentialParticipants=[]),n.potentialParticipants.push(c)),u?.length&&s&&(e.targetMatchUpIds||(n=r.find((({matchUpId:t})=>t===s.matchUpId))),s.potentialParticipants||(s.potentialParticipants=[]),s.potentialParticipants.push(u))}}}var d})),Object.keys(i).length&&r.forEach((t=>{Object.keys(i).includes(t.matchUpId)&&(t.schedule.scheduleConflict=i[t.matchUpId])})),{scheduleConflictMatchUpIds:i}}function Tc({matchUp:t,drawDefinition:e,inContextDrawMatchUps:n}){const{matchUpId:r,matchUpStatus:i,structureId:a}=t||{};if(!t||!a||t?.matchUpStatus===ja)return{matchUp:t};if(i===Ma){let i;if(t.winnerMatchUpId)i=n.find((({matchUpId:e})=>e===t.winnerMatchUpId));else{const t=Uc({inContextDrawMatchUps:n,drawDefinition:e,matchUpId:r});({winnerMatchUp:i}=t?.targetMatchUps||{})}return Tc({matchUp:i,drawDefinition:e,inContextDrawMatchUps:n})}return{matchUp:void 0}}function Pc(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 Dc({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:n,drawDefinition:r,structure:i,event:a}){if(!Array.isArray(e))return{error:Kt};const o={};return n&&s(n),a&&s(a),r&&s(r),i&&s(i),{appliedPolicies:o,...E};function s(n){const r=n?.extensions,i=r?.find((t=>t.name===Vi))?.value;if(i)for(const n of Object.keys(i))(t?e.includes(n):!e.length||e.includes(n))&&(o[n]=gi(i[n],!1,!0))}}function bc({policyTypes:t=[],tournamentRecord:e,drawDefinition:n,structure:r,event:i}){if(!Array.isArray(t))return{error:Kt};const{appliedPolicies:a}=Dc({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:ee.message}}const Nc="WALKOVER",Rc="RETIRED",Mc="COMPETITIVE",Ac="ROUTINE",Ec="DECISIVE",Cc="winRatio",Oc={[Si]:{policyName:"Competitive Bands Default",profileBands:{[Ec]:20,[Ac]:50}}};function Fc({policyDefinitions:t,tournamentRecord:e,contextProfile:n,drawDefinition:r,event:i}){const a={policies:{}};if(!n)return a;const o=bc({tournamentRecord:e,drawDefinition:r,event:i}).policyDefinitions;if(n.withCompetitiveness){const e=t?.[Si]??o?.[Si]??Oc[Si];a.policies[Si]=e}return a}function kc({drawDefinition:t}){if("object"!=typeof t)return{error:V};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&&[to,no].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 xc({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 _c({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(gi(t,!0,!0),{containerStructureId:n,structureId:e,structureName:a}))):i})).flat();return(i?.matchUps||[]).concat(...a)}function Lc({matchUp:t}){return!!t&&(Ya.includes(t?.matchUpStatus)||t?.winningSide)}function Bc({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 Vc({tournamentParticipants:t,tournamentRecord:e,participantIds:n}){const r="getPairedParticipant";if(!t&&!e)return{error:_};if(!Array.isArray(n)||n.length>2)return{error:Pe};if(!n.length)return wr({result:{error:Fe},stack:r});const i=(t=t??e?.participants??[]).filter((t=>t.participantType===uc&&P(n,t.individualParticipantIds).length===n.length&&t.individualParticipantIds.length===n.length)),a=i[0];if(!a)return wr({result:{error:Ee},stack:r});const o=gi(i.slice(1),!1,!0);return{participant:gi(a),duplicatedPairParticipants:o,...E}}function jc({drawDefinition:t,participantId:e}){if("object"!=typeof t)return{error:j};if("string"!=typeof e)return{error:Ae};const{extension:n}=Mr({element:t,name:Zi});return{lineUp:(n?.value||{})[e]}}function Gc({drawDefinition:t,attributes:e}){let{extension:n}=Mr({element:t,name:Yi});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:Yi,value:r},xi({drawDefinition:t,extension:n}),{entryProfile:r}}function qc({drawDefinition:t}){const{extension:e}=Mr({element:t,name:Yi});return{entryProfile:e?.value||{}}}const $c="ALTERNATE",Wc="CONFIRMED",Hc="DIRECT_ACCEPTANCE",zc="FEED_IN",Yc="JUNIOR_EXEMPT",Kc="LUCKY_LOSER",Jc="ORGANISER_ACCEPTANCE",Zc="QUALIFIER",Xc="SPECIAL_EXEMPT",Qc="UNGROUPED",tu="UNPAIRED",eu="WILDCARD",nu="WITHDRAWN",ru=[Wc,Hc,Yc,Jc,Xc],iu=[zc,Kc,Zc],au=[Wc,Hc,zc,Yc,Jc,Xc,eu],ou=[Wc,Hc,Yc,Kc,Zc,Jc,Xc,eu],su=[$c,Wc,Hc,zc,Yc,Kc,Jc,Zc,"REGISTERED",Xc,Qc,tu,eu,nu],cu={ALTERNATE:$c,CONFIRMED:Wc,DIRECT_ACCEPTANCE:Hc,DIRECT_ENTRY_STATUSES:au,DRAW_SPECIFIC_STATUSES:iu,EQUIVALENT_ACCEPTANCE_STATUSES:ru,FEED_IN:zc,JUNIOR_EXEMPT:Yc,LUCKY_LOSER:Kc,ORGANISER_ACCEPTANCE:Jc,QUALIFIER:Zc,SPECIAL_EXEMPT:Xc,STRUCTURE_SELECTED_STATUSES:ou,UNGROUPED:Qc,UNPAIRED:tu,VALID_ENTRY_STATUSES:su,WILDCARD:eu,WITHDRAWN:nu};function uu({stage:t,drawDefinition:e}){const{entryProfile:n}=qc({drawDefinition:e}),r=Object.keys(n).includes(t);if(!r&&ro.includes(t)){return Gc({drawDefinition:e,attributes:[{[t]:{drawSize:void 0,alternates:!0}}]}),!0}return r}function du({stage:t,drawDefinition:e,entryStatus:n}){return e.entries.reduce(((e,r)=>r.entryStage===t&&r.entryStatus===n?e+1:e),0)}function pu({provisionalPositioning:t,placementGroup:n,drawDefinition:r,stageSequence:i,entryStatuses:a,structureId:o,roundTarget:s,stages:c,stage:u}){const d=r.entries?.reduce(((t,e)=>{const n=Mr({name:ra,element:e})?.extension?.value,r=u&&e.entryStage===u||c?.length&&e.entryStage&&c.includes(e.entryStage),o=!a||e.entryStatus&&a.includes(e.entryStatus),d=e.entryStageSequence??1;return r&&(!i||d===i)&&o&&(!s||!n||s===n)?t.concat(e):t}),[])??[];if(o&&u===no){const{playoffEntries:i,error:a}=function({provisionalPositioning:t,drawDefinition:n,structureId:r}){const i=[],a=(n.links??[]).find((t=>t.linkType===Uo&&t.target.structureId===r));if(a){const{finishingPositions:r,structureId:o}=a.source,{structure:s}=ts({drawDefinition:n,structureId:o});if(s?.structureType===mo){(s.structures??[]).forEach((n=>{const a=n.positionAssignments??[],{structureId:o}=n,s=o,c=Object.assign({},...a.map((t=>{const{participantId:e}=t,n=Mr({element:t,name:ca}).extension?.value;return n&&e?{[e]:n}:void 0})).filter(Boolean)),u=Object.keys(c).reduce(((e,n)=>{const r=c[n],i=r.groupOrder||t&&r.provisionalOrder;return e.includes(i)||e.push(i),e}),[]),d=u.length===Object.keys(c).length,p=Object.keys(c).filter((e=>{const n=c[e],i=n.groupOrder||t&&n.provisionalOrder;return r?.includes(i)}));t&&!d||p.forEach((n=>{const a=c[n],{groupOrder:o,provisionalOrder:u,GEMscore:d}=a,p=o||t&&u,l=(r??[]).sort(e).indexOf(p)+1;i.push({entryStage:no,entryStatus:zc,placementGroup:l,groupingValue:s,participantId:n,GEMscore:d})}))}))}}return{playoffEntries:i}}({provisionalPositioning:t,drawDefinition:r,structureId:o});return a&&console.log("playoff entries error"),(i?.length?i:d).filter((t=>!n||t.placementGroup===n))}return d}function lu({provisionalPositioning:t,returnAllProxies:e,drawDefinition:n,structureId:r,structure:i}){let a,o=[];i||({structure:i,error:a}=ts({drawDefinition:n,structureId:r}));const s=rs({structure:i}).positionAssignments;if(a||!i)return{seedAssignments:[],error:Ut};r||(r=i.structureId);const{stage:c,stageSequence:u}=i,d=c===no&&n&&pu({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=lt;return{seedAssignments:o,stageSequence:u,seedLimit:i.seedLimit??i?.positionAssignments?.length,stage:c,error:a}}const mu=(t,e)=>(t||0)+(e||0);function fu(t,e){const n=Array.isArray(t)?t[0]:t;return isNaN(n)&&Nc||n<=e[Ec]&&Ec||n<=e[Ac]&&Ac||Mc}function hu({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(mu)&&(n[r[0]>r[1]?0:1]+=1),{sets:e,games:n,score:t}}function gu(t){const e=Math.min(...t.games),n=Math.max(...t.games);return Math.round(e/n*100)}function Iu(t){return t.map(gu).sort().map((t=>parseFloat(t.toFixed(2))))}function Uu({tournamentRecord:t,drawDefinition:e,policyType:n,structure:r,event:i}){if(!t)return{error:_};const{appliedPolicies:a}=Dc({tournamentRecord:t,drawDefinition:e,structure:r,event:i});return a?.[n]?{policy:a[n]}:{info:ee?.message}}function Su({tournamentRecord:t,profileBands:e,matchUp:n}){if(!n)return{error:zt};const{score:r,winningSide:i}=n;if(!i)return{error:Nn};const a=!e&&t&&Uu({policyType:Si,tournamentRecord:t}).policy,o=e||a?.profileBands||Oc[Si].profileBands,s=Iu([hu({score:r})]),c=fu(s,o),u=Array.isArray(s)?s[0]:s;return{...E,competitiveness:c,pctSpread:u}}function yu({matchUp:t}){if(!t)return{error:zt};if(t&&!t.sides)return{error:Yt};if(t&&!t.hasContext)return{error:hn};const e=(t.sides??[])?.map((t=>t?.participantId)).filter(Boolean),n=t.sides?.filter((t=>t.participant?.participantType===sc)).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:m(i.concat(e)).filter(Boolean)??[],individualParticipantIds:i,sideParticipantIds:e,...E}}const vu="CHECK_IN",wu="CHECK_OUT",Tu="SCHEDULE.ASSIGNMENT.VENUE",Pu="SCHEDULE.ALLOCATION.COURTS",Du="SCHEDULE.ASSIGNMENT.COURT",bu="SCHEDULE.COURT.ORDER",Nu="SCHEDULE.DATE",Ru="SCHEDULE.ASSIGN.OFFICIAL",Mu="SCHEDULE.TIME.SCHEDULED",Au="SCHEDULE.TIME.START",Eu="SCHEDULE.TIME.STOP",Cu="SCHEDULE.TIME.RESUME",Ou="SCHEDULE.TIME.END",Fu="SCHEDULE.TIME.MODIFIERS",ku="TO_BE_ANNOUNCED",xu="NEXT_AVAILABLE",_u="FOLLOWED_BY",Lu="AFTER_REST",Bu="RAIN_DELAY",Vu=[ku,xu,_u,Lu,Bu],ju="SCALE",Gu="RATING",qu="RANKING",$u="SEEDING",Wu="PUBLISH",Hu="PUBLIC",zu="STATUS",Yu={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:Vu,AFTER_REST:Lu,ALLOCATE_COURTS:Pu,ASSIGN_COURT:Du,ASSIGN_OFFICIAL:Ru,ASSIGN_VENUE:Tu,CHECK_IN:vu,CHECK_OUT:wu,COMPLETED_DATE:"COMPLETED.DATE",COURT_ORDER:bu,ELIGIBILITY:"ELIGIBILITY",END_TIME:Ou,FOLLOWED_BY:_u,MEDICAL:"MEDICAL",MODIFICATION:"MODIFICATION",NEXT_AVAILABLE:xu,NOT_BEFORE:"NOT_BEFORE",OTHER:"other",PENALTY:"PENALTY",PUBLIC:Hu,PUBLISH:Wu,RANKING:qu,RATING:Gu,RAIN_DELAY:Bu,REGISTRATION:"REGISTRATION",RESUME_TIME:Cu,RETRIEVAL:"RETRIEVAL",SCALE:ju,SCHEDULE:"SCHEDULE",SCHEDULED_DATE:Nu,SCHEDULED_TIME:Mu,SEEDING:$u,START_TIME:Au,STATUS:zu,STOP_TIME:Eu,SUSPENSION:"SUSPENSION",TIME_MODIFIERS:Fu,TO_BE_ANNOUNCED:ku};function Ku({matchUp:t}){if(!t)return{error:zt};if(!t.hasContext)return{error:hn};if(!t.sides||2!==t.sides.filter(Boolean).length)return{error:Yt};const{nestedIndividualParticipantIds:e,allRelevantParticipantIds:n,sideParticipantIds:r}=yu({matchUp:t}),i=(t.timeItems??[]).filter((t=>t?.itemType&&[vu,wu].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===vu));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,...E}}function Ju(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 Zu(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 Xu({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)}function Qu({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}=Uu({policyType:Ni,tournamentRecord:t,event:r}),a=t?Mr({element:t,name:aa}).extension:void 0,o=a?.value,s=r&&Mr({name:aa,element:r}).extension,c=s?.value;return{scheduleTiming:{tournamentScheduling:o,eventScheduling:c,categoryName:e,categoryType:n,policy:i}}}const td="SINGLES",ed="SINGLES",nd="DOUBLES",rd="DOUBLES",id="TEAM",ad="TEAM",od={AGE:"AGE",BOTH:"BOTH",DOUBLES:nd,DOUBLES_EVENT:rd,RATING:"RATING",SINGLES:td,SINGLES_EVENT:ed,TEAM_EVENT:ad,TEAM:id},sd="DOUBLES_SINGLES",cd="SINGLES_DOUBLES",ud="total",dd="participantConflict",pd="matchUpConflict",ld="ISSUE_IDS",md="CONFLICT",fd="WARNING",hd="ERROR",gd="ISSUE",Id="STATE",Ud={SINGLES_DOUBLES:cd,DOUBLES_SINGLES:sd,TOTAL:ud,CONFLICT_MATCHUP_ORDER:pd,CONFLICT_PARTICIPANTS:dd,SCHEDULE_ISSUE_IDS:ld,SCHEDULE_CONFLICT:md,SCHEDULE_WARNING:fd,SCHEDULE_ERROR:hd,SCHEDULE_ISSUE:gd,SCHEDULE_STATE:Id};function Sd({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:n,matchUpFormat:r,categoryName:i,categoryType:a,eventType:o,event:s}){if(!n)return{error:_};o=o??s?.eventType??ed;const c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=Qu({tournamentRecord:n,categoryName:i,categoryType:a,event:s});return yd({eventType:o,timingDetails:{...u,matchUpFormat:r,categoryType:a,defaultTiming:c}})}function yd({timingDetails:t,eventType:e}){const n=function({matchUpFormat:t,categoryName:e,categoryType:n,defaultTiming:r,tournamentScheduling:i,eventScheduling:a,policy:o}){return Xu({categoryName:e,categoryType:n,timesBlockArray:[a?.matchUpAverageTimes&&Ju({...a,matchUpFormat:t}),i?.matchUpAverageTimes&&Ju({...i,matchUpFormat:t}),o?.matchUpAverageTimes&&Ju({...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 Xu({categoryName:a,categoryType:o,timesBlockArray:[e?.matchUpRecoveryTimes&&Zu({...e,averageMinutes:n,matchUpFormat:i}),t?.matchUpRecoveryTimes&&Zu({...t,averageMinutes:n,matchUpFormat:i}),s?.matchUpRecoveryTimes&&Zu({...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=e===ed?cd:sd;return{averageMinutes:i,recoveryMinutes:s,typeChangeRecoveryMinutes:a?.minutes&&(o?.includes(c)&&a.minutes[c]||s)}}function vd(t){return t.createdAt?new Date(t.createdAt).getTime():0}function wd({visibilityThreshold:t,timeItems:e,itemType:n}){const r=e.filter((e=>e&&e.itemType===n&&(!t||vd(e)<new Date(t).getTime()))).sort(((t,e)=>vd(t)-vd(e))).pop(),i=r&&vd(r);return{itemValue:r?.itemValue,timeStamp:i}}function Td({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=wd({timeItems:r?.timeItems||[],itemType:Mu,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{scheduledTime:i}:n}function Pd({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=wd({timeItems:r?.timeItems||[],itemType:Nu,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{scheduledDate:i}:n}function Dd({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=wd({timeItems:r?.timeItems||[],itemType:Pu,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{allocatedCourts:gi(i,!1,!0)}:n}function bd({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=wd({timeItems:r?.timeItems||[],itemType:Du,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{courtId:i}:n}function Nd({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=wd({timeItems:r?.timeItems||[],itemType:Tu,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{venueId:i}:n}function Rd({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:x};return{linkedTournamentIds:Object.assign({},...Object.keys(t).map((e=>{const n=t[e],r=n?.tournamentId,{extension:i}=Mr({element:n,name:Xi});return{[e]:(i?.value?.tournamentIds||[]).filter((t=>t!==r))}})))}}function Md(){const t=[];for(let e=0;e<256;e++)t[e]=(e<16?"0":"")+e.toString(16);const e=4294967295*Math.random()|0,n=4294967295*Math.random()|0,r=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return t[255&e]+t[e>>8&255]+t[e>>16&255]+t[e>>24&255]+"-"+t[255&n]+t[n>>8&255]+"-"+t[n>>16&15|64]+t[n>>24&255]+"-"+t[63&r|128]+t[r>>8&255]+"-"+t[r>>16&255]+t[r>>24&255]+t[255&i]+t[i>>8&255]+t[i>>16&255]+t[i>>24&255]}function Ad(t){const{disableNotice:e,venue:n,context:r}=t;if("object"!=typeof n)return{error:Nn};const i=nc(t);let a;n.venueId||(n.venueId=Md());for(const t of Object.values(i)){const e=Ed({disableNotice:!0,tournamentRecord:t,context:r,venue:n});if(e?.error)return e;a=e.venue}return e||sr({topic:us,payload:{venue:n}}),vr({...E,venue:a})}function Ed({tournamentRecord:t,disableNotice:e,context:n,venue:r}){if(!t)return{error:_};if(!r)return{error:ae,info:"missing venue"};t.venues||(t.venues=[]),r.venueId||(r.venueId=Md());if(t.venues.reduce(((t,e)=>t||e.venueId===r.venueId),void 0))return{error:nn};if(n){Nr({element:r,extension:{value:n,name:Gi}})}return t.venues.push(r),e||sr({payload:{venue:r,tournamentId:t.tournamentId},topic:us}),{...E,venue:gi(r)}}function Cd({tournamentRecords:t,tournamentRecord:e,venueId:n}){if(!e)return{error:_};if(!n)return{error:an};const r=(e.venues??[]).reduce(((t,e)=>e.venueId===n?e:t),void 0);if(!r&&t){const i=(Rd({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(const a of i){const i=Cd({tournamentRecord:t[a],venueId:n});if(i.success&&i.venue)return Ad({tournamentRecord:e,venue:i.venue}),{...E,venue:r}}}return r?{...E,venue:r}:{error:rn}}function Od({tournamentRecords:t,tournamentRecord:e,courtId:n}){if(!e)return{error:_};if(!n)return{error:ie};let r,i;if((e.venues??[]).forEach((t=>{(t.courts??[]).forEach((e=>{e.courtId===n&&(r=e,i=t)}))})),r)return{...E,court:r,venue:i};if(t){const a=(Rd({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(const o of a){const a=Od({tournamentRecord:t[o],courtId:n});if(a.success)return a.venue&&Ad({tournamentRecord:e,venue:a.venue}),{...E,court:r,venue:i}}}return wr({result:{error:tn},stack:"findCourt"})}function Fd({tournamentRecord:t,internalUse:e,courtId:n}){if(!t)return{error:_};if(!n)return{error:ie};const r=Od({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{...E,courtInfo:gi(i,!1,e)}}function kd({tournamentRecord:t,venueId:e}){if(!t)return{error:_};if(!e)return{error:an};const n=Cd({tournamentRecord:t,venueId:e});if(n.error)return n;const r=(n.venue?.courts??[]).map((e=>(({courtInfo:t})=>({...t}))(Fd({courtId:e.courtId,internalUse:!0,tournamentRecord:t})))),i=n.venue&&(({venueId:t,venueName:e,venueAbbreviation:n})=>({venueAbbreviation:n,venueName:e,venueId:t}))(n.venue),a=i&&{...i,courtsInfo:r};return{...E,venueData:gi(a,!1,!0)}}function xd({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=wd({timeItems:r?.timeItems||[],itemType:Fu,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{timeModifiers:i}:n}function _d(t){if(Br.test(t)){const e=Hr();return new Date(`${e}T${t}`)}return new Date(t)}function Ld(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 Bd({event:t,eventId:e}){if(!t)return{error:Tt};const n=Mr({name:Ki,element:t}),r=n?.extension,i=e?gi(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 Vd(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&&Bd({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,...wr({result:{error:Pt},stack:i})}}return{event:void 0,drawDefinition:void 0,...wr({result:{error:q},context:{drawId:r,eventId:n},stack:i})}}function jd({scheduleVisibilityFilters:t,afterRecoveryTimes:e,tournamentRecord:n,usePublishState:r,scheduleTiming:i,matchUpFormat:a,publishStatus:o,matchUpType:s,matchUp:c,event:u}){if(!c)return{error:zt};if(e&&!c.matchUpType&&!s&&(u||n)&&c.drawId){let t=u?.drawDefinitions?.find((t=>t.drawId===c.drawId));!t&&n&&({drawDefinition:t,event:u}=Vd({tournamentRecord:n,drawId:c.drawId}));const e=c.structureId&&t?.structures?.find((({structureId:t})=>t===c.structureId));s=e?.matchUpType||t?.matchUpType||u?.eventType!==id&&u?.eventType}const{milliseconds:d,time:p}=function({matchUp:t}){if(!t)return{error:zt};if(!t.timeItems)return{error:fn};const e=t.timeItems.filter((t=>[Au,Eu,Cu,Ou].includes(t?.itemType))).sort(((t,e)=>_d(t.itemValue).getTime()-_d(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 Au:n=0;break;case Ou:if(t.lastValue&&[Au,Cu].includes(t.lastType)){const r=_d(e.itemValue).getTime()-_d(t.lastValue).getTime();n=t.milliseconds+r}else n=t.milliseconds;break;case Eu:if([Au,"SCHECULE.TIME.RESUME"].includes(t.lastType)){const r=_d(e.itemValue).getTime()-_d(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([Au,Cu].includes(n.lastType)){const t=(new Date).getTime()-_d(n.lastValue).getTime();n.milliseconds+=t}return{milliseconds:n.milliseconds,time:Ld(n.milliseconds),relevantTimeItems:e}}({matchUp:c}),{startTime:l}=function({matchUp:t}){const e=t=>t.createdAt?new Date(t.createdAt).getTime():0,n=(t?.timeItems||[]).reduce(((t,n)=>{const r=n.itemType===Au&&n;return r&&(!t||e(r)<e(t))?r:t}),void 0),r=n?.itemValue;return{startTime:r}}({matchUp:c}),{endTime: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===Ou&&n;return r&&(!t||e(r)>e(t))?r:t}),void 0),r=n?.itemValue;return{endTime:r}}({matchUp:c});let f;const{visibilityThreshold:h,eventIds:g,drawIds:I}=t??{};if(g&&!g.includes(c.eventId)||I&&!I.includes(c.drawId))f=vr({milliseconds:d,startTime:l,endTime:m,time:p});else{const t={matchUp:c,visibilityThreshold:h},{allocatedCourts:r}=Dd(t),{scheduledTime:o}=Td(t);let{scheduledDate:u}=Pd(t);const{venueId:g}=Nd(t),{courtId:I}=bd(t),{courtOrder:U}=function({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=wd({timeItems:r?.timeItems||[],itemType:bu,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{courtOrder:i}:n}(t),{timeModifiers:S}=xd(t);let y,v,w,T,P;const D=c.matchUpType??s;if(i&&o&&e&&D){const t={matchUpFormat:c.matchUpFormat??a,...i};({averageMinutes:v=0,recoveryMinutes:w=0,typeChangeRecoveryMinutes:T=0}=yd({timingDetails:t,eventType:D})),(v||w)&&(y=m?pi(ni(m),w):pi(o,v+w)),T&&(P=m?pi(ni(m),T):pi(o,v+T))}!u&&o&&(u=ri(o));const b=Gr({scheduledDate:u,scheduledTime:o}),N={},R=(n&&g&&kd({tournamentRecord:n,venueId:g}))?.venueData||{};g&&(N[g]=R);const{venueName:M,venueAbbreviation:A,courtsInfo:E}=R,C=I&&E?.find((t=>t.courtId===I)),O=C?.courtName;for(const t of r||[]){if(!n)break;t.venueId&&!N[t.venueid]&&(N[t.venueId]=kd({venueId:t.venueId,tournamentRecord:n})?.venueData);const e=N[t.venueId];t.venueName=e?.venueName;const r=e?.courtsInfo?.find((e=>e.courtId===t.courtId));t.courtName=r?.courtName}f=vr({typeChangeTimeAfterRecovery:P,timeAfterRecovery:y,scheduledDate:u,scheduledTime:o,isoDateString:b,allocatedCourts:r,timeModifiers:S,venueAbbreviation:A,venueName:M,venueId:g,courtOrder:U,courtName:O,courtId:I,typeChangeRecoveryMinutes:T,recoveryMinutes:w,averageMinutes:v,milliseconds:d,startTime:l,endTime:m,time:p})}const{scheduledDate:U}=Pd({matchUp:c}),{scheduledTime:S}=Td({matchUp:c});if(r&&o?.displaySettings?.draws){const t=o.displaySettings.draws,e=(t?.[c.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){f=_r({source:f,template:Object.assign({},...Object.keys(f).map((t=>({[t]:!0}))),t)})}}}return{schedule:f,endDate:c.matchUpStatus&&Ya.includes(c.matchUpStatus)&&(ri(m)||ri(U)||ri(S))||void 0}}function Gd(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 qd({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 $d({drawDefinition:t,structure:e,matchUp:n,event:r}){return{tieFormat:qd({item:n,drawDefinition:t,structure:e,event:r})||qd({item:e,drawDefinition:t,structure:e,event:r})||Gd(t)||Gd(r)}}function Wd(t){if(!Array.isArray(t))return"";const e=t.filter(s);if(!e.length)return"";return m([Math.min(...e),Math.max(...e)]).join("-")}const Hd="timed",zd="NOAD",Yd="SET",Kd={S:"normal",F:"final"};function Jd(t){if("string"==typeof t){const e=t.startsWith("T")&&Hd||t.startsWith(Yd)&&Yd||"";if(e===Hd){const e=tp(t);if(e)return{simplified:!0,setFormat:e,bestOf:1}}if(e===Yd)return function(t){const e=t.split("-"),n=np(e[0].slice(3)),r=1===n||n%2!=0?n:void 0,i=1!==n&&n%2==0?n:void 0,a=e&&Zd(e[1]),o=e&&Zd(e[2]),s=a&&a.timed||o&&o.timed,c=r&&r<6||s&&i,u=!e[2]||o,d=a,p=vr({setFormat:a,exactly:i,bestOf:r});o&&(p.finalSetFormat=o);if(c&&d&&u)return p}(t)}}function Zd(t){if(":"===t?.[1]){const e=t.split(":"),n=Kd[e[0]],r=e[1];if(n&&r){if(r.startsWith("TB")){const t=Qd(r);return!1!==t&&("object"==typeof t?{tiebreakSet:t}:void 0)}if(r.startsWith("T"))return tp(r);const e=t.match(/^[FS]:(\d+)([A-Za-z]*)/),n=e&&ep(e[2])||!1,i=!e?.[2]||n,a=e?np(e[1]):void 0,o=Xd(r),s=!1!==o,c=s&&o||a,u=Qd(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 Xd(t,e=!0){const n=t?.indexOf("@")>0&&t.split("@");if(n){return(e?np(n[1]):n[1])||!1}}function Qd(t){if(t){if(t.startsWith("TB")){const e=Xd(t,!1),n=t.match(/^TB(\d+)([A-Za-z]*)/),r=n?.[1],i=n&&ep(n[2]),a=!n?.[2]||i,o=np(r);if(o&&a){const t={tiebreakTo:o};return e&&"string"==typeof e&&!p(e)&&(t.modifier=e),i&&(t.NoAD=!0),t}return!1}return!1}}function tp(t){const e=t.slice(1),n=e.match(/^(\d+)(@?[A-Za-z]*)/),r=np(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 ep(t){return t&&t.indexOf(zd)>=0}function np(t){return isNaN(Number(t))?0:Number(t)}function rp(t){const{matchUps:e,isCollectionMatchUp:n,excludeMatchUpStatuses:r,matchUpStatuses:i,hasWinningSide:a,matchUpFormats:o,roundPositions:s,matchUpFormat:c,collectionIds:u,isMatchUpTie:d,roundNumbers:p,matchUpIds:l,roundNames:m,stageSequences:f,scheduledDates:h,scheduledDate:g,participantIds:I,processContext:U,tournamentIds:S,matchUpTypes:y,structureIds:v,readyToScore:w,courtIds:T,eventIds:P,venueIds:D,drawIds:b,stages:N,filterMatchUpIds:R=!0,filterMatchUpTypes:M=!0}=t,A=Array.isArray(I)?I.filter(Boolean):[],E=Array.isArray(i)?i.filter(Boolean):[],C=Array.isArray(r)?r.filter(Boolean):[],O=Array.isArray(N)?N.filter(Boolean):[],F=Array.isArray(f)?f.filter(Boolean):[],k=Array.isArray(u)?u.filter(Boolean):[],x=Array.isArray(m)?m.filter(Boolean):[],_=Array.isArray(p)?p.filter(Boolean):[],L=Array.isArray(s)?s.filter(Boolean):[],B=Array.isArray(l)&&R?l.filter(Boolean):[],V=Array.isArray(y)&&M?y.filter(Boolean):[],j=Array.isArray(T)?T.filter(Boolean):[],G=Array.isArray(D)?D.filter(Boolean):[],q=Array.isArray(o)&&o.filter(Boolean)||"string"==typeof c&&[c]||[],$=Array.isArray(h)&&h.filter(Boolean)||"string"==typeof g&&g.length&&[g]||[],W=Array.isArray(S)?S.filter(Boolean):[],H=Array.isArray(P)?P.filter(Boolean):[],z=Array.isArray(b)?b.filter(Boolean):[],Y=Array.isArray(v)?v.filter(Boolean):[];return e.filter((t=>{if(w&&t.matchUpType!==Xs&&!t.readyToScore)return!1;if(t.winningSide&&a&&![1,2].includes(t.winningSide))return!1;if(void 0!==d){if(d&&!t.tieMatchUps)return!1;if(!d&&t.tieMatchUps)return!1}if(void 0!==n){if(n&&!t.collectionId)return!1;if(!n&&t.collectionId)return!1}if(O.length&&!O.includes(t.stage))return!1;if(F.length&&!F.includes(t.stageSequence))return!1;if(k.length&&(!t.collectionId||!k.includes(t.collectionId)))return!1;if(x.length&&(!t.roundName||!x.includes(t.roundName)))return!1;if(_.length&&(!t.roundNumber||!_.includes(t.roundNumber)))return!1;if(L.length&&(!t.roundPosition||!L.includes(t.roundPosition)))return!1;if(E.length&&(!t.matchUpStatus||!E.includes(t.matchUpStatus)))return!1;if(C.length&&t.matchUpStatus&&C.includes(t.matchUpStatus))return!1;if(B.length&&!B.includes(t.matchUpId))return!1;if(V.length&&(!t.matchUpType||!V.includes(t.matchUpType)))return!1;if(q.length&&(!t.matchUpFormat||!q.includes(t.matchUpFormat)))return!1;if($?.length){const{scheduledTime:e}=Td({matchUp:t}),{scheduledDate:n}=Pd({matchUp:t}),r=ri(e)||n;if(!$.find((t=>fi(t,r))))return!1}if(j.length){const{courtId:e}=bd({matchUp:t}),{allocatedCourts:n}=Dd({matchUp:t}),r=n?.map((({courtId:t})=>t));if(!j.filter(Boolean).includes(e)||r?.includes(e))return!1}if(G.length){const{venueId:e}=Nd({matchUp:t});if(!G.filter(Boolean).includes(e))return!1}if(U){if(W.length&&!W.includes(t.tournamentId))return!1;if(H.length&&!H.includes(t.eventId))return!1;if(z.length&&!z.includes(t.drawId))return!1;if(Y.length&&!Y.includes(t.structureId))return!1;if(A.length){const e=t.sides?.map((({participantId:t})=>t)).filter(Boolean)??[];if(!A.some((t=>e.includes(t))))return!1}}return!0}))}function ip({roundsNotPowerOf2:t,drawDefinition:e,structure:n,matchUps:r}){if(!n)return!1;r=r??n.matchUps??[],t=t??vc({matchUps:r}).roundsNotPowerOf2;const i=!!n.positionAssignments?.find((({drawPosition:t})=>t))||!!r?.find((({drawPositions:t})=>t?.length));return(!e?.drawType||e.drawType!==Ao)&&!n?.structures&&t&&i}function ap({drawDefinition:t,structure:e}){if(!e)return!1;const n=e.matchUps||e.roundMatchUps&&Object.values(e.roundMatchUps).flat(),r=n?.find((t=>t?.roundPosition)),i=n?.find((t=>t?.drawPositions?.length));return!(e?.structures||e?.stage===eo||t?.drawType&&t.drawType!==wo||r||i)}const op={[Pi]:{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:{[Xa]:"",[no]:"P",[Qa]:"Q",[to]:"C"}}};const sp="tournamentRecords",cp="policyDefinitions",up="tournamentRecord",dp="drawDefinition",pp="matchUpFormat",lp="participantId",mp="scheduleDates",fp="structureId",hp="matchUpIds",gp="structures",Ip="matchUpId",Up="inContext",Sp="structure",yp="courtIds",vp="venueIds",wp="matchUps",Tp="courtId",Pp="eventId",Dp="matchUp",bp="drawId",Np="error",Rp="event",Mp="param",Ap="object",Ep="array",Cp="validate",Op="invalid",Fp="_ofType",kp="_oneOf",xp={[sp]:x,[up]:_,[cp]:Jt,[dp]:j,[lp]:Ae,tournamentId:B,[fp]:It,[hp]:$t,[gp]:St,[Ip]:qt,[Sp]:yt,[Tp]:ie,[wp]:Ht,[Dp]:zt,[yp]:ae,[vp]:ae,[bp]:at,[Pp]:Tt,[Rp]:Pt},_p={[sp]:Ap,[cp]:Ap,[up]:Ap,[dp]:Ap,[mp]:Ep,[hp]:Ep,[gp]:Ep,[Sp]:Ap,[yp]:Ep,[vp]:Ep,[wp]:Ep,[Dp]:Ap,[Rp]:Ap};function Lp(t,e,n){if(!t&&!ha(t))return{error:Nn};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:Nn};const{paramError:r,errorParam:i}=function(t,e){let n;const r=e.find((({_ofType:e,_oneOf:r,_anyOf:i,validate:a,...o})=>{const s=r&&function(t,e){if(!e)return;const n=Bp(t,e);return 1!==n.length?{error:Nn}:n.reduce(((t,e)=>({...t,[e]:!0})),{})}(t,r);if(s?.error)return s.error;s&&Object.assign(o,s);const c=i&&function(t,e){if(!e)return;const n=Bp(t,e).filter((e=>t[e]));return n.length<1?{error:Nn}:n.reduce(((t,e)=>({...t,[e]:!0})),{})}(t,i);if(c?.error)return c.error;c&&Object.assign(o,c);const u=Object.keys(o).filter((t=>"boolean"==typeof o[t])),d=u.find((r=>{const i=!ma(a)&&(void 0===t[r]||function(t,e,n){if(n=n||_p[e]||"string","array"===n)return!Array.isArray(t[e]);return typeof t[e]!==n}(t,r,e)),o=i||a&&!function(t,e){return!ma(e)||e(t)}(t[r],a);return o&&(n=r),o}));return!u.length||d}));return{paramError:r,errorParam:n}}(t,e);if(!r)return{valid:!0};return wr({info:{param:i},result:{error:void 0===t[i]?xp[i]||Nn:r.validate&&r.invalid||Nn},stack:n})}function Bp(t,e){return P(Object.keys(t),Object.keys(e))}function Vp(t){const e=Lp(t,[{[Dp]:!0}]);if(e.error)return e;const n=t?.matchUp;let r=n?.matchUpType;if(!r&&n?.sides?.length){const t=n.sides.find((({participant:t})=>t)),e=t?.participant,i=e?.participantType;r=i===sc&&Ks||i===uc&&Zs||i===dc&&dc||void 0}return{matchUpType:r}}function jp({drawPositionCollectionAssignment:t,positionAssignments:e,displaySideNumber:n,seedAssignments:r,drawPosition:i,isFeedRound:a,sideNumber:o}){const s=e.find((t=>t.drawPosition&&t.drawPosition===i)),c=t?t[i]?.participantId:s?.participantId,u=s?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})}else r.bye&&Object.assign(a,{bye:!0});r.qualifier&&Object.assign(a,{qualifier:!0});return a}({displaySideNumber:n,seedAssignments:r,participantId:c,assignment:s,sideNumber:o}):{};a&&(1===o?Object.assign(u,{participantFed:!0}):Object.assign(u,{participantAdvanced:!0}));const d=t?.[i]?.teamParticipant,p=t?.[i]?.participant,l=t?.[i]?.substitutions;return p&&Object.assign(u,{participant:p}),l&&Object.assign(u,{substitutions:l}),d&&Object.assign(u,{teamParticipant:d}),u}const Gp="ANY",qp="MALE",$p="MIXED",Wp="OTHER",Hp="FEMALE",zp={ANY:Gp,MALE:qp,FEMALE:Hp,MIXED:$p,OTHER:Wp};function Yp({scheduleVisibilityFilters:t,tournamentAppliedPolicies:r,provisionalPositioning:i,tournamentParticipants:a,afterRecoveryTimes:o,policyDefinitions:s,tournamentRecord:c,seedAssignments:u,usePublishState:d,contextFilters:l,contextContent:f,matchUpFilters:h,participantMap:g,scheduleTiming:I,contextProfile:U,drawDefinition:S,publishStatus:y,context:v={},exitProfiles:T,matchUpsMap:P,structure:D,inContext:A,event:E}){let C={},O={};if(a=a??c?.participants,!D)return{collectionPositionMatchUps:C,error:yt,roundMatchUps:O,matchUps:[]};const F=Array.isArray(h?.eventIds)?h?.eventIds.filter(Boolean):[],k=Array.isArray(h?.structureIds)?h?.structureIds.filter(Boolean):[],x=Array.isArray(h?.drawIds)?h?.drawIds.filter(Boolean):[],_=!v?.eventId||!F?.length&&!l?.eventIds?.filter(Boolean).length||F?.includes(v.eventId)||l?.eventIds?.includes(v.eventId),L=!k?.length||k.includes(D.structureId),B=!S||!x?.length||x.includes(S.drawId);if(!_||!L||!B)return{collectionPositionMatchUps:C,roundMatchUps:O,matchUps:[]};U&&!f&&(f=Fc({tournamentRecord:c,contextProfile:U,drawDefinition:S}));const{appliedPolicies:V}=Dc({drawDefinition:S}),G={...r,...V,...s},q=G?.scoring?.structures,$=D.stage&&q?.stage&&q?.stage[D.stage],W=D.stageSequence&&$?.stageSequence&&$.stageSequence[D.stageSequence],H=G?.scoring?.requireAllPositionsAssigned||$?.requireAllPositionsAssigned||W?.requireAllPositionsAssigned;P||(P=xc({drawDefinition:S,structure:D}));const{positionAssignments:z,allPositionsAssigned:Y}=is({structure:D}),K=!H||Y,{seedAssignments:J}=lu({provisionalPositioning:i,drawDefinition:S,structure:D});u=u??J;const{roundOffset:Z,structureId:X,structureName:Q,stage:tt,stageSequence:et}=D,{drawId:nt,drawName:rt,drawType:it}=S??{};T=T||S&&kc({drawDefinition:S}).exitProfiles;const at=T?.[X],ot=at?.length&&(at[0].split("-").map((t=>parseInt(t))).reduce(((t,e)=>t+e))||0),st=!!D.structures;let ct=_c({matchUpsMap:P,structureId:X,inContext:A});const ut=G?.[Pi],dt=function({roundNamingPolicy:t,drawDefinition:e,structure:n,matchUps:r}){const{roundProfile:i,roundMatchUps:a}=vc({matchUps:r}),{structureAbbreviation:o,stage:s}=n,c=ap({structure:n}),u=ip({structure:n}),d=n.structures,p={},l=op[Pi],m=n.stage===Qa,f=m?Math.max(...(e?.structures??[]).filter((t=>t.stage===Qa)).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||{},S=t?.affixes?.preFeedRound||l.affixes.preFeedRound,y=t?.affixes?.roundNumber||l.affixes.roundNumber,v=(t?.namingConventions||l.namingConventions).round,w=s&&s!==Xa?s[0]:"",T=t?.stageConstants||l.stageConstants,P=`${g}${s&&T?.[s]||w}${h}`,D=i?Object.keys(i):[],b=m&&T?.[Qa]?`${T?.[Qa]}-`:"";if(d||c||u)Object.assign(p,...D.map((t=>({[t]:{roundName:`${b}${v} ${t}`,abbreviatedRoundName:`${y}${t}`}}))));else{const e=m&&(t?.qualifyingFinishMap||l?.qualifyingFinishMap||{});Object.assign(p,...D.map((t=>{if(!i?.[t])return;const{matchUpsCount:n,preFeedRound:r}=i[t],a=2*n,s=e?.[i?.[t].finishingRound]||e&&`${y}${a}`||I[n]||`${y}${a}`,c=r?`-${S}`:"",u=[P,o,`${s}${c}`].filter(Boolean).join("-"),d=U[n]||`${y}${a}`;return{[t]:{abbreviatedRoundName:[P,o,`${d}${c}`].filter(Boolean).join("-"),roundName:u}}})))}return{roundNamingProfile:p,roundProfile:i,roundMatchUps:a}}({roundNamingPolicy:ut,drawDefinition:S,structure:D,matchUps:ct}),{roundNamingProfile:pt,roundProfile:lt}=dt;if(O=dt?.roundMatchUps??[],h&&(ct=rp({matchUps:ct,...h,filterMatchUpTypes:!1,filterMatchUpIds:!1})),A){const{sourceDrawPositionRanges:n}=function({drawDefinition:t,structureId:e,matchUpsMap:n}){if(!t)return{error:j};if(!e)return{error:It};const{structure:r}=ts({drawDefinition:t,structureId:e});if(r?.stage!==to)return{error:At,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=>({[t]:vc({matchUps:_c({structureId:t,matchUpsMap:n})}).roundProfile})))),c=_c({matchUpsMap:n,structureId:e}),{roundProfile:u}=vc({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=fc({roundPositionsCount:g.length,groupedOrder:i}),U=I?.length||1;if(U<=h){const t=N(g,p.length/U);r===Io&&t.forEach((t=>t.reverse())),g=I?.length&&I?.map((e=>t[e-1])).flat()||g}let S=N(g,f);if(I?.length||r!==Io||S.reverse(),a){const t=w(0,a.interleave).map((()=>{})),e=w(0,a.offset).map((()=>{}));S=S.map((e=>[e,...t])),S.unshift(e),S=S.flat(1);const n=S.length-a.offset;S=S.slice(0,n)}d[o]||(d[o]={});const y=u?.[o],v=y?.feedRound?2:1;S.forEach(((t,e)=>{const n=1+e*v;d[o][n]||(d[o][n]=Wd(t))}))})),{sourceDrawPositionRanges:d}}({drawDefinition:S,matchUpsMap:P,structureId:X}),r=S?function({drawDefinition:t,roundProfile:n,structureId:r,matchUpsMap:i}){if(!t)return{error:j};if(!r)return{error:It};if(!n){const t=_c({matchUpsMap:i,structureId:r});if(({roundProfile:n}=vc({matchUps:t})),!n)return{error:ae}}const a=(Math.min(...n?.[1]?.drawPositions??[])||1)-1,o=Object.keys(n);return{drawPositionsRanges:Object.assign({},...(o||[]).map((t=>{const r=n?.[t]?.matchUpsCount,i=n?.[1]?.drawPositions??[],s=N(i,i.length/r),c=s.map(Wd),u=s.map((t=>t.map((t=>t-a)))).map(Wd),d=o.map((e=>{if(e>t)return;const i=n?.[e]?.drawPositions??[];return N(i,i.length/r)})).filter(Boolean),p=w(0,r).map((t=>d.map((e=>e[t])).flat().filter(Boolean).sort(e))).map((t=>m(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(Wd).join(", ");var e})),f=Object.assign({},...w(0,r).map((t=>({[t+1]:{firstRoundDrawPositionsRange:c[t],firstRoundOffsetDrawPositionsRange:u[t],possibleDrawPositions:p[t],drawPositionsRange:l[t]}}))));return{[t]:f}})))}}({drawDefinition:S,roundProfile:lt,matchUpsMap:P,structureId:X}).drawPositionsRanges:void 0;ct=ct.map((e=>mt({scheduleVisibilityFilters:t,sourceDrawPositionRanges:n,drawPositionsRanges:r,roundNamingProfile:pt,initialRoundOfPlay:ot,appliedPolicies:G,usePublishState:d,publishStatus:y,isRoundRobin:st,roundProfile:lt,matchUp:e,event:E})));const i=ct?.filter((t=>Array.isArray(t.tieMatchUps)));i.forEach((t=>{const e=t.tieMatchUps;ct=ct.concat(...e)})),l&&(ct=rp({processContext:!0,...l,matchUps:ct}))}else{const t=ct?.filter((t=>Array.isArray(t.tieMatchUps)));t.forEach((t=>{const e=t.tieMatchUps;ct=ct.concat(...e)}))}return h&&(ct=rp({matchUps:ct,...h,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(h?.matchUpTypes||h?.matchUpIds)&&(ct=rp({matchUpTypes:h.matchUpTypes,matchUpIds:h.matchUpIds,matchUps:ct})),(h?.matchUpTypes||h?.matchUpIds||A)&&(O=vc({matchUps:ct}).roundMatchUps??[]),$d({drawDefinition:S,structure:D,event:E})?.tieFormat&&({collectionPositionMatchUps:C}=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:ct})),{collectionPositionMatchUps:C,roundMatchUps:O,roundProfile:lt,matchUpsMap:P,matchUps:ct};function mt({scheduleVisibilityFilters:t,sourceDrawPositionRanges:r,drawPositionsRanges:i,initialRoundOfPlay:s,additionalContext:d,roundNamingProfile:l,tieDrawPositions:h,appliedPolicies:y,isCollectionBye:w,usePublishState:T,publishStatus:P,matchUpTieId:N,isRoundRobin:A,roundProfile:E,sideLineUps:C,matchUp:O,event:F}){d=d??{};const k=$d({drawDefinition:S,structure:D,matchUp:O,event:F})?.tieFormat,x=k?.collectionDefinitions,_=O.collectionId&&x?.find((t=>t.collectionId===O.collectionId)),L=O.collectionId?_?.matchUpFormat:O.matchUpFormat??D?.matchUpFormat??S?.matchUpFormat??F?.matchUpFormat,B=O.matchUpType||_?.matchUpType||D?.matchUpType||S?.matchUpType||F?.eventType!==id&&F?.eventType,V=w?Ma:O.matchUpStatus,{schedule:j,endDate:G}=jd({scheduleVisibilityFilters:t,afterRecoveryTimes:o,tournamentRecord:c,usePublishState:T,scheduleTiming:I,matchUpFormat:L,publishStatus:P,matchUpType:B,matchUp:O,event:F}),q=h??O.drawPositions??[],{collectionPosition:$,collectionId:W,roundPosition:H}=O,Y=O.roundNumber??d.roundNumber,J=W?function({tournamentParticipants:t,positionAssignments:e,collectionPosition:n,drawPositions:r=[],participantMap:i,drawDefinition:a,collectionId:o,sideLineUps:s,matchUpType:c}){if(!o||!n)return;const u=r?.map((r=>{const u=e.find((t=>t.drawPosition===r))?.participantId,d=s?.find((t=>t?.drawPosition===r)),p=d?.teamParticipant||u&&i?.[u]?.participant||t?.find((({participantId:t})=>t===u)),l=d?.lineUp||jc({participantId:u,drawDefinition:a})?.lineUp,{assignedParticipantIds:m,substitutions:f}=Bc({collectionPosition:n,collectionId:o,lineUp:l});if(c!==Zs){const t=m?.[0];return t&&{[r]:{participantId:t,teamParticipant:p,substitutions:f}}}if(m?.length<=2){const e=i?.[m[0]]?.pairIdMap?.[m[1]],n=e&&i[e]?.participant||Vc({participantIds:m,tournamentParticipants:t}).participant,a=n?.participantId;return{[r]:{participantId:a,teamParticipant:p,substitutions:f}}}if(m?.length>2)return{[r]:{teamParticipant:p,substitutions:f}}})).filter(Boolean)||{};return Object.assign({},...u)}({tournamentParticipants:a,positionAssignments:z,collectionPosition:$,drawDefinition:S,participantMap:g,drawPositions:q,collectionId:W,sideLineUps:C,matchUpType:B}):void 0,at=l?.[Y]?.roundName||d.roundName,ot=l?.[Y]?.abbreviatedRoundName||d.abbreviatedRoundName,st=E?.[Y]?.feedRound,ct=E?.[Y]?.preFeedRound,ut=E?.[Y]?.roundFactor,dt=i?.[Y],pt=H?dt?.[H]:void 0,lt=r?.[Y],ft=_?.category?{...v?.category||{},..._.category}:v?.category??F?.category,ht=O.processCodes?.length&&O.processCodes||_?.processCodes?.length&&_?.processCodes||D?.processCodes?.length&&D?.processCodes||S?.processCodes?.length&&S?.processCodes||F?.processCodes?.length&&F?.processCodes||c?.processCodes,gt=U?.withCompetitiveness&&Su({...f,matchUp:O}),It=O.finishingPositionRange??d.finishingPositionRange,Ut=t=>vr(t,void 0,!0),St={...Ut(v),...Ut({matchUpFormat:O.matchUpType===id?void 0:L,tieFormat:O.matchUpType!==id?void 0:k,gender:_?.gender??F?.gender,roundOfPlay:tt!==Qa&&p(s)&&s+(Y||0),endDate:O.endDate??G,discipline:F?.discipline,category:ft,finishingPositionRange:It,abbreviatedRoundName:ot,drawPositionsRange:pt,competitiveProfile:gt,structureName:Q,stageSequence:et,drawPositions:q,matchUpStatus:V,processCodes:ht,isRoundRobin:A,matchUpTieId:N,preFeedRound:ct,matchUpType:B,roundFactor:ut,roundOffset:Z,structureId:X,roundNumber:Y,feedRound:st,roundName:at,drawName:rt,drawType:it,schedule:j,drawId:nt,stage:tt}),...gi(Ut(O),!0,!0)};if(L&&O.score?.scoreStringSide1){const t=Jd(L),{bestOf:e,finalSetFormat:n,setFormat:r}=t??{};(n?.tiebreakSet||r?.tiebreakSet||r?.timed)&&(St.score.sets=St.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(q)){const{orderedDrawPositions:t,displayOrder:r}=function({drawPositions:t,roundProfile:r,roundNumber:i}){const a=[void 0,void 0];if(M(t))return{orderedDrawPositions:a,displayOrder:a};const o=r?.[i],s=o?.pairedDrawPositions,c=s?.find((e=>b(e||[],t.filter(Boolean))))??a,u=o?.feedRound;if(R(t)){const n=[...t].sort(e);return{orderedDrawPositions:2===n.length?n:c,displayOrder:u?n:c}}if(u){const e=[t.find((t=>!isNaN(n(t)))),void 0];return{orderedDrawPositions:e,displayOrder:e}}return{orderedDrawPositions:c,displayOrder:c}}({drawPositions:q,roundProfile:E,roundNumber:Y}),i=E?.[Y]?.feedRound,a=r[0]!==t[0],o=t.concat(void 0,void 0).slice(0,2).map(((t,e)=>{const n=e+1,r=jp({drawPositionCollectionAssignment:J,positionAssignments:z,displaySideNumber:a?3-n:n,seedAssignments:u,drawPosition:t,isFeedRound:i,sideNumber:n}),o=O.sides?.find((t=>t.sideNumber===n)),s=H?2*(H-1)+e+1:void 0;return Ut({sourceDrawPositionRange:s?lt?.[s]:void 0,...o,...r})}));Object.assign(St,gi({sides:o},!0,!0))}if(a&&St.sides){const t=y?.[Di],e=e=>{const n=g?.[e]?.participant;return n&&_r({template:t?.participant,source:n})};if(St.sides.filter(Boolean).forEach((t=>{if(t.participantId){const n=gi(e(t.participantId)||a&&Fi({policyDefinitions:y,participantId:t.participantId,tournamentParticipants:a,internalUse:!0,contextProfile:U}),void 0,!0);if(n){if(S?.entries){const e=S.entries.find((e=>e.participantId===t.participantId));e?.entryStatus&&(n.entryStatus=e.entryStatus),e?.entryStage&&(n.entryStage=e.entryStage)}Object.assign(t,{participant:n})}}if(t?.participant?.individualParticipantIds?.length&&!t.participant.individualParticipants?.length){const n=t.participant.individualParticipantIds.map((t=>e(t)||a&&Fi({policyDefinitions:y,tournamentParticipants:a,internalUse:!0,contextProfile:U,participantId:t})));Object.assign(t.participant,{individualParticipants:n})}})),!St.matchUpType){const{matchUpType:t}=Vp({matchUp:St});t&&Object.assign(St,{matchUpType:t})}if(U?.inferGender&&(!St.gender||St.gender===$p)&&2===St.sides?.length&&St.matchUpType!==id){const t=St.sides.map((t=>{if(St.matchUpType===Ks)return t.participant?.person?.sex;if(2===t.participant?.individualParticipants?.length){const e=m(t.participant.individualParticipants.map((t=>t.person?.sex))).filter(Boolean);if(1===e.length)return e[0]}}));if(2===t.filter(Boolean).length&&1===m(t).length){const e=t[0];St.inferredGender=e}}}if(St.tieMatchUps){const e=St.matchUpStatus===Ma,n=St.sides?.map((({participant:t,drawPosition:e,sideNumber:n,lineUp:r})=>{const i=t?.participantType===id&&t;return{teamParticipant:i&&vr({participantRoleResponsibilities:i.participantRoleResponsibilities,participantOtherName:i.participanOthertName,participantName:i.participantName,participantId:i.participantId,teamId:i.teamId}),drawPosition:e,sideNumber:n,lineUp:r}}));St.tieMatchUps=St.tieMatchUps.map((a=>{const o=St.matchUpId,c=St.finishingPositionRange;return mt({tieDrawPositions:q,scheduleVisibilityFilters:t,sourceDrawPositionRanges:r,sideLineUps:n,drawPositionsRanges:i,initialRoundOfPlay:s,roundNamingProfile:l,additionalContext:{finishingPositionRange:c,abbreviatedRoundName:ot,roundNumber:Y,roundName:at},appliedPolicies:y,isCollectionBye:e,usePublishState:T,publishStatus:P,matchUpTieId:o,isRoundRobin:A,roundProfile:E,matchUp:a,event:F})}))}const yt=St.sides&&2===St.sides.filter((t=>t?.participantId)).length,vt=!St.winningSide,wt=K&&yt&&vt;if(Object.assign(St,{readyToScore:wt,hasContext:!0}),yt){const{allParticipantsCheckedIn:t,checkedInParticipantIds:e}=Ku({matchUp:St});Object.assign(St,{allParticipantsCheckedIn:t,checkedInParticipantIds:e})}return Array.isArray(U?.exclude)&&U?.exclude.forEach((t=>delete St[t])),St}}function Kp({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:n,tournamentParticipants:r,afterRecoveryTimes:i,policyDefinitions:a,tournamentRecord:o,usePublishState:s,matchUpFilters:c,contextFilters:u,contextContent:d,participantMap:p,scheduleTiming:l,publishStatus:m,contextProfile:f,drawDefinition:h,exitProfiles:g,matchUpsMap:I,structureId:U,inContext:S,structure:y,context:v,event:w}){!y&&U&&({structure:y}=ts({drawDefinition:h,structureId:U}));const T=Yp({tournamentAppliedPolicies:n,scheduleVisibilityFilters:e,tournamentParticipants:r,afterRecoveryTimes:i,policyDefinitions:a,tournamentRecord:o,usePublishState:s,matchUpFilters:c,contextFilters:u,contextContent:d,participantMap:p,scheduleTiming:l,publishStatus:m,contextProfile:f,drawDefinition:h,exitProfiles:g,matchUpsMap:I,structure:y,inContext:S,context:v,event:w}),P=[],D=[],b=[],N=[],R=[];if(T.error)return T;const{matchUps:M}=T,{assignedPositions:A}=is({structure:y}),E=A?.filter((t=>t.participantId)).map((t=>t.drawPosition));let C;return M.filter((t=>{const e=1===c?.matchUpTypes?.length&&c.matchUpTypes[0]===Qs;return!(t.matchUpType!==Qs&&e)})).forEach((e=>{if(e.matchUpStatus===Na)return void P.push(e);e.matchUpType===Qs&&(C=!0);const n=e.collectionId,r=n&&e.sides?.every((t=>t.participantId)),i=!n&&2===e.drawPositions?.filter(Boolean).length,a=!n&&e.drawPositions?.every((t=>E?.includes(t))),o=A?.filter((t=>t.bye)).map((t=>t.drawPosition)),s=!n&&e.drawPositions?.find((t=>o?.includes(t))),c=Ja.includes(e.matchUpStatus)&&(r||i&&(!t||a));return s?R.push(e):Lc({matchUp:e})?D.push(e):c?b.push(e):N.push(e)})),{includesTeamMatchUps:C,abandonedMatchUps:P,completedMatchUps:D,upcomingMatchUps:b,pendingMatchUps:N,byeMatchUps:R,structure:y}}function Jp(t){Object.assign(t,{requireParticipants:!1});const e=Zp(t);if(e.error)return wr({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 Zp(t){if(!t?.drawDefinition)return{error:j};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:S,inContext:y,context:v,event:w}=t;let T,P=[],D=[],b=[],N=[],R=[];I&&!n&&(n=Fc({policyDefinitions:u,tournamentRecord:d,contextProfile:I,event:w})),!e?.length&&d&&(e=d?.participants,(y||s?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:T}=mc({participants:e,participantsProfile:s})));const{structures:M}=es({drawDefinition:U});if(!M)return{error:Ut};r||(r=xc({drawDefinition:U}));const A=U&&kc({drawDefinition:U}).exitProfiles;M.forEach((t=>{const{byeMatchUps:s=[],pendingMatchUps:T=[],upcomingMatchUps:M=[],completedMatchUps:E=[],abandonedMatchUps:C=[]}=Kp({matchUpFilters:S?void 0:m,contextFilters:S?void 0:l,inContext:y||S||l,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:t,context:v,event:w});P=P.concat(...C),D=D.concat(...E),b=b.concat(...M),N=N.concat(...T),R=R.concat(...s)}));const C=t=>m||S||l?(m&&(t=rp({matchUps:t,...m})),l&&(t=rp({matchUps:t,...l,processContext:!0})),t):t,O={abandonedMatchUps:C(P),completedMatchUps:C(D),upcomingMatchUps:C(b),pendingMatchUps:C(N),byeMatchUps:C(R),matchUpsMap:r,...E,groupInfo:T};if(S){const t="object"==typeof S||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:e,completed:n,upcoming:r,pending:i,bye:a}=t;wc({inContextDrawMatchUps:[].concat(...e&&P||[],...n&&D||[],...r&&b||[],...i&&N||[],...a&&R||[]),drawDefinition:U})}return O}function Xp({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:n,roundsCount:r,roundLimit:i,matchUps:a,lucky:o,fmlc:s}){if(!yc(a))return[];const{roundProfile:c,roundNumbers:u=[]}=vc({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(Ua("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=w(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=Qn({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 Qp({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:n}){if(!e)return{error:j};const r={loserMatchUpIds:{},winnerMatchUpIds:{}};t||({matchUps:t,matchUpsMap:n}=Jp({inContext:!0,drawDefinition:e,matchUpsMap:n}));const i=n?.drawMatchUps.some((t=>t.finishingPositionRange));if(!i&&1===e?.structures?.length&&!e?.structures[0].structures){Xp({matchUps:n?.drawMatchUps??[]})}return(t??[]).filter((({collectionId:t})=>!t)).forEach((i=>{const{matchUpId:a,structureId:o}=i,s=Uc({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:a}),{winnerMatchUp:c,loserMatchUp:u}=s.targetMatchUps,d=c?.matchUpId,p=u?.matchUpId,l=_c({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 tl(t){return t&&void 0!==String.fromCodePoint?t.toUpperCase().replace(/./g,(t=>String.fromCodePoint(t.charCodeAt(0)+127397))):t}const el=[{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 nl({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=el.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 rl(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:Ee}}function il({returnPreviousValues:t,itemSubTypes:e,itemType:n,element:r}){if(!r)return{error:ae,info:Tr};if(e&&!Array.isArray(e))return{error:Nn,context:{itemSubTypes:e}};if(!Array.isArray(r.timeItems))return{error:fn};const i=r.timeItems.filter((t=>t?.itemType===n)).filter((t=>!e?.length||e.some((e=>t?.itemSubTypes?.includes(e))))).sort(((t,e)=>new Date(t.createdAt||void 0).getTime()-new Date(e.createdAt||void 0).getTime())),a=i.pop();if(a){const e={timeItem:a,...E};return t&&Object.assign(e,{previousItems:i}),e}return{info:On}}function al({returnPreviousValues:t,itemSubTypes:e,itemType:n,event:r}){if(!r)return{error:Tt};if(!r.timeItems)return{info:On};const{timeItem:i,previousItems:a,info:o}=il({returnPreviousValues:t,element:r,itemSubTypes:e,itemType:n});return i&&{timeItem:i,previousItems:a}||{info:o}}function ol({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:n,itemType:r}){if(!e)return{error:_};if(!e.timeItems)return{info:On};const{timeItem:i,previousItems:a,info:o}=il({element:e,returnPreviousValues:t,itemSubTypes:n,itemType:r});return i&&{timeItem:i,previousItems:a}||{info:o}}const sl={[cc]:"groupParticipantIds",[uc]:"pairParticipantIds",[dc]:"teamParticipantIds"},cl={[cc]:"groups",[dc]:"teams"};function ul({withIndividualParticipants:t,convertExtensions:e,tournamentRecord:n,withSignInStatus:r,withScaleValues:i,internalUse:a,withISO2:o,withIOC:s}){const c={};for(const t of n.participants??[]){const e=t?.participantId;e&&ll({participantMap:c,participantId:e})}for(const t of n.participants??[]){const n=gi(t,e,a),{participantId:u,individualParticipantIds:d,participantType:p}=n;if(Object.assign(c[u].participant,n),d&&pl({individualParticipantIds:d,participantCopy:n,participantMap:c,participantType:p,participantId:u}),r&&(c[u].participant.signedIn=dl(n)),i){const{ratings:t,rankings:e,seedings:r}=xr({participant:n});c[u].participant.seedings=r,c[u].participant.rankings=e,c[u].participant.ratings=t}(s||o)&&nl({participant:c[u].participant,withISO2:o,withIOC:s})}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?_r({template:e,source:i}):i)}}}}({participantMap:c,template:ha(t)?t:void 0})}return{participantMap:c}}function dl(t){const{timeItem:e}=il({itemType:rc,element:t});return e?.itemValue===ac}function pl({individualParticipantIds:t,participantCopy:e,participantMap:n,participantType:r,participantId:i}){for(const a of t){const o=n[a].participant;if(o[sl[r]].push(i),[dc,cc].includes(r)){const{participantRoleResponsibilities:t,participantOtherName:n,participantName:i,participantId:a,teamId:s}=e;o[cl[r]].push({participantRoleResponsibilities:t,participantOtherName:n,participantName:i,participantId:a,teamId:s})}if(r===uc){const e=t.find((t=>t!==a));n[a].pairIdMap[i]=e,n[a].pairIdMap[e]=i}}}function ll({participantMap:t,participantId:e}){if(t[e])return;const n={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:{[Ks]:{...n},[Zs]:{...n},[dc]:{...n},...n}}}function ml({participantsProfile:t,useParticipantMap:e,tournamentRecord:n,contextProfile:r,inContext:i}){if(e){const e=ul({...t,...r,tournamentRecord:n})?.participantMap;return{participantMap:e}}let a,o=gi(n.participants,!1,!0)||[];if((t?.withIOC||t?.withISO2)&&o.forEach((e=>nl({participant:e,...t}))),(i||t?.withGroupings)&&o?.length&&({participantsWithGroupings:o,groupInfo:a}=mc({participantsProfile:t,deepCopy:!1,participants:o})),t?.withScaleValues&&o?.length)for(const t of o){const{ratings:e,rankings:n}=xr({participant:t});t.rankings=n,t.ratings=e}return{participants:o,groupInfo:a}}function fl(t){let{participants:e=[],contextContent:n,participantMap:r}=t;const{scheduleVisibilityFilters:i,tournamentAppliedPolicies:a,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:d,contextFilters:p,contextProfile:l,matchUpFilters:m,nextMatchUps:f,inContext:h,context:g,event:I}=t;if(!I)return{error:Tt};const{eventId:U,eventName:S,endDate:y,category:v,gender:w,matchUpFormat:T}=I,P={...g,...vr({indoorOutDoor:I.indoorOutdoor??d?.indoorOutdoor,surfaceCategory:I.surfaceCategory??d?.surfaceCategory,endDate:I.endDate??d?.endDate,tournamentId:d?.tournamentId,matchUpFormat:T,eventName:S,category:v,gender:w,eventId:U})};let D;if(y&&(P.endDate=y),l&&!n&&(n=Fc({policyDefinitions:c,tournamentRecord:d,contextProfile:l,event:I})),!e?.length&&!r&&d){const t=ml({participantsProfile:o,useParticipantMap:u,policyDefinitions:c,tournamentRecord:d,contextProfile:l,inContext:h});r=t.participantMap,e=t.participants??[],D=t.groupInfo}const b=I.drawDefinitions??[],N=Qu({tournamentRecord:d,event:I}).scheduleTiming;return{matchUps:b.flatMap((t=>{const{matchUps:u}=Jp({tournamentParticipants:e,tournamentAppliedPolicies:a,scheduleVisibilityFilters:i,context:P,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:d,contextFilters:p,contextProfile:l,drawDefinition:t,contextContent:n,matchUpFilters:m,participantMap:r,scheduleTiming:N,nextMatchUps:f,inContext:h,event:I});return u??[]})),groupInfo:D}}function hl(t){if(!t?.tournamentRecord)return{error:_};let{participantMap:e,participants:n}=t;const{scheduleVisibilityFilters:r,participantsProfile:i,afterRecoveryTimes:a,useParticipantMap:o,policyDefinitions:s,tournamentRecord:c,inContext:u=!0,contextProfile:d,matchUpFilters:p,contextFilters:l,nextMatchUps:m,context:f}=t,h=t.tournamentId??c.tournamentId,g=c?.events??[];n||({participants:n,participantMap:e}=ml({participantsProfile:i,useParticipantMap:o,policyDefinitions:s,tournamentRecord:c,contextProfile:d,inContext:u}));const{appliedPolicies:I}=Dc({tournamentRecord:c}),U={...f,tournamentId:h,indoorOutDoor:c.indoorOutdoor,surfaceCategory:c.surfaceCategory,endDate:c.endDate},S=Fc({policyDefinitions:s,tournamentRecord:c,contextProfile:d});return{matchUps:g.flatMap((t=>(U.eventDrawsCount=t.drawDefinitions?.length??0,fl({context:U,scheduleVisibilityFilters:r,tournamentAppliedPolicies:I,participantsProfile:i,afterRecoveryTimes:a,policyDefinitions:s,tournamentRecord:c,contextContent:S,contextFilters:l,contextProfile:d,matchUpFilters:p,participantMap:e,nextMatchUps:m,participants:n,inContext:u,event:t}).matchUps??[]))).concat(...c.matchUps??[])}}function gl({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:n,tournamentRecords:r,policyDefinitions:i,matchUpFilters:a,contextFilters:o,nextMatchUps:s,inContext:c}){if("object"!=typeof r||!Object.keys(r).length)return{error:x};return{matchUps:Object.keys(r).map((u=>{const d=r[u];return hl({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:n,policyDefinitions:i,tournamentRecord:d,matchUpFilters:a,contextFilters:o,nextMatchUps:s,inContext:c}).matchUps??[]})).flat()}}function Il(t,e){return function(t,e){return(io[t?.stage]||0)-(io[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 Ul(t){let{participants:e,participantMap:n,contextContent:r}=t;const{scheduleVisibilityFilters:i,tournamentAppliedPolicies:a,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:d,contextFilters:p,contextProfile:l,drawDefinition:m,matchUpFilters:f,nextMatchUps:h,inContext:g,context:I,event:U}=t,{eventId:S,eventName:y,eventType:v,category:w,gender:T,matchUpFormat:P}=U??{},D={...I,eventId:S,eventType:v,eventName:y,category:w,gender:T,matchUpFormat:P,indoorOutDoor:U?.indoorOutdoor??d?.indoorOutdoor,surfaceCategory:U?.surfaceCategory??d?.surfaceCategory,endDate:U?.endDate};let b;e?.length||n||!d||({participants:e=[],participantMap:n,groupInfo:b}=ml({participantsProfile:o,useParticipantMap:u,policyDefinitions:c,tournamentRecord:d,contextProfile:l,inContext:g})),l&&!r&&(r=Fc({policyDefinitions:c,tournamentRecord:d,contextProfile:l,drawDefinition:m,event:U}));return{...Jp({context:D,tournamentAppliedPolicies:a,scheduleVisibilityFilters:i,tournamentParticipants:e,participantsProfile:o,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:d,drawDefinition:m,contextContent:r,contextFilters:p,contextProfile:l,matchUpFilters:f,participantMap:n,nextMatchUps:h,inContext:g,event:U}),groupInfo:b}}function Sl(t){let e=nc(t);const n=t.matchUps??[];let r=t.drawIds??[];const{includeParticipantDependencies:i,tournamentRecord:a,drawDefinition:o}=t;if(!Array.isArray(n))return{error:Ht};if(!Array.isArray(r))return{error:at};const s=t.matchUpIds?.length?t.matchUpIds:n.map((t=>t.matchUpId));if(!Array.isArray(s))return{error:$t};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)),[]).filter((({linkType:t})=>t===Uo));let f=n;if(m.length){f=gl({nextMatchUps:!0,tournamentRecords:e}).matchUps;const t=m.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 f??[]){const n=e.containerStructureId||e.structureId;t.includes(n)&&c[n].push(e.matchUpId)}}const h=t=>{u[t]||(u[t]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},p[t]=[])},g=(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)))},I=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(h(t),i){const{individualParticipantIds:e}=ec(n);u[t].participantIds=e}r&&(h(r),g(t,r),p[r].push(t)),a&&(h(a),g(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])h(e),g(e,t),p[e].push(t)}}}};if(o)Qp({drawDefinition:o}),f?.length||(f=Ul({drawDefinition:o}).matchUps),I(f);else{if(f?.length||(f=gl({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=f?.filter((e=>e.drawId===t)).sort(Il),r=n?.find((({roundPosition:t})=>!t));if(!r){const r=n?.find((({tournamentId:t})=>t)),{drawDefinition:i}=Vd({tournamentRecord:e[r?.tournamentId],drawId:t});i&&Qp({drawDefinition:i})}I(n)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:p,matchUps:f,...E}}function yl(t){const{drawDefinition:n,findContainer:r,structureId:i,event:a}=t;let o=t.structure;const{containedStructures:s}=qs({drawDefinition:n}),c=i&&s[i]||[];if(!o){const t=ts({drawDefinition:n,structureId:i});if(t.error)return t;o=r?t.containingStructure??t.structure:t.structure}if(ap({drawDefinition:n,structure:o}))return{structure:o,isAdHoc:!0,error:Q};const{matchUps:u}=Jp({inContext:!0,matchUpFilters:{isCollectionMatchUp:!1},drawDefinition:n,event:a}),d=u?.filter((t=>t.structureId===i||c.includes(t.structureId))),{matchUpDependencies:p}=Sl({drawIds:[n.drawId],matchUps:u,drawDefinition:n}),l=[],f=[],h={},g=[];for(const t of u??[]){if(t.structureId===i||c.includes(t.structureId)){f.push(...t.drawPositions??[]);const e=t.roundNumber;for(const n of(t.drawPositions??[]).filter(Boolean))(!h[n]||e&&h[n]>e)&&(h[n]=e)}zs(t)&&(g.push(t),l.push(t.matchUpId,...p?.[t?.matchUpId]?.matchUpIds||[]))}const I=m(f.filter(Boolean)).sort(e),U=m(l),S=m(d?.map((({matchUpId:t,drawPositions:e})=>U.includes(t)?e:[])).flat().filter(Boolean)).sort(e),{positionAssignments:y}=rs({drawDefinition:n,structure:o}),v=y?.filter((t=>t.bye)).map((t=>t.drawPosition)),w=y?.filter((t=>t.qualifier)).map((t=>t.drawPosition)),T=I?.filter((t=>!S.includes(t)))||[];return{allDrawPositions:I,inContextStructureMatchUps:d,drawPositionInitialRounds:h,activeDependentMatchUpIds:U,qualifyingDrawPositions:w,inactiveDrawPositions:T,positionAssignments:y,activeDrawPositions:S,byeDrawPositions:v,activeMatchUps:g,structure:o}}function vl({drawPosition:t,matchUps:n=[]}){return{initialRoundNumber:n.filter((({drawPositions:e})=>t&&e?.includes(t))).map((({roundNumber:t})=>t)).sort(e)[0]}}const wl={reset:"",bright:"",dim:"",red:"",brightred:"",green:"",brightgreen:"",yellow:"",brightyellow:"",blue:"",brightblue:"",lightblue:"",magenta:"",brightmagenta:"",cyan:"",brightcyan:"",white:"",brightwhite:""},Tl=[];function Pl(t,e){"string"==typeof t&&(t={method:t}),(e||Qn())&&Tl.push(t)}function Dl(t){const e=function(t){const e=Tl.slice();return t&&(Tl.length=0),e}(t),n=e.map((t=>{const{color:e,keyColors:n,method:r,newline:i}=t,a=Object.keys(wl).includes(e)?wl[e]:wl.cyan,o=Object.keys(t).filter((t=>!["color","keyColors","method","newline"].includes(t))).map((e=>{const r=n&&Object.keys(n).includes(e)&&wl[n[e]]?wl[n[e]]:wl.brightwhite;return`${wl.white}${e}: ${r}${t[e]}`})).join(", ");return[i?"\n":"",a,r,r?.length<15?"\t\t":"\t",wl.white,o,wl.reset,"\n"].join("")}));n?.length&&console.log(...n)}function bl({provisionalPositioning:t,isPositionAction:e,tournamentRecord:n,drawDefinition:r,drawPosition:i,matchUpsMap:a,structureId:o,structure:s,event:c}){if(!r)return{error:j};if(s||({structure:s}=ts({drawDefinition:r,structureId:o})),!s)return{error:Ut};o||({structureId:o}=s);const u="assignDrawPositionBye";Pl({method:u,color:"cyan",drawPosition:i}),a||(a=xc({drawDefinition:r}));const{positionAssignments:d}=rs({structure:s}),{activeDrawPositions:p}=yl({drawDefinition:r,structureId:o}),l=d?.find((t=>t.drawPosition===i));if(l?.bye)return{...E};const m=p?.includes(i);if(m)return{error:X};const f=d?.find((t=>t.drawPosition===i));if(!f)return{error:Q};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{...E};if(h&&!g)return wr({result:{error:z},stack:u});const U=Jp({inContext:!0,drawDefinition:r,matchUpsMap:a}).matchUps??[],{matchUps:S}=Yp({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)&&Rl({eventId:i?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:r})}))}({tournamentRecord:n,drawDefinition:r,drawPosition:i,matchUps:S}),Vs({tournamentId:n?.tournamentId,drawDefinition:r,structure:s,event:c}),Nl({assignedParticipantId:I,isPositionAction:e,drawDefinition:r,drawPosition:i,structureId:o,stack:u});const{roundProfile:y,roundMatchUps:v}=vc({matchUps:S}),w=y&&Object.keys(y).map((t=>parseInt(t))).reverse(),T=w?.find((t=>y?.[t].drawPositions?.includes(i))),P=T?v?.[T].find((({drawPositions:t})=>t?.includes(i))):void 0;P&&Rl({tournamentRecord:n,drawDefinition:r,matchUp:P,event:c});const D=P?.drawPositions?.find((t=>t!==i));if(P&&D){const t=Ml({sourceDrawPositions:P.drawPositions,matchUpId:P.matchUpId,inContextDrawMatchUps:U,drawPositionToAdvance:D,tournamentRecord:n,drawDefinition:r,matchUpsMap:a});if(t.error)return t}return Vs({tournamentId:n?.tournamentId,drawDefinition:r,structure:s,event:c}),Nl({assignedParticipantId:I,isPositionAction:e,drawDefinition:r,drawPosition:i,structureId:o,stack:u})}function Nl({assignedParticipantId:t,isPositionAction:e,drawDefinition:n,drawPosition:r,structureId:i,stack:a}){if(e){Gs({drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:r,structureId:i,name:a}})}return wr({result:{...E},stack:a})}function Rl({tournamentRecord:t,drawDefinition:e,eventId:n,matchUp:r,event:i}){Object.assign(r,{matchUpStatus:Ma,score:void 0,winningSide:void 0}),xs({tournamentId:t?.tournamentId,eventId:n??i?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:r})}function Ml({drawPositionToAdvance:t,inContextDrawMatchUps:n,sourceDrawPositions:r,tournamentRecord:i,drawDefinition:a,matchUpsMap:o,matchUpId:s,event:c}){Pl({method:"advanceDrawPosition",color:"cyan",drawPositionToAdvance:t});const u=o.drawMatchUps.find((t=>t.matchUpId===s)),d=n.find((t=>t.matchUpId===s)),p=d?.structureId,{structure:l}=ts({drawDefinition:a,structureId:p}),{positionAssignments:m}=rs({structure:l}),f=m?.filter((t=>t.bye)).map((t=>t.drawPosition)),h=u?.drawPositions?.find((e=>e!==t)),g=h&&f?.includes(h),{targetLinks:{loserTargetLink:I},targetMatchUps:{loserMatchUp:U,winnerMatchUp:S,loserTargetDrawPosition:y}}=Uc({inContextDrawMatchUps:n,drawDefinition:a,matchUpId:s});if(S&&S.structureId===l?.structureId&&function({drawPositionToAdvance:t,inContextDrawMatchUps:n,sourceDrawPositions:r,tournamentRecord:i,drawDefinition:a,winnerMatchUp:o,matchUpsMap:s,event:c}){const u="advanceWinner",d=s.drawMatchUps.find((t=>t.matchUpId===o.matchUpId)),p=n.find((t=>t.matchUpId===o.matchUpId)),l=p?.structureId,{structure:m}=ts({drawDefinition:a,structureId:l}),{positionAssignments:f}=rs({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))),S=f?.find((({drawPosition:e})=>e===t)),y=r?.find((e=>e!==t)),v=y&&U?.find((({drawPosition:t})=>t===y)),w=v?.bye,T=g&&w;T&&console.log({isByeAdvancedBye:T});if(I?.length>1&&g&&!w)return wr({result:{error:z},stack:u});const P=I?.find((e=>e!==t));let D=T;const b=[...(d.drawPositions||[]).filter(Boolean),void 0,void 0].slice(0,2),N=b.map((e=>!e&&!D||e===t?(D=!0,t):e)).sort(e);if(!D)return console.log("@@@@@@@",{advancingAssignmentIsBye:S,drawPositionToAdvance:t,existingAssignments:U}),wr({result:{error:z},stack:u});const R=f?.find((({drawPosition:t})=>t===P))?.bye,M=f?.find((({drawPosition:e})=>e===t))?.bye,A=M||R?Ma:ja;Object.assign(d,{matchUpStatus:A,score:void 0,winningSide:void 0,drawPositions:N});const E=d.drawPositions.find((t=>!b.includes(t)));Pl({method:u,color:"brightyellow",changedDrawPosition:E,pairedDrawPositionIsBye:R,drawPositionIsBye:M}),xs({tournamentId:i?.tournamentId,matchUp:d,eventId:c?.eventId,context:u,drawDefinition:a});const{targetLinks:{loserTargetLink:C},targetMatchUps:{loserMatchUp:O,loserTargetDrawPosition:F}}=Uc({matchUpId:o.matchUpId,inContextDrawMatchUps:n,drawDefinition:a});if(R||M){const e=R?t:P;if(e)Ml({drawPositionToAdvance:e,matchUpId:o.matchUpId,inContextDrawMatchUps:n,tournamentRecord:i,drawDefinition:a,matchUpsMap:s});else if(M&&C&&O)if(O.feedRound)Al({loserTargetDrawPosition:F,tournamentRecord:i,loserTargetLink:C,drawDefinition:a,loserMatchUp:O,matchUpsMap:s});else{const t=1-o.roundPosition%2,e=O.drawPositions[t],n=bl({structureId:C.target.structureId,drawPosition:e,tournamentRecord:i,drawDefinition:a,event:c});if(n.error);}}}({drawPositionToAdvance:t,inContextDrawMatchUps:n,sourceDrawPositions:r,tournamentRecord:i,drawDefinition:a,winnerMatchUp:S,matchUpsMap:o,event:c}),U&&g&&U.structureId!==l?.structureId){const{roundNumber:t}=U;if(1===t){const t=bl({structureId:I.target.structureId,drawPosition:y,tournamentRecord:i,drawDefinition:a,event:c});if(t.error)return t}else Al({loserTargetDrawPosition:y,tournamentRecord:i,loserTargetLink:I,drawDefinition:a,loserMatchUp:U,matchUpsMap:o,event:c})}return{...E}}function Al({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:n,drawDefinition:r,loserMatchUp:i,matchUpsMap:a,event:o}){const{roundNumber:s}=i;Pl({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});const c=(a?.mappedMatchUps||{})[i.structureId].matchUps,{initialRoundNumber:u}=vl({drawPosition:t,matchUps:c});if(u===s){const i=bl({structureId:n.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:r,event:o});if(i.error)return i}}function El({positionAssignments:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:r,structure:i,event:a}){const{matchUps:o}=Yp({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?Ma:ja;Object.assign(r,{matchUpStatus:t}),xs({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:a?.eventId,drawDefinition:n,matchUp:r})}}))}function Cl(t){let{inContextDrawMatchUps:e,participantId:n,drawPosition:r}=t;const{tournamentRecord:i,drawDefinition:a,structureId:o,matchUpsMap:s,event:c}=t,{structure:u}=ts({drawDefinition:a,structureId:o}),d=(is({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:tt};n||(n=d?.participantId);const{activeDrawPositions:p}=yl({drawDefinition:a,structureId:o});if(p.includes(r))return{error:X};e||({matchUps:e}=Jp({inContext:!0,drawDefinition:a,matchUpsMap:s}));return Ol({inContextDrawMatchUps:e,tournamentRecord:i,drawDefinition:a,structureId:o,drawPosition:r,matchUpsMap:s,event:c}).drawPositionCleared?(Vs({tournamentId:i?.tournamentId,drawDefinition:a,structure:u,event:c}),{...E,participantId:n}):{error:K}}function Ol({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:i,matchUpsMap:a,structureId:o,event:s}){const{structure:c}=ts({drawDefinition:r,structureId:o});if(!c)return{error:Ut};const u=is({drawDefinition:r,structure:c}).positionAssignments||[],d=u.some((t=>{if(t.drawPosition===i)return delete t.participantId,delete t.qualifier,delete t.bye,!0}));if(c.structureType===mo)return El({positionAssignments:u,tournamentRecord:e,drawDefinition:r,matchUpsMap:a,structure:c}),{drawPositionCleared:d,...E};const{matchUps:p}=Yp({drawDefinition:r,matchUpFilters:{isCollectionMatchUp:!1},matchUpsMap:a,structure:c,event:s}),{roundProfile:l,roundMatchUps:m}=vc({matchUps:p}),f=l&&Object.keys(l),h=f?.map((t=>n(t)));let g=i;const I=h?.map((t=>{const e=l?.[t],n=e?.pairedDrawPositions?.find((t=>t.includes(g))),r=n?.find((t=>t!==g)),i=u.find((t=>t.drawPosition===r)),a=l?.[t+1],o=i?.bye,s=a?.pairedDrawPositions?.find((t=>t.includes(r))),c=o&&s&&a&&a.drawPositions?.includes(r),d=n&&{pairedDrawPositionByeAdvancedPair:!c&&s,pairedDrawPosition:r,targetDrawPosition:g,relevantPair:n,roundNumber:t};return c&&(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:n,targetDrawPosition:d,relevantPair:p})=>{const l=m?.[n].find((t=>b(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}=ts({drawDefinition:r,structureId:o});if(!s)return{error:Ut};if(s.structureType===mo)return;i=i||xc({drawDefinition:r});const c=i?.mappedMatchUps||{},u=c[o].matchUps,{initialRoundNumber:d}=vl({drawPosition:e,matchUps:u}),p=u?.filter((t=>t.roundNumber>=a&&t.roundNumber!==d&&t.drawPositions?.includes(e))),l=rs({drawDefinition:r,structureId:o}).positionAssignments??[];p?.forEach((a=>Fl({drawPosition:e,targetMatchUp:a,inContextDrawMatchUps:t,positionAssignments:l,tournamentRecord:n,drawDefinition:r,matchUpsMap:i,structure:s})))}({inContextDrawMatchUps:t,targetDrawPosition:d,tournamentRecord:e,drawDefinition:r,structureId:o,roundNumber:n,matchUpsMap:a}),Fl({inContextDrawMatchUps:t,positionAssignments:u,tournamentRecord:e,drawDefinition:r,targetMatchUp:l,drawPosition:i,matchUpsMap:a,structure:c,event:s}))})),{tasks:U,drawPositionCleared:d,positionAssignments:u}}function Fl({inContextDrawMatchUps:t,positionAssignments:e,tournamentRecord:n,drawDefinition:r,targetMatchUp:i,drawPosition:a,matchUpsMap:o,structure:s,event:c}){const u="removeDrawPosition",d=i.drawPositions?.slice(),p=i.matchUpStatus,l=i.winningSide,m=(o=o??xc({drawDefinition:r})).mappedMatchUps[s.structureId].matchUps,{initialRoundNumber:f}=vl({drawPosition:a,matchUps:m});if(i.roundNumber&&f&&i.roundNumber>f){const t=(i.drawPositions??[]).map((t=>t===a?void 0:t));i.drawPositions=t}if(i.matchUpType===Qs){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,xs({tournamentId:n?.tournamentId,context:`${u}-TEAM`,eventId:c?.eventId,matchUp:i,drawDefinition:r}))}const h=Uc({matchUpId:i.matchUpId,inContextDrawMatchUps:t,drawDefinition:r}),{targetLinks:{winnerTargetLink:g},targetMatchUps:{loserMatchUp:I,winnerMatchUp:U,loserMatchUpDrawPositionIndex:S}}=h,y=e.filter((({drawPosition:t})=>i.drawPositions?.includes(t))).filter((t=>t.bye)).length,v=y&&Ma||i.matchUpStatus&&[Oa,Ga].includes(i.matchUpStatus)&&i.matcHUpStatus||2===i.drawPositions?.length&&ja||void 0;i.matchUpStatus=v,i.matchUpStatus&&[Ga,Oa].includes(i.matchUpStatus)&&(i.winningSide=void 0);const w=d?.find((t=>!i.drawPositions?.includes(t)));if(d?.includes(a)&&p===i.matchUpStatus&&l===i.winningSide||(w&&Pl({method:u,color:"brightyellow",removedDrawPosition:w}),xs({tournamentId:n?.tournamentId,eventId:c?.eventId,matchUp:i,context:`${u}-${a}`,drawDefinition:r})),I&&I.structureId!==h.matchUp.structureId&&!y){const{drawPositions:e,roundNumber:i}=I;if(1===i){const i=e[S];Ol({structureId:I.structureId,drawPosition:i,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:r,matchUpsMap:o})}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}=ts({structureId:i.structureId,drawDefinition:r}),{positionAssignments:c}=rs({structure:s}),u=c?.find((e=>e.drawPosition===t));if(u?.bye){const s=Cl({drawPosition:t,structureId:i.structureId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,matchUpsMap:a,event:o});if(s.error)return s}return{...E}}({loserMatchUpDrawPosition:i,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:r,loserMatchUp:I,matchUpsMap:o,event:c});if(a.error)return wr({result:a,stack:u});const s=(o?.mappedMatchUps||{})[I.structureId].matchUps,{initialRoundNumber:d}=vl({drawPosition:i,matchUps:s});1===d&&(Pl({method:u,color:"brightyellow",loserMatchUpDrawPosition:i}),Ol({structureId:I.structureId,drawPosition:i,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:r,matchUpsMap:o}))}}return U&&U.structureId!==h.matchUp.structureId&&g.target.feedProfile,{...E}}function kl({drawDefinition:t,stages:e}){if(!t)return{error:j};const n=m((t?.structures??[]).filter((t=>!e?.length||t.stage&&e.includes(t.stage))).map((t=>{const{positionAssignments:e}=rs({structure:t});return e?e.map(Ua("participantId")):[]})).flat().filter(Boolean));return{...E,assignedParticipantIds:n}}function xl(t){const e=(t?.entries??[]).filter(Boolean).reduce(((t,e)=>{const{entryStage:n,entryStatus:r}=e,i=`_${n||Xa}${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 _l(t){return[tu,Qc].includes(t)}function Ll({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:Te,method:"modifyEntriesStatus",participantIds:i};if(!r&&!p)return{error:Tt};if(a&&!su.includes(a))return{error:je};if(o&&!ro.includes(o))return{error:At};const l="modifyEntriesStatus",m=[];if(!a&&!s)return wr({result:{error:ae},info:"Missing entryStatus",stack:l});if(s&&!br({extension:s,requiredAttributes:["name"]}))return wr({result:{error:Nn},info:"Invalid extension",context:{extension:s},stack:l});const f=[];p?.drawDefinitions?.forEach((t=>{const e=kl({stages:d&&[d],drawDefinition:t}).assignedParticipantIds??[];f.push(...e)}));const h=n?.participants??[];if(!i.every((t=>{const e=Fi({tournamentParticipants:h,participantId:t})?.participantType;return!(e&&[uc,oc].includes(e)&&_l(a)||a&&p?.eventType&&e===sc&&[nd,ad].includes(p.eventType)&&[$c,...ru].includes(a))})))return{error:je};const g=p&&Bd({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)&&!(ru.includes(t.entryStatus)&&ru.includes(a)))(t)&&!e)&&(a&&(t.entryStatus=a,delete t.entryPosition),o&&(t.entryStage=o,delete t.entryPosition),s&&(s.value?Nr({element:t,extension:s}):Dr({element:t,name:s.name})),!0)))?{...E}:{error:Le}},S=({flight:t,drawDefinition:e})=>{p&&(p.entries=xl({entries:p.entries??[]})),t&&(t.drawEntries=xl({entries:t.drawEntries})),e&&(e.entries=xl({entries:e.entries}))},y=t=>{const{flight:e,drawDefinition:n}=t,r="updateDrawEntries";if(e){const t=U(e.drawEntries);if(t.error)return wr({result:t,stack:r})}if(n){const t=U(n.entries);if(t.error)return wr({result:t,stack:r});m.includes(n.drawId)||m.push(n.drawId)}return{...E}},v=p?.entries?.find((({entryPosition:t})=>t))??(I?.drawEntries?.find((({entryPosition:t})=>t))||r?.entries?.find((({entryPosition:t})=>t)));if(t&&!v&&S({flight:I,drawDefinition:r}),I||r){const t=y({flight:I,drawDefinition:r});if(t.error)return wr({result:t,stack:l})}const w=p?.drawDefinitions?.map((({drawId:t})=>t))??[],T=g?.flights?.filter((t=>!w.includes(t.drawId)))||[];for(const t of T){const e=t&&y({flight:t});if(e?.error)return wr({result:e,stack:l})}const P=1===g?.flights?.length&&(p?.drawDefinitions?.length??0)<=g?.flights?.length;if(!I&&!r&&a&&iu.includes(a))return{error:He};if(!I&&!r||a===nu||c&&P){const t=U(p?.entries);if(t?.error)return wr({result:t,stack:l});let e;if(a===nu&&(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 wr({result:{error:e},stack:l})}t&&S({flight:I,drawDefinition:r});for(const t of p?.drawDefinitions??[])m.length&&!m.includes(t.drawId)||Ls({tournamentId:n.tournamentId,eventId:p?.eventId,drawDefinition:t});return{...E}}function Bl(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===Ma||e[n].scheduleItems.push({...d,scheduledDate:ri(d?.scheduledDate),scheduledTime:ni(d?.scheduledTime),checkScoreHasValue:$s({score:l}),matchUpStatus:r,roundPosition:i,structureId:a,matchUpType:o,roundNumber:s,matchUpId:c,potential:u,drawId:p})}function Vl({requireTimeStamp:t,scaleAttributes:e,participant:n}){if(!n)return{error:Re};if(!ha(e))return{error:Nn};if(n.timeItems||(n.timeItems=[]),Array.isArray(n.timeItems)){const{accessor:r,scaleType:i,eventType:a,scaleName:o}=e,s=[Or,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))).pop();if(c){const[t,e,n,i]=c.itemType?.split(".")??[];if(t!==Or)return{error:In};const a=r&&la({element:c.itemValue,accessor:r}),o=a?.value||c.itemValue,s={eventType:n,scaleDate:c.itemDate,scaleValue:o,scaleName:i,scaleType:e};return{...E,scaleItem:s}}}return{...E,scaleItem:void 0}}function jl({publishedSeeding:t,usePublishState:e,withSeeding:n,participant:r,event:i}){const a={},o=t=>[Or,Fr,i.eventType,t].join("."),s=Object.assign({},...(r.timeItems||[]).filter((({itemType:t})=>t.split(".")[1]===Fr)).map((({itemType:t,itemValue:e})=>({[t]:e})))),c=(t?.stageSeedingScaleNames&&Object.values(t?.stageSeedingScaleNames)||Array.isArray(t?.seedingScaleNames)&&t.seedingScaleNames||[]).map(o),u=P(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=Vl({scaleAttributes:{eventType:i.eventType,scaleType:Fr,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 Gl({event:t,status:e=Hu}){const n=`${Wu}.${zu}`;return al({itemType:n,event:t})?.timeItem?.itemValue?.[e]}function ql({drawDetails:t,drawId:e}){const n=t?.[e]?.publishingDetail;return n?.published}function $l({event:t}){const e=Gl({event:t});if(e){const t={published:void 0,seedingScaleNames:[],drawIds:[]};e.seeding&&Object.assign(t,e.seeding);const{drawDetails:n,drawIds:r}=e;return{publishedDrawIds:n&&Object.keys(n).filter((t=>ql({drawDetails:n,drawId:t})))||r||[],publishedSeeding:t}}}function Wl({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({},...Ii(p)):{},m=Object.assign(l,{entryPosition:d,entryStatus:c,entryStage:u,ranking:o,eventId:a});n.events[a]=vr(m,!1,!1,!0),r&&(e&&(n.events[a].seedAssignments=e),i&&(n.events[a].seedValue=i))}function Hl(t,e){return(t||"").localeCompare(e||"")}function zl({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===Ga&&(f.walkoverWinCount+=1),i===Oa&&(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 Yl(t){const{withScheduleItems:e,scheduleAnalysis:n,withTeamMatchUps:r,participantMap:i,withOpponents:a,withMatchUps:o,withEvents:s,withDraws:c,finishingPositionRange:u,finishingRound:d,matchUpStatus:p,stageSequence:l,roundNumber:m,structureId:f,score:h,stage:g,withRankingProfile:I,tieWinningSide:U,roundPosition:S,matchUpTieId:y,matchUpSides:v,collectionId:w,matchUpType:T,winningSide:P,matchUpId:D,schedule:b,eventId:N,drawId:R,sides:M}=t,A=a&&2===M?.length&&Object.assign({},...M.map((({sideNumber:t},e)=>{const n=M[1-e].participantId;return t&&{[t]:n}})).filter(Boolean));for(const t of M){const{participantId:M,sideNumber:E,bye:C}=t;if(C)continue;const O=P===E,F=t=>{const e=i[t]?.participant,n=e?.participantType,r=[{participantId:t,participantType:n}];if(n!==oc)for(const t of e?.individualParticipantIds||[]){const e=i[t]?.participant;r.push({participantType:e?.participantType,participantId:t})}return r},k=(t,r)=>{if(o){if(i[t].matchUps[D]={participantWon:O,matchUpType:T,structureId:f,sideNumber:E,matchUpId:D,eventId:N,drawId:R,stage:g},a){const e=F(r);i[t].matchUps[D].opponentParticipantInfo=e}w&&(i[t].matchUps[D].collectionId=w)}a&&r&&(i[t].opponents[r]={participantId:r,matchUpId:D,eventId:N,drawId:R}),I&&zl({finishingPositionRange:u,participantMap:i,participantWon:O,finishingRound:d,matchUpStatus:p,participantId:t,stageSequence:l,roundNumber:m,structureId:f,matchUpId:D,drawId:R,stage:g}),(n||e)&&Bl({participantMap:i,participantId:t,matchUpStatus:p,roundPosition:S,matchUpType:T,roundNumber:m,structureId:f,matchUpId:D,schedule:b,drawId:R,score:h})},x=({participant:t,partnerParticipantId:e})=>{const n=(t,e)=>{t&&(t.partnerParticipantIds||(t.partnerParticipantIds=[]),t.partnerParticipantIds.includes(e)||t.partnerParticipantIds.push(e))};c&&n(t?.draws?.[R],e),s&&n(t?.events?.[N],e),o&&n(t?.matchUps?.[D],e)};if(M&&i[M]){const t=A?.[E];k(M,t);const e=i[M]?.participant.participantType===uc,n=i[M]?.participant.individualParticipantIds||[];if(y){if(r){const t=t=>i[t].matchUps[y]={participantWon:U===E,matchUpId:y,matchUpType:Qs,sideNumber:E};t(M),n.forEach(t)}if(c&&!i[M].draws[R]){const t=v.find((t=>t.sideNumber===E))?.participant?.participantId,e=i[t]?.draws?.[R]?.entryStatus,r=t=>i[t].draws[R]={entryStatus:e,eventId:N,drawId:R};r(M),n.forEach(r)}}if(e&&(n.forEach((e=>i[e]&&k(e,t))),n.forEach(((t,e)=>{const r=n[1-e],a=i[t];a&&x({participant:a,partnerParticipantId:r})})),s&&v)){const t=v.find((t=>t.sideNumber===E))?.participant?.participantId;if(t){const e=i[t]?.events[N];e?(i[M].events[N]={...e},n.forEach((t=>i[t].events[N]={...e}))):console.log("Missing teamEntry",{eventId:N,teamParticipantId:t})}}if(P){const t=t=>{O?(i[t].counters[T].wins+=1,i[t].counters.wins+=1,p===Ga&&(i[t].counters[T].walkoverWins+=1,i[t].counters.walkoverWins+=1),p===Oa&&(i[t].counters[T].defaultWins+=1,i[t].counters.defaultWins+=1)):(i[t].counters[T].losses+=1,i[t].counters.losses+=1,p===Ga&&(i[t].counters[T].walkovers+=1,i[t].counters.walkovers+=1),p===Oa&&(i[t].counters[T].defaults+=1,i[t].counters.defaults+=1))};t(M),n.forEach(t)}}}}function Kl({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:f,genders:h}=t,g=Jl(f)&&e?.events?.filter((t=>f?.includes(t.eventId)))||e?.events||[],I=i&&function({drawEntryStatuses:t,tournamentEvents:e}){const n=({entryStatus:e})=>!Array.isArray(t)||t.includes(e);return m(e.reduce(((t,e)=>{const{flightProfile:r}=Bd({event:e}),i=r?.flights?.map((({drawEntries:t})=>Array.isArray(t)?t.filter(n).map(Da):[])).flat()||[],a=e.drawDefinitions?.map((({entries:t})=>t?t.filter(n).map(Da):[]))||[];return t.concat(...i,...a)}),[]))}({drawEntryStatuses:i,tournamentEvents:g}),U=o&&function({eventEntryStatuses:t,tournamentEvents:e}){return m(e.reduce(((e,n)=>{const r=(n.entries||[]).filter((({entryStatus:e})=>!Array.isArray(t)||t.includes(e))).map(Da);return e.concat(...r)}),[]))}({eventEntryStatuses:o,tournamentEvents:g}),S=void 0!==a&&[!0,!1].includes(a)&&g.reduce(((t,e)=>t.concat(...(e.drawDefinitions||[]).map((t=>ns({drawDefinition:t}).allPositionedParticipantIds)).filter(Boolean))),[]),y=t=>r?.reduce(((e,n)=>{const{accessor:r,value:i}=n,{values:a}=la({element:t,accessor:r});return e&&a?.includes(i)}),!0);if(n=n?.filter((t=>{const e=il({element:t,itemType:rc})?.timeItem?.itemValue,{participantRoleResponsibilities:n,participantType:i,participantRole:o,participantId:m,person:f}=t,g=Array.isArray(h)&&h?.length&&f?.sex&&h.includes(f.sex);return l?h&&g||a&&S.includes(m)||!1===a&&!S.includes(m)||I?.includes(m)||U?.includes(m)||d?.includes(m)||p&&e===p||u&&i&&Jl(u)&&u.includes(i)||s&&o&&Jl(s)&&s.includes(o)||c&&Jl(n)&&Jl(c)&&c.find((t=>n?.includes(t)))||r?.length&&Jl(r)&&y(t):(!h||g)&&(void 0===a||a&&S.includes(m)||!1===a&&!S.includes(m))&&(!I||I.includes(m))&&(!U||U.includes(m))&&(!d||d.includes(m))&&(!p||e===p)&&(!u||i&&Jl(u)&&u.includes(i))&&(!s||o&&Jl(s)&&s.includes(o))&&(!c||Jl(n)&&Jl(c)&&c.find((t=>n?.includes(t))))&&(!r?.length||Jl(r)&&y(t))})),g.length&&f){const t=g.filter((t=>f.includes(t.eventId))).map((t=>{const n=(t.entries||[]).map((t=>t.participantId));if(t.eventType===td)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 Jl(t){return t&&Array.isArray(t)&&t.length}function Zl(t){const{withIndividualParticipants:e,participantFilters:n={},withPotentialMatchUps:r,withRankingProfile:i,convertExtensions:a,policyDefinitions:o,withScheduleItems:s,tournamentRecord:c,scheduleAnalysis:u,withSignInStatus:d,withTeamMatchUps:p,withScaleValues:l,usePublishState:f,contextProfile:h,withStatistics:g,withOpponents:I,withMatchUps:U,internalUse:S,withSeeding:y,withEvents:v,withDraws:w,withISO2:T,withIOC:P}=t;if(!c)return{error:_};(U||i)&&Sl({tournamentRecord:c});let{participantMap:D}=ul({convertExtensions:a,tournamentRecord:c,withSignInStatus:d,withScaleValues:l,internalUse:S,withISO2:T,withIOC:P});const b=function(t){const{participantFilters:e,convertExtensions:n,policyDefinitions:r,tournamentRecord:i,usePublishState:a,contextProfile:o,participantMap:s,withPotentialMatchUps:c,withRankingProfile:u,withScheduleItems:d,scheduleAnalysis:p,withTeamMatchUps:l,withStatistics:f,withOpponents:h,withMatchUps:g,withSeeding:I,withEvents:U,withDraws:S}=t,y=e?.participantIds,v=t=>{const e=[t];return s[t]?.participant.individualParticipantIds?.forEach((t=>e.push(t))),e.some((t=>!y?.length||y.includes(t)))?e:[]},w={withMatchUps:g||u,withEvents:U||u,withDraws:S||u,withPotentialMatchUps:c,withRankingProfile:u,withScheduleItems:d,scheduleAnalysis:p,withTeamMatchUps:l,withStatistics:f,participantMap:s,withOpponents:h,withSeeding:I},T=[],P={},D=[],b={},N={},R={},M=({eventType:t,scaleNames:e,participantId:n})=>s[n].participant?.rankings?.[t]?.find((t=>e.includes(t.scaleName)))?.scaleValue;for(const t of i?.events||[]){if(e?.eventIds&&!e.eventIds.includes(t.eventId))continue;const{drawDefinitions:y=[],extensions:T=[],eventType:A,eventName:E,category:C,entries:O,eventId:F,gender:k}=t,{flightProfile:x}=Bd({event:t}),_=x?.flights??[],L=$l({event:t}),B=L?.publishedSeeding;if(L&&(b[F]=L),U||I||u){const e=n?Object.assign({},...Ii(T)):{};N[F]={...e,eventName:E,eventType:A,category:C,eventId:F,gender:k};const r=[C?.categoryName,C?.ageCategoryCode].filter(Boolean);for(const e of O){const{participantId:i}=e;if(!i||!s[i])continue;const o=M({eventType:A,scaleNames:r,participantId:i});let c,u;if(I){const e=s[i].participant;({seedAssignments:c,seedValue:u}=jl({publishedSeeding:B,usePublishState:a,withSeeding:I,participant:e,event:t}))}const d=t=>{if(s[t]?.events?.[F])return;const r=s[t];Wl({convertExtensions:n,seedAssignments:c,participant:r,withSeeding:I,seedValue:u,eventId:F,ranking:o,entry:e})};d(i),(s[i].participant.individualParticipantIds||[]).forEach(d)}}const V=b?.[F]?.publishedSeeding;if(S||u||I){const t=t=>t?Object.assign({},...t.map((({participantId:t,seedValue:e,seedNumber:n})=>({[t]:{seedValue:e,seedNumber:n}})))):void 0,e=m([...y.map(Ua("drawId")),..._.map(Ua("drawId"))]);for(const n of e){const e=y.find((t=>t.drawId===n)),r=_?.find((t=>t.drawId===n)),i=e?.entries||r?.drawEntries,{structures:o=[],drawOrder:c,drawName:d,drawType:p}=e??{},l=r?.flightNumber,m=[C?.categoryName,C?.ageCategoryCode].filter(Boolean),f=(e?.structures||[]).sort(((t,e)=>Xo(t,e))).map((({structureId:t,structures:e})=>[t,...(e||[]).map((({structureId:t})=>t))])).flat(1/0);let h,g,U,v,w=0;const T=o.filter((({stage:t,stageSequence:e})=>t===Xa&&1===e||t===Qa)).flatMap((t=>{const{seedAssignments:e,stageSequence:n,stage:r}=t,{positionAssignments:i}=rs({structure:t});return r===Xa?(w=i?.length??0,U=i,v=e):1===n&&(h=i,g=e),i})).map((({participantId:t})=>t)).filter(Boolean),P=t(v),D=t(g),b=e?i.filter((({participantId:t})=>T.includes(t))):i,N=!a||V?.published&&(0===V?.drawIds?.length||V?.drawIds?.includes(n));for(const t of b){const{entryStatus:e,entryStage:r,entryPosition:i,participantId:a}=t,o=M({participantId:a,scaleNames:m,eventType:A}),c=t=>{if(s[t].draws?.[n])return;const c=I&&N,d=c?{}:void 0,p=c?P?.[a]?.seedValue||P?.[a]?.seedNumber:void 0,l=p?P?.[a]:void 0,m=c?D?.[a]?.seedValue||D?.[a]?.seedNumber:void 0,f=m?D?.[a]:void 0;d&&p&&(d[Xa]=l),d&&m&&(d[Qa]=f);const h=p||m;h&&(s[t].participant.seedings[A]||(s[t].participant.seedings[A]=[]),l&&s[t].participant.seedings[A].push({...l,scaleName:n}),f&&s[t].participant.seedings[A].push({...f,scaleName:n}),d&&(s[t].events[F].seedAssignments||(s[t].events[F].seedAssignments={}),Object.keys(d).forEach((e=>s[t].events[F].seedAssignments[e]=d[e])))),(S||u)&&(s[t].draws[n]=vr({seedAssignments:d,entryPosition:i,entryStatus:e,entryStage:r,seedValue:h,eventId:F,ranking:o,drawId:n},!1,!1,!0))};if(![Qc,tu].includes(e)){c(a);const t=s[a].participant.individualParticipantIds||[];t?.forEach(c)}}const E=(e?.structures??[]).reduce(((t,e)=>(t.includes(e.stage)||t.push(e.stage),t)),[]),O=(e?.links??[]).length;R[n]={qualifyingPositionAssignments:h,qualifyingSeedAssignments:g,mainPositionAssignments:U,qualifyingSeedingMap:D,mainSeedAssignments:v,orderedStructureIds:f,mainSeedingMap:P,flightNumber:l,linksCount:O,drawOrder:c,drawName:d,drawType:p,drawSize:w,drawId:n,stages:E}}}if(u||p||l||f||h||g||S){const e=!!p||c,n=fl({afterRecoveryTimes:!!p,policyDefinitions:r,tournamentRecord:i,inContext:!0,contextProfile:o,participantMap:s,nextMatchUps:e,event:t})?.matchUps??[];for(const t of n){const{finishingPositionRange:n,potentialParticipants:r,tieMatchUps:a=[],sides:o=[],winningSide:c,matchUpType:u,matchUpId:l,eventId:m,drawId:f,collectionId:h,stageSequence:g,finishingRound:I,matchUpStatus:U,roundPosition:S,roundNumber:y,structureId:T,schedule:D,score:b,stage:N}=t;P[l]=t;const R={finishingPositionRange:n,finishingRound:I,stageSequence:g,roundPosition:S,collectionId:h,roundNumber:y,structureId:T,schedule:D,eventId:m,drawId:f,score:b,stage:N};Yl({...R,...w,matchUpStatus:U,winningSide:c,matchUpType:u,matchUpId:l,sides:o});for(const t of a){const{winningSide:e,sides:n=[],matchUpId:r,matchUpStatus:i,matchUpType:a}=t;Yl({...R,...w,winningSide:e,tieWinningSide:c,matchUpTieId:l,matchUpId:r,sides:n,matchUpSides:o,matchUpStatus:i,matchUpType:a})}if(Array.isArray(r)&&(e||p||d)){const t=r.flat().map(Ua("participantId")).filter(Boolean);t?.forEach((t=>{const e=v(t);e?.forEach((t=>{s[t]&&(s[t].potentialMatchUps[l]=vr({tournamentId:i?.tournamentId,matchUpId:l,eventId:m,drawId:f}))})),(p||d)&&Bl({potential:!0,participantMap:s,participantId:t,matchUpStatus:U,roundPosition:S,structureId:T,matchUpType:u,roundNumber:y,matchUpId:l,schedule:D,drawId:f,score:b})}))}}D.push(...n)}}if(f||u||p){const t=Object.values(s);for(const e of t){const{wins:t,losses:n,[Ks]:{wins:r,losses:i},[Zs]:{wins:a,losses:o}}=e.counters,c=(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(f&&(c(Cc,t,n),c(`${Cc}.${Ks}`,r,i),c(`${Cc}.${Zs}`,a,o)),u){const t=(t=[])=>Math.abs(t[0]-t[1]);for(const n of Object.keys(e.draws)){const{orderedStructureIds:r=[],flightNumber:i}=R[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!==Qa;s&&(o+=1);const c=s?o:void 0;return vr({...r,participationOrder:c,flightNumber:i})})).filter(Boolean);e.draws[n]&&(e.draws[n].finishingPositionRange=a,e.draws[n].structureParticipation=s)}}}if(p){const t=ha(p)?p.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(si)));for(const a of n){const{typeChangeTimeAfterRecovery:n,timeAfterRecovery:o,scheduledDate:s,scheduledTime:c}=a,u=i[s],d=ti(c);for(const i of u){if(i.matchUpId===a.matchUpId||[Ga,Oa].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=ti(i.scheduledTime),l=Math.abs(p-d),m=p>=d;if((t&&!isNaN(t)?l<=t:m&&ti(i.scheduledTime)<ti(s))&&(!u||!c)&&m){const t=[a.matchUpId,i.matchUpId].sort(Hl).join("|");e.scheduleConflicts[t]={priorScheduledMatchUpId:a.matchUpId,matchUpIdWithConflict:i.matchUpId}}}}const a=e.participant.participantId;Object.keys(e.scheduleConflicts).length&&T.push(a),s[a].scheduleConflicts=e.scheduleConflicts}}}return{participantIdsWithConflicts:T,eventsPublishStatuses:b,derivedEventInfo:N,derivedDrawInfo:R,mappedMatchUps:P,participantMap:s,matchUps:D}}({withMatchUps:U??i,withEvents:v??i,withDraws:w??i,withPotentialMatchUps:r,participantFilters:n,withRankingProfile:i,convertExtensions:a,withScheduleItems:s,policyDefinitions:o,tournamentRecord:c,scheduleAnalysis:u,withTeamMatchUps:p,usePublishState:f,withStatistics:g,participantMap:D,withOpponents:I,contextProfile:h,withSeeding:y}),{participantIdsWithConflicts:N,eventsPublishStatuses:R,derivedEventInfo:M,derivedDrawInfo:A,mappedMatchUps:C}=b,O=b.matchUps;D=b.participantMap;const F=u??r,k=({potentialMatchUps:t,scheduleConflicts:e,scheduleItems:n,participant:r,statistics:a,opponents:o,matchUps:c,events:d,draws:p})=>{const l=Object.values(p),m=Object.values(o);return I&&l?.forEach((t=>{t.opponents=m.filter((e=>e.drawId===t.drawId))})),vr({...r,scheduleConflicts:u?Object.values(e):void 0,draws:w||i?l:void 0,events:v||i?Object.values(d):void 0,matchUps:U||i?Object.values(c):void 0,opponents:I?m:void 0,potentialMatchUps:F?Object.values(t):void 0,statistics:g?Object.values(a):void 0,scheduleItems:s?n:void 0},!1,!1,!0)},x=new Map;for(const t of Object.keys(D))x.set(t,k(D[t]));const L=[...x.values()],B=o?.[Di],V=B?.participant,j=Kl({participants:L,participantFilters:n,tournamentRecord:c});if(e){const t=ha(e)?e:void 0;for(const e of j)for(const n of e.individualParticipantIds??[]){e.individualParticipants||(e.individualParticipants=[]);const r=x.get(n);e.individualParticipants.push(t?_r({template:t,source:r}):r)}}return{participantIdsWithConflicts:N,eventsPublishStatuses:R,derivedEventInfo:M,derivedDrawInfo:A,mappedMatchUps:C,participantMap:D,participants:V?j.map((t=>_r({source:t,template:V}))):j,...E,matchUps:O}}function Xl({participantId:t,drawDefinition:e,entryStatus:n,entryStage:r}){if(!e)return{error:j};const i=e.entries?.find((e=>!(e.participantId!==t||n&&n!==e.entryStatus||r&&r!==e.entryStage)));return t&&i}function Ql(t){const{provisionalPositioning:e,drawDefinition:n,stageSequence:r,structureId:i,stage:a}=t;if(!n)return{error:j};const{entryProfile:o}=qc({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}=ts({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=ts({structureId:t.source.structureId,drawDefinition:n})?.structure;if(r?.stage===Qa){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=Yp({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 tm({stage:t,drawDefinition:e}){const{entryProfile:n}=qc({drawDefinition:e});return n?.[t]?.drawSize||0}function em({stage:t,drawDefinition:e}){return Boolean(t===eo||uu({stage:t,drawDefinition:e})&&tm({stage:t,drawDefinition:e}))}function nm({entryStatus:t=Hc,drawDefinition:e,stageSequence:n,stage:r}){if(t===$c)return function({stage:t,drawDefinition:e}){const{entryProfile:n}=qc({drawDefinition:e});return n[t]?.alternates||0}({stage:r,drawDefinition:e})?{positionsAvailable:1/0,...E}:{error:We};const i=function(t){const{provisionalPositioning:e,drawDefinition:n,stageSequence:r,stage:i}=t,a=tm({stage:i,drawDefinition:n}),{qualifiersCount:o}=Ql({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}=qc({drawDefinition:e});return n[t]?.wildcardsCount||0}({drawDefinition:e,stage:r}),o=du({entryStatus:eu,drawDefinition:e,stage:r}),s=o+du({entryStatus:Hc,drawDefinition:e,stage:r}),c=i-s;return r!==eo&&s>=i?{error:ze}:t===eu?o<a?{...E}:{error:ze}:{positionsAvailable:c,...E}}function rm(t){const{entryStatus:e=Hc,entryStageSequence:n,entryStage:r=Xa,ignoreStageSpace:i,drawDefinition:a,entryPosition:o,participant:s,roundTarget:c,extensions:u,extension:d,drawType:p}=t,l="addDrawEntry";if(!a)return{error:j};if(!r)return{error:Mt};if(p!==wo&&!em({stage:r,drawDefinition:a}))return wr({result:{error:At},stack:l});const m=nm({stageSequence:n,stage:r,drawDefinition:a,entryStatus:e});if(!i&&!m.success)return{error:m.error};if(d&&!br({extension:d}))return wr({result:{error:Nn},info:"Invalid extension",context:{extension:d},stack:l});const f=t.participantId||s?.participantId;if(!f)return wr({result:{error:Ae},stack:l});const h=e===Kc&&Xl({participantId:f,drawDefinition:a,entryStatus:e}),g=r===eo&&Xl({participantId:f,drawDefinition:a,entryStage:r}),I=e!==Kc&&r!==eo&&Xl({drawDefinition:a,participantId:f});if(I||h||g)return wr({context:{invalidEntry:I,invalidLuckyLoser:h,invalidVoluntaryConsolation:g},result:{error:Be},stack:l});const U=vr({entryStageSequence:n,participantId:f,entryPosition:o,entryStatus:e,entryStage:r,extensions:u});return d&&Nr({element:U,extension:d}),c&&Nr({extension:{name:"roundEntry",value:c},element:U}),a.entries||(a.entries=[]),a.entries.push(U),Ls({drawDefinition:a}),{...E}}function im({autoEntryPositions:t=!0,entryStageSequence:e,ignoreStageSpace:n,drawDefinition:r,participantIds:i,entryStatus:a,roundTarget:o,entryStage:s,extension:c,drawId:u,event:d}){if(!i?.length)return{error:Fe};if(!d)return{error:Pt};if(!u)return{error:at};const p=(d.entries||[]).map(Da);if(i.filter((t=>!p.includes(t))).length)return{error:bt};if(r){const u=function(t){const{entryStatus:e=Hc,stage:n=Xa,autoEntryPositions:r=!0,ignoreStageSpace:i,drawDefinition:a,participantIds:o,stageSequence:s,roundTarget:c,extension:u}=t;if(!n)return{error:Mt};if(!a)return{error:j};if(!Array.isArray(o))return{error:Pe};if(!em({stage:n,drawDefinition:a}))return{error:At};if(u&&!br({extension:u}))return wr({result:{error:Nn},info:"Invalid extension",context:{extension:u},stack:"addDrawEntries"});const d=nm({drawDefinition:a,stageSequence:s,entryStatus:e,stage:n});if(!i&&!d.success)return{error:d.error};const p=d.positionsAvailable??0;if(!i&&n!==eo&&p<o.length)return{error:Ve};const l=o.reduce(((t,r)=>{const i=e===Kc&&Xl({participantId:r,drawDefinition:a,entryStatus:e}),o=n===eo&&Xl({entryStage:n,drawDefinition:a,participantId:r});return e!==Kc&&n!==eo&&Xl({drawDefinition:a,participantId:r})||i||o?t.concat(r):t}),[]);return o.filter((t=>t&&!l.includes(t))).forEach((t=>{const r={entryStageSequence:s,entryStage:n,participantId:t,entryStatus:e};u&&Nr({element:r,extension:u}),c&&Nr({extension:{name:ra,value:c},element:r}),a.entries||(a.entries=[]),a.entries.push(r)})),r&&(a.entries=xl({entries:a.entries})),Ls({drawDefinition:a}),l?.length?{info:"some participantIds could not be added",participantIdsNotAdded:l,...E}:{...E}}({stageSequence:e,autoEntryPositions:t,stage:s,ignoreStageSpace:n,drawDefinition:r,participantIds:i,entryStatus:a,roundTarget:o,extension:c});if(u.error)return u}const{flightProfile:l}=Bd({event:d}),m=l?.flights.find((t=>t.drawId===u));return m?.drawEntries&&(i.forEach((t=>{const e=a===Kc&&am({participantId:t,entryStatus:a,flight:m}),n=s===eo&&am({participantId:t,entryStage:s,flight:m});a!==Kc&&s!==eo&&am({flight:m,participantId:t})||e||n||m.drawEntries.push({participantId:t,entryStatus:a,entryStage:s})})),t&&(m.drawEntries=xl({entries:m.drawEntries}))),{...E}}function am({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 om({autoEntryPositions:t=!0,participantIds:e=[],entryStatuses:n,stage:r,event:i}){const a="removeEventEntries";if(!i?.eventId)return{error:Tt};if(!Array.isArray(e)||e.some((t=>!fa(t))))return wr({result:{error:Te},stack:a});const o=(i.drawDefinitions??[]).flatMap((t=>kl({drawDefinition:t}).assignedParticipantIds??[])),s=(n?.length&&i.entries?.filter((t=>t.entryStatus&&n.includes(t.entryStatus)))||[]).map(Ua("participantId")).filter((t=>!o.includes(t))),c=(r&&i.entries?.filter((t=>t.entryStage&&t.entryStage===r))||[]).map(Ua("participantId")).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=P(s,c):s.length?e=s:c.length&&(e=c),e?.length&&o.some((t=>e.includes(t))))return wr({result:{error:Le},stack:a});if(!e?.length)return{...E,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=xl({entries:i.entries}));const{flightProfile:d}=Bd({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)))})),{...E,participantIdsRemoved:u}}const sm={[wi]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}};function cm(t){const{entryStatus:e=Hc,autoEntryPositions:n=!0,enforceGender:r=!0,participantIds:i=[],entryStageSequence:a,policyDefinitions:o,entryStage:s=Xa,tournamentRecord:c,ignoreStageSpace:u,drawDefinition:d,roundTarget:p,extensions:l,extension:m,drawId:f,event:h}=t,g="addEventEntries";if(!h)return{error:Tt};if(!i?.length)return wr({result:{error:Fe},stack:g});if(!h?.eventId)return{error:Pt};const I=Dc({tournamentRecord:c,event:h}).appliedPolicies??{},U=o?.[wi]??I?.[wi]??sm[wi],S=!1!==(r??U?.participants?.enforceGender),y=[],v=[];if(l&&(!Array.isArray(l)||!l.every((t=>br({extension:t}))))||m&&!br({extension:m}))return wr({context:vr({extension:m,extensions:l}),result:{error:Nn},info:"Invalid extension(s)",stack:g});const w=!!c,T=[];let P;const D=c?.participants?.filter((t=>{if(!i.includes(t.participantId))return!1;const n=h.eventType===Ks&&t.participantType===sc&&!_l(e),r=h.eventType===Zs&&t.participantType===uc;return!(!n||h.gender&&S&&![$p,Gp].includes(h.gender)&&h.gender!==t.person?.sex)||(!(!r||_l(e))||(!(h.eventType!==Zs||t.participantType!==sc||!_l(e))||(n&&h.gender&&S&&![$p,Gp].includes(h.gender)&&h.gender!==t.person?.sex?(T.push({participantId:t.participantId,sex:t.person?.sex}),!1):h.eventType===dc&&(t.participantType===dc||_l(e)&&t.participantType===sc))))})).map((t=>t.participantId))??[],b=i.filter((t=>!w||D.includes(t)));h.entries||(h.entries=[]);const N=h.entries.map((t=>t.participantId||t.participant?.participantId));if(b.forEach((t=>{if(!N.includes(t)){const n=vr({participantId:t,entryStatus:e,entryStage:s,extensions:l});m&&Nr({element:n,extension:m}),p&&Nr({extension:{name:ra,value:p},element:n}),a&&(n.entryStageSequence=a),y.push(n.participantId),h.entries?.push(n)}})),f&&!_l(s)){const t=im({participantIds:b,autoEntryPositions:n,entryStageSequence:a,ignoreStageSpace:u,drawDefinition:d,entryStatus:e,roundTarget:p,entryStage:s,extension:m,drawId:f,event:h});t.error&&(P=t.error)}if(h.eventType&&[rd,ad].includes(h.eventType)){const t=(h.entries||[]).map((t=>t.participantId)),e=(h.entries||[]).filter((t=>_l(t.entryStatus))).map((t=>t.participantId)),n=(c?.participants??[]).filter((e=>t.includes(e.participantId)&&e.participantType&&[uc,dc].includes(e.participantType))).map((t=>t.individualParticipantIds)).flat(1/0),r=e.filter((t=>n.includes(t)));r.length&&(v.push(...r),om({participantIds:r,autoEntryPositions:!1,event:h}))}if(b.length!==i.length)return wr({context:{mismatchedGender:T,gender:h.gender},result:{error:Pe},stack:g});n&&(h.entries=xl({entries:h.entries||[]}));const R=y.length-v.length;return wr({result:{...E,addedEntriesCount:R},stack:g,info:P})}const um="COMPETITOR",dm="OFFICIAL",pm="OTHER",lm={ADMINISTRATION:"ADMINISTRATION",CAPTAIN:"CAPTAIN",COACH:"COACH",COMPETITOR:um,MEDIA:"MEDIA",MEDICAL:"MEDICAL",OFFICIAL:dm,OTHER:pm,SECURITY:"SECURITY"};function mm({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:n,tournamentRecord:r,suppressErrors:i}){const a="removeIndividualParticipantIds";if(!r)return wr({result:{error:_},stack:a});if(!n||!e)return wr({result:{error:ae},stack:a});const o=(r.participants??[]).find((t=>t.participantId===n));if(!o)return wr({result:{error:Ee},stack:a});if(![dc,cc].includes(o.participantType))return wr({result:{participantType:o.participantType,error:be},stack:a});const s=fm({individualParticipantIds:e,groupingParticipant:o,tournamentRecord:r,suppressErrors:i}),{removed:c,error:u}=s;if(u)return wr({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)));cm({participantIds:n,entryStatus:Qc,tournamentRecord:r,event:t})}}return c&&sr({topic:Ss,payload:{tournamentId:r.tournamentId,participants:[o]}}),{...E,...s}}function fm({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}=Zl({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||$s({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}=Mr({element:i,name:Zi}),a=t?.value[e.participantId];t&&a&&(t.value[e.participantId]=a.filter((t=>t.participantId!==r)),Nr({element:i,extension:t}),_s({drawDefinition:i}));const o=Ul({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)),xs({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:ye}||l}function hm({participantRole:t=um,individualParticipantIds:e=[],groupingTypes:n=[oc,cc],tournamentRecord:r}){if(!r)return{error:_};const i=r.participants??[],{participants:a,mappedMatchUps:o}=Zl({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}=fm({groupingParticipant:t,individualParticipantIds:e,tournamentRecord:r,mappedMatchUps:o,participants:a});n&&s++})),s?E:{error:Oe}}function gm(t){if(!t?.tournamentRecord)return{error:_};if(!t?.participantIds?.length)return{error:Fe};const{addIndividualParticipantsToEvents:e,tournamentRecord:n,participantIds:r}=t,i=n.participants?.length||0;if(!i)return{...E};const a=(n.events||[])?.filter((({eventType:t})=>t===id)).map((t=>t?.drawDefinitions?.map((({drawId:t})=>t)))).flat(1/0),o=Zl({participantFilters:{participantIds:r},tournamentRecord:n,withDraws:!0}).participants??[],s=a?.length&&P((hl({matchUpFilters:{drawIds:a,matchUpTypes:[Zs]},tournamentRecord:n}).matchUps??[]).map((({sides:t})=>t?.map((({participantId:t})=>t)))).flat().filter(Boolean),r),c=o.filter((t=>t.draws?.filter((t=>(!a?.length||!a?.includes(t.drawId))&&t.positionAssignments)).length));if(s?.length||c.length)return{error:Le};const u={},d={};for(const t of n.events||[]){const e=om({participantIds:r,event:t});if(e.error)return e;u[t.eventId]=e.participantIdsRemoved}n.participants=n.participants.filter((t=>{const n=r.includes(t.participantId)||t.participantType===uc&&t.individualParticipantIds.some((t=>r.includes(t)));if(!n&&t.participantType===id&&t.individualParticipantIds.some((t=>r.includes(t)))&&(t.individualParticipantIds=t.individualParticipantIds.filter((t=>!r.includes(t)))),n&&e&&[uc,dc].includes(t.participantType))for(const e of t.individualParticipantIds||[])r.includes(e)||(d[t.participantId]||(d[t.participantId]=[]),d[t.participantId].push(e));return!n}));const p=i-n.participants.length;if(hm({individualParticipantIds:r,tournamentRecord:n}),e)for(const t of n.events||[]){cm({participantIds:u[t.eventId].map((t=>d[t]||[])).flat(),entryStatus:Qc,tournamentRecord:n,event:t})}return p&&sr({payload:{participantIds:r,tournamentId:n.tournamentId},topic:ps}),p?{...E,participantsRemovedCount:p}:{error:ye}}function Im({selected:t=!0,drawDefinition:e,entryStatuses:n,drawId:r,event:i,stage:a}){let o=i.entries??[];if(r){const{flightProfile:t}=Bd({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&&ou.includes(e.entryStatus))));return{entries:o,stageEntries:s}}function Um({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:i,stage:a,event:o}){const s="destroyGroupEntry";if(!e)return{error:_};if(!r)return wr({result:{error:Ae},stack:s});if(!o)return{error:Tt};if(!o.eventType||![rd,ad].includes(o.eventType))return wr({result:{error:wt},stack:s});const c=e.participants??[],u=c.find((t=>t.participantId===r));if(!u)return wr({result:{error:Ee},stack:s});if(!u.participantType||![uc,oc].includes(u.participantType)||u.participantType===oc&&o.eventType!==ad||u.participantType===uc&&o.eventType!==rd)return{error:be};const d=(o.entries??[]).find((t=>t.participantId===r));if(!d)return{error:Ge};const{stageEntries:p}=Im({selected:!1,drawDefinition:n,drawId:i,event:o,stage:a}),l=p.map(Da),m=c.filter((({participantId:t})=>l.includes(t))).map((({individualParticipantIds:t})=>t)).flat().filter(Boolean),f=u.individualParticipantIds?.filter((t=>1===T(t,m).length));let h,g=om({participantIds:[r],event:o});if(g.error)return g;if(f?.length&&(g=cm({participantIds:f,entryStatus:Qc,entryStage:d.entryStage,tournamentRecord:e,drawDefinition:n,drawId:i,event:o}),g.error))return g;if(t){gm({participantIds:[r],tournamentRecord:e}).success&&(h=!0)}return{...E,participantRemoved:h}}function Sm({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:i,event:a}){return Um({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:i,event:a})}function ym(t){const{tournamentRecord:e,replaceWithBye:n,drawDefinition:r,destroyPair:i,entryStatus:a,matchUpsMap:o,drawId:s}=t,c="removeDrawPositionAssignment",u=Cl(t);if(u.error)return wr({result:u,stack:c});const{participantId:d}=u,{drawPosition:p,event:l,structureId:m}=t;if([$c,nu].includes(a)&&d){const{tournamentRecord:e}=t,{participant:n}=rl({tournamentRecord:e,participantId:d}),{participantType:o,individualParticipantIds:u}=n??{};if(i&&o===uc){const t=Sm({tournamentRecord:e,drawDefinition:r,participantId:d,event:l});if(t.error)return wr({result:t,stack:c});u&&Ll({participantIds:u,tournamentRecord:e,drawDefinition:r,entryStatus:a,drawId:s,event:l})}else Ll({participantIds:[d],tournamentRecord:e,drawDefinition:r,entryStatus:a,drawId:s,event:l})}if(n){const t=bl({tournamentRecord:e,drawDefinition:r,drawPosition:p,structureId:m,matchUpsMap:o,event:l});if(t.error)return wr({result:t,stack:c})}const{structure:f}=ts({drawDefinition:r,structureId:m});js({structure:f,drawPositions:[p]});return Gs({drawDefinition:r,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:n,drawPosition:p,entryStatus:a,structureId:m}}),u}function vm(t){return fa(t)?t.split(" ").map((t=>t.split("").map(((t,e)=>e?t.toLowerCase():t.toUpperCase())).join(""))).join(" "):t}function wm(t){return fa(t)?vm(t.replace(/_/g," ")):t}const Tm=({finishingPosition:t=Ko,qualifyingRoundNumber:e,structureAbbreviation:n,seedAssignments:r=[],stageSequence:i=1,structureOrder:a,seedingProfile:o,matchUpFormat:s,structureType:c,structureName:u,matchUpType:d,matchUps:p=[],structureId:l,roundOffset:f,roundLimit:h,stageOrder:g,structures:I,stage:U})=>{const S={structureId:l??Md(),structureAbbreviation:n,finishingPosition:t,seedAssignments:r,matchUpFormat:s,stageSequence:i,structureName:u};a&&(S.structureOrder=a),c&&(S.structureType=c),o&&("string"==typeof o?S.seedingProfile=o:"object"==typeof o&&"string"==typeof o.positioning&&(S.seedingProfile=o.positioning)),d&&(S.matchUpType=d),f&&(S.roundOffset=f),g&&(S.stageOrder=g),h&&(S.roundLimit=h),U&&(S.stage=U),e&&(S.qualifyingRoundNumber=e);const y=p.flatMap((({drawPositions:t})=>t)).filter(Boolean);return I?S.structures=I:(S.matchUps=p,S.positionAssignments=m(y).sort(((t,e)=>t-e)).map((t=>({drawPosition:t})))),S};function Pm({structureName:t=wm(eo),structureAbbreviation:e,drawDefinition:n,matchUpType:r,structureId:i}){if(!n)return{error:j};const a=Tm({stage:eo,structureAbbreviation:e,structureName:t,matchUps:[],structureId:i,matchUpType:r});return n.structures||(n.structures=[]),n.structures.push(a),Ls({drawDefinition:n,structureIds:[a.structureId]}),{...E}}function Dm({tournamentRecord:t,drawDefinition:e,stage:n=Xa,structureId:r,structure:i}){if(!t)return{error:_};if(!i&&!e)return{error:j};if(i||r||1!==e?.structures?.filter((t=>t.stage===n)).length||(i=e.structures.find((t=>t.stage===n))),!i&&!r)return{error:It};const{error:a,positionAssignments:o}=rs({drawDefinition:e,structureId:r,structure:i});return{positionAssignments:o??[],structureId:i?.structureId,error:a}}function bm({schedulingProfile:t,venueIds:e,eventIds:n,drawIds:r}){const i=[],a=t?.map((t=>{const a=ri(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 Nm({tournamentRecords:t,schedulingProfile:e}){if(!e)return{valid:!0};if(!Array.isArray(e))return{valid:!1,error:Nn};const{venueIds:n,tournamentsMap:i}=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]={};(e?.events||[]).forEach((t=>{const e=t.eventId;o.push(e),n[u][e]={},(t.drawDefinitions||[]).forEach((t=>{const r=t.drawId;s.push(r),n[u][e][r]={};const{structures:i}=es({drawDefinition:t});(i||[]).forEach((t=>{const i=t.structureId,{matchUps:o}=Yp({structure:t}),{roundMatchUps:s}=vc({matchUps:o}),c=s&&Object.keys(s).map((t=>parseInt(t)));n[u][e][r][i]=c,a.push(i),t.structures?.length&&t.structures.forEach((t=>{a.push(t.structureId),n[u][e][r][t.structureId]=c}))}))}))}))}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 a,o;const s=e.every((t=>{const{scheduleDate:e,venues:s}=t;return!!Wr(e)&&s.every((t=>{const{venueId:e,rounds:s}=t;if("string"!=typeof e)return o="venueId should be a string",!1;if(!Array.isArray(s))return o="rounds should be an array",!1;if(!n.includes(e))return a=rn,!1;return!!s.every((t=>{if(!t)return o="empty round",!1;const{roundSegment:e,tournamentId:n,structureId:a,roundNumber:s,eventId:c,drawId:u}=t,d=i?.[n]?.[c]?.[u]?.[a],l=d?.includes(s);l||(o="Invalid rounds");const{segmentNumber:m,segmentsCount:f}=e||{},h=!e||p(m)&&r(f)&&m<=f;return h||(o="Invalid segment"),l&&h}))}))}));return s||a||(a=Nn),{valid:!!s,error:a,info:o}}function Rm({convertExtensions:t,ignoreDisabled:e,venue:n,court:r}){const i={...gi(r,t,!0),venueId:n.venueId},{extension:a}=Mr({name:$i,element:r});if(e&&a){const t=ha(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 Mm({dates:t=[],extension:e}){if(!e)return!1;if("boolean"==typeof e.value&&e.value)return!0;if(!t.length)return!1;const n=ha(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 Am(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}=Mr({name:$i,element:t});if(e?.value)continue}o.includes(t.venueId)||(u.push(gi(t,e,!0)),o.push(t.venueId));for(const r of t.courts??[])if(!s.includes(r.courtId)){if(n){const{extension:t}=Mr({name:$i,element:r});if(Mm({extension:t,dates:i}))continue}const{inContextCourt:a}=Rm({convertExtensions:e,ignoreDisabled:n,venue:t,court:r});c.push(a),s.push(r.courtId)}}})),{courts:c,venues:u,...E}}function Em({tournamentRecords:t,requireCourts:e,dates:n}){if("object"!=typeof t||!Object.keys(t).length)return{error:x};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:x};const i=gi(e.venues??[],t).filter((t=>{if(!n)return t;const{extension:e}=Mr({name:$i,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}=Mr({name:$i,element:t});return Mm({extension:e,dates:r})})).filter(Boolean).map((e=>{const{inContextCourt:r}=Rm({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 Cm(t){const e=Lp(t,[{[sp]:!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 Om({tournamentRecords:t,tournamentRecord:e}){if("object"!=typeof t||!Object.keys(t).length)return{error:x};const{extension:n}=Mr({element:e,name:oa,tournamentRecords:t,discover:!0});let r=n?.value||[];if(r.length){const{venueIds:n}=Em({requireCourts:!0,tournamentRecords:t}),{eventIds:i,drawIds:a}=Cm({tournamentRecords:t}),{updatedSchedulingProfile:o,modifications:s,issues:c}=bm({schedulingProfile:r,venueIds:n,eventIds:i,drawIds:a});if(s){r=o;const n=Fm({tournamentRecords:t,tournamentRecord:e,schedulingProfile:r});return n.error?n:{schedulingProfile:r,modifications:s,issues:c}}}return{schedulingProfile:r,modifications:0}}function Fm({tournamentRecords:t,tournamentRecord:e,schedulingProfile:n}){const r=Nm({tournamentRecords:t,schedulingProfile:n});if(r.error)return r;if(!n)return Dr({element:e,name:oa,tournamentRecords:t,discover:!0});return Nr({tournamentRecords:t,discover:!0,extension:{name:oa,value:n}})}function km(t){const{tournamentRecord:e}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!t.schedulingProfile){const{modifications:t,issues:r}=Om({tournamentRecords:n,tournamentRecord:e});return{success:!t,modifications:t,issues:r}}const{venueIds:r}=Em({tournamentRecords:n}),{eventIds:i,drawIds:a}=Cm({tournamentRecords:n}),{updatedSchedulingProfile:o,modifications:s,issues:c}=bm({schedulingProfile:t.schedulingProfile,venueIds:r,eventIds:i,drawIds:a});return s?{...Fm({schedulingProfile:o,tournamentRecords:n}),modifications:s,issues:c}:{...E,modifications:s,issues:c}}function xm(t){const{duplicateValues:e=!0,creationTime:n=!0,removePriorValues:r,timeItem:i,element:a}=t;if(!i)return{error:mn};if(!a)return{error:ae,info:Tr};const o=i&&Object.keys(i),s=["itemType","itemValue"];if(!(s.filter((t=>o.includes(t))).length===s.length))return{error:pn};if(a.timeItems){const{itemType:t,itemSubTypes:n,itemValue:r}=i,o=t&&il({itemSubTypes:n,itemType:t,element:a})?.timeItem;if(o&&JSON.stringify(o?.itemValue)===JSON.stringify(r)&&!e)return{...E}}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),{...E}}function _m({creationTime:t=!0,removePriorValues:e,tournamentRecord:n,duplicateValues:r,participantId:i,timeItem:a}){if(!n)return{error:_};if(!i)return{error:Ae};const o=rl({tournamentRecord:n,participantId:i});return o.error?o:xm({element:o.participant,removePriorValues:e,duplicateValues:r,creationTime:t,timeItem:a})}function Lm(t){const{removePriorValues:e,tournamentRecord:n,duplicateValues:r,creationTime:i,timeItem:a}=t;return n?xm({element:n,removePriorValues:e,duplicateValues:r,creationTime:i,timeItem:a}):{error:_}}function Bm(t){const{removePriorValues:e,duplicateValues:n,creationTime:r,timeItem:i,event:a}=t;return a?xm({removePriorValues:e,duplicateValues:n,element:a,creationTime:r,timeItem:i}):{error:Pt}}function Vm({removePriorValues:t=!0,status:e=Hu,statusObject:n,event:r}){if(!ha(n))return{error:Nn};const i=Gl({event:r,status:e}),a=`${Wu}.${zu}`;return Bm({timeItem:{itemValue:{[e]:{...i,...n}},itemType:a},removePriorValues:t,event:r})}function jm({tournamentRecord:t}){if(!t)return{error:_};const e=(({tournamentId:t,tournamentRank:e,tournamentStatus:n,formalName:r,tournamentName:i,promotionalName:a,onlineResources:o,localTimeZone:s,startDate:c,endDate:u,hostCountryCode:d,tournamentContacts:p,tournamentAddresses:l})=>({tournamentId:t,tournamentRank:e,tournamentStatus:n,formalName:r,tournamentName:i,promotionalName:a,onlineResources:o,localTimeZone:s,startDate:c,endDate:u,hostCountryCode:d,tournamentContacts:p,tournamentAddresses:l}))(t);return{...E,tournamentInfo:gi(e,!1,!0)}}function Gm({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[Io,go,ho,po].includes(t.target.feedProfile)?(r?.targets.push(n),s?.sources.push(e)):t.target.feedProfile===fo&&(s?.drawSources.push(e),r?.drawTargets.push(n)),o[n]=o[n]||t.target.feedProfile===fo,a[n]=m([...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===Qa){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;w(0,Math.ceil(u/2)).forEach((()=>{s=w(0,u).map((t=>{const e=s[t],n=s.reduce(((t,n)=>b(e,n)?t.concat(...n):t),[])||[];return m(e.concat(...n))}))}));const d=s[0],p=s.slice(1).reduce(((t,e)=>{return t&&P(n=e,d).length===n.length;var n}),!0),l=[d].filter(Boolean),f=[d].filter(Boolean);e.forEach((t=>{const{structureId:e,stage:n}=t;l.find((t=>t.includes(e)))||(l.push([e]),n!==eo&&f.push([e]))}));const h=p&&1===f.length;return n?.length||1!==e.length||i(e[0].structureId),{structureProfiles:Object.fromEntries(r),allStructuresLinked:h,maxQualifyingDepth:c,sourceStructureIds:a,hasDrawFeedProfile:o,structureGroups:l}}function qm(t){const{tournamentParticipants:e=[],includePositionAssignments:n,policyDefinitions:r,tournamentRecord:i,inContext:a=!0,usePublishState:o,drawDefinition:s,publishStatus:c,noDeepCopy:u,sortConfig:d,context:p,event:l}=t;if(!s)return{error:j};const m=(({matchUpFormat:t,updatedAt:e,drawType:n,drawName:r,drawId:i})=>({matchUpFormat:t,updatedAt:e,drawName:r,drawType:n,drawId:i}))(s);let f,h;const{allStructuresLinked:g,sourceStructureIds:I,hasDrawFeedProfile:U,structureGroups:S}=Gm({drawDefinition:s});if(!g)return{error:vt};let y=!1,v=!1;const w=S.map((t=>{const u={},g=t.map((t=>{const{structure:e}=ts({drawDefinition:s,structureId:t}),{seedAssignments:n}=lu({drawDefinition:s,structure:e});return e?.stage===Xa&&1===e.stageSequence&&(f=n),e?.stage===Qa&&1===e.stageSequence&&(h=n),e})).sort(((t,e)=>Xo(t,e,d))).map((t=>{if(!t)return;const n=t?.structureId;let d=[];t.stage&&[Xa,to,no].includes(t.stage)&&(d=f),t?.stage===Qa&&(d=h);const{matchUps:g,roundMatchUps:S,roundProfile:w}=Yp({seedAssignments:t?.seedAssignments?.length?void 0:d,context:{drawId:m.drawId,...p},tournamentParticipants:e,policyDefinitions:r,tournamentRecord:i,usePublishState:o,publishStatus:c,drawDefinition:s,inContext:a,structure:t,event:l}),{positionAssignments:T}=rs({structure:t}),P=T?.filter(Ua(lp)).map((t=>{v=!0;const{drawPosition:e,participantId:n}=t,{extension:r}=Mr({element:t,name:ca});return r&&{drawPosition:e,participantId:n,participantResult:r.value}})).filter((t=>t?.participantResult)),D=t?(({stageSequence:t,structureName:e,structureType:n,matchUpFormat:r,stage:i})=>({stageSequence:t,structureName:e,structureType:n,matchUpFormat:r,stage:i}))(t):{};D.sourceStructureIds=I[n],D.hasDrawFeedProfile=U[n],D.positionAssignments=T,D.structureActive=g.reduce(((t,e)=>{const n=[Ea,Aa,Oa,Ba,Ga,xa,Fa,ka].includes(e.matchUpStatus);return t||n||!!e.winningSide||!!e.score?.scoreStringSide1}),!1);const b=g.reduce(((t,e)=>t&&[Ma,Ea,Ba,Ga,Oa,Na].includes(e.matchUpStatus)),!!g.length);return D.structureCompleted=b,u[n]=b,D.structureActive&&(y=!0),{...D,participantResults:P,seedAssignments:d,roundMatchUps:S,roundProfile:w,structureId:n}}));return g.forEach((t=>{n||delete t.positionAssignments,t.sourceStructuresComplete=t.sourceStructureIds?.every((t=>u[t]))})),g})).flat();return m.drawActive=y,m.participantPlacements=v,m.drawGenerated=w?.reduce(((t,e)=>t||!!e?.roundMatchUps),!1),m.drawCompleted=w?.reduce(((t,e)=>t&&e.structureCompleted),!0),{structures:u?w:gi(w,!1,!0),drawInfo:u?m:gi(m,!1,!0),...E}}function $m(t){const{includePositionAssignments:e,tournamentRecord:n,participantsProfile:r,policyDefinitions:i,usePublishState:a,status:o=Hu,sortConfig:s,event:c}=t,u=gi(n,!1,!0),d=gi(c,!1,!0);if(!u)return{error:_};if(!d)return{error:Tt};const{eventId:l}=d,{tournamentId:m,endDate:f}=u,h=Gl({event:d,status:o}),{participants:g}=Zl({withGroupings:!0,withEvents:!1,withDraws:!1,...r,tournamentRecord:u}),I=(d.drawDefinitions||[]).filter((({drawId:t})=>!a||(h.drawDetails?h.drawDetails[t]?.publishingDetail?.published:!h.drawIds||h.drawIds.includes(t)))).map((t=>(({drawInfo:t,structures:e})=>({...t,structures:e}))(qm({context:{eventId:l,tournamentId:m,endDate:f},includePositionAssignments:e,tournamentParticipants:g,noDeepCopy:!0,policyDefinitions:i,tournamentRecord:u,usePublishState:a,drawDefinition:t,publishStatus:h,sortConfig:s,event:d})))).map((({structures:t,...e})=>{const n=t?.filter((({stage:t,structureId:n})=>(({structureId:t,drawId:e})=>{if(!a)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(!a)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(!a)return e;const n=h?.drawDetails?.[t]?.structureDetails?.[e.structureId]?.roundLimit;if(p(n)){const t=w(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)),{tournamentInfo:U}=jm({tournamentRecord:u}),S={tournamentInfo:U,venuesData:(u.venues||[]).map((t=>(({venueData:t})=>({...t}))(kd({tournamentRecord:u,venueId:t.venueId})))),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})=>({eventId:t,eventName:e,eventType:n,eventLevel:r,surfaceCategory:i,matchUpFormat:a,category:o,gender:s,startDate:c,endDate:u,ballType:d,discipline:p}))(d),drawsData:I};return S.eventInfo.publish=h,{...E,eventData:S}}function Wm(t){const{includePositionAssignments:e,removePriorValues:n,tournamentRecord:r,status:i=Hu,event:a,drawIdsToRemove:o,drawIdsToAdd:s}=t;if(!r)return{error:_};if(!a)return{error:Tt};const{appliedPolicies:c}=Dc({tournamentRecord:r,event:a}),u={...c,...t.policyDefinitions},d=a.drawDefinitions?.map((({drawId:t})=>t))??[],p=t.drawDetails?Object.keys(t.drawDetails):[],l=p.length?[]:t.drawIds,m=(s??[]).concat(...o??[],...l??[],...p),f=m.filter((t=>!d.includes(t)));if(f.length)return wr({result:{error:q},context:{invalidDrawIds:f}});const h=Gl({event:a,status:i}),g=h?.drawDetails||{};for(const e of d)if(m.length&&!m.includes(e)||(o?.includes(e)||l?.length&&!l.includes(e)?g[e]={...g[e],publishingDetail:{published:!1}}:(s?.includes(e)||l?.includes(e)||!l?.length)&&(g[e]={...g[e],publishingDetail:{published:!0}})),t.drawDetails?.[e]){const n=t.drawDetails[e];let r=n.structureDetails??g[e].structureDetails;const i=n.stageDetails??g[e].stageDetails??{},{structureIdsToRemove:o=[],structureIdsToAdd:s=[],publishingDetail:c={},stagesToRemove:u=[],stagesToAdd:d=[]}=n;if((s||d)&&(c.published=!0),g[e]={publishingDetail:c,structureDetails:r,stageDetails:i},s.length||o.length){const t=(a.drawDefinitions?.find((t=>t.drawId===e))?.structures??[]).map((({structureId:t})=>t)),n=(s??[]).concat(o??[]).filter((e=>!t.includes(e)));if(n.length)return wr({result:{error:Ut},context:{invalidStructureIds:n}});r=r??{};for(const e of t)o.includes(e)?r[e]={published:!1}:r[e]={published:!0};g[e].structureDetails=r}const p=(a.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)&&(g[e].stageDetails=i)}Vm({statusObject:{drawDetails:g},removePriorValues:n,status:i,event:a});const{eventData:I}=$m({includePositionAssignments:e,usePublishState:!0,tournamentRecord:r,policyDefinitions:u,event:a});return sr({payload:{eventData:I,tournamentId:r.tournamentId},topic:Ds}),{...E,eventData:I}}const Hm="deleteDrawDefinitions",zm="autoSchedulingAudit",Ym="deleteEvents",Km={AUTO_SCHEDULING_AUDIT:zm,DELETE_EVENTS:Ym,DELETE_DRAW_DEFINITIONS:Hm};function Jm(t){if(!t.tournamentRecord)return{error:_};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}=Dc({tournamentRecord:a,event:r}),d={...u,...t.policyDefinitions},p=Array.isArray(n)?n[0]:void 0;if(!r){const t=Vd({tournamentRecord:a,eventId:s,drawId:p});if(t.error)return t;r=t.event}const l=[],m=[],f=[];if(!r?.drawDefinitions)return wr({info:"event has no drawDefinition",result:{...E},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 wr({info:"nothing to do; no matching drawIds in event.",result:{...E},stack:e});const g=gi(Bd({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?.[Mi]?.allowDeletionWithScoresPresent?.drawDefinitions,S=Gl({event:r})??{};let y,v=S.drawIds??(S.drawDetails&&Object.keys(S.drawDetails))??[];const w=[],T=r.drawDefinitions.filter((t=>{if(n.includes(t.drawId)){const e=Ul({event:r,drawDefinition:t})?.matchUps??[];if(e.some((({score:t})=>$s({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=>ou.includes(t.entryStatus)))),v.includes(n)&&(v=v.filter((t=>t!==n)),y=!0);const d=es({stageSequence:1,drawDefinition:t,stage:Xa})?.structures?.[0],p=d?Dm({structureId:d.structureId,tournamentRecord:a,drawDefinition:t}):void 0,h=p?.positionAssignments?.map(I),S=es({stage:Qa,drawDefinition:t})?.structures,T=S?.length?S.map((e=>{const n=e.stageSequence,r=Dm({structureId:e.structureId,tournamentRecord:a,drawDefinition:t}),i=r?.positionAssignments.map(I);return{positionAssignments:i,stageSequence:n}})):void 0,P={action:Hm,payload:{drawDefinitions:[t],eventId:s??r?.eventId,auditData:o}};f.push(P),l.push(vr({tournamentId:a.tournamentId,eventId:s??r?.eventId,qualifyingPositionAssignments:T,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 wr({context:{drawIdsWithScoresPresent:w},result:{error:qn},stack:e});if(r.drawDefinitions=T,g){_i({event:r,extension:{name:Ki,value:g}})}if(km({tournamentRecord:a}),y){const t={};for(const e of v)t[e]=S.drawDetails?.[e]??{published:!0};const e=Vm({statusObject:{drawDetails:t},event:r});if(e.error)return{error:e.error}}if(f.length&&sr({topic:ds,payload:f}),m.length&&ks({tournamentId:a?.tournamentId,matchUpIds:m}),n.forEach((t=>{!function({tournamentId:t,eventId:e,drawId:n}){sr({payload:{drawId:n,tournamentId:t,eventId:e},topic:ms,key:n}),dr({key:n})}({drawId:t})})),function({event:t,deletedDrawsDetail:e,auditData:n}){const{extension:r}=Mr({name:zi,element:t}),i={...n,deletedDrawsDetail:e},a={name:zi,value:Array.isArray(r?.value)?r?.value.concat(i):[i]};Nr({element:t,extension:a})}({event:r,deletedDrawsDetail:l,auditData:o}),i&&y){const t=Wm({drawIdsToRemove:n,policyDefinitions:d,tournamentRecord:a,event:r});if(t.error)return{...E,info:t.error}}return{...E}}function Zm({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find((t=>t.matchUpId===e))}}function Xm({tournamentParticipants:t,afterRecoveryTimes:e,contextContent:n,contextProfile:r,drawDefinition:i,matchUpsMap:a,matchUpId:o,inContext:s,context:c,event:u}){if(!i)return{error:j};if(!o)return{error:qt};if("string"!=typeof o)return{error:Nn};const{structures:d=[]}=es({drawDefinition:i});r&&!n&&(n=Fc({contextProfile:r,drawDefinition:i}));for(const p of d){const{matchUps:d}=Yp({tournamentParticipants:t,afterRecoveryTimes:e,contextContent:n,drawDefinition:i,contextProfile:r,matchUpsMap:a,inContext:s,structure:p,context:c,event:u}),{matchUp:l}=Zm({matchUps:d,matchUpId:o});if(l)return{matchUp:l,structure:p}}return{error:Wt}}function Qm(t){let{sourceMatchUp:e}=t;const{targetMatchUp:n,structure:r,matchUpsMap:i,drawPosition:a}=t,o=n.roundNumber>1&&n.roundNumber-1,s=_c({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:[ka,Fa].includes(p)}}function tf({structureId:t,matchUpsMap:e,matchUp:n}){const r=n?.roundPosition,i=r+(r%2?1:-1);return{pairedPreviousMatchUp:_c({matchUpsMap:e,structureId:t}).find((({roundNumber:t,roundPosition:e})=>t===n?.roundNumber&&e===i))}}function ef({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:n,matchUpsMap:r,matchUp:i}){const a=t.find((t=>t.matchUpId===n)),{pairedPreviousMatchUp:o}=tf({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=fa(t)||!isNaN(t)?{code:t}:t;return n.sideNumber===s?{...n,previousMatchUpStatus:e}:n}))}}function nf({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 rf({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}=Mr({element:i,name:Zi}),d=gi((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)}xs({tournamentId:r?.tournamentId,context:"updateSidLineUp",eventId:o?.eventId,drawDefinition:i,matchUp:a})}function af({inContextDrawMatchUps:t,sourceMatchUpStatus:n,tournamentRecord:r,sourceMatchUpId:i,drawDefinition:a,matchUpStatus:o,drawPosition:s,matchUpsMap:c,matchUpId:u,event:d}){const p="assignMatchUpDrawPosition";c||(c=xc({drawDefinition:a})),t||(t=Jp({inContext:!0,drawDefinition:a,matchUpsMap:c}).matchUps??[]);const l=t.find((t=>t.matchUpId===u)),m=l?.structureId,f=a?.structures?.find((t=>t.structureId===m));if(!f)return{error:Ut};const h=c?.drawMatchUps?.find((t=>t.matchUpId===u)),g=h?.drawPositions??[],{positionAdded:I,positionAssigned:U,updatedDrawPositions:S}=function({drawPosition:t,drawPositions:n}){let r=!1,i=!!n?.includes(t);return{updatedDrawPositions:i?n||[]:[...n,void 0,void 0].slice(0,2).map((e=>e||i?e:(i=!0,r=!0,t))).sort(e).filter(Boolean),positionAdded:r,positionAssigned:i}}({drawPosition:s,drawPositions:g}),{positionAssignments:y}=rs({drawDefinition:a,structure:f}),v=y?.filter((t=>S.includes(t.drawPosition))),w=v?.find((({bye:t})=>t)),T=h?.matchUpStatus&&[Ga,Oa].includes(h.matchUpStatus)&&S.filter(Boolean).length<2;if(o=w&&Ma||o||T&&h.matchUpStatus||h?.matchUpStatus&&[ka,Fa].includes(h.matchUpStatus)&&h.matchUpStatus||ja,h&&I){t=Jp({inContext:!0,drawDefinition:a,matchUpsMap:c}).matchUps??[];const e=T&&nf({inContextDrawMatchUps:t,drawPosition:s,matchUpId:u})||void 0;h?.matchUpStatusCodes&&ef({inContextDrawMatchUps:t,sourceMatchUpStatus:n,sourceMatchUpId:i,matchUpsMap:c,matchUp:h}),Object.assign(h,{drawPositions:S,winningSide:e,matchUpStatus:o}),xs({tournamentId:r?.tournamentId,eventId:l?.eventId,context:p,drawDefinition:a,matchUp:h})}const P=Uc({inContextDrawMatchUps:t,inContextMatchUp:l,drawDefinition:a,matchUpId:u}),{targetMatchUps:{winnerMatchUp:D,loserMatchUp:N,loserTargetDrawPosition:R},targetLinks:{loserTargetLink:M}}=P,A=_c({structureId:f.structureId,matchUpsMap:c});if(U&&w){if(D)if([Ma,ka,Fa].includes(o)){const e=af({matchUpId:D.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:a,drawPosition:s,matchUpsMap:c});if(e.error)return e}else{const{structureId:t}=D;t!==f.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(D&&l&&!l.feedRound){const{pairedPreviousMatchUpIsDoubleExit:e}=Qm({targetMatchUp:h,drawPosition:s,matchUpsMap:c,structure:f});if(e){const e=af({matchUpId:D.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:a,drawPosition:s,matchUpsMap:c});if(e.error)return e}}if(h?.matchUpType===Qs){const e=t?.find((({matchUpId:t})=>t===h.matchUpId)),n=(e?.sides??[]).reduce(((t,e,n)=>e.drawPosition===s?n:t),void 0),i=y?.find((t=>t.drawPosition===s))?.participantId;i&&void 0!==n&&rf({inContextTargetMatchUp:e,drawPositionSideIndex:n,teamParticipantId:i,tournamentRecord:r,drawDefinition:a,matchUp:h})}if(M?.linkCondition===vo&&2===S.filter(Boolean).length&&!w){if(A.filter((({drawPositions:t,roundNumber:e})=>1===e&&b(t,S))).every((({matchUpStatus:t})=>[Ea,Ba].includes(t)))&&N){const{structureId:t}=N,e=bl({drawPosition:R,tournamentRecord:r,drawDefinition:a,structureId:t,matchUpsMap:c,event:d});if(e.error)return e}}return U?{...E}:wr({result:{error:z},context:{drawPosition:s},stack:p})}function of(t){if(!t)return 1/0;if(p(t))return n(t);const e=t.split("-")[0];return p(e)?n(e):1/0}function sf({drawPositions:t}){const e=[].concat(...t.map((e=>t.filter((t=>t!==e)).map((t=>[e,t]))))),n=m(e.map(cf)).map((t=>t.split("|").map((t=>+t))));return{groupMatchUps:e,uniqueMatchUpGroupings:n}}function cf(t){return[...t].sort(e).join("|")}function uf({groupSize:t,drawPositionOffset:e}){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=>cf(t.map((t=>t+e)))))))}const df={getRoundRobinGroupMatchUps:sf,determineRoundNumber:function({rounds:t,hash:e}){return t.reduce(((t,n,r)=>n.includes(e)?r+1:t),void 0)},drawPositionsHash:cf,groupRounds:uf};function pf(t){const{groupNameBase:e="Group",playoffAttributes:n,stageSequence:r=1,structureOptions:i,appliedPolicies:a,seedingProfile:o,stage:s=Xa,matchUpType:c,roundTarget:u,structureId:d,groupNames:p,drawSize:l,idPrefix:m,isMock:f,uuids:h}=t,g=t.structureName??n?.[0]?.name??wm(Xa),{groupCount:I,groupSize:U}=function({appliedPolicies:t,structureOptions:e,drawSize:n}){let r=e?.groupSize;const i=e?.groupSizeLimit||8,{validGroupSizes:a}=lf({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:i,appliedPolicies:a,drawSize:l}),S=Yo;let y;const v=w(1,I+1).map((t=>{const n=function({structureOrder:t,matchUpType:e,groupSize:n,drawSize:r,idPrefix:i,isMock:a,uuids:o}){const s=(t-1)*n,c=w(1+s,n+1+s),{uniqueMatchUpGroupings:u}=sf({drawPositions:c}),d=uf({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(cf(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()||Md()}({structureOrder:t,drawPositions:n,roundNumber:s,idPrefix:i,uuids:o}),d={matchUpStatus:s?ja:Ma,matchUpType:e,finishingPositionRange:{winner:c,loser:c},drawPositions:n,roundNumber:s,matchUpId:u};return a&&(d.isMock=!0),d}}({groupSize:U,structureOrder:t,matchUpType:c,drawSize:l,idPrefix:m,isMock:f});y=Math.max(...n.map((({roundNumber:t})=>t)));const r=p?.[t-1]??`${e} ${t}`;return Tm({structureId:h?.pop(),structureType:lo,finishingPosition:S,structureOrder:t,structureName:r,matchUps:n})})),T=Tm({structureId:d??h?.pop(),structureType:mo,finishingPosition:S,seedingProfile:o,structureName:g,stageSequence:r,structures:v,stage:s});return u&&Nr({extension:{name:ra,value:u},element:T}),{structures:[T],maxRoundNumber:y,groupCount:I,links:[],groupSize:U,...E}}function lf({drawSize:t,groupSizeLimit:e=10}){const n=w(3,e+1).filter((e=>{const n=Math.ceil(t/e),r=n*e-t,i=Math.ceil(t/n),a=Math.ceil(r/n);return(!r||r<e)&&i===e&&i>=3&&a<2}));return{...E,validGroupSizes:n}}function mf(t){const{roundRobinGroupsCount:e,participantsCount:n,cluster:r}=t;if(!p(n))return{seedBlocks:void 0,...wr({result:{error:Nn},context:{participantsCount:n},stack:"getSeedBlocks"})};const i=u(n);if(e){const t=Math.min(e,i),n=[];let r=1;for(w(0,t).forEach((()=>{n.push([r]),r++}));r<i;){const e=w(r,r+t);r+=t,n.push(e)}return{...E,seedBlocks:n}}const a=w(1,i+1),o=[];let s=i/2;for(;s>1;){const t=N(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,b(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 d=w(0,20).map((t=>Math.pow(2,t)));d.unshift(1);const l=d.indexOf(i);let m=0;const f=[];return w(0,l).forEach((t=>{f.push(o.slice(m,m+d[t])),m+=d[t]})),{...E,seedBlocks:f}}function ff({roundRobinGroupsCount:t,drawSize:e}){const n="getSeedGroups";if(!p(e))return{seedGroups:void 0,...wr({result:{error:Nn},context:{drawSize:e},stack:n})};if(t){if(!p(t))return{seedGroups:void 0,...wr({context:{roundRobinGroupsCount:t},result:{error:Nn},stack:n})};let r=1;return{seedGroups:w(0,Math.floor(e/t)).map((()=>{const e=w(r,r+t);return r+=t,e}))}}{const{seedBlocks:n}=mf({participantsCount:e,roundRobinGroupsCount:t});let r=0;return{seedGroups:(n||[]).map((t=>(t||[]).map((()=>(r+=1,r)))))}}}function hf({positioning:t,size:n}){const r=function({size:t}){const n=[t];let r=t;for(;r/2===Math.floor(r/2);)r/=2,n.push(r);return n.includes(1)||n.push(1),n.sort(e),n.reverse(),n}({size:n}),i=[],a=[],o=t=>t[0],s=(e,n)=>(t===uo&&n%2?(t=>t[t.length-1])(e):o(e))||o(e),c=(t,e)=>{if(t.every((t=>!a.includes(t)))){const n=s(t,e);return a.push(n),n}},u=t=>{const e=t.filter((t=>!a.includes(t)));if(e.length)return a.push(...e),e},d=(t,e)=>{const n=s(t,e);if(!a.includes(n))return a.push(n),n},p=w(1,n+1);for(const t of r)if(1===t){const t=N(p,2),e=t.map(c).filter(Boolean);e.length&&i.push(e);const n=t.flatMap(u).filter(Boolean);n.length&&i.push(n)}else{const e=N(p,t).map(d).filter(Boolean);e.length&&i.push(e)}return{divisions:r,divisionGroupings:i}}function gf({provisionalPositioning:t,returnAllProxies:e,appliedPolicies:n,seedingProfile:r,drawDefinition:i,allPositions:a,structure:o}){let s=[];if(!o)return{error:yt};const{matchUps:c,roundMatchUps:u}=Yp({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:o}),{seedAssignments:d}=lu({provisionalPositioning:t,returnAllProxies:e,drawDefinition:i,structure:o}),{positionAssignments:p}=is({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,S=h.filter((t=>t.filter((t=>t<=m)).length)),{stage:y,structureType:v,roundLimit:T}=o,P=v===mo,D=!P&&h?.length,b=!P&&y===Qa&&T,R=S.flat(1/0),M=D?R?.length:0,A=a?l:m,E=ip({drawDefinition:i,structure:o,matchUps:c}),C=E?0:!D&&A||A&&R.length<A&&A-R.length||0;if(b){const t=o?.matchUps?o.matchUps.filter((({roundNumber:t})=>t===o.roundLimit)).length:0,e=g.length/t;if(D);else{const t=yf(r),n=N(g,e);let i=1;const a=w(0,n[0].length).map((()=>{const t=w(i,i+n.length);return i+=n.length,t}));({validSeedBlocks:s}=If({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=rs({structure:e})?.positionAssignments,o=yf(t),s=a?.length??0,{seedGroups:c}=ff({roundRobinGroupsCount:i,drawSize:s});return If({drawPositionBlocks:r.map((t=>rs({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=S.map((t=>({seedNumbers:t,drawPositions:t})));else if(E){N(g,2).map(((t,e)=>({drawPositions:[t[0]],seedNumbers:[e+1]}))).forEach((t=>s.push(t)))}if(!P&&!E&&!b){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}=mf({cluster:yf(i)===uo,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:M,seedCountGoal:C,seedingProfile:r,baseDrawSize:U});t.forEach((t=>s.push(t)))}const O=s.flatMap((t=>t.drawPositions)).reduce(((t,e)=>g?.includes(e)&&t),!0);return E||D||P||O?{isLuckyStructure:E,validSeedBlocks:s,isContainer:P,isFeedIn:D}:{error:ft,validSeedBlocks:[],isContainer:P,isFeedIn:D}}function If({drawPositionBlocks:t,positioning:e,seedGroups:n,nonRandom:r}){const i=[],{divisionGroupings:a}=hf({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!==po?d=r?d:f(d):s%2&&d.reverse();const p=d.find((t=>!o.includes(t)));p&&(o.push(p),i.push({seedNumbers:[n],drawPositions:[p]}))}))})),{validSeedBlocks:i}}function Uf({appliedPolicies:t,drawDefinition:e,seedBlockInfo:n,drawPosition:r,structureId:i,seedNumber:a}){const{structure:o}=ts({drawDefinition:e,structureId:i});t||(t=Dc({drawDefinition:e}).appliedPolicies);let s=n?.validSeedBlocks;if(!s&&o&&(s=gf({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 Sf(t){const{provisionalPositioning:e,drawDefinition:n,seedingProfile:r,seedBlockInfo:i,structureId:a,randomize:o}=t,{structure:s}=ts({drawDefinition:n,structureId:a}),{seedAssignments:c}=lu({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,drawDefinition:n,structure:s}),{positionAssignments:u}=is({structure:s}),d=u?.filter((t=>t.participantId??t.bye??t.qualifier)),p=d?.map((t=>t.drawPosition)).filter(Boolean),{appliedPolicies:l}=Dc({drawDefinition:n}),m=(i?.validSeedBlocks||s&&gf({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],h=c?.map((t=>t.participantId)).filter(Boolean),g=u?.map((t=>t.participantId)).filter(Boolean),I=h?.filter((t=>g?.includes(t))),U=h?.filter((t=>!g?.includes(t))),S=c?.filter((t=>U?.includes(t.participantId))),y=c?.filter((t=>!t.participantId)),v=(S?.length&&S.length>0?S.length:y?.length??0)&&m?.drawPositions.filter((t=>!p?.includes(t)))||[],w=o?f(v):v,T=[],P=w.map((()=>{const t=function(t,e){const n=t.filter((t=>!e.includes(t.participantId))),r=Math.min(...n.map((t=>of(t.seedValue)))),i=n.filter((t=>of(t.seedValue)===r));return f(i).pop()}(S,T),e=t?.participantId;return e&&T.push(e),e})).filter(Boolean),D=c?.filter((t=>I?.includes(t.participantId))).map((t=>t.seedNumber)),b=(m?.seedNumbers||[]).filter((t=>!D?.includes(t))),N=c?.filter((t=>b.includes(t.seedNumber))).map((t=>t.participantId)),R=l?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:m,unplacedSeedParticipantIds:void 0===R||R?P:N,unplacedSeedNumbers:b,unfilledPositions:w,unplacedSeedAssignments:S}}function yf(t){return"string"==typeof t?t:"object"==typeof t?t.positioning:void 0}function vf({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}=ts({drawDefinition:n,structureId:o}),{positionAssignments:m}=is({structure:l}),f=lu({provisionalPositioning:t,drawDefinition:n,structure:l}).seedAssignments,h=f.map((t=>t.seedNumber)),g=Xl({drawDefinition:n,participantId:i});if(i&&!g)return wr({result:{error:Te},context:{participantId:i},stack:p});const I=d?Bd({event:d}).flightProfile?.flights?.length:0,U=I&&I>1,S=m?.find((t=>t.participantId===i)),y=S?.drawPosition;if(y){if(!Uf({drawPosition:y,drawDefinition:n,seedBlockInfo:a,structureId:o,seedNumber:s}))return wr({result:{error:H},context:{assignedDrawPosition:y},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?(Bs({tournamentId:e?.tournamentId,drawDefinition:n,structure:l,eventId:u}),{...E}):wr({result:{error:mt},stack:p})}function wf({inContextDrawMatchUps:t,drawDefinition:e,assignments:n,matchUpsMap:r,structure:i}){const a=qs({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)&&P(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 Tf({lineUp:t}){if(!Array.isArray(t))return;const e={};return m(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}=Bc({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 Pf(t){return`${t} must be an array`}function Df({lineUp:t,tieFormat:e}){const n=[];if(!Array.isArray(t))return n.push(Pf("lineUp")),{valid:!1,errors:n,error:Nn};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(Pf("collectionAssignments")),!1):(n.push("Missing participantId"),!1)})),i=m(t.map(Da)).length===t.length;i||n.push("Duplicated participantId(s)");return{valid:r&&i,errors:n,error:n.length?Nn:void 0}}function bf({drawDefinition:t,participantId:e,tieFormat:n,lineUp:r}){if("object"!=typeof t)return{error:j};if("string"!=typeof e)return{error:Ae};const i=Df({lineUp:r,tieFormat:n});if(!i.valid)return i;const{extension:a}=Mr({element:t,name:Zi}),o=a?.value||{};o[e]=Tf({lineUp:r});return Nr({element:t,extension:{name:Zi,value:o}}),_s({drawDefinition:t}),{...E}}function Nf({inContextDrawMatchUps:t,inheritance:e=!0,tournamentRecord:n,drawDefinition:r,matchUpsMap:i,assignments:a,structure:o,event:s}){if(!r)return{error:j};const{drawPositions:c,matchUps:u,targetMatchUps:d}=wf({inContextDrawMatchUps:t,matchUpsMap:i,assignments:a,structure:o});for(const t of d)t.matchUpType===Xs&&(t.sides??[]).forEach(((i,a)=>{if(i?.drawPosition&&c?.includes(i.drawPosition)){const o=u.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&&bf({drawDefinition:r,participantId:n,lineUp:[],tieFormat:e})}xs({tournamentId:n?.tournamentId,context:"resetLineUps",eventId:s?.eventId,drawDefinition:r,matchUp:o})}}}));return{...E}}function Rf({provisionalPositioning:t,inContextDrawMatchUps:e,isQualifierPosition:n,sourceMatchUpStatus:r,tournamentRecord:i,drawDefinition:a,seedingProfile:o,participantId:s,seedBlockInfo:c,drawPosition:u,matchUpsMap:d,structureId:p,event:l}){const m="assignDrawPosition";if(!s&&!n)return wr({result:{error:Ae},stack:m});d=d??xc({drawDefinition:a}),e||({matchUps:e}=Jp({inContext:!0,drawDefinition:a,matchUpsMap:d}));const f=ts({drawDefinition:a,structureId:p});if(f.error)return wr({result:f,stack:m});const{structure:h}=f;if(!h)return{error:Ut};if(ap({drawDefinition:a,structure:h}))return wr({result:{error:Yt},stack:m});const{seedAssignments:g}=lu({provisionalPositioning:t,drawDefinition:a,structure:h}),I=g?.find((t=>t.participantId===s)),U=I?.seedNumber,{appliedPolicies:S}=Dc({tournamentRecord:i,drawDefinition:a,structure:h,event:l});if(U){if(!Uf({seedNumber:U,appliedPolicies:S,drawDefinition:a,seedBlockInfo:c,drawPosition:u,structureId:p}))return wr({result:{error:H},context:{drawPosition:u},stack:m})}const y=is({structure:h}).positionAssignments||[],v=y?.find((t=>t.drawPosition===u));if(!v)return wr({result:{error:Q},context:{drawPosition:u},stack:m});const w=y?.map(Da).includes(s);if(w)return wr({result:{error:Le},context:{drawPosition:u},stack:m});const{containsParticipant:T,containsBye:P}=function(t){const e=t.bye,n=t.qualifier,r=t.participantId;return{containsBye:e,containsQualifier:n,containsParticipant:r,filled:e||n||r}}(v);if(P){const t=Cl({inContextDrawMatchUps:e,tournamentRecord:i,drawDefinition:a,drawPosition:u,structureId:p,matchUpsMap:d,event:l});if(t.error)return wr({result:t,stack:m})}if(T&&v.participantId!==s){const{activeDrawPositions:t}=yl({drawDefinition:a,structureId:p});if(t.includes(u))return wr({result:{error:X},stack:m});Nf({assignments:[v],inContextDrawMatchUps:e,tournamentRecord:i,drawDefinition:a,matchUpsMap:d,structure:h})}if(v.participantId=s,n&&(v.qualifier=!0),(h?.stageSequence||0)>1||h.stage&&[to,no].includes(h.stage)){const e=h.stage===Qa?Qa:Xa,n=a.structures?.find((t=>t?.stage===e&&1===t?.stageSequence)),r=(n?.seedAssignments??[]).find((t=>t.participantId===s));if(r?.participantId){const{participantId:e,seedNumber:n,seedValue:s}=r;vf({eventId:l?.eventId,provisionalPositioning:t,tournamentRecord:i,drawDefinition:a,seedingProfile:o,participantId:e,seedNumber:n,seedValue:s,structureId:p,event:l})}}if(h.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}=Yp({provisionalPositioning:t,matchUpFilters:u,drawDefinition:i,matchUpsMap:o,structure:s,event:c}),{roundMatchUps:p}=vc({matchUps:d}),{initialRoundNumber:l}=vl({drawPosition:a,matchUps:d}),m=l&&p?.[l].find((t=>t.drawPositions?.includes(a)));if(m){const t=af({matchUpId:m.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:r,drawDefinition:i,drawPosition:a,matchUpsMap:o});if(t.error)return wr({stack:"assignDrawPositionToMatchUps",context:{drawPosition:a},result:t})}}({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:i,drawDefinition:a,drawPosition:u,matchUpsMap:d,structure:h,event:l});else{El({positionAssignments:y,tournamentRecord:i,drawDefinition:a,matchUpsMap:d,structure:h});const{drawPositions:t,matchUps:n,targetMatchUps:r}=wf({assignments:[v],inContextDrawMatchUps:e,drawDefinition:a,matchUpsMap:d,structure:h});if(t&&1===n?.length&&n[0].matchUpType===Qs){const e=(r?.[0].sides??[]).reduce(((e,n,r)=>t?.includes(n.drawPosition)?r:e),void 0);rf({inContextTargetMatchUp:r[0],teamParticipantId:s,matchUp:n[0],drawPositionSideIndex:e,tournamentRecord:i,drawDefinition:a})}}return Vs({tournamentId:i?.tournamentId,drawDefinition:a,structure:h,event:l}),{positionAssignments:y,...E}}function Mf(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:j};let{inContextDrawMatchUps:p,matchUpsMap:l}=t;l||(l=xc({drawDefinition:a}),Object.assign(t,{matchUpsMap:l})),p||(({matchUps:p}=Jp({inContext:!0,drawDefinition:a,matchUpsMap:l})),Object.assign(t,{inContextDrawMatchUps:p}));const{positionAssignments:m}=rs({drawDefinition:a,structureId:c}),f=m?.find((t=>t.drawPosition===s));if(f?.participantId){const t=f.participantId,e=Rf({inContextDrawMatchUps:p,tournamentRecord:i,drawDefinition:a,participantId:o,drawPosition:s,structureId:c,matchUpsMap:l,event:u});return e.success?U({removedParticipantId:t}):wr({result:e,stack:d})}const h=Cl({inContextDrawMatchUps:p,tournamentRecord:i,drawDefinition:a,drawPosition:s,structureId:c,matchUpsMap:l,event:u});if(h.error)return wr({result:h,stack:d});const g=h.participantId,I=Rf({inContextDrawMatchUps:p,isQualifierPosition:n,tournamentRecord:i,drawDefinition:a,participantId:o,drawPosition:s,structureId:c,matchUpsMap:l,event:u});return I.success?U({removedParticipantId:g}):wr({result:I,stack:d});function U({removedParticipantId:t}){const{structure:n}=ts({drawDefinition:a,structureId:c});js({drawPositions:[s],structure:n});return Gs({drawDefinition:a,positionAction:{[e]:o,name:r,drawPosition:s,structureId:c}}),wr({context:{removedParticipantId:t},result:{...E},stack:d})}}function Af(t){Object.assign(t,{inContext:!0});const{matchUp:e,error:n}=Ef(t);return{matchUp:gi(e,!0,!0),error:n}}function Ef({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:_};if("string"!=typeof s)return{error:qt};if(!a||!p){const t=(hl({tournamentRecord:n,nextMatchUps:o}).matchUps??[]).find((t=>t.matchUpId===s));if(!t)return{error:Wt};({eventId:u,drawId:d}=t),({event:p,drawDefinition:a}=Vd({tournamentRecord:n,eventId:u,drawId:d}))}if(!a)return{error:q};i&&!r&&(r=Fc({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=[]}=ml({participantsProfile:t,tournamentRecord:n,contextProfile:i,inContext:c});if(o){const t=(Ul({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:Wt};const n=a?.structures?.find((e=>e.structureId===t.structureId));return{drawDefinition:a,structure:n,matchUp:t}}{const{matchUp:t,structure:n}=Xm({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 Cf(t,e){if(!ha(t))return{error:Nn};if(!Array.isArray(e))return{error:Nn};const n={};for(const{param:r,error:i,attr:a}of e){const e=Of({params:t,param:r,attr:a,error:i});if(e?.error)return e;n[r]=e}return n}function Of({params:t,param:e,attr:n,error:r}){if(e===Sp&&ha(t.drawDefinition)&&fa(t.structureId)){const e=(t.drawDefinition.structures??[]).find((({structureId:e})=>e===t.structureId));return!e.length&&r?{error:r}:{structure:e}}if(e===Dp){const e=Ef({...t,...n});return e.error&&r?{...e,error:r}:e}return{error:On,info:{param:e}}}function Ff({removePriorValues:t,tournamentRecord:e,duplicateValues:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:o,event:s}){const{matchUp:c}=Xm({drawDefinition:r,event:s,matchUpId:a});if(!c)return{error:Wt};const u=xm({removePriorValues:t,element:c,duplicateValues:n,timeItem:o});return i||xs({tournamentId:e?.tournamentId,eventId:s?.eventId,context:"addTimeItem",drawDefinition:r,matchUp:c}),u}function kf(t){const e=Lp(t,[{[up]:!0},{[dp]:!0},{[lp]:!0},{[Ip]:!0}]);if(e.error)return e;const n=Cf(t,[{[Mp]:Dp,attr:{[Up]:!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&&Ka.includes(c)||c&&Ya.includes(c)||$s({score:u}))return{error:dt};const d=Ku({matchUp:s});if(d?.error)return d;const{checkedInParticipantIds:p,allRelevantParticipantIds:l}=d??{};if(!l?.includes(a))return{error:Te};if(!p?.includes(a))return{error:xe};const m=yu({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=>{Ff({drawDefinition:i,matchUpId:o,timeItem:{itemType:wu,itemValue:t}})}));return Ff({tournamentRecord:r,drawDefinition:i,matchUpId:o,timeItem:{itemValue:a,itemType:wu}})}function xf(t){const e=Lp(t,[{[up]:!0},{[dp]:!0},{[lp]:!0},{[Ip]:!0}]);if(e[Np])return e;const n=Cf(t,[{[Mp]:Dp,attr:{[Up]:!0}}]);if(n[Np])return n;const{tournamentRecord:r,drawDefinition:i,participantId:a,matchUpId:o}=t,s=Ku({matchUp:n?.matchUp?.matchUp});if(s?.error)return s;const{checkedInParticipantIds:c,allRelevantParticipantIds:u}=s??{};if(c?.includes(a))return{...E};if(!u?.includes(a))return{[Np]:Te};return Ff({tournamentRecord:r,drawDefinition:i,matchUpId:o,timeItem:{itemValue:a,itemType:vu}})}function _f(t){const e=Lp(t,[{[lp]:!0,[dp]:!0,[Ip]:!0}]);if(e.error)return e;const n=t.tournamentId??t.activeTournamentId,r=t.tournamentRecord??(n&&t.tournamentRecords?.[n]),{participantId:i,matchUpId:a,drawDefinition:o}=t;if(!r)return{error:_};const s=Cf(t,[{[Mp]:Dp,[Np]:Wt}]),c=s.matchUp?.matchUp;if(!c)return{error:Wt};const{checkedInParticipantIds:u=[]}=Ku({matchUp:c});return i&&u.includes(i)?kf({tournamentRecord:r,drawDefinition:o,participantId:i,matchUpId:a,matchUp:c}):xf({tournamentRecord:r,drawDefinition:o,participantId:i,matchUpId:a,matchUp:c})}function Lf({tournamentRecord:t,drawDefinition:e,tieMatchUpId:n,event:r}){if(!t)return{error:_};if(!e)return{error:at};if(!r)return{error:Pt};const i=xc({drawDefinition:e}),{matchUp:a}=Xm({matchUpId:n,drawDefinition:e,matchUpsMap:i});if(!a)return{error:Wt};const{matchUp:o,structure:s}=Xm({tournamentParticipants:t.participants,matchUpId:n,inContext:!0,drawDefinition:e,matchUpsMap:i,event:r});if(!o)return{error:Wt};const{collectionPosition:c,drawPositions:u,collectionId:d,matchUpTieId:p,matchUpType:l}=o;if(l&&![Ks,Zs].includes(l))return{error:Yt};const{positionAssignments:m}=rs({structure:s}),f=m?.filter((t=>u?.includes(t.drawPosition))),h=f?.map(Ua("participantId")),{participants:g}=Zl({tournamentRecord:t,participantFilters:{participantTypes:[dc],participantIds:h}}),{matchUp:I}=Xm({matchUpId:p,drawDefinition:e,matchUpsMap:i}),{matchUp:U}=Xm({matchUpId:p,inContext:!0,drawDefinition:e,matchUpsMap:i}),S=$d({matchUp:I,drawDefinition:e,structure:s,event:r})?.tieFormat;return{inContextDualMatchUp:U,inContextTieMatchUp:o,relevantAssignments:f,collectionPosition:c,teamParticipants:g,collectionId:d,matchUpType:l,dualMatchUp:I,tieMatchUp:a,tieFormat:S,structure:s,...E}}function Bf(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:_};if(!o)return wr({result:{error:Re},stack:e});o.participantId||(o.participantId=Md()),s.participants||(s.participants=[]);const{participantId:c,individualParticipantIds:u}=o;if(s.participants.reduce(((t,e)=>e.participantId===c||t),!1))return{error:Ce};const{participantType:d,participantRole:p}=o;if(!d||!Object.keys(pc).includes(d))return{error:be,participantType:d};if(!p)return{error:Ne};const l=s.participants||[],m=l.filter((t=>t.participantType===sc)).map((t=>t.participantId));if(d!==sc&&o.person)return{error:Nn,person:o.person};if(u&&!Array.isArray(u))return{error:Nn,individualParticipantIds:u};if(d===uc){if(o.person)return{error:Nn,person:o.person};if(!o.individualParticipantIds)return wr({result:{error:Fe},stack:e});if(2!==o.individualParticipantIds.length&&!a)return wr({info:"PAIR must be 2 individualParticipantIds",result:{error:Pe},stack:e});{const t=l.filter((t=>t.participantType===sc)).map((t=>t.participantId));if(!Array.isArray(o.individualParticipantIds))return wr({result:{error:Pe},stack:e});if(!o.individualParticipantIds.reduce(((e,n)=>t.includes(n)&&e),!0))return wr({result:{error:Pe},stack:e})}const t=l.filter((t=>t.participantType===uc)).map((t=>({individualParticipantIds:t.individualParticipantIds,participant:t}))),i=o.participantType===uc&&t.find((t=>2===P(t.individualParticipantIds,o.individualParticipantIds).length));if(i&&!n)return{...E,existingParticipant:!0,participant:r&&gi(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===sc){if(!o.person?.standardFamilyName||!o.person?.standardGivenName)return{error:_e};if(!o.participantName){const t=`${o.person.standardFamilyName.toUpperCase()}, ${o.person.standardGivenName}`;o.participantName=t}}else{if(!d||![dc,cc].includes(d))return{error:be};if(u||(o.individualParticipantIds=[]),o.individualParticipantIds?.length)for(const t of o.individualParticipantIds){if("string"!=typeof t)return wr({result:{participantId:t,error:Nn},stack:e});if(!m.includes(t))return wr({result:{participantId:t,error:Ee},stack:e})}}s.participants.push(o),i||sr({payload:{tournamentId:s.tournamentId,participants:[o]},topic:ss});return vr({participant:r&&gi(o),...E})}function Vf({inContextDualMatchUp:t,drawDefinition:e,tournamentId:n,dualMatchUp:r,eventId:i}){if(r){t||(t=Xm({matchUpId:r.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);const{extension:a}=Mr({element:e,name:Zi}),o=gi(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}})),xs({context:"ensureSidLineUps",matchUp:r,drawDefinition:e,tournamentId:n,eventId:i})}}function jf(t){const e=Lf(t);if(e.error)return e;const n="replaceTieMatchUpParticipantid",{existingParticipantId:r,tournamentRecord:i,newParticipantId:a,drawDefinition:o,substitution:s,event:c}=t;if(!r||!a)return wr({result:{error:Ae},stack:n});if(r===a)return{...E};const{inContextDualMatchUp:u,inContextTieMatchUp:d,collectionPosition:p,collectionId:l,dualMatchUp:f,tieMatchUp:h,tieFormat:g}=e,I=d?.matchUpType,U=d?.sides?.find((t=>t.participant?.participantId===r||t.participant?.individualParticipantIds?.includes(r)));if(!U)return{error:Ee};const S=Zl({tournamentRecord:i,participantFilters:{participantIds:[r,a]}})?.participants??[];if(2!==S.length)return wr({result:{error:Ae},stack:n});if(S[0].participantType!==S[1].participantType)return wr({result:{error:be},stack:n});const{appliedPolicies:y}=Dc({tournamentRecord:i,drawDefinition:o,event:c}),v=t.policyDefinitions?.[wi]??y?.[wi]??sm[wi],w=S.find((({participantId:t})=>t===a));if(!1!==(t.enforceGender??v?.participants?.enforceGender)&&[qp,Hp].includes(d?.gender)&&d?.gender!==w?.person?.sex)return{error:we,info:"Gender mismatch"};const T=v?.processCodes?.substitution;Vf({tournamentId:i.tournamentId,eventId:c.eventId,inContextDualMatchUp:u,drawDefinition:o,dualMatchUp:f});const P=f?.sides?.find((({sideNumber:t})=>t===U.sideNumber));if(!P)return wr({result:{sideNumber:U.sideNumber,existingParticipantId:r,error:On},stack:n});const D=d?.sides?.flatMap((t=>t.participant?.individualParticipantIds||t.participant?.participantId||[]));if(D?.includes(a))return wr({result:{error:Be},stack:n});const b=u?.sides?.find((({sideNumber:t})=>t===U.sideNumber))?.participantId,N=P.lineUp,R=N?.find((({participantId:t})=>a===t)),M=N?.reduce(((t,e)=>e.substitutionOrder>t?e.substitutionOrder:t),0),A=N?.map((t=>{const e=gi(t,!1,!0);if(![r,a].includes(e.participantId))return e;if(!s&&[r,a].includes(e.participantId)&&(e.collectionAssignments=e.collectionAssignments?.filter((t=>!(t.collectionPosition===p&&t.collectionId===l)))),s&&r===e.participantId&&(e.collectionAssignments=e.collectionAssignments.map((t=>t.collectionPosition===p&&t.collectionId===l&&void 0===t.substitutionOrder?{...t,substitutionOrder:M}:t))),e.participantId===a){e.collectionAssignments||(e.collectionAssignments=[]);const t={collectionId:l,collectionPosition:p};s&&(t.previousParticipantId=r,t.substitutionOrder=(M??0)+1),e.collectionAssignments.push(t)}return e}))??[];if(!R){const t={collectionId:l,collectionPosition:p};s&&(t.substitutionOrder=(M??0)+1,t.previousParticipantId=r);const e={collectionAssignments:[t],participantId:a};A.push(e)}const C=I===Zs,{assignedParticipantIds:O}=Bc({lineUp:N,collectionPosition:p,collectionId:l}),{assignedParticipantIds:F}=Bc({lineUp:A,collectionPosition:p,collectionId:l});if(P.lineUp=A,b&&g){const t=bf({participantId:b,lineUp:A,drawDefinition:o,tieFormat:g});if(t.error)return wr({result:t,stack:n})}else console.log("team participantId not found");let k,x;if(C){const{tournamentRecord:e}=t;let r=Vc({participantIds:F,tournamentRecord:e});if(!r.participant){const t=Bf({returnParticipant:!0,pairOverride:!0,tournamentRecord:e,participant:{participantRole:um,individualParticipantIds:F,participantType:uc}});if(t.error)return wr({result:t,stack:n});k=t.participant?.participantId}r=Vc({participantIds:O,tournamentRecord:e});const i=r.participant?.participantId;if(i){gm({participantIds:[i],tournamentRecord:e}).success&&(x=i)}}if(s||1===U.substitutions?.length){if(s)T&&h&&(h.processCodes=m([...h?.processCodes??[],...T]));else for(const t of T||[]){const e=h?.processCodes?.lastIndexOf(t);void 0!==e&&h?.processCodes?.splice(e,1)}h&&xs({tournamentId:i?.tournamentId,matchUp:h,context:n,drawDefinition:o})}return f&&xs({tournamentId:i?.tournamentId,matchUp:f,context:n,drawDefinition:o}),{...E,modifiedLineUp:A,participantRemoved:x,participantAdded:k}}function Gf({collectionPosition:t,teamParticipantId:e,dualMatchUpSide:n,drawDefinition:r,participantIds:i,collectionId:a}){if(!a||!t||!Array.isArray(i))return{modifiedLineUp:n?.lineUp||[],error:Nn};const o=n?.lineUp||jc({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 qf({individualParticipantIds:t,groupingParticipantId:e,removeFromOtherTeams:n,tournamentRecord:r}){const i="addIndividualParticipantIds";if(!r)return wr({result:{error:_},stack:i});if(!e||!t)return wr({result:{error:ae},stack:i});const a=r.participants??[],o=a.find((t=>t.participantId===e));if(!o)return wr({result:{error:Ee},stack:i});if(o?.participantType&&![dc,cc].includes(o.participantType))return wr({context:{participantType:o.participantType},result:{error:be},stack:i});const s=t.filter((t=>{const e=a.find((e=>e.participantId===t));return e?.participantType!==sc}));if(s.length)return wr({result:{error:Pe,invalidParticipantIds:s},stack:i});o.individualParticipantIds||(o.individualParticipantIds=[]);const c=o.individualParticipantIds,u=t.filter((t=>!c.includes(t)));u.length&&(n&&hm({individualParticipantIds:u,tournamentRecord:r}),o.individualParticipantIds=o.individualParticipantIds.concat(...u));const{topics:d}=lr();if(d.includes(Ss)){const t=a.find((({participantId:t})=>t===e));sr({topic:Ss,payload:{participants:[t]}})}return function({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}){const r=(n.events||[]).filter((t=>t?.eventType===id&&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}=Bd({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:gi(o,!1,!0),added:u.length,...E}}function $f(t){const{updateParticipantName:e=!0,groupingParticipantId:n,removeFromOtherTeams:r,tournamentRecord:i,pairOverride:a,participant:o}=t;if(!i)return{error:_};if(!o)return{error:Re};if(!o.participantId)return Bf({tournamentRecord:i,participant:o});const{participant:s}=rl({participantId:o.participantId,tournamentRecord:i});if(!s)return Bf({tournamentRecord:i,participant:o});const{participantRoleResponsibilties:c,individualParticipantIds:u,participantOtherName:d,participantName:p,participantRole:l,participantType:m,onlineResources:f,contacts:h,person:g}=o;if(m&&s.participantType!==m)return{error:Se};const I={};if(h&&(I.contacts=h),f&&(I.onlineResources=f),p&&"string"==typeof p&&(I.participantName=p),d&&"string"==typeof d&&(I.participantOtherName=d),Array.isArray(u)){const{participants:t}=Zl({participantFilters:{participantTypes:[sc]},tournamentRecord:i}),n=t?.map(Da);if(n){const r=u.filter((t=>"string"==typeof t&&n.includes(t)));([cc,Qs].includes(m||s.participantType)||m===uc&&(2===r.length||a))&&(I.individualParticipantIds=r),s.participantType===pc.PAIR&&e&&(I.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:I}))}}return Object.keys(lm).includes(l)&&(I.participantRole=l),Object.keys(pc).includes(m)&&(I.participantType=m),Array.isArray(c)&&(I.participantRoleResponsibilties=c),s.participantType===pc.INDIVIDUAL&&g&&function({updateParticipantName:t,existingParticipant:e,newValues:n,person:r}){const i={},{standardFamilyName:a,standardGivenName:o,nationalityCode:s,personId:c,sex:u}=r;u&&Object.keys(zp).includes(u)&&(i.sex=u);let d;c&&"string"==typeof c&&(i.personId=c);s&&"string"==typeof s&&(p=s,el.flatMap((({iso:t,ioc:e})=>[t,e])).filter(Boolean).includes(p)||""===s)&&(i.nationalityCode=s);var p;a&&"string"==typeof a&&a.length>1&&(i.standardFamilyName=a,d=!0);o&&"string"==typeof o&&o.length>1&&(i.standardGivenName=o,d=!0);if(d&&t){const t=`${i.standardGivenName} ${i.standardFamilyName}`;n.participantName=t}Object.assign(e.person,i)}({updateParticipantName:e,existingParticipant:s,newValues:I,person:g}),Object.assign(s,vr(I)),n&&qf({individualParticipantIds:[s.participantId],groupingParticipantId:n,removeFromOtherTeams:r,tournamentRecord:i}),sr({topic:Ss,payload:{tournamentId:i.tournamentId,participants:[s]}}),{participant:gi(s),...E}}function Wf(t){const e=Lf(t);if(e.error)return e;const n="assignTieMatchUpParticipantId";let r=t.teamParticipantId;const{tournamentRecord:i,drawDefinition:a,participantId:o,event:s}=t;if(!o)return wr({result:{error:Ae},stack:n});if(t.sideNumber&&![1,2].includes(t.sideNumber))return wr({result:{error:ne},stack:n});const{inContextDualMatchUp:c,inContextTieMatchUp:u,relevantAssignments:d,collectionPosition:p,teamParticipants:l,collectionId:m,matchUpType:f,dualMatchUp:h,tieFormat:g}=e,I=u?.sides?.flatMap((t=>t.participant?.individualParticipantIds||t.participant?.participantId||[]));if(I?.includes(o))return wr({result:{...E},stack:n});r=r??(t.sideNumber?c?.sides?.find((e=>e.sideNumber===t.sideNumber))?.participantId:void 0);const U=Zl({participantFilters:{participantIds:[o]},tournamentRecord:i})?.participants?.[0];if(!U)return wr({result:{error:Ee},stack:n});const{appliedPolicies:S}=Dc({tournamentRecord:i,drawDefinition:a,event:s}),y=t.policyDefinitions?.[wi]??S?.[wi]??sm[wi];if(!1!==(t.enforceGender??y?.participants?.enforceGender)&&[qp,Hp].includes(u?.gender)&&u?.gender!==U.person?.sex)return{error:we,info:"Gender mismatch"};const{individualParticipantIds:v,participantType:w}=U;if(f===Ks&&w!==sc)return{error:be};const T=w===sc?[o]:v,P=r&&l?.find((({participantId:t})=>t===r))||l?.find((({individualParticipantIds:t})=>b(T,t)));if(!P)return{error:Mn};if(r||(r=P.participantId),!r)return{error:Ee};const D=d?.find((t=>t.participantId===P?.participantId)),N=D?.drawPosition,R=u?.sides?.find((t=>t.drawPosition===N)),M=t.sideNumber??R?.sideNumber;if(!g)return{error:Gt};const A=g.collectionDefinitions?.find((t=>t.collectionId===m));if(!A)return{error:jt};Vf({tournamentId:i.tournamentId,eventId:s.eventId,inContextDualMatchUp:c,drawDefinition:a,dualMatchUp:h});const C=h?.sides?.find((t=>t.sideNumber===M)),O=u?.sides?.find((t=>t.sideNumber===M)),F=C?.lineUp??jc({participantId:r,drawDefinition:a})?.lineUp,k=F?.filter((t=>t.collectionAssignments?.find((t=>t.collectionPosition===p&&t.collectionId===m&&!t.previousParticipantId)))),x=k?.map((t=>t?.participantId)),_=x?.length>1&&x||(w===uc?U.individualParticipantIds:[o]),L=Gf({collectionPosition:p,teamParticipantId:r,dualMatchUpSide:C,drawDefinition:a,participantIds:_,collectionId:m});if(L.error)return wr({result:L,stack:n});const{modifiedLineUp:B}=L;let V;if(f===Zs){if(w!==uc){let t=Hf({collectionPosition:p,teamParticipantId:r,drawDefinition:a,modifiedLineUp:B,participantId:o,collectionId:m,tieFormat:g});if(t?.error)return wr({result:t,stack:n});if(t=function({side:t}){let e;if(t.participant){const n=t.participant.individualParticipantIds||[];if(1===n.filter(Boolean).length){const{participant:t}=Vc({participantIds:n,tournamentRecord:i});n.push(o);const{participant:r}=Vc({participantIds:n,tournamentRecord:i});if(!r&&t){t.individualParticipantIds=n;const e=$f({pairOverride:!0,tournamentRecord:i,participant:t});if(e.error)return e}else e=t?.participantId}}else{const t=Bf({participant:{individualParticipantIds:[o],participantRole:um,participantType:uc},pairOverride:!0,tournamentRecord:i});if(t.error)return t}return{...E,deletedParticipantId:e}}({side:O}),t.error)return t;V=t.deletedParticipantId,C&&(C.lineUp=B),h&&xs({tournamentId:i?.tournamentId,matchUp:h,context:n,drawDefinition:a})}else if(w===uc)for(const t of _)Hf({collectionPosition:p,teamParticipantId:r,drawDefinition:a,modifiedLineUp:B,participantId:t,collectionId:m,tieFormat:g})}else{const t=Hf({collectionPosition:p,teamParticipantId:r,drawDefinition:a,modifiedLineUp:B,participantId:o,collectionId:m,tieFormat:g});if(t?.error)return t}if(C&&(C.lineUp=B),h&&xs({tournamentId:i?.tournamentId,matchUp:h,context:n,drawDefinition:a}),V){const{error:t}=gm({participantIds:[V],tournamentRecord:i});t&&console.log("cleanup")}return{...E,modifiedLineUp:B}}function Hf({collectionPosition:t,teamParticipantId:e,drawDefinition:n,modifiedLineUp:r,participantId:i,collectionId:a,tieFormat:o}){const s=jc({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 bf({participantId:e,lineUp:r,drawDefinition:n,tieFormat:o})}function zf({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!==m(r).length?(n.push("collectionPositions are not unique"),{errors:n}):{...E}}function Yf(t){if(t)return gi(t,!1,!0)}function Kf({collectionGroups:t=[]}){const e=Object.assign({},...t.filter((t=>p(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=>n(t)))}}function Jf({collectionDefinitions:t=[],collectionGroups:e=[]}){let n=0;const{groupValueNumbers:r}=Kf({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,l=a&&r.includes(a);if(p(d||u))i=!0;else{if(l)continue;if("number"==typeof o&&p(o))n+=o;else if(t?.length)for(const e of t)n+=e.matchUpValue;else"number"==typeof c&&p(c)&&(n+=(s??0)*c)}}for(const t of e)n+=t.groupValue??0;if(i||!n)return{aggregateValue:!0};return{valueGoal:Math.floor(n/2)+1}}function Zf({drawDefinition:t,structureId:e,matchUpId:n,structure:r,matchUp:i,eventId:a,event:o}){const s="getTieFormat";let c;if(e=r?.structureId??e,((n=i?.matchUpId??n)||e)&&!t)return{error:j};if(a&&o)c=Gd(o);else if(n){if(t&&(!i||!r)){const e=Xm({drawDefinition:t,matchUpId:n});if(e.error)return e;if(e.matchUp?.matchUpType!==Xs)return wr({result:{error:Yt},stack:s});r||(r=e.structure),i||(i=e.matchUp)}c=qd({item:i,drawDefinition:t,structure:r,event:o})||qd({item:r,drawDefinition:t,structure:r,event:o})||Gd(t)||Gd(o)}else if(t&&e){if(!r){const n=ts({drawDefinition:t,structureId:e});if(n.error)return n;r=n?.structure}c=qd({item:r,drawDefinition:t,structure:r,event:o})||Gd(t)||Gd(o)}else c=Gd(t)||Gd(o);return c?{...E,structure:r,tieFormat:c,matchUp:i}:wr({result:{error:Gt},stack:s})}function Xf(t,e){if((t?.bestOf||t?.exactly)&&t?.setFormat)return function(t,e){const n=Qf(t.bestOf)||void 0,r=Qf(t.exactly)||void 0,i=n||r;if(t.setFormat?.timed&&t.simplified&&1===i)return th(t.setFormat);const a=i&&`${Yd}${i}`||"",o=eh(t.setFormat,e),s=o&&`S:${o}`||"",c=eh(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 Qf(t){return!isNaN(Number(t))&&Number(t)}function th(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function eh(t,e){if("object"==typeof t&&Object.keys(t).length){if(t.timed)return th(t);if(t.tiebreakSet)return nh(t.tiebreakSet);const n=Qf(t.setTo);if(n){const r=t.NoAD&&zd||"",i=nh(t.tiebreakFormat),a=i&&`/${i}`||"",o=Qf(t.tiebreakAt);if(!1!==i)return`${n}${r}${a}${o&&(o!==n||e)&&`@${o}`||""}`}}}function nh(t){if(t){if("object"!=typeof t||t.tiebreakTo){if("object"==typeof t&&Qf(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?zd:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}return!1}return""}}function rh(t){if("string"!=typeof t)return!1;const e=Jd(t),n=t.match(/-S:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),r=n?.[1],i=n?.[2],a=n?.[3],o=t.match(/-F:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),s=o?.[1],c=o?.[2],u=o?.[3];return Xf(e,!!(n&&i&&r===a||o&&c&&s===u))===t}const ih="MIXED events can not contain mixed singles or { gender: ANY } collections",ah="events with { gender: ANY } can not contain MIXED singles collections";function oh(t){const e="tieFormatGenderValidityCheck",{referenceGender:n,matchUpType:r,gender:i}=t;return n&&i&&[qp,Hp].includes(n)&&n!==i?wr({result:{valid:!1,error:Dn},context:{gender:i},stack:e}):n===$p&&(i===Gp||i===$p&&r!==Zs)?wr({result:{error:Dn,valid:!1},info:ih,stack:e}):n===Gp&&i===$p&&r!==Zs?wr({result:{error:Dn,valid:!1},info:ah,stack:e}):{valid:!0}}const sh=(t,e)=>t.filter(Boolean).every((t=>typeof t===e)),ch=t=>t.filter(Boolean).every(s);function uh(t){const e=t.category;if("object"!=typeof e)return{error:bn};let{ageCategoryCode:n,ageMaxDate:r,ageMinDate:i,ageMax:a,ageMin:o}=e;const s=e.categoryName;let c;if(!sh([n,r,i,s],"string")||!ch([a,o]))return{error:bn};const u=t.consideredDate??ri((new Date).toLocaleDateString("sv"));if(!Wr(u))return{error:pe};const[d]=u.split("-").slice(0,3).map((t=>parseInt(t))),p=ii(u,-1),[l,m]=p.split("-").slice(1,3).map((t=>parseInt(t))),f=`${mi(l)}-${mi(m)}`,h=ii(u,1),[g,I]=h.split("-").slice(1,3).map((t=>parseInt(t))),U=`${mi(g)}-${mi(I)}`;let S=o&&ii(u,-365*o),y=a&&ii(u,-365*a);const v=[],w=t=>!v.includes(t)&&v.push(t);n=n??s;const T=/^([UO]?)(\d{1,2})([UO]?)$/,P=/^C(\d{1,2})-(\d{1,2})$/,D=n?.includes("-"),b=D&&n?.match(P),N=n?.match(T),R=(t,e)=>`${t}-${e}`,M=t=>{const r=R(d-t-1,U);e.ageMin&&e.ageMin>t&&w(`Invalid submitted ageMin: ${o}`),e.ageMax&&e.ageMax>t&&w(`Invalid submitted ageMax: ${a}`),e.ageMinDate&&e.ageMinDate!==r&&w(`Invalid submitted ageMinDate: ${i}`),i=r,n&&(e.ageMax&&e.ageMax!==t&&(w(`Invalid submitted ageMax: ${a}`),S=void 0),a=t)},A=t=>{const i=R(d-t,f);e.ageMaxDate&&e.ageMaxDate!==i&&w(`Invalid submitted ageMaxDate: ${r}`),r=i,n&&(e.ageMin&&e.ageMin!==t+1&&(w(`Invalid submitted ageMin: ${o}`),S=void 0),o=t+1)},E=t=>{const[s,c,u]=(t.match(T)||[]).slice(1),p=parseInt(c);"U"===s?(e.ageMaxDate&&e.ageMaxDate!==r&&w(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),(t=>{const r=R(d-t,U);e.ageMinDate&&e.ageMinDate!==r&&w(`Invalid submitted ageMinDate: ${i}`),i=r,n&&(e.ageMax&&e.ageMax!==t-1&&(w(`Invalid submitted ageMax: ${a}`),y=void 0),a=t-1)})(p)):"O"===s&&A(p),"U"===u?(e.ageMaxDate&&e.ageMaxDate!==r&&w(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),M(p)):"O"===u&&(t=>{const i=R(d-t-1,f);e.ageMaxDate&&e.ageMaxDate!==i&&w(`Invalid submitted ageMaxDate: ${r}`),r=i,n&&(e.ageMin&&e.ageMin!==t&&(w(`Invalid submitted ageMin: ${o}`),S=void 0),o=t)})(p),r=r??S,i=i??y};if(b){if(r=void 0,i=void 0,a=void 0,o=void 0,e.ageMin){const t=d-e.ageMin;r=R(t,f)}if(e.ageMax){const t=d-e.ageMax-1;i=R(t,U)}const[t,s]=(n?.match(P)??[]).slice(1).map((t=>parseInt(t)));t<=s?(o=t,a=s,c=!0):w(`Invalid combined age range ${n}`)}else D?n?.split("-").forEach(E):N?E(n):(o&&A(o),a&&M(a));a&&e.ageMin&&e.ageMin>a&&(w(`Invalid submitted ageMin: ${e.ageMin}`),o=void 0);const C=vr({consideredDate:u,combinedAge:c,ageMaxDate:r,ageMinDate:i,ageMax:a,ageMin:o});return v.length&&(C.errors=v),C}function dh({category:t}){if(!ha(t))return{error:Nn};const e=uh({category:t});if(e.error)return{error:e};const{ratingMax:n,ratingMin:r}=t;return n&&!s(n)?wr({result:{error:Nn},context:{ratingMax:n}}):r&&!s(r)?wr({result:{error:Nn},context:{ratingMin:r}}):{...e}}function ph({childCategory:t,withDetails:e,category:n}){const r=dh({category:n}),i=dh({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=vr({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}const lh={isValid:rh,isValidMatchUpFormat:rh,stringify:Xf,parse:Jd};function mh({checkCategory:t=!0,collectionDefinition:e,checkCollectionIds:n,checkGender:r=!0,referenceCategory:i,referenceGender:a,event:o}){a=a??o?.gender;const s="validateCollectionDefinition",c=[];if("object"!=typeof e)return c.push(`collectionDefinition must be an object: ${e}`),wr({result:{errors:c,error:Pn},stack:s});const{collectionValueProfiles:u,collectionGroupNumber:d,collectionValue:l,collectionId:m,matchUpCount:f,matchUpFormat:h,matchUpValue:g,matchUpType:I,scoreValue:U,setValue:S,category:y,gender:v}=e;n&&"string"!=typeof m&&c.push(`collectionId is not type string: ${m}`),"number"!=typeof f&&c.push(`matchUpCount is not type number: ${f}`),I&&![Ks,Zs].includes(I)&&c.push(`matchUpType must be SINGLES or DOUBLES: ${I}`);if(1!==[!!u?.length].concat([g,l,U,S].map(p)).filter(Boolean).length&&c.push("Missing value definition for matchUps: matchUpValue, collectionValue, or collectionValueProfiles"),g&&"number"!=typeof g&&c.push(`matchUpValue is not type number: ${g}`),l&&"number"!=typeof l&&c.push(`collectionValue is not type number: ${l}`),u&&f){const t=zf({collectionValueProfiles:u,matchUpCount:f});t.errors&&c.push(...t.errors)}if(d&&"number"!=typeof d&&c.push(`collectionGroupNumber is not type number: ${l}`),h&&!lh.isValidMatchUpFormat(h)&&c.push(`Invalid matchUpFormat: ${h}`),r){const t=oh({referenceGender:a,matchUpType:I,gender:v});if(t.error)return wr({context:{referenceGender:a,gender:v},result:t,stack:s})}if(t&&i&&y){const t=ph({category:i,childCategory:y});if(!t.valid)return wr({result:{error:bn},context:t,stack:s})}return c.length?wr({result:{errors:c,error:Tn},stack:s}):{valid:!0}}function fh(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=[];if(!t||!i||"object"!=typeof i)return s.push("tieFormat must be an object"),wr({result:{error:Lt},context:{tieFormat:i,errors:s},stack:o});if("object"!=typeof i.winCriteria)return s.push("tieFormat.winCriteria must be an object"),wr({result:{error:Lt},context:{tieFormat:i,errors:s},stack:o});if(!Array.isArray(i.collectionDefinitions))return s.push(Pf("tieFormat.collectionDefinitions")),wr({result:{error:Lt},context:{tieFormat:i,errors:s},stack:o});let c;const u=i.collectionDefinitions.every((i=>{const{setValue:o,scoreValue:u,collectionValue:d}=i;!o&&!u||d||(c=!0);const{valid:p,errors:l}=mh({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)})),d="number"==typeof i.winCriteria?.valueGoal&&i.winCriteria?.valueGoal>0&&!c||i.winCriteria?.aggregateValue;if(!d&&!i.winCriteria?.aggregateValue)return c?s.push("aggregateValue is required"):s.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),wr({context:{tieFormat:i,errors:s,aggregateValueImperative:c},result:{error:Lt},stack:o});const p=i.collectionDefinitions.map((({collectionId:t})=>t)),l=!r||p.length===m(p).length,f=u&&d&&l;return f?{valid:f,errors:s}:wr({result:{error:Lt},context:{tieFormat:i,errors:s},stack:o})}function hh({tieFormat:t,isMock:e,uuids:n}){const{collectionDefinitions:r}=t??{};return{tieMatchUps:(r??[]).map((t=>gh({collectionDefinition:t,uuids:n,isMock:e}))).filter(Boolean).flat()}}function gh({collectionPositionOffset:t=0,collectionDefinition:e,matchUpsLimit:n,isMock:r,uuids:i}){const{matchUpCount:a,matchUpType:o,collectionId:s,processCodes:c}=e||{};return w(0,n??a??0).map((e=>{const n=t+e+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:i?.pop()??Md(),matchUpStatus:ja,collectionPosition:n,collectionId:s,processCodes:c,matchUpType:o,isMock:r}}))}function Ih(t){if(!t)return{};const e=[],n=t.tieFormatName,r=t.collectionDefinitions?.map((t=>{const{matchUpType:n,matchUpFormat:r,matchUpCount:i,category:a,gender:o}=t;e.includes(r)||e.push(r);const s=a?.ageCategoryCode;return[i,n===Js?"D":"S",s,r,o].join(";")})).join("|");return{tieFormatName:t&&n||"UNNAMED",matchUpFormats:e,tieFormatDesc:r}}function Uh({considerations:t={},descendant:e,ancestor:n}){const r={},i={},{matchUpFormats:a,tieFormatDesc:o}=Ih(e),{matchUpFormats:s,tieFormatDesc:c}=Ih(n),u=m((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})))),f=Object.assign({},...(n?.collectionDefinitions||[]).map((t=>({[t.collectionId]:t}))));r.collectionIds=D(Object.keys(l),Object.keys(f)),i.collectionIds=D(Object.keys(f),Object.keys(l)),r.collectionsValue=Sh(l),i.collectionsValue=Sh(f),r.groupsCount=n?.collectionGroups?.length??(0-(e?.collectionGroups?.length??0)||0),i.groupsCount=r.groupsCount?-1*r.groupsCount:0;const h=r.collectionsValue.totalValue-i.collectionsValue.totalValue,g=r.collectionsValue.totalMatchUps-i.collectionsValue.totalMatchUps,I=i.collectionsValue.assignmentValues.length!==r.collectionsValue.assignmentValues.length,U=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))))})),S=d||p||c!==o||I||U||0!==h,y=[...i.collectionsValue.invalidValues,...r.collectionsValue.invalidValues],v=y.length&&y;return{matchUpFormatDifferences:u,matchUpCountDifference:g,descendantDifferences:r,ancestorDifferences:i,orderDifference:p,valueDifference:h,nameDifference:d,descendantDesc:o,ancestorDesc:c,...E,different:S,invalid:v}}function Sh(t){const e=[],n=[];let r=0;return{totalValue:Object.keys(t).sort(Hl).reduce(((i,a)=>{const o=t[a],{collectionValueProfiles:s,collectionValue:c,matchUpCount:u,matchUpValue:d,scoreValue:l,setValue:m}=o,f={collectionValueProfiles:s,collectionValue:c,matchUpValue:d,scoreValue:l,setValue:m},h=Object.keys(f).filter((t=>![void 0,null].includes(f[t])));1!==h.length&&e.push({collectionId:a});const g=h[0];if(g){const t="collectionValueProfiles"===g?Object.values(s):f[g];n.push({valueKey:g,value:t})}return r+=u,s?i+s.reduce(((t,e)=>t+e.value),0):u?p(d)?i+d*u:p(l)?i+l*u:p(m)?i+m*u:i+c:i}),0),totalMatchUps:r,invalidValues:e,assignmentValues:n}}function yh({matchUp:t,updateInProgressMatchUps:e}){return!t.winningSide&&![Ya].includes(t.matchUpStatus)&&(e||t.matchUpStatus!==xa&&!$s(t))}function vh({from:t,to:e}){const n=Object.keys(t),r=P(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 wh({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===ja)).map(Ua("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 Th({drawDefinition:t,auditData:e}){const{extension:n}=Mr({name:ua,element:t});Nr({element:t,extension:{name:ua,value:Array.isArray(n?.value)?n?.value.concat(e):[e]}})}function Ph({updateInProgressMatchUps:t=!1,tournamentRecord:e,collectionOrder:n,collectionName:r,tieFormatName:i,drawDefinition:a,matchUpFormat:o,matchUpCount:s,collectionId:c,matchUpType:u,structureId:d,matchUpId:l,category:m,eventId:f,gender:h,event:I,collectionValueProfiles:U,collectionValue:S,matchUpValue:y,scoreValue:v,setValue:w}){const T="modifyCollectionDefinition";if(o&&!rh(o))return wr({result:{error:Nn},context:{matchUpFormat:o},stack:T});if(r&&"string"!=typeof r)return wr({result:{error:Nn},context:{collectionName:r},stack:T});if(h&&!Object.values(zp).includes(h))return wr({result:{error:Nn},context:{gender:h},stack:T});if(m&&"object"!=typeof m)return wr({result:{error:Nn},context:{category:m},stack:T});const D={collectionValueProfiles:U,collectionValue:S,matchUpValue:y,scoreValue:v,setValue:w};if(!(Object.values(D).filter(Boolean).length||n||r||o||s||u))return wr({result:{error:ae},stack:T});if(Object.values(D).filter(Boolean).length>1)return wr({info:"Only one value assignment allowed per collectionDefinition",result:{error:Nn},stack:T});let b=Zf({drawDefinition:a,structureId:d,matchUpId:l,eventId:f,event:I});if(b.error)return wr({result:b,stack:T});const{matchUp:N,structure:R,tieFormat:M}=b,A=Yf(M),C=M?.collectionDefinitions.find((t=>t.collectionId===c)),O=A?.collectionDefinitions.find((t=>t.collectionId===c));if(!C)return wr({info:"source collectionDefinition",result:{error:On},context:{collectionId:c},stack:T});const F=S??y??v??w;if(U){const t=zf({matchUpCount:s??C?.matchUpCount??0,collectionValueProfiles:U});if(t.errors)return wr({result:{error:Nn},info:t.errors,stack:T})}else if(F&&!p(F))return wr({result:{error:Nn},info:"value is not an integer",context:{value:F},stack:T});const k=U&&(!C.collectionValueProfiles||(x=C.collectionValueProfiles,_=U,!(P(Object.keys(x),Object.keys(_)).length===Object.keys(x).length&&P(Object.values(x),Object.values(_)).length===Object.values(x).length)));var x,_;const L=[];if((p(S)&&C.collectionValue!==S||p(y)&&C.matchUpValue!==y||p(v)&&C.scoreValue!==v||p(w)&&C.setValue!==w||k)&&(O.collectionValueProfiles=void 0,O.collectionValue=void 0,O.matchUpValue=void 0,O.scoreValue=void 0,O.setValue=void 0,Object.assign(O,D),L.push({collectionId:c,...vr(D)})),(p(v)||p(w))&&O.collectionGroupNumber){const t=O.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:c,change:"collectionGroupNumber removed"})}const{aggregateValue:B,valueGoal:V}=Jf(A),G=vr({aggregateValue:B,valueGoal:V});if(G.aggregateValue===M?.winCriteria.aggregateValue&&G.valueGoal===M?.winCriteria.valueGoal||(A.winCriteria=G,L.push({collectionId:c,winCriteria:G})),p(n)&&C.collectionOrder!==n&&(O.collectionOrder=n,L.push({collectionId:c,collectionOrder:n})),r&&C.collectionName!==r&&(O.collectionName=r,L.push({collectionId:c,collectionName:r})),o&&C.matchUpFormat!==o&&(O.matchUpFormat=o,L.push({collectionId:c,matchUpFormat:o})),p(s)&&C.matchUpCount!==s&&(O.matchUpCount=s,L.push({collectionId:c,matchUpCount:s})),u&&C.matchUpType!==u)return wr({result:{error:Fn},context:{matchUpType:u},stack:T});m&&C.category!==m&&(O.category=m,L.push({collectionId:c,category:m})),h&&C.gender!==h&&(O.gender=h,L.push({collectionId:c,gender:h}));const q=vr(A);if(b=fh({tieFormat:q}),b.error)return wr({result:b,stack:T});if(!L.length)return wr({result:{...E,modifications:L}});if(M?.tieFormatName!==i?(q.tieFormatName=i,L.push({tieFormatName:i})):L.length&&(delete q.tieFormatName,L.push("tieFormatName removed: modifications without new tieFormatName")),b=function({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:n,structure:r,tieFormat:i,eventId:a,matchUp:o,event:s,uuids:c}){const u="updateTieFormat",d=e?.tournamentId;let p=0,l=0,m=0,f=0;const h=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 vh({from:e,to:h}).equivalent},U=Zf({drawDefinition:n})?.tieFormat,S=Zf({event:s})?.tieFormat;if(s&&a){for(const t of s.drawDefinitions??[])y({drawDefinition:t});s.tieFormat=Yf(i),f+=1}else if(o){if(!o.tieMatchUps)return wr({result:{error:Yt},stack:u});const e=g(o.tieMatchUps?.map((({collectionId:t})=>t))),r=vh({to:h,from:e}),{changes:a,changesArePossible:p,cannotChangeReaon:m}=wh({matchUp:o,check:r});if(r.equivalent){if(!yh({matchUp:o,updateInProgressMatchUps:t}))return wr({result:{error:Ue},info:"matchUp is IN_PROGRESS or COMPLETE",stack:u});o.tieFormat=Yf(i),f+=1}else{if(!p)return wr({context:{collectionMap:h,matchUpMap:e},result:{error:Lt},info:m||"specified changes not possible",stack:u});w({tieFormat:i,matchUp:o,changes:a,uuids:c})}l+=1,xs({eventId:s?.eventId,context:u,drawDefinition:n,tournamentId:d,matchUp:o})}else if(r){const t=U??S,e=v({inheritedTieFormat:t,structure:r})?.modifiedMatchUpsCount;e&&(l+=e,p+=1,f+=1);const a=!r.tieFormat||Uh({ancestor:r.tieFormat,descendant:i}).different;a&&(r.tieFormat=Yf(i),p+=1,f+=1),(e||a)&&n&&Ls({structureIds:[r.structureId],eventId:s?.eventId,drawDefinition:n})}else{if(!n)return{error:j};y({drawDefinition:n}),n.tieFormat=Yf(i),f+=1}return{modifiedStructuresCount:p,modifiedMatchUpsCount:l,addedMatchUpsCount:m,modifiedCount:f,...E,tieFormat:i};function y({drawDefinition:t}){const e=t.structures||[],n=[];for(const t of e){if(t.tieFormat)continue;const e=S,r=v({inheritedTieFormat:e,structure:t})?.modifiedMatchUpsCount;if(r){p+=1,l+=r;const e=t.structureId;n.push(e)}}return Ls({structureIds:n,eventId:s?.eventId,drawDefinition:t}),n.length}function v({inheritedTieFormat:r,structure:o}){let s=0;const d=Yp({matchUpFilters:{matchUpTypes:[Qs]},structure:o})?.matchUps||[];for(const o of d){const d=yh({matchUp:o,updateInProgressMatchUps:t});let p=!1;const l=vh({from:g(o.tieMatchUps?.map((({collectionId:t})=>t))),to:h});if(l.equivalent)o.tieFormat&&I(o)&&d&&(o.tieFormat=Yf(i),p=!0);else{const{changes:t,changesArePossible:e}=wh({matchUp:o,check:l});if(e&&!o.tieFormat)w({changes:t,matchUp:o,tieFormat:i,uuids:c});else{if(!r)return wr({result:{error:Gt},stack:u});(!o.tieFormat||Uh({ancestor:r,descendant:o.tieFormat}).different)&&(o.tieFormat=r,p=!0)}}p&&(s+=1,xs({tournamentId:e?.tournamentId,drawDefinition:n,context:u,eventId:a,matchUp:o}))}return{modifiedMatchUpsCount:s}}function w({uuids:t,matchUp:e,tieFormat:r,changes:i}){e.tieFormat=Yf(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(Ua("collectionPosition"))),a=r.collectionDefinitions.find((t=>t.collectionId===n.collectionId)),o=gh({matchUpsLimit:n.countChange,collectionPositionOffset:i,collectionDefinition:a,uuids:t});s.push(...gi(o,!1,!0)),m+=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&&Fs({matchUps:s,drawDefinition:n,tournamentId:d,eventId:a}),o.length&&ks({matchUpIds:o,action:"updateTieFormat",drawDefinition:n,tournamentId:d,eventId:a}),{matchUpIdsRemoved:o,matchUpsAdded:s}}}({tieFormat:q,updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:a,structure:R,eventId:f,matchUp:N,event:I}),!b.error){const{appliedPolicies:t}=Dc({tournamentRecord:e});if(t?.audit?.[ua]){Th({drawDefinition:a,auditData:vr({collectionDefinition:O,drawId:a?.drawId,action:T,structureId:d,matchUpId:l,eventId:f})})}}return wr({result:{...b,modifications:L},stack:T})}function Dh({tournamentRecord:t,drawDefinition:e,drawPositions:n,structureId:r,event:i}){if(!e)return{error:j};if(!r)return{error:It};if(2!==n?.length)return{error:Nn,drawPositions:n};const a=xc({drawDefinition:e}),{matchUps:o}=Jp({inContext:!0,drawDefinition:e,matchUpsMap:a}),{structure:s}=ts({drawDefinition:e,structureId:r});if(!s)return{error:Ut};let c;if(c=s.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{...E};if(2===s.filter((({qualifier:t})=>t)).length)return{...E};Nf({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)bh({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:s,matchUpsMap:i,structure:a,event:o});else{const t=gi(s,!1,!0);s.forEach(((e,n)=>{const r=t[1-n].participantId;e.qualifier=t[1-n].qualifier,e.participantId=r}))}return{...E}}({inContextDrawMatchUps:o,tournamentRecord:t,drawDefinition:e,drawPositions:n,matchUpsMap:a,structure:s,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:Nn,structure:a,info:"Missing positionAssignments"};if(2===s.filter((({bye:t})=>t)).length)return{...E};if(2===s.filter((({qualifier:t})=>t)).length)return{...E};const c=s.some((({qualifier:t})=>t));return s.some((({bye:t})=>t))&&!c?bh({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;return{[n]:{...r[1-e],drawPosition:n}}})));return a.positionAssignments=a.positionAssignments.map((t=>s[t.drawPosition]||t)),Nf({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:i,assignments:r,structure:a,event:o}),{...E}}({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:s,matchUpsMap:i,structure:a,event:o})}({inContextDrawMatchUps:o,tournamentRecord:t,drawDefinition:e,drawPositions:n,matchUpsMap:a,structure:s,event:i}),c.error)return c;js({structure:s,drawPositions:n});if(Gs({drawDefinition:e,positionAction:{name:"swapDrawPositionAssignments",drawPositions:n,structureId:r}}),Vs({tournamentId:t?.tournamentId,drawDefinition:e,structure:s,event:i}),i.eventType===ad){const r=Yp({matchUpFilters:{matchUpTypes:[Xs]},inContext:!0,structure:s}).matchUps.filter((t=>t.drawPositions?.some((t=>n.includes(t))))),a=Yp({structure:s,matchUpFilters:{matchUpTypes:[Xs]}}).matchUps;r.forEach((r=>{(r.sides||[]).forEach((o=>{const s=o?.drawPosition;if(n.includes(s)){const n=o.participantId,c=a.find((({matchUpId:t})=>t===r.matchUpId)),u=r?.sides?.reduce(((t,e,n)=>e.drawPosition===s?n:t),void 0);rf({inContextTargetMatchUp:r,drawPositionSideIndex:u,teamParticipantId:n,tournamentRecord:t,drawDefinition:e,matchUp:c,event:i})}}))}))}return Ls({drawDefinition:e,structureIds:[r]}),{...E}}function bh({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=ym({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:l,matchUpsMap:i});return m.error?m:(m=ym({drawPosition:p,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:l,matchUpsMap:i}),m.error?m:(bl({drawPosition:p,tournamentRecord:e,drawDefinition:n,structureId:l,matchUpsMap:i,event:o}),m=Rf({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:l,participantId:d,matchUpsMap:i,event:o}),m.error?m:{...E}))}function Nh({drawDefinition:t,structureId:e}){if(!t)return{error:j};const{structure:n}=ts({drawDefinition:t,structureId:e}),r=(t?.links||[]).filter((t=>t.source?.structureId===e)).map((t=>t.target?.structureId));return{playoffStructures:(t?.structures||[]).filter((t=>r.includes(t.structureId))),structure:n}}function Rh({withStageGrouping:t,stageSequences:e,stageSequence:n,roundTarget:r,stages:i,event:a,stage:o}){if(!a)return{error:Tt};const s={},c=[];for(const u of a.drawDefinitions||[]){const{structures:a,stageStructures:d}=es({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 Mh(t){if(!t?.drawDefinition)return!1;const e=Kp(t),n=e?.includesTeamMatchUps;let{completedMatchUps:r,pendingMatchUps:i,upcomingMatchUps:a}=e||{};n&&(r=r?.filter((({matchUpType:t})=>t===Qs)),i=i?.filter((({matchUpType:t})=>t===Qs)),a=a?.filter((({matchUpType:t})=>t===Qs)));return!!(r?.length&&!i?.length&&!a?.length)}function Ah({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=Ah({accessors:a,significantCharacters:t,value:e});r.push(...n)}))}else if(n=n[i],a.length){const e=Ah({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 Eh({policyAttributes:t,idCollections:e,participants:n,participant:r}){if(!Array.isArray(t))return{error:Xt};if(!r)return{error:Re};const i=[];t.forEach((t=>{const{directive:a,groupings:o,key:s,significantCharacters:c}=t||{};if(s){const t=s.split(".");i.push(...Ah({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:m(i)}}function Ch({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}=Eh({participants:e,policyAttributes:n,idCollections:r,participant:a});return{...t,values:o}}))}function Oh({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 Fh(t){const{unfilledPositions:e,chunkedDrawPositions:n}=t,r=Oh(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=kh(e);return!t.includes(n)}}(n),a=n.filter((t=>!i.includes(t))).filter((t=>{const e=kh(t);return!r[e]?.includesGroupsToAvoid}));return{unassigned:n,unpaired:i,pairedNoConflict:a}}))}function kh(t){return Number(t%2?t+1:t-1)}function xh({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=Oh(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}):Fh({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 _h({positionAssignments:t,participantIds:e}){const n=t.map((t=>t.participantId));return e.filter((t=>!n.includes(t)))}function Lh({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=_h({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=v(n?s:Object.keys(a));return{participantId:(i=t&&a[i]?.length?i:c)&&a[i]?v(a[i]):v(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=xh({positionAssignments:t,isRoundRobin:c,selectedParticipantGroups:m,participantIdGroups:n,drawPositionChunks:r,unfilledPositions:d}),{unassigned:h,unpaired:g,pairedNoConflict:I}=f,U=I?.length&&I[0],S=g?.length&&g[0],w=a&&U?U:S,T=a?S:U,P=w?.length&&w||T?.length&&T;let D;if(P?.length){const t=y(P);D=y(t)}else{const t=y(h[0]);D=y(t)}return{newGroupKey:l,selectedParticipantId:p,targetDrawPosition:D}}function Bh({isRoundRobin:t,groupedParticipants:e}){const n=[];return t?e.forEach((t=>{const e=t.map((t=>t.drawPosition)),{uniqueMatchUpGroupings:r}=sf({drawPositions:e}),i=Object.assign({},...t.map((t=>({[t.drawPosition]:t}))));r.forEach((e=>{b(i[e[0]].values||[],i[e[1]].values||[])&&(n.push(e),t.conflict=!0)}))})):e.forEach((t=>{b(t[0]?.values||[],t[1]?.values||[])&&(n.push(t),t.conflict=!0)})),n}function Vh({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=Bh({isRoundRobin:i,groupedParticipants:[[r,o]]}),c=t.find((t=>t.drawPosition===e)),u=Bh({isRoundRobin:i,groupedParticipants:[[c,o]]});return!s.length&&!u.length}));if(o.length)return{drawPosition:r.drawPosition,possibleDrawPositions:o}})).filter(Boolean)})).flat(1)}function jh(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=gi(e,!1,!0).filter((t=>!t.qualifier)),f=e.filter((t=>!t.participantId&&(!t.bye||i?.includes(t.drawPosition)))).map((t=>t.drawPosition));w(0,r).forEach((()=>{const{newGroupKey:e,selectedParticipantId:n,targetDrawPosition:r}=Lh({...t,candidatePositionAssignments:m,allGroups:c,groupKey:d});d=e,m.forEach((t=>{t.drawPosition===r&&(t.participantId=n)}))}));let h=Ch({candidatePositionAssignments:m,participantsWithGroupings:n,policyAttributes:o,idCollections:s}),g=N(h,p),I=Bh({groupedParticipants:g,isRoundRobin:l}),U=0;for(;U<20&&I.length;){const t=Vh({positionedParticipants:h,potentialDrawPositions:f,avoidanceConflicts:I,drawPositionGroups:a,isRoundRobin:l});if(t.length){const e=Gh({candidatePositionAssignments:m,swapOptions:t});e.error&&console.log({result:e}),h=Ch({candidatePositionAssignments:m,participantsWithGroupings:n,policyAttributes:o,idCollections:s}),g=N(h,p),I=Bh({groupedParticipants:g,isRoundRobin:l}),U++}else U=20}return m.forEach((t=>{if(t.bye&&t.participantId){const t=pt;u.push(t)}if(t.qualifier&&t.participantId){const t=pt;u.push(t)}})),{positionAssignments:m,conflicts:I.length,groupedParticipants:g,errors:u}}function Gh({candidatePositionAssignments:t,swapOptions:e}){const n=y(e);if(!n)return{error:{message:"No swap options"}};const r=n.drawPosition,i=y(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),{...E}}function qh({provisionalPositioning:t,unseededParticipantIds:n,inContextDrawMatchUps:i,unseededByePositions:a,tournamentRecord:s,drawDefinition:c,seedBlockInfo:u,participants:d,matchUpsMap:p,structureId:l,avoidance:m,drawSize:f,event:h}){if(!m)return{error:Zt};const{candidatesCount:g=1,policyAttributes:I,targetDivisions:U}=m;let{roundsToSeparate:S}=m;const y="randomUnseededSeparation",{structure:v}=ts({drawDefinition:c,structureId:l}),{matchUps:T}=Yp({provisionalPositioning:t,matchUpsMap:p,structure:v,event:h});if(U&&r(U)&&!S){const t=function(t){if(!r(t))return!1;let e=t,n=1;for(;2!==e;)n+=1,e/=2;return n}(U)||0,e=T.reduce(((t,e)=>e.roundNumber>t?e.roundNumber:t),0);S=e<t?1:e-t+1}const{positionAssignments:P}=is({structure:v}),D=mc({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:d}).participantsWithGroupings,b=P?.filter((t=>!t.participantId)),R=P?.map((t=>t.drawPosition)),M=v?.structureType===mo,A=M?{structure:v,matchUps:T,allDrawPositions:R,roundsToSeparate:S}:{matchUps:T,allDrawPositions:R,roundsToSeparate:S},{drawPositionGroups:C,drawPositionChunks:O}=M?function(t){const{structure:{structures:e}}=t,n=e.map((t=>t.positionAssignments.map((t=>t.drawPosition))));return{drawPositionGroups:n,drawPositionChunks:[n]}}(A):function({allDrawPositions:t,roundsToSeparate:n,matchUps:r}){const i=r.filter((t=>1===t.roundNumber)).map((t=>t.drawPositions)),a=i.flat().sort(e),s=Math.max(...a),c=t.filter((t=>t>s)),u=a.length,d=w(2===u?1:2,u).filter((t=>t===o(t))),p=d.slice(0,n||d.length).reverse(),l=p.map((t=>N(a,t)));c.length&&console.log({fedDrawPositions:c});return{drawPositionGroups:i,drawPositionChunks:l}}(A),F={groupParticipants:d.filter((t=>t.participantType===cc)).map((t=>t.participantId)),teamParticipants:d.filter((t=>t.participantType===dc)).map((t=>t.participantId)),pairParticipants:d.filter((t=>t.participantType===uc)).map((t=>t.participantId))},k=function({targetParticipantIds:t,policyAttributes:e,idCollections:n,participants:r}){if(!Array.isArray(e))return{error:Xt};if(!Array.isArray(r))return{error:Me};const i={};return t.forEach((t=>{const a=r.find((e=>e.participantId===t)),{values:o}=Eh({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:n,policyAttributes:I,idCollections:F,participants:d});if(k.error)return wr({result:k,stack:y});const x=Object.assign({},...n.map((t=>{const e=Object.keys(k).filter((e=>(k[e]??[]).includes(t)));return{[t]:e}}))),_=_h({participantIds:n,positionAssignments:P});if(_.length>(b?.length||0))return{error:Ke};let L;const B=_.length,V=w(0,g).map((()=>jh({initialPositionAssignments:P,participantsWithGroupings:D,unseededParticipantIds:n,opponentsToPlaceCount:B,pairedPriority:!1,unseededByePositions:a,participantIdGroups:x,drawPositionChunks:O,drawPositionGroups:C,policyAttributes:I,idCollections:F,allGroups:k,drawSize:f})));if(L=V.reduce(((t,e)=>!t||(e.conflicts||0)<(t.conflicts||0)?e:t),void 0),!L||L.conflicts){const t=w(0,g).map((()=>jh({initialPositionAssignments:P,participantsWithGroupings:D,unseededParticipantIds:n,opponentsToPlaceCount:B,pairedPriority:!0,unseededByePositions:a,participantIdGroups:x,drawPositionChunks:O,drawPositionGroups:C,policyAttributes:I,idCollections:F,allGroups:k,drawSize:f})));L=V.concat(...t).filter((t=>!t.errors?.length)).reduce(((t,e)=>!t||(e.conflicts||0)<(t.conflicts||0)?e:t),void 0)}if(!L)return{error:vn};const j=(rs({structure:v})?.positionAssignments??[]).filter((t=>t.participantId)).map((t=>t.participantId)),G=L.positionAssignments.filter((t=>!j.includes(t.participantId)));for(const t of G)if(t.bye){const e=bl({tournamentRecord:s,drawDefinition:c,seedBlockInfo:u,structureId:l,matchUpsMap:p,event:h,...t});if(e.error)return wr({result:e,stack:y})}else if(t.participantId){const e=Rf({automaticPlacement:!0,inContextDrawMatchUps:i,tournamentRecord:s,drawDefinition:c,seedBlockInfo:u,structureId:l,matchUpsMap:p,event:h,...t});if(e.error)return wr({result:e,stack:y,context:{assignment:t}})}return{...E}}function $h({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}=ts({drawDefinition:a,structureId:u})),u||({structureId:u}=d);const{positionAssignments:m}=is({structure:d}),{seedAssignments:h}=lu({provisionalPositioning:t,drawDefinition:a,structure:d}),g=h?.map((t=>t.participantId)).filter(Boolean),{stage:I,stageSequence:U}=d,S=I===Qa?Mr({element:d,name:ra})?.extension?.value:void 0,y=pu({provisionalPositioning:t,drawDefinition:a,stageSequence:U,entryStatuses:au,structureId:u,roundTarget:S,stage:I}),v=y.filter((t=>!g?.includes(t.participantId))).map((t=>t.participantId)),w=m?.filter((t=>!t.participantId&&!t.bye&&!t.qualifier)).map((t=>t.drawPosition));if(!r&&v.length>(w?.length||0))return wr({result:{error:Ke},context:{unseededParticipantsCount:v.length,unfilledDrawPositionsCount:w?.length},stack:"positionUnseededParticipants"});const{appliedPolicies:T}=Dc({tournamentRecord:i,drawDefinition:a,event:l});let P=T?.[Ri];if(d.stage===no){const t=y.reduce(((t,e)=>(t[e.groupingValue]||(t[e.groupingValue]=[]),t[e.groupingValue].push(e.participantId),t)),{});Object.keys(t).length&&(P||(P={policyName:"Playoff Avoidance"}),P.policyAttributes||(P.policyAttributes=[]),P.policyAttributes.push({groupings:t}))}return P&&s?qh({provisionalPositioning:t,unseededParticipantIds:v,inContextDrawMatchUps:e,unseededByePositions:n,tournamentRecord:i,drawDefinition:a,seedBlockInfo:o,participants:s,matchUpsMap:c,structureId:u,avoidance:P,drawSize:p,entries:y}):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?f(r):r.reverse();for(const r of e){const e=l.pop();if(!i||e){const i=Rf({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 wr({result:i,stack:"randomUnseededDistribution"})}}return{...E}}({provisionalPositioning:t,unseededParticipantIds:v,inContextDrawMatchUps:e,unfilledDrawPositions:w,multipleStructures:r,tournamentRecord:i,drawDefinition:a,seedBlockInfo:o,structureId:u,matchUpsMap:c,drawSize:p,event:l})}function Wh(t){const e=t.structure??ts(t).structure,r="positionQualifiers",i=[];if(e.stage===to)return wr({result:{error:At},stack:r});const{unplacedRoundQualifierCounts:a,positionAssignments:o,roundDrawPositions:s}=function({drawDefinition:t,structure:e,structureId:r}){e||({structure:e}=ts({drawDefinition:t,structureId:r}));r||({structureId:r}=e);const{positionAssignments:i}=is({structure:e}),{stage:a,stageSequence:o}=e,{qualifiersCount:s,roundQualifiersCounts:c}=Ql({drawDefinition:t,stageSequence:o,structureId:r,stage:a}),u=(c?Object.keys(c):[]).map((t=>n(t))),{matchUps:d}=Yp({structure:e}),{roundProfile:p}=vc({matchUps:d}),l=Object.assign({},...u.filter((t=>p?.[t])).map((t=>({[t]:p?.[t]?.drawPositions?.filter(Boolean)??[]})))),m=i?.filter((t=>t.qualifier)).map((t=>t.drawPosition)),f=s-(m?.length??0),h=m?.length,g=Object.assign({},...u.map((t=>{const e=i?.filter((e=>e.qualifier&&l[t]?.drawPositions?.includes(e.drawPosition))).map((t=>t.drawPosition));return{[t]:(c?.[t]??0)-(e?.length??0)}})));return{unplacedRoundQualifierCounts:g,unplacedQualifiersCount:f,placedQualifiersCount:h,roundQualifiersCounts:c,positionAssignments:i,roundDrawPositions:l,qualifiersCount:s}}(t);for(const t of Object.keys(a)){const e=o?.filter((e=>s[t].includes(e.drawPosition)&&!e.participantId&&!e.qualifier&&!e.bye)).map((t=>t.drawPosition));if(a[t]>(e||0))return wr({result:{error:Ye},context:{unfilledDrawPositions:e},stack:r});w(0,a[t]).forEach((()=>{const t=y(e);i.push(t),o?.forEach((e=>{e.drawPosition===t&&(e.qualifier=!0,delete e.participantId,delete e.bye)}))}))}return{...E,qualifierDrawPositions:i}}function Hh({orderedSortedFirstRoundSeededDrawPositions:t,validSeedBlocks:e,byesToPlace:n}){const r=[];e.forEach((e=>{if(n-r.length>e.drawPositions.length)r.push(...e.drawPositions);else{const n=Yh(N(e.drawPositions,2));let i,a=t[r.length];for(;i=zh(n,a);)r.push(i),a=t[r.length]}}));const i=r.map((t=>Array.isArray(t)?f(t):t)).flat(1/0);if(c(n)){if(e.map((t=>t.seedNumbers[0])).includes(n))return t}return i}function zh(t,e){if(Array.isArray(t)&&2!==t.length)return t.pop();if(!Array.isArray(t[0]))return t.includes(e)?t.indexOf(e)?t.pop():t.shift():Math.round(Math.random())?t.pop():t.shift();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 zh(e?n:t[Math.round(Math.random())],e)}return zh(n<r?t[1]:t[0],e)}function Yh(t){const e=Math.floor(t.length/2);return t.length>2?[Yh(t.slice(0,e)),Yh(t.slice(e))]:t}function Kh({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:n,drawDefinition:r,seedingProfile:i,seedBlockInfo:a,byesToPlace:o,structure:s}){a||(a=gf({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}=is({structure:n}),{seedAssignments:i}=lu({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})??[],f=m([].concat(...e.map((t=>t.drawPositions)))),h=l.filter((t=>f.includes(t.drawPosition))),g=(t,e)=>of(t.seedValue)-of(e.seedValue),I=p.reduce(((t,e)=>{const n=h.filter((t=>e.drawPositions?.includes(t.drawPosition))).sort(g);return t.concat(...n)}),[]).map((t=>t.drawPosition)),U=Hh({orderedSortedFirstRoundSeededDrawPositions:I,validSeedBlocks:p,byesToPlace:o});return{strictSeedOrderByePositions:Jh({orderedSeedDrawPositions:I,relevantMatchUps:e}).slice(0,o),blockSeedOrderByePositions:Jh({orderedSeedDrawPositions:U,relevantMatchUps:e}).slice(0,o),isLuckyStructure:u,positionedSeeds:l,isContainer:d,isFeedIn:c}}function Jh({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 Zh({provisionalPositioning:t,tournamentRecord:n,appliedPolicies:r,drawDefinition:i,seedBlockInfo:a,seedingProfile:o,matchUpsMap:s,structureId:c,structure:u,seedLimit:d,seedsOnly:p,event:l}){u||({structure:u}=ts({drawDefinition:i,structureId:c})),c||(c=u?.structureId);const h=!(u?.structures??u?.stage===Qa),{byesCount:g,placedByes:I,relevantMatchUps:U}=function({provisionalPositioning:t,drawDefinition:e,matchUpsMap:n,structure:r,event:i}){const{matchUps:a,roundMatchUps:o}=Yp({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=pu({entryStatuses:ou,provisionalPositioning:t,drawDefinition:e,stageSequence:m,structureId:p,stage:l}),{qualifiersCount:h}=Ql({provisionalPositioning:t,drawDefinition:e,stageSequence:m,structureId:p,stage:l}),g=f.length+h,{positionAssignments:I,unassignedPositions:U}=is({structure:r}),S=U?.map((t=>t.drawPosition)),y=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=>S?.includes(t))),T=I?.length;let P=T?T-g:0;return P>d&&1===r.stageSequence&&r.stage!==to&&(P=d),{placedByes:y,byesCount:P,relevantMatchUps:u,placedByePositions:v,roundMatchUps:o,positionsToAvoidDoubleBye:w}}({provisionalPositioning:t,drawDefinition:i,matchUpsMap:s,structure:u,event:l}),S=g-(I||0);if(S<=0)return{...E};const{strictSeedOrderByePositions:y,blockSeedOrderByePositions:v,isLuckyStructure:w,isFeedIn:T}=Kh({provisionalPositioning:t,relevantMatchUps:U,appliedPolicies:r,drawDefinition:i,seedingProfile:o,seedBlockInfo:a,byesToPlace:S,structure:u}),P=u?.structureType&&[mo,lo].includes(u.structureType)&&r?.seeding?.containerByesIgnoreSeeding,D=h&&v?.length?v:y;let{unseededByePositions:b}=function({provisionalPositioning:t,seedOrderByePositions:n,isLuckyStructure:r,appliedPolicies:i,drawDefinition:a,seedLimit:o,structure:s,isFeedIn:c}){const u=i?.seeding?.seedingProfile,d=s.stage===Qa,{positionAssignments:p}=is({structure:s}),l=p?.filter((t=>t.participantId)).map((t=>t.drawPosition)),{matchUps:h,roundMatchUps:g}=Yp({provisionalPositioning:t,matchUpFilters:{isCollectionMatchUp:!1},structure:s}),I=g?.[1]||[],U=s.structureType===mo?h:I,S=m([].concat(...U.map((t=>t.drawPositions)))),y=Math.min(...S)-1,v=l?.filter((t=>S.includes(t))),w=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=f(n),[u,d]=!i||s?[n[o],n[1-o]]:[c[0],c[1]];return{greaterHalf:u,lesserHalf:d}},T=t=>{const{greaterHalf:e,lesserHalf:n}=w(t),{greaterHalf:r,lesserHalf:i}=w(e),a=f(r.flat(1/0)).pop();return{newlyFilteredChunks:[...n,...i,r.flat().filter((t=>t!==a))],drawPosition:a}},P=t=>!v?.includes(t),D=t=>{let n=N(t.sort(e),Math.ceil(t.length/4)).map((t=>t.filter(P)));const r=[].concat(...n.flat(1/0)).length,i=[];for(let t=0;t<r;t++){const{newlyFilteredChunks:t,drawPosition:e}=T(n);i.push(e),n=t}return i},{validSeedBlocks:b}=gf({provisionalPositioning:t,allPositions:!0,appliedPolicies:i,drawDefinition:a,structure:s}),R=b?.map((t=>t.drawPositions?.map((t=>t+y))));let M;if(c){const t=S.length,{seedBlocks:e}=mf({cluster:yf(u)===uo,participantsCount:t});M=e.map((t=>t.map((t=>t+y)))).map(D).filter((t=>t.length))}else M=d?R?.map((t=>t.filter(P))):R?.map(D).filter((t=>t.length));const A=U.map((t=>t.drawPositions)).map((t=>t?.sort(((t,e)=>t-e)))).filter((t=>t?.[0]+1===t?.[1])),E=t=>A.reduce(((e,n)=>n.includes(t)?n.reduce(((e,n)=>n!==t?n:e),void 0):e),void 0);let C=M.map((t=>t.map(E))).flat(1/0).filter(P).filter((t=>!n.includes(t))).filter(Boolean);if(d&&!s.structures){const t=o%4,e=C.slice(0,t),n=g[s.roundLimit]?.length,r=N(C.slice(t),n).map(f).flat();C=e.concat(r)}return{unseededByePositions:C}}({provisionalPositioning:t,seedOrderByePositions:D,isLuckyStructure:w,appliedPolicies:r,drawDefinition:i,seedLimit:d,structure:u,isFeedIn:T});let R=[].concat(...D);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=[])}P&&(R=f(R),Qn({ignoreSeededByes:P})&&console.log({byePositions:R}));const M=R.slice(0,S);for(const e of M){const r=bl({provisionalPositioning:t,tournamentRecord:n,drawDefinition:i,drawPosition:e,matchUpsMap:s,structureId:c,structure:u,event:l});if(r?.error)return r}return{...E,unseededByePositions:b,byeDrawPositions:M}}function Xh({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}=ts({drawDefinition:a,structureId:d})),d||(d=l?.structureId),r||(r=Dc({drawDefinition:a}).appliedPolicies),!i){const e=l&&gf({provisionalPositioning:t,appliedPolicies:r,drawDefinition:a,seedingProfile:o,structure:l});e?.error&&h.push(e.error),i=e?.validSeedBlocks}return w(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}=Sf({provisionalPositioning:t,randomize:!0,drawDefinition:r,seedingProfile:i,seedBlockInfo:a,structureId:s,event:u}),{appliedPolicies:l}=Dc({drawDefinition:r}),{avoidance:m}=l??{};const f=[];for(const o of d){const d=p.pop();if(!d)return{error:tt};f.push(d);const l=Rf({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{...E,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}:{...E,seedPositions:f}}function Qh({applyPositioning:t=!0,provisionalPositioning:e,inContextDrawMatchUps:n,multipleStructures:r,placeByes:i=!0,tournamentRecord:a,appliedPolicies:o,placementGroup:s,drawDefinition:c,seedingProfile:u,structureId:d,matchUpsMap:p,seedLimit:l,seedsOnly:m,drawType:f,drawSize:h,event:g}){const I=[];t||(Jn.disableNotifications(),c=gi(c,!1,!0));const U=e=>(t||nr(),wr({result:e,stack:"automatedPositioning"})),S=ts({drawDefinition:c,structureId:d});if(S.error)return U(S);const y=S.structure;if(!y)return{error:Ut};o||(o=Dc({drawDefinition:c,structure:y,event:g})?.appliedPolicies);const{qualifiersCount:v}=Ql({stageSequence:y.stageSequence,provisionalPositioning:e,stage:y.stage,drawDefinition:c,structureId:d}),w=au,T=pu({stageSequence:y.stageSequence,provisionalPositioning:e,stage:y.stage,placementGroup:s,drawDefinition:c,entryStatuses:w,structureId:d});if(!T?.length&&!v)return P={...E},t||nr(),P;var P;p=p??xc({drawDefinition:c}),n||({matchUps:n}=Jp({inContext:!0,drawDefinition:c,matchUpsMap:p}));let D=[];const b=gf({provisionalPositioning:e,appliedPolicies:o,drawDefinition:c,seedingProfile:u,structure:y});if(b.error)return b;const{validSeedBlocks:N}=b;I.push({validSeedBlocks:N});const R=a?Zl({withIndividualParticipants:!0,tournamentRecord:a})?.participants:[];if(yf(y.seedingProfile||u)===po){let t=i?Zh({provisionalPositioning:e,tournamentRecord:a,appliedPolicies:o,drawDefinition:c,seedBlockInfo:b,matchUpsMap:p,structure:y,seedLimit:l,seedsOnly:m,event:g}):void 0;if(t?.error)return U(t);D=t.unseededByePositions,I.push({action:"positionByes",unseededByePositions:D});if(t=Xh({seedingProfile:y.seedingProfile?{positioning:y.seedingProfile}:u,provisionalPositioning:e,inContextDrawMatchUps:n,tournamentRecord:a,appliedPolicies:o,validSeedBlocks:N,drawDefinition:c,seedBlockInfo:b,participants:R,matchUpsMap:p,structure:y,event:g}),t.error)return U(t);I.push({seedPositions:t.seedPositions,action:"positionSeedBlocks"})}else{if(f!==Ao){const t=Xh({seedingProfile:y.seedingProfile?{positioning:y.seedingProfile}:u,provisionalPositioning:e,inContextDrawMatchUps:n,tournamentRecord:a,appliedPolicies:o,validSeedBlocks:N,drawDefinition:c,seedBlockInfo:b,participants:R,matchUpsMap:p,structure:y,event:g});if(t.error)return U(t);I.push({action:"positionSeedBlocks",seedPositions:t.seedPositions})}const t=i?Zh({provisionalPositioning:e,tournamentRecord:a,appliedPolicies:o,drawDefinition:c,seedBlockInfo:b,matchUpsMap:p,structure:y,seedLimit:l,seedsOnly:m,event:g}):void 0;if(t?.error)return U(t);D=t?.unseededByePositions,I.push({action:"positionByes",byeDrawPositions:t?.byeDrawPositions,unseededByePositions:D})}const M={};if(!m){let t=Wh({inContextDrawMatchUps:n,tournamentRecord:a,appliedPolicies:o,validSeedBlocks:N,drawDefinition:c,seedBlockInfo:b,participants:R,matchUpsMap:p,structure:y});if(t.error)return U(t);if(t.conflicts&&(M.qualifierConflicts=t.conflicts),I.push({action:"positionQualifiers",qualifierDrawPositions:t.qualifierDrawPositions}),t=$h({provisionalPositioning:e,inContextDrawMatchUps:n,unseededByePositions:D,multipleStructures:r,tournamentRecord:a,drawDefinition:c,seedBlockInfo:b,participants:R,matchUpsMap:p,structureId:d,structure:y,drawSize:h,event:g}),t.error)return U(t);t.conflicts&&(M.unseededConflicts=t.conflicts),I.push({action:"positionUnseededParticipants"})}const{positionAssignments:A}=rs({drawDefinition:c,structure:y});return Ls({drawDefinition:c,structureIds:[d]}),t||nr(),{positionAssignments:A,conflicts:M,...E,positioningReport:I}}function tg(t){const{applyPositioning:e=!0,provisionalPositioning:n,tournamentRecord:r,drawDefinition:i,seedingProfile:a,structureId:o,placeByes:s,seedsOnly:c,event:u}=t;if(!u)return{error:Pt};if(!i)return{error:q};if(!Mh({drawDefinition:i,structureId:o})&&!n)return{error:W};const d=Nh({drawDefinition:i,structureId:o}).playoffStructures?.sort(((t,e)=>Qo(t)-Qo(e))),p=[],l=[];if(d)for(const t of d){const{structureId:o}=t,u=Qh({structureId:o,provisionalPositioning:n,applyPositioning:e,tournamentRecord:r,drawDefinition:i,seedingProfile:a,placeByes:s,seedsOnly:c});if(u.error)return u;u.positionAssignments&&p.push({positionAssignments:u.positionAssignments,structureId:o}),u.positioningReport&&l.push(u.positioningReport)}return{...E,structurePositionAssignments:p,positioningReports:l}}function eg({drawDefinition:t,matchUpsMap:e,structureId:n}){const r=ts({drawDefinition:t,structureId:n});if(r.error)return wr({result:r});const{matchUps:i}=Yp({structure:r.structure,matchUpsMap:e});return{...vc({matchUps:i}),matchUps:i,matchUpsMap:e}}function ng({finishingPositions:t,drawDefinition:e,structureId:n}){const{roundProfile:r}=eg({drawDefinition:e,structureId:n}),i=r&&Object.keys(r);return i?.reduce(((e,n)=>(rg(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 w(n,(r||n)+1).includes(t)})({position:t,rangeDefinition:r})&&(e[t]={roundNumber:n})}))})),e)),{})}function rg(t){return[m(t?.finishingPositionRange?.loser||[]),m(t?.finishingPositionRange?.winner||[])]}function ig(t){return rg(t).map((t=>w(t[0],t[1]&&t[1]+1||t[0]+1)))}function ag({drawDefinition:t,structureIds:n,matchUpsMap:r}){if(n&&!Array.isArray(n))return{error:Nn,context:{structureIds:n}};if(!t)return{error:j};const i=(n=n??(t.structures??[]).filter((t=>t.stage!==Qa)).map((({structureId:t})=>t))).map((e=>{const{roundProfile:n}=eg({drawDefinition:t,matchUpsMap:r,structureId:e}),i=n&&Object.values(n);return i?.map(ig).flat()})).flat(),a=i.filter((t=>1===t?.length)).sort(e).flat();return{positionsNotPlayedOff:m(i.flat()).filter((t=>!a.includes(t))),positionsPlayedOff:a}}function og({excludeRoundNumbers:t=[],playoffPositions:r=[],drawDefinition:i,structureId:a}){if(!i)return{error:j};if(!a)return{error:It};if(!r)return{error:ae,info:"missing playoffPositions"};const o=ag({drawDefinition:i});if(o.error)return o;const s=o.positionsPlayedOff,c=ng({finishingPositions:r.filter((t=>!s.includes(t))),drawDefinition:i,structureId:a}),u=Object.values(c).reduce(((t,e)=>t.includes(e.roundNumber)?t:t.concat(e.roundNumber)),[]).map((t=>n(t))).filter((e=>!t.includes(e))),d=ng({finishingPositions:s,drawDefinition:i,structureId:a}),p=d?Object.values(d).reduce(((t,e)=>t.includes(e.roundNumber)?t:t.concat(e.roundNumber)),[]).map((t=>n(t))):[],l=u.filter((t=>!p.includes(t))).sort(e),{roundProfile:m}=eg({drawDefinition:i,structureId:a}),f=l.map((t=>{const e=m?.[t].finishingPositionRange.loser,[n,r]=e??[0,0];return w(n,(r||n)+1)})).flat().sort(e),{playoffRoundsRanges:h}=function({playoffSourceRounds:t,roundProfile:e}){const n=t.map((t=>{const n=e[t].finishingPositionRange.loser,[r,i]=n,a=w(r,(i||r)+1);return{finishingPositionRange:n.join("-"),finishingPositions:a,roundNumber:t}}));return{playoffRoundsRanges:n}}({playoffSourceRounds:l,roundProfile:m}),g=[...l,...p];return{playoffPositionsReturned:f,playedOffSourceRounds:p,playoffRoundsRanges:h,playoffSourceRounds:l,sourceRounds:g,roundProfile:m}}function sg({drawDefinition:t,structureId:e}){if(!t)return{error:j};const{matchUps:n,matchUpsMap:r}=Ul({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:i,positionsPlayedOff:a}=ag({drawDefinition:t,matchUpsMap:r}),{structures:o}=es({drawDefinition:t}),s=o.filter((t=>!e&&t.stage!==eo||t.structureId===e)),c={};for(const e of s){const r=e?.structureId,a=cg({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 cg({playoffPositions:t,drawDefinition:n,structure:r,matchUps:i}){const a=r?.structureId,{links:o}=Ic({drawDefinition:n,structureId:a});if(r.structureType===mo||r.structures){const t=rs({structure:r})?.positionAssignments?.length,e=r.structures.length,s=(t??0)/e,c=o.source?.flatMap((({source:t})=>t?.finishingPositions||[]))||[],u=w(1,s+1).filter((t=>!c.includes(t))),d=i.find((t=>t.containerStructureId===a&&t.finishingPositionRange))?.finishingPositionRange?.winner||[0,1],p=o?.source.map((({target:t})=>t.structureId)),{positionsPlayedOff:l,positionsNotPlayedOff:m}=ag({structureIds:p,drawDefinition:n}),f=[...l??[],...m],h=w(d[0],d[1]+1).filter((t=>!f.includes(t))),g=N(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:e,groupSize:s}}const s=o?.source?.filter((t=>t.linkCondition!==vo)).map((t=>t.source?.roundNumber))||[],c=o?.source?.filter((t=>t.linkCondition===vo)).map((t=>t.source?.roundNumber))||[],{playoffSourceRounds:u,playoffRoundsRanges:d,roundProfile:p,error:l}=og({excludeRoundNumbers:s,playoffPositions:t,drawDefinition:n,structureId:a});for(const t of c){const e=o?.source.find((e=>e.source.roundNumber===t)),n=e?.target.roundNumber,r=e?.target.structureId,a=i.filter((({roundNumber:t,structureId:e})=>e===r&&t===n)),s=a.filter((({sides:t})=>t.find((t=>t.participantFed&&!t.participantId)))).length;if(u&&s===a.length){u.push(t);const e=p?.[t]?.finishingPositionRange?.loser;if(e){const n=Math.min(...e),r=n+s,i=w(n,r),a={finishingPositionRange:[n,r-1].join("-"),finishingPositions:i,roundNumber:t};d.push(a)}}}return u&&u.sort(e),d.sort(((t,e)=>t.roundNumber-e.roundNumber)),{playoffRounds:u,playoffRoundsRanges:d,error:l}}function ug(t){return sg(t)}function dg({drawDefinition:t}){const{maxQualifyingDepth:e,structureProfiles:n}=Gm({drawDefinition:t});for(const r of t.structures){const t=n[r.structureId];t.distanceFromMain&&(r.stageSequence=e+1-t.distanceFromMain)}return{...E}}function pg({tournamentRecord:t,drawDefinition:e,structure:n,link:r}){if(!t)return{error:_};if(!e)return{error:j};const i=function({drawDefinition:t,tournamentId:e,structure:n,eventId:r,link:i}){if(!t)return{error:j};if(!n)return{error:yt};if(!i)return{error:ht};const a=i.target.structureId,o=ts({drawDefinition:t,structureId:a});if(o.error)return wr({stack:"attachQualifyingStructure",context:{targetStructureId:a},result:o});t.structures||(t.structures=[]);t.links||(t.links=[]);t.structures.push(n),t.links.push(i),dg({drawDefinition:t});const s=Yp({structure:n})?.matchUps||[];return Fs({drawDefinition:t,tournamentId:e,matchUps:s,eventId:r}),Ls({drawDefinition:t,structureIds:[n.structureId]}),{...E}}({tournamentId:t.tournamentId,drawDefinition:e,structure:n,link:r});if(i.error)return i;return Lm({tournamentRecord:t,timeItem:{itemType:"attachQualifyingStructures",itemValue:{structureId:n.structureId,drawId:e.drawId}}}),i}const lg="SET3-S:6/TB7",mg="SET3-S:6/TB7-F:TB10",fg={FORMAT_STANDARD:lg,FORMAT_STANDARD_NOAD:"SET3-S:6NOAD",FORMAT_ATP_DOUBLES:mg,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"};function hg({winningSide:t,matchUpFormat:e=lg,matchUpStatus:n,tallyPolicy:r,score:i}){const a=[0,0],o=i?.sets,s="number"==typeof t&&t-1,c=Jd(e),u=Ug(c?.bestOf??1);if("number"==typeof s&&(n===Oa&&r?.setsCreditForDefaults||n===Ga&&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===Ba&&(+a[1-s]===u&&(a[1-s]-=1),r?.setsCreditForRetirements&&(a[s]=u)),a}function gg({matchUpFormat:t=lg,winningSide:e,matchUpStatus:r,tallyPolicy:i,score:a}){const{sets:o}=a||{};if(!o)return[0,0];const s="number"==typeof e&&e-1,c=Jd(t),u=Ug(c?.bestOf??1),d=c?.setFormat?.tiebreakAt||0,p=[[],[]];if("number"==typeof s&&(r===Oa&&i?.gamesCreditForDefaults||r===Ga&&i?.gamesCreditForWalkovers)){const t=u*(c?.setFormat?.setTo||0);p[s].push(t)}else o.forEach(((t,e)=>{const r=(t.setNumber||e+1)>u&&c?.finalSetFormat?"finalSetFormat":"setFormat",a=c?.[r]?.based,o=c?.[r].tiebreakSet,{side1Score:s,side2Score:d}=t;yg(a)&&(p[0].push(n(s||0)),p[1].push(n(d||0))),o&&t.winningSide&&!1!==i?.gamesCreditForTiebreakSets&&p[t.winningSide-1].push(1)}));if(r===Ba&&"number"==typeof s){const a=o.length>u&&c?.finalSetFormat?"finalSetFormat":"setFormat",l=c?.[a];if(yg(l.based)){const a=l?.setTo||0,m=t=>{if(c&&""!==t)return+t==d-1||+t===d?n(d||0)+1:+t<d?a:d},f=hg({winningSide:e,score:{sets:o},matchUpStatus:r,matchUpFormat:t,tallyPolicy:i});if(p.map((t=>t[s]<=t[1-s])).reduce(((t,e)=>t+(e?1:0)),0)>f[1-s]){const t=p[s].length,e=m(p[1-s][t-1]);e&&(p[s][t-1]=e)}u>p[s].length&&i?.gamesCreditForRetirements&&p[s].push(a)}}return[p[0].reduce(((t,e)=>t+e),0),p[1].reduce(((t,e)=>t+e),0)]}function Ig({matchUpFormat:t,score:e}){const r=t?Jd(t):void 0,i=Ug(r?.bestOf??1),a=[0,0],o=[0,0];return e?.sets?.forEach(((t,e)=>{const s=(t.setNumber||e+1)>i&&r?.finalSetFormat?"finalSetFormat":"setFormat",c=r?.[s]?.based;if(Sg(c)){const{side1Score:e,side2Score:r}=t;e&&(o[0]+=n(e||0)),r&&(o[1]+=n(r||0))}else t.side1TiebreakScore&&(o[0]+=n(t.side1TiebreakScore||0)),t.side2TiebreakScore&&(o[1]+=n(t.side2TiebreakScore||0)),(t.side1TiebreakScore||t.side2TiebreakScore)&&t.winningSide&&(a[t.winningSide-1]+=1)})),{pointsTally:o,tiebreaksTally:a}}function Ug(t){return t&&Math.ceil(t/2)||1}function Sg(t){return"P"===t}function yg(t){return!Sg(t)}function vg({participantIds:t,matchUpFormat:e,tallyPolicy:n,perPlayer:r,matchUps:i}){const a={},o=n?.excludeMatchUpStatuses||[],s=i.filter((e=>(e.tieMatchUps||!o.includes(e.matchUpStatus))&&(!t?.length||2===P(t,[Pg(e,0),Pg(e,1)]).length))),c=s.flatMap((({score:t,tieMatchUps:e})=>e?e.filter((({matchUpStatus:t})=>!o.includes(t))).flatMap((({score:t})=>t?.sets?.length??0)):t?.sets?.length??0)).reduce(((t,e)=>t+e),0);for(const t of s){const{matchUpStatus:i,tieMatchUps:o,tieFormat:s,score:c,winningSide:u,sides:d}=t,p=s&&t._disableAutoCalc&&s.collectionDefinitions.every((({scoreValue:t})=>t)),l=u&&wg(t),m=u&&Tg(t);if(l||m)if(Dg(a,l),Dg(a,m),o?.length){r=0;for(const t of o){const{matchUpType:e}=t,r=e===Zs,i=e===Ks;t.winningSide&&(t.winningSide===u?(l&&(a[l].tieMatchUpsWon+=1,i&&(a[l].tieSinglesWon+=1),r&&(a[l].tieDoublesWon+=1)),m&&(a[m].tieMatchUpsLost+=1,i&&(a[m].tieSinglesLost+=1),r&&(a[m].tieDoublesLost+=1))):t.winningSide!==u&&(m&&(a[m].tieMatchUpsWon+=1,i&&(a[m].tieSinglesWon+=1),r&&(a[m].tieDoublesWon+=1)),l&&(a[l].tieMatchUpsLost+=1,i&&(a[l].tieSinglesLost+=1),r&&(a[l].tieDoublesLost+=1)))),Ng({matchUpFormat:t.matchUpFormat,matchUpStatus:t.matchUpStatus,score:t.score,winningParticipantId:l,losingParticipantId:m,participantResults:a,isTieMatchUp:!0,manualGamesOverride:p,tallyPolicy:n,winningSide:u})}Rg({winningParticipantId:l,losingParticipantId:m,participantResults:a,matchUpStatus:i})}else Ng({matchUpFormat:t.matchUpFormat??e,isTieMatchUp:void 0,winningParticipantId:l,manualGamesOverride:p,losingParticipantId:m,participantResults:a,matchUpStatus:i,tallyPolicy:n,winningSide:u,score:c});else if(i&&Ya.includes(i)){const e=Pg(t,0),n=Pg(t,1);e&&(Dg(a,e),a[e].matchUpsCancelled+=1),n&&(Dg(a,n),a[n].matchUpsCancelled+=1)}else if(o?.length){r=0;for(const t of o){if(t.winningSide){const e=d?.find((({sideNumber:e})=>e===t.winningSide))?.participantId,n=d?.find((({sideNumber:e})=>e===t.winningSide))?.participantId;e&&n&&(Dg(a,e),Dg(a,n),a[e].tieMatchUpsWon+=1,a[n].tieMatchUpsLost+=1,t.matchUpType===Ks?(a[e].tieSinglesWon+=1,a[n].tieSinglesLost+=1):t.matchUpType===Zs&&(a[e].tieDoublesWon+=1,a[n].tieDoublesLost+=1))}bg({score:t.score,manualGamesOverride:p,participantResults:a,sides:d})}}else bg({manualGamesOverride:p,participantResults:a,score:c,sides:d});if(p){const t=d?.find((({sideNumber:t})=>1===t))?.participantId,e=d?.find((({sideNumber:t})=>2===t))?.participantId;Dg(a,t),Dg(a,e);const n=c?.sets?.reduce(((t,e)=>t+(e?.side1Score??0)),0),r=c?.sets?.reduce(((t,e)=>t+(e.side2Score??0)),0);t&&(a[t].gamesWon+=n,a[t].gamesLost+=r),e&&(a[e].gamesWon+=r,a[e].gamesLost+=n)}}return function({participantResults:t,matchUpFormat:e,tallyPolicy:n,perPlayer:r,totalSets:i}){const a=e&&Jd(e)||{},o=a.bestOf,s=o&&Math.ceil(o/2)||1,c=a.setFormat?.setTo;Object.keys(t).forEach((e=>{const a=t[e].setsWon,o=t[e].setsLost,u=n?.groupTotalSetsPlayed?i:r*(s||0)||a+o;let d=Math.round(a/u*1e3)/1e3;(d===1/0||isNaN(d))&&(d=u);const p=t[e].tieMatchUpsWon,l=p+t[e].tieMatchUpsLost;let m=Math.round(p/l*1e3)/1e3;(m===1/0||isNaN(m))&&(m=p);const f=t[e].matchUpsWon,h=f+t[e].matchUpsLost;let g=Math.round(f/h*1e3)/1e3;(g===1/0||isNaN(g))&&(g=f);const I=t[e].gamesWon||0,U=t[e].gamesLost||0,S=(r||0)*(s||0)*(c||0),y=Math.max(S,I+U);let v=Math.round(I/y*1e3)/1e3;(v===1/0||isNaN(v))&&(v=0);let w=Math.round(t[e].pointsWon/t[e].pointsLost*1e3)/1e3;(w===1/0||isNaN(w))&&(w=0),t[e].setsWon=a,t[e].setsLost=o,t[e].setsPct=d,t[e].tieMatchUpsWon=p,t[e].tieMatchUpsPct=m,t[e].matchUpsPct=g,t[e].gamesWon=I,t[e].gamesLost=U,t[e].gamesPct=v,t[e].pointsPct=w,t[e].result=`${t[e].matchUpsWon}/${t[e].matchUpsLost}`}))}({participantResults:a,matchUpFormat:e,tallyPolicy:n,perPlayer:r,totalSets:c}),{participantResults:a}}function wg(t){return Pg(t,t.winningSide-1)}function Tg(t){return Pg(t,1-(t.winningSide-1))}function Pg(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 Dg(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,retirements:0,setsLost:0,setsWon:0,tieSinglesWon:0,tieSinglesLost:0,tieDoublesWon:0,tieDoublesLost:0,tieMatchUpsLost:0,tieMatchUpsWon:0,victories:[],walkovers:0})}function bg({manualGamesOverride:t,participantResults:e,score:r,sides:i}){const{sets:a}=r||{},o=[[],[]],s=[0,0];for(const t of a||[]){const{winningSide:e,side1Score:r,side2Score:i}=t;e&&(s[e-1]+=1),o[0].push(n(r||0)),o[1].push(n(i||0))}const c=[o[0].reduce(((t,e)=>t+e),0),o[1].reduce(((t,e)=>t+e),0)];i.forEach(((n,r)=>{const{participantId:i}=n;i&&(Dg(e,i),e[i].setsWon+=s[r],e[i].setsLost+=s[1-r],t||(e[i].gamesWon+=c[r],e[i].gamesLost+=c[1-r]))}))}function Ng({winningParticipantId:t,losingParticipantId:e,participantResults:n,manualGamesOverride:r,matchUpFormat:i,matchUpStatus:a,isTieMatchUp:o,tallyPolicy:s,winningSide:c,score:u}){const d=c&&c-1,p=1-d;o||Rg({winningParticipantId:t,losingParticipantId:e,participantResults:n,matchUpStatus:a});const l=hg({matchUpStatus:a,matchUpFormat:i,tallyPolicy:s,winningSide:c,score:u}),m=gg({matchUpStatus:a,matchUpFormat:i,tallyPolicy:s,winningSide:c,score:u}),{pointsTally:f}=Ig({score:u,matchUpFormat:i});t&&(n[t].setsWon+=l[d],n[t].setsLost+=l[p],r||(n[t].gamesWon+=m[d],n[t].gamesLost+=m[p]),n[t].pointsWon+=f[d],n[t].pointsLost+=f[p]),e&&(n[e].setsWon+=l[p],n[e].setsLost+=l[d],r||(n[e].gamesWon+=m[p],n[e].gamesLost+=m[d]),n[e].pointsWon+=f[p],n[e].pointsLost+=f[d])}function Rg({winningParticipantId:t,losingParticipantId:e,participantResults:n,matchUpStatus:r}){e&&(r===Ga&&(n[e].walkovers+=1),r===Oa&&(n[e].defaults+=1),r===Ba&&(n[e].retirements+=1),[Oa,Ba,Ga].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 Mg({participantResults:t,participantIds:e,attribute:n}){return Ag({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 Ag(t){return(t.participantIds||Object.keys(t.participantResults)).reduce(((e,n,r)=>(e.push({participantId:n,i:r,results:t.participantResults[n]}),e)),[])}const Eg=[{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}],Cg={matchUpsPct:20,tieMatchUpsPct:16,setsPct:12,gamesPct:8,pointsPct:4};function Og(t){const{requireCompletion:e=!0,participantResults:n,subOrderMap:r,tallyPolicy:i}=t,a=[];if(e&&!function({participantResults:t,participantsCount:e}){const n=Ag({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=Mg({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=Fg({participantIds:e,...t});return a.push(...n.report??[]),n.order})).flat(1/0);let u,d=1;c.forEach(((t,e)=>{e&&(t.resolved||u&&!t.resolved)&&(d+=1),u=t.resolved,t.resolved?(t.position=e+1,d=t.position):t.position=d}));const p=g(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(Cg).filter((t=>i.GEMscore.includes(t))):Object.keys(Cg);return e.map((e=>(t[e]||0)*Math.pow(10,Cg[e].toFixed(3)))).reduce(((t,e)=>t+e),0)}(o);const s=p[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 Fg({participantResults:t,disableHeadToHead:e,participantIds:n,matchUpFormat:r,tallyPolicy:i,matchUps:a}){const o=[],c=[];let u;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 c.push({attribute:"head2Head",participantIds:n,headToHeadWinner:t}),{order:[e],headToHeadWinner:t,report:c}}}const d=(i?.tallyDirectives||Eg).filter((t=>{const e=!(s(t.maxParticipants)&&n?.length>t.maxParticipants);return e||o.push(t),e}));return o.length&&c.push({excludedDirectives:o,participantIds:n}),d.every((({attribute:t,reversed:e,idsFilter:o,disableHeadToHead:s})=>(u=function({disableHeadToHead:t,participantIds:e,matchUpFormat:n,tallyPolicy:r,attribute:i,idsFilter:a,matchUps:o,reversed:s}){const{participantResults:c}=vg({participantIds:a&&e,matchUpFormat:n,tallyPolicy:r,matchUps:o}),u=Mg({participantResults:c,participantIds:e,attribute:i}),d=[{attribute:i,reversed:s,groups:u,idsFilter:a}];let p;return Object.keys(u).length>1&&e.length&&(p=Object.keys(u).map((t=>parseFloat(t))).sort(((t,e)=>s?t-e:e-t)).map((t=>u[t])).map((e=>{const i=Fg({participantResults:c,disableHeadToHead:t,participantIds:e,matchUpFormat:n,tallyPolicy:r,matchUps:o});return d.push(...i.report??[]),i.order})).flat(1/0)),{order:p,report:d}}({disableHeadToHead:s,participantIds:n,matchUpFormat:r,tallyPolicy:i,attribute:t,idsFilter:o,matchUps:a,reversed:e}),c.push(u.report),!u.order))),u.order?{order:u.order,report:c}:{order:n?.map((t=>({participantId:t}))),report:c}}function kg({policyDefinitions:t,generateReport:e,matchUpFormat:n,matchUps:r=[],subOrderMap:i,perPlayer:a}){if(!yc(r))return{error:Ht};if(1!==r.reduce(((t,{structureId:e})=>t.includes(e)?t:t.concat(e)),[]).length)return{error:Nn,info:"Maximum one structureId"};const o=r.filter((t=>t&&t.matchUpStatus!==Ma)),s=o.length&&m(o.map((({drawPositions:t})=>t)).flat()).length,c=o.filter((t=>Lc({matchUp:t}))).length===o.length;c||(a=0);const u=r.every((({matchUpType:t,tieMatchUps:e})=>t===Qs&&e.every((t=>Lc({matchUp:t}))))),d=t?.[yi],p=r.filter((t=>Lc({matchUp:t})||t.matchUpType===Qs)),{participantResults:l}=vg({matchUps:p,matchUpFormat:n,tallyPolicy:d,perPlayer:a});let f,h;const{groupOrder:g,report:I}=Og({matchUps:p,participantResults:l,participantsCount:s,matchUpFormat:n,tallyPolicy:d,subOrderMap:i});if(c&&g)f=I,h=g,g.forEach((t=>{const{participantId:e,groupOrder:n,rankOrder:r,subOrder:i,ties:a,GEMscore:o}=t,s=l[e];Object.assign(s,{groupOrder:n,rankOrder:r,GEMscore:o,subOrder:i,ties:a})}));else{const{groupOrder:t,report:e}=Og({requireCompletion:!1,participantResults:l,participantsCount:s,matchUpFormat:n,tallyPolicy:d,subOrderMap:i,matchUps:r});f=e,h=t,t&&t.forEach((t=>{const{participantId:e,groupOrder:n,GEMscore:r}=t,i=l[e];Object.assign(i,{provisionalOrder:n,GEMscore:r})}))}const U={completedTieMatchUps:u,readableReport:"",participantResults:l,bracketComplete:c,order:[],report:f};if((c||u)&&(U.order=h),e||Qn({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:r,report:f,order:h});Qn({tally:!0})&&console.log(t),U.readableReport=t}return U}function xg({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=>Ya.includes(t.matchUpStatus))),{collectionValueProfiles:u,collectionGroupNumber:d,collectionValue:l,matchUpValue:m,winCriteria:f,scoreValue:h,setValue:g}=t,I=d&&e.includes(d),U=[0,0];if(a.forEach((t=>{t.winningSide&&(U[t.winningSide-1]+=1)})),p(m)?a.forEach((t=>{t.winningSide&&(o[t.winningSide-1]+=m)})):p(g)?a.forEach((t=>{t.score?.sets?.forEach((t=>{t.winningSide&&(o[t.winningSide-1]+=g)}))})):p(h)?a.forEach((t=>{t.score?.sets?.forEach((e=>{const{side1TiebreakScore:n=0,side2TiebreakScore:r=0,side1Score:i=0,side2Score:a=0}=e;(t.matchUpStatus===Ea||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});p(r)&&(o[e.winningSide-1]+=r)}})),p(l)){let e;if(f?.aggregateValue)c&&(p(m||g||h)&&o[0]!==o[1]?e=o[0]>o[1]?1:2:U[0]!==U[1]&&(e=U[0]>U[1]?1:2));else if(f?.valueGoal)e=o.reduce(((t,e,n)=>e>=f.valueGoal?n+1:t),0);else{const n=Math.floor(t.matchUpCount/2)+1;e=U.reduce(((t,e,r)=>e>=n?r+1:t),0)}e&&(I?n[d].values[e-1]+=l:s[e-1]+=l)}else I?(n[d].values[0]+=o[0]||0,n[d].values[1]+=o[1]||0):s=o;I?(n[d].sideWins[0]+=U[0]||0,n[d].sideWins[1]+=U[1]||0,n[d].allGroupMatchUpsCompleted=n[d].allGroupMatchUpsCompleted&&c,n[d].matchUpsCount+=a.length):s.forEach(((t,e)=>r[e]+=t||0))}function _g(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:Nn};if(!o)return{error:zt};const c=$d({matchUp:o,drawDefinition:r,structure:a,event:s})?.tieFormat||t?.tieFormat;if(!c)return{error:Gt};const u=fh({tieFormat:c});if(u.error)return u;const d=c?.collectionDefinitions||[],p=o?.tieMatchUps??[],l=[0,0],{groupValueGroups:m,groupValueNumbers:f}=Kf(c);for(const t of d)xg({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 S;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));S=e?.sideNumber}else if(e){p.every((t=>t.matchUpStatus&&Ya.includes(t.matchUpStatus)||t.winningSide))&&h[0]!==h[1]&&(S=h[0]>h[1]?1:2)}if(!S&&n){const t=o.matchUpId,e=o.hasContext?o:i?.drawMatchUps?.[t]||r&&Xm({inContext:!0,drawDefinition:r,matchUpId:t})?.matchUp;if(e){const{completedTieMatchUps:t,order:n}=kg({matchUps:[e]});if(t&&n?.length){const t=n[0].participantId;S=e.sides.find((({participantId:e})=>e===t))?.sideNumber}}}}return S&&(g.winningSide=S),{scoreStringSide1:I,scoreStringSide2:U,winningSide:S,set:g}}const Lg={matchUpStatus:ja,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function Bg({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&&Ma||[Oa,Ga].includes(u.matchUpStatus)&&u.matchUpStatus||ja,[Ga,Oa].includes(u.matchUpStatus)&&(u.winningSide=void 0),u.matchUpStatusCodes&&ef({inContextDrawMatchUps:t,sourceMatchUpStatus:n,sourceMatchUpId:a,matchUpsMap:c,matchUp:u}),xs({tournamentId:i?.tournamentId,eventId:d?.eventId,context:`removeSubsequentDrawPosition-${r}`,drawDefinition:o,matchUp:u}),{...E}}function Vg({tournamentRecords:t,eventId:e,drawId:n}){const{tournamentIdMap:r}=Cm({tournamentRecords:t});return(r?Object.keys(r):[]).find((t=>e&&r?.[t].includes(e)||n&&r?.[t].includes(n)))}function jg({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:i,matchUps:a,event:o}){if(!yc(a))return{error:Nn};if(!t)return{error:Nn};const{policyDefinitions:s}=bc({policyTypes:[yi],tournamentRecord:e,drawDefinition:r,event:o}),{subOrderMap:c}=function({positionAssignments:t}){const e=(t||[]).filter(Ua(lp)).map((t=>{const{extension:e}=Mr({element:t,name:sa}),r=n(e?.value),i=!isNaN(r)&&r;return i&&{participantId:t.participantId,subOrder:i}})).filter(Boolean),r=g(e.map((({subOrder:t})=>t)));return{subOrderMap:Object.assign({},...e.filter((({subOrder:t})=>1===r[t])).map((({participantId:t,subOrder:e})=>({[t]:e}))))}}({positionAssignments:t}),u=kg({policyDefinitions:s,matchUpFormat:i,subOrderMap:c,matchUps:a});if(u.error)return u;const{participantResults:d,bracketComplete:p,report:l}=u,m=Object.keys(d);return t.forEach((t=>{const{participantId:e}=t;if(m.includes(e)){Nr({element:t,extension:{value:d[e],name:ca}}),d[e].ties||Dr({element:t,name:sa})}else Dr({element:t,name:ca}),Dr({element:t,name:sa})})),Ls({drawDefinition:r}),{...E,participantResults:d,bracketComplete:p,report:l}}function Gg(t){return"object"!=typeof t?{error:ae}:"object"!=typeof t.element?{error:Nn}:t.notes?"string"==typeof t.notes||t.notes?.testing?(Object.assign(t.element,{notes:t.notes}),{...E}):{error:Nn}:{error:ae}}function qg({matchUpStatusCodes:t,removeWinningSide:e,tournamentRecord:n,drawDefinition:r,matchUpFormat:i,matchUpStatus:a,removeScore:o,winningSide:s,matchUpId:c,matchUp:u,event:d,notes:p,score:l}){const f="modifyMatchUpScore";let h;const g=u.matchUpType===Qs;if(g&&r){if(c&&u.matchUpId!==c){const t=Xm({drawDefinition:r,matchUpId:c,event:d});if(!t.matchUp)return{error:Wt};({matchUp:u,structure:h}=t)}}else u.matchUpId!==c&&console.log("!!!!!");a&&[Ga,ka].includes(a)||o?Object.assign(u,{...Lg}):l&&(u.score=l);const I=a&&u?.matchUpStatus===Oa&&a!==Oa;let U;if(a&&(u.matchUpStatus=a),i&&(u.matchUpFormat=i),t&&(u.matchUpStatusCodes=t),s&&(u.winningSide=s),e&&(u.winningSide=void 0),!h&&r&&({structure:h}=Xm({drawDefinition:r,matchUpId:c,event:d})),!a||u.winningSide||!$s(u)||Ya.includes(a)||[Ra,Va].includes(a)||(u.matchUpStatus=xa),I&&u?.processCodes?.length||a===Oa){const t=Dc({tournamentRecord:n,drawDefinition:r,structure:h,event:d})?.appliedPolicies;U=t?.[Mi]?.processCodes?.incompleteAssignmentsOnDefault}if(!u.collectionId){const t=h?.structureType===mo,e=ap({drawDefinition:r,structure:h});if(ip({drawDefinition:r,structure:h})||e||t){const a=(t=>{i=g?"SET1-S:T100":i??u.matchUpFormat??t?.matchUpFormat??r?.matchUpFormat??d?.matchUpFormat;const a=g?{matchUpTypes:[Qs]}:void 0,{matchUps:o}=Yp({afterRecoveryTimes:!1,tournamentRecord:n,inContext:!0,matchUpFilters:a,drawDefinition:r,structure:t,event:d});return e&&(t.positionAssignments=m(o.flatMap((t=>(t.sides??[]).map((t=>t.participantId)))).filter(Boolean)).map((t=>({participantId:t})))),jg({positionAssignments:t.positionAssignments,tournamentRecord:n,drawDefinition:r,matchUpFormat:i,matchUps:o,event:d})})(t&&h.structures.find((t=>t?.matchUps.find((t=>t.matchUpId===c))))||h);if(a.error)return wr({result:a,stack:f})}}if(p){const t=Gg({element:u,notes:p});if(t.error)return wr({result:t,stack:f})}const S=n?.tournamentId,y=lr().topics.includes(Es),v=(y||U)&&xc({drawDefinition:r}),w=v&&Jp({matchUpFilters:{matchUpIds:[c]},nextMatchUps:!0,tournamentRecord:n,inContext:!0,drawDefinition:r,matchUpsMap:v}).matchUps?.[0];if(y&&w&&function({tournamentId:t,inContextMatchUp:e}){e&&sr({payload:{inContextMatchUp:e,tournamentId:t},topic:Es,key:e.matchUpId})}({tournamentId:S,inContextMatchUp:w}),Array.isArray(U)&&w&&!w.sides?.every((({participantId:t})=>t)))if(a===Oa)u.processCodes=m([...u.processCodes??[],...U]);else for(const t of U||[]){const e=t&&u?.processCodes?.lastIndexOf(t);u?.processCodes?.splice(e,1)}return xs({eventId:d?.eventId,context:f,drawDefinition:r,tournamentId:S,matchUp:u}),{...E}}function $g(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&&Vg({tournamentRecords:c,...t});const d=u&&c[u];if(!d)return{error:_};const p=Xm({drawDefinition:n,event:s,matchUpId:o});if(p.error)return p;if(!p.matchUp)return{error:Wt};const{matchUp:l,structure:m}=p;if(!l.tieMatchUps)return{error:Yt};Vf({tournamentId:d?.tournamentId,eventId:s?.eventId,dualMatchUp:l,drawDefinition:n});const{extension:f}=Mr({name:Hi,element:l});if(f?.value){if(!i)return{...E,score:l.score};Dr({element:l,name:Hi})}const h=$d({drawDefinition:n,structure:m,matchUp:l,event:s})?.tieFormat;l.tieFormat=Yf(h);const g=_g({drawDefinition:n,matchUpsMap:a,structure:m,matchUp:l,event:s}),{winningSide:I,set:U,scoreStringSide1:S,scoreStringSide2:y}=g,v=U?.side1Score||U?.side2Score;if(e&&!l.score&&!v)return{...E};const w={scoreStringSide1:S,scoreStringSide2:y,sets:U?[U]:[]},T=I&&[1,2].includes(I),P=T&&Ea||zs({matchUpStatus:r??l.matchUpStatus,tieMatchUps:l.tieMatchUps,winningSide:l.winningSide,score:w})&&xa||ja,D=!(!l.winningSide||T),b=l.tieMatchUps.find((({score:t,winningSide:e,matchUpStatus:n})=>t?.sets?.length&&(t.sets[0].side1Score||t.sets[0].side2Score)||n&&Ya.includes(n)||e));let N;if(l.tieFormat&&!T&&!b){const t=$d({drawDefinition:n,structure:m,event:s})?.tieFormat;t&&JSON.stringify(h)===JSON.stringify(t)&&(l.tieFormatId=void 0,l.tieFormat=void 0,N=!0)}return qg({matchUpStatus:P,score:w,removeWinningSide:D,tournamentRecord:d,drawDefinition:n,removeScore:i,winningSide:I,matchUpId:o,matchUp:l,event:s}),{...E,score:w,removeWinningSide:D,tieFormatRemoved:N,winningSide:I}}function Wg(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=ap({drawDefinition:i,structure:d}),{drawPositions:f,winningSide:h}=c.matchUp||{};if(!m&&!f)return{error:Z};const{targetLinks:{loserTargetLink:g,winnerTargetLink:I,byeTargetLink:U},targetMatchUps:{loserMatchUp:S,winnerMatchUp:y,byeMatchUp:v}}=c,w=qg({...t,matchUpStatus:a||ja,removeWinningSide:!0});if(w.error)return w;let T;if(l){const{matchUpTieId:n,matchUpsMap:a}=t;if(T=$g({matchUpId:n,tournamentRecord:r,drawDefinition:i,matchUpsMap:a,event:p}),!e&&!T.removeWinningSide)return{...E}}if(m)return{...E};const{matchUps:P}=Yp({afterRecoveryTimes:!1,inContext:!0,drawDefinition:i,matchUpsMap:o,structure:d}),{positionAssignments:D}=is({structure:d}),N=h-1,R=1-N,M=f[N],A=f[R],{winnerParticipantId:C,loserParticipantId:O}=D?.reduce(((t,e)=>(e.drawPosition===A&&(t.loserParticipantId=e.participantId),e.drawPosition===M&&(t.winnerParticipantId=e.participantId),t)),{winnerParticipantId:void 0,loserParticipantId:void 0})||{},F=P.filter((t=>t.drawPositions?.includes(A)));if(y&&Hg({sourceMatchUpStatus:a,sourceMatchUpId:u,inContextDrawMatchUps:n,winningDrawPosition:M,winnerParticipantId:C,tournamentRecord:r,winnerTargetLink:I,drawDefinition:i,winnerMatchUp:y,dualMatchUp:s,matchUpsMap:o}),S){const{winnerHadMatchUpStatus:t}=function({matchUpStatuses:t=[Ma,Ga,Oa],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:b(o||[],t),winnerMatchUpStatuses:o,loserHadMatchUpStatus:b(s||[],t),loserMatchUpStatuses:s}}({drawPositionMatchUps:F,loserDrawPosition:A,sourceMatchUps:P}),e=g.linkCondition;if(t&&e===vo){zg({targetLink:g,inContextDrawMatchUps:n,drawDefinition:i,drawPosition:Math.min(...S.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}=ts({drawDefinition:a,structureId:p});if(!l)return{error:Ut};const{positionAssignments:m}=is({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,xs({tournamentId:n?.tournamentId,eventId:u?.eventId,matchUp:e,context:d,drawDefinition:a}))}return{...E}}({sourceMatchUpStatus:a,sourceMatchUpId:u,loserParticipantId:O,tournamentRecord:r,loserTargetLink:g,drawDefinition:i,loserMatchUp:S,dualMatchUp:s,matchUpsMap:o,event:p});if(c.error)return c}if(v){zg({sourceMatchUpId:u,targetLink:U,inContextDrawMatchUps:n,drawDefinition:i,drawPosition:Math.min(...v.drawPositions),matchUpsMap:o,event:p})}const k=T&&{tieMatchUpResult:T};return{...E,...k}}function Hg({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}=ts({drawDefinition:s,structureId:t});if(!e)return{error:Ut};const{positionAssignments:n}=is({structure:e});e.seedAssignments=(e.seedAssignments??[]).filter((t=>t.participantId!==r));const o=n?.find((t=>t.participantId===r)),d=o?.drawPosition,{matchUps:l}=Yp({drawDefinition:s,structure:e,event:p}),m=g(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&&xs({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}=ts({drawDefinition:a,structureId:o});if(p?.structureType===mo)return{...E};u=u??xc({drawDefinition:a});const l=(u?.mappedMatchUps||{})[o].matchUps,{initialRoundNumber:m}=vl({drawPosition:n,matchUps:l}),f=l?.filter((t=>t.roundNumber>=c&&t.roundNumber!==m&&t.drawPositions?.includes(n))),{positionAssignments:h}=rs({drawDefinition:a,structureId:o});for(const o of f??[])Bg({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}),{...E}}function zg({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,matchUpsMap:i,targetLink:a,event:o}){return Cl({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:i,drawPosition:r,structureId:a.target.structureId,event:o}),{...E}}function Yg(t){const{tournamentRecord:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:i,targetData:a,structure:o,event:s}=t,c="doubleExitAdvancement";if(o.structureType===mo)return wr({result:{...E},stack:c});const{matchUp:u,targetMatchUps:d,targetLinks:p}=a,{loserMatchUp:l,winnerMatchUp:m,loserTargetDrawPosition:f}=d;if(l&&l.matchUpStatus!==Ma){const{loserTargetLink:a}=p;if(n?.progression?.doubleExitPropagateBye){const t=Jg({loserTargetDrawPosition:f,tournamentRecord:e,loserTargetLink:a,drawDefinition:r,loserMatchUp:l,matchUpsMap:i,event:s});if(t.error)return wr({result:t,stack:c})}else{const{feedRound:n,drawPositions:r,matchUpId:i}=l,a=n?2:2-r.indexOf(f),o=Kg({...t,targetMatchUp:l,walkoverWinningSide:a,tournamentRecord:e,sourceMatchUp:u,matchUpId:i});if(o.error)return wr({result:o,stack:c})}}if(m){const n=Kg({...t,matchUpId:m.matchUpId,targetMatchUp:m,tournamentRecord:e,sourceMatchUp:u});if(n.error)return wr({result:n,stack:c})}return wr({result:{...E},stack:c})}function Kg(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===Fa?Fa:ka,u=t.matchUpStatus===Fa?Oa:Ga,d="conditionallyAdvanceDrawPosition",p=o.drawMatchUps.find((t=>t.matchUpId===a.matchUpId));if(!p)return{error:zt};const l=i?.drawPositions||[];let m=p.drawPositions?.filter(Boolean);const f=i?.structureId===a.structureId;if(f&&b(l,m)&&(m=m.filter((t=>!l.includes(t)))),f&&m.length>1)return wr({result:{error:z},stack:d});const{pairedPreviousMatchUpIsDoubleExit:h,pairedPreviousMatchUp:g}=Qm(t),I=Uc({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),{targetMatchUps:U,targetLinks:S}=I,{loserTargetDrawPosition:y,winnerMatchUp:v,loserMatchUp:w}=U;if(w){const{loserTargetLink:t}=S,e=Jg({loserTargetDrawPosition:y,loserMatchUp:w,tournamentRecord:n,loserTargetLink:t,drawDefinition:r,matchUpsMap:o});if(e.error)return wr({result:e,stack:d})}const T=p.drawPositions?.filter(Boolean)||[],P=1===T.length,D=t.walkoverWinningSide||P&&nf({drawPosition:T[0],matchUpId:a.matchUpId,inContextDrawMatchUps:e})||void 0,N=[Ga,Oa].includes(p.matchUpStatus)&&!T.length,R=1===p.finishingRound,M=N&&!R?c:u,A=e.find((t=>t.matchUpId===g.matchUpId));let C,O=[];i&&(i?.structureId===A?.structureId?C=i.roundPosition<g?.roundPosition?1:2:a.feedRound?C=i.structureId===a.structureId?2:1:D&&(C=3-D));const F=t.matchUpStatus,k=g?.matchUpStatus;1===C?O=[{matchUpStatus:Zg(F),previousMatchUpStatus:F,sideNumber:1},{matchUpStatus:Zg(k),previousMatchUpStatus:k,sideNumber:2}]:2===C&&(O=[{matchUpStatus:Zg(k),previousMatchUpStatus:k,sideNumber:1},{matchUpStatus:Zg(F),previousMatchUpStatus:F,sideNumber:2}]),O.length&&(O=O.map((t=>vr(t))));const x=qg({...t,matchUp:p,winningSide:D,matchUpStatusCodes:O,matchUpStatus:M});if(x.error)return wr({result:x,stack:d});if(N)return Yg({...t,matchUpStatus:M,targetData:I});if(!v)return wr({result:{...E},stack:d});const _=2===m.length?m[D-1]:m[0],{positionAssignments:L}=rs({structure:s}),B=L?.find((t=>t.drawPosition===_)),V=o.drawMatchUps.find((t=>t.matchUpId===v.matchUpId)),j=V?.drawPositions?.filter(Boolean),G=1===j.length;if(_){if(B?.bye){const n=Uc({matchUpId:V.matchUpId,inContextDrawMatchUps:e,drawDefinition:r});if(G){const t=j.filter(Boolean)[0],n=nf({drawPosition:t,matchUpId:V.matchUpId,inContextDrawMatchUps:e}),i=qg({matchUpId:V.matchUpId,matchUp:V,matchUpStatus:u,matchUpStatusCodes:[],removeScore:!0,drawDefinition:r,winningSide:n});return i.error?wr({result:i,stack:d}):Ml({drawPositionToAdvance:t,matchUpId:V.matchUpId,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:o})}if([Ga,Oa].includes(v.matchUpStatus)){const e=Yg({...t,matchUpId:V.matchUpId,matchUpStatus:M,targetData:n});if(e.error)return wr({result:e,stack:d})}return wr({result:{...E},stack:d})}return af({matchUpId:v.matchUpId,drawPosition:_,inContextDrawMatchUps:e,drawDefinition:r})}if(h){if(!V)return{error:zt};if(G){const t=j[0],n=nf({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawPosition:t});console.log("existing drawPosition is winningSide",{walkoverWinningSide:n})}const n=[Ga,Oa].includes(V.matchUpStatus)?u:c,i=qg({matchUpId:V.matchUpId,matchUp:V,matchUpStatusCodes:[],removeScore:!0,drawDefinition:r,matchUpStatus:n});if(i.error)return wr({result:i,stack:d});if(n===c){const e=Yg({...t,matchUpId:a.matchUpId,matchUpStatus:n,targetData:I});if(e.error)return e}}return wr({result:{...E},stack:d})}function Jg(t){const{loserTargetDrawPosition:e,tournamentRecord:n,loserTargetLink:r,drawDefinition:i,matchUpsMap:a,event:o}=t,s=r?.target?.structureId,{structure:c}=ts({drawDefinition:i,structureId:s});return c?bl({drawPosition:e,tournamentRecord:n,drawDefinition:i,structureId:s,matchUpsMap:a,event:o}):{error:yt}}function Zg(t){return t===ka?Ga:t===Fa?Oa:t}function Xg(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===Ma,c=a.winningSide,u=[ka,Fa].includes(r),d=Ws({matchUpStatus:r}),p=Hs({matchUpStatus:r}),l=!d&&!p,m=t.matchUpTieId||c&&d&&!u,f=c&&u;return l&&{error:Ft}||m&&Qg(t)||f&&function(t){const e=Wg(t);return e.error?e:Yg(t)}(t)||c&&Wg(t)||p&&qg({...t,removeScore:[Aa,Ga].includes(r),matchUpStatus:r||ja})||s&&function({tournamentRecord:t,drawDefinition:e,structure:n,matchUp:r}){const i="attemptToSetMatchUpStatusBYE";if(r?.winningSide)return wr({result:{error:_t},context:{matchUpStatus:Ma},stack:i});const{positionAssignments:a}=is({structure:n}),o=a?.filter((t=>t.bye)).map((t=>t.drawPosition)),s=r.drawPositions?.some((t=>o?.includes(t)));return s?(r.matchUpStatus=Ma,r.matchUpStatusCodes=[],xs({tournamentId:t?.tournamentId,context:i,drawDefinition:e,matchUp:r}),{...E}):wr({result:{error:Ot},info:"matchUp does not include BYE",stack:i})}({tournamentRecord:e,drawDefinition:n,structure:i,matchUp:a})||!d&&{error:Ft}||u&&function(t){const e=Qg({...t,removeScore:!0});return e.error?e:Yg(t)}(t)||o&&Qg(t)||wr({result:{error:_t},stack:"attemptToSetMatchUpStatus"})}function Qg(t){const e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){const n=Wg(t);if(n.error)return wr({result:n,stack:e})}const n=Boolean(t.matchUp.collectionId),r=qg(t);if(n){const{matchUpTieId:n,drawDefinition:i,matchUpsMap:a}=t,o=$g({tournamentRecord:t.tournamentRecord,matchUpId:n,event:t.event,drawDefinition:i,matchUpsMap:a});if(o.error)return wr({result:o,stack:e});Object.assign(r,{tieMatchUpResult:o})}return wr({result:r,stack:e})}function tI({drawDefinition:t,structure:e,matchUp:n}){const r=[];if(e.finishingPosition===Yo){if(Mh({drawDefinition:t,structure:e})){const{structureIds:i}=function({drawDefinition:t,structure:e,matchUp:n}){const{drawPositions:r}=n,{positionAssignments:i}=rs({drawDefinition:t,structure:e}),a=i?.filter((({drawPosition:t})=>r?.includes(t))),o=a?.map((t=>{const{extension:e}=Mr({element:t,name:ca});return e?.value?.groupOrder})),{containerStructures:s}=qs({drawDefinition:t}),c=s[e.structureId],u=Ic({drawDefinition:t,structureId:c})?.links?.source,d=u?.filter((t=>b(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 eI(t){const{dualWinningSideChange:e,matchUpStatusCodes:n,tournamentRecord:r,drawDefinition:i,matchUpFormat:a,matchUpStatus:o,winningSide:s,matchUpId:c,structure:u,matchUp:d,event:p,score:l}=t,m=Ws({matchUpStatus:o})||[Aa,Na].includes(o)&&e,f=Boolean(d.collectionId),h=ap({drawDefinition:i,structure:u}),g=f||h||function({structure:t,matchUp:e}){const{drawPositions:n}=e,{positionAssignments:r}=is({structure:t}),i=r?.filter((t=>n?.includes(t.drawPosition)&&t.participantId));return 2===i?.length}({structure:u,matchUp:d});if(!g)return{error:Rt};const I=[Ga].includes(o);return wr({result:qg({matchUpStatusCodes:m&&n||[],matchUpStatus:m&&o||Ea,tournamentRecord:r,drawDefinition:i,matchUpFormat:a,removeScore:I,winningSide:s,matchUpId:c,matchUp:d,event:p,score:l}),stack:"attemptToModifyScore"})}function nI(t){const n=eI(t);if(n.error)return n;const r=Ws({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:i,projectedWinningSide:a,inContextDrawMatchUps:o,tournamentRecord:s,drawDefinition:c,matchUpStatus:u,dualMatchUp:d,matchUpsMap:p,winningSide:l,targetData:m,matchUpId:f,structure:h,matchUp:g,event:I}=t,U="directParticipants",S=Boolean(g.collectionId),y=ap({drawDefinition:c,structure:h});let v,w=g.drawPositions;if(S){const{matchUpTieId:e,matchUpsMap:n}=t,r=$g({matchUpId:e,tournamentRecord:s,drawDefinition:c,matchUpsMap:n,event:I});v=r&&{tieMatchUpResult:r};const a=o.find((({matchUpId:t})=>t===e));if(w=a?.drawPositions,!i)return wr({result:{...E,...v},stack:U})}if(y)return wr({result:{...E,...v},stack:U});if(!w)return wr({result:{error:Z},stack:U});{const t=a?a-1:l-1,n=1-t,i=w[t],h=w[n],{targetLinks:{loserTargetLink:g,winnerTargetLink:S,byeTargetLink:y},targetMatchUps:{winnerMatchUpDrawPositionIndex:v,loserMatchUpDrawPositionIndex:T,winnerMatchUp:P,loserMatchUp:D,byeMatchUp:b}}=m;if(P){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=ts({structureId:f,drawDefinition:c});if(h.error)return h;const{structure:g}=h,{positionAssignments:I}=is({structureId:f,drawDefinition:c}),U=I?.find((t=>t.drawPosition===i)),S=U?.participantId,y=o.target.structureId,{positionAssignments:v}=is({structureId:y,drawDefinition:c}),w=v?.find((t=>t.participantId===S)),T=w?.drawPosition,P=v?.filter((t=>{const e=n.includes(t.drawPosition),r=!t.participantId&&!t.bye&&!t.qualifier;return e&&r})).map((t=>t.drawPosition)),D=P?.includes(d);if(S&&1===o.target.roundNumber&&D)Rf({drawPosition:d,participantId:S,structureId:y,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:a,drawDefinition:c,matchUpsMap:p,event:l});else if(S&&P?.length){const t=P.pop();t&&Rf({participantId:S,structureId:y,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:a,drawDefinition:c,drawPosition:t,matchUpsMap:p,event:l})}else if(T){const t=af({drawPosition:T,matchUpId:u.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:a,sourceMatchUpId:s,drawDefinition:c,matchUpsMap:p});if(t.error)return wr({result:t,stack:m})}else if(g?.stage!==Qa){const t="winner target position unavaiallble";return console.log(t),{error:t}}if(g?.seedAssignments&&g.structureId!==y){const t=g.seedAssignments.find((({participantId:t})=>t===S)),e=t?.participantId;t&&e&&vf({eventId:u?.eventId,structureId:y,...t,tournamentRecord:a,drawDefinition:c,participantId:e})}}else{const t=af({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=>({...i.sides?.find((e=>e.sideNumber===t))||{},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=Tf({lineUp:e}),xs({tournamentId:a?.tournamentId,eventId:u?.eventId,matchUp:i,context:m,drawDefinition:c})}}}return{...E}}({sourceMatchUpStatus:r&&u||Ea,winnerMatchUpDrawPositionIndex:v,sourceMatchUpId:f,inContextDrawMatchUps:o,projectedWinningSide:a,winningDrawPosition:i,tournamentRecord:s,winnerTargetLink:S,drawDefinition:c,winnerMatchUp:P,dualMatchUp:d,matchUpsMap:p,event:I});if(t.error)return wr({result:t,stack:U})}if(D){const t=function(t){const{loserMatchUpDrawPositionIndex:n,inContextDrawMatchUps:r,projectedWinningSide:i,sourceMatchUpStatus:a,loserDrawPosition:o,tournamentRecord:s,loserTargetLink:c,drawDefinition:u,loserMatchUp:d,dualMatchUp:p,matchUpsMap:l,event:m}=t,f="directLoser",h=c.linkCondition,g=d.drawPositions||[],I=h===vo&&2===d.roundNumber&&Math.min(...g.filter(Boolean)),U=I||g[n],S=I||g[1-n],y=c.source.structureId,{structure:v}=ts({structureId:y,drawDefinition:u}),{matchUps:w}=Yp({afterRecoveryTimes:!1,inContext:!0,drawDefinition:u,structure:v,event:m}),T=w.filter((t=>t.drawPositions?.includes(o))).filter((t=>{const e=t.sides.find((t=>t.drawPosition===o)),n=t.matchUpStatus===Ga||t.matchUpStatus===Oa&&!$s(t);return e?.sideNumber===t.winningSide&&!n})),P=h===vo&&0===T.length,{positionAssignments:D}=is({structureId:y,drawDefinition:u}),b=D?.find((t=>t.drawPosition===o)),N=b?.participantId,R=c.target.structureId,{positionAssignments:M}=is({structureId:R,drawDefinition:u}),A=M?.filter((({drawPosition:t})=>g.includes(t))),C=A?.some((t=>t.participantId===N));if(C)return{...E};const O=A?.filter((t=>{const e=g.includes(t.drawPosition),n=!t.participantId&&!t.bye&&!t.qualifier;return e&&n})).map((t=>t.drawPosition)),F=O?.includes(U),k=c.target.roundNumber>1&&O?.length,x=1===c.target.roundNumber&&F;if(I){const t=function(){const t="loserLinkFedFMLC";return wr(P?{result:L(),stack:t}:{result:_(),stack:t})}();if(t.error)return wr({result:t,stack:f})}else if(x){const t=L();if(t.error)return wr({result:t,stack:f})}else{if(!N||!k)return wr({result:{error:Q},context:{loserDrawPosition:o,loserTargetLink:c},stack:f});{O.sort(e);const t=O[0],n=Rf({participantId:N,structureId:R,drawPosition:t,inContextDrawMatchUps:r,sourceMatchUpStatus:a,tournamentRecord:s,drawDefinition:u,matchUpsMap:l,event:m});if(n.error)return wr({result:n,stack:f})}}if(v?.seedAssignments&&v.structureId!==R){const t=v.seedAssignments.find((({participantId:t})=>t===N)),e=t?.participantId;t&&e&&vf({eventId:d?.eventId,structureId:R,...t,tournamentRecord:s,drawDefinition:u,participantId:e})}if(p&&i){const t=p.sides?.find((t=>t.sideNumber===3-i));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)),o=[1,2].map((t=>({...a.sides?.find((e=>e.sideNumber===t))||{},sideNumber:t})));a.sides=o;const c=a.sides.find((t=>t.sideNumber===i));c&&(c.lineUp=Tf({lineUp:t.lineUp}),xs({tournamentId:s?.tournamentId,matchUp:a,context:f,drawDefinition:u,eventId:n}))}}return{...E};function _(){return wr({result:bl({drawPosition:S,structureId:R,tournamentRecord:s,drawDefinition:u,event:m}),stack:"assignLoserPositionBye"})}function L(){return wr({result:N?Rf({drawPosition:U,participantId:N,structureId:R,inContextDrawMatchUps:r,sourceMatchUpStatus:a,tournamentRecord:s,drawDefinition:u,matchUpsMap:l,event:m}):{error:Ae},stack:"assignLoserDrawPosition"})}}({sourceMatchUpStatus:r&&u||Ea,loserMatchUpDrawPositionIndex:T,sourceMatchUpId:f,inContextDrawMatchUps:o,projectedWinningSide:a,loserDrawPosition:h,tournamentRecord:s,loserTargetLink:g,drawDefinition:c,loserMatchUp:D,winningSide:l,matchUpsMap:p,dualMatchUp:d,event:I});if(t.error)return wr({result:t,stack:U})}if(b){const t=b.drawPositions||[],e=bl({drawPosition:Math.min(...t.filter(Boolean)),structureId:y.target.structureId,tournamentRecord:s,drawDefinition:c,event:I});if(e.error)return wr({result:e,stack:U})}}return wr({result:{...E,...v},stack:U})}function rI(t){const{inContextDrawMatchUps:e,targetData:n,drawDefinition:r,relevantLink:i}=t;if(i?.linkCondition===vo&&n?.matchUp?.matchUpStatus===Ma)return!1;const{targetMatchUps:{loserMatchUp:a,winnerMatchUp:o},targetLinks:s}=n,c=[Oa,Ga].includes(a?.matchUpStatus),u=o?.drawPositions?.filter(Boolean).length||0;if(a?.winningSide&&!c||o?.winningSide&&2===u&&(!o.feedRound||![Ga,Oa].includes(o?.matchUpStatus)))return!0;const d=a&&Uc({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),p=o&&Uc({matchUpId:o.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),l=d&&rI({relevantLink:s?.loserTargetLink,targetData:d,inContextDrawMatchUps:e,drawDefinition:r});return!(!(p&&rI({targetData:p,inContextDrawMatchUps:e,drawDefinition:r}))&&!l)}function iI(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 eI(t);if(u.winningSide&&u.winningSide!==s){const{connectedStructureIds:e}=tI({drawDefinition:a,structure:c,matchUp:u});e.length&&(console.log({connectedStructureIds:e}),n=!0);const r=Wg(t);if(r.error)return r}const d=nI(t);if(d.error)return wr({result:d,stack:e});let p,l;return t.qualifierChanging&&r?.[bi]?.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===fo){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===ja&&!rI({inContextDrawMatchUps:n,drawDefinition:i,targetData:Uc({matchUpId:c.matchUpId,inContextDrawMatchUps:n,drawDefinition:i})})){const{structure:n}=ts({structureId:c.structureId,drawDefinition:i}),o=rs({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]))}Vs({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:i,structure:n}),e=!0}}}return{...E,qualifierReplaced:e}}(t).qualifierReplaced),t.qualifierAdvancing&&r?.[bi]?.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===fo){const s=r.sides.find((({sideNumber:t})=>t===a))?.participantId,c=v(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===ja&&!rI({inContextDrawMatchUps:n,drawDefinition:i,targetData:Uc({matchUpId:c.matchUpId,inContextDrawMatchUps:n,drawDefinition:i})})){const n=c.sides.find((t=>t.qualifier&&!t.participantId))?.drawPosition,{structure:r}=ts({structureId:c.structureId,drawDefinition:i});if(!r)return{error:Ut};const a=rs({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]))}Vs({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:i,structure:r}),e=!0}}}return{...E,qualifierPlaced:e}}(t).qualifierPlaced),wr({result:vr({...E,...d,connectedStructures:n,qualifierReplaced:p,qualifierPlaced:l}),stack:e})}const aI={drawPositionToRemove:"green",iteration:"brightred",winner:"green",loser:"brightred"};function oI(t){const{inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:i,targetData:a,matchUp:o}=t;let{iteration:s=0}=t;s+=1;const c="removeDoubleExit";Pl({method:c,color:"brightyellow",iteration:s,keyColors:aI});const{targetLinks:{loserTargetLink:u},targetMatchUps:{loserMatchUp:d,winnerMatchUp:p,loserTargetDrawPosition:l}}=a;if(p&&p.matchUpStatus!==Ma){const{stage:e,roundNumber:n,roundPosition:r}=p;Pl({winner:"winner",stage:e,roundNumber:n,roundPosition:r,keyColors:aI}),sI({...t,targetMatchUp:p,sourceMatchUp:o,iteration:s})}if(d&&d.matchUpStatus!==Ma){const a=e.find((({matchUpId:t})=>t===d.matchUpId)),{structure:o}=ts({drawDefinition:r,structureId:a.structureId}),{stage:p,roundNumber:m,roundPosition:f,feedRound:h}=d;if(Pl({loser:"loser",stage:p,roundNumber:m,roundPosition:f,keyColors:aI,feedRound:h}),n?.progression?.doubleExitPropagateBye)zg({drawPosition:l,targetLink:u,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:i});else{const e=sI({...t,structure:o,targetMatchUp:d,iteration:s});if(e.error)return wr({result:e,stack:c})}}return wr({result:{...E},stack:c})}function sI(t){const{inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,sourceMatchUp:i,targetMatchUp:a,matchUpsMap:o,structure:s,iteration:c}=t,u="conditionallyRemoveDrawPosition";Pl({method:u});const d=Uc({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=tf({structureId:s.structureId,matchUp:i,matchUpsMap:o})?.pairedPreviousMatchUp,m=[ka,Fa].includes(f?.matchUpStatus),g=f?.drawPositions?.filter(Boolean)||[];if([...Ya,Ma].includes(f?.matchUpStatus)||f?.winningSide){const t=i.drawPositions||[];let e=a.drawPositions?.filter(Boolean);b(t,e)&&(e=e?.filter((e=>!t.includes(e))));h=t.concat(g).find((t=>e?.includes(t)))}}else h=P(a?.drawPositions||[],p?.drawPositions||[])?.[0];if(p&&h){const{stage:t,roundNumber:n,roundPosition:i}=p;Pl({method:"removeDirectedWinner",drawPositionToRemove:h,keyColors:aI,color:"brightgreen",stage:t,roundNumber:n,roundPosition:i}),Hg({winningDrawPosition:h,winnerMatchUp:p,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:o})}let I=oI({targetData:d,matchUp:a,inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:o,structure:s,iteration:c});if(I.error)return wr({result:I,stack:u});const U=function({pairedPreviousDoubleExit:t,noContextTargetMatchUp:e}){return e.matchUpStatus===Ma?Ma:t?[Fa,Oa].includes(e?.matchUpStatus)?Oa:Ga:ja}({pairedPreviousDoubleExit:m,noContextTargetMatchUp:l}),S=!m;return I=qg({...t,matchUpStatus:U,removeScore:S,score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},removeWinningSide:!0,matchUp:l,matchUpId:a.matchUpId,matchUpStatusCodes:[]}),I.error?wr({result:I,stack:u}):{...E}}function cI(t){const{matchUp:e,matchUpStatus:n,score:r,winningSide:i}=t,a="noDownStreamDependencies";if([ka,Fa].includes(e?.matchUpStatus)&&![ka,Fa].includes(n)){const e=oI(t);if(e.error)return wr({result:e,stack:a})}const o=n===ka,s=$s({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&&Jd(e),{setFormat:a,finalSetFormat:o,bestOf:s}=i??{},c=s&&r===s&&o||a;return c?.timed||!1}(t.inContextMatchUp),u=t.removeScore||!c&&![_a,Na].includes(n||_a),d=t.isCollectionMatchUp&&t.dualMatchUp.winningSide&&!t.projectedWinningSide||e.winningSide&&!i&&!$s({score:r}),p=n&&n!==ja,l=n=>{let r;const{structure:i,drawDefinition:a,dualMatchUp:o,disableAutoCalc:s}=t;if(o?._disableAutoCalc&&!1!==s)return eI(t);const{connectedStructureIds:c}=tI({drawDefinition:a,structure:i,matchUp:e});c.length&&(console.log({connectedStructureIds:c}),r=!0),Object.assign(t,{removeScore:n});const u=Wg(t);if(u.error)return u;if(t.removingQualifier&&t.appliedPolicies?.[bi]?.autoRemoveQualifiers){const e=function(t){let e;const{inContextDrawMatchUps:n,inContextMatchUp:r,drawDefinition:i}=t,a=t.targetData.targetLinks?.winnerTargetLink;if(a.target.feedProfile===fo){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===ja&&!rI({inContextDrawMatchUps:n,drawDefinition:i,targetData:Uc({matchUpId:s.matchUpId,inContextDrawMatchUps:n,drawDefinition:i})})){const{structure:n}=ts({structureId:s.structureId,drawDefinition:i}),r=rs({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]))}Vs({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:i,structure:n}),e=!0}}}return{qualifierRemoved:e}}(t);return{...E,connectedStructures:r,...e}}return{...E,connectedStructures:r}};if(d&&i&&t.isCollectionMatchUp)return uI(t);const m=[Aa,Na].includes(n)&&t.dualWinningSideChange;return wr({result:(i||m)&&iI(t)||s&&l(u)||p&&Xg(t)||d&&l(u)||e&&uI({...t,removeScore:!0})||{...E},stack:a})}function uI(t){if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){const e=Wg(t);if(e.error)return e}const e=qg({...t});if(t.isCollectionMatchUp){const{matchUpTieId:e,drawDefinition:n,event:r,matchUpsMap:i}=t,{removeWinningSide:a}=$g({tournamentRecord:t.tournamentRecord,matchUpId:e,drawDefinition:n,matchUpsMap:i,event:r});a&&console.log("REMOVE WINNING SIDE")}return wr({result:e,stack:"scoreModification"})}function dI({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,courtDayDate:a,matchUpId:o,courtIds:s}){if(!n&&!e)return{error:_};if(!o)return{error:qt};const c=Xm({drawDefinition:r,matchUpId:o});if(c.error)return c;if(c?.matchUp?.matchUpType!==Xs)return{error:Yt};if(!(void 0===s||Array.isArray(s)&&s.length&&s.every((t=>"string"==typeof t))))return{error:Nn,context:{courtIds:s}};let u;if(s){const t=Am({tournamentRecords:e||n&&{[n.tournamentId]:n}});if(t.error)return t;const r=t.courts?.filter((t=>s.includes(t.courtId)));if(r?.length!==s.length)return{error:Nn,context:{courtIds:s}};u=r?.map((t=>({venueId:t.venueId,courtId:t.courtId})))}return Ff({duplicateValues:!1,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o,timeItem:{itemType:Pu,itemDate:a,itemValue:u}})}function pI({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,venueId:o}){if(!n)return{error:_};if(!a)return{error:qt};if(o){const t=Cd({tournamentRecords:e,tournamentRecord:n,venueId:o});if(t.error)return t}return Ff({duplicateValues:!1,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:{itemType:Tu,itemValue:o}})}function lI({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,courtDayDate:a,matchUpId:o,courtId:s}){if(!n&&!e)return{error:_};if(!o)return{error:qt};if(s){const t=Od({tournamentRecords:e,tournamentRecord:n,courtId:s});if(t.error)return t;const a=t.venue?.venueId;pI({tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o,venueId:a})}return Ff({duplicateValues:!1,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o,timeItem:{itemType:Du,itemDate:a,itemValue:s}})}function mI(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 wr({result:{error:qt},stack:e});if(!$r(s))return wr({result:{error:le},stack:e});if(!n){const t=Xm({drawDefinition:a,matchUpId:c});if(t.error)return wr({result:t,stack:e});n=t.matchUp}const u=ri(s),d=Pd({matchUp:n}).scheduledDate,p=u&&!d,l=xd({matchUp:n}).timeModifiers||[];if(l?.length){const t=fI({disableNotice:!0,removePriorValues:r,tournamentRecord:i,timeModifiers:[],drawDefinition:a,matchUpId:c,matchUp:n});if(t?.error)return wr({result:t,stack:e})}const m=oi(s,!0,p);return Ff({duplicateValues:!1,removePriorValues:r,tournamentRecord:i,drawDefinition:a,disableNotice:o,matchUpId:c,timeItem:{itemType:Mu,itemValue:m}})}function fI({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,timeModifiers:i,matchUpId:a,matchUp:o}){const s="addMatchUpTimeModifiers";if(!a)return wr({result:{error:qt},stack:s});if(void 0!==i&&!Array.isArray(i))return wr({info:Pf("timeModifiers"),result:{error:Nn},stack:s});if(!o){const t=Xm({drawDefinition:n,matchUpId:a});if(t.error)return wr({result:t,stack:s});o=t.matchUp}let c=xd({matchUp:o}).timeModifiers||[];const u=i.filter((t=>!c.includes(t)));if(i.length&&!u.length)return{...E};if(u.some((t=>Vu.includes(t)))){c=c.filter((t=>!Vu.includes(t)));const r=mI({disableNotice:!0,removePriorValues:t,scheduledTime:"",tournamentRecord:e,drawDefinition:n,matchUpId:a});if(r.error)return wr({result:r,stack:s})}const d=i?.length?[...u,...c]:void 0;return Ff({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:a,timeItem:{itemType:Fu,itemValue:d}})}function hI(t,e){const n=Br.test(t)?t:ni(t),r=ri(t)||ri(e)||zr(new Date);return new Date(`${r}T${n}`).getTime()}function gI({errorOnAnachronism:t=!1,checkChronology:e=!0,matchUpDependencies:n,inContextMatchUps:r,removePriorValues:i,tournamentRecords:a,tournamentRecord:o,drawDefinition:s,disableNotice:c,drawMatchUps:u,matchUpId:d,schedule:l,event:m}){if(!l)return{error:ae,info:"Missing schedule"};if(!s)return{error:j};if(!d)return{error:qt};const f="addMatchUpScheduleItems";let h,g;if(u)h=u.find((t=>t.matchUpId===d));else{const t=Xm({drawDefinition:s,event:m,matchUpId:d});if(t.error)return t;h=t.matchUp}const{endTime:I,courtId:U,courtIds:S,courtOrder:y,resumeTime:v,scheduledDate:w,scheduledTime:T,startTime:P,stopTime:D,timeModifiers:b,venueId:N}=l;!e||n&&r||({matchUpDependencies:n,matchUps:r}=Sl({drawDefinition:s}));const R=n?.[d]?.matchUpIds;if(l.scheduledDate&&e&&R){const e=r?.filter((t=>(t.schedule?.scheduledDate||ri(t.schedule?.scheduledTime))&&R.includes(t.matchUpId))).map((({schedule:t})=>{const e=Gr(t);return new Date(e).getTime()}));if(e?.length){const n=Gr(l),r=new Date(n).getTime();if(Math.max(...e)>=r){if(t)return wr({result:{error:O},stack:f});g=O}}}if(void 0!==w){const t=II({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,scheduledDate:w,matchUpId:d});if(t?.error)return wr({result:t,stack:f,context:{scheduledDate:w}})}if(void 0!==T){const t=mI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,scheduledTime:T,matchUpId:d,matchUp:h});if(t?.error)return wr({result:t,stack:f,context:{scheduledTime:T}})}if(void 0!==P){const t=SI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,matchUpId:d,startTime:P,event:m});if(t?.error)return wr({result:t,stack:f,context:{startTime:P}})}if(void 0!==D){const t=vI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,matchUpId:d,stopTime:D,event:m});if(t?.error)return wr({result:t,stack:f,context:{stopTime:D}})}if(void 0!==v){const t=wI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,resumeTime:v,matchUpId:d,event:m});if(t?.error)return wr({result:t,stack:f,context:{resumeTime:v}})}if(void 0!==I){const t=yI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,matchUpId:d,endTime:I,event:m});if(t?.error)return wr({result:t,stack:f,context:{endTime:I}})}if(void 0!==S){const t=dI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,matchUpId:d,courtIds:S});if(t?.error)return wr({result:t,stack:f,context:{courtIds:S}})}if(void 0!==U&&void 0!==w){const t=lI({courtDayDate:w,disableNotice:!0,removePriorValues:i,tournamentRecords:a,tournamentRecord:o,drawDefinition:s,matchUpId:d,courtId:U});if(t?.error)return wr({result:t,stack:f,context:{courtId:U}})}if(void 0!==N){const t=pI({disableNotice:!0,removePriorValues:i,tournamentRecords:a,tournamentRecord:o,drawDefinition:s,matchUpId:d,venueId:N});if(t?.error)return wr({result:t,stack:f,context:{venueId:N}})}if(void 0!==y&&p(y)){const t=UI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,courtOrder:y,matchUpId:d});if(t?.error)return wr({result:t,stack:f,context:{courtOrder:y}})}if(void 0!==b){const t=fI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,timeModifiers:b,matchUpId:d,matchUp:h});if(t?.error)return wr({result:t,stack:f,context:{timeModifiers:b}})}return c||xs({tournamentId:o?.tournamentId,eventId:m?.eventId,context:f,drawDefinition:s,matchUp:h}),g?{...E,warnings:[g]}:{...E}}function II({scheduledDate:t,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a}){if(!a)return{error:qt};const o=t&&Vr.test(t);if(t&&!o)return{error:pe};return Ff({duplicateValues:!1,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:{itemValue:ri(t),itemType:Nu}})}function UI({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:i,courtOrder:a,matchUpId:o}){if(!o)return{error:qt};if(a&&!p(a))return{error:Nn,info:"courtOrder must be numeric"};const s=a&&n(a);return Ff({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:i,matchUpId:o,timeItem:{itemType:bu,itemValue:s}})}function SI({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,startTime:a,event:o}){if(!i)return{error:qt};if(!$r(a))return{error:le};const{matchUp:s}=Xm({drawDefinition:n,event:o,matchUpId:i}),{scheduledDate:c}=Pd({matchUp:s}),u=(s?.timeItems??[]).filter((t=>[Eu,Cu,Ou].includes(t?.itemType))).map((t=>hI(t.itemValue,c))).reduce(((t,e)=>!t||e<t?e:t),void 0);if(!u||hI(a,c)<u){s?.timeItems&&(s.timeItems=s.timeItems.filter((t=>t.itemType!==Au)));const o=oi(a,!0,!0);return Ff({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,timeItem:{itemType:Au,itemValue:o}})}return{error:un}}function yI({validateTimeSeries:t=!0,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,endTime:o,event:s}){if(!a)return{error:qt};if(!$r(o))return{error:le};const{matchUp:c}=Xm({drawDefinition:r,event:s,matchUpId:a}),{scheduledDate:u}=Pd({matchUp:c}),d=(c?.timeItems??[]).filter((t=>[Au,Cu,Eu].includes(t?.itemType))).map((t=>hI(t.itemValue,u))).reduce(((t,e)=>!t||e>t?e:t),void 0);if(!t||!d||hI(o,u)>d){c?.timeItems&&(c.timeItems=c.timeItems.filter((t=>t.itemType!==Ou)));const t=oi(o,!0,!0);return Ff({duplicateValues:!1,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:{itemType:Ou,itemValue:t}})}return{error:on}}function vI({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,stopTime:a,event:o}){if(!i)return{error:qt};if(!$r(a))return{error:le};const{matchUp:s}=Xm({drawDefinition:n,event:o,matchUpId:i}),{scheduledDate:c}=Pd({matchUp:s}),u=s?.timeItems??[];if(u.reduce(((t,e)=>e.itemType===Ou||t),void 0))return{error:sn};const d=u.filter((t=>[Au,Cu,Eu].includes(t?.itemType))).sort(((t,e)=>hI(t.itemValue,c)-hI(e.itemValue,c))),p=d[d.length-1],l=p&&p.itemType===Eu,m=d.filter((t=>!l||t.createdAt!==p.createdAt)).map((t=>hI(t.itemValue,c))).reduce(((t,e)=>!t||e>t?e:t),void 0);if(hI(a,c)>m){if(s?.timeItems&&l){const t=p.createdAt;s.timeItems=s.timeItems.filter((e=>e.createdAt!==t))}return Ff({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,timeItem:{itemValue:oi(a,!0,!0),itemType:Eu}})}return{error:cn}}function wI({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,resumeTime:i,matchUpId:a,event:o}){if(!a)return{error:qt};if(!$r(i))return{error:le};const{matchUp:s}=Xm({drawDefinition:n,event:o,matchUpId:a}),{scheduledDate:c}=Pd({matchUp:s}),u=s?.timeItems??[];if(u.reduce(((t,e)=>e.itemType===Ou||t),void 0))return{error:sn};const d=u.filter((t=>[Au,Cu,Eu].includes(t?.itemType))).sort(((t,e)=>hI(t.itemValue,c)-hI(e.itemValue,c))),p=d[d.length-1],l=p&&p.itemType===Cu,m=d.filter((t=>!l||t.createdAt!==p.createdAt)).map((t=>hI(t.itemValue,c))).reduce(((t,e)=>!t||e>t?e:t),void 0);if(hI(i,c)>m){if(s?.timeItems&&l){const t=p.createdAt;s.timeItems=s.timeItems.filter((e=>e.createdAt!==t))}return Ff({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:a,timeItem:{itemValue:oi(i,!0,!0),itemType:Cu}})}return{error:dn}}function TI({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:n,winningSide:r,score:i}){if("object"!=typeof i)return{error:Nn};const{sets:a,scoreStringSide1:o,scoreStringSide2:s}=i,c="scoreString must be a string!";if(void 0!==o&&"string"!=typeof o)return{error:Nn,info:c};if(void 0!==s&&"string"!=typeof s)return{error:Nn,info:c};if(void 0!==a&&!Array.isArray(a))return{error:Nn,info:Pf("sets")};if(a?.length){const o=a.map((t=>t?.setNumber)).filter(Boolean);if(o.length!==m(o).length)return{error:Nn,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!==t)))).every((t=>t.every((t=>p(t))))))return{error:Nn,info:"non-numeric values"};if(![c,s].filter((t=>void 0!==t)).every((t=>p(t))))return{error:Nn,info:"non-numeric values"};if(s&&![1,2].includes(s))return{error:Nn,info:"winningSide must be 1 or 2"}}const{valid:s}=function({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;return n?(t[n-1]++,t):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?Jd(e):void 0,l=Math.max(...o),m=g(o)[l],f=p?.bestOf,h=f&&Math.ceil(f/2)||1,I=n??t,U=I&&[Oa,Ba,Ga].includes(I),S=!p||!a.length||a.every(((t,e)=>{const n=e+1,r=n===f,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:h,setFormat:g}=p,I=r&&h||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}}return!I.setTo||!(!I.noTiebreak&&l>I.setTo+1)})),y=(!e||l===h)&&1===m&&o.indexOf(l)+1||void 0;return{valid:S&&(r&&u>d&&r===y||!r&&!y||U)}}({existingMatchUpStatus:t,matchUpStatus:n,matchUpFormat:e,winningSide:r,score:i});if(!s)return{error:he,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}function PI(t){const e="setMatchUpStatus";t.matchUpStatus&&[Ga,ka].includes(t.matchUpStatus)&&(t.score=void 0);const{allowChangePropagation:n,disableScoreValidation:r,tournamentRecords:i,tournamentRecord:a,disableAutoCalc:o,enableAutoCalc:s,drawDefinition:c,matchUpStatus:u,winningSide:d,matchUpId:p,event:l,score:m}=t;if(!c)return{error:j};if(u&&[Aa,_a,Na,ja].includes(u)&&d)return{error:Nn,winningSide:d,matchUpStatus:u};if(![void 0,...Wa].includes(u))return wr({result:{error:_t},info:"matchUpStatus does not exist",stack:"setMatchUpStatus"});const f=xc({drawDefinition:c}),{matchUps:h}=Jp({nextMatchUps:!0,inContext:!0,drawDefinition:c,matchUpsMap:f,event:l}),g=f.drawMatchUps.find((t=>t.matchUpId===p)),I=h?.find((t=>t.matchUpId===p));if(!g||!h)return{error:Wt};if((g.winningSide||d)&&u===Ma)return{context:"Cannot have Bye with winningSide",error:xt,matchUpStatus:u};const U=I?.structureId,{structure:S}=ts({drawDefinition:c,structureId:U}),y=I?.drawPositions?.filter(Boolean);let v;if(g.matchUpType===Qs){if(o)Nr({extension:{name:Hi,value:!0},element:g});else if(s){const e=g.winningSide;Dr({name:Hi,element:g});const{winningSide:n,scoreStringSide1:r,scoreStringSide2:i,set:a}=_g({drawDefinition:c,matchUpsMap:f,structure:S,matchUp:g,event:l}),o={scoreStringSide1:r,scoreStringSide2:i,sets:a?[a]:[]};v=n!==e,Object.assign(t,{winningSide:n,dualWinningSideChange:v,projectedWinningSide:n,score:o})}Vf({tournamentId:a?.tournamentId,inContextDualMatchUp:I,eventId:l?.eventId,drawDefinition:c,dualMatchUp:g})}if(g.matchUpType===Qs&&u&&[Ra].includes(u))return{error:Nn,info:"Not supported for matchUpType: TEAM"};const w=I?.matchUpTieId,T=Uc({matchUpId:w||p,inContextDrawMatchUps:h,drawDefinition:c});if(m&&g.matchUpType!==Qs&&!r){const t=g.matchUpFormat??S?.matchUpFormat??c?.matchUpFormat??l?.matchUpFormat,e=TI({existingMatchUpStatus:g.matchUpStatus,matchUpFormat:t,matchUpStatus:u,winningSide:d,score:m});if(e.error)return e}const P=g?.sides?[]:rs({drawDefinition:c,structureId:U}).positionAssignments,D=2===g.sides?.map((t=>t.participantId)).filter(Boolean).length||2===y?.length&&P?.filter((t=>y.includes(t.drawPosition))).every((t=>t.participantId));if(u&&$a.includes(u)&&!D)return wr({info:"present in participantRequiredMatchUpStatuses",context:{matchUpStatus:u,bothSideParticipants:D},result:{error:_t}});const b=Dc({policyTypes:[bi],tournamentRecord:a,drawDefinition:c,event:l})?.appliedPolicies??{};"object"==typeof t.policyDefinitions&&Object.assign(b,t.policyDefinitions);const N=I?.stage===Qa&&1===I.finishingRound,R=N&&d,M=N&&g.winningSide&&!d&&(!t.matchUpStatus||t.matchUpStatus&&Hs({matchUpStatus:t.matchUpStatus}))&&(!t.outcome||!$s({outcome:t.outcome})),A=R&&d!==g.winningSide&&g.winningSide;if(Object.assign(t,{inContextDrawMatchUps:h,qualifierAdvancing:R,qualifierChanging:A,removingQualifier:M,inContextMatchUp:I,appliedPolicies:b,matchUpTieId:w,matchUpsMap:f,targetData:T,structure:S,matchUp:g}),w){const{matchUp:e}=Xm({matchUpId:w,inContext:!0,drawDefinition:c,matchUpsMap:f,event:l});if(e){const n=$d({matchUp:e,drawDefinition:c,structure:S,event:l})?.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=gi(i,void 0,!0);for(const t of d?.tieMatchUps||[])t.matchUpId===s.matchUpId&&(t.winningSide=r,t.score=u,$s({score:u})||e?e&&(t.matchUpStatus=e):Object.assign(t,{...Lg}));a=a??$d({matchUp:s,structure:o,drawDefinition:t,event:c})?.tieFormat;const{winningSide:p}=_g({matchUp:d,drawDefinition:t,matchUpsMap:n,structure:o,tieFormat:a,event:c});return{projectedWinningSide:p}}({drawDefinition:c,matchUpStatus:u,dualMatchUp:e,matchUpsMap:f,winningSide:d,tieFormat:n,structure:S,matchUp:g,event:l,score:m});v=r!==e.winningSide,Object.assign(t,{isCollectionMatchUp:!0,dualWinningSideChange:v,projectedWinningSide:r,matchUpTieId:w,dualMatchUp:e,tieFormat:n})}}const E=rI(t),C=Ws({matchUpStatus:u});if(!w){if(E&&!d&&(u&&Hs({matchUpStatus:u})||u&&[ka,Fa].includes(u)))return{error:xt,activeDownstream:E,winningSide:d};if(d&&d===g.winningSide&&u&&!C)return{context:"winningSide must include directing matchUpStatus",error:xt,directingMatchUpStatus:C,matchUpStatus:u}}const{schedule:O}=t;if(O){const t=gI({disableNotice:!0,tournamentRecords:i,tournamentRecord:a,drawDefinition:c,matchUpId:p,schedule:O});if(t.error)return t}const F=g.matchUpType!==Qs&&!v&&d&&g.winningSide&&g.winningSide!==d;if(n&&F&&g.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}=Yp(t),m=l.filter((({drawPositions:t,roundNumber:e})=>t?.includes(c)&&e>a));Qn({changeWinner:!0})&&console.log({existingWinnerSubsequentMatchUps:m}),m.forEach((n=>{n.drawPositions=n.drawPositions?.map((t=>t===c?d:t))||[],xs({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,S=[I?.target.structureId,U?.target?.structureId].filter(Boolean);return i.structures.filter((({stage:t,structureId:e})=>t!==f&&S.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}=rs({structure:t}),n=e?.find((({participantId:t})=>t===u)),r=e?.find((({participantId:t})=>t===p));n&&(n.participantId=p),r&&(r.participantId=u)})),qg(t)}(t);const k=d&&!w||t.projectedWinningSide;Pl({method:e,activeDownstream:E,matchUpWinner:k,winningSide:d});const x=!E&&cI(t)||k&&function(t){const{matchUp:e,winningSide:n,matchUpTieId:r,dualWinningSideChange:i}=t;return n===e.winningSide||r&&!i?DI(t):wr({stack:"winningSideWithDownstreamDependencies",result:{error:ve},context:{winningSide:n,matchUp:e}})}(t)||C&&DI(t)||{error:An};return wr({result:x,stack:e})}function DI(t){const{tournamentRecord:e,matchUp:n,event:r}=t,i=t.isCollectionMatchUp&&n.winningSide&&!t.winningSide&&!$s({score:t.score}),a=t.isCollectionMatchUp?t.matchUpStatus||i&&ja||Ea:t.matchUpStatus||Ea,o=t.removeScore||[Aa,Ga].includes(a)&&![_a,Na].includes(a),s=qg({...t,matchUpStatus:a,removeWinningSide:i,removeScore:o});if(s.error)return s;if(t.isCollectionMatchUp){const{matchUpTieId:n,drawDefinition:i,matchUpsMap:a}=t,o=$g({matchUpId:n,tournamentRecord:e,drawDefinition:i,matchUpsMap:a,event:r});if(o.error)return o;Object.assign(s,{tieMatchUpResult:o})}return s}function bI({event:t,orderedDrawIdsMap:e}){if("object"!=typeof t)return{error:Tt};if(!e)return{error:ae,info:"Missing drawIdsOrderMap"};if("object"!=typeof e)return{error:Nn,info:"orderedDrawIdsMap must be an object"};const n=Object.values(e);if(!n.every((t=>!isNaN(t))))return{error:Nn,info:"drawOrder must be numeric"};if(m(n).length!==n.length)return{error:Nn,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&&P(n,r).length!==n.length)return{error:Nn,info:"Missing drawIds"};t.drawDefinitions.forEach((t=>{t.drawOrder=e[t.drawId]}))}const{flightProfile:r}=Bd({event:t});return r?.flights?.forEach((t=>{t.flightNumber=e[t.drawId]})),{...E}}function NI({tournamentRecord:t,event:e}){if(!t)return{error:_};if(!e)return{error:Tt};const{flightProfile:n}=Bd({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?bI({event:e,orderedDrawIdsMap:r}):{...E}}function RI({drawDefinition:t,timeItem:e}){if(!t)return{error:q};if(!e)return{error:mn};const n=e&&Object.keys(e),r=["itemType","itemValue"];if(!(r.filter((t=>n.includes(t))).length===r.length))return{error:pn};t.timeItems||(t.timeItems=[]);const i=(new Date).toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),_s({drawDefinition:t}),{...E}}function MI({stageSequence:t=1,drawDefinition:e,drawSize:n,stage:r}){if(!e)return{error:j};if(!uu({drawDefinition:e,stage:r}))return{error:At};const i=function({stage:t,drawDefinition:e}){return au.reduce(((n,r)=>(du({drawDefinition:e,entryStatus:r,stage:t})||0)+n),0)}({drawDefinition:e,stage:r}),{qualifiersCount:a}=Ql({drawDefinition:e,stageSequence:t,stage:r});if(n<i+a)return{error:rt};const{entryProfile:o}=Gc({attributes:[{[r]:{drawSize:n}}],drawDefinition:e});return Ls({drawDefinition:e}),{...E,entryProfile:o}}function AI({qualifiersCount:t=0,drawDefinition:e,stage:n}){return e?uu({drawDefinition:e,stage:n})?n!==Xa?{error:rt,info:"qualifiersCount can only be set for main stage"}:(Gc({attributes:[{[n]:{qualifiersCount:t}}],drawDefinition:e}),Ls({drawDefinition:e}),{...E}):{error:At}:{error:j}}function EI({updateInProgressMatchUps:t,originalValueGoal:e,tournamentRecord:n,wasAggregateValue:r,tieFormatName:i,drawDefinition:a,structureId:o,structure:s,tieFormat:c,matchUpId:u,matchUp:d,eventId:p,event:l}){const{aggregateValue:m,valueGoal:f}=Jf(c);c.winCriteria=vr({aggregateValue:m,valueGoal:f}),(e&&e!==f||m&&!r)&&(i?c.tieFormatName=i:delete c.tieFormatName);const{targetMatchUps:h}=function({updateInProgressMatchUps:t,drawDefinition:e,structureId:n,structure:r,matchUpId:i,matchUp:a}){let o=[];return i&&a?o=[a]:n&&r?o=Yp({matchUpFilters:{matchUpTypes:[Qs]},structure:r})?.matchUps??[]:e&&(o=Ul({matchUpFilters:{matchUpTypes:[Qs]},drawDefinition:e})?.matchUps??[]),{targetMatchUps:o.filter((e=>!e.winningSide&&e.matchUpStatus!==Ea&&(t||e.matchUpStatus!==xa&&!$s(e))))}}({updateInProgressMatchUps:t,drawDefinition:a,structureId:o,structure:s,matchUpId:u,matchUp:d});!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=Yf(i)),t){const t=$g({matchUpId:o.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,drawDefinition:n,event:a});if(t.error)return t;s=t.score}r&&!s&&xs({tournamentId:e?.tournamentId,context:"updateTargetTeamMatchUps",eventId:a?.eventId,matchUp:o,drawDefinition:n})}}({updateInProgressMatchUps:t,tournamentRecord:n,targetMatchUps:h,drawDefinition:a,tieFormat:c,event:l});const g=vr(c),I=fh({tieFormat:g});if(I.error)return I;if(p&&l)l.tieFormat=g;else if(u&&d)d.tieFormat=c;else if(s)s.tieFormat=g;else if(a)a.tieFormat=g;else if(!d||!a)return{error:j};return Ls({drawDefinition:a,eventId:l?.eventId}),{...E}}function CI({tieFormat:t,orderMap:e}){const n=Yf(t);return n.collectionDefinitions.forEach((t=>{const n=e[t.collectionId];n&&(t.collectionOrder=n)})),n.collectionDefinitions.sort(((t,e)=>h(t.collectionOrder)-h(e.collectionOrder))),n}function OI({tournamentRecord:t,structureIds:e,orderMap:n,event:r}){const i=CI({tieFormat:r.tieFormat,orderMap:n});e?.length||(r.tieFormat=i);for(const i of r.drawDefinitions??[])FI({tournamentRecord:t,drawDefinition:i,structureIds:e,orderMap:n,event:r})}function FI({tournamentRecord:t,drawDefinition:e,structureIds:n,orderMap:r,event:i}){const a=CI({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=CI({tieFormat:a.tieFormat??e.tieFormat??i?.tieFormat,orderMap:r})),kI({eventId:i?.eventId,tournamentRecord:t,drawDefinition:e,structure:a,orderMap:r}),o.push(a.structureId));Ls({drawDefinition:e,structureIds:o})}function kI({tournamentRecord:t,drawDefinition:e,structure:n,orderMap:r,eventId:i}){const a=Yp({matchUpFilters:{matchUpTypes:[Qs]},structure:n})?.matchUps;for(const n of a)n.tieFormat&&(n.tieFormat=CI({tieFormat:n.tieFormat,orderMap:r}),xs({tournamentId:t?.tournamentId,drawDefinition:e,eventId:i,matchUp:n}))}function xI({updateInProgressMatchUps:t=!0,tieFormatComparison:e,tournamentRecord:n,drawDefinition:r,tieFormatName:i,collectionId:a,structureId:o,matchUpId:s,eventId:c,matchUp:u,event:d}){const p="removeCollectionDefinition";let l=u?void 0:Zf({drawDefinition:r,structureId:o,matchUpId:s,eventId:c,event:d});if(l?.error)return wr({result:l,stack:p});const m=l?.structure;u=u??l?.matchUp;const f=l?.tieFormat,h=Yf(f);if(l=fh({tieFormat:h}),l.error)return wr({result:l,stack:p});const g=h?.collectionDefinitions?.find((t=>t.collectionId===a));if(!g)return wr({result:{error:On,collectionId:a}});h.collectionDefinitions=h.collectionDefinitions.filter((t=>t.collectionId!==a)),g.collectionGroupNumber&&(h.collectionDefinitions=h.collectionDefinitions.map((t=>{const{collectionGroupNumber:e,...n}=t;return n})),h.collectionGroups=h.collectionGroups.filter((({groupNumber:t})=>t!==g.collectionGroupNumber)));const{aggregateValue:I,valueGoal:U}=Jf(h);h.winCriteria=vr({aggregateValue:I,valueGoal:U});const S=f?.winCriteria.valueGoal,y=f?.winCriteria.aggregateValue;(S&&S!==U||I&&!y)&&(i?h.tieFormatName=i:delete h.tieFormatName);let v=[];s&&u?v=[u]:o&&m?v=Yp({matchUpFilters:{matchUpTypes:[Qs]},structure:m})?.matchUps??[]:r?v=Ul({matchUpFilters:{matchUpTypes:[Qs]},drawDefinition:r})?.matchUps??[]:d&&(v=fl({matchUpFilters:{matchUpTypes:[Qs]},drawDefinition:r})?.matchUps??[]);const w=(v||[]).filter((n=>{const r=n.tieMatchUps?.filter((t=>t.collectionId===a)),i=r?.some($s),o=!(!e||!n.tieFormat)&&Uh({descendant:n.tieFormat,ancestor:h})?.different;return t&&!i||!n.winningSide&&n.matchUpStatus!==Ea&&(t||n.matchUpStatus!==xa&&!$s(n)&&!o)}));if(!w.length)return{error:Sn};if(s&&u&&t){const t=u.tieMatchUps?.filter((t=>t.collectionId===a));for(const e of t??[]){let t=PI({matchUpId:e.matchUpId,tieMatchUpId:u?.matchUpId,winningSide:void 0,removeScore:!0,tournamentRecord:n,drawDefinition:r,event:d});if(t.error)return t;if(t=Xm({drawDefinition:r,matchUpId:s}),t.error)return t;u=t?.matchUp}}const T=[];for(const e of w){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=Yf(h)),t){const t=$g({matchUpId:e.matchUpId,exitWhenNoValues:!0,tournamentRecord:n,drawDefinition:r,event:d});if(t.error)return t}xs({tournamentId:n?.tournamentId,eventId:d?.eventId,drawDefinition:r,context:p,matchUp:e})}T.length&&ks({tournamentId:n?.tournamentId,matchUpIds:T,eventId:d?.eventId,drawDefinition:r});const P=vr(h);if(l=fh({tieFormat:P}),l.error)return wr({result:l,stack:p});if(c&&d)d.tieFormat=P;else if(s&&u)u.tieFormat=P;else if(m)m.tieFormat=P;else if(r)r.tieFormat=P;else if(!u||!r)return{error:j};Ls({drawDefinition:r,eventId:d?.eventId});const{appliedPolicies:D}=Dc({tournamentRecord:n});if(D?.audit?.[ua]){Th({drawDefinition:r,auditData:vr({drawId:r?.drawId,action:p,collectionId:a,structureId:o,matchUpId:s,eventId:c})})}return{tieFormat:P,deletedMatchUpIds:T,targetMatchUps:w,...E}}function _I({targetEntryRound:t=1,finishingPositions:e,sourceRoundNumber:n,sourceStructureId:r,targetStructureId:i,linkType:a=So}){if(!r||!i)return{error:It};return{link:vr({linkType:a,source:{roundNumber:n,structureId:r,finishingPositions:e},target:{feedProfile:fo,roundNumber:t,structureId:i}})}}function LI({roundPosition:t,roundNumber:e,idPrefix:n,uuids:r}){return n?`${n}-${e}-${t}`:r?.pop()||Md()}function BI({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:LI({roundPosition:d,roundNumber:n,idPrefix:i,uuids:o})};u.push(f);const h={drawPositions:f.children.map((t=>t?.drawPosition)).filter(Boolean),matchUpStatus:ja,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 VI({finishingPositionOffset:t,finishingPositionLimit:e,qualifyingRoundNumber:n,qualifyingPositions:i,matchUpType:a,roundLimit:o,idPrefix:s,drawSize:c,isMock:u,uuids:d}){if(isNaN(c)||c<2||i&&c<=i)return{matchUps:[],roundsCount:0};if(i&&(!r(c)||c%i)){let t=i;for(;t<c;)t*=2;c=t}const p=i&&!(c%2)&&(!isNaN(i)||n&&!isNaN(n))&&(c/i===Math.round(c/i)||n&&c/n===Math.round(c/n));if(!r(c)&&!p)return{matchUps:[],roundsCount:0};const l=w(1,c+1).map((t=>({drawPosition:t})));let m,f=[],h=1;for(({roundNodes:m,matchUps:f}=BI({matchUpType:a,roundNumber:h,idPrefix:s,matchUps:f,isMock:u,nodes:l,uuids:d})),h++,o=o??n;m.length>1;)i&&m.length===i&&(o=h-1),({roundNodes:m,matchUps:f}=BI({nodes:m,matchUpType:a,roundNumber:h,idPrefix:s,matchUps:f,isMock:u,uuids:d})),h++;const g=h-1;return f=Xp({finishingPositionOffset:t,finishingPositionLimit:e,roundsCount:g,roundLimit:o,matchUps:f}),o?f=f.filter((t=>o&&(t.roundNumber??0)<=o)):o=h-1,{drawSize:c,matchUps:f,roundsCount:g,roundLimit:o}}function jI(t){const e="generateQualifyingStructure";if(!t.drawDefinition)return wr({result:{error:j},stack:e});if(t.drawSize&&!p(t.drawSize)||t.participantsCount&&!p(t.participantsCount)||t.qualifyingPositions&&!p(t.qualifyingPositions))return wr({result:{error:Nn},stack:e});let n=t.drawSize??a(t.participantsCount);const{qualifyingRoundNumber:r,qualifyingPositions:i,targetStructureId:o,structureOptions:s,appliedPolicies:c,drawDefinition:u,matchUpFormat:d,structureName:l,structureId:m,roundTarget:f,drawType:h,idPrefix:g,isMock:I,uuids:U}=t;if(!t.drawSize)return wr({result:{error:it},context:{drawSize:n},stack:e});if(i&&i>=t.drawSize)return wr({result:{error:Nn},context:{drawSize:n,qualifyingPositions:i},stack:e});let S,y,v,w,T,P=0;const{structureProfiles:D}=Gm({drawDefinition:u}),b=D[o];if(!b)return wr({result:{error:Ut},context:{targetStructureId:o},stack:e});const N=u.matchUpType,R=f?`${f}-`:"",M=b.stage===Qa,A=c?.[Pi]?.namingConventions?.pre??op[Pi]?.namingConventions?.pre,C=M&&A?`${A}-`:"",O=l??(R?`${C}${wm(Qa)} ${R}`:`${C}${wm(Qa)}`);if(h===Go){const{maxRoundNumber:t,structures:e,groupCount:r}=pf({structureName:l??O,structureId:m??U?.pop(),stage:Qa,structureOptions:s,appliedPolicies:c,stageSequence:1,matchUpType:N,roundTarget:f,idPrefix:g,drawSize:n,isMock:I,uuids:U});P=r,S=t,v=e[0],T=[1]}else({drawSize:n,matchUps:w,roundLimit:S,roundsCount:y}=VI({qualifyingRoundNumber:r,qualifyingPositions:i,matchUpType:N,idPrefix:g,drawSize:n,isMock:I,uuids:U})),S||(S=y),v=Tm({structureName:l??O,structureId:m??U?.pop(),qualifyingRoundNumber:S,stage:Qa,matchUpFormat:d,stageSequence:1,matchUpType:N,roundLimit:S,matchUps:w}),f&&Nr({extension:{name:ra,value:f},element:v}),P=w?.filter((t=>t.roundNumber===S))?.length;const F=h===Go?Uo:So,k=v&&S&&_I({sourceStructureId:v.structureId,sourceRoundNumber:S,targetStructureId:o,finishingPositions:T,linkType:F})?.link;return{qualifyingDrawPositionsCount:n,qualifiersCount:P,...E,structure:v,link:k}}function GI(t){let e=t.structureIds;const{tournamentRecord:n,drawDefinition:r,matchUpFormat:i,structureId:a,matchUpId:o,event:s}=t;if(!r)return{error:j};if(!i)return{error:Vt};if(!rh(i))return{error:kt};if(o){const t=Xm({drawDefinition:r,matchUpId:o,event:s});if(t.error)return t;if(!t.matchUp)return{error:Wt};const e=t.matchUp;if(e?.matchUpType===id)return{error:Yt,info:"Cannot set matchUpFormat when { matchUpType: TEAM }"};e.matchUpFormat=i,xs({tournamentId:n?.tournamentId,eventId:s?.eventId,context:"setMatchUpFormat",drawDefinition:r,matchUp:e})}else if(Array.isArray(e)){if(s?.eventType===id)return{error:wt};for(const t of e){const e=ts({drawDefinition:r,structureId:t});if(e.error)return e;if(!e.structure)return{error:Ut};e.structure.matchUpFormat=i}}else if(a){if(s?.eventType===id)return{error:wt};const t=ts({drawDefinition:r,structureId:a});if(t.error)return t;if(!t.structure)return{error:Ut};t.structure.matchUpFormat=i}else r&&(r.matchUpFormat=i);return e=e??(a?[a]:void 0),Ls({drawDefinition:r,structureIds:e}),{...E}}function qI({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=w(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=LI({roundPosition:f.roundPosition,roundNumber:n,idPrefix:i,uuids:s}),g={roundPosition:f.roundPosition,drawPositions:[d],matchUpStatus:ja,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 $I(t){const e=t.drawSize;let{feedRoundsProfile:n,feedRounds:r=0,skipRounds:i=0,baseDrawSize:a}=t;const{linkFedFinishingRoundNumbers:s,finishingPositionOffset:c,linkFedRoundNumbers:u,feedsFromFinal:d,isConsolation:p,matchUpType:l,idPrefix:m,isMock:f,uuids:h,fmlc:I}=t;a=a??function(t){const e=o(t);return e>t?e/2:e}(e);const U=function({drawSize:t}){const e=Math.ceil(Math.log(t)/Math.log(2));return w(0,e).reverse().map((t=>Math.pow(2,t)))}({drawSize:a}),S=U.length;let y=0;if(n?.length)y=n.reduce(((t,e)=>t+e),0);else if(e){let t=e-a;n=U.filter((e=>e<=t&&(t-=e,!0))),y=n.reduce(((t,e)=>t+e),0),r=n.length}else i>=S?r=0:d&&(r=S-d,i=0),n=U.filter(((t,e)=>d&&!r||r&&e>=i+r||e<i?0:t)),y=n.reduce(((t,e)=>t+e),0),r=n.length;const v=[...U,...n].sort(((t,e)=>e-t)),T=v.length,P=[...(u??[]).map((t=>t-1)),...(s??[]).map((t=>T-t))].map((t=>v[t])).reduce(((t,e)=>t+e),0);y-=P;let D,b=0,N=[],R=1;let M=w(0,a).map(((t,e)=>({drawPosition:e+1+y}))),A=y+1;for(const t of U){if(({roundNodes:D,matchUps:N}=BI({matchUpType:l,roundNumber:R,idPrefix:m,matchUps:N,isMock:f,nodes:M,uuids:h})),R++,n.includes(t)){const e=w(0,g(n)[t]),r=T+1-R,i=s?.includes(r)??u?.includes(R);e.forEach((()=>{const t=!i&&A||void 0;({roundNodes:D,matchUps:N,drawPosition:A}=qI({drawPosition:t,nodes:D,matchUpType:l,roundNumber:R,idPrefix:m,matchUps:N,isMock:f,uuids:h,fed:b})),R++,b+=1}))}M=D}T!==R-1&&console.log("ERROR");N=Xp({finishingPositionOffset:p?a-y:c,positionsFed:y,roundsCount:T,matchUps:N,fmlc:I});const E=D?.length?D[0]:D;return E&&(E.roundNumber=R-1,E.matchUps=N),{draw:E,matchUps:N,roundsCount:T}}function WI(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=Xa,drawSize:g,idPrefix:I,isMock:U,uuids:S}=t;if(!(!o||!u||o?.[c])||g<2||f&&s>f)return{};const y=[],v=[],T=[],P=t.matchUpType??l?.matchUpType,D=e+1,b=`${D}-${e+g}`,N=o?.[c],R=r&&`${r} `||"",M=o?.[b]??i?.[b],A=t.structureName||M?.name||N?.name&&(n?`${R}${N?.name}`:N.name)||`${R}${b}`,C=M?.abbreviation??N?.abbreviation,O=t.structureId??N?.structureId??S?.pop(),F={idPrefix:I&&`${I}-${A}-RP`,finishingPositionOffset:e,matchUpType:P,drawSize:g,isMock:U,uuids:S},{matchUps:k}=m?$I(F):VI(F),x=Tm({structureAbbreviation:C,stageSequence:s,structureName:A,matchUpType:P,roundOffset:p,structureId:O,matchUps:k,stage:h});y.push(...k),v.push(x);const _=Math.ceil(Math.log(g)/Math.log(2)),L=d?Math.min(d-p,_):!a||D<a?_:0;return g>2&&w(1,L+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:w,structureId:D,matchUps:b,links:N}=WI({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:S,stage:h});if(x.structureId&&D){const e={linkType:yo,source:{roundNumber:t,structureId:x.structureId},target:{roundNumber:1,feedProfile:go,structureId:D}};N&&x&&N.push(e),N?.length&&T.push(...N)}w?.length&&v.push(...w);b?.length&&y.push(...b);return{structureId:D,childLinks:N,structures:v}}(t))),{structureId:x.structureId,matchUps:y,structureName:A,structures:v,links:T,...E}}function HI(t){const{finishingPositionOffset:e=0,playoffAttributes:n,stageSequence:r=1,staggeredEntry:i,structureName:a,stage:o=Xa,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?$I(m):VI(m),h=Tm({structureName:a||n?.[0]?.name||wm(Xa),structureId:c||l?.pop(),stageSequence:r,matchUpType:s,matchUps:f,stage:o}),g=[h],I=[];if(d>2){const r=d/2,{matchUps:i}=VI({finishingPositionOffset:e+r,idPrefix:u&&`${u}-c`,drawSize:r,matchUpType:s,isMock:p}),o=wm(to),c=n?.["0-1"]?.name??t.consolationStructureName??(a?`${a} ${o}`:o),m=Tm({structureName:c,matchUps:i,structureId:l?.pop(),stage:to,stageSequence:1,matchUpType:s});g.push(m);const f={linkType:yo,source:{roundNumber:1,structureId:h.structureId},target:{roundNumber:1,feedProfile:go,structureId:m.structureId}};I.push(f)}return{...E,structures:g,links:I}}function zI({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 w(1+e,r+1+e).map((r=>{const i=c&&c[r-1]?c[r-1]:r%2?go:Io,u=r-e<=2?r-e:2*(r-e-2)+2,d={linkType:yo,source:{roundNumber:r,structureId:n.structureId},target:{feedProfile:i,roundNumber:u,structureId:t.structureId}},p=s[r-1];return p&&(d.target.groupedOrder=p),Qn()&&(d.source.structureName=n.structureName,d.target.structureName=t.structureName),2===r&&a&&(d.linkCondition=vo,d.target.feedProfile=go),o.includes(u)?d:void 0})).filter(Boolean)}function YI(t){const{playoffStructureNameBase:e,finishingPositionOffset:n,stageSequence:r=1,playoffAttributes:i,structureNameMap:a,staggeredEntry:o,stage:s=Xa,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?$I(f):VI(f),I=t.structureName??i?.[0]?.name??wm(Xa),U=Tm({structureId:u||m?.pop(),structureName:I,stageSequence:r,matchUpType:c,matchUps:h,stage:s}),S=[U],y=[];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}=$I({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||`${wm(to)} ${d+1}`,I=r?.[g]||g,U=t?`${t} ${I}`:I,S=Tm({matchUps:m,stage:to,structureName:U,stageSequence:e,matchUpType:a,structureId:o});return{consolationStructure:S,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});S.push(o);return{consolationStructure:o,links:zI({consolationStructure:o,roundsCount:2,mainStructure:U,roundOffset:t})}})),n=t.map((t=>t.links)).flat();if(y.push(...n),d>=4&&d<=16||d>32){const{matchUps:t}=VI({idPrefix:p&&`${p}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:l}),n=i?.["3-4"]?.name??wm(no),r=a?.[n]||n,o=e?`${e} ${r}`:r,s=Tm({structureId:m?.pop(),matchUps:t,stageSequence:2,stage:no,structureName:o,matchUpType:c}),u={linkType:yo,source:{roundNumber:g-1,structureId:U.structureId},target:{structureId:s.structureId,feedProfile:go,roundNumber:1}};S.push(s),y.push(u)}}return{structures:S,links:y,...E}}function KI(t){const{finishingPositionOffset:e,stageSequence:n=1,playoffAttributes:r,policyDefinitions:i,feedsFromFinal:a,staggeredEntry:o,structureName:s,stage:c=Xa,structureId:u,matchUpType:d,skipRounds:p,feedRounds:l,idPrefix:m,drawSize:f,isMock:h,uuids:g,fmlc:I}=t,U=t.feedPolicy||i?.[Ei],S={finishingPositionOffset:e,matchUpType:d,skipRounds:p,drawSize:f,idPrefix:m,isMock:h,uuids:g},{matchUps:y}=o?$I(S):VI(S),v=Tm({structureName:s||r?.[0]?.name||wm(Xa),structureId:u||g?.pop(),stageSequence:n,matchUpType:d,matchUps:y,stage:c}),w=[v],T=[],P=f/2,{matchUps:D,roundsCount:b}=$I({finishingPositionOffset:P,idPrefix:m&&`${m}-c`,isConsolation:!0,feedsFromFinal:a,baseDrawSize:P,matchUpType:d,feedRounds:l,skipRounds:p,isMock:h,uuids:g,fmlc:I});if(f>2){const e=r?.["0-1"]?.name??wm(to),n=t.playoffStructureNameBase?`${t.playoffStructureNameBase} ${e}`:e,i=Tm({matchUps:D,structureId:g?.pop(),stage:to,stageSequence:1,structureName:n,matchUpType:d});w.push(i);const a=zI({consolationStructure:i,mainStructure:v,roundsCount:b,feedPolicy:U,fmlc:I});T.push(...a)}return{...E,structures:w,links:T}}function JI({requireSequential:t=!0,playoffMatchUpFormat:n,playoffAttributes:r,sourceStructureId:i,policyDefinitions:a,stageSequence:o,drawDefinition:s,playoffGroups:c,matchUpType:d,feedPolicy:p,groupCount:l,idPrefix:m,isMock:f,uuids:h}){p=p||a?.[Ei];const g="processPlayoffGroups";let I=0;const U=[],S=[],y=[],{error:v,positionRangeMap:w}=function({playoffGroups:t,drawDefinition:e,structureId:n}){if(!e)return{error:j};if("string"!=typeof n||!Array.isArray(t))return{error:Nn};const r=t.map((({finishingPositions:t})=>t)).flat(),i=sg({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:i,drawDefinition:s,playoffGroups:c});if(v)return wr({result:{error:v},stack:g});if(!(!w||c?.every((n=>{const{finishingPositions:r=[]}=n;if(!r.length)return!1;const i=r.sort(e).map(((t,e)=>(r[e+1]||t)-t)).every((t=>t<2));return(!t||i)&&r.every((t=>w[t]))}))))return wr({context:{validFinishingPositions:Object.values(w)},result:{error:Nn},stack:g});for(const t of c){const e=t.finishingPositions,s=w&&e.map((t=>w[t]?.finishingPositions)).flat(),c=l*e.length,g=u(c),v=2===g&&bo||t.drawType||bo;s&&(I=Math.min(...s)-1);const T=s&&`${Math.min(...s)}-${Math.max(...s)}`,P=t.structureName||T&&t.playoffAttributes?.[T]?.name||t.playoffAttributes?.[0]?.name,D={...{addNameBaseToAttributeName:t.addNameBaseToAttributeName,playoffStructureNameBase:t.playoffStructureNameBase,finishingPositionNaming:t.finishingPositionNaming,finishingPositionLimit:t.finishingPositionLimit,structureId:t.structureId??h?.pop(),playoffAttributes:t.playoffAttributes,structureNameMap:t.structureNameMap,sequenceLimit:t.sequenceLimit,structureName:P},idPrefix:m&&`${m}-po`,appliedPolicies:a,finishingPositionOffset:I,stage:no,stageSequence:o,matchUpType:d,drawSize:g,isMock:f,uuids:h},b=({playoffStructures:t,playoffLinks:n})=>{const[r]=t,a=ZI({playoffStructureId:r.structureId,finishingPositions:e,sourceStructureId:i});y.push(a),y.push(...n),S.push(...t),U.push({structureId:r.structureId,finishingPositions:e}),I+=c};if(v===bo){const{matchUps:r}=VI({finishingPositionLimit:I+c,idPrefix:m&&`${m}-po`,finishingPositionOffset:I,matchUpType:d,drawSize:g,isMock:f,uuids:h}),a=Tm({structureId:t.structureId??h?.pop(),matchUpFormat:n,stage:no,structureName:P,stageSequence:o,matchUps:r});S.push(a);const s=ZI({playoffStructureId:a.structureId,finishingPositions:e,sourceStructureId:i});y.push(s),I+=c,U.push({structureId:a.structureId,finishingPositions:e})}else if([Po,Do,no].includes(v)){const n={playoffAttributes:t.playoffAttributes??r,playoffStructureNameBase:t.playoffStructureNameBase,structureId:t.structureId??h?.pop(),structureName:t.structureName,idPrefix:m&&`${m}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:I,stage:no,roundOffset:0,stageSequence:o,drawSize:g,isMock:f,uuids:h};v===Po?Object.assign(n,{playoffAttributes:t?.playoffAttributes??r??Ho,roundOffsetLimit:3}):v===Do&&Object.assign(n,{playoffAttributes:t?.playoffAttributes??r??zo,roundOffsetLimit:2});const a=WI(n);if(a.error)return a;if(a.links?.length&&y.push(...a.links),a.structures?.length&&S.push(...a.structures),S.sort(Xo),a.structureId){const t=ZI({playoffStructureId:a.structureId,finishingPositions:e,sourceStructureId:i});y.push(t),U.push({structureId:a.structureId,finishingPositions:e})}I+=c}else if([Ro,jo,Lo,xo,Fo,Vo].includes(v)){const n=[h?.pop(),h?.pop()],r={playoffStructureNameBase:t.playoffStructureNameBase,structureId:t.structureId??h?.pop(),playoffAttributes:t.playoffAttributes,idPrefix:m&&`${m}-po`,finishingPositionOffset:I,uuids:n,stage:no,structureName:P,matchUpType:d,feedPolicy:p,drawSize:g,isMock:f},a={[Ro]:{fmlc:!0,feedRounds:1},[Vo]:{feedRounds:1},[Lo]:{feedsFromFinal:3},[xo]:{feedsFromFinal:2},[Fo]:{feedsFromFinal:1}};Object.assign(r,a[v]||{});const{structures:o,links:s}=KI(r),[u]=o,l=ZI({playoffStructureId:u.structureId,finishingPositions:e,sourceStructureId:i});y.push(l),y.push(...s),S.push(...o),U.push({structureId:u.structureId,finishingPositions:e}),I+=c}else if([Go].includes(v)){const{structures:e,links:n}=pf({...D,structureOptions:t.structureOptions||{groupSize:4}});b({playoffStructures:e,playoffLinks:n})}else if([Mo].includes(v)){const{structures:t,links:e}=HI(D);b({playoffStructures:t,playoffLinks:e})}else if([Co].includes(v)){const{structures:t,links:e}=YI(D);b({playoffStructures:t,playoffLinks:e})}else if([wo].includes(v)){b({playoffStructures:[Tm({structureId:t.structureId??h?.pop(),structureName:t.structureName,finishingPosition:Cc,stage:no,stageSequence:o,matchUps:[]})],playoffLinks:[]})}}return{finishingPositionTargets:U,positionRangeMap:w,structures:S,links:y}}function ZI({playoffStructureId:t,finishingPositions:e,sourceStructureId:n}){return{linkType:Uo,source:{structureId:n,finishingPositions:e},target:{structureId:t,feedProfile:fo,roundNumber:1}}}function XI(t){const e="genPlayoffStructure";if(!t.drawDefinition)return wr({result:{error:j},stack:e});const r=sg(t);if(r.error)return wr({result:r,stack:e});const{structureId:i,addNameBaseToAttributeName:a,playoffStructureNameBase:o,finishingPositionNaming:s,finishingPositionLimit:c,playoffAttributes:u,playoffPositions:d,roundOffsetLimit:p,tournamentRecord:l,exitProfileLimit:m,roundProfiles:f,roundNumbers:h,idPrefix:g,isMock:I,event:U,uuids:S}=t,y=gi(t.drawDefinition,!1,!0),{structure:v}=ts({structureId:i,drawDefinition:y});if(!v)return wr({result:{error:Ut},stack:e});if(v.structureType===mo||v.structures)return function(t){const e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return wr({result:{error:ae},info:"playoffGroups required",stack:e});const{sourceStructureId:n,requireSequential:r,tournamentRecord:i,drawDefinition:a,playoffGroups:o,groupCount:s,groupSize:c,event:u}=t,{structures:d=[],links:p=[],finishingPositionTargets:l,positionRangeMap:m,error:f}=JI({requireSequential:r,sourceStructureId:n,playoffGroups:o,groupCount:s,groupSize:c,...t});if(f)return{error:f};const h=l?.map((({finishingPositions:t})=>t)).flat().map((t=>m[t].finishingPositions)).flat();a.structures.push(...d),a.links.push(...p);const{matchUps:g,matchUpsMap:I}=Jp({inContext:!0,drawDefinition:a}),U=d.map((({structureId:t})=>t)),S=g?.filter((({structureId:t})=>U.includes(t))).map(ba),y=I?.drawMatchUps?.filter((({matchUpId:t})=>S?.includes(t)));if(y?.length){const e=$d({drawDefinition:a,event:u})?.tieFormat;e&&y.forEach((n=>{const{tieMatchUps:r}=hh({isMock:t.isMock,tieFormat:e});Object.assign(n,{tieMatchUps:r,matchUpType:Xs})}))}const{positionAssignments:v}=rs({structureId:n,drawDefinition:a}),w={};v?.forEach((t=>{const e=Mr({element:t,name:ca}),n=e?.extension?.value,r=n?.groupOrder;r&&(w[r]||(w[r]=[]),w[r].push(t.participantId))}));const T=tg({provisionalPositioning:t.provisionalPositioning,structureId:n,applyPositioning:!0,event:t.event,tournamentRecord:i,drawDefinition:a});return T.error&&T.error?.code!==W.code?wr({result:T,stack:e}):{structures:d,links:p,positionsPlayedOff:h,drawDefinition:a,...E}}({sourceStructureId:v.structureId,...t,...r,drawDefinition:y});const{playoffRoundsRanges:w,playoffRounds:T}=r,{playoffPositionsReturned:P,error:D,playoffSourceRounds:b,playoffRoundsRanges:N}=og(t);if(D)return wr({result:{error:D},stack:e});const R=f?.length&&Object.assign({},...f),M=h||"object"==typeof f&&f.map((t=>Object.keys(t))).flat(),A=Array.isArray(M)&&M.map((t=>!isNaN(t)&&n(t))).filter(Boolean);if(A){if(!Array.isArray(A))return wr({result:{error:Nn},context:{validRoundNumbers:A},stack:e});A.forEach((t=>{if(!T?.includes(t))return wr({result:{error:Nn},context:{roundNumber:t},stack:e})}))}d&&d.forEach((t=>{if(!P?.includes(t))return wr({result:{error:Nn},context:{playoffPosition:t},stack:e})}));const C=A||b,O=A?w:N,F=[],k=[];for(const t of C??[]){const n=O?.find((e=>e.roundNumber===t));if(!n)return wr({result:{error:Nn},context:{roundNumber:t},stack:e});const r=n.finishingPositions.length,d=Math.min(...n.finishingPositions)-1,l=2,f=t&&R?.[t]&&l+R[t]-1,h=WI({exitProfile:`0-${t}`,addNameBaseToAttributeName:a,playoffStructureNameBase:o,finishingPositionOffset:d,playoffAttributes:u,exitProfileLimit:m,stage:no,roundOffset:0,drawDefinition:y,sequenceLimit:f,stageSequence:l,drawSize:r,idPrefix:g,isMock:I,uuids:S,finishingPositionNaming:s,finishingPositionLimit:c,roundOffsetLimit:p});if(h.error)return wr({result:h,stack:e});const{structures:U,links:v}=h;if(U?.length&&F.push(...U),v?.length&&k.push(...v),h.structureId&&t){const e={linkType:yo,source:{structureId:i,roundNumber:t},target:{structureId:h.structureId,feedProfile:go,roundNumber:1}};k.push(e)}}if(!F.length)return wr({result:{error:Nn},info:"No structures generated",stack:e});y.structures.push(...F),y.links.push(...k);const{matchUps:x,matchUpsMap:_}=Jp({inContext:!0,drawDefinition:y}),L=F.map((({structureId:t})=>t)),B=x?.filter((({structureId:t})=>L.includes(t))).map(ba),V=_?.drawMatchUps?.filter((({matchUpId:t})=>B?.includes(t)));if(V?.length){const t=$d({drawDefinition:y,event:U})?.tieFormat;t&&V.forEach((e=>{const{tieMatchUps:n}=hh({tieFormat:t,isMock:I});Object.assign(e,{tieMatchUps:n,matchUpType:Qs})}))}const G=x?.filter((t=>Lc({matchUp:t})&&t.structureId===i));G?.forEach((t=>{const{matchUpId:e,score:n,winningSide:r}=t,i=Uc({inContextDrawMatchUps:x,drawDefinition:y,matchUpId:e}),a=nI({inContextDrawMatchUps:x,tournamentRecord:l,drawDefinition:y,matchUpsMap:_,winningSide:r,targetData:i,matchUpId:e,structure:v,matchUp:t,score:n,event:U});a.error&&console.log(a.error)}));const q=x?.filter((t=>t.matchUpStatus===Ma&&t.structureId===i));q?.forEach((t=>{const{matchUpId:e}=t,n=Uc({inContextDrawMatchUps:x,drawDefinition:y,matchUpId:e}),{targetLinks:{loserTargetLink:r},targetMatchUps:{loserMatchUpDrawPositionIndex:i,loserMatchUp:a}}=n;if(r&&a){const t=r.target.structureId,e=bl({drawPosition:a.drawPositions[i],structureId:t,tournamentRecord:l,drawDefinition:y,event:U});e.error&&console.log(e.error)}}));const $=[],H=Qp({inContextDrawMatchUps:x,drawDefinition:y,matchUpsMap:_}).goesToMap,{structure:z}=ts({drawDefinition:t.drawDefinition,structureId:i}),{matchUps:Y}=Yp({structure:z});return Y.forEach((n=>{const r=H?.loserMatchUpIds[n.matchUpId];if(r&&n.loserMatchUpId!==r){n.loserMatchUpId=r;const i={tournamentId:l?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:n};$.push(i)}const i=H?.winnerMatchUpIds[n.matchUpId];if(i&&n.winnerMatchUpId!==i){n.winnerMatchUpId=i;const r={tournamentId:l?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:n};$.push(r)}})),{structures:F,matchUpModifications:$,links:k,drawDefinition:y,...E}}function QI(t){return tU({...t,itemType:"attachPlayoffStructures"})}function tU({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:n,drawDefinition:r,structures:i,links:a=[],event:o}){const s="attachStructures";if(!r)return{error:j};if(!Array.isArray(i)||!Array.isArray(a))return wr({result:{error:Nn},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 wr({result:{error:Vn},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),Qp({drawDefinition:r});const m=i.map((t=>Yp({structure:t})?.matchUps||[])).flat();Fs({tournamentId:n?.tournamentId,eventId:o?.eventId,drawDefinition:r,matchUps:m});const f=i.map((({structureId:t})=>t));if(Ls({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,xs(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(Ua("structureId"));if(n){xm({element:n,timeItem:{itemValue:{structureIds:f,drawId:r.drawId},itemType:t}})}return{...E,addedStructureIds:h}}function eU(t){const{structures:e,links:n,matchUpModifications:r,error:i}=XI(t);if(i)return{error:i};const a=t.drawDefinition;return QI({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:r,drawDefinition:a,structures:e,links:n})}function nU(t){const{winnerFirst:e=!0,addOutcomeString:n,reversed:r=!1,matchUpStatus:i,matchUpFormat:a,autoComplete:o,winningSide:c,sets:u}=t;if(!u)return{error:ae,info:"missing sets"};const d=a&&Jd(a),{bestOf:p,finalSetFormat:l,setFormat:m}=d??{},f=r||!(!e||!c||1===c),h=n?function({matchUpStatus:t}){const e={[Ba]:"RET",[Ga]:"WO",[Fa]:"DF/DF",[ka]:"WO/WO",[Va]:"SUS",[Na]:"ABN",[Oa]:"DEF",[Ca]:"DR"};return t&&e[t]||""}({matchUpStatus:i}):"",g=u?.sort(rU).map((function(t){const e=p&&t.setNumber===p&&l?l:m,n=e?.tiebreakSet||(h=t,!(s(h?.side1Score)||s(h?.side2Score))&&(t=>s(t?.side1TiebreakScore)||s(t?.side2TiebreakScore))(t)),{side1Score:r,side2Score:i,side1TiebreakScore:a,side2TiebreakScore:c}=t,u=a||(s(a)||o?0:""),d=c||(s(c)||o?0:"");var h;if(n){return`[${(f?[d,u]:[u,d]).join("-")}]`}const g=Math.min(u,d),I=g?`(${g})`:"",U=r||(s(r)||o?0:""),S=i||(s(i)||o?0:"");let y=f?`${[S,U].join("-")}${I}`:`${[U,S].join("-")}${I}`;["-"," "].includes(y)&&(y="");return y})).filter(Boolean).join(" ")||"";return h?2===c?`${h} ${g}`:`${g} ${h}`:g}function rU(t,e){return t.setNumber-e.setNumber}function iU(t){const{matchUpFormat:e,matchUpStatus:n,winningSide:r,score:i}=t;if(!i)return{sets:[]};const a=i.sets||[];let o=nU({winnerFirst:!1,matchUpFormat:e,matchUpStatus:n,sets:a}),s=nU({winnerFirst:!1,reversed:!0,matchUpFormat:e,matchUpStatus:n,sets:a});const c=nU({matchUpFormat:e,matchUpStatus:n,winningSide:r,sets:a}),u=o===c?s:o;return r&&(o=1===r?c:u,s=2===r?c:u),{score:{sets:a,scoreStringSide1:o,scoreStringSide2:s}}}function aU(t){const e=nc(t);if(!t.drawDefinition){const n=t.tournamentRecord??(t.tournamentId&&e[t.tournamentId]);t.tournamentRecord||(t.tournamentRecord=n);const r=Vd({eventId:t.eventId,drawId:t.drawId,tournamentRecord:n});if(r.error)return r;r.drawDefinition&&(t.drawDefinition=r.drawDefinition),t.event=r.event}const{policyDefinitions:n,tournamentRecord:r,disableAutoCalc:i,enableAutoCalc:a,drawDefinition:o,matchUpFormat:s,matchUpId:c,schedule:u,event:d,notes:p}=t;if(!o)return{error:at};if(!c)return{error:qt};const{policy:l}=Uu({policyType:Mi,tournamentRecord:r,event:d}),m=void 0!==t.allowChangePropagation&&t.allowChangePropagation||void 0!==l?.allowChangePropagation&&l.allowChangePropagation||void 0,{outcome:f}=t;if(s){const t=GI({tournamentRecord:r,drawDefinition:o,matchUpFormat:s,matchUpId:c,event:d});if(t.error)return t}if(f?.score?.sets&&!f.score.scoreStringSide1){const{score:t}=iU(f);f.score=t,f.score.sets=f.score.sets.filter((t=>t.side1Score||t.side2Score||t.side1TiebreakScore||t.side2TiebreakScore))}return PI({matchUpStatusCodes:f?.matchUpStatusCodes,matchUpStatus:f?.matchUpStatus,winningSide:f?.winningSide,allowChangePropagation:m,score:f?.score,tournamentRecords:e,policyDefinitions:n,tournamentRecord:r,disableAutoCalc:i,enableAutoCalc:a,drawDefinition:o,matchUpFormat:s,matchUpId:c,schedule:u,event:d,notes:p})}function oU({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=Dc({tournamentRecord:r,drawDefinition:s,event:h}).appliedPolicies??{},U=i?.[wi]??I?.[wi];a=a??U?.participants?.enforceCategory;const S=!1!==(u??U?.participants?.enforceGender),y=!(!(n??h?.category)||!1===a),v=!(!(o??h?.gender)||!S),w=mh({referenceCategory:n??h?.category,collectionDefinition:e,referenceGender:o,checkCategory:y,checkGender:v,event:h});if(w.error)return wr({result:w,stack:g});let T=l?.tieFormat?void 0:Zf({drawDefinition:s,structureId:d,matchUpId:p,eventId:m,event:h});if(T?.error)return wr({result:{error:T.error},stack:g});const P=T?.structure;l=l??T?.matchUp;const D=l?.tieFormat??T?.tieFormat,b=Yf(D);if(T=fh({tieFormat:b}),T?.error)return wr({result:{error:T.error},stack:g});if(e.collectionId){if(b.collectionDefinitions.map((({collectionId:t})=>t)).includes(e.collectionId))return wr({context:{collectionId:e.collectionId},result:{error:Rn}})}else e.collectionId=Md();b.collectionDefinitions.push(e),b.collectionDefinitions.sort(((t,e)=>(t.collectionOrder||0)-(e.collectionOrder||0))).forEach(((t,e)=>t.collectionOrder=e+1));const{aggregateValue:N,valueGoal:R}=Jf(b);b.winCriteria=vr({aggregateValue:N,valueGoal:R});const M=D?.winCriteria.valueGoal,A=D?.winCriteria.aggregateValue;(M&&M!==R||N&&!A)&&(c?b.tieFormatName=c:delete b.tieFormatName);const C=[],O=[];let F=[];const k=vr(b);if(T=fh({tieFormat:k}),T?.error)return wr({result:{error:T.error},stack:g});if(m&&h){h.tieFormat=k;for(const n of h.drawDefinitions??[])if(!n.tieFormat)for(const r of n.structures??[]){if(r.tieFormat)continue;const n=sU({updateInProgressMatchUps:t,collectionDefinition:e,structure:r,uuids:f});O.push(...n.newMatchUps),F.push(...n.targetMatchUps),C.push(r.structureId)}cU({modifiedMatchUps:F,eventId:h?.eventId,modifiedStructureIds:C,tournamentRecord:r,drawDefinition:s,addedMatchUps:O,stack:g})}else if(d&&P){P.tieFormat=k;const n=sU({updateInProgressMatchUps:t,collectionDefinition:e,structure:P,uuids:f});O.push(...n.newMatchUps),F=n.targetMatchUps,cU({modifiedMatchUps:F,eventId:h?.eventId,modifiedStructureIds:C,tournamentRecord:r,drawDefinition:s,addedMatchUps:O,stack:g})}else if(p&&l){if(!yh({matchUp:l,updateInProgressMatchUps:t}))return wr({result:{error:Ue},stack:g});l.tieFormat=k;const n=gh({collectionDefinition:e,uuids:f});Array.isArray(l.tieMatchUps)||(l.tieMatchUps=[]),l.tieMatchUps.push(...n),O.push(...n),cU({modifiedMatchUps:[l],eventId:h?.eventId,modifiedStructureIds:C,tournamentRecord:r,drawDefinition:s,addedMatchUps:O,stack:g})}else{if(!s)return{error:j};s.tieFormat=k;for(const n of s.structures??[]){const r=sU({updateInProgressMatchUps:t,collectionDefinition:e,structure:n,uuids:f});C.push(n.structureId),O.push(...r.newMatchUps),F.push(...r.targetMatchUps)}cU({modifiedMatchUps:F,eventId:h?.eventId,tournamentRecord:r,drawDefinition:s,addedMatchUps:O,stack:g})}if(I?.audit?.[ua]){Th({drawDefinition:s,auditData:vr({drawId:s?.drawId,collectionDefinition:e,action:g,structureId:d,matchUpId:p,eventId:m})})}return{tieFormat:k,targetMatchUps:F,addedMatchUps:O,...E}}function sU({updateInProgressMatchUps:t,collectionDefinition:e,structure:n,uuids:r}){const i=[],a=Yp({matchUpFilters:{matchUpTypes:[Qs]},structure:n})?.matchUps,o=a.filter((e=>yh({matchUp:e,updateInProgressMatchUps:t})&&!e.tieFormat));for(const t of o){const n=gh({collectionDefinition:e,uuids:r});Array.isArray(t.tieMatchUps)||(t.tieMatchUps=[]),t.tieMatchUps.push(...n),i.push(...n)}return{newMatchUps:i,targetMatchUps:o}}function cU({modifiedStructureIds:t,tournamentRecord:e,modifiedMatchUps:n,drawDefinition:r,addedMatchUps:i,eventId:a,stack:o}){Fs({tournamentId:e?.tournamentId,matchUps:i,drawDefinition:r,eventId:a}),n?.forEach((t=>{xs({tournamentId:e?.tournamentId,drawDefinition:r,context:o,matchUp:t,eventId:a})})),Ls({structureIds:t,drawDefinition:r,eventId:a})}function uU(t){const e=Lp(t,[{_anyOf:{[sp]:!0,[up]:!0,[dp]:!0,[Rp]:!0},[cp]:!0}]);if(e.error)return e;const n=[],r=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(r){const e=dU(t,r);if(e.error)return e;n.push(...e?.applied??[]),t.drawDefinition&&Ls({drawDefinition:t.drawDefinition,tournamentId:t.tournamentId})}else{if(!t.tournamentRecords)return{error:_};{const e=Object.keys(t.tournamentRecords);if(!e.length)return{error:_};for(const r of e){const e=dU(t,t.tournamentRecords[r]);if(e.error)return e;n.push(...e?.applied??[])}}}return n.length?{...E,applied:n}:{error:te}}function dU(t,e){const n=Dc(t).appliedPolicies??{};e.extensions||(e.extensions=[]);const r=[],i=Object.keys(t.policyDefinitions);if(!i.length)return{error:Jt};for(const e of i)if(!n[e]||t.allowReplacement){const i=t.policyDefinitions[e];if(!i)continue;if(!ha(i))return{error:Nn};const{policyName:a,...o}=i;if(!o||!Object.keys(o).length||a&&!fa(a))return{error:Nn};n[e]=t.policyDefinitions[e],r.push(e)}if(r?.length){return{...Nr({element:e,extension:{name:Vi,value:n}}),applied:r}}return{applied:r,error:te}}function pU({tournamentRecord:t,drawDefinition:e,flightProfile:n,drawName:r,drawId:i,event:a}){if(!r||"string"!=typeof r)return wr({result:{error:Nn},context:{drawName:r}});n||(n=Bd({event:a}).flightProfile);const o=n?.flights?.find((t=>t.drawId===i));if(o){o.drawName=r;_i({event:a,extension:{name:Ki,value:{...n,flights:n.flights}}})}return e&&(e.drawName=r,Ls({tournamentId:t?.tournamentId,drawDefinition:e})),o||e?{...E,flight:o}:{error:j}}function lU(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}=Vd({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=aU({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{...E}}function mU({tournamentRecord:t}){if(!t)return{error:_};const e={positionsNoOutcomes:[],canBePruned:[],matchPlay:[],inactive:[],drawAnalysis:{}},r={},i=t.events?.map((t=>{const e=t.eventId;return r[e]=t,(t?.drawDefinitions||[]).map((t=>({drawDefinition:t,eventId:e})))})).flat().filter(Boolean);return i.forEach((({drawDefinition:t,eventId:i})=>{let a=0,o=0,s=0;const{allStructuresLinked:c}=Gm({drawDefinition:t}),u=r[i],d=(t?.structures||[]).map((e=>{const{stage:n,stageSequence:r,structureId:i}=e,c=io[n],{inContextStructureMatchUps:d}=yl({drawDefinition:t,structure:e,event:u}),p=d?.filter((({winningSide:t})=>t)),l=p.filter(Boolean).length||0;o+=l,s+=d.length-o;const m=Math.max(p.filter((({roundNumber:t})=>1===t)).map((({roundPosition:t})=>t))),{positionAssignments:f}=rs({structure:e}),h=f?.filter((({participantId:t})=>t));a+=h?.length??0;const g=(f?.length??0)-(h?.length??0),{roundMatchUps:I,roundProfile:U,roundNumbers:S,maxMatchUpsCount:y}=vc({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))),T=U&&Object.values(U).every((t=>t.inactiveRound));return{positionsAssignedCount:h?.length??0,maxWinningSideFirstRoundPosition:m,unassignedPositionsCount:g,inactiveStructure:T,maxMatchUpsCount:y,inactiveRounds:w,roundMatchUps:I,activeRounds:v,roundNumbers:S,roundProfile:U,structureId:i,stageSequence:r,orderNumber:c,stage:n}})),p=d.find((t=>2===t.orderNumber&&1===t.stageSequence)),l=d.filter((({inactiveStructure:t})=>!t)).length,{links:m}=Ic({structureId:p.structureId,drawDefinition:t}),f=1===n(p.activeRounds[0])&&1===p.activeRounds.length&&1===l,h=d?.every((({inactiveStructure:t})=>t)),g=!m.length&&p.activeRounds.length&&(p.roundProfile[1].inactiveCount||p.inactiveRounds.length),I=t.drawId;a&&!o&&e.positionsNoOutcomes.push(I),h&&e.inactive.push(I),f&&e.matchPlay.push(I),g&&e.canBePruned.push(I);const U={matchUpsWithWinningSideCount:o,matchUpsNoOutcomeCount:s,positionsAssignedCount:a,allStructuresLinked:c,structuresData:d,inactiveDraw:h,isMatchPlay:f,drawId:I};e.drawAnalysis[I]=U})),{...E,drawsAnalysis:e}}function fU({tournamentRecord:t,drawDefinition:e,structureId:n,matchUps:r}){if("object"!=typeof e)return{error:j};if(n||1!==e.structures?.length||(n=e.structures?.[0]?.structureId),"string"!=typeof n)return{error:It};if(!yc(r))return{error:Nn,info:Pf("matchUps")};const i=e.structures?.find((t=>t.structureId===n));if(!i)return{error:Ut};const a=i?.matchUps,o=a.find((t=>!!t.roundPosition));if(i.structures||o||i.finishingPosition===Ko)return{error:$};return b(hl({tournamentRecord:t,inContext:!1})?.matchUps?.map(ba)??[],r.map(ba))?{error:Ln,info:"One or more matchUpIds already present in tournamentRecord"}:(i.matchUps.push(...r),Fs({tournamentId:t?.tournamentId,drawDefinition:e,matchUps:r}),Ls({drawDefinition:e,structureIds:[n]}),{...E})}function hU(t){const{flight:e,suppressNotifications:r,modifyEventEntries:i,existingDrawCount:a,allowReplacement:o,checkEntryStatus:s,tournamentRecord:c,drawDefinition:u,event:d}=t;if(!u)return{error:j};if(!d)return{error:Tt};d.drawDefinitions||(d.drawDefinitions=[]);const{drawId:p,drawName:l,entries:m}=u,{entries:f}=d;let h=0;if(void 0!==a&&a!==d.drawDefinitions.length)return{error:Nn,info:"drawDefintions count mismatch"};const{flightProfile:g}=Bd({event:d}),I=e&&g?.flights?.find((t=>t.flightNumber===e.flightNumber)),U=g?.links?.find((t=>t?.target?.drawId===p))?.source?.drawId;if(U&&!d.drawDefinitions.find((t=>t.drawId===U)))return wr({result:{error:j},info:{sourceDrawId:U}});if(I&&I.drawId!==u.drawId)return wr({result:{error:V},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})),y=!s||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 wr({result:{error:V},context:{drawEntriesPresentInFlight:S,matchingEventEntries:y,relevantFlight:I},info:"Draw entries are not present in flight or do not match entryStatuses"});if(i&&m?.filter(Boolean).forEach((t=>{if(t?.entryStatus&&ou.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&&!y)return wr({result:{info:"Draw entries do not match event entryStatuses",context:{matchingEventEntries:y,eventEntries:f},error:V}});const v=g?.flights?.map((({flightNumber:t})=>!isNaN(t)&&n(t)))?.filter(Boolean)||[],w=d.drawDefinitions.map((({drawOrder:t})=>t&&n(t)))?.filter(Boolean)||[];let T=Math.max(0,...w,...v)+1;const P=g?.flights?.find((t=>t.drawId===p));let D;if(P){P.drawName=u.drawName,D={name:Ki,value:{...g,flights:g.flights}};const t=P.flightNumber;t&&!w.includes(t)?T=t:P.flightNumber=T}else{const t=g?.flights||[];t.push({manuallyAdded:!0,flightNumber:T,drawEntries:m,drawName:l,drawId:p}),D={name:Ki,value:{...g||{},flights:t}}}_i({event:d,extension:D}),Object.assign(u,{drawOrder:T});const b=d.drawDefinitions.find((t=>t.drawId===p)),N=c?.tournamentId,R=d.eventId;if(b){if(!o)return{error:ot};const t=Ul({drawDefinition:b})?.matchUps,e=t?.map(ba)??[],n=Ul({drawDefinition:u})?.matchUps;if(!r){e?.length&&ks({matchUpIds:e,action:"modifyDrawDefinition",tournamentId:N,eventId:R}),n?.length&&Fs({matchUps:n,tournamentId:N,eventId:R}),d.drawDefinitions=d.drawDefinitions.map((t=>t.drawId===p?u:t));const t=u.structures?.map((({structureId:t})=>t));Ls({drawDefinition:u,tournamentId:N,structureIds:t,eventId:R})}}else if(d.drawDefinitions.push(u),!r){const{matchUps:t}=Ul({drawDefinition:u,event:d});t&&Fs({tournamentId:c?.tournamentId,matchUps:t}),_s({drawDefinition:u,tournamentId:N,eventId:R})}return{...E,modifiedEventEntryStatusCount:h}}function gU({allowDuplicateParticipantIdPairs:t,returnParticipants:e,participants:n,tournamentRecord:r}){if(!r)return{error:_};r.participants||(r.participants=[]);const i=r.participants.map((t=>t.participantId))||[];n.forEach((t=>{t.participantId||(t.participantId=Md())}));const a=n.filter((t=>!i.includes(t.participantId))),o=n.filter((t=>i.includes(t.participantId))),s=a.filter((t=>t.participantType===sc)),c=a.filter((t=>t.participantType!==sc)),u=s.concat(...c),d=[];if(u.length){for(const e of u){const n=Bf({allowDuplicateParticipantIdPairs:t,returnParticipant:!0,disableNotice:!0,tournamentRecord:r,participant:e});if(n.error)return n;n.success&&!n.existingParticipant&&d.push(n.participant)}d.length&&sr({topic:ss,payload:{tournamentId:r.tournamentId,participants:d}});const n={participants:e&&gi(d),addedCount:d.length,...E};return o.length&&Object.assign(n,{notAdded:o,info:Be}),vr(n)}return{info:"No new participants to add",addedCount:0,...E}}function IU({deleteExisting:t,event:e,flightProfile:n}){const r="attachFlightProfile";if(!n)return wr({result:{error:ae},stack:r});if(!e)return wr({result:{error:Tt},stack:r});const{flightProfile:i}=Bd({event:e});if(i&&!t)return wr({result:{error:xn},stack:r});if(e.drawDefinitions?.length)return wr({result:{error:G},stack:r});return _i({event:e,extension:{name:Ki,value:n}}),{flightProfile:gi(n,!1,!0),...E}}function UU({tournamentRecord:t,scaleAttributes:e,drawDefinition:n,entryStatuses:r,drawId:i,event:a,stage:o}){if(!a)return{error:Tt};if(r&&!Array.isArray(r))return wr({result:{error:Nn},info:Pf("entryStatus"),stack:"removeScaleValues"});let s=a.entries;if(i){const{flightProfile:t}=Bd({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:_};if(!n)return{error:Fe};if(!e)return{error:ae,info:"scaleAttributes required"};const{scaleType:r,eventType:i,scaleName:a}=e,o=[ju,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)))})),{...E}}({tournamentRecord:t,scaleAttributes:e,participantIds:(s||[]).filter((t=>(!o||!t.entryStage||t.entryStage===o)&&(!r||r.includes(t.entryStatus)))).map(Da)})}function SU(t){const e="resetTieFormat",{drawDefinition:n,event:r,uuids:i}=t,a=Lp(t,[{[up]:!0,[Ip]:!0}],e);if(a.error)return a;const o=Cf(t,[{[Mp]:Dp}]);if(o[Np])return o;const s=t.tournamentRecord?.tournamentId,{matchUp:c,structure:u}=o?.matchUp??{};if(!c?.tieMatchUps)return wr({result:{error:Yt},info:"Must be a TEAM matchUp",stack:e});if(!c.tieFormat)return{...E};const d=$d({structure:u,drawDefinition:n,event:r})?.tieFormat;if(!d)return wr({result:{error:On},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===ja?1:0)-(e.matchUpStatus===ja?1:0))),m.push(...r.slice(0,e)),p.push(...r.slice(3).map(ba));else if(m.push(...r),r.length<e){const n=gh({collectionDefinition:t,matchUpsLimit:e-r.length,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),Fs({eventId:r?.eventId,matchUps:f,drawDefinition:n,tournamentId:s})),p.length&&ks({matchUpIds:p,eventId:r?.eventId,drawDefinition:n,tournamentId:s}),c&&(c.tieMatchUps=m,c.tieFormatId=void 0,c.tieFormat=void 0,xs({structureId:u?.structureId,eventId:r?.eventId,context:e,drawDefinition:n,tournamentId:s,matchUp:c})),{...E,newMatchUps:f,deletedMatchUpIds:p}}function yU({participantIdPairings:t,matchUpIds:e=[],drawDefinition:n,matchUpsCount:r,roundNumber:i,structureId:a,newRound:o}){if("object"!=typeof n)return{error:j};if(a||1!==n.structures?.length||(a=n.structures?.[0]?.structureId),"string"!=typeof a)return{error:It};const s=n.structures?.find((t=>t.structureId===a));if(!s)return{error:Ut};let c;const u=s.matchUps??[],d=u?.reduce(((t,e)=>(e.roundPosition&&(c=!0),(e?.roundNumber||0)>t?e.roundNumber:t)),0);if(!r){const t=n?.entries?.filter((t=>{const e=t.entryStatus;return ou.includes(e)}))??[],e=Math.floor(t?.length/2)||1;if(o)r=e;else{const t=i??d??1,n=e-(s.matchUps?.filter((e=>e.roundNumber===t))?.length??0);n>0&&(r=n)}}if(t&&!Array.isArray(t)||r&&!p(r)||e&&!Array.isArray(e)||!t&&!r)return{error:Nn,info:"matchUpsCount or pairings error"};if(s.structures||c||s.finishingPosition===Ko)return{error:$};if(i&&i-1>(d||0))return{error:Nn,info:"roundNumber error"};const l=i??(o&&(d??0)+1||d||1);t=t??w(0,r).map((()=>({participantIds:[void 0,void 0]})));const m=t?.map((t=>{const n=t?.participantIds??[void 0,void 0];n.push(void 0,void 0);const r=n.slice(0,2).map(((t,e)=>vr({sideNumber:e+1,participantId:t})));return{matchUpId:e.pop()??Md(),roundNumber:l,matchUpStatus:ja,sides:r}}));return{matchUpsCount:m?.length??0,matchUps:m,...E}}function vU(t){return t.participantIdPairings.map((({participantIds:t})=>t.sort().join("|"))).sort().join("/")}function wU({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=TU(e,r),a=n[i];s.push({participantIds:t,value:a}),c+=n[i]}));N(t,a).map((t=>f(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=TU(n,i),o=r[a];return o>t?o:t}),0),d=s.reduce(((t,e)=>{const[n,r]=e.participantIds,a=TU(n,r),o=i[a];return o>t?o:t}),0);return{value:c,participantIdPairings:s,maxDelta:u,maxDiff:d}}function TU(t,e){return[t,e].sort(Hl).join("|")}function PU({participantIds:t}){const e={},n=[];t.forEach((r=>{e[r]=t.filter((t=>t!==r)),e[r].forEach((t=>{const e=TU(t,r);n.includes(e)||n.push(e)}))}));const r=Object.assign({},...n.map((t=>({[t]:0}))));return{uniquePairings:n,possiblePairings:e,deltaObjects:r}}const DU="ELO",bU="NTRP",NU="WTN",RU={ELO:DU,NTRP:bU,TRN:"TRN",UTR:"UTR",WTN:NU},MU={[DU]:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!0},[bU]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!0,range:[1,7]},UTR:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!0,range:[1,16]},[NU]:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!1,decimalsCount:2,range:[40,1]}},AU=0;function EU({tournamentParticipants:t,adHocRatings:e={},possiblePairings:n,uniquePairings:r,maxIterations:i,deltaObjects:a,valueObjects:o,eventType:s,scaleName:c,salted:u}){r.forEach((n=>{const r=function({tournamentParticipants:t,adHocRatings:e,eventType:n,scaleName:r,pairing:i}){const a=MU[r]?.defaultInitialization??AU;return i.split("|").map((r=>{if(n===nd){const n=t?.find((t=>t.participantId===r))?.individualParticipantIds;return n?n?.map((t=>e[t]||a)):2*a}return e[r]||a}))}({tournamentParticipants:t,adHocRatings:e,scaleName:c,eventType:s,pairing:n}),i="number"==typeof u&&u||.5,d=u&&(Math.round(Math.random())?i:-1*i)||0,p=Math.abs(r[0]-r[1])+d,l=Math.abs(r[0]-r[1]);a[n]=l,o[n]||(o[n]=0),o[n]+=p?Math.pow(p,2):0}));const d=r.map((t=>({pairing:t,value:o[t]}))).sort(((t,e)=>t.value-e.value)),{pairingValues:p}=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=TU(t,n);return{opponent:n,value:e[r]}}return{pairingValues:n}}({possiblePairings:n,valueObjects:o}),{candidate:l,candidatesCount:m,deltaCandidate:f,iterations:h}=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=wU({actorsCount:o.length,valueSortedPairings:e,pairingValueMap:a,deltaObjects:i,valueObjects:r}),u=[vU(c)];s.push(c);let d,p=c.value,l=c,m=0,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=TU(t,n.opponent);if(!g.includes(c)){const d=wU({stipulated:[[t,n.opponent]],actorsCount:o.length,valueSortedPairings:e,pairingValueMap:a,deltaObjects:i,valueObjects:r});if(!u.includes(vU(d))){u.push(vU(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=y(s);return{candidatesCount:m,deltaCandidate:l,maxIterations:t,iterations:f,candidate:I}}({valueSortedPairings:d,maxIterations:i,pairingValues:p,deltaObjects:a,valueObjects:o}),{participantIdPairings:g}=l;return{participantIdPairings:g,candidatesCount:m,deltaCandidate:f,iterations:h,candidate:l}}const CU=100,OU=100,FU=4e3;function kU({encounterValue:t=CU,sameTeamValue:e=OU,maxIterations:n=FU,generateMatchUps:r=!0,tournamentParticipants:i,participantIds:a,drawDefinition:o,adHocRatings:s,structureId:c,salted:u=.5,matchUpIds:d,eventType:p,structure:l,scaleName:m}){if(!o)return{error:j};if(!l&&!c)return{error:Ut};if(l||(l=ts({drawDefinition:o,structureId:c}).structure),!ha(l))return{error:yt};if(!a?.length)return{error:Fe};const{encounters:f}=function({matchUps:t}){const e=[];for(const n of t){const t=n.sides.map(Ua("participantId"));if(2===t.length){const[n,r]=t,i=TU(n,r);e.includes(i)||e.push(i)}}return{encounters:e}}({matchUps:l?.matchUps??[]}),h={};for(const e of f)h[e]||(h[e]=0),h[e]+=t;const g=i?.filter((({participantType:t})=>t===dc));if(g)for(const t of g){const n=t.individualParticipantIds??[],{uniquePairings:r}=PU({participantIds:n});for(const t of r)h[t]||(h[t]=0),h[t]+=e}const{uniquePairings:I,possiblePairings:U,deltaObjects:S}=PU({participantIds:a}),y={tournamentParticipants:i,possiblePairings:U,drawDefinition:o,participantIds:a,uniquePairings:I,maxIterations:n,adHocRatings:s,deltaObjects:S,valueObjects:h,eventType:p,scaleName:m,structure:l,salted:u},{candidatesCount:v,participantIdPairings:w,iterations:T,candidate:P}=EU(y);if(!v)return{error:vn};let D;if(r){const t=yU({structureId:l?.structureId,participantIdPairings:w,newRound:!0,drawDefinition:o,matchUpIds:d});if(t.error)return t;D=t.matchUps}const{maxDelta:b,maxDiff:N}=P;return{...E,participantIdPairings:w,candidatesCount:v,iterations:T,matchUps:D,maxDelta:b,maxDiff:N}}function xU({tournamentParticipants:t,restrictEntryStatus:e,adHocRatings:n={},generateMatchUps:r,tournamentRecord:i,participantIds:a,encounterValue:o,sameTeamValue:s,drawDefinition:c,scaleAccessor:u,maxIterations:d,structureId:p,matchUpIds:l,scaleName:m,eventType:f,salted:h,event:g}){if("object"!=typeof c||c.drawType&&c.drawType!==wo)return{error:V};if(!Array.isArray(c?.entries)&&a&&!Array.isArray(a))return{error:Nn,info:"Missing Entries"};f=f??g?.eventType;const I=c?.entries?.filter((t=>{const n=t.entryStatus;return!e||ou.includes(n)})).map(Da);if(a){const t=a.filter((t=>!I?.includes(t)));if(t?.length)return wr({result:{error:Te},info:{invalidParticipantIds:t}})}else a=I;if(!p){const t=c?.structures?.filter((t=>1===t.stageSequence))?.reduce(((t,e)=>{const n=e.stage&&io[e.stage];return ap({drawDefinition:c,structure:e})&&n>(io[t?.stage]||1)?e:t}),void 0);p=t?.structureId}const U=c?.structures?.find((t=>t.structureId===p));if(!U)return{error:Ut};if(!ap({drawDefinition:c,structure:U}))return{error:V};t=t??i.participants??[];for(const e of a??[]){const r=t?.find((t=>t.participantId===e));let i=_U({scaleName:`${m}.${Ar}`,scaleAccessor:u,participant:r,eventType:f});!i&&m&&(i=_U({scaleAccessor:u,participant:r,scaleName:m,eventType:f})),i&&!n[e]&&(n[e]=i)}return kU({tournamentParticipants:t,generateMatchUps:r,participantIds:a,encounterValue:o,sameTeamValue:s,drawDefinition:c,maxIterations:d,adHocRatings:n,matchUpIds:l,structure:U,eventType:f,salted:h})}function _U({scaleType:t=Cr,scaleAccessor:e,participant:n,scaleName:r,eventType:i}){const a=n&&Vl({scaleAttributes:{eventType:i??ed,scaleType:t,scaleName:r},participant:n}),o=a?.scaleItem?.scaleValue;return e&&ha(o)?o[e]:o}function LU({participantsCount:t,participantCount:e}){if(!(t=t??e))return{error:Nn};const n=u(t);return n?{drawSize:n}:wr({result:{error:Nn},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function BU(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=bc({tournamentRecord:a,drawDefinition:o,event:s});if(t.error)return wr({result:t,stack:c});n=t.policyDefinitions}const d=p(u);if(u&&!d)return wr({result:{error:Nn},context:{participantsCount:u},stack:c});if(i&&!d)return wr({result:{error:ke},stack:c});if(isNaN(r)){if(!u)return wr({result:{error:it},stack:c});({drawSize:r}=LU({participantsCount:u}))}const l=i&&u||r;if(l&&l>r)return{error:Ve};const m=n?.[Ai];if(!m)return{error:Qt};const f=m.seedsCountThresholds;if(!f)return{error:ut};void 0!==m.drawSizeProgression&&(e=m.drawSizeProgression);return{seedsCount:f.filter((t=>e?t.drawSize<=r:r===t.drawSize)).reduce(((t,e)=>u&&u>=e.minimumParticipantCount?e.seedsCount:t),0)}}function VU({policyDefinitions:t,drawDefinition:e,drawSize:n,drawId:r,event:i,stage:a}){if(!i)return{error:Tt};const{entries:o,stageEntries:s}=Im({drawDefinition:e,drawId:r,stage:a,event:i}),c=s.length,{drawSize:u}=LU({participantsCount:c}),d=BU({drawSize:n??u,participantsCount:c,policyDefinitions:t});if(d.error)return wr({result:d,stack:"getEntriesAndSeedsCount"});const{seedsCount:p}=d;return{entries:o,seedsCount:p,stageEntries:s}}function jU({scaleAttributes:t,scaledEntries:e,stageEntries:n,seedsCount:r,scaleName:i}){if(!t)return{error:ae,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:Fr,scaleName:i,scaleDate:o}],participantId:e})))}}function GU(t){const{tournamentRecord:e,scaleAttributes:n,participantId:r}=t,i=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!r)return{error:Ae};const{participant:a,tournamentId:o}=rl({tournamentRecords:i,tournamentRecord:e,participantId:r});return a?{...Vl({participant:a,scaleAttributes:n}),tournamentId:o}:{error:Ee}}function qU({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:n,scaleSortMethod:r,stageSequence:i,entries:a,event:o,stage:s}){if(!e)return{error:_};return{scaledEntries:(a=a??o?.entries??[]).filter((t=>(!s||!t.entryStage||t.entryStage===s)&&(!i||!t.entryStageSequence||t.entryStageSequence===i)&&ou.includes(t.entryStatus))).map((t=>{const{participantId:r}=t,{scaleItem:i}=GU({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 $U({qualifyingPositions:t,drawEntries:e=[],drawName:r,drawId:i,event:a,stage:o}){const s="addFlight";if(!a)return wr({result:{error:Tt},stack:s});if(!r)return wr({result:{error:ae},stack:s});if(e?.length){const t=(a.entries??[]).map(Ua("participantId")),n=e.map(Ua("participantId"));if(P(n,t).length!==n.length)return wr({result:{error:Nn},stack:s})}const c=Bd({event:a})?.flightProfile,u=c?.flights?.map((({flightNumber:t})=>!isNaN(t)&&n(t)))?.filter(Boolean)||[],d=Math.max(0,...u)+1,p={drawId:i||Md(),flightNumber:d,drawEntries:e,drawName:r};o&&(p.stage=o),t&&(p.qualifyingPositions=t);if((c?.flights||[]).find((({drawId:t})=>t===p.drawId)))return wr({result:{error:kn},stack:s});const l=(c?.flights||[]).concat(p);return _i({event:a,extension:{name:Ki,value:{...c||{},flights:l}}})}var WU={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}},HU={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}},zU={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}},YU={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}},KU={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}},JU={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}},ZU={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}},XU={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}},QU={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}},tS={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}]},eS={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}},nS={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}},rS={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}},iS={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}},aS={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}},oS={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}},sS={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 cS="COLLEGE_DEFAULT",uS="COLLEGE_JUCO",dS="COLLEGE_D3",pS="DOMINANT_DUO",lS="DOMINANT_DUO_MIXED",mS="LAVER_CUP",fS="TEAM_DOUBLES_3_AGGREGATION",hS="TIME_TENNIS_DUAL",gS="TIME_TENNIS_PRO_CIRCUIT",IS="USTA_BREWER_CUP",US="USTA_OZAKI_CUP",SS="USTA_COLLEGE",yS="USTA_GOLD_TEAM_CHALLENGE",vS="USTA_LEVEL_1",wS="USTA_INTERSECTIONAL",TS="USTA_SECTION_BATTLE",PS="USTA_SOUTHERN_LEVEL_5",DS="USTA_TOC",bS="USTA_WTT_ITT",NS="USTA_ZONAL",RS={COLLEGE_D3:dS,COLLEGE_DEFAULT:cS,COLLEGE_JUCO:uS,DOMINANT_DUO:pS,DOMINANT_DUO_MIXED:lS,LAVER_CUP:mS,TEAM_DOUBLES_3_AGGREGATION:fS,TIME_TENNIS_DUAL:hS,TIME_TENNIS_PRO_CIRCUIT:gS,USTA_BREWER_CUP:IS,USTA_OZAKI_CUP:US,USTA_COLLEGE:SS,USTA_GOLD_TEAM_CHALLENGE:yS,USTA_INTERSECTIONAL:wS,USTA_LEVEL_1:vS,USTA_SECTION_BATTLE:TS,USTA_SOUTHERN_LEVEL_5:PS,USTA_TOC:DS,USTA_WTT_ITT:bS,USTA_ZONAL:NS},MS="STANDARD",AS={[MS]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[dS]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1,matchUpFormat:"SET1-S:8/TB7@7"},singles:{matchUpFormat:lg,matchUpCount:6,matchUpValue:1},tieFormatName:dS,valueGoal:5},[cS]:{hydrate:!0,doubles:{matchUpCount:3,collectionValue:1,matchUpFormat:lg},singles:{matchUpCount:6,matchUpValue:1,matchUpFormat:lg},tieFormatName:cS,valueGoal:4},[uS]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1,matchUpFormat:"SET1-S:8/TB7"},singles:{matchUpCount:6,matchUpValue:1,matchUpFormat:lg},tieFormatName:uS,valueGoal:5},[mS]:oS,[pS]:eS,[lS]:ZU,[fS]:HU,[hS]:XU,[gS]:JU,[IS]:QU,[US]:tS,[SS]:nS,[yS]:WU,[wS]:KU,[vS]:rS,[TS]:YU,[PS]:zU,[bS]:iS,[DS]:sS,[NS]:aS},ES=t=>{const e=t?.namedFormat&&Object.keys(AS).includes(t.namedFormat)?t.namedFormat:MS,n=Array.isArray(t?.uuids)?t?.uuids:[];let r;const{category:i,gender:a}=t?.event??{},o=gi(AS[e],!1,!0);return o.hydrate?(r={winCriteria:{valueGoal:o.valueGoal},collectionDefinitions:[{collectionId:n?.pop()??Md(),matchUpFormat:mg,collectionName:"Doubles",matchUpType:Zs,...o.doubles},{collectionId:n?.pop()??Md(),matchUpFormat:lg,collectionName:"Singles",matchUpType:Ks,...o.singles}]},o.tieFormatName&&(r.tieFormatName=o.tieFormatName)):(o.collectionDefinitions.forEach((t=>t.collectionId=Md())),r=o),t?.hydrateCollections&&r.collectionDefinitions.forEach((t=>{i&&!t.category&&(t.category=i),a&&!t.gender&&(t.gender=a)})),r};const CS={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:eS,DOMINANT_DUO_MIXED:ZU,LAVER_CUP:oS,TEAM_DOUBLES_3_AGGREGATION:HU,TIME_TENNIS_DUAL:XU,TIME_TENNIS_PRO_CIRCUIT:JU,USTA_BREWER_CUP:QU,USTA_OZAKI_CUP:tS,USTA_COLLEGE:nS,USTA_GOLD_TEAM_CHALLENGE:WU,USTA_INTERSECTIONAL:KU,USTA_LEVEL_1:rS,USTA_SECTION_BATTLE:YU,USTA_SOUTHERN_LEVEL_5:zU,USTA_TOC:sS,USTA_WTT_ITT:iS,USTA_ZONAL:aS};function OS({suppressNotifications:t,tournamentRecord:e,internalUse:n,event:r}){if(!e)return{error:_};if(e.events||(e.events=[]),!r)return{error:Tt};const{startDate:i,endDate:a}=e;if(!n&&(r.entries?.length||r.drawDefinitions?.length)){const t=vr({drawDefinitions:!!r.drawDefinitions?.length,entries:!!r.entries?.length});return{info:"entries/drawDefinitions cannot exist",error:Nn,context:t}}const o={eventType:ed,drawDefinitions:[],entries:[],startDate:i,endDate:a,...r};if(r.eventType===ad)if(r.tieFormat){const t=fh({tieFormat:r.tieFormat});if(t.error)return t}else if(r.tieFormatName){if(!CS[r.tieFormatName])return{context:{tieFormatName:r.tieFormatName},error:Nn};const t=ES({namedFormat:r.tieFormatName});o.tieFormat=t}o.eventId||(o.eventId=Md());if(e.events.reduce(((t,e)=>t||e.eventId===o.eventId),void 0))return{error:Dt};{const n=o;if(e.events.push(n),!t){const{topics:t}=lr();if(t.includes(os)){const t=fl({event:r}).matchUps??[];Fs({tournamentId:e?.tournamentId,eventId:r.eventId,matchUps:t})}for(const t of r.drawDefinitions||[])_s({drawDefinition:t})}return{...E,event:o}}}function FS({tournamentRecord:t,drawDefinition:e,participantIds:n,stageSequence:r,stage:i=Xa,eventId:a,event:o}){if(!t)return{error:_};if(!Array.isArray(n))return{error:Nn,participantIds:n};if(!o)return{error:Tt};if(o){const t=kS({element:o,participantIds:n,stageSequence:r,stage:i});if(t.error)return t}if(e){const t=kS({element:e,participantIds:n,stageSequence:r,stage:i});if(t.error)return a?wr({context:{drawPromotionError:t.error,drawId:e.drawId},result:{...E},stack:"promoteAlternates"}):t}return{...E}}function kS({participantIds:t,stageSequence:e,element:r,stage:i}){const a=(r.entries||[]).filter((t=>t.entryStatus===$c)),o=(r.entries||[]).filter((e=>t.includes(e.participantId))),s=a.reduce(((t,e)=>{const{entryPosition:n}=e;return isNaN(n)&&t||(!t||n<t.entryPosition)&&e||t}),void 0),c=o.length?o:[s].filter(Boolean);if(!c?.length)return{error:Ge};const u=c.filter((({entryStatus:t})=>t!==$c));if(u.length)return{error:je,invalidEntryStatus:u};const d=c.filter((({entryStage:t})=>t&&t!==i));if(d.length)return{error:qe,invalidStage:d};const p=e&&c.filter((t=>t.stageSequence!==e));if(p?.length)return{error:$e,invalidStageSequence:p};for(const t of c){t.entryStatus=Hc;const e=t?.entryPosition;isNaN(e)||r.entries.forEach((t=>{t.entryStatus===$c&&t.entryPosition>e&&(t.entryPosition=t.entryPosition-1)}));const i=Math.max(...r.entries.filter((t=>t.entryStatus===Hc&&!isNaN(t.entryPosition))).map((({entryPosition:t})=>n(t||0))),0);t.entryPosition=i||0}return{...E}}function xS({tournamentRecord:t,drawDefinition:e,participantId:n,entryPosition:r,skipRefresh:i,event:a}){if(!t)return{error:_};if(!n)return wr({result:{error:Ae},stack:"setEntryPositions"});if(void 0!==r&&!Number.isSafeInteger(r))return{error:Nn,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=xl({entries:a.entries})),e?.entries&&(o(e),e.entries=xl({entries:e.entries}))),{...E}}function _S({tournamentRecord:t,event:e,startDate:n}){if(!t)return{error:_};if(!e)return{error:Tt};if(!Vr.test(n))return{error:pe};const r=BS(t);if(r.error)return r;const{tournamentStartDate:i,tournamentEndDate:a}=r,o=new Date(ri(n)).getTime();if(!i||!a||o<i||o>a)return{error:pe};const s=e.endDate&&new Date(ri(e.endDate));return s&&o>s&&(e.endDate=n),e.startDate=n,{...E}}function LS({tournamentRecord:t,event:e,endDate:n}){if(!t)return{error:_};if(!e)return{error:Tt};if(!Vr.test(n))return{error:pe};const r=BS(t);if(r.error)return r;const{tournamentStartDate:i,tournamentEndDate:a}=r,o=new Date(ri(n)).getTime();if(!i||!a||o<i||o>a)return{error:pe};const s=e.startDate&&new Date(ri(e.startDate));return s&&o<s&&(e.startDate=n),e.endDate=n,{...E}}function BS(t){const{startDate:e,endDate:n}=t;return Vr.test(e)&&Vr.test(n)?{tournamentStartDate:new Date(ri(e)).getTime(),tournamentEndDate:new Date(ri(n)).getTime()}:wr({result:{error:me},context:{startDate:e,endDate:n}})}const VS={addAdHocMatchUps:fU,addCollectionDefinition:oU,addCollectionGroup:function({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 wr({result:{error:ae},stack:p});let l=c?void 0:Zf({drawDefinition:r,structureId:o,matchUpId:s,eventId:u,event:d});if(l?.error)return wr({result:l,stack:p});const m=l?.structure;c=c||l?.matchUp;const f=l?.tieFormat,h=f?.winCriteria.valueGoal,g=Yf(f);if(l=fh({tieFormat:g}),l.error)return wr({result:l,stack:p});for(const t of g.collectionDefinitions){const{collectionId:e,collectionGroupNumber:n}=t;if(n&&i.includes(e))return wr({info:"collectionIds cannot be part of other collectionGroups",result:{error:Nn},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],EI({updateInProgressMatchUps:t,originalValueGoal:h,tournamentRecord:e,drawDefinition:r,tieFormatName:a,structureId:o,structure:m,tieFormat:g,matchUpId:s,matchUp:c,eventId:u,event:d})},addDrawDefinition:hU,addDrawDefinitionTimeItem:RI,addDrawEntries:im,addEvent:OS,addEventEntries:cm,addEventEntryPairs:function({allowDuplicateParticipantIdPairs:t,entryStage:e=Xa,entryStatus:n=$c,participantIdPairs:r=[],tournamentRecord:i,drawDefinition:a,event:o,uuids:s}){if(!i)return{error:_};if(!o)return{error:Tt};if(o.eventType!==Zs)return{error:wt};const c=[],u=new Map;for(const t of i.participants??[]){const{participantType:e,participantId:n,person:r,individualParticipantIds:i}=t;e===sc&&r?.sex?u.set(n,r.sex):e===uc&&i&&c.push(i)}const d=r.filter((t=>{if(2!==t.length)return!0;if(!u.has(t[0])||!u.has(t[1]))return!0;if(!o.gender||o.gender===Gp)return!1;const e=t.map((t=>u.get(t)));let n=o.gender===qp&&(e[0]!==qp||e[1]!==qp)||o.gender===Hp&&(e[0]!==Hp||e[1]!==Hp);return o.gender===$p&&(e.sort(Hl),e[0]===Hp&&e[1]===qp||(n=!0)),n}));if(d.length)return{error:Pe,invalidParticipantIdPairs:d};const p=r.map((t=>({participantId:s?.pop()??Md(),participantRole:um,individualParticipantIds:t,participantType:uc}))),l=t?p:p.filter((t=>!c.find((e=>2===P(e,t.individualParticipantIds).length))));let m,f=[];if(l){const e=gU({allowDuplicateParticipantIdPairs:t,participants:l,returnParticipants:!0,tournamentRecord:i});if(e.error)return e;f=e.participants||[],m=e.info}const h=cm({participantIds:r.map((t=>{const e=f.find((e=>2===P(e.individualParticipantIds,t).length));if(e)return e;const{participant:n}=Vc({tournamentRecord:i,participantIds:t});return n})).map((t=>t.participantId)),tournamentRecord:i,drawDefinition:a,entryStatus:n,entryStage:e,event:o});return l.length&&sr({payload:{participants:l},topic:ss}),{...h,info:m,newParticipantIds:l.map(Da)}},addFlight:$U,addPlayoffStructures:eU,addQualifyingStructure:function(t){const e=t.tournamentRecord;if(!e)return{error:_};const n=function(t){if(!t.drawDefinition)return{error:j};if(!t.targetStructureId)return{error:It};const e=jI(t);if(e.error)return e;const{structure:n,link:r}=e;return n&&r?pg({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,structure:n,link:r}):{error:Nn}}(t);if(n.error)return n;const{qualifyingRoundNumber:r,qualifyingPositions:i,targetStructureId:a,drawDefinition:o,structureName:s,matchUpType:c,drawSize:u,drawType:d}=t;return Lm({tournamentRecord:e,timeItem:{itemType:"addQualifyingStructures",itemValue:vr({drawId:o.drawId,qualifyingRoundNumber:r,qualifyingPositions:i,targetStructureId:a,structureName:s,matchUpType:c,drawSize:u,drawType:d})}}),n},addVoluntaryConsolationStage:function(t){return function({drawDefinition:t,drawSize:e}){if(!t)return{error:j};const n=MI({stage:eo,stageSequence:1,drawDefinition:t,drawSize:e});return n.error?n:(Ls({drawDefinition:t}),{...E})}(t)},addVoluntaryConsolationStructure:Pm,aggregateTieFormats:function({tournamentRecord:t}){if(!t)return{error:_};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){Uh({descendant:t.tieFormat,ancestor:e}).different||(n=e.tieFormatId)}if(n)t.tieFormatId=n,delete t.tieFormat;else{const n=gi(t.tieFormat,void 0,!0);n.tieFormatId||(n.tieFormatId=Md()),t.tieFormatId=n.tieFormatId,delete t.tieFormat,r.push(n),e+=1}},a=n.eventType;i({tieFormat:n.tieFormat,eventType:a});for(const t of n.drawDefinitions??[]){i({tieFormat:t.tieFormat,eventType:a});for(const e of t.structures??[])i({tieFormat:e.tieFormat,eventType:a})}const o=(e,r)=>{const i=c.matchUps?.find((t=>t.matchUpId===e));i&&(i.tieFormatId=r,delete i.tieFormat,xs({tournamentId:t?.tournamentId,eventId:n.eventId,matchUp:i}))},s=t=>{const n=gi(t.tieFormat,void 0,!0);n.tieFormatId||(n.tieFormatId=Md()),r.push(n),e+=1,o(t.matchUpId,n.tieFormatId)},c=fl({matchUpFilters:{matchUpTypes:[Xs]},event:n}),u=c.matchUps??[];for(const t of u){let e;for(const n of r){t.tieFormat&&Uh({descendant:t.tieFormat,ancestor:n}).different||(e=n.tieFormatId)}e?o(t.matchUpId,e):s(t)}r.length&&(n.tieFormats=r)}return{...E,addedCount:e}},alternateDrawPositionAssignment:function(t){return function({alternateParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i}){return Mf({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i})}(t)},applyLineUps:function({tournamentRecord:t,drawDefinition:e,matchUpId:n,lineUps:r,event:i}){if(!t)return{error:_};if(!e)return{error:q};if("string"!=typeof n)return{error:Yt};if(!Array.isArray(r))return{error:Nn,lineUps:r};const a=t.participants||[];let o=Xm({tournamentParticipants:a,inContext:!0,drawDefinition:e,matchUpId:n});if(o.error)return o;if(!o.matchUp)return{error:Wt};const{matchUp:s,structure:c}=o,{drawPositions:u,matchUpType:d}=s;if(d!==Qs)return{error:Yt};if(!u?.length)return{error:Z};const p=$d({matchUp:s,drawDefinition:e,structure:c,event:i})?.tieFormat,l={};for(const e of r){if(!Array.isArray(e))return{error:Nn,lineUp:e};const n={},r=[];for(const t of e){if("object"!=typeof t)return{error:Nn,lineUpAssignment:t};const{participantId:e,collectionAssignments:i=[]}=t;if(!Array.isArray(i))return{error:Nn,collectionAssignments:i};const o=a.find((t=>t.participantId===e));if(!o)return{error:Ee};if(o.participantType!==sc)return{error:be};const c=s.sides?.find((t=>t.participant?.individualParticipantIds?.includes(e)))?.sideNumber;c&&r.push(c);for(const t of i){if("object"!=typeof t)return{error:Nn,collectionAssignment:t};const{collectionId:r,collectionPosition:i}=t,a=p?.collectionDefinitions?.find((t=>t.collectionId===r));if(!a)return{error:Nn,collectionId:r};const o=`${r}-${i}`;n[o]||(n[o]=[]);const s=n[o].length;if(a.matchUpType===Ks&&s||a.matchUpType===Zs&&s>1)return{info:"Excessive collectionPosition assignments",error:Nn};n[o].push(e)}}const i=Object.values(n);for(const e of i)if(2===e.length){const{participant:n}=Vc({tournamentParticipants:a,participantIds:e});if(!n){const n=Bf({participant:{participantType:uc,participantRole:um,individualParticipantIds:e},pairOverride:!0,tournamentRecord:t});if(n.error)return n}}const o=g(r),c=((o[1]||0)>(o[2]||0)?1:(o[2]||0)>(o[1]||0)&&2)||void 0,u=Object.keys(l).map((t=>parseInt(t)));c&&!u.includes(c)&&(l[c]=e)}if(!Object.keys(l).length)return{error:Cn};if(o=Xm({drawDefinition:e,matchUpId:n}),o.error)return o;if(!o.matchUp)return{error:Wt};const{matchUp:m}=o;m.sides||(m.sides=[]);for(const t of[1,2]){const e=m.sides.find((e=>e.sideNumber===t)),n=l[t];n&&(e?e.lineUp=n:m.sides.push({lineUp:n,sideNumber:t}))}return xs({tournamentId:t?.tournamentId,context:"applyLineUps",drawDefinition:e,matchUp:m}),{...E}},assignDrawPosition:function({tournamentRecord:t,drawDefinition:e,participantId:n,drawPosition:r,structureId:i,qualifier:a,event:o,bye:s}){if(!e)return{error:j};if(!r)return{error:tt};if(!i)return{error:It};if(s){const n=bl({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:i,event:o});if(n.error)return n}else{if(a)return{error:Fn};{const a=Rf({tournamentRecord:t,drawDefinition:e,participantId:n,drawPosition:r,structureId:i,event:o});if(a.error)return a}}return{...E}},assignDrawPositionBye:bl,assignMatchUpSideParticipant:function({tournamentRecord:t,drawDefinition:e,participantId:n,sideNumber:r,matchUpId:i,event:a}){if(n&&"string"!=typeof n)return{error:Te};if(!e)return{error:j};if(!i)return{error:qt};const o=void 0===r;if(o&&(r=1),![1,2].includes(r))return wr({result:{error:Nn,context:{sideNumber:r}}});const{matchUp:s,structure:c}=Xm({drawDefinition:e,matchUpId:i,event:a});if(!s)return{error:Wt};if(!!(c?.structures||e.drawType&&e.drawType!==wo||c?.matchUps?.find((({roundPosition:t})=>!!t))))return{error:et};if(!n&&(s?.score?.scoreStringSide1||Ya.includes(s?.matchUpstatus)||s?.matchUpStatus&&[ka,Fa].includes(s.matchUpStatus)))return{error:ye,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);xs({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:s})}return{...E,sidesSwapped:o}},assignSeedPositions:function(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:Rt};if(!r)return{error:_};if(!c)return{error:at};const p=lu({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!==S(g).length)return{error:st};for(const t of h){const n=vf({...t,provisionalPositioning:e,tournamentRecord:r,drawDefinition:i,seedingProfile:a,structureId:o,event:u});if(n?.error)return n;n?.success&&d++}return d?{...E,modifications:d}:{error:Sn}},assignTieMatchUpParticipantId:Wf,attachConsolationStructures:function(t){return tU({...t,itemType:"attachConsolationStructures"})},attachFlightProfile:IU,attachPlayoffStructures:QI,attachQualifyingStructure:pg,attachStructures:tU,automatedPlayoffPositioning:tg,automatedPositioning:Qh,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=VU({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:Nn};const h=qU({tournamentRecord:t,scaleAttributes:r,scaleSortMethod:d,sortDescending:u,entries:l,stage:c}).scaledEntries??[],{scaleItemsWithParticipantIds:g}=jU({scaleAttributes:r,scaledEntries:h,stageEntries:f,seedsCount:m,scaleName:i});return{scaleItemsWithParticipantIds:g}},bulkMatchUpStatusUpdate:function(t){if(!t?.outcomes)return{error:ae};if(!Array.isArray(t.outcomes))return{error:ae,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:_};const i=n.filter((e=>e.tournamentId===t));if(i.length){const t=lU({outcomes:i,tournamentRecord:r});if(t.error)return t}}return{...E}},checkInParticipant:xf,checkOutParticipant:kf,deleteAdHocMatchUps:function({tournamentRecord:t,matchUpIds:e=[],drawDefinition:n,structureId:r,event:i}){if("object"!=typeof n)return{error:j};if("string"!=typeof r)return{error:It};if(!Array.isArray(e))return{error:Nn};const a=n.structures?.find((t=>t.structureId===r));if(!a)return{error:Ut};const o=a?.matchUps,s=o?.find((t=>!!t.roundPosition));if(a.structures||s||a.finishingPosition===Ko)return{error:$};const c=[],u=o?.filter((({matchUpId:t,score:n})=>($s({score:n})&&c.push(t),e.includes(t))))??[],d=u.map(Ua("matchUpId"));if(d.length){a.matchUps=(a.matchUps??[]).filter((({matchUpId:t})=>!d.includes(t))),ks({tournamentId:t?.tournamentId,matchUpIds:d,action:"deleteAdHocMatchUps",eventId:i?.eventId,drawDefinition:n});const e=function(t,e=1){return Array.isArray(t)&&t.every(p)?w(Math.min(...t,e),Math.max(...t)+1).filter((e=>!t.includes(e))):[]}(m(a.matchUps.map(Ua("roundNumber"))));if(e.length){e.reverse();for(const r of e)a.matchUps.forEach((e=>{e.roundNumber&&e.roundNumber>r&&(e.roundNumber-=1,xs({tournamentId:t?.tournamentId,context:["adHoc round deletion"],eventId:i?.eventId,drawDefinition:n,matchUp:e}))}))}if(c.length){a.positionAssignments=m(a.matchUps.flatMap((t=>(t.sides??[]).map((t=>t.participantId)))).filter(Boolean)).map((t=>({participantId:t})));const e=a?.matchUpFormat??n?.matchUpFormat??i?.matchUpFormat,r=jg({positionAssignments:a.positionAssignments,matchUps:a.matchUps,tournamentRecord:t,drawDefinition:n,matchUpFormat:e,event:i});r.error&&console.log(r)}Ls({structureIds:[r],eventId:i?.eventId,drawDefinition:n})}return{...E}},deleteDrawDefinitions:Jm,deleteEvents:function({removePairParticipants:t,tournamentRecord:e,eventIds:n}){if(!e)return{error:_};if(!e.events)return{error:Pt};if(!Array.isArray(n))return{error:ae,info:Pf("drawIds")};const r=[],i=[],a=[],o=[];if(e.events=(e.events||[]).filter((t=>{if(n.includes(t.eventId)){const n={action:Ym,payload:{events:[t]}};r.push(n),i.push({tournamentId:e.tournamentId,eventName:t.eventName,eventType:t.eventType,category:t.category,eventId:t.eventId,gender:t.gender})}const s=t.eventType===nd?(t.entries||[]).map((({entryStatus:t,participantId:e})=>t!==Qc&&e)).filter(Boolean):[],c=n.includes(t.eventId);return c?o.push(...s):a.push(...s),!c})),t){const t=o.filter((t=>!a.includes(t)));e.participants=e.participants.filter((({participantId:e})=>!t.includes(e)))}if(km({tournamentRecord:e}),r.length){sr({topic:ds,payload:r});Lm({tournamentRecord:e,timeItem:{itemType:Ym,itemValue:i}})}return{...E}},deleteFlightAndFlightDraw:function({autoPublish:t=!0,tournamentRecord:e,auditData:n,drawId:r,event:i,force:a}){if(!e)return{error:_};if(!r)return{error:at};if(!i)return{error:Tt};const{flightProfile:o}=Bd({event:i});if(o){const t=o.flights?.find((t=>t.drawId===r));if(t){const t=o.flights.filter((t=>t.drawId!==r));_i({event:i,extension:{name:Ki,value:{...o,flights:t}}})}}const s=i.drawDefinitions?.find((t=>t.drawId===r));if(s){const o=Jm({drawIds:[r],eventId:i.eventId,tournamentRecord:e,autoPublish:t,auditData:n,event:i,force:a});if(o.error)return o}return NI({tournamentRecord:e,event:i})},deleteFlightProfileAndFlightDraws:function({autoPublish:t=!0,tournamentRecord:e,auditData:n,event:r,force:i}){if(!e)return{error:_};if(!r)return{error:Tt};const{flightProfile:a}=Bd({event:r});if(a){const o=a.flights?.map((({drawId:t})=>t)).filter(Boolean),s=Jm({eventId:r.eventId,tournamentRecord:e,autoPublish:t,auditData:n,drawIds:o,event:r,force:i});return s.error?s:Bi({event:r,name:Ki})}return{...E}},destroyPairEntries:function(t){if(!t.tournamentRecord)return{error:_};const{participantIds:e,...n}=t;let r=0;const i=[];for(const t of e){const e=Um({participantId:t,...n});e.success&&(r+=1),e.error&&i.push(e.error)}return r?{destroyedCount:r,...E}:{error:i}},destroyPairEntry:Sm,disableTieAutoCalc:function({drawDefinition:t,matchUpId:e,event:n}){if(!t)return{error:j};const{matchUp:r}=Xm({drawDefinition:t,matchUpId:e,event:n});return Nr({extension:{name:Hi,value:!0},element:r})},drawMatic:function(t){const e=t.tournamentRecord?.participants;return Object.assign(t,{tournamentParticipants:e}),xU(t)},enableTieAutoCalc:function({tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r}){if(!e)return{error:j};const{matchUp:i}=Xm({drawDefinition:e,matchUpId:n,event:r});return i?.matchUpType!==Xs?{error:Yt}:PI({enableAutoCalc:!0,tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r})},getAvailablePlayoffProfiles:ug,getAvailablePlayoffRounds:ug,luckyLoserDrawPositionAssignment:function(t){return function({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i}){return Mf({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i})}(t)},modifyCollectionDefinition:Ph,modifyDrawDefinition:function({tournamentRecord:t,drawDefinition:e,drawUpdates:n,drawId:r,event:i}){if(!ha(n))return{error:Nn};const a=Bd({event:i}).flightProfile,o=n.drawName&&pU({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:j};if(s){_i({event:i,extension:{name:Ki,value:{...a,flights:a.flights}}})}return e&&(n.policyDefinitions&&uU({policyDefinitions:n.policyDefinitions,drawDefinition:e}),Ls({tournamentId:t?.tournamentId,drawDefinition:e})),{...E}},modifyDrawName:pU,modifyEntriesStatus:Ll,modifyEvent:function({tournamentRecord:t,eventUpdates:e,eventId:n,event:r}){const i="modifyEvent";if(!t)return wr({result:{error:_},stack:i});if(!fa(n))return wr({result:{error:Tt},context:{eventId:n},stack:i});if(!ha(e))return wr({result:{error:Nn},context:{eventUpdates:e},stack:i});const a=r?.entries?.filter((({entryStatus:t})=>{const e=t;return[...ou,$c].includes(e)})).map((({participantId:t})=>t))??[],o=a?Zl({participantFilters:{participantIds:a},withIndividualParticipants:!0,tournamentRecord:t}).participants??[]:[],s=[],c=o.reduce(((t,e)=>{const n=e.person?.sex?[e.person.sex]:e.individualParticpants?.map((t=>t.person?.sex))||[];return s.push(...n),t.includes(e.participantType)?t:t.concat(e.participantType)}),[]),u=m(s),d=!u.length||[$p,Gp].includes(e.gender??"")||1===u.length&&u[0]===e.gender;if(e.gender&&!d)return wr({context:{gender:e.gender,validGender:d},result:{error:Nn},stack:i});const p=(c.includes(id)&&[id]||c.includes(sc)&&[td]||c.includes(uc)&&[nd]||[nd,td,id]).includes(e.eventType??"");return e.eventType&&!p?wr({context:{participantType:e.eventType,validEventType:p},result:{error:Nn},stack:i}):(e.eventType&&(r.eventType=e.eventType),e.eventName&&(r.eventName=e.eventName),e.gender&&(r.gender=e.gender),{...E})},modifyEventEntries:function({entryStatus:t=Hc,unpairedParticipantIds:e=[],participantIdPairs:n=[],entryStage:r=Xa,tournamentRecord:i,event:a}){if(!i)return{error:_};if(!a)return{error:Tt};const o=i.participants??[],s=o.filter((t=>t.participantType===sc)).map((t=>t.participantId)),c=e.concat(...n).flat(1/0).filter((t=>!s.includes(t)));if(c.length)return{error:Pe,invalidParticipantIds:c};const u=n.filter((t=>2!==t.length));if(u.length)return{error:Pe,invalidParticipantIdPairs:u};const d=o.filter((t=>t.participantType===uc)).map((t=>t.individualParticipantIds)),p=gU({participants:n.filter((t=>!d.find((e=>2===P(e,t).length)))).map((t=>({participantType:uc,participantRole:um,individualParticipantIds:t}))),tournamentRecord:i});if(p.error)return p;const l=n.map((t=>{const{participant:e}=Vc({tournamentRecord:i,participantIds:t});return e})).map((e=>({participantId:e,entryStatus:t,entryStage:r}))),m=e.map((t=>({entryStatus:Qc,participantId:t,entryStage:r})));return a.entries=(a.entries??[]).filter((t=>t.entryStage===r)),a.entries=a.entries.concat(...l,...m),{...E}},modifyPairAssignment:function({replacementIndividualParticipantId:t,existingIndividualParticipantId:e,tournamentRecord:n,drawDefinition:r,participantId:i,event:a,uuids:o}){if(!a)return{error:Tt};if(a?.eventType!==nd)return{error:wt};if(o&&!Array.isArray(o))return{error:Nn};if(!n)return{error:_};if(![t,e,i].every((t=>"string"==typeof t)))return{error:Ae};if(!(a?.entries?.filter((({entryStatus:t})=>[Qc,tu].includes(t))).map((({participantId:t})=>t))||[]).includes(t))return{error:Te};const s=(n.participants||[]).find((t=>t.participantId===i));if(s?.participantType!==uc)return{error:we,participant:s};const c=s.individualParticipantIds,u=[t,...c.filter((t=>t!==e))],{participant:d}=Vc({participantIds:u,tournamentRecord:n});let p;if(d)p=d.participantId;else{const t=Bf({participant:{participantId:o?.pop(),participantRole:um,individualParticipantIds:u,participantType:uc},returnParticipant:!0,tournamentRecord:n});if(t.error)return t;p=t.participant.participantId}const{flightProfile:l}=Bd({event:a});if(r){const t=l?.flights?.find((({drawId:t})=>t===r.drawId));t&&(t.drawEntries=t.drawEntries.map((t=>t.participantId===i?{...t,participantId:p}:t))),r.entries=r.entries.map((t=>t.participantId===i?{...t,participantId:p}:t));for(const t of r.structures||[])if(t.positionAssignments)t.positionAssignments=t.positionAssignments.map((t=>t.participantId===i?{...t,participantId:p}:t));else if(t.structures)for(const e of t.structures)e.positionAssignments=e.positionAssignments.map((t=>t.participantId===i?{...t,participantId:p}:t))}a.entries=a.entries.map((n=>n.participantId===i&&{...n,participantId:p}||n.participantId===t&&{...n,participantId:e}||n));const m=n.events.some((({entries:t,eventId:e,drawDefinitions:n})=>a.eventId===e?n.some((({drawId:t,entries:e})=>t!==r?.drawId&&e?.find((t=>t.participantId===i)))):t?.find((t=>t.participantId===i))));if(!m){const t=gm({addIndividualParticipantsToEvents:!1,participantIds:[i],tournamentRecord:n});if(t.error)return t}return{...E,participantOtherEntries:m,newPairParticipantId:p}},modifySeedAssignment:function({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:i,seedValue:a,event:o}){return t?(t.participants||[]).find((t=>t.participantId===r))?function({validation:t=!0,tournamentRecord:e,drawDefinition:r,participantId:i,structureId:a,seedValue:o,event:c}){if(!r)return{error:j};if(!a)return{error:It};const{structure:u}=ts({drawDefinition:r,structureId:a});if(!u)return{error:Ut};if(!(!t||s(o)||void 0===o||""===o||"string"==typeof o&&o.split("-").every((t=>s(t)&&n(t)>0))))return{error:Nn};const{seedAssignments:d}=lu({drawDefinition:r,structure:u}),p=d?.map((t=>t.seedNumber)),l=d?.find((t=>t.participantId===i));if(l){const t="string"==typeof o?o.includes("-")&&o.split("-").map((t=>parseInt(t))).join("-")||parseInt(o)>0&&parseInt(o)||"":o&&o>0&&o||"";l.seedValue=t}else{const t={seedNumber:Math.max(0,...p||[])+1,participantId:i};o&&(t.seedValue=o),u.seedAssignments||(u.seedAssignments=[]),u.seedAssignments.push(t)}return Bs({tournamentId:e?.tournamentId,eventId:c?.eventId,drawDefinition:r,structure:u}),{...E}}({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:i,seedValue:a,event:o}):{error:Te}:{error:_}},modifyTieFormat:function({updateInProgressMatchUps:t=!1,tieFormatComparison:e,modifiedTieFormat:n,tournamentRecord:r,drawDefinition:i,structureId:a,matchUpId:o,eventId:s,uuids:c,event:u}){const d="modifyTieFormat";if(!fh({tieFormat:n}).valid)return wr({result:{error:Lt},info:"falied validation",stack:d});const p=Zf({drawDefinition:i,structureId:a,matchUpId:o,eventId:s,event:u});if(p.error)return wr({result:p,stack:d});const{matchUp:l,tieFormat:m}=p,f=Yf(m),g=Uh({descendant:n,ancestor:f});if(g.invalid)return wr({context:{invalid:g.invalid},result:{error:Lt},stack:d});if(!g?.different)return wr({result:{...E},info:"Nothing to do",stack:d});const I=f.collectionDefinitions.map((({collectionId:t})=>t)),U=n.collectionDefinitions.map((({collectionId:t})=>t)),S=I.filter((t=>!U.includes(t))),y=n.collectionDefinitions.filter((({collectionId:t})=>!I.includes(t))),v=y.map(Ua("collectionId")),w=[];let T;const P=n.tieFormatName;for(const e of n.collectionDefinitions){if(v.includes(e.collectionId))continue;const n=Ph({updateInProgressMatchUps:t,...e,tournamentRecord:r,tieFormatName:P,drawDefinition:i,structureId:a,matchUpId:o,eventId:s,event:u});if(n.modifications&&w.push(...n.modifications),n.error)return wr({result:n,stack:d});n.tieFormat&&(T=n.tieFormat)}for(const e of y){const n=oU({updateInProgressMatchUps:t,collectionDefinition:e,tournamentRecord:r,drawDefinition:i,tieFormatName:P,structureId:a,matchUpId:o,matchUp:l,eventId:s,uuids:c,event:u});if(n.error)return wr({result:n,stack:d});n.tieFormat&&(T=n.tieFormat)}for(const n of S){const c=xI({updateInProgressMatchUps:t,tieFormatComparison:e,tournamentRecord:r,drawDefinition:i,tieFormatName:P,collectionId:n,structureId:a,matchUpId:o,eventId:s,matchUp:l,event:u});if(c.error)return wr({result:c,stack:d});c.tieFormat&&(T=c.tieFormat)}return m?.tieFormatName!==P?(T.tieFormatName=P,w.push({tieFormatName:P})):(w.length||v.length||S.length)&&(delete T.tieFormatName,w.push("tieFormatName removed: modifications without new tieFormatName")),T.collectionDefinitions=T.collectionDefinitions.sort(((t,e)=>h(t.collectionOrder)-h(e.collectionOrder))).map(((t,e)=>({...t,collectionOrder:e+1}))),{processedTieFormat:Yf(T),modifications:w,...E}},orderCollectionDefinitions:function({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=>p(t))))return wr({result:{error:Nn},context:{orderMap:i}});if(a&&s?.tieFormat)OI({tournamentRecord:t,event:s,orderMap:i});else if(r){const n=e&&Xm({drawDefinition:e,matchUpId:r});if(n?.error)return n;if(!(o=n.matchUp))return{error:zt};o?.tieFormat&&(o.tieFormat=CI({tieFormat:o.tieFormat,orderMap:i}),xs({tournamentId:t?.tournamentId,eventId:s?.eventId,drawDefinition:e,matchUp:o}))}else if(n){const r=ts({drawDefinition:e,structureId:n});if(r.error)return r;const a=r.structure;if(a?.tieFormat)a.tieFormat=CI({tieFormat:a.tieFormat,orderMap:i}),kI({eventId:s?.eventId,tournamentRecord:t,drawDefinition:e,structure:a,orderMap:i}),Ls({drawDefinition:e,structureIds:[a.structureId]});else if(e.tieFormat)FI({structureIds:[n],tournamentRecord:t,drawDefinition:e,orderMap:i,event:s});else{if(!s?.tieFormat)return{error:On};OI({structureIds:[n],tournamentRecord:t,orderMap:i,event:s})}}else{if(!e?.tieFormat)return{error:On};FI({tournamentRecord:t,drawDefinition:e,orderMap:i,event:s})}return{...E}},promoteAlternate:function(t){const{participantId:e}=t;return e&&"string"!=typeof e?{error:Nn,participantId:e}:FS({...t,participantIds:[e].filter(Boolean)})},promoteAlternates:FS,pruneDrawDefinition:function({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:n,drawId:r}){if(!e)return{error:_};if(!n)return{error:j};let i=[];const{drawsAnalysis:a}=mU({tournamentRecord:e});if(a.canBePruned.includes(r)){const o=a.matchPlay.includes(r),s=a.drawAnalysis[r],{structures:[c]}=es({stageSequence:1,drawDefinition:n,stage:Xa}),u=s.structuresData.find((({structureId:t})=>c.structureId===t)),d=c.matchUps??[];i=d.sort(((t,e)=>t.roundPosition-e.roundPosition)).filter((({roundNumber:t})=>!u.inactiveRounds.includes(t)));const p=i.map(ba),l=d.map(ba).filter((t=>!p.includes(t)));if(o){const e=i.sort(((t,e)=>t.roundPosition-e.roundPosition)).filter((({roundNumber:t})=>!u.inactiveRounds.includes(t))).filter((({winningSide:t})=>t)),n=e.map(ba),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}ks({tournamentId:e?.tournamentId,matchUpIds:l,drawDefinition:n}),Ls({drawDefinition:n})}return{...E,matchUps:i}},qualifierDrawPositionAssignment:function(t){return function({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i}){return Mf({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i})}(t)},refreshEventDrawOrder:NI,removeCollectionDefinition:xI,removeCollectionGroup:function({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:ae};if(isNaN(e))return{error:Nn};const d="removeCollectionGroup";let p=s?void 0:Zf({drawDefinition:r,structureId:a,matchUpId:o,eventId:c,event:u});if(p?.error)return wr({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=Yf(m);if(p=fh({tieFormat:g}),p.error)return wr({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=EI({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}=Dc({tournamentRecord:n});if(t?.audit?.[ua]){Th({drawDefinition:r,auditData:vr({drawId:r?.drawId,collectionGroupNumber:e,action:d,structureId:a,matchUpId:o,eventId:c})})}}return wr({result:{...p,modifiedCollectionIds:I},stack:d})},removeDelegatedOutcome:function({drawDefinition:t,event:e,matchUpId:n}){if(!t)return{error:j};if(!n)return{error:qt};const{matchUp:r}=Xm({drawDefinition:t,event:e,matchUpId:n});return r?Dr({name:qi,element:r}):{error:Wt}},removeDrawEntries:function({autoEntryPositions:t=!0,participantIds:e,drawDefinition:n,drawId:r,stages:i,event:a}){if(!a)return{error:Tt};if(!r)return{error:at};if(!e?.length)return{error:Fe};if(b(kl({drawDefinition:n,stages:i}).assignedParticipantIds??[],e))return{error:Le};const o=t=>{const n=t.participantId;return!e.includes(n)},{flightProfile:s}=Bd({event:a}),c=s?.flights?.find((t=>t.drawId===r));return c?.drawEntries&&(c.drawEntries=c.drawEntries.filter(o),t&&(c.drawEntries=xl({entries:c.drawEntries}))),n?.entries&&(n.entries=n.entries.filter(o),t&&(n.entries=xl({entries:n.entries}))),{...E}},removeDrawPositionAssignment:ym,removeEventEntries:om,removeMatchUpSideParticipant:function({tournamentRecord:t,drawDefinition:e,sideNumber:n,matchUpId:r,event:i}){if(!t)return{error:_};if(!e)return{error:j};if(!r)return{error:qt};if(!n)return{error:ae};if(![1,2].includes(n))return{error:Nn,sideNumber:n};const{matchUp:a,structure:o}=Xm({drawDefinition:e,matchUpId:r,event:i});return a?o?.structures||e.drawType&&e.drawType!==wo||o?.matchUps?.find((({roundPosition:t})=>!!t))?{error:et}:(a.sides?.forEach((t=>{t.sideNumber===n&&delete t.participantId})),xs({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:a}),{...E}):{error:Wt}},removeRoundMatchUps:function({removeCompletedMatchUps:t,tournamentRecord:n,drawDefinition:r,structureId:i,roundNumber:a,event:o}){if(!n)return{error:_};if(!r)return{error:j};if(!a)return wr({result:{error:ae},info:"roundNumber required"});const s=ts({drawDefinition:r,structureId:i});if(s.error)return s;const c=s.structure;return c?.structures?{error:$}:ap({drawDefinition:r,structure:c})?function({removeCompletedMatchUps:t,drawDefinition:n,tournamentId:r,roundNumber:i,structure:a,eventId:o}){const s=a?.matchUps??[],c=[];let u=!1;if(s.reduce(((t,e)=>{const n=e?.roundNumber;return n?t.includes(n)?t:t.concat(n):t}),[]).sort(e).includes(i)){const e=s.filter((e=>{const n=e.roundNumber===i&&(!Ya.includes(e.matchUpStatus)||t);return n&&c.push(e.matchUpId),!n}));if(c.length){ks({matchUpIds:c,drawDefinition:n,tournamentId:r,eventId:o});e.some((t=>t.roundNumber===i))||(e.forEach((t=>{t.roundNumber>i&&(t.roundNumber-=1,xs({drawDefinition:n,tournamentId:r,eventId:o,matchUp:t}))})),u=!0),a.matchUps=e}}return{deletedMatchUpsCount:c.length,roundRemoved:u,...E}}({tournamentId:n.tournamentId,removeCompletedMatchUps:t,eventId:o.eventId,drawDefinition:r,roundNumber:a,structure:c}):(console.log("not implemented"),{...E})},removeScaleValues:UU,removeSeededParticipant:function({tournamentRecord:t,drawDefinition:e,participantId:n,structureId:r}){const i="removeSeededParticipant";if(!t)return{error:_};if(!e)return{error:j};const a=(e.structures??[]).find((t=>t.structureId===r));if(!a)return wr({result:{error:Ut},stack:i});if(!a.stage||![Xa,Qa].includes(a.stage)||a.stage===Xa&&1!==a.stageSequence)return wr({result:{error:$},stack:i});const o=a.seedAssignments?.find((t=>t.participantId===n));return o?{...E}:wr({info:"participant not seeded",result:{error:On},context:{participantId:n}})},removeSeeding:function({tournamentRecord:t,drawDefinition:e,entryStatuses:n,scaleName:r,drawId:i,event:a,stage:o}){return t?a?(r=r||a.category?.categoryName||a.category?.ageCategoryCode,UU({tournamentRecord:t,scaleAttributes:{eventType:a.eventType,scaleType:Fr,scaleName:r},drawDefinition:e,entryStatuses:n,drawId:i,event:a,stage:o})):{error:Tt}:{error:_}},removeStructure:function({tournamentRecord:t,drawDefinition:e,structureId:n,event:r,force:i}){if("string"!=typeof n)return{error:Nn};if(!e)return{error:j};if(!n)return{error:It};const a=e.structures??[],o=[],s=a.find((t=>t.structureId===n));if(!s)return{error:Ut};if(Yp({structure:s}).matchUps.some((({score:t})=>$s({score:t})))){const n=Dc({tournamentRecord:t,drawDefinition:e,structure:s,event:r})?.appliedPolicies;if(!(i??n?.[Mi]?.allowDeletionWithScoresPresent?.structures))return{error:qn}}const c=a.find((({stage:t,stageSequence:e})=>t===Xa&&1===e)),u=n===c?.structureId,d=a.filter((({stage:t})=>t===Qa)).map(Ua("structureId"));if(u&&!d.length)return{error:F};const p=a.map(Ua("structureId")),l=[],m=d.includes(n),f=new Map;p.forEach((t=>{return f.set(t,m?(n=t,e.links?.map((t=>d.includes(t.source.structureId)&&t.target.structureId===n&&t.source.structureId)).filter(Boolean)??[]):(t=>e.links?.map((e=>e.source.structureId===t&&e.target.structureId!==c?.structureId&&e.target.structureId)).filter(Boolean)??[])(t));var n}));const h=u?f.get(n):[n];for(;h?.length;){const t=h.pop(),{structure:r}=ts({structureId:t,drawDefinition:e}),{matchUps:i}=Yp({structure:r}),a=Ta(i);l.push(...a),e.links=e.links?.filter((e=>e.source.structureId!==t&&e.target.structureId!==t))??[],(!u||u&&d.length||t!==n)&&(e.structures=(e.structures??[]).filter((e=>(t&&t===e.structureId&&o.push(t),e.structureId!==t))));const s=t&&f.get(t)?.filter((t=>t!==c?.structureId||n===c.structureId));s?.length&&h.push(...s)}const{matchUps:g}=Jp({drawDefinition:e});if(g?.forEach((t=>{t.winnerMatchUpId&&l.includes(t.winnerMatchUpId)&&delete t.winnerMatchUpId,t.loserMatchUpId&&l.includes(t.loserMatchUpId)&&delete t.loserMatchUpId})),u){const t=(c.matchUps??[])?.map(Ua("matchUpId"));l.push(...t),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return m&&dg({drawDefinition:e}),ks({tournamentId:t?.tournamentId,matchUpIds:l,action:"removeStructure",eventId:r?.eventId,drawDefinition:e}),Ls({drawDefinition:e,eventId:r?.eventId}),{...E,removedMatchUpIds:l,removedStructureIds:o}},removeTieMatchUpParticipantId:function(t){const{tournamentRecord:e,drawDefinition:n,participantId:r,event:i}=t,a="removeTieMatchUpParticiapantId";if(!r)return wr({result:{error:Ae},stack:a});const o=Lf(t);if(o.error)return o;const{appliedPolicies:s}=Dc({tournamentRecord:e,drawDefinition:n,event:i}),c=t.policyDefinitions?.[wi]??s?.[wi]??sm[wi],u=c?.processCodes?.substitution,{inContextDualMatchUp:d,inContextTieMatchUp:p,relevantAssignments:l,collectionPosition:m,teamParticipants:f,collectionId:h,matchUpType:g,dualMatchUp:I,tieMatchUp:U,tieFormat:S}=o;if(!I)return wr({result:{error:zt},stack:a});const y=p?.sides?.find((t=>t.participant?.participantId===r||t.participant?.individualParticipantIds?.includes(r)));if(!y)return wr({result:{error:Ee},stack:a});if(!y.substitutions?.length&&($s({score:p?.score})||p?.winningSide))return wr({result:{error:_n},stack:a});const v=d?.sides?.find((({sideNumber:t})=>t===y.sideNumber))?.participantId;if(!v)return wr({result:{error:Ee},stack:a});const w=Zl({participantFilters:{participantIds:[r]},tournamentRecord:e})?.participants?.[0];if(!w)return wr({result:{error:Ee},stack:a});if(g===Ks&&w.participantType===uc)return wr({result:{error:we},stack:a});const T=w.participantType===sc?[r]:w.individualParticipantIds;Vf({tournamentId:e.tournamentId,eventId:i.eventId,inContextDualMatchUp:d,drawDefinition:n,dualMatchUp:I});let P=I.sides?.find((({sideNumber:t})=>t===y.sideNumber));if(!P&&(I.sides?.filter((({lineUp:t})=>!t)).length||0)<2){const t=f?.map((({participantId:t})=>({drawPosition:l?.find((e=>e.participantId===t))?.drawPosition,teamParticipantId:t})));P=I.sides?.find((e=>t?.find((({drawPosition:t})=>t===e.drawPosition))?.teamParticipantId===v))}if(!P)return wr({result:{error:Ee,context:{participantId:r}}});const{modifiedLineUp:D,previousParticipantIds:b}=Gf({collectionPosition:m,teamParticipantId:v,dualMatchUpSide:P,participantIds:T,drawDefinition:n,collectionId:h});if(P.lineUp=D,v&&S&&bf({participantId:v,lineUp:D,drawDefinition:n,tieFormat:S}),g===Zs&&w.participantType===sc){const t=p?.sides?.find((t=>t.sideNumber===P?.sideNumber)),{participantId:n}=t??{},i=n&&Zl({participantFilters:{participantIds:[n]},tournamentRecord:e,withDraws:!0})?.participants?.[0];if(!i)return wr({result:{error:Ee},stack:a});{const t=i?.individualParticipantIds?.filter((t=>t!==r))??[];if(b&&t.push(...b),t.length>2)return wr({result:{error:Pe},stack:a});if(i.draws?.length){if(1===t.length){const{participant:n}=Vc({participantIds:t,tournamentRecord:e});if(!n){const n=Bf({participant:{participantRole:um,individualParticipantIds:t,participantType:uc},pairOverride:!0,tournamentRecord:e});if(n.error)return wr({result:n,stack:a})}}}else if(t.length){i.individualParticipantIds=t;const n=$f({participant:i,pairOverride:!0,tournamentRecord:e});if(n.error)return wr({result:n,stack:a})}else{const t=gm({participantIds:[n],tournamentRecord:e});t.error&&console.log("cleanup",{result:t})}}}if(1===y.substitutions?.length){const t=p?.sides?.find((t=>t.sideNumber!==y.sideNumber));if(!t?.substitutions?.length&&U?.processCodes?.length){for(const t of u||[]){const e=U.processCodes.lastIndexOf(t);U.processCodes.splice(e,1)}xs({tournamentId:e?.tournamentId,matchUp:U,context:a,drawDefinition:n})}}return xs({tournamentId:e?.tournamentId,matchUp:I,context:a,drawDefinition:n}),{...E,modifiedLineUp:D}},renameStructures:function({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:Nn};if(!t)return{error:j};const n=Object.assign({},...e.map((t=>{if(!ha(t))return;const{structureId:e,structureName:n}=t||{};return e&&n?{[e]:n}:void 0})).filter(Boolean));if(!Object.values(n).length)return{error:ae};for(const e of t.structures||[]){const t=n[e.structureId];t&&(e.structureName=t)}return{...E}},replaceTieMatchUpParticipantId:jf,resetDrawDefinition:function({tournamentRecord:t,removeScheduling:e,drawDefinition:n}){if(!n)return{error:j};const r=xc({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&&[Qa,Xa].includes(s)||(a.positionAssignments=o.map((t=>(delete t.participantId,t))),a.seedAssignments=[]);const{matchUps:u}=Yp({afterRecoveryTimes:!1,inContext:!0,matchUpsMap:r,structure:a});for(const r of u){const{matchUpId:a,roundNumber:o,sides:s}=r,c=i(a);if(c){if(delete c.extensions,delete c.notes,c.matchUpStatus!==Ma&&Object.assign(c,Lg),o&&o>1&&c.drawPositions){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&&![Pu,Du,Tu,Ru,Nu,Mu].includes(t.itemType)))),xs({tournamentId:t?.tournamentId,context:"resetDrawDefiniton",drawDefinition:n,matchUp:c})}}}return Ls({drawDefinition:n,structureIds:(n.structures||[]).map((({structureId:t})=>t))}),{...E}},resetMatchUpLineUps:function({inheritance:t=!0,tournamentRecord:e,drawDefinition:n,matchUpId:r,event:i}){if(!n)return{error:j};const a=Xm({drawDefinition:n,matchUpId:r})?.matchUp;if(!a?.tieMatchUps)return{error:Yt};const o=Xm({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&&bf({drawDefinition:n,participantId:e,lineUp:[],tieFormat:t})}xs({tournamentId:e?.tournamentId,context:"resetMatchUpLineUps",eventId:i?.eventId,drawDefinition:n,matchUp:a})})),{...E,modificationsCount:s}},resetScorecard:function(t){const{tournamentRecord:e,drawDefinition:n,matchUpId:r,event:i}=t,a="resetScorecard";if(!n)return wr({result:{error:j},stack:a});if(!r)return wr({result:{error:qt},stack:a});if(!fa(r))return wr({result:{error:Nn,matchUpId:r},stack:a});const o=xc({drawDefinition:n}),{matchUps:s}=Jp({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:Wt};if(c.matchUpType!==ad)return{error:Yt};const d=Uc({inContextDrawMatchUps:s,drawDefinition:n,matchUpId:r}),p=u?.structureId,{structure:l}=ts({drawDefinition:n,structureId:p});if(Object.assign(t,{inContextDrawMatchUps:s,inContextMatchUp:u,matchUpsMap:o,targetData:d,structure:l,matchUp:c}),rI(t))return{error:ve};if(c.tieMatchUps?.length)for(const t of c.tieMatchUps){const o=PI({matchUpId:t.matchUpId,matchUpTieId:r,winningSide:void 0,removeScore:!0,tournamentRecord:e,drawDefinition:n,event:i});if(o.error)return wr({result:o,stack:a})}const m=$g({event:t.event,removeScore:!0,tournamentRecord:e,drawDefinition:n,matchUpsMap:o,matchUpId:r});if(m.error)return wr({result:m,stack:a});if(t.tiebreakReset&&!m.tieFormatRemoved){const t=$d({drawDefinition:n,structure:l,event:i})?.tieFormat;if(c.tieFormat&&t){const{matchUpCountDifference:a,descendantDifferences:o,ancestorDifferences:s,valueDifference:u}=Uh({descendant:c.tieFormat,ancestor:t});if(1===o.collectionIds.length&&!s.collectionIds.length&&!s.groupsCount&&1===a&&1===u){const t=SU({tournamentRecord:e,drawDefinition:n,matchUpId:r,event:i});if(t.error)return t}}}return{...E}},resetTieFormat:SU,resetVoluntaryConsolationStructure:function({tournamentRecord:t,drawDefinition:e,resetEntries:n,event:r}){if(!e)return{error:j};const i=e.structures?.find((t=>t.stage===eo));if(!i)return{error:Ut};const a=i.matchUps?.map((({matchUpId:t})=>t))||[];return i.positionAssignments=[],i.seedAssignments=[],i.matchUps=[],ks({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:a,drawDefinition:e}),n&&(e.entries=e.entries.filter((t=>t.entryStage!==eo))),Ls({tournamentId:t?.tournamentId,eventId:r?.eventId,drawDefinition:e,structureIds:[i.structureId]}),{...E}},setDelegatedOutcome:function(t){return function({drawDefinition:t,matchUpId:e,outcome:n,matchUp:r}){if(!r&&!t)return{error:j};if(!n)return{error:ae,info:"missing outcome"};if(!r&&!e)return{error:zt};if(!r){const n=Xm({drawDefinition:t,matchUpId:e});if(n.error)return n;r=n.matchUp}return"object"==typeof n&&n.score?.scoreStringSide1&&n.score?.scoreStringSide2?Nr({element:r,extension:{name:qi,value:n}}):{error:Nn}}(t)},setDrawParticipantRepresentativeIds:function({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:q};if(!Array.isArray(t))return{error:Nn};const n=Pa(e?.entries||[]);return t.length&&P(t,n).length<t.length?{error:Nn}:xi({drawDefinition:e,extension:{name:ta,value:t}})},setEntryPosition:xS,setEntryPositions:function({tournamentRecord:t,entryPositions:e,drawDefinition:n,event:r}){if(!t)return{error:_};if(!Array.isArray(e))return{error:Nn};for(const i of e){const{participantId:e,entryPosition:a}=i,o=xS({skipRefresh:!0,tournamentRecord:t,drawDefinition:n,participantId:e,entryPosition:a,event:r});if(o.error)return o}return r?.entries&&(r.entries=xl({entries:r.entries})),n?.entries&&(n.entries=xl({entries:n.entries})),{...E}},setEventDates:function({tournamentRecord:t,event:e,startDate:n,endDate:r}){if(!t)return{error:_};if(!e)return{error:Tt};if(!n&&!r)return{error:ae,info:"missing date"};if(n&&!Vr.test(n))return{error:pe};if(r&&!Vr.test(r))return{error:pe};if(n&&r){if(new Date(ri(n))>new Date(ri(r)))return{error:Nn}}if(n){const r=_S({tournamentRecord:t,event:e,startDate:n});if(r.error)return r}if(r){const n=LS({tournamentRecord:t,event:e,endDate:r});if(n.error)return n}return{...E}},setEventEndDate:LS,setEventStartDate:_S,setMatchUpFormat:function(t){const e="setMatchUpFormat",{tournamentRecord:n,drawDefinition:r,scheduledDates:i,stageSequences:a,matchUpFormat:o,structureId:s,eventType:c,matchUpId:u,eventId:d,stages:p,drawId:l,event:m,force:f}=t;if(!n)return{error:_};if(!o)return{error:Vt};if(o&&!rh(o))return wr({result:{error:kt,matchUpFormat:o},stack:e});if(i&&!Array.isArray(i))return wr({result:{error:Nn,scheduledDates:i},stack:e});if(c&&![td,nd].includes(c))return wr({result:{error:wt},stack:e});let h=0;const g=t.structureIds||s&&[s].filter(Boolean)||[],I=t.eventIds||d&&[d].filter(Boolean)||[],U=t.drawIds||l&&[l].filter(Boolean)||[];if((s||g?.length)&&!r)return wr({result:{error:j},stack:e});if(l&&u&&r){const t=GI({tournamentRecord:n,drawDefinition:r,matchUpFormat:o,structureIds:g,structureId:s,matchUpId:u});if(t.error)return t;h+=1}const S=t=>{const r=[];for(const s of t.structures||[]){if(Array.isArray(p)&&!p.includes(s.stage)||Array.isArray(a)&&!a.includes(s.stageSequence)||g?.length&&!g.includes(s.structureId))continue;g?.length&&s.matchUpFormat!==o&&(s.matchUpFormat=o,r.push(s.structureId),h+=1);const c=(f||i)&&Yp({matchUpFilters:{matchUpStatuses:[ja]},structure:s}).matchUps,u=i&&Yp({matchUpFilters:{matchUpStatuses:[ja]},contextFilters:{scheduledDates:i},afterRecoveryTimes:!1,inContext:!0,structure:s}).matchUps;if(c?.length){const r=u?u.map(ba):c.map(ba);for(const a of c)r.includes(a.matchUpId)&&(a.matchUpFormat=i?.length?o:void 0,xs({tournamentId:n?.tournamentId,eventId:m?.eventId,context:e,drawDefinition:t,matchUp:a}))}}return r.length||t.matchUpFormat===o||(t.matchUpFormat=o,h+=1),r};for(const t of n.events||[])if(!(I?.length&&!I.includes(t.eventId)||c&&c!==t.eventType||c===id))if(Array.isArray(a)||Array.isArray(p)||g?.length||U?.length)for(const e of t.drawDefinitions||[]){if(Array.isArray(U)&&!U.includes(e.drawId))continue;Ls({structureIds:S(e),drawDefinition:e})}else t.matchUpFormat!==o&&(t.matchUpFormat=o,h+=1);return h?{...E,modificationsCount:h}:{...E,info:Sn}},setMatchUpStatus:aU,setOrderOfFinish:function(t){return function({drawDefinition:t,finishingOrder:e}){if(!t)return{error:j};const n="setOrderOfFinish";if(!Array.isArray(e))return wr({info:Pf("finishingOrder"),result:{error:Nn},stack:n});const{completedMatchUps:r,matchUpsMap:i}=Zp({inContext:!0,drawDefinition:t}),a=r?.map(ba)??[],o=e.map(ba),{matchUpTypes:s,roundNumbers:c,structureIds:u,matchUpTieIds:d}=(r??[]).filter((({matchUpId:t})=>o.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(s.length>1||d.length>1||c.length>1||u.length>1)return wr({info:"matchUpType, structureId and roundNumber must be equivalent",result:{error:Nn},stack:n});let l,m;const f={},h=[],g=[],I=e.every((({orderOfFinish:t,matchUpId:e})=>(h.push(e),t&&g.push(t),f[e]=t,l=a.includes(e),m=void 0===t||p(t)&&Math.floor(t)>0,l&&m)));if(!I)return wr({result:{error:l?Nn:_t},info:(l?!m&&"orderOfFinish must be integer > 0 or undefined":"matchUps must be completed")||void 0,stack:n});const U=r?.filter((t=>t.structureId===u[0]&&t.roundNumber===c[0]&&t.matchUpType===s[0]&&t.matchUpTieId===d[0]&&!h.includes(t.matchUpId)));for(const t of U??[]){const{orderOfFinish:e}=t||{};if(e){if(!p(e))return wr({context:{orderOfFinish:e,matchUp:t},result:{error:Nn},stack:n});g.push(e)}}if(S(g).length!==g.length||Math.max(...g)>g.length)return wr({info:"Values not unique or greater than expected number of values",result:{error:Nn},stack:n});if(u.length){const e=Kp({matchUpFilters:{matchUpIds:o},structureId:u[0],drawDefinition:t,matchUpsMap:i});if(e.error)return wr({result:e,stack:n});e.completedMatchUps?.forEach((t=>t.orderOfFinish=f[t.matchUpId]))}return{...E}}(t)},setPositionAssignments:function(t){return function({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:n,drawDefinition:r,event:i}){if(!r)return{error:j};if(!Array.isArray(t))return{error:Nn};for(const a of t){const{structureId:t,positionAssignments:o}=a;if(!o)continue;const s=ts({drawDefinition:r,structureId:t});if(s.error)return s;const c=s.structure;if(!c)return{error:Ut};const u=rs({structure:c}).positionAssignments?.map((({drawPosition:t})=>t)),d=o?.map((({drawPosition:t})=>t));if(P(u,d).length!==u?.length)return wr({result:{error:Nn},info:"drawPositions do not match",stack:"setPositionAssignments"});const p=xc({drawDefinition:r}),{matchUps:l}=Jp({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=bl({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=Rf({provisionalPositioning:e,inContextDrawMatchUps:l,tournamentRecord:n,drawDefinition:r,participantId:u,drawPosition:s,matchUpsMap:p,structureId:t,event:i});if(a?.error)return a}}Vs({tournamentId:n?.tournamentId,drawDefinition:r,structure:c,event:i})}const a=t.map((({structureId:t})=>t));return Ls({tournamentId:n?.tournamentId,eventId:i?.eventId,drawDefinition:r,structureIds:a}),{...E}}(t)},setStructureOrder:function({drawDefinition:t,orderMap:e}){return t?("object"==typeof e&&Object.values(e).every((t=>p(t)))||wr({result:{error:Nn},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)=>h(t.structureOrder)-h(e.structureOrder))),{...E}):{error:j}},setSubOrder:function({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:r,subOrder:i,event:a}){if(!e)return{error:j};if(!r)return{error:It};if(!n)return{error:tt};const{structure:o}=ts({drawDefinition:e,structureId:r});if(!o)return{error:Ut};let s=o;o.structures&&o.structureType===mo&&(s=o.structures?.find((t=>t.positionAssignments?.find((t=>t.drawPosition===n)))));const c=s?.positionAssignments,u=c?.find((t=>t.drawPosition===n));u&&Nr({element:u,extension:{name:sa,value:i}});const d=(a?.eventType===Qs||e.matchUpType===Qs||(a?.tieFormat??e?.tieFormat??o?.tieFormat))&&{matchUpTypes:[Qs]},{matchUps:p}=Yp({structure:s,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:d,event:a});return jg({positionAssignments:c,tournamentRecord:t,drawDefinition:e,matchUpFormat:o?.matchUpFormat??e.matchUpFormat,matchUps:p,event:a}),Ls({drawDefinition:e,structureIds:[r]}),{...E}},substituteParticipant:function(t){return function({substituteParticipantId:t,existingParticipantId:e,tournamentRecord:n,drawDefinition:r,sideNumber:i,matchUpId:a,event:o}){const s="substituteParticipant";if(!r)return{error:j};if(!a)return{error:qt};if(!e||!t)return wr({result:{error:Ae},stack:s});const{matchUp:c}=Xm({drawDefinition:r,matchUpId:a,event:o});if(!c)return{error:Wt};if(!c.collectionId)return wr({result:{error:Yt},stack:s});const u=xc({drawDefinition:r}),{matchUps:d}=Jp({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:Te};const f=m.participant?.individualParticipants?.map(Da).filter((t=>t!==e));return f?.includes(t)?jf({newParticipantId:t,tieMatchUpId:a,existingParticipantId:e,substitution:!0,tournamentRecord:n,drawDefinition:r,event:o}):wr({result:{error:Te},stack:s})}(t)},swapDrawPositionAssignments:function(t){return Dh(t)},toggleParticipantCheckInState:_f,updateDrawIdsOrder:bI,updateTeamLineUp:bf,updateTieMatchUpScore:$g,withdrawParticipantAtDrawPosition:function(t){return Object.assign(t,{entryStatus:nu}),ym(t)}};function jS({qualifyingProfiles:t,appliedPolicies:e,idPrefix:n,isMock:r,uuids:i}){const o=[],s=[],c=[],u=(t,e)=>t.stageSequence-e.stageSequence,d=(t,e)=>t.roundTarget-e.roundTarget;let l,m=0,f=0,h=1;for(const g of t.sort(d)){const d=g.structureProfiles||[];h=g.roundTarget||h;let I,U,S,y=1,v=0;for(const o of(d||[]).sort(u)){let u=a(o.drawSize||o.participantsCount);const{qualifyingRoundNumber:f,structureOptions:g,matchUpFormat:w,structureName:T,structureId:P,drawType:D}=o,b=o.matchUpType,N=o.qualifyingPositions||GS({drawSize:u,qualifyingRoundNumber:f});let R,M,A;if(!p(u))return wr({result:{error:it},stack:"generateQualifyingSTructures"});const E=t.length>1?`${h}-`:"",C=d.length>1||E?y:"",O=T||(E||C?`${wm(Qa)} ${E}${C}`:wm(Qa));if(D===Go){const{structures:t,groupCount:a,maxRoundNumber:s}=pf({structureName:o.structureName||O,structureId:P||i?.pop(),stage:Qa,structureOptions:g,appliedPolicies:e,stageSequence:y,matchUpType:b,roundTarget:h,drawSize:u,idPrefix:n,isMock:r,uuids:i});v=a,R=s,M=t[0],l=[1]}else({drawSize:u,matchUps:A,roundLimit:R}=VI({qualifyingRoundNumber:f,qualifyingPositions:N,matchUpType:b,drawSize:u,idPrefix:n,isMock:r,uuids:i})),M=Tm({structureName:o.structureName||O,structureId:P||i?.pop(),qualifyingRoundNumber:R,stage:Qa,matchUpFormat:w,stageSequence:y,matchUpType:b,roundLimit:R,matchUps:A}),h&&Nr({extension:{name:ra,value:h},element:M}),v=A?.filter((t=>t.roundNumber===R))?.length||0;if(y>1){const{link:t}=_I({sourceStructureId:U,sourceRoundNumber:I,targetStructureId:M.structureId,finishingPositions:S===Uo?[1]:void 0,linkType:S});c.push(t),m+=(u||0)-v}else m+=u||0;S=D===Go?Uo:So,U=M.structureId,I=R,s.push(M),y+=1}f+=v,o.push({qualifiersCount:v,finalQualifyingRoundNumber:I,finalQualifyingStructureId:U,finishingPositions:l,roundTarget:h,linkType:S}),h+=1}return{qualifiersCount:f,qualifyingDrawPositionsCount:m,qualifyingDetails:o,structures:s,...E,links:c}}function GS({drawSize:t,qualifyingRoundNumber:e}){let n=t,r=0;for(;r<e;)n=Math.floor(n/2),r+=1;return n}function qS({structureName:t,matchUpType:e,idPrefix:n,drawSize:r,isMock:i,uuids:a}){const o=[],{matchUps:s}=$I({linkFedFinishingRoundNumbers:[1],drawSize:r+1,matchUpType:e,idPrefix:n,isMock:i}),c=Tm({structureName:t||wm(Xa),structureId:a?.pop(),stageSequence:1,stage:Xa,matchUpType:e,matchUps:s});o.push(c);const u=r/2,{matchUps:d}=$I({finishingPositionOffset:u,idPrefix:n&&`${n}-c`,drawSize:r-1,isConsolation:!0,matchUpType:e,isMock:i,uuids:a}),p=Tm({structureName:wm(Wo),matchUps:d,structureId:a?.pop(),stage:to,stageSequence:2,matchUpType:e});o.push(p);const{matchUps:l}=VI({idPrefix:n&&`${n}-p1t2`,drawSize:2,matchUpType:e,isMock:i}),m=Tm({structureName:wm($o),matchUps:l,structureId:a?.pop(),stageSequence:3,stage:no,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?go:Io;return{linkType:yo,source:{roundNumber:1+i,structureId:t.structureId},target:{feedProfile:a,roundNumber:n,structureId:e.structureId}}})),{linkType:So,source:{roundNumber:a,structureId:e.structureId},target:{feedProfile:go,roundNumber:i,structureId:t.structureId}},{linkType:So,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:go,roundNumber:1,structureId:n.structureId}},{linkType:yo,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:go,roundNumber:1,structureId:n.structureId}}]}({mainStructure:c,consolationStructure:p,deciderStructure:m});return{structures:o,links:f,...E}}function $S(t){const{qualifyingRoundNumber:e,finishingPositionOffset:i,qualifyingPositions:a,matchUpType:o,idPrefix:s,drawSize:c,isMock:u,uuids:d}=t;if(!p(c)||c<2)return{matchUps:[],roundsCount:0};if(r(c))return VI(t);const l=function(t){const e=n(t);let r=e%2?e+1:e;const i=!!(Math.ceil(r/2)%2),a=[{participantsCount:r,preFeedRound:i}];for(;r>2;){const t=Math.ceil(r/2),e=1===t,n=!(e||!(t%2));r=!e&&n?t+1:t;const i=!!(2!==r&&Math.ceil(r/2)%2);a.push({participantsCount:r,preFeedRound:i,feedRound:n})}return a}(c),m=l.shift(),f=w(1,(m?.participantsCount||0)+1).map((t=>({drawPosition:t})));let h=[],g=1;({matchUps:h}=BI({roundNumber:g,matchUpType:o,idPrefix:s,matchUps:h,isMock:u,nodes:f,uuids:d})),g++;let I=t.roundLimit||e;for(const t of l){const e=t.participantsCount/2,n=w(1,e+1);a&&e===a&&(I=g-1);const r=n.map((t=>{const e=LI({roundPosition:t,roundNumber:g,idPrefix:s,uuids:d});return{roundPosition:t,roundNumber:g,matchUpId:e}}));h.push(...r),g++}const U=g-1;return h=Xp({finishingPositionOffset:i,lucky:!0,roundsCount:U,roundLimit:I,matchUps:h}),I&&(h=h.filter((t=>t.roundNumber<=I))),{matchUps:h,roundsCount:U,roundLimit:I}}function WS(t){const{playoffAttributes:e,stageSequence:n=1,structureId:r,stage:i=Xa,matchUpType:a,drawSize:o,uuids:s}=t,{appliedPolicies:c}=Dc(t),u=t.policyDefinitions?.[Ei]||c?.[Ei];t.skipRounds=t.skipRounds||o<=4&&(u?.feedMainFinal?0:1)||0;const d=t.structureName??e?.[0]?.name??wm(Xa),p={[wo]:()=>({structures:[Tm({structureId:r||s?.pop(),finishingPosition:Yo,stageSequence:n,structureName:d,matchUps:[],matchUpType:a,stage:i})],links:[],...E}),[Ao]:()=>{const{matchUps:e}=$S(t);return{structures:[Tm({structureId:r||s?.pop(),stageSequence:n,structureName:d,matchUpType:a,matchUps:e,stage:i})],links:[],...E}},[bo]:()=>(()=>{const{matchUps:e}=VI(t);return{structures:[Tm({structureId:r||s?.pop(),stageSequence:n,structureName:d,matchUpType:a,matchUps:e,stage:i})],links:[],...E}})(),[No]:()=>qS(t),[Po]:()=>WI({...t,roundOffsetLimit:3,playoffAttributes:e??Ho}),[Do]:()=>WI({...t,roundOffsetLimit:2,playoffAttributes:e??zo}),[no]:()=>WI(t),[To]:()=>{const{matchUps:t}=$I({drawSize:o,uuids:s,matchUpType:a});return{structures:[Tm({structureId:r||s?.pop(),stageSequence:n,structureName:d,matchUpType:a,stage:Xa,matchUps:t})],links:[],...E}},[Mo]:()=>HI(t),[Ro]:()=>KI({...t,feedRounds:1,fmlc:!0}),[Bo]:()=>KI({...t,feedRounds:1}),[Oo]:()=>KI({...t,feedsFromFinal:1}),[ko]:()=>KI({...t,feedsFromFinal:2}),[_o]:()=>KI({...t,feedsFromFinal:3}),[jo]:()=>KI(t),[Eo]:()=>YI(t),[Go]:()=>pf(t),[qo]:()=>function(t){const{drawDefinition:e,structureOptions:n,requireSequential:r}=t,i={structureName:wm(Xa),...t,stage:Xa},{structures:a,groupCount:o,groupSize:s}=pf(i);if(o<1)return{error:wn};const c=n?.playoffGroups||[{finishingPositions:[1],structureName:wm(no)}],[u]=a,{structures:d,links:p}=JI({sourceStructureId:u.structureId,requireSequential:r,drawDefinition:e,playoffGroups:c,groupCount:o,groupSize:s,...t});return d&&a.push(...d),{...E,structures:a,links:p}}(t)};return{generators:p}}function HS(t){const{enforceMinimumDrawSize:e=!0,overwriteExisting:i,appliedPolicies:a,staggeredEntry:o,drawDefinition:s,tieFormat:c,drawSize:u,isMock:d,uuids:p}=t||{},l=t.drawTypeCoercion??a?.[Ci]?.drawTypeCoercion??!0,m="generateDrawStructuresAndLinks";let f=l&&2===t.drawSize&&bo||t.drawType||bo;const h=[],g=[],I=t?.matchUpType??Ks,U=s?.structures?.filter((({stage:t})=>t===Qa));U&&h.push(...U);const S=U?.map((({structureId:t})=>t)),y=s?.structures?.find((({stage:t,stageSequence:e})=>t===Xa&&1===e)),v=s?.links?.filter((t=>t.target.structureId===y?.structureId&&S?.includes(t.source.structureId))),w=(t,e)=>{if(t.linkType===Uo&&e?.structures){const n=t.source.finishingPositions||[];return e.structures.length*n.length}if(t.linkType===So&&e?.matchUps?.length){const n=t.source.roundNumber;return e.matchUps.filter((({roundNumber:t})=>t===n)).length}},T=U?.map((t=>{const e=v?.find((e=>e.target.structureId===t.structureId)),n=rs({structure:t})?.positionAssignments?.length??0;if(!e)return n;const r=e?.source.structureId,i=s.structures?.find((t=>t.structureId===r));return n-(w(e,i)||0)})).filter(Boolean).reduce(((t,e)=>t+e),0),P=v?.map((t=>{const e=t.source.structureId,n=U?.find((t=>t.structureId===e));return w(t,n)})).filter(Boolean).reduce(((t,e)=>t+e),0),D=!(!y||y?.matchUps?.length);if(U?.length&&!D)return{error:Bn};const b=!U?.length&&t.qualifyingProfiles,N=b?.length&&jS({idPrefix:t.idPrefix,qualifyingProfiles:b,appliedPolicies:a,isMock:d,uuids:p});if(N?.error)return N;const{qualifyingDrawPositionsCount:R,qualifyingDetails:M,qualifiersCount:A}=N||{qualifyingDrawPositionsCount:T,qualifiersCount:P};R&&(N?.structures&&h.push(...N.structures),N?.links&&g.push(...N.links)),Object.assign(t,vr({drawSize:u,matchUpType:I,tieFormat:c}));const C=f!==wo&&(!u||isNaN(u)||u<2||!o&&![To,Ao].includes(f)&&([qo,Go].includes(f)&&u<3||![Go,qo].includes(f)&&!r(u)));if(C&&!R)return wr({context:{drawSize:u,invalidDrawSize:C},result:{error:nt},stack:m});const O=Jo.includes(f);if(u&&n(u)<4&&O)if(l)f=bo;else if(e)return wr({context:{enforceMinimumDrawSize:e,invalidDrawSize:C,drawSize:u,drawType:f},result:{error:nt},stack:m});const{generators:F,error:k}=WS(t);if(k)return{error:k};const x=F[f];if(!x)return{error:J};const _=x?.();if(_.error)return _;const{structures:L,links:B}=_;if(L?.length){const t=L.find((({stage:t,stageSequence:e})=>t===Xa&&1===e));if(y&&t)if(D){const e=t.structureId;if(t.structureId=y.structureId,B?.length)for(const t of B)t.source.structureId===e&&(t.source.structureId=y.structureId),t.target.structureId===e&&(t.target.structureId=y.structureId)}else if(!i)return{error:Bn};h.push(...L)}h.sort(Xo),B?.length&&g.push(...B);const V=_.structures.find((({stage:t,stageSequence:e})=>t===Xa&&1===e));for(const t of M||[]){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&&g.push(o)}return v&&g.push(...v),{...E,qualifyingResult:{qualifyingDrawPositionsCount:R,qualifiersCount:A},structures:h,links:g}}function zS(t){const{modifyOriginal:e=!0,stageSequence:n=1,isMock:r}=t||{},i="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return wr({result:{error:j},stack:i});const a=e?t.drawDefinition:gi(t.drawDefinition,!1,!0);let{tieFormat:o,matchUpType:s}=t;if(o){const t=fh({tieFormat:o});if(t.error)return t}o=Yf(o??$d({drawDefinition:a})?.tieFormat),s=s??(a.matchUpType||Ks),t.tieFormat=o,t.matchUpType=s;const c=tm({drawDefinition:a,stage:Xa});t.drawSize=t.drawSize??c,!c&&t.drawSize&&MI({drawSize:t.drawSize,drawDefinition:a,stageSequence:n,stage:Xa});const u=xc({drawDefinition:a}).drawMatchUps.map(ba),d=HS(t);if(d.error)return wr({result:d,stack:i});const{structures:p,links:l,qualifyingResult:m}=d;a.structures=p,a.links=l;const f=Math.max(t.qualifiersCount??0,m?.qualifiersCount||0);if(m?.qualifyingDrawPositionsCount){if(!tm({stage:Qa,drawDefinition:a})){const t=MI({drawSize:m.qualifyingDrawPositionsCount,stage:Qa,drawDefinition:a});if(t.error)return t}}if(f){const t=AI({qualifiersCount:f,drawDefinition:a,stage:Xa});if(t.error)return t}const h=t.drawSize??c;Object.assign(t,vr({drawSize:h,matchUpType:s,tieFormat:o}));const{matchUps:g,matchUpsMap:I}=Jp({drawDefinition:a});o&&g?.forEach((t=>{if(!u.includes(t.matchUpId)){const{tieMatchUps:e}=hh({tieFormat:o,isMock:r});Object.assign(t,{tieMatchUps:e,matchUpType:s})}}));const{inContextDrawMatchUps:U}=Qp({drawDefinition:a,matchUpsMap:I});return Ls({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:a}),{inContextDrawMatchUps:U,drawDefinition:a,matchUpsMap:I,...E,structures:p,matchUps:g,links:l}}function YS({tournamentRecord:t,categoryName:e,categoryType:n}){if(!t)return{error:_};const{appliedPolicies:r}=Dc({tournamentRecord:t}),i=r?.[Ci];return(i?.allowedDrawTypes||[]).filter((({categoryNames:t,categoryTypes:r})=>!e&&!r||e&&t?.includes(e)||n&&r?.includes(n)))}function KS({consideredEntries:t,policyDefinitions:e,tournamentRecord:n,appliedPolicies:r,participantMap:i,enforceGender:a,participants:o,event:s}){if(o&&i||!n||({participants:o,participantMap:i}=Zl({tournamentRecord:n})),!o)return{error:Me};if(!Array.isArray(o))return{error:Nn};if(!s)return{error:Tt};const c=e?.[wi]??r?.[wi]??sm[wi],u=!1!==(a??c?.participants?.enforceGender),{eventType:d,gender:p}=s,l=d===rd,f=d===ad&&dc||l&&uc||sc,h=Object.assign({},...(t??s.entries??[]).map((t=>({[t.participantId]:t.entryStatus})))),g=Object.keys(h),I=o.filter((t=>g.includes(t.participantId))).filter((t=>{const e=h[t.participantId],n=d&&[rd,ad].includes(d)&&t.participantType===sc&&(_l(e)||e===nu),r=t.participantType!==f&&!n,a=!r&&l&&m(t?.individualParticipantIds?.map((t=>i?.[t]?.participant?.person?.sex)).filter(Boolean)??[]),o=!p||!a?.length||Gp===p||[qp,Hp].includes(p)&&a[0]===p||$p===p&&(1==a.length&&1===t.individualParticipantIds?.length||2===a.length),s=t?.person?.sex,c=!t?.person||!p||[Gp,$p].includes(p)||[qp,Hp].includes(p)&&s===p;return r||!(!u||o&&c)}));if(I.length){const t=I.map((t=>t.participantId));return{error:Nt,invalidParticipantIds:t}}return{...E,valid:!0}}const JS=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});function ZS(t){const e="prepareStage";let{seedsCount:n}=t;const r=t.preparedStructureIds||[],{provisionalPositioning:i,inContextDrawMatchUps:a,tournamentRecord:o,appliedPolicies:s,qualifyingOnly:c,drawDefinition:u,seedingProfile:d,matchUpsMap:l,automated:m,placeByes:f,drawType:h,drawSize:g,entries:I,event:U,enforcePolicyLimits:S=!0,seedAssignmentProfile:y,seedByRanking:v=!0,seededParticipants:T,assignSeedsCount:P,seedingScaleName:D,stageSequence:b=1,roundTarget:N,stage:R}=t,M=U?.eventType,A=I.filter((t=>{const e=Mr({name:ra,element:t})?.extension?.value;return(!t.entryStage||t.entryStage===R)&&(!b||!t.entryStageSequence||t.entryStageSequence===b)&&(!N||!e||e===N)&&au.includes(t.entryStatus)}));T&&(n=T.length),n>g&&(n=g),n>A.length&&(n=A.length);const{structures:C}=es({drawDefinition:u,stageSequence:b,roundTarget:N,stage:R}),O=(C?.length||0)>1,F=C?.find((({structureId:t})=>!r.includes(t)));if(!F)return wr({result:{error:Ut},stack:e});const k=F?.structureId,x=F?gf({provisionalPositioning:i,appliedPolicies:s,drawDefinition:u,seedingProfile:d,structure:F}):void 0,{seedLimit:_}=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=ts({drawDefinition:o,structureId:c});if(d.error)return d;const l=d.structure;if(!l)return{error:Ut};const{positionAssignments:m}=is({structure:l}),f=m?.length||0;if(u>f)return{error:ct};const h=l.structures?.length,g=p(s?.groupSeedingThreshold)&&s?.groupSeedingThreshold,I=ff({roundRobinGroupsCount:h,drawSize:f})?.seedGroups,{seedsCount:U}=BU({policyDefinitions:a,requireParticipantCount:t,drawSizeProgression:n,participantsCount:r,drawSize:f});return U&&a?.[Ai]&&u>U&&e&&(u=U),l.seedLimit=u,l.seedAssignments=w(1,u+1).map((t=>{const e=I?.find((e=>e.includes(t))),n=e&&Math.min(...e);return{participantId:void 0,seedNumber:t,seedValue:g&&t>=g?n:t}})),Ls({drawDefinition:o,structureIds:[c]}),{...E,seedLimit:u}}({participantsCount:A.length,enforcePolicyLimits:S,appliedPolicies:s,drawDefinition:u,seedingProfile:d,structureId:k,seedsCount:n});_&&_<n&&(n=_);const L=I.map(Da);if(T)T.filter((({participantId:t})=>L.includes(t))).filter((t=>!t.seedNumber||t.seedNumber<=T.length)).sort(((t,e)=>t.seedNumber<e.seedNumber?-1:t.seedNumber<e.seedNumber?1:0)).forEach((t=>{const{participantId:e,seedNumber:n,seedValue:r}=t;vf({provisionalPositioning:i,tournamentRecord:o,drawDefinition:u,seedingProfile:d,participantId:e,seedBlockInfo:x,structureId:k,seedNumber:n,seedValue:r,event:U})}));else if(U||D){const{categoryName:t,ageCategoryCode:e}=U?.category||{},r={scaleType:Fr,scaleName:D||t||e||U.eventId,eventType:M};let{scaledEntries:a}=qU({scaleAttributes:r,tournamentRecord:o,stageSequence:b,entries:I,stage:R});if(!a?.length&&v){const n={scaleName:t||e,scaleType:Er,eventType:M};({scaledEntries:a}=qU({scaleAttributes:n,tournamentRecord:o,stageSequence:b,entries:I,stage:R}))}const s=a?.length??0;s<n&&(n=s),a?.filter((({participantId:t})=>L.includes(t))).slice(0,P||n).forEach(((t,e)=>{const n=e+1,{participantId:r,scaleValue:a}=t;vf({provisionalPositioning:i,tournamentRecord:o,drawDefinition:u,seedingProfile:d,participantId:r,structureId:k,seedNumber:n,seedValue:y?.[n]||a||n,event:U})}))}let B,V,j=[];if(!1!==m&&h!==wo&&(!c||R===Qa)){const t="object"==typeof m&&m.seedsOnly,n=Qh({inContextDrawMatchUps:a,multipleStructures:O,tournamentRecord:o,appliedPolicies:s,drawDefinition:u,seedingProfile:d,structureId:k,matchUpsMap:l,placeByes:f,seedLimit:_,seedsOnly:t,drawSize:g,drawType:h,event:U});if(n.conflicts&&(j=n?.conflicts),B=n?.positionAssignments,V=n?.positioningReport,n.error)return wr({result:n,stack:e})}return{positionAssignments:B,positioningReport:V,stageEntries:A,structureId:k,seedsCount:n,conflicts:j}}const XS={[Ai]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[qo]:{positioning:po},[Go]:{positioning:po}},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 QS(t){const e="generateDrawDefinition",{considerEventEntries:r=!0,ignoreAllowedDrawTypes:i,voluntaryConsolation:a,hydrateCollections:o,ignoreStageSpace:s,tournamentRecord:c,qualifyingOnly:d,tieFormatName:l,drawEntries:m,placeByes:f,event:h}=t,g=Dc({tournamentRecord:c,event:h}).appliedPolicies??{},I=gi(t.policyDefinitions??{},!1,!0),U=(t.drawTypeCoercion??I?.[Ci]?.drawTypeCoercion??g?.[Ci]?.drawTypeCoercion??!0)&&2===t.drawSize&&bo||t.drawType||bo,S=I?.[Ai]??g?.[Ai],y=t.seedingProfile??S?.seedingProfile?.drawTypes?.[U]??S?.seedingProfile;t.seedingProfile&&(I[Ai]||(I[Ai]={...XS[Ai]}),I[Ai].seedingProfile=y);const{participants:v,participantMap:T}=Zl({withIndividualParticipants:!0,convertExtensions:!0,internalUse:!0,tournamentRecord:c}),P=t.enforceGender??I?.[wi]?.participants?.enforceGender??g?.[wi]?.participants?.enforceGender,D=!i&&c&&YS({tournamentRecord:c,categoryType:h?.category?.categoryType,categoryName:h?.category?.categoryName});if(D?.length&&!D.includes(U))return wr({result:{error:et},stack:e});const b=h?.entries?.filter((t=>t.entryStatus&&[...ou,Zc].includes(t.entryStatus)))??[],N=(d&&[]||m||(r?b:[])).filter((({entryStage:t})=>!t||t===Xa)),R=h&&v&&KS({consideredEntries:N,appliedPolicies:g,participantMap:T,enforceGender:P,participants:v,event:h});if(R?.error)return wr({result:R,stack:e});const M=!t.drawSize&&N.length&&![wo,No,To,Go,qo].includes(U)&&u(N.length)||t.drawSize&&p(t.drawSize)&&n(t.drawSize)||!1;if(isNaN(M)&&U!==wo)return wr({result:{error:it},stack:e});let A="number"!=typeof t.seedsCount?n(t.seedsCount??0):t.seedsCount??0;const C=h?.eventType,O=t.matchUpType??C,F=t.drawId?h?.drawDefinitions?.find((e=>e.drawId===t.drawId)):void 0;let{tieFormat:k,matchUpFormat:x}=t;if(O===Qs&&C===Qs){const t=F?.structures?.find((({stage:t})=>t===Xa))?.tieFormat;k=k||t||l&&h?.tieFormat?.tieFormatName===l&&h.tieFormat||l&&ES({namedFormat:l,hydrateCollections:o,event:h})||h?.tieFormat||ES({event:h,hydrateCollections:o}),x=void 0}else x||(k=void 0,h?.matchUpFormat||(x=lg));if(k){const t=fh({gender:h?.gender,enforceGender:P,tieFormat:k});if(t.error)return wr({result:t,stack:e})}if(t.drawId&&"string"!=typeof t.drawId)return wr({result:{error:Nn},stack:e});F&&U!==F.drawType&&(F.drawType=U);let _=F??function(t){const{drawId:e=Md(),processCodes:n,matchUpType:r,drawType:i}=t??{},a=JS();return Object.assign(a,{processCodes:n,matchUpType:r,drawType:i,drawId:e})}({drawType:U,drawId:t.drawId,processCodes:t.processCodes});if(x||k){if(!(x&&h?.matchUpFormat===x||h?.tieFormat&&k&&JSON.stringify(h.tieFormat)===JSON.stringify(k))){if(k){const t=function({tieFormat:t}){const e=fh({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(const e of t.collectionDefinitions)e.collectionId||(e.collectionId=Md());return{tieFormat:t}}({tieFormat:k});if(t.error)return wr({result:t,stack:e});_.tieFormat=t.tieFormat??k}else if(x){const t=GI({tournamentRecord:c,drawDefinition:_,matchUpFormat:x,event:h});if(t.error)return{error:t.error,info:"matchUpFormat or tieFormat error"}}O&&(_.matchUpType=O)}}const L={[Ri]:g[Ri]};if(I){if("object"!=typeof I)return wr({info:"policyDefinitions must be an object",result:{error:Nn},stack:e});for(const t of Object.keys(I))JSON.stringify(g?.[t])!==JSON.stringify(I[t])&&(L[t]=I[t]);Object.keys(L).length&&(uU({policyDefinitions:L,drawDefinition:_}),Object.assign(g,L))}else L.avoidance&&uU({drawDefinition:_,policyDefinitions:L});g[Ai]||I[Ai]||(uU({policyDefinitions:XS,drawDefinition:_}),Object.assign(g,XS));let B=F?.structures?.find((t=>t.stage===Xa&&1===t.stageSequence))?.structureId;const V=m??b,j=[];let G,q=[];const $=t.qualifyingPlaceholder&&!t.qualifyingProfiles?.length&&!F,W=F?F.structures?.filter((t=>t.stage===Qa)):[],H=1===W?.length&&!W[0].matchUps?.length&&W[0].structureId;if(H){const e=t.qualifyingProfiles,n=e?.length?jS({idPrefix:t.idPrefix,isMock:t.isMock,uuids:t.uuids,qualifyingProfiles:e,appliedPolicies:g}):void 0;if(n?.error)return n;_.structures=_.structures?.filter((({structureId:t})=>t!==H)),_.links=_.links?.filter((({source:t})=>t.structureId!==H));const{qualifiersCount:r,qualifyingDrawPositionsCount:i,qualifyingDetails:a}=n??{};i&&(n?.structures&&_.structures?.push(...n.structures),n?.links&&_.links?.push(...n.links));const o=_.structures?.find((({stage:t,stageSequence:e})=>t===Xa&&1===e)),{qualifiersCount:s}=Ql({stageSequence:1,drawDefinition:_,structureId:B,stage:Xa});let c=AI({qualifiersCount:Math.max(r??0,s??0),drawDefinition:_,stage:Xa});if(c.error)return c;if(c=MI({drawSize:i,stage:Qa,drawDefinition:_}),c.error)return c;for(const t of(m??[]).filter((({entryStage:t})=>t===Qa))){rm({...t,entryStage:t.entryStage??Xa,drawDefinition:_})}for(const t of a||[]){const{finalQualifyingRoundNumber:e,finalQualifyingStructureId:n,roundTarget:r,finishingPositions:i,linkType:a}=t,s=o&&_I({targetStructureId:o.structureId,sourceStructureId:n,sourceRoundNumber:e,finishingPositions:i,targetEntryRound:r,linkType:a})?.link;if(s?.error)return s;s&&(_.links||(_.links=[]),_.links.push(s))}G={drawDefinition:_}}else{if(G=zS({...t,modifyOriginal:!1,tournamentRecord:c,appliedPolicies:g,drawDefinition:_,matchUpFormat:x,matchUpType:O,tieFormat:k,drawSize:M}),G.error)return wr({result:G,stack:e});_=G.drawDefinition;for(const t of V){if(m&&t.entryStage&&t.entryStage!==Xa)continue;const n=rm({...t,ignoreStageSpace:s??U===wo,entryStage:t.entryStage??Xa,drawDefinition:_,drawType:U});if(m&&n.error)return wr({result:n,stack:e})}U===Ao&&(A=0);const n=ZS({...G,...t,qualifyingOnly:!M||d,appliedPolicies:g,drawDefinition:_,seedingProfile:y,participants:v,stage:Xa,seedsCount:A,placeByes:f,drawSize:M,entries:V});if(n.error&&!n.conflicts)return n;if(n.positioningReport?.length&&j.push({[Xa]:n.positioningReport}),B=n.structureId,n.conflicts&&(q=n.conflicts),U===wo&&t.roundsCount){const e=h?.entries?.filter((({entryStage:t,entryStatus:e})=>(!t||t===Xa)&&e&&ou.includes(e))),n=e?.map(Ua("participantId")),r=e?Math.floor(e.length/2):0;w(1,t.roundsCount+1).forEach((()=>{if(t.automated){const{restrictEntryStatus:e,generateMatchUps:r,structureId:i,matchUpIds:a,scaleName:o}=t.drawMatic??{},s=xU({eventType:t.drawMatic?.eventType??O,generateMatchUps:r??!0,restrictEntryStatus:e,tournamentRecord:c,participantIds:n,drawDefinition:_,structureId:i,matchUpIds:a,scaleName:o}).matchUps;fU({tournamentRecord:c,drawDefinition:_,structureId:i,matchUps:s})}else{const{matchUps:t}=yU({newRound:!0,drawDefinition:_,matchUpsCount:r});fU({tournamentRecord:c,drawDefinition:_,structureId:B,matchUps:t})}}))}}const z=[];if(t.qualifyingProfiles){const n=(t,e)=>t.stageSequence-e.stageSequence,r=(t,e)=>t.roundTarget-e.roundTarget,i=[];let a=1;t.qualifyingProfiles.sort(r);for(const r of t.qualifyingProfiles){if(!Array.isArray(r.structureProfiles))return wr({info:Pf("structureProfiles"),result:{error:ae},stack:e});a=r.roundTarget||a;const o=r.structureProfiles?.sort(n)||[];let s=1;for(const e of o){const{qualifyingRoundNumber:n,qualifyingPositions:r,seededParticipants:o,seedingScaleName:c,seedsCount:u=0,seedByRanking:p,placeByes:l,drawSize:m}=e,f=ZS({...G,...t,seedingProfile:e.seedingProfile??y,stageSequence:s,qualifyingRoundNumber:n,preparedStructureIds:i,qualifyingPositions:r,seededParticipants:o,stage:Qa,seedingScaleName:c,appliedPolicies:g,drawDefinition:_,qualifyingOnly:d,seedByRanking:p,participants:v,roundTarget:a,seedsCount:u,placeByes:l,drawSize:m,entries:V});if(f.error)return f;f.structureId&&i.push(f.structureId),s+=1,f.conflicts?.length&&z.push(...f.conflicts),f.positioningReport?.length&&j.push({[Qa]:f.positioningReport})}a+=1}}else if(B&&$){const t=Tm({structureName:wm(Qa),stage:Qa}),{link:e}=_I({sourceStructureId:t.structureId,targetStructureId:B,sourceRoundNumber:0,linkType:Uo});_.structures||(_.structures=[]),_.structures.push(t),_.links||(_.links=[]),_.links.push(e)}return _.drawName=t.drawName??(U&&wm(U)),"object"==typeof a&&M>=4&&Pm({...a,drawDefinition:_,matchUpType:O}),{existingDrawDefinition:!!F,qualifyingConflicts:z,positioningReports:j,drawDefinition:_,structureId:B,...E,conflicts:q}}const ty="splitWaterfall",ey="splitShuttle",ny={SPLIT_LEVEL_BASED:"splitLevelBased",SPLIT_WATERFALL:ty,SPLIT_SHUTTLE:ey};const ry="ASC",iy="DESC",ay={ASC:"ASC",ASCENDING:ry,DESC:"DESC",DESCENDING:iy};function oy(t){let{tieFormat:e}=t;const{useDefaultEventRanking:n,tournamentRecord:r,drawDefinition:i,scaleAccessor:a,singlesOnly:o,attach:c,event:u}=t;if(u?.eventType!==ad)return{error:wt};if(!r)return{error:_};if(!e&&!i)return{error:q};if(e=e??$d({drawDefinition:i,event:u})?.tieFormat,fh({tieFormat:e}).error)return{error:Lt};if("object"!=typeof a&&!n)return{error:Nn,context:{scaleAccessor:a}};const d={},p=(i?.entries??u?.entries??[]).filter((t=>t?.entryStatus===Hc)).map(Da),{participants:l=[]}=Zl({withIndividualParticipants:!0,withScaleValues:!0,tournamentRecord:r}),m=l.filter((({participantId:t})=>p.includes(t))),f=u?.category?.categoryName??u?.category?.ageCategoryCode,{scaleName:h=f,scaleType:g=Er,sortOrder:I,accessor:U}=a||{},S=g===Er?"rankings":"ratings";const y=(t,e)=>{let r=t[S]?.[e];if(!r&&n&&(r=t[S]?.[Ys]),Array.isArray(r)){const t=r.find((t=>t.scaleName===h))?.scaleValue;if(s(t))return t;if(U&&"object"==typeof t)return t[U]}return 0},v=(t,e,n)=>{const r=I===iy?t:e;return y(I===iy?e:t,n)-y(r,n)},T=(t,e)=>v(t,e,Ys),P=(t,e)=>v(t,e,Js),D=[],b=e?.collectionDefinitions??[];for(const t of m){const e=t.individualParticipants?.sort(T)??[],n=o?e:t.individualParticipants?.sort(P)??[],r={};for(const t of b){const i=[],{collectionId:a,matchUpCount:o,matchUpType:s,gender:c}=t,u=s===Ys;w(0,o).forEach((t=>{const o=u?e:n??[],s=t+1,d=[];w(0,u?1:2).forEach((t=>{const e=o?.find((e=>{const n=c&&([qp,Hp].includes(c)&&c||c===$p&&[qp,Hp][t]);return!(n&&n!==e.person?.sex||i.includes(e.participantId))}))?.participantId;e&&(d.push(e),i.push(e),r[e]||(r[e]=[]),r[e].push({collectionPosition:s,collectionId:a}))})),u||D.push(d)}))}const i=Object.keys(r).map((t=>({collectionAssignments:r[t],participantId:t})));d[t.participantId]=i}const N=[];for(const t of D){const{participant:e}=Vc({tournamentParticipants:l,participantIds:t});if(!e){const e={individualParticipantIds:t,participantRole:um,participantType:uc};N.push(e)}}if(c){for(;N.length;)Bf({participant:N.pop(),tournamentRecord:r});Nr({element:i,extension:{name:Zi,value:d}})}return{...E,lineUps:d,participantsToAdd:N}}function sy({court:t,date:e}){const n=e&&t.dateAvailability.find((t=>fi(t.date,e))),r=t.dateAvailability.find((t=>!t.date));return n||r}function cy({includeBookingTypes:t=[],courtDate:e}){const n=[];let r=ui(e.startTime);(e.bookings||[]).filter((e=>!e.bookingType||!t.includes(e.bookingType))).sort(((t,e)=>ei(t.startTime).localeCompare(ei(e.startTime)))).forEach((t=>{const e={startTime:ni(r.toISOString()),endTime:t.startTime};ui(t.startTime)>r&&n.push(e),ui(t.endTime)>r&&(r=ui(t.endTime))}));const i={startTime:ni(r.toISOString()),endTime:e.endTime};return ui(e.endTime)>r&&n.push(i),n}function uy(t){const{averageMatchUpMinutes:e,includeBookingTypes:n,periodStart:r,date:i}=t,a=t.courts,o=ui(r),s=li(o,e),{enoughTime:c}=function({averageMatchUpMinutes:t,includeBookingTypes:e,periodStartTime:n,periodEndTime:r}){function i(e){const i=ui(e.startTime),a=ui(e.endTime);return!(i>n)&&(!(a<r)&&di(n,a)>=t)}return{enoughTime:t=>!!cy({includeBookingTypes:e,courtDate:t}).filter(i).length}}({averageMatchUpMinutes:e,includeBookingTypes:n,periodStartTime:o,periodEndTime:s});return{availableToScheduleCount:(a?.filter((t=>{if(!Array.isArray(t.dateAvailability))return!1;const e=sy({date:i,court:t});return!(!e||!c(e))}))||[]).length}}function dy(t){const{startTime:e="8:00",endTime:n="20:30",count:r=10,date:i}=t??{};return w(0,r).map((()=>({dateAvailability:[{date:i,startTime:e,endTime:n}]})))}function py(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:Nn,courts:a};if(!Array.isArray(o))return{error:ce};if(!Wr(i))return{error:pe};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=sy({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]},...gi(u,!1,!0),...o].filter(Boolean),startTime:d,endTime:p,date:l}}}));c.sort(((t,e)=>ti(t.startTime)-ti(e.startTime)));const d=[];for(const t of c){const{startTime:e,endTime:n,averageMinutes:i,recoveryMinutes:a,matchUpId:o}=t,s=ti(e),c=ti(n),p=u.map((t=>{const e=cy({courtDate:t.dateAvailability});return{courtName:t.courtName,courtId:t.courtId,timeSlots:e}})).flat().reduce(((t,{courtId:e,courtName:n,timeSlots:i})=>{let a;return i.find((({startTime:e,endTime:n})=>{a=ti(e)-s;const i=s>=ti(e);return c<=ti(n)&&0!==t.startDifference&&((0===a||a+r>=0)&&(void 0===t.startDifference||a<t.startDifference)||i)}))?{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 ly({averageMatchUpMinutes:t,periodLength:e=30,recoveryMinutes:n}){const r=(t||90)+(n||0);return e>r?r:e||30}function my({scheduleDate:t,startTime:e,endTime:n,courts:r}){const i=(e?"startTime":n&&"endTime")||void 0;return r.reduce(((r,a)=>{const o=sy({date:t,court:a}),s=i&&(o?.[i]||a[i]);return s&&(!r||e&&ti(s)<ti(r)||n&&ti(s)>ti(r))?s:r}),void 0)}function fy(t){let{date:e=Hr(),startTime:r="08:00",endTime:i="19:00",periodLength:a,courts:o}=t;const{calculateStartTimeFromCourts:s=!0,remainingScheduleTimes:c,averageMatchUpMinutes:u,clearScheduleDates:d,courtsCount:p,bookings:l}=t;a=a||ly({averageMatchUpMinutes:u}),e=ri(e),r=ni(r),i=ni(i);let m=0,f=0,h=0,g=0,I=0;!o&&p&&(o=dy({startTime:r,endTime:i,count:p,date:e}));const{virtualCourts:U}=py({remainingScheduleTimes:c,clearScheduleDates:d,scheduleDate:e,periodLength:a,bookings:l,courts:o}),{firstTimeSlotStartTime:S}=function({averageMinutes:t,startTime:e,endTime:n,courts:r,date:i}){let a;if(e=e||my({courts:r,scheduleDate:i,startTime:!0}),n=n||my({courts:r,scheduleDate:i,endTime:!0}),e&&n){const o=ui(e),s=ui(n);for(const e of r||[])Array.isArray(e.dateAvailability)&&cy({courtDate:sy({court:e,date:i})}).forEach((e=>{const n=ui(e.startTime),r=ui(e.endTime);if(n>s||n<o)return!1;if(r<o)return!1;if(di(n,r)>=t){const t=ni(n.toISOString());(!a||t<a)&&(a=t)}}))}return{firstTimeSlotStartTime:a}}({averageMinutes:u,courts:U,startTime:r,endTime:i,date:e});s&&S&&(r=S||r);const y=ti(r),v=ti(i)-y,T=w(0,Math.floor(v/a)+1).map((t=>{const r=function(t){let e=Math.floor(t/60);const n=t-60*e;return e>23&&(e%=24),[mi(e),mi(n)].join(":")}(y+t*a),{availableToScheduleCount:i}=uy({courts:U||[],averageMatchUpMinutes:u,periodStart:r,date:e}),o=i>f?i-f:0;I+=t?i:0;const s=t?I/t:i,c=t?a*s/u*(t-1)+s:s,d=i?f&&c-m||o:0;m=c,f=i,h+=d;const p=n(h)-g;return g+=p,{periodStart:r,add:p,availableToScheduleCount:i,newCourts:o,totalMatchUps:g}}));return{scheduleTimes:T.reduce(((t,e)=>{const n=w(0,e.add).map((()=>({scheduleTime:e.periodStart})));return t.concat(...n)}),[]).flat(),timingProfile:T,totalMatchUps:g}}const hy={garman:{getCourtsAvailableAtPeriodStart:uy,generateTimeSlots:cy,getScheduleTimes:fy,courtGenerator:dy},generateAdHocMatchUps:yU,generateAndPopulatePlayoffStructures:XI,generateDrawDefinition:QS,generateDrawMaticRound:kU,generateDrawStructuresAndLinks:HS,generateDrawTypeAndModifyDrawDefinition:zS,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:Tt};const h=l.entries??[],{flightProfile:g}=Bd({event:l});if(g&&n&&!o)return{error:xn};const I=t.scaledEntries??qU({tournamentRecord:r,scaleAttributes:i,scaleSortMethod:a,sortDescending:s,event:l,stage:m}).scaledEntries,U=I.map(Da),S=f(h.filter((({participantId:t})=>!U.includes(t))).filter((t=>(!m||!t.entryStage||t.entryStage===m)&&(!t.entryStatus||au.includes(t.entryStatus))))),y=I.concat(...S),v=y.length;let T=N(y,Math.ceil(v/u));d===ty?T=A(y,u):d===ey&&(T=A(y,u,!0));const P={scaleAttributes:i,splitMethod:d,flights:w(0,u).map((t=>{const n=t+1;return{flightNumber:n,drawId:p?.pop()??Md(),drawEntries:(r=T[t],(r||[]).map((({participantId:t,scaleValue:e})=>{const n=h.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}))};if(n){const t=IU({flightProfile:P,deleteExisting:o,event:l});return{splitEntries:Qn()&&T||void 0,...t}}return{flightProfile:P,...E}},generateLineUps:oy,generateQualifyingStructure:jI,generateSeedingScaleItems:jU,generateVoluntaryConsolation:function(t){const{drawType:e=bo,attachConsolation:n=!0,applyPositioning:r=!0,tournamentRecord:i,staggeredEntry:a,automated:o,placeByes:s,isMock:c,event:d}=t;let p=t?.drawDefinition;if(!p)return{error:j};const l=eo,m=pu({stageSequence:1,drawDefinition:p,stage:l}),f=[Go,No,qo].includes(e)?m.length:u(m.length);if(!a&&e===To&&m.length<2||e===Go&&m.length<3)return{error:nt};let{tieFormat:h,matchUpType:g}=t;if(h){const t=fh({tieFormat:h});if(t.error)return t}h=Yf(h??$d({drawDefinition:p})?.tieFormat),g=g??p.matchUpType??Ks;const{structures:I}=es({stageSequence:1,drawDefinition:p,stage:l});if(I.length>1)return{error:Et};if(I?.[0]?.matchUps?.length)return{error:Vn};const U=I?.[0]?.structureId;Object.assign(t,vr({structureName:t.structureName??wm(eo),structureId:U,matchUpType:g,tieFormat:h,drawSize:f,stage:l}));const S=WS(t);if(S.error)return S;const y=S.generators[e];if(!y)return{error:J};const v=y?.();if(v.error)return v;const{structures:w,links:T}=v,P=w.map((t=>Yp({structure:t}).matchUps)).flat();h&&P.forEach((t=>{const{tieMatchUps:e}=hh({tieFormat:h,isMock:c});Object.assign(t,{tieMatchUps:e,matchUpType:g})})),r&&n||(p=gi(p,!1,!0)),p.links||(p.links=[]),T.length&&p.links.push(...T);const D=w.map((({structureId:t})=>t));p.structures||(p.structures=[]);const b=p.structures.map((({structureId:t})=>t));p.structures=p.structures.map((t=>D.includes(t.structureId)?w.find((({structureId:e})=>e===t.structureId)):t));const N=w.filter((({structureId:t})=>!b.includes(t)));return N.length&&p.structures.push(...N),o&&Qh({seedingProfile:t.seedingProfile,applyPositioning:r,tournamentRecord:i,drawDefinition:p,structureId:U,placeByes:s,drawSize:f,event:d}),n&&Ls({drawDefinition:p}),{links:T,structures:w,...E}}};var gy=[{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"}],Iy=["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 Uy({count:t=1,participantsCount:e=32}={}){const n=f(Iy),r=n.slice(0,t);return{cities:w(0,e).map((e=>e<Math.min(t,n.length)?r[e]:v(r)))}}function Sy({count:t=1,participantsCount:e=32}={}){const n=f(gy),r=n.slice(0,t).map((t=>Object.keys(t))).flat();return{states:w(0,e).map((e=>e<Math.min(t,n.length)?r[e]:v(r)))}}function yy({count:t=1,participantsCount:e=32}={}){const n=w(0,t).map((()=>w(0,5).map((()=>d(0,9))).join("")));return{postalCodes:w(0,e).map((e=>e<t?n[e]:v(n)))}}var vy={lastNames:["Abbey","Assange","Ahern","Ampleforth","Atreides","Austen","Bach","Banks","Barrington","Batty","Bauers","Beals","Beer","Bennett","Berry","Bonaparte","Brockovich","Bukowski","Cassidy","Catton","Calvino","Carson","Chip","Constant","Crane","Crowne","Cummings","Curie","Dallas","Diamond","Deckard","Drazic","Dunbar","Earhart","Eisenstein","Eldritch","Elliot","Escher","Eyre","Faulkner","Fukuoka","Godel","Goldstein","Greer","Hedges","Herbert","Holmgren","Humperdinck","Huxley","Illich","Jeffers","Jensen","Jevons","Johnson","Johnstone","Jovovich","Kingsnorth","Langer","Fernwright","Fuller","Le Guin","Lem","Lovelace","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","Wormwood"],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","Bill","Bruce","Charles","Chris","Darwin","David","Derrick","Edward","Emmanuel","Ernst","Estlin","Fezzik","Filby","Frank","Frito","George","Glen","Helmholtz","Inigo","Italo","Ivan","James","Jared","Joe","Johann","Julian","John Michael","Jonathan","Korben","Kirkpatrick","Kurt","Lief","Malachi","Mark","Masanobu","Maurits","Michael","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 wy(t){const{count:e=100,sex:n}=t||{};if(!e||n&&![qp,Hp].includes(n))return{personData:[],error:Nn};const r=Math.ceil(1.3*e),{lastNames:i,firstFemale:a,firstMale:o}=vy,s=el.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=w(0,c).flatMap((()=>{const t=gi(i,!1,!0);return w(0,i.length).map((()=>y(t)))})),l=w(0,u).flatMap((()=>{const t=gi(a,!1,!0);return w(0,a.length).map((()=>y(t)))})),m=w(0,d).flatMap((()=>{const t=gi(o,!1,!0);return w(0,o.length).map((()=>y(t)))})),f={};for(let t=0;t<r;t++){const t=p.pop(),e=n||v([qp,Hp]),r=e===qp?m.pop():l.pop(),i=v(s);f[`${r}${t}`]={nationalityCode:i,sex:e,firstName:r,lastName:t}}return{personData:Object.values(f).slice(0,e)}}function Ty(t){let e=t?.count||1;const{personExtensions:r,consideredDate:i,isMock:a=!0,gendersCount:o,personData:s,category:c,sex:u}=t||{};if(isNaN(e))return{error:Nn};const d=o?.[qp]||u===qp&&e||0,p=o?.[Hp]||u===Hp&&e||0;e=Math.max(e,d+p);const l=e-(d+p),m=[...d&&wy({count:d,sex:qp}).personData||[],...p&&wy({count:p,sex:Hp}).personData||[],...l&&wy({count:l}).personData||[]];let h=m.filter((t=>!u||d&&p||t.sex===u));const g=[];if(Array.isArray(s)){const t=s.filter((t=>"string"==typeof t.firstName&&("string"==typeof t.lastName&&(!(t.sex&&![qp,Hp].includes(t.sex))&&(!(t.nationalityCode&&("string"!=typeof t.nationalityCode||t.nationalityCode.length>3||!el.find((({iso:e,ioc:n})=>[e,n].includes(t.nationalityCode)))))&&(t.nationalityCode&&g.push(t.nationalityCode),!0))))));if(!t.length)return{error:Nn};h=t}const I=s?h:f(h);if(I.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===qp?(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:[]});w(0,e-I.length).forEach((()=>{const e=u||v([qp,Hp]),o=v(a),s={firstName:v(e===qp?t:r),lastName:v(e===qp?n:i),sex:e,nationalityCode:o};I.push(s)}))}const{ageMinDate:U,ageMaxDate:S}=uh({consideredDate:i,category:c}),T=n(U?.slice(0,4)||0)||n(S?.slice(0,4)||0)-3,P=n(S?.slice(0,4)||0)||n(U?.slice(0,4)||0)+3,D=(U||S)&&[T,P],b=I.slice(0,e).map(((t,e)=>{const[n,i]=D||[],o=D&&y(w(n,i)),s=y(w(0,365)),c=o&&function(t,e,n){const r=new Date(t,0);return zr(new Date(r.setDate(e)),n)}(o,s);return Object.assign(vr({extensions:r||[{name:"regionCode",value:e+1}],birthDate:c,isMock:a}),t)}));return{persons:b.length&&b||I[0],nationalityCodes:g}}function Py(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 Dy=["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","Sparkle Soul Tribe","Stacked Deck","Cross Stringers","The Emergence","Total Demolition","Touch and Go","Upside Downers","Vertically Challenged","Visual Spectacle"];function by({nameRoot:t="TEAM",count:e=1}={}){const n=f(Dy).slice(0,e);return n.length<e&&w(0,e-n.length).forEach((e=>n.push(`${t} ${e+1}`))),{names:n}}const Ny=t=>{const{isSide1:e,lowValue:r,setTo:i,tiebreakAt:a,NoAD:o}=t;if(void 0===r)return!1;let s,c=n(r);c?.toString().length>2&&(c=parseInt(c.toString().slice(0,2))),a&&a<i&&c>a&&(c=a),s=o&&!a?c<i?i:i-1:c+1<i&&i||a&&a<i&&c===a&&i||!a&&c+2||i+1;return[e?c:s,e?s:c]},Ry=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 My({tiebreakTo:t=7,scoreString:e}){return e.split(" ").filter(Boolean).map(((e,n)=>function({set:e,setNumber:n}){const r=e?.startsWith("[")&&e.split("[")[1].split("]")[0].split("-").map((t=>parseInt(t))),i=e.includes("(")&&e.split("(")[0]||e.includes("[")&&e.split("[")[0]||e,a=!r&&i.split("-").map((t=>parseInt(t))),o=r?(r[0]>r[1]?1:r[0]<r[1]&&2)||void 0:(a[0]>a[1]?1:a[0]<a[1]&&2)||void 0,s=e.includes("(")?e.split("(")[1].split(")")[0]:void 0,c=(s&&Ry({lowValue:s,isSide1:2===o,tiebreakTo:t}))??[],[u,d]=a||[],[p,l]=r||c||[];return{side1Score:u,side2Score:d,side1TiebreakScore:p,side2TiebreakScore:l,winningSide:o,setNumber:n}}({set:e,setNumber:n+1})))}function Ay(t){const{matchUpFormat:e,matchUpStatus:n,winningSide:r,scoreString:i}=t;if(!i)return{outcome:{...Lg,winningSide:r,matchUpStatus:n}};if(r&&![1,2,void 0].includes(r))return{error:Nn,winningSide:r};const a=i&&My({scoreString:i}),o={},s=nU({sets:a,matchUpFormat:e}),c=nU({sets:a,reversed:!0,matchUpFormat:e});return 2===r?(o.scoreStringSide1=c,o.scoreStringSide2=s):(o.scoreStringSide1=s,o.scoreStringSide2=c),o.sets=My({scoreString:o.scoreStringSide1}),vr({outcome:{matchUpStatus:n,winningSide:r,score:o}})}function Ey({tournamentRecords:t,tournamentId:e}){if("object"!=typeof t||!Object.keys(t).length)return{error:x};let n;return Object.keys(t).filter((t=>!e||t===e)).forEach((e=>{const r=t[e],{matchUpDailyLimits:i}=function(t){const e=Lp(t,[{[up]:!0}]);if(e.error)return e;const{tournamentRecord:n}=t,{policy:r}=Uu({policyType:Ni,tournamentRecord:n}),{extension:i}=Mr({element:n,name:ia}),a=i?.value?.dailyLimits,o=r?.defaultDailyLimits;return{matchUpDailyLimits:a||o}}({tournamentRecord:r});n=i})),{matchUpDailyLimits:n}}function Cy({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 Oy({tournamentRecords:t,tournamentRecord:e,tournamentId:n,drawId:r}){if(!e&&!t)return{error:_};if(!r)return{error:at};if(!e&&t){if("string"!=typeof n&&!(n=Vg({tournamentRecords:t,drawId:r})))return{error:B};if(!(e=t[n]))return{error:_}}const i=e&&Vd({tournamentRecord:e,drawId:r});return i?.drawDefinition?{drawDefinition:i.drawDefinition,event:i.event,tournamentRecord:e,...E}:wr({result:{error:q},stack:"findDrawDefinition"})}function Fy({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:e,timeAfterRecovery:n,matchUp:r}){const{individualParticipantIds:i}=ec(r);n=n??r.schedule?.timeAfterRecovery;const a=e=>{t[e]||(t[e]=[]),t[e]=m(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 ky({individualParticipantProfiles:t,participantId:e}){t[e]||(t[e]={typeChangeTimeAfterRecovery:void 0,timeAfterRecovery:void 0,priorMatchUpType:void 0,potentialRecovery:{},potentialCounted:{},potentialBookings:{},bookings:[],counters:{}})}function xy({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,typeChangeRecoveryMinutes:r,averageMatchUpMinutes:i=0,matchUpNotBeforeTimes:a,matchUpDependencies:o,recoveryMinutes:s=0,scheduleTime:c,matchUp:u}){const d=ni(u?.schedule?.endTime),p=d?pi(d,n(s)):pi(c,n(i)+n(s)),l=r&&(d?pi(ni(d),r):pi(c,n(i)+n(r))),m=o?.[u.matchUpId]?.participantIds||[],f=(u.roundPosition&&t[u.matchUpId]||[]).flat();m.forEach((t=>{ky({individualParticipantProfiles:e,participantId:t});const n=e[t].priorMatchUpType!==u.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:u.drawId,recoveryValue:n,participantId:t,scheduleTime:c}):(e[t].timeAfterRecovery=n,e[t].bookings.push({scheduleTime:c,timeAfterRecovery:n}))})),Fy({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:a,timeAfterRecovery:p,matchUp:u})}function _y({matchUpScheduleTimes:t,matchUpDependencies:e,scheduleTime:n,matchUpId:r,details:i}){let a;const o=i.minutesMap?.[r]?.recoveryMinutes,s=i.minutesMap?.[r]?.averageMinutes,c=pi(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||ti(r)<ti(e.scheduleTime)?i:e}),{});e.scheduleTime&&ti(c)>ti(e.scheduleTime)&&(a=e)}return{scheduledDependent:a}}const Ly="DO_NOT_SCHEDULE",By={DO_NOT_SCHEDULE:Ly};function Vy({averageMatchUpMinutes:t=90,requestConflicts:e={},potentials:n=!0,personRequests:r,scheduleTime:i,scheduleDate:a,matchUp:o}){const s=function(t){const{sides:e,matchUpType:n}=t||{};return(e||[]).map((t=>n===Zs&&(t?.participant?.individualParticipants||[])||t?.participant&&[t.participant]||[])).flat()}(o).map((({person:t})=>t?.personId));if(n){const t=(o?.potentialParticipants||[]).flat().map((({person:t})=>t?.personId));s.push(...t)}const c=s.map((t=>r[t]?.map((e=>({...e,personId:t}))))).filter(Boolean).flat().filter((t=>t.requestType===Ly&&fi(a,t.date))),u=[],d=o?.matchUpId,p=ui(ni(i),ri(a)),l=ni(li(p,t).toISOString());for(const t of c){const{requestId:n,startTime:r,endTime:a}=t;(i>r&&i<a||l>r&&l<a)&&(u.push({matchUpId:d,request:t,scheduleTime:i}),e[n]?(e[n].scheduleTimes.includes(i)||e[n].scheduleTimes.push(i),e[n].matchUpIds.includes(d)||e[n].matchUpIds.push(d)):e[n]={request:t,scheduleTimes:[i],matchUpIds:[d]})}return{conflicts:u}}function jy({defaultRecoveryMinutes:t=0,defaultAverageMinutes:e,tournamentRecords:n,matchUpFormat:r,categoryName:i,categoryType:a,tournamentId:o,eventType:s,eventId:c}){if(!rh(r))return{error:kt};let u;return Object.keys(n).filter((t=>!o||t===o)).forEach((t=>{if(u)return;const e=n[t],o=c?Vd({tournamentRecord:e,eventId:c})?.event:void 0;return u=Sd({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 Gy({scheduleCompletedMatchUps:t,containedStructureIds:e,tournamentRecords:n,periodLength:i=30,matchUps:a,rounds:o}){if("object"!=typeof n)return{error:x};if(!Array.isArray(o))return{error:ae,info:Pf("rounds")};const s={},c=[];o.sort(((t,e)=>(t.sortOrder??0)-(e.sortOrder??0))),e=e??Object.assign({},...Object.values(n).map((t=>qs({tournamentRecord:t}).containedStructures))),a||({matchUps:a}=gl({nextMatchUps:!0,tournamentRecords:n}));let u=0;const d={},l={},m={},f=o.flatMap((o=>{const f=o.periodLength||i,h=[];e?.[o.structureId]?h.push(...e[o.structureId]):h.push(o.structureId);let g=a?rp({tournamentIds:[o.tournamentId],roundNumbers:[o.roundNumber],matchUpIds:o.matchUpIds,eventIds:[o.eventId],drawIds:[o.drawId],processContext:!0,structureIds:h,matchUps:a}).sort(Il):[];const{segmentNumber:I,segmentsCount:U}=o.roundSegment||{};if(p(I)&&r(g?.length)&&r(U)&&I>0&&I<=U&&U<g?.length&&!o.matchUpIds?.length){const t=g.length/U,e=t*(I-1);g=g.slice(e,e+t)}const S=n[o.tournamentId],y=Vd({drawId:o.drawId,tournamentRecord:S}).event,v=[];for(const t of g){const e=t.matchUpFormat;e&&(s[e]||(s[e]=[],s[e].push(t)),v.push(e))}for(const e of v){const{eventType:r,category:i}=y??{},{categoryName:a,ageCategoryCode:s}=i??{},{typeChangeRecoveryMinutes:p,recoveryMinutes:h,averageMinutes:I,error:U}=jy({categoryName:a??s,categoryType:i?.categoryType,tournamentId:o.tournamentId,eventId:o.eventId,tournamentRecords:n,matchUpFormat:e,eventType:r});if(U)return{error:U,round:o};const S=g.filter((e=>(t||!Ya.includes(e.matchUpStatus))&&e.matchUpStatus!==Ma)).map(ba);S.forEach((t=>{m[t]={typeChangeRecoveryMinutes:p,recoveryMinutes:h,averageMinutes:I},d[t]=h,l[t]=I})),c.push(...S),u=Math.max(I||0,u);return{roundPeriodLength:f,recoveryMinutes:h,averageMinutes:I,matchUpIds:S,hash:`${I}|${f}`}}}));return{scheduledRoundsDetails:f,greatestAverageMinutes:u,matchUpFormatCohorts:s,recoveryMinutesMap:d,averageMinutesMap:l,orderedMatchUpIds:c,minutesMap:m,...E}}function qy({scheduledRoundsDetails:t,greatestAverageMinutes:e,garmanSinglePass:n}){const r=[];let i,a,o,s,c=[];for(const u of t.filter(Boolean))s||(s=u.hash),(u.hash===s||n)&&(c=c.concat(u.matchUpIds)),u.hash===s||n||(s=u.hash,r.push({averageMinutes:o,recoveryMinutes:a,roundPeriodLength:i,matchUpIds:c}),c=u.matchUpIds),o=n?e:u.averageMinutes,a=u.recoveryMinutes,i=u.roundPeriodLength;return c.length&&r.push({matchUpIds:c,roundPeriodLength:i,recoveryMinutes:a,averageMinutes:o}),{groupedRounds:r}}function $y({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUp:n,value:r}){const{matchUpType:i}=n,{individualParticipantIds:a}=ec(n),o=(t[n.matchUpId]||[]).filter((t=>!b(t,a))).flat();[...a,...o].forEach((t=>{if(ky({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[ud]?a[ud]+=r:r>0&&(a[ud]=r),o.includes(t)&&(e[t].potentialCounted[n.drawId]=!0)}}))}const Wy=({scheduleAttributes:t=["scheduledDate","scheduledTime"],schedule:e={}})=>!!Object.keys(e).filter((e=>t.includes(e))).filter((t=>e[t])).length;function Hy({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===Ma;return n&&l.push({tournamentId:t.tournamentId,matchUpId:t.matchUpId}),!n&&Wy({schedule:e})&&(!u||t.schedule.scheduledDate===u)})),n=i.map(ba));const m=Array.isArray(c)?c.includes(u):c,f=m?[]:p.filter((({matchUpId:t})=>n.includes(t)));for(const n of f){$y({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;xy({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 zy({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:e,dateScheduledMatchUpIds:n,matchUpNotBeforeTimes:r,matchUpScheduleTimes:i,orderedMatchUpIds:a,clearDate:o,matchUps:s}){const c=Object.keys(i),u=a.map((t=>s.find((e=>e.matchUpId===t)))).filter(Boolean).filter((t=>{const r=!o&&(n.includes(t.matchUpId)||c.includes(t.matchUpId)),i=[Ma,Oa,Ea,Na,Ba,Ga,ka,Fa].includes(t?.matchUpStatus);return e||!r&&!t.winningSide&&!i})),{matchUpMap:d}=u.reduce(((e,n)=>{const{drawId:i,tournamentId:a}=n;return e.matchUpMap[a]||(e.matchUpMap[a]={}),e.matchUpMap[a][i]?e.matchUpMap[a][i].push(n):e.matchUpMap[a][i]=[n],Fy({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:r,matchUp:n}),e}),{matchUpMap:{}});return{matchUpsToSchedule:u,matchUpMap:d}}function Yy({defaultRecoveryMinutes:t=0,averageMatchUpMinutes:e=90,dateScheduledMatchUps:n,tournamentRecords:r,venueIds:i=[],periodLength:a,scheduleDate:o,matchUps:s}){if("object"!=typeof r)return{error:x};if(!yc(s)&&!Array.isArray(n))return{error:Ht};a=a??ly({recoveryMinutes:t,averageMatchUpMinutes:e});const c=Object.assign({},...Object.values(r).map((t=>(t.events??[]).map((e=>{const{scheduleTiming:n}=Qu({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 Wy({schedule:e})&&(!o||t.schedule.scheduledDate===o)})));const d=n?.filter((t=>(!i.length||i.includes(t.schedule.venueId))&&t.matchUpStatus!==Ma)),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}=yd({timingDetails:s,eventType:o}),{courtId:l,venueId:m}=e,f=ni(e.scheduledTime),h=pi(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 Ky({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:x};s=s??ly({recoveryMinutes:n,averageMatchUpMinutes:r});const{courts:m,venues:f}=Am({dates:[c],ignoreDisabled:!0,tournamentRecords:a}),h=m?.filter((t=>!d||d.includes(t.venueId)))??[];u=u??my({courts:h,scheduleDate:c,startTime:!0}),l=l??my({courts:h,scheduleDate:c,endTime:!0});const{bookings:g,dateScheduledMatchUps:I}=Yy({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:S}=fy(U),y=1===d?.length&&d[0]||1===f?.length&&f[0].venueId||void 0,v=I?.map(Ua("matchUpId"));return{dateScheduledMatchUpIds:v,dateScheduledMatchUps:I,scheduleTimes:S,venueId:y}}function Jy({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 S of f){const{rounds:f=[],venueId:y}=S,{scheduledRoundsDetails:v,greatestAverageMinutes:w,orderedMatchUpIds:T,minutesMap:P}=Gy({scheduleCompletedMatchUps:n,containedStructureIds:r,tournamentRecords:c,periodLength:u,matchUps:l,rounds:f});U.push(...T??[]);const{groupedRounds:D}=qy({scheduledRoundsDetails:v,greatestAverageMinutes:w,garmanSinglePass:!0});let b,N,R=[];p&&({scheduleTimes:R,dateScheduledMatchUpIds:b,dateScheduledMatchUps:N}=Ky({averageMatchUpMinutes:D[0]?.averageMinutes,scheduleDate:ri(d),venueIds:[S.venueId],clearScheduleDates:s,tournamentRecords:c,periodLength:u,matchUps:l}));const M=Hy({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:b,greatestAverageMinutes:w,matchUpNotBeforeTimes:i,matchUpScheduleTimes:a,matchUpDependencies:o,clearScheduleDates:s,scheduleDate:d,minutesMap:P,matchUps:l});({dateScheduledMatchUpIds:b,dateScheduledMatchUps:N}=M);const{byeScheduledMatchUpDetails:A,clearDate:E}=M;A?.length&&I.push(...A);const{matchUpsToSchedule:C,matchUpMap:O}=zy({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:n,dateScheduledMatchUpIds:b,matchUpNotBeforeTimes:i,matchUpScheduleTimes:a,orderedMatchUpIds:T,clearDate:E,matchUps:l}),F=m.filter((t=>t.venueId===y));h[y]={previousRemainingScheduleTimes:[],courtsCount:F.length,greatestAverageMinutes:w,scheduledRoundsDetails:v,dateScheduledMatchUps:N,matchUpsToSchedule:C,scheduleTimes:R,groupedRounds:D,venueCourts:F,minutesMap:P,matchUpMap:O},s||g.push(...b)}return{allDateScheduledByeMatchUpDetails:I,allDateScheduledMatchUpIds:g,venueScheduledRoundDetails:h,allDateMatchUpIds:U}}function Zy({individualParticipantProfiles:t,matchUpNotBeforeTimes:e,matchUpDependencies:r,scheduleTime:i,matchUp:a,details:o}){const s=(r?.[a.matchUpId]?.participantIds||[]).flat(),c=o?.minutesMap?.[a.matchUpId]?.averageMinutes||0,u=o?.minutesMap?.[a.matchUpId]?.recoveryMinutes||0,d=s.every((e=>{ky({individualParticipantProfiles:t,participantId:e});const r=t[e];if(!r.timeAfterRecovery)return!0;const o=ni(a?.schedule?.endTime),s=o?pi(o,n(u)):pi(i,n(c)+n(u));return!!![...Object.keys(r.potentialBookings).filter((t=>t!==a.drawId)).map((t=>r.potentialBookings[t])).flat(),...r.bookings].find((t=>function(t,e){const n=ti(t.scheduleTime),r=ti(t.timeAfterRecovery),i=ti(e.scheduleTime),a=ti(e.timeAfterRecovery),o=n>i&&n<a,s=i>n&&i<r,c=r>i&&r<a,u=a>n&&a<r;return vr({hasOverlap:n===i||r===a||o||c||s||u,startAisContained:o,endAisContained:c,startBisContained:s,endBisContained:u},!0)}({scheduleTime:i,timeAfterRecovery:s},t).hasOverlap))})),p=e[a.matchUpId],l=p?di(ui(p),ui(i),!1):0;return{enoughTime:d&&l>=0}}function Xy({individualParticipantProfiles:t,matchUpPotentialParticipantIds:e,matchUpDailyLimits:n={},matchUp:r}){const{matchUpId:i,matchUpType:a}=r,{enteredIndividualParticipantIds:o}=ec(r),s=(r.roundPosition&&e[i]||[]).flat(),c=m(o.concat(...s));c.forEach((e=>{ky({individualParticipantProfiles:t,participantId:e})}));return{participantIdsAtLimit:c.filter((e=>{const r=t[e];if(r)return[a,ud].find((t=>{const e=r.counters?.[t]||0,i=n[t]||0;return e&&i&&e>=i}))})),relevantParticipantIds:c}}function Qy({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:_};if(!(c||u&&Array.isArray(u)))return{error:$t};if(!(c||d&&"object"==typeof d))return{error:gn};let p;const l=[];let m=0;if(r&&!i){const t=Sl({tournamentRecords:o,tournamentRecord:s});i=t.matchUpDependencies,p=t.matchUps}p||(p=hl({tournamentRecord:s})?.matchUps??[]);const f=p.reduce(((n,r)=>{const{matchUpId:i,drawId:a,matchUpStatus:o}=r;return!e&&o===Ma||!t&&Ya.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}=Oy({tournamentRecord:s,drawId:t});if(!e)continue;const g=f[t].filter((t=>u?.includes(t)??h?.includes(t))),I=Ul({inContext:!1,drawDefinition:e}).matchUps;for(const t of g){const u=gI({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?{...E,scheduled:m,warnings:l}:{...E,scheduled:m}}function tv(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 Qy(t);const d=Lp(t,[{[sp]:!0},{[kp]:{matchUpContextIds:!0,matchUpDetails:!0},[Op]:Nn,[Fp]:Ep}]);if(d.error)return d;if((!c||i)&&!u)return{error:ae,info:"schedule is required"};const p=[];let l=0;const{matchUpDependencies:m}=Sl({tournamentRecords:o});for(const t of Object.values(o)){const{tournamentId:d}=t,f=i?.filter((t=>t.tournamentId===d)).map(ba),h=c?.filter((t=>t?.tournamentId===d));if(f?.length||h?.length){const i=Qy({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?{...E,scheduled:l,warnings:p}:{...E,scheduled:l}}function ev({autoSchedulingAudit:t,tournamentRecords:e}){sr({topic:ds,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:zm,itemValue:i};for(const t of Object.values(e))Lm({tournamentRecord:t,timeItem:a})}function nv(t){const{tournamentRecords:e,requestType:n}=t,r=Lp(t,[{[sp]:!0}]);if(r.error)return r;const i={};for(const t of Object.values(e)){const{extension:e}=Mr({element:t,name:ea}),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,...E}}function rv({averageMinutes:t,startTime:e,endTime:n,court:r,date:i}){if(!Array.isArray(r.dateAvailability))return{error:ae,stack:"getEarliestCourtTime"};const a=my({scheduleDate:i,courts:[r],startTime:!0}),o=my({scheduleDate:i,courts:[r],endTime:!0});e=e||a,n=n||o;const s=cy({courtDate:sy({court:r,date:i})}),c=ui(e),u=ui(n);return{earliestCourtTime:s.reduce(((e,n)=>{const r=ui(n.startTime),i=ui(n.endTime);if(r>u||i<c)return e;const a=c>r?c:r;if(di(a,i)>=t){const t=ni(a.toISOString());(!e||t<e)&&(e=t)}return e}),void 0),courtStartTime:a,courtEndTime:o}}function iv(t){const{scheduleAttributes:e=["scheduledDate","scheduledTime"],ignoreMatchUpStatuses:n=Ya,scheduledDates:r,venueIds:i}=t,a=nc(t),o=ha(a)?Object.values(a).map((({tournamentId:t})=>t)).filter(Boolean):[];if(!o?.length)return{error:x};let s=0;for(const t of o){const o=av({ignoreMatchUpStatuses:n,scheduleAttributes:e,tournamentRecord:a[t],scheduledDates:r,venueIds:i});if(o.error)return o;s+=o.clearedScheduleCount||0}return{...E,clearedScheduleCount:s}}function av({scheduleAttributes:t=["scheduledDate","scheduledTime"],ignoreMatchUpStatuses:e=Ya,tournamentRecord:n,scheduledDates:r,venueIds:i=[]}){if("object"!=typeof n)return{error:_};if(!Array.isArray(e)||!Array.isArray(i))return{error:Nn};i.length&&t.push("venueId");const a=(hl({matchUpFilters:{scheduledDates:r},tournamentRecord:n}).matchUps??[]).filter((n=>n.matchUpStatus&&!e.includes(n.matchUpStatus)&&Wy({schedule:n.schedule,scheduleAttributes:t})&&(!i?.length||i.includes(n.schedule.venueId)))).map(ba),o=hl({tournamentRecord:n,inContext:!1}).matchUps??[];let s=0;for(const t of o)a.includes(t.matchUpId)&&(t.timeItems=(t.timeItems??[]).filter((t=>t?.itemType&&![Pu,Du,Tu,Nu,Mu].includes(t?.itemType))),s+=1);return{...E,clearedScheduleCount:s}}function ov(t){const{checkPotentialRequestConflicts:e=!0,scheduleCompletedMatchUps:n,clearScheduleDates:r,scheduleDates:i=[],tournamentRecords:a,periodLength:o,useGarman:s,dryRun:c,pro:u}=t,d=Lp(t,[{[sp]:!0},{[Cp]:t=>!t||Array.isArray(t)&&t.every(Wr),[mp]:!0,[Fp]:Ep}]);if(d.error)return d;const p=Om({tournamentRecords:a});if(p.error)return p;if(!p.schedulingProfile.length)return{...E};const{modifications:l,issues:m=[],schedulingProfile:f=[]}=p,h=Object.assign({},...Object.values(a).map((t=>qs({tournamentRecord:t}).containedStructures))),g=i.map((t=>{if(Wr(t))return ri(t)})).filter(Boolean),I=f.map((t=>t.scheduleDate)).map((t=>Wr(t)&&ri(t))).filter((t=>t&&(!i.length||g.includes(t))));if(!I.length)return{error:se};if(r&&!c){iv({tournamentRecords:a,scheduledDates:Array.isArray(r)?r:[]})}const U=Am({ignoreDisabled:!1,tournamentRecords:a}).courts,{matchUps:S}=gl({matchUpFilters:{matchUpTypes:[Ks,Zs]},afterRecoveryTimes:!0,nextMatchUps:!0,tournamentRecords:a}),{matchUpDependencies:y}=Sl({includeParticipantDependencies:!0,tournamentRecords:a,matchUps:S}),{matchUpDailyLimits:v}=Ey({tournamentRecords:a}),{personRequests:w}=nv({requestType:Ly,tournamentRecords:a}),T={schedulingProfileModifications:l,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:n,schedulingProfileIssues:m,dateSchedulingProfiles:f.filter((t=>{const e=ri(t?.scheduleDate);return I.includes(e)})).sort(((t,e)=>new Date(t.scheduleDate).getTime()-new Date(e.scheduleDate).getTime())),containedStructureIds:h,matchUpDependencies:y,matchUpDailyLimits:v,clearScheduleDates:r,tournamentRecords:a,schedulingProfile:f,personRequests:w,periodLength:o,useGarman:s,matchUps:S,dryRun:c,courts:U};return u?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={},S={},y={},v={},w={},T={},P={};for(const t of i??[]){const r=ri(t?.scheduleDate),i=t?.venues||[],p={},D={},b=(t,e)=>{t.forEach((t=>{const n=D[t].counters;n[e]?n[e]+=1:n[e]=1,n[ud]?n[ud]+=1:n[ud]=1}))};g[r]={},I[r]={},v[r]=[],w[r]=[],T[r]=[],P[r]=[];const N={};m?.forEach((t=>{t.schedule?.scheduledDate&&fi(r,ri(t.schedule.scheduledDate))&&Fy({matchUpPotentialParticipantIds:p,matchUpNotBeforeTimes:N,matchUp:t})}));const{allDateScheduledByeMatchUpDetails:R,allDateScheduledMatchUpIds:M,venueScheduledRoundDetails:A,allDateMatchUpIds:E}=Jy({matchUpPotentialParticipantIds:p,individualParticipantProfiles:D,scheduleCompletedMatchUps:n,containedStructureIds:a,matchUpNotBeforeTimes:N,matchUpScheduleTimes:y,matchUpDependencies:o,clearScheduleDates:c,tournamentRecords:u,periodLength:d,scheduleDate:r,matchUps:m,courts:f,venues:i}),C=m?.filter((({matchUpId:t})=>M.includes(t))),{bookings:O}=Yy({dateScheduledMatchUps:C,tournamentRecords:u,scheduleDate:r,periodLength:d}),{virtualCourts:F}=py({scheduleDate:r,periodLength:d,bookings:O,courts:f}),k=F?.reduce(((t,e)=>{const{earliestCourtTime:n,courtEndTime:i}=rv({date:r,averageMinutes:0,court:e});return(!t.startTime||ui(n)<ui(t.startTime))&&(t.startTime=n),(!t.endTime||ui(i)>ui(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}=Xy({matchUpPotentialParticipantIds:p,individualParticipantProfiles:D,matchUpDailyLimits:s,matchUp:i});if(h.length){w[r].includes(m)||w[r].push(m);continue}const{dependenciesScheduled:T,remainingDependencies:R}=Cy({matchUpScheduleTimes:y,matchUpDependencies:o,allDateMatchUpIds:E,matchUp:i});if(!T){I[r][m]||(I[r][m]=[]),I[r][m].push({remainingDependencies:R});continue}const M=[],A=F?.reduce(((t,a)=>{if(c.includes(a.courtId))return t;const{earliestCourtTime:s}=rv({averageMinutes:n.greatestAverageMinutes,startTime:x,date:r,court:a});if(t.scheduleTime&&ti(s)>=ti(t.scheduleTime))return t;const{scheduledDependent:u}=_y({matchUpScheduleTimes:y,matchUpDependencies:o,scheduleTime:s,matchUpId:m,details:n});if(u)return t;const{enoughTime:d}=Zy({individualParticipantProfiles:D,matchUpNotBeforeTimes:N,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}=Vy({potentials:e,averageMatchUpMinutes:h,requestConflicts:P,personRequests:l,scheduleTime:s,scheduleDate:r,matchUp:i});if(I?.length)return M.push(...I),!1;b(v,f);const U=n.minutesMap?.[m]?.recoveryMinutes;return xy({matchUpPotentialParticipantIds:p,individualParticipantProfiles:D,matchUpNotBeforeTimes:N,averageMatchUpMinutes:h,matchUpDependencies:o,recoveryMinutes:U,scheduleTime:s,matchUp:i}),(!t.scheduleTime||ti(s)<ti(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;y[m]=i,S[m]=o,a.push(m),c.push(o);const s=i,u=pi(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 M?.length&&(U[r]||(U[r]=[]),U[r].push(...M))}c.length!==n.courtsCount&&a.length!==n.courtsCount&&n.matchUpsToSchedule.length||(u=!0),n.matchUpsToSchedule.length&&a<n.courtsCount&&(ui(x)<ui(k.endTime)?x=pi(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}=Oy({tournamentRecord:n,drawId:i});a&&e[t][i].forEach((({matchUpId:t})=>{const e=y[t],i=S[t];if(e){const o=e.split(":").map(mi).join(":"),s=`${ri(r)}T${o}`;h||(mI({drawDefinition:a,scheduledTime:s,matchUpId:t}),lI({courtDayDate:r,tournamentRecords:u,tournamentRecord:n,drawDefinition:a,matchUpId:t,courtId:i})),v[r].push(t)}}))}))})),T[r]=A[t].matchUpsToSchedule.map(ba)}!h&&R?.length&&tv({matchUpDetails:R,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 D=(i??[]).map((({scheduleDate:t})=>t)),b={timeStamp:Date.now(),overLimitMatchUpIds:w,scheduledMatchUpIds:v,schedulingProfile:p,noTimeMatchUpIds:T,requestConflicts:P,scheduledDates:D};return ev({tournamentRecords:u,autoSchedulingAudit:b}),{...E,schedulingProfileModifications:t,schedulingProfileIssues:r,dateSchedulingProfiles:i,recoveryTimeDeferredMatchUpIds:g,dependencyDeferredMatchUpIds:I,matchUpScheduleTimes:y,overLimitMatchUpIds:w,scheduledMatchUpIds:v,noTimeMatchUpIds:T,requestConflicts:P,scheduledDates:D}}(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={},S={},y={},v={},w={},T={},P={},D={};for(const t of i){const r=ri(t?.scheduleDate),i=t?.venues||[],d={},b={},N=(t,e)=>{t.forEach((t=>{const n=b[t].counters;n[e]?n[e]+=1:n[e]=1,n[ud]?n[ud]+=1:n[ud]=1}))};U[r]={},S[r]={},g[r]={},I[r]={},w[r]=[],T[r]=[],P[r]=[],D[r]=[];const R={};m.forEach((t=>{t.schedule?.scheduledDate&&fi(r,ri(t.schedule.scheduledDate))&&Fy({matchUpPotentialParticipantIds:d,matchUpNotBeforeTimes:R,matchUp:t})}));const{allDateScheduledByeMatchUpDetails:M,venueScheduledRoundDetails:A,allDateMatchUpIds:E}=Jy({matchUpPotentialParticipantIds:d,individualParticipantProfiles:b,scheduleCompletedMatchUps:n,containedStructureIds:a,matchUpNotBeforeTimes:R,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}=Xy({matchUpPotentialParticipantIds:d,individualParticipantProfiles:b,matchUpDailyLimits:s,matchUp:t});if(u.length)return T[r].includes(n)||T[r].push(n),!1;const{scheduledDependent:m}=_y({matchUpScheduleTimes:v,matchUpDependencies:o,scheduleTime:a,matchUpId:n,details:i});if(m)return!1;const{dependenciesScheduled:f,remainingDependencies:h}=Cy({matchUpScheduleTimes:v,matchUpDependencies:o,allDateMatchUpIds:E,matchUp:t});if(!f)return S[r][n]||(S[r][n]=[]),S[r][n].push({scheduleTime:a,remainingDependencies:h}),!1;const{enoughTime:g}=Zy({individualParticipantProfiles:b,matchUpNotBeforeTimes:R,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}=Vy({potentials:e,averageMatchUpMinutes:I,requestConflicts:D,personRequests:p,scheduleTime:a,scheduleDate:r,matchUp:t});if(w?.length)return y[r]||(y[r]=[]),y[r].push(...w),!1;N(l,c);const P=i.minutesMap?.[n]?.recoveryMinutes;return xy({matchUpPotentialParticipantIds:d,individualParticipantProfiles:b,matchUpNotBeforeTimes:R,averageMatchUpMinutes:I,matchUpDependencies:o,recoveryMinutes:P,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}=Oy({tournamentRecord:i,drawId:a});o&&e[n][a].forEach((({matchUpId:e})=>{const n=v[e];if(n){const a=n.split(":").map(mi).join(":"),s=`${ri(r)}T${a}`;h?w[r].push(e):(mI({drawDefinition:o,scheduledTime:s,matchUpId:e}).success&&w[r].push(e),t&&pI({tournamentRecord:i,drawDefinition:o,matchUpId:e,venueId:t}))}}))}))})),P[r]=A[t].matchUpsToSchedule.map(ba),g[r][t]=A[t].scheduleTimes.sort(((t,e)=>ti(t.scheduleTime)-ti(e.scheduleTime)))}!h&&M?.length&&tv({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=>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)),N={timeStamp:Date.now(),overLimitMatchUpIds:T,scheduledMatchUpIds:w,schedulingProfile:d,noTimeMatchUpIds:P,requestConflicts:D,scheduledDates:b};return ev({tournamentRecords:u,autoSchedulingAudit:N}),{...E,schedulingProfileModifications:t,schedulingProfileIssues:r,scheduleTimesRemaining:g,dateSchedulingProfiles:i,skippedScheduleTimes:I,recoveryTimeDeferredMatchUpIds:U,dependencyDeferredMatchUpIds:S,matchUpScheduleTimes:v,overLimitMatchUpIds:T,scheduledMatchUpIds:w,noTimeMatchUpIds:P,requestConflicts:D,scheduledDates:b}}(T)}function sv(t){const e=t||{};return e.tournamentId||(e.tournamentId=Md()),(!e.startDate||Xr(e.startDate)||Lr.test(e.startDate))&&(!e.endDate||Xr(e.endDate)||Lr.test(e.endDate))?(e.extensions&&(e.extensions=e.extensions.filter(br)),{...e}):{error:pe}}function cv({addParticipants:t=!0,participantAttribute:e,tournamentRecord:n,personAttribute:r,teamNames:i,accessor:a,uuids:o}){if(!n)return{error:_};const s={},c=(n.participants??[]).filter((({participantType:t,participantRole:e})=>t===sc&&e===um));let u=0;for(const t of c){const n=a&&la({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()??Md(),individualParticipantIds:[],participantRole:um,participantType:dc};const t={value:r??e,name:Ji};Nr({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!==dc)return;if(t.participantRole!==um)return;const{extension:e}=Mr({name:Ji,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?(sr({payload:{tournamentId:n.tournamentId,participants:m},topic:ss}),{...E,participantsAdded:l}):m.length?{...E,newParticipants:m}:{error:Ie}}function uv(t){let{rankingRange:e,scaledParticipantsCount:n}=t;const{ratingsParameters:r=MU,valuesInstanceLimit:i,consideredDate:a,category:o,nationalityCodesCount:c,nationalityCodeType:u,nationalityCodes:p,participantsCount:m=32,participantType:h,personIds:g,idPrefix:I,uuids:U,personExtensions:S,addressProps:y,gendersCount:v,matchUpType:T,personData:P,sex:D,inContext:b,withISO2:N,withIOC:R,scaleAllParticipants:M}=t,A=h===uc||T===Js,E=h===dc||T===dc;!e||Array.isArray(e)&&e.every((t=>s(t)))&&2===e.length||(e=void 0),n=M?m:n;e=e||[1,n&&n>1e3?n:1e3],e[1]+=1;const C=m*(A?2:E?8:1),O=Ty({count:C,personExtensions:S,consideredDate:a,gendersCount:v,personData:P,category:o,sex:D});if(O.error)return O;const{nationalityCodes:F,persons:k}=O;let x=[],_=[],L=[],B=[];if("object"==typeof o){const{categoryName:t,ageCategoryCode:i,ratingType:a}=o;if((t||i)&&!a){const[t,r]=e||[];if(_=f(w(t,r)).slice(0,n||d(20,30)),[uc,dc].includes(h)){const[t,r]=e||[];x=f(w(t,r)).slice(0,n||d(20,30))}}if(a&&r[a]){const{ratingMax:t,ratingMin:e,ratingAttributes:i}=o,s={...r[a],...i||{}},{attributes:c={},decimalsCount:u,accessors:p,range:m,step:f}=s,g=t=>{const e={};for(const n of Object.keys(t)||{}){const r=t[n];if("object"==typeof r&&r.generator){const{range:t}=r,[i,a]=t.slice().sort();e[n]=d(i,a)}else e[n]=r}return e},I=m[0]>m[1]?2:.5,[U,S]=m.slice().sort(),y=()=>w(0,2e3).map((()=>l(U,S,I,f,u))).filter((n=>(!t||n<=t)&&(!e||n>=e))).slice(0,n||d(20,30)).map((t=>p?Object.assign({},...p.map((e=>({[e]:t}))),g(c)):t));L=y(),[uc,dc].includes(h)&&(B=y())}}const V=el.filter((t=>"IOC"===u&&t.ioc||t.iso));const{postalCodesProfile:j,postalCodesCount:G,statesProfile:q,citiesProfile:$,citiesCount:W,statesCount:H}=y||{},z=t=>Object.keys(t).map((t=>w(0,q[t]).map((()=>t)))).flat(),Y={cities:$&&z($)||y?.cities||Uy({count:W||C,participantsCount:C}).cities,states:q&&z(q)||y?.states||Sy({count:H||C,participantsCount:C}).states,postalCodes:j&&z(j)||y?.postalCodes||yy({count:G||C,participantsCount:C}).postalCodes},K=function(t){const e=Math.ceil(C/t);return i&&e>i?Math.ceil(C/i):t}(c),J=K?f(V).slice(0,c):p?V.filter((t=>p.includes(t.iso))):V,Z=f(w(0,Math.ceil(C/(K||1))).map((()=>J)).flat(1/0)),X=by({count:m}).names;return{participants:w(0,m).map((t=>{const e=A?2:E?8:1,n=w(0,e).map((n=>function(t){const e=k[t],{nationalityCode:n,participantExtensions:r,participantTimeItems:i,extensions:a,firstName:s,birthDate:c,lastName:d,personId:p,sex:l}=e||{},m=s||"GivenName",f=d||"FamilyName",h=`${m} ${f}`,S=Z[t],y=F?.length&&n||S&&("IOC"===u?S.ioc||S.iso:S.iso||S.ioc)||n;!Z?.length||y||n||console.log("%c Invalid Nationality Code",{participantIndex:t,country:S});const v=Py({...Y,participantIndex:t,nationalityCode:y}),w=vr({participantId:pv({participantType:sc,index:t,idPrefix:I,uuids:U}),extensions:r,timeItems:i,participantRole:um,participantType:sc,participantName:h,person:{addresses:[v],personId:p||g?.length&&g[t]||Md(),standardFamilyName:f,standardGivenName:m,nationalityCode:y,extensions:a,birthDate:Wr(c)?c:void 0,sex:l}});if(R&&y){const t=el.find((({iso:t})=>t===y));t?.ioc&&(w.person.iocNationalityCode=t.ioc),t?.label&&(w.person.countryName=t.label)}if(N&&y){const t=el.find((({iso:t})=>t===y));t?.iso2&&(w.person.iso2NationalityCode=t.iso2),t?.label&&(w.person.countryName=t.label)}if(o){const e=_[t],n=x[t];dv({scaleValue:e,eventType:ed,scaleType:Er,participant:w,category:o}),dv({scaleValue:n,eventType:rd,scaleType:Er,participant:w,category:o});const r=L[t],i=B[t];dv({scaleValue:r,eventType:ed,scaleType:Cr,participant:w,category:o}),dv({scaleValue:i,eventType:rd,scaleType:Cr,participant:w,category:o})}return w}(t*e+n))),r=n.map((t=>t.participantId)),i=n.map((t=>t.person.standardFamilyName)).join("/"),a=A?uc:dc,s={participantId:pv({participantType:a,idPrefix:I,index:t,uuids:U}),participantRole:um,participantName:A?i:X[t],individualParticipantIds:r,participantType:a};return b&&(s.individualParticipants=n),A||E?[s,...n]:n})).flat()}}function dv({scaleValue:t,participant:e,eventType:n,scaleType:r,category:i}){const a=i.categoryName||i.ratingType||i.ageCategoryCode,o={itemValue:t,itemType:[Or,r,n,a].join(".")};a&&t&&(e.timeItems||(e.timeItems=[]),e.timeItems.push(o))}function pv({idPrefix:t,participantType:e,index:n,uuids:r}){return t?`${t}-${e===sc?"I":"P"}-${n}`:r?.pop()||Md()}function lv({alternatesCount:t=0,tieFormatName:e,tieFormat:n,drawSize:r}){let i=0,a=0,o=0,s=0;const c={},u={[qp]:0,[Hp]:0,[$p]:0,[Wp]:0,[Gp]:0};n="object"==typeof n?n:ES({namedFormat:e}),n?.collectionDefinitions?.filter(Boolean).forEach((t=>{const{category:e,collectionId:n,matchUpType:r,matchUpCount:d,gender:p}=t;if([qp,Hp].includes(p)){const t=d*(r===Zs?2:1);u[p]<t&&(u[p]=t)}else p===$p&&(u[qp]<d&&(u[qp]=d),u[Hp]<d&&(u[Hp]=d));if(e){const t=JSON.stringify(e);c[t]=e}if(n||(t.collectionId=Md()),r===Zs){const t=d;s+=d,i=Math.max(i,t)}if(r===Ks){const t=d;o+=d,a=Math.max(a,t)}}));const d=Object.keys(c).length?Math.max(o,2*s):Math.max(a,2*i);return{maxDoublesDraw:i*(r+t),maxSinglesDraw:a*(r+t),teamSize:d,genders:u}}function mv({participantsProfile:t,tournamentRecord:e,eventProfiles:n,drawProfiles:r,startDate:i,uuids:a}){const{participantsCount:o,participantType:s,largestTeamDraw:c,largestTeamSize:u,gendersCount:d}=function({participantsProfile:t,eventProfiles:e,drawProfiles:n}){let{participantsCount:r,participantType:i=sc}=t||{};const a=r||0,o={[Hp]:0,[$p]:0,[Wp]:0,[qp]:0,[Gp]: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===nd,g=i===id,I=Boolean(e||f===Qa||l||m);if(g){d=Math.max(d,r+t),a="object"==typeof a?a:ES({namedFormat:n});const{teamSize:e,maxDoublesDraw:i,maxSinglesDraw:p,genders:l}=lv({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=uc),(r||a)<m&&(r=m),r&&s&&[uc,id].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=uv({uuids:a,...t,consideredDate:i,participantsCount:o,participantType:s,gendersCount:d}).participants;let m=0,f=gU({tournamentRecord:e,participants:l});if(f.error)return f;if(m+=f.addedCount,p){const t=cv({tournamentRecord:e,...p});if(t.error)return t}const h=l.filter((({participantType:t})=>t===sc)).map(Da);return f=gU({participants:w(0,c).map((t=>{const e=h.slice(t*u,(t+1)*u);return{participantName:`Team ${t+1}`,participantRole:um,participantType:dc,participantId:Md(),individualParticipantIds:e}})),tournamentRecord:e}),f.error?f:(m+=f.addedCount,{addedCount:m,...E})}const fv=()=>({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});function hv(t){return parseInt(t)}function gv({startTime:t="",endTime:e=""}={}){if(!(t&&e&&jr.test(t)&&jr.test(e)))return!1;const[n,r]=t.split(":").map(hv),[i,a]=e.split(":").map(hv);return!(i<n)&&!(n===i&&a<r)}function Iv(t,e){const[n,r]=t.startTime.split(":").map(hv),[i,a]=e.startTime.split(":").map(hv);return n<i?-1:n>i?1:r<a?-1:r>a?1:0}function Uv({dateAvailability:t}){if(!t)return{error:de};if(!Array.isArray(t))return{error:ue};const e="Times must be 24 hour => 00:00";for(const n of t){if("object"!=typeof n)return{error:ue};const{date:t,startTime:r,endTime:i,bookings:a=[]}=n;if(!r||!i)return{error:ue};if(t&&!Vr.test(t))return{error:pe,dateAvailability:{date:t},info:"Dates must be formated => YYYY-MM-DD"};if(!jr.test(r))return{error:le,dateAvailability:{startTime:r},info:e};if(!jr.test(i))return{error:le,dateAvailability:{endTime:i},info:e};if(r===i)return{error:le,dateAvailability:{startTime:r,endTime:i},info:"startTime and endTime are equivalent"};if(!gv({startTime:r,endTime:i}))return{error:le,dateAvailability:{startTime:r,endTime:i},info:"endTime must be after startTime"};if(a){if(!Array.isArray(a))return{error:ce};for(const t of a){if("object"!=typeof t)return{error:ce};const{startTime:n,endTime:r}=t;if(!jr.test(n))return{error:le,booking:{startTime:n},info:e};if(!jr.test(r))return{error:le,booking:{endTime:r},info:e};if(n===r)return{error:le,dateAvailability:{startTime:n,endTime:r},info:"startTime and endTime are equivalent"};if(!gv({startTime:n,endTime:r}))return{error:le,dateAvailability:{startTime:n,endTime:r},info:"endTime must be after startTime"}}}}return{valid:!0}}function Sv({tournamentRecord:t,disableNotice:e,venueId:n,courtId:r,court:i}){const{venue:a}=Cd({tournamentRecord:t,venueId:n});if(!a)return{error:rn};a.courts||(a.courts=[]);const o={...fv(),venueId:n,courtId:r};o.courtId||(o.courtId=Md());if(a.courts.some((t=>t.courtId===o.courtId)))return{error:en};{const r=(i?.dateAvailability||[]).map((t=>({...t,date:ri(t.date),startTime:ni(t.startTime),endTime:ni(t.endTime),bookings:t.bookings?.map((({startTime:t,endTime:e,bookingType:n})=>({startTime:ni(t),endTime:ni(e),bookingType:n})))}))),s=Object.keys(o);for(const t of s)if(i?.[t])if("dateAvailability"===t){const t=Uv({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||sr({payload:{venue:a,tournamentId:t.tournamentId},topic:Ts,key:a.venueId}),{...E,court:gi(o),venueId:n}}}function yv(t){const{tournamentRecord:e,venueId:n}=t;if("string"!=typeof n||!n)return{error:an};const r=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},i=[];let a;for(const e of Object.values(r)){const{venue:r}=Cd({tournamentRecord:e,venueId:n});if(r){const n=vv({...t,tournamentRecord:e});for(const t of n?.courts??[])i.push(t?.courtId);if(n.error)return n;a=!0}}return a?{...E,courtIds:i}:{error:rn}}function vv({courtNameRoot:t="Court",dateAvailability:e=[],venueAbbreviationRoot:n,tournamentRecord:r,courtNames:i=[],courtTimings:a,courtsCount:o,startTime:c,courtIds:u,endTime:d,idPrefix:p,venueId:l,dates:m}){if(!l)return{error:an};const f=Cd({tournamentRecord:r,venueId:l});if(f.error)return f;const{venue:h}=f;if(!s(o)||!i)return{error:Qe};const g=w(0,o=o??i.length).map((r=>{const o=a?.[r],s=o?m.map((t=>({date:zr(t),startTime:c,endTime:d,...o}))):e;return o&&c&&d&&s.push({startTime:c,endTime:d}),{courtName:i[r]||n&&h?.venueAbbreviation&&`${h?.venueAbbreviation} ${r+1}`||`${t} ${r+1}`,dateAvailability:s}})).map(((t,e)=>{const n=u?.pop()||p&&`${p}-${e+1}`;return Sv({disableNotice:!0,tournamentRecord:r,courtId:n,venueId:l,court:t})})).map((t=>t.court)).filter(Boolean);return g.length!==o?wr({info:"not all courts could be generated",result:{error:Nn}}):(h&&sr({payload:{venue:h,tournamentId:r.tournamentId},topic:Ts,key:h.venueId}),{...E,courts:gi(g)})}function wv({tournamentRecord:t,venueProfiles:e,uuids:n}){const{startDate:r,endDate:i}=t,a=[];for(const[o,s]of e.entries()){const{venueAbbreviation:e,venueId:c=n?.pop()??Md(),dateAvailability:u,startTime:d="07:00",endTime:p="19:00",courtTimings:l,courtsCount:m,courtNames:f,venueName:h,idPrefix:g,courtIds:I}=s,U=Ad({tournamentRecord:t,venue:{venueName:h||`Venue ${o+1}`,venueAbbreviation:e,venueId:c}});if(U.error)return U;a.push(c);const S=Jr(r,i),y=!Array.isArray(u)&&[{startTime:d,endTime:p}].concat(S.map((t=>({date:zr(t),startTime:d,endTime:p})))),v=yv({dateAvailability:u||y,tournamentRecord:t,courtTimings:l,courtsCount:m,courtNames:f,startTime:d,idPrefix:g,courtIds:I,endTime:p,venueId:c,dates:S});if(v.error)return v}return a}function Tv({drawProfiles:t,category:e,gender:n}){const r={},i=t?.reduce(((t,i)=>{const{qualifyingPositions:a=0,participantsCount:o=0,uniqueParticipants:s,stage:c=Xa,drawSize:u=0}=i||{};Object.keys(t).includes(c)||(t[c]=0);const d=(o||u)-a;return s||n||e||c===Qa?(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 Pv({allUniqueParticipantIds:t,stageParticipantsCount:e,eventParticipantType:n,targetParticipants:r}){const i=e[Xa]||0,a=e[Qa]||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)}}}function Dv(t){const{removePriorValues:e,tournamentRecord:n,participantId:r,scaleItem:i}=t;let a,o;if(!bv({scaleItem:i}))return{error:In};if(r&&Array.isArray(n.participants)&&(o=n.participants.find((t=>t.participantId===r)),o)){const t=Nv({removePriorValues:e,participant:o,scaleItem:i});if(t.error)return t;a=!t.valueChanged;const{topics:r}=lr();r.includes(Ss)&&sr({topic:Ss,payload:{tournamentId:n.tournamentId,participants:[o]}})}return a&&{...E,info:Cn,existingValue:i?.scaleValue}||o&&{...E,newValue:i?.scaleValue}||{error:Ee}}function bv({scaleItem:t}){const e=t&&Object.keys(t),n=["scaleType","eventType","scaleName"];return!!(n.filter((t=>e?.includes(t))).length===n.length)}function Nv({removePriorValues:t,participant:e,scaleItem:n}){if(!e)return{error:Re};const r=n&&Object.keys(n),i=["scaleType","eventType","scaleName"];if(!(i.filter((t=>r.includes(t)&&n[t])).length===i.length))return{error:In};const a=(new Date).toISOString();e.timeItems||(e.timeItems=[]);const{scaleItem:o}=Vl({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=[Or,r,i,o].join("."),c=vr({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{...E,valueChanged:c,newValue:n.scaleValue}}function Rv({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:n,setObject:r}){if(!r)return;const i=Mv({set:r}),a=function({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:n,isTiebreakSet:r,isDecidingSet:i,set:a}){if(!a)return{error:ae,info:"missing set"};e=e||n&&Jd(n);const o=i&&e.finalSetFormat||e?.setFormat||{},{side1Score:s,side2Score:c}=a,{setTo:u,tiebreakAt:d,tiebreakFormat:p}=o,l=p?.NoAd,m=Mv({set:a}),f=Math.abs(s-c),h=s>=u||c>=u,g=r||s>=u&&c>=u||d&&d<u&&(s===d||c===d),I=t||g&&(1===m&&a.side1TiebreakScore>a.side2TiebreakScore||2===m&&a.side2TiebreakScore>a.side1TiebreakScore),U=g&&(d&&!r||r&&l)?1:2,S=f>=U;return(h&&(S||g)||r)&&(!g||I)}({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:n,set:r});return a&&i||void 0}function Mv({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 Av(t){const{setObject:e,matchUpScoringFormat:n}=t;if(!e)return{error:re};const{setNumber:r}=e||{},{bestOf:i}=n||{},a=!(!r||!i||r!==i),o=a&&n?.finalSetFormat||n?.setFormat,s=!!o?.tiebreakSet,c=!!o?.timed,u=!s&&!c,d=!!(r&&i&&r<=i),p=[e?.side1Score,e?.side2Score],l=[e?.side1PointScore,e?.side2PointScore],m=[e?.side1TiebreakScore,e?.side2TiebreakScore],f=p.filter((t=>void 0!==t)).length,h=l.filter((t=>void 0!==t)).length,g=m.filter((t=>void 0!==t)).length,I=p?.filter((t=>!isNaN(t))).length,U=m?.filter((t=>!isNaN(t))).length,{tiebreakAt:S}=o||{},y=S&&2===p.filter((t=>t>=S)).length,v=y&&((p[0]>p[1]?1:p[1]>p[0]&&2)||void 0),w=!(!U||I),T=!!e?.winningSide,{error:P,result:D}=function({setObject:t,setFormat:e,sideGameScores:n,sideTiebreakScores:r}){if(!t)return{result:!1,error:re};const i=!!e?.tiebreakSet,a=!!e?.timed;if(!e||i||a)return{result:!1,error:Nn};const o=2===n?.filter((t=>!isNaN(t))).length;if(!o)return{result:!1,error:fe};const{setTo:s,tiebreakAt:c,tiebreakFormat:u,NoAD:d}=e||{},p=!(!s||!n?.find((t=>t>=s)));if(!p)return{result:!1,error:fe};const l=[1,2].includes(t?.winningSide);if(!t||!l)return{result:!1,error:ge};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,S=2===r?.filter((t=>!isNaN(t))).length,y=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(!S)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(!y||!v||y<v)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};const n=y-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 T=d?1:2,P=g>=s-1,D=I&&P&&!w&&I<T;if(D)return{result:!1,error:{message:"invalid winning game scoreString (3)"}};if(I>T&&h>s)return{result:!1,error:{message:"invalid winning game scoreString (4)"}};return{result:!0}}({setObject:e,setFormat:o,sideGameScores:p,sideTiebreakScores:m}),{error:b,result:N}=function({setObject:t,setFormat:e,sideTiebreakScores:n}){if(!t)return{result:!1,error:re};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:ge};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}}({setObject:e,setFormat:o,sideTiebreakScores:m}),R=u&&!w&&D||s&&w&&N,M={expectTiebreakSet:s,expectTimedSet:c,hasTiebreakCondition:y,isCompletedSet:T,isDecidingSet:a,isTiebreakSet:w,isValidSet:d&&!(s&&!w)&&!(u&&w)&&(!T||R),isValidSetNumber:d,isValidSetOutcome:R,leadingSide:v,setFormat:o,sideGameScores:p,sideGameScoresCount:f,sidePointScores:l,sidePointScoresCount:h,sideTiebreakScores:m,sideTiebreakScoresCount:g,winningSide:Rv({isDecidingSet:a,isTiebreakSet:w,matchUpScoringFormat:n,setObject:e})};return void 0!==e?.winningSide&&(w?(M.isValidTiebreakSetOutcome=N,N||(M.tiebreakSetError=b)):(M.isValidStandardSetOutcome=D,D||(M.standardSetError=P))),M}function Ev(t){const{matchUp:e,sideNumber:n,setNumber:r,isTiebreakValue:i,isPointValue:a}=t||{};let{matchUpFormat:o}=t||{};if(!e)return{error:zt};o=o||e?.matchUpFormat;const s=Jd(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)||[],I=!!(d&&r&&h?.reduce(((t,e)=>(!e||!e.side1Score&&!e.side2Score&&!e.side1TiebreakScore&&!e.side2TiebreakScore&&!e.side1PointScore&&!e.side2PointScore)&&t),!0)),U=r<=d&&u.find((t=>t.setNumber===r)),S=U&&Av({setObject:U,matchUpScoringFormat:s}),{isCompletedSet:y,sideGameScores:v,sideTiebreakScores:w}=S||{},T=!!(U&&!y&&I||r&&r===d+1&&!c),P=[1,2].includes(n),D=P?n-1:0,b=U&&P&&(!i&&!a&&void 0!==v[D]&&v[D]||i&&void 0!==w[D]&&w[D]),N=!!b,R=m?.map((t=>Av({setObject:t,matchUpScoringFormat:s}).isValidSetOutcome)).reduce(((t,e)=>t&&e),!0),M=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=M[E],F=M[C],k=Math.max(...M),x=g(M)[k],{bestOf:_}=s||{},L=k===(_&&Math.ceil(_/2)||1)&&1===x&&M.indexOf(k)+1||void 0,B=O>F&&A===L;return{completedSetsHaveValidOutcomes:R,validMatchUpWinningSide:B,calculatedWinningSide:L,matchUpScoringFormat:s,validMatchUpOutcome:L&&R&&B,isLastSetWithValues:I,completedSetsCount:f,isCompletedMatchUp:c,isValidSideNumber:P,hasExistingValue:N,existingValue:b,isExistingSet:l,isActiveSet:T,...S}}const Cv={[Ga]:2,[ka]:1,[Fa]:1,[Ba]:1,[Oa]:4};function Ov(t){let{defaultWithScorePercent:e=2,winningSide:n}=t;const{matchUpStatusProfile:r=Cv,matchUpFormat:i=lg,pointsPerMinute:a=1,sideWeight:o=4}=t;if(!rh(i))return{error:Bt};if("object"!=typeof r)return{error:Nn};if(e>100&&(e=100),isNaN(e)||isNaN(a)||isNaN(o))return{error:Nn};const s=Object.keys(r).filter((t=>Object.keys(Za).includes(t)&&t!==Ea));if(Object.keys(s).reduce(((t,e)=>t+r[e]),0)>100)return{error:Nn,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=d(1,100),p=(c.valueMap.find((t=>u<=t[0]))??[100,Ea])[1],l={sets:[],scoreStringSide1:"",side2ScoreString:""};if([Ga,Oa].includes(p)){n=n||d(1,2);const t={score:l,winningSide:n,matchUpStatus:p};if(!(p===Oa&&d(1,100)>100-e))return{outcome:t}}else if([ka,Fa].includes(p))return{outcome:{score:l,matchUpStatus:p}};const m=Jd(i),{bestOf:f,setFormat:h,finalSetFormat:g}=m??{},I=[],U=d(0,1),S=n?[n-1]:[...w(0,o).map((()=>U)),1-U],v=[Ba,Oa,_a,Va].includes(p)&&(y(w(1,f))||1);let T;for(const t of w(1,(f??0)+1)){const e=t===f,{set:n,incomplete:r,winningSideNumber:o}=Fv({incomplete:v===t,matchUpStatus:p,pointsPerMinute:a,setFormat:e&&g||h,setNumber:t,weightedRange:S});if(I.push(n),r){T=o;break}if(Ev({matchUp:{score:{sets:I},matchUpFormat:i}}).calculatedWinningSide)break}const P=Ev({matchUp:{score:{sets:I},matchUpFormat:i}}),D=T?n||T:P.calculatedWinningSide,{score:b}=iU({score:{sets:I},winningSide:D,matchUpStatus:p});return{outcome:{score:b,winningSide:D,matchUpStatus:p}}}function Fv({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:p,timed:l,minutes:m}=i,f=d(0,t.length-1),h=t[f];let g;if(l){const i=m*e,a=Math.round(.2*i),s=i+y([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];h&&u.reverse(),g=t[f]+1;let p=(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}),Ya.includes(n)?{set:o,incomplete:r,winningSideNumber:g}:{set:o,incomplete:r}}p||(u[d(0,1)]+=1),p=u[0]>u[1]?1:2,p!==g&&u.reverse();const[l,I]=u;return Object.assign(o,{side1Score:l,side2Score:I,winningSide:g}),{set:o}}if(r)return o.side1Score=d(0,u),o.side2Score=d(0,u),Ya.includes(n)&&(g=t[f]+1),{set:o,incomplete:r,winningSideNumber:g};{const e=w(1,s+1).map((t=>w(0,s+2-t).map((()=>t)))).flat(),n=e[d(0,e.length-1)],r=s&&Ny({isSide1:!0,tiebreakAt:u,lowValue:n,setTo:s}),a=!r,l=1===t.length&&t[f]+1;if(!a){if(l){(r[0]>r[1]?1:2)!==l&&r.reverse()}else h&&r.reverse();const[t,e]=r;Object.assign(o,{side1Score:t,side2Score:e})}const m=Av({matchUpScoringFormat:{setFormat:i},setObject:o});let g;if(m.hasTiebreakCondition||a){const{NoAD:t,tiebreakTo:e}=c||p||{},n=w(1,e+1).map((t=>w(0,e+2-t).map((()=>t)))).flat(),r=n[d(0,n.length-1)],i=Ry({isSide1:!0,tiebreakNoAd:t,tiebreakTo:e,lowValue:r});if(i)if(a){const t=i[0]>i[1]?1:2;l?t!==l&&i.reverse():h&&i.reverse(),[o.side1TiebreakScore,o.side2TiebreakScore]=i,g=(i[0]>i[1]?1:i[1]>i[0]&&2)||void 0}else 2===m.leadingSide?[o.side1TiebreakScore,o.side2TiebreakScore]=i:[o.side2TiebreakScore,o.side1TiebreakScore]=i}o.winningSide=m.winningSide||m.leadingSide||l||g}return{set:o}}function kv(t){const{matchUpStatusProfile:e,completeAllMatchUps:n,randomWinningSide:r,tournamentRecord:i,completionGoal:a,drawDefinition:o,event:s}=t;if(!o)return{error:j};const c=t.matchUpFormat||o.matchUpFormat||s?.matchUpFormat,u=o.structures.slice().sort(Xo);let d=0;const{matchUps:p,matchUpsMap:l}=Jp({contextFilters:{stages:[Xa,Qa]},matchUpFilters:{matchUpTypes:[Qs],roundNumbers:[1]},inContext:!0,drawDefinition:o});if(p?.length){const t=s?.category?.ageCategoryCode||s?.category?.categoryName;if(t){const e=oy({singlesOnly:!0,tournamentRecord:i,drawDefinition:o,scaleAccessor:{scaleName:t,sortOrder:ry,scaleType:Er},event:s});if(e.error)return e;const{lineUps:n,participantsToAdd:r}=e;gU({tournamentRecord:i,participants:r});Nr({element:o,extension:{name:Zi,value:n}})}else{const t=p[0]?.structureId,{positionAssignments:e}=rs({drawDefinition:o,structureId:t});if(e?.length){const{participants:t}=Zl({participantFilters:{participantTypes:[Qs]},tournamentRecord:i}),n=n=>{const r=n.tieMatchUps.filter((({matchUpType:t})=>t===Ks)),a=n.tieMatchUps.filter((({matchUpType:t})=>t===Zs));r.forEach(((n,r)=>{const a=n.matchUpId;n.sides.forEach((n=>{const{drawPosition:c}=n,u=t?.find((t=>{const{participantId:n}=t,r=e.find((t=>t.participantId===n));return r?.drawPosition===c}));if(u){const t=u.individualParticipantIds?.[r];t&&Wf({teamParticipantId:u.participantId,participantId:t,tournamentRecord:i,drawDefinition:o,tieMatchUpId:a,event:s})}}))})),a.forEach(((n,r)=>{const a=n.matchUpId;n.sides.forEach((n=>{const{drawPosition:c}=n,u=t?.find((t=>{const{participantId:n}=t,r=e.find((t=>t.participantId===n));return r?.drawPosition===c}));if(u){const t=u.individualParticipantIds?.slice(2*r,2*r+2);t?.forEach((t=>{Wf({teamParticipantId:u.participantId,participantId:t,tournamentRecord:i,drawDefinition:o,tieMatchUpId:a,event:s})}))}}))}))};p.forEach(n)}}}const m="string"==typeof n&&n,f=m&&Ea;for(const t of u){if(d>=a)break;const{matchUps:n}=Yp({matchUpFilters:{matchUpTypes:[Zs,Ks]},afterRecoveryTimes:!1,tournamentRecord:i,inContext:!0,drawDefinition:o,matchUpsMap:l,structure:t,event:s}),u=n.filter((({winningSide:t})=>!t)).sort(Il).map(ba);for(const n of u){if(!isNaN(a)&&d>=a)break;const{matchUps:u}=Yp({matchUpFilters:{matchUpTypes:[Zs,Ks]},afterRecoveryTimes:!1,tournamentRecord:i,inContext:!0,drawDefinition:o,matchUpsMap:l,structure:t,event:s}),p=u.find((t=>t.matchUpId===n)),h=[ka,Fa].includes(p.matchUpStatus);if(p?.readyToScore&&!h){const t=_v({winningSide:!r&&1,matchUpStatusProfile:e,tournamentRecord:i,drawDefinition:o,targetMatchUp:p,matchUpFormat:c,matchUpStatus:f,scoreString:m,event:s});if(t?.error)return t;d+=1}}}return{...E,completedCount:d}}function xv(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===Ma)return;const{matchUpId:p}=a||{},{outcome:l}=Ay({matchUpFormat:s,matchUpStatus:o,scoreString:c,winningSide:u});return e&&(l.matchUpStatusCodes=e),aU({tournamentRecord:r,policyDefinitions:n,drawDefinition:i,matchUpFormat:s,matchUpId:p,outcome:l,event:d})}function _v(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 xv(t);const{matchUpId:p}=s||{},{outcome:l}=Ov({matchUpStatusProfile:e,matchUpFormat:o,winningSide:u});return aU({policyDefinitions:r,tournamentRecord:n,drawDefinition:i,matchUpFormat:o,matchUpId:p,outcome:l,event:d})}function Lv({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:n,tournamentRecord:r,drawProfiles:i,event:a}){const o=Bd({event:a}).flightProfile,{eventName:s,eventType:c,category:u}=a,{startDate:d}=r,p=[],l=u?.categoryName||u?.ageCategoryCode||u?.ratingType,m=a.drawDefinitions?.map((({drawId:t})=>t));if(Array.isArray(o?.flights))for(const[u,f]of o.flights.entries()){const{drawId:o,stage:h,drawName:g,drawEntries:I}=f;p.push(f.drawId);const U=i[u],{seedsCount:S,generate:y=!0}=U||{};if(y){const p=I.filter(Ua(lp)).map(Ua(lp)),f=l||s;if(r&&S&&S<=p.length){w(1,S+1).forEach(((t,e)=>{const n={scaleValue:t,scaleName:f,scaleType:Fr,eventType:c,scaleDate:d},i=p[e];Dv({tournamentRecord:r,participantId:i,scaleItem:n})}))}if(m?.includes(o))break;let y=QS({...U,matchUpType:c,seedingScaleName:f,tournamentRecord:r,isMock:!0,drawEntries:I,drawName:g,drawId:o,event:a,stage:h});if(y.error)return{error:y.error,drawIds:[]};const{drawDefinition:v}=y;if(!v)return{error:q};const T=i[u]?.drawExtensions;if(Array.isArray(T)&&T.filter(br).forEach((t=>Nr({element:v,extension:t}))),y=hU({suppressNotifications:!0,tournamentRecord:r,drawDefinition:v,event:a}),y.error)return{error:y.error,drawIds:[]};if(U?.withPlayoffs){const t=v.structures?.[0].structureId,e=eU({idPrefix:U.idPrefix,...U.withPlayoffs,tournamentRecord:r,drawDefinition:v,isMock:!0,structureId:t,event:a});if(e?.error)return e}const P=U?.completionGoal;if(!(!1===U?.automated)&&(e||P)){const i=U?.matchUpFormat,o=kv({completeAllMatchUps:!P&&e,matchUpStatusProfile:t,randomWinningSide:n,tournamentRecord:r,completionGoal:P,drawDefinition:v,matchUpFormat:i,event:a});if(o.error)return{error:o.error,drawIds:[]};const s=o.completedCount;if(U?.drawType===qo){const o=v.structures?.find((t=>t.stage===Xa));if(!o)return{error:Ut};let c=tg({structureId:o.structureId,tournamentRecord:r,drawDefinition:v,event:a});if(c.error)return{error:c.error,drawIds:[]};if(c=kv({completeAllMatchUps:!P&&e,completionGoal:P?P?P-(s??0):void 0:void 0,matchUpStatusProfile:t,randomWinningSide:n,tournamentRecord:r,drawDefinition:v,matchUpFormat:i,event:a}),c.error)return{error:c.error,drawIds:[]}}}}}return{...E,drawIds:p}}function Bv(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=p===td&&sc||p===nd&&uc||p,m=n[Xa]||0,f=n[Qa]||0,h=a.drawProfiles?.length?m+f:a.participantsProfile?.participantsCount??0,g=[qp,Hp].includes(d)?d:void 0,I=e?.idPrefix?`E-${o}-${e?.idPrefix}`:void 0,{participants:U}=uv({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}),S=gU({tournamentRecord:i,participants:U});if(S.error)return S;const y=U?.filter((({participantType:t})=>t===l)),v=U?.map(Da);return{uniqueDrawParticipants:y,uniqueParticipantIds:v}}function Vv({autoEntryPositions:t,tournamentRecord:e,drawParticipants:n,drawProfile:r,event:i}){const{drawType:a=bo,qualifyingPositions:o=0,stage:s=Xa,drawSize:c=0,drawName:u,drawId:d}=r,p=c-o,l=n.slice(0,p).map(Da);if(l.length){const n=cm({participantIds:l,autoEntryPositions:t,entryStage:s,tournamentRecord:e,event:i});if(n.error)return n}const m=$U({drawName:u||a,qualifyingPositions:o,drawEntries:l.map((t=>({entryStatus:Hc,entryStage:s,participantId:t}))),drawId:d,event:i,stage:s});return m.error?m:{...E}}function jv({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=Xa,drawSize:l=0}=u,m=l-i,f=d||o||a||p===Qa,h=f?t.slice(c,c+m):n[p||Xa]||[];f&&(c+=m);const g=Vv({autoEntryPositions:e,drawParticipants:h,tournamentRecord:r,drawProfile:u,event:s});if(g.error)return g}return{...E}}function Gv(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,uuids:m}=t;let f=d.gender,h=d.eventName;const{eventType:g=td,policyDefinitions:I,drawProfiles:U=[],eventExtensions:S,surfaceCategory:y,tieFormatName:v,processCodes:w,discipline:T,eventLevel:P,timeItems:D,ballType:b,category:N}=d,R=d.eventId||Md(),M=d.tieFormat||(g===id?ES({namedFormat:v,event:{eventId:R,category:N,gender:f},hydrateCollections:o}):void 0),A=u.participants;for(const t of U)!f&&t.gender&&(f=t?.gender);const{stageParticipantsCount:E,uniqueParticipantsCount:C,uniqueParticipantStages:O}=Tv({drawProfiles:U,category:N,gender:f}),F=g===td&&sc||g===nd&&uc||g,{uniqueDrawParticipants:k=[],uniqueParticipantIds:x=[]}=O?Bv({event:{eventType:g,category:N,gender:f},uniqueParticipantsCount:C,participantsProfile:r,ratingsParameters:c,tournamentRecord:u,eventProfile:d,eventIndex:p,uuids:m}):{};let{eventAttributes:_}=d;"object"!=typeof _&&(_={});const L=N?.categoryName||N?.ageCategoryCode||N?.ratingType;h=h||L||"Generated Event";const B={..._,surfaceCategory:y,processCodes:w,discipline:T,eventLevel:P,eventName:h,eventType:g,tieFormat:M,ballType:b,category:N,eventId:R,gender:f};if(S?.length&&Array.isArray(S)){const t=S.filter(br);t?.length&&Object.assign(B,{extensions:t})}if(Array.isArray(D)&&D.forEach((t=>Bm({event:G,timeItem:t}))),"object"==typeof I)for(const t of Object.keys(I))uU({policyDefinitions:{[t]:I[t]},event:B});let V;B.category&&(B.category.categoryName=L);const j=OS({suppressNotifications:!1,internalUse:!0,tournamentRecord:u,event:B});if(j.error)return j;const G=j?.event,{stageParticipants:q}=Pv({allUniqueParticipantIds:e,stageParticipantsCount:E,eventParticipantType:F,targetParticipants:A});if(U?.length){const t=jv({uniqueDrawParticipants:k,autoEntryPositions:a,stageParticipants:q,tournamentRecord:u,drawProfiles:U,category:N,gender:f,event:G});if(t.error)return t;const e=Lv({matchUpStatusProfile:n,completeAllMatchUps:i,randomWinningSide:s,tournamentRecord:u,drawProfiles:U,event:G});if(e.error)return e;V=e.drawIds}else if(d?.participantsProfile?.participantsCount){const t=k.map(Ua("participantId"));if(t.length){const e=cm({participantIds:t,autoEntryPositions:a,tournamentRecord:u,entryStage:Xa,event:G});if(e.error)return e}}return l&&Wm({tournamentRecord:u,event:G}),{drawIds:V,eventId:R,uniqueParticipantIds:x}}function qv({tournamentRecords:t}){if(!ha(t))return{error:x};const e=Object.keys(t??{}).reduce(((e,n)=>{const r=t[n],{tournamentInfo:{startDate:i,endDate:a}}=jm({tournamentRecord:r}),o=i&&new Date(ri(i));(!e.startDate||o&&o<e.startDate)&&(e.startDate=o);const s=a&&new Date(ri(a));return(!e.endDate||s&&s>e.endDate)&&(e.endDate=s),e}),{startDate:void 0,endDate:void 0}),n=e.startDate&&ri(e.startDate.toISOString()),r=e.endDate&&ri(e.endDate.toISOString());return n&&r?{startDate:n,endDate:r}:{error:oe}}function $v({tournamentRecords:t,scheduleDate:e,venueId:n,round:r}){if(!Wr(e))return{error:pe};const{extension:i}=Mr({name:oa,tournamentRecords:t,discover:!0}),a=i?.value||[];let o=a.find((t=>fi(e,t.scheduleDate)));if(!o){const{startDate:n,endDate:r}=qv({tournamentRecords:t}),i=new Date(e);if(n&&i<new Date(n)||r&&i>new Date(r))return{error:pe};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=>ha(t[e])?u(t[e]):t[e])).flat().join("|");if(s.rounds.find((t=>u(t)===u(r))))return wr({result:{error:gt},stack:"addSchedulingProfileRound"});s.rounds.push(r);const d=Fm({tournamentRecords:t,schedulingProfile:a});return d.error?d:{...E}}function Wv(t){const{allUniqueParticipantIds:e=[],participantsProfile:n={},matchUpStatusProfile:r,completeAllMatchUps:i,autoEntryPositions:o,hydrateCollections:s,randomWinningSide:c,ratingsParameters:u,tournamentRecord:d,isMock:p=!0,drawProfile:l,startDate:m,drawIndex:f,uuids:h}=t,g=gi(l,!1,!0),{excessParticipantAlternates:I=!0,matchUpFormat:U=lg,drawType:S=bo,tournamentAlternates:y=0,alternatesCount:v=0,qualifyingPositions:T,qualifyingProfiles:D,generate:b=!0,eventExtensions:N,drawExtensions:R,completionGoal:M,tieFormatName:A,seedsCount:C,timeItems:O,drawName:F,category:k,idPrefix:x,publish:_,gender:L,stage:B}=g,V=g.drawSize||(g.ignoreDefaults?void 0:32),j=g.eventId||Md(),G=l.eventType||l.matchUpType||td,$=G===nd?uc:sc,W="object"==typeof l.tieFormat&&l.tieFormat||G===dc&&ES({namedFormat:A,event:{eventId:j,category:k,gender:L},hydrateCollections:s})||void 0,H=k?.categoryName||k?.ageCategoryCode||k?.ratingType,z=l.eventName||H||`Generated ${G}`;let Y=d?.participants||[];const K=(D?.map((t=>t.structureProfiles||[])).flat().reduce(((t,e)=>t+(!e.participantsCount||e.participantsCount>e.drawSize?e.drawSize:e.participantsCount||0)),0)||0)*($===uc?2:1),J=(!l.participantsCount||l.participantsCount>V?V:l.participantsCount)||0,Z={eventName:z,eventType:G,tieFormat:W,category:k,eventId:j,gender:L};Array.isArray(O)&&O.forEach((t=>Bm({event:Z,timeItem:t})));let{eventAttributes:X}=l;if("object"!=typeof X&&(X={}),Object.assign(Z,X),N?.length&&Array.isArray(N)){const t=N.filter(br);t?.length&&Object.assign(Z,{extensions:t})}const Q=[];if(K||l.uniqueParticipants||!d||L||k){const t=(J||0)+v+K;let e=t;const r={[qp]:0,[Hp]:0};let i,a;G===dc&&(({teamSize:i,genders:a}=lv({alternatesCount:v,tieFormatName:A,tieFormat:W,drawSize:V})),Object.keys(a).forEach((t=>{[qp,Hp].includes(t)&&a[t]&&(r[t]=V*a[t])})),e=i*((V||0)+K));const o=n?.idPrefix?`D-${f}-${n?.idPrefix}`:void 0,s=uv({...n,scaledParticipantsCount:l.scaledParticipantsCount||n.scaledParticipantsCount,participantsCount:e,consideredDate:d?.startDate,sex:L||n?.sex,rankingRange:l.rankingRange,uuids:l.uuids||h,ratingsParameters:u,participantType:$,gendersCount:r,idPrefix:o,category:k}).participants;if(Z.category&&(Z.category.categoryName=H),d){const t=gU({participants:s,tournamentRecord:d});if(t.error)return t}if(s.forEach((({participantId:t})=>Q.push(t))),Y=s,G===dc){const e=a[qp]?s.filter((({participantType:t,person:e})=>t===sc&&e?.sex===qp)).map(Da):[],n=a[Hp]?s.filter((({participantType:t,person:e})=>t===sc&&e?.sex===Hp)).map(Da):[],r=s.filter((({participantType:t})=>t===sc)).map(Da).filter((t=>!e.includes(t)&&!n.includes(t))),o=i-(a[qp]+a[Hp]);let c=0,u=0,p=0;const l=w(0,t).map((t=>{const i=n.slice(c,c+a[Hp]),s=e.slice(u,u+a[qp]),d=r.slice(p,p+o);return c+=a[Hp],u+=a[qp],p+=o,{individualParticipantIds:[...i,...s,...d],participantOtherName:`TM${t+1}`,participantName:`Team ${t+1}`,participantRole:um,participantType:dc,participantId:Md()}})),m=gU({participants:l,tournamentRecord:d});if(!m.success)return m;Y=l}}const tt=t=>{const{participantType:e}=t;return G===td&&e===sc||(G===nd&&e===uc||G===dc&&e===dc)},et=t=>!l.gender||(t.person?.sex===l.gender||t.individualParticipantIds?.some((t=>{const e=Y.find((e=>e.participantId===t));return e&&et(e)}))),nt=Y.filter(tt).filter(et).filter((({participantId:t})=>!e.includes(t))),rt=nt.slice(0,J).map((t=>t.participantId));if(p&&rt?.length){const t=cm({autoEntryPositions:o,entryStage:B,tournamentRecord:d,participantIds:rt,event:Z});if(t.error)return t}const it=K?nt.slice(J,J+K).map((t=>t.participantId)):0;if(p&&it?.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,s=1;for(const c of i.structureProfiles.sort(n)){const n=(c.drawSize||a(c.participantsCount))-(r||0),i=it.slice(t,t+n),u=cm({entryStage:Qa,entryStageSequence:s,autoEntryPositions:o,tournamentRecord:d,participantIds:i,roundTarget:e,event:Z});if(u.error)return u;r=c.qualifyingPositions,t+=n,s+=1}e+=1}}const at=I&&d?.participants?.filter((({participantId:t})=>!rt.includes(t))).filter(tt).filter(et).slice(0,v||V-J||y).map((t=>t.participantId));if(p&&at?.length){const t=cm({participantIds:at,autoEntryPositions:!1,entryStatus:$c,tournamentRecord:d,event:Z});if(t.error)return t.error}const ot=H||z;if(d&&C&&C<=rt.length){w(1,C+1).forEach(((t,e)=>{const n={scaleName:ot,scaleDate:m,scaleType:$u,scaleValue:t,eventType:G},r=rt[e];Dv({tournamentRecord:d,participantId:r,scaleItem:n})}))}const st=QS({...gi(l,!1,!0),tournamentRecord:d,seedingScaleName:ot,matchUpFormat:U,eventId:j,isMock:p,event:Z});if(st.error)return st;if(!st.drawDefinition)return{error:q};const{drawDefinition:ct}=st,ut=ct.drawId;if(Array.isArray(R)&&R.filter(br).forEach((t=>Nr({element:ct,extension:t}))),b){if(hU({drawDefinition:ct,event:Z,suppressNotifications:!0}),l.withPlayoffs){const t=ct.structures?.[0].structureId,e=eU({...l.withPlayoffs,tournamentRecord:d,drawDefinition:ct,structureId:t,idPrefix:x,isMock:p,event:Z});if(e?.error)return e}const t=!1===l.automated;if(p&&!t){const t=t=>{const e=kv({completeAllMatchUps:t.completeAllMatchUps,completionGoal:t.completionGoal,matchUpStatusProfile:r,randomWinningSide:c,tournamentRecord:d,drawDefinition:ct,matchUpFormat:U,event:Z});if(e.error)return e;const n=e.completedCount;if(S===qo){const t=ct.structures?.find((t=>t.stage===Xa));if(!t)return{error:Ut};tg({structureId:t.structureId,tournamentRecord:d,drawDefinition:ct,event:Z});const e=kv({completionGoal:M?M?M-(n??0):void 0:void 0,matchUpStatusProfile:r,completeAllMatchUps:i,randomWinningSide:c,tournamentRecord:d,drawDefinition:ct,matchUpFormat:U,event:Z});if(e.error)return e}};if(M&&t({completionGoal:M}),l.outcomes){const{matchUps:t}=Ul({inContext:!0,drawDefinition:ct,event:Z});for(const e of l.outcomes){const{matchUpStatus:n=Ea,matchUpStatusCodes:r,stageSequence:i=1,matchUpIndex:a=0,structureOrder:o,matchUpFormat:s,drawPositions:c,roundPosition:u,stage:p=Xa,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!==P(c,t.drawPositions).length))),U=I?.[a],S=xv({matchUpStatusCodes:r,tournamentRecord:d,drawDefinition:ct,targetMatchUp:U,matchUpFormat:s,matchUpStatus:n,scoreString:f,winningSide:m});if(S?.error)return S}}i&&t({completeAllMatchUps:i})}_&&Wm({tournamentRecord:d,event:Z})}else{const t=$U({drawEntries:ct.entries,drawName:F||S,qualifyingPositions:T,drawId:ut,event:Z,stage:B});if(t.error)return t}return{...E,event:vr(Z),uniqueParticipantIds:Q,targetParticipants:Y,drawDefinition:ct,eventId:j,drawId:ut}}const Hv=["Mock Tournament","CourtHive Challenge","Racket Rally","Generated Tournament","Factory Follies","Open Competition"];function zv(){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 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 "}const Yv={generateOutcomeFromScoreString:Ay,anonymizeTournamentRecord:function({keepExtensions:t=[],anonymizeParticipantNames:e=!0,tournamentRecord:n,tournamentName:r,personIds:i=[],tournamentId:a}){if(!n)return{error:_};const o=Array.isArray(t)?pa.concat(...t):pa,s=e=>Array.isArray(t)?e?.extensions?.filter((t=>o.includes(t.name))):e?.extensions,c={};n.extensions=s(n);const u=a||Md();c[n.tournamentId]=u,n.tournamentId=u,n.createdAt=(new Date).toISOString(),n.tournamentName=r||`Anonymized: ${zr(new Date)}`,delete n.parentOrganisation;for(const t of n.participants||[]){const e=Md();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.extensions=s(t),t.venueName=`Venue #${d}`,t.venueAbbreviation=`V${d}`;const e=Md();c[t.venueId]=e,d+=1}let p=1;for(const t of n.events||[]){t.extensions=s(t);const e=Md();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=Md();if(c[e.drawId]=t,e.drawId=t,Array.isArray(e.entries))for(const t of e.entries)t.participantId=c[t.participantId];const n=t=>{t.extensions=s(t);const e=Md();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||[])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}=Mr({name:Ki,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||zr(new Date),m=(n.participants||[]).filter((({participantType:t})=>t===sc)),f=m.reduce(((t,e)=>{const n=e.person?.sex;return[qp,Hp].includes(n)?t[n]+=1:t[Wp]+=1,t}),{[qp]:0,[Hp]:0,[Wp]:0}),h=Object.assign({},...Object.keys(f).map((t=>({[t]:Ty({category:{ageCategoryCode:"O18"},count:f[t],addressProps:{citiesCount:10},personExtensions:[],consideredDate:l,sex:t})?.persons||[]})))),g={[qp]:0,[Hp]:0,[Wp]: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:[]}),S=U.postalCodes.length,y=U.cities.length,v=U.states.length,{cities:w}=Uy({count:y||I,participantsCount:I}),{states:T}=Sy({count:v||I,participantsCount:I}),{postalCodes:P}=yy({count:S||I,participantsCount:I}),D={cities:w,states:T,postalCodes:P};m.forEach(((t,n)=>{const r=t?.person,a=r?.sex||Wp,o=ri(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=Py({...D,participantIndex:n,nationalityCode:d.nationalityCode});d.addresses=[t]}d.personId=i?.[n]||Md(),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===uc)).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===dc)),N=by({count:b.length}).names;b.forEach(((t,e)=>{t.participantName=N[e]}));const R=(n.participants||[]).filter((({participantType:t})=>t===cc)),M=by({count:R.length,nameRoot:"Group"}).names;R.forEach(((t,e)=>{t.participantName=M[e]}));const{extension:A}=Mr({element:n,name:oa});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:C}=Mr({element:n,name:ea});return Array.isArray(C?.value)&&C?.value.forEach((t=>{t.personId=c[t.personId]})),{...E}},generateTournamentRecord:function(t){let{tournamentAttributes:e,startDate:n,endDate:r}=t;const{tournamentName:i=y(Hv),ratingsParameters:a=MU,scheduleCompletedMatchUps:o,tournamentExtensions:s,matchUpStatusProfile:c,completeAllMatchUps:u,participantsProfile:d,autoEntryPositions:p,hydrateCollections:l,randomWinningSide:f,policyDefinitions:h,schedulingProfile:g,periodLength:I,autoSchedule:U,eventProfiles:S,venueProfiles:v,drawProfiles:w,uuids:T}=t;if(n&&!Wr(n)||r&&!Wr(r))return{error:pe};if(S&&!Array.isArray(S))return{error:Nn};if(!n){const t=new Date;n=zr(r??t),r=zr(t.setDate(t.getDate()+7))}if(!r){const t=new Date(n);r=zr(t.setDate(t.getDate()+7))}"object"!=typeof e&&(e={});const D=sv({...e,tournamentName:i,startDate:n,endDate:r});if(s?.length&&Array.isArray(s)){const t=s.filter((t=>br({extension:t})));t?.length&&Object.assign(D,{extensions:t,isMock:!0})}if("object"==typeof h)for(const t of Object.keys(h))uU({policyDefinitions:{[t]:h[t]},tournamentRecord:D});const b=mv({participantsProfile:d,tournamentRecord:D,eventProfiles:S,drawProfiles:w,startDate:n,uuids:T});if(!b.success)return b;const N=[],R=[],M=[];if(Array.isArray(w)){let t=0;for(const e of w){let r=Wv({allUniqueParticipantIds:N,matchUpStatusProfile:c,participantsProfile:d,completeAllMatchUps:u,autoEntryPositions:p,hydrateCollections:l,randomWinningSide:f,ratingsParameters:a,tournamentRecord:D,isMock:!0,drawProfile:e,startDate:n,drawIndex:t,uuids:T});if(r.error)return r;const{drawId:i,eventId:o,event:s,uniqueParticipantIds:m}=r;if(r=OS({suppressNotifications:!1,internalUse:!0,tournamentRecord:D,event:s}),r.error)return r;i&&M.push(i),R.push(o),m?.length&&N.push(...m),t+=1}}if(S){let t=0;for(const e of S){const r=Gv({allUniqueParticipantIds:N,matchUpStatusProfile:c,participantsProfile:d,completeAllMatchUps:u,autoEntryPositions:p,hydrateCollections:l,randomWinningSide:f,ratingsParameters:a,tournamentRecord:D,eventProfile:e,eventIndex:t,startDate:n,uuids:T});if(r.error)return r;const{eventId:i,drawIds:o,uniqueParticipantIds:s}=r;o&&M.push(...o),R.push(i),s?.length&&N.push(...s),t+=1}}const A=v?.length?wv({tournamentRecord:D,venueProfiles:v,uuids:T}):[];let C,O={};if(g){const t=function({schedulingProfile:t,tournamentRecord:e}){if("object"!=typeof t)return{error:Nn};const n=qs({tournamentRecord:e}).containedStructures,r=hl({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!==P(n,e).length&&(m(n).length!==m(e).length||P(n,e).length!==m(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=$v({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:g,tournamentRecord:D});if(t.error)return t;if(C=t.scheduledRounds,U){const{tournamentId:t}=D;O=ov({scheduleCompletedMatchUps:o,tournamentRecords:{[t]:D},periodLength:I})}}return or(),vr({...E,tournamentRecord:D,scheduledRounds:C,schedulerResult:O,eventIds:R,venueIds:A,drawIds:M})},modifyTournamentRecord:function(t){const{ratingsParameters:e=MU,participantsProfile:n={},matchUpStatusProfile:r,completeAllMatchUps:i,autoEntryPositions:a,hydrateCollections:o,randomWinningSide:s,schedulingProfile:c,tournamentRecord:u,eventProfiles:d,periodLength:p,venueProfiles:l,autoSchedule:m,drawProfiles:f,uuids:h}=t;if(!u)return{error:_};const g=[],I=[],U=[];d?.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 y=mv({startDate:u.startDate,participantsProfile:n,tournamentRecord:u,eventProfiles:d,drawProfiles:f,uuids:h});if(!y.success)return y;if(d){let t=u.events?.length||0;for(const e of d){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=p===td&&sc||p===nd&&uc||p;if(l){const{stageParticipantsCount:m,uniqueParticipantsCount:I,uniqueParticipantStages:S}=Tv({drawProfiles:l,category:d,gender:t}),{uniqueDrawParticipants:y=[],uniqueParticipantIds:v=[]}=S?Bv({event:{eventType:p,category:d,gender:t},uniqueParticipantsCount:I,participantsProfile:n,ratingsParameters:o,tournamentRecord:u,eventProfile:e,uuids:h}):{};g.push(...v);const{stageParticipants:w}=Pv({targetParticipants:u.participants||[],allUniqueParticipantIds:g,stageParticipantsCount:m,eventParticipantType:f});let T=jv({uniqueDrawParticipants:y,autoEntryPositions:a,stageParticipants:w,tournamentRecord:u,drawProfiles:l,category:d,gender:t,event:c});if(T.error)return T;if(T=Lv({matchUpStatusProfile:r,completeAllMatchUps:i,randomWinningSide:s,tournamentRecord:u,drawProfiles:l,event:c}),T.error)return T;U.push(...T.drawIds)}m&&Wm({tournamentRecord:u,event:c})}else{const c=Gv({startDate:u.startDate,allUniqueParticipantIds:g,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:i,autoEntryPositions:a,randomWinningSide:s,ratingsParameters:o,tournamentRecord:u,eventProfile:e,eventIndex:t,uuids:h});if(c.error)return c;const{eventId:d,drawIds:p,uniqueParticipantIds:l}=c;p&&U.push(...p),I.push(d),l?.length&&g.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=Wv({startDate:u.startDate,allUniqueParticipantIds:g,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:i,autoEntryPositions:a,hydrateCollections:o,randomWinningSide:s,ratingsParameters:e,tournamentRecord:u,drawProfile:c,drawIndex:t,uuids:h});if(d.error)return d;const{drawId:p,eventId:l,event:m,uniqueParticipantIds:f}=d;if(d=OS({tournamentRecord:u,event:m,internalUse:!0}),d.error)return d;p&&U.push(p),I.push(l),f?.length&&g.push(...f),t+=1}}const v=l?.length?wv({tournamentRecord:u,venueProfiles:l}):[];let w={};if(c?.length){const t=Fm({tournamentRecords:{[u.tournamentId]:u},schedulingProfile:c});if(t.error)return t;if(m){const{tournamentId:t}=u;w=ov({tournamentRecords:{[t]:u},periodLength:p})}}return{totalParticipantsCount:u.participants.length,scheduledRounds:undefined,schedulerResult:w,...E,eventIds:I,venueIds:v,drawIds:U}},generateEventWithDraw:Wv,generateParticipants:uv,parseScoreString:My,generateOutcome:Ov,credits:zv};function Kv({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=vm(e?.standardGivenName??""),s=vm(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 Jv({participantMap:t,participant:e,formats:n}){const{participantType:r,individualParticipantIds:i,person:a}=e,o=r&&n[r];if(r!==oc&&o){const{personFormat:n,doublesJoiner:s}=o;r===sc&&(e.participantName=Kv({person:a,personFormat:n})),r===uc&&(e.participantName=i?.map((e=>{const r=t[e]?.person;return Kv({person:r,personFormat:n})})).filter(Boolean).join(s??"/"))}}function Zv({tournamentRecord:t,penaltyId:e}){if(!t)return{error:_};if(!e)return{error:Ze};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&&sr({topic:Ss,payload:{tournamentId:t.tournamentId,participants:n}}),r?{...E,penalty:r}:{error:Xe}}const Xv=({penaltyId:t=Md()}={})=>({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 Qv({tournamentRecord:t,modifications:e,penaltyId:n}){if(!t)return{error:_};if(!e)return{error:Nn,modifications:e};if(!n)return{error:Ze};const r=t?.participants??[],i=Object.keys(Xv()).filter((t=>"penaltyId"!==t)),a=Object.keys(e).filter((t=>i.includes(t)));if(!a.length)return{error:En};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&&sr({topic:Ss,payload:{tournamentId:t.tournamentId,participants:s}}),o?{...E,penalty:o}:{error:Xe}}function tw(t,e,n){if(!t&&e)return e;if(t&&!e)return t;if("object"!=typeof t||"object"!=typeof e)return t;return m(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=m(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]=tw(t[i],e[i],n):r[i]=e[i];else r[i]=e[i];else r[i]=t[i];return r}),{})}function ew({refereeParticipantId:t,tournamentRecord:e,participantIds:n,penaltyCode:r,penaltyType:i,extensions:a,penaltyId:o,matchUpId:s,issuedAt:c,notes:u}){if(!e)return{error:_};if(!n)return{error:Ae};if(!i)return{error:Je};const d=(e?.participants??[]).filter((t=>n.includes(t.participantId)));if(!d.length)return{error:Ee};const p=(new Date).toISOString(),l=Object.assign(Xv({penaltyId:o}),{refereeParticipantId:t,penaltyCode:r,penaltyType:i,matchUpId:s,notes:u,issuedAt:c,createdAt:p});return Array.isArray(a)&&a.forEach((t=>Nr({element:l,extension:t}))),d.forEach((t=>{t.penalties||(t.penalties=[]),t.penalties.push(l)})),sr({topic:Ss,payload:{tournamentId:e.tournamentId,participants:d}}),{...E,penaltyId:l.penaltyId}}const nw={addIndividualParticipantIds:qf,addParticipant:Bf,addParticipants:gU,addPenalty:function(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=Zl({tournamentRecord:e}).participants??[],a=r?.map(Ua("participantId")).filter((t=>n.includes(t)));if(a.length){i=ew({...t,penaltyId:t.penaltyId??i,tournamentRecord:e,participantIds:a}).penaltyId}}return i?{...E,penaltyId:i}:{error:Ee}},addPersons:function({participantRole:t=um,tournamentRecord:e,persons:n}){if(!e)return{error:_};if(!Array.isArray(n))return{error:Nn};if(!Object.keys(lm).includes(t))return{error:De};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=Md()),i.push(t.personId),t)));let o=0,s=0,c=gU({participants:a.map((e=>{return vr({extensions:e.participantExtensions,timeItems:e.participantTimeItems,participantType:sc,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=Zl({participantFilters:{participantTypes:[sc]},tournamentRecord:e})?.participants??[];if(t===um&&n.filter((({pairedPersons:t})=>t)).forEach((({personId:t,pairedPersons:e})=>{Array.isArray(e)&&e.forEach((e=>{const n=[t,e.personId].map((t=>Fi({tournamentParticipants:d,personId:t}))).filter(Boolean);if(2===n.length){const t=n.map(Da);u.push(vr({extensions:e.participantExtensions,timeItems:e.timeItems,participantRole:um,individualParticipantIds:t,participantType:uc}))}}))})),u.length){if(c=gU({participants:u,tournamentRecord:e}),c.error)return c;o=c.addedCount||0}const p=s+o;return{...E,addedCount:p,newPersonIds:i}},createGroupParticipant:function({individualParticipantIds:t=[],participantRoleResponsibilities:e,participantRole:n=pm,tournamentRecord:r,participantId:i,groupName:a}){if(!r)return{error:_};if(!a)return{error:ae,info:"Missing groupName"};if(!Array.isArray(t))return{info:"Invalid individualParticipantIds",error:Nn};const o=(Zl({participantFilters:{participantTypes:[sc]},tournamentRecord:r}).participants??[]).map((t=>t.participantId));for(const e of t)if(!o.includes(e))return{error:be,participantId:e};const s=vr({participantId:i||Md(),participantRoleResponsibilities:e,participantName:a,individualParticipantIds:t,participantType:cc,participantRole:n}),c=Bf({participant:s,tournamentRecord:r});if(c.error)return c;const{topics:u}=lr();return u.includes(ss)&&sr({topic:ss,payload:{tournamentId:r.tournamentId,participants:[s]}}),{...E,participant:gi(s)}},createTeamsFromParticipantAttributes:cv,deleteParticipants:gm,filterParticipants:Kl,mergeParticipants:function({participants:t=[],tournamentRecord:e,arraysToMerge:n}){if(!e)return{error:_};e.participants||(e.participants=[]);const r=t.filter(Ua(lp)).map((t=>({[t.participantId]:t}))),i=Object.assign({},...r),a=[];e.participants=e.participants.map((t=>{if(i[t.participantId]){const e=tw(t,i[t.participantId],n);return a.push(e),e}return t}));const o=e.participants.map(Ua(lp))||[],s=t.filter((({participantId:t})=>!o.includes(t))),{topics:c}=lr();return s.length&&(e.participants=e.participants.concat(...s),c.includes(ss)&&sr({topic:ss,payload:{participants:s}})),a.length&&c.includes(Ss)&&sr({topic:Ss,payload:{tournamentId:e.tournamentId,participants:a}}),{modifiedParticipantsCount:a.length,newParticipantsCount:s.length,...E}},modifyIndividualParticipantIds:function({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}){const r="modifyIndividualParticipantIds";if(!n)return wr({result:{error:_},stack:r});if(!e||!t)return wr({result:{error:ae},stack:r});const i=n.participants||[],a=i.find((t=>t.participantId===e));if(!a)return wr({result:{error:Ee},stack:r});if(![dc,cc].includes(a.participantType))return wr({result:{error:be},context:{participantType:a.participantType},stack:r});const o=t.filter((t=>{const e=i.find((e=>e.participantId===t));return e?.participantType!==sc}));if(o.length)return wr({result:{error:Pe,invalidParticipantIds:o},stack:r});const s=a.individualParticipantIds||[],c=t.filter((t=>!s.includes(t))),u=s.filter((e=>!t.includes(e))),d=qf({individualParticipantIds:c,groupingParticipantId:e,tournamentRecord:n});if(d.error)return wr({result:d,stack:r});const p=mm({individualParticipantIds:u,groupingParticipantId:e,tournamentRecord:n});if(p.error)return wr({result:p,stack:r});const{topics:l}=lr();if(l.includes(Ss)){const t=i.find((({participantId:t})=>t===e));sr({topic:Ss,payload:{tournamentId:n.tournamentId,participants:[t]}})}return{...d,...p}},modifyParticipant:$f,modifyParticipantName:function({tournamentRecord:t,participantName:e,participantId:n}){if(!t)return{error:_};if(!n)return{error:Ae};if(!e)return{error:ae,info:"Missing participantName"};const{participant:r}=rl({tournamentRecord:t,participantId:n});if(!r)return{error:Ee};r.participantName=e;const{topics:i}=lr();return i.includes(Ss)&&sr({topic:Ss,payload:{tournamentId:t.tournamentId,participants:[r]}}),{...E}},modifyParticipantOtherName:function({tournamentRecord:t,participantId:e,participantOtherName:n}){if(!t)return{error:_};if(!e)return{error:Ae};const{participant:r}=rl({tournamentRecord:t,participantId:e});if(!r)return{error:Ee};r.participantOtherName=n;const{topics:i}=lr();return i.includes(Ss)&&sr({topic:Ss,payload:{tournamentId:t.tournamentId,participants:[r]}}),{...E}},modifyParticipantsSignInStatus:function({tournamentRecord:t,participantIds:e,signInState:n}){if(!t)return{error:_};if(!Array.isArray(e))return{error:ae};if(![ac,ic].includes(n))return{error:Nn,signInState:n};const r=t.participants||[];if(!r.length)return{error:Me};const i=r.map(Da),a=e.filter((t=>!i.includes(t)));if(a.length)return{error:Nn,context:{invalidParticipantIds:a}};const o=[],s=(new Date).toISOString();for(const i of r){const{participantId:r}=i;if(e.includes(r)){const e=_m({duplicateValues:!1,tournamentRecord:t,participantId:r,timeItem:{itemType:rc,itemValue:n,createdAt:s}});if(e.error)return e;o.push(i)}}const{topics:c}=lr();return o.length&&c.includes(Ss)&&sr({topic:Ss,payload:{tournamentId:t.tournamentId,participants:o}}),{...E}},modifyPenalty:function(t){const{tournamentRecords:e}=t;if("object"!=typeof e||!Object.keys(e).length)return{error:x};for(const n of Object.values(e)){const e=Qv({...t,tournamentRecord:n});if(e.error&&e.error!==Xe)return e;if(e.success)return e}return{error:Xe}},regenerateParticipantNames:function({tournamentRecord:t,formats:e}){if(!t)return{error:_};if(!ha(e))return{error:ae};const n=t.participants??[],r=Ia(n,"participantId");for(const t of n)Jv({participant:t,participantMap:r,formats:e});return{...E}},removeIndividualParticipantIds:mm,removeParticipantIdsFromAllTeams:hm,removePenalty:function(t){const{tournamentRecords:e}=t;if("object"!=typeof e||!Object.keys(e).length)return{error:x};for(const n of Object.values(e)){const e=Zv({...t,tournamentRecord:n});if(e.error&&e.error!==Xe)return e}return{...E}},scaledTeamAssignment:function({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:l}){if(!o)return{error:_};if(!Array.isArray(a)&&!p(u)&&!d||!p(r)||i&&!Array.isArray(i)||s&&("object"!=typeof s||!Object.keys(s).length))return{error:Nn};if(!s&&!i.length||!i&&(!e||!s))return{error:ae,info:"Missing scaling details"};if(d&&!a){if(l?.eventType!==ad)return{error:wt};a=l?.entries?.filter((({entryStatus:t})=>t===Hc)).map(Da)}if(!a?.length&&!u)return{info:"Missing teamParticipantIds or teamsCount",error:ae};let m=e??i.map((({participantId:t})=>t));n&&(a?.reverse(),r+=1),r>(a?.length||0)-1&&(r=0);const f=a?.slice(r).concat(...a.slice(0,r))??[],h=[];for(const t of o.participants??[]){const{participantId:e,participantType:n}=t;if(f.includes(e)){if(n!==oc)return{error:be,participant:t};h.push(t)}}if(u&&h.length<u){const t=c??"Team",e=w(0,u-(h?.length||0)).map((e=>({participantName:`${t} ${e+1}`,participantType:oc,participantRole:um}))),{participants:n=[]}=gU({participants:e,returnParticipants:!0,tournamentRecord:o}),r=n.map(Da),i=o.participants?.filter((({participantId:t})=>r.includes(t)))??[];h.push(...i)}if(!h.length)return{error:Mn};if(t)for(const t of h)t.individualParticipantIds=[];else{const t=h.map((t=>t)).flat();e?.length?m=m.filter((e=>!t.includes(e))):i=i?.filter((({participantId:e})=>!t.includes(e)))}if(!e?.length&&!i?.length)return{error:vn,info:"Nothing to be done"};if(!i.length){for(const t of o.participants??[]){const{participantId:e,participantType:n}=t;if(!m.includes(e))continue;if(n!==sc)return{error:be,participant:t};const r=Vl({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:Ee}}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:Nn,scaledParticipant:t};let g=0;for(;g<i.length;){for(const t of h){if(g+1>i.length)break;const e=i[g];t.individualParticipantIds.push(e.participantId),g++}h.reverse()}const I=h.map(Da);for(const t of o.events??[]){if(t.eventType!==ad)continue;const e=(t.entries??[]).filter((t=>I.includes(t.participantId)));for(const n of e){const e=n.participantId,r=h.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}=Bd({event:t});(a?.flights||[]).forEach((t=>{t.drawEntries=(t.drawEntries||[]).filter((t=>!i.includes(t.participantId)))}))}}return{...E,scaledParticipants:i}},setParticipantScaleItem:Dv,setParticipantScaleItems:function(t){const{scaleItemsWithParticipantIds:e=[],removePriorValues:n,tournamentRecord:r,auditData:i,context:a}=t;if(!r)return{error:_};if(!r.participants)return{error:Me};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(!bv({scaleItem:n}))return{error:In};Array.isArray(s[e])||(s[e]=[]),s[e].push(n)}}r.participants.forEach((t=>{const{participantId:e}=t||{};Array.isArray(s[e])&&s[e].forEach((e=>{Nv({participant:t,scaleItem:e,removePriorValues:n}),c.push(t),o++}))}));const u=o?void 0:Sn,{topics:d}=lr();if(d.includes(Ss)&&o&&sr({topic:Ss,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:cs,itemValue:n};if(i&&(a.itemSubTypes=i),e||t){const{drawDefinition:n,event:i}=Vd({tournamentRecord:r,eventId:t,drawId:e});e&&RI({drawDefinition:n,timeItem:a}),t&&Bm({event:i,timeItem:a})}else Lm({tournamentRecord:r,timeItem:a})}}return i&&d.includes(ds)&&sr({topic:ds,payload:i}),vr({...E,modificationsApplied:o,info:u})}};function rw(t,e){const n=Dc(t).appliedPolicies??{};if(n[t.policyType]){if(delete n[t.policyType],Object.keys(n).length){Nr({element:e,extension:{name:Vi,value:n}})}else Dr({element:e,name:Vi});return{...E}}return{error:ee}}const iw={attachPolicies:uU,removePolicy:function(t){const e=Lp(t,[{policyType:!0,_anyOf:{[sp]:!0,[up]:!0,[dp]:!0,[Rp]:!0}}]);if(e.error)return e;let n;const r=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(r)return rw(t,r);if(!t.tournamentRecords)return{error:_};{const e=Object.keys(t.tournamentRecords);if(!e.length)return{error:_};for(const r of e){const e=rw(t,t.tournamentRecords[r]);if(e.error)return e;n=!0}}return n?{...E}:{error:ee}}};function aw({removePriorValues:t=!0,tournamentRecord:e,status:n=Hu}){if(!e)return{error:_};const r=`${Wu}.${zu}`,{timeItem:i}=il({element:e,itemType:r}),a=i?.itemValue||{[n]:{}};a[n]&&delete a[n].orderOfPlay;return xm({timeItem:{itemValue:a,itemType:r},element:e,removePriorValues:t}),sr({topic:As,payload:{tournamentId:e.tournamentId}}),{...E}}function ow({scheduledDates:t=[],removePriorValues:e,tournamentRecord:n,status:r=Hu,eventIds:i=[]}){if(!n)return{error:_};const a=`${Wu}.${zu}`,{timeItem:o}=il({element:n,itemType:a}),s=o?.itemValue||{[r]:{}};s[r].orderOfPlay={published:!0,scheduledDates:t,eventIds:i};return xm({timeItem:{itemValue:s,itemType:a},element:n,removePriorValues:e}),sr({topic:Ns,payload:{tournamentId:n.tournamentId,scheduledDates:t,eventIds:i}}),{...E}}const sw={getTournamentInfo:jm,getVenueData:kd,getCourtInfo:Fd,getAllEventData:function({tournamentRecord:t,policyDefinitions:e}){if(!t)return{error:_};const n=t.events||[],r=t?.participants||[],{tournamentInfo:i}=jm({tournamentRecord:t}),{venues:a}=Am({tournamentRecord:t});return{allEventData:{tournamentInfo:i,venuesData:a,eventsData:n.map((n=>{const{eventId:i}=n,a=(({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}))(n),o=Qu({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}=Zp({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=Gl({event:n});return Object.assign(a,{drawsData:s,publish:c}),a}))}}},getEventData:$m,getDrawData:qm,unPublishEventSeeding:function({removePriorValues:t=!0,seedingScaleNames:e,tournamentRecord:n,status:r=Hu,drawIds:i,stages:a,event:o}){if(!n)return{error:_};if(!o)return{error:Tt};const s=Gl({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),Vm({statusObject:{seeding:n},removePriorValues:t,status:r,event:o})}return sr({topic:Ms,payload:{tournamentId:n.tournamentId,eventId:o.eventId}}),{...E}},publishEventSeeding:function({removePriorValues:t=!0,stageSeedingScaleNames:e,seedingScaleNames:n,tournamentRecord:r,status:i=Hu,drawIds:a=[],event:o}){if(!r)return{error:_};if(!o)return{error:Tt};const s=Gl({event:o,status:i}),c=(s?.seeding?.seedingScaleNames||n)&&{...s?.seeding?.seedingScaleNames,...n};return Vm({statusObject:{seeding:vr({stageSeedingScaleNames:(s?.seeding?.stageSeedingScaleNames||e)&&{...s?.seeding?.stageSeedingScaleNames,...e},seedingScaleNames:c,published:!0,drawIds:a})},removePriorValues:t,status:i,event:o}),sr({topic:bs,payload:{tournamentId:r.tournamentId,eventId:o.eventId,drawIds:a}}),{...E}},setEventDisplay:function({removePriorValues:t,tournamentRecord:e,displaySettings:n,status:r=Hu,event:i}){if(!e)return wr({result:{error:_}});if(!i)return wr({result:{error:Tt}});if(!ha(n))return wr({result:{error:ae}});if(ha(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=>ga(e.attributes,t.attributes)));e?.dates&&t.dates?e.dates.push(...t.dates):r.push(t)}n.draws[t].scheduleDetails=r}}const a=Vm({statusObject:{displaySettings:n},removePriorValues:t,status:r,event:i});return a.error?a:{...E}},unPublishEvent:function({removePriorValues:t=!0,tournamentRecord:e,status:n=Hu,event:r}){if(!e)return{error:_};if(!r)return{error:Tt};const i=`${Wu}.${zu}`,{timeItem:a}=al({itemType:i,event:r}),o=a?.itemValue||{[n]:{}};return delete o[n].structureIds,delete o[n].drawDetails,delete o[n].drawIds,Bm({event:r,timeItem:{itemValue:o,itemType:i},removePriorValues:t}),Vm({statusObject:{structureIds:void 0,drawIds:void 0,seeding:void 0},removePriorValues:t,status:n,event:r}),sr({topic:Rs,payload:{tournamentId:e.tournamentId,eventId:r.eventId}}),{eventId:r.eventId,...E}},publishEvent:Wm,unPublishOrderOfPlay:function(t){const e=t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{};if(!Object.keys(e).length)return{error:x};for(const n of Object.values(e)){const e=aw({tournamentRecord:n,...t});if(e.error)return e}return{...E}},publishOrderOfPlay:function(t){const e=nc(t);if(!Object.keys(e).length)return{error:x};for(const n of Object.values(e)){const e=ow({tournamentRecord:n,...t});if(e.error)return e}return{...E}}};function cw({tournamentRecords:t,extensionName:e}){if("object"!=typeof t||!Object.keys(t).length)return{error:x};const n=[];let r;for(const i of Object.values(t)){const{extension:t}=Mr({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}=Mr({name:e,element:t});i&&n.push({params:{eventId:r,extension:i},method:"addEventExtension"})}}return{methods:n}}const uw="ADULT",dw="JUNIOR",pw="WHEELCHAIR",lw={[Ni]:{allowModificationWhenMatchUpsScheduled:{courts:!1,venues:!1},defaultTimes:{averageTimes:[{categoryNames:[],minutes:{default:90}}],recoveryTimes:[{minutes:{[Zs]:30,default:60}}]},defaultDailyLimits:{[Ks]:2,[Zs]:2,total:3},matchUpAverageTimes:[{matchUpFormatCodes:[lg],averageTimes:[{categoryNames:[],minutes:{default:90}},{categoryTypes:[pw],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:[uw,pw],minutes:{default:60,[Zs]:30}},{categoryTypes:[dw],minutes:{default:60,[Zs]: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:[uw,pw],minutes:{default:30}},{categoryTypes:[dw],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:[uw,dw],minutes:{default:30}},{categoryTypes:[pw],minutes:{default:15}}]},{matchUpFormatCodes:["SET1-S:TB10"],recoveryTimes:[{categoryNames:[],minutes:{default:15}}]}],matchUpDailyLimits:[]}};function mw(t){const e=Lp(t,[{[up]:!0},{[Op]:kt,[Cp]:rh,[pp]:!0}]);if(e.error)return e;const{tournamentRecord:n,matchUpFormat:r,event:i}=t,{extension:a}=Mr({name:aa,element:i}),o=a?.value,{extension:s}=Mr({element:n,name:aa}),c=s?.value,u=[o?.matchUpAverageTimes&&Ju({...o,matchUpFormat:r}),c?.matchUpAverageTimes&&Ju({...c,matchUpFormat:r})].find((t=>t));return{matchUpFormat:r,recoveryTimes:[o?.matchUpRecoveryTimes&&Zu({...o,matchUpFormat:r}),c?.matchUpRecoveryTimes&&Zu({...c,matchUpFormat:r})].find((t=>t)),averageTimes:u}}function fw({tournamentRecord:t}){if(!t)return{error:_};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 hw({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&&ri(e.scheduledDate)||e.scheduledTime&&ri(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&&ni(e.scheduledTime)||"noScheduledTime";o[n]||(o[n]=[]),o[n].push(t)}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 gw({courtPrefix:t="C|",minRowsCount:e,courtsData:n}){if(!Array.isArray(n))return{error:Nn};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=w(0,e?Math.max(e,r):r).map((t=>({matchUps:w(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}))))))}}function Iw(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:S}=t;if(!S)return{error:Tt};const{eventId:y,eventName:v,endDate:w}=S,T={...U,...vr({eventId:y,eventName:v,endDate:w??d?.endDate,tournamentId:g??d?.tournamentId,indoorOutDoor:S.indoorOutdoor??d?.indoorOutdoor,surfaceCategory:S.surfaceCategory??d?.surfaceCategory})};let P;!e&&d&&({participants:e,participantMap:r,groupInfo:P}=ml({participantsProfile:o,policyDefinitions:c,useParticipantMap:u,tournamentRecord:d,contextProfile:f,inContext:I})),f&&!n&&(n=Fc({policyDefinitions:c,tournamentRecord:d,contextProfile:f,event:S}));const D=Gl({event:S});return{...(S.drawDefinitions??[]).reduce(((t,u)=>{const g=Zp({context:T,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:D,contextProfile:f,drawDefinition:u,nextMatchUps:h,inContext:I,event:S}),U=Object.keys(g);return U?.forEach((e=>{Array.isArray(g[e])&&(t[e]||(t[e]=[]),t[e]=t[e].concat(g[e]))})),t}),{}),...E,groupInfo:P}}function Uw(t){if(!t?.tournamentRecord)return{error:_};let e=t.contextContent;const{scheduleVisibilityFilters:n,participantsProfile:r,afterRecoveryTimes:i,policyDefinitions:a,useParticipantMap:o,tournamentRecord:s,inContext:c=!0,usePublishState:u,contextFilters:d,matchUpFilters:p,contextProfile:l,nextMatchUps:m,context:f}=t,h=t.tournamentId??s.tournamentId,g=s?.events??[],{participants:I,participantMap:U,groupInfo:S}=ml({participantsProfile:r,policyDefinitions:a,useParticipantMap:o,tournamentRecord:s,contextProfile:l,inContext:c});l&&!e&&(e=Fc({policyDefinitions:a,tournamentRecord:s,contextProfile:l}));const{appliedPolicies:y}=Dc({tournamentRecord:s}),v=d?.eventIds??[];return{...g.filter((t=>!v.includes(t.eventId))).map((t=>{const o=Bd({event:t}).flightProfile;return Iw({context:{eventDrawsCount:o?.flights?.length||t.drawDefinitions?.length||0,...f},tournamentAppliedPolicies:y,scheduleVisibilityFilters:n,participantsProfile:r,afterRecoveryTimes:i,policyDefinitions:a,tournamentRecord:s,usePublishState:u,contextFilters:d,contextProfile:l,contextContent:e,matchUpFilters:p,participantMap:U,participants:I,tournamentId:h,nextMatchUps:m,inContext:c,event:t})})).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]),t.matchUpsCount+=e[n].length)})),t}),{matchUpsCount:0}),groupInfo:S}}function Sw({scheduleVisibilityFilters:t,participantsProfile:e,tournamentRecords:n,policyDefinitions:r,usePublishState:i,matchUpFilters:a,contextFilters:o,nextMatchUps:s,inContext:c}){if("object"!=typeof n||!Object.keys(n).length)return{error:x};const u=Object.keys(n).map((u=>{const d=n[u];return Uw({scheduleVisibilityFilters:t,participantsProfile:e,policyDefinitions:r,tournamentRecord:d,usePublishState:i,matchUpFilters:a,contextFilters:o,nextMatchUps:s,inContext:c})})),d={};return{...u.reduce(((t,e)=>(Object.keys(e).forEach((n=>{Array.isArray(e[n])&&(t[n]||(t[n]=[]),t[n]=t[n].concat(e[n])),"groupInfo"===n&&Object.assign(d,e[n])})),t)),{}),groupInfo:d}}function yw(t){if("object"!=typeof t?.tournamentRecords||!Object.keys(t?.tournamentRecords).length)return{error:x};const{courts:e,venues:n}=Am(t),r=Om(t).schedulingProfile,{sortDateMatchUps:i=!0,courtCompletedMatchUps:a,alwaysReturnCompleted:o,activeTournamentId:s,tournamentRecords:c,withCourtGridRows:u,minCourtGridRows:d,usePublishState:p,status:l=Hu,sortCourtsData:m}=t,f=p?ol({tournamentRecord:c[s??fr()],itemType:`${Wu}.${zu}`}).timeItem?.itemValue?.[l]:void 0,h=o?Sw({...t,matchUpFilters:{...t.matchUpFilters,matchUpStatuses:[Ea]},contextFilters:t.contextFilters}).completedMatchUps:[];if(p&&(!f||!Object.keys(f).length))return{completedMatchUps:h,dateMatchUps:[],courtsData:[],venues:n};let g,I;p&&({drawIds:g,detailsMap:I}=function({tournamentRecords:t}){const e=[],n={};for(const r of Object.values(t))for(const t of r.events??[]){const r=Gl({event:t}),i=r?.drawDetails;ha(i)?(Object.assign(n,i),e.push(...Object.keys(i).filter((t=>ql({drawId:t,drawDetails:i}))))):r?.drawIds?.length&&e.push(...r.drawIds)}return{drawIds:e,detailsMap:n}}({tournamentRecords:c})),g?.length&&(t.contextFilters||(t.contextFilters={}),t.contextFilters?.drawIds?t.contextFilters.drawIds=t.contextFilters.drawIds.filter((t=>g.includes(t))):t.contextFilters.drawIds=g),f?.eventIds?.length&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters?.eventIds&&t.matchUpFilters.eventIds.length?t.matchUpFilters.eventIds=t.matchUpFilters.eventIds.filter((t=>f.eventIds.includes(t))):t.matchUpFilters.eventIds=f.eventIds),f?.scheduledDates?.length&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters.scheduledDates&&t.matchUpFilters.scheduledDates.length?t.matchUpFilters.scheduledDates=t.matchUpFilters.scheduledDates.filter((t=>f.scheduledDates.includes(t))):t.matchUpFilters.scheduledDates=f.scheduledDates),o&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters?.excludeMatchUpStatuses?.length?t.matchUpFilters.excludeMatchUpStatuses.includes(Ea)||t.matchUpFilters.excludeMatchUpStatuses.push(Ea):t.matchUpFilters.excludeMatchUpStatuses=[Ea]);const{completedMatchUps:U,upcomingMatchUps:S,pendingMatchUps:y,groupInfo:v}=Sw({...t,matchUpFilters:t.matchUpFilters,contextFilters:t.contextFilters});let w=[...S??[],...y??[]];I&&Object.keys(I).length&&(w=w.filter((t=>{const{drawId:e,structureId:n,stage:r}=t;if(!I[e])return!1;if(I[e].stageDetails){const t=Object.keys(I[e].stageDetails),n=t.filter((t=>!I[e].stageDetails[t].published)),i=t.filter((t=>I[e].stageDetails[t].published));return(!n.length||!n.includes(r))&&(!(!i.length||!i.includes(r))||n.length&&!n.includes(r)&&!i.length)}if(I[e].structureDetails){const t=Object.keys(I[e].structureDetails),r=t.filter((t=>!I[e].structureDetails[t].published)),i=t.filter((t=>I[e].structureDetails[t].published));return(!r.length||!r.includes(n))&&(!(!i.length||!i.includes(n))||r.length&&!r.includes(n)&&!i.length)}return!0})));const T=i?hw({matchUps:w,schedulingProfile:r}):w,P=e?.map((t=>{const e=function({courtId:t}){const e=(a?T.concat(U??[]):T).filter((e=>e.schedule?.courtId===t||e.schedule?.allocatedCourts?.map((({courtId:t})=>t)).includes(t)));return m?hw({matchUps:e,schedulingProfile:r}):e}(t);return{surfaceCategory:t?.surfaceCategory??"",matchUps:e,...t}})),D={completedMatchUps:o?h:U,dateMatchUps:T,courtsData:P,groupInfo:v,venues:n};if(u){const{rows:t,courtPrefix:e}=gw({minRowsCount:d,courtsData:P});D.courtPrefix=e,D.rows=t}return{...D,...E}}function vw({targetRoundNumber:t,finishingPosition:e,drawDefinition:n,structureId:r,linkType:i}){const{links:a}=Ic({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}=ts({structureId:r,drawDefinition:n});if(!e||i?.finishingPosition===e)return t})).filter(Boolean);return{sourceStructureIds:o.map((({source:t})=>t.structureId)),relevantLinks:o}}const ww="qualifierDrawPositionAssignment",Tw="alternateDrawPositionAssignment",Pw="luckyLoserDrawPositionAssignment",Dw="removeDrawPositionAssignment",bw="swapDrawPositionAssignments",Nw="modifyPairAssignment",Rw="assignDrawPosition",Mw="assignDrawPositionBye",Aw="addPenalty",Ew="MODIFY_PAIR",Cw="QUALIFIER",Ow="ALTERNATE",Fw="WITHDRAW",kw="ASSIGN",xw="REMOVE",_w="LUCKY",Lw="REMOVE_SEED",Bw="SWAP",Vw="NICKNAME",jw="SEED_VALUE",Gw="PENALTY",qw="BYE",$w={MODIFY_PAIR_ASSIGNMENT:Ew,QUALIFYING_PARTICIPANT:Cw,ALTERNATE_PARTICIPANT:Ow,WITHDRAW_PARTICIPANT:Fw,ASSIGN_PARTICIPANT:kw,LUCKY_PARTICIPANT:_w,REMOVE_ASSIGNMENT:xw,SWAP_PARTICIPANTS:Bw,ADD_NICKNAME:Vw,REMOVE_SEED:Lw,ADD_PENALTY:Gw,ASSIGN_BYE:qw,SEED_VALUE:jw};function Ww({restrictQualifyingAlternates:t,structure:e,entry:n}){const{stage:r}=e;if(!n.entryStage||n.entryStage===r||r===Qa&&!t||n.entryStage===Xa&&r===to)return!0}function Hw(t,e){return t.bye||of(t.seedValue)<of(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function zw({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}=Yp({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:l,event:f}),S=U.filter((({drawPositions:t})=>b(t,I))),y=Object.assign({},...S.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))),T=Object.assign({},...w.map((t=>({[t.participantId]:t})))),P=g.map((t=>{const e=T?.[t.participantId],n=y[t.drawPosition];return vr({...t,participant:o?gi(e,!1,!0):void 0,sourceDrawPositionRange:n})}));if(P.length){return{validSwapAction:{payload:{drawId:m,structureId:p,drawPositions:[d]},willDisableLinks:e,method:bw,type:Bw,availableAssignments:P}}}return{}}const Yw={[vi]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[Qa,Xa],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[Vw,Gw,Cw,jw],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}},Kw="positionAction",Jw="matchUpAction";function Zw({actionType:t=Kw,appliedPolicies:e,drawDefinition:n,structure:r}){const i=t===Kw&&vi||t===Jw&&wi,a=t===Kw&&Yw||t===Jw&&sm,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 Xw({activePositionOverrides:t,activeDrawPositions:e,action:n}){return!(!n||!t.includes(n))||!e.length}function Qw({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 tT({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 eT="replaceTieMatchUpParticipantId",nT="assignTieMatchUpParticipantId",rT="removeTieMatchUpParticipantId",iT="assignMatchUpSideParticipant",aT="removeMatchUpSideParticipant",oT="substituteParticipant",sT="REMOVE_SUBSTITUTION",cT="REPLACE_PARTICIPANT",uT="REMOVE_PARTICIPANT",dT="setMatchUpStatus",pT="SUBSTITUTION",lT="SCHEDULE",mT="REFEREE",fT="STATUS",hT="START",gT="SCORE",IT="END",UT={REPLACE_TEAM_POSITION_METHOD:eT,ASSIGN_TEAM_POSITION_METHOD:nT,REMOVE_TEAM_POSITION_METHOD:rT,REPLACE_PARTICIPANT:cT,SUBSTITUTION_METHOD:oT,REMOVE_SUBSTITUTION:sT,REMOVE_PARTICIPANT:uT,SCHEDULE_METHOD:dT,SUBSTITUTION:pT,SCHEDULE:lT,PENALTY:"PENALTY",REFEREE:mT,STATUS:fT,SCORE:gT,START:hT,END:IT};function ST(t){if(!t)return{error:Nn};let e,n;const{restrictAdHocRoundParticipants:r=!0,policyDefinitions:i,enforceGender:a,participantId:o,sideNumber:s,matchUpId:c}=t,u=t.tournamentRecord??(t.tournamentId&&fa(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:_};if(!c||!fa(c))return{error:qt};if(s&&![1,2].includes(s))return wr({result:{error:Nn},context:{sideNumber:s}});if(!e){const t=(hl({tournamentRecord:u}).matchUps??[]).find((t=>t.matchUpId===c));n=(u?.events??[]).find((e=>e.eventId===t?.eventId)),e=(n?.drawDefinitions??[]).find((e=>e.drawId===t?.drawId))}if(!e)return{error:j};const d=Zl({tournamentRecord:u,withIndividualParticipants:!0}).participants,{drawId:p}=e,{matchUp:l,structure:f}=Xm({drawDefinition:e,matchUpId:c,event:n});if(!l)return{error:Wt};const h=Dc({tournamentRecord:u,drawDefinition:e,structure:f,event:n}).appliedPolicies??{};Object.assign(h,i??{});const g=h?.[vi]?.otherFlightEntries,I=h?.[wi]??sm[wi],U=ap({drawDefinition:e,structure:f}),{enabledStructures:S}=Zw({actionType:Jw,appliedPolicies:h,drawDefinition:e,structure:f}),{policyActions:y}=Qw({enabledStructures:S,drawDefinition:e,structure:f}),v=t.matchUpsMap??xc({drawDefinition:e}),w=t.inContextDrawMatchUps??Jp({tournamentParticipants:d,inContext:!0,drawDefinition:e,matchUpsMap:v,event:n}).matchUps,T=w?.find((t=>t.matchUpId===c)),P=s&&T?.sides?.find((t=>t.sideNumber===s)),D=T?.sides?.map((t=>t.participantId||t.participant?.participantid)).filter(Boolean)??[],{assignedPositions:b,allPositionsAssigned:N}=is({structure:f}),{structureId:R}=f??{},M=[];if(!R)return{validActions:M};if(U){const t=(f?.matchUps??[]).filter((({roundNumber:t})=>t===l.roundNumber)),i=e?.entries?.filter((({entryStatus:t})=>t&&au.includes(t))).map(Da)??[],a=t.map((t=>(t.sides??[]).flatMap(Da))).flat().filter(Boolean),o=i.filter((t=>!(D.includes(t)||r&&a.includes(t)))),u=d?.filter((t=>o?.includes(t.participantId))).map((t=>gi(t,void 0,!0)));u?.forEach((t=>{const n=(e.entries??[]).find((e=>e.participantId===t.participantId));t.entryPosition=n?.entryPosition})),o.length&&M.push({payload:{drawId:p,matchUpId:c,structureId:R,sideNumber:s},method:iT,type:kw,availableParticipantIds:o,participantsAvailable:u});const h=function({eventEntries:t,structure:e}){const n=t=>t.entryStatus===$c&&Ww({structure:e,entry:t}),r=(t,e)=>(t.entryPosition||1/0)-(e.entryPosition||1/0);return t.filter(n).sort(r).map(Da)}({eventEntries:n?.entries??[],structure:f});let I=m(i.concat(h));if(g){const t=n?Bd({event:n}):void 0,e=t?.flights?.filter((t=>t.drawId!==p)).flatMap((t=>t.drawEntries.filter((t=>t.participantId&&![nu,Qc,tu].includes(t.entryStatus))).map((({participantId:t})=>t)))).filter(Boolean);e?.length&&I.push(...e)}I=I.filter((t=>!(D.includes(t)||o.includes(t)||r&&a.includes(t))));const U=d?.filter((t=>I.includes(t.participantId))).map((t=>gi(t,void 0,!0)));if(U?.forEach((t=>{const n=(e.entries??[]).find((e=>e.participantId===t.participantId));t.entryPosition=n?.entryPosition})),U?.sort(((t,e)=>(t.entryPosition||1/0)-(e.entryPosition||1/0))),I.length&&M.push({payload:{drawId:p,matchUpId:c,structureId:R,sideNumber:s},availableParticipantIds:I,participantsAvailable:U,method:iT,type:$c}),!$s(l)&&s){const t=l.sides?.find((t=>t.sideNumber===s));t?.participantId&&M.push({payload:{drawId:p,matchUpId:c,structureId:R,sideNumber:s},method:aT,type:uT})}}const A=Mh({drawDefinition:e,structure:f}),E=b?.filter((t=>t.participantId)).map((t=>t.drawPosition)),C=b?.filter((t=>t.bye)).map((t=>t.drawPosition)),O=l.collectionId,F=l.matchUpStatus===Ma||!O&&l.drawPositions?.reduce(((t,e)=>C?.includes(e)||t),!1);if(F)return{validActions:M,isByeMatchUp:F};tT({policyActions:y,action:mT})&&M.push({type:mT,payload:{matchUpId:c}});const k=!Ws({matchUpStatus:l.matchUpStatus}),x=h?.scoring?.structures,L=f?.stage&&x?.stage&&x?.stage[f.stage],B=f?.stageSequence&&L?.stageSequence&&L.stageSequence[f.stageSequence],V=!(h?.scoring?.requireAllPositionsAssigned||L?.requireAllPositionsAssigned||B?.requireAllPositionsAssigned)||N,G=l.sides&&2===l.sides.filter((t=>t?.participantId)).length,q=l.matchUpStatus&&[ka,Fa].includes(l.matchUpStatus),$=Uc({inContextDrawMatchUps:w,drawDefinition:e,matchUpId:c}),W=rI({inContextDrawMatchUps:w,drawDefinition:e,targetData:$}),H=(2===T?.drawPositions?.length&&T.drawPositions.every((t=>E?.includes(t)))&&2===T?.sides?.length&&T.sides.every((({participantId:t})=>t))||G)&&!(q&&W),z={method:Aw,type:Gw,payload:{drawId:p,matchUpId:c,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};if(k&&M.push({payload:{drawId:p,matchUpId:c,schedule:{}},method:dT,type:lT}),tT({policyActions:y,action:Gw})&&(P?.participant||!s&&D?.length)&&M.push(z),k&&H&&M.push({type:fT}),V&&H){const{matchUpId:t,matchUpFormat:e}=l,n={drawId:p,matchUpId:t,matchUpFormat:e,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};M.push({info:"set outcome and winningSide",method:dT,type:gT,payload:n}),tT({policyActions:y,action:hT})&&M.push({type:hT}),tT({policyActions:y,action:IT})&&M.push({type:IT})}if(O&&T){const t=T.sides?.find((t=>t.participant)),e=T.gender===$p&&T.sideNumber&&1===T.sides?.filter((t=>t.particiapntId)).length&&t?.participant?.person?.sex,n=T.matchUpType,r=!1!==(a??I?.participants?.enforceGender)?T.gender:void 0,u=T.sides?.flatMap((t=>t.participant?.individualParticipants||t.participant)).filter(Boolean),d=u?.map(Da),m=T.sides?.filter((t=>!s||t.sideNumber===s)).flatMap((t=>t.participant?.individualParticipants||t.participant)).filter(Boolean),f=m?.map(Da),h=w?.find((t=>t.matchUpId===T.matchUpTieId)),g=h?.sides?.map((t=>t.participant?.individualParticipants.filter((({participantId:t,person:n})=>!f?.includes(t)&&(!r||r===Gp||n.sex===r||r===$p&&!e||e&&n.sex!==e))))),U=s?g?.[s-1]:g?.map(((t,e)=>({participants:t,sideNumber:e+1}))),S=s?g?.[s-1]?.map(Da):g?.map(((t,e)=>({participants:t?.map(Da),sideNumber:e+1}))),v=s&&(n===Ys&&!f?.length||n===Js&&(f?.length??0)<2)||!s&&(n===Ys&&(f?.length??0)<2||n===Js&&(f?.length??0)<4),b=S?.filter((t=>!d?.includes(t))),N=U?.filter((({participantId:t})=>b.includes(t)));if(v&&b?.length&&M.push({availableParticipantIds:b,method:nT,availableParticipants:N,type:kw,payload:{participantId:void 0,tieMatchUpId:c,drawId:p}}),!f?.length||$s(l)&&!P?.substitutions?.length||M.push({method:rT,type:uT,existingParticipantIds:f,payload:{participantId:void 0,tieMatchUpId:c,drawId:p}}),N?.length&&(!s&&f?.length||s&&P?.participant)&&M.push({availableParticipantIds:b,method:eT,availableParticipants:N,type:cT,existingParticipantIds:f,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:c,drawId:p}}),tT({policyActions:y,action:sT})&&P?.substitutions?.length){const t=P.participant?.participantType===sc&&[P.participantId]||P.participant?.participantType===uc&&P.participant.individualParticipantIds||[],e=P.substitutions.map((t=>t.participantId)).filter((e=>t.includes(e)));o&&!e.includes(o)||M.push({method:rT,type:sT,substitutedParticipantIds:e,payload:{participantId:void 0,tieMatchUpId:c,drawId:p}})}const R=i?.[wi],A=R?.substituteWithoutScore,E=R?.substituteAfterCompleted;if(tT({policyActions:y,action:pT})&&2===D.length&&(!s&&f?.length||s&&P?.participant)&&(A||$s(l))&&(E||l.matchUpStatus&&!Ya.includes(l.matchUpStatus))&&m?.length&&U.length){const t=m.map(Da);M.push({info:"list of team players available for substitution",method:oT,availableParticipantIds:S,existingParticipantIds:t,availableParticipants:U,existingParticipants:m,type:pT,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:s,matchUpId:c,drawId:p}})}}return{structureIsComplete:A,validActions:M,isDoubleExit:q}}function yT({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}=vT({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}=vT({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 vT({singlesForDoubles:t,valueAccessor:e,matchUpType:n,participant:r,scaleName:i}){const a=t?Ks:n,o=r?.rankings?.[a]?.find((t=>t.scaleName===i)),s=r?.ratings?.[a]?.find((t=>t.scaleName===i)),c=(s||o)?.scaleValue;return{scaleValue:c,value:e?c?.[e]:c}}function wT(t){const e=t.participants?.filter((({participantType:t})=>t===dc)),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 TT(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 vr({structureId:u,roundSegment:n,tournamentId:i,roundNumber:a,eventId:s,drawId:c,id:d})}function PT({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=g(e.map((({matchUpFormat:t})=>t)));let p=0;return Object.keys(d).forEach((e=>{const n=d[e],i=jy({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 DT(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||Ya.includes(e))).length||0,i=t.filter((({schedule:t,matchUpStatus:e})=>t?.scheduledDate&&t?.scheduledTime&&e!==Ma)).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 bT({tournamentRecords:t,schedulingProfile:e,tournamentRecord:n,withRoundId:r}){if(n&&!t){if("object"!=typeof n)return{error:L};t={[n.tournamentId]:n}}if(e){const n=Nm({tournamentRecords:t,schedulingProfile:e});if(n.error)return n}if(!e&&t){const n=Om({tournamentRecords:t});if(n.error)return n;e=n.schedulingProfile}if(!e)return{error:On};const i={};return{profileRounds:e.map((({venues:t,scheduleDate:e})=>t.map((({rounds:t})=>t.map((t=>{const n=TT(t);return n.roundSegment?.segmentsCount&&(i[n.id]=n.roundSegment.segmentsCount),vr({id:r?n.id:void 0,scheduleDate:e,...n})})))))).flat(1/0),segmentedRounds:i}}const{stageOrder:NT}=Zo;function RT(t,e){return t.eventName.localeCompare(e.eventName)||t.eventId.localeCompare(e.eventId)||(NT[t?.stage]||0)-(NT[e?.stage]||0)||e.matchUpsCount-t.matchUpsCount||`${t.stageSequence}-${t.roundNumber}-${t.minFinishingSum}`.localeCompare(`${e.stageSequence}-${e.roundNumber}-${e.minFinishingSum}`)}const MT={allCompetitionMatchUps:gl,allDrawMatchUps:Ul,allEventMatchUps:fl,allTournamentMatchUps:hl,analyzeDraws:mU,analyzeMatchUp:Ev,analyzeTournament:function({tournamentRecord:t}){if(!t)return{error:_};const{drawsAnalysis:e}=mU({tournamentRecord:t}),n={isDual:wT(t),drawsAnalysis:e};return{...E,analysis:n}},bulkUpdatePublishedEventIds:function({tournamentRecord:t,outcomes:e}){if(!t)return{error:_};if(!e?.length)return{error:ae,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=Gl({event:t}),{drawDetails:r,drawIds:i}=e??{},{eventId:a}=t;return n[a].filter((t=>{const n=r?Object.keys(e.drawDetails).filter((t=>ql({drawId:t,drawDetails:r}))):[];return i?.includes(t)||n.includes(t)})).length})).map((t=>t.eventId)),eventIdPublishedDrawIdsMap:n}},categoryCanContain:ph,checkMatchUpIsComplete:Lc,checkValidEntries:KS,competitionScheduleMatchUps:yw,credits:zv,drawMatchUps:function({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:S,event:y}){const{eventId:v,eventName:w,endDate:T}=y??{},P={...S,...vr({eventId:v,eventName:w,endDate:T??y?.endDate??s?.endDate,tournamentId:I??s?.tournamentId,indoorOutDoor:y?.indoorOutdoor??s?.indoorOutdoor,surfaceCategory:y?.surfaceCategory??s?.surfaceCategory})};let D;return!t?.length&&s&&({participants:t,participantMap:l,groupInfo:D}=ml({participantsProfile:r,policyDefinitions:a,useParticipantMap:o,tournamentRecord:s,contextProfile:f,inContext:U})),y&&f&&!d&&(d=Fc({policyDefinitions:a,tournamentRecord:s,contextProfile:f,drawDefinition:h,event:y})),{...Zp({context:P,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:y}),groupInfo:D}},eventMatchUps:Iw,findDrawDefinition:function({tournamentRecord:t,drawDefinition:e}){return t?e?{drawDefinition:gi(e)}:{error:at}:{error:_}},findExtension:Mr,findMatchUp:Af,findParticipant:function(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:ae,stack:"publicFindParticipant"};let s,c;for(const t of Object.values(o)){c=t.tournamentId;if(s=Fi({tournamentParticipants:t.participants||[],internalUse:!0,policyDefinitions:n,contextProfile:r,participantId:i,personId:a}),s)break}return{participant:s,tournamentId:c,...E}},findPolicy:Uu,getAllDrawMatchUps:Jp,getAllowedDrawTypes:YS,getAllowedMatchUpFormats:function({tournamentRecord:t,categoryName:e,categoryType:n}){if(!t)return{error:_};const{appliedPolicies:r}=Dc({tournamentRecord:t}),i=r?.[Mi];return(i?.matchUpFormats||[]).filter((({categoryNames:t,categoryTypes:r})=>!e&&!r||e&&t?.includes(e)||n&&r?.includes(n)))},getAppliedPolicies:Dc,getAssignedParticipantIds:kl,getCompetitionDateRange:qv,getCompetitionMatchUps:Sw,getCompetitionParticipants:function(t){const{tournamentRecords:e}=t||{};if("object"!=typeof e||!Object.keys(e).length)return{error:x};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}=Zl({...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,...E,matchUps:o}},getCompetitionPenalties:function({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:x};const e=[];for(const n of Object.values(t)){const{penalties:t}=fw({tournamentRecord:n});e.push(...t??[])}return{penalties:e}},getCompetitionVenues:Em,getCourts:function({tournamentRecord:t,venueId:e,venueIds:n}){return t?{courts:(t.venues||[]).filter((t=>e?t.venueId===e:!n||n.includes(t.venueId))).map((t=>{const{venueId:e}=t,n=gi(t.courts||[]);return n.forEach((t=>Object.assign(t,{venueId:e}))),n})).flat()}:{error:_}},getDrawDefinitionTimeItem:function({returnPreviousValues:t,drawDefinition:e,itemSubTypes:n,itemType:r}){if(!e)return{error:at};if(!e.timeItems)return{info:On};const{timeItem:i,previousItems:a,info:o}=il({element:e,returnPreviousValues:t,itemSubTypes:n,itemType:r});return i&&{timeItem:i,previousItems:a}||{info:o}},getDrawParticipantRepresentativeIds:function({drawDefinition:t}){const e=Mr({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value||[]}},getEligibleVoluntaryConsolationParticipants:function({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:j};const f=[Xa,no];n&&f.push(Qa);const h=m?.eventType?{matchUpTypes:[m.eventType]}:void 0,g=s?.matchUpType?{matchUpTypes:[s.matchUpType]}:void 0,I=e&&m?fl({contextFilters:{stages:f},matchUpFilters:h,tournamentRecord:o,inContext:!0,event:m})?.matchUps??[]:Ul({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:o,inContext:!0,drawDefinition:s})?.matchUps??[],U=pu({stage:eo,drawDefinition:s}).map((({participantId:t})=>t)),S={},y={},v={},w={};i||(i=bc({policyTypes:[Ui],tournamentRecord:o,drawDefinition:s,event:m}).policyDefinitions);const T=i?.[Ui];t=t.length&&t||T?.excludedMatchUpStatuses||[],e=e??T?.includeEventParticipants,p=p??T?.allEntries,r=r??T?.finishingRoundLimit,a=a??T?.roundNumberLimit,c=c??T?.matchUpsLimit,void 0===u&&(u=void 0===T?.requirePlay||T.requirePlay),void 0===d&&(d=void 0===T?.requireLoss||T.requireLoss),l=l??T?.winsLimit;for(const e of I){if(u&&e.winningSide&&![1,2].includes(e.winningSide)&&e.matchUpStatus!==ka)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!==ka||u||(y[r]=n.participant,S[r]||(S[r]=0),e.matchUpStatus&&t.includes(e.matchUpStatus)||(S[r]+=1)))})),n?.participant){const r=n.participant.participantId;y[r]=n.participant,S[r]||(S[r]=0),e.matchUpStatus&&!t.includes(e.matchUpStatus)&&(S[r]+=1)}if(i?.participant){const n=i.participant.participantId;w[n]||(w[n]=0),w[n]+=1,S[n]||(S[n]=0),e.matchUpStatus&&!t.includes(e.matchUpStatus)&&(S[n]+=1)}}const P=o?.participants&&!u&&!d&&p,D=P?((e&&m?m.entries:s.entries)??[]).filter((t=>![nu,Qc].includes(t.entryStatus))).map((({participantId:t})=>t)):[],b=Object.keys(y);return{eligibleParticipants:(P?(o?.participants??[]).filter((({participantId:t})=>D.includes(t))):d&&Object.values(y)||Object.values(v)).filter((t=>{return e=t.participantId,(!d||b.includes(e))&&(t=>!u||(S[t]||0)>=0)(t.participantId)&&(t=>!l||(w[t]||0)<=l)(t.participantId)&&(t=>!c||S[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,...E}},getEntriesAndSeedsCount:VU,getEvent:function({tournamentRecord:t,drawDefinition:e,context:n,event:r}){if(!t)return{error:_};if(!r)return{error:Tt};const i=gi(r);return n&&Object.assign(i,n),vr({drawDefinition:e&&i.drawDefinitions?.find((({drawId:t})=>e.drawId===t)),event:i})},getEventMatchUpFormatTiming:function({tournamentRecord:t,matchUpFormats:e,categoryType:n,event:r}){if(!r)return{error:Tt};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)&&rh(n?.matchUpFormat))return t.push(n.matchUpFormat),n})).filter(Boolean)}else{const{policy:e}=Uu({policyType:Mi,tournamentRecord:t,event:r});if(e?.matchUpFormats)a=e?.matchUpFormats;else{const{extension:t}=Mr({name:aa,element:r});let e,n;({matchUpAverageTimes:e,matchUpRecoveryTimes:n}=t?.value?t.value:lw[Ni]),a=m([...(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;return s?vr({eventMatchUpFormatTiming:a.map((({matchUpFormat:e,description:i})=>({matchUpFormat:e,description:i,...Sd({tournamentRecord:t,matchUpFormat:e,categoryName:u,categoryType:n,eventType:o,event:r})}))),info:i}):{error:Tt}},getEventProperties:function({tournamentRecord:t,event:e}){if(!t)return{error:_};if(!e)return{error:Tt};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:$u,eventType:a,scaleName:i};const d=Vl({participant:t,scaleAttributes:o})?.scaleItem?.scaleValue;o={scaleType:qu,eventType:a,scaleName:i};const p=Vl({participant:t,scaleAttributes:o})?.scaleItem?.scaleValue;o={scaleType:Gu,eventType:a,scaleName:i};const l=Vl({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}},getEvents:function({tournamentRecord:t,withScaleValues:e,scaleEventType:n,inContext:r,eventIds:a,drawIds:o,context:s}){if(!t)return{error:_};const{tournamentId:c}=t,u=(t.events??[]).filter((({eventId:t})=>!a||Array.isArray(a)&&a.includes(t))).map((t=>{const e=t.drawDefinitions?.map(Ua("drawId"));if(o?.length&&!P(o,e).length)return;const n=gi(t);return r&&Object.assign(n,{tournamentId:c}),s&&Object.assign(n,s),n})).filter(Boolean),d={};if(e){const e=Zl({withScaleValues:!0,tournamentRecord:t}).participantMap,r=t=>t.reduce(((t,e)=>t+parseFloat(e)),0);for(const t of u){const a=n??t.eventType,s=t.eventId;d[s]||(d[s]={ratingsStats:{},ratings:{},ranking:{},draws:{}});const c=(t.entries??[]).filter((({entryStatus:t})=>ou.includes(t))).map(Ua(lp)),u=t=>{if(t?.ratings?.[a])for(const e of t?.ratings?.[a]??[]){const t=e.scaleName;d[s].ratings[t]||(d[s].ratings[t]=[]);const n=MU[t]?.accessor;if(n){const r=parseFloat(e.scaleValue?.[n]);r&&d[s].ratings[t].push(r)}}if(t?.rankings?.[a])for(const e of t?.rankings?.[a]??[]){const t=e.scaleName;d[s].ranking[t]||(d[s].ranking[t]=[]),e.scaleValue&&d[s].ranking[t].push(e.scaleValue)}};for(const t of c){const n=e?.[t]?.participant;if(n?.participantType!==sc)for(const t of n?.individualParticipantIds??[]){const n=e?.[t]?.participant;u(n)}else u(n)}const p=d[s].ratings;for(const t of Object.keys(p)){const e=p[t];if(!e.length)continue;const n=i(e)?.toFixed(2);d[s].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 l=(t,n)=>{const r=e=>{if(d[s].draws?.[t]&&e?.ratings?.[a])for(const n of e?.ratings?.[a]??[]){const e=n.scaleName;d[s].draws[t]?.ratings[e]||(d[s].draws[t].ratings[e]=[]);const r=MU[e]?.accessor;if(r){const i=parseFloat(n.scaleValue?.[r]);i&&d[s].draws[t].ratings[e].push(i)}}if(d[s].draws?.[t]&&e?.rankings?.[a])for(const n of e?.rankings?.[a]??[]){const e=n.scaleName;d[s].draws[t]?.ranking[e]||(d[s].draws[t].ranking[e]=[]);const r=n.scaleValue;r&&d[s].draws[t].ranking[e].push(r)}};for(const t of n.filter(Boolean)){const n=e?.[t]?.participant;if(n?.participantType!==sc)for(const t of n?.individualParticipantIds??[]){const n=e?.[t]?.participant;r(n)}else r(n)}},m=[],f=t=>o?.length&&o.includes(t)||m.includes(t);for(const e of t.drawDefinitions??[]){const t=e.drawId;if(f(t))continue;const n=kl({drawDefinition:e}).assignedParticipantIds??[];d[s].draws[t]||(d[s].draws[t]={ratingsStats:{},ratings:{},ranking:{}}),m.push(t),l(t,n)}const h=Bd({event:t}).flightProfile;for(const t of h?.flights??[]){const e=t.drawId;if(f(e))continue;l(e,t.drawEntries.map(Ua(lp)))}for(const t of m){const e=d[s].draws[t].ratings;for(const n of Object.keys(e)){const a=e[n];if(!a.length)continue;const o=i(a)?.toFixed(2);d[s].draws[t].ratingsStats[n]={avg:parseFloat((r(a)/a.length).toFixed(2)),median:o?parseFloat(o):void 0,max:Math.max(...a),min:Math.min(...a)}}}}}return vr({eventScaleValues:d,events:u,...E})},getEventStructures:Rh,getEventTimeItem:al,getFlightProfile:Bd,getLinkedTournamentIds:Rd,getMatchUpCompetitiveProfile:Su,getMatchUpDailyLimits:Ey,getMatchUpDailyLimitsUpdate:function({tournamentRecords:t}){return cw({extensionName:ia,tournamentRecords:t})},getMatchUpDependencies:Sl,getMatchUpFormat:function(t){const{structureId:e,matchUpId:n,event:r}=t;let i=t.drawDefinition;const a=Lp(t,[{[up]:!0},{_anyOf:{[fp]:!0,[Ip]:!0,[bp]:!0,[Rp]:!0}}]);if(a[Np])return a;const o=Cf(t,[{[Mp]:Dp,[Np]:ae}]),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:at};const t=ts({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}},getMatchUpFormatTiming:Sd,getMatchUpFormatTimingUpdate:function({tournamentRecords:t}){return cw({extensionName:aa,tournamentRecords:t})},getMatchUpScheduleDetails:jd,getMatchUpsStats:function({profileBands:t,tournamentRecord:e,matchUps:n}){if(!yc(n))return{error:Ht};const r=!t&&Uu({policyType:Si,tournamentRecord:e}).policy,i=t||r?.profileBands||Oc[Si].profileBands,a=n.filter((({winningSide:t})=>t)),o=Iu(a.map(hu)).reduce(((t,e)=>((t,e)=>(t[fu(e,i)]+=1,t))(t,e)),{[Mc]:0,[Ac]:0,[Ec]:0,[Nc]:0}),s=Object.keys(o).reduce(((t,e)=>(o[e]||0)+t),0),c=Object.keys(o).map((t=>({[t]:100*parseFloat((o[t]/s).toFixed(4))}))),u=a.filter((({matchUpStatus:t})=>t===Rc)).length;return c.push({[Rc]:100*parseFloat((u/s).toFixed(4))}),{competitiveBands:Object.assign({},...c),...E}},getMatchUpType:Vp,getMaxEntryPosition:function(t){const{entries:e=[],entryStatus:r,stage:i}=t;return Math.max(...e.filter((t=>!(i&&i!==t.entryStage||r&&t.entryStatus!==r||isNaN(t.entryPosition)))).map((({entryPosition:t})=>n(t||0))),0)},getModifiedMatchUpFormatTiming:mw,getPairedParticipant:Vc,getParticipantEventDetails:function({tournamentRecord:t,participantId:e}){if(!t)return{error:_};if(!e)return{error:Ae};const n=[e].concat((t.participants??[]).filter((t=>t?.participantType&&[dc,uc].includes(t.participantType)&&t.individualParticipantIds?.includes(e))).map((t=>t.participantId)));return{eventDetails:(t.events??[]).filter((t=>b((t?.entries??[]).map((t=>t.participantId)),n))).map((t=>({eventName:t.eventName,eventId:t.eventId})))}},getParticipantIdFinishingPositions:function({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:n}){if(!n)return{error:j};const{participantIds:r,participantIdMatchUps:i}=function({tournamentParticipants:t,drawDefinition:e,event:n}){if(!e)return{error:j};const r=gi(Jp({tournamentParticipants:t,inContext:!0,drawDefinition:e,event:n}).matchUps,!1,!0),i=m(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=>[Ea,Ma].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)},getParticipantMembership:function({tournamentRecord:t,participantId:e}){if(!t)return{error:_};if(!e)return{error:Ae};const{participants:n}=Zl({participantFilters:{participantTypes:[dc,uc,cc]},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}),{})},getParticipants:Zl,getParticipantScaleItem:GU,getParticipantSchedules:function({participantFilters:t={},tournamentRecord:e}){if(!e)return{error:_};if("object"!=typeof t)return{error:Pn,context:{participantFilters:t}};const n=hl({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=Sl({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)))),...E}},getParticipantSignInStatus:function({tournamentRecord:t,participantId:e}){if(!t)return{error:_};if(!e)return{error:Ae};const{participant:n}=rl({tournamentRecord:t,participantId:e});if(!n)return{error:Ee};const{timeItem:r}=il({itemType:rc,element:n});return r&&r.itemValue===ac&&ac},getParticipantTimeItem:function({returnPreviousValues:t,tournamentRecord:e,participantId:n,itemSubTypes:r,itemType:i}){if(!e)return{error:_};if(!n)return{error:Ae};const a=rl({tournamentRecord:e,participantId:n});if(a.error)return a;const{participant:o}=a;if(!o?.timeItems)return{info:On};const{timeItem:s,previousItems:c,info:u}=il({element:a.participant,returnPreviousValues:t,itemSubTypes:r,itemType:i});return s&&{timeItem:s,previousItems:c}||{info:u}},getPersonRequests:nv,getPolicyDefinitions:bc,getPositionAssignments:Dm,getPredictiveAccuracy:function(t){let{matchUps:e}=t;const{singlesForDoubles:n,tournamentRecord:r,drawDefinition:i,excludeMargin:a,exclusionRule:o,zoneDoubling:s,matchUpType:c,scaleName:u,eventId:d,zonePct:l,drawId:m,event:f}=t;if(!r&&!e)return{error:_};if(c&&![Ks,Zs].includes(c))return{error:Nn,info:{matchUpType:c}};if(e&&!yc(e))return{error:Nn,context:{matchUps:e}};const h=MU[u],g=h?.ascending??t.ascending??!1,I=h?.accessor??t.valueAccessor,U=Array.isArray(h?.range)?Math.abs(h.range[0]-h.range[1]):0,S=p(l)&&U?(l??0)*U:t.zoneMargin??U,y={withScaleValues:!0,withCompetitiveness:!0},v={matchUpTypes:c?[c]:[Ks,Zs]},w=r?.participants;e?.[0]?.hasContext?m?e=e.filter((t=>t.drawId===m)):d&&(e=e.filter((t=>t.eventId===d))):void 0===e&&(e=m&&!i&&[]||!m&&d&&!f&&[]||m&&Ul({inContext:!0,drawDefinition:i,contextFilters:v,contextProfile:y,participants:w})?.matchUps||!m&&d&&fl({inContext:!0,contextFilters:v,contextProfile:y,participants:w,event:f})?.matchUps||hl({tournamentRecord:r,contextFilters:v,contextProfile:y})?.matchUps||[]),c&&(e=e.filter((t=>t.matchUpType===c)));const T=e.filter((({winningSide:t,score:e,sides:n,matchUpStatus:r})=>![Ba,Oa,Ga,Ca,Na].includes(r??"")&&$s({score:e})&&2===n?.length&&t)),P=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:ae};const p=d-1,l=yT({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:a,exclusionRule:o,valueAccessor:I,ascending:g,scaleName:u}),D=s&&c!==Ks?2*(S||0):S,b=S?T.map((({competitiveProfile:t,matchUpType:e,score:r,sides:i})=>{const a=yT({singlesForDoubles:n,valueAccessor:I,matchUpType:e,scaleName:u,sides:i}),o=Math.abs(a[0].value-a[1].value);return{competitiveness:t?.competitiveness,valuesGap:o,score:r}})).filter((({valuesGap:t})=>t<=D)):[],N=function({zoneData:t}){const e={[Mc]:[],[Ac]:[],[Ec]:[]};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:b}),R=N&&[].concat(Object.values(N)).flat().length,M=R&&Object.assign({},...Object.keys(N).map((t=>({[t]:Math.round(1e4*N[t].length/R)/100})))),A=T.length-(b?.length||0);return{...E,relevantMatchUps:T,zoneDistribution:M,zoneData:b,accuracy:P,nonZone:A}},getRoundMatchUps:vc,getRounds:function({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:Nn,inContextMatchUps:r};if(o&&!i){if("object"!=typeof o)return{error:L};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:x};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)&&bT({tournamentRecords:i,schedulingProfile:a})||{},U=t&&Object.assign({},...I.map((t=>({[t.id]:t})))),S=r||i&&gl({tournamentRecords:i,matchUpFilters:c})?.matchUps||[],y=[],v=S&&Object.values(S.reduce(((t,e)=>{const n=TT(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:S,drawId:y}=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:S,drawId:y}}}),{})).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 N(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}=DT(a),f=PT({matchUps:t.matchUps,tournamentRecords:i,events:h,round:t});return vr({...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}=DT(t.matchUps),p=PT({matchUps:t.matchUps,tournamentRecords:i,events:h,round:t});return vr({...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=ri(t),n=d?r.id:TT(r).id;if(e&&U[n]&&ri(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),S=g&&I,v=!p||l?.validVenueIds.includes(p),w=s&&c&&v&&S;return w||y.push(r),w})).sort(RT)||[];return{...E,rounds:v,excludedRounds:y}},getScaledEntries:qU,getScheduledRoundsDetails:Gy,getSchedulingProfileIssues:function(t){const{scheduleDates:e=[],tournamentRecords:n,periodLength:r=30}=t??{};if("object"!=typeof n)return{error:L};if(!Array.isArray(e))return{error:Nn};if(!e.every(Wr))return{error:pe};const i=[];let a=0;const o={},{schedulingProfile:s}=Om({tournamentRecords:n});if(!s)return{issues:i,...E};const{matchUps:c}=gl({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}=Gy({tournamentRecords:n,periodLength:r,matchUps:c,rounds:e}),{matchUpDependencies:l}=Sl({tournamentRecords:n,matchUps:c}),f=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=P(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=f(t),r=m(e.map(f));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,...E}},getSeedsCount:BU,getStructureSeedAssignments:lu,getTeamLineUp:jc,getTieFormat:function({tournamentRecord:t,drawDefinition:e,structureId:n,matchUpId:r,structure:i,eventId:a,drawId:o,event:s}){if(!t)return{error:_};if(!(o||s||n||r))return wr({result:{error:ae},stack:"getTieFormat"});a&&!s&&(s=t.events?.find((t=>t.eventId===a)));const c=Af({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:at};const t=ts({drawDefinition:e,structureId:n});if(t.error)return t;i=t.structure}const u=(i?.tieFormat||i?.tieFormatId)&&$d({structure:i,drawDefinition:e,event:s})?.tieFormat,d=(e?.tieFormat||e?.tieFormatId)&&$d({drawDefinition:e,event:s})?.tieFormat,p=$d({event:s})?.tieFormat,l=$d({matchUp:c?.matchUp,drawDefinition:e,structure:i,event:s})?.tieFormat;return{...E,matchUp:c?.matchUp,structureDefaultTieFormat:Yf(u),eventDefaultTieFormat:Yf(p),drawDefaultTieFormat:Yf(d),tieFormat:Yf(l),structure:i}},getTournamentIds:ya,getTournamentPenalties:fw,getTournamentPersons:function({tournamentRecord:t,participantFilters:e}){if(!t)return{error:_};let n=t.participants||[];e&&(n=Kl({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)}},getTournamentStructures:function({withStageGrouping:t,tournamentRecord:e,stageSequences:n,stageSequence:r,roundTarget:i,stages:a,stage:o}){if(!e)return{error:_};const s={},c=[];for(const u of e.events||[]){const{structures:e,stageStructures:d}=Rh({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}},getTournamentTimeItem:ol,getVenuesAndCourts:Am,getVenuesReport:function({ignoreDisabled:t=!0,tournamentRecords:e,tournamentId:n,venueIds:r=[],dates:i=[]}){if(!Array.isArray(i))return{error:Nn,dates:i};if(!Array.isArray(r))return{error:Nn,venueIds:r};if(!(e&&Object.keys(e).filter((t=>!n||t===n))||[]).length)return{error:x};if(!i.every(Wr))return{error:pe};const a=Am({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}=gl({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&&cy({courtDate:r}),a=i?.reduce(((t,e)=>{const{startTime:n,endTime:r}=e;return t+(ti(r)-ti(n))}),0);a&&(s+=1),e+=a}const c=n.filter((({schedule:e})=>e.venueId===r&&fi(t,e.scheduledDate)));c.forEach((({schedule:t})=>{const e=ni(t.scheduledTime),n=ti(pi(e,t.averageMinutes))-ti(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}},isValidForQualifying:function({structureId:t,drawDefinition:e}){if(!e)return{error:j};if(!fa(t))return{error:Nn};const n=Ic({drawDefinition:e,structureId:t});if(n.error)return n;const r=n.links.target.flatMap((t=>t.target.feedProfile)).filter(Boolean),i=!P([Io,go,ho,po],r).length;return{...E,valid:i}},isValidMatchUpFormat:rh,matchUpActions:ST,participantScaleItem:Vl,participantScheduledMatchUps:function({scheduleAttributes:t=["scheduledDate","scheduledTime"],matchUps:e=[]}){if(!yc(e))return{error:Ht};if(!Array.isArray(t))return{error:Nn};const n=e.filter(Boolean).filter((({schedule:e})=>Wy({schedule:e,scheduleAttributes:t}))).reduce(((t,e)=>{const{schedule:n}=e,r=ri(n?.scheduledDate),i=ni(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)=>si(ni(t.schedule?.scheduledTime),ni(e.schedule?.scheduledTime))))})),{...E,scheduledMatchUps:n}},positionActions:function(t){const{policyDefinitions:e,returnParticipants:n=!0,provisionalPositioning:r,tournamentRecord:i,drawDefinition:a,drawPosition:o,event:s}=t;if(!s)return{error:Tt};if(!a)return{error:j};if(!t.structureId)return{error:It};const c=t.tournamentParticipants??(i&&Zl({withIndividualParticipants:!0,tournamentRecord:i}).participants)??[];let u=ts({structureId:t.structureId,drawDefinition:a});if(u.error)return u;const d=u.containingStructure||u.structure;if(!d)return{error:Ut};const p=d.structureId;if(u=yl({drawDefinition:a,structureId:p}),void 0===o&&!u.isAdHoc)return{error:tt};if(u.isAdHoc)return ST(t);if(u.error)return u;const{drawPositionInitialRounds:l,inactiveDrawPositions:f,activeDrawPositions:h,byeDrawPositions:g}=u,I=Dc({tournamentRecord:i,drawDefinition:a,structure:d,event:s}).appliedPolicies??{};Object.assign(I,e??{});const{actionsPolicy:U,enabledStructures:S,actionsDisabled:y}=Zw({actionType:Kw,appliedPolicies:I,drawDefinition:a,structure:d}),v=U?.activePositionOverrides||[],{sourceStructureIds:w}=vw({finishingPosition:Yo,targetRoundNumber:1,linkType:Uo,drawDefinition:a,structureId:p})||{};let T;w?.length&&(T=w.reduce(((t,e)=>Mh({structureId:e,drawDefinition:a})&&t),!0));const P=w.length,D=w.length&&!T,{policyActions:b}=Qw({enabledStructures:S,drawDefinition:a,structure:d}),N=![Qa,Xa].includes(d.stage)||1!==d.stageSequence,{drawId:R}=a,M=[],{assignedPositions:A,positionAssignments:E}=is({structure:d}),C=A?.find((t=>t.drawPosition===o)),O=E?.map((t=>t.drawPosition));if(!O?.includes(o))return{error:Q};const{stage:F,stageSequence:k}=d,x=[F];F===to&&x.push(Xa),F===Xa&&x.push(to);const _=pu({entryStatuses:au,provisionalPositioning:r,drawDefinition:a,stageSequence:k,structureId:p,stages:x}),L=kl({drawDefinition:a,stages:x}).assignedParticipantIds??[],B=_.filter((t=>!L.includes(t.participantId))).map((t=>t.participantId)),V=g.includes(o),G=h.includes(o);if(y)return{hasPositionAssigned:!!C,info:"Actions Disabled for structure",isActiveDrawPosition:G,isDrawPosition:!0,validActions:[],isByePosition:V};if(tT({policyActions:b,action:kw})&&!G&&E&&!D&&(!C||V)){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:f,event:h}){const{drawId:g}=u,I=[];let U,S,y=[];const v=c?.[Ai]?.validSeedPositions?.ignore;if(!v){const t=Sf({provisionalPositioning:r,returnAllProxies:!0,randomize:!0,drawDefinition:u,seedingProfile:d,structureId:f,event:h});({unplacedSeedParticipantIds:U,unplacedSeedAssignments:S,unfilledPositions:y}=t)}if(y?.length||(y=o.filter((t=>!t.participantId&&!t.bye&&!t.qualifier)).map((t=>t.drawPosition))),p||I.push({payload:{drawId:g,structureId:f,drawPosition:l,isPositionAction:!0},willDisableLinks:n,method:Mw,type:qw}),a&&v){const e=o.map((t=>t.participantId)).filter(Boolean),r={structureIds:t},{completedMatchUps:a}=Zp({inContext:!0,matchUpFilters:r,drawDefinition:u}),c=m((a??[]).filter((({matchUpType:t})=>h?.eventType!==id||t===id))?.map((({sides:t})=>t?.map(Ua("participantId")))).flat().filter((t=>t&&!e.includes(t)))),d=s?i?.filter((t=>c?.includes(t.participantId))).map((t=>gi(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&&I.push(vr({payload:{drawId:g,structureId:f,drawPosition:l},willDisableLinks:n,method:Rw,type:kw,availableParticipantIds:c,participantsAvailable:d})),{validAssignmentActions:I}}if(y.includes(l)||p){let t;if(S?.length){const e=S.filter((t=>U?.includes(t.participantId)));e.sort(Hw),t=e.map((t=>t.participantId))}else t=e;const r=s?i?.filter((e=>t.includes(e.participantId))).map((t=>gi(t,void 0,!0))):void 0;r?.length&&I.push(vr({payload:{drawId:g,structureId:f,drawPosition:l},willDisableLinks:n,method:Rw,type:kw,availableParticipantIds:t,participantsAvailable:r}))}return{validAssignmentActions:I}}({positionSourceStructureIds:w,unassignedParticipantIds:B,possiblyDisablingAction:N,isWinRatioFedStructure:P,tournamentParticipants:c,positionAssignments:E,returnParticipants:n,appliedPolicies:I,drawDefinition:a,isByePosition:V,drawPosition:o,structureId:p,event:s});t?.forEach((t=>M.push(t)))}if(tT({policyActions:b,action:Cw})){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?.[vi],h=!f?.disableRoundRestrictions&&t[o],g=f?.requireCompletedStructures,{sourceStructureIds:I,relevantLinks:U}=vw({targetRoundNumber:h,linkType:So,drawDefinition:a,structureId:s})||{};I?.length&&l.push(...I);const{sourceStructureIds:S,relevantLinks:y}=vw({targetRoundNumber:h,linkType:Uo,drawDefinition:a,structureId:s})||{};S?.length&&l.push(...S);for(const t of U){const n=a.structures?.find((e=>e.structureId===t.source.structureId));if(n?.stage!==Qa)continue;const i=Mh({structureId:t.source.structureId,drawDefinition:a});if(!g||i){const t=n.qualifyingRoundNumber,{matchUps:i}=Yp({matchUpFilters:{roundNumbers:[t],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===Ma&&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 y){const n=a.structures?.find((e=>e.structureId===t.source.structureId));if(n?.stage!==Qa)continue;const i=Mh({structureId:t.source.structureId,drawDefinition:a});if(!g||i){const{positionAssignments:t}=rs({structure:n}),i=t?.map((t=>{const e=t.participantId,n=Mr({element:t,name:ca}).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(vr({payload:{qualifyingParticipantId:void 0,drawPosition:o,structureId:s,drawId:c},method:ww,type:Cw,qualifyingParticipantIds:d,qualifyingParticipants:r?u:void 0})),{validAssignmentActions:p,sourceStructureIds:l}}({drawPositionInitialRounds:l,tournamentParticipants:c,positionAssignments:E,returnParticipants:n,appliedPolicies:I,drawDefinition:a,drawPosition:o,structureId:p,drawId:R});t?.forEach((t=>M.push(t)))}const{participantId:q}=C||{},$=q&&c.find((t=>t.participantId===q));if(C){tT({policyActions:b,action:xw})&&!G&&(M.push({type:xw,method:Dw,payload:{drawId:R,structureId:p,drawPosition:o},willDisableLinks:N}),V||M.push({type:Fw,method:"withdrawParticipantAtDrawPosition",payload:{drawId:R,structureId:p,drawPosition:o},willDisableLinks:N}),tT({policyActions:b,action:qw})&&!V&&M.push({type:qw,method:Dw,payload:{drawId:R,structureId:p,drawPosition:o,replaceWithBye:!0},willDisableLinks:N}));const t=d.stage===Qa||d.stage===Xa&&1===d.stageSequence;if(!V&&Xw({activePositionOverrides:v,activeDrawPositions:h,action:jw})&&tT({policyActions:b,action:jw})&&Uf({drawDefinition:a,structureId:p,drawPosition:o})&&t){const{seedAssignments:t}=lu({returnAllProxies:!0,drawDefinition:a,structure:d}),{seedNumber:e,seedValue:n}=t?.find((t=>t.participantId===q))??{};M.push({type:jw,method:"modifySeedAssignment",participant:$,seedNumber:e,payload:{drawId:R,structureId:p,participantId:q,seedValue:n}})}if(!V&&Xw({activePositionOverrides:v,activeDrawPositions:h,action:Lw})&&tT({policyActions:b,action:Lw})&&Uf({drawDefinition:a,structureId:p,drawPosition:o})&&t){const{seedAssignments:t}=lu({returnAllProxies:!0,drawDefinition:a,structure:d}),{seedNumber:e}=t?.find((t=>t.participantId===q))??{};M.push({method:"removeSeededParticipant",type:Lw,participant:$,seedNumber:e,payload:{participantId:q,structureId:p,drawId:R}})}if(!V&&q){if(tT({policyActions:b,action:Gw})){const t={type:Gw,method:Aw,participant:$,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:R}};M.push(t)}if(tT({policyActions:b,action:Vw})){const t={type:Vw,method:"modifyParticipantOtherName",participant:$,payload:{participantId:q,otherName:void 0}};M.push(t)}}if(tT({policyActions:b,action:Bw})){const{validSwapAction:t}=zw({possiblyDisablingAction:N,tournamentParticipants:c,inactiveDrawPositions:f,activeDrawPositions:h,positionAssignments:E,returnParticipants:n,byeDrawPositions:g,drawDefinition:a,isByePosition:V,drawPosition:o,structureId:p,structure:d,drawId:R});t&&M.push(t)}}if(tT({policyActions:b,action:Ow})&&!D){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 f=c.find((t=>t.type===kw))?.availableParticipantIds,h=a?.[vi]?.otherFlightEntries,g=a?.[vi]?.restrictQualifyingAlternates,I=(o.entries??[]).filter((({entryStage:t})=>!g||(d.stage===Qa?t===Qa:t!==Qa))).sort(((t,e)=>(t.entryPosition??1/0)-(e.entryPosition??1/0))).map((({participantId:t})=>t)).filter(Boolean),{allPositionedParticipantIds:U}=ns({drawDefinition:o}),S=r.map((t=>t.participantId)).filter(Boolean),y=I.filter((t=>d.stage&&[Qa,Xa,no].includes(d.stage)?!U?.includes(t):!S.includes(t))),v=(l?.entries??[]).filter((t=>t.entryStatus===$c&&Ww({restrictQualifyingAlternates:g,structure:d,entry:t})&&(d.stage&&[Qa,Xa,no].includes(d.stage)?!U?.includes(t.participantId):!S.includes(t.participantId)))).sort(((t,e)=>(t.entryPosition??1/0)-(e.entryPosition??1/0))).map((t=>t.participantId));let w=m(y.concat(v));if(h){const t=l?Bd({event:l}).flightProfile:void 0,e=t?.flights?.filter((t=>t.drawId!==p)).map((t=>t.drawEntries.filter((t=>t.participantId&&![nu,Qc,tu].includes(t.entryStatus)&&!I.includes(t.participantId))).map((({participantId:t})=>t)))).flat().filter(Boolean);e?.length&&w.push(...e)}f?.length&&(w=w.filter((t=>!f.includes(t))));const T=i?t?.filter((t=>w.includes(t.participantId))):void 0;if(T?.forEach((t=>{const e=(o.entries??[]).find((e=>e.participantId===t.participantId));t.entryPosition=e?.entryPosition})),T?.sort(((t,e)=>(t.entryPosition||1/0)-(e.entryPosition||1/0))),w.length)return{validAlternatesAction:vr({payload:{drawId:p,structureId:u,drawPosition:s},willDisableLinks:e,method:Tw,availableAlternatesParticipantIds:w,type:Ow,availableAlternates:T})};return{}}({possiblyDisablingAction:N,tournamentParticipants:c,positionAssignments:E,activeDrawPositions:h,returnParticipants:n,appliedPolicies:I,drawDefinition:a,drawPosition:o,validActions:M,structureId:p,structure:d,drawId:R,event:s});t&&M.push(t)}if(tT({policyActions:b,action:_w})&&!D&&E){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}=ts({structureId:e,drawDefinition:o}),r={};if(n?.finishingPosition===Ko&&(1!==l?.length||1!==m?.length)){const{matchUps:t}=Yp({drawDefinition:o,structure:u,event:p}),{initialRoundNumber:e}=vl({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}=Kp({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!==id||t===id))).map((({winningSide:t,sides:e})=>t&&e?.[1-(t-1)])).map(Ua("participantId")).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:_w,method:Pw,availableLuckyLosers:g,availableLuckyLoserParticipantIds:f,willDisableLinks:n,payload:{drawId:d,structureId:c,drawPosition:s}}};return{}}({sourceStructuresComplete:T,possiblyDisablingAction:N,isWinRatioFedStructure:P,tournamentParticipants:c,activeDrawPositions:h,positionAssignments:E,drawDefinition:a,drawPosition:o,structureId:p,structure:d,drawId:R});t&&M.push(t)}if($?.participantType===uc&&tT({policyActions:b,action:Ew})){const{validModifyAssignedPairAction:t}=function({tournamentParticipants:t,returnParticipants:e,drawPosition:n,participant:r,drawId:i,event:a}){const o=a?.entries?.filter((({entryStatus:t})=>[Qc,tu].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:vr({payload:{participantId:r.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:n,drawId:i},method:Nw,availableIndividualParticipantIds:o,availableIndividualParticipants:s,existingIndividualParticipantIds:a,existingIndividualParticipants:c,type:Ew},!1,!1,!0)}}return{}}({tournamentParticipants:c,returnParticipants:n,drawPosition:o,participant:$,drawId:R,event:s});t&&M.push(t)}return{hasPositionAssigned:!!C,isActiveDrawPosition:G,isDrawPosition:!0,isByePosition:V,validActions:M}},tallyParticipantResults:kg,tournamentMatchUps:Uw,validateCollectionDefinition:mh,validateLineUp:Df,validMatchUp:Sc,validMatchUps:yc};function AT({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===NU)),o=a?.scaleValue,{wtnRating:s,confidence:c}=o||{};return{timeStamp:a?.scaleDate,personOtherId:r,confidence:c,wtnRating:s,personId:n,tennisId:i}}function ET({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=>AT({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}}const CT={getStructureReports:function({firstFlightOnly:t=!0,extensionProfiles:e,tournamentRecord:n}){if(!n)return{error:B};const r={},i=Object.assign({},...(e??[]).map((({name:t,label:e,accessor:r})=>{const i=Mr({element:n,name:t})?.extension?.value;return{[e||t]:r?la({element:i,accessor:r})?.value:i}}))),a=n?.tournamentId,o=hl({participantsProfile:{withScaleValues:!0},tournamentRecord:n}).matchUps??[],s=t=>{const e=il({itemType:cs,itemSubTypes:[Fr],element:{timeItems:t}})?.timeItem;return e?.itemValue?.scaleBasis},c=n?.events?.flatMap((({timeItems:e,drawDefinitions:n=[],extensions:c,eventType:u,eventId:d,category:p})=>{const l=c?.find((t=>t.name===Ki)),m=l?.value?.flights?.map((t=>({[t.drawId]:t.flightNumber}))),f=m&&Object.assign({},...m),h=c?.find((t=>t.name===zi))?.value?.length||0,g=Object.values(f),I=f&&Math.min(...g),U=s(e);return r[d]={totalPositionManipulations:0,maxPositionManipulations:0,generatedDrawsCount:0,drawDeletionsCount:h,seedingBasis:U?JSON.stringify(U):void 0,tournamentId:a,eventId:d},n.filter((e=>!t||!m||f[e.drawId]===I)).flatMap((t=>{const{matchUpFormat:e,tieFormat:n,timeItems:c,extensions:l,structures:m,drawType:h,drawId:g}=t,{matchUpFormatCounts:I,matchUpsCount:S,avgConfidence:y,pctNoRating:v,avgWTN:w}=ET({eventType:u,matchUps:o,drawId:g}),T=s(c)||U,P=function({extensions:t}){return t?.find((({name:t})=>t===ji))?.value?.slice(1)}({extensions:l}),D=P?.length||0;return r[d].totalPositionManipulations+=D,r[d].generatedDrawsCount+=1,D>r[d].maxPositionManipulations&&(r[d].maxPositionManipulations=D),m?.filter((t=>1===t.stageSequence&&[Qa,Xa,to,no].includes(t.stage))).map((t=>{const r=[Xa,no].includes(t.stage)?o.find((e=>e.structureId===t.structureId&&1===e.finishingRound&&e.winningSide)):void 0,s=r?.sides?.find((t=>t.sideNumber===r.winningSide)),c=s?.participant,l=c?.participantType===oc&&c.participantId,m=c?.participantType===uc?c.individualParticipants:[],U=AT({participant:m?.[0]||c,eventType:u}),{personId:D,personOtherId:b,tennisId:N,confidence:R,wtnRating:M}=U||{},A=AT({participant:m?.[1],eventType:u}),{personId:E,personOtherId:C,tennisId:O,confidence:F,wtnRating:k}=A||{},{ageCategoryCode:x,categoryName:_,subType:L}=p??{},B=t.matchUpFormat||e,V=(I[B]||0)/S*100,{tieFormatName:j,tieFormatDesc:G}=Ih(n),{tieFormatName:q,tieFormatDesc:$}=Ih(t.tieFormat),W=G===$,H=!W&&q,z=t.tieFormat&&!W&&$,Y=P?.filter((e=>e.structureId===t.structureId))?.length||0;return{...i,tournamentId:a,eventId:d,structureId:t.structureId,drawId:g,eventType:u,category:L,categoryName:_,ageCategoryCode:x,flightNumber:f[g],drawType:h,stage:t.stage,seedingBasis:T?JSON.stringify(T):void 0,winningPersonId:D,winningPersonOtherId:b,winningPersonTennisId:N,winningPersonWTNrating:M,winningPersonWTNconfidence:R,winningPerson2Id:E,winningPerson2OtherId:C,winningPerson2TennisId:O,winningPerson2WTNrating:k,winningPerson2WTNconfidence:F,winningTeamId:l,positionManipulations:Y,pctNoRating:v,matchUpFormat:B,pctInitialMatchUpFormat:V,matchUpsCount:S,drawTieFormatName:j,drawTieFormatDesc:G,tieFormatName:H,tieFormatDesc:z,avgConfidence:y,avgWTN:w}}))}))}));return{eventStructureReports:Object.values(r),structureReports:c}},getEntryStatusReports:function({tournamentRecord:t}){if(!t)return{error:_};const e=t.tournamentId,{participantMap:n}=Zl({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:t,withDraws:!0}),r=(hl({matchUpFilters:{matchUpTypes:[Ys,Js]},tournamentRecord:t}).matchUps??[]).flatMap((({sides:t,matchUpType:e})=>t?.flatMap((t=>e===Js?t?.participant?.individualParticipantIds:t?.participant?.participantId||t.participantId)).filter(Boolean))).filter(Boolean),i=[],a={},o={},s={};let c=0;const u=({id:t,entry:r,eventId:o,eventType:s})=>{const{qualifyingSeeding:c,mainSeeding:u,entryStatus:d,entryStage:p,drawId:l}=r;a[t]||(a[t]=[]);const{participant:m,events:f}=n?.[t]??{},h=AT({participant:m,eventType:s}),g=f?.[o]?.ranking;d===Fw&&i.push(t),a[t].push({participantType:m?.participantType,participantId:t,tournamentId:e,eventType:s,eventId:o,drawId:l,entryStatus:d,entryStage:p,...h,ranking:g,mainSeeding:u,qualifyingSeeding:c})};for(const i of t.events??[]){const t={},a=e=>{t[e]||(t[e]={count:0}),t[e].count+=1},{drawDefinitions:d=[],eventType:p,eventId:l}=i,m=d.flatMap((t=>{const{drawId:e,entries:r}=t;c+=1;const i=(t.structures??[]).filter((({stage:t,stageSequence:e})=>t===Xa&&1===e||t===Qa)).flatMap((({positionAssignments:t})=>t)).filter(Boolean).map((({participantId:t})=>t));return r?.filter((({participantId:t})=>i.includes(t))).map((t=>{const{participantId:r,entryStatus:i,entryStage:o}=t;a(i);const s=n?.[r]?.draws?.[e]?.seedAssignments?.[Xa],c=n?.[r]?.draws?.[e]?.seedAssignments?.[Qa];return{qualifyingSeeding:c,participantId:r,mainSeeding:s,entryStatus:i,entryStage:o,drawId:e}}))})),f=t=>{const e=t.participantId,i=n?.[e].participant.individualParticipantIds?.filter((t=>r.includes(t)));return e&&{[e]:{individualParticipantIds:i}}};p===rd?(()=>{const t=Object.assign({},...m.map(f).filter(Boolean));m.forEach((e=>{t[e.participantId].individualParticipantIds.forEach((t=>{u({id:t,eventType:p,eventId:l,entry:e})}))}))})():m.forEach((t=>{u({id:t?.participantId,eventType:p,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})),s[l]={tournamentId:e,eventId:l,entries:m,entryStatuses:t};const g=Object.assign({},...ou.flatMap((e=>[{[e+"_count"]:t[e]?.count},{[e+"_pct"]:t[e]?.pct}])));o[l]={tournamentId:e,eventId:l,...g}}const d=Object.values(n??{}).filter((({participant:{participantType:t,participantRole:e}})=>t===sc&&e===um)),p=d.filter((({participant:t})=>!r.includes(t.participantId))).map((({participant:t})=>t.participantId)),l={nonParticipatingEntriesCount:p.length,individualParticipantsCount:d.length,eventsCount:Object.values(s).length,nonParticipatingParticipantIds:p,drawDefinitionsCount:c,tournamentId:e};return{entryStatusReports:Object.values(o).flat(),participantEntryReports:Object.values(a).flat(),eventReports:Object.values(s).flat(),withDrawnParticipantIds:i,tournamentEntryReport:l}},getParticipantStats:function({withCompetitiveProfiles:t,opponentParticipantId:e,withIndividualStats:n,teamParticipantId:r,tournamentRecord:i,withScaleValues:a,tallyPolicy:o,matchUps:s}){if(!i)return{error:_};if(s&&!Array.isArray(s))return{error:Yt};if(s=s??hl({tournamentRecord:i,participantsProfile:a?{withScaleValues:a}:void 0}).matchUps,!s?.length)return{error:Ht};const c=[];e&&c.push(e),r&&c.push(r);const u=Zl({participantFilters:c.length?{participantIds:c}:{participantTypes:[oc]},tournamentRecord:i}).participants??[];if(!u.every((({participantType:t})=>t===oc)))return{error:Pe};c.length||c.push(...u.map(Ua("participantId")));const d=new Map,p=new Map,l=new Map,m=new Map,f=(t,e="")=>p.get(t)||p.set(t,{participantName:e,participantId:t,competitorIds:[],competitiveness:{},matchUpStatuses:{},tiebreaks:[0,0],matchUps:[0,0],points:[0,0],games:[0,0],sets:[0,0]})&&p.get(t);for(const t of u){const{participantId:e,individualParticipantIds:n}=t;m.set(e,n??[]),f(e,t.participantName)}if(r&&!m.get(r))return wr({result:{error:Ee},context:{teamParticipantId:r}});if(e&&!m.get(e))return wr({result:{error:Ee},context:{opponentParticipantId:e}});const h=[],g=t=>{const i=[[],[]];for(const e of t){const t=e.participant;if(t?.participantName){d.set(t.participantId,{participantName:t.participantName,ratings:t.ratings});const e=p.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||P(e,t.participant?.individualParticipantIds).length===t.participant?.individualParticipantIds?.length)&&t.participant.individualParticipantIds;if(m.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=p.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:m.get(r),side:t})||a({individualParticipantIds:m.get(e),side:t})))))&&o(r,m.get(r))}else for(const[t,e]of m)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 s){if(!ha(e))return{error:Yt};const{matchUpStatus:n,matchUpFormat:r,matchUpType:i,winningSide:a,score:s,sides:c}=e;if(!c||!s||i===Xs||n===Ma)continue;const u=g(c);if(!u.filter(Boolean).length)continue;const p=t&&a&&Su({matchUp:e})?.competitiveness;h.push(e);const l=hg({matchUpStatus:n,matchUpFormat:r,tallyPolicy:o,winningSide:a,score:s}),m=gg({matchUpStatus:n,matchUpFormat:r,tallyPolicy:o,winningSide:a,score:s}),{pointsTally:I,tiebreaksTally:U}=Ig({matchUpFormat:r,score:s});u.forEach(((t,e)=>{for(const r of t){const t=d.get(r)?.participantName,i=f(r,t);if(i){const t=(t,e)=>e.forEach(((e,n)=>i[t][n]+=e)),r=e?[...U].reverse():U,o=e?[...I].reverse():I,s=e?[...m].reverse():m,c=e?[...l].reverse():l;if(t("tiebreaks",r),t("points",o),t("games",s),t("sets",c),a){const t=a-1===e?0:1;i.matchUps[t]+=1}if(p){const t=p.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 I=["tiebreaks","matchUps","points","games","sets"],U=["competitive","routine","decisive"],S=new Map,y=(t,e)=>(t??0)+(e??0);for(const[t,e]of p.entries()){for(const n of I){const r=e[n].reduce(y);if(r){const i=e[n][0]/r,a=`${n}Ratio`,o=parseFloat(i.toFixed(2));e[a]=o,l.set(t,!0),S.has(a)||S.set(a,[]),S.get(a)?.push(o)}}for(const t of U){const n=e.competitiveness?.[t]?.reduce(y);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 p.values())for(const n of I){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 v={relevantMatchUps:h,...E};return r?(v.teamStats=p.get(r),e&&(v.opponentStats=p.get(e))):v.participatingTeamsCount=l.size,v.allParticipantStats=[...p.values()],v}};function OT(t=0){const e=new Date;return e.setHours(e.getHours()+t),e.getTime().toString(36).slice(-6).toUpperCase()}function FT({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===Ly&&(e=ri(e),n=ni(n),r=ni(r),e&&n&&r)?{date:e,startTime:n,endTime:r,requestType:t.requestType}:t})).filter(Boolean);for(const n of r)n.requestId=OT(),t[e].push(n);return{mergeCount:r.length}}function kT(t){const{tournamentRecords:e,personRequests:n}=t,r=Lp(t,[{[sp]:!0}]);if(r.error)return r;if(!n)return{...E};const i=Object.values(e);for(const t of i){const e=t.participants??[],r=[];for(const t of Object.keys(n))if(Fi({tournamentParticipants:e,personId:t})){const e=n[t];e.length&&r.push({personId:t,requests:e})}if(Object.keys(r).length){Nr({element:t,extension:{value:r,name:ea}})}}return{...E}}function xT({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:x};o=o??ly({recoveryMinutes:e,averageMatchUpMinutes:n});const{courts:p,venues:l}=Am({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||fi(s,t.date))),r=n?.startTime??e.startTime;return r&&(!t||ti(r)<ti(t))?r:t}),void 0)),d||(d=m?.reduce(((t,e)=>{const n=e.dateAvailability?.find((t=>!t.date||fi(s,t.date))),r=n?.endTime??e.endTime;return r&&(!t||ti(r)>ti(t))?r:t}),void 0));const f=Object.values(a),h=Object.assign({},...f.map((t=>(t.events??[]).map((e=>{const{scheduleTiming:n}=Qu({tournamentRecord:t,event:e});return{[e.eventId]:{event:e,scheduleTiming:n}}})))).flat()),g=yw({sortDateMatchUps:!1,tournamentRecords:a,matchUpFilters:{scheduledDate:s,venueIds:u}}),I=g?.dateMatchUps??[],U=g?.completedMatchUps??[],S=[];S.push(...I),S.push(...U);const y={averageTimes:[{minutes:{default:n}}],recoveryTimes:[{minutes:{default:e}}]},v=S?.map((({eventId:t,schedule:e,matchUpFormat:n})=>{const{event:r,scheduleTiming:i}=h[t],a=r?.eventType,s={...i,defaultTiming:y,matchUpFormat:n},{averageMinutes:c,recoveryMinutes:u}=yd({eventType:a,timingDetails:s}),{courtId:d,venueId:p}=e,l=ni(e.scheduledTime),m=pi(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:T}=fy(w);return{venueId:1===u?.length&&u[0]||1===l?.length&&l[0].venueId||void 0,scheduleTimes:T,dateScheduledMatchUpIds:S.map(ba)}}function _T(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:x};const s=Object.keys(o).filter((t=>!i||i===t));if(i&&!s.includes(i))return{error:Nn};let c;for(const t of s){const i=o[t],{event:s}=Vd({tournamentRecord:i,eventId:a});a&&s&&(c=!0);const u=LT({tournamentRecord:i,event:s,matchUpFormat:e,averageTimes:r,recoveryTimes:n});if(u.error)return u}return!a||c?{...E}:{error:Pt}}function LT({tournamentRecord:t,recoveryTimes:e,matchUpFormat:n,averageTimes:r,event:i}){if(!t)return{error:_};if(r&&!Array.isArray(r))return{error:Nn};if(e&&!Array.isArray(e))return{error:Nn};const a=aa;if(i){const{extension:t}=Mr({element:i,name:a});Nr({element:i,extension:{name:a,value:BT({...t?.value||{},matchUpFormat:n,averageTimes:r,recoveryTimes:e})}})}else{const{extension:i}=Mr({element:t,name:a});Nr({extension:{name:a,value:BT({...i?.value||{},matchUpFormat:n,averageTimes:r,recoveryTimes:e})},element:t})}return{...E}}function BT(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 VT({event:t}){return Bi({event:t,name:aa})}function jT({tournamentRecord:t,scheduleChange:e,matchUpIds:n,dryRun:r}){if(!t)return{error:_};if(!n||!Array.isArray(n))return{error:$t};if("object"!=typeof e)return{error:Nn};const i=[],a=[],{minutesChange:o,daysChange:s}=e;if(!o&&!s)return{...E};if(o&&isNaN(o))return{error:Nn};if(s&&isNaN(s))return{error:Nn};const{matchUps:c}=hl({matchUpFilters:{matchUpIds:n},tournamentRecord:t}),u=c?.filter((t=>Wy({schedule:t.schedule}))).filter((t=>(({matchUpStatus:t})=>!Ya.includes(t))({matchUpStatus:t.matchUpStatus})));if(!u?.length)return{...E};const{tournamentInfo:d}=jm({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=Oy({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=ii(ri(m),s),f=new Date(g)<new Date(p)||new Date(g)>new Date(l)}if(o&&c){const t=ri(c),e=ti(ni(c))+o;if(f=e<0||e>1440,!f){const e=pi(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=mI({scheduledTime:h,drawDefinition:d,matchUpId:t});if(e.error)return e}if(g){const e=II({scheduledDate:g,drawDefinition:d,matchUpId:t});if(e.error)return e}}(h||g)&&i.push(t)}}}const f=hl({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{...E,rescheduled:h,notRescheduled:g,allRescheduled:I}}const GT={addMatchUpCourtOrder:UI,addMatchUpEndTime:yI,addMatchUpOfficial:function({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,participantId:i,officialType:a,matchUpId:o}){if(!o)return{error:qt};if(!i)return{error:Ae};if(e){if(!Fi({tournamentParticipants:Zl({tournamentRecord:e,participantFilters:{participantTypes:[sc],participantRoles:[dm]}}).participants??[],participantId:i}))return{error:Ee}}const s={itemType:"SCHEDULE.ASSIGNMENT.OFFICIAL",itemValue:i};return a&&(s.itemSubTypes=[a]),Ff({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:o,timeItem:s})},addMatchUpResumeTime:wI,addMatchUpScheduledDate:II,addMatchUpScheduledTime:mI,addMatchUpScheduleItems:gI,addMatchUpStartTime:SI,addMatchUpStopTime:vI,addPersonRequests:function(t){const{tournamentRecords:e,personId:n,requests:r}=t,i=Lp(t,[{[sp]:!0,personId:!0},{requests:!0,[Fp]:Ep,[Op]:Nn}]);if(i.error)return i;const{personRequests:a}=nv({tournamentRecords:e}),{mergeCount:o}=FT({personRequests:a,personId:n,requests:r});return o&&a?kT({tournamentRecords:e,personRequests:a}):{error:Nn}},addSchedulingProfileRound:$v,allocateTeamMatchUpCourts:dI,assignMatchUpCourt:lI,assignMatchUpVenue:pI,bulkRescheduleMatchUps:function(t){const{scheduleChange:e,matchUpIds:n,dryRun:r}=t;if(!n||!Array.isArray(n))return{error:$t};if("object"!=typeof e)return{error:Nn};const i=nc(t),a=[];let o=[];for(const t of Object.values(i)){const i=jT({tournamentRecord:t,scheduleChange:e,matchUpIds:n,dryRun:r});if(i.error)return i;Array.isArray(i.notRescheduled)&&o.push(...i.notRescheduled);const s=Ta(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{...E,rescheduled:a,notRescheduled:o,allRescheduled:s}},bulkScheduleMatchUps:tv,bulkScheduleTournamentMatchUps:Qy,bulkUpdateCourtAssignments:function(t){const{courtDayDate:e}=t,n=Lp(t,[{[sp]:!0},{courtAssignments:!0,[Fp]:Ep,[Op]:ae}]);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[sp][n];if(!a)return i={error:_},!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}=Vd({tournamentRecord:a,drawId:t});return n?(o[t].every((t=>{const{matchUpId:r,courtId:o}=t,s=lI({tournamentRecord:a,drawDefinition:n,courtDayDate:e,matchUpId:r,courtId:o});if(s.success)return s?.success;i={error:yn}})),!0):(i={error:j},!1)}))})),i||E},calculateScheduleTimes:xT,clearMatchUpSchedule:function({scheduleAttributes:t=[Pu,Du,Tu,Nu,Mu,Au,Ou,Cu,Eu],tournamentRecord:e,drawDefinition:n,matchUpId:r}){const i=n?Ul({matchUpFilters:{matchUpIds:[r]},inContext:!1,drawDefinition:n}).matchUps?.[0]:hl({matchUpFilters:{matchUpIds:[r]},tournamentRecord:e,inContext:!1}).matchUps?.[0];if(!i)return{error:Wt};const a=(i.timeItems??[]).filter((e=>e?.itemType&&!t.includes(e?.itemType)));return i.timeItems=a,xs({tournamentId:e.tournamentId,context:"clearMatchUpSchedule",drawDefinition:n,matchUp:i}),{...E}},clearScheduledMatchUps:iv,courtGridRows:gw,findCourt:function(t){return gi(Od(t),!1,!0)},findMatchUpFormatTiming:jy,findVenue:Cd,generateBookings:Yy,generateVirtualCourts:py,getProfileRounds:bT,getSchedulingProfile:Om,matchUpScheduleChange:function(t){const e="matchUpScheduleChange",{tournamentRecords:n}=t;if("object"!=typeof n||!Object.keys(n).length)return{error:x};const{sourceMatchUpContextIds:r,targetMatchUpContextIds:i,sourceCourtId:a,targetCourtId:o,courtDayDate:s}=t||{},{drawId:c,matchUpId:u,tournamentId:d}=r||{},{drawId:p,matchUpId:l,tournamentId:m}=i||{};if(!u&&!l)return wr({result:{error:ae},stack:e});const{matchUps:f}=gl({matchUpFilters:{matchUpIds:[u,l].filter(Boolean),drawIds:[c,p].filter(Boolean)},tournamentRecords:t.tournamentRecords}),h=f?.find((({matchUpId:t})=>t===u)),g=f?.find((({matchUpId:t})=>t===l));let I=0;if(o&&u&&!l){const t=U({tournamentId:d,matchUpId:u,courtId:o,matchUp:h,drawId:c,tournamentRecords:n,sourceCourtId:a,courtDayDate:s});if(t?.success&&I++,t.error)return wr({result:t,stack:e})}else{if(!(a&&o&&u&&l))return{error:ae};{const t=U({tournamentId:d,matchUpId:u,courtId:o,matchUp:h,drawId:c,tournamentRecords:n,sourceCourtId:a,courtDayDate:s});if(t.success&&I++,t.error)return wr({result:t,stack:e,info:"source"});const r=U({tournamentId:m,sourceCourtId:o,matchUpId:l,matchUp:g,courtId:a,drawId:p,tournamentRecords:n,courtDayDate:s});if(r.success&&I++,r.error)return wr({result:r,stack:e,info:"target"})}}return I?E:wr({result:{error:Sn},stack:e});function U(t){const{tournamentRecords:e,tournamentId:n,matchUp:r,drawId:i}=t,a=e[n],{drawDefinition:o}=Oy({tournamentRecord:a,drawId:i});return r.matchUpType===Qs?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 dI({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,courtDayDate:a,matchUpId:o,courtIds:u})}({...t,tournamentRecord:a,drawDefinition:o}):lI({...t,tournamentRecord:a,drawDefinition:o})}},modifyEventMatchUpFormatTiming:function(t){const{tournamentRecord:e,recoveryMinutes:r,averageMinutes:i,matchUpFormat:a,categoryType:o,eventId:s,event:c}=t;if(!e)return{error:_};if(!rh(a))return{error:Nn};if(!c)return{error:Tt};const{averageTimes:u=[],recoveryTimes:d=[]}=mw({tournamentRecord:e,matchUpFormat:a,event:c}),p=c.category,l=p?.categoryName||p?.ageCategoryCode||c?.eventId;let m={categoryNames:[l],minutes:{}};const f={categoryNames:[l],minutes:{}},h=t=>{if(t.categoryTypes?.includes(o)&&console.log("encountered:",{categoryType:o}),!t.categoryNames?.includes(l)||(t.categoryNames=t.categoryNames.filter((t=>t!==l)),m={minutes:t.minutes,categoryNames:[l]},t.categoryNames.length))return t},g=i&&!isNaN(n(i)),I=r&&!isNaN(n(r)),U=u.map(h).filter((t=>t?.categoryNames?.length)),S=d.map(h).filter((t=>t?.categoryNames?.length));return g&&(Object.assign(m.minutes,{[c?.eventType||Ks]:i}),U.push(m)),I&&(Object.assign(f.minutes,{[c?.eventType||Ks]:r}),S.push(f)),g||I?_T({averageTimes:g&&U,recoveryTimes:I&&S,tournamentRecord:e,matchUpFormat:a,eventId:s,event:c}):{error:Nn}},modifyMatchUpFormatTiming:_T,modifyPersonRequests:function(t){const{tournamentRecords:e,requests:n,personId:r}=t,i=Lp(t,[{[sp]:!0},{requests:!0,[Fp]:Ep,[Op]:Nn}]);if(i.error)return i;const a=n.map((({requestId:t})=>t)).filter(Boolean),{personRequests:o}=nv({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&&FT({personRequests:o,personId:r,requests:c}),kT({tournamentRecords:e,personRequests:o})},proAutoSchedule:function({scheduleCompletedMatchUps:t,tournamentRecords:e,scheduledDate:n,matchUps:r}){if(!yc(r))return{error:Nn};if(r.some((({hasContext:t})=>!t)))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:hn};let i=yw({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(ha(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=>ha(t)&&!t.matchUpId));return t.concat({matchUpIds:n,availableCourts:i,rowId:e.rowId,participantIds:r})}),[]);r.filter((({matchUpStatus:e})=>e&&e!==Ma&&(t||!Ya.includes(e)))).sort(Il);const u=Sl({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=tv({tournamentRecords:e,matchUpDetails:l});const m=r;return{...i,scheduled:d,notScheduled:m}},proConflicts:function({tournamentRecords:t,matchUps:e}){if(!yc(e))return{error:Ht};if(e.some((({matchUpId:t,hasContext:e})=>t&&!e)))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:hn};const r=w(1,Math.max(...e.map((({schedule:t})=>t?.courtOrder||1)).map((t=>n(t))))+1).map((t=>e.filter((e=>n(e.schedule?.courtOrder)===t)))),i={},a={},o={};r.flat().filter(Boolean).sort(Il).forEach((({schedule:t})=>delete t[Id]));const s=Sl({includeParticipantDependencies:!0,tournamentRecords:t,drawIds:m(e.map((({drawId:t})=>t)))}).matchUpDependencies,c=r.map(((t,e)=>t.reduce(((t,n)=>{if(!n.matchUpId)return t;const{matchUpId:r,winnerMatchUpId:c,loserMatchUpId:u,schedule:d,sides:p,potentialParticipants:l}=n,m=d?.courtId;i[r]=e,a[m]=[],t.matchUpIds.push(r),o[r]=n;const f=s[r].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:[]}))),u=c.map((()=>[])),d=(t,e,n,r)=>{if(!o[t].schedule[Id]){o[t].schedule[Id]=e,o[t].schedule[ld]=r,u[i[t]].push({matchUpId:t,issueType:n,issueIds:r,issue:e});const s=o[t].schedule.courtId;a[s]||(a[s]=[]),a[s].push({matchUpId:t,issue:e,issueType:n,issueIds:r})}};return c.forEach(((t,e)=>{const n=e?c[e-1]:void 0,r=c.slice(e+1),i={},a=g(t.participantIds),u=Object.keys(a).filter((t=>a[t]>1)),p=t.matchUpIds.filter((t=>s[t].participantIds.some((t=>u.includes(t)))));p.forEach((t=>{i[t]||(i[t]={}),i[t][md]||(i[t][md]=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=>s[t].participantIds.includes(e)));r.forEach((t=>{i[t]||(i[t]={}),i[t][fd]||(i[t][fd]=r.filter((e=>e!==t)))}))})),t.matchUpIds.forEach((e=>{const a=s[e].matchUpIds;for(const t of r){const n=t.matchUpIds.filter((t=>a.includes(t)));n?.length&&(n.forEach((t=>d(t,hd,pd,[e]))),d(e,hd,pd,n))}if(i[e]?.[md]&&d(e,md,dd,i[e][md]),t.sourceMatchUpIds.includes(e)){const n=t.matchUpIds.filter((t=>s[t].matchUpIds.includes(e)));d(e,md,pd,n),t.matchUpIds.filter((t=>s[t].matchUpIds.includes(e))).forEach((t=>d(t,md,pd,[e])))}const c=n?.matchUpIds?.filter((t=>{return n=t,s[e].sources.reduce(((t,e,r)=>e.includes(n)&&r+1||t),0)>1;var n}));if(c?.length&&(d(e,gd,pd,c),c.forEach((t=>d(t,gd,pd,[e])))),i[e]?.[fd]&&d(e,fd,dd,i[e][fd]),n?.targetMatchUpIds?.includes(e)){const t=o[e].schedule.courtId,r=a.filter((t=>n.matchUpIds.includes(t)));r.some((e=>o[e].schedule.courtId===t))||(r.forEach((t=>d(t,fd,pd,[e]))),d(e,fd,pd,r))}}))})),{courtIssues:a,rowIssues:u}},removeEventMatchUpFormatTiming:function(t){if(t.event)return VT({event:t.event});{t.tournamentRecord&&!t.tournamentRecords&&(t.tournamentRecords={[t.tournamentRecord.tournamentId]:t.tournamentRecord});const e=Lp(t,[{[sp]:!0,[Pp]:!0}]);if(e.error)return e;const{tournamentRecords:n,eventId:r}=t;for(const t of Object.values(n??{})){const{event:e}=Vd({tournamentRecord:t,eventId:r});if(e)return VT({event:e})}}return{error:Pt}},removeMatchUpCourtAssignment:function(t){const e=Lp(t,[{[sp]:!0}]);if(e.error)return e;const{removePriorValues:n,tournamentRecords:r,tournamentId:i,courtDayDate:a,matchUpId:o,courtId:s,drawId:c}=t,u=r[i];if(!u)return{error:_};const{drawDefinition:d,event:p}=Oy({tournamentRecord:u,drawId:c});if(!d)return{error:j};const l=Xm({drawDefinition:d,event:p,matchUpId:o});if(l.error)return l;if(l?.matchUp?.matchUpType===Xs){const{itemValue:t}=wd({timeItems:l.matchUp.timeItems??[],itemType:Pu}),e=s&&t.filter((t=>t.courtId!==s));return Ff({duplicateValues:!1,removePriorValues:n,tournamentRecord:u,drawDefinition:d,matchUpId:o,timeItem:{itemType:Pu,itemValue:e}})}return lI({tournamentRecord:u,drawDefinition:d,courtDayDate:a,courtId:"",matchUpId:o})},removePersonRequests:function(t){const{tournamentRecords:e,requestType:n,requestId:r,personId:i,date:a}=t,o=Lp(t,[{[sp]:!0}]);if(o.error)return o;const{personRequests:s}=nv({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?kT({tournamentRecords:e,personRequests:s}):Dr({name:ea,tournamentRecords:e,discover:!0})},reorderUpcomingMatchUps:function(t){const e="reorderUpcomingMatchUps",{tournamentRecords:n}=t;if("object"!=typeof n||!Object.keys(n).length)return wr({result:{error:x},stack:e});const{matchUpsContextIds:r,firstToLast:i}=t;if(!r)return wr({result:{error:ae},stack:e});const a=r?.length;if(!a)return{...E};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}=Oy({tournamentRecord:a,drawId:i});return o?mI({drawDefinition:o,scheduledTime:e,matchUpId:r}):{error:q}}({tournamentId:s,scheduledTime:r[d].schedule.scheduledTime,matchUpId:u,drawId:c});if(!p.success)return p;o++})),o===a?E:wr({result:{error:Un},stack:e})},scheduleMatchUps:function(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:S}=t,y=Lp(t,[{[sp]:!0,[hp]:!0},{[Cp]:Wr,[Op]:pe,scheduleDate:!0},{[Cp]:t=>!t||!isNaN(t),averageMatchUpMinutes:!0,[Op]:Nn,recoveryMinutes:!0,periodLength:!0}]);if(y.error)return y;const v=t.competitionMatchUps??gl({nextMatchUps:!0,tournamentRecords:e}).matchUps??[],w=t.matchUpDependencies??Sl({includeParticipantDependencies:!0,matchUps:v,tournamentRecords:e}).matchUpDependencies;v.forEach((t=>{t.schedule?.scheduledDate&&fi(f,ri(t.schedule.scheduledDate))&&Fy({matchUpPotentialParticipantIds:o,matchUpNotBeforeTimes:c,matchUp:t})}));const T=h.map((t=>v.find((e=>e.matchUpId===t)))).filter(Boolean),{venueId:P,scheduleTimes:D,dateScheduledMatchUpIds:b}=xT({tournamentRecords:e,remainingScheduleTimes:p,startTime:ni(I),endTime:ni(U),scheduleDate:ri(f),averageMatchUpMinutes:r,clearScheduleDates:l,periodLength:m,venueIds:g}),N={},R=[],M={},A={},C={},O=v.filter((({matchUpId:t})=>b?.includes(t)));O.forEach((t=>{$y({matchUpPotentialParticipantIds:o,individualParticipantProfiles:s,matchUp:t,value:1});const e=t.schedule?.scheduledTime;if(e){M[t.matchUpId]=e;const n=a?.[t.matchUpId];xy({recoveryMinutes:n||i,matchUpPotentialParticipantIds:o,individualParticipantProfiles:s,matchUpNotBeforeTimes:c,averageMatchUpMinutes:r,matchUpDependencies:w,scheduleTime:e,matchUp:t})}}));let F=T.filter((t=>{const e=b?.includes(t.matchUpId),n=[Ma,Oa,Ea,Na,Ba,Ga].includes(t?.matchUpStatus);return!e&&!t.winningSide&&!n}));const{matchUpMap:k,overLimitMatchUpIds:x,participantIdsAtLimit:_}=F.reduce(((t,e)=>{const{drawId:n,tournamentId:r,matchUpType:i}=e,{participantIdsAtLimit:a,relevantParticipantIds:d}=Xy({individualParticipantProfiles:s,matchUpPotentialParticipantIds:o,matchUpDailyLimits:u,matchUp:e});return a?.length?(t.overLimitMatchUpIds.push(e.matchUpId),t.participantIdsAtLimit.push(...a),t):(d.forEach((t=>{ky({individualParticipantProfiles:s,participantId:t});const e=s[t].counters;e[i]?e[i]+=1:e[i]=1,e[ud]?e[ud]+=1:e[ud]=1})),t.matchUpMap[r]||(t.matchUpMap[r]={}),t.matchUpMap[r][n]?t.matchUpMap[r][n].push(e):t.matchUpMap[r][n]=[e],Fy({matchUpPotentialParticipantIds:o,matchUpNotBeforeTimes:c,matchUp:e}),t)}),{matchUpMap:{},overLimitMatchUpIds:[],participantIdsAtLimit:[]});F=F.filter((({matchUpId:t})=>!x.includes(t)));let L=0;const B=D?.length??0,{personRequests:V}=nv({tournamentRecords:e,requestType:Ly});for(;D?.length&&F.length&&L<=B;){L++;const{scheduleTime:t}=D.shift(),e=F.find((e=>{const{matchUpId:u}=e,{dependenciesScheduled:p,remainingDependencies:l}=Cy({matchUpScheduleTimes:M,matchUpDependencies:w,allDateMatchUpIds:n,matchUp:e});if(!p)return C[u]||(C[u]=[]),C[u].push({scheduleTime:t,remainingDependencies:l}),!1;const{enoughTime:m}=Zy({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}=Vy({potentials:d,averageMatchUpMinutes:r,requestConflicts:N,personRequests:V,scheduleTime:t,scheduleDate:f,matchUp:e});if(h?.length)return!1;const g=a?.[e.matchUpId];return xy({recoveryMinutes:g||i,matchUpPotentialParticipantIds:o,individualParticipantProfiles:s,matchUpNotBeforeTimes:c,averageMatchUpMinutes:r,matchUpDependencies:w,scheduleTime:t,matchUp:e}),M[e.matchUpId]=t,!0}));F=F.filter((({matchUpId:t})=>t!==e?.matchUpId)),e||R.push(t)}F.forEach((t=>{$y({individualParticipantProfiles:s,matchUpPotentialParticipantIds:o,value:-1,matchUp:t})}));const j=[];Object.keys(k).forEach((t=>{const n=e[t];n&&Object.keys(k[t]).forEach((r=>{const{drawDefinition:i}=Oy({tournamentRecord:n,drawId:r});if(i){k[t][r].forEach((({matchUpId:t})=>{const r=M[t];if(r){const a=r.split(":").map(mi).join(":"),o=`${ri(f)}T${a}`;if(S)j.push(t);else{mI({drawDefinition:i,matchUpId:t,scheduledTime:o}).success&&j.push(t),P&&pI({tournamentRecords:e,tournamentRecord:n,drawDefinition:i,matchUpId:t,venueId:P})}}}))}}))}));const G=Ta(F);return{...E,requestConflicts:Object.values(N),remainingScheduleTimes:D?.map((({scheduleTime:t})=>t)),individualParticipantProfiles:s,matchUpNotBeforeTimes:c,participantIdsAtLimit:_,skippedScheduleTimes:R,overLimitMatchUpIds:x,scheduledMatchUpIds:j,noTimeMatchUpIds:G,recoveryTimeDeferred:A,dependencyDeferred:C}},scheduleProfileRounds:ov,setMatchUpDailyLimits:function(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:x};if("object"!=typeof r)return{error:Pn};const a=Object.keys(i).filter((t=>!n||n===t));if(n&&!a.includes(n))return{error:Nn};for(const t of a){const e=Nr({element:i[t],extension:{name:ia,value:{dailyLimits:r}}});if(e.error)return e}return{...E}},setSchedulingProfile:Fm,toggleParticipantCheckInState:_f,validateSchedulingProfile:Nm},qT="\\d+-\\d+",$T="\\d+-\\d+\\(\\d+\\)",WT="\\[\\d+-\\d+\\]",HT=new RegExp(`(${qT}),`,"g"),zT=new RegExp(`(${$T}),`,"g"),YT=[qT,$T,WT,"\\d+-\\d+\\(\\d+-\\d+\\)"],KT=["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=>YT[t])).join(" ");return new RegExp(`^${e}$`)}));function JT(t){return!t||KT.some((e=>e.test(t)))}function ZT(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function XT(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 QT(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 tP(t){return 2===t.length?t.split("").join("-"):([", ",",","/"," "].forEach((e=>t=t.split(e).join("-"))),t=t.replace(/-{2,}/,"-"))}function eP(t){return t.startsWith("(")&&t.endsWith(")")}function nP(t){if(!/^[\d-]+(\(\d\))*$/.test(t))return t;const e=T("-",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 rP({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=s(t)&&parseInt(t),c=void 0!==r[0]&&void 0!==r[1];if(s(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(c&&1===e.length&&s(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]}c&&o()}}return{sets:n}}function iP(t){const e=t.indexOf("1"),n=t.split(""),r=n.every((t=>!isNaN(t)));if(r&&3===t.length&&0===e){const t=QT(n,e);if(t)return t}if(r&&7===t.length&&e>3){const t=QT(n.slice(4),e-4);if(t)return`${n[0]}-${n[1]} ${n[2]}-${n[3]} ${t}`}}function aP(t){let{score:e}=t;const{applied:n,matchUpStatus:r}=t,i=e?.toString().split(""),a=i?.every((t=>s(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)));if(rP({score:e}),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=iP(e);t&&e!==t&&n.push("parsedSuperPattern"),e=t??e}else{const r=N(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=g(i),s=g(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 oP(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 sP={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 I=()=>{h=g(t.split("")),l=h["("]===(h[")"]||0)+1,p=(h["("]||0)+1===h[")"],m=h["["]===h["]"]+1,f=l&&!m};I();const U=/(\d+-\d+\(\d+)0,/;if(U.test(t)){const[e]=t.match(U).slice(1);t=t.replace(U,e+")")}if(h["("]===h[")"]&&h["("]>1){const e=t.split(")(").join(") (").split(" ");t=e.every(eP)?e.map((t=>{const e=t.slice(1,t.length-1);return e.length>2?e:t})).join(" "):e.join(" ")}I();const S=/[A-Za-z]+/.test(t),y=/\d+/.test(t);if(!S&&!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)+")",I()),1!==h["("]||h[")"]||"("!==t[0]||(t+=")",I()),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("")}I()}if(h[")"]>(h["("]||0)&&")"===t[0]&&(t="("+t.slice(1),I()),f&&(t.endsWith(9)||/\d+0$/.test(t))&&(t=t.slice(0,t.length-1)+")",I()),!f||t.endsWith(")")&&!t.startsWith("((")||(t+=")",I()),f){let e="",n=0;for(const r of t.split(""))"("===r&&(n?e+=")":n+=1),")"===r&&(n-=1),e+=r;t=e}if(I(),m&&!l&&(t+="]"),t.includes("([")&&t.includes("])")&&(t=t.split("([").join("[").split("])").join("]"),I()),/\(\d+0$/.test(t)&&(t=t.slice(0,t.length-1)+")"),I(),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),I()),/^\([\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,I())}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(ZT);let a=0,o="";for(const t of i){const n=T(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":XT(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=T("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;!XT(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(WT).test(t)?"super":new RegExp($T).test(t)&&"tiebreak")||new RegExp(qT).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(")")),[HT,zT].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(nP).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=>s(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=QT(t.split(""),n);return e.push("getSuper"),r}}else{const{score:n,applied:r}=aP({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=nP(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 S=/(.*)\s(1\d)\s(\d+)$/;if(S.test(t)){const[n,r,i]=t.match(S).slice(1);n.replace(/\D/g,"").length>=4&&(t=n+` ${r}${i}`,e.push("spaceSeparatedSuperPattern"))}const y=/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/g;for(const n of t.match(y)||[]){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)&&iP(t)){return{score:iP(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(XT(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(s(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=QT(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 XT(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:aP,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=nP(tP(r));t=t.replace(e,`(${a})`).trim()}const a=new RegExp(/\[[\d,/ ]+\]/g),o=t.match(a);o?.forEach((e=>{const n=tP(e.match(/^\[(.*)\]$/)[1]);t=t.replace(e,`(${n}) `).trim()}));const c=[")(","), (",") (",")[",") [","](","] ("];if(t.startsWith("(")&&[")","]"].some((e=>t.endsWith(e)))&&c.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(",")||ZT(t))),i=n.every((t=>t.includes("/")||ZT(t))),a=n.every((t=>t.includes("-")||ZT(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 u=g(t.split(""));1===u["("]&&1===u[")"]&&t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,t.length-1),1===u["-"]&&XT(t)&&s(e?.removed)&&(t+=`(${e.removed})`,e.removed=void 0));const d=/\(\)/g;return d.test(t)&&(t=t.replace(d,"").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($T).test(t)){const n=t.slice(3),r=t.slice(0,3),i=r.split("-");if(!XT(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&&s(t))return t.split("").join("-");t=nP(t);const a=(new RegExp(`^${WT}$`).test(t)?"super":new RegExp(`^${$T}$`).test(t)&&"tiebreak")||new RegExp(`^${qT}$`).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:c,setWinners:u,totalSets:d}=oP(t);if(1===d&&"6"===n?.removed&&(t+=" 6-0"),t.split(" ").length>2&&Math.max(...c)>=2&&u[0]===u[1]&&(t=t.split(" ").slice(0,2).join(" ")),Math.max(...c)>2){const e=[0,0];t=t.split(" ").map(((t,n)=>(e[u[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}=oP(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=>s(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:rP,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 cP={};const uP=["handleNumeric","handleWalkover","handleRetired","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],dP=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];function pP({analysis:t,set:e}){const n=mP({set:e}),{isDecidingSet:r,isTiebreakSet:i,matchUpScoringFormat:a}=t;return lP({matchUpScoringFormat:a,isDecidingSet:r,isTiebreakSet:i,set:e})&&n}function lP(t){let e=t.matchUpScoringFormat;const{ignoreTiebreak:n=!1,matchUpFormat:r,isTiebreakSet:i,isDecidingSet:a,set:o}=t;if(!o)return{error:ae};e=e||r;const s=a&&e.finalSetFormat||e?.setFormat||{},{side1Score:c,side2Score:u}=o,{NoAD:d,setTo:p,tiebreakAt:l,tiebreakFormat:m}=s,f=m?.NoAd,h=mP({set:o}),g=Math.abs(c-u),I=c>=p||u>=p,U=i||c>=p&&u>=p||l&&l<p&&(c===l||u===l),S=n||U&&(1===h&&o.side1TiebreakScore>o.side2TiebreakScore||2===h&&o.side2TiebreakScore>o.side1TiebreakScore);return(I&&(g>=(d||U&&(l&&!i||i&&f)?1:2)||U)||i)&&(!U||S)}function mP({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}}const fP=" ",hP="DEF",gP="WO",IP="ABN",UP="SUS",SP="RET",yP="INT",vP=[SP,hP,gP,"WO/WO",IP,UP,yP],wP="DEFAULTED",TP="WALKOVER",PP="ABANDONED",DP="SUSPENDED",bP="RETIRED",NP="INTERRUPTED",RP=[bP,wP,TP],MP="()",AP="[]",EP=["up","left","shift+tab"],CP=["enter","down","tab","right"],OP="backspace",FP="r",kP="s",xP="a",_P="d",LP="w",BP="i",VP=[FP,_P,LP,xP,kP,BP],jP="space",GP=["[","("],qP=[...EP,...CP,jP,"]"],$P="-",WP="-",HP=["/"],zP=["0","1","2","3","4","5","6","7","8","9"].concat(VP),YP=zP.map((t=>`shift+${t}`)),KP=[$P,OP].concat(qP,HP),JP=[zP,YP,KP].join(","),ZP=[JP,EP,CP,["=","+","num_1","num_2","shift+=","shift+-"]].join(",");[].concat(...zP,...zP,...KP,...zP,...zP,...zP,...zP,...zP,...zP);const XP={OUTCOMEKEYS:VP,SIDE1KEYS:zP,SIDE2KEYS:YP,MODIFIERS:KP,PROMPT:"Enter Score",MOVEUP:EP,MOVEDOWN:CP,HOTKEYS:ZP};function QP({scoreString:t,lowSide:e,outcome:n}){if(({scoreString:t}=tD({scoreString:t})),2===e){return t+((t&&t[t.length-1])!==fP?fP:"")+n}return n+fP+t}function tD({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(const n of vP){const r=t?.indexOf(n);0===r?t=t.slice(n.length+1).trim()+fP:r>0&&(t=t.slice(0,r)),r>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function eD({analysis:t,scoreString:e,sets:n,lowSide:r}){let i,a;if(!e)return{scoreString:e,sets:n};const{scoreString:o,removed:s}=tD({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}=nD({brackets:AP,scoreString:e}),f=function(t){const e=t.split("");return e.reduce(((t,e,n)=>(e.match(/\d+/g)&&t.push(n),t)),[]).pop()}(e);if(f>=0){i=e.slice(0,f);const{isTiebreakEntry:o}=nD({brackets:MP,scoreString:i}),{lastOpenBracketIndex:s,isTiebreakEntry:u}=nD({brackets:AP,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(WP),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(WP)}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 nD({brackets:t=MP,scoreString:e}){if(!e)return{};const[n,r]=t.split(""),i=e.split(""),a=Math.max(...T(n,i));return{isTiebreakEntry:a>Math.max(...T(r,i)),lastOpenBracketIndex:a}}function rD(t){const{lowValue:e=0,NoAD:n=!1,tiebreakTo:r}=t||{};return e+1>=r?e+(n?1:2):parseInt(r)}function iD({matchUpFormat:t,matchUpStatus:e,winningSide:n,sets:r}){const i=Jd(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 RP.includes(e)&&n&&(c=n),{matchUpWinningSide:c}}function aD({lowSide:t,value:e,sets:n,scoreString:r,winningSide:i,matchUpStatus:a}){let o;return e===FP?r?(o=!0,r=QP({scoreString:r,lowSide:t,outcome:SP}),i=2===t?1:2,a=bP):(o=!0,r=QP({scoreString:r,lowSide:t,outcome:hP}),i=2===t?1:2,a=wP):e===_P?(o=!0,r=QP({scoreString:r,lowSide:t,outcome:hP}),i=2===t?1:2,a=wP):e===LP?(o=!0,n=[],r=gP,i=2===t?1:2,a=TP):e===kP&&r?(o=!0,r=QP({scoreString:r,lowSide:t,outcome:UP}),a=DP,i=void 0):e===xP?(o=!0,r=QP({scoreString:r,lowSide:t,outcome:IP}),a=PP,i=void 0):e===BP&&r&&(o=!0,r=QP({scoreString:r,lowSide:t,outcome:yP}),a=NP,i=void 0),{updated:o,sets:n,scoreString:r,matchUpStatus:a,winningSide:i}}function oD({matchUpFormat:t,scoreString:e,winningSide:n,value:r,sets:i}){const a=(i?.filter((t=>t?.winningSide))?.length||0)+(n?0:1),o=Jd(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}=nD({brackets:MP,scoreString:e}),{isTiebreakEntry:m}=nD({brackets:AP,scoreString:e}),f=l||m,h=!!c.tiebreakSet,g=e?.[e.length-1]?.trim(),I=e&&!isNaN(g),U=!f&&g===$P,S=l&&GP.includes(g),y=m&&GP.includes(g),v=m&&g===WP,w=e?.split(""),[P]=AP.split(""),D=w&&Math.max(...T(P,w)),b=w&&Math.max(...T(WP,w)),N=w&&b>D,R=i[i.length-1]?.winningSide,M=i?.length&&!R,A=vP.find((t=>e?.indexOf(t)>=0)),E=!isNaN(r),C=r===jP,O=qP.includes(r),F=e?.split("").find((t=>GP.includes(t))),k=O&&m&&!y&&(v||!function({scoreString:t}){if(!t)return!1;const e=t&&t[t.length-1].trim(),n=t&&!isNaN(e),[r,i]=AP.split(""),a=t.split(""),o=Math.max(...T(r,a)),s=Math.max(...T(i,a)),c=Math.max(...T(WP,a));return n&&o>s&&c>o}({scoreString:e}));return{isTiebreakSetValue:h&&E,matchUpScoringFormat:o,setNumber:a,setFormat:c,matchTiebreakHasJoiner:N,isGameScoreEntry:M,isSpace:C,isCloser:O,isTiebreakCloser:O&&F&&f&&I,isDecidingSet:s,isTiebreakSet:h,isTimedSet:u,isNumericEnding:I,isNumericValue:E,hasOpener:F,hasOutcome:A,finalSet:d,finalSetIsComplete:p,lastSetIsComplete:R,isInvalidSetTiebreakValue:C&&f&&S,isInvalidMatchTiebreakValue:k,isTiebreakEntry:f,isSetTiebreakEntry:l,isMatchTiebreakEntry:m,isIncompleteSetScore:U,isIncompleteSetTiebreak:S,isIncompleteMatchTiebreak:y,isPartialMatchTiebreakValue:v}}function sD({matchUp:t}){const{extension:e}=Mr({name:Qi,element:t});if(!e)return{error:On};const{history:n=[],undoHistory:r=[]}=e.value;return{history:n,undoHistory:r,...E}}function cD({undoHistory:t,history:e,matchUp:n}){return Nr({element:n,extension:{value:{history:e,undoHistory:t},name:Qi}})}const uD={analyzeSet:Av,checkScoreHasValue:$s,checkSetIsComplete:lP,generateScoreString:nU,generateTieMatchUpScore:_g,getSetComplement:Ny,getTiebreakComplement:Ry,isValidMatchUpFormat:rh,keyValueScore:function(t){let{lowSide:e=1,value:r}=t,{scoreString:i,sets:a,winningSide:o,matchUpStatus:s}=t;const{matchUpFormat:c,shiftFirst:u,auto:d=!0}=t;let p,l;const m=u&&2===e||!u&&1===e;if(!JP.includes(r))return{updated:!1,info:"invalid key"};u&&(e=3-e);const{matchUpWinningSide:f}=iD({sets:a,winningSide:o,matchUpStatus:s,matchUpFormat:c});o=f;const h=oD({value:r,winningSide:o,scoreString:i,sets:a,matchUpFormat:c});if(HP.includes(r)&&(r=$P),h.hasOpener&&h.isTiebreakEntry&&!h.isTiebreakSet&&m&&0===n(r)&&(h.isTiebreakCloser=!0),qP.includes(r)&&h.hasOpener&&(r=""),qP.includes(r)&&(r=jP),h.lastSetIsComplete){const t=i?.length&&i[i.length-1];i&&" "!==t&&(i+=" ")}if(h.isTimedSet)({info:l,sets:a,scoreString:i,updated:p,matchUpStatus:s,winningSide:o}=function(t){let{sets:e,info:r,scoreString:i,winningSide:a,matchUpStatus:o}=t;const{analysis:s,lowSide:c,value:u}=t;let d,p;e?.length||u===OP||(e=[{setNumber:1}]);const l=e.length-1;if(VP.includes(u)){const t=e[e.length-1]||{},{side1Score:n,side2Score:p}=t;n&&!p?r="missing side2Score":s.finalSetIsComplete||a?r="final set is already complete":s.isIncompleteSetScore?r="incomplete set scoreString":s.isIncompleteSetScore||({sets:e,scoreString:i,winningSide:a,matchUpStatus:o,updated:d}=aD({lowSide:c,value:u,sets:e,scoreString:i,matchUpStatus:o,winningSide:a}))}else if(u===OP){if(({scoreString:i,sets:e,outcomeRemoved:p}=eD({analysis:s,scoreString:i,sets:e})),""===i?.trim()&&(i=i.trim()),i||(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}))}}o=void 0,a=void 0,d=!0}else if(s.hasOutcome)r="has outcome";else{if(a)return{sets:e,scoreString:i,winningSide:a,matchUpStatus:o,updated:!1,info:"matchUp is complete"};if(u===jP){const t=e[e.length-1]||{},{side1Score:n,side2Score:r}=t,o=(n>r?1:r>n&&2)||void 0;!o||a||s.isIncompleteSetScore||(e[e.length-1].winningSide=o,e.push({setNumber:e.length+1}),i+=" ",d=!0)}else if(u===$P&&void 0!==e[l].side1Score&&void 0===e[l].side2Score&&i&&s.isNumericEnding)i+="-",e[l].side2Score=0,o=void 0,a=void 0,d=!0;else if(!isNaN(u)){let t;if(void 0===e[l].side2Score){const r=n((e[l].side1Score||0).toString()+u).toString().slice(0,2);e[l].side1Score=n(r),t=e[l].side1Score.toString(),d=!0}else{const r=n((e[l].side2Score||0).toString()+u).toString().slice(0,2);e[l].side2Score=n(r),t=[e[l].side1Score,e[l].side2Score].join("-"),d=!0}if(d){const n=(e.slice(0,l)||[]).filter((t=>t)).map((t=>{const{side1Score:e,side2Score:n}=t;return[e,n].join("-")})).join(" ");i=n?n+" "+t:t}}}return{sets:e,scoreString:i,winningSide:a,matchUpStatus:o,info:r,updated:d}}({analysis:h,lowSide:e,scoreString:i,sets:a,matchUpStatus:s,winningSide:o,value:r}));else if(VP.includes(r))h.finalSetIsComplete||o?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:r}):({sets:a,scoreString:i,matchUpStatus:s,winningSide:o,updated:p}=aD({lowSide:e,sets:a,scoreString:i,matchUpStatus:s,winningSide:o,value:r}));else if(r===OP)p=!0,({scoreString:i,sets:a}=eD({analysis:h,scoreString:i,sets:a,lowSide:e})),i||(a=[]),s=void 0,o=void 0;else if(h.hasOutcome)l="has outcome";else if(r!==$P||h.isMatchTiebreakEntry)if(r===WP&&h.isMatchTiebreakEntry&&!h.isSetTiebreakEntry)h.matchTiebreakHasJoiner?l="existing joiner":h.isNumericEnding&&(p=!0,i+=WP);else if([$P,WP].includes(r))l="invalid location for joiner";else{if(o)return{updated:!1,info:"matchUp is complete"};if(h.isIncompleteSetScore)h.isNumericValue&&({sets:a,scoreString:i,updated:p}=function({analysis:t,scoreString:e,sets:r,value:i}){let a;if(!r?.length)return{sets:[]};const o=r[r.length-1];i=n(i);const{validSide2Score:s,requiresTiebreak:c}=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:o,value:i});if(s){a=!0,e=(e||"")+i,o.side2Score=i;const n=pP({analysis:t,set:r[r.length-1]});o.winningSide=n||void 0,c?e+=MP.split("")[0]:t.isDecidingSet||(e+=fP)}return{sets:r,scoreString:e,updated:a}}({analysis:h,scoreString:i,sets:a,value:r}));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?MP:AP,e=t.split("").reverse()[0],n=t.split("")[0],r=a[a.length-1],{tiebreakFormat:o}=h.setFormat,{tiebreakTo:s,NoAD:c}=o||{},u=mP({set:r});if(!h.isTiebreakSet){const t=parseInt(i.split(n).reverse()[0]),e=rD({lowValue:t,tiebreakTo:s,NoAD:c});1===u?(r.side1TiebreakScore=e,r.side2TiebreakScore=t):(r.side1TiebreakScore=t,r.side2TiebreakScore=e)}i=(i||"")+e,h.isDecidingSet||(i+=fP);const d=pP({analysis:h,set:r});r.winningSide=d||void 0,p=!0}else if(h.isTiebreakSetValue)({info:l,scoreString:i,sets:a,updated:p}=function({analysis:t,auto:e,lowSide:r,scoreString:i="",sets:a,value:o}){let s,c;const{tiebreakSet:{tiebreakTo:u,NoAD:d}}=t.setFormat,[p]=AP.split("");if(t.isMatchTiebreakEntry||(i+=p),a[t.setNumber-1]){const{lastOpenBracketIndex:t}=nD({brackets:AP,scoreString:i}),p=(i.slice((t??0)+1)+(e?"":o)).split(WP);if((p[r-1]?.length||0)>=2)c="tiebreak digit limit";else if(e){1===r&&(p[0]=(p[0]||"")+o),2===r&&(p[1]=(p[1]||"")+o);const e=[p[0]||0,p[1]||0].map((t=>n(t))),c=1===r?1:0;e[c]=e[1-c]+(d?1:2),e[c]<u&&(e[c]=u);const l=a[a.length-1];l.side1TiebreakScore=e[0],l.side2TiebreakScore=e[1],i=i.slice(0,(t??0)+1),i+=e.join(WP),s=!0}else{const t=[p[0]||0,p[1]||0].map((t=>n(t))),e=a[a.length-1];e.side1TiebreakScore=t[0],e.side2TiebreakScore=t[1],i+=o,s=!0}}else{const t=rD({lowValue:n(o||0),tiebreakTo:u,NoAD:d}),e=[n(o),t];2===r&&e.reverse();const c={side1TiebreakScore:e[0],side2TiebreakScore:e[1],setNumber:a?.length+1||1};a.push(c),i+=e.join(WP),s=!0}return{info:c,scoreString:i,sets:a,updated:s}}({analysis:h,auto:d,lowSide:e,scoreString:i,sets:a,value:r}));else if(h.isSetTiebreakEntry){const[t]=MP.split(""),e=Math.max(...T(t,i.split(""))),a=i.slice(e+1),o=a&&0===n(a),s=n(a?a+r:r),{tiebreakFormat:c}=h.setFormat,{tiebreakTo:u,NoAD:d}=c||{};!o&&a.length<2?d&&s>u-1?l="invalid low value for NoAD tiebreak":(p=!0,i=(i||"")+r):l=o?"tiebreak begins with zero":"tiebreak digit limit"}else if(h.isCloser)l=`invalid key: ${r}`;else if(h.isGameScoreEntry)l="game scoreString entry";else if(h.lastSetIsComplete||!a.length){p=!0;const{scoreString:t,set:o}=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=MP.split("")[0];n=(n||"")+(u.join($P)+(s?d:fP));const p={side1Score:u[0],side2Score:u[1]},l=pP({analysis:t,set:p});return p.winningSide=l||void 0,{scoreString:n,set:p}}({analysis:h,lowSide:e,scoreString:i,value:n(r)});o&&(o.setNumber=a?.length+1||1),a=a?.concat(o).filter(Boolean)||[o],i=t||void 0}else console.log("error: unknown outcome")}else(!h.isSetTiebreakEntry||h.isSetTiebreakEntry&&!h.isNumericEnding)&&(p=!0,({scoreString:i,sets:a}=eD({analysis:h,scoreString:i,sets:a,lowSide:e})),s=void 0);if(p){a=a?.filter(Boolean);const{matchUpWinningSide:t}=iD({sets:a,winningSide:o,matchUpStatus:s,matchUpFormat:c});return o=t,!t||s&&![ja,_a].includes(s)?!i||o||[DP,PP,NP].includes(s)||(s=void 0):(s="COMPLETED",a=a.filter((t=>{const{side1Score:e,side2Score:n,side1TiebreakScore:r,side2TiebreakScore:i}=t;return e||n||r||i}))),{updated:p,scoreString:i,sets:a,winningSide:o,matchUpStatus:s,info:l}}return{updated:p,scoreString:i,sets:a,winningSide:o,matchUpStatus:s,info:l}},parseMatchUpFormat:Jd,reverseScore:function(t){if(!t?.score)return{error:ae};const{sets:e}=t.score,n=e.map((t=>{const{side1TiebreakScore:e,side2TiebreakScore:n,winningSide:r,side1Score:i,side2Score:a,setNumber:o}=t;return vr({winningSide:r?3-r:void 0,side1TiebreakScore:n,side2TiebreakScore:e,side1Score:a,side2Score:i,setNumber:o})}));return{reversedScore:{sets:n,scoreStringSide1:nU({sets:n}),scoreStringSide2:nU({sets:n,reversed:!0})},...E}},stringifyMatchUpFormat:Xf,tidyScore:function(t){if(!t.score)return{error:Nn};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=sP[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(uP);let h=JT(m);return h||(m=e.toString().replace(/\D/g,""),d?.removed&&(d.removed=void 0),f(dP),h=JT(m),h||(m="")),l.forEach((t=>{cP[t]||(cP[t]=0),cP[t]+=1})),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:d,isValid:h,score:m}},updateTieMatchUpScore:$g,validateScore:TI,validateTieFormat:fh,calculateHistoryScore:function(t){if(!t)return{error:ae};const{matchUp:e,updateScore:n}=t;if(!e)return{error:zt};const r=sD({matchUp:e})?.history||[];if(!Array.isArray(r))return{error:Nn,info:"history is not an array"};const{matchUpFormat:i}=e;if(!i)return{error:Vt};if(!rh(i))return{error:Bt};const a=Jd(i),{bestOf:o,finalSetFormat:s,setFormat:c}=a,u=["0","15","30","40","A","G"],d={sets:[]};let l,m,f=[],h=[0,0],g=1,I=0,U=0;const S=t=>[1,2].includes(t),y=()=>(I+=1,{winningSide:void 0,side1Score:0,side2Score:0,setNumber:I,games:[]});let v={winningSide:void 0,side1Score:"",side2Score:"",shots:[]},w={winningSide:void 0,points:[]},T=y(),P=0;for(const t of r){P+=1,m=d.sets.length+1===o;const e=m&&s?s:c,{tiebreakAt:n,setTo:r,NoAD:i,tiebbreakFormat:a}=e,I=T.side1Score===n&&T.side1Score===T.side2Score,D=!!e.tiebreakSet,b=D?e.tiebreakSet:a,{tiebreakTo:N,NoAD:R}=b||{},M=()=>{l=void 0,h=[0,0],g=3-g,T.side1TiebreakScore=0,T.side2TiebreakScore=0,T.side1PointScore="",T.side2PointScore="",U=0},A=t=>{T.winningSide=t;const{s:e,...n}=T;d.sets.push(n),v={winningSide:void 0,side1Score:"",side2Score:"",shots:[]},w={winningSide:void 0,points:[]},T=y(),M()},E=t=>{w.winningSide=t;const{g:e,...n}=w;T.games.push(n),v={winningSide:void 0,side1Score:"",side2Score:"",shots:[]},w={winningSide:void 0,points:[]},M();T[`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:[]},U=0;const r=t-1;if(I||D){h[r]+=1,l=h.reduce(((t,e)=>t+e))%4/4>.5?g:3-g,T[`side${t}TiebreakScore`]=h[r],T[`side${3-t}TiebreakScore`]=h[1-r];const e=R?1:2;if(h[r]>=N&&h[r]>=h[1-r]+e)return E(t),{gameCompleted:!0}}else if(4===h[1-r]&&3===h[r]?h[1-r]-=1:h[r]+=1,T.side1PointScore=u[h[0]],T.side2PointScore=u[h[1]],5===h[r]||4===h[r]&&h[1-r]<3||i&&4===h[r])return E(t),{gameCompleted:!0}};if(S(t.srv)&&(g=t.srv),["p","s","g","o"].includes(t.u)&&f.push(t.u),t.shotOutcome){v.shots.push(t);if("SERVE"===t.shotType&&["OUT","NET"].includes(t.shotOutcome)&&(U+=1),2===U){C(3-g)}}if(S(t.p)||p(t.pointNumber)){const e=C(t.winningSide||t.p);if(e?.gameCompleted)continue}if(S(t.g)||p(t.gameNumber)){const e=t.winningSide||t.g;w.winningSide=e;const n=`side${e}Score`,a=`side${3-e}Score`;f.length&&(f.includes("p"),f=[]),E(e);if(T[n]===r&&T[n]-T[a]>=(i?1:2)&&(A(e),m))break}if(S(t.s)||p(t.setNumber)){if(A(t.winningSide||t.s),f.length&&(f.includes("p"),f.includes("g"),f=[]),m)break}}return P!==r.length&&console.log({error:"Match completed with excess history"}),(T.side1Score||T.side2Score||T.games.length||T.side1TiebreakScore||T.side2TiebreakScore)&&d.sets.push(T),d.scoreStringSide1=nU({...d,matchUpFormat:i}),d.scoreStringSide2=nU({...d,matchUpFormat:i,reversed:!0}),g=l||g,n&&(e.score=d),{...E,servingSide:g,score:d}},setServingSide:function({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:ne};const{history:n=[]}=sD({matchUp:t});return n.push({srv:e}),cD({matchUp:t,history:n})},clearHistory:function({matchUp:t}){return cD({matchUp:t})},addPoint:function({matchUp:t,point:e}){if(!e)return{error:ae};if("object"!=typeof e)return{error:Nn,context:{point:e}};const{history:n=[]}=sD({matchUp:t});return n.push(e),cD({matchUp:t,history:n})},addGame:function({matchUp:t,game:e}){if("object"!=typeof e)return{error:Nn,context:{game:e}};const{history:n=[]}=sD({matchUp:t});return n.push(e),cD({matchUp:t,history:n})},addShot:function({matchUp:t,shot:e}){if("object"!=typeof e)return{error:ae};const{history:n=[]}=sD({matchUp:t});return n.push(e),cD({matchUp:t,history:n})},addSet:function({matchUp:t,set:e}){if("object"!=typeof e)return{error:ae};const{history:n=[]}=sD({matchUp:t});return n.push(e),cD({matchUp:t,history:n})},redo:function({matchUp:t}){const{history:e=[],undoHistory:n=[]}=sD({matchUp:t});return n.length&&e.push(n.pop()),cD({matchUp:t,history:e,undoHistory:n})},undo:function({matchUp:t}){const{history:e=[],undoHistory:n=[]}=sD({matchUp:t});return n.push(e.pop()),cD({matchUp:t,history:e,undoHistory:n})},umo:{scoreboard:()=>{},addPoints:()=>{},addPoint:()=>{}}},dD={ABANDONED:"ABANDONED",ACTIVE:"ACTIVE",CANCELLED:"CANCELLED",COMPLETED:"COMPLETED",IN_PROGRESS:"IN_PROGRESS"};function pD({tournamentRecord:t,startDate:e,endDate:n}){if(!t)return{error:_};if(e&&!Vr.test(e)||n&&!Vr.test(n))return{error:pe};if(!e&&!n)return{error:oe};if(n&&e&&new Date(n)<new Date(e))return{error:Nn};let r;(e&&t.startDate&&new Date(e)>new Date(t.startDate)||n&&t.endDate&&new Date(n)<new Date(t.endDate))&&(r=!0),e&&(t.startDate=e),n&&(t.endDate=n),e&&t.endDate&&new Date(e)>new Date(t.endDate)&&(t.endDate=e),n&&t.startDate&&new Date(n)<new Date(t.startDate)&&(t.startDate=n);const i=r&&function({tournamentRecord:t}){const e=hl({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(!iv({scheduledDates:i,tournamentRecord:t}).clearedScheduleCount)return{error:Y}}return{unscheduledMatchUpIds:a}}({tournamentRecord:t})?.unscheduledMatchUpIds;return function({tournamentRecord:t}){if(!t)return{error:_};const{startDate:e,endDate:n}=t,r=Jr(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=ti(t.startTime),r=ti(t.endTime);return e.startTime&&ti(e.startTime)<n&&(t.startTime=e.startTime),e.endTime&&ti(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:t}),sr({topic:ws,payload:{startDate:e,endDate:n}}),{...E,unscheduledMatchUpIds:i}}const lD={addDrawDefinitionExtension:xi,addEventExtension:_i,addEventTimeItem:Bm,addExtension:Nr,addNotes:Gg,addOnlineResource:function({tournamentRecord:t,onlineResource:e,organisationId:n,participantId:r,personId:i,courtId:a,venueId:o}){if(!t)return{error:_};if(!ha(e))return{error:ae};if(3!==P(Object.keys(e),["resourceSubType","resourceType","identifier"]).length)return wr({result:{error:Pn},context:{onlineResource:e}});if(n){if(t.parentOrganisation?.parentOrganisationId!==n)return wr({result:{error:On}});t.parentOrganisation.onlineResources||(t.parentOrganisation.onlineResources=[]),t.parentOrganisation.onlineResources.push(e)}else if(r||i){const n=(t.participants??[]).find((t=>i&&t.person?.personId===i||t.participantId===r));if(!n)return wr(i?{result:{error:On}}:{result:{error:Ee}});if(i){if(n.person?.personId!==i)return wr({result:{error:we}});n.person.onlineResources||(n.person.onlineResources=[]),n.person.onlineResources.push(e)}else n.onlineResources||(n.onlineResources=[]),n.onlineResources.push(e)}else if(a){const n=(t.venues??[]).filter((t=>!o||t.venueId===o)).flatMap((t=>(t.courts??[]).filter((t=>t.courtId===a))))?.[0];if(!n)return wr({result:{error:tn}});n.onlineResources||(n.onlineResources=[]),n.onlineResources.push(e)}else if(o){const n=(t.venues??[]).find((t=>t.venueId===o));if(!n)return wr({result:{error:rn}});n.onlineResources||(n.onlineResources=[]),n.onlineResources.push(e)}else t.onlineResources||(t.onlineResources=[]),t.onlineResources.push(e);return{...E}},addParticipantExtension:function(t){if(!t||"object"!=typeof t)return{error:ae};if(!t.participantId)return{error:Ae};const e=t.tournamentRecord?.participants||[],n=Fi({participantId:t.participantId,tournamentParticipants:e});return n?Nr({creationTime:t.creationTime,extension:t.extension,element:n}):{error:Ee}},addParticipantTimeItem:_m,addTimeItem:xm,addTournamentExtension:ki,addTournamentTimeItem:Lm,getProfileRounds:bT,removeDrawDefinitionExtension:function(t){return t&&"object"==typeof t?t.drawDefinition?Dr({element:t.drawDefinition,name:t.name}):{error:q}:{error:ae}},removeEventExtension:Bi,removeExtension:Dr,removeNotes:function(t){return"object"!=typeof t?{error:ae}:"object"!=typeof t.element?{error:Nn}:(t.element.notes&&delete t.element.notes,{...E})},removeParticipantExtension:function(t){if(!t||"object"!=typeof t)return{error:ae};if(!t.participantId)return{error:Ae};const e=t.tournamentRecord?.participants||[],n=Fi({participantId:t.participantId,tournamentParticipants:e});return n?Dr({element:n,name:t.name}):{error:Ee}},removeTournamentExtension:Li,setTournamentCategories:function({tournamentRecord:t,categories:e}){return t?(e=(e||[]).filter((t=>t.categoryName&&t.type)),t.tournamentCategories=e,{...E}):{error:_}},setTournamentDates:pD,setTournamentEndDate:function({tournamentRecord:t,endDate:e}){return pD({tournamentRecord:t,endDate:e})},setTournamentName:function({tournamentRecord:t,promotionalName:e,tournamentName:n,formalName:r}){return t?(n&&(t.tournamentName=n),e&&(t.promotionalName=e),r&&(t.formalName=r),t.promotionalName===t.tournamentName&&delete t.promotionalName,t.formalName===t.tournamentName&&delete t.formalName,{...E}):{error:_}},setTournamentNotes:function({tournamentRecord:t,notes:e}){return t?Gg({element:t,notes:e}):{error:_}},setTournamentStartDate:function({tournamentRecord:t,startDate:e}){return pD({tournamentRecord:t,startDate:e})},setTournamentStatus:function({tournamentRecord:t,status:e}){return t?e&&!Object.keys(dD).includes(e)?{error:Nn,info:"Unknown status"}:(t.tournamentStatus=e,{...E}):{error:_}}};const mD=["collectionId","collectionPosition","drawPositions","extensions","finishingPositionRange","finishingRound","isMock","matchUpId","matchUpStatus","matchUpStatusCodes","orderOfFinish","processCodes","roundNumber","tieFormat","tieMatchUps","roundPosition","score","sides","winnerMatchUpId","loserMatchUpId","matchUpDuration","winningSide"];function fD(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,fD(t[i],e,n.concat(i)))),{})}const hD={allNumeric:R,allPlayoffPositionsFilled:function(t){const{drawDefinition:e,structureId:n}=t;if(!e)return{error:j};const{playoffStructures:r}=Nh({drawDefinition:e,structureId:n});if(!r?.length)return!1;const i=e?.entries?.filter((t=>t?.entryStatus&&ou.includes(t.entryStatus)))?.length??0;let a=0;return(r||[]).reduce(((t,e)=>{const n=rs({structure:e}).positionAssignments??[],r=n?.filter((t=>(t.participantId&&a++,t?.bye??t?.participantId))).length;return!(!r||!t)}),!!r.length)||a===i},attributeFilter:_r,calculateWinCriteria:Jf,chunkArray:N,chunkByNth:A,chunkSizeProfile:function t(e,[n,...r]){return e.length?[e.slice(0,n),...t(e.slice(n),[...r,n])]:[]},compareTieFormats:Uh,constantToString:wm,countValues:function(t){return I(g(t))},createMap:Ia,dateRange:Jr,dateTime:hi,definedAttributes:vr,dehydrateMatchUps:function({tournamentRecord:t}){if(!t)return{error:_};if("object"!=typeof t||!t.tournamentId)return{error:Nn};const{matchUps:e}=hl({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))mD.includes(t)||delete n[t];n.sides&&n.drawPositions&&!n.tieMatchUps&&delete n.sides,o&&(n.matchUpFormat=o)}}(e,n)}return{...E}},extractAttributes:Ua,flattenJSON:fD,generateHashCode:function(t){if(null===t||"object"!=typeof t)return;const e=JSON.stringify(t),n=Sa(t),r=e.split("").reduce(((t,e)=>t+e.charCodeAt(0)),0);return[e.length,n,r].map((t=>t.toString(36))).join("")},generateRange:w,generateTimeCode:OT,getCategoryAgeDetails:uh,getMatchUpContextIds:function({matchUps:t,matchUpId:e}){if(!yc(t))return{error:Nn};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}},getScaleValues:xr,getSeedingThresholds:function({roundRobinGroupsCount:t,participantsCount:e}){if(t){const{validGroupSizes:n}=lf({drawSize:e}),r=n?.map((t=>Math.ceil(e/t)));if(!r?.includes(t))return wr({context:{roundRobinGroupsCount:t},result:{error:Nn}})}const{seedGroups:n}=ff({drawSize:e,roundRobinGroupsCount:t}),r=n?.map((t=>Math.min(...t)))||[];return{...E,seedingThresholds:r}},getTimeItem:il,getValidGroupSizes:lf,groupValues:I,hasAttributeValues:t=>e=>Object.keys(t).every((n=>e[n]===t[n])),instanceCount:g,intersection:P,isAdHoc:ap,isCompletedStructure:Mh,isConvertableInteger:p,isNumeric:s,isOdd:c,isPowerOf2:r,JSON2CSV:function(t,e){if(e&&"object"!=typeof e)return Nn;let{columnTransform:n={}}=e||{};const{includeTransformAccessors:r,includeHeaderRow:i=!0,returnTransformedJSON:a,removeEmptyColumns:o,onlyHeaderRow:c,columnAccessors:u=[],functionMap:d={},columnMap:p={},valuesMap:l={},context:m={},delimiter:f='"',columnJoiner:h=",",rowJoiner:g="\r\n",keyJoiner:I="."}=e||{};if(!Array.isArray(t)||!Array.isArray(u)||"object"!=typeof m||"object"!=typeof p||"object"!=typeof n||"object"!=typeof d||"object"!=typeof l||"string"!=typeof h||"string"!=typeof g||"string"!=typeof I||"string"!=typeof f)return Nn;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=>fD(t,I))),S=Object.values(n).flat();r&&u.push(...S);const y=U.reduce(((t,e)=>Object.keys(e).every((e=>!t.includes(e)&&t.push(e)||!0))&&t),[]).filter((t=>!u?.length||u.includes(t))),v=Object.assign({},...Object.keys(n).reverse().map((t=>n[t].map((e=>({[e]:t}))).flat())).flat()),w=y.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(p).forEach((t=>!w.includes(t)&&w.unshift(t))),Object.keys(n).forEach((t=>!w.includes(t)&&w.unshift(t))),"object"==typeof m&&Object.keys(m).forEach((t=>!w.includes(t)&&w.unshift(t)));let T=w.map((t=>p[t]||t));if(c)return[T];const P=t=>`${f}${t}${f}`,D=[];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])||m?.[r]||"",s=l[r]?.[o]||o,c="function"==typeof d[r]?d[r](s):s;return e[r]=P(c),c&&(D[i]=(D[i]||0)+1),e}),{}))));const N=o&&[...D].map(((t,e)=>!t&&e)).filter(s).reverse();if(N){const t=t=>t.filter(((t,e)=>!N.includes(e)));b=b.map(t),T=t(T)}const R=b.map((t=>t.join(h)));return a?R.map((t=>{const e=t.split(h);return Object.assign({},...e.map(((t,e)=>({[T[e]]:t}))))})):i?[T.map(P).join(h),...R].join(g):R.join(g)},makeDeepCopy:gi,matchUpSort:Il,nearestPowerOf2:o,nextPowerOf2:u,noNulls:function(t){return t?.map((t=>null===t?void 0:t))},noNumeric:M,numericSort:e,occurrences:function(t,e){return e.reduce(((t,e)=>(t[e]=1+t[e]||1,t)),{})[t]||0},overlap:b,randomMember:v,randomPop:y,roundRobinGroups:df,shuffleArray:f,structureSort:Xo,subSort:function(t,e,n,r){return[].concat(...t.slice(0,e),...t.slice(e,e+n).sort(r),...t.slice(e+n,t.length))},tieFormatGenderValidityCheck:oh,undefinedToNull:function t(e,n){if(void 0===e)return null;if("object"!=typeof 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:m,UUID:Md,UUIDS:function(t=1){return w(0,t).map(Md)},validateCategory:dh,visualizeScheduledMatchUps:function({scheduledMatchUps:t,showGlobalLog:e}){Tl.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=>{Pl({color:"blue",method:"draw",structure:r[e],keyColors:{structure:"magenta"}},!0);const n=t.filter((t=>t.structureId===e)),i=vc({matchUps:n})?.roundMatchUps||[];Object.keys(i).forEach((t=>{Pl({roundNumber:t,keyColors:{roundNumber:"brightcyan"}},!0),i[t].forEach((({matchUpId:t,schedule:e})=>{Pl({matchUpId:t,time:ni(e.scheduledTime),date:e.scheduledDate,venue:e.venueId,keyColors:{time:"brightcyan",date:"brightcyan",matchUpId:"yellow",venue:"magenta"}},!0)}))}))})),e&&Dl()}},gD=hD;function ID(t){if(!t?.tournamentRecord&&!Array.isArray(t?.venueMatchUps))return{error:_};if(!t?.courtId)return{error:ie};const{scheduleVisibilityFilters:e,tournamentRecord:n,matchUpFilters:r,venueMatchUps:i,courtId:a}=t,{schedulingProfile:o}=Om({tournamentRecord:n});if(Array.isArray(i))return{matchUps:c({matchUps:i,courtId:a})};const{matchUps:s}=hl({scheduleVisibilityFilters:e,tournamentRecord:n,matchUpFilters:r});return{matchUps:c({matchUps:s,courtId:a})};function c({matchUps:t,courtId:e}){return hw({matchUps:t.filter((t=>{const n=t.schedule?.allocatedCourts?.map((({courtId:t})=>t));return t.schedule?.courtId===e||n?.includes(e)})),schedulingProfile:o})}}function UD({tournamentRecord:t,dateAvailability:e,disableNotice:n,venueMatchUps:r,courtId:i,force:a}){if(!t)return{error:_};if(!i)return{error:ie};const o=Uv({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(Iv);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(di(ui(n),ui(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=Od({tournamentRecord:t,courtId:i});if(u.error)return u;const{court:d,venue:p}=u,{matchUps:l}=ID({tournamentRecord:t,venueMatchUps:r,courtId:i});if(l?.length){const e=Dc({tournamentRecord:t})?.appliedPolicies,n=a??e?.[Ni]?.allowDeletionWithScoresPresent?.courts,r=[];r.length&&(n||console.log("throw error: scheduled court matchUps",r.length))}return d&&(d.dateAvailability=e,!n&&p&&sr({payload:{venue:p,tournamentId:t.tournamentId},topic:Ts,key:p.venueId})),{...E,totalMergeCount:c}}function SD({matchUpsCount:t=0}){return{error:Gn,info:`Schedule would be deleted from ${t} ${1===t?"matchUp":"matchUps"}; use { force: true }`}}function yD({tournamentRecord:t,drawDefinition:e,matchUpId:n,drawId:r}){if(!n)return{error:qt};if(!e&&!r)return{error:at};let i;if(!e){if(!t)return{error:_};({drawDefinition:e}=Vd({tournamentRecord:t,drawId:r}))}if(e)({matchUp:i}=Xm({drawDefinition:e,matchUpId:n}));else{if(!t)return{error:_};const e=hl({tournamentRecord:t,inContext:!1}).matchUps??[];({matchUp:i}=Zm({matchUps:e,matchUpId:n}))}if(!i)return{error:Wt};if(i.timeItems){i.timeItems.find((t=>[Du,Pu].includes(t.itemType)))&&(i.timeItems=i.timeItems.filter((({itemType:t})=>![Du,Pu].includes(t))),xs({tournamentId:t?.tournamentId,context:"removeCourtAssignment",drawDefinition:e,matchUp:i}))}return{...E}}function vD(t){if("string"!=typeof t?.venueId)return{error:an};const{tournamentRecord:e,venueId:n,force:r}=t,i=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!Object.keys(i).length)return{error:_};const a=gl({tournamentRecords:i,contextFilters:{venueIds:[n]}}).matchUps??[],o=Dc({tournamentRecord:e})?.appliedPolicies,s=r??o?.[Ni]?.allowDeletionWithScoresPresent?.venues;if(a.length&&!s)return SD({matchUpsCount:a.length});for(const t of Object.values(i)){for(const e of a){const n=yD({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&&sr({payload:{venueId:n,tournamentId:t.tournamentId},topic:ls,key:n})}return km({tournamentRecords:i}),{...E}}function wD({tournamentRecord:t,courtIds:e,dates:n}){const r=!Array.isArray(n)||!n.length||{dates:n},i=t=>Nr({extension:{value:r,name:$i},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{...E}}function TD({tournamentRecord:t,venueIds:e}){for(const n of t.venues||[])if(e?.includes(n.venueId)){const t=Nr({creationTime:!1,element:n,extension:{name:$i,value:!0}});if(t.error)return t}return{...E}}function PD({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}=Mr({element:t,name:$i});if(e){const n=e.value;Array.isArray(n.dates)&&(n.dates=n.dates.filter((t=>!r.includes(t)))),Nr({extension:{name:$i,value:n},creationTime:!1,element:t})}}else Dr({element:t,name:$i});return{...E}}function DD({tournamentRecord:t,disableNotice:e,courtId:n,force:r}){const i=Od({tournamentRecord:t,courtId:n});if(i.error)return i;const a=i.venue,{matchUps:o}=ID({tournamentRecord:t,courtId:n}),s=Dc({tournamentRecord:t})?.appliedPolicies,c=r??s?.[Ni]?.allowDeletionWithScoresPresent?.courts;if(o?.length&&!c)return SD({matchUpsCount:o.length});for(const e of o??[]){const n=yD({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||sr({payload:{venue:a,tournamentId:t.tournamentId},topic:Ts,key:a.venueId})),{...E}}function bD(t){const{disableNotice:e,modifications:n,courtId:r,force:i,venueMatchUps:a}=t,o=nc(t);if(!Object.keys(o).length)return{error:x};let s;for(const t of Object.values(o)){const o=ND({tournamentRecord:t,disableNotice:e,venueMatchUps:a,modifications:n,courtId:r,force:i});if(o?.error)return o;s=!0}return s?{...E}:undefined}function ND({tournamentRecord:t,disableNotice:e,venueMatchUps:n,modifications:r,courtId:i,force:a}){if(!t)return{error:_};if(!i)return{error:ie};if(!r||"object"!=typeof r)return{error:Pn};const o=Od({tournamentRecord:t,courtId:i});if(o.error)return o;const{venue:s,court:c}=o,u=Object.keys(fv()).filter((t=>"courtId"!==t));if(!Object.keys(r).filter((t=>u.includes(t))).length)return{error:En};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=UD({dateAvailability:r.dateAvailability,tournamentRecord:t,venueMatchUps:n,disableNotice:e,courtId:i,force:a});if(o.error)return o}return e||sr({payload:{venue:s,tournamentId:t.tournamentId},topic:Ts,key:s?.venueId}),{...E,court:gi(c)}}const RD=()=>({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,addresses:[],contacts:[],courts:[],roles:[]});function MD({tournamentRecord:t,modifications:e,venueId:n,force:r}){if(!t)return{error:_};if(!e||"object"!=typeof e)return{error:Pn};if(!n)return{error:an};const i=Dc({tournamentRecord:t})?.appliedPolicies,a=r??i?.[Ni]?.allowDeletionWithScoresPresent?.venues,{matchUps:o}=function({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:n,venueId:r}){if(!e)return{error:_};if(!r)return{error:an};const{schedulingProfile:i}=Om({tournamentRecord:e}),{matchUps:a}=hl({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:n});return{matchUps:function({matchUps:t,venueId:e}){return hw({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})}}({tournamentRecord:t,venueId:n}),s=Cd({tournamentRecord:t,venueId:n});if(s.error)return s;const c=s.venue,u=Object.keys(RD()).filter((t=>"venueId"!==t));if(!Object.keys(e).filter((t=>u.includes(t))).length)return{error:En};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=l.filter((t=>!m.includes(t))),h=[];if(f.length){const e=c?.courts?.filter((t=>f.includes(t.courtId))),n=e?.map((e=>{const n=ID({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 SD({matchUpsCount:n});c.courts=c.courts?.filter((t=>m.includes(t.courtId))),Qy({schedule:{courtId:"",scheduledDate:""},matchUpDetails:h,removePriorValues:!0,tournamentRecord:t})}if(e.courts)for(const i of e.courts){const{courtId:e}=i||{};let a=bD({modifications:i,disableNotice:!0,tournamentRecord:t,venueMatchUps:o,courtId:e,force:r});if(a.error===tn&&(a=Sv({disableNotice:!0,tournamentRecord:t,venueId:n,court:i})),a.error)return a}return km({tournamentRecord:t}),c&&sr({payload:{venue:c,tournamentId:t.tournamentId},topic:Ts,key:c?.venueId}),{...E,venue:gi(c)}}const AD={addCourt:Sv,addCourts:yv,addVenue:Ad,deleteCourt:function(t){const{courtId:e,disableNotice:n,force:r}=t,i=nc(t),a=Lp(t,[{[sp]:!0,[Tp]:!0}]);if(a.error)return a;let o,s;for(const t of Object.values(i)){if(s=DD({tournamentRecord:t,disableNotice:n,courtId:e,force:r}),s.error&&s.error!==tn)return s;s.success&&(o=!0)}return o?{...E}:s},deleteVenue:vD,deleteVenues:function({tournamentRecord:t,venueIds:e,force:n}){if(!t)return{error:_};if(!Array.isArray(e))return{error:Nn};for(const r of t.venues||[]){const{venueId:i}=r;if(e.includes(i)){const{venueId:e}=r,i=vD({tournamentRecord:t,venueId:e,force:n});if(i.error)return i}}return{...E}},disableCourts:function(t){const{courtIds:e,dates:n}=t,r=nc(t),i=Lp(t,[{[sp]:!0,[yp]:!0}]);if(i.error)return i;for(const t of Object.values(r))wD({tournamentRecord:t,courtIds:e,dates:n});return{...E}},disableVenues:function(t){const{tournamentRecords:e,tournamentId:n,venueIds:r}=t,i=Lp(t,[{[sp]:!0,[vp]:!0}]);if(i.error)return i;const a=Object.keys(e).filter((t=>!n||t===n));for(const t of a){TD({tournamentRecord:e[t],venueIds:r})}return{...E}},enableCourts:function(t){const e=nc(t),n=[{[sp]:!0}];!t.enableAll&&n.push({[yp]:!0});const r=Lp(t,n);if(r.error)return r;const{enableAll:i,courtIds:a,dates:o}=t;for(const t of Object.values(e))PD({tournamentRecord:t,courtIds:a,enableAll:i,dates:o});return{...E}},enableVenues:function(t){const e=nc(t),n=[{[sp]:!0}];!t.enableAll&&n.push({[vp]:!0});const r=Lp(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))&&Dr({element:e,name:$i});return{...E}},findVenue:function({convertExtensions:t,...e}){const{tournamentRecords:n,tournamentRecord:r,venueId:i}=e;return gi(Cd({tournamentRecords:n,tournamentRecord:r,venueId:i}),t,!0)},modifyCourt:bD,modifyCourtAvailability:UD,modifyVenue:function(t){const{modifications:e,venueId:n,force:r}=t,i=nc(t);if(!Object.keys(i).length)return{error:x};if("string"!=typeof n)return{error:an};let a,o;for(const t of Object.values(i)){const i=MD({tournamentRecord:t,modifications:e,venueId:n,force:r});if(i.success&&(o=!0),i.error&&(a=i.error),i.error&&i.error!==rn)return i}return km({tournamentRecords:i}),o?{...E}:{error:a}}},ED={competitionGovernor:va,eventGovernor:VS,generationGovernor:hy,matchUpFormatGovernor:lh,mocksGovernor:Yv,participantGovernor:nw,policyGovernor:iw,publishingGovernor:sw,queryGovernor:MT,reportGovernor:CT,scheduleGovernor:GT,scoreGovernor:uD,tournamentGovernor:lD,utilitiesGovernor:hD,venueGovernor:AD},CD={};function OD(t){const{mutationStatus:e,tournamentId:n,directives:r,timeStamp:i}=t||{},{topics:a}=lr();for(const t of[...a].sort(xD)){const e=ur({topic:t});e&&mr({topic:t,notices:e})}e&&i&&a.includes(Ps)&&mr({notices:[{tournamentId:n,directives:r,timeStamp:i}],topic:Ps})}async function FD(t){const{mutationStatus:e,tournamentId:n,directives:r,timeStamp:i}=t||{},{topics:a}=lr();for(const t of[...a].sort(xD)){const e=ur({topic:t});e&&await mr({topic:t,notices:e})}e&&i&&a.includes(Ps)&&mr({notices:[{tournamentId:n,directives:r,timeStamp:i}],topic:Ps})}const kD={[Ms]:5,[Rs]:5,[As]:5,[vs]:5,[ys]:5,[hs]:5,[gs]:5,[Is]:5,[Us]:1,[Es]:1,[Ss]:5,[Ts]:5,[fs]:4,[ps]:4,[ls]:4,[ms]:4,[os]:3,[as]:2};function xD(t,e){return(kD[e]||0)-(kD[t]||0)}const{FACTORY:_D}=da;function LD({timeStamp:t}){const e=gr(),n=or();return n&&Object.values(e).forEach((e=>{!function({tournamentRecord:t,value:e}){const{extension:n}=Mr({element:t,name:_D});Nr({element:t,extension:{name:_D,value:{...n?.value,...e}}})}({tournamentRecord:e,value:{version:"3.0.0-alpha.0",timeStamp:t}})})),n}function BD({engineType:t,methodName:e,elapsed:n,params:r,result:i}){const a=Qn();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&&function(t,e){if(Kn.globalLog)try{Kn.globalLog({engine:t,log:e})}catch(n){console.log("globalLog error",n),console.log(t,e),tr()}else console.log(t,e)}(t,o)}function VD({methodName:t,params:e,start:n}){const r={error:jn,methodName:t};return BD({result:r,methodName:t,elapsed:n?Date.now()-n:0,params:e,engineType:"sync"}),r}function jD(t,e,n,r,i){delete t.success,delete t.error;const a=Date.now(),o=fr();if(n&&(n.activeTournamentId=o),n?.sandboxTournament&&!n?.sandboxTournament.tournamentId)return{error:Nn};const s=n?.sandboxTournament||hr(o),c=n?.sandboxTournament?{[n?.sandboxTournament.tournamentId]:n.sandboxTournament}:gr(),u=n?function(t,e){if(!1===e._middleware)return e;if(e.tournamentId&&!t[e.tournamentId])return{error:_};const n=e.drawId||e.matchUp?.drawId;if(n){const{event:r,drawDefinition:i,tournamentId:a}=Vd({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}=Vd({eventId:e.eventId,tournamentRecords:t});if(!n)return{error:Pt};e.tournamentId=r,e.event=n}const r=e.tournamentId??fr();if(!r&&e)return e;const i=t[r];return r&&!i?{error:_}:i?(e.tournamentRecord=i,e):e}(c,n):void 0;if(u?.error)return u;const d=function({tournamentRecords:t,tournamentRecord:e,params:n,methodName:r,method:i}){if(Qn())return i({tournamentRecords:t,tournamentRecord:e,...n});try{return i({tournamentRecords:t,tournamentRecord:e,...n})}catch(t){return yr({engineName:"engine",methodName:r,params:n,err:t})}}({params:u,tournamentRecords:c,tournamentRecord:s,methodName:r,method:e});return BD({result:d,methodName:r,elapsed:Date.now()-a,params:n,engineType:i}),d}function GD(t,e=!0){return"object"!=typeof t||Array.isArray(t)?{error:Pn}:t?.tournamentId?(n=e?gi(t):t,Jn.setTournamentRecord(n)):{error:Nn};var n}function qD(t,e=!0){if("object"!=typeof t)return{error:Pn};if(Ur(),Array.isArray(t)){if(!(t.filter((t=>t?.tournamentId)).length===t.length))return{error:k};t=Object.assign({},...t.map((t=>({[t.tournamentId]:t}))))}else if(t?.tournamentId)Ur((t={[t.tournamentId]:t}).tournamentId);else{if(!Object.keys(t).every((e=>t[e].tournamentId===e)))return{error:k}}return Ir(e?gi(t):t)}async function $D(t,e){if(!ha(e))return{error:Nn};const n=Object.values(e).filter(ma).length;if(n>1)return{error:Nn};const r=n?Object.keys(e).find((t=>ma(e[t]))):fa(e.method)&&e.method;if(!r)return{error:Nn};const{[r]:i,...a}=e,o=e?.params||{...a},s=o.rollbackOnError&&gi(gr(),!1,!0),c=i||t[r]||Yn()[r];if(!c)return VD({methodName:r,params:o});const u=await jD(t,c,o,r,"async")??{};u?.error&&s&&qD(s);const d=Date.now(),p=LD({timeStamp:d}),l=u?.success&&!0!==o?.delayNotify&&!0!==o?.doNotNotify;return l&&await FD({directives:[{method:c,params:o}],mutationStatus:p,timeStamp:d}),(l||!u?.success||o?.doNotNotify)&&pr(),u}function WD(t,e,n){if(!ha(n))return{error:Nn};var r;!(r=n)||("object"!=typeof r||Jn.setMethods(r));return Object.keys(n).filter((t=>ma(n[t]))).forEach((r=>{t[r]=i=>{const a=()=>e(t,{[r]:n[r],...i});if(Qn())return a();try{return a()}catch(t){yr({engineName:"engine",methodName:r,params:i,err:t})}}})),{...E,...t}}function HD(t,e){return e?.error?(t.error=e.error,t.success=!1):(t.error=void 0,t.success=!0),t}function zD(t,e){t.importMethods=n=>WD(t,e,n),t.getTournament=t=>function(t){const{convertExtensions:e=!1,removeExtensions:n=!1}=t??{},r=t?.tournamentId??fr();return"string"!=typeof r?{}:{tournamentRecord:gi(hr(r),e,!1,n)}}(t),t.getState=t=>function({convertExtensions:t,removeExtensions:e}){const n=gr();return{tournamentId:fr(),tournamentRecords:gi(n,t,!1,e)}}({convertExtensions:t?.convertExtensions,removeExtensions:t?.removeExtensions}),t.version=()=>"3.0.0-alpha.0",t.reset=()=>(Ir({}),HD(t)),t.devContext=e=>(er(e),HD(t)),t.getDevContext=t=>Qn(t),t.newTournamentRecord=(t={})=>{const e=sv(t),n=e.tournamentId;return e.error?e:(GD(e),Ur(n),{...E,tournamentId:n})},t.setState=(e,n,r)=>{rr(n,r);const i=qD(e,n);return HD(t,i)},t.setTournamentId=t=>Ur(t),t.setTournamentRecord=(e,n,r)=>{rr(n,r);const i=GD(e,n);return HD(t,i)},t.removeTournamentRecord=e=>{const n=function(t){return Jn.removeTournamentRecord(t)}(e);return HD(t,n)},t.removeUnlinkedTournamentRecords=()=>{const e=function(){const t=gr(),{extension:e}=Mr({name:Xi,tournamentRecords:t,discover:!0}),n=e?.value?.tournamentIds||[];return Object.keys(t).forEach((e=>{n.includes(e)||delete t[e]})),Ir(t)}();return HD(t,e)}}function YD(t){const e=function(){if(Jn.createInstanceState){try{Jn.createInstanceState()}catch(t){return{error:t}}return{success:!0}}return{error:ln}}();if(e.error&&!t)return e;const n={executionQueue:(t,e)=>async function(t,e,n){if(!Array.isArray(e))return{error:Nn};const r=cr(),i=Date.now(),a=n&&gi(gr(),!1,!0),o=[];for(const n of e){if("object"!=typeof n)return{error:Nn};const{method:e,params:s}=n;if(!r[e])return VD({methodName:e,start:i,params:s});const c=jD(t,r[e],s,e,"async");if(c?.error)return a&&qD(a),{...c,rolledBack:!!a};o.push({...c,methodName:e})}const s=Date.now();return FD({directives:e,mutationStatus:LD({timeStamp:s}),timeStamp:s}),pr(),{success:o.every((t=>t.success)),results:o}}(n,t,e),execute:t=>$D(n,t)};return zD(n,$D),n}function KD(t,e){if(!ha(e))return{error:Nn};const n=Object.values(e).filter(ma).length;if(n>1)return{error:Nn};const r=n?Object.keys(e).find((t=>ma(e[t]))):fa(e.method)&&e.method;if(!r)return{error:Nn};const{[r]:i,...a}=e,o=e?.params||{...a},s=i||t[r]||Yn()[r];return s?jD(t,s,o,r,"ask"):VD({methodName:r,params:o})}const JD=(()=>{const t={execute:e=>KD(t,e)};return zD(t,KD),t})();function ZD(t,e){if(!ha(e))return{error:Nn};const n=Object.values(e).filter(ma).length;if(n>1)return{error:Nn};const r=n?Object.keys(e).find((t=>ma(e[t]))):fa(e.method)&&e.method;if(!r)return{error:Nn};const{[r]:i,...a}=e,o=e?.params||{...a},s=o.rollbackOnError&&gi(gr(),!1,!0),c=i||t[r]||Yn()[r];if(!c)return VD({methodName:r,params:o});const u=jD(t,c,o,r,"sync")??{};u?.error&&s&&qD(s);const d=Date.now(),p=LD({timeStamp:d}),l=u?.success&&!0!==o?.delayNotify&&!0!==o?.doNotNotify;return l&&OD({directives:[{method:c,params:o}],mutationStatus:p,timeStamp:d}),(l||!u?.success||o?.doNotNotify)&&pr(),u}const XD=(()=>{const t={executionQueue:(e,n)=>function(t,e,n){if(!Array.isArray(e))return{error:Nn};const r=cr(),i=Date.now(),a=n&&gi(gr(),!1,!0),o=[];for(const n of e){if("object"!=typeof n)return{error:Nn};const{method:e,params:s}=n;if(!r[e])return VD({methodName:e,start:i,params:s});const c=jD(t,r[e],s,e,"sync");if(c?.error)return a&&qD(a),{...c,rolledBack:!!a};o.push({...c,methodName:e})}const s=Date.now();return OD({directives:e,mutationStatus:LD({timeStamp:s}),timeStamp:s}),pr(),{success:o.every((t=>t.success)),results:o}}(t,e,n),execute:e=>ZD(t,e)};return zD(t,ZD),t})(),QD={...va,...nw,...sw,...hy,...lD,...GT,...iw,...CT,...VS,...MT,...uD,...AD};XD.importMethods(QD);const tb=XD,eb=XD;let nb,rb={};function ib(t,e=!0){if(!t)return{error:ae};if("object"!=typeof t)return{error:Pn};if(t.matchUpId)nb=t.matchUpId,rb[nb]=e?gi(t):t;else if(Array.isArray(t))for(const n of t.reverse())n.matchUpId&&(rb[n.matchUpId]=e?gi(n):n,nb||(nb=n.matchUpId));else for(const n of Object.values(t))n.matchUpId&&(rb[n.matchUpId]=e?gi(n):n,nb||(nb=n.matchUpId));return e?gi(t):t}const ab=(()=>{const t={getState:t=>function(t){return gi(rb[nb],t?.convertExtensions,!1,t?.removeExtensions)}(t),version:()=>"3.0.0-alpha.0",reset:()=>(nb=void 0,rb={},{...E}),drawId:void 0,error:void 0,success:!1,devContext:e=>(er(e),t),setState:(e,n,r)=>{rr(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}(ib(e))}};return function(n){n.forEach((n=>{Object.keys(n).forEach((r=>{t[r]=t=>{if(Qn())return e({params:t,governor:n,methodName:r});try{return e({params:t,governor:n,methodName:r})}catch(e){yr({engineName:"matchUpEngine",methodName:r,params:t,err:e})}}}))}))}([uD]),t;function e({params:e,governor:n,methodName:r}){t.error=void 0,t.success=!1;const i=e?.matchUp||rb[nb],a=e?.matchUps||Object.values(rb),o=e?.rollbackOnError&&gi(i,!1,!0);e={...e,matchUpId:i?.matchUpId,matchUps:a,matchUp:i};const s=n[r](e);if(s?.error)return o&&ib(o),{...s,rolledBack:!!o};const c=s?.success&&!0!==e?.delayNotify&&!0!==e?.doNotNotify;return c&&OD(),(c||!s?.success||e?.doNotNotify)&&pr(),s}})();let ob=!1;const sb=(()=>{const t={version:()=>"3.0.0-alpha.0",setDeepCopy:(e,n)=>(rr(e,n),t),devContext:e=>(er(e),ob=!0,t)};return function(e){e.forEach((e=>{Object.keys(e).forEach((n=>{t[n]=t=>{try{return function(t,e){const n=t({...e});n?.error||OD();pr(),ob&&(er(!1),ob=!1);return n}(e[n],t)}catch(e){let r;"string"==typeof e?r=e.toUpperCase():e instanceof Error&&(r=e.message),console.log("ERROR",{params:JSON.stringify(t),method:n,error:r})}}}))}))}([Yv]),t})();function cb(t,e){return t&&e&&Array.isArray(e)&&e[t-1]||"object"==typeof e&&e[t]}function ub(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,m=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))));return{awardProfile:m}}function db({participantWon:t,flightNumber:e,valueObj:n,drawSize:r,flights:i,level:a}){const o=(t,e)=>{const n=t?.value||t?.v||(p(t)?t:0),r=cb(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||p(r)&&r||n}};let s,c,u,d,l=0;const m=(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!==m&&(t=t?.[m],i=i?.[m],a=a?.[m]),c=o(t,e).value,u=o(i,e).value,d=o(a,e).value,l=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!==m&&(t=t?.[m],i=i?.[m]),c=o(t,e).value,d=o(i,e).value,l=c||d,s=c?t.requireWin:i?.requireWin}else p(n)&&void 0===m&&(l=n);return e&&i?.pct?.[e]&&(l=Math.round(l*i.pct[e])),{awardPoints:l,requireWin:s}}const pb={getTournamentPoints:function({participantFilters:t,policyDefinitions:e,tournamentRecord:n,saveRankings:r,level:i}){if(!n)return{error:_};const{policyDefinitions:a}=bc({policyTypes:[Ti],tournamentRecord:n}),o=e?.[Ti]??a?.[Ti];if(!o)return{error:Jt};const s=o.awardProfiles;let c=o.requireWinFirstRound;const u=o.requireWinForPoints,{participants:d,derivedEventInfo:p,derivedDrawInfo:l,mappedMatchUps:f}=Zl({withRankingProfile:!0,participantFilters:t,tournamentRecord:n}),h=d?.filter((t=>t.draws?.length)),g={},I={},U={};for(const t of h??[]){const{participantType:e,participantId:r,person:a,draws:o}=t;for(const d of o){const{drawId:o,structureParticipation:h,eventId:S}=d,y=p[S],v=l[o],w=v?.drawType,{category:T,eventType:P}=y||{},D=d.startDate||y.startDate||n.startDate,b=d.endDate||y.endDate||n.endDate;if(P===ad&&r!==oc)continue;let N;if(s){let n,d=u,p=0,l=0,S=0;for(const a of h){const{finishingPositionRange:o,participationOrder:u,participantWon:h,flightNumber:g,rankingStage:I,winCount:U}=a;p+=U||0;const y=v?.drawSize,{awardProfile:R}=ub({awardProfiles:s,participation:a,eventType:P,startDate:D,category:T,drawSize:y,drawType:w,endDate:b,level:i});if(R){if(!y)continue;const t=Array.isArray(o)&&Math.max(...o),e=m(o||[]).join("-"),r=t&&I!==Qa&&o?.includes(y);void 0!==R.requireWinForPoints&&(d=R.requireWinForPoints),void 0!==R.requireWinFirstRound&&(c=R.requireWinFirstRound);const{finishingPositionPoints:a={},finishingPositionRanges:s,finishingRound:p,pointsPerWin:f,flights:v}=R,w=Array.isArray(R.perWinPoints)?R.perWinPoints?.find((t=>t.participationOrders?.includes(u))):R.perWinPoints,T=a.participationOrders;let P,D=0;if((!T||T.includes(u))&&s&&t){const e=s[t];e&&({awardPoints:D,requireWin:P}=db({flightNumber:g,valueObj:e,drawSize:y,flights:v,level:i}))}if(!D&&p&&1===u&&t){const e=p[t];e&&({awardPoints:D,requireWin:P}=db({participantWon:h,flightNumber:g,valueObj:e,drawSize:y,flights:v,level:i}))}if(r&&void 0!==c&&(d=c),void 0!==P&&(d=P),D>l&&(!d||U)&&(l=D,n=t),!D&&f&&U&&(S+=U*f,n=e),!D&&U&&w){const t=cb(i,w?.level);t?S+=U*t:w.value&&(S+=U*w.value)}}if(N=l+S,e===oc){const e=(t.matchUps||[]).filter((({structureId:t})=>t===a.structureId));for(const{matchUpId:t}of e){const e=f[t],n=e.sides.find((t=>t.participantId===r)).sideNumber;if(e.winningSice===n)for(const t of e.tieMatchUps)t.winningSide}}}if(S||l){const t={winCount:p,positionPoints:l,rangeAccessor:n,perWinPoints:S,eventType:P,drawId:o,points:N},i=a?.personId;i?(g[i]||(g[i]=[]),g[i].push(t)):e===uc?(U[r]||(U[r]=[]),U[r].push(t)):e===oc&&(I[r]||(I[r]=[]),I[r].push(t))}}}}if(r){Nr({element:n,extension:{name:na,value:{personPoints:g,teamPoints:I,pairPoints:U}}})}return{participantsWithOutcomes:h,personPoints:g,pairPoints:U,teamPoints:I,...E}}};const lb={nSpread:400,diffThreshold:.125,kCalc:t=>250/Math.pow(t+5,.4),kMultiplier:function(t=3,e=2){const n=t/e;return isNaN(n)?lb.kDefault():n},kDefault:()=>1};function mb(t){let{winnerRating:e,loserRating:n,ratingRange:r}=t;const{ratings:i=MU,winnerCountables:a=1,loserCountables:o=0,ratingType:s=DU,maxCountables:c,countables:u}=t||{},d=i?.[s];if(!d)return{error:ae};r=d.range||r,e=e||d.defaultInitialization,n=n||d.defaultInitialization;const p=r[0]>r[1],l=d.decimalsCount||0,m=p?r.slice().reverse():r,f=(t,e)=>parseFloat(e)>=Math.min(...t)&&parseFloat(e)<=Math.max(...t);f(r,e)&&f(r,n)||(f(r,e)||(e=d.defaultInitialization),f(r,n)||(n=d.defaultInitialization));const h=({value:t,sourceRange:e,targetRange:n})=>(t-e[0])*(n[1]-n[0])/(e[1]-e[0])+n[0],g=h({targetRange:MU[DU].range,sourceRange:m,value:p?r[0]-e:e}),I=h({targetRange:MU[DU].range,sourceRange:m,value:p?r[0]-n:n}),U=(t,e)=>1/(1+Math.pow(10,(e-t)/lb.nSpread)),S=U(g,I),y=U(I,g),v=lb.kCalc(a),w=lb.kCalc(o),T=lb.kMultiplier(c,u),P=g+T*v*(1-S),D=I+T*w*(0-y),b=h({sourceRange:MU[DU].range,value:P,targetRange:m}),N=h({sourceRange:MU[DU].range,value:D,targetRange:m}),R=p?r[0]-b:b;let M=parseFloat(parseFloat(R).toFixed(l));const A=p?r[0]-N:N;let E=parseFloat(parseFloat(A).toFixed(l));const C=Math.max(...r)?Math.abs(e-n)/Math.max(...r):0;return(b>N&&C>lb.diffThreshold||M<0||E<0)&&(M=e,E=n),{newWinnerRating:M,newLoserRating:E}}const fb={calculateNewRatings:mb,generateDynamicRatings:function({removePriorValues:t=!0,tournamentRecord:e,ratingType:n=DU,considerGames:r,matchUpIds:i,asDynamic:a}){if(!e)return{error:_};if(!Array.isArray(i))return{error:Ht};if("string"!=typeof n)return{error:Nn,ratingType:n};if(!MU[n])return{error:Nn};const o=MU[n],{accessor:s}=o,c={},u=hl({matchUpFilters:{matchUpIds:i,matchUpStatuses:Ya},tournamentRecord:e,inContext:!0}).matchUps??[];u.sort(Il);for(const i of u){const{endDate:o,matchUpFormat:u,score:p,sides:l,winningSide:m}=i,f=i.matchUpType,h={eventType:f,scaleName:n,scaleType:Cr},g=`${n}.${Ar}`,I={scaleName:g,eventType:f,scaleType:Cr},U=Object.assign({},...(l??[]).map((t=>{const{sideNumber:e,participant:n}=t;return e&&{[e]:[n?.participantId,...n?.individualParticipantIds??[]].filter(Boolean).flat()}}))),S=a?g:n,y=Object.assign({},...Object.values(U).flat().map((t=>{const{scaleItem:n}=GU({scaleAttributes:I,tournamentRecord:e,participantId:t}),{scaleItem:r}=GU({tournamentRecord:e,scaleAttributes:h,participantId:t});return t&&{[t]:n??r??{scaleName:S,eventType:f,scaleDate:o,scaleType:Cr,scaleValue:s?{[s]:void 0}:void 0}}}))),v=u?Jd(u):{},w=v?.bestOf||1,T=r?w&(v?.setsTo||1):w,P=p?.sets&&(d=p.sets,d?.reduce(((t,e)=>(e.winningSide&&(t[e.winningSide-1]+=1),t)),[0,0])||[0,0])||1===m&&[1,0]||[0,1],D=m?U[m]:[],b=m?U[3-m]:[];for(const r of D){const i=y[r]?.scaleValue,a="object"==typeof i?i[s]:i;for(const o of b){const c=y[o]?.scaleValue,u="object"==typeof c?c[s]:c,d=m?P[m]:[0,0],p=m?P[3-m]:[0,0],{newWinnerRating:l,newLoserRating:f}=mb({winnerCountables:d,loserCountables:p,maxCountables:T,winnerRating:a,loserRating:u,ratingType:n}),h=s?{...i,[s]:l}:l,g=s?{...c,[s]:f}:f;y[r].scaleValue=h,y[o].scaleValue=g;let I=Dv({participantId:r,removePriorValues:t,tournamentRecord:e,scaleItem:{...y[r],scaleName:S}});if(I.error)return I;if(I=Dv({participantId:o,removePriorValues:t,tournamentRecord:e,scaleItem:{...y[o],scaleName:S}}),I.error)return I}}Object.assign(c,y)}var d;const p=u.map((({matchUpId:t})=>t));return{...E,modifiedScaleValues:c,processedMatchUpIds:p}}},hb={...pb,...fb};XD.importMethods(hb);const gb=XD,Ib={ratingsParameters:MU,matchUpFormats:fg,countryToFlag:tl,tieFormats:CS,countries:el,policies:{POLICY_AVOIDANCE_COUNTRY:{[Ri]:{roundsToSeparate:void 0,policyName:"Nationality Code",policyAttributes:[{key:"person.nationalityCode"},{key:"individualParticipants.person.nationalityCode"}]}},POLICY_POSITION_ACTIONS_DEFAULT:Yw,POLICY_POSITION_ACTIONS_DISABLED:{[vi]:{policyName:"positionActionsDisabled",enabledStructures:!1}},POLICY_POSITION_ACTIONS_NO_MOVEMENT:{[vi]:{policyName:"positionActionsNoMovement",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[jw,Vw,Gw],disabledActions:[]}]}},POLICY_POSITION_ACTIONS_UNRESTRICTED:{[vi]:{policyName:"positionActionsUnrestricted",enabledStructures:[],otherFlightEntries:!0,disableRoundRestrictions:!0,activePositionOverrides:[jw,Lw]}},POLICY_PRIVACY_DEFAULT:{[Di]:{policyName:"Participant Privacy Policy",participant:{contacts:!1,individualParticipants:{onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,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,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:op,POLICY_SCHEDULING_DEFAULT:lw,POLICY_SCORING_DEFAULT:{[Mi]:{defaultMatchUpFormat:lg,allowDeletionWithScoresPresent:{drawDefinitions:!1,structures:!1},requireAllPositionsAssigned:!1,processCodes:{incompleteAssignmentsOnDefault:["RANKING.IGNORE"]},stage:{[Xa]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}}}},POLICY_SCORING_USTA:{[Mi]:{requireAllPositionsAssigned:!1,stage:{[Xa]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},defaultMatchUpFormat:lg,matchUpFormats:[{description:"Best of 3 tiebreak sets",matchUpFormat:lg,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"}]}},POLICY_SEEDING_ITF:{[Ai]:{seedingProfile:{positioning:uo},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:XS},flagIOC:function(t){return tl(Object.assign({},...el.filter((t=>t.ioc)).map((t=>({[t.ioc]:t.iso}))))[t])}},Ub={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"},Sb={CLAY:"CLAY",HARD:"HARD",GRASS:"GRASS",CARPET:"CARPET",ARTIFICIAL:"ARTIFICIAL"},yb={INDOOR:"INDOOR",OUTDOOR:"OUTDOOR"},vb={activeMatchUpStatuses:Ka,auditConstants:Km,completedMatchUpStatuses:Ya,directingMatchUpStatuses:Ha,drawDefinitionConstants:Zo,entryStatusConstants:cu,errorConditionConstants:$n,eventConstants:od,extensionConstants:da,flightConstants:ny,genderConstants:zp,keyValueConstants:XP,matchUpActionConstants:UT,matchUpStatusConstants:Za,matchUpTypes:tc,nonDirectingMatchUpStatuses:za,participantConstants:lc,participantRoles:lm,particicipantsRequiredMatchUpStatuses:$a,participantTypes:pc,penaltyConstants:Ub,policyConstants:Oi,positionActionConstants:$w,ratingConstants:RU,recoveryTimeRequiredMatchUpStatuses:qa,requestConstants:By,resultConstants:C,scaleConstants:kr,scheduleConstants:Ud,sortingConstants:ay,surfaceConstants:Sb,tieFormatConstants:RS,timeItemConstants:Yu,topicConstants:Cs,tournamentConstants:dD,upcomingMatchUpStatuses:Ja,validMatchUpStatuses:Wa,venueConstants:yb};export{JD as askEngine,YD as asyncEngine,tb as competitionEngine,pr as deleteNotices,Zo as drawDefinitionConstants,cu as entryStatusConstants,$n as errorConditionConstants,od as eventConstants,vb as factoryConstants,Ib as fixtures,ny as flightConstants,CD as forge,zp as genderConstants,ur as getNotices,ED as governors,XP as keyValueConstants,UT as matchUpActionConstants,ab as matchUpEngine,lh as matchUpFormatCode,Za as matchUpStatusConstants,tc as matchUpTypes,sb as mocksEngine,lc as participantConstants,lm as participantRoles,pc as participantTypes,Ub as penaltyConstants,Oi as policyConstants,$w as positionActionConstants,C as resultConstants,kr as scaleConstants,gb as scaleEngine,uD as scoreGovernor,rr as setDeepCopy,er as setDevContext,tr as setGlobalLog,Xn as setStateProvider,ar as setSubscriptions,Sb as surfaceConstants,XD as syncEngine,Yu as timeItemConstants,eb as tournamentEngine,gD as utilities,yb as venueConstants,t as version};
2
2
  //# sourceMappingURL=index.mjs.map