tods-competition-factory 2.0.0-beta.6 → 2.0.0-beta.7
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 +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/tods-competition-factory.d.ts +7969 -8318
- package/dist/tods-competition-factory.development.cjs.js +54936 -55521
- package/dist/tods-competition-factory.development.cjs.js.map +1 -1
- package/dist/tods-competition-factory.production.cjs.min.js +1 -1
- package/dist/tods-competition-factory.production.cjs.min.js.map +1 -1
- package/package.json +14 -12
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function t(){return"2.0.0-beta.6"}function e(t,e){return(t??0)-(e??0)}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(){if(Jn.createInstanceState){try{Jn.createInstanceState()}catch(t){return{error:t}}return{success:!0}}return{error:ln}}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.disableNotifications()}function rr(){Jn.enableNotifications()}function ir(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 ar(){return{enabled:Kn.deepCopy,...Kn.deepCopyAttributes}}function or(t){return t?"object"!=typeof t?{error:Nn}:Jn.setMethods(t):{error:ae,info:"missing method declarations"}}function sr(){return Jn.cycleMutationStatus()}function cr(t){return Jn.addNotice(t)}function ur(){return Jn.getMethods()}function dr(t){return Jn.getNotices(t)}function pr({key:t,topic:e}){return Jn.deleteNotice({key:t,topic:e})}function lr(){return Jn.deleteNotices()}function mr(){return Jn.getTopics()}async function fr(t){return Jn.callListener(t)}function hr(){return Jn.getTournamentId()}function gr(t){return Jn.getTournamentRecord(t)}function Ir(){return Jn.getTournamentRecords()}function Ur(t){return Jn.setTournamentRecord(t)}function Sr(t){return Jn.setTournamentRecords(t)}function yr(t){return Jn.setTournamentId(t)}function vr(t){return Jn.removeTournamentRecord(t)}function wr(){return Jn}function Tr({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 Pr(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)}var Dr=Object.freeze({__proto__:null,addNotice:cr,callListener:fr,createInstanceState:Xn,cycleMutationStatus:sr,deepCopyEnabled:ar,deleteNotice:pr,deleteNotices:lr,disableNotifications:nr,enableNotifications:rr,getDevContext:Qn,getMethods:ur,getNotices:dr,getProvider:wr,getTopics:mr,getTournamentId:hr,getTournamentRecord:gr,getTournamentRecords:Ir,globalLog:Pr,handleCaughtError:Tr,removeTournamentRecord:vr,setDeepCopy:ir,setDevContext:er,setGlobalLog:tr,setMethods:or,setStateProvider:function(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}},setSubscriptions:function(t){return t?.subscriptions?Jn.setSubscriptions({subscriptions:t.subscriptions}):{error:ae,info:"missing subscriptions"}},setTournamentId:yr,setTournamentRecord:Ur,setTournamentRecords:Sr,timeKeeper:function(t="reset",e="default"){const n=Date.now();if("report"===t){if("allTimers"===e){return Object.keys(Kn.timers).filter((t=>"default"!==t||Kn.timers[t].startTime)).map((t=>{const e=Kn.timers[t],r="stopped"===e.state?0:(n-(e?.startTime??0))/1e3,i=e.elapsedTime+r;return{state:Kn.timers[t].state,elapsedTime:i.toFixed(2),timer:t}}))}{const t="stopped"===Kn.timers[e].state?0:(n-(Kn.timers[e]?.startTime??0))/1e3,r=Kn.timers[e].elapsedTime+t;return{state:Kn.timers[e].state,elapsedTime:r.toFixed(2),timer:e}}}if(!Kn.timers[e]||"reset"===t){if("allTimers"===e)return Kn.timers={default:{elapsedTime:0}},!0;Kn.timers[e]={startTime:n,state:"active",elapsedTime:0}}return Kn.timers[e].elapsedTime||(Kn.timers[e].elapsedTime=0),"stop"===t&&"stopped"!==Kn.timers[e].state&&(Kn.timers[e].state="stopped")&&(Kn.timers[e].elapsedTime+=(n-(Kn.timers[e]?.startTime??0))/1e3),"start"===t&&(Kn.timers[e].startTime=n)&&(Kn.timers[e].state="active"),Kn.timers[e]}});function br(t,e,n,r){if("object"!=typeof t||null===t)return t;const i=ar();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=>br(t)))}:{[e]:r?t[e]:br(t[e])})))}function Nr({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,br(t)),!e||e?.error||e?.success||Object.assign(e,{...E}),e??{success:!0}}const Rr="element required",Mr="missing name";function Ar(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:Mr};if(!t?.element){if(t.discover&&t.tournamentRecords){for(const e of Object.keys(t.tournamentRecords)){const n=Ar({element:t.tournamentRecords[e],name:t.name});if(n.error)return Nr({result:n,stack:"removeExtension"})}return{...E}}return{error:ae,info:Rr}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter((e=>e?.name!==t.name)),{...E}):{...E,info:On}}function Er({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 Cr(t){if("object"!=typeof t)return{error:ae};const e="addExtension";if(t?.element&&"object"!=typeof t.element)return Nr({result:{error:Nn},stack:e});if(!Er({extension:t.extension}))return Nr({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=Cr({extension:t.extension,element:n});if(r.error)return Nr({result:r,stack:e})}return{...E}}return Nr({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 Or="extensionQueries";function Fr({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 Nr({result:{error:ae},stack:Or})}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 kr=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,xr=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,_r=/^([\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?$/,Lr=/^([\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 Br(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=ti(t.scheduledTime)),!e)return;const n=Qr(t.scheduledTime);let r=ti(e);return r&&n&&(r+=`T${n}`),r}function Vr(t){if("object"!=typeof t||Array.isArray(t))return!1;return"[object Date]"===Object.prototype.toString.call(t)}function jr(t){const e="string"==typeof t?t?.split(" "):[];return!(t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase()))&&!(t&&!Lr.test(ri(t,!0,!0)))}function Gr(t){return Kr(t)||kr.test(t)}const qr=t=>{const e=Hr(t)||Kr(t)?new Date(t):new Date,n=e.getUTCMonth()+1,r=n<10?`0${n}`:`${n}`;return`${e.getUTCFullYear()}-${di(r)}-${di(e.getUTCDate())}`};function $r(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 Wr(t){const e=t?new Date(t):new Date,n=e.getTimezoneOffset();return new Date(e.getTime()-60*n*1e3)}function Hr(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 zr(t,e){if(!Gr(t)||!Gr(e))return[];const n=ti(t)+"T00:00",r=ti(e)+"T00:00",i=new Date(n),a=new Date(r);const o=[];let s=0;if(Hr(a)&&Hr(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=>$r(t)))}const Yr=/^([+-]?\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 Kr(t){return"string"==typeof t&&Yr.test(t)}function Jr(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 Zr(t){const e=Qr(t);if(!e)return 0;const[n,r]=e.split(":").map((t=>parseInt(t)));return 60*n+r}function Xr(t){return Jr(t)?t.split(":").slice(0,2).map(di).join(":"):void 0}function Qr(t){return Kr(t)&&t.indexOf("T")>0?Xr(t.split("T").reverse()[0]):Xr(t)}function ti(t){return Kr(t)||_r.test(t)?t.split("T")[0]:void 0}function ei(t,e){const n=new Date(t);return n.setDate(n.getDate()+e),ti(n.toISOString())}function ni(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 ri(t,e,n){const r=ti(t),i=Qr(t),a=r?i:t;return t?e&&(r&&n&&t||function(t){const e=ni(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(di).join(":")}(a))||function(t){const e=ni(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 ii(t,e){const n=ni(t),r=ni(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 ai(t,e=7){const n=ti(t)+"T00:00",r=new Date(n);return $r(new Date(r.setDate(r.getDate()+e)))}function oi(t,e=void 0){const[n,r]=(t||"00:00").split(":").map(di),i=Wr(e).setHours(n,r,0,0);return Wr(i)}function si(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 ci(t,e){const n=Qr(t);if(!n)return"00:00";const r=isNaN(e)?0:e;return Qr(ui(oi(n),r).toISOString())}function ui(t,e){const n=new Date(t);return new Date(n.getTime()+6e4*e)}function di(t){return t.toString()[1]?t:"0"+t}function pi(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 li={addDays:ai,addWeek:function(t){return ai(t)},addMinutesToTimeString:ci,convertTime:ri,getIsoDateString:Br,getUTCdateString:qr,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(di).join(":")}(e.getSeconds()+60*e.getMinutes()+3600*e.getHours(),{displaySeconds:!1})},extractDate:ti,extractTime:Qr,formatDate:$r,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())),$r(i,n)},isISODateString:Kr,isDate:Hr,isTimeString:Jr,offsetDate:Wr,offsetTime:function(t){return Wr(t).getTime()},sameDay:pi,timeStringMinutes:Zr,timeToDate:oi,timeUTC:function(t){const e=Hr(t)||Kr(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())},validTimeValue:jr,validDateString:kr,timeValidation:Lr,dateValidation:_r};function mi(t,e,n,r,i=0){if(wr().makeDeepCopy)return wr().makeDeepCopy(t,e,n,r);const a=ar(),{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=fi(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:Vr(c)?d[a]=new Date(c).toISOString():d[a]=mi(c,e,n,r,i+1)}return d}function fi(t){return t?.map((t=>{const{name:e,value:n}=t;return e&&n&&{[`_${e}`]:n}})).filter(Boolean)}function hi({element:t,accessor:e}){if("string"!=typeof e)return{values:[]};const n=mi(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 gi(t){return"function"==typeof t}function Ii(t){return"string"==typeof t}function Ui(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function Si(t,e){if(!Ui(t)||!Ui(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 yi(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(Ui).map((t=>t[e]&&{[t[e]]:t})).filter(Boolean)):{}}const vi=t=>e=>t&&"object"==typeof e?Array.isArray(t)&&t.map((t=>({[t]:hi({element:e,accessor:t})?.value})))||"object"==typeof t&&Object.keys(t).map((t=>({[t]:hi({element:e,accessor:t})?.value})))||("string"==typeof t&&hi({element:e,accessor:t}))?.value:void 0,wi=vi;function Ti(t){return Array.isArray(t)?t.length+t.map(Ti).reduce(((t,e)=>t+e),0):"object"==typeof t&&null!==t?Object.keys(t).length+Object.keys(t).map((e=>Ti(t[e]))).reduce(((t,e)=>t+e),0):0}const Pi="tournamentRecords",Di="policyDefinitions",bi="tournamentRecord",Ni="drawDefinition",Ri="matchUpFormat",Mi="participantId",Ai="scheduleDates",Ei="structureId",Ci="participant",Oi="matchUpIds",Fi="structures",ki="matchUpId",xi="inContext",_i="structure",Li="courtIds",Bi="venueIds",Vi="matchUps",ji="courtId",Gi="eventId",qi="matchUp",$i="drawId",Wi="error",Hi="event",zi="param",Yi="object",Ki="array",Ji="validate",Zi="invalid",Xi="_ofType",Qi="_oneOf",ta={[Pi]:x,[bi]:_,[Di]:Jt,[Ni]:j,[Mi]:Ae,tournamentId:B,[Ei]:It,[Oi]:$t,[Ci]:Re,[Fi]:St,[ki]:qt,[_i]:yt,[ji]:ie,[Vi]:Ht,[qi]:zt,[Li]:ae,[Bi]:ae,[$i]:at,[Gi]:Tt,[Hi]:Pt},ea={[Pi]:Yi,[Di]:Yi,[bi]:Yi,[Ni]:Yi,[Ai]:Ki,[Ci]:Yi,[Oi]:Ki,[Fi]:Ki,[_i]:Yi,[Li]:Ki,[Bi]:Ki,[Vi]:Ki,[qi]:Yi,[Hi]:Yi,uuids:Ki};function na(t,e,n){if(!t&&!Ui(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=ra(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=ra(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=a&&!gi(a),s=t[r]&&!a&&function(t,e,n){if(n=n||ea[e]||"string","array"===n)return!Array.isArray(t[e]);return typeof t[e]!==n}(t,r,e),c=o[r]&&!t[r],u=i||s||c||a&&t[r]&&!function(t,e){return!gi(e)||e(t)}(t[r],a);return u&&(n=r),u}));return!u.length||d}));return{paramError:r,errorParam:n}}(t,e);if(!r)return{valid:!0};return Nr({info:{param:i},result:{error:void 0===t[i]?ta[i]||Nn:r.validate&&r.invalid||Nn},stack:n})}function ra(t,e){return P(Object.keys(t),Object.keys(e))}const ia="DYNAMIC",aa="RANKING",oa="RATING",sa="SCALE",ca="SEEDING",ua={RANKING:aa,RATING:oa,SCALE:sa,SEEDING:ca};function da(t){const e=na(t,[{[Ci]:!0}]);if(e.error)return e;const n=t.participant.timeItems?.filter((({itemType:t})=>t?.startsWith(sa)&&[aa,oa,ca].includes(t.split(".")[1]))),r={ratings:{},rankings:{},seedings:{}};if(n?.length){const t=t=>n.filter((e=>e?.itemType===t)).sort(((t,e)=>new Date(t.createdAt||void 0).getTime()-new Date(e.createdAt||void 0).getTime())).pop(),e=m(n.map((({itemType:t})=>t)));for(const n of e){const e=t(n);if(e){const[,t,n,i,a]=e.itemType.split("."),o=a?`${i}.${a}`:i,s=(t===ca?"seedings":t===aa&&"rankings")||"ratings";r[s][n]||(r[s][n]=[]),r[s][n].push({scaleValue:e.itemValue,scaleDate:e.itemDate,scaleName:o})}}}return{...E,...r}}function pa(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 la="voluntaryConsolation",ma="competitiveBands",fa="roundRobinTally",ha="positionActions",ga="matchUpActions",Ia="rankingPoints",Ua="roundNaming",Sa="participant",ya="progression",va="scheduling",wa="avoidance",Ta="scoring",Pa="seeding",Da="feedIn",ba="draws",Na={POLICY_TYPE_VOLUNTARY_CONSOLATION:la,POLICY_TYPE_COMPETITIVE_BANDS:ma,POLICY_TYPE_ROUND_ROBIN_TALLY:fa,POLICY_TYPE_POSITION_ACTIONS:ha,POLICY_TYPE_MATCHUP_ACTIONS:ga,POLICY_TYPE_RANKING_POINTS:Ia,POLICY_TYPE_ROUND_NAMING:Ua,POLICY_TYPE_PARTICIPANT:Sa,POLICY_TYPE_PROGRESSION:ya,POLICY_TYPE_SCHEDULING:va,POLICY_TYPE_AVOIDANCE:wa,POLICY_TYPE_DISPLAY:"display",POLICY_TYPE_FEED_IN:Da,POLICY_TYPE_SCORING:Ta,POLICY_TYPE_SEEDING:Pa,POLICY_TYPE_AUDIT:"audit",POLICY_TYPE_DRAWS:ba};function Ra({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:n,participantId:r,internalUse:i,personId:a}){const o=mi(t.find((t=>r&&t.participantId===r||a&&t.person&&t.person.personId===a)),!1,i);if(o){const t=e?.[Sa];if(n?.withScaleValues){const{ratings:t,rankings:e}=da({participant:o});o.rankings=e,o.ratings=t}if(t?.participant)return pa({template:t.participant,source:o})}return o}function Ma(t){return t&&"object"==typeof t?t.tournamentRecord?Cr({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:_}:{error:ae}}function Aa(t){return t&&"object"==typeof t?t.drawDefinition?Cr({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:q}:{error:ae}}function Ea(t){return t&&"object"==typeof t?t.event?Cr({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:Pt}:{error:ae}}function Ca(t){return t&&"object"==typeof t?t.tournamentRecord?Ar({element:t.tournamentRecord,name:t.name}):{error:_}:{error:ae}}function Oa(t){return t&&"object"==typeof t?t?.event?Ar({element:t.event,name:t.name}):{error:Pt}:{error:ae}}const Fa="appliedPolicies",ka="positionActions",xa="context",_a="delegatedOutcome",La="disabled",Ba="disableLinks",Va="disableAutoCalc",ja="drawDeletions",Ga="entryProfile",qa="flightProfile",$a="groupingAttribute",Wa="lineUps",Ha="linkedTournamentsIds",za="matchUpHistory",Ya="participantRepresentatives",Ka="personRequests",Ja="rankingPoints",Za="roundTarget",Xa="scheduleLimits",Qa="scheduleTiming",to="schedulingProfile",eo="subOrder",no="tally",ro="tieFormatModification",io={ACTIVE_SUSPENSION:"activeSuspension",APPLIED_POLICIES:Fa,AUDIT_POSITION_ACTIONS:ka,CONTEXT:xa,DELEGATED_OUTCOME:_a,DISABLED:La,DISABLE_LINKS:Ba,DISABLE_AUTO_CALC:Va,DRAW_DELETIONS:ja,DRAW_PROFILE:"drawProfile",ENTRY_PROFILE:Ga,EVENT_PROFILE:"eventProfile",EVENT_WITHDRAWAL_REQUESTS:"eventWithdrawalRequests",FLIGHT_PROFILE:qa,GROUPING_ATTRIBUTE:$a,LINEUPS:Wa,LINKED_TOURNAMENTS:Ha,MATCHUP_HISTORY:za,PARTICIPANT_REPRESENTATIVES:Ya,PERSON_REQUESTS:Ka,RANKING_POINTS:Ja,ROUND_TARGET:Za,SCHEDULE_LIMITS:Xa,SCHEDULE_TIMING:Qa,SCHEDULING_PROFILE:to,STATUS_DETAIL:"statusDetail",SUB_ORDER:eo,TALLY:no,TIE_FORMAT_MODIFICATIONS:ro,FACTORY:"factory"},ao=[_a,La,Ba,qa,Wa,za,Ya,Ka,Za,Xa,Qa,to,eo,no];function oo({tournamentRecords:t}){return{tournamentIds:Ui(t)?Object.keys(t):[],...E}}const so={linkTournaments:function({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:x};const e=oo({tournamentRecords:t}),{tournamentIds:n}=e;if(n?.length>1){return Cr({tournamentRecords:t,discover:!0,extension:{name:Ha,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=oo({tournamentRecords:t}),{tournamentIds:r}=n;if(!r.includes(e))return{error:B};let i;return r.every((n=>{const r=t[n],{extension:a}=Fr({element:r,name:Ha});if(!a)return!0;const o=a?.value?.tournamentIds||[];if(!o?.length||1===o.length&&o.includes(e)||n===e){const t=Ca({name:Ha,tournamentRecord:r});return t.error&&(i=t.error),t.success}const s=o.filter((t=>t!==e));a.value={tournamentIds:s};const c=Ma({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?Nr({result:Ar({name:Ha,tournamentRecords:t,discover:!0}),stack:"unlinkTournaments"}):{error:x}}},co=t=>e=>t[e],uo=(t=[])=>t.map(mo).filter(Boolean),po=(t=[])=>t.map(lo).filter(Boolean),lo=(t={})=>co(t)("participantId"),mo=(t={})=>co(t)("matchUpId");const fo="ABANDONED",ho="AWAITING_RESULT",go="BYE",Io="CANCELLED",Uo="COMPLETED",So="DEAD_RUBBER",yo="DEFAULTED",vo="DOUBLE_DEFAULT",wo="DOUBLE_WALKOVER",To="IN_PROGRESS",Po="INCOMPLETE",Do="NOT_PLAYED",bo="RETIRED",No="SUSPENDED",Ro="TO_BE_PLAYED",Mo="WALKOVER",Ao=[ho,Uo,yo,To,Po,bo,No],Eo=[ho,Uo,yo,wo,vo,To,Po,bo,No,Mo],Co=[fo,ho,go,Io,Uo,So,yo,wo,vo,To,Po,Do,bo,No,Ro,Mo],Oo=[go,wo,vo,Uo,yo,bo,Mo],Fo=[fo,ho,Io,So,To,Po,Do,No,Ro,void 0],ko=[Io,fo,Uo,So,yo,wo,vo,bo,Mo],xo=[fo,Uo,yo,wo,vo,To,bo,Mo],_o=[To,Po,No,Ro],Lo={ABANDONED:fo,AWAITING_RESULT:ho,BYE:go,CANCELLED:Io,COMPLETED:Uo,DEAD_RUBBER:So,DEFAULTED:yo,DOUBLE_WALKOVER:wo,DOUBLE_DEFAULT:vo,IN_PROGRESS:To,INCOMPLETE:Po,NOT_PLAYED:Do,RETIRED:bo,SUSPENDED:No,TO_BE_PLAYED:Ro,WALKOVER:Mo},Bo="MAIN",Vo="QUALIFYING",jo="CONSOLATION",Go="VOLUNTARY_CONSOLATION",qo="PLAY_OFF",$o=[Bo,Vo,jo,qo,Go],Wo={[Vo]:1,[Bo]:2,[qo]:3,[jo]:3,[Go]:4},Ho="finishingPositions",zo="aggregateEventStructures",Yo={[Bo]:1,[qo]:2,[jo]:3,[Vo]:4,[Go]:5},Ko={[qo]:1,[Bo]:2,[jo]:3,[Vo]:4,[Go]:5},Jo="CLUSTER",Zo="WATERFALL",Xo="ITEM",Qo="CONTAINER",ts="DRAW",es="RANDOM",ns="TOP_DOWN",rs="BOTTOM_UP",is="POSITION",as="WINNER",os="LOSER",ss="FIRST_MATCHUP",cs="AD_HOC",us="FEED_IN",ds="COMPASS",ps="OLYMPIC",ls="SINGLE_ELIMINATION",ms="DOUBLE_ELIMINATION",fs="FIRST_MATCH_LOSER_CONSOLATION",hs="FIRST_ROUND_LOSER_CONSOLATION",gs="LUCKY_DRAW",Is="CURTIS_CONSOLATION",Us="CURTIS_CONSOLATION",Ss="FEED_IN_CHAMPIONSHIP_TO_SF",ys="FEED_IN_CHAMPIONSHIP_TO_SF",vs="FEED_IN_CHAMPIONSHIP_TO_QF",ws="FEED_IN_CHAMPIONSHIP_TO_QF",Ts="FEED_IN_CHAMPIONSHIP_TO_R16",Ps="FEED_IN_CHAMPIONSHIP_TO_R16",Ds="MODIFIED_FEED_IN_CHAMPIONSHIP",bs="MODIFIED_FEED_IN_CHAMPIONSHIP",Ns="FEED_IN_CHAMPIONSHIP",Rs="ROUND_ROBIN",Ms="ROUND_ROBIN_WITH_PLAYOFF",As="DECIDER",Es="BACKDRAW",Cs={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"}},Os={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},Fs="WIN_RATIO",ks="ROUND_OUTCOME",xs=[ds,Is,ws,Ps,ys,Ns,vs,Ts,Ss,fs,hs,gs,bs,ps,qo,Ms],_s={MAIN:Bo,QUALIFYING:Vo,CONSOLATION:jo,ITEM:Xo,CONTAINER:Qo,FIRST_MATCHUP:ss,WINNER:as,LOSER:os,AD_HOC:cs,FEED_IN:us,FLEX_ROUNDS:"AD_HOC",COMPASS:ds,PLAY_OFF:qo,OLYMPIC:ps,KNOCKOUT:"SINGLE_ELIMINATION",SINGLE_ELIMINATION:ls,DOUBLE_ELIMINATION:ms,CURTIS:Is,FICSF:Ss,FICQF:vs,FICR16:Ts,MFIC:Ds,VOLUNTARY_CONSOLATION:Go,FIRST_MATCH_LOSER_CONSOLATION:fs,FIRST_ROUND_LOSER_CONSOLATION:hs,MODIFIED_FEED_IN_CHAMPIONSHIP:bs,FEED_IN_CHAMPIONSHIP_TO_R16:Ps,FEED_IN_CHAMPIONSHIP_TO_QF:ws,FEED_IN_CHAMPIONSHIP_TO_SF:ys,FEED_IN_CHAMPIONSHIP:Ns,LUCKY_DRAW:gs,ROUND_ROBIN_WITH_PLAYOFF:Ms,ROUND_ROBIN:Rs,DECIDER:As,BACKDRAW:Es,COMPASS_ATTRIBUTES:Cs,OLYMPIC_ATTRIBUTES:Os,DRAW:ts,RANDOM:es,TOP_DOWN:ns,BOTTOM_UP:rs,WATERFALL:Zo,WIN_RATIO:Fs,ROUND_OUTCOME:ks,MULTI_STRUCTURE_DRAWS:xs,generatedDrawTypes:[cs,ds,Is,ms,ws,Ps,ys,Ns,us,fs,hs,gs,bs,ps,qo,Rs,Ms,ls],stageOrder:Wo,finishOrder:Yo,AGGREGATE_EVENT_STRUCTURES:zo,FINISHING_POSITIONS:Ho};function Ls(t,e,n){const r=t=>Fr({element:t,name:Za})?.extension?.value,i=n?.deprioritizeCompleted,a=n?.mode===zo&&Ko,o=n?.mode===Ho&&Yo,s=o||a||Wo,c=t=>(t=>t?.stage===Bo&&1===t?.stageSequence)(t)?-1:s[t?.stage],u=t=>t?.matchUps.every((({matchUpStatus:t})=>ko.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)||(Bs(t)||0)-(Bs(e)||0)}function Bs(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 Vs({drawDefinition:t,structureId:e}){if(!t)return{error:j};if(!e)return{error:It};const{structures:n}=js({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===Xo?r?.find((t=>t.structures?.some((t=>t.structureId===e)))):void 0}}function js({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=Fr({element:t,name:Za})?.extension?.value;return!i||i===e})).sort(((t,e)=>Ls(t,e,a)))??[],d=t?Object.assign({},...$o.map((t=>{const e=u?.filter((e=>e.stage===t));return e?.length&&{[t]:e}})).filter(Boolean)):{};return{structures:u,stageStructures:d}}function Gs({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}=qs({structure:t}),i=r?.map(wi("participantId")).filter(Boolean)??[];return e[n].push(...i),i})).flat(),stagePositionedParticipantIds:e}}function qs({drawDefinition:t,structureId:e,structure:n}){let r,i=[];if(!n){if(!t)return{positionAssignments:i,error:j};if(({structure:n,error:r}=Vs({drawDefinition:t,structureId:e})),r)return{positionAssignments:i,error:r}}return n.structures?i=[].concat(...n.structures.map((t=>qs({structure:t}).positionAssignments))):n.positionAssignments?i=n.positionAssignments:r=Ct,{positionAssignments:i,error:r}}function $s({drawDefinition:t,structureId:e,structure:n}){const r=qs({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 Ws="SIGN_IN_STATUS",Hs="SIGNED_OUT",zs="SIGNED_IN",Ys="TEAM",Ks="INDIVIDUAL",Js="GROUP",Zs="PAIR",Xs="TEAM",Qs={TEAM_PARTICIPANT:Ys,INDIVIDUAL:Ks,GROUP:Js,TEAM:Xs,PAIR:Zs},tc={INDIVIDUAL:Ks,GROUP:Js,PAIR:Zs,TEAM:Xs,SIGN_IN_STATUS:Ws,SIGNED_OUT:Hs,SIGNED_IN:zs};function ec({participantsProfile:t,participants:e=[],deepCopy:n}){const r=new Map,i=!1!==n?mi(e,t?.convertExtensions,!0):e,a=i.filter((t=>t.participantType===Xs)),o=i.filter((t=>t.participantType===Js)),s=i.filter((t=>t.participantType===Zs));return i.forEach((t=>{if(t.participantType===Ks){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 nc(t){return t&&void 0!==String.fromCodePoint?t.toUpperCase().replace(/./g,(t=>String.fromCodePoint(t.charCodeAt(0)+127397))):t}const rc=[{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 ic({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=rc.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 ac(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 oc({returnPreviousValues:t,itemSubTypes:e,itemType:n,element:r}){if(!r)return{error:ae,info:Rr};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 sc({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}=oc({returnPreviousValues:t,element:r,itemSubTypes:e,itemType:n});return i&&{timeItem:i,previousItems:a}||{info:o}}function cc({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}=oc({element:e,returnPreviousValues:t,itemSubTypes:n,itemType:r});return i&&{timeItem:i,previousItems:a}||{info:o}}const uc="SINGLES",dc="SINGLES",pc="DOUBLES",lc="DOUBLES",mc="TEAM",fc="TEAM",hc={SINGLES_MATCHUP:uc,SINGLES:dc,DOUBLES_MATCHUP:pc,DOUBLES:lc,TEAM_MATCHUP:mc,TEAM:fc},gc={[Js]:"groupParticipantIds",[Zs]:"pairParticipantIds",[Xs]:"teamParticipantIds"},Ic={[Js]:"groups",[Xs]:"teams"};function Uc({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&&vc({participantMap:c,participantId:e})}for(const t of n.participants??[]){const n=mi(t,e,a),{participantId:u,individualParticipantIds:d,participantType:p}=n;if(Object.assign(c[u].participant,n),d&&yc({individualParticipantIds:d,participantCopy:n,participantMap:c,participantType:p,participantId:u}),r&&(c[u].participant.signedIn=Sc(n)),i){const{ratings:t,rankings:e,seedings:r}=da({participant:n});c[u].participant.seedings=r,c[u].participant.rankings=e,c[u].participant.ratings=t}(s||o)&&ic({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?pa({template:e,source:i}):i)}}}}({participantMap:c,template:Ui(t)?t:void 0})}return{participantMap:c}}function Sc(t){const{timeItem:e}=oc({itemType:Ws,element:t});return e?.itemValue===zs}function yc({individualParticipantIds:t,participantCopy:e,participantMap:n,participantType:r,participantId:i}){for(const a of t){const o=n[a].participant;if(o[gc[r]].push(i),[Xs,Js].includes(r)){const{participantRoleResponsibilities:t,participantOtherName:n,participantName:i,participantId:a,teamId:s}=e;o[Ic[r]].push({participantRoleResponsibilities:t,participantOtherName:n,participantName:i,participantId:a,teamId:s})}if(r===Zs){const e=t.find((t=>t!==a));n[a].pairIdMap[i]=e,n[a].pairIdMap[e]=i}}}function vc({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:{[dc]:{...n},[lc]:{...n},[Xs]:{...n},...n}}}function wc({participantsProfile:t,useParticipantMap:e,tournamentRecord:n,contextProfile:r,inContext:i}){if(e){const e=Uc({...t,...r,tournamentRecord:n})?.participantMap;return{participantMap:e}}let a,o=mi(n.participants,!1,!0)||[];if((t?.withIOC||t?.withISO2)&&o.forEach((e=>ic({participant:e,...t}))),(i||t?.withGroupings)&&o?.length&&({participantsWithGroupings:o,groupInfo:a}=ec({participantsProfile:t,deepCopy:!1,participants:o})),t?.withScaleValues&&o?.length)for(const t of o){const{ratings:e,rankings:n}=da({participant:t});t.rankings=n,t.ratings=e}return{participants:o,groupInfo:a}}function Tc({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 Pc({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}=Vs({drawDefinition:r,structureId:a}),{positionAssignments:p}=qs({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=Tc({groupedOrder:s,roundPositionsCount:h.length}),T=v?.length||1;if(T<=h.length){const t=N(h,f/T);o===rs&&t.forEach((t=>t.reverse())),S=v?.length&&v?.map((e=>t[e-1])).flat()||S}o===ns?y=S[I-1]:o===rs?((!v?.length||T>h.length)&&(I=m.length+1-I),y=S[I-1]):o===es&&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}=Fr({element:b,name:Ba});if(t?.value)return{disabledDrawPosition:D}}return{matchUp:P,targetDrawPosition:D,matchUpDrawPositionIndex:U}}function Dc({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[as,os].includes(i?.linkType)&&!i?.source?.roundNumber?Nr({result:{error:Nn},stack:"getTargetLink",context:i}):i}function bc({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 Nc({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}=Vs({structureId:a?.structureId,drawDefinition:r}),s=o?.finishingPosition;return s===ks?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}=bc({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=Dc({source:c,linkType:as}),d=Dc({linkCondition:ss,linkType:os,source:c});let p=Dc({source:c,linkType:os});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!==ts&&t.find((({matchUpId:t})=>t===a)),S=o&&f!==ts&&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!==ts&&({matchUpDrawPositionIndex:v,targetDrawPosition:y,matchUp:S}=Pc({targetLink:p,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:b,drawDefinition:n}));l&&h!==ts&&({matchUpDrawPositionIndex:U,targetDrawPosition:I,matchUp:g}=Pc({targetLink:d,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:b,drawDefinition:n}));u&&!w&&m!==ts&&({matchUpDrawPositionIndex:P,targetDrawPosition:T,matchUp:w}=Pc({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 br({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 Rc(t){if(!Ui(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 Mc(t){return!!Array.isArray(t)&&t.every(Rc)}function Ac({matchUps:t=[],interpolate:i}){if(!Mc(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===fc))?r.filter((({matchUpType:t})=>t===fc)):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]=br({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=>!ko.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 Ec({drawDefinition:t,inContextDrawMatchUps:r}){const i={};return r.forEach((a=>{const{matchUpId:o,structureId:s,drawPositions:c=[]}=a,{structure:u}=Vs({drawDefinition:t,structureId:s});if(u?.finishingPosition===Fs){const{roundNumber:t}=a,r=t&&n(t)+1,i=u.matchUps??[],{roundMatchUps:o}=Ac({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=Nc({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=Oc({upcomingMatchUp:n});let u=Oc({upcomingMatchUp:s});if(a.matchUpStatus!==go&&s?.matchUpStatus===go){const{matchUp:e}=Cc({matchUp:s,drawDefinition:t,inContextDrawMatchUps:r})||{};u=e&&Oc({upcomingMatchUp:e})||u}const p=a.schedule?.timeAfterRecovery;if(p){if(c?.schedule?.scheduledTime){Zr(c.schedule.scheduledTime)<Zr(p)&&(i[c.matchUpId]=a.matchUpId,c.schedule.scheduleConflict=a.matchUpId)}if(u?.schedule?.scheduledTime){Zr(u.schedule.scheduledTime)<Zr(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===ss,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=po(n?.sides),a=po(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 Cc({matchUp:t,drawDefinition:e,inContextDrawMatchUps:n}){const{matchUpId:r,matchUpStatus:i,structureId:a}=t||{};if(!t||!a||t?.matchUpStatus===Ro)return{matchUp:t};if(i===go){let i;if(t.winnerMatchUpId)i=n.find((({matchUpId:e})=>e===t.winnerMatchUpId));else{const t=Nc({inContextDrawMatchUps:n,drawDefinition:e,matchUpId:r});({winnerMatchUp:i}=t?.targetMatchUps||{})}return Cc({matchUp:i,drawDefinition:e,inContextDrawMatchUps:n})}return{matchUp:void 0}}function Oc(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 Fc({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===Fa))?.value;if(i)for(const n of Object.keys(i))(t?e.includes(n):!e.length||e.includes(n))&&(o[n]=mi(i[n],!1,!0))}}function kc({policyTypes:t=[],tournamentRecord:e,drawDefinition:n,structure:r,event:i}){if(!Array.isArray(t))return{error:Kt};const{appliedPolicies:a}=Fc({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 xc="WALKOVER",_c="RETIRED",Lc="COMPETITIVE",Bc="ROUTINE",Vc="DECISIVE",jc="winRatio",Gc={[ma]:{policyName:"Competitive Bands Default",profileBands:{[Vc]:20,[Bc]:50}}};function qc({policyDefinitions:t,tournamentRecord:e,contextProfile:n,drawDefinition:r,event:i}){const a={policies:{}};if(!n)return a;const o=kc({tournamentRecord:e,drawDefinition:r,event:i}).policyDefinitions;if(n.withCompetitiveness){const e=t?.[ma]??o?.[ma]??Gc[ma];a.policies[ma]=e}return a}function $c({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&&[jo,qo].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 Wc({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 Hc({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(mi(t,!0,!0),{containerStructureId:n,structureId:e,structureName:a}))):i})).flat();return(i?.matchUps||[]).concat(...a)}function zc({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 Yc({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 Nr({result:{error:Fe},stack:r});const i=(t=t??e?.participants??[]).filter((t=>t.participantType===Zs&&P(n,t.individualParticipantIds).length===n.length&&t.individualParticipantIds.length===n.length)),a=i[0];if(!a)return Nr({result:{error:Ee},stack:r});const o=mi(i.slice(1),!1,!0);return{participant:mi(a),duplicatedPairParticipants:o,...E}}function Kc({drawDefinition:t,participantId:e}){if("object"!=typeof t)return{error:j};if("string"!=typeof e)return{error:Ae};const{extension:n}=Fr({element:t,name:Wa});return{lineUp:(n?.value||{})[e]}}function Jc({drawDefinition:t,attributes:e}){let{extension:n}=Fr({element:t,name:Ga});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:Ga,value:r},Aa({drawDefinition:t,extension:n}),{entryProfile:r}}function Zc({drawDefinition:t}){const{extension:e}=Fr({element:t,name:Ga});return{entryProfile:e?.value||{}}}const Xc="ALTERNATE",Qc="CONFIRMED",tu="DIRECT_ACCEPTANCE",eu="FEED_IN",nu="JUNIOR_EXEMPT",ru="LUCKY_LOSER",iu="ORGANISER_ACCEPTANCE",au="QUALIFIER",ou="SPECIAL_EXEMPT",su="UNGROUPED",cu="UNPAIRED",uu="WILDCARD",du="WITHDRAWN",pu=[Qc,tu,nu,iu,ou],lu=[eu,ru,au],mu=[Qc,tu,eu,nu,iu,ou,uu],fu=[Qc,tu,nu,ru,au,iu,ou,uu],hu=[Xc,Qc,tu,eu,nu,ru,iu,au,"REGISTERED",ou,su,cu,uu,du],gu={ALTERNATE:Xc,CONFIRMED:Qc,DIRECT_ACCEPTANCE:tu,DIRECT_ENTRY_STATUSES:mu,DRAW_SPECIFIC_STATUSES:lu,EQUIVALENT_ACCEPTANCE_STATUSES:pu,FEED_IN:eu,JUNIOR_EXEMPT:nu,LUCKY_LOSER:ru,ORGANISER_ACCEPTANCE:iu,QUALIFIER:au,SPECIAL_EXEMPT:ou,STRUCTURE_SELECTED_STATUSES:fu,UNGROUPED:su,UNPAIRED:cu,VALID_ENTRY_STATUSES:hu,WILDCARD:uu,WITHDRAWN:du};function Iu({stage:t,drawDefinition:e}){const{entryProfile:n}=Zc({drawDefinition:e}),r=Object.keys(n).includes(t);if(!r&&$o.includes(t)){return Jc({drawDefinition:e,attributes:[{[t]:{drawSize:void 0,alternates:!0}}]}),!0}return r}function Uu({stage:t,drawDefinition:e,entryStatus:n}){return e.entries.reduce(((e,r)=>r.entryStage===t&&r.entryStatus===n?e+1:e),0)}function Su({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=Fr({name:Za,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===qo){const{playoffEntries:i,error:a}=function({provisionalPositioning:t,drawDefinition:n,structureId:r}){const i=[],a=(n.links??[]).find((t=>t.linkType===is&&t.target.structureId===r));if(a){const{finishingPositions:r,structureId:o}=a.source,{structure:s}=Vs({drawDefinition:n,structureId:o});if(s?.structureType===Qo){(s.structures??[]).forEach((n=>{const a=n.positionAssignments??[],{structureId:o}=n,s=o,c=Object.assign({},...a.map((t=>{const{participantId:e}=t,n=Fr({element:t,name:no}).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:qo,entryStatus:eu,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 yu({provisionalPositioning:t,returnAllProxies:e,drawDefinition:n,structureId:r,structure:i}){let a,o=[];i||({structure:i,error:a}=Vs({drawDefinition:n,structureId:r}));const s=qs({structure:i}).positionAssignments;if(a||!i)return{seedAssignments:[],error:Ut};r||(r=i.structureId);const{stage:c,stageSequence:u}=i,d=c===qo&&n&&Su({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 vu=(t,e)=>(t||0)+(e||0);function wu(t,e){const n=Array.isArray(t)?t[0]:t;return isNaN(n)&&xc||n<=e[Vc]&&Vc||n<=e[Bc]&&Bc||Lc}function Tu({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(vu)&&(n[r[0]>r[1]?0:1]+=1),{sets:e,games:n,score:t}}function Pu(t){const e=Math.min(...t.games),n=Math.max(...t.games);return Math.round(e/n*100)}function Du(t){return t.map(Pu).sort().map((t=>parseFloat(t.toFixed(2))))}function bu({tournamentRecord:t,drawDefinition:e,policyType:n,structure:r,event:i}){if(!t)return{error:_};const{appliedPolicies:a}=Fc({tournamentRecord:t,drawDefinition:e,structure:r,event:i});return a?.[n]?{policy:a[n]}:{info:ee?.message}}function Nu({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&&bu({policyType:ma,tournamentRecord:t}).policy,o=e||a?.profileBands||Gc[ma].profileBands,s=Du([Tu({score:r})]),c=wu(s,o),u=Array.isArray(s)?s[0]:s;return{...E,competitiveness:c,pctSpread:u}}function Ru({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===Ks)).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 Mu="CHECK_IN",Au="CHECK_OUT",Eu="SCHEDULE.ASSIGNMENT.VENUE",Cu="SCHEDULE.ALLOCATION.COURTS",Ou="SCHEDULE.ASSIGNMENT.COURT",Fu="SCHEDULE.COURT.ORDER",ku="SCHEDULE.DATE",xu="SCHEDULE.ASSIGN.OFFICIAL",_u="SCHEDULE.TIME.SCHEDULED",Lu="SCHEDULE.TIME.START",Bu="SCHEDULE.TIME.STOP",Vu="SCHEDULE.TIME.RESUME",ju="SCHEDULE.TIME.END",Gu="SCHEDULE.TIME.MODIFIERS",qu="TO_BE_ANNOUNCED",$u="NEXT_AVAILABLE",Wu="FOLLOWED_BY",Hu="AFTER_REST",zu="RAIN_DELAY",Yu=[qu,$u,Wu,Hu,zu],Ku="SCALE",Ju="RATING",Zu="RANKING",Xu="SEEDING",Qu="PUBLISH",td="PUBLIC",ed="STATUS",nd={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:Yu,AFTER_REST:Hu,ALLOCATE_COURTS:Cu,ASSIGN_COURT:Ou,ASSIGN_OFFICIAL:xu,ASSIGN_VENUE:Eu,CHECK_IN:Mu,CHECK_OUT:Au,COMPLETED_DATE:"COMPLETED.DATE",COURT_ORDER:Fu,ELIGIBILITY:"ELIGIBILITY",END_TIME:ju,FOLLOWED_BY:Wu,MEDICAL:"MEDICAL",MODIFICATION:"MODIFICATION",NEXT_AVAILABLE:$u,NOT_BEFORE:"NOT_BEFORE",OTHER:"other",PENALTY:"PENALTY",PUBLIC:td,PUBLISH:Qu,RANKING:Zu,RATING:Ju,RAIN_DELAY:zu,REGISTRATION:"REGISTRATION",RESUME_TIME:Vu,RETRIEVAL:"RETRIEVAL",SCALE:Ku,SCHEDULE:"SCHEDULE",SCHEDULED_DATE:ku,SCHEDULED_TIME:_u,SEEDING:Xu,START_TIME:Lu,STATUS:ed,STOP_TIME:Bu,SUSPENSION:"SUSPENSION",TIME_MODIFIERS:Gu,TO_BE_ANNOUNCED:qu};function rd({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}=Ru({matchUp:t}),i=(t.timeItems??[]).filter((t=>t?.itemType&&[Mu,Au].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===Mu));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 id(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 ad(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 od({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 sd({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}=bu({policyType:va,tournamentRecord:t,event:r}),a=t?Fr({element:t,name:Qa}).extension:void 0,o=a?.value,s=r&&Fr({name:Qa,element:r}).extension,c=s?.value;return{scheduleTiming:{tournamentScheduling:o,eventScheduling:c,categoryName:e,categoryType:n,policy:i}}}const cd="SINGLES",ud="SINGLES",dd="DOUBLES",pd="DOUBLES",ld="TEAM",md="TEAM",fd={AGE:"AGE",BOTH:"BOTH",DOUBLES:dd,DOUBLES_EVENT:pd,RATING:"RATING",SINGLES:cd,SINGLES_EVENT:ud,TEAM_EVENT:md,TEAM:ld},hd="DOUBLES_SINGLES",gd="SINGLES_DOUBLES",Id="total",Ud="participantConflict",Sd="matchUpConflict",yd="ISSUE_IDS",vd="CONFLICT",wd="WARNING",Td="ERROR",Pd="ISSUE",Dd="STATE",bd={SINGLES_DOUBLES:gd,DOUBLES_SINGLES:hd,TOTAL:Id,CONFLICT_MATCHUP_ORDER:Sd,CONFLICT_PARTICIPANTS:Ud,SCHEDULE_ISSUE_IDS:yd,SCHEDULE_CONFLICT:vd,SCHEDULE_WARNING:wd,SCHEDULE_ERROR:Td,SCHEDULE_ISSUE:Pd,SCHEDULE_STATE:Dd};function Nd({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??ud;const c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=sd({tournamentRecord:n,categoryName:i,categoryType:a,event:s});return Rd({eventType:o,timingDetails:{...u,matchUpFormat:r,categoryType:a,defaultTiming:c}})}function Rd({timingDetails:t,eventType:e}){const n=function({matchUpFormat:t,categoryName:e,categoryType:n,defaultTiming:r,tournamentScheduling:i,eventScheduling:a,policy:o}){return od({categoryName:e,categoryType:n,timesBlockArray:[a?.matchUpAverageTimes&&id({...a,matchUpFormat:t}),i?.matchUpAverageTimes&&id({...i,matchUpFormat:t}),o?.matchUpAverageTimes&&id({...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 od({categoryName:a,categoryType:o,timesBlockArray:[e?.matchUpRecoveryTimes&&ad({...e,averageMinutes:n,matchUpFormat:i}),t?.matchUpRecoveryTimes&&ad({...t,averageMinutes:n,matchUpFormat:i}),s?.matchUpRecoveryTimes&&ad({...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===ud?gd:hd;return{averageMinutes:i,recoveryMinutes:s,typeChangeRecoveryMinutes:a?.minutes&&(o?.includes(c)&&a.minutes[c]||s)}}function Md(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Ad({visibilityThreshold:t,timeItems:e,itemType:n}){const r=e.filter((e=>e&&e.itemType===n&&(!t||Md(e)<new Date(t).getTime()))).sort(((t,e)=>Md(t)-Md(e))).pop(),i=r&&Md(r);return{itemValue:r?.itemValue,timeStamp:i}}function Ed({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=Ad({timeItems:r?.timeItems||[],itemType:_u,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{scheduledTime:i}:n}function Cd({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=Ad({timeItems:r?.timeItems||[],itemType:ku,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{scheduledDate:i}:n}function Od({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=Ad({timeItems:r?.timeItems||[],itemType:Cu,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{allocatedCourts:mi(i,!1,!0)}:n}function Fd({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=Ad({timeItems:r?.timeItems||[],itemType:Ou,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{courtId:i}:n}function kd({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=Ad({timeItems:r?.timeItems||[],itemType:Eu,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{venueId:i}:n}function xd({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}=Fr({element:n,name:Ha});return{[e]:(i?.value?.tournamentIds||[]).filter((t=>t!==r))}})))}}function _d(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}function Ld(){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]}const Bd="addDrawDefinition",Vd="addMatchUps",jd="addParticipants",Gd="addScaleItems",qd="addVenue",$d="audit",Wd="deleteParticipants",Hd="deleteVenue",zd="deletedDrawIds",Yd="deletedMatchUpIds",Kd="modifyDrawDefinition",Jd="modifyDrawEntries",Zd="modifyEventEntries",Xd="modifyMatchUp",Qd="modifyParticipants",tp="modifyPositionAssignments",ep="modifySeedAssignments",np="modifyTournamentDetail",rp="modifyVenue",ip="mutations",ap="publishEvent",op="publishEventSeeding",sp="publishOrderOfPlay",cp="unPublishEvent",up="unPublishEventSeeding",dp="unPublishOrderOfPlay",pp="updateInContextMatchUp",lp={ADD_DRAW_DEFINITION:Bd,ADD_MATCHUPS:Vd,ADD_PARTICIPANTS:jd,ADD_SCALE_ITEMS:Gd,ADD_VENUE:qd,AUDIT:$d,DELETE_PARTICIPANTS:Wd,DELETE_VENUE:Hd,DELETED_DRAW_IDS:zd,DELETED_MATCHUP_IDS:Yd,MODIFY_DRAW_DEFINITION:Kd,MODIFY_DRAW_ENTRIES:Jd,MODIFY_EVENT_ENTRIES:Zd,MODIFY_MATCHUP:Xd,MODIFY_PARTICIPANTS:Qd,MODIFY_POSITION_ASSIGNMENTS:tp,MODIFY_SEED_ASSIGNMENTS:ep,MODIFY_TOURNAMENT_DETAIL:np,MODIFY_VENUE:rp,MUTATIONS:ip,PUBLISH_EVENT_SEEDING:op,PUBLISH_EVENT:ap,PUBLISH_ORDER_OF_PLAY:sp,UNPUBLISH_EVENT_SEEDING:up,UNPUBLISH_EVENT:cp,UNPUBLISH_ORDER_OF_PLAY:dp,UPDATE_INCONTEXT_MATCHUP:pp};function mp(t){const{disableNotice:e,venue:n,context:r}=t;if("object"!=typeof n)return{error:Nn};const i=_d(t);let a;n.venueId||(n.venueId=Ld());for(const t of Object.values(i)){const e=fp({disableNotice:!0,tournamentRecord:t,context:r,venue:n});if(e?.error)return e;a=e.venue}return e||cr({topic:qd,payload:{venue:n}}),br({...E,venue:a})}function fp({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=Ld());if(t.venues.reduce(((t,e)=>t||e.venueId===r.venueId),void 0))return{error:nn};if(n){Cr({element:r,extension:{value:n,name:xa}})}return t.venues.push(r),e||cr({payload:{venue:r,tournamentId:t.tournamentId},topic:qd}),{...E,venue:mi(r)}}function hp({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=(xd({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(const a of i){const i=hp({tournamentRecord:t[a],venueId:n});if(i.success&&i.venue)return mp({tournamentRecord:e,venue:i.venue}),{...E,venue:r}}}return r?{...E,venue:r}:{error:rn}}function gp({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=(xd({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(const o of a){const a=gp({tournamentRecord:t[o],courtId:n});if(a.success)return a.venue&&mp({tournamentRecord:e,venue:a.venue}),{...E,court:r,venue:i}}}return Nr({result:{error:tn},stack:"findCourt"})}function Ip({tournamentRecord:t,internalUse:e,courtId:n}){if(!t)return{error:_};if(!n)return{error:ie};const r=gp({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:mi(i,!1,e)}}function Up({tournamentRecord:t,venueId:e}){if(!t)return{error:_};if(!e)return{error:an};const n=hp({tournamentRecord:t,venueId:e});if(n.error)return n;const r=(n.venue?.courts??[]).map((e=>(({courtInfo:t})=>({...t}))(Ip({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:mi(a,!1,!0)}}function Sp({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=Ad({timeItems:r?.timeItems||[],itemType:Gu,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{timeModifiers:i}:n}function yp(t){if(xr.test(t)){const e=qr();return new Date(`${e}T${t}`)}return new Date(t)}function vp(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 wp({event:t,eventId:e}){if(!t)return{error:Tt};const n=Fr({name:qa,element:t}),r=n?.extension,i=e?mi(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 Tp(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&&wp({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,...Nr({result:{error:Pt},stack:i})}}return{event:void 0,drawDefinition:void 0,...Nr({result:{error:q},context:{drawId:r,eventId:n},stack:i})}}function Pp(t){let e=t.event,n=t.matchUpType;const{scheduleVisibilityFilters:r,afterRecoveryTimes:i,tournamentRecord:a,usePublishState:o,scheduleTiming:s,matchUpFormat:c,publishStatus:u,matchUp:d}=t;if(!d)return{error:zt};if(i&&!d.matchUpType&&!t.matchUpType&&(e||a)&&d.drawId){let r=e?.drawDefinitions?.find((t=>t.drawId===d.drawId));!r&&a&&({drawDefinition:r,event:e}=Tp({tournamentRecord:a,drawId:d.drawId}));const i=d.structureId&&r?.structures?.find((({structureId:t})=>t===d.structureId));n=t.matchUpType||i?.matchUpType||r?.matchUpType||e?.eventType!==ld&&e?.eventType}const{milliseconds:p,time:l}=function({matchUp:t}){if(!t)return{error:zt};if(!t.timeItems)return{error:fn};const e=t.timeItems.filter((t=>[Lu,Bu,Vu,ju].includes(t?.itemType))).sort(((t,e)=>yp(t.itemValue).getTime()-yp(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 Lu:n=0;break;case ju:if(t.lastValue&&[Lu,Vu].includes(t.lastType)){const r=yp(e.itemValue).getTime()-yp(t.lastValue).getTime();n=t.milliseconds+r}else n=t.milliseconds;break;case Bu:if([Lu,"SCHECULE.TIME.RESUME"].includes(t.lastType)){const r=yp(e.itemValue).getTime()-yp(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([Lu,Vu].includes(n.lastType)){const t=(new Date).getTime()-yp(n.lastValue).getTime();n.milliseconds+=t}return{milliseconds:n.milliseconds,time:vp(n.milliseconds),relevantTimeItems:e}}({matchUp:d}),{startTime:m}=function({matchUp:t}){const e=t=>t.createdAt?new Date(t.createdAt).getTime():0,n=(t?.timeItems||[]).reduce(((t,n)=>{const r=n.itemType===Lu&&n;return r&&(!t||e(r)<e(t))?r:t}),void 0),r=n?.itemValue;return{startTime:r}}({matchUp:d}),{endTime:f}=function({matchUp:t}){const e=t=>t.createdAt?new Date(t.createdAt).getTime():0,n=(t?.timeItems||[]).reduce(((t,n)=>{const r=n.itemType===ju&&n;return r&&(!t||e(r)>e(t))?r:t}),void 0),r=n?.itemValue;return{endTime:r}}({matchUp:d});let h;const{visibilityThreshold:g,eventIds:I,drawIds:U}=r??{};if(I&&!I.includes(d.eventId)||U&&!U.includes(d.drawId))h=br({milliseconds:p,startTime:m,endTime:f,time:l});else{const t={matchUp:d,visibilityThreshold:g},{allocatedCourts:e}=Od(t),{scheduledTime:r}=Ed(t);let{scheduledDate:o}=Cd(t);const{venueId:u}=kd(t),{courtId:I}=Fd(t),{courtOrder:U}=function({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=Ad({timeItems:r?.timeItems||[],itemType:Fu,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{courtOrder:i}:n}(t),{timeModifiers:S}=Sp(t);let y,v,w,T,P;const D=d.matchUpType??n;if(s&&r&&i&&D){const t={matchUpFormat:d.matchUpFormat??c,...s};({averageMinutes:v=0,recoveryMinutes:w=0,typeChangeRecoveryMinutes:T=0}=Rd({timingDetails:t,eventType:D})),(v||w)&&(y=f?ci(Qr(f),w):ci(r,v+w)),T&&(P=f?ci(Qr(f),T):ci(r,v+T))}!o&&r&&(o=ti(r));const b=Br({scheduledDate:o,scheduledTime:r}),N={},R=(a&&u&&Up({tournamentRecord:a,venueId:u}))?.venueData||{};u&&(N[u]=R);const{venueName:M,venueAbbreviation:A,courtsInfo:E}=R,C=I&&E?.find((t=>t.courtId===I)),O=C?.courtName;for(const t of e||[]){if(!a)break;t.venueId&&!N[t.venueid]&&(N[t.venueId]=Up({venueId:t.venueId,tournamentRecord:a})?.venueData);const e=N[t.venueId];t.venueName=e?.venueName;const n=e?.courtsInfo?.find((e=>e.courtId===t.courtId));t.courtName=n?.courtName}h=br({typeChangeTimeAfterRecovery:P,timeAfterRecovery:y,scheduledDate:o,scheduledTime:r,isoDateString:b,allocatedCourts:e,timeModifiers:S,venueAbbreviation:A,venueName:M,venueId:u,courtOrder:U,courtName:O,courtId:I,typeChangeRecoveryMinutes:T,recoveryMinutes:w,averageMinutes:v,milliseconds:p,startTime:m,endTime:f,time:l})}const{scheduledDate:S}=Cd({matchUp:d}),{scheduledTime:y}=Ed({matchUp:d});if(o&&u?.displaySettings?.draws){const t=u.displaySettings.draws,e=(t?.[d.drawId]??t?.default)?.scheduleDetails;if(e){const t=(e.find((t=>S&&t.dates?.includes(S)))??e.find((t=>!t.dates?.length)))?.attributes;if(t){h=pa({source:h,template:Object.assign({},...Object.keys(h).map((t=>({[t]:!0}))),t)})}}}return{schedule:h,endDate:d.matchUpStatus&&ko.includes(d.matchUpStatus)&&(ti(f)||ti(S)||ti(y))||void 0}}function Dp(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 bp({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 Np({drawDefinition:t,structure:e,matchUp:n,event:r}){return{tieFormat:bp({item:n,drawDefinition:t,structure:e,event:r})||bp({item:e,drawDefinition:t,structure:e,event:r})||Dp(t)||Dp(r)}}function Rp(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 Mp="timed",Ap="NOAD",Ep="SET",Cp={S:"normal",F:"final"};function Op(t){if("string"==typeof t){const e=t.startsWith("T")&&Mp||t.startsWith(Ep)&&Ep||"";if(e===Mp){const e=_p(t);if(e)return{simplified:!0,setFormat:e,bestOf:1}}if(e===Ep)return function(t){const e=t.split("-"),n=Bp(e[0].slice(3)),r=1===n||n%2!=0?n:void 0,i=1!==n&&n%2==0?n:void 0,a=e&&Fp(e[1]),o=e&&Fp(e[2]),s=a&&a.timed||o&&o.timed,c=r&&r<6||s&&i,u=!e[2]||o,d=a,p=br({setFormat:a,exactly:i,bestOf:r});o&&(p.finalSetFormat=o);if(c&&d&&u)return p}(t)}}function Fp(t){if(":"===t?.[1]){const e=t.split(":"),n=Cp[e[0]],r=e[1];if(n&&r){if(r.startsWith("TB")){const t=xp(r);return!1!==t&&("object"==typeof t?{tiebreakSet:t}:void 0)}if(r.startsWith("T"))return _p(r);const e=t.match(/^[FS]:(\d+)([A-Za-z]*)/),n=e&&Lp(e[2])||!1,i=!e?.[2]||n,a=e?Bp(e[1]):void 0,o=kp(r),s=!1!==o,c=s&&o||a,u=xp(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 kp(t,e=!0){const n=t?.indexOf("@")>0&&t.split("@");if(n){return(e?Bp(n[1]):n[1])||!1}}function xp(t){if(t){if(t.startsWith("TB")){const e=kp(t,!1),n=t.match(/^TB(\d+)([A-Za-z]*)/),r=n?.[1],i=n&&Lp(n[2]),a=!n?.[2]||i,o=Bp(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 _p(t){const e=t.slice(1),n=e.match(/^(\d+)(@?[A-Za-z]*)/),r=Bp(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 Lp(t){return t&&t.indexOf(Ap)>=0}function Bp(t){return isNaN(Number(t))?0:Number(t)}function Vp({roundsNotPowerOf2:t,drawDefinition:e,structure:n,matchUps:r}){if(!n)return!1;r=r??n.matchUps??[],t=t??Ac({matchUps:r}).roundsNotPowerOf2;const i=!!n.positionAssignments?.find((({drawPosition:t})=>t))||!!r?.find((({drawPositions:t})=>t?.length));return(!e?.drawType||e.drawType!==gs)&&!n?.structures&&t&&i}function jp({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===Go||t?.drawType&&t.drawType!==cs||r||i)}const Gp={[Ua]:{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:{[Bo]:"",[qo]:"P",[Vo]:"Q",[jo]:"C"}}};function qp(t){const e=na(t,[{[qi]:!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===Ks&&dc||i===Zs&&lc||i===Xs&&Xs||void 0}return{matchUpType:r}}function $p(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!==mc&&!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}=Ed({matchUp:t}),{scheduledDate:n}=Cd({matchUp:t}),r=ti(e)||n;if(!$.find((t=>pi(t,r))))return!1}if(j.length){const{courtId:e}=Fd({matchUp:t}),{allocatedCourts:n}=Od({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}=kd({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 Wp({drawPositionCollectionAssignment:t,sideNumberCollectionAssignment:e,positionAssignments:n,displaySideNumber:r,seedAssignments:i,drawPosition:a,isFeedRound:o,sideNumber:s}){const c=n.find((t=>t.drawPosition&&t.drawPosition===a)),u=a&&t,d=s&&e,p=u?u[a]?.participantId:c?.participantId,l=c?function({displaySideNumber:t,seedAssignments:e,participantId:n,assignment:r,sideNumber:i}){const a={drawPosition:r.drawPosition,displaySideNumber:t,sideNumber:i};if(n){const t=function({seedAssignments:t,participantId:e}){return t?.find((t=>!t.seedProxy&&t.participantId===e))}({seedAssignments:e,participantId:n});Object.assign(a,t,{participantId:n})}else r.bye&&Object.assign(a,{bye:!0});r.qualifier&&Object.assign(a,{qualifier:!0});return a}({displaySideNumber:r,seedAssignments:i,participantId:p,assignment:c,sideNumber:s}):{...d?.[s]};if(o&&(1===s?Object.assign(l,{participantFed:!0}):Object.assign(l,{participantAdvanced:!0})),a&&u){const t=u[a]?.teamParticipant,e=u[a]?.participant,n=u[a]?.substitutions;e&&(l.participant=e),n&&(l.substitutions=n),t&&(l.teamParticipant=t)}return l}const Hp="ANY",zp="MALE",Yp="MIXED",Kp="OTHER",Jp="FEMALE",Zp={ANY:Hp,MALE:zp,FEMALE:Jp,MIXED:Yp,OTHER:Kp};function Xp({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=qc({tournamentRecord:c,contextProfile:U,drawDefinition:S}));const{appliedPolicies:V}=Fc({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=Wc({drawDefinition:S,structure:D}));const{positionAssignments:z,allPositionsAssigned:Y}=$s({structure:D}),K=!H||Y,{seedAssignments:J}=yu({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&&$c({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=Hc({matchUpsMap:P,structureId:X,inContext:A});const ut=G?.[Ua],dt=function({roundNamingPolicy:t,drawDefinition:e,structure:n,matchUps:r}){const{roundProfile:i,roundMatchUps:a}=Ac({matchUps:r}),{structureAbbreviation:o,stage:s}=n,c=jp({structure:n}),u=Vp({structure:n}),d=n.structures,p={},l=Gp[Ua],m=n.stage===Vo,f=m?Math.max(...(e?.structures??[]).filter((t=>t.stage===Vo)).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!==Bo?s[0]:"",T=t?.stageConstants||l.stageConstants,P=`${g}${s&&T?.[s]||w}${h}`,D=i?Object.keys(i):[],b=m&&T?.[Vo]?`${T?.[Vo]}-`:"";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=$p({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}=Vs({drawDefinition:t,structureId:e});if(r?.stage!==jo)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]:Ac({matchUps:Hc({structureId:t,matchUpsMap:n})}).roundProfile})))),c=Hc({matchUpsMap:n,structureId:e}),{roundProfile:u}=Ac({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=Tc({roundPositionsCount:g.length,groupedOrder:i}),U=I?.length||1;if(U<=h){const t=N(g,p.length/U);r===rs&&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!==rs||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]=Rp(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=Hc({matchUpsMap:i,structureId:r});if(({roundProfile:n}=Ac({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(Rp),u=s.map((t=>t.map((t=>t-a)))).map(Rp),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(Rp).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=$p({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=$p({matchUps:ct,...h,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(h?.matchUpTypes||h?.matchUpIds)&&(ct=$p({matchUpTypes:h.matchUpTypes,matchUpIds:h.matchUpIds,matchUps:ct})),(h?.matchUpTypes||h?.matchUpIds||A)&&(O=Ac({matchUps:ct}).roundMatchUps??[]),Np({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=Np({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!==ld&&F?.eventType,V=w?go:O.matchUpStatus,{schedule:j,endDate:G}=Pp({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=({attribute:e,lineUp:r,teamParticipant:a})=>{const{assignedParticipantIds:s,substitutions:u}=zc({collectionPosition:n,collectionId:o,lineUp:r});if(c!==lc){const t=s?.[0];return t&&{[e]:{participantId:t,teamParticipant:a,substitutions:u}}}if(s?.length<=2){const n=i?.[s[0]]?.pairIdMap?.[s[1]],r=n&&i[n]?.participant||Yc({participantIds:s,tournamentParticipants:t}).participant,o=r?.participantId;return{[e]:{participantId:o,teamParticipant:a,substitutions:u}}}if(s?.length>2)return{[e]:{teamParticipant:a,substitutions:u}}};if(!r?.length){const t=s?.map((t=>{const{teamParticipant:e,sideNumber:n}=t,r=t.lineUp||Kc({participantId:e.teamParticipantId,drawDefinition:a})?.lineUp;return u({attribute:n,lineUp:r,teamParticipant:e})})).filter(Boolean)||{};return{sideNumberCollectionAssignment:Object.assign({},...t)}}const d=r?.map((n=>{const r=e.find((t=>t.drawPosition===n))?.participantId,o=s?.find((t=>t?.drawPosition===n)),c=o?.teamParticipant||r&&i?.[r]?.participant||t?.find((({participantId:t})=>t===r)),d=o?.lineUp||Kc({participantId:r,drawDefinition:a})?.lineUp;return u({attribute:n,lineUp:d,teamParticipant:c})})).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...d)}}({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&&Nu({...f,matchUp:O}),It=O.finishingPositionRange??d.finishingPositionRange,Ut=t=>br(t,void 0,!0),St={...Ut(v),...Ut({matchUpFormat:O.matchUpType===ld?void 0:L,tieFormat:O.matchUpType!==ld?void 0:k,gender:_?.gender??F?.gender,roundOfPlay:tt!==Vo&&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}),...mi(Ut(O),!0,!0)};if(L&&O.score?.scoreStringSide1){const t=Op(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=Wp({...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,mi({sides:o},!0,!0))}if(a&&St.sides){const t=y?.[Sa],e=e=>{const n=g?.[e]?.participant;return n&&pa({template:t?.participant,source:n})};if(St.sides.filter(Boolean).forEach((t=>{if(t.participantId){const n=mi(e(t.participantId)||a&&Ra({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&&Ra({policyDefinitions:y,tournamentParticipants:a,internalUse:!0,contextProfile:U,participantId:t})));Object.assign(t.participant,{individualParticipants:n})}})),!St.matchUpType){const{matchUpType:t}=qp({matchUp:St});t&&Object.assign(St,{matchUpType:t})}if(U?.inferGender&&(!St.gender||St.gender===Yp)&&2===St.sides?.length&&St.matchUpType!==ld){const t=St.sides.map((t=>{if(St.matchUpType===dc)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===go,n=St.sides?.map((({participant:t,drawPosition:e,sideNumber:n,lineUp:r})=>{const i=t?.participantType===ld&&t;return{teamParticipant:i&&br({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}=rd({matchUp:St});Object.assign(St,{allParticipantsCheckedIn:t,checkedInParticipantIds:e})}return Array.isArray(U?.exclude)&&U?.exclude.forEach((t=>delete St[t])),St}}function Qp({matchUp:t}){return!!t&&(ko.includes(t?.matchUpStatus)||t?.winningSide)}function tl({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}=Vs({drawDefinition:h,structureId:U}));const T=Xp({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}=$s({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]===fc;return!(t.matchUpType!==fc&&e)})).forEach((e=>{if(e.matchUpStatus===fo)return void P.push(e);e.matchUpType===fc&&(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=_o.includes(e.matchUpStatus)&&(r||i&&(!t||a));return s?R.push(e):Qp({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 el(t){Object.assign(t,{requireParticipants:!1});const e=nl(t);if(e.error)return Nr({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 nl(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=qc({policyDefinitions:u,tournamentRecord:d,contextProfile:I,event:w})),!e?.length&&d&&(e=d?.participants,(y||s?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:T}=ec({participants:e,participantsProfile:s})));const{structures:M}=js({drawDefinition:U});if(!M)return{error:Ut};r||(r=Wc({drawDefinition:U}));const A=U&&$c({drawDefinition:U}).exitProfiles;M.forEach((t=>{const{byeMatchUps:s=[],pendingMatchUps:T=[],upcomingMatchUps:M=[],completedMatchUps:E=[],abandonedMatchUps:C=[]}=tl({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=$p({matchUps:t,...m})),l&&(t=$p({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;Ec({inContextDrawMatchUps:[].concat(...e&&P||[],...n&&D||[],...r&&b||[],...i&&N||[],...a&&R||[]),drawDefinition:U})}return O}function rl(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}=wc({participantsProfile:o,useParticipantMap:u,policyDefinitions:c,tournamentRecord:d,contextProfile:l,inContext:g})),l&&!r&&(r=qc({policyDefinitions:c,tournamentRecord:d,contextProfile:l,drawDefinition:m,event:U}));return{...el({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 il({drawDefinition:t,matchUpsMap:e,structureId:n}){const r=Vs({drawDefinition:t,structureId:n});if(r.error)return Nr({result:r});const{matchUps:i}=Xp({structure:r.structure,matchUpsMap:e});return{...Ac({matchUps:i}),matchUps:i,matchUpsMap:e}}function al({finishingPositions:t,drawDefinition:e,structureId:n}){const{roundProfile:r}=il({drawDefinition:e,structureId:n}),i=r&&Object.keys(r);return i?.reduce(((e,n)=>(ol(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 ol(t){return[m(t?.finishingPositionRange?.loser||[]),m(t?.finishingPositionRange?.winner||[])]}function sl(t){return ol(t).map((t=>w(t[0],t[1]&&t[1]+1||t[0]+1)))}function cl({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!==Vo)).map((({structureId:t})=>t))).map((e=>{const{roundProfile:n}=il({drawDefinition:t,matchUpsMap:r,structureId:e}),i=n&&Object.values(n);return i?.map(sl).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 ul({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=cl({drawDefinition:i});if(o.error)return o;const s=o.positionsPlayedOff,c=al({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=al({finishingPositions:s,drawDefinition:i,structureId:a}),p=d?Object.values(d):[],l=d?p.reduce(((t,e)=>t.includes(e.roundNumber)?t:t.concat(e.roundNumber)),[]).map((t=>n(t))):[],m=u.filter((t=>!l.includes(t))).sort(e),{roundProfile:f}=il({drawDefinition:i,structureId:a}),h=m.map((t=>{const e=f?.[t].finishingPositionRange.loser,[n,r]=e??[0,0];return w(n,(r||n)+1)})).flat().sort(e),{playoffRoundsRanges:g}=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:m,roundProfile:f}),I=[...m,...l];return{playoffPositionsReturned:h,playedOffSourceRounds:l,playoffRoundsRanges:g,playoffSourceRounds:m,sourceRounds:I,roundProfile:f}}function dl({drawDefinition:t,structureId:e}){if(!t)return{error:j};const{matchUps:n,matchUpsMap:r}=rl({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:i,positionsPlayedOff:a}=cl({drawDefinition:t,matchUpsMap:r}),{structures:o}=js({drawDefinition:t}),s=o.filter((t=>!e&&t.stage!==Go||t.structureId===e)),c={};for(const e of s){const r=e?.structureId,a=pl({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 pl({playoffPositions:t,drawDefinition:n,structure:r,matchUps:i}){const a=r?.structureId,{links:o}=bc({drawDefinition:n,structureId:a});if(r.structureType===Qo||r.structures){const t=qs({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}=cl({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!==ss)).map((t=>t.source?.roundNumber))||[],c=o?.source?.filter((t=>t.linkCondition===ss)).map((t=>t.source?.roundNumber))||[],u=ul({excludeRoundNumbers:s,playoffPositions:t,drawDefinition:n,structureId:a}),d=u?.playoffSourceRounds?[...u?.playoffSourceRounds||[]]:void 0,p=[...u?.playoffRoundsRanges||[]],{roundProfile:l,error:m}=u;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(d&&s===a.length){d.push(t);const e=l?.[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};p.push(a)}}}return d&&d.sort(e),p.sort(((t,e)=>t.roundNumber-e.roundNumber)),{playoffRounds:d,playoffRoundsRanges:p,error:m}}function ll(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 ml({drawDefinition:t,tournamentId:e,matchUps:n,eventId:r}){return t&&ll(t),cr({payload:{matchUps:n,tournamentId:e,eventId:r},topic:Vd}),{...E}}function fl({drawDefinition:t,tournamentId:e,matchUpIds:n,eventId:r,action:i}){t&&ll(t),cr({topic:Yd,payload:{tournamentId:e,matchUpIds:n,eventId:r,action:i}});for(const t of n)pr({key:t});return{...E}}function hl({drawDefinition:t,tournamentId:e,structureId:n,context:r,eventId:i,matchUp:a}){if(!a)return console.log(zt),{error:zt};if(t){Il({drawDefinition:t,structureIds:n?[n]:void 0,tournamentId:e,eventId:i})}return cr({topic:Xd,payload:{matchUp:a,tournamentId:e,context:r},key:a.matchUpId}),{...E}}function gl({tournamentId:t,eventId:e,drawDefinition:n}){return n?(ll(n),cr({payload:{drawDefinition:n,tournamentId:t,eventId:e},topic:Bd,key:n.drawId}),{...E}):(console.log(j),{error:j})}function Il({drawDefinition:t,tournamentId:e,structureIds:n,eventId:r}){return t?(ll(t,n),cr({payload:{tournamentId:e,eventId:r,drawDefinition:t},topic:Kd,key:t.drawId}),{...E}):{error:j}}function Ul({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 cr({payload:{tournamentId:e,eventId:r,drawId:t.drawId,structureId:a,seedAssignments:i},topic:ep,key:t.drawId}),Il({structureIds:[a],drawDefinition:t,tournamentId:e,eventId:r}),{...E}}function Sl({drawDefinition:t,tournamentId:e,structure:n,event:r}){if(!t)return{error:j};if(!n)return{error:yt};const i=qs({structure:n}),a=n.structureId,o=t.drawId,s=r?.eventId;return cr({topic:tp,payload:{positionAssignments:i,tournamentId:e,structureId:a,eventId:s,drawId:o},key:a}),Il({structureIds:[a],drawDefinition:t,tournamentId:e,eventId:s}),{...E}}function yl({drawPositions:t,structure:e}){if([Vo,Bo].includes(e.stage)&&1===e.stageSequence)return;const{positionAssignments:n}=qs({structure:e}),r=n?.filter((({drawPosition:e})=>t?.includes(e)));r?.forEach((t=>{Cr({element:t,extension:{name:Ba,value:!0}})}))}function vl({drawDefinition:t,positionAction:e}){const{extension:n}=Fr({name:ka,element:t}),r=Array.isArray(n?.value)?n?.value??[]:[];if(!r?.length){const e=t.structures.find((t=>t.stage===Bo));if(e){const t=qs({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})}}Cr({element:t,extension:{name:ka,value:r.concat(e)}})}function wl({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 Tl(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 Pl({matchUpStatus:t}){return Oo.includes(t)}function Dl({matchUpStatus:t}){return Fo.includes(t)}function bl({matchUpStatus:t,winningSide:e,tieMatchUps:n,sides:r,score:i}){const a=r?.find((({participantId:t})=>t)),o=n?.filter(bl)?.length;return Tl({score:i})||o||e&&a||t&&function({matchUpStatus:t}){return xo.includes(t)}({matchUpStatus:t})&&![yo,Mo,To].includes(t)}function Nl(t){const{sides:e,matchUpType:n}=t||{},r=t.potentialParticipants?.length?t.potentialParticipants.flat().map((t=>n===lc?t?.individualParticipantIds||[]:t.participantId)).flat():[],i=(e||[]).map((t=>n===lc&&(t?.participant?.individualParticipantIds||[])||t?.participantId&&[t.participantId]||[])).flat();return{individualParticipantIds:i.concat(r).flat(),enteredIndividualParticipantIds:i,potentialIndividualParticipantIds:r}}function Rl({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:n,roundsCount:r,roundLimit:i,matchUps:a,lucky:o,fmlc:s}){if(!Mc(a))return[];const{roundProfile:c,roundNumbers:u=[]}=Ac({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(wi("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 Ml({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:n}){if(!e)return{error:j};const r={loserMatchUpIds:{},winnerMatchUpIds:{}};t||({matchUps:t,matchUpsMap:n}=el({inContext:!0,drawDefinition:e,matchUpsMap:n}));const i=n?.drawMatchUps.some((t=>t.finishingPositionRange));if(!i&&1===e?.structures?.length&&!e?.structures[0].structures){Rl({matchUps:n?.drawMatchUps??[]})}return(t??[]).filter((({collectionId:t})=>!t)).forEach((i=>{const{matchUpId:a,structureId:o}=i,s=Nc({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:a}),{winnerMatchUp:c,loserMatchUp:u}=s.targetMatchUps,d=c?.matchUpId,p=u?.matchUpId,l=Hc({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 Al(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,...br({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=qc({policyDefinitions:c,tournamentRecord:d,contextProfile:l,event:I})),!e?.length&&!r&&d){const t=wc({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=sd({tournamentRecord:d,event:I}).scheduleTiming;return{matchUps:b.flatMap((t=>{const{matchUps:u}=el({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 El(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}=wc({participantsProfile:i,useParticipantMap:o,policyDefinitions:s,tournamentRecord:c,contextProfile:d,inContext:u}));const{appliedPolicies:I}=Fc({tournamentRecord:c}),U={...f,tournamentId:h,indoorOutDoor:c.indoorOutdoor,surfaceCategory:c.surfaceCategory,endDate:c.endDate},S=qc({policyDefinitions:s,tournamentRecord:c,contextProfile:d});return{matchUps:g.flatMap((t=>(U.eventDrawsCount=t.drawDefinitions?.length??0,Al({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 Cl({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 El({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:n,policyDefinitions:i,tournamentRecord:d,matchUpFilters:a,contextFilters:o,nextMatchUps:s,inContext:c}).matchUps??[]})).flat()}}function Ol(t,e){return function(t,e){return(Wo[t?.stage]||0)-(Wo[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 Fl(t){let e=_d(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===is));let f=n;if(m.length){f=Cl({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}=Nl(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)Ml({drawDefinition:o}),f?.length||(f=rl({drawDefinition:o}).matchUps),I(f);else{if(f?.length||(f=Cl({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(Ol),r=n?.find((({roundPosition:t})=>!t));if(!r){const r=n?.find((({tournamentId:t})=>t)),{drawDefinition:i}=Tp({tournamentRecord:e[r?.tournamentId],drawId:t});i&&Ml({drawDefinition:i})}I(n)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:p,matchUps:f,...E}}function kl(t){const{drawDefinition:n,findContainer:r,structureId:i,event:a}=t;let o=t.structure;const{containedStructures:s}=wl({drawDefinition:n}),c=i&&s[i]||[];if(!o){const t=Vs({drawDefinition:n,structureId:i});if(t.error)return t;o=r?t.containingStructure??t.structure:t.structure}if(jp({drawDefinition:n,structure:o}))return{structure:o,isAdHoc:!0,error:Q};const{matchUps:u}=el({inContext:!0,matchUpFilters:{isCollectionMatchUp:!1},drawDefinition:n,event:a}),d=u?.filter((t=>t.structureId===i||c.includes(t.structureId))),{matchUpDependencies:p}=Fl({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)}bl(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}=qs({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 xl({drawPosition:t,matchUps:n=[]}){return{initialRoundNumber:n.filter((({drawPositions:e})=>t&&e?.includes(t))).map((({roundNumber:t})=>t)).sort(e)[0]}}const _l={reset:"[0m",bright:"[1m",dim:"[2m",red:"[31m",brightred:"[91m",green:"[32m",brightgreen:"[92m",yellow:"[33m",brightyellow:"[93m",blue:"[34m",brightblue:"[94m",lightblue:"[105m",magenta:"[35m",brightmagenta:"[95m",cyan:"[36m",brightcyan:"[96m",white:"[37m",brightwhite:"[97m"},Ll=[];function Bl(t,e){"string"==typeof t&&(t={method:t}),(e||Qn())&&Ll.push(t)}function Vl(t){const e=function(t){const e=Ll.slice();return t&&(Ll.length=0),e}(t),n=e.map((t=>{const{color:e,keyColors:n,method:r,newline:i}=t,a=Object.keys(_l).includes(e)?_l[e]:_l.cyan,o=Object.keys(t).filter((t=>!["color","keyColors","method","newline"].includes(t))).map((e=>{const r=n&&Object.keys(n).includes(e)&&_l[n[e]]?_l[n[e]]:_l.brightwhite;return`${_l.white}${e}: ${r}${t[e]}`})).join(", ");return[i?"\n":"",a,r,r?.length<15?"\t\t":"\t",_l.white,o,_l.reset,"\n"].join("")}));n?.length&&console.log(...n)}function jl({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}=Vs({drawDefinition:r,structureId:o})),!s)return{error:Ut};o||({structureId:o}=s);const u="assignDrawPositionBye";Bl({method:u,color:"cyan",drawPosition:i}),a||(a=Wc({drawDefinition:r}));const{positionAssignments:d}=qs({structure:s}),{activeDrawPositions:p}=kl({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 Nr({result:{error:z},stack:u});const U=el({inContext:!0,drawDefinition:r,matchUpsMap:a}).matchUps??[],{matchUps:S}=Xp({provisionalPositioning:t,drawDefinition:r,matchUpFilters:{isCollectionMatchUp:!1},matchUpsMap:a,structure:s});if(d?.forEach((t=>{t.drawPosition===i&&(t.bye=!0)})),s.structureType===Qo)return function({tournamentRecord:t,drawDefinition:e,drawPosition:n,matchUps:r,event:i}){r.forEach((r=>{r.drawPositions?.includes(n)&&ql({eventId:i?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:r})}))}({tournamentRecord:n,drawDefinition:r,drawPosition:i,matchUps:S}),Sl({tournamentId:n?.tournamentId,drawDefinition:r,structure:s,event:c}),Gl({assignedParticipantId:I,isPositionAction:e,drawDefinition:r,drawPosition:i,structureId:o,stack:u});const{roundProfile:y,roundMatchUps:v}=Ac({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&&ql({tournamentRecord:n,drawDefinition:r,matchUp:P,event:c});const D=P?.drawPositions?.find((t=>t!==i));if(P&&D){const t=$l({sourceDrawPositions:P.drawPositions,matchUpId:P.matchUpId,inContextDrawMatchUps:U,drawPositionToAdvance:D,tournamentRecord:n,drawDefinition:r,matchUpsMap:a});if(t.error)return t}return Sl({tournamentId:n?.tournamentId,drawDefinition:r,structure:s,event:c}),Gl({assignedParticipantId:I,isPositionAction:e,drawDefinition:r,drawPosition:i,structureId:o,stack:u})}function Gl({assignedParticipantId:t,isPositionAction:e,drawDefinition:n,drawPosition:r,structureId:i,stack:a}){if(e){vl({drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:r,structureId:i,name:a}})}return Nr({result:{...E},stack:a})}function ql({tournamentRecord:t,drawDefinition:e,eventId:n,matchUp:r,event:i}){Object.assign(r,{matchUpStatus:go,score:void 0,winningSide:void 0}),hl({tournamentId:t?.tournamentId,eventId:n??i?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:r})}function $l({drawPositionToAdvance:t,inContextDrawMatchUps:n,sourceDrawPositions:r,tournamentRecord:i,drawDefinition:a,matchUpsMap:o,matchUpId:s,event:c}){Bl({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}=Vs({drawDefinition:a,structureId:p}),{positionAssignments:m}=qs({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}}=Nc({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}=Vs({drawDefinition:a,structureId:l}),{positionAssignments:f}=qs({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 Nr({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}),Nr({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?go:Ro;Object.assign(d,{matchUpStatus:A,score:void 0,winningSide:void 0,drawPositions:N});const E=d.drawPositions.find((t=>!b.includes(t)));Bl({method:u,color:"brightyellow",changedDrawPosition:E,pairedDrawPositionIsBye:R,drawPositionIsBye:M}),hl({tournamentId:i?.tournamentId,matchUp:d,eventId:c?.eventId,context:u,drawDefinition:a});const{targetLinks:{loserTargetLink:C},targetMatchUps:{loserMatchUp:O,loserTargetDrawPosition:F}}=Nc({matchUpId:o.matchUpId,inContextDrawMatchUps:n,drawDefinition:a});if(R||M){const e=R?t:P;if(e)$l({drawPositionToAdvance:e,matchUpId:o.matchUpId,inContextDrawMatchUps:n,tournamentRecord:i,drawDefinition:a,matchUpsMap:s});else if(M&&C&&O)if(O.feedRound)Wl({loserTargetDrawPosition:F,tournamentRecord:i,loserTargetLink:C,drawDefinition:a,loserMatchUp:O,matchUpsMap:s});else{const t=1-o.roundPosition%2,e=O.drawPositions[t],n=jl({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=jl({structureId:I.target.structureId,drawPosition:y,tournamentRecord:i,drawDefinition:a,event:c});if(t.error)return t}else Wl({loserTargetDrawPosition:y,tournamentRecord:i,loserTargetLink:I,drawDefinition:a,loserMatchUp:U,matchUpsMap:o,event:c})}return{...E}}function Wl({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:n,drawDefinition:r,loserMatchUp:i,matchUpsMap:a,event:o}){const{roundNumber:s}=i;Bl({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});const c=(a?.mappedMatchUps||{})[i.structureId].matchUps,{initialRoundNumber:u}=xl({drawPosition:t,matchUps:c});if(u===s){const i=jl({structureId:n.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:r,event:o});if(i.error)return i}}function Hl({positionAssignments:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:r,structure:i,event:a}){const{matchUps:o}=Xp({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?go:Ro;Object.assign(r,{matchUpStatus:t}),hl({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:a?.eventId,drawDefinition:n,matchUp:r})}}))}function zl(t){let{inContextDrawMatchUps:e,participantId:n,drawPosition:r}=t;const{tournamentRecord:i,drawDefinition:a,structureId:o,matchUpsMap:s,event:c}=t,{structure:u}=Vs({drawDefinition:a,structureId:o}),d=($s({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}=kl({drawDefinition:a,structureId:o});if(p.includes(r))return{error:X};e||({matchUps:e}=el({inContext:!0,drawDefinition:a,matchUpsMap:s}));return Yl({inContextDrawMatchUps:e,tournamentRecord:i,drawDefinition:a,structureId:o,drawPosition:r,matchUpsMap:s,event:c}).drawPositionCleared?(Sl({tournamentId:i?.tournamentId,drawDefinition:a,structure:u,event:c}),{...E,participantId:n}):{error:K}}function Yl({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:i,matchUpsMap:a,structureId:o,event:s}){const{structure:c}=Vs({drawDefinition:r,structureId:o});if(!c)return{error:Ut};const u=$s({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===Qo)return Hl({positionAssignments:u,tournamentRecord:e,drawDefinition:r,matchUpsMap:a,structure:c}),{drawPositionCleared:d,...E};const{matchUps:p}=Xp({drawDefinition:r,matchUpFilters:{isCollectionMatchUp:!1},matchUpsMap:a,structure:c,event:s}),{roundProfile:l,roundMatchUps:m}=Ac({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}=Vs({drawDefinition:r,structureId:o});if(!s)return{error:Ut};if(s.structureType===Qo)return;i=i||Wc({drawDefinition:r});const c=i?.mappedMatchUps||{},u=c[o].matchUps,{initialRoundNumber:d}=xl({drawPosition:e,matchUps:u}),p=u?.filter((t=>t.roundNumber>=a&&t.roundNumber!==d&&t.drawPositions?.includes(e))),l=qs({drawDefinition:r,structureId:o}).positionAssignments??[];p?.forEach((a=>Kl({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}),Kl({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 Kl({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??Wc({drawDefinition:r})).mappedMatchUps[s.structureId].matchUps,{initialRoundNumber:f}=xl({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===fc){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,hl({tournamentId:n?.tournamentId,context:`${u}-TEAM`,eventId:c?.eventId,matchUp:i,drawDefinition:r}))}const h=Nc({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&&go||i.matchUpStatus&&[yo,Mo].includes(i.matchUpStatus)&&i.matcHUpStatus||2===i.drawPositions?.length&&Ro||void 0;i.matchUpStatus=v,i.matchUpStatus&&[Mo,yo].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&&Bl({method:u,color:"brightyellow",removedDrawPosition:w}),hl({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];Yl({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}=Vs({structureId:i.structureId,drawDefinition:r}),{positionAssignments:c}=qs({structure:s}),u=c?.find((e=>e.drawPosition===t));if(u?.bye){const s=zl({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 Nr({result:a,stack:u});const s=(o?.mappedMatchUps||{})[I.structureId].matchUps,{initialRoundNumber:d}=xl({drawPosition:i,matchUps:s});1===d&&(Bl({method:u,color:"brightyellow",loserMatchUpDrawPosition:i}),Yl({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 Jl({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}=qs({structure:t});return e?e.map(wi("participantId")):[]})).flat().filter(Boolean));return{...E,assignedParticipantIds:n}}function Zl(t){const e=(t?.entries??[]).filter(Boolean).reduce(((t,e)=>{const{entryStage:n,entryStatus:r}=e,i=`_${n||Bo}${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 Xl(t){return[cu,su].includes(t)}function Ql({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&&!hu.includes(a))return{error:je};if(o&&!$o.includes(o))return{error:At};const l="modifyEntriesStatus",m=[];if(!a&&!s)return Nr({result:{error:ae},info:"Missing entryStatus",stack:l});if(s&&!Er({extension:s,requiredAttributes:["name"]}))return Nr({result:{error:Nn},info:"Invalid extension",context:{extension:s},stack:l});const f=[];p?.drawDefinitions?.forEach((t=>{const e=Jl({stages:d&&[d],drawDefinition:t}).assignedParticipantIds??[];f.push(...e)}));const h=n?.participants??[];if(!i.every((t=>{const e=Ra({tournamentParticipants:h,participantId:t})?.participantType;return!(e&&[Zs,Ys].includes(e)&&Xl(a)||a&&p?.eventType&&e===Ks&&[dd,md].includes(p.eventType)&&[Xc,...pu].includes(a))})))return{error:je};const g=p&&wp({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)&&!(pu.includes(t.entryStatus)&&pu.includes(a)))(t)&&!e)&&(a&&(t.entryStatus=a,delete t.entryPosition),o&&(t.entryStage=o,delete t.entryPosition),s&&(s.value?Cr({element:t,extension:s}):Ar({element:t,name:s.name})),!0)))?{...E}:{error:Le}},S=({flight:t,drawDefinition:e})=>{p&&(p.entries=Zl({entries:p.entries??[]})),t&&(t.drawEntries=Zl({entries:t.drawEntries})),e&&(e.entries=Zl({entries:e.entries}))},y=t=>{const{flight:e,drawDefinition:n}=t,r="updateDrawEntries";if(e){const t=U(e.drawEntries);if(t.error)return Nr({result:t,stack:r})}if(n){const t=U(n.entries);if(t.error)return Nr({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 Nr({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 Nr({result:e,stack:l})}const P=1===g?.flights?.length&&(p?.drawDefinitions?.length??0)<=g?.flights?.length;if(!I&&!r&&a&&lu.includes(a))return{error:He};if(!I&&!r||a===du||c&&P){const t=U(p?.entries);if(t?.error)return Nr({result:t,stack:l});let e;if(a===du&&(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 Nr({result:{error:e},stack:l})}t&&S({flight:I,drawDefinition:r});for(const t of p?.drawDefinitions??[])m.length&&!m.includes(t.drawId)||Il({tournamentId:n.tournamentId,eventId:p?.eventId,drawDefinition:t});return{...E}}function tm(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===go||e[n].scheduleItems.push({...d,scheduledDate:ti(d?.scheduledDate),scheduledTime:Qr(d?.scheduledTime),checkScoreHasValue:Tl({score:l}),matchUpStatus:r,roundPosition:i,structureId:a,matchUpType:o,roundNumber:s,matchUpId:c,potential:u,drawId:p})}function em({requireTimeStamp:t,scaleAttributes:e,participant:n}){if(!n)return{error:Re};if(!Ui(e))return{error:Nn};if(n.timeItems||(n.timeItems=[]),Array.isArray(n.timeItems)){const{accessor:r,scaleType:i,eventType:a,scaleName:o}=e,s=[sa,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!==sa)return{error:In};const a=r&&hi({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 nm({publishedSeeding:t,usePublishState:e,withSeeding:n,participant:r,event:i}){const a={},o=t=>[sa,ca,i.eventType,t].join("."),s=Object.assign({},...(r.timeItems||[]).filter((({itemType:t})=>t.split(".")[1]===ca)).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=em({scaleAttributes:{eventType:i.eventType,scaleType:ca,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 rm({event:t,status:e=td}){const n=`${Qu}.${ed}`;return sc({itemType:n,event:t})?.timeItem?.itemValue?.[e]}function im({drawDetails:t,drawId:e}){const n=t?.[e]?.publishingDetail;return n?.published}function am({tournamentRecord:t,eventIds:e,drawIds:n,drawId:r,event:i}){if(Array.isArray(e)&&e?.length){const n={};for(const r of e){if(!Ii(r))return{error:Nn};const e=Tp({tournamentRecord:t,eventId:r});if(!e)return{error:Pt};const i=om({event:e});if(i.error)return i;n[r]=i}return{...E,publishState:n}}if(!i&&t?.events&&Array.isArray(n)&&n.length){const e={};for(const r of t.events){const t=om({event:r});if(t.error)return t;for(const r of n){if(!Ii(r))return{error:Nn};const n=t.publishState.publishedDrawIds.includes(r);n&&(e[r]={published:n})}}return{...E,publishState:e}}if(i){const t=om({event:i});if(t.error)return t;if(r)return{publishState:{published:t.publishState.publishedDrawIds.includes(r),...E}};if(!Array.isArray(n)||!n?.length)return t;{const e={};for(const r of n)return Ii(r)?(e[r]={published:t.publishState.publishedDrawIds.includes(r)},{...E,publishState:e}):{error:Nn}}}return{error:Nn}}function om({event:t}){const e=rm({event:t});if(!e)return{error:Pt};const n={published:void 0,seedingScaleNames:[],drawIds:[]};e.seeding&&Object.assign(n,e.seeding);const{drawDetails:r}=e,i=r&&Object.keys(r).filter((t=>im({drawDetails:r,drawId:t})))||e.drawIds||[];return{publishState:{published:i.length>0,publishedDrawIds:i,publishedSeeding:n,drawDetails:r},...E}}function sm({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({},...fi(p)):{},m=Object.assign(l,{entryPosition:d,entryStatus:c,entryStage:u,ranking:o,eventId:a});n.events[a]=br(m,!1,!1,!0),r&&(e&&(n.events[a].seedAssignments=e),i&&(n.events[a].seedValue=i))}function cm(t,e){return(t||"").localeCompare(e||"")}function um({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===Mo&&(f.walkoverWinCount+=1),i===yo&&(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 dm(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!==Ys)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&&um({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)&&tm({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===Zs,n=i[M]?.participant.individualParticipantIds||[];if(y){if(r){const t=t=>i[t].matchUps[y]={participantWon:U===E,matchUpId:y,matchUpType:fc,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===Mo&&(i[t].counters[T].walkoverWins+=1,i[t].counters.walkoverWins+=1),p===yo&&(i[t].counters[T].defaultWins+=1,i[t].counters.defaultWins+=1)):(i[t].counters[T].losses+=1,i[t].counters.losses+=1,p===Mo&&(i[t].counters[T].walkovers+=1,i[t].counters.walkovers+=1),p===yo&&(i[t].counters[T].defaults+=1,i[t].counters.defaults+=1))};t(M),n.forEach(t)}}}}function pm({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=lm(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}=wp({event:e}),i=r?.flights?.map((({drawEntries:t})=>Array.isArray(t)?t.filter(n).map(lo):[])).flat()||[],a=e.drawDefinitions?.map((({entries:t})=>t?t.filter(n).map(lo):[]))||[];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(lo);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=>Gs({drawDefinition:t}).allPositionedParticipantIds)).filter(Boolean))),[]),y=t=>r?.reduce(((e,n)=>{const{accessor:r,value:i}=n,{values:a}=hi({element:t,accessor:r});return e&&a?.includes(i)}),!0);if(n=n?.filter((t=>{const e=oc({element:t,itemType:Ws})?.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&&lm(u)&&u.includes(i)||s&&o&&lm(s)&&s.includes(o)||c&&lm(n)&&lm(c)&&c.find((t=>n?.includes(t)))||r?.length&&lm(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&&lm(u)&&u.includes(i))&&(!s||o&&lm(s)&&s.includes(o))&&(!c||lm(n)&&lm(c)&&c.find((t=>n?.includes(t))))&&(!r?.length||lm(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===cd)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 lm(t){return t&&Array.isArray(t)&&t.length}function mm(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)&&Fl({tournamentRecord:c});let{participantMap:D}=Uc({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}=wp({event:t}),_=x?.flights??[],L=am({event:t}).publishState;L&&(b[F]=L);const B=L?.publishedSeeding;if(U||I||u){const e=n?Object.assign({},...fi(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}=nm({publishedSeeding:B,usePublishState:a,withSeeding:I,participant:e,event:t}))}const d=t=>{if(s[t]?.events?.[F])return;const r=s[t];sm({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(wi("drawId")),..._.map(wi("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)=>Ls(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===Bo&&1===e||t===Vo)).flatMap((t=>{const{seedAssignments:e,stageSequence:n,stage:r}=t,{positionAssignments:i}=qs({structure:t});return r===Bo?(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[Bo]=l),d&&m&&(d[Vo]=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]=br({seedAssignments:d,entryPosition:i,entryStatus:e,entryStage:r,seedValue:h,eventId:F,ranking:o,drawId:n},!1,!1,!0))};if(![su,cu].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=Al({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};dm({...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;dm({...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(wi("participantId")).filter(Boolean);t?.forEach((t=>{const e=v(t);e?.forEach((t=>{s[t]&&(s[t].potentialMatchUps[l]=br({tournamentId:i?.tournamentId,matchUpId:l,eventId:m,drawId:f}))})),(p||d)&&tm({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,[dc]:{wins:r,losses:i},[lc]:{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(jc,t,n),c(`${jc}.${dc}`,r,i),c(`${jc}.${lc}`,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!==Vo;s&&(o+=1);const c=s?o:void 0;return br({...r,participationOrder:c,flightNumber:i})})).filter(Boolean);e.draws[n]&&(e.draws[n].finishingPositionRange=a,e.draws[n].structureParticipation=s)}}}if(p){const t=Ui(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(ii)));for(const a of n){const{typeChangeTimeAfterRecovery:n,timeAfterRecovery:o,scheduledDate:s,scheduledTime:c}=a,u=i[s],d=Zr(c);for(const i of u){if(i.matchUpId===a.matchUpId||[Mo,yo].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=Zr(i.scheduledTime),l=Math.abs(p-d),m=p>=d;if((t&&!isNaN(t)?l<=t:m&&Zr(i.scheduledTime)<Zr(s))&&(!u||!c)&&m){const t=[a.matchUpId,i.matchUpId].sort(cm).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))})),br({...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?.[Sa],V=B?.participant,j=pm({participants:L,participantFilters:n,tournamentRecord:c});if(e){const t=Ui(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?pa({template:t,source:r}):r)}}return{participantIdsWithConflicts:N,eventsPublishStatuses:R,derivedEventInfo:M,derivedDrawInfo:A,mappedMatchUps:C,participantMap:D,participants:V?j.map((t=>pa({source:t,template:V}))):j,...E,matchUps:O}}function fm({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 hm(t){const{provisionalPositioning:e,drawDefinition:n,stageSequence:r,structureId:i,stage:a}=t;if(!n)return{error:j};const{entryProfile:o}=Zc({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}=Vs({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=Vs({structureId:t.source.structureId,drawDefinition:n})?.structure;if(r?.stage===Vo){const n=t.source.roundNumber,i=t.target.roundNumber;let a=0;if(r.structureType===Qo){a=(r.structures?.length??0)*(t.source.finishingPositions?.length??0)}else{const t=Xp({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 gm({stage:t,drawDefinition:e}){const{entryProfile:n}=Zc({drawDefinition:e});return n?.[t]?.drawSize||0}function Im({stage:t,drawDefinition:e}){return Boolean(t===Go||Iu({stage:t,drawDefinition:e})&&gm({stage:t,drawDefinition:e}))}function Um({entryStatus:t=tu,drawDefinition:e,stageSequence:n,stage:r}){if(t===Xc)return function({stage:t,drawDefinition:e}){const{entryProfile:n}=Zc({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=gm({stage:i,drawDefinition:n}),{qualifiersCount:o}=hm({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}=Zc({drawDefinition:e});return n[t]?.wildcardsCount||0}({drawDefinition:e,stage:r}),o=Uu({entryStatus:uu,drawDefinition:e,stage:r}),s=o+Uu({entryStatus:tu,drawDefinition:e,stage:r}),c=i-s;return r!==Go&&s>=i?{error:ze}:t===uu?o<a?{...E}:{error:ze}:{positionsAvailable:c,...E}}function Sm(t){const{entryStatus:e=tu,entryStageSequence:n,entryStage:r=Bo,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!==cs&&!Im({stage:r,drawDefinition:a}))return Nr({result:{error:At},stack:l});const m=Um({stageSequence:n,stage:r,drawDefinition:a,entryStatus:e});if(!i&&!m.success)return{error:m.error};if(d&&!Er({extension:d}))return Nr({result:{error:Nn},info:"Invalid extension",context:{extension:d},stack:l});const f=t.participantId||s?.participantId;if(!f)return Nr({result:{error:Ae},stack:l});const h=e===ru&&fm({participantId:f,drawDefinition:a,entryStatus:e}),g=r===Go&&fm({participantId:f,drawDefinition:a,entryStage:r}),I=e!==ru&&r!==Go&&fm({drawDefinition:a,participantId:f});if(I||h||g)return Nr({context:{invalidEntry:I,invalidLuckyLoser:h,invalidVoluntaryConsolation:g},result:{error:Be},stack:l});const U=br({entryStageSequence:n,participantId:f,entryPosition:o,entryStatus:e,entryStage:r,extensions:u});return d&&Cr({element:U,extension:d}),c&&Cr({extension:{name:"roundEntry",value:c},element:U}),a.entries||(a.entries=[]),a.entries.push(U),Il({drawDefinition:a}),{...E}}function ym({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(lo);if(i.filter((t=>!p.includes(t))).length)return{error:bt};if(r){const u=function(t){const{entryStatus:e=tu,stage:n=Bo,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(!Im({stage:n,drawDefinition:a}))return{error:At};if(u&&!Er({extension:u}))return Nr({result:{error:Nn},info:"Invalid extension",context:{extension:u},stack:"addDrawEntries"});const d=Um({drawDefinition:a,stageSequence:s,entryStatus:e,stage:n});if(!i&&!d.success)return{error:d.error};const p=d.positionsAvailable??0;if(!i&&n!==Go&&p<o.length)return{error:Ve};const l=o.reduce(((t,r)=>{const i=e===ru&&fm({participantId:r,drawDefinition:a,entryStatus:e}),o=n===Go&&fm({entryStage:n,drawDefinition:a,participantId:r});return e!==ru&&n!==Go&&fm({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&&Cr({element:r,extension:u}),c&&Cr({extension:{name:Za,value:c},element:r}),a.entries||(a.entries=[]),a.entries.push(r)})),r&&(a.entries=Zl({entries:a.entries})),Il({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}=wp({event:d}),m=l?.flights.find((t=>t.drawId===u));return m?.drawEntries&&(i.forEach((t=>{const e=a===ru&&vm({participantId:t,entryStatus:a,flight:m}),n=s===Go&&vm({participantId:t,entryStage:s,flight:m});a!==ru&&s!==Go&&vm({flight:m,participantId:t})||e||n||m.drawEntries.push({participantId:t,entryStatus:a,entryStage:s})})),t&&(m.drawEntries=Zl({entries:m.drawEntries}))),{...E}}function vm({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 wm({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=>!Ii(t))))return Nr({result:{error:Te},stack:a});const o=(i.drawDefinitions??[]).flatMap((t=>Jl({drawDefinition:t}).assignedParticipantIds??[])),s=(n?.length&&i.entries?.filter((t=>t.entryStatus&&n.includes(t.entryStatus)))||[]).map(wi("participantId")).filter((t=>!o.includes(t))),c=(r&&i.entries?.filter((t=>t.entryStage&&t.entryStage===r))||[]).map(wi("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 Nr({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=Zl({entries:i.entries}));const{flightProfile:d}=wp({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 Tm={[ga]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}};function Pm(t){const{entryStatus:e=tu,autoEntryPositions:n=!0,enforceGender:r=!0,participantIds:i=[],entryStageSequence:a,policyDefinitions:o,entryStage:s=Bo,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 Nr({result:{error:Fe},stack:g});if(!h?.eventId)return{error:Pt};const I=Fc({tournamentRecord:c,event:h}).appliedPolicies??{},U=o?.[ga]??I?.[ga]??Tm[ga],S=!1!==(r??U?.participants?.enforceGender),y=[],v=[];if(l&&(!Array.isArray(l)||!l.every((t=>Er({extension:t}))))||m&&!Er({extension:m}))return Nr({context:br({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===dc&&t.participantType===Ks&&!Xl(e),r=h.eventType===lc&&t.participantType===Zs;return!(!n||h.gender&&S&&![Yp,Hp].includes(h.gender)&&h.gender!==t.person?.sex)||(!(!r||Xl(e))||(!(h.eventType!==lc||t.participantType!==Ks||!Xl(e))||(n&&h.gender&&S&&![Yp,Hp].includes(h.gender)&&h.gender!==t.person?.sex?(T.push({participantId:t.participantId,sex:t.person?.sex}),!1):h.eventType===Xs&&(t.participantType===Xs||Xl(e)&&t.participantType===Ks))))})).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=br({participantId:t,entryStatus:e,entryStage:s,extensions:l});m&&Cr({element:n,extension:m}),p&&Cr({extension:{name:Za,value:p},element:n}),a&&(n.entryStageSequence=a),y.push(n.participantId),h.entries?.push(n)}})),f&&!Xl(s)){const t=ym({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&&[pd,md].includes(h.eventType)){const t=(h.entries||[]).map((t=>t.participantId)),e=(h.entries||[]).filter((t=>Xl(t.entryStatus))).map((t=>t.participantId)),n=(c?.participants??[]).filter((e=>t.includes(e.participantId)&&e.participantType&&[Zs,Xs].includes(e.participantType))).map((t=>t.individualParticipantIds)).flat(1/0),r=e.filter((t=>n.includes(t)));r.length&&(v.push(...r),wm({participantIds:r,autoEntryPositions:!1,event:h}))}if(b.length!==i.length)return Nr({context:{mismatchedGender:T,gender:h.gender},result:{error:Pe},stack:g});n&&(h.entries=Zl({entries:h.entries||[]}));const R=y.length-v.length;return Nr({result:{...E,addedEntriesCount:R},stack:g,info:P})}const Dm="COMPETITOR",bm="OFFICIAL",Nm="OTHER",Rm={ADMINISTRATION:"ADMINISTRATION",CAPTAIN:"CAPTAIN",COACH:"COACH",COMPETITOR:Dm,MEDIA:"MEDIA",MEDICAL:"MEDICAL",OFFICIAL:bm,OTHER:Nm,SECURITY:"SECURITY"};function Mm({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:n,tournamentRecord:r,suppressErrors:i}){const a="removeIndividualParticipantIds";if(!r)return Nr({result:{error:_},stack:a});if(!n||!e)return Nr({result:{error:ae},stack:a});const o=(r.participants??[]).find((t=>t.participantId===n));if(!o)return Nr({result:{error:Ee},stack:a});if(![Xs,Js].includes(o.participantType))return Nr({result:{participantType:o.participantType,error:be},stack:a});const s=Am({individualParticipantIds:e,groupingParticipant:o,tournamentRecord:r,suppressErrors:i}),{removed:c,error:u}=s;if(u)return Nr({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)));Pm({participantIds:n,entryStatus:su,tournamentRecord:r,event:t})}}return c&&cr({topic:Qd,payload:{tournamentId:r.tournamentId,participants:[o]}}),{...E,...s}}function Am({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}=mm({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||Tl({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}=Fr({element:i,name:Wa}),a=t?.value[e.participantId];t&&a&&(t.value[e.participantId]=a.filter((t=>t.participantId!==r)),Cr({element:i,extension:t}),gl({drawDefinition:i}));const o=rl({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)),hl({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 Em({participantRole:t=Dm,individualParticipantIds:e=[],groupingTypes:n=[Ys,Js],tournamentRecord:r}){if(!r)return{error:_};const i=r.participants??[],{participants:a,mappedMatchUps:o}=mm({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}=Am({groupingParticipant:t,individualParticipantIds:e,tournamentRecord:r,mappedMatchUps:o,participants:a});n&&s++})),s?E:{error:Oe}}function Cm(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===ld)).map((t=>t?.drawDefinitions?.map((({drawId:t})=>t)))).flat(1/0),o=mm({participantFilters:{participantIds:r},tournamentRecord:n,withDraws:!0}).participants??[],s=a?.length&&P((El({matchUpFilters:{drawIds:a,matchUpTypes:[lc]},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=wm({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===Zs&&t.individualParticipantIds.some((t=>r.includes(t)));if(!n&&t.participantType===ld&&t.individualParticipantIds.some((t=>r.includes(t)))&&(t.individualParticipantIds=t.individualParticipantIds.filter((t=>!r.includes(t)))),n&&e&&[Zs,Xs].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(Em({individualParticipantIds:r,tournamentRecord:n}),e)for(const t of n.events||[]){Pm({participantIds:u[t.eventId].map((t=>d[t]||[])).flat(),entryStatus:su,tournamentRecord:n,event:t})}return p&&cr({payload:{participantIds:r,tournamentId:n.tournamentId},topic:Wd}),p?{...E,participantsRemovedCount:p}:{error:ye}}function Om({selected:t=!0,drawDefinition:e,entryStatuses:n,drawId:r,event:i,stage:a}){let o=i.entries??[];if(r){const{flightProfile:t}=wp({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&&fu.includes(e.entryStatus))));return{entries:o,stageEntries:s}}function Fm({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:i,stage:a,event:o}){const s="destroyGroupEntry";if(!e)return{error:_};if(!r)return Nr({result:{error:Ae},stack:s});if(!o)return{error:Tt};if(!o.eventType||![pd,md].includes(o.eventType))return Nr({result:{error:wt},stack:s});const c=e.participants??[],u=c.find((t=>t.participantId===r));if(!u)return Nr({result:{error:Ee},stack:s});if(!u.participantType||![Zs,Ys].includes(u.participantType)||u.participantType===Ys&&o.eventType!==md||u.participantType===Zs&&o.eventType!==pd)return{error:be};const d=(o.entries??[]).find((t=>t.participantId===r));if(!d)return{error:Ge};const{stageEntries:p}=Om({selected:!1,drawDefinition:n,drawId:i,event:o,stage:a}),l=p.map(lo),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=wm({participantIds:[r],event:o});if(g.error)return g;if(f?.length&&(g=Pm({participantIds:f,entryStatus:su,entryStage:d.entryStage,tournamentRecord:e,drawDefinition:n,drawId:i,event:o}),g.error))return g;if(t){Cm({participantIds:[r],tournamentRecord:e}).success&&(h=!0)}return{...E,participantRemoved:h}}function km({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:i,event:a}){return Fm({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:i,event:a})}function xm(t){const{tournamentRecord:e,replaceWithBye:n,drawDefinition:r,destroyPair:i,entryStatus:a,matchUpsMap:o,drawId:s}=t,c="removeDrawPositionAssignment",u=zl(t);if(u.error)return Nr({result:u,stack:c});const{participantId:d}=u,{drawPosition:p,event:l,structureId:m}=t;if([Xc,du].includes(a)&&d){const{tournamentRecord:e}=t,{participant:n}=ac({tournamentRecord:e,participantId:d}),{participantType:o,individualParticipantIds:u}=n??{};if(i&&o===Zs){const t=km({tournamentRecord:e,drawDefinition:r,participantId:d,event:l});if(t.error)return Nr({result:t,stack:c});u&&Ql({participantIds:u,tournamentRecord:e,drawDefinition:r,entryStatus:a,drawId:s,event:l})}else Ql({participantIds:[d],tournamentRecord:e,drawDefinition:r,entryStatus:a,drawId:s,event:l})}if(n){const t=jl({tournamentRecord:e,drawDefinition:r,drawPosition:p,structureId:m,matchUpsMap:o,event:l});if(t.error)return Nr({result:t,stack:c})}const{structure:f}=Vs({drawDefinition:r,structureId:m});yl({structure:f,drawPositions:[p]});return vl({drawDefinition:r,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:n,drawPosition:p,entryStatus:a,structureId:m}}),u}function _m(t){return Ii(t)?t.split(" ").map((t=>t.split("").map(((t,e)=>e?t.toLowerCase():t.toUpperCase())).join(""))).join(" "):t}function Lm(t){return Ii(t)?_m(t.replace(/_/g," ")):t}const Bm=({finishingPosition:t=ks,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??Ld(),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 Vm({structureName:t=Lm(Go),structureAbbreviation:e,drawDefinition:n,matchUpType:r,structureId:i}){if(!n)return{error:j};const a=Bm({stage:Go,structureAbbreviation:e,structureName:t,matchUps:[],structureId:i,matchUpType:r});return n.structures||(n.structures=[]),n.structures.push(a),Il({drawDefinition:n,structureIds:[a.structureId]}),{...E}}function jm({tournamentRecord:t,drawDefinition:e,stage:n=Bo,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}=qs({drawDefinition:e,structureId:r,structure:i});return{positionAssignments:o??[],structureId:i?.structureId,error:a}}function Gm({schedulingProfile:t,venueIds:e,eventIds:n,drawIds:r}){const i=[],a=t?.map((t=>{const a=ti(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 qm({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}=js({drawDefinition:t});(i||[]).forEach((t=>{const i=t.structureId,{matchUps:o}=Xp({structure:t}),{roundMatchUps:s}=Ac({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!!Gr(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 $m({convertExtensions:t,ignoreDisabled:e,venue:n,court:r}){const i={...mi(r,t,!0),venueId:n.venueId},{extension:a}=Fr({name:La,element:r});if(e&&a){const t=Ui(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 Wm({dates:t=[],extension:e}){if(!e)return!1;if("boolean"==typeof e.value&&e.value)return!0;if(!t.length)return!1;const n=Ui(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 Hm(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}=Fr({name:La,element:t});if(e?.value)continue}o.includes(t.venueId)||(u.push(mi(t,e,!0)),o.push(t.venueId));for(const r of t.courts??[])if(!s.includes(r.courtId)){if(n){const{extension:t}=Fr({name:La,element:r});if(Wm({extension:t,dates:i}))continue}const{inContextCourt:a}=$m({convertExtensions:e,ignoreDisabled:n,venue:t,court:r});c.push(a),s.push(r.courtId)}}})),{courts:c,venues:u,...E}}function zm({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=mi(e.venues??[],t).filter((t=>{if(!n)return t;const{extension:e}=Fr({name:La,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}=Fr({name:La,element:t});return Wm({extension:e,dates:r})})).filter(Boolean).map((e=>{const{inContextCourt:r}=$m({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 Ym(t){const e=na(t,[{[Pi]:!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 Km({tournamentRecords:t,tournamentRecord:e}){if("object"!=typeof t||!Object.keys(t).length)return{error:x};const{extension:n}=Fr({element:e,name:to,tournamentRecords:t,discover:!0});let r=n?.value||[];if(r.length){const{venueIds:n}=zm({requireCourts:!0,tournamentRecords:t}),{eventIds:i,drawIds:a}=Ym({tournamentRecords:t}),{updatedSchedulingProfile:o,modifications:s,issues:c}=Gm({schedulingProfile:r,venueIds:n,eventIds:i,drawIds:a});if(s){r=o;const n=Jm({tournamentRecords:t,tournamentRecord:e,schedulingProfile:r});return n.error?n:{schedulingProfile:r,modifications:s,issues:c}}}return{schedulingProfile:r,modifications:0}}function Jm({tournamentRecords:t,tournamentRecord:e,schedulingProfile:n}){const r=qm({tournamentRecords:t,schedulingProfile:n});if(r.error)return r;if(!n)return Ar({element:e,name:to,tournamentRecords:t,discover:!0});return Cr({tournamentRecords:t,discover:!0,extension:{name:to,value:n}})}function Zm(t){const{tournamentRecord:e}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!t.schedulingProfile){const{modifications:t,issues:r}=Km({tournamentRecords:n,tournamentRecord:e});return{success:!t,modifications:t,issues:r}}const{venueIds:r}=zm({tournamentRecords:n}),{eventIds:i,drawIds:a}=Ym({tournamentRecords:n}),{updatedSchedulingProfile:o,modifications:s,issues:c}=Gm({schedulingProfile:t.schedulingProfile,venueIds:r,eventIds:i,drawIds:a});return s?{...Jm({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:Rr};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&&oc({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 Qm({creationTime:t=!0,removePriorValues:e,tournamentRecord:n,duplicateValues:r,participantId:i,timeItem:a}){if(!n)return{error:_};if(!i)return{error:Ae};const o=ac({tournamentRecord:n,participantId:i});return o.error?o:Xm({element:o.participant,removePriorValues:e,duplicateValues:r,creationTime:t,timeItem:a})}function tf(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 ef(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 nf({removePriorValues:t=!0,status:e=td,statusObject:n,event:r}){if(!Ui(n))return{error:Nn};const i=rm({event:r,status:e}),a=`${Qu}.${ed}`;return ef({timeItem:{itemValue:{[e]:{...i,...n}},itemType:a},removePriorValues:t,event:r})}function rf({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:mi(e,!1,!0)}}function af({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[rs,ns,es,Zo].includes(t.target.feedProfile)?(r?.targets.push(n),s?.sources.push(e)):t.target.feedProfile===ts&&(s?.drawSources.push(e),r?.drawTargets.push(n)),o[n]=o[n]||t.target.feedProfile===ts,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===Vo){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!==Go&&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 of(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}=af({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}=Vs({drawDefinition:s,structureId:t}),{seedAssignments:n}=yu({drawDefinition:s,structure:e});return e?.stage===Bo&&1===e.stageSequence&&(f=n),e?.stage===Vo&&1===e.stageSequence&&(h=n),e})).sort(((t,e)=>Ls(t,e,d))).map((t=>{if(!t)return;const n=t?.structureId;let d=[];t.stage&&[Bo,jo,qo].includes(t.stage)&&(d=f),t?.stage===Vo&&(d=h);const{matchUps:g,roundMatchUps:S,roundProfile:w}=Xp({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}=qs({structure:t}),P=T?.filter(wi(Mi)).map((t=>{v=!0;const{drawPosition:e,participantId:n}=t,{extension:r}=Fr({element:t,name:no});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=[Uo,Io,yo,bo,Mo,To,vo,wo].includes(e.matchUpStatus);return t||n||!!e.winningSide||!!e.score?.scoreStringSide1}),!1);const b=g.reduce(((t,e)=>t&&[go,Uo,bo,Mo,yo,fo].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:mi(w,!1,!0),drawInfo:u?m:mi(m,!1,!0),...E}}function sf(t){const{includePositionAssignments:e,tournamentRecord:n,participantsProfile:r,policyDefinitions:i,usePublishState:a,status:o=td,sortConfig:s,event:c}=t,u=mi(n,!1,!0),d=mi(c,!1,!0);if(!u)return{error:_};if(!d)return{error:Tt};const{eventId:l}=d,{tournamentId:m,endDate:f}=u,h=rm({event:d,status:o}),{publishState:g}=am({event:d}),{participants:I}=mm({withGroupings:!0,withEvents:!1,withDraws:!1,...r,tournamentRecord:u}),U=(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}))(of({context:{eventId:l,tournamentId:m,endDate:f},includePositionAssignments:e,tournamentParticipants:I,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:S}=rf({tournamentRecord:u}),y={tournamentInfo:S,venuesData:(u.venues||[]).map((t=>(({venueData:t})=>({...t}))(Up({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:U};return y.eventInfo.publishState=g,y.eventInfo.publish=h,{...E,eventData:y}}function cf(t){const{includePositionAssignments:e,removePriorValues:n,tournamentRecord:r,status:i=td,event:a,drawIdsToRemove:o,drawIdsToAdd:s}=t;if(!r)return{error:_};if(!a)return{error:Tt};const{appliedPolicies:c}=Fc({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 Nr({result:{error:q},context:{invalidDrawIds:f}});const h=rm({event:a,status:i}),g=Object.keys(h?.drawDetails||{}).filter((t=>d.includes(t))).reduce(((t,e)=>(t[e]=h.drawDetails[e],t)),{});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 Nr({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)}nf({statusObject:{drawDetails:g},removePriorValues:n,status:i,event:a});const{eventData:I}=sf({includePositionAssignments:e,usePublishState:!0,tournamentRecord:r,policyDefinitions:u,event:a});return cr({payload:{eventData:I,tournamentId:r.tournamentId},topic:ap}),{...E,eventData:I}}const uf="deleteDrawDefinitions",df="autoSchedulingAudit",pf="deleteEvents",lf={AUTO_SCHEDULING_AUDIT:df,DELETE_EVENTS:pf,DELETE_DRAW_DEFINITIONS:uf};function mf(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}=Fc({tournamentRecord:a,event:r}),d={...u,...t.policyDefinitions},p=Array.isArray(n)?n[0]:void 0;if(!r){const t=Tp({tournamentRecord:a,eventId:s,drawId:p});if(t.error)return t;r=t.event}const l=[],m=[],f=[];if(!r?.drawDefinitions)return Nr({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 Nr({info:"nothing to do; no matching drawIds in event.",result:{...E},stack:e});const g=mi(wp({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?.[Ta]?.allowDeletionWithScoresPresent?.drawDefinitions,S=rm({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=rl({event:r,drawDefinition:t})?.matchUps??[];if(e.some((({score:t})=>Tl({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=>fu.includes(t.entryStatus)))),v.includes(n)&&(v=v.filter((t=>t!==n)),y=!0);const d=js({stageSequence:1,drawDefinition:t,stage:Bo})?.structures?.[0],p=d?jm({structureId:d.structureId,tournamentRecord:a,drawDefinition:t}):void 0,h=p?.positionAssignments?.map(I),S=js({stage:Vo,drawDefinition:t})?.structures,T=S?.length?S.map((e=>{const n=e.stageSequence,r=jm({structureId:e.structureId,tournamentRecord:a,drawDefinition:t}),i=r?.positionAssignments.map(I);return{positionAssignments:i,stageSequence:n}})):void 0,P={action:uf,payload:{drawDefinitions:[t],eventId:s??r?.eventId,auditData:o}};f.push(P),l.push(br({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 Nr({context:{drawIdsWithScoresPresent:w},result:{error:qn},stack:e});if(r.drawDefinitions=T,g){Ea({event:r,extension:{name:qa,value:g}})}if(Zm({tournamentRecord:a}),y){const t={};for(const e of v)t[e]=S.drawDetails?.[e]??{published:!0};const e=nf({statusObject:{drawDetails:t},event:r});if(e.error)return{error:e.error}}if(f.length&&cr({topic:$d,payload:f}),m.length&&fl({tournamentId:a?.tournamentId,matchUpIds:m}),n.forEach((t=>{!function({tournamentId:t,eventId:e,drawId:n}){cr({payload:{drawId:n,tournamentId:t,eventId:e},topic:zd,key:n}),pr({key:n})}({drawId:t})})),function({event:t,deletedDrawsDetail:e,auditData:n}){const{extension:r}=Fr({name:ja,element:t}),i={...n,deletedDrawsDetail:e},a={name:ja,value:Array.isArray(r?.value)?r?.value.concat(i):[i]};Cr({element:t,extension:a})}({event:r,deletedDrawsDetail:l,auditData:o}),i&&y){const t=cf({drawIdsToRemove:n,policyDefinitions:d,tournamentRecord:a,event:r});if(t.error)return{...E,info:t.error}}return{...E}}function ff({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find((t=>t.matchUpId===e))}}function hf({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=[]}=js({drawDefinition:i});r&&!n&&(n=qc({contextProfile:r,drawDefinition:i}));for(const p of d){const{matchUps:d}=Xp({tournamentParticipants:t,afterRecoveryTimes:e,contextContent:n,drawDefinition:i,contextProfile:r,matchUpsMap:a,inContext:s,structure:p,context:c,event:u}),{matchUp:l}=ff({matchUps:d,matchUpId:o});if(l)return{matchUp:l,structure:p}}return{error:Wt}}function gf(t){let{sourceMatchUp:e}=t;const{targetMatchUp:n,structure:r,matchUpsMap:i,drawPosition:a}=t,o=n.roundNumber>1&&n.roundNumber-1,s=Hc({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:[wo,vo].includes(p)}}function If({structureId:t,matchUpsMap:e,matchUp:n}){const r=n?.roundPosition,i=r+(r%2?1:-1);return{pairedPreviousMatchUp:Hc({matchUpsMap:e,structureId:t}).find((({roundNumber:t,roundPosition:e})=>t===n?.roundNumber&&e===i))}}function Uf({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:n,matchUpsMap:r,matchUp:i}){const a=t.find((t=>t.matchUpId===n)),{pairedPreviousMatchUp:o}=If({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=Ii(t)||!isNaN(t)?{code:t}:t;return n.sideNumber===s?{...n,previousMatchUpStatus:e}:n}))}}function Sf({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 yf({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}=Fr({element:i,name:Wa}),d=mi((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)}hl({tournamentId:r?.tournamentId,context:"updateSidLineUp",eventId:o?.eventId,drawDefinition:i,matchUp:a})}function vf({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=Wc({drawDefinition:a})),t||(t=el({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}=qs({drawDefinition:a,structure:f}),v=y?.filter((t=>S.includes(t.drawPosition))),w=v?.find((({bye:t})=>t)),T=h?.matchUpStatus&&[Mo,yo].includes(h.matchUpStatus)&&S.filter(Boolean).length<2;if(o=w&&go||o||T&&h.matchUpStatus||h?.matchUpStatus&&[wo,vo].includes(h.matchUpStatus)&&h.matchUpStatus||Ro,h&&I){t=el({inContext:!0,drawDefinition:a,matchUpsMap:c}).matchUps??[];const e=T&&Sf({inContextDrawMatchUps:t,drawPosition:s,matchUpId:u})||void 0;h?.matchUpStatusCodes&&Uf({inContextDrawMatchUps:t,sourceMatchUpStatus:n,sourceMatchUpId:i,matchUpsMap:c,matchUp:h}),Object.assign(h,{drawPositions:S,winningSide:e,matchUpStatus:o}),hl({tournamentId:r?.tournamentId,eventId:l?.eventId,context:p,drawDefinition:a,matchUp:h})}const P=Nc({inContextDrawMatchUps:t,inContextMatchUp:l,drawDefinition:a,matchUpId:u}),{targetMatchUps:{winnerMatchUp:D,loserMatchUp:N,loserTargetDrawPosition:R},targetLinks:{loserTargetLink:M}}=P,A=Hc({structureId:f.structureId,matchUpsMap:c});if(U&&w){if(D)if([go,wo,vo].includes(o)){const e=vf({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}=gf({targetMatchUp:h,drawPosition:s,matchUpsMap:c,structure:f});if(e){const e=vf({matchUpId:D.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:a,drawPosition:s,matchUpsMap:c});if(e.error)return e}}if(h?.matchUpType===fc){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&&yf({inContextTargetMatchUp:e,drawPositionSideIndex:n,teamParticipantId:i,tournamentRecord:r,drawDefinition:a,matchUp:h})}if(M?.linkCondition===ss&&2===S.filter(Boolean).length&&!w){if(A.filter((({drawPositions:t,roundNumber:e})=>1===e&&b(t,S))).every((({matchUpStatus:t})=>[Uo,bo].includes(t)))&&N){const{structureId:t}=N,e=jl({drawPosition:R,tournamentRecord:r,drawDefinition:a,structureId:t,matchUpsMap:c,event:d});if(e.error)return e}}return U?{...E}:Nr({result:{error:z},context:{drawPosition:s},stack:p})}function wf({drawPositions:t}){const e=[].concat(...t.map((e=>t.filter((t=>t!==e)).map((t=>[e,t]))))),n=m(e.map(Tf)).map((t=>t.split("|").map((t=>+t))));return{groupMatchUps:e,uniqueMatchUpGroupings:n}}function Tf(t){return[...t].sort(e).join("|")}function Pf({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=>Tf(t.map((t=>t+e)))))))}const Df={getRoundRobinGroupMatchUps:wf,determineRoundNumber:function({rounds:t,hash:e}){return t.reduce(((t,n,r)=>n.includes(e)?r+1:t),void 0)},drawPositionsHash:Tf,groupRounds:Pf};function bf(t){const{groupNameBase:e="Group",playoffAttributes:n,stageSequence:r=1,structureOptions:i,appliedPolicies:a,seedingProfile:o,stage:s=Bo,matchUpType:c,roundTarget:u,structureId:d,groupNames:p,drawSize:l,idPrefix:m,isMock:f,uuids:h}=t,g=t.structureName??n?.[0]?.name??Lm(Bo),{groupCount:I,groupSize:U}=function({appliedPolicies:t,structureOptions:e,drawSize:n}){let r=e?.groupSize;const i=e?.groupSizeLimit||8,{validGroupSizes:a}=Nf({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=Fs;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}=wf({drawPositions:c}),d=Pf({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(Tf(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()||Ld()}({structureOrder:t,drawPositions:n,roundNumber:s,idPrefix:i,uuids:o}),d={matchUpStatus:s?Ro:go,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 Bm({structureId:h?.pop(),structureType:Xo,finishingPosition:S,structureOrder:t,structureName:r,matchUps:n})})),T=Bm({structureId:d??h?.pop(),structureType:Qo,finishingPosition:S,seedingProfile:o,structureName:g,stageSequence:r,structures:v,stage:s});return u&&Cr({extension:{name:Za,value:u},element:T}),{structures:[T],maxRoundNumber:y,groupCount:I,links:[],groupSize:U,...E}}function Nf({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 Rf(t){const{roundRobinGroupsCount:e,participantsCount:n,cluster:r}=t;if(!p(n))return{seedBlocks:void 0,...Nr({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 Mf({roundRobinGroupsCount:t,drawSize:e}){const n="getSeedGroups";if(!p(e))return{seedGroups:void 0,...Nr({result:{error:Nn},context:{drawSize:e},stack:n})};if(t){if(!p(t))return{seedGroups:void 0,...Nr({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}=Rf({participantsCount:e,roundRobinGroupsCount:t});let r=0;return{seedGroups:(n||[]).map((t=>(t||[]).map((()=>(r+=1,r)))))}}}function Af(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 Ef({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&&[Jo,Zo].includes(t)&&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 Cf({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}=Xp({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:o}),{seedAssignments:d}=yu({provisionalPositioning:t,returnAllProxies:e,drawDefinition:i,structure:o}),{positionAssignments:p}=$s({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===Qo,D=!P&&h?.length,b=!P&&y===Vo&&T,R=S.flat(1/0),M=D?R?.length:0,A=a?l:m,E=Vp({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=xf(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}=Of({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=qs({structure:e})?.positionAssignments,o=xf(t),s=a?.length??0,{seedGroups:c}=Mf({roundRobinGroupsCount:i,drawSize:s});return Of({drawPositionBlocks:r.map((t=>qs({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}=Rf({cluster:xf(i)===Jo,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 Of({drawPositionBlocks:t,positioning:e,seedGroups:n,nonRandom:r}){const i=[],{divisionGroupings:a}=Ef({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!==Zo?d=r?d:f(d):s%2&&d.reverse();const p=d.find((t=>!o.includes(t)));p&&(o.push(p),i.push({drawPositions:[p],seedNumbers:[n]}))}))})),{validSeedBlocks:i}}function Ff({appliedPolicies:t,drawDefinition:e,seedBlockInfo:n,drawPosition:r,structureId:i,seedNumber:a}){const{structure:o}=Vs({drawDefinition:e,structureId:i});t||(t=Fc({drawDefinition:e}).appliedPolicies);let s=n?.validSeedBlocks;if(!s&&o&&(s=Cf({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 kf(t){const{provisionalPositioning:e,drawDefinition:n,seedingProfile:r,seedBlockInfo:i,structureId:a,randomize:o}=t,{structure:s}=Vs({drawDefinition:n,structureId:a}),{seedAssignments:c}=yu({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,drawDefinition:n,structure:s}),{positionAssignments:u}=$s({structure:s}),d=u?.filter((t=>t.participantId??t.bye??t.qualifier)),p=d?.map((t=>t.drawPosition)).filter(Boolean),{appliedPolicies:l}=Fc({drawDefinition:n}),m=(i?.validSeedBlocks||s&&Cf({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=>Af(t.seedValue)))),i=n.filter((t=>Af(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 xf(t){return"string"==typeof t?t:"object"==typeof t?t.positioning:void 0}function _f({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}=Vs({drawDefinition:n,structureId:o}),{positionAssignments:m}=$s({structure:l}),f=yu({provisionalPositioning:t,drawDefinition:n,structure:l}).seedAssignments,h=f.map((t=>t.seedNumber)),g=fm({drawDefinition:n,participantId:i});if(i&&!g)return Nr({result:{error:Te},context:{participantId:i},stack:p});const I=d?wp({event:d}).flightProfile?.flights?.length:0,U=I&&I>1,S=m?.find((t=>t.participantId===i)),y=S?.drawPosition;if(y){if(!Ff({drawPosition:y,drawDefinition:n,seedBlockInfo:a,structureId:o,seedNumber:s}))return Nr({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?(Ul({tournamentId:e?.tournamentId,drawDefinition:n,structure:l,eventId:u}),{...E}):Nr({result:{error:mt},stack:p})}function Lf({inContextDrawMatchUps:t,drawDefinition:e,assignments:n,matchUpsMap:r,structure:i}){const a=wl({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 Bf({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}=zc({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 Vf(t){return`${t} must be an array`}function jf({lineUp:t,tieFormat:e}){const n=[];if(!Array.isArray(t))return n.push(Vf("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(Vf("collectionAssignments")),!1):(n.push("Missing participantId"),!1)})),i=m(t.map(lo)).length===t.length;i||n.push("Duplicated participantId(s)");return{valid:r&&i,errors:n,error:n.length?Nn:void 0}}function Gf({drawDefinition:t,participantId:e,tieFormat:n,lineUp:r}){if("object"!=typeof t)return{error:j};if("string"!=typeof e)return{error:Ae};const i=jf({lineUp:r,tieFormat:n});if(!i.valid)return i;const{extension:a}=Fr({element:t,name:Wa}),o=a?.value||{};o[e]=Bf({lineUp:r});return Cr({element:t,extension:{name:Wa,value:o}}),gl({drawDefinition:t}),{...E}}function qf({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}=Lf({inContextDrawMatchUps:t,matchUpsMap:i,assignments:a,structure:o});for(const t of d)t.matchUpType===mc&&(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&&Gf({drawDefinition:r,participantId:n,lineUp:[],tieFormat:e})}hl({tournamentId:n?.tournamentId,context:"resetLineUps",eventId:s?.eventId,drawDefinition:r,matchUp:o})}}}));return{...E}}function $f({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 Nr({result:{error:Ae},stack:m});d=d??Wc({drawDefinition:a}),e||({matchUps:e}=el({inContext:!0,drawDefinition:a,matchUpsMap:d}));const f=Vs({drawDefinition:a,structureId:p});if(f.error)return Nr({result:f,stack:m});const{structure:h}=f;if(!h)return{error:Ut};if(jp({drawDefinition:a,structure:h}))return Nr({result:{error:Yt},stack:m});const{seedAssignments:g}=yu({provisionalPositioning:t,drawDefinition:a,structure:h}),I=g?.find((t=>t.participantId===s)),U=I?.seedNumber,{appliedPolicies:S}=Fc({tournamentRecord:i,drawDefinition:a,structure:h,event:l});if(U){if(!Ff({seedNumber:U,appliedPolicies:S,drawDefinition:a,seedBlockInfo:c,drawPosition:u,structureId:p}))return Nr({result:{error:H},context:{drawPosition:u},stack:m})}const y=$s({structure:h}).positionAssignments||[],v=y?.find((t=>t.drawPosition===u));if(!v)return Nr({result:{error:Q},context:{drawPosition:u},stack:m});const w=y?.map(lo).includes(s);if(w)return Nr({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=zl({inContextDrawMatchUps:e,tournamentRecord:i,drawDefinition:a,drawPosition:u,structureId:p,matchUpsMap:d,event:l});if(t.error)return Nr({result:t,stack:m})}if(T&&v.participantId!==s){const{activeDrawPositions:t}=kl({drawDefinition:a,structureId:p});if(t.includes(u))return Nr({result:{error:X},stack:m});qf({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&&[jo,qo].includes(h.stage)){const e=h.stage===Vo?Vo:Bo,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;_f({eventId:l?.eventId,provisionalPositioning:t,tournamentRecord:i,drawDefinition:a,seedingProfile:o,participantId:e,seedNumber:n,seedValue:s,structureId:p,event:l})}}if(h.structureType!==Qo)!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}=Xp({provisionalPositioning:t,matchUpFilters:u,drawDefinition:i,matchUpsMap:o,structure:s,event:c}),{roundMatchUps:p}=Ac({matchUps:d}),{initialRoundNumber:l}=xl({drawPosition:a,matchUps:d}),m=l&&p?.[l].find((t=>t.drawPositions?.includes(a)));if(m){const t=vf({matchUpId:m.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:r,drawDefinition:i,drawPosition:a,matchUpsMap:o});if(t.error)return Nr({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{Hl({positionAssignments:y,tournamentRecord:i,drawDefinition:a,matchUpsMap:d,structure:h});const{drawPositions:t,matchUps:n,targetMatchUps:r}=Lf({assignments:[v],inContextDrawMatchUps:e,drawDefinition:a,matchUpsMap:d,structure:h});if(t&&1===n?.length&&n[0].matchUpType===fc){const e=(r?.[0].sides??[]).reduce(((e,n,r)=>t?.includes(n.drawPosition)?r:e),void 0);yf({inContextTargetMatchUp:r[0],teamParticipantId:s,matchUp:n[0],drawPositionSideIndex:e,tournamentRecord:i,drawDefinition:a})}}return Sl({tournamentId:i?.tournamentId,drawDefinition:a,structure:h,event:l}),{positionAssignments:y,...E}}function Wf(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=Wc({drawDefinition:a}),Object.assign(t,{matchUpsMap:l})),p||(({matchUps:p}=el({inContext:!0,drawDefinition:a,matchUpsMap:l})),Object.assign(t,{inContextDrawMatchUps:p}));const{positionAssignments:m}=qs({drawDefinition:a,structureId:c}),f=m?.find((t=>t.drawPosition===s));if(f?.participantId){const t=f.participantId,e=$f({inContextDrawMatchUps:p,tournamentRecord:i,drawDefinition:a,participantId:o,drawPosition:s,structureId:c,matchUpsMap:l,event:u});return e.success?U({removedParticipantId:t}):Nr({result:e,stack:d})}const h=zl({inContextDrawMatchUps:p,tournamentRecord:i,drawDefinition:a,drawPosition:s,structureId:c,matchUpsMap:l,event:u});if(h.error)return Nr({result:h,stack:d});const g=h.participantId,I=$f({inContextDrawMatchUps:p,isQualifierPosition:n,tournamentRecord:i,drawDefinition:a,participantId:o,drawPosition:s,structureId:c,matchUpsMap:l,event:u});return I.success?U({removedParticipantId:g}):Nr({result:I,stack:d});function U({removedParticipantId:t}){const{structure:n}=Vs({drawDefinition:a,structureId:c});yl({drawPositions:[s],structure:n});return vl({drawDefinition:a,positionAction:{[e]:o,name:r,drawPosition:s,structureId:c}}),Nr({context:{removedParticipantId:t},result:{...E},stack:d})}}function Hf(t){Object.assign(t,{inContext:!0});const{matchUp:e,error:n}=zf(t);return{matchUp:mi(e,!0,!0),error:n}}function zf({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=(El({tournamentRecord:n,nextMatchUps:o}).matchUps??[]).find((t=>t.matchUpId===s));if(!t)return{error:Wt};({eventId:u,drawId:d}=t),({event:p,drawDefinition:a}=Tp({tournamentRecord:n,eventId:u,drawId:d}))}if(!a)return{error:q};i&&!r&&(r=qc({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=[]}=wc({participantsProfile:t,tournamentRecord:n,contextProfile:i,inContext:c});if(o){const t=(rl({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}=hf({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 Yf(t,e){if(!Ui(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=Kf({params:t,param:r,attr:a,error:i});if(e?.error)return e;n[r]=e}return n}function Kf({params:t,param:e,attr:n,error:r}){if(e===_i&&Ui(t.drawDefinition)&&Ii(t.structureId)){const e=(t.drawDefinition.structures??[]).find((({structureId:e})=>e===t.structureId));return!e.length&&r?{error:r}:{structure:e}}if(e===qi){const e=zf({...t,...n});return e.error&&r?{...e,error:r}:e}return{error:On,info:{param:e}}}function Jf({removePriorValues:t,tournamentRecord:e,duplicateValues:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:o,event:s}){const{matchUp:c}=hf({drawDefinition:r,event:s,matchUpId:a});if(!c)return{error:Wt};const u=Xm({removePriorValues:t,element:c,duplicateValues:n,timeItem:o});return i||hl({tournamentId:e?.tournamentId,eventId:s?.eventId,context:"addTimeItem",drawDefinition:r,matchUp:c}),u}function Zf(t){const e=na(t,[{[bi]:!0},{[Ni]:!0},{[Mi]:!0},{[ki]:!0}]);if(e.error)return e;const n=Yf(t,[{[zi]:qi,attr:{[xi]:!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&&xo.includes(c)||c&&ko.includes(c)||Tl({score:u}))return{error:dt};const d=rd({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=Ru({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=>{Jf({drawDefinition:i,matchUpId:o,timeItem:{itemType:Au,itemValue:t}})}));return Jf({tournamentRecord:r,drawDefinition:i,matchUpId:o,timeItem:{itemValue:a,itemType:Au}})}function Xf(t){const e=na(t,[{[bi]:!0},{[Ni]:!0},{[Mi]:!0},{[ki]:!0}]);if(e[Wi])return e;const n=Yf(t,[{[zi]:qi,attr:{[xi]:!0}}]);if(n[Wi])return n;const{tournamentRecord:r,drawDefinition:i,participantId:a,matchUpId:o}=t,s=rd({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{[Wi]:Te};return Jf({tournamentRecord:r,drawDefinition:i,matchUpId:o,timeItem:{itemValue:a,itemType:Mu}})}function Qf(t){const e=na(t,[{[Mi]:!0,[Ni]:!0,[ki]:!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=Yf(t,[{[zi]:qi,[Wi]:Wt}]),c=s.matchUp?.matchUp;if(!c)return{error:Wt};const{checkedInParticipantIds:u=[]}=rd({matchUp:c});return i&&u.includes(i)?Zf({tournamentRecord:r,drawDefinition:o,participantId:i,matchUpId:a,matchUp:c}):Xf({tournamentRecord:r,drawDefinition:o,participantId:i,matchUpId:a,matchUp:c})}function th({tournamentRecord:t,drawDefinition:e,tieMatchUpId:n,event:r}){if(!t)return{error:_};if(!e)return{error:at};if(!r)return{error:Pt};const i=Wc({drawDefinition:e}),{matchUp:a}=hf({matchUpId:n,drawDefinition:e,matchUpsMap:i});if(!a)return{error:Wt};const{matchUp:o,structure:s}=hf({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&&![dc,lc].includes(l))return{error:Yt};const{positionAssignments:m}=qs({structure:s}),f=m?.filter((t=>u?.includes(t.drawPosition))),{matchUp:h}=hf({matchUpId:p,drawDefinition:e,matchUpsMap:i}),g=[...h?.sides?.map(wi("participantId"))??[],...f?.map(wi("participantId"))??[]],{participants:I}=mm({tournamentRecord:t,participantFilters:{participantTypes:[Xs],participantIds:g}}),{matchUp:U}=hf({matchUpId:p,inContext:!0,drawDefinition:e,matchUpsMap:i}),S=Np({matchUp:h,drawDefinition:e,structure:s,event:r})?.tieFormat;return{inContextDualMatchUp:U,inContextTieMatchUp:o,relevantAssignments:f,collectionPosition:c,teamParticipants:I,collectionId:d,matchUpType:l,dualMatchUp:h,tieMatchUp:a,tieFormat:S,structure:s,...E}}function eh(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 Nr({result:{error:Re},stack:e});o.participantId||(o.participantId=Ld()),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(Qs).includes(d))return{error:be,participantType:d};if(!p)return{error:Ne};const l=s.participants||[],m=l.filter((t=>t.participantType===Ks)).map((t=>t.participantId));if(d!==Ks&&o.person)return{error:Nn,person:o.person};if(u&&!Array.isArray(u))return{error:Nn,individualParticipantIds:u};if(d===Zs){if(o.person)return{error:Nn,person:o.person};if(!o.individualParticipantIds)return Nr({result:{error:Fe},stack:e});if(2!==o.individualParticipantIds.length&&!a)return Nr({info:"PAIR must be 2 individualParticipantIds",result:{error:Pe},stack:e});{const t=l.filter((t=>t.participantType===Ks)).map((t=>t.participantId));if(!Array.isArray(o.individualParticipantIds))return Nr({result:{error:Pe},stack:e});if(!o.individualParticipantIds.reduce(((e,n)=>t.includes(n)&&e),!0))return Nr({result:{error:Pe},stack:e})}const t=l.filter((t=>t.participantType===Zs)).map((t=>({individualParticipantIds:t.individualParticipantIds,participant:t}))),i=o.participantType===Zs&&t.find((t=>2===P(t.individualParticipantIds,o.individualParticipantIds).length));if(i&&!n)return{...E,existingParticipant:!0,participant:r&&mi(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===Ks){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||![Xs,Js].includes(d))return{error:be};if(u||(o.individualParticipantIds=[]),o.individualParticipantIds?.length)for(const t of o.individualParticipantIds){if("string"!=typeof t)return Nr({result:{participantId:t,error:Nn},stack:e});if(!m.includes(t))return Nr({result:{participantId:t,error:Ee},stack:e})}}s.participants.push(o),i||cr({payload:{tournamentId:s.tournamentId,participants:[o]},topic:jd});return br({participant:r&&mi(o),...E})}function nh({inContextDualMatchUp:t,drawDefinition:e,tournamentId:n,dualMatchUp:r,eventId:i}){if(r){t||(t=hf({matchUpId:r.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);const{extension:a}=Fr({element:e,name:Wa}),o=mi(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}})),hl({context:"ensureSidLineUps",matchUp:r,drawDefinition:e,tournamentId:n,eventId:i})}}function rh(t){const e=th(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 Nr({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=mm({tournamentRecord:i,participantFilters:{participantIds:[r,a]}})?.participants??[];if(2!==S.length)return Nr({result:{error:Ae},stack:n});if(S[0].participantType!==S[1].participantType)return Nr({result:{error:be},stack:n});const{appliedPolicies:y}=Fc({tournamentRecord:i,drawDefinition:o,event:c}),v=t.policyDefinitions?.[ga]??y?.[ga]??Tm[ga],w=S.find((({participantId:t})=>t===a));if(!1!==(t.enforceGender??v?.participants?.enforceGender)&&[zp,Jp].includes(d?.gender)&&d?.gender!==w?.person?.sex)return{error:we,info:"Gender mismatch"};const T=v?.processCodes?.substitution;nh({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 Nr({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 Nr({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=mi(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===lc,{assignedParticipantIds:O}=zc({lineUp:N,collectionPosition:p,collectionId:l}),{assignedParticipantIds:F}=zc({lineUp:A,collectionPosition:p,collectionId:l});if(P.lineUp=A,b&&g){const t=Gf({participantId:b,lineUp:A,drawDefinition:o,tieFormat:g});if(t.error)return Nr({result:t,stack:n})}else console.log("team participantId not found");let k,x;if(C){const{tournamentRecord:e}=t;let r=Yc({participantIds:F,tournamentRecord:e});if(!r.participant){const t=eh({returnParticipant:!0,pairOverride:!0,tournamentRecord:e,participant:{participantRole:Dm,individualParticipantIds:F,participantType:Zs}});if(t.error)return Nr({result:t,stack:n});k=t.participant?.participantId}r=Yc({participantIds:O,tournamentRecord:e});const i=r.participant?.participantId;if(i){Cm({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&&hl({tournamentId:i?.tournamentId,matchUp:h,context:n,drawDefinition:o})}return f&&hl({tournamentId:i?.tournamentId,matchUp:f,context:n,drawDefinition:o}),{...E,modifiedLineUp:A,participantRemoved:x,participantAdded:k}}function ih({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||Kc({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 ah({individualParticipantIds:t,groupingParticipantId:e,removeFromOtherTeams:n,tournamentRecord:r}){const i="addIndividualParticipantIds";if(!r)return Nr({result:{error:_},stack:i});if(!e||!t)return Nr({result:{error:ae},stack:i});const a=r.participants??[],o=a.find((t=>t.participantId===e));if(!o)return Nr({result:{error:Ee},stack:i});if(o?.participantType&&![Xs,Js].includes(o.participantType))return Nr({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!==Ks}));if(s.length)return Nr({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&&Em({individualParticipantIds:u,tournamentRecord:r}),o.individualParticipantIds=o.individualParticipantIds.concat(...u));const{topics:d}=mr();if(d.includes(Qd)){const t=a.find((({participantId:t})=>t===e));cr({topic:Qd,payload:{participants:[t]}})}return function({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}){const r=(n.events||[]).filter((t=>t?.eventType===ld&&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}=wp({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:mi(o,!1,!0),added:u.length,...E}}function oh(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 eh({tournamentRecord:i,participant:o});const{participant:s}=ac({participantId:o.participantId,tournamentRecord:i});if(!s)return eh({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}=mm({participantFilters:{participantTypes:[Ks]},tournamentRecord:i}),n=t?.map(lo);if(n){const r=u.filter((t=>"string"==typeof t&&n.includes(t)));([Js,fc].includes(m||s.participantType)||m===Zs&&(2===r.length||a))&&(I.individualParticipantIds=r),s.participantType===Qs.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(Rm).includes(l)&&(I.participantRole=l),Object.keys(Qs).includes(m)&&(I.participantType=m),Array.isArray(c)&&(I.participantRoleResponsibilties=c),s.participantType===Qs.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,rc.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,br(I)),n&&ah({individualParticipantIds:[s.participantId],groupingParticipantId:n,removeFromOtherTeams:r,tournamentRecord:i}),cr({topic:Qd,payload:{tournamentId:i.tournamentId,participants:[s]}}),{participant:mi(s),...E}}function sh(t){const e=th(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 Nr({result:{error:Ae},stack:n});if(t.sideNumber&&![1,2].includes(t.sideNumber))return Nr({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 Nr({result:{...E},stack:n});r=r??(t.sideNumber?c?.sides?.find((e=>e.sideNumber===t.sideNumber))?.participantId:void 0);const U=mm({participantFilters:{participantIds:[o]},tournamentRecord:i})?.participants?.[0];if(!U)return Nr({result:{error:Ee},stack:n});const{appliedPolicies:S}=Fc({tournamentRecord:i,drawDefinition:a,event:s}),y=t.policyDefinitions?.[ga]??S?.[ga]??Tm[ga];if(!1!==(t.enforceGender??y?.participants?.enforceGender)&&[zp,Jp].includes(u?.gender)&&u?.gender!==U.person?.sex)return{error:we,info:"Gender mismatch"};const{individualParticipantIds:v,participantType:w}=U;if(f===dc&&w!==Ks)return{error:be};const T=w===Ks?[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=h?.sides?.find((t=>t.participantId===r))?.sideNumber,M=u?.sides?.find((t=>N&&t.drawPosition===N))?.sideNumber,A=R??M??t.sideNumber;if(!g)return{error:Gt};const C=g.collectionDefinitions?.find((t=>t.collectionId===m));if(!C)return{error:jt};nh({tournamentId:i.tournamentId,eventId:s.eventId,inContextDualMatchUp:c,drawDefinition:a,dualMatchUp:h});const O=h?.sides?.find((t=>t.sideNumber===A)),F=u?.sides?.find((t=>t.sideNumber===A)),k=O?.lineUp??Kc({participantId:r,drawDefinition:a})?.lineUp,x=k?.filter((t=>t.collectionAssignments?.find((t=>t.collectionPosition===p&&t.collectionId===m&&!t.previousParticipantId)))),_=x?.map((t=>t?.participantId)),L=_?.length>1&&_||(w===Zs?U.individualParticipantIds:[o]),B=ih({collectionPosition:p,teamParticipantId:r,dualMatchUpSide:O,drawDefinition:a,participantIds:L,collectionId:m});if(B.error)return Nr({result:B,stack:n});const{modifiedLineUp:V}=B;let j;if(f===lc){if(w!==Zs){let t=ch({collectionPosition:p,teamParticipantId:r,drawDefinition:a,modifiedLineUp:V,participantId:o,collectionId:m,tieFormat:g});if(t?.error)return Nr({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}=Yc({participantIds:n,tournamentRecord:i});n.push(o);const{participant:r}=Yc({participantIds:n,tournamentRecord:i});if(!r&&t){t.individualParticipantIds=n;const e=oh({pairOverride:!0,tournamentRecord:i,participant:t});if(e.error)return e}else e=t?.participantId}}else{const t=eh({participant:{individualParticipantIds:[o],participantRole:Dm,participantType:Zs},pairOverride:!0,tournamentRecord:i});if(t.error)return t}return{...E,deletedParticipantId:e}}({side:F}),t.error)return t;j=t.deletedParticipantId,O&&(O.lineUp=V),h&&hl({tournamentId:i?.tournamentId,matchUp:h,context:n,drawDefinition:a})}else if(w===Zs)for(const t of L)ch({collectionPosition:p,teamParticipantId:r,drawDefinition:a,modifiedLineUp:V,participantId:t,collectionId:m,tieFormat:g})}else{const t=ch({collectionPosition:p,teamParticipantId:r,drawDefinition:a,modifiedLineUp:V,participantId:o,collectionId:m,tieFormat:g});if(t?.error)return t}if(O&&(O.lineUp=V),h&&hl({tournamentId:i?.tournamentId,matchUp:h,context:n,drawDefinition:a}),j){const{error:t}=Cm({participantIds:[j],tournamentRecord:i});t&&console.log("cleanup")}return{...E,modifiedLineUp:V}}function ch({collectionPosition:t,teamParticipantId:e,drawDefinition:n,modifiedLineUp:r,participantId:i,collectionId:a,tieFormat:o}){const s=Kc({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 Gf({participantId:e,lineUp:r,drawDefinition:n,tieFormat:o})}function uh({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 dh(t){if(t)return mi(t,!1,!0)}function ph({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 lh({collectionDefinitions:t=[],collectionGroups:e=[]}){let n=0;const{groupValueNumbers:r}=ph({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,...E};return{valueGoal:Math.floor(n/2)+1,...E}}function mh({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=Dp(o);else if(n){if(t&&(!i||!r)){const e=hf({drawDefinition:t,matchUpId:n});if(e.error)return e;if(e.matchUp?.matchUpType!==mc)return Nr({result:{error:Yt},stack:s});r||(r=e.structure),i||(i=e.matchUp)}c=bp({item:i,drawDefinition:t,structure:r,event:o})||bp({item:r,drawDefinition:t,structure:r,event:o})||Dp(t)||Dp(o)}else if(t&&e){if(!r){const n=Vs({drawDefinition:t,structureId:e});if(n.error)return n;r=n?.structure}c=bp({item:r,drawDefinition:t,structure:r,event:o})||Dp(t)||Dp(o)}else c=Dp(t)||Dp(o);return c?{...E,structure:r,tieFormat:c,matchUp:i}:Nr({result:{error:Gt},stack:s})}function fh(t,e){if((t?.bestOf||t?.exactly)&&t?.setFormat)return function(t,e){const n=hh(t.bestOf)||void 0,r=hh(t.exactly)||void 0,i=n||r;if(t.setFormat?.timed&&t.simplified&&1===i)return gh(t.setFormat);const a=i&&`${Ep}${i}`||"",o=Ih(t.setFormat,e),s=o&&`S:${o}`||"",c=Ih(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 hh(t){return!isNaN(Number(t))&&Number(t)}function gh(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function Ih(t,e){if("object"==typeof t&&Object.keys(t).length){if(t.timed)return gh(t);if(t.tiebreakSet)return Uh(t.tiebreakSet);const n=hh(t.setTo);if(n){const r=t.NoAD&&Ap||"",i=Uh(t.tiebreakFormat),a=i&&`/${i}`||"",o=hh(t.tiebreakAt);if(!1!==i)return`${n}${r}${a}${o&&(o!==n||e)&&`@${o}`||""}`}}}function Uh(t){if(t){if("object"!=typeof t||t.tiebreakTo){if("object"==typeof t&&hh(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?Ap:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}return!1}return""}}function Sh({matchUpFormat:t}){if("string"!=typeof t)return!1;const e=Op(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 fh(e,!!(n&&i&&r===a||o&&c&&s===u))===t}const yh="MIXED events can not contain mixed singles or { gender: ANY } collections",vh="events with { gender: ANY } can not contain MIXED singles collections";function wh(t){const e="tieFormatGenderValidityCheck",{referenceGender:n,matchUpType:r,gender:i}=t;return n&&i&&[zp,Jp].includes(n)&&n!==i?Nr({result:{valid:!1,error:Dn},context:{gender:i},stack:e}):n===Yp&&(i===Hp||i===Yp&&r!==lc)?Nr({result:{error:Dn,valid:!1},info:yh,stack:e}):n===Hp&&i===Yp&&r!==lc?Nr({result:{error:Dn,valid:!1},info:vh,stack:e}):{valid:!0}}const Th=(t,e)=>t.filter(Boolean).every((t=>typeof t===e)),Ph=t=>t.filter(Boolean).every(s);function Dh(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(!Th([n,r,i,s],"string")||!Ph([a,o]))return{error:bn};const u=t.consideredDate??ti((new Date).toLocaleDateString("sv"));if(!Gr(u))return{error:pe};const[d]=u.split("-").slice(0,3).map((t=>parseInt(t))),p=ei(u,-1),[l,m]=p.split("-").slice(1,3).map((t=>parseInt(t))),f=`${di(l)}-${di(m)}`,h=ei(u,1),[g,I]=h.split("-").slice(1,3).map((t=>parseInt(t))),U=`${di(g)}-${di(I)}`;let S=o&&ei(u,-365*o),y=a&&ei(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=br({consideredDate:u,combinedAge:c,ageMaxDate:r,ageMinDate:i,ageMax:a,ageMin:o});return v.length&&(C.errors=v),C}function bh({category:t}){if(!Ui(t))return{error:Nn};const e=Dh({category:t});if(e.error)return{error:e};const{ratingMax:n,ratingMin:r}=t;return n&&!s(n)?Nr({result:{error:Nn},context:{ratingMax:n}}):r&&!s(r)?Nr({result:{error:Nn},context:{ratingMin:r}}):{...e}}function Nh({childCategory:t,withDetails:e,category:n}){const r=bh({category:n}),i=bh({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=br({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 Rh={isValid:Sh,isValidMatchUpFormat:Sh,stringify:fh,parse:Op};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}`),Nr({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&&![dc,lc].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=uh({collectionValueProfiles:u,matchUpCount:f});t.errors&&c.push(...t.errors)}if(d&&"number"!=typeof d&&c.push(`collectionGroupNumber is not type number: ${l}`),h&&!Rh.isValidMatchUpFormat({matchUpFormat:h})&&c.push(`Invalid matchUpFormat: ${h}`),r){const t=wh({referenceGender:a,matchUpType:I,gender:v});if(t.error)return Nr({context:{referenceGender:a,gender:v},result:t,stack:s})}if(t&&i&&y){const t=Nh({category:i,childCategory:y});if(!t.valid)return Nr({result:{error:bn},context:t,stack:s})}return c.length?Nr({result:{errors:c,error:Tn},stack:s}):{valid:!0}}function Ah(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"),Nr({result:{error:Lt},context:{tieFormat:i,errors:s},stack:o});if("object"!=typeof i.winCriteria)return s.push("tieFormat.winCriteria must be an object"),Nr({result:{error:Lt},context:{tieFormat:i,errors:s},stack:o});if(!Array.isArray(i.collectionDefinitions))return s.push(Vf("tieFormat.collectionDefinitions")),Nr({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"),Nr({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}:Nr({result:{error:Lt},context:{tieFormat:i,errors:s},stack:o})}function Eh({matchUp:t,tieFormat:e,isMock:n,uuids:r}){const{collectionDefinitions:i}=e??{};return{tieMatchUps:(i??[]).map((e=>Ch({matchUp:t,collectionDefinition:e,uuids:r,isMock:n}))).filter(Boolean).flat()}}function Ch({collectionPositionOffset:t=0,collectionDefinition:e,matchUpsLimit:n,matchUp:r,isMock:i,uuids:a}){const{matchUpCount:o,matchUpType:s,collectionId:c,processCodes:u}=e||{},d=t=>{if(!i&&!r?.isMock)return a?.pop()??Ld();const n=e?.collectionId;return a?.pop()??`${r?.matchUpId}-${n}-TMU-${t+1}`};return w(0,n??o??0).map((e=>{const n=t+e+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:d(e),matchUpStatus:Ro,collectionPosition:n,collectionId:c,processCodes:u,matchUpType:s,isMock:i}}))}function Oh(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===pc?"D":"S",s,r,o].join(";")})).join("|");return{tieFormatName:t&&n||"UNNAMED",matchUpFormats:e,tieFormatDesc:r}}function Fh({considerations:t={},descendant:e,ancestor:n}){const r={},i={},{matchUpFormats:a,tieFormatDesc:o}=Oh(e),{matchUpFormats:s,tieFormatDesc:c}=Oh(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=kh(l),i.collectionsValue=kh(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 kh(t){const e=[],n=[];let r=0;return{totalValue:Object.keys(t).sort(cm).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 xh({matchUp:t,updateInProgressMatchUps:e}){return!t.winningSide&&![ko].includes(t.matchUpStatus)&&(e||t.matchUpStatus!==To&&!Tl(t))}function _h({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 Lh({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===Ro)).map(wi("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 Bh({drawDefinition:t,auditData:e}){const{extension:n}=Fr({name:ro,element:t});Cr({element:t,extension:{name:ro,value:Array.isArray(n?.value)?n?.value.concat(e):[e]}})}function Vh({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&&!Sh({matchUpFormat:o}))return Nr({result:{error:Nn},context:{matchUpFormat:o},stack:T});if(r&&"string"!=typeof r)return Nr({result:{error:Nn},context:{collectionName:r},stack:T});if(h&&!Object.values(Zp).includes(h))return Nr({result:{error:Nn},context:{gender:h},stack:T});if(m&&"object"!=typeof m)return Nr({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 Nr({result:{error:ae},stack:T});if(Object.values(D).filter(Boolean).length>1)return Nr({info:"Only one value assignment allowed per collectionDefinition",result:{error:Nn},stack:T});let b=mh({drawDefinition:a,structureId:d,matchUpId:l,eventId:f,event:I});if(b.error)return Nr({result:b,stack:T});const{matchUp:N,structure:R,tieFormat:M}=b,A=dh(M),C=M?.collectionDefinitions.find((t=>t.collectionId===c)),O=A?.collectionDefinitions.find((t=>t.collectionId===c));if(!C)return Nr({info:"source collectionDefinition",result:{error:On},context:{collectionId:c},stack:T});const F=S??y??v??w;if(U){const t=uh({matchUpCount:s??C?.matchUpCount??0,collectionValueProfiles:U});if(t.errors)return Nr({result:{error:Nn},info:t.errors,stack:T})}else if(F&&!p(F))return Nr({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,...br(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}=lh(A),G=br({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 Nr({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=br(A);if(b=Ah({tieFormat:q}),b.error)return Nr({result:b,stack:T});if(!L.length)return Nr({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 _h({from:e,to:h}).equivalent},U=mh({drawDefinition:n})?.tieFormat,S=mh({event:s})?.tieFormat;if(s&&a){for(const t of s.drawDefinitions??[])y({drawDefinition:t});s.tieFormat=dh(i),f+=1}else if(o){if(!o.tieMatchUps)return Nr({result:{error:Yt},stack:u});const e=g(o.tieMatchUps?.map((({collectionId:t})=>t))),r=_h({to:h,from:e}),{changes:a,changesArePossible:p,cannotChangeReaon:m}=Lh({matchUp:o,check:r});if(r.equivalent){if(!xh({matchUp:o,updateInProgressMatchUps:t}))return Nr({result:{error:Ue},info:"matchUp is IN_PROGRESS or COMPLETE",stack:u});o.tieFormat=dh(i),f+=1}else{if(!p)return Nr({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,hl({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||Fh({ancestor:r.tieFormat,descendant:i}).different;a&&(r.tieFormat=dh(i),p+=1,f+=1),(e||a)&&n&&Il({structureIds:[r.structureId],eventId:s?.eventId,drawDefinition:n})}else{if(!n)return{error:j};y({drawDefinition:n}),n.tieFormat=dh(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 Il({structureIds:n,eventId:s?.eventId,drawDefinition:t}),n.length}function v({inheritedTieFormat:r,structure:o}){let s=0;const d=Xp({matchUpFilters:{matchUpTypes:[fc]},structure:o})?.matchUps||[];for(const o of d){const d=xh({matchUp:o,updateInProgressMatchUps:t});let p=!1;const l=_h({from:g(o.tieMatchUps?.map((({collectionId:t})=>t))),to:h});if(l.equivalent)o.tieFormat&&I(o)&&d&&(o.tieFormat=dh(i),p=!0);else{const{changes:t,changesArePossible:e}=Lh({matchUp:o,check:l});if(e&&!o.tieFormat)w({changes:t,matchUp:o,tieFormat:i,uuids:c});else{if(!r)return Nr({result:{error:Gt},stack:u});(!o.tieFormat||Fh({ancestor:r,descendant:o.tieFormat}).different)&&(o.tieFormat=r,p=!0)}}p&&(s+=1,hl({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=dh(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(wi("collectionPosition"))),a=r.collectionDefinitions.find((t=>t.collectionId===n.collectionId)),o=Ch({matchUpsLimit:n.countChange,collectionPositionOffset:i,collectionDefinition:a,matchUp:e,uuids:t});s.push(...mi(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&&ml({matchUps:s,drawDefinition:n,tournamentId:d,eventId:a}),o.length&&fl({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}=Fc({tournamentRecord:e});if(t?.audit?.[ro]){Bh({drawDefinition:a,auditData:br({collectionDefinition:O,drawId:a?.drawId,action:T,structureId:d,matchUpId:l,eventId:f})})}}return Nr({result:{...b,modifications:L},stack:T})}function jh({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=Wc({drawDefinition:e}),{matchUps:o}=el({inContext:!0,drawDefinition:e,matchUpsMap:a}),{structure:s}=Vs({drawDefinition:e,structureId:r});if(!s)return{error:Ut};let c;if(c=s.structureType===Qo?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};qf({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)Gh({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:s,matchUpsMap:i,structure:a,event:o});else{const t=mi(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?Gh({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)),qf({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;yl({structure:s,drawPositions:n});if(vl({drawDefinition:e,positionAction:{name:"swapDrawPositionAssignments",drawPositions:n,structureId:r}}),Sl({tournamentId:t?.tournamentId,drawDefinition:e,structure:s,event:i}),i.eventType===md){const r=Xp({matchUpFilters:{matchUpTypes:[mc]},inContext:!0,structure:s}).matchUps.filter((t=>t.drawPositions?.some((t=>n.includes(t))))),a=Xp({structure:s,matchUpFilters:{matchUpTypes:[mc]}}).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);yf({inContextTargetMatchUp:r,drawPositionSideIndex:u,teamParticipantId:n,tournamentRecord:t,drawDefinition:e,matchUp:c,event:i})}}))}))}return Il({drawDefinition:e,structureIds:[r]}),{...E}}function Gh({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=xm({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:l,matchUpsMap:i});return m.error?m:(m=xm({drawPosition:p,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:l,matchUpsMap:i}),m.error?m:(jl({drawPosition:p,tournamentRecord:e,drawDefinition:n,structureId:l,matchUpsMap:i,event:o}),m=$f({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:l,participantId:d,matchUpsMap:i,event:o}),m.error?m:{...E}))}function qh({drawDefinition:t,structureId:e}){if(!t)return{error:j};const{structure:n}=Vs({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 $h({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}=js({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 Wh(t){if(!t?.drawDefinition)return!1;const e=tl(t),n=e?.includesTeamMatchUps;let{completedMatchUps:r,pendingMatchUps:i,upcomingMatchUps:a}=e||{};n&&(r=r?.filter((({matchUpType:t})=>t===fc)),i=i?.filter((({matchUpType:t})=>t===fc)),a=a?.filter((({matchUpType:t})=>t===fc)));return!!(r?.length&&!i?.length&&!a?.length)}function Hh({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=Hh({accessors:a,significantCharacters:t,value:e});r.push(...n)}))}else if(n=n[i],a.length){const e=Hh({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 zh({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(...Hh({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 Yh({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}=zh({participants:e,policyAttributes:n,idCollections:r,participant:a});return{...t,values:o}}))}function Kh({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 Jh(t){const{unfilledPositions:e,chunkedDrawPositions:n}=t,r=Kh(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=Zh(e);return!t.includes(n)}}(n),a=n.filter((t=>!i.includes(t))).filter((t=>{const e=Zh(t);return!r[e]?.includesGroupsToAvoid}));return{unassigned:n,unpaired:i,pairedNoConflict:a}}))}function Zh(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=Kh(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}):Jh({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 Qh({positionAssignments:t,participantIds:e}){const n=t.map((t=>t.participantId));return e.filter((t=>!n.includes(t)))}function tg({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=Qh({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 eg({isRoundRobin:t,groupedParticipants:e}){const n=[];return t?e.forEach((t=>{const e=t.map((t=>t.drawPosition)),{uniqueMatchUpGroupings:r}=wf({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 ng({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=eg({isRoundRobin:i,groupedParticipants:[[r,o]]}),c=t.find((t=>t.drawPosition===e)),u=eg({isRoundRobin:i,groupedParticipants:[[c,o]]});return!s.length&&!u.length}));if(o.length)return{drawPosition:r.drawPosition,possibleDrawPositions:o}})).filter(Boolean)})).flat(1)}function rg(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=mi(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}=tg({...t,candidatePositionAssignments:m,allGroups:c,groupKey:d});d=e,m.forEach((t=>{t.drawPosition===r&&(t.participantId=n)}))}));let h=Yh({candidatePositionAssignments:m,participantsWithGroupings:n,policyAttributes:o,idCollections:s}),g=N(h,p),I=eg({groupedParticipants:g,isRoundRobin:l}),U=0;for(;U<20&&I.length;){const t=ng({positionedParticipants:h,potentialDrawPositions:f,avoidanceConflicts:I,drawPositionGroups:a,isRoundRobin:l});if(t.length){const e=ig({candidatePositionAssignments:m,swapOptions:t});e.error&&console.log({result:e}),h=Yh({candidatePositionAssignments:m,participantsWithGroupings:n,policyAttributes:o,idCollections:s}),g=N(h,p),I=eg({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 ig({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 ag({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}=Vs({drawDefinition:c,structureId:l}),{matchUps:T}=Xp({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}=$s({structure:v}),D=ec({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:d}).participantsWithGroupings,b=P?.filter((t=>!t.participantId)),R=P?.map((t=>t.drawPosition)),M=v?.structureType===Qo,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===Js)).map((t=>t.participantId)),teamParticipants:d.filter((t=>t.participantType===Xs)).map((t=>t.participantId)),pairParticipants:d.filter((t=>t.participantType===Zs)).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}=zh({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 Nr({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}}))),_=Qh({participantIds:n,positionAssignments:P});if(_.length>(b?.length||0))return{error:Ke};let L;const B=_.length,V=w(0,g).map((()=>rg({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((()=>rg({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=(qs({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=jl({tournamentRecord:s,drawDefinition:c,seedBlockInfo:u,structureId:l,matchUpsMap:p,event:h,...t});if(e.error)return Nr({result:e,stack:y})}else if(t.participantId){const e=$f({automaticPlacement:!0,inContextDrawMatchUps:i,tournamentRecord:s,drawDefinition:c,seedBlockInfo:u,structureId:l,matchUpsMap:p,event:h,...t});if(e.error)return Nr({result:e,stack:y,context:{assignment:t}})}return{...E}}function og({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}=Vs({drawDefinition:a,structureId:u})),u||({structureId:u}=d);const{positionAssignments:m}=$s({structure:d}),{seedAssignments:h}=yu({provisionalPositioning:t,drawDefinition:a,structure:d}),g=h?.map((t=>t.participantId)).filter(Boolean),{stage:I,stageSequence:U}=d,S=I===Vo?Fr({element:d,name:Za})?.extension?.value:void 0,y=Su({provisionalPositioning:t,drawDefinition:a,stageSequence:U,entryStatuses:mu,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 Nr({result:{error:Ke},context:{unseededParticipantsCount:v.length,unfilledDrawPositionsCount:w?.length},stack:"positionUnseededParticipants"});const{appliedPolicies:T}=Fc({tournamentRecord:i,drawDefinition:a,event:l});let P=T?.[wa];if(d.stage===qo){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?ag({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=$f({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 Nr({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 sg(t){const e=t.structure??Vs(t).structure,r="positionQualifiers",i=[];if(e.stage===jo)return Nr({result:{error:At},stack:r});const{unplacedRoundQualifierCounts:a,positionAssignments:o,roundDrawPositions:s}=function({drawDefinition:t,structure:e,structureId:r}){e||({structure:e}=Vs({drawDefinition:t,structureId:r}));r||({structureId:r}=e);const{positionAssignments:i}=$s({structure:e}),{stage:a,stageSequence:o}=e,{qualifiersCount:s,roundQualifiersCounts:c}=hm({drawDefinition:t,stageSequence:o,structureId:r,stage:a}),u=(c?Object.keys(c):[]).map((t=>n(t))),{matchUps:d}=Xp({structure:e}),{roundProfile:p}=Ac({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 Nr({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 cg({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=dg(N(e.drawPositions,2));let i,a=t[r.length];for(;i=ug(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 ug(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 ug(e?n:t[Math.round(Math.random())],e)}return ug(n<r?t[1]:t[0],e)}function dg(t){const e=Math.floor(t.length/2);return t.length>2?[dg(t.slice(0,e)),dg(t.slice(e))]:t}function pg({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:n,drawDefinition:r,seedingProfile:i,seedBlockInfo:a,byesToPlace:o,structure:s}){a||(a=Cf({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}=$s({structure:n}),{seedAssignments:i}=yu({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)=>Af(t.seedValue)-Af(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=cg({orderedSortedFirstRoundSeededDrawPositions:I,validSeedBlocks:p,byesToPlace:o});return{strictSeedOrderByePositions:lg({orderedSeedDrawPositions:I,relevantMatchUps:e}).slice(0,o),blockSeedOrderByePositions:lg({orderedSeedDrawPositions:U,relevantMatchUps:e}).slice(0,o),isLuckyStructure:u,positionedSeeds:l,isContainer:d,isFeedIn:c}}function lg({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 mg({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}=Vs({drawDefinition:i,structureId:c})),c||(c=u?.structureId);const h=!(u?.structures??u?.stage===Vo),{byesCount:g,placedByes:I,relevantMatchUps:U}=function({provisionalPositioning:t,drawDefinition:e,matchUpsMap:n,structure:r,event:i}){const{matchUps:a,roundMatchUps:o}=Xp({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:{isCollectionMatchUp:!1},matchUpsMap:n,structure:r,event:i}),s=o?.[1]||[],c=r?.structureType===Qo,u=c?a:s,d=c?r?.structures?.length||0:a.length,{structureId:p,stage:l,stageSequence:m}=r,f=Su({entryStatuses:fu,provisionalPositioning:t,drawDefinition:e,stageSequence:m,structureId:p,stage:l}),{qualifiersCount:h}=hm({provisionalPositioning:t,drawDefinition:e,stageSequence:m,structureId:p,stage:l}),g=f.length+h,{positionAssignments:I,unassignedPositions:U}=$s({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!==jo&&(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}=pg({provisionalPositioning:t,relevantMatchUps:U,appliedPolicies:r,drawDefinition:i,seedingProfile:o,seedBlockInfo:a,byesToPlace:S,structure:u}),P=u?.structureType&&[Qo,Xo].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===Vo,{positionAssignments:p}=$s({structure:s}),l=p?.filter((t=>t.participantId)).map((t=>t.drawPosition)),{matchUps:h,roundMatchUps:g}=Xp({provisionalPositioning:t,matchUpFilters:{isCollectionMatchUp:!1},structure:s}),I=g?.[1]||[],U=s.structureType===Qo?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}=Cf({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}=Rf({cluster:xf(u)===Jo,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=jl({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 fg({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}=Vs({drawDefinition:a,structureId:d})),d||(d=l?.structureId),r||(r=Fc({drawDefinition:a}).appliedPolicies),!i){const e=l&&Cf({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}=kf({provisionalPositioning:t,randomize:!0,drawDefinition:r,seedingProfile:i,seedBlockInfo:a,structureId:s,event:u}),{appliedPolicies:l}=Fc({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=$f({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 hg({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||(nr(),c=mi(c,!1,!0));const U=e=>(t||rr(),Nr({result:e,stack:"automatedPositioning"})),S=Vs({drawDefinition:c,structureId:d});if(S.error)return U(S);const y=S.structure;if(!y)return{error:Ut};o||(o=Fc({drawDefinition:c,structure:y,event:g})?.appliedPolicies);const{qualifiersCount:v}=hm({stageSequence:y.stageSequence,provisionalPositioning:e,stage:y.stage,drawDefinition:c,structureId:d}),w=mu,T=Su({stageSequence:y.stageSequence,provisionalPositioning:e,stage:y.stage,placementGroup:s,drawDefinition:c,entryStatuses:w,structureId:d});if(!T?.length&&!v)return P={...E},t||rr(),P;var P;p=p??Wc({drawDefinition:c}),n||({matchUps:n}=el({inContext:!0,drawDefinition:c,matchUpsMap:p}));let D=[];const b=Cf({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?mm({withIndividualParticipants:!0,tournamentRecord:a})?.participants:[];if(xf(y.seedingProfile||u)===Zo){let t=i?mg({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=fg({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!==gs){const t=fg({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?mg({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=sg({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=og({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}=qs({drawDefinition:c,structure:y});return Il({drawDefinition:c,structureIds:[d]}),t||rr(),{positionAssignments:A,conflicts:M,...E,positioningReport:I}}function gg(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(!Wh({drawDefinition:i,structureId:o})&&!n)return{error:W};const d=qh({drawDefinition:i,structureId:o}).playoffStructures?.sort(((t,e)=>Bs(t)-Bs(e))),p=[],l=[];if(d)for(const t of d){const{structureId:o}=t,u=hg({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 Ig({drawDefinition:t}){const{maxQualifyingDepth:e,structureProfiles:n}=af({drawDefinition:t});for(const r of t.structures){const t=n[r.structureId];t.distanceFromMain&&(r.stageSequence=e+1-t.distanceFromMain)}return{...E}}function Ug({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=Vs({drawDefinition:t,structureId:a});if(o.error)return Nr({stack:"attachQualifyingStructure",context:{targetStructureId:a},result:o});t.structures||(t.structures=[]);t.links||(t.links=[]);t.structures.push(n),t.links.push(i),Ig({drawDefinition:t});const s=Xp({structure:n})?.matchUps||[];return ml({drawDefinition:t,tournamentId:e,matchUps:s,eventId:r}),Il({drawDefinition:t,structureIds:[n.structureId]}),{...E}}({tournamentId:t.tournamentId,drawDefinition:e,structure:n,link:r});if(i.error)return i;return tf({tournamentRecord:t,timeItem:{itemType:"attachQualifyingStructures",itemValue:{structureId:n.structureId,drawId:e.drawId}}}),i}const Sg="SET3-S:6/TB7",yg="SET3-S:6/TB7-F:TB10",vg={FORMAT_STANDARD:Sg,FORMAT_STANDARD_NOAD:"SET3-S:6NOAD",FORMAT_ATP_DOUBLES:yg,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 wg({winningSide:t,matchUpFormat:e=Sg,matchUpStatus:n,tallyPolicy:r,score:i}){const a=[0,0],o=i?.sets,s="number"==typeof t&&t-1,c=Op(e),u=Dg(c?.bestOf??1);if("number"==typeof s&&(n===yo&&r?.setsCreditForDefaults||n===Mo&&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===bo&&(+a[1-s]===u&&(a[1-s]-=1),r?.setsCreditForRetirements&&(a[s]=u)),a}function Tg({matchUpFormat:t=Sg,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=Op(t),u=Dg(c?.bestOf??1),d=c?.setFormat?.tiebreakAt||0,p=[[],[]];if("number"==typeof s&&(r===yo&&i?.gamesCreditForDefaults||r===Mo&&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;Ng(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===bo&&"number"==typeof s){const a=o.length>u&&c?.finalSetFormat?"finalSetFormat":"setFormat",l=c?.[a];if(Ng(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=wg({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 Pg({matchUpFormat:t,score:e}){const r=t?Op(t):void 0,i=Dg(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(bg(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 Dg(t){return t&&Math.ceil(t/2)||1}function bg(t){return"P"===t}function Ng(t){return!bg(t)}function Rg({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,[Eg(e,0),Eg(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&&Mg(t),m=u&&Ag(t);if(l||m)if(Cg(a,l),Cg(a,m),o?.length){r=0;for(const t of o){const{matchUpType:e}=t,r=e===lc,i=e===dc;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)))),Fg({matchUpFormat:t.matchUpFormat,matchUpStatus:t.matchUpStatus,score:t.score,winningParticipantId:l,losingParticipantId:m,participantResults:a,isTieMatchUp:!0,manualGamesOverride:p,tallyPolicy:n,winningSide:u})}kg({winningParticipantId:l,losingParticipantId:m,participantResults:a,matchUpStatus:i})}else Fg({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&&ko.includes(i)){const e=Eg(t,0),n=Eg(t,1);e&&(Cg(a,e),a[e].matchUpsCancelled+=1),n&&(Cg(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&&(Cg(a,e),Cg(a,n),a[e].tieMatchUpsWon+=1,a[n].tieMatchUpsLost+=1,t.matchUpType===dc?(a[e].tieSinglesWon+=1,a[n].tieSinglesLost+=1):t.matchUpType===lc&&(a[e].tieDoublesWon+=1,a[n].tieDoublesLost+=1))}Og({score:t.score,manualGamesOverride:p,participantResults:a,sides:d})}}else Og({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;Cg(a,t),Cg(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&&Op(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 Mg(t){return Eg(t,t.winningSide-1)}function Ag(t){return Eg(t,1-(t.winningSide-1))}function Eg(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 Cg(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 Og({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&&(Cg(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 Fg({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||kg({winningParticipantId:t,losingParticipantId:e,participantResults:n,matchUpStatus:a});const l=wg({matchUpStatus:a,matchUpFormat:i,tallyPolicy:s,winningSide:c,score:u}),m=Tg({matchUpStatus:a,matchUpFormat:i,tallyPolicy:s,winningSide:c,score:u}),{pointsTally:f}=Pg({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 kg({winningParticipantId:t,losingParticipantId:e,participantResults:n,matchUpStatus:r}){e&&(r===Mo&&(n[e].walkovers+=1),r===yo&&(n[e].defaults+=1),r===bo&&(n[e].retirements+=1),[yo,bo,Mo].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 xg({participantResults:t,participantIds:e,attribute:n}){return _g({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 _g(t){return(t.participantIds||Object.keys(t.participantResults)).reduce(((e,n,r)=>(e.push({participantId:n,i:r,results:t.participantResults[n]}),e)),[])}const Lg=[{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}],Bg={matchUpsPct:20,tieMatchUpsPct:16,setsPct:12,gamesPct:8,pointsPct:4};function Vg(t){const{requireCompletion:e=!0,participantResults:n,subOrderMap:r,tallyPolicy:i}=t,a=[];if(e&&!function({participantResults:t,participantsCount:e}){const n=_g({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=xg({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=jg({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(Bg).filter((t=>i.GEMscore.includes(t))):Object.keys(Bg);return e.map((e=>(t[e]||0)*Math.pow(10,Bg[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 jg({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||Lg).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}=Rg({participantIds:a&&e,matchUpFormat:n,tallyPolicy:r,matchUps:o}),u=xg({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=jg({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 Gg({policyDefinitions:t,generateReport:e,matchUpFormat:n,matchUps:r=[],subOrderMap:i,perPlayer:a}){if(!Mc(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!==go)),s=o.length&&m(o.map((({drawPositions:t})=>t)).flat()).length,c=o.filter((t=>Qp({matchUp:t}))).length===o.length;c||(a=0);const u=r.every((({matchUpType:t,tieMatchUps:e})=>t===fc&&e?.every((t=>Qp({matchUp:t}))))),d=t?.[fa],p=r.filter((t=>Qp({matchUp:t})||t.matchUpType===fc)),{participantResults:l}=Rg({matchUps:p,matchUpFormat:n,tallyPolicy:d,perPlayer:a});let f,h;const{groupOrder:g,report:I}=Vg({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}=Vg({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 qg({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=>ko.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===Uo||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=Np({matchUp:o,drawDefinition:r,structure:a,event:s})?.tieFormat||t?.tieFormat;if(!c)return{error:Gt};const u=Ah({tieFormat:c});if(u.error)return u;const d=c?.collectionDefinitions||[],p=o?.tieMatchUps??[],l=[0,0],{groupValueGroups:m,groupValueNumbers:f}=ph(c);for(const t of d)qg({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&&ko.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&&hf({inContext:!0,drawDefinition:r,matchUpId:t})?.matchUp;if(e){const{completedTieMatchUps:t,order:n}=Gg({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 Wg={matchUpStatus:Ro,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function Hg({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&&go||[yo,Mo].includes(u.matchUpStatus)&&u.matchUpStatus||Ro,[Mo,yo].includes(u.matchUpStatus)&&(u.winningSide=void 0),u.matchUpStatusCodes&&Uf({inContextDrawMatchUps:t,sourceMatchUpStatus:n,sourceMatchUpId:a,matchUpsMap:c,matchUp:u}),hl({tournamentId:i?.tournamentId,eventId:d?.eventId,context:`removeSubsequentDrawPosition-${r}`,drawDefinition:o,matchUp:u}),{...E}}function zg({tournamentRecords:t,eventId:e,drawId:n}){const{tournamentIdMap:r}=Ym({tournamentRecords:t});return(r?Object.keys(r):[]).find((t=>e&&r?.[t].includes(e)||n&&r?.[t].includes(n)))}function Yg({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:i,matchUps:a,event:o}){if(!Mc(a))return{error:Nn};if(!t)return{error:Nn};const{policyDefinitions:s}=kc({policyTypes:[fa],tournamentRecord:e,drawDefinition:r,event:o}),{subOrderMap:c}=function({positionAssignments:t}){const e=(t||[]).filter(wi(Mi)).map((t=>{const{extension:e}=Fr({element:t,name:eo}),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=Gg({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)){Cr({element:t,extension:{value:d[e],name:no}}),d[e].ties||Ar({element:t,name:eo})}else Ar({element:t,name:no}),Ar({element:t,name:eo})})),Il({drawDefinition:r}),{...E,participantResults:d,bracketComplete:p,report:l}}function Kg(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 Jg({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===fc;if(g&&r){if(c&&u.matchUpId!==c){const t=hf({drawDefinition:r,matchUpId:c,event:d});if(!t.matchUp)return{error:Wt};({matchUp:u,structure:h}=t)}}else u.matchUpId!==c&&console.log("!!!!!");a&&[Mo,wo].includes(a)||o?Object.assign(u,{...Wg}):l&&(u.score=l);const I=a&&u?.matchUpStatus===yo&&a!==yo;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}=hf({drawDefinition:r,matchUpId:c,event:d})),!a||u.winningSide||!Tl(u)||ko.includes(a)||[ho,No].includes(a)||(u.matchUpStatus=To),I&&u?.processCodes?.length||a===yo){const t=Fc({tournamentRecord:n,drawDefinition:r,structure:h,event:d})?.appliedPolicies;U=t?.[Ta]?.processCodes?.incompleteAssignmentsOnDefault}if(!u.collectionId){const t=h?.structureType===Qo,e=jp({drawDefinition:r,structure:h});if(Vp({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:[fc]}:void 0,{matchUps:o}=Xp({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})))),Yg({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 Nr({result:a,stack:f})}}if(p){const t=Kg({element:u,notes:p});if(t.error)return Nr({result:t,stack:f})}const S=n?.tournamentId,y=mr().topics.includes(pp),v=(y||U)&&Wc({drawDefinition:r}),w=v&&el({matchUpFilters:{matchUpIds:[c]},nextMatchUps:!0,tournamentRecord:n,inContext:!0,drawDefinition:r,matchUpsMap:v}).matchUps?.[0];if(y&&w&&function({tournamentId:t,inContextMatchUp:e}){e&&cr({payload:{inContextMatchUp:e,tournamentId:t},topic:pp,key:e.matchUpId})}({tournamentId:S,inContextMatchUp:w}),Array.isArray(U)&&w&&!w.sides?.every((({participantId:t})=>t)))if(a===yo)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 hl({eventId:d?.eventId,context:f,drawDefinition:r,tournamentId:S,matchUp:u}),{...E}}function Zg(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&&zg({tournamentRecords:c,...t});const d=u&&c[u];if(!d)return{error:_};const p=hf({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};nh({tournamentId:d?.tournamentId,eventId:s?.eventId,dualMatchUp:l,drawDefinition:n});const{extension:f}=Fr({name:Va,element:l});if(f?.value){if(!i)return{...E,score:l.score};Ar({element:l,name:Va})}const h=Np({drawDefinition:n,structure:m,matchUp:l,event:s})?.tieFormat;l.tieFormat=dh(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&&Uo||bl({matchUpStatus:r??l.matchUpStatus,tieMatchUps:l.tieMatchUps,winningSide:l.winningSide,score:w})&&To||Ro,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&&ko.includes(n)||e));let N;if(l.tieFormat&&!T&&!b){const t=Np({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 Jg({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 Xg(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=jp({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=Jg({...t,matchUpStatus:a||Ro,removeWinningSide:!0});if(w.error)return w;let T;if(l){const{matchUpTieId:n,matchUpsMap:a}=t;if(T=Zg({matchUpId:n,tournamentRecord:r,drawDefinition:i,matchUpsMap:a,event:p}),!e&&!T.removeWinningSide)return{...E}}if(m)return{...E};const{matchUps:P}=Xp({afterRecoveryTimes:!1,inContext:!0,drawDefinition:i,matchUpsMap:o,structure:d}),{positionAssignments:D}=$s({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&&Qg({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=[go,Mo,yo],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===ss){tI({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}=Vs({drawDefinition:a,structureId:p});if(!l)return{error:Ut};const{positionAssignments:m}=$s({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,hl({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){tI({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 Qg({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}=Vs({drawDefinition:s,structureId:t});if(!e)return{error:Ut};const{positionAssignments:n}=$s({structure:e});e.seedAssignments=(e.seedAssignments??[]).filter((t=>t.participantId!==r));const o=n?.find((t=>t.participantId===r)),d=o?.drawPosition,{matchUps:l}=Xp({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&&hl({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}=Vs({drawDefinition:a,structureId:o});if(p?.structureType===Qo)return{...E};u=u??Wc({drawDefinition:a});const l=(u?.mappedMatchUps||{})[o].matchUps,{initialRoundNumber:m}=xl({drawPosition:n,matchUps:l}),f=l?.filter((t=>t.roundNumber>=c&&t.roundNumber!==m&&t.drawPositions?.includes(n))),{positionAssignments:h}=qs({drawDefinition:a,structureId:o});for(const o of f??[])Hg({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 tI({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,matchUpsMap:i,targetLink:a,event:o}){return zl({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:i,drawPosition:r,structureId:a.target.structureId,event:o}),{...E}}function eI(t){const{tournamentRecord:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:i,targetData:a,structure:o,event:s}=t,c="doubleExitAdvancement";if(o.structureType===Qo)return Nr({result:{...E},stack:c});const{matchUp:u,targetMatchUps:d,targetLinks:p}=a,{loserMatchUp:l,winnerMatchUp:m,loserTargetDrawPosition:f}=d;if(l&&l.matchUpStatus!==go){const{loserTargetLink:a}=p;if(n?.progression?.doubleExitPropagateBye){const t=rI({loserTargetDrawPosition:f,tournamentRecord:e,loserTargetLink:a,drawDefinition:r,loserMatchUp:l,matchUpsMap:i,event:s});if(t.error)return Nr({result:t,stack:c})}else{const{feedRound:n,drawPositions:r,matchUpId:i}=l,a=n?2:2-r.indexOf(f),o=nI({...t,targetMatchUp:l,walkoverWinningSide:a,tournamentRecord:e,sourceMatchUp:u,matchUpId:i});if(o.error)return Nr({result:o,stack:c})}}if(m){const n=nI({...t,matchUpId:m.matchUpId,targetMatchUp:m,tournamentRecord:e,sourceMatchUp:u});if(n.error)return Nr({result:n,stack:c})}return Nr({result:{...E},stack:c})}function nI(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===vo?vo:wo,u=t.matchUpStatus===vo?yo:Mo,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 Nr({result:{error:z},stack:d});const{pairedPreviousMatchUpIsDoubleExit:h,pairedPreviousMatchUp:g}=gf(t),I=Nc({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=rI({loserTargetDrawPosition:y,loserMatchUp:w,tournamentRecord:n,loserTargetLink:t,drawDefinition:r,matchUpsMap:o});if(e.error)return Nr({result:e,stack:d})}const T=p.drawPositions?.filter(Boolean)||[],P=1===T.length,D=t.walkoverWinningSide||P&&Sf({drawPosition:T[0],matchUpId:a.matchUpId,inContextDrawMatchUps:e})||void 0,N=[Mo,yo].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:iI(F),previousMatchUpStatus:F,sideNumber:1},{matchUpStatus:iI(k),previousMatchUpStatus:k,sideNumber:2}]:2===C&&(O=[{matchUpStatus:iI(k),previousMatchUpStatus:k,sideNumber:1},{matchUpStatus:iI(F),previousMatchUpStatus:F,sideNumber:2}]),O.length&&(O=O.map((t=>br(t))));const x=Jg({...t,matchUp:p,winningSide:D,matchUpStatusCodes:O,matchUpStatus:M});if(x.error)return Nr({result:x,stack:d});if(N)return eI({...t,matchUpStatus:M,targetData:I});if(!v)return Nr({result:{...E},stack:d});const _=2===m.length?m[D-1]:m[0],{positionAssignments:L}=qs({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=Nc({matchUpId:V.matchUpId,inContextDrawMatchUps:e,drawDefinition:r});if(G){const t=j.filter(Boolean)[0],n=Sf({drawPosition:t,matchUpId:V.matchUpId,inContextDrawMatchUps:e}),i=Jg({matchUpId:V.matchUpId,matchUp:V,matchUpStatus:u,matchUpStatusCodes:[],removeScore:!0,drawDefinition:r,winningSide:n});return i.error?Nr({result:i,stack:d}):$l({drawPositionToAdvance:t,matchUpId:V.matchUpId,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:o})}if([Mo,yo].includes(v.matchUpStatus)){const e=eI({...t,matchUpId:V.matchUpId,matchUpStatus:M,targetData:n});if(e.error)return Nr({result:e,stack:d})}return Nr({result:{...E},stack:d})}return vf({matchUpId:v.matchUpId,drawPosition:_,inContextDrawMatchUps:e,drawDefinition:r})}if(h){if(!V)return{error:zt};if(G){const t=j[0],n=Sf({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawPosition:t});console.log("existing drawPosition is winningSide",{walkoverWinningSide:n})}const n=[Mo,yo].includes(V.matchUpStatus)?u:c,i=Jg({matchUpId:V.matchUpId,matchUp:V,matchUpStatusCodes:[],removeScore:!0,drawDefinition:r,matchUpStatus:n});if(i.error)return Nr({result:i,stack:d});if(n===c){const e=eI({...t,matchUpId:a.matchUpId,matchUpStatus:n,targetData:I});if(e.error)return e}}return Nr({result:{...E},stack:d})}function rI(t){const{loserTargetDrawPosition:e,tournamentRecord:n,loserTargetLink:r,drawDefinition:i,matchUpsMap:a,event:o}=t,s=r?.target?.structureId,{structure:c}=Vs({drawDefinition:i,structureId:s});return c?jl({drawPosition:e,tournamentRecord:n,drawDefinition:i,structureId:s,matchUpsMap:a,event:o}):{error:yt}}function iI(t){return t===wo?Mo:t===vo?yo:t}function aI(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===go,c=a.winningSide,u=[wo,vo].includes(r),d=Pl({matchUpStatus:r}),p=Dl({matchUpStatus:r}),l=!d&&!p,m=t.matchUpTieId||c&&d&&!u,f=c&&u;return l&&{error:Ft}||m&&oI(t)||f&&function(t){const e=Xg(t);return e.error?e:eI(t)}(t)||c&&Xg(t)||p&&Jg({...t,removeScore:[Io,Mo].includes(r),matchUpStatus:r||Ro})||s&&function({tournamentRecord:t,drawDefinition:e,structure:n,matchUp:r}){const i="attemptToSetMatchUpStatusBYE";if(r?.winningSide)return Nr({result:{error:_t},context:{matchUpStatus:go},stack:i});const{positionAssignments:a}=$s({structure:n}),o=a?.filter((t=>t.bye)).map((t=>t.drawPosition)),s=r.drawPositions?.some((t=>o?.includes(t)));return s?(r.matchUpStatus=go,r.matchUpStatusCodes=[],hl({tournamentId:t?.tournamentId,context:i,drawDefinition:e,matchUp:r}),{...E}):Nr({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=oI({...t,removeScore:!0});return e.error?e:eI(t)}(t)||o&&oI(t)||Nr({result:{error:_t},stack:"attemptToSetMatchUpStatus"})}function oI(t){const e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){const n=Xg(t);if(n.error)return Nr({result:n,stack:e})}const n=Boolean(t.matchUp.collectionId),r=Jg(t);if(n){const{matchUpTieId:n,drawDefinition:i,matchUpsMap:a}=t,o=Zg({tournamentRecord:t.tournamentRecord,matchUpId:n,event:t.event,drawDefinition:i,matchUpsMap:a});if(o.error)return Nr({result:o,stack:e});Object.assign(r,{tieMatchUpResult:o})}return Nr({result:r,stack:e})}function sI({drawDefinition:t,structure:e,matchUp:n}){const r=[];if(e.finishingPosition===Fs){if(Wh({drawDefinition:t,structure:e})){const{structureIds:i}=function({drawDefinition:t,structure:e,matchUp:n}){const{drawPositions:r}=n,{positionAssignments:i}=qs({drawDefinition:t,structure:e}),a=i?.filter((({drawPosition:t})=>r?.includes(t))),o=a?.map((t=>{const{extension:e}=Fr({element:t,name:no});return e?.value?.groupOrder})),{containerStructures:s}=wl({drawDefinition:t}),c=s[e.structureId],u=bc({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 cI(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=Pl({matchUpStatus:o})||[Io,fo].includes(o)&&e,f=Boolean(d.collectionId),h=jp({drawDefinition:i,structure:u}),g=f||h||function({structure:t,matchUp:e}){const{drawPositions:n}=e,{positionAssignments:r}=$s({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=[Mo].includes(o);return Nr({result:Jg({matchUpStatusCodes:m&&n||[],matchUpStatus:m&&o||Uo,tournamentRecord:r,drawDefinition:i,matchUpFormat:a,removeScore:I,winningSide:s,matchUpId:c,matchUp:d,event:p,score:l}),stack:"attemptToModifyScore"})}function uI(t){const n=cI(t);if(n.error)return n;const r=Pl({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=jp({drawDefinition:c,structure:h});let v,w=g.drawPositions;if(S){const{matchUpTieId:e,matchUpsMap:n}=t,r=Zg({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 Nr({result:{...E,...v},stack:U})}if(y)return Nr({result:{...E,...v},stack:U});if(!w)return Nr({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=Vs({structureId:f,drawDefinition:c});if(h.error)return h;const{structure:g}=h,{positionAssignments:I}=$s({structureId:f,drawDefinition:c}),U=I?.find((t=>t.drawPosition===i)),S=U?.participantId,y=o.target.structureId,{positionAssignments:v}=$s({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)$f({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&&$f({participantId:S,structureId:y,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:a,drawDefinition:c,drawPosition:t,matchUpsMap:p,event:l})}else if(T){const t=vf({drawPosition:T,matchUpId:u.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:a,sourceMatchUpId:s,drawDefinition:c,matchUpsMap:p});if(t.error)return Nr({result:t,stack:m})}else if(g?.stage!==Vo){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&&_f({eventId:u?.eventId,structureId:y,...t,tournamentRecord:a,drawDefinition:c,participantId:e})}}else{const t=vf({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=Bf({lineUp:e}),hl({tournamentId:a?.tournamentId,eventId:u?.eventId,matchUp:i,context:m,drawDefinition:c})}}}return{...E}}({sourceMatchUpStatus:r&&u||Uo,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 Nr({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===ss&&2===d.roundNumber&&Math.min(...g.filter(Boolean)),U=I||g[n],S=I||g[1-n],y=c.source.structureId,{structure:v}=Vs({structureId:y,drawDefinition:u}),{matchUps:w}=Xp({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===Mo||t.matchUpStatus===yo&&!Tl(t);return e?.sideNumber===t.winningSide&&!n})),P=h===ss&&0===T.length,{positionAssignments:D}=$s({structureId:y,drawDefinition:u}),b=D?.find((t=>t.drawPosition===o)),N=b?.participantId,R=c.target.structureId,{positionAssignments:M}=$s({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 Nr(P?{result:L(),stack:t}:{result:_(),stack:t})}();if(t.error)return Nr({result:t,stack:f})}else if(x){const t=L();if(t.error)return Nr({result:t,stack:f})}else{if(!N||!k)return Nr({result:{error:Q},context:{loserDrawPosition:o,loserTargetLink:c},stack:f});{O.sort(e);const t=O[0],n=$f({participantId:N,structureId:R,drawPosition:t,inContextDrawMatchUps:r,sourceMatchUpStatus:a,tournamentRecord:s,drawDefinition:u,matchUpsMap:l,event:m});if(n.error)return Nr({result:n,stack:f})}}if(v?.seedAssignments&&v.structureId!==R){const t=v.seedAssignments.find((({participantId:t})=>t===N)),e=t?.participantId;t&&e&&_f({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=Bf({lineUp:t.lineUp}),hl({tournamentId:s?.tournamentId,matchUp:a,context:f,drawDefinition:u,eventId:n}))}}return{...E};function _(){return Nr({result:jl({drawPosition:S,structureId:R,tournamentRecord:s,drawDefinition:u,event:m}),stack:"assignLoserPositionBye"})}function L(){return Nr({result:N?$f({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||Uo,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 Nr({result:t,stack:U})}if(b){const t=b.drawPositions||[],e=jl({drawPosition:Math.min(...t.filter(Boolean)),structureId:y.target.structureId,tournamentRecord:s,drawDefinition:c,event:I});if(e.error)return Nr({result:e,stack:U})}}return Nr({result:{...E,...v},stack:U})}function dI(t){const{inContextDrawMatchUps:e,targetData:n,drawDefinition:r,relevantLink:i}=t;if(i?.linkCondition===ss&&n?.matchUp?.matchUpStatus===go)return!1;const{targetMatchUps:{loserMatchUp:a,winnerMatchUp:o},targetLinks:s}=n,c=[yo,Mo].includes(a?.matchUpStatus),u=o?.drawPositions?.filter(Boolean).length||0;if(a?.winningSide&&!c||o?.winningSide&&2===u&&(!o.feedRound||![Mo,yo].includes(o?.matchUpStatus)))return!0;const d=a&&Nc({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),p=o&&Nc({matchUpId:o.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),l=d&&dI({relevantLink:s?.loserTargetLink,targetData:d,inContextDrawMatchUps:e,drawDefinition:r});return!(!(p&&dI({targetData:p,inContextDrawMatchUps:e,drawDefinition:r}))&&!l)}function pI(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 cI(t);if(u.winningSide&&u.winningSide!==s){const{connectedStructureIds:e}=sI({drawDefinition:a,structure:c,matchUp:u});e.length&&(console.log({connectedStructureIds:e}),n=!0);const r=Xg(t);if(r.error)return r}const d=uI(t);if(d.error)return Nr({result:d,stack:e});let p,l;return t.qualifierChanging&&r?.[ya]?.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===ts){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===Ro&&!dI({inContextDrawMatchUps:n,drawDefinition:i,targetData:Nc({matchUpId:c.matchUpId,inContextDrawMatchUps:n,drawDefinition:i})})){const{structure:n}=Vs({structureId:c.structureId,drawDefinition:i}),o=qs({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]))}Sl({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:i,structure:n}),e=!0}}}return{...E,qualifierReplaced:e}}(t).qualifierReplaced),t.qualifierAdvancing&&r?.[ya]?.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===ts){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===Ro&&!dI({inContextDrawMatchUps:n,drawDefinition:i,targetData:Nc({matchUpId:c.matchUpId,inContextDrawMatchUps:n,drawDefinition:i})})){const n=c.sides.find((t=>t.qualifier&&!t.participantId))?.drawPosition,{structure:r}=Vs({structureId:c.structureId,drawDefinition:i});if(!r)return{error:Ut};const a=qs({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]))}Sl({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:i,structure:r}),e=!0}}}return{...E,qualifierPlaced:e}}(t).qualifierPlaced),Nr({result:br({...E,...d,connectedStructures:n,qualifierReplaced:p,qualifierPlaced:l}),stack:e})}const lI={drawPositionToRemove:"green",iteration:"brightred",winner:"green",loser:"brightred"};function mI(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";Bl({method:c,color:"brightyellow",iteration:s,keyColors:lI});const{targetLinks:{loserTargetLink:u},targetMatchUps:{loserMatchUp:d,winnerMatchUp:p,loserTargetDrawPosition:l}}=a;if(p&&p.matchUpStatus!==go){const{stage:e,roundNumber:n,roundPosition:r}=p;Bl({winner:"winner",stage:e,roundNumber:n,roundPosition:r,keyColors:lI}),fI({...t,targetMatchUp:p,sourceMatchUp:o,iteration:s})}if(d&&d.matchUpStatus!==go){const a=e.find((({matchUpId:t})=>t===d.matchUpId)),{structure:o}=Vs({drawDefinition:r,structureId:a.structureId}),{stage:p,roundNumber:m,roundPosition:f,feedRound:h}=d;if(Bl({loser:"loser",stage:p,roundNumber:m,roundPosition:f,keyColors:lI,feedRound:h}),n?.progression?.doubleExitPropagateBye)tI({drawPosition:l,targetLink:u,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:i});else{const e=fI({...t,structure:o,targetMatchUp:d,iteration:s});if(e.error)return Nr({result:e,stack:c})}}return Nr({result:{...E},stack:c})}function fI(t){const{inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,sourceMatchUp:i,targetMatchUp:a,matchUpsMap:o,structure:s,iteration:c}=t,u="conditionallyRemoveDrawPosition";Bl({method:u});const d=Nc({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=If({structureId:s.structureId,matchUp:i,matchUpsMap:o})?.pairedPreviousMatchUp,m=[wo,vo].includes(f?.matchUpStatus),g=f?.drawPositions?.filter(Boolean)||[];if([...ko,go].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;Bl({method:"removeDirectedWinner",drawPositionToRemove:h,keyColors:lI,color:"brightgreen",stage:t,roundNumber:n,roundPosition:i}),Qg({winningDrawPosition:h,winnerMatchUp:p,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:o})}let I=mI({targetData:d,matchUp:a,inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:o,structure:s,iteration:c});if(I.error)return Nr({result:I,stack:u});const U=function({pairedPreviousDoubleExit:t,noContextTargetMatchUp:e}){return e.matchUpStatus===go?go:t?[vo,yo].includes(e?.matchUpStatus)?yo:Mo:Ro}({pairedPreviousDoubleExit:m,noContextTargetMatchUp:l}),S=!m;return I=Jg({...t,matchUpStatus:U,removeScore:S,score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},removeWinningSide:!0,matchUp:l,matchUpId:a.matchUpId,matchUpStatusCodes:[]}),I.error?Nr({result:I,stack:u}):{...E}}function hI(t){const{matchUp:e,matchUpStatus:n,score:r,winningSide:i}=t,a="noDownStreamDependencies";if([wo,vo].includes(e?.matchUpStatus)&&![wo,vo].includes(n)){const e=mI(t);if(e.error)return Nr({result:e,stack:a})}const o=n===wo,s=Tl({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&&Op(e),{setFormat:a,finalSetFormat:o,bestOf:s}=i??{},c=s&&r===s&&o||a;return c?.timed||!1}(t.inContextMatchUp),u=t.removeScore||!c&&![Po,fo].includes(n||Po),d=t.isCollectionMatchUp&&t.dualMatchUp.winningSide&&!t.projectedWinningSide||e.winningSide&&!i&&!Tl({score:r}),p=n&&n!==Ro,l=n=>{let r;const{structure:i,drawDefinition:a,dualMatchUp:o,disableAutoCalc:s}=t;if(o?._disableAutoCalc&&!1!==s)return cI(t);const{connectedStructureIds:c}=sI({drawDefinition:a,structure:i,matchUp:e});c.length&&(console.log({connectedStructureIds:c}),r=!0),Object.assign(t,{removeScore:n});const u=Xg(t);if(u.error)return u;if(t.removingQualifier&&t.appliedPolicies?.[ya]?.autoRemoveQualifiers){const e=function(t){let e;const{inContextDrawMatchUps:n,inContextMatchUp:r,drawDefinition:i}=t,a=t.targetData.targetLinks?.winnerTargetLink;if(a.target.feedProfile===ts){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===Ro&&!dI({inContextDrawMatchUps:n,drawDefinition:i,targetData:Nc({matchUpId:s.matchUpId,inContextDrawMatchUps:n,drawDefinition:i})})){const{structure:n}=Vs({structureId:s.structureId,drawDefinition:i}),r=qs({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]))}Sl({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 gI(t);const m=[Io,fo].includes(n)&&t.dualWinningSideChange;return Nr({result:(i||m)&&pI(t)||s&&l(u)||p&&aI(t)||d&&l(u)||e&&gI({...t,removeScore:!0})||{...E},stack:a})}function gI(t){if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){const e=Xg(t);if(e.error)return e}const e=Jg({...t});if(t.isCollectionMatchUp){const{matchUpTieId:e,drawDefinition:n,event:r,matchUpsMap:i}=t,{removeWinningSide:a}=Zg({tournamentRecord:t.tournamentRecord,matchUpId:e,drawDefinition:n,matchUpsMap:i,event:r});a&&console.log("REMOVE WINNING SIDE")}return Nr({result:e,stack:"scoreModification"})}function II({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=hf({drawDefinition:r,matchUpId:o});if(c.error)return c;if(c?.matchUp?.matchUpType!==mc)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=Hm({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 Jf({duplicateValues:!1,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o,timeItem:{itemType:Cu,itemDate:a,itemValue:u}})}function UI({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=hp({tournamentRecords:e,tournamentRecord:n,venueId:o});if(t.error)return t}return Jf({duplicateValues:!1,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:{itemType:Eu,itemValue:o}})}function SI({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=gp({tournamentRecords:e,tournamentRecord:n,courtId:s});if(t.error)return t;const a=t.venue?.venueId;UI({tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o,venueId:a})}return Jf({duplicateValues:!1,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o,timeItem:{itemType:Ou,itemDate:a,itemValue:s}})}function yI(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 Nr({result:{error:qt},stack:e});if(!jr(s))return Nr({result:{error:le},stack:e});if(!n){const t=hf({drawDefinition:a,matchUpId:c});if(t.error)return Nr({result:t,stack:e});n=t.matchUp}const u=ti(s),d=Cd({matchUp:n}).scheduledDate,p=u&&!d,l=Sp({matchUp:n}).timeModifiers||[];if(l?.length){const t=vI({disableNotice:!0,removePriorValues:r,tournamentRecord:i,timeModifiers:[],drawDefinition:a,matchUpId:c,matchUp:n});if(t?.error)return Nr({result:t,stack:e})}const m=ri(s,!0,p);return Jf({duplicateValues:!1,removePriorValues:r,tournamentRecord:i,drawDefinition:a,disableNotice:o,matchUpId:c,timeItem:{itemType:_u,itemValue:m}})}function vI({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,timeModifiers:i,matchUpId:a,matchUp:o}){const s="addMatchUpTimeModifiers";if(!a)return Nr({result:{error:qt},stack:s});if(void 0!==i&&!Array.isArray(i))return Nr({info:Vf("timeModifiers"),result:{error:Nn},stack:s});if(!o){const t=hf({drawDefinition:n,matchUpId:a});if(t.error)return Nr({result:t,stack:s});o=t.matchUp}let c=Sp({matchUp:o}).timeModifiers||[];const u=i.filter((t=>!c.includes(t)));if(i.length&&!u.length)return{...E};if(u.some((t=>Yu.includes(t)))){c=c.filter((t=>!Yu.includes(t)));const r=yI({disableNotice:!0,removePriorValues:t,scheduledTime:"",tournamentRecord:e,drawDefinition:n,matchUpId:a});if(r.error)return Nr({result:r,stack:s})}const d=i?.length?[...u,...c]:void 0;return Jf({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:a,timeItem:{itemType:Gu,itemValue:d}})}function wI(t,e){const n=xr.test(t)?t:Qr(t),r=ti(t)||ti(e)||$r(new Date);return new Date(`${r}T${n}`).getTime()}function TI({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=hf({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}=Fl({drawDefinition:s}));const R=n?.[d]?.matchUpIds;if(l.scheduledDate&&e&&R){const e=r?.filter((t=>(t.schedule?.scheduledDate||ti(t.schedule?.scheduledTime))&&R.includes(t.matchUpId))).map((({schedule:t})=>{const e=Br(t);return new Date(e).getTime()}));if(e?.length){const n=Br(l),r=new Date(n).getTime();if(Math.max(...e)>=r){if(t)return Nr({result:{error:O},stack:f});g=O}}}if(void 0!==w){const t=PI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,scheduledDate:w,matchUpId:d});if(t?.error)return Nr({result:t,stack:f,context:{scheduledDate:w}})}if(void 0!==T){const t=yI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,scheduledTime:T,matchUpId:d,matchUp:h});if(t?.error)return Nr({result:t,stack:f,context:{scheduledTime:T}})}if(void 0!==P){const t=bI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,matchUpId:d,startTime:P,event:m});if(t?.error)return Nr({result:t,stack:f,context:{startTime:P}})}if(void 0!==D){const t=RI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,matchUpId:d,stopTime:D,event:m});if(t?.error)return Nr({result:t,stack:f,context:{stopTime:D}})}if(void 0!==v){const t=MI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,resumeTime:v,matchUpId:d,event:m});if(t?.error)return Nr({result:t,stack:f,context:{resumeTime:v}})}if(void 0!==I){const t=NI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,matchUpId:d,endTime:I,event:m});if(t?.error)return Nr({result:t,stack:f,context:{endTime:I}})}if(void 0!==S){const t=II({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,matchUpId:d,courtIds:S});if(t?.error)return Nr({result:t,stack:f,context:{courtIds:S}})}if(void 0!==U&&void 0!==w){const t=SI({courtDayDate:w,disableNotice:!0,removePriorValues:i,tournamentRecords:a,tournamentRecord:o,drawDefinition:s,matchUpId:d,courtId:U});if(t?.error)return Nr({result:t,stack:f,context:{courtId:U}})}if(void 0!==N){const t=UI({disableNotice:!0,removePriorValues:i,tournamentRecords:a,tournamentRecord:o,drawDefinition:s,matchUpId:d,venueId:N});if(t?.error)return Nr({result:t,stack:f,context:{venueId:N}})}if(void 0!==y&&p(y)){const t=DI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,courtOrder:y,matchUpId:d});if(t?.error)return Nr({result:t,stack:f,context:{courtOrder:y}})}if(void 0!==b){const t=vI({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,timeModifiers:b,matchUpId:d,matchUp:h});if(t?.error)return Nr({result:t,stack:f,context:{timeModifiers:b}})}return c||hl({tournamentId:o?.tournamentId,eventId:m?.eventId,context:f,drawDefinition:s,matchUp:h}),g?{...E,warnings:[g]}:{...E}}function PI({scheduledDate:t,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a}){if(!a)return{error:qt};const o=t&&_r.test(t);if(t&&!o)return{error:pe};return Jf({duplicateValues:!1,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:{itemValue:ti(t),itemType:ku}})}function DI({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 Jf({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:i,matchUpId:o,timeItem:{itemType:Fu,itemValue:s}})}function bI({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,startTime:a,event:o}){if(!i)return{error:qt};if(!jr(a))return{error:le};const{matchUp:s}=hf({drawDefinition:n,event:o,matchUpId:i}),{scheduledDate:c}=Cd({matchUp:s}),u=(s?.timeItems??[]).filter((t=>[Bu,Vu,ju].includes(t?.itemType))).map((t=>wI(t.itemValue,c))).reduce(((t,e)=>!t||e<t?e:t),void 0);if(!u||wI(a,c)<u){s?.timeItems&&(s.timeItems=s.timeItems.filter((t=>t.itemType!==Lu)));const o=ri(a,!0,!0);return Jf({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,timeItem:{itemType:Lu,itemValue:o}})}return{error:un}}function NI({validateTimeSeries:t=!0,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,endTime:o,event:s}){if(!a)return{error:qt};if(!jr(o))return{error:le};const{matchUp:c}=hf({drawDefinition:r,event:s,matchUpId:a}),{scheduledDate:u}=Cd({matchUp:c}),d=(c?.timeItems??[]).filter((t=>[Lu,Vu,Bu].includes(t?.itemType))).map((t=>wI(t.itemValue,u))).reduce(((t,e)=>!t||e>t?e:t),void 0);if(!t||!d||wI(o,u)>d){c?.timeItems&&(c.timeItems=c.timeItems.filter((t=>t.itemType!==ju)));const t=ri(o,!0,!0);return Jf({duplicateValues:!1,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:{itemType:ju,itemValue:t}})}return{error:on}}function RI({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,stopTime:a,event:o}){if(!i)return{error:qt};if(!jr(a))return{error:le};const{matchUp:s}=hf({drawDefinition:n,event:o,matchUpId:i}),{scheduledDate:c}=Cd({matchUp:s}),u=s?.timeItems??[];if(u.reduce(((t,e)=>e.itemType===ju||t),void 0))return{error:sn};const d=u.filter((t=>[Lu,Vu,Bu].includes(t?.itemType))).sort(((t,e)=>wI(t.itemValue,c)-wI(e.itemValue,c))),p=d[d.length-1],l=p&&p.itemType===Bu,m=d.filter((t=>!l||t.createdAt!==p.createdAt)).map((t=>wI(t.itemValue,c))).reduce(((t,e)=>!t||e>t?e:t),void 0);if(wI(a,c)>m){if(s?.timeItems&&l){const t=p.createdAt;s.timeItems=s.timeItems.filter((e=>e.createdAt!==t))}return Jf({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,timeItem:{itemValue:ri(a,!0,!0),itemType:Bu}})}return{error:cn}}function MI({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,resumeTime:i,matchUpId:a,event:o}){if(!a)return{error:qt};if(!jr(i))return{error:le};const{matchUp:s}=hf({drawDefinition:n,event:o,matchUpId:a}),{scheduledDate:c}=Cd({matchUp:s}),u=s?.timeItems??[];if(u.reduce(((t,e)=>e.itemType===ju||t),void 0))return{error:sn};const d=u.filter((t=>[Lu,Vu,Bu].includes(t?.itemType))).sort(((t,e)=>wI(t.itemValue,c)-wI(e.itemValue,c))),p=d[d.length-1],l=p&&p.itemType===Vu,m=d.filter((t=>!l||t.createdAt!==p.createdAt)).map((t=>wI(t.itemValue,c))).reduce(((t,e)=>!t||e>t?e:t),void 0);if(wI(i,c)>m){if(s?.timeItems&&l){const t=p.createdAt;s.timeItems=s.timeItems.filter((e=>e.createdAt!==t))}return Jf({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:a,timeItem:{itemValue:ri(i,!0,!0),itemType:Vu}})}return{error:dn}}function AI({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:Vf("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?Op(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&&[yo,bo,Mo].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 EI(t){const e="setMatchUpStatus";t.matchUpStatus&&[Mo,wo].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&&[Io,Po,fo,Ro].includes(u)&&d)return{error:Nn,winningSide:d,matchUpStatus:u};if(![void 0,...Co].includes(u))return Nr({result:{error:_t},info:"matchUpStatus does not exist",stack:"setMatchUpStatus"});const f=Wc({drawDefinition:c}),{matchUps:h}=el({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===go)return{context:"Cannot have Bye with winningSide",error:xt,matchUpStatus:u};const U=I?.structureId,{structure:S}=Vs({drawDefinition:c,structureId:U}),y=I?.drawPositions?.filter(Boolean);let v;if(g.matchUpType===fc){if(o)Cr({extension:{name:Va,value:!0},element:g});else if(s){const e=g.winningSide;Ar({name:Va,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})}nh({tournamentId:a?.tournamentId,inContextDualMatchUp:I,eventId:l?.eventId,drawDefinition:c,dualMatchUp:g})}if(g.matchUpType===fc&&u&&[ho].includes(u))return{error:Nn,info:"Not supported for matchUpType: TEAM"};const w=I?.matchUpTieId,T=Nc({matchUpId:w||p,inContextDrawMatchUps:h,drawDefinition:c});if(m&&g.matchUpType!==fc&&!r){const t=g.matchUpFormat??S?.matchUpFormat??c?.matchUpFormat??l?.matchUpFormat,e=AI({existingMatchUpStatus:g.matchUpStatus,matchUpFormat:t,matchUpStatus:u,winningSide:d,score:m});if(e.error)return e}const P=g?.sides?[]:qs({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&&Eo.includes(u)&&!D)return Nr({info:"present in participantRequiredMatchUpStatuses",context:{matchUpStatus:u,bothSideParticipants:D},result:{error:_t}});const b=Fc({policyTypes:[ya],tournamentRecord:a,drawDefinition:c,event:l})?.appliedPolicies??{};"object"==typeof t.policyDefinitions&&Object.assign(b,t.policyDefinitions);const N=I?.stage===Vo&&1===I.finishingRound,R=N&&d,M=N&&g.winningSide&&!d&&(!t.matchUpStatus||t.matchUpStatus&&Dl({matchUpStatus:t.matchUpStatus}))&&(!t.outcome||!Tl({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}=hf({matchUpId:w,inContext:!0,drawDefinition:c,matchUpsMap:f,event:l});if(e){const n=Np({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=mi(i,void 0,!0);for(const t of d?.tieMatchUps||[])t.matchUpId===s.matchUpId&&(t.winningSide=r,t.score=u,Tl({score:u})||e?e&&(t.matchUpStatus=e):Object.assign(t,{...Wg}));a=a??Np({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=dI(t),C=Pl({matchUpStatus:u});if(!w){if(E&&!d&&(u&&Dl({matchUpStatus:u})||u&&[wo,vo].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=TI({disableNotice:!0,tournamentRecords:i,tournamentRecord:a,drawDefinition:c,matchUpId:p,schedule:O});if(t.error)return t}const F=g.matchUpType!==fc&&!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}=Xp(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))||[],hl({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}=qs({structure:t}),n=e?.find((({participantId:t})=>t===u)),r=e?.find((({participantId:t})=>t===p));n&&(n.participantId=p),r&&(r.participantId=u)})),Jg(t)}(t);const k=d&&!w||t.projectedWinningSide;Bl({method:e,activeDownstream:E,matchUpWinner:k,winningSide:d});const x=!E&&hI(t)||k&&function(t){const{matchUp:e,winningSide:n,matchUpTieId:r,dualWinningSideChange:i}=t;return n===e.winningSide||r&&!i?CI(t):Nr({stack:"winningSideWithDownstreamDependencies",result:{error:ve},context:{winningSide:n,matchUp:e}})}(t)||C&&CI(t)||{error:An};return Nr({result:x,stack:e})}function CI(t){const{tournamentRecord:e,matchUp:n,event:r}=t,i=t.isCollectionMatchUp&&n.winningSide&&!t.winningSide&&!Tl({score:t.score}),a=t.isCollectionMatchUp?t.matchUpStatus||i&&Ro||Uo:t.matchUpStatus||Uo,o=t.removeScore||[Io,Mo].includes(a)&&![Po,fo].includes(a),s=Jg({...t,matchUpStatus:a,removeWinningSide:i,removeScore:o});if(s.error)return s;if(t.isCollectionMatchUp){const{matchUpTieId:n,drawDefinition:i,matchUpsMap:a}=t,o=Zg({matchUpId:n,tournamentRecord:e,drawDefinition:i,matchUpsMap:a,event:r});if(o.error)return o;Object.assign(s,{tieMatchUpResult:o})}return s}function OI({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}=wp({event:t});return r?.flights?.forEach((t=>{t.flightNumber=e[t.drawId]})),{...E}}function FI({tournamentRecord:t,event:e}){if(!t)return{error:_};if(!e)return{error:Tt};const{flightProfile:n}=wp({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?OI({event:e,orderedDrawIdsMap:r}):{...E}}function kI({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),gl({drawDefinition:t}),{...E}}function xI({stageSequence:t=1,drawDefinition:e,drawSize:n,stage:r}){if(!e)return{error:j};if(!Iu({drawDefinition:e,stage:r}))return{error:At};const i=function({stage:t,drawDefinition:e}){return mu.reduce(((n,r)=>(Uu({drawDefinition:e,entryStatus:r,stage:t})||0)+n),0)}({drawDefinition:e,stage:r}),{qualifiersCount:a}=hm({drawDefinition:e,stageSequence:t,stage:r});if(n<i+a)return{error:rt};const{entryProfile:o}=Jc({attributes:[{[r]:{drawSize:n}}],drawDefinition:e});return Il({drawDefinition:e}),{...E,entryProfile:o}}function _I({qualifiersCount:t=0,drawDefinition:e,stage:n}){return e?Iu({drawDefinition:e,stage:n})?n!==Bo?{error:rt,info:"qualifiersCount can only be set for main stage"}:(Jc({attributes:[{[n]:{qualifiersCount:t}}],drawDefinition:e}),Il({drawDefinition:e}),{...E}):{error:At}:{error:j}}function LI({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}=lh(c);c.winCriteria=br({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=Xp({matchUpFilters:{matchUpTypes:[fc]},structure:r})?.matchUps??[]:e&&(o=rl({matchUpFilters:{matchUpTypes:[fc]},drawDefinition:e})?.matchUps??[]),{targetMatchUps:o.filter((e=>!e.winningSide&&e.matchUpStatus!==Uo&&(t||e.matchUpStatus!==To&&!Tl(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=dh(i)),t){const t=Zg({matchUpId:o.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,drawDefinition:n,event:a});if(t.error)return t;s=t.score}r&&!s&&hl({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=br(c),I=Ah({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 Il({drawDefinition:a,eventId:l?.eventId}),{...E}}function BI({tieFormat:t,orderMap:e}){const n=dh(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 VI({tournamentRecord:t,structureIds:e,orderMap:n,event:r}){const i=BI({tieFormat:r.tieFormat,orderMap:n});e?.length||(r.tieFormat=i);for(const i of r.drawDefinitions??[])jI({tournamentRecord:t,drawDefinition:i,structureIds:e,orderMap:n,event:r})}function jI({tournamentRecord:t,drawDefinition:e,structureIds:n,orderMap:r,event:i}){const a=BI({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=BI({tieFormat:a.tieFormat??e.tieFormat??i?.tieFormat,orderMap:r})),GI({eventId:i?.eventId,tournamentRecord:t,drawDefinition:e,structure:a,orderMap:r}),o.push(a.structureId));Il({drawDefinition:e,structureIds:o})}function GI({tournamentRecord:t,drawDefinition:e,structure:n,orderMap:r,eventId:i}){const a=Xp({matchUpFilters:{matchUpTypes:[fc]},structure:n})?.matchUps;for(const n of a)n.tieFormat&&(n.tieFormat=BI({tieFormat:n.tieFormat,orderMap:r}),hl({tournamentId:t?.tournamentId,drawDefinition:e,eventId:i,matchUp:n}))}function qI({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:mh({drawDefinition:r,structureId:o,matchUpId:s,eventId:c,event:d});if(l?.error)return Nr({result:l,stack:p});const m=l?.structure;u=u??l?.matchUp;const f=l?.tieFormat,h=dh(f);if(l=Ah({tieFormat:h}),l.error)return Nr({result:l,stack:p});const g=h?.collectionDefinitions?.find((t=>t.collectionId===a));if(!g)return Nr({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}=lh(h);h.winCriteria=br({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=Xp({matchUpFilters:{matchUpTypes:[fc]},structure:m})?.matchUps??[]:r?v=rl({matchUpFilters:{matchUpTypes:[fc]},drawDefinition:r})?.matchUps??[]:d&&(v=Al({matchUpFilters:{matchUpTypes:[fc]},drawDefinition:r})?.matchUps??[]);const w=(v||[]).filter((n=>{const r=n.tieMatchUps?.filter((t=>t.collectionId===a)),i=r?.some(Tl),o=!(!e||!n.tieFormat)&&Fh({descendant:n.tieFormat,ancestor:h})?.different;return t&&!i||!n.winningSide&&n.matchUpStatus!==Uo&&(t||n.matchUpStatus!==To&&!Tl(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=EI({matchUpId:e.matchUpId,tieMatchUpId:u?.matchUpId,winningSide:void 0,removeScore:!0,tournamentRecord:n,drawDefinition:r,event:d});if(t.error)return t;if(t=hf({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=dh(h)),t){const t=Zg({matchUpId:e.matchUpId,exitWhenNoValues:!0,tournamentRecord:n,drawDefinition:r,event:d});if(t.error)return t}hl({tournamentId:n?.tournamentId,eventId:d?.eventId,drawDefinition:r,context:p,matchUp:e})}T.length&&fl({tournamentId:n?.tournamentId,matchUpIds:T,eventId:d?.eventId,drawDefinition:r});const P=br(h);if(l=Ah({tieFormat:P}),l.error)return Nr({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};Il({drawDefinition:r,eventId:d?.eventId});const{appliedPolicies:D}=Fc({tournamentRecord:n});if(D?.audit?.[ro]){Bh({drawDefinition:r,auditData:br({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=as}){if(!r||!i)return{error:It};return{link:br({linkType:a,source:{roundNumber:n,structureId:r,finishingPositions:e},target:{feedProfile:ts,roundNumber:t,structureId:i}})}}function WI({roundPosition:t,roundNumber:e,idPrefix:n,uuids:r}){return n?`${n}-${e}-${t}`:r?.pop()||Ld()}function HI({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:WI({roundPosition:d,roundNumber:n,idPrefix:i,uuids:o})};u.push(f);const h={drawPositions:f.children.map((t=>t?.drawPosition)).filter(Boolean),matchUpStatus:Ro,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 zI({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}=HI({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}=HI({nodes:m,matchUpType:a,roundNumber:h,idPrefix:s,matchUps:f,isMock:u,uuids:d})),h++;const g=h-1;return f=Rl({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 YI(t){const e="generateQualifyingStructure";if(!t.drawDefinition)return Nr({result:{error:j},stack:e});if(t.drawSize&&!p(t.drawSize)||t.participantsCount&&!p(t.participantsCount)||t.qualifyingPositions&&!p(t.qualifyingPositions))return Nr({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 Nr({result:{error:it},context:{drawSize:n},stack:e});if(i&&i>=t.drawSize)return Nr({result:{error:Nn},context:{drawSize:n,qualifyingPositions:i},stack:e});let S,y,v,w,T,P=0;const{structureProfiles:D}=af({drawDefinition:u}),b=D[o];if(!b)return Nr({result:{error:Ut},context:{targetStructureId:o},stack:e});const N=u.matchUpType,R=f?`${f}-`:"",M=b.stage===Vo,A=c?.[Ua]?.namingConventions?.pre??Gp[Ua]?.namingConventions?.pre,C=M&&A?`${A}-`:"",O=l??(R?`${C}${Lm(Vo)} ${R}`:`${C}${Lm(Vo)}`);if(h===Rs){const{maxRoundNumber:t,structures:e,groupCount:r}=bf({structureName:l??O,structureId:m??U?.pop(),stage:Vo,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}=zI({qualifyingRoundNumber:r,qualifyingPositions:i,matchUpType:N,idPrefix:g,drawSize:n,isMock:I,uuids:U})),S||(S=y),v=Bm({structureName:l??O,structureId:m??U?.pop(),qualifyingRoundNumber:S,stage:Vo,matchUpFormat:d,stageSequence:1,matchUpType:N,roundLimit:S,matchUps:w}),f&&Cr({extension:{name:Za,value:f},element:v}),P=w?.filter((t=>t.roundNumber===S))?.length;const F=h===Rs?is:as,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 KI(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(!Sh({matchUpFormat:i}))return{error:kt};if(o){const t=hf({drawDefinition:r,matchUpId:o,event:s});if(t.error)return t;if(!t.matchUp)return{error:Wt};const e=t.matchUp;if(e?.matchUpType===ld)return{error:Yt,info:"Cannot set matchUpFormat when { matchUpType: TEAM }"};e.matchUpFormat=i,hl({tournamentId:n?.tournamentId,eventId:s?.eventId,context:"setMatchUpFormat",drawDefinition:r,matchUp:e})}else if(Array.isArray(e)){if(s?.eventType===ld)return{error:wt};for(const t of e){const e=Vs({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===ld)return{error:wt};const t=Vs({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),Il({drawDefinition:r,structureIds:e}),{...E}}function JI({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=WI({roundPosition:f.roundPosition,roundNumber:n,idPrefix:i,uuids:s}),g={roundPosition:f.roundPosition,drawPositions:[d],matchUpStatus:Ro,roundNumber:n,matchUpId:h};t&&(g.matchUpType=r),o&&(g.isMock=!0),a.push(g);const I={children:[f,p]};m.push(I)}return{roundNodes:m,matchUps:a,drawPosition:e?e-d:void 0}}function ZI(t){const e=t.drawSize;let{feedRoundsProfile:n,feedRounds:r=0,skipRounds:i=0,baseDrawSize:a}=t;const{linkFedFinishingRoundNumbers: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}=HI({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}=JI({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=Rl({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 XI(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=Bo,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?ZI(F):zI(F),x=Bm({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}=XI({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:os,source:{roundNumber:t,structureId:x.structureId},target:{roundNumber:1,feedProfile:ns,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 QI(t){const{finishingPositionOffset:e=0,playoffAttributes:n,stageSequence:r=1,staggeredEntry:i,structureName:a,stage:o=Bo,matchUpType:s,structureId:c,idPrefix:u,drawSize:d,isMock:p,uuids:l}=t,m={finishingPositionOffset:e,matchUpType:s,drawSize:d,idPrefix:u,isMock:p,uuids:l},{matchUps:f}=i?ZI(m):zI(m),h=Bm({structureName:a||n?.[0]?.name||Lm(Bo),structureId:c||l?.pop(),stageSequence:r,matchUpType:s,matchUps:f,stage:o}),g=[h],I=[];if(d>2){const r=d/2,{matchUps:i}=zI({finishingPositionOffset:e+r,idPrefix:u&&`${u}-c`,drawSize:r,matchUpType:s,isMock:p}),o=Lm(jo),c=n?.["0-1"]?.name??t.consolationStructureName??(a?`${a} ${o}`:o),m=Bm({structureName:c,matchUps:i,structureId:l?.pop(),stage:jo,stageSequence:1,matchUpType:s});g.push(m);const f={linkType:os,source:{roundNumber:1,structureId:h.structureId},target:{roundNumber:1,feedProfile:ns,structureId:m.structureId}};I.push(f)}return{...E,structures:g,links:I}}function tU({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?ns:rs,u=r-e<=2?r-e:2*(r-e-2)+2,d={linkType:os,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=ss,d.target.feedProfile=ns),o.includes(u)?d:void 0})).filter(Boolean)}function eU(t){const{playoffStructureNameBase:e,finishingPositionOffset:n,stageSequence:r=1,playoffAttributes:i,structureNameMap:a,staggeredEntry:o,stage:s=Bo,matchUpType:c,structureId:u,drawSize:d,idPrefix:p,isMock:l,uuids:m}=t,f={finishingPositionOffset:n,matchUpType:c,drawSize:d,idPrefix:p,isMock:l,uuids:m},{matchUps:h,roundsCount:g}=o?ZI(f):zI(f),I=t.structureName??i?.[0]?.name??Lm(Bo),U=Bm({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}=ZI({finishingPositionOffset:l,baseDrawSize:l,isConsolation:!0,feedRounds:1,matchUpType:a,idPrefix:s,isMock:u,uuids:p}),h=0===d&&n?.["0-1"]?.name||1===d&&n?.["0-3"]?.name,g=h||`${Lm(jo)} ${d+1}`,I=r?.[g]||g,U=t?`${t} ${I}`:I,S=Bm({matchUps:m,stage:jo,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:tU({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}=zI({idPrefix:p&&`${p}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:l}),n=i?.["3-4"]?.name??Lm(qo),r=a?.[n]||n,o=e?`${e} ${r}`:r,s=Bm({structureId:m?.pop(),matchUps:t,stageSequence:2,stage:qo,structureName:o,matchUpType:c}),u={linkType:os,source:{roundNumber:g-1,structureId:U.structureId},target:{structureId:s.structureId,feedProfile:ns,roundNumber:1}};S.push(s),y.push(u)}}return{structures:S,links:y,...E}}function nU(t){const{finishingPositionOffset:e,stageSequence:n=1,playoffAttributes:r,policyDefinitions:i,feedsFromFinal:a,staggeredEntry:o,structureName:s,stage:c=Bo,structureId:u,matchUpType:d,skipRounds:p,feedRounds:l,idPrefix:m,drawSize:f,isMock:h,uuids:g,fmlc:I}=t,U=t.feedPolicy||i?.[Da],S={finishingPositionOffset:e,matchUpType:d,skipRounds:p,drawSize:f,idPrefix:m,isMock:h,uuids:g},{matchUps:y}=o?ZI(S):zI(S),v=Bm({structureName:s||r?.[0]?.name||Lm(Bo),structureId:u||g?.pop(),stageSequence:n,matchUpType:d,matchUps:y,stage:c}),w=[v],T=[],P=f/2,{matchUps:D,roundsCount:b}=ZI({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??Lm(jo),n=t.playoffStructureNameBase?`${t.playoffStructureNameBase} ${e}`:e,i=Bm({matchUps:D,structureId:g?.pop(),stage:jo,stageSequence:1,structureName:n,matchUpType:d});w.push(i);const a=tU({consolationStructure:i,mainStructure:v,roundsCount:b,feedPolicy:U,fmlc:I});T.push(...a)}return{...E,structures:w,links:T}}function rU({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?.[Da];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=dl({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 Nr({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 Nr({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&&ls||t.drawType||ls;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:qo,stageSequence:o,matchUpType:d,drawSize:g,isMock:f,uuids:h},b=({playoffStructures:t,playoffLinks:n})=>{const[r]=t,a=iU({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===ls){const{matchUps:r}=zI({finishingPositionLimit:I+c,idPrefix:m&&`${m}-po`,finishingPositionOffset:I,matchUpType:d,drawSize:g,isMock:f,uuids:h}),a=Bm({structureId:t.structureId??h?.pop(),matchUpFormat:n,stage:qo,structureName:P,stageSequence:o,matchUps:r});S.push(a);const s=iU({playoffStructureId:a.structureId,finishingPositions:e,sourceStructureId:i});y.push(s),I+=c,U.push({structureId:a.structureId,finishingPositions:e})}else if([ds,ps,qo].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:qo,roundOffset:0,stageSequence:o,drawSize:g,isMock:f,uuids:h};v===ds?Object.assign(n,{playoffAttributes:t?.playoffAttributes??r??Cs,roundOffsetLimit:3}):v===ps&&Object.assign(n,{playoffAttributes:t?.playoffAttributes??r??Os,roundOffsetLimit:2});const a=XI(n);if(a.error)return a;if(a.links?.length&&y.push(...a.links),a.structures?.length&&S.push(...a.structures),S.sort(Ls),a.structureId){const t=iU({playoffStructureId:a.structureId,finishingPositions:e,sourceStructureId:i});y.push(t),U.push({structureId:a.structureId,finishingPositions:e})}I+=c}else if([fs,Ns,Ps,ws,ys,bs].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:qo,structureName:P,matchUpType:d,feedPolicy:p,drawSize:g,isMock:f},a={[fs]:{fmlc:!0,feedRounds:1},[bs]:{feedRounds:1},[Ps]:{feedsFromFinal:3},[ws]:{feedsFromFinal:2},[ys]:{feedsFromFinal:1}};Object.assign(r,a[v]||{});const{structures:o,links:s}=nU(r),[u]=o,l=iU({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([Rs].includes(v)){const{structures:e,links:n}=bf({...D,structureOptions:t.structureOptions||{groupSize:4}});b({playoffStructures:e,playoffLinks:n})}else if([hs].includes(v)){const{structures:t,links:e}=QI(D);b({playoffStructures:t,playoffLinks:e})}else if([Us].includes(v)){const{structures:t,links:e}=eU(D);b({playoffStructures:t,playoffLinks:e})}else if([cs].includes(v)){b({playoffStructures:[Bm({structureId:t.structureId??h?.pop(),structureName:t.structureName,finishingPosition:jc,stage:qo,stageSequence:o,matchUps:[]})],playoffLinks:[]})}}return{finishingPositionTargets:U,positionRangeMap:w,structures:S,links:y}}function iU({playoffStructureId:t,finishingPositions:e,sourceStructureId:n}){return{linkType:is,source:{structureId:n,finishingPositions:e},target:{structureId:t,feedProfile:ts,roundNumber:1}}}function aU(t){const e="genPlayoffStructure";if(!t.drawDefinition)return Nr({result:{error:j},stack:e});const r=dl(t);if(r.error)return Nr({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=mi(t.drawDefinition,!1,!0),{structure:v}=Vs({structureId:i,drawDefinition:y});if(!v)return Nr({result:{error:Ut},stack:e});if(v.structureType===Qo||v.structures)return function(t){const e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return Nr({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}=rU({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}=el({inContext:!0,drawDefinition:a}),U=d.map((({structureId:t})=>t)),S=g?.filter((({structureId:t})=>U.includes(t))).map(mo),y=I?.drawMatchUps?.filter((({matchUpId:t})=>S?.includes(t)));if(y?.length){const e=Np({drawDefinition:a,event:u})?.tieFormat;e&&y.forEach((n=>{const{tieMatchUps:r}=Eh({isMock:t.isMock,tieFormat:e,matchUp:n});Object.assign(n,{tieMatchUps:r,matchUpType:mc})}))}const{positionAssignments:v}=qs({structureId:n,drawDefinition:a}),w={};v?.forEach((t=>{const e=Fr({element:t,name:no}),n=e?.extension?.value,r=n?.groupOrder;r&&(w[r]||(w[r]=[]),w[r].push(t.participantId))}));const T=gg({provisionalPositioning:t.provisionalPositioning,structureId:n,applyPositioning:!0,event:t.event,tournamentRecord:i,drawDefinition:a});return T.error&&T.error?.code!==W.code?Nr({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}=ul(t);if(D)return Nr({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 Nr({result:{error:Nn},context:{validRoundNumbers:A},stack:e});A.forEach((t=>{if(!T?.includes(t))return Nr({result:{error:Nn},context:{roundNumber:t},stack:e})}))}d&&d.forEach((t=>{if(!P?.includes(t))return Nr({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 Nr({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=XI({exitProfile:`0-${t}`,addNameBaseToAttributeName:a,playoffStructureNameBase:o,finishingPositionOffset:d,playoffAttributes:u,exitProfileLimit:m,stage:qo,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 Nr({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:os,source:{structureId:i,roundNumber:t},target:{structureId:h.structureId,feedProfile:ns,roundNumber:1}};k.push(e)}}if(!F.length)return Nr({result:{error:Nn},info:"No structures generated",stack:e});y.structures.push(...F),y.links.push(...k);const{matchUps:x,matchUpsMap:_}=el({inContext:!0,drawDefinition:y}),L=F.map((({structureId:t})=>t)),B=x?.filter((({structureId:t})=>L.includes(t))).map(mo),V=_?.drawMatchUps?.filter((({matchUpId:t})=>B?.includes(t)));if(V?.length){const t=Np({drawDefinition:y,event:U})?.tieFormat;t&&V.forEach((e=>{const{tieMatchUps:n}=Eh({matchUp:e,tieFormat:t,isMock:I});Object.assign(e,{tieMatchUps:n,matchUpType:fc})}))}const G=x?.filter((t=>Qp({matchUp:t})&&t.structureId===i));G?.forEach((t=>{const{matchUpId:e,score:n,winningSide:r}=t,i=Nc({inContextDrawMatchUps:x,drawDefinition:y,matchUpId:e}),a=uI({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===go&&t.structureId===i));q?.forEach((t=>{const{matchUpId:e}=t,n=Nc({inContextDrawMatchUps:x,drawDefinition:y,matchUpId:e}),{targetLinks:{loserTargetLink:r},targetMatchUps:{loserMatchUpDrawPositionIndex:i,loserMatchUp:a}}=n;if(r&&a){const t=r.target.structureId,e=jl({drawPosition:a.drawPositions[i],structureId:t,tournamentRecord:l,drawDefinition:y,event:U});e.error&&console.log(e.error)}}));const $=[],H=Ml({inContextDrawMatchUps:x,drawDefinition:y,matchUpsMap:_}).goesToMap,{structure:z}=Vs({drawDefinition:t.drawDefinition,structureId:i}),{matchUps:Y}=Xp({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 oU(t){return sU({...t,itemType:"attachPlayoffStructures"})}function sU({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 Nr({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 Nr({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),Ml({drawDefinition:r});const m=i.map((t=>Xp({structure:t})?.matchUps||[])).flat();ml({tournamentId:n?.tournamentId,eventId:o?.eventId,drawDefinition:r,matchUps:m});const f=i.map((({structureId:t})=>t));if(Il({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,hl(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(wi("structureId"));if(n){Xm({element:n,timeItem:{itemValue:{structureIds:f,drawId:r.drawId},itemType:t}})}return{...E,addedStructureIds:h}}function cU(t){const{structures:e,links:n,matchUpModifications:r,error:i}=aU(t);if(i)return{error:i};const a=t.drawDefinition;return oU({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:r,drawDefinition:a,structures:e,links:n})}function uU(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&&Op(a),{bestOf:p,finalSetFormat:l,setFormat:m}=d??{},f=r||!(!e||!c||1===c),h=n?function({matchUpStatus:t}){const e={[bo]:"RET",[Mo]:"WO",[vo]:"DF/DF",[wo]:"WO/WO",[No]:"SUS",[fo]:"ABN",[yo]:"DEF",[So]:"DR"};return t&&e[t]||""}({matchUpStatus:i}):"",g=u?.sort(dU).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 dU(t,e){return t.setNumber-e.setNumber}function pU(t){const{matchUpFormat:e,matchUpStatus:n,winningSide:r,score:i}=t;if(!i)return{sets:[]};const a=i.sets||[];let o=uU({winnerFirst:!1,matchUpFormat:e,matchUpStatus:n,sets:a}),s=uU({winnerFirst:!1,reversed:!0,matchUpFormat:e,matchUpStatus:n,sets:a});const c=uU({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 lU(t){const e=_d(t);if(!t.drawDefinition){const n=t.tournamentRecord??(t.tournamentId&&e[t.tournamentId]);t.tournamentRecord||(t.tournamentRecord=n);const r=Tp({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}=bu({policyType:Ta,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=KI({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}=pU(f);f.score=t,f.score.sets=f.score.sets.filter((t=>t.side1Score||t.side2Score||t.side1TiebreakScore||t.side2TiebreakScore))}return EI({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 mU({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=Fc({tournamentRecord:r,drawDefinition:s,event:h}).appliedPolicies??{},U=i?.[ga]??I?.[ga];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 Nr({result:w,stack:g});let T=l?.tieFormat?void 0:mh({drawDefinition:s,structureId:d,matchUpId:p,eventId:m,event:h});if(T?.error)return Nr({result:{error:T.error},stack:g});const P=T?.structure;l=l??T?.matchUp;const D=l?.tieFormat??T?.tieFormat,b=dh(D);if(T=Ah({tieFormat:b}),T?.error)return Nr({result:{error:T.error},stack:g});if(e.collectionId){if(b.collectionDefinitions.map((({collectionId:t})=>t)).includes(e.collectionId))return Nr({context:{collectionId:e.collectionId},result:{error:Rn}})}else e.collectionId=Ld();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}=lh(b);b.winCriteria=br({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=br(b);if(T=Ah({tieFormat:k}),T?.error)return Nr({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=fU({updateInProgressMatchUps:t,collectionDefinition:e,structure:r,uuids:f});O.push(...n.newMatchUps),F.push(...n.targetMatchUps),C.push(r.structureId)}hU({modifiedMatchUps:F,eventId:h?.eventId,modifiedStructureIds:C,tournamentRecord:r,drawDefinition:s,addedMatchUps:O,stack:g})}else if(d&&P){P.tieFormat=k;const n=fU({updateInProgressMatchUps:t,collectionDefinition:e,structure:P,uuids:f});O.push(...n.newMatchUps),F=n.targetMatchUps,hU({modifiedMatchUps:F,eventId:h?.eventId,modifiedStructureIds:C,tournamentRecord:r,drawDefinition:s,addedMatchUps:O,stack:g})}else if(p&&l){if(!xh({matchUp:l,updateInProgressMatchUps:t}))return Nr({result:{error:Ue},stack:g});l.tieFormat=k;const n=Ch({collectionDefinition:e,matchUp:l,uuids:f});Array.isArray(l.tieMatchUps)||(l.tieMatchUps=[]),l.tieMatchUps.push(...n),O.push(...n),hU({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=fU({updateInProgressMatchUps:t,collectionDefinition:e,structure:n,uuids:f});C.push(n.structureId),O.push(...r.newMatchUps),F.push(...r.targetMatchUps)}hU({modifiedMatchUps:F,eventId:h?.eventId,tournamentRecord:r,drawDefinition:s,addedMatchUps:O,stack:g})}if(I?.audit?.[ro]){Bh({drawDefinition:s,auditData:br({drawId:s?.drawId,collectionDefinition:e,action:g,structureId:d,matchUpId:p,eventId:m})})}return{tieFormat:k,targetMatchUps:F,addedMatchUps:O,...E}}function fU({updateInProgressMatchUps:t,collectionDefinition:e,structure:n,uuids:r}){const i=[],a=Xp({matchUpFilters:{matchUpTypes:[fc]},structure:n})?.matchUps,o=a.filter((e=>xh({matchUp:e,updateInProgressMatchUps:t})&&!e.tieFormat));for(const t of o){const n=Ch({collectionDefinition:e,matchUp:t,uuids:r});Array.isArray(t.tieMatchUps)||(t.tieMatchUps=[]),t.tieMatchUps.push(...n),i.push(...n)}return{newMatchUps:i,targetMatchUps:o}}function hU({modifiedStructureIds:t,tournamentRecord:e,modifiedMatchUps:n,drawDefinition:r,addedMatchUps:i,eventId:a,stack:o}){ml({tournamentId:e?.tournamentId,matchUps:i,drawDefinition:r,eventId:a}),n?.forEach((t=>{hl({tournamentId:e?.tournamentId,drawDefinition:r,context:o,matchUp:t,eventId:a})})),Il({structureIds:t,drawDefinition:r,eventId:a})}function gU(t){const e=na(t,[{_anyOf:{[Pi]:!1,[bi]:!1,[Ni]:!1,[Hi]:!1},[Di]:!0}]);if(e.error)return e;const n=[],r=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(r){const e=IU(t,r);if(e.error)return e;n.push(...e?.applied??[]),t.drawDefinition&&Il({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=IU(t,t.tournamentRecords[r]);if(e.error)return e;n.push(...e?.applied??[])}}}return n.length?{...E,applied:n}:{error:te}}function IU(t,e){const n=Fc(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(!Ui(i))return{error:Nn};const{policyName:a,...o}=i;if(!o||!Object.keys(o).length||a&&!Ii(a))return{error:Nn};n[e]=t.policyDefinitions[e],r.push(e)}if(r?.length){return{...Cr({element:e,extension:{name:Fa,value:n}}),applied:r}}return{applied:r,error:te}}function UU({tournamentRecord:t,drawDefinition:e,flightProfile:n,drawName:r,drawId:i,event:a}){if(!r||"string"!=typeof r)return Nr({result:{error:Nn},context:{drawName:r}});n||(n=wp({event:a}).flightProfile);const o=n?.flights?.find((t=>t.drawId===i));if(o){o.drawName=r;Ea({event:a,extension:{name:qa,value:{...n,flights:n.flights}}})}return e&&(e.drawName=r,Il({tournamentId:t?.tournamentId,drawDefinition:e})),o||e?{...E,flight:o}:{error:j}}function SU(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}=Tp({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=lU({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 yU({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}=af({drawDefinition:t}),u=r[i],d=(t?.structures||[]).map((e=>{const{stage:n,stageSequence:r,structureId:i}=e,c=Wo[n],{inContextStructureMatchUps:d}=kl({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}=qs({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}=Ac({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}=bc({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 vU(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}=wp({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 Nr({result:{error:j},info:{sourceDrawId:U}});if(I&&I.drawId!==u.drawId)return Nr({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 Nr({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&&fu.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 Nr({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:qa,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:qa,value:{...g||{},flights:t}}}Ea({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=rl({drawDefinition:b})?.matchUps,e=t?.map(mo)??[],n=rl({drawDefinition:u})?.matchUps;if(!r){e?.length&&fl({matchUpIds:e,action:"modifyDrawDefinition",tournamentId:N,eventId:R}),n?.length&&ml({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));Il({drawDefinition:u,tournamentId:N,structureIds:t,eventId:R})}}else if(d.drawDefinitions.push(u),!r){const{matchUps:t}=rl({drawDefinition:u,event:d});t&&ml({tournamentId:c?.tournamentId,matchUps:t}),gl({drawDefinition:u,tournamentId:N,eventId:R})}return{...E,modifiedEventEntryStatusCount:h}}function wU({allowDuplicateParticipantIdPairs:t,returnParticipants:e,tournamentRecord:n,participants:r=[]}){if(!n)return{error:_};n.participants||(n.participants=[]);const i=n.participants.map((t=>t.participantId))||[];r.forEach((t=>{t.participantId||(t.participantId=Ld())}));const a=r.filter((t=>!i.includes(t.participantId))),o=r.filter((t=>i.includes(t.participantId))),s=a.filter((t=>t.participantType===Ks)),c=a.filter((t=>t.participantType!==Ks)),u=s.concat(...c),d=[];if(u.length){for(const e of u){const r=eh({allowDuplicateParticipantIdPairs:t,returnParticipant:!0,disableNotice:!0,tournamentRecord:n,participant:e});if(r.error)return r;r.success&&!r.existingParticipant&&d.push(r.participant)}d.length&&cr({topic:jd,payload:{tournamentId:n.tournamentId,participants:d}});const r={participants:e&&mi(d),addedCount:d.length,...E};return o.length&&Object.assign(r,{notAdded:o,info:Be}),br(r)}return{info:"No new participants to add",addedCount:0,...E}}function TU(t){const{matchUpIds:e=[],drawDefinition:n,roundNumber:r,newRound:i,isMock:a,event:o}=t;if("object"!=typeof n)return{error:j};let{participantIdPairings:s,matchUpsCount:c}=t;const u=t.structureId??(1===n.structures?.length&&n.structures?.[0]?.structureId);if("string"!=typeof u)return{error:It};const d=n.structures?.find((t=>t.structureId===u));if(!d)return{error:Ut};let l;const m=d.matchUps??[],f=m?.reduce(((t,e)=>(e.roundPosition&&(l=!0),(e?.roundNumber||0)>t?e.roundNumber:t)),0);if(!c){const t=n?.entries?.filter((t=>{const e=t.entryStatus;return fu.includes(e)}))??[],e=Math.floor(t?.length/2)||1;if(i)c=e;else{const t=r??f??1,n=e-(d.matchUps?.filter((e=>e.roundNumber===t))?.length??0);n>0&&(c=n)}}if(s&&!Array.isArray(s)||c&&!p(c)||e&&!Array.isArray(e)||!s&&!c)return{error:Nn,info:"matchUpsCount or pairings error"};if(d.structures||l||d.finishingPosition===ks)return{error:$};if(r&&r-1>(f||0))return{error:Nn,info:"roundNumber error"};const h=r??(i&&(f??0)+1||f||1);s=s??w(0,c).map((()=>({participantIds:[void 0,void 0]})));const g=s?.map(((r,i)=>{const o=r?.participantIds??[void 0,void 0];o.push(void 0,void 0);const s=o.slice(0,2).map(((t,e)=>br({sideNumber:e+1,participantId:t}))),c=e[i]??(e=>{if(!t.idPrefix&&!a)return;return`${n.drawId}-${t.idPrefix??"ah"}-${h}-${e}`})(i)??Ld();return{roundNumber:h,matchUpStatus:Ro,matchUpId:c,sides:s}}));if(g?.length){const t=Np({drawDefinition:n,event:o})?.tieFormat;t&&g.forEach((e=>{const{tieMatchUps:n}=Eh({tieFormat:t,matchUp:e,isMock:a});Object.assign(e,{tieMatchUps:n,matchUpType:fc})}))}return{matchUpsCount:g?.length??0,matchUps:g,...E}}function PU(t){return t.participantIdPairings.map((({participantIds:t})=>t.sort().join("|"))).sort().join("/")}function DU({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=bU(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=bU(n,i),o=r[a];return o>t?o:t}),0),d=s.reduce(((t,e)=>{const[n,r]=e.participantIds,a=bU(n,r),o=i[a];return o>t?o:t}),0);return{value:c,participantIdPairings:s,maxDelta:u,maxDiff:d}}function bU(t,e){return[t,e].sort(cm).join("|")}function NU({participantIds:t}){const e={},n=[];t.forEach((r=>{e[r]=t.filter((t=>t!==r)),e[r].forEach((t=>{const e=bU(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 RU="ELO",MU="NTRP",AU="WTN",EU={ELO:RU,NTRP:MU,TRN:"TRN",UTR:"UTR",WTN:AU},CU={[RU]:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!0},[MU]:{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]},[AU]:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!1,decimalsCount:2,range:[40,1]}},OU=0;function FU({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=CU[r]?.defaultInitialization??OU;return i.split("|").map((r=>{if(n===dd){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=bU(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=DU({actorsCount:o.length,valueSortedPairings:e,pairingValueMap:a,deltaObjects:i,valueObjects:r}),u=[PU(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=bU(t,n.opponent);if(!g.includes(c)){const d=DU({stipulated:[[t,n.opponent]],actorsCount:o.length,valueSortedPairings:e,pairingValueMap:a,deltaObjects:i,valueObjects:r});if(!u.includes(PU(d))){u.push(PU(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 kU=100,xU=100,_U=4e3;function LU({encounterValue:t=kU,sameTeamValue:e=xU,maxIterations:n=_U,generateMatchUps:r=!0,tournamentParticipants:i,participantIds:a,drawDefinition:o,adHocRatings:s,structureId:c,salted:u=.5,matchUpIds:d,eventType:p,structure:l,scaleName:m,idPrefix:f,isMock:h,event:g}){if(!o)return{error:j};if(!l&&!c)return{error:Ut};if(l||(l=Vs({drawDefinition:o,structureId:c}).structure),!Ui(l))return{error:yt};if(!a?.length)return{error:Fe};const{encounters:I}=function({matchUps:t}){const e=[];for(const n of t){const t=n.sides.map(wi("participantId"));if(2===t.length){const[n,r]=t,i=bU(n,r);e.includes(i)||e.push(i)}}return{encounters:e}}({matchUps:l?.matchUps??[]}),U={};for(const e of I)U[e]||(U[e]=0),U[e]+=t;const S=i?.filter((({participantType:t})=>t===Xs));if(S)for(const t of S){const n=t.individualParticipantIds??[],{uniquePairings:r}=NU({participantIds:n});for(const t of r)U[t]||(U[t]=0),U[t]+=e}const{uniquePairings:y,possiblePairings:v,deltaObjects:w}=NU({participantIds:a}),T={tournamentParticipants:i,possiblePairings:v,drawDefinition:o,participantIds:a,uniquePairings:y,maxIterations:n,adHocRatings:s,deltaObjects:w,valueObjects:U,eventType:p,scaleName:m,structure:l,salted:u},{candidatesCount:P,participantIdPairings:D,iterations:b,candidate:N}=FU(T);if(!P)return{error:vn};let R;if(r){const t=TU({structureId:l?.structureId,participantIdPairings:D,newRound:!0,drawDefinition:o,matchUpIds:d,idPrefix:f,isMock:h,event:g});if(t.error)return t;R=t.matchUps}const{maxDelta:M,maxDiff:A}=N;return{...E,participantIdPairings:D,candidatesCount:P,iterations:b,matchUps:R,maxDelta:M,maxDiff:A}}function BU(t){const{restrictEntryStatus:e,adHocRatings:n={},generateMatchUps:r,tournamentRecord:i,encounterValue:a,sameTeamValue:o,drawDefinition:s,scaleAccessor:c,maxIterations:u,matchUpIds:d,scaleName:p,idPrefix:l,salted:m,event:f}=t;if("object"!=typeof s||s.drawType&&s.drawType!==cs)return{error:V};let{participantIds:h,structureId:g}=t;const I=i?.isMock??t.isMock;if(!Array.isArray(s?.entries)&&h&&!Array.isArray(h))return{error:Nn,info:"Missing Entries"};const U=t.eventType??f?.eventType,S=s?.entries?.filter((t=>{const n=t.entryStatus;return!e||fu.includes(n)})).map(lo);if(h){const t=h.filter((t=>!S?.includes(t)));if(t?.length)return Nr({result:{error:Te},info:{invalidParticipantIds:t}})}else h=S;if(!g){const t=s?.structures?.filter((t=>1===t.stageSequence))?.reduce(((t,e)=>{const n=e.stage&&Wo[e.stage];return jp({drawDefinition:s,structure:e})&&n>(Wo[t?.stage]||1)?e:t}),void 0);g=t?.structureId}const y=s?.structures?.find((t=>t.structureId===g));if(!y)return{error:Ut};if(!jp({drawDefinition:s,structure:y}))return{error:V};const v=i.participants??[];for(const t of h??[]){const e=v?.find((e=>e.participantId===t));let r=VU({scaleName:`${p}.${ia}`,scaleAccessor:c,participant:e,eventType:U});!r&&p&&(r=VU({scaleAccessor:c,participant:e,scaleName:p,eventType:U})),r&&!n[t]&&(n[t]=r)}return LU({tournamentParticipants:v,generateMatchUps:r,participantIds:h,encounterValue:a,sameTeamValue:o,drawDefinition:s,maxIterations:u,adHocRatings:n,matchUpIds:d,structure:y,eventType:U,idPrefix:l,salted:m,isMock:I,event:f})}function VU({scaleType:t=oa,scaleAccessor:e,participant:n,scaleName:r,eventType:i}){const a=n&&em({scaleAttributes:{eventType:i??ud,scaleType:t,scaleName:r},participant:n}),o=a?.scaleItem?.scaleValue;return e&&Ui(o)?o[e]:o}function jU({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(!Mc(r))return{error:Nn,info:Vf("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===ks)return{error:$};return b(El({tournamentRecord:t,inContext:!1})?.matchUps?.map(mo)??[],r.map(mo))?{error:Ln,info:"One or more matchUpIds already present in tournamentRecord"}:(i.matchUps.push(...r),ml({tournamentId:t?.tournamentId,drawDefinition:e,matchUps:r}),Il({drawDefinition:e,structureIds:[n]}),{...E})}function GU({deleteExisting:t,event:e,flightProfile:n}){const r="attachFlightProfile";if(!n)return Nr({result:{error:ae},stack:r});if(!e)return Nr({result:{error:Tt},stack:r});const{flightProfile:i}=wp({event:e});if(i&&!t)return Nr({result:{error:xn},stack:r});if(e.drawDefinitions?.length)return Nr({result:{error:G},stack:r});return Ea({event:e,extension:{name:qa,value:n}}),{flightProfile:mi(n,!1,!0),...E}}function qU({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 Nr({result:{error:Nn},info:Vf("entryStatus"),stack:"removeScaleValues"});let s=a.entries;if(i){const{flightProfile:t}=wp({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=[Ku,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(lo)})}function $U(t){const e="resetTieFormat",{drawDefinition:n,event:r,uuids:i}=t,a=na(t,[{[bi]:!0,[ki]:!0}],e);if(a.error)return a;const o=Yf(t,[{[zi]:qi}]);if(o[Wi])return o;const s=t.tournamentRecord?.tournamentId,{matchUp:c,structure:u}=o?.matchUp??{};if(!c?.tieMatchUps)return Nr({result:{error:Yt},info:"Must be a TEAM matchUp",stack:e});if(!c.tieFormat)return{...E};const d=Np({structure:u,drawDefinition:n,event:r})?.tieFormat;if(!d)return Nr({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===Ro?1:0)-(e.matchUpStatus===Ro?1:0))),m.push(...r.slice(0,e)),p.push(...r.slice(3).map(mo));else if(m.push(...r),r.length<e){const n=Ch({collectionDefinition:t,matchUpsLimit:e-r.length,matchUp:c,uuids:i});f.push(...n)}}for(const t of c?.tieMatchUps||[])t.collectionId&&!l.includes(t.collectionId)&&p.push(t.matchUpId);return f.length&&(m.push(...f),ml({eventId:r?.eventId,matchUps:f,drawDefinition:n,tournamentId:s})),p.length&&fl({matchUpIds:p,eventId:r?.eventId,drawDefinition:n,tournamentId:s}),c&&(c.tieMatchUps=m,c.tieFormatId=void 0,c.tieFormat=void 0,hl({structureId:u?.structureId,eventId:r?.eventId,context:e,drawDefinition:n,tournamentId:s,matchUp:c})),{...E,newMatchUps:f,deletedMatchUpIds:p}}function WU({participantsCount:t,participantCount:e}){if(!(t=t??e))return{error:Nn};const n=u(t);return n?{drawSize:n}:Nr({result:{error:Nn},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function HU(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=kc({tournamentRecord:a,drawDefinition:o,event:s});if(t.error)return Nr({result:t,stack:c});n=t.policyDefinitions}const d=p(u);if(u&&!d)return Nr({result:{error:Nn},context:{participantsCount:u},stack:c});if(i&&!d)return Nr({result:{error:ke},stack:c});if(isNaN(r)){if(!u)return Nr({result:{error:it},stack:c});({drawSize:r}=WU({participantsCount:u}))}const l=i&&u||r;if(l&&l>r)return{error:Ve};const m=n?.[Pa];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 zU({policyDefinitions:t,drawDefinition:e,drawSize:n,drawId:r,event:i,stage:a}){if(!i)return{error:Tt};const{entries:o,stageEntries:s}=Om({drawDefinition:e,drawId:r,stage:a,event:i}),c=s.length,{drawSize:u}=WU({participantsCount:c}),d=HU({drawSize:n??u,participantsCount:c,policyDefinitions:t});if(d.error)return Nr({result:d,stack:"getEntriesAndSeedsCount"});const{seedsCount:p}=d;return{entries:o,seedsCount:p,stageEntries:s}}function YU({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:ca,scaleName:i,scaleDate:o}],participantId:e})))}}function KU(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}=ac({tournamentRecords:i,tournamentRecord:e,participantId:r});return a?{...em({participant:a,scaleAttributes:n}),tournamentId:o}:{error:Ee}}function JU({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)&&fu.includes(t.entryStatus))).map((t=>{const{participantId:r}=t,{scaleItem:i}=KU({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 ZU({qualifyingPositions:t,drawEntries:e=[],drawName:r,drawId:i,event:a,stage:o}){const s="addFlight";if(!a)return Nr({result:{error:Tt},stack:s});if(!r)return Nr({result:{error:ae},stack:s});if(e?.length){const t=(a.entries??[]).map(wi("participantId")),n=e.map(wi("participantId"));if(P(n,t).length!==n.length)return Nr({result:{error:Nn},stack:s})}const c=wp({event:a})?.flightProfile,u=c?.flights?.map((({flightNumber:t})=>!isNaN(t)&&n(t)))?.filter(Boolean)||[],d=Math.max(0,...u)+1,p={drawId:i||Ld(),flightNumber:d,drawEntries:e,drawName:r};o&&(p.stage=o),t&&(p.qualifyingPositions=t);if((c?.flights||[]).find((({drawId:t})=>t===p.drawId)))return Nr({result:{error:kn},stack:s});const l=(c?.flights||[]).concat(p);return Ea({event:a,extension:{name:qa,value:{...c||{},flights:l}}})}var XU={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}},QU={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}},tS={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}},eS={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}},nS={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}},rS={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}},iS={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}},aS={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}},oS={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}},sS={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}]},cS={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}},uS={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}},dS={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}},pS={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}},lS={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}},mS={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}},fS={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 hS="COLLEGE_DEFAULT",gS="COLLEGE_JUCO",IS="COLLEGE_D3",US="DOMINANT_DUO",SS="DOMINANT_DUO_MIXED",yS="LAVER_CUP",vS="TEAM_DOUBLES_3_AGGREGATION",wS="TIME_TENNIS_DUAL",TS="TIME_TENNIS_PRO_CIRCUIT",PS="USTA_BREWER_CUP",DS="USTA_OZAKI_CUP",bS="USTA_COLLEGE",NS="USTA_GOLD_TEAM_CHALLENGE",RS="USTA_LEVEL_1",MS="USTA_INTERSECTIONAL",AS="USTA_SECTION_BATTLE",ES="USTA_SOUTHERN_LEVEL_5",CS="USTA_TOC",OS="USTA_WTT_ITT",FS="USTA_ZONAL",kS={COLLEGE_D3:IS,COLLEGE_DEFAULT:hS,COLLEGE_JUCO:gS,DOMINANT_DUO:US,DOMINANT_DUO_MIXED:SS,LAVER_CUP:yS,TEAM_DOUBLES_3_AGGREGATION:vS,TIME_TENNIS_DUAL:wS,TIME_TENNIS_PRO_CIRCUIT:TS,USTA_BREWER_CUP:PS,USTA_OZAKI_CUP:DS,USTA_COLLEGE:bS,USTA_GOLD_TEAM_CHALLENGE:NS,USTA_INTERSECTIONAL:MS,USTA_LEVEL_1:RS,USTA_SECTION_BATTLE:AS,USTA_SOUTHERN_LEVEL_5:ES,USTA_TOC:CS,USTA_WTT_ITT:OS,USTA_ZONAL:FS},xS="STANDARD",_S={[xS]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[IS]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1,matchUpFormat:"SET1-S:8/TB7@7"},singles:{matchUpFormat:Sg,matchUpCount:6,matchUpValue:1},tieFormatName:IS,valueGoal:5},[hS]:{hydrate:!0,doubles:{matchUpCount:3,collectionValue:1,matchUpFormat:Sg},singles:{matchUpCount:6,matchUpValue:1,matchUpFormat:Sg},tieFormatName:hS,valueGoal:4},[gS]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1,matchUpFormat:"SET1-S:8/TB7"},singles:{matchUpCount:6,matchUpValue:1,matchUpFormat:Sg},tieFormatName:gS,valueGoal:5},[yS]:mS,[US]:cS,[SS]:iS,[vS]:QU,[wS]:aS,[TS]:rS,[PS]:oS,[DS]:sS,[bS]:uS,[NS]:XU,[MS]:nS,[RS]:dS,[AS]:eS,[ES]:tS,[OS]:pS,[CS]:fS,[FS]:lS},LS=t=>{const e=t?.namedFormat&&Object.keys(_S).includes(t.namedFormat)?t.namedFormat:xS,n=Array.isArray(t?.uuids)?t?.uuids:[];let r;const{category:i,gender:a}=t?.event??{},o=mi(_S[e],!1,!0),s=e=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return n?.pop()??Ld();const r=t?.event?.eventId;return n.pop()??`${r}-COL-${e+1}`};return o.hydrate?(r={winCriteria:{valueGoal:o.valueGoal},collectionDefinitions:[{collectionId:s(0),matchUpFormat:yg,collectionName:"Doubles",matchUpType:lc,...o.doubles},{collectionId:s(1),matchUpFormat:Sg,collectionName:"Singles",matchUpType:dc,...o.singles}]},o.tieFormatName&&(r.tieFormatName=o.tieFormatName)):(o.collectionDefinitions.forEach(((t,e)=>t.collectionId=s(e))),r=o),t?.hydrateCollections&&r.collectionDefinitions.forEach((t=>{i&&!t.category&&(t.category=i),a&&!t.gender&&(t.gender=a)})),r};const BS={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:cS,DOMINANT_DUO_MIXED:iS,LAVER_CUP:mS,TEAM_DOUBLES_3_AGGREGATION:QU,TIME_TENNIS_DUAL:aS,TIME_TENNIS_PRO_CIRCUIT:rS,USTA_BREWER_CUP:oS,USTA_OZAKI_CUP:sS,USTA_COLLEGE:uS,USTA_GOLD_TEAM_CHALLENGE:XU,USTA_INTERSECTIONAL:nS,USTA_LEVEL_1:dS,USTA_SECTION_BATTLE:eS,USTA_SOUTHERN_LEVEL_5:tS,USTA_TOC:fS,USTA_WTT_ITT:pS,USTA_ZONAL:lS};function VS({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=br({drawDefinitions:!!r.drawDefinitions?.length,entries:!!r.entries?.length});return{info:"entries/drawDefinitions cannot exist",error:Nn,context:t}}const o={eventType:ud,drawDefinitions:[],entries:[],startDate:i,endDate:a,...r};if(r.eventType===md)if(r.tieFormat){const t=Ah({tieFormat:r.tieFormat});if(t.error)return t}else if(r.tieFormatName){if(!BS[r.tieFormatName])return{context:{tieFormatName:r.tieFormatName},error:Nn};const t=LS({isMock:e?.isMock,namedFormat:r.tieFormatName,event:r});o.tieFormat=t}o.eventId||(o.eventId=Ld());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}=mr();if(t.includes(Vd)){const t=Al({event:r}).matchUps??[];ml({tournamentId:e?.tournamentId,eventId:r.eventId,matchUps:t})}for(const t of r.drawDefinitions||[])gl({drawDefinition:t})}return{...E,event:o}}}function jS({tournamentRecord:t,drawDefinition:e,participantIds:n,stageSequence:r,stage:i=Bo,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=GS({element:o,participantIds:n,stageSequence:r,stage:i});if(t.error)return t}if(e){const t=GS({element:e,participantIds:n,stageSequence:r,stage:i});if(t.error)return a?Nr({context:{drawPromotionError:t.error,drawId:e.drawId},result:{...E},stack:"promoteAlternates"}):t}return{...E}}function GS({participantIds:t,stageSequence:e,element:r,stage:i}){const a=(r.entries||[]).filter((t=>t.entryStatus===Xc)),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!==Xc));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=tu;const e=t?.entryPosition;isNaN(e)||r.entries.forEach((t=>{t.entryStatus===Xc&&t.entryPosition>e&&(t.entryPosition=t.entryPosition-1)}));const i=Math.max(...r.entries.filter((t=>t.entryStatus===tu&&!isNaN(t.entryPosition))).map((({entryPosition:t})=>n(t||0))),0);t.entryPosition=i||0}return{...E}}function qS({tournamentRecord:t,drawDefinition:e,participantId:n,entryPosition:r,skipRefresh:i,event:a}){if(!t)return{error:_};if(!n)return Nr({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=Zl({entries:a.entries})),e?.entries&&(o(e),e.entries=Zl({entries:e.entries}))),{...E}}function $S({tournamentRecord:t,event:e,startDate:n}){if(!t)return{error:_};if(!e)return{error:Tt};if(!_r.test(n))return{error:pe};const r=HS(t);if(r.error)return r;const{tournamentStartDate:i,tournamentEndDate:a}=r,o=new Date(ti(n)).getTime();if(!i||!a||o<i||o>a)return{error:pe};const s=e.endDate&&new Date(ti(e.endDate)).getTime();return s&&o>s&&(e.endDate=n),e.startDate=n,{...E}}function WS({tournamentRecord:t,event:e,endDate:n}){if(!t)return{error:_};if(!e)return{error:Tt};if(!_r.test(n))return{error:pe};const r=HS(t);if(r.error)return r;const{tournamentStartDate:i,tournamentEndDate:a}=r,o=new Date(ti(n)).getTime();if(!i||!a||o<i||o>a)return{error:pe};const s=e.startDate&&new Date(ti(e.startDate)).getTime();return s&&o<s&&(e.startDate=n),e.endDate=n,{...E}}function HS(t){const{startDate:e,endDate:n}=t;return _r.test(e)&&_r.test(n)?{tournamentStartDate:new Date(ti(e)).getTime(),tournamentEndDate:new Date(ti(n)).getTime()}:Nr({result:{error:me},context:{startDate:e,endDate:n}})}const zS={addAdHocMatchUps:jU,addCollectionDefinition:mU,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 Nr({result:{error:ae},stack:p});let l=c?void 0:mh({drawDefinition:r,structureId:o,matchUpId:s,eventId:u,event:d});if(l?.error)return Nr({result:l,stack:p});const m=l?.structure;c=c||l?.matchUp;const f=l?.tieFormat,h=f?.winCriteria.valueGoal,g=dh(f);if(l=Ah({tieFormat:g}),l.error)return Nr({result:l,stack:p});for(const t of g.collectionDefinitions){const{collectionId:e,collectionGroupNumber:n}=t;if(n&&i.includes(e))return Nr({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],LI({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:vU,addDrawDefinitionTimeItem:kI,addDrawEntries:ym,addEvent:VS,addEventEntries:Pm,addEventEntryPairs:function({allowDuplicateParticipantIdPairs:t,entryStage:e=Bo,entryStatus:n=Xc,participantIdPairs:r=[],tournamentRecord:i,drawDefinition:a,event:o,uuids:s}){if(!i)return{error:_};if(!o)return{error:Tt};if(o.eventType!==lc)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===Ks&&r?.sex?u.set(n,r.sex):e===Zs&&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===Hp)return!1;const e=t.map((t=>u.get(t)));let n=o.gender===zp&&(e[0]!==zp||e[1]!==zp)||o.gender===Jp&&(e[0]!==Jp||e[1]!==Jp);return o.gender===Yp&&(e.sort(cm),e[0]===Jp&&e[1]===zp||(n=!0)),n}));if(d.length)return{error:Pe,invalidParticipantIdPairs:d};const p=r.map((t=>({participantId:s?.pop()??Ld(),participantRole:Dm,individualParticipantIds:t,participantType:Zs}))),l=t?p:p.filter((t=>!c.find((e=>2===P(e,t.individualParticipantIds).length))));let m,f=[];if(l){const e=wU({allowDuplicateParticipantIdPairs:t,participants:l,returnParticipants:!0,tournamentRecord:i});if(e.error)return e;f=e.participants||[],m=e.info}const h=Pm({participantIds:r.map((t=>{const e=f.find((e=>2===P(e.individualParticipantIds,t).length));if(e)return e;const{participant:n}=Yc({tournamentRecord:i,participantIds:t});return n})).map((t=>t.participantId)),tournamentRecord:i,drawDefinition:a,entryStatus:n,entryStage:e,event:o});return l.length&&cr({payload:{participants:l},topic:jd}),{...h,info:m,newParticipantIds:l.map(lo)}},addFlight:ZU,addPlayoffStructures:cU,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=YI(t);if(e.error)return e;const{structure:n,link:r}=e;return n&&r?Ug({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 tf({tournamentRecord:e,timeItem:{itemType:"addQualifyingStructures",itemValue:br({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=xI({stage:Go,stageSequence:1,drawDefinition:t,drawSize:e});return n.error?n:(Il({drawDefinition:t}),{...E})}(t)},addVoluntaryConsolationStructure:Vm,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){Fh({descendant:t.tieFormat,ancestor:e}).different||(n=e.tieFormatId)}if(n)t.tieFormatId=n,delete t.tieFormat;else{const n=mi(t.tieFormat,void 0,!0);n.tieFormatId||(n.tieFormatId=Ld()),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,hl({tournamentId:t?.tournamentId,eventId:n.eventId,matchUp:i}))},s=t=>{const n=mi(t.tieFormat,void 0,!0);n.tieFormatId||(n.tieFormatId=Ld()),r.push(n),e+=1,o(t.matchUpId,n.tieFormatId)},c=Al({matchUpFilters:{matchUpTypes:[mc]},event:n}),u=c.matchUps??[];for(const t of u){let e;for(const n of r){t.tieFormat&&Fh({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 Wf({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=hf({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!==fc)return{error:Yt};if(!u?.length)return{error:Z};const p=Np({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!==Ks)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===dc&&s||a.matchUpType===lc&&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}=Yc({tournamentParticipants:a,participantIds:e});if(!n){const n=eh({participant:{participantType:Zs,participantRole:Dm,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=hf({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 hl({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=jl({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:i,event:o});if(n.error)return n}else{if(a)return{error:Fn};{const a=$f({tournamentRecord:t,drawDefinition:e,participantId:n,drawPosition:r,structureId:i,event:o});if(a.error)return a}}return{...E}},assignDrawPositionBye:jl,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 Nr({result:{error:Nn,context:{sideNumber:r}}});const{matchUp:s,structure:c}=hf({drawDefinition:e,matchUpId:i,event:a});if(!s)return{error:Wt};if(!!(c?.structures||e.drawType&&e.drawType!==cs||c?.matchUps?.find((({roundPosition:t})=>!!t))))return{error:et};if(!n&&(s?.score?.scoreStringSide1||ko.includes(s?.matchUpstatus)||s?.matchUpStatus&&[wo,vo].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);hl({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=yu({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=_f({...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:sh,attachConsolationStructures:function(t){return sU({...t,itemType:"attachConsolationStructures"})},attachFlightProfile:GU,attachPlayoffStructures:oU,attachQualifyingStructure:Ug,attachStructures:sU,automatedPlayoffPositioning:gg,automatedPositioning:hg,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=zU({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=JU({tournamentRecord:t,scaleAttributes:r,scaleSortMethod:d,sortDescending:u,entries:l,stage:c}).scaledEntries??[],{scaleItemsWithParticipantIds:g}=YU({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=SU({outcomes:i,tournamentRecord:r});if(t.error)return t}}return{...E}},checkInParticipant:Xf,checkOutParticipant:Zf,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===ks)return{error:$};const c=[],u=o?.filter((({matchUpId:t,score:n})=>(Tl({score:n})&&c.push(t),e.includes(t))))??[],d=u.map(wi("matchUpId"));if(d.length){a.matchUps=(a.matchUps??[]).filter((({matchUpId:t})=>!d.includes(t))),fl({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(wi("roundNumber"))));if(e.length){e.reverse();for(const r of e)a.matchUps.forEach((e=>{e.roundNumber&&e.roundNumber>r&&(e.roundNumber-=1,hl({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=Yg({positionAssignments:a.positionAssignments,matchUps:a.matchUps,tournamentRecord:t,drawDefinition:n,matchUpFormat:e,event:i});r.error&&console.log(r)}Il({structureIds:[r],eventId:i?.eventId,drawDefinition:n})}return{...E}},deleteDrawDefinitions:mf,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:Vf("drawIds")};const r=[],i=[],a=[],o=[];if(e.events=(e.events||[]).filter((t=>{if(n.includes(t.eventId)){const n={action:pf,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===dd?(t.entries||[]).map((({entryStatus:t,participantId:e})=>t!==su&&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(Zm({tournamentRecord:e}),r.length){cr({topic:$d,payload:r});tf({tournamentRecord:e,timeItem:{itemType:pf,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}=wp({event:i});if(o){const t=o.flights?.find((t=>t.drawId===r));if(t){const t=o.flights.filter((t=>t.drawId!==r));Ea({event:i,extension:{name:qa,value:{...o,flights:t}}})}}const s=i.drawDefinitions?.find((t=>t.drawId===r));if(s){const o=mf({drawIds:[r],eventId:i.eventId,tournamentRecord:e,autoPublish:t,auditData:n,event:i,force:a});if(o.error)return o}return FI({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}=wp({event:r});if(a){const o=a.flights?.map((({drawId:t})=>t)).filter(Boolean),s=mf({eventId:r.eventId,tournamentRecord:e,autoPublish:t,auditData:n,drawIds:o,event:r,force:i});return s.error?s:Oa({event:r,name:qa})}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=Fm({participantId:t,...n});e.success&&(r+=1),e.error&&i.push(e.error)}return r?{destroyedCount:r,...E}:{error:i}},destroyPairEntry:km,disableTieAutoCalc:function({drawDefinition:t,matchUpId:e,event:n}){if(!t)return{error:j};const{matchUp:r}=hf({drawDefinition:t,matchUpId:e,event:n});return Cr({extension:{name:Va,value:!0},element:r})},drawMatic:BU,enableTieAutoCalc:function({tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r}){if(!e)return{error:j};const{matchUp:i}=hf({drawDefinition:e,matchUpId:n,event:r});return i?.matchUpType!==mc?{error:Yt}:EI({enableAutoCalc:!0,tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r})},getAvailablePlayoffProfiles:dl,getAvailablePlayoffRounds:dl,luckyLoserDrawPositionAssignment:function(t){return function({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i}){return Wf({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i})}(t)},modifyCollectionDefinition:Vh,modifyDrawDefinition:function({tournamentRecord:t,drawDefinition:e,drawUpdates:n,drawId:r,event:i}){if(!Ui(n))return{error:Nn};const a=wp({event:i}).flightProfile,o=n.drawName&&UU({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){Ea({event:i,extension:{name:qa,value:{...a,flights:a.flights}}})}return e&&(n.policyDefinitions&&gU({policyDefinitions:n.policyDefinitions,drawDefinition:e}),Il({tournamentId:t?.tournamentId,drawDefinition:e})),{...E}},modifyDrawName:UU,modifyEntriesStatus:Ql,modifyEvent:function({tournamentRecord:t,eventUpdates:e,eventId:n,event:r}){const i="modifyEvent";if(!t)return Nr({result:{error:_},stack:i});if(!Ii(n))return Nr({result:{error:Tt},context:{eventId:n},stack:i});if(!Ui(e))return Nr({result:{error:Nn},context:{eventUpdates:e},stack:i});const a=r?.entries?.filter((({entryStatus:t})=>{const e=t;return[...fu,Xc].includes(e)})).map((({participantId:t})=>t))??[],o=a?mm({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||[Yp,Hp].includes(e.gender??"")||1===u.length&&u[0]===e.gender;if(e.gender&&!d)return Nr({context:{gender:e.gender,validGender:d},result:{error:Nn},stack:i});const p=(c.includes(ld)&&[ld]||c.includes(Ks)&&[cd]||c.includes(Zs)&&[dd]||[dd,cd,ld]).includes(e.eventType??"");return e.eventType&&!p?Nr({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=tu,unpairedParticipantIds:e=[],participantIdPairs:n=[],entryStage:r=Bo,tournamentRecord:i,event:a}){if(!i)return{error:_};if(!a)return{error:Tt};const o=i.participants??[],s=o.filter((t=>t.participantType===Ks)).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===Zs)).map((t=>t.individualParticipantIds)),p=wU({participants:n.filter((t=>!d.find((e=>2===P(e,t).length)))).map((t=>({participantType:Zs,participantRole:Dm,individualParticipantIds:t}))),tournamentRecord:i});if(p.error)return p;const l=n.map((t=>{const{participant:e}=Yc({tournamentRecord:i,participantIds:t});return e})).map((e=>({participantId:e,entryStatus:t,entryStage:r}))),m=e.map((t=>({entryStatus:su,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!==dd)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})=>[su,cu].includes(t))).map((({participantId:t})=>t))||[]).includes(t))return{error:Te};const s=(n.participants||[]).find((t=>t.participantId===i));if(s?.participantType!==Zs)return{error:we,participant:s};const c=s.individualParticipantIds,u=[t,...c.filter((t=>t!==e))],{participant:d}=Yc({participantIds:u,tournamentRecord:n});let p;if(d)p=d.participantId;else{const t=eh({participant:{participantId:o?.pop(),participantRole:Dm,individualParticipantIds:u,participantType:Zs},returnParticipant:!0,tournamentRecord:n});if(t.error)return t;p=t.participant.participantId}const{flightProfile:l}=wp({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=Cm({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}=Vs({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}=yu({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 Ul({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(!Ah({tieFormat:n}).valid)return Nr({result:{error:Lt},info:"falied validation",stack:d});const p=mh({drawDefinition:i,structureId:a,matchUpId:o,eventId:s,event:u});if(p.error)return Nr({result:p,stack:d});const{matchUp:l,tieFormat:m}=p,f=dh(m),g=Fh({descendant:n,ancestor:f});if(g.invalid)return Nr({context:{invalid:g.invalid},result:{error:Lt},stack:d});if(!g?.different)return Nr({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(wi("collectionId")),w=[];let T;const P=n.tieFormatName;for(const e of n.collectionDefinitions){if(v.includes(e.collectionId))continue;const n=Vh({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 Nr({result:n,stack:d});n.tieFormat&&(T=n.tieFormat)}for(const e of y){const n=mU({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 Nr({result:n,stack:d});n.tieFormat&&(T=n.tieFormat)}for(const n of S){const c=qI({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 Nr({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:dh(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 Nr({result:{error:Nn},context:{orderMap:i}});if(a&&s?.tieFormat)VI({tournamentRecord:t,event:s,orderMap:i});else if(r){const n=e&&hf({drawDefinition:e,matchUpId:r});if(n?.error)return n;if(!(o=n.matchUp))return{error:zt};o?.tieFormat&&(o.tieFormat=BI({tieFormat:o.tieFormat,orderMap:i}),hl({tournamentId:t?.tournamentId,eventId:s?.eventId,drawDefinition:e,matchUp:o}))}else if(n){const r=Vs({drawDefinition:e,structureId:n});if(r.error)return r;const a=r.structure;if(a?.tieFormat)a.tieFormat=BI({tieFormat:a.tieFormat,orderMap:i}),GI({eventId:s?.eventId,tournamentRecord:t,drawDefinition:e,structure:a,orderMap:i}),Il({drawDefinition:e,structureIds:[a.structureId]});else if(e.tieFormat)jI({structureIds:[n],tournamentRecord:t,drawDefinition:e,orderMap:i,event:s});else{if(!s?.tieFormat)return{error:On};VI({structureIds:[n],tournamentRecord:t,orderMap:i,event:s})}}else{if(!e?.tieFormat)return{error:On};jI({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}:jS({...t,participantIds:[e].filter(Boolean)})},promoteAlternates:jS,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}=yU({tournamentRecord:e});if(a.canBePruned.includes(r)){const o=a.matchPlay.includes(r),s=a.drawAnalysis[r],{structures:[c]}=js({stageSequence:1,drawDefinition:n,stage:Bo}),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(mo),l=d.map(mo).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(mo),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}fl({tournamentId:e?.tournamentId,matchUpIds:l,drawDefinition:n}),Il({drawDefinition:n})}return{...E,matchUps:i}},qualifierDrawPositionAssignment:function(t){return function({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i}){return Wf({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i})}(t)},refreshEventDrawOrder:FI,removeCollectionDefinition:qI,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:mh({drawDefinition:r,structureId:a,matchUpId:o,eventId:c,event:u});if(p?.error)return Nr({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=dh(m);if(p=Ah({tieFormat:g}),p.error)return Nr({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=LI({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}=Fc({tournamentRecord:n});if(t?.audit?.[ro]){Bh({drawDefinition:r,auditData:br({drawId:r?.drawId,collectionGroupNumber:e,action:d,structureId:a,matchUpId:o,eventId:c})})}}return Nr({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}=hf({drawDefinition:t,event:e,matchUpId:n});return r?Ar({name:_a,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(Jl({drawDefinition:n,stages:i}).assignedParticipantIds??[],e))return{error:Le};const o=t=>{const n=t.participantId;return!e.includes(n)},{flightProfile:s}=wp({event:a}),c=s?.flights?.find((t=>t.drawId===r));return c?.drawEntries&&(c.drawEntries=c.drawEntries.filter(o),t&&(c.drawEntries=Zl({entries:c.drawEntries}))),n?.entries&&(n.entries=n.entries.filter(o),t&&(n.entries=Zl({entries:n.entries}))),{...E}},removeDrawPositionAssignment:xm,removeEventEntries:wm,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}=hf({drawDefinition:e,matchUpId:r,event:i});return a?o?.structures||e.drawType&&e.drawType!==cs||o?.matchUps?.find((({roundPosition:t})=>!!t))?{error:et}:(a.sides?.forEach((t=>{t.sideNumber===n&&delete t.participantId})),hl({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 Nr({result:{error:ae},info:"roundNumber required"});const s=Vs({drawDefinition:r,structureId:i});if(s.error)return s;const c=s.structure;return c?.structures?{error:$}:jp({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&&(!ko.includes(e.matchUpStatus)||t);return n&&c.push(e.matchUpId),!n}));if(c.length){fl({matchUpIds:c,drawDefinition:n,tournamentId:r,eventId:o});e.some((t=>t.roundNumber===i))||(e.forEach((t=>{t.roundNumber>i&&(t.roundNumber-=1,hl({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:qU,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 Nr({result:{error:Ut},stack:i});if(!a.stage||![Bo,Vo].includes(a.stage)||a.stage===Bo&&1!==a.stageSequence)return Nr({result:{error:$},stack:i});const o=a.seedAssignments?.find((t=>t.participantId===n));return o?{...E}:Nr({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,qU({tournamentRecord:t,scaleAttributes:{eventType:a.eventType,scaleType:ca,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(Xp({structure:s}).matchUps.some((({score:t})=>Tl({score:t})))){const n=Fc({tournamentRecord:t,drawDefinition:e,structure:s,event:r})?.appliedPolicies;if(!(i??n?.[Ta]?.allowDeletionWithScoresPresent?.structures))return{error:qn}}const c=a.find((({stage:t,stageSequence:e})=>t===Bo&&1===e)),u=n===c?.structureId,d=a.filter((({stage:t})=>t===Vo)).map(wi("structureId"));if(u&&!d.length)return{error:F};const p=a.map(wi("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}=Vs({structureId:t,drawDefinition:e}),{matchUps:i}=Xp({structure:r}),a=uo(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}=el({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(wi("matchUpId"));l.push(...t),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return m&&Ig({drawDefinition:e}),fl({tournamentId:t?.tournamentId,matchUpIds:l,action:"removeStructure",eventId:r?.eventId,drawDefinition:e}),Il({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 Nr({result:{error:Ae},stack:a});const o=th(t);if(o.error)return o;const{appliedPolicies:s}=Fc({tournamentRecord:e,drawDefinition:n,event:i}),c=t.policyDefinitions?.[ga]??s?.[ga]??Tm[ga],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 Nr({result:{error:zt},stack:a});const y=p?.sides?.find((t=>t.participant?.participantId===r||t.participant?.individualParticipantIds?.includes(r)));if(!y)return Nr({result:{error:Ee},stack:a});if(!y.substitutions?.length&&(Tl({score:p?.score})||p?.winningSide))return Nr({result:{error:_n},stack:a});const v=d?.sides?.find((({sideNumber:t})=>t===y.sideNumber))?.participantId;if(!v)return Nr({result:{error:Ee},stack:a});const w=mm({participantFilters:{participantIds:[r]},tournamentRecord:e})?.participants?.[0];if(!w)return Nr({result:{error:Ee},stack:a});if(g===dc&&w.participantType===Zs)return Nr({result:{error:we},stack:a});const T=w.participantType===Ks?[r]:w.individualParticipantIds;nh({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 Nr({result:{error:Ee,context:{participantId:r}}});const{modifiedLineUp:D,previousParticipantIds:b}=ih({collectionPosition:m,teamParticipantId:v,dualMatchUpSide:P,participantIds:T,drawDefinition:n,collectionId:h});if(P.lineUp=D,v&&S&&Gf({participantId:v,lineUp:D,drawDefinition:n,tieFormat:S}),g===lc&&w.participantType===Ks){const t=p?.sides?.find((t=>t.sideNumber===P?.sideNumber)),{participantId:n}=t??{},i=n&&mm({participantFilters:{participantIds:[n]},tournamentRecord:e,withDraws:!0})?.participants?.[0];if(!i)return Nr({result:{error:Ee},stack:a});{const t=i?.individualParticipantIds?.filter((t=>t!==r))??[];if(b&&t.push(...b),t.length>2)return Nr({result:{error:Pe},stack:a});if(i.draws?.length){if(1===t.length){const{participant:n}=Yc({participantIds:t,tournamentRecord:e});if(!n){const n=eh({participant:{participantRole:Dm,individualParticipantIds:t,participantType:Zs},pairOverride:!0,tournamentRecord:e});if(n.error)return Nr({result:n,stack:a})}}}else if(t.length){i.individualParticipantIds=t;const n=oh({participant:i,pairOverride:!0,tournamentRecord:e});if(n.error)return Nr({result:n,stack:a})}else{const t=Cm({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)}hl({tournamentId:e?.tournamentId,matchUp:U,context:a,drawDefinition:n})}}return hl({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(!Ui(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:rh,resetDrawDefinition:function({tournamentRecord:t,removeScheduling:e,drawDefinition:n}){if(!n)return{error:j};const r=Wc({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&&[Vo,Bo].includes(s)||(a.positionAssignments=o.map((t=>(delete t.participantId,t))),a.seedAssignments=[]);const{matchUps:u}=Xp({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!==go&&Object.assign(c,Wg),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&&![Cu,Ou,Eu,xu,ku,_u].includes(t.itemType)))),hl({tournamentId:t?.tournamentId,context:"resetDrawDefiniton",drawDefinition:n,matchUp:c})}}}return Il({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=hf({drawDefinition:n,matchUpId:r})?.matchUp;if(!a?.tieMatchUps)return{error:Yt};const o=hf({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&&Gf({drawDefinition:n,participantId:e,lineUp:[],tieFormat:t})}hl({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 Nr({result:{error:j},stack:a});if(!r)return Nr({result:{error:qt},stack:a});if(!Ii(r))return Nr({result:{error:Nn,matchUpId:r},stack:a});const o=Wc({drawDefinition:n}),{matchUps:s}=el({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!==md)return{error:Yt};const d=Nc({inContextDrawMatchUps:s,drawDefinition:n,matchUpId:r}),p=u?.structureId,{structure:l}=Vs({drawDefinition:n,structureId:p});if(Object.assign(t,{inContextDrawMatchUps:s,inContextMatchUp:u,matchUpsMap:o,targetData:d,structure:l,matchUp:c}),dI(t))return{error:ve};if(c.tieMatchUps?.length)for(const t of c.tieMatchUps){const o=EI({matchUpId:t.matchUpId,matchUpTieId:r,winningSide:void 0,removeScore:!0,tournamentRecord:e,drawDefinition:n,event:i});if(o.error)return Nr({result:o,stack:a})}const m=Zg({event:t.event,removeScore:!0,tournamentRecord:e,drawDefinition:n,matchUpsMap:o,matchUpId:r});if(m.error)return Nr({result:m,stack:a});if(t.tiebreakReset&&!m.tieFormatRemoved){const t=Np({drawDefinition:n,structure:l,event:i})?.tieFormat;if(c.tieFormat&&t){const{matchUpCountDifference:a,descendantDifferences:o,ancestorDifferences:s,valueDifference:u}=Fh({descendant:c.tieFormat,ancestor:t});if(1===o.collectionIds.length&&!s.collectionIds.length&&!s.groupsCount&&1===a&&1===u){const t=$U({tournamentRecord:e,drawDefinition:n,matchUpId:r,event:i});if(t.error)return t}}}return{...E}},resetTieFormat:$U,resetVoluntaryConsolationStructure:function({tournamentRecord:t,drawDefinition:e,resetEntries:n,event:r}){if(!e)return{error:j};const i=e.structures?.find((t=>t.stage===Go));if(!i)return{error:Ut};const a=i.matchUps?.map((({matchUpId:t})=>t))||[];return i.positionAssignments=[],i.seedAssignments=[],i.matchUps=[],fl({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:a,drawDefinition:e}),n&&(e.entries=e.entries.filter((t=>t.entryStage!==Go))),Il({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=hf({drawDefinition:t,matchUpId:e});if(n.error)return n;r=n.matchUp}return"object"==typeof n&&n.score?.scoreStringSide1&&n.score?.scoreStringSide2?Cr({element:r,extension:{name:_a,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=po(e?.entries||[]);return t.length&&P(t,n).length<t.length?{error:Nn}:Aa({drawDefinition:e,extension:{name:Ya,value:t}})},setEntryPosition:qS,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=qS({skipRefresh:!0,tournamentRecord:t,drawDefinition:n,participantId:e,entryPosition:a,event:r});if(o.error)return o}return r?.entries&&(r.entries=Zl({entries:r.entries})),n?.entries&&(n.entries=Zl({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&&!_r.test(n))return{error:pe};if(r&&!_r.test(r))return{error:pe};if(n&&r){if(new Date(ti(n)).getTime()>new Date(ti(r)).getTime())return{error:Nn}}if(n){const r=$S({tournamentRecord:t,event:e,startDate:n});if(r.error)return r}if(r){const n=WS({tournamentRecord:t,event:e,endDate:r});if(n.error)return n}return{...E}},setEventEndDate:WS,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&&!Sh({matchUpFormat:o}))return Nr({result:{error:kt,matchUpFormat:o},stack:e});if(i&&!Array.isArray(i))return Nr({result:{error:Nn,scheduledDates:i},stack:e});if(c&&![cd,dd].includes(c))return Nr({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 Nr({result:{error:j},stack:e});if(l&&u&&r){const t=KI({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)&&Xp({matchUpFilters:{matchUpStatuses:[Ro]},structure:s}).matchUps,u=i&&Xp({matchUpFilters:{matchUpStatuses:[Ro]},contextFilters:{scheduledDates:i},afterRecoveryTimes:!1,inContext:!0,structure:s}).matchUps;if(c?.length){const r=u?u.map(mo):c.map(mo);for(const a of c)r.includes(a.matchUpId)&&(a.matchUpFormat=i?.length?o:void 0,hl({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===ld))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;Il({structureIds:S(e),drawDefinition:e})}else t.matchUpFormat!==o&&(t.matchUpFormat=o,h+=1);return h?{...E,modificationsCount:h}:{...E,info:Sn}},setMatchUpStatus:lU,setOrderOfFinish:function(t){return function({drawDefinition:t,finishingOrder:e}){if(!t)return{error:j};const n="setOrderOfFinish";if(!Array.isArray(e))return Nr({info:Vf("finishingOrder"),result:{error:Nn},stack:n});const{completedMatchUps:r,matchUpsMap:i}=nl({inContext:!0,drawDefinition:t}),a=r?.map(mo)??[],o=e.map(mo),{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 Nr({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 Nr({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 Nr({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 Nr({info:"Values not unique or greater than expected number of values",result:{error:Nn},stack:n});if(u.length){const e=tl({matchUpFilters:{matchUpIds:o},structureId:u[0],drawDefinition:t,matchUpsMap:i});if(e.error)return Nr({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=Vs({drawDefinition:r,structureId:t});if(s.error)return s;const c=s.structure;if(!c)return{error:Ut};const u=qs({structure:c}).positionAssignments?.map((({drawPosition:t})=>t)),d=o?.map((({drawPosition:t})=>t));if(P(u,d).length!==u?.length)return Nr({result:{error:Nn},info:"drawPositions do not match",stack:"setPositionAssignments"});const p=Wc({drawDefinition:r}),{matchUps:l}=el({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=jl({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=$f({provisionalPositioning:e,inContextDrawMatchUps:l,tournamentRecord:n,drawDefinition:r,participantId:u,drawPosition:s,matchUpsMap:p,structureId:t,event:i});if(a?.error)return a}}Sl({tournamentId:n?.tournamentId,drawDefinition:r,structure:c,event:i})}const a=t.map((({structureId:t})=>t));return Il({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)))||Nr({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}=Vs({drawDefinition:e,structureId:r});if(!o)return{error:Ut};let s=o;o.structures&&o.structureType===Qo&&(s=o.structures?.find((t=>t.positionAssignments?.find((t=>t.drawPosition===n)))));const c=s?.positionAssignments,u=c?.find((t=>t.drawPosition===n));u&&Cr({element:u,extension:{name:eo,value:i}});const d=(a?.eventType===fc||e.matchUpType===fc||(a?.tieFormat??e?.tieFormat??o?.tieFormat))&&{matchUpTypes:[fc]},{matchUps:p}=Xp({structure:s,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:d,event:a});return Yg({positionAssignments:c,tournamentRecord:t,drawDefinition:e,matchUpFormat:o?.matchUpFormat??e.matchUpFormat,matchUps:p,event:a}),Il({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 Nr({result:{error:Ae},stack:s});const{matchUp:c}=hf({drawDefinition:r,matchUpId:a,event:o});if(!c)return{error:Wt};if(!c.collectionId)return Nr({result:{error:Yt},stack:s});const u=Wc({drawDefinition:r}),{matchUps:d}=el({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(lo).filter((t=>t!==e));return f?.includes(t)?rh({newParticipantId:t,tieMatchUpId:a,existingParticipantId:e,substitution:!0,tournamentRecord:n,drawDefinition:r,event:o}):Nr({result:{error:Te},stack:s})}(t)},swapDrawPositionAssignments:function(t){return jh(t)},toggleParticipantCheckInState:Qf,updateDrawIdsOrder:OI,updateTeamLineUp:Gf,updateTieMatchUpScore:Zg,withdrawParticipantAtDrawPosition:function(t){return Object.assign(t,{entryStatus:du}),xm(t)}};function YS({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||KS({drawSize:u,qualifyingRoundNumber:f});let R,M,A;if(!p(u))return Nr({result:{error:it},stack:"generateQualifyingSTructures"});const E=t.length>1?`${h}-`:"",C=d.length>1||E?y:"",O=T||(E||C?`${Lm(Vo)} ${E}${C}`:Lm(Vo));if(D===Rs){const{structures:t,groupCount:a,maxRoundNumber:s}=bf({structureName:o.structureName||O,structureId:P||i?.pop(),stage:Vo,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}=zI({qualifyingRoundNumber:f,qualifyingPositions:N,matchUpType:b,drawSize:u,idPrefix:n,isMock:r,uuids:i})),M=Bm({structureName:o.structureName||O,structureId:P||i?.pop(),qualifyingRoundNumber:R,stage:Vo,matchUpFormat:w,stageSequence:y,matchUpType:b,roundLimit:R,matchUps:A}),h&&Cr({extension:{name:Za,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===is?[1]:void 0,linkType:S});c.push(t),m+=(u||0)-v}else m+=u||0;S=D===Rs?is:as,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 KS({drawSize:t,qualifyingRoundNumber:e}){let n=t,r=0;for(;r<e;)n=Math.floor(n/2),r+=1;return n}function JS({policyDefinitions:t,appliedPolicies:e,drawType:n}){const r=t?.[ba]?.drawTypeCoercion,i=e?.[ba]?.drawTypeCoercion;return("boolean"==typeof r?r:void 0)??(n&&r?.[n])??("boolean"==typeof i?i:void 0)??(n&&i?.[n])??!0}function ZS({structureName:t,matchUpType:e,idPrefix:n,drawSize:r,isMock:i,uuids:a}){const o=[],{matchUps:s}=ZI({linkFedFinishingRoundNumbers:[1],drawSize:r+1,matchUpType:e,idPrefix:n,isMock:i}),c=Bm({structureName:t||Lm(Bo),structureId:a?.pop(),stageSequence:1,stage:Bo,matchUpType:e,matchUps:s});o.push(c);const u=r/2,{matchUps:d}=ZI({finishingPositionOffset:u,idPrefix:n&&`${n}-c`,drawSize:r-1,isConsolation:!0,matchUpType:e,isMock:i,uuids:a}),p=Bm({structureName:Lm(Es),matchUps:d,structureId:a?.pop(),stage:jo,stageSequence:2,matchUpType:e});o.push(p);const{matchUps:l}=zI({idPrefix:n&&`${n}-p1t2`,drawSize:2,matchUpType:e,isMock:i}),m=Bm({structureName:Lm(As),matchUps:l,structureId:a?.pop(),stageSequence:3,stage:qo,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?ns:rs;return{linkType:os,source:{roundNumber:1+i,structureId:t.structureId},target:{feedProfile:a,roundNumber:n,structureId:e.structureId}}})),{linkType:as,source:{roundNumber:a,structureId:e.structureId},target:{feedProfile:ns,roundNumber:i,structureId:t.structureId}},{linkType:as,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:ns,roundNumber:1,structureId:n.structureId}},{linkType:os,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:ns,roundNumber:1,structureId:n.structureId}}]}({mainStructure:c,consolationStructure:p,deciderStructure:m});return{structures:o,links:f,...E}}function XS(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 zI(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}=HI({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=WI({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=Rl({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 QS(t){const{playoffAttributes:e,stageSequence:n=1,stage:r=Bo,matchUpType:i,drawSize:a,uuids:o}=t,s=t.structureId||(()=>{if(!t.isMock&&!t.idPrefix)return;return`${t.drawDefinition.drawId}-s-0`})()||o?.pop(),{appliedPolicies:c}=Fc(t),u=t.policyDefinitions?.[Da]||c?.[Da];t.skipRounds=t.skipRounds||a<=4&&(u?.feedMainFinal?0:1)||0;const d=t.structureName??e?.[0]?.name??Lm(Bo),p={[cs]:()=>({structures:[Bm({finishingPosition:Fs,stageSequence:n,structureName:d,matchUps:[],matchUpType:i,structureId:s,stage:r})],links:[],...E}),[gs]:()=>{const{matchUps:e}=XS(t);return{structures:[Bm({stageSequence:n,structureName:d,matchUpType:i,structureId:s,matchUps:e,stage:r})],links:[],...E}},[ls]:()=>(()=>{const{matchUps:e}=zI(t);return{structures:[Bm({stageSequence:n,structureName:d,matchUpType:i,structureId:s,matchUps:e,stage:r})],links:[],...E}})(),[ms]:()=>ZS(t),[ds]:()=>XI({...t,roundOffsetLimit:3,playoffAttributes:e??Cs}),[ps]:()=>XI({...t,roundOffsetLimit:2,playoffAttributes:e??Os}),[qo]:()=>XI(t),[us]:()=>{const{matchUps:t}=ZI({drawSize:a,uuids:o,matchUpType:i});return{structures:[Bm({stageSequence:n,structureName:d,matchUpType:i,structureId:s,stage:Bo,matchUps:t})],links:[],...E}},[hs]:()=>QI(t),[fs]:()=>nU({...t,feedRounds:1,fmlc:!0}),[Ds]:()=>nU({...t,feedRounds:1}),[Ss]:()=>nU({...t,feedsFromFinal:1}),[vs]:()=>nU({...t,feedsFromFinal:2}),[Ts]:()=>nU({...t,feedsFromFinal:3}),[Ns]:()=>nU(t),[Is]:()=>eU(t),[Rs]:()=>bf(t),[Ms]:()=>function(t){const{drawDefinition:e,structureOptions:n,requireSequential:r}=t,i={structureName:Lm(Bo),...t,stage:Bo},{structures:a,groupCount:o,groupSize:s}=bf(i);if(o<1)return{error:wn};const c=n?.playoffGroups||[{finishingPositions:[1],structureName:Lm(qo)}],[u]=a,{structures:d,links:p}=rU({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 ty(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??JS({appliedPolicies:a,drawType:t.drawType}),m="generateDrawStructuresAndLinks";let f=l&&2===t.drawSize&&ls||t.drawType||ls;const h=[],g=[],I=t?.matchUpType??dc,U=s?.structures?.filter((({stage:t})=>t===Vo));U&&h.push(...U);const S=U?.map((({structureId:t})=>t)),y=s?.structures?.find((({stage:t,stageSequence:e})=>t===Bo&&1===e)),v=s?.links?.filter((t=>t.target.structureId===y?.structureId&&S?.includes(t.source.structureId))),w=(t,e)=>{if(t.linkType===is&&e?.structures){const n=t.source.finishingPositions||[];return e.structures.length*n.length}if(t.linkType===as&&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=qs({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&&YS({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,br({drawSize:u,matchUpType:I,tieFormat:c}));const C=f!==cs&&(!u||isNaN(u)||u<2||!o&&![us,gs].includes(f)&&([Ms,Rs].includes(f)&&u<3||![Rs,Ms].includes(f)&&!r(u)));if(C&&!R)return Nr({context:{drawSize:u,invalidDrawSize:C},result:{error:nt},stack:m});const O=xs.includes(f);if(u&&n(u)<4&&O)if(l)f=ls;else if(e)return Nr({context:{enforceMinimumDrawSize:e,invalidDrawSize:C,drawSize:u,drawType:f},result:{error:nt},stack:m});const{generators:F,error:k}=QS(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===Bo&&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(Ls),B?.length&&g.push(...B);const V=_.structures.find((({stage:t,stageSequence:e})=>t===Bo&&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 ey(t){const{modifyOriginal:e=!0,stageSequence:n=1,isMock:r}=t||{},i="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return Nr({result:{error:j},stack:i});const a=e?t.drawDefinition:mi(t.drawDefinition,!1,!0);let{tieFormat:o,matchUpType:s}=t;if(o){const t=Ah({tieFormat:o});if(t.error)return t}o=dh(o??Np({drawDefinition:a})?.tieFormat),s=s??(a.matchUpType||dc),t.tieFormat=o,t.matchUpType=s;const c=gm({drawDefinition:a,stage:Bo});t.drawSize=t.drawSize??c,!c&&t.drawSize&&xI({drawSize:t.drawSize,drawDefinition:a,stageSequence:n,stage:Bo});const u=Wc({drawDefinition:a}).drawMatchUps.map(mo),d=ty(t);if(d.error)return Nr({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(!gm({stage:Vo,drawDefinition:a})){const t=xI({drawSize:m.qualifyingDrawPositionsCount,stage:Vo,drawDefinition:a});if(t.error)return t}}if(f){const t=_I({qualifiersCount:f,drawDefinition:a,stage:Bo});if(t.error)return t}const h=t.drawSize??c;Object.assign(t,br({drawSize:h,matchUpType:s,tieFormat:o}));const{matchUps:g,matchUpsMap:I}=el({drawDefinition:a});o&&g?.forEach((t=>{if(!u.includes(t.matchUpId)){const{tieMatchUps:e}=Eh({tieFormat:o,matchUp:t,isMock:r});Object.assign(t,{tieMatchUps:e,matchUpType:s})}}));const{inContextDrawMatchUps:U}=Ml({drawDefinition:a,matchUpsMap:I});return Il({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:a}),{inContextDrawMatchUps:U,drawDefinition:a,matchUpsMap:I,...E,structures:p,matchUps:g,links:l}}function ny({tournamentRecord:t,categoryName:e,categoryType:n}){if(!t)return{error:_};const{appliedPolicies:r}=Fc({tournamentRecord:t}),i=r?.[ba];return(i?.allowedDrawTypes||[]).filter((({categoryNames:t,categoryTypes:r})=>!e&&!r||e&&t?.includes(e)||n&&r?.includes(n)))}function ry({consideredEntries:t,policyDefinitions:e,tournamentRecord:n,appliedPolicies:r,participantMap:i,enforceGender:a,participants:o,event:s}){if(o&&i||!n||({participants:o,participantMap:i}=mm({tournamentRecord:n})),!o)return{error:Me};if(!Array.isArray(o))return{error:Nn};if(!s)return{error:Tt};const c=e?.[ga]??r?.[ga]??Tm[ga],u=!1!==(a??c?.participants?.enforceGender),{eventType:d,gender:p}=s,l=d===pd,f=d===md&&Xs||l&&Zs||Ks,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&&[pd,md].includes(d)&&t.participantType===Ks&&(Xl(e)||e===du),r=t.participantType!==f&&!n,a=!r&&l&&m(t?.individualParticipantIds?.map((t=>i?.[t]?.participant?.person?.sex)).filter(Boolean)??[]),o=!p||!a?.length||Hp===p||[zp,Jp].includes(p)&&a[0]===p||Yp===p&&(1==a.length&&1===t.individualParticipantIds?.length||2===a.length),s=t?.person?.sex,c=!t?.person||!p||[Hp,Yp].includes(p)||[zp,Jp].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 iy=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});function ay(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=Fr({name:Za,element:t})?.extension?.value;return(!t.entryStage||t.entryStage===R)&&(!b||!t.entryStageSequence||t.entryStageSequence===b)&&(!N||!e||e===N)&&mu.includes(t.entryStatus)}));T&&(n=T.length),n>g&&(n=g),n>A.length&&(n=A.length);const{structures:C}=js({drawDefinition:u,stageSequence:b,roundTarget:N,stage:R}),O=(C?.length||0)>1,F=C?.find((({structureId:t})=>!r.includes(t)));if(!F)return Nr({result:{error:Ut},stack:e});const k=F?.structureId,x=F?Cf({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=Vs({drawDefinition:o,structureId:c});if(d.error)return d;const l=d.structure;if(!l)return{error:Ut};const{positionAssignments:m}=$s({structure:l}),f=m?.length||0;if(u>f)return{error:ct};const h=l.structures?.length,g=p(s?.groupSeedingThreshold)&&s?.groupSeedingThreshold,I=Mf({roundRobinGroupsCount:h,drawSize:f})?.seedGroups,{seedsCount:U}=HU({policyDefinitions:a,requireParticipantCount:t,drawSizeProgression:n,participantsCount:r,drawSize:f});return U&&a?.[Pa]&&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}})),Il({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(lo);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;_f({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:ca,scaleName:D||t||e||U.eventId,eventType:M};let{scaledEntries:a}=JU({scaleAttributes:r,tournamentRecord:o,stageSequence:b,entries:I,stage:R});if(!a?.length&&v){const n={scaleName:t||e,scaleType:aa,eventType:M};({scaledEntries:a}=JU({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;_f({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!==cs&&(!c||R===Vo)){const t="object"==typeof m&&m.seedsOnly,n=hg({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 Nr({result:n,stack:e})}return{positionAssignments:B,positioningReport:V,stageEntries:A,structureId:k,seedsCount:n,conflicts:j}}const oy={[Pa]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[Ms]:{positioning:Zo},[Rs]:{positioning:Zo}},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 sy(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=t.isMock??!0,I=t.idPrefix,U=Fc({tournamentRecord:c,event:h}).appliedPolicies??{},S=mi(t.policyDefinitions??{},!1,!0),y=(t.drawTypeCoercion??JS({drawType:t.drawType,policyDefinitions:S,appliedPolicies:U}))&&2===t.drawSize&&ls||t.drawType||ls,v=S?.[Pa]??U?.[Pa],T=t.seedingProfile??v?.seedingProfile?.drawTypes?.[y]??v?.seedingProfile;t.seedingProfile&&(S[Pa]||(S[Pa]={...oy[Pa]}),S[Pa].seedingProfile=T);const{participants:P,participantMap:D}=mm({withIndividualParticipants:!0,convertExtensions:!0,internalUse:!0,tournamentRecord:c}),b=t.enforceGender??S?.[ga]?.participants?.enforceGender??U?.[ga]?.participants?.enforceGender,N=!i&&c&&ny({tournamentRecord:c,categoryType:h?.category?.categoryType,categoryName:h?.category?.categoryName});if(N?.length&&!N.includes(y))return Nr({result:{error:et},stack:e});const R=h?.entries?.filter((t=>t.entryStatus&&[...fu,au].includes(t.entryStatus)))??[],M=(d&&[]||m||(r?R:[])).filter((({entryStage:t})=>!t||t===Bo)),A=h&&P&&ry({consideredEntries:M,appliedPolicies:U,participantMap:D,enforceGender:b,participants:P,event:h});if(A?.error)return Nr({result:A,stack:e});const C=!t.drawSize&&M.length&&![cs,ms,us,Rs,Ms].includes(y)&&u(M.length)||t.drawSize&&p(t.drawSize)&&n(t.drawSize)||!1;if(isNaN(C)&&y!==cs)return Nr({result:{error:it},stack:e});let O="number"!=typeof t.seedsCount?n(t.seedsCount??0):t.seedsCount??0;const F=h?.eventType,k=t.matchUpType??F,x=t.drawId?h?.drawDefinitions?.find((e=>e.drawId===t.drawId)):void 0;let{tieFormat:_,matchUpFormat:L}=t;if(k===fc&&F===fc){const t=x?.structures?.find((({stage:t})=>t===Bo))?.tieFormat;_=_||t||l&&h?.tieFormat?.tieFormatName===l&&h.tieFormat||l&&LS({namedFormat:l,hydrateCollections:o,isMock:g,event:h})||h?.tieFormat||LS({event:h,isMock:g,hydrateCollections:o}),L=void 0}else L||(_=void 0,h?.matchUpFormat||(L=Sg));if(_){const t=Ah({gender:h?.gender,enforceGender:b,tieFormat:_});if(t.error)return Nr({result:t,stack:e})}if(t.drawId&&"string"!=typeof t.drawId)return Nr({result:{error:Nn},stack:e});x&&y!==x.drawType&&(x.drawType=y);let B=x??function(t){const{drawId:e=Ld(),processCodes:n,matchUpType:r,drawType:i}=t??{},a=iy();return Object.assign(a,{processCodes:n,matchUpType:r,drawType:i,drawId:e})}({drawType:y,drawId:t.drawId,processCodes:t.processCodes});if(L||_){if(!(L&&h?.matchUpFormat===L||h?.tieFormat&&_&&JSON.stringify(h.tieFormat)===JSON.stringify(_))){if(_){const t=function({tieFormat:t}){const e=Ah({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(const e of t.collectionDefinitions)e.collectionId||(e.collectionId=Ld());return{tieFormat:t}}({tieFormat:_});if(t.error)return Nr({result:t,stack:e});B.tieFormat=t.tieFormat??_}else if(L){const t=KI({tournamentRecord:c,drawDefinition:B,matchUpFormat:L,event:h});if(t.error)return{error:t.error,info:"matchUpFormat or tieFormat error"}}k&&(B.matchUpType=k)}}const V={[wa]:U[wa]};if(S){if("object"!=typeof S)return Nr({info:"policyDefinitions must be an object",result:{error:Nn},stack:e});for(const t of Object.keys(S))JSON.stringify(U?.[t])!==JSON.stringify(S[t])&&(V[t]=S[t]);Object.keys(V).length&&(gU({policyDefinitions:V,drawDefinition:B}),Object.assign(U,V))}else V.avoidance&&gU({drawDefinition:B,policyDefinitions:V});U[Pa]||S[Pa]||(gU({policyDefinitions:oy,drawDefinition:B}),Object.assign(U,oy));let j=x?.structures?.find((t=>t.stage===Bo&&1===t.stageSequence))?.structureId;const G=m??R,q=[];let $,W=[];const H=t.qualifyingPlaceholder&&!t.qualifyingProfiles?.length&&!x,z=x?x.structures?.filter((t=>t.stage===Vo)):[],Y=1===z?.length&&!z[0].matchUps?.length&&z[0].structureId;if(Y){const e=t.qualifyingProfiles,n=e?.length?YS({uuids:t.uuids,qualifyingProfiles:e,appliedPolicies:U,idPrefix:I,isMock:g}):void 0;if(n?.error)return n;B.structures=B.structures?.filter((({structureId:t})=>t!==Y)),B.links=B.links?.filter((({source:t})=>t.structureId!==Y));const{qualifiersCount:r,qualifyingDrawPositionsCount:i,qualifyingDetails:a}=n??{};i&&(n?.structures&&B.structures?.push(...n.structures),n?.links&&B.links?.push(...n.links));const o=B.structures?.find((({stage:t,stageSequence:e})=>t===Bo&&1===e)),{qualifiersCount:s}=hm({stageSequence:1,drawDefinition:B,structureId:j,stage:Bo});let c=_I({qualifiersCount:Math.max(r??0,s??0),drawDefinition:B,stage:Bo});if(c.error)return c;if(c=xI({drawSize:i,stage:Vo,drawDefinition:B}),c.error)return c;for(const t of(m??[]).filter((({entryStage:t})=>t===Vo))){Sm({...t,entryStage:t.entryStage??Bo,drawDefinition:B})}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&&(B.links||(B.links=[]),B.links.push(s))}$={drawDefinition:B}}else{if($=ey({...t,modifyOriginal:!1,tournamentRecord:c,appliedPolicies:U,drawDefinition:B,matchUpFormat:L,matchUpType:k,tieFormat:_,drawSize:C,isMock:g}),$.error)return Nr({result:$,stack:e});B=$.drawDefinition;for(const t of G){if(m&&t.entryStage&&t.entryStage!==Bo)continue;const n=Sm({...t,ignoreStageSpace:s??y===cs,entryStage:t.entryStage??Bo,drawDefinition:B,drawType:y});if(m&&n.error)return Nr({result:n,stack:e})}y===gs&&(O=0);const n=ay({...$,...t,qualifyingOnly:!C||d,appliedPolicies:U,drawDefinition:B,seedingProfile:T,participants:P,stage:Bo,seedsCount:O,placeByes:f,drawSize:C,entries:G});if(n.error&&!n.conflicts)return n;if(n.positioningReport?.length&&q.push({[Bo]:n.positioningReport}),j=n.structureId,n.conflicts&&(W=n.conflicts),y===cs&&t.roundsCount){const e=h?.entries?.filter((({entryStage:t,entryStatus:e})=>(!t||t===Bo)&&e&&fu.includes(e))),n=e?.map(wi("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=BU({eventType:t.drawMatic?.eventType??k,generateMatchUps:r??!0,restrictEntryStatus:e,tournamentRecord:c,participantIds:n,drawDefinition:B,structureId:i,matchUpIds:a,scaleName:o,idPrefix:I,isMock:g,event:h}).matchUps;jU({tournamentRecord:c,drawDefinition:B,structureId:i,matchUps:s})}else{const{matchUps:t}=TU({newRound:!0,drawDefinition:B,matchUpsCount:r,idPrefix:I,isMock:g,event:h});jU({tournamentRecord:c,drawDefinition:B,structureId:j,matchUps:t})}}))}}const K=[];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 Nr({info:Vf("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=ay({...$,...t,seedingProfile:e.seedingProfile??T,stageSequence:s,qualifyingRoundNumber:n,preparedStructureIds:i,qualifyingPositions:r,seededParticipants:o,stage:Vo,seedingScaleName:c,appliedPolicies:U,drawDefinition:B,qualifyingOnly:d,seedByRanking:p,participants:P,roundTarget:a,seedsCount:u,placeByes:l,drawSize:m,entries:G});if(f.error)return f;f.structureId&&i.push(f.structureId),s+=1,f.conflicts?.length&&K.push(...f.conflicts),f.positioningReport?.length&&q.push({[Vo]:f.positioningReport})}a+=1}}else if(j&&H){const t=Bm({structureName:Lm(Vo),stage:Vo}),{link:e}=$I({sourceStructureId:t.structureId,targetStructureId:j,sourceRoundNumber:0,linkType:is});B.structures||(B.structures=[]),B.structures.push(t),B.links||(B.links=[]),B.links.push(e)}return B.drawName=t.drawName??(y&&Lm(y)),"object"==typeof a&&C>=4&&Vm({...a,drawDefinition:B,matchUpType:k}),{existingDrawDefinition:!!x,qualifyingConflicts:K,positioningReports:q,drawDefinition:B,structureId:j,...E,conflicts:W}}const cy="splitWaterfall",uy="splitShuttle",dy={SPLIT_LEVEL_BASED:"splitLevelBased",SPLIT_WATERFALL:cy,SPLIT_SHUTTLE:uy};const py="ASC",ly="DESC",my={ASC:"ASC",ASCENDING:py,DESC:"DESC",DESCENDING:ly};function fy(t){let{tieFormat:e}=t;const{useDefaultEventRanking:n,tournamentRecord:r,drawDefinition:i,scaleAccessor:a,singlesOnly:o,attach:c,event:u}=t;if(u?.eventType!==md)return{error:wt};if(!r)return{error:_};if(!e&&!i)return{error:q};if(e=e??Np({drawDefinition:i,event:u})?.tieFormat,Ah({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===tu)).map(lo),{participants:l=[]}=mm({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=aa,sortOrder:I,accessor:U}=a||{},S=g===aa?"rankings":"ratings";const y=(t,e)=>{let r=t[S]?.[e];if(!r&&n&&(r=t[S]?.[uc]),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===ly?t:e;return y(I===ly?e:t,n)-y(r,n)},T=(t,e)=>v(t,e,uc),P=(t,e)=>v(t,e,pc),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===uc;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&&([zp,Jp].includes(c)&&c||c===Yp&&[zp,Jp][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}=Yc({tournamentParticipants:l,participantIds:t});if(!e){const e={individualParticipantIds:t,participantRole:Dm,participantType:Zs};N.push(e)}}if(c){for(;N.length;)eh({participant:N.pop(),tournamentRecord:r});Cr({element:i,extension:{name:Wa,value:d}})}return{...E,lineUps:d,participantsToAdd:N}}function hy({court:t,date:e}){const n=e&&t.dateAvailability.find((t=>pi(t.date,e))),r=t.dateAvailability.find((t=>!t.date));return n||r}function gy({includeBookingTypes:t=[],courtDate:e}){const n=[];let r=oi(e.startTime);(e.bookings||[]).filter((e=>!e.bookingType||!t.includes(e.bookingType))).sort(((t,e)=>Xr(t.startTime).localeCompare(Xr(e.startTime)))).forEach((t=>{const e={startTime:Qr(r.toISOString()),endTime:t.startTime};oi(t.startTime)>r&&n.push(e),oi(t.endTime)>r&&(r=oi(t.endTime))}));const i={startTime:Qr(r.toISOString()),endTime:e.endTime};return oi(e.endTime)>r&&n.push(i),n}function Iy(t){const{averageMatchUpMinutes:e,includeBookingTypes:n,periodStart:r,date:i}=t,a=t.courts,o=oi(r),s=ui(o,e),{enoughTime:c}=function({averageMatchUpMinutes:t,includeBookingTypes:e,periodStartTime:n,periodEndTime:r}){function i(e){const i=oi(e.startTime),a=oi(e.endTime);return!(i>n)&&(!(a<r)&&si(n,a)>=t)}return{enoughTime:t=>!!gy({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=hy({date:i,court:t});return!(!e||!c(e))}))||[]).length}}function Uy(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 Sy(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(!Gr(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=hy({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]},...mi(u,!1,!0),...o].filter(Boolean),startTime:d,endTime:p,date:l}}}));c.sort(((t,e)=>Zr(t.startTime)-Zr(e.startTime)));const d=[];for(const t of c){const{startTime:e,endTime:n,averageMinutes:i,recoveryMinutes:a,matchUpId:o}=t,s=Zr(e),c=Zr(n),p=u.map((t=>{const e=gy({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=Zr(e)-s;const i=s>=Zr(e);return c<=Zr(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 yy({averageMatchUpMinutes:t,periodLength:e=30,recoveryMinutes:n}){const r=(t||90)+(n||0);return e>r?r:e||30}function vy({scheduleDate:t,startTime:e,endTime:n,courts:r}){const i=(e?"startTime":n&&"endTime")||void 0;return r.reduce(((r,a)=>{const o=hy({date:t,court:a}),s=i&&(o?.[i]||a[i]);return s&&(!r||e&&Zr(s)<Zr(r)||n&&Zr(s)>Zr(r))?s:r}),void 0)}function wy(t){let{date:e=qr(),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||yy({averageMatchUpMinutes:u}),e=ti(e),r=Qr(r),i=Qr(i);let m=0,f=0,h=0,g=0,I=0;!o&&p&&(o=Uy({startTime:r,endTime:i,count:p,date:e}));const{virtualCourts:U}=Sy({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||vy({courts:r,scheduleDate:i,startTime:!0}),n=n||vy({courts:r,scheduleDate:i,endTime:!0}),e&&n){const o=oi(e),s=oi(n);for(const e of r||[])Array.isArray(e.dateAvailability)&&gy({courtDate:hy({court:e,date:i})}).forEach((e=>{const n=oi(e.startTime),r=oi(e.endTime);if(n>s||n<o)return!1;if(r<o)return!1;if(si(n,r)>=t){const t=Qr(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=Zr(r),v=Zr(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),[di(e),di(n)].join(":")}(y+t*a),{availableToScheduleCount:i}=Iy({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 Ty={garman:{getCourtsAvailableAtPeriodStart:Iy,generateTimeSlots:gy,getScheduleTimes:wy,courtGenerator:Uy},generateAdHocMatchUps:TU,generateAndPopulatePlayoffStructures:aU,generateCourts:function(t){if(!t)return{error:ae};const e=na(t,[{dates:!1,[Ji]:t=>Array.isArray(t)&&t.every(Gr)},{uuids:!1,[Ji]:t=>Array.isArray(t)&&t.every(Ii)},{startTime:!1,endTime:!1,[Ji]:Jr},{idPrefix:!1,namePrefix:!1,[Ji]:Ii},{count:!0,[Ji]:s}]);if(e.error)return e;const{startDate:n,endDate:r}=t.tournamentRecord??{},i=t.dates||n&&r&&zr(n,r)||[],a=w(1,t.count+1).map((e=>br({courtId:t.uuids?.pop()??(t.idPrefix&&`${t.idPrefix}-${e}`)??Ld(),courtName:t.courtNames?.pop()??(t.namePrefix&&`${t.namePrefix} ${e}`),dateAvailability:i.map((e=>({startTime:t.startTime??"08:00",endTime:t.endTime??"20:00",date:e})))})));return{...E,courts:a}},generateDrawDefinition:sy,generateDrawMaticRound:LU,generateDrawStructuresAndLinks:ty,generateDrawTypeAndModifyDrawDefinition:ey,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}=wp({event:l});if(g&&n&&!o)return{error:xn};const I=t.scaledEntries??JU({tournamentRecord:r,scaleAttributes:i,scaleSortMethod:a,sortDescending:s,event:l,stage:m}).scaledEntries,U=I.map(lo),S=f(h.filter((({participantId:t})=>!U.includes(t))).filter((t=>(!m||!t.entryStage||t.entryStage===m)&&(!t.entryStatus||mu.includes(t.entryStatus))))),y=I.concat(...S),v=y.length;let T=N(y,Math.ceil(v/u));d===cy?T=A(y,u):d===uy&&(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()??Ld(),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=GU({flightProfile:P,deleteExisting:o,event:l});return{splitEntries:Qn()&&T||void 0,...t}}return{flightProfile:P,...E}},generateLineUps:fy,generateQualifyingStructure:YI,generateSeedingScaleItems:YU,generateVoluntaryConsolation:function(t){const{drawType:e=ls,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=Go,m=Su({stageSequence:1,drawDefinition:p,stage:l}),f=[Rs,ms,Ms].includes(e)?m.length:u(m.length);if(!a&&e===us&&m.length<2||e===Rs&&m.length<3)return{error:nt};let{tieFormat:h,matchUpType:g}=t;if(h){const t=Ah({tieFormat:h});if(t.error)return t}h=dh(h??Np({drawDefinition:p})?.tieFormat),g=g??p.matchUpType??dc;const{structures:I}=js({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,br({structureName:t.structureName??Lm(Go),structureId:U,matchUpType:g,tieFormat:h,drawSize:f,stage:l}));const S=QS(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=>Xp({structure:t}).matchUps)).flat();h&&P.forEach((t=>{const{tieMatchUps:e}=Eh({matchUp:t,tieFormat:h,isMock:c});Object.assign(t,{tieMatchUps:e,matchUpType:g})})),r&&n||(p=mi(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&&hg({seedingProfile:t.seedingProfile,applyPositioning:r,tournamentRecord:i,drawDefinition:p,structureId:U,placeByes:s,drawSize:f,event:d}),n&&Il({drawDefinition:p}),{links:T,structures:w,...E}}};var Py=[{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"}],Dy=["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 by({count:t=1,participantsCount:e=32}={}){const n=f(Dy),r=n.slice(0,t);return{cities:w(0,e).map((e=>e<Math.min(t,n.length)?r[e]:v(r)))}}function Ny({count:t=1,participantsCount:e=32}={}){const n=f(Py),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 Ry({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 My={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 Ay(t){const{count:e=100,sex:n}=t||{};if(!e||n&&![zp,Jp].includes(n))return{personData:[],error:Nn};const r=Math.ceil(1.3*e),{lastNames:i,firstFemale:a,firstMale:o}=My,s=rc.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=mi(i,!1,!0);return w(0,i.length).map((()=>y(t)))})),l=w(0,u).flatMap((()=>{const t=mi(a,!1,!0);return w(0,a.length).map((()=>y(t)))})),m=w(0,d).flatMap((()=>{const t=mi(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([zp,Jp]),r=e===zp?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 Ey(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?.[zp]||u===zp&&e||0,p=o?.[Jp]||u===Jp&&e||0;e=Math.max(e,d+p);const l=e-(d+p),m=[...d&&Ay({count:d,sex:zp}).personData||[],...p&&Ay({count:p,sex:Jp}).personData||[],...l&&Ay({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&&![zp,Jp].includes(t.sex))&&(!(t.nationalityCode&&("string"!=typeof t.nationalityCode||t.nationalityCode.length>3||!rc.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===zp?(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([zp,Jp]),o=v(a),s={firstName:v(e===zp?t:r),lastName:v(e===zp?n:i),sex:e,nationalityCode:o};I.push(s)}))}const{ageMinDate:U,ageMaxDate:S}=Dh({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 $r(new Date(r.setDate(e)),n)}(o,s);return Object.assign(br({extensions:r||[{name:"regionCode",value:e+1}],birthDate:c,isMock:a}),t)}));return{persons:b.length&&b||I[0],nationalityCodes:g}}function Cy(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 Oy=["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 Fy({nameRoot:t="TEAM",count:e=1}={}){const n=f(Oy).slice(0,e);return n.length<e&&w(0,e-n.length).forEach((e=>n.push(`${t} ${e+1}`))),{names:n}}const ky=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]},xy=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 _y({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&&xy({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 Ly(t){const{matchUpFormat:e,matchUpStatus:n,winningSide:r,scoreString:i}=t;if(!i)return{outcome:{...Wg,winningSide:r,matchUpStatus:n}};if(r&&![1,2,void 0].includes(r))return{error:Nn,winningSide:r};const a=i&&_y({scoreString:i}),o={},s=uU({sets:a,matchUpFormat:e}),c=uU({sets:a,reversed:!0,matchUpFormat:e});return 2===r?(o.scoreStringSide1=c,o.scoreStringSide2=s):(o.scoreStringSide1=s,o.scoreStringSide2=c),o.sets=_y({scoreString:o.scoreStringSide1}),br({outcome:{matchUpStatus:n,winningSide:r,score:o}})}function By({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=na(t,[{[bi]:!0}]);if(e.error)return e;const{tournamentRecord:n}=t,{policy:r}=bu({policyType:va,tournamentRecord:n}),{extension:i}=Fr({element:n,name:Xa}),a=i?.value?.dailyLimits,o=r?.defaultDailyLimits;return{matchUpDailyLimits:a||o}}({tournamentRecord:r});n=i})),{matchUpDailyLimits:n}}function Vy({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 jy({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=zg({tournamentRecords:t,drawId:r})))return{error:B};if(!(e=t[n]))return{error:_}}const i=e&&Tp({tournamentRecord:e,drawId:r});return i?.drawDefinition?{drawDefinition:i.drawDefinition,event:i.event,tournamentRecord:e,...E}:Nr({result:{error:q},stack:"findDrawDefinition"})}function Gy({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:e,timeAfterRecovery:n,matchUp:r}){const{individualParticipantIds:i}=Nl(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 qy({individualParticipantProfiles:t,participantId:e}){t[e]||(t[e]={typeChangeTimeAfterRecovery:void 0,timeAfterRecovery:void 0,priorMatchUpType:void 0,potentialRecovery:{},potentialCounted:{},potentialBookings:{},bookings:[],counters:{}})}function $y({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,typeChangeRecoveryMinutes:r,averageMatchUpMinutes:i=0,matchUpNotBeforeTimes:a,matchUpDependencies:o,recoveryMinutes:s=0,scheduleTime:c,matchUp:u}){const d=Qr(u?.schedule?.endTime),p=d?ci(d,n(s)):ci(c,n(i)+n(s)),l=r&&(d?ci(Qr(d),r):ci(c,n(i)+n(r))),m=o?.[u.matchUpId]?.participantIds||[],f=(u.roundPosition&&t[u.matchUpId]||[]).flat();m.forEach((t=>{qy({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}))})),Gy({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:a,timeAfterRecovery:p,matchUp:u})}function Wy({matchUpScheduleTimes:t,matchUpDependencies:e,scheduleTime:n,matchUpId:r,details:i}){let a;const o=i.minutesMap?.[r]?.recoveryMinutes,s=i.minutesMap?.[r]?.averageMinutes,c=ci(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||Zr(r)<Zr(e.scheduleTime)?i:e}),{});e.scheduleTime&&Zr(c)>Zr(e.scheduleTime)&&(a=e)}return{scheduledDependent:a}}const Hy="DO_NOT_SCHEDULE",zy={DO_NOT_SCHEDULE:Hy};function Yy({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===lc&&(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===Hy&&pi(a,t.date))),u=[],d=o?.matchUpId,p=oi(Qr(i),ti(a)),l=Qr(ui(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 Ky({defaultRecoveryMinutes:t=0,defaultAverageMinutes:e,tournamentRecords:n,matchUpFormat:r,categoryName:i,categoryType:a,tournamentId:o,eventType:s,eventId:c}){if(!Sh({matchUpFormat: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?Tp({tournamentRecord:e,eventId:c})?.event:void 0;return u=Nd({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 Jy({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:Vf("rounds")};const s={},c=[];o.sort(((t,e)=>(t.sortOrder??0)-(e.sortOrder??0))),e=e??Object.assign({},...Object.values(n).map((t=>wl({tournamentRecord:t}).containedStructures))),a||({matchUps:a}=Cl({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?$p({tournamentIds:[o.tournamentId],roundNumbers:[o.roundNumber],matchUpIds:o.matchUpIds,eventIds:[o.eventId],drawIds:[o.drawId],processContext:!0,structureIds:h,matchUps:a}).sort(Ol):[];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=Tp({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}=Ky({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||!ko.includes(e.matchUpStatus))&&e.matchUpStatus!==go)).map(mo);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 Zy({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 Xy({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUp:n,value:r}){const{matchUpType:i}=n,{individualParticipantIds:a}=Nl(n),o=(t[n.matchUpId]||[]).filter((t=>!b(t,a))).flat();[...a,...o].forEach((t=>{if(qy({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[Id]?a[Id]+=r:r>0&&(a[Id]=r),o.includes(t)&&(e[t].potentialCounted[n.drawId]=!0)}}))}const Qy=({scheduleAttributes:t=["scheduledDate","scheduledTime"],schedule:e={}})=>!!Object.keys(e).filter((e=>t.includes(e))).filter((t=>e[t])).length;function tv({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===go;return n&&l.push({tournamentId:t.tournamentId,matchUpId:t.matchUpId}),!n&&Qy({schedule:e})&&(!u||t.schedule.scheduledDate===u)})),n=i.map(mo));const m=Array.isArray(c)?c.includes(u):c,f=m?[]:p.filter((({matchUpId:t})=>n.includes(t)));for(const n of f){Xy({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;$y({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 ev({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=[go,yo,Uo,fo,bo,Mo,wo,vo].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],Gy({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:r,matchUp:n}),e}),{matchUpMap:{}});return{matchUpsToSchedule:u,matchUpMap:d}}function nv({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(!Mc(s)&&!Array.isArray(n))return{error:Ht};a=a??yy({recoveryMinutes:t,averageMatchUpMinutes:e});const c=Object.assign({},...Object.values(r).map((t=>(t.events??[]).map((e=>{const{scheduleTiming:n}=sd({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 Qy({schedule:e})&&(!o||t.schedule.scheduledDate===o)})));const d=n?.filter((t=>(!i.length||i.includes(t.schedule.venueId))&&t.matchUpStatus!==go)),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}=Rd({timingDetails:s,eventType:o}),{courtId:l,venueId:m}=e,f=Qr(e.scheduledTime),h=ci(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 rv({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??yy({recoveryMinutes:n,averageMatchUpMinutes:r});const{courts:m,venues:f}=Hm({dates:[c],ignoreDisabled:!0,tournamentRecords:a}),h=m?.filter((t=>!d||d.includes(t.venueId)))??[];u=u??vy({courts:h,scheduleDate:c,startTime:!0}),l=l??vy({courts:h,scheduleDate:c,endTime:!0});const{bookings:g,dateScheduledMatchUps:I}=nv({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}=wy(U),y=1===d?.length&&d[0]||1===f?.length&&f[0].venueId||void 0,v=I?.map(wi("matchUpId"));return{dateScheduledMatchUpIds:v,dateScheduledMatchUps:I,scheduleTimes:S,venueId:y}}function iv({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}=Jy({scheduleCompletedMatchUps:n,containedStructureIds:r,tournamentRecords:c,periodLength:u,matchUps:l,rounds:f});U.push(...T??[]);const{groupedRounds:D}=Zy({scheduledRoundsDetails:v,greatestAverageMinutes:w,garmanSinglePass:!0});let b,N,R=[];p&&({scheduleTimes:R,dateScheduledMatchUpIds:b,dateScheduledMatchUps:N}=rv({averageMatchUpMinutes:D[0]?.averageMinutes,scheduleDate:ti(d),venueIds:[S.venueId],clearScheduleDates:s,tournamentRecords:c,periodLength:u,matchUps:l}));const M=tv({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}=ev({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 av({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=>{qy({individualParticipantProfiles:t,participantId:e});const r=t[e];if(!r.timeAfterRecovery)return!0;const o=Qr(a?.schedule?.endTime),s=o?ci(o,n(u)):ci(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=Zr(t.scheduleTime),r=Zr(t.timeAfterRecovery),i=Zr(e.scheduleTime),a=Zr(e.timeAfterRecovery),o=n>i&&n<a,s=i>n&&i<r,c=r>i&&r<a,u=a>n&&a<r;return br({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?si(oi(p),oi(i),!1):0;return{enoughTime:d&&l>=0}}function ov({individualParticipantProfiles:t,matchUpPotentialParticipantIds:e,matchUpDailyLimits:n={},matchUp:r}){const{matchUpId:i,matchUpType:a}=r,{enteredIndividualParticipantIds:o}=Nl(r),s=(r.roundPosition&&e[i]||[]).flat(),c=m(o.concat(...s));c.forEach((e=>{qy({individualParticipantProfiles:t,participantId:e})}));return{participantIdsAtLimit:c.filter((e=>{const r=t[e];if(r)return[a,Id].find((t=>{const e=r.counters?.[t]||0,i=n[t]||0;return e&&i&&e>=i}))})),relevantParticipantIds:c}}function sv({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=Fl({tournamentRecords:o,tournamentRecord:s});i=t.matchUpDependencies,p=t.matchUps}p||(p=El({tournamentRecord:s})?.matchUps??[]);const f=p.reduce(((n,r)=>{const{matchUpId:i,drawId:a,matchUpStatus:o}=r;return!e&&o===go||!t&&ko.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}=jy({tournamentRecord:s,drawId:t});if(!e)continue;const g=f[t].filter((t=>u?.includes(t)??h?.includes(t))),I=rl({inContext:!1,drawDefinition:e}).matchUps;for(const t of g){const u=TI({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 cv(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 sv(t);const d=na(t,[{[Pi]:!0},{[Qi]:{matchUpContextIds:!1,matchUpDetails:!1},[Zi]:Nn,[Xi]:Ki}]);if(d.error)return d;if((!c||i)&&!u)return{error:ae,info:"schedule is required"};const p=[];let l=0;const{matchUpDependencies:m}=Fl({tournamentRecords:o});for(const t of Object.values(o)){const{tournamentId:d}=t,f=i?.filter((t=>t.tournamentId===d)).map(mo),h=c?.filter((t=>t?.tournamentId===d));if(f?.length||h?.length){const i=sv({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 uv({autoSchedulingAudit:t,tournamentRecords:e}){cr({topic:$d,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:df,itemValue:i};for(const t of Object.values(e))tf({tournamentRecord:t,timeItem:a})}function dv(t){const{tournamentRecords:e,requestType:n}=t,r=na(t,[{[Pi]:!0}]);if(r.error)return r;const i={};for(const t of Object.values(e)){const{extension:e}=Fr({element:t,name:Ka}),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 pv({averageMinutes:t,startTime:e,endTime:n,court:r,date:i}){if(!Array.isArray(r.dateAvailability))return{error:ae,stack:"getEarliestCourtTime"};const a=vy({scheduleDate:i,courts:[r],startTime:!0}),o=vy({scheduleDate:i,courts:[r],endTime:!0});e=e||a,n=n||o;const s=gy({courtDate:hy({court:r,date:i})}),c=oi(e),u=oi(n);return{earliestCourtTime:s.reduce(((e,n)=>{const r=oi(n.startTime),i=oi(n.endTime);if(r>u||i<c)return e;const a=c>r?c:r;if(si(a,i)>=t){const t=Qr(a.toISOString());(!e||t<e)&&(e=t)}return e}),void 0),courtStartTime:a,courtEndTime:o}}function lv(t){const{scheduleAttributes:e=["scheduledDate","scheduledTime"],ignoreMatchUpStatuses:n=ko,scheduledDates:r,venueIds:i}=t,a=_d(t),o=Ui(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=mv({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 mv({scheduleAttributes:t=["scheduledDate","scheduledTime"],ignoreMatchUpStatuses:e=ko,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=(El({matchUpFilters:{scheduledDates:r},tournamentRecord:n}).matchUps??[]).filter((n=>n.matchUpStatus&&!e.includes(n.matchUpStatus)&&Qy({schedule:n.schedule,scheduleAttributes:t})&&(!i?.length||i.includes(n.schedule.venueId)))).map(mo),o=El({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&&![Cu,Ou,Eu,ku,_u].includes(t?.itemType))),s+=1);return{...E,clearedScheduleCount:s}}function fv(t){const{checkPotentialRequestConflicts:e=!0,scheduleCompletedMatchUps:n,clearScheduleDates:r,scheduleDates:i=[],tournamentRecords:a,periodLength:o,useGarman:s,dryRun:c,pro:u}=t,d=na(t,[{[Pi]:!0},{[Ji]:t=>!t||Array.isArray(t)&&t.every(Gr),[Ai]:!1,[Xi]:Ki}]);if(d.error)return d;const p=Km({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=>wl({tournamentRecord:t}).containedStructures))),g=i.map((t=>{if(Gr(t))return ti(t)})).filter(Boolean),I=f.map((t=>t.scheduleDate)).map((t=>Gr(t)&&ti(t))).filter((t=>t&&(!i.length||g.includes(t))));if(!I.length)return{error:se};if(r&&!c){lv({tournamentRecords:a,scheduledDates:Array.isArray(r)?r:[]})}const U=Hm({ignoreDisabled:!1,tournamentRecords:a}).courts,{matchUps:S}=Cl({matchUpFilters:{matchUpTypes:[dc,lc]},afterRecoveryTimes:!0,nextMatchUps:!0,tournamentRecords:a}),{matchUpDependencies:y}=Fl({includeParticipantDependencies:!0,tournamentRecords:a,matchUps:S}),{matchUpDailyLimits:v}=By({tournamentRecords:a}),{personRequests:w}=dv({requestType:Hy,tournamentRecords:a}),T={schedulingProfileModifications:l,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:n,schedulingProfileIssues:m,dateSchedulingProfiles:f.filter((t=>{const e=ti(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=ti(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[Id]?n[Id]+=1:n[Id]=1}))};g[r]={},I[r]={},v[r]=[],w[r]=[],T[r]=[],P[r]=[];const N={};m?.forEach((t=>{t.schedule?.scheduledDate&&pi(r,ti(t.schedule.scheduledDate))&&Gy({matchUpPotentialParticipantIds:p,matchUpNotBeforeTimes:N,matchUp:t})}));const{allDateScheduledByeMatchUpDetails:R,allDateScheduledMatchUpIds:M,venueScheduledRoundDetails:A,allDateMatchUpIds:E}=iv({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}=nv({dateScheduledMatchUps:C,tournamentRecords:u,scheduleDate:r,periodLength:d}),{virtualCourts:F}=Sy({scheduleDate:r,periodLength:d,bookings:O,courts:f}),k=F?.reduce(((t,e)=>{const{earliestCourtTime:n,courtEndTime:i}=pv({date:r,averageMinutes:0,court:e});return(!t.startTime||oi(n)<oi(t.startTime))&&(t.startTime=n),(!t.endTime||oi(i)>oi(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}=ov({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}=Vy({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}=pv({averageMinutes:n.greatestAverageMinutes,startTime:x,date:r,court:a});if(t.scheduleTime&&Zr(s)>=Zr(t.scheduleTime))return t;const{scheduledDependent:u}=Wy({matchUpScheduleTimes:y,matchUpDependencies:o,scheduleTime:s,matchUpId:m,details:n});if(u)return t;const{enoughTime:d}=av({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}=Yy({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 $y({matchUpPotentialParticipantIds:p,individualParticipantProfiles:D,matchUpNotBeforeTimes:N,averageMatchUpMinutes:h,matchUpDependencies:o,recoveryMinutes:U,scheduleTime:s,matchUp:i}),(!t.scheduleTime||Zr(s)<Zr(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=ci(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&&(oi(x)<oi(k.endTime)?x=ci(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}=jy({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(di).join(":"),s=`${ti(r)}T${o}`;h||(yI({drawDefinition:a,scheduledTime:s,matchUpId:t}),SI({courtDayDate:r,tournamentRecords:u,tournamentRecord:n,drawDefinition:a,matchUpId:t,courtId:i})),v[r].push(t)}}))}))})),T[r]=A[t].matchUpsToSchedule.map(mo)}!h&&R?.length&&cv({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 uv({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=ti(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[Id]?n[Id]+=1:n[Id]=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&&pi(r,ti(t.schedule.scheduledDate))&&Gy({matchUpPotentialParticipantIds:d,matchUpNotBeforeTimes:R,matchUp:t})}));const{allDateScheduledByeMatchUpDetails:M,venueScheduledRoundDetails:A,allDateMatchUpIds:E}=iv({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}=ov({matchUpPotentialParticipantIds:d,individualParticipantProfiles:b,matchUpDailyLimits:s,matchUp:t});if(u.length)return T[r].includes(n)||T[r].push(n),!1;const{scheduledDependent:m}=Wy({matchUpScheduleTimes:v,matchUpDependencies:o,scheduleTime:a,matchUpId:n,details:i});if(m)return!1;const{dependenciesScheduled:f,remainingDependencies:h}=Vy({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}=av({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}=Yy({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 $y({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}=jy({tournamentRecord:i,drawId:a});o&&e[n][a].forEach((({matchUpId:e})=>{const n=v[e];if(n){const a=n.split(":").map(di).join(":"),s=`${ti(r)}T${a}`;h?w[r].push(e):(yI({drawDefinition:o,scheduledTime:s,matchUpId:e}).success&&w[r].push(e),t&&UI({tournamentRecord:i,drawDefinition:o,matchUpId:e,venueId:t}))}}))}))})),P[r]=A[t].matchUpsToSchedule.map(mo),g[r][t]=A[t].scheduleTimes.sort(((t,e)=>Zr(t.scheduleTime)-Zr(e.scheduleTime)))}!h&&M?.length&&cv({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 uv({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 hv(t){const e=t||{};return e.tournamentId||(e.tournamentId=Ld()),(!e.startDate||Kr(e.startDate)||kr.test(e.startDate))&&(!e.endDate||Kr(e.endDate)||kr.test(e.endDate))?(e.extensions&&(e.extensions=e.extensions.filter(Er)),{...e}):{error:pe}}function gv({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===Ks&&e===Dm));let u=0;for(const t of c){const n=a&&hi({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()??Ld(),individualParticipantIds:[],participantRole:Dm,participantType:Xs};const t={value:r??e,name:$a};Cr({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!==Xs)return;if(t.participantRole!==Dm)return;const{extension:e}=Fr({name:$a,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?(cr({payload:{tournamentId:n.tournamentId,participants:m},topic:jd}),{...E,participantsAdded:l}):m.length?{...E,newParticipants:m}:{error:Ie}}function Iv({idPrefix:t,participantType:e,index:n,uuids:r}){return t?`${t}-${e===Ks?"I":"P"}-${n}`:r?.pop()||Ld()}function Uv(t){let{rankingRange:e,scaledParticipantsCount:n}=t;const{ratingsParameters:r=CU,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===Zs||T===pc,E=h===Xs||T===Xs;!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=Ey({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)),[Zs,Xs].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={},n=Object.keys(t||{});for(const r of n){const n=t[r];if("object"==typeof n&&n.generator){const{range:t}=n,[i,a]=t.slice().sort();e[r]=d(i,a)}else e[r]=n}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(),[Zs,Xs].includes(h)&&(B=y())}}const V=rc.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||by({count:W||C,participantsCount:C}).cities,states:q&&z(q)||y?.states||Ny({count:H||C,participantsCount:C}).states,postalCodes:j&&z(j)||y?.postalCodes||Ry({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=Fy({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=Cy({...Y,participantIndex:t,nationalityCode:y}),w=br({participantId:Iv({participantType:Ks,index:t,idPrefix:I,uuids:U}),extensions:r,timeItems:i,participantRole:Dm,participantType:Ks,participantName:h,person:{addresses:[v],personId:p||g?.length&&g[t]||Ld(),standardFamilyName:f,standardGivenName:m,nationalityCode:y,extensions:a,birthDate:Gr(c)?c:void 0,sex:l}});if(R&&y){const t=rc.find((({iso:t})=>t===y));t?.ioc&&(w.person.iocNationalityCode=t.ioc),t?.label&&(w.person.countryName=t.label)}if(N&&y){const t=rc.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];Sv({scaleValue:e,eventType:ud,scaleType:aa,participant:w,category:o}),Sv({scaleValue:n,eventType:pd,scaleType:aa,participant:w,category:o});const r=L[t],i=B[t];Sv({scaleValue:r,eventType:ud,scaleType:oa,participant:w,category:o}),Sv({scaleValue:i,eventType:pd,scaleType:oa,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?Zs:Xs,s={participantId:Iv({participantType:a,idPrefix:I,index:t,uuids:U}),participantRole:Dm,participantName:A?i:X[t],individualParticipantIds:r,participantType:a};return b&&(s.individualParticipants=n),A||E?[s,...n]:n})).flat()}}function Sv({scaleValue:t,participant:e,eventType:n,scaleType:r,category:i}){const a=i.categoryName||i.ratingType||i.ageCategoryCode,o={itemValue:t,itemType:[sa,r,n,a].join(".")};a&&t&&(e.timeItems||(e.timeItems=[]),e.timeItems.push(o))}function yv({alternatesCount:t=0,tieFormatName:e,tieFormat:n,drawSize:r}){let i=0,a=0,o=0,s=0;const c={},u={[zp]:0,[Jp]:0,[Yp]:0,[Kp]:0,[Hp]:0};n="object"==typeof n?n:LS({namedFormat:e}),n?.collectionDefinitions?.filter(Boolean).forEach((t=>{const{category:e,collectionId:n,matchUpType:r,matchUpCount:d,gender:p}=t;if([zp,Jp].includes(p)){const t=d*(r===lc?2:1);u[p]<t&&(u[p]=t)}else p===Yp&&(u[zp]<d&&(u[zp]=d),u[Jp]<d&&(u[Jp]=d));if(e){const t=JSON.stringify(e);c[t]=e}if(n||(t.collectionId=Ld()),r===lc){const t=d;s+=d,i=Math.max(i,t)}if(r===dc){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 vv({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=Ks}=t||{};const a=r||0,o={[Jp]:0,[Yp]:0,[Kp]:0,[zp]:0,[Hp]: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===dd,g=i===ld,I=Boolean(e||f===Vo||l||m);if(g){d=Math.max(d,r+t),a="object"==typeof a?a:LS({namedFormat:n});const{teamSize:e,maxDoublesDraw:i,maxSinglesDraw:p,genders:l}=yv({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=Zs),(r||a)<m&&(r=m),r&&s&&[Zs,ld].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=wU({tournamentRecord:e,participants:l});if(f.error)return f;if(m+=f.addedCount,p){const t=gv({tournamentRecord:e,...p});if(t.error)return t}const h=l.filter((({participantType:t})=>t===Ks)).map(lo),g=t?.idPrefix?`${Xs}-${t.idPrefix}`:void 0;return f=wU({participants:w(0,c).map((t=>{const e=h.slice(t*u,(t+1)*u),n=Iv({index:t,participantType:s,idPrefix:g,uuids:a});return{participantName:`Team ${t+1}`,participantRole:Dm,individualParticipantIds:e,participantType:Xs,participantId:n}})),tournamentRecord:e}),f.error?f:(m+=f.addedCount,{addedCount:m,...E})}const wv=()=>({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 Tv(t){return parseInt(t)}function Pv({startTime:t="",endTime:e=""}={}){if(!(t&&e&&Lr.test(t)&&Lr.test(e)))return!1;const[n,r]=t.split(":").map(Tv),[i,a]=e.split(":").map(Tv);return!(i<n)&&!(n===i&&a<r)}function Dv(t,e){const[n,r]=t.startTime.split(":").map(Tv),[i,a]=e.startTime.split(":").map(Tv);return n<i?-1:n>i?1:r<a?-1:r>a?1:0}function bv({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&&!_r.test(t))return{error:pe,dateAvailability:{date:t},info:"Dates must be formated => YYYY-MM-DD"};if(!Lr.test(r))return{error:le,dateAvailability:{startTime:r},info:e};if(!Lr.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(!Pv({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(!Lr.test(n))return{error:le,booking:{startTime:n},info:e};if(!Lr.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(!Pv({startTime:n,endTime:r}))return{error:le,dateAvailability:{startTime:n,endTime:r},info:"endTime must be after startTime"}}}}return{valid:!0}}function Nv({tournamentRecord:t,disableNotice:e,venueId:n,courtId:r,court:i}){const{venue:a}=hp({tournamentRecord:t,venueId:n});if(!a)return{error:rn};a.courts||(a.courts=[]);const o={...wv(),venueId:n,courtId:r};o.courtId||(o.courtId=Ld());if(a.courts.some((t=>t.courtId===o.courtId)))return{error:en};{const r=(i?.dateAvailability||[]).map((t=>({...t,date:ti(t.date),startTime:Qr(t.startTime),endTime:Qr(t.endTime),bookings:t.bookings?.map((({startTime:t,endTime:e,bookingType:n})=>({startTime:Qr(t),endTime:Qr(e),bookingType:n})))}))),s=Object.keys(o);for(const t of s)if(i?.[t])if("dateAvailability"===t){const t=bv({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||cr({payload:{venue:a,tournamentId:t.tournamentId},topic:rp,key:a.venueId}),{...E,court:mi(o),venueId:n}}}function Rv(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}=hp({tournamentRecord:e,venueId:n});if(r){const n=Mv({...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 Mv({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=hp({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:$r(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 Nv({disableNotice:!0,tournamentRecord:r,courtId:n,venueId:l,court:t})})).map((t=>t.court)).filter(Boolean);return g.length!==o?Nr({info:"not all courts could be generated",result:{error:Nn}}):(h&&cr({payload:{venue:h,tournamentId:r.tournamentId},topic:rp,key:h.venueId}),{...E,courts:mi(g)})}function Av({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()??Ld(),dateAvailability:u,startTime:d="07:00",endTime:p="19:00",courtTimings:l,courtsCount:m,courtNames:f,venueName:h,idPrefix:g,courtIds:I}=s,U=mp({tournamentRecord:t,venue:{venueName:h||`Venue ${o+1}`,venueAbbreviation:e,venueId:c}});if(U.error)return U;a.push(c);const S=zr(r,i),y=!Array.isArray(u)&&[{startTime:d,endTime:p}].concat(S.map((t=>({date:$r(t),startTime:d,endTime:p})))),v=Rv({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 Ev({drawProfiles:t,category:e,gender:n}){const r={},i=t?.reduce(((t,i)=>{const{qualifyingPositions:a=0,participantsCount:o=0,uniqueParticipants:s,stage:c=Bo,drawSize:u=0}=i||{};Object.keys(t).includes(c)||(t[c]=0);const d=(o||u)-a;return s||n||e||c===Vo?(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 Cv({allUniqueParticipantIds:t,stageParticipantsCount:e,eventParticipantType:n,targetParticipants:r}){const i=e[Bo]||0,a=e[Vo]||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 Ov(t){const{removePriorValues:e,tournamentRecord:n,participantId:r,scaleItem:i}=t;let a,o;if(!Fv({scaleItem:i}))return{error:In};if(r&&Array.isArray(n.participants)&&(o=n.participants.find((t=>t.participantId===r)),o)){const t=kv({removePriorValues:e,participant:o,scaleItem:i});if(t.error)return t;a=!t.valueChanged;const{topics:r}=mr();r.includes(Qd)&&cr({topic:Qd,payload:{tournamentId:n.tournamentId,participants:[o]}})}return a&&{...E,info:Cn,existingValue:i?.scaleValue}||o&&{...E,newValue:i?.scaleValue}||{error:Ee}}function Fv({scaleItem:t}){const e=t&&Object.keys(t),n=["scaleType","eventType","scaleName"];return!!(n.filter((t=>e?.includes(t))).length===n.length)}function kv({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}=em({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=[sa,r,i,o].join("."),c=br({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 xv({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:n,setObject:r}){if(!r)return;const i=_v({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&&Op(n);const o=i&&e.finalSetFormat||e?.setFormat||{},{side1Score:s,side2Score:c}=a,{setTo:u,tiebreakAt:d,tiebreakFormat:p}=o,l=p?.NoAd,m=_v({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 _v({set:t}){if(t.side1Score||t.side2Score){if(t.side1Score>t.side2Score)return 1;if(t.side2Score>t.side1Score)return 2}else if(t.side1TiebreakScore||t.side2TiebreakScore){if(t.side1TiebreakScore>t.side2TiebreakScore)return 1;if(t.side2TiebreakScore>t.side1TiebreakScore)return 2}}function Lv(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:xv({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 Bv(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=Op(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&&Lv({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=>Lv({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 Vv={[Mo]:2,[wo]:1,[vo]:1,[bo]:1,[yo]:4};function jv(t){let{defaultWithScorePercent:e=2,winningSide:n}=t;const{matchUpStatusProfile:r=Vv,matchUpFormat:i=Sg,pointsPerMinute:a=1,sideWeight:o=4}=t;if(!Sh({matchUpFormat: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(Lo).includes(t)&&t!==Uo));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,Uo])[1],l={sets:[],scoreStringSide1:"",side2ScoreString:""};if([Mo,yo].includes(p)){n=n||d(1,2);const t={score:l,winningSide:n,matchUpStatus:p};if(!(p===yo&&d(1,100)>100-e))return{outcome:t}}else if([wo,vo].includes(p))return{outcome:{score:l,matchUpStatus:p}};const m=Op(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=[bo,yo,Po,No].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}=Gv({incomplete:v===t,matchUpStatus:p,pointsPerMinute:a,setFormat:e&&g||h,setNumber:t,weightedRange:S});if(I.push(n),r){T=o;break}if(Bv({matchUp:{score:{sets:I},matchUpFormat:i}}).calculatedWinningSide)break}const P=Bv({matchUp:{score:{sets:I},matchUpFormat:i}}),D=T?n||T:P.calculatedWinningSide,{score:b}=pU({score:{sets:I},winningSide:D,matchUpStatus:p});return{outcome:{score:b,winningSide:D,matchUpStatus:p}}}function Gv({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}),ko.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),ko.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&&ky({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=Lv({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=xy({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 qv(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(Ls);let d=0;const{matchUps:p,matchUpsMap:l}=el({contextFilters:{stages:[Bo,Vo]},matchUpFilters:{matchUpTypes:[fc],roundNumbers:[1]},inContext:!0,drawDefinition:o});if(p?.length){const t=s?.category?.ageCategoryCode||s?.category?.categoryName;if(t){const e=fy({singlesOnly:!0,tournamentRecord:i,drawDefinition:o,scaleAccessor:{scaleName:t,sortOrder:py,scaleType:aa},event:s});if(e.error)return e;const{lineUps:n,participantsToAdd:r}=e;wU({tournamentRecord:i,participants:r});Cr({element:o,extension:{name:Wa,value:n}})}else{const t=p[0]?.structureId,{positionAssignments:e}=qs({drawDefinition:o,structureId:t});if(e?.length){const{participants:t}=mm({participantFilters:{participantTypes:[fc]},tournamentRecord:i}),n=n=>{const r=n.tieMatchUps.filter((({matchUpType:t})=>t===dc)),a=n.tieMatchUps.filter((({matchUpType:t})=>t===lc));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&&sh({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=>{sh({teamParticipantId:u.participantId,participantId:t,tournamentRecord:i,drawDefinition:o,tieMatchUpId:a,event:s})}))}}))}))};p.forEach(n)}}}const m="string"==typeof n&&n,f=m&&Uo;for(const t of u){if(d>=a)break;const{matchUps:n}=Xp({matchUpFilters:{matchUpTypes:[lc,dc]},afterRecoveryTimes:!1,tournamentRecord:i,inContext:!0,drawDefinition:o,matchUpsMap:l,structure:t,event:s}),u=n.filter((({winningSide:t})=>!t)).sort(Ol).map(mo);for(const n of u){if(!isNaN(a)&&d>=a)break;const{matchUps:u}=Xp({matchUpFilters:{matchUpTypes:[lc,dc]},afterRecoveryTimes:!1,tournamentRecord:i,inContext:!0,drawDefinition:o,matchUpsMap:l,structure:t,event:s}),p=u.find((t=>t.matchUpId===n)),h=[wo,vo].includes(p.matchUpStatus);if(p?.readyToScore&&!h){const t=Wv({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 $v(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===go)return;const{matchUpId:p}=a||{},{outcome:l}=Ly({matchUpFormat:s,matchUpStatus:o,scoreString:c,winningSide:u});return e&&(l.matchUpStatusCodes=e),lU({tournamentRecord:r,policyDefinitions:n,drawDefinition:i,matchUpFormat:s,matchUpId:p,outcome:l,event:d})}function Wv(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 $v(t);const{matchUpId:p}=s||{},{outcome:l}=jv({matchUpStatusProfile:e,matchUpFormat:o,winningSide:u});return lU({policyDefinitions:r,tournamentRecord:n,drawDefinition:i,matchUpFormat:o,matchUpId:p,outcome:l,event:d})}function Hv({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:n,tournamentRecord:r,drawProfiles:i,event:a}){const o=wp({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(wi(Mi)).map(wi(Mi)),f=l||s;if(r&&S&&S<=p.length){w(1,S+1).forEach(((t,e)=>{const n={scaleValue:t,scaleName:f,scaleType:ca,eventType:c,scaleDate:d},i=p[e];Ov({tournamentRecord:r,participantId:i,scaleItem:n})}))}if(m?.includes(o))break;let y=sy({...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(Er).forEach((t=>Cr({element:v,extension:t}))),y=vU({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=cU({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=qv({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===Ms){const o=v.structures?.find((t=>t.stage===Bo));if(!o)return{error:Ut};let c=gg({structureId:o.structureId,tournamentRecord:r,drawDefinition:v,event:a});if(c.error)return{error:c.error,drawIds:[]};if(c=qv({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 zv(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===cd&&Ks||p===dd&&Zs||p,m=n[Bo]||0,f=n[Vo]||0,h=a.drawProfiles?.length?m+f:a.participantsProfile?.participantsCount??0,g=[zp,Jp].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=wU({tournamentRecord:i,participants:U});if(S.error)return S;const y=U?.filter((({participantType:t})=>t===l)),v=U?.map(lo);return{uniqueDrawParticipants:y,uniqueParticipantIds:v}}function Yv({autoEntryPositions:t,tournamentRecord:e,drawParticipants:n,drawProfile:r,event:i}){const{drawType:a=ls,qualifyingPositions:o=0,stage:s=Bo,drawSize:c=0,drawName:u,drawId:d}=r,p=c-o,l=n.slice(0,p).map(lo);if(l.length){const n=Pm({participantIds:l,autoEntryPositions:t,entryStage:s,tournamentRecord:e,event:i});if(n.error)return n}const m=ZU({drawName:u||a,qualifyingPositions:o,drawEntries:l.map((t=>({entryStatus:tu,entryStage:s,participantId:t}))),drawId:d,event:i,stage:s});return m.error?m:{...E}}function Kv({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=Bo,drawSize:l=0}=u,m=l-i,f=d||o||a||p===Vo,h=f?t.slice(c,c+m):n[p||Bo]||[];f&&(c+=m);const g=Yv({autoEntryPositions:e,drawParticipants:h,tournamentRecord:r,drawProfile:u,event:s});if(g.error)return g}return{...E}}function Jv(t){const{allUniqueParticipantIds:e,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:i,autoEntryPositions:a,hydrateCollections:o,randomWinningSide:s,ratingsParameters:c,tournamentRecord:u,eventProfile:d,eventIndex:p,publish:l,isMock:m,uuids:f}=t;let h=d.gender,g=d.eventName;const{eventType:I=cd,policyDefinitions:U,drawProfiles:S=[],eventExtensions:y,surfaceCategory:v,tieFormatName:w,processCodes:T,discipline:P,eventLevel:D,timeItems:b,ballType:N,category:R}=d,M=d.eventId||Ld(),A=d.tieFormat||(I===ld?LS({namedFormat:w,event:{eventId:M,category:R,gender:h},hydrateCollections:o,isMock:m}):void 0),E=u.participants;for(const t of S)!h&&t.gender&&(h=t?.gender);const{stageParticipantsCount:C,uniqueParticipantsCount:O,uniqueParticipantStages:F}=Ev({drawProfiles:S,category:R,gender:h}),k=I===cd&&Ks||I===dd&&Zs||I,{uniqueDrawParticipants:x=[],uniqueParticipantIds:_=[]}=F?zv({event:{eventType:I,category:R,gender:h},uniqueParticipantsCount:O,participantsProfile:r,ratingsParameters:c,tournamentRecord:u,eventProfile:d,eventIndex:p,uuids:f}):{};let{eventAttributes:L}=d;"object"!=typeof L&&(L={});const B=R?.categoryName||R?.ageCategoryCode||R?.ratingType;g=g||B||"Generated Event";const V={...L,surfaceCategory:v,processCodes:T,discipline:P,eventLevel:D,eventName:g,eventType:I,tieFormat:A,ballType:N,category:R,eventId:M,gender:h};if(y?.length&&Array.isArray(y)){const t=y.filter(Er);t?.length&&Object.assign(V,{extensions:t})}if(Array.isArray(b)&&b.forEach((t=>ef({event:q,timeItem:t}))),"object"==typeof U)for(const t of Object.keys(U))gU({policyDefinitions:{[t]:U[t]},event:V});let j;V.category&&(V.category.categoryName=B);const G=VS({suppressNotifications:!1,internalUse:!0,tournamentRecord:u,event:V});if(G.error)return G;const q=G?.event,{stageParticipants:$}=Cv({allUniqueParticipantIds:e,stageParticipantsCount:C,eventParticipantType:k,targetParticipants:E});if(S?.length){const t=Kv({uniqueDrawParticipants:x,autoEntryPositions:a,stageParticipants:$,tournamentRecord:u,drawProfiles:S,category:R,gender:h,event:q});if(t.error)return t;const e=Hv({matchUpStatusProfile:n,completeAllMatchUps:i,randomWinningSide:s,tournamentRecord:u,drawProfiles:S,event:q});if(e.error)return e;j=e.drawIds}else if(d?.participantsProfile?.participantsCount){const t=x.map(wi("participantId"));if(t.length){const e=Pm({participantIds:t,autoEntryPositions:a,tournamentRecord:u,entryStage:Bo,event:q});if(e.error)return e}}return l&&cf({tournamentRecord:u,event:q}),{drawIds:j,eventId:M,uniqueParticipantIds:_}}function Zv({tournamentRecords:t}){if(!Ui(t))return{error:x};const e=Object.keys(t??{}).reduce(((e,n)=>{const r=t[n],{tournamentInfo:{startDate:i,endDate:a}}=rf({tournamentRecord:r}),o=i&&new Date(ti(i));(!e.startDate||o&&o<e.startDate)&&(e.startDate=o);const s=a&&new Date(ti(a));return(!e.endDate||s&&s>e.endDate)&&(e.endDate=s),e}),{startDate:void 0,endDate:void 0}),n=e.startDate&&ti(e.startDate.toISOString()),r=e.endDate&&ti(e.endDate.toISOString());return n&&r?{startDate:n,endDate:r}:{error:oe}}function Xv({tournamentRecords:t,scheduleDate:e,venueId:n,round:r}){if(!Gr(e))return{error:pe};const{extension:i}=Fr({name:to,tournamentRecords:t,discover:!0}),a=i?.value||[];let o=a.find((t=>pi(e,t.scheduleDate)));if(!o){const{startDate:n,endDate:r}=Zv({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=>Ui(t[e])?u(t[e]):t[e])).flat().join("|");if(s.rounds.find((t=>u(t)===u(r))))return Nr({result:{error:gt},stack:"addSchedulingProfileRound"});s.rounds.push(r);const d=Jm({tournamentRecords:t,schedulingProfile:a});return d.error?d:{...E}}function Qv(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=mi(l,!1,!0),{excessParticipantAlternates:I=!0,matchUpFormat:U=Sg,drawType:S=ls,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||Ld(),G=l.eventType||l.matchUpType||cd,$=G===dd?Zs:Ks,W="object"==typeof l.tieFormat&&l.tieFormat||G===Xs&&LS({event:{eventId:j,category:k,gender:L},namedFormat:A,hydrateCollections:s,isMock:p})||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)*($===Zs?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=>ef({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(Er);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={[zp]:0,[Jp]:0};let i,a;G===Xs&&(({teamSize:i,genders:a}=yv({alternatesCount:v,tieFormatName:A,tieFormat:W,drawSize:V})),Object.keys(a).forEach((t=>{[zp,Jp].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=wU({participants:s,tournamentRecord:d});if(t.error)return t}if(s.forEach((({participantId:t})=>Q.push(t))),Y=s,G===Xs){const e=a[zp]?s.filter((({participantType:t,person:e})=>t===Ks&&e?.sex===zp)).map(lo):[],n=a[Jp]?s.filter((({participantType:t,person:e})=>t===Ks&&e?.sex===Jp)).map(lo):[],r=s.filter((({participantType:t})=>t===Ks)).map(lo).filter((t=>!e.includes(t)&&!n.includes(t))),o=i-(a[zp]+a[Jp]);let c=0,u=0,p=0;const l=w(0,t).map((t=>{const i=n.slice(c,c+a[Jp]),s=e.slice(u,u+a[zp]),d=r.slice(p,p+o);return c+=a[Jp],u+=a[zp],p+=o,{individualParticipantIds:[...i,...s,...d],participantOtherName:`TM${t+1}`,participantName:`Team ${t+1}`,participantRole:Dm,participantType:Xs,participantId:Ld()}})),m=wU({participants:l,tournamentRecord:d});if(!m.success)return m;Y=l}}const tt=t=>{const{participantType:e}=t;return G===cd&&e===Ks||(G===dd&&e===Zs||G===Xs&&e===Xs)},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=Pm({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=Pm({entryStage:Vo,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=Pm({participantIds:at,autoEntryPositions:!1,entryStatus:Xc,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:Xu,scaleValue:t,eventType:G},r=rt[e];Ov({tournamentRecord:d,participantId:r,scaleItem:n})}))}const st=sy({...mi(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(Er).forEach((t=>Cr({element:ct,extension:t}))),b){if(vU({drawDefinition:ct,event:Z,suppressNotifications:!0}),l.withPlayoffs){const t=ct.structures?.[0].structureId,e=cU({...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=qv({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===Ms){const t=ct.structures?.find((t=>t.stage===Bo));if(!t)return{error:Ut};gg({structureId:t.structureId,tournamentRecord:d,drawDefinition:ct,event:Z});const e=qv({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}=rl({inContext:!0,drawDefinition:ct,event:Z});for(const e of l.outcomes){const{matchUpStatus:n=Uo,matchUpStatusCodes:r,stageSequence:i=1,matchUpIndex:a=0,structureOrder:o,matchUpFormat:s,drawPositions:c,roundPosition:u,stage:p=Bo,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=$v({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})}_&&cf({tournamentRecord:d,event:Z})}else{const t=ZU({drawEntries:ct.entries,drawName:F||S,qualifyingPositions:T,drawId:ut,event:Z,stage:B});if(t.error)return t}return{...E,event:br(Z),uniqueParticipantIds:Q,targetParticipants:Y,drawDefinition:ct,eventId:j,drawId:ut}}const tw=["Mock Tournament","CourtHive Challenge","Racket Rally","Generated Tournament","Factory Follies","Open Competition"];function ew(){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 nw={generateOutcomeFromScoreString:Ly,anonymizeTournamentRecord:function({keepExtensions:t=[],anonymizeParticipantNames:e=!0,tournamentRecord:n,tournamentName:r,personIds:i=[],tournamentId:a}){if(!n)return{error:_};const o=Array.isArray(t)?ao.concat(...t):ao,s=e=>Array.isArray(t)?e?.extensions?.filter((t=>o.includes(t.name))):e?.extensions,c={};n.extensions=s(n);const u=a||Ld();c[n.tournamentId]=u,n.tournamentId=u,n.createdAt=(new Date).toISOString(),n.tournamentName=r||`Anonymized: ${$r(new Date)}`,delete n.parentOrganisation;for(const t of n.participants||[]){const e=Ld();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=Ld();c[t.venueId]=e,d+=1}let p=1;for(const t of n.events||[]){t.extensions=s(t);const e=Ld();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=Ld();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=Ld();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}=Fr({name:qa,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||$r(new Date),m=(n.participants||[]).filter((({participantType:t})=>t===Ks)),f=m.reduce(((t,e)=>{const n=e.person?.sex;return[zp,Jp].includes(n)?t[n]+=1:t[Kp]+=1,t}),{[zp]:0,[Jp]:0,[Kp]:0}),h=Object.assign({},...Object.keys(f).map((t=>({[t]:Ey({category:{ageCategoryCode:"O18"},count:f[t],addressProps:{citiesCount:10},personExtensions:[],consideredDate:l,sex:t})?.persons||[]})))),g={[zp]:0,[Jp]:0,[Kp]: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}=by({count:y||I,participantsCount:I}),{states:T}=Ny({count:v||I,participantsCount:I}),{postalCodes:P}=Ry({count:S||I,participantsCount:I}),D={cities:w,states:T,postalCodes:P};m.forEach(((t,n)=>{const r=t?.person,a=r?.sex||Kp,o=ti(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=Cy({...D,participantIndex:n,nationalityCode:d.nationalityCode});d.addresses=[t]}d.personId=i?.[n]||Ld(),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===Zs)).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===Xs)),N=Fy({count:b.length}).names;b.forEach(((t,e)=>{t.participantName=N[e]}));const R=(n.participants||[]).filter((({participantType:t})=>t===Js)),M=Fy({count:R.length,nameRoot:"Group"}).names;R.forEach(((t,e)=>{t.participantName=M[e]}));const{extension:A}=Fr({element:n,name:to});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}=Fr({element:n,name:Ka});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(tw),ratingsParameters:a=CU,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&&!Gr(n)||r&&!Gr(r))return{error:pe};if(S&&!Array.isArray(S))return{error:Nn};if(!n){const t=new Date;n=$r(r??t),r=$r(t.setDate(t.getDate()+7))}if(!r){const t=new Date(n);r=$r(t.setDate(t.getDate()+7))}"object"!=typeof e&&(e={});const D=hv({...e,tournamentName:i,isMock:!0,startDate:n,endDate:r});if(s?.length&&Array.isArray(s)){const t=s.filter((t=>Er({extension:t})));t?.length&&Object.assign(D,{extensions:t,isMock:!0})}if("object"==typeof h)for(const t of Object.keys(h))gU({policyDefinitions:{[t]:h[t]},tournamentRecord:D});const b=vv({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=Qv({allUniqueParticipantIds:N,matchUpStatusProfile:c,completeAllMatchUps:u,autoEntryPositions:p,hydrateCollections:l,participantsProfile:d,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=VS({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=Jv({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?Av({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=wl({tournamentRecord:e}).containedStructures,r=El({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=Xv({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=fv({scheduleCompletedMatchUps:o,tournamentRecords:{[t]:D},periodLength:I})}}return sr(),br({...E,tournamentRecord:D,scheduledRounds:C,schedulerResult:O,eventIds:R,venueIds:A,drawIds:M})},modifyTournamentRecord:function(t){const{ratingsParameters:e=CU,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=vv({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===cd&&Ks||p===dd&&Zs||p;if(l){const{stageParticipantsCount:m,uniqueParticipantsCount:I,uniqueParticipantStages:S}=Ev({drawProfiles:l,category:d,gender:t}),{uniqueDrawParticipants:y=[],uniqueParticipantIds:v=[]}=S?zv({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}=Cv({targetParticipants:u.participants||[],allUniqueParticipantIds:g,stageParticipantsCount:m,eventParticipantType:f});let T=Kv({uniqueDrawParticipants:y,autoEntryPositions:a,stageParticipants:w,tournamentRecord:u,drawProfiles:l,category:d,gender:t,event:c});if(T.error)return T;if(T=Hv({matchUpStatusProfile:r,completeAllMatchUps:i,randomWinningSide:s,tournamentRecord:u,drawProfiles:l,event:c}),T.error)return T;U.push(...T.drawIds)}m&&cf({tournamentRecord:u,event:c})}else{const c=Jv({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=Qv({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=VS({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?Av({tournamentRecord:u,venueProfiles:l}):[];let w={};if(c?.length){const t=Jm({tournamentRecords:{[u.tournamentId]:u},schedulingProfile:c});if(t.error)return t;if(m){const{tournamentId:t}=u;w=fv({tournamentRecords:{[t]:u},periodLength:p})}}return{totalParticipantsCount:u.participants.length,scheduledRounds:undefined,schedulerResult:w,...E,eventIds:I,venueIds:v,drawIds:U}},generateEventWithDraw:Qv,generateParticipants:Uv,parseScoreString:_y,generateOutcome:jv,credits:ew};function rw({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=_m(e?.standardGivenName??""),s=_m(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 iw({participantMap:t,participant:e,formats:n}){const{participantType:r,individualParticipantIds:i,person:a}=e,o=r&&n[r];if(r!==Ys&&o){const{personFormat:n,doublesJoiner:s}=o;r===Ks&&(e.participantName=rw({person:a,personFormat:n})),r===Zs&&(e.participantName=i?.map((e=>{const r=t[e]?.person;return rw({person:r,personFormat:n})})).filter(Boolean).join(s??"/"))}}function aw({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&&cr({topic:Qd,payload:{tournamentId:t.tournamentId,participants:n}}),r?{...E,penalty:r}:{error:Xe}}const ow=({penaltyId:t=Ld()}={})=>({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 sw({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(ow()).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&&cr({topic:Qd,payload:{tournamentId:t.tournamentId,participants:s}}),o?{...E,penalty:o}:{error:Xe}}function cw(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]=cw(t[i],e[i],n):r[i]=e[i];else r[i]=e[i];else r[i]=t[i];return r}),{})}function uw({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(ow({penaltyId:o}),{refereeParticipantId:t,penaltyCode:r,penaltyType:i,matchUpId:s,notes:u,issuedAt:c,createdAt:p});return Array.isArray(a)&&a.forEach((t=>Cr({element:l,extension:t}))),d.forEach((t=>{t.penalties||(t.penalties=[]),t.penalties.push(l)})),cr({topic:Qd,payload:{tournamentId:e.tournamentId,participants:d}}),{...E,penaltyId:l.penaltyId}}const dw={addIndividualParticipantIds:ah,addParticipant:eh,addParticipants:wU,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=mm({tournamentRecord:e}).participants??[],a=r?.map(wi("participantId")).filter((t=>n.includes(t)));if(a.length){i=uw({...t,penaltyId:t.penaltyId??i,tournamentRecord:e,participantIds:a}).penaltyId}}return i?{...E,penaltyId:i}:{error:Ee}},addPersons:function({participantRole:t=Dm,tournamentRecord:e,persons:n}){if(!e)return{error:_};if(!Array.isArray(n))return{error:Nn};if(!Object.keys(Rm).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=Ld()),i.push(t.personId),t)));let o=0,s=0,c=wU({participants:a.map((e=>{return br({extensions:e.participantExtensions,timeItems:e.participantTimeItems,participantType:Ks,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=mm({participantFilters:{participantTypes:[Ks]},tournamentRecord:e})?.participants??[];if(t===Dm&&n.filter((({pairedPersons:t})=>t)).forEach((({personId:t,pairedPersons:e})=>{Array.isArray(e)&&e.forEach((e=>{const n=[t,e.personId].map((t=>Ra({tournamentParticipants:d,personId:t}))).filter(Boolean);if(2===n.length){const t=n.map(lo);u.push(br({extensions:e.participantExtensions,timeItems:e.timeItems,participantRole:Dm,individualParticipantIds:t,participantType:Zs}))}}))})),u.length){if(c=wU({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=Nm,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=(mm({participantFilters:{participantTypes:[Ks]},tournamentRecord:r}).participants??[]).map((t=>t.participantId));for(const e of t)if(!o.includes(e))return{error:be,participantId:e};const s=br({participantId:i||Ld(),participantRoleResponsibilities:e,participantName:a,individualParticipantIds:t,participantType:Js,participantRole:n}),c=eh({participant:s,tournamentRecord:r});if(c.error)return c;const{topics:u}=mr();return u.includes(jd)&&cr({topic:jd,payload:{tournamentId:r.tournamentId,participants:[s]}}),{...E,participant:mi(s)}},createTeamsFromParticipantAttributes:gv,deleteParticipants:Cm,filterParticipants:pm,mergeParticipants:function({participants:t=[],tournamentRecord:e,arraysToMerge:n}){if(!e)return{error:_};e.participants||(e.participants=[]);const r=t.filter(wi(Mi)).map((t=>({[t.participantId]:t}))),i=Object.assign({},...r),a=[];e.participants=e.participants.map((t=>{if(i[t.participantId]){const e=cw(t,i[t.participantId],n);return a.push(e),e}return t}));const o=e.participants.map(wi(Mi))||[],s=t.filter((({participantId:t})=>!o.includes(t))),{topics:c}=mr();return s.length&&(e.participants=e.participants.concat(...s),c.includes(jd)&&cr({topic:jd,payload:{participants:s}})),a.length&&c.includes(Qd)&&cr({topic:Qd,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 Nr({result:{error:_},stack:r});if(!e||!t)return Nr({result:{error:ae},stack:r});const i=n.participants||[],a=i.find((t=>t.participantId===e));if(!a)return Nr({result:{error:Ee},stack:r});if(![Xs,Js].includes(a.participantType))return Nr({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!==Ks}));if(o.length)return Nr({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=ah({individualParticipantIds:c,groupingParticipantId:e,tournamentRecord:n});if(d.error)return Nr({result:d,stack:r});const p=Mm({individualParticipantIds:u,groupingParticipantId:e,tournamentRecord:n});if(p.error)return Nr({result:p,stack:r});const{topics:l}=mr();if(l.includes(Qd)){const t=i.find((({participantId:t})=>t===e));cr({topic:Qd,payload:{tournamentId:n.tournamentId,participants:[t]}})}return{...d,...p}},modifyParticipant:oh,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}=ac({tournamentRecord:t,participantId:n});if(!r)return{error:Ee};r.participantName=e;const{topics:i}=mr();return i.includes(Qd)&&cr({topic:Qd,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}=ac({tournamentRecord:t,participantId:e});if(!r)return{error:Ee};r.participantOtherName=n;const{topics:i}=mr();return i.includes(Qd)&&cr({topic:Qd,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(![zs,Hs].includes(n))return{error:Nn,signInState:n};const r=t.participants||[];if(!r.length)return{error:Me};const i=r.map(lo),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=Qm({duplicateValues:!1,tournamentRecord:t,participantId:r,timeItem:{itemType:Ws,itemValue:n,createdAt:s}});if(e.error)return e;o.push(i)}}const{topics:c}=mr();return o.length&&c.includes(Qd)&&cr({topic:Qd,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=sw({...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(!Ui(e))return{error:ae};const n=t.participants??[],r=yi(n,"participantId");for(const t of n)iw({participant:t,participantMap:r,formats:e});return{...E}},removeIndividualParticipantIds:Mm,removeParticipantIdsFromAllTeams:Em,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=aw({...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!==md)return{error:wt};a=l?.entries?.filter((({entryStatus:t})=>t===tu)).map(lo)}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!==Ys)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:Ys,participantRole:Dm}))),{participants:n=[]}=wU({participants:e,returnParticipants:!0,tournamentRecord:o}),r=n.map(lo),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!==Ks)return{error:be,participant:t};const r=em({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(lo);for(const t of o.events??[]){if(t.eventType!==md)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}=wp({event:t});(a?.flights||[]).forEach((t=>{t.drawEntries=(t.drawEntries||[]).filter((t=>!i.includes(t.participantId)))}))}}return{...E,scaledParticipants:i}},setParticipantScaleItem:Ov,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(!Fv({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=>{kv({participant:t,scaleItem:e,removePriorValues:n}),c.push(t),o++}))}));const u=o?void 0:Sn,{topics:d}=mr();if(d.includes(Qd)&&o&&cr({topic:Qd,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:Gd,itemValue:n};if(i&&(a.itemSubTypes=i),e||t){const{drawDefinition:n,event:i}=Tp({tournamentRecord:r,eventId:t,drawId:e});e&&kI({drawDefinition:n,timeItem:a}),t&&ef({event:i,timeItem:a})}else tf({tournamentRecord:r,timeItem:a})}}return i&&d.includes($d)&&cr({topic:$d,payload:i}),br({...E,modificationsApplied:o,info:u})}};function pw(t,e){const n=Fc(t).appliedPolicies??{};if(n[t.policyType]){if(delete n[t.policyType],Object.keys(n).length){Cr({element:e,extension:{name:Fa,value:n}})}else Ar({element:e,name:Fa});return{...E}}return{error:ee}}const lw={attachPolicies:gU,removePolicy:function(t){const e=na(t,[{policyType:!0,_anyOf:{[Pi]:!1,[bi]:!1,[Ni]:!1,[Hi]:!1}}]);if(e.error)return e;let n;const r=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(r)return pw(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=pw(t,t.tournamentRecords[r]);if(e.error)return e;n=!0}}return n?{...E}:{error:ee}}};function mw({removePriorValues:t=!0,tournamentRecord:e,status:n=td}){if(!e)return{error:_};const r=`${Qu}.${ed}`,{timeItem:i}=oc({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}),cr({topic:dp,payload:{tournamentId:e.tournamentId}}),{...E}}function fw({scheduledDates:t=[],removePriorValues:e,tournamentRecord:n,status:r=td,eventIds:i=[]}){if(!n)return{error:_};const a=`${Qu}.${ed}`,{timeItem:o}=oc({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}),cr({topic:sp,payload:{tournamentId:n.tournamentId,scheduledDates:t,eventIds:i}}),{...E}}const hw={getAllEventData:function({tournamentRecord:t,policyDefinitions:e}){if(!t)return{error:_};const n=t.events||[],r=t?.participants||[],{tournamentInfo:i}=rf({tournamentRecord:t}),{venues:a}=Hm({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=sd({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}=nl({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=rm({event:n});return Object.assign(a,{drawsData:s,publish:c}),a}))}}},getCourtInfo:Ip,getDrawData:of,getEventData:sf,getPublishState:am,getVenueData:Up,publishEvent:cf,publishEventSeeding:function({removePriorValues:t=!0,stageSeedingScaleNames:e,seedingScaleNames:n,tournamentRecord:r,status:i=td,drawIds:a=[],event:o}){if(!r)return{error:_};if(!o)return{error:Tt};const s=rm({event:o,status:i}),c=(s?.seeding?.seedingScaleNames||n)&&{...s?.seeding?.seedingScaleNames,...n};return nf({statusObject:{seeding:br({stageSeedingScaleNames:(s?.seeding?.stageSeedingScaleNames||e)&&{...s?.seeding?.stageSeedingScaleNames,...e},seedingScaleNames:c,published:!0,drawIds:a})},removePriorValues:t,status:i,event:o}),cr({topic:op,payload:{tournamentId:r.tournamentId,eventId:o.eventId,drawIds:a}}),{...E}},publishOrderOfPlay:function(t){const e=_d(t);if(!Object.keys(e).length)return{error:x};for(const n of Object.values(e)){const e=fw({tournamentRecord:n,...t});if(e.error)return e}return{...E}},setEventDisplay:function({removePriorValues:t,tournamentRecord:e,displaySettings:n,status:r=td,event:i}){if(!e)return Nr({result:{error:_}});if(!i)return Nr({result:{error:Tt}});if(!Ui(n))return Nr({result:{error:ae}});if(Ui(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=>Si(e.attributes,t.attributes)));e?.dates&&t.dates?e.dates.push(...t.dates):r.push(t)}n.draws[t].scheduleDetails=r}}const a=nf({statusObject:{displaySettings:n},removePriorValues:t,status:r,event:i});return a.error?a:{...E}},unPublishEvent:function({removePriorValues:t=!0,tournamentRecord:e,status:n=td,event:r}){if(!e)return{error:_};if(!r)return{error:Tt};const i=`${Qu}.${ed}`,{timeItem:a}=sc({itemType:i,event:r}),o=a?.itemValue||{[n]:{}};return delete o[n].structureIds,delete o[n].drawDetails,delete o[n].drawIds,ef({event:r,timeItem:{itemValue:o,itemType:i},removePriorValues:t}),nf({statusObject:{structureIds:void 0,drawIds:void 0,seeding:void 0},removePriorValues:t,status:n,event:r}),cr({topic:cp,payload:{tournamentId:e.tournamentId,eventId:r.eventId}}),{eventId:r.eventId,...E}},unPublishEventSeeding:function({removePriorValues:t=!0,seedingScaleNames:e,tournamentRecord:n,status:r=td,drawIds:i,stages:a,event:o}){if(!n)return{error:_};if(!o)return{error:Tt};const s=rm({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),nf({statusObject:{seeding:n},removePriorValues:t,status:r,event:o})}return cr({topic:up,payload:{tournamentId:n.tournamentId,eventId:o.eventId}}),{...E}},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=mw({tournamentRecord:n,...t});if(e.error)return e}return{...E}}};function gw({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}=Fr({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}=Fr({name:e,element:t});i&&n.push({params:{eventId:r,extension:i},method:"addEventExtension"})}}return{methods:n}}const Iw="ADULT",Uw="JUNIOR",Sw="WHEELCHAIR",yw={[va]:{allowModificationWhenMatchUpsScheduled:{courts:!1,venues:!1},defaultTimes:{averageTimes:[{categoryNames:[],minutes:{default:90}}],recoveryTimes:[{minutes:{[lc]:30,default:60}}]},defaultDailyLimits:{[dc]:2,[lc]:2,total:3},matchUpAverageTimes:[{matchUpFormatCodes:[Sg],averageTimes:[{categoryNames:[],minutes:{default:90}},{categoryTypes:[Sw],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:[Iw,Sw],minutes:{default:60,[lc]:30}},{categoryTypes:[Uw],minutes:{default:60,[lc]: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:[Iw,Sw],minutes:{default:30}},{categoryTypes:[Uw],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:[Iw,Uw],minutes:{default:30}},{categoryTypes:[Sw],minutes:{default:15}}]},{matchUpFormatCodes:["SET1-S:TB10"],recoveryTimes:[{categoryNames:[],minutes:{default:15}}]}],matchUpDailyLimits:[]}};function vw(t){const e=na(t,[{[bi]:!0},{[Ji]:t=>Sh({matchUpFormat:t}),[Zi]:kt,[Ri]:!0}]);if(e.error)return e;const{tournamentRecord:n,matchUpFormat:r,event:i}=t,{extension:a}=Fr({name:Qa,element:i}),o=a?.value,{extension:s}=Fr({element:n,name:Qa}),c=s?.value,u=[o?.matchUpAverageTimes&&id({...o,matchUpFormat:r}),c?.matchUpAverageTimes&&id({...c,matchUpFormat:r})].find((t=>t));return{matchUpFormat:r,recoveryTimes:[o?.matchUpRecoveryTimes&&ad({...o,matchUpFormat:r}),c?.matchUpRecoveryTimes&&ad({...c,matchUpFormat:r})].find((t=>t)),averageTimes:u}}function ww({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 Tw({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&&ti(e.scheduledDate)||e.scheduledTime&&ti(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&&Qr(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 Pw({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 Dw(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,...br({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}=wc({participantsProfile:o,policyDefinitions:c,useParticipantMap:u,tournamentRecord:d,contextProfile:f,inContext:I})),f&&!n&&(n=qc({policyDefinitions:c,tournamentRecord:d,contextProfile:f,event:S}));const D=rm({event:S});return{...(S.drawDefinitions??[]).reduce(((t,u)=>{const g=nl({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 bw(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}=wc({participantsProfile:r,policyDefinitions:a,useParticipantMap:o,tournamentRecord:s,contextProfile:l,inContext:c});l&&!e&&(e=qc({policyDefinitions:a,tournamentRecord:s,contextProfile:l}));const{appliedPolicies:y}=Fc({tournamentRecord:s}),v=d?.eventIds??[];return{...g.filter((t=>!v.includes(t.eventId))).map((t=>{const o=wp({event:t}).flightProfile;return Dw({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 Nw({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 bw({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 Rw(t){if("object"!=typeof t?.tournamentRecords||!Object.keys(t?.tournamentRecords).length)return{error:x};const{courts:e,venues:n}=Hm(t),r=Km(t).schedulingProfile,{sortDateMatchUps:i=!0,courtCompletedMatchUps:a,alwaysReturnCompleted:o,activeTournamentId:s,tournamentRecords:c,withCourtGridRows:u,minCourtGridRows:d,usePublishState:p,status:l=td,sortCourtsData:m}=t,f=p?cc({tournamentRecord:c[s??hr()],itemType:`${Qu}.${ed}`}).timeItem?.itemValue?.[l]:void 0,h=o?Nw({...t,matchUpFilters:{...t.matchUpFilters,matchUpStatuses:[Uo]},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=rm({event:t}),i=r?.drawDetails;Ui(i)?(Object.assign(n,i),e.push(...Object.keys(i).filter((t=>im({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(Uo)||t.matchUpFilters.excludeMatchUpStatuses.push(Uo):t.matchUpFilters.excludeMatchUpStatuses=[Uo]);const{completedMatchUps:U,upcomingMatchUps:S,pendingMatchUps:y,groupInfo:v}=Nw({...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?Tw({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?Tw({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}=Pw({minRowsCount:d,courtsData:P});D.courtPrefix=e,D.rows=t}return{...D,...E}}function Mw({targetRoundNumber:t,finishingPosition:e,drawDefinition:n,structureId:r,linkType:i}){const{links:a}=bc({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}=Vs({structureId:r,drawDefinition:n});if(!e||i?.finishingPosition===e)return t})).filter(Boolean);return{sourceStructureIds:o.map((({source:t})=>t.structureId)),relevantLinks:o}}const Aw="qualifierDrawPositionAssignment",Ew="alternateDrawPositionAssignment",Cw="luckyLoserDrawPositionAssignment",Ow="removeDrawPositionAssignment",Fw="swapDrawPositionAssignments",kw="modifyPairAssignment",xw="assignDrawPosition",_w="assignDrawPositionBye",Lw="addPenalty",Bw="MODIFY_PAIR",Vw="QUALIFIER",jw="ALTERNATE",Gw="WITHDRAW",qw="ASSIGN",$w="REMOVE",Ww="LUCKY",Hw="REMOVE_SEED",zw="SWAP",Yw="NICKNAME",Kw="SEED_VALUE",Jw="PENALTY",Zw="BYE",Xw={MODIFY_PAIR_ASSIGNMENT:Bw,QUALIFYING_PARTICIPANT:Vw,ALTERNATE_PARTICIPANT:jw,WITHDRAW_PARTICIPANT:Gw,ASSIGN_PARTICIPANT:qw,LUCKY_PARTICIPANT:Ww,REMOVE_ASSIGNMENT:$w,SWAP_PARTICIPANTS:zw,ADD_NICKNAME:Yw,REMOVE_SEED:Hw,ADD_PENALTY:Jw,ASSIGN_BYE:Zw,SEED_VALUE:Kw};function Qw({restrictQualifyingAlternates:t,structure:e,entry:n}){const{stage:r}=e;if(!n.entryStage||n.entryStage===r||r===Vo&&!t||n.entryStage===Bo&&r===jo)return!0}function tT(t,e){return t.bye||Af(t.seedValue)<Af(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function eT({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}=Xp({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 br({...t,participant:o?mi(e,!1,!0):void 0,sourceDrawPositionRange:n})}));if(P.length){return{validSwapAction:{payload:{drawId:m,structureId:p,drawPositions:[d]},willDisableLinks:e,method:Fw,type:zw,availableAssignments:P}}}return{}}const nT={[ha]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[Vo,Bo],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[Yw,Jw,Vw,Kw],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}},rT="positionAction",iT="matchUpAction";function aT({actionType:t=rT,appliedPolicies:e,drawDefinition:n,structure:r}){const i=t===rT&&ha||t===iT&&ga,a=t===rT&&nT||t===iT&&Tm,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 oT({activePositionOverrides:t,activeDrawPositions:e,action:n}){return!(!n||!t.includes(n))||!e.length}function sT({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 cT({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 uT="replaceTieMatchUpParticipantId",dT="assignTieMatchUpParticipantId",pT="removeTieMatchUpParticipantId",lT="assignMatchUpSideParticipant",mT="removeMatchUpSideParticipant",fT="substituteParticipant",hT="REMOVE_SUBSTITUTION",gT="REPLACE_PARTICIPANT",IT="REMOVE_PARTICIPANT",UT="setMatchUpStatus",ST="SUBSTITUTION",yT="SCHEDULE",vT="REFEREE",wT="STATUS",TT="START",PT="SCORE",DT="END",bT={REPLACE_TEAM_POSITION_METHOD:uT,ASSIGN_TEAM_POSITION_METHOD:dT,REMOVE_TEAM_POSITION_METHOD:pT,REPLACE_PARTICIPANT:gT,SUBSTITUTION_METHOD:fT,REMOVE_SUBSTITUTION:hT,REMOVE_PARTICIPANT:IT,SCHEDULE_METHOD:UT,SUBSTITUTION:ST,SCHEDULE:yT,PENALTY:"PENALTY",REFEREE:vT,STATUS:wT,SCORE:PT,START:TT,END:DT};function NT({restrictAdHocRoundParticipants:t,tournamentParticipants:e,matchUpParticipantIds:n,otherFlightEntries:r,drawDefinition:i,structureId:a,sideNumber:o,matchUpId:s,structure:c,matchUp:u,drawId:d,event:p}){const l=[],f=(c?.matchUps??[]).filter((({roundNumber:t})=>t===u.roundNumber)),h=i?.entries?.filter((({entryStatus:t})=>t&&mu.includes(t))).map(wi("participantId"))??[],g=f.map((t=>(t.sides??[]).flatMap(wi("participantId")))).flat().filter(Boolean),I=h.filter((e=>!(n.includes(e)||t&&g.includes(e)))),U=e?.filter((t=>I?.includes(t.participantId))).map((t=>mi(t,void 0,!0)));U?.forEach((t=>{const e=(i.entries??[]).find((e=>e.participantId===t.participantId));t.entryPosition=e?.entryPosition})),I.length&&l.push({payload:{drawId:d,matchUpId:s,structureId:a,sideNumber:o},method:lT,type:qw,availableParticipantIds:I,participantsAvailable:U});const S=function({eventEntries:t,structure:e}){return t.filter((t=>t.entryStatus===Xc&&Qw({structure:e,entry:t}))).sort(((t,e)=>(t.entryPosition||1/0)-(e.entryPosition||1/0))).map(wi("participantId"))}({eventEntries:p?.entries??[],structure:c});let y=m(h.concat(S));if(r){const t=p?wp({event:p}):void 0,e=t?.flights?.filter((t=>t.drawId!==d)).flatMap((t=>t.drawEntries.filter((t=>t.participantId&&![du,su,cu].includes(t.entryStatus))).map((({participantId:t})=>t)))).filter(Boolean);e?.length&&y.push(...e)}y=y.filter((e=>!(n.includes(e)||I.includes(e)||t&&g.includes(e))));const v=e?.filter((t=>y.includes(t.participantId))).map((t=>mi(t,void 0,!0)));if(v?.forEach((t=>{const e=(i.entries??[]).find((e=>e.participantId===t.participantId));t.entryPosition=e?.entryPosition})),v?.sort(((t,e)=>(t.entryPosition||1/0)-(e.entryPosition||1/0))),y.length&&l.push({payload:{drawId:d,matchUpId:s,structureId:a,sideNumber:o},availableParticipantIds:y,participantsAvailable:v,method:lT,type:Xc}),!Tl(u)&&o){const t=u.sides?.find((t=>t.sideNumber===o));t?.participantId&&l.push({payload:{drawId:d,matchUpId:s,structureId:a,sideNumber:o},method:mT,type:IT})}return l}function RT(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&&Ii(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:_};if(!c||!Ii(c))return{error:qt};if(s&&![1,2].includes(s))return Nr({result:{error:Nn},context:{sideNumber:s}});if(!e){const t=(El({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=mm({tournamentRecord:u,withIndividualParticipants:!0}).participants,{drawId:p}=e,{matchUp:l,structure:m}=hf({drawDefinition:e,matchUpId:c,event:n});if(!l)return{error:Wt};const f=Fc({tournamentRecord:u,drawDefinition:e,structure:m,event:n}).appliedPolicies??{};Object.assign(f,i??{});const h=f?.[ha]?.otherFlightEntries,g=f?.[ga]??Tm[ga],{enabledStructures:I}=aT({actionType:iT,appliedPolicies:f,drawDefinition:e,structure:m}),{policyActions:U}=sT({enabledStructures:I,drawDefinition:e,structure:m}),S=t.matchUpsMap??Wc({drawDefinition:e}),y=t.inContextDrawMatchUps??el({tournamentParticipants:d,inContext:!0,drawDefinition:e,matchUpsMap:S,event:n}).matchUps,v=y?.find((t=>t.matchUpId===c)),w=s&&v?.sides?.find((t=>t.sideNumber===s)),T=v?.sides?.map((t=>t.participantId||t.participant?.participantid)).filter(Boolean)??[],{assignedPositions:P,allPositionsAssigned:D}=$s({structure:m}),{structureId:b}=m??{},N=[];if(!b)return{validActions:N};const R=jp({drawDefinition:e,structure:m}),M=l.collectionId;if(R&&!M){const t=NT({restrictAdHocRoundParticipants:r,tournamentParticipants:d,matchUpParticipantIds:T,otherFlightEntries:h,drawDefinition:e,structureId:b,sideNumber:s,matchUpId:c,structure:m,matchUp:l,drawId:p,event:n});N.push(...t)}const A=Wh({drawDefinition:e,structure:m}),E=P?.filter((t=>t.participantId)).map((t=>t.drawPosition)),C=P?.filter((t=>t.bye)).map((t=>t.drawPosition)),O=l.matchUpStatus===go||!M&&l.drawPositions?.reduce(((t,e)=>C?.includes(e)||t),!1);if(O)return{validActions:N,isByeMatchUp:O};cT({policyActions:U,action:vT})&&N.push({type:vT,payload:{matchUpId:c}});const F=!Pl({matchUpStatus:l.matchUpStatus}),k=f?.scoring?.structures,x=m?.stage&&k?.stage&&k?.stage[m.stage],L=m?.stageSequence&&x?.stageSequence&&x.stageSequence[m.stageSequence],B=!(f?.scoring?.requireAllPositionsAssigned||x?.requireAllPositionsAssigned||L?.requireAllPositionsAssigned)||D,V=l.sides&&2===l.sides.filter((t=>t?.participantId)).length,G=l.matchUpStatus&&[wo,vo].includes(l.matchUpStatus),q=dI({inContextDrawMatchUps:y,drawDefinition:e,targetData:Nc({inContextDrawMatchUps:y,drawDefinition:e,matchUpId:c})}),$=(2===v?.drawPositions?.length&&v.drawPositions.every((t=>E?.includes(t)))&&2===v?.sides?.length&&v.sides.every((({participantId:t})=>t))||V)&&!(G&&q),W={method:Lw,type:Jw,payload:{drawId:p,matchUpId:c,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};if(F&&N.push({payload:{drawId:p,matchUpId:c,schedule:{}},method:UT,type:yT}),cT({policyActions:U,action:Jw})&&(w?.participant||!s&&T?.length)&&N.push(W),F&&$&&N.push({type:wT}),B&&$){const{matchUpId:t,matchUpFormat:e}=l,n={drawId:p,matchUpId:t,matchUpFormat:e,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};N.push({info:"set outcome and winningSide",method:UT,type:PT,payload:n}),cT({policyActions:U,action:TT})&&N.push({type:TT}),cT({policyActions:U,action:DT})&&N.push({type:DT})}if(M&&v){const t=function({specifiedPolicyDefinitions:t,inContextDrawMatchUps:e,matchUpParticipantIds:n,matchUpActionsPolicy:r,inContextMatchUp:i,policyActions:a,enforceGender:o,participantId:s,sideNumber:c,matchUpId:u,matchUp:d,drawId:p,side:l}){const m=[],f=i.sides?.find((t=>t.participant)),h=i.gender===Yp&&i.sideNumber&&1===i.sides?.filter((t=>t.particiapntId)).length&&f?.participant?.person?.sex,g=i.matchUpType,I=!1!==(o??r?.participants?.enforceGender)?i.gender:void 0,U=i.sides?.flatMap((t=>t.participant?.individualParticipants||t.participant)).filter(Boolean),S=U?.map(wi("participantId")),y=i.sides?.filter((t=>!c||t.sideNumber===c)).flatMap((t=>t.participant?.individualParticipants||t.participant)).filter(Boolean),v=y?.map(wi("participantId")),w=e?.find((t=>t.matchUpId===i.matchUpTieId)),T=w?.sides?.map((t=>t.participant?.individualParticipants.filter((({participantId:t,person:e})=>!v?.includes(t)&&(!I||I===Hp||e.sex===I||I===Yp&&!h||h&&e.sex!==h))))),P=c?T?.[c-1]:T?.map(((t,e)=>({participants:t,sideNumber:e+1}))),D=c?T?.[c-1]?.map(lo):T?.map(((t,e)=>({participants:t?.map(lo),sideNumber:e+1}))),b=c&&(g===uc&&!v?.length||g===pc&&(v?.length??0)<2)||!c&&(g===uc&&(v?.length??0)<2||g===pc&&(v?.length??0)<4),N=D?.filter((t=>!S?.includes(t))),R=P?.filter((({participantId:t})=>N.includes(t)));if(b&&N?.length&&m.push({availableParticipantIds:N,method:dT,availableParticipants:R,type:qw,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:p}}),!v?.length||Tl(d)&&!l?.substitutions?.length||m.push({method:pT,type:IT,existingParticipantIds:v,payload:{participantId:void 0,tieMatchUpId:u,drawId:p}}),R?.length&&(!c&&v?.length||c&&l?.participant)&&m.push({availableParticipantIds:N,method:uT,availableParticipants:R,type:gT,existingParticipantIds:v,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:p}}),cT({policyActions:a,action:hT})&&l?.substitutions?.length){const t=l.participant?.participantType===Ks&&[l.participantId]||l.participant?.participantType===Zs&&l.participant.individualParticipantIds||[],e=l.substitutions.map((t=>t.participantId)).filter((e=>t.includes(e)));s&&!e.includes(s)||m.push({method:pT,type:hT,substitutedParticipantIds:e,payload:{participantId:void 0,tieMatchUpId:u,drawId:p}})}const M=t?.[ga],A=M?.substituteWithoutScore,E=M?.substituteAfterCompleted;if(cT({policyActions:a,action:ST})&&2===n.length&&(!c&&v?.length||c&&l?.participant)&&(A||Tl(d))&&(E||d.matchUpStatus&&!ko.includes(d.matchUpStatus))&&y?.length&&P.length){const t=y.map(lo);m.push({info:"list of team players available for substitution",method:fT,availableParticipantIds:D,existingParticipantIds:t,availableParticipants:P,existingParticipants:y,type:ST,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:p}})}return m}({specifiedPolicyDefinitions:i,inContextDrawMatchUps:y,matchUpParticipantIds:T,matchUpActionsPolicy:g,inContextMatchUp:v,policyActions:U,enforceGender:a,participantId:o,sideNumber:s,matchUpId:c,matchUp:l,drawId:p,side:w});N.push(...t)}return{structureIsComplete:A,validActions:N,isDoubleExit:G}}function MT({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}=AT({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}=AT({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 AT({singlesForDoubles:t,valueAccessor:e,matchUpType:n,participant:r,scaleName:i}){const a=t?dc: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 ET(t){const e=t.participants?.filter((({participantType:t})=>t===Xs)),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 CT(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 br({structureId:u,roundSegment:n,tournamentId:i,roundNumber:a,eventId:s,drawId:c,id:d})}function OT({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=Ky({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 FT(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||ko.includes(e))).length||0,i=t.filter((({schedule:t,matchUpStatus:e})=>t?.scheduledDate&&t?.scheduledTime&&e!==go)).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 kT({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=qm({tournamentRecords:t,schedulingProfile:e});if(n.error)return n}if(!e&&t){const n=Km({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=CT(t);return n.roundSegment?.segmentsCount&&(i[n.id]=n.roundSegment.segmentsCount),br({id:r?n.id:void 0,scheduleDate:e,...n})})))))).flat(1/0),segmentedRounds:i}}const{stageOrder:xT}=_s;function _T(t,e){return t.eventName.localeCompare(e.eventName)||t.eventId.localeCompare(e.eventId)||(xT[t?.stage]||0)-(xT[e?.stage]||0)||e.matchUpsCount-t.matchUpsCount||`${t.stageSequence}-${t.roundNumber}-${t.minFinishingSum}`.localeCompare(`${e.stageSequence}-${e.roundNumber}-${e.minFinishingSum}`)}const LT={allCompetitionMatchUps:Cl,allDrawMatchUps:rl,allEventMatchUps:Al,allTournamentMatchUps:El,analyzeDraws:yU,analyzeMatchUp:Bv,analyzeTournament:function({tournamentRecord:t}){if(!t)return{error:_};const{drawsAnalysis:e}=yU({tournamentRecord:t}),n={isDual:ET(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=rm({event:t}),{drawDetails:r,drawIds:i}=e??{},{eventId:a}=t;return n[a].filter((t=>{const n=r?Object.keys(e.drawDetails).filter((t=>im({drawId:t,drawDetails:r}))):[];return i?.includes(t)||n.includes(t)})).length})).map((t=>t.eventId)),eventIdPublishedDrawIdsMap:n}},categoryCanContain:Nh,checkMatchUpIsComplete:Qp,checkValidEntries:ry,competitionScheduleMatchUps:Rw,credits:ew,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,...br({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}=wc({participantsProfile:r,policyDefinitions:a,useParticipantMap:o,tournamentRecord:s,contextProfile:f,inContext:U})),y&&f&&!d&&(d=qc({policyDefinitions:a,tournamentRecord:s,contextProfile:f,drawDefinition:h,event:y})),{...nl({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:Dw,findDrawDefinition:function({tournamentRecord:t,drawDefinition:e}){return t?e?{drawDefinition:mi(e)}:{error:at}:{error:_}},findExtension:Fr,findMatchUp:Hf,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=Ra({tournamentParticipants:t.participants||[],internalUse:!0,policyDefinitions:n,contextProfile:r,participantId:i,personId:a}),s)break}return{participant:s,tournamentId:c,...E}},findPolicy:bu,getAllDrawMatchUps:el,getAllowedDrawTypes:ny,getAllowedMatchUpFormats:function({tournamentRecord:t,categoryName:e,categoryType:n}){if(!t)return{error:_};const{appliedPolicies:r}=Fc({tournamentRecord:t}),i=r?.[Ta];return(i?.matchUpFormats||[]).filter((({categoryNames:t,categoryTypes:r})=>!e&&!r||e&&t?.includes(e)||n&&r?.includes(n)))},getAppliedPolicies:Fc,getAssignedParticipantIds:Jl,getCompetitionDateRange:Zv,getCompetitionMatchUps:Nw,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}=mm({...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}=ww({tournamentRecord:n});e.push(...t??[])}return{penalties:e}},getCompetitionVenues:zm,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=mi(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}=oc({element:e,returnPreviousValues:t,itemSubTypes:n,itemType:r});return i&&{timeItem:i,previousItems:a}||{info:o}},getDrawParticipantRepresentativeIds:function({drawDefinition:t}){const e=Fr({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value||[]}},getDrawTypeCoercion:JS,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=[Bo,qo];n&&f.push(Vo);const h=m?.eventType?{matchUpTypes:[m.eventType]}:void 0,g=s?.matchUpType?{matchUpTypes:[s.matchUpType]}:void 0,I=e&&m?Al({contextFilters:{stages:f},matchUpFilters:h,tournamentRecord:o,inContext:!0,event:m})?.matchUps??[]:rl({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:o,inContext:!0,drawDefinition:s})?.matchUps??[],U=Su({stage:Go,drawDefinition:s}).map((({participantId:t})=>t)),S={},y={},v={},w={};i||(i=kc({policyTypes:[la],tournamentRecord:o,drawDefinition:s,event:m}).policyDefinitions);const T=i?.[la];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!==wo)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!==wo||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=>![du,su].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:zU,getEvent:function({tournamentRecord:t,drawDefinition:e,context:n,event:r}){if(!t)return{error:_};if(!r)return{error:Tt};const i=mi(r);return n&&Object.assign(i,n),br({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)&&Sh({matchUpFormat:n?.matchUpFormat}))return t.push(n.matchUpFormat),n})).filter(Boolean)}else{const{policy:e}=bu({policyType:Ta,tournamentRecord:t,event:r});if(e?.matchUpFormats)a=e?.matchUpFormats;else{const{extension:t}=Fr({name:Qa,element:r});let e,n;({matchUpAverageTimes:e,matchUpRecoveryTimes:n}=t?.value?t.value:yw[va]),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?br({eventMatchUpFormatTiming:a.map((({matchUpFormat:e,description:i})=>({matchUpFormat:e,description:i,...Nd({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:Xu,eventType:a,scaleName:i};const d=em({participant:t,scaleAttributes:o})?.scaleItem?.scaleValue;o={scaleType:Zu,eventType:a,scaleName:i};const p=em({participant:t,scaleAttributes:o})?.scaleItem?.scaleValue;o={scaleType:Ju,eventType:a,scaleName:i};const l=em({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(wi("drawId"));if(o?.length&&!P(o,e).length)return;const n=mi(t);return r&&Object.assign(n,{tournamentId:c}),s&&Object.assign(n,s),n})).filter(Boolean),d={};if(e){const e=mm({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})=>fu.includes(t))).map(wi(Mi)),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=CU[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!==Ks)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=CU[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!==Ks)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=Jl({drawDefinition:e}).assignedParticipantIds??[];d[s].draws[t]||(d[s].draws[t]={ratingsStats:{},ratings:{},ranking:{}}),m.push(t),l(t,n)}const h=wp({event:t}).flightProfile;for(const t of h?.flights??[]){const e=t.drawId;if(f(e))continue;l(e,t.drawEntries.map(wi(Mi)))}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 br({eventScaleValues:d,events:u,...E})},getEventStructures:$h,getEventTimeItem:sc,getFlightProfile:wp,getLinkedTournamentIds:xd,getMatchUpCompetitiveProfile:Nu,getMatchUpDailyLimits:By,getMatchUpDailyLimitsUpdate:function({tournamentRecords:t}){return gw({extensionName:Xa,tournamentRecords:t})},getMatchUpDependencies:Fl,getMatchUpFormat:function(t){const{structureId:e,matchUpId:n,event:r}=t;let i=t.drawDefinition;const a=na(t,[{[bi]:!0},{_anyOf:{[Ei]:!1,[ki]:!1,[$i]:!1,[Hi]:!1}}]);if(a[Wi])return a;const o=Yf(t,[{[zi]:qi,[Wi]: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=Vs({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:Nd,getMatchUpFormatTimingUpdate:function({tournamentRecords:t}){return gw({extensionName:Qa,tournamentRecords:t})},getMatchUpScheduleDetails:Pp,getMatchUpsStats:function({profileBands:t,tournamentRecord:e,matchUps:n}){if(!Mc(n))return{error:Ht};const r=!t&&bu({policyType:ma,tournamentRecord:e}).policy,i=t||r?.profileBands||Gc[ma].profileBands,a=n.filter((({winningSide:t})=>t)),o=Du(a.map(Tu)).reduce(((t,e)=>((t,e)=>(t[wu(e,i)]+=1,t))(t,e)),{[Lc]:0,[Bc]:0,[Vc]:0,[xc]: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===_c)).length;return c.push({[_c]:100*parseFloat((u/s).toFixed(4))}),{competitiveBands:Object.assign({},...c),...E}},getMatchUpType:qp,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:vw,getPairedParticipant:Yc,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&&[Xs,Zs].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=mi(el({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=>[Uo,go].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}=mm({participantFilters:{participantTypes:[Xs,Zs,Js]},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:mm,getParticipantScaleItem:KU,getParticipantSchedules:function({participantFilters:t={},tournamentRecord:e}){if(!e)return{error:_};if("object"!=typeof t)return{error:Pn,context:{participantFilters:t}};const n=El({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=Fl({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}=ac({tournamentRecord:t,participantId:e});if(!n)return{error:Ee};const{timeItem:r}=oc({itemType:Ws,element:n});return r&&r.itemValue===zs&&zs},getParticipantTimeItem:function({returnPreviousValues:t,tournamentRecord:e,participantId:n,itemSubTypes:r,itemType:i}){if(!e)return{error:_};if(!n)return{error:Ae};const a=ac({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}=oc({element:a.participant,returnPreviousValues:t,itemSubTypes:r,itemType:i});return s&&{timeItem:s,previousItems:c}||{info:u}},getPersonRequests:dv,getPolicyDefinitions:kc,getPositionAssignments:jm,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&&![dc,lc].includes(c))return{error:Nn,info:{matchUpType:c}};if(e&&!Mc(e))return{error:Nn,context:{matchUps:e}};const h=CU[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]:[dc,lc]},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&&rl({inContext:!0,drawDefinition:i,contextFilters:v,contextProfile:y,participants:w})?.matchUps||!m&&d&&Al({inContext:!0,contextFilters:v,contextProfile:y,participants:w,event:f})?.matchUps||El({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})=>![bo,yo,Mo,So,fo].includes(r??"")&&Tl({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=MT({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!==dc?2*(S||0):S,b=S?T.map((({competitiveProfile:t,matchUpType:e,score:r,sides:i})=>{const a=MT({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={[Lc]:[],[Bc]:[],[Vc]:[]};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:Ac,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)&&kT({tournamentRecords:i,schedulingProfile:a})||{},U=t&&Object.assign({},...I.map((t=>({[t.id]:t})))),S=r||i&&Cl({tournamentRecords:i,matchUpFilters:c})?.matchUps||[],y=[],v=S&&Object.values(S.reduce(((t,e)=>{const n=CT(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}=FT(a),f=OT({matchUps:t.matchUps,tournamentRecords:i,events:h,round:t});return br({...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}=FT(t.matchUps),p=OT({matchUps:t.matchUps,tournamentRecords:i,events:h,round:t});return br({...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=ti(t),n=d?r.id:CT(r).id;if(e&&U[n]&&ti(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(_T)||[];return{...E,rounds:v,excludedRounds:y}},getScaledEntries:JU,getScheduledRoundsDetails:Jy,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(Gr))return{error:pe};const i=[];let a=0;const o={},{schedulingProfile:s}=Km({tournamentRecords:n});if(!s)return{issues:i,...E};const{matchUps:c}=Cl({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}=Jy({tournamentRecords:n,periodLength:r,matchUps:c,rounds:e}),{matchUpDependencies:l}=Fl({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:HU,getStructureSeedAssignments:yu,getTeamLineUp:Kc,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 Nr({result:{error:ae},stack:"getTieFormat"});a&&!s&&(s=t.events?.find((t=>t.eventId===a)));const c=Hf({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=Vs({drawDefinition:e,structureId:n});if(t.error)return t;i=t.structure}const u=(i?.tieFormat||i?.tieFormatId)&&Np({structure:i,drawDefinition:e,event:s})?.tieFormat,d=(e?.tieFormat||e?.tieFormatId)&&Np({drawDefinition:e,event:s})?.tieFormat,p=Np({event:s})?.tieFormat,l=Np({matchUp:c?.matchUp,drawDefinition:e,structure:i,event:s})?.tieFormat;return{...E,matchUp:c?.matchUp,structureDefaultTieFormat:dh(u),eventDefaultTieFormat:dh(p),drawDefaultTieFormat:dh(d),tieFormat:dh(l),structure:i}},getTournamentIds:oo,getTournamentInfo:rf,getTournamentPenalties:ww,getTournamentPersons:function({tournamentRecord:t,participantFilters:e}){if(!t)return{error:_};let n=t.participants||[];e&&(n=pm({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}=$h({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:cc,getVenuesAndCourts:Hm,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(Gr))return{error:pe};const a=Hm({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}=Cl({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&&gy({courtDate:r}),a=i?.reduce(((t,e)=>{const{startTime:n,endTime:r}=e;return t+(Zr(r)-Zr(n))}),0);a&&(s+=1),e+=a}const c=n.filter((({schedule:e})=>e.venueId===r&&pi(t,e.scheduledDate)));c.forEach((({schedule:t})=>{const e=Qr(t.scheduledTime),n=Zr(ci(e,t.averageMinutes))-Zr(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(!Ii(t))return{error:Nn};const n=bc({drawDefinition:e,structureId:t});if(n.error)return n;const r=n.links.target.flatMap((t=>t.target.feedProfile)).filter(Boolean),i=!P([rs,ns,es,Zo],r).length;return{...E,valid:i}},isValidMatchUpFormat:Sh,matchUpActions:RT,participantScaleItem:em,participantScheduledMatchUps:function({scheduleAttributes:t=["scheduledDate","scheduledTime"],matchUps:e=[]}){if(!Mc(e))return{error:Ht};if(!Array.isArray(t))return{error:Nn};const n=e.filter(Boolean).filter((({schedule:e})=>Qy({schedule:e,scheduleAttributes:t}))).reduce(((t,e)=>{const{schedule:n}=e,r=ti(n?.scheduledDate),i=Qr(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)=>ii(Qr(t.schedule?.scheduledTime),Qr(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&&mm({withIndividualParticipants:!0,tournamentRecord:i}).participants)??[];let u=Vs({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=kl({drawDefinition:a,structureId:p}),void 0===o&&!u.isAdHoc)return{error:tt};if(u.isAdHoc)return RT(t);if(u.error)return u;const{drawPositionInitialRounds:l,inactiveDrawPositions:f,activeDrawPositions:h,byeDrawPositions:g}=u,I=Fc({tournamentRecord:i,drawDefinition:a,structure:d,event:s}).appliedPolicies??{};Object.assign(I,e??{});const{actionsPolicy:U,enabledStructures:S,actionsDisabled:y}=aT({actionType:rT,appliedPolicies:I,drawDefinition:a,structure:d}),v=U?.activePositionOverrides||[],{sourceStructureIds:w}=Mw({finishingPosition:Fs,targetRoundNumber:1,linkType:is,drawDefinition:a,structureId:p})||{};let T;w?.length&&(T=w.reduce(((t,e)=>Wh({structureId:e,drawDefinition:a})&&t),!0));const P=w.length,D=w.length&&!T,{policyActions:b}=sT({enabledStructures:S,drawDefinition:a,structure:d}),N=![Vo,Bo].includes(d.stage)||1!==d.stageSequence,{drawId:R}=a,M=[],{assignedPositions:A,positionAssignments:E}=$s({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===jo&&x.push(Bo),F===Bo&&x.push(jo);const _=Su({entryStatuses:mu,provisionalPositioning:r,drawDefinition:a,stageSequence:k,structureId:p,stages:x}),L=Jl({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(cT({policyActions:b,action:qw})&&!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?.[Pa]?.validSeedPositions?.ignore;if(!v){const t=kf({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:_w,type:Zw}),a&&v){const e=o.map((t=>t.participantId)).filter(Boolean),r={structureIds:t},{completedMatchUps:a}=nl({inContext:!0,matchUpFilters:r,drawDefinition:u}),c=m((a??[]).filter((({matchUpType:t})=>h?.eventType!==ld||t===ld))?.map((({sides:t})=>t?.map(wi("participantId")))).flat().filter((t=>t&&!e.includes(t)))),d=s?i?.filter((t=>c?.includes(t.participantId))).map((t=>mi(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(br({payload:{drawId:g,structureId:f,drawPosition:l},willDisableLinks:n,method:xw,type:qw,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(tT),t=e.map((t=>t.participantId))}else t=e;const r=s?i?.filter((e=>t.includes(e.participantId))).map((t=>mi(t,void 0,!0))):void 0;r?.length&&I.push(br({payload:{drawId:g,structureId:f,drawPosition:l},willDisableLinks:n,method:xw,type:qw,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(cT({policyActions:b,action:Vw})){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?.[ha],h=!f?.disableRoundRestrictions&&t[o],g=f?.requireCompletedStructures,{sourceStructureIds:I,relevantLinks:U}=Mw({targetRoundNumber:h,linkType:as,drawDefinition:a,structureId:s})||{};I?.length&&l.push(...I);const{sourceStructureIds:S,relevantLinks:y}=Mw({targetRoundNumber:h,linkType:is,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!==Vo)continue;const i=Wh({structureId:t.source.structureId,drawDefinition:a});if(!g||i){const t=n.qualifyingRoundNumber,{matchUps:i}=Xp({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===go&&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!==Vo)continue;const i=Wh({structureId:t.source.structureId,drawDefinition:a});if(!g||i){const{positionAssignments:t}=qs({structure:n}),i=t?.map((t=>{const e=t.participantId,n=Fr({element:t,name:no}).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(br({payload:{qualifyingParticipantId:void 0,drawPosition:o,structureId:s,drawId:c},method:Aw,type:Vw,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){cT({policyActions:b,action:$w})&&!G&&(M.push({type:$w,method:Ow,payload:{drawId:R,structureId:p,drawPosition:o},willDisableLinks:N}),V||M.push({type:Gw,method:"withdrawParticipantAtDrawPosition",payload:{drawId:R,structureId:p,drawPosition:o},willDisableLinks:N}),cT({policyActions:b,action:Zw})&&!V&&M.push({type:Zw,method:Ow,payload:{drawId:R,structureId:p,drawPosition:o,replaceWithBye:!0},willDisableLinks:N}));const t=d.stage===Vo||d.stage===Bo&&1===d.stageSequence;if(!V&&oT({activePositionOverrides:v,activeDrawPositions:h,action:Kw})&&cT({policyActions:b,action:Kw})&&Ff({drawDefinition:a,structureId:p,drawPosition:o})&&t){const{seedAssignments:t}=yu({returnAllProxies:!0,drawDefinition:a,structure:d}),{seedNumber:e,seedValue:n}=t?.find((t=>t.participantId===q))??{};M.push({type:Kw,method:"modifySeedAssignment",participant:$,seedNumber:e,payload:{drawId:R,structureId:p,participantId:q,seedValue:n}})}if(!V&&oT({activePositionOverrides:v,activeDrawPositions:h,action:Hw})&&cT({policyActions:b,action:Hw})&&Ff({drawDefinition:a,structureId:p,drawPosition:o})&&t){const{seedAssignments:t}=yu({returnAllProxies:!0,drawDefinition:a,structure:d}),{seedNumber:e}=t?.find((t=>t.participantId===q))??{};M.push({method:"removeSeededParticipant",type:Hw,participant:$,seedNumber:e,payload:{participantId:q,structureId:p,drawId:R}})}if(!V&&q){if(cT({policyActions:b,action:Jw})){const t={type:Jw,method:Lw,participant:$,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:R}};M.push(t)}if(cT({policyActions:b,action:Yw})){const t={type:Yw,method:"modifyParticipantOtherName",participant:$,payload:{participantId:q,otherName:void 0}};M.push(t)}}if(cT({policyActions:b,action:zw})){const{validSwapAction:t}=eT({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(cT({policyActions:b,action:jw})&&!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===qw))?.availableParticipantIds,h=a?.[ha]?.otherFlightEntries,g=a?.[ha]?.restrictQualifyingAlternates,I=(o.entries??[]).filter((({entryStage:t})=>!g||(d.stage===Vo?t===Vo:t!==Vo))).sort(((t,e)=>(t.entryPosition??1/0)-(e.entryPosition??1/0))).map((({participantId:t})=>t)).filter(Boolean),{allPositionedParticipantIds:U}=Gs({drawDefinition:o}),S=r.map((t=>t.participantId)).filter(Boolean),y=I.filter((t=>d.stage&&[Vo,Bo,qo].includes(d.stage)?!U?.includes(t):!S.includes(t))),v=(l?.entries??[]).filter((t=>t.entryStatus===Xc&&Qw({restrictQualifyingAlternates:g,structure:d,entry:t})&&(d.stage&&[Vo,Bo,qo].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?wp({event:l}).flightProfile:void 0,e=t?.flights?.filter((t=>t.drawId!==p)).map((t=>t.drawEntries.filter((t=>t.participantId&&![du,su,cu].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:br({payload:{drawId:p,structureId:u,drawPosition:s},willDisableLinks:e,method:Ew,availableAlternatesParticipantIds:w,type:jw,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(cT({policyActions:b,action:Ww})&&!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}=Vs({structureId:e,drawDefinition:o}),r={};if(n?.finishingPosition===ks&&(1!==l?.length||1!==m?.length)){const{matchUps:t}=Xp({drawDefinition:o,structure:u,event:p}),{initialRoundNumber:e}=xl({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}=tl({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!==ld||t===ld))).map((({winningSide:t,sides:e})=>t&&e?.[1-(t-1)])).map(wi("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:Ww,method:Cw,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===Zs&&cT({policyActions:b,action:Bw})){const{validModifyAssignedPairAction:t}=function({tournamentParticipants:t,returnParticipants:e,drawPosition:n,participant:r,drawId:i,event:a}){const o=a?.entries?.filter((({entryStatus:t})=>[su,cu].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:br({payload:{participantId:r.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:n,drawId:i},method:kw,availableIndividualParticipantIds:o,availableIndividualParticipants:s,existingIndividualParticipantIds:a,existingIndividualParticipants:c,type:Bw},!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:Gg,tournamentMatchUps:bw,validateCollectionDefinition:Mh,validateLineUp:jf,validMatchUp:Rc,validMatchUps:Mc,allPlayoffPositionsFilled:function(t){const{drawDefinition:e,structureId:n}=t;if(!e)return{error:j};const{playoffStructures:r}=qh({drawDefinition:e,structureId:n});if(!r?.length)return!1;const i=e?.entries?.filter((t=>t?.entryStatus&&fu.includes(t.entryStatus)))?.length??0;let a=0;return(r||[]).reduce(((t,e)=>{const n=qs({structure:e}).positionAssignments??[],r=n?.filter((t=>(t.participantId&&a++,t?.bye??t?.participantId))).length;return!(!r||!t)}),!!r.length)||a===i},getCategoryAgeDetails:Dh,calculateWinCriteria:lh,compareTieFormats:Fh,getMatchUpContextIds:function({matchUps:t,matchUpId:e}){if(!Mc(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:da,getSeedingThresholds:function({roundRobinGroupsCount:t,participantsCount:e}){if(t){const{validGroupSizes:n}=Nf({drawSize:e}),r=n?.map((t=>Math.ceil(e/t)));if(!r?.includes(t))return Nr({context:{roundRobinGroupsCount:t},result:{error:Nn}})}const{seedGroups:n}=Mf({drawSize:e,roundRobinGroupsCount:t}),r=n?.map((t=>Math.min(...t)))||[];return{...E,seedingThresholds:r}},getTimeItem:oc,getValidGroupSizes:Nf,isAdHoc:jp,isCompletedStructure:Wh,roundRobinGroups:Df,tieFormatGenderValidityCheck:wh,validateCategory:bh};function BT({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===AU)),o=a?.scaleValue,{wtnRating:s,confidence:c}=o||{};return{timeStamp:a?.scaleDate,personOtherId:r,confidence:c,wtnRating:s,personId:n,tennisId:i}}function VT({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=>BT({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 jT={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=Fr({element:n,name:t})?.extension?.value;return{[e||t]:r?hi({element:i,accessor:r})?.value:i}}))),a=n?.tournamentId,o=El({participantsProfile:{withScaleValues:!0},tournamentRecord:n}).matchUps??[],s=t=>{const e=oc({itemType:Gd,itemSubTypes:[ca],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===qa)),m=l?.value?.flights?.map((t=>({[t.drawId]:t.flightNumber}))),f=m&&Object.assign({},...m),h=c?.find((t=>t.name===ja))?.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}=VT({eventType:u,matchUps:o,drawId:g}),T=s(c)||U,P=function({extensions:t}){return t?.find((({name:t})=>t===ka))?.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&&[Vo,Bo,jo,qo].includes(t.stage))).map((t=>{const r=[Bo,qo].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===Ys&&c.participantId,m=c?.participantType===Zs?c.individualParticipants:[],U=BT({participant:m?.[0]||c,eventType:u}),{personId:D,personOtherId:b,tennisId:N,confidence:R,wtnRating:M}=U||{},A=BT({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}=Oh(n),{tieFormatName:q,tieFormatDesc:$}=Oh(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}=mm({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:t,withDraws:!0}),r=(El({matchUpFilters:{matchUpTypes:[uc,pc]},tournamentRecord:t}).matchUps??[]).flatMap((({sides:t,matchUpType:e})=>t?.flatMap((t=>e===pc?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=BT({participant:m,eventType:s}),g=f?.[o]?.ranking;d===Gw&&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===Bo&&1===e||t===Vo)).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?.[Bo],c=n?.[r]?.draws?.[e]?.seedAssignments?.[Vo];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===pd?(()=>{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({},...fu.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===Ks&&e===Dm)),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??El({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=mm({participantFilters:c.length?{participantIds:c}:{participantTypes:[Ys]},tournamentRecord:i}).participants??[];if(!u.every((({participantType:t})=>t===Ys)))return{error:Pe};c.length||c.push(...u.map(wi("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 Nr({result:{error:Ee},context:{teamParticipantId:r}});if(e&&!m.get(e))return Nr({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(!Ui(e))return{error:Yt};const{matchUpStatus:n,matchUpFormat:r,matchUpType:i,winningSide:a,score:s,sides:c}=e;if(!c||!s||i===mc||n===go)continue;const u=g(c);if(!u.filter(Boolean).length)continue;const p=t&&a&&Nu({matchUp:e})?.competitiveness;h.push(e);const l=wg({matchUpStatus:n,matchUpFormat:r,tallyPolicy:o,winningSide:a,score:s}),m=Tg({matchUpStatus:n,matchUpFormat:r,tallyPolicy:o,winningSide:a,score:s}),{pointsTally:I,tiebreaksTally:U}=Pg({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 GT(t=0){const e=new Date;return e.setHours(e.getHours()+t),e.getTime().toString(36).slice(-6).toUpperCase()}function qT({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===Hy&&(e=ti(e),n=Qr(n),r=Qr(r),e&&n&&r)?{date:e,startTime:n,endTime:r,requestType:t.requestType}:t})).filter(Boolean);for(const n of r)n.requestId=GT(),t[e].push(n);return{mergeCount:r.length}}function $T(t){const{tournamentRecords:e,personRequests:n}=t,r=na(t,[{[Pi]:!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(Ra({tournamentParticipants:e,personId:t})){const e=n[t];e.length&&r.push({personId:t,requests:e})}if(Object.keys(r).length){Cr({element:t,extension:{value:r,name:Ka}})}}return{...E}}function WT({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??yy({recoveryMinutes:e,averageMatchUpMinutes:n});const{courts:p,venues:l}=Hm({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||pi(s,t.date))),r=n?.startTime??e.startTime;return r&&(!t||Zr(r)<Zr(t))?r:t}),void 0)),d||(d=m?.reduce(((t,e)=>{const n=e.dateAvailability?.find((t=>!t.date||pi(s,t.date))),r=n?.endTime??e.endTime;return r&&(!t||Zr(r)>Zr(t))?r:t}),void 0));const f=Object.values(a),h=Object.assign({},...f.map((t=>(t.events??[]).map((e=>{const{scheduleTiming:n}=sd({tournamentRecord:t,event:e});return{[e.eventId]:{event:e,scheduleTiming:n}}})))).flat()),g=Rw({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}=Rd({eventType:a,timingDetails:s}),{courtId:d,venueId:p}=e,l=Qr(e.scheduledTime),m=ci(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}=wy(w);return{venueId:1===u?.length&&u[0]||1===l?.length&&l[0].venueId||void 0,scheduleTimes:T,dateScheduledMatchUpIds:S.map(mo)}}function HT(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}=Tp({tournamentRecord:i,eventId:a});a&&s&&(c=!0);const u=zT({tournamentRecord:i,event:s,matchUpFormat:e,averageTimes:r,recoveryTimes:n});if(u.error)return u}return!a||c?{...E}:{error:Pt}}function zT({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=Qa;if(i){const{extension:t}=Fr({element:i,name:a});Cr({element:i,extension:{name:a,value:YT({...t?.value||{},matchUpFormat:n,averageTimes:r,recoveryTimes:e})}})}else{const{extension:i}=Fr({element:t,name:a});Cr({extension:{name:a,value:YT({...i?.value||{},matchUpFormat:n,averageTimes:r,recoveryTimes:e})},element:t})}return{...E}}function YT(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 KT({event:t}){return Oa({event:t,name:Qa})}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}=El({matchUpFilters:{matchUpIds:n},tournamentRecord:t}),u=c?.filter((t=>Qy({schedule:t.schedule}))).filter((t=>(({matchUpStatus:t})=>!ko.includes(t))({matchUpStatus:t.matchUpStatus})));if(!u?.length)return{...E};const{tournamentInfo:d}=rf({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=jy({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=ei(ti(m),s),f=new Date(g)<new Date(p)||new Date(g)>new Date(l)}if(o&&c){const t=ti(c),e=Zr(Qr(c))+o;if(f=e<0||e>1440,!f){const e=ci(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=yI({scheduledTime:h,drawDefinition:d,matchUpId:t});if(e.error)return e}if(g){const e=PI({scheduledDate:g,drawDefinition:d,matchUpId:t});if(e.error)return e}}(h||g)&&i.push(t)}}}const f=El({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 ZT={addMatchUpCourtOrder:DI,addMatchUpEndTime:NI,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(!Ra({tournamentParticipants:mm({tournamentRecord:e,participantFilters:{participantTypes:[Ks],participantRoles:[bm]}}).participants??[],participantId:i}))return{error:Ee}}const s={itemType:"SCHEDULE.ASSIGNMENT.OFFICIAL",itemValue:i};return a&&(s.itemSubTypes=[a]),Jf({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:o,timeItem:s})},addMatchUpResumeTime:MI,addMatchUpScheduledDate:PI,addMatchUpScheduledTime:yI,addMatchUpScheduleItems:TI,addMatchUpStartTime:bI,addMatchUpStopTime:RI,addPersonRequests:function(t){const{tournamentRecords:e,personId:n,requests:r}=t,i=na(t,[{[Pi]:!0,personId:!0},{requests:!0,[Xi]:Ki,[Zi]:Nn}]);if(i.error)return i;const{personRequests:a}=dv({tournamentRecords:e}),{mergeCount:o}=qT({personRequests:a,personId:n,requests:r});return o&&a?$T({tournamentRecords:e,personRequests:a}):{error:Nn}},addSchedulingProfileRound:Xv,allocateTeamMatchUpCourts:II,assignMatchUpCourt:SI,assignMatchUpVenue:UI,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=_d(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=uo(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:cv,bulkScheduleTournamentMatchUps:sv,bulkUpdateCourtAssignments:function(t){const{courtDayDate:e}=t,n=na(t,[{courtAssignments:!0,[Xi]:Ki,[Zi]:ae},{[Pi]:!0}]);if(n.error)return n;const r=t.courtAssignments.reduce(((t,e)=>{const{tournamentId:n}=e;return t[n]||(t[n]=[]),t[n].push(e),t}),{});let i;return Object.keys(r).every((n=>{const a=t[Pi][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}=Tp({tournamentRecord:a,drawId:t});return n?(o[t].every((t=>{const{matchUpId:r,courtId:o}=t,s=SI({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:WT,clearMatchUpSchedule:function({scheduleAttributes:t=[Cu,Ou,Eu,ku,_u,Lu,ju,Vu,Bu],tournamentRecord:e,drawDefinition:n,matchUpId:r}){const i=n?rl({matchUpFilters:{matchUpIds:[r]},inContext:!1,drawDefinition:n}).matchUps?.[0]:El({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,hl({tournamentId:e.tournamentId,context:"clearMatchUpSchedule",drawDefinition:n,matchUp:i}),{...E}},clearScheduledMatchUps:lv,courtGridRows:Pw,findCourt:function(t){return mi(gp(t),!1,!0)},findMatchUpFormatTiming:Ky,findVenue:hp,generateBookings:nv,generateVirtualCourts:Sy,getProfileRounds:kT,getSchedulingProfile:Km,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 Nr({result:{error:ae},stack:e});const{matchUps:f}=Cl({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 Nr({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 Nr({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 Nr({result:r,stack:e,info:"target"})}}return I?E:Nr({result:{error:Sn},stack:e});function U(t){const{tournamentRecords:e,tournamentId:n,matchUp:r,drawId:i}=t,a=e[n],{drawDefinition:o}=jy({tournamentRecord:a,drawId:i});return r.matchUpType===fc?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 II({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,courtDayDate:a,matchUpId:o,courtIds:u})}({...t,tournamentRecord:a,drawDefinition:o}):SI({...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(!Sh({matchUpFormat:a}))return{error:Nn};if(!c)return{error:Tt};const{averageTimes:u=[],recoveryTimes:d=[]}=vw({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||dc]:i}),U.push(m)),I&&(Object.assign(f.minutes,{[c?.eventType||dc]:r}),S.push(f)),g||I?HT({averageTimes:g&&U,recoveryTimes:I&&S,tournamentRecord:e,matchUpFormat:a,eventId:s,event:c}):{error:Nn}},modifyMatchUpFormatTiming:HT,modifyPersonRequests:function(t){const{tournamentRecords:e,requests:n,personId:r}=t,i=na(t,[{[Pi]:!0},{requests:!0,[Xi]:Ki,[Zi]:Nn}]);if(i.error)return i;const a=n.map((({requestId:t})=>t)).filter(Boolean),{personRequests:o}=dv({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&&qT({personRequests:o,personId:r,requests:c}),$T({tournamentRecords:e,personRequests:o})},proAutoSchedule:function({scheduleCompletedMatchUps:t,tournamentRecords:e,scheduledDate:n,matchUps:r}){if(!Mc(r))return{error:Nn};if(r.some((({hasContext:t})=>!t)))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:hn};let i=Rw({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(Ui(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=>Ui(t)&&!t.matchUpId));return t.concat({matchUpIds:n,availableCourts:i,rowId:e.rowId,participantIds:r})}),[]);r.filter((({matchUpStatus:e})=>e&&e!==go&&(t||!ko.includes(e)))).sort(Ol);const u=Fl({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=cv({tournamentRecords:e,matchUpDetails:l});const m=r;return{...i,scheduled:d,notScheduled:m}},proConflicts:function({tournamentRecords:t,matchUps:e}){if(!Mc(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(Ol).forEach((({schedule:t})=>delete t[Dd]));const s=Fl({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[Dd]){o[t].schedule[Dd]=e,o[t].schedule[yd]=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][vd]||(i[t][vd]=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][wd]||(i[t][wd]=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,Td,Sd,[e]))),d(e,Td,Sd,n))}if(i[e]?.[vd]&&d(e,vd,Ud,i[e][vd]),t.sourceMatchUpIds.includes(e)){const n=t.matchUpIds.filter((t=>s[t].matchUpIds.includes(e)));d(e,vd,Sd,n),t.matchUpIds.filter((t=>s[t].matchUpIds.includes(e))).forEach((t=>d(t,vd,Sd,[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,Pd,Sd,c),c.forEach((t=>d(t,Pd,Sd,[e])))),i[e]?.[wd]&&d(e,wd,Ud,i[e][wd]),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,wd,Sd,[e]))),d(e,wd,Sd,r))}}))})),{courtIssues:a,rowIssues:u}},removeEventMatchUpFormatTiming:function(t){if(t.event)return KT({event:t.event});{t.tournamentRecord&&!t.tournamentRecords&&(t.tournamentRecords={[t.tournamentRecord.tournamentId]:t.tournamentRecord});const e=na(t,[{[Pi]:!0,[Gi]:!0}]);if(e.error)return e;const{tournamentRecords:n,eventId:r}=t;for(const t of Object.values(n??{})){const{event:e}=Tp({tournamentRecord:t,eventId:r});if(e)return KT({event:e})}}return{error:Pt}},removeMatchUpCourtAssignment:function(t){const e=na(t,[{[Pi]:!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}=jy({tournamentRecord:u,drawId:c});if(!d)return{error:j};const l=hf({drawDefinition:d,event:p,matchUpId:o});if(l.error)return l;if(l?.matchUp?.matchUpType===mc){const{itemValue:t}=Ad({timeItems:l.matchUp.timeItems??[],itemType:Cu}),e=s&&t.filter((t=>t.courtId!==s));return Jf({duplicateValues:!1,removePriorValues:n,tournamentRecord:u,drawDefinition:d,matchUpId:o,timeItem:{itemType:Cu,itemValue:e}})}return SI({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=na(t,[{[Pi]:!0}]);if(o.error)return o;const{personRequests:s}=dv({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?$T({tournamentRecords:e,personRequests:s}):Ar({name:Ka,tournamentRecords:e,discover:!0})},reorderUpcomingMatchUps:function(t){const e="reorderUpcomingMatchUps",{tournamentRecords:n}=t;if("object"!=typeof n||!Object.keys(n).length)return Nr({result:{error:x},stack:e});const{matchUpsContextIds:r,firstToLast:i}=t;if(!r)return Nr({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}=jy({tournamentRecord:a,drawId:i});return o?yI({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:Nr({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=na(t,[{[Pi]:!0,[Oi]:!0},{[Ji]:Gr,[Zi]:pe,scheduleDate:!0},{[Ji]:t=>!t||!isNaN(t),averageMatchUpMinutes:!1,[Zi]:Nn,recoveryMinutes:!1,periodLength:!1}]);if(y.error)return y;const v=t.competitionMatchUps??Cl({nextMatchUps:!0,tournamentRecords:e}).matchUps??[],w=t.matchUpDependencies??Fl({includeParticipantDependencies:!0,matchUps:v,tournamentRecords:e}).matchUpDependencies;v.forEach((t=>{t.schedule?.scheduledDate&&pi(f,ti(t.schedule.scheduledDate))&&Gy({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}=WT({tournamentRecords:e,remainingScheduleTimes:p,startTime:Qr(I),endTime:Qr(U),scheduleDate:ti(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=>{Xy({matchUpPotentialParticipantIds:o,individualParticipantProfiles:s,matchUp:t,value:1});const e=t.schedule?.scheduledTime;if(e){M[t.matchUpId]=e;const n=a?.[t.matchUpId];$y({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=[go,yo,Uo,fo,bo,Mo].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}=ov({individualParticipantProfiles:s,matchUpPotentialParticipantIds:o,matchUpDailyLimits:u,matchUp:e});return a?.length?(t.overLimitMatchUpIds.push(e.matchUpId),t.participantIdsAtLimit.push(...a),t):(d.forEach((t=>{qy({individualParticipantProfiles:s,participantId:t});const e=s[t].counters;e[i]?e[i]+=1:e[i]=1,e[Id]?e[Id]+=1:e[Id]=1})),t.matchUpMap[r]||(t.matchUpMap[r]={}),t.matchUpMap[r][n]?t.matchUpMap[r][n].push(e):t.matchUpMap[r][n]=[e],Gy({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}=dv({tournamentRecords:e,requestType:Hy});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}=Vy({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}=av({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}=Yy({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 $y({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=>{Xy({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}=jy({tournamentRecord:n,drawId:r});if(i){k[t][r].forEach((({matchUpId:t})=>{const r=M[t];if(r){const a=r.split(":").map(di).join(":"),o=`${ti(f)}T${a}`;if(S)j.push(t);else{yI({drawDefinition:i,matchUpId:t,scheduledTime:o}).success&&j.push(t),P&&UI({tournamentRecords:e,tournamentRecord:n,drawDefinition:i,matchUpId:t,venueId:P})}}}))}}))}));const G=uo(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:fv,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=Cr({element:i[t],extension:{name:Xa,value:{dailyLimits:r}}});if(e.error)return e}return{...E}},setSchedulingProfile:Jm,toggleParticipantCheckInState:Qf,validateSchedulingProfile:qm},XT="\\d+-\\d+",QT="\\d+-\\d+\\(\\d+\\)",tP="\\[\\d+-\\d+\\]",eP=new RegExp(`(${XT}),`,"g"),nP=new RegExp(`(${QT}),`,"g"),rP=[XT,QT,tP,"\\d+-\\d+\\(\\d+-\\d+\\)"],iP=["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=>rP[t])).join(" ");return new RegExp(`^${e}$`)}));function aP(t){return!t||iP.some((e=>e.test(t)))}function oP(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function sP(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 cP(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 uP(t){return 2===t.length?t.split("").join("-"):([", ",",","/"," "].forEach((e=>t=t.split(e).join("-"))),t=t.replace(/-{2,}/,"-"))}function dP(t){return t.startsWith("(")&&t.endsWith(")")}function pP(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 lP({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 mP(t){const e=t.indexOf("1"),n=t.split(""),r=n.every((t=>!isNaN(t)));if(r&&3===t.length&&0===e){const t=cP(n,e);if(t)return t}if(r&&7===t.length&&e>3){const t=cP(n.slice(4),e-4);if(t)return`${n[0]}-${n[1]} ${n[2]}-${n[3]} ${t}`}}function fP(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(lP({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=mP(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 hP(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 gP={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(dP)?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(oP);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":sP(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;!sP(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(tP).test(t)?"super":new RegExp(QT).test(t)&&"tiebreak")||new RegExp(XT).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(")")),[eP,nP].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(pP).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=cP(t.split(""),n);return e.push("getSuper"),r}}else{const{score:n,applied:r}=fP({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=pP(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)&&mP(t)){return{score:mP(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(sP(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=cP(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 sP(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:fP,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=pP(uP(r));t=t.replace(e,`(${a})`).trim()}const a=new RegExp(/\[[\d,/ ]+\]/g),o=t.match(a);o?.forEach((e=>{const n=uP(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(",")||oP(t))),i=n.every((t=>t.includes("/")||oP(t))),a=n.every((t=>t.includes("-")||oP(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["-"]&&sP(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(QT).test(t)){const n=t.slice(3),r=t.slice(0,3),i=r.split("-");if(!sP(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=pP(t);const a=(new RegExp(`^${tP}$`).test(t)?"super":new RegExp(`^${QT}$`).test(t)&&"tiebreak")||new RegExp(`^${XT}$`).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}=hP(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}=hP(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:lP,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 IP={};const UP=["handleNumeric","handleWalkover","handleRetired","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],SP=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];function yP({analysis:t,set:e}){const n=wP({set:e}),{isDecidingSet:r,isTiebreakSet:i,matchUpScoringFormat:a}=t;return vP({matchUpScoringFormat:a,isDecidingSet:r,isTiebreakSet:i,set:e})&&n}function vP(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=wP({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 wP({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 TP=" ",PP="DEF",DP="WO",bP="ABN",NP="SUS",RP="RET",MP="INT",AP=[RP,PP,DP,"WO/WO",bP,NP,MP],EP="DEFAULTED",CP="WALKOVER",OP="ABANDONED",FP="SUSPENDED",kP="RETIRED",xP="INTERRUPTED",_P=[kP,EP,CP],LP="()",BP="[]",VP=["up","left","shift+tab"],jP=["enter","down","tab","right"],GP="backspace",qP="r",$P="s",WP="a",HP="d",zP="w",YP="i",KP=[qP,HP,zP,WP,$P,YP],JP="space",ZP=["[","("],XP=[...VP,...jP,JP,"]"],QP="-",tD="-",eD=["/"],nD=["0","1","2","3","4","5","6","7","8","9"].concat(KP),rD=nD.map((t=>`shift+${t}`)),iD=[QP,GP].concat(XP,eD),aD=[nD,rD,iD].join(","),oD=[aD,VP,jP,["=","+","num_1","num_2","shift+=","shift+-"]].join(",");[].concat(...nD,...nD,...iD,...nD,...nD,...nD,...nD,...nD,...nD);const sD={OUTCOMEKEYS:KP,SIDE1KEYS:nD,SIDE2KEYS:rD,MODIFIERS:iD,PROMPT:"Enter Score",MOVEUP:VP,MOVEDOWN:jP,HOTKEYS:oD};function cD({scoreString:t,lowSide:e,outcome:n}){if(({scoreString:t}=uD({scoreString:t})),2===e){return t+((t&&t[t.length-1])!==TP?TP:"")+n}return n+TP+t}function uD({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(const n of AP){const r=t?.indexOf(n);0===r?t=t.slice(n.length+1).trim()+TP:r>0&&(t=t.slice(0,r)),r>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function dD({analysis:t,scoreString:e,sets:n,lowSide:r}){let i,a;if(!e)return{scoreString:e,sets:n};const{scoreString:o,removed:s}=uD({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}=pD({brackets:BP,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}=pD({brackets:LP,scoreString:i}),{lastOpenBracketIndex:s,isTiebreakEntry:u}=pD({brackets:BP,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(tD),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(tD)}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 pD({brackets:t=LP,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 lD(t){const{lowValue:e=0,NoAD:n=!1,tiebreakTo:r}=t||{};return e+1>=r?e+(n?1:2):parseInt(r)}function mD({matchUpFormat:t,matchUpStatus:e,winningSide:n,sets:r}){const i=Op(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 _P.includes(e)&&n&&(c=n),{matchUpWinningSide:c}}function fD({lowSide:t,value:e,sets:n,scoreString:r,winningSide:i,matchUpStatus:a}){let o;return e===qP?r?(o=!0,r=cD({scoreString:r,lowSide:t,outcome:RP}),i=2===t?1:2,a=kP):(o=!0,r=cD({scoreString:r,lowSide:t,outcome:PP}),i=2===t?1:2,a=EP):e===HP?(o=!0,r=cD({scoreString:r,lowSide:t,outcome:PP}),i=2===t?1:2,a=EP):e===zP?(o=!0,n=[],r=DP,i=2===t?1:2,a=CP):e===$P&&r?(o=!0,r=cD({scoreString:r,lowSide:t,outcome:NP}),a=FP,i=void 0):e===WP?(o=!0,r=cD({scoreString:r,lowSide:t,outcome:bP}),a=OP,i=void 0):e===YP&&r&&(o=!0,r=cD({scoreString:r,lowSide:t,outcome:MP}),a=xP,i=void 0),{updated:o,sets:n,scoreString:r,matchUpStatus:a,winningSide:i}}function hD({matchUpFormat:t,scoreString:e,winningSide:n,value:r,sets:i}){const a=(i?.filter((t=>t?.winningSide))?.length||0)+(n?0:1),o=Op(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}=pD({brackets:LP,scoreString:e}),{isTiebreakEntry:m}=pD({brackets:BP,scoreString:e}),f=l||m,h=!!c.tiebreakSet,g=e?.[e.length-1]?.trim(),I=e&&!isNaN(g),U=!f&&g===QP,S=l&&ZP.includes(g),y=m&&ZP.includes(g),v=m&&g===tD,w=e?.split(""),[P]=BP.split(""),D=w&&Math.max(...T(P,w)),b=w&&Math.max(...T(tD,w)),N=w&&b>D,R=i[i.length-1]?.winningSide,M=i?.length&&!R,A=AP.find((t=>e?.indexOf(t)>=0)),E=!isNaN(r),C=r===JP,O=XP.includes(r),F=e?.split("").find((t=>ZP.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]=BP.split(""),a=t.split(""),o=Math.max(...T(r,a)),s=Math.max(...T(i,a)),c=Math.max(...T(tD,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 gD({matchUp:t}){const{extension:e}=Fr({name:za,element:t});if(!e)return{error:On};const{history:n=[],undoHistory:r=[]}=e.value;return{history:n,undoHistory:r,...E}}function ID({undoHistory:t,history:e,matchUp:n}){return Cr({element:n,extension:{value:{history:e,undoHistory:t},name:za}})}const UD={analyzeSet:Lv,checkScoreHasValue:Tl,checkSetIsComplete:vP,generateScoreString:uU,generateTieMatchUpScore:$g,getSetComplement:ky,getTiebreakComplement:xy,isValidMatchUpFormat:Sh,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(!aD.includes(r))return{updated:!1,info:"invalid key"};u&&(e=3-e);const{matchUpWinningSide:f}=mD({sets:a,winningSide:o,matchUpStatus:s,matchUpFormat:c});o=f;const h=hD({value:r,winningSide:o,scoreString:i,sets:a,matchUpFormat:c});if(eD.includes(r)&&(r=QP),h.hasOpener&&h.isTiebreakEntry&&!h.isTiebreakSet&&m&&0===n(r)&&(h.isTiebreakCloser=!0),XP.includes(r)&&h.hasOpener&&(r=""),XP.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===GP||(e=[{setNumber:1}]);const l=e.length-1;if(KP.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}=fD({lowSide:c,value:u,sets:e,scoreString:i,matchUpStatus:o,winningSide:a}))}else if(u===GP){if(({scoreString:i,sets:e,outcomeRemoved:p}=dD({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===QP&&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(KP.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}=fD({lowSide:e,sets:a,scoreString:i,matchUpStatus:s,winningSide:o,value:r}));else if(r===GP)p=!0,({scoreString:i,sets:a}=dD({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!==QP||h.isMatchTiebreakEntry)if(r===tD&&h.isMatchTiebreakEntry&&!h.isSetTiebreakEntry)h.matchTiebreakHasJoiner?l="existing joiner":h.isNumericEnding&&(p=!0,i+=tD);else if([QP,tD].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=yP({analysis:t,set:r[r.length-1]});o.winningSide=n||void 0,c?e+=LP.split("")[0]:t.isDecidingSet||(e+=TP)}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?LP:BP,e=t.split("").reverse()[0],n=t.split("")[0],r=a[a.length-1],{tiebreakFormat:o}=h.setFormat,{tiebreakTo:s,NoAD:c}=o||{},u=wP({set:r});if(!h.isTiebreakSet){const t=parseInt(i.split(n).reverse()[0]),e=lD({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+=TP);const d=yP({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]=BP.split("");if(t.isMatchTiebreakEntry||(i+=p),a[t.setNumber-1]){const{lastOpenBracketIndex:t}=pD({brackets:BP,scoreString:i}),p=(i.slice((t??0)+1)+(e?"":o)).split(tD);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(tD),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=lD({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(tD),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]=LP.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=LP.split("")[0];n=(n||"")+(u.join(QP)+(s?d:TP));const p={side1Score:u[0],side2Score:u[1]},l=yP({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}=dD({analysis:h,scoreString:i,sets:a,lowSide:e})),s=void 0);if(p){a=a?.filter(Boolean);const{matchUpWinningSide:t}=mD({sets:a,winningSide:o,matchUpStatus:s,matchUpFormat:c});return o=t,!t||s&&![Ro,Po].includes(s)?!i||o||[FP,OP,xP].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:Op,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 br({winningSide:r?3-r:void 0,side1TiebreakScore:n,side2TiebreakScore:e,side1Score:a,side2Score:i,setNumber:o})}));return{reversedScore:{sets:n,scoreStringSide1:uU({sets:n}),scoreStringSide2:uU({sets:n,reversed:!0})},...E}},stringifyMatchUpFormat:fh,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=gP[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=aP(m);return h||(m=e.toString().replace(/\D/g,""),d?.removed&&(d.removed=void 0),f(SP),h=aP(m),h||(m="")),l.forEach((t=>{IP[t]||(IP[t]=0),IP[t]+=1})),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:d,isValid:h,score:m}},updateTieMatchUpScore:Zg,validateScore:AI,validateTieFormat:Ah,calculateHistoryScore:function(t){if(!t)return{error:ae};const{matchUp:e,updateScore:n}=t;if(!e)return{error:zt};const r=gD({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(!Sh({matchUpFormat:i}))return{error:Bt};const a=Op(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=uU({...d,matchUpFormat:i}),d.scoreStringSide2=uU({...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=[]}=gD({matchUp:t});return n.push({srv:e}),ID({matchUp:t,history:n})},clearHistory:function({matchUp:t}){return ID({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=[]}=gD({matchUp:t});return n.push(e),ID({matchUp:t,history:n})},addGame:function({matchUp:t,game:e}){if("object"!=typeof e)return{error:Nn,context:{game:e}};const{history:n=[]}=gD({matchUp:t});return n.push(e),ID({matchUp:t,history:n})},addShot:function({matchUp:t,shot:e}){if("object"!=typeof e)return{error:ae};const{history:n=[]}=gD({matchUp:t});return n.push(e),ID({matchUp:t,history:n})},addSet:function({matchUp:t,set:e}){if("object"!=typeof e)return{error:ae};const{history:n=[]}=gD({matchUp:t});return n.push(e),ID({matchUp:t,history:n})},redo:function({matchUp:t}){const{history:e=[],undoHistory:n=[]}=gD({matchUp:t});return n.length&&e.push(n.pop()),ID({matchUp:t,history:e,undoHistory:n})},undo:function({matchUp:t}){const{history:e=[],undoHistory:n=[]}=gD({matchUp:t});return n.push(e.pop()),ID({matchUp:t,history:e,undoHistory:n})},umo:{scoreboard:()=>{},addPoints:()=>{},addPoint:()=>{}}},SD={ABANDONED:"ABANDONED",ACTIVE:"ACTIVE",CANCELLED:"CANCELLED",COMPLETED:"COMPLETED",IN_PROGRESS:"IN_PROGRESS"};function yD({tournamentRecord:t,startDate:e,endDate:n}){if(!t)return{error:_};if(e&&!_r.test(e)||n&&!_r.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=El({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(!lv({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=zr(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=Zr(t.startTime),r=Zr(t.endTime);return e.startTime&&Zr(e.startTime)<n&&(t.startTime=e.startTime),e.endTime&&Zr(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}),cr({topic:np,payload:{startDate:e,endDate:n}}),{...E,unscheduledMatchUpIds:i}}const vD={addDrawDefinitionExtension:Aa,addEventExtension:Ea,addEventTimeItem:ef,addExtension:Cr,addNotes:Kg,addOnlineResource:function({tournamentRecord:t,onlineResource:e,organisationId:n,participantId:r,personId:i,courtId:a,venueId:o}){if(!t)return{error:_};if(!Ui(e))return{error:ae};if(3!==P(Object.keys(e),["resourceSubType","resourceType","identifier"]).length)return Nr({result:{error:Pn},context:{onlineResource:e}});if(n){if(t.parentOrganisation?.parentOrganisationId!==n)return Nr({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 Nr(i?{result:{error:On}}:{result:{error:Ee}});if(i){if(n.person?.personId!==i)return Nr({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 Nr({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 Nr({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=Ra({participantId:t.participantId,tournamentParticipants:e});return n?Cr({creationTime:t.creationTime,extension:t.extension,element:n}):{error:Ee}},addParticipantTimeItem:Qm,addTimeItem:Xm,addTournamentExtension:Ma,addTournamentTimeItem:tf,getProfileRounds:kT,removeDrawDefinitionExtension:function(t){return t&&"object"==typeof t?t.drawDefinition?Ar({element:t.drawDefinition,name:t.name}):{error:q}:{error:ae}},removeEventExtension:Oa,removeExtension:Ar,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=Ra({participantId:t.participantId,tournamentParticipants:e});return n?Ar({element:n,name:t.name}):{error:Ee}},removeTournamentExtension:Ca,setTournamentCategories:function({tournamentRecord:t,categories:e}){return t?(e=(e||[]).filter((t=>t.categoryName&&t.type)),t.tournamentCategories=e,{...E}):{error:_}},setTournamentDates:yD,setTournamentEndDate:function({tournamentRecord:t,endDate:e}){return yD({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?Kg({element:t,notes:e}):{error:_}},setTournamentStartDate:function({tournamentRecord:t,startDate:e}){return yD({tournamentRecord:t,startDate:e})},setTournamentStatus:function({tournamentRecord:t,status:e}){return t?e&&!Object.keys(SD).includes(e)?{error:Nn,info:"Unknown status"}:(t.tournamentStatus=e,{...E}):{error:_}}};const wD=["collectionId","collectionPosition","drawPositions","extensions","finishingPositionRange","finishingRound","isMock","matchUpId","matchUpStatus","matchUpStatusCodes","orderOfFinish","processCodes","roundNumber","tieFormat","tieMatchUps","roundPosition","score","sides","winnerMatchUpId","loserMatchUpId","matchUpDuration","winningSide"];function TD(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,TD(t[i],e,n.concat(i)))),{})}const PD={visualizeScheduledMatchUps:function({scheduledMatchUps:t,showGlobalLog:e}){Ll.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=>{Bl({color:"blue",method:"draw",structure:r[e],keyColors:{structure:"magenta"}},!0);const n=t.filter((t=>t.structureId===e)),i=Ac({matchUps:n})?.roundMatchUps||[];Object.keys(i).forEach((t=>{Bl({roundNumber:t,keyColors:{roundNumber:"brightcyan"}},!0),i[t].forEach((({matchUpId:t,schedule:e})=>{Bl({matchUpId:t,time:Qr(e.scheduledTime),date:e.scheduledDate,venue:e.venueId,keyColors:{time:"brightcyan",date:"brightcyan",matchUpId:"yellow",venue:"magenta"}},!0)}))}))})),e&&Vl()},dehydrateMatchUps:function({tournamentRecord:t}){if(!t)return{error:_};if("object"!=typeof t||!t.tournamentId)return{error:Nn};const{matchUps:e}=El({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))wD.includes(t)||delete n[t];n.sides&&n.drawPositions&&!n.tieMatchUps&&delete n.sides,o&&(n.matchUpFormat=o)}}(e,n)}return{...E}},structureSort:Ls,allNumeric:R,attributeFilter:pa,chunkArray:N,chunkByNth:A,chunkSizeProfile:function t(e,[n,...r]){return e.length?[e.slice(0,n),...t(e.slice(n),[...r,n])]:[]},constantToString:Lm,countValues:function(t){return I(g(t))},createMap:yi,dateTime:li,definedAttributes:br,extractAttributes:vi,flattenJSON:TD,generateDateRange:zr,generateHashCode:function(t){if(null===t||"object"!=typeof t)return;const e=JSON.stringify(t),n=Ti(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:GT,groupValues:I,hasAttributeValues:t=>e=>Object.keys(t).every((n=>e[n]===t[n])),instanceCount:g,intersection:P,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=>TD(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:mi,matchUpSort:Ol,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,shuffleArray:f,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))},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:Ld,UUIDS:function(t=1){return w(0,t).map(Ld)}},DD=PD;function bD(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}=Km({tournamentRecord:n});if(Array.isArray(i))return{matchUps:c({matchUps:i,courtId:a})};const{matchUps:s}=El({scheduleVisibilityFilters:e,tournamentRecord:n,matchUpFilters:r});return{matchUps:c({matchUps:s,courtId:a})};function c({matchUps:t,courtId:e}){return Tw({matchUps:t.filter((t=>{const n=t.schedule?.allocatedCourts?.map((({courtId:t})=>t));return t.schedule?.courtId===e||n?.includes(e)})),schedulingProfile:o})}}function ND({tournamentRecord:t,dateAvailability:e,disableNotice:n,venueMatchUps:r,courtId:i,force:a}){if(!t)return{error:_};if(!i)return{error:ie};const o=bv({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(Dv);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(si(oi(n),oi(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=gp({tournamentRecord:t,courtId:i});if(u.error)return u;const{court:d,venue:p}=u,{matchUps:l}=bD({tournamentRecord:t,venueMatchUps:r,courtId:i});if(l?.length){const e=Fc({tournamentRecord:t})?.appliedPolicies,n=a??e?.[va]?.allowDeletionWithScoresPresent?.courts,r=[];r.length&&(n||console.log("throw error: scheduled court matchUps",r.length))}return d&&(d.dateAvailability=e,!n&&p&&cr({payload:{venue:p,tournamentId:t.tournamentId},topic:rp,key:p.venueId})),{...E,totalMergeCount:c}}function RD({matchUpsCount:t=0}){return{error:Gn,info:`Schedule would be deleted from ${t} ${1===t?"matchUp":"matchUps"}; use { force: true }`}}function MD({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}=Tp({tournamentRecord:t,drawId:r}))}if(e)({matchUp:i}=hf({drawDefinition:e,matchUpId:n}));else{if(!t)return{error:_};const e=El({tournamentRecord:t,inContext:!1}).matchUps??[];({matchUp:i}=ff({matchUps:e,matchUpId:n}))}if(!i)return{error:Wt};if(i.timeItems){i.timeItems.find((t=>[Ou,Cu].includes(t.itemType)))&&(i.timeItems=i.timeItems.filter((({itemType:t})=>![Ou,Cu].includes(t))),hl({tournamentId:t?.tournamentId,context:"removeCourtAssignment",drawDefinition:e,matchUp:i}))}return{...E}}function AD(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=Cl({tournamentRecords:i,contextFilters:{venueIds:[n]}}).matchUps??[],o=Fc({tournamentRecord:e})?.appliedPolicies,s=r??o?.[va]?.allowDeletionWithScoresPresent?.venues;if(a.length&&!s)return RD({matchUpsCount:a.length});for(const t of Object.values(i)){for(const e of a){const n=MD({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&&cr({payload:{venueId:n,tournamentId:t.tournamentId},topic:Hd,key:n})}return Zm({tournamentRecords:i}),{...E}}function ED({tournamentRecord:t,courtIds:e,dates:n}){const r=!Array.isArray(n)||!n.length||{dates:n},i=t=>Cr({extension:{value:r,name:La},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 CD({tournamentRecord:t,venueIds:e}){for(const n of t.venues||[])if(e?.includes(n.venueId)){const t=Cr({creationTime:!1,element:n,extension:{name:La,value:!0}});if(t.error)return t}return{...E}}function OD({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}=Fr({element:t,name:La});if(e){const n=e.value;Array.isArray(n.dates)&&(n.dates=n.dates.filter((t=>!r.includes(t)))),Cr({extension:{name:La,value:n},creationTime:!1,element:t})}}else Ar({element:t,name:La});return{...E}}function FD({tournamentRecord:t,disableNotice:e,courtId:n,force:r}){const i=gp({tournamentRecord:t,courtId:n});if(i.error)return i;const a=i.venue,{matchUps:o}=bD({tournamentRecord:t,courtId:n}),s=Fc({tournamentRecord:t})?.appliedPolicies,c=r??s?.[va]?.allowDeletionWithScoresPresent?.courts;if(o?.length&&!c)return RD({matchUpsCount:o.length});for(const e of o??[]){const n=MD({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||cr({payload:{venue:a,tournamentId:t.tournamentId},topic:rp,key:a.venueId})),{...E}}function kD(t){const{disableNotice:e,modifications:n,courtId:r,force:i,venueMatchUps:a}=t,o=_d(t);if(!Object.keys(o).length)return{error:x};let s;for(const t of Object.values(o)){const o=xD({tournamentRecord:t,disableNotice:e,venueMatchUps:a,modifications:n,courtId:r,force:i});if(o?.error)return o;s=!0}return s?{...E}:undefined}function xD({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=gp({tournamentRecord:t,courtId:i});if(o.error)return o;const{venue:s,court:c}=o,u=Object.keys(wv()).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=ND({dateAvailability:r.dateAvailability,tournamentRecord:t,venueMatchUps:n,disableNotice:e,courtId:i,force:a});if(o.error)return o}return e||cr({payload:{venue:s,tournamentId:t.tournamentId},topic:rp,key:s?.venueId}),{...E,court:mi(c)}}const _D=()=>({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,addresses:[],contacts:[],courts:[],roles:[]});function LD({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=Fc({tournamentRecord:t})?.appliedPolicies,a=r??i?.[va]?.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}=Km({tournamentRecord:e}),{matchUps:a}=El({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:n});return{matchUps:function({matchUps:t,venueId:e}){return Tw({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=hp({tournamentRecord:t,venueId:n});if(s.error)return s;const c=s.venue,u=Object.keys(_D()).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=m.length&&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=bD({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(console.log({scheduleDeletionsCount:n}),!c||n&&!a)return RD({matchUpsCount:n});c.courts=c.courts?.filter((t=>m.includes(t.courtId))),sv({schedule:{courtId:"",scheduledDate:""},matchUpDetails:h,removePriorValues:!0,tournamentRecord:t})}if(e.courts)for(const i of e.courts){const{courtId:e}=i||{};let a=kD({modifications:i,disableNotice:!0,tournamentRecord:t,venueMatchUps:o,courtId:e,force:r});if(a.error===tn&&(a=Nv({disableNotice:!0,tournamentRecord:t,venueId:n,court:i})),a.error)return a}return Zm({tournamentRecord:t}),c&&cr({payload:{venue:c,tournamentId:t.tournamentId},topic:rp,key:c?.venueId}),{...E,venue:mi(c)}}const BD={addCourt:Nv,addCourts:Rv,addVenue:mp,deleteCourt:function(t){const{courtId:e,disableNotice:n,force:r}=t,i=_d(t),a=na(t,[{[Pi]:!0,[ji]:!0}]);if(a.error)return a;let o,s;for(const t of Object.values(i)){if(s=FD({tournamentRecord:t,disableNotice:n,courtId:e,force:r}),s.error&&s.error!==tn)return s;s.success&&(o=!0)}return o?{...E}:s},deleteVenue:AD,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=AD({tournamentRecord:t,venueId:e,force:n});if(i.error)return i}}return{...E}},disableCourts:function(t){const{courtIds:e,dates:n}=t,r=_d(t),i=na(t,[{[Pi]:!0,[Li]:!0}]);if(i.error)return i;for(const t of Object.values(r))ED({tournamentRecord:t,courtIds:e,dates:n});return{...E}},disableVenues:function(t){const{tournamentRecords:e,tournamentId:n,venueIds:r}=t,i=na(t,[{[Pi]:!0,[Bi]:!0}]);if(i.error)return i;const a=Object.keys(e).filter((t=>!n||t===n));for(const t of a){CD({tournamentRecord:e[t],venueIds:r})}return{...E}},enableCourts:function(t){const e=_d(t),n=[{[Pi]:!0}];!t.enableAll&&n.push({[Li]:!0});const r=na(t,n);if(r.error)return r;const{enableAll:i,courtIds:a,dates:o}=t;for(const t of Object.values(e))OD({tournamentRecord:t,courtIds:a,enableAll:i,dates:o});return{...E}},enableVenues:function(t){const e=_d(t),n=[{[Pi]:!0}];!t.enableAll&&n.push({[Bi]:!0});const r=na(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))&&Ar({element:e,name:La});return{...E}},findVenue:function({convertExtensions:t,...e}){const{tournamentRecords:n,tournamentRecord:r,venueId:i}=e;return mi(hp({tournamentRecords:n,tournamentRecord:r,venueId:i}),t,!0)},modifyCourt:kD,modifyCourtAvailability:ND,modifyVenue:function(t){const{modifications:e,venueId:n,force:r}=t,i=_d(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=LD({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 Zm({tournamentRecords:i}),o?{...E}:{error:a}}},VD={competitionGovernor:so,eventGovernor:zS,generationGovernor:Ty,matchUpFormatGovernor:Rh,mocksGovernor:nw,participantGovernor:dw,policyGovernor:lw,publishingGovernor:hw,queryGovernor:LT,reportGovernor:jT,scheduleGovernor:ZT,scoreGovernor:UD,tournamentGovernor:vD,utilitiesGovernor:PD,venueGovernor:BD},jD={};function GD(t){const{mutationStatus:e,tournamentId:n,directives:r,timeStamp:i}=t||{},{topics:a}=mr();for(const t of[...a].sort(WD)){const e=dr({topic:t});e&&fr({topic:t,notices:e})}e&&i&&a.includes(ip)&&fr({notices:[{tournamentId:n,directives:r,timeStamp:i}],topic:ip})}async function qD(t){const{mutationStatus:e,tournamentId:n,directives:r,timeStamp:i}=t||{},{topics:a}=mr();for(const t of[...a].sort(WD)){const e=dr({topic:t});e&&await fr({topic:t,notices:e})}e&&i&&a.includes(ip)&&fr({notices:[{tournamentId:n,directives:r,timeStamp:i}],topic:ip})}const $D={[up]:5,[cp]:5,[dp]:5,[ep]:5,[tp]:5,[Kd]:5,[Jd]:5,[Zd]:5,[Xd]:1,[pp]:1,[Qd]:5,[rp]:5,[Yd]:4,[Wd]:4,[Hd]:4,[zd]:4,[Vd]:3,[Bd]:2};function WD(t,e){return($D[e]||0)-($D[t]||0)}const{FACTORY:HD}=io;function zD({timeStamp:t}){const e=Ir(),n=sr();return n&&Object.values(e).forEach((e=>{!function({tournamentRecord:t,value:e}){const{extension:n}=Fr({element:t,name:HD});Cr({element:t,extension:{name:HD,value:{...n?.value,...e}}})}({tournamentRecord:e,value:{version:"2.0.0-beta.6",timeStamp:t}})})),n}function YD({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&&Pr(t,o)}function KD({methodName:t,params:e,start:n}){const r={error:jn,methodName:t};return YD({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=hr();if(n&&(n.activeTournamentId=o),n?.sandboxTournament&&!n?.sandboxTournament.tournamentId)return{error:Nn};const s=n?.sandboxTournament||gr(o),c=n?.sandboxTournament?{[n?.sandboxTournament.tournamentId]:n.sandboxTournament}:Ir(),u=n?mi(n,void 0,!0):void 0,d=n?function(t,e){if(!1===e._middleware)return e;if(e.tournamentId&&!t[e.tournamentId])return{error:_};const n=e.drawId||e.matchUp?.drawId;if(n){const{event:r,drawDefinition:i,tournamentId:a}=Tp({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}=Tp({eventId:e.eventId,tournamentRecords:t});if(!n)return{error:Pt};e.tournamentId=r,e.event=n}const r=e.tournamentId??hr();if(!r&&e)return e;const i=t[r];return r&&!i?{error:_}:i?(e.tournamentRecord=i,e):e}(c,n):void 0;if(d?.error)return d;const p=function({tournamentRecords:t,tournamentRecord:e,params:n,methodName:r,method:i}){if(Qn())return i({tournamentRecords:t,tournamentRecord:e,...n});try{return i({tournamentRecords:t,tournamentRecord:e,...n})}catch(t){return Tr({engineName:"engine",methodName:r,params:n,err:t})}}({params:d,tournamentRecords:c,tournamentRecord:s,methodName:r,method:e});return YD({result:p,methodName:r,elapsed:Date.now()-a,params:u,engineType:i}),p}function ZD(t,e=!0){return"object"!=typeof t||Array.isArray(t)?{error:Pn}:t?.tournamentId?Ur(e?mi(t):t):{error:Nn}}function XD(t,e=!0){if("object"!=typeof t)return{error:Pn};if(yr(),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)yr((t={[t.tournamentId]:t}).tournamentId);else{if(!Object.keys(t).every((e=>t[e].tournamentId===e)))return{error:k}}return Sr(e?mi(t):t)}async function QD(t,e){if(!Ui(e))return{error:Nn,message:"args must be an object"};const n=Object.values(e).filter(gi).length;if(n>1)return{message:"there must be only one arg with typeof function",error:Nn};const r=n?Object.keys(e).find((t=>gi(e[t]))):Ii(e.method)&&e.method;if(!r)return{error:jn};const{[r]:i,...a}=e,o=e?.params||{...a},s=o.rollbackOnError&&mi(Ir(),!1,!0),c=i||t[r]||Yn()[r];if(!c)return KD({methodName:r,params:o});const u=await JD(t,c,o,r,"async")??{};u?.error&&s&&XD(s);const d=Date.now(),p=zD({timeStamp:d}),l=u?.success&&!0!==o?.delayNotify&&!0!==o?.doNotNotify;return l&&await qD({directives:[{method:c,params:o}],mutationStatus:p,timeStamp:d}),(l||!u?.success||o?.doNotNotify)&&lr(),u}function tb(t,e){return e?.error?(t.error=e.error,t.success=!1):(t.error=void 0,t.success=!0),t}function eb(t,e){t.importMethods=n=>function(t,e,n){return Ui(n)?(or(n),Object.keys(n).filter((t=>gi(n[t]))).forEach((r=>{t[r]=i=>{const a=()=>e(t,{[r]:n[r],...i});if(Qn())return a();try{return a()}catch(t){Tr({engineName:"engine",methodName:r,params:i,err:t})}}})),{...E,...t}):{error:Nn}}(t,e,n),t.getTournament=t=>function(t){const{convertExtensions:e=!1,removeExtensions:n=!1}=t??{},r=t?.tournamentId??hr();return"string"!=typeof r?{}:{tournamentRecord:mi(gr(r),e,!1,n)}}(t),t.getState=t=>function({convertExtensions:t,removeExtensions:e}){const n=Ir();return{tournamentId:hr(),tournamentRecords:mi(n,t,!1,e)}}({convertExtensions:t?.convertExtensions,removeExtensions:t?.removeExtensions}),t.version=()=>"2.0.0-beta.6",t.reset=()=>(Sr({}),tb(t)),t.devContext=e=>(er(e),tb(t)),t.getDevContext=t=>Qn(t),t.newTournamentRecord=(t={})=>{const e=hv(t),n=e.tournamentId;return e.error?e:(ZD(e),yr(n),{...E,tournamentId:n})},t.setState=(e,n,r)=>{ir(n,r);const i=XD(e,n);return tb(t,i)},t.setTournamentId=t=>yr(t),t.getTournamentId=()=>hr(),t.setTournamentRecord=(e,n,r)=>{ir(n,r);const i=ZD(e,n);return tb(t,i)},t.removeTournamentRecord=e=>{const n=vr(e);return tb(t,n)},t.removeUnlinkedTournamentRecords=()=>{const e=function(){const t=Ir(),{extension:e}=Fr({name:Ha,tournamentRecords:t,discover:!0}),n=e?.value?.tournamentIds||[];return Object.keys(t).forEach((e=>{n.includes(e)||delete t[e]})),Sr(t)}();return tb(t,e)}}function nb(t){const e=Xn();if(e.error&&!t)return e;const n={executionQueue:(t,e)=>async function(t,e,n){if(!Array.isArray(e))return{error:Nn,message:"directives must be an array"};const r=ur(),i=Date.now(),a=n&&mi(Ir(),!1,!0),o=[];for(const n of e){if("object"!=typeof n)return{error:Nn,message:"directive must be an object"};const{method:e,params:s={},pipe:c}=n;if(!r[e])return KD({methodName:e,start:i,params:s});if(c){const t=o[o.length-1],e=Object.keys(c);for(const n of e)t[n]&&(s[n]=t[n])}const u=JD(t,r[e],s,e,"async");if(u?.error)return a&&XD(a),{...u,rolledBack:!!a};o.push({...u,methodName:e})}const s=Date.now();return qD({directives:e,mutationStatus:zD({timeStamp:s}),timeStamp:s}),lr(),{success:o.every((t=>t.success)),results:o}}(n,t,e),execute:t=>QD(n,t)};return eb(n,QD),n}function rb(t,e){if(!Ui(e))return{error:Nn,message:"args must be an object"};const n=Object.values(e).filter(gi).length;if(n>1)return{message:"there must be only one arg with typeof function",error:Nn};const r=n?Object.keys(e).find((t=>gi(e[t]))):Ii(e.method)&&e.method;if(!r)return{error:jn};const{[r]:i,...a}=e,o=e?.params||{...a},s=i||t[r]||Yn()[r];return s?JD(t,s,o,r,"ask"):KD({methodName:r,params:o})}const ib=(()=>{const t={execute:e=>rb(t,e)};return eb(t,rb),t})();function ab(t,e){if(!Ui(e))return{error:Nn,message:"args must be an object"};const n=Object.values(e).filter(gi).length;if(n>1)return{message:"there must be only one arg with typeof function",error:Nn};const r=n?Object.keys(e).find((t=>gi(e[t]))):Ii(e.method)&&e.method;if(!r)return{error:jn};const{[r]:i,...a}=e,o=e?.params||{...a},s=o.rollbackOnError&&mi(Ir(),!1,!0),c=i||t[r]||Yn()[r];if(!c)return KD({methodName:r,params:o});const u=JD(t,c,o,r,"sync")??{};u?.error&&s&&XD(s);const d=Date.now(),p=zD({timeStamp:d}),l=u?.success&&!0!==o?.delayNotify&&!0!==o?.doNotNotify;return l&&GD({directives:[{method:c,params:o}],mutationStatus:p,timeStamp:d}),(l||!u?.success||o?.doNotNotify)&&lr(),u}const ob=(()=>{const t={executionQueue:(e,n)=>function(t,e,n){if(!Array.isArray(e))return{error:Nn,message:"directives must be an array"};const r=ur(),i=Date.now(),a=n&&mi(Ir(),!1,!0),o=[];for(const n of e){if("object"!=typeof n)return{error:Nn,message:"directive must be an object"};const{method:e,params:s={},pipe:c}=n;if(!r[e])return KD({methodName:e,start:i,params:s});if(c){const t=o[o.length-1],e=Object.keys(c);for(const n of e)t[n]&&(s[n]=t[n])}const u=JD(t,r[e],s,e,"sync");if(u?.error)return a&&XD(a),{...u,rolledBack:!!a};o.push({...u,methodName:e})}const s=Date.now();return GD({directives:e,mutationStatus:zD({timeStamp:s}),timeStamp:s}),lr(),{success:o.every((t=>t.success)),results:o}}(t,e,n),execute:e=>ab(t,e)};return eb(t,ab),t})(),sb={...so,...dw,...hw,...Ty,...vD,...ZT,...lw,...jT,...zS,...LT,...UD,...BD};ob.importMethods(sb);const cb=ob,ub=ob;let db,pb={};function lb(t,e=!0){if(!t)return{error:ae};if("object"!=typeof t)return{error:Pn};if(t.matchUpId)db=t.matchUpId,pb[db]=e?mi(t):t;else if(Array.isArray(t))for(const n of t.reverse())n.matchUpId&&(pb[n.matchUpId]=e?mi(n):n,db||(db=n.matchUpId));else for(const n of Object.values(t))n.matchUpId&&(pb[n.matchUpId]=e?mi(n):n,db||(db=n.matchUpId));return e?mi(t):t}const mb=(()=>{const t={getState:t=>function(t){return mi(pb[db],t?.convertExtensions,!1,t?.removeExtensions)}(t),version:()=>"2.0.0-beta.6",reset:()=>(db=void 0,pb={},{...E}),drawId:void 0,error:void 0,success:!1,devContext:e=>(er(e),t),setState:(e,n,r)=>{ir(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}(lb(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){Tr({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||pb[db],a=e?.matchUps||Object.values(pb),o=e?.rollbackOnError&&mi(i,!1,!0);e={...e,matchUpId:i?.matchUpId,matchUps:a,matchUp:i};const s=n[r](e);if(s?.error)return o&&lb(o),{...s,rolledBack:!!o};const c=s?.success&&!0!==e?.delayNotify&&!0!==e?.doNotNotify;return c&&GD(),(c||!s?.success||e?.doNotNotify)&&lr(),s}})();let fb=!1;const hb=(()=>{const t={version:()=>"2.0.0-beta.6",setDeepCopy:(e,n)=>(ir(e,n),t),devContext:e=>(er(e),fb=!0,t)};return function(e){e.forEach((e=>{Object.keys(e).forEach((n=>{t[n]=t=>{try{const r=function(t,e){const n=t({...e});n?.error||GD();lr(),fb&&(er(!1),fb=!1);return n}(e[n],t);return!r?.error&&t?.setState&&r?.tournamentRecord&&XD(r.tournamentRecord),r}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})}}}))}))}([nw]),t})();function gb(t,e){return t&&e&&Array.isArray(e)&&e[t-1]||"object"==typeof e&&e[t]}function Ib(t){const{participation:e={},awardProfiles:n,startDate:r,eventType:i,drawSize:a,drawType:o,category:s,endDate:c,level:u}=t,{participationOrder:d,flightNumber:p,rankingStage:l}=e;return{awardProfile:n.find((t=>(t=>!r&&!c||!t.dateRanges||t.dateRanges.some((t=>{const e=!r||!t.startDate||new Date(r)>new Date(t.startDate),n=!c||!t.endDate||new Date(c)<=new Date(t.endDate);return e&&n})))(t)&&(!t.maxFlightNumber||p<=t.maxFlightNumber)&&(!t.drawTypes?.length||t.drawTypes?.includes(o))&&(!t.drawSizes?.length||t.drawSizes.includes(a))&&(!t.stages?.length||t.stages.includes(l))&&(!t.levels?.length||t.levels.includes(u))&&(!t.maxDrawSize||a<=t.maxDrawSize)&&(!t.drawSize||t.drawSize===a)&&(!t.maxLevel||u<=t.maxLevel)&&(!p||!t.flights?.flightNumbers?.length||t.flights.flightNumbers.includes(p))&&(!t.participationOrder||t.participationOrder===d)&&(!t.category?.ageCategoryCodes||t.category.ageCategoryCodes.includes(s?.ageCategoryCode))&&(!t.eventTypes?.length||t.eventTypes?.includes(i))))}}function Ub({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=gb(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 Sb={getTournamentPoints:function({participantFilters:t,policyDefinitions:e,tournamentRecord:n,saveRankings:r,level:i}){if(!n)return{error:_};const{policyDefinitions:a}=kc({policyTypes:[Ia],tournamentRecord:n}),o=e?.[Ia]??a?.[Ia];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}=mm({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===md&&r!==Ys)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}=Ib({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!==Vo&&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}=Ub({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}=Ub({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=gb(i,w?.level);t?S+=U*t:w.value&&(S+=U*w.value)}}if(N=l+S,e===Ys){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===Zs?(U[r]||(U[r]=[]),U[r].push(t)):e===Ys&&(I[r]||(I[r]=[]),I[r].push(t))}}}}if(r){Cr({element:n,extension:{name:Ja,value:{personPoints:g,teamPoints:I,pairPoints:U}}})}return{participantsWithOutcomes:h,personPoints:g,pairPoints:U,teamPoints:I,...E}}};const yb={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)?yb.kDefault():n},kDefault:()=>1};function vb(t){let{winnerRating:e,loserRating:n,ratingRange:r}=t;const{ratings:i=CU,winnerCountables:a=1,loserCountables:o=0,ratingType:s=RU,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:CU[RU].range,sourceRange:m,value:p?r[0]-e:e}),I=h({targetRange:CU[RU].range,sourceRange:m,value:p?r[0]-n:n}),U=(t,e)=>1/(1+Math.pow(10,(e-t)/yb.nSpread)),S=U(g,I),y=U(I,g),v=yb.kCalc(a),w=yb.kCalc(o),T=yb.kMultiplier(c,u),P=g+T*v*(1-S),D=I+T*w*(0-y),b=h({sourceRange:CU[RU].range,value:P,targetRange:m}),N=h({sourceRange:CU[RU].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>yb.diffThreshold||M<0||E<0)&&(M=e,E=n),{newWinnerRating:M,newLoserRating:E}}const wb={calculateNewRatings:vb,generateDynamicRatings:function({removePriorValues:t=!0,tournamentRecord:e,ratingType:n=RU,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(!CU[n])return{error:Nn};const o=CU[n],{accessor:s}=o,c={},u=El({matchUpFilters:{matchUpIds:i,matchUpStatuses:ko},tournamentRecord:e,inContext:!0}).matchUps??[];u.sort(Ol);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:oa},g=`${n}.${ia}`,I={scaleName:g,eventType:f,scaleType:oa},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}=KU({scaleAttributes:I,tournamentRecord:e,participantId:t}),{scaleItem:r}=KU({tournamentRecord:e,scaleAttributes:h,participantId:t});return t&&{[t]:n??r??{scaleName:S,eventType:f,scaleDate:o,scaleType:oa,scaleValue:s?{[s]:void 0}:void 0}}}))),v=u?Op(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}=vb({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=Ov({participantId:r,removePriorValues:t,tournamentRecord:e,scaleItem:{...y[r],scaleName:S}});if(I.error)return I;if(I=Ov({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}}},Tb={...Sb,...wb};ob.importMethods(Tb);const Pb=ob,Db={ratingsParameters:CU,matchUpFormats:vg,countryToFlag:nc,tieFormats:BS,countries:rc,policies:{POLICY_AVOIDANCE_COUNTRY:{[wa]:{roundsToSeparate:void 0,policyName:"Nationality Code",policyAttributes:[{key:"person.nationalityCode"},{key:"individualParticipants.person.nationalityCode"}]}},POLICY_POSITION_ACTIONS_DEFAULT:nT,POLICY_POSITION_ACTIONS_DISABLED:{[ha]:{policyName:"positionActionsDisabled",enabledStructures:!1}},POLICY_POSITION_ACTIONS_NO_MOVEMENT:{[ha]:{policyName:"positionActionsNoMovement",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[Kw,Yw,Jw],disabledActions:[]}]}},POLICY_POSITION_ACTIONS_UNRESTRICTED:{[ha]:{policyName:"positionActionsUnrestricted",enabledStructures:[],otherFlightEntries:!0,disableRoundRestrictions:!0,activePositionOverrides:[Kw,Hw]}},POLICY_PRIVACY_DEFAULT:{[Sa]:{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:Gp,POLICY_SCHEDULING_DEFAULT:yw,POLICY_SCORING_DEFAULT:{[Ta]:{defaultMatchUpFormat:Sg,allowDeletionWithScoresPresent:{drawDefinitions:!1,structures:!1},requireAllPositionsAssigned:!1,processCodes:{incompleteAssignmentsOnDefault:["RANKING.IGNORE"]},stage:{[Bo]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}}}},POLICY_SCORING_USTA:{[Ta]:{requireAllPositionsAssigned:!1,stage:{[Bo]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},defaultMatchUpFormat:Sg,matchUpFormats:[{description:"Best of 3 tiebreak sets",matchUpFormat:Sg,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:{[Pa]:{seedingProfile:{positioning:Jo},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:oy},flagIOC:function(t){return nc(Object.assign({},...rc.filter((t=>t.ioc)).map((t=>({[t.ioc]:t.iso}))))[t])}},bb={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"},Nb={CLAY:"CLAY",HARD:"HARD",GRASS:"GRASS",CARPET:"CARPET",ARTIFICIAL:"ARTIFICIAL"},Rb={INDOOR:"INDOOR",OUTDOOR:"OUTDOOR"},Mb={activeMatchUpStatuses:xo,auditConstants:lf,completedMatchUpStatuses:ko,directingMatchUpStatuses:Oo,drawDefinitionConstants:_s,entryStatusConstants:gu,errorConditionConstants:$n,eventConstants:fd,extensionConstants:io,flightConstants:dy,genderConstants:Zp,keyValueConstants:sD,matchUpActionConstants:bT,matchUpStatusConstants:Lo,matchUpTypes:hc,nonDirectingMatchUpStatuses:Fo,participantConstants:tc,participantRoles:Rm,particicipantsRequiredMatchUpStatuses:Eo,participantTypes:Qs,penaltyConstants:bb,policyConstants:Na,positionActionConstants:Xw,ratingConstants:EU,recoveryTimeRequiredMatchUpStatuses:Ao,requestConstants:zy,resultConstants:C,scaleConstants:ua,scheduleConstants:bd,sortingConstants:my,surfaceConstants:Nb,tieFormatConstants:kS,timeItemConstants:nd,topicConstants:lp,tournamentConstants:SD,upcomingMatchUpStatuses:_o,validMatchUpStatuses:Co,venueConstants:Rb};export{ib as askEngine,nb as asyncEngine,cb as competitionEngine,_s as drawDefinitionConstants,gu as entryStatusConstants,$n as errorConditionConstants,fd as eventConstants,Mb as factoryConstants,Db as fixtures,dy as flightConstants,jD as forge,Zp as genderConstants,Dr as globalState,VD as governors,sD as keyValueConstants,bT as matchUpActionConstants,mb as matchUpEngine,Rh as matchUpFormatCode,Lo as matchUpStatusConstants,hc as matchUpTypes,hb as mocksEngine,tc as participantConstants,Rm as participantRoles,Qs as participantTypes,bb as penaltyConstants,Na as policyConstants,Xw as positionActionConstants,C as resultConstants,ua as scaleConstants,Pb as scaleEngine,Nb as surfaceConstants,ob as syncEngine,nd as timeItemConstants,ub as tournamentEngine,DD as utilities,Rb as venueConstants,t as version};
|
|
1
|
+
function t(){return"2.0.0-beta.7"}function e(t,e){return(t??0)-(e??0)}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 Array.isArray(t)?t?.filter(((t,e,n)=>n.lastIndexOf(t)===e)):[]}function f(t){return Array.isArray(t)?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 Array.isArray(t)?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 Array.isArray(t)?t.reduce(((t,n,r)=>{const i=Math.floor(r/e);return t[i]=[].concat(t[i]||[],n),t}),[]):[]}function M(t){return!!Array.isArray(t)&&t.reduce(((t,e)=>!isNaN(parseInt(e))&&t),!0)}function R(t){return!!Array.isArray(t)&&t.reduce(((t,e)=>isNaN(parseInt(e))&&t),!0)}function A(t,e,n){return Array.isArray(t)?t.reduce(((t,r,i)=>{const a=!!n&&!!(Math.floor(i/e)%2),o=i%e,s=a?e-1-o:o;return t[s]||(t[s]=[]),t[s].push(r),t}),[]):[]}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"},_={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},x={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"},Q={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},Z={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},X={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"},Mt={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},Rt={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"},_t={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},xt={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"},Qt={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},Zt={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},Xt={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"},Me={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},Re={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"},_e={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},xe={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"},Qe={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},Ze={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},Xe={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"},Mn={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},Rn={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"},_n={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},xn={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:Z,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:Mn,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:xn,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Le,EXISTING_PARTICIPANT:Be,EXISTING_POLICY_TYPE:te,EXISTING_PROFILE:_n,EXISTING_ROUND:gt,EXISTING_STAGE:Bn,EXISTING_STRUCTURE:Vn,INCOMPATIBLE_MATCHUP_STATUS:_t,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:X,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:xt,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:Xt,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:Mt,MISSING_ASYNC_STATE_PROVIDER:ln,MISSING_AVOIDANCE_POLICY:Qt,MISSING_COLLECTION_DEFINITION:jt,MISSING_COURT_ID:ie,MISSING_COURTS_INFO:Xe,MISSING_DATE_AVAILABILITY:de,MISSING_DATE:oe,MISSING_DRAW_DEFINITION:j,MISSING_DRAW_ID:at,MISSING_DRAW_POSITION:tt,MISSING_DRAW_POSITIONS:Q,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:Me,MISSING_PARTICIPANTS:Re,MISSING_PENALTY_ID:Qe,MISSING_PENALTY_TYPE:Je,MISSING_PERSON_DETAILS:xe,MISSING_POLICY_ATTRIBUTES:Zt,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:Rt,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:x,MISSING_TOURNAMENT_RECORDS:_,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:_e,PARTICIPANT_NOT_FOUND:Ee,PARTICIPANT_PAIR_EXISTS:{message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},PENALTY_NOT_FOUND:Ze,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:Rn,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:x}},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 Qn=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function Zn(){if(Jn.createInstanceState){try{Jn.createInstanceState()}catch(t){return{error:t}}return{success:!0}}return{error:ln}}function Xn(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.disableNotifications()}function rr(){Jn.enableNotifications()}function ir(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 ar(){return{enabled:Kn.deepCopy,...Kn.deepCopyAttributes}}function or(t){return t?"object"!=typeof t?{error:Nn}:Jn.setMethods(t):{error:ae,info:"missing method declarations"}}function sr(){return Jn.cycleMutationStatus()}function cr(t){return Jn.addNotice(t)}function ur(){return Jn.getMethods()}function dr(t){return Jn.getNotices(t)}function pr({key:t,topic:e}){return Jn.deleteNotice({key:t,topic:e})}function lr(){return Jn.deleteNotices()}function mr(){return Jn.getTopics()}async function fr(t){return Jn.callListener(t)}function hr(){return Jn.getTournamentId()}function gr(t){return Jn.getTournamentRecord(t)}function Ir(){return Jn.getTournamentRecords()}function Ur(t){return Jn.setTournamentRecord(t)}function Sr(t){return Jn.setTournamentRecords(t)}function yr(t){return Jn.setTournamentId(t)}function vr(t){return Jn.removeTournamentRecord(t)}function wr(){return Jn}function Tr({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 Pr(t,e){if(Kn.globalLog)try{Kn.globalLog({log:t,engine:e})}catch(n){console.log("globalLog error",n),console.log(e,t),tr()}else console.log(e,t)}var Dr=Object.freeze({__proto__:null,addNotice:cr,callListener:fr,createInstanceState:Zn,cycleMutationStatus:sr,deepCopyEnabled:ar,deleteNotice:pr,deleteNotices:lr,disableNotifications:nr,enableNotifications:rr,getDevContext:Xn,getMethods:ur,getNotices:dr,getProvider:wr,getTopics:mr,getTournamentId:hr,getTournamentRecord:gr,getTournamentRecords:Ir,globalLog:Pr,handleCaughtError:Tr,removeTournamentRecord:vr,setDeepCopy:ir,setDevContext:er,setGlobalLog:tr,setMethods:or,setStateProvider:function(t){if("object"!=typeof t)throw new Error("Global state provider can not be undefined or null");if(P(Object.keys(t),Qn).length!==Qn.length)throw new Error("Global state provider is missing required methods");return Jn=t,{success:!0}},setSubscriptions:function(t){return t?.subscriptions?Jn.setSubscriptions({subscriptions:t.subscriptions}):{error:ae,info:"missing subscriptions"}},setTournamentId:yr,setTournamentRecord:Ur,setTournamentRecords:Sr,timeKeeper:function(t="reset",e="default"){const n=Date.now();if("report"===t){if("allTimers"===e){return Object.keys(Kn.timers).filter((t=>"default"!==t||Kn.timers[t].startTime)).map((t=>{const e=Kn.timers[t],r="stopped"===e.state?0:(n-(e?.startTime??0))/1e3,i=e.elapsedTime+r;return{state:Kn.timers[t].state,elapsedTime:i.toFixed(2),timer:t}}))}{const t="stopped"===Kn.timers[e].state?0:(n-(Kn.timers[e]?.startTime??0))/1e3,r=Kn.timers[e].elapsedTime+t;return{state:Kn.timers[e].state,elapsedTime:r.toFixed(2),timer:e}}}if(!Kn.timers[e]||"reset"===t){if("allTimers"===e)return Kn.timers={default:{elapsedTime:0}},!0;Kn.timers[e]={startTime:n,state:"active",elapsedTime:0}}return Kn.timers[e].elapsedTime||(Kn.timers[e].elapsedTime=0),"stop"===t&&"stopped"!==Kn.timers[e].state&&(Kn.timers[e].state="stopped")&&(Kn.timers[e].elapsedTime+=(n-(Kn.timers[e]?.startTime??0))/1e3),"start"===t&&(Kn.timers[e].startTime=n)&&(Kn.timers[e].state="active"),Kn.timers[e]}});function br(t,e,n,r){if("object"!=typeof t||null===t)return t;const i=ar();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=>br(t)))}:{[e]:r?t[e]:br(t[e])})))}function Nr({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,br(t)),!e||e?.error||e?.success||Object.assign(e,{...E}),e??{success:!0}}const Mr="element required",Rr="missing name";function Ar(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:Rr};if(!t?.element){if(t.discover&&t.tournamentRecords){for(const e of Object.keys(t.tournamentRecords)){const n=Ar({element:t.tournamentRecords[e],name:t.name});if(n.error)return Nr({result:n,stack:"removeExtension"})}return{...E}}return{error:ae,info:Mr}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter((e=>e?.name!==t.name)),{...E}):{...E,info:On}}function Er({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 Cr(t){if("object"!=typeof t)return{error:ae};const e="addExtension";if(t?.element&&"object"!=typeof t.element)return Nr({result:{error:Nn},stack:e});if(!Er({extension:t.extension}))return Nr({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=Cr({extension:t.extension,element:n});if(r.error)return Nr({result:r,stack:e})}return{...E}}return Nr({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 Or="extensionQueries";function Fr({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 Nr({result:{error:ae},stack:Or})}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 kr=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,_r=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,xr=/^([\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?$/,Lr=/^([\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 Br(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=ti(t.scheduledTime)),!e)return;const n=Xr(t.scheduledTime);let r=ti(e);return r&&n&&(r+=`T${n}`),r}function Vr(t){if("object"!=typeof t||Array.isArray(t))return!1;return"[object Date]"===Object.prototype.toString.call(t)}function jr(t){const e="string"==typeof t?t?.split(" "):[];return!(t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase()))&&!(t&&!Lr.test(ri(t,!0,!0)))}function Gr(t){return Kr(t)||kr.test(t)}const qr=t=>{const e=Hr(t)||Kr(t)?new Date(t):new Date,n=e.getUTCMonth()+1,r=n<10?`0${n}`:`${n}`;return`${e.getUTCFullYear()}-${di(r)}-${di(e.getUTCDate())}`};function $r(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 Wr(t){const e=t?new Date(t):new Date,n=e.getTimezoneOffset();return new Date(e.getTime()-60*n*1e3)}function Hr(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 zr(t,e){if(!Gr(t)||!Gr(e))return[];const n=ti(t)+"T00:00",r=ti(e)+"T00:00",i=new Date(n),a=new Date(r);const o=[];let s=0;if(Hr(a)&&Hr(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=>$r(t)))}const Yr=/^([+-]?\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 Kr(t){return"string"==typeof t&&Yr.test(t)}function Jr(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 Qr(t){const e=Xr(t);if(!e)return 0;const[n,r]=e.split(":").map((t=>parseInt(t)));return 60*n+r}function Zr(t){return Jr(t)?t.split(":").slice(0,2).map(di).join(":"):void 0}function Xr(t){return Kr(t)&&t.indexOf("T")>0?Zr(t.split("T").reverse()[0]):Zr(t)}function ti(t){return Kr(t)||xr.test(t)?t.split("T")[0]:void 0}function ei(t,e){const n=new Date(t);return n.setDate(n.getDate()+e),ti(n.toISOString())}function ni(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 ri(t,e,n){const r=ti(t),i=Xr(t),a=r?i:t;return t?e&&(r&&n&&t||function(t){const e=ni(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(di).join(":")}(a))||function(t){const e=ni(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 ii(t,e){const n=ni(t),r=ni(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 ai(t,e=7){const n=ti(t)+"T00:00",r=new Date(n);return $r(new Date(r.setDate(r.getDate()+e)))}function oi(t,e=void 0){const[n,r]=(t||"00:00").split(":").map(di),i=Wr(e).setHours(n,r,0,0);return Wr(i)}function si(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 ci(t,e){const n=Xr(t);if(!n)return"00:00";const r=isNaN(e)?0:e;return Xr(ui(oi(n),r).toISOString())}function ui(t,e){const n=new Date(t);return new Date(n.getTime()+6e4*e)}function di(t){return t.toString()[1]?t:"0"+t}function pi(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 li={addDays:ai,addWeek:function(t){return ai(t)},addMinutesToTimeString:ci,convertTime:ri,getIsoDateString:Br,getUTCdateString:qr,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(di).join(":")}(e.getSeconds()+60*e.getMinutes()+3600*e.getHours(),{displaySeconds:!1})},extractDate:ti,extractTime:Xr,formatDate:$r,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())),$r(i,n)},isISODateString:Kr,isDate:Hr,isTimeString:Jr,offsetDate:Wr,offsetTime:function(t){return Wr(t).getTime()},sameDay:pi,timeStringMinutes:Qr,timeToDate:oi,timeUTC:function(t){const e=Hr(t)||Kr(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())},validTimeValue:jr,validDateString:kr,timeValidation:Lr,dateValidation:xr};function mi(t,e,n,r,i=0){if(wr().makeDeepCopy)return wr().makeDeepCopy(t,e,n,r);const a=ar(),{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=fi(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:Vr(c)?d[a]=new Date(c).toISOString():d[a]=mi(c,e,n,r,i+1)}return d}function fi(t){return t?.map((t=>{const{name:e,value:n}=t;return e&&n&&{[`_${e}`]:n}})).filter(Boolean)}function hi({element:t,accessor:e}){if("string"!=typeof e)return{values:[]};const n=mi(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 gi(t){return"function"==typeof t}function Ii(t){return"string"==typeof t}function Ui(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function Si(t,e){if(!Ui(t)||!Ui(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 yi(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(Ui).map((t=>t[e]&&{[t[e]]:t})).filter(Boolean)):{}}const vi=t=>e=>t&&"object"==typeof e?Array.isArray(t)&&t.map((t=>({[t]:hi({element:e,accessor:t})?.value})))||"object"==typeof t&&Object.keys(t).map((t=>({[t]:hi({element:e,accessor:t})?.value})))||("string"==typeof t&&hi({element:e,accessor:t}))?.value:void 0,wi=vi;function Ti(t){return Array.isArray(t)?t.length+t.map(Ti).reduce(((t,e)=>t+e),0):"object"==typeof t&&null!==t?Object.keys(t).length+Object.keys(t).map((e=>Ti(t[e]))).reduce(((t,e)=>t+e),0):0}const Pi="tournamentRecords",Di="policyDefinitions",bi="tournamentRecord",Ni="drawDefinition",Mi="matchUpFormat",Ri="participantId",Ai="scheduleDates",Ei="structureId",Ci="participant",Oi="matchUpIds",Fi="structures",ki="matchUpId",_i="inContext",xi="structure",Li="courtIds",Bi="venueIds",Vi="matchUps",ji="courtId",Gi="eventId",qi="matchUp",$i="drawId",Wi="error",Hi="event",zi="param",Yi="object",Ki="array",Ji="validate",Qi="invalid",Zi="_ofType",Xi="_oneOf",ta={[Pi]:_,[bi]:x,[Di]:Jt,[Ni]:j,[Ri]:Ae,tournamentId:B,[Ei]:It,[Oi]:$t,[Ci]:Me,[Fi]:St,[ki]:qt,[xi]:yt,[ji]:ie,[Vi]:Ht,[qi]:zt,[Li]:ae,[Bi]:ae,[$i]:at,[Gi]:Tt,[Hi]:Pt},ea={[Pi]:Yi,[Di]:Yi,[bi]:Yi,[Ni]:Yi,[Ai]:Ki,[Ci]:Yi,[Oi]:Ki,[Fi]:Ki,[xi]:Yi,[Li]:Ki,[Bi]:Ki,[Vi]:Ki,[qi]:Yi,[Hi]:Yi,uuids:Ki};function na(t,e,n){if(!t&&!Ui(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=ra(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=ra(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=a&&!gi(a),s=t[r]&&!a&&function(t,e,n){if(n=n||ea[e]||"string","array"===n)return!Array.isArray(t[e]);return typeof t[e]!==n}(t,r,e),c=o[r]&&!t[r],u=i||s||c||a&&t[r]&&!function(t,e){return!gi(e)||e(t)}(t[r],a);return u&&(n=r),u}));return!u.length||d}));return{paramError:r,errorParam:n}}(t,e);if(!r)return{valid:!0};return Nr({info:{param:i},result:{error:void 0===t[i]?ta[i]||Nn:r.validate&&r.invalid||Nn},stack:n})}function ra(t,e){return P(Object.keys(t),Object.keys(e))}const ia="DYNAMIC",aa="RANKING",oa="RATING",sa="SCALE",ca="SEEDING",ua={RANKING:aa,RATING:oa,SCALE:sa,SEEDING:ca};function da(t){const e=na(t,[{[Ci]:!0}]);if(e.error)return e;const n=t.participant.timeItems?.filter((({itemType:t})=>t?.startsWith(sa)&&[aa,oa,ca].includes(t.split(".")[1]))),r={ratings:{},rankings:{},seedings:{}};if(n?.length){const t=t=>n.filter((e=>e?.itemType===t)).sort(((t,e)=>new Date(t.createdAt||void 0).getTime()-new Date(e.createdAt||void 0).getTime())).pop(),e=m(n.map((({itemType:t})=>t)));for(const n of e){const e=t(n);if(e){const[,t,n,i,a]=e.itemType.split("."),o=a?`${i}.${a}`:i,s=(t===ca?"seedings":t===aa&&"rankings")||"ratings";r[s][n]||(r[s][n]=[]),r[s][n].push({scaleValue:e.itemValue,scaleDate:e.itemDate,scaleName:o})}}}return{...E,...r}}function pa(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 la="voluntaryConsolation",ma="competitiveBands",fa="roundRobinTally",ha="positionActions",ga="matchUpActions",Ia="rankingPoints",Ua="roundNaming",Sa="participant",ya="progression",va="scheduling",wa="avoidance",Ta="scoring",Pa="seeding",Da="feedIn",ba="draws",Na={POLICY_TYPE_VOLUNTARY_CONSOLATION:la,POLICY_TYPE_COMPETITIVE_BANDS:ma,POLICY_TYPE_ROUND_ROBIN_TALLY:fa,POLICY_TYPE_POSITION_ACTIONS:ha,POLICY_TYPE_MATCHUP_ACTIONS:ga,POLICY_TYPE_RANKING_POINTS:Ia,POLICY_TYPE_ROUND_NAMING:Ua,POLICY_TYPE_PARTICIPANT:Sa,POLICY_TYPE_PROGRESSION:ya,POLICY_TYPE_SCHEDULING:va,POLICY_TYPE_AVOIDANCE:wa,POLICY_TYPE_DISPLAY:"display",POLICY_TYPE_FEED_IN:Da,POLICY_TYPE_SCORING:Ta,POLICY_TYPE_SEEDING:Pa,POLICY_TYPE_AUDIT:"audit",POLICY_TYPE_DRAWS:ba};function Ma({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:n,participantId:r,internalUse:i,personId:a}){const o=mi(t.find((t=>r&&t.participantId===r||a&&t.person&&t.person.personId===a)),!1,i);if(o){const t=e?.[Sa];if(n?.withScaleValues){const{ratings:t,rankings:e}=da({participant:o});o.rankings=e,o.ratings=t}if(t?.participant)return pa({template:t.participant,source:o})}return o}function Ra(t){return t&&"object"==typeof t?t.tournamentRecord?Cr({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:x}:{error:ae}}function Aa(t){return t&&"object"==typeof t?t.drawDefinition?Cr({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:q}:{error:ae}}function Ea(t){return t&&"object"==typeof t?t.event?Cr({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:Pt}:{error:ae}}function Ca(t){if(!t||"object"!=typeof t)return{error:ae};if(!t.participantId)return{error:Ae};const e=t.tournamentRecord?.participants||[],n=Ma({participantId:t.participantId,tournamentParticipants:e});return n?Cr({creationTime:t.creationTime,extension:t.extension,element:n}):{error:Ee}}function Oa(t){return t&&"object"==typeof t?t.tournamentRecord?Ar({element:t.tournamentRecord,name:t.name}):{error:x}:{error:ae}}function Fa(t){return t&&"object"==typeof t?t.drawDefinition?Ar({element:t.drawDefinition,name:t.name}):{error:q}:{error:ae}}function ka(t){return t&&"object"==typeof t?t?.event?Ar({element:t.event,name:t.name}):{error:Pt}:{error:ae}}function _a(t){if(!t||"object"!=typeof t)return{error:ae};if(!t.participantId)return{error:Ae};const e=t.tournamentRecord?.participants||[],n=Ma({participantId:t.participantId,tournamentParticipants:e});return n?Ar({element:n,name:t.name}):{error:Ee}}const xa="appliedPolicies",La="positionActions",Ba="context",Va="delegatedOutcome",ja="disabled",Ga="disableLinks",qa="disableAutoCalc",$a="drawDeletions",Wa="entryProfile",Ha="flightProfile",za="groupingAttribute",Ya="lineUps",Ka="linkedTournamentsIds",Ja="matchUpHistory",Qa="participantRepresentatives",Za="personRequests",Xa="rankingPoints",to="roundTarget",eo="scheduleLimits",no="scheduleTiming",ro="schedulingProfile",io="subOrder",ao="tally",oo="tieFormatModification",so={ACTIVE_SUSPENSION:"activeSuspension",APPLIED_POLICIES:xa,AUDIT_POSITION_ACTIONS:La,CONTEXT:Ba,DELEGATED_OUTCOME:Va,DISABLED:ja,DISABLE_LINKS:Ga,DISABLE_AUTO_CALC:qa,DRAW_DELETIONS:$a,DRAW_PROFILE:"drawProfile",ENTRY_PROFILE:Wa,EVENT_PROFILE:"eventProfile",EVENT_WITHDRAWAL_REQUESTS:"eventWithdrawalRequests",FLIGHT_PROFILE:Ha,GROUPING_ATTRIBUTE:za,LINEUPS:Ya,LINKED_TOURNAMENTS:Ka,MATCHUP_HISTORY:Ja,PARTICIPANT_REPRESENTATIVES:Qa,PERSON_REQUESTS:Za,RANKING_POINTS:Xa,ROUND_TARGET:to,SCHEDULE_LIMITS:eo,SCHEDULE_TIMING:no,SCHEDULING_PROFILE:ro,STATUS_DETAIL:"statusDetail",SUB_ORDER:io,TALLY:ao,TIE_FORMAT_MODIFICATIONS:oo,FACTORY:"factory"},co=[Va,ja,Ga,Ha,Ya,Ja,Qa,Za,to,eo,no,ro,io,ao];function uo({tournamentRecords:t}){return{tournamentIds:Ui(t)?Object.keys(t):[],...E}}function po({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:_};const e=uo({tournamentRecords:t}),{tournamentIds:n}=e;if(n?.length>1){return Cr({tournamentRecords:t,discover:!0,extension:{name:Ka,value:{tournamentIds:n}}})}return{...E}}function lo({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:_};return Nr({result:Ar({name:Ka,tournamentRecords:t,discover:!0}),stack:"unlinkTournaments"})}function mo({tournamentRecords:t,tournamentId:e}){if("object"!=typeof t)return{error:Nn};if(!e)return{error:B};const n=uo({tournamentRecords:t}),{tournamentIds:r}=n;if(!r.includes(e))return{error:B};let i;return r.every((n=>{const r=t[n],{extension:a}=Fr({element:r,name:Ka});if(!a)return!0;const o=a?.value?.tournamentIds||[];if(!o?.length||1===o.length&&o.includes(e)||n===e){const t=Oa({name:Ka,tournamentRecord:r});return t.error&&(i=t.error),t.success}const s=o.filter((t=>t!==e));a.value={tournamentIds:s};const c=Ra({tournamentRecord:r,extension:a});return c.error&&(i=c.error),c.success})),i?{error:i}:{...E}}var fo=Object.freeze({__proto__:null,linkTournaments:po,unlinkTournament:mo,unlinkTournaments:lo});function ho({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:_};return{linkedTournamentIds:Object.assign({},...Object.keys(t).map((e=>{const n=t[e],r=n?.tournamentId,{extension:i}=Fr({element:n,name:Ka});return{[e]:(i?.value?.tournamentIds||[]).filter((t=>t!==r))}})))}}var go=Object.freeze({__proto__:null,getLinkedTournamentIds:ho,getTournamentIds:uo}),Io=Object.freeze({__proto__:null,getLinkedTournamentIds:ho,getTournamentIds:uo,linkTournaments:po,mutate:fo,query:go,unlinkTournament:mo,unlinkTournaments:lo});const Uo=t=>e=>t[e],So=(t=[])=>t.map(wo).filter(Boolean),yo=(t=[])=>t.map(vo).filter(Boolean),vo=(t={})=>Uo(t)("participantId"),wo=(t={})=>Uo(t)("matchUpId"),To=(t={})=>Uo(t)("drawId");function Po({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:q};if(!Array.isArray(t))return{error:Nn};const n=yo(e?.entries||[]);if(t.length&&P(t,n).length<t.length)return{error:Nn};return Aa({drawDefinition:e,extension:{name:Qa,value:t}})}const Do="ABANDONED",bo="AWAITING_RESULT",No="BYE",Mo="CANCELLED",Ro="COMPLETED",Ao="DEAD_RUBBER",Eo="DEFAULTED",Co="DOUBLE_DEFAULT",Oo="DOUBLE_WALKOVER",Fo="IN_PROGRESS",ko="INCOMPLETE",_o="NOT_PLAYED",xo="RETIRED",Lo="SUSPENDED",Bo="TO_BE_PLAYED",Vo="WALKOVER",jo=[bo,Ro,Eo,Fo,ko,xo,Lo],Go=[bo,Ro,Eo,Oo,Co,Fo,ko,xo,Lo,Vo],qo=[Do,bo,No,Mo,Ro,Ao,Eo,Oo,Co,Fo,ko,_o,xo,Lo,Bo,Vo],$o=[No,Oo,Co,Ro,Eo,xo,Vo],Wo=[Do,bo,Mo,Ao,Fo,ko,_o,Lo,Bo,void 0],Ho=[Mo,Do,Ro,Ao,Eo,Oo,Co,xo,Vo],zo=[Do,Ro,Eo,Oo,Co,Fo,xo,Vo],Yo=[Fo,ko,Lo,Bo],Ko={ABANDONED:Do,AWAITING_RESULT:bo,BYE:No,CANCELLED:Mo,COMPLETED:Ro,DEAD_RUBBER:Ao,DEFAULTED:Eo,DOUBLE_WALKOVER:Oo,DOUBLE_DEFAULT:Co,IN_PROGRESS:Fo,INCOMPLETE:ko,NOT_PLAYED:_o,RETIRED:xo,SUSPENDED:Lo,TO_BE_PLAYED:Bo,WALKOVER:Vo},Jo="MAIN",Qo="QUALIFYING",Zo="CONSOLATION",Xo="VOLUNTARY_CONSOLATION",ts="PLAY_OFF",es=[Jo,Qo,Zo,ts,Xo],ns={[Qo]:1,[Jo]:2,[ts]:3,[Zo]:3,[Xo]:4},rs="finishingPositions",is="aggregateEventStructures",as={[Jo]:1,[ts]:2,[Zo]:3,[Qo]:4,[Xo]:5},os={[ts]:1,[Jo]:2,[Zo]:3,[Qo]:4,[Xo]:5},ss="CLUSTER",cs="WATERFALL",us="ITEM",ds="CONTAINER",ps="DRAW",ls="RANDOM",ms="TOP_DOWN",fs="BOTTOM_UP",hs="POSITION",gs="WINNER",Is="LOSER",Us="FIRST_MATCHUP",Ss="AD_HOC",ys="FEED_IN",vs="COMPASS",ws="OLYMPIC",Ts="SINGLE_ELIMINATION",Ps="DOUBLE_ELIMINATION",Ds="FIRST_MATCH_LOSER_CONSOLATION",bs="FIRST_ROUND_LOSER_CONSOLATION",Ns="LUCKY_DRAW",Ms="CURTIS_CONSOLATION",Rs="CURTIS_CONSOLATION",As="FEED_IN_CHAMPIONSHIP_TO_SF",Es="FEED_IN_CHAMPIONSHIP_TO_SF",Cs="FEED_IN_CHAMPIONSHIP_TO_QF",Os="FEED_IN_CHAMPIONSHIP_TO_QF",Fs="FEED_IN_CHAMPIONSHIP_TO_R16",ks="FEED_IN_CHAMPIONSHIP_TO_R16",_s="MODIFIED_FEED_IN_CHAMPIONSHIP",xs="MODIFIED_FEED_IN_CHAMPIONSHIP",Ls="FEED_IN_CHAMPIONSHIP",Bs="ROUND_ROBIN",Vs="ROUND_ROBIN_WITH_PLAYOFF",js="DECIDER",Gs="BACKDRAW",qs={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"}},$s={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},Ws="WIN_RATIO",Hs="ROUND_OUTCOME",zs=[vs,Ms,Os,ks,Es,Ls,Cs,Fs,As,Ds,bs,Ns,xs,ws,ts,Vs],Ys={MAIN:Jo,QUALIFYING:Qo,CONSOLATION:Zo,ITEM:us,CONTAINER:ds,FIRST_MATCHUP:Us,WINNER:gs,LOSER:Is,AD_HOC:Ss,FEED_IN:ys,FLEX_ROUNDS:"AD_HOC",COMPASS:vs,PLAY_OFF:ts,OLYMPIC:ws,KNOCKOUT:"SINGLE_ELIMINATION",SINGLE_ELIMINATION:Ts,DOUBLE_ELIMINATION:Ps,CURTIS:Ms,FICSF:As,FICQF:Cs,FICR16:Fs,MFIC:_s,VOLUNTARY_CONSOLATION:Xo,FIRST_MATCH_LOSER_CONSOLATION:Ds,FIRST_ROUND_LOSER_CONSOLATION:bs,MODIFIED_FEED_IN_CHAMPIONSHIP:xs,FEED_IN_CHAMPIONSHIP_TO_R16:ks,FEED_IN_CHAMPIONSHIP_TO_QF:Os,FEED_IN_CHAMPIONSHIP_TO_SF:Es,FEED_IN_CHAMPIONSHIP:Ls,LUCKY_DRAW:Ns,ROUND_ROBIN_WITH_PLAYOFF:Vs,ROUND_ROBIN:Bs,DECIDER:js,BACKDRAW:Gs,COMPASS_ATTRIBUTES:qs,OLYMPIC_ATTRIBUTES:$s,DRAW:ps,RANDOM:ls,TOP_DOWN:ms,BOTTOM_UP:fs,WATERFALL:cs,WIN_RATIO:Ws,ROUND_OUTCOME:Hs,MULTI_STRUCTURE_DRAWS:zs,generatedDrawTypes:[Ss,vs,Ms,Ps,Os,ks,Es,Ls,ys,Ds,bs,Ns,xs,ws,ts,Bs,Vs,Ts],stageOrder:ns,finishOrder:as,AGGREGATE_EVENT_STRUCTURES:is,FINISHING_POSITIONS:rs};function Ks(t,e,n){const r=t=>Fr({element:t,name:to})?.extension?.value,i=n?.deprioritizeCompleted,a=n?.mode===is&&os,o=n?.mode===rs&&as,s=o||a||ns,c=t=>(t=>t?.stage===Jo&&1===t?.stageSequence)(t)?-1:s[t?.stage],u=t=>t?.matchUps.every((({matchUpStatus:t})=>Ho.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)||(Js(t)||0)-(Js(e)||0)}function Js(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 Qs({drawDefinition:t,structureId:e}){if(!t)return{error:j};if(!e)return{error:It};const{structures:n}=Zs({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===us?r?.find((t=>t.structures?.some((t=>t.structureId===e)))):void 0}}function Zs({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=Fr({element:t,name:to})?.extension?.value;return!i||i===e})).sort(((t,e)=>Ks(t,e,a)))??[],d=t?Object.assign({},...es.map((t=>{const e=u?.filter((e=>e.stage===t));return e?.length&&{[t]:e}})).filter(Boolean)):{};return{structures:u,stageStructures:d}}function Xs({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}=tc({structure:t}),i=r?.map(vo).filter(Boolean)??[];return e[n].push(...i),i})).flat(),stagePositionedParticipantIds:e}}function tc({drawDefinition:t,structureId:e,structure:n}){let r,i=[];if(!n){if(!t)return{positionAssignments:i,error:j};if(({structure:n,error:r}=Qs({drawDefinition:t,structureId:e})),r)return{positionAssignments:i,error:r}}return n.structures?i=[].concat(...n.structures.map((t=>tc({structure:t}).positionAssignments))):n.positionAssignments?i=n.positionAssignments:r=Ct,{positionAssignments:i,error:r}}function ec({drawDefinition:t,structureId:e,structure:n}){const r=tc({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 nc="addDrawDefinition",rc="addMatchUps",ic="addParticipants",ac="addScaleItems",oc="addVenue",sc="audit",cc="deleteParticipants",uc="deleteVenue",dc="deletedDrawIds",pc="deletedMatchUpIds",lc="modifyDrawDefinition",mc="modifyDrawEntries",fc="modifyEventEntries",hc="modifyMatchUp",gc="modifyParticipants",Ic="modifyPositionAssignments",Uc="modifySeedAssignments",Sc="modifyTournamentDetail",yc="modifyVenue",vc="mutations",wc="publishEvent",Tc="publishEventSeeding",Pc="publishOrderOfPlay",Dc="unPublishEvent",bc="unPublishEventSeeding",Nc="unPublishOrderOfPlay",Mc="updateInContextMatchUp",Rc={ADD_DRAW_DEFINITION:nc,ADD_MATCHUPS:rc,ADD_PARTICIPANTS:ic,ADD_SCALE_ITEMS:ac,ADD_VENUE:oc,AUDIT:sc,DELETE_PARTICIPANTS:cc,DELETE_VENUE:uc,DELETED_DRAW_IDS:dc,DELETED_MATCHUP_IDS:pc,MODIFY_DRAW_DEFINITION:lc,MODIFY_DRAW_ENTRIES:mc,MODIFY_EVENT_ENTRIES:fc,MODIFY_MATCHUP:hc,MODIFY_PARTICIPANTS:gc,MODIFY_POSITION_ASSIGNMENTS:Ic,MODIFY_SEED_ASSIGNMENTS:Uc,MODIFY_TOURNAMENT_DETAIL:Sc,MODIFY_VENUE:yc,MUTATIONS:vc,PUBLISH_EVENT_SEEDING:Tc,PUBLISH_EVENT:wc,PUBLISH_ORDER_OF_PLAY:Pc,UNPUBLISH_EVENT_SEEDING:bc,UNPUBLISH_EVENT:Dc,UNPUBLISH_ORDER_OF_PLAY:Nc,UPDATE_INCONTEXT_MATCHUP:Mc};function Ac(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 Ec({drawDefinition:t,tournamentId:e,matchUps:n,eventId:r}){return t&&Ac(t),cr({payload:{matchUps:n,tournamentId:e,eventId:r},topic:rc}),{...E}}function Cc({drawDefinition:t,tournamentId:e,matchUpIds:n,eventId:r,action:i}){t&&Ac(t),cr({topic:pc,payload:{tournamentId:e,matchUpIds:n,eventId:r,action:i}});for(const t of n)pr({key:t});return{...E}}function Oc({drawDefinition:t,tournamentId:e,structureId:n,context:r,eventId:i,matchUp:a}){if(!a)return console.log(zt),{error:zt};if(t){kc({drawDefinition:t,structureIds:n?[n]:void 0,tournamentId:e,eventId:i})}return cr({topic:hc,payload:{matchUp:a,tournamentId:e,context:r},key:a.matchUpId}),{...E}}function Fc({tournamentId:t,eventId:e,drawDefinition:n}){return n?(Ac(n),cr({payload:{drawDefinition:n,tournamentId:t,eventId:e},topic:nc,key:n.drawId}),{...E}):(console.log(j),{error:j})}function kc({drawDefinition:t,tournamentId:e,structureIds:n,eventId:r}){return t?(Ac(t,n),cr({payload:{tournamentId:e,eventId:r,drawDefinition:t},topic:lc,key:t.drawId}),{...E}):{error:j}}function _c({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 cr({payload:{tournamentId:e,eventId:r,drawId:t.drawId,structureId:a,seedAssignments:i},topic:Uc,key:t.drawId}),kc({structureIds:[a],drawDefinition:t,tournamentId:e,eventId:r}),{...E}}function xc({drawDefinition:t,tournamentId:e,structure:n,event:r}){if(!t)return{error:j};if(!n)return{error:yt};const i=tc({structure:n}),a=n.structureId,o=t.drawId,s=r?.eventId;return cr({topic:Ic,payload:{positionAssignments:i,tournamentId:e,structureId:a,eventId:s,drawId:o},key:a}),kc({structureIds:[a],drawDefinition:t,tournamentId:e,eventId:s}),{...E}}function Lc({tournamentRecord:t,drawDefinition:e,resetEntries:n,event:r}){if(!e)return{error:j};const i=e.structures?.find((t=>t.stage===Xo));if(!i)return{error:Ut};const a=i.matchUps?.map((({matchUpId:t})=>t))||[];return i.positionAssignments=[],i.seedAssignments=[],i.matchUps=[],Cc({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:a,drawDefinition:e}),n&&(e.entries=e.entries.filter((t=>t.entryStage!==Xo))),kc({tournamentId:t?.tournamentId,eventId:r?.eventId,drawDefinition:e,structureIds:[i.structureId]}),{...E}}function Bc({drawPositions:t,structure:e}){if([Qo,Jo].includes(e.stage)&&1===e.stageSequence)return;const{positionAssignments:n}=tc({structure:e}),r=n?.filter((({drawPosition:e})=>t?.includes(e)));r?.forEach((t=>{Cr({element:t,extension:{name:Ga,value:!0}})}))}function Vc({drawDefinition:t,positionAction:e}){const{extension:n}=Fr({name:La,element:t}),r=Array.isArray(n?.value)?n?.value??[]:[];if(!r?.length){const e=t.structures.find((t=>t.stage===Jo));if(e){const t=tc({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})}}Cr({element:t,extension:{name:La,value:r.concat(e)}})}function jc({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 Gc(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 qc({matchUpStatus:t}){return $o.includes(t)}function $c({matchUpStatus:t}){return Wo.includes(t)}function Wc({matchUpStatus:t,winningSide:e,tieMatchUps:n,sides:r,score:i}){const a=r?.find((({participantId:t})=>t)),o=n?.filter(Wc)?.length;return Gc({score:i})||o||e&&a||t&&function({matchUpStatus:t}){return zo.includes(t)}({matchUpStatus:t})&&![Eo,Vo,Fo].includes(t)}const Hc="SINGLES",zc="SINGLES",Yc="DOUBLES",Kc="DOUBLES",Jc="TEAM",Qc="TEAM",Zc={SINGLES_MATCHUP:Hc,SINGLES:zc,DOUBLES_MATCHUP:Yc,DOUBLES:Kc,TEAM_MATCHUP:Jc,TEAM:Qc};function Xc(t){const{sides:e,matchUpType:n}=t||{},r=t.potentialParticipants?.length?t.potentialParticipants.flat().map((t=>n===Kc?t?.individualParticipantIds||[]:t.participantId)).flat():[],i=(e||[]).map((t=>n===Kc&&(t?.participant?.individualParticipantIds||[])||t?.participantId&&[t.participantId]||[])).flat();return{individualParticipantIds:i.concat(r).flat(),enteredIndividualParticipantIds:i,potentialIndividualParticipantIds:r}}function tu(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}const eu="SIGN_IN_STATUS",nu="SIGNED_OUT",ru="SIGNED_IN",iu="TEAM",au="INDIVIDUAL",ou="GROUP",su="PAIR",cu="TEAM",uu={TEAM_PARTICIPANT:iu,INDIVIDUAL:au,GROUP:ou,TEAM:cu,PAIR:su},du={INDIVIDUAL:au,GROUP:ou,PAIR:su,TEAM:cu,SIGN_IN_STATUS:eu,SIGNED_OUT:nu,SIGNED_IN:ru};function pu({participantsProfile:t,participants:e=[],deepCopy:n}){const r=new Map,i=!1!==n?mi(e,t?.convertExtensions,!0):e,a=i.filter((t=>t.participantType===cu)),o=i.filter((t=>t.participantType===ou)),s=i.filter((t=>t.participantType===su));return i.forEach((t=>{if(t.participantType===au){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 lu({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 mu({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}=Qs({drawDefinition:r,structureId:a}),{positionAssignments:p}=tc({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=lu({groupedOrder:s,roundPositionsCount:h.length}),T=v?.length||1;if(T<=h.length){const t=N(h,f/T);o===fs&&t.forEach((t=>t.reverse())),S=v?.length&&v?.map((e=>t[e-1])).flat()||S}o===ms?y=S[I-1]:o===fs?((!v?.length||T>h.length)&&(I=m.length+1-I),y=S[I-1]):o===ls&&Xn()&&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}=Fr({element:b,name:Ga});if(t?.value)return{disabledDrawPosition:D}}return{matchUp:P,targetDrawPosition:D,matchUpDrawPositionIndex:U}}function fu({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[gs,Is].includes(i?.linkType)&&!i?.source?.roundNumber?Nr({result:{error:Nn},stack:"getTargetLink",context:i}):i}function hu({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 gu({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}=Qs({structureId:a?.structureId,drawDefinition:r}),s=o?.finishingPosition;return s===Hs?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}=hu({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=fu({source:c,linkType:gs}),d=fu({linkCondition:Us,linkType:Is,source:c});let p=fu({source:c,linkType:Is});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!==ps&&t.find((({matchUpId:t})=>t===a)),S=o&&f!==ps&&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!==ps&&({matchUpDrawPositionIndex:v,targetDrawPosition:y,matchUp:S}=mu({targetLink:p,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:b,drawDefinition:n}));l&&h!==ps&&({matchUpDrawPositionIndex:U,targetDrawPosition:I,matchUp:g}=mu({targetLink:d,sourceRoundMatchUpCount:N,inContextDrawMatchUps:t,sourceRoundPosition:b,drawDefinition:n}));u&&!w&&m!==ps&&({matchUpDrawPositionIndex:P,targetDrawPosition:T,matchUp:w}=mu({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 br({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 Iu(t){if(!Ui(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 Uu(t){return!!Array.isArray(t)&&t.every(Iu)}function Su({matchUps:t=[],interpolate:i}){if(!Uu(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===Qc))?r.filter((({matchUpType:t})=>t===Qc)):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]=br({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=>!Ho.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 yu({drawDefinition:t,inContextDrawMatchUps:r}){const i={};return r.forEach((a=>{const{matchUpId:o,structureId:s,drawPositions:c=[]}=a,{structure:u}=Qs({drawDefinition:t,structureId:s});if(u?.finishingPosition===Ws){const{roundNumber:t}=a,r=t&&n(t)+1,i=u.matchUps??[],{roundMatchUps:o}=Su({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=gu({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=wu({upcomingMatchUp:n});let u=wu({upcomingMatchUp:s});if(a.matchUpStatus!==No&&s?.matchUpStatus===No){const{matchUp:e}=vu({matchUp:s,drawDefinition:t,inContextDrawMatchUps:r})||{};u=e&&wu({upcomingMatchUp:e})||u}const p=a.schedule?.timeAfterRecovery;if(p){if(c?.schedule?.scheduledTime){Qr(c.schedule.scheduledTime)<Qr(p)&&(i[c.matchUpId]=a.matchUpId,c.schedule.scheduleConflict=a.matchUpId)}if(u?.schedule?.scheduledTime){Qr(u.schedule.scheduledTime)<Qr(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===Us,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=yo(n?.sides),a=yo(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 vu({matchUp:t,drawDefinition:e,inContextDrawMatchUps:n}){const{matchUpId:r,matchUpStatus:i,structureId:a}=t||{};if(!t||!a||t?.matchUpStatus===Bo)return{matchUp:t};if(i===No){let i;if(t.winnerMatchUpId)i=n.find((({matchUpId:e})=>e===t.winnerMatchUpId));else{const t=gu({inContextDrawMatchUps:n,drawDefinition:e,matchUpId:r});({winnerMatchUp:i}=t?.targetMatchUps||{})}return vu({matchUp:i,drawDefinition:e,inContextDrawMatchUps:n})}return{matchUp:void 0}}function wu(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 Tu({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===xa))?.value;if(i)for(const n of Object.keys(i))(t?e.includes(n):!e.length||e.includes(n))&&(o[n]=mi(i[n],!1,!0))}}function Pu({policyTypes:t=[],tournamentRecord:e,drawDefinition:n,structure:r,event:i}){if(!Array.isArray(t))return{error:Kt};const{appliedPolicies:a}=Tu({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 Du="WALKOVER",bu="RETIRED",Nu="COMPETITIVE",Mu="ROUTINE",Ru="DECISIVE",Au="winRatio",Eu={[ma]:{policyName:"Competitive Bands Default",profileBands:{[Ru]:20,[Mu]:50}}};function Cu({policyDefinitions:t,tournamentRecord:e,contextProfile:n,drawDefinition:r,event:i}){const a={policies:{}};if(!n)return a;const o=Pu({tournamentRecord:e,drawDefinition:r,event:i}).policyDefinitions;if(n.withCompetitiveness){const e=t?.[ma]??o?.[ma]??Eu[ma];a.policies[ma]=e}return a}function Ou({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&&[Zo,ts].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 Fu({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 ku({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(mi(t,!0,!0),{containerStructureId:n,structureId:e,structureName:a}))):i})).flat();return(i?.matchUps||[]).concat(...a)}function _u({drawDefinition:t,attributes:e}){let{extension:n}=Fr({element:t,name:Wa});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:Wa,value:r},Aa({drawDefinition:t,extension:n}),{entryProfile:r}}function xu({drawDefinition:t}){const{extension:e}=Fr({element:t,name:Wa});return{entryProfile:e?.value||{}}}const Lu="ALTERNATE",Bu="CONFIRMED",Vu="DIRECT_ACCEPTANCE",ju="FEED_IN",Gu="JUNIOR_EXEMPT",qu="LUCKY_LOSER",$u="ORGANISER_ACCEPTANCE",Wu="QUALIFIER",Hu="SPECIAL_EXEMPT",zu="UNGROUPED",Yu="UNPAIRED",Ku="WILDCARD",Ju="WITHDRAWN",Qu=[Bu,Vu,Gu,$u,Hu],Zu=[ju,qu,Wu],Xu=[Bu,Vu,ju,Gu,$u,Hu,Ku],td=[Bu,Vu,Gu,qu,Wu,$u,Hu,Ku],ed=[Lu,Bu,Vu,ju,Gu,qu,$u,Wu,"REGISTERED",Hu,zu,Yu,Ku,Ju],nd={ALTERNATE:Lu,CONFIRMED:Bu,DIRECT_ACCEPTANCE:Vu,DIRECT_ENTRY_STATUSES:Xu,DRAW_SPECIFIC_STATUSES:Zu,EQUIVALENT_ACCEPTANCE_STATUSES:Qu,FEED_IN:ju,JUNIOR_EXEMPT:Gu,LUCKY_LOSER:qu,ORGANISER_ACCEPTANCE:$u,QUALIFIER:Wu,SPECIAL_EXEMPT:Hu,STRUCTURE_SELECTED_STATUSES:td,UNGROUPED:zu,UNPAIRED:Yu,VALID_ENTRY_STATUSES:ed,WILDCARD:Ku,WITHDRAWN:Ju};function rd({stage:t,drawDefinition:e}){const{entryProfile:n}=xu({drawDefinition:e}),r=Object.keys(n).includes(t);if(!r&&es.includes(t)){return _u({drawDefinition:e,attributes:[{[t]:{drawSize:void 0,alternates:!0}}]}),!0}return r}function id({stage:t,drawDefinition:e,entryStatus:n}){return e.entries.reduce(((e,r)=>r.entryStage===t&&r.entryStatus===n?e+1:e),0)}function ad({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=Fr({name:to,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===ts){const{playoffEntries:i,error:a}=function({provisionalPositioning:t,drawDefinition:n,structureId:r}){const i=[],a=(n.links??[]).find((t=>t.linkType===hs&&t.target.structureId===r));if(a){const{finishingPositions:r,structureId:o}=a.source,{structure:s}=Qs({drawDefinition:n,structureId:o});if(s?.structureType===ds){(s.structures??[]).forEach((n=>{const a=n.positionAssignments??[],{structureId:o}=n,s=o,c=Object.assign({},...a.map((t=>{const{participantId:e}=t,n=Fr({element:t,name:ao}).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:ts,entryStatus:ju,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 od({provisionalPositioning:t,returnAllProxies:e,drawDefinition:n,structureId:r,structure:i}){let a,o=[];i||({structure:i,error:a}=Qs({drawDefinition:n,structureId:r}));const s=tc({structure:i}).positionAssignments;if(a||!i)return{seedAssignments:[],error:Ut};r||(r=i.structureId);const{stage:c,stageSequence:u}=i,d=c===ts&&n&&ad({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 sd=(t,e)=>(t||0)+(e||0);function cd(t,e){const n=Array.isArray(t)?t[0]:t;return isNaN(n)&&Du||n<=e[Ru]&&Ru||n<=e[Mu]&&Mu||Nu}function ud({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(sd)&&(n[r[0]>r[1]?0:1]+=1),{sets:e,games:n,score:t}}function dd(t){const e=Math.min(...t.games),n=Math.max(...t.games);return Math.round(e/n*100)}function pd(t){return t.map(dd).sort().map((t=>parseFloat(t.toFixed(2))))}function ld({tournamentRecord:t,drawDefinition:e,policyType:n,structure:r,event:i}){if(!t)return{error:x};const{appliedPolicies:a}=Tu({tournamentRecord:t,drawDefinition:e,structure:r,event:i});return a?.[n]?{policy:a[n]}:{info:ee?.message}}function md({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&&ld({policyType:ma,tournamentRecord:t}).policy,o=e||a?.profileBands||Eu[ma].profileBands,s=pd([ud({score:r})]),c=cd(s,o),u=Array.isArray(s)?s[0]:s;return{...E,competitiveness:c,pctSpread:u}}function fd({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===au)).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 hd="CHECK_IN",gd="CHECK_OUT",Id="SCHEDULE.ASSIGNMENT.VENUE",Ud="SCHEDULE.ALLOCATION.COURTS",Sd="SCHEDULE.ASSIGNMENT.COURT",yd="SCHEDULE.COURT.ORDER",vd="SCHEDULE.DATE",wd="SCHEDULE.ASSIGN.OFFICIAL",Td="SCHEDULE.TIME.SCHEDULED",Pd="SCHEDULE.TIME.START",Dd="SCHEDULE.TIME.STOP",bd="SCHEDULE.TIME.RESUME",Nd="SCHEDULE.TIME.END",Md="SCHEDULE.TIME.MODIFIERS",Rd="TO_BE_ANNOUNCED",Ad="NEXT_AVAILABLE",Ed="FOLLOWED_BY",Cd="AFTER_REST",Od="RAIN_DELAY",Fd=[Rd,Ad,Ed,Cd,Od],kd="SCALE",_d="RATING",xd="RANKING",Ld="SEEDING",Bd="PUBLISH",Vd="PUBLIC",jd="STATUS",Gd={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:Fd,AFTER_REST:Cd,ALLOCATE_COURTS:Ud,ASSIGN_COURT:Sd,ASSIGN_OFFICIAL:wd,ASSIGN_VENUE:Id,CHECK_IN:hd,CHECK_OUT:gd,COMPLETED_DATE:"COMPLETED.DATE",COURT_ORDER:yd,ELIGIBILITY:"ELIGIBILITY",END_TIME:Nd,FOLLOWED_BY:Ed,MEDICAL:"MEDICAL",MODIFICATION:"MODIFICATION",NEXT_AVAILABLE:Ad,NOT_BEFORE:"NOT_BEFORE",OTHER:"other",PENALTY:"PENALTY",PUBLIC:Vd,PUBLISH:Bd,RANKING:xd,RATING:_d,RAIN_DELAY:Od,REGISTRATION:"REGISTRATION",RESUME_TIME:bd,RETRIEVAL:"RETRIEVAL",SCALE:kd,SCHEDULE:"SCHEDULE",SCHEDULED_DATE:vd,SCHEDULED_TIME:Td,SEEDING:Ld,START_TIME:Pd,STATUS:jd,STOP_TIME:Dd,SUSPENSION:"SUSPENSION",TIME_MODIFIERS:Md,TO_BE_ANNOUNCED:Rd};function qd({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}=fd({matchUp:t}),i=(t.timeItems??[]).filter((t=>t?.itemType&&[hd,gd].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===hd));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 $d(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 Wd(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 Hd({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 zd({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}=ld({policyType:va,tournamentRecord:t,event:r}),a=t?Fr({element:t,name:no}).extension:void 0,o=a?.value,s=r&&Fr({name:no,element:r}).extension,c=s?.value;return{scheduleTiming:{tournamentScheduling:o,eventScheduling:c,categoryName:e,categoryType:n,policy:i}}}const Yd="SINGLES",Kd="SINGLES",Jd="DOUBLES",Qd="DOUBLES",Zd="TEAM",Xd="TEAM",tp={AGE:"AGE",BOTH:"BOTH",DOUBLES:Jd,DOUBLES_EVENT:Qd,RATING:"RATING",SINGLES:Yd,SINGLES_EVENT:Kd,TEAM_EVENT:Xd,TEAM:Zd},ep="DOUBLES_SINGLES",np="SINGLES_DOUBLES",rp="total",ip="participantConflict",ap="matchUpConflict",op="ISSUE_IDS",sp="CONFLICT",cp="WARNING",up="ERROR",dp="ISSUE",pp="STATE",lp={SINGLES_DOUBLES:np,DOUBLES_SINGLES:ep,TOTAL:rp,CONFLICT_MATCHUP_ORDER:ap,CONFLICT_PARTICIPANTS:ip,SCHEDULE_ISSUE_IDS:op,SCHEDULE_CONFLICT:sp,SCHEDULE_WARNING:cp,SCHEDULE_ERROR:up,SCHEDULE_ISSUE:dp,SCHEDULE_STATE:pp};function mp({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:n,matchUpFormat:r,categoryName:i,categoryType:a,eventType:o,event:s}){if(!n)return{error:x};o=o??s?.eventType??Kd;const c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=zd({tournamentRecord:n,categoryName:i,categoryType:a,event:s});return fp({eventType:o,timingDetails:{...u,matchUpFormat:r,categoryType:a,defaultTiming:c}})}function fp({timingDetails:t,eventType:e}){const n=function({matchUpFormat:t,categoryName:e,categoryType:n,defaultTiming:r,tournamentScheduling:i,eventScheduling:a,policy:o}){return Hd({categoryName:e,categoryType:n,timesBlockArray:[a?.matchUpAverageTimes&&$d({...a,matchUpFormat:t}),i?.matchUpAverageTimes&&$d({...i,matchUpFormat:t}),o?.matchUpAverageTimes&&$d({...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 Hd({categoryName:a,categoryType:o,timesBlockArray:[e?.matchUpRecoveryTimes&&Wd({...e,averageMinutes:n,matchUpFormat:i}),t?.matchUpRecoveryTimes&&Wd({...t,averageMinutes:n,matchUpFormat:i}),s?.matchUpRecoveryTimes&&Wd({...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===Kd?np:ep;return{averageMinutes:i,recoveryMinutes:s,typeChangeRecoveryMinutes:a?.minutes&&(o?.includes(c)&&a.minutes[c]||s)}}function hp(t){return t.createdAt?new Date(t.createdAt).getTime():0}function gp({visibilityThreshold:t,timeItems:e,itemType:n}){const r=e.filter((e=>e&&e.itemType===n&&(!t||hp(e)<new Date(t).getTime()))).sort(((t,e)=>hp(t)-hp(e))).pop(),i=r&&hp(r);return{itemValue:r?.itemValue,timeStamp:i}}function Ip({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=gp({timeItems:r?.timeItems||[],itemType:Td,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{scheduledTime:i}:n}function Up({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=gp({timeItems:r?.timeItems||[],itemType:vd,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{scheduledDate:i}:n}function Sp({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=gp({timeItems:r?.timeItems||[],itemType:Ud,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{allocatedCourts:mi(i,!1,!0)}:n}function yp({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=gp({timeItems:r?.timeItems||[],itemType:Sd,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{courtId:i}:n}function vp({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=gp({timeItems:r?.timeItems||[],itemType:Id,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{venueId:i}:n}function wp(){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 Tp(t){const{disableNotice:e,venue:n,context:r}=t;if("object"!=typeof n)return{error:Nn};const i=tu(t);let a;n.venueId||(n.venueId=wp());for(const t of Object.values(i)){const e=Pp({disableNotice:!0,tournamentRecord:t,context:r,venue:n});if(e?.error)return e;a=e.venue}return e||cr({topic:oc,payload:{venue:n}}),br({...E,venue:a})}function Pp({tournamentRecord:t,disableNotice:e,context:n,venue:r}){if(!t)return{error:x};if(!r)return{error:ae,info:"missing venue"};t.venues||(t.venues=[]),r.venueId||(r.venueId=wp());if(t.venues.reduce(((t,e)=>t||e.venueId===r.venueId),void 0))return{error:nn};if(n){Cr({element:r,extension:{value:n,name:Ba}})}return t.venues.push(r),e||cr({payload:{venue:r,tournamentId:t.tournamentId},topic:oc}),{...E,venue:mi(r)}}function Dp({tournamentRecords:t,tournamentRecord:e,venueId:n}){if(!e)return{error:x};if(!n)return{error:an};const r=(e.venues??[]).reduce(((t,e)=>e.venueId===n?e:t),void 0);if(!r&&t){const i=(ho({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(const a of i){const i=Dp({tournamentRecord:t[a],venueId:n});if(i.success&&i.venue)return Tp({tournamentRecord:e,venue:i.venue}),{...E,venue:r}}}return r?{...E,venue:r}:{error:rn}}function bp({convertExtensions:t,...e}){const{tournamentRecords:n,tournamentRecord:r,venueId:i}=e;return mi(Dp({tournamentRecords:n,tournamentRecord:r,venueId:i}),t,!0)}function Np({tournamentRecords:t,tournamentRecord:e,courtId:n}){if(!e)return{error:x};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=(ho({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(const o of a){const a=Np({tournamentRecord:t[o],courtId:n});if(a.success)return a.venue&&Tp({tournamentRecord:e,venue:a.venue}),{...E,court:r,venue:i}}}return Nr({result:{error:tn},stack:"findCourt"})}function Mp(t){return mi(Np(t),!1,!0)}function Rp({tournamentRecord:t,internalUse:e,courtId:n}){if(!t)return{error:x};if(!n)return{error:ie};const r=Np({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:mi(i,!1,e)}}function Ap({tournamentRecord:t,venueId:e}){if(!t)return{error:x};if(!e)return{error:an};const n=Dp({tournamentRecord:t,venueId:e});if(n.error)return n;const r=(n.venue?.courts??[]).map((e=>(({courtInfo:t})=>({...t}))(Rp({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:mi(a,!1,!0)}}function Ep({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=gp({timeItems:r?.timeItems||[],itemType:Md,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{timeModifiers:i}:n}function Cp(t){if(_r.test(t)){const e=qr();return new Date(`${e}T${t}`)}return new Date(t)}function Op(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 Fp({event:t,eventId:e}){if(!t)return{error:Tt};const n=Fr({name:Ha,element:t}),r=n?.extension,i=e?mi(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 kp(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&&Fp({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,...Nr({result:{error:Pt},stack:i})}}return{event:void 0,drawDefinition:void 0,...Nr({result:{error:q},context:{drawId:r,eventId:n},stack:i})}}function _p(t){let e=t.event,n=t.matchUpType;const{scheduleVisibilityFilters:r,afterRecoveryTimes:i,tournamentRecord:a,usePublishState:o,scheduleTiming:s,matchUpFormat:c,publishStatus:u,matchUp:d}=t;if(!d)return{error:zt};if(i&&!d.matchUpType&&!t.matchUpType&&(e||a)&&d.drawId){let r=e?.drawDefinitions?.find((t=>t.drawId===d.drawId));!r&&a&&({drawDefinition:r,event:e}=kp({tournamentRecord:a,drawId:d.drawId}));const i=d.structureId&&r?.structures?.find((({structureId:t})=>t===d.structureId));n=t.matchUpType||i?.matchUpType||r?.matchUpType||e?.eventType!==Zd&&e?.eventType}const{milliseconds:p,time:l}=function({matchUp:t}){if(!t)return{error:zt};if(!t.timeItems)return{error:fn};const e=t.timeItems.filter((t=>[Pd,Dd,bd,Nd].includes(t?.itemType))).sort(((t,e)=>Cp(t.itemValue).getTime()-Cp(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 Pd:n=0;break;case Nd:if(t.lastValue&&[Pd,bd].includes(t.lastType)){const r=Cp(e.itemValue).getTime()-Cp(t.lastValue).getTime();n=t.milliseconds+r}else n=t.milliseconds;break;case Dd:if([Pd,"SCHECULE.TIME.RESUME"].includes(t.lastType)){const r=Cp(e.itemValue).getTime()-Cp(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([Pd,bd].includes(n.lastType)){const t=(new Date).getTime()-Cp(n.lastValue).getTime();n.milliseconds+=t}return{milliseconds:n.milliseconds,time:Op(n.milliseconds),relevantTimeItems:e}}({matchUp:d}),{startTime:m}=function({matchUp:t}){const e=t=>t.createdAt?new Date(t.createdAt).getTime():0,n=(t?.timeItems||[]).reduce(((t,n)=>{const r=n.itemType===Pd&&n;return r&&(!t||e(r)<e(t))?r:t}),void 0),r=n?.itemValue;return{startTime:r}}({matchUp:d}),{endTime:f}=function({matchUp:t}){const e=t=>t.createdAt?new Date(t.createdAt).getTime():0,n=(t?.timeItems||[]).reduce(((t,n)=>{const r=n.itemType===Nd&&n;return r&&(!t||e(r)>e(t))?r:t}),void 0),r=n?.itemValue;return{endTime:r}}({matchUp:d});let h;const{visibilityThreshold:g,eventIds:I,drawIds:U}=r??{};if(I&&!I.includes(d.eventId)||U&&!U.includes(d.drawId))h=br({milliseconds:p,startTime:m,endTime:f,time:l});else{const t={matchUp:d,visibilityThreshold:g},{allocatedCourts:e}=Sp(t),{scheduledTime:r}=Ip(t);let{scheduledDate:o}=Up(t);const{venueId:u}=vp(t),{courtId:I}=yp(t),{courtOrder:U}=function({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:i,timeStamp:a}=gp({timeItems:r?.timeItems||[],itemType:yd,visibilityThreshold:t});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{courtOrder:i}:n}(t),{timeModifiers:S}=Ep(t);let y,v,w,T,P;const D=d.matchUpType??n;if(s&&r&&i&&D){const t={matchUpFormat:d.matchUpFormat??c,...s};({averageMinutes:v=0,recoveryMinutes:w=0,typeChangeRecoveryMinutes:T=0}=fp({timingDetails:t,eventType:D})),(v||w)&&(y=f?ci(Xr(f),w):ci(r,v+w)),T&&(P=f?ci(Xr(f),T):ci(r,v+T))}!o&&r&&(o=ti(r));const b=Br({scheduledDate:o,scheduledTime:r}),N={},M=(a&&u&&Ap({tournamentRecord:a,venueId:u}))?.venueData||{};u&&(N[u]=M);const{venueName:R,venueAbbreviation:A,courtsInfo:E}=M,C=I&&E?.find((t=>t.courtId===I)),O=C?.courtName;for(const t of e||[]){if(!a)break;t.venueId&&!N[t.venueid]&&(N[t.venueId]=Ap({venueId:t.venueId,tournamentRecord:a})?.venueData);const e=N[t.venueId];t.venueName=e?.venueName;const n=e?.courtsInfo?.find((e=>e.courtId===t.courtId));t.courtName=n?.courtName}h=br({typeChangeTimeAfterRecovery:P,timeAfterRecovery:y,scheduledDate:o,scheduledTime:r,isoDateString:b,allocatedCourts:e,timeModifiers:S,venueAbbreviation:A,venueName:R,venueId:u,courtOrder:U,courtName:O,courtId:I,typeChangeRecoveryMinutes:T,recoveryMinutes:w,averageMinutes:v,milliseconds:p,startTime:m,endTime:f,time:l})}const{scheduledDate:S}=Up({matchUp:d}),{scheduledTime:y}=Ip({matchUp:d});if(o&&u?.displaySettings?.draws){const t=u.displaySettings.draws,e=(t?.[d.drawId]??t?.default)?.scheduleDetails;if(e){const t=(e.find((t=>S&&t.dates?.includes(S)))??e.find((t=>!t.dates?.length)))?.attributes;if(t){h=pa({source:h,template:Object.assign({},...Object.keys(h).map((t=>({[t]:!0}))),t)})}}}return{schedule:h,endDate:d.matchUpStatus&&Ho.includes(d.matchUpStatus)&&(ti(f)||ti(S)||ti(y))||void 0}}function xp(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 Lp({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 Bp({drawDefinition:t,structure:e,matchUp:n,event:r}){return{tieFormat:Lp({item:n,drawDefinition:t,structure:e,event:r})||Lp({item:e,drawDefinition:t,structure:e,event:r})||xp(t)||xp(r)}}function Vp(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 jp="timed",Gp="NOAD",qp="SET",$p={S:"normal",F:"final"};function Wp(t){if("string"==typeof t){const e=t.startsWith("T")&&jp||t.startsWith(qp)&&qp||"";if(e===jp){const e=Kp(t);if(e)return{simplified:!0,setFormat:e,bestOf:1}}if(e===qp)return function(t){const e=t.split("-"),n=Qp(e[0].slice(3)),r=1===n||n%2!=0?n:void 0,i=1!==n&&n%2==0?n:void 0,a=e&&Hp(e[1]),o=e&&Hp(e[2]),s=a&&a.timed||o&&o.timed,c=r&&r<6||s&&i,u=!e[2]||o,d=a,p=br({setFormat:a,exactly:i,bestOf:r});o&&(p.finalSetFormat=o);if(c&&d&&u)return p}(t)}}function Hp(t){if(":"===t?.[1]){const e=t.split(":"),n=$p[e[0]],r=e[1];if(n&&r){if(r.startsWith("TB")){const t=Yp(r);return!1!==t&&("object"==typeof t?{tiebreakSet:t}:void 0)}if(r.startsWith("T"))return Kp(r);const e=t.match(/^[FS]:(\d+)([A-Za-z]*)/),n=e&&Jp(e[2])||!1,i=!e?.[2]||n,a=e?Qp(e[1]):void 0,o=zp(r),s=!1!==o,c=s&&o||a,u=Yp(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 zp(t,e=!0){const n=t?.indexOf("@")>0&&t.split("@");if(n){return(e?Qp(n[1]):n[1])||!1}}function Yp(t){if(t){if(t.startsWith("TB")){const e=zp(t,!1),n=t.match(/^TB(\d+)([A-Za-z]*)/),r=n?.[1],i=n&&Jp(n[2]),a=!n?.[2]||i,o=Qp(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 Kp(t){const e=t.slice(1),n=e.match(/^(\d+)(@?[A-Za-z]*)/),r=Qp(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 Jp(t){return t&&t.indexOf(Gp)>=0}function Qp(t){return isNaN(Number(t))?0:Number(t)}function Zp({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 Xp({tournamentParticipants:t,tournamentRecord:e,participantIds:n}){const r="getPairedParticipant";if(!t&&!e)return{error:x};if(!Array.isArray(n)||n.length>2)return{error:Pe};if(!n.length)return Nr({result:{error:Fe},stack:r});const i=(t=t??e?.participants??[]).filter((t=>t.participantType===su&&P(n,t.individualParticipantIds).length===n.length&&t.individualParticipantIds.length===n.length)),a=i[0];if(!a)return Nr({result:{error:Ee},stack:r});const o=mi(i.slice(1),!1,!0);return{participant:mi(a),duplicatedPairParticipants:o,...E}}function tl({drawDefinition:t,participantId:e}){if("object"!=typeof t)return{error:j};if("string"!=typeof e)return{error:Ae};const{extension:n}=Fr({element:t,name:Ya});return{lineUp:(n?.value||{})[e]}}function el({roundsNotPowerOf2:t,drawDefinition:e,structure:n,matchUps:r}){if(!n)return!1;r=r??n.matchUps??[],t=t??Su({matchUps:r}).roundsNotPowerOf2;const i=!!n.positionAssignments?.find((({drawPosition:t})=>t))||!!r?.find((({drawPositions:t})=>t?.length));return(!e?.drawType||e.drawType!==Ns)&&!n?.structures&&t&&i}function nl({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===Xo||t?.drawType&&t.drawType!==Ss||r||i)}const rl={[Ua]:{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:{[Jo]:"",[ts]:"P",[Qo]:"Q",[Zo]:"C"}}};function il(t){const e=na(t,[{[qi]:!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===au&&zc||i===su&&Kc||i===cu&&cu||void 0}return{matchUpType:r}}function al(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:M=!0,filterMatchUpTypes:R=!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):[],_=Array.isArray(m)?m.filter(Boolean):[],x=Array.isArray(p)?p.filter(Boolean):[],L=Array.isArray(s)?s.filter(Boolean):[],B=Array.isArray(l)&&M?l.filter(Boolean):[],V=Array.isArray(y)&&R?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!==Jc&&!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(_.length&&(!t.roundName||!_.includes(t.roundName)))return!1;if(x.length&&(!t.roundNumber||!x.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}=Ip({matchUp:t}),{scheduledDate:n}=Up({matchUp:t}),r=ti(e)||n;if(!$.find((t=>pi(t,r))))return!1}if(j.length){const{courtId:e}=yp({matchUp:t}),{allocatedCourts:n}=Sp({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}=vp({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 ol({drawPositionCollectionAssignment:t,sideNumberCollectionAssignment:e,positionAssignments:n,displaySideNumber:r,seedAssignments:i,drawPosition:a,isFeedRound:o,sideNumber:s}){const c=n.find((t=>t.drawPosition&&t.drawPosition===a)),u=a&&t,d=s&&e,p=u?u[a]?.participantId:c?.participantId,l=c?function({displaySideNumber:t,seedAssignments:e,participantId:n,assignment:r,sideNumber:i}){const a={drawPosition:r.drawPosition,displaySideNumber:t,sideNumber:i};if(n){const t=function({seedAssignments:t,participantId:e}){return t?.find((t=>!t.seedProxy&&t.participantId===e))}({seedAssignments:e,participantId:n});Object.assign(a,t,{participantId:n})}else r.bye&&Object.assign(a,{bye:!0});r.qualifier&&Object.assign(a,{qualifier:!0});return a}({displaySideNumber:r,seedAssignments:i,participantId:p,assignment:c,sideNumber:s}):{...d?.[s]};if(o&&(1===s?Object.assign(l,{participantFed:!0}):Object.assign(l,{participantAdvanced:!0})),a&&u){const t=u[a]?.teamParticipant,e=u[a]?.participant,n=u[a]?.substitutions;e&&(l.participant=e),n&&(l.substitutions=n),t&&(l.teamParticipant=t)}return l}const sl="ANY",cl="MALE",ul="MIXED",dl="OTHER",pl="FEMALE",ll={ANY:sl,MALE:cl,FEMALE:pl,MIXED:ul,OTHER:dl};function ml({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):[],_=Array.isArray(h?.drawIds)?h?.drawIds.filter(Boolean):[],x=!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||!_?.length||_.includes(S.drawId);if(!x||!L||!B)return{collectionPositionMatchUps:C,roundMatchUps:O,matchUps:[]};U&&!f&&(f=Cu({tournamentRecord:c,contextProfile:U,drawDefinition:S}));const{appliedPolicies:V}=Tu({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=Fu({drawDefinition:S,structure:D}));const{positionAssignments:z,allPositionsAssigned:Y}=ec({structure:D}),K=!H||Y,{seedAssignments:J}=od({provisionalPositioning:i,drawDefinition:S,structure:D});u=u??J;const{roundOffset:Q,structureId:Z,structureName:X,stage:tt,stageSequence:et}=D,{drawId:nt,drawName:rt,drawType:it}=S??{};T=T||S&&Ou({drawDefinition:S}).exitProfiles;const at=T?.[Z],ot=at?.length&&(at[0].split("-").map((t=>parseInt(t))).reduce(((t,e)=>t+e))||0),st=!!D.structures;let ct=ku({matchUpsMap:P,structureId:Z,inContext:A});const ut=G?.[Ua],dt=function({roundNamingPolicy:t,drawDefinition:e,structure:n,matchUps:r}){const{roundProfile:i,roundMatchUps:a}=Su({matchUps:r}),{structureAbbreviation:o,stage:s}=n,c=nl({structure:n}),u=el({structure:n}),d=n.structures,p={},l=rl[Ua],m=n.stage===Qo,f=m?Math.max(...(e?.structures??[]).filter((t=>t.stage===Qo)).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!==Jo?s[0]:"",T=t?.stageConstants||l.stageConstants,P=`${g}${s&&T?.[s]||w}${h}`,D=i?Object.keys(i):[],b=m&&T?.[Qo]?`${T?.[Qo]}-`:"";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=al({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}=Qs({drawDefinition:t,structureId:e});if(r?.stage!==Zo)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]:Su({matchUps:ku({structureId:t,matchUpsMap:n})}).roundProfile})))),c=ku({matchUpsMap:n,structureId:e}),{roundProfile:u}=Su({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=lu({roundPositionsCount:g.length,groupedOrder:i}),U=I?.length||1;if(U<=h){const t=N(g,p.length/U);r===fs&&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!==fs||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]=Vp(t))}))})),{sourceDrawPositionRanges:d}}({drawDefinition:S,matchUpsMap:P,structureId:Z}),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=ku({matchUpsMap:i,structureId:r});if(({roundProfile:n}=Su({matchUps:t})),!n)return{error:ae}}const a=(Math.min(...n?.[1]?.drawPositions??[])||1)-1,o=Object.keys(n),s=Object.assign({},...(o||[]).map((t=>{const r=n?.[t]?.matchUpsCount,i=n?.[1]?.drawPositions??[],s=N(i,i.length/r),c=s.map(Vp),u=s.map((t=>t.map((t=>t-a)))).map(Vp),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(Vp).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}})));return{drawPositionsRanges:s}}({drawDefinition:S,roundProfile:lt,matchUpsMap:P,structureId:Z}).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=al({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=al({matchUps:ct,...h,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(h?.matchUpTypes||h?.matchUpIds)&&(ct=al({matchUpTypes:h.matchUpTypes,matchUpIds:h.matchUpIds,matchUps:ct})),(h?.matchUpTypes||h?.matchUpIds||A)&&(O=Su({matchUps:ct}).roundMatchUps??[]),Bp({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=Bp({drawDefinition:S,structure:D,matchUp:O,event:F})?.tieFormat,_=k?.collectionDefinitions,x=O.collectionId&&_?.find((t=>t.collectionId===O.collectionId)),L=O.collectionId?x?.matchUpFormat:O.matchUpFormat??D?.matchUpFormat??S?.matchUpFormat??F?.matchUpFormat,B=O.matchUpType||x?.matchUpType||D?.matchUpType||S?.matchUpType||F?.eventType!==Zd&&F?.eventType,V=w?No:O.matchUpStatus,{schedule:j,endDate:G}=_p({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=({attribute:e,lineUp:r,teamParticipant:a})=>{const{assignedParticipantIds:s,substitutions:u}=Zp({collectionPosition:n,collectionId:o,lineUp:r});if(c!==Kc){const t=s?.[0];return t&&{[e]:{participantId:t,teamParticipant:a,substitutions:u}}}if(s?.length<=2){const n=i?.[s[0]]?.pairIdMap?.[s[1]],r=n&&i[n]?.participant||Xp({participantIds:s,tournamentParticipants:t}).participant,o=r?.participantId;return{[e]:{participantId:o,teamParticipant:a,substitutions:u}}}if(s?.length>2)return{[e]:{teamParticipant:a,substitutions:u}}};if(!r?.length){const t=s?.map((t=>{const{teamParticipant:e,sideNumber:n}=t,r=t.lineUp||tl({participantId:e.teamParticipantId,drawDefinition:a})?.lineUp;return u({attribute:n,lineUp:r,teamParticipant:e})})).filter(Boolean)||{};return{sideNumberCollectionAssignment:Object.assign({},...t)}}const d=r?.map((n=>{const r=e.find((t=>t.drawPosition===n))?.participantId,o=s?.find((t=>t?.drawPosition===n)),c=o?.teamParticipant||r&&i?.[r]?.participant||t?.find((({participantId:t})=>t===r)),d=o?.lineUp||tl({participantId:r,drawDefinition:a})?.lineUp;return u({attribute:n,lineUp:d,teamParticipant:c})})).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...d)}}({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=x?.category?{...v?.category||{},...x.category}:v?.category??F?.category,ht=O.processCodes?.length&&O.processCodes||x?.processCodes?.length&&x?.processCodes||D?.processCodes?.length&&D?.processCodes||S?.processCodes?.length&&S?.processCodes||F?.processCodes?.length&&F?.processCodes||c?.processCodes,gt=U?.withCompetitiveness&&md({...f,matchUp:O}),It=O.finishingPositionRange??d.finishingPositionRange,Ut=t=>br(t,void 0,!0),St={...Ut(v),...Ut({matchUpFormat:O.matchUpType===Zd?void 0:L,tieFormat:O.matchUpType!==Zd?void 0:k,gender:x?.gender??F?.gender,roundOfPlay:tt!==Qo&&p(s)&&s+(Y||0),endDate:O.endDate??G,discipline:F?.discipline,category:ft,finishingPositionRange:It,abbreviatedRoundName:ot,drawPositionsRange:pt,competitiveProfile:gt,structureName:X,stageSequence:et,drawPositions:q,matchUpStatus:V,processCodes:ht,isRoundRobin:A,matchUpTieId:N,preFeedRound:ct,matchUpType:B,roundFactor:ut,roundOffset:Q,structureId:Z,roundNumber:Y,feedRound:st,roundName:at,drawName:rt,drawType:it,schedule:j,drawId:nt,stage:tt}),...mi(Ut(O),!0,!0)};if(L&&O.score?.scoreStringSide1){const t=Wp(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(R(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(M(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=ol({...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,mi({sides:o},!0,!0))}if(a&&St.sides){const t=y?.[Sa],e=e=>{const n=g?.[e]?.participant;return n&&pa({template:t?.participant,source:n})};if(St.sides.filter(Boolean).forEach((t=>{if(t.participantId){const n=mi(e(t.participantId)||a&&Ma({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&&Ma({policyDefinitions:y,tournamentParticipants:a,internalUse:!0,contextProfile:U,participantId:t})));Object.assign(t.participant,{individualParticipants:n})}})),!St.matchUpType){const{matchUpType:t}=il({matchUp:St});t&&Object.assign(St,{matchUpType:t})}if(U?.inferGender&&(!St.gender||St.gender===ul)&&2===St.sides?.length&&St.matchUpType!==Zd){const t=St.sides.map((t=>{if(St.matchUpType===zc)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===No,n=St.sides?.map((({participant:t,drawPosition:e,sideNumber:n,lineUp:r})=>{const i=t?.participantType===Zd&&t;return{teamParticipant:i&&br({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}=qd({matchUp:St});Object.assign(St,{allParticipantsCheckedIn:t,checkedInParticipantIds:e})}return Array.isArray(U?.exclude)&&U?.exclude.forEach((t=>delete St[t])),St}}function fl({matchUp:t}){return!!t&&(Ho.includes(t?.matchUpStatus)||t?.winningSide)}function hl({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}=Qs({drawDefinition:h,structureId:U}));const T=ml({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=[],M=[];if(T.error)return T;const{matchUps:R}=T,{assignedPositions:A}=ec({structure:y}),E=A?.filter((t=>t.participantId)).map((t=>t.drawPosition));let C;return R.filter((t=>{const e=1===c?.matchUpTypes?.length&&c.matchUpTypes[0]===Qc;return!(t.matchUpType!==Qc&&e)})).forEach((e=>{if(e.matchUpStatus===Do)return void P.push(e);e.matchUpType===Qc&&(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=Yo.includes(e.matchUpStatus)&&(r||i&&(!t||a));return s?M.push(e):fl({matchUp:e})?D.push(e):c?b.push(e):N.push(e)})),{includesTeamMatchUps:C,abandonedMatchUps:P,completedMatchUps:D,upcomingMatchUps:b,pendingMatchUps:N,byeMatchUps:M,structure:y}}function gl(t){Object.assign(t,{requireParticipants:!1});const e=Il(t);if(e.error)return Nr({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 Il(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=[],M=[];I&&!n&&(n=Cu({policyDefinitions:u,tournamentRecord:d,contextProfile:I,event:w})),!e?.length&&d&&(e=d?.participants,(y||s?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:T}=pu({participants:e,participantsProfile:s})));const{structures:R}=Zs({drawDefinition:U});if(!R)return{error:Ut};r||(r=Fu({drawDefinition:U}));const A=U&&Ou({drawDefinition:U}).exitProfiles;R.forEach((t=>{const{byeMatchUps:s=[],pendingMatchUps:T=[],upcomingMatchUps:R=[],completedMatchUps:E=[],abandonedMatchUps:C=[]}=hl({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(...R),N=N.concat(...T),M=M.concat(...s)}));const C=t=>m||S||l?(m&&(t=al({matchUps:t,...m})),l&&(t=al({matchUps:t,...l,processContext:!0})),t):t,O={abandonedMatchUps:C(P),completedMatchUps:C(D),upcomingMatchUps:C(b),pendingMatchUps:C(N),byeMatchUps:C(M),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;yu({inContextDrawMatchUps:[].concat(...e&&P||[],...n&&D||[],...r&&b||[],...i&&N||[],...a&&M||[]),drawDefinition:U})}return O}function Ul({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:n,roundsCount:r,roundLimit:i,matchUps:a,lucky:o,fmlc:s}){if(!Uu(a))return[];const{roundProfile:c,roundNumbers:u=[]}=Su({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(wi("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=Xn({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 Sl({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:n}){if(!e)return{error:j};const r={loserMatchUpIds:{},winnerMatchUpIds:{}};t||({matchUps:t,matchUpsMap:n}=gl({inContext:!0,drawDefinition:e,matchUpsMap:n}));const i=n?.drawMatchUps.some((t=>t.finishingPositionRange));if(!i&&1===e?.structures?.length&&!e?.structures[0].structures){Ul({matchUps:n?.drawMatchUps??[]})}return(t??[]).filter((({collectionId:t})=>!t)).forEach((i=>{const{matchUpId:a,structureId:o}=i,s=gu({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:a}),{winnerMatchUp:c,loserMatchUp:u}=s.targetMatchUps,d=c?.matchUpId,p=u?.matchUpId,l=ku({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 yl(t){return t&&void 0!==String.fromCodePoint?t.toUpperCase().replace(/./g,(t=>String.fromCodePoint(t.charCodeAt(0)+127397))):t}const vl=[{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 wl({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=vl.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 Tl(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 Pl({returnPreviousValues:t,itemSubTypes:e,itemType:n,element:r}){if(!r)return{error:ae,info:Mr};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 Dl({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}=Pl({element:e,returnPreviousValues:t,itemSubTypes:n,itemType:r});return i&&{timeItem:i,previousItems:a}||{info:o}}function bl({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}=Pl({returnPreviousValues:t,element:r,itemSubTypes:e,itemType:n});return i&&{timeItem:i,previousItems:a}||{info:o}}function Nl({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:n,itemType:r}){if(!e)return{error:x};if(!e.timeItems)return{info:On};const{timeItem:i,previousItems:a,info:o}=Pl({element:e,returnPreviousValues:t,itemSubTypes:n,itemType:r});return i&&{timeItem:i,previousItems:a}||{info:o}}function Ml({returnPreviousValues:t,tournamentRecord:e,participantId:n,itemSubTypes:r,itemType:i}){if(!e)return{error:x};if(!n)return{error:Ae};const a=Tl({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}=Pl({element:a.participant,returnPreviousValues:t,itemSubTypes:r,itemType:i});return s&&{timeItem:s,previousItems:c}||{info:u}}const Rl={[ou]:"groupParticipantIds",[su]:"pairParticipantIds",[cu]:"teamParticipantIds"},Al={[ou]:"groups",[cu]:"teams"};function El({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&&Fl({participantMap:c,participantId:e})}for(const t of n.participants??[]){const n=mi(t,e,a),{participantId:u,individualParticipantIds:d,participantType:p}=n;if(Object.assign(c[u].participant,n),d&&Ol({individualParticipantIds:d,participantCopy:n,participantMap:c,participantType:p,participantId:u}),r&&(c[u].participant.signedIn=Cl(n)),i){const{ratings:t,rankings:e,seedings:r}=da({participant:n});c[u].participant.seedings=r,c[u].participant.rankings=e,c[u].participant.ratings=t}(s||o)&&wl({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?pa({template:e,source:i}):i)}}}}({participantMap:c,template:Ui(t)?t:void 0})}return{participantMap:c}}function Cl(t){const{timeItem:e}=Pl({itemType:eu,element:t});return e?.itemValue===ru}function Ol({individualParticipantIds:t,participantCopy:e,participantMap:n,participantType:r,participantId:i}){for(const a of t){const o=n[a].participant;if(o[Rl[r]].push(i),[cu,ou].includes(r)){const{participantRoleResponsibilities:t,participantOtherName:n,participantName:i,participantId:a,teamId:s}=e;o[Al[r]].push({participantRoleResponsibilities:t,participantOtherName:n,participantName:i,participantId:a,teamId:s})}if(r===su){const e=t.find((t=>t!==a));n[a].pairIdMap[i]=e,n[a].pairIdMap[e]=i}}}function Fl({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:{[zc]:{...n},[Kc]:{...n},[cu]:{...n},...n}}}function kl({participantsProfile:t,useParticipantMap:e,tournamentRecord:n,contextProfile:r,inContext:i}){if(e){const e=El({...t,...r,tournamentRecord:n})?.participantMap;return{participantMap:e}}let a,o=mi(n.participants,!1,!0)||[];if((t?.withIOC||t?.withISO2)&&o.forEach((e=>wl({participant:e,...t}))),(i||t?.withGroupings)&&o?.length&&({participantsWithGroupings:o,groupInfo:a}=pu({participantsProfile:t,deepCopy:!1,participants:o})),t?.withScaleValues&&o?.length)for(const t of o){const{ratings:e,rankings:n}=da({participant:t});t.rankings=n,t.ratings=e}return{participants:o,groupInfo:a}}function _l(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,...br({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=Cu({policyDefinitions:c,tournamentRecord:d,contextProfile:l,event:I})),!e?.length&&!r&&d){const t=kl({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=zd({tournamentRecord:d,event:I}).scheduleTiming;return{matchUps:b.flatMap((t=>{const{matchUps:u}=gl({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 xl(t){if(!t?.tournamentRecord)return{error:x};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}=kl({participantsProfile:i,useParticipantMap:o,policyDefinitions:s,tournamentRecord:c,contextProfile:d,inContext:u}));const{appliedPolicies:I}=Tu({tournamentRecord:c}),U={...f,tournamentId:h,indoorOutDoor:c.indoorOutdoor,surfaceCategory:c.surfaceCategory,endDate:c.endDate},S=Cu({policyDefinitions:s,tournamentRecord:c,contextProfile:d});return{matchUps:g.flatMap((t=>(U.eventDrawsCount=t.drawDefinitions?.length??0,_l({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 Ll({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:_};return{matchUps:Object.keys(r).map((u=>{const d=r[u];return xl({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:n,policyDefinitions:i,tournamentRecord:d,matchUpFilters:a,contextFilters:o,nextMatchUps:s,inContext:c}).matchUps??[]})).flat()}}function Bl(t,e){return function(t,e){return(ns[t?.stage]||0)-(ns[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 Vl(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}=kl({participantsProfile:o,useParticipantMap:u,policyDefinitions:c,tournamentRecord:d,contextProfile:l,inContext:g})),l&&!r&&(r=Cu({policyDefinitions:c,tournamentRecord:d,contextProfile:l,drawDefinition:m,event:U}));return{...gl({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 jl(t){let e=tu(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===hs));let f=n;if(m.length){f=Ll({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}=Xc(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)Sl({drawDefinition:o}),f?.length||(f=Vl({drawDefinition:o}).matchUps),I(f);else{if(f?.length||(f=Ll({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(Bl),r=n?.find((({roundPosition:t})=>!t));if(!r){const r=n?.find((({tournamentId:t})=>t)),{drawDefinition:i}=kp({tournamentRecord:e[r?.tournamentId],drawId:t});i&&Sl({drawDefinition:i})}I(n)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:p,matchUps:f,...E}}function Gl(t){const{drawDefinition:n,findContainer:r,structureId:i,event:a}=t;let o=t.structure;const{containedStructures:s}=jc({drawDefinition:n}),c=i&&s[i]||[];if(!o){const t=Qs({drawDefinition:n,structureId:i});if(t.error)return t;o=r?t.containingStructure??t.structure:t.structure}if(nl({drawDefinition:n,structure:o}))return{structure:o,isAdHoc:!0,error:X};const{matchUps:u}=gl({inContext:!0,matchUpFilters:{isCollectionMatchUp:!1},drawDefinition:n,event:a}),d=u?.filter((t=>t.structureId===i||c.includes(t.structureId))),{matchUpDependencies:p}=jl({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)}Wc(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}=tc({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 ql({drawPosition:t,matchUps:n=[]}){return{initialRoundNumber:n.filter((({drawPositions:e})=>t&&e?.includes(t))).map((({roundNumber:t})=>t)).sort(e)[0]}}const $l={reset:"[0m",bright:"[1m",dim:"[2m",red:"[31m",brightred:"[91m",green:"[32m",brightgreen:"[92m",yellow:"[33m",brightyellow:"[93m",blue:"[34m",brightblue:"[94m",lightblue:"[105m",magenta:"[35m",brightmagenta:"[95m",cyan:"[36m",brightcyan:"[96m",white:"[37m",brightwhite:"[97m"},Wl=[];function Hl(t,e){"string"==typeof t&&(t={method:t}),(e||Xn())&&Wl.push(t)}function zl(t){const e=function(t){const e=Wl.slice();return t&&(Wl.length=0),e}(t),n=e.map((t=>{const{color:e,keyColors:n,method:r,newline:i}=t,a=Object.keys($l).includes(e)?$l[e]:$l.cyan,o=Object.keys(t).filter((t=>!["color","keyColors","method","newline"].includes(t))).map((e=>{const r=n&&Object.keys(n).includes(e)&&$l[n[e]]?$l[n[e]]:$l.brightwhite;return`${$l.white}${e}: ${r}${t[e]}`})).join(", ");return[i?"\n":"",a,r,r?.length<15?"\t\t":"\t",$l.white,o,$l.reset,"\n"].join("")}));n?.length&&console.log(...n)}function Yl({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}=Qs({drawDefinition:r,structureId:o})),!s)return{error:Ut};o||({structureId:o}=s);const u="assignDrawPositionBye";Hl({method:u,color:"cyan",drawPosition:i}),a||(a=Fu({drawDefinition:r}));const{positionAssignments:d}=tc({structure:s}),{activeDrawPositions:p}=Gl({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:Z};const f=d?.find((t=>t.drawPosition===i));if(!f)return{error:X};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 Nr({result:{error:z},stack:u});const U=gl({inContext:!0,drawDefinition:r,matchUpsMap:a}).matchUps??[],{matchUps:S}=ml({provisionalPositioning:t,drawDefinition:r,matchUpFilters:{isCollectionMatchUp:!1},matchUpsMap:a,structure:s});if(d?.forEach((t=>{t.drawPosition===i&&(t.bye=!0)})),s.structureType===ds)return function({tournamentRecord:t,drawDefinition:e,drawPosition:n,matchUps:r,event:i}){r.forEach((r=>{r.drawPositions?.includes(n)&&Jl({eventId:i?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:r})}))}({tournamentRecord:n,drawDefinition:r,drawPosition:i,matchUps:S}),xc({tournamentId:n?.tournamentId,drawDefinition:r,structure:s,event:c}),Kl({assignedParticipantId:I,isPositionAction:e,drawDefinition:r,drawPosition:i,structureId:o,stack:u});const{roundProfile:y,roundMatchUps:v}=Su({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&&Jl({tournamentRecord:n,drawDefinition:r,matchUp:P,event:c});const D=P?.drawPositions?.find((t=>t!==i));if(P&&D){const t=Ql({sourceDrawPositions:P.drawPositions,matchUpId:P.matchUpId,inContextDrawMatchUps:U,drawPositionToAdvance:D,tournamentRecord:n,drawDefinition:r,matchUpsMap:a});if(t.error)return t}return xc({tournamentId:n?.tournamentId,drawDefinition:r,structure:s,event:c}),Kl({assignedParticipantId:I,isPositionAction:e,drawDefinition:r,drawPosition:i,structureId:o,stack:u})}function Kl({assignedParticipantId:t,isPositionAction:e,drawDefinition:n,drawPosition:r,structureId:i,stack:a}){if(e){Vc({drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:r,structureId:i,name:a}})}return Nr({result:{...E},stack:a})}function Jl({tournamentRecord:t,drawDefinition:e,eventId:n,matchUp:r,event:i}){Object.assign(r,{matchUpStatus:No,score:void 0,winningSide:void 0}),Oc({tournamentId:t?.tournamentId,eventId:n??i?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:r})}function Ql({drawPositionToAdvance:t,inContextDrawMatchUps:n,sourceDrawPositions:r,tournamentRecord:i,drawDefinition:a,matchUpsMap:o,matchUpId:s,event:c}){Hl({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}=Qs({drawDefinition:a,structureId:p}),{positionAssignments:m}=tc({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}}=gu({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}=Qs({drawDefinition:a,structureId:l}),{positionAssignments:f}=tc({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 Nr({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}),Nr({result:{error:z},stack:u});const M=f?.find((({drawPosition:t})=>t===P))?.bye,R=f?.find((({drawPosition:e})=>e===t))?.bye,A=R||M?No:Bo;Object.assign(d,{matchUpStatus:A,score:void 0,winningSide:void 0,drawPositions:N});const E=d.drawPositions.find((t=>!b.includes(t)));Hl({method:u,color:"brightyellow",changedDrawPosition:E,pairedDrawPositionIsBye:M,drawPositionIsBye:R}),Oc({tournamentId:i?.tournamentId,matchUp:d,eventId:c?.eventId,context:u,drawDefinition:a});const{targetLinks:{loserTargetLink:C},targetMatchUps:{loserMatchUp:O,loserTargetDrawPosition:F}}=gu({matchUpId:o.matchUpId,inContextDrawMatchUps:n,drawDefinition:a});if(M||R){const e=M?t:P;if(e)Ql({drawPositionToAdvance:e,matchUpId:o.matchUpId,inContextDrawMatchUps:n,tournamentRecord:i,drawDefinition:a,matchUpsMap:s});else if(R&&C&&O)if(O.feedRound)Zl({loserTargetDrawPosition:F,tournamentRecord:i,loserTargetLink:C,drawDefinition:a,loserMatchUp:O,matchUpsMap:s});else{const t=1-o.roundPosition%2,e=O.drawPositions[t],n=Yl({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=Yl({structureId:I.target.structureId,drawPosition:y,tournamentRecord:i,drawDefinition:a,event:c});if(t.error)return t}else Zl({loserTargetDrawPosition:y,tournamentRecord:i,loserTargetLink:I,drawDefinition:a,loserMatchUp:U,matchUpsMap:o,event:c})}return{...E}}function Zl({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:n,drawDefinition:r,loserMatchUp:i,matchUpsMap:a,event:o}){const{roundNumber:s}=i;Hl({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});const c=(a?.mappedMatchUps||{})[i.structureId].matchUps,{initialRoundNumber:u}=ql({drawPosition:t,matchUps:c});if(u===s){const i=Yl({structureId:n.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:r,event:o});if(i.error)return i}}function Xl({positionAssignments:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:r,structure:i,event:a}){const{matchUps:o}=ml({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?No:Bo;Object.assign(r,{matchUpStatus:t}),Oc({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:a?.eventId,drawDefinition:n,matchUp:r})}}))}function tm(t){let{inContextDrawMatchUps:e,participantId:n,drawPosition:r}=t;const{tournamentRecord:i,drawDefinition:a,structureId:o,matchUpsMap:s,event:c}=t,{structure:u}=Qs({drawDefinition:a,structureId:o}),d=(ec({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}=Gl({drawDefinition:a,structureId:o});if(p.includes(r))return{error:Z};e||({matchUps:e}=gl({inContext:!0,drawDefinition:a,matchUpsMap:s}));return em({inContextDrawMatchUps:e,tournamentRecord:i,drawDefinition:a,structureId:o,drawPosition:r,matchUpsMap:s,event:c}).drawPositionCleared?(xc({tournamentId:i?.tournamentId,drawDefinition:a,structure:u,event:c}),{...E,participantId:n}):{error:K}}function em({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:i,matchUpsMap:a,structureId:o,event:s}){const{structure:c}=Qs({drawDefinition:r,structureId:o});if(!c)return{error:Ut};const u=ec({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===ds)return Xl({positionAssignments:u,tournamentRecord:e,drawDefinition:r,matchUpsMap:a,structure:c}),{drawPositionCleared:d,...E};const{matchUps:p}=ml({drawDefinition:r,matchUpFilters:{isCollectionMatchUp:!1},matchUpsMap:a,structure:c,event:s}),{roundProfile:l,roundMatchUps:m}=Su({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}=Qs({drawDefinition:r,structureId:o});if(!s)return{error:Ut};if(s.structureType===ds)return;i=i||Fu({drawDefinition:r});const c=i?.mappedMatchUps||{},u=c[o].matchUps,{initialRoundNumber:d}=ql({drawPosition:e,matchUps:u}),p=u?.filter((t=>t.roundNumber>=a&&t.roundNumber!==d&&t.drawPositions?.includes(e))),l=tc({drawDefinition:r,structureId:o}).positionAssignments??[];p?.forEach((a=>nm({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}),nm({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 nm({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??Fu({drawDefinition:r})).mappedMatchUps[s.structureId].matchUps,{initialRoundNumber:f}=ql({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===Qc){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,Oc({tournamentId:n?.tournamentId,context:`${u}-TEAM`,eventId:c?.eventId,matchUp:i,drawDefinition:r}))}const h=gu({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&&No||i.matchUpStatus&&[Eo,Vo].includes(i.matchUpStatus)&&i.matcHUpStatus||2===i.drawPositions?.length&&Bo||void 0;i.matchUpStatus=v,i.matchUpStatus&&[Vo,Eo].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&&Hl({method:u,color:"brightyellow",removedDrawPosition:w}),Oc({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];em({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}=Qs({structureId:i.structureId,drawDefinition:r}),{positionAssignments:c}=tc({structure:s}),u=c?.find((e=>e.drawPosition===t));if(u?.bye){const s=tm({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 Nr({result:a,stack:u});const s=(o?.mappedMatchUps||{})[I.structureId].matchUps,{initialRoundNumber:d}=ql({drawPosition:i,matchUps:s});1===d&&(Hl({method:u,color:"brightyellow",loserMatchUpDrawPosition:i}),em({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 rm({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}=tc({structure:t});return e?e.map(vo):[]})).flat().filter(Boolean));return{...E,assignedParticipantIds:n}}function im(t){const e=(t?.entries??[]).filter(Boolean).reduce(((t,e)=>{const{entryStage:n,entryStatus:r}=e,i=`_${n||Jo}${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 am(t){return[Yu,zu].includes(t)}function om({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&&!ed.includes(a))return{error:je};if(o&&!es.includes(o))return{error:At};const l="modifyEntriesStatus",m=[];if(!a&&!s)return Nr({result:{error:ae},info:"Missing entryStatus",stack:l});if(s&&!Er({extension:s,requiredAttributes:["name"]}))return Nr({result:{error:Nn},info:"Invalid extension",context:{extension:s},stack:l});const f=[];p?.drawDefinitions?.forEach((t=>{const e=rm({stages:d&&[d],drawDefinition:t}).assignedParticipantIds??[];f.push(...e)}));const h=n?.participants??[];if(!i.every((t=>{const e=Ma({tournamentParticipants:h,participantId:t})?.participantType;return!(e&&[su,iu].includes(e)&&am(a)||a&&p?.eventType&&e===au&&[Jd,Xd].includes(p.eventType)&&[Lu,...Qu].includes(a))})))return{error:je};const g=p&&Fp({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)&&!(Qu.includes(t.entryStatus)&&Qu.includes(a)))(t)&&!e)&&(a&&(t.entryStatus=a,delete t.entryPosition),o&&(t.entryStage=o,delete t.entryPosition),s&&(s.value?Cr({element:t,extension:s}):Ar({element:t,name:s.name})),!0)))?{...E}:{error:Le}},S=({flight:t,drawDefinition:e})=>{p&&(p.entries=im({entries:p.entries??[]})),t&&(t.drawEntries=im({entries:t.drawEntries})),e&&(e.entries=im({entries:e.entries}))},y=t=>{const{flight:e,drawDefinition:n}=t,r="updateDrawEntries";if(e){const t=U(e.drawEntries);if(t.error)return Nr({result:t,stack:r})}if(n){const t=U(n.entries);if(t.error)return Nr({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 Nr({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 Nr({result:e,stack:l})}const P=1===g?.flights?.length&&(p?.drawDefinitions?.length??0)<=g?.flights?.length;if(!I&&!r&&a&&Zu.includes(a))return{error:He};if(!I&&!r||a===Ju||c&&P){const t=U(p?.entries);if(t?.error)return Nr({result:t,stack:l});let e;if(a===Ju&&(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 Nr({result:{error:e},stack:l})}t&&S({flight:I,drawDefinition:r});for(const t of p?.drawDefinitions??[])m.length&&!m.includes(t.drawId)||kc({tournamentId:n.tournamentId,eventId:p?.eventId,drawDefinition:t});return{...E}}function sm(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===No||e[n].scheduleItems.push({...d,scheduledDate:ti(d?.scheduledDate),scheduledTime:Xr(d?.scheduledTime),checkScoreHasValue:Gc({score:l}),matchUpStatus:r,roundPosition:i,structureId:a,matchUpType:o,roundNumber:s,matchUpId:c,potential:u,drawId:p})}function cm({requireTimeStamp:t,scaleAttributes:e,participant:n}){if(!n)return{error:Me};if(!Ui(e))return{error:Nn};if(n.timeItems||(n.timeItems=[]),Array.isArray(n.timeItems)){const{accessor:r,scaleType:i,eventType:a,scaleName:o}=e,s=[sa,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!==sa)return{error:In};const a=r&&hi({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 um({publishedSeeding:t,usePublishState:e,withSeeding:n,participant:r,event:i}){const a={},o=t=>[sa,ca,i.eventType,t].join("."),s=Object.assign({},...(r.timeItems||[]).filter((({itemType:t})=>t.split(".")[1]===ca)).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=cm({scaleAttributes:{eventType:i.eventType,scaleType:ca,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 dm({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({},...fi(p)):{},m=Object.assign(l,{entryPosition:d,entryStatus:c,entryStage:u,ranking:o,eventId:a});n.events[a]=br(m,!1,!1,!0),r&&(e&&(n.events[a].seedAssignments=e),i&&(n.events[a].seedValue=i))}function pm(t,e){return(t||"").localeCompare(e||"")}function lm({event:t,status:e=Vd}){const n=`${Bd}.${jd}`;return bl({itemType:n,event:t})?.timeItem?.itemValue?.[e]}function mm({drawDetails:t,drawId:e}){const n=t?.[e]?.publishingDetail;return n?.published}function fm({tournamentRecord:t,eventIds:e,drawIds:n,drawId:r,event:i}){if(Array.isArray(e)&&e?.length){const n={};for(const r of e){if(!Ii(r))return{error:Nn};const e=kp({tournamentRecord:t,eventId:r});if(!e)return{error:Pt};const i=hm({event:e});if(i.error)return i;n[r]=i}return{...E,publishState:n}}if(!i&&t?.events&&Array.isArray(n)&&n.length){const e={};for(const r of t.events){const t=hm({event:r});if(t.error)return t;for(const r of n){if(!Ii(r))return{error:Nn};const n=t.publishState.publishedDrawIds.includes(r);n&&(e[r]={published:n})}}return{...E,publishState:e}}if(i){const t=hm({event:i});if(t.error)return t;if(r)return{publishState:{published:t.publishState.publishedDrawIds.includes(r),...E}};if(!Array.isArray(n)||!n?.length)return t;{const e={};for(const r of n)return Ii(r)?(e[r]={published:t.publishState.publishedDrawIds.includes(r)},{...E,publishState:e}):{error:Nn}}}return{error:Nn}}function hm({event:t}){const e=lm({event:t});if(!e)return{error:Pt};const n={published:void 0,seedingScaleNames:[],drawIds:[]};e.seeding&&Object.assign(n,e.seeding);const{drawDetails:r}=e,i=r&&Object.keys(r).filter((t=>mm({drawDetails:r,drawId:t})))||e.drawIds||[];return{publishState:{published:i.length>0,publishedDrawIds:i,publishedSeeding:n,drawDetails:r},...E}}function gm({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===Vo&&(f.walkoverWinCount+=1),i===Eo&&(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 Im(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:M,sides:R}=t,A=a&&2===R?.length&&Object.assign({},...R.map((({sideNumber:t},e)=>{const n=R[1-e].participantId;return t&&{[t]:n}})).filter(Boolean));for(const t of R){const{participantId:R,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!==iu)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:M,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:M}),I&&gm({finishingPositionRange:u,participantMap:i,participantWon:O,finishingRound:d,matchUpStatus:p,participantId:t,stageSequence:l,roundNumber:m,structureId:f,matchUpId:D,drawId:M,stage:g}),(n||e)&&sm({participantMap:i,participantId:t,matchUpStatus:p,roundPosition:S,matchUpType:T,roundNumber:m,structureId:f,matchUpId:D,schedule:b,drawId:M,score:h})},_=({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?.[M],e),s&&n(t?.events?.[N],e),o&&n(t?.matchUps?.[D],e)};if(R&&i[R]){const t=A?.[E];k(R,t);const e=i[R]?.participant.participantType===su,n=i[R]?.participant.individualParticipantIds||[];if(y){if(r){const t=t=>i[t].matchUps[y]={participantWon:U===E,matchUpId:y,matchUpType:Qc,sideNumber:E};t(R),n.forEach(t)}if(c&&!i[R].draws[M]){const t=v.find((t=>t.sideNumber===E))?.participant?.participantId,e=i[t]?.draws?.[M]?.entryStatus,r=t=>i[t].draws[M]={entryStatus:e,eventId:N,drawId:M};r(R),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&&_({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[R].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===Vo&&(i[t].counters[T].walkoverWins+=1,i[t].counters.walkoverWins+=1),p===Eo&&(i[t].counters[T].defaultWins+=1,i[t].counters.defaultWins+=1)):(i[t].counters[T].losses+=1,i[t].counters.losses+=1,p===Vo&&(i[t].counters[T].walkovers+=1,i[t].counters.walkovers+=1),p===Eo&&(i[t].counters[T].defaults+=1,i[t].counters.defaults+=1))};t(R),n.forEach(t)}}}}function Um({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=Sm(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}=Fp({event:e}),i=r?.flights?.map((({drawEntries:t})=>Array.isArray(t)?t.filter(n).map(vo):[])).flat()||[],a=e.drawDefinitions?.map((({entries:t})=>t?t.filter(n).map(vo):[]))||[];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(vo);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=>Xs({drawDefinition:t}).allPositionedParticipantIds)).filter(Boolean))),[]),y=t=>r?.reduce(((e,n)=>{const{accessor:r,value:i}=n,{values:a}=hi({element:t,accessor:r});return e&&a?.includes(i)}),!0);if(n=n?.filter((t=>{const e=Pl({element:t,itemType:eu})?.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&&Sm(u)&&u.includes(i)||s&&o&&Sm(s)&&s.includes(o)||c&&Sm(n)&&Sm(c)&&c.find((t=>n?.includes(t)))||r?.length&&Sm(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&&Sm(u)&&u.includes(i))&&(!s||o&&Sm(s)&&s.includes(o))&&(!c||Sm(n)&&Sm(c)&&c.find((t=>n?.includes(t))))&&(!r?.length||Sm(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===Yd)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 Sm(t){return t&&Array.isArray(t)&&t.length}function ym(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:x};(U||i)&&jl({tournamentRecord:c});let{participantMap:D}=El({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={},M={},R=({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:_}=Fp({event:t}),x=_?.flights??[],L=fm({event:t}).publishState;L&&(b[F]=L);const B=L?.publishedSeeding;if(U||I||u){const e=n?Object.assign({},...fi(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=R({eventType:A,scaleNames:r,participantId:i});let c,u;if(I){const e=s[i].participant;({seedAssignments:c,seedValue:u}=um({publishedSeeding:B,usePublishState:a,withSeeding:I,participant:e,event:t}))}const d=t=>{if(s[t]?.events?.[F])return;const r=s[t];dm({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(To),...x.map(To)]);for(const n of e){const e=y.find((t=>t.drawId===n)),r=x?.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)=>Ks(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===Jo&&1===e||t===Qo)).flatMap((t=>{const{seedAssignments:e,stageSequence:n,stage:r}=t,{positionAssignments:i}=tc({structure:t});return r===Jo?(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=R({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[Jo]=l),d&&m&&(d[Qo]=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]=br({seedAssignments:d,entryPosition:i,entryStatus:e,entryStage:r,seedValue:h,eventId:F,ranking:o,drawId:n},!1,!1,!0))};if(![zu,Yu].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;M[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=_l({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 M={finishingPositionRange:n,finishingRound:I,stageSequence:g,roundPosition:S,collectionId:h,roundNumber:y,structureId:T,schedule:D,eventId:m,drawId:f,score:b,stage:N};Im({...M,...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;Im({...M,...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(vo).filter(Boolean);t?.forEach((t=>{const e=v(t);e?.forEach((t=>{s[t]&&(s[t].potentialMatchUps[l]=br({tournamentId:i?.tournamentId,matchUpId:l,eventId:m,drawId:f}))})),(p||d)&&sm({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,[zc]:{wins:r,losses:i},[Kc]:{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(Au,t,n),c(`${Au}.${zc}`,r,i),c(`${Au}.${Kc}`,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}=M[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!==Qo;s&&(o+=1);const c=s?o:void 0;return br({...r,participationOrder:c,flightNumber:i})})).filter(Boolean);e.draws[n]&&(e.draws[n].finishingPositionRange=a,e.draws[n].structureParticipation=s)}}}if(p){const t=Ui(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(ii)));for(const a of n){const{typeChangeTimeAfterRecovery:n,timeAfterRecovery:o,scheduledDate:s,scheduledTime:c}=a,u=i[s],d=Qr(c);for(const i of u){if(i.matchUpId===a.matchUpId||[Vo,Eo].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=Qr(i.scheduledTime),l=Math.abs(p-d),m=p>=d;if((t&&!isNaN(t)?l<=t:m&&Qr(i.scheduledTime)<Qr(s))&&(!u||!c)&&m){const t=[a.matchUpId,i.matchUpId].sort(pm).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:M,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:M,derivedEventInfo:R,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))})),br({...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)},_=new Map;for(const t of Object.keys(D))_.set(t,k(D[t]));const L=[..._.values()],B=o?.[Sa],V=B?.participant,j=Um({participants:L,participantFilters:n,tournamentRecord:c});if(e){const t=Ui(e)?e:void 0;for(const e of j)for(const n of e.individualParticipantIds??[]){e.individualParticipants||(e.individualParticipants=[]);const r=_.get(n);e.individualParticipants.push(t?pa({template:t,source:r}):r)}}return{participantIdsWithConflicts:N,eventsPublishStatuses:M,derivedEventInfo:R,derivedDrawInfo:A,mappedMatchUps:C,participantMap:D,participants:V?j.map((t=>pa({source:t,template:V}))):j,...E,matchUps:O}}function vm({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 wm(t){const{provisionalPositioning:e,drawDefinition:n,stageSequence:r,structureId:i,stage:a}=t;if(!n)return{error:j};const{entryProfile:o}=xu({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}=Qs({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=Qs({structureId:t.source.structureId,drawDefinition:n})?.structure;if(r?.stage===Qo){const n=t.source.roundNumber,i=t.target.roundNumber;let a=0;if(r.structureType===ds){a=(r.structures?.length??0)*(t.source.finishingPositions?.length??0)}else{const t=ml({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}=xu({drawDefinition:e});return n?.[t]?.drawSize||0}function Pm({stage:t,drawDefinition:e}){return Boolean(t===Xo||rd({stage:t,drawDefinition:e})&&Tm({stage:t,drawDefinition:e}))}function Dm({entryStatus:t=Vu,drawDefinition:e,stageSequence:n,stage:r}){if(t===Lu)return function({stage:t,drawDefinition:e}){const{entryProfile:n}=xu({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}=wm({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}=xu({drawDefinition:e});return n[t]?.wildcardsCount||0}({drawDefinition:e,stage:r}),o=id({entryStatus:Ku,drawDefinition:e,stage:r}),s=o+id({entryStatus:Vu,drawDefinition:e,stage:r}),c=i-s;return r!==Xo&&s>=i?{error:ze}:t===Ku?o<a?{...E}:{error:ze}:{positionsAvailable:c,...E}}function bm(t){const{entryStatus:e=Vu,entryStageSequence:n,entryStage:r=Jo,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:Rt};if(p!==Ss&&!Pm({stage:r,drawDefinition:a}))return Nr({result:{error:At},stack:l});const m=Dm({stageSequence:n,stage:r,drawDefinition:a,entryStatus:e});if(!i&&!m.success)return{error:m.error};if(d&&!Er({extension:d}))return Nr({result:{error:Nn},info:"Invalid extension",context:{extension:d},stack:l});const f=t.participantId||s?.participantId;if(!f)return Nr({result:{error:Ae},stack:l});const h=e===qu&&vm({participantId:f,drawDefinition:a,entryStatus:e}),g=r===Xo&&vm({participantId:f,drawDefinition:a,entryStage:r}),I=e!==qu&&r!==Xo&&vm({drawDefinition:a,participantId:f});if(I||h||g)return Nr({context:{invalidEntry:I,invalidLuckyLoser:h,invalidVoluntaryConsolation:g},result:{error:Be},stack:l});const U=br({entryStageSequence:n,participantId:f,entryPosition:o,entryStatus:e,entryStage:r,extensions:u});return d&&Cr({element:U,extension:d}),c&&Cr({extension:{name:"roundEntry",value:c},element:U}),a.entries||(a.entries=[]),a.entries.push(U),kc({drawDefinition:a}),{...E}}function Nm({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(vo);if(i.filter((t=>!p.includes(t))).length)return{error:bt};if(r){const u=function(t){const{entryStatus:e=Vu,stage:n=Jo,autoEntryPositions:r=!0,ignoreStageSpace:i,drawDefinition:a,participantIds:o,stageSequence:s,roundTarget:c,extension:u}=t;if(!n)return{error:Rt};if(!a)return{error:j};if(!Array.isArray(o))return{error:Pe};if(!Pm({stage:n,drawDefinition:a}))return{error:At};if(u&&!Er({extension:u}))return Nr({result:{error:Nn},info:"Invalid extension",context:{extension:u},stack:"addDrawEntries"});const d=Dm({drawDefinition:a,stageSequence:s,entryStatus:e,stage:n});if(!i&&!d.success)return{error:d.error};const p=d.positionsAvailable??0;if(!i&&n!==Xo&&p<o.length)return{error:Ve};const l=o.reduce(((t,r)=>{const i=e===qu&&vm({participantId:r,drawDefinition:a,entryStatus:e}),o=n===Xo&&vm({entryStage:n,drawDefinition:a,participantId:r});return e!==qu&&n!==Xo&&vm({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&&Cr({element:r,extension:u}),c&&Cr({extension:{name:to,value:c},element:r}),a.entries||(a.entries=[]),a.entries.push(r)})),r&&(a.entries=im({entries:a.entries})),kc({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}=Fp({event:d}),m=l?.flights.find((t=>t.drawId===u));return m?.drawEntries&&(i.forEach((t=>{const e=a===qu&&Mm({participantId:t,entryStatus:a,flight:m}),n=s===Xo&&Mm({participantId:t,entryStage:s,flight:m});a!==qu&&s!==Xo&&Mm({flight:m,participantId:t})||e||n||m.drawEntries.push({participantId:t,entryStatus:a,entryStage:s})})),t&&(m.drawEntries=im({entries:m.drawEntries}))),{...E}}function Mm({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 Rm({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=>!Ii(t))))return Nr({result:{error:Te},stack:a});const o=(i.drawDefinitions??[]).flatMap((t=>rm({drawDefinition:t}).assignedParticipantIds??[])),s=(n?.length&&i.entries?.filter((t=>t.entryStatus&&n.includes(t.entryStatus)))||[]).map(vo).filter((t=>!o.includes(t))),c=(r&&i.entries?.filter((t=>t.entryStage&&t.entryStage===r))||[]).map(vo).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 Nr({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=im({entries:i.entries}));const{flightProfile:d}=Fp({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 Am={[ga]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}};function Em(t){const{entryStatus:e=Vu,autoEntryPositions:n=!0,enforceGender:r=!0,participantIds:i=[],entryStageSequence:a,policyDefinitions:o,entryStage:s=Jo,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 Nr({result:{error:Fe},stack:g});if(!h?.eventId)return{error:Pt};const I=Tu({tournamentRecord:c,event:h}).appliedPolicies??{},U=o?.[ga]??I?.[ga]??Am[ga],S=!1!==(r??U?.participants?.enforceGender),y=[],v=[];if(l&&(!Array.isArray(l)||!l.every((t=>Er({extension:t}))))||m&&!Er({extension:m}))return Nr({context:br({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===zc&&t.participantType===au&&!am(e),r=h.eventType===Kc&&t.participantType===su;return!(!n||h.gender&&S&&![ul,sl].includes(h.gender)&&h.gender!==t.person?.sex)||(!(!r||am(e))||(!(h.eventType!==Kc||t.participantType!==au||!am(e))||(n&&h.gender&&S&&![ul,sl].includes(h.gender)&&h.gender!==t.person?.sex?(T.push({participantId:t.participantId,sex:t.person?.sex}),!1):h.eventType===cu&&(t.participantType===cu||am(e)&&t.participantType===au))))})).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=br({participantId:t,entryStatus:e,entryStage:s,extensions:l});m&&Cr({element:n,extension:m}),p&&Cr({extension:{name:to,value:p},element:n}),a&&(n.entryStageSequence=a),y.push(n.participantId),h.entries?.push(n)}})),f&&!am(s)){const t=Nm({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&&[Qd,Xd].includes(h.eventType)){const t=(h.entries||[]).map((t=>t.participantId)),e=(h.entries||[]).filter((t=>am(t.entryStatus))).map((t=>t.participantId)),n=(c?.participants??[]).filter((e=>t.includes(e.participantId)&&e.participantType&&[su,cu].includes(e.participantType))).map((t=>t.individualParticipantIds)).flat(1/0),r=e.filter((t=>n.includes(t)));r.length&&(v.push(...r),Rm({participantIds:r,autoEntryPositions:!1,event:h}))}if(b.length!==i.length)return Nr({context:{mismatchedGender:T,gender:h.gender},result:{error:Pe},stack:g});n&&(h.entries=im({entries:h.entries||[]}));const M=y.length-v.length;return Nr({result:{...E,addedEntriesCount:M},stack:g,info:P})}const Cm="COMPETITOR",Om="OFFICIAL",Fm="OTHER",km={ADMINISTRATION:"ADMINISTRATION",CAPTAIN:"CAPTAIN",COACH:"COACH",COMPETITOR:Cm,MEDIA:"MEDIA",MEDICAL:"MEDICAL",OFFICIAL:Om,OTHER:Fm,SECURITY:"SECURITY"};function _m({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:n,tournamentRecord:r,suppressErrors:i}){const a="removeIndividualParticipantIds";if(!r)return Nr({result:{error:x},stack:a});if(!n||!e)return Nr({result:{error:ae},stack:a});const o=(r.participants??[]).find((t=>t.participantId===n));if(!o)return Nr({result:{error:Ee},stack:a});if(![cu,ou].includes(o.participantType))return Nr({result:{participantType:o.participantType,error:be},stack:a});const s=xm({individualParticipantIds:e,groupingParticipant:o,tournamentRecord:r,suppressErrors:i}),{removed:c,error:u}=s;if(u)return Nr({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)));Em({participantIds:n,entryStatus:zu,tournamentRecord:r,event:t})}}return c&&cr({topic:gc,payload:{tournamentId:r.tournamentId,participants:[o]}}),{...E,...s}}function xm({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}=ym({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||Gc({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}=Fr({element:i,name:Ya}),a=t?.value[e.participantId];t&&a&&(t.value[e.participantId]=a.filter((t=>t.participantId!==r)),Cr({element:i,extension:t}),Fc({drawDefinition:i}));const o=Vl({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)),Oc({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 Lm({participantRole:t=Cm,individualParticipantIds:e=[],groupingTypes:n=[iu,ou],tournamentRecord:r}){if(!r)return{error:x};const i=r.participants??[],{participants:a,mappedMatchUps:o}=ym({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}=xm({groupingParticipant:t,individualParticipantIds:e,tournamentRecord:r,mappedMatchUps:o,participants:a});n&&s++})),s?E:{error:Oe}}function Bm(t){if(!t?.tournamentRecord)return{error:x};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===Zd)).map((t=>t?.drawDefinitions?.map((({drawId:t})=>t)))).flat(1/0),o=ym({participantFilters:{participantIds:r},tournamentRecord:n,withDraws:!0}).participants??[],s=a?.length&&P((xl({matchUpFilters:{drawIds:a,matchUpTypes:[Kc]},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=Rm({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===su&&t.individualParticipantIds.some((t=>r.includes(t)));if(!n&&t.participantType===Zd&&t.individualParticipantIds.some((t=>r.includes(t)))&&(t.individualParticipantIds=t.individualParticipantIds.filter((t=>!r.includes(t)))),n&&e&&[su,cu].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(Lm({individualParticipantIds:r,tournamentRecord:n}),e)for(const t of n.events||[]){Em({participantIds:u[t.eventId].map((t=>d[t]||[])).flat(),entryStatus:zu,tournamentRecord:n,event:t})}return p&&cr({payload:{participantIds:r,tournamentId:n.tournamentId},topic:cc}),p?{...E,participantsRemovedCount:p}:{error:ye}}function Vm({selected:t=!0,drawDefinition:e,entryStatuses:n,drawId:r,event:i,stage:a}){let o=i.entries??[];if(r){const{flightProfile:t}=Fp({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&&td.includes(e.entryStatus))));return{entries:o,stageEntries:s}}function jm({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:i,stage:a,event:o}){const s="destroyGroupEntry";if(!e)return{error:x};if(!r)return Nr({result:{error:Ae},stack:s});if(!o)return{error:Tt};if(!o.eventType||![Qd,Xd].includes(o.eventType))return Nr({result:{error:wt},stack:s});const c=e.participants??[],u=c.find((t=>t.participantId===r));if(!u)return Nr({result:{error:Ee},stack:s});if(!u.participantType||![su,iu].includes(u.participantType)||u.participantType===iu&&o.eventType!==Xd||u.participantType===su&&o.eventType!==Qd)return{error:be};const d=(o.entries??[]).find((t=>t.participantId===r));if(!d)return{error:Ge};const{stageEntries:p}=Vm({selected:!1,drawDefinition:n,drawId:i,event:o,stage:a}),l=p.map(vo),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=Rm({participantIds:[r],event:o});if(g.error)return g;if(f?.length&&(g=Em({participantIds:f,entryStatus:zu,entryStage:d.entryStage,tournamentRecord:e,drawDefinition:n,drawId:i,event:o}),g.error))return g;if(t){Bm({participantIds:[r],tournamentRecord:e}).success&&(h=!0)}return{...E,participantRemoved:h}}function Gm({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:i,event:a}){return jm({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:i,event:a})}function qm(t){if(!t.tournamentRecord)return{error:x};const{participantIds:e,...n}=t;let r=0;const i=[];for(const t of e){const e=jm({participantId:t,...n});e.success&&(r+=1),e.error&&i.push(e.error)}return r?{destroyedCount:r,...E}:{error:i}}function $m(t){const{tournamentRecord:e,replaceWithBye:n,drawDefinition:r,destroyPair:i,entryStatus:a,matchUpsMap:o,drawId:s}=t,c="removeDrawPositionAssignment",u=tm(t);if(u.error)return Nr({result:u,stack:c});const{participantId:d}=u,{drawPosition:p,event:l,structureId:m}=t;if([Lu,Ju].includes(a)&&d){const{tournamentRecord:e}=t,{participant:n}=Tl({tournamentRecord:e,participantId:d}),{participantType:o,individualParticipantIds:u}=n??{};if(i&&o===su){const t=Gm({tournamentRecord:e,drawDefinition:r,participantId:d,event:l});if(t.error)return Nr({result:t,stack:c});u&&om({participantIds:u,tournamentRecord:e,drawDefinition:r,entryStatus:a,drawId:s,event:l})}else om({participantIds:[d],tournamentRecord:e,drawDefinition:r,entryStatus:a,drawId:s,event:l})}if(n){const t=Yl({tournamentRecord:e,drawDefinition:r,drawPosition:p,structureId:m,matchUpsMap:o,event:l});if(t.error)return Nr({result:t,stack:c})}const{structure:f}=Qs({drawDefinition:r,structureId:m});Bc({structure:f,drawPositions:[p]});return Vc({drawDefinition:r,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:n,drawPosition:p,entryStatus:a,structureId:m}}),u}function Wm(t){return Object.assign(t,{entryStatus:Ju}),$m(t)}function Hm(t){return Ii(t)?t.split(" ").map((t=>t.split("").map(((t,e)=>e?t.toLowerCase():t.toUpperCase())).join(""))).join(" "):t}function zm(t){return Ii(t)?Hm(t.replace(/_/g," ")):""}const Ym=({finishingPosition:t=Hs,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??wp(),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 Km({structureName:t=zm(Xo),structureAbbreviation:e,drawDefinition:n,matchUpType:r,structureId:i}){if(!n)return{error:j};const a=Ym({stage:Xo,structureAbbreviation:e,structureName:t,matchUps:[],structureId:i,matchUpType:r});return n.structures||(n.structures=[]),n.structures.push(a),kc({drawDefinition:n,structureIds:[a.structureId]}),{...E}}function Jm(t){let{sourceMatchUp:e}=t;const{targetMatchUp:n,structure:r,matchUpsMap:i,drawPosition:a}=t,o=n.roundNumber>1&&n.roundNumber-1,s=ku({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:[Oo,Co].includes(p)}}function Qm({structureId:t,matchUpsMap:e,matchUp:n}){const r=n?.roundPosition,i=r+(r%2?1:-1);return{pairedPreviousMatchUp:ku({matchUpsMap:e,structureId:t}).find((({roundNumber:t,roundPosition:e})=>t===n?.roundNumber&&e===i))}}function Zm({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:n,matchUpsMap:r,matchUp:i}){const a=t.find((t=>t.matchUpId===n)),{pairedPreviousMatchUp:o}=Qm({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=Ii(t)||!isNaN(t)?{code:t}:t;return n.sideNumber===s?{...n,previousMatchUpStatus:e}:n}))}}function Xm({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 tf({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}=Fr({element:i,name:Ya}),d=mi((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)}Oc({tournamentId:r?.tournamentId,context:"updateSidLineUp",eventId:o?.eventId,drawDefinition:i,matchUp:a})}function ef({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=Fu({drawDefinition:a})),t||(t=gl({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}=tc({drawDefinition:a,structure:f}),v=y?.filter((t=>S.includes(t.drawPosition))),w=v?.find((({bye:t})=>t)),T=h?.matchUpStatus&&[Vo,Eo].includes(h.matchUpStatus)&&S.filter(Boolean).length<2;if(o=w&&No||o||T&&h.matchUpStatus||h?.matchUpStatus&&[Oo,Co].includes(h.matchUpStatus)&&h.matchUpStatus||Bo,h&&I){t=gl({inContext:!0,drawDefinition:a,matchUpsMap:c}).matchUps??[];const e=T&&Xm({inContextDrawMatchUps:t,drawPosition:s,matchUpId:u})||void 0;h?.matchUpStatusCodes&&Zm({inContextDrawMatchUps:t,sourceMatchUpStatus:n,sourceMatchUpId:i,matchUpsMap:c,matchUp:h}),Object.assign(h,{drawPositions:S,winningSide:e,matchUpStatus:o}),Oc({tournamentId:r?.tournamentId,eventId:l?.eventId,context:p,drawDefinition:a,matchUp:h})}const P=gu({inContextDrawMatchUps:t,inContextMatchUp:l,drawDefinition:a,matchUpId:u}),{targetMatchUps:{winnerMatchUp:D,loserMatchUp:N,loserTargetDrawPosition:M},targetLinks:{loserTargetLink:R}}=P,A=ku({structureId:f.structureId,matchUpsMap:c});if(U&&w){if(D)if([No,Oo,Co].includes(o)){const e=ef({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}=Jm({targetMatchUp:h,drawPosition:s,matchUpsMap:c,structure:f});if(e){const e=ef({matchUpId:D.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:a,drawPosition:s,matchUpsMap:c});if(e.error)return e}}if(h?.matchUpType===Qc){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&&tf({inContextTargetMatchUp:e,drawPositionSideIndex:n,teamParticipantId:i,tournamentRecord:r,drawDefinition:a,matchUp:h})}if(R?.linkCondition===Us&&2===S.filter(Boolean).length&&!w){if(A.filter((({drawPositions:t,roundNumber:e})=>1===e&&b(t,S))).every((({matchUpStatus:t})=>[Ro,xo].includes(t)))&&N){const{structureId:t}=N,e=Yl({drawPosition:M,tournamentRecord:r,drawDefinition:a,structureId:t,matchUpsMap:c,event:d});if(e.error)return e}}return U?{...E}:Nr({result:{error:z},context:{drawPosition:s},stack:p})}function nf({drawPositions:t}){if(!t?.length)return{error:Q};const e=[].concat(...(t??[]).map((e=>t.filter((t=>t!==e)).map((t=>[e,t]))))),n=m(e.map(rf)).map((t=>t.split("|").map((t=>+t))));return{groupMatchUps:e,uniqueMatchUpGroupings:n}}function rf(t=[]){return Array.isArray(t)&&t.length?[...t].sort(e).join("|"):""}function af({groupSize:t,drawPositionOffset:e}){if(!t)return[];const n=t=>[...Array(t)].map(((t,e)=>e)),r=n(2*Math.round(t/2)+1).slice(1),i=n(r.length-1).map((()=>[]));let a=r.slice(0,r.length/2),o=r.slice(r.length/2);r.slice(1).forEach(((t,e)=>{a.forEach(((t,n)=>{i[e].push([a[n],o[n]])}));const n=a.shift(),r=a.pop(),s=o.shift();a=[n,s,...a].filter(Boolean),o=[...o,r].filter(Boolean)}));const s=a.shift(),c=a.pop(),u=o.shift();a=[s,u,...a].filter(Boolean),o=[...o,c].filter(Boolean);const d=t=>t[0].reduce(((t,e)=>t+e));return[...i].reverse().sort(((t,e)=>d(t)-d(e))).map((n=>n.filter((e=>e.every((e=>e<=t)))).map((t=>rf(t.map((t=>t+e)))))))}const of={getRoundRobinGroupMatchUps:nf,determineRoundNumber:function({rounds:t,hash:e}){return t?.length?t?.reduce(((t,n,r)=>n.includes(e)?r+1:t),void 0):{error:ae}},drawPositionsHash:rf,groupRounds:af};function sf(t){const{groupNameBase:e="Group",playoffAttributes:n,stageSequence:r=1,structureOptions:i,appliedPolicies:a,seedingProfile:o,stage:s=Jo,matchUpType:c,roundTarget:u,structureId:d,groupNames:p,drawSize:l,idPrefix:m,isMock:f,uuids:h}=t,g=t.structureName??n?.[0]?.name??zm(Jo),{groupCount:I,groupSize:U}=function({appliedPolicies:t,structureOptions:e,drawSize:n}){let r=e?.groupSize;const i=e?.groupSizeLimit||8,{validGroupSizes:a}=cf({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=Ws;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),u=nf({drawPositions:c}).uniqueMatchUpGroupings??[],d=af({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(rf(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()||wp()}({structureOrder:t,drawPositions:n,roundNumber:s,idPrefix:i,uuids:o}),d={matchUpStatus:s?Bo:No,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=Array.isArray(n)?Math.max(...n.map((({roundNumber:t})=>t??0))):0;const r=p?.[t-1]??`${e} ${t}`;return Ym({structureId:h?.pop(),structureType:us,finishingPosition:S,structureOrder:t,structureName:r,matchUps:n})})),T=Ym({structureId:d??h?.pop(),structureType:ds,finishingPosition:S,seedingProfile:o,structureName:g,stageSequence:r,structures:v,stage:s});return u&&Cr({extension:{name:to,value:u},element:T}),{structures:[T],maxRoundNumber:y,groupCount:I,links:[],groupSize:U,...E}}function cf({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 uf(t){const{roundRobinGroupsCount:e,participantsCount:n,cluster:r}=t;if(!p(n))return{seedBlocks:void 0,...Nr({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 df({roundRobinGroupsCount:t,drawSize:e}){const n="getSeedGroups";if(!p(e))return{seedGroups:void 0,...Nr({result:{error:Nn},context:{drawSize:e},stack:n})};if(t){if(!p(t))return{seedGroups:void 0,...Nr({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}=uf({participantsCount:e,roundRobinGroupsCount:t});let r=0;return{seedGroups:(n||[]).map((t=>(t||[]).map((()=>(r+=1,r)))))}}}function pf({roundRobinGroupsCount:t,participantsCount:e}){if(t){const{validGroupSizes:n}=cf({drawSize:e}),r=n?.map((t=>Math.ceil(e/t)));if(!r?.includes(t))return Nr({context:{roundRobinGroupsCount:t},result:{error:Nn}})}const{seedGroups:n}=df({drawSize:e,roundRobinGroupsCount:t}),r=n?.map((t=>Math.min(...t)))||[];return{...E,seedingThresholds:r}}function lf(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 mf({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&&[ss,cs].includes(t)&&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 ff({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}=ml({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:o}),{seedAssignments:d}=od({provisionalPositioning:t,returnAllProxies:e,drawDefinition:i,structure:o}),{positionAssignments:p}=ec({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===ds,D=!P&&h?.length,b=!P&&y===Qo&&T,M=S.flat(1/0),R=D?M?.length:0,A=a?l:m,E=el({drawDefinition:i,structure:o,matchUps:c}),C=E?0:!D&&A||A&&M.length<A&&A-M.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=Uf(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}=hf({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=tc({structure:e})?.positionAssignments,o=Uf(t),s=a?.length??0,{seedGroups:c}=df({roundRobinGroupsCount:i,drawSize:s});return hf({drawPositionBlocks:r.map((t=>tc({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}=uf({cluster:Uf(i)===ss,participantsCount:o,roundRobinGroupsCount:n});s=0;for(const t of u){if(s+1>a)break;const n=t.map((t=>t+e)),i=d(s+1,t.length).map((t=>+t+r));s+=t.length,c.push({drawPositions:n,seedNumbers:i})}return{blocks:c};function d(t,e){return Array.from(new Array(e),((e,n)=>n+t))}}({drawPositionOffset:I,seedNumberOffset:R,seedCountGoal: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 hf({drawPositionBlocks:t,positioning:e,seedGroups:n,nonRandom:r}){const i=[],{divisionGroupings:a}=mf({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!==cs?d=r?d:f(d):s%2&&d.reverse();const p=d.find((t=>!o.includes(t)));p&&(o.push(p),i.push({drawPositions:[p],seedNumbers:[n]}))}))})),{validSeedBlocks:i}}function gf({appliedPolicies:t,drawDefinition:e,seedBlockInfo:n,drawPosition:r,structureId:i,seedNumber:a}){const{structure:o}=Qs({drawDefinition:e,structureId:i});t||(t=Tu({drawDefinition:e}).appliedPolicies);let s=n?.validSeedBlocks;if(!s&&o&&(s=ff({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 If(t){const{provisionalPositioning:e,drawDefinition:n,seedingProfile:r,seedBlockInfo:i,structureId:a,randomize:o}=t,{structure:s}=Qs({drawDefinition:n,structureId:a}),{seedAssignments:c}=od({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,drawDefinition:n,structure:s}),{positionAssignments:u}=ec({structure:s}),d=u?.filter((t=>t.participantId??t.bye??t.qualifier)),p=d?.map((t=>t.drawPosition)).filter(Boolean),{appliedPolicies:l}=Tu({drawDefinition:n}),m=(i?.validSeedBlocks||s&&ff({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=>lf(t.seedValue)))),i=n.filter((t=>lf(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)),M=l?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:m,unplacedSeedParticipantIds:void 0===M||M?P:N,unplacedSeedNumbers:b,unfilledPositions:w,unplacedSeedAssignments:S}}function Uf(t){return"string"==typeof t?t:"object"==typeof t?t.positioning:void 0}function Sf({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}=Qs({drawDefinition:n,structureId:o}),{positionAssignments:m}=ec({structure:l}),f=od({provisionalPositioning:t,drawDefinition:n,structure:l}).seedAssignments,h=f.map((t=>t.seedNumber)),g=vm({drawDefinition:n,participantId:i});if(i&&!g)return Nr({result:{error:Te},context:{participantId:i},stack:p});const I=d?Fp({event:d}).flightProfile?.flights?.length:0,U=I&&I>1,S=m?.find((t=>t.participantId===i)),y=S?.drawPosition;if(y){if(!gf({drawPosition:y,drawDefinition:n,seedBlockInfo:a,structureId:o,seedNumber:s}))return Nr({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?(_c({tournamentId:e?.tournamentId,drawDefinition:n,structure:l,eventId:u}),{...E}):Nr({result:{error:mt},stack:p})}function yf({inContextDrawMatchUps:t,drawDefinition:e,assignments:n,matchUpsMap:r,structure:i}){const a=jc({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 vf({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}=Zp({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 wf(t){return`${t} must be an array`}function Tf({lineUp:t,tieFormat:e}){const n=[];if(!Array.isArray(t))return n.push(wf("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(wf("collectionAssignments")),!1):(n.push("Missing participantId"),!1)})),i=m(t.map(vo)).length===t.length;i||n.push("Duplicated participantId(s)");return{valid:r&&i,errors:n,error:n.length?Nn:void 0}}function Pf({drawDefinition:t,participantId:e,tieFormat:n,lineUp:r}){if("object"!=typeof t)return{error:j};if("string"!=typeof e)return{error:Ae};const i=Tf({lineUp:r,tieFormat:n});if(!i.valid)return i;const{extension:a}=Fr({element:t,name:Ya}),o=a?.value||{};o[e]=vf({lineUp:r});return Cr({element:t,extension:{name:Ya,value:o}}),Fc({drawDefinition:t}),{...E}}function Df({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}=yf({inContextDrawMatchUps:t,matchUpsMap:i,assignments:a,structure:o});for(const t of d)t.matchUpType===Jc&&(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&&Pf({drawDefinition:r,participantId:n,lineUp:[],tieFormat:e})}Oc({tournamentId:n?.tournamentId,context:"resetLineUps",eventId:s?.eventId,drawDefinition:r,matchUp:o})}}}));return{...E}}function bf({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 Nr({result:{error:Ae},stack:m});d=d??Fu({drawDefinition:a}),e||({matchUps:e}=gl({inContext:!0,drawDefinition:a,matchUpsMap:d}));const f=Qs({drawDefinition:a,structureId:p});if(f.error)return Nr({result:f,stack:m});const{structure:h}=f;if(!h)return{error:Ut};if(nl({drawDefinition:a,structure:h}))return Nr({result:{error:Yt},stack:m});const{seedAssignments:g}=od({provisionalPositioning:t,drawDefinition:a,structure:h}),I=g?.find((t=>t.participantId===s)),U=I?.seedNumber,{appliedPolicies:S}=Tu({tournamentRecord:i,drawDefinition:a,structure:h,event:l});if(U){if(!gf({seedNumber:U,appliedPolicies:S,drawDefinition:a,seedBlockInfo:c,drawPosition:u,structureId:p}))return Nr({result:{error:H},context:{drawPosition:u},stack:m})}const y=ec({structure:h}).positionAssignments||[],v=y?.find((t=>t.drawPosition===u));if(!v)return Nr({result:{error:X},context:{drawPosition:u},stack:m});const w=y?.map(vo).includes(s);if(w)return Nr({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=tm({inContextDrawMatchUps:e,tournamentRecord:i,drawDefinition:a,drawPosition:u,structureId:p,matchUpsMap:d,event:l});if(t.error)return Nr({result:t,stack:m})}if(T&&v.participantId!==s){const{activeDrawPositions:t}=Gl({drawDefinition:a,structureId:p});if(t.includes(u))return Nr({result:{error:Z},stack:m});Df({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&&[Zo,ts].includes(h.stage)){const e=h.stage===Qo?Qo:Jo,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;Sf({eventId:l?.eventId,provisionalPositioning:t,tournamentRecord:i,drawDefinition:a,seedingProfile:o,participantId:e,seedNumber:n,seedValue:s,structureId:p,event:l})}}if(h.structureType!==ds)!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}=ml({provisionalPositioning:t,matchUpFilters:u,drawDefinition:i,matchUpsMap:o,structure:s,event:c}),{roundMatchUps:p}=Su({matchUps:d}),{initialRoundNumber:l}=ql({drawPosition:a,matchUps:d}),m=l&&p?.[l].find((t=>t.drawPositions?.includes(a)));if(m){const t=ef({matchUpId:m.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:r,drawDefinition:i,drawPosition:a,matchUpsMap:o});if(t.error)return Nr({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{Xl({positionAssignments:y,tournamentRecord:i,drawDefinition:a,matchUpsMap:d,structure:h});const{drawPositions:t,matchUps:n,targetMatchUps:r}=yf({assignments:[v],inContextDrawMatchUps:e,drawDefinition:a,matchUpsMap:d,structure:h});if(t&&1===n?.length&&n[0].matchUpType===Qc){const e=(r?.[0].sides??[]).reduce(((e,n,r)=>t?.includes(n.drawPosition)?r:e),void 0);tf({inContextTargetMatchUp:r[0],teamParticipantId:s,matchUp:n[0],drawPositionSideIndex:e,tournamentRecord:i,drawDefinition:a})}}return xc({tournamentId:i?.tournamentId,drawDefinition:a,structure:h,event:l}),{positionAssignments:y,...E}}function Nf(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=Fu({drawDefinition:a}),Object.assign(t,{matchUpsMap:l})),p||(({matchUps:p}=gl({inContext:!0,drawDefinition:a,matchUpsMap:l})),Object.assign(t,{inContextDrawMatchUps:p}));const{positionAssignments:m}=tc({drawDefinition:a,structureId:c}),f=m?.find((t=>t.drawPosition===s));if(f?.participantId){const t=f.participantId,e=bf({inContextDrawMatchUps:p,tournamentRecord:i,drawDefinition:a,participantId:o,drawPosition:s,structureId:c,matchUpsMap:l,event:u});return e.success?U({removedParticipantId:t}):Nr({result:e,stack:d})}const h=tm({inContextDrawMatchUps:p,tournamentRecord:i,drawDefinition:a,drawPosition:s,structureId:c,matchUpsMap:l,event:u});if(h.error)return Nr({result:h,stack:d});const g=h.participantId,I=bf({inContextDrawMatchUps:p,isQualifierPosition:n,tournamentRecord:i,drawDefinition:a,participantId:o,drawPosition:s,structureId:c,matchUpsMap:l,event:u});return I.success?U({removedParticipantId:g}):Nr({result:I,stack:d});function U({removedParticipantId:t}){const{structure:n}=Qs({drawDefinition:a,structureId:c});Bc({drawPositions:[s],structure:n});return Vc({drawDefinition:a,positionAction:{[e]:o,name:r,drawPosition:s,structureId:c}}),Nr({context:{removedParticipantId:t},result:{...E},stack:d})}}function Mf(t){return function({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i}){return Nf({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i})}(t)}function Rf(t){return function({alternateParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i}){return Nf({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i})}(t)}function Af({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=Qs({drawDefinition:r,structureId:t});if(s.error)return s;const c=s.structure;if(!c)return{error:Ut};const u=tc({structure:c}).positionAssignments?.map((({drawPosition:t})=>t)),d=o?.map((({drawPosition:t})=>t));if(P(u,d).length!==u?.length)return Nr({result:{error:Nn},info:"drawPositions do not match",stack:"setPositionAssignments"});const p=Fu({drawDefinition:r}),{matchUps:l}=gl({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=Yl({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=bf({provisionalPositioning:e,inContextDrawMatchUps:l,tournamentRecord:n,drawDefinition:r,participantId:u,drawPosition:s,matchUpsMap:p,structureId:t,event:i});if(a?.error)return a}}xc({tournamentId:n?.tournamentId,drawDefinition:r,structure:c,event:i})}const a=t.map((({structureId:t})=>t));return kc({tournamentId:n?.tournamentId,eventId:i?.eventId,drawDefinition:r,structureIds:a}),{...E}}function Ef(t){return function({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i}){return Nf({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i})}(t)}function Cf({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=Fu({drawDefinition:e}),{matchUps:o}=gl({inContext:!0,drawDefinition:e,matchUpsMap:a}),{structure:s}=Qs({drawDefinition:e,structureId:r});if(!s)return{error:Ut};let c;if(c=s.structureType===ds?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};Df({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)Of({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:s,matchUpsMap:i,structure:a,event:o});else{const t=mi(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?Of({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)),Df({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;Bc({structure:s,drawPositions:n});if(Vc({drawDefinition:e,positionAction:{name:"swapDrawPositionAssignments",drawPositions:n,structureId:r}}),xc({tournamentId:t?.tournamentId,drawDefinition:e,structure:s,event:i}),i.eventType===Xd){const r=ml({matchUpFilters:{matchUpTypes:[Jc]},inContext:!0,structure:s}).matchUps.filter((t=>t.drawPositions?.some((t=>n.includes(t))))),a=ml({structure:s,matchUpFilters:{matchUpTypes:[Jc]}}).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);tf({inContextTargetMatchUp:r,drawPositionSideIndex:u,teamParticipantId:n,tournamentRecord:t,drawDefinition:e,matchUp:c,event:i})}}))}))}return kc({drawDefinition:e,structureIds:[r]}),{...E}}function Of({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=$m({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:l,matchUpsMap:i});return m.error?m:(m=$m({drawPosition:p,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:l,matchUpsMap:i}),m.error?m:(Yl({drawPosition:p,tournamentRecord:e,drawDefinition:n,structureId:l,matchUpsMap:i,event:o}),m=bf({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:l,participantId:d,matchUpsMap:i,event:o}),m.error?m:{...E}))}function Ff(t){return Cf(t)}function kf({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 u=(e?.participants??[]).find((t=>t.participantId===i));if(e&&!u)return{error:Te};const{structure:d}=Qs({drawDefinition:r,structureId:a});if(!d)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:p}=od({drawDefinition:r,structure:d}),l=p?.map((t=>t.seedNumber)),m=p?.find((t=>t.participantId===i));if(m){const t="string"==typeof o?o.includes("-")&&o.split("-").map((t=>parseInt(t))).join("-")||parseInt(o)>0&&parseInt(o)||"":o&&o>0&&o||"";m.seedValue=t}else{const t={seedNumber:Math.max(0,...l||[])+1,participantId:i};o&&(t.seedValue=o),d.seedAssignments||(d.seedAssignments=[]),d.seedAssignments.push(t)}return _c({tournamentId:e?.tournamentId,eventId:c?.eventId,drawDefinition:r,structure:d}),{...E}}function _f({drawDefinition:t,structureId:e}){if(!t)return{error:j};const{structure:n}=Qs({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 xf({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}=Zs({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 Lf({withStageGrouping:t,tournamentRecord:e,stageSequences:n,stageSequence:r,roundTarget:i,stages:a,stage:o}){if(!e)return{error:x};const s={},c=[];for(const u of e.events||[]){const{structures:e,stageStructures:d}=xf({withStageGrouping:t,stageSequences:n,stageSequence:r,roundTarget:i,stages:a,event:u,stage:o});if(e&&c.push(...e),d)for(const t of Object.keys(d))s[t]||(s[t]=[]),s[t].push(...d[t])}return{structures:c,stageStructures:s}}function Bf(t){if(!t?.drawDefinition)return!1;const e=hl(t),n=e?.includesTeamMatchUps;let{completedMatchUps:r,pendingMatchUps:i,upcomingMatchUps:a}=e||{};n&&(r=r?.filter((({matchUpType:t})=>t===Qc)),i=i?.filter((({matchUpType:t})=>t===Qc)),a=a?.filter((({matchUpType:t})=>t===Qc)));return!!(r?.length&&!i?.length&&!a?.length)}function Vf(t){const{drawDefinition:e,structureId:n}=t;if(!e)return{error:j};const{playoffStructures:r}=_f({drawDefinition:e,structureId:n});if(!r?.length)return!1;const i=e?.entries?.filter((t=>t?.entryStatus&&td.includes(t.entryStatus)))?.length??0;let a=0;return(r||[]).reduce(((t,e)=>{const n=tc({structure:e}).positionAssignments??[],r=n?.filter((t=>(t.participantId&&a++,t?.bye??t?.participantId))).length;return!(!r||!t)}),!!r.length)||a===i}function jf({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=jf({accessors:a,significantCharacters:t,value:e});r.push(...n)}))}else if(n=n[i],a.length){const e=jf({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 Gf({policyAttributes:t,idCollections:e,participants:n,participant:r}){if(!Array.isArray(t))return{error:Zt};if(!r)return{error:Me};const i=[];t.forEach((t=>{const{directive:a,groupings:o,key:s,significantCharacters:c}=t||{};if(s){const t=s.split(".");i.push(...jf({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 qf({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}=Gf({participants:e,policyAttributes:n,idCollections:r,participant:a});return{...t,values:o}}))}function $f({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 Wf(t){const{unfilledPositions:e,chunkedDrawPositions:n}=t,r=$f(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=Hf(e);return!t.includes(n)}}(n),a=n.filter((t=>!i.includes(t))).filter((t=>{const e=Hf(t);return!r[e]?.includesGroupsToAvoid}));return{unassigned:n,unpaired:i,pairedNoConflict:a}}))}function Hf(t){return Number(t%2?t+1:t-1)}function zf({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=$f(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}):Wf({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 Yf({positionAssignments:t,participantIds:e}){const n=t.map((t=>t.participantId));return e.filter((t=>!n.includes(t)))}function Kf({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=Yf({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=zf({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 Jf({isRoundRobin:t,groupedParticipants:e}){const n=[];return t?e.forEach((t=>{const e=nf({drawPositions:t.map((t=>t.drawPosition))}).uniqueMatchUpGroupings??[],r=Object.assign({},...t.map((t=>({[t.drawPosition]:t}))));e.forEach((e=>{b(r[e[0]].values||[],r[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 Qf({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=Jf({isRoundRobin:i,groupedParticipants:[[r,o]]}),c=t.find((t=>t.drawPosition===e)),u=Jf({isRoundRobin:i,groupedParticipants:[[c,o]]});return!s.length&&!u.length}));if(o.length)return{drawPosition:r.drawPosition,possibleDrawPositions:o}})).filter(Boolean)})).flat(1)}function Zf(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=mi(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}=Kf({...t,candidatePositionAssignments:m,allGroups:c,groupKey:d});d=e,m.forEach((t=>{t.drawPosition===r&&(t.participantId=n)}))}));let h=qf({candidatePositionAssignments:m,participantsWithGroupings:n,policyAttributes:o,idCollections:s}),g=N(h,p),I=Jf({groupedParticipants:g,isRoundRobin:l}),U=0;for(;U<20&&I.length;){const t=Qf({positionedParticipants:h,potentialDrawPositions:f,avoidanceConflicts:I,drawPositionGroups:a,isRoundRobin:l});if(t.length){const e=Xf({candidatePositionAssignments:m,swapOptions:t});e.error&&console.log({result:e}),h=qf({candidatePositionAssignments:m,participantsWithGroupings:n,policyAttributes:o,idCollections:s}),g=N(h,p),I=Jf({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 Xf({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 th({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:Qt};const{candidatesCount:g=1,policyAttributes:I,targetDivisions:U}=m;let{roundsToSeparate:S}=m;const y="randomUnseededSeparation",{structure:v}=Qs({drawDefinition:c,structureId:l}),{matchUps:T}=ml({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}=ec({structure:v}),D=pu({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:d}).participantsWithGroupings,b=P?.filter((t=>!t.participantId)),M=P?.map((t=>t.drawPosition)),R=v?.structureType===ds,A=R?{structure:v,matchUps:T,allDrawPositions:M,roundsToSeparate:S}:{matchUps:T,allDrawPositions:M,roundsToSeparate:S},{drawPositionGroups:C,drawPositionChunks:O}=R?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===ou)).map((t=>t.participantId)),teamParticipants:d.filter((t=>t.participantType===cu)).map((t=>t.participantId)),pairParticipants:d.filter((t=>t.participantType===su)).map((t=>t.participantId))},k=function({targetParticipantIds:t,policyAttributes:e,idCollections:n,participants:r}){if(!Array.isArray(e))return{error:Zt};if(!Array.isArray(r))return{error:Re};const i={};return t.forEach((t=>{const a=r.find((e=>e.participantId===t)),{values:o}=Gf({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 Nr({result:k,stack:y});const _=Object.assign({},...n.map((t=>{const e=Object.keys(k).filter((e=>(k[e]??[]).includes(t)));return{[t]:e}}))),x=Yf({participantIds:n,positionAssignments:P});if(x.length>(b?.length||0))return{error:Ke};let L;const B=x.length,V=w(0,g).map((()=>Zf({initialPositionAssignments:P,participantsWithGroupings:D,unseededParticipantIds:n,opponentsToPlaceCount:B,pairedPriority:!1,unseededByePositions:a,participantIdGroups:_,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((()=>Zf({initialPositionAssignments:P,participantsWithGroupings:D,unseededParticipantIds:n,opponentsToPlaceCount:B,pairedPriority:!0,unseededByePositions:a,participantIdGroups:_,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=(tc({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=Yl({tournamentRecord:s,drawDefinition:c,seedBlockInfo:u,structureId:l,matchUpsMap:p,event:h,...t});if(e.error)return Nr({result:e,stack:y})}else if(t.participantId){const e=bf({automaticPlacement:!0,inContextDrawMatchUps:i,tournamentRecord:s,drawDefinition:c,seedBlockInfo:u,structureId:l,matchUpsMap:p,event:h,...t});if(e.error)return Nr({result:e,stack:y,context:{assignment:t}})}return{...E}}function eh({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}=Qs({drawDefinition:a,structureId:u})),u||({structureId:u}=d);const{positionAssignments:m}=ec({structure:d}),{seedAssignments:h}=od({provisionalPositioning:t,drawDefinition:a,structure:d}),g=h?.map((t=>t.participantId)).filter(Boolean),{stage:I,stageSequence:U}=d,S=I===Qo?Fr({element:d,name:to})?.extension?.value:void 0,y=ad({provisionalPositioning:t,drawDefinition:a,stageSequence:U,entryStatuses:Xu,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 Nr({result:{error:Ke},context:{unseededParticipantsCount:v.length,unfilledDrawPositionsCount:w?.length},stack:"positionUnseededParticipants"});const{appliedPolicies:T}=Tu({tournamentRecord:i,drawDefinition:a,event:l});let P=T?.[wa];if(d.stage===ts){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?th({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=bf({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 Nr({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 nh(t){const e=t.structure??Qs(t).structure,r="positionQualifiers",i=[];if(e.stage===Zo)return Nr({result:{error:At},stack:r});const{unplacedRoundQualifierCounts:a,positionAssignments:o,roundDrawPositions:s}=function({drawDefinition:t,structure:e,structureId:r}){e||({structure:e}=Qs({drawDefinition:t,structureId:r}));r||({structureId:r}=e);const{positionAssignments:i}=ec({structure:e}),{stage:a,stageSequence:o}=e,{qualifiersCount:s,roundQualifiersCounts:c}=wm({drawDefinition:t,stageSequence:o,structureId:r,stage:a}),u=(c?Object.keys(c):[]).map((t=>n(t))),{matchUps:d}=ml({structure:e}),{roundProfile:p}=Su({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 Nr({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 rh({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=ah(N(e.drawPositions,2));let i,a=t[r.length];for(;i=ih(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 ih(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 ih(e?n:t[Math.round(Math.random())],e)}return ih(n<r?t[1]:t[0],e)}function ah(t){const e=Math.floor(t.length/2);return t.length>2?[ah(t.slice(0,e)),ah(t.slice(e))]:t}function oh({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:n,drawDefinition:r,seedingProfile:i,seedBlockInfo:a,byesToPlace:o,structure:s}){a||(a=ff({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}=ec({structure:n}),{seedAssignments:i}=od({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)=>lf(t.seedValue)-lf(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=rh({orderedSortedFirstRoundSeededDrawPositions:I,validSeedBlocks:p,byesToPlace:o});return{strictSeedOrderByePositions:sh({orderedSeedDrawPositions:I,relevantMatchUps:e}).slice(0,o),blockSeedOrderByePositions:sh({orderedSeedDrawPositions:U,relevantMatchUps:e}).slice(0,o),isLuckyStructure:u,positionedSeeds:l,isContainer:d,isFeedIn:c}}function sh({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 ch({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}=Qs({drawDefinition:i,structureId:c})),c||(c=u?.structureId);const h=!(u?.structures??u?.stage===Qo),{byesCount:g,placedByes:I,relevantMatchUps:U}=function({provisionalPositioning:t,drawDefinition:e,matchUpsMap:n,structure:r,event:i}){const{matchUps:a,roundMatchUps:o}=ml({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:{isCollectionMatchUp:!1},matchUpsMap:n,structure:r,event:i}),s=o?.[1]||[],c=r?.structureType===ds,u=c?a:s,d=c?r?.structures?.length||0:a.length,{structureId:p,stage:l,stageSequence:m}=r,f=ad({entryStatuses:td,provisionalPositioning:t,drawDefinition:e,stageSequence:m,structureId:p,stage:l}),{qualifiersCount:h}=wm({provisionalPositioning:t,drawDefinition:e,stageSequence:m,structureId:p,stage:l}),g=f.length+h,{positionAssignments:I,unassignedPositions:U}=ec({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!==Zo&&(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}=oh({provisionalPositioning:t,relevantMatchUps:U,appliedPolicies:r,drawDefinition:i,seedingProfile:o,seedBlockInfo:a,byesToPlace:S,structure:u}),P=u?.structureType&&[ds,us].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===Qo,{positionAssignments:p}=ec({structure:s}),l=p?.filter((t=>t.participantId)).map((t=>t.drawPosition)),{matchUps:h,roundMatchUps:g}=ml({provisionalPositioning:t,matchUpFilters:{isCollectionMatchUp:!1},structure:s}),I=g?.[1]||[],U=s.structureType===ds?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}=ff({provisionalPositioning:t,allPositions:!0,appliedPolicies:i,drawDefinition:a,structure:s}),M=b?.map((t=>t.drawPositions?.map((t=>t+y))));let R;if(c){const t=S.length,{seedBlocks:e}=uf({cluster:Uf(u)===ss,participantsCount:t});R=e.map((t=>t.map((t=>t+y)))).map(D).filter((t=>t.length))}else R=d?M?.map((t=>t.filter(P))):M?.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=R.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 M=[].concat(...D);if(!p)for(;b.length;){const t=b.find((t=>{return e=t,(M||[]).every((t=>t%2?e!==t+1:e!==t-1));var e}));t?(M.push(t),b=b.filter((e=>e!==t))):(M.push(...b),b=[])}P&&(M=f(M),Xn({ignoreSeededByes:P})&&console.log({byePositions:M}));const R=M.slice(0,S);for(const e of R){const r=Yl({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:R}}function uh({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}=Qs({drawDefinition:a,structureId:d})),d||(d=l?.structureId),r||(r=Tu({drawDefinition:a}).appliedPolicies),!i){const e=l&&ff({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}=If({provisionalPositioning:t,randomize:!0,drawDefinition:r,seedingProfile:i,seedBlockInfo:a,structureId:s,event:u}),{appliedPolicies:l}=Tu({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=bf({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 dh({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||(nr(),c=mi(c,!1,!0));const U=e=>(t||rr(),Nr({result:e,stack:"automatedPositioning"})),S=Qs({drawDefinition:c,structureId:d});if(S.error)return U(S);const y=S.structure;if(!y)return{error:Ut};o||(o=Tu({drawDefinition:c,structure:y,event:g})?.appliedPolicies);const{qualifiersCount:v}=wm({stageSequence:y.stageSequence,provisionalPositioning:e,stage:y.stage,drawDefinition:c,structureId:d}),w=Xu,T=ad({stageSequence:y.stageSequence,provisionalPositioning:e,stage:y.stage,placementGroup:s,drawDefinition:c,entryStatuses:w,structureId:d});if(!T?.length&&!v)return P={...E},t||rr(),P;var P;p=p??Fu({drawDefinition:c}),n||({matchUps:n}=gl({inContext:!0,drawDefinition:c,matchUpsMap:p}));let D=[];const b=ff({provisionalPositioning:e,appliedPolicies:o,drawDefinition:c,seedingProfile:u,structure:y});if(b.error)return b;const{validSeedBlocks:N}=b;I.push({validSeedBlocks:N});const M=a?ym({withIndividualParticipants:!0,tournamentRecord:a})?.participants:[];if(Uf(y.seedingProfile||u)===cs){let t=i?ch({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=uh({seedingProfile:y.seedingProfile?{positioning:y.seedingProfile}:u,provisionalPositioning:e,inContextDrawMatchUps:n,tournamentRecord:a,appliedPolicies:o,validSeedBlocks:N,drawDefinition:c,seedBlockInfo:b,participants:M,matchUpsMap:p,structure:y,event:g}),t.error)return U(t);I.push({seedPositions:t.seedPositions,action:"positionSeedBlocks"})}else{if(f!==Ns){const t=uh({seedingProfile:y.seedingProfile?{positioning:y.seedingProfile}:u,provisionalPositioning:e,inContextDrawMatchUps:n,tournamentRecord:a,appliedPolicies:o,validSeedBlocks:N,drawDefinition:c,seedBlockInfo:b,participants:M,matchUpsMap:p,structure:y,event:g});if(t.error)return U(t);I.push({action:"positionSeedBlocks",seedPositions:t.seedPositions})}const t=i?ch({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 R={};if(!m){let t=nh({inContextDrawMatchUps:n,tournamentRecord:a,appliedPolicies:o,validSeedBlocks:N,drawDefinition:c,seedBlockInfo:b,participants:M,matchUpsMap:p,structure:y});if(t.error)return U(t);if(t.conflicts&&(R.qualifierConflicts=t.conflicts),I.push({action:"positionQualifiers",qualifierDrawPositions:t.qualifierDrawPositions}),t=eh({provisionalPositioning:e,inContextDrawMatchUps:n,unseededByePositions:D,multipleStructures:r,tournamentRecord:a,drawDefinition:c,seedBlockInfo:b,participants:M,matchUpsMap:p,structureId:d,structure:y,drawSize:h,event:g}),t.error)return U(t);t.conflicts&&(R.unseededConflicts=t.conflicts),I.push({action:"positionUnseededParticipants"})}const{positionAssignments:A}=tc({drawDefinition:c,structure:y});return kc({drawDefinition:c,structureIds:[d]}),t||rr(),{positionAssignments:A,conflicts:R,...E,positioningReport:I}}function ph(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(!Bf({drawDefinition:i,structureId:o})&&!n)return{error:W};const d=_f({drawDefinition:i,structureId:o}).playoffStructures?.sort(((t,e)=>Js(t)-Js(e))),p=[],l=[];if(d)for(const t of d){const{structureId:o}=t,u=dh({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 lh({drawDefinition:t,orderMap:e}){return t?("object"==typeof e&&Object.values(e).every((t=>p(t)))||Nr({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}}function mh({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[fs,ms,ls,cs].includes(t.target.feedProfile)?(r?.targets.push(n),s?.sources.push(e)):t.target.feedProfile===ps&&(s?.drawSources.push(e),r?.drawTargets.push(n)),o[n]=o[n]||t.target.feedProfile===ps,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===Qo){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!==Xo&&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 fh({drawDefinition:t}){const{maxQualifyingDepth:e,structureProfiles:n}=mh({drawDefinition:t});for(const r of t.structures){const t=n[r.structureId];t.distanceFromMain&&(r.stageSequence=e+1-t.distanceFromMain)}return{...E}}function hh(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:Mr};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&&Pl({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 gh({creationTime:t=!0,removePriorValues:e,tournamentRecord:n,duplicateValues:r,participantId:i,timeItem:a}){if(!n)return{error:x};if(!i)return{error:Ae};const o=Tl({tournamentRecord:n,participantId:i});return o.error?o:hh({element:o.participant,removePriorValues:e,duplicateValues:r,creationTime:t,timeItem:a})}function Ih(t){const{removePriorValues:e,tournamentRecord:n,duplicateValues:r,creationTime:i,timeItem:a}=t;return n?hh({element:n,removePriorValues:e,duplicateValues:r,creationTime:i,timeItem:a}):{error:x}}function Uh(t){const{removePriorValues:e,duplicateValues:n,creationTime:r,timeItem:i,event:a}=t;return a?hh({removePriorValues:e,duplicateValues:n,element:a,creationTime:r,timeItem:i}):{error:Pt}}function Sh({tournamentRecord:t,drawDefinition:e,structure:n,link:r}){if(!t)return{error:x};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=Qs({drawDefinition:t,structureId:a});if(o.error)return Nr({stack:"attachQualifyingStructure",context:{targetStructureId:a},result:o});t.structures||(t.structures=[]);t.links||(t.links=[]);t.structures.push(n),t.links.push(i),fh({drawDefinition:t});const s=ml({structure:n})?.matchUps||[];return Ec({drawDefinition:t,tournamentId:e,matchUps:s,eventId:r}),kc({drawDefinition:t,structureIds:[n.structureId]}),{...E}}({tournamentId:t.tournamentId,drawDefinition:e,structure:n,link:r});if(i.error)return i;return Ih({tournamentRecord:t,timeItem:{itemType:"attachQualifyingStructures",itemValue:{structureId:n.structureId,drawId:e.drawId}}}),i}function yh({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:Nn};if(!t)return{error:j};const n=Object.assign({},...e.map((t=>{if(!Ui(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}}function vh({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),Fc({drawDefinition:t}),{...E}}function wh({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(ml({structure:s}).matchUps.some((({score:t})=>Gc({score:t})))){const n=Tu({tournamentRecord:t,drawDefinition:e,structure:s,event:r})?.appliedPolicies;if(!(i??n?.[Ta]?.allowDeletionWithScoresPresent?.structures))return{error:qn}}const c=a.find((({stage:t,stageSequence:e})=>t===Jo&&1===e)),u=n===c?.structureId,d=a.filter((({stage:t})=>t===Qo)).map(wi("structureId"));if(u&&!d.length)return{error:F};const p=a.map(wi("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}=Qs({structureId:t,drawDefinition:e}),{matchUps:i}=ml({structure:r}),a=So(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}=gl({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(wi("matchUpId"));l.push(...t),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return m&&fh({drawDefinition:e}),Cc({tournamentId:t?.tournamentId,matchUpIds:l,action:"removeStructure",eventId:r?.eventId,drawDefinition:e}),kc({drawDefinition:e,eventId:r?.eventId}),{...E,removedMatchUpIds:l,removedStructureIds:o}}function Th({stageSequence:t=1,drawDefinition:e,drawSize:n,stage:r}){if(!e)return{error:j};if(!rd({drawDefinition:e,stage:r}))return{error:At};const i=function({stage:t,drawDefinition:e}){return Xu.reduce(((n,r)=>(id({drawDefinition:e,entryStatus:r,stage:t})||0)+n),0)}({drawDefinition:e,stage:r}),{qualifiersCount:a}=wm({drawDefinition:e,stageSequence:t,stage:r});if(n<i+a)return{error:rt};const{entryProfile:o}=_u({attributes:[{[r]:{drawSize:n}}],drawDefinition:e});return kc({drawDefinition:e}),{...E,entryProfile:o}}function Ph({qualifiersCount:t=0,drawDefinition:e,stage:n}){return e?rd({drawDefinition:e,stage:n})?n!==Jo?{error:rt,info:"qualifiersCount can only be set for main stage"}:(_u({attributes:[{[n]:{qualifiersCount:t}}],drawDefinition:e}),kc({drawDefinition:e}),{...E}):{error:At}:{error:j}}function Dh(t){return function({drawDefinition:t,drawSize:e}){if(!t)return{error:j};const n=Th({stage:Xo,stageSequence:1,drawDefinition:t,drawSize:e});return n.error?n:(kc({drawDefinition:t}),{...E})}(t)}function bh({tournamentRecord:t,drawDefinition:e,participantId:n,structureId:r}){const i="removeSeededParticipant";if(!t)return{error:x};if(!e)return{error:j};const a=(e.structures??[]).find((t=>t.structureId===r));if(!a)return Nr({result:{error:Ut},stack:i});if(!a.stage||![Jo,Qo].includes(a.stage)||a.stage===Jo&&1!==a.stageSequence)return Nr({result:{error:$},stack:i});const o=a.seedAssignments?.find((t=>t.participantId===n));return o?{...E}:Nr({info:"participant not seeded",result:{error:On},context:{participantId:n}})}function Nh({targetEntryRound:t=1,finishingPositions:e,sourceRoundNumber:n,sourceStructureId:r,targetStructureId:i,linkType:a=gs}){if(!r||!i)return{error:It};return{link:br({linkType:a,source:{roundNumber:n,structureId:r,finishingPositions:e},target:{feedProfile:ps,roundNumber:t,structureId:i}})}}function Mh({roundPosition:t,roundNumber:e,idPrefix:n,uuids:r}){return n?`${n}-${e}-${t}`:r?.pop()||wp()}function Rh({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:Mh({roundPosition:d,roundNumber:n,idPrefix:i,uuids:o})};u.push(f);const h={drawPositions:f.children.map((t=>t?.drawPosition)).filter(Boolean),matchUpStatus:Bo,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 Ah({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}=Rh({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}=Rh({nodes:m,matchUpType:a,roundNumber:h,idPrefix:s,matchUps:f,isMock:u,uuids:d})),h++;const g=h-1;return f=Ul({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 Eh(t){const e="generateQualifyingStructure";if(!t.drawDefinition)return Nr({result:{error:j},stack:e});if(t.drawSize&&!p(t.drawSize)||t.participantsCount&&!p(t.participantsCount)||t.qualifyingPositions&&!p(t.qualifyingPositions))return Nr({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 Nr({result:{error:it},context:{drawSize:n},stack:e});if(i&&i>=t.drawSize)return Nr({result:{error:Nn},context:{drawSize:n,qualifyingPositions:i},stack:e});let S,y,v,w,T,P=0;const{structureProfiles:D}=mh({drawDefinition:u}),b=D[o];if(!b)return Nr({result:{error:Ut},context:{targetStructureId:o},stack:e});const N=u.matchUpType,M=f?`${f}-`:"",R=b.stage===Qo,A=c?.[Ua]?.namingConventions?.pre??rl[Ua]?.namingConventions?.pre,C=R&&A?`${A}-`:"",O=l??(M?`${C}${zm(Qo)} ${M}`:`${C}${zm(Qo)}`);if(h===Bs){const{maxRoundNumber:t,structures:e,groupCount:r}=sf({structureName:l??O,structureId:m??U?.pop(),stage:Qo,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}=Ah({qualifyingRoundNumber:r,qualifyingPositions:i,matchUpType:N,idPrefix:g,drawSize:n,isMock:I,uuids:U})),S||(S=y),v=Ym({structureName:l??O,structureId:m??U?.pop(),qualifyingRoundNumber:S,stage:Qo,matchUpFormat:d,stageSequence:1,matchUpType:N,roundLimit:S,matchUps:w}),f&&Cr({extension:{name:to,value:f},element:v}),P=w?.filter((t=>t.roundNumber===S))?.length;const F=h===Bs?hs:gs,k=v&&S&&Nh({sourceStructureId:v.structureId,sourceRoundNumber:S,targetStructureId:o,finishingPositions:T,linkType:F})?.link;return{qualifyingDrawPositionsCount:n,qualifiersCount:P,...E,structure:v,link:k}}function Ch(t){const e=t.tournamentRecord;if(!e)return{error:x};const n=function(t){if(!t.drawDefinition)return{error:j};if(!t.targetStructureId)return{error:It};const e=Eh(t);if(e.error)return e;const{structure:n,link:r}=e;return n&&r?Sh({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 Ih({tournamentRecord:e,timeItem:{itemType:"addQualifyingStructures",itemValue:br({drawId:o.drawId,qualifyingRoundNumber:r,qualifyingPositions:i,targetStructureId:a,structureName:s,matchUpType:c,drawSize:u,drawType:d})}}),n}function Oh({drawDefinition:t,matchUpsMap:e,structureId:n}){const r=Qs({drawDefinition:t,structureId:n});if(r.error)return Nr({result:r});const{matchUps:i}=ml({structure:r.structure,matchUpsMap:e});return{...Su({matchUps:i}),matchUps:i,matchUpsMap:e}}function Fh({finishingPositions:t,drawDefinition:e,structureId:n}){const{roundProfile:r}=Oh({drawDefinition:e,structureId:n}),i=r&&Object.keys(r);return i?.reduce(((e,n)=>(kh(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 kh(t){return[m(t?.finishingPositionRange?.loser||[]),m(t?.finishingPositionRange?.winner||[])]}function _h(t){return kh(t).map((t=>w(t[0],t[1]&&t[1]+1||t[0]+1)))}function xh({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!==Qo)).map((({structureId:t})=>t))).map((e=>{const{roundProfile:n}=Oh({drawDefinition:t,matchUpsMap:r,structureId:e}),i=n&&Object.values(n);return i?.map(_h).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 Lh({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=xh({drawDefinition:i});if(o.error)return o;const s=o.positionsPlayedOff,c=Fh({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=Fh({finishingPositions:s,drawDefinition:i,structureId:a}),p=d?Object.values(d):[],l=d?p.reduce(((t,e)=>t.includes(e.roundNumber)?t:t.concat(e.roundNumber)),[]).map((t=>n(t))):[],m=u.filter((t=>!l.includes(t))).sort(e),{roundProfile:f}=Oh({drawDefinition:i,structureId:a}),h=m.map((t=>{const e=f?.[t].finishingPositionRange.loser,[n,r]=e??[0,0];return w(n,(r||n)+1)})).flat().sort(e),{playoffRoundsRanges:g}=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:m,roundProfile:f}),I=[...m,...l];return{playoffPositionsReturned:h,playedOffSourceRounds:l,playoffRoundsRanges:g,playoffSourceRounds:m,sourceRounds:I,roundProfile:f}}function Bh({drawDefinition:t,structureId:e}){if(!t)return{error:j};const{matchUps:n,matchUpsMap:r}=Vl({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:i,positionsPlayedOff:a}=xh({drawDefinition:t,matchUpsMap:r}),{structures:o}=Zs({drawDefinition:t}),s=o.filter((t=>!e&&t.stage!==Xo||t.structureId===e)),c={};for(const e of s){const r=e?.structureId,a=Vh({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 Vh({playoffPositions:t,drawDefinition:n,structure:r,matchUps:i}){const a=r?.structureId,{links:o}=hu({drawDefinition:n,structureId:a});if(r.structureType===ds||r.structures){const t=tc({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=[]}=xh({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!==Us)).map((t=>t.source?.roundNumber))||[],c=o?.source?.filter((t=>t.linkCondition===Us)).map((t=>t.source?.roundNumber))||[],u=Lh({excludeRoundNumbers:s,playoffPositions:t,drawDefinition:n,structureId:a}),d=u?.playoffSourceRounds?[...u?.playoffSourceRounds||[]]:void 0,p=[...u?.playoffRoundsRanges||[]],{roundProfile:l,error:m}=u;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(d&&s===a.length){d.push(t);const e=l?.[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};p.push(a)}}}return d&&d.sort(e),p.sort(((t,e)=>t.roundNumber-e.roundNumber)),{playoffRounds:d,playoffRoundsRanges:p,error:m}}function jh({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=Mh({roundPosition:f.roundPosition,roundNumber:n,idPrefix:i,uuids:s}),g={roundPosition:f.roundPosition,drawPositions:[d],matchUpStatus:Bo,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 Gh(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=[],M=1;let R=w(0,a).map(((t,e)=>({drawPosition:e+1+y}))),A=y+1;for(const t of U){if(({roundNodes:D,matchUps:N}=Rh({matchUpType:l,roundNumber:M,idPrefix:m,matchUps:N,isMock:f,nodes:R,uuids:h})),M++,n.includes(t)){const e=w(0,g(n)[t]),r=T+1-M,i=s?.includes(r)??u?.includes(M);e.forEach((()=>{const t=!i&&A||void 0;({roundNodes:D,matchUps:N,drawPosition:A}=jh({drawPosition:t,nodes:D,matchUpType:l,roundNumber:M,idPrefix:m,matchUps:N,isMock:f,uuids:h,fed:b})),M++,b+=1}))}R=D}T!==M-1&&console.log("ERROR");N=Ul({finishingPositionOffset:p?a-y:c,positionsFed:y,roundsCount:T,matchUps:N,fmlc:I});const E=D?.length?D[0]:D;return E&&(E.roundNumber=M-1,E.matchUps=N),{draw:E,matchUps:N,roundsCount:T}}function qh(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=Jo,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],M=r&&`${r} `||"",R=o?.[b]??i?.[b],A=t.structureName||R?.name||N?.name&&(n?`${M}${N?.name}`:N.name)||`${M}${b}`,C=R?.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?Gh(F):Ah(F),_=Ym({structureAbbreviation:C,stageSequence:s,structureName:A,matchUpType:P,roundOffset:p,structureId:O,matchUps:k,stage:h});y.push(...k),v.push(_);const x=Math.ceil(Math.log(g)/Math.log(2)),L=d?Math.min(d-p,x):!a||D<a?x: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}=qh({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(_.structureId&&D){const e={linkType:Is,source:{roundNumber:t,structureId:_.structureId},target:{roundNumber:1,feedProfile:ms,structureId:D}};N&&_&&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:_.structureId,matchUps:y,structureName:A,structures:v,links:T,...E}}function $h(t){const{finishingPositionOffset:e=0,playoffAttributes:n,stageSequence:r=1,staggeredEntry:i,structureName:a,stage:o=Jo,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?Gh(m):Ah(m),h=Ym({structureName:a||n?.[0]?.name||zm(Jo),structureId:c||l?.pop(),stageSequence:r,matchUpType:s,matchUps:f,stage:o}),g=[h],I=[];if(d>2){const r=d/2,{matchUps:i}=Ah({finishingPositionOffset:e+r,idPrefix:u&&`${u}-c`,drawSize:r,matchUpType:s,isMock:p}),o=zm(Zo),c=n?.["0-1"]?.name??t.consolationStructureName??(a?`${a} ${o}`:o),m=Ym({structureName:c,matchUps:i,structureId:l?.pop(),stage:Zo,stageSequence:1,matchUpType:s});g.push(m);const f={linkType:Is,source:{roundNumber:1,structureId:h.structureId},target:{roundNumber:1,feedProfile:ms,structureId:m.structureId}};I.push(f)}return{...E,structures:g,links:I}}function Wh({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?ms:fs,u=r-e<=2?r-e:2*(r-e-2)+2,d={linkType:Is,source:{roundNumber:r,structureId:n.structureId},target:{feedProfile:i,roundNumber:u,structureId:t.structureId}},p=s[r-1];return p&&(d.target.groupedOrder=p),Xn()&&(d.source.structureName=n.structureName,d.target.structureName=t.structureName),2===r&&a&&(d.linkCondition=Us,d.target.feedProfile=ms),o.includes(u)?d:void 0})).filter(Boolean)}function Hh(t){const{playoffStructureNameBase:e,finishingPositionOffset:n,stageSequence:r=1,playoffAttributes:i,structureNameMap:a,staggeredEntry:o,stage:s=Jo,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?Gh(f):Ah(f),I=t.structureName??i?.[0]?.name??zm(Jo),U=Ym({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}=Gh({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||`${zm(Zo)} ${d+1}`,I=r?.[g]||g,U=t?`${t} ${I}`:I,S=Ym({matchUps:m,stage:Zo,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:Wh({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}=Ah({idPrefix:p&&`${p}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:l}),n=i?.["3-4"]?.name??zm(ts),r=a?.[n]||n,o=e?`${e} ${r}`:r,s=Ym({structureId:m?.pop(),matchUps:t,stageSequence:2,stage:ts,structureName:o,matchUpType:c}),u={linkType:Is,source:{roundNumber:g-1,structureId:U.structureId},target:{structureId:s.structureId,feedProfile:ms,roundNumber:1}};S.push(s),y.push(u)}}return{structures:S,links:y,...E}}function zh(t){const{finishingPositionOffset:e,stageSequence:n=1,playoffAttributes:r,policyDefinitions:i,feedsFromFinal:a,staggeredEntry:o,structureName:s,stage:c=Jo,structureId:u,matchUpType:d,skipRounds:p,feedRounds:l,idPrefix:m,drawSize:f,isMock:h,uuids:g,fmlc:I}=t,U=t.feedPolicy||i?.[Da],S={finishingPositionOffset:e,matchUpType:d,skipRounds:p,drawSize:f,idPrefix:m,isMock:h,uuids:g},{matchUps:y}=o?Gh(S):Ah(S),v=Ym({structureName:s||r?.[0]?.name||zm(Jo),structureId:u||g?.pop(),stageSequence:n,matchUpType:d,matchUps:y,stage:c}),w=[v],T=[],P=f/2,{matchUps:D,roundsCount:b}=Gh({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??zm(Zo),n=t.playoffStructureNameBase?`${t.playoffStructureNameBase} ${e}`:e,i=Ym({matchUps:D,structureId:g?.pop(),stage:Zo,stageSequence:1,structureName:n,matchUpType:d});w.push(i);const a=Wh({consolationStructure:i,mainStructure:v,roundsCount:b,feedPolicy:U,fmlc:I});T.push(...a)}return{...E,structures:w,links:T}}function Yh({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?.[Da];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=Bh({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 Nr({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 Nr({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&&Ts||t.drawType||Ts;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:ts,stageSequence:o,matchUpType:d,drawSize:g,isMock:f,uuids:h},b=({playoffStructures:t,playoffLinks:n})=>{const[r]=t,a=Kh({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===Ts){const{matchUps:r}=Ah({finishingPositionLimit:I+c,idPrefix:m&&`${m}-po`,finishingPositionOffset:I,matchUpType:d,drawSize:g,isMock:f,uuids:h}),a=Ym({structureId:t.structureId??h?.pop(),matchUpFormat:n,stage:ts,structureName:P,stageSequence:o,matchUps:r});S.push(a);const s=Kh({playoffStructureId:a.structureId,finishingPositions:e,sourceStructureId:i});y.push(s),I+=c,U.push({structureId:a.structureId,finishingPositions:e})}else if([vs,ws,ts].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:ts,roundOffset:0,stageSequence:o,drawSize:g,isMock:f,uuids:h};v===vs?Object.assign(n,{playoffAttributes:t?.playoffAttributes??r??qs,roundOffsetLimit:3}):v===ws&&Object.assign(n,{playoffAttributes:t?.playoffAttributes??r??$s,roundOffsetLimit:2});const a=qh(n);if(a.error)return a;if(a.links?.length&&y.push(...a.links),a.structures?.length&&S.push(...a.structures),S.sort(Ks),a.structureId){const t=Kh({playoffStructureId:a.structureId,finishingPositions:e,sourceStructureId:i});y.push(t),U.push({structureId:a.structureId,finishingPositions:e})}I+=c}else if([Ds,Ls,ks,Os,Es,xs].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:ts,structureName:P,matchUpType:d,feedPolicy:p,drawSize:g,isMock:f},a={[Ds]:{fmlc:!0,feedRounds:1},[xs]:{feedRounds:1},[ks]:{feedsFromFinal:3},[Os]:{feedsFromFinal:2},[Es]:{feedsFromFinal:1}};Object.assign(r,a[v]||{});const{structures:o,links:s}=zh(r),[u]=o,l=Kh({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([Bs].includes(v)){const{structures:e,links:n}=sf({...D,structureOptions:t.structureOptions||{groupSize:4}});b({playoffStructures:e,playoffLinks:n})}else if([bs].includes(v)){const{structures:t,links:e}=$h(D);b({playoffStructures:t,playoffLinks:e})}else if([Rs].includes(v)){const{structures:t,links:e}=Hh(D);b({playoffStructures:t,playoffLinks:e})}else if([Ss].includes(v)){b({playoffStructures:[Ym({structureId:t.structureId??h?.pop(),structureName:t.structureName,finishingPosition:Au,stage:ts,stageSequence:o,matchUps:[]})],playoffLinks:[]})}}return{finishingPositionTargets:U,positionRangeMap:w,structures:S,links:y}}function Kh({playoffStructureId:t,finishingPositions:e,sourceStructureId:n}){return{linkType:hs,source:{structureId:n,finishingPositions:e},target:{structureId:t,feedProfile:ps,roundNumber:1}}}function Jh({matchUp:t,tieFormat:e,isMock:n,uuids:r}){const{collectionDefinitions:i}=e??{};return{tieMatchUps:(i??[]).map((e=>Qh({matchUp:t,collectionDefinition:e,uuids:r,isMock:n}))).filter(Boolean).flat()}}function Qh({collectionPositionOffset:t=0,collectionDefinition:e,matchUpsLimit:n,matchUp:r,isMock:i,uuids:a}){const{matchUpCount:o,matchUpType:s,collectionId:c,processCodes:u}=e||{},d=t=>{if(!i&&!r?.isMock)return a?.pop()??wp();const n=e?.collectionId;return a?.pop()??`${r?.matchUpId}-${n}-TMU-${t+1}`};return w(0,n??o??0).map((e=>{const n=t+e+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:d(e),matchUpStatus:Bo,collectionPosition:n,collectionId:c,processCodes:u,matchUpType:s,isMock:i}}))}const Zh="SET3-S:6/TB7",Xh="SET3-S:6/TB7-F:TB10",tg={FORMAT_STANDARD:Zh,FORMAT_STANDARD_NOAD:"SET3-S:6NOAD",FORMAT_ATP_DOUBLES:Xh,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 eg({winningSide:t,matchUpFormat:e=Zh,matchUpStatus:n,tallyPolicy:r,score:i}){const a=[0,0],o=i?.sets,s="number"==typeof t&&t-1,c=Wp(e),u=ig(c?.bestOf??1);if("number"==typeof s&&(n===Eo&&r?.setsCreditForDefaults||n===Vo&&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===xo&&(+a[1-s]===u&&(a[1-s]-=1),r?.setsCreditForRetirements&&(a[s]=u)),a}function ng({matchUpFormat:t=Zh,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=Wp(t),u=ig(c?.bestOf??1),d=c?.setFormat?.tiebreakAt||0,p=[[],[]];if("number"==typeof s&&(r===Eo&&i?.gamesCreditForDefaults||r===Vo&&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;og(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===xo&&"number"==typeof s){const a=o.length>u&&c?.finalSetFormat?"finalSetFormat":"setFormat",l=c?.[a];if(og(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=eg({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 rg({matchUpFormat:t,score:e}){const r=t?Wp(t):void 0,i=ig(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(ag(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 ig(t){return t&&Math.ceil(t/2)||1}function ag(t){return"P"===t}function og(t){return!ag(t)}function sg({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,[dg(e,0),dg(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&&cg(t),m=u&&ug(t);if(l||m)if(pg(a,l),pg(a,m),o?.length){r=0;for(const t of o){const{matchUpType:e}=t,r=e===Kc,i=e===zc;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)))),mg({matchUpFormat:t.matchUpFormat,matchUpStatus:t.matchUpStatus,score:t.score,winningParticipantId:l,losingParticipantId:m,participantResults:a,isTieMatchUp:!0,manualGamesOverride:p,tallyPolicy:n,winningSide:u})}fg({winningParticipantId:l,losingParticipantId:m,participantResults:a,matchUpStatus:i})}else mg({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&&Ho.includes(i)){const e=dg(t,0),n=dg(t,1);e&&(pg(a,e),a[e].matchUpsCancelled+=1),n&&(pg(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&&(pg(a,e),pg(a,n),a[e].tieMatchUpsWon+=1,a[n].tieMatchUpsLost+=1,t.matchUpType===zc?(a[e].tieSinglesWon+=1,a[n].tieSinglesLost+=1):t.matchUpType===Kc&&(a[e].tieDoublesWon+=1,a[n].tieDoublesLost+=1))}lg({score:t.score,manualGamesOverride:p,participantResults:a,sides:d})}}else lg({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;pg(a,t),pg(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&&Wp(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 cg(t){return dg(t,t.winningSide-1)}function ug(t){return dg(t,1-(t.winningSide-1))}function dg(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 pg(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 lg({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&&(pg(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 mg({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||fg({winningParticipantId:t,losingParticipantId:e,participantResults:n,matchUpStatus:a});const l=eg({matchUpStatus:a,matchUpFormat:i,tallyPolicy:s,winningSide:c,score:u}),m=ng({matchUpStatus:a,matchUpFormat:i,tallyPolicy:s,winningSide:c,score:u}),{pointsTally:f}=rg({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 fg({winningParticipantId:t,losingParticipantId:e,participantResults:n,matchUpStatus:r}){e&&(r===Vo&&(n[e].walkovers+=1),r===Eo&&(n[e].defaults+=1),r===xo&&(n[e].retirements+=1),[Eo,xo,Vo].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 hg({participantResults:t,participantIds:e,attribute:n}){return gg({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 gg(t){return(t.participantIds||Object.keys(t.participantResults)).reduce(((e,n,r)=>(e.push({participantId:n,i:r,results:t.participantResults[n]}),e)),[])}const Ig=[{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}],Ug={matchUpsPct:20,tieMatchUpsPct:16,setsPct:12,gamesPct:8,pointsPct:4};function Sg(t){const{requireCompletion:e=!0,participantResults:n,subOrderMap:r,tallyPolicy:i}=t,a=[];if(e&&!function({participantResults:t,participantsCount:e}){const n=gg({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=hg({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=yg({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(Ug).filter((t=>i.GEMscore.includes(t))):Object.keys(Ug);return e.map((e=>(t[e]||0)*Math.pow(10,Ug[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 yg({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||Ig).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}=sg({participantIds:a&&e,matchUpFormat:n,tallyPolicy:r,matchUps:o}),u=hg({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=yg({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 vg({policyDefinitions:t,generateReport:e,matchUpFormat:n,matchUps:r=[],subOrderMap:i,perPlayer:a}){if(!Uu(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!==No)),s=o.length&&m(o.map((({drawPositions:t})=>t)).flat()).length,c=o.filter((t=>fl({matchUp:t}))).length===o.length;c||(a=0);const u=r.every((({matchUpType:t,tieMatchUps:e})=>t===Qc&&e?.every((t=>fl({matchUp:t}))))),d=t?.[fa],p=r.filter((t=>fl({matchUp:t})||t.matchUpType===Qc)),{participantResults:l}=sg({matchUps:p,matchUpFormat:n,tallyPolicy:d,perPlayer:a});let f,h;const{groupOrder:g,report:I}=Sg({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}=Sg({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||Xn({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});Xn({tally:!0})&&console.log(t),U.readableReport=t}return U}function wg({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:i,matchUps:a,event:o}){if(!Uu(a))return{error:Nn};if(!t)return{error:Nn};const{policyDefinitions:s}=Pu({policyTypes:[fa],tournamentRecord:e,drawDefinition:r,event:o}),{subOrderMap:c}=function({positionAssignments:t}){const e=(t||[]).filter(wi(Ri)).map((t=>{const{extension:e}=Fr({element:t,name:io}),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=vg({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)){Cr({element:t,extension:{value:d[e],name:ao}}),d[e].ties||Ar({element:t,name:io})}else Ar({element:t,name:ao}),Ar({element:t,name:io})})),kc({drawDefinition:r}),{...E,participantResults:d,bracketComplete:p,report:l}}const Tg={matchUpStatus:Bo,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function Pg({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find((t=>t.matchUpId===e))}}function Dg({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=[]}=Zs({drawDefinition:i});r&&!n&&(n=Cu({contextProfile:r,drawDefinition:i}));for(const p of d){const{matchUps:d}=ml({tournamentParticipants:t,afterRecoveryTimes:e,contextContent:n,drawDefinition:i,contextProfile:r,matchUpsMap:a,inContext:s,structure:p,context:c,event:u}),{matchUp:l}=Pg({matchUps:d,matchUpId:o});if(l)return{matchUp:l,structure:p}}return{error:Wt}}function bg(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 Ng(t){return"object"!=typeof t?{error:ae}:"object"!=typeof t.element?{error:Nn}:(t.element.notes&&delete t.element.notes,{...E})}function Mg({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===Qc;if(g&&r){if(c&&u.matchUpId!==c){const t=Dg({drawDefinition:r,matchUpId:c,event:d});if(!t.matchUp)return{error:Wt};({matchUp:u,structure:h}=t)}}else u.matchUpId!==c&&console.log("!!!!!");a&&[Vo,Oo].includes(a)||o?Object.assign(u,{...Tg}):l&&(u.score=l);const I=a&&u?.matchUpStatus===Eo&&a!==Eo;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}=Dg({drawDefinition:r,matchUpId:c,event:d})),!a||u.winningSide||!Gc(u)||Ho.includes(a)||[bo,Lo].includes(a)||(u.matchUpStatus=Fo),I&&u?.processCodes?.length||a===Eo){const t=Tu({tournamentRecord:n,drawDefinition:r,structure:h,event:d})?.appliedPolicies;U=t?.[Ta]?.processCodes?.incompleteAssignmentsOnDefault}if(!u.collectionId){const t=h?.structureType===ds,e=nl({drawDefinition:r,structure:h});if(el({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:[Qc]}:void 0,{matchUps:o}=ml({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})))),wg({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 Nr({result:a,stack:f})}}if(p){const t=bg({element:u,notes:p});if(t.error)return Nr({result:t,stack:f})}const S=n?.tournamentId,y=mr().topics.includes(Mc),v=(y||U)&&Fu({drawDefinition:r}),w=v&&gl({matchUpFilters:{matchUpIds:[c]},nextMatchUps:!0,tournamentRecord:n,inContext:!0,drawDefinition:r,matchUpsMap:v}).matchUps?.[0];if(y&&w&&function({tournamentId:t,inContextMatchUp:e}){e&&cr({payload:{inContextMatchUp:e,tournamentId:t},topic:Mc,key:e.matchUpId})}({tournamentId:S,inContextMatchUp:w}),Array.isArray(U)&&w&&!w.sides?.every((({participantId:t})=>t)))if(a===Eo)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 Oc({eventId:d?.eventId,context:f,drawDefinition:r,tournamentId:S,matchUp:u}),{...E}}function Rg(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=qc({matchUpStatus:o})||[Mo,Do].includes(o)&&e,f=Boolean(d.collectionId),h=nl({drawDefinition:i,structure:u}),g=f||h||function({structure:t,matchUp:e}){const{drawPositions:n}=e,{positionAssignments:r}=ec({structure:t}),i=r?.filter((t=>n?.includes(t.drawPosition)&&t.participantId));return 2===i?.length}({structure:u,matchUp:d});if(!g)return{error:Mt};const I=[Vo].includes(o);return Nr({result:Mg({matchUpStatusCodes:m&&n||[],matchUpStatus:m&&o||Ro,tournamentRecord:r,drawDefinition:i,matchUpFormat:a,removeScore:I,winningSide:s,matchUpId:c,matchUp:d,event:p,score:l}),stack:"attemptToModifyScore"})}function Ag({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}}const Eg="MIXED events can not contain mixed singles or { gender: ANY } collections",Cg="events with { gender: ANY } can not contain MIXED singles collections";function Og(t){const e="tieFormatGenderValidityCheck",{referenceGender:n,matchUpType:r,gender:i}=t;return n&&i&&[cl,pl].includes(n)&&n!==i?Nr({result:{valid:!1,error:Dn},context:{gender:i},stack:e}):n===ul&&(i===sl||i===ul&&r!==Kc)?Nr({result:{error:Dn,valid:!1},info:Eg,stack:e}):n===sl&&i===ul&&r!==Kc?Nr({result:{error:Dn,valid:!1},info:Cg,stack:e}):{valid:!0}}const Fg=(t,e)=>t.filter(Boolean).every((t=>typeof t===e)),kg=t=>t.filter(Boolean).every(s);function _g(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(!Fg([n,r,i,s],"string")||!kg([a,o]))return{error:bn};const u=t.consideredDate??ti((new Date).toLocaleDateString("sv"));if(!Gr(u))return{error:pe};const[d]=u.split("-").slice(0,3).map((t=>parseInt(t))),p=ei(u,-1),[l,m]=p.split("-").slice(1,3).map((t=>parseInt(t))),f=`${di(l)}-${di(m)}`,h=ei(u,1),[g,I]=h.split("-").slice(1,3).map((t=>parseInt(t))),U=`${di(g)}-${di(I)}`;let S=o&&ei(u,-365*o),y=a&&ei(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),M=(t,e)=>`${t}-${e}`,R=t=>{const r=M(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=M(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=M(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}`),R(p)):"O"===u&&(t=>{const i=M(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=M(t,f)}if(e.ageMax){const t=d-e.ageMax-1;i=M(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&&R(a));a&&e.ageMin&&e.ageMin>a&&(w(`Invalid submitted ageMin: ${e.ageMin}`),o=void 0);const C=br({consideredDate:u,combinedAge:c,ageMaxDate:r,ageMinDate:i,ageMax:a,ageMin:o});return v.length&&(C.errors=v),C}function xg({category:t}){if(!Ui(t))return{error:Nn};const e=_g({category:t});if(e.error)return{error:e};const{ratingMax:n,ratingMin:r}=t;return n&&!s(n)?Nr({result:{error:Nn},context:{ratingMax:n}}):r&&!s(r)?Nr({result:{error:Nn},context:{ratingMin:r}}):{...e}}function Lg({childCategory:t,withDetails:e,category:n}){const r=xg({category:n}),i=xg({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=br({invalidRatingRange:u,invalidAgeMinDate:s,invalidAgeMaxDate:c,invalidBallType:d,invalidAgeMax:o,invalidAgeMin:a,valid:!(u||s||c||d||o||a)},!0);return e&&Object.assign(p,{categoryDetails:r,childCategoryDetails:i}),p}function Bg(t,e){if((t?.bestOf||t?.exactly)&&t?.setFormat)return function(t,e){const n=Vg(t.bestOf)||void 0,r=Vg(t.exactly)||void 0,i=n||r;if(t.setFormat?.timed&&t.simplified&&1===i)return jg(t.setFormat);const a=i&&`${qp}${i}`||"",o=Gg(t.setFormat,e),s=o&&`S:${o}`||"",c=Gg(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 Vg(t){return!isNaN(Number(t))&&Number(t)}function jg(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function Gg(t,e){if("object"==typeof t&&Object.keys(t).length){if(t.timed)return jg(t);if(t.tiebreakSet)return qg(t.tiebreakSet);const n=Vg(t.setTo);if(n){const r=t.NoAD&&Gp||"",i=qg(t.tiebreakFormat),a=i&&`/${i}`||"",o=Vg(t.tiebreakAt);if(!1!==i)return`${n}${r}${a}${o&&(o!==n||e)&&`@${o}`||""}`}}}function qg(t){if(t){if("object"!=typeof t||t.tiebreakTo){if("object"==typeof t&&Vg(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?Gp:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}return!1}return""}}function $g({matchUpFormat:t}){if("string"!=typeof t)return!1;const e=Wp(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 Bg(e,!!(n&&i&&r===a||o&&c&&s===u))===t}function Wg({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}`),Nr({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&&![zc,Kc].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=Ag({collectionValueProfiles:u,matchUpCount:f});t.errors&&c.push(...t.errors)}if(d&&"number"!=typeof d&&c.push(`collectionGroupNumber is not type number: ${l}`),h&&!$g({matchUpFormat:h})&&c.push(`Invalid matchUpFormat: ${h}`),r){const t=Og({referenceGender:a,matchUpType:I,gender:v});if(t.error)return Nr({context:{referenceGender:a,gender:v},result:t,stack:s})}if(t&&i&&y){const t=Lg({category:i,childCategory:y});if(!t.valid)return Nr({result:{error:bn},context:t,stack:s})}return c.length?Nr({result:{errors:c,error:Tn},stack:s}):{valid:!0}}function Hg(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"),Nr({result:{error:Lt},context:{tieFormat:i,errors:s},stack:o});if("object"!=typeof i.winCriteria)return s.push("tieFormat.winCriteria must be an object"),Nr({result:{error:Lt},context:{tieFormat:i,errors:s},stack:o});if(!Array.isArray(i.collectionDefinitions))return s.push(wf("tieFormat.collectionDefinitions")),Nr({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}=Wg({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"),Nr({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}:Nr({result:{error:Lt},context:{tieFormat:i,errors:s},stack:o})}function zg({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=>Ho.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===Ro||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 Yg({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 Kg(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=Bp({matchUp:o,drawDefinition:r,structure:a,event:s})?.tieFormat||t?.tieFormat;if(!c)return{error:Gt};const u=Hg({tieFormat:c});if(u.error)return u;const d=c?.collectionDefinitions||[],p=o?.tieMatchUps??[],l=[0,0],{groupValueGroups:m,groupValueNumbers:f}=Yg(c);for(const t of d)zg({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&&Ho.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&&Dg({inContext:!0,drawDefinition:r,matchUpId:t})?.matchUp;if(e){const{completedTieMatchUps:t,order:n}=vg({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}}function Jg(t){if(t)return mi(t,!1,!0)}function Qg(t){const e=na(t,[{[Pi]:!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 Zg({tournamentRecords:t,eventId:e,drawId:n}){const{tournamentIdMap:r}=Qg({tournamentRecords:t});return(r?Object.keys(r):[]).find((t=>e&&r?.[t].includes(e)||n&&r?.[t].includes(n)))}function Xg({inContextDualMatchUp:t,drawDefinition:e,tournamentId:n,dualMatchUp:r,eventId:i}){if(r){t||(t=Dg({matchUpId:r.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);const{extension:a}=Fr({element:e,name:Ya}),o=mi(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}})),Oc({context:"ensureSidLineUps",matchUp:r,drawDefinition:e,tournamentId:n,eventId:i})}}function tI(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&&Zg({tournamentRecords:c,...t});const d=u&&c[u];if(!d)return{error:x};const p=Dg({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};Xg({tournamentId:d?.tournamentId,eventId:s?.eventId,dualMatchUp:l,drawDefinition:n});const{extension:f}=Fr({name:qa,element:l});if(f?.value){if(!i)return{...E,score:l.score};Ar({element:l,name:qa})}const h=Bp({drawDefinition:n,structure:m,matchUp:l,event:s})?.tieFormat;l.tieFormat=Jg(h);const g=Kg({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&&Ro||Wc({matchUpStatus:r??l.matchUpStatus,tieMatchUps:l.tieMatchUps,winningSide:l.winningSide,score:w})&&Fo||Bo,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&&Ho.includes(n)||e));let N;if(l.tieFormat&&!T&&!b){const t=Bp({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 Mg({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 eI(t){const n=Rg(t);if(n.error)return n;const r=qc({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=nl({drawDefinition:c,structure:h});let v,w=g.drawPositions;if(S){const{matchUpTieId:e,matchUpsMap:n}=t,r=tI({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 Nr({result:{...E,...v},stack:U})}if(y)return Nr({result:{...E,...v},stack:U});if(!w)return Nr({result:{error:Q},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=Qs({structureId:f,drawDefinition:c});if(h.error)return h;const{structure:g}=h,{positionAssignments:I}=ec({structureId:f,drawDefinition:c}),U=I?.find((t=>t.drawPosition===i)),S=U?.participantId,y=o.target.structureId,{positionAssignments:v}=ec({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)bf({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&&bf({participantId:S,structureId:y,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:a,drawDefinition:c,drawPosition:t,matchUpsMap:p,event:l})}else if(T){const t=ef({drawPosition:T,matchUpId:u.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:a,sourceMatchUpId:s,drawDefinition:c,matchUpsMap:p});if(t.error)return Nr({result:t,stack:m})}else if(g?.stage!==Qo){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&&Sf({eventId:u?.eventId,structureId:y,...t,tournamentRecord:a,drawDefinition:c,participantId:e})}}else{const t=ef({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=vf({lineUp:e}),Oc({tournamentId:a?.tournamentId,eventId:u?.eventId,matchUp:i,context:m,drawDefinition:c})}}}return{...E}}({sourceMatchUpStatus:r&&u||Ro,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 Nr({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===Us&&2===d.roundNumber&&Math.min(...g.filter(Boolean)),U=I||g[n],S=I||g[1-n],y=c.source.structureId,{structure:v}=Qs({structureId:y,drawDefinition:u}),{matchUps:w}=ml({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===Vo||t.matchUpStatus===Eo&&!Gc(t);return e?.sideNumber===t.winningSide&&!n})),P=h===Us&&0===T.length,{positionAssignments:D}=ec({structureId:y,drawDefinition:u}),b=D?.find((t=>t.drawPosition===o)),N=b?.participantId,M=c.target.structureId,{positionAssignments:R}=ec({structureId:M,drawDefinition:u}),A=R?.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,_=1===c.target.roundNumber&&F;if(I){const t=function(){const t="loserLinkFedFMLC";return Nr(P?{result:L(),stack:t}:{result:x(),stack:t})}();if(t.error)return Nr({result:t,stack:f})}else if(_){const t=L();if(t.error)return Nr({result:t,stack:f})}else{if(!N||!k)return Nr({result:{error:X},context:{loserDrawPosition:o,loserTargetLink:c},stack:f});{O.sort(e);const t=O[0],n=bf({participantId:N,structureId:M,drawPosition:t,inContextDrawMatchUps:r,sourceMatchUpStatus:a,tournamentRecord:s,drawDefinition:u,matchUpsMap:l,event:m});if(n.error)return Nr({result:n,stack:f})}}if(v?.seedAssignments&&v.structureId!==M){const t=v.seedAssignments.find((({participantId:t})=>t===N)),e=t?.participantId;t&&e&&Sf({eventId:d?.eventId,structureId:M,...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=vf({lineUp:t.lineUp}),Oc({tournamentId:s?.tournamentId,matchUp:a,context:f,drawDefinition:u,eventId:n}))}}return{...E};function x(){return Nr({result:Yl({drawPosition:S,structureId:M,tournamentRecord:s,drawDefinition:u,event:m}),stack:"assignLoserPositionBye"})}function L(){return Nr({result:N?bf({drawPosition:U,participantId:N,structureId:M,inContextDrawMatchUps:r,sourceMatchUpStatus:a,tournamentRecord:s,drawDefinition:u,matchUpsMap:l,event:m}):{error:Ae},stack:"assignLoserDrawPosition"})}}({sourceMatchUpStatus:r&&u||Ro,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 Nr({result:t,stack:U})}if(b){const t=b.drawPositions||[],e=Yl({drawPosition:Math.min(...t.filter(Boolean)),structureId:y.target.structureId,tournamentRecord:s,drawDefinition:c,event:I});if(e.error)return Nr({result:e,stack:U})}}return Nr({result:{...E,...v},stack:U})}function nI(t){const e="genPlayoffStructure";if(!t.drawDefinition)return Nr({result:{error:j},stack:e});const r=Bh(t);if(r.error)return Nr({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=mi(t.drawDefinition,!1,!0),{structure:v}=Qs({structureId:i,drawDefinition:y});if(!v)return Nr({result:{error:Ut},stack:e});if(v.structureType===ds||v.structures)return function(t){const e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return Nr({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}=Yh({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}=gl({inContext:!0,drawDefinition:a}),U=d.map((({structureId:t})=>t)),S=g?.filter((({structureId:t})=>U.includes(t))).map(wo),y=I?.drawMatchUps?.filter((({matchUpId:t})=>S?.includes(t)));if(y?.length){const e=Bp({drawDefinition:a,event:u})?.tieFormat;e&&y.forEach((n=>{const{tieMatchUps:r}=Jh({isMock:t.isMock,tieFormat:e,matchUp:n});Object.assign(n,{tieMatchUps:r,matchUpType:Jc})}))}const{positionAssignments:v}=tc({structureId:n,drawDefinition:a}),w={};v?.forEach((t=>{const e=Fr({element:t,name:ao}),n=e?.extension?.value,r=n?.groupOrder;r&&(w[r]||(w[r]=[]),w[r].push(t.participantId))}));const T=ph({provisionalPositioning:t.provisionalPositioning,structureId:n,applyPositioning:!0,event:t.event,tournamentRecord:i,drawDefinition:a});return T.error&&T.error?.code!==W.code?Nr({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}=Lh(t);if(D)return Nr({result:{error:D},stack:e});const M=f?.length&&Object.assign({},...f),R=h||"object"==typeof f&&f.map((t=>Object.keys(t))).flat(),A=Array.isArray(R)&&R.map((t=>!isNaN(t)&&n(t))).filter(Boolean);if(A){if(!Array.isArray(A))return Nr({result:{error:Nn},context:{validRoundNumbers:A},stack:e});A.forEach((t=>{if(!T?.includes(t))return Nr({result:{error:Nn},context:{roundNumber:t},stack:e})}))}d&&d.forEach((t=>{if(!P?.includes(t))return Nr({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 Nr({result:{error:Nn},context:{roundNumber:t},stack:e});const r=n.finishingPositions.length,d=Math.min(...n.finishingPositions)-1,l=2,f=t&&M?.[t]&&l+M[t]-1,h=qh({exitProfile:`0-${t}`,addNameBaseToAttributeName:a,playoffStructureNameBase:o,finishingPositionOffset:d,playoffAttributes:u,exitProfileLimit:m,stage:ts,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 Nr({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:Is,source:{structureId:i,roundNumber:t},target:{structureId:h.structureId,feedProfile:ms,roundNumber:1}};k.push(e)}}if(!F.length)return Nr({result:{error:Nn},info:"No structures generated",stack:e});y.structures.push(...F),y.links.push(...k);const{matchUps:_,matchUpsMap:x}=gl({inContext:!0,drawDefinition:y}),L=F.map((({structureId:t})=>t)),B=_?.filter((({structureId:t})=>L.includes(t))).map(wo),V=x?.drawMatchUps?.filter((({matchUpId:t})=>B?.includes(t)));if(V?.length){const t=Bp({drawDefinition:y,event:U})?.tieFormat;t&&V.forEach((e=>{const{tieMatchUps:n}=Jh({matchUp:e,tieFormat:t,isMock:I});Object.assign(e,{tieMatchUps:n,matchUpType:Qc})}))}const G=_?.filter((t=>fl({matchUp:t})&&t.structureId===i));G?.forEach((t=>{const{matchUpId:e,score:n,winningSide:r}=t,i=gu({inContextDrawMatchUps:_,drawDefinition:y,matchUpId:e}),a=eI({inContextDrawMatchUps:_,tournamentRecord:l,drawDefinition:y,matchUpsMap:x,winningSide:r,targetData:i,matchUpId:e,structure:v,matchUp:t,score:n,event:U});a.error&&console.log(a.error)}));const q=_?.filter((t=>t.matchUpStatus===No&&t.structureId===i));q?.forEach((t=>{const{matchUpId:e}=t,n=gu({inContextDrawMatchUps:_,drawDefinition:y,matchUpId:e}),{targetLinks:{loserTargetLink:r},targetMatchUps:{loserMatchUpDrawPositionIndex:i,loserMatchUp:a}}=n;if(r&&a){const t=r.target.structureId,e=Yl({drawPosition:a.drawPositions[i],structureId:t,tournamentRecord:l,drawDefinition:y,event:U});e.error&&console.log(e.error)}}));const $=[],H=Sl({inContextDrawMatchUps:_,drawDefinition:y,matchUpsMap:x}).goesToMap,{structure:z}=Qs({drawDefinition:t.drawDefinition,structureId:i}),{matchUps:Y}=ml({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 rI(t){return aI({...t,itemType:"attachConsolationStructures"})}function iI(t){return aI({...t,itemType:"attachPlayoffStructures"})}function aI({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 Nr({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 Nr({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),Sl({drawDefinition:r});const m=i.map((t=>ml({structure:t})?.matchUps||[])).flat();Ec({tournamentId:n?.tournamentId,eventId:o?.eventId,drawDefinition:r,matchUps:m});const f=i.map((({structureId:t})=>t));if(kc({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,Oc(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(wi("structureId"));if(n){hh({element:n,timeItem:{itemValue:{structureIds:f,drawId:r.drawId},itemType:t}})}return{...E,addedStructureIds:h}}function oI(t){const{structures:e,links:n,matchUpModifications:r,error:i}=nI(t);if(i)return{error:i};const a=t.drawDefinition;return iI({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:r,drawDefinition:a,structures:e,links:n})}function sI(t){const e=na(t,[{_anyOf:{[Pi]:!1,[bi]:!1,[Ni]:!1,[Hi]:!1},[Di]:!0}]);if(e.error)return e;const n=[],r=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(r){const e=cI(t,r);if(e.error)return e;n.push(...e?.applied??[]),t.drawDefinition&&kc({drawDefinition:t.drawDefinition,tournamentId:t.tournamentId})}else{if(!t.tournamentRecords)return{error:x};{const e=Object.keys(t.tournamentRecords);if(!e.length)return{error:x};for(const r of e){const e=cI(t,t.tournamentRecords[r]);if(e.error)return e;n.push(...e?.applied??[])}}}return n.length?{...E,applied:n}:{error:te}}function cI(t,e){const n=Tu(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(!Ui(i))return{error:Nn};const{policyName:a,...o}=i;if(!o||!Object.keys(o).length||a&&!Ii(a))return{error:Nn};n[e]=t.policyDefinitions[e],r.push(e)}if(r?.length){return{...Cr({element:e,extension:{name:xa,value:n}}),applied:r}}return{applied:r,error:te}}function uI({tournamentRecord:t,drawDefinition:e,flightProfile:n,drawName:r,drawId:i,event:a}){if(!r||"string"!=typeof r)return Nr({result:{error:Nn},context:{drawName:r}});n||(n=Fp({event:a}).flightProfile);const o=n?.flights?.find((t=>t.drawId===i));if(o){o.drawName=r;Ea({event:a,extension:{name:Ha,value:{...n,flights:n.flights}}})}return e&&(e.drawName=r,kc({tournamentId:t?.tournamentId,drawDefinition:e})),o||e?{...E,flight:o}:{error:j}}function dI({tournamentRecord:t,drawDefinition:e,drawUpdates:n,drawId:r,event:i}){if(!Ui(n))return{error:Nn};const a=Fp({event:i}).flightProfile,o=n.drawName&&uI({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){Ea({event:i,extension:{name:Ha,value:{...a,flights:a.flights}}})}return e&&(n.policyDefinitions&&sI({policyDefinitions:n.policyDefinitions,drawDefinition:e}),kc({tournamentId:t?.tournamentId,drawDefinition:e})),{...E}}function pI({tournamentRecord:t,removeScheduling:e,drawDefinition:n}){if(!n)return{error:j};const r=Fu({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&&[Qo,Jo].includes(s)||(a.positionAssignments=o.map((t=>(delete t.participantId,t))),a.seedAssignments=[]);const{matchUps:u}=ml({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!==No&&Object.assign(c,Tg),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&&![Ud,Sd,Id,wd,vd,Td].includes(t.itemType)))),Oc({tournamentId:t?.tournamentId,context:"resetDrawDefiniton",drawDefinition:n,matchUp:c})}}}return kc({drawDefinition:n,structureIds:(n.structures||[]).map((({structureId:t})=>t))}),{...E}}function lI({tournamentRecord:t}){if(!t)return{error:x};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}=mh({drawDefinition:t}),u=r[i],d=(t?.structures||[]).map((e=>{const{stage:n,stageSequence:r,structureId:i}=e,c=ns[n],{inContextStructureMatchUps:d}=Gl({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}=tc({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}=Su({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}=hu({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 mI({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:n,drawId:r}){if(!e)return{error:x};if(!n)return{error:j};let i=[];const{drawsAnalysis:a}=lI({tournamentRecord:e});if(a.canBePruned.includes(r)){const o=a.matchPlay.includes(r),s=a.drawAnalysis[r],{structures:[c]}=Zs({stageSequence:1,drawDefinition:n,stage:Jo}),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(wo),l=d.map(wo).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(wo),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}Cc({tournamentId:e?.tournamentId,matchUpIds:l,drawDefinition:n}),kc({drawDefinition:n})}return{...E,matchUps:i}}function fI({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=Yl({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:i,event:o});if(n.error)return n}else{if(a)return{error:Fn};{const a=bf({tournamentRecord:t,drawDefinition:e,participantId:n,drawPosition:r,structureId:i,event:o});if(a.error)return a}}return{...E}}function hI({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===Hs)return{error:$};const c=[],u=o?.filter((({matchUpId:t,score:n})=>(Gc({score:n})&&c.push(t),e.includes(t))))??[],d=u.map(wi("matchUpId"));if(d.length){a.matchUps=(a.matchUps??[]).filter((({matchUpId:t})=>!d.includes(t))),Cc({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(wi("roundNumber"))));if(e.length){e.reverse();for(const r of e)a.matchUps.forEach((e=>{e.roundNumber&&e.roundNumber>r&&(e.roundNumber-=1,Oc({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=wg({positionAssignments:a.positionAssignments,matchUps:a.matchUps,tournamentRecord:t,drawDefinition:n,matchUpFormat:e,event:i});r.error&&console.log(r)}kc({structureIds:[r],eventId:i?.eventId,drawDefinition:n})}return{...E}}function gI({removeCompletedMatchUps:t,tournamentRecord:n,drawDefinition:r,structureId:i,roundNumber:a,event:o}){if(!n)return{error:x};if(!r)return{error:j};if(!a)return Nr({result:{error:ae},info:"roundNumber required"});const s=Qs({drawDefinition:r,structureId:i});if(s.error)return s;const c=s.structure;if(c?.structures)return{error:$};return nl({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&&(!Ho.includes(e.matchUpStatus)||t);return n&&c.push(e.matchUpId),!n}));if(c.length){Cc({matchUpIds:c,drawDefinition:n,tournamentId:r,eventId:o});e.some((t=>t.roundNumber===i))||(e.forEach((t=>{t.roundNumber>i&&(t.roundNumber-=1,Oc({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})}function II({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(!Uu(r))return{error:Nn,info:wf("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===Hs)return{error:$};return b(xl({tournamentRecord:t,inContext:!1})?.matchUps?.map(wo)??[],r.map(wo))?{error:Ln,info:"One or more matchUpIds already present in tournamentRecord"}:(i.matchUps.push(...r),Ec({tournamentId:t?.tournamentId,drawDefinition:e,matchUps:r}),kc({drawDefinition:e,structureIds:[n]}),{...E})}function UI({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}=Qs({drawDefinition:e,structureId:r});if(!o)return{error:Ut};let s=o;o.structures&&o.structureType===ds&&(s=o.structures?.find((t=>t.positionAssignments?.find((t=>t.drawPosition===n)))));const c=s?.positionAssignments,u=c?.find((t=>t.drawPosition===n));u&&Cr({element:u,extension:{name:io,value:i}});const d=(a?.eventType===Qc||e.matchUpType===Qc||(a?.tieFormat??e?.tieFormat??o?.tieFormat))&&{matchUpTypes:[Qc]},{matchUps:p}=ml({structure:s,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:d,event:a});return wg({positionAssignments:c,tournamentRecord:t,drawDefinition:e,matchUpFormat:o?.matchUpFormat??e.matchUpFormat,matchUps:p,event:a}),kc({drawDefinition:e,structureIds:[r]}),{...E}}function SI({participantsCount:t,participantCount:e}){if(!(t=t??e))return{error:Nn};const n=u(t);return n?{drawSize:n}:Nr({result:{error:Nn},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function yI(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=Pu({tournamentRecord:a,drawDefinition:o,event:s});if(t.error)return Nr({result:t,stack:c});n=t.policyDefinitions}const d=p(u);if(u&&!d)return Nr({result:{error:Nn},context:{participantsCount:u},stack:c});if(i&&!d)return Nr({result:{error:ke},stack:c});if(isNaN(r)){if(!u)return Nr({result:{error:it},stack:c});({drawSize:r}=SI({participantsCount:u}))}const l=i&&u||r;if(l&&l>r)return{error:Ve};const m=n?.[Pa];if(!m)return{error:Xt};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 vI({policyDefinitions:t,drawDefinition:e,drawSize:n,drawId:r,event:i,stage:a}){if(!i)return{error:Tt};const{entries:o,stageEntries:s}=Vm({drawDefinition:e,drawId:r,stage:a,event:i}),c=s.length,{drawSize:u}=SI({participantsCount:c}),d=yI({drawSize:n??u,participantsCount:c,policyDefinitions:t});if(d.error)return Nr({result:d,stack:"getEntriesAndSeedsCount"});const{seedsCount:p}=d;return{entries:o,seedsCount:p,stageEntries:s}}function wI({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:ca,scaleName:i,scaleDate:o}],participantId:e})))}}function TI(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}=Tl({tournamentRecords:i,tournamentRecord:e,participantId:r});return a?{...cm({participant:a,scaleAttributes:n}),tournamentId:o}:{error:Ee}}function PI({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:n,scaleSortMethod:r,stageSequence:i,entries:a,event:o,stage:s}){if(!e)return{error:x};return{scaledEntries:(a=a??o?.entries??[]).filter((t=>(!s||!t.entryStage||t.entryStage===s)&&(!i||!t.entryStageSequence||t.entryStageSequence===i)&&td.includes(t.entryStatus))).map((t=>{const{participantId:r}=t,{scaleItem:i}=TI({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 DI({tournamentRecord:t,drawDefinition:e,policyDefinitions:n,scaleAttributes:r,scaleName:i,drawSize:a,drawId:o,event:s,stage:c,sortDescending:u,scaleSortMethod:d}){const p=vI({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=PI({tournamentRecord:t,scaleAttributes:r,scaleSortMethod:d,sortDescending:u,entries:l,stage:c}).scaledEntries??[],{scaleItemsWithParticipantIds:g}=wI({scaleAttributes:r,scaledEntries:h,stageEntries:f,seedsCount:m,scaleName:i});return{scaleItemsWithParticipantIds:g}}var bI=Object.freeze({__proto__:null,addAdHocMatchUps:II,addDrawDefinitionTimeItem:vh,addPlayoffStructures:oI,addQualifyingStructure:Ch,addVoluntaryConsolationStage:Dh,addVoluntaryConsolationStructure:Km,alternateDrawPositionAssignment:Rf,assignDrawPosition:fI,assignDrawPositionBye:Yl,attachConsolationStructures:rI,attachPlayoffStructures:iI,attachQualifyingStructure:Sh,attachStructures:aI,autoSeeding:DI,automatedPlayoffPositioning:ph,automatedPositioning:dh,deleteAdHocMatchUps:hI,luckyLoserDrawPositionAssignment:Mf,modifyDrawDefinition:dI,modifyDrawName:uI,modifySeedAssignment:kf,pruneDrawDefinition:mI,qualifierDrawPositionAssignment:Ef,removeDrawPositionAssignment:$m,removeRoundMatchUps:gI,removeSeededParticipant:bh,removeStructure:wh,renameStructures:yh,resetDrawDefinition:pI,resetVoluntaryConsolationStructure:Lc,setDrawParticipantRepresentativeIds:Po,setPositionAssignments:Af,setStructureOrder:lh,setSubOrder:UI,swapDrawPositionAssignments:Ff,updateTeamLineUp:Pf,withdrawParticipantAtDrawPosition:Wm});function NI({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=[Jo,ts];n&&f.push(Qo);const h=m?.eventType?{matchUpTypes:[m.eventType]}:void 0,g=s?.matchUpType?{matchUpTypes:[s.matchUpType]}:void 0,I=e&&m?_l({contextFilters:{stages:f},matchUpFilters:h,tournamentRecord:o,inContext:!0,event:m})?.matchUps??[]:Vl({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:o,inContext:!0,drawDefinition:s})?.matchUps??[],U=ad({stage:Xo,drawDefinition:s}).map((({participantId:t})=>t)),S={},y={},v={},w={};i||(i=Pu({policyTypes:[la],tournamentRecord:o,drawDefinition:s,event:m}).policyDefinitions);const T=i?.[la];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!==Oo)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!==Oo||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=>![Ju,zu].includes(t.entryStatus))).map((({participantId:t})=>t)):[],b=Object.keys(y),N=P?(o?.participants??[]).filter((({participantId:t})=>D.includes(t))):d&&Object.values(y)||Object.values(v);return{eligibleParticipants:N.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}}function MI({drawDefinition:t}){const e=Fr({name:"participantRepresentatives",element:t});if(e.error)return e;return{representativeParticipantIds:e.extension?.value||[]}}function RI({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=mi(gl({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=>[Ro,No].includes(t.matchUpStatus)||t.winningSide)),r=n.map((n=>{const r=n.sides.find((t=>t.bye)),i=n.sides.find((t=>t.participantId===e)).sideNumber;return(n.winningSide||t&&r&&i)===i?n.finishingPositionRange.winner:n.finishingPositionRange.loser})),a=t=>Math.abs(t[0]-t[1]),o=r.reduce(((t,e)=>t&&a(t)<a(e)?t:e),void 0);return{[e]:{relevantMatchUps:n,finishingPositionRanges:r,finishingPositionRange:o}}}))||[];return Object.assign({},...a)}function AI({tournamentRecords:t,tournamentRecord:e,tournamentId:n,drawId:r}){if(!e&&!t)return{error:x};if(!r)return{error:at};if(!e&&t){if("string"!=typeof n&&!(n=Zg({tournamentRecords:t,drawId:r})))return{error:B};if(!(e=t[n]))return{error:x}}const i=e&&kp({tournamentRecord:e,drawId:r});return i?.drawDefinition?{drawDefinition:i.drawDefinition,event:i.event,tournamentRecord:e,...E}:Nr({result:{error:q},stack:"findDrawDefinition"})}function EI(t){const{drawDefinition:e,error:n}=AI(t);return n?{error:n}:{drawDefinition:mi(e)}}function CI({targetRoundNumber:t,finishingPosition:e,drawDefinition:n,structureId:r,linkType:i}){const{links:a}=hu({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}=Qs({structureId:r,drawDefinition:n});if(!e||i?.finishingPosition===e)return t})).filter(Boolean);return{sourceStructureIds:o.map((({source:t})=>t.structureId)),relevantLinks:o}}const OI="qualifierDrawPositionAssignment",FI="alternateDrawPositionAssignment",kI="luckyLoserDrawPositionAssignment",_I="removeDrawPositionAssignment",xI="swapDrawPositionAssignments",LI="modifyPairAssignment",BI="assignDrawPosition",VI="assignDrawPositionBye",jI="addPenalty",GI="MODIFY_PAIR",qI="QUALIFIER",$I="ALTERNATE",WI="WITHDRAW",HI="ASSIGN",zI="REMOVE",YI="LUCKY",KI="REMOVE_SEED",JI="SWAP",QI="NICKNAME",ZI="SEED_VALUE",XI="PENALTY",tU="BYE",eU={MODIFY_PAIR_ASSIGNMENT:GI,QUALIFYING_PARTICIPANT:qI,ALTERNATE_PARTICIPANT:$I,WITHDRAW_PARTICIPANT:WI,ASSIGN_PARTICIPANT:HI,LUCKY_PARTICIPANT:YI,REMOVE_ASSIGNMENT:zI,SWAP_PARTICIPANTS:JI,ADD_NICKNAME:QI,REMOVE_SEED:KI,ADD_PENALTY:XI,ASSIGN_BYE:tU,SEED_VALUE:ZI};function nU({restrictQualifyingAlternates:t,structure:e,entry:n}){const{stage:r}=e;if(!n.entryStage||n.entryStage===r||r===Qo&&!t||n.entryStage===Jo&&r===Zo)return!0}function rU(t,e){return t.bye||lf(t.seedValue)<lf(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function iU({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}=ml({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 br({...t,participant:o?mi(e,!1,!0):void 0,sourceDrawPositionRange:n})}));if(P.length){return{validSwapAction:{payload:{drawId:m,structureId:p,drawPositions:[d]},willDisableLinks:e,method:xI,type:JI,availableAssignments:P}}}return{}}function aU(t){const{inContextDrawMatchUps:e,targetData:n,drawDefinition:r,relevantLink:i}=t;if(i?.linkCondition===Us&&n?.matchUp?.matchUpStatus===No)return!1;const{targetMatchUps:{loserMatchUp:a,winnerMatchUp:o},targetLinks:s}=n,c=[Eo,Vo].includes(a?.matchUpStatus),u=o?.drawPositions?.filter(Boolean).length||0;if(a?.winningSide&&!c||o?.winningSide&&2===u&&(!o.feedRound||![Vo,Eo].includes(o?.matchUpStatus)))return!0;const d=a&&gu({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),p=o&&gu({matchUpId:o.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),l=d&&aU({relevantLink:s?.loserTargetLink,targetData:d,inContextDrawMatchUps:e,drawDefinition:r});return!(!(p&&aU({targetData:p,inContextDrawMatchUps:e,drawDefinition:r}))&&!l)}const oU={[ha]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[Qo,Jo],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[QI,XI,qI,ZI],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}},sU="positionAction",cU="matchUpAction";function uU({actionType:t=sU,appliedPolicies:e,drawDefinition:n,structure:r}){const i=t===sU&&ha||t===cU&&ga,a=t===sU&&oU||t===cU&&Am,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 dU({activePositionOverrides:t,activeDrawPositions:e,action:n}){return!(!n||!t.includes(n))||!e.length}function pU({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 lU({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 mU="replaceTieMatchUpParticipantId",fU="assignTieMatchUpParticipantId",hU="removeTieMatchUpParticipantId",gU="assignMatchUpSideParticipant",IU="removeMatchUpSideParticipant",UU="substituteParticipant",SU="REMOVE_SUBSTITUTION",yU="REPLACE_PARTICIPANT",vU="REMOVE_PARTICIPANT",wU="setMatchUpStatus",TU="SUBSTITUTION",PU="SCHEDULE",DU="REFEREE",bU="STATUS",NU="START",MU="SCORE",RU="END",AU={REPLACE_TEAM_POSITION_METHOD:mU,ASSIGN_TEAM_POSITION_METHOD:fU,REMOVE_TEAM_POSITION_METHOD:hU,REPLACE_PARTICIPANT:yU,SUBSTITUTION_METHOD:UU,REMOVE_SUBSTITUTION:SU,REMOVE_PARTICIPANT:vU,SCHEDULE_METHOD:wU,SUBSTITUTION:TU,SCHEDULE:PU,PENALTY:"PENALTY",REFEREE:DU,STATUS:bU,SCORE:MU,START:NU,END:RU};function EU({restrictAdHocRoundParticipants:t,tournamentParticipants:e,matchUpParticipantIds:n,otherFlightEntries:r,drawDefinition:i,structureId:a,sideNumber:o,matchUpId:s,structure:c,matchUp:u,drawId:d,event:p}){const l=[],f=(c?.matchUps??[]).filter((({roundNumber:t})=>t===u.roundNumber)),h=i?.entries?.filter((({entryStatus:t})=>t&&Xu.includes(t))).map(vo)??[],g=f.map((t=>(t.sides??[]).flatMap(vo))).flat().filter(Boolean),I=h.filter((e=>!(n.includes(e)||t&&g.includes(e)))),U=e?.filter((t=>I?.includes(t.participantId))).map((t=>mi(t,void 0,!0)));U?.forEach((t=>{const e=(i.entries??[]).find((e=>e.participantId===t.participantId));t.entryPosition=e?.entryPosition})),I.length&&l.push({payload:{drawId:d,matchUpId:s,structureId:a,sideNumber:o},method:gU,type:HI,availableParticipantIds:I,participantsAvailable:U});const S=function({eventEntries:t,structure:e}){return t.filter((t=>t.entryStatus===Lu&&nU({structure:e,entry:t}))).sort(((t,e)=>(t.entryPosition||1/0)-(e.entryPosition||1/0))).map(vo)}({eventEntries:p?.entries??[],structure:c});let y=m(h.concat(S));if(r){const t=p?Fp({event:p}):void 0,e=t?.flights?.filter((t=>t.drawId!==d)).flatMap((t=>t.drawEntries.filter((t=>t.participantId&&![Ju,zu,Yu].includes(t.entryStatus))).map((({participantId:t})=>t)))).filter(Boolean);e?.length&&y.push(...e)}y=y.filter((e=>!(n.includes(e)||I.includes(e)||t&&g.includes(e))));const v=e?.filter((t=>y.includes(t.participantId))).map((t=>mi(t,void 0,!0)));if(v?.forEach((t=>{const e=(i.entries??[]).find((e=>e.participantId===t.participantId));t.entryPosition=e?.entryPosition})),v?.sort(((t,e)=>(t.entryPosition||1/0)-(e.entryPosition||1/0))),y.length&&l.push({payload:{drawId:d,matchUpId:s,structureId:a,sideNumber:o},availableParticipantIds:y,participantsAvailable:v,method:gU,type:Lu}),!Gc(u)&&o){const t=u.sides?.find((t=>t.sideNumber===o));t?.participantId&&l.push({payload:{drawId:d,matchUpId:s,structureId:a,sideNumber:o},method:IU,type:vU})}return l}function CU(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&&Ii(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:x};if(!c||!Ii(c))return{error:qt};if(s&&![1,2].includes(s))return Nr({result:{error:Nn},context:{sideNumber:s}});if(!e){const t=(xl({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=ym({tournamentRecord:u,withIndividualParticipants:!0}).participants,{drawId:p}=e,{matchUp:l,structure:m}=Dg({drawDefinition:e,matchUpId:c,event:n});if(!l)return{error:Wt};const f=Tu({tournamentRecord:u,drawDefinition:e,structure:m,event:n}).appliedPolicies??{};Object.assign(f,i??{});const h=f?.[ha]?.otherFlightEntries,g=f?.[ga]??Am[ga],{enabledStructures:I}=uU({actionType:cU,appliedPolicies:f,drawDefinition:e,structure:m}),{policyActions:U}=pU({enabledStructures:I,drawDefinition:e,structure:m}),S=t.matchUpsMap??Fu({drawDefinition:e}),y=t.inContextDrawMatchUps??gl({tournamentParticipants:d,inContext:!0,drawDefinition:e,matchUpsMap:S,event:n}).matchUps,v=y?.find((t=>t.matchUpId===c)),w=s&&v?.sides?.find((t=>t.sideNumber===s)),T=v?.sides?.map((t=>t.participantId||t.participant?.participantid)).filter(Boolean)??[],{assignedPositions:P,allPositionsAssigned:D}=ec({structure:m}),{structureId:b}=m??{},N=[];if(!b)return{validActions:N};const M=nl({drawDefinition:e,structure:m}),R=l.collectionId;if(M&&!R){const t=EU({restrictAdHocRoundParticipants:r,tournamentParticipants:d,matchUpParticipantIds:T,otherFlightEntries:h,drawDefinition:e,structureId:b,sideNumber:s,matchUpId:c,structure:m,matchUp:l,drawId:p,event:n});N.push(...t)}const A=Bf({drawDefinition:e,structure:m}),E=P?.filter((t=>t.participantId)).map((t=>t.drawPosition)),C=P?.filter((t=>t.bye)).map((t=>t.drawPosition)),O=l.matchUpStatus===No||!R&&l.drawPositions?.reduce(((t,e)=>C?.includes(e)||t),!1);if(O)return{validActions:N,isByeMatchUp:O};lU({policyActions:U,action:DU})&&N.push({type:DU,payload:{matchUpId:c}});const F=!qc({matchUpStatus:l.matchUpStatus}),k=f?.scoring?.structures,_=m?.stage&&k?.stage&&k?.stage[m.stage],L=m?.stageSequence&&_?.stageSequence&&_.stageSequence[m.stageSequence],B=!(f?.scoring?.requireAllPositionsAssigned||_?.requireAllPositionsAssigned||L?.requireAllPositionsAssigned)||D,V=l.sides&&2===l.sides.filter((t=>t?.participantId)).length,G=l.matchUpStatus&&[Oo,Co].includes(l.matchUpStatus),q=aU({inContextDrawMatchUps:y,drawDefinition:e,targetData:gu({inContextDrawMatchUps:y,drawDefinition:e,matchUpId:c})}),$=(2===v?.drawPositions?.length&&v.drawPositions.every((t=>E?.includes(t)))&&2===v?.sides?.length&&v.sides.every((({participantId:t})=>t))||V)&&!(G&&q),W={method:jI,type:XI,payload:{drawId:p,matchUpId:c,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};if(F&&N.push({payload:{drawId:p,matchUpId:c,schedule:{}},method:wU,type:PU}),lU({policyActions:U,action:XI})&&(w?.participant||!s&&T?.length)&&N.push(W),F&&$&&N.push({type:bU}),B&&$){const{matchUpId:t,matchUpFormat:e}=l,n={drawId:p,matchUpId:t,matchUpFormat:e,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};N.push({info:"set outcome and winningSide",method:wU,type:MU,payload:n}),lU({policyActions:U,action:NU})&&N.push({type:NU}),lU({policyActions:U,action:RU})&&N.push({type:RU})}if(R&&v){const t=function({specifiedPolicyDefinitions:t,inContextDrawMatchUps:e,matchUpParticipantIds:n,matchUpActionsPolicy:r,inContextMatchUp:i,policyActions:a,enforceGender:o,participantId:s,sideNumber:c,matchUpId:u,matchUp:d,drawId:p,side:l}){const m=[],f=i.sides?.find((t=>t.participant)),h=i.gender===ul&&i.sideNumber&&1===i.sides?.filter((t=>t.particiapntId)).length&&f?.participant?.person?.sex,g=i.matchUpType,I=!1!==(o??r?.participants?.enforceGender)?i.gender:void 0,U=i.sides?.flatMap((t=>t.participant?.individualParticipants||t.participant)).filter(Boolean),S=U?.map(vo),y=i.sides?.filter((t=>!c||t.sideNumber===c)).flatMap((t=>t.participant?.individualParticipants||t.participant)).filter(Boolean),v=y?.map(vo),w=e?.find((t=>t.matchUpId===i.matchUpTieId)),T=w?.sides?.map((t=>t.participant?.individualParticipants.filter((({participantId:t,person:e})=>!v?.includes(t)&&(!I||I===sl||e.sex===I||I===ul&&!h||h&&e.sex!==h))))),P=c?T?.[c-1]:T?.map(((t,e)=>({participants:t,sideNumber:e+1}))),D=c?T?.[c-1]?.map(vo):T?.map(((t,e)=>({participants:t?.map(vo),sideNumber:e+1}))),b=c&&(g===Hc&&!v?.length||g===Yc&&(v?.length??0)<2)||!c&&(g===Hc&&(v?.length??0)<2||g===Yc&&(v?.length??0)<4),N=D?.filter((t=>!S?.includes(t))),M=P?.filter((({participantId:t})=>N.includes(t)));if(b&&N?.length&&m.push({availableParticipantIds:N,method:fU,availableParticipants:M,type:HI,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:p}}),!v?.length||Gc(d)&&!l?.substitutions?.length||m.push({method:hU,type:vU,existingParticipantIds:v,payload:{participantId:void 0,tieMatchUpId:u,drawId:p}}),M?.length&&(!c&&v?.length||c&&l?.participant)&&m.push({availableParticipantIds:N,method:mU,availableParticipants:M,type:yU,existingParticipantIds:v,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:p}}),lU({policyActions:a,action:SU})&&l?.substitutions?.length){const t=l.participant?.participantType===au&&[l.participantId]||l.participant?.participantType===su&&l.participant.individualParticipantIds||[],e=l.substitutions.map((t=>t.participantId)).filter((e=>t.includes(e)));s&&!e.includes(s)||m.push({method:hU,type:SU,substitutedParticipantIds:e,payload:{participantId:void 0,tieMatchUpId:u,drawId:p}})}const R=t?.[ga],A=R?.substituteWithoutScore,E=R?.substituteAfterCompleted;if(lU({policyActions:a,action:TU})&&2===n.length&&(!c&&v?.length||c&&l?.participant)&&(A||Gc(d))&&(E||d.matchUpStatus&&!Ho.includes(d.matchUpStatus))&&y?.length&&P.length){const t=y.map(vo);m.push({info:"list of team players available for substitution",method:UU,availableParticipantIds:D,existingParticipantIds:t,availableParticipants:P,existingParticipants:y,type:TU,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:p}})}return m}({specifiedPolicyDefinitions:i,inContextDrawMatchUps:y,matchUpParticipantIds:T,matchUpActionsPolicy:g,inContextMatchUp:v,policyActions:U,enforceGender:a,participantId:o,sideNumber:s,matchUpId:c,matchUp:l,drawId:p,side:w});N.push(...t)}return{structureIsComplete:A,validActions:N,isDoubleExit:G}}function OU(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&&ym({withIndividualParticipants:!0,tournamentRecord:i}).participants)??[];let u=Qs({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=Gl({drawDefinition:a,structureId:p}),void 0===o&&!u.isAdHoc)return{error:tt};if(u.isAdHoc)return CU(t);if(u.error)return u;const{drawPositionInitialRounds:l,inactiveDrawPositions:f,activeDrawPositions:h,byeDrawPositions:g}=u,I=Tu({tournamentRecord:i,drawDefinition:a,structure:d,event:s}).appliedPolicies??{};Object.assign(I,e??{});const{actionsPolicy:U,enabledStructures:S,actionsDisabled:y}=uU({actionType:sU,appliedPolicies:I,drawDefinition:a,structure:d}),v=U?.activePositionOverrides||[],{sourceStructureIds:w}=CI({finishingPosition:Ws,targetRoundNumber:1,linkType:hs,drawDefinition:a,structureId:p})||{};let T;w?.length&&(T=w.reduce(((t,e)=>Bf({structureId:e,drawDefinition:a})&&t),!0));const P=w.length,D=w.length&&!T,{policyActions:b}=pU({enabledStructures:S,drawDefinition:a,structure:d}),N=![Qo,Jo].includes(d.stage)||1!==d.stageSequence,{drawId:M}=a,R=[],{assignedPositions:A,positionAssignments:E}=ec({structure:d}),C=A?.find((t=>t.drawPosition===o)),O=E?.map((t=>t.drawPosition));if(!O?.includes(o))return{error:X};const{stage:F,stageSequence:k}=d,_=[F];F===Zo&&_.push(Jo),F===Jo&&_.push(Zo);const x=ad({entryStatuses:Xu,provisionalPositioning:r,drawDefinition:a,stageSequence:k,structureId:p,stages:_}),L=rm({drawDefinition:a,stages:_}).assignedParticipantIds??[],B=x.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(lU({policyActions:b,action:HI})&&!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?.[Pa]?.validSeedPositions?.ignore;if(!v){const t=If({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:VI,type:tU}),a&&v){const e=o.map((t=>t.participantId)).filter(Boolean),r={structureIds:t},{completedMatchUps:a}=Il({inContext:!0,matchUpFilters:r,drawDefinition:u}),c=m((a??[]).filter((({matchUpType:t})=>h?.eventType!==Zd||t===Zd))?.map((({sides:t})=>t?.map(vo))).flat().filter((t=>t&&!e.includes(t)))),d=s?i?.filter((t=>c?.includes(t.participantId))).map((t=>mi(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(br({payload:{drawId:g,structureId:f,drawPosition:l},willDisableLinks:n,method:BI,type:HI,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(rU),t=e.map((t=>t.participantId))}else t=e;const r=s?i?.filter((e=>t.includes(e.participantId))).map((t=>mi(t,void 0,!0))):void 0;r?.length&&I.push(br({payload:{drawId:g,structureId:f,drawPosition:l},willDisableLinks:n,method:BI,type:HI,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=>R.push(t)))}if(lU({policyActions:b,action:qI})){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?.[ha],h=!f?.disableRoundRestrictions&&t[o],g=f?.requireCompletedStructures,{sourceStructureIds:I,relevantLinks:U}=CI({targetRoundNumber:h,linkType:gs,drawDefinition:a,structureId:s})||{};I?.length&&l.push(...I);const{sourceStructureIds:S,relevantLinks:y}=CI({targetRoundNumber:h,linkType:hs,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!==Qo)continue;const i=Bf({structureId:t.source.structureId,drawDefinition:a});if(!g||i){const t=n.qualifyingRoundNumber,{matchUps:i}=ml({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===No&&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!==Qo)continue;const i=Bf({structureId:t.source.structureId,drawDefinition:a});if(!g||i){const{positionAssignments:t}=tc({structure:n}),i=t?.map((t=>{const e=t.participantId,n=Fr({element:t,name:ao}).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(br({payload:{qualifyingParticipantId:void 0,drawPosition:o,structureId:s,drawId:c},method:OI,type:qI,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:M});t?.forEach((t=>R.push(t)))}const{participantId:q}=C||{},$=q&&c.find((t=>t.participantId===q));if(C){lU({policyActions:b,action:zI})&&!G&&(R.push({type:zI,method:_I,payload:{drawId:M,structureId:p,drawPosition:o},willDisableLinks:N}),V||R.push({type:WI,method:"withdrawParticipantAtDrawPosition",payload:{drawId:M,structureId:p,drawPosition:o},willDisableLinks:N}),lU({policyActions:b,action:tU})&&!V&&R.push({type:tU,method:_I,payload:{drawId:M,structureId:p,drawPosition:o,replaceWithBye:!0},willDisableLinks:N}));const t=d.stage===Qo||d.stage===Jo&&1===d.stageSequence;if(!V&&dU({activePositionOverrides:v,activeDrawPositions:h,action:ZI})&&lU({policyActions:b,action:ZI})&&gf({drawDefinition:a,structureId:p,drawPosition:o})&&t){const{seedAssignments:t}=od({returnAllProxies:!0,drawDefinition:a,structure:d}),{seedNumber:e,seedValue:n}=t?.find((t=>t.participantId===q))??{};R.push({type:ZI,method:"modifySeedAssignment",participant:$,seedNumber:e,payload:{drawId:M,structureId:p,participantId:q,seedValue:n}})}if(!V&&dU({activePositionOverrides:v,activeDrawPositions:h,action:KI})&&lU({policyActions:b,action:KI})&&gf({drawDefinition:a,structureId:p,drawPosition:o})&&t){const{seedAssignments:t}=od({returnAllProxies:!0,drawDefinition:a,structure:d}),{seedNumber:e}=t?.find((t=>t.participantId===q))??{};R.push({method:"removeSeededParticipant",type:KI,participant:$,seedNumber:e,payload:{participantId:q,structureId:p,drawId:M}})}if(!V&&q){if(lU({policyActions:b,action:XI})){const t={type:XI,method:jI,participant:$,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:M}};R.push(t)}if(lU({policyActions:b,action:QI})){const t={type:QI,method:"modifyParticipantOtherName",participant:$,payload:{participantId:q,otherName:void 0}};R.push(t)}}if(lU({policyActions:b,action:JI})){const{validSwapAction:t}=iU({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:M});t&&R.push(t)}}if(lU({policyActions:b,action:$I})&&!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===HI))?.availableParticipantIds,h=a?.[ha]?.otherFlightEntries,g=a?.[ha]?.restrictQualifyingAlternates,I=(o.entries??[]).filter((({entryStage:t})=>!g||(d.stage===Qo?t===Qo:t!==Qo))).sort(((t,e)=>(t.entryPosition??1/0)-(e.entryPosition??1/0))).map((({participantId:t})=>t)).filter(Boolean),{allPositionedParticipantIds:U}=Xs({drawDefinition:o}),S=r.map((t=>t.participantId)).filter(Boolean),y=I.filter((t=>d.stage&&[Qo,Jo,ts].includes(d.stage)?!U?.includes(t):!S.includes(t))),v=(l?.entries??[]).filter((t=>t.entryStatus===Lu&&nU({restrictQualifyingAlternates:g,structure:d,entry:t})&&(d.stage&&[Qo,Jo,ts].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?Fp({event:l}).flightProfile:void 0,e=t?.flights?.filter((t=>t.drawId!==p)).map((t=>t.drawEntries.filter((t=>t.participantId&&![Ju,zu,Yu].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:br({payload:{drawId:p,structureId:u,drawPosition:s},willDisableLinks:e,method:FI,availableAlternatesParticipantIds:w,type:$I,availableAlternates:T})};return{}}({possiblyDisablingAction:N,tournamentParticipants:c,positionAssignments:E,activeDrawPositions:h,returnParticipants:n,appliedPolicies:I,drawDefinition:a,drawPosition:o,validActions:R,structureId:p,structure:d,drawId:M,event:s});t&&R.push(t)}if(lU({policyActions:b,action:YI})&&!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}=Qs({structureId:e,drawDefinition:o}),r={};if(n?.finishingPosition===Hs&&(1!==l?.length||1!==m?.length)){const{matchUps:t}=ml({drawDefinition:o,structure:u,event:p}),{initialRoundNumber:e}=ql({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}=hl({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!==Zd||t===Zd))).map((({winningSide:t,sides:e})=>t&&e?.[1-(t-1)])).map(vo).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:YI,method:kI,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:M});t&&R.push(t)}if($?.participantType===su&&lU({policyActions:b,action:GI})){const{validModifyAssignedPairAction:t}=function({tournamentParticipants:t,returnParticipants:e,drawPosition:n,participant:r,drawId:i,event:a}){const o=a?.entries?.filter((({entryStatus:t})=>[zu,Yu].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:br({payload:{participantId:r.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:n,drawId:i},method:LI,availableIndividualParticipantIds:o,availableIndividualParticipants:s,existingIndividualParticipantIds:a,existingIndividualParticipants:c,type:GI},!1,!1,!0)}}return{}}({tournamentParticipants:c,returnParticipants:n,drawPosition:o,participant:$,drawId:M,event:s});t&&R.push(t)}return{hasPositionAssigned:!!C,isActiveDrawPosition:G,isDrawPosition:!0,isByePosition:V,validActions:R}}function FU({policyDefinitions:t,appliedPolicies:e,drawType:n}){const r=t?.[ba]?.drawTypeCoercion,i=e?.[ba]?.drawTypeCoercion;return("boolean"==typeof r?r:void 0)??(n&&r?.[n])??("boolean"==typeof i?i:void 0)??(n&&i?.[n])??!0}function kU({tournamentRecord:t,drawDefinition:e,stage:n=Jo,structureId:r,structure:i}){if(!t)return{error:x};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}=tc({drawDefinition:e,structureId:r,structure:i});return{positionAssignments:o??[],structureId:i?.structureId,error:a}}function _U({structureId:t,drawDefinition:e}){if(!e)return{error:j};if(!Ii(t))return{error:Nn};const n=hu({drawDefinition:e,structureId:t});if(n.error)return n;const r=n.links.target.flatMap((t=>t.target.feedProfile)).filter(Boolean),i=!P([fs,ms,ls,cs],r).length;return{...E,valid:i}}function xU({consideredEntries:t,policyDefinitions:e,tournamentRecord:n,appliedPolicies:r,participantMap:i,enforceGender:a,participants:o,event:s}){if(o&&i||!n||({participants:o,participantMap:i}=ym({tournamentRecord:n})),!o)return{error:Re};if(!Array.isArray(o))return{error:Nn};if(!s)return{error:Tt};const c=e?.[ga]??r?.[ga]??Am[ga],u=!1!==(a??c?.participants?.enforceGender),{eventType:d,gender:p}=s,l=d===Qd,f=d===Xd&&cu||l&&su||au,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&&[Qd,Xd].includes(d)&&t.participantType===au&&(am(e)||e===Ju),r=t.participantType!==f&&!n,a=!r&&l&&m(t?.individualParticipantIds?.map((t=>i?.[t]?.participant?.person?.sex)).filter(Boolean)??[])||[],o=!p||!a?.length||sl===p||[cl,pl].includes(p)&&a[0]===p||ul===p&&(1==a.length&&1===t.individualParticipantIds?.length||2===a.length),s=t?.person?.sex,c=!t?.person||!p||[sl,ul].includes(p)||[cl,pl].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}}var LU=Object.freeze({__proto__:null,allPlayoffPositionsFilled:Vf,checkValidEntries:xU,findDrawDefinition:EI,getAssignedParticipantIds:rm,getAvailablePlayoffProfiles:Bh,getDrawDefinitionTimeItem:Dl,getDrawParticipantRepresentativeIds:MI,getDrawTypeCoercion:FU,getEligibleVoluntaryConsolationParticipants:NI,getParticipantIdFinishingPositions:RI,getPositionAssignments:kU,getPositionsPlayedOff:xh,getSeedingThresholds:pf,getSeedsCount:yI,getStructureSeedAssignments:od,getTeamLineUp:tl,getValidGroupSizes:cf,isAdHoc:nl,isCompletedStructure:Bf,isValidForQualifying:_U,positionActions:OU});function BU({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||VU({drawSize:u,qualifyingRoundNumber:f});let M,R,A;if(!p(u))return Nr({result:{error:it},stack:"generateQualifyingSTructures"});const E=t.length>1?`${h}-`:"",C=d.length>1||E?y:"",O=T||(E||C?`${zm(Qo)} ${E}${C}`:zm(Qo));if(D===Bs){const{structures:t,groupCount:a,maxRoundNumber:s}=sf({structureName:o.structureName||O,structureId:P||i?.pop(),stage:Qo,structureOptions:g,appliedPolicies:e,stageSequence:y,matchUpType:b,roundTarget:h,drawSize:u,idPrefix:n,isMock:r,uuids:i});v=a,M=s,R=t[0],l=[1]}else({drawSize:u,matchUps:A,roundLimit:M}=Ah({qualifyingRoundNumber:f,qualifyingPositions:N,matchUpType:b,drawSize:u,idPrefix:n,isMock:r,uuids:i})),R=Ym({structureName:o.structureName||O,structureId:P||i?.pop(),qualifyingRoundNumber:M,stage:Qo,matchUpFormat:w,stageSequence:y,matchUpType:b,roundLimit:M,matchUps:A}),h&&Cr({extension:{name:to,value:h},element:R}),v=A?.filter((t=>t.roundNumber===M))?.length||0;if(y>1){const{link:t}=Nh({sourceStructureId:U,sourceRoundNumber:I,targetStructureId:R.structureId,finishingPositions:S===hs?[1]:void 0,linkType:S});c.push(t),m+=(u||0)-v}else m+=u||0;S=D===Bs?hs:gs,U=R.structureId,I=M,s.push(R),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 VU({drawSize:t,qualifyingRoundNumber:e}){let n=t,r=0;for(;r<e;)n=Math.floor(n/2),r+=1;return n}function jU({structureName:t,matchUpType:e,idPrefix:n,drawSize:r,isMock:i,uuids:a}){const o=[],{matchUps:s}=Gh({linkFedFinishingRoundNumbers:[1],drawSize:r+1,matchUpType:e,idPrefix:n,isMock:i}),c=Ym({structureName:t||zm(Jo),structureId:a?.pop(),stageSequence:1,stage:Jo,matchUpType:e,matchUps:s});o.push(c);const u=r/2,{matchUps:d}=Gh({finishingPositionOffset:u,idPrefix:n&&`${n}-c`,drawSize:r-1,isConsolation:!0,matchUpType:e,isMock:i,uuids:a}),p=Ym({structureName:zm(Gs),matchUps:d,structureId:a?.pop(),stage:Zo,stageSequence:2,matchUpType:e});o.push(p);const{matchUps:l}=Ah({idPrefix:n&&`${n}-p1t2`,drawSize:2,matchUpType:e,isMock:i}),m=Ym({structureName:zm(js),matchUps:l,structureId:a?.pop(),stageSequence:3,stage:ts,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?ms:fs;return{linkType:Is,source:{roundNumber:1+i,structureId:t.structureId},target:{feedProfile:a,roundNumber:n,structureId:e.structureId}}})),{linkType:gs,source:{roundNumber:a,structureId:e.structureId},target:{feedProfile:ms,roundNumber:i,structureId:t.structureId}},{linkType:gs,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:ms,roundNumber:1,structureId:n.structureId}},{linkType:Is,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:ms,roundNumber:1,structureId:n.structureId}}]}({mainStructure:c,consolationStructure:p,deciderStructure:m});return{structures:o,links:f,...E}}function GU(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 Ah(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}=Rh({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=Mh({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=Ul({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 qU(t){const{playoffAttributes:e,stageSequence:n=1,stage:r=Jo,matchUpType:i,drawSize:a,uuids:o}=t,s=t.structureId||(()=>{if(!t.isMock&&!t.idPrefix)return;return`${t.drawDefinition.drawId}-s-0`})()||o?.pop(),{appliedPolicies:c}=Tu(t),u=t.policyDefinitions?.[Da]||c?.[Da];t.skipRounds=t.skipRounds||a<=4&&(u?.feedMainFinal?0:1)||0;const d=t.structureName??e?.[0]?.name??zm(Jo),p={[Ss]:()=>({structures:[Ym({finishingPosition:Ws,stageSequence:n,structureName:d,matchUps:[],matchUpType:i,structureId:s,stage:r})],links:[],...E}),[Ns]:()=>{const{matchUps:e}=GU(t);return{structures:[Ym({stageSequence:n,structureName:d,matchUpType:i,structureId:s,matchUps:e,stage:r})],links:[],...E}},[Ts]:()=>(()=>{const{matchUps:e}=Ah(t);return{structures:[Ym({stageSequence:n,structureName:d,matchUpType:i,structureId:s,matchUps:e,stage:r})],links:[],...E}})(),[Ps]:()=>jU(t),[vs]:()=>qh({...t,roundOffsetLimit:3,playoffAttributes:e??qs}),[ws]:()=>qh({...t,roundOffsetLimit:2,playoffAttributes:e??$s}),[ts]:()=>qh(t),[ys]:()=>{const{matchUps:t}=Gh({drawSize:a,uuids:o,matchUpType:i});return{structures:[Ym({stageSequence:n,structureName:d,matchUpType:i,structureId:s,stage:Jo,matchUps:t})],links:[],...E}},[bs]:()=>$h(t),[Ds]:()=>zh({...t,feedRounds:1,fmlc:!0}),[_s]:()=>zh({...t,feedRounds:1}),[As]:()=>zh({...t,feedsFromFinal:1}),[Cs]:()=>zh({...t,feedsFromFinal:2}),[Fs]:()=>zh({...t,feedsFromFinal:3}),[Ls]:()=>zh(t),[Ms]:()=>Hh(t),[Bs]:()=>sf(t),[Vs]:()=>function(t){const{drawDefinition:e,structureOptions:n,requireSequential:r}=t,i={structureName:zm(Jo),...t,stage:Jo},{structures:a,groupCount:o,groupSize:s}=sf(i);if(o<1)return{error:wn};const c=n?.playoffGroups||[{finishingPositions:[1],structureName:zm(ts)}],[u]=a,{structures:d,links:p}=Yh({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 $U(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??FU({appliedPolicies:a,drawType:t.drawType}),m="generateDrawStructuresAndLinks";let f=l&&2===t.drawSize&&Ts||t.drawType||Ts;const h=[],g=[],I=t?.matchUpType??zc,U=s?.structures?.filter((({stage:t})=>t===Qo));U&&h.push(...U);const S=U?.map((({structureId:t})=>t)),y=s?.structures?.find((({stage:t,stageSequence:e})=>t===Jo&&1===e)),v=s?.links?.filter((t=>t.target.structureId===y?.structureId&&S?.includes(t.source.structureId))),w=(t,e)=>{if(t.linkType===hs&&e?.structures){const n=t.source.finishingPositions||[];return e.structures.length*n.length}if(t.linkType===gs&&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=tc({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&&BU({idPrefix:t.idPrefix,qualifyingProfiles:b,appliedPolicies:a,isMock:d,uuids:p});if(N?.error)return N;const{qualifyingDrawPositionsCount:M,qualifyingDetails:R,qualifiersCount:A}=N||{qualifyingDrawPositionsCount:T,qualifiersCount:P};M&&(N?.structures&&h.push(...N.structures),N?.links&&g.push(...N.links)),Object.assign(t,br({drawSize:u,matchUpType:I,tieFormat:c}));const C=f!==Ss&&(!u||isNaN(u)||u<2||!o&&![ys,Ns].includes(f)&&([Vs,Bs].includes(f)&&u<3||![Bs,Vs].includes(f)&&!r(u)));if(C&&!M)return Nr({context:{drawSize:u,invalidDrawSize:C},result:{error:nt},stack:m});const O=zs.includes(f);if(u&&n(u)<4&&O)if(l)f=Ts;else if(e)return Nr({context:{enforceMinimumDrawSize:e,invalidDrawSize:C,drawSize:u,drawType:f},result:{error:nt},stack:m});const{generators:F,error:k}=qU(t);if(k)return{error:k};const _=F[f];if(!_)return{error:J};const x=_?.();if(x.error)return x;const{structures:L,links:B}=x;if(L?.length){const t=L.find((({stage:t,stageSequence:e})=>t===Jo&&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(Ks),B?.length&&g.push(...B);const V=x.structures.find((({stage:t,stageSequence:e})=>t===Jo&&1===e));for(const t of R||[]){const{finalQualifyingRoundNumber:e,finalQualifyingStructureId:n,roundTarget:r,finishingPositions:i,linkType:a}=t,o=V&&Nh({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:M,qualifiersCount:A},structures:h,links:g}}function WU(t){const{modifyOriginal:e=!0,stageSequence:n=1,isMock:r}=t||{},i="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return Nr({result:{error:j},stack:i});const a=e?t.drawDefinition:mi(t.drawDefinition,!1,!0);let{tieFormat:o,matchUpType:s}=t;if(o){const t=Hg({tieFormat:o});if(t.error)return t}o=Jg(o??Bp({drawDefinition:a})?.tieFormat),s=s??(a.matchUpType||zc),t.tieFormat=o,t.matchUpType=s;const c=Tm({drawDefinition:a,stage:Jo});t.drawSize=t.drawSize??c,!c&&t.drawSize&&Th({drawSize:t.drawSize,drawDefinition:a,stageSequence:n,stage:Jo});const u=Fu({drawDefinition:a}).drawMatchUps.map(wo),d=$U(t);if(d.error)return Nr({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:Qo,drawDefinition:a})){const t=Th({drawSize:m.qualifyingDrawPositionsCount,stage:Qo,drawDefinition:a});if(t.error)return t}}if(f){const t=Ph({qualifiersCount:f,drawDefinition:a,stage:Jo});if(t.error)return t}const h=t.drawSize??c;Object.assign(t,br({drawSize:h,matchUpType:s,tieFormat:o}));const{matchUps:g,matchUpsMap:I}=gl({drawDefinition:a});o&&g?.forEach((t=>{if(!u.includes(t.matchUpId)){const{tieMatchUps:e}=Jh({tieFormat:o,matchUp:t,isMock:r});Object.assign(t,{tieMatchUps:e,matchUpType:s})}}));const{inContextDrawMatchUps:U}=Sl({drawDefinition:a,matchUpsMap:I});return kc({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:a}),{inContextDrawMatchUps:U,drawDefinition:a,matchUpsMap:I,...E,structures:p,matchUps:g,links:l}}function HU(t){const{drawType:e=Ts,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=Xo,m=ad({stageSequence:1,drawDefinition:p,stage:l}),f=[Bs,Ps,Vs].includes(e)?m.length:u(m.length);if(!a&&e===ys&&m.length<2||e===Bs&&m.length<3)return{error:nt};let{tieFormat:h,matchUpType:g}=t;if(h){const t=Hg({tieFormat:h});if(t.error)return t}h=Jg(h??Bp({drawDefinition:p})?.tieFormat),g=g??p.matchUpType??zc;const{structures:I}=Zs({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,br({structureName:t.structureName??zm(Xo),structureId:U,matchUpType:g,tieFormat:h,drawSize:f,stage:l}));const S=qU(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=>ml({structure:t}).matchUps)).flat();h&&P.forEach((t=>{const{tieMatchUps:e}=Jh({matchUp:t,tieFormat:h,isMock:c});Object.assign(t,{tieMatchUps:e,matchUpType:g})})),r&&n||(p=mi(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&&dh({seedingProfile:t.seedingProfile,applyPositioning:r,tournamentRecord:i,drawDefinition:p,structureId:U,placeByes:s,drawSize:f,event:d}),n&&kc({drawDefinition:p}),{links:T,structures:w,...E}}function zU(t){const{matchUpIds:e=[],drawDefinition:n,roundNumber:r,newRound:i,isMock:a,event:o}=t;if("object"!=typeof n)return{error:j};let{participantIdPairings:s,matchUpsCount:c}=t;const u=t.structureId??(1===n.structures?.length&&n.structures?.[0]?.structureId);if("string"!=typeof u)return{error:It};const d=n.structures?.find((t=>t.structureId===u));if(!d)return{error:Ut};let l;const m=d.matchUps??[],f=m?.reduce(((t,e)=>(e.roundPosition&&(l=!0),(e?.roundNumber||0)>t?e.roundNumber:t)),0);if(!c){const t=n?.entries?.filter((t=>{const e=t.entryStatus;return td.includes(e)}))??[],e=Math.floor(t?.length/2)||1;if(i)c=e;else{const t=r??f??1,n=e-(d.matchUps?.filter((e=>e.roundNumber===t))?.length??0);n>0&&(c=n)}}if(s&&!Array.isArray(s)||c&&!p(c)||e&&!Array.isArray(e)||!s&&!c)return{error:Nn,info:"matchUpsCount or pairings error"};if(d.structures||l||d.finishingPosition===Hs)return{error:$};if(r&&!t.ignoreLastRoundNumber&&r-1>(f||0))return{error:Nn,info:"roundNumber error"};const h=r??(i&&(f??0)+1||f||1);s=s??w(0,c).map((()=>({participantIds:[void 0,void 0]})));const g=s?.map(((r,i)=>{const o=r?.participantIds??[void 0,void 0];o.push(void 0,void 0);const s=o.slice(0,2).map(((t,e)=>br({sideNumber:e+1,participantId:t}))),c=e[i]??(e=>{if(!t.idPrefix&&!a)return;return`${n.drawId}-${t.idPrefix??"ah"}-${h}-${e}`})(i)??wp();return{roundNumber:h,matchUpStatus:Bo,matchUpId:c,sides:s}}));if(g?.length){const t=Bp({drawDefinition:n,event:o})?.tieFormat;t&&g.forEach((e=>{const{tieMatchUps:n}=Jh({tieFormat:t,matchUp:e,isMock:a});Object.assign(e,{tieMatchUps:n,matchUpType:Qc})}))}return{roundNumber:h,matchUpsCount:g?.length??0,matchUps:g,...E}}function YU(t){return t.participantIdPairings.map((({participantIds:t})=>t.sort().join("|"))).sort().join("/")}function KU({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=JU(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=JU(n,i),o=r[a];return o>t?o:t}),0),d=s.reduce(((t,e)=>{const[n,r]=e.participantIds,a=JU(n,r),o=i[a];return o>t?o:t}),0);return{value:c,participantIdPairings:s,maxDelta:u,maxDiff:d}}function JU(t,e){return[t,e].sort(pm).join("|")}function QU({participantIds:t}){const e={},n=[];t.forEach((r=>{e[r]=t.filter((t=>t!==r)),e[r].forEach((t=>{const e=JU(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 ZU="ELO",XU="NTRP",tS="WTN",eS={ELO:ZU,NTRP:XU,TRN:"TRN",UTR:"UTR",WTN:tS},nS={[ZU]:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!0},[XU]:{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]},[tS]:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!1,decimalsCount:2,range:[40,1]}},rS=0;function iS({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=nS[r]?.defaultInitialization??rS;return i.split("|").map((r=>{if(n===Jd){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=JU(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=KU({actorsCount:o.length,valueSortedPairings:e,pairingValueMap:a,deltaObjects:i,valueObjects:r}),u=[YU(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=JU(t,n.opponent);if(!g.includes(c)){const d=KU({stipulated:[[t,n.opponent]],actorsCount:o.length,valueSortedPairings:e,pairingValueMap:a,deltaObjects:i,valueObjects:r});if(!u.includes(YU(d))){u.push(YU(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 aS=100,oS=100,sS=4e3;function cS({encounterValue:t=aS,sameTeamValue:e=oS,maxIterations:n=sS,generateMatchUps:r=!0,tournamentParticipants:i,ignoreLastRoundNumber:a,participantIds:o,drawDefinition:s,adHocRatings:c,salted:u=.5,roundNumber:d,structureId:p,matchUpIds:l,eventType:m,structure:f,scaleName:h,idPrefix:g,isMock:I,event:U}){if(!s)return{error:j};if(!f&&!p)return{error:Ut};if(f||(f=Qs({drawDefinition:s,structureId:p}).structure),!Ui(f))return{error:yt};if(!o?.length)return{error:Fe};const{encounters:S}=function({matchUps:t}){const e=[];for(const n of t){const t=n.sides.map(vo);if(2===t.length){const[n,r]=t,i=JU(n,r);e.includes(i)||e.push(i)}}return{encounters:e}}({matchUps:f?.matchUps??[]}),y={};for(const e of S)y[e]||(y[e]=0),y[e]+=t;const v=i?.filter((({participantType:t})=>t===cu));if(v)for(const t of v){const n=t.individualParticipantIds??[],{uniquePairings:r}=QU({participantIds:n});for(const t of r)y[t]||(y[t]=0),y[t]+=e}const{uniquePairings:w,possiblePairings:T,deltaObjects:P}=QU({participantIds:o}),D={tournamentParticipants:i,possiblePairings:T,drawDefinition:s,participantIds:o,uniquePairings:w,maxIterations:n,adHocRatings:c,deltaObjects:P,valueObjects:y,eventType:m,scaleName:h,structure:f,salted:u},{candidatesCount:b,participantIdPairings:N,iterations:M,candidate:R}=iS(D);if(!b)return{error:vn};let A,C;if(r){const t=zU({structureId:f?.structureId,ignoreLastRoundNumber:a,participantIdPairings:N,newRound:!0,drawDefinition:s,roundNumber:d,matchUpIds:l,idPrefix:g,isMock:I,event:U});if(t.error)return t;A=t.roundNumber,C=t.matchUps}const{maxDelta:O,maxDiff:F}=R;return{roundNumber:A,participantIdPairings:N,candidatesCount:b,...E,iterations:M,matchUps:C,maxDelta:O,maxDiff:F}}function uS(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(!$g({matchUpFormat:i}))return{error:kt};if(o){const t=Dg({drawDefinition:r,matchUpId:o,event:s});if(t.error)return t;if(!t.matchUp)return{error:Wt};const e=t.matchUp;if(e?.matchUpType===Zd)return{error:Yt,info:"Cannot set matchUpFormat when { matchUpType: TEAM }"};e.matchUpFormat=i,Oc({tournamentId:n?.tournamentId,eventId:s?.eventId,context:"setMatchUpFormat",drawDefinition:r,matchUp:e})}else if(Array.isArray(e)){if(s?.eventType===Zd)return{error:wt};for(const t of e){const e=Qs({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===Zd)return{error:wt};const t=Qs({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),kc({drawDefinition:r,structureIds:e}),{...E}}function dS({tournamentRecord:t,categoryName:e,categoryType:n}){if(!t)return{error:x};const{appliedPolicies:r}=Tu({tournamentRecord:t}),i=r?.[Ta];return(i?.matchUpFormats||[]).filter((({categoryNames:t,categoryTypes:r})=>!e&&!r||e&&t?.includes(e)||n&&r?.includes(n)))}function pS({tournamentRecord:t,categoryName:e,categoryType:n}){if(!t)return{error:x};const{appliedPolicies:r}=Tu({tournamentRecord:t}),i=r?.[ba];return(i?.allowedDrawTypes||[]).filter((({categoryNames:t,categoryTypes:r})=>!e&&!r||e&&t?.includes(e)||n&&r?.includes(n)))}var lS={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}},mS={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}},fS={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}},hS={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}},gS={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}},IS={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}},US={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}},SS={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}},yS={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}},vS={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}]},wS={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}},TS={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}},PS={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}},DS={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}},bS={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}},NS={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}},MS={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 RS="COLLEGE_DEFAULT",AS="COLLEGE_JUCO",ES="COLLEGE_D3",CS="DOMINANT_DUO",OS="DOMINANT_DUO_MIXED",FS="LAVER_CUP",kS="TEAM_DOUBLES_3_AGGREGATION",_S="TIME_TENNIS_DUAL",xS="TIME_TENNIS_PRO_CIRCUIT",LS="USTA_BREWER_CUP",BS="USTA_OZAKI_CUP",VS="USTA_COLLEGE",jS="USTA_GOLD_TEAM_CHALLENGE",GS="USTA_LEVEL_1",qS="USTA_INTERSECTIONAL",$S="USTA_SECTION_BATTLE",WS="USTA_SOUTHERN_LEVEL_5",HS="USTA_TOC",zS="USTA_WTT_ITT",YS="USTA_ZONAL",KS={COLLEGE_D3:ES,COLLEGE_DEFAULT:RS,COLLEGE_JUCO:AS,DOMINANT_DUO:CS,DOMINANT_DUO_MIXED:OS,LAVER_CUP:FS,TEAM_DOUBLES_3_AGGREGATION:kS,TIME_TENNIS_DUAL:_S,TIME_TENNIS_PRO_CIRCUIT:xS,USTA_BREWER_CUP:LS,USTA_OZAKI_CUP:BS,USTA_COLLEGE:VS,USTA_GOLD_TEAM_CHALLENGE:jS,USTA_INTERSECTIONAL:qS,USTA_LEVEL_1:GS,USTA_SECTION_BATTLE:$S,USTA_SOUTHERN_LEVEL_5:WS,USTA_TOC:HS,USTA_WTT_ITT:zS,USTA_ZONAL:YS},JS="STANDARD",QS={[JS]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[ES]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1,matchUpFormat:"SET1-S:8/TB7@7"},singles:{matchUpFormat:Zh,matchUpCount:6,matchUpValue:1},tieFormatName:ES,valueGoal:5},[RS]:{hydrate:!0,doubles:{matchUpCount:3,collectionValue:1,matchUpFormat:Zh},singles:{matchUpCount:6,matchUpValue:1,matchUpFormat:Zh},tieFormatName:RS,valueGoal:4},[AS]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1,matchUpFormat:"SET1-S:8/TB7"},singles:{matchUpCount:6,matchUpValue:1,matchUpFormat:Zh},tieFormatName:AS,valueGoal:5},[FS]:NS,[CS]:wS,[OS]:US,[kS]:mS,[_S]:SS,[xS]:IS,[LS]:yS,[BS]:vS,[VS]:TS,[jS]:lS,[qS]:gS,[GS]:PS,[$S]:hS,[WS]:fS,[zS]:DS,[HS]:MS,[YS]:bS},ZS=t=>{const e=t?.namedFormat&&Object.keys(QS).includes(t.namedFormat)?t.namedFormat:JS,n=Array.isArray(t?.uuids)?t?.uuids:[];let r;const{category:i,gender:a}=t?.event??{},o=mi(QS[e],!1,!0),s=e=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return n?.pop()??wp();const r=t?.event?.eventId;return n.pop()??`${r}-COL-${e+1}`};return o.hydrate?(r={winCriteria:{valueGoal:o.valueGoal},collectionDefinitions:[{collectionId:s(0),matchUpFormat:Xh,collectionName:"Doubles",matchUpType:Kc,...o.doubles},{collectionId:s(1),matchUpFormat:Zh,collectionName:"Singles",matchUpType:zc,...o.singles}]},o.tieFormatName&&(r.tieFormatName=o.tieFormatName)):(o.collectionDefinitions.forEach(((t,e)=>t.collectionId=s(e))),r=o),t?.hydrateCollections&&r.collectionDefinitions.forEach((t=>{i&&!t.category&&(t.category=i),a&&!t.gender&&(t.gender=a)})),r};function XS(t){const{restrictEntryStatus:e,adHocRatings:n={},generateMatchUps:r,tournamentRecord:i,encounterValue:a,sameTeamValue:o,drawDefinition:s,scaleAccessor:c,maxIterations:u,roundsCount:d,matchUpIds:p,scaleName:l,idPrefix:m,salted:f,event:h}=t;if(d&&"number"!=typeof d)return{error:Nn,info:"roundsCount must be a number"};if("object"!=typeof s||s.drawType&&s.drawType!==Ss)return{error:V};let{participantIds:g,structureId:I}=t;const U=i?.isMock??t.isMock;if(!Array.isArray(s?.entries)&&g&&!Array.isArray(g))return{error:Nn,info:"Missing Entries"};const S=t.eventType??h?.eventType,y=s?.entries?.filter((t=>{const n=t.entryStatus;return!e||td.includes(n)})).map(vo)??[];if(g){const t=g.filter((t=>!y?.includes(t)));if(t?.length)return Nr({result:{error:Te},info:{invalidParticipantIds:t}})}else g=y;if(d&&d>g.length-1)return{error:Nn,info:"Not enough participants for roundsCount"};if(!I){const t=s?.structures?.filter((t=>1===t.stageSequence))?.reduce(((t,e)=>{const n=e.stage&&ns[e.stage];return nl({drawDefinition:s,structure:e})&&n>(ns[t?.stage]||1)?e:t}),void 0);I=t?.structureId}const v=s?.structures?.find((t=>t.structureId===I));if(!v)return{error:Ut};if(!nl({drawDefinition:s,structure:v}))return{error:V};const T=i.participants??[];for(const t of g??[]){const e=T?.find((e=>e.participantId===t));let r=ty({scaleName:`${l}.${ia}`,scaleAccessor:c,participant:e,eventType:S});!r&&l&&(r=ty({scaleAccessor:c,participant:e,scaleName:l,eventType:S})),r&&!n[t]&&(n[t]=r)}const P=[],D=[];let b;for(const t of w(0,d??1)){const e=cS({ignoreLastRoundNumber:!0,tournamentParticipants:T,generateMatchUps:r,participantIds:g,encounterValue:a,sameTeamValue:o,drawDefinition:s,maxIterations:u,adHocRatings:n,roundNumber:b,matchUpIds:p,structure:v,eventType:S,idPrefix:m,salted:f,isMock:U,event:h});if(e.error)return e;const{matchUps:i,...c}=e;D.push({...c,iteration:t,matchUpsCount:i?.length}),b=(c?.roundNumber||1)+1,i?.length&&P.push(...i)}return{...E,matchUps:P,roundResults:D}}function ty({scaleType:t=oa,scaleAccessor:e,participant:n,scaleName:r,eventType:i}){const a=n&&cm({scaleAttributes:{eventType:i??Kd,scaleType:t,scaleName:r},participant:n}),o=a?.scaleItem?.scaleValue;return e&&Ui(o)?o[e]:o}const ey=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});function ny(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:M}=t,R=U?.eventType,A=I.filter((t=>{const e=Fr({name:to,element:t})?.extension?.value;return(!t.entryStage||t.entryStage===M)&&(!b||!t.entryStageSequence||t.entryStageSequence===b)&&(!N||!e||e===N)&&Xu.includes(t.entryStatus)}));T&&(n=T.length),n>g&&(n=g),n>A.length&&(n=A.length);const{structures:C}=Zs({drawDefinition:u,stageSequence:b,roundTarget:N,stage:M}),O=(C?.length||0)>1,F=C?.find((({structureId:t})=>!r.includes(t)));if(!F)return Nr({result:{error:Ut},stack:e});const k=F?.structureId,_=F?ff({provisionalPositioning:i,appliedPolicies:s,drawDefinition:u,seedingProfile:d,structure:F}):void 0,{seedLimit:x}=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=Qs({drawDefinition:o,structureId:c});if(d.error)return d;const l=d.structure;if(!l)return{error:Ut};const{positionAssignments:m}=ec({structure:l}),f=m?.length||0;if(u>f)return{error:ct};const h=l.structures?.length,g=p(s?.groupSeedingThreshold)&&s?.groupSeedingThreshold,I=df({roundRobinGroupsCount:h,drawSize:f})?.seedGroups,{seedsCount:U}=yI({policyDefinitions:a,requireParticipantCount:t,drawSizeProgression:n,participantsCount:r,drawSize:f});return U&&a?.[Pa]&&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}})),kc({drawDefinition:o,structureIds:[c]}),{...E,seedLimit:u}}({participantsCount:A.length,enforcePolicyLimits:S,appliedPolicies:s,drawDefinition:u,seedingProfile:d,structureId:k,seedsCount:n});x&&x<n&&(n=x);const L=I.map(vo);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;Sf({provisionalPositioning:i,tournamentRecord:o,drawDefinition:u,seedingProfile:d,participantId:e,seedBlockInfo:_,structureId:k,seedNumber:n,seedValue:r,event:U})}));else if(U||D){const{categoryName:t,ageCategoryCode:e}=U?.category||{},r={scaleType:ca,scaleName:D||t||e||U.eventId,eventType:R};let{scaledEntries:a}=PI({scaleAttributes:r,tournamentRecord:o,stageSequence:b,entries:I,stage:M});if(!a?.length&&v){const n={scaleName:t||e,scaleType:aa,eventType:R};({scaledEntries:a}=PI({scaleAttributes:n,tournamentRecord:o,stageSequence:b,entries:I,stage:M}))}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;Sf({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!==Ss&&(!c||M===Qo)){const t="object"==typeof m&&m.seedsOnly,n=dh({inContextDrawMatchUps:a,multipleStructures:O,tournamentRecord:o,appliedPolicies:s,drawDefinition:u,seedingProfile:d,structureId:k,matchUpsMap:l,placeByes:f,seedLimit:x,seedsOnly:t,drawSize:g,drawType:h,event:U});if(n.conflicts&&(j=n?.conflicts),B=n?.positionAssignments,V=n?.positioningReport,n.error)return Nr({result:n,stack:e})}return{positionAssignments:B,positioningReport:V,stageEntries:A,structureId:k,seedsCount:n,conflicts:j}}const ry={[Pa]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[Vs]:{positioning:cs},[Bs]:{positioning:cs}},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 iy(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=t.isMock??!0,I=t.idPrefix,U=Tu({tournamentRecord:c,event:h}).appliedPolicies??{},S=mi(t.policyDefinitions??{},!1,!0),y=(t.drawTypeCoercion??FU({drawType:t.drawType,policyDefinitions:S,appliedPolicies:U}))&&2===t.drawSize&&Ts||t.drawType||Ts,v=S?.[Pa]??U?.[Pa],T=t.seedingProfile??v?.seedingProfile?.drawTypes?.[y]??v?.seedingProfile;t.seedingProfile&&(S[Pa]||(S[Pa]={...ry[Pa]}),S[Pa].seedingProfile=T);const{participants:P,participantMap:D}=ym({withIndividualParticipants:!0,convertExtensions:!0,internalUse:!0,tournamentRecord:c}),b=t.enforceGender??S?.[ga]?.participants?.enforceGender??U?.[ga]?.participants?.enforceGender,N=!i&&c&&pS({tournamentRecord:c,categoryType:h?.category?.categoryType,categoryName:h?.category?.categoryName});if(N?.length&&!N.includes(y))return Nr({result:{error:et},stack:e});const M=h?.entries?.filter((t=>t.entryStatus&&[...td,Wu].includes(t.entryStatus)))??[],R=(d&&[]||m||(r?M:[])).filter((({entryStage:t})=>!t||t===Jo)),A=h&&P&&xU({consideredEntries:R,appliedPolicies:U,participantMap:D,enforceGender:b,participants:P,event:h});if(A?.error)return Nr({result:A,stack:e});const C=!t.drawSize&&R.length&&![Ss,Ps,ys,Bs,Vs].includes(y)&&u(R.length)||t.drawSize&&p(t.drawSize)&&n(t.drawSize)||!1;if(isNaN(C)&&y!==Ss)return Nr({result:{error:it},stack:e});let O="number"!=typeof t.seedsCount?n(t.seedsCount??0):t.seedsCount??0;const F=h?.eventType,k=t.matchUpType??F,_=t.drawId?h?.drawDefinitions?.find((e=>e.drawId===t.drawId)):void 0;let{tieFormat:x,matchUpFormat:L}=t;if(k===Qc&&F===Qc){const t=_?.structures?.find((({stage:t})=>t===Jo))?.tieFormat;x=x||t||l&&h?.tieFormat?.tieFormatName===l&&h.tieFormat||l&&ZS({namedFormat:l,hydrateCollections:o,isMock:g,event:h})||h?.tieFormat||ZS({event:h,isMock:g,hydrateCollections:o}),L=void 0}else L||(x=void 0,h?.matchUpFormat||(L=Zh));if(x){const t=Hg({gender:h?.gender,enforceGender:b,tieFormat:x});if(t.error)return Nr({result:t,stack:e})}if(t.drawId&&"string"!=typeof t.drawId)return Nr({result:{error:Nn},stack:e});_&&y!==_.drawType&&(_.drawType=y);let B=_??function(t){const{drawId:e=wp(),processCodes:n,matchUpType:r,drawType:i}=t??{},a=ey();return Object.assign(a,{processCodes:n,matchUpType:r,drawType:i,drawId:e})}({drawType:y,drawId:t.drawId,processCodes:t.processCodes});if(L||x){if(!(L&&h?.matchUpFormat===L||h?.tieFormat&&x&&JSON.stringify(h.tieFormat)===JSON.stringify(x))){if(x){const t=function({tieFormat:t}){const e=Hg({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(const e of t.collectionDefinitions)e.collectionId||(e.collectionId=wp());return{tieFormat:t}}({tieFormat:x});if(t.error)return Nr({result:t,stack:e});B.tieFormat=t.tieFormat??x}else if(L){const t=uS({tournamentRecord:c,drawDefinition:B,matchUpFormat:L,event:h});if(t.error)return{error:t.error,info:"matchUpFormat or tieFormat error"}}k&&(B.matchUpType=k)}}const V={[wa]:U[wa]};if(S){if("object"!=typeof S)return Nr({info:"policyDefinitions must be an object",result:{error:Nn},stack:e});for(const t of Object.keys(S))JSON.stringify(U?.[t])!==JSON.stringify(S[t])&&(V[t]=S[t]);Object.keys(V).length&&(sI({policyDefinitions:V,drawDefinition:B}),Object.assign(U,V))}else V.avoidance&&sI({drawDefinition:B,policyDefinitions:V});U[Pa]||S[Pa]||(sI({policyDefinitions:ry,drawDefinition:B}),Object.assign(U,ry));let j=_?.structures?.find((t=>t.stage===Jo&&1===t.stageSequence))?.structureId;const G=m??M,q=[];let $,W=[];const H=t.qualifyingPlaceholder&&!t.qualifyingProfiles?.length&&!_,z=_?_.structures?.filter((t=>t.stage===Qo)):[],Y=1===z?.length&&!z[0].matchUps?.length&&z[0].structureId;if(Y){const e=t.qualifyingProfiles,n=e?.length?BU({uuids:t.uuids,qualifyingProfiles:e,appliedPolicies:U,idPrefix:I,isMock:g}):void 0;if(n?.error)return n;B.structures=B.structures?.filter((({structureId:t})=>t!==Y)),B.links=B.links?.filter((({source:t})=>t.structureId!==Y));const{qualifiersCount:r,qualifyingDrawPositionsCount:i,qualifyingDetails:a}=n??{};i&&(n?.structures&&B.structures?.push(...n.structures),n?.links&&B.links?.push(...n.links));const o=B.structures?.find((({stage:t,stageSequence:e})=>t===Jo&&1===e)),{qualifiersCount:s}=wm({stageSequence:1,drawDefinition:B,structureId:j,stage:Jo});let c=Ph({qualifiersCount:Math.max(r??0,s??0),drawDefinition:B,stage:Jo});if(c.error)return c;if(c=Th({drawSize:i,stage:Qo,drawDefinition:B}),c.error)return c;for(const t of(m??[]).filter((({entryStage:t})=>t===Qo))){bm({...t,entryStage:t.entryStage??Jo,drawDefinition:B})}for(const t of a||[]){const{finalQualifyingRoundNumber:e,finalQualifyingStructureId:n,roundTarget:r,finishingPositions:i,linkType:a}=t,s=o&&Nh({targetStructureId:o.structureId,sourceStructureId:n,sourceRoundNumber:e,finishingPositions:i,targetEntryRound:r,linkType:a})?.link;if(s?.error)return s;s&&(B.links||(B.links=[]),B.links.push(s))}$={drawDefinition:B}}else{if($=WU({...t,modifyOriginal:!1,tournamentRecord:c,appliedPolicies:U,drawDefinition:B,matchUpFormat:L,matchUpType:k,tieFormat:x,drawSize:C,isMock:g}),$.error)return Nr({result:$,stack:e});B=$.drawDefinition;for(const t of G){if(m&&t.entryStage&&t.entryStage!==Jo)continue;const n=bm({...t,ignoreStageSpace:s??y===Ss,entryStage:t.entryStage??Jo,drawDefinition:B,drawType:y});if(m&&n.error)return Nr({result:n,stack:e})}y===Ns&&(O=0);const n=ny({...$,...t,qualifyingOnly:!C||d,appliedPolicies:U,drawDefinition:B,seedingProfile:T,participants:P,stage:Jo,seedsCount:O,placeByes:f,drawSize:C,entries:G});if(n.error&&!n.conflicts)return n;if(n.positioningReport?.length&&q.push({[Jo]:n.positioningReport}),j=n.structureId,n.conflicts&&(W=n.conflicts),y===Ss&&t.roundsCount){const e=h?.entries?.filter((({entryStage:t,entryStatus:e})=>(!t||t===Jo)&&e&&td.includes(e))),n=e?.map(vo),r=e?Math.floor(e.length/2):0;if(t.automated){const{restrictEntryStatus:e,generateMatchUps:r,structureId:i,matchUpIds:a,scaleName:o}=t.drawMatic??{};II({matchUps:XS({eventType:t.drawMatic?.eventType??k,generateMatchUps:r??!0,roundsCount:t.roundsCount,restrictEntryStatus:e,tournamentRecord:c,participantIds:n,drawDefinition:B,structureId:i,matchUpIds:a,scaleName:o,idPrefix:I,isMock:g,event:h}).matchUps,tournamentRecord:c,drawDefinition:B,structureId:i})}else w(1,t.roundsCount+1).forEach((()=>{const{matchUps:t}=zU({newRound:!0,drawDefinition:B,matchUpsCount:r,idPrefix:I,isMock:g,event:h});II({tournamentRecord:c,drawDefinition:B,structureId:j,matchUps:t})}))}}const K=[];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 Nr({info:wf("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=ny({...$,...t,seedingProfile:e.seedingProfile??T,stageSequence:s,qualifyingRoundNumber:n,preparedStructureIds:i,qualifyingPositions:r,seededParticipants:o,stage:Qo,seedingScaleName:c,appliedPolicies:U,drawDefinition:B,qualifyingOnly:d,seedByRanking:p,participants:P,roundTarget:a,seedsCount:u,placeByes:l,drawSize:m,entries:G});if(f.error)return f;f.structureId&&i.push(f.structureId),s+=1,f.conflicts?.length&&K.push(...f.conflicts),f.positioningReport?.length&&q.push({[Qo]:f.positioningReport})}a+=1}}else if(j&&H){const t=Ym({structureName:zm(Qo),stage:Qo}),{link:e}=Nh({sourceStructureId:t.structureId,targetStructureId:j,sourceRoundNumber:0,linkType:hs});B.structures||(B.structures=[]),B.structures.push(t),B.links||(B.links=[]),B.links.push(e)}return B.drawName=t.drawName??(y&&zm(y)),"object"==typeof a&&C>=4&&Km({...a,drawDefinition:B,matchUpType:k}),{existingDrawDefinition:!!_,qualifyingConflicts:K,positioningReports:q,drawDefinition:B,structureId:j,...E,conflicts:W}}var ay=Object.freeze({__proto__:null,addAdHocMatchUps:II,addDrawDefinitionTimeItem:vh,addPlayoffStructures:oI,addQualifyingStructure:Ch,addVoluntaryConsolationStage:Dh,addVoluntaryConsolationStructure:Km,allPlayoffPositionsFilled:Vf,alternateDrawPositionAssignment:Rf,assignDrawPosition:fI,assignDrawPositionBye:Yl,attachConsolationStructures:rI,attachPlayoffStructures:iI,attachQualifyingStructure:Sh,attachStructures:aI,autoSeeding:DI,automatedPlayoffPositioning:ph,automatedPositioning:dh,checkValidEntries:xU,deleteAdHocMatchUps:hI,drawMatic:XS,findDrawDefinition:EI,generateAdHocMatchUps:zU,generateAndPopulatePlayoffStructures:nI,generateDrawDefinition:iy,generateDrawMaticRound:cS,generateDrawStructuresAndLinks:$U,generateDrawTypeAndModifyDrawDefinition:WU,generateQualifyingStructure:Eh,generateVoluntaryConsolation:HU,getAssignedParticipantIds:rm,getAvailablePlayoffProfiles:Bh,getDrawDefinitionTimeItem:Dl,getDrawParticipantRepresentativeIds:MI,getDrawTypeCoercion:FU,getEligibleVoluntaryConsolationParticipants:NI,getParticipantIdFinishingPositions:RI,getPositionAssignments:kU,getPositionsPlayedOff:xh,getSeedingThresholds:pf,getSeedsCount:yI,getStructureSeedAssignments:od,getTeamLineUp:tl,getValidGroupSizes:cf,isAdHoc:nl,isCompletedStructure:Bf,isValidForQualifying:_U,luckyLoserDrawPositionAssignment:Mf,modifyDrawDefinition:dI,modifyDrawName:uI,modifySeedAssignment:kf,mutate:bI,positionActions:OU,pruneDrawDefinition:mI,qualifierDrawPositionAssignment:Ef,query:LU,removeDrawPositionAssignment:$m,removeRoundMatchUps:gI,removeSeededParticipant:bh,removeStructure:wh,renameStructures:yh,resetDrawDefinition:pI,resetVoluntaryConsolationStructure:Lc,setDrawParticipantRepresentativeIds:Po,setPositionAssignments:Af,setStructureOrder:lh,setSubOrder:UI,swapDrawPositionAssignments:Ff,updateTeamLineUp:Pf,withdrawParticipantAtDrawPosition:Wm});function oy({tournamentRecord:t,drawDefinition:e,participantId:n,entryPosition:r,skipRefresh:i,event:a}){if(!t)return{error:x};if(!n)return Nr({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=im({entries:a.entries})),e?.entries&&(o(e),e.entries=im({entries:e.entries}))),{...E}}function sy({tournamentRecord:t,entryPositions:e,drawDefinition:n,event:r}){if(!t)return{error:x};if(!Array.isArray(e))return{error:Nn};for(const i of e){const{participantId:e,entryPosition:a}=i,o=oy({skipRefresh:!0,tournamentRecord:t,drawDefinition:n,participantId:e,entryPosition:a,event:r});if(o.error)return o}return r?.entries&&(r.entries=im({entries:r.entries})),n?.entries&&(n.entries=im({entries:n.entries})),{...E}}function cy(t){const{participantId:e}=t;return e&&"string"!=typeof e?{error:Nn,participantId:e}:uy({...t,participantIds:[e].filter(Boolean)})}function uy({tournamentRecord:t,drawDefinition:e,participantIds:n,stageSequence:r,stage:i=Jo,eventId:a,event:o}){if(!t)return{error:x};if(!Array.isArray(n))return{error:Nn,participantIds:n};if(!o)return{error:Tt};if(o){const t=dy({element:o,participantIds:n,stageSequence:r,stage:i});if(t.error)return t}if(e){const t=dy({element:e,participantIds:n,stageSequence:r,stage:i});if(t.error)return a?Nr({context:{drawPromotionError:t.error,drawId:e.drawId},result:{...E},stack:"promoteAlternates"}):t}return{...E}}function dy({participantIds:t,stageSequence:e,element:r,stage:i}){const a=(r.entries||[]).filter((t=>t.entryStatus===Lu)),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!==Lu));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=Vu;const e=t?.entryPosition;isNaN(e)||r.entries.forEach((t=>{t.entryStatus===Lu&&t.entryPosition>e&&(t.entryPosition=t.entryPosition-1)}));const i=Math.max(...r.entries.filter((t=>t.entryStatus===Vu&&!isNaN(t.entryPosition))).map((({entryPosition:t})=>n(t||0))),0);t.entryPosition=i||0}return{...E}}function py({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(rm({drawDefinition:n,stages:i}).assignedParticipantIds??[],e))return{error:Le};const o=t=>{const n=t.participantId;return!e.includes(n)},{flightProfile:s}=Fp({event:a}),c=s?.flights?.find((t=>t.drawId===r));return c?.drawEntries&&(c.drawEntries=c.drawEntries.filter(o),t&&(c.drawEntries=im({entries:c.drawEntries}))),n?.entries&&(n.entries=n.entries.filter(o),t&&(n.entries=im({entries:n.entries}))),{...E}}function ly(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:x};if(!o)return Nr({result:{error:Me},stack:e});o.participantId||(o.participantId=wp()),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(uu).includes(d))return{error:be,participantType:d};if(!p)return{error:Ne};const l=s.participants||[],m=l.filter((t=>t.participantType===au)).map((t=>t.participantId));if(d!==au&&o.person)return{error:Nn,person:o.person};if(u&&!Array.isArray(u))return{error:Nn,individualParticipantIds:u};if(d===su){if(o.person)return{error:Nn,person:o.person};if(!o.individualParticipantIds)return Nr({result:{error:Fe},stack:e});if(2!==o.individualParticipantIds.length&&!a)return Nr({info:"PAIR must be 2 individualParticipantIds",result:{error:Pe},stack:e});{const t=l.filter((t=>t.participantType===au)).map((t=>t.participantId));if(!Array.isArray(o.individualParticipantIds))return Nr({result:{error:Pe},stack:e});if(!o.individualParticipantIds.reduce(((e,n)=>t.includes(n)&&e),!0))return Nr({result:{error:Pe},stack:e})}const t=l.filter((t=>t.participantType===su)).map((t=>({individualParticipantIds:t.individualParticipantIds,participant:t}))),i=o.participantType===su&&t.find((t=>2===P(t.individualParticipantIds,o.individualParticipantIds).length));if(i&&!n)return{...E,existingParticipant:!0,participant:r&&mi(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===au){if(!o.person?.standardFamilyName||!o.person?.standardGivenName)return{error:xe};if(!o.participantName){const t=`${o.person.standardFamilyName.toUpperCase()}, ${o.person.standardGivenName}`;o.participantName=t}}else{if(!d||![cu,ou].includes(d))return{error:be};if(u||(o.individualParticipantIds=[]),o.individualParticipantIds?.length)for(const t of o.individualParticipantIds){if("string"!=typeof t)return Nr({result:{participantId:t,error:Nn},stack:e});if(!m.includes(t))return Nr({result:{participantId:t,error:Ee},stack:e})}}s.participants.push(o),i||cr({payload:{tournamentId:s.tournamentId,participants:[o]},topic:ic});return br({participant:r&&mi(o),...E})}function my({allowDuplicateParticipantIdPairs:t,returnParticipants:e,tournamentRecord:n,participants:r=[]}){if(!n)return{error:x};n.participants||(n.participants=[]);const i=n.participants.map((t=>t.participantId))||[];r.forEach((t=>{t.participantId||(t.participantId=wp())}));const a=r.filter((t=>!i.includes(t.participantId))),o=r.filter((t=>i.includes(t.participantId))),s=a.filter((t=>t.participantType===au)),c=a.filter((t=>t.participantType!==au)),u=s.concat(...c),d=[];if(u.length){for(const e of u){const r=ly({allowDuplicateParticipantIdPairs:t,returnParticipant:!0,disableNotice:!0,tournamentRecord:n,participant:e});if(r.error)return r;r.success&&!r.existingParticipant&&d.push(r.participant)}d.length&&cr({topic:ic,payload:{tournamentId:n.tournamentId,participants:d}});const r={participants:e&&mi(d),addedCount:d.length,...E};return o.length&&Object.assign(r,{notAdded:o,info:Be}),br(r)}return{info:"No new participants to add",addedCount:0,...E}}function fy({allowDuplicateParticipantIdPairs:t,entryStage:e=Jo,entryStatus:n=Lu,participantIdPairs:r=[],tournamentRecord:i,drawDefinition:a,event:o,uuids:s}){if(!i)return{error:x};if(!o)return{error:Tt};if(o.eventType!==Kc)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===au&&r?.sex?u.set(n,r.sex):e===su&&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===sl)return!1;const e=t.map((t=>u.get(t)));let n=o.gender===cl&&(e[0]!==cl||e[1]!==cl)||o.gender===pl&&(e[0]!==pl||e[1]!==pl);return o.gender===ul&&(e.sort(pm),e[0]===pl&&e[1]===cl||(n=!0)),n}));if(d.length)return{error:Pe,invalidParticipantIdPairs:d};const p=r.map((t=>({participantId:s?.pop()??wp(),participantRole:Cm,individualParticipantIds:t,participantType:su}))),l=t?p:p.filter((t=>!c.find((e=>2===P(e,t.individualParticipantIds).length))));let m,f=[];if(l){const e=my({allowDuplicateParticipantIdPairs:t,participants:l,returnParticipants:!0,tournamentRecord:i});if(e.error)return e;f=e.participants||[],m=e.info}const h=Em({participantIds:r.map((t=>{const e=f.find((e=>2===P(e.individualParticipantIds,t).length));if(e)return e;const{participant:n}=Xp({tournamentRecord:i,participantIds:t});return n})).map((t=>t.participantId)),tournamentRecord:i,drawDefinition:a,entryStatus:n,entryStage:e,event:o});l.length&&cr({payload:{participants:l},topic:ic});return{...h,info:m,newParticipantIds:l.map(vo)}}function hy({entryStatus:t=Vu,unpairedParticipantIds:e=[],participantIdPairs:n=[],entryStage:r=Jo,tournamentRecord:i,event:a}){if(!i)return{error:x};if(!a)return{error:Tt};const o=i.participants??[],s=o.filter((t=>t.participantType===au)).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===su)).map((t=>t.individualParticipantIds)),p=my({participants:n.filter((t=>!d.find((e=>2===P(e,t).length)))).map((t=>({participantType:su,participantRole:Cm,individualParticipantIds:t}))),tournamentRecord:i});if(p.error)return p;const l=n.map((t=>{const{participant:e}=Xp({tournamentRecord:i,participantIds:t});return e})).map((e=>({participantId:e,entryStatus:t,entryStage:r}))),m=e.map((t=>({entryStatus:zu,participantId:t,entryStage:r})));return a.entries=(a.entries??[]).filter((t=>t.entryStage===r)),a.entries=a.entries.concat(...l,...m),{...E}}var gy=Object.freeze({__proto__:null,addDrawEntries:Nm,addEventEntries:Em,addEventEntryPairs:fy,destroyPairEntries:qm,destroyPairEntry:Gm,modifyEntriesStatus:om,modifyEventEntries:hy,promoteAlternate:cy,promoteAlternates:uy,removeDrawEntries:py,removeEventEntries:Rm,setEntryPosition:oy,setEntryPositions:sy});function Iy(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)}var Uy=Object.freeze({__proto__:null,getEntriesAndSeedsCount:vI,getMaxEntryPosition:Iy}),Sy=Object.freeze({__proto__:null,addDrawEntries:Nm,addEventEntries:Em,addEventEntryPairs:fy,destroyPairEntries:qm,destroyPairEntry:Gm,getEntriesAndSeedsCount:vI,getMaxEntryPosition:Iy,modifyEntriesStatus:om,modifyEventEntries:hy,mutate:gy,promoteAlternate:cy,promoteAlternates:uy,query:Uy,removeDrawEntries:py,removeEventEntries:Rm,setEntryPosition:oy,setEntryPositions:sy});function yy({schedulingProfile:t,venueIds:e,eventIds:n,drawIds:r}){const i=[],a=t?.map((t=>{const a=ti(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 vy({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}=Zs({drawDefinition:t});(i||[]).forEach((t=>{const i=t.structureId,{matchUps:o}=ml({structure:t}),{roundMatchUps:s}=Su({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!!Gr(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 wy({dates:t=[],extension:e}){if(!e)return!1;if("boolean"==typeof e.value&&e.value)return!0;if(!t.length)return!1;const n=Ui(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 Ty({convertExtensions:t,ignoreDisabled:e,venue:n,court:r}){const i={...mi(r,t,!0),venueId:n.venueId},{extension:a}=Fr({name:ja,element:r});if(e&&a){const t=Ui(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 Py(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}=Fr({name:ja,element:t});if(e?.value)continue}o.includes(t.venueId)||(u.push(mi(t,e,!0)),o.push(t.venueId));for(const r of t.courts??[])if(!s.includes(r.courtId)){if(n){const{extension:t}=Fr({name:ja,element:r});if(wy({extension:t,dates:i}))continue}const{inContextCourt:a}=Ty({convertExtensions:e,ignoreDisabled:n,venue:t,court:r});c.push(a),s.push(r.courtId)}}})),{courts:c,venues:u,...E}}function Dy({tournamentRecords:t,requireCourts:e,dates:n}){if("object"!=typeof t||!Object.keys(t).length)return{error:_};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:_};const i=mi(e.venues??[],t).filter((t=>{if(!n)return t;const{extension:e}=Fr({name:ja,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}=Fr({name:ja,element:t});return wy({extension:e,dates:r})})).filter(Boolean).map((e=>{const{inContextCourt:r}=Ty({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 by({tournamentRecords:t,tournamentRecord:e}){if("object"!=typeof t||!Object.keys(t).length)return{error:_};const{extension:n}=Fr({element:e,name:ro,tournamentRecords:t,discover:!0});let r=n?.value||[];if(r.length){const{venueIds:n}=Dy({requireCourts:!0,tournamentRecords:t}),{eventIds:i,drawIds:a}=Qg({tournamentRecords:t}),{updatedSchedulingProfile:o,modifications:s,issues:c}=yy({schedulingProfile:r,venueIds:n,eventIds:i,drawIds:a});if(s){r=o;const n=Ny({tournamentRecords:t,tournamentRecord:e,schedulingProfile:r});return n.error?n:{schedulingProfile:r,modifications:s,issues:c}}}return{schedulingProfile:r,modifications:0}}function Ny({tournamentRecords:t,tournamentRecord:e,schedulingProfile:n}){const r=vy({tournamentRecords:t,schedulingProfile:n});if(r.error)return r;if(!n)return Ar({element:e,name:ro,tournamentRecords:t,discover:!0});return Cr({tournamentRecords:t,discover:!0,extension:{name:ro,value:n}})}function My(t){const{tournamentRecord:e}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!t.schedulingProfile){const{modifications:t,issues:r}=by({tournamentRecords:n,tournamentRecord:e});return{success:!t,modifications:t,issues:r}}const{venueIds:r}=Dy({tournamentRecords:n}),{eventIds:i,drawIds:a}=Qg({tournamentRecords:n}),{updatedSchedulingProfile:o,modifications:s,issues:c}=yy({schedulingProfile:t.schedulingProfile,venueIds:r,eventIds:i,drawIds:a});return s?{...Ny({schedulingProfile:o,tournamentRecords:n}),modifications:s,issues:c}:{...E,modifications:s,issues:c}}function Ry({removePriorValues:t=!0,status:e=Vd,statusObject:n,event:r}){if(!Ui(n))return{error:Nn};const i=lm({event:r,status:e}),a=`${Bd}.${jd}`;return Uh({timeItem:{itemValue:{[e]:{...i,...n}},itemType:a},removePriorValues:t,event:r})}function Ay({tournamentRecord:t}){if(!t)return{error:x};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:mi(e,!1,!0)}}function Ey(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}=mh({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}=Qs({drawDefinition:s,structureId:t}),{seedAssignments:n}=od({drawDefinition:s,structure:e});return e?.stage===Jo&&1===e.stageSequence&&(f=n),e?.stage===Qo&&1===e.stageSequence&&(h=n),e})).sort(((t,e)=>Ks(t,e,d))).map((t=>{if(!t)return;const n=t?.structureId;let d=[];t.stage&&[Jo,Zo,ts].includes(t.stage)&&(d=f),t?.stage===Qo&&(d=h);const{matchUps:g,roundMatchUps:S,roundProfile:w}=ml({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}=tc({structure:t}),P=T?.filter(wi(Ri)).map((t=>{v=!0;const{drawPosition:e,participantId:n}=t,{extension:r}=Fr({element:t,name:ao});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=[Ro,Mo,Eo,xo,Vo,Fo,Co,Oo].includes(e.matchUpStatus);return t||n||!!e.winningSide||!!e.score?.scoreStringSide1}),!1);const b=g.reduce(((t,e)=>t&&[No,Ro,xo,Vo,Eo,Do].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:mi(w,!1,!0),drawInfo:u?m:mi(m,!1,!0),...E}}function Cy(t){const{includePositionAssignments:e,tournamentRecord:n,participantsProfile:r,policyDefinitions:i,usePublishState:a,status:o=Vd,sortConfig:s,event:c}=t,u=mi(n,!1,!0),d=mi(c,!1,!0);if(!u)return{error:x};if(!d)return{error:Tt};const{eventId:l}=d,{tournamentId:m,endDate:f}=u,h=lm({event:d,status:o}),{publishState:g}=fm({event:d}),{participants:I}=ym({withGroupings:!0,withEvents:!1,withDraws:!1,...r,tournamentRecord:u}),U=(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}))(Ey({context:{eventId:l,tournamentId:m,endDate:f},includePositionAssignments:e,tournamentParticipants:I,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:S}=Ay({tournamentRecord:u}),y={tournamentInfo:S,venuesData:(u.venues||[]).map((t=>(({venueData:t})=>({...t}))(Ap({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:U};return y.eventInfo.publishState=g,y.eventInfo.publish=h,{...E,eventData:y}}function Oy(t){const{includePositionAssignments:e,removePriorValues:n,tournamentRecord:r,status:i=Vd,event:a,drawIdsToRemove:o,drawIdsToAdd:s}=t;if(!r)return{error:x};if(!a)return{error:Tt};const{appliedPolicies:c}=Tu({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 Nr({result:{error:q},context:{invalidDrawIds:f}});const h=lm({event:a,status:i}),g=Object.keys(h?.drawDetails||{}).filter((t=>d.includes(t))).reduce(((t,e)=>(t[e]=h.drawDetails[e],t)),{});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 Nr({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)}Ry({statusObject:{drawDetails:g},removePriorValues:n,status:i,event:a});const{eventData:I}=Cy({includePositionAssignments:e,usePublishState:!0,tournamentRecord:r,policyDefinitions:u,event:a});return cr({payload:{eventData:I,tournamentId:r.tournamentId},topic:wc}),{...E,eventData:I}}const Fy="deleteDrawDefinitions",ky="autoSchedulingAudit",_y="deleteEvents",xy={AUTO_SCHEDULING_AUDIT:ky,DELETE_EVENTS:_y,DELETE_DRAW_DEFINITIONS:Fy};function Ly(t){if(!t.tournamentRecord)return{error:x};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}=Tu({tournamentRecord:a,event:r}),d={...u,...t.policyDefinitions},p=Array.isArray(n)?n[0]:void 0;if(!r){const t=kp({tournamentRecord:a,eventId:s,drawId:p});if(t.error)return t;r=t.event}const l=[],m=[],f=[];if(!r?.drawDefinitions)return Nr({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 Nr({info:"nothing to do; no matching drawIds in event.",result:{...E},stack:e});const g=mi(Fp({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?.[Ta]?.allowDeletionWithScoresPresent?.drawDefinitions,S=lm({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=Vl({event:r,drawDefinition:t})?.matchUps??[];if(e.some((({score:t})=>Gc({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=>td.includes(t.entryStatus)))),v.includes(n)&&(v=v.filter((t=>t!==n)),y=!0);const d=Zs({stageSequence:1,drawDefinition:t,stage:Jo})?.structures?.[0],p=d?kU({structureId:d.structureId,tournamentRecord:a,drawDefinition:t}):void 0,h=p?.positionAssignments?.map(I),S=Zs({stage:Qo,drawDefinition:t})?.structures,T=S?.length?S.map((e=>{const n=e.stageSequence,r=kU({structureId:e.structureId,tournamentRecord:a,drawDefinition:t}),i=r?.positionAssignments.map(I);return{positionAssignments:i,stageSequence:n}})):void 0,P={action:Fy,payload:{drawDefinitions:[t],eventId:s??r?.eventId,auditData:o}};f.push(P),l.push(br({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 Nr({context:{drawIdsWithScoresPresent:w},result:{error:qn},stack:e});if(r.drawDefinitions=T,g){Ea({event:r,extension:{name:Ha,value:g}})}if(My({tournamentRecord:a}),y){const t={};for(const e of v)t[e]=S.drawDetails?.[e]??{published:!0};const e=Ry({statusObject:{drawDetails:t},event:r});if(e.error)return{error:e.error}}if(f.length&&cr({topic:sc,payload:f}),m.length&&Cc({tournamentId:a?.tournamentId,matchUpIds:m}),n.forEach((t=>{!function({tournamentId:t,eventId:e,drawId:n}){cr({payload:{drawId:n,tournamentId:t,eventId:e},topic:dc,key:n}),pr({key:n})}({drawId:t})})),function({event:t,deletedDrawsDetail:e,auditData:n}){const{extension:r}=Fr({name:$a,element:t}),i={...n,deletedDrawsDetail:e},a={name:$a,value:Array.isArray(r?.value)?r?.value.concat(i):[i]};Cr({element:t,extension:a})}({event:r,deletedDrawsDetail:l,auditData:o}),i&&y){const t=Oy({drawIdsToRemove:n,policyDefinitions:d,tournamentRecord:a,event:r});if(t.error)return{...E,info:t.error}}return{...E}}function By({autoPublish:t=!0,tournamentRecord:e,auditData:n,event:r,force:i}){if(!e)return{error:x};if(!r)return{error:Tt};const{flightProfile:a}=Fp({event:r});if(a){const o=a.flights?.map((({drawId:t})=>t)).filter(Boolean),s=Ly({eventId:r.eventId,tournamentRecord:e,autoPublish:t,auditData:n,drawIds:o,event:r,force:i});return s.error?s:ka({event:r,name:Ha})}return{...E}}function Vy(t){const e=na(t,[{[bi]:!0},{[Ji]:t=>$g({matchUpFormat:t}),[Qi]:kt,[Mi]:!0}]);if(e.error)return e;const{tournamentRecord:n,matchUpFormat:r,event:i}=t,{extension:a}=Fr({name:no,element:i}),o=a?.value,{extension:s}=Fr({element:n,name:no}),c=s?.value,u=[o?.matchUpAverageTimes&&$d({...o,matchUpFormat:r}),c?.matchUpAverageTimes&&$d({...c,matchUpFormat:r})].find((t=>t));return{matchUpFormat:r,recoveryTimes:[o?.matchUpRecoveryTimes&&Wd({...o,matchUpFormat:r}),c?.matchUpRecoveryTimes&&Wd({...c,matchUpFormat:r})].find((t=>t)),averageTimes:u}}function jy(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:_};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}=kp({tournamentRecord:i,eventId:a});a&&s&&(c=!0);const u=Gy({tournamentRecord:i,event:s,matchUpFormat:e,averageTimes:r,recoveryTimes:n});if(u.error)return u}return!a||c?{...E}:{error:Pt}}function Gy({tournamentRecord:t,recoveryTimes:e,matchUpFormat:n,averageTimes:r,event:i}){if(!t)return{error:x};if(r&&!Array.isArray(r))return{error:Nn};if(e&&!Array.isArray(e))return{error:Nn};const a=no;if(i){const{extension:t}=Fr({element:i,name:a});Cr({element:i,extension:{name:a,value:qy({...t?.value||{},matchUpFormat:n,averageTimes:r,recoveryTimes:e})}})}else{const{extension:i}=Fr({element:t,name:a});Cr({extension:{name:a,value:qy({...i?.value||{},matchUpFormat:n,averageTimes:r,recoveryTimes:e})},element:t})}return{...E}}function qy(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 $y(t){const{tournamentRecord:e,recoveryMinutes:r,averageMinutes:i,matchUpFormat:a,categoryType:o,eventId:s,event:c}=t;if(!e)return{error:x};if(!$g({matchUpFormat:a}))return{error:Nn};if(!c)return{error:Tt};const{averageTimes:u=[],recoveryTimes:d=[]}=Vy({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||zc]:i}),U.push(m)),I&&(Object.assign(f.minutes,{[c?.eventType||zc]:r}),S.push(f)),g||I?jy({averageTimes:g&&U,recoveryTimes:I&&S,tournamentRecord:e,matchUpFormat:a,eventId:s,event:c}):{error:Nn}}function Wy(t){if(t.event)return Hy({event:t.event});{t.tournamentRecord&&!t.tournamentRecords&&(t.tournamentRecords={[t.tournamentRecord.tournamentId]:t.tournamentRecord});const e=na(t,[{[Pi]:!0,[Gi]:!0}]);if(e.error)return e;const{tournamentRecords:n,eventId:r}=t;for(const t of Object.values(n??{})){const{event:e}=kp({tournamentRecord:t,eventId:r});if(e)return Hy({event:e})}}return{error:Pt}}function Hy({event:t}){return ka({event:t,name:no})}function zy({tournamentRecord:t,event:e,startDate:n}){if(!t)return{error:x};if(!e)return{error:Tt};if(!xr.test(n))return{error:pe};const r=Jy(t);if(r.error)return r;const{tournamentStartDate:i,tournamentEndDate:a}=r,o=new Date(ti(n)).getTime();if(!i||!a||o<i||o>a)return{error:pe};const s=e.endDate&&new Date(ti(e.endDate)).getTime();return s&&o>s&&(e.endDate=n),e.startDate=n,{...E}}function Yy({tournamentRecord:t,event:e,endDate:n}){if(!t)return{error:x};if(!e)return{error:Tt};if(!xr.test(n))return{error:pe};const r=Jy(t);if(r.error)return r;const{tournamentStartDate:i,tournamentEndDate:a}=r,o=new Date(ti(n)).getTime();if(!i||!a||o<i||o>a)return{error:pe};const s=e.startDate&&new Date(ti(e.startDate)).getTime();return s&&o<s&&(e.startDate=n),e.endDate=n,{...E}}function Ky({tournamentRecord:t,event:e,startDate:n,endDate:r}){if(!t)return{error:x};if(!e)return{error:Tt};if(!n&&!r)return{error:ae,info:"missing date"};if(n&&!xr.test(n))return{error:pe};if(r&&!xr.test(r))return{error:pe};if(n&&r){if(new Date(ti(n)).getTime()>new Date(ti(r)).getTime())return{error:Nn}}if(n){const r=zy({tournamentRecord:t,event:e,startDate:n});if(r.error)return r}if(r){const n=Yy({tournamentRecord:t,event:e,endDate:r});if(n.error)return n}return{...E}}function Jy(t){const{startDate:e,endDate:n}=t;return xr.test(e)&&xr.test(n)?{tournamentStartDate:new Date(ti(e)).getTime(),tournamentEndDate:new Date(ti(n)).getTime()}:Nr({result:{error:me},context:{startDate:e,endDate:n}})}function Qy({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}=Fp({event:t});return r?.flights?.forEach((t=>{t.flightNumber=e[t.drawId]})),{...E}}function Zy({tournamentRecord:t,event:e}){if(!t)return{error:x};if(!e)return{error:Tt};const{flightProfile:n}=Fp({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?Qy({event:e,orderedDrawIdsMap:r}):{...E}}function Xy({autoPublish:t=!0,tournamentRecord:e,auditData:n,drawId:r,event:i,force:a}){if(!e)return{error:x};if(!r)return{error:at};if(!i)return{error:Tt};const{flightProfile:o}=Fp({event:i});if(o){const t=o.flights?.find((t=>t.drawId===r));if(t){const t=o.flights.filter((t=>t.drawId!==r));Ea({event:i,extension:{name:Ha,value:{...o,flights:t}}})}}const s=i.drawDefinitions?.find((t=>t.drawId===r));if(s){const o=Ly({drawIds:[r],eventId:i.eventId,tournamentRecord:e,autoPublish:t,auditData:n,event:i,force:a});if(o.error)return o}return Zy({tournamentRecord:e,event:i})}function tv({replacementIndividualParticipantId:t,existingIndividualParticipantId:e,tournamentRecord:n,drawDefinition:r,participantId:i,event:a,uuids:o}){if(!a)return{error:Tt};if(a?.eventType!==Jd)return{error:wt};if(o&&!Array.isArray(o))return{error:Nn};if(!n)return{error:x};if(![t,e,i].every((t=>"string"==typeof t)))return{error:Ae};if(!(a?.entries?.filter((({entryStatus:t})=>[zu,Yu].includes(t))).map((({participantId:t})=>t))||[]).includes(t))return{error:Te};const s=(n.participants||[]).find((t=>t.participantId===i));if(s?.participantType!==su)return{error:we,participant:s};const c=s.individualParticipantIds,u=[t,...c.filter((t=>t!==e))],{participant:d}=Xp({participantIds:u,tournamentRecord:n});let p;if(d)p=d.participantId;else{const t=ly({participant:{participantId:o?.pop(),participantRole:Cm,individualParticipantIds:u,participantType:su},returnParticipant:!0,tournamentRecord:n});if(t.error)return t;p=t.participant.participantId}const{flightProfile:l}=Fp({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=Bm({addIndividualParticipantsToEvents:!1,participantIds:[i],tournamentRecord:n});if(t.error)return t}return{...E,participantOtherEntries:m,newPairParticipantId:p}}function ev(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}=Fp({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 Nr({result:{error:j},info:{sourceDrawId:U}});if(I&&I.drawId!==u.drawId)return Nr({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 Nr({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&&td.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 Nr({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:Ha,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:Ha,value:{...g||{},flights:t}}}Ea({event:d,extension:D}),Object.assign(u,{drawOrder:T});const b=d.drawDefinitions.find((t=>t.drawId===p)),N=c?.tournamentId,M=d.eventId;if(b){if(!o)return{error:ot};const t=Vl({drawDefinition:b})?.matchUps,e=t?.map(wo)??[],n=Vl({drawDefinition:u})?.matchUps;if(!r){e?.length&&Cc({matchUpIds:e,action:"modifyDrawDefinition",tournamentId:N,eventId:M}),n?.length&&Ec({matchUps:n,tournamentId:N,eventId:M}),d.drawDefinitions=d.drawDefinitions.map((t=>t.drawId===p?u:t));const t=u.structures?.map((({structureId:t})=>t));kc({drawDefinition:u,tournamentId:N,structureIds:t,eventId:M})}}else if(d.drawDefinitions.push(u),!r){const{matchUps:t}=Vl({drawDefinition:u,event:d});t&&Ec({tournamentId:c?.tournamentId,matchUps:t}),Fc({drawDefinition:u,tournamentId:N,eventId:M})}return{...E,modifiedEventEntryStatusCount:h}}function nv(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:Mt};if(!r)return{error:x};if(!c)return{error:at};const p=od({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=Sf({...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}}function rv({deleteExisting:t,event:e,flightProfile:n}){const r="attachFlightProfile";if(!n)return Nr({result:{error:ae},stack:r});if(!e)return Nr({result:{error:Tt},stack:r});const{flightProfile:i}=Fp({event:e});if(i&&!t)return Nr({result:{error:_n},stack:r});if(e.drawDefinitions?.length)return Nr({result:{error:G},stack:r});return Ea({event:e,extension:{name:Ha,value:n}}),{flightProfile:mi(n,!1,!0),...E}}function iv({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 Nr({result:{error:Nn},info:wf("entryStatus"),stack:"removeScaleValues"});let s=a.entries;if(i){const{flightProfile:t}=Fp({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:x};if(!n)return{error:Fe};if(!e)return{error:ae,info:"scaleAttributes required"};const{scaleType:r,eventType:i,scaleName:a}=e,o=[kd,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(vo)})}function av({removePriorValues:t,tournamentRecord:e,displaySettings:n,status:r=Vd,event:i}){if(!e)return Nr({result:{error:x}});if(!i)return Nr({result:{error:Tt}});if(!Ui(n))return Nr({result:{error:ae}});if(Ui(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=>Si(e.attributes,t.attributes)));e?.dates&&t.dates?e.dates.push(...t.dates):r.push(t)}n.draws[t].scheduleDetails=r}}const a=Ry({statusObject:{displaySettings:n},removePriorValues:t,status:r,event:i});return a.error?a:{...E}}function ov({tournamentRecord:t,drawDefinition:e,entryStatuses:n,scaleName:r,drawId:i,event:a,stage:o}){if(!t)return{error:x};if(!a)return{error:Tt};r=r||a.category?.categoryName||a.category?.ageCategoryCode;return iv({tournamentRecord:t,scaleAttributes:{eventType:a.eventType,scaleType:ca,scaleName:r},drawDefinition:e,entryStatuses:n,drawId:i,event:a,stage:o})}function sv({removePairParticipants:t,tournamentRecord:e,eventIds:n}){if(!e)return{error:x};if(!e.events)return{error:Pt};if(!Array.isArray(n))return{error:ae,info:wf("drawIds")};const r=[],i=[],a=[],o=[];if(e.events=(e.events||[]).filter((t=>{if(n.includes(t.eventId)){const n={action:_y,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===Jd?(t.entries||[]).map((({entryStatus:t,participantId:e})=>t!==zu&&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(My({tournamentRecord:e}),r.length){cr({topic:sc,payload:r});Ih({tournamentRecord:e,timeItem:{itemType:_y,itemValue:i}})}return{...E}}function cv({tournamentRecord:t,eventUpdates:e,eventId:n,event:r}){const i="modifyEvent";if(!t)return Nr({result:{error:x},stack:i});if(!Ii(n))return Nr({result:{error:Tt},context:{eventId:n},stack:i});if(!Ui(e))return Nr({result:{error:Nn},context:{eventUpdates:e},stack:i});const a=r?.entries?.filter((({entryStatus:t})=>{const e=t;return[...td,Lu].includes(e)})).map((({participantId:t})=>t))??[],o=a?ym({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||[ul,sl].includes(e.gender??"")||1===u.length&&u[0]===e.gender;if(e.gender&&!d)return Nr({context:{gender:e.gender,validGender:d},result:{error:Nn},stack:i});const p=(c.includes(Zd)&&[Zd]||c.includes(au)&&[Yd]||c.includes(su)&&[Jd]||[Jd,Yd,Zd]).includes(e.eventType??"");return e.eventType&&!p?Nr({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})}function uv({qualifyingPositions:t,drawEntries:e=[],drawName:r,drawId:i,event:a,stage:o}){const s="addFlight";if(!a)return Nr({result:{error:Tt},stack:s});if(!r)return Nr({result:{error:ae},stack:s});if(e?.length){const t=(a.entries??[]).map(vo),n=e.map(vo);if(P(n,t).length!==n.length)return Nr({result:{error:Nn},stack:s})}const c=Fp({event:a})?.flightProfile,u=c?.flights?.map((({flightNumber:t})=>!isNaN(t)&&n(t)))?.filter(Boolean)||[],d=Math.max(0,...u)+1,p={drawId:i||wp(),flightNumber:d,drawEntries:e,drawName:r};o&&(p.stage=o),t&&(p.qualifyingPositions=t);if((c?.flights||[]).find((({drawId:t})=>t===p.drawId)))return Nr({result:{error:kn},stack:s});const l=(c?.flights||[]).concat(p);return Ea({event:a,extension:{name:Ha,value:{...c||{},flights:l}}})}const dv={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:wS,DOMINANT_DUO_MIXED:US,LAVER_CUP:NS,TEAM_DOUBLES_3_AGGREGATION:mS,TIME_TENNIS_DUAL:SS,TIME_TENNIS_PRO_CIRCUIT:IS,USTA_BREWER_CUP:yS,USTA_OZAKI_CUP:vS,USTA_COLLEGE:TS,USTA_GOLD_TEAM_CHALLENGE:lS,USTA_INTERSECTIONAL:gS,USTA_LEVEL_1:PS,USTA_SECTION_BATTLE:hS,USTA_SOUTHERN_LEVEL_5:fS,USTA_TOC:MS,USTA_WTT_ITT:DS,USTA_ZONAL:bS};function pv({suppressNotifications:t,tournamentRecord:e,internalUse:n,event:r}){if(!e)return{error:x};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=br({drawDefinitions:!!r.drawDefinitions?.length,entries:!!r.entries?.length});return{info:"entries/drawDefinitions cannot exist",error:Nn,context:t}}const o={eventType:Kd,drawDefinitions:[],entries:[],startDate:i,endDate:a,...r};if(r.eventType===Xd)if(r.tieFormat){const t=Hg({tieFormat:r.tieFormat});if(t.error)return t}else if(r.tieFormatName){if(!dv[r.tieFormatName])return{context:{tieFormatName:r.tieFormatName},error:Nn};const t=ZS({isMock:e?.isMock,namedFormat:r.tieFormatName,event:r});o.tieFormat=t}o.eventId||(o.eventId=wp());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}=mr();if(t.includes(rc)){const t=_l({event:r}).matchUps??[];Ec({tournamentId:e?.tournamentId,eventId:r.eventId,matchUps:t})}for(const t of r.drawDefinitions||[])Fc({drawDefinition:t})}return{...E,event:o}}}var lv=Object.freeze({__proto__:null,addDrawDefinition:ev,addEvent:pv,addFlight:uv,assignSeedPositions:nv,attachFlightProfile:rv,deleteDrawDefinitions:Ly,deleteEvents:sv,deleteFlightAndFlightDraw:Xy,deleteFlightProfileAndFlightDraws:By,modifyEvent:cv,modifyEventMatchUpFormatTiming:$y,modifyPairAssignment:tv,refreshEventDrawOrder:Zy,removeEventMatchUpFormatTiming:Wy,removeScaleValues:iv,removeSeeding:ov,setEventDates:Ky,setEventDisplay:av,setEventEndDate:Yy,setEventStartDate:zy,updateDrawIdsOrder:Qy,validateCategory:xg});function mv({tournamentRecord:t,outcomes:e}){if(!t)return{error:x};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=lm({event:t}),{drawDetails:r,drawIds:i}=e??{},{eventId:a}=t;return n[a].filter((t=>{const n=r?Object.keys(e.drawDetails).filter((t=>mm({drawId:t,drawDetails:r}))):[];return i?.includes(t)||n.includes(t)})).length})).map((t=>t.eventId)),eventIdPublishedDrawIdsMap:n}}function fv({tournamentRecord:t,event:e}){if(!t)return{error:x};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:Ld,eventType:a,scaleName:i};const d=cm({participant:t,scaleAttributes:o})?.scaleItem?.scaleValue;o={scaleType:xd,eventType:a,scaleName:i};const p=cm({participant:t,scaleAttributes:o})?.scaleItem?.scaleValue;o={scaleType:_d,eventType:a,scaleName:i};const l=cm({participant:t,scaleAttributes:o})?.scaleItem?.scaleValue;return s=!(!s&&!d),c=!(!c&&!p),u=!(!u&&!l),{participantId:e,participantName:n||r,seed:d,ranking:p,rating:l}})),hasSeededParticipants:s,hasRankedParticipants:c,hasRatedParticipants:u}}function hv({tournamentRecord:t,withScaleValues:e,scaleEventType:n,inContext:r,eventIds:a,drawIds:o,context:s}){if(!t)return{error:x};const{tournamentId:c}=t,u=(t.events??[]).filter((({eventId:t})=>!a||Array.isArray(a)&&a.includes(t))).map((t=>{const e=t.drawDefinitions?.map(To);if(o?.length&&!P(o,e).length)return;const n=mi(t);return r&&Object.assign(n,{tournamentId:c}),s&&Object.assign(n,s),n})).filter(Boolean),d={};if(e){const e=ym({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})=>td.includes(t))).map(vo),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=nS[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!==au)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=nS[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!==au)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=rm({drawDefinition:e}).assignedParticipantIds??[];d[s].draws[t]||(d[s].draws[t]={ratingsStats:{},ratings:{},ranking:{}}),m.push(t),l(t,n)}const h=Fp({event:t}).flightProfile;for(const t of h?.flights??[]){const e=t.drawId;if(f(e))continue;l(e,t.drawEntries.map(vo))}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 br({eventScaleValues:d,events:u,...E})}function gv({tournamentRecord:t,drawDefinition:e,context:n,event:r}){if(!t)return{error:x};if(!r)return{error:Tt};const i=mi(r);n&&Object.assign(i,n);return br({drawDefinition:e&&i.drawDefinitions?.find((({drawId:t})=>e.drawId===t)),event:i})}var Iv=Object.freeze({__proto__:null,bulkUpdatePublishedEventIds:mv,categoryCanContain:Lg,getCategoryAgeDetails:_g,getEvent:gv,getEventProperties:fv,getEventStructures:xf,getEventTimeItem:bl,getEvents:hv,getFlightProfile:Fp,getScaledEntries:PI}),Uv=Object.freeze({__proto__:null,addDrawDefinition:ev,addEvent:pv,addFlight:uv,assignSeedPositions:nv,attachFlightProfile:rv,bulkUpdatePublishedEventIds:mv,categoryCanContain:Lg,deleteDrawDefinitions:Ly,deleteEvents:sv,deleteFlightAndFlightDraw:Xy,deleteFlightProfileAndFlightDraws:By,getCategoryAgeDetails:_g,getEvent:gv,getEventProperties:fv,getEventStructures:xf,getEventTimeItem:bl,getEvents:hv,getFlightProfile:Fp,getScaledEntries:PI,modifyEvent:cv,modifyEventMatchUpFormatTiming:$y,modifyPairAssignment:tv,mutate:lv,query:Iv,refreshEventDrawOrder:Zy,removeEventMatchUpFormatTiming:Wy,removeScaleValues:iv,removeSeeding:ov,setEventDates:Ky,setEventDisplay:av,setEventEndDate:Yy,setEventStartDate:zy,updateDrawIdsOrder:Qy,validateCategory:xg});const Sv="splitWaterfall",yv="splitShuttle",vv={SPLIT_LEVEL_BASED:"splitLevelBased",SPLIT_WATERFALL:Sv,SPLIT_SHUTTLE:yv};const wv="ASC",Tv="DESC",Pv={ASC:"ASC",ASCENDING:wv,DESC:"DESC",DESCENDING:Tv};function Dv(t){let{tieFormat:e}=t;const{useDefaultEventRanking:n,tournamentRecord:r,drawDefinition:i,scaleAccessor:a,singlesOnly:o,attach:c,event:u}=t;if(u?.eventType!==Xd)return{error:wt};if(!r)return{error:x};if(!e&&!i)return{error:q};if(e=e??Bp({drawDefinition:i,event:u})?.tieFormat,Hg({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===Vu)).map(vo),{participants:l=[]}=ym({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=aa,sortOrder:I,accessor:U}=a||{},S=g===aa?"rankings":"ratings";const y=(t,e)=>{let r=t[S]?.[e];if(!r&&n&&(r=t[S]?.[Hc]),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===Tv?t:e;return y(I===Tv?e:t,n)-y(r,n)},T=(t,e)=>v(t,e,Hc),P=(t,e)=>v(t,e,Yc),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===Hc;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&&([cl,pl].includes(c)&&c||c===ul&&[cl,pl][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}=Xp({tournamentParticipants:l,participantIds:t});if(!e){const e={individualParticipantIds:t,participantRole:Cm,participantType:su};N.push(e)}}if(c){for(;N.length;)ly({participant:N.pop(),tournamentRecord:r});Cr({element:i,extension:{name:Ya,value:d}})}return{...E,lineUps:d,participantsToAdd:N}}function bv(t){if(!t)return{error:ae};const e=na(t,[{dates:!1,[Ji]:t=>Array.isArray(t)&&t.every(Gr)},{uuids:!1,[Ji]:t=>Array.isArray(t)&&t.every(Ii)},{startTime:!1,endTime:!1,[Ji]:Jr},{idPrefix:!1,namePrefix:!1,[Ji]:Ii},{count:!0,[Ji]:s}]);if(e.error)return e;const{startDate:n,endDate:r}=t.tournamentRecord??{},i=t.dates||n&&r&&zr(n,r)||[],a=w(1,t.count+1).map((e=>br({courtId:t.uuids?.pop()??(t.idPrefix&&`${t.idPrefix}-${e}`)??wp(),courtName:t.courtNames?.pop()??(t.namePrefix&&`${t.namePrefix} ${e}`),dateAvailability:i.map((e=>({startTime:t.startTime??"08:00",endTime:t.endTime??"20:00",date:e})))})));return{...E,courts:a}}function Nv({court:t,date:e}){const n=e&&t.dateAvailability.find((t=>pi(t.date,e))),r=t.dateAvailability.find((t=>!t.date));return n||r}function Mv(t){const e=na(t,[{courtDate:!0,_ofType:Yi}]);if(e.error)return e;const{includeBookingTypes:n=[],courtDate:r}=t,i=[];let a=oi(r.startTime);(r.bookings||[]).filter((t=>!t.bookingType||!n.includes(t.bookingType))).sort(((t,e)=>Zr(t.startTime).localeCompare(Zr(e.startTime)))).forEach((t=>{const e={startTime:Xr(a.toISOString()),endTime:t.startTime};oi(t.startTime)>a&&i.push(e),oi(t.endTime)>a&&(a=oi(t.endTime))}));const o={startTime:Xr(a.toISOString()),endTime:r.endTime};return oi(r.endTime)>a&&i.push(o),{timeSlots:i}}function Rv(t){const e=na(t,[{periodStart:!0,date:!0},{courts:!0,_ofType:Ki}]);if(e.error)return e;const{averageMatchUpMinutes:n,includeBookingTypes:r,periodStart:i,date:a}=t,o=t.courts,s=oi(i),c=ui(s,n),{enoughTime:u}=function({averageMatchUpMinutes:t,includeBookingTypes:e,periodStartTime:n,periodEndTime:r}){function i(e){const i=oi(e.startTime),a=oi(e.endTime);return!(i>n)&&(!(a<r)&&si(n,a)>=t)}return{enoughTime:t=>{const{timeSlots:n}=Mv({includeBookingTypes:e,courtDate:t}),r=n?.filter(i);return!!r?.length}}}({averageMatchUpMinutes:n,includeBookingTypes:r,periodStartTime:s,periodEndTime:c});return{availableToScheduleCount:(o?.filter((t=>{if(!Array.isArray(t.dateAvailability))return!1;const e=Nv({date:a,court:t});return!(!e||!u(e))}))||[]).length,...E}}function Av(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(!Gr(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=Nv({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]},...mi(u,!1,!0),...o].filter(Boolean),startTime:d,endTime:p,date:l}}}));c.sort(((t,e)=>Qr(t.startTime)-Qr(e.startTime)));const d=[];for(const t of c){const{startTime:e,endTime:n,averageMinutes:i,recoveryMinutes:a,matchUpId:o}=t,s=Qr(e),c=Qr(n),p=u.map((t=>{const e=t.dateAvailability,{timeSlots:n=[]}=Mv({courtDate:e});return{courtName:t.courtName,courtId:t.courtId,timeSlots:n}})).flat().reduce(((t,{courtId:e,courtName:n,timeSlots:i})=>{let a;return i.find((({startTime:e,endTime:n})=>{a=Qr(e)-s;const i=s>=Qr(e);return c<=Qr(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 Ev({averageMatchUpMinutes:t,periodLength:e=30,recoveryMinutes:n}){const r=(t||90)+(n||0);return e>r?r:e||30}function Cv(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 Ov({scheduleDate:t,startTime:e,endTime:n,courts:r}){const i=(e?"startTime":n&&"endTime")||void 0;return r.reduce(((r,a)=>{const o=Nv({date:t,court:a}),s=i&&(o?.[i]||a[i]);return s&&(!r||e&&Qr(s)<Qr(r)||n&&Qr(s)>Qr(r))?s:r}),void 0)}function Fv(t){const e=na(t,[{courts:!0,_ofType:Ki}]);if(e.error)return e;let{date:r=qr(),startTime:i="08:00",endTime:a="19:00",periodLength:o,courts:s}=t;const{calculateStartTimeFromCourts:c=!0,remainingScheduleTimes:u,averageMatchUpMinutes:d,clearScheduleDates:p,courtsCount:l,bookings:m}=t;o=o||Ev({averageMatchUpMinutes:d}),r=ti(r),i=Xr(i),a=Xr(a);let f=0,h=0,g=0,I=0,U=0;!s&&l&&(s=Cv({startTime:i,endTime:a,count:l,date:r}));const{virtualCourts:S}=Av({remainingScheduleTimes:u,clearScheduleDates:p,scheduleDate:r,periodLength:o,bookings:m,courts:s}),{firstTimeSlotStartTime:y}=function({averageMinutes:t,startTime:e,endTime:n,courts:r,date:i}){let a;if(e=e||Ov({courts:r,scheduleDate:i,startTime:!0}),n=n||Ov({courts:r,scheduleDate:i,endTime:!0}),e&&n){const o=oi(e),s=oi(n);for(const e of r||[]){if(!Array.isArray(e.dateAvailability))continue;const n=Nv({court:e,date:i}),{timeSlots:r}=Mv({courtDate:n});r?.forEach((e=>{const n=oi(e.startTime),r=oi(e.endTime);if(n>s||n<o)return!1;if(r<o)return!1;if(si(n,r)>=t){const t=Xr(n.toISOString());(!a||t<a)&&(a=t)}}))}}return{firstTimeSlotStartTime:a}}({averageMinutes:d,courts:S,startTime:i,endTime:a,date:r});c&&y&&(i=y||i);const v=Qr(i),T=Qr(a)-v,P=w(0,Math.floor(T/o)+1).map((t=>{const e=function(t){let e=Math.floor(t/60);const n=t-60*e;return e>23&&(e%=24),[di(e),di(n)].join(":")}(v+t*o),i=Rv({courts:S||[],averageMatchUpMinutes:d,periodStart:e,date:r});if(i.error)return{error:i.error};const{availableToScheduleCount:a=0}=i,s=a>h?a-h:0;U+=t?a:0;const c=t?U/t:a,u=t?o*c/d*(t-1)+c:c,p=a?h&&u-f||s:0;f=u,h=a,g+=p;const l=n(g)-I;return I+=l,{periodStart:e,add:l,availableToScheduleCount:a,newCourts:s,totalMatchUps:I}}));return{scheduleTimes:P.reduce(((t,e)=>{const n=w(0,e.add).map((()=>({scheduleTime:e.periodStart})));return t.concat(...n)}),[]).flat(),timingProfile:P,totalMatchUps:I}}const kv={getCourtsAvailableAtPeriodStart:Rv,generateTimeSlots:Mv,getScheduleTimes:Fv,courtGenerator:Cv};var _v=Object.freeze({__proto__:null,default:kv,garman:kv}),xv=Object.freeze({__proto__:null,drawMatic:XS,garman:_v,generateAdHocMatchUps:zU,generateAndPopulatePlayoffStructures:nI,generateCourts:bv,generateDrawDefinition:iy,generateDrawMaticRound:cS,generateDrawStructuresAndLinks:$U,generateDrawTypeAndModifyDrawDefinition:WU,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}=Fp({event:l});if(g&&n&&!o)return{error:_n};const I=t.scaledEntries??PI({tournamentRecord:r,scaleAttributes:i,scaleSortMethod:a,sortDescending:s,event:l,stage:m}).scaledEntries,U=I.map(vo),S=f(h.filter((({participantId:t})=>!U.includes(t))).filter((t=>(!m||!t.entryStage||t.entryStage===m)&&(!t.entryStatus||Xu.includes(t.entryStatus))))),y=I.concat(...S),v=y.length;let T=N(y,Math.ceil(v/u));d===Sv?T=A(y,u):d===yv&&(T=A(y,u,!0));const P=w(0,u).map((t=>{const n=t+1;return{flightNumber:n,drawId:p?.pop()??wp(),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})),D={scaleAttributes:i,splitMethod:d,flights:P};if(n){const t=rv({flightProfile:D,deleteExisting:o,event:l});return{splitEntries:Xn()&&T||void 0,...t}}return{flightProfile:D,...E}},generateLineUps:Dv,generateQualifyingStructure:Eh,generateSeedingScaleItems:wI,generateVoluntaryConsolation:HU,roundRobinGroups:of}),Lv=Object.freeze({__proto__:null,isValid:$g,isValidMatchUpFormat:$g,parse:Wp,stringify:Bg});function Bv({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 Nr({result:{error:Nn,context:{sideNumber:r}}});const{matchUp:s,structure:c}=Dg({drawDefinition:e,matchUpId:i,event:a});if(!s)return{error:Wt};if(!!(c?.structures||e.drawType&&e.drawType!==Ss||c?.matchUps?.find((({roundPosition:t})=>!!t))))return{error:et};if(!n&&(s?.score?.scoreStringSide1||Ho.includes(s?.matchUpstatus)||s?.matchUpStatus&&[Oo,Co].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);Oc({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:s})}return{...E,sidesSwapped:o}}function Vv(t){Object.assign(t,{inContext:!0});const{matchUp:e,error:n}=jv(t);return{matchUp:mi(e,!0,!0),error:n}}function jv({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:x};if("string"!=typeof s)return{error:qt};if(!a||!p){const t=(xl({tournamentRecord:n,nextMatchUps:o}).matchUps??[]).find((t=>t.matchUpId===s));if(!t)return{error:Wt};({eventId:u,drawId:d}=t),({event:p,drawDefinition:a}=kp({tournamentRecord:n,eventId:u,drawId:d}))}if(!a)return{error:q};i&&!r&&(r=Cu({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=[]}=kl({participantsProfile:t,tournamentRecord:n,contextProfile:i,inContext:c});if(o){const t=(Vl({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}=Dg({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 Gv(t,e){if(!Ui(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=qv({params:t,param:r,attr:a,error:i});if(e?.error)return e;n[r]=e}return n}function qv({params:t,param:e,attr:n,error:r}){if(e===xi&&Ui(t.drawDefinition)&&Ii(t.structureId)){const e=(t.drawDefinition.structures??[]).find((({structureId:e})=>e===t.structureId));return!e.length&&r?{error:r}:{structure:e}}if(e===qi){const e=jv({...t,...n});return e.error&&r?{...e,error:r}:e}return{error:On,info:{param:e}}}function $v({removePriorValues:t,tournamentRecord:e,duplicateValues:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:o,event:s}){const{matchUp:c}=Dg({drawDefinition:r,event:s,matchUpId:a});if(!c)return{error:Wt};const u=hh({removePriorValues:t,element:c,duplicateValues:n,timeItem:o});return i||Oc({tournamentId:e?.tournamentId,eventId:s?.eventId,context:"addTimeItem",drawDefinition:r,matchUp:c}),u}function Wv(t){const e=na(t,[{[bi]:!0},{[Ni]:!0},{[Ri]:!0},{[ki]:!0}]);if(e.error)return e;const n=Gv(t,[{[zi]:qi,attr:{[_i]:!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&&zo.includes(c)||c&&Ho.includes(c)||Gc({score:u}))return{error:dt};const d=qd({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:_e};const m=fd({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=>{$v({drawDefinition:i,matchUpId:o,timeItem:{itemType:gd,itemValue:t}})}));return $v({tournamentRecord:r,drawDefinition:i,matchUpId:o,timeItem:{itemValue:a,itemType:gd}})}function Hv(t){const e=na(t,[{[bi]:!0},{[Ni]:!0},{[Ri]:!0},{[ki]:!0}]);if(e[Wi])return e;const n=Gv(t,[{[zi]:qi,attr:{[_i]:!0}}]);if(n[Wi])return n;const{tournamentRecord:r,drawDefinition:i,participantId:a,matchUpId:o}=t,s=qd({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{[Wi]:Te};return $v({tournamentRecord:r,drawDefinition:i,matchUpId:o,timeItem:{itemValue:a,itemType:hd}})}function zv(t){const e=na(t,[{[Ri]:!0,[Ni]:!0,[ki]:!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:x};const s=Gv(t,[{[zi]:qi,[Wi]:Wt}]),c=s.matchUp?.matchUp;if(!c)return{error:Wt};const{checkedInParticipantIds:u=[]}=qd({matchUp:c});return i&&u.includes(i)?Wv({tournamentRecord:r,drawDefinition:o,participantId:i,matchUpId:a,matchUp:c}):Hv({tournamentRecord:r,drawDefinition:o,participantId:i,matchUpId:a,matchUp:c})}function Yv({tournamentRecord:t,drawDefinition:e,tieMatchUpId:n,event:r}){if(!t)return{error:x};if(!e)return{error:at};if(!r)return{error:Pt};const i=Fu({drawDefinition:e}),{matchUp:a}=Dg({matchUpId:n,drawDefinition:e,matchUpsMap:i});if(!a)return{error:Wt};const{matchUp:o,structure:s}=Dg({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&&![zc,Kc].includes(l))return{error:Yt};const{positionAssignments:m}=tc({structure:s}),f=m?.filter((t=>u?.includes(t.drawPosition))),{matchUp:h}=Dg({matchUpId:p,drawDefinition:e,matchUpsMap:i}),g=[...h?.sides?.map(vo)??[],...f?.map(vo)??[]],{participants:I}=ym({tournamentRecord:t,participantFilters:{participantTypes:[cu],participantIds:g}}),{matchUp:U}=Dg({matchUpId:p,inContext:!0,drawDefinition:e,matchUpsMap:i}),S=Bp({matchUp:h,drawDefinition:e,structure:s,event:r})?.tieFormat;return{inContextDualMatchUp:U,inContextTieMatchUp:o,relevantAssignments:f,collectionPosition:c,teamParticipants:I,collectionId:d,matchUpType:l,dualMatchUp:h,tieMatchUp:a,tieFormat:S,structure:s,...E}}function Kv(t){const e=Yv(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 Nr({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=ym({tournamentRecord:i,participantFilters:{participantIds:[r,a]}})?.participants??[];if(2!==S.length)return Nr({result:{error:Ae},stack:n});if(S[0].participantType!==S[1].participantType)return Nr({result:{error:be},stack:n});const{appliedPolicies:y}=Tu({tournamentRecord:i,drawDefinition:o,event:c}),v=t.policyDefinitions?.[ga]??y?.[ga]??Am[ga],w=S.find((({participantId:t})=>t===a));if(!1!==(t.enforceGender??v?.participants?.enforceGender)&&[cl,pl].includes(d?.gender)&&d?.gender!==w?.person?.sex)return{error:we,info:"Gender mismatch"};const T=v?.processCodes?.substitution;Xg({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 Nr({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 Nr({result:{error:Be},stack:n});const b=u?.sides?.find((({sideNumber:t})=>t===U.sideNumber))?.participantId,N=P.lineUp,M=N?.find((({participantId:t})=>a===t)),R=N?.reduce(((t,e)=>e.substitutionOrder>t?e.substitutionOrder:t),0),A=N?.map((t=>{const e=mi(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:R}:t))),e.participantId===a){e.collectionAssignments||(e.collectionAssignments=[]);const t={collectionId:l,collectionPosition:p};s&&(t.previousParticipantId=r,t.substitutionOrder=(R??0)+1),e.collectionAssignments.push(t)}return e}))??[];if(!M){const t={collectionId:l,collectionPosition:p};s&&(t.substitutionOrder=(R??0)+1,t.previousParticipantId=r);const e={collectionAssignments:[t],participantId:a};A.push(e)}const C=I===Kc,{assignedParticipantIds:O}=Zp({lineUp:N,collectionPosition:p,collectionId:l}),{assignedParticipantIds:F}=Zp({lineUp:A,collectionPosition:p,collectionId:l});if(P.lineUp=A,b&&g){const t=Pf({participantId:b,lineUp:A,drawDefinition:o,tieFormat:g});if(t.error)return Nr({result:t,stack:n})}else console.log("team participantId not found");let k,_;if(C){const{tournamentRecord:e}=t;let r=Xp({participantIds:F,tournamentRecord:e});if(!r.participant){const t=ly({returnParticipant:!0,pairOverride:!0,tournamentRecord:e,participant:{participantRole:Cm,individualParticipantIds:F,participantType:su}});if(t.error)return Nr({result:t,stack:n});k=t.participant?.participantId}r=Xp({participantIds:O,tournamentRecord:e});const i=r.participant?.participantId;if(i){Bm({participantIds:[i],tournamentRecord:e}).success&&(_=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&&Oc({tournamentId:i?.tournamentId,matchUp:h,context:n,drawDefinition:o})}return f&&Oc({tournamentId:i?.tournamentId,matchUp:f,context:n,drawDefinition:o}),{...E,modifiedLineUp:A,participantRemoved:_,participantAdded:k}}function Jv({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||tl({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 Qv({individualParticipantIds:t,groupingParticipantId:e,removeFromOtherTeams:n,tournamentRecord:r}){const i="addIndividualParticipantIds";if(!r)return Nr({result:{error:x},stack:i});if(!e||!t)return Nr({result:{error:ae},stack:i});const a=r.participants??[],o=a.find((t=>t.participantId===e));if(!o)return Nr({result:{error:Ee},stack:i});if(o?.participantType&&![cu,ou].includes(o.participantType))return Nr({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!==au}));if(s.length)return Nr({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&&Lm({individualParticipantIds:u,tournamentRecord:r}),o.individualParticipantIds=o.individualParticipantIds.concat(...u));const{topics:d}=mr();if(d.includes(gc)){const t=a.find((({participantId:t})=>t===e));cr({topic:gc,payload:{participants:[t]}})}return function({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}){const r=(n.events||[]).filter((t=>t?.eventType===Zd&&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}=Fp({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:mi(o,!1,!0),added:u.length,...E}}function Zv(t){const{updateParticipantName:e=!0,groupingParticipantId:n,removeFromOtherTeams:r,tournamentRecord:i,pairOverride:a,participant:o}=t;if(!i)return{error:x};if(!o)return{error:Me};if(!o.participantId)return ly({tournamentRecord:i,participant:o});const{participant:s}=Tl({participantId:o.participantId,tournamentRecord:i});if(!s)return ly({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}=ym({participantFilters:{participantTypes:[au]},tournamentRecord:i}),n=t?.map(vo);if(n){const r=u.filter((t=>"string"==typeof t&&n.includes(t)));([ou,Qc].includes(m||s.participantType)||m===su&&(2===r.length||a))&&(I.individualParticipantIds=r),s.participantType===uu.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(km).includes(l)&&(I.participantRole=l),Object.keys(uu).includes(m)&&(I.participantType=m),Array.isArray(c)&&(I.participantRoleResponsibilties=c),s.participantType===uu.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(ll).includes(u)&&(i.sex=u);let d;c&&"string"==typeof c&&(i.personId=c);s&&"string"==typeof s&&(p=s,vl.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,br(I)),n&&Qv({individualParticipantIds:[s.participantId],groupingParticipantId:n,removeFromOtherTeams:r,tournamentRecord:i}),cr({topic:gc,payload:{tournamentId:i.tournamentId,participants:[s]}}),{participant:mi(s),...E}}function Xv(t){const e=Yv(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 Nr({result:{error:Ae},stack:n});if(t.sideNumber&&![1,2].includes(t.sideNumber))return Nr({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 Nr({result:{...E},stack:n});r=r??(t.sideNumber?c?.sides?.find((e=>e.sideNumber===t.sideNumber))?.participantId:void 0);const U=ym({participantFilters:{participantIds:[o]},tournamentRecord:i})?.participants?.[0];if(!U)return Nr({result:{error:Ee},stack:n});const{appliedPolicies:S}=Tu({tournamentRecord:i,drawDefinition:a,event:s}),y=t.policyDefinitions?.[ga]??S?.[ga]??Am[ga];if(!1!==(t.enforceGender??y?.participants?.enforceGender)&&[cl,pl].includes(u?.gender)&&u?.gender!==U.person?.sex)return{error:we,info:"Gender mismatch"};const{individualParticipantIds:v,participantType:w}=U;if(f===zc&&w!==au)return{error:be};const T=w===au?[o]:v,P=r&&l?.find((({participantId:t})=>t===r))||l?.find((({individualParticipantIds:t})=>b(T,t)));if(!P)return{error:Rn};if(r||(r=P.participantId),!r)return{error:Ee};const D=d?.find((t=>t.participantId===P?.participantId)),N=D?.drawPosition,M=h?.sides?.find((t=>t.participantId===r))?.sideNumber,R=u?.sides?.find((t=>N&&t.drawPosition===N))?.sideNumber,A=M??R??t.sideNumber;if(!g)return{error:Gt};const C=g.collectionDefinitions?.find((t=>t.collectionId===m));if(!C)return{error:jt};Xg({tournamentId:i.tournamentId,eventId:s.eventId,inContextDualMatchUp:c,drawDefinition:a,dualMatchUp:h});const O=h?.sides?.find((t=>t.sideNumber===A)),F=u?.sides?.find((t=>t.sideNumber===A)),k=O?.lineUp??tl({participantId:r,drawDefinition:a})?.lineUp,_=k?.filter((t=>t.collectionAssignments?.find((t=>t.collectionPosition===p&&t.collectionId===m&&!t.previousParticipantId)))),x=_?.map((t=>t?.participantId)),L=x?.length>1&&x||(w===su?U.individualParticipantIds:[o]),B=Jv({collectionPosition:p,teamParticipantId:r,dualMatchUpSide:O,drawDefinition:a,participantIds:L,collectionId:m});if(B.error)return Nr({result:B,stack:n});const{modifiedLineUp:V}=B;let j;if(f===Kc){if(w!==su){let t=tw({collectionPosition:p,teamParticipantId:r,drawDefinition:a,modifiedLineUp:V,participantId:o,collectionId:m,tieFormat:g});if(t?.error)return Nr({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}=Xp({participantIds:n,tournamentRecord:i});n.push(o);const{participant:r}=Xp({participantIds:n,tournamentRecord:i});if(!r&&t){t.individualParticipantIds=n;const e=Zv({pairOverride:!0,tournamentRecord:i,participant:t});if(e.error)return e}else e=t?.participantId}}else{const t=ly({participant:{individualParticipantIds:[o],participantRole:Cm,participantType:su},pairOverride:!0,tournamentRecord:i});if(t.error)return t}return{...E,deletedParticipantId:e}}({side:F}),t.error)return t;j=t.deletedParticipantId,O&&(O.lineUp=V),h&&Oc({tournamentId:i?.tournamentId,matchUp:h,context:n,drawDefinition:a})}else if(w===su)for(const t of L)tw({collectionPosition:p,teamParticipantId:r,drawDefinition:a,modifiedLineUp:V,participantId:t,collectionId:m,tieFormat:g})}else{const t=tw({collectionPosition:p,teamParticipantId:r,drawDefinition:a,modifiedLineUp:V,participantId:o,collectionId:m,tieFormat:g});if(t?.error)return t}if(O&&(O.lineUp=V),h&&Oc({tournamentId:i?.tournamentId,matchUp:h,context:n,drawDefinition:a}),j){const{error:t}=Bm({participantIds:[j],tournamentRecord:i});t&&console.log("cleanup")}return{...E,modifiedLineUp:V}}function tw({collectionPosition:t,teamParticipantId:e,drawDefinition:n,modifiedLineUp:r,participantId:i,collectionId:a,tieFormat:o}){const s=tl({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 Pf({participantId:e,lineUp:r,drawDefinition:n,tieFormat:o})}function ew(t){const{tournamentRecord:e,drawDefinition:n,participantId:r,event:i}=t,a="removeTieMatchUpParticiapantId";if(!r)return Nr({result:{error:Ae},stack:a});const o=Yv(t);if(o.error)return o;const{appliedPolicies:s}=Tu({tournamentRecord:e,drawDefinition:n,event:i}),c=t.policyDefinitions?.[ga]??s?.[ga]??Am[ga],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 Nr({result:{error:zt},stack:a});const y=p?.sides?.find((t=>t.participant?.participantId===r||t.participant?.individualParticipantIds?.includes(r)));if(!y)return Nr({result:{error:Ee},stack:a});if(!y.substitutions?.length&&(Gc({score:p?.score})||p?.winningSide))return Nr({result:{error:xn},stack:a});const v=d?.sides?.find((({sideNumber:t})=>t===y.sideNumber))?.participantId;if(!v)return Nr({result:{error:Ee},stack:a});const w=ym({participantFilters:{participantIds:[r]},tournamentRecord:e})?.participants?.[0];if(!w)return Nr({result:{error:Ee},stack:a});if(g===zc&&w.participantType===su)return Nr({result:{error:we},stack:a});const T=w.participantType===au?[r]:w.individualParticipantIds;Xg({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 Nr({result:{error:Ee,context:{participantId:r}}});const{modifiedLineUp:D,previousParticipantIds:b}=Jv({collectionPosition:m,teamParticipantId:v,dualMatchUpSide:P,participantIds:T,drawDefinition:n,collectionId:h});if(P.lineUp=D,v&&S&&Pf({participantId:v,lineUp:D,drawDefinition:n,tieFormat:S}),g===Kc&&w.participantType===au){const t=p?.sides?.find((t=>t.sideNumber===P?.sideNumber)),{participantId:n}=t??{},i=n&&ym({participantFilters:{participantIds:[n]},tournamentRecord:e,withDraws:!0})?.participants?.[0];if(!i)return Nr({result:{error:Ee},stack:a});{const t=i?.individualParticipantIds?.filter((t=>t!==r))??[];if(b&&t.push(...b),t.length>2)return Nr({result:{error:Pe},stack:a});if(i.draws?.length){if(1===t.length){const{participant:n}=Xp({participantIds:t,tournamentRecord:e});if(!n){const n=ly({participant:{participantRole:Cm,individualParticipantIds:t,participantType:su},pairOverride:!0,tournamentRecord:e});if(n.error)return Nr({result:n,stack:a})}}}else if(t.length){i.individualParticipantIds=t;const n=Zv({participant:i,pairOverride:!0,tournamentRecord:e});if(n.error)return Nr({result:n,stack:a})}else{const t=Bm({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)}Oc({tournamentId:e?.tournamentId,matchUp:U,context:a,drawDefinition:n})}}return Oc({tournamentId:e?.tournamentId,matchUp:I,context:a,drawDefinition:n}),{...E,modifiedLineUp:D}}function nw({tournamentRecord:t,drawDefinition:e,sideNumber:n,matchUpId:r,event:i}){if(!t)return{error:x};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}=Dg({drawDefinition:e,matchUpId:r,event:i});if(!a)return{error:Wt};return o?.structures||e.drawType&&e.drawType!==Ss||o?.matchUps?.find((({roundPosition:t})=>!!t))?{error:et}:(a.sides?.forEach((t=>{t.sideNumber===n&&delete t.participantId})),Oc({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:a}),{...E})}function rw({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&&No||[Eo,Vo].includes(u.matchUpStatus)&&u.matchUpStatus||Bo,[Vo,Eo].includes(u.matchUpStatus)&&(u.winningSide=void 0),u.matchUpStatusCodes&&Zm({inContextDrawMatchUps:t,sourceMatchUpStatus:n,sourceMatchUpId:a,matchUpsMap:c,matchUp:u}),Oc({tournamentId:i?.tournamentId,eventId:d?.eventId,context:`removeSubsequentDrawPosition-${r}`,drawDefinition:o,matchUp:u}),{...E}}function iw(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=nl({drawDefinition:i,structure:d}),{drawPositions:f,winningSide:h}=c.matchUp||{};if(!m&&!f)return{error:Q};const{targetLinks:{loserTargetLink:g,winnerTargetLink:I,byeTargetLink:U},targetMatchUps:{loserMatchUp:S,winnerMatchUp:y,byeMatchUp:v}}=c,w=Mg({...t,matchUpStatus:a||Bo,removeWinningSide:!0});if(w.error)return w;let T;if(l){const{matchUpTieId:n,matchUpsMap:a}=t;if(T=tI({matchUpId:n,tournamentRecord:r,drawDefinition:i,matchUpsMap:a,event:p}),!e&&!T.removeWinningSide)return{...E}}if(m)return{...E};const{matchUps:P}=ml({afterRecoveryTimes:!1,inContext:!0,drawDefinition:i,matchUpsMap:o,structure:d}),{positionAssignments:D}=ec({structure:d}),N=h-1,M=1-N,R=f[N],A=f[M],{winnerParticipantId:C,loserParticipantId:O}=D?.reduce(((t,e)=>(e.drawPosition===A&&(t.loserParticipantId=e.participantId),e.drawPosition===R&&(t.winnerParticipantId=e.participantId),t)),{winnerParticipantId:void 0,loserParticipantId:void 0})||{},F=P.filter((t=>t.drawPositions?.includes(A)));if(y&&aw({sourceMatchUpStatus:a,sourceMatchUpId:u,inContextDrawMatchUps:n,winningDrawPosition:R,winnerParticipantId:C,tournamentRecord:r,winnerTargetLink:I,drawDefinition:i,winnerMatchUp:y,dualMatchUp:s,matchUpsMap:o}),S){const{winnerHadMatchUpStatus:t}=function({matchUpStatuses:t=[No,Vo,Eo],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===Us){ow({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}=Qs({drawDefinition:a,structureId:p});if(!l)return{error:Ut};const{positionAssignments:m}=ec({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,Oc({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){ow({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 aw({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}=Qs({drawDefinition:s,structureId:t});if(!e)return{error:Ut};const{positionAssignments:n}=ec({structure:e});e.seedAssignments=(e.seedAssignments??[]).filter((t=>t.participantId!==r));const o=n?.find((t=>t.participantId===r)),d=o?.drawPosition,{matchUps:l}=ml({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&&Oc({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}=Qs({drawDefinition:a,structureId:o});if(p?.structureType===ds)return{...E};u=u??Fu({drawDefinition:a});const l=(u?.mappedMatchUps||{})[o].matchUps,{initialRoundNumber:m}=ql({drawPosition:n,matchUps:l}),f=l?.filter((t=>t.roundNumber>=c&&t.roundNumber!==m&&t.drawPositions?.includes(n))),{positionAssignments:h}=tc({drawDefinition:a,structureId:o});for(const o of f??[])rw({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 ow({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,matchUpsMap:i,targetLink:a,event:o}){return tm({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:i,drawPosition:r,structureId:a.target.structureId,event:o}),{...E}}function sw(t){const{tournamentRecord:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:i,targetData:a,structure:o,event:s}=t,c="doubleExitAdvancement";if(o.structureType===ds)return Nr({result:{...E},stack:c});const{matchUp:u,targetMatchUps:d,targetLinks:p}=a,{loserMatchUp:l,winnerMatchUp:m,loserTargetDrawPosition:f}=d;if(l&&l.matchUpStatus!==No){const{loserTargetLink:a}=p;if(n?.progression?.doubleExitPropagateBye){const t=uw({loserTargetDrawPosition:f,tournamentRecord:e,loserTargetLink:a,drawDefinition:r,loserMatchUp:l,matchUpsMap:i,event:s});if(t.error)return Nr({result:t,stack:c})}else{const{feedRound:n,drawPositions:r,matchUpId:i}=l,a=n?2:2-r.indexOf(f),o=cw({...t,targetMatchUp:l,walkoverWinningSide:a,tournamentRecord:e,sourceMatchUp:u,matchUpId:i});if(o.error)return Nr({result:o,stack:c})}}if(m){const n=cw({...t,matchUpId:m.matchUpId,targetMatchUp:m,tournamentRecord:e,sourceMatchUp:u});if(n.error)return Nr({result:n,stack:c})}return Nr({result:{...E},stack:c})}function cw(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===Co?Co:Oo,u=t.matchUpStatus===Co?Eo:Vo,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 Nr({result:{error:z},stack:d});const{pairedPreviousMatchUpIsDoubleExit:h,pairedPreviousMatchUp:g}=Jm(t),I=gu({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=uw({loserTargetDrawPosition:y,loserMatchUp:w,tournamentRecord:n,loserTargetLink:t,drawDefinition:r,matchUpsMap:o});if(e.error)return Nr({result:e,stack:d})}const T=p.drawPositions?.filter(Boolean)||[],P=1===T.length,D=t.walkoverWinningSide||P&&Xm({drawPosition:T[0],matchUpId:a.matchUpId,inContextDrawMatchUps:e})||void 0,N=[Vo,Eo].includes(p.matchUpStatus)&&!T.length,M=1===p.finishingRound,R=N&&!M?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:dw(F),previousMatchUpStatus:F,sideNumber:1},{matchUpStatus:dw(k),previousMatchUpStatus:k,sideNumber:2}]:2===C&&(O=[{matchUpStatus:dw(k),previousMatchUpStatus:k,sideNumber:1},{matchUpStatus:dw(F),previousMatchUpStatus:F,sideNumber:2}]),O.length&&(O=O.map((t=>br(t))));const _=Mg({...t,matchUp:p,winningSide:D,matchUpStatusCodes:O,matchUpStatus:R});if(_.error)return Nr({result:_,stack:d});if(N)return sw({...t,matchUpStatus:R,targetData:I});if(!v)return Nr({result:{...E},stack:d});const x=2===m.length?m[D-1]:m[0],{positionAssignments:L}=tc({structure:s}),B=L?.find((t=>t.drawPosition===x)),V=o.drawMatchUps.find((t=>t.matchUpId===v.matchUpId)),j=V?.drawPositions?.filter(Boolean),G=1===j.length;if(x){if(B?.bye){const n=gu({matchUpId:V.matchUpId,inContextDrawMatchUps:e,drawDefinition:r});if(G){const t=j.filter(Boolean)[0],n=Xm({drawPosition:t,matchUpId:V.matchUpId,inContextDrawMatchUps:e}),i=Mg({matchUpId:V.matchUpId,matchUp:V,matchUpStatus:u,matchUpStatusCodes:[],removeScore:!0,drawDefinition:r,winningSide:n});return i.error?Nr({result:i,stack:d}):Ql({drawPositionToAdvance:t,matchUpId:V.matchUpId,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:o})}if([Vo,Eo].includes(v.matchUpStatus)){const e=sw({...t,matchUpId:V.matchUpId,matchUpStatus:R,targetData:n});if(e.error)return Nr({result:e,stack:d})}return Nr({result:{...E},stack:d})}return ef({matchUpId:v.matchUpId,drawPosition:x,inContextDrawMatchUps:e,drawDefinition:r})}if(h){if(!V)return{error:zt};if(G){const t=j[0],n=Xm({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawPosition:t});console.log("existing drawPosition is winningSide",{walkoverWinningSide:n})}const n=[Vo,Eo].includes(V.matchUpStatus)?u:c,i=Mg({matchUpId:V.matchUpId,matchUp:V,matchUpStatusCodes:[],removeScore:!0,drawDefinition:r,matchUpStatus:n});if(i.error)return Nr({result:i,stack:d});if(n===c){const e=sw({...t,matchUpId:a.matchUpId,matchUpStatus:n,targetData:I});if(e.error)return e}}return Nr({result:{...E},stack:d})}function uw(t){const{loserTargetDrawPosition:e,tournamentRecord:n,loserTargetLink:r,drawDefinition:i,matchUpsMap:a,event:o}=t,s=r?.target?.structureId,{structure:c}=Qs({drawDefinition:i,structureId:s});return c?Yl({drawPosition:e,tournamentRecord:n,drawDefinition:i,structureId:s,matchUpsMap:a,event:o}):{error:yt}}function dw(t){return t===Oo?Vo:t===Co?Eo:t}function pw(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===No,c=a.winningSide,u=[Oo,Co].includes(r),d=qc({matchUpStatus:r}),p=$c({matchUpStatus:r}),l=!d&&!p,m=t.matchUpTieId||c&&d&&!u,f=c&&u;return l&&{error:Ft}||m&&lw(t)||f&&function(t){const e=iw(t);return e.error?e:sw(t)}(t)||c&&iw(t)||p&&Mg({...t,removeScore:[Mo,Vo].includes(r),matchUpStatus:r||Bo})||s&&function({tournamentRecord:t,drawDefinition:e,structure:n,matchUp:r}){const i="attemptToSetMatchUpStatusBYE";if(r?.winningSide)return Nr({result:{error:xt},context:{matchUpStatus:No},stack:i});const{positionAssignments:a}=ec({structure:n}),o=a?.filter((t=>t.bye)).map((t=>t.drawPosition)),s=r.drawPositions?.some((t=>o?.includes(t)));return s?(r.matchUpStatus=No,r.matchUpStatusCodes=[],Oc({tournamentId:t?.tournamentId,context:i,drawDefinition:e,matchUp:r}),{...E}):Nr({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=lw({...t,removeScore:!0});return e.error?e:sw(t)}(t)||o&&lw(t)||Nr({result:{error:xt},stack:"attemptToSetMatchUpStatus"})}function lw(t){const e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){const n=iw(t);if(n.error)return Nr({result:n,stack:e})}const n=Boolean(t.matchUp.collectionId),r=Mg(t);if(n){const{matchUpTieId:n,drawDefinition:i,matchUpsMap:a}=t,o=tI({tournamentRecord:t.tournamentRecord,matchUpId:n,event:t.event,drawDefinition:i,matchUpsMap:a});if(o.error)return Nr({result:o,stack:e});Object.assign(r,{tieMatchUpResult:o})}return Nr({result:r,stack:e})}function mw({drawDefinition:t,structure:e,matchUp:n}){const r=[];if(e.finishingPosition===Ws){if(Bf({drawDefinition:t,structure:e})){const{structureIds:i}=function({drawDefinition:t,structure:e,matchUp:n}){const{drawPositions:r}=n,{positionAssignments:i}=tc({drawDefinition:t,structure:e}),a=i?.filter((({drawPosition:t})=>r?.includes(t))),o=a?.map((t=>{const{extension:e}=Fr({element:t,name:ao});return e?.value?.groupOrder})),{containerStructures:s}=jc({drawDefinition:t}),c=s[e.structureId],u=hu({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 fw(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 Rg(t);if(u.winningSide&&u.winningSide!==s){const{connectedStructureIds:e}=mw({drawDefinition:a,structure:c,matchUp:u});e.length&&(console.log({connectedStructureIds:e}),n=!0);const r=iw(t);if(r.error)return r}const d=eI(t);if(d.error)return Nr({result:d,stack:e});let p,l;return t.qualifierChanging&&r?.[ya]?.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===ps){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===Bo&&!aU({inContextDrawMatchUps:n,drawDefinition:i,targetData:gu({matchUpId:c.matchUpId,inContextDrawMatchUps:n,drawDefinition:i})})){const{structure:n}=Qs({structureId:c.structureId,drawDefinition:i}),o=tc({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]))}xc({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:i,structure:n}),e=!0}}}return{...E,qualifierReplaced:e}}(t).qualifierReplaced),t.qualifierAdvancing&&r?.[ya]?.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===ps){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===Bo&&!aU({inContextDrawMatchUps:n,drawDefinition:i,targetData:gu({matchUpId:c.matchUpId,inContextDrawMatchUps:n,drawDefinition:i})})){const n=c.sides.find((t=>t.qualifier&&!t.participantId))?.drawPosition,{structure:r}=Qs({structureId:c.structureId,drawDefinition:i});if(!r)return{error:Ut};const a=tc({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]))}xc({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:i,structure:r}),e=!0}}}return{...E,qualifierPlaced:e}}(t).qualifierPlaced),Nr({result:br({...E,...d,connectedStructures:n,qualifierReplaced:p,qualifierPlaced:l}),stack:e})}const hw={drawPositionToRemove:"green",iteration:"brightred",winner:"green",loser:"brightred"};function gw(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";Hl({method:c,color:"brightyellow",iteration:s,keyColors:hw});const{targetLinks:{loserTargetLink:u},targetMatchUps:{loserMatchUp:d,winnerMatchUp:p,loserTargetDrawPosition:l}}=a;if(p&&p.matchUpStatus!==No){const{stage:e,roundNumber:n,roundPosition:r}=p;Hl({winner:"winner",stage:e,roundNumber:n,roundPosition:r,keyColors:hw}),Iw({...t,targetMatchUp:p,sourceMatchUp:o,iteration:s})}if(d&&d.matchUpStatus!==No){const a=e.find((({matchUpId:t})=>t===d.matchUpId)),{structure:o}=Qs({drawDefinition:r,structureId:a.structureId}),{stage:p,roundNumber:m,roundPosition:f,feedRound:h}=d;if(Hl({loser:"loser",stage:p,roundNumber:m,roundPosition:f,keyColors:hw,feedRound:h}),n?.progression?.doubleExitPropagateBye)ow({drawPosition:l,targetLink:u,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:i});else{const e=Iw({...t,structure:o,targetMatchUp:d,iteration:s});if(e.error)return Nr({result:e,stack:c})}}return Nr({result:{...E},stack:c})}function Iw(t){const{inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,sourceMatchUp:i,targetMatchUp:a,matchUpsMap:o,structure:s,iteration:c}=t,u="conditionallyRemoveDrawPosition";Hl({method:u});const d=gu({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=Qm({structureId:s.structureId,matchUp:i,matchUpsMap:o})?.pairedPreviousMatchUp,m=[Oo,Co].includes(f?.matchUpStatus),g=f?.drawPositions?.filter(Boolean)||[];if([...Ho,No].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;Hl({method:"removeDirectedWinner",drawPositionToRemove:h,keyColors:hw,color:"brightgreen",stage:t,roundNumber:n,roundPosition:i}),aw({winningDrawPosition:h,winnerMatchUp:p,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:o})}let I=gw({targetData:d,matchUp:a,inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:o,structure:s,iteration:c});if(I.error)return Nr({result:I,stack:u});const U=function({pairedPreviousDoubleExit:t,noContextTargetMatchUp:e}){return e.matchUpStatus===No?No:t?[Co,Eo].includes(e?.matchUpStatus)?Eo:Vo:Bo}({pairedPreviousDoubleExit:m,noContextTargetMatchUp:l}),S=!m;return I=Mg({...t,matchUpStatus:U,removeScore:S,score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},removeWinningSide:!0,matchUp:l,matchUpId:a.matchUpId,matchUpStatusCodes:[]}),I.error?Nr({result:I,stack:u}):{...E}}function Uw(t){const{matchUp:e,matchUpStatus:n,score:r,winningSide:i}=t,a="noDownStreamDependencies";if([Oo,Co].includes(e?.matchUpStatus)&&![Oo,Co].includes(n)){const e=gw(t);if(e.error)return Nr({result:e,stack:a})}const o=n===Oo,s=Gc({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&&Wp(e),{setFormat:a,finalSetFormat:o,bestOf:s}=i??{},c=s&&r===s&&o||a;return c?.timed||!1}(t.inContextMatchUp),u=t.removeScore||!c&&![ko,Do].includes(n||ko),d=t.isCollectionMatchUp&&t.dualMatchUp.winningSide&&!t.projectedWinningSide||e.winningSide&&!i&&!Gc({score:r}),p=n&&n!==Bo,l=n=>{let r;const{structure:i,drawDefinition:a,dualMatchUp:o,disableAutoCalc:s}=t;if(o?._disableAutoCalc&&!1!==s)return Rg(t);const{connectedStructureIds:c}=mw({drawDefinition:a,structure:i,matchUp:e});c.length&&(console.log({connectedStructureIds:c}),r=!0),Object.assign(t,{removeScore:n});const u=iw(t);if(u.error)return u;if(t.removingQualifier&&t.appliedPolicies?.[ya]?.autoRemoveQualifiers){const e=function(t){let e;const{inContextDrawMatchUps:n,inContextMatchUp:r,drawDefinition:i}=t,a=t.targetData.targetLinks?.winnerTargetLink;if(a.target.feedProfile===ps){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===Bo&&!aU({inContextDrawMatchUps:n,drawDefinition:i,targetData:gu({matchUpId:s.matchUpId,inContextDrawMatchUps:n,drawDefinition:i})})){const{structure:n}=Qs({structureId:s.structureId,drawDefinition:i}),r=tc({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]))}xc({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 Sw(t);const m=[Mo,Do].includes(n)&&t.dualWinningSideChange;return Nr({result:(i||m)&&fw(t)||s&&l(u)||p&&pw(t)||d&&l(u)||e&&Sw({...t,removeScore:!0})||{...E},stack:a})}function Sw(t){if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){const e=iw(t);if(e.error)return e}const e=Mg({...t});if(t.isCollectionMatchUp){const{matchUpTieId:e,drawDefinition:n,event:r,matchUpsMap:i}=t,{removeWinningSide:a}=tI({tournamentRecord:t.tournamentRecord,matchUpId:e,drawDefinition:n,matchUpsMap:i,event:r});a&&console.log("REMOVE WINNING SIDE")}return Nr({result:e,stack:"scoreModification"})}function yw({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,courtDayDate:a,matchUpId:o,courtIds:s}){if(!n&&!e)return{error:x};if(!o)return{error:qt};const c=Dg({drawDefinition:r,matchUpId:o});if(c.error)return c;if(c?.matchUp?.matchUpType!==Jc)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=Py({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 $v({duplicateValues:!1,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o,timeItem:{itemType:Ud,itemDate:a,itemValue:u}})}function vw({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,venueId:o}){if(!n)return{error:x};if(!a)return{error:qt};if(o){const t=Dp({tournamentRecords:e,tournamentRecord:n,venueId:o});if(t.error)return t}return $v({duplicateValues:!1,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:{itemType:Id,itemValue:o}})}function ww({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,courtDayDate:a,matchUpId:o,courtId:s}){if(!n&&!e)return{error:x};if(!o)return{error:qt};if(s){const t=Np({tournamentRecords:e,tournamentRecord:n,courtId:s});if(t.error)return t;const a=t.venue?.venueId;vw({tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o,venueId:a})}return $v({duplicateValues:!1,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o,timeItem:{itemType:Sd,itemDate:a,itemValue:s}})}function Tw(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 Nr({result:{error:qt},stack:e});if(!jr(s))return Nr({result:{error:le},stack:e});if(!n){const t=Dg({drawDefinition:a,matchUpId:c});if(t.error)return Nr({result:t,stack:e});n=t.matchUp}const u=ti(s),d=Up({matchUp:n}).scheduledDate,p=u&&!d,l=Ep({matchUp:n}).timeModifiers||[];if(l?.length){const t=Pw({disableNotice:!0,removePriorValues:r,tournamentRecord:i,timeModifiers:[],drawDefinition:a,matchUpId:c,matchUp:n});if(t?.error)return Nr({result:t,stack:e})}const m=ri(s,!0,p);return $v({duplicateValues:!1,removePriorValues:r,tournamentRecord:i,drawDefinition:a,disableNotice:o,matchUpId:c,timeItem:{itemType:Td,itemValue:m}})}function Pw({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,timeModifiers:i,matchUpId:a,matchUp:o}){const s="addMatchUpTimeModifiers";if(!a)return Nr({result:{error:qt},stack:s});if(void 0!==i&&!Array.isArray(i))return Nr({info:wf("timeModifiers"),result:{error:Nn},stack:s});if(!o){const t=Dg({drawDefinition:n,matchUpId:a});if(t.error)return Nr({result:t,stack:s});o=t.matchUp}let c=Ep({matchUp:o}).timeModifiers||[];const u=i.filter((t=>!c.includes(t)));if(i.length&&!u.length)return{...E};if(u.some((t=>Fd.includes(t)))){c=c.filter((t=>!Fd.includes(t)));const r=Tw({disableNotice:!0,removePriorValues:t,scheduledTime:"",tournamentRecord:e,drawDefinition:n,matchUpId:a});if(r.error)return Nr({result:r,stack:s})}const d=i?.length?[...u,...c]:void 0;return $v({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:a,timeItem:{itemType:Md,itemValue:d}})}function Dw(t,e){const n=_r.test(t)?t:Xr(t),r=ti(t)||ti(e)||$r(new Date);return new Date(`${r}T${n}`).getTime()}function bw({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=Dg({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}=jl({drawDefinition:s}));const M=n?.[d]?.matchUpIds;if(l.scheduledDate&&e&&M){const e=r?.filter((t=>(t.schedule?.scheduledDate||ti(t.schedule?.scheduledTime))&&M.includes(t.matchUpId))).map((({schedule:t})=>{const e=Br(t);return new Date(e).getTime()}));if(e?.length){const n=Br(l),r=new Date(n).getTime();if(Math.max(...e)>=r){if(t)return Nr({result:{error:O},stack:f});g=O}}}if(void 0!==w){const t=Nw({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,scheduledDate:w,matchUpId:d});if(t?.error)return Nr({result:t,stack:f,context:{scheduledDate:w}})}if(void 0!==T){const t=Tw({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,scheduledTime:T,matchUpId:d,matchUp:h});if(t?.error)return Nr({result:t,stack:f,context:{scheduledTime:T}})}if(void 0!==P){const t=Aw({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,matchUpId:d,startTime:P,event:m});if(t?.error)return Nr({result:t,stack:f,context:{startTime:P}})}if(void 0!==D){const t=Cw({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,matchUpId:d,stopTime:D,event:m});if(t?.error)return Nr({result:t,stack:f,context:{stopTime:D}})}if(void 0!==v){const t=Ow({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,resumeTime:v,matchUpId:d,event:m});if(t?.error)return Nr({result:t,stack:f,context:{resumeTime:v}})}if(void 0!==I){const t=Ew({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,matchUpId:d,endTime:I,event:m});if(t?.error)return Nr({result:t,stack:f,context:{endTime:I}})}if(void 0!==S){const t=yw({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,matchUpId:d,courtIds:S});if(t?.error)return Nr({result:t,stack:f,context:{courtIds:S}})}if(void 0!==U&&void 0!==w){const t=ww({courtDayDate:w,disableNotice:!0,removePriorValues:i,tournamentRecords:a,tournamentRecord:o,drawDefinition:s,matchUpId:d,courtId:U});if(t?.error)return Nr({result:t,stack:f,context:{courtId:U}})}if(void 0!==N){const t=vw({disableNotice:!0,removePriorValues:i,tournamentRecords:a,tournamentRecord:o,drawDefinition:s,matchUpId:d,venueId:N});if(t?.error)return Nr({result:t,stack:f,context:{venueId:N}})}if(void 0!==y&&p(y)){const t=Mw({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,courtOrder:y,matchUpId:d});if(t?.error)return Nr({result:t,stack:f,context:{courtOrder:y}})}if(void 0!==b){const t=Pw({disableNotice:!0,removePriorValues:i,tournamentRecord:o,drawDefinition:s,timeModifiers:b,matchUpId:d,matchUp:h});if(t?.error)return Nr({result:t,stack:f,context:{timeModifiers:b}})}return c||Oc({tournamentId:o?.tournamentId,eventId:m?.eventId,context:f,drawDefinition:s,matchUp:h}),g?{...E,warnings:[g]}:{...E}}function Nw({scheduledDate:t,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a}){if(!a)return{error:qt};const o=t&&xr.test(t);if(t&&!o)return{error:pe};return $v({duplicateValues:!1,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:{itemValue:ti(t),itemType:vd}})}function Mw({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 $v({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:i,matchUpId:o,timeItem:{itemType:yd,itemValue:s}})}function Rw({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(!Ma({tournamentParticipants:ym({tournamentRecord:e,participantFilters:{participantTypes:[au],participantRoles:[Om]}}).participants??[],participantId:i}))return{error:Ee}}const s={itemType:"SCHEDULE.ASSIGNMENT.OFFICIAL",itemValue:i};return a&&(s.itemSubTypes=[a]),$v({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:o,timeItem:s})}function Aw({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,startTime:a,event:o}){if(!i)return{error:qt};if(!jr(a))return{error:le};const{matchUp:s}=Dg({drawDefinition:n,event:o,matchUpId:i}),{scheduledDate:c}=Up({matchUp:s}),u=(s?.timeItems??[]).filter((t=>[Dd,bd,Nd].includes(t?.itemType))).map((t=>Dw(t.itemValue,c))).reduce(((t,e)=>!t||e<t?e:t),void 0);if(!u||Dw(a,c)<u){s?.timeItems&&(s.timeItems=s.timeItems.filter((t=>t.itemType!==Pd)));const o=ri(a,!0,!0);return $v({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,timeItem:{itemType:Pd,itemValue:o}})}return{error:un}}function Ew({validateTimeSeries:t=!0,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,endTime:o,event:s}){if(!a)return{error:qt};if(!jr(o))return{error:le};const{matchUp:c}=Dg({drawDefinition:r,event:s,matchUpId:a}),{scheduledDate:u}=Up({matchUp:c}),d=(c?.timeItems??[]).filter((t=>[Pd,bd,Dd].includes(t?.itemType))).map((t=>Dw(t.itemValue,u))).reduce(((t,e)=>!t||e>t?e:t),void 0);if(!t||!d||Dw(o,u)>d){c?.timeItems&&(c.timeItems=c.timeItems.filter((t=>t.itemType!==Nd)));const t=ri(o,!0,!0);return $v({duplicateValues:!1,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,timeItem:{itemType:Nd,itemValue:t}})}return{error:on}}function Cw({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,stopTime:a,event:o}){if(!i)return{error:qt};if(!jr(a))return{error:le};const{matchUp:s}=Dg({drawDefinition:n,event:o,matchUpId:i}),{scheduledDate:c}=Up({matchUp:s}),u=s?.timeItems??[];if(u.reduce(((t,e)=>e.itemType===Nd||t),void 0))return{error:sn};const d=u.filter((t=>[Pd,bd,Dd].includes(t?.itemType))).sort(((t,e)=>Dw(t.itemValue,c)-Dw(e.itemValue,c))),p=d[d.length-1],l=p&&p.itemType===Dd,m=d.filter((t=>!l||t.createdAt!==p.createdAt)).map((t=>Dw(t.itemValue,c))).reduce(((t,e)=>!t||e>t?e:t),void 0);if(Dw(a,c)>m){if(s?.timeItems&&l){const t=p.createdAt;s.timeItems=s.timeItems.filter((e=>e.createdAt!==t))}return $v({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,timeItem:{itemValue:ri(a,!0,!0),itemType:Dd}})}return{error:cn}}function Ow({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,resumeTime:i,matchUpId:a,event:o}){if(!a)return{error:qt};if(!jr(i))return{error:le};const{matchUp:s}=Dg({drawDefinition:n,event:o,matchUpId:a}),{scheduledDate:c}=Up({matchUp:s}),u=s?.timeItems??[];if(u.reduce(((t,e)=>e.itemType===Nd||t),void 0))return{error:sn};const d=u.filter((t=>[Pd,bd,Dd].includes(t?.itemType))).sort(((t,e)=>Dw(t.itemValue,c)-Dw(e.itemValue,c))),p=d[d.length-1],l=p&&p.itemType===bd,m=d.filter((t=>!l||t.createdAt!==p.createdAt)).map((t=>Dw(t.itemValue,c))).reduce(((t,e)=>!t||e>t?e:t),void 0);if(Dw(i,c)>m){if(s?.timeItems&&l){const t=p.createdAt;s.timeItems=s.timeItems.filter((e=>e.createdAt!==t))}return $v({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:a,timeItem:{itemValue:ri(i,!0,!0),itemType:bd}})}return{error:dn}}function Fw({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:wf("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?Wp(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&&[Eo,xo,Vo].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 kw(t){const e="setMatchUpStatus";t.matchUpStatus&&[Vo,Oo].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&&[Mo,ko,Do,Bo].includes(u)&&d)return{error:Nn,winningSide:d,matchUpStatus:u};if(![void 0,...qo].includes(u))return Nr({result:{error:xt},info:"matchUpStatus does not exist",stack:"setMatchUpStatus"});const f=Fu({drawDefinition:c}),{matchUps:h}=gl({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===No)return{context:"Cannot have Bye with winningSide",error:_t,matchUpStatus:u};const U=I?.structureId,{structure:S}=Qs({drawDefinition:c,structureId:U}),y=I?.drawPositions?.filter(Boolean);let v;if(g.matchUpType===Qc){if(o)Cr({extension:{name:qa,value:!0},element:g});else if(s){const e=g.winningSide;Ar({name:qa,element:g});const{winningSide:n,scoreStringSide1:r,scoreStringSide2:i,set:a}=Kg({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})}Xg({tournamentId:a?.tournamentId,inContextDualMatchUp:I,eventId:l?.eventId,drawDefinition:c,dualMatchUp:g})}if(g.matchUpType===Qc&&u&&[bo].includes(u))return{error:Nn,info:"Not supported for matchUpType: TEAM"};const w=I?.matchUpTieId,T=gu({matchUpId:w||p,inContextDrawMatchUps:h,drawDefinition:c});if(m&&g.matchUpType!==Qc&&!r){const t=g.matchUpFormat??S?.matchUpFormat??c?.matchUpFormat??l?.matchUpFormat,e=Fw({existingMatchUpStatus:g.matchUpStatus,matchUpFormat:t,matchUpStatus:u,winningSide:d,score:m});if(e.error)return e}const P=g?.sides?[]:tc({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&&Go.includes(u)&&!D)return Nr({info:"present in participantRequiredMatchUpStatuses",context:{matchUpStatus:u,bothSideParticipants:D},result:{error:xt}});const b=Tu({policyTypes:[ya],tournamentRecord:a,drawDefinition:c,event:l})?.appliedPolicies??{};"object"==typeof t.policyDefinitions&&Object.assign(b,t.policyDefinitions);const N=I?.stage===Qo&&1===I.finishingRound,M=N&&d,R=N&&g.winningSide&&!d&&(!t.matchUpStatus||t.matchUpStatus&&$c({matchUpStatus:t.matchUpStatus}))&&(!t.outcome||!Gc({outcome:t.outcome})),A=M&&d!==g.winningSide&&g.winningSide;if(Object.assign(t,{inContextDrawMatchUps:h,qualifierAdvancing:M,qualifierChanging:A,removingQualifier:R,inContextMatchUp:I,appliedPolicies:b,matchUpTieId:w,matchUpsMap:f,targetData:T,structure:S,matchUp:g}),w){const{matchUp:e}=Dg({matchUpId:w,inContext:!0,drawDefinition:c,matchUpsMap:f,event:l});if(e){const n=Bp({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=mi(i,void 0,!0);for(const t of d?.tieMatchUps||[])t.matchUpId===s.matchUpId&&(t.winningSide=r,t.score=u,Gc({score:u})||e?e&&(t.matchUpStatus=e):Object.assign(t,{...Tg}));a=a??Bp({matchUp:s,structure:o,drawDefinition:t,event:c})?.tieFormat;const{winningSide:p}=Kg({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=aU(t),C=qc({matchUpStatus:u});if(!w){if(E&&!d&&(u&&$c({matchUpStatus:u})||u&&[Oo,Co].includes(u)))return{error:_t,activeDownstream:E,winningSide:d};if(d&&d===g.winningSide&&u&&!C)return{context:"winningSide must include directing matchUpStatus",error:_t,directingMatchUpStatus:C,matchUpStatus:u}}const{schedule:O}=t;if(O){const t=bw({disableNotice:!0,tournamentRecords:i,tournamentRecord:a,drawDefinition:c,matchUpId:p,schedule:O});if(t.error)return t}const F=g.matchUpType!==Qc&&!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}=ml(t),m=l.filter((({drawPositions:t,roundNumber:e})=>t?.includes(c)&&e>a));Xn({changeWinner:!0})&&console.log({existingWinnerSubsequentMatchUps:m}),m.forEach((n=>{n.drawPositions=n.drawPositions?.map((t=>t===c?d:t))||[],Oc({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}=tc({structure:t}),n=e?.find((({participantId:t})=>t===u)),r=e?.find((({participantId:t})=>t===p));n&&(n.participantId=p),r&&(r.participantId=u)})),Mg(t)}(t);const k=d&&!w||t.projectedWinningSide;Hl({method:e,activeDownstream:E,matchUpWinner:k,winningSide:d});const _=!E&&Uw(t)||k&&function(t){const{matchUp:e,winningSide:n,matchUpTieId:r,dualWinningSideChange:i}=t;return n===e.winningSide||r&&!i?_w(t):Nr({stack:"winningSideWithDownstreamDependencies",result:{error:ve},context:{winningSide:n,matchUp:e}})}(t)||C&&_w(t)||{error:An};return Nr({result:_,stack:e})}function _w(t){const{tournamentRecord:e,matchUp:n,event:r}=t,i=t.isCollectionMatchUp&&n.winningSide&&!t.winningSide&&!Gc({score:t.score}),a=t.isCollectionMatchUp?t.matchUpStatus||i&&Bo||Ro:t.matchUpStatus||Ro,o=t.removeScore||[Mo,Vo].includes(a)&&![ko,Do].includes(a),s=Mg({...t,matchUpStatus:a,removeWinningSide:i,removeScore:o});if(s.error)return s;if(t.isCollectionMatchUp){const{matchUpTieId:n,drawDefinition:i,matchUpsMap:a}=t,o=tI({matchUpId:n,tournamentRecord:e,drawDefinition:i,matchUpsMap:a,event:r});if(o.error)return o;Object.assign(s,{tieMatchUpResult:o})}return s}function xw({tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r}){if(!e)return{error:j};const{matchUp:i}=Dg({drawDefinition:e,matchUpId:n,event:r});return i?.matchUpType!==Jc?{error:Yt}:kw({enableAutoCalc:!0,tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r})}function Lw({drawDefinition:t,event:e,matchUpId:n}){if(!t)return{error:j};if(!n)return{error:qt};const{matchUp:r}=Dg({drawDefinition:t,event:e,matchUpId:n});return r?Ar({name:Va,element:r}):{error:Wt}}function Bw(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 Nr({result:{error:Ae},stack:s});const{matchUp:c}=Dg({drawDefinition:r,matchUpId:a,event:o});if(!c)return{error:Wt};if(!c.collectionId)return Nr({result:{error:Yt},stack:s});const u=Fu({drawDefinition:r}),{matchUps:d}=gl({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(vo).filter((t=>t!==e));return f?.includes(t)?Kv({newParticipantId:t,tieMatchUpId:a,existingParticipantId:e,substitution:!0,tournamentRecord:n,drawDefinition:r,event:o}):Nr({result:{error:Te},stack:s})}(t)}function Vw({drawDefinition:t,matchUpId:e,event:n}){if(!t)return{error:j};const{matchUp:r}=Dg({drawDefinition:t,matchUpId:e,event:n});return Cr({extension:{name:qa,value:!0},element:r})}function jw(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:x};if(!o)return{error:Vt};if(o&&!$g({matchUpFormat:o}))return Nr({result:{error:kt,matchUpFormat:o},stack:e});if(i&&!Array.isArray(i))return Nr({result:{error:Nn,scheduledDates:i},stack:e});if(c&&![Yd,Jd].includes(c))return Nr({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 Nr({result:{error:j},stack:e});if(l&&u&&r){const t=uS({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)&&ml({matchUpFilters:{matchUpStatuses:[Bo]},structure:s}).matchUps,u=i&&ml({matchUpFilters:{matchUpStatuses:[Bo]},contextFilters:{scheduledDates:i},afterRecoveryTimes:!1,inContext:!0,structure:s}).matchUps;if(c?.length){const r=u?u.map(wo):c.map(wo);for(const a of c)r.includes(a.matchUpId)&&(a.matchUpFormat=i?.length?o:void 0,Oc({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===Zd))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;kc({structureIds:S(e),drawDefinition:e})}else t.matchUpFormat!==o&&(t.matchUpFormat=o,h+=1);return h?{...E,modificationsCount:h}:{...E,info:Sn}}function Gw({inheritance:t=!0,tournamentRecord:e,drawDefinition:n,matchUpId:r,event:i}){if(!n)return{error:j};const a=Dg({drawDefinition:n,matchUpId:r})?.matchUp;if(!a?.tieMatchUps)return{error:Yt};const o=Dg({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&&Pf({drawDefinition:n,participantId:e,lineUp:[],tieFormat:t})}Oc({tournamentId:e?.tournamentId,context:"resetMatchUpLineUps",eventId:i?.eventId,drawDefinition:n,matchUp:a})})),{...E,modificationsCount:s}}function qw(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&&Wp(a),{bestOf:p,finalSetFormat:l,setFormat:m}=d??{},f=r||!(!e||!c||1===c),h=n?function({matchUpStatus:t}){const e={[xo]:"RET",[Vo]:"WO",[Co]:"DF/DF",[Oo]:"WO/WO",[Lo]:"SUS",[Do]:"ABN",[Eo]:"DEF",[Ao]:"DR"};return t&&e[t]||""}({matchUpStatus:i}):"",g=u?.sort($w).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 $w(t,e){return t.setNumber-e.setNumber}function Ww(t){const{matchUpFormat:e,matchUpStatus:n,winningSide:r,score:i}=t;if(!i)return{sets:[]};const a=i.sets||[];let o=qw({winnerFirst:!1,matchUpFormat:e,matchUpStatus:n,sets:a}),s=qw({winnerFirst:!1,reversed:!0,matchUpFormat:e,matchUpStatus:n,sets:a});const c=qw({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 Hw(t){const e=tu(t);if(!t.drawDefinition){const n=t.tournamentRecord??(t.tournamentId&&e[t.tournamentId]);t.tournamentRecord||(t.tournamentRecord=n);const r=kp({eventId:t.eventId,drawId:t.drawId,tournamentRecord:n});if(r.error)return r;r.drawDefinition&&(t.drawDefinition=r.drawDefinition),t.event=r.event}const{disableScoreValidation:n,policyDefinitions:r,tournamentRecord:i,disableAutoCalc:a,enableAutoCalc:o,drawDefinition:s,matchUpFormat:c,matchUpId:u,schedule:d,event:p,notes:l}=t;if(!s)return{error:at};if(!u)return{error:qt};const{policy:m}=ld({policyType:Ta,tournamentRecord:i,event:p}),f=void 0!==t.allowChangePropagation&&t.allowChangePropagation||void 0!==m?.allowChangePropagation&&m.allowChangePropagation||void 0,{outcome:h}=t;if(c){const t=uS({tournamentRecord:i,drawDefinition:s,matchUpFormat:c,matchUpId:u,event:p});if(t.error)return t}if(h?.score?.sets&&!h.score.scoreStringSide1){const{score:t}=Ww(h);h.score=t,h.score.sets=h.score.sets.filter((t=>t.side1Score||t.side2Score||t.side1TiebreakScore||t.side2TiebreakScore))}return kw({matchUpStatusCodes:h?.matchUpStatusCodes,matchUpStatus:h?.matchUpStatus,winningSide:h?.winningSide,allowChangePropagation:f,disableScoreValidation:n,score:h?.score,tournamentRecords:e,policyDefinitions:r,tournamentRecord:i,disableAutoCalc:a,enableAutoCalc:o,drawDefinition:s,matchUpFormat:c,matchUpId:u,schedule:d,event:p,notes:l})}function zw(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:x};const i=n.filter((e=>e.tournamentId===t));if(i.length){const t=Yw({outcomes:i,tournamentRecord:r});if(t.error)return t}}return{...E}}function Yw(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}=kp({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=Hw({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 Kw(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=Dg({drawDefinition:t,matchUpId:e});if(n.error)return n;r=n.matchUp}return"object"==typeof n&&n.score?.scoreStringSide1&&n.score?.scoreStringSide2?Cr({element:r,extension:{name:Va,value:n}}):{error:Nn}}(t)}function Jw(t){return function({drawDefinition:t,finishingOrder:e}){if(!t)return{error:j};const n="setOrderOfFinish";if(!Array.isArray(e))return Nr({info:wf("finishingOrder"),result:{error:Nn},stack:n});const{completedMatchUps:r,matchUpsMap:i}=Il({inContext:!0,drawDefinition:t}),a=r?.map(wo)??[],o=e.map(wo),{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 Nr({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 Nr({result:{error:l?Nn:xt},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 Nr({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 Nr({info:"Values not unique or greater than expected number of values",result:{error:Nn},stack:n});if(u.length){const e=hl({matchUpFilters:{matchUpIds:o},structureId:u[0],drawDefinition:t,matchUpsMap:i});if(e.error)return Nr({result:e,stack:n});e.completedMatchUps?.forEach((t=>t.orderOfFinish=f[t.matchUpId]))}return{...E}}(t)}function Qw({tournamentRecord:t,drawDefinition:e,matchUpId:n,lineUps:r,event:i}){if(!t)return{error:x};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=Dg({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!==Qc)return{error:Yt};if(!u?.length)return{error:Q};const p=Bp({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!==au)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===zc&&s||a.matchUpType===Kc&&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}=Xp({tournamentParticipants:a,participantIds:e});if(!n){const n=ly({participant:{participantType:su,participantRole:Cm,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=Dg({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 Oc({tournamentId:t?.tournamentId,context:"applyLineUps",drawDefinition:e,matchUp:m}),{...E}}function Zw(t){const e="resetTieFormat",{drawDefinition:n,event:r,uuids:i}=t,a=na(t,[{[bi]:!0,[ki]:!0}],e);if(a.error)return a;const o=Gv(t,[{[zi]:qi}]);if(o[Wi])return o;const s=t.tournamentRecord?.tournamentId,{matchUp:c,structure:u}=o?.matchUp??{};if(!c?.tieMatchUps)return Nr({result:{error:Yt},info:"Must be a TEAM matchUp",stack:e});if(!c.tieFormat)return{...E};const d=Bp({structure:u,drawDefinition:n,event:r})?.tieFormat;if(!d)return Nr({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===Bo?1:0)-(e.matchUpStatus===Bo?1:0))),m.push(...r.slice(0,e)),p.push(...r.slice(3).map(wo));else if(m.push(...r),r.length<e){const n=Qh({collectionDefinition:t,matchUpsLimit:e-r.length,matchUp:c,uuids:i});f.push(...n)}}for(const t of c?.tieMatchUps||[])t.collectionId&&!l.includes(t.collectionId)&&p.push(t.matchUpId);return f.length&&(m.push(...f),Ec({eventId:r?.eventId,matchUps:f,drawDefinition:n,tournamentId:s})),p.length&&Cc({matchUpIds:p,eventId:r?.eventId,drawDefinition:n,tournamentId:s}),c&&(c.tieMatchUps=m,c.tieFormatId=void 0,c.tieFormat=void 0,Oc({structureId:u?.structureId,eventId:r?.eventId,context:e,drawDefinition:n,tournamentId:s,matchUp:c})),{...E,newMatchUps:f,deletedMatchUpIds:p}}function Xw(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===Yc?"D":"S",s,r,o].join(";")})).join("|");return{tieFormatName:t&&n||"UNNAMED",matchUpFormats:e,tieFormatDesc:r}}function tT({considerations:t={},descendant:e,ancestor:n}){const r={},i={},{matchUpFormats:a,tieFormatDesc:o}=Xw(e),{matchUpFormats:s,tieFormatDesc:c}=Xw(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=eT(l),i.collectionsValue=eT(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 eT(t){const e=[],n=[];let r=0;return{totalValue:Object.keys(t).sort(pm).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 nT(t){const{tournamentRecord:e,drawDefinition:n,matchUpId:r,event:i}=t,a="resetScorecard";if(!n)return Nr({result:{error:j},stack:a});if(!r)return Nr({result:{error:qt},stack:a});if(!Ii(r))return Nr({result:{error:Nn,matchUpId:r},stack:a});const o=Fu({drawDefinition:n}),{matchUps:s}=gl({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!==Xd)return{error:Yt};const d=gu({inContextDrawMatchUps:s,drawDefinition:n,matchUpId:r}),p=u?.structureId,{structure:l}=Qs({drawDefinition:n,structureId:p});Object.assign(t,{inContextDrawMatchUps:s,inContextMatchUp:u,matchUpsMap:o,targetData:d,structure:l,matchUp:c});if(aU(t))return{error:ve};if(c.tieMatchUps?.length)for(const t of c.tieMatchUps){const o=kw({matchUpId:t.matchUpId,matchUpTieId:r,winningSide:void 0,removeScore:!0,tournamentRecord:e,drawDefinition:n,event:i});if(o.error)return Nr({result:o,stack:a})}const m=tI({event:t.event,removeScore:!0,tournamentRecord:e,drawDefinition:n,matchUpsMap:o,matchUpId:r});if(m.error)return Nr({result:m,stack:a});if(t.tiebreakReset&&!m.tieFormatRemoved){const t=Bp({drawDefinition:n,structure:l,event:i})?.tieFormat;if(c.tieFormat&&t){const{matchUpCountDifference:a,descendantDifferences:o,ancestorDifferences:s,valueDifference:u}=tT({descendant:c.tieFormat,ancestor:t});if(1===o.collectionIds.length&&!s.collectionIds.length&&!s.groupsCount&&1===a&&1===u){const t=Zw({tournamentRecord:e,drawDefinition:n,matchUpId:r,event:i});if(t.error)return t}}}return{...E}}var rT=Object.freeze({__proto__:null,applyLineUps:Qw,assignMatchUpSideParticipant:Bv,assignTieMatchUpParticipantId:Xv,bulkMatchUpStatusUpdate:zw,checkInParticipant:Hv,checkOutParticipant:Wv,disableTieAutoCalc:Vw,enableTieAutoCalc:xw,findMatchUp:Vv,removeDelegatedOutcome:Lw,removeMatchUpSideParticipant:nw,removeTieMatchUpParticipantId:ew,replaceTieMatchUpParticipantId:Kv,resetMatchUpLineUps:Gw,resetScorecard:nT,resetTieFormat:Zw,setDelegatedOutcome:Kw,setMatchUpFormat:jw,setMatchUpStatus:Hw,setOrderOfFinish:Jw,substituteParticipant:Bw,toggleParticipantCheckInState:zv,updateTieMatchUpScore:tI});function iT({tournamentRecords:t,extensionName:e}){if("object"!=typeof t||!Object.keys(t).length)return{error:_};const n=[];let r;for(const i of Object.values(t)){const{extension:t}=Fr({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}=Fr({name:e,element:t});i&&n.push({params:{eventId:r,extension:i},method:"addEventExtension"})}}return{methods:n}}function aT({tournamentRecords:t}){return iT({extensionName:no,tournamentRecords:t})}const oT="ADULT",sT="JUNIOR",cT="WHEELCHAIR",uT={[va]:{allowModificationWhenMatchUpsScheduled:{courts:!1,venues:!1},defaultTimes:{averageTimes:[{categoryNames:[],minutes:{default:90}}],recoveryTimes:[{minutes:{[Kc]:30,default:60}}]},defaultDailyLimits:{[zc]:2,[Kc]:2,total:3},matchUpAverageTimes:[{matchUpFormatCodes:[Zh],averageTimes:[{categoryNames:[],minutes:{default:90}},{categoryTypes:[cT],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:[oT,cT],minutes:{default:60,[Kc]:30}},{categoryTypes:[sT],minutes:{default:60,[Kc]: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:[oT,cT],minutes:{default:30}},{categoryTypes:[sT],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:[oT,sT],minutes:{default:30}},{categoryTypes:[cT],minutes:{default:15}}]},{matchUpFormatCodes:["SET1-S:TB10"],recoveryTimes:[{categoryNames:[],minutes:{default:15}}]}],matchUpDailyLimits:[]}};function dT({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)&&$g({matchUpFormat:n?.matchUpFormat}))return t.push(n.matchUpFormat),n})).filter(Boolean)}else{const{policy:e}=ld({policyType:Ta,tournamentRecord:t,event:r});if(e?.matchUpFormats)a=e?.matchUpFormats;else{const{extension:t}=Fr({name:no,element:r});let e,n;({matchUpAverageTimes:e,matchUpRecoveryTimes:n}=t?.value?t.value:uT[va]),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;if(!s)return{error:Tt};return br({eventMatchUpFormatTiming:a.map((({matchUpFormat:e,description:i})=>({matchUpFormat:e,description:i,...mp({tournamentRecord:t,matchUpFormat:e,categoryName:u,categoryType:n,eventType:o,event:r})}))),info:i})}function pT({tournamentRecords:t}){return iT({extensionName:eo,tournamentRecords:t})}const lT=({scheduleAttributes:t=["scheduledDate","scheduledTime"],schedule:e={}})=>!!Object.keys(e).filter((e=>t.includes(e))).filter((t=>e[t])).length;function mT({scheduleAttributes:t=["scheduledDate","scheduledTime"],matchUps:e=[]}){if(!Uu(e))return{error:Ht};if(!Array.isArray(t))return{error:Nn};const n=e.filter(Boolean).filter((({schedule:e})=>lT({schedule:e,scheduleAttributes:t}))).reduce(((t,e)=>{const{schedule:n}=e,r=ti(n?.scheduledDate),i=Xr(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)=>ii(Xr(t.schedule?.scheduledTime),Xr(e.schedule?.scheduledTime))))})),{...E,scheduledMatchUps:n}}function fT({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&&ti(e.scheduledDate)||e.scheduledTime&&ti(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&&Xr(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 hT({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 gT(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,...br({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}=kl({participantsProfile:o,policyDefinitions:c,useParticipantMap:u,tournamentRecord:d,contextProfile:f,inContext:I})),f&&!n&&(n=Cu({policyDefinitions:c,tournamentRecord:d,contextProfile:f,event:S}));const D=lm({event:S});return{...(S.drawDefinitions??[]).reduce(((t,u)=>{const g=Il({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 IT(t){if(!t?.tournamentRecord)return{error:x};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}=kl({participantsProfile:r,policyDefinitions:a,useParticipantMap:o,tournamentRecord:s,contextProfile:l,inContext:c});l&&!e&&(e=Cu({policyDefinitions:a,tournamentRecord:s,contextProfile:l}));const{appliedPolicies:y}=Tu({tournamentRecord:s}),v=d?.eventIds??[];return{...g.filter((t=>!v.includes(t.eventId))).map((t=>{const o=Fp({event:t}).flightProfile;return gT({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 UT({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:_};const u=Object.keys(n).map((u=>{const d=n[u];return IT({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 ST(t){if("object"!=typeof t?.tournamentRecords||!Object.keys(t?.tournamentRecords).length)return{error:_};const{courts:e,venues:n}=Py(t),r=by(t).schedulingProfile,{sortDateMatchUps:i=!0,courtCompletedMatchUps:a,alwaysReturnCompleted:o,activeTournamentId:s,tournamentRecords:c,withCourtGridRows:u,minCourtGridRows:d,usePublishState:p,status:l=Vd,sortCourtsData:m}=t,f=p?Nl({tournamentRecord:c[s??hr()],itemType:`${Bd}.${jd}`}).timeItem?.itemValue?.[l]:void 0,h=o?UT({...t,matchUpFilters:{...t.matchUpFilters,matchUpStatuses:[Ro]},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=lm({event:t}),i=r?.drawDetails;Ui(i)?(Object.assign(n,i),e.push(...Object.keys(i).filter((t=>mm({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(Ro)||t.matchUpFilters.excludeMatchUpStatuses.push(Ro):t.matchUpFilters.excludeMatchUpStatuses=[Ro]);const{completedMatchUps:U,upcomingMatchUps:S,pendingMatchUps:y,groupInfo:v}=UT({...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?fT({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?fT({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}=hT({minRowsCount:d,courtsData:P});D.courtPrefix=e,D.rows=t}return{...D,...E}}function yT({tournamentRecords:t,tournamentId:e}){if("object"!=typeof t||!Object.keys(t).length)return{error:_};let n;return Object.keys(t).filter((t=>!e||t===e)).forEach((e=>{const r=t[e],{matchUpDailyLimits:i}=function(t){const e=na(t,[{[bi]:!0}]);if(e.error)return e;const{tournamentRecord:n}=t,{policy:r}=ld({policyType:va,tournamentRecord:n}),{extension:i}=Fr({element:n,name:eo}),a=i?.value?.dailyLimits,o=r?.defaultDailyLimits;return{matchUpDailyLimits:a||o}}({tournamentRecord:r});n=i})),{matchUpDailyLimits:n}}function vT(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:x};if(c&&![zc,Kc].includes(c))return{error:Nn,info:{matchUpType:c}};if(e&&!Uu(e))return{error:Nn,context:{matchUps:e}};const h=nS[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]:[zc,Kc]},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&&Vl({inContext:!0,drawDefinition:i,contextFilters:v,contextProfile:y,participants:w})?.matchUps||!m&&d&&_l({inContext:!0,contextFilters:v,contextProfile:y,participants:w,event:f})?.matchUps||xl({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})=>![xo,Eo,Vo,Ao,Do].includes(r??"")&&Gc({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=wT({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!==zc?2*(S||0):S,b=S?T.map((({competitiveProfile:t,matchUpType:e,score:r,sides:i})=>{const a=wT({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={[Nu]:[],[Mu]:[],[Ru]:[]};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}),M=N&&[].concat(Object.values(N)).flat().length,R=M&&Object.assign({},...Object.keys(N).map((t=>({[t]:Math.round(1e4*N[t].length/M)/100})))),A=T.length-(b?.length||0);return{...E,relevantMatchUps:T,zoneDistribution:R,zoneData:b,accuracy:P,nonZone:A}}function wT({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}=TT({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}=TT({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 TT({singlesForDoubles:t,valueAccessor:e,matchUpType:n,participant:r,scaleName:i}){const a=t?zc: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 PT({collectionDefinitions:t=[],collectionGroups:e=[]}){let n=0;const{groupValueNumbers:r}=Yg({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,...E};return{valueGoal:Math.floor(n/2)+1,...E}}function DT({matchUps:t,matchUpId:e}){if(!Uu(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}}function bT(t){const{structureId:e,matchUpId:n,event:r}=t;let i=t.drawDefinition;const a=na(t,[{[bi]:!0},{_anyOf:{[Ei]:!1,[ki]:!1,[$i]:!1,[Hi]:!1}}]);if(a[Wi])return a;const o=Gv(t,[{[zi]:qi,[Wi]: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=Qs({drawDefinition:i,structureId:e});if(t.error)return t;c=t.structure}const u=c?.matchUpFormat,d=i?.matchUpFormat,p=r?.matchUpFormat;return{structureDefaultMatchUpFormat:u,eventDefaultMatchUpFormat:p,drawDefaultMatchUpFormat:d,matchUpFormat:s?.matchUp?.matchUpFormat||u||d||p}}function NT({profileBands:t,tournamentRecord:e,matchUps:n}){if(!Uu(n))return{error:Ht};const r=!t&&ld({policyType:ma,tournamentRecord:e}).policy,i=t||r?.profileBands||Eu[ma].profileBands,a=n.filter((({winningSide:t})=>t)),o=a.map(ud),s=pd(o).reduce(((t,e)=>((t,e)=>(t[cd(e,i)]+=1,t))(t,e)),{[Nu]:0,[Mu]:0,[Ru]:0,[Du]:0}),c=Object.keys(s).reduce(((t,e)=>(s[e]||0)+t),0),u=Object.keys(s).map((t=>({[t]:100*parseFloat((s[t]/c).toFixed(4))}))),d=a.filter((({matchUpStatus:t})=>t===bu)).length;return u.push({[bu]:100*parseFloat((d/c).toFixed(4))}),{competitiveBands:Object.assign({},...u),...E}}function MT({defaultRecoveryMinutes:t=0,defaultAverageMinutes:e,tournamentRecords:n,matchUpFormat:r,categoryName:i,categoryType:a,tournamentId:o,eventType:s,eventId:c}){if(!$g({matchUpFormat: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?kp({tournamentRecord:e,eventId:c})?.event:void 0;return u=mp({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 RT(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 br({structureId:u,roundSegment:n,tournamentId:i,roundNumber:a,eventId:s,drawId:c,id:d})}function AT({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=MT({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 ET(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||Ho.includes(e))).length||0,i=t.filter((({schedule:t,matchUpStatus:e})=>t?.scheduledDate&&t?.scheduledTime&&e!==No)).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 CT({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=vy({tournamentRecords:t,schedulingProfile:e});if(n.error)return n}if(!e&&t){const n=by({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=RT(t);return n.roundSegment?.segmentsCount&&(i[n.id]=n.roundSegment.segmentsCount),br({id:r?n.id:void 0,scheduleDate:e,...n})})))))).flat(1/0),segmentedRounds:i}}const{stageOrder:OT}=Ys;function FT(t,e){return t.eventName.localeCompare(e.eventName)||t.eventId.localeCompare(e.eventId)||(OT[t?.stage]||0)-(OT[e?.stage]||0)||e.matchUpsCount-t.matchUpsCount||`${t.stageSequence}-${t.roundNumber}-${t.minFinishingSum}`.localeCompare(`${e.stageSequence}-${e.roundNumber}-${e.minFinishingSum}`)}function kT({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:_};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)&&CT({tournamentRecords:i,schedulingProfile:a})||{},U=t&&Object.assign({},...I.map((t=>({[t.id]:t})))),S=r||i&&Ll({tournamentRecords:i,matchUpFilters:c})?.matchUps||[],y=[],v=S&&Object.values(S.reduce(((t,e)=>{const n=RT(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}=ET(a),f=AT({matchUps:t.matchUps,tournamentRecords:i,events:h,round:t});return br({...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}=ET(t.matchUps),p=AT({matchUps:t.matchUps,tournamentRecords:i,events:h,round:t});return br({...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=ti(t),n=d?r.id:RT(r).id;if(e&&U[n]&&ti(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(FT)||[];return{...E,rounds:v,excludedRounds:y}}function _T({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:n,isTiebreakSet:r,isDecidingSet:i,set:a}){if(!a)return{error:ae,info:"missing set"};e=e||n&&Wp(n);const o=i&&e.finalSetFormat||e?.setFormat||{},{side1Score:s,side2Score:c}=a,{setTo:u,tiebreakAt:d}=o,p=xT({set:a}),l=Math.abs(s-c),m=s>=u||c>=u,f=r||s>=u&&c>=u||d&&d<u&&(s===d||c===d),h=t||f&&(1===p&&a.side1TiebreakScore>a.side2TiebreakScore||2===p&&a.side2TiebreakScore>a.side1TiebreakScore),g=!f&&o.NoAD||f||r&&o.tiebreakFormat?.NoAD?1:2;return!(!(m&&(l>=g||f))&&!r||f&&!h)}function xT({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 LT(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}),M=u&&!w&&D||s&&w&&N,R=d&&!(s&&!w)&&!(u&&w)&&(!T||M),A=function({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:n,setObject:r}){if(!r)return;const i=xT({set:r});return _T({matchUpScoringFormat:t,set:r,isDecidingSet:e,isTiebreakSet:n})&&i||void 0}({isDecidingSet:a,isTiebreakSet:w,matchUpScoringFormat:n,setObject:e}),E={expectTiebreakSet:s,expectTimedSet:c,hasTiebreakCondition:y,isCompletedSet:T,isDecidingSet:a,isTiebreakSet:w,isValidSet:R,isValidSetNumber:d,isValidSetOutcome:M,leadingSide:v,setFormat:o,sideGameScores:p,sideGameScoresCount:f,sidePointScores:l,sidePointScoresCount:h,sideTiebreakScores:m,sideTiebreakScoresCount:g,winningSide:A};return void 0!==e?.winningSide&&(w?(E.isValidTiebreakSetOutcome=N,N||(E.tiebreakSetError=b)):(E.isValidStandardSetOutcome=D,D||(E.standardSetError=P))),E}function BT(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=Wp(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&<({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,M=m?.map((t=>LT({setObject:t,matchUpScoringFormat:s}).isValidSetOutcome)).reduce(((t,e)=>t&&e),!0),R=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=R[E],F=R[C],k=Math.max(...R),_=g(R)[k],{bestOf:x}=s??{},L=k===(x&&Math.ceil(x/2)||1)&&1===_&&R.indexOf(k)+1||void 0,B=O>F&&A===L;return{completedSetsHaveValidOutcomes:M,validMatchUpWinningSide:B,calculatedWinningSide:L,matchUpScoringFormat:s,validMatchUpOutcome:L&&M&&B,isLastSetWithValues:I,completedSetsCount:f,isCompletedMatchUp:c,isValidSideNumber:P,hasExistingValue:N,existingValue:b,isExistingSet:l,isActiveSet:T,...S}}function VT({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,...br({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;!t?.length&&s&&({participants:t,participantMap:l,groupInfo:D}=kl({participantsProfile:r,policyDefinitions:a,useParticipantMap:o,tournamentRecord:s,contextProfile:f,inContext:U})),y&&f&&!d&&(d=Cu({policyDefinitions:a,tournamentRecord:s,contextProfile:f,drawDefinition:h,event:y}));return{...Il({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}}var jT=Object.freeze({__proto__:null,allCompetitionMatchUps:Ll,allDrawMatchUps:Vl,allEventMatchUps:_l,allTournamentMatchUps:xl,analyzeMatchUp:BT,calculateWinCriteria:PT,checkMatchUpIsComplete:fl,competitionScheduleMatchUps:ST,drawMatchUps:VT,eventMatchUps:gT,getAllDrawMatchUps:gl,getCheckedInParticipantIds:qd,getCompetitionMatchUps:UT,getEventMatchUpFormatTiming:dT,getMatchUpCompetitiveProfile:md,getMatchUpContextIds:DT,getMatchUpDailyLimits:yT,getMatchUpDailyLimitsUpdate:pT,getMatchUpDependencies:jl,getMatchUpFormat:bT,getMatchUpFormatTiming:mp,getMatchUpFormatTimingUpdate:aT,getMatchUpScheduleDetails:_p,getMatchUpType:il,getMatchUpsStats:NT,getModifiedMatchUpFormatTiming:Vy,getPredictiveAccuracy:vT,getRoundMatchUps:Su,getRounds:kT,isValidMatchUpFormat:$g,matchUpActions:CU,participantScheduledMatchUps:mT,tallyParticipantResults:vg,tournamentMatchUps:IT,validMatchUp:Iu,validMatchUps:Uu}),GT=Object.freeze({__proto__:null,allCompetitionMatchUps:Ll,allDrawMatchUps:Vl,allEventMatchUps:_l,allTournamentMatchUps:xl,analyzeMatchUp:BT,applyLineUps:Qw,assignMatchUpSideParticipant:Bv,assignTieMatchUpParticipantId:Xv,bulkMatchUpStatusUpdate:zw,calculateWinCriteria:PT,checkInParticipant:Hv,checkMatchUpIsComplete:fl,checkOutParticipant:Wv,competitionScheduleMatchUps:ST,disableTieAutoCalc:Vw,drawMatchUps:VT,enableTieAutoCalc:xw,eventMatchUps:gT,findMatchUp:Vv,getAllDrawMatchUps:gl,getCheckedInParticipantIds:qd,getCompetitionMatchUps:UT,getEventMatchUpFormatTiming:dT,getMatchUpCompetitiveProfile:md,getMatchUpContextIds:DT,getMatchUpDailyLimits:yT,getMatchUpDailyLimitsUpdate:pT,getMatchUpDependencies:jl,getMatchUpFormat:bT,getMatchUpFormatTiming:mp,getMatchUpFormatTimingUpdate:aT,getMatchUpScheduleDetails:_p,getMatchUpType:il,getMatchUpsStats:NT,getModifiedMatchUpFormatTiming:Vy,getPredictiveAccuracy:vT,getRoundMatchUps:Su,getRounds:kT,isValidMatchUpFormat:$g,matchUpActions:CU,mutate:rT,participantScheduledMatchUps:mT,query:jT,removeDelegatedOutcome:Lw,removeMatchUpSideParticipant:nw,removeTieMatchUpParticipantId:ew,replaceTieMatchUpParticipantId:Kv,resetMatchUpLineUps:Gw,resetScorecard:nT,resetTieFormat:Zw,setDelegatedOutcome:Kw,setMatchUpFormat:jw,setMatchUpStatus:Hw,setOrderOfFinish:Jw,substituteParticipant:Bw,tallyParticipantResults:vg,toggleParticipantCheckInState:zv,tournamentMatchUps:IT,updateTieMatchUpScore:tI,validMatchUp:Iu,validMatchUps:Uu});const qT=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),o&&!a?(c>i&&(s=i),s=c<i?i:i-1):s=c+1<i&&i||a&&a<i&&c===a&&i||!a&&c+2||i+1;return[e?c:s,e?s:c]},$T=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 WT({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&&$T({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 HT(t){const{matchUpFormat:e,matchUpStatus:n,winningSide:r,scoreString:i}=t;if(!i)return{outcome:{...Tg,winningSide:r,matchUpStatus:n}};if(r&&![1,2,void 0].includes(r))return{error:Nn,winningSide:r};const a=i&&WT({scoreString:i}),o={},s=qw({sets:a,matchUpFormat:e}),c=qw({sets:a,reversed:!0,matchUpFormat:e});return 2===r?(o.scoreStringSide1=c,o.scoreStringSide2=s):(o.scoreStringSide1=s,o.scoreStringSide2=c),o.sets=WT({scoreString:o.scoreStringSide1}),br({outcome:{matchUpStatus:n,winningSide:r,score:o}})}function zT({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 YT({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:e,timeAfterRecovery:n,matchUp:r}){const{individualParticipantIds:i}=Xc(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 KT({individualParticipantProfiles:t,participantId:e}){t[e]||(t[e]={typeChangeTimeAfterRecovery:void 0,timeAfterRecovery:void 0,priorMatchUpType:void 0,potentialRecovery:{},potentialCounted:{},potentialBookings:{},bookings:[],counters:{}})}function JT({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,typeChangeRecoveryMinutes:r,averageMatchUpMinutes:i=0,matchUpNotBeforeTimes:a,matchUpDependencies:o,recoveryMinutes:s=0,scheduleTime:c,matchUp:u}){const d=Xr(u?.schedule?.endTime),p=d?ci(d,n(s)):ci(c,n(i)+n(s)),l=r&&(d?ci(Xr(d),r):ci(c,n(i)+n(r))),m=o?.[u.matchUpId]?.participantIds||[],f=(u.roundPosition&&t[u.matchUpId]||[]).flat();m.forEach((t=>{KT({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}))})),YT({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:a,timeAfterRecovery:p,matchUp:u})}function QT({matchUpScheduleTimes:t,matchUpDependencies:e,scheduleTime:n,matchUpId:r,details:i}){let a;const o=i.minutesMap?.[r]?.recoveryMinutes,s=i.minutesMap?.[r]?.averageMinutes,c=ci(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||Qr(r)<Qr(e.scheduleTime)?i:e}),{});e.scheduleTime&&Qr(c)>Qr(e.scheduleTime)&&(a=e)}return{scheduledDependent:a}}const ZT="DO_NOT_SCHEDULE",XT={DO_NOT_SCHEDULE:ZT};function tP({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===Kc&&(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===ZT&&pi(a,t.date))),u=[],d=o?.matchUpId,p=oi(Xr(i),ti(a)),l=Xr(ui(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 eP({scheduleCompletedMatchUps:t,containedStructureIds:e,tournamentRecords:n,periodLength:i=30,matchUps:a,rounds:o}){if("object"!=typeof n)return{error:_};if(!Array.isArray(o))return{error:ae,info:wf("rounds")};const s={},c=[];o.sort(((t,e)=>(t.sortOrder??0)-(e.sortOrder??0))),e=e??Object.assign({},...Object.values(n).map((t=>jc({tournamentRecord:t}).containedStructures))),a||({matchUps:a}=Ll({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?al({tournamentIds:[o.tournamentId],roundNumbers:[o.roundNumber],matchUpIds:o.matchUpIds,eventIds:[o.eventId],drawIds:[o.drawId],processContext:!0,structureIds:h,matchUps:a}).sort(Bl):[];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=kp({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}=MT({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||!Ho.includes(e.matchUpStatus))&&e.matchUpStatus!==No)).map(wo);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 nP({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 rP({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUp:n,value:r}){const{matchUpType:i}=n,{individualParticipantIds:a}=Xc(n),o=(t[n.matchUpId]||[]).filter((t=>!b(t,a))).flat();[...a,...o].forEach((t=>{if(KT({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[rp]?a[rp]+=r:r>0&&(a[rp]=r),o.includes(t)&&(e[t].potentialCounted[n.drawId]=!0)}}))}function iP({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===No;return n&&l.push({tournamentId:t.tournamentId,matchUpId:t.matchUpId}),!n&&lT({schedule:e})&&(!u||t.schedule.scheduledDate===u)})),n=i.map(wo));const m=Array.isArray(c)?c.includes(u):c,f=m?[]:p.filter((({matchUpId:t})=>n.includes(t)));for(const n of f){rP({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;JT({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 aP({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=[No,Eo,Ro,Do,xo,Vo,Oo,Co].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],YT({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:r,matchUp:n}),e}),{matchUpMap:{}});return{matchUpsToSchedule:u,matchUpMap:d}}function oP({defaultRecoveryMinutes:t=0,averageMatchUpMinutes:e=90,dateScheduledMatchUps:n,tournamentRecords:r,venueIds:i=[],periodLength:a,scheduleDate:o,matchUps:s}){if("object"!=typeof r)return{error:_};if(!Uu(s)&&!Array.isArray(n))return{error:Ht};a=a??Ev({recoveryMinutes:t,averageMatchUpMinutes:e});const c=Object.assign({},...Object.values(r).map((t=>(t.events??[]).map((e=>{const{scheduleTiming:n}=zd({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 lT({schedule:e})&&(!o||t.schedule.scheduledDate===o)})));const d=n?.filter((t=>(!i.length||i.includes(t.schedule.venueId))&&t.matchUpStatus!==No)),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}=fp({timingDetails:s,eventType:o}),{courtId:l,venueId:m}=e,f=Xr(e.scheduledTime),h=ci(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 sP({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:_};s=s??Ev({recoveryMinutes:n,averageMatchUpMinutes:r});const{courts:m,venues:f}=Py({dates:[c],ignoreDisabled:!0,tournamentRecords:a}),h=m?.filter((t=>!d||d.includes(t.venueId)))??[];u=u??Ov({courts:h,scheduleDate:c,startTime:!0}),l=l??Ov({courts:h,scheduleDate:c,endTime:!0});const{bookings:g,dateScheduledMatchUps:I}=oP({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}=Fv(U),y=1===d?.length&&d[0]||1===f?.length&&f[0].venueId||void 0,v=I?.map(wi("matchUpId"));return{dateScheduledMatchUpIds:v,dateScheduledMatchUps:I,scheduleTimes:S,venueId:y}}function cP({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}=eP({scheduleCompletedMatchUps:n,containedStructureIds:r,tournamentRecords:c,periodLength:u,matchUps:l,rounds:f});U.push(...T??[]);const{groupedRounds:D}=nP({scheduledRoundsDetails:v,greatestAverageMinutes:w,garmanSinglePass:!0});let b,N,M=[];p&&({scheduleTimes:M,dateScheduledMatchUpIds:b,dateScheduledMatchUps:N}=sP({averageMatchUpMinutes:D[0]?.averageMinutes,scheduleDate:ti(d),venueIds:[S.venueId],clearScheduleDates:s,tournamentRecords:c,periodLength:u,matchUps:l}));const R=iP({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}=R);const{byeScheduledMatchUpDetails:A,clearDate:E}=R;A?.length&&I.push(...A);const{matchUpsToSchedule:C,matchUpMap:O}=aP({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:M,groupedRounds:D,venueCourts:F,minutesMap:P,matchUpMap:O},s||g.push(...b)}return{allDateScheduledByeMatchUpDetails:I,allDateScheduledMatchUpIds:g,venueScheduledRoundDetails:h,allDateMatchUpIds:U}}function uP({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=>{KT({individualParticipantProfiles:t,participantId:e});const r=t[e];if(!r.timeAfterRecovery)return!0;const o=Xr(a?.schedule?.endTime),s=o?ci(o,n(u)):ci(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=Qr(t.scheduleTime),r=Qr(t.timeAfterRecovery),i=Qr(e.scheduleTime),a=Qr(e.timeAfterRecovery),o=n>i&&n<a,s=i>n&&i<r,c=r>i&&r<a,u=a>n&&a<r;return br({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?si(oi(p),oi(i),!1):0;return{enoughTime:d&&l>=0}}function dP({individualParticipantProfiles:t,matchUpPotentialParticipantIds:e,matchUpDailyLimits:n={},matchUp:r}){const{matchUpId:i,matchUpType:a}=r,{enteredIndividualParticipantIds:o}=Xc(r),s=(r.roundPosition&&e[i]||[]).flat(),c=m(o.concat(...s));c.forEach((e=>{KT({individualParticipantProfiles:t,participantId:e})}));return{participantIdsAtLimit:c.filter((e=>{const r=t[e];if(r)return[a,rp].find((t=>{const e=r.counters?.[t]||0,i=n[t]||0;return e&&i&&e>=i}))})),relevantParticipantIds:c}}function pP({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:x};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=jl({tournamentRecords:o,tournamentRecord:s});i=t.matchUpDependencies,p=t.matchUps}p||(p=xl({tournamentRecord:s})?.matchUps??[]);const f=p.reduce(((n,r)=>{const{matchUpId:i,drawId:a,matchUpStatus:o}=r;return!e&&o===No||!t&&Ho.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}=AI({tournamentRecord:s,drawId:t});if(!e)continue;const g=f[t].filter((t=>u?.includes(t)??h?.includes(t))),I=Vl({inContext:!1,drawDefinition:e}).matchUps;for(const t of g){const u=bw({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 lP(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 pP(t);const d=na(t,[{[Pi]:!0},{[Xi]:{matchUpContextIds:!1,matchUpDetails:!1},[Qi]:Nn,[Zi]:Ki}]);if(d.error)return d;if((!c||i)&&!u)return{error:ae,info:"schedule is required"};const p=[];let l=0;const{matchUpDependencies:m}=jl({tournamentRecords:o});for(const t of Object.values(o)){const{tournamentId:d}=t,f=i?.filter((t=>t.tournamentId===d)).map(wo),h=c?.filter((t=>t?.tournamentId===d));if(f?.length||h?.length){const i=pP({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 mP({autoSchedulingAudit:t,tournamentRecords:e}){cr({topic:sc,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:ky,itemValue:i};for(const t of Object.values(e))Ih({tournamentRecord:t,timeItem:a})}function fP(t){const{tournamentRecords:e,requestType:n}=t,r=na(t,[{[Pi]:!0}]);if(r.error)return r;const i={};for(const t of Object.values(e)){const{extension:e}=Fr({element:t,name:Za}),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 hP({averageMinutes:t,startTime:e,endTime:n,court:r,date:i}){if(!Array.isArray(r.dateAvailability))return{error:ae,stack:"getEarliestCourtTime"};const a=Ov({scheduleDate:i,courts:[r],startTime:!0}),o=Ov({scheduleDate:i,courts:[r],endTime:!0});e=e||a,n=n||o;const s=Nv({court:r,date:i}),{timeSlots:c}=Mv({courtDate:s}),u=oi(e),d=oi(n),p=c?.reduce(((e,n)=>{const r=oi(n.startTime),i=oi(n.endTime);if(r>d||i<u)return e;const a=u>r?u:r;if(si(a,i)>=t){const t=Xr(a.toISOString());(!e||t<e)&&(e=t)}return e}),void 0);return{earliestCourtTime:p,courtStartTime:a,courtEndTime:o}}function gP(t){const{scheduleAttributes:e=["scheduledDate","scheduledTime"],ignoreMatchUpStatuses:n=Ho,scheduledDates:r,venueIds:i}=t,a=tu(t),o=Ui(a)?Object.values(a).map((({tournamentId:t})=>t)).filter(Boolean):[];if(!o?.length)return{error:_};let s=0;for(const t of o){const o=IP({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 IP({scheduleAttributes:t=["scheduledDate","scheduledTime"],ignoreMatchUpStatuses:e=Ho,tournamentRecord:n,scheduledDates:r,venueIds:i=[]}){if("object"!=typeof n)return{error:x};if(!Array.isArray(e)||!Array.isArray(i))return{error:Nn};i.length&&t.push("venueId");const a=(xl({matchUpFilters:{scheduledDates:r},tournamentRecord:n}).matchUps??[]).filter((n=>n.matchUpStatus&&!e.includes(n.matchUpStatus)&&lT({schedule:n.schedule,scheduleAttributes:t})&&(!i?.length||i.includes(n.schedule.venueId)))).map(wo),o=xl({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&&![Ud,Sd,Id,vd,Td].includes(t?.itemType))),s+=1);return{...E,clearedScheduleCount:s}}function UP(t){const{checkPotentialRequestConflicts:e=!0,scheduleCompletedMatchUps:n,clearScheduleDates:r,scheduleDates:i=[],tournamentRecords:a,periodLength:o,useGarman:s,dryRun:c,pro:u}=t,d=na(t,[{[Pi]:!0},{[Ji]:t=>!t||Array.isArray(t)&&t.every(Gr),[Ai]:!1,[Zi]:Ki}]);if(d.error)return d;const p=by({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=>jc({tournamentRecord:t}).containedStructures))),g=i.map((t=>{if(Gr(t))return ti(t)})).filter(Boolean),I=f.map((t=>t.scheduleDate)).map((t=>Gr(t)&&ti(t))).filter((t=>t&&(!i.length||g.includes(t))));if(!I.length)return{error:se};if(r&&!c){gP({tournamentRecords:a,scheduledDates:Array.isArray(r)?r:[]})}const U=Py({ignoreDisabled:!1,tournamentRecords:a}).courts,{matchUps:S}=Ll({matchUpFilters:{matchUpTypes:[zc,Kc]},afterRecoveryTimes:!0,nextMatchUps:!0,tournamentRecords:a}),{matchUpDependencies:y}=jl({includeParticipantDependencies:!0,tournamentRecords:a,matchUps:S}),{matchUpDailyLimits:v}=yT({tournamentRecords:a}),{personRequests:w}=fP({requestType:ZT,tournamentRecords:a}),T={schedulingProfileModifications:l,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:n,schedulingProfileIssues:m,dateSchedulingProfiles:f.filter((t=>{const e=ti(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=ti(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[rp]?n[rp]+=1:n[rp]=1}))};g[r]={},I[r]={},v[r]=[],w[r]=[],T[r]=[],P[r]=[];const N={};m?.forEach((t=>{t.schedule?.scheduledDate&&pi(r,ti(t.schedule.scheduledDate))&&YT({matchUpPotentialParticipantIds:p,matchUpNotBeforeTimes:N,matchUp:t})}));const{allDateScheduledByeMatchUpDetails:M,allDateScheduledMatchUpIds:R,venueScheduledRoundDetails:A,allDateMatchUpIds:E}=cP({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})=>R.includes(t))),{bookings:O}=oP({dateScheduledMatchUps:C,tournamentRecords:u,scheduleDate:r,periodLength:d}),{virtualCourts:F}=Av({scheduleDate:r,periodLength:d,bookings:O,courts:f}),k=F?.reduce(((t,e)=>{const{earliestCourtTime:n,courtEndTime:i}=hP({date:r,averageMinutes:0,court:e});return(!t.startTime||oi(n)<oi(t.startTime))&&(t.startTime=n),(!t.endTime||oi(i)>oi(t.endTime))&&(t.endTime=i),t}),{});let _=k.startTime;const x=({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}=dP({matchUpPotentialParticipantIds:p,individualParticipantProfiles:D,matchUpDailyLimits:s,matchUp:i});if(h.length){w[r].includes(m)||w[r].push(m);continue}const{dependenciesScheduled:T,remainingDependencies:M}=zT({matchUpScheduleTimes:y,matchUpDependencies:o,allDateMatchUpIds:E,matchUp:i});if(!T){I[r][m]||(I[r][m]=[]),I[r][m].push({remainingDependencies:M});continue}const R=[],A=F?.reduce(((t,a)=>{if(c.includes(a.courtId))return t;const{earliestCourtTime:s}=hP({averageMinutes:n.greatestAverageMinutes,startTime:_,date:r,court:a});if(t.scheduleTime&&Qr(s)>=Qr(t.scheduleTime))return t;const{scheduledDependent:u}=QT({matchUpScheduleTimes:y,matchUpDependencies:o,scheduleTime:s,matchUpId:m,details:n});if(u)return t;const{enoughTime:d}=uP({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}=tP({potentials:e,averageMatchUpMinutes:h,requestConflicts:P,personRequests:l,scheduleTime:s,scheduleDate:r,matchUp:i});if(I?.length)return R.push(...I),!1;b(v,f);const U=n.minutesMap?.[m]?.recoveryMinutes;return JT({matchUpPotentialParticipantIds:p,individualParticipantProfiles:D,matchUpNotBeforeTimes:N,averageMatchUpMinutes:h,matchUpDependencies:o,recoveryMinutes:U,scheduleTime:s,matchUp:i}),(!t.scheduleTime||Qr(s)<Qr(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=ci(s,e);x({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 R?.length&&(U[r]||(U[r]=[]),U[r].push(...R))}c.length!==n.courtsCount&&a.length!==n.courtsCount&&n.matchUpsToSchedule.length||(u=!0),n.matchUpsToSchedule.length&&a<n.courtsCount&&(oi(_)<oi(k.endTime)?_=ci(_,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}=AI({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(di).join(":"),s=`${ti(r)}T${o}`;h||(Tw({drawDefinition:a,scheduledTime:s,matchUpId:t}),ww({courtDayDate:r,tournamentRecords:u,tournamentRecord:n,drawDefinition:a,matchUpId:t,courtId:i})),v[r].push(t)}}))}))})),T[r]=A[t].matchUpsToSchedule.map(wo)}!h&&M?.length&&lP({matchUpDetails:M,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(const e of t.venues)for(const t of e.rounds){const e=(t.matchUps??[]).map((({matchUpId:t})=>t)),n=e?.filter((t=>v[r].includes(t)));t.canScheduledMatchUpIds=n;let i=Math.round((n?.length||0)/t.matchUpsCount*1e4)/100;(i===1/0||isNaN(i))&&(i=void 0),t.possibleToSchedulePct=i,t.matchUpsCount===n?.length&&(t.possibleToSchedule=!0)}}const D=(i??[]).map((({scheduleDate:t})=>t)),b={timeStamp:Date.now(),overLimitMatchUpIds:w,scheduledMatchUpIds:v,schedulingProfile:p,noTimeMatchUpIds:T,requestConflicts:P,scheduledDates:D};return mP({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=ti(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[rp]?n[rp]+=1:n[rp]=1}))};U[r]={},S[r]={},g[r]={},I[r]={},w[r]=[],T[r]=[],P[r]=[],D[r]=[];const M={};m.forEach((t=>{t.schedule?.scheduledDate&&pi(r,ti(t.schedule.scheduledDate))&&YT({matchUpPotentialParticipantIds:d,matchUpNotBeforeTimes:M,matchUp:t})}));const{allDateScheduledByeMatchUpDetails:R,venueScheduledRoundDetails:A,allDateMatchUpIds:E}=cP({matchUpPotentialParticipantIds:d,individualParticipantProfiles:b,scheduleCompletedMatchUps:n,containedStructureIds:a,matchUpNotBeforeTimes:M,matchUpScheduleTimes:v,matchUpDependencies:o,clearScheduleDates:c,tournamentRecords:u,useGarman:!0,periodLength:l,scheduleDate:r,matchUps:m,courts:f,venues:i}),C=10;let O,F=0;const k=10;for(;!O;){for(const{venueId:t}of i){let n=0;const i=A[t];for(;i.courtsCount&&i.scheduleTimes?.length&&i.matchUpsToSchedule?.length&&n<=i.courtsCount;){const{scheduleTime:a,attempts:c=0}=i.scheduleTimes.shift(),u=i.matchUpsToSchedule.find((t=>{const{matchUpId:n,matchUpType:c}=t,{participantIdsAtLimit:u,relevantParticipantIds:l}=dP({matchUpPotentialParticipantIds:d,individualParticipantProfiles:b,matchUpDailyLimits:s,matchUp:t});if(u.length)return T[r].includes(n)||T[r].push(n),!1;const{scheduledDependent:m}=QT({matchUpScheduleTimes:v,matchUpDependencies:o,scheduleTime:a,matchUpId:n,details:i});if(m)return!1;const{dependenciesScheduled:f,remainingDependencies:h}=zT({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}=uP({individualParticipantProfiles:b,matchUpNotBeforeTimes:M,matchUpDependencies:o,scheduleTime:a,details:i,matchUp:t});if(!g)return U[r][n]||(U[r][n]=[]),U[r][n].push({scheduleTime:a}),!1;const I=i.greatestAverageMinutes,{conflicts:w}=tP({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 JT({matchUpPotentialParticipantIds:d,individualParticipantProfiles:b,matchUpNotBeforeTimes:M,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}=AI({tournamentRecord:i,drawId:a});o&&e[n][a].forEach((({matchUpId:e})=>{const n=v[e];if(n){const a=n.split(":").map(di).join(":"),s=`${ti(r)}T${a}`;h?w[r].push(e):(Tw({drawDefinition:o,scheduledTime:s,matchUpId:e}).success&&w[r].push(e),t&&vw({tournamentRecord:i,drawDefinition:o,matchUpId:e,venueId:t}))}}))}))})),P[r]=A[t].matchUpsToSchedule.map(wo),g[r][t]=A[t].scheduleTimes.sort(((t,e)=>Qr(t.scheduleTime)-Qr(e.scheduleTime)))}!h&&R?.length&&lP({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=>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 mP({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 SP(t){const e=t||{};return e.tournamentId||(e.tournamentId=wp()),(!e.startDate||Kr(e.startDate)||kr.test(e.startDate))&&(!e.endDate||Kr(e.endDate)||kr.test(e.endDate))?(e.extensions&&(e.extensions=e.extensions.filter(Er)),{...e}):{error:pe}}function yP({addParticipants:t=!0,participantAttribute:e,tournamentRecord:n,personAttribute:r,teamNames:i,accessor:a,uuids:o}){if(!n)return{error:x};const s={},c=(n.participants??[]).filter((({participantType:t,participantRole:e})=>t===au&&e===Cm));let u=0;for(const t of c){const n=a&&hi({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()??wp(),individualParticipantIds:[],participantRole:Cm,participantType:cu};const t={value:r??e,name:za};Cr({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!==cu)return;if(t.participantRole!==Cm)return;const{extension:e}=Fr({name:za,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?(cr({payload:{tournamentId:n.tournamentId,participants:m},topic:ic}),{...E,participantsAdded:l}):m.length?{...E,newParticipants:m}:{error:Ie}}var vP=[{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"}],wP=["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 TP({count:t=1,participantsCount:e=32}={}){const n=f(wP),r=n.slice(0,t);return{cities:w(0,e).map((e=>e<Math.min(t,n.length)?r[e]:v(r)))}}function PP({count:t=1,participantsCount:e=32}={}){const n=f(vP),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 DP({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)))}}function bP(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 NP={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 MP(t){const{count:e=100,sex:n}=t||{};if(!e||n&&![cl,pl].includes(n))return{personData:[],error:Nn};const r=Math.ceil(1.3*e),{lastNames:i,firstFemale:a,firstMale:o}=NP,s=vl.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=mi(i,!1,!0);return w(0,i.length).map((()=>y(t)))})),l=w(0,u).flatMap((()=>{const t=mi(a,!1,!0);return w(0,a.length).map((()=>y(t)))})),m=w(0,d).flatMap((()=>{const t=mi(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([cl,pl]),r=e===cl?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 RP(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?.[cl]||u===cl&&e||0,p=o?.[pl]||u===pl&&e||0;e=Math.max(e,d+p);const l=e-(d+p),m=[...d&&MP({count:d,sex:cl}).personData||[],...p&&MP({count:p,sex:pl}).personData||[],...l&&MP({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&&![cl,pl].includes(t.sex))&&(!(t.nationalityCode&&("string"!=typeof t.nationalityCode||t.nationalityCode.length>3||!vl.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===cl?(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([cl,pl]),o=v(a),s={firstName:v(e===cl?t:r),lastName:v(e===cl?n:i),sex:e,nationalityCode:o};I.push(s)}))}const{ageMinDate:U,ageMaxDate:S}=_g({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 $r(new Date(r.setDate(e)),n)}(o,s);return Object.assign(br({extensions:r||[{name:"regionCode",value:e+1}],birthDate:c,isMock:a}),t)}));return{persons:b.length&&b||I[0],nationalityCodes:g}}var AP=["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 EP({nameRoot:t="TEAM",count:e=1}={}){const n=f(AP).slice(0,e);return n.length<e&&w(0,e-n.length).forEach((e=>n.push(`${t} ${e+1}`))),{names:n}}function CP({idPrefix:t,participantType:e,index:n,uuids:r}){return t?`${t}-${e===au?"I":"P"}-${n}`:r?.pop()||wp()}function OP(t){let{rankingRange:e,scaledParticipantsCount:n}=t;const{ratingsParameters:r=nS,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:M,scaleAllParticipants:R}=t,A=h===su||T===Yc,C=h===cu||T===cu;!e||Array.isArray(e)&&e.every((t=>s(t)))&&2===e.length||(e=void 0),n=R?m:n;e=e||[1,n&&n>1e3?n:1e3],e[1]+=1;const O=m*(A?2:C?8:1),F=RP({count:O,personExtensions:S,consideredDate:a,gendersCount:v,personData:P,category:o,sex:D});if(F.error)return F;const{nationalityCodes:k,persons:_}=F;let x=[],L=[],B=[],V=[];if("object"==typeof o){const{categoryName:t,ageCategoryCode:i,ratingType:a}=o;if((t||i)&&!a){const[t,r]=e||[];if(L=f(w(t,r)).slice(0,n||d(20,30)),[su,cu].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={},n=Object.keys(t||{});for(const r of n){const n=t[r];if("object"==typeof n&&n.generator){const{range:t}=n,[i,a]=t.slice().sort();e[r]=d(i,a)}else e[r]=n}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));B=y(),[su,cu].includes(h)&&(V=y())}}const j=vl.filter((t=>"IOC"===u&&t.ioc||t.iso));const{postalCodesProfile:G,postalCodesCount:q,statesProfile:$,citiesProfile:W,citiesCount:H,statesCount:z}=y||{},Y=t=>Object.keys(t).map((t=>w(0,$[t]).map((()=>t)))).flat(),K={cities:W&&Y(W)||y?.cities||TP({count:H||O,participantsCount:O}).cities,states:$&&Y($)||y?.states||PP({count:z||O,participantsCount:O}).states,postalCodes:G&&Y(G)||y?.postalCodes||DP({count:q||O,participantsCount:O}).postalCodes},J=function(t){const e=Math.ceil(O/t);return i&&e>i?Math.ceil(O/i):t}(c),Q=J?f(j).slice(0,c):p?j.filter((t=>p.includes(t.iso))):j,Z=f(w(0,Math.ceil(O/(J||1))).map((()=>Q)).flat(1/0)),X=EP({count:m}).names;return{participants:w(0,m).map((t=>{const e=A?2:C?8:1,n=w(0,e).map((n=>function(t){const e=_[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=k?.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=bP({...K,participantIndex:t,nationalityCode:y}),w=br({participantId:CP({participantType:au,index:t,idPrefix:I,uuids:U}),extensions:r,timeItems:i,participantRole:Cm,participantType:au,participantName:h,person:{addresses:[v],personId:p||g?.length&&g[t]||wp(),standardFamilyName:f,standardGivenName:m,nationalityCode:y,extensions:a,birthDate:Gr(c)?c:void 0,sex:l}});if(M&&y){const t=vl.find((({iso:t})=>t===y));t?.ioc&&(w.person.iocNationalityCode=t.ioc),t?.label&&(w.person.countryName=t.label)}if(N&&y){const t=vl.find((({iso:t})=>t===y));t?.iso2&&(w.person.iso2NationalityCode=t.iso2),t?.label&&(w.person.countryName=t.label)}if(o){const e=L[t],n=x[t];FP({scaleValue:e,eventType:Kd,scaleType:aa,participant:w,category:o}),FP({scaleValue:n,eventType:Qd,scaleType:aa,participant:w,category:o});const r=B[t],i=V[t];FP({scaleValue:r,eventType:Kd,scaleType:oa,participant:w,category:o}),FP({scaleValue:i,eventType:Qd,scaleType:oa,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?su:cu,s={participantId:CP({participantType:a,idPrefix:I,index:t,uuids:U}),participantRole:Cm,participantName:A?i:X[t],individualParticipantIds:r,participantType:a};return b&&(s.individualParticipants=n),A||C?[s,...n]:n})).flat(),...E}}function FP({scaleValue:t,participant:e,eventType:n,scaleType:r,category:i}){const a=i.categoryName||i.ratingType||i.ageCategoryCode,o={itemValue:t,itemType:[sa,r,n,a].join(".")};a&&t&&(e.timeItems||(e.timeItems=[]),e.timeItems.push(o))}function kP({alternatesCount:t=0,tieFormatName:e,tieFormat:n,drawSize:r}){let i=0,a=0,o=0,s=0;const c={},u={[cl]:0,[pl]:0,[ul]:0,[dl]:0,[sl]:0};n="object"==typeof n?n:ZS({namedFormat:e}),n?.collectionDefinitions?.filter(Boolean).forEach((t=>{const{category:e,collectionId:n,matchUpType:r,matchUpCount:d,gender:p}=t;if([cl,pl].includes(p)){const t=d*(r===Kc?2:1);u[p]<t&&(u[p]=t)}else p===ul&&(u[cl]<d&&(u[cl]=d),u[pl]<d&&(u[pl]=d));if(e){const t=JSON.stringify(e);c[t]=e}if(n||(t.collectionId=wp()),r===Kc){const t=d;s+=d,i=Math.max(i,t)}if(r===zc){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 _P({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=au}=t||{};const a=r||0,o={[pl]:0,[ul]:0,[dl]:0,[cl]:0,[sl]: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===Jd,g=i===Zd,I=Boolean(e||f===Qo||l||m);if(g){d=Math.max(d,r+t),a="object"==typeof a?a:ZS({namedFormat:n});const{teamSize:e,maxDoublesDraw:i,maxSinglesDraw:p,genders:l}=kP({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=su),(r||a)<m&&(r=m),r&&s&&[su,Zd].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=OP({uuids:a,...t,consideredDate:i,participantsCount:o,participantType:s,gendersCount:d}).participants;let m=0,f=my({tournamentRecord:e,participants:l});if(f.error)return f;if(m+=f.addedCount,p){const t=yP({tournamentRecord:e,...p});if(t.error)return t}const h=l.filter((({participantType:t})=>t===au)).map(vo),g=t?.idPrefix?`${cu}-${t.idPrefix}`:void 0;return f=my({participants:w(0,c).map((t=>{const e=h.slice(t*u,(t+1)*u),n=CP({index:t,participantType:s,idPrefix:g,uuids:a});return{participantName:`Team ${t+1}`,participantRole:Cm,individualParticipantIds:e,participantType:cu,participantId:n}})),tournamentRecord:e}),f.error?f:(m+=f.addedCount,{addedCount:m,...E})}const xP=()=>({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 LP(t){return parseInt(t)}function BP({startTime:t="",endTime:e=""}={}){if(!(t&&e&&Lr.test(t)&&Lr.test(e)))return!1;const[n,r]=t.split(":").map(LP),[i,a]=e.split(":").map(LP);return!(i<n)&&!(n===i&&a<r)}function VP(t,e){const[n,r]=t.startTime.split(":").map(LP),[i,a]=e.startTime.split(":").map(LP);return n<i?-1:n>i?1:r<a?-1:r>a?1:0}function jP({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&&!xr.test(t))return{error:pe,dateAvailability:{date:t},info:"Dates must be formated => YYYY-MM-DD"};if(!Lr.test(r))return{error:le,dateAvailability:{startTime:r},info:e};if(!Lr.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(!BP({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(!Lr.test(n))return{error:le,booking:{startTime:n},info:e};if(!Lr.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(!BP({startTime:n,endTime:r}))return{error:le,dateAvailability:{startTime:n,endTime:r},info:"endTime must be after startTime"}}}}return{valid:!0}}function GP({tournamentRecord:t,disableNotice:e,venueId:n,courtId:r,court:i}){const{venue:a}=Dp({tournamentRecord:t,venueId:n});if(!a)return{error:rn};a.courts||(a.courts=[]);const o={...xP(),venueId:n,courtId:r};o.courtId||(o.courtId=wp());if(a.courts.some((t=>t.courtId===o.courtId)))return{error:en};{const r=(i?.dateAvailability||[]).map((t=>({...t,date:ti(t.date),startTime:Xr(t.startTime),endTime:Xr(t.endTime),bookings:t.bookings?.map((({startTime:t,endTime:e,bookingType:n})=>({startTime:Xr(t),endTime:Xr(e),bookingType:n})))}))),s=Object.keys(o);for(const t of s)if(i?.[t])if("dateAvailability"===t){const t=jP({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||cr({payload:{venue:a,tournamentId:t.tournamentId},topic:yc,key:a.venueId}),{...E,court:mi(o),venueId:n}}}function qP(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}=Dp({tournamentRecord:e,venueId:n});if(r){const n=$P({...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 $P({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=Dp({tournamentRecord:r,venueId:l});if(f.error)return f;const{venue:h}=f;if(!s(o)||!i)return{error:Xe};const g=w(0,o=o??i.length).map((r=>{const o=a?.[r],s=o?m.map((t=>({date:$r(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 GP({disableNotice:!0,tournamentRecord:r,courtId:n,venueId:l,court:t})})).map((t=>t.court)).filter(Boolean);return g.length!==o?Nr({info:"not all courts could be generated",result:{error:Nn}}):(h&&cr({payload:{venue:h,tournamentId:r.tournamentId},topic:yc,key:h.venueId}),{...E,courts:mi(g)})}function WP({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()??wp(),dateAvailability:u,startTime:d="07:00",endTime:p="19:00",courtTimings:l,courtsCount:m,courtNames:f,venueName:h,idPrefix:g,courtIds:I}=s,U=Tp({tournamentRecord:t,venue:{venueName:h||`Venue ${o+1}`,venueAbbreviation:e,venueId:c}});if(U.error)return U;a.push(c);const S=zr(r,i),y=!Array.isArray(u)&&[{startTime:d,endTime:p}].concat(S.map((t=>({date:$r(t),startTime:d,endTime:p})))),v=qP({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 HP({drawProfiles:t,category:e,gender:n}){const r={},i=t?.reduce(((t,i)=>{const{qualifyingPositions:a=0,participantsCount:o=0,uniqueParticipants:s,stage:c=Jo,drawSize:u=0}=i||{};Object.keys(t).includes(c)||(t[c]=0);const d=(o||u)-a;return s||n||e||c===Qo?(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 zP({allUniqueParticipantIds:t,stageParticipantsCount:e,eventParticipantType:n,targetParticipants:r}){const i=e[Jo]||0,a=e[Qo]||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 YP(t){const{removePriorValues:e,tournamentRecord:n,participantId:r,scaleItem:i}=t;let a,o;if(!JP({scaleItem:i}))return{error:In};if(r&&Array.isArray(n.participants)&&(o=n.participants.find((t=>t.participantId===r)),o)){const t=QP({removePriorValues:e,participant:o,scaleItem:i});if(t.error)return t;a=!t.valueChanged;const{topics:r}=mr();r.includes(gc)&&cr({topic:gc,payload:{tournamentId:n.tournamentId,participants:[o]}})}return a&&{...E,info:Cn,existingValue:i?.scaleValue}||o&&{...E,newValue:i?.scaleValue}||{error:Ee}}function KP(t){const{scaleItemsWithParticipantIds:e=[],removePriorValues:n,tournamentRecord:r,auditData:i,context:a}=t;if(!r)return{error:x};if(!r.participants)return{error:Re};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(!JP({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=>{QP({participant:t,scaleItem:e,removePriorValues:n}),c.push(t),o++}))}));const u=o?void 0:Sn,{topics:d}=mr();if(d.includes(gc)&&o&&cr({topic:gc,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:ac,itemValue:n};if(i&&(a.itemSubTypes=i),e||t){const{drawDefinition:n,event:i}=kp({tournamentRecord:r,eventId:t,drawId:e});e&&vh({drawDefinition:n,timeItem:a}),t&&Uh({event:i,timeItem:a})}else Ih({tournamentRecord:r,timeItem:a})}}return i&&d.includes(sc)&&cr({topic:sc,payload:i}),br({...E,modificationsApplied:o,info:u})}function JP({scaleItem:t}){const e=t&&Object.keys(t),n=["scaleType","eventType","scaleName"];return!!(n.filter((t=>e?.includes(t))).length===n.length)}function QP({removePriorValues:t,participant:e,scaleItem:n}){if(!e)return{error:Me};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}=cm({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=[sa,r,i,o].join("."),c=br({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}}const ZP={[Vo]:2,[Oo]:1,[Co]:1,[xo]:1,[Eo]:4};function XP(t){let{defaultWithScorePercent:e=2,winningSide:n}=t;const{matchUpStatusProfile:r=ZP,matchUpFormat:i=Zh,pointsPerMinute:a=1,sideWeight:o=4}=t;if(!$g({matchUpFormat: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(Ko).includes(t)&&t!==Ro));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,Ro])[1],l={sets:[],scoreStringSide1:"",side2ScoreString:""};if([Vo,Eo].includes(p)){n=n||d(1,2);const t={score:l,winningSide:n,matchUpStatus:p};if(!(p===Eo&&d(1,100)>100-e))return{outcome:t}}else if([Oo,Co].includes(p))return{outcome:{score:l,matchUpStatus:p}};const m=Wp(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=[xo,Eo,ko,Lo].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}=tD({incomplete:v===t,matchUpStatus:p,pointsPerMinute:a,setFormat:e&&g||h,setNumber:t,weightedRange:S});if(I.push(n),r){T=o;break}if(BT({matchUp:{score:{sets:I},matchUpFormat:i}}).calculatedWinningSide)break}const P=BT({matchUp:{score:{sets:I},matchUpFormat:i}}),D=T?n||T:P.calculatedWinningSide,{score:b}=Ww({score:{sets:I},winningSide:D,matchUpStatus:p});return{outcome:{score:b,winningSide:D,matchUpStatus:p}}}function tD({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}),Ho.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),Ho.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&&qT({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=LT({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=$T({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 eD(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(Ks);let d=0;const{matchUps:p,matchUpsMap:l}=gl({contextFilters:{stages:[Jo,Qo]},matchUpFilters:{matchUpTypes:[Qc],roundNumbers:[1]},inContext:!0,drawDefinition:o});if(p?.length){const t=s?.category?.ageCategoryCode||s?.category?.categoryName;if(t){const e=Dv({singlesOnly:!0,tournamentRecord:i,drawDefinition:o,scaleAccessor:{scaleName:t,sortOrder:wv,scaleType:aa},event:s});if(e.error)return e;const{lineUps:n,participantsToAdd:r}=e;my({tournamentRecord:i,participants:r});Cr({element:o,extension:{name:Ya,value:n}})}else{const t=p[0]?.structureId,{positionAssignments:e}=tc({drawDefinition:o,structureId:t});if(e?.length){const{participants:t}=ym({participantFilters:{participantTypes:[Qc]},tournamentRecord:i}),n=n=>{const r=n.tieMatchUps.filter((({matchUpType:t})=>t===zc)),a=n.tieMatchUps.filter((({matchUpType:t})=>t===Kc));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&&Xv({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=>{Xv({teamParticipantId:u.participantId,participantId:t,tournamentRecord:i,drawDefinition:o,tieMatchUpId:a,event:s})}))}}))}))};p.forEach(n)}}}const m="string"==typeof n&&n,f=m&&Ro;for(const t of u){if(d>=a)break;const{matchUps:n}=ml({matchUpFilters:{matchUpTypes:[Kc,zc]},afterRecoveryTimes:!1,tournamentRecord:i,inContext:!0,drawDefinition:o,matchUpsMap:l,structure:t,event:s}),u=n.filter((({winningSide:t})=>!t)).sort(Bl).map(wo);for(const n of u){if(!isNaN(a)&&d>=a)break;const{matchUps:u}=ml({matchUpFilters:{matchUpTypes:[Kc,zc]},afterRecoveryTimes:!1,tournamentRecord:i,inContext:!0,drawDefinition:o,matchUpsMap:l,structure:t,event:s}),p=u.find((t=>t.matchUpId===n)),h=[Oo,Co].includes(p.matchUpStatus);if(p?.readyToScore&&!h){const t=rD({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 nD(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===No)return;const{matchUpId:p}=a||{},{outcome:l}=HT({matchUpFormat:s,matchUpStatus:o,scoreString:c,winningSide:u});return e&&(l.matchUpStatusCodes=e),Hw({tournamentRecord:r,policyDefinitions:n,drawDefinition:i,matchUpFormat:s,matchUpId:p,outcome:l,event:d})}function rD(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 nD(t);const{matchUpId:p}=s||{},{outcome:l}=XP({matchUpStatusProfile:e,matchUpFormat:o,winningSide:u});return Hw({policyDefinitions:r,tournamentRecord:n,drawDefinition:i,matchUpFormat:o,matchUpId:p,outcome:l,event:d})}function iD({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:n,tournamentRecord:r,drawProfiles:i,event:a}){const o=Fp({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(wi(Ri)).map(wi(Ri)),f=l||s;if(r&&S&&S<=p.length){w(1,S+1).forEach(((t,e)=>{const n={scaleValue:t,scaleName:f,scaleType:ca,eventType:c,scaleDate:d},i=p[e];YP({tournamentRecord:r,participantId:i,scaleItem:n})}))}if(m?.includes(o))break;let y=iy({...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(Er).forEach((t=>Cr({element:v,extension:t}))),y=ev({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=oI({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=eD({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===Vs){const o=v.structures?.find((t=>t.stage===Jo));if(!o)return{error:Ut};let c=ph({structureId:o.structureId,tournamentRecord:r,drawDefinition:v,event:a});if(c.error)return{error:c.error,drawIds:[]};if(c=eD({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 aD(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===Yd&&au||p===Jd&&su||p,m=n[Jo]||0,f=n[Qo]||0,h=a.drawProfiles?.length?m+f:a.participantsProfile?.participantsCount??0,g=[cl,pl].includes(d)?d:void 0,I=e?.idPrefix?`E-${o}-${e?.idPrefix}`:void 0,{participants:U}=OP({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=my({tournamentRecord:i,participants:U});if(S.error)return S;const y=U?.filter((({participantType:t})=>t===l)),v=U?.map(vo);return{uniqueDrawParticipants:y,uniqueParticipantIds:v}}function oD({autoEntryPositions:t,tournamentRecord:e,drawParticipants:n,drawProfile:r,event:i}){const{drawType:a=Ts,qualifyingPositions:o=0,stage:s=Jo,drawSize:c=0,drawName:u,drawId:d}=r,p=c-o,l=n.slice(0,p).map(vo);if(l.length){const n=Em({participantIds:l,autoEntryPositions:t,entryStage:s,tournamentRecord:e,event:i});if(n.error)return n}const m=uv({drawName:u||a,qualifyingPositions:o,drawEntries:l.map((t=>({entryStatus:Vu,entryStage:s,participantId:t}))),drawId:d,event:i,stage:s});return m.error?m:{...E}}function sD({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=Jo,drawSize:l=0}=u,m=l-i,f=d||o||a||p===Qo,h=f?t.slice(c,c+m):n[p||Jo]||[];f&&(c+=m);const g=oD({autoEntryPositions:e,drawParticipants:h,tournamentRecord:r,drawProfile:u,event:s});if(g.error)return g}return{...E}}function cD(t){const{allUniqueParticipantIds:e,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:i,autoEntryPositions:a,hydrateCollections:o,randomWinningSide:s,ratingsParameters:c,tournamentRecord:u,eventProfile:d,eventIndex:p,publish:l,isMock:m,uuids:f}=t;let h=d.gender,g=d.eventName;const{eventType:I=Yd,policyDefinitions:U,drawProfiles:S=[],eventExtensions:y,surfaceCategory:v,tieFormatName:w,processCodes:T,discipline:P,eventLevel:D,timeItems:b,ballType:N,category:M}=d,R=d.eventId||wp(),A=d.tieFormat||(I===Zd?ZS({namedFormat:w,event:{eventId:R,category:M,gender:h},hydrateCollections:o,isMock:m}):void 0),E=u.participants;for(const t of S)!h&&t.gender&&(h=t?.gender);const{stageParticipantsCount:C,uniqueParticipantsCount:O,uniqueParticipantStages:F}=HP({drawProfiles:S,category:M,gender:h}),k=I===Yd&&au||I===Jd&&su||I,{uniqueDrawParticipants:_=[],uniqueParticipantIds:x=[]}=F?aD({event:{eventType:I,category:M,gender:h},uniqueParticipantsCount:O,participantsProfile:r,ratingsParameters:c,tournamentRecord:u,eventProfile:d,eventIndex:p,uuids:f}):{};let{eventAttributes:L}=d;"object"!=typeof L&&(L={});const B=M?.categoryName||M?.ageCategoryCode||M?.ratingType;g=g||B||"Generated Event";const V={...L,surfaceCategory:v,processCodes:T,discipline:P,eventLevel:D,eventName:g,eventType:I,tieFormat:A,ballType:N,category:M,eventId:R,gender:h};if(y?.length&&Array.isArray(y)){const t=y.filter(Er);t?.length&&Object.assign(V,{extensions:t})}if(Array.isArray(b)&&b.forEach((t=>Uh({event:q,timeItem:t}))),"object"==typeof U)for(const t of Object.keys(U))sI({policyDefinitions:{[t]:U[t]},event:V});let j;V.category&&(V.category.categoryName=B);const G=pv({suppressNotifications:!1,internalUse:!0,tournamentRecord:u,event:V});if(G.error)return G;const q=G?.event,{stageParticipants:$}=zP({allUniqueParticipantIds:e,stageParticipantsCount:C,eventParticipantType:k,targetParticipants:E});if(S?.length){const t=sD({uniqueDrawParticipants:_,autoEntryPositions:a,stageParticipants:$,tournamentRecord:u,drawProfiles:S,category:M,gender:h,event:q});if(t.error)return t;const e=iD({matchUpStatusProfile:n,completeAllMatchUps:i,randomWinningSide:s,tournamentRecord:u,drawProfiles:S,event:q});if(e.error)return e;j=e.drawIds}else if(d?.participantsProfile?.participantsCount){const t=_.map(vo);if(t.length){const e=Em({participantIds:t,autoEntryPositions:a,tournamentRecord:u,entryStage:Jo,event:q});if(e.error)return e}}return l&&Oy({tournamentRecord:u,event:q}),{drawIds:j,eventId:R,uniqueParticipantIds:x}}function uD({tournamentRecords:t}){if(!Ui(t))return{error:_};const e=Object.keys(t??{}).reduce(((e,n)=>{const r=t[n],{tournamentInfo:{startDate:i,endDate:a}}=Ay({tournamentRecord:r}),o=i&&new Date(ti(i));(!e.startDate||o&&o<e.startDate)&&(e.startDate=o);const s=a&&new Date(ti(a));return(!e.endDate||s&&s>e.endDate)&&(e.endDate=s),e}),{startDate:void 0,endDate:void 0}),n=e.startDate&&ti(e.startDate.toISOString()),r=e.endDate&&ti(e.endDate.toISOString());return n&&r?{startDate:n,endDate:r}:{error:oe}}function dD({tournamentRecords:t,scheduleDate:e,venueId:n,round:r}){if(!Gr(e))return{error:pe};const{extension:i}=Fr({name:ro,tournamentRecords:t,discover:!0}),a=i?.value||[];let o=a.find((t=>pi(e,t.scheduleDate)));if(!o){const{startDate:n,endDate:r}=uD({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=>Ui(t[e])?u(t[e]):t[e])).flat().join("|");if(s.rounds.find((t=>u(t)===u(r))))return Nr({result:{error:gt},stack:"addSchedulingProfileRound"});s.rounds.push(r);const d=Ny({tournamentRecords:t,schedulingProfile:a});return d.error?d:{...E}}function pD(t){const e=na(t,[{drawProfile:!0,_ofType:Yi}]);if(e.error)return e;const{allUniqueParticipantIds:n=[],participantsProfile:r={},matchUpStatusProfile:i,completeAllMatchUps:o,autoEntryPositions:s,hydrateCollections:c,randomWinningSide:u,ratingsParameters:d,tournamentRecord:p,isMock:l=!0,drawProfile:m,startDate:f,drawIndex:h,uuids:g}=t,I=mi(m,!1,!0),{excessParticipantAlternates:U=!0,matchUpFormat:S=Zh,drawType:y=Ts,tournamentAlternates:v=0,alternatesCount:T=0,qualifyingPositions:D,qualifyingProfiles:b,generate:N=!0,eventExtensions:M,drawExtensions:R,completionGoal:A,tieFormatName:C,seedsCount:O,timeItems:F,drawName:k,category:_,idPrefix:x,publish:L,gender:B,stage:V}=I,j=I.drawSize||(I.ignoreDefaults?void 0:32),G=I.eventId||wp(),$=m.eventType||m.matchUpType||Yd,W=$===Jd?su:au,H="object"==typeof m.tieFormat&&m.tieFormat||$===cu&&ZS({event:{eventId:G,category:_,gender:B},namedFormat:C,hydrateCollections:c,isMock:l})||void 0,z=_?.categoryName||_?.ageCategoryCode||_?.ratingType,Y=m.eventName||z||`Generated ${$}`;let K=p?.participants||[];const J=(b?.map((t=>t.structureProfiles||[])).flat().reduce(((t,e)=>t+(!e.participantsCount||e.participantsCount>e.drawSize?e.drawSize:e.participantsCount||0)),0)||0)*(W===su?2:1),Q=(!m.participantsCount||m.participantsCount>j?j:m.participantsCount)||0,Z={eventName:Y,eventType:$,tieFormat:H,category:_,eventId:G,gender:B};Array.isArray(F)&&F.forEach((t=>Uh({event:Z,timeItem:t})));let{eventAttributes:X}=m;if("object"!=typeof X&&(X={}),Object.assign(Z,X),M?.length&&Array.isArray(M)){const t=M.filter(Er);t?.length&&Object.assign(Z,{extensions:t})}const tt=[];if(J||m.uniqueParticipants||!p||B||_){const t=(Q||0)+T+J;let e=t;const n={[cl]:0,[pl]:0};let i,a;$===cu&&(({teamSize:i,genders:a}=kP({alternatesCount:T,tieFormatName:C,tieFormat:H,drawSize:j})),Object.keys(a).forEach((t=>{[cl,pl].includes(t)&&a[t]&&(n[t]=j*a[t])})),e=i*((j||0)+J));const o=r?.idPrefix?`D-${h}-${r?.idPrefix}`:void 0,s=OP({...r,scaledParticipantsCount:m.scaledParticipantsCount||r.scaledParticipantsCount,participantsCount:e,consideredDate:p?.startDate,sex:B||r?.sex,rankingRange:m.rankingRange,uuids:m.uuids||g,ratingsParameters:d,participantType:W,gendersCount:n,idPrefix:o,category:_}).participants;if(Z.category&&(Z.category.categoryName=z),p){const t=my({participants:s,tournamentRecord:p});if(t.error)return t}if(s.forEach((({participantId:t})=>tt.push(t))),K=s,$===cu){const e=a[cl]?s.filter((({participantType:t,person:e})=>t===au&&e?.sex===cl)).map(vo):[],n=a[pl]?s.filter((({participantType:t,person:e})=>t===au&&e?.sex===pl)).map(vo):[],r=s.filter((({participantType:t})=>t===au)).map(vo).filter((t=>!e.includes(t)&&!n.includes(t))),o=i-(a[cl]+a[pl]);let c=0,u=0,d=0;const l=w(0,t).map((t=>{const i=n.slice(c,c+a[pl]),s=e.slice(u,u+a[cl]),p=r.slice(d,d+o);return c+=a[pl],u+=a[cl],d+=o,{individualParticipantIds:[...i,...s,...p],participantOtherName:`TM${t+1}`,participantName:`Team ${t+1}`,participantRole:Cm,participantType:cu,participantId:wp()}})),m=my({participants:l,tournamentRecord:p});if(!m.success)return m;K=l}}const et=t=>{const{participantType:e}=t;return $===Yd&&e===au||($===Jd&&e===su||$===cu&&e===cu)},nt=t=>!m.gender||(t.person?.sex===m.gender||t.individualParticipantIds?.some((t=>{const e=K.find((e=>e.participantId===t));return e&&nt(e)}))),rt=K.filter(et).filter(nt).filter((({participantId:t})=>!n.includes(t))),it=rt.slice(0,Q).map((t=>t.participantId));if(l&&it?.length){const t=Em({autoEntryPositions:s,entryStage:V,tournamentRecord:p,participantIds:it,event:Z});if(t.error)return t}const at=J?rt.slice(Q,Q+J).map((t=>t.participantId)):0;if(l&&at?.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 b.sort(r)){e=i.roundTarget||e;let r,o=1;for(const c of i.structureProfiles.sort(n)){const n=(c.drawSize||a(c.participantsCount))-(r||0),i=at.slice(t,t+n),u=Em({entryStage:Qo,entryStageSequence:o,autoEntryPositions:s,tournamentRecord:p,participantIds:i,roundTarget:e,event:Z});if(u.error)return u;r=c.qualifyingPositions,t+=n,o+=1}e+=1}}const ot=U&&p?.participants?.filter((({participantId:t})=>!it.includes(t))).filter(et).filter(nt).slice(0,T||j-Q||v).map((t=>t.participantId));if(l&&ot?.length){const t=Em({participantIds:ot,autoEntryPositions:!1,entryStatus:Lu,tournamentRecord:p,event:Z});if(t.error)return t.error}const st=z||Y;if(p&&O&&O<=it.length){w(1,O+1).forEach(((t,e)=>{const n={scaleName:st,scaleDate:f,scaleType:Ld,scaleValue:t,eventType:$},r=it[e];YP({tournamentRecord:p,participantId:r,scaleItem:n})}))}const ct=iy({...mi(m,!1,!0),tournamentRecord:p,seedingScaleName:st,matchUpFormat:S,eventId:G,isMock:l,event:Z});if(ct.error)return ct;if(!ct.drawDefinition)return{error:q};const{drawDefinition:ut}=ct,dt=ut.drawId;if(Array.isArray(R)&&R.filter(Er).forEach((t=>Cr({element:ut,extension:t}))),N){if(ev({drawDefinition:ut,event:Z,suppressNotifications:!0}),m.withPlayoffs){const t=ut.structures?.[0].structureId,e=oI({...m.withPlayoffs,tournamentRecord:p,drawDefinition:ut,structureId:t,idPrefix:x,isMock:l,event:Z});if(e?.error)return e}const t=!1===m.automated;if(l&&!t){const t=t=>{const e=eD({completeAllMatchUps:t.completeAllMatchUps,completionGoal:t.completionGoal,matchUpStatusProfile:i,randomWinningSide:u,tournamentRecord:p,drawDefinition:ut,matchUpFormat:S,event:Z});if(e.error)return e;const n=e.completedCount;if(y===Vs){const t=ut.structures?.find((t=>t.stage===Jo));if(!t)return{error:Ut};ph({structureId:t.structureId,tournamentRecord:p,drawDefinition:ut,event:Z});const e=eD({completionGoal:A?A?A-(n??0):void 0:void 0,matchUpStatusProfile:i,completeAllMatchUps:o,randomWinningSide:u,tournamentRecord:p,drawDefinition:ut,matchUpFormat:S,event:Z});if(e.error)return e}};if(A&&t({completionGoal:A}),m.outcomes){const{matchUps:t}=Vl({inContext:!0,drawDefinition:ut,event:Z});for(const e of m.outcomes){const{matchUpStatus:n=Ro,matchUpStatusCodes:r,stageSequence:i=1,matchUpIndex:a=0,structureOrder:o,matchUpFormat:s,drawPositions:c,roundPosition:u,stage:d=Jo,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=>!(d&&t.stage!==d||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=nD({matchUpStatusCodes:r,tournamentRecord:p,drawDefinition:ut,targetMatchUp:U,matchUpFormat:s,matchUpStatus:n,scoreString:f,winningSide:m});if(S?.error)return S}}o&&t({completeAllMatchUps:o})}L&&Oy({tournamentRecord:p,event:Z})}else{const t=uv({drawEntries:ut.entries,drawName:k||y,qualifyingPositions:D,drawId:dt,event:Z,stage:V});if(t.error)return t}return{...E,event:br(Z),uniqueParticipantIds:tt,targetParticipants:K,drawDefinition:ut,eventId:G,drawId:dt}}const lD=["Mock Tournament","CourtHive Challenge","Racket Rally","Generated Tournament","Factory Follies","Open Competition"];function mD(t){let{tournamentAttributes:e,startDate:n,endDate:r}=t;const{tournamentName:i=y(lD),ratingsParameters:a=nS,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&&!Gr(n)||r&&!Gr(r))return{error:pe};if(S&&!Array.isArray(S))return{error:Nn};if(!n){const t=new Date;n=$r(r??t),r=$r(t.setDate(t.getDate()+7))}if(!r){const t=new Date(n);r=$r(t.setDate(t.getDate()+7))}"object"!=typeof e&&(e={});const D=SP({...e,tournamentName:i,isMock:!0,startDate:n,endDate:r});if(s?.length&&Array.isArray(s)){const t=s.filter((t=>Er({extension:t})));t?.length&&Object.assign(D,{extensions:t,isMock:!0})}if("object"==typeof h)for(const t of Object.keys(h))sI({policyDefinitions:{[t]:h[t]},tournamentRecord:D});const b=_P({participantsProfile:d,tournamentRecord:D,eventProfiles:S,drawProfiles:w,startDate:n,uuids:T});if(!b.success)return b;const N=[],M=[],R=[];if(Array.isArray(w)){let t=0;for(const e of w){let r=pD({allUniqueParticipantIds:N,matchUpStatusProfile:c,completeAllMatchUps:u,autoEntryPositions:p,hydrateCollections:l,participantsProfile:d,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=pv({suppressNotifications:!1,internalUse:!0,tournamentRecord:D,event:s}),r.error)return r;i&&R.push(i),M.push(o),m?.length&&N.push(...m),t+=1}}if(S){let t=0;for(const e of S){const r=cD({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&&R.push(...o),M.push(i),s?.length&&N.push(...s),t+=1}}const A=v?.length?WP({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=jc({tournamentRecord:e}).containedStructures,r=xl({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=dD({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=UP({scheduleCompletedMatchUps:o,tournamentRecords:{[t]:D},periodLength:I})}}return sr(),br({...E,tournamentRecord:D,scheduledRounds:C,schedulerResult:O,eventIds:M,venueIds:A,drawIds:R})}var fD=Object.freeze({__proto__:null,generateEventWithDraw:pD,generateOutcome:XP,generateOutcomeFromScoreString:HT,generateParticipants:OP,generateTournamentRecord:mD});function hD({keepExtensions:t=[],anonymizeParticipantNames:e=!0,tournamentRecord:n,tournamentName:r,personIds:i=[],tournamentId:a}){if(!n)return{error:x};const o=Array.isArray(t)?co.concat(...t):co,s=e=>Array.isArray(t)?e?.extensions?.filter((t=>o.includes(t.name))):e?.extensions,c={};n.extensions=s(n);const u=a||wp();c[n.tournamentId]=u,n.tournamentId=u,n.createdAt=(new Date).toISOString(),n.tournamentName=r||`Anonymized: ${$r(new Date)}`,delete n.parentOrganisation;for(const t of n.participants||[]){const e=wp();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=wp();c[t.venueId]=e,d+=1}let p=1;for(const t of n.events||[]){t.extensions=s(t);const e=wp();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=wp();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=wp();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}=Fr({name:Ha,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||$r(new Date),m=(n.participants||[]).filter((({participantType:t})=>t===au)),f=m.reduce(((t,e)=>{const n=e.person?.sex;return[cl,pl].includes(n)?t[n]+=1:t[dl]+=1,t}),{[cl]:0,[pl]:0,[dl]:0}),h=Object.assign({},...Object.keys(f).map((t=>({[t]:RP({category:{ageCategoryCode:"O18"},count:f[t],addressProps:{citiesCount:10},personExtensions:[],consideredDate:l,sex:t})?.persons||[]})))),g={[cl]:0,[pl]:0,[dl]: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}=TP({count:y||I,participantsCount:I}),{states:T}=PP({count:v||I,participantsCount:I}),{postalCodes:P}=DP({count:S||I,participantsCount:I}),D={cities:w,states:T,postalCodes:P};m.forEach(((t,n)=>{const r=t?.person,a=r?.sex||dl,o=ti(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=bP({...D,participantIndex:n,nationalityCode:d.nationalityCode});d.addresses=[t]}d.personId=i?.[n]||wp(),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===su)).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===cu)),N=EP({count:b.length}).names;b.forEach(((t,e)=>{t.participantName=N[e]}));const M=(n.participants||[]).filter((({participantType:t})=>t===ou)),R=EP({count:M.length,nameRoot:"Group"}).names;M.forEach(((t,e)=>{t.participantName=R[e]}));const{extension:A}=Fr({element:n,name:ro});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}=Fr({element:n,name:Za});return Array.isArray(C?.value)&&C?.value.forEach((t=>{t.personId=c[t.personId]})),{...E}}function gD(t){const{ratingsParameters:e=nS,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:x};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=_P({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===Yd&&au||p===Jd&&su||p;if(l){const{stageParticipantsCount:m,uniqueParticipantsCount:I,uniqueParticipantStages:S}=HP({drawProfiles:l,category:d,gender:t}),{uniqueDrawParticipants:y=[],uniqueParticipantIds:v=[]}=S?aD({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}=zP({targetParticipants:u.participants||[],allUniqueParticipantIds:g,stageParticipantsCount:m,eventParticipantType:f});let T=sD({uniqueDrawParticipants:y,autoEntryPositions:a,stageParticipants:w,tournamentRecord:u,drawProfiles:l,category:d,gender:t,event:c});if(T.error)return T;if(T=iD({matchUpStatusProfile:r,completeAllMatchUps:i,randomWinningSide:s,tournamentRecord:u,drawProfiles:l,event:c}),T.error)return T;U.push(...T.drawIds)}m&&Oy({tournamentRecord:u,event:c})}else{const c=cD({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=pD({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=pv({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?WP({tournamentRecord:u,venueProfiles:l}):[];let w={};if(c?.length){const t=Ny({tournamentRecords:{[u.tournamentId]:u},schedulingProfile:c});if(t.error)return t;if(m){const{tournamentId:t}=u;w=UP({tournamentRecords:{[t]:u},periodLength:p})}}return{totalParticipantsCount:u.participants.length,scheduledRounds:undefined,schedulerResult:w,...E,eventIds:I,venueIds:v,drawIds:U}}var ID=Object.freeze({__proto__:null,anonymizeTournamentRecord:hD,modifyTournamentRecord:gD}),UD=Object.freeze({__proto__:null,anonymizeTournamentRecord:hD,generate:fD,generateEventWithDraw:pD,generateOutcome:XP,generateOutcomeFromScoreString:HT,generateParticipants:OP,generateTournamentRecord:mD,modifyTournamentRecord:gD,mutate:ID});function SD(t=0){("number"!=typeof t||isNaN(t))&&(t=0);const e=new Date;return e.setHours(e.getHours()+t),e.getTime().toString(36).slice(-6).toUpperCase()}function yD({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===ZT&&(e=ti(e),n=Xr(n),r=Xr(r),e&&n&&r)?{date:e,startTime:n,endTime:r,requestType:t.requestType}:t})).filter(Boolean);for(const n of r)n.requestId=SD(),t[e].push(n);return{mergeCount:r.length}}function vD(t){const{tournamentRecords:e,personRequests:n}=t,r=na(t,[{[Pi]:!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(Ma({tournamentParticipants:e,personId:t})){const e=n[t];e.length&&r.push({personId:t,requests:e})}if(Object.keys(r).length){Cr({element:t,extension:{value:r,name:Za}})}}return{...E}}function wD(t){const{tournamentRecords:e,requests:n,personId:r}=t,i=na(t,[{[Pi]:!0},{requests:!0,[Zi]:Ki,[Qi]:Nn}]);if(i.error)return i;const a=n.map((({requestId:t})=>t)).filter(Boolean),{personRequests:o}=fP({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&&yD({personRequests:o,personId:r,requests:c}),vD({tournamentRecords:e,personRequests:o})}function TD(t){const{tournamentRecords:e,requestType:n,requestId:r,personId:i,date:a}=t,o=na(t,[{[Pi]:!0}]);if(o.error)return o;const{personRequests:s}=fP({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?vD({tournamentRecords:e,personRequests:s}):Ar({name:Za,tournamentRecords:e,discover:!0})}function PD(t){const{tournamentRecords:e,personId:n,requests:r}=t,i=na(t,[{[Pi]:!0,personId:!0},{requests:!0,[Zi]:Ki,[Qi]:Nn}]);if(i.error)return i;const{personRequests:a}=fP({tournamentRecords:e}),{mergeCount:o}=yD({personRequests:a,personId:n,requests:r});return o&&a?vD({tournamentRecords:e,personRequests:a}):{error:Nn}}function DD({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}){const r="modifyIndividualParticipantIds";if(!n)return Nr({result:{error:x},stack:r});if(!e||!t)return Nr({result:{error:ae},stack:r});const i=n.participants||[],a=i.find((t=>t.participantId===e));if(!a)return Nr({result:{error:Ee},stack:r});if(![cu,ou].includes(a.participantType))return Nr({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!==au}));if(o.length)return Nr({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=Qv({individualParticipantIds:c,groupingParticipantId:e,tournamentRecord:n});if(d.error)return Nr({result:d,stack:r});const p=_m({individualParticipantIds:u,groupingParticipantId:e,tournamentRecord:n});if(p.error)return Nr({result:p,stack:r});const{topics:l}=mr();if(l.includes(gc)){const t=i.find((({participantId:t})=>t===e));cr({topic:gc,payload:{tournamentId:n.tournamentId,participants:[t]}})}return{...d,...p}}function bD({tournamentRecord:t,participantIds:e,signInState:n}){if(!t)return{error:x};if(!Array.isArray(e))return{error:ae};if(![ru,nu].includes(n))return{error:Nn,signInState:n};const r=t.participants||[];if(!r.length)return{error:Re};const i=r.map(vo),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=gh({duplicateValues:!1,tournamentRecord:t,participantId:r,timeItem:{itemType:eu,itemValue:n,createdAt:s}});if(e.error)return e;o.push(i)}}const{topics:c}=mr();return o.length&&c.includes(gc)&&cr({topic:gc,payload:{tournamentId:t.tournamentId,participants:o}}),{...E}}function ND({tournamentRecord:t,participantId:e,participantOtherName:n}){if(!t)return{error:x};if(!e)return{error:Ae};const{participant:r}=Tl({tournamentRecord:t,participantId:e});if(!r)return{error:Ee};r.participantOtherName=n;const{topics:i}=mr();return i.includes(gc)&&cr({topic:gc,payload:{tournamentId:t.tournamentId,participants:[r]}}),{...E}}function MD({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=Hm(e?.standardGivenName??""),s=Hm(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 RD({participantMap:t,participant:e,formats:n}){const{participantType:r,individualParticipantIds:i,person:a}=e,o=r&&n[r];if(r!==iu&&o){const{personFormat:n,doublesJoiner:s}=o;r===au&&(e.participantName=MD({person:a,personFormat:n})),r===su&&(e.participantName=i?.map((e=>{const r=t[e]?.person;return MD({person:r,personFormat:n})})).filter(Boolean).join(s??"/"))}}function AD({tournamentRecord:t,formats:e}){if(!t)return{error:x};if(!Ui(e))return{error:ae};const n=t.participants??[],r=yi(n,"participantId");for(const t of n)RD({participant:t,participantMap:r,formats:e});return{...E}}function ED(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=Ma({tournamentParticipants:t.participants||[],internalUse:!0,policyDefinitions:n,contextProfile:r,participantId:i,personId:a}),s)break}return{participant:s,tournamentId:c,...E}}function CD({individualParticipantIds:t=[],participantRoleResponsibilities:e,participantRole:n=Fm,tournamentRecord:r,participantId:i,groupName:a}){if(!r)return{error:x};if(!a)return{error:ae,info:"Missing groupName"};if(!Array.isArray(t))return{info:"Invalid individualParticipantIds",error:Nn};const o=(ym({participantFilters:{participantTypes:[au]},tournamentRecord:r}).participants??[]).map((t=>t.participantId));for(const e of t)if(!o.includes(e))return{error:be,participantId:e};const s=br({participantId:i||wp(),participantRoleResponsibilities:e,participantName:a,individualParticipantIds:t,participantType:ou,participantRole:n}),c=ly({participant:s,tournamentRecord:r});if(c.error)return c;const{topics:u}=mr();return u.includes(ic)&&cr({topic:ic,payload:{tournamentId:r.tournamentId,participants:[s]}}),{...E,participant:mi(s)}}function OD({tournamentRecord:t,participantName:e,participantId:n}){if(!t)return{error:x};if(!n)return{error:Ae};if(!e)return{error:ae,info:"Missing participantName"};const{participant:r}=Tl({tournamentRecord:t,participantId:n});if(!r)return{error:Ee};r.participantName=e;const{topics:i}=mr();return i.includes(gc)&&cr({topic:gc,payload:{tournamentId:t.tournamentId,participants:[r]}}),{...E}}function FD({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:x};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!==Xd)return{error:wt};a=l?.entries?.filter((({entryStatus:t})=>t===Vu)).map(vo)}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!==iu)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:iu,participantRole:Cm}))),{participants:n=[]}=my({participants:e,returnParticipants:!0,tournamentRecord:o}),r=n.map(vo),i=o.participants?.filter((({participantId:t})=>r.includes(t)))??[];h.push(...i)}if(!h.length)return{error:Rn};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!==au)return{error:be,participant:t};const r=cm({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(vo);for(const t of o.events??[]){if(t.eventType!==Xd)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}=Fp({event:t});(a?.flights||[]).forEach((t=>{t.drawEntries=(t.drawEntries||[]).filter((t=>!i.includes(t.participantId)))}))}}return{...E,scaledParticipants:i}}function kD(t){const{tournamentRecords:e}=t;if("object"!=typeof e||!Object.keys(e).length)return{error:_};for(const n of Object.values(e)){const e=_D({...t,tournamentRecord:n});if(e.error&&e.error!==Ze)return e}return{...E}}function _D({tournamentRecord:t,penaltyId:e}){if(!t)return{error:x};if(!e)return{error:Qe};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&&cr({topic:gc,payload:{tournamentId:t.tournamentId,participants:n}}),r?{...E,penalty:r}:{error:Ze}}const xD=({penaltyId:t=wp()}={})=>({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 LD(t){const{tournamentRecords:e}=t;if("object"!=typeof e||!Object.keys(e).length)return{error:_};for(const n of Object.values(e)){const e=BD({...t,tournamentRecord:n});if(e.error&&e.error!==Ze)return e;if(e.success)return e}return{error:Ze}}function BD({tournamentRecord:t,modifications:e,penaltyId:n}){if(!t)return{error:x};if(!e)return{error:Nn,modifications:e};if(!n)return{error:Qe};const r=t?.participants??[],i=Object.keys(xD()).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&&cr({topic:gc,payload:{tournamentId:t.tournamentId,participants:s}}),o?{...E,penalty:o}:{error:Ze}}function VD(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]=VD(t[i],e[i],n):r[i]=e[i];else r[i]=e[i];else r[i]=t[i];return r}),{})}function jD({participants:t=[],tournamentRecord:e,arraysToMerge:n}){if(!e)return{error:x};e.participants||(e.participants=[]);const r=t.filter(wi(Ri)).map((t=>({[t.participantId]:t}))),i=Object.assign({},...r),a=[];e.participants=e.participants.map((t=>{if(i[t.participantId]){const e=VD(t,i[t.participantId],n);return a.push(e),e}return t}));const o=e.participants.map(wi(Ri))||[],s=t.filter((({participantId:t})=>!o.includes(t))),{topics:c}=mr();return s.length&&(e.participants=e.participants.concat(...s),c.includes(ic)&&cr({topic:ic,payload:{participants:s}})),a.length&&c.includes(gc)&&cr({topic:gc,payload:{tournamentId:e.tournamentId,participants:a}}),{modifiedParticipantsCount:a.length,newParticipantsCount:s.length,...E}}function GD(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=ym({tournamentRecord:e}).participants??[],a=r?.map(vo).filter((t=>n.includes(t)));if(a.length){i=qD({...t,penaltyId:t.penaltyId??i,tournamentRecord:e,participantIds:a}).penaltyId}}return i?{...E,penaltyId:i}:{error:Ee}}function qD({refereeParticipantId:t,tournamentRecord:e,participantIds:n,penaltyCode:r,penaltyType:i,extensions:a,penaltyId:o,matchUpId:s,issuedAt:c,notes:u}){if(!e)return{error:x};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(xD({penaltyId:o}),{refereeParticipantId:t,penaltyCode:r,penaltyType:i,matchUpId:s,notes:u,issuedAt:c,createdAt:p});return Array.isArray(a)&&a.forEach((t=>Cr({element:l,extension:t}))),d.forEach((t=>{t.penalties||(t.penalties=[]),t.penalties.push(l)})),cr({topic:gc,payload:{tournamentId:e.tournamentId,participants:d}}),{...E,penaltyId:l.penaltyId}}function $D({participantRole:t=Cm,tournamentRecord:e,persons:n}){if(!e)return{error:x};if(!Array.isArray(n))return{error:Nn};if(!Object.keys(km).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=wp()),i.push(t.personId),t)));let o=0,s=0,c=my({participants:a.map((e=>{return br({extensions:e.participantExtensions,timeItems:e.participantTimeItems,participantType:au,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=ym({participantFilters:{participantTypes:[au]},tournamentRecord:e})?.participants??[];if(t===Cm&&n.filter((({pairedPersons:t})=>t)).forEach((({personId:t,pairedPersons:e})=>{Array.isArray(e)&&e.forEach((e=>{const n=[t,e.personId].map((t=>Ma({tournamentParticipants:d,personId:t}))).filter(Boolean);if(2===n.length){const t=n.map(vo);u.push(br({extensions:e.participantExtensions,timeItems:e.timeItems,participantRole:Cm,individualParticipantIds:t,participantType:su}))}}))})),u.length){if(c=my({participants:u,tournamentRecord:e}),c.error)return c;o=c.addedCount||0}const p=s+o;return{...E,addedCount:p,newPersonIds:i}}var WD=Object.freeze({__proto__:null,addIndividualParticipantIds:Qv,addParticipant:ly,addParticipants:my,addPenalty:GD,addPersonRequests:PD,addPersons:$D,createGroupParticipant:CD,createTeamsFromParticipantAttributes:yP,deleteParticipants:Bm,findParticipant:ED,mergeParticipants:jD,modifyIndividualParticipantIds:DD,modifyParticipant:Zv,modifyParticipantName:OD,modifyParticipantOtherName:ND,modifyParticipantsSignInStatus:bD,modifyPenalty:LD,modifyPersonRequests:wD,regenerateParticipantNames:AD,removeIndividualParticipantIds:_m,removeParticipantIdsFromAllTeams:Lm,removePenalty:kD,removePersonRequests:TD,scaledTeamAssignment:FD,setParticipantScaleItem:YP,setParticipantScaleItems:KP});function HD(t){const{tournamentRecords:e}=t||{};if("object"!=typeof e||!Object.keys(e).length)return{error:_};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}=ym({...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}}function zD({tournamentRecord:t,participantId:e}){if(!t)return{error:x};if(!e)return{error:Ae};const n=[e].concat((t.participants??[]).filter((t=>t?.participantType&&[cu,su].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})))}}function YD({tournamentRecord:t,participantId:e}){if(!t)return{error:x};if(!e)return{error:Ae};const{participants:n}=ym({participantFilters:{participantTypes:[cu,su,ou]},tournamentRecord:t});return(n??[]).filter((t=>t.individualParticipantIds?.includes(e))).reduce(((t,e)=>{const n=e.participantType;return n&&(t[n]||(t[n]=[]),t[n].push(e)),t}),{})}function KD({participantFilters:t={},tournamentRecord:e}){if(!e)return{error:x};if("object"!=typeof t)return{error:Pn,context:{participantFilters:t}};const n=xl({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=jl({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}}function JD({tournamentRecord:t,participantId:e}){if(!t)return{error:x};if(!e)return{error:Ae};const{participant:n}=Tl({tournamentRecord:t,participantId:e});if(!n)return{error:Ee};const{timeItem:r}=Pl({itemType:eu,element:n});return r&&r.itemValue===ru&&ru}var QD=Object.freeze({__proto__:null,filterParticipants:Um,getCompetitionParticipants:HD,getPairedParticipant:Xp,getParticipantEventDetails:zD,getParticipantMembership:YD,getParticipantScaleItem:TI,getParticipantSchedules:KD,getParticipantSignInStatus:JD,getParticipantTimeItem:Ml,getParticipants:ym,getScaleValues:da,participantScaleItem:cm,validateLineUp:Tf}),ZD=Object.freeze({__proto__:null,addIndividualParticipantIds:Qv,addParticipant:ly,addParticipants:my,addPenalty:GD,addPersonRequests:PD,addPersons:$D,createGroupParticipant:CD,createTeamsFromParticipantAttributes:yP,deleteParticipants:Bm,filterParticipants:Um,findParticipant:ED,getCompetitionParticipants:HD,getPairedParticipant:Xp,getParticipantEventDetails:zD,getParticipantMembership:YD,getParticipantScaleItem:TI,getParticipantSchedules:KD,getParticipantSignInStatus:JD,getParticipantTimeItem:Ml,getParticipants:ym,getScaleValues:da,mergeParticipants:jD,modifyIndividualParticipantIds:DD,modifyParticipant:Zv,modifyParticipantName:OD,modifyParticipantOtherName:ND,modifyParticipantsSignInStatus:bD,modifyPenalty:LD,modifyPersonRequests:wD,mutate:WD,participantScaleItem:cm,query:QD,regenerateParticipantNames:AD,removeIndividualParticipantIds:_m,removeParticipantIdsFromAllTeams:Lm,removePenalty:kD,removePersonRequests:TD,scaledTeamAssignment:FD,setParticipantScaleItem:YP,setParticipantScaleItems:KP,validateLineUp:Tf});function XD(t){const e=na(t,[{policyType:!0,_anyOf:{[Pi]:!1,[bi]:!1,[Ni]:!1,[Hi]:!1}}]);if(e.error)return e;let n;const r=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(r)return tb(t,r);if(!t.tournamentRecords)return{error:x};{const e=Object.keys(t.tournamentRecords);if(!e.length)return{error:x};for(const r of e){const e=tb(t,t.tournamentRecords[r]);if(e.error)return e;n=!0}}return n?{...E}:{error:ee}}function tb(t,e){const n=Tu(t).appliedPolicies??{};if(n[t.policyType]){if(delete n[t.policyType],Object.keys(n).length){Cr({element:e,extension:{name:xa,value:n}})}else Ar({element:e,name:xa});return{...E}}return{error:ee}}var eb=Object.freeze({__proto__:null,attachPolicies:sI,removePolicy:XD}),nb=Object.freeze({__proto__:null,findPolicy:ld,getAppliedPolicies:Tu,getPolicyDefinitions:Pu}),rb=Object.freeze({__proto__:null,attachPolicies:sI,findPolicy:ld,getAppliedPolicies:Tu,getPolicyDefinitions:Pu,mutate:eb,query:nb,removePolicy:XD});function ib({removePriorValues:t=!0,stageSeedingScaleNames:e,seedingScaleNames:n,tournamentRecord:r,status:i=Vd,drawIds:a=[],event:o}){if(!r)return{error:x};if(!o)return{error:Tt};const s=lm({event:o,status:i}),c=(s?.seeding?.seedingScaleNames||n)&&{...s?.seeding?.seedingScaleNames,...n};return Ry({statusObject:{seeding:br({stageSeedingScaleNames:(s?.seeding?.stageSeedingScaleNames||e)&&{...s?.seeding?.stageSeedingScaleNames,...e},seedingScaleNames:c,published:!0,drawIds:a})},removePriorValues:t,status:i,event:o}),cr({topic:Tc,payload:{tournamentId:r.tournamentId,eventId:o.eventId,drawIds:a}}),{...E}}function ab({removePriorValues:t=!0,seedingScaleNames:e,tournamentRecord:n,status:r=Vd,drawIds:i,stages:a,event:o}){if(!n)return{error:x};if(!o)return{error:Tt};const s=lm({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),Ry({statusObject:{seeding:n},removePriorValues:t,status:r,event:o})}return cr({topic:bc,payload:{tournamentId:n.tournamentId,eventId:o.eventId}}),{...E}}function ob(t){const e=t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{};if(!Object.keys(e).length)return{error:_};for(const n of Object.values(e)){const e=sb({tournamentRecord:n,...t});if(e.error)return e}return{...E}}function sb({removePriorValues:t=!0,tournamentRecord:e,status:n=Vd}){if(!e)return{error:x};const r=`${Bd}.${jd}`,{timeItem:i}=Pl({element:e,itemType:r}),a=i?.itemValue||{[n]:{}};a[n]&&delete a[n].orderOfPlay;return hh({timeItem:{itemValue:a,itemType:r},element:e,removePriorValues:t}),cr({topic:Nc,payload:{tournamentId:e.tournamentId}}),{...E}}function cb(t){const e=tu(t);if(!Object.keys(e).length)return{error:_};for(const n of Object.values(e)){const e=ub({tournamentRecord:n,...t});if(e.error)return e}return{...E}}function ub({scheduledDates:t=[],removePriorValues:e,tournamentRecord:n,status:r=Vd,eventIds:i=[]}){if(!n)return{error:x};const a=`${Bd}.${jd}`,{timeItem:o}=Pl({element:n,itemType:a}),s=o?.itemValue||{[r]:{}};s[r].orderOfPlay={published:!0,scheduledDates:t,eventIds:i};return hh({timeItem:{itemValue:s,itemType:a},element:n,removePriorValues:e}),cr({topic:Pc,payload:{tournamentId:n.tournamentId,scheduledDates:t,eventIds:i}}),{...E}}function db({removePriorValues:t=!0,tournamentRecord:e,status:n=Vd,event:r}){if(!e)return{error:x};if(!r)return{error:Tt};const i=`${Bd}.${jd}`,{timeItem:a}=bl({itemType:i,event:r}),o=a?.itemValue||{[n]:{}};delete o[n].structureIds,delete o[n].drawDetails,delete o[n].drawIds;return Uh({event:r,timeItem:{itemValue:o,itemType:i},removePriorValues:t}),Ry({statusObject:{structureIds:void 0,drawIds:void 0,seeding:void 0},removePriorValues:t,status:n,event:r}),cr({topic:Dc,payload:{tournamentId:e.tournamentId,eventId:r.eventId}}),{eventId:r.eventId,...E}}var pb=Object.freeze({__proto__:null,publishEvent:Oy,publishEventSeeding:ib,publishOrderOfPlay:cb,setEventDisplay:av,unPublishEvent:db,unPublishEventSeeding:ab,unPublishOrderOfPlay:ob});function lb({tournamentRecord:t,policyDefinitions:e}){if(!t)return{error:x};const n=t.events||[],r=t?.participants||[],{tournamentInfo:i}=Ay({tournamentRecord:t}),{venues:a}=Py({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=zd({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}=Il({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=lm({event:n});return Object.assign(a,{drawsData:s,publish:c}),a}))}}}var mb=Object.freeze({__proto__:null,bulkUpdatePublishedEventIds:mv,getAllEventData:lb,getCourtInfo:Rp,getDrawData:Ey,getEventData:Cy,getPublishState:fm,getVenueData:Ap}),fb=Object.freeze({__proto__:null,bulkUpdatePublishedEventIds:mv,getAllEventData:lb,getCourtInfo:Rp,getDrawData:Ey,getEventData:Cy,getPublishState:fm,getVenueData:Ap,mutate:pb,publishEvent:Oy,publishEventSeeding:ib,publishOrderOfPlay:cb,query:mb,setEventDisplay:av,unPublishEvent:db,unPublishEventSeeding:ab,unPublishOrderOfPlay:ob});function hb({tournamentRecord:t}){if(!t)return{error:x};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 gb({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:_};const e=[];for(const n of Object.values(t)){const{penalties:t}=hb({tournamentRecord:n});e.push(...t??[])}return{penalties:e}}function Ib({tournamentRecord:t,participantFilters:e}){if(!t)return{error:x};let n=t.participants||[];e&&(n=Um({participants:n,participantFilters:e,tournamentRecord:t}));const r={};return n.forEach((t=>{t.person&&(t=>{if(t.person){const{personId:e}=t.person;r[e]?r[e].participantIds.push(t.participantId):r[e]={...t.person,participantIds:[t.participantId]}}})(t)})),{tournamentPersons:Object.values(r)}}function Ub(t){const e=t.participants?.filter((({participantType:t})=>t===cu)),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 Sb({tournamentRecord:t}){if(!t)return{error:x};const{drawsAnalysis:e}=lI({tournamentRecord:t}),n={isDual:Ub(t),drawsAnalysis:e};return{...E,analysis:n}}var yb=Object.freeze({__proto__:null,analyzeDraws:lI,analyzeTournament:Sb,getAllowedDrawTypes:pS,getAllowedMatchUpFormats:dS,getAppliedPolicies:Tu,getCompetitionDateRange:uD,getCompetitionPenalties:gb,getPolicyDefinitions:Pu,getTournamentInfo:Ay,getTournamentPenalties:hb,getTournamentPersons:Ib,getTournamentStructures:Lf,getTournamentTimeItem:Nl});function vb({tournamentRecord:t,drawDefinition:e,structureId:n,matchUpId:r,structure:i,eventId:a,drawId:o,event:s}){if(!t)return{error:x};if(!(o||s||n||r))return Nr({result:{error:ae},stack:"getTieFormat"});a&&!s&&(s=t.events?.find((t=>t.eventId===a)));const c=Vv({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=Qs({drawDefinition:e,structureId:n});if(t.error)return t;i=t.structure}const u=(i?.tieFormat||i?.tieFormatId)&&Bp({structure:i,drawDefinition:e,event:s})?.tieFormat,d=(e?.tieFormat||e?.tieFormatId)&&Bp({drawDefinition:e,event:s})?.tieFormat,p=Bp({event:s})?.tieFormat,l=Bp({matchUp:c?.matchUp,drawDefinition:e,structure:i,event:s})?.tieFormat;return{...E,matchUp:c?.matchUp,structureDefaultTieFormat:Jg(u),eventDefaultTieFormat:Jg(p),drawDefaultTieFormat:Jg(d),tieFormat:Jg(l),structure:i}}var wb=Object.freeze({__proto__:null,compareTieFormats:tT,getTieFormat:vb,tieFormatGenderValidityCheck:Og,validateCollectionDefinition:Wg});function Tb(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(Gr))return{error:pe};const i=[];let a=0;const o={},{schedulingProfile:s}=by({tournamentRecords:n});if(!s)return{issues:i,...E};const{matchUps:c}=Ll({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}=eP({tournamentRecords:n,periodLength:r,matchUps:c,rounds:e}),{matchUpDependencies:l}=jl({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}}var Pb=Object.freeze({__proto__:null,getPersonRequests:fP,getScheduledRoundsDetails:eP,getSchedulingProfile:by,getSchedulingProfileIssues:Tb});function Db({tournamentRecord:t,venueId:e,venueIds:n}){if(!t)return{error:x};return{courts:(t.venues||[]).filter((t=>e?t.venueId===e:!n||n.includes(t.venueId))).map((t=>{const{venueId:e}=t,n=mi(t.courts||[]);return n.forEach((t=>Object.assign(t,{venueId:e}))),n})).flat()}}var bb=Object.freeze({__proto__:null,getCompetitionVenues:Dy,getCourts:Db,getVenuesAndCourts:Py,publicFindVenue:bp}),Nb=Object.freeze({__proto__:null,allCompetitionMatchUps:Ll,allDrawMatchUps:Vl,allEventMatchUps:_l,allPlayoffPositionsFilled:Vf,allTournamentMatchUps:xl,analyzeDraws:lI,analyzeMatchUp:BT,analyzeTournament:Sb,bulkUpdatePublishedEventIds:mv,calculateWinCriteria:PT,categoryCanContain:Lg,checkMatchUpIsComplete:fl,checkValidEntries:xU,compareTieFormats:tT,competitionScheduleMatchUps:ST,credits:function(){return"\n This project would not have been possible without the generous input and patience\n of tournament organizers and directors who worked with early versions of CourtHive/TMX.\n\n Thanks to Pavel, Ivan, Mladen, Zdenko, Antonia, Jakov, Kreso, Barry, Jeff, Bobby... to name just a few. \n\n The project would not have even begun without the support of Miro, or the introduction by Sretchko.\n The project would not have succeeded without the enthusiasm of Randy and Bruce.\n Thanks to serendipity and Luca and the ensuing TODS conversations with ITF.\n Thanks to Scott and Jake for sanity checks, suggestions, and camaraderie.\n Thanks to Zoran for inspiring the async support and getting into the weeds with subscriptions.\n Thanks to Dave for backing the conversion of TMX 1.x source into the factory repository.\n Thanks to Vuk and Pavle and Rich and Chris and Deepa for the direct engagement with the APIs.\n Thanks to Joe for repeatedly challenging me and the many pointers to useful tooling.\n Thanks to Shannon for the validation of the approach from his deep domain experience.\n Thanks to Nikola for the ongoing camaraderie and explorations of what we can do with TODS.\n\n And a special thanks to my family for putting up with the long days and weeks and months of coding\n and conversations at all hours.\n "},drawMatchUps:VT,eventMatchUps:gT,filterParticipants:Um,findDrawDefinition:EI,findExtension:Fr,getAllDrawMatchUps:gl,getAllowedDrawTypes:pS,getAllowedMatchUpFormats:dS,getAppliedPolicies:Tu,getAssignedParticipantIds:rm,getAvailablePlayoffProfiles:Bh,getCategoryAgeDetails:_g,getCheckedInParticipantIds:qd,getCompetitionDateRange:uD,getCompetitionMatchUps:UT,getCompetitionParticipants:HD,getCompetitionPenalties:gb,getCompetitionVenues:Dy,getCourts:Db,getDrawDefinitionTimeItem:Dl,getDrawParticipantRepresentativeIds:MI,getDrawTypeCoercion:FU,getEligibleVoluntaryConsolationParticipants:NI,getEntriesAndSeedsCount:vI,getEvent:gv,getEventMatchUpFormatTiming:dT,getEventProperties:fv,getEventStructures:xf,getEventTimeItem:bl,getEvents:hv,getFlightProfile:Fp,getLinkedTournamentIds:ho,getMatchUpCompetitiveProfile:md,getMatchUpContextIds:DT,getMatchUpDailyLimits:yT,getMatchUpDailyLimitsUpdate:pT,getMatchUpDependencies:jl,getMatchUpFormat:bT,getMatchUpFormatTiming:mp,getMatchUpFormatTimingUpdate:aT,getMatchUpScheduleDetails:_p,getMatchUpType:il,getMatchUpsStats:NT,getMaxEntryPosition:Iy,getModifiedMatchUpFormatTiming:Vy,getPairedParticipant:Xp,getParticipantEventDetails:zD,getParticipantIdFinishingPositions:RI,getParticipantMembership:YD,getParticipantScaleItem:TI,getParticipantSchedules:KD,getParticipantSignInStatus:JD,getParticipantTimeItem:Ml,getParticipants:ym,getPersonRequests:fP,getPolicyDefinitions:Pu,getPositionAssignments:kU,getPositionsPlayedOff:xh,getPredictiveAccuracy:vT,getRoundMatchUps:Su,getRounds:kT,getScaleValues:da,getScaledEntries:PI,getScheduledRoundsDetails:eP,getSchedulingProfile:by,getSchedulingProfileIssues:Tb,getSeedingThresholds:pf,getSeedsCount:yI,getStructureSeedAssignments:od,getTeamLineUp:tl,getTieFormat:vb,getTimeItem:Pl,getTournamentIds:uo,getTournamentInfo:Ay,getTournamentPenalties:hb,getTournamentPersons:Ib,getTournamentStructures:Lf,getTournamentTimeItem:Nl,getValidGroupSizes:cf,getVenuesAndCourts:Py,isAdHoc:nl,isCompletedStructure:Bf,isValidForQualifying:_U,isValidMatchUpFormat:$g,matchUpActions:CU,participantScaleItem:cm,participantScheduledMatchUps:mT,positionActions:OU,publicFindVenue:bp,tallyParticipantResults:vg,tieFormatGenderValidityCheck:Og,tournamentMatchUps:IT,validMatchUp:Iu,validMatchUps:Uu,validateCollectionDefinition:Wg,validateLineUp:Tf});function Mb({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===tS)),o=a?.scaleValue,{wtnRating:s,confidence:c}=o||{};return{timeStamp:a?.scaleDate,personOtherId:r,confidence:c,wtnRating:s,personId:n,tennisId:i}}function Rb({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=>Mb({participant:e,eventType:t}))).filter((({wtnRating:t})=>t)),c=(o.length-s.length)/o.length*100,u=s.reduce(((t,e)=>{const{wtnRating:n,confidence:r}=e;return t.totalWTN+=n,t.totalConfidence+=r,t}),{totalWTN:0,totalConfidence:0}),d=s?.length?u.totalWTN/s.length:0,p=s?.length?u.totalConfidence/s.length:0,l=Object.values(i).reduce(((t,e)=>t+(e||0)),0);return{matchUpFormatCounts:i,matchUpsCount:l,avgConfidence:p,pctNoRating:c,avgWTN:d}}var Ab=Object.freeze({__proto__:null,getEntryStatusReports:function({tournamentRecord:t}){if(!t)return{error:x};const e=t.tournamentId,{participantMap:n}=ym({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:t,withDraws:!0}),r=(xl({matchUpFilters:{matchUpTypes:[Hc,Yc]},tournamentRecord:t}).matchUps??[]).flatMap((({sides:t,matchUpType:e})=>t?.flatMap((t=>e===Yc?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=Mb({participant:m,eventType:s}),g=f?.[o]?.ranking;d===WI&&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===Jo&&1===e||t===Qo)).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?.[Jo],c=n?.[r]?.draws?.[e]?.seedAssignments?.[Qo];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===Qd?(()=>{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({},...td.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===au&&e===Cm)),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:x};if(s&&!Array.isArray(s))return{error:Yt};if(s=s??xl({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=ym({participantFilters:c.length?{participantIds:c}:{participantTypes:[iu]},tournamentRecord:i}).participants??[];if(!u.every((({participantType:t})=>t===iu)))return{error:Pe};c.length||c.push(...u.map(vo));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 Nr({result:{error:Ee},context:{teamParticipantId:r}});if(e&&!m.get(e))return Nr({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(!Ui(e))return{error:Yt};const{matchUpStatus:n,matchUpFormat:r,matchUpType:i,winningSide:a,score:s,sides:c}=e;if(!c||!s||i===Jc||n===No)continue;const u=g(c);if(!u.filter(Boolean).length)continue;const p=t&&a&&md({matchUp:e})?.competitiveness;h.push(e);const l=eg({matchUpStatus:n,matchUpFormat:r,tallyPolicy:o,winningSide:a,score:s}),m=ng({matchUpStatus:n,matchUpFormat:r,tallyPolicy:o,winningSide:a,score:s}),{pointsTally:I,tiebreaksTally:U}=rg({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},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=Fr({element:n,name:t})?.extension?.value;return{[e||t]:r?hi({element:i,accessor:r})?.value:i}}))),a=n?.tournamentId,o=xl({participantsProfile:{withScaleValues:!0},tournamentRecord:n}).matchUps??[],s=t=>{const e=Pl({itemType:ac,itemSubTypes:[ca],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===Ha)),m=l?.value?.flights?.map((t=>({[t.drawId]:t.flightNumber}))),f=m&&Object.assign({},...m),h=c?.find((t=>t.name===$a))?.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}=Rb({eventType:u,matchUps:o,drawId:g}),T=s(c)||U,P=function({extensions:t}){return t?.find((({name:t})=>t===La))?.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&&[Qo,Jo,Zo,ts].includes(t.stage))).map((t=>{const r=[Jo,ts].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===iu&&c.participantId,m=c?.participantType===su?c.individualParticipants:[],U=Mb({participant:m?.[0]||c,eventType:u}),{personId:D,personOtherId:b,tennisId:N,confidence:M,wtnRating:R}=U||{},A=Mb({participant:m?.[1],eventType:u}),{personId:E,personOtherId:C,tennisId:O,confidence:F,wtnRating:k}=A||{},{ageCategoryCode:_,categoryName:x,subType:L}=p??{},B=t.matchUpFormat||e,V=(I[B]||0)/S*100,{tieFormatName:j,tieFormatDesc:G}=Xw(n),{tieFormatName:q,tieFormatDesc:$}=Xw(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:x,ageCategoryCode:_,flightNumber:f[g],drawType:h,stage:t.stage,seedingBasis:T?JSON.stringify(T):void 0,winningPersonId:D,winningPersonOtherId:b,winningPersonTennisId:N,winningPersonWTNrating:R,winningPersonWTNconfidence:M,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}},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:_};if(!i.every(Gr))return{error:pe};const a=Py({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}=Ll({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&&Mv({courtDate:r}).timeSlots,a=i?.reduce(((t,e)=>{const{startTime:n,endTime:r}=e;return t+(Qr(r)-Qr(n))}),0);a&&(s+=1),e+=a}const c=n.filter((({schedule:e})=>e.venueId===r&&pi(t,e.scheduledDate)));c.forEach((({schedule:t})=>{const e=Xr(t.scheduledTime),n=Qr(ci(e,t.averageMinutes))-Qr(e);a+=n}));const u=e?(a/e*100).toFixed(2):"100";o[t]={scheduledMatchUpsCount:c.length,availableCourts:s,availableMinutes:e,scheduledMinutes:a,percentUtilization:u}})),{venueId:r,venueName:a,venueReport:o}}(s,t,u)));return{venuesReport:d}}});function Eb({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:_};o=o??Ev({recoveryMinutes:e,averageMatchUpMinutes:n});const{courts:p,venues:l}=Py({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||pi(s,t.date))),r=n?.startTime??e.startTime;return r&&(!t||Qr(r)<Qr(t))?r:t}),void 0)),d||(d=m?.reduce(((t,e)=>{const n=e.dateAvailability?.find((t=>!t.date||pi(s,t.date))),r=n?.endTime??e.endTime;return r&&(!t||Qr(r)>Qr(t))?r:t}),void 0));const f=Object.values(a),h=Object.assign({},...f.map((t=>(t.events??[]).map((e=>{const{scheduleTiming:n}=zd({tournamentRecord:t,event:e});return{[e.eventId]:{event:e,scheduleTiming:n}}})))).flat()),g=ST({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}=fp({eventType:a,timingDetails:s}),{courtId:d,venueId:p}=e,l=Xr(e.scheduledTime),m=ci(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}=Fv(w);return{venueId:1===u?.length&&u[0]||1===l?.length&&l[0].venueId||void 0,scheduleTimes:T,dateScheduledMatchUpIds:S.map(wo)}}function Cb(t){const e=na(t,[{[Pi]:!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:x};const{drawDefinition:d,event:p}=AI({tournamentRecord:u,drawId:c});if(!d)return{error:j};const l=Dg({drawDefinition:d,event:p,matchUpId:o});if(l.error)return l;if(l?.matchUp?.matchUpType===Jc){const{itemValue:t}=gp({timeItems:l.matchUp.timeItems??[],itemType:Ud}),e=s&&t.filter((t=>t.courtId!==s));return $v({duplicateValues:!1,removePriorValues:n,tournamentRecord:u,drawDefinition:d,matchUpId:o,timeItem:{itemType:Ud,itemValue:e}})}return ww({tournamentRecord:u,drawDefinition:d,courtDayDate:a,courtId:"",matchUpId:o})}function Ob({scheduleCompletedMatchUps:t,tournamentRecords:e,scheduledDate:n,matchUps:r}){if(!Uu(r))return{error:Nn};if(r.some((({hasContext:t})=>!t)))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:hn};let i=ST({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(Ui(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=>Ui(t)&&!t.matchUpId));return t.concat({matchUpIds:n,availableCourts:i,rowId:e.rowId,participantIds:r})}),[]);r.filter((({matchUpStatus:e})=>e&&e!==No&&(t||!Ho.includes(e)))).sort(Bl);const u=jl({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=lP({tournamentRecords:e,matchUpDetails:l});const m=r;return{...i,scheduled:d,notScheduled:m}}function Fb(t){const{courtDayDate:e}=t,n=na(t,[{courtAssignments:!0,[Zi]:Ki,[Qi]:ae},{[Pi]:!0}]);if(n.error)return n;const r=t.courtAssignments.reduce(((t,e)=>{const{tournamentId:n}=e;return t[n]||(t[n]=[]),t[n].push(e),t}),{});let i;return Object.keys(r).every((n=>{const a=t[Pi][n];if(!a)return i={error:x},!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}=kp({tournamentRecord:a,drawId:t});return n?(o[t].every((t=>{const{matchUpId:r,courtId:o}=t,s=ww({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}function kb(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=na(t,[{[Pi]:!0,[Oi]:!0},{[Ji]:Gr,[Qi]:pe,scheduleDate:!0},{[Ji]:t=>!t||!isNaN(t),averageMatchUpMinutes:!1,[Qi]:Nn,recoveryMinutes:!1,periodLength:!1}]);if(y.error)return y;const v=t.competitionMatchUps??Ll({nextMatchUps:!0,tournamentRecords:e}).matchUps??[],w=t.matchUpDependencies??jl({includeParticipantDependencies:!0,matchUps:v,tournamentRecords:e}).matchUpDependencies;v.forEach((t=>{t.schedule?.scheduledDate&&pi(f,ti(t.schedule.scheduledDate))&&YT({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}=Eb({tournamentRecords:e,remainingScheduleTimes:p,startTime:Xr(I),endTime:Xr(U),scheduleDate:ti(f),averageMatchUpMinutes:r,clearScheduleDates:l,periodLength:m,venueIds:g}),N={},M=[],R={},A={},C={},O=v.filter((({matchUpId:t})=>b?.includes(t)));O.forEach((t=>{rP({matchUpPotentialParticipantIds:o,individualParticipantProfiles:s,matchUp:t,value:1});const e=t.schedule?.scheduledTime;if(e){R[t.matchUpId]=e;const n=a?.[t.matchUpId];JT({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=[No,Eo,Ro,Do,xo,Vo].includes(t?.matchUpStatus);return!e&&!t.winningSide&&!n}));const{matchUpMap:k,overLimitMatchUpIds:_,participantIdsAtLimit:x}=F.reduce(((t,e)=>{const{drawId:n,tournamentId:r,matchUpType:i}=e,{participantIdsAtLimit:a,relevantParticipantIds:d}=dP({individualParticipantProfiles:s,matchUpPotentialParticipantIds:o,matchUpDailyLimits:u,matchUp:e});return a?.length?(t.overLimitMatchUpIds.push(e.matchUpId),t.participantIdsAtLimit.push(...a),t):(d.forEach((t=>{KT({individualParticipantProfiles:s,participantId:t});const e=s[t].counters;e[i]?e[i]+=1:e[i]=1,e[rp]?e[rp]+=1:e[rp]=1})),t.matchUpMap[r]||(t.matchUpMap[r]={}),t.matchUpMap[r][n]?t.matchUpMap[r][n].push(e):t.matchUpMap[r][n]=[e],YT({matchUpPotentialParticipantIds:o,matchUpNotBeforeTimes:c,matchUp:e}),t)}),{matchUpMap:{},overLimitMatchUpIds:[],participantIdsAtLimit:[]});F=F.filter((({matchUpId:t})=>!_.includes(t)));let L=0;const B=D?.length??0,{personRequests:V}=fP({tournamentRecords:e,requestType:ZT});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}=zT({matchUpScheduleTimes:R,matchUpDependencies:w,allDateMatchUpIds:n,matchUp:e});if(!p)return C[u]||(C[u]=[]),C[u].push({scheduleTime:t,remainingDependencies:l}),!1;const{enoughTime:m}=uP({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}=tP({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 JT({recoveryMinutes:g||i,matchUpPotentialParticipantIds:o,individualParticipantProfiles:s,matchUpNotBeforeTimes:c,averageMatchUpMinutes:r,matchUpDependencies:w,scheduleTime:t,matchUp:e}),R[e.matchUpId]=t,!0}));F=F.filter((({matchUpId:t})=>t!==e?.matchUpId)),e||M.push(t)}F.forEach((t=>{rP({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}=AI({tournamentRecord:n,drawId:r});if(i){k[t][r].forEach((({matchUpId:t})=>{const r=R[t];if(r){const a=r.split(":").map(di).join(":"),o=`${ti(f)}T${a}`;if(S)j.push(t);else{Tw({drawDefinition:i,matchUpId:t,scheduledTime:o}).success&&j.push(t),P&&vw({tournamentRecords:e,tournamentRecord:n,drawDefinition:i,matchUpId:t,venueId:P})}}}))}}))}));const G=So(F);return{...E,requestConflicts:Object.values(N),remainingScheduleTimes:D?.map((({scheduleTime:t})=>t)),individualParticipantProfiles:s,matchUpNotBeforeTimes:c,participantIdsAtLimit:x,skippedScheduleTimes:M,overLimitMatchUpIds:_,scheduledMatchUpIds:j,noTimeMatchUpIds:G,recoveryTimeDeferred:A,dependencyDeferred:C}}function _b({tournamentRecords:t,matchUps:e}){if(!Uu(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(Bl).forEach((({schedule:t})=>delete t[pp]));const s=jl({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[pp]){o[t].schedule[pp]=e,o[t].schedule[op]=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][sp]||(i[t][sp]=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][cp]||(i[t][cp]=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,up,ap,[e]))),d(e,up,ap,n))}if(i[e]?.[sp]&&d(e,sp,ip,i[e][sp]),t.sourceMatchUpIds.includes(e)){const n=t.matchUpIds.filter((t=>s[t].matchUpIds.includes(e)));d(e,sp,ap,n),t.matchUpIds.filter((t=>s[t].matchUpIds.includes(e))).forEach((t=>d(t,sp,ap,[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,dp,ap,c),c.forEach((t=>d(t,dp,ap,[e])))),i[e]?.[cp]&&d(e,cp,ip,i[e][cp]),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,cp,ap,[e]))),d(e,cp,ap,r))}}))})),{courtIssues:a,rowIssues:u}}function xb(t){const e="reorderUpcomingMatchUps",{tournamentRecords:n}=t;if("object"!=typeof n||!Object.keys(n).length)return Nr({result:{error:_},stack:e});const{matchUpsContextIds:r,firstToLast:i}=t;if(!r)return Nr({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}=AI({tournamentRecord:a,drawId:i});return o?Tw({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:Nr({result:{error:Un},stack:e})}function Lb(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=tu(t),a=[];let o=[];for(const t of Object.values(i)){const i=Bb({tournamentRecord:t,scheduleChange:e,matchUpIds:n,dryRun:r});if(i.error)return i;Array.isArray(i.notRescheduled)&&o.push(...i.notRescheduled);const s=So(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}}function Bb({tournamentRecord:t,scheduleChange:e,matchUpIds:n,dryRun:r}){if(!t)return{error:x};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}=xl({matchUpFilters:{matchUpIds:n},tournamentRecord:t}),u=c?.filter((t=>lT({schedule:t.schedule}))).filter((t=>(({matchUpStatus:t})=>!Ho.includes(t))({matchUpStatus:t.matchUpStatus})));if(!u?.length)return{...E};const{tournamentInfo:d}=Ay({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=AI({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=ei(ti(m),s),f=new Date(g)<new Date(p)||new Date(g)>new Date(l)}if(o&&c){const t=ti(c),e=Qr(Xr(c))+o;if(f=e<0||e>1440,!f){const e=ci(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=Tw({scheduledTime:h,drawDefinition:d,matchUpId:t});if(e.error)return e}if(g){const e=Nw({scheduledDate:g,drawDefinition:d,matchUpId:t});if(e.error)return e}}(h||g)&&i.push(t)}}}const f=xl({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}}function Vb(t){const e="matchUpScheduleChange",{tournamentRecords:n}=t;if("object"!=typeof n||!Object.keys(n).length)return{error:_};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 Nr({result:{error:ae},stack:e});const{matchUps:f}=Ll({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 Nr({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 Nr({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 Nr({result:r,stack:e,info:"target"})}}return I?E:Nr({result:{error:Sn},stack:e});function U(t){const{tournamentRecords:e,tournamentId:n,matchUp:r,drawId:i}=t,a=e[n],{drawDefinition:o}=AI({tournamentRecord:a,drawId:i});return r.matchUpType===Qc?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 yw({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,courtDayDate:a,matchUpId:o,courtIds:u})}({...t,tournamentRecord:a,drawDefinition:o}):ww({...t,tournamentRecord:a,drawDefinition:o})}}function jb({scheduleAttributes:t=[Ud,Sd,Id,vd,Td,Pd,Nd,bd,Dd],tournamentRecord:e,drawDefinition:n,matchUpId:r}){const i=n?Vl({matchUpFilters:{matchUpIds:[r]},inContext:!1,drawDefinition:n}).matchUps?.[0]:xl({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,Oc({tournamentId:e.tournamentId,context:"clearMatchUpSchedule",drawDefinition:n,matchUp:i}),{...E}}function Gb(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:_};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=Cr({element:i[t],extension:{name:eo,value:{dailyLimits:r}}});if(e.error)return e}return{...E}}var qb=Object.freeze({__proto__:null,addMatchUpCourtOrder:Mw,addMatchUpEndTime:Ew,addMatchUpOfficial:Rw,addMatchUpResumeTime:Ow,addMatchUpScheduleItems:bw,addMatchUpScheduledDate:Nw,addMatchUpScheduledTime:Tw,addMatchUpStartTime:Aw,addMatchUpStopTime:Cw,addSchedulingProfileRound:dD,allocateTeamMatchUpCourts:yw,assignMatchUpCourt:ww,assignMatchUpVenue:vw,bulkRescheduleMatchUps:Lb,bulkScheduleMatchUps:lP,bulkScheduleTournamentMatchUps:pP,bulkUpdateCourtAssignments:Fb,calculateScheduleTimes:Eb,clearMatchUpSchedule:jb,clearScheduledMatchUps:gP,courtGridRows:hT,findMatchUpFormatTiming:MT,findVenue:Dp,generateBookings:oP,generateVirtualCourts:Av,getProfileRounds:CT,matchUpScheduleChange:Vb,modifyMatchUpFormatTiming:jy,proAutoSchedule:Ob,proConflicts:_b,publicFindCourt:Mp,removeEventMatchUpFormatTiming:Wy,removeMatchUpCourtAssignment:Cb,reorderUpcomingMatchUps:xb,scheduleMatchUps:kb,scheduleProfileRounds:UP,setMatchUpDailyLimits:Gb,setSchedulingProfile:Ny,toggleParticipantCheckInState:zv,validateSchedulingProfile:vy}),$b=Object.freeze({__proto__:null,addMatchUpCourtOrder:Mw,addMatchUpEndTime:Ew,addMatchUpOfficial:Rw,addMatchUpResumeTime:Ow,addMatchUpScheduleItems:bw,addMatchUpScheduledDate:Nw,addMatchUpScheduledTime:Tw,addMatchUpStartTime:Aw,addMatchUpStopTime:Cw,addSchedulingProfileRound:dD,allocateTeamMatchUpCourts:yw,assignMatchUpCourt:ww,assignMatchUpVenue:vw,bulkRescheduleMatchUps:Lb,bulkScheduleMatchUps:lP,bulkScheduleTournamentMatchUps:pP,bulkUpdateCourtAssignments:Fb,calculateScheduleTimes:Eb,clearMatchUpSchedule:jb,clearScheduledMatchUps:gP,courtGridRows:hT,findMatchUpFormatTiming:MT,findVenue:Dp,generateBookings:oP,generateVirtualCourts:Av,getPersonRequests:fP,getProfileRounds:CT,getScheduledRoundsDetails:eP,getSchedulingProfile:by,getSchedulingProfileIssues:Tb,matchUpScheduleChange:Vb,modifyMatchUpFormatTiming:jy,mutate:qb,proAutoSchedule:Ob,proConflicts:_b,publicFindCourt:Mp,query:Pb,removeEventMatchUpFormatTiming:Wy,removeMatchUpCourtAssignment:Cb,reorderUpcomingMatchUps:xb,scheduleMatchUps:kb,scheduleProfileRounds:UP,setMatchUpDailyLimits:Gb,setSchedulingProfile:Ny,toggleParticipantCheckInState:zv,validateSchedulingProfile:vy});const Wb="\\d+-\\d+",Hb="\\d+-\\d+\\(\\d+\\)",zb="\\[\\d+-\\d+\\]",Yb=new RegExp(`(${Wb}),`,"g"),Kb=new RegExp(`(${Hb}),`,"g"),Jb=[Wb,Hb,zb,"\\d+-\\d+\\(\\d+-\\d+\\)"],Qb=["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=>Jb[t])).join(" ");return new RegExp(`^${e}$`)}));function Zb(t){return!t||Qb.some((e=>e.test(t)))}function Xb(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function tN(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 eN(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 nN(t){return 2===t.length?t.split("").join("-"):([", ",",","/"," "].forEach((e=>t=t.split(e).join("-"))),t=t.replace(/-{2,}/,"-"))}function rN(t){return t.startsWith("(")&&t.endsWith(")")}function iN(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 aN({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 oN(t){const e=t.indexOf("1"),n=t.split(""),r=n.every((t=>!isNaN(t)));if(r&&3===t.length&&0===e){const t=eN(n,e);if(t)return t}if(r&&7===t.length&&e>3){const t=eN(n.slice(4),e-4);if(t)return`${n[0]}-${n[1]} ${n[2]}-${n[3]} ${t}`}}function sN(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(aN({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=oN(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 cN(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 uN={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(rN)?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(Xb);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":tN(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;!tN(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(zb).test(t)?"super":new RegExp(Hb).test(t)&&"tiebreak")||new RegExp(Wb).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(")")),[Yb,Kb].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(iN).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=eN(t.split(""),n);return e.push("getSuper"),r}}else{const{score:n,applied:r}=sN({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=iN(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)&&oN(t)){return{score:oN(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(tN(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=eN(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 tN(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:sN,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=iN(nN(r));t=t.replace(e,`(${a})`).trim()}const a=new RegExp(/\[[\d,/ ]+\]/g),o=t.match(a);o?.forEach((e=>{const n=nN(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(",")||Xb(t))),i=n.every((t=>t.includes("/")||Xb(t))),a=n.every((t=>t.includes("-")||Xb(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["-"]&&tN(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(Hb).test(t)){const n=t.slice(3),r=t.slice(0,3),i=r.split("-");if(!tN(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=iN(t);const a=(new RegExp(`^${zb}$`).test(t)?"super":new RegExp(`^${Hb}$`).test(t)&&"tiebreak")||new RegExp(`^${Wb}$`).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}=cN(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}=cN(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:aN,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 dN={};const pN=["handleNumeric","handleWalkover","handleRetired","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],lN=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];const mN=" ",fN="DEF",hN="WO",gN="ABN",IN="SUS",UN="RET",SN="INT",yN=[UN,fN,hN,"WO/WO",gN,IN,SN],vN="DEFAULTED",wN="WALKOVER",TN="ABANDONED",PN="SUSPENDED",DN="RETIRED",bN="INTERRUPTED",NN=[DN,vN,wN],MN="()",RN="[]",AN=["up","left","shift+tab"],EN=["enter","down","tab","right"],CN="backspace",ON="r",FN="s",kN="a",_N="d",xN="w",LN="i",BN=[ON,_N,xN,kN,FN,LN],VN="space",jN=["[","("],GN=[...AN,...EN,VN,"]"],qN="-",$N="-",WN=["/"],HN=["0","1","2","3","4","5","6","7","8","9"].concat(BN),zN=HN.map((t=>`shift+${t}`)),YN=[qN,CN].concat(GN,WN),KN=[HN,zN,YN].join(","),JN=[KN,AN,EN,["=","+","num_1","num_2","shift+=","shift+-"]].join(",");[].concat(...HN,...HN,...YN,...HN,...HN,...HN,...HN,...HN,...HN);const QN={OUTCOMEKEYS:BN,SIDE1KEYS:HN,SIDE2KEYS:zN,MODIFIERS:YN,PROMPT:"Enter Score",MOVEUP:AN,MOVEDOWN:EN,HOTKEYS:JN};function ZN({scoreString:t,lowSide:e,outcome:n}){if(({scoreString:t}=XN({scoreString:t})),2===e){return t+((t&&t[t.length-1])!==mN?mN:"")+n}return n+mN+t}function XN({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(const n of yN){const r=t?.indexOf(n);0===r?t=t.slice(n.length+1).trim()+mN:r>0&&(t=t.slice(0,r)),r>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function tM({analysis:t,scoreString:e,sets:n,lowSide:r}){let i,a;if(!e)return{scoreString:e,sets:n};const{scoreString:o,removed:s}=XN({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}=eM({brackets:RN,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}=eM({brackets:MN,scoreString:i}),{lastOpenBracketIndex:s,isTiebreakEntry:u}=eM({brackets:RN,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($N),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($N)}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 eM({brackets:t=MN,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 nM(t){const{lowValue:e=0,NoAD:n=!1,tiebreakTo:r}=t||{};return e+1>=r?e+(n?1:2):parseInt(r)}function rM({matchUpFormat:t,matchUpStatus:e,winningSide:n,sets:r}){const i=Wp(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 NN.includes(e)&&n&&(c=n),{matchUpWinningSide:c}}function iM({analysis:t,set:e}){const n=xT({set:e}),{isDecidingSet:r,isTiebreakSet:i,matchUpScoringFormat:a}=t;return _T({matchUpScoringFormat:a,isDecidingSet:r,isTiebreakSet:i,set:e})&&n}function aM({lowSide:t,value:e,sets:n,scoreString:r,winningSide:i,matchUpStatus:a}){let o;return e===ON?r?(o=!0,r=ZN({scoreString:r,lowSide:t,outcome:UN}),i=2===t?1:2,a=DN):(o=!0,r=ZN({scoreString:r,lowSide:t,outcome:fN}),i=2===t?1:2,a=vN):e===_N?(o=!0,r=ZN({scoreString:r,lowSide:t,outcome:fN}),i=2===t?1:2,a=vN):e===xN?(o=!0,n=[],r=hN,i=2===t?1:2,a=wN):e===FN&&r?(o=!0,r=ZN({scoreString:r,lowSide:t,outcome:IN}),a=PN,i=void 0):e===kN?(o=!0,r=ZN({scoreString:r,lowSide:t,outcome:gN}),a=TN,i=void 0):e===LN&&r&&(o=!0,r=ZN({scoreString:r,lowSide:t,outcome:SN}),a=bN,i=void 0),{updated:o,sets:n,scoreString:r,matchUpStatus:a,winningSide:i}}function oM({matchUpFormat:t,scoreString:e,winningSide:n,value:r,sets:i}){const a=(i?.filter((t=>t?.winningSide))?.length||0)+(n?0:1),o=Wp(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}=eM({brackets:MN,scoreString:e}),{isTiebreakEntry:m}=eM({brackets:RN,scoreString:e}),f=l||m,h=!!c.tiebreakSet,g=e?.[e.length-1]?.trim(),I=e&&!isNaN(g),U=!f&&g===qN,S=l&&jN.includes(g),y=m&&jN.includes(g),v=m&&g===$N,w=e?.split(""),[P]=RN.split(""),D=w&&Math.max(...T(P,w)),b=w&&Math.max(...T($N,w)),N=w&&b>D,M=i[i.length-1]?.winningSide,R=i?.length&&!M,A=yN.find((t=>e?.indexOf(t)>=0)),E=!isNaN(r),C=r===VN,O=GN.includes(r),F=e?.split("").find((t=>jN.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]=RN.split(""),a=t.split(""),o=Math.max(...T(r,a)),s=Math.max(...T(i,a)),c=Math.max(...T($N,a));return n&&o>s&&c>o}({scoreString:e}));return{isTiebreakSetValue:h&&E,matchUpScoringFormat:o,setNumber:a,setFormat:c,matchTiebreakHasJoiner:N,isGameScoreEntry:R,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:M,isInvalidSetTiebreakValue:C&&f&&S,isInvalidMatchTiebreakValue:k,isTiebreakEntry:f,isSetTiebreakEntry:l,isMatchTiebreakEntry:m,isIncompleteSetScore:U,isIncompleteSetTiebreak:S,isIncompleteMatchTiebreak:y,isPartialMatchTiebreakValue:v}}function sM({matchUp:t}){const{extension:e}=Fr({name:Ja,element:t});if(!e)return{error:On};const{history:n=[],undoHistory:r=[]}=e.value;return{history:n,undoHistory:r,...E}}function cM({undoHistory:t,history:e,matchUp:n}){return Cr({element:n,extension:{value:{history:e,undoHistory:t},name:Ja}})}var uM=Object.freeze({__proto__:null,addGame:function({matchUp:t,game:e}){if("object"!=typeof e)return{error:Nn,context:{game:e}};const{history:n=[]}=sM({matchUp:t});return n.push(e),cM({matchUp:t,history:n})},addPoint:function({matchUp:t,point:e}){if(!e||!t)return{error:ae};if("object"!=typeof e)return{error:Nn,context:{point:e}};const{history:n=[]}=sM({matchUp:t});return n.push(e),cM({matchUp:t,history:n})},addSet:function({matchUp:t,set:e}){if("object"!=typeof e)return{error:ae};const{history:n=[]}=sM({matchUp:t});return n.push(e),cM({matchUp:t,history:n})},addShot:function({matchUp:t,shot:e}){if("object"!=typeof e)return{error:ae};const{history:n=[]}=sM({matchUp:t});return n.push(e),cM({matchUp:t,history:n})},analyzeSet:LT,calculateHistoryScore:function(t){if(!t)return{error:ae};const{matchUp:e,updateScore:n}=t;if(!e)return{error:zt};const r=sM({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(!$g({matchUpFormat:i}))return{error:Bt};const a=Wp(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:M}=b||{},R=()=>{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(),R()},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:[]},R();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=M?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=qw({...d,matchUpFormat:i}),d.scoreStringSide2=qw({...d,matchUpFormat:i,reversed:!0}),g=l||g,n&&(e.score=d),{...E,servingSide:g,score:d}},checkScoreHasValue:Gc,checkSetIsComplete:_T,clearHistory:function({matchUp:t}){return cM({matchUp:t})},generateScoreString:qw,generateTieMatchUpScore:Kg,getSetComplement:qT,getTiebreakComplement:$T,isValidMatchUpFormat:$g,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(!KN.includes(r))return{updated:!1,info:"invalid key"};u&&(e=3-e);const{matchUpWinningSide:f}=rM({sets:a,winningSide:o,matchUpStatus:s,matchUpFormat:c});o=f;const h=oM({value:r,winningSide:o,scoreString:i,sets:a,matchUpFormat:c});if(WN.includes(r)&&(r=qN),h.hasOpener&&h.isTiebreakEntry&&!h.isTiebreakSet&&m&&0===n(r)&&(h.isTiebreakCloser=!0),GN.includes(r)&&h.hasOpener&&(r=""),GN.includes(r)&&(r=VN),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===CN||(e=[{setNumber:1}]);const l=e.length-1;if(BN.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}=aM({lowSide:c,value:u,sets:e,scoreString:i,matchUpStatus:o,winningSide:a}))}else if(u===CN){if(({scoreString:i,sets:e,outcomeRemoved:p}=tM({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===VN){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===qN&&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(BN.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}=aM({lowSide:e,sets:a,scoreString:i,matchUpStatus:s,winningSide:o,value:r}));else if(r===CN)p=!0,({scoreString:i,sets:a}=tM({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!==qN||h.isMatchTiebreakEntry)if(r===$N&&h.isMatchTiebreakEntry&&!h.isSetTiebreakEntry)h.matchTiebreakHasJoiner?l="existing joiner":h.isNumericEnding&&(p=!0,i+=$N);else if([qN,$N].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=iM({analysis:t,set:r[r.length-1]});o.winningSide=n||void 0,c?e+=MN.split("")[0]:t.isDecidingSet||(e+=mN)}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?MN:RN,e=t.split("").reverse()[0],n=t.split("")[0],r=a[a.length-1],{tiebreakFormat:o}=h.setFormat,{tiebreakTo:s,NoAD:c}=o||{},u=xT({set:r});if(!h.isTiebreakSet){const t=parseInt(i.split(n).reverse()[0]),e=nM({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+=mN);const d=iM({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]=RN.split("");if(t.isMatchTiebreakEntry||(i+=p),a[t.setNumber-1]){const{lastOpenBracketIndex:t}=eM({brackets:RN,scoreString:i}),p=(i.slice((t??0)+1)+(e?"":o)).split($N);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($N),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=nM({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($N),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]=MN.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=MN.split("")[0];n=(n||"")+(u.join(qN)+(s?d:mN));const p={side1Score:u[0],side2Score:u[1]},l=iM({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}=tM({analysis:h,scoreString:i,sets:a,lowSide:e})),s=void 0);if(p){a=a?.filter(Boolean);const{matchUpWinningSide:t}=rM({sets:a,winningSide:o,matchUpStatus:s,matchUpFormat:c});return o=t,!t||s&&![Bo,ko].includes(s)?!i||o||[PN,TN,bN].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:Wp,parseScoreString:WT,redo:function({matchUp:t}){const{history:e=[],undoHistory:n=[]}=sM({matchUp:t});return n.length&&e.push(n.pop()),cM({matchUp:t,history:e,undoHistory:n})},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 br({winningSide:r?3-r:void 0,side1TiebreakScore:n,side2TiebreakScore:e,side1Score:a,side2Score:i,setNumber:o})}));return{reversedScore:{sets:n,scoreStringSide1:qw({sets:n}),scoreStringSide2:qw({sets:n,reversed:!0})},...E}},setServingSide:function({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:ne};const{history:n=[]}=sM({matchUp:t});return n.push({srv:e}),cM({matchUp:t,history:n})},stringifyMatchUpFormat:Bg,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=uN[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(pN);let h=Zb(m);return h||(m=e.toString().replace(/\D/g,""),d?.removed&&(d.removed=void 0),f(lN),h=Zb(m),h||(m="")),l.forEach((t=>{dN[t]||(dN[t]=0),dN[t]+=1})),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:d,isValid:h,score:m}},umo:{},undo:function({matchUp:t}){const{history:e=[],undoHistory:n=[]}=sM({matchUp:t});return n.push(e.pop()),cM({matchUp:t,history:e,undoHistory:n})},updateTieMatchUpScore:tI,validateScore:Fw,validateTieFormat:Hg});function dM({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=xp(o);else if(n){if(t&&(!i||!r)){const e=Dg({drawDefinition:t,matchUpId:n});if(e.error)return e;if(e.matchUp?.matchUpType!==Jc)return Nr({result:{error:Yt},stack:s});r||(r=e.structure),i||(i=e.matchUp)}c=Lp({item:i,drawDefinition:t,structure:r,event:o})||Lp({item:r,drawDefinition:t,structure:r,event:o})||xp(t)||xp(o)}else if(t&&e){if(!r){const n=Qs({drawDefinition:t,structureId:e});if(n.error)return n;r=n?.structure}c=Lp({item:r,drawDefinition:t,structure:r,event:o})||xp(t)||xp(o)}else c=xp(t)||xp(o);return c?{...E,structure:r,tieFormat:c,matchUp:i}:Nr({result:{error:Gt},stack:s})}function pM({matchUp:t,updateInProgressMatchUps:e}){return!t.winningSide&&![Ho].includes(t.matchUpStatus)&&(e||t.matchUpStatus!==Fo&&!Gc(t))}function lM({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 mM({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===Bo)).map(wi("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 fM({drawDefinition:t,auditData:e}){const{extension:n}=Fr({name:oo,element:t});Cr({element:t,extension:{name:oo,value:Array.isArray(n?.value)?n?.value.concat(e):[e]}})}function hM({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&&!$g({matchUpFormat:o}))return Nr({result:{error:Nn},context:{matchUpFormat:o},stack:T});if(r&&"string"!=typeof r)return Nr({result:{error:Nn},context:{collectionName:r},stack:T});if(h&&!Object.values(ll).includes(h))return Nr({result:{error:Nn},context:{gender:h},stack:T});if(m&&"object"!=typeof m)return Nr({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 Nr({result:{error:ae},stack:T});if(Object.values(D).filter(Boolean).length>1)return Nr({info:"Only one value assignment allowed per collectionDefinition",result:{error:Nn},stack:T});let b=dM({drawDefinition:a,structureId:d,matchUpId:l,eventId:f,event:I});if(b.error)return Nr({result:b,stack:T});const{matchUp:N,structure:M,tieFormat:R}=b,A=Jg(R),C=R?.collectionDefinitions.find((t=>t.collectionId===c)),O=A?.collectionDefinitions.find((t=>t.collectionId===c));if(!C)return Nr({info:"source collectionDefinition",result:{error:On},context:{collectionId:c},stack:T});const F=S??y??v??w;if(U){const t=Ag({matchUpCount:s??C?.matchUpCount??0,collectionValueProfiles:U});if(t.errors)return Nr({result:{error:Nn},info:t.errors,stack:T})}else if(F&&!p(F))return Nr({result:{error:Nn},info:"value is not an integer",context:{value:F},stack:T});const k=U&&(!C.collectionValueProfiles||(_=C.collectionValueProfiles,x=U,!(P(Object.keys(_),Object.keys(x)).length===Object.keys(_).length&&P(Object.values(_),Object.values(x)).length===Object.values(_).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,...br(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}=PT(A),G=br({aggregateValue:B,valueGoal:V});if(G.aggregateValue===R?.winCriteria.aggregateValue&&G.valueGoal===R?.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 Nr({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=br(A);if(b=Hg({tieFormat:q}),b.error)return Nr({result:b,stack:T});if(!L.length)return Nr({result:{...E,modifications:L}});if(R?.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 lM({from:e,to:h}).equivalent},U=dM({drawDefinition:n})?.tieFormat,S=dM({event:s})?.tieFormat;if(s&&a){for(const t of s.drawDefinitions??[])y({drawDefinition:t});s.tieFormat=Jg(i),f+=1}else if(o){if(!o.tieMatchUps)return Nr({result:{error:Yt},stack:u});const e=g(o.tieMatchUps?.map((({collectionId:t})=>t))),r=lM({to:h,from:e}),{changes:a,changesArePossible:p,cannotChangeReaon:m}=mM({matchUp:o,check:r});if(r.equivalent){if(!pM({matchUp:o,updateInProgressMatchUps:t}))return Nr({result:{error:Ue},info:"matchUp is IN_PROGRESS or COMPLETE",stack:u});o.tieFormat=Jg(i),f+=1}else{if(!p)return Nr({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,Oc({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||tT({ancestor:r.tieFormat,descendant:i}).different;a&&(r.tieFormat=Jg(i),p+=1,f+=1),(e||a)&&n&&kc({structureIds:[r.structureId],eventId:s?.eventId,drawDefinition:n})}else{if(!n)return{error:j};y({drawDefinition:n}),n.tieFormat=Jg(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 kc({structureIds:n,eventId:s?.eventId,drawDefinition:t}),n.length}function v({inheritedTieFormat:r,structure:o}){let s=0;const d=ml({matchUpFilters:{matchUpTypes:[Qc]},structure:o})?.matchUps||[];for(const o of d){const d=pM({matchUp:o,updateInProgressMatchUps:t});let p=!1;const l=lM({from:g(o.tieMatchUps?.map((({collectionId:t})=>t))),to:h});if(l.equivalent)o.tieFormat&&I(o)&&d&&(o.tieFormat=Jg(i),p=!0);else{const{changes:t,changesArePossible:e}=mM({matchUp:o,check:l});if(e&&!o.tieFormat)w({changes:t,matchUp:o,tieFormat:i,uuids:c});else{if(!r)return Nr({result:{error:Gt},stack:u});(!o.tieFormat||tT({ancestor:r,descendant:o.tieFormat}).different)&&(o.tieFormat=r,p=!0)}}p&&(s+=1,Oc({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=Jg(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(wi("collectionPosition"))),a=r.collectionDefinitions.find((t=>t.collectionId===n.collectionId)),o=Qh({matchUpsLimit:n.countChange,collectionPositionOffset:i,collectionDefinition:a,matchUp:e,uuids:t});s.push(...mi(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&&Ec({matchUps:s,drawDefinition:n,tournamentId:d,eventId:a}),o.length&&Cc({matchUpIds:o,action:"updateTieFormat",drawDefinition:n,tournamentId:d,eventId:a}),{matchUpIdsRemoved:o,matchUpsAdded:s}}}({tieFormat:q,updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:a,structure:M,eventId:f,matchUp:N,event:I}),!b.error){const{appliedPolicies:t}=Tu({tournamentRecord:e});if(t?.audit?.[oo]){fM({drawDefinition:a,auditData:br({collectionDefinition:O,drawId:a?.drawId,action:T,structureId:d,matchUpId:l,eventId:f})})}}return Nr({result:{...b,modifications:L},stack:T})}function gM({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}=PT(c);c.winCriteria=br({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=ml({matchUpFilters:{matchUpTypes:[Qc]},structure:r})?.matchUps??[]:e&&(o=Vl({matchUpFilters:{matchUpTypes:[Qc]},drawDefinition:e})?.matchUps??[]),{targetMatchUps:o.filter((e=>!e.winningSide&&e.matchUpStatus!==Ro&&(t||e.matchUpStatus!==Fo&&!Gc(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=Jg(i)),t){const t=tI({matchUpId:o.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,drawDefinition:n,event:a});if(t.error)return t;s=t.score}r&&!s&&Oc({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=br(c),I=Hg({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 kc({drawDefinition:a,eventId:l?.eventId}),{...E}}function IM({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:dM({drawDefinition:r,structureId:a,matchUpId:o,eventId:c,event:u});if(p?.error)return Nr({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=Jg(m);if(p=Hg({tieFormat:g}),p.error)return Nr({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=gM({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}=Tu({tournamentRecord:n});if(t?.audit?.[oo]){fM({drawDefinition:r,auditData:br({drawId:r?.drawId,collectionGroupNumber:e,action:d,structureId:a,matchUpId:o,eventId:c})})}}return Nr({result:{...p,modifiedCollectionIds:I},stack:d})}function UM({tieFormat:t,orderMap:e}){const n=Jg(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 SM({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 Nr({result:{error:Nn},context:{orderMap:i}});if(a&&s?.tieFormat)yM({tournamentRecord:t,event:s,orderMap:i});else if(r){const n=e&&Dg({drawDefinition:e,matchUpId:r});if(n?.error)return n;if(!(o=n.matchUp))return{error:zt};o?.tieFormat&&(o.tieFormat=UM({tieFormat:o.tieFormat,orderMap:i}),Oc({tournamentId:t?.tournamentId,eventId:s?.eventId,drawDefinition:e,matchUp:o}))}else if(n){const r=Qs({drawDefinition:e,structureId:n});if(r.error)return r;const a=r.structure;if(a?.tieFormat)a.tieFormat=UM({tieFormat:a.tieFormat,orderMap:i}),wM({eventId:s?.eventId,tournamentRecord:t,drawDefinition:e,structure:a,orderMap:i}),kc({drawDefinition:e,structureIds:[a.structureId]});else if(e.tieFormat)vM({structureIds:[n],tournamentRecord:t,drawDefinition:e,orderMap:i,event:s});else{if(!s?.tieFormat)return{error:On};yM({structureIds:[n],tournamentRecord:t,orderMap:i,event:s})}}else{if(!e?.tieFormat)return{error:On};vM({tournamentRecord:t,drawDefinition:e,orderMap:i,event:s})}return{...E}}function yM({tournamentRecord:t,structureIds:e,orderMap:n,event:r}){const i=UM({tieFormat:r.tieFormat,orderMap:n});e?.length||(r.tieFormat=i);for(const i of r.drawDefinitions??[])vM({tournamentRecord:t,drawDefinition:i,structureIds:e,orderMap:n,event:r})}function vM({tournamentRecord:t,drawDefinition:e,structureIds:n,orderMap:r,event:i}){const a=UM({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=UM({tieFormat:a.tieFormat??e.tieFormat??i?.tieFormat,orderMap:r})),wM({eventId:i?.eventId,tournamentRecord:t,drawDefinition:e,structure:a,orderMap:r}),o.push(a.structureId));kc({drawDefinition:e,structureIds:o})}function wM({tournamentRecord:t,drawDefinition:e,structure:n,orderMap:r,eventId:i}){const a=ml({matchUpFilters:{matchUpTypes:[Qc]},structure:n})?.matchUps;for(const n of a)n.tieFormat&&(n.tieFormat=UM({tieFormat:n.tieFormat,orderMap:r}),Oc({tournamentId:t?.tournamentId,drawDefinition:e,eventId:i,matchUp:n}))}function TM({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:dM({drawDefinition:r,structureId:o,matchUpId:s,eventId:c,event:d});if(l?.error)return Nr({result:l,stack:p});const m=l?.structure;u=u??l?.matchUp;const f=l?.tieFormat,h=Jg(f);if(l=Hg({tieFormat:h}),l.error)return Nr({result:l,stack:p});const g=h?.collectionDefinitions?.find((t=>t.collectionId===a));if(!g)return Nr({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}=PT(h);h.winCriteria=br({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=ml({matchUpFilters:{matchUpTypes:[Qc]},structure:m})?.matchUps??[]:r?v=Vl({matchUpFilters:{matchUpTypes:[Qc]},drawDefinition:r})?.matchUps??[]:d&&(v=_l({matchUpFilters:{matchUpTypes:[Qc]},drawDefinition:r})?.matchUps??[]);const w=(v||[]).filter((n=>{const r=n.tieMatchUps?.filter((t=>t.collectionId===a)),i=r?.some(Gc),o=!(!e||!n.tieFormat)&&tT({descendant:n.tieFormat,ancestor:h})?.different;return t&&!i||!n.winningSide&&n.matchUpStatus!==Ro&&(t||n.matchUpStatus!==Fo&&!Gc(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=kw({matchUpId:e.matchUpId,tieMatchUpId:u?.matchUpId,winningSide:void 0,removeScore:!0,tournamentRecord:n,drawDefinition:r,event:d});if(t.error)return t;if(t=Dg({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=Jg(h)),t){const t=tI({matchUpId:e.matchUpId,exitWhenNoValues:!0,tournamentRecord:n,drawDefinition:r,event:d});if(t.error)return t}Oc({tournamentId:n?.tournamentId,eventId:d?.eventId,drawDefinition:r,context:p,matchUp:e})}T.length&&Cc({tournamentId:n?.tournamentId,matchUpIds:T,eventId:d?.eventId,drawDefinition:r});const P=br(h);if(l=Hg({tieFormat:P}),l.error)return Nr({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};kc({drawDefinition:r,eventId:d?.eventId});const{appliedPolicies:D}=Tu({tournamentRecord:n});if(D?.audit?.[oo]){fM({drawDefinition:r,auditData:br({drawId:r?.drawId,action:p,collectionId:a,structureId:o,matchUpId:s,eventId:c})})}return{tieFormat:P,deletedMatchUpIds:T,targetMatchUps:w,...E}}function PM({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 Nr({result:{error:ae},stack:p});let l=c?void 0:dM({drawDefinition:r,structureId:o,matchUpId:s,eventId:u,event:d});if(l?.error)return Nr({result:l,stack:p});const m=l?.structure;c=c||l?.matchUp;const f=l?.tieFormat,h=f?.winCriteria.valueGoal,g=Jg(f);if(l=Hg({tieFormat:g}),l.error)return Nr({result:l,stack:p});for(const t of g.collectionDefinitions){const{collectionId:e,collectionGroupNumber:n}=t;if(n&&i.includes(e))return Nr({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],gM({updateInProgressMatchUps:t,originalValueGoal:h,tournamentRecord:e,drawDefinition:r,tieFormatName:a,structureId:o,structure:m,tieFormat:g,matchUpId:s,matchUp:c,eventId:u,event:d})}function DM({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=Tu({tournamentRecord:r,drawDefinition:s,event:h}).appliedPolicies??{},U=i?.[ga]??I?.[ga];a=a??U?.participants?.enforceCategory;const S=!1!==(u??U?.participants?.enforceGender),y=!(!(n??h?.category)||!1===a),v=!(!(o??h?.gender)||!S),w=Wg({referenceCategory:n??h?.category,collectionDefinition:e,referenceGender:o,checkCategory:y,checkGender:v,event:h});if(w.error)return Nr({result:w,stack:g});let T=l?.tieFormat?void 0:dM({drawDefinition:s,structureId:d,matchUpId:p,eventId:m,event:h});if(T?.error)return Nr({result:{error:T.error},stack:g});const P=T?.structure;l=l??T?.matchUp;const D=l?.tieFormat??T?.tieFormat,b=Jg(D);if(T=Hg({tieFormat:b}),T?.error)return Nr({result:{error:T.error},stack:g});if(e.collectionId){if(b.collectionDefinitions.map((({collectionId:t})=>t)).includes(e.collectionId))return Nr({context:{collectionId:e.collectionId},result:{error:Mn}})}else e.collectionId=wp();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:M}=PT(b);b.winCriteria=br({aggregateValue:N,valueGoal:M});const R=D?.winCriteria.valueGoal,A=D?.winCriteria.aggregateValue;(R&&R!==M||N&&!A)&&(c?b.tieFormatName=c:delete b.tieFormatName);const C=[],O=[];let F=[];const k=br(b);if(T=Hg({tieFormat:k}),T?.error)return Nr({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=bM({updateInProgressMatchUps:t,collectionDefinition:e,structure:r,uuids:f});O.push(...n.newMatchUps),F.push(...n.targetMatchUps),C.push(r.structureId)}NM({modifiedMatchUps:F,eventId:h?.eventId,modifiedStructureIds:C,tournamentRecord:r,drawDefinition:s,addedMatchUps:O,stack:g})}else if(d&&P){P.tieFormat=k;const n=bM({updateInProgressMatchUps:t,collectionDefinition:e,structure:P,uuids:f});O.push(...n.newMatchUps),F=n.targetMatchUps,NM({modifiedMatchUps:F,eventId:h?.eventId,modifiedStructureIds:C,tournamentRecord:r,drawDefinition:s,addedMatchUps:O,stack:g})}else if(p&&l){if(!pM({matchUp:l,updateInProgressMatchUps:t}))return Nr({result:{error:Ue},stack:g});l.tieFormat=k;const n=Qh({collectionDefinition:e,matchUp:l,uuids:f});Array.isArray(l.tieMatchUps)||(l.tieMatchUps=[]),l.tieMatchUps.push(...n),O.push(...n),NM({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=bM({updateInProgressMatchUps:t,collectionDefinition:e,structure:n,uuids:f});C.push(n.structureId),O.push(...r.newMatchUps),F.push(...r.targetMatchUps)}NM({modifiedMatchUps:F,eventId:h?.eventId,tournamentRecord:r,drawDefinition:s,addedMatchUps:O,stack:g})}if(I?.audit?.[oo]){fM({drawDefinition:s,auditData:br({drawId:s?.drawId,collectionDefinition:e,action:g,structureId:d,matchUpId:p,eventId:m})})}return{tieFormat:k,targetMatchUps:F,addedMatchUps:O,...E}}function bM({updateInProgressMatchUps:t,collectionDefinition:e,structure:n,uuids:r}){const i=[],a=ml({matchUpFilters:{matchUpTypes:[Qc]},structure:n})?.matchUps,o=a.filter((e=>pM({matchUp:e,updateInProgressMatchUps:t})&&!e.tieFormat));for(const t of o){const n=Qh({collectionDefinition:e,matchUp:t,uuids:r});Array.isArray(t.tieMatchUps)||(t.tieMatchUps=[]),t.tieMatchUps.push(...n),i.push(...n)}return{newMatchUps:i,targetMatchUps:o}}function NM({modifiedStructureIds:t,tournamentRecord:e,modifiedMatchUps:n,drawDefinition:r,addedMatchUps:i,eventId:a,stack:o}){Ec({tournamentId:e?.tournamentId,matchUps:i,drawDefinition:r,eventId:a}),n?.forEach((t=>{Oc({tournamentId:e?.tournamentId,drawDefinition:r,context:o,matchUp:t,eventId:a})})),kc({structureIds:t,drawDefinition:r,eventId:a})}function MM({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(!Hg({tieFormat:n}).valid)return Nr({result:{error:Lt},info:"falied validation",stack:d});const p=dM({drawDefinition:i,structureId:a,matchUpId:o,eventId:s,event:u});if(p.error)return Nr({result:p,stack:d});const{matchUp:l,tieFormat:m}=p,f=Jg(m),g=tT({descendant:n,ancestor:f});if(g.invalid)return Nr({context:{invalid:g.invalid},result:{error:Lt},stack:d});if(!g?.different)return Nr({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(wi("collectionId")),w=[];let T;const P=n.tieFormatName;for(const e of n.collectionDefinitions){if(v.includes(e.collectionId))continue;const n=hM({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 Nr({result:n,stack:d});n.tieFormat&&(T=n.tieFormat)}for(const e of y){const n=DM({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 Nr({result:n,stack:d});n.tieFormat&&(T=n.tieFormat)}for(const n of S){const c=TM({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 Nr({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:Jg(T),modifications:w,...E}}function RM({tournamentRecord:t}){if(!t)return{error:x};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){tT({descendant:t.tieFormat,ancestor:e}).different||(n=e.tieFormatId)}if(n)t.tieFormatId=n,delete t.tieFormat;else{const n=mi(t.tieFormat,void 0,!0);n.tieFormatId||(n.tieFormatId=wp()),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,Oc({tournamentId:t?.tournamentId,eventId:n.eventId,matchUp:i}))},s=t=>{const n=mi(t.tieFormat,void 0,!0);n.tieFormatId||(n.tieFormatId=wp()),r.push(n),e+=1,o(t.matchUpId,n.tieFormatId)},c=_l({matchUpFilters:{matchUpTypes:[Jc]},event:n}),u=c.matchUps??[];for(const t of u){let e;for(const n of r){t.tieFormat&&tT({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}}var AM=Object.freeze({__proto__:null,addCollectionDefinition:DM,addCollectionGroup:PM,aggregateTieFormats:RM,modifyCollectionDefinition:hM,modifyTieFormat:MM,orderCollectionDefinitions:SM,removeCollectionDefinition:TM,removeCollectionGroup:IM}),EM=Object.freeze({__proto__:null,addCollectionDefinition:DM,addCollectionGroup:PM,aggregateTieFormats:RM,compareTieFormats:tT,getTieFormat:vb,modifyCollectionDefinition:hM,modifyTieFormat:MM,mutate:AM,orderCollectionDefinitions:SM,query:wb,removeCollectionDefinition:TM,removeCollectionGroup:IM,tieFormatGenderValidityCheck:Og,validateCollectionDefinition:Wg});const CM={ABANDONED:"ABANDONED",ACTIVE:"ACTIVE",CANCELLED:"CANCELLED",COMPLETED:"COMPLETED",IN_PROGRESS:"IN_PROGRESS"};function OM({tournamentRecord:t,status:e}){return t?e&&!Object.keys(CM).includes(e)?{error:Nn,info:"Unknown status"}:(t.tournamentStatus=e,{...E}):{error:x}}function FM({tournamentRecord:t,onlineResource:e,organisationId:n,participantId:r,personId:i,courtId:a,venueId:o}){if(!t)return{error:x};if(!Ui(e))return{error:ae};if(3!==P(Object.keys(e),["resourceSubType","resourceType","identifier"]).length)return Nr({result:{error:Pn},context:{onlineResource:e}});if(n){if(t.parentOrganisation?.parentOrganisationId!==n)return Nr({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 Nr(i?{result:{error:On}}:{result:{error:Ee}});if(i){if(n.person?.personId!==i)return Nr({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 Nr({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 Nr({result:{error:rn}});n.onlineResources||(n.onlineResources=[]),n.onlineResources.push(e)}else t.onlineResources||(t.onlineResources=[]),t.onlineResources.push(e);return{...E}}function kM({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:x}}function _M({tournamentRecord:t,notes:e}){return t?bg({element:t,notes:e}):{error:x}}function xM({tournamentRecord:t,categories:e}){return t?(e=(e||[]).filter((t=>t.categoryName&&t.type)),t.tournamentCategories=e,{...E}):{error:x}}function LM({tournamentRecord:t,startDate:e,endDate:n}){if(!t)return{error:x};if(e&&!xr.test(e)||n&&!xr.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=xl({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(!gP({scheduledDates:i,tournamentRecord:t}).clearedScheduleCount)return{error:Y}}return{unscheduledMatchUpIds:a}}({tournamentRecord:t})?.unscheduledMatchUpIds;return function({tournamentRecord:t}){if(!t)return{error:x};const{startDate:e,endDate:n}=t,r=zr(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=Qr(t.startTime),r=Qr(t.endTime);return e.startTime&&Qr(e.startTime)<n&&(t.startTime=e.startTime),e.endTime&&Qr(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}),cr({topic:Sc,payload:{startDate:e,endDate:n}}),{...E,unscheduledMatchUpIds:i}}function BM({tournamentRecord:t,startDate:e}){return LM({tournamentRecord:t,startDate:e})}function VM({tournamentRecord:t,endDate:e}){return LM({tournamentRecord:t,endDate:e})}var jM=Object.freeze({__proto__:null,addDrawDefinitionExtension:Aa,addEventExtension:Ea,addEventTimeItem:Uh,addExtension:Cr,addNotes:bg,addOnlineResource:FM,addParticipantExtension:Ca,addParticipantTimeItem:gh,addTimeItem:hh,addTournamentExtension:Ra,addTournamentTimeItem:Ih,removeDrawDefinitionExtension:Fa,removeEventExtension:ka,removeExtension:Ar,removeNotes:Ng,removeParticipantExtension:_a,removeTournamentExtension:Oa,setTournamentCategories:xM,setTournamentDates:LM,setTournamentEndDate:VM,setTournamentName:kM,setTournamentNotes:_M,setTournamentStartDate:BM,setTournamentStatus:OM}),GM=Object.freeze({__proto__:null,addDrawDefinitionExtension:Aa,addEventExtension:Ea,addEventTimeItem:Uh,addExtension:Cr,addNotes:bg,addOnlineResource:FM,addParticipantExtension:Ca,addParticipantTimeItem:gh,addTimeItem:hh,addTournamentExtension:Ra,addTournamentTimeItem:Ih,analyzeDraws:lI,analyzeTournament:Sb,getAllowedDrawTypes:pS,getAllowedMatchUpFormats:dS,getAppliedPolicies:Tu,getCompetitionDateRange:uD,getCompetitionPenalties:gb,getPolicyDefinitions:Pu,getTournamentInfo:Ay,getTournamentPenalties:hb,getTournamentPersons:Ib,getTournamentStructures:Lf,getTournamentTimeItem:Nl,mutate:jM,query:yb,removeDrawDefinitionExtension:Fa,removeEventExtension:ka,removeExtension:Ar,removeNotes:Ng,removeParticipantExtension:_a,removeTournamentExtension:Oa,setTournamentCategories:xM,setTournamentDates:LM,setTournamentEndDate:VM,setTournamentName:kM,setTournamentNotes:_M,setTournamentStartDate:BM,setTournamentStatus:OM}),qM=Object.freeze({__proto__:null,generateCourts:bv});function $M(t){if(!t?.tournamentRecord&&!Array.isArray(t?.venueMatchUps))return{error:x};if(!t?.courtId)return{error:ie};const{scheduleVisibilityFilters:e,tournamentRecord:n,matchUpFilters:r,venueMatchUps:i,courtId:a}=t,{schedulingProfile:o}=by({tournamentRecord:n});if(Array.isArray(i))return{matchUps:c({matchUps:i,courtId:a})};const{matchUps:s}=xl({scheduleVisibilityFilters:e,tournamentRecord:n,matchUpFilters:r});return{matchUps:c({matchUps:s,courtId:a})};function c({matchUps:t,courtId:e}){return fT({matchUps:t.filter((t=>{const n=t.schedule?.allocatedCourts?.map((({courtId:t})=>t));return t.schedule?.courtId===e||n?.includes(e)})),schedulingProfile:o})}}function WM({tournamentRecord:t,dateAvailability:e,disableNotice:n,venueMatchUps:r,courtId:i,force:a}){if(!t)return{error:x};if(!i)return{error:ie};const o=jP({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(VP);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(si(oi(n),oi(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=Np({tournamentRecord:t,courtId:i});if(u.error)return u;const{court:d,venue:p}=u,{matchUps:l}=$M({tournamentRecord:t,venueMatchUps:r,courtId:i});if(l?.length){const e=Tu({tournamentRecord:t})?.appliedPolicies,n=a??e?.[va]?.allowDeletionWithScoresPresent?.courts,r=[];r.length&&(n||console.log("throw error: scheduled court matchUps",r.length))}return d&&(d.dateAvailability=e,!n&&p&&cr({payload:{venue:p,tournamentId:t.tournamentId},topic:yc,key:p.venueId})),{...E,totalMergeCount:c}}function HM({matchUpsCount:t=0}){return{error:Gn,info:`Schedule would be deleted from ${t} ${1===t?"matchUp":"matchUps"}; use { force: true }`}}function zM({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:x};({drawDefinition:e}=kp({tournamentRecord:t,drawId:r}))}if(e)({matchUp:i}=Dg({drawDefinition:e,matchUpId:n}));else{if(!t)return{error:x};const e=xl({tournamentRecord:t,inContext:!1}).matchUps??[];({matchUp:i}=Pg({matchUps:e,matchUpId:n}))}if(!i)return{error:Wt};if(i.timeItems){i.timeItems.find((t=>[Sd,Ud].includes(t.itemType)))&&(i.timeItems=i.timeItems.filter((({itemType:t})=>![Sd,Ud].includes(t))),Oc({tournamentId:t?.tournamentId,context:"removeCourtAssignment",drawDefinition:e,matchUp:i}))}return{...E}}function YM(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:x};const a=Ll({tournamentRecords:i,contextFilters:{venueIds:[n]}}).matchUps??[],o=Tu({tournamentRecord:e})?.appliedPolicies,s=r??o?.[va]?.allowDeletionWithScoresPresent?.venues;if(a.length&&!s)return HM({matchUpsCount:a.length});for(const t of Object.values(i)){for(const e of a){const n=zM({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&&cr({payload:{venueId:n,tournamentId:t.tournamentId},topic:uc,key:n})}return My({tournamentRecords:i}),{...E}}function KM({tournamentRecord:t,venueIds:e,force:n}){if(!t)return{error:x};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=YM({tournamentRecord:t,venueId:e,force:n});if(i.error)return i}}return{...E}}function JM(t){const{courtIds:e,dates:n}=t,r=tu(t),i=na(t,[{[Pi]:!0,[Li]:!0}]);if(i.error)return i;for(const t of Object.values(r))QM({tournamentRecord:t,courtIds:e,dates:n});return{...E}}function QM({tournamentRecord:t,courtIds:e,dates:n}){const r=!Array.isArray(n)||!n.length||{dates:n},i=t=>Cr({extension:{value:r,name:ja},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 ZM(t){const{tournamentRecords:e,tournamentId:n,venueIds:r}=t,i=na(t,[{[Pi]:!0,[Bi]:!0}]);if(i.error)return i;const a=Object.keys(e).filter((t=>!n||t===n));for(const t of a){XM({tournamentRecord:e[t],venueIds:r})}return{...E}}function XM({tournamentRecord:t,venueIds:e}){for(const n of t.venues||[])if(e?.includes(n.venueId)){const t=Cr({creationTime:!1,element:n,extension:{name:ja,value:!0}});if(t.error)return t}return{...E}}function tR(t){const e=tu(t),n=[{[Pi]:!0}];!t.enableAll&&n.push({[Li]:!0});const r=na(t,n);if(r.error)return r;const{enableAll:i,courtIds:a,dates:o}=t;for(const t of Object.values(e))eR({tournamentRecord:t,courtIds:a,enableAll:i,dates:o});return{...E}}function eR({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}=Fr({element:t,name:ja});if(e){const n=e.value;Array.isArray(n.dates)&&(n.dates=n.dates.filter((t=>!r.includes(t)))),Cr({extension:{name:ja,value:n},creationTime:!1,element:t})}}else Ar({element:t,name:ja});return{...E}}function nR(t){const e=tu(t),n=[{[Pi]:!0}];!t.enableAll&&n.push({[Bi]:!0});const r=na(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))&&Ar({element:e,name:ja});return{...E}}function rR(t){const{courtId:e,disableNotice:n,force:r}=t,i=tu(t),a=na(t,[{[Pi]:!0,[ji]:!0}]);if(a.error)return a;let o,s;for(const t of Object.values(i)){if(s=iR({tournamentRecord:t,disableNotice:n,courtId:e,force:r}),s.error&&s.error!==tn)return s;s.success&&(o=!0)}return o?{...E}:s}function iR({tournamentRecord:t,disableNotice:e,courtId:n,force:r}){const i=Np({tournamentRecord:t,courtId:n});if(i.error)return i;const a=i.venue,{matchUps:o}=$M({tournamentRecord:t,courtId:n}),s=Tu({tournamentRecord:t})?.appliedPolicies,c=r??s?.[va]?.allowDeletionWithScoresPresent?.courts;if(o?.length&&!c)return HM({matchUpsCount:o.length});for(const e of o??[]){const n=zM({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||cr({payload:{venue:a,tournamentId:t.tournamentId},topic:yc,key:a.venueId})),{...E}}function aR(t){const{disableNotice:e,modifications:n,courtId:r,force:i,venueMatchUps:a}=t,o=tu(t);if(!Object.keys(o).length)return{error:_};let s;for(const t of Object.values(o)){const o=oR({tournamentRecord:t,disableNotice:e,venueMatchUps:a,modifications:n,courtId:r,force:i});if(o?.error)return o;s=!0}return s?{...E}:undefined}function oR({tournamentRecord:t,disableNotice:e,venueMatchUps:n,modifications:r,courtId:i,force:a}){if(!t)return{error:x};if(!i)return{error:ie};if(!r||"object"!=typeof r)return{error:Pn};const o=Np({tournamentRecord:t,courtId:i});if(o.error)return o;const{venue:s,court:c}=o,u=Object.keys(xP()).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=WM({dateAvailability:r.dateAvailability,tournamentRecord:t,venueMatchUps:n,disableNotice:e,courtId:i,force:a});if(o.error)return o}return e||cr({payload:{venue:s,tournamentId:t.tournamentId},topic:yc,key:s?.venueId}),{...E,court:mi(c)}}const sR=()=>({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,addresses:[],contacts:[],courts:[],roles:[]});function cR(t){const{modifications:e,venueId:n,force:r}=t,i=tu(t);if(!Object.keys(i).length)return{error:_};if("string"!=typeof n)return{error:an};let a,o;for(const t of Object.values(i)){const i=uR({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 My({tournamentRecords:i}),o?{...E}:{error:a}}function uR({tournamentRecord:t,modifications:e,venueId:n,force:r}){if(!t)return{error:x};if(!e||"object"!=typeof e)return{error:Pn};if(!n)return{error:an};const i=Tu({tournamentRecord:t})?.appliedPolicies,a=r??i?.[va]?.allowDeletionWithScoresPresent?.venues,{matchUps:o}=function({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:n,venueId:r}){if(!e)return{error:x};if(!r)return{error:an};const{schedulingProfile:i}=by({tournamentRecord:e}),{matchUps:a}=xl({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:n});return{matchUps:function({matchUps:t,venueId:e}){return fT({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=Dp({tournamentRecord:t,venueId:n});if(s.error)return s;const c=s.venue,u=Object.keys(sR()).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=m.length&&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=$M({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 HM({matchUpsCount:n});c.courts=c.courts?.filter((t=>m.includes(t.courtId))),pP({schedule:{courtId:"",scheduledDate:""},matchUpDetails:h,removePriorValues:!0,tournamentRecord:t})}if(e.courts)for(const i of e.courts){const{courtId:e}=i||{};let a=aR({modifications:i,disableNotice:!0,tournamentRecord:t,venueMatchUps:o,courtId:e,force:r});if(a.error===tn&&(a=GP({disableNotice:!0,tournamentRecord:t,venueId:n,court:i})),a.error)return a}return My({tournamentRecord:t}),c&&cr({payload:{venue:c,tournamentId:t.tournamentId},topic:yc,key:c?.venueId}),{...E,venue:mi(c)}}var dR=Object.freeze({__proto__:null,addCourt:GP,addCourts:qP,addVenue:Tp,deleteCourt:rR,deleteVenue:YM,deleteVenues:KM,disableCourts:JM,disableVenues:ZM,enableCourts:tR,enableVenues:nR,modifyCourt:aR,modifyCourtAvailability:WM,modifyVenue:cR}),pR=Object.freeze({__proto__:null,addCourt:GP,addCourts:qP,addVenue:Tp,deleteCourt:rR,deleteVenue:YM,deleteVenues:KM,disableCourts:JM,disableVenues:ZM,enableCourts:tR,enableVenues:nR,generate:qM,generateCourts:bv,getCompetitionVenues:Dy,getCourts:Db,getVenuesAndCourts:Py,modifyCourt:aR,modifyCourtAvailability:WM,modifyVenue:cR,mutate:dR,publicFindVenue:bp,query:bb}),lR=Object.freeze({__proto__:null,competitionGovernor:Io,drawsGovernor:ay,entriesGovernor:Sy,eventGovernor:Uv,generationGovernor:xv,matchUpFormatGovernor:Lv,matchUpGovernor:GT,mocksGovernor:UD,participantGovernor:ZD,policyGovernor:rb,publishingGovernor:fb,queryGovernor:Nb,reportGovernor:Ab,scheduleGovernor:$b,scoreGovernor:uM,tieFormatGovernor:EM,tournamentGovernor:GM,venueGovernor:pR});const mR=["collectionId","collectionPosition","drawPositions","extensions","finishingPositionRange","finishingRound","isMock","matchUpId","matchUpStatus","matchUpStatusCodes","orderOfFinish","processCodes","roundNumber","tieFormat","tieMatchUps","roundPosition","score","sides","winnerMatchUpId","loserMatchUpId","matchUpDuration","winningSide"];function fR(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,fR(t[i],e,n.concat(i)))),{})}var hR=Object.freeze({__proto__:null,JSON2CSV:function(t,e){if(e&&"object"!=typeof e)return{error: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{error: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=>fR(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 M=b.map((t=>t.join(h)));return a?M.map((t=>{const e=t.split(h);return Object.assign({},...e.map(((t,e)=>({[T[e]]:t}))))})):i?[T.map(P).join(h),...M].join(g):M.join(g)},UUID:wp,UUIDS:function(t=1){return w(0,t).map(wp)},allNumeric:M,attributeFilter:pa,chunkArray:N,chunkByNth:A,chunkSizeProfile:function t(e,[n,...r]){return e.length?[e.slice(0,n),...t(e.slice(n),[...r,n])]:[]},constantToString:zm,countValues:function(t){return I(g(t))},createMap:yi,dateTime:li,definedAttributes:br,dehydrateMatchUps:function({tournamentRecord:t}){if(!t)return{error:x};if("object"!=typeof t||!t.tournamentId)return{error:Nn};const{matchUps:e}=xl({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))mR.includes(t)||delete n[t];n.sides&&n.drawPositions&&!n.tieMatchUps&&delete n.sides,o&&(n.matchUpFormat=o)}}(e,n)}return{...E}},extractAttributes:vi,flattenJSON:fR,generateDateRange:zr,generateHashCode:function(t){if(null===t||"object"!=typeof t)return;const e=JSON.stringify(t),n=Ti(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:SD,groupValues:I,hasAttributeValues:t=>e=>Object.keys(t).every((n=>e[n]===t[n])),instanceCount:g,intersection:P,isConvertableInteger:p,isNumeric:s,isOdd:c,isPowerOf2:r,makeDeepCopy:mi,matchUpSort:Bl,nearestPowerOf2:o,nextPowerOf2:u,noNulls:function(t){return Array.isArray(t)?t?.map((t=>null===t?void 0:t)):t},noNumeric:R,numericSort:e,occurrences:function(t,e){return Array.isArray(e)&&e.reduce(((t,e)=>(t[e]=1+t[e]||1,t)),{})[t]||0},overlap:b,randomMember:v,randomPop:y,shuffleArray:f,structureSort:Ks,subSort:function(t,e,n,r){return Array.isArray(t)?[].concat(...t.slice(0,e),...t.slice(e,e+n).sort(r),...t.slice(e+n,t.length)):[]},undefinedToNull:function t(e,n){if(void 0===e)return null;if("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,visualizeScheduledMatchUps:function({scheduledMatchUps:t,showGlobalLog:e}){Wl.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=>{Hl({color:"blue",method:"draw",structure:r[e],keyColors:{structure:"magenta"}},!0);const n=t.filter((t=>t.structureId===e)),i=Su({matchUps:n})?.roundMatchUps||[];Object.keys(i).forEach((t=>{Hl({roundNumber:t,keyColors:{roundNumber:"brightcyan"}},!0),i[t].forEach((({matchUpId:t,schedule:e})=>{Hl({matchUpId:t,time:Xr(e.scheduledTime),date:e.scheduledDate,venue:e.venueId,keyColors:{time:"brightcyan",date:"brightcyan",matchUpId:"yellow",venue:"magenta"}},!0)}))}))})),e&&zl()}});const gR={};function IR(t){const{mutationStatus:e,tournamentId:n,directives:r,timeStamp:i}=t||{},{topics:a}=mr();for(const t of[...a].sort(yR)){const e=dr({topic:t});e&&fr({topic:t,notices:e})}e&&i&&a.includes(vc)&&fr({notices:[{tournamentId:n,directives:r,timeStamp:i}],topic:vc})}async function UR(t){const{mutationStatus:e,tournamentId:n,directives:r,timeStamp:i}=t||{},{topics:a}=mr();for(const t of[...a].sort(yR)){const e=dr({topic:t});e&&await fr({topic:t,notices:e})}e&&i&&a.includes(vc)&&fr({notices:[{tournamentId:n,directives:r,timeStamp:i}],topic:vc})}const SR={[bc]:5,[Dc]:5,[Nc]:5,[Uc]:5,[Ic]:5,[lc]:5,[mc]:5,[fc]:5,[hc]:1,[Mc]:1,[gc]:5,[yc]:5,[pc]:4,[cc]:4,[uc]:4,[dc]:4,[rc]:3,[nc]:2};function yR(t,e){return(SR[e]||0)-(SR[t]||0)}const{FACTORY:vR}=so;function wR({timeStamp:t}){const e=Ir(),n=sr();return n&&Object.values(e).forEach((e=>{!function({tournamentRecord:t,value:e}){const{extension:n}=Fr({element:t,name:vR});Cr({element:t,extension:{name:vR,value:{...n?.value,...e}}})}({tournamentRecord:e,value:{version:"2.0.0-beta.7",timeStamp:t}})})),n}function TR({engineType:t,methodName:e,elapsed:n,params:r,result:i}){const a=Xn();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&&Pr(o,t)}function PR({methodName:t,params:e,start:n}){const r={error:jn,methodName:t};return TR({result:r,methodName:t,elapsed:n?Date.now()-n:0,params:e,engineType:"sync"}),r}function DR(t,e,n,r,i){delete t.success,delete t.error;const a=Date.now(),o=hr();n&&(n.activeTournamentId=o);const s=n?.tournamentRecord||gr(o),c="object"==typeof n?.tournamentRecord&&{[n?.tournamentRecord.tournamentId]:n.tournamentRecord}||Ir(),u=n?mi(n,void 0,!0):void 0,d=n?function(t,e){if(!1===e._middleware)return e;if(e.tournamentId&&!t[e.tournamentId])return{error:x};const n=e.drawId||e.matchUp?.drawId;if(n){const{event:r,drawDefinition:i,tournamentId:a}=kp({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}=kp({eventId:e.eventId,tournamentRecords:t});if(!n)return{error:Pt};e.tournamentId=r,e.event=n}const r=e.tournamentId??hr();if(!r&&e)return e;const i=t[r];return r&&!i?{error:x}:i?(e.tournamentRecord=i,e):e}(c,n):void 0;if(d?.error)return d;const p=function({tournamentRecords:t,tournamentRecord:e,params:n,methodName:r,method:i}){if(Xn())return i({tournamentRecords:t,tournamentRecord:e,...n});try{return i({tournamentRecords:t,tournamentRecord:e,...n})}catch(t){return Tr({engineName:"engine",methodName:r,params:n,err:t})}}({params:d,tournamentRecords:c,tournamentRecord:s,methodName:r,method:e});return TR({result:p,methodName:r,elapsed:Date.now()-a,params:u,engineType:i}),p}function bR(t,e=!0){return"object"!=typeof t||Array.isArray(t)?{error:Pn}:t?.tournamentId?Ur(e?mi(t):t):{error:Nn}}function NR(t,e=!0){if("object"!=typeof t)return{error:Pn};if(yr(),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)yr((t={[t.tournamentId]:t}).tournamentId);else{if(!Object.keys(t).every((e=>t[e].tournamentId===e)))return{error:k}}return Sr(e?mi(t):t)}async function MR(t,e){if(!Ui(e))return{error:Nn,message:"args must be an object"};const n=Object.values(e).filter(gi).length;if(n>1)return{message:"there must be only one arg with typeof function",error:Nn};const r=n?Object.keys(e).find((t=>gi(e[t]))):Ii(e.method)&&e.method;if(!r)return{error:jn};const{[r]:i,...a}=e,o=e?.params||{...a},s=o.rollbackOnError&&mi(Ir(),!1,!0),c=i||t[r]||Yn()[r];if(!c)return PR({methodName:r,params:o});const u=await DR(t,c,o,r,"async")??{};u?.error&&s&&NR(s);const d=Date.now(),p=wR({timeStamp:d}),l=u?.success&&!0!==o?.delayNotify&&!0!==o?.doNotNotify;return l&&await UR({directives:[{method:c,params:o}],mutationStatus:p,timeStamp:d}),(l||!u?.success||o?.doNotNotify)&&lr(),u}function RR(t,e){return e?.error?(t.error=e.error,t.success=!1):(t.error=void 0,t.success=!0),t}function AR(t,e){t.importMethods=(n,r,i)=>function(t,e,n,r,i){if(!Ui(n))return{error:Nn};const a=Array.isArray(r)?r:[],o={},s=(t,e=0)=>{Object.keys(t).forEach((n=>{gi(t[n])?o[n]=t[n]:Ui(t[n])&&(!0===r||a?.includes(n))&&(void 0===i||e<i)&&s(t[n],e+1)}))};return s(n),or(o),Object.keys(o).filter((t=>gi(o[t]))).forEach((n=>{t[n]=r=>{const i=()=>e(t,{[n]:o[n],...r});if(Xn())return i();try{return i()}catch(t){Tr({engineName:"engine",methodName:n,params:r,err:t})}}})),{...E,...t}}(t,e,n,r,i),t.getTournament=t=>function(t){const{convertExtensions:e=!1,removeExtensions:n=!1}=t??{},r=t?.tournamentId??hr();return"string"!=typeof r?{}:{tournamentRecord:mi(gr(r),e,!1,n)}}(t),t.getState=t=>function({convertExtensions:t,removeExtensions:e}){const n=Ir();return{tournamentId:hr(),tournamentRecords:mi(n,t,!1,e)}}({convertExtensions:t?.convertExtensions,removeExtensions:t?.removeExtensions}),t.version=()=>"2.0.0-beta.7",t.reset=()=>(Sr({}),RR(t)),t.devContext=e=>(er(e),RR(t)),t.getDevContext=t=>Xn(t),t.newTournamentRecord=(t={})=>{const e=SP(t),n=e.tournamentId;return e.error?e:(bR(e),yr(n),{...E,tournamentId:n})},t.setState=(e,n,r)=>{ir(n,r);const i=NR(e,n);return RR(t,i)},t.setTournamentId=t=>yr(t),t.getTournamentId=()=>hr(),t.setTournamentRecord=(e,n,r)=>{ir(n,r);const i=bR(e,n);return RR(t,i)},t.removeTournamentRecord=e=>{const n=vr(e);return RR(t,n)},t.removeUnlinkedTournamentRecords=()=>{const e=function(){const t=Ir(),{extension:e}=Fr({name:Ka,tournamentRecords:t,discover:!0}),n=e?.value?.tournamentIds||[];return Object.keys(t).forEach((e=>{n.includes(e)||delete t[e]})),Sr(t)}();return RR(t,e)}}function ER(t){const e=Zn();if(e.error&&!t)return e;const n={executionQueue:(t,e)=>async function(t,e,n){if(!Array.isArray(e))return{error:Nn,message:"directives must be an array"};const r=ur(),i=Date.now(),a=n&&mi(Ir(),!1,!0),o=[];for(const n of e){if("object"!=typeof n)return{error:Nn,message:"directive must be an object"};const{method:e,params:s={},pipe:c}=n;if(!r[e])return PR({methodName:e,start:i,params:s});if(c){const t=o[o.length-1],e=Object.keys(c);for(const n of e)t[n]&&(s[n]=t[n])}const u=DR(t,r[e],s,e,"async");if(u?.error)return a&&NR(a),{...u,rolledBack:!!a};o.push({...u,methodName:e})}const s=Date.now();return UR({directives:e,mutationStatus:wR({timeStamp:s}),timeStamp:s}),lr(),{success:o.every((t=>t.success)),results:o}}(n,t,e),execute:t=>MR(n,t)};return AR(n,MR),n}function CR(t,e){if(!Ui(e))return{error:Nn,message:"args must be an object"};const n=Object.values(e).filter(gi).length;if(n>1)return{message:"there must be only one arg with typeof function",error:Nn};const r=n?Object.keys(e).find((t=>gi(e[t]))):Ii(e.method)&&e.method;if(!r)return{error:jn};const{[r]:i,...a}=e,o=e?.params||{...a},s=o.rollbackOnError&&mi(Ir(),!1,!0),c=i||t[r]||Yn()[r];if(!c)return PR({methodName:r,params:o});const u=DR(t,c,o,r,"sync")??{};u?.error&&s&&NR(s);const d=Date.now(),p=wR({timeStamp:d}),l=u?.success&&!0!==o?.delayNotify&&!0!==o?.doNotNotify;return l&&IR({directives:[{method:c,params:o}],mutationStatus:p,timeStamp:d}),(l||!u?.success||o?.doNotNotify)&&lr(),u}const OR=(()=>{const t={executionQueue:(e,n)=>function(t,e,n){if(!Array.isArray(e))return{error:Nn,message:"directives must be an array"};const r=ur(),i=Date.now(),a=n&&mi(Ir(),!1,!0),o=[];for(const n of e){if("object"!=typeof n)return{error:Nn,message:"directive must be an object"};const{method:e,params:s={},pipe:c}=n;if(!r[e])return PR({methodName:e,start:i,params:s});if(c){const t=o[o.length-1],e=Object.keys(c);for(const n of e)t[n]&&(s[n]=t[n])}const u=DR(t,r[e],s,e,"sync");if(u?.error)return a&&NR(a),{...u,rolledBack:!!a};o.push({...u,methodName:e})}const s=Date.now();return IR({directives:e,mutationStatus:wR({timeStamp:s}),timeStamp:s}),lr(),{success:o.every((t=>t.success)),results:o}}(t,e,n),execute:e=>CR(t,e)};return AR(t,CR),t})();function FR(t,e){if(!Ui(e))return{error:Nn,message:"args must be an object"};const n=Object.values(e).filter(gi).length;if(n>1)return{message:"there must be only one arg with typeof function",error:Nn};const r=n?Object.keys(e).find((t=>gi(e[t]))):Ii(e.method)&&e.method;if(!r)return{error:jn};const{[r]:i,...a}=e,o=e?.params||{...a},s=i||t[r]||Yn()[r];return s?DR(t,s,o,r,"ask"):PR({methodName:r,params:o})}const kR=(()=>{const t={execute:e=>FR(t,e)};return AR(t,FR),t})();let _R,xR={};function LR(t,e=!0){if(!t)return{error:ae};if("object"!=typeof t)return{error:Pn};if(t.matchUpId)_R=t.matchUpId,xR[_R]=e?mi(t):t;else if(Array.isArray(t))for(const n of t.reverse())n.matchUpId&&(xR[n.matchUpId]=e?mi(n):n,_R||(_R=n.matchUpId));else for(const n of Object.values(t))n.matchUpId&&(xR[n.matchUpId]=e?mi(n):n,_R||(_R=n.matchUpId));return e?mi(t):t}const BR=(()=>{const t={getState:t=>function(t){return mi(xR[_R],t?.convertExtensions,!1,t?.removeExtensions)}(t),version:()=>"2.0.0-beta.7",reset:()=>(_R=void 0,xR={},{...E}),drawId:void 0,error:void 0,success:!1,devContext:e=>(er(e),t),setState:(e,n,r)=>{ir(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}(LR(e))}};return function(n){n.forEach((n=>{Object.keys(n).forEach((r=>{t[r]=t=>{if(Xn())return e({params:t,governor:n,methodName:r});try{return e({params:t,governor:n,methodName:r})}catch(e){Tr({engineName:"matchUpEngine",methodName:r,params:t,err:e})}}}))}))}([uM]),t;function e({params:e,governor:n,methodName:r}){t.error=void 0,t.success=!1;const i=e?.matchUp||xR[_R],a=e?.matchUps||Object.values(xR),o=e?.rollbackOnError&&mi(i,!1,!0);e={...e,matchUpId:i?.matchUpId,matchUps:a,matchUp:i};const s=n[r](e);if(s?.error)return o&&LR(o),{...s,rolledBack:!!o};const c=s?.success&&!0!==e?.delayNotify&&!0!==e?.doNotNotify;return c&&IR(),(c||!s?.success||e?.doNotNotify)&&lr(),s}})();let VR=!1;const jR=(()=>{const t={version:()=>"2.0.0-beta.7",setDeepCopy:(e,n)=>(ir(e,n),t),devContext:e=>(er(e),VR=!0,t)};return function(e){e.forEach((e=>{Object.keys(e).forEach((n=>{t[n]=t=>{try{const r=function(t,e){const n=t({...e});n?.error||IR();lr(),VR&&(er(!1),VR=!1);return n}(e[n],t);return!r?.error&&t?.setState&&r?.tournamentRecord&&NR(r.tournamentRecord),r}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})}}}))}))}([UD]),t})();OR.importMethods(lR,!0,1);const GR=OR,qR=OR;function $R(t,e){return t&&e&&Array.isArray(e)&&e[t-1]||"object"==typeof e&&e[t]}function WR(t){const{participation:e={},awardProfiles:n,startDate:r,eventType:i,drawSize:a,drawType:o,category:s,endDate:c,level:u}=t,{participationOrder:d,flightNumber:p,rankingStage:l}=e;return{awardProfile:n.find((t=>(t=>!r&&!c||!t.dateRanges||t.dateRanges.some((t=>{const e=!r||!t.startDate||new Date(r)>new Date(t.startDate),n=!c||!t.endDate||new Date(c)<=new Date(t.endDate);return e&&n})))(t)&&(!t.maxFlightNumber||p<=t.maxFlightNumber)&&(!t.drawTypes?.length||t.drawTypes?.includes(o))&&(!t.drawSizes?.length||t.drawSizes.includes(a))&&(!t.stages?.length||t.stages.includes(l))&&(!t.levels?.length||t.levels.includes(u))&&(!t.maxDrawSize||a<=t.maxDrawSize)&&(!t.drawSize||t.drawSize===a)&&(!t.maxLevel||u<=t.maxLevel)&&(!p||!t.flights?.flightNumbers?.length||t.flights.flightNumbers.includes(p))&&(!t.participationOrder||t.participationOrder===d)&&(!t.category?.ageCategoryCodes||t.category.ageCategoryCodes.includes(s?.ageCategoryCode))&&(!t.eventTypes?.length||t.eventTypes?.includes(i))))}}function HR({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=$R(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 zR={getTournamentPoints:function({participantFilters:t,policyDefinitions:e,tournamentRecord:n,saveRankings:r,level:i}){if(!n)return{error:x};const{policyDefinitions:a}=Pu({policyTypes:[Ia],tournamentRecord:n}),o=e?.[Ia]??a?.[Ia];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}=ym({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===Xd&&r!==iu)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:M}=WR({awardProfiles:s,participation:a,eventType:P,startDate:D,category:T,drawSize:y,drawType:w,endDate:b,level:i});if(M){if(!y)continue;const t=Array.isArray(o)&&Math.max(...o),e=m(o||[]).join("-"),r=t&&I!==Qo&&o?.includes(y);void 0!==M.requireWinForPoints&&(d=M.requireWinForPoints),void 0!==M.requireWinFirstRound&&(c=M.requireWinFirstRound);const{finishingPositionPoints:a={},finishingPositionRanges:s,finishingRound:p,pointsPerWin:f,flights:v}=M,w=Array.isArray(M.perWinPoints)?M.perWinPoints?.find((t=>t.participationOrders?.includes(u))):M.perWinPoints,T=a.participationOrders;let P,D=0;if((!T||T.includes(u))&&s&&t){const e=s[t];e&&({awardPoints:D,requireWin:P}=HR({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}=HR({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=$R(i,w?.level);t?S+=U*t:w.value&&(S+=U*w.value)}}if(N=l+S,e===iu){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===su?(U[r]||(U[r]=[]),U[r].push(t)):e===iu&&(I[r]||(I[r]=[]),I[r].push(t))}}}}if(r){Cr({element:n,extension:{name:Xa,value:{personPoints:g,teamPoints:I,pairPoints:U}}})}return{participantsWithOutcomes:h,personPoints:g,pairPoints:U,teamPoints:I,...E}}};const YR={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)?YR.kDefault():n},kDefault:()=>1};function KR(t){let{winnerRating:e,loserRating:n,ratingRange:r}=t;const{ratings:i=nS,winnerCountables:a=1,loserCountables:o=0,ratingType:s=ZU,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:nS[ZU].range,sourceRange:m,value:p?r[0]-e:e}),I=h({targetRange:nS[ZU].range,sourceRange:m,value:p?r[0]-n:n}),U=(t,e)=>1/(1+Math.pow(10,(e-t)/YR.nSpread)),S=U(g,I),y=U(I,g),v=YR.kCalc(a),w=YR.kCalc(o),T=YR.kMultiplier(c,u),P=g+T*v*(1-S),D=I+T*w*(0-y),b=h({sourceRange:nS[ZU].range,value:P,targetRange:m}),N=h({sourceRange:nS[ZU].range,value:D,targetRange:m}),M=p?r[0]-b:b;let R=parseFloat(parseFloat(M).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>YR.diffThreshold||R<0||E<0)&&(R=e,E=n),{newWinnerRating:R,newLoserRating:E}}const JR={calculateNewRatings:KR,generateDynamicRatings:function({removePriorValues:t=!0,tournamentRecord:e,ratingType:n=ZU,considerGames:r,matchUpIds:i,asDynamic:a}){if(!e)return{error:x};if(!Array.isArray(i))return{error:Ht};if("string"!=typeof n)return{error:Nn,ratingType:n};if(!nS[n])return{error:Nn};const o=nS[n],{accessor:s}=o,c={},u=xl({matchUpFilters:{matchUpIds:i,matchUpStatuses:Ho},tournamentRecord:e,inContext:!0}).matchUps??[];u.sort(Bl);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:oa},g=`${n}.${ia}`,I={scaleName:g,eventType:f,scaleType:oa},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}=TI({scaleAttributes:I,tournamentRecord:e,participantId:t}),{scaleItem:r}=TI({tournamentRecord:e,scaleAttributes:h,participantId:t});return t&&{[t]:n??r??{scaleName:S,eventType:f,scaleDate:o,scaleType:oa,scaleValue:s?{[s]:void 0}:void 0}}}))),v=u?Wp(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}=KR({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=YP({participantId:r,removePriorValues:t,tournamentRecord:e,scaleItem:{...y[r],scaleName:S}});if(I.error)return I;if(I=YP({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}}},QR={...zR,...JR};OR.importMethods(QR);const ZR=OR,XR={ratingsParameters:nS,matchUpFormats:tg,countryToFlag:yl,tieFormats:dv,countries:vl,policies:{POLICY_AVOIDANCE_COUNTRY:{[wa]:{roundsToSeparate:void 0,policyName:"Nationality Code",policyAttributes:[{key:"person.nationalityCode"},{key:"individualParticipants.person.nationalityCode"}]}},POLICY_POSITION_ACTIONS_DEFAULT:oU,POLICY_POSITION_ACTIONS_DISABLED:{[ha]:{policyName:"positionActionsDisabled",enabledStructures:!1}},POLICY_POSITION_ACTIONS_NO_MOVEMENT:{[ha]:{policyName:"positionActionsNoMovement",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[ZI,QI,XI],disabledActions:[]}]}},POLICY_POSITION_ACTIONS_UNRESTRICTED:{[ha]:{policyName:"positionActionsUnrestricted",enabledStructures:[],otherFlightEntries:!0,disableRoundRestrictions:!0,activePositionOverrides:[ZI,KI]}},POLICY_PRIVACY_DEFAULT:{[Sa]:{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:rl,POLICY_SCHEDULING_DEFAULT:uT,POLICY_SCORING_DEFAULT:{[Ta]:{defaultMatchUpFormat:Zh,allowDeletionWithScoresPresent:{drawDefinitions:!1,structures:!1},requireAllPositionsAssigned:!1,processCodes:{incompleteAssignmentsOnDefault:["RANKING.IGNORE"]},stage:{[Jo]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}}}},POLICY_SCORING_USTA:{[Ta]:{requireAllPositionsAssigned:!1,stage:{[Jo]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},defaultMatchUpFormat:Zh,matchUpFormats:[{description:"Best of 3 tiebreak sets",matchUpFormat:Zh,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:{[Pa]:{seedingProfile:{positioning:ss},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:ry},flagIOC:function(t){return yl(Object.assign({},...vl.filter((t=>t.ioc)).map((t=>({[t.ioc]:t.iso}))))[t])}},tA={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"},eA={CLAY:"CLAY",HARD:"HARD",GRASS:"GRASS",CARPET:"CARPET",ARTIFICIAL:"ARTIFICIAL"},nA={INDOOR:"INDOOR",OUTDOOR:"OUTDOOR"};var rA=Object.freeze({__proto__:null,activeMatchUpStatuses:zo,auditConstants:xy,completedMatchUpStatuses:Ho,directingMatchUpStatuses:$o,drawDefinitionConstants:Ys,entryStatusConstants:nd,errorConditionConstants:$n,eventConstants:tp,extensionConstants:so,flightConstants:vv,genderConstants:ll,keyValueConstants:QN,matchUpActionConstants:AU,matchUpStatusConstants:Ko,matchUpTypes:Zc,nonDirectingMatchUpStatuses:Wo,particicipantsRequiredMatchUpStatuses:Go,participantConstants:du,participantRoles:km,participantTypes:uu,penaltyConstants:tA,policyConstants:Na,positionActionConstants:eU,ratingConstants:eS,recoveryTimeRequiredMatchUpStatuses:jo,requestConstants:XT,resultConstants:C,scaleConstants:ua,scheduleConstants:lp,sortingConstants:Pv,surfaceConstants:eA,tieFormatConstants:KS,timeItemConstants:Gd,topicConstants:Rc,tournamentConstants:CM,upcomingMatchUpStatuses:Yo,validMatchUpStatuses:qo,venueConstants:nA});export{kR as askEngine,ER as asyncEngine,GR as competitionEngine,Ys as drawDefinitionConstants,nd as entryStatusConstants,$n as errorConditionConstants,tp as eventConstants,rA as factoryConstants,XR as fixtures,vv as flightConstants,gR as forge,ll as genderConstants,Dr as globalState,lR as governors,QN as keyValueConstants,AU as matchUpActionConstants,BR as matchUpEngine,Lv as matchUpFormatCode,Ko as matchUpStatusConstants,Zc as matchUpTypes,jR as mocksEngine,du as participantConstants,km as participantRoles,uu as participantTypes,tA as penaltyConstants,Na as policyConstants,eU as positionActionConstants,C as resultConstants,ua as scaleConstants,ZR as scaleEngine,eA as surfaceConstants,OR as syncEngine,Gd as timeItemConstants,hR as tools,qR as tournamentEngine,hR as utilities,nA as venueConstants,t as version};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|