tods-competition-factory
Version:
Create and mutate TODS compliant tournament objects
3 lines • 1.52 MB
JavaScript
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});function t(){return"5.2.4"}const e="SINGLES",n="SINGLES",r="DOUBLES",i="DOUBLES",o="TEAM",a="TEAM",s="HYBRID",c={SINGLES_MATCHUP:e,SINGLES:n,DOUBLES_MATCHUP:r,DOUBLES:i,TEAM_MATCHUP:o,TEAM:a,HYBRID_MATCHUP:"HYBRID",HYBRID:s},u={[n]:[n,"S"],[i]:[i,"D"],[a]:[a,"T"],[s]:[s,"H"],S:[n,"S"],D:[i,"D"],T:[a,"T"],H:[s,"H"]};function d(t,e){return(t??0)-(e??0)}function p(t){return"number"==typeof t?parseInt(t.toString()):"string"==typeof t?parseInt(t):0}function l(t){return"function"==typeof t}function m(t){return"string"==typeof t}function f(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function h(t,e){if(!f(t)||!f(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 g(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(f).map(t=>t[e]&&{[t[e]]:t}).filter(Boolean)):{}}function I(t){return Array.isArray(t)?t.length+t.map(I).reduce((t,e)=>t+e,0):f(t)&&null!==t?Object.keys(t).length+Object.keys(t).map(e=>I(t[e])).reduce((t,e)=>t+e,0):0}function S(t){return!Number.isNaN(Number(t))&&(t>0&&!(t&t-1))}function y(t){if(!t.length)return;const e=[...t].sort(d),n=Math.floor(e.length/2);return e.length%2?e[n]:(e[n-1]+e[n])/2}function v(t){return Number.isNaN(Number(t))?0:t%2&&t+1||t}function U(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function P(t){return!Number.isNaN(Number.parseFloat(t))}function T(t){const e=p(t);if(!Number.isNaN(e))return 0!==e&&1===(e&-e)}function w(t){if(Number.isNaN(Number(t)))return!1;for(;!S(t);)t++;return t}function D(t,e,n){return t=Math.ceil(t),e=Math.floor(e),Math.floor((n??Math.random)()*(e-t+1))+t}function R(t){return!(m(t)&&!t.trim().length)&&Number.isSafeInteger("string"==typeof t?+t:t)}function b(t,e,n,r,i=2,o){const a=o??Math.random,s=1-a(),c=1-a();let u=Math.sqrt(-2*Math.log(s))*Math.cos(2*Math.PI*c);return u=u/10+.5,u>1||u<0?u=b(t,e,n,void 0,2,o):(u=Math.pow(u,n),u*=e-t,u+=t),r&&(u=function(t,e){e||(e=1);const n=1/e;return Math.round(t*n)/n}(u,r)),Number.parseFloat(u.toFixed(i))}function N(t,e=2){return Number.parseFloat(Number(Math.round(1e3*t)/1e3).toFixed(e))}function M(t){return Array.isArray(t)?t?.filter((t,e,n)=>n.lastIndexOf(t)===e):[]}function A(t,e){if(!Array.isArray(t))return[];const n=e??Math.random;return t.map(t=>[n(),t]).sort((t,e)=>t[0]-e[0]).map(t=>t[1])}function E(t){return R(t)?t:1/0}function C(t){return Array.isArray(t)?t.reduce((t,e)=>(t[e]||(t[e]=0),t[e]++,t),{}):{}}function O(t){return Object.keys(t).reduce((e,n)=>{const r=t[n];return e[r]?e[r].push(n):e[r]=[n],e},{})}function k(t,e,n){return n.indexOf(t)===e}function F(t){return t.filter(k)}function x(t,e){return Array.isArray(t)&&t.length?t.splice(Math.floor((e??Math.random)()*t.length),1)[0]:void 0}function _(t,e){return t[Math.floor((e??Math.random)()*t.length)]}function L(t,e){return Array.from({length:e-t},(e,n)=>n+t)}function B(t,e){return e.reduce((e,n,r)=>(n===t&&e.push(r),e),[])}function V(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 G(t,e){return Array.isArray(t)&&Array.isArray(e)?t.filter(t=>!e.includes(t)):[]}function j(t,e){return!(!Array.isArray(t)||!Array.isArray(e))&&t.some(t=>e.includes(t))}function q(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 W(t){return!!Array.isArray(t)&&t.reduce((t,e)=>!isNaN(parseInt(e))&&t,!0)}function $(t){return!!Array.isArray(t)&&t.reduce((t,e)=>isNaN(parseInt(e))&&t,!0)}function H(t,e,n){return Array.isArray(t)?t.reduce((t,r,i)=>{const o=!!n&&!!(Math.floor(i/e)%2),a=i%e,s=o?e-1-a:a;return t[s]||(t[s]=[]),t[s].push(r),t},[]):[]}function z(t,e){return!(!Array.isArray(t)||!m(e))&&V(t,u[e]).length}const Y={success:!0},K="error",Q={SUCCESS:Y,ERROR:K};function J({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}):{...Y}}const X={message:"Chronological error; time violation.",code:"ANACHRONISM"},Z={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},tt={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},et={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},nt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},rt={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},it={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},ot={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},at={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},st={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},ct={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},ut={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},dt={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},pt={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},lt={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},mt={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},ft={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},ht={message:"Schedule conflict: court slot already occupied",code:"ERR_SCHEDULE_CONFLICT_DOUBLE_BOOKING"},gt={message:"Schedule conflict: matchUps scheduled outside court availability",code:"ERR_SCHEDULE_CONFLICT_COURT_UNAVAILABLE"},It={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},St={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},yt={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},vt={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},Ut={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},Pt={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Tt={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},wt={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},Dt={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},Rt={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},bt={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},Nt={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},Mt={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},At={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},Et={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},Ct={message:"Invalid action",code:"ERR_INVALID_ACTION"},Ot={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},kt={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},Ft={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},xt={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},_t={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},Lt={message:"Existing round",code:"ERR_EXISTING_ROUND"},Bt={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},Vt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Gt={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},jt={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},qt={message:"Missing MAIN structure",code:"ERR_MISSING_MAIN_STRUCTURE"},Wt={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},$t={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"},Ht={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},zt={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},Yt={message:"Event exists",code:"ERR_EXISTING_EVENT"},Kt={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},Qt={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Jt={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},Xt={message:"Missing stage",code:"ERR_MISSING_STAGE"},Zt={message:"Invalid stage",code:"ERR_INVALID_STAGE"},te={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},ee={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},ne={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},re={message:"Lucky draw first round allows at most one BYE",code:"ERR_LUCKY_DRAW_BYE_LIMIT"},ie={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},oe={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},ae={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},se={message:"Propagated exits downstream",code:"ERR_PROPAGATED_EXITS_DOWNSTREAM"},ce={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},ue={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},de={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},pe={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},le={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},me={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},fe={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},he={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},ge={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},Ie={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},Se={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},ye={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},ve={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Ue={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},Pe={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},Te={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},we={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},De={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},Re={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},be={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},Ne={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},Me={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},Ae={message:"Missing value",code:"ERR_MISSING_VALUE"},Ee={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},Ce={message:"Missing date",code:"ERR_MISSING_DATE"},Oe={message:"No valid dates",code:"ERR_NO_VALID_DATES"},ke={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},Fe={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},xe={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},_e={message:"Invalid Date",code:"ERR_INVALID_DATE"},Le={message:"Invalid time",code:"ERR_INVALID_TIME"},Be={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"},Ve={message:"Missing date range",info:"Event or tournament must have start and end dates",code:"ERR_MISSING_DATE_RANGE"},Ge={message:"Invalid Time Zone",code:"ERR_INVALID_TIME_ZONE"},je={message:"Invalid embargo: must be an ISO 8601 datetime with timezone (Z or ±HH:MM offset)",code:"ERR_INVALID_EMBARGO"},qe={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},We={message:"Invalid score",code:"ERR_INVALID_SCORE"},$e={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"},He={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},ze={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},Ye={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},Ke={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},Qe={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},Je={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},Xe={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},Ze={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},tn={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},en={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},nn={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},rn={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},on={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},an={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},sn={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},cn={message:"Missing qualified participants",code:"ERR_MISSING_QUALIFIED_PARTICIPANTS"},un={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},dn={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},pn={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},ln={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},mn={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},fn={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},hn={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},gn={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},In={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},Sn={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},yn={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},vn={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},Un={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},Pn={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},Tn={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},wn={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},Dn={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},Rn={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},bn={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},Nn={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},Mn={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},An={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},En={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Cn={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},On={message:"Court exists",code:"ERR_EXISTING_COURT"},kn={message:"Booking not found",code:"ERR_NOT_FOUND_BOOKING"},Fn={message:"An active draft already exists for this draw",code:"ERR_EXISTING_DRAFT"},xn={message:"Existing matchUps conflict with booking",code:"ERR_EXISTING_MATCHUPS"},_n={message:"Venue exists",code:"ERR_EXISTING_VENUE"},Ln={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Bn={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},Vn={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},Gn={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},jn={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},qn={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},Wn={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},$n={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},Hn={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},zn={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},Yn={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Kn={message:"Missing context",code:"ERR_MISSING_CONTEXT"},Qn={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},Jn={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},Xn={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},Zn={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},tr={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},er={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},nr={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},rr={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},ir={message:"Invalid object",code:"ERR_INVALID_OBJECT"},or={message:"Invalid gender",code:"ERR_INVALID_GENDER"},ar={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},sr={message:"Invalid values",code:"ERR_INVALID_VALUES"},cr={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},ur={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},dr={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},pr={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},lr={message:"Value unchanged",code:"ABORT_UNCHANGED"},mr={message:"Not found",code:"ERR_NOT_FOUND"},fr={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},hr={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},gr={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},Ir={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},Sr={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},yr={message:"Existing stage",code:"ERR_EXISTING_STAGE"},vr={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},Ur={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},Pr={message:"Mutation blocked by active lock",code:"ERR_MUTATION_LOCKED"},Tr={message:"Active mutation lock already exists for scope",code:"ERR_EXISTING_MUTATION_LOCK"},wr={message:"Mutation lock not found",code:"ERR_NOT_FOUND_MUTATION_LOCK"},Dr={message:"Lock token does not match",code:"ERR_UNAUTHORIZED_LOCK_OPERATION"},Rr={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},br={message:"Scores present",code:"ERR_SCORES_PRESENT"},Nr={message:"Tournament category is referenced by one or more events",code:"ERR_TOURNAMENT_CATEGORY_IN_USE"},Mr={message:"Practice registration not found",code:"ERR_NOT_FOUND_REGISTRATION"},Ar={message:"Booking capacity exceeded",code:"ERR_CAPACITY_EXCEEDED"},Er={ANACHRONISM:X,BOOKING_NOT_FOUND:kn,CANNOT_CHANGE_WINNING_SIDE:Je,CAPACITY_EXCEEDED:Ar,REGISTRATION_NOT_FOUND:Mr,CANNOT_MODIFY_TIEFORMAT:ze,TOURNAMENT_CATEGORY_IN_USE:Nr,CANNOT_MODIFY_PARTICIPANT_TYPE:Ye,CANNOT_REMOVE_MAIN_STRUCTURE:tt,CANNOT_REMOVE_PARTICIPANTS:Ke,CATEGORY_MISMATCH:Qe,COURT_EXISTS:On,COURT_NOT_FOUND:Cn,EXISTING_DRAFT:Fn,EXISTING_MATCHUPS:xn,DRAW_DEFINITION_NOT_FOUND:ut,DRAW_ID_EXISTS:Nt,DRAW_POSITION_ACTIVE:vt,DRAW_POSITION_ASSIGNED:mt,DRAW_POSITION_NOT_CLEARED:It,DRAW_POSITION_NOT_FOUND:{message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},DRAW_SIZE_MISMATCH:{message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},DUPLICATE_ENTRY:Z,DUPLICATE_VALUE:cr,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:wn,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:Tn,EVENT_EXISTS:Yt,EVENT_NOT_FOUND:zt,EXISTING_DRAW_DEFINITIONS:ct,EXISTING_END_TIME:Gn,EXISTING_FLIGHT:hr,EXISTING_MATCHUP_ID:Sr,EXISTING_OUTCOME:Ir,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:gn,EXISTING_PARTICIPANT:In,EXISTING_POLICY_TYPE:De,EXISTING_PROFILE:gr,EXISTING_ROUND:Lt,EXISTING_STAGE:yr,EXISTING_STRUCTURE:vr,INCOMPATIBLE_MATCHUP_STATUS:ae,INCOMPLETE_SOURCE_STRUCTURE:pt,INSUFFICIENT_DRAW_POSITIONS:bn,INVALID_ACTION:Ct,INVALID_ASSIGNMENT:Ot,INVALID_BOOKINGS:ke,INVALID_CATEGORY:ar,INVALID_COLLECTION_DEFINITION:rr,INVALID_CONFIGURATION:nr,INVALID_DATE_AVAILABILITY:Fe,INVALID_DATE:_e,INVALID_DRAW_DEFINITION:at,INVALID_DRAW_POSITION_FOR_SEEDING:lt,INVALID_DRAW_POSITION:Pt,INVALID_DRAW_SIZE:Dt,INVALID_END_TIME:Vn,INVALID_ENTRIES:Qt,INVALID_EVENT_TYPE:$t,INVALID_GAME_SCORES:qe,INVALID_GENDER:or,INVALID_MATCHUP_FORMAT:de,INVALID_MATCHUP_STATUS:ce,INVALID_MATCHUP_STATUS_BYE:ne,INVALID_MATCHUP:ye,INVALID_OBJECT:ir,INVALID_PARTICIPANT_ID:Ze,INVALID_PARTICIPANT_IDS:tn,INVALID_PARTICIPANT_ROLE:en,INVALID_PARTICIPANT_SEEDING:Mt,INVALID_PARTICIPANT_TYPE:nn,INVALID_PARTICIPANT:Xe,INVALID_POLICY_DEFINITION:we,INVALID_RECORDS:et,INVALID_SCALE_ITEM:Jn,INVALID_SEED_NUMBER:Ft,INVALID_SEED_POSITION:xt,INVALID_SET_NUMBER:{message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},INVALID_SIDE_NUMBER:be,INVALID_SCORE:We,INVALID_STAGE:Zt,INVALID_START_TIME:qn,INVALID_STRUCTURE:dt,INVALID_STOP_TIME:jn,INVALID_TIE_FORMAT:ue,INVALID_TIME:Le,INVALID_TIME_ITEM:$n,INVALID_TOURNAMENT_DATES:Be,INVALID_TOURNAMENT_RECORD:it,INVALID_VALUES:sr,INVALID_WINNING_SIDE:$e,LUCKY_DRAW_BYE_LIMIT:re,MATCHUP_NOT_FOUND:ge,METHOD_NOT_FOUND:Ur,MUTATION_LOCKED:Pr,MUTATION_LOCK_EXISTS:Tr,MUTATION_LOCK_NOT_FOUND:wr,MISSING_ASSIGNMENTS:Jt,MISSING_ASYNC_STATE_PROVIDER:Hn,MISSING_AVOIDANCE_POLICY:Pe,MISSING_BIRTH_DATE:Ee,MISSING_COLLECTION_DEFINITION:le,MISSING_COURT_ID:Me,MISSING_COURTS_INFO:En,MISSING_DATE_AVAILABILITY:xe,MISSING_DATE:Ce,MISSING_DRAW_DEFINITION:st,MISSING_DRAW_ID:bt,MISSING_DRAW_POSITION:Tt,MISSING_DRAW_POSITIONS:yt,MISSING_DRAW_SIZE:Rt,MISSING_ENTRIES:Kt,MISSING_EVENT:Ht,MISSING_QUALIFIED_PARTICIPANTS:cn,MISSING_MATCHUP_FORMAT:pe,MISSING_MATCHUP_ID:fe,MISSING_MATCHUP_IDS:he,MISSING_MATCHUP:Se,MISSING_MATCHUPS:Ie,MISSING_PARTICIPANT_COUNT:mn,MISSING_PARTICIPANT_ID:sn,MISSING_PARTICIPANT_IDS:ln,MISSING_PARTICIPANT_ROLE:rn,MISSING_PARTICIPANT:on,MISSING_PARTICIPANTS:an,MISSING_PENALTY_ID:Mn,MISSING_PENALTY_TYPE:Nn,MISSING_PERSON_DETAILS:hn,MISSING_POLICY_ATTRIBUTES:Te,MISSING_POLICY_DEFINITION:Ue,MISSING_POLICY_TYPE:ve,MISSING_POSITION_ASSIGNMENTS:ee,MISSING_ROUND_NUMBER:{message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},MISSING_SCHEDULE:Qn,MISSING_SCORING_POLICY:{message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},MISSING_SEED_ASSIGNMENTS:kt,MISSING_SEEDCOUNT_THRESHOLDS:Et,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:Ne,MISSING_SIDE_NUMBER:{message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},MISSING_STAGE:Xt,MISSING_STRUCTURE_ID:Bt,MISSING_STRUCTURE:jt,MISSING_MAIN_STRUCTURE:qt,MISSING_STRUCTURES:Gt,MISSING_TARGET_LINK:_t,MISSING_TIE_FORMAT:me,MISSING_TIME_ITEM:zn,MISSING_TIME_ITEMS:Yn,MISSING_TOURNAMENT_ID:ot,MISSING_TOURNAMENT_RECORD:rt,MISSING_TOURNAMENT_RECORDS:nt,MISSING_VALUE:Ae,MISSING_VENUE_ID:Bn,MODIFICATIONS_FAILED:Xn,NO_CANDIDATES:er,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:Rn,NO_MODIFICATIONS_APPLIED:Zn,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:Dn,NO_PARTICIPANT_REMOVED:pn,NO_VALID_ACTIONS:dr,NO_VALID_ATTRIBUTES:pr,NO_VALID_DATES:Oe,NOT_FOUND:mr,NOT_IMPLEMENTED:fr,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:Sn,PARTICIPANT_ID_EXISTS:dn,PARTICIPANT_NOT_CHECKED_IN:fn,PARTICIPANT_NOT_FOUND:un,PARTICIPANT_PAIR_EXISTS:{message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},PENALTY_NOT_FOUND:An,POLICY_NOT_ATTACHED:{message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},POLICY_NOT_FOUND:Re,SCHEDULE_NOT_CLEARED:ft,SCHEDULE_CONFLICT_DOUBLE_BOOKING:ht,SCHEDULE_CONFLICT_COURT_UNAVAILABLE:gt,SCHEDULED_MATCHUPS:Rr,SCORES_PRESENT:br,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:At,STAGE_SEQUENCE_LIMIT:te,STRUCTURE_NOT_FOUND:Vt,TEAM_NOT_FOUND:ur,UNABLE_TO_ASSIGN_COURT:tr,UNAUTHORIZED_LOCK_OPERATION:Dr,UNLINKED_STRUCTURES:Wt,UNRECOGNIZED_DRAW_TYPE:St,UNRECOGNIZED_MATCHUP_FORMAT:oe,UNRECOGNIZED_MATCHUP_STATUS:ie,VALUE_UNCHANGED:lr,VENUE_EXISTS:_n},Cr={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]};var Or={addNotice:function({topic:t,payload:e,key:n},r){if("string"!=typeof t||"object"!=typeof e)return;Cr.disableNotifications||(Cr.modified=!0);if(Cr.disableNotifications||!Cr.subscriptions[t]&&!r)return;n&&(Cr.notices=Cr.notices.filter(e=>!(e.topic===t&&e.key===n)));return Cr.notices.push({topic:t,payload:e,key:n}),{...Y}},callListener:function({topic:t,payloads:e,notices:n},r){const i=e??n??[],o=Cr.subscriptions[t];o&&"function"==typeof o&&o(i);const a=r?.[t];a&&"function"==typeof a&&a(i)},cycleMutationStatus:function(){const t=Cr.modified;return Cr.modified=!1,t},deleteNotice:function({topic:t,key:e}){Cr.notices=Cr.notices.filter(n=>(!t||n.topic===t)&&n.key!==e)},deleteNotices:function(){Cr.notices=[]},disableNotifications:function(){Cr.disableNotifications=!0},enableNotifications:function(){Cr.disableNotifications=!1},getMethods:Fr,getNotices:xr,getPayloads:xr,getTopics:function(){return{topics:Object.keys(Cr.subscriptions)}},getTournamentId:kr,getTournamentRecord:function(t){return Cr.tournamentRecords[t]},getTournamentRecords:function(){return Cr.tournamentRecords},removeTournamentRecord:function(t){if("string"!=typeof t)return{error:sr};if(!Cr.tournamentRecords[t])return{error:mr};delete Cr.tournamentRecords[t];const e=Object.keys(Cr.tournamentRecords);1===e.length?Cr.tournamentId=e[0]:e.length||(Cr.tournamentId=void 0);return{success:!0}},setMethods:function(t){return"object"!=typeof t?{error:sr}:(Object.keys(t).forEach(e=>{"function"==typeof t[e]&&(Cr.methods[e]=t[e])}),{...Y})},setSubscriptions:function(t){if(null===t.subscriptions||0===Object.keys(t.subscriptions).length)return Cr.subscriptions={},{...Y};return"object"!=typeof t.subscriptions?{error:sr}:(Object.keys(t.subscriptions).forEach(e=>{"function"==typeof t.subscriptions[e]?Cr.subscriptions[e]=t.subscriptions[e]:delete Cr.subscriptions[e]}),{...Y})},setTournamentId:function(t){if(!t)return Cr.tournamentId=void 0,{success:!0};return Cr.tournamentRecords[t]?(Cr.tournamentId=t,{success:!0}):{error:rt}},setTournamentRecord:function(t){const e=t?.tournamentId;return e?(Cr.tournamentRecords[e]=t,{success:!0}):{error:it}},setTournamentRecords:function(t){Cr.tournamentRecords=t;const e=Object.keys(t);1===e.length?Cr.tournamentId=e[0]:e.length||(Cr.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:kr(),params:JSON.stringify(n),engine:t,methodName:e,error:i}),{error:i}}};function kr(){return Cr.tournamentId}function Fr(){return Cr.methods??{}}function xr({topic:t}){return Cr.notices.filter(e=>e.topic===t).map(t=>t.payload)}const _r="native",Lr="legacy",Br="dual",Vr=[_r,Br,Lr],Gr={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],schemaWriteMode:_r,saveDrawDeletions:!1,auditAuthorityServer:!1,deepCopy:!0};let jr=Or;const qr=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function Wr(){if(jr.createInstanceState){try{jr.createInstanceState()}catch(t){return{error:t}}return{success:!0}}return{error:Hn}}function $r(t){return t&&"object"==typeof t?"object"==typeof Gr.devContext&&(Object.keys(t).every(e=>Gr.devContext?.[e]===t[e])&&Gr.devContext):Gr.devContext??!1}function Hr(t){l(t)?Gr.globalLog=t:delete Gr.globalLog}function zr(t){Gr.devContext=t}function Yr(t){return void 0===t?(Gr.schemaWriteMode=_r,{...Y}):Vr.includes(t)?(Gr.schemaWriteMode=t,{...Y}):{error:sr}}function Kr(){return Gr.schemaWriteMode}function Qr(){return Gr.schemaWriteMode===_r||Gr.schemaWriteMode===Br}function Jr(){return Gr.schemaWriteMode===Lr||Gr.schemaWriteMode===Br}function Xr(t){return void 0===t?(Gr.saveDrawDeletions=!1,{...Y}):"boolean"!=typeof t?{error:sr}:(Gr.saveDrawDeletions=t,{...Y})}function Zr(){return Gr.saveDrawDeletions}function ti(t){return void 0===t?(Gr.auditAuthorityServer=!1,{...Y}):"boolean"!=typeof t?{error:sr}:(Gr.auditAuthorityServer=t,{...Y})}function ei(){return Gr.auditAuthorityServer}function ni(){jr.disableNotifications()}function ri(){jr.enableNotifications()}function ii(t,e){"boolean"==typeof t&&(Gr.deepCopy=t),"object"==typeof e&&(Array.isArray(e.ignore)&&(Gr.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(Gr.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(Gr.deepCopyAttributes.stringify=e.stringify),e.threshold&&(Gr.deepCopyAttributes.threshold=e.threshold))}function oi(){return{enabled:Gr.deepCopy,...Gr.deepCopyAttributes}}function ai(t){return t?.subscriptions?jr.setSubscriptions({subscriptions:t.subscriptions}):{error:Ae,info:"missing subscriptions"}}function si(t){return t?"object"!=typeof t?{error:sr}:(Object.keys(t).forEach(e=>{l(t[e])&&(Gr.globalMethods[e]=t[e])}),{...Y}):{error:Ae,info:"missing method declarations"}}function ci(t){return t?"object"!=typeof t?{error:sr}:jr.setMethods(t):{error:Ae,info:"missing method declarations"}}function ui(){return jr.cycleMutationStatus()}function di(t){if("string"!=typeof t?.topic)return;const e=Gr.globalSubscriptions[t.topic];return jr.addNotice(t,e)}function pi(){return{...Gr.globalMethods,...jr.getMethods()}}function li(t){return mi(t)}function mi(t){return"function"==typeof jr.getPayloads?jr.getPayloads(t):jr.getNotices(t)}function fi({key:t,topic:e}){return jr.deleteNotice({key:t,topic:e})}function hi(){return jr.deleteNotices()}function gi(){return jr.getTopics()}function Ii(t){return gi()?.topics?.includes(t)}async function Si(t){return jr.callListener(t,Gr.globalSubscriptions)}function yi(){return jr.getTournamentId()}function vi(t){return jr.getTournamentRecord(t)}function Ui(){return jr.getTournamentRecords()}function Pi(t){return jr.setTournamentRecord(t)}function Ti(t){return jr.setTournamentRecords(t)}function wi(t){return jr.setTournamentId(t)}function Di(t){return jr.removeTournamentRecord(t)}function Ri(){return jr}function bi({engineName:t,methodName:e,params:n,err:r}){const i=l(jr.handleCaughtError)&&jr.handleCaughtError||Or.handleCaughtError,{tournamentRecord:o,...a}=n;return i({params:a,engineName:t,methodName:e,err:r})}function Ni(t,e){if(Gr.globalLog)try{Gr.globalLog({log:t,engine:e})}catch(n){console.log("globalLog error",n),console.log(e,t),Hr()}else console.log(e,t)}function Mi(t,e,n,r){if(!f(t))return{error:sr};P||(n=1);const i=Array.isArray(e)?e:[],o={},a=(t,r=0)=>{Object.keys(t).forEach(s=>{l(t[s])?o[s]=t[s]:f(t[s])&&(!0===e||i?.includes(s))&&(void 0===n||r<n)&&a(t[s],r+1)})};return a(t),r?si(o):ci(o),{methods:o}}var Ai={__proto__:null,addNotice:di,callListener:Si,createInstanceState:Wr,cycleMutationStatus:ui,deepCopyEnabled:oi,deleteNotice:fi,deleteNotices:hi,disableNotifications:ni,enableNotifications:ri,getAuditAuthorityServer:ei,getDevContext:$r,getMethods:pi,getNotices:li,getPayloads:mi,getProvider:Ri,getSaveDrawDeletions:Zr,getSchemaWriteMode:Kr,getTopics:gi,getTournamentId:yi,getTournamentRecord:vi,getTournamentRecords:Ui,globalLog:Ni,handleCaughtError:bi,hasTopic:Ii,removeTournamentRecord:Di,setAuditAuthorityServer:ti,setDeepCopy:ii,setDevContext:zr,setGlobalLog:Hr,setGlobalMethods:si,setGlobalSubscriptions:function(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{Gr.globalSubscriptions[e]=t.subscriptions[e]}),{...Y}):{error:Ae,info:"missing subscriptions"}},setMethods:ci,setSaveDrawDeletions:Xr,setSchemaWriteMode:Yr,setStateMethods:Mi,setStateProvider:function(t){if("object"!=typeof t)throw new Error("Global state provider can not be undefined or null");if(V(Object.keys(t),qr).length!==qr.length)throw new Error("Global state provider is missing required methods");return jr=t,{success:!0}},setSubscriptions:ai,setTournamentId:wi,setTournamentRecord:Pi,setTournamentRecords:Ti,timeKeeper:function(t="reset",e="default"){const n=Date.now();if("report"===t){if("allTimers"===e){return Object.keys(Gr.timers).filter(t=>"default"!==t||Gr.timers[t].startTime).map(t=>{const e=Gr.timers[t],r="stopped"===e.state?0:(n-(e?.startTime??0))/1e3,i=e.elapsedTime+r;return{state:Gr.timers[t].state,elapsedTime:i.toFixed(2),timer:t}})}{const t="stopped"===Gr.timers[e].state?0:(n-(Gr.timers[e]?.startTime??0))/1e3,r=Gr.timers[e].elapsedTime+t;return{state:Gr.timers[e].state,elapsedTime:r.toFixed(2),timer:e}}}if(!Gr.timers[e]||"reset"===t){if("allTimers"===e)return Gr.timers={default:{elapsedTime:0}},!0;Gr.timers[e]={startTime:n,state:"active",elapsedTime:0}}return Gr.timers[e].elapsedTime||(Gr.timers[e].elapsedTime=0),"stop"===t&&"stopped"!==Gr.timers[e].state&&(Gr.timers[e].state="stopped")&&(Gr.timers[e].elapsedTime+=(n-(Gr.timers[e]?.startTime??0))/1e3),"start"===t&&(Gr.timers[e].startTime=n)&&(Gr.timers[e].state="active"),Gr.timers[e]},writeLegacyEnabled:Jr,writeNativeEnabled:Qr};function Ei(t,e,n,r){if("object"!=typeof t||null===t)return t;const i=oi();i?.enabled||(r=!0);const o=["",void 0,null];e&&o.push(!1);const a=function(t,e,n){return Object.keys(t).filter(r=>!e.includes(t[r])&&(!n||!Array.isArray(t[r])||t[r].length))}(t,o,n);return Object.assign({},...a.map(e=>Array.isArray(t[e])?{[e]:r?t[e]:t[e].map(t=>Ei(t))}:{[e]:r?t[e]:Ei(t[e])}))}function Ci({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&&(e.context??={},Object.assign(e.context,Ei(t))),!e||e?.error||e?.success||Object.assign(e,{...Y}),e??{success:!0}}const Oi="F",ki="X",Fi="M",xi="A",_i="FEMALE",Li="OTHER",Bi="MIXED",Vi="MALE",Gi="ANY",ji={FEMALE_ABBR:Oi,OTHER_ABBR:"O",MIXED_ABBR:ki,MALE_ABBR:Fi,ANY_ABBR:xi,FEMALE:_i,MIXED:Bi,OTHER:Li,MALE:Vi,ANY:Gi};function qi(t){return[_i,Oi].includes(t)}function Wi(t){return[Vi,Fi].includes(t)}function $i(t){return[Bi,ki].includes(t)}function Hi(t){return[Gi,xi].includes(t)}function zi(t){if(t){if(qi(t))return _i;if($i(t))return Bi;if(Wi(t))return Vi;if(Hi(t))return Gi}return Li}function Yi(t){return qi(t)||Wi(t)}function Ki(t){const e="tieFormatGenderValidityCheck",{referenceGender:n,matchUpType:r,gender:o}=t;return n&&o&&Yi(n)&&zi(n)!==zi(o)?Ci({result:{valid:!1,error:or},context:{gender:o},stack:e}):$i(n)&&(Hi(o)||$i(o)&&r!==i)?Ci({result:{error:or,valid:!1},info:"MIXED events can not contain mixed singles or { gender: ANY } collections",stack:e}):Hi(n)&&$i(o)&&r!==i?Ci({result:{error:or,valid:!1},info:"events with { gender: ANY } can not contain MIXED singles collections",stack:e}):{valid:!0}}const Qi="timed",Ji="NOAD",Xi="SET",Zi=["SET","HAL","QTR","PER","INN","RND","FRM","MAP","MAT"],to="CONSECUTIVE",eo="TRADITIONAL",no={S:"normal",F:"final",G:"game",M:"matchUp"};function ro(t,e){if(f(t))return(t?.bestOf||t?.exactly)&&t?.setFormat?function(t,e){const n=io(t.bestOf)||void 0,r=io(t.exactly)||void 0,i=n||r;if(t.setFormat?.timed&&t.simplified&&1===i)return oo(t.setFormat);const o=t.matchRoot||Xi,a=r&&1!==r?"X":"",s=t.aggregate?"A":"",c=i&&`${o}${i}${a}${s}`||"",u=ao(t.setFormat,e),d=u&&`S:${u}`||"",p=ao(t.finalSetFormat,e),l=i&&i>1&&p&&u!==p&&`F:${p}`||"",m=t.gameFormat?`G:${function(t){const e=t?.deuceAfter?`${t.deuceAfter}D`:"";return t?.type===eo?`TN${e}`:t?.type===to&&Number.isInteger(t.count)?`${t.count}C${e}`:void 0}(t.gameFormat)}`:"",f=t.matchUpConstraint?.timed?`M:T${t.matchUpConstraint.minutes}`:"";if(c&&u)return[c,d,m,l,f].filter(Boolean).join("-");return}(t,e):void 0}function io(t){return!Number.isNaN(Number(t))&&Number(t)}function oo(t){let e=`T${t.minutes}`;return"P"===t.based&&(e+="P"),t.tiebreakFormat?.tiebreakTo&&(e+=`/TB${t.tiebreakFormat.tiebreakTo}`),t.modifier&&(e+=`@${t.modifier}`),e}function ao(t,e){if("object"==typeof t&&Object.keys(t).length){if(t.timed)return oo(t);if(t.outs)return`O${t.outs}`;if(t.tiebreakSet)return so(t.tiebreakSet);const n=io(t.setTo);if(n){const r=t.NoAD&&Ji||"",i=io(t.winBy),o=so(t.tiebreakFormat),a=o&&`/${o}`||"",s=i&&2!==i&&!o?`WB${i}`:"",c=io(t.tiebreakAt);if(!1!==o)return`${n}${r}${s}${a}${c&&(c!==n||e)&&`@${c}`||""}`}}}function so(t){if(t){if("object"!=typeof t||t.tiebreakTo){if("object"==typeof t&&io(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?Ji:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}return!1}return""}}function co(t){if(m(t)){const e=t.startsWith("T")&&Qi||Zi.some(e=>t.startsWith(e))&&Xi||"";if(e===Qi){const e=fo(t);if(e)return{simplified:!0,setFormat:e,bestOf:1}}if(e===Xi)return function(t){const e=t.split("-"),n=function(t){const e=Zi.find(e=>t.startsWith(e));if(!e)return;const n=t.slice(e.length),r=/^(\d+)([A-Z]*)$/.exec(n);if(!r)return;const i=go(r[1]);if(!i)return;const o=r[2];let a=!1,s=!1;const c=[];for(const t of o)"X"===t?a=!0:"A"===t?s=!0:c.push(t);return{matchRoot:e,count:i,exactly:a,aggregate:s,matchMods:c}}(e[0]);if(!n)return;const{matchRoot:r,count:i,exactly:o,aggregate:a,matchMods:s}=n,c=o&&1!==i?void 0:i,u=o&&1!==i?i:void 0;let d,p,l,m;const f={setFormat:d,finalSetFormat:p,gameFormat:l,matchUpConstraint:m,sCount:0,fCount:0,gCount:0,mCount:0};for(let t=1;t<e.length;t++){if(!uo(e[t],f))return}return({setFormat:d,finalSetFormat:p,gameFormat:l,matchUpConstraint:m}=f),function({setFormat:t,finalSetFormat:e,gameFormat:n,matchUpConstraint:r,matchRoot:i,aggregate:o,matchMods:a,bestOf:s,exactly:c}){const u=t&&t.timed||e&&e.timed;if(i===Xi){if(!(s&&s<6||u&&c))return}const d=!e||e;if(!t||!d)return;const p=Ei({setFormat:t,exactly:c,bestOf:s});i!==Xi&&(p.matchRoot=i);o&&(p.aggregate=!0);a.length>0&&(p.matchMods=a);e&&(p.finalSetFormat=e);n&&(p.gameFormat=n);r&&(p.matchUpConstraint=r);return p}({setFormat:d,finalSetFormat:p,gameFormat:l,matchUpConstraint:m,matchRoot:r,aggregate:a,matchMods:s,bestOf:c,exactly:u})}(t)}}function uo(t,e){const n=t.indexOf(":");if(n<0)return!1;const r=t.slice(0,n),i=t.slice(n+1);if(!(r in no))return!1;if("S"===r){if(e.sCount++,e.sCount>1)return!1;e.setFormat=po(t,i)}else if("F"===r){if(e.fCount++,e.fCount>1)return!1;e.finalSetFormat=po(t,i)}else if("G"===r){if(e.gCount++,e.gCount>1)return!1;if(e.gameFormat=function(t){const e=/^(.+?)(\d+D)$/.exec(t),n=e?e[1]:t,r=e?Number(e[2].slice(0,-1)):void 0;if(void 0!==r&&(r<1||!Number.isInteger(r)))return;if("TN"===n){const t={type:eo};return r&&(t.deuceAfter=r),t}const i=/^([1-9]\d*)C$/.exec(n);if(i){const t={type:to,count:Number(i[1])};return r&&(t.deuceAfter=r),t}}(i),!e.gameFormat)return!1}else if("M"===r){if(e.mCount++,e.mCount>1)return!1;if(e.matchUpConstraint=function(t){const e=/^T(\d+)$/.exec(t);if(!e)return;const n=go(e[1]);return n?{timed:!0,minutes:n}:void 0}(i),!e.matchUpConstraint)return!1}return!0}function po(t,e){return e.startsWith("TB")?function(t){const e=mo(t);return!1!==e&&("object"==typeof e?{tiebreakSet:e}:void 0)}(e):e.startsWith("O")?function(t){const e=/^O([1-9]\d*)$/.exec(t);return e?{outs:Number(e[1])}:void 0}(e):e.startsWith("T")?fo(e):function(t,e){const n=/^[FS]:(\d+)([A-Za-z]*?)(WB(\d+))?(?=[/@]|$)/.exec(t),r=n&&ho(n[2])||!1,i=!n?.[2]||r,o=n?go(n[1]):void 0,a=n?.[4],s=a?go(a):void 0,c=void 0===s||s>=1,u=lo(e),d=!1!==u,p=d&&u||o,l=mo(e.split("/")[1]),m=!1!==l;return!!(o&&i&&m&&d&&c)&&((void 0===s||!l)&&function(t,e,n,r,i){const o={setTo:t};e&&(o.NoAD=!0);n?(o.tiebreakFormat=n,o.tiebreakAt=r):(o.noTiebreak=!0,void 0!==i&&2!==i&&(o.winBy=i));return o}(o,r,l,p,s))}(t,e)}function lo(t,e=!0){const n=t?.indexOf("@")>0&&t.split("@");if(n){return(e?go(n[1]):n[1])||!1}}function mo(t){if(t)return!!t.startsWith("TB")&&function(t){const e=lo(t,!1),n=/^TB(\d+)([A-Za-z]*)/.exec(t),r=n?.[1],i=n&&ho(n[2]),o=!n?.[2]||i,a=go(r);if(!a||!o)return!1;const s={tiebreakTo:a};e&&"string"==typeof e&&!R(e)&&(s.modifier=e);i&&(s.NoAD=!0);return s}(t)}function fo(t){const e=t.slice(1),n=/^(\d+)([PG])?(?:\/TB(\d+))?(@[A-Za-z]+)?$/.exec(e),r=go(n?.[1]);if(!r)return;const i={timed:!0,minutes:r},o=n?.[2];"P"===o?i.based="P":"G"===o&&(i.based="G");const a=n?.[3];if(a){const t=go(a);t&&(i.tiebreakFormat={tiebreakTo:t})}const s=n?.[4],c=[void 0,"P","G",""].includes(s);if(s&&!c){const t=/^(\d+)([PGA])?(?:\/TB\d+)?(@)([A-Za-z]+)$/.exec(e)?.[4];return t?(i.modifier=t,i):void 0}return s&&(i.based=s),i}function ho(t){return t?.includes(Ji)}function go(t){const e=Number(t);return Number.isNaN(e)?0:e}function Io({matchUpFormat:t}){if(!m(t)||""===t)return!1;const e=co(t),n=/-S:(\d+)\/TB(\d{1,2})@?(\d?)/.exec(t),r=n?.[1],i=n?.[2],o=n?.[3],a=/-F:(\d+)\/TB(\d{1,2})@?(\d?)/.exec(t),s=a?.[1],c=a?.[2],u=a?.[3];return ro(e,!!(n&&i&&r===o||a&&c&&s===u))===t.replaceAll(/T(\d+)G(?=\/TB|@|-|$)/g,"T$1")}const So=/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])$/,yo=/^((0\d|1\d|2[0-3]):[0-5]\d(:[0-5]\d)?)([.,]\d{3})?$/,vo=/^(\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?$/,Uo=/^(\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 Po(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Lo(t.scheduledTime)),!e)return;const n=_o(t.scheduledTime);let r=Lo(e);return r&&n&&(r+=`T${n}`),r}function To(t){if("object"!=typeof t||Array.isArray(t))return!1;return"[object Date]"===Object.prototype.toString.call(t)}function wo(t){const e="string"==typeof t?t?.split(" "):[];if(t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase()))return!1;const n=Go(t,!0,!0);return!!(!t||n&&Uo.test(n))}function Do(t){return Co(t)||So.test(t)}const Ro=t=>{const e=Mo(t)||Co(t)?new Date(t):new Date,n=e.getUTCMonth()+1,r=n<10?`0${n}`:`${n}`;return`${e.getUTCFullYear()}-${Yo(r)}-${Yo(e.getUTCDate())}`};function bo(t,e="-",n="YMD"){if(!t)return"";"string"!=typeof t||t.includes("T")||(t+="T00:00");const r=new Date(t);let i=""+(r.getMonth()+1),o=""+r.getDate();const a=r.getFullYear();return i.length<2&&(i="0"+i),o.length<2&&(o="0"+o),"DMY"===n?[o,i,a].join(e):"MDY"===n?[i,o,a].join(e):"YDM"===n?[a,o,i].join(e):"DYM"===n?[o,a,i].join(e):"MYD"===n?[i,a,o].join(e):[a,i,o].join(e)}function No(t){const e=t?new Date(t):new Date,n=e.getTimezoneOffset();return new Date(e.getTime()-60*n*1e3)}function Mo(t){if("boolean"==typeof t)return!1;const e=t instanceof Date&&t||!Number.isNaN(Number(t))&&new Date(t)||!1;return e&&!Number.isNaN(Number(e.valueOf()))}function Ao(t,e){if(!Do(t)||!Do(e))return[];const n=Lo(t)+"T00:00",r=Lo(e)+"T00:00",i=new Date(n),o=new Date(r);const a=[];let s=0;if(Mo(o)&&Mo(i)&&i<=o){const t=i;let e=t.getTime();for(;e<=o.getTime()&&s<300;)s+=1,a.push(new Date(t)),e=t.setDate(t.getDate()+1)}return a.map(t=>bo(t))}const Eo=/^([+-]?\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 Co(t){return"string"==typeof t&&Eo.test(t)}function Oo(t){return"string"==typeof t&&(!!Co(t)&&/([zZ]|[+-]\d{2}:?\d{2})$/.test(t))}function ko(t){if("string"!=typeof t)return!1;const e=t.split("Z")[0].split(":"),n=e.every(t=>!Number.isNaN(Number.parseInt(t)));return!(e.length<2||!n||Number.parseInt(e[0])>23||Number.parseInt(e[1])>60)}function Fo(t){const e=_o(t);if(!e)return 0;const[n,r]=e.split(":").map(t=>Number.parseInt(t));return 60*n+r}function xo(t){return ko(t)?t.split(":").slice(0,2).map(Yo).join(":"):void 0}function _o(t){return Co(t)&&t.indexOf("T")>0?xo(t.split("T").reverse()[0]):xo(t)}function Lo(t){return Co(t)||vo.test(t)?t.split("T")[0]:""}function Bo(t,e){const n=new Date(t);return n.setUTCDate(n.getUTCDate()+e),Lo(n.toISOString())}function Vo(t){t="string"==typeof t?t:"00:00";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,Number.isNaN(Number.parseInt(n.hours))||Number.isNaN(Number.parseInt(n.minutes))||n.ampm&&!["AM","PM"].includes(n.ampm.toUpperCase())?{}:n}function Go(t,e,n){const r=Lo(t),i=_o(t),o=r?i:t;return t?e&&(r&&n&&t||function(t){const e=Vo(t);return e.ampm&&e.hours&&("pm"===e.ampm.toLowerCase()&&Number.parseInt(e.hours)<12&&(e.hours=(e.hours&&Number.parseInt(e.hours)||0)+12),"am"===e.ampm.toLowerCase()&&"12"===e.hours&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(Yo).join(":")}(o))||function(t){const e=Vo(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}`)}(o):void 0}function jo(t,e){const n=Vo(t),r=Vo(e);if(Number.parseInt(n.hours)<Number.parseInt(r.hours))return-1;if(Number.parseInt(n.hours)>Number.parseInt(r.hours))return 1;if(n.hours===r.hours){if(Number.parseInt(n.minutes)<Number.parseInt(r.minutes))return-1;if(Number.parseInt(n.minutes)>Number.parseInt(r.minutes))return 1}return 0}function qo(t,e=7){const n=Lo(t)+"T00:00",r=new Date(n);return bo(new Date(r.setDate(r.getDate()+e)))}function Wo(t,e=void 0){const[n,r]=(t||"00:00").split(":").map(Yo),i=No(e).setHours(n,r,0,0);return No(i)}function $o(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 Ho(t,e){const n=_o(t);if(!n)return"00:00";const r=Number.isNaN(e)?0:e;return _o(zo(Wo(n),r).toISOString())||"00:00"}function zo(t,e){const n=new Date(t);return new Date(n.getTime()+6e4*e)}function Yo(t){return t.toString()[1]?t:"0"+t}function Ko(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 Qo={addDays:qo,addWeek:function(t){return qo(t)},addMinutesToTimeString:Ho,convertTime:Go,getIsoDateString:Po,getUTCdateString:Ro,DateHHMM:function(t){const e=new Date(t);return function(t,e){const n=Number.parseInt(t,10),r=Math.floor(n/3600),i=Math.floor((n-3600*r)/60),o=n-3600*r-60*i;return(!e||e?.displaySeconds?r+":"+i+":"+o:r+":"+i).split(":").map(Yo).join(":")}(e.getSeconds()+60*e.getMinutes()+3600*e.getHours(),{displaySeconds:!1})},extractDate:Lo,extractTime:_o,formatDate:bo,getDateByWeek:function(t,e,n,r=!1){const i=new Date(e,0,1+7*(t-1)),o=r?0:1;return i.setDate(i.getDate()+(o-i.getDay())),bo(i,n)},isISODateString:Co,isValidEmbargoDate:Oo,isDate:Mo,isTimeString:ko,offsetDate:No,offsetTime:function(t){return No(t).getTime()},sameDay:Ko,timeStringMinutes:Fo,timeToDate:Wo,timeUTC:function(t){const e=Mo(t)||Co(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())},validTimeValue:wo,validDateString:So,timeValidation:Uo,dateValidation:vo};function Jo(t,e){return`${t}-${e}`}function Xo(t){const e=t.category;if("object"!=typeof e||!e)return{error:ar};let{ageCategoryCode:n,ageMaxDate:r,ageMinDate:i,ageMax:o,ageMin:a}=e;const s=e.categoryName;let c;var u;if(!(u="string",[n,r,i,s].filter(Boolean).every(t=>typeof t===u)&&(t=>t.filter(Boolean).every(P))([o,a])&&[r,i].filter(Boolean).every(Do)))return{error:ar};const d=t.consideredDate??Lo((new Date).toLocaleDateString("sv"));if(!d||!Do(d))return{error:_e};const[p]=d.split("-").slice(0,3).map(t=>Number.parseInt(t)),l=Bo(d,-1);if(!l)return{error:_e};const[m,f]=l.split("-").slice(1,3).map(t=>Number.parseInt(t)),h=`${Yo(m)}-${Yo(f)}`,g=Bo(d,1);if(!g)return{error:_e};const[I,S]=g.split("-").slice(1,3).map(t=>Number.parseInt(t)),y=`${Yo(I)}-${Yo(S)}`;let v=a&&Bo(d,-365*a),U=o&&Bo(d,-365*o);const T=[],w=t=>!T.includes(t)&&T.push(t);n=n??s;const D=/^([UO]?)(\d{1,2})([UO]?)$/,R=/^C(\d{1,2})-(\d{1,2})$/,b=n?.includes("-"),N=b&&n?.match(R),M=n?.match(D);function A(t){const r=Jo(p-t-1,y);e.ageMin&&e.ageMin>t&&w(`Invalid submitted ageMin: ${a}`),e.ageMax&&e.ageMax>t&&w(`Invalid submitted ageMax: ${o}`),e.ageMinDate&&e.ageMinDate!==r&&w(`Invalid submitted ageMinDate: ${i}`),i=r,n&&(e.ageMax&&e.ageMax!==t&&(w(`Invalid submitted ageMax: ${o}`),v=void 0),o=t)}function E(t){const i=Jo(p-t,h);e.ageMaxDate&&e.ageMaxDate!==i&&w(`Invalid submitted ageMaxDate: ${r}`),r=i,n&&(e.ageMin&&e.ageMin!==t+1&&(w(`Invalid submitted ageMin: ${a}`),v=void 0),a=t+1)}function C(t){const s=D.exec(t)??[],[c,u,d]=s.slice(1),l=Number.parseInt(u);"U"===c?(e.ageMaxDate&&e.ageMaxDate!==r&&w(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),function(t){const r=Jo(p-t,y);e.ageMinDate&&e.ageMinDate!==r&&w(`Invalid submitted ageMinDate: ${i}`),i=r,n&&(e.ageMax&&e.ageMax!==t-1&&(w(`Invalid submitted ageMax: ${o}`),U=void 0),o=t-1)}(l)):"O"===c&&E(l),"U"===d?(e.ageMaxDate&&e.ageMaxDate!==r&&w(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),A(l)):"O"===d&&function(t){const i=Jo(p-t-1,h);e.ageMaxDate&&e.ageMaxDate!==i&&w(`Invalid submitted ageMaxDate: ${r}`),r=i,n&&(e.ageMin&&e.ageMin!==t&&(w(`Invalid submitted ageMin: ${a}`),v=void 0),a=t)}(l),r=(r??v)||void 0,i=(i??U)||void 0}N?function(){if(r=void 0,i=void 0,o=void 0,a=void 0,e.ageMin){const t=p-e.ageMin;r=Jo(t,h)}if(e.ageMax){const t=p-e.ageMax-1;i=Jo(t,y)}const[t,s]=(n?.match(R)??[]).slice(1).map(t=>Number.parseInt(t));t<=s?(a=t,o=s,c=!0):w(`Invalid combined age range ${n}`)}():b?n?.split("-").forEach(C):M&&n?C(n):(a&&E(a),o&&A(o)),o&&e?.ageMin&&e?.ageMin>o&&(w(`Invalid submitted ageMin: ${e?.ageMin}`),a=void 0);const O=Ei({consideredDate:d,combinedAge:c,ageMaxDate:r,ageMinDate:i,ageMax:o,ageMin:a});return T.length&&(O.errors=T),O}function Zo({category:t}){if(!f(t))return{error:sr};const e=Xo({category:t});if(e.error)return{error:e};const{ratingMax:n,ratingMin:r}=t;return n&&!P(n)?Ci({result:{error:sr},context:{ratingMax:n}}):r&&!P(r)?Ci({result:{error:sr},context:{ratingMin:r}}):{...e}}function ta({childCategory:t,withDetails:e,category:n}){const r=Zo({category:n}),i=Zo({category:t}),o=i.ageMin&&(r.ageMin&&i.ageMin<r.ageMin||r.ageMax&&i.ageMin>r.ageMax),a=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=Ei({invalidRatingRange:u,invalidAgeMinDate:s,invalidAgeMaxDate:c,invalidBallType:d,invalidAgeMax:a,invalidAgeMin:o,valid:!(u||s||c||d||a||o)},!0);return e&&Object.assign(p,{categoryDetails:r,childCategoryDetails:i}),p}function ea({checkCategory:t=!0,collectionDefinition:e,checkCollectionIds:r,checkGender:o=!0,referenceCategory:a,referenceGender:c,event:u}){c=c??u?.gender;const d="validateCollectionDefinition",p=[];if("object"!=typeof e)return p.push(`collectionDefinition must be an object: ${e}`),Ci({result:{errors:p,error:ir},stack:d});const{collectionValueProfiles:l,collectionGroupNumber:m,collectionValue:f,collectionId:h,matchUpCount:g,matchUpFormat:I,matchUpValue:S,matchUpType:y,scoreValue:v,setValue:U,category:P,gender:T}=e;r&&"string"!=typeof h&&p.push(`collectionId is not type string: ${h}`),"number"!=typeof g&&p.push(`matchUpCount is not type number: ${g}`),y&&!z([n,i,s],y)&&p.push(`matchUpType must be SINGLES, DOUBLES, or HYBRID: ${y}`);if(1!==[!!l?.length].concat([S,f,v,U].map(R)).filter(Boolean).length&&p.push("Missing value definition for matchUps: matchUpValue, collectionValue, or collectionValueProfiles"),S&&"number"!=typeof S&&p.push(`matchUpValue is not type number: ${S}`),f&&"number"!=typeof f&&p.push(`collectionValue is not type number: ${f}`),l&&g){const t=J({collectionValueProfiles:l,matchUpCount:g});t.errors&&p.push(...t.errors)}if(m&&"number"!=typeof m&&p.push(`collectionGroupNumber is not type number: ${f}`),I&&!Io({matchUpFormat:I})&&p.push(`Invalid matchUpFormat: ${I}`),o){const t=Ki({referenceGender:c,matchUpType:y,gender:T});if(t.error)return Ci({context:{referenceGender:c,gender:T},result:t,stack:d})}if(t&&a&&P){const t=ta({category:a,childCategory:P});if(!t.valid)return Ci({result:{error:ar},context:t,stack:d})}return p.length?Ci({result:{errors:p,error:rr},stack:d}):{valid:!0}}function na(t){const e=!(!1===t?.enforceCategory||!t?.category),n=!(!1===t?.enforceGender||!t?.gender),r=t?.checkCollectionIds,i=t?.tieFormat,o=t?.event,a="validateTieFormat",s=[],c=function(t){const{tieFormat:e,stack:n}=t;if(!t||!e||!f(e))return Ci({result:{error:ue},context:{tieFormat:e,message:"tieformat must be an object"},stack:n});if(!f(e.winCriteria))return Ci({result:{error:ue},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:n});if(!Array.isArray(e.collectionDefinitions))return Ci({result:{error:ue},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:n});return{...Y}}({...t,stack:a});if(c?.error)return c;let u;const d=i.collectionDefinitions.every(i=>{const{setValue:a,scoreValue:c,collectionValue:d}=i;!a&&!c||d||(u=!0);const{valid:p,errors:l}=ea({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:i,checkCollectionIds:r,checkCategory:e,checkGender:n,event:o});return!!p||(Array.isArray(l)&&s.push(...l),!1)}),p="number"==typeof i.winCriteria?.valueGoal&&i.winCriteria?.valueGoal>0&&!u||i.winCriteria?.aggregateValue;if(!p&&!i.winCriteria?.aggregateValue)return u?s.push("aggregateValue is required"):s.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),Ci({context:{tieFormat:i,errors:s,aggregateValueImperative:u},result:{error:ue},stack:a});const l=i.collectionDefinitions.map(({collectionId:t})=>t),m=!r||l.length===M(l).length,h=d&&p&&m;return h?{valid:h,errors:s}:Ci({result:{error:ue},context:{tieFormat:i,errors:s},stack:a})}const ra="resourceSubType",ia="resourceType",oa="identifier",aa="name",sa={RESOURCE_SUB_TYPE:ra,RESOURCE_TYPE:ia,IDENTIFIER:oa,NAME:aa};function ca(t,e,n,r,i=0){if(Ri().makeDeepCopy)return Ri().makeDeepCopy(t,e,n,r);const o=oi(),{stringify:a,toJSON:s,ignore:c,modulate:u}=o??{};if(!o?.enabled&&!n||"object"!=typeof t||l(t)||null===t||"number"==typeof o?.threshold&&i>=o.threshold)return t;const d=Array.isArray(t)?[]:{},p=Object.keys(t).filter(t=>!n||!c||Array.isArray(c)&&!c.includes(t)||l(c)&&!c(t)),m=(t,e)=>{d[t]=l(e?.toString)?e.toString():JSON.stringify(e)};for(const o of p){const c=t[o],p=l(u)?u(c):void 0;if(void 0!==p)d[o]=p;else if(e&&"extensions"===o&&Array.isArray(c)){const t=ua(c);Object.assign(d,...t)}else r&&"extensions"===o?d[o]=[]:Array.isArray(a)&&a.includes(o)?m(o,c):Array.isArray(s)&&s.includes(o)&&l(c?.toJSON)?d[o]=c.toJSON():null===c?d[o]=void 0:To(c)?d[o]=new Date(c).toISOString():d[o]=ca(c,e,n,r,i+1)}return d}function ua(t){return t?.map(t=>{const{name:e,value:n}=t;return e&&n&&{[`_${e}`]:n}}).filter(Boolean)}function da(t=1,e,n){return L(0,t).map(()=>pa(e,n))}function pa(t,e){const n=e??Math.random,r=[];for(let t=0;t<256;t++)r[t]=(t<16?"0":"")+t.toString(16);const i=Math.trunc(4294967295*n()),o=Math.trunc(4294967295*n()),a=Math.trunc(4294967295*n()),s=Math.trunc(4294967295*n()),c=r[255&i]+r[i>>8&255]+r[i>>16&255]+r[i>>24&255]+"-"+r[255&o]+r[o>>8&255]+"-"+r[o>>16&15|64]+r[o>>24&255]+"-"+r[63&a|128]+r[a>>8&255]+"-"+r[a>>16&255]+r[a>>24&255]+r[255&s]+r[s>>8&255]+r[s>>16&255]+r[s>>24&255];return"string"==typeof t?`${t}_${c.replaceAll("-","")}`:c}var la={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}},ma={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}},fa={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}},ha={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}},ga={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}},Ia={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}},Sa={collectionDefinitions:[{category:{ageCategoryCode:"14U"},collectionName:"14U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],collectionGroups:[{groupNumber:1,groupName:"Doubles",groupValue:1,winCriteria:{valueGoal:2}}],tieFormatName:"Brewer Cup",winCriteria:{valueGoal:4}},ya={winCriteria:{valueGoal:23},tieFormatName:"USTA Ozaki Cup",collectionDefinitions:[{category:{ageCategoryCode:"18U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"18U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"18U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"18U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"18U"},collectionName:"18U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"16U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"16U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"16U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"16U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"16U"},collectionName:"16U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"14U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"14U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"14U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"14U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"14U"},collectionName:"14U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"12U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"12U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"12U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"12U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"12U"},collectionName:"12U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"12U"},collectionName:"12U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"12U"},collectionName:"12U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1}]};const va="SET3-S:6/TB7",Ua="SET3-S:6NOAD/TB7-F:TB10",Pa={FORMAT_STANDARD:va,FORMAT_STANDARD_NOAD:"SET3-S:6NOAD",FORMAT_ATP_DOUBLES:Ua,FORMAT_SHORT_SETS:"SET3-S:4/TB7",FORMAT_FAST4:"SET3-S:4/TB5@3",FORMAT_GRAND_SLAM:"SET5-S:6/TB7",FORMAT_ONE_SET:"SET1-S:6/TB7",FORMAT_MATCH_TIEBREAK:"SET1-S:TB10",FORMAT_SET3_TB7:"SET3-S:6/TB7-F:TB7",FORMAT_PRO_SET:"SET1-S:8/TB7",FORMAT_COLLEGE_PRO_SET:"SET1-S:8/TB7@7",TIMED20:"SET1-S:T20"};var Ta={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}},wa={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",collectionValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"USTA Collegiate",winCriteria:{valueGoal:4}},Da={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}},Ra={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"World Team Tennis ITT",winCriteria:{aggregateValue:!0}},ba={tieFormatName:"INTENNSE 2026",winCriteria:{aggregateValue:!0},collectionDefinitions:[{collectionId:"intennse-ms",collectionName:"Men's Singles",matchUpType:"SINGLES",matchUpCount:2,matchUpFormat:"SET2XA-S:T10",scoreValue:1,gender:"MALE",category:{categoryName:"MS"}},{collectionId:"intennse-ws",collectionName:"Women's Singles",matchUpType:"SINGLES",matchUpCount:2,matchUpFormat:"SET2XA-S:T10",scoreValue:1,gender:"FEMALE",category:{categoryName:"WS"}},{collectionId:"intennse-md",collectionName:"Men's Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"MALE",category:{categoryName:"MD"}},{collectionId:"intennse-wd",collectionName:"Women's Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"FEMALE",category:{categoryName:"WD"}},{collectionId:"intennse-xd",collectionName:"Mixed Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"MIXED",category:{categoryName:"XD"}}]},Na={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}},Ma={collectionDefinitions:[{collectionGroupNumber:1,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6NOAD/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:1,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:2,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6NOAD/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:2,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:3,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6NOAD/TB7-F:TB10",matchUpValue:3},{collectionGroupNumber:3,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3}],collectionGroups:[{groupNumber:1,groupName:"Day 1"},{groupNumber:2,groupName:"Day 2"},{groupNumber:3,groupName:"Day 3"}],tieFormatName:"Laver Cup",winCriteria:{valueGoal:13}},Aa={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA Tennis on Campus",winCriteria:{aggregateValue:!0}};const Ea="COLLEGE_DEFAULT",Ca="COLLEGE_JUCO",Oa="COLLEGE_D3",ka="DOMINANT_DUO",Fa="DOMINANT_DUO_MIXED",xa="INTENNSE_2026",_a="LAVER_CUP",La="TEAM_DOUBLES_3_AGGREGATION",Ba="USTA_BREWER_CUP",Va="USTA_OZAKI_CUP",Ga="USTA_COLLEGE",ja="USTA_GOLD_TEAM_CHALLENGE",qa="USTA_LEVEL_1",Wa="USTA_INTERSECTIONAL",$a="USTA_SECTION_BATTLE",Ha="USTA_SOUTHERN_LEVEL_5",za="USTA_TOC",Ya="USTA_WTT_ITT",Ka="USTA_ZONAL",Qa={COLLEGE_D3:Oa,COLLEGE_DEFAULT:Ea,COLLEGE_JUCO:Ca,DOMINANT_DUO:ka,DOMINANT_DUO_MIXED:Fa,INTENNSE_2026:xa,LAVER_CUP:_a,TEAM_DOUBLES_3_AGGREGATION:La,USTA_BREWER_CUP:Ba,USTA_OZAKI_CUP:Va,USTA_COLLEGE:Ga,USTA_GOLD_TEAM_CHALLENGE:ja,USTA_INTERSECTIONAL:Wa,USTA_LEVEL_1:qa,USTA_SECTION_BATTLE:$a,USTA_SOUTHERN_LEVEL_5:Ha,USTA_TOC:za,USTA_WTT_ITT:Ya,USTA_ZONAL:Ka},Ja="STANDARD",Xa={[Ja]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[Oa]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:va,matchUpCount:6,matchUpValue:1},tieFormatName:"College D3",valueGoal:5},[Ea]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:va,matchUpCount:6,matchUpValue:1},tieFormatName:"College Default",valueGoal:4},[Ca]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:va,matchUpCount:6,matchUpValue:1},tieFormatName:"College JUCO",valueGoal:5},[_a]:Ma,[ka]:Ta,[Fa]:Ia,[xa]:ba,[La]:ma,[Ba]:Sa,[Va]:ya,[Ga]:wa,[ja]:la,[Wa]:ga,[qa]:Da,[$a]:ha,[Ha]:fa,[Ya]:Ra,[za]:Aa,[Ka]:Na},Za=t=>{const e=t?.namedFormat&&Object.keys(Xa).includes(t.namedFormat)?t.namedFormat:Ja,r=Array.isArray(t?.uuids)?t?.uuids:[];let o;const{category:a,gender:s}=t?.event??{},c=ca(Xa[e],!1,!0),u=e=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??pa();const n=t?.event?.eventId;return r.pop()??`${n}-COL-${e+1}`};return c.hydrate?(o={winCriteria:{valueGoal:c.valueGoal},collectionDefinitions:[{collectionId:u(0),matchUpFormat:Ua,collectionName:"Doubles",matchUpType:i,...c.doubles},{collectionId:u(1),matchUpFormat:va,collectionName:"Singles",matchUpType:n,...c.singles}]},c.tieFormatName&&(o.tieFormatName=c.tieFormatName)):(c.collectionDefinitions.forEach((t,e)=>t.collectionId=u(e)),o=c),t?.hydrateCollections&&o.collectionDefinitions.forEach(t=>{a&&!t.category&&(t.category=a),s&&!t.gender&&(t.gender=s)}),o},ts="SINGLES",es="SINGLES",ns="DOUBLES",rs="DOUBLES",is="TEAM",os="TEAM",as="HYBRID",ss="HYBRID",cs={AGE:"AGE",BOTH:"BOTH",DOUBLES:ns,DOUBLES_EVENT:rs,HYBRID:as,HYBRID_EVENT:ss,RATING:"RATING",SINGLES:ts,SINGLES_EVENT:es,TEAM_EVENT:os,TEAM:is},us="MAIN",ds="QUALIFYING",ps="CONSOLATION",ls="VOLUNTARY_CONSOLATION",ms="PLAY_OFF",fs=[us,ds,ps,ms,ls],hs={[ds]:1,[us]:2,[ms]:3,[ps]:3,[ls]:4},gs="finishingPositions",Is="aggregateEventStructures",Ss={[us]:1,[ms]:2,[ps]:3,[ds]:4,[ls]:5},ys={[ms]:1,[us]:2,[ps]:3,[ds]:4,[ls]:5},vs="CLUSTER",Us="ADJACENT",Ps="SEPARATE",Ts="WATERFALL",ws="ITEM",Ds="CONTAINER",Rs="DRAW",bs="RANDOM",Ns="TOP_DOWN",Ms="BOTTOM_UP",As="POSITION",Es="WINNER",Cs="LOSER",Os="FIRST_MATCHUP",ks="AD_HOC",Fs="FEED_IN",xs="COMPASS",_s="OLYMPIC",Ls="SINGLE_ELIMINATION",Bs="DOUBLE_ELIMINATION",Vs="FIRST_MATCH_LOSER_CONSOLATION",Gs="FIRST_ROUND_LOSER_CONSOLATION",js="LUCKY_DRAW",qs="ADAPTIVE",Ws="CURTIS_CONSOLATION",$s="FEED_IN_CHAMPIONSHIP_TO_SF",Hs="FEED_IN_CHAMPIONSHIP_TO_SF",zs="FEED_IN_CHAMPIONSHIP_TO_QF",Ys="FEED_IN_CHAMPIONSHIP_TO_QF",Ks="FEED_IN_CHAMPIONSHIP_TO_R16",Qs="FEED_IN_CHAMPIONSHIP_TO_R16",Js="MODIFIED_FEED_IN_CHAMPIONSHIP",Xs="MODIFIED_FEED_IN_CHAMPIONSHIP",Zs="FEED_IN_CHAMPIONSHIP",tc="PAGE_PLAYOFF",ec="PLAYOFF",nc="SWISS",rc="DOUBLE_ROUND_ROBIN",ic="ROUND_ROBIN",oc="ROUND_ROBIN_WITH_PLAYOFF",ac="DECIDER",sc="BACKDRAW",cc={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"}},uc={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},dc={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"}},pc="WIN_RATIO",lc="ROUND_OUTCOME",mc=[qs,xs,Ws,Ys,Qs,Hs,Zs,zs,Ks,$s,Vs,Gs,js,Xs,_s,tc,ec,oc],fc={MAIN:us,QUALIFYING:ds,CONSOLATION:ps,ITEM:ws,CONTAINER:Ds,FIRST_MATCHUP:Os,WINNER:Es,LOSER:Cs,AD_HOC:ks,FEED_IN:Fs,FLEX_ROUNDS:"AD_HOC",COMPASS:xs,PLAY_OFF:ms,PAGE_PLAYOFF:tc,PAGE_PLAYOFF_ATTRIBUTES:{0:{name:"Qualifier 1",abbreviation:"Q1"},"0-1":{name:"Eliminator",abbreviation:"EL"},"0-2":{name:"Final",abbreviation:"F"}},PLAYOFF:ec,SWISS:nc,OLYMPIC:_s,KNOCKOUT:"SINGLE_ELIMINATION",SINGLE_ELIMINATION:Ls,DOUBLE_ELIMINATION:Bs,CURTIS:Ws,FICSF:$s,FICQF:zs,FICR16:Ks,MFIC:Js,VOLUNTARY_CONSOLATION:ls,FIRST_MATCH_LOSER_CONSOLATION:Vs,FIRST_ROUND_LOSER_CONSOLATION:Gs,MODIFIED_FEED_IN_CHAMPIONSHIP:Xs,FEED_IN_CHAMPIONSHIP_TO_R16:Qs,FEED_IN_CHAMPIONSHIP_TO_QF:Ys,FEED_IN_CHAMPIONSHIP_TO_SF:Hs,FEED_IN_CHAMPIONSHIP:Zs,LUCKY_DRAW:js,ADAPTIVE:qs,ROUND_ROBIN_WITH_PLAYOFF:oc,ROUND_ROBIN:ic,DECIDER:ac,BACKDRAW:sc,COMPASS_ATTRIBUTES:cc,OLYMPIC_ATTRIBUTES:uc,ADAPTIVE_ATTRIBUTES:dc,DRAW:Rs,RANDOM:bs,TOP_DOWN:Ns,BOTTOM_UP:Ms,CLUSTER:vs,ADJACENT:Us,SEPARATE:Ps,WATERFALL:Ts,WIN_RATIO:pc,ROUND_OUTCOME:lc,MULTI_STRUCTURE_DRAWS:mc,generatedDrawTypes:[ks,qs,xs,Ws,Bs,Ys,Qs,Hs,Zs,Fs,Vs,Gs,js,Xs,_s,tc,ec,ic,oc,Ls,nc],stageOrder:hs,finishOrder:Ss,AGGREGATE_EVENT_STRUCTURES:Is,FINISHING_POSITIONS:gs},hc="tournamentRecords",gc="policyDefinitions",Ic="tournamentRecord",Sc="onlineResource",yc="drawDefinition",vc="tieFormatName",Uc="matchUpFormat",Pc="participantId",Tc="scheduleDates",wc="tournamentId",Dc="scheduleDate",Rc="roundNumber",bc="structureId",Nc="participant",Mc="matchUpIds",Ac="entryStage",Ec="policyType",Cc="structures",Oc="eventType",kc="matchUpId",Fc="tieFormat",xc="inContext",_c="structure",Lc="courtIds",Bc="personId",Vc="venueIds",Gc="matchUps",jc="courtId",qc="eventId",Wc="matchUp",$c="drawId",Hc="error",zc="event",Yc="param",Kc="uuids",Qc="penaltyType",Jc="penaltyId",Xc="venueId",Zc="stage",tu="averageMatchUpMinutes",eu="recoveryMinutes",nu="periodLength",ru="object",iu="array",ou="_validate",au="_message",su="_invalid",cu="_ofType",uu="_anyOf",du="_oneOf",pu={[Sc]:t=>3===V(Object.keys(t),[ra,ia,oa]).length,[vc]:t=>t&&Za({namedFormat:t}),[Kc]:t=>!t||Array.isArray(t)&&t.every(m),[Fc]:t=>!na({tieFormat:t}).error,[Oc]:t=>[ts,ns,is].includes(t),[Ac]:t=>fs.includes(t)},lu={[hc]:nt,[Ic]:rt,[gc]:Ue,[yc]:st,[Pc]:sn,[Uc]:pe,[wc]:ot,[bc]:Bt,[Mc]:he,[Nc]:on,[Sc]:ir,[Oc]:$t,[Cc]:Gt,[kc]:fe,[Fc]:ue,[_c]:jt,[jc]:Me,[Gc]:Ie,[qc]:zt,[Wc]:Se,[Lc]:Ae,[Vc]:Ae,[Qc]:Nn,[Jc]:Mn,[Xc]:Bn,[$c]:bt,[zc]:Ht,[Zc]:Xt},mu={[hc]:ru,[gc]:ru,[Ic]:ru,[yc]:ru,[Sc]:ru,[Tc]:iu,[Nc]:ru,[Mc]:iu,[Cc]:iu,[Fc]:ru,[_c]:ru,[Lc]:iu,[Vc]:iu,[Gc]:iu,[Wc]:ru,[zc]:ru,[Kc]:iu};function fu(t,e,n){if(!t&&!f(t))return{error:sr};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:sr};const{paramError:r,errorParam:i}=function(t,e){let n,r;const i=e.find(({_ofType:e,_oneOf:i,_anyOf:o,_validate:a,_info:s,...c})=>{const u=i&&function(t,e){if(!e)return;const n=hu(t,e);return 1!==n.length?{error:sr}:n.reduce((t,e)=>({...t,[e]:!0}),{})}(t,i);if(u?.error)return u.error;u&&Object.assign(c,u);const d=o&&function(t,e){if(!e)return;const n=hu(t,e).filter(e=>t[e]);return n.length<1?{error:sr}:n.reduce((t,e)=>({...t,[e]:!0}),{})}(t,o);if(d?.error)return d.error;d&&Object.assign(c,d);const p=Object.keys(c).filter(t=>"boolean"==typeof c[t]),m=p.find(i=>{const o=a&&!l(a),u=void 0!==t[i]&&!a&&function(t,e,n){if(n=n||mu[e]||"string","array"===n)return!Array.isArray(t[e]);return typeof t[e]!==n}(t,i,e),d=c[i]&&null==t[i],p=o||u||d||a&&void 0!==t[i]&&(m=t[i],!(!l(f=a)||f(m)))||pu[i]&&!pu[i](t[i]);var m,f;return p&&(n=i,r=s),p});return!p.length||m});return{paramError:i,errorParam:n,paramInfo:r}}(t,e);if(!r)return{valid:!0};const o=r[ou]&&(r[Hc]||r[su])||null==t?.[i]&&(r[Hc]||r[su]||lu[i]||sr)||sr;return Ci({info:{param:i??(r[du]&&Object.keys(r[du]).join(", ")),message:r[au]},result:{error:o},stack:n})}function hu(t,e){return V(Object.keys(t),Object.keys(e))}const gu="DYNAMIC",Iu="RANKING",Su="RATING",yu="SCALE",vu="SEEDING",Uu={RANKING:Iu,RATING:Su,SCALE:yu,SEEDING:vu};function Pu(t){const e=fu(t,[{[Nc]:!0}]);if(e.error)return e;const n=t.participant.timeItems?.filter(({itemType:t})=>t?.startsWith(yu)&&[Iu,Su,vu].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,o]=e.itemType.split("."),a=o?`${i}.${o}`:i,s=(t===vu?"seedings":t===Iu&&"rankings")||"ratings";r[s][n]||(r[s][n]=[]),r[s][n].push({scaleValue:e.itemValue,scaleDate:e.itemDate,scaleName:a})}}}return{...Y,...r}}function Tu(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),o=Object.keys(n),a=Object.assign({},...o.filter(t=>t.indexOf("||")).map(t=>t.split("||").map(e=>({[e]:t}))).flat()),s=o.concat(...Object.keys(a)),c=s.includes("*");for(const o of i)if(s.indexOf(o)>=0||c){const i=n[a[o]||o]||c,s=e[o];if("object"!=typeof i||"function"==typeof s||Array.isArray(i)){const t=e[o];if(Array.isArray(i)&&!i.includes(t))return!1;(n[o]||c&&!1!==n[o])&&(r[o]=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[o]=e}else s&&(r[o]={},t(s,i,r[o]))}return}(e,n,r),r}const wu="voluntaryConsolation",Du="competitiveBands",Ru="roundRobinTally",bu="positionActions",Nu="matchUpActions",Mu="rankingPoints",Au="roundNaming",Eu="participant",Cu="progression",Ou="scheduling",ku="avoidance",Fu="scoring",xu="seeding",_u="feedIn",Lu="competition",Bu="draws",Vu="print",Gu={POLICY_TYPE_VOLUNTARY_CONSOLATION:wu,POLICY_TYPE_COMPETITIVE_BANDS:Du,POLICY_TYPE_ROUND_ROBIN_TALLY:Ru,POLICY_TYPE_POSITION_ACTIONS:bu,POLICY_TYPE_MATCHUP_ACTIONS:Nu,POLICY_TYPE_RANKING_POINTS:Mu,POLICY_TYPE_ROUND_NAMING:Au,POLICY_TYPE_PARTICIPANT:Eu,POLICY_TYPE_PROGRESSION:Cu,POLICY_TYPE_SCHEDULING:Ou,POLICY_TYPE_AVOIDANCE:ku,POLICY_TYPE_COMPETITION:Lu,POLICY_TYPE_DISPLAY:"display",POLICY_TYPE_PRIVACY:"participant",POLICY_TYPE_FEED_IN:_u,POLICY_TYPE_SCORING:Fu,POLICY_TYPE_SEEDING:xu,POLICY_TYPE_SANCTIONING:"sanctioning",POLICY_TYPE_AUDIT:"audit",POLICY_TYPE_DRAWS:Bu,POLICY_TYPE_PRINT:Vu};function ju({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:n,participantId:r,internalUse:i,personId:o}){const a=ca(t.find(t=>r&&t.participantId===r||o&&t.person&&t.person.personId===o),!1,i);if(a){const t=e?.[Eu];if(n?.withScaleValues){const{ratings:t,rankings:e}=Pu({participant:a});a.rankings=e,a.ratings=t}if(t?.participant)return Tu({template:t.participant,source:a})}return a}function qu(t){if(!t||"object"!=typeof t)return{error:Ae};if(t.element&&"object"!=typeof t?.element)return{error:sr};if(!t?.name)return{error:Ae,info:"missing name"};if(!t?.element){if(t.discover&&t.tournamentRecords){for(const e of Object.keys(t.tournamentRecords)){const n=qu({element:t.tournamentRecords[e],name:t.name});if(n.error)return Ci({result:n,stack:"removeExtension"})}return{...Y}}return{error:Ae,info:"element required"}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...Y}):{...Y,info:mr}}function Wu({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 $u(t){if("object"!=typeof t)return{error:Ae};const e="addExtension";if(t?.element&&"object"!=typeof t.element)return Ci({result:{error:sr},stack:e});if(!Wu({extension:t.extension}))return Ci({result:{error:sr,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=$u({extension:t.extension,element:n});if(r.error)return Ci({result:r,stack:e})}return{...Y}}return Ci({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),{...Y}}function Hu(t){return t&&"object"==typeof t?t.tournamentRecord?$u({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:rt}:{error:Ae}}function zu(t){return t&&"object"==typeof t?t.drawDefinition?$u({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:ut}:{error:Ae}}function Yu(t){return t&&"object"==typeof t?t.event?$u({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:zt}:{error:Ae}}function Ku(t){if(!t||"object"!=typeof t)return{error:Ae};if(!t.participantId)return{error:sn};const e=t.tournamentRecord?.participants??[],n=ju({participantId:t.participantId,tournamentParticipants:e});return n?$u({creationTime:t.creationTime,extension:t.extension,element:n}):{error:un}}function Qu(t){return t&&"object"==typeof t?t.tournamentRecord?qu({element:t.tournamentRecord,name:t.name}):{error:rt}:{error:Ae}}function Ju(t){return t&&"object"==typeof t?t.drawDefinition?qu({element:t.drawDefinition,name:t.name}):{error:ut}:{error:Ae}}function Xu(t){return t&&"object"==typeof t?t?.event?qu({element:t.event,name:t.name}):{error:zt}:{error:Ae}}function Zu(t){if(!t||"object"!=typeof t)return{error:Ae};if(!t.participantId)return{error:sn};const e=t.tournamentRecord?.participants??[],n=ju({participantId:t.participantId,tournamentParticipants:e});return n?qu({element:n,name:t.name}):{error:un}}function td({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 o=i?.extensions?.find(t=>t?.name===n);return{extension:o,info:o?void 0:mr}}return Ci({result:{error:Ae},stack:"extensionQueries"})}if(!Array.isArray(e.extensions))return{info:"no extensions"};const i=e.extensions.find(t=>t?.name===n);return{extension:i,info:i?void 0:mr}}const ed="appliedPolicies",nd="competitionState",rd="context",id="delegatedOutcome",od="disabled",ad="disableAutoCalc",sd="disableLinks",cd="display",ud="draftState",dd="drawDeletions",pd="factory",ld="flightProfile",md="groupingAttribute",fd="lineUps",hd="linkedTournamentsIds",gd="mutationLocks",Id="participantRepresentatives",Sd="personRequests",yd="positionActions",vd="roundTarget",Ud="sanctioningConstraints",Pd="scheduleLimits",Td="scheduleTiming",wd="schedulingProfile",Dd="subOrder",Rd="tally",bd="tieFormatModification",Nd={ACTIVE_SUSPENSION:"activeSuspension",APPLIED_POLICIES:ed,COMPETITION_STATE:nd,CONTEXT:rd,DELEGATED_OUTCOME:id,DISABLED:od,DISABLE_LINKS:sd,DISABLE_AUTO_CALC:ad,DISPLAY:cd,DRAFT_STATE:ud,DRAW_DELETIONS:dd,DRAW_PROFILE:"drawProfile",EVENT_PROFILE:"eventProfile",EVENT_WITHDRAWAL_REQUESTS:"eventWithdrawalRequests",FLIGHT_PROFILE:ld,GROUPING_ATTRIBUTE:md,LINEUPS:fd,LINKED_TOURNAMENTS:hd,MUTATION_LOCKS:gd,PARTICIPANT_REPRESENTATIVES:Id,PERSON_REQUESTS:Sd,POSITION_ACTIONS:yd,RANKING_POINTS:"rankingPoints",REGISTRATION:"registration",ROUND_TARGET:vd,SANCTIONING_CONSTRAINTS:Ud,SCHEDULE_LIMITS:Pd,SCHEDULE_TIMING:Td,SCHEDULING_PROFILE:wd,STATUS_DETAIL:"statusDetail",SUB_ORDER:Dd,TALLY:Rd,TIE_FORMAT_MODIFICATIONS:bd,FACTORY:pd},Md=[id,od,ad,sd,ld,fd,hd,gd,Id,Sd,vd,Pd,Td,wd,Dd,Rd,bd];function Ad(t){if(Array.isArray(t?.linkedTournamentIds))return t.linkedTournamentIds;const{extension:e}=td({element:t,name:hd});return e?.value?.tournamentIds??[]}function Ed({tournamentRecords:t}){return{tournamentIds:f(t)?Object.keys(t):[],...Y}}function Cd(t,e){const n=!e.length;Qr()&&!n?t.linkedTournamentIds=[...e]:void 0!==t?.linkedTournamentIds&&delete t.linkedTournamentIds,Jr()&&!n?Hu({tournamentRecord:t,extension:{name:hd,value:{tournamentIds:[...e]}}}):Qu({tournamentRecord:t,name:hd})}function Od({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:nt};const e=Ed({tournamentRecords:t}),{tournamentIds:n}=e;if(n?.length>1)for(const e of Object.values(t))Cd(e,n);return{...Y}}function kd({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:nt};for(const e of Object.values(t))Cd(e,[]);return Ci({result:qu({name:hd,tournamentRecords:t,discover:!0}),stack:"unlinkTournaments"})}function Fd({tournamentRecords:t,tournamentId:e}){if("object"!=typeof t)return{error:sr};if(!e)return{error:ot};const n=Ed({tournamentRecords:t}),{tournamentIds:r}=n;if(!r.includes(e))return{error:ot};for(const n of r){const r=t[n],i=Ad(r);if(!i?.length||1===i.length&&i.includes(e)||n===e){Cd(r,[]);continue}Cd(r,i.filter(t=>t!==e))}return{...Y}}function xd({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:n,drawDefinition:r,structure:i,event:o}){if(!Array.isArray(e))return{error:ve};const a={};return n&&s(n),o&&s(o),r&&s(r),i&&s(i),{appliedPolicies:a,...Y};function s(n){const r=n?.extensions,i=r?.find(t=>t.name===ed)?.value;if(i)for(const n of Object.keys(i))(t?e.includes(n):!e.length||e.includes(n))&&(a[n]=ca(i[n],!1,!0))}}function _d({policyTypes:t=[],tournamentRecord:e,drawDefinition:n,structure:r,event:i}){if(!Array.isArray(t))return{error:ve};const{appliedPolicies:o}=xd({tournamentRecord:e,drawDefinition:n,structure:r,event:i}),a={};for(const e of t){const t=o?.[e];t&&(a[e]=t)}return Object.keys(a).length?{policyDefinitions:a}:{info:Re.message}}function Ld(t){const{appliedPolicies:e}=xd({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,event:t.event}),n=e?.[Lu];return{competitionPolicy:n}}function Bd({element:t,accessor:e}){if("string"!=typeof e)return{values:[]};const n=ca(t),r=e.split("."),i=[];let o;!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 a({targetElement:e=e[s],index:r});else o||(o=e[s]),i.includes(e[s])||i.push(e[s])}function a({targetElement:t,index:e}){if(t&&e===n.length-1&&["string","number"].includes(typeof t)){const e=r?t.slice(0,r):t;o?i.includes(e)||i.push(e):(o=e,i.push(e))}}}({targetElement:n,attributes:r});const a={value:o};return i.length&&(a.values=i),a}function Vd({requireTimeStamp:t,scaleAttributes:e,participant:n}){if(!n)return{error:on};if(!f(e))return{error:sr};if(n.timeItems??=[],Array.isArray(n.timeItems)){const{accessor:r,scaleType:i,eventType:o,scaleName:a}=e,s=[yu,i,o,a].join("."),c=n.timeItems.filter(t=>t?.itemType===s).filter(e=>!t||e?.itemDate).sort((t,e)=>(t.createdAt?new Date(t.createdAt).getTime():0)-(e.createdAt?new Date(e.createdAt).getTime():0)),u=c.pop();if(u){const[t,e,n,i]=u.itemType?.split(".")??[];if(t!==yu)return{error:Jn};const o=r&&Bd({element:u.itemValue,accessor:r}),a=o?.value||u.itemValue,s={rawValue:o&&u.itemValue,eventType:n,scaleDate:u.itemDate,scaleValue:a,scaleName:i,scaleType:e};return{...Y,scaleItem:s}}}return{...Y,scaleItem:void 0}}function Gd({value:t,sourceRange:e,targetRange:n}){if(!Array.isArray(e)||2!==e.length)return 0;const r=Math.min(...e),i=Math.max(...e),o=Math.min(...n);return(t-r)*(Math.max(...n)-o)/(i-r)+o}const jd="ELO",qd="NTRP",Wd="UTR",$d="WTN",Hd="DUPR",zd="UTR_P",Yd="UTPR",Kd="PSA",Qd="SQUASH_LEVELS",Jd="US_SQUASH",Xd="USATT",Zd="ITTF",tp="USAR",ep="BWF",np={ELO:jd,NTRP:qd,TRN:"TRN",UTR:"UTR",WTN:$d,DUPR:Hd,UTR_P:zd,UTPR:Yd,PSA:"PSA",SQUASH_LEVELS:Qd,US_SQUASH:Jd,USATT:Xd,ITTF:Zd,USAR:tp,BWF:"BWF"},rp={[jd]:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!1},[qd]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!1,range:[1,7]},[Wd]:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!1,range:[1,16]},[$d]:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!0,decimalsCount:2,range:[40,1]},[Hd]:{defaultInitialization:3.5,accessors:["duprRating","reliabilityScore"],accessor:"duprRating",attributes:{reliabilityScore:{generator:!0,range:[0,100]}},decimalsCount:3,ascending:!1,range:[2,8]},[zd]:{defaultInitialization:5,accessors:["utrpRating","verified"],accessor:"utrpRating",attributes:{verified:{type:"boolean"},provisional:{type:"string"}},decimalsCount:1,ascending:!1,range:[1,10]},[Yd]:{defaultInitialization:3.5,accessor:"utprRating",decimalsCount:1,ascending:!1,range:[2,5],deprecated:!0},[Kd]:{defaultInitialization:500,accessor:"psaPoints",decimalsCount:0,ascending:!1,range:[0,3e3],attributes:{tournaments:{generator:!0,range:[1,20]},divisor:{generator:!0,range:[10,20]}}},[Qd]:{defaultInitialization:2e3,accessor:"squashLevel",decimalsCount:0,ascending:!1,range:[0,7e3]},[Jd]:{defaultInitialization:3.5,accessor:"usSquashRating",decimalsCount:1,ascending:!1,range:[2,6]},[Xd]:{defaultInitialization:1e3,accessor:"usattRating",decimalsCount:0,ascending:!1,range:[200,3e3]},[Zd]:{defaultInitialization:500,accessor:"ittfPoints",decimalsCount:0,ascending:!1,range:[0,2e4]},[tp]:{defaultInitialization:1e4,accessor:"usarRanking",decimalsCount:0,ascending:!0,range:[1,25e3]},[ep]:{defaultInitialization:5e3,accessor:"bwfPoints",decimalsCount:0,ascending:!0,range:[0,15e4],attributes:{tournaments:{generator:!0,range:[1,10]}}}};function ip({sourceRatingType:t,sourceRating:e}){const n=rp[t]?.range,r=n?.[0]>n?.[1],i=rp[jd].range;return Gd({value:r?n[0]-e:e,sourceRange:n,targetRange:i})}function op(t){const{tournamentRecord:e,participantIds:n,scaleName:r,eventType:i,convertToELO:o,adHocRatings:a={}}=t,s=t.scaleAccessor??rp[r]?.accessor,c=e.participants??[];for(const t of n??[]){const e=c?.find(e=>e.participantId===t);let n;o&&(n=ap({scaleName:`${jd}.${gu}`,participant:e,eventType:i})),n||(n=ap({scaleName:`${r}.${gu}`,participant:e,eventType:i}),n&&o&&r!==jd&&(n=ip({sourceRatingType:r,sourceRating:n}))),!n&&r&&(n=ap({scaleAccessor:s,participant:e,scaleName:r,eventType:i}),n&&o&&r!==jd&&(n=ip({sourceRatingType:r,sourceRating:n}))),n&&!a[t]&&(a[t]=n)}return a}function ap({scaleType:t=Su,scaleAccessor:e,participant:n,scaleName:r,eventType:i}){const o=n&&Vd({scaleAttributes:{eventType:i??es,scaleType:t,scaleName:r},participant:n}),a=o?.scaleItem?.scaleValue;return e&&f(a)?a[e]:a}function sp(t){const e="setFirstClassOrExtension";if("object"!=typeof t)return{error:Ae};const{element:n,attribute:r,name:i,value:o,creationTime:a}=t;if(!n||"object"!=typeof n)return Ci({result:{error:sr},stack:e});if("string"!=typeof r||!r)return Ci({result:{error:sr},stack:e});if("string"!=typeof i||!i)return Ci({result:{error:sr},stack:e});if(Qr()&&(null==o?delete n[r]:n[r]=o),Jr())if(null==o)qu({element:n,name:i});else{const t=$u({element:n,extension:{name:i,value:o},creationTime:a});if(t.error)return Ci({result:t,stack:e})}else Array.isArray(n.extensions)&&n.extensions.some(t=>t?.name===i)&&qu({element:n,name:i});return{...Y}}function cp(t){const{tournamentRecord:e,drawDefinition:n,participantIds:r,event:i}=t;if(!n)return{error:st};if(!r?.length)return{error:Ae};const{competitionPolicy:o}=Ld({tournamentRecord:e,drawDefinition:n,event:i});if(!o)return{...Y};const a=o.ratingPolicy,s=a.baselineRating.scaleName,c=a.ratingAggregation??"AVERAGE",u=i?.eventType,d=s?op({tournamentRecord:e,participantIds:r,scaleName:s,eventType:u}):{},p={};for(const t of r){const n=up({tournamentRecord:e,participantId:t,adHocRatings:d,aggregation:c,eventType:u});p[t]={participantId:t,baselineRating:n,dynamicFormRating:n,pressureRating:0,roundsPlayed:0,wins:0,losses:0,draws:0,totalPointsWon:0,totalPointsLost:0,ratingHistory:[]}}const l={participantStates:p,roundStates:{}};return sp({element:n,attribute:"competitionState",name:nd,value:l}),{competitionState:l,...Y}}function up({tournamentRecord:t,participantId:e,adHocRatings:n,aggregation:r,eventType:i}){if(void 0!==n[e])return n[e];if(i===ns){const i=t.participants?.find(t=>t.participantId===e),o=i?.individualParticipantIds;if(o?.length){return function(t,e){if(!t.length)return 0;switch(e){case"MIN":return Math.min(...t);case"MAX":return Math.max(...t);case"SUM":return t.reduce((t,e)=>t+e,0);default:return t.reduce((t,e)=>t+e,0)/t.length}}(o.map(t=>n[t]??0),r)}}return 0}function dp({element:t,attribute:e,name:n}){if(void 0!==t?.[e])return t[e];const{extension:r}=td({element:t,name:n});return r?.value}function pp({drawDefinition:t}){return{competitionState:dp({element:t,attribute:"competitionState",name:nd})}}function lp(t){const{winningSide:e}=t;return 1===e?{side1Count:1,side2Count:0}:2===e?{side1Count:0,side2Count:1}:{side1Count:0,side2Count:0}}function mp({pointsWon:t,pointsLost:e,competitionPolicy:n}){const r=t+e;if(0===r)return.5;const i=t/r,o=n.ratingPolicy.pressureRating;if(!o||"POINT_SHARE"===o.actualOutputMethod)return i;const a=o.weights??{pointShare:1},s=(t-e)/r,c=a.pointShare??1,u=a.pointDifferential??0,d=a.contextFactor??0,p=c+u+d;return 0===p?i:(c*i+u*s+0*d)/p}function fp(t,e,n){return 1/(1+Math.pow(10,(e-t)/n))}function hp(t){const{tournamentRecord:e,drawDefinition:n,matchUp:r,event:i}=t;if(!n)return{error:st};if(!r)return{error:Se};const{competitionPolicy:o}=Ld({tournamentRecord:e,drawDefinition:n,event:i});if(!o)return{...Y};const{competitionState:a}=pp({drawDefinition:n});if(!a)return{...Y};const s=r.sides??[],c=s[0]?.participantId,u=s[1]?.participantId;if(!c||!u)return{...Y};const d=a.participantStates[c],p=a.participantStates[u];if(!d||!p)return{...Y};const{winningSide:l}=r,{side1Count:m,side2Count:f}=function(t){const e=t.score?.sets??[];if(!e.length)return lp(t);let n=0,r=0;for(const t of e){const e=t.side1Score??0,i=t.side2Score??0;if(void 0!==t.side1TiebreakScore||void 0!==t.side2TiebreakScore){const o=t.side1TiebreakScore??0,a=t.side2TiebreakScore??0,s=o+a;if(s>0){n+=e-(1===t.winningSide?1:0)+o/s,r+=i-(2===t.winningSide?1:0)+a/s;continue}}n+=e,r+=i}return n>0||r>0?{side1Count:n,side2Count:r}:lp(t)}(r),h=mp({pointsWon:m,pointsLost:f,competitionPolicy:o}),g=mp({pointsWon:f,pointsLost:m,competitionPolicy:o}),I=o.ratingPolicy.dynamicFormRating.logisticScale,S=o.ratingPolicy.dynamicFormRating.kFactor,y=fp(d.baselineRating,p.baselineRating,I),v=fp(p.baselineRating,d.baselineRating,I),U=fp(d.dynamicFormRating,p.dynamicFormRating,I),P=fp(p.dynamicFormRating,d.dynamicFormRating,I),T=o.ratingPolicy.pressureRating?.enabled,w=T?h-y:0,D=T?g-v:0,R=o.ratingPolicy.dynamicFormRating.enabled,b=R?d.dynamicFormRating+S*(h-U):d.dynamicFormRating,N=R?p.dynamicFormRating+S*(g-P):p.dynamicFormRating,M=r.roundNumber??0;return d.dynamicFormRating=b,d.pressureRating+=w,d.roundsPlayed+=1,d.wins+=1===l?1:0,d.losses+=2===l?1:0,d.draws+=l?0:1,d.totalPointsWon+=m,d.totalPointsLost+=f,d.ratingHistory.push({roundNumber:M,opponentParticipantId:u,dynamicFormRatingBefore:d.dynamicFormRating-S*(h-U),dynamicFormRatingAfter:b,pressureDelta:w,actualOutput:h,expectedOutput:y}),p.dynamicFormRating=N,p.pressureRating+=D,p.roundsPlayed+=1,p.wins+=2===l?1:0,p.losses+=1===l?1:0,p.draws+=l?0:1,p.totalPointsWon+=f,p.totalPointsLost+=m,p.ratingHistory.push({roundNumber:M,opponentParticipantId:c,dynamicFormRatingBefore:p.dynamicFormRating-S*(g-P),dynamicFormRatingAfter:N,pressureDelta:D,actualOutput:g,expectedOutput:v}),sp({element:n,attribute:"competitionState",name:nd,value:a}),{...Y}}const gp="ABANDONED",Ip="AWAITING_RESULT",Sp="BYE",yp="CANCELLED",vp="COMPLETED",Up="DEAD_RUBBER",Pp="DEFAULTED",Tp="DOUBLE_DEFAULT",wp="DOUBLE_WALKOVER",Dp="IN_PROGRESS",Rp="INCOMPLETE",bp="NOT_PLAYED",Np="RETIRED",Mp="SUSPENDED",Ap="TO_BE_PLAYED",Ep="WALKOVER",Cp=[Ip,vp,Pp,Dp,Rp,Np,Mp],Op=[Ip,vp,Pp,wp,Tp,Dp,Rp,Np,Mp,Ep],kp=[gp,Ip,Sp,yp,vp,Up,Pp,wp,Tp,Dp,Rp,bp,Np,Mp,Ap,Ep],Fp=[Sp,wp,Tp,vp,Pp,Np,Ep],xp=[gp,Ip,yp,Up,Dp,Rp,bp,Mp,Ap,void 0],_p=[yp,gp,vp,Up,Pp,wp,Tp,Np,Ep],Lp=[gp,vp,Pp,wp,Tp,Dp,Np,Ep],Bp=[Dp,Rp,Mp,Ap],Vp={ABANDONED:gp,AWAITING_RESULT:Ip,BYE:Sp,CANCELLED:yp,COMPLETED:vp,DEAD_RUBBER:Up,DEFAULTED:Pp,DOUBLE_WALKOVER:wp,DOUBLE_DEFAULT:Tp,IN_PROGRESS:Dp,INCOMPLETE:Rp,NOT_PLAYED:bp,RETIRED:Np,SUSPENDED:Mp,TO_BE_PLAYED:Ap,WALKOVER:Ep};function Gp(t){const{tournamentRecord:e,drawDefinition:n,roundNumber:r,matchUps:i,event:o}=t;if(!n)return{error:st};const{competitionPolicy:a}=Ld({tournamentRecord:e,drawDefinition:n,event:o});if(!a)return{...Y};const{competitionState:s}=pp({drawDefinition:n});if(!s)return{...Y};if(s.roundStates[r]?.processed)return{...Y};const c=i.filter(t=>t.roundNumber===r&&(t.winningSide||_p.includes(t.matchUpStatus)));for(const t of c)hp({tournamentRecord:e,drawDefinition:n,matchUp:t,event:o});const{competitionState:u}=pp({drawDefinition:n});return u&&(u.roundStates[r]={roundNumber:r,processed:!0},sp({element:n,attribute:"competitionState",name:nd,value:u})),{...Y}}function jp({drawDefinition:t}){return t?(sp({element:t,attribute:"competitionState",name:nd,value:void 0}),{...Y}):{error:st}}function qp({drawDefinition:t,participantId:e}){const{competitionState:n}=pp({drawDefinition:t}),r=n?.participantStates?.[e];return{participantState:r}}function Wp(t){const{tournamentRecord:e,drawDefinition:n,event:r}=t,{competitionPolicy:i}=Ld({tournamentRecord:e,drawDefinition:n,event:r}),{competitionState:o}=pp({drawDefinition:n});if(!o||!i)return{leaderboard:[]};const a=i.victoryPolicy.primaryRanking,s=[...Object.values(o.participantStates)].sort((t,e)=>{const n=$p(e,a)-$p(t,a);if(0!==n)return n;for(const n of i.victoryPolicy.tiebreakOrder??[]){const r=Hp(t,e,n,o.participantStates);if(0!==r)return r}return 0});return{leaderboard:s.map((t,e)=>({participantId:t.participantId,rank:e+1,baselineRating:t.baselineRating,dynamicFormRating:t.dynamicFormRating,pressureRating:t.pressureRating,wins:t.wins,losses:t.losses,draws:t.draws,pointsWon:t.totalPointsWon,pointsLost:t.totalPointsLost}))}}function $p(t,e){switch(e){case"PRESSURE_RATING":return t.pressureRating;case"DYNAMIC_FORM_RATING":return t.dynamicFormRating;case"WINS":default:return t.wins;case"POINTS":return t.totalPointsWon}}function Hp(t,e,n,r){switch(n){case"POINT_DIFFERENTIAL":return e.totalPointsWon-e.totalPointsLost-(t.totalPointsWon-t.totalPointsLost);case"DYNAMIC_FORM_RATING":return e.dynamicFormRating-t.dynamicFormRating;case"PRESSURE_RATING":return e.pressureRating-t.pressureRating;case"HEAD_TO_HEAD":{const n=t.ratingHistory.filter(t=>t.opponentParticipantId===e.participantId),r=e.ratingHistory.filter(e=>e.opponentParticipantId===t.participantId),i=n.filter(t=>t.actualOutput>.5).length;return r.filter(t=>t.actualOutput>.5).length-i}case"HEAD_TO_HEAD_PRESSURE":{const n=t.ratingHistory.filter(t=>t.opponentParticipantId===e.participantId),r=e.ratingHistory.filter(e=>e.opponentParticipantId===t.participantId),i=n.reduce((t,e)=>t+e.pressureDelta,0);return r.reduce((t,e)=>t+e.pressureDelta,0)-i}case"STRENGTH_OF_OPPOSITION":{const n=t.ratingHistory.map(t=>r[t.opponentParticipantId]?.baselineRating??0),i=e.ratingHistory.map(t=>r[t.opponentParticipantId]?.baselineRating??0),o=n.length?n.reduce((t,e)=>t+e,0)/n.length:0;return(i.length?i.reduce((t,e)=>t+e,0)/i.length:0)-o}default:return 0}}function zp({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:nt};return{linkedTournamentIds:Object.assign({},...Object.keys(t).map(e=>{const n=t[e],r=n?.tournamentId,i=Ad(n).filter(t=>t!==r);return{[e]:i}}))}}var Yp={__proto__:null,getCompetitionLeaderboard:Wp,getCompetitionParticipantState:qp,getCompetitionPolicy:Ld,getCompetitionState:pp,getLinkedTournamentIds:zp,getTournamentIds:Ed,initializeCompetitionState:cp,linkTournaments:Od,mutate:{__proto__:null,initializeCompetitionState:cp,linkTournaments:Od,processCompetitionMatchUp:hp,processCompetitionRound:Gp,resetCompetitionState:jp,unlinkTournament:Fd,unlinkTournaments:kd},processCompetitionMatchUp:hp,processCompetitionRound:Gp,query:{__proto__:null,getCompetitionLeaderboard:Wp,getCompetitionParticipantState:qp,getCompetitionPolicy:Ld,getCompetitionState:pp,getLinkedTournamentIds:zp,getTournamentIds:Ed},resetCompetitionState:jp,unlinkTournament:Fd,unlinkTournaments:kd};const Kp=t=>e=>t[e],Qp=(t=[])=>t.map(tl).filter(Boolean),Jp=(t=[])=>t.map(Xp).filter(Boolean),Xp=(t={})=>Kp(t)("participantId"),Zp=(t={})=>Kp(t)("drawPosition"),tl=(t={})=>Kp(t)("matchUpId"),el=(t={})=>Kp(t)("drawId");function nl({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:ut};if(!Array.isArray(t))return{error:sr};const n=Jp(e?.entries??[]);if(t.length&&V(t,n).length<t.length)return{error:sr};return zu({drawDefinition:e,extension:{name:Id,value:t}})}function rl(t,e,n){const r=t=>dp({element:t,attribute:"roundTarget",name:vd}),i=n?.deprioritizeCompleted,o=n?.mode===Is&&ys,a=n?.mode===gs&&Ss,s=a||o||hs,c=t=>(t=>t?.stage===us&&1===t?.stageSequence)(t)?-1:s[t?.stage],u=t=>t?.matchUps.every(({matchUpStatus:t})=>_p.includes(t)?1:-1);return i&&u(t)-u(e)||o&&c(t)-c(e)||(t?.stage&&s[t.stage]||0)-(e?.stage&&s[e.stage]||0)||(r(t)||0)-(r(e)||0)||!a&&!o&&(e?.positionAssignments?.length??1/0)-(t?.positionAssignments?.length??1/0)||(t?.stageSequence??0)-(e?.stageSequence??0)||(il(t)||0)-(il(e)||0)}function il(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 ol(t){const e=fu(t,[{[yc]:!0,[bc]:!0}]);if(e.error)return e;const{drawDefinition:n,structureId:r}=t,{structures:i}=al({drawDefinition:n}),o=i?.flatMap(t=>t.structures?[...t.structures].concat(t):t),a=o?.find(t=>t.structureId===r);if(!a)return{error:Vt};return{structure:a,containingStructure:a.structureType===ws?o?.find(t=>t.structures?.some(t=>t.structureId===r)):void 0}}function al({withStageGrouping:t,drawDefinition:e,stageSequences:n,stageSequence:r,roundTarget:i,sortConfig:o,stages:a,stage:s}){const c=!e&&st||!e?.structures&&Gt||void 0;if(c)return{error:c,structures:[],stageStructures:{}};const u=e?.structures?.filter(function(t){return!s&&!Array.isArray(a)||s&&t.stage===s||Array.isArray(a)&&a.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=dp({element:t,attribute:"roundTarget",name:vd});return!i||i===e}).sort((t,e)=>rl(t,e,o))??[],d=t?Object.assign({},...fs.map(t=>{const e=u?.filter(e=>e.stage===t);return e?.length&&{[t]:e}}).filter(Boolean)):{};return{structures:u,stageStructures:d}}function sl({drawDefinition:t}){if(!t)return{error:st};const e={};return{allPositionedParticipantIds:(t.structures??[]).map(t=>{const n=t.stage;e[n]||(e[n]=[]);const{positionAssignments:r}=cl({structure:t}),i=r?.map(Xp).filter(Boolean)??[];return e[n].push(...i),i}).flat(),stagePositionedParticipantIds:e}}function cl({drawDefinition:t,structureId:e,structure:n}){let r,i=[];if(!n){if(!t)return{positionAssignments:i,error:st};if(({structure:n,error:r}=ol({drawDefinition:t,structureId:e})),r)return{positionAssignments:i,error:r}}return n.structures?i=[].concat(...n.structures.map(t=>cl({structure:t}).positionAssignments)):n.positionAssignments?i=n.positionAssignments:r=ee,{positionAssignments:i,error:r}}function ul({drawDefinition:t,structureId:e,structure:n}){const r=cl({drawDefinition:t,structureId:e,structure:n})?.positionAssignments??[],i=r?.filter(t=>t.participantId??t.bye??t.qualifier),o=r&&r?.length===i?.length,a=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:o,positionAssignments:r,unassignedPositions:a,assignedPositions:i,qualifierPositions:c,byePositions:s}}function dl(t,e,n){return fu(t,[e.reduce((t,e)=>(t[e]=!0,t),{})],n)}const pl="addDrawDefinition",ll="addMatchUps",ml="addParticipants",fl="addScaleItems",hl="addEvent",gl="addVenue",Il="audit",Sl="dataIssue",yl="deleteParticipants",vl="deleteVenue",Ul="deletedDrawIds",Pl="deletedMatchUpIds",Tl="modifyDrawDefinition",wl="modifyDrawEntries",Dl="modifyEventEntries",Rl="modifyMatchUp",bl="modifyParticipants",Nl="modifyPositionAssignments",Ml="modifySeedAssignments",Al="modifyTournamentDetail",El="modifyVenue",Cl="mutations",Ol="publishEvent",kl="publishEventSeeding",Fl="publishOrderOfPlay",xl="publishParticipants",_l="unPublishEvent",Ll="unPublishEventSeeding",Bl="unPublishOrderOfPlay",Vl="unPublishParticipants",Gl="unPublishTournament",jl="updateInContextMatchUp",ql={ADD_DRAW_DEFINITION:pl,ADD_MATCHUPS:ll,ADD_PARTICIPANTS:ml,ADD_SCALE_ITEMS:fl,ADD_EVENT:hl,ADD_VENUE:gl,AUDIT:Il,DATA_ISSUE:Sl,DELETE_PARTICIPANTS:yl,DELETE_VENUE:vl,DELETED_DRAW_IDS:Ul,DELETED_MATCHUP_IDS:Pl,MODIFY_DRAW_DEFINITION:Tl,MODIFY_DRAW_ENTRIES:wl,MODIFY_EVENT_ENTRIES:Dl,MODIFY_MATCHUP:Rl,MODIFY_PARTICIPANTS:bl,MODIFY_POSITION_ASSIGNMENTS:Nl,MODIFY_SEED_ASSIGNMENTS:Ml,MODIFY_TOURNAMENT_DETAIL:Al,MODIFY_VENUE:El,MUTATIONS:Cl,PUBLISH_EVENT_SEEDING:kl,PUBLISH_EVENT:Ol,PUBLISH_ORDER_OF_PLAY:Fl,PUBLISH_PARTICIPANTS:xl,UNPUBLISH_EVENT_SEEDING:Ll,UNPUBLISH_EVENT:_l,UNPUBLISH_ORDER_OF_PLAY:Bl,UNPUBLISH_PARTICIPANTS:Vl,UNPUBLISH_TOURNAMENT:Gl,UPDATE_INCONTEXT_MATCHUP:jl};function Wl(t,e){if(!t)return{error:st};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)}),{...Y}}function $l(t){if(!t)return;let e=Date.now();const n=t.updatedAt;if(n){const t="string"==typeof n?new Date(n).getTime():n.getTime();!Number.isNaN(t)&&e<=t&&(e=t+1)}t.updatedAt=new Date(e).toISOString()}function Hl({drawDefinition:t,tournamentId:e,matchUps:n,eventId:r}){if(t&&Wl(t),Array.isArray(n))for(const t of n)$l(t);return di({payload:{matchUps:n,tournamentId:e,eventId:r},topic:ll}),{...Y}}function zl({drawDefinition:t,tournamentId:e,matchUpIds:n,eventId:r,action:i}){t&&Wl(t),di({topic:Pl,payload:{tournamentId:e,matchUpIds:n,eventId:r,action:i}});for(const t of n)fi({key:t});return{...Y}}function Yl({drawDefinition:t,tournamentId:e,structureId:n,context:r,eventId:i,matchUp:o}){if(!o)return console.log(Se),{error:Se};if(t){Ql({drawDefinition:t,structureIds:n?[n]:void 0,tournamentId:e,eventId:i})}return $l(o),di({topic:Rl,payload:{matchUp:o,tournamentId:e,context:r},key:o.matchUpId}),{...Y}}function Kl({tournamentId:t,eventId:e,drawDefinition:n}){return n?(Wl(n),di({payload:{drawDefinition:n,tournamentId:t,eventId:e},topic:pl,key:n.drawId}),{...Y}):(console.log(st),{error:st})}function Ql({drawDefinition:t,tournamentId:e,structureIds:n,eventId:r}){return t?(Wl(t,n),di({payload:{tournamentId:e,eventId:r,drawDefinition:t},topic:Tl,key:t.drawId}),{...Y}):{error:st}}function Jl({drawDefinition:t,tournamentId:e,structure:n,eventId:r}){const i=dl({drawDefinition:t,structure:n},[yc,_c]);if(i.error)return i;const o=n.seedAssignments,a=n.structureId;return di({payload:{tournamentId:e,eventId:r,drawId:t.drawId,structureId:a,seedAssignments:o},topic:Ml,key:t.drawId}),Ql({structureIds:[a],drawDefinition:t,tournamentId:e,eventId:r}),{...Y}}function Xl({drawDefinition:t,tournamentId:e,structure:n,event:r}){const i=dl({drawDefinition:t,structure:n},[yc,_c]);if(i.error)return i;const o=cl({structure:n}),a=n.structureId,s=t.drawId,c=r?.eventId;return di({topic:Nl,payload:{positionAssignments:o,tournamentId:e,structureId:a,eventId:c,drawId:s},key:a}),Ql({structureIds:[a],drawDefinition:t,tournamentId:e,eventId:c}),{...Y}}function Zl({tournamentRecord:t,drawDefinition:e,resetEntries:n,event:r}){if(!e)return{error:st};const i=e.structures?.find(t=>t.stage===ls);if(!i)return{error:Vt};const o=i.matchUps?.map(({matchUpId:t})=>t)??[];return i.positionAssignments=[],i.seedAssignments=[],i.matchUps=[],zl({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:o,drawDefinition:e}),n&&(e.entries=e.entries.filter(t=>t.entryStage!==ls)),Ql({tournamentId:t?.tournamentId,eventId:r?.eventId,drawDefinition:e,structureIds:[i.structureId]}),{...Y}}function tm({drawPositions:t,structure:e}){if([ds,us].includes(e.stage)&&1===e.stageSequence)return;const{positionAssignments:n}=cl({structure:e}),r=n?.filter(({drawPosition:e})=>t?.includes(e));r?.forEach(t=>{sp({element:t,attribute:"disableLinks",name:sd,value:!0})})}function em(t){const{appliedPolicies:e,positionAction:n,drawDefinition:r}=t;if(!1===e?.audit?.[yd])return;const{extension:i}=td({name:yd,element:r}),o=Array.isArray(i?.value)?i?.value??[]:[];if(!o?.length){const t=r.structures.find(t=>t.stage===us);if(t){const e=cl({structure:t}).positionAssignments?.map(({drawPosition:t,participantId:e,bye:n,qualifier:r})=>({drawPosition:t,participantId:e,qualifier:r,bye:n}));o.push({name:"initialMainAssignments",initialAssignments:e})}}$u({element:r,extension:{value:o.concat(n),name:yd}})}function nm({tournamentRecord:t,drawDefinition:e,event:n}){const r=t?.events||n&&[n],i=r?.map(t=>t?.drawDefinitions).flat().filter(Boolean)||e&&[e]||[],o={},a={},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&&(o[n]=e?.map(t=>t.structureId))&&e.forEach(e=>a[e.structureId]=t?.structureId)}return{containedStructures:o,containerStructures:a}}function rm(t){const{sides:e,matchUpType:n}=t??{},r=t.potentialParticipants?.length?t.potentialParticipants.flat().map(t=>n===i?t?.individualParticipantIds??[]:t.participantId).flat():[],o=(e??[]).map(t=>n===i&&(t?.participant?.individualParticipantIds??[])||t?.participantId&&[t.participantId]||[]).flat();return{individualParticipantIds:o.concat(r).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:r}}function im(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}const om="SIGN_IN_STATUS",am="SIGNED_OUT",sm="SIGNED_IN",cm="PAYMENT_STATUS",um="REFUNDED",dm="PARTIAL",pm="WAIVED",lm="UNPAID",mm="PAID",fm=[mm,lm,dm,pm,um],hm="TEAM",gm="INDIVIDUAL",Im="GROUP",Sm="PAIR",ym="TEAM",vm={TEAM_PARTICIPANT:hm,INDIVIDUAL:gm,GROUP:Im,TEAM:ym,PAIR:Sm},Um={INDIVIDUAL:gm,GROUP:Im,PAIR:Sm,TEAM:ym,SIGN_IN_STATUS:om,SIGNED_OUT:am,SIGNED_IN:sm,PAYMENT_STATUS:cm,REFUNDED:um,PARTIAL:dm,WAIVED:pm,UNPAID:lm,PAID:mm};function Pm({participantsProfile:t,participants:e=[],deepCopy:n}){const r=new Map,i=!1!==n?ca(e,t?.convertExtensions,!0):e,o=i.filter(t=>t.participantType===ym),a=i.filter(t=>t.participantType===Im),s=i.filter(t=>t.participantType===Sm);return i.forEach(t=>{if(t.participantType===gm){const{participantId:e}=t;t.groupParticipantIds=[],t.teamParticipantIds=[],t.pairParticipantIds=[],t.groups=[],t.teams=[],o.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)})}),a.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 Tm(t){return t&&void 0!==String.fromCodePoint?t.toUpperCase().replace(/./g,t=>String.fromCodePoint(t.charCodeAt(0)+127397)):t}const wm=[{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 Dm({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=wm.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 Rm(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:un}}function bm(t){const{tournamentRecord:e,participantId:n}=t;if(n){const t=Rm({tournamentRecord:e,participantId:n});return t.participant??t}const r=t.element||t.drawDefinition||t.event||t.tournamentRecord;return r||{error:Ae}}function Nm(t){const{returnPreviousValues:e,itemSubTypes:n,itemType:r}=t,i=bm(t);if(i.error)return i;if(n&&!Array.isArray(n))return{error:sr,context:{itemSubTypes:n}};if(!Array.isArray(i.timeItems))return{error:Yn};const o=i.timeItems.filter(t=>t?.itemType===r).filter(t=>!n?.length||n.some(e=>t?.itemSubTypes?.includes(e))).sort((t,e)=>new Date(t.createdAt||void 0).getTime()-new Date(e.createdAt||void 0).getTime()),a=ca(o.pop(),!1,!0);if(a){const t={timeItem:a,...Y};return e&&Object.assign(t,{previousItems:o}),t}return{info:mr}}function Mm({returnPreviousValues:t,drawDefinition:e,itemSubTypes:n,itemType:r}){if(!e)return{error:bt};if(!e.timeItems)return{info:mr};const{timeItem:i,previousItems:o,info:a}=Nm({element:e,returnPreviousValues:t,itemSubTypes:n,itemType:r});return i&&{timeItem:i,previousItems:o}||{info:a}}function Am({returnPreviousValues:t,itemSubTypes:e,itemType:n,event:r}){if(!r)return{error:Ht};if(!r.timeItems)return{info:mr};const{timeItem:i,previousItems:o,info:a}=Nm({returnPreviousValues:t,element:r,itemSubTypes:e,itemType:n});return i&&{timeItem:i,previousItems:o}||{info:a}}function Em({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:n,itemType:r}){if(!e)return{error:rt};if(!e.timeItems)return{info:mr};const{timeItem:i,previousItems:o,info:a}=Nm({element:e,returnPreviousValues:t,itemSubTypes:n,itemType:r});return i&&{timeItem:i,previousItems:o}||{info:a}}function Cm({returnPreviousValues:t,tournamentRecord:e,participantId:n,itemSubTypes:r,itemType:i}){const o=dl({tournamentRecord:e,participantId:n},[Ic,Pc]);if(o.error)return o;const a=Rm({tournamentRecord:e,participantId:n});if(a.error)return a;const{participant:s}=a;if(!s?.timeItems)return{info:mr};const{timeItem:c,previousItems:u,info:d}=Nm({element:a.participant,returnPreviousValues:t,itemSubTypes:r,itemType:i});return c&&{timeItem:c,previousItems:u}||{info:d}}const Om={[Im]:"groupParticipantIds",[Sm]:"pairParticipantIds",[ym]:"teamParticipantIds"},km={[Im]:"groups",[ym]:"teams"};function Fm({withIndividualParticipants:t,convertExtensions:e,tournamentRecord:n,withSignInStatus:r,withScaleValues:i,withGroupings:o,internalUse:a,withISO2:s,withIOC:c}){const u=[],d={};for(const t of n.participants??[]){const e=t?.participantId;e&&Lm({participantMap:d,participantId:e})}for(const t of n.participants??[]){const n=ca(t,e,a),{participantId:o,individualParticipantIds:p,participantType:l}=n;if(d[o]){if(Object.assign(d[o].participant,n),p){const t=_m({individualParticipantIds:p,participantCopy:n,participantMap:d,participantType:l,participantId:o});t.missingParticipantIds.length&&u.push(...t.missingParticipantIds)}if(r&&(d[o].participant.signedIn=xm(n)),i){const{ratings:t,rankings:e,seedings:r}=Pu({participant:n});d[o].participant.seedings=r,d[o].participant.rankings=e,d[o].participant.ratings=t}(c||s)&&Dm({participant:d[o].participant,withISO2:s,withIOC:c})}else u.push(o)}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?Tu({template:e,source:i}):i)}}}}({participantMap:d,template:f(t)?t:void 0})}let p;return o&&(p=Pm({participants:Object.values(d).map(({participant:t})=>t),participantsProfile:{convertExtensions:e},deepCopy:!1}).groupInfo),{missingParticipantIds:u,participantMap:d,groupInfo:p}}function xm(t){const{timeItem:e}=Nm({itemType:om,element:t});return e?.itemValue===sm}function _m({individualParticipantIds:t,participantCopy:e,participantMap:n,participantType:r,participantId:i}){const o=[];for(const a of t){const s=n[a]?.participant;if(s){if(s[Om[r]].push(i),[ym,Im].includes(r)){const{participantRoleResponsibilities:t,participantOtherName:n,participantName:i,participantId:o,teamId:a}=e;s[km[r]].push({participantRoleResponsibilities:t,participantOtherName:n,participantName:i,participantId:o,teamId:a})}if(r===Sm){const e=t.find(t=>t!==a);n[a].pairIdMap[i]=e,n[a].pairIdMap[e]=i}}else o.push(a)}return{missingParticipantIds:o}}function Lm({participantMap:t,participantId:e}){if(t[e])return;const r={walkoverWins:0,defaultWins:0,walkovers:0,defaults:0,losses:0,wins:0};t[e]={structureParticipation:{},potentialMatchUps:{},scheduleConflicts:{},scheduleItems:[],participant:{groupParticipantIds:[],pairParticipantIds:[],teamParticipantIds:[],seedings:{},rankings:{},ratings:{},groups:[],teams:[]},statistics:{},opponents:{},pairIdMap:{},matchUps:{},events:{},draws:{},counters:{[n]:{...r},[i]:{...r},[ym]:{...r},...r}}}function Bm({participantsProfile:t,useParticipantMap:e,tournamentRecord:n,contextProfile:r,inContext:i}){if(e)return Fm({...t,...r,tournamentRecord:n});let o,a=ca(n.participants,!1,!0)??[];if((t?.withIOC||t?.withISO2)&&a.forEach(e=>Dm({participant:e,...t})),(i||t?.withGroupings)&&a?.length&&({participantsWithGroupings:a,groupInfo:o}=Pm({participantsProfile:t,deepCopy:!1,participants:a})),t?.withScaleValues&&a?.length)for(const t of a){const{ratings:e,rankings:n}=Pu({participant:t});t.rankings=n,t.ratings=e}return{participants:a,groupInfo:o}}const Vm="WALKOVER",Gm="RETIRED",jm="COMPETITIVE",qm="ROUTINE",Wm="DECISIVE",$m="winRatio",Hm={[Du]:{policyName:"Competitive Bands Default",profileBands:{[Wm]:20,[qm]:50},predictionModel:{competitiveAnchors:[{delta:0,probability:.7},{delta:1.5,probability:.25}],decisiveAnchors:[{delta:0,probability:.1},{delta:1.5,probability:.55}]}}};function zm({policyDefinitions:t,tournamentRecord:e,contextProfile:n,drawDefinition:r,event:i}){const o={policies:{}};if(!n)return o;const a=_d({tournamentRecord:e,drawDefinition:r,event:i}).policyDefinitions;if(n.withCompetitiveness){const e=t?.[Du]??a?.[Du]??Hm[Du];o.policies[Du]=e}return o}function Ym(t){const e="setGroupLeafOrExtension";if("object"!=typeof t)return{error:Ae};const{element:n,groupAttribute:r,leafAttribute:i,name:o,value:a,creationTime:s}=t;if(!n||"object"!=typeof n)return Ci({result:{error:sr},stack:e});if("string"!=typeof r||!r)return Ci({result:{error:sr},stack:e});if("string"!=typeof i||!i)return Ci({result:{error:sr},stack:e});if("string"!=typeof o||!o)return Ci({result:{error:sr},stack:e});if(Qr()&&function(t,e,n,r){null!=r?(t[e]||(t[e]={}),t[e][n]=r):t[e]&&(delete t[e][n],0===Object.keys(t[e]).length&&delete t[e])}(n,r,i,a),Jr())if(null==a)qu({element:n,name:o});else{const t=$u({element:n,extension:{name:o,value:a},creationTime:s});if(t.error)return Ci({result:t,stack:e})}else!function(t,e){Array.isArray(t.extensions)&&t.extensions.some(t=>t?.name===e)&&qu({element:t,name:e})}(n,o);return{...Y}}function Km({element:t,groupAttribute:e,leafAttribute:n,name:r}){const i=t?.[e]?.[n];if(void 0!==i)return i;const o=(t?.extensions??[]).find(t=>t?.name===r);return o?.value}function Qm({tournamentRecord:t,drawDefinition:e,policyType:n,structure:r,event:i}){if(!t)return{error:rt};const{appliedPolicies:o}=xd({tournamentRecord:t,drawDefinition:e,structure:r,event:i});return o?.[n]?{policy:o[n]}:{info:Re?.message}}function Jm({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}=Qm({policyType:Ou,tournamentRecord:t,event:r}),o=t?Km({element:t,groupAttribute:"scheduling",leafAttribute:"timing",name:Td}):void 0,a=r&&td({name:Td,element:r}).extension,s=a?.value;return{scheduleTiming:{tournamentScheduling:o,eventScheduling:s,categoryName:e,categoryType:n,policy:i}}}function Xm({tournamentRecord:t,event:e}){if(!t)return{};const{extension:n}=td({element:t,name:Ud}),r=n?.value;if(!r?.events?.length)return{};const i=e?r.events.find(t=>!(t.eventType!==e.eventType||t.eventName&&t.eventName!==e.eventName||t.category?.categoryName&&t.category?.categoryName!==e.category?.categoryName)):void 0;if(!i)return{};const o={};return void 0!==i.drawSize&&(o.drawSize=i.drawSize),void 0!==i.maxWildcards&&(o.maxWildcards=i.maxWildcards),void 0!==i.maxAlternates&&(o.maxAlternates=i.maxAlternates),void 0!==i.maxQualifiers&&(o.maxQualifiers=i.maxQualifiers),Object.keys(o).length?{constraints:o}:{}}const Zm="GEMscore",tf={GEM_SCORE:Zm};const ef="ALTERNATE",nf="CONFIRMED",rf="DIRECT_ACCEPTANCE",of="FEED_IN",af="JUNIOR_EXEMPT",sf="LUCKY_LOSER",cf="ORGANISER_ACCEPTANCE",uf="QUALIFIER",df="SPECIAL_EXEMPT",pf="UNGROUPED",lf="UNPAIRED",mf="WILDCARD",ff="WITHDRAWN",hf=[nf,rf,af,cf,df],gf=[of,sf,uf],If=[nf,rf,of,af,cf,df,mf],Sf=[nf,rf,af,sf,uf,cf,df,mf],yf=[ef,nf,rf,of,af,sf,cf,uf,"REGISTERED",df,pf,lf,mf,ff],vf={ALTERNATE:ef,CONFIRMED:nf,DIRECT_ACCEPTANCE:rf,DIRECT_ENTRY_STATUSES:If,DRAW_SPECIFIC_STATUSES:gf,EQUIVALENT_ACCEPTANCE_STATUSES:hf,FEED_IN:of,JUNIOR_EXEMPT:af,LUCKY_LOSER:sf,ORGANISER_ACCEPTANCE:cf,QUALIFIER:uf,SPECIAL_EXEMPT:df,STRUCTURE_SELECTED_STATUSES:Sf,UNGROUPED:pf,UNPAIRED:lf,VALID_ENTRY_STATUSES:yf,WILDCARD:mf,WITHDRAWN:ff};function Uf({stage:t,drawDefinition:e,entryStatus:n}){return e.entries.reduce((e,r)=>r.entryStage===t&&r.entryStatus===n?e+1:e,0)}function Pf({provisionalPositioning:t,placementGroup:e,drawDefinition:n,stageSequence:r,entryStatuses:i,structureId:o,roundTarget:a,stages:s,stage:c}){const u=n.entries?.reduce((t,e)=>{const n=dp({element:e,attribute:"roundTarget",name:vd}),o=c&&e.entryStage===c||s?.length&&e.entryStage&&s.includes(e.entryStage),u=!i||e.entryStatus&&i.includes(e.entryStatus),d=e.entryStageSequence??1;return o&&(!r||d===r)&&u&&(!a||!n||a===n)?t.concat(e):t},[])??[];if(o&&c===ms){const{playoffEntries:r,error:i}=function({provisionalPositioning:t,drawDefinition:e,structureId:n}){const r=[],i=(e.links??[]).find(t=>t.linkType===As&&t.target.structureId===n);if(i){const{finishingPositions:n,structureId:o,bestOf:a,rankBy:s}=i.source,{structure:c}=ol({drawDefinition:e,structureId:o});if(c?.structureType===Ds){const u=(c.structures??[]).map(t=>{const e=t.positionAssignments??[],{structureId:n}=t;return{structureId:n,results:Object.assign({},...e.map(t=>{const{participantId:e}=t,n=dp({element:t,attribute:"tally",name:Rd});return n&&e?{[e]:n}:void 0}).filter(Boolean))}});if(i.source.remainder)!function({provisionalPositioning:t,allGroupResults:e,drawDefinition:n,playoffEntries:r,inboundLink:i,structureId:o}){const a=new Set,s=(n.links??[]).filter(t=>t.linkType===As&&t.source.structureId===o&&t.target.structureId!==i.target.structureId&&void 0!==t.source.bestOf);for(const t of s){const{structure:e}=ol({structureId:t.target.structureId,drawDefinition:n});if(e)for(const t of e.positionAssignments??[])t.participantId&&a.add(t.participantId)}e.forEach(({structureId:e,results:n})=>{Object.keys(n).forEach(i=>{if(!a.has(i)){const o=n[i],{groupOrder:a,provisionalOrder:s,GEMscore:c}=o,u=a||t&&s;r.push({groupingValue:e,entryStage:ms,entryStatus:of,placementGroup:u||1,participantId:i,GEMscore:c})}})})}({provisionalPositioning:t,allGroupResults:u,drawDefinition:e,playoffEntries:r,inboundLink:i,structureId:o});else if(void 0!==a&&n){const{selectedParticipants:e}=function({provisionalPositioning:t,rankBy:e=Zm,finishingPositions:n,groupResults:r,bestOf:i}){const o=[],a=[],s=[...n].sort(d),c=Math.max(...s);for(const{structureId:e,results:n}of r)for(const[r,i]of Object.entries(n)){const n=i.groupOrder||t&&i.provisionalOrder;if(!n)continue;const u={groupingValue:e,GEMscore:i.GEMscore,isBestFinisher:!1,finishingPosition:n,participantId:r};s.includes(n)?a.push(u):n>c&&o.push(u)}const u=[...a],p=i-a.length;p>0&&o.length>0&&o.toSorted((t,n)=>t.finishingPosition!==n.finishingPosition?t.finishingPosition-n.finishingPosition:e===Zm?(n.GEMscore??0)-(t.GEMscore??0):0).slice(0,p).forEach(t=>{t.isBestFinisher=!0,u.push(t)});const l={};for(const t of u){const e=t.finishingPosition;l[e]=(l[e]||0)+1}return{selectedParticipants:u,consumedPositions:l}}({groupResults:u,provisionalPositioning:t,finishingPositions:n,bestOf:a,rankBy:s});e.forEach(t=>{const e=n.includes(t.finishingPosition)?[...n].sort(d).indexOf(t.finishingPosition)+1:[...n].sort(d).length+1;r.push({isBestFinisher:t.isBestFinisher,groupingValue:t.groupingValue,participantId:t.participantId,GEMscore:t.GEMscore,entryStatus:of,entryStage:ms,placementGroup:e})})}else!function({provisionalPositioning:t,finishingPositions:e,allGroupResults:n,playoffEntries:r}){n.forEach(({structureId:n,results:i})=>{const o=n,a=Object.keys(i).reduce((e,n)=>{const r=i[n],o=r.groupOrder||t&&r.provisionalOrder;return e.includes(o)||e.push(o),e},[]),s=a.length===Object.keys(i).length,c=Object.keys(i).filter(n=>{const r=i[n],o=r.groupOrder||t&&r.provisionalOrder;return e?.includes(o)});t&&!s||c.forEach(n=>{const a=i[n],{groupOrder:s,provisionalOrder:c,GEMscore:u}=a,p=s||t&&c,l=[...e??[]].sort(d).indexOf(p)+1;r.push({entryStage:ms,entryStatus:of,placementGroup:l,groupingValue:o,participantId:n,GEMscore:u})})})}({provisionalPositioning:t,finishingPositions:n,allGroupResults:u,playoffEntries:r})}}return{playoffEntries:r}}({provisionalPositioning:t,drawDefinition:n,structureId:o});return i&&console.log("playoff entries error"),(r?.length?r:u).filter(t=>!e||t.placementGroup===e)}return u}function Tf({provisionalPositioning:t,returnAllProxies:e,drawDefinition:n,structureId:r,structure:i}){let o,a=[];i||({structure:i,error:o}=ol({drawDefinition:n,structureId:r}));const s=cl({structure:i}).positionAssignments;if(o||!i)return{seedAssignments:[],error:Vt};r||(r=i.structureId);const{stage:c,stageSequence:u}=i,d=c===ms&&n&&Pf({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?a=l:i.seedAssignments?a=i.seedAssignments:o=kt;return{seedAssignments:a,stageSequence:u,seedLimit:i.seedLimit??i?.positionAssignments?.length,stage:c,error:o}}function wf(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 Df({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 Rf({drawDefinition:t,structure:e,matchUp:n,event:r}){return{tieFormat:Df({item:n,drawDefinition:t,structure:e,event:r})||Df({item:e,drawDefinition:t,structure:e,event:r})||wf(t)||wf(r)}}function bf({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:o}=t,a=Array.isArray(o);if(a)a&&o.forEach(t=>{const{structureName:i}=t,o=t.matchUps;n[t.structureId]={matchUps:o,itemStructureIds:[],structureName:i},o&&(r.push(...o),o.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 Nf({mappedMatchUps:t,matchUpsMap:e,structureId:n,inContext:r}){const i=(t=e?.mappedMatchUps??t)[n],o=(i?.itemStructureIds??[]).map(e=>{const{matchUps:i,structureName:o}=t[e];return r?i.map(t=>Object.assign(ca(t,!0,!0),{containerStructureId:n,structureId:e,structureName:o})):i}).flat();return(i?.matchUps??[]).concat(...o)}function Mf({policyDefinitions:t,tournamentRecord:e,drawDefinition:n,structure:r,event:i}){const o=t?.[Du];if(o?.profileBands)return o.profileBands;if(e){const{appliedPolicies:t}=xd({tournamentRecord:e,drawDefinition:n,structure:r,event:i}),o=t?.[Du];if(o?.profileBands)return o.profileBands}return Hm[Du].profileBands}const Af=(t,e)=>(t||0)+(e||0);function Ef(t,e){const n=Array.isArray(t)?t[0]:t;return void 0===n||Number.isNaN(n)?Vm:n<=e[Wm]&&Wm||n<=e[qm]&&qm||jm}function Cf({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(Af)&&(n[r[0]>r[1]?0:1]+=1),{sets:e,games:n,score:t}}function Of(t){const e=t?.games;if(!e?.length)return;const n=Math.max(...e);if(0===n)return;const r=Math.min(...e);return Math.round(r/n*100)}function kf(t){return t.map(Of).filter(t=>void 0!==t).sort((t,e)=>t-e).map(t=>parseFloat(t.toFixed(2)))}function Ff({tournamentRecord:t,profileBands:e,matchUp:n}){if(!n)return{error:Se};const{score:r,winningSide:i}=n;if(!i)return{error:sr};const o=e||Mf({tournamentRecord:t}),a=kf([Cf({score:r})]),s=Ef(a,o),c=Array.isArray(a)?a[0]:a;return{...Y,competitiveness:s,pctSpread:c}}function xf({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;const n=q(t,t.length/e).map(t=>t.reduce((t,e)=>t+e)),r=n.slice().sort(d);return n.map(t=>r.indexOf(t)+1)}function _f(t){if(!f(t))return!1;const{matchUpId:e,drawPositions:n}=t,r="string"==typeof e,i=!n||Array.isArray(n)&&n.length<=2&&n.every(t=>R(t)||null==t);return r&&i}function Lf(t){return!!Array.isArray(t)&&t.every(_f)}function Bf({matchUps:t=[],interpolate:e}){if(!Lf(t))return{roundMatchUps:[],error:sr};const n=t.reduce((t,e)=>{const n="string"==typeof e.roundNumber?p(e.roundNumber):e.roundNumber;return!e.roundNumber||t.includes(n)?t:t.concat(n)},[]).sort(d).map(e=>{const n=t.filter(t=>t.roundNumber===e),r=n.find(({matchUpType:t})=>t===a)?n.filter(({matchUpType:t})=>t===a):n;return{[e]:(i=r,i.sort((t,e)=>d(t.roundPosition,e.roundPosition)))};var i}),r=t.reduce((t,e)=>{const n="string"==typeof e.roundNumber?p(e.roundNumber):e.roundNumber;return t[n]||(t[n]=Ei({abbreviatedRoundName:e.abbreviatedRoundName,finishingRound:e.finishingRound,roundName:e.roundName})),t},{}),i=Object.assign({},...n);if(e){const t=Math.max(...Object.keys(i).map(t=>p(t)).filter(t=>!Number.isNaN(t))),e=i[t]?.length;if(e>1&&S(e)){const n=t+1;L(n,n+e/2).forEach((t,n)=>{i[t]=L(0,e/(2+2*n)).map(()=>({}))})}}let o=0;const s=Object.assign({},...Object.keys(i).map(t=>{const e=i[t]?.length,n=i[t]?.filter(t=>!_p.includes(t.matchUpStatus)&&!t.score?.scoreStringSide1)?.length,r=e&&e===n;return o=Math.max(o,e),{[t]:{matchUpsCount:e,inactiveCount:n,inactiveRound:r}}}));let c=0,u=0;const l=Object.keys(i).map(t=>p(t)).filter(t=>!Number.isNaN(t));l.forEach(t=>{const e=i[t].sort((t,e)=>t.roundPosition-e.roundPosition),n=e.flatMap(t=>t?.drawPositions??[]);if(s[t].roundNumber=t,s[t].roundFactor=s[t].matchUpsCount?o/s[t].matchUpsCount:1,s[t].finishingRound=r[t]?.finishingRound,s[t].roundName=r[t]?.roundName,s[t].abbreviatedRoundName=r[t]?.abbreviatedRoundName,s[t].finishingPositionRange=i[t]?.[0]?.finishingPositionRange,1!==t&&s[t-1]){const n=s[t-1],r=n.drawPositions,i=n.matchUpsCount/s[t].matchUpsCount,o=q(r,i),a=e.map(e=>{const{roundPosition:n}=e,i=[...e.drawPositions??[],void 0,void 0].slice(0,2);if(!n)return i;const a=i?.filter(Boolean)??[];if(!a?.length)return[void 0,void 0];if(t<3&&2===a?.length)return i?.slice().sort(d);const s=V(r,a).length!==a?.length;if(a?.length&&s)return 1===a?.length?[a[0],void 0]:i?.slice().sort(d);const c=2*(n-1);return o.slice(c,c+2).map(t=>function(t,e){return e?.find(e=>t.includes(e))}(t,a))});s[t].drawPositions=a?.flat(),s[t].pairedDrawPositions=a}else{const e=n.sort(d),r=q(e,2);s[t].drawPositions=e,s[t].pairedDrawPositions=r}s[t+1]?.matchUpsCount===s[t].matchUpsCount&&(s[t+1].feedRound=!0,s[t+1].feedRoundIndex=u,s[t].preFeedRound=!0,u+=1),s[t]&&!s[t].feedRound&&(s[t].roundIndex=c,c+=1)});const m=!!Object.values(s).some(({matchUpsCount:t})=>!S(t));return{hasNoRoundPositions:t.some(t=>!t.roundPosition),roundsNotPowerOf2:m,maxMatchUpsCount:o,roundMatchUps:i,roundNumbers:l,roundProfile:s,...Y}}function Vf(t){if(!Array.isArray(t))return"";const e=t.filter(P);if(!e.length)return"";return M([Math.min(...e),Math.max(...e)]).join("-")}function Gf({drawDefinition:t}){if("object"!=typeof t)return{error:at};const e={},{structures:n=[],links:r=[]}=t??{},i=n.reduce((t,e)=>{const{stage:n}=e;return t[n]?t[n].push(e):t[n]=[e],t},{});for(const t of Object.keys(i)){const n=i[t].find(({stageSequence:t})=>1===t);if(!n)continue;const{structureId:r}=n;o({aggregator:{},targetRound:0,exitProfiles:e,exitProfile:"0",structureId:r,stage:t})}return{exitProfiles:e};function o({exitProfiles:t,exitProfile:e,structureId:i,targetRound:a,aggregator:s,stage:c}){t[i]||(t[i]=[]),"0"===e&&[ps,ms].includes(c)||t[i].push(e);const u=r.filter(t=>t.source.structureId===i&&t.source.roundNumber>=a);for(const r of u){const i=r.source.roundNumber,a=r.target.roundNumber,c=r.target.structureId,u=n.find(t=>t.structureId===c).stage,d=[u,c,a,i].join("|");if(s[d])return;s[d]=!0,o({exitProfile:`${e}-${i}`,structureId:c,exitProfiles:t,targetRound:a,aggregator:s,stage:u})}}}const jf=new Set([js,qs]);function qf(t){return!!t&&jf.has(t)}function Wf({structure:t,matchUps:e}){const n=Bf({matchUps:e=e??t?.matchUps??[]}),r=n.roundProfile,i=n.roundNumbers;if(!r||!i?.length||i.length<2)return!1;const o=[...i].sort((t,e)=>t-e);for(let t=0;t<o.length-1;t++){const e=r[o[t]]?.matchUpsCount??0,n=r[o[t+1]]?.matchUpsCount??0;if(e%2==1&&n%2==0)return!0}return!1}function $f({roundsNotPowerOf2:t,drawDefinition:e,structure:n,matchUps:r}){if(!n)return!1;r=r??n.matchUps??[],t=t??Bf({matchUps:r}).roundsNotPowerOf2;return!(!n.positionAssignments?.find(({drawPosition:t})=>t)&&!r?.find(({drawPositions:t})=>t?.length)||n?.structures)&&((!e?.drawType||!qf(e.drawType))&&(!!t&&Wf({structure:n,matchUps:r})))}function Hf({structure:t}){if(!t)return!1;const e=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),n=!!e?.find(t=>t?.roundPosition),r=!!e?.find(t=>t?.drawPositions?.length);return t?.stage===ls?!t?.structures&&((t?.structureType!==ws||!r)&&t?.finishingPosition===pc):!(t?.structures||e.length&&(n||r))}const zf={[Au]:{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:{[us]:"",[ms]:"P",[ds]:"Q",[ps]:"C"}}};function Yf({roundNamingPolicy:t,drawDefinition:e,structure:n,matchUps:r}){const{roundProfile:i,roundMatchUps:o}=Bf({matchUps:r}),{structureAbbreviation:a,stage:s}=n,c=Hf({structure:n}),u=$f({structure:n}),d=n.structures,p={},l=zf[Au],m=n.stage===ds,f=m?Math.max(...(e?.structures??[]).filter(t=>t.stage===ds).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??{}),S=t?.abbreviatedRoundNamingMap||(l.abbreviatedRoundNamingMap??{}),y=t?.affixes?.preFeedRound||l.affixes.preFeedRound,v=t?.affixes?.roundNumber||l.affixes.roundNumber,U=(t?.namingConventions||l.namingConventions).round,P=s&&s!==us?s[0]:"",T=t?.stageConstants||l.stageConstants,w=`${g}${s&&T?.[s]||P}${h}`,D=i?Object.keys(i):[],R=m&&T?.[ds]?`${T?.[ds]}-`:"";if(d||c||u)Object.assign(p,...D.map(t=>{const e=`${R}${U} ${t}`,n=`${v}${t}`;return{[t]:{roundName:e,abbreviatedRoundName:n}}}));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],o=2*n,s=e?.[i?.[t].finishingRound]||e&&`${v}${o}`||I[n]||`${v}${o}`,c=r?`-${y}`:"",u=[w,a,`${s}${c}`].filter(Boolean).join("-"),d=S[n]||`${v}${o}`,p=[w,a,`${d}${c}`].filter(Boolean).join("-");return{[t]:{abbreviatedRoundName:p,roundName:u}}}))}return{roundNamingProfile:p,roundProfile:i,roundMatchUps:o}}function Kf({matchUp:t}){if(!t)return{error:Se};if(t&&!t.sides)return{error:ye};if(t&&!t.hasContext)return{error:Kn};const e=(t.sides??[])?.map(t=>t?.participantId).filter(Boolean),n=t.sides?.filter(t=>t.participant?.participantType===gm).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,...Y}}const Qf="CHECK_IN",Jf="CHECK_OUT",Xf="SCHEDULE.ASSIGNMENT.VENUE",Zf="SCHEDULE.ALLOCATION.COURTS",th="SCHEDULE.ASSIGNMENT.COURT",eh="SCHEDULE.COURT.ORDER",nh="SCHEDULE.COURT.ANNOTATION",rh="SCHEDULE.DATE",ih="HOME_PARTICIPANT_ID",oh="SCHEDULE.ASSIGNMENT.OFFICIAL",ah="SCHEDULE.TIME.SCHEDULED",sh="SCHEDULE.TIME.START",ch="SCHEDULE.TIME.STOP",uh="SCHEDULE.TIME.RESUME",dh="SCHEDULE.TIME.END",ph="SCHEDULE.TIME.MODIFIERS",lh="TO_BE_ANNOUNCED",mh="NEXT_AVAILABLE",fh="FOLLOWED_BY",hh="AFTER_REST",gh="RAIN_DELAY",Ih=[lh,mh,fh,hh,gh],Sh="SCALE",yh="RATING",vh="RANKING",Uh="SEEDING",Ph="PUBLISH",Th="PUBLIC",wh="STATUS",Dh={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:Ih,AFTER_REST:hh,ALLOCATE_COURTS:Zf,ASSIGN_COURT:th,ASSIGN_OFFICIAL:oh,ASSIGN_VENUE:Xf,CHECK_IN:Qf,CHECK_OUT:Jf,COMPLETED_DATE:"COMPLETED.DATE",COURT_ANNOTATION:nh,COURT_ORDER:eh,ELIGIBILITY:"ELIGIBILITY",END_TIME:dh,FOLLOWED_BY:fh,MEDICAL:"MEDICAL",MODIFICATION:"MODIFICATION",NEXT_AVAILABLE:mh,NOT_BEFORE:"NOT_BEFORE",OTHER:"other",PENALTY:"PENALTY",PUBLIC:Th,PUBLISH:Ph,RANKING:vh,RATING:yh,RAIN_DELAY:gh,REGISTRATION:"REGISTRATION",RESUME_TIME:uh,RETRIEVAL:"RETRIEVAL",SCALE:Sh,SCHEDULE:"SCHEDULE",SCHEDULED_DATE:rh,SCHEDULED_TIME:ah,SEEDING:Uh,START_TIME:sh,STATUS:wh,STOP_TIME:ch,SUSPENSION:"SUSPENSION",TIME_MODIFIERS:ph,TO_BE_ANNOUNCED:lh};function Rh({matchUp:t}){if(!t)return{error:Se};if(!t.hasContext)return{error:Kn};if(!t.sides||2!==t?.sides.filter(Boolean).length)return{error:ye};const{nestedIndividualParticipantIds:e,allRelevantParticipantIds:n,sideParticipantIds:r}=Kf({matchUp:t}),i=(t.timeItems??[]).filter(t=>t?.itemType&&[Qf,Jf].includes(t.itemType)).sort((t,e)=>(t.createdAt?new Date(t.createdAt).getTime():0)-(e.createdAt?new Date(e.createdAt).getTime():0)),o=i.map(t=>t.itemValue).filter(t=>i.filter(e=>e?.itemValue===t).reverse()[0].itemType===Qf);e?.forEach((t,e)=>{const n=r?.[e],i=t?.length&&t.every(t=>o.includes(t));n&&i&&!o.includes(n)&&o.push(n)}),r?.forEach((t,n)=>{o.includes(t)&&(e?.[n]??[]).forEach(t=>{t&&!o.includes(t)&&o.push(t)})});const a=r?.reduce((t,e)=>o.includes(e)&&t,!0);return{allRelevantParticipantIds:n,allParticipantsCheckedIn:a,checkedInParticipantIds:o,...Y}}const bh=t=>e=>{const n=f(e)&&e?.matchUpType||m(e)&&e;return n&&u[t].includes(n)};function Nh(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],o=e?.find(({matchUpFormatCodes:t,averageTimes:e})=>t?.find(t=>i===t)&&e);return o?.averageTimes}function Mh(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 Ah({timesBlockArray:t,categoryName:e,categoryType:n}){return t.filter(t=>Array.isArray(t)).map(t=>t.sort((t,e)=>(e.categoryNames?.length||0)-(t.categoryNames?.length||0)).find(({categoryTypes:t,categoryNames:r})=>!r?.length&&!t?.length||r?.includes(e)||t?.includes(n))).find(Boolean)}const Eh="ADULT",Ch="JUNIOR",Oh="WHEELCHAIR",kh={[Ou]:{allowModificationWhenMatchUpsScheduled:{courts:!1,venues:!1},defaultTimes:{averageTimes:[{categoryNames:[],minutes:{default:90}}],recoveryTimes:[{minutes:{[i]:30,default:60}}]},defaultDailyLimits:{[n]:2,[i]:2,total:3},matchUpAverageTimes:[{matchUpFormatCodes:[va],averageTimes:[{categoryNames:[],minutes:{default:90}},{categoryTypes:[Oh],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:[Eh,Oh],minutes:{default:60,[i]:30}},{categoryTypes:[Ch],minutes:{default:60,[i]:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7","SET3-S:4/TB7-F:TB10","SET3-S:4NOAD-F:TB7","SET3-S:4/TB7","SET3-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[Eh,Oh],minutes:{default:30}},{categoryTypes:[Ch],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:[Eh,Ch],minutes:{default:30}},{categoryTypes:[Oh],minutes:{default:15}}]},{matchUpFormatCodes:["SET1-S:TB10"],recoveryTimes:[{categoryNames:[],minutes:{default:15}}]}],matchUpDailyLimits:[]}},Fh="DOUBLES_SINGLES",xh="SINGLES_DOUBLES",_h="total",Lh="participantConflict",Bh="potentialParticipantConflict",Vh="matchUpConflict",Gh="courtDoubleBooking",jh="positionLinkConflict",qh="ISSUE_IDS",Wh="CONFLICT",$h="WARNING",Hh="ERROR",zh="ISSUE",Yh="STATE",Kh="PRACTICE",Qh={SINGLES_DOUBLES:xh,DOUBLES_SINGLES:Fh,TOTAL:_h,CONFLICT_MATCHUP_ORDER:Vh,CONFLICT_PARTICIPANTS:Lh,CONFLICT_POTENTIAL_PARTICIPANTS:Bh,CONFLICT_COURT_DOUBLE_BOOKING:Gh,CONFLICT_POSITION_LINK:jh,SCHEDULE_ISSUE_IDS:qh,SCHEDULE_CONFLICT:Wh,SCHEDULE_WARNING:$h,SCHEDULE_ERROR:Hh,SCHEDULE_ISSUE:zh,SCHEDULE_STATE:Yh,BLOCKED:"BLOCKED",PRACTICE:Kh,MAINTENANCE:"MAINTENANCE"};function Jh({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:n,matchUpFormat:r,categoryName:i,categoryType:o,eventType:a,event:s}){if(!n)return{error:rt};a=a??s?.eventType??es;const c=function(t){if(!t)return;const e=t.matchUpConstraint?.timed?t.matchUpConstraint.minutes:void 0;if("number"==typeof e)return e;const n=t.setFormat?.timed&&"number"==typeof t.setFormat.minutes?t.setFormat.minutes:void 0;if("number"!=typeof n)return;const r=t.bestOf??1,i=t.finalSetFormat?.timed&&"number"==typeof t.finalSetFormat.minutes?t.finalSetFormat.minutes:void 0;return r<=1?n:"number"==typeof i?(r-1)*n+i:r*n}(co(r)),u={averageTimes:[{minutes:{default:c??t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:d}=Jm({tournamentRecord:n,categoryName:i,categoryType:o,event:s});let p=d.policy??kh[Ou];"number"==typeof c&&p&&(p={...p,defaultTimes:{...p.defaultTimes,averageTimes:[{minutes:{default:c}}]}});return Xh({eventType:a,timingDetails:{...d,policy:p,matchUpFormat:r,categoryType:o,defaultTiming:u}})}function Xh({timingDetails:t,eventType:e}){const n=function({matchUpFormat:t,categoryName:e,categoryType:n,defaultTiming:r,tournamentScheduling:i,eventScheduling:o,policy:a}){return Ah({categoryName:e,categoryType:n,timesBlockArray:[o?.matchUpAverageTimes&&Nh({...o,matchUpFormat:t}),i?.matchUpAverageTimes&&Nh({...i,matchUpFormat:t}),a?.matchUpAverageTimes&&Nh({...a,matchUpFormat:t}),a?.defaultTimes?.averageTimes,r?.averageTimes]})}(t),r=Object.keys(n?.minutes??{}),i=n?.minutes&&(r?.includes(e)&&n.minutes[e]||n.minutes.default),o=function({tournamentScheduling:t,eventScheduling:e,averageMinutes:n,defaultTiming:r,matchUpFormat:i,categoryName:o,categoryType:a,policy:s}){return Ah({categoryName:o,categoryType:a,timesBlockArray:[e?.matchUpRecoveryTimes&&Mh({...e,averageMinutes:n,matchUpFormat:i}),t?.matchUpRecoveryTimes&&Mh({...t,averageMinutes:n,matchUpFormat:i}),s?.matchUpRecoveryTimes&&Mh({...s,averageMinutes:n,matchUpFormat:i}),s?.defaultTimes?.recoveryTimes,r?.recoveryTimes]})}({...t,averageMinutes:i}),a=Object.keys(o?.minutes??{}),s=o?.minutes&&(a?.includes(e)&&o.minutes[e]||o.minutes.default),c=bh(es)(e)?xh:Fh;return{averageMinutes:i,recoveryMinutes:s,typeChangeRecoveryMinutes:o?.minutes&&(a?.includes(c)&&o.minutes[c]||s)}}function Zh(t){return t.createdAt?new Date(t.createdAt).getTime():0}function tg({timeItems:t,itemType:e}){const n=t.filter(t=>t&&t.itemType===e).sort((t,e)=>Zh(t)-Zh(e)).pop(),r=n&&Zh(n);return{itemValue:n?.itemValue,timeStamp:r}}function eg({timeStamp:t,schedule:e,matchUp:n}){const{itemValue:r,timeStamp:i}=tg({timeItems:n?.timeItems??[],itemType:ah});return!e||i&&t&&new Date(i).getTime()>new Date(t).getTime()?{scheduledTime:r}:e}function ng({timeStamp:t,schedule:e,matchUp:n}){const r=n?.schedule?.scheduledDate,{itemValue:i,timeStamp:o}=tg({timeItems:n?.timeItems??[],itemType:rh}),a=r??i;return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledDate:a}:e}function rg(t){if(yo.test(t)){const e=Ro();return new Date(`${e}T${t}`)}return new Date(t)}function ig(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 og(t){return parseInt(t)}function ag({startTime:t="",endTime:e=""}={}){if(!(t&&e&&Uo.test(t)&&Uo.test(e)))return!1;const[n,r]=t.split(":").map(og),[i,o]=e.split(":").map(og);return!(i<n)&&!(n===i&&o<r)}function sg(t,e){const[n,r]=t.startTime.split(":").map(og),[i,o]=e.startTime.split(":").map(og);return n<i?-1:n>i?1:r<o?-1:r>o?1:0}function cg({dateAvailability:t}){if(!t)return{error:xe};if(!Array.isArray(t))return{error:Fe};for(const e of t){if("object"!=typeof e)return{error:Fe};const{date:t,startTime:n,endTime:r,bookings:i=[]}=e;if(!n||!r)return{error:Fe};const o=pg(t);if(o)return o;const a=lg(n,r);if(a)return a;if(i){const t=mg(i);if(t)return t}}return{valid:!0}}const ug="Dates must be formated => YYYY-MM-DD",dg="Times must be 24 hour => 00:00";function pg(t){if(t&&!vo.test(t))return{error:_e,dateAvailability:{date:t},info:ug}}function lg(t,e){return Uo.test(t)?Uo.test(e)?t===e?{error:Le,dateAvailability:{startTime:t,endTime:e},info:"startTime and endTime are equivalent"}:ag({startTime:t,endTime:e})?void 0:{error:Le,dateAvailability:{startTime:t,endTime:e},info:"endTime must be after startTime"}:{error:Le,dateAvailability:{endTime:e},info:dg}:{error:Le,dateAvailability:{startTime:t},info:dg}}function mg(t){if(!Array.isArray(t))return{error:ke};for(const e of t){if("object"!=typeof e)return{error:ke};const{startTime:t,endTime:n}=e,r=lg(t,n);if(r)return r}}function fg({tournamentRecord:t}){for(const e of t.venues??[])e.isPrimary&&delete e.isPrimary}function hg(t){const{disableNotice:e,venue:n,context:r}=t;if("object"!=typeof n)return{error:sr};const i=im(t);let o;n.venueId??=pa();for(const t of Object.values(i)){const e=gg({disableNotice:!0,tournamentRecord:t,context:r,venue:n});if(e?.error)return e;o=e.venue}return e||di({topic:gl,payload:{venue:n}}),Ei({...Y,venue:o})}function gg({tournamentRecord:t,disableNotice:e,context:n,venue:r}){const i=dl({tournamentRecord:t},[Ic]);if(i.error)return i;if(!r)return{error:Ae,info:"missing venue"};t.venues??=[],r.venueId??=pa();if(t.venues.reduce((t,e)=>t||e.venueId===r.venueId,void 0))return{error:_n};if(r.dateAvailability?.length){const t=cg({dateAvailability:r.dateAvailability});if(t.error)return t}if(r.defaultStartTime||r.defaultEndTime){if(!r.defaultStartTime||!r.defaultEndTime)return{error:sr,info:"both defaultStartTime and defaultEndTime are required"};if(!ag({startTime:r.defaultStartTime,endTime:r.defaultEndTime}))return{error:sr,info:"defaultEndTime must be after defaultStartTime"}}if(n){$u({element:r,extension:{value:n,name:rd}})}return r.isPrimary&&fg({tournamentRecord:t}),t.venues.push(r),{...Y,venue:ca(r)}}function Ig({tournamentRecords:t,tournamentRecord:e,venueId:n}){const r=dl({tournamentRecord:e,venueId:n},[Ic,Xc]);if(r.error)return r;const i=(e.venues??[]).reduce((t,e)=>e.venueId===n?e:t,void 0);if(!i&&t){const r=(zp({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(const o of r){const r=Ig({tournamentRecord:t[o],venueId:n});if(r.success&&r.venue)return hg({tournamentRecord:e,venue:r.venue}),{...Y,venue:i}}}return i?{...Y,venue:i}:{error:Ln}}function Sg({convertExtensions:t,...e}){const{tournamentRecords:n,tournamentRecord:r,venueId:i}=e;return ca(Ig({tournamentRecords:n,tournamentRecord:r,venueId:i}),t,!0)}function yg({tournamentRecords:t,tournamentRecord:e,courtId:n}){const r=dl({tournamentRecord:e,courtId:n},[Ic,jc]);if(r.error)return r;let i,o;if((e.venues??[]).forEach(t=>{(t.courts??[]).forEach(e=>{e.courtId===n&&(i=e,o=t)})}),i)return{...Y,court:i,venue:o};if(t){const r=(zp({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(const a of r){const r=yg({tournamentRecord:t[a],courtId:n});if(r.success)return r.venue&&hg({tournamentRecord:e,venue:r.venue}),{...Y,court:i,venue:o}}}return Ci({result:{error:Cn},stack:"findCourt"})}function vg(t){return ca(yg(t),!1,!0)}function Ug({tournamentRecord:t,internalUse:e,courtId:n}){const r=dl({tournamentRecord:t,courtId:n},[Ic,jc]);if(r.error)return r;const i=yg({tournamentRecord:t,courtId:n});if(i.error)return i;const o=i.court&&(({altitude:t,courtId:e,courtName:n,courtDimensions:r,latitude:i,longitude:o,surfaceCategory:a,surfaceType:s,surfacedDate:c,pace:u,notes:d})=>({altitude:t,courtId:e,courtName:n,courtDimensions:r,latitude:i,longitude:o,surfaceCategory:a,surfaceType:s,surfacedDate:c,pace:u,notes:d}))(i.court);return{...Y,courtInfo:ca(o,!1,e)}}function Pg(t){const e=fu(t,[{[Ic]:!0},{venueId:!0,[Hc]:Bn}]);if(e.error)return e;const{tournamentRecord:n,venueId:r}=t,i=Ig({tournamentRecord:n,venueId:r});if(i.error)return i;const o=(i.venue?.courts??[]).map(t=>(({courtInfo:t})=>({...t}))(Ug({courtId:t.courtId,internalUse:!0,tournamentRecord:n}))),a=i.venue&&(({venueId:t,venueName:e,venueAbbreviation:n})=>({venueAbbreviation:n,venueName:e,venueId:t}))(i.venue),s=a&&{...a,courtsInfo:o};return{...Y,venueData:ca(s,!1,!0)}}function Tg({event:t,eventId:e}){if(!t)return{error:Ht};const n=dp({element:t,attribute:"flightProfile",name:ld}),r=e?ca(n,!1,!0):n;return e&&t.drawDefinitions?.forEach(t=>{r?.flights?.forEach(e=>{e.drawId===t.drawId&&Object.assign(e,{drawDefinition:t})})}),{flightProfile:r}}function wg(t){const{tournamentRecord:e,eventId:n,drawId:r}=t,i="findEvent",o={},a=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},s=Object.values(a).map(({events:t,tournamentId:e})=>(t&&t.forEach(t=>{o[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=o[e.eventId].tournamentId;else{const t=e&&Tg({event:e})?.flightProfile,n=t?.flights?.find(t=>t.drawId===r);if(n)return c=o[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=o[t.eventId].tournamentId,{event:t,drawDefinition:void 0,tournamentId:c}):{event:void 0,drawDefinition:void 0,...Ci({result:{error:zt},stack:i})}}return{event:void 0,drawDefinition:void 0,...Ci({result:{error:ut},context:{drawId:r,eventId:n},stack:i})}}function Dg(t){let e=t.event,n=t.matchUpType;const{scheduleVisibilityFilters:r,afterRecoveryTimes:i,tournamentRecord:o,usePublishState:a,scheduleTiming:s,matchUpFormat:c,publishStatus:u,matchUp:d}=t;if(!d)return{error:Se};if(i&&!d.matchUpType&&!t.matchUpType&&(e||o)&&d.drawId){let r=t.drawDefinition||e?.drawDefinitions?.find(t=>t.drawId===d.drawId);!r&&o&&({drawDefinition:r,event:e}=wg({drawId:d.drawId,tournamentRecord:o}));const i=d.structureId?r?.structures?.find(({structureId:t})=>t===d.structureId):void 0;n=t.matchUpType||i?.matchUpType||r?.matchUpType||e?.eventType!==is&&e?.eventType}const{milliseconds:p,time:l}=function({matchUp:t}){if(!t)return{error:Se};if(!t.timeItems)return{error:Yn};const e=t.timeItems.filter(t=>[sh,ch,uh,dh].includes(t?.itemType)).sort((t,e)=>rg(t.itemValue).getTime()-rg(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 sh:n=0;break;case dh:if(t.lastValue&&[sh,uh].includes(t.lastType)){const r=rg(e.itemValue).getTime()-rg(t.lastValue).getTime();n=t.milliseconds+r}else n=t.milliseconds;break;case ch:if([sh,"SCHECULE.TIME.RESUME"].includes(t.lastType)){const r=rg(e.itemValue).getTime()-rg(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([sh,uh].includes(n.lastType)){const t=(new Date).getTime()-rg(n.lastValue).getTime();n.milliseconds+=t}return{milliseconds:n.milliseconds,time:ig(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===sh&&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===dh&&n;return r&&(!t||e(r)>e(t))?r:t},void 0),r=n?.itemValue;return{endTime:r}}({matchUp:d}),{eventIds:h,drawIds:g}=r??{};let I=(!h||h.includes(d.eventId))&&(!g||g.includes(d.drawId))?function({tournamentRecord:t,scheduleTiming:e,afterRecoveryTimes:n,matchUpFormat:r,matchUpType:i,matchUp:o,endTime:a,startTime:s,milliseconds:c,time:u}){const d=t=>t.createdAt?new Date(t.createdAt).getTime():0,p=new Map,l=o.timeItems?.toSorted((t,e)=>d(t)-d(e))??[];for(const t of l)p.set(t.itemType,t.itemValue);const m=o.schedule??{},f=m.homeParticipantId??p.get(ih),h=m.courtAnnotation??p.get(nh),g=m.allocatedCourts??p.get(Zf),I=m.scheduledTime??p.get(ah),S=m.timeModifiers??p.get(ph);let y=m.scheduledDate??p.get(rh);const v=m.official??p.get(oh),U=m.courtOrder??p.get(eh),P=m.venueId??p.get(Xf),T=m.courtId??p.get(th),w=function({scheduleTiming:t,afterRecoveryTimes:e,matchUpFormat:n,matchUpType:r,matchUp:i,endTime:o,scheduledTime:a}){let s,c,u,d,p;const l=i.matchUpType??r;if(t&&a&&e&&l){const e={matchUpFormat:i.matchUpFormat??n,...t};({averageMinutes:c=0,recoveryMinutes:u=0,typeChangeRecoveryMinutes:d=0}=Xh({timingDetails:e,eventType:l})),(c||u)&&(s=o?Ho(_o(o),u):Ho(a,c+u)),d&&(p=o?Ho(_o(o),d):Ho(a,c+d))}return{timeAfterRecovery:s,averageMinutes:c,recoveryMinutes:u,typeChangeRecoveryMinutes:d,typeChangeTimeAfterRecovery:p}}({scheduleTiming:e,afterRecoveryTimes:n,matchUpFormat:r,matchUpType:i,matchUp:o,endTime:a,scheduledTime:I});!y&&I&&(y=Lo(I));const D=Po({scheduledDate:y,scheduledTime:I}),{venueName:R,venueAbbreviation:b,courtName:N}=function({tournamentRecord:t,allocatedCourts:e,venueId:n,courtId:r}){const i={},o=(t&&n&&Pg({tournamentRecord:t,venueId:n}))?.venueData??{};n&&(i[n]=o);const{venueName:a,venueAbbreviation:s,courtsInfo:c}=o,u=r&&c?.find(t=>t.courtId===r),d=u?.courtName;for(const n of e??[]){if(!t)break;n.venueId&&!i[n.venueid]&&(i[n.venueId]=Pg({venueId:n.venueId,tournamentRecord:t})?.venueData);const e=i[n.venueId];n.venueName=e?.venueName;const r=e?.courtsInfo?.find(t=>t.courtId===n.courtId);n.courtName=r?.courtName}return{venueName:a,venueAbbreviation:s,courtName:d}}({tournamentRecord:t,allocatedCourts:g,venueId:P,courtId:T});return Ei({typeChangeTimeAfterRecovery:w.typeChangeTimeAfterRecovery,typeChangeRecoveryMinutes:w.typeChangeRecoveryMinutes,timeAfterRecovery:w.timeAfterRecovery,recoveryMinutes:w.recoveryMinutes,averageMinutes:w.averageMinutes,homeParticipantId:f,courtAnnotation:h,venueAbbreviation:b,allocatedCourts:g,scheduledDate:y,scheduledTime:I,isoDateString:D,timeModifiers:S,venueName:R,venueId:P,courtOrder:U,courtName:N,courtId:T,official:v,milliseconds:c,startTime:s,endTime:a,time:u})}({tournamentRecord:o,scheduleTiming:s,afterRecoveryTimes:i,matchUpFormat:c,matchUpType:n,matchUp:d,endTime:f,startTime:m,milliseconds:p,time:l}):Ei({milliseconds:p,startTime:m,endTime:f,time:l});const{scheduledDate:S}=ng({matchUp:d}),{scheduledTime:y}=eg({matchUp:d});if(a&&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){I=Tu({source:I,template:Object.assign({},...Object.keys(I).map(t=>({[t]:!0})),t)})}}}return{schedule:I,endDate:d.matchUpStatus&&_p.includes(d.matchUpStatus)&&(Lo(f)||Lo(S)||Lo(y))||void 0}}function Rg({collectionPosition:t,collectionId:e,lineUp:n}){let r=[];const i=[];if(n){const o=t=>void 0===t?-1:t,a=n.map(n=>{const{collectionAssignments:r,participantId:i}=n,o=r?.find(n=>n.collectionPosition===t&&n.collectionId===e);return o&&{participantId:i,...o}}).filter(Boolean).sort((t,e)=>o(t.substitutionOrder)-o(e.substitutionOrder));for(const t of a){const{participantId:e,previousParticipantId:n,substitutionOrder:o}=t;r.includes(e)||(n&&i.push({previousParticipantId:n,substitutionOrder:o,participantId:e}),r=r.filter(t=>t!==n),r.push(e))}}return{assignedParticipantIds:r,substitutions:i}}function bg({tournamentParticipants:t,tournamentRecord:e,participantIds:n}){const r="getPairedParticipant";if(!t&&!e)return{error:rt};if(!Array.isArray(n)||n.length>2)return{error:tn};if(!n.length)return Ci({result:{error:ln},stack:r});const i=(t=t??e?.participants??[]).filter(t=>t.participantType===Sm&&V(n,t.individualParticipantIds).length===n.length&&t.individualParticipantIds.length===n.length),o=i[0];if(!o)return Ci({result:{error:un},stack:r});const a=ca(i.slice(1),!1,!0);return{participant:ca(o),duplicatedPairParticipants:a,...Y}}function Ng({drawDefinition:t,participantId:e}){if("object"!=typeof t)return{error:st};if("string"!=typeof e)return{error:sn};return{lineUp:(dp({element:t,attribute:"lineUps",name:fd})??{})[e]}}function Mg(t){const e=fu(t,[{[Wc]:!0}]);if(e.error)return e;const r=t?.matchUp;let o=r?.matchUpType;if(!o&&r?.sides?.length){const t=r.sides.find(({participant:t})=>t),e=t?.participant,a=e?.participantType;o=a===gm&&n||a===Sm&&i||a===ym&&ym||void 0}return{matchUpType:o}}function Ag({drawPositionCollectionAssignment:t,sideNumberCollectionAssignment:e,positionAssignments:n,displaySideNumber:r,seedAssignments:i,drawPosition:o,isFeedRound:a,sideNumber:s}){const c=n.find(t=>t.drawPosition&&t.drawPosition===o),u=o&&t,d=s&&e,p=u?u[o]?.participantId:c?.participantId,l=c?function({displaySideNumber:t,seedAssignments:e,participantId:n,assignment:r,sideNumber:i}){const o={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(o,t,{participantId:n}),t?.seedNumber&&""===t?.seedValue&&(o.seedValue="~")}else r.bye&&Object.assign(o,{bye:!0});r.qualifier&&Object.assign(o,{qualifier:!0});return o}({displaySideNumber:r,seedAssignments:i,participantId:p,assignment:c,sideNumber:s}):{...d?.[s]};if(a&&(1===s?Object.assign(l,{participantFed:!0}):Object.assign(l,{participantAdvanced:!0})),o&&u){const t=u[o]?.teamParticipant,e=u[o]?.participant,n=u[o]?.substitutions;e&&(l.participant=e),n&&(l.substitutions=n),t&&(l.teamParticipant=t)}return l}function Eg(t){const e=t?.embargo;return!(!e||!Co(e))&&new Date(e).getTime()>Date.now()}function Cg(t){return!!t?.published&&!Eg(t)}function Og({scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,tournamentParticipants:r,positionAssignments:o,drawPositionsRanges:a,hydrateParticipants:s,afterRecoveryTimes:c,initialRoundOfPlay:u,additionalContext:l,roundNamingProfile:m,tournamentRecord:f,tieDrawPositions:h,appliedPolicies:g,isCollectionBye:I,seedAssignments:S,usePublishState:y,participantMap:v,contextContent:U,scheduleTiming:P,contextProfile:T,drawDefinition:w,publishStatus:D,scoringActive:b,matchUpTieId:N,isRoundRobin:A,roundProfile:E,sideLineUps:C,structure:O,context:k,matchUp:F,event:x}){l=l??{};const _=Rf({drawDefinition:w,structure:O,matchUp:F,event:x})?.tieFormat,{roundOffset:L,structureId:B,structureName:V,stage:G,stageSequence:q}=O,{drawId:H,drawName:z,drawType:Y}=w??{},K=_?.collectionDefinitions,Q=F.collectionId&&K?.find(t=>t.collectionId===F.collectionId),J=F.collectionId?Q?.matchUpFormat:F.matchUpFormat??O?.matchUpFormat??w?.matchUpFormat??x?.matchUpFormat,X=F.matchUpType||Q?.matchUpType||O?.matchUpType||w?.matchUpType||!bh(is)(x?.eventType)&&x?.eventType,Z=I?Sp:F.matchUpStatus;let{schedule:tt,endDate:et}=Dg({scheduleVisibilityFilters:t,afterRecoveryTimes:c,tournamentRecord:f,usePublishState:y,scheduleTiming:P,drawDefinition:w,matchUpFormat:J,publishStatus:D,matchUpType:X,matchUp:F,event:x});y&&tt&&(tt=function({publishStatus:t,drawDefinition:e,structure:n,matchUp:r,schedule:i}){if(!t||!e?.drawId||!n?.structureId)return i;const o=t?.drawDetails?.[e.drawId]?.structureDetails?.[n.structureId];if(!o)return i;const a=r.roundNumber;if(!R(a))return i;const s=o.scheduledRounds?.[a];return s&&Eg(s)?void 0:i}({publishStatus:D,drawDefinition:w,structure:O,matchUp:F,schedule:tt}));const nt=h??F.drawPositions??[],{collectionPosition:rt,collectionId:it,roundPosition:ot}=F,at=F.roundNumber??l.roundNumber,st=it?function({tournamentParticipants:t,positionAssignments:e,collectionPosition:n,drawPositions:r=[],participantMap:o,drawDefinition:a,collectionId:s,sideLineUps:c,matchUpType:u}){if(!s||!n)return{};const d=({attribute:e,lineUp:r,teamParticipant:a})=>{const{assignedParticipantIds:c,substitutions:d}=Rg({collectionPosition:n,collectionId:s,lineUp:r});if(u!==i){const t=c?.[0];return t&&{[e]:{participantId:t,teamParticipant:a,substitutions:d}}}if(c?.length<=2){const n=o?.[c[0]]?.pairIdMap?.[c[1]],r=n&&o[n]?.participant||bg({participantIds:c,tournamentParticipants:t}).participant,i=r?.participantId;return{[e]:{participantId:i,teamParticipant:a,substitutions:d}}}if(c?.length>2)return{[e]:{teamParticipant:a,substitutions:d}}};if(!r?.length){const t=c?.map(t=>{const{teamParticipant:e,sideNumber:n}=t,r=t.lineUp||Ng({participantId:e.teamParticipantId,drawDefinition:a})?.lineUp;return d({attribute:n,lineUp:r,teamParticipant:e})}).filter(Boolean)??{};return{sideNumberCollectionAssignment:Object.assign({},...t)}}const p=r?.map(n=>{const r=e.find(t=>t.drawPosition===n)?.participantId,i=c?.find(t=>t?.drawPosition===n),s=i?.teamParticipant||r&&o?.[r]?.participant||t?.find(({participantId:t})=>t===r),u=i?.lineUp||Ng({participantId:r,drawDefinition:a})?.lineUp;return d({attribute:n,lineUp:u,teamParticipant:s})}).filter(Boolean)??{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}({tournamentParticipants:r,positionAssignments:o,collectionPosition:rt,participantMap:v,drawDefinition:w,drawPositions:nt,collectionId:it,sideLineUps:C,matchUpType:X}):void 0,ct=m?.[at]?.roundName||l.roundName,ut=m?.[at]?.abbreviatedRoundName||l.abbreviatedRoundName,dt=E?.[at]?.feedRound,pt=E?.[at]?.preFeedRound,lt=E?.[at]?.roundFactor,mt=a?.[at],ft=ot?mt?.[ot]:void 0,ht=e?.[at],gt=Q?.category?{...k?.category,...Q.category}:k?.category??x?.category,It=function({matchUp:t,collectionDefinition:e,structure:n,drawDefinition:r,event:i,tournamentRecord:o}){return t.processCodes?.length&&t.processCodes||e?.processCodes?.length&&e?.processCodes||n?.processCodes?.length&&n?.processCodes||r?.processCodes?.length&&r?.processCodes||i?.processCodes?.length&&i?.processCodes||o?.processCodes}({matchUp:F,collectionDefinition:Q,structure:O,drawDefinition:w,event:x,tournamentRecord:f}),St=T?.withCompetitiveness&&Ff({...U,matchUp:F}),yt=F.finishingPositionRange??l.finishingPositionRange,vt=G!==ds&&R(u)&&u+(at||0),Ut=t=>Ei(t,void 0,!0),Pt={...Ut(k),...Ut({matchUpFormat:X===is?void 0:J,tieFormat:X===is?_:void 0,gender:Q?.gender??x?.gender,endDate:F.endDate??et,discipline:x?.discipline,category:gt,finishingPositionRange:yt,abbreviatedRoundName:ut,drawPositionsRange:ft,competitiveProfile:St,structureName:V,stageSequence:q,drawPositions:nt,matchUpStatus:Z,processCodes:It,isRoundRobin:A,matchUpTieId:N,preFeedRound:pt,matchUpType:X,roundFactor:lt,roundOffset:L,structureId:B,roundNumber:at,roundOfPlay:vt,feedRound:dt,roundName:ct,drawName:z,drawType:Y,schedule:tt,drawId:H,stage:G}),...ca(Ut(F),!0,!0)};if(J&&F.score?.scoreStringSide1&&function(t,e){const n=co(e),{bestOf:r,finalSetFormat:i,setFormat:o}=n??{};if(!i?.tiebreakSet&&!o?.tiebreakSet&&!o?.timed)return;t.score.sets=t.score.sets.sort((t,e)=>t.setNumber-e.setNumber).map((t,e)=>{const n=e+1===r&&i?i:o,a=n?.tiebreakSet&&!n?.timed,s=n?.timed;return a?(t.tiebreakSet=!0,[1,2].includes(t.winningSide)&&(t.side1Score=1===t.winningSide?1:0,t.side2Score=2===t.winningSide?1:0)):s&&(t.timed=!0),t})}(Pt,J),Array.isArray(nt)){const t=function({sourceDrawPositionRoundRanges:t,collectionAssignmentDetail:e,positionAssignments:n,seedAssignments:r,drawPositions:i,roundPosition:o,roundProfile:a,roundNumber:s,onlyDefined:c,matchUp:u}){const{orderedDrawPositions:l,displayOrder:m}=function({drawPositions:t,roundProfile:e,roundNumber:n}){const r=[void 0,void 0];if($(t))return{orderedDrawPositions:r,displayOrder:r};const i=e?.[n],o=i?.pairedDrawPositions,a=o?.find(e=>j(e??[],t.filter(Boolean)))??r,s=i?.feedRound;if(W(t)){const e=[...t].sort(d);return{orderedDrawPositions:2===e.length?e:a,displayOrder:s?e:a}}if(s){const e=[t.find(t=>!isNaN(p(t))),void 0];return{orderedDrawPositions:e,displayOrder:e}}return{orderedDrawPositions:a,displayOrder:a}}({drawPositions:i,roundProfile:a,roundNumber:s}),f=a?.[s]?.feedRound,h=m[0]!==l[0];return l.concat(void 0,void 0).slice(0,2).map((i,a)=>{const s=a+1,d=Ag({...e,positionAssignments:n,displaySideNumber:h?3-s:s,seedAssignments:r,drawPosition:i,isFeedRound:f,sideNumber:s}),p=u.sides?.find(t=>t.sideNumber===s),l=o?2*(o-1)+a+1:void 0;return c({sourceDrawPositionRange:l?t?.[l]:void 0,...p,...d})})}({sourceDrawPositionRoundRanges:ht,collectionAssignmentDetail:st,positionAssignments:o,seedAssignments:S,drawPositions:nt,roundPosition:ot,roundProfile:E,roundNumber:at,onlyDefined:Ut,matchUp:F});Object.assign(Pt,ca({sides:t},!0,!0))}if(r&&Pt.sides){if(function({tournamentParticipants:t,hydrateParticipants:e,positionAssignments:n,appliedPolicies:r,drawDefinition:i,participantMap:o,contextProfile:a,matchUpWithContext:s,event:c}){const u=r?.[Eu],d=t=>{const e=o?.[t]?.participant;return e&&Tu({template:u?.participant,source:e})};s.sides.filter(Boolean).forEach(o=>{if(function({side:t,getMappedParticipant:e,tournamentParticipants:n,hydrateParticipants:r,positionAssignments:i,appliedPolicies:o,drawDefinition:a,contextProfile:s,event:c}){if(!t.participantId)return;const u=ca(e(t.participantId)||(n?ju({policyDefinitions:o,participantId:t.participantId,tournamentParticipants:n,internalUse:!0,contextProfile:s}):void 0),void 0,!0);if(!u)return;let d,p,l;if(a?.entries){const e=a.entries.find(e=>e.participantId===t.participantId),n=c?.entries?.find(e=>e.participantId===t.participantId);d=e?.entryStatus||n?.entryStatus,u.entryStatus=d,e?.entryStage&&(p=e.entryStage,u.entryStage=p)}if(t.drawPosition&&i){const e=i.find(e=>e.drawPosition===t.drawPosition);e?.extensions?.some(t=>"luckyAdvancement"===t.name)&&(l=!0,u.luckyAdvancement=!0)}!1===r?Object.assign(t,{participant:{entryStage:p,entryStatus:d,luckyAdvancement:l}}):Object.assign(t,{participant:u})}({side:o,getMappedParticipant:d,tournamentParticipants:t,hydrateParticipants:e,positionAssignments:n,appliedPolicies:r,drawDefinition:i,contextProfile:a,event:c}),o?.participant?.individualParticipantIds?.length&&!o.participant.individualParticipants?.length){const n=o.participant.individualParticipantIds.map(e=>d(e)||(t?ju({policyDefinitions:r,tournamentParticipants:t,internalUse:!0,contextProfile:a,participantId:e}):void 0));!1!==e&&Object.assign(o.participant,{individualParticipants:n})}})}({tournamentParticipants:r,hydrateParticipants:s,positionAssignments:o,appliedPolicies:g,drawDefinition:w,participantMap:v,contextProfile:T,matchUpWithContext:Pt,event:x}),!Pt.matchUpType){const{matchUpType:t}=Mg({matchUp:Pt});t&&Object.assign(Pt,{matchUpType:t})}!function({contextProfile:t,matchUpWithContext:e}){const r=t?.inferGender&&(!e.gender||e.gender===Bi)&&2===e.sides?.length&&e.matchUpType!==is;if(!r)return;const i=e.sides.map(t=>{if(bh(n)(e.matchUpType))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]}});2===i.filter(Boolean).length&&1===M(i).length&&(e.inferredGender=i[0])}({contextProfile:T,matchUpWithContext:Pt})}Pt.tieMatchUps&&function(t){const{matchUpWithContext:e}=t,n=e.matchUpStatus===Sp,r=e.sides?.map(({participant:t,drawPosition:e,sideNumber:n,lineUp:r})=>{const i=t?.participantType===is&&t;return{teamParticipant:i&&Ei({participantRoleResponsibilities:i.participantRoleResponsibilities,participantOtherName:i.participantOtherName,participantName:i.participantName,participantId:i.participantId,teamId:i.teamId}),drawPosition:e,sideNumber:n,lineUp:r}});e.tieMatchUps=e.tieMatchUps.map(i=>{const o=e.matchUpId,a={finishingPositionRange:e.finishingPositionRange,abbreviatedRoundName:t.abbreviatedRoundName,roundNumber:t.roundNumber,roundName:t.roundName};return Og({tieDrawPositions:t.drawPositions,scheduleVisibilityFilters:t.scheduleVisibilityFilters,sourceDrawPositionRanges:t.sourceDrawPositionRanges,sideLineUps:r,drawPositionsRanges:t.drawPositionsRanges,initialRoundOfPlay:t.initialRoundOfPlay,roundNamingProfile:t.roundNamingProfile,additionalContext:a,appliedPolicies:t.appliedPolicies,isCollectionBye:n,usePublishState:t.usePublishState,publishStatus:t.publishStatus,matchUpTieId:o,isRoundRobin:t.isRoundRobin,roundProfile:t.roundProfile,matchUp:i,event:t.event,tournamentParticipants:t.tournamentParticipants,positionAssignments:t.positionAssignments,tournamentRecord:t.tournamentRecord,seedAssignments:t.seedAssignments,participantMap:t.participantMap,contextContent:t.contextContent,scheduleTiming:t.scheduleTiming,contextProfile:t.contextProfile,drawDefinition:t.drawDefinition,scoringActive:t.scoringActive,structure:t.structure,context:t.context})})}({matchUpWithContext:Pt,abbreviatedRoundName:ut,roundNumber:at,roundName:ct,drawPositions:nt,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,drawPositionsRanges:a,initialRoundOfPlay:u,roundNamingProfile:m,appliedPolicies:g,usePublishState:y,publishStatus:D,isRoundRobin:A,roundProfile:E,event:x,tournamentParticipants:r,positionAssignments:o,tournamentRecord:f,seedAssignments:S,participantMap:v,contextContent:U,scheduleTiming:P,contextProfile:T,drawDefinition:w,scoringActive:b,structure:O,context:k});const Tt=2===Pt.sides?.filter(t=>t?.participantId).length,wt=!Pt.winningSide,Dt=b&&Tt&&wt;if(Object.assign(Pt,{readyToScore:Dt,hasContext:!0}),Tt){const{allParticipantsCheckedIn:t,checkedInParticipantIds:e}=Rh({matchUp:Pt});Object.assign(Pt,{allParticipantsCheckedIn:t,checkedInParticipantIds:e})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(t=>delete Pt[t]),Pt}function kg(t){if(!Array.isArray(t.matchUps))return[];const{matchUps:e,excludeMatchUpStatuses:n,hasParticipantsCount:r,isCollectionMatchUp:i,matchUpStatuses:a,hasWinningSide:s,matchUpFormats:c,roundPositions:u,matchUpFormat:d,collectionIds:p,isMatchUpTie:l,roundNumbers:m,matchUpIds:f,roundNames:h,filterMatchUpTypes:g=!0,filterMatchUpIds:I=!0,stageSequences:S,scheduledDates:y,scheduledDate:v,participantIds:U,processContext:P,tournamentIds:T,matchUpTypes:w,structureIds:D,readyToScore:R,courtIds:b,eventIds:N,venueIds:M,drawIds:A,stages:E}=t,C=Array.isArray(U)?U.filter(Boolean):[],O=Array.isArray(a)?a.filter(Boolean):[],k=Array.isArray(n)?n.filter(Boolean):[],F=Array.isArray(E)?E.filter(Boolean):[],x=Array.isArray(S)?S.filter(Boolean):[],_=Array.isArray(p)?p.filter(Boolean):[],L=Array.isArray(h)?h.filter(Boolean):[],B=Array.isArray(m)?m.filter(Boolean):[],V=Array.isArray(u)?u.filter(Boolean):[],G=Array.isArray(f)&&I?f.filter(Boolean):[],j=Array.isArray(w)&&g?w.filter(Boolean):[],q=Array.isArray(b)?b.filter(Boolean):[],W=Array.isArray(M)?M.filter(Boolean):[],$=Array.isArray(c)&&c.filter(Boolean)||"string"==typeof d&&[d]||[],H=Array.isArray(y)&&y.filter(Boolean).length&&y.filter(Boolean)||"string"==typeof v&&v.length&&[v]||[],Y=Array.isArray(T)?T.filter(Boolean):[],K=Array.isArray(N)?N.filter(Boolean):[],Q=Array.isArray(A)?A.filter(Boolean):[],J=Array.isArray(D)?D.filter(Boolean):[];return e.filter(t=>!!function({matchUp:t,readyToScore:e,hasWinningSide:n,isMatchUpTie:r,isCollectionMatchUp:i}){if(e&&!bh(o)(t)&&!t.readyToScore)return!1;if(t.winningSide&&n&&![1,2].includes(t.winningSide))return!1;if(void 0!==r){if(r&&!t.tieMatchUps)return!1;if(!r&&t.tieMatchUps)return!1}if(void 0!==i){if(i&&!t.collectionId)return!1;if(!i&&t.collectionId)return!1}return!0}({matchUp:t,readyToScore:R,hasWinningSide:s,isMatchUpTie:l,isCollectionMatchUp:i})&&(!!function({matchUp:t,targetStages:e,targetStageSequences:n,targetCollectionIds:r,targetRoundNames:i,targetRoundNumbers:o,targetRoundPositions:a,targetMatchUpStatuses:s,excludeTargetMatchUpStatuses:c,targetMatchUpIds:u,targetMatchUpTypes:d,targetMatchUpFormats:p}){if(e.length&&!e.includes(t.stage))return!1;if(n.length&&!n.includes(t.stageSequence))return!1;if(r.length&&(!t.collectionId||!r.includes(t.collectionId)))return!1;if(i.length&&(!t.roundName||!i.includes(t.roundName)))return!1;if(o.length&&(!t.roundNumber||!o.includes(t.roundNumber)))return!1;if(a.length&&(!t.roundPosition||!a.includes(t.roundPosition)))return!1;if(s.length&&(!t.matchUpStatus||!s.includes(t.matchUpStatus)))return!1;if(c.length&&t.matchUpStatus&&c.includes(t.matchUpStatus))return!1;if(u.length&&!u.includes(t.matchUpId))return!1;if(d.length&&(!t.matchUpType||!z(d,t.matchUpType)))return!1;if(p.length&&(!t.matchUpFormat||!p.includes(t.matchUpFormat)))return!1;return!0}({matchUp:t,targetStages:F,targetStageSequences:x,targetCollectionIds:_,targetRoundNames:L,targetRoundNumbers:B,targetRoundPositions:V,targetMatchUpStatuses:O,excludeTargetMatchUpStatuses:k,targetMatchUpIds:G,targetMatchUpTypes:j,targetMatchUpFormats:$})&&(!!function({matchUp:t,targetScheduledDates:e,targetCourtIds:n,targetVenueIds:r}){if(e?.length){const{scheduledTime:n}=eg({matchUp:t}),{scheduledDate:r}=ng({matchUp:t}),i=Lo(n)||r;if(!e.some(t=>Ko(t,i)))return!1}if(n.length){const{courtId:e}=function({timeStamp:t,schedule:e,matchUp:n}){const{itemValue:r,timeStamp:i}=tg({timeItems:n?.timeItems??[],itemType:th});return!e||i&&t&&new Date(i).getTime()>new Date(t).getTime()?{courtId:r}:e}({matchUp:t}),{allocatedCourts:r}=function({timeStamp:t,schedule:e,matchUp:n}){const{itemValue:r,timeStamp:i}=tg({timeItems:n?.timeItems??[],itemType:Zf});return!e||i&&t&&new Date(i).getTime()>new Date(t).getTime()?{allocatedCourts:ca(r,!1,!0)}:e}({matchUp:t}),i=r?.map(({courtId:t})=>t);if(!n.filter(Boolean).includes(e)||i?.includes(e))return!1}if(r.length){const{venueId:e}=function({timeStamp:t,schedule:e,matchUp:n}){const{itemValue:r,timeStamp:i}=tg({timeItems:n?.timeItems??[],itemType:Xf});return!e||i&&t&&new Date(i).getTime()>new Date(t).getTime()?{venueId:r}:e}({matchUp:t});if(!r.filter(Boolean).includes(e))return!1}return!0}({matchUp:t,targetScheduledDates:H,targetCourtIds:q,targetVenueIds:W})&&!(P&&!function({matchUp:t,targetTournamentIds:e,targetEventIds:n,targetDrawIds:r,targetStructureIds:i,targetParticipantIds:o,hasParticipantsCount:a}){if(e.length&&!e.includes(t.tournamentId))return!1;if(n.length&&!n.includes(t.eventId))return!1;if(r.length&&!r.includes(t.drawId))return!1;if(i.length&&!i.includes(t.structureId))return!1;const s=t.sides?.map(({participantId:t})=>t).filter(Boolean)??[];if(a&&s.length<a)return!1;if(o.length){if(!o.some(t=>s.includes(t)))return!1}return!0}({matchUp:t,targetTournamentIds:Y,targetEventIds:K,targetDrawIds:Q,targetStructureIds:J,targetParticipantIds:C,hasParticipantsCount:r})))))}function Fg(t){const{provisionalPositioning:e,tournamentRecord:n,contextFilters:r,matchUpFilters:i,contextProfile:o,drawDefinition:a,context:s={},structure:c,inContext:u,event:p}=t;let{seedAssignments:l,contextContent:m,exitProfiles:f,matchUpsMap:h}=t,g={},I={};if(!c)return{collectionPositionMatchUps:g,error:jt,roundMatchUps:I,matchUps:[]};const S=Array.isArray(i?.eventIds)?i?.eventIds.filter(Boolean):[],y=Array.isArray(i?.structureIds)?i?.structureIds.filter(Boolean):[],v=Array.isArray(i?.drawIds)?i?.drawIds.filter(Boolean):[],U=!s?.eventId||!S?.length&&!r?.eventIds?.filter(Boolean).length||S?.includes(s.eventId)||r?.eventIds?.includes(s.eventId),P=!y?.length||y.includes(c.structureId),T=!a||!v?.length||v.includes(a.drawId);if(!U||!P||!T)return{collectionPositionMatchUps:g,roundMatchUps:I,matchUps:[]};o&&!m&&(m=zm({tournamentRecord:n,contextProfile:o,drawDefinition:a}));const{appliedPolicies:w}=xd({drawDefinition:a}),D={...t.tournamentAppliedPolicies,...w,...t.policyDefinitions},R=D?.scoring?.structures,b=c.stage&&R?.stage?.[c.stage],N=c.stageSequence&&b?.stageSequence?.[c.stageSequence],A=D?.scoring?.requireAllPositionsAssigned||b?.requireAllPositionsAssigned||N?.requireAllPositionsAssigned;h??=bf({drawDefinition:a,structure:c});const{positionAssignments:E,allPositionsAssigned:C}=ul({structure:c}),O=!A||C,{seedAssignments:k}=Tf({provisionalPositioning:e,drawDefinition:a,structure:c});l=l??k;const{structureId:F}=c;f=f||a&&Gf({drawDefinition:a}).exitProfiles;const x=f?.[F],_=x?.length&&(x[0].split("-").map(t=>Number.parseInt(t)).reduce((t,e)=>t+e,0)||0),B=!!c.structures;let V=Nf({matchUpsMap:h,structureId:F,inContext:u});const G=D?.[Au],j=Yf({roundNamingPolicy:G,drawDefinition:a,structure:c,matchUps:V}),{roundNamingProfile:W,roundProfile:$}=j;if(I=j?.roundMatchUps??[],i){const t=new Set(V.filter(t=>Array.isArray(t.tieMatchUps)).map(t=>t.matchUpId));V=kg({matchUps:t.size?V.filter(e=>!t.has(e.matchUpId)):V,...i,filterMatchUpTypes:!1,filterMatchUpIds:!1}).concat(t.size?V.filter(e=>t.has(e.matchUpId)):[])}return u?V=function({positionAssignments:t,initialRoundOfPlay:e,roundNamingProfile:n,tournamentRecord:r,appliedPolicies:i,seedAssignments:o,contextContent:a,contextProfile:s,drawDefinition:c,contextFilters:u,scoringActive:p,isRoundRobin:l,roundProfile:m,matchUpsMap:f,structureId:h,structure:g,context:I,params:S,event:y,matchUps:v}){const{sourceDrawPositionRanges:U}=function({drawDefinition:t,structureId:e,matchUpsMap:n}){const r=dl({drawDefinition:t,structureId:e},[yc,bc]);if(r.error)return r;const{structure:i}=ol({drawDefinition:t,structureId:e});if(i?.stage!==ps)return{error:Zt,info:"Structure is not CONSOLATION stage"};const{links:o}=t,a=o?.filter(t=>t.target.structureId===e)??[],s=a?.reduce((t,e)=>{const{structureId:n}=e.source;return t.includes(n)?t:t.concat(n)},[])??[],c=Object.assign({},...s.map(t=>{const e=Bf({matchUps:Nf({structureId:t,matchUpsMap:n})}).roundProfile;return{[t]:e}})),u=Nf({matchUpsMap:n,structureId:e}),{roundProfile:d}=Bf({matchUps:u}),p={};return a?.forEach(t=>{const{structureId:e,roundNumber:n}=t.source,{feedProfile:r,groupedOrder:i,positionInterleave:o,roundNumber:a}=t.target,s=c[e],u=s[1]?.drawPositions,l=s[n],m=l?.matchUpsCount;if(!m)return;const f=m?u.length/m:0,h=u.length/f;let g=u.slice();const I=xf({roundPositionsCount:h,groupedOrder:i}),S=I?.length||1;if(S<=h){const t=q(g,u.length/S);r===Ms&&t.forEach(t=>t.reverse()),g=I?.length&&I?.map(e=>t[e-1]).flat()||t.flat()}let y=q(g,f);if(o){const t=L(0,o.interleave).map(()=>{}),e=L(0,o.offset).map(()=>{});y=y.map(e=>[e,...t]),y.unshift(e),y=y.flat(1);const n=y.length-o.offset;y=y.slice(0,n)}p[a]||(p[a]={});const v=d?.[a],U=v?.feedRound?2:1;y.forEach((t,e)=>{const n=1+e*U;p[a][n]||(p[a][n]=Vf(t))})}),{sourceDrawPositionRanges:p}}({drawDefinition:c,matchUpsMap:f,structureId:h}),P=c?function({drawDefinition:t,roundProfile:e,structureId:n,matchUpsMap:r}){const i=dl({drawDefinition:t,structureId:n},[yc,bc]);if(i.error)return i;if(!e){const t=Nf({matchUpsMap:r,structureId:n});if(({roundProfile:e}=Bf({matchUps:t})),!e)return{error:Ae}}const o=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,a=Object.keys(e),s=Object.assign({},...(a??[]).map(t=>{const n=e?.[t]?.matchUpsCount,r=e?.[1]?.drawPositions??[],i=q(r,r.length/n),s=i.map(Vf),c=i.map(t=>t.map(t=>t-o)).map(Vf),u=a.map(r=>{if(r>t)return;const i=e?.[r]?.drawPositions??[];return q(i,i.length/n)}).filter(Boolean),p=L(0,n).map(t=>u.map(e=>e[t]).flat().filter(Boolean).sort(d)).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(Vf).join(", ");var e}),m=Object.assign({},...L(0,n).map(t=>{const e=t+1;return{[e]:{firstRoundDrawPositionsRange:s[t],firstRoundOffsetDrawPositionsRange:c[t],possibleDrawPositions:p[t],drawPositionsRange:l[t]}}}));return{[t]:m}}));return{drawPositionsRanges:s}}({drawDefinition:c,roundProfile:m,matchUpsMap:f,structureId:h}).drawPositionsRanges:void 0;let T=S.tournamentParticipants,w=S.participantMap;T?.length||w||!r||({participants:T=[],participantMap:w}=Bm({participantsProfile:S.participantsProfile,useParticipantMap:S.useParticipantMap,policyDefinitions:S.policyDefinitions,tournamentRecord:r,contextProfile:s,inContext:!0}));let D=v.map(u=>Og({scheduleVisibilityFilters:S.scheduleVisibilityFilters,hydrateParticipants:S.hydrateParticipants,afterRecoveryTimes:S.afterRecoveryTimes,usePublishState:S.usePublishState,scheduleTiming:S.scheduleTiming,publishStatus:S.publishStatus,sourceDrawPositionRanges:U,tournamentParticipants:T,positionAssignments:t,drawPositionsRanges:P,initialRoundOfPlay:e,roundNamingProfile:n,tournamentRecord:r,appliedPolicies:i,seedAssignments:o,contextContent:a,participantMap:w,contextProfile:s,drawDefinition:c,scoringActive:p,isRoundRobin:l,roundProfile:m,structure:g,context:I,matchUp:u,event:y}));D=xg(D),u&&(D=kg({processContext:!0,...u,matchUps:D}));return D}({positionAssignments:E,initialRoundOfPlay:_,roundNamingProfile:W,tournamentRecord:n,appliedPolicies:D,seedAssignments:l,contextContent:m,contextProfile:o,drawDefinition:a,contextFilters:r,scoringActive:O,isRoundRobin:B,roundProfile:$,matchUpsMap:h,structureId:F,structure:c,context:s,params:t,event:p,matchUps:V}):(V=xg(V),o?.withCompetitiveness&&(V=function({policyDefinitions:t,tournamentRecord:e,drawDefinition:n,structure:r,matchUps:i,event:o}){const a=Mf({policyDefinitions:t,tournamentRecord:e,drawDefinition:n,structure:r,event:o});return i.map(t=>{if(t.competitiveProfile||!t.winningSide)return t;const e=Ff({profileBands:a,matchUp:t});return e.error?t:{...t,competitiveProfile:e}})}({policyDefinitions:t.policyDefinitions,tournamentRecord:n,drawDefinition:a,structure:c,matchUps:V,event:p}))),i&&(V=kg({matchUps:V,...i,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(i?.matchUpTypes||i?.matchUpIds)&&(V=kg({matchUpTypes:i.matchUpTypes,matchUpIds:i.matchUpIds,matchUps:V})),(i?.matchUpTypes||i?.matchUpIds||u)&&(I=Bf({matchUps:V}).roundMatchUps??[]),Rf({drawDefinition:a,structure:c,event:p})?.tieFormat&&({collectionPositionMatchUps:g}=function({matchUps:t}){const e=t.reduce((t,e)=>!e.collectionPosition||t.includes(e.collectionPosition)?t:t.concat(e.collectionPosition),[]).map(e=>({[e]:t.filter(t=>t.collectionPosition===e)}));return{collectionPositionMatchUps:Object.assign({},...e)}}({matchUps:V})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:B,roundProfile:$,matchUpsMap:h,matchUps:V}}function xg(t){const e=t?.filter(t=>Array.isArray(t.tieMatchUps));let n=t;return e.forEach(t=>{n=n.concat(...t.tieMatchUps)}),n}function _g({matchUp:t}){return!!t&&(_p.includes(t?.matchUpStatus)||t?.winningSide)}function Lg({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:n,tournamentParticipants:r,hydrateParticipants:i,afterRecoveryTimes:o,policyDefinitions:s,tournamentRecord:c,usePublishState:u,matchUpFilters:d,contextFilters:p,contextContent:l,participantMap:m,scheduleTiming:f,publishStatus:h,contextProfile:g,drawDefinition:I,exitProfiles:S,matchUpsMap:y,structureId:v,inContext:U,structure:P,context:T,event:w}){!P&&v&&({structure:P}=ol({drawDefinition:I,structureId:v}));const D=Fg({tournamentAppliedPolicies:n,scheduleVisibilityFilters:e,tournamentParticipants:r,hydrateParticipants:i,afterRecoveryTimes:o,policyDefinitions:s,tournamentRecord:c,usePublishState:u,matchUpFilters:d,contextFilters:p,contextContent:l,participantMap:m,scheduleTiming:f,publishStatus:h,contextProfile:g,drawDefinition:I,exitProfiles:S,matchUpsMap:y,structure:P,inContext:U,context:T,event:w}),R=[],b=[],N=[],M=[],A=[];if(D.error)return D;const{matchUps:E}=D,{assignedPositions:C}=ul({structure:P}),O=C?.filter(t=>t.participantId).map(t=>t.drawPosition);let k;return E.filter(t=>{const e=1===d?.matchUpTypes?.length&&d.matchUpTypes[0]===a;return!(t.matchUpType!==a&&e)}).forEach(e=>{if(e.matchUpStatus===gp)return void R.push(e);e.matchUpType===a&&(k=!0);const n=Boolean(e.collectionId),r=n&&e.sides?.every(t=>t.participantId),i=!n&&2===e.drawPositions?.filter(Boolean).length,o=!n&&e.drawPositions?.every(t=>O?.includes(t)),s=C?.filter(t=>t.bye).map(t=>t.drawPosition),c=!n&&e.drawPositions?.find(t=>s?.includes(t)),u=Bp.includes(e.matchUpStatus)&&(r||i&&(!t||o));return c?A.push(e):_g({matchUp:e})?b.push(e):u?N.push(e):M.push(e)}),{includesTeamMatchUps:k,abandonedMatchUps:R,completedMatchUps:b,upcomingMatchUps:N,pendingMatchUps:M,byeMatchUps:A,structure:P}}function Bg({finishingPositions:t,linkCondition:e,linkType:n,source:r}){const i=r.find(r=>{const i=!r.source?.finishingPositions||!t||j(t,r.source?.finishingPositions);return e===r.linkCondition&&i&&r.linkType===n});return[Es,Cs].includes(i?.linkType)&&!i?.source?.roundNumber?Ci({result:{error:sr},stack:"getTargetLink",context:i}):i}function Vg({drawDefinition:t,structureId:e,roundNumber:n}){const r=dl({drawDefinition:t,structureId:e},[yc,bc]);if(r.error)return r;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 Gg({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:n,drawDefinition:r,targetLink:i}){if(!i)return{error:_t};const{target:{structureId:o,feedProfile:a,groupedOrder:s,roundNumber:c,positionInterleave:u}}=i,{structure:d}=ol({drawDefinition:r,structureId:o}),{positionAssignments:p}=cl({structure:d}),l=e?.filter(t=>t.structureId===d?.structureId),m=l.filter(t=>t.roundNumber===c&&!t.matchUpTieId),f=m.length,h=L(1,f+1),g=f/t;let I=Math.ceil(g*n),S=1-n%2;if(u?.interleave&&.5!==g){const t=n+(u.offset+(n-1)*u.interleave);I=Math.ceil(t/2),S=1-t%2}let y=h,v=h[I-1];const U=xf({roundPositionsCount:h.length,groupedOrder:s}),P=U?.length||1;if(P<=h.length){const t=q(h,f/P);a===Ms&&t.forEach(t=>t.reverse()),y=U?.length&&U?.map(e=>t[e-1]).flat()||y}a===Ns?v=y[I-1]:a===Ms?((!U?.length||P>h.length)&&(I=m.length+1-I),v=y[I-1]):a===bs&&$r()&&console.log(fr,{feedProfile:a});const T=v&&m.reduce((t,e)=>e.roundPosition===v?e:t,void 0);let w;T?.feedRound?(S=0,w=Math.min(...(T.drawPositions??[]).filter(Boolean))):w=2===T?.drawPositions?.length&&T?.drawPositions[S];const D=p?.find(({drawPosition:t})=>t===w);if(D){if(dp({element:D,attribute:"disableLinks",name:sd}))return{disabledDrawPosition:w}}return{matchUp:T,targetDrawPosition:w,matchUpDrawPositionIndex:S}}function jg({inContextDrawMatchUps:t=[],useTargetMatchUpIds:e,inContextMatchUp:n,drawDefinition:r,matchUpId:i}){let o=n;t.length&&!o&&(o=t.find(t=>t.matchUpId===i));const{structure:a}=ol({structureId:o?.structureId,drawDefinition:r}),s=a?.finishingPosition;return s===lc?function({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:r,matchUp:i}){const{winnerMatchUpId:o,loserMatchUpId:a}=i,{links:s}=function({drawDefinition:t,roundNumber:e,structureId:n}){const r=dl({drawDefinition:t,structureId:n},[yc,bc]);if(r.error)return r;const{links:i}=Vg({drawDefinition:t,structureId:n});return{links:{source:i.source.reduce((t,n)=>n.source.roundNumber&&n.source.roundNumber!==e?t:t.concat(n),[]),target:i.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=Bg({source:c,linkType:Es}),d=Bg({linkCondition:Os,linkType:Cs,source:c});let p=Bg({source:c,linkType:Cs});const l=d&&p;p||(p=d);const m=u?.target?.feedProfile,f=p?.target?.feedProfile,h=d?.target?.feedProfile;let g,I,S,y,v,U,P,T,w,D;if(e&&(o||a)&&(P=o&&m!==Rs&&t.find(({matchUpId:t})=>t===o),y=a&&f!==Rs&&t.find(({matchUpId:t})=>t===a),P||y))return{matchUp:i,targetLinks:{loserTargetLink:p,winnerTargetLink:u},targetMatchUps:{loserMatchUp:y,winnerMatchUp:P}};const{roundPosition:R}=i;D=D||t.filter(t=>t.structureId===r.structureId);const b=D.reduce((t,e)=>e.roundNumber!==i.roundNumber||e.matchUpTieId?t:t+1,0);p&&!y&&f!==Rs&&({matchUpDrawPositionIndex:U,targetDrawPosition:v,matchUp:y}=Gg({targetLink:p,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:R,drawDefinition:n}));l&&h!==Rs&&({matchUpDrawPositionIndex:S,targetDrawPosition:I,matchUp:g}=Gg({targetLink:d,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:R,drawDefinition:n}));u&&!P&&m!==Rs&&({matchUpDrawPositionIndex:w,targetDrawPosition:T,matchUp:P}=Gg({targetLink:u,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:R,drawDefinition:n}));P||(D=D||t.filter(t=>t.structureId===r.structureId),({matchUp:P}=function({structureMatchUps:t,matchUp:e}){const{roundNumber:n,roundPosition:r}=e,i=t.filter(t=>t.roundNumber===n&&!t.matchUpTieId),o=t.filter(t=>t.roundNumber===n+1&&!t.matchUpTieId);if(o.length){let t;return o.length===i.length?t=o.find(t=>t.roundPosition===r):o.length===i.length/2&&(t=o.find(t=>t.roundPosition===Math.ceil(r/2))),{matchUp:t}}return{message:"no progression found"}}({structureMatchUps:D,matchUp:i})));return Ei({matchUp:i,targetLinks:{loserTargetLink:p,winnerTargetLink:u,byeTargetLink:d},targetMatchUps:{winnerMatchUpDrawPositionIndex:w,loserMatchUpDrawPositionIndex:U,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:T,loserTargetDrawPosition:v,byeTargetDrawPosition:I,winnerMatchUp:P,loserMatchUp:y,byeMatchUp:g},targetMatchUpIds:!(!o&&!a)})}({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:a,matchUp:o}):function({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}({matchUp:o})}function qg({drawDefinition:t,inContextDrawMatchUps:e}){const n={};return e.forEach(r=>{const{matchUpId:i,structureId:o,drawPositions:a=[]}=r,{structure:s}=ol({drawDefinition:t,structureId:o});s?.finishingPosition===pc?function({inContextMatchUp:t,structure:e,drawPositions:n}){const{roundNumber:r}=t,i=r&&p(r)+1,o=e.matchUps??[],{roundMatchUps:a}=Bf({matchUps:o});if(i&&a?.[i]){const r=[...n].sort(d).map((t,n)=>{const r=a[i].find(e=>e.drawPositions?.includes(t));return{matchUpId:r?.matchUpId,roundNumber:i,schedule:r?.schedule,sideNumber:n+1,structureName:e.structureName}});Object.assign(t,{sidesTo:r})}}({inContextMatchUp:r,structure:s,drawPositions:a}):function({scheduleConflictMatchUpIds:t,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:r,matchUpId:i}){const o=jg({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:r,matchUpId:i});let{winnerMatchUp:a}=o.targetMatchUps;const{loserMatchUp:s}=o.targetMatchUps;!n.winnerMatchUpId&&a&&(n.winnerMatchUpId=a.matchUpId);!n.loserMatchUpId&&s&&(n.loserMatchUpId=s.matchUpId);const c=Hg({upcomingMatchUp:a});let u=Hg({upcomingMatchUp:s});if(n.matchUpStatus!==Sp&&s?.matchUpStatus===Sp){const{matchUp:t}=$g({matchUp:s,drawDefinition:r,inContextDrawMatchUps:e})??{};u=t&&Hg({upcomingMatchUp:t})||u}const d=n.schedule?.timeAfterRecovery;d&&(Wg({scheduleConflictMatchUpIds:t,inContextMatchUp:n,timeAfterRecovery:d,upcomingTo:c}),Wg({scheduleConflictMatchUpIds:t,inContextMatchUp:n,timeAfterRecovery:d,upcomingTo:u}));Object.assign(n,{winnerTo:c,loserTo:u}),n.drawPositions?.filter(Boolean).length&&function({inContextDrawMatchUps:t,inContextMatchUp:e,winnerMatchUp:n,loserMatchUp:r,targetData:i}){const o=i.targetLinks?.loserTargetLink,a=o?.linkCondition===Os,s=(c=e,c?.sides?.map(({participant:t,participantId:e,qualifier:n})=>t||e&&{participantId:e}||n&&{qualifier:n}).filter(Boolean)??[]);var c;if(!s.length)return;const u=Jp(n?.sides),d=Jp(r?.sides),p=s.find(({participantId:t})=>u.includes(t))?[]:s,l=s.find(({participantId:t})=>d.includes(t))?[]:s;r&&a&&l.length<2&&l.push({bye:!0,tbd:!0});p?.length&&n&&(!i.targetMatchUpIds&&n&&(n=t.find(({matchUpId:t})=>t===n.matchUpId)),n.potentialParticipants??=[],n.potentialParticipants.push(p));l?.length&&r&&(i.targetMatchUpIds||(n=t.find(({matchUpId:t})=>t===r.matchUpId)),r.potentialParticipants||(r.potentialParticipants=[]),r.potentialParticipants.push(l))}({inContextDrawMatchUps:e,inContextMatchUp:n,winnerMatchUp:a,loserMatchUp:s,targetData:o})}({scheduleConflictMatchUpIds:n,inContextDrawMatchUps:e,inContextMatchUp:r,drawDefinition:t,matchUpId:i})}),Object.keys(n).length&&e.forEach(t=>{Object.keys(n).includes(t.matchUpId)&&(t.schedule.scheduleConflict=n[t.matchUpId])}),{scheduleConflictMatchUpIds:n}}function Wg({scheduleConflictMatchUpIds:t,inContextMatchUp:e,timeAfterRecovery:n,upcomingTo:r}){if(r?.schedule?.scheduledTime){Fo(r.schedule.scheduledTime)<Fo(n)&&(t[r.matchUpId]=e.matchUpId,r.schedule.scheduleConflict=e.matchUpId)}}function $g({matchUp:t,drawDefinition:e,inContextDrawMatchUps:n}){const{matchUpId:r,matchUpStatus:i,structureId:o}=t??{};if(!t||!o||t?.matchUpStatus===Ap)return{matchUp:t};if(i===Sp){let i;if(t.winnerMatchUpId)i=n.find(({matchUpId:e})=>e===t.winnerMatchUpId);else{const t=jg({inContextDrawMatchUps:n,drawDefinition:e,matchUpId:r});({winnerMatchUp:i}=t?.targetMatchUps??{})}return $g({matchUp:i,drawDefinition:e,inContextDrawMatchUps:n})}return{matchUp:void 0}}function Hg(t){if(t?.upcomingMatchUp)return(({matchUpId:t,structureId:e,schedule:n,roundNumber:r,roundPosition:i,structureName:o})=>({matchUpId:t,structureId:e,schedule:n,roundNumber:r,roundPosition:i,structureName:o}))(t.upcomingMatchUp)}function zg(t){Object.assign(t,{requireParticipants:!1});const e=Yg(t);if(e.error)return Ci({result:e,stack:"getAllDrawMatchUps"});const{abandonedMatchUps:n,completedMatchUps:r,upcomingMatchUps:i,pendingMatchUps:o,byeMatchUps:a,matchUpsMap:s}=e;return{matchUps:(n??[]).concat(...r??[],...i??[],...o??[],...a??[]),matchUpsMap:s}}function Yg(t){if(!t?.drawDefinition)return{error:st};let{tournamentParticipants:e,contextContent:n,matchUpsMap:r}=t;const{scheduleVisibilityFilters:i,tournamentAppliedPolicies:o,requireParticipants:a,participantsProfile:s,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:d,usePublishState:p,contextFilters:l,matchUpFilters:m,scheduleTiming:f,participantMap:h,publishStatus:g,contextProfile:I,drawDefinition:S,nextMatchUps:y,inContext:v,context:U,event:P}=t;let T,w=[],D=[],R=[],b=[],N=[];I&&!n&&(n=zm({policyDefinitions:u,tournamentRecord:d,contextProfile:I,event:P})),!e?.length&&d&&(e=d?.participants,(v||s?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:T}=Pm({participants:e,participantsProfile:s})));const{structures:M}=al({drawDefinition:S});if(!M)return{error:Vt};r||(r=bf({drawDefinition:S}));const A=S&&Gf({drawDefinition:S}).exitProfiles;M.forEach(s=>{const{byeMatchUps:T=[],pendingMatchUps:M=[],upcomingMatchUps:E=[],completedMatchUps:C=[],abandonedMatchUps:O=[]}=Lg({matchUpFilters:y?void 0:m,contextFilters:y?void 0:l,inContext:v||y||l,hydrateParticipants:t.hydrateParticipants,tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,tournamentParticipants:e,requireParticipants:a,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:d,usePublishState:p,contextContent:n,participantMap:h,scheduleTiming:f,publishStatus:g,contextProfile:I,drawDefinition:S,exitProfiles:A,matchUpsMap:r,structure:s,context:U,event:P});w=w.concat(...O),D=D.concat(...C),R=R.concat(...E),b=b.concat(...M),N=N.concat(...T)});const E=t=>m||y||l?(m&&(t=kg({matchUps:t,...m})),l&&(t=kg({matchUps:t,...l,processContext:!0})),t):t,C={abandonedMatchUps:E(w),completedMatchUps:E(D),upcomingMatchUps:E(R),pendingMatchUps:E(b),byeMatchUps:E(N),matchUpsMap:r,...Y,groupInfo:T};if(y){const t="object"==typeof y||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:e,completed:n,upcoming:r,pending:i,bye:o}=t;qg({inContextDrawMatchUps:[].concat(...(e&&w)??[],...(n&&D)??[],...(r&&R)??[],...(i&&b)??[],...(o&&N)??[]),drawDefinition:S})}return C}function Kg(t){let{participants:e=[],contextContent:n,participantMap:r}=t;const{scheduleVisibilityFilters:i,tournamentAppliedPolicies:o,participantsProfile:a,afterRecoveryTimes:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:d,usePublishState:p,contextFilters:l,matchUpFilters:m,contextProfile:f,nextMatchUps:h,inContext:g,context:I,event:S}=t;if(!S)return{error:Ht};const{eventId:y,eventName:v,endDate:U,eventType:P,category:T,gender:w,matchUpFormat:D}=S??{},R={...I,...Ei({indoorOutDoor:S.indoorOutdoor??d?.indoorOutdoor,surfaceCategory:S.surfaceCategory??d?.surfaceCategory,endDate:S.endDate??d?.endDate,tournamentId:d?.tournamentId,matchUpFormat:D,eventName:v,eventType:P,category:T,eventId:y,gender:w})};let b;if(U&&(R.endDate=U),f&&!n&&(n=zm({policyDefinitions:c,tournamentRecord:d,contextProfile:f,event:S})),!e?.length&&!r&&d){const t=Bm({participantsProfile:a,useParticipantMap:u,tournamentRecord:d,contextProfile:f,inContext:g});r=t.participantMap,e=t.participants??[],b=t.groupInfo}const N=S.drawDefinitions??[],M=Jm({tournamentRecord:d,event:S}).scheduleTiming;return{matchUps:N.flatMap(t=>{const{matchUps:u}=zg({tournamentParticipants:e,tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,context:R,participantsProfile:a,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:d,usePublishState:p,contextFilters:l,contextProfile:f,drawDefinition:t,contextContent:n,matchUpFilters:m,participantMap:r,scheduleTiming:M,nextMatchUps:h,inContext:g,event:S});return u??[]}),groupInfo:b}}function Qg(t){const e=fu(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:rt};let{participantMap:n,participants:r}=t;const{scheduleVisibilityFilters:i,participantsProfile:o,afterRecoveryTimes:a,useParticipantMap:s,policyDefinitions:c,tournamentRecord:u,inContext:d=!0,usePublishState:p,contextProfile:l,matchUpFilters:m,contextFilters:f,nextMatchUps:h,context:g}=t,I=t.tournamentId??u.tournamentId,S=u?.events??[];r||({participants:r,participantMap:n}=Bm({participantsProfile:o,useParticipantMap:s,tournamentRecord:u,contextProfile:l,inContext:d}));const{appliedPolicies:y}=xd({tournamentRecord:u}),v={...g,tournamentId:I,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},U=zm({policyDefinitions:c,tournamentRecord:u,contextProfile:l});return{matchUps:S.flatMap(t=>(v.eventDrawsCount=t.drawDefinitions?.length??0,Kg({context:v,scheduleVisibilityFilters:i,tournamentAppliedPolicies:y,participantsProfile:o,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:u,usePublishState:p,contextContent:U,contextFilters:f,contextProfile:l,matchUpFilters:m,participantMap:n,nextMatchUps:h,participants:r,inContext:d,event:t}).matchUps??[])).concat(...u.matchUps??[])}}function Jg({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:n,tournamentRecords:r,policyDefinitions:i,usePublishState:o,matchUpFilters:a,contextFilters:s,nextMatchUps:c,inContext:u}){if("object"!=typeof r||!Object.keys(r).length)return{error:nt};const d=Object.keys(r).map(d=>{const p=r[d];return Qg({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:n,policyDefinitions:i,tournamentRecord:p,usePublishState:o,matchUpFilters:a,contextFilters:s,nextMatchUps:c,inContext:u}).matchUps??[]}).flat();return{...Y,matchUps:d}}function Xg(t,e){return function(t,e){return(hs[t?.stage]||0)-(hs[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 Zg(t){let{participants:e,participantMap:n,contextContent:r}=t;const{scheduleVisibilityFilters:i,tournamentAppliedPolicies:o,participantsProfile:a,afterRecoveryTimes:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:d,matchUpFilters:p,contextFilters:l,contextProfile:m,drawDefinition:f,nextMatchUps:h,inContext:g,context:I,event:S}=t,{eventId:y,eventName:v,endDate:U,eventType:P,category:T,gender:w,matchUpFormat:D}=S??{},R={...I,surfaceCategory:S?.surfaceCategory??d?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??d?.indoorOutdoor,matchUpFormat:D,eventType:P,eventName:v,category:T,eventId:y,endDate:U,gender:w};let b;e?.length||n||!d||({participants:e=[],participantMap:n,groupInfo:b}=Bm({participantsProfile:a,useParticipantMap:u,tournamentRecord:d,contextProfile:m,inContext:g})),m&&!r&&(r=zm({policyDefinitions:c,tournamentRecord:d,contextProfile:m,drawDefinition:f,event:S}));return{...zg({context:R,tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,tournamentParticipants:e,participantsProfile:a,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:d,drawDefinition:f,contextContent:r,contextFilters:l,contextProfile:m,matchUpFilters:p,participantMap:n,nextMatchUps:h,inContext:g,event:S}),groupInfo:b}}const tI=t=>e=>t&&"object"==typeof e?Array.isArray(t)&&t.map(t=>({[t]:Bd({element:e,accessor:t})?.value}))||"object"==typeof t&&Object.keys(t).map(t=>({[t]:Bd({element:e,accessor:t})?.value}))||("string"==typeof t&&Bd({element:e,accessor:t}))?.value:void 0,eI=tI;function nI({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:n,roundsCount:r,roundLimit:i,matchUps:o,lucky:a,fmlc:s}){if(!Lf(o))return[];const{roundProfile:c,roundNumbers:u=[]}=Bf({interpolate:!0,matchUps:o});r=r??Math.max(...u,0);const d=i?r-i:0,p=d&&c?.[r-d]?.matchUpsCount,l=c&&Object.values(c).map(eI("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,o=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=L(f,a?f+2*o:p+f+1),g=p+1-o,I=m(h.slice(g)),S=m(h.slice(0,g),!0);return u.finishingPositionRange={loser:I,winner:S},{[e]:u}})),h=$r({finishingRound:!0});return o.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}),o}function rI({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:n}){if(!e)return{error:st};const r={loserMatchUpIds:{},winnerMatchUpIds:{}};t||({matchUps:t,matchUpsMap:n}=zg({inContext:!0,drawDefinition:e,matchUpsMap:n}));const i=n?.drawMatchUps.some(t=>t.finishingPositionRange);if(!i&&1===e?.structures?.length&&!e?.structures[0].structures){nI({matchUps:n?.drawMatchUps??[]})}return(t??[]).filter(({collectionId:t})=>!t).forEach(i=>{const{matchUpId:o,structureId:a}=i,s=jg({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:o}),{winnerMatchUp:c,loserMatchUp:u}=s.targetMatchUps,d=c?.matchUpId,p=u?.matchUpId,l=Nf({matchUpsMap:n,structureId:a}).find(t=>t.matchUpId===o);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 iI(t){let e=im(t);const n=t.matchUps??[];let r=t.drawIds??[];const{includeParticipantDependencies:i,tournamentRecord:o,drawDefinition:a}=t;if(!Array.isArray(n))return{error:Ie};if(!Array.isArray(r))return{error:bt};const s=t.matchUpIds?.length?t.matchUpIds:n.map(t=>t.matchUpId);if(!Array.isArray(s))return{error:he};const c={},u={},d={},p={};o&&!Object.keys(e).length&&(e={[o.tournamentId]:o});const l=Object.values(e),m=l.reduce((t,e)=>t.concat(e.events??[]).map(t=>(t.drawDefinitions??[]).map(t=>t.links??[])).flat(1/0),[]),f=m.filter(({linkType:t})=>t===As);let h=n;f.length&&(h=Jg({nextMatchUps:!0,tournamentRecords:e}).matchUps,function({positionLinks:t,sourceStructureIdMap:e,positionDependencies:n,matchUps:r}){const i=t.reduce((t,n)=>{const r=n.source?.structureId,i=n.target?.structureId;return r&&i&&(e[i]=r),r&&!t.includes(r)&&t.push(r),t},[]);for(const t of i)n[t]=[];for(const t of r??[]){const e=t.containerStructureId||t.structureId;i.includes(e)&&n[e].push(t.matchUpId)}}({positionLinks:f,sourceStructureIdMap:d,positionDependencies:c,matchUps:h}));const g=t=>{u[t]||(u[t]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},p[t]=[])},I=(t,e)=>{u[t].matchUpIds.forEach(t=>{u[e].matchUpIds.push(t)}),u[e].matchUpIds.push(t),u[t].dependentMatchUpIds.push(e),i&&u[t].participantIds.forEach(t=>u[e].participantIds.push(t))},S=t=>{const e=Object.keys(c).length;for(const n of t??[]){const{matchUpId:t,winnerMatchUpId:r,loserMatchUpId:o}=n;if(!s.length||s.includes(t)){if(g(t),i){const{individualParticipantIds:e}=rm(n);u[t].participantIds=e}r&&(g(r),I(t,r),p[r].push(t)),o&&(g(o),I(t,o),p[o].push(t)),u[t].sources.push(p[t]);const a=p[t].map(t=>u[t].sources[0]).flat(),s=p[t].map(t=>u[t].sources[1]).flat();if(u[t].sources.push(a,s),e){const e=n.containerStructureId||n.structureId,r=d[e];if(c[r])for(const e of c[r])g(e),I(e,t),p[e].push(t)}}}};if(a)rI({drawDefinition:a}),h?.length||(h=Zg({drawDefinition:a}).matchUps),S(h);else{h?.length||(h=Jg({nextMatchUps:!0,tournamentRecords:e}).matchUps),r.length||(r=function(t){return t?.length?t.map(({events:t=[]})=>t.map(({drawDefinitions:t=[]})=>t.map(({drawId:t})=>t))).flat(1/0):[]}(l));for(const t of r)oI({matchUps:h,drawId:t,tournamentRecords:e,processMatchUps:S})}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:p,matchUps:h,...Y}}function oI({matchUps:t,drawId:e,tournamentRecords:n,processMatchUps:r}){const i=t?.filter(t=>t.drawId===e).sort(Xg),o=i?.find(({roundPosition:t})=>!t);if(!o){const t=i?.find(({tournamentId:t})=>t),{drawDefinition:r}=wg({tournamentRecord:n[t?.tournamentId],drawId:e});r&&rI({drawDefinition:r})}r(i)}function aI(t){const e=t?.matchUp,n=t?.score||e?.score,r=n?.sets?.[0],{side1Score:i,side2Score:o,side1TiebreakScore:a,side2TiebreakScore:s,side1PointScore:c,side2PointScore:u}=r??{},d=i||o||a||s||c||u;return!!(n?.sets?.length>1||d)}function sI({matchUpStatus:t}){return Fp.includes(t)}function cI({matchUpStatus:t}){return xp.includes(t)}function uI({matchUpStatus:t,winningSide:e,tieMatchUps:n,sides:r,score:i}){const o=r?.find(({participantId:t})=>t),a=n?.filter(uI)?.length;return aI({score:i})||a||e&&o||t&&function({matchUpStatus:t}){return Lp.includes(t)}({matchUpStatus:t})&&![Pp,Ep,Dp].includes(t)}function dI(t){const{drawDefinition:e,findContainer:n,structureId:r,event:i}=t;let o=t.structure;const{containedStructures:a}=nm({drawDefinition:e}),s=r?a[r]??[]:[];if(!o){const t=ol({drawDefinition:e,structureId:r});if(t.error)return t;o=n?t.containingStructure??t.structure:t.structure}if(Hf({structure:o}))return{structure:o,isAdHoc:!0,error:Pt};const{matchUps:c}=zg({inContext:!0,matchUpFilters:{isCollectionMatchUp:!1},drawDefinition:e,event:i}),u=c?.filter(t=>t.structureId===r||s.includes(t.structureId)),{matchUpDependencies:p}=iI({drawIds:[e.drawId],matchUps:c,drawDefinition:e}),l=[],m=[],f={},h=[];for(const t of c??[]){if(t.structureId===r||s.includes(t.structureId)){m.push(...t.drawPositions??[]);const e=t.roundNumber;for(const n of(t.drawPositions??[]).filter(Boolean))(!f[n]||e&&f[n]>e)&&(f[n]=e)}uI(t)&&(h.push(t),l.push(t.matchUpId,...p?.[t?.matchUpId]?.matchUpIds??[]))}const g=M(m.filter(Boolean)).sort(d),I=M(l),S=M(u?.map(({matchUpId:t,drawPositions:e})=>I.includes(t)?e:[]).flat().filter(Boolean)).sort(d),{positionAssignments:y}=cl({drawDefinition:e,structure:o}),v=y?.filter(t=>t.bye).map(t=>t.drawPosition),U=y?.filter(t=>t.qualifier).map(t=>t.drawPosition),P=g?.filter(t=>!S.includes(t))??[];return{allDrawPositions:g,inContextStructureMatchUps:u,drawPositionInitialRounds:f,activeDependentMatchUpIds:I,qualifyingDrawPositions:U,inactiveDrawPositions:P,positionAssignments:y,activeDrawPositions:S,byeDrawPositions:v,activeMatchUps:h,structure:o}}function pI({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:e})=>t&&e?.includes(t)).map(({roundNumber:t})=>t).sort(d)[0]}}const lI={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"},mI=[];function fI(t,e){m(t)&&(t={method:t}),(e||$r())&&mI.push(t)}function hI(t){const e=mI.slice().map(t=>{const{color:e,keyColors:n,method:r,newline:i}=t,o=Object.keys(lI).includes(e)?lI[e]:lI.cyan,a=Object.keys(t).filter(t=>!["color","keyColors","method","newline"].includes(t)).map(e=>{const r=n&&Object.keys(n).includes(e)&&lI[n[e]]?lI[n[e]]:lI.brightwhite;return`${lI.white}${e}: ${r}${t[e]}`}).join(", ");return[i?"\n":"",o,r,r?.length<15?"\t\t":"\t",lI.white,a,lI.reset,"\n"].join("")});e?.length&&console.log(...e)}function gI(t){const e=t.bye,n=t.qualifier,r=t.participantId;return{containsBye:e,containsQualifier:n,containsParticipant:r,filled:e||n||r}}function II(t){return[Pp,Ep,Np].includes(t)}function SI({provisionalPositioning:t,isPositionAction:e,tournamentRecord:n,drawDefinition:r,drawPosition:i,loserMatchUp:o,matchUpsMap:a,structureId:s,structure:c,event:u}){if(!r)return{error:st};if(c||({structure:c}=ol({drawDefinition:r,structureId:s})),!c)return{error:Vt};s||({structureId:s}=c);const d="assignDrawPositionBye";fI({method:d,color:"cyan",drawPosition:i}),a??=bf({drawDefinition:r});const{positionAssignments:p}=cl({structure:c}),{activeDrawPositions:l}=dI({drawDefinition:r,structureId:s}),m=p?.find(t=>t.drawPosition===i);if(m?.bye)return{...Y};if(qf(r.drawType)){const t=p?.filter(t=>t.bye&&t.drawPosition!==i);if(t?.length)return Ci({result:{error:re},stack:d})}const f=!(!o||!a.drawMatchUps.some(t=>t.loserMatchUpId===o?.matchUpId&&II(t.matchUpStatus))),h=l?.includes(i);if(h&&!f)return{error:vt};let g=p?.find(t=>t.drawPosition===i);g||(g={drawPosition:i},p?.push(g));const{filled:I,containsBye:S,containsParticipant:y}=gI(g);if(S)return{...Y};if(I&&!S&&!f)return Ci({result:{error:mt},stack:d});const v=xd({tournamentRecord:n,drawDefinition:r,event:u}).appliedPolicies??{},U=zg({inContext:!0,drawDefinition:r,matchUpsMap:a}).matchUps??[],{matchUps:P}=Fg({provisionalPositioning:t,drawDefinition:r,matchUpFilters:{isCollectionMatchUp:!1},matchUpsMap:a,structure:c});if(p?.forEach(t=>{t.drawPosition===i&&(t.bye=!0,f&&(t.participantId=void 0))}),c.structureType===Ds)return function({tournamentRecord:t,drawDefinition:e,drawPosition:n,matchUps:r,event:i}){r.forEach(r=>{r.drawPositions?.includes(n)&&vI({eventId:i?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:r})})}({tournamentRecord:n,drawDefinition:r,drawPosition:i,matchUps:P}),Xl({tournamentId:n?.tournamentId,drawDefinition:r,structure:c,event:u}),yI({assignedParticipantId:y,isPositionAction:e,appliedPolicies:v,drawDefinition:r,drawPosition:i,structureId:s,stack:d});const{roundProfile:T,roundMatchUps:w}=Bf({matchUps:P}),D=T&&Object.keys(T).map(t=>Number.parseInt(t)).reverse(),R=D?.find(t=>T?.[t].drawPositions?.includes(i)),b=R?w?.[R].find(({drawPositions:t})=>t?.includes(i)):void 0;b&&vI({tournamentRecord:n,drawDefinition:r,matchUp:b,event:u});const N=b?.drawPositions?.find(t=>t!==i);if(b&&N){const t=UI({sourceDrawPositions:b.drawPositions,matchUpId:b.matchUpId,inContextDrawMatchUps:U,drawPositionToAdvance:N,tournamentRecord:n,drawDefinition:r,matchUpsMap:a});if(t.error)return t}return Xl({tournamentId:n?.tournamentId,drawDefinition:r,structure:c,event:u}),yI({assignedParticipantId:y,isPositionAction:e,appliedPolicies:v,drawDefinition:r,drawPosition:i,structureId:s,stack:d})}function yI({assignedParticipantId:t,isPositionAction:e,appliedPolicies:n,drawDefinition:r,drawPosition:i,structureId:o,stack:a}){if(e){em({appliedPolicies:n,drawDefinition:r,positionAction:{removedParticipantId:t,drawPosition:i,structureId:o,name:a}})}return Ci({result:{...Y},stack:a})}function vI({tournamentRecord:t,drawDefinition:e,eventId:n,matchUp:r,event:i}){Object.assign(r,{matchUpStatus:Sp,score:void 0,winningSide:void 0}),Yl({tournamentId:t?.tournamentId,eventId:n??i?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:r})}function UI({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:n,tournamentRecord:r,drawDefinition:i,matchUpsMap:o,matchUpId:a,event:s}){fI({method:"advanceDrawPosition",color:"cyan",drawPositionToAdvance:t});const c=o.drawMatchUps.find(t=>t.matchUpId===a),u=e.find(t=>t.matchUpId===a),p=u?.structureId,{structure:l}=ol({drawDefinition:i,structureId:p}),{positionAssignments:m}=cl({structure:l}),f=m?.filter(t=>t.bye).map(t=>t.drawPosition),h=c?.drawPositions?.find(e=>e!==t),g=h&&f?.includes(h),{targetLinks:{loserTargetLink:I},targetMatchUps:{loserMatchUp:S,winnerMatchUp:y,loserTargetDrawPosition:v}}=jg({inContextDrawMatchUps:e,drawDefinition:i,matchUpId:a}),U=qf(i?.drawType),P=(()=>{if(!U||!c?.roundNumber||!l?.matchUps)return!1;return l.matchUps.filter(t=>t.roundNumber===c.roundNumber).length%2!=0})();if(!y||y.structureId!==l?.structureId||U&&P||function({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:n,tournamentRecord:r,drawDefinition:i,winnerMatchUp:o,matchUpsMap:a,event:s}){const c="advanceWinner",u=a.drawMatchUps.find(t=>t.matchUpId===o.matchUpId),p=e.find(t=>t.matchUpId===o.matchUpId),l=p?.structureId,{structure:m}=ol({drawDefinition:i,structureId:l}),{positionAssignments:f}=cl({structure:m}),h=f?.find(({drawPosition:e})=>e===t),g=h?.bye,I=u.drawPositions?.filter(Boolean),S=f?.filter(t=>I?.includes(t.drawPosition)),y=f?.find(({drawPosition:e})=>e===t),v=n?.find(e=>e!==t),U=v&&S?.find(({drawPosition:t})=>t===v),P=U?.bye,T=g&&P;T&&console.log({isByeAdvancedBye:T});if(I?.length>1&&g&&!P)return Ci({result:{error:mt},stack:c});const w=I?.find(e=>e!==t);let D=T;const R=[...(u.drawPositions??[]).filter(Boolean),void 0,void 0].slice(0,2),b=R.map(e=>!e&&!D||e===t?(D=!0,t):e).sort(d);if(!D)return console.log("@@@@@@@",{advancingAssignmentIsBye:y,drawPositionToAdvance:t,existingAssignments:S}),Ci({result:{error:mt},stack:c});const N=f?.find(({drawPosition:t})=>t===w)?.bye,M=f?.find(({drawPosition:e})=>e===t)?.bye,A=M||N?Sp:Ap;Object.assign(u,{matchUpStatus:A,score:void 0,winningSide:void 0,drawPositions:b});const E=u.drawPositions.find(t=>!R.includes(t));fI({method:c,color:"brightyellow",changedDrawPosition:E,pairedDrawPositionIsBye:N,drawPositionIsBye:M}),Yl({tournamentId:r?.tournamentId,matchUp:u,eventId:s?.eventId,context:c,drawDefinition:i});const{targetLinks:{loserTargetLink:C},targetMatchUps:{loserMatchUp:O,loserTargetDrawPosition:k}}=jg({matchUpId:o.matchUpId,inContextDrawMatchUps:e,drawDefinition:i});if(N||M){const n=N?t:w;if(n)UI({drawPositionToAdvance:n,matchUpId:o.matchUpId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:i,matchUpsMap:a});else if(M&&C&&O)if(O.feedRound)PI({loserTargetDrawPosition:k,tournamentRecord:r,loserTargetLink:C,drawDefinition:i,loserMatchUp:O,matchUpsMap:a});else{const t=1-o.roundPosition%2,e=O.drawPositions[t],n=SI({structureId:C.target.structureId,drawPosition:e,tournamentRecord:r,drawDefinition:i,event:s});if(n.error);}}}({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:n,tournamentRecord:r,drawDefinition:i,winnerMatchUp:y,matchUpsMap:o,event:s}),S&&g&&S.structureId!==l?.structureId){const{roundNumber:t}=S;if(1===t){const t=SI({structureId:I.target.structureId,drawPosition:v,tournamentRecord:r,drawDefinition:i,event:s});if(t.error)return t}else PI({loserTargetDrawPosition:v,tournamentRecord:r,loserTargetLink:I,drawDefinition:i,loserMatchUp:S,matchUpsMap:o,event:s})}return{...Y}}function PI({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:n,drawDefinition:r,loserMatchUp:i,matchUpsMap:o,event:a}){const{roundNumber:s}=i;fI({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});const c=(o?.mappedMatchUps??{})[i.structureId].matchUps,{initialRoundNumber:u}=pI({drawPosition:t,matchUps:c});if(u===s){const i=SI({structureId:n.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:r,event:a});if(i.error)return i}}function TI({positionAssignments:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:r,structure:i,event:o}){const{matchUps:a}=Fg({drawDefinition:n,matchUpsMap:r,structure:i,event:o});a.forEach(r=>{const i=t.filter(({drawPosition:t})=>r.drawPositions?.includes(t)).filter(t=>t.bye).length;if(!r.winningSide){const t=i?Sp:Ap;Object.assign(r,{matchUpStatus:t}),Yl({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:o?.eventId,drawDefinition:n,matchUp:r})}})}function wI(t){let{inContextDrawMatchUps:e,participantId:n,drawPosition:r}=t;const{tournamentRecord:i,drawDefinition:o,structureId:a,matchUpsMap:s,event:c}=t,{structure:u}=ol({drawDefinition:o,structureId:a}),d=(ul({drawDefinition:o,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}=dI({drawDefinition:o,structureId:a});if(p.includes(r))return{error:vt};e||({matchUps:e}=zg({inContext:!0,drawDefinition:o,matchUpsMap:s}));return DI({inContextDrawMatchUps:e,tournamentRecord:i,drawDefinition:o,structureId:a,drawPosition:r,matchUpsMap:s,event:c}).drawPositionCleared?(Xl({tournamentId:i?.tournamentId,drawDefinition:o,structure:u,event:c}),{...Y,participantId:n}):{error:It}}function DI({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,matchUpsMap:i,structureId:o,event:a}){const{structure:s}=ol({drawDefinition:n,structureId:o});if(!s)return{error:Vt};const c=ul({drawDefinition:n,structure:s}).positionAssignments??[],u=c.some(t=>{if(t.drawPosition===r)return delete t.participantId,delete t.qualifier,delete t.bye,!0});if(s.structureType===Ds)return TI({positionAssignments:c,tournamentRecord:e,drawDefinition:n,matchUpsMap:i,structure:s}),{drawPositionCleared:u,...Y};const{matchUps:d}=Fg({drawDefinition:n,matchUpFilters:{isCollectionMatchUp:!1},matchUpsMap:i,structure:s,event:a}),{roundProfile:l,roundMatchUps:m}=Bf({matchUps:d}),f=l&&Object.keys(l),h=f?.map(t=>p(t)),g=function({roundNumbers:t,roundProfile:e,positionAssignments:n,drawPosition:r}){let i=r;return t?.map(t=>{const r=e?.[t],o=r?.pairedDrawPositions?.find(t=>t.includes(i)),a=o?.find(t=>t!==i),s=n.find(t=>t.drawPosition===a),c=e?.[t+1],u=s?.bye,d=c?.pairedDrawPositions?.find(t=>t.includes(a)),p=u&&d&&c?.drawPositions?.includes(a),l=o&&{pairedDrawPositionByeAdvancedPair:!p&&d,pairedDrawPosition:a,targetDrawPosition:i,relevantPair:o,roundNumber:t};return p&&(i=a),l}).filter(t=>t?.targetDrawPosition)}({roundNumbers:h,roundProfile:l,positionAssignments:c,drawPosition:r}),I=function(t){return t?.reduce((t,e)=>{const{roundNumber:n,relevantPair:r,targetDrawPosition:i,pairedDrawPosition:o,pairedDrawPositionByeAdvancedPair:a}=e,s=[{roundNumber:n,targetDrawPosition:i,relevantPair:r},a&&{roundNumber:n+1,targetDrawPosition:o,relevantPair:a,subsequentRoundRemoval:!0}].filter(Boolean);return t.concat(...s)},[])}(g);return I?.forEach(({roundNumber:u,targetDrawPosition:d,relevantPair:p})=>{const l=m?.[u].find(t=>j(t.drawPositions?.filter(Boolean),p.filter(Boolean)));l&&(!function({inContextDrawMatchUps:t,targetDrawPosition:e,tournamentRecord:n,drawDefinition:r,matchUpsMap:i,roundNumber:o,structureId:a}){const{structure:s}=ol({drawDefinition:r,structureId:a});if(!s)return{error:Vt};if(s.structureType===Ds)return;i=i||bf({drawDefinition:r});const c=i?.mappedMatchUps??{},u=c[a].matchUps,{initialRoundNumber:d}=pI({drawPosition:e,matchUps:u}),p=u?.filter(t=>t.roundNumber>=o&&t.roundNumber!==d&&t.drawPositions?.includes(e)),l=cl({drawDefinition:r,structureId:a}).positionAssignments??[];p?.forEach(o=>RI({drawPosition:e,targetMatchUp:o,inContextDrawMatchUps:t,positionAssignments:l,tournamentRecord:n,drawDefinition:r,matchUpsMap:i,structure:s}))}({inContextDrawMatchUps:t,targetDrawPosition:d,tournamentRecord:e,drawDefinition:n,structureId:o,roundNumber:u,matchUpsMap:i}),RI({inContextDrawMatchUps:t,positionAssignments:c,tournamentRecord:e,drawDefinition:n,targetMatchUp:l,drawPosition:r,matchUpsMap:i,structure:s,event:a}))}),{tasks:I,drawPositionCleared:u,positionAssignments:c}}function RI({inContextDrawMatchUps:t,positionAssignments:e,tournamentRecord:n,drawDefinition:r,targetMatchUp:i,drawPosition:o,matchUpsMap:s,structure:c,event:u}){const d="removeDrawPosition",p=i.drawPositions?.slice(),l=i.matchUpStatus,m=i.winningSide,f=(s=s??bf({drawDefinition:r})).mappedMatchUps[c.structureId].matchUps,{initialRoundNumber:h}=pI({drawPosition:o,matchUps:f});if(i.roundNumber&&h&&i.roundNumber>h){const t=(i.drawPositions??[]).map(t=>t===o?void 0:t);i.drawPositions=t}!function({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,targetMatchUp:r,drawPosition:i,event:o,stack:s}){if(r.matchUpType!==a)return;const c=t?.find(t=>t.matchUpId===r.matchUpId),u=(c?.sides??[]).reduce((t,e,n)=>e.drawPosition===i?n:t,void 0);void 0!==u&&r.sides?.[u]?.lineUp&&(delete r.sides?.[u].lineUp,Yl({tournamentId:e?.tournamentId,context:`${s}-TEAM`,eventId:o?.eventId,matchUp:r,drawDefinition:n}))}({inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:r,targetMatchUp:i,drawPosition:o,event:u,stack:d});const g=jg({matchUpId:i.matchUpId,inContextDrawMatchUps:t,drawDefinition:r}),{targetLinks:{winnerTargetLink:I},targetMatchUps:{loserMatchUp:S,winnerMatchUp:y,loserMatchUpDrawPositionIndex:v}}=g,U=function({initialDrawPositions:t,initialMatchUpStatus:e,initialWinningSide:n,positionAssignments:r,tournamentRecord:i,drawDefinition:o,targetMatchUp:a,drawPosition:s,event:c,stack:u}){const d=r.filter(({drawPosition:t})=>a.drawPositions?.includes(t)),p=d.filter(t=>t.bye).length,l=p&&Sp||a.matchUpStatus&&II(a.matchUpStatus)&&a.matcHUpStatus||Ap;a.matchUpStatus=l,a.matchUpStatus&&II(a.matchUpStatus)&&(a.winningSide=void 0);const m=t?.find(t=>!a.drawPositions?.includes(t)),f=t?.includes(s)&&e===a.matchUpStatus&&n===a.winningSide;f||(m&&fI({method:u,color:"brightyellow",removedDrawPosition:m}),Yl({tournamentId:i?.tournamentId,context:`${u}-${s}`,eventId:c?.eventId,matchUp:a,drawDefinition:o}));return p}({initialDrawPositions:p,initialMatchUpStatus:l,initialWinningSide:m,positionAssignments:e,tournamentRecord:n,drawDefinition:r,targetMatchUp:i,drawPosition:o,event:u,stack:d});if(S&&S.structureId!==g.matchUp.structureId&&!U){const e=function({loserMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,loserMatchUp:i,matchUpsMap:o,event:a,stack:s}){const{drawPositions:c,roundNumber:u}=i;if(1===u){const a=c[t];return void DI({structureId:i.structureId,drawPosition:a,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,matchUpsMap:o})}const d=Math.min(...c.filter(Boolean)),p=function({loserMatchUpDrawPosition:t,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,loserMatchUp:i,matchUpsMap:o,event:a}){const{structure:s}=ol({structureId:i.structureId,drawDefinition:r}),{positionAssignments:c}=cl({structure:s}),u=c?.find(e=>e.drawPosition===t);if(u?.bye){const s=wI({drawPosition:t,structureId:i.structureId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,matchUpsMap:o,event:a});if(s.error)return s}return{...Y}}({loserMatchUpDrawPosition:d,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,loserMatchUp:i,matchUpsMap:o,event:a});if(p.error)return Ci({result:p,stack:s});const l=o?.mappedMatchUps??{},m=l[i.structureId].matchUps,{initialRoundNumber:f}=pI({drawPosition:d,matchUps:m});1===f&&(fI({method:s,color:"brightyellow",loserMatchUpDrawPosition:d}),DI({structureId:i.structureId,drawPosition:d,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,matchUpsMap:o}))}({loserMatchUpDrawPositionIndex:v,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:r,loserMatchUp:S,matchUpsMap:s,event:u,stack:d});if(e?.error)return e}return y&&y.structureId!==g.matchUp.structureId&&I.target.feedProfile,{...Y}}function bI({drawDefinition:t,stages:e}){if(!t)return{error:st};const n=M((t?.structures??[]).filter(t=>!e?.length||t.stage&&e.includes(t.stage)).map(t=>{const{positionAssignments:e}=cl({structure:t});return e?e.map(Xp):[]}).flat().filter(Boolean));return{...Y,assignedParticipantIds:n}}function NI(t){const e=(t?.entries??[]).filter(Boolean).reduce((t,e)=>{const{entryStage:n,entryStatus:r}=e,i=`_${n||us}${r||""}`;return t[i]||(t[i]=[]),t[i].push(e),t},{}),n=t=>Number.isNaN(Number(t))?1/0:t;return Object.keys(e).flatMap(t=>e[t].sort((t,e)=>n(t.entryPosition)-n(e.entryPosition)).map((t,e)=>({...t,entryPosition:e+1})))}function MI(t){return[lf,pf].includes(t)}function AI({autoEntryPositions:t=!0,ignoreAssignment:e,tournamentRecord:n,drawDefinition:r,participantIds:i,entryStatus:o,entryStage:a,extension:s,eventSync:c,drawId:u,stage:d,event:p}){const l=function({participantIds:t,drawDefinition:e,entryStatus:n,entryStage:r,extension:i,event:o}){if(!t||!Array.isArray(t))return{error:Ze,method:"modifyEntriesStatus",participantIds:t};if(!e&&!o)return{error:Ht};if(n&&!yf.includes(n))return{error:yn};if(r&&!fs.includes(r))return{error:Zt};const a="modifyEntriesStatus";return n||i?i&&!Wu({extension:i,requiredAttributes:["name"]})?Ci({result:{error:sr},info:"Invalid extension",context:{extension:i},stack:a}):void 0:Ci({result:{error:Ae},info:"Missing entryStatus",stack:a})}({participantIds:i,drawDefinition:r,entryStatus:o,entryStage:a,extension:s,event:p});if(l)return l;const m="modifyEntriesStatus",f=[],h=function({event:t,stage:e}){const n=[];return t?.drawDefinitions?.forEach(t=>{const r=bI({stages:e&&[e],drawDefinition:t}).assignedParticipantIds??[];n.push(...r)}),n}({event:p,stage:d});if(!function({participantIds:t,tournamentParticipants:e,entryStatus:n,event:r}){return t.every(t=>{const i=ju({tournamentParticipants:e,participantId:t})?.participantType;return!(i&&[Sm,hm].includes(i)&&MI(n)||n&&r?.eventType&&i===gm&&[ns,os].includes(r.eventType)&&[ef,...hf].includes(n))})}({participantIds:i,tournamentParticipants:n?.participants??[],entryStatus:o,event:p}))return{error:yn};const g=p&&Tg({event:p}).flightProfile,I=g?.flights?.find(t=>t.drawId===u),S=function({assignedParticipantIds:t,ignoreAssignment:e,participantIds:n,entryStatus:r,entryStage:i,extension:o,stage:a}){return s=>{const c=(s??[]).filter(t=>!a||!t.entryStage||a===t.entryStage).filter(({participantId:t})=>n.includes(t)),u=e=>r&&t.includes(e.participantId)&&!(hf.includes(e.entryStatus)&&hf.includes(r));return c.every(t=>!(u(t)&&!e)&&(r&&(t.entryStatus=r,delete t.entryPosition),i&&(t.entryStage=i,delete t.entryPosition),o&&(o.value?$u({element:t,extension:o}):qu({element:t,name:o.name})),!0))?{...Y}:{error:gn}}}({assignedParticipantIds:h,ignoreAssignment:e,participantIds:i,entryStatus:o,entryStage:a,extension:s,stage:d}),y=({flight:t,drawDefinition:e})=>{p&&(p.entries=NI({entries:p.entries??[]})),t&&(t.drawEntries=NI({entries:t.drawEntries})),e&&(e.entries=NI({entries:e.entries}))},v=({flight:t,drawDefinition:e})=>{const n="updateDrawEntries";if(t){const e=S(t.drawEntries);if(e.error)return Ci({result:e,stack:n})}if(e){const t=S(e.entries);if(t.error)return Ci({result:t,stack:n});f.includes(e.drawId)||f.push(e.drawId)}return{...Y}},U=p?.entries?.find(({entryPosition:t})=>t)??(I?.drawEntries?.find(({entryPosition:t})=>t)||r?.entries?.find(({entryPosition:t})=>t));if(t&&!U&&y({flight:I,drawDefinition:r}),I||r){const t=v({flight:I,drawDefinition:r});if(t.error)return Ci({result:t,stack:m})}const P=p?.drawDefinitions?.map(({drawId:t})=>t)??[],T=g?.flights?.filter(t=>!P.includes(t.drawId))??[];for(const t of T){const e=t&&v({flight:t,drawDefinition:void 0});if(e?.error)return Ci({result:e,stack:m})}const w=1===g?.flights?.length&&(p?.drawDefinitions?.length??0)<=g?.flights?.length;if(!I&&!r&&o&&gf.includes(o))return{error:wn};if(!I&&!r||o===ff||c&&w){const t=S(p?.entries);if(t?.error)return Ci({result:t,stack:m});if(o===ff){const t=function({updateEntryStatus:t,participantIds:e,flightProfile:n,event:r}){const i=new Set(e);for(const e of n?.flights??[]){const n=t(e.drawEntries);if(n.error)return n.error;e.drawEntries=e.drawEntries.filter(({participantId:t})=>!i.has(t))}for(const e of r?.drawDefinitions??[]){const n=t(e.entries);if(n.error)return n.error;e.entries=e.entries?.filter(({participantId:t})=>!i.has(t))}return}({updateEntryStatus:S,participantIds:i,flightProfile:g,event:p});if(t)return Ci({result:{error:t},stack:m})}}t&&y({flight:I,drawDefinition:r});for(const t of p?.drawDefinitions??[])f.length&&!f.includes(t.drawId)||Ql({tournamentId:n.tournamentId,eventId:p?.eventId,drawDefinition:t});return{...Y}}function EI(t){const e=fu(t,[{ratings:!0,[cu]:ru}]);if(e.error)return e;const r=t.matchUpType&&[n,i].includes(t.matchUpType)?t.matchUpType:n,o=Object.keys(rp),a=t.targetRatingType&&o.includes(t.targetRatingType)?t.targetRatingType:jd,s=t.ratings[r]?t.ratings[r].reduce((t,e)=>t.includes(e.scaleName)?t:t.concat(e.scaleName),[]):[];if(!s)return{error:mr};const c=t.ratings[r]?.find(t=>t.scaleName===a)??t.ratings[r]?.[0];if(s[0]===a)return c;const u=c?.scaleName,d=rp[c?.scaleName]?.accessor,p=d&&c.scaleValue[d]||c?.scaleValue,l=ip({sourceRatingType:u,sourceRating:p}),m=function({targetRatingType:t,sourceRating:e}){const n=rp[t]?.decimalsCount||0,r=rp[t]?.range,i=r?.[0]>r?.[1],o=Math.max(...r),a=rp[jd]?.range,s=Gd({targetRange:r,sourceRange:a,value:e}),c=Number.parseFloat(s?.toFixed(n))||0;return i?o-c:c}({targetRatingType:a,sourceRating:l});return m?{convertedRating:m,sourceRating:p}:{error:sr}}function CI({participantResults:t,sides:e,score:r}){const i=e?.find(({sideNumber:t})=>1===t),o=e?.find(({sideNumber:t})=>2===t),a=i?.participant?.ratings,s=o?.participant?.ratings;if(a?.[n]&&s?.[n]){const e=jd,{convertedRating:n}=EI({ratings:a,targetRatingType:e}),{convertedRating:c}=EI({ratings:s,targetRatingType:e}),{side1pressure:u,side2pressure:d}=function({side1ConvertedRating:t,side2ConvertedRating:e,score:n}){const r=Math.max(t,e),i=Math.min(t,e),o=Math.abs(t-e),a=rp[jd].range,s=Math.max(...a),c=(r+0*(s-r))/s*o,u=n?.sets?.reduce((t,e)=>t+(e?.side1Score??0),0),d=n?.sets?.reduce((t,e)=>t+(e.side2Score??0),0),p=t>e?2:1,l=(u||0)*(i+(1===p?c:0)),m=(d||0)*(i+(2===p?c:0)),f=l+m,h=f?N(l/f):0,g=f?N(m/f):0;return{side1pressure:h,side2pressure:g}}({side1ConvertedRating:n,side2ConvertedRating:c,score:r});u&&t[i?.participantId].pressureScores.push(u),d&&t[o?.participantId].pressureScores.push(d);const p=Math.max(...rp[jd].range),l=N((c-n)/p),m=N((n-c)/p);t[i?.participantId].ratingVariation.push(l),t[o?.participantId].ratingVariation.push(m)}}function OI({winningSide:t,matchUpFormat:e=va,matchUpStatus:n,tallyPolicy:r,score:i}){const o=[0,0],a=i?.sets,s="number"==typeof t&&t-1,c=co(e),u=xI(c?.bestOf??1);if("number"==typeof s&&(n===Pp&&r?.setsCreditForDefaults||n===Ep&&r?.setsCreditForWalkovers))o[s]=u;else for(const t of a??[]){const{winningSide:e}=t;e&&(o[e-1]+=1)}return"number"==typeof s&&n===Np&&(+o[1-s]===u&&(o[1-s]-=1),r?.setsCreditForRetirements&&(o[s]=u)),o}function kI({matchUpFormat:t=va,winningSide:e,matchUpStatus:n,tallyPolicy:r,score:i}){const{sets:o}=i??{};if(!o)return[0,0];const a="number"==typeof e&&e-1,s=co(t),c=xI(s?.bestOf??1),u=s?.setFormat?.tiebreakAt||0,d=[[],[]];if("number"==typeof a&&(n===Pp&&r?.gamesCreditForDefaults||n===Ep&&r?.gamesCreditForWalkovers)){const t=c*(s?.setFormat?.setTo||0);d[a].push(t)}else o.forEach((t,e)=>{const n=(t.setNumber||e+1)>c&&s?.finalSetFormat?"finalSetFormat":"setFormat",i=s?.[n]?.based,o=s?.[n].tiebreakSet,{side1Score:a,side2Score:u}=t;LI(i)&&!o&&(d[0].push(p(a||0)),d[1].push(p(u||0))),o&&t.winningSide&&!1!==r?.gamesCreditForTiebreakSets&&d[t.winningSide-1].push(1)});if(n===Np&&"number"==typeof a){const i=o.length>c&&s?.finalSetFormat?"finalSetFormat":"setFormat",l=s?.[i];if(LI(l.based)){const i=l?.setTo||0,m=t=>{if(s&&""!==t)return+t===u-1||+t===u?p(u||0)+1:+t<u?i:u},f=OI({winningSide:e,score:{sets:o},matchUpStatus:n,matchUpFormat:t,tallyPolicy:r});if(d.map(t=>t[a]<=t[1-a]).reduce((t,e)=>t+(e?1:0),0)>f[1-a]){const t=d[a].length,e=m(d[1-a][t-1]);e&&(d[a][t-1]=e)}c>d[a].length&&r?.gamesCreditForRetirements&&d[a].push(i)}}return[d[0].reduce((t,e)=>t+e,0),d[1].reduce((t,e)=>t+e,0)]}function FI({matchUpFormat:t,score:e}){const n=t?co(t):void 0,r=xI(n?.bestOf??1),i=[0,0],o=[0,0];return e?.sets?.forEach((t,e)=>{const a=(t.setNumber||e+1)>r&&n?.finalSetFormat?"finalSetFormat":"setFormat",s=n?.[a]?.based;if(_I(s)){const{side1Score:e,side2Score:n}=t;e&&(o[0]+=p(e||0)),n&&(o[1]+=p(n||0))}else t.side1TiebreakScore&&(o[0]+=p(t.side1TiebreakScore||0)),t.side2TiebreakScore&&(o[1]+=p(t.side2TiebreakScore||0)),(t.side1TiebreakScore||t.side2TiebreakScore)&&t.winningSide&&(i[t.winningSide-1]+=1)}),{pointsTally:o,tiebreaksTally:i}}function xI(t){return t&&Math.ceil(t/2)||1}function _I(t){return"P"===t}function LI(t){return!_I(t)}function BI({participantIds:t,pressureRating:e,groupingTotal:n,matchUpFormat:r,tallyPolicy:i,perPlayer:o,matchUps:a}){const s={},c=i?.excludeMatchUpStatuses??[],u=function({matchUps:t,excludeMatchUpStatuses:e,participantIds:n}){return t?.filter(t=>(t.tieMatchUps||!e.includes(t.matchUpStatus))&&(!n?.length||2===V(n,[YI(t,0),YI(t,1)]).length))}({matchUps:a,excludeMatchUpStatuses:c,participantIds:t}),{totalSets:d,totalGames:p}=function({filteredMatchUps:t,excludeMatchUpStatuses:e}){const n=t?.flatMap(({score:t,tieMatchUps:n})=>n?n.filter(({matchUpStatus:t})=>!e.includes(t)).flatMap(({score:t})=>t?.sets?.length??0):t?.sets?.length??0),r=n?.reduce((t,e)=>t+e,0),i=t=>t?.sets?.reduce((t,e)=>t+(e?.side1Score??0)+(e?.side2Score??0),0)??0,o=t?.flatMap(({score:t,tieMatchUps:n})=>n?n.filter(({matchUpStatus:t})=>!e.includes(t)).flatMap(({score:t})=>i(t)):i(t)),a=o?.reduce((t,e)=>t+e,0);return{totalSets:r,totalGames:a}}({filteredMatchUps:u,excludeMatchUpStatuses:c});for(const t of u??[]){const{matchUpStatus:n,tieMatchUps:a,tieFormat:c,score:u,winningSide:d,sides:p}=t,l=c&&t._disableAutoCalc&&c.collectionDefinitions.every(({scoreValue:t})=>t),m=d&&HI(t),f=d&&zI(t);m||f?(KI(s,m),KI(s,f),o=jI({winningParticipantId:m,losingParticipantId:f,manualGamesOverride:l,participantResults:s,pressureRating:e,matchUpFormat:r,matchUpStatus:n,tieMatchUps:a,tallyPolicy:i,winningSide:d,perPlayer:o,matchUp:t,score:u,sides:p})):o=VI({participantResults:s,manualGamesOverride:l,matchUpStatus:n,tieMatchUps:a,perPlayer:o,score:u,sides:p}),l&&$I({participantResults:s,score:u,sides:p})}return function({participantResults:t,groupingTotal:e,matchUpFormat:n,tallyPolicy:r,totalGames:i,perPlayer:o,totalSets:a}){const s=(n&&co(n))??{},c=s.bestOf,u=c&&Math.ceil(c/2)||1,d=s.setFormat?.setTo,p=Math.pow(10,r?.precision||3);Object.keys(t).forEach(n=>{const s=t[n].setsWon,c=t[n].setsLost,l=r?.groupTotalSetsPlayed||"setsPct"===e?a:o*u||s+c;let m=Math.round(s/l*p)/p;(m===1/0||Number.isNaN(m))&&(m=l);const f=t[n].tieMatchUpsWon,h=f+t[n].tieMatchUpsLost;let g=Math.round(f/h*p)/p;(g===1/0||Number.isNaN(g))&&(g=f);const I=t[n].matchUpsWon,S=I+t[n].matchUpsLost;let y=Math.round(I/S*p)/p;(y===1/0||Number.isNaN(y))&&(y=I);const v=t[n].gamesWon||0,U=t[n].gamesLost||0,P=(o||0)*u*(d||0),T=r?.groupTotalGamesPlayed||"gamesPct"===e?i:Math.max(P,v+U);let w=Math.round(v/T*p)/p;(w===1/0||Number.isNaN(w))&&(w=0);const D=t[n].pointsWon+t[n].pointsLost;let R=Math.round(t[n].pointsWon/D*p)/p;(R===1/0||Number.isNaN(R))&&(R=0),t[n].setsWon=s,t[n].setsLost=c,t[n].setsPct=m,t[n].tieMatchUpsWon=f,t[n].tieMatchUpsPct=g,t[n].matchUpsPct=y,t[n].gamesWon=v,t[n].gamesLost=U,t[n].gamesPct=w,t[n].pointsPct=R,t[n].result=`${t[n].matchUpsWon}/${t[n].matchUpsLost}`})}({participantResults:s,groupingTotal:n,matchUpFormat:r,tallyPolicy:i,totalGames:p,perPlayer:o,totalSets:d}),{participantResults:s}}function VI({participantResults:t,manualGamesOverride:e,matchUpStatus:n,tieMatchUps:r,perPlayer:i,score:o,sides:a}){if(n&&_p.includes(n)){const e=YI({sides:a},0),n=YI({sides:a},1);e&&(KI(t,e),t[e].matchUpsCancelled+=1),n&&(KI(t,n),t[n].matchUpsCancelled+=1)}else if(r?.length){i=0;for(const n of r)n.winningSide&&GI({participantResults:t,tieMatchUp:n,sides:a}),QI({score:n.score,manualGamesOverride:e,participantResults:t,sides:a})}else QI({manualGamesOverride:e,participantResults:t,score:o,sides:a});return i}function GI({participantResults:t,tieMatchUp:e,sides:r}){const o=r?.find(({sideNumber:t})=>t===e.winningSide)?.participantId,a=r?.find(({sideNumber:t})=>t===e.winningSide)?.participantId;o&&a&&(KI(t,o),KI(t,a),t[o].tieMatchUpsWon+=1,t[a].tieMatchUpsLost+=1,bh(n)(e.matchUpType)?(t[o].tieSinglesWon+=1,t[a].tieSinglesLost+=1):bh(i)(e.matchUpType)&&(t[o].tieDoublesWon+=1,t[a].tieDoublesLost+=1))}function jI({winningParticipantId:t,losingParticipantId:e,manualGamesOverride:n,participantResults:r,pressureRating:i,matchUpFormat:o,matchUpStatus:a,tieMatchUps:s,tallyPolicy:c,winningSide:u,perPlayer:d,matchUp:p,score:l,sides:m}){if(s?.length){d=0;for(const o of s)o.winningSide&&qI({winningParticipantId:t,losingParticipantId:e,participantResults:r,tieMatchUp:o,winningSide:u}),JI({matchUpFormat:o.matchUpFormat,matchUpStatus:o.matchUpStatus,matchUpType:o.matchUpType,score:o.score,sides:o.sides,winningParticipantId:t,losingParticipantId:e,manualGamesOverride:n,participantResults:r,isTieMatchUp:!0,pressureRating:i,tallyPolicy:c,winningSide:u});XI({winningParticipantId:t,losingParticipantId:e,participantResults:r,matchUpStatus:a})}else JI({matchUpFormat:p.matchUpFormat??o,matchUpType:p.matchUpType,isTieMatchUp:void 0,winningParticipantId:t,manualGamesOverride:n,losingParticipantId:e,participantResults:r,pressureRating:i,matchUpStatus:a,tallyPolicy:c,winningSide:u,score:l,sides:m});return d}function qI({winningParticipantId:t,losingParticipantId:e,participantResults:r,tieMatchUp:o,winningSide:a}){const{matchUpType:s}=o,c=bh(i)(s),u=bh(n)(s),d=o.winningSide===a,p=d?e:t;WI(r,d?t:e,"Won",u,c),WI(r,p,"Lost",u,c)}function WI(t,e,n,r,i){e&&(t[e][`tieMatchUps${n}`]+=1,r&&(t[e][`tieSingles${n}`]+=1),i&&(t[e][`tieDoubles${n}`]+=1))}function $I({participantResults:t,score:e,sides:n}){const r=e?.sets?.reduce((t,e)=>t+(e?.side1Score??0),0),i=e?.sets?.reduce((t,e)=>t+(e.side2Score??0),0),o=n?.find(({sideNumber:t})=>1===t)?.participantId,a=n?.find(({sideNumber:t})=>2===t)?.participantId;KI(t,o),KI(t,a),o&&(t[o].gamesWon+=r,t[o].gamesLost+=i),a&&(t[a].gamesWon+=i,t[a].gamesLost+=r)}function HI(t){return YI(t,t.winningSide-1)}function zI(t){return YI(t,1-(t.winningSide-1))}function YI(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 KI(t,e){e&&!t[e]&&(t[e]={allDefaults:0,defaults:0,defeats:[],gamesLost:0,gamesWon:0,matchUpsCancelled:0,matchUpsLost:0,matchUpsWon:0,pointsLost:0,pointsWon:0,pressureScores:[],ratingVariation:[],retirements:0,setsLost:0,setsWon:0,tieSinglesWon:0,tieSinglesLost:0,tieDoublesWon:0,tieDoublesLost:0,tieMatchUpsLost:0,tieMatchUpsWon:0,victories:[],walkovers:0})}function QI({manualGamesOverride:t,participantResults:e,score:n,sides:r}){const{sets:i}=n??{},o=[[],[]],a=[0,0];for(const t of i??[]){const{winningSide:e,side1Score:n,side2Score:r}=t;e&&(a[e-1]+=1),o[0].push(p(n||0)),o[1].push(p(r||0))}const s=[o[0].reduce((t,e)=>t+e,0),o[1].reduce((t,e)=>t+e,0)];r.forEach((n,r)=>{const{participantId:i}=n;i&&(KI(e,i),e[i].setsWon+=a[r],e[i].setsLost+=a[1-r],t||(e[i].gamesWon+=s[r],e[i].gamesLost+=s[1-r]))})}function JI({winningParticipantId:t,manualGamesOverride:e,losingParticipantId:r,participantResults:i,pressureRating:o,matchUpFormat:a,matchUpStatus:s,isTieMatchUp:c,matchUpType:u,tallyPolicy:d,winningSide:p,score:l,sides:m}){const f=p&&p-1,h=1-f;o&&u===n&&CI({participantResults:i,sides:m,score:l}),c||XI({winningParticipantId:t,losingParticipantId:r,participantResults:i,matchUpStatus:s});const g=OI({matchUpStatus:s,matchUpFormat:a,tallyPolicy:d,winningSide:p,score:l}),I=kI({matchUpStatus:s,matchUpFormat:a,tallyPolicy:d,winningSide:p,score:l}),{pointsTally:S}=FI({score:l,matchUpFormat:a});t&&(i[t].setsWon+=g[f],i[t].setsLost+=g[h],e||(i[t].gamesWon+=I[f],i[t].gamesLost+=I[h]),i[t].pointsWon+=S[f],i[t].pointsLost+=S[h]),r&&(i[r].setsWon+=g[h],i[r].setsLost+=g[f],e||(i[r].gamesWon+=I[h],i[r].gamesLost+=I[f]),i[r].pointsWon+=S[h],i[r].pointsLost+=S[f])}function XI({winningParticipantId:t,losingParticipantId:e,participantResults:n,matchUpStatus:r}){e&&(r===Ep&&(n[e].walkovers+=1),r===Pp&&(n[e].defaults+=1),r===Np&&(n[e].retirements+=1),II(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 ZI(t,e,n,r){if(t.excludedDirectives?.length){const e=t.excludedDirectives.map(({attribute:t})=>t).join(", "),n=`${e.length} directives were excluded due to participants limit}`;r.push(n);const i=`Excluded: ${e}`;r.push(i)}else{const i=(e,n)=>Number.parseFloat(t.reversed?e:n)-Number.parseFloat(t.reversed?n:e),o=t.groups?Object.values(t.groups).flat(1/0).length:t.participantIds?.length??0,a=t.reversed?" in reverse order":"",s=`Step ${e+1}: ${o} particiants were ${t.groups?"grouped":"separated"}${a} by ${t.attribute}`;if(r.push(s),t.idsFilter){const e=`${t.attribute} was calculated considering ONLY TIED PARTICIPANTS`;r.push(e)}!function(t,e,n,r){t.groups&&Object.keys(t.groups).sort(r).forEach(r=>{const i=t.groups[r].map(t=>e[t]).join(", "),o=`${r} ${t.attribute}: ${i}`;n.push(o)})}(t,n,r,i)}r.push("----------------------")}function tS({participantResults:t,participantIds:e,attribute:n}){return eS({participantResults:t,participantIds:e}).reduce((t,e)=>{const{participantId:r,results:i}=e,o=i?.[n];return!isNaN(o)&&r&&(t[o]?t[o].push(r):t[o]=[r]),t},{})}function eS(t){return(t.participantIds||Object.keys(t.participantResults)).reduce((e,n,r)=>(e.push({participantId:n,i:r,results:t.participantResults[n]}),e),[])}const nS=[{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}],rS={matchUpsPct:20,tieMatchUpsPct:16,pointsPct:4,gamesPct:8,setsPct:12};function iS(t){const{requireCompletion:e=!0,participantResults:n,subOrderMap:r,tallyPolicy:i}=t,o=[];if(e&&!function({participantResults:t,participantsCount:e}){const n=eS({participantResults:t}),r=n.filter(t=>e-1===t.results.matchUpsWon+t.results.matchUpsLost+t.results.matchUpsCancelled);return e===r.length}(t))return{};const a=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(i?.groupOrderKey)?i.groupOrderKey:"matchUpsWon",s=tS({participantResults:n,attribute:a});o.push({attribute:a,groups:s});const c=Object.keys(s).map(t=>Number.parseFloat(t)).sort((t,e)=>e-t).map(t=>s[t]).map(e=>{const n=oS({participantIds:e,...t});return o.push(...n.report??[]),n.order}).flatMap((t,e)=>t.map(t=>t.resolved?t:{...t,subGroup:[e].concat(...t.subGroup??[])}));let u,d,p=0,l=1;c.forEach((t,e)=>{e&&(t.resolved||d&&!t.resolved)&&(l+=1),d=t.resolved;const n=Number.parseInt(t.subGroup?.join("")||0);t.resolved?(t.position=e+1,l=t.position):(u&&n>u&&(l+=p,p=0),t.position=l,p+=1),u=n});const m=C(c.map(({position:t})=>t));return c.forEach(t=>{const{participantId:e,position:o}=t??{},a=n[e];t.GEMscore=function(t){const e=Array.isArray(i?.GEMscore)?Object.keys(rS).filter(t=>i.GEMscore.includes(t)):Object.keys(rS),n=e.map(e=>(t[e]||0)*Math.pow(10,rS[e].toFixed(3)));return n.reduce((t,e)=>t+e,0)}(a);const s=m[o];void 0!==t?.position&&(s>1&&(t.ties=s,r&&(t.subOrder=r[e])),t.rankOrder=o,t.groupOrder=o+(t.subOrder||1)-1)}),{groupOrder:c,report:o.flat(1/0).filter(Boolean)}}function oS({participantResults:t,disableHeadToHead:e,participantIds:n,matchUpFormat:r,tallyPolicy:i,matchUps:o}){const a=[],s=[];let c;if(1===n?.length){return{order:[{resolved:!0,participantId:n[0]}]}}if(2===n?.length&&(!i?.headToHead||!i.headToHead.disabled&&!e)){const e=function({participantIds:t,participantResults:e}){if(!t)return;if(e[t[0]].victories.includes(t[1]))return t.map(t=>({resolved:!0,participantId:t}));if(e[t[1]].victories.includes(t[0]))return t.reverse().map(t=>({resolved:!0,participantId:t}))}({participantIds:n,participantResults:t});if(e){const t=e[0].participantId;return s.push({attribute:"head2Head",participantIds:n,headToHeadWinner:t}),{order:e,headToHeadWinner:t,report:s}}}const u=(i?.tallyDirectives||nS).filter(t=>{const e=!(P(t.maxParticipants)&&n?.length>t.maxParticipants);return e||a.push(t),e});return a.length&&s.push({excludedDirectives:a,participantIds:n}),u.every(({attribute:t,reversed:e,idsFilter:a,groupTotals:u,disableHeadToHead:d})=>(c=function({disableHeadToHead:t,participantIds:e,matchUpFormat:n,groupTotals:r,tallyPolicy:i,attribute:o,idsFilter:a,matchUps:s,reversed:c}){const{participantResults:u}=BI({participantIds:a&&e,groupingTotal:r&&o,matchUpFormat:n,tallyPolicy:i,matchUps:s}),d=tS({participantResults:u,participantIds:e,attribute:o}),p=[{attribute:o,reversed:c,groups:d,idsFilter:a,groupTotals:r}];let l;if(Object.keys(d).length>1&&e.length){const e=Object.keys(d).map(t=>Number.parseFloat(t)).sort((t,e)=>c?t-e:e-t).map(t=>d[t]).map(e=>{const r=oS({participantResults:u,disableHeadToHead:t,participantIds:e,matchUpFormat:n,tallyPolicy:i,matchUps:s});return p.push(...r.report??[]),r.order});l=e.flatMap((t,e)=>t.map(t=>t.resolved?t:{...t,subGroup:[e].concat(...t.subGroup??[])}))}return{order:l,report:p}}({disableHeadToHead:d,participantIds:n,matchUpFormat:r,groupTotals:u,tallyPolicy:i,attribute:t,idsFilter:a,matchUps:o,reversed:e}),s.push(c.report),!c.order)),c.order?{order:c.order,report:s}:{order:n?.map(t=>({participantId:t})),report:s}}function aS({policyDefinitions:t,generateReport:e,pressureRating:n,matchUpFormat:r,matchUps:i=[],subOrderMap:o,perPlayer:s}){if(!i?.length||!Lf(i))return{error:Ie};const c=M(i.map(({structureId:t})=>t));if(1!==c.length)return Ci({result:{error:sr,info:"Maximum one structureId"},stack:"tallyParticipantResults",context:{structureIds:c}});const u=i.filter(t=>t&&t.matchUpStatus!==Sp),d=u.length&&M(u.flatMap(({drawPositions:t})=>t)).length,p=u.filter(t=>_g({matchUp:t})).length===u.length;p||(s=0);const l=i.every(({matchUpType:t,tieMatchUps:e})=>t===a&&e?.every(t=>_g({matchUp:t}))),m=t?.[Ru],f=i.filter(t=>_g({matchUp:t})??t.matchUpType===a),{participantResults:h}=BI({matchUps:f,pressureRating:n,matchUpFormat:r,tallyPolicy:m,perPlayer:s});let g,I;const{groupOrder:S,report:y}=iS({matchUps:f,participantResults:h,participantsCount:d,matchUpFormat:r,subOrderMap:o,tallyPolicy:m});if(n&&function({participantResults:t}){const e=t=>t.reduce((t,e)=>t+parseFloat(e),0),n=t=>parseFloat((e(t)/t.length).toFixed(2)),r=Object.keys(t).map(e=>{const r=t[e],{pressureScores:i}=r;return{participantId:e,averagePressure:i?.length?n(i):0}}).sort((t,e)=>(e.averagePressure||0)-(t.averagePressure||0)).map((t,e)=>({...t,order:e+1}));for(const e of r)t[e.participantId].pressureOrder=e.order}({participantResults:h}),p&&S)g=y,I=S,S.forEach(t=>{const{participantId:e,groupOrder:n,rankOrder:r,subOrder:i,ties:o,GEMscore:a}=t,s=h[e];Object.assign(s,{groupOrder:n,rankOrder:r,GEMscore:a,subOrder:i,ties:o})});else{const{groupOrder:t,report:e}=iS({requireCompletion:!1,participantResults:h,participantsCount:d,matchUpFormat:r,tallyPolicy:m,subOrderMap:o,matchUps:i});g=e,I=t,t&&t.forEach(t=>{const{participantId:e,groupOrder:n,subOrder:r,ties:i,GEMscore:o}=t,a=h[e];Object.assign(a,{provisionalOrder:n,GEMscore:o,subOrder:r,ties:i})})}const v={completedTieMatchUps:l,readableReport:"",participantResults:h,bracketComplete:p,order:[],report:g};if((p||l)&&(v.order=I),e||$r({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)=>{ZI(t,e,r,i)}),i.push("Final Order:"),e.forEach(t=>{const{participantId:e,resolved:n}=t,o=t.groupOrder||t.provisionalOrder;i.push(`${o}: ${r[e]} => resolved: ${!!n}`)}),i.join("\r\n")}({matchUps:i,report:g,order:I});$r({tally:!0})&&console.log(t),v.readableReport=t}return v}function sS({publishedSeeding:t,usePublishState:e,withSeeding:n,participant:r,event:i}){const o={},a=t=>[yu,vu,i.eventType,t].join("."),s=Object.assign({},...(r.timeItems??[]).filter(({itemType:t})=>t.split(".")[1]===vu).map(({itemType:t,itemValue:e})=>({[t]:e}))),c=(t?.stageSeedingScaleNames&&Object.values(t?.stageSeedingScaleNames)||Array.isArray(t?.seedingScaleNames)&&t.seedingScaleNames||[]).map(a),u=V(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=a(t.stageSeedingScaleNames[e]);return[e,s[n]]}).filter(t=>t[1]).map(t=>({[t[0]]:{seedValue:t[1]}})),n=Object.assign({},...e);o.seedAssignments=n}else if(u){const t=u.map(t=>s[t]);o.seedValue=t.pop()}}else if(e||"object"!=typeof n){const{categoryName:n,ageCategoryCode:a}=i.category??{},s=[a,i.eventId,n].filter(Boolean);let c;for(const t of s){const e=Vd({scaleAttributes:{eventType:i.eventType,scaleType:vu,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;o.seedValue=t}}}else{const t=Object.keys(n).map(t=>{const e=a(n[t]);return[t,s[e]]}).filter(t=>t[1]).map(t=>({[t[0]]:{seedValue:t[1]}})),e=Object.assign({},...t);o.seedAssignments=e}return o}function cS({positionAssignments:t}){const e=(t??[]).filter(eI(Pc)).map(t=>{const e=p(dp({element:t,attribute:"subOrder",name:Dd})),n=!isNaN(e)&&e;return n&&{participantId:t.participantId,subOrder:n}}).filter(Boolean),n=C(e.map(({subOrder:t})=>t));return{subOrderMap:Object.assign({},...e.filter(({subOrder:t})=>1===n[t]).map(({participantId:t,subOrder:e})=>({[t]:e})))}}function uS({convertExtensions:t,seedAssignments:e,participant:n,withSeeding:r,seedValue:i,eventId:o,ranking:a,entry:s}){const{entryStatus:c,entryStage:u,entryPosition:d,extensions:p}=s,l=p?.length&&t?Object.assign({},...ua(p??[])):{},m=Object.assign(l,{entryPosition:d,entryStatus:c,entryStage:u,ranking:a,eventId:o});n.events[o]=Ei(m,!1,!1,!0),r&&(e&&(n.events[o].seedAssignments=e),i&&(n.events[o].seedValue=i))}function dS(t){const e=fu(t,[{[Ic]:!0}]);if(e.error)return e;const{tournamentRecord:n,status:r=Th}=t,i=`${Ph}.${wh}`;return ca(Em({tournamentRecord:n,itemType:i})?.timeItem?.itemValue?.[r],!1,!0)}function pS({event:t,status:e=Th}){const n=`${Ph}.${wh}`;return Am({itemType:n,event:t})?.timeItem?.itemValue?.[e]}function lS({drawDetails:t,drawId:e,ignoreEmbargo:n=!1}){const r=t?.[e]?.publishingDetail;return n?!!r?.published:Cg(r)}function mS(t){const{tournamentRecord:e,drawDefinition:n,eventIds:r,eventId:i,drawIds:o,drawId:a,event:s}=t??{};if(e&&!function(t){const{tournamentId:e}=t??{};return!!e}(e))return{error:sr};if(i&&!s)return{error:zt};if(Array.isArray(r)&&r?.length){const t={};for(const n of r){if(!m(n))return{error:sr};const r=wg({tournamentRecord:e,eventId:n})?.event;if(!r)return{error:zt};const i=gS({event:r});t[n]=i}return{...Y,publishState:t}}if(s)return function({event:t,drawId:e,drawIds:n,drawDefinition:r}){const i=gS({event:t});let o={};if(e)return r?{publishState:{status:{published:!!i.status.publishedDrawIds?.includes(e),drawDetail:i.status.drawDetails?.[e]},...Y}}:{error:ut};if(Array.isArray(n)&&n?.length){const e=t.drawDefinitions?.map(el)??[];for(const t of n){if(!m(t))return{error:sr};if(!e.includes(t))return{error:ut};o[t]={status:{published:!!i.status.publishedDrawIds.includes(t),drawDetail:i.status.drawDetails?.[t]}}}}else o=i;return{...Y,publishState:o}}({event:s,drawId:a,drawIds:o,drawDefinition:n});const c={},{publishedEventIds:u,tournamentPublished:d}=function({publishState:t,tournamentRecord:e}){const n=[];let r=!1;for(const i of e?.events??[]){const e=gS({event:i});t[i.eventId]=e,e.status.published&&(n.push(i.eventId),r=!0);for(const{drawId:n}of i.drawDefinitions??[]){const r=e.status?.publishedDrawIds?.includes(n);r&&(t[n]={status:{published:r}})}}return{publishedEventIds:n,tournamentPublished:r}}({publishState:c,tournamentRecord:e}),p=[];return e&&function({publishState:t,tournamentRecord:e,tournamentPublished:n,publishedEventIds:r,embargoes:i}){const o=dS({tournamentRecord:e});t.tournament=o??{},(o?.orderOfPlay?.published||o?.participants?.published)&&(n=!0);t.tournament.status={published:n,publishedEventIds:r},o?.orderOfPlay?.embargo&&i.push({type:"orderOfPlay",embargo:o.orderOfPlay.embargo,embargoActive:Eg(o.orderOfPlay)});o?.participants?.embargo&&i.push({type:"participants",embargo:o.participants.embargo,embargoActive:Eg(o.participants)})}({tournamentPublished:d,publishedEventIds:u,tournamentRecord:e,publishState:c,embargoes:p}),function({tournamentRecord:t,embargoes:e}){for(const n of t?.events??[]){const t=pS({event:n}),r=t?.drawDetails??{};for(const[t,n]of Object.entries(r))fS({drawId:t,detail:n,embargoes:e})}}({tournamentRecord:e,embargoes:p}),p.length&&(c.embargoes=p),{...Y,publishState:c}}function fS({drawId:t,detail:e,embargoes:n}){e?.publishingDetail?.embargo&&n.push({type:"draw",id:t,embargo:e.publishingDetail.embargo,embargoActive:Eg(e.publishingDetail)});for(const[r,i]of Object.entries(e?.stageDetails??{}))i?.embargo&&n.push({type:"stage",id:`${t}:${r}`,embargo:i.embargo,embargoActive:Eg(i)});for(const[t,r]of Object.entries(e?.structureDetails??{}))r?.embargo&&n.push({type:"structure",id:t,embargo:r.embargo,embargoActive:Eg(r)}),hS({structureId:t,structureDetail:r,embargoes:n})}function hS({structureId:t,structureDetail:e,embargoes:n}){if(e?.scheduledRounds)for(const[r,i]of Object.entries(e.scheduledRounds))i?.embargo&&n.push({type:"scheduledRound",id:`${t}:round${r}`,embargo:i.embargo,embargoActive:Eg(i)})}function gS({event:t}){const e=pS({event:t});if(!e)return{status:{published:!1}};const n={published:void 0,seedingScaleNames:[],drawIds:[]};e.seeding&&Object.assign(n,e.seeding);const r=e.drawDetails??{};for(const e of t.drawDefinitions?.map(el)??[])r[e]||(r[e]={publishingDetail:{published:!1}});const i=r&&Object.keys(r).length&&Object.keys(r).filter(t=>lS({drawDetails:r,drawId:t,ignoreEmbargo:!0})),o=i?.length?i:e.drawIds??[];if(o?.length&&!i?.length)for(const t of o)r[t]={publishingDetail:{published:!0}};return{status:{publishedDrawIds:o,publishedSeeding:n,drawDetails:r,published:o?.length>0}}}function IS(t){const{participantMap:e,participantId:n,matchUpStatus:r,roundPosition:i,structureId:o,matchUpType:a,roundNumber:s,matchUpId:c,potential:u,schedule:d,drawId:p,score:l}=t;if(!d||!Object.keys(d).length)return;r===Sp||e[n].scheduleItems.push({...d,scheduledDate:Lo(d?.scheduledDate),scheduledTime:_o(d?.scheduledTime),checkScoreHasValue:aI({score:l}),matchUpStatus:r,roundPosition:i,structureId:o,matchUpType:a,roundNumber:s,matchUpId:c,potential:u,drawId:p})}function SS({finishingPositionRange:t={winner:[],loser:[]},collectionPosition:e,participantMap:n,finishingRound:r,participantWon:i,collectionId:o,matchUpStatus:a,participantId:s,stageSequence:c,roundNumber:u,structureId:d,matchUpId:p,drawId:l,stage:m}){const f=n[s],h=t=>Math.abs(t[0]-t[1]);f.structureParticipation[d]||(f.structureParticipation[d]={rankingStage:m,walkoverWinCount:0,defaultWinCount:0,stageSequence:c,winCount:0,structureId:d,drawId:l});const g=f.structureParticipation[d],{winner:I,loser:S}=t,y=i?I:S;i&&(g.winCount+=1,a===Ep&&(g.walkoverWinCount+=1),a===Pp&&(g.defaultWinCount+=1)),y&&(!g.finishingPositionRange||h(y)<h(g.finishingPositionRange))&&(g.finishingPositionRange=y),r&&((!g.finishingRound||r<g.finishingRound)&&(g.finishingMatchUpId=p,g.finishingRound=r,g.roundNumber=u),1===r&&(g.participantWon=i)),e&&(g.lineParticipation||(g.lineParticipation=[]),g.lineParticipation.push({collectionPosition:e,collectionId:o,won:i}))}function yS(t){const{withScheduleItems:e,scheduleAnalysis:n,withTeamMatchUps:r,participantMap:i,withOpponents:o,withMatchUps:a,withEvents:s,withDraws:c,finishingPositionRange:u,finishingRound:d,matchUpStatus:p,stageSequence:l,roundNumber:m,structureId:f,score:h,stage:g,withRankingProfile:I,collectionPosition:S,tieWinningSide:y,roundPosition:v,matchUpTieId:U,matchUpSides:P,collectionId:T,matchUpType:w,winningSide:D,matchUpId:R,schedule:b,eventId:N,drawId:M,sides:A}=t,E=o&&2===A?.length&&Object.assign({},...A.map(({sideNumber:t},e)=>{const n=A[1-e].participantId;return t&&{[t]:n}}).filter(Boolean));for(const t of A){const{participantId:A,sideNumber:C,bye:O}=t;if(O)continue;const k=D===C,F=t=>{const e=i[t]?.participant,n=e?.participantType,r=[{participantId:t,participantType:n}];if(n!==hm)for(const t of e?.individualParticipantIds??[]){const e=i[t]?.participant;r.push({participantType:e?.participantType,participantId:t})}return r},x=(t,r)=>{if(a){if(i[t].matchUps[R]={participantWon:k,matchUpType:w,structureId:f,sideNumber:C,matchUpId:R,eventId:N,drawId:M,stage:g},o){const e=F(r);i[t].matchUps[R].opponentParticipantInfo=e}T&&(i[t].matchUps[R].collectionId=T)}o&&r&&(i[t].opponents[r]={participantId:r,matchUpId:R,eventId:N,drawId:M}),I&&D&&SS({finishingPositionRange:u,collectionPosition:S,participantMap:i,participantWon:k,collectionId:T,finishingRound:d,matchUpStatus:p,participantId:t,stageSequence:l,roundNumber:m,structureId:f,matchUpId:R,drawId:M,stage:g}),(n||e)&&IS({participantMap:i,participantId:t,matchUpStatus:p,roundPosition:v,matchUpType:w,roundNumber:m,structureId:f,matchUpId:R,schedule:b,drawId:M,score:h})},_=({participant:t,partnerParticipantId:e})=>{const n=(t,e)=>{t&&(t.partnerParticipantIds??=[],t.partnerParticipantIds.includes(e)||t.partnerParticipantIds.push(e))};c&&n(t?.draws?.[M],e),s&&n(t?.events?.[N],e),a&&n(t?.matchUps?.[R],e)};if(A&&i[A]){const t=E?.[C];x(A,t);const e=i[A]?.participant.participantType===Sm,n=i[A]?.participant.individualParticipantIds??[];U&&vS({individualParticipantIds:n,tieWinningSide:y,withTeamMatchUps:r,participantMap:i,matchUpSides:P,matchUpTieId:U,sideNumber:C,participantId:A,withDraws:c,eventId:N,drawId:M}),e&&US({individualParticipantIds:n,opponentParticipantId:t,participantMap:i,matchUpSides:P,participantId:A,sideNumber:C,withEvents:s,addMatchUp:x,addPartner:_,eventId:N}),D&&PS({individualParticipantIds:n,participantMap:i,participantWon:k,matchUpStatus:p,participantId:A,matchUpType:w})}}}function vS({individualParticipantIds:t,tieWinningSide:e,withTeamMatchUps:n,participantMap:r,matchUpSides:i,matchUpTieId:o,sideNumber:s,participantId:c,withDraws:u,eventId:d,drawId:p}){if(n){const n=t=>r[t].matchUps[o]={participantWon:e===s,matchUpId:o,matchUpType:a,sideNumber:s};n(c),t.forEach(n)}if(u&&!r[c].draws[p]){const e=i.find(t=>t.sideNumber===s)?.participant?.participantId,n=r[e]?.draws?.[p]?.entryStatus,o=t=>r[t].draws[p]={entryStatus:n,eventId:d,drawId:p};o(c),t.forEach(o)}}function US({individualParticipantIds:t,opponentParticipantId:e,participantMap:n,matchUpSides:r,participantId:i,sideNumber:o,withEvents:a,addMatchUp:s,addPartner:c,eventId:u}){if(t.forEach(t=>n[t]&&s(t,e)),t.forEach((e,r)=>{const i=t[1-r],o=n[e];o&&c({participant:o,partnerParticipantId:i})}),a&&r){const e=r.find(t=>t.sideNumber===o)?.participant?.participantId;if(e){const r=n[e]?.events[u];r?(n[i].events[u]={...r},t.forEach(t=>n[t].events[u]={...r})):console.log("Missing teamEntry",{eventId:u,teamParticipantId:e})}}}function PS({individualParticipantIds:t,participantMap:e,participantWon:n,matchUpStatus:r,participantId:i,matchUpType:o}){const a=t=>{n?(e[t].counters[o].wins+=1,e[t].counters.wins+=1,r===Ep&&(e[t].counters[o].walkoverWins+=1,e[t].counters.walkoverWins+=1),r===Pp&&(e[t].counters[o].defaultWins+=1,e[t].counters.defaultWins+=1)):(e[t].counters[o].losses+=1,e[t].counters.losses+=1,r===Ep&&(e[t].counters[o].walkovers+=1,e[t].counters.walkovers+=1),r===Pp&&(e[t].counters[o].defaults+=1,e[t].counters.defaults+=1))};a(i),t.forEach(a)}function TS(t,e){return(t||"").localeCompare(e||"")}function wS(t){const{participantFilters:e,convertExtensions:r,policyDefinitions:o,tournamentRecord:a,usePublishState:s,contextFilters:c,matchUpFilters:u,participantMap:d,contextProfile:p,withPotentialMatchUps:l,withRankingProfile:m,withScheduleItems:f,scheduleAnalysis:h,withTeamMatchUps:g,withStatistics:I,withOpponents:S,withMatchUps:y,withSeeding:v,withEvents:U,withDraws:P}=t,T=e?.participantIds,w=t=>{const e=[t];return d[t]?.participant.individualParticipantIds?.forEach(t=>e.push(t)),e.some(t=>!T?.length||T.includes(t))?e:[]},D={withMatchUps:y||m,withEvents:U||m,withDraws:P||m,withPotentialMatchUps:l,withRankingProfile:m,withScheduleItems:f,scheduleAnalysis:h,withTeamMatchUps:g,withStatistics:I,participantMap:d,withOpponents:S,withSeeding:v},R=[],b={},N=[],M={},A={},E={},C={},O={},k=({eventType:t,scaleNames:e,participantId:n})=>d[n]?.participant?.rankings?.[t]?.find(t=>e.includes(t.scaleName))?.scaleValue;for(const t of a?.events??[])e?.eventIds&&!e.eventIds.includes(t.eventId)||DS({convertExtensions:r,eventsPublishStatuses:M,derivedEventInfo:A,derivedDrawInfo:E,participantMap:d,getRanking:k,withOpts:D,event:t,getRelevantParticipantIds:w,withPotentialMatchUps:l,withRankingProfile:m,withScheduleItems:f,scheduleAnalysis:h,withTeamMatchUps:g,policyDefinitions:o,tournamentRecord:a,withStatistics:I,rrContainerInfo:O,rrGroupMatchUps:C,mappedMatchUps:b,contextFilters:c,matchUpFilters:u,contextProfile:p,withOpponents:S,usePublishState:s,withMatchUps:y,withSeeding:v,withEvents:U,withDraws:P,matchUps:N});const F=function(t,e,n){const r={};if(!n)return r;for(const[n,i]of Object.entries(e)){const{drawDefinition:e,drawId:o}=i,a=e.structures?.find(t=>t.structureType===Ds&&t.stage===us&&1===t.stageSequence);if(!a?.structures)continue;const s=a.structures,c=s.length,u=s.reduce((t,e)=>t+(e.positionAssignments?.length||0),0),d=e.structures?.find(t=>t.stage===ms);r[o]||(r[o]={});for(const i of s)ES({containedStructure:i,rrGroupMatchUps:t,drawPositionsCount:u,containerStructureId:n,bracketsCount:c,playoffStructure:d,drawDefinition:e,drawPositions:r[o]})}return r}(C,O,m);if(I||m||h){const t=function({rrFinishingPositions:t,withRankingProfile:e,scheduleAnalysis:r,withStatistics:o,derivedDrawInfo:a,participantMap:s}){const c=[],u=Object.values(s);for(const d of u){const{wins:u,losses:p,[n]:{wins:l,losses:m},[i]:{wins:f,losses:h}}=d.counters,g=(t,e,n)=>{const r=e+n,i=e,o=r&&i/r;d.statistics[t]={denominator:r,numerator:i,statValue:o,statCode:t}};o&&(g($m,u,p),g(`${$m}.${n}`,l,m),g(`${$m}.${i}`,f,h)),e&&CS({participantAggregator:d,derivedDrawInfo:a,rrFinishingPositions:t}),r&&OS({participantAggregator:d,scheduleAnalysis:r,participantMap:s,participantIdsWithConflicts:c})}return c}({rrFinishingPositions:F,withRankingProfile:m,scheduleAnalysis:h,withStatistics:I,derivedDrawInfo:E,participantMap:d});R.push(...t)}return{participantIdsWithConflicts:R,eventsPublishStatuses:M,derivedEventInfo:A,derivedDrawInfo:E,mappedMatchUps:b,participantMap:d,matchUps:N}}function DS({convertExtensions:t,eventsPublishStatuses:e,derivedEventInfo:n,derivedDrawInfo:r,participantMap:i,getRanking:o,withOpts:a,event:s,getRelevantParticipantIds:c,withPotentialMatchUps:u,withRankingProfile:d,withScheduleItems:p,scheduleAnalysis:l,withTeamMatchUps:m,policyDefinitions:f,tournamentRecord:h,withStatistics:g,rrContainerInfo:I,rrGroupMatchUps:S,mappedMatchUps:y,contextFilters:v,matchUpFilters:U,contextProfile:P,withOpponents:T,usePublishState:w,withMatchUps:D,withSeeding:R,withEvents:b,withDraws:N,matchUps:A}){const{drawDefinitions:E=[],extensions:C=[],wheelchairClass:O,eventType:k,eventName:F,category:x,entries:_,eventId:L,gender:B}=s,{flightProfile:V}=Tg({event:s}),G=V?.flights??[],j=mS({event:s}).publishState;j&&(e[L]=j);const q=j?.status?.publishedSeeding;if(b||R||d){const e=t?Object.assign({},...ua(C??[])):{};n[L]={...e,wheelchairClass:O,eventName:F,eventType:k,category:x,eventId:L,gender:B};const r=[x?.categoryName,x?.ageCategoryCode].filter(Boolean);for(const e of _){const{participantId:n}=e;if(!n||!i[n])continue;const a=o({eventType:k,scaleNames:r,participantId:n});let c,u;if(R){const t=i[n].participant;({seedAssignments:c,seedValue:u}=sS({publishedSeeding:q,usePublishState:w,withSeeding:R,participant:t,event:s}))}const d=n=>{if(i[n]?.events?.[L])return;const r=i[n];uS({convertExtensions:t,seedAssignments:c,participant:r,withSeeding:R,seedValue:u,eventId:L,ranking:a,entry:e})};d(n);(i[n].participant.individualParticipantIds??[]).forEach(d)}}const W=e?.[L]?.publishedSeeding;if(N||d||R){const t=M([...E.map(el),...G.map(el)]);for(const e of t)NS({drawDefinitions:E,participantMap:i,derivedDrawInfo:r,eventPublishedSeeding:W,usePublishState:w,withRankingProfile:d,withSeeding:R,withDraws:N,eventType:k,category:x,eventId:L,flights:G,drawId:e,getRanking:o})}if(d||l||m||g||T||D||N){const t=!!l||u,e=Kg({afterRecoveryTimes:!!l,policyDefinitions:f,tournamentRecord:h,inContext:!0,participantMap:i,contextFilters:v,matchUpFilters:U,contextProfile:P,nextMatchUps:t,event:s})?.matchUps??[];for(const n of e)MS({getRelevantParticipantIds:c,withScheduleItems:p,tournamentRecord:h,drawDefinitions:E,scheduleAnalysis:l,withRankingProfile:d,rrContainerInfo:I,rrGroupMatchUps:S,mappedMatchUps:y,participantMap:i,nextMatchUps:t,withOpts:a,matchUp:n});A.push(...e)}}function RS(t){return t?Object.assign({},...t.map(({participantId:t,seedValue:e,seedNumber:n})=>({[t]:{seedValue:e,seedNumber:n}}))):void 0}function bS({participantMap:t,id:e,participantId:n,eventId:r,eventType:i,drawId:o,mainSeedingMap:a,qualifyingSeedingMap:s,seedingPublished:c,withSeeding:u}){const d=u&&c,p=d?{}:void 0,l=d?a?.[n]?.seedValue||a?.[n]?.seedNumber:void 0,m=l?a?.[n]:void 0,f=d?s?.[n]?.seedValue||s?.[n]?.seedNumber:void 0,h=f?s?.[n]:void 0;p&&l&&(p[us]=m),p&&f&&(p[ds]=h);const g=l||f;return g&&(t[e].participant.seedings[i]||(t[e].participant.seedings[i]=[]),m&&t[e].participant.seedings[i].push({...m,scaleName:o}),h&&t[e].participant.seedings[i].push({...h,scaleName:o}),p&&(t[e].events[r].seedAssignments||(t[e].events[r].seedAssignments={}),Object.keys(p).forEach(n=>t[e].events[r].seedAssignments[n]=p[n]))),{seedAssignments:p,seedValue:g}}function NS({drawDefinitions:t,participantMap:e,derivedDrawInfo:n,eventPublishedSeeding:r,usePublishState:i,withRankingProfile:o,withSeeding:a,withDraws:s,eventType:c,category:u,eventId:d,flights:p,drawId:l,getRanking:m}){const f=t.find(t=>t.drawId===l),h=[u?.categoryName,u?.ageCategoryCode].filter(Boolean),{structures:g=[],drawOrder:I,drawName:S,drawType:y}=f??{},v=p?.find(t=>t.drawId===l),U=f?.entries||v?.drawEntries,P=v?.flightNumber,T=(f?.structures??[]).sort((t,e)=>rl(t,e)).map(({structureId:t,structures:e})=>[t,...(e??[]).map(({structureId:t})=>t)]).flat(1/0);let w,D,R,b,N=0;const M=new Set(g.filter(({stage:t,stageSequence:e})=>t===us&&1===e||t===ds).flatMap(t=>{const{positionAssignments:e}=cl({structure:t}),{seedAssignments:n,stageSequence:r,stage:i}=t;return i===us?(N=e?.length??0,R=e,b=n):1===r&&(w=e,D=n),e}).map(({participantId:t})=>t).filter(Boolean)),A=RS(b),E=RS(D),C=f?U.filter(({participantId:t})=>M.has(t)):U,O=!i||r?.published&&(0===r?.drawIds?.length||r?.drawIds?.includes(l));for(const t of C){if(!e[t.participantId])continue;const{entryStatus:n,entryStage:r,entryPosition:i,participantId:u}=t,p=m({participantId:u,scaleNames:h,eventType:c}),f=t=>{if(!e[t]||e[t].draws?.[l])return;const{seedAssignments:m,seedValue:f}=bS({participantMap:e,id:t,participantId:u,eventId:d,eventType:c,drawId:l,mainSeedingMap:A,qualifyingSeedingMap:E,seedingPublished:O,withSeeding:a});(s||o)&&(e[t].draws[l]=Ei({seedAssignments:m,entryPosition:i,entryStatus:n,entryStage:r,seedValue:f,eventId:d,ranking:p,drawId:l},!1,!1,!0))};if(![pf,lf].includes(n)){f(u);const t=e[u].participant.individualParticipantIds??[];t?.forEach(f)}}const k=(f?.structures??[]).reduce((t,e)=>(t.includes(e.stage)||t.push(e.stage),t),[]),F=(f?.links??[]).length;n[l]={qualifyingPositionAssignments:w,qualifyingSeedAssignments:D,mainPositionAssignments:R,qualifyingSeedingMap:E,mainSeedAssignments:b,orderedStructureIds:T,mainSeedingMap:A,flightNumber:P,linksCount:F,drawOrder:I,drawName:S,drawType:y,drawSize:N,drawId:l,stages:k}}function MS({getRelevantParticipantIds:t,withScheduleItems:e,tournamentRecord:n,drawDefinitions:r,scheduleAnalysis:i,withRankingProfile:o,rrContainerInfo:a,rrGroupMatchUps:s,mappedMatchUps:c,participantMap:u,nextMatchUps:d,withOpts:p,matchUp:l}){const{finishingPositionRange:m,potentialParticipants:f,tieMatchUps:h=[],sides:g=[],winningSide:I,matchUpType:S,matchUpId:y,eventId:v,drawId:U,collectionId:P,containerStructureId:T,stageSequence:w,finishingRound:D,matchUpStatus:R,roundPosition:b,roundNumber:N,structureId:M,schedule:A,score:E,stage:C}=l;if(c[y]=l,o&&T&&M&&U&&(s[M]||(s[M]=[]),s[M].push(l),!a[T])){const t=r.find(t=>t.drawId===U);t&&(a[T]={drawDefinition:t,drawId:U})}const O={finishingPositionRange:m,containerStructureId:T,finishingRound:D,stageSequence:w,roundPosition:b,collectionId:P,roundNumber:N,structureId:M,schedule:A,eventId:v,drawId:U,score:E,stage:C};yS({...O,...p,matchUpStatus:R,winningSide:I,matchUpType:S,matchUpId:y,sides:g});for(const t of h){const{winningSide:e,sides:n=[],matchUpId:r,collectionPosition:i,collectionId:o,matchUpStatus:a,matchUpType:s}=t;yS({...O,...p,winningSide:e,tieWinningSide:I,matchUpTieId:y,matchUpId:r,sides:n,collectionId:o,collectionPosition:i,matchUpSides:g,matchUpStatus:a,matchUpType:s})}Array.isArray(f)&&(d||i||e)&&function({getRelevantParticipantIds:t,potentialParticipants:e,withScheduleItems:n,tournamentRecord:r,scheduleAnalysis:i,participantMap:o,matchUpStatus:a,roundPosition:s,structureId:c,matchUpType:u,roundNumber:d,matchUpId:p,schedule:l,eventId:m,drawId:f,score:h}){const g=e.flat().map(Xp).filter(Boolean);g?.forEach(e=>{const g=t(e);g?.forEach(t=>{o[t]&&(o[t].potentialMatchUps[p]=Ei({tournamentId:r?.tournamentId,matchUpId:p,eventId:m,drawId:f}))}),(i||n)&&IS({potential:!0,participantMap:o,participantId:e,matchUpStatus:a,roundPosition:s,structureId:c,matchUpType:u,roundNumber:d,matchUpId:p,schedule:l,drawId:f,score:h})})}({getRelevantParticipantIds:t,potentialParticipants:f,withScheduleItems:e,tournamentRecord:n,scheduleAnalysis:i,participantMap:u,matchUpStatus:R,roundPosition:b,structureId:M,matchUpType:S,roundNumber:N,matchUpId:y,schedule:A,eventId:v,drawId:U,score:E})}function AS({drawPositionsCount:t,containerStructureId:e,bracketsCount:n,playoffStructure:r,drawDefinition:i,bracketSize:o,order:a}){if(t===o&&a)return[a,a];if(n>1&&a&&!r)return[1,n];if(n>1&&a&&r){const r=i.links?.find(t=>t.source.structureId===e)?.source?.finishingPositions;if(r){const e=r.length*n;if(r.includes(a))return[1,e];return[e+1,t-(o-a)*n]}}}function ES({containedStructure:t,rrGroupMatchUps:e,drawPositionsCount:n,containerStructureId:r,bracketsCount:i,playoffStructure:o,drawDefinition:a,drawPositions:s}){const c=e[t.structureId];if(!c?.length)return;const u=t.positionAssignments?.length,{subOrderMap:d}=cS({positionAssignments:t.positionAssignments}),p=aS({matchUps:c,subOrderMap:d});if(p?.participantResults)for(const[t,e]of Object.entries(p.participantResults)){const c=e.groupOrder||e.provisionalOrder;if(!c)continue;const d=AS({drawPositionsCount:n,containerStructureId:r,bracketsCount:i,playoffStructure:o,drawDefinition:a,bracketSize:u,order:c});d&&(s[t]=d)}}function CS({participantAggregator:t,derivedDrawInfo:e,rrFinishingPositions:n}){const r=(t=[])=>Math.abs(t[0]-t[1]);for(const i of Object.keys(t.draws)){const{orderedStructureIds:o=[],flightNumber:a}=e[i]??{};if(!t.structureParticipation||!o.length)continue;let s,c=0;const u=o.map(e=>{const n=t.structureParticipation[e];if(!n)return;s||(s=n?.finishingPositionRange),r(s)>r(n?.finishingPositionRange)&&(s=n?.finishingPositionRange);const i=n.stage!==ds;i&&(c+=1);const o=i?c:void 0;return Ei({...n,participationOrder:o,flightNumber:a})}).filter(Boolean);if(t.draws[i]){const e=t.participant.participantId,r=n[i]?.[e];r&&(s=r),t.draws[i].finishingPositionRange=s,t.draws[i].structureParticipation=u}}}function OS({participantAggregator:t,scheduleAnalysis:e,participantMap:n,participantIdsWithConflicts:r}){const i=t.scheduleItems??[],o=t.potentialMatchUps??{};t.scheduleConflicts=function({scheduleItems:t,potentialMatchUps:e,scheduleAnalysis:n}){const r=f(n)?n.scheduledMinutesDifference:0,i={},o=t.reduce((t,e)=>{const{scheduledDate:n,scheduledTime:r}=e;return t[n]||(t[n]=[]),r&&t[n].push(e),t},{});Object.values(o).forEach(t=>t.sort(jo));for(const n of t){const{typeChangeTimeAfterRecovery:t,timeAfterRecovery:a,scheduledDate:s,scheduledTime:c}=n,u=o[s],d=Fo(c);for(const o of u){if(o.matchUpId===n.matchUpId||II(o.matchUpStatus)&&!o.checkScoreHasValue)continue;const s=n.matchUpType!==o.matchUpType&&t||a,c=n.drawId===o.drawId,u=e[n.matchUpId]&&e[o.matchUpId],p=Fo(o.scheduledTime),l=Math.abs(p-d),m=p>=d;!(r&&!Number.isNaN(r)?l<=r:m&&Fo(o.scheduledTime)<Fo(s))||u&&c||!m||(i[[n.matchUpId,o.matchUpId].sort(TS).join("|")]={priorScheduledMatchUpId:n.matchUpId,matchUpIdWithConflict:o.matchUpId})}}return i}({scheduleAnalysis:e,scheduleItems:i,potentialMatchUps:o});const a=t.participant.participantId;Object.keys(t.scheduleConflicts).length&&r.push(a),n[a].scheduleConflicts=t.scheduleConflicts}function kS({participantFilters:t={},tournamentRecord:e,participants:n=[]}){if(!Object.keys(t).length)return n;const{accessorValues:r,drawEntryStatuses:i,positionedParticipants:o,eventEntryStatuses:a,participantRoles:s,participantRoleResponsibilities:c,participantTypes:u,participantIds:d,signInStatus:p,enableOrFiltering:l,eventIds:m,genders:f}=t,h=FS(m)&&e?.events?.filter(t=>m?.includes(t.eventId))||e?.events||[],g=i&&function({drawEntryStatuses:t,tournamentEvents:e}){const n=({entryStatus:e})=>!Array.isArray(t)||t.includes(e);return M(e.reduce((t,e)=>{const{flightProfile:r}=Tg({event:e}),i=r?.flights?.flatMap(({drawEntries:t})=>Array.isArray(t)?t.filter(n).map(Xp):[])??[],o=e.drawDefinitions?.map(({entries:t})=>t?t.filter(n).map(Xp):[])??[];return t.concat(...i,...o)},[]))}({drawEntryStatuses:i,tournamentEvents:h}),I=a&&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(Xp);return e.concat(...r)},[]))}({eventEntryStatuses:a,tournamentEvents:h}),S=void 0!==o&&[!0,!1].includes(o)&&h.reduce((t,e)=>t.concat(...(e.drawDefinitions??[]).map(t=>sl({drawDefinition:t}).allPositionedParticipantIds).filter(Boolean)),[]),y=t=>r?.reduce((e,n)=>{const{accessor:r,value:i}=n,{values:o}=Bd({element:t,accessor:r});return e&&o?.includes(i)},!0);if(n=n?.filter(t=>{const e=Nm({element:t,itemType:om})?.timeItem?.itemValue,{participantRoleResponsibilities:n,participantType:i,participantRole:a,participantId:m,person:h}=t,v=Array.isArray(f)&&f?.length&&h?.sex&&f.includes(h.sex);return l?f&&v||o&&S.includes(m)||!1===o&&!S.includes(m)||g?.includes(m)||I?.includes(m)||d?.includes(m)||p&&e===p||u&&i&&FS(u)&&u.includes(i)||s&&a&&FS(s)&&s.includes(a)||c&&FS(n)&&FS(c)&&c.find(t=>n?.includes(t))||r?.length&&FS(r)&&y(t):(!f||v)&&(void 0===o||o&&S.includes(m)||!1===o&&!S.includes(m))&&(!g||g.includes(m))&&(!I||I.includes(m))&&(!d||d.includes(m))&&(!p||e===p)&&(!u||i&&FS(u)&&u.includes(i))&&(!s||a&&FS(s)&&s.includes(a))&&(!c||FS(n)&&FS(c)&&c.find(t=>n?.includes(t)))&&(!r?.length||FS(r)&&y(t))}),h.length&&m){const t=new Set(h.filter(t=>m.includes(t.eventId)).flatMap(t=>{const n=(t.entries??[]).map(t=>t.participantId);if(bh(ts)(t.eventType))return n;const r=(e?.participants??[]).filter(t=>n.includes(t.participantId)).flatMap(t=>t.individualParticipantIds);return n.concat(...r)}));n=n?.filter(e=>t.has(e.participantId))}return n}function FS(t){return t&&Array.isArray(t)&&t.length}function xS(t){const{withIndividualParticipants:e,participantFilters:n={},withPotentialMatchUps:r,withRankingProfile:i,convertExtensions:o,policyDefinitions:a,withScheduleItems:s,tournamentRecord:c,scheduleAnalysis:u,withSignInStatus:d,withTeamMatchUps:p,withScaleValues:l,usePublishState:m,withStatistics:h,contextFilters:g,matchUpFilters:I,contextProfile:S,withOpponents:y,withMatchUps:v,internalUse:U,withSeeding:P,withEvents:T,withDraws:w,withISO2:D,withIOC:R}=t;if(!c)return Ci({stack:"getParticipants",result:{error:rt}});(v||i)&&iI({tournamentRecord:c});const b=Fm({convertExtensions:o,tournamentRecord:c,withSignInStatus:d,withScaleValues:l,internalUse:U,withISO2:D,withIOC:R});let{participantMap:N}=b;const M=wS({withMatchUps:v??i,withEvents:T??i,withDraws:w??i,withPotentialMatchUps:r,participantFilters:n,withRankingProfile:i,convertExtensions:o,withScheduleItems:s,policyDefinitions:a,tournamentRecord:c,scheduleAnalysis:u,withTeamMatchUps:p,usePublishState:m,withStatistics:h,contextFilters:g,matchUpFilters:I,participantMap:N,withOpponents:y,contextProfile:S,withSeeding:P}),{participantIdsWithConflicts:A,eventsPublishStatuses:E,derivedEventInfo:C,derivedDrawInfo:O,mappedMatchUps:k}=M,F=M.matchUps;N=M.participantMap;const x=u??r,_=({potentialMatchUps:t,scheduleConflicts:e,scheduleItems:n,participant:r,statistics:o,opponents:a,matchUps:c,events:d,draws:p})=>{const l=Object.values(p),m=Object.values(a);return y&&l?.forEach(t=>{t.opponents=m.filter(e=>e.drawId===t.drawId)}),Ei({...r,scheduleConflicts:u?Object.values(e):void 0,draws:w||i?l:void 0,events:T||i?Object.values(d):void 0,matchUps:v||i?Object.values(c):void 0,opponents:y?m:void 0,potentialMatchUps:x?Object.values(t):void 0,statistics:h?Object.values(o):void 0,scheduleItems:s?n:void 0},!1,!1,!0)},L=new Map;for(const t of Object.keys(N))L.set(t,_(N[t]));const B=[...L.values()],V=a?.[Eu],G=V?.participant,j=kS({participants:B,participantFilters:n,tournamentRecord:c});if(e){const t=f(e)?e:void 0;for(const e of j)for(const n of e.individualParticipantIds??[]){e.individualParticipants??=[];const r=L.get(String(n)),i=t?Tu({template:t,source:r}):r;e.individualParticipants.push(i)}}const q=G?j.map(t=>Tu({source:t,template:G})):j;return{participantMap:!1!==t.returnParticipantMap?N:void 0,mappedMatchUps:!1!==t.returnMatchUps?k:void 0,matchUps:!1!==t.returnMatchUps?F:void 0,missingParticipantIds:b.missingParticipantIds,participantIdsWithConflicts:A,eventsPublishStatuses:E,derivedEventInfo:C,derivedDrawInfo:O,participants:q,...Y}}function _S(t){const{tournamentRecord:e,scaleAttributes:n,participantId:r}=t,i=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!r)return{error:sn};const{participant:o,tournamentId:a}=Rm({tournamentRecords:i,tournamentRecord:e,participantId:r});return o?{...Vd({participant:o,scaleAttributes:n}),tournamentId:a}:{error:un}}function LS(t,e){return Number(Lo(e).split("-")[0])-t}function BS(t,e){const n=new Date(Lo(t)),r=new Date(Lo(e));let i=r.getFullYear()-n.getFullYear();const o=r.getMonth()-n.getMonth();return(o<0||0===o&&r.getDate()<n.getDate())&&i--,i}function VS(t,e,n){return!(void 0!==e&&t<e)&&!(void 0!==n&&t>n)}function GS(t){const e=t.person;if(!e)return t.participantOtherName||t.participantName||"Unknown";return[e.standardGivenName||e.passportGivenName,e.standardFamilyName||e.passportFamilyName].filter(Boolean).join(" ")||t.participantOtherName||t.participantName||"Unknown"}function jS(t,e,n,r,i,o){const a=function(t,e,n,r){if(function(t){return/^C\d{1,2}-\d{1,2}$/.test(t.ageCategoryCode||"")}(e))return{valid:!0};let i=e.ageMin,o=e.ageMax;if(e.ageCategoryCode&&!i&&!o){const t=Xo({consideredDate:n,category:e});t.error||(i=t.ageMin,o=t.ageMax)}if(!i&&!o)return{valid:!0};const a=t.person?.birthDate,s=t.person?.birthYear;if(!a&&void 0===s)return{valid:!1,reason:"Missing birthDate or birthYear",details:{requiredMin:i,requiredMax:o}};const c=a?{birthDate:a}:{birthYear:s},u=a?BS(a,n):LS(s,n),d=a?BS(a,r):LS(s,r),p=VS(u,i,o),l=VS(d,i,o);if(!p)return{valid:!1,reason:`Age ${u} at event start (${n}) outside range [${[void 0===i?null:`min: ${i}`,void 0===o?null:`max: ${o}`].filter(Boolean).join(", ")}]`,details:{...c,ageAtStart:u,ageAtEnd:d,requiredMin:i,requiredMax:o}};if(!l)return{valid:!1,reason:`Age ${d} at event end (${r}) outside range [${[void 0===i?null:`min: ${i}`,void 0===o?null:`max: ${o}`].filter(Boolean).join(", ")}]`,details:{...c,ageAtStart:u,ageAtEnd:d,requiredMin:i,requiredMax:o}};return{valid:!0}}(t,e,r,i),s=function(t,e,n,r){if(!e.ratingMin&&!e.ratingMax)return{valid:!0};if(!e.ratingType)return{valid:!0};const i={scaleType:"RATING",scaleName:e.ratingType,eventType:n.eventType},{scaleItem:o}=_S({tournamentRecord:r,participantId:t.participantId,scaleAttributes:i});if(!o?.scaleValue)return{valid:!1,reason:`Missing ${e.ratingType} rating`,details:{ratingType:e.ratingType,requiredMin:e.ratingMin,requiredMax:e.ratingMax}};let a;if("object"==typeof o.scaleValue){const t=Bd({element:o.scaleValue,accessor:o.scaleValue?.accessor});if(void 0===t)return{valid:!1,reason:`Cannot extract rating value from ${e.ratingType} scale item`,details:{ratingType:e.ratingType,requiredMin:e.ratingMin,requiredMax:e.ratingMax}};a=t}else a=o.scaleValue;return void 0!==e.ratingMin&&a<e.ratingMin?{valid:!1,reason:`${e.ratingType} rating ${a} below minimum ${e.ratingMin}`,details:{ratingType:e.ratingType,ratingValue:a,requiredMin:e.ratingMin,requiredMax:e.ratingMax}}:void 0!==e.ratingMax&&a>e.ratingMax?{valid:!1,reason:`${e.ratingType} rating ${a} above maximum ${e.ratingMax}`,details:{ratingType:e.ratingType,ratingValue:a,requiredMin:e.ratingMin,requiredMax:e.ratingMax}}:{valid:!0}}(t,e,n,o);if(!a.valid||!s.valid){const e={participantId:t.participantId,participantName:GS(t),rejectionReasons:[]};return a.valid||e.rejectionReasons.push({type:"age",reason:a.reason,details:a.details??{}}),s.valid||e.rejectionReasons.push({type:"rating",reason:s.reason,details:s.details??{}}),e}return null}function qS({participantId:t,drawDefinition:e,entryStatus:n,entryStage:r}){if(!e)return{error:st};const i=e.entries?.find(e=>!(e.participantId!==t||n&&n!==e.entryStatus||r&&r!==e.entryStage));return t&&i}function WS({stage:t,drawDefinition:e}){return Boolean(t===ls||function({stage:t,drawDefinition:e}){if(!fs.includes(t))return!1;const n=e?.structures?.some(e=>e.stage===t);return n||fs.includes(t)}({stage:t,drawDefinition:e}))}function $S(t){const{provisionalPositioning:e,drawDefinition:n,structureId:r}=t;if(!n)return{error:st};const i={};if(!r)return{qualifiersCount:0,roundQualifiersCounts:i};const{structure:o}=ol({drawDefinition:n,structureId:r}),a=n.links?.filter(t=>t?.target?.structureId===o?.structureId);let s=0;return a?.length&&(s=function({relevantLinks:t,drawDefinition:e,provisionalPositioning:n,roundQualifiersCounts:r}){let i=0;for(const o of t){const t=ol({structureId:o.source.structureId,drawDefinition:e})?.structure;if(t?.stage===ds){const e=o.source.roundNumber,a=o.target.roundNumber;let s;if(t.structureType===Ds)s=(t.structures?.length??0)*(o.source.finishingPositions?.length??0);else if(0===e&&o.source.qualifyingPositions)s=o.source.qualifyingPositions;else{const r=Fg({matchUpFilters:{roundNumbers:[e]},structure:t,afterRecoveryTimes:!1,provisionalPositioning:n,inContext:!1}).matchUps;s=r?.length||0}r[a]||(r[a]=0),r[a]+=s,i+=s}}return i}({relevantLinks:a,drawDefinition:n,provisionalPositioning:e,roundQualifiersCounts:i})),{qualifiersCount:s,roundQualifiersCounts:i}}function HS({stage:t,drawDefinition:e,stageSequence:n,tournamentRecord:r,event:i}){const o=e?.structures?.filter(e=>e.stage===t&&(!n||e.stageSequence===n));if(o?.length)return o.reduce((t,e)=>e.structureType===Ds?t+(e.structures?.reduce((t,e)=>t+(e.positionAssignments?.length??0),0)??0):t+(e.positionAssignments?.length??0),0);if(t===us&&r){const{constraints:t}=Xm({tournamentRecord:r,event:i});if(t?.drawSize)return t.drawSize}return 0}function zS({entryStatus:t=rf,tournamentRecord:e,drawDefinition:n,stageSequence:r,event:i,stage:o}){const{constraints:a}=Xm({tournamentRecord:e,event:i});if(t===ef){if(!a)return{positionsAvailable:1/0,...Y};if(void 0===a.maxAlternates)return{positionsAvailable:1/0,...Y};const t=Uf({entryStatus:ef,drawDefinition:n,stage:o});return t<a.maxAlternates?{positionsAvailable:a.maxAlternates-t,...Y}:{error:Tn}}const s=n?.structures?.some(t=>t.stage===o);if(!s)return{positionsAvailable:1/0,...Y};const c=function(t){const{provisionalPositioning:e,drawDefinition:n,stageSequence:r,stage:i,tournamentRecord:o,event:a}=t,s=HS({stage:i,drawDefinition:n,stageSequence:r,tournamentRecord:o,event:a}),c=n?.structures?.find(t=>t.stage===i&&(!r||t.stageSequence===r)),{qualifiersCount:u}=$S({structureId:c?.structureId,provisionalPositioning:e,drawDefinition:n});return s&&s-(u??0)}({drawDefinition:n,stageSequence:r,stage:o}),u=Uf({entryStatus:mf,drawDefinition:n,stage:o}),d=u+Uf({entryStatus:rf,drawDefinition:n,stage:o}),p=c-d;if(o!==ls&&(c>0&&d>=c))return{error:Dn};if(t===mf){if(!a)return d<c?{...Y}:{error:Dn};return u<(a.maxWildcards??c)?{...Y}:{error:Dn}}return{positionsAvailable:p,...Y}}const YS=new Set([ks,nc]);function KS(t){return!!t&&YS.has(t)}function QS(t){const e=fu(t,[{[yc]:!0,[Ac]:!0}]);if(e.error)return e;const{suppressDuplicateEntries:n=!0,entryStatus:r=rf,entryStageSequence:i,entryStage:o=us,ignoreStageSpace:a,drawDefinition:s,entryPosition:c,participant:u,roundTarget:d,extensions:p,extension:l,drawType:m,event:f}=t,h="addDrawEntry";if(!KS(m)&&!WS({stage:o,drawDefinition:s}))return Ci({result:{error:Zt},stack:h});const g=zS({stageSequence:i,stage:o,drawDefinition:s,entryStatus:r});if(!(a||g.success||m&&KS(m)))return{error:g.error};if(l&&!Wu({extension:l}))return Ci({result:{error:sr},info:"Invalid extension",context:{extension:l},stack:h});const I=t.participantId||u?.participantId;if(!I)return Ci({result:{error:sn},stack:h});const S=r===sf&&qS({participantId:I,drawDefinition:s,entryStatus:r}),y=o===ls&&qS({participantId:I,drawDefinition:s,entryStage:o}),v=qS({participantId:I,drawDefinition:s}),U=r!==sf&&o!==ls&&v;if(U)return n?(di({payload:{drawId:s.drawId,eventId:f?.eventId,error:Z,participantId:I},topic:Sl}),{...Y}):Ci({result:{error:Z},context:{participantId:I},stack:h});if(S||y)return Ci({context:{invalidEntry:U,invalidLuckyLoser:S,invalidVoluntaryConsolation:y},result:{error:In},stack:h});const P=Ei({entryStageSequence:i,participantId:I,entryPosition:c,entryStatus:r,entryStage:o,extensions:p});return l&&$u({element:P,extension:l}),d&&sp({element:P,attribute:"roundTarget",name:vd,value:d}),s.entries??=[],s.entries.push(P),Ql({drawDefinition:s}),{...Y}}function JS({suppressDuplicateEntries:t=!0,autoEntryPositions:e=!0,entryStageSequence:n,ignoreStageSpace:r,participantIds:i,drawDefinition:o,entryStatus:a,roundTarget:s,entryStage:c,extension:u,drawId:d,event:p}){if(!i?.length)return{error:ln};if(!p)return{error:zt};if(!d)return{error:bt};const l=(p.entries??[]).map(Xp);if(i.filter(t=>!l.includes(t)).length)return{error:Kt};if(o){const d=function(t){const e="addDrawEntries",{suppressDuplicateEntries:n=!0,entryStatus:r=rf,autoEntryPositions:i=!0,ignoreStageSpace:o,participantIds:a,drawDefinition:s,stageSequence:c,stage:u=us,roundTarget:d,extension:p,event:l}=t,m=KS(s.drawType);if(!u)return{error:Xt};if(!s)return{error:st};if(!Array.isArray(a))return{error:tn};if(!m&&!WS({stage:u,drawDefinition:s}))return{error:Zt};if(p&&!Wu({extension:p}))return Ci({result:{error:sr},info:"Invalid extension",context:{extension:p},stack:e});const f=zS({drawDefinition:s,stageSequence:c,entryStatus:r,stage:u});if(!o&&!f.success&&!m)return{error:f.error};const h=f.positionsAvailable??0;if(!o&&!m&&u!==ls&&h<a.length)return{error:Sn};const g=[],I=s.drawId,S=l?.eventId,y=a.reduce((t,e)=>{const i=r===sf&&qS({participantId:e,drawDefinition:s,entryStatus:r}),o=u===ls&&qS({entryStage:u,drawDefinition:s,participantId:e}),a=qS({participantId:e,drawDefinition:s});return r!==sf&&u!==ls&&a&&(g.push(e),n&&di({payload:{error:Z,participantId:e,eventId:S,drawId:I},topic:Sl})),i||o?t.concat(e):t},[]);return g.length&&!n?Ci({context:{eventId:S,drawId:I,duplicateEntries:g},result:{error:Z},stack:e}):(a.filter(t=>t&&!y.includes(t)).forEach(t=>{const e={entryStageSequence:c,entryStage:u,participantId:t,entryStatus:r};p&&$u({element:e,extension:p}),d&&sp({element:e,attribute:"roundTarget",name:vd,value:d}),s.entries??=[],s.entries.push(e)}),i&&(s.entries=NI({entries:s.entries})),Ql({drawDefinition:s}),y?.length||g?.length?{info:"some participantIds could not be added",participantIdsNotAdded:y,duplicateEntries:g,...Y}:{...Y})}({stageSequence:n,suppressDuplicateEntries:t,autoEntryPositions:e,stage:c,ignoreStageSpace:r,participantIds:i,drawDefinition:o,entryStatus:a,roundTarget:s,extension:u});if(d.error)return d}const{flightProfile:m}=Tg({event:p}),f=m?.flights.find(t=>t.drawId===d);return f?.drawEntries&&(i.forEach(t=>{const e=a===sf&&XS({participantId:t,entryStatus:a,flight:f}),n=c===ls&&XS({participantId:t,entryStage:c,flight:f});a!==sf&&c!==ls&&XS({flight:f,participantId:t})||e||n||f.drawEntries.push({participantId:t,entryStatus:a,entryStage:c})}),e&&(f.drawEntries=NI({entries:f.drawEntries}))),{...Y}}function XS({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 ZS({autoEntryPositions:t=!0,participantIds:e=[],entryStatuses:n,stage:r,event:i}){const o="removeEventEntries";if(!i?.eventId)return{error:Ht};if(!Array.isArray(e)||e.some(t=>!m(t)))return Ci({result:{error:Ze},stack:o});const a=(i.drawDefinitions??[]).flatMap(t=>bI({drawDefinition:t}).assignedParticipantIds??[]),s=(n?.length&&i.entries?.filter(t=>t.entryStatus&&n.includes(t.entryStatus))||[]).map(Xp).filter(t=>!a.includes(t)),c=(r&&i.entries?.filter(t=>t.entryStage&&t.entryStage===r)||[]).map(Xp).filter(t=>!a.includes(t));if(e.length?e=e.filter(t=>(!n?.length||s.includes(t))&&(!r||c.includes(t))):s.length&&c.length?e=V(s,c):s.length?e=s:c.length&&(e=c),e?.length&&a.some(t=>e.includes(t)))return Ci({result:{error:gn},stack:o});if(!e?.length)return{...Y,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=NI({entries:i.entries}));const{flightProfile:d}=Tg({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))}),{...Y,participantIdsRemoved:u}}const ty={[Nu]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}};function ey({tournamentRecord:t,participantIds:e,event:r,entryStatus:o,genderEnforced:a,mismatchedGender:s}){return t?.participants?.filter(t=>!!e.includes(t.participantId)&&(function(t,e,r){return bh(n)(e.eventType)&&t.participantType===gm&&!MI(r)}(t,r,o)?function(t,e,n,r){return!(e.gender&&n&&!$i(e.gender)&&!Hi(e.gender)&&zi(e.gender)!==zi(t.person?.sex)&&(r.push({participantId:t.participantId,sex:t.person?.sex}),1))}(t,r,a,s):!!function(t,e,n){return e.eventType===i&&t.participantType===Sm&&!MI(n)}(t,r,o)||(!!function(t,e,n,r,o){return!(e.eventType!==i||t.participantType!==gm||!MI(n)||e.gender&&r&&!$i(e.gender)&&!Hi(e.gender)&&zi(e.gender)!==zi(t.person?.sex)&&(o.push({participantId:t.participantId,sex:t.person?.sex}),1))}(t,r,o,a,s)||(!!function(t,e,n){return e.eventType===ss&&[gm,Sm].includes(t.participantType)&&!MI(n)}(t,r,o)||function(t,e,n){return e.eventType===ym&&(t.participantType===ym||MI(n)&&t.participantType===gm)}(t,r,o))))).map(t=>t.participantId)??[]}function ny(t,e,n,r,i){const o=[];for(const a of t.individualParticipantIds??[]){const t=e.participants?.find(t=>t.participantId===a);if(!t)continue;const s=jS(t,n.category,n,r,i,e);s&&o.push(s)}return o.length?{participantId:t.participantId,participantName:GS(t),rejectionReasons:o.flatMap(t=>t.rejectionReasons.map(e=>({...e,reason:`${t.participantName}: ${e.reason}`})))}:null}function ry(t){return(t.participantType===Sm||t.participantType===ym)&&!!t.individualParticipantIds?.length}function iy({enforceCategory:t,event:e,tournamentRecord:n,typedParticipantIds:r,categoryRejections:i}){if(t&&e.category&&n){const t=function(t,e){const n=t.startDate||e?.startDate,r=t.endDate||e?.endDate;return n&&r?Do(n)&&Do(r)?{startDate:n,endDate:r}:{error:_e}:{error:Ve}}(e,n);if(!("error"in t)){const{startDate:o,endDate:a}=t;return function({typedParticipantIds:t,categoryRejections:e,tournamentRecord:n,startDate:r,endDate:i,event:o}){const a=[];for(const s of t){const t=n.participants?.find(t=>t.participantId===s);if(t)if(o.category){const c=ry(t)?ny(t,n,o,r,i):jS(t,o.category,o,r,i,n);c?e.push(c):a.push(s)}else a.push(s)}return a}({typedParticipantIds:r,tournamentRecord:n,event:e,startDate:o,endDate:a,categoryRejections:i})}}return r}function oy(t){const{suppressDuplicateEntries:e=!0,entryStatus:n=rf,autoEntryPositions:r=!0,enforceCategory:i=!1,enforceGender:o=!0,entryStageSequence:a,policyDefinitions:s,entryStage:c=us,tournamentRecord:u,ignoreStageSpace:d,drawDefinition:p,roundTarget:l,extensions:m,extension:f,drawId:h,event:g}=t,I="addEventEntries",S=function(t,e){if(!Array.isArray(t.participantIds))return Ci({result:{error:tn},stack:e});const n=M(t.participantIds??[]);return t.event?n?.length?t.event?.eventId?{participantIds:n}:{error:zt}:Ci({result:{error:ln},stack:e}):{error:Ht}}(t,I);if("error"in S)return S;const y="participantIds"in S?S.participantIds:[],v=function(t,e,n){return t&&(!Array.isArray(t)||!t.every(t=>Wu({extension:t})))||e&&!Wu({extension:e})?Ci({context:Ei({extension:e,extensions:t}),result:{error:sr},info:"Invalid extension(s)",stack:n}):null}(m,f,I);if(v)return v;const{genderEnforced:U}=function({policyDefinitions:t,tournamentRecord:e,event:n,enforceGender:r}){const i=xd({tournamentRecord:e,event:n}).appliedPolicies??{},o=t?.[Nu]??i?.[Nu]??ty[Nu];return{matchUpActionsPolicy:o,genderEnforced:!1!==(r??o?.participants?.enforceGender)}}({policyDefinitions:s,tournamentRecord:u,event:g,enforceGender:o}),P=[],T=[],w=!!u,D=[];let R,b=ey({tournamentRecord:u,participantIds:y,event:g,entryStatus:n,genderEnforced:U,mismatchedGender:D});const N=[];b=iy({enforceCategory:i,event:g,tournamentRecord:u,typedParticipantIds:b,categoryRejections:N});const A=function({participantIds:t,typedParticipantIds:e,checkTypedParticipants:n}){return t.filter(t=>!n||e.includes(t))}({participantIds:y,typedParticipantIds:b,checkTypedParticipants:w});g.entries??=[];if(function({validParticipantIds:t,existingIds:e,entryStatus:n,entryStage:r,extensions:i,extension:o,roundTarget:a,entryStageSequence:s,addedParticipantIdEntries:c,event:u}){t.forEach(t=>{if(!e.has(t)){const e=Ei({participantId:t,entryStatus:n,entryStage:r,extensions:i});o&&$u({element:e,extension:o}),a&&sp({element:e,attribute:"roundTarget",name:vd,value:a}),s&&(e.entryStageSequence=s),c.push(e.participantId),u.entries?.push(e)}})}({validParticipantIds:A,existingIds:new Set(g.entries.map(t=>t.participantId||t.participant?.participantId)),entryStatus:n,entryStage:c,extensions:m,extension:f,roundTarget:l,entryStageSequence:a,addedParticipantIdEntries:P,event:g}),h&&!MI(c)){const t=JS({participantIds:A,suppressDuplicateEntries:e,autoEntryPositions:r,entryStageSequence:a,ignoreStageSpace:d,drawDefinition:p,entryStatus:n,roundTarget:l,entryStage:c,extension:f,drawId:h,event:g});t.error&&(R=t.error)}!function({tournamentRecord:t,removedEntries:e,event:n}){if(n.eventType&&[rs,os].includes(n.eventType)){const r=new Set((n.entries??[]).map(t=>t.participantId)),i=(n.entries??[]).filter(t=>MI(t.entryStatus)).map(t=>t.participantId),o=new Set((t?.participants??[]).filter(t=>r.has(t.participantId)&&t.participantType&&[Sm,ym].includes(t.participantType)).map(t=>t.individualParticipantIds).flat(1/0)),a=i.filter(t=>o.has(t));a.length&&(e.push(...a),ZS({participantIds:a,autoEntryPositions:!1,event:n}))}}({event:g,tournamentRecord:u,removedEntries:T});if(A.length!==y.length)return Ci({context:Ei({categoryRejections:N.length?N:void 0,mismatchedGender:D.length?D:void 0,gender:g.gender}),result:{error:tn},stack:I});r&&(g.entries=NI({entries:g.entries??[]}));const E=P.length,C=T.length;return Ci({result:{...Y,addedEntriesCount:E,removedEntriesCount:C,...N.length&&{context:Ei({categoryRejections:N})}},stack:I,info:R})}const ay="ADMINISTRATION",sy="COMPETITOR",cy="MEDIA",uy="MEDICAL",dy="OFFICIAL",py="OTHER",ly="SECURITY",my={ADMINISTRATION:ay,CAPTAIN:"CAPTAIN",COACH:"COACH",COMPETITOR:sy,DIRECTOR:"DIRECTOR",HOSPITALITY:"HOSPITALITY",MEDIA:cy,MEDICAL:uy,OFFICIAL:dy,OTHER:py,PHYSIO:"PHYSIO",SECURITY:ly,STRINGER:"STRINGER",SUPERVISOR:"SUPERVISOR",TRAINER:"TRAINER",TRANSPORT:"TRANSPORT",VOLUNTEER:"VOLUNTEER"};function fy({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:n,tournamentRecord:r,suppressErrors:i}){const o="removeIndividualParticipantIds";if(!r)return Ci({result:{error:rt},stack:o});if(!n||!e)return Ci({result:{error:Ae},stack:o});const a=(r.participants??[]).find(t=>t.participantId===n);if(!a)return Ci({result:{error:un},stack:o});if(![ym,Im].includes(a.participantType))return Ci({result:{participantType:a.participantType,error:nn},stack:o});const s=hy({individualParticipantIds:e,groupingParticipant:a,tournamentRecord:r,suppressErrors:i}),{removed:c,error:u}=s;if(u)return Ci({result:s,stack:o});if(t)for(const t of r.events??[]){const e=new Set((t.entries??[]).map(({participantId:t})=>t).filter(Boolean));if(e.has(n)){const n=c?.filter(t=>!e.has(t));oy({participantIds:n,entryStatus:pf,tournamentRecord:r,event:t})}}return c&&di({topic:bl,payload:{tournamentId:r.tournamentId,participants:[a]}}),{...Y,...s}}function hy({individualParticipantIds:t=[],groupingParticipant:e,tournamentRecord:n,suppressErrors:r,mappedMatchUps:i,participants:o}){const a=[];if(!e)return{removed:a};const s=[],c=[];o||({participants:o,mappedMatchUps:i}=xS({withMatchUps:!0,tournamentRecord:n,withEvents:!0}));const u=o?.find(({participantId:t})=>t===e.participantId),d=u?.events?.map(({eventId:t})=>t),p=new Set(t),l=(e.individualParticipantIds??[]).filter(t=>{if(!p.has(t))return s.push(t),!0;const r=function({groupingParticipantEventIds:t,mappedMatchUps:e,participantId:n,participants:r}){const i=r?.find(t=>t.participantId===n)?.matchUps.filter(({eventId:e})=>t.includes(e)).map(({matchUpId:t})=>e?.[t]).filter(({winningSide:t,score:e})=>t||aI({score:e}));return i?.length>0}({groupingParticipantEventIds:d,mappedMatchUps:i,participantId:t,participants:o});return r?(c.push(t),!0):(a.push(t),function({groupingParticipantId:t,tournamentRecord:e,participantId:n}){for(const r of e.events??[])for(const i of r.drawDefinitions??[])gy({drawDefinition:i,groupingParticipantId:t,participantId:n}),Iy({drawDefinition:i,tournamentRecord:e,participantId:n})}({groupingParticipantId:e.participantId,tournamentRecord:n,participantId:t}),!1)});e.individualParticipantIds=l;const m={groupingParticipantId:e.participantId,cannotRemove:c,notRemoved:s,removed:a};return c.length&&!r&&{...m,cannotRemove:c,error:Ke}||m}function gy({drawDefinition:t,groupingParticipantId:e,participantId:n}){const r=dp({element:t,attribute:"lineUps",name:fd}),i=r?.[e];r&&i&&(r[e]=i.filter(t=>t.participantId!==n),sp({element:t,attribute:"lineUps",name:fd,value:r}),Kl({drawDefinition:t}))}function Iy({drawDefinition:t,tournamentRecord:e,participantId:n}){const r=Zg({drawDefinition:t,inContext:!1}).matchUps??[];for(const i of r)for(const r of i.sides??[]){const o=r.lineUp??[];o.find(t=>t.participantId===n)&&(r.lineUp=o.filter(t=>t.participantId!==n),Yl({tournamentId:e?.tournamentId,drawDefinition:t,matchUp:i}))}}function Sy({participantRole:t=sy,individualParticipantIds:e=[],groupingTypes:n=[hm,Im],tournamentRecord:r}){if(!r)return{error:rt};const i=r.participants??[],{participants:o,mappedMatchUps:a}=xS({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}=hy({groupingParticipant:t,individualParticipantIds:e,tournamentRecord:r,mappedMatchUps:a,participants:o});n&&s++}),s?Y:{error:pn}}function yy(t){const e=fu(t,[{[Ic]:!0},{participantIds:!0,[cu]:iu,[Hc]:ln}]);if(e.error)return e;const{addIndividualParticipantsToEvents:n,tournamentRecord:r,participantIds:o}=t,a=r.participants?.length||0;if(!a)return{...Y};const s=(r.events??[])?.filter(({eventType:t})=>t===is).map(t=>t?.drawDefinitions?.map(({drawId:t})=>t)).flat(1/0),c=xS({participantFilters:{participantIds:o},tournamentRecord:r,withDraws:!0}).participants??[],u=s?.length?(t=>V((Qg({matchUpFilters:{drawIds:t,matchUpTypes:[i]},tournamentRecord:r}).matchUps??[]).flatMap(({sides:t})=>t?.map(({participantId:t})=>t??[])).filter(Boolean),o))(s):[],d=c.filter(t=>t.draws?.filter(t=>(!s?.length||!s?.includes(t.drawId))&&t.positionAssignments).length);if(u?.length||d.length)return{error:gn};const p={},l={};for(const t of r.events??[]){const e=ZS({participantIds:o,event:t});if(e.error)return e;p[t.eventId]=e.participantIdsRemoved}r.participants=(r.participants??[]).filter(t=>{const e=o.includes(t.participantId)||t.participantType===Sm&&t.individualParticipantIds?.some(t=>o.includes(t));if(!e&&t.participantType===is&&t.individualParticipantIds?.some(t=>o.includes(t))&&(t.individualParticipantIds=t.individualParticipantIds.filter(t=>!o.includes(t))),e&&n&&t.participantType&&[Sm,ym].includes(t.participantType))for(const e of t.individualParticipantIds??[])o.includes(e)||(l[t.participantId]||(l[t.participantId]=[]),l[t.participantId].push(e));return!e});const m=a-r.participants.length;if(Sy({individualParticipantIds:o,tournamentRecord:r}),n)for(const t of r.events??[]){oy({participantIds:p[t.eventId].map(t=>l[t]??[]).flat(),entryStatus:pf,tournamentRecord:r,event:t})}return m&&di({payload:{participantIds:o,tournamentId:r.tournamentId},topic:yl}),m?{...Y,participantsRemovedCount:m}:{error:Ke}}function vy({selected:t=!0,drawDefinition:e,entryStatuses:n,drawId:r,event:i,stage:o}){let a=i.entries??[];if(r){const{flightProfile:t}=Tg({event:i}),n=t?.flights?.find(t=>t.drawId===r);n?a=n.drawEntries:e.entries&&(a=e?.entries)}const s=a.filter(e=>(!n?.length||!e.entryStatus||n.includes(e.entryStatus))&&(!o||!e.entryStage||e.entryStage===o)&&(!t||e.entryStatus&&Sf.includes(e.entryStatus)));return{entries:a,stageEntries:s}}function Uy({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:i,stage:o,event:a}){const s="destroyGroupEntry",c=dl({tournamentRecord:e,participantId:r,event:a},[Ic,Pc,zc]);if(c.error)return c;if(!a.eventType||![rs,os].includes(a.eventType))return Ci({result:{error:$t},stack:s});const u=e.participants??[],d=u.find(t=>t.participantId===r);if(!d)return Ci({result:{error:un},stack:s});if(!d.participantType||![Sm,hm].includes(d.participantType)||d.participantType===hm&&a.eventType!==os||d.participantType===Sm&&a.eventType!==rs)return{error:nn};const p=(a.entries??[]).find(t=>t.participantId===r);if(!p)return{error:vn};const{stageEntries:l}=vy({selected:!1,drawDefinition:n,drawId:i,event:a,stage:o}),m=l.map(Xp),f=u.filter(({participantId:t})=>m.includes(t)).map(({individualParticipantIds:t})=>t).flat().filter(Boolean),h=d.individualParticipantIds?.filter(t=>1===B(t,f).length);let g,I=ZS({participantIds:[r],event:a});if(I.error)return I;if(h?.length&&(I=oy({participantIds:h,entryStatus:pf,entryStage:p.entryStage,tournamentRecord:e,drawDefinition:n,drawId:i,event:a}),I.error))return I;if(t){yy({participantIds:[r],tournamentRecord:e}).success&&(g=!0)}return{...Y,participantRemoved:g}}function Py({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:i,event:o}){return Uy({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:i,event:o})}function Ty(t){if(!t.tournamentRecord)return{error:rt};const{participantIds:e,...n}=t;let r=0;const i=[];for(const t of e){const e=Uy({participantId:t,...n});e.success&&(r+=1),e.error&&i.push(e.error)}return r?{destroyedCount:r,...Y}:{error:i}}function wy(t){const{tournamentRecord:e,replaceWithBye:n,drawDefinition:r,destroyPair:i,entryStatus:o,matchUpsMap:a,drawId:s}=t,c="removeDrawPositionAssignment",u=wI(t);if(u.error)return Ci({result:u,stack:c});const{participantId:d}=u,{drawPosition:p,event:l,structureId:m}=t,f=xd({tournamentRecord:e,drawDefinition:r,event:l}).appliedPolicies??{};if([ef,ff].includes(o)&&d){const{tournamentRecord:e}=t,{participant:n}=Rm({tournamentRecord:e,participantId:d}),{participantType:a,individualParticipantIds:u}=n??{};if(i&&a===Sm){const t=Py({tournamentRecord:e,drawDefinition:r,participantId:d,event:l});if(t.error)return Ci({result:t,stack:c});u&&AI({participantIds:u,tournamentRecord:e,drawDefinition:r,entryStatus:o,drawId:s,event:l})}else AI({participantIds:[d],tournamentRecord:e,drawDefinition:r,entryStatus:o,drawId:s,event:l})}if(n){const t=SI({tournamentRecord:e,drawDefinition:r,drawPosition:p,structureId:m,matchUpsMap:a,event:l});if(t.error)return Ci({result:t,stack:c})}const{structure:h}=ol({drawDefinition:r,structureId:m});tm({structure:h,drawPositions:[p]});return em({appliedPolicies:f,drawDefinition:r,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:n,drawPosition:p,entryStatus:o,structureId:m}}),u}function Dy(t){return Object.assign(t,{entryStatus:ff}),wy(t)}const Ry=({finishingPosition:t=lc,hasExistingDrawDefinition:e,qualifyingRoundNumber:n,structureAbbreviation:r,seedAssignments:i=[],stageSequence:o=1,qualifyingOnly:a,structureOrder:s,seedingProfile:c,matchUpFormat:u,structureType:d,structureName:p,matchUps:l=[],matchUpType:m,structureId:f,roundOffset:h,roundLimit:g,stageOrder:I,structures:S,tieFormat:y,stage:v})=>{const U={structureId:f??pa(),structureAbbreviation:r,finishingPosition:t,seedAssignments:i,matchUpFormat:u,stageSequence:o,structureName:p};(a||e&&y)&&(U.tieFormat=y),s&&(U.structureOrder=s),d&&(U.structureType=d),c&&("string"==typeof c?U.seedingProfile=c:"object"==typeof c&&"string"==typeof c.positioning&&(U.seedingProfile=c.positioning)),m&&(U.matchUpType=m),h&&(U.roundOffset=h),I&&(U.stageOrder=I),g&&(U.roundLimit=g),v&&(U.stage=v),n&&(U.qualifyingRoundNumber=n);const P=l.flatMap(({drawPositions:t})=>t).filter(Boolean);return S?U.structures=S:(U.matchUps=l,U.positionAssignments=M(P).sort((t,e)=>t-e).map(t=>({drawPosition:t}))),U};function by(t){return m(t)?t.split(" ").map(t=>t.split("").map((t,e)=>e?t.toLowerCase():t.toUpperCase()).join("")).join(" "):t}function Ny(t){return m(t)?by(t.replace(/_/g," ")):""}function My({structureName:t=Ny(ls),structureAbbreviation:e,drawDefinition:n,matchUpType:r,structureId:i}){if(!n)return{error:st};const o=Ry({stage:ls,structureAbbreviation:e,structureName:t,matchUps:[],structureId:i,matchUpType:r});return n.structures??=[],n.structures.push(o),Ql({drawDefinition:n,structureIds:[o.structureId]}),{...Y}}function Ay({positioning:t,size:e}){const n=function({size:t}){const e=[t];let n=t;for(;n/2===Math.floor(n/2);)n/=2,e.push(n);return e.includes(1)||e.push(1),e.sort(d),e.reverse(),e}({size:e}),r=[],i=[],o=t=>t[0],a=(e,n)=>(t&&[vs,Us,Ts].includes(t)&&n%2?(t=>t[t.length-1])(e):o(e))||o(e),s=(t,e)=>{if(t.every(t=>!i.includes(t))){const n=a(t,e);return i.push(n),n}},c=t=>{const e=t.filter(t=>!i.includes(t));if(e.length)return i.push(...e),e},u=(t,e)=>{const n=a(t,e);if(!i.includes(n))return i.push(n),n},p=L(1,e+1);for(const t of n)if(1===t){const t=q(p,2),e=t.map(s).filter(Boolean);e.length&&r.push(e);const n=t.flatMap(c).filter(Boolean);n.length&&r.push(n)}else{const e=q(p,t).map(u).filter(Boolean);e.length&&r.push(e)}return{divisions:n,divisionGroupings:r}}function Ey({drawPositions:t}){if(!t?.length)return{error:yt};const e=[].concat(...(t??[]).map(e=>t.filter(t=>t!==e).map(t=>[e,t]))),n=M(e.map(Cy)).map(t=>t.split("|").map(t=>+t));return{groupMatchUps:e,uniqueMatchUpGroupings:n}}function Cy(t=[]){return Array.isArray(t)&&t.length?[...t].sort(d).join("|"):""}function Oy({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 o=r.slice(0,r.length/2),a=r.slice(r.length/2);r.slice(1).forEach((t,e)=>{o.forEach((t,n)=>{i[e].push([o[n],a[n]])});const n=o.shift(),r=o.pop(),s=a.shift();o=[n,s,...o].filter(Boolean),a=[...a,r].filter(Boolean)});const s=o.shift(),c=o.pop(),u=a.shift();o=[s,u,...o].filter(Boolean),a=[...a,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=>Cy(t.map(t=>t+e))))}const ky={getRoundRobinGroupMatchUps:Ey,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:Cy,groupRounds:Oy};function Fy(t){const{hasExistingDrawDefinition:e,groupNameBase:n="Group",playoffAttributes:r,stageSequence:i=1,structureOptions:o,appliedPolicies:a,qualifyingOnly:s,seedingProfile:c,stage:u=us,matchUpType:d,roundTarget:p,structureId:l,groupNames:m,tieFormat:f,drawSize:h,idPrefix:g,isMock:I,uuids:S}=t,y=t.structureName??r?.[0]?.name??Ny(us),{groupCount:v,groupSize:U}=function({appliedPolicies:t,structureOptions:e,drawSize:n}){let r=e?.groupSize;const i=e?.groupSizeLimit||8,{validGroupSizes:o}=xy({groupSizeLimit:i,drawSize:n}),a=o&&Math.max(...o),s=r&&o?.includes(r);s||(r=r&&r>4||!o?.includes(4)?a:4);const c=Math.ceil(n/r);return{groupSize:r,groupCount:c}}({structureOptions:o,appliedPolicies:a,drawSize:h}),P=pc;let T;const w=L(1,v+1).map(t=>{const r=function({structureOrder:t,matchUpType:e,groupSize:n,drawSize:r,idPrefix:i,isMock:o,uuids:a}){const s=(t-1)*n,c=L(1+s,n+1+s),u=Ey({drawPositions:c}).uniqueMatchUpGroupings??[],d=Oy({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(Cy(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()||pa()}({structureOrder:t,drawPositions:n,roundNumber:s,idPrefix:i,uuids:a}),d={matchUpStatus:s?Ap:Sp,matchUpType:e,finishingPositionRange:{winner:c,loser:c},drawPositions:n,roundNumber:s,matchUpId:u};return o&&(d.isMock=!0),d}}({groupSize:U,structureOrder:t,matchUpType:d,drawSize:h,idPrefix:g,isMock:I});T=Array.isArray(r)?Math.max(...r.map(({roundNumber:t})=>t??0)):0;const i=m?.[t-1]??`${n} ${t}`;return Ry({structureId:S?.pop(),hasExistingDrawDefinition:e,structureType:ws,finishingPosition:P,qualifyingOnly:s,structureOrder:t,structureName:i,tieFormat:f,matchUps:r,stage:u})}),D=Ry({structureId:l??S?.pop(),hasExistingDrawDefinition:e,structureType:Ds,finishingPosition:P,seedingProfile:c,structureName:y,stageSequence:i,structures:w,tieFormat:f,stage:u});return p&&sp({element:D,attribute:"roundTarget",name:vd,value:p}),{structures:[D],maxRoundNumber:T,groupCount:v,links:[],groupSize:U,...Y}}function xy(t){const{groupSizeLimit:e=10,drawSize:n=0}=t??{},r=L(3,e+1).filter(t=>{const e=Math.ceil(n/t),r=e*t-n,i=Math.ceil(n/e),o=Math.ceil(r/e);return(!r||r<t)&&i===t&&i>=3&&o<2});return{...Y,validGroupSizes:r}}function _y(t){const{roundRobinGroupsCount:e,participantsCount:n,cluster:r}=t;if(!R(n))return{seedBlocks:void 0,...Ci({result:{error:sr},context:{participantsCount:n},stack:"getSeedBlocks"})};const i=w(n);if(e){const t=Math.min(e,i),n=[];let r=1;for(L(0,t).forEach(()=>{n.push([r]),r++});r<i;){const e=L(r,r+t);r+=t,n.push(e)}return{...Y,seedBlocks:n}}const o=L(1,i+1),a=[];let s=i/2;for(;s>1;){const t=q(o,s),e=t.length;t.forEach((t,n)=>{let i;const o=n<e/2,s=n%2==0,c=t[0],u=t[t.length-1];i=r&&e>4?8===e?o?u:c:s?c:u:o?c:u,j(t,a)||a.push(i)}),s/=2}const c=o.filter(t=>!a.includes(t));for(;c.length;)c.length%2==0?a.push(c.pop()):a.push(c.shift());const u=L(0,20).map(t=>Math.pow(2,t));u.unshift(1);const d=u.indexOf(i);let p=0;const l=[];return L(0,d).forEach(t=>{l.push(a.slice(p,p+u[t])),p+=u[t]}),{...Y,seedBlocks:l}}function Ly({roundRobinGroupsCount:t,drawSize:e}){const n="getSeedGroups";if(!R(e))return{seedGroups:void 0,...Ci({result:{error:sr},context:{drawSize:e},stack:n})};if(t){if(!R(t))return{seedGroups:void 0,...Ci({context:{roundRobinGroupsCount:t},result:{error:sr},stack:n})};let r=1;return{seedGroups:L(0,Math.floor(e/t)).map(()=>{const e=L(r,r+t);return r+=t,e})}}{const{seedBlocks:n}=_y({participantsCount:e,roundRobinGroupsCount:t});let r=0;return{seedGroups:(n??[]).map(t=>(t??[]).map(()=>(r+=1,r)))}}}function By({roundRobinGroupsCount:t,participantsCount:e}){if(t){const{validGroupSizes:n}=xy({drawSize:e}),r=n?.map(t=>Math.ceil(e/t));if(!r?.includes(t))return Ci({context:{roundRobinGroupsCount:t},result:{error:sr}})}const{seedGroups:n}=Ly({drawSize:e,roundRobinGroupsCount:t}),r=n?.map(t=>Math.min(...t))??[];return{...Y,seedingThresholds:r}}function Vy(t){if(!t)return 1/0;if(R(t))return p(t);const e=t.split("-")[0];return R(e)?p(e):1/0}function Gy({provisionalPositioning:t,returnAllProxies:e,appliedPolicies:n,seedingProfile:r,drawDefinition:i,allPositions:o,structure:a,random:s}){let c=[];if(!a)return{error:jt};const{matchUps:u,roundMatchUps:d}=Fg({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:a}),{seedAssignments:p}=Tf({provisionalPositioning:t,returnAllProxies:e,drawDefinition:i,structure:a}),{positionAssignments:l}=ul({structure:a}),m=l?.length,f=p?.length??0;let h=[];const g=Object.keys(d).map(t=>Number.parseInt(t)).sort((t,e)=>t-e).map(t=>{const e=d[t].map(t=>t.drawPositions).flat(1/0).filter(Boolean),n=e.filter(t=>!h.includes(t));return h=h.concat(...e),n}).filter(t=>t.length).reverse(),I=g.pop()??[],S=I&&Math.min(...I)-1||0;r=r??n?.seeding?.seedingProfile;const y=I?.length||0,v=g.filter(t=>t.filter(t=>t<=f).length),{stage:U,structureType:P,roundLimit:T}=a,w=P===Ds,D=!w&&g?.length,R=!w&&U===ds&&T,b=v.flat(1/0),N=D?b?.length:0,M=o?m:f,A=$f({drawDefinition:i,structure:a,matchUps:u}),E=A?0:!D&&M||M&&b.length<M&&M-b.length||0;if(R){const t=a?.matchUps?a.matchUps.filter(({roundNumber:t})=>t===a.roundLimit).length:0,e=I.length/t;if(!D){const t=Hy(r),n=q(I,e);let i=1;const o=L(0,n[0].length).map(()=>{const t=L(i,i+n.length);return i+=n.length,t});({validSeedBlocks:c}=jy({drawPositionBlocks:n,nonRandom:r?.nonRandom,positioning:t,seedGroups:o,random:s}))}}else if(w){const t=function({seedingProfile:t,structure:e,nonRandom:n,random:r}){const i=e.structures??[],o=i.length,a=cl({structure:e})?.positionAssignments,s=Hy(t),c=a?.length??0,{seedGroups:u}=Ly({roundRobinGroupsCount:o,drawSize:c});return jy({drawPositionBlocks:i.map(t=>cl({structure:t}).positionAssignments?.map(t=>t.drawPosition)),positioning:s,seedGroups:u,nonRandom:n,random:r})}({nonRandom:r?.nonRandom,seedingProfile:r,structure:a,random:s});({validSeedBlocks:c}=t)}else if(D)c=v.map(t=>({seedNumbers:t,drawPositions:t}));else if(A){q(I,2).map((t,e)=>({drawPositions:[t[0]],seedNumbers:[e+1]})).forEach(t=>c.push(t))}if(!w&&!A&&!R){const{blocks:t}=function(t){const{drawPositionOffset:e=0,roundRobinGroupsCount:n,seedNumberOffset:r=0,seedingProfile:i,seedCountGoal:o,baseDrawSize:a}=t;let s;const c=[],{seedBlocks:u}=_y({cluster:[vs,Us].includes(Hy(i)),participantsCount:a,roundRobinGroupsCount:n});s=0;for(const t of u){if(s+1>o)break;const n=t.map(t=>t+e),i=qy(s+1,t.length).map(t=>+t+r);s+=t.length,c.push({drawPositions:n,seedNumbers:i})}return{blocks:c}}({drawPositionOffset:S,seedNumberOffset:N,seedCountGoal:E,seedingProfile:r,baseDrawSize:y});t.forEach(t=>c.push(t))}const C=c.flatMap(t=>t.drawPositions).reduce((t,e)=>I?.includes(e)&&t,!0);return A||D||w||C?{isLuckyStructure:A,validSeedBlocks:c,isContainer:w,isFeedIn:D}:{error:xt,validSeedBlocks:[],isContainer:w,isFeedIn:D}}function jy({drawPositionBlocks:t,positioning:e,seedGroups:n,nonRandom:r,random:i}){const o=[],{divisionGroupings:a}=Ay({size:n.length,positioning:e}),s=[];return n.forEach((n,c)=>{const u=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:c});n.forEach((n,a)=>{const d=c%2?t.length-a-1:a;let p=t[d].slice().filter((t,e)=>u.includes(e+1)&&t);e!==Ts?p=r?p:A(p,i):c%2&&p.reverse();const l=p.find(t=>!s.includes(t));l&&(s.push(l),o.push({drawPositions:[l],seedNumbers:[n]}))})}),{validSeedBlocks:o}}function qy(t,e){return Array.from(new Array(e),(e,n)=>n+t)}function Wy({appliedPolicies:t,drawDefinition:e,seedBlockInfo:n,drawPosition:r,structureId:i,seedNumber:o}){const{structure:a}=ol({drawDefinition:e,structureId:i});t??=xd({drawDefinition:e}).appliedPolicies;let s=n?.validSeedBlocks;if(!s&&a&&(s=Gy({appliedPolicies:t,drawDefinition:e,structure:a})?.validSeedBlocks),t?.seeding?.validSeedPositions?.ignore)return!0;if(t?.seeding?.validSeedPositions?.strict){const t=s.find(t=>t.seedNumbers.includes(o));return(t?.drawPositions??[]).includes(r)}return s.flatMap(t=>t.drawPositions).includes(r)}function $y(t){const{provisionalPositioning:e,drawDefinition:n,seedingProfile:r,seedBlockInfo:i,structureId:o,randomize:a,random:s}=t,{structure:c}=ol({drawDefinition:n,structureId:o}),{seedAssignments:u}=Tf({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,drawDefinition:n,structure:c}),{positionAssignments:d}=ul({structure:c}),p=d?.filter(t=>t.participantId??t.bye??t.qualifier),l=p?.map(t=>t.drawPosition).filter(Boolean),{appliedPolicies:m}=xd({drawDefinition:n}),f=((i?.validSeedBlocks||c&&Gy({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,appliedPolicies:m,drawDefinition:n,seedingProfile:r,structure:c})?.validSeedBlocks)??[]).find(t=>t.drawPositions.filter(t=>!l?.includes(t)).length),h=u?.map(t=>t.participantId).filter(Boolean),g=d?.map(t=>t.participantId).filter(Boolean),I=h?.filter(t=>g?.includes(t)),S=h?.filter(t=>!g?.includes(t)),y=u?.filter(t=>S?.includes(t.participantId)),v=u?.filter(t=>!t.participantId),U=(y?.length&&y.length>0?y.length:v?.length??0)&&f?.drawPositions.filter(t=>!l?.includes(t))||[],P=a?A(U,s):U,T=[],w=P.map(()=>{const t=function(t,e){const n=t.filter(t=>!e.includes(t.participantId)),r=Math.min(...n.map(t=>Vy(t.seedValue))),i=n.filter(t=>Vy(t.seedValue)===r);return A(i,s).pop()}(y,T),e=t?.participantId;return e&&T.push(e),e}).filter(Boolean),D=u?.filter(t=>I?.includes(t.participantId)).map(t=>t.seedNumber),R=(f?.seedNumbers??[]).filter(t=>!D?.includes(t)),b=u?.filter(t=>R.includes(t.seedNumber)).map(t=>t.participantId),N=m?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:f,unplacedSeedParticipantIds:"boolean"!=typeof N||N?w:b,unplacedSeedNumbers:R,unfilledPositions:P,unplacedSeedAssignments:y}}function Hy(t){return"string"==typeof t?t:"object"==typeof t?t.positioning:void 0}function zy({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,seedingProfile:r,participantId:i,seedBlockInfo:o,structureId:a,seedNumber:s,seedValue:c,eventId:u,event:d}){const p="assignSeed",{structure:l}=ol({drawDefinition:n,structureId:a}),{positionAssignments:m}=ul({structure:l}),f=Tf({provisionalPositioning:t,drawDefinition:n,structure:l}).seedAssignments,h=f.map(t=>t.seedNumber),g=qS({drawDefinition:n,participantId:i});if(i&&!g)return Ci({result:{error:Ze},context:{participantId:i},stack:p});const I=d?Tg({event:d}).flightProfile?.flights?.length:0,S=I&&I>1,y=m?.find(t=>t.participantId===i),v=y?.drawPosition;if(v){if(!Wy({drawPosition:v,drawDefinition:n,seedBlockInfo:o,structureId:a,seedNumber:s}))return Ci({result:{error:lt},context:{assignedDrawPosition:v},info:"invalid seed position",stack:p})}let U;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||S||(t.seedValue=c??s),U=!0)}),U?(Jl({tournamentId:e?.tournamentId,drawDefinition:n,structure:l,eventId:u}),{...Y}):Ci({result:{error:Ft},stack:p})}function Yy({inContextTargetMatchUp:t,drawPositionSideIndex:e,teamParticipantId:n,tournamentRecord:r,drawDefinition:i,matchUp:o,event:a}){const s=t?.sides?.[e]?.sideNumber,c=s&&o.sides?.find(t=>t.sideNumber===s),u=ca((dp({element:i,attribute:"lineUps",name:fd})??{})[n],!1,!0);if(c)o?.sides?.forEach(t=>{t.sideNumber===s&&(t.lineUp=u)});else{o.sides=[1,2].map(t=>({...o.sides?.find(e=>e.sideNumber===t)??{},sideNumber:t}));const t=o.sides.find(t=>t.sideNumber===s);t&&(t.lineUp=u)}Yl({tournamentId:r?.tournamentId,context:"updateSidLineUp",eventId:a?.eventId,drawDefinition:i,matchUp:o})}function Ky(t){let{sourceMatchUp:e}=t;const{targetMatchUp:n,structure:r,matchUpsMap:i,drawPosition:o}=t,a=n.roundNumber>1&&n.roundNumber-1,s=Nf({structureId:r.structureId,matchUpsMap:i});fI({method:"getPairedPreviousMatchUpIsDoubleExit",color:"brightcyan",keyColors:{structureId:"brightyellow",sourceMatchUpId:"brightmagenta"},structureId:r.structureId?.slice(0,8),targetMatchUpId:n.matchUpId,targetRound:[n.roundNumber,n.roundPosition],previousRoundNumber:a,sourceMatchUpId:e?.matchUpId,sourceStructureId:e?.structureId?.slice(0,8),sourceRound:e?[e.roundNumber,e.roundPosition]:void 0,drawPosition:o,structureMatchUpCount:s?.length}),e&&e.structureId!==r.structureId&&o?(fI({method:"getPairedPreviousMatchUpIsDoubleExit",color:"cyan",info:"cross_structure_sourceMatchUp_resolving_in_target",originalSourceId:e?.matchUpId,originalSourceStructure:e?.structureId?.slice(0,8),targetStructure:r.structureId?.slice(0,8)}),e=s.find(({drawPositions:t,roundNumber:e})=>e===a&&t?.includes(o)),fI({method:"getPairedPreviousMatchUpIsDoubleExit",color:"cyan",info:"resolved_cross_structure_sourceMatchUp",resolvedMatchUpId:e?.matchUpId,resolvedRound:e?[e.roundNumber,e.roundPosition]:void 0,resolvedStatus:e?.matchUpStatus})):!e&&o&&(e=s.find(({drawPositions:t,roundNumber:e})=>e===a&&t?.includes(o)),fI({method:"getPairedPreviousMatchUpIsDoubleExit",color:"cyan",info:"resolved_sourceMatchUp_from_drawPosition",resolvedMatchUpId:e?.matchUpId,resolvedRound:e?[e.roundNumber,e.roundPosition]:void 0,resolvedStatus:e?.matchUpStatus}));const c=e?.roundPosition,u=c%2?1:-1,d=c+u,p=a&&s.find(({roundNumber:t,roundPosition:e})=>t===a&&e===d),l=p?.matchUpStatus,m=[wp,Tp].includes(l);return fI({method:"getPairedPreviousMatchUpIsDoubleExit",color:m?"brightred":"brightgreen",keyColors:{pairedMatchUpId:"brightcyan",isDoubleExit:m?"brightred":"brightgreen"},sourceRoundPosition:c,offset:u,pairedRoundPosition:d,pairedMatchUpId:p?.matchUpId,pairedRound:p?[p.roundNumber,p.roundPosition]:void 0,pairedStatus:l,isDoubleExit:m}),{pairedPreviousMatchUp:p,pairedPreviousMatchUpIsDoubleExit:m}}function Qy({structureId:t,matchUpsMap:e,matchUp:n}){const r=n?.roundPosition,i=r+(r%2?1:-1);return{pairedPreviousMatchUp:Nf({matchUpsMap:e,structureId:t}).find(({roundNumber:t,roundPosition:e})=>t===n?.roundNumber&&e===i)}}function Jy({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:n,matchUpsMap:r,matchUp:i}){const o=t.find(t=>t.matchUpId===n),{pairedPreviousMatchUp:a}=Qy({structureId:o?.structureId,matchUp:o,matchUpsMap:r});if(o&&a){const n=a?.matchUpId,r=t.find(t=>t.matchUpId===n),s=o?.structureId===r?.structureId?o?.roundPosition<r?.roundPosition?1:2:o.structureId===r?.structureId?2:1;i.matchUpStatusCodes=(i.matchUpStatusCodes??[]).map(t=>{const n=m(t)||!isNaN(t)?{code:t}:t;return n.sideNumber===s?{...n,previousMatchUpStatus:e}:n})}}function Xy({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 Zy({inContextDrawMatchUps:t,sourceMatchUpStatus:e,tournamentRecord:n,sourceMatchUpId:r,drawDefinition:i,matchUpStatus:o,drawPosition:s,matchUpsMap:c,matchUpId:u,event:p}){const l="assignMatchUpDrawPosition";c??=bf({drawDefinition:i});const m=t??zg({inContext:!0,drawDefinition:i,matchUpsMap:c}).matchUps??[],f=m.find(t=>t.matchUpId===u),h=f?.structureId,g=i?.structures?.find(t=>t.structureId===h);if(!g)return{error:Vt};const I=c?.drawMatchUps?.find(t=>t.matchUpId===u),S=I?.drawPositions??[],{positionAdded:y,positionAssigned:v,updatedDrawPositions:U}=function({drawPosition:t,drawPositions:e}){let n=!1,r=!!e?.includes(t);return{updatedDrawPositions:r?e??[]:[...e,void 0,void 0].slice(0,2).map(e=>e||r?e:(r=!0,n=!0,t)).sort(d).filter(Boolean),positionAdded:n,positionAssigned:r}}({drawPositions:S,drawPosition:s}),{positionAssignments:P}=cl({drawDefinition:i,structure:g}),T=P?.filter(t=>U.includes(t.drawPosition)),w=T?.find(({bye:t})=>t),D=I?.matchUpStatus&&II(I.matchUpStatus)&&U.filter(Boolean).length<2;o=function({isByeMatchUp:t,matchUpStatus:e,isDoubleExitExit:n,matchUp:r}){return t&&Sp||e||n&&r.matchUpStatus||r?.matchUpStatus&&[wp,Tp].includes(r.matchUpStatus)&&r.matchUpStatus||Ap}({isByeMatchUp:w,matchUpStatus:o,isDoubleExitExit:D,matchUp:I});const R=!(!II(I?.matchUpStatus)||!I?.winningSide);I&&y&&function({updatedDrawPositions:t,sourceMatchUpStatus:e,isPropagatedExit:n,isDoubleExitExit:r,tournamentRecord:i,inContextMatchUp:o,sourceMatchUpId:a,drawDefinition:s,matchUpStatus:c,drawPosition:u,matchUpsMap:d,matchUpId:p,matchUp:l,stack:m}){const f=zg({inContext:!0,drawDefinition:s,matchUpsMap:d}).matchUps??[],h=r&&Xy({inContextDrawMatchUps:f,drawPosition:u,matchUpId:p})||n&&l.winningSide||void 0;l?.matchUpStatusCodes&&Jy({inContextDrawMatchUps:f,sourceMatchUpStatus:e,sourceMatchUpId:a,matchUpsMap:d,matchUp:l});Object.assign(l,{drawPositions:t,winningSide:h,matchUpStatus:n?l?.matchUpStatus:c}),Yl({tournamentId:i?.tournamentId,eventId:o?.eventId,context:m,drawDefinition:s,matchUp:l})}({updatedDrawPositions:U,sourceMatchUpStatus:e,isPropagatedExit:R,isDoubleExitExit:D,tournamentRecord:n,inContextMatchUp:f,sourceMatchUpId:r,drawDefinition:i,matchUpStatus:o,drawPosition:s,matchUpsMap:c,matchUpId:u,matchUp:I,stack:l});const b=jg({inContextDrawMatchUps:m,inContextMatchUp:f,drawDefinition:i,matchUpId:u}),{targetMatchUps:{winnerMatchUp:N,loserMatchUp:M,loserTargetDrawPosition:A},targetLinks:{loserTargetLink:E}}=b,C=function({inContextDrawMatchUps:t,positionAssigned:e,isPropagatedExit:n,tournamentRecord:r,inContextMatchUp:i,drawDefinition:o,matchUpStatus:a,winnerMatchUp:s,drawPosition:c,isByeMatchUp:u,isLuckyDraw:d,matchUpsMap:p,matchUp:l,structure:m}){if(e&&u&&!d){if(s)if([Sp,wp,Tp].includes(a)){const e=Zy({matchUpId:s.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:c,matchUpsMap:p});if(e.error)return e}else{const{structureId:t}=s;t!==m.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(e&&n){if(s){const e=Zy({matchUpId:s.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:c,matchUpsMap:p});if(e.error)return e}}else if(s&&i&&!i.feedRound){const{pairedPreviousMatchUpIsDoubleExit:e}=Ky({targetMatchUp:l,drawPosition:c,matchUpsMap:p,structure:m});if(e){const e=Zy({matchUpId:s.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:c,matchUpsMap:p});if(e.error)return e}}return}({inContextDrawMatchUps:m,positionAssigned:v,isPropagatedExit:R,tournamentRecord:n,inContextMatchUp:f,drawDefinition:i,matchUpStatus:o,winnerMatchUp:N,drawPosition:s,isByeMatchUp:w,isLuckyDraw:qf(i?.drawType),matchUpsMap:c,matchUp:I,structure:g});if(C?.error)return C;I?.matchUpType===a&&function({inContextDrawMatchUps:t,positionAssignments:e,tournamentRecord:n,drawDefinition:r,drawPosition:i,matchUp:o}){const a=t?.find(({matchUpId:t})=>t===o.matchUpId),s=(a?.sides??[]).reduce((t,e,n)=>e.drawPosition===i?n:t,void 0),c=e?.find(t=>t.drawPosition===i)?.participantId;c&&void 0!==s&&Yy({inContextTargetMatchUp:a,drawPositionSideIndex:s,teamParticipantId:c,tournamentRecord:n,drawDefinition:r,matchUp:o})}({inContextDrawMatchUps:m,positionAssignments:P,tournamentRecord:n,drawDefinition:i,drawPosition:s,matchUp:I});const O=function({updatedDrawPositions:t,loserTargetDrawPosition:e,tournamentRecord:n,loserTargetLink:r,drawDefinition:i,structureId:o,isByeMatchUp:a,loserMatchUp:s,matchUpsMap:c,event:u}){if(r?.linkCondition!==Os||2!==t.filter(Boolean).length||a)return;const d=Nf({structureId:o,matchUpsMap:c}),p=d.filter(({drawPositions:e,roundNumber:n})=>1===n&&j(e,t)),l=p.every(({matchUpStatus:t})=>[vp,Np].includes(t));if(l&&s){const{structureId:t}=s,r=SI({drawPosition:e,tournamentRecord:n,drawDefinition:i,structureId:t,matchUpsMap:c,event:u});if(r.error)return r}return}({updatedDrawPositions:U,loserTargetDrawPosition:A,tournamentRecord:n,loserTargetLink:E,drawDefinition:i,structureId:g.structureId,isByeMatchUp:w,loserMatchUp:M,matchUpsMap:c,event:p});return O?.error?O:v?{...Y}:Ci({result:{error:mt},context:{drawPosition:s},stack:l})}function tv({inContextDrawMatchUps:t,drawDefinition:e,assignments:n,matchUpsMap:r,structure:i}){const o=nm({drawDefinition:e})?.containedStructures,a=o?.[i.structureId]?.map(({structureId:t})=>t)??[];a.push(i?.structureId);const s=n?.map(({drawPosition:t})=>t)??[],c=t?.filter(t=>a.includes(t.structureId)&&V(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 ev({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("|"),o=parseInt(i),{assignedParticipantIds:a}=Rg({collectionPosition:o,collectionId:r,lineUp:t});a.forEach(t=>{e[t]||(e[t]=[]),e[t].push({collectionId:r,collectionPosition:o})})}),Object.keys(e).map(t=>({participantId:t,collectionAssignments:e[t]}))}function nv(t){return`${t} must be an array`}function rv({lineUp:t,tieFormat:e}){const n=[];if(!Array.isArray(t))return n.push(nv("lineUp")),{valid:!1,errors:n,error:sr};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(nv("collectionAssignments")),!1):(n.push("Missing participantId"),!1)}),i=M(t.map(Xp)).length===t.length;i||n.push("Duplicated participantId(s)");return{valid:r&&i,errors:n,error:n.length?sr:void 0}}function iv({drawDefinition:t,participantId:e,tieFormat:n,lineUp:r}){if("object"!=typeof t)return{error:st};if("string"!=typeof e)return{error:sn};const i=rv({lineUp:r,tieFormat:n});if(!i.valid)return i;const o=dp({element:t,attribute:"lineUps",name:fd})??{};return o[e]=ev({lineUp:r}),sp({element:t,attribute:"lineUps",name:fd,value:o}),Kl({drawDefinition:t}),{...Y}}function ov({inContextDrawMatchUps:t,inheritance:e=!0,tournamentRecord:n,drawDefinition:r,matchUpsMap:i,assignments:a,structure:s,event:c}){if(!r)return{error:st};const{drawPositions:u,matchUps:d,targetMatchUps:p}=tv({inContextDrawMatchUps:t,matchUpsMap:i,assignments:a,structure:s});for(const t of p)t.matchUpType===o&&(t.sides??[]).forEach((i,o)=>{if(i?.drawPosition&&u?.includes(i.drawPosition)){const a=d.find(({matchUpId:e})=>e===t.matchUpId);if(a?.sides?.[o]){if(delete a.sides[o].lineUp,!1===e){const e=t.tieFormat,n=i.participantId;e&&n&&iv({drawDefinition:r,participantId:n,lineUp:[],tieFormat:e})}Yl({tournamentId:n?.tournamentId,context:"resetLineUps",eventId:c?.eventId,drawDefinition:r,matchUp:a})}}});return{...Y}}function av({provisionalPositioning:t,inContextDrawMatchUps:e,isQualifierPosition:n,sourceMatchUpStatus:r,tournamentRecord:i,drawDefinition:o,seedingProfile:s,participantId:c,seedBlockInfo:u,drawPosition:d,matchUpsMap:p,structureId:l,event:m}){const f="assignDrawPosition";if(!c&&!n)return Ci({result:{error:sn},stack:f});p=p??bf({drawDefinition:o}),e||({matchUps:e}=zg({inContext:!0,drawDefinition:o,matchUpsMap:p}));const h=ol({drawDefinition:o,structureId:l});if(h.error)return Ci({result:h,stack:f});const{structure:g}=h;if(!g)return{error:Vt};if(Hf({structure:g}))return Ci({result:{error:ye},stack:f});const{seedAssignments:I}=Tf({provisionalPositioning:t,drawDefinition:o,structure:g}),S=I?.find(t=>t.participantId===c),y=S?.seedNumber,{appliedPolicies:v}=xd({tournamentRecord:i,drawDefinition:o,structure:g,event:m});if(y){if(!Wy({seedNumber:y,appliedPolicies:v,drawDefinition:o,seedBlockInfo:u,drawPosition:d,structureId:l}))return Ci({result:{error:lt},context:{drawPosition:d},stack:f})}const U=ul({structure:g}).positionAssignments??[],P=U?.find(t=>t.drawPosition===d);if(!P)return Ci({result:{error:Pt},context:{drawPosition:d},stack:f});const T=U?.map(Xp).includes(c);if(T)return Ci({result:{error:gn},context:{drawPosition:d},stack:f});const{containsParticipant:w,containsBye:D}=gI(P);if(D){const t=wI({inContextDrawMatchUps:e,tournamentRecord:i,drawDefinition:o,drawPosition:d,structureId:l,matchUpsMap:p,event:m});if(t.error)return Ci({result:t,stack:f})}if(w&&P.participantId!==c){const{activeDrawPositions:t}=dI({drawDefinition:o,structureId:l});if(t.includes(d))return Ci({result:{error:vt},stack:f});ov({assignments:[P],inContextDrawMatchUps:e,tournamentRecord:i,drawDefinition:o,matchUpsMap:p,structure:g})}P.participantId=c,n&&(P.qualifier=!0),function({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,seedingProfile:r,participantId:i,structureId:o,structure:a,event:s}){const c=a.stage===us&&(!a.stageSequence||a.stageSequence>1);if(!(c||a.stage&&[ps,ms].includes(a.stage)))return;const u=a.stage===ds?ds:us,d=n.structures?.find(t=>t?.stage===u&&1===t?.stageSequence),p=d?.seedAssignments??[],l=p.find(t=>t.participantId===i);l?.participantId&&zy({eventId:s?.eventId,participantId:l.participantId,seedNumber:l.seedNumber,seedValue:l.seedValue,provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,seedingProfile:r,structureId:o,event:s})}({provisionalPositioning:t,tournamentRecord:i,drawDefinition:o,seedingProfile:s,participantId:c,structureId:l,structure:g,event:m}),g.structureType===Ds?function({inContextDrawMatchUps:t,positionAssignments:e,positionAssignment:n,tournamentRecord:r,drawDefinition:i,participantId:o,matchUpsMap:s,structure:c}){TI({positionAssignments:e,tournamentRecord:r,drawDefinition:i,matchUpsMap:s,structure:c});const{drawPositions:u,matchUps:d,targetMatchUps:p}=tv({assignments:[n],inContextDrawMatchUps:t,drawDefinition:i,matchUpsMap:s,structure:c});if(u&&1===d?.length&&d[0].matchUpType===a){const t=(p?.[0].sides??[]).reduce((t,e,n)=>u?.includes(e.drawPosition)?n:t,void 0);Yy({inContextTargetMatchUp:p[0],teamParticipantId:o,matchUp:d[0],drawPositionSideIndex:t,tournamentRecord:r,drawDefinition:i})}}({inContextDrawMatchUps:e,positionAssignments:U,positionAssignment:P,tournamentRecord:i,drawDefinition:o,participantId:c,matchUpsMap:p,structure:g}):function({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:r,drawDefinition:i,drawPosition:o,matchUpsMap:a,structure:s,event:c}){const u={isCollectionMatchUp:!1},{matchUps:d}=Fg({provisionalPositioning:t,matchUpFilters:u,drawDefinition:i,matchUpsMap:a,structure:s,event:c}),{roundMatchUps:p}=Bf({matchUps:d}),{initialRoundNumber:l}=pI({drawPosition:o,matchUps:d}),m=l&&p?.[l].find(t=>t.drawPositions?.includes(o));if(m){const t=Zy({matchUpId:m.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:r,drawDefinition:i,drawPosition:o,matchUpsMap:a});if(t.error)return Ci({stack:"assignDrawPositionToMatchUps",context:{drawPosition:o},result:t})}}({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:i,drawDefinition:o,drawPosition:d,matchUpsMap:p,structure:g,event:m});const R=o.entries?.find(t=>t.participantId===c),b=m?.entries?.find(t=>t.participantId===c);return!R&&b&&QS({entryStatus:b.entryStatus,entryStage:g.stage,ignoreStageSpace:!0,drawDefinition:o,participantId:c,event:m}),Xl({tournamentId:i?.tournamentId,drawDefinition:o,structure:g,event:m}),{positionAssignments:U,...Y}}function sv(t){const{participantIdAttributeName:e="participantId",isQualifierPosition:n,positionActionName:r,tournamentRecord:i,drawDefinition:o,participantId:a,drawPosition:s,structureId:c,event:u}=t,d="positionParticipantAction";if(!o)return{error:st};const p=xd({tournamentRecord:i,drawDefinition:o,event:u}).appliedPolicies??{};let{inContextDrawMatchUps:l,matchUpsMap:m}=t;m||(m=bf({drawDefinition:o}),Object.assign(t,{matchUpsMap:m})),l||(({matchUps:l}=zg({inContext:!0,drawDefinition:o,matchUpsMap:m})),Object.assign(t,{inContextDrawMatchUps:l}));const{positionAssignments:f}=cl({drawDefinition:o,structureId:c}),h=f?.find(t=>t.drawPosition===s);if(h?.participantId){const t=h.participantId,e=av({inContextDrawMatchUps:l,tournamentRecord:i,drawDefinition:o,participantId:a,drawPosition:s,structureId:c,matchUpsMap:m,event:u});return e.success?y({appliedPolicies:p,removedParticipantId:t}):Ci({result:e,stack:d})}const g=wI({inContextDrawMatchUps:l,tournamentRecord:i,drawDefinition:o,drawPosition:s,structureId:c,matchUpsMap:m,event:u});if(g.error)return Ci({result:g,stack:d});const I=g.participantId,S=av({inContextDrawMatchUps:l,isQualifierPosition:n,tournamentRecord:i,drawDefinition:o,participantId:a,drawPosition:s,structureId:c,matchUpsMap:m,event:u});return S.success?y({appliedPolicies:p,removedParticipantId:I}):Ci({result:S,stack:d});function y({appliedPolicies:t,removedParticipantId:n}){const{structure:i}=ol({drawDefinition:o,structureId:c});tm({drawPositions:[s],structure:i});return em({appliedPolicies:t,drawDefinition:o,positionAction:{[e]:a,name:r,drawPosition:s,structureId:c}}),Ci({context:{removedParticipantId:n},result:{...Y},stack:d})}}function cv(t){return function({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i}){return sv({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i})}(t)}function uv({params:t,modMap:e,structure:n}){const{tournamentRecord:r,drawDefinition:i,event:o}=t;for(const t of n.matchUps)e[t.matchUpId]&&(t.roundNumber=e[t.matchUpId],Yl({tournamentId:r?.tournamentId,eventId:o?.eventId,drawDefinition:i,matchUp:t}))}function dv(t,e){const n=[{drawDefinition:!0,structureId:!0}];Array.isArray(e)&&n.push(...e);const r=fu(t,n);if(r.error)return r;const i=ol(t);if(i.error)return i;const o=i.structure;if(!Hf({structure:o}))return Ci({result:{error:dt,message:"structure must be adHoc"}});const{roundMatchUps:a=[],roundNumbers:s}=Bf({matchUps:o?.matchUps});return s?.length?{valid:!0,structure:o,roundMatchUps:a,roundNumbers:s}:{error:Ie}}function pv(t){const e=dv(t,[{targetRoundNumber:!0,roundNumber:!0,[cu]:"number"}]);if(e.error)return e;const{structure:n,roundMatchUps:r,roundNumbers:i}=e,{targetRoundNumber:o,roundNumber:a}=t;if(!i?.includes(a)||!i?.includes(o))return Ci({result:{error:sr},info:"roundNumbers must be valid rounds"});const s=o>a,c=s?L(a+1,o+1):L(o,a),u={};return c.forEach(t=>(r?.[t]??[]).forEach(({matchUpId:e})=>{u[e]=t-(s?1:-1)})),r?.[a]?.forEach(({matchUpId:t})=>u[t]=o),uv({params:t,modMap:u,structure:n}),{...Y}}function lv({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:n,drawDefinition:r,event:i}){if(!r)return{error:st};if(!Array.isArray(t))return{error:sr};for(const o of t){const{structureId:t,positionAssignments:a}=o;if(!a)continue;const s=ol({drawDefinition:r,structureId:t});if(s.error)return s;const c=s.structure;if(!c)return{error:Vt};const u=cl({structure:c}).positionAssignments?.map(({drawPosition:t})=>t),d=a?.map(({drawPosition:t})=>t);if(V(u,d).length!==u?.length)return Ci({result:{error:sr},info:"drawPositions do not match",stack:"setPositionAssignments"});const p=bf({drawDefinition:r}),{matchUps:l}=zg({inContext:!0,drawDefinition:r,matchUpsMap:p});for(const o of a??[]){const{drawPosition:s,participantId:u,bye:d,qualifier:m}=o;if(d){const e=SI({tournamentRecord:n,drawDefinition:r,drawPosition:s,matchUpsMap:p,structureId:t,structure:c,event:i});if(e?.error)return e}else if(m)a.forEach(t=>{t.drawPosition===s&&(t.qualifier=!0,delete t.participantId,delete t.bye)});else if(u){const o=av({provisionalPositioning:e,inContextDrawMatchUps:l,tournamentRecord:n,drawDefinition:r,participantId:u,drawPosition:s,matchUpsMap:p,structureId:t,event:i});if(o?.error)return o}}Xl({tournamentId:n?.tournamentId,drawDefinition:r,structure:c,event:i})}const o=t.map(({structureId:t})=>t);return Ql({tournamentId:n?.tournamentId,eventId:i?.eventId,drawDefinition:r,structureIds:o}),{...Y}}function mv(t){const e=dv(t,[{roundNumbers:!0,[cu]:iu,[ou]:t=>2===t.length&&t.every(P)}]);if(e.error)return e;const{structure:n,roundMatchUps:r,roundNumbers:i}=e;if(!t.roundNumbers.every(t=>i?.includes(t)))return Ci({result:{error:sr,message:"roundNumbers must be valid rounds"}});const o={};return t.roundNumbers.forEach((e,n)=>(r?.[e]??[]).forEach(({matchUpId:e})=>{o[e]=t.roundNumbers[1-n]})),uv({params:t,modMap:o,structure:n}),{...Y}}function fv({roundPosition:t,roundNumber:e,idPrefix:n,uuids:r}){return n?`${n}-${e}-${t}`:r?.pop()||pa()}function hv({includeMatchUpType:t,drawPosition:e,roundNumber:n,matchUpType:r,idPrefix:i,matchUps:o,isMock:a,uuids:s,nodes:c,fed:u}){const d=c.length,p=e?e-d:void 0,l=L(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=fv({roundPosition:f.roundPosition,roundNumber:n,idPrefix:i,uuids:s}),g={roundPosition:f.roundPosition,drawPositions:[d],matchUpStatus:Ap,roundNumber:n,matchUpId:h};t&&(g.matchUpType=r),a&&(g.isMock=!0),o.push(g);const I={children:[f,p]};m.push(I)}return{roundNodes:m,matchUps:o,drawPosition:e?e-d:void 0}}function gv({includeMatchUpType:t,matchUpType:e,roundNumber:n,matchUps:r,idPrefix:i,isMock:o,uuids:a,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:fv({roundPosition:d,roundNumber:n,idPrefix:i,uuids:a})};u.push(f);const h={drawPositions:f.children.map(t=>t?.drawPosition).filter(Boolean),matchUpStatus:Ap,matchUpId:f.matchUpId,roundPosition:d,roundNumber:n};t&&e&&(h.matchUpType=e),o&&(h.isMock=!0),r.push(h),d++,c+=2}return{roundNodes:u,matchUps:r}}function Iv(t){const e=t.drawSize;let{feedRoundsProfile:n,feedRounds:r=0,skipRounds:i=0,baseDrawSize:o}=t;const{linkFedFinishingRoundNumbers:a,finishingPositionOffset:s,linkFedRoundNumbers:c,feedsFromFinal:u,isConsolation:d,matchUpType:p,idPrefix:l,isMock:m,uuids:f,fmlc:h}=t;o=o??function(t){const e=U(t);return e>t?e/2:e}(e);const g=function({drawSize:t}){const e=Math.ceil(Math.log(t)/Math.log(2));return L(0,e).reverse().map(t=>Math.pow(2,t))}({drawSize:o}),I=g.length;let S=0;if(n?.length)S=n.reduce((t,e)=>t+e,0);else if(e){let t=e-o;n=g.filter(e=>e<=t&&(t-=e,!0)),S=n.reduce((t,e)=>t+e,0),r=n.length}else i>=I?r=0:u&&(r=I-u,i=0),n=g.filter((t,e)=>u&&!r||r&&e>=i+r||e<i?0:t),S=n.reduce((t,e)=>t+e,0),r=n.length;const y=[...g,...n].sort((t,e)=>e-t),v=y.length,P=[...(c??[]).map(t=>t-1),...(a??[]).map(t=>v-t)].map(t=>y[t]).reduce((t,e)=>t+e,0);S-=P;let T,w=0,D=[],R=1;let b=L(0,o).map((t,e)=>({drawPosition:e+1+S})),N=S+1;for(const t of g){if(({roundNodes:T,matchUps:D}=gv({matchUpType:p,roundNumber:R,idPrefix:l,matchUps:D,isMock:m,nodes:b,uuids:f})),R++,n.includes(t)){const e=L(0,C(n)[t]),r=v+1-R,i=a?.includes(r)??c?.includes(R);e.forEach(()=>{const t=!i&&N||void 0;({roundNodes:T,matchUps:D,drawPosition:N}=hv({drawPosition:t,nodes:T,matchUpType:p,roundNumber:R,idPrefix:l,matchUps:D,isMock:m,uuids:f,fed:w})),R++,w+=1})}b=T}v!==R-1&&console.log("ERROR");D=nI({finishingPositionOffset:d?o-S:s,positionsFed:S,roundsCount:v,matchUps:D,fmlc:h});const M=T?.length?T[0]:T;return M&&(M.roundNumber=R-1,M.matchUps=D),{draw:M,matchUps:D,roundsCount:v}}function Sv({finishingPositionOffset:t,finishingPositionLimit:e,qualifyingRoundNumber:n,qualifyingPositions:r,matchUpType:i,roundLimit:o,idPrefix:a,drawSize:s,isMock:c,uuids:u}){if(isNaN(s)||s<2||r&&s<=r)return{matchUps:[],roundsCount:0};if(r&&(!S(s)||s%r)){let t=r;for(;t<s;)t*=2;s=t}const d=r&&!(s%2)&&(!isNaN(r)||n&&!isNaN(n))&&(s/r===Math.round(s/r)||n&&s/n===Math.round(s/n));if(!S(s)&&!d)return{matchUps:[],roundsCount:0};const p=L(1,s+1).map(t=>({drawPosition:t}));let l,m=[],f=1;for(({roundNodes:l,matchUps:m}=gv({matchUpType:i,roundNumber:f,idPrefix:a,matchUps:m,isMock:c,nodes:p,uuids:u})),f++,o=o??n;l.length>1;)r&&l.length===r&&(o=f-1),({roundNodes:l,matchUps:m}=gv({nodes:l,matchUpType:i,roundNumber:f,idPrefix:a,matchUps:m,isMock:c,uuids:u})),f++;const h=f-1;return m=nI({finishingPositionOffset:t,finishingPositionLimit:e,roundsCount:h,roundLimit:o,matchUps:m}),o?m=m.filter(t=>o&&(t.roundNumber??0)<=o):o=f-1,{drawSize:s,matchUps:m,roundsCount:h,roundLimit:o}}function yv(t){const{finishingPositionOffset:e=0,addNameBaseToAttributeName:n,playoffStructureNameBase:r,finishingPositionNaming:i,finishingPositionLimit:o,playoffAttributes:a,stageSequence:s=1,exitProfile:c="0",exitProfileLimit:u,roundOffsetLimit:d,roundOffset:p=0,drawDefinition:l,staggeredEntry:m,sequenceLimit:f,childStage:h,stage:g=us,drawSize:I,idPrefix:S,isMock:y,uuids:v}=t;if(!(!a||!u||a?.[c])||I<2||f&&s>f)return{};const U=[],P=[],T=[],w=t.matchUpType??l?.matchUpType,D=e+1,R=`${D}-${e+I}`,b=a?.[c],N=r&&`${r} `||"",M=a?.[R]??i?.[R],A=t.structureName||M?.name||b?.name&&(n?`${N}${b?.name}`:b.name)||`${N}${R}`,E=M?.abbreviation??b?.abbreviation,C=t.structureId??b?.structureId??v?.pop(),O={idPrefix:S&&`${S}-${A}-RP`,finishingPositionOffset:e,matchUpType:w,drawSize:I,isMock:y,uuids:v},{matchUps:k}=m?Iv(O):Sv(O),F=Ry({structureAbbreviation:E,stageSequence:s,structureName:A,matchUpType:w,roundOffset:p,structureId:C,matchUps:k,stage:g});U.push(...k),P.push(F);const x=Math.ceil(Math.log(I)/Math.log(2)),_=d?Math.min(d-p,x):(!o||D<o)&&x||0;return I>2&&L(1,_+1).forEach(t=>function(t){const m=I/Math.pow(2,t);if(m<2)return;const y=I/Math.pow(2,t)+e;if(o&&y+1>o)return;const{structures:D,structureId:R,matchUps:b,links:N}=yv({finishingPositionOffset:y,exitProfile:`${c}-${t}`,roundOffset:p+t,stageSequence:s+1,stage:h??g,drawSize:m,addNameBaseToAttributeName:n,playoffStructureNameBase:r,finishingPositionNaming:i,finishingPositionLimit:o,playoffAttributes:a,exitProfileLimit:u,roundOffsetLimit:d,drawDefinition:l,sequenceLimit:f,childStage:h,matchUpType:w,idPrefix:S,uuids:v});if(F.structureId&&R){const e={linkType:Cs,source:{roundNumber:t,structureId:F.structureId},target:{roundNumber:1,feedProfile:Ns,structureId:R}};N&&F&&N.push(e),N?.length&&T.push(...N)}D?.length&&P.push(...D);b?.length&&U.push(...b);return{structureId:R,childLinks:N,structures:P}}(t)),{structureId:F.structureId,matchUps:U,structureName:A,structures:P,links:T,...Y}}function vv({finishingPositionOffset:t=0,stage:e=us,structureName:n,matchUpType:r,idPrefix:i,drawSize:o,isMock:a,uuids:s}){if(4!==o)return{error:nr,info:"PAGE_PLAYOFF requires exactly 4 participants"};const c=[],{matchUps:u}=Sv({idPrefix:i&&`${i}-q1`,drawSize:2,matchUpType:r,isMock:a,uuids:s}),d=Ry({structureName:n?`${n} Qualifier 1`:"Qualifier 1",structureAbbreviation:"Q1",structureId:s?.pop(),matchUps:u,stageSequence:1,matchUpType:r,stage:e});c.push(d);const{matchUps:p}=Sv({finishingPositionOffset:t+2,idPrefix:i&&`${i}-el`,drawSize:2,matchUpType:r,isMock:a,uuids:s}),l=Ry({structureName:n?`${n} Eliminator`:"Eliminator",structureAbbreviation:"EL",structureId:s?.pop(),matchUps:p,stageSequence:2,matchUpType:r,stage:e});c.push(l);const{matchUps:m}=Sv({finishingPositionOffset:t+1,idPrefix:i&&`${i}-q2`,drawSize:2,matchUpType:r,isMock:a,uuids:s}),f=Ry({structureName:n?`${n} Qualifier 2`:"Qualifier 2",structureAbbreviation:"Q2",structureId:s?.pop(),stage:ms,matchUps:m,stageSequence:3,matchUpType:r});c.push(f);const{matchUps:h}=Sv({finishingPositionOffset:t,idPrefix:i&&`${i}-fi`,drawSize:2,matchUpType:r,isMock:a,uuids:s}),g=Ry({structureName:n?`${n} Final`:"Final",structureAbbreviation:"F",structureId:s?.pop(),matchUps:h,stage:ms,stageSequence:4,matchUpType:r});c.push(g);const I=function({q1Structure:t,eliminatorStructure:e,q2Structure:n,finalStructure:r}){return[{linkType:Es,source:{roundNumber:1,structureId:t.structureId},target:{feedProfile:Ns,roundNumber:1,structureId:r.structureId}},{linkType:Cs,source:{roundNumber:1,structureId:t.structureId},target:{feedProfile:Ns,roundNumber:1,structureId:n.structureId}},{linkType:Es,source:{roundNumber:1,structureId:e.structureId},target:{feedProfile:Ns,roundNumber:1,structureId:n.structureId}},{linkType:Es,source:{roundNumber:1,structureId:n.structureId},target:{feedProfile:Ns,roundNumber:1,structureId:r.structureId}}]}({eliminatorStructure:l,q1Structure:d,q2Structure:f,finalStructure:g});return{structures:c,links:I,...Y}}function Uv({drawDefinition:t,matchUpsMap:e,structureId:n}){const r=ol({drawDefinition:t,structureId:n});if(r.error)return Ci({result:r});const{matchUps:i}=Fg({structure:r.structure,matchUpsMap:e});return{...Bf({matchUps:i}),matchUps:i,matchUpsMap:e}}function Pv({finishingPositions:t,drawDefinition:e,structureId:n}){const{roundProfile:r}=Uv({drawDefinition:e,structureId:n}),i=r&&Object.keys(r);return i?.reduce((e,n)=>(Tv(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 L(n,(r||n)+1).includes(t)})({position:t,rangeDefinition:r})&&(e[t]={roundNumber:n})})}),e),{})}function Tv(t){return[M(t?.finishingPositionRange?.loser??[]),M(t?.finishingPositionRange?.winner??[])]}function wv(t){return Tv(t).map(t=>L(t[0],t[1]&&t[1]+1||t[0]+1))}function Dv({drawDefinition:t,structureIds:e,matchUpsMap:n}){if(e&&!Array.isArray(e))return{error:sr,context:{structureIds:e}};if(!t)return{error:st};const r=(e=e??(t.structures??[]).filter(t=>t.stage!==ds).map(({structureId:t})=>t)).map(e=>{const{roundProfile:r}=Uv({drawDefinition:t,matchUpsMap:n,structureId:e}),i=r&&Object.values(r);return i?.map(wv).flat()}).flat(),i=r.filter(t=>1===t?.length).sort(d).flat();return{positionsNotPlayedOff:M(r.flat()).filter(t=>!i.includes(t)),positionsPlayedOff:i}}function Rv({excludeRoundNumbers:t=[],playoffPositions:e=[],drawDefinition:n,structureId:r}){const i=dl({drawDefinition:n,structureId:r},[yc,bc]);if(i.error)return i;if(!e)return{error:Ae,info:"missing playoffPositions"};const o=Dv({drawDefinition:n});if(o.error)return o;const a=o.positionsPlayedOff,s=Pv({finishingPositions:e.filter(t=>!a.includes(t)),drawDefinition:n,structureId:r}),c=Object.values(s).reduce((t,e)=>t.includes(e.roundNumber)?t:t.concat(e.roundNumber),[]).map(t=>p(t)).filter(e=>!t.includes(e)),u=Pv({finishingPositions:a,drawDefinition:n,structureId:r}),l=u?Object.values(u):[],m=u?l.reduce((t,e)=>t.includes(e.roundNumber)?t:t.concat(e.roundNumber),[]).map(t=>p(t)):[],f=c.filter(t=>!m.includes(t)).sort(d),{roundProfile:h}=Uv({drawDefinition:n,structureId:r}),g=f.map(t=>{const e=h?.[t].finishingPositionRange.loser,[n,r]=e??[0,0];return L(n,(r||n)+1)}).flat().sort(d),{playoffRoundsRanges:I}=function({playoffSourceRounds:t,roundProfile:e}){const n=t.map(t=>{const n=e[t].finishingPositionRange.loser,[r,i]=n,o=L(r,(i||r)+1);return{finishingPositionRange:n.join("-"),finishingPositions:o,roundNumber:t}});return{playoffRoundsRanges:n}}({playoffSourceRounds:f,roundProfile:h}),S=[...f,...m];return{playoffPositionsReturned:g,playedOffSourceRounds:m,playoffRoundsRanges:I,playoffSourceRounds:f,sourceRounds:S,roundProfile:h}}function bv({drawDefinition:t,structureId:e}){if(!t)return{error:st};const{matchUps:n,matchUpsMap:r}=Zg({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:i,positionsPlayedOff:o}=Dv({drawDefinition:t,matchUpsMap:r}),{structures:a}=al({drawDefinition:t}),s=a.filter(t=>!e&&t.stage!==ls||t.structureId===e),c={};for(const e of s){const r=e?.structureId,o=Nv({playoffPositions:i,drawDefinition:t,structure:e,matchUps:n}),{error:a,...s}=o;if(a)return o;c[r]={structureId:r,...s}}return e?{positionsPlayedOff:o,...c[e]}:{availablePlayoffProfiles:Object.values(c),availablePlayoffRounds:Object.values(c),positionsPlayedOff:o}}function Nv({playoffPositions:t,drawDefinition:e,structure:n,matchUps:r}){const i=n?.structureId,{links:o}=Vg({drawDefinition:e,structureId:i});if(n.structureType===Ds||n.structures){const t=cl({structure:n})?.positionAssignments?.length,a=n.structures.length,s=(t??0)/a,c=o.source?.flatMap(({source:t})=>t?.finishingPositions??[])??[],u=L(1,s+1).filter(t=>!c.includes(t)),d=r.find(t=>t.containerStructureId===i&&t.finishingPositionRange)?.finishingPositionRange?.winner||[0,1],p=o?.source.map(({target:t})=>t.structureId),{positionsPlayedOff:l=[],positionsNotPlayedOff:m=[]}=Dv({structureIds:p,drawDefinition:e}),f=new Set([...l,...m]),h=L(d[0],d[1]+1).filter(t=>!f.has(t)),g=q(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:a,groupSize:s}}const a=o?.source?.filter(t=>t.linkCondition!==Os).map(t=>t.source?.roundNumber)??[],s=o?.source?.filter(t=>t.linkCondition===Os).map(t=>t.source?.roundNumber)??[],c=Rv({excludeRoundNumbers:a,playoffPositions:t,drawDefinition:e,structureId:i}),u=c?.playoffSourceRounds?[...c?.playoffSourceRounds??[]]:void 0,p=[...c?.playoffRoundsRanges??[]],{roundProfile:l,error:m}=c;for(const t of s){const e=o?.source.find(e=>e.source.roundNumber===t),n=e?.target.roundNumber,i=e?.target.structureId,a=r.filter(({roundNumber:t,structureId:e})=>e===i&&t===n),s=a.filter(({sides:t})=>t.find(t=>t.participantFed&&!t.participantId)).length;if(u&&s===a.length){u.push(t);const e=l?.[t]?.finishingPositionRange?.loser;if(e){const n=Math.min(...e),r=n+s,i=L(n,r),o={finishingPositionRange:[n,r-1].join("-"),finishingPositions:i,roundNumber:t};p.push(o)}}}return u&&u.sort(d),p.sort((t,e)=>t.roundNumber-e.roundNumber),{playoffRounds:u,playoffRoundsRanges:p,error:m}}function Mv({playoffGroups:t,groupCount:e,groupSize:n}){if(!Array.isArray(t)||!t.length)return{error:sr,valid:!1,info:"playoffGroups must be a non-empty array"};if(!e||e<1)return{error:sr,valid:!1,info:"groupCount must be >= 1"};if(!n||n<1)return{error:sr,valid:!1,info:"groupSize must be >= 1"};const r={};for(let t=1;t<=n;t++)r[t]=0;const i=e*n;let o=0,a=!1;for(const s of t){const{finishingPositions:t,bestOf:c,rankBy:u,remainder:d}=s;if(d){const t=Av({hasBestOf:a,totalAvailable:i,totalClaimed:o});if(t.error)return t;o+=i-o;continue}if(!Array.isArray(t)||!t.length)return{error:sr,valid:!1,info:"Each playoffGroup must have non-empty finishingPositions"};for(const e of t)if(e<1||e>n)return{error:sr,valid:!1,info:`finishingPosition ${e} out of range [1, ${n}]`};const p=e*t.length;if(void 0===c){const n=Ev({finishingPositions:t,groupCount:e,consumptionMap:r});if(n?.error)return n;o+=p}else{const s=Cv({finishingPositions:t,guaranteedCount:p,consumptionMap:r,totalAvailable:i,groupCount:e,groupSize:n,bestOf:c,rankBy:u});if(s?.error)return s;a=!0,o+=c}}return o>i?{info:`Total claimed participants (${o}) exceeds available (${i})`,error:nr,valid:!1}:{valid:!0,consumptionMap:r}}function Av({hasBestOf:t,totalAvailable:e,totalClaimed:n}){if(!t)return{error:nr,valid:!1,info:"A remainder group must appear after at least one bestOf group"};const r=e-n;return r<2?{error:nr,valid:!1,info:`Remainder group would have insufficient participants (${r}), minimum 2 required`}:{}}function Ev({finishingPositions:t,groupCount:e,consumptionMap:n}){for(const r of t){const t=e-n[r];if(t<2)return{error:nr,valid:!1,info:`finishingPosition ${r} has insufficient remaining participants (${t}) for a standard playoff group (minimum 2 required)`};n[r]+=t}return{}}function Cv({finishingPositions:t,guaranteedCount:e,consumptionMap:n,totalAvailable:r,groupCount:i,groupSize:o,bestOf:a,rankBy:s}){if("number"!=typeof a||a<1)return{error:sr,valid:!1,info:"bestOf must be a positive number"};if(a<e)return{info:`bestOf (${a}) cannot be less than guaranteed count (${e}) for finishingPositions [${t}] with ${i} groups`,error:nr,valid:!1};if(a>r)return{info:`bestOf (${a}) exceeds total available participants (${r})`,error:nr,valid:!1};if(void 0!==s&&s!==Zm)return{info:`Unsupported rankBy value: '${s}'. Currently only '${Zm}' is supported.`,error:sr,valid:!1};for(const e of t)n[e]+=i;const c=a-e;if(c>0){const e=function({remainder:t,finishingPositions:e,groupCount:n,groupSize:r,consumptionMap:i,bestOf:o}){let a=t;const s=[...e].sort(d);let c=Math.max(...s)+1;for(;a>0&&c<=r;){const t=n-i[c],e=Math.min(a,t);i[c]+=e,a-=e,c++}if(a>0)return{info:`bestOf (${o}) requires more participants than available from remaining finishing positions`,error:nr,valid:!1};return{}}({remainder:c,finishingPositions:t,groupCount:i,groupSize:o,consumptionMap:n,bestOf:a});if(e?.error)return e}return{}}function Ov(t){const{finishingPositionOffset:e=0,playoffAttributes:n,stageSequence:r=1,staggeredEntry:i,structureName:o,stage:a=us,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?Iv(m):Sv(m),h=Ry({structureName:o||n?.[0]?.name||Ny(us),structureId:c||l?.pop(),stageSequence:r,matchUpType:s,matchUps:f,stage:a}),g=[h],I=[];if(d>2){const r=d/2,{matchUps:i}=Sv({finishingPositionOffset:e+r,idPrefix:u&&`${u}-c`,drawSize:r,matchUpType:s,isMock:p}),a=Ny(ps),c=n?.["0-1"]?.name??t.consolationStructureName??(o?`${o} ${a}`:a),m=Ry({structureName:c,matchUps:i,structureId:l?.pop(),stage:ps,stageSequence:1,matchUpType:s});g.push(m);const f={linkType:Cs,source:{roundNumber:1,structureId:h.structureId},target:{roundNumber:1,feedProfile:Ns,structureId:m.structureId}};I.push(f)}return{...Y,structures:g,links:I}}function kv({consolationStructure:t,roundOffset:e=0,mainStructure:n,roundsCount:r,feedPolicy:i,fmlc:o}){const a=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 L(1+e,r+1+e).map(r=>{const i=c?.[r-1]?c[r-1]:r%2&&Ns||Ms,u=r-e<=2?r-e:2*(r-e-2)+2,d={linkType:Cs,source:{roundNumber:r,structureId:n.structureId},target:{feedProfile:i,roundNumber:u,structureId:t.structureId}},p=s[r-1];return p&&(d.target.groupedOrder=p),$r()&&(d.source.structureName=n.structureName,d.target.structureName=t.structureName),2===r&&o&&(d.linkCondition=Os,d.target.feedProfile=Ns),a.includes(u)?d:void 0}).filter(Boolean)}function Fv(t){const{playoffStructureNameBase:e,finishingPositionOffset:n,stageSequence:r=1,playoffAttributes:i,structureNameMap:o,staggeredEntry:a,stage:s=us,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}=a?Iv(f):Sv(f),I=t.structureName??i?.[0]?.name??Ny(us),S=Ry({structureId:u||m?.pop(),structureName:I,stageSequence:r,matchUpType:c,matchUps:h,stage:s}),y=[S],v=[];if(d>2){const t=[0,2].slice(0,d/16).map((t,n)=>{const r=n+1,{consolationStructure:a}=function({playoffStructureNameBase:t,stageSequence:e=1,playoffAttributes:n,structureNameMap:r,roundOffset:i=0,matchUpType:o,structureId:a,idPrefix:s,drawSize:c,isMock:u,index:d,uuids:p}){const l=c/(2*Math.pow(2,i)),{matchUps:m,roundsCount:f}=Iv({finishingPositionOffset:l,baseDrawSize:l,isConsolation:!0,feedRounds:1,matchUpType:o,idPrefix:s,isMock:u,uuids:p}),h=0===d&&n?.["0-1"]?.name||1===d&&n?.["0-3"]?.name,g=h||`${Ny(ps)} ${d+1}`,I=r?.[g]||g,S=t?`${t} ${I}`:I,y=Ry({matchUps:m,stage:ps,structureName:S,stageSequence:e,matchUpType:o,structureId:a});return{consolationStructure:y,consolationRoundsCount:f}}({idPrefix:p&&`${p}-c${n}`,structureId:m?.pop(),playoffStructureNameBase:e,playoffAttributes:i,structureNameMap:o,stageSequence:r,roundOffset:t,matchUpType:c,drawSize:d,isMock:l,index:n,uuids:m});y.push(a);return{consolationStructure:a,links:kv({consolationStructure:a,roundsCount:2,mainStructure:S,roundOffset:t})}}),n=t.map(t=>t.links).flat();if(v.push(...n),d>=4&&d<=16||d>32){const{matchUps:t}=Sv({idPrefix:p&&`${p}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:l}),n=i?.["3-4"]?.name??Ny(ms),r=o?.[n]||n,a=e?`${e} ${r}`:r,s=Ry({structureId:m?.pop(),matchUps:t,stageSequence:2,stage:ms,structureName:a,matchUpType:c}),u={linkType:Cs,source:{roundNumber:g-1,structureId:S.structureId},target:{structureId:s.structureId,feedProfile:Ns,roundNumber:1}};y.push(s),v.push(u)}}return{structures:y,links:v,...Y}}function xv(t){const{finishingPositionOffset:e,stageSequence:n=1,playoffAttributes:r,feedsFromFinal:i,staggeredEntry:o,structureName:a,stage:s=us,structureId:c,matchUpType:u,skipRounds:d,feedRounds:p,idPrefix:l,drawSize:m,isMock:f,uuids:h,fmlc:g}=t,I=t.feedPolicy||t.policyDefinitions?.[_u]||t.appliedPolicies?.[_u],S={finishingPositionOffset:e,matchUpType:u,skipRounds:d,drawSize:m,idPrefix:l,isMock:f,uuids:h},{matchUps:y}=o?Iv(S):Sv(S),v=Ry({structureName:a||r?.[0]?.name||Ny(us),structureId:c||h?.pop(),stageSequence:n,matchUpType:u,matchUps:y,stage:s}),U=[v],P=[],T=m/2,{matchUps:w,roundsCount:D}=Iv({finishingPositionOffset:T,idPrefix:l&&`${l}-c`,isConsolation:!0,feedsFromFinal:i,baseDrawSize:T,matchUpType:u,feedRounds:p,skipRounds:d,isMock:f,uuids:h,fmlc:g});if(m>2){const e=r?.["0-1"]?.name??Ny(ps),n=t.playoffStructureNameBase?`${t.playoffStructureNameBase} ${e}`:e,i=Ry({matchUps:w,structureId:h?.pop(),stage:ps,stageSequence:1,structureName:n,matchUpType:u});U.push(i);const o=kv({consolationStructure:i,mainStructure:v,roundsCount:D,feedPolicy:I,fmlc:g});P.push(...o)}return{...Y,structures:U,links:P}}const _v=new Set([Vs,Zs,Qs,Ys,Hs,Xs]),Lv=new Set([xs,_s,ec]);function Bv({requireSequential:t=!0,playoffMatchUpFormat:e,playoffAttributes:n,sourceStructureId:r,policyDefinitions:i,stageSequence:o,drawDefinition:a,playoffGroups:s,matchUpType:c,feedPolicy:u,groupCount:p,groupSize:l,idPrefix:f,isMock:h,uuids:g}={}){const I=u||i?.[_u],S="processPlayoffGroups";let y=0;const v=[],U=[],P=[],T=s?.some(t=>void 0!==t.bestOf||t.remainder);if(T&&l){const t=Mv({playoffGroups:s,groupCount:p,groupSize:l});if(!t.valid)return Ci({result:{error:t.error||nr},context:{info:t.info},stack:S})}const D=s?.filter(t=>!t.remainder),{error:R,positionRangeMap:b}=function({playoffGroups:t,drawDefinition:e,structureId:n}){if(!e)return{error:st};if(!m(n)||!Array.isArray(t))return{error:sr};const r=t.map(({finishingPositions:t})=>t).flat(),i=bv({drawDefinition:e,structureId:n}),o=i.playoffFinishingPositionRanges?.filter(t=>r.includes(t.finishingPosition)),a=o?.reduce((t,e)=>(t[e.finishingPosition]=e,t),{});return{positionRangeMap:a}}({structureId:r,playoffGroups:D,drawDefinition:a});if(R)return Ci({result:{error:R},stack:S});if(!(!b||D?.every(e=>{const{finishingPositions:n=[]}=e;if(!n.length)return!1;const r=[...n].sort(d).map((t,e)=>(n[e+1]||t)-t).every(t=>t<2);return(!t||r)&&n.every(t=>b[t])})))return Ci({context:{validFinishingPositions:Object.values(b)},result:{error:sr},stack:S});let N=0;for(const t of s){const{bestOf:s,rankBy:u,remainder:d}=t;if(d){const n=Vv({finishingPositionOffset:y,playoffMatchUpFormat:e,sourceStructureId:r,stageSequence:o,totalClaimed:N,playoffGroup:t,matchUpType:c,groupCount:p,groupSize:l,idPrefix:f,isMock:h,uuids:g});U.push(n.structure),P.push(n.link),v.push(n.target),y+=n.remainderCount,N+=n.remainderCount;continue}const m=t.finishingPositions??[],T=b&&m.flatMap(t=>b[t]?.finishingPositions??[]),D=s??p*m.length;N+=D;const R=w(D),M=2===R&&Ls||t.drawType||Ls;T&&(y=Math.min(...T)-1);const A=Hv({positionsPlayedOff:T,playoffGroup:t}),E={...{addNameBaseToAttributeName:t.addNameBaseToAttributeName,playoffStructureNameBase:t.playoffStructureNameBase,finishingPositionNaming:t.finishingPositionNaming,finishingPositionLimit:t.finishingPositionLimit,structureId:t.structureId??g?.pop(),playoffAttributes:t.playoffAttributes,structureNameMap:t.structureNameMap,sequenceLimit:t.sequenceLimit,structureName:A},idPrefix:f&&`${f}-po`,appliedPolicies:i,finishingPositionOffset:y,stage:ms,stageSequence:o,matchUpType:c,drawSize:R,isMock:h,uuids:g},C=({playoffStructures:t,playoffLinks:e})=>{const[n]=t,i=zv({playoffStructureId:n.structureId,finishingPositions:m,sourceStructureId:r,bestOf:s,rankBy:u});P.push(i,...e),U.push(...t),v.push({structureId:n.structureId,finishingPositions:m}),y+=D};if(M===Ls)Gv({finishingPositionOffset:y,playoffMatchUpFormat:e,finishingPositions:m,sourceStructureId:r,participantsInDraw:D,stageSequence:o,playoffGroup:t,structureName:A,matchUpType:c,drawSize:R,idPrefix:f,bestOf:s,rankBy:u,isMock:h,uuids:g,finishingPositionTargets:v,structures:U,links:P}),y+=D;else if(Lv.has(M)){const e=jv({finishingPositionOffset:y,finishingPositions:m,sourceStructureId:r,playoffAttributes:n,playoffDrawType:M,stageSequence:o,playoffGroup:t,drawSize:R,idPrefix:f,bestOf:s,rankBy:u,isMock:h,uuids:g,finishingPositionTargets:v,structures:U,links:P});if(e)return e;y+=D}else if(_v.has(M))qv({finishingPositionOffset:y,finishingPositions:m,sourceStructureId:r,playoffDrawType:M,playoffGroup:t,structureName:A,matchUpType:c,drawSize:R,idPrefix:f,bestOf:s,rankBy:u,isMock:h,uuids:g,feedPolicy:I,finishingPositionTargets:v,structures:U,links:P}),y+=D;else if(M===ic){const{structures:e,links:n}=Fy({...E,structureOptions:t.structureOptions||{groupSize:4}});C({playoffStructures:e,playoffLinks:n})}else if(M===Gs){const{structures:t,links:e}=Ov(E);C({playoffStructures:t,playoffLinks:e})}else if("CURTIS_CONSOLATION"===M){const{structures:t,links:e}=Fv(E);C({playoffStructures:t,playoffLinks:e})}else if(M===tc){const e=Wv({finishingPositionTargets:v,participantsInDraw:D,sourceStructureId:r,finishingPositions:m,drawDefinition:a,playoffGroup:t,structures:U,params:E,links:P,stack:S});if(e)return e}else M===ks&&$v({finishingPositions:m,stageSequence:o,structureName:A,playoffGroup:t,groupSize:l,uuids:g,updateStructureAndLinks:C})}return{finishingPositionTargets:v,positionRangeMap:b,structures:U,links:P}}function Vv({finishingPositionOffset:t,playoffMatchUpFormat:e,sourceStructureId:n,stageSequence:r,totalClaimed:i,playoffGroup:o,matchUpType:a,groupCount:s,groupSize:c,idPrefix:u,isMock:d,uuids:p}){const l=s*c-i,m=w(l),f=Array.from({length:c},(t,e)=>e+1),h=o.structureName||"Remainder Playoff",{matchUps:g}=Sv({finishingPositionLimit:t+l,idPrefix:u&&`${u}-po`,finishingPositionOffset:t,matchUpType:a,drawSize:m,isMock:d,uuids:p}),I=Ry({structureId:o.structureId??p?.pop(),matchUpFormat:e,stage:ms,structureName:h,stageSequence:r,matchUps:g}),S=zv({playoffStructureId:I.structureId,finishingPositions:f,sourceStructureId:n,remainder:!0});return{structure:I,target:{structureId:I.structureId,finishingPositions:f},remainderCount:l,link:S}}function Gv({finishingPositionOffset:t,playoffMatchUpFormat:e,finishingPositions:n,sourceStructureId:r,participantsInDraw:i,stageSequence:o,playoffGroup:a,structureName:s,matchUpType:c,drawSize:u,idPrefix:d,bestOf:p,rankBy:l,isMock:m,uuids:f,finishingPositionTargets:h,structures:g,links:I}){const{matchUps:S}=Sv({finishingPositionLimit:t+i,idPrefix:d&&`${d}-po`,finishingPositionOffset:t,matchUpType:c,drawSize:u,isMock:m,uuids:f}),y=Ry({structureId:a.structureId??f?.pop(),matchUpFormat:e,stage:ms,structureName:s,stageSequence:o,matchUps:S});g.push(y);const v=zv({playoffStructureId:y.structureId,finishingPositions:n,sourceStructureId:r,bestOf:p,rankBy:l});I.push(v),h.push({structureId:y.structureId,finishingPositions:n})}function jv({finishingPositionOffset:t,finishingPositions:e,sourceStructureId:n,playoffAttributes:r,playoffDrawType:i,stageSequence:o,playoffGroup:a,drawSize:s,idPrefix:c,bestOf:u,rankBy:d,isMock:p,uuids:l,finishingPositionTargets:m,structures:f,links:h}){const g={playoffAttributes:a.playoffAttributes??r,playoffStructureNameBase:a.playoffStructureNameBase,structureId:a.structureId??l?.pop(),structureName:a.structureName,idPrefix:c&&`${c}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:t,stage:ms,roundOffset:0,stageSequence:o,drawSize:s,isMock:p,uuids:l};i===xs?Object.assign(g,{playoffAttributes:a?.playoffAttributes??r??cc,roundOffsetLimit:3}):i===_s&&Object.assign(g,{playoffAttributes:a?.playoffAttributes??r??uc,roundOffsetLimit:2});const I=yv(g);if(I.error)return I;if(I.links?.length&&h.push(...I.links),I.structures?.length&&f.push(...I.structures),f.sort(rl),I.structureId){const t=zv({playoffStructureId:I.structureId,finishingPositions:e,sourceStructureId:n,bestOf:u,rankBy:d});h.push(t),m.push({structureId:I.structureId,finishingPositions:e})}}function qv({finishingPositionOffset:t,finishingPositions:e,sourceStructureId:n,playoffDrawType:r,playoffGroup:i,structureName:o,matchUpType:a,feedPolicy:s,drawSize:c,idPrefix:u,bestOf:d,rankBy:p,isMock:l,uuids:m,finishingPositionTargets:f,structures:h,links:g}){const I=[m?.pop(),m?.pop()],S={playoffStructureNameBase:i.playoffStructureNameBase,structureId:i.structureId??m?.pop(),playoffAttributes:i.playoffAttributes,idPrefix:u&&`${u}-po`,finishingPositionOffset:t,uuids:I,stage:ms,structureName:o,matchUpType:a,feedPolicy:s,drawSize:c,isMock:l},y={[Vs]:{fmlc:!0,feedRounds:1},[Xs]:{feedRounds:1},[Qs]:{feedsFromFinal:3},[Ys]:{feedsFromFinal:2},[Hs]:{feedsFromFinal:1}};Object.assign(S,y[r]??{});const{structures:v,links:U}=xv(S),[P]=v,T=zv({playoffStructureId:P.structureId,finishingPositions:e,sourceStructureId:n,bestOf:d,rankBy:p});g.push(T,...U),h.push(...v),f.push({structureId:P.structureId,finishingPositions:e})}function Wv({finishingPositionTargets:t,participantsInDraw:e,sourceStructureId:n,finishingPositions:r,drawDefinition:i,playoffGroup:o,structures:a,params:s,links:c,stack:u}){if(4!==e)return Ci({result:{error:nr},context:{info:"PAGE_PLAYOFF requires exactly 4 participants"},stack:u});const d=i?.structures?.find(t=>t.structureId===n);return d&&!d.structures&&!d.structureType?function({finishingPositionTargets:t,sourceStructureId:e,drawDefinition:n,playoffGroup:r,structures:i,params:o,links:a}){const s=r.structureName,{matchUpType:c,isMock:u,uuids:d,idPrefix:p,finishingPositionOffset:l=0}=o,m=ms,{matchUps:f}=Sv({finishingPositionOffset:l+2,idPrefix:p&&`${p}-el`,drawSize:2,matchUpType:c,isMock:u,uuids:d}),h=Ry({structureName:s?`${s} 3-4 Playoff`:"3-4 Playoff",structureAbbreviation:"EL",structureId:d?.pop(),matchUps:f,stageSequence:1,matchUpType:c,stage:m}),{matchUps:g}=Sv({finishingPositionOffset:l+1,idPrefix:p&&`${p}-q2`,drawSize:2,matchUpType:c,isMock:u,uuids:d}),I=Ry({structureName:s?`${s} Playoff Qualifier`:"Playoff Qualifier",structureAbbreviation:"Q2",structureId:d?.pop(),matchUps:g,stageSequence:2,matchUpType:c,stage:m}),{matchUps:S}=Sv({finishingPositionOffset:l,idPrefix:p&&`${p}-fi`,drawSize:2,matchUpType:c,isMock:u,uuids:d}),y=Ry({structureName:s?`${s} Final`:"Playoff Final",structureAbbreviation:"F",structureId:d?.pop(),matchUps:S,stageSequence:3,matchUpType:c,stage:m});i.push(h,I,y);const v=n?.structures?.find(t=>t.structureId===e),U=v?.matchUps||[],P=U.length?Math.max(...U.map(t=>t.roundNumber)):1,T=P-1;return a.push({linkType:Cs,source:{structureId:e,roundNumber:T},target:{feedProfile:Ns,roundNumber:1,structureId:h.structureId}},{linkType:Es,source:{structureId:e,roundNumber:P},target:{feedProfile:Ns,roundNumber:1,structureId:y.structureId}},{linkType:Cs,source:{structureId:e,roundNumber:P},target:{feedProfile:Ns,roundNumber:1,structureId:I.structureId}},{linkType:Es,source:{structureId:h.structureId,roundNumber:1},target:{feedProfile:Ns,roundNumber:1,structureId:I.structureId}},{linkType:Es,source:{structureId:I.structureId,roundNumber:1},target:{feedProfile:Ns,roundNumber:1,structureId:y.structureId}}),void t.push({structureId:h.structureId,finishingPositions:[3,4]})}({finishingPositionTargets:t,sourceStructureId:n,drawDefinition:i,playoffGroup:o,structures:a,params:s,links:c}):function({finishingPositionTargets:t,sourceStructureId:e,finishingPositions:n,playoffGroup:r,structures:i,params:o,links:a,stack:s}){const c=vv({...o,structureName:r.structureName});if(c.error)return Ci({result:c,stack:s});i.push(...c.structures),a.push(...c.links);const u=c.structures.find(t=>"Q1"===t.structureAbbreviation),d=c.structures.find(t=>"EL"===t.structureAbbreviation);if(n.length>=2&&u&&d){const r=Math.ceil(n.length/2),i=n.slice(0,r),o=n.slice(r);a.push(zv({playoffStructureId:u.structureId,finishingPositions:i,sourceStructureId:e}),zv({playoffStructureId:d.structureId,finishingPositions:o,sourceStructureId:e})),t.push({structureId:u.structureId,finishingPositions:i},{structureId:d.structureId,finishingPositions:o})}else u&&d&&(a.push(zv({playoffStructureId:u.structureId,finishingPositions:n,sourceStructureId:e}),zv({playoffStructureId:d.structureId,finishingPositions:n,sourceStructureId:e})),t.push({structureId:u.structureId,finishingPositions:n},{structureId:d.structureId,finishingPositions:n}));return}({finishingPositionTargets:t,sourceStructureId:n,finishingPositions:r,playoffGroup:o,structures:a,params:s,links:c,stack:u})}function $v({finishingPositions:t,stageSequence:e,structureName:n,playoffGroup:r,groupSize:i,uuids:o,updateStructureAndLinks:a}){!t.length&&i&&t.push(...Array.from({length:i},(t,e)=>e+1));a({playoffStructures:[Ry({structureId:r.structureId??o?.pop(),structureName:r.structureName||n||"Playoff",finishingPosition:$m,stage:ms,stageSequence:e,matchUps:[]})],playoffLinks:[]})}function Hv({positionsPlayedOff:t,playoffGroup:e}){const n=t&&`${Math.min(...t)}-${Math.max(...t)}`;return e.structureName||n&&e.playoffAttributes?.[n]?.name||e.playoffAttributes?.[0]?.name}function zv({playoffStructureId:t,finishingPositions:e,sourceStructureId:n,remainder:r,bestOf:i,rankBy:o}){const a={structureId:n,finishingPositions:e};return void 0!==i&&(a.bestOf=i,a.rankBy=o||Zm),r&&(a.remainder=!0),{linkType:As,source:a,target:{structureId:t,feedProfile:Rs,roundNumber:1}}}function Yv({structureName:t,matchUpType:e,idPrefix:n,drawSize:r,isMock:i,uuids:o}){const a=[],{matchUps:s}=Iv({linkFedFinishingRoundNumbers:[1],drawSize:r+1,matchUpType:e,idPrefix:n,isMock:i}),c=Ry({structureName:t||Ny(us),structureId:o?.pop(),stageSequence:1,stage:us,matchUpType:e,matchUps:s});a.push(c);const u=r/2,{matchUps:d}=Iv({finishingPositionOffset:u,idPrefix:n&&`${n}-c`,drawSize:r-1,isConsolation:!0,matchUpType:e,isMock:i,uuids:o}),p=Ry({structureName:Ny(sc),matchUps:d,structureId:o?.pop(),stage:ps,stageSequence:2,matchUpType:e});a.push(p);const{matchUps:l}=Sv({idPrefix:n&&`${n}-p1t2`,drawSize:2,matchUpType:e,isMock:i}),m=Ry({structureName:Ny(ac),matchUps:l,structureId:o?.pop(),stageSequence:3,stage:ms,matchUpType:e});a.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),o=e.matchUps.reduce((t,e)=>!t||e.roundNumber>t?e.roundNumber:t,void 0);return[...r.map((n,i)=>{const o=r.indexOf(n)%2?Ns:Ms;return{linkType:Cs,source:{roundNumber:1+i,structureId:t.structureId},target:{feedProfile:o,roundNumber:n,structureId:e.structureId}}}),{linkType:Es,source:{roundNumber:o,structureId:e.structureId},target:{feedProfile:Ns,roundNumber:i,structureId:t.structureId}},{linkType:Es,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:Ns,roundNumber:1,structureId:n.structureId}},{linkType:Cs,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:Ns,roundNumber:1,structureId:n.structureId}}]}({mainStructure:c,consolationStructure:p,deciderStructure:m});return{structures:a,links:f,...Y}}function Kv(t){const{qualifyingRoundNumber:e,finishingPositionOffset:n,qualifyingPositions:r,matchUpType:i,idPrefix:o,drawSize:a,isMock:s,uuids:c}=t;if(!R(a)||a<2)return{matchUps:[],roundsCount:0};if(S(a))return Sv(t);const u=Qv(a),d=u.shift(),p=L(1,(d?.participantsCount||0)+1).map(t=>({drawPosition:t}));let l=[],m=1;({matchUps:l}=gv({roundNumber:m,matchUpType:i,idPrefix:o,matchUps:l,isMock:s,nodes:p,uuids:c})),m++;let f=t.roundLimit||e;for(const t of u){const e=t.participantsCount/2,n=L(1,e+1);r&&e===r&&(f=m-1);const i=n.map(t=>{const e=fv({roundPosition:t,roundNumber:m,idPrefix:o,uuids:c});return{roundPosition:t,roundNumber:m,matchUpId:e}});l.push(...i),m++}const h=m-1;return l=nI({finishingPositionOffset:n,lucky:!0,roundsCount:h,roundLimit:f,matchUps:l}),f&&(l=l.filter(t=>t.roundNumber<=f)),{matchUps:l,roundsCount:h,roundLimit:f}}function Qv(t){const e=p(t);let n=e%2?e+1:e;const r=[{participantsCount:n,preFeedRound:!!(Math.ceil(n/2)%2)}];for(;n>2;){const t=Math.ceil(n/2),e=1===t,i=!(e||!(t%2));n=!e&&i?t+1:t;const o=!!(2!==n&&Math.ceil(n/2)%2);r.push({participantsCount:n,preFeedRound:o,feedRound:i})}return r}function Jv(t){const{finishingPositionOffset:e=0,playoffAttributes:n=dc,stageSequence:r=1,exitProfile:i="0",roundOffsetLimit:o=3,roundOffset:a=0,childStage:s=ms,stage:c=us,matchUpType:u,structureId:d,drawSize:p,idPrefix:l,isMock:m,uuids:f}=t;if(!(!n||n[i])||p<2)return{};const h=[],g=[],I=n[i],y=t.structureName||I?.name||`${e+1}-${e+p}`,v=I?.abbreviation,U=d??I?.structureId??f?.pop(),{matchUps:P}=Kv({finishingPositionOffset:e,matchUpType:u,drawSize:p,idPrefix:l&&`${l}-${y}-RP`,isMock:m,uuids:f}),T=Ry({structureAbbreviation:v,structureName:y,stageSequence:r,matchUpType:u,roundOffset:a,structureId:U,matchUps:P,stage:c});h.push(T);const w=function(t){if(S(t)){const e=Math.ceil(Math.log(t)/Math.log(2)),n=[];for(let r=1;r<=e;r++){const e=t/Math.pow(2,r);e>=2&&n.push({roundNumber:r,childSize:e})}return n}const e=Qv(t),n=[];for(let t=0;t<e.length-1;t++){const r=e[t],i=r.participantsCount/2,o=r.preFeedRound?i-1:i;o>=2&&n.push({roundNumber:t+1,childSize:o})}return n}(p),D=w.length,R=Math.min(o-a,D);for(let t=0;t<R;t++){const{roundNumber:c,childSize:d}=w[t];if(d<2)continue;const I=Jv({finishingPositionOffset:e+Xv(p,c),exitProfile:`${i}-${c}`,roundOffset:a+c,stageSequence:r+1,drawSize:d,stage:s,playoffAttributes:n,roundOffsetLimit:o,childStage:s,matchUpType:u,idPrefix:l,isMock:m,uuids:f});if(I.structureId&&T.structureId){const t={linkType:Cs,source:{roundNumber:c,structureId:T.structureId},target:{roundNumber:1,feedProfile:Ns,structureId:I.structureId}};g.push(t)}I.structures?.length&&h.push(...I.structures),I.links?.length&&g.push(...I.links)}return{structureId:T.structureId,structures:h,links:g,...Y}}function Xv(t,e){if(S(t))return t/Math.pow(2,e);const n=Qv(t);return e<n.length?Math.ceil(n[e].participantsCount/2):1}function Zv(t){const{finishingPositionOffset:e,qualifyingRoundNumber:n,qualifyingPositions:r,matchUpType:i,idPrefix:o,drawSize:a,isMock:s,uuids:c}=t;if(!R(a)||a<2)return{matchUps:[],roundsCount:0};const u=function(t,e){if(!Array.isArray(t)||!t.length)return{error:sr,info:"roundProfile must be a non-empty array"};const n=t.map(t=>p(t));if(n.some(t=>!Number.isInteger(t)||t<1))return{error:sr,info:"roundProfile entries must be positive integers"};if(1!==n[n.length-1])return{error:sr,info:"roundProfile must end with 1 (final matchUp)"};const r=2*n[0];if(p(e)!==r)return{error:sr,info:`roundProfile[0] * 2 (${r}) must equal drawSize (${e})`};for(let t=0;t<n.length-1;t++){const e=n[t],r=2*n[t+1];if(r<e)return{error:sr,info:`round ${t+2} has ${r} slots but round ${t+1} produces ${e} winners (would drop winners)`}}return{profile:n}}(t.roundProfile,a);if(u.error||!u.profile)return{matchUps:[],roundsCount:0,error:u.error,info:u.info};const d=u.profile,l=L(1,2*d[0]+1).map(t=>({drawPosition:t}));let m=[],f=1;({matchUps:m}=gv({roundNumber:f,matchUpType:i,idPrefix:o,matchUps:m,isMock:s,nodes:l,uuids:c})),f++;let h=t.roundLimit||n;for(let t=1;t<d.length;t++){const e=d[t];r&&e===r&&(h=f-1);const n=L(1,e+1).map(t=>({roundPosition:t,roundNumber:f,matchUpId:fv({roundPosition:t,roundNumber:f,idPrefix:o,uuids:c})}));m.push(...n),f++}const g=f-1;return m=nI({finishingPositionOffset:e,lucky:!0,roundsCount:g,roundLimit:h,matchUps:m}),h&&(m=m.filter(t=>t.roundNumber<=h)),{matchUps:m,roundsCount:g,roundLimit:h,roundProfile:d}}function tU(t){const{playoffAttributes:e,stageSequence:n=1,stage:r=us,tieFormat:i,matchUpType:o,drawSize:a,uuids:s}=t,c=t.structureId||(()=>{if(!t.isMock&&!t.idPrefix)return;return`${t.drawDefinition.drawId}-s-0`})()||s?.pop(),u=t.appliedPolicies??xd(t),d=t.policyDefinitions?.[_u]||u?.[_u];t.skipRounds=t.skipRounds||a<=4&&(d?.feedFromMainFinal?0:1)||0;const p=t.structureName??e?.[0]?.name??Ny(us),l={[ks]:()=>({structures:[Ry({finishingPosition:pc,stageSequence:n,structureName:p,matchUps:[],matchUpType:o,structureId:c,stage:r})],links:[],...Y}),[nc]:()=>{const t=Ry({finishingPosition:pc,stageSequence:n,structureName:p,matchUps:[],matchUpType:o,structureId:c,stage:r});return a&&(t.positionAssignments=Array.from({length:a},(t,e)=>({drawPosition:e+1}))),{structures:[t],links:[],...Y}},[js]:()=>{if(t.roundProfile){const{matchUps:e,roundProfile:i,error:a,info:s}=Zv(t);if(a)return{error:a,info:s};const u=Ry({stageSequence:n,structureName:p,matchUpType:o,structureId:c,matchUps:e,stage:r});return i&&(u.extensions=[{name:"customRoundProfile",value:i}]),{structures:[u],links:[],...Y}}const{matchUps:e}=Kv(t);return{structures:[Ry({stageSequence:n,structureName:p,matchUpType:o,structureId:c,matchUps:e,stage:r})],links:[],...Y}},[Ls]:()=>(()=>{const{matchUps:e}=Sv(t);return{structures:[Ry({stageSequence:n,structureName:p,matchUpType:o,structureId:c,tieFormat:i,matchUps:e,stage:r})],links:[],...Y}})(),[Bs]:()=>Yv(t),[xs]:()=>yv({...t,childStage:ms,roundOffsetLimit:3,playoffAttributes:e??cc}),[_s]:()=>yv({...t,childStage:ms,roundOffsetLimit:2,playoffAttributes:e??uc}),[qs]:()=>Jv({...t,childStage:ms,roundOffsetLimit:t.roundOffsetLimit??3,playoffAttributes:e??dc}),[tc]:()=>vv(t),[ec]:()=>yv({...t,childStage:ms}),[Fs]:()=>{const{matchUps:t}=Iv({drawSize:a,uuids:s,matchUpType:o});return{structures:[Ry({stageSequence:n,structureName:p,matchUpType:o,structureId:c,stage:us,tieFormat:i,matchUps:t})],links:[],...Y}},[Gs]:()=>Ov(t),[Vs]:()=>xv({...t,feedRounds:1,fmlc:!0}),[Js]:()=>xv({...t,feedRounds:1}),[$s]:()=>xv({...t,feedsFromFinal:1}),[zs]:()=>xv({...t,feedsFromFinal:2}),[Ks]:()=>xv({...t,feedsFromFinal:3}),[Zs]:()=>xv(t),[Ws]:()=>Fv(t),[ic]:()=>Fy(t),[oc]:()=>function(t){const{drawDefinition:e,structureOptions:n,requireSequential:r}=t,i={structureName:Ny(us),...t,stage:us},{structures:o,groupCount:a,groupSize:s}=Fy(i);if(a<1)return{error:nr};const c=n?.playoffGroups||[{finishingPositions:[1],structureName:Ny(ms)}],[u]=o,{structures:d,links:p}=Bv({sourceStructureId:u.structureId,requireSequential:r,drawDefinition:e,playoffGroups:c,groupCount:a,groupSize:s,...t});return d&&o.push(...d),{...Y,structures:o,links:p}}(t)};return{generators:l}}function eU({element:t}){if(!t)return{error:sr};if(!t.timeItems)return{};if(!Array.isArray(t.timeItems))return{error:sr};return t.timeItems.reduce((e="itemType",n="itemValue",(t,r)=>r[e]?(t[r[e]]=r[n],t):t),{});var e,n}function nU(t){const{duplicateValues:e=!0,creationTime:n=!0,removePriorValues:r,timeItem:i}=t;if(!i)return{error:zn};const o=bm(t);if(o.error)return o;if(!(f(i)&&m(i.itemType)&&Object.keys(i).includes("itemValue")))return{error:$n};if(i.itemDate&&"string"==typeof i.itemDate&&!Do(i.itemDate))return{error:_e};if(o.timeItems){if(function({element:t,duplicateValues:e,timeItem:n}){const{itemType:r,itemSubTypes:i,itemValue:o}=n,a=r&&Nm({itemSubTypes:i,itemType:r,element:t})?.timeItem;return a&&JSON.stringify(a?.itemValue)===JSON.stringify(o)&&!e}({element:o,duplicateValues:e,timeItem:i}))return{...Y}}else o.timeItems=[];if(i.itemSubTypes&&!i.itemSubTypes.length&&delete i.itemSubTypes,n){const t=(new Date).toISOString();Object.assign(i,{createdAt:t})}r&&(o.timeItems=o.timeItems.filter(({itemType:t})=>i.itemType!==t));return r&&!i.itemValue||o.timeItems.push(i),{...Y}}function rU({creationTime:t=!0,removePriorValues:e,tournamentRecord:n,duplicateValues:r,participantId:i,timeItem:o}){if(!n)return{error:rt};if(!i)return{error:sn};const a=Rm({tournamentRecord:n,participantId:i});return a.error?a:nU({element:a.participant,removePriorValues:e,duplicateValues:r,creationTime:t,timeItem:o})}function iU(t){const{removePriorValues:e,tournamentRecord:n,duplicateValues:r,creationTime:i,timeItem:o}=t;if(!n)return{error:rt};const a=nU({element:n,removePriorValues:e,duplicateValues:r,creationTime:i,timeItem:o});if(a.error)return a;const s=eU({element:n});return di({payload:{parentOrganisation:n.parentOrganisation,tournamentId:n.tournamentId,timeItemValues:s},topic:Al}),a}function oU(t){const{removePriorValues:e,duplicateValues:n,creationTime:r,timeItem:i,event:o}=t;return o?nU({removePriorValues:e,duplicateValues:n,element:o,creationTime:r,timeItem:i}):{error:zt}}function aU(t){return cU({...t,itemType:"attachConsolationStructures"})}function sU(t){return cU({...t,itemType:"attachPlayoffStructures"})}function cU({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:n,drawDefinition:r,structures:i,links:o=[],event:a}){const s="attachStructures";if(!r)return{error:st};if(!Array.isArray(i)||!Array.isArray(o))return Ci({result:{error:sr},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(o.some(t=>{const e=c(t);return u?.includes(e)}))return Ci({result:{error:vr},info:"playoff structure exists",stack:s});if(o.length){const t=new Set([...r.structures?.map(({structureId:t})=>t)??[],...i.map(({structureId:t})=>t)]),e=o.filter(e=>!t.has(e.source.structureId)||!t.has(e.target.structureId));if(e.length)return Ci({result:{error:dt},info:"links reference non-existent structures",context:{invalidLinks:e.map(t=>({source:t.source.structureId,target:t.target.structureId}))},stack:s})}o.length&&r.links?.push(...o);const d=new Set(i.map(({structureId:t})=>t)),p=r.structures?.map(({structureId:t})=>t);r.structures=(r.structures??[]).map(t=>d.has(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),rI({drawDefinition:r});const m=i.map(t=>Fg({structure:t})?.matchUps??[]).flat();Hl({tournamentId:n?.tournamentId,eventId:a?.eventId,drawDefinition:r,matchUps:m});const f=i.map(({structureId:t})=>t);if(Ql({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,Yl(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(eI("structureId"));if(n){nU({element:n,timeItem:{itemValue:{structureIds:f,drawId:r.drawId},itemType:t}})}return{...Y,addedStructureIds:h}}function uU({structureName:t,structureType:e=ks,drawSize:n=2,matchUpFormat:r,matchUpType:i}){const o={stage:ps,stageSequence:1,structureName:t||Ny(ps),drawSize:n,matchUpFormat:r,matchUpType:i},{generators:a,error:s}=tU(o);if(s)return{error:s};const c=a[e];if(!c)return{error:St};const u=c();return u.error?u:{...Y,structures:u.structures}}function dU({drawDefinition:t,structureId:e,structureName:n,structureType:r=ks,drawSize:i=2,matchUpFormat:o,matchUpType:a,links:s=[]}){if(!t)return{error:st};if(e||(e=t.structures?.find(t=>t.stage===us)?.structureId),!e)return{error:jt};const{structure:c}=ol({drawDefinition:t,structureId:e});if(!c)return{error:jt};const u=uU({structureName:n,structureType:r,drawSize:i,matchUpFormat:o,matchUpType:a||t.matchUpType});if(u.error)return u;const d=u.structures?.[0];if(!d)return{error:St};const p=s.map(t=>({linkType:Cs,source:{roundNumber:t.sourceRoundNumber,structureId:e},target:{roundNumber:t.targetRoundNumber,feedProfile:Ns,structureId:d.structureId}}));return aU({drawDefinition:t,structures:[d],links:p})}function pU({drawDefinition:t,participantId:e,preferences:n}){if(!t)return{error:st};if(!e)return{error:Ze};if(!Array.isArray(n))return{error:sr};const r=dp({element:t,attribute:"draftState",name:ud});if(!r)return{error:mr,info:"No active draft found"};if("COMPLETE"===r.status)return{error:sr,info:"Draft is already complete"};const i=r.tiers?.find(t=>t.participantIds?.includes(e));if(!i)return{error:Ze,info:"Participant not in any draft tier"};const o=new Set(r.unassignedDrawPositions);for(const t of n)if(!o.has(t))return{error:Pt,info:`Draw position ${t} is not available`};const a=r.preferencesCount??3,s=n.slice(0,a);return r.preferences[e]=s,"SEEDS_PLACED"===r.status&&(r.status="COLLECTING_PREFERENCES"),sp({element:t,attribute:"draftState",name:ud,value:r}),{...Y}}function lU({alternateParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i,event:o}){return sv({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i,event:o})}function mU({targetMatchUpIds:t,drawDefinition:e}){if(!e)return{error:st};if(!Array.isArray(t)||!t.length)return{error:sr};const{exitProfiles:n}=Gf({drawDefinition:e}),r=e.structures??[],i={};let o=0;for(const e of r){const r=n?.[e.structureId]??[];if(e.structures?.length)for(const n of e.structures)o+=fU({exitProfiles:r,structure:n,parentStructure:e,targetMatchUpIds:t,idMap:i});o+=fU({exitProfiles:r,targetMatchUpIds:t,structure:e,idMap:i})}if(Object.keys(i).length)for(const t of r){gU(t,i);for(const e of t.structures??[])gU(e,i)}return{...Y,remappedCount:o}}function fU({parentStructure:t,targetMatchUpIds:e,exitProfiles:n,structure:r,idMap:i}){let o=0;const a=t?.stage??r.stage,s=t?.stageSequence??r.stageSequence;for(const c of r.matchUps??[]){const u=hU({stageSequence:s,roundPosition:c.roundPosition,roundNumber:c.roundNumber,structureId:r.structureId,parentStructureId:t?.structureId,stage:a,targetMatchUpIds:e,exitProfiles:n});u&&u.matchUpId!==c.matchUpId&&(i[c.matchUpId]=u.matchUpId,c.matchUpId=u.matchUpId,o++);for(const u of c.tieMatchUps??[]){const c=hU({stageSequence:s,roundPosition:u.roundPosition,roundNumber:u.roundNumber,structureId:r.structureId,parentStructureId:t?.structureId,stage:a,targetMatchUpIds:e,exitProfiles:n});c&&c.matchUpId!==u.matchUpId&&(i[u.matchUpId]=c.matchUpId,u.matchUpId=c.matchUpId,o++)}}return o}function hU({parentStructureId:t,targetMatchUpIds:e,stageSequence:n,roundPosition:r,exitProfiles:i,structureId:o,roundNumber:a,stage:s}){return e.find(e=>e.roundNumber===a&&e.roundPosition===r&&(e.structureId?e.structureId===o||e.structureId===t:e.exitProfile?i.includes(e.exitProfile):(!e.stage||e.stage===s)&&(!e.stageSequence||e.stageSequence===n)))}function gU(t,e){const n=t=>{t.winnerMatchUpId&&e[t.winnerMatchUpId]&&(t.winnerMatchUpId=e[t.winnerMatchUpId]),t.loserMatchUpId&&e[t.loserMatchUpId]&&(t.loserMatchUpId=e[t.loserMatchUpId]);for(const e of t.tieMatchUps??[])n(e)};for(const e of t.matchUps??[])n(e)}function IU({targetRoundNumber:t,finishingPosition:e,drawDefinition:n,structureId:r,linkType:i}){const{links:o}=Vg({drawDefinition:n,structureId:r})??{},a=(o?.target??[]).filter(({linkType:t})=>t===i).filter(({target:e})=>!t||t===e.roundNumber).map(t=>{const r=t.source.structureId,{structure:i}=ol({structureId:r,drawDefinition:n});if(!e||i?.finishingPosition===e)return t}).filter(Boolean);return{sourceStructureIds:a.map(({source:t})=>t.structureId),relevantLinks:a}}function SU({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i}){return sv({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:i})}function yU({drawDefinition:t,structureId:e}){if(!t)return{error:st};const{structure:n}=ol({drawDefinition:t,structureId:e}),r=(t?.links??[]).filter(t=>t.source?.structureId===e).map(t=>t.target?.structureId),i=(t?.structures??[]).filter(t=>r.includes(t.structureId));return{playoffStructures:i,structure:n}}function vU({withStageGrouping:t,stageSequences:e,stageSequence:n,roundTarget:r,stages:i,event:o,stage:a}){if(!o)return{error:Ht};const s={},c=[];for(const u of o.drawDefinitions??[]){const{structures:o,stageStructures:d}=al({withStageGrouping:t,stageSequences:e,drawDefinition:u,stageSequence:n,roundTarget:r,stages:i,stage:a});if(c.push(...o),d)for(const t of Object.keys(d))s[t]||(s[t]=[]),s[t].push(...d[t])}return{structures:c,stageStructures:s}}function UU({withStageGrouping:t,tournamentRecord:e,stageSequences:n,stageSequence:r,roundTarget:i,stages:o,stage:a}){if(!e)return{error:rt};const s={},c=[];for(const u of e.events??[]){const{structures:e,stageStructures:d}=vU({withStageGrouping:t,stageSequences:n,stageSequence:r,roundTarget:i,stages:o,event:u,stage:a});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 PU(t){if(!t?.drawDefinition)return!1;const e=Lg(t),n=e?.includesTeamMatchUps;let{completedMatchUps:r,pendingMatchUps:i,upcomingMatchUps:o}=e??{};n&&(r=r?.filter(({matchUpType:t})=>t===a),i=i?.filter(({matchUpType:t})=>t===a),o=o?.filter(({matchUpType:t})=>t===a));return!!(r?.length&&!i?.length&&!o?.length)}function TU(t){const{drawDefinition:e,structureId:n}=t;if(!e)return{error:st};const{playoffStructures:r}=yU({drawDefinition:e,structureId:n});if(!r?.length)return!1;const i=e?.entries?.filter(t=>t?.entryStatus&&Sf.includes(t.entryStatus))?.length??0;let o=0;return(r??[]).reduce((t,e)=>{const n=cl({structure:e}).positionAssignments??[],r=n?.filter(t=>(t.participantId&&o++,t?.bye??t?.participantId)).length;return!(!r||!t)},!!r.length)||o===i}function wU({targetRoundNumber:t=1,tournamentRecord:e,drawDefinition:n,event:r,randomList:i}){const o=fu({drawDefinition:n,event:r,tournamentRecord:e},[{[yc]:!0,[zc]:!0,[Ic]:!0}]);if(o.error)return o;const a=[],s=[],c=n.structures?.find(t=>t.stage===us&&1===t.stageSequence);if(!c)return Ci({result:{error:qt}});const u=(xd({tournamentRecord:e,drawDefinition:n,structure:c,event:r}).appliedPolicies??{})[bu],d=u?.requireCompletedStructures,{qualifierPositions:p,positionAssignments:l}=ul({structure:c});if(!p.length)return Ci({result:{error:Rn}});let m=L(0,p.length);i&&(m=((t,e)=>{const n=[...new Set(e.slice(0,t.length))],r=[...n].sort((t,e)=>t-e),i=new Set,o=[];n.forEach(e=>{const n=t.indexOf(e);if(-1===n||i.has(n)){const n=r.indexOf(e);let a=t.findIndex((t,e)=>!i.has(e));for(;i.has(a)&&-1===a&&i.size<t.length;)a=t.findIndex((t,e)=>!i.has(e)&&e>a);o.push(n),i.add(n)}else o.push(n),i.add(n)});const a=t.filter((t,e)=>!i.has(e));return[...o,...a]})(m,i));const f=l.map(t=>t.participantId).filter(Boolean),{relevantLinks:h}=IU({structureId:c.structureId,targetRoundNumber:t,linkType:Es,drawDefinition:n})??{},{relevantLinks:g}=IU({structureId:c.structureId,targetRoundNumber:t,linkType:As,drawDefinition:n})??{};return function({eliminationSourceLinks:t,requireCompletedStructures:e,assignedParticipantIds:n,qualifyingParticipantIds:r,drawDefinition:i}){for(const o of t){const t=i.structures?.find(t=>t.structureId===o.source.structureId);if(t?.stage!==ds)continue;const a=PU({structureId:o.source.structureId,drawDefinition:i});if(e&&!a)continue;const s=t.qualifyingRoundNumber,{matchUps:c}=Fg({matchUpFilters:{...s&&{roundNumbers:[s]},isCollectionMatchUp:!1,hasWinningSide:!0},afterRecoveryTimes:!1,inContext:!0,structure:t});for(const t of c){const e=t.matchUpStatus===Sp&&t.sides?.find(({participantId:t})=>t),i=t.sides.find(e=>e?.sideNumber===t.winningSide);if(i||e){const{participantId:t}=i||(e??{});t&&!n.includes(t)&&r.push(t)}}}}({eliminationSourceLinks:h,requireCompletedStructures:d,assignedParticipantIds:f,qualifyingParticipantIds:s,drawDefinition:n}),function({roundRobinSourceLinks:t,assignedParticipantIds:e,qualifyingParticipantIds:n,drawDefinition:r}){for(const i of t){const t=r?.structures?.find(t=>t.structureId===i.source.structureId);if(t?.stage!==ds)continue;if(!PU({structureId:i.source.structureId,drawDefinition:r}))continue;const{positionAssignments:o}=cl({structure:t}),a=o?.map(t=>{const e=t.participantId,n=dp({element:t,attribute:"tally",name:Rd});return n?{participantId:e,groupOrder:n?.groupOrder}:{}}).filter(({groupOrder:t,participantId:n})=>1===t&&!e.includes(n)).map(({participantId:t})=>t)??[];a&&n.push(...a)}}({roundRobinSourceLinks:g,assignedParticipantIds:f,qualifyingParticipantIds:s,drawDefinition:n}),s.length?(m.forEach((t,r)=>{const i=s[r],o=p[t].drawPosition;if(i){const t=SU({qualifyingParticipantId:i,structureId:c.structureId,drawPosition:o,tournamentRecord:e,drawDefinition:n});t?.success&&a.push({participantId:i,drawPosition:o})}}),Ci({result:Ei({...Y,assignedParticipants:a})})):Ci({result:{error:cn}})}function DU({significantCharacters:t,accessors:e=[],value:n}){const r=[],i=e[0];if(n?.[i]){const o=e.slice(1);if(Array.isArray(n[i])){n[i].forEach(e=>{const n=DU({accessors:o,significantCharacters:t,value:e});r.push(...n)})}else if(n=n[i],o.length){const e=DU({accessors:o,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 RU({targetParticipantIds:t,policyAttributes:e,idCollections:n,participants:r}){if(!Array.isArray(e))return{error:Te};if(!Array.isArray(r))return{error:an};const i={};return t.forEach(t=>{const o=r.find(e=>e.participantId===t),{values:a}=bU({policyAttributes:e,idCollections:n,participants:r,participant:o});a&&a.forEach(e=>{i[e]||(i[e]=[]),i[e].includes(t)||i[e].push(t)})}),i}function bU({policyAttributes:t,idCollections:e,participants:n,participant:r}){if(!Array.isArray(t))return{error:Te};if(!r)return{error:on};const i=[];t.forEach(t=>{const{directive:o,groupings:a,key:s,significantCharacters:c}=t??{};if(s){const t=s.split(".");i.push(...DU({significantCharacters:c,value:r,accessors:t}))}else if(o){const a=t?.includeIds,s=(e?.[o]??[]).filter(t=>!a||a.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 a&&Object.keys(a).forEach(t=>{a[t].includes(r.participantId)&&i.push(t)})});return{values:M(i)}}function NU({candidatePositionAssignments:t,participantsWithGroupings:e,policyAttributes:n,idCollections:r}){const i=Object.assign({},...e.map(t=>({[t.participantId]:t})));return t.map(t=>{const o=i[t.participantId],{values:a}=bU({participants:e,policyAttributes:n,idCollections:r,participant:o});return{...t,values:a}})}function MU({participantIdGroups:t,positionAssignments:e,groupsToAvoid:n}){return Object.assign({},...e.filter(t=>t?.participantId).map(e=>{const{drawPosition:r,participantId:i}=e,o=t?t[i]??[]:[],a=!!n.some(t=>o.includes(t));return{[r]:{participantGroups:o,includesGroupsToAvoid:a}}}))}function AU(t){const{unfilledPositions:e,chunkedDrawPositions:n}=t,r=MU(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=EU(e);return!t.includes(n)}}(n),o=n.filter(t=>!i.includes(t)).filter(t=>{const e=EU(t);return!r[e]?.includesGroupsToAvoid});return{unassigned:n,unpaired:i,pairedNoConflict:o}})}function EU(t){return Number(t%2?t+1:t-1)}function CU({selectedParticipantGroups:t,participantIdGroups:e,positionAssignments:n,drawPositionChunks:r,unfilledPositions:i,isRoundRobin:o}){const a=r.map(r=>o?function(t){const{unfilledPositions:e,chunkedDrawPositions:n}=t,r=MU(t);return n.map(t=>{const n=e.filter(e=>t.includes(e)),i=n.length===t.length?n:[],o=t.filter(t=>r[t]?.includesGroupsToAvoid).length;return{unassigned:n,unpaired:i,pairedNoConflict:o?[]:n,conflictsCount:o}})}({groupsToAvoid:t,chunkedDrawPositions:r,participantIdGroups:e,positionAssignments:n,unfilledPositions:i}):AU({groupsToAvoid:t,chunkedDrawPositions:r,participantIdGroups:e,positionAssignments:n,unfilledPositions:i}));if(o){return{unassigned:a.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:a.map(t=>t.map(t=>t.unpaired).filter(t=>t?.length)).filter(t=>t?.length),pairedNoConflict:a.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:a.map(t=>t.map(t=>t.unassigned).filter(t=>t?.length)).filter(t=>t?.length),unpaired:a.map(t=>t.map(t=>t.unpaired).filter(t=>t?.length)).filter(t=>t?.length),pairedNoConflict:a.map(t=>t.map(t=>t.pairedNoConflict).filter(t=>t?.length)).filter(t=>t?.length)}}function OU({positionAssignments:t,participantIds:e}){const n=t.map(t=>t.participantId);return e.filter(t=>!n.includes(t))}function kU({candidatePositionAssignments:t,unseededParticipantIds:e,participantIdGroups:n,drawPositionChunks:r,drawPositionGroups:i,pairedPriority:o,allGroups:a,groupKey:s,random:c}){const u=i.reduce((t,e)=>e.length>t?e.length:t,0)<=2,d=OU({positionAssignments:t,participantIds:e}),p=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:l,groupKey:m}=function({useSpecifiedGroupKey:t=!1,targetParticipantIds:e,largestFirst:n=!0,allGroups:r,groupKey:i,random:o}){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}))),s=Object.keys(a).reduce((t,e)=>a[e].length>t?a[e].length:t,0),c=Object.keys(a).filter(t=>a[t].length===s),u=_(n?c:Object.keys(a),o);return{participantId:(i=t&&a[i]?.length?i:u)&&a[i]?_(a[i],o):_(e,o),groupKey:i}}({targetParticipantIds:d,useSpecifiedGroupKey:u,allGroups:a,groupKey:s,random:c}),f=function({allGroups:t,participantId:e}){return Object.keys(t).filter(n=>t[n].includes(e))}({participantId:l,allGroups:a}),h=CU({positionAssignments:t,isRoundRobin:u,selectedParticipantGroups:f,participantIdGroups:n,drawPositionChunks:r,unfilledPositions:p}),{unassigned:g,unpaired:I,pairedNoConflict:S}=h,y=S?.length&&S[0],v=I?.length&&I[0],U=o&&y?y:v,P=o?v:y,T=U?.length&&U||P?.length&&P;let w;if(T?.length){const t=x(T,c);w=x(t,c)}else{const t=x(g[0],c);w=x(t,c)}return{newGroupKey:m,selectedParticipantId:l,targetDrawPosition:w}}function FU({isRoundRobin:t,groupedParticipants:e}){const n=[];return t?e.forEach(t=>{const e=Ey({drawPositions:t.map(t=>t.drawPosition)}).uniqueMatchUpGroupings??[],r=Object.assign({},...t.map(t=>({[t.drawPosition]:t})));e.forEach(e=>{j(r[e[0]].values??[],r[e[1]].values??[])&&(n.push(e),t.conflict=!0)})}):e.forEach(t=>{j(t[0]?.values??[],t[1]?.values??[])&&(n.push(t),t.conflict=!0)}),n}function xU(t,e){return t.find(t=>t.drawPosition===e)}function _U({positionedParticipants:t,potentialDrawPositions:e,drawPositionGroups:n,avoidanceConflicts:r,isRoundRobin:i}){return r.flatMap(r=>{const o=r.map(t=>t.drawPosition);return r.filter(t=>e.includes(t.drawPosition)).map(r=>{const a=e.filter(t=>!o?.includes(t)).filter(e=>function({moveableParticipant:t,possibleDrawPosition:e,positionedParticipants:n,drawPositionGroups:r,isRoundRobin:i,getAvoidanceConflicts:o}){const a=function(t,e){const n=t.find(t=>t.includes(e));if(n)return n.find(t=>t!==e)}(r,e),s=xU(n,a),c=o({isRoundRobin:i,groupedParticipants:[[t,s]]}),u=o({isRoundRobin:i,groupedParticipants:[[xU(n,e),s]]});return!c.length&&!u.length}({moveableParticipant:r,possibleDrawPosition:e,positionedParticipants:t,drawPositionGroups:n,isRoundRobin:i,getAvoidanceConflicts:FU}));if(a.length)return{drawPosition:r.drawPosition,possibleDrawPositions:a}}).filter(Boolean)})}function LU(t){const{initialPositionAssignments:e,participantsWithGroupings:n,opponentsToPlaceCount:r,unseededByePositions:i,drawPositionGroups:o,policyAttributes:a,idCollections:s,allGroups:c,random:u}=t,d=[];let p;const l=Math.min(...(o??[]).map(t=>t?.length).filter(Boolean)),m=l>2,f=ca(e,!1,!0).filter(t=>!t.qualifier),h=e.filter(t=>!t.participantId&&!t.qualifier&&(!t.bye||i?.includes(t.drawPosition))).map(t=>t.drawPosition);L(0,r).forEach(()=>{const{newGroupKey:e,selectedParticipantId:n,targetDrawPosition:r}=kU({...t,candidatePositionAssignments:f,allGroups:c,groupKey:p});p=e,f.forEach(t=>{t.drawPosition===r&&(t.participantId=n)})});let g=NU({candidatePositionAssignments:f,participantsWithGroupings:n,policyAttributes:a,idCollections:s}),I=q(g,l),S=FU({groupedParticipants:I,isRoundRobin:m}),y=0;for(;y<20&&S.length;){const t=_U({positionedParticipants:g,potentialDrawPositions:h,avoidanceConflicts:S,drawPositionGroups:o,isRoundRobin:m});if(t.length){const e=BU({candidatePositionAssignments:f,swapOptions:t,random:u});e.error&&console.log({result:e}),g=NU({candidatePositionAssignments:f,participantsWithGroupings:n,policyAttributes:a,idCollections:s}),I=q(g,l),S=FU({groupedParticipants:I,isRoundRobin:m}),y++}else y=20}return f.forEach(t=>{if(t.bye&&t.participantId){const t=Ot;d.push(t)}if(t.qualifier&&t.participantId){const t=Ot;d.push(t)}}),{positionAssignments:f,conflicts:S.length,groupedParticipants:I,errors:d}}function BU({candidatePositionAssignments:t,swapOptions:e,random:n}){const r=x(e,n);if(!r)return{error:{message:"No swap options"}};const i=r.drawPosition,o=x(r.possibleDrawPositions,n),a=t.find(t=>t.drawPosition===i),s=t.find(t=>t.drawPosition===o)??{},c={participantId:s?.participantId,qualifier:s?.qualifier,bye:s?.bye},u={participantId:a.participantId,qualifier:a.qualifier,bye:a.bye};return Object.assign(a,c),Object.assign(s,u),{...Y}}function VU({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:n,unseededByePositions:r,tournamentRecord:i,drawDefinition:o,seedBlockInfo:a,participants:s,matchUpsMap:c,structureId:u,avoidance:p,drawSize:l,event:m,random:f}){if(!p)return{error:Pe};const{candidatesCount:h=1,policyAttributes:g,targetDivisions:I}=p;let{roundsToSeparate:y}=p;const v="randomUnseededSeparation",{structure:P}=ol({drawDefinition:o,structureId:u}),{matchUps:T}=Fg({provisionalPositioning:t,matchUpsMap:c,structure:P,event:m});if(I&&S(I)&&!y){const t=function(t){if(1===t)return!1;if(Number.isNaN(Number(t)))return!1;if(!S(t))return!1;let e=t,n=1;for(;2!==e;)n+=1,e/=2;return n}(I)||0,e=T.reduce((t,e)=>Math.max(Number(e.roundNumber),t),0);y=e<t?1:e-t+1}const{positionAssignments:w}=ul({structure:P}),D=Pm({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:s}).participantsWithGroupings,R=w?.filter(t=>!t.participantId),b=w?.map(t=>t.drawPosition),N=P?.structureType===Ds,M=N?{structure:P,matchUps:T,allDrawPositions:b,roundsToSeparate:y}:{matchUps:T,allDrawPositions:b,roundsToSeparate:y},{drawPositionGroups:A,drawPositionChunks:E}=N?function(t){const{structure:{structures:e}}=t,n=e.map(t=>t.positionAssignments.map(t=>t.drawPosition));return{drawPositionGroups:n,drawPositionChunks:[n]}}(M):function({allDrawPositions:t,roundsToSeparate:e,matchUps:n}){const r=n.filter(t=>1===t.roundNumber).map(t=>t.drawPositions),i=r.flat().sort(d),o=Math.max(...i),a=t.filter(t=>t>o),s=i.length,c=L(2===s?1:2,s).filter(t=>t===U(t)),u=c.slice(0,e||c.length).reverse(),p=u.map(t=>q(i,t));a.length&&console.log({fedDrawPositions:a});return{drawPositionGroups:r,drawPositionChunks:p}}(M),C={groupParticipants:s.filter(t=>t.participantType===Im).map(t=>t.participantId),teamParticipants:s.filter(t=>t.participantType===ym).map(t=>t.participantId),pairParticipants:s.filter(t=>t.participantType===Sm).map(t=>t.participantId)},O=RU({targetParticipantIds:e,policyAttributes:g,idCollections:C,participants:s});if(O.error)return Ci({result:O,stack:v});const k=Object.assign({},...e.map(t=>{const e=Object.keys(O).filter(e=>(O[e]??[]).includes(t));return{[t]:e}})),F=OU({participantIds:e,positionAssignments:w});if(F.length>(R?.length||0))return{error:bn};let x;const _=F.length,B=L(0,h).map(()=>LU({initialPositionAssignments:w,participantsWithGroupings:D,unseededParticipantIds:e,opponentsToPlaceCount:_,pairedPriority:!1,unseededByePositions:r,participantIdGroups:k,drawPositionChunks:E,drawPositionGroups:A,policyAttributes:g,idCollections:C,allGroups:O,drawSize:l,random:f}));if(x=B.reduce((t,e)=>!t||(e.conflicts||0)<(t.conflicts||0)?e:t,void 0),!x||x.conflicts){const t=L(0,h).map(()=>LU({initialPositionAssignments:w,participantsWithGroupings:D,unseededParticipantIds:e,opponentsToPlaceCount:_,pairedPriority:!0,unseededByePositions:r,participantIdGroups:k,drawPositionChunks:E,drawPositionGroups:A,policyAttributes:g,idCollections:C,allGroups:O,drawSize:l,random:f})),n=B.concat(...t).filter(t=>!t.errors?.length);x=n.reduce((t,e)=>!t||(e.conflicts||0)<(t.conflicts||0)?e:t,void 0)}if(!x)return{error:er};const V=new Set((cl({structure:P})?.positionAssignments??[]).filter(t=>t.participantId).map(t=>t.participantId)),G=x.positionAssignments.filter(t=>!V.has(t.participantId));for(const t of G)if(t.bye){const e=SI({tournamentRecord:i,drawDefinition:o,structureId:u,matchUpsMap:c,event:m,...t});if(e.error)return Ci({result:e,stack:v})}else if(t.participantId){const e=av({inContextDrawMatchUps:n,tournamentRecord:i,drawDefinition:o,seedBlockInfo:a,structureId:u,matchUpsMap:c,event:m,...t});if(e.error)return Ci({result:e,stack:v,context:{assignment:t}})}return{...Y}}function GU({provisionalPositioning:t,inContextDrawMatchUps:e,unseededByePositions:n,multipleStructures:r,tournamentRecord:i,drawDefinition:o,seedBlockInfo:a,participants:s,matchUpsMap:c,structureId:u,structure:d,drawSize:p,event:l,random:m}){d||({structure:d}=ol({drawDefinition:o,structureId:u})),u||({structureId:u}=d);const{positionAssignments:f}=ul({structure:d}),{seedAssignments:h}=Tf({provisionalPositioning:t,drawDefinition:o,structure:d}),g=h?.map(t=>t.participantId).filter(Boolean),{stage:I,stageSequence:S}=d,y=I===ds?dp({element:d,attribute:"roundTarget",name:vd}):void 0,v=Pf({provisionalPositioning:t,drawDefinition:o,stageSequence:S,entryStatuses:If,structureId:u,roundTarget:y,stage:I}),U=v.filter(t=>!g?.includes(t.participantId)).map(t=>t.participantId),P=f?.filter(t=>!t.participantId&&!t.bye&&!t.qualifier).map(t=>t.drawPosition);if(!r&&U.length>(P?.length||0))return Ci({result:{error:bn},context:{unseededParticipantsCount:U.length,unfilledDrawPositionsCount:P?.length},stack:"positionUnseededParticipants"});const{appliedPolicies:T}=xd({tournamentRecord:i,drawDefinition:o,event:l});let w=T?.[ku];if(d.stage===ms){const t=v.reduce((t,e)=>(t[e.groupingValue]||(t[e.groupingValue]=[]),t[e.groupingValue].push(e.participantId),t),{});Object.keys(t).length&&(w??={policyName:"Playoff Avoidance"},w.policyAttributes??=[],w.policyAttributes.push({groupings:t}))}return w&&s?VU({provisionalPositioning:t,unseededParticipantIds:U,inContextDrawMatchUps:e,unseededByePositions:n,tournamentRecord:i,drawDefinition:o,seedBlockInfo:a,participants:s,matchUpsMap:c,structureId:u,avoidance:w,drawSize:p,random:m}):function({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:n,unfilledDrawPositions:r,multipleStructures:i,tournamentRecord:o,drawDefinition:a,seedBlockInfo:s,matchUpsMap:c,structureId:u,drawSize:d,event:p,random:l}){const m=d>2?A(r,l):r.reverse();for(const r of e){const e=m.pop();if(!i||e){const i=av({provisionalPositioning:t,inContextDrawMatchUps:n,tournamentRecord:o,drawDefinition:a,seedBlockInfo:s,participantId:r,drawPosition:e,matchUpsMap:c,structureId:u,event:p});if(i?.error&&console.log("!!!!!",{result:i}),i?.error)return Ci({result:i,stack:"randomUnseededDistribution"})}}return{...Y}}({provisionalPositioning:t,unseededParticipantIds:U,inContextDrawMatchUps:e,unfilledDrawPositions:P,multipleStructures:r,tournamentRecord:i,drawDefinition:o,seedBlockInfo:a,structureId:u,matchUpsMap:c,drawSize:p,event:l,random:m})}function jU(t){const{random:e}=t,n=t.structure??ol(t).structure,r="positionQualifiers",i=[];if(n.stage===ps)return Ci({result:{error:Zt},stack:r});const{unplacedRoundQualifierCounts:o,positionAssignments:a,roundDrawPositions:s}=function({drawDefinition:t,structure:e,structureId:n,qualifiersCount:r}){e||({structure:e}=ol({drawDefinition:t,structureId:n}));n||({structureId:n}=e);const{positionAssignments:i}=ul({structure:e}),{stage:o,stageSequence:a}=e,{qualifiersCount:s,roundQualifiersCounts:c}=$S({drawDefinition:t,structureId:n}),u=s||r||0,d=Object.keys(c??{}).length?c:u?{1:u}:{},l=(d?Object.keys(d):[]).map(t=>p(t)),{matchUps:m}=Fg({structure:e}),{roundProfile:f}=Bf({matchUps:m}),h=Object.assign({},...l.filter(t=>f?.[t]).map(t=>({[t]:f?.[t]?.drawPositions?.filter(Boolean)??[]}))),g=i?.filter(t=>t.qualifier).map(t=>t.drawPosition),I=(u??0)-(g?.length??0),S=g?.length,y=Object.assign({},...l.map(t=>{const e=i?.filter(e=>e.qualifier&&h[t]?.drawPositions?.includes(e.drawPosition)).map(t=>t.drawPosition);return{[t]:(d?.[t]??0)-(e?.length??0)}}));return{unplacedRoundQualifierCounts:y,unplacedQualifiersCount:I,placedQualifiersCount:S,roundQualifiersCounts:d,positionAssignments:i,roundDrawPositions:h,qualifiersCount:u}}(t);for(const t of Object.keys(o)){const n=a?.filter(e=>s[t].includes(e.drawPosition)&&!e.participantId&&!e.qualifier&&!e.bye).map(t=>t.drawPosition);if(o[t]>(n||0))return Ci({result:{error:Rn},context:{unfilledDrawPositions:n},stack:r});L(0,o[t]).forEach(()=>{const t=x(n,e);i.push(t),a?.forEach(e=>{e.drawPosition===t&&(e.qualifier=!0,delete e.participantId,delete e.bye)})})}return{...Y,qualifierDrawPositions:i}}function qU({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:n,appliedPolicies:r,validSeedBlocks:i,drawDefinition:o,seedingProfile:a,seedBlockInfo:s,participants:c,groupsCount:u,structureId:d,matchUpsMap:p,structure:l,random:m,event:f}){const h=[],g=[];let I=0;if(l||({structure:l}=ol({drawDefinition:o,structureId:d})),d||(d=l?.structureId),r??=xd({drawDefinition:o}).appliedPolicies,!i){const e=l&&Gy({provisionalPositioning:t,appliedPolicies:r,drawDefinition:o,seedingProfile:a,structure:l,random:m});e?.error&&g.push(e.error),i=e?.validSeedBlocks}return L(0,u=u??i?.length??0).forEach(()=>{if(I<(u||0)){const r=function({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,seedingProfile:i,seedBlockInfo:o,participants:a,structureId:s,matchUpsMap:c,random:u,event:d}){const{unplacedSeedParticipantIds:p,unfilledPositions:l}=$y({provisionalPositioning:t,randomize:!0,drawDefinition:r,seedingProfile:i,seedBlockInfo:o,structureId:s,random:u}),{appliedPolicies:m}=xd({drawDefinition:r}),f=m?.[ku];f?.policyAttributes&&a&&p?.length>2&&function({unplacedSeedParticipantIds:t,unfilledPositions:e,policyAttributes:n,participants:r}){const i=RU({targetParticipantIds:t,policyAttributes:n,participants:r});if("error"in i)return;const o=i,a=Object.values(o).filter(t=>t.length>1);if(!a.length)return;const s=e.length;if(s<2)return;const c=Math.max(...e),u=Math.min(s,Math.max(2,a.length)),d=Math.ceil(c/u),p=t=>Math.floor((t-1)/d),l=t.map((t,n)=>{const r=e[s-1-n];return void 0===r?n:p(r)});for(const e of a){const n=e.map(e=>t.indexOf(e)),r=n.map(t=>l[t]);if(!(r.length!==new Set(r).size))continue;const i=new Set(e),o=t.map((t,e)=>i.has(t)?-1:e).filter(t=>t>=0),a=new Set;for(const e of n){const n=l[e];if(!a.has(n)){a.add(n);continue}const r=o.find(t=>!a.has(l[t]));if(void 0!==r){const n=t[e];t[e]=t[r],t[r]=n;const i=l[e];l[e]=l[r],l[r]=i,a.add(l[e]);const s=o.indexOf(r);s>=0&&o.splice(s,1)}}}}({unplacedSeedParticipantIds:p,unfilledPositions:l,policyAttributes:f.policyAttributes,participants:a});const h=[];for(const a of p){const u=l.pop();if(!u)return{error:Tt};h.push(u);const p=av({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,seedingProfile:i,participantId:a,seedBlockInfo:o,drawPosition:u,matchUpsMap:c,structureId:s,event:d});if(!p.success)return p}return{...Y,seedPositions:h}}({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:o,seedingProfile:a,seedBlockInfo:s,participants:c,structureId:d,matchUpsMap:p,random:m,event:f});r?.success&&(I++,h.push(...r.seedPositions??[])),r.error&&g.push({seedPositionError:r.error})}}),g.length?{error:g}:{...Y,seedPositions:h}}function WU({orderedSortedFirstRoundSeededDrawPositions:t,validSeedBlocks:e,byesToPlace:n,random:r}){const i=r??Math.random,o=[];e.forEach(e=>function(t,e,n,r,i){const o=e-n.length;if(o>t.drawPositions.length)n.push(...t.drawPositions);else{!function(t,e,n,r){let i,o=n[e.length];for(;i=$U(t,o,r);)e.push(i),o=n[e.length]}(HU(q(t.drawPositions,2)),n,r,i)}}(e,n,o,t,i));const a=o.map(t=>Array.isArray(t)?A(t,r):t).flat(1/0);if(T(n)){if(e.map(t=>t.seedNumbers[0]).includes(n))return t}return a}function $U(t,e,n){return Array.isArray(t)&&2!==t.length?t.pop():Array.isArray(t[0])?function(t,e,n){const r=t[0].flat(1/0).length,i=t[1].flat(1/0).length;if(r===i){const r=t[0].flat(1/0).includes(e)?t[0]:t[1];return $U(e?r:t[Math.round(n())],e,n)}return $U(r<i?t[1]:t[0],e,n)}(t,e,n):function(t,e,n){return t.includes(e)?t.indexOf(e)?t.pop():t.shift():Math.round(n())?t.pop():t.shift()}(t,e,n)}function HU(t){const e=Math.floor(t.length/2);return t.length>2?[HU(t.slice(0,e)),HU(t.slice(e))]:t}function zU({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:n,drawDefinition:r,seedingProfile:i,seedBlockInfo:o,byesToPlace:a,structure:s}){o||(o=Gy({provisionalPositioning:t,appliedPolicies:n,drawDefinition:r,seedingProfile:i,structure:s}));const{isFeedIn:c,isLuckyStructure:u,isContainer:d}=o;let{validSeedBlocks:p}=o;n?.seeding?.containerByesIgnoreSeeding&&(p=[]);const l=function({provisionalPositioning:t,drawDefinition:e,structure:n}){const{positionAssignments:r}=ul({structure:n}),{seedAssignments:i}=Tf({provisionalPositioning:t,drawDefinition:e,structure:n}),o=Object.assign({},...(i??[]).filter(t=>t.participantId).map(t=>({[t.participantId]:t})));return r?.map(t=>o[t.participantId]?{...t,seedNumber:o[t.participantId].seedNumber,seedValue:o[t.participantId].seedValue}:"").filter(Boolean)}({provisionalPositioning:t,drawDefinition:r,structure:s})??[],m=M([].concat(...e.map(t=>t.drawPositions))),f=l.filter(t=>m.includes(t.drawPosition)),h=(t,e)=>Vy(t.seedValue)-Vy(e.seedValue),g=p.reduce((t,e)=>{const n=f.filter(t=>e.drawPositions?.includes(t.drawPosition)).sort(h);return t.concat(...n)},[]).map(t=>t.drawPosition),I=WU({orderedSortedFirstRoundSeededDrawPositions:g,validSeedBlocks:p,byesToPlace:a});return{strictSeedOrderByePositions:YU({orderedSeedDrawPositions:g,relevantMatchUps:e}).slice(0,a),blockSeedOrderByePositions:YU({orderedSeedDrawPositions:I,relevantMatchUps:e}).slice(0,a),isLuckyStructure:u,positionedSeeds:l,isContainer:d,isFeedIn:c}}function YU({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 KU({provisionalPositioning:t,tournamentRecord:e,appliedPolicies:n,drawDefinition:r,seedBlockInfo:i,seedingProfile:o,matchUpsMap:a,structureId:s,structure:c,seedLimit:u,seedsOnly:p,event:l,random:m}){c||({structure:c}=ol({drawDefinition:r,structureId:s})),s||(s=c?.structureId);const f=!(c?.structures??c?.stage===ds),{byesCount:h,placedByes:g,relevantMatchUps:I}=function({provisionalPositioning:t,drawDefinition:e,matchUpsMap:n,structure:r,event:i}){const{matchUps:o,roundMatchUps:a}=Fg({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:{isCollectionMatchUp:!1},matchUpsMap:n,structure:r,event:i}),s=a?.[1]??[],c=r?.structureType===Ds,u=c?o:s,d=c?r?.structures?.length||0:o.length,{structureId:p,stage:l,stageSequence:m}=r,f=Pf({entryStatuses:Sf,provisionalPositioning:t,drawDefinition:e,stageSequence:m,structureId:p,stage:l}),{qualifiersCount:h}=$S({provisionalPositioning:t,drawDefinition:e,structureId:p}),g=f.length+(h??0),{positionAssignments:I,unassignedPositions:S}=ul({structure:r}),y=S?.map(t=>t.drawPosition),v=I?.filter(t=>t.bye).length,U=I?.filter(t=>t.bye).map(t=>t.drawPosition),P=u.map(t=>t.drawPositions).filter(t=>t?.reduce((t,e)=>!U?.includes(e)&&t,!0)).flat(1/0).filter(t=>y?.includes(t)),T=I?.length;let w=T?T-g:0;return w>d&&1===r.stageSequence&&r.stage!==ps&&(w=d),{placedByes:v,byesCount:w,relevantMatchUps:u,placedByePositions:U,roundMatchUps:a,positionsToAvoidDoubleBye:P}}({provisionalPositioning:t,drawDefinition:r,matchUpsMap:a,structure:c,event:l}),S=h-(g||0);if(S<=0)return{...Y};if(qf(r.drawType)){const n=(I??[]).flatMap(t=>t.drawPositions??[]).filter(Boolean),i=new Set(c?.positionAssignments?.filter(t=>t.participantId).map(t=>t.drawPosition)??[]),o=n.filter(t=>!i.has(t)).slice(0,S);for(const n of o){const i=SI({provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:a,structureId:s,structure:c,event:l});if(i?.error)return i}return{...Y,byeDrawPositions:o}}const{strictSeedOrderByePositions:y,blockSeedOrderByePositions:v,isLuckyStructure:U,isFeedIn:P}=zU({provisionalPositioning:t,relevantMatchUps:I,appliedPolicies:n,drawDefinition:r,seedingProfile:o,seedBlockInfo:i,byesToPlace:S,structure:c}),T=c?.structureType&&[Ds,ws].includes(c.structureType)&&n?.seeding?.containerByesIgnoreSeeding,w=f&&v?.length?v:y;let{unseededByePositions:D}=function({provisionalPositioning:t,seedOrderByePositions:e,isLuckyStructure:n,appliedPolicies:r,drawDefinition:i,seedLimit:o,structure:a,isFeedIn:s,random:c}){const u=r?.seeding?.seedingProfile,p=a.stage===ds,{positionAssignments:l}=ul({structure:a}),m=l?.filter(t=>t.participantId).map(t=>t.drawPosition),{matchUps:f,roundMatchUps:h}=Fg({provisionalPositioning:t,matchUpFilters:{isCollectionMatchUp:!1},structure:a}),g=h?.[1]??[],I=a.structureType===Ds?f:g,S=M(I.flatMap(t=>t.drawPositions)),y=Math.min(...S)-1,v=m?.filter(t=>S.includes(t)),U=t=>{const e=Math.ceil(t.length/2),n=[t.slice(0,e),t.slice(e)],r=n.map(t=>t.flat(1/0).flat().length),i=Math.min(...r.flat(1/0)),o=Math.max(...r.flat(1/0)),a=r.indexOf(o),s=i!==o,u=A(n,c),[d,p]=!i||s?[n[a],n[1-a]]:[u[0],u[1]];return{greaterHalf:d,lesserHalf:p}},P=t=>{const{greaterHalf:e,lesserHalf:n}=U(t),{greaterHalf:r,lesserHalf:i}=U(e),o=A(r.flat(1/0),c).pop();return{newlyFilteredChunks:[...n,...i,r.flat().filter(t=>t!==o)],drawPosition:o}},T=t=>!v?.includes(t),w=t=>{let e=q(t.sort(d),Math.ceil(t.length/4)).map(t=>t.filter(T));const n=e.flat(1/0).flat().length,r=[];for(let t=0;t<n;t++){const{newlyFilteredChunks:t,drawPosition:n}=P(e);r.push(n),e=t}return r},{validSeedBlocks:D}=Gy({provisionalPositioning:t,allPositions:!0,appliedPolicies:r,drawDefinition:i,structure:a}),R=D?.map(t=>t.drawPositions?.map(t=>t+y));let b;if(s){const t=S.length,{seedBlocks:e}=_y({cluster:[vs,Us].includes(Hy(u)),participantsCount:t});b=e.map(t=>t.map(t=>t+y)).map(w).filter(t=>t.length)}else b=p?R?.map(t=>t.filter(T)):R?.map(w).filter(t=>t.length);const N=I.map(t=>t.drawPositions).map(t=>t?.sort((t,e)=>t-e)).filter(t=>t?.[0]+1===t?.[1]),E=t=>N.reduce((e,n)=>n.includes(t)?n.reduce((e,n)=>n===t?e:n,void 0):e,void 0);let C=b.map(t=>t.map(E)).flat(1/0).filter(T).filter(t=>!e.includes(t)).filter(Boolean);if(p&&!a.structures){const t=o%4,e=C.slice(0,t),n=h[a.roundLimit]?.length,r=q(C.slice(t),n).flatMap(t=>A(t,c));C=e.concat(r)}return{unseededByePositions:C}}({provisionalPositioning:t,seedOrderByePositions:w,isLuckyStructure:U,appliedPolicies:n,drawDefinition:r,seedLimit:u,structure:c,isFeedIn:P,random:m});let R=w.flat();if(!p)for(;D.length;){const t=D.find(t=>{return e=t,(R??[]).every(t=>t%2?e!==t+1:e!==t-1);var e});t?(R.push(t),D=D.filter(e=>e!==t)):(R.push(...D),D=[])}T&&(R=A(R,m),$r({ignoreSeededByes:T})&&console.log({byePositions:R}));const b=R.slice(0,S);for(const n of b){const i=SI({provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:a,structureId:s,structure:c,event:l});if(i?.error)return i}return{...Y,unseededByePositions:D,byeDrawPositions:b}}function QU(t,e){return e||ri(),Ci({result:t,stack:"automatedPositioning"})}function JU(t){let{drawDefinition:e}=t;const{applyPositioning:n=!0,provisionalPositioning:r,multipleStructures:i,placeByes:o=!0,tournamentRecord:a,seedingProfile:s,structureId:c,seedLimit:u,seedsOnly:d,drawType:p,drawSize:l,random:m,event:f}=t,h=[];n||(ni(),e=ca(e,!1,!0));const{structure:g,appliedPolicies:I,qualifiersCount:S,entries:y,error:v}=function(t,e,n,r){const i=ol({drawDefinition:e,structureId:n});if(i.error)return{error:i.error};const o=i.structure;if(!o)return{error:Vt};const a=t.appliedPolicies||xd({drawDefinition:e,structure:o,event:r})?.appliedPolicies,{qualifiersCount:s}=$S({stageSequence:o.stageSequence,provisionalPositioning:t.provisionalPositioning,stage:o.stage,drawDefinition:e,structureId:n}),c=s||t.qualifiersCount||0,u=If;return{structure:o,appliedPolicies:a,qualifiersCount:c,entries:Pf({stageSequence:o.stageSequence,provisionalPositioning:t.provisionalPositioning,stage:o.stage,placementGroup:t.placementGroup,drawDefinition:e,entryStatuses:u,structureId:n})}}(t,e,c,f);if(v)return QU(v,n);if(!y?.length&&!S)return function(t,e){return e||ri(),t}({...Y},n);const U=t.matchUpsMap??bf({drawDefinition:e}),P=t.inContextDrawMatchUps??zg({inContext:!0,drawDefinition:e,matchUpsMap:U})?.matchUps,T=Gy({provisionalPositioning:r,appliedPolicies:I,drawDefinition:e,seedingProfile:s,structure:g,random:m});if(T.error)return QU(T,n);const{validSeedBlocks:w}=T;h.push({validSeedBlocks:w});const D=t.participants||(a?xS({withIndividualParticipants:!0,convertExtensions:!0,tournamentRecord:a})?.participants:[]);let R;if(Hy(g.seedingProfile||s)===Ts){const t=function({placeByes:t,provisionalPositioning:e,tournamentRecord:n,appliedPolicies:r,drawDefinition:i,seedBlockInfo:o,matchUpsMap:a,structure:s,seedLimit:c,seedsOnly:u,event:d,structureSeedingProfile:p,seedingProfile:l,inContextDrawMatchUps:m,participants:f,positioningReport:h,random:g}){let I=t?KU({provisionalPositioning:e,tournamentRecord:n,appliedPolicies:r,drawDefinition:i,seedBlockInfo:o,matchUpsMap:a,structure:s,seedLimit:c,seedsOnly:u,random:g,event:d}):void 0;if(I?.error)return{error:I.error};const S=I?.unseededByePositions;return h.push({action:"positionByes",unseededByePositions:S}),I=qU({seedingProfile:p?{positioning:p}:l,provisionalPositioning:e,inContextDrawMatchUps:m,tournamentRecord:n,appliedPolicies:r,validSeedBlocks:o.validSeedBlocks,drawDefinition:i,seedBlockInfo:o,participants:f,matchUpsMap:a,structure:s,random:g,event:d}),I.error?{error:I.error}:(h.push({seedPositions:I.seedPositions,action:"positionSeedBlocks"}),{unseededByePositions:S})}({placeByes:o,provisionalPositioning:r,tournamentRecord:a,appliedPolicies:I,drawDefinition:e,seedBlockInfo:T,matchUpsMap:U,structure:g,seedLimit:u,seedsOnly:d,event:f,structureSeedingProfile:g.seedingProfile,seedingProfile:s,inContextDrawMatchUps:P,participants:D,positioningReport:h,random:m});if(t?.error)return QU(t.error,n);R=t.unseededByePositions}else{const t=function({drawType:t,structureSeedingProfile:e,seedingProfile:n,provisionalPositioning:r,inContextDrawMatchUps:i,tournamentRecord:o,appliedPolicies:a,validSeedBlocks:s,drawDefinition:c,seedBlockInfo:u,participants:d,matchUpsMap:p,structure:l,event:m,placeByes:f,seedLimit:h,seedsOnly:g,positioningReport:I,random:S}){let y;if(!qf(t)){const t=qU({seedingProfile:e?{positioning:e}:n,provisionalPositioning:r,inContextDrawMatchUps:i,tournamentRecord:o,appliedPolicies:a,validSeedBlocks:s,drawDefinition:c,seedBlockInfo:u,participants:d,matchUpsMap:p,structure:l,random:S,event:m});if(t.error)return{error:t.error};I.push({action:"positionSeedBlocks",seedPositions:t.seedPositions})}const v=f?KU({provisionalPositioning:r,tournamentRecord:o,appliedPolicies:a,drawDefinition:c,seedBlockInfo:u,matchUpsMap:p,structure:l,seedLimit:h,seedsOnly:g,random:S,event:m}):void 0;return v?.error?{error:v.error}:(y=v?.unseededByePositions,I.push({action:"positionByes",byeDrawPositions:v?.byeDrawPositions,unseededByePositions:y}),{unseededByePositions:y})}({drawType:p,structureSeedingProfile:g.seedingProfile,seedingProfile:s,provisionalPositioning:r,inContextDrawMatchUps:P,tournamentRecord:a,appliedPolicies:I,validSeedBlocks:w,drawDefinition:e,seedBlockInfo:T,participants:D,matchUpsMap:U,structure:g,event:f,placeByes:o,seedLimit:u,seedsOnly:d,positioningReport:h,random:m});if(t?.error)return QU(t.error,n);R=t.unseededByePositions}const b={},N=function({seedsOnly:t,inContextDrawMatchUps:e,tournamentRecord:n,appliedPolicies:r,validSeedBlocks:i,drawDefinition:o,seedBlockInfo:a,participants:s,matchUpsMap:c,structure:u,positionQualifiers:d,positionUnseededParticipants:p,provisionalPositioning:l,unseededByePositions:m,multipleStructures:f,qualifiersCount:h,structureId:g,drawSize:I,event:S,positioningReport:y,conflicts:v,random:U}){if(t)return{};let P=d({inContextDrawMatchUps:e,tournamentRecord:n,appliedPolicies:r,validSeedBlocks:i,drawDefinition:o,qualifiersCount:h,seedBlockInfo:a,participants:s,matchUpsMap:c,structure:u,random:U});return P.error?{error:P.error}:(P.conflicts&&(v.qualifierConflicts=P.conflicts),y.push({action:"positionQualifiers",qualifierDrawPositions:P.qualifierDrawPositions}),P=p({provisionalPositioning:l,inContextDrawMatchUps:e,unseededByePositions:m,multipleStructures:f,tournamentRecord:n,drawDefinition:o,seedBlockInfo:a,participants:s,matchUpsMap:c,structureId:g,structure:u,drawSize:I,random:U,event:S}),P.error?{error:P.error}:(P.conflicts&&(v.unseededConflicts=P.conflicts),y.push({action:"positionUnseededParticipants"}),{}))}({seedsOnly:d,inContextDrawMatchUps:P,tournamentRecord:a,appliedPolicies:I,validSeedBlocks:w,drawDefinition:e,seedBlockInfo:T,participants:D,matchUpsMap:U,structure:g,positionQualifiers:jU,positionUnseededParticipants:GU,provisionalPositioning:r,unseededByePositions:R,multipleStructures:i,qualifiersCount:S,structureId:c,drawSize:l,event:f,positioningReport:h,conflicts:b,random:m});if(N?.error)return QU(N.error,n);const{positionAssignments:M}=cl({drawDefinition:e,structure:g});return Ql({drawDefinition:e,structureIds:[c]}),n||ri(),{positionAssignments:M,conflicts:b,...Y,positioningReport:h}}function XU(t){const{applyPositioning:e=!0,provisionalPositioning:n,tournamentRecord:r,drawDefinition:i,seedingProfile:o,structureId:a,placeByes:s,seedsOnly:c,random:u}=t;if(!i)return{error:ut};if(!PU({drawDefinition:i,structureId:a})&&!n)return{error:pt};const d=yU({drawDefinition:i,structureId:a}).playoffStructures?.sort((t,e)=>il(t)-il(e)),p=[],l=[];if(d)for(const t of d){const{structureId:a}=t,d=JU({structureId:a,provisionalPositioning:n,applyPositioning:e,tournamentRecord:r,drawDefinition:i,seedingProfile:o,placeByes:s,seedsOnly:c,random:u});if(d.error)return d;d.positionAssignments&&p.push({positionAssignments:d.positionAssignments,structureId:a}),d.positioningReport&&l.push(d.positioningReport)}return{...Y,structurePositionAssignments:p,positioningReports:l}}function ZU({validation:t=!0,tournamentRecord:e,drawDefinition:n,participantId:r,structureId:i,seedValue:o,event:a}){if(!n)return{error:st};if(!i)return{error:Bt};const s=(e?.participants??[]).find(t=>t.participantId===r);if(e&&!s)return{error:Ze};const{structure:c}=ol({drawDefinition:n,structureId:i});if(!c)return{error:Vt};if(!(!t||P(o)||void 0===o||""===o||"string"==typeof o&&o.split("-").every(t=>P(t)&&p(t)>0)))return{error:sr};const{seedAssignments:u}=Tf({drawDefinition:n,structure:c}),d=u?.map(t=>t.seedNumber),l=u?.find(t=>t.participantId===r);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,...d??[])+1,participantId:r};o&&(t.seedValue=o),c.seedAssignments??=[],c.seedAssignments.push(t)}return Jl({tournamentId:e?.tournamentId,eventId:a?.eventId,drawDefinition:n,structure:c}),{...Y}}function tP({drawDefinition:t,orderMap:e}){return t?("object"==typeof e&&Object.values(e).every(t=>R(t))||Ci({result:{error:sr},context:{orderMap:e}}),t.structures??=[],t.structures.forEach(t=>{const n=e[t.structureId];n&&(t.structureOrder=n)}),t.structures.sort((t,e)=>E(t.structureOrder)-E(e.structureOrder)),{...Y}):{error:st}}function eP({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},o={},a={};let s=function({links:t,initStructureProfile:e,sourceStructureIds:n,hasDrawFeedProfile:r}){return t.map(t=>{const i=t.source.structureId,o=t.target.structureId,a=e(i),s=e(o);return[Ms,Ns,bs,Ts].includes(t.target.feedProfile)?(a?.targets.push(o),s?.sources.push(i)):t.target.feedProfile===Rs&&(s?.drawSources.push(i),a?.drawTargets.push(o)),r[o]=r[o]||t.target.feedProfile===Rs,n[o]=M([...n[o]??[],i]).filter(Boolean),[t.source.structureId,t.target.structureId]})}({links:n,initStructureProfile:i,sourceStructureIds:o,hasDrawFeedProfile:a});!function(t){for(const e of t.keys()){const n=t.get(e);n&&(nP(n,t),rP(n,t))}}(r);const c=function(t){let e=0;for(const n of t.keys()){const r=t.get(n);if(r?.rootStage!==ds)continue;const i=[r.drawTargets?.[0]];let o=0;for(;i.length;){o+=1;const e=i.pop(),n=e?t.get(e):void 0;n?.drawTargets?.length&&i.push(n.drawTargets[0])}r.distanceFromMain=o,o>e&&(e=o)}return e}(r),u=s.length;L(0,Math.ceil(u/2)).forEach(()=>{s=L(0,u).map(t=>{const e=s[t],n=s.reduce((t,n)=>j(e,n)?t.concat(...n):t,[])??[];return M(e.concat(...n))})});const d=s[0],p=s.slice(1).reduce((t,e)=>{return t&&V(n=e,d).length===n.length;var n},!0),l=[d].filter(Boolean),m=[d].filter(Boolean);!function({structures:t,structureGroups:e,linkCheck:n}){t.forEach(t=>{const{structureId:r,stage:i}=t;e.find(t=>t.includes(r))||(e.push([r]),i!==ls&&n.push([r]))})}({structures:e,structureGroups:l,linkCheck:m});const f=p&&1===m.length;return n?.length||1!==e.length||i(e[0].structureId),{structureProfiles:Object.fromEntries(r),allStructuresLinked:f,maxQualifyingDepth:c,sourceStructureIds:o,hasDrawFeedProfile:a,structureGroups:l}}function nP(t,e){const n=t.targets??[];for(;n.length;){const r=n.pop(),i=r&&e[r];i?.targets?.length?n.push(...i.targets):i&&(t.rootStage=i.stage)}t.rootStage??=t.stage}function rP(t,e){if(t.targets?.length)return;const n=t.sources??[];for(;n.length;){const r=n.pop(),i=r&&e[r];if(i?.sources?.length){for(const e of i.sources)t.progeny?.includes(e)||t.progeny?.push(e);n.push(...i.sources)}}}function iP({drawDefinition:t}){const{maxQualifyingDepth:e,structureProfiles:n}=eP({drawDefinition:t});for(const r of t.structures){const t=n[r.structureId];t.distanceFromMain&&(r.stageSequence=e+1-t.distanceFromMain)}return{...Y}}function oP(t){const e=fu(t,[{[Ic]:!0,[yc]:!0}]);if(e.error)return e;const{tournamentRecord:n,drawDefinition:r,structure:i,link:o}=t;return function(t){const e=fu(t,[{[yc]:!0,[_c]:!0},{link:!0,[cu]:ru,[K]:_t}]);if(e.error)return e;const{drawDefinition:n,tournamentId:r,structure:i,eventId:o,link:a}=t,s=a.target.structureId,c=ol({drawDefinition:n,structureId:s});if(c.error)return Ci({stack:"attachQualifyingStructure",context:{targetStructureId:s},result:c});n.structures??=[],n.links??=[],n.structures.push(i),n.links.push(a),iP({drawDefinition:n});const u=Fg({structure:i})?.matchUps??[];return Hl({drawDefinition:n,tournamentId:r,matchUps:u,eventId:o}),Ql({drawDefinition:n,structureIds:[i.structureId]}),{...Y}}({tournamentId:n.tournamentId,drawDefinition:r,structure:i,link:o})}function aP({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:sr};if(!t)return{error:st};const n=Object.assign({},...e.map(t=>{if(!f(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];if(t&&(e.structureName=t),e.structures)for(const t of e.structures){const e=n[t.structureId];e&&(t.structureName=e)}}return{...Y}}function sP({drawDefinition:t,timeItem:e}){if(!t)return{error:ut};if(!e)return{error:zn};const n=e&&Object.keys(e),r=["itemType","itemValue"];if(!(r.filter(t=>n.includes(t)).length===r.length))return{error:$n};t.timeItems??=[];const i=(new Date).toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),Kl({drawDefinition:t}),{...Y}}function cP({participantPreferences:t,drawPositionResolutions:e={},random:n}){const r=Object.keys(t).reduce((e,n)=>{const r=t[n].preferences[0];return r&&(e[r]||(e[r]=[]),e[r].push(n)),e},{}),i=Math.min(...Object.values(r).filter(t=>t.length).map(t=>t.length)),o=Object.keys(r).filter(t=>r[t].length&&i&&r[t].length===i);let a;return o.forEach(i=>{const o=x(r[i],n);e[i]=o,delete t[o]}),Object.values(t).forEach(t=>{t.preferences=t.preferences.filter(t=>{const e=!o.includes(t.toString());return e&&(a=!0),e})}),{drawPositionResolutions:e,remainingPreferences:a,participantPreferences:t}}function uP({tournamentRecord:t,drawDefinition:e,applyResults:n=!0,tierIndex:r,random:i,event:o}){if(!e)return{error:st};const a=dp({element:e,attribute:"draftState",name:ud});if(!a)return{error:mr,info:"No active draft found"};if("COMPLETE"===a.status)return{error:sr,info:"Draft is already complete"};const s=a.structureId,{structure:c}=ol({drawDefinition:e,structureId:s});if(!c)return{error:mr,info:"Structure not found"};const{positionAssignments:u}=cl({drawDefinition:e,structureId:s});if(!u)return{error:mr,info:"No position assignments"};const d=function({draftState:t,targetTierIndex:e}){if(void 0===e)return;if(e<0||e>=t.tiers.length)return{error:sr,info:"Invalid tier index"};if(t.tiers[e].resolved)return{error:sr,info:"Tier already resolved"};for(let n=0;n<e;n++)if(!t.tiers[n].resolved)return{error:sr,info:`Tier ${n+1} must be resolved first`};return}({draftState:a,targetTierIndex:r});if(d?.error)return d;const p=u.map(t=>({...t})),l={},m=[];for(let t=0;t<a.tiers.length;t++){const e=a.tiers[t];e.resolved||(void 0!==r&&t!==r||(dP({draftState:a,tier:e,tierIndex:t,workingAssignments:p,allResolutions:l,tierReports:m,random:i}),e.resolved=!0))}const f=function(t,e){const n=[],r={};for(const[t,n]of Object.entries(e))r[n]=Number(t);for(const e of t.tiers)for(const i of e.participantIds){const e=t.preferences[i]??[],o=r[i],a=e.indexOf(o);n.push({participantId:i,preferences:e,assignedPosition:o,preferenceMatch:a>=0?a+1:null})}return n}(a,l);if(n){const n=function({allResolutions:t,tournamentRecord:e,drawDefinition:n,structureId:r,draftState:i,transparencyReport:o,tierReports:a,event:s}){const c=[];for(const[i,o]of Object.entries(t)){const t=av({drawPosition:Number(i),participantId:o,tournamentRecord:e,drawDefinition:n,structureId:r,event:s});t.error&&c.push({drawPosition:Number(i),participantId:o,error:t.error})}const u=new Set(Object.keys(t).map(Number));i.unassignedDrawPositions=(i.unassignedDrawPositions??[]).filter(t=>!u.has(t)),function({draftState:t,allResolutions:e}){const n={};for(const[t,r]of Object.entries(e))n[r]=Number(t);for(const e of t.tiers){if(!e.resolved||e.resolutions)continue;const r={};for(const i of e.participantIds){const e=n[i];if(void 0===e)continue;const o=(t.preferences[i]??[]).indexOf(e);r[i]={assignedPosition:e,preferenceMatch:o>=0?o+1:null}}e.resolutions=r}}({draftState:i,allResolutions:t});const d=i.tiers.every(t=>t.resolved);d&&(i.status="COMPLETE",i.resolvedAt=(new Date).toISOString(),i.transparencyReport=o);if(sp({element:n,attribute:"draftState",name:ud,value:i}),c.length)return{...Y,errors:c,drawPositionResolutions:t,tierReports:a,transparencyReport:o};return}({allResolutions:l,tournamentRecord:t,drawDefinition:e,structureId:s,draftState:a,transparencyReport:f,tierReports:m,event:o});if(n)return n}return{...Y,drawPositionResolutions:l,tierReports:m,transparencyReport:f}}function dP({draftState:t,tier:e,tierIndex:n,workingAssignments:r,allResolutions:i,tierReports:o,random:a}){const s=new Set(r.filter(t=>!t.participantId&&!t.bye&&!t.qualifier).map(t=>t.drawPosition)),c={},u=[];for(const n of e.participantIds){const e=t.preferences[n],r=e?.filter(t=>s.has(t));r?.length?c[n]={preferences:r}:u.push(n)}if(Object.keys(c).length){const{drawPositionResolutions:t,report:e}=function({positionAssignments:t,participantFactors:e,random:n}){if(!e||!t)return{error:Ae};let r=ca(e,!1,!0);const i=t.map(({drawPosition:t})=>t),o=t.filter(t=>!t.participantId&&!t.bye&&!t.qualifier).map(Zp);let a,s=!0;for(;s;)({drawPositionResolutions:a,remainingPreferences:s,participantPreferences:r}=cP({participantPreferences:r,drawPositionResolutions:a,random:n}));const c=new Set(Object.keys(a).map(t=>p(t)));let u=o.filter(t=>!c.has(t)),d=Object.keys(r);const l=L(1,(m=2,f=i?.length||0,Math.log(f)/Math.log(m)+1)).map(t=>Math.pow(2,t));var m,f;const h={};for(const t of l){const r=q(i,t).filter(t=>j(t,u)),o={};if(d.forEach(t=>{r.forEach(n=>{const r=n.join("|");j(n,e[t].preferences)&&(o[r]||(o[r]=[]),o[r].push(t))})}),A(Object.keys(o),n).forEach(t=>{const e=o[t].filter(t=>d.includes(t));for(;e.length;){const r=x(e,n),i=t.split("|").map(t=>p(t)).filter(t=>u.includes(p(t)));if(i.length){const e=x(i,n);u=u.filter(t=>t!==e),d=d.filter(t=>t!==r),a[e]=r;const o=t.split("|").length;h[o]||(h[o]=0),h[o]+=1}}}),!u.length)break}const g={chunkResolution:h};return d.length&&(d.forEach(t=>{const e=x(u,n);e&&(a[e]=t)}),g.randomAssignment=d.length),{drawPositionResolutions:a,report:g}}({positionAssignments:r,participantFactors:c});if(t)for(const[e,n]of Object.entries(t)){i[Number(e)]=n;const t=r.find(t=>t.drawPosition===Number(e));t&&(t.participantId=n)}o.push({tierIndex:n,preferenceReport:e,participantsWithoutPreferences:u})}if(u.length){const t=r.filter(t=>!t.participantId&&!t.bye&&!t.qualifier).map(t=>t.drawPosition),e=a??Math.random,s=[...t].sort(()=>e()-.5);for(let t=0;t<u.length&&t<s.length;t++){const e=s[t],n=u[t];i[e]=n;const o=r.find(t=>t.drawPosition===e);o&&(o.participantId=n)}o.push({tierIndex:n,randomAssignment:u.length})}}function pP({tournamentRecord:t,drawDefinition:e,event:n,structureId:r}){if(!e)return{error:st};const i=e.structures?.find(t=>t.stage===ds&&t.structureId===r);if(!i)return{error:Vt};const o=i.matchUps?.some(({matchUpStatus:t,score:e})=>aI({score:e})??_p.includes(t));if(o)return{error:br};const a=i.matchUps?.map(({matchUpId:t})=>t)??[];return i.positionAssignments=[],i.seedAssignments=[],i.matchUps=[],zl({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:a,drawDefinition:e}),Ql({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[i.structureId]}),{...Y}}function lP(t){const{tournamentRecord:e,drawDefinition:n,structureId:r,event:i}=t,o=fu(t,[{drawDefinition:!0,structureId:!0}]);if(o.error)return o;const a=n.structures??[],s=a.find(t=>t.structureId===r);if(!s)return{error:Vt};const c=a.find(({stage:t,stageSequence:e})=>t===us&&1===e),u=r===c?.structureId,d=a.filter(({stage:t})=>t===ds).map(eI("structureId"));if(u&&!d.length)return{error:tt};const p=d.includes(r),l=function({isQualifyingStructure:t,tournamentRecord:e,drawDefinition:n,structureId:r,structure:i,event:o,force:a}){const s=[r];if(t){const t=t=>n.links?.find(e=>e.target.structureId===t);let e=t(r)?.source.structureId;for(;e;)s.push(e),e=t(e)?.source.structureId}const c=zg({matchUpFilters:{structureIds:s},drawDefinition:n}).matchUps,u=c?.some(({score:t})=>aI({score:t}));if(u){const t=xd({tournamentRecord:e,drawDefinition:n,structure:i,event:o})?.appliedPolicies;if(!(a??t?.[Fu]?.allowDeletionWithScoresPresent?.structures))return{error:br}}return{...Y}}({isQualifyingStructure:p,structure:s,...t});if(l?.error)return l;const{structureIdsToRemove:m,relatedStructureIdsMap:f}=function({qualifyingStructureIds:t,isQualifyingStructure:e,isMainStageSequence1:n,mainStageSequence1:r,drawDefinition:i,structureId:o}){const a=i.structures??[],s=a.map(eI("structureId")),c=t=>i.links?.map(e=>e.source.structureId===t&&e.target.structureId!==r?.structureId&&e.target.structureId).filter(Boolean)??[],u=e=>i.links?.map(n=>t.includes(n.source.structureId)&&n.target.structureId===e&&n.source.structureId).filter(Boolean)??[],d=new Map;s.forEach(t=>d.set(t,e?u(t):c(t)));const p=n?d.get(o):[o];return{structureIdsToRemove:p,relatedStructureIdsMap:d}}({qualifyingStructureIds:d,isQualifyingStructure:p,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:n,structureId:r}),{removedMatchUpIds:h,removedStructureIds:g}=function({relatedStructureIdsMap:t,qualifyingStructureIds:e,isMainStageSequence1:n,mainStageSequence1:r,drawDefinition:i,structureIdsToRemove:o,structureId:a}){const s=[],c=[];for(;o?.length;){const u=o.pop();c.push(...hP({idBeingRemoved:u,drawDefinition:i}));const d=fP({qualifyingStructureIds:e,isMainStageSequence1:n,idBeingRemoved:u,drawDefinition:i,structureId:a});s.push(...d.removedStructureIds);const p=mP({relatedStructureIdsMap:t,mainStageSequence1:r,idBeingRemoved:u,structureId:a});p?.length&&o.push(...p)}return{removedMatchUpIds:c,removedStructureIds:s}}({relatedStructureIdsMap:f,qualifyingStructureIds:d,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:n,structureIdsToRemove:m,structureId:r});if(function({removedMatchUpIds:t,drawDefinition:e}){const{matchUps:n}=zg({drawDefinition:e});n?.forEach(e=>{e.winnerMatchUpId&&t.includes(e.winnerMatchUpId)&&delete e.winnerMatchUpId,e.loserMatchUpId&&t.includes(e.loserMatchUpId)&&delete e.loserMatchUpId})}({removedMatchUpIds:h,drawDefinition:n}),u){const t=(c.matchUps??[])?.map(eI("matchUpId"));h.push(...t),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return p&&iP({drawDefinition:n}),zl({tournamentId:e?.tournamentId,matchUpIds:h,action:"removeStructure",eventId:i?.eventId,drawDefinition:n}),Ql({drawDefinition:n,eventId:i?.eventId}),{...Y,removedMatchUpIds:h,removedStructureIds:g}}function mP({idBeingRemoved:t,relatedStructureIdsMap:e,mainStageSequence1:n,structureId:r}){return t&&e.get(t)?.filter(t=>t!==n?.structureId||r===n.structureId)}function fP({qualifyingStructureIds:t,isMainStageSequence1:e,idBeingRemoved:n,drawDefinition:r,structureId:i}){const o=[];return r.links=r.links?.filter(t=>t.source.structureId!==n&&t.target.structureId!==n)??[],(!e||e&&t.length||n!==i)&&(r.structures=(r.structures??[]).filter(t=>(n&&n===t.structureId&&o.push(n),t.structureId!==n))),{removedStructureIds:o}}function hP({idBeingRemoved:t,drawDefinition:e}){const{structure:n}=ol({structureId:t,drawDefinition:e}),r=Fg({structure:n}).matchUps;return Qp(r)}const gP="removeDrawPositionAssignment",IP="swapDrawPositionAssignments",SP="assignDrawPosition",yP="addPenalty",vP="MODIFY_PAIR",UP="QUALIFIER",PP="ALTERNATE",TP="WITHDRAW",wP="ASSIGN",DP="REMOVE",RP="LUCKY",bP="REMOVE_SEED",NP="SWAP",MP="NICKNAME",AP="SEED_VALUE",EP="PENALTY",CP="SEED_CASCADE",OP="BYE",kP={MODIFY_PAIR_ASSIGNMENT:vP,QUALIFYING_PARTICIPANT:UP,ALTERNATE_PARTICIPANT:PP,WITHDRAW_PARTICIPANT:TP,ASSIGN_PARTICIPANT:wP,LUCKY_PARTICIPANT:RP,REMOVE_ASSIGNMENT:DP,SWAP_PARTICIPANTS:NP,ADD_NICKNAME:MP,REMOVE_SEED:bP,ADD_PENALTY:EP,ASSIGN_BYE:OP,SEED_CASCADE:CP,SEED_VALUE:AP};function FP({tournamentRecord:t,drawDefinition:e,drawPositions:n,structureId:r,event:i}){if(!e)return{error:st};if(!r)return{error:Bt};if(2!==n?.length)return{error:sr,drawPositions:n};const a=bf({drawDefinition:e}),{matchUps:s}=zg({inContext:!0,drawDefinition:e,matchUpsMap:a}),{structure:c}=ol({drawDefinition:e,structureId:r});if(!c)return{error:Vt};const u=xd({tournamentRecord:t,drawDefinition:e,event:i}).appliedPolicies??{};let d;if(d=c.structureType===Ds?function({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPositions:r,matchUpsMap:i,structure:o,event:a}){const s=o.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{...Y};if(2===s.filter(({qualifier:t})=>t).length)return{...Y};ov({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:i,assignments:s,structure:o,event:a});const c=s.some(({qualifier:t})=>t);if(s.some(({bye:t})=>t)&&!c)xP({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:s,matchUpsMap:i,structure:o,event:a});else{const t=ca(s,!1,!0);s.forEach((e,n)=>{const r=t[1-n].participantId;e.qualifier=t[1-n].qualifier,e.participantId=r})}return{...Y}}({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:n,matchUpsMap:a,structure:c,event:i}):function({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPositions:r,matchUpsMap:i,structure:o,event:a}){const s=o?.positionAssignments.filter(t=>r?.includes(t.drawPosition));if(!s)return{error:sr,structure:o,info:"Missing positionAssignments"};if(2===s.filter(({bye:t})=>t).length)return{...Y};if(2===s.filter(({qualifier:t})=>t).length)return{...Y};const c=s.some(({qualifier:t})=>t);return s.some(({bye:t})=>t)&&!c?xP({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:s,matchUpsMap:i,structure:o,event:a}):function({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:r,matchUpsMap:i,structure:o,event:a}){const s=Object.assign({},...r.map((t,e)=>{const{drawPosition:n}=t,i={...r[1-e],drawPosition:n};return{[n]:i}}));return o.positionAssignments=o.positionAssignments.map(t=>s[t.drawPosition]||t),ov({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:i,assignments:r,structure:o,event:a}),{...Y}}({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:s,matchUpsMap:i,structure:o,event:a})}({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:n,matchUpsMap:a,structure:c,event:i}),d.error)return d;tm({structure:c,drawPositions:n});if(em({appliedPolicies:u,drawDefinition:e,positionAction:{name:IP,drawPositions:n,structureId:r}}),Xl({tournamentId:t?.tournamentId,drawDefinition:e,structure:c,event:i}),i.eventType===os){const r=Fg({matchUpFilters:{matchUpTypes:[o]},inContext:!0,structure:c}).matchUps.filter(t=>t.drawPositions?.some(t=>n.includes(t))),a=Fg({matchUpFilters:{matchUpTypes:[o]},structure:c}).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);Yy({inContextTargetMatchUp:r,drawPositionSideIndex:u,teamParticipantId:n,tournamentRecord:t,drawDefinition:e,matchUp:c,event:i})}})})}return Ql({drawDefinition:e,structureIds:[r]}),{...Y}}function xP({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:r,matchUpsMap:i,structure:o,event:a}){const s=r.find(({bye:t})=>t),c=r.find(({participantId:t})=>t),u=s.drawPosition,{participantId:d,drawPosition:p}=c,{structureId:l}=o;let m=wy({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:l,matchUpsMap:i});return m.error?m:(m=wy({drawPosition:p,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:l,matchUpsMap:i}),m.error?m:(SI({drawPosition:p,tournamentRecord:e,drawDefinition:n,structureId:l,matchUpsMap:i,event:a}),m=av({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:l,participantId:d,matchUpsMap:i,event:a}),m.error?m:{...Y}))}function _P({tournamentRecord:t,drawDefinition:e,participantId:n,structureId:r}){const i="removeSeededParticipant";if(!t)return{error:rt};if(!e)return{error:st};const o=(e.structures??[]).find(t=>t.structureId===r);if(!o)return Ci({result:{error:Vt},stack:i});if(!o.stage||![us,ds].includes(o.stage)||o.stage===us&&1!==o.stageSequence)return Ci({result:{error:dt},stack:i});const a=o.seedAssignments?.find(t=>t.participantId===n);return a?{...Y}:Ci({info:"participant not seeded",result:{error:mr},context:{participantId:n}})}function LP({qualifyingPositions:t,targetEntryRound:e=1,finishingPositions:n,sourceRoundNumber:r,sourceStructureId:i,targetStructureId:o,linkType:a=Es}){if(!i||!o)return{error:Bt};return{link:Ei({linkType:a,source:{roundNumber:r,structureId:i,qualifyingPositions:t,finishingPositions:n},target:{feedProfile:Rs,roundNumber:e,structureId:o}})}}function BP({matchUp:t,tieFormat:e,isMock:n,uuids:r}){const{collectionDefinitions:i}=e??{};return{tieMatchUps:(i??[]).map(e=>VP({matchUp:t,collectionDefinition:e,uuids:r,isMock:n})).filter(Boolean).flat()}}function VP({collectionPositionOffset:t=0,collectionDefinition:e,matchUpsLimit:n,matchUp:r,isMock:i,uuids:o}){const{matchUpCount:a,matchUpType:s,collectionId:c,processCodes:u}=e??{},d=t=>{if(!i&&!r?.isMock)return o?.pop()??pa();const n=e?.collectionId;return o?.pop()??`${r?.matchUpId}-${n}-TMU-${t+1}`};return L(0,n??a??0).map(e=>{const n=t+e+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:d(e),matchUpStatus:Ap,collectionPosition:n,collectionId:c,processCodes:u,matchUpType:s,isMock:i}})}function GP(t){const e="generateQualifyingStructure",n=function(t,e){return t.drawDefinition?t.drawSize&&!R(t.drawSize)||t.participantsCount&&!R(t.participantsCount)||t.qualifyingPositions&&!R(t.qualifyingPositions)?Ci({result:{error:sr},stack:e}):t.drawSize?t.qualifyingPositions&&t.qualifyingPositions>=t.drawSize?Ci({result:{error:sr},context:{drawSize:t.drawSize,qualifyingPositions:t.qualifyingPositions},stack:e}):null:Ci({result:{error:Rt},context:{drawSize:t.drawSize},stack:e}):Ci({result:{error:st},stack:e})}(t,e);if(n)return n;let r=t.drawSize??v(t.participantsCount);const{hasExistingDrawDefinition:i,qualifyingRoundNumber:o,qualifyingPositions:a,targetStructureId:s,structureOptions:c,appliedPolicies:u,qualifyingOnly:d,drawDefinition:p,matchUpFormat:l,structureName:m,structureId:f,roundTarget:h,tieFormat:g,drawType:I,idPrefix:S,isMock:y,uuids:U}=t,P=function(t,e,n){const{structureProfiles:r}=eP({drawDefinition:t}),i=r[e];return i||Ci({result:{error:Vt},context:{targetStructureId:e},stack:n})}(p,s,e);if(P?.error)return P;const T=p.matchUpType,w=h?`${h}-`:"",D="object"==typeof P&&"stage"in P&&P.stage===ds,b=u?.[Au]?.namingConventions?.pre??zf[Au]?.namingConventions?.pre,N=D&&b?`${b}-`:"",M=m??(w?`${N}${Ny(ds)} ${w}`:`${N}${Ny(ds)}`);let A,E,C,O,k;if(I===ic){const t=function(t){const{maxRoundNumber:e,structures:n,groupCount:r}=Fy(t);return{qualifiersCount:r,roundLimit:e,structure:n[0],finishingPositions:[1]}}({structureName:m??M,structureId:f??U?.pop(),hasExistingDrawDefinition:i,stage:ds,structureOptions:c,appliedPolicies:u,qualifyingOnly:d,stageSequence:1,matchUpType:T,roundTarget:h,tieFormat:g,idPrefix:S,drawSize:r,isMock:y,uuids:U});O=t.qualifiersCount,C=t.roundLimit,A=t.structure,k=t.finishingPositions}else{const t=function(t){let{drawSize:e,matchUps:n,roundLimit:r,roundsCount:i}=Sv(t);r||(r=i);const o=Ry({structureName:t.structureName,structureId:t.structureId,qualifyingRoundNumber:r,stage:ds,matchUpFormat:t.matchUpFormat,stageSequence:t.stageSequence,matchUpType:t.matchUpType,roundLimit:r,matchUps:n});t.roundTarget&&sp({element:o,attribute:"roundTarget",name:vd,value:t.roundTarget});const a=n?.filter(t=>t.roundNumber===r)?.length??0;return{drawSize:e,structure:o,matchUps:n,roundLimit:r,qualifiersCount:a}}({qualifyingRoundNumber:o,qualifyingPositions:a,matchUpType:T,idPrefix:S,drawSize:r,isMock:y,uuids:U,structureName:m??M,structureId:f??U?.pop(),matchUpFormat:l,stageSequence:1,roundTarget:h});r=t.drawSize,A=t.structure,C=t.roundLimit,O=t.qualifiersCount}const F=I===ic?As:Es,x=A&&C&&LP({sourceStructureId:A.structureId,sourceRoundNumber:C,targetStructureId:s,finishingPositions:k,linkType:F})?.link;return g&&(E=Fg({structure:A})?.matchUps??[],E?.forEach(t=>{const{tieMatchUps:e}=BP({tieFormat:g,matchUp:t,isMock:y});Object.assign(t,{tieMatchUps:e,matchUpType:T})})),{qualifyingDrawPositionsCount:r,qualifiersCount:O,...Y,structure:A,link:x}}function jP(t){if(!t.tournamentRecord)return{error:rt};const e=function(t){if(!t.drawDefinition)return{error:st};if(!t.targetStructureId)return{error:Bt};const e=GP(t);if(e.error)return e;const{structure:n,link:r}=e;return n&&r?oP({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,structure:n,link:r}):{error:sr}}(t);return e.error,e}function qP({tournamentRecord:t,drawDefinition:e,structureId:n,drawPosition:r,event:i}){if(!e)return{error:st};if(!(n=n||e.structures?.[0]?.structureId))return{error:sr};const{structure:o}=ol({drawDefinition:e,structureId:n});if(!o)return{error:sr};if(o.stage!==us||1!==o.stageSequence)return{error:sr};if(o.structureType===Ds)return{error:sr};const a=dI({drawDefinition:e,structureId:n});if(a.activeDrawPositions?.length)return{error:sr};const{positionAssignments:s}=ul({structure:o});if(!s)return{error:sr};const{seedAssignments:c}=Tf({drawDefinition:e,structure:o});if(!c?.length)return{error:sr};const u=s.find(t=>t.drawPosition===r),d=u?.participantId;if(!d)return{error:sr};const p=c.find(t=>t.participantId===d);if(!p)return{error:sr};const{validSeedBlocks:l}=Gy({drawDefinition:e,structure:o});if(!l?.length)return{error:sr};const m=p.seedNumber,f=l.findIndex(t=>t.seedNumbers.includes(m));if(f<0)return{error:sr};const h=[];let g=r,I=m;for(let t=f+1;t<l.length;t++){const e=l[t],n=c.filter(t=>e.seedNumbers.includes(t.seedNumber)&&t.participantId).sort((t,e)=>t.seedNumber-e.seedNumber);if(!n.length)break;const r=n[0],i=r.participantId,o=s.find(t=>t.participantId===i);if(!o)break;h.push({replacementParticipantId:i,replacementSeedNumber:r.seedNumber,targetSeedNumber:I,sourceDrawPosition:o.drawPosition,targetDrawPosition:g}),g=o.drawPosition,I=r.seedNumber}for(const t of h){const e=s.find(e=>e.drawPosition===t.targetDrawPosition);e&&(e.participantId=t.replacementParticipantId);const n=c.find(e=>e.seedNumber===t.targetSeedNumber);n&&(n.participantId=t.replacementParticipantId)}const S=h.length?h.at(-1)?.sourceDrawPosition:r,y=s.find(t=>t.drawPosition===S);if(y&&(y.participantId=void 0),0===h.length)p.participantId=void 0;else{const t=h.at(-1),e=c.find(e=>e.seedNumber===t?.replacementSeedNumber);e&&(e.participantId=void 0)}const v=e.entries?.find(t=>t.participantId===d);v&&(v.entryStatus=ff);const U=t?.tournamentId;return Xl({drawDefinition:e,tournamentId:U,structure:o,event:i}),Jl({eventId:i?.eventId,drawDefinition:e,tournamentId:U,structure:o}),{...Y,vacatedDrawPosition:S}}function WP(t){const e=fu(t,[{[yc]:!0,[bc]:!0,[kc]:!0},{[Rc]:!0,[ou]:t=>Number.isInteger(t)&&t>0},{[ou]:t=>Array.isArray(t)&&2===t.length&&t.every(m),[su]:tn,participantIds:!0}]);if(e.error)return e;const{drawDefinition:n,structureId:r,tournamentRecord:i,event:o}=t,{structure:a}=ol({drawDefinition:n,structureId:r});if(!a)return{error:Vt};if(!Hf({structure:a}))return{error:dt};const s=(a?.matchUps??[]).filter(e=>e.roundNumber===t.roundNumber).filter(t=>!aI(t)).filter(e=>e.sides?.map(t=>t.participantId).some(e=>t.participantIds.includes(e)));if(2!==s.length)return{error:tn};for(const e of s){const r=e?.sides?.find(e=>t.participantIds.includes(e?.participantId));if(r){const a=t.participantIds.find(t=>t!==r?.participantId);r.participantId=a,Yl({tournamentId:i?.tournamentId,eventId:o?.eventId,drawDefinition:n,matchUp:e})}}return Ql({drawDefinition:n,structureIds:[r]}),{...Y}}const $P=new Set([Ep,Pp,wp,Tp]);function HP({matchUp:t}){if(!t)return{error:Se};const{winningSide:e,score:n,matchUpStatus:r}=t;if(!e||!n)return{error:sr};if(r&&$P.has(r))return{...Y,margin:Number.NaN,setRatio:Number.NaN,gameRatio:Number.NaN,pointRatio:Number.NaN,setsWonByLoser:0,setsWonByWinner:0,gameDifferential:0};const i=n.sets??[],o=1===e?2:1,a=i.filter(t=>t.winningSide===e).length,s=i.filter(t=>t.winningSide===o).length,c=a+s,u=c>0?s/c:Number.NaN;let d=!1,p=0,l=0;for(const t of i){const n=1===e?t.side1PointScore:t.side2PointScore,r=1===e?t.side2PointScore:t.side1PointScore;null!=n&&(p+=Number(n),d=!0),null!=r&&(l+=Number(r),d=!0)}const m=p+l,f=d&&m>0?l/m:Number.NaN,{games:h}=Cf({score:n}),g=h[e-1],I=h[o-1],S=g+I,y=S>0?I/S:Number.NaN,v=g-I;let U;return U=Number.isFinite(f)?f:Number.isFinite(y)?y:u,{...Y,margin:U,setRatio:u,gameRatio:y,pointRatio:f,setsWonByLoser:s,setsWonByWinner:a,gameDifferential:v}}function zP({tournamentRecord:t,drawDefinition:e,structureId:n,cumulativeMargin:r}){if(!e)return{error:st};const i=qf(e.drawType);if(!(n=n||e.structures?.[0]?.structureId))return i?{error:sr}:{...Y,isLuckyDraw:!1,rounds:[]};const{structure:o}=ol({drawDefinition:e,structureId:n});if(!o)return{error:sr};if(!(i||$f({drawDefinition:e,structure:o})))return{...Y,isLuckyDraw:!1,rounds:[]};const a=o.matchUps??[],{roundProfile:s,roundNumbers:c}=Bf({matchUps:a});if(!s||!c?.length)return{...Y,isLuckyDraw:!0,rounds:[]};const u=td({element:o,name:"customRoundProfile"}).extension?.value,d=o.positionAssignments??[],p={};for(const t of d)t.drawPosition&&t.participantId&&(p[t.drawPosition]=t.participantId);const l={};if(t?.participants)for(const e of t.participants)e.participantId&&e.participantName&&(l[e.participantId]=e.participantName);const m=c.map(t=>{const i=s[t],o=a.filter(e=>e.roundNumber===t),c=o.filter(t=>_p.includes(t.matchUpStatus)||t.winningSide||t.matchUpStatus===Sp).length,m=c===i.matchUpsCount;let f=0;if(!(1===i.matchUpsCount))if(u){const e=u[t-1],n=u[t];e&&n&&(f=Math.max(0,2*n-e))}else i.matchUpsCount%2!=0&&(f=1);const h=f>0,g=t+1,I=a.filter(t=>t.roundNumber===g).some(t=>!t.drawPositions||t.drawPositions.filter(Boolean).length<2||t.drawPositions.some(t=>{if(!t)return!0;const e=d.find(e=>e.drawPosition===t);return!e?.participantId&&!e?.bye})),S=h&&m&&I,y=(e.links??[]).filter(e=>e.linkType===Cs&&e.source.structureId===n&&(e.source.roundNumber||1)===t).map(t=>{const n=t.target.structureId,r=t.target.roundNumber,{structure:i}=ol({drawDefinition:e,structureId:n}),o=i?.positionAssignments??[],a=(i?.matchUps??[]).filter(t=>t.roundNumber===r),s=new Set(a.flatMap(t=>(t.drawPositions??[]).filter(Boolean))),c=s.size>0&&[...s].some(t=>o.some(e=>e.drawPosition===t&&e.participantId));return{targetStructureId:n,targetRoundNumber:r,feedProfile:t.target.feedProfile,losersPlaced:c}}),v={roundNumber:t,matchUpsCount:i.matchUpsCount,completedCount:c,isComplete:m,isPreFeedRound:h,needsLuckySelection:S,nextRoundHasOpenPosition:I,requiredLuckyLoserCount:f,...y.length&&{consolidationLinks:y}},U=(t,e)=>{const n=t.sides?.find(t=>t.sideNumber===e);if(n)return n.participantId||n.participant?.participantId;const r=t.drawPositions?.[e-1];return r?p[r]:void 0},P=(t,e)=>{const n=U(t,e);if(!n)return;const r=((t,e,n)=>{const r=t.sides?.find(t=>t.sideNumber===e);return r?.participant?.participantName||l[n]})(t,e,n),i=HP({matchUp:t});return{participantId:n,participantName:r,matchUpId:t.matchUpId,scoreString:t.score?.scoreStringSide1,margin:i.margin??0,gameRatio:Number.isFinite(i.gameRatio)?i.gameRatio:void 0,pointRatio:Number.isFinite(i.pointRatio)?i.pointRatio:void 0,setRatio:Number.isFinite(i.setRatio)?i.setRatio:void 0,gameDifferential:i.gameDifferential??0,setsWonByLoser:i.setsWonByLoser??0}},T=o.filter(t=>t.winningSide),w=[...o].sort((t,e)=>(t.roundPosition||0)-(e.roundPosition||0)),D=[];for(const t of w)if(t.winningSide){const e=P(t,t.winningSide);e&&D.push(e)}else if(t.matchUpStatus===Sp){const e=t.drawPositions??[];for(const n of e){if(!n)continue;const e=d.find(t=>t.drawPosition===n);if(e?.participantId&&!e.bye){D.push({participantId:e.participantId,participantName:l[e.participantId],matchUpId:t.matchUpId,margin:0,gameDifferential:0,setsWonByLoser:0});break}}}if(v.advancingWinners=D,h){const e=T.map(e=>{const n=1===e.winningSide?2:1,i=P(e,n);if(!i||!r)return i;const o=a.filter(e=>{if(!e.roundNumber||e.roundNumber>t||!e.winningSide)return!1;const n=U(e,1),r=U(e,2);return n===i.participantId||r===i.participantId});let s=0,c=0;for(const t of o){const e=HP({matchUp:t});if(Number.isFinite(e.margin)){const n=U(t,1);s+=n===i.participantId&&1!==t.winningSide||n!==i.participantId&&2!==t.winningSide?e.margin??0:1-(e.margin??0),c++}}return c>0&&(i.margin=s/c),i}).filter(t=>!!t).sort((t,e)=>(e.margin??0)!==(t.margin??0)?(e.margin??0)-(t.margin??0):(e.setsWonByLoser??0)-(t.setsWonByLoser??0));v.eligibleLosers=e}return v});return{...Y,isLuckyDraw:!0,rounds:m}}const YP="luckyDrawAdvancement";function KP({tournamentRecord:t,drawDefinition:e,participantId:n,participantIds:r,structureId:i,roundNumber:o,random:a,event:s}){if(!e)return{error:st};if(!(i=i||e.structures?.[0]?.structureId))return{error:sr};const{structure:c}=ol({drawDefinition:e,structureId:i});if(!c)return{error:sr};if(!qf(e.drawType)&&!$f({drawDefinition:e,structure:c}))return Ci({result:{error:sr},info:"Not a lucky draw"});const u=zP({tournamentRecord:t,drawDefinition:e,structureId:i});if(u.error)return u;const d=u.rounds?.find(t=>t.roundNumber===o);if(!d?.isComplete)return Ci({result:{error:sr},info:"Round is not complete"});const p=r??(n?[n]:[]);if(d.needsLuckySelection){if(!p.length)return{error:sn};if(p.length!==d.requiredLuckyLoserCount)return Ci({result:{error:sr},info:`Expected ${d.requiredLuckyLoserCount} lucky loser(s), got ${p.length}`});if(new Set(p).size!==p.length)return Ci({result:{error:sr},info:"Duplicate lucky loser participantIds"});const t=new Set((d.eligibleLosers??[]).map(t=>t.participantId)),e=p.find(e=>!t.has(e));if(e)return Ci({result:{error:sr},info:`Participant ${e} is not an eligible loser from this round`})}const l=o+1,m=(c.matchUps??[]).filter(t=>t.roundNumber===l).sort((t,e)=>(t.roundPosition||0)-(e.roundPosition||0)),f=d.advancingWinners??[],h=f.map(t=>t.participantId);if(d.isPreFeedRound&&p.length&&function({advancingParticipantIds:t,nextRoundMatchUps:e,roundStatus:n,luckyLoserIds:r,winners:i,random:o}){const a=o??Math.random,s=e.length,c=new Set(i.map(t=>t.participantId));for(const e of r)JP({advancingParticipantIds:t,numMatchUps:s,roundStatus:n,winnerIds:c,winners:i,llId:e,rng:a})}({advancingParticipantIds:h,nextRoundMatchUps:m,roundStatus:d,luckyLoserIds:p,winners:f,random:a}),!m.length)return Ci({result:{error:sr},info:"No matchUps found in next round"});const g=2*m.length;if(h.length!==g)return Ci({result:{error:sr},info:`Expected ${g} advancing participants, got ${h.length}`});let I=c.positionAssignments??[];I=function({positionAssignments:t,nextRoundMatchUps:e,structure:n,roundNumber:r}){const i=new Set(e.flatMap(t=>(t.drawPositions??[]).filter(Boolean)));if(i.size){const e=[];for(const n of i){const r=t.filter(t=>t.drawPosition===n),i=r.some(t=>!t.participantId&&!t.bye);(r.length>1||i)&&e.push(n)}if(e.length){const n=new Set(e);t=t.filter(t=>!n.has(t.drawPosition))}}const o=new Set((n.matchUps??[]).filter(t=>t.roundNumber&&t.roundNumber<=r).flatMap(t=>t.drawPositions??[]).filter(Boolean));return t=t.filter(t=>!(!t.participantId&&!t.bye)||o.has(t.drawPosition)),t}({positionAssignments:I,nextRoundMatchUps:m,structure:c,roundNumber:o}),c.positionAssignments=I;const S=function({nextRoundMatchUps:t,positionAssignments:e}){for(const n of t){const t=n.drawPositions;if(!t?.length)continue;if(t.filter(t=>!!t&&e.some(e=>e.drawPosition===t&&e.participantId)).length)return Ci({result:{error:sr},info:"Next round already has participants assigned"});t.some(Boolean)&&(n.drawPositions=[]),n.matchUpStatus&&"TO_BE_PLAYED"!==n.matchUpStatus&&(n.matchUpStatus=void 0,n.winningSide=void 0,n.score=void 0)}return}({nextRoundMatchUps:m,positionAssignments:I});if(S)return S;const y=t?.tournamentId;return function({advancingParticipantIds:t,positionAssignments:e,nextRoundMatchUps:n,drawDefinition:r,roundNumber:i,roundStatus:o,luckyLoserIds:a,tournamentId:s,structureId:c,structure:u}){const d=new Set(e.map(t=>t.drawPosition)),p=(u.matchUps??[]).flatMap(t=>t.drawPositions??[]).filter(Boolean),l=[...d,...p];let m=(l.length?Math.max(...l):0)+1;const f=new Set(a??[]),h=o.isPreFeedRound&&f.size>0,g=()=>({name:"luckyAdvancement",value:{fromRoundNumber:i}});for(let i=0;i<n.length;i++){const o=n[i],a=m++,u=m++,d=t[2*i],p=t[2*i+1];o.drawPositions=[a,u];const l={drawPosition:a,participantId:d},I={drawPosition:u,participantId:p};h&&(f.has(d)&&(l.extensions=[g()]),f.has(p)&&(I.extensions=[g()])),e.push(l,I),Yl({context:YP,drawDefinition:r,tournamentId:s,structureId:c,matchUp:o})}u.positionAssignments=e}({advancingParticipantIds:h,positionAssignments:I,nextRoundMatchUps:m,drawDefinition:e,roundNumber:o,roundStatus:d,luckyLoserIds:p,tournamentId:y,structureId:i,structure:c}),Xl({drawDefinition:e,tournamentId:y,structure:c,event:s}),d.isPreFeedRound&&p.length&&function({drawDefinition:t,tournamentRecord:e,roundStatus:n,luckyLoserIds:r,structureId:i,roundNumber:o,event:a}){const s=new Set(r),c=(n.eligibleLosers??[]).filter(t=>!s.has(t.participantId)).map(t=>t.participantId);if(!c.length)return;const u=(t.links??[]).filter(t=>t.linkType===Cs&&t.source.structureId===i&&(t.source.roundNumber||1)===o);for(const n of u){const r=QP({drawDefinition:t,tournamentRecord:e,targetStructureId:n.target.structureId,targetRoundNumber:n.target.roundNumber,feedProfile:n.target.feedProfile,participantIds:c,event:a});r?.error&&$r()&&console.warn("Failed to place discarded losers in consolidation structure:",r.error)}}({drawDefinition:e,tournamentRecord:t,roundStatus:d,luckyLoserIds:p,structureId:i,roundNumber:o,event:s}),{...Y}}function QP({drawDefinition:t,tournamentRecord:e,targetStructureId:n,targetRoundNumber:r,feedProfile:i,participantIds:o,event:a}){const{structure:s}=ol({drawDefinition:t,structureId:n});if(!s)return{error:sr};if(Hf({structure:s})&&s.finishingPosition===pc)return{...Y};let c=(s.matchUps??[]).filter(t=>t.roundNumber===r).sort((t,e)=>(t.roundPosition||0)-(e.roundPosition||0)),u=s.positionAssignments??[];const d=[];s.matchUps??=[],0===c.length?(!function({targetStructure:t,targetStructureId:e,targetRoundNumber:n,participantIds:r,unfilledPositions:i}){const o=Math.ceil(r.length/2);let a=1;for(let r=0;r<o;r++){const o=a++,s=a++,c={matchUpId:`${e}-mu-${r+1}`,roundNumber:n,roundPosition:r+1,drawPositions:[o,s],matchUpStatus:"TO_BE_PLAYED"};t.matchUps.push(c),i.push(o,s)}}({targetStructure:s,targetStructureId:n,targetRoundNumber:r,participantIds:o,unfilledPositions:d}),c=s.matchUps.filter(t=>t.roundNumber===r).sort((t,e)=>(t.roundPosition||0)-(e.roundPosition||0))):function({targetMatchUps:t,targetPositionAssignments:e,targetStructure:n,unfilledPositions:r}){for(const n of t)for(const t of n.drawPositions??[]){if(!t)continue;const n=e.find(e=>e.drawPosition===t);n?.participantId||n?.bye||r.push(t)}if(!r.length){const i=new Set(e.filter(t=>t.participantId).map(t=>t.drawPosition)),o=(n.matchUps??[]).flatMap(t=>t.drawPositions??[]).filter(t=>t&&i.has(t)),a=[...i,...o];let s=a.length?Math.max(...a)+1:1;for(const e of t)if(!e.drawPositions?.length||!e.drawPositions.some(Boolean)){const t=s++,n=s++;e.drawPositions=[t,n],r.push(t,n)}}}({targetMatchUps:c,targetPositionAssignments:u,targetStructure:s,unfilledPositions:d}),"BOTTOM_UP"===i?d.sort((t,e)=>e-t):d.sort((t,e)=>t-e);const p=e?.tournamentId;for(let e=0;e<o.length&&e<d.length;e++){const r=d[e],i=o[e],a=u.find(t=>t.drawPosition===r&&!t.participantId);a?a.participantId=i:u.push({drawPosition:r,participantId:i});const s=c.find(t=>t.drawPositions?.includes(r));s&&Yl({context:YP,drawDefinition:t,tournamentId:p,structureId:n,matchUp:s})}return s.positionAssignments=u,Xl({drawDefinition:t,tournamentId:p,structure:s,event:a}),{...Y}}function JP({advancingParticipantIds:t,numMatchUps:e,roundStatus:n,winnerIds:r,winners:i,llId:o,rng:a}){const s=n.eligibleLosers?.find(t=>t.participantId===o);if(!s||e<=1)return void t.push(o);const c=i.find(t=>t.matchUpId===s.matchUpId);if(!c)return void t.push(o);const u=t.indexOf(c.participantId);if(u<0)return void t.push(o);const d=(t.length+1)/2,p=function({advancingParticipantIds:t,defeatingWinnerIdx:e,winnerIds:n,halfSplit:r,quarterSplit:i}){const o=[];for(let a=0;a<=t.length;a++){const s=Math.floor(a/2),c=e+(a<=e?1:0),u=Math.floor(c/2),d=s<r?0:1;let p=0;d===(u<r?0:1)&&(p+=100),Math.floor(s/i)===Math.floor(u/i)&&(p+=10),p+=2*XP({advancingParticipantIds:t,winnerIds:n,insertAtP:a,halfSplit:r,targetHalf:d}),o.push({p:a,score:p})}return o}({advancingParticipantIds:t,defeatingWinnerIdx:u,winnerIds:r,halfSplit:Math.ceil(d/2),quarterSplit:Math.max(1,Math.ceil(d/4))});let l=1/0;for(const t of p)t.score<l&&(l=t.score);const m=p.filter(t=>t.score===l).map(t=>t.p),f=m[Math.floor(a()*m.length)];t.splice(f,0,o)}function XP({advancingParticipantIds:t,winnerIds:e,insertAtP:n,halfSplit:r,targetHalf:i}){let o=0;for(let a=0;a<t.length;a++){if(e.has(t[a]))continue;const s=a<n?a:a+1;(Math.floor(s/2)<r?0:1)===i&&o++}return o}function ZP(t){const e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return Ci({result:{error:Ae},info:"playoffGroups required",stack:e});const{sourceStructureId:n,requireSequential:r,tournamentRecord:i,drawDefinition:a,playoffGroups:s,groupCount:c,groupSize:u,event:d}=t,p=Bv({requireSequential:r,sourceStructureId:n,playoffGroups:s,groupCount:c,groupSize:u,...t});if(p.error)return Ci({result:p,stack:e});const{structures:l=[],links:m=[],finishingPositionTargets:f,positionRangeMap:h}=p,g=f?.flatMap(({finishingPositions:t})=>t).flatMap(t=>h[t].finishingPositions);a.structures.push(...l),a.links.push(...m);const{matchUps:I,matchUpsMap:S}=zg({inContext:!0,drawDefinition:a}),y=new Set(l.map(({structureId:t})=>t)),v=I?.filter(({structureId:t})=>y.has(t)).map(tl),U=S?.drawMatchUps?.filter(({matchUpId:t})=>v?.includes(t));if(U?.length){const e=Rf({drawDefinition:a,event:d})?.tieFormat;e&&U.forEach(n=>{const{tieMatchUps:r}=BP({isMock:t.isMock,tieFormat:e,matchUp:n});Object.assign(n,{tieMatchUps:r,matchUpType:o})})}const{positionAssignments:P}=cl({structureId:n,drawDefinition:a}),T={};P?.forEach(t=>{const e=dp({element:t,attribute:"tally",name:Rd}),n=e?.groupOrder;n&&(T[n]||(T[n]=[]),T[n].push(t.participantId))});const w=XU({provisionalPositioning:t.provisionalPositioning,structureId:n,applyPositioning:!0,event:t.event,tournamentRecord:i,drawDefinition:a});return w.error&&w.error?.code!==pt.code?Ci({result:w,stack:e}):{structures:l,links:m,positionsPlayedOff:g,drawDefinition:a,...Y}}function tT({positionAssignments:t,tournamentRecord:e,drawDefinition:n,matchUpFormat:r,matchUps:i,event:o}){if(!Lf(i))return{error:sr};if(!t)return{error:sr};const{policyDefinitions:a}=_d({policyTypes:[Ru],tournamentRecord:e,drawDefinition:n,event:o}),{subOrderMap:s}=cS({positionAssignments:t}),c=i.length?aS({policyDefinitions:a,matchUpFormat:r,subOrderMap:s,matchUps:i}):void 0;if(c?.error)return c;const{participantResults:u={},bracketComplete:d,report:p}=c??{},l=Object.keys(u);return t.forEach(t=>{const{participantId:e}=t;l.includes(e)?(sp({value:u[e],element:t,attribute:"tally",name:Rd}),u[e].ties||sp({element:t,attribute:"subOrder",name:Dd,value:void 0})):(sp({element:t,attribute:"tally",name:Rd,value:void 0}),sp({element:t,attribute:"subOrder",name:Dd,value:void 0}))}),Ql({drawDefinition:n}),{...Y,participantResults:u,bracketComplete:d,report:p}}function eT({matchUps:t,matchUpId:e}){return{matchUp:(t??[]).find(t=>t.matchUpId===e)}}function nT(t){const e=fu(t,[{[yc]:!0,[kc]:!0}]);if(e.error)return e;const{tournamentParticipants:n,participantsProfile:r,afterRecoveryTimes:i,contextProfile:o,drawDefinition:a,matchUpsMap:s,matchUpId:c,inContext:u,context:d,event:p}=t,{structures:l=[]}=al({drawDefinition:a}),m=t.contextContent||o&&zm({contextProfile:o,drawDefinition:a});for(const t of l){const{matchUps:e}=Fg({tournamentParticipants:n,participantsProfile:r,afterRecoveryTimes:i,contextContent:m,drawDefinition:a,contextProfile:o,matchUpsMap:s,inContext:u,structure:t,context:d,event:p}),{matchUp:l}=eT({matchUps:e,matchUpId:c});if(l)return{matchUp:l,structure:t}}return{error:ge}}function rT(t){return f(t)&&t.notes?f(t.element)&&(m(t.notes)||t.notes?.testing)?(Object.assign(t.element,{notes:t.notes}),{...Y}):{error:sr}:{error:Ae}}function iT(t){return f(t)?f(t.element)?(t.element.notes&&delete t.element.notes,{...Y}):{error:sr}:{error:Ae}}const oT={matchUpStatus:Ap,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function aT(t){const e="modifyMatchUpScore";let n,r=t.matchUpFormat,i=t.matchUp;const{matchUpStatusCodes:o,tournamentRecord:s,drawDefinition:c,matchUpStatus:u,removeScore:d,winningSide:p,matchUpId:l,event:m,notes:f,score:h}=t,g=function({appliedPolicies:t,tournamentRecord:e,drawDefinition:n,structure:r,event:i}){const o=t&&Object.keys(t).length;return o?t:xd({policyTypes:[Fu],tournamentRecord:e,drawDefinition:n,structure:r,event:i})?.appliedPolicies}({appliedPolicies:t.appliedPolicies,tournamentRecord:s,drawDefinition:c,structure:n,event:m}),I=i.matchUpType===a,S=function({isDualMatchUp:t,drawDefinition:e,matchUpId:n,matchUp:r,event:i}){if(t&&e){if(n&&r.matchUpId!==n){const t=nT({drawDefinition:e,matchUpId:n,event:i});return t.matchUp?{matchUp:t.matchUp,structure:t.structure}:{error:ge}}return}r.matchUpId!==n&&console.log("!!!!!");return}({isDualMatchUp:I,drawDefinition:c,matchUpId:l,matchUp:i,event:m});if(S?.error)return S;S&&({matchUp:i,structure:n}=S);const y=u&&i?.matchUpStatus===Pp&&u!==Pp;let v;!function({matchUpStatusCodes:t,removeWinningSide:e,matchUpStatus:n,matchUpFormat:r,removeScore:i,winningSide:o,matchUp:a,score:s}){const c=new Set([Ep,wp]);n&&c.has(n)||i?Object.assign(a,{...oT}):s&&(a.score=s);n&&(a.matchUpStatus=n);r&&(a.matchUpFormat=r);t&&(a.matchUpStatusCodes=t);o&&(a.winningSide=o);e&&(a.winningSide=void 0)}({matchUpStatusCodes:o,removeWinningSide:t.removeWinningSide,matchUpStatus:u,matchUpFormat:r,removeScore:d,winningSide:p,matchUp:i,score:h}),!n&&c&&({structure:n}=nT({drawDefinition:c,matchUpId:l,event:m})),function({matchUpStatus:t,matchUp:e}){const n=new Set([Ip,Mp,Rp]);!t||e.winningSide||!aI(e)||_p.includes(t)||n.has(t)||(e.matchUpStatus=Dp)}({matchUpStatus:u,matchUp:i}),(y&&i?.processCodes?.length||u===Pp)&&(v=g?.[Fu]?.processCodes?.incompleteAssignmentsOnDefault);const U=function({isDualMatchUp:t,tournamentRecord:e,drawDefinition:n,matchUpFormat:r,matchUpId:i,structure:o,matchUp:s,event:c}){if(s.collectionId)return;const u=o?.structureType===Ds,d=Hf({structure:o});if(!$f({drawDefinition:n,structure:o})&&!d&&!u)return;const p=t?"SET1-S:T100":r??s.matchUpFormat??o?.matchUpFormat??n?.matchUpFormat??c?.matchUpFormat,l=t?{matchUpTypes:[a]}:void 0,m=u&&o.structures.find(t=>t?.matchUps.find(t=>t.matchUpId===i))||o,{matchUps:f}=Fg({structure:m,afterRecoveryTimes:!1,tournamentRecord:e,inContext:!0,matchUpFilters:l,drawDefinition:n,event:c});d&&(m.positionAssignments=M(f.flatMap(t=>(t.sides??[]).map(t=>t.participantId)).filter(Boolean)).map(t=>({participantId:t})));const h=tT({positionAssignments:m.positionAssignments,matchUpFormat:p,tournamentRecord:e,drawDefinition:n,matchUps:f,event:c});return h.error?h:{matchUpFormat:p}}({isDualMatchUp:I,tournamentRecord:s,drawDefinition:c,matchUpFormat:r,matchUpId:l,structure:n,matchUp:i,event:m});if(U?.error)return Ci({result:U,stack:e});if(c&&i.winningSide){const{competitionPolicy:t}=Ld({tournamentRecord:s,drawDefinition:c,event:m});"PER_MATCHUP"===t?.processingGranularity&&hp({tournamentRecord:s,drawDefinition:c,matchUp:i,event:m})}if(f){const t=rT({element:i,notes:f});if(t.error)return Ci({result:t,stack:e})}const P=s?.tournamentId,T=function({defaultedProcessCodes:t,tournamentRecord:e,drawDefinition:n,matchUpId:r}){if(!gi().topics.includes(jl)&&!t)return;const i=bf({drawDefinition:n});return i?zg({matchUpFilters:{matchUpIds:[r]},nextMatchUps:!0,tournamentRecord:e,inContext:!0,drawDefinition:n,matchUpsMap:i}).matchUps?.[0]:void 0}({defaultedProcessCodes:v,tournamentRecord:s,drawDefinition:c,matchUpId:l});if(T){gi().topics.includes(jl)&&function({tournamentId:t,inContextMatchUp:e}){e&&di({payload:{inContextMatchUp:e,tournamentId:t},topic:jl,key:e.matchUpId})}({tournamentId:P,inContextMatchUp:T})}return function({defaultedProcessCodes:t,inContextMatchUp:e,matchUpStatus:n,matchUp:r}){if(!Array.isArray(t)||!e)return;if(e.sides?.every(({participantId:t})=>t))return;if(n===Pp)r.processCodes=M([...r.processCodes??[],...t]);else for(const e of t??[]){const t=e&&r?.processCodes?.lastIndexOf(e);r?.processCodes?.splice(t,1)}}({defaultedProcessCodes:v,inContextMatchUp:T,matchUpStatus:u,matchUp:i}),Yl({eventId:m?.eventId,context:e,drawDefinition:c,tournamentId:P,matchUp:i}),{...Y}}function sT(t){const{propagateExitStatus:e,matchUpStatusCodes:n,autoCalcDisabled:r,inContextMatchUp:i,matchUpStatus:o,dualMatchUp:a,structure:s,matchUp:c}=t,u=sI({matchUpStatus:o})||[yp,gp].includes(o)&&a||r,d=c?.sides?.map(t=>t.participantId).filter(Boolean).length||i?.sides?.map(t=>t.participantId).filter(Boolean).length,p="attemptToModifyScore",l=Hf({structure:s})&&1===d||o===Pp&&d||function({structure:t,matchUp:e,inContextMatchUp:n}){const{drawPositions:r}=e,{positionAssignments:i}=ul({structure:t}),o=i?.filter(t=>r?.includes(t.drawPosition)&&t.participantId),a=n?.sides?.every(t=>t.participantId);return 2===o?.length||a}({structure:s,matchUp:c,inContextMatchUp:i})||!1===t.appliedPolicies?.[Fu]?.requireParticipantsForScoring||II(o)&&1===d&&e;if(!l)return Ci({result:{error:Jt},stack:p});const m=[Ep].includes(o),f=u?o:t.winningSide&&vp||Rp;return Ci({result:aT({...t,winningSide:t.winningSide,matchUpStatusCodes:(u&&n)??[],matchUpStatus:f,removeScore:m}),stack:p})}function cT({collectionGroups:t=[]}){const e=Object.assign({},...t.filter(t=>R(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=>p(t))}}function uT({collectionDefinition:t,groupValueNumbers:e,groupValueGroups:n,sideTieValues:r,tieMatchUps:i}){const o=i.filter(e=>e.collectionId===t.collectionId),a=[0,0];let s=[0,0];const c=o.every(t=>_p.includes(t.matchUpStatus)),{collectionValueProfiles:u,collectionGroupNumber:d,collectionValue:p,matchUpValue:l,winCriteria:m,scoreValue:f,setValue:h}=t,g=d&&e.includes(d),I=[0,0];o.forEach(t=>{t.winningSide&&(I[t.winningSide-1]+=1)}),function({collectionDefinition:t,collectionMatchUps:e,sideMatchUpValues:n,collectionValueProfiles:r,matchUpValue:i,scoreValue:o,setValue:a}){R(i)?e.forEach(t=>{t.winningSide&&(n[t.winningSide-1]+=i)}):R(a)?e.forEach(t=>{t.score?.sets?.forEach(t=>{t.winningSide&&(n[t.winningSide-1]+=a)})}):R(o)?function({collectionMatchUps:t,sideMatchUpValues:e}){t.forEach(t=>{t.score?.sets?.forEach(n=>{const{side1TiebreakScore:r=0,side2TiebreakScore:i=0,side1Score:o=0,side2Score:a=0}=n;(t.matchUpStatus===vp||t.winningSide||n.winningSide)&&(o||a?(e[0]+=o,e[1]+=a):(r||i)&&n.winningSide&&(e[n.winningSide-1]+=1))})})}({collectionMatchUps:e,sideMatchUpValues:n}):Array.isArray(r)&&function({collectionMatchUps:t,collectionDefinition:e,sideMatchUpValues:n}){t.forEach(t=>{if(t.winningSide){const r=t.collectionPosition,i=function({collectionDefinition:t,collectionPosition:e}){const n=t.collectionValueProfiles??[],r=n?.find(t=>t.collectionPosition===e);return r?.matchUpValue}({collectionDefinition:e,collectionPosition:r});R(i)&&(n[t.winningSide-1]+=i)}})}({collectionMatchUps:e,collectionDefinition:t,sideMatchUpValues:n})}({collectionDefinition:t,collectionMatchUps:o,sideMatchUpValues:a,collectionValueProfiles:u,matchUpValue:l,scoreValue:f,setValue:h}),s=function({allCollectionMatchUpsCompleted:t,collectionDefinition:e,sideCollectionValues:n,belongsToValueGroup:r,sideMatchUpValues:i,groupValueGroups:o,collectionGroupNumber:a,collectionValue:s,matchUpValue:c,winCriteria:u,scoreValue:d,setValue:p,sideWins:l}){if(R(s)){const m=function({allCollectionMatchUpsCompleted:t,collectionDefinition:e,sideMatchUpValues:n,matchUpValue:r,winCriteria:i,scoreValue:o,setValue:a,sideWins:s}){if(i?.aggregateValue){if(t){if(R(r||a||o)&&n[0]!==n[1])return n[0]>n[1]?1:2;if(s[0]!==s[1])return s[0]>s[1]?1:2}return}if(i?.valueGoal)return n.reduce((t,e,n)=>e>=i.valueGoal?n+1:t,0);const c=Math.floor(e.matchUpCount/2)+1;return s.reduce((t,e,n)=>e>=c?n+1:t,0)}({allCollectionMatchUpsCompleted:t,collectionDefinition:e,sideMatchUpValues:i,matchUpValue:c,winCriteria:u,scoreValue:d,setValue:p,sideWins:l});m&&(r?o[a].values[m-1]+=s:n[m-1]+=s)}else r?(o[a].values[0]+=i[0]||0,o[a].values[1]+=i[1]||0):n=i;return n}({allCollectionMatchUpsCompleted:c,collectionDefinition:t,sideCollectionValues:s,belongsToValueGroup:g,sideMatchUpValues:a,groupValueGroups:n,collectionGroupNumber:d,collectionValue:p,matchUpValue:l,winCriteria:m,scoreValue:f,setValue:h,sideWins:I}),g?(n[d].sideWins[0]+=I[0]||0,n[d].sideWins[1]+=I[1]||0,n[d].allGroupMatchUpsCompleted=n[d].allGroupMatchUpsCompleted&&c,n[d].matchUpsCount+=o.length):s.forEach((t,e)=>r[e]+=t||0)}function dT(t){const{sideAdjustments:e=[0,0],separator:n="-",drawDefinition:r,matchUpsMap:i,structure:o,matchUp:a,event:s}=t;if(!Array.isArray(e)||2!==e.length||Number.isNaN(e.reduce((t,e)=>t+e)))return{error:sr};if(!a)return{error:Se};const c=Rf({matchUp:a,drawDefinition:r,structure:o,event:s})?.tieFormat||t?.tieFormat;if(!c)return{error:me};const u=na({tieFormat:c});if(u.error)return u;const d=function(t,e){const n=t?.collectionDefinitions??[],r=e?.tieMatchUps??[],i=[0,0],{groupValueGroups:o,groupValueNumbers:a}=cT(t);for(const t of n)uT({collectionDefinition:t,groupValueNumbers:a,groupValueGroups:o,sideTieValues:i,tieMatchUps:r});for(const t of a){const e=pT(o[t]);e&&(i[e-1]+=o[t].groupValue||0)}return i}(c,a),p=d.map((t,n)=>(t||0)+e[n]),l={side1Score:p[0],side2Score:p[1],winningSide:void 0},m=p.join(n),f=p.slice().reverse().join(n),h=function({drawDefinition:t,matchUpsMap:e,sideScores:n,tieFormat:r,matchUp:i}){if(!r?.winCriteria)return;const{valueGoal:o,aggregateValue:a,tallyDirectives:s}=r.winCriteria,c=i?.tieMatchUps??[];let u;o?u=function(t,e){const n=t.map((t,e)=>({sideNumber:e+1,points:t})).find(({points:t})=>t>=e);return n?.sideNumber}(n,o):a&&(u=function(t,e){const n=t.every(t=>t.matchUpStatus&&_p.includes(t.matchUpStatus)||t.winningSide);if(n&&e[0]!==e[1])return e[0]>e[1]?1:2;return}(c,n));!u&&s&&(u=function({drawDefinition:t,matchUpsMap:e,matchUp:n}){const r=n.matchUpId,i=n.hasContext?n:e?.drawMatchUps?.[r]||t&&nT({inContext:!0,drawDefinition:t,matchUpId:r})?.matchUp;if(!i)return;const{completedTieMatchUps:o,order:a}=aS({matchUps:[i]});if(!o||!a?.length)return;const s=a[0].participantId;return i.sides.find(({participantId:t})=>t===s)?.sideNumber}({drawDefinition:t,matchUpsMap:e,matchUp:i}));return u}({drawDefinition:r,matchUpsMap:i,sideScores:p,tieFormat:c,matchUp:a});return h&&(l.winningSide=h),{scoreStringSide1:m,scoreStringSide2:f,winningSide:h,set:l}}function pT(t){const{allGroupMatchUpsCompleted:e,matchUpCount:n,winCriteria:r,sideWins:i,values:o}=t;if(r?.aggregateValue)return e&&o[0]!==o[1]?o[0]>o[1]?1:2:void 0;if(r?.valueGoal)return o.reduce((t,e,n)=>e>=r.valueGoal?n+1:t,void 0);const a=Math.floor(n/2)+1;return i.reduce((t,e,n)=>e>=a?n+1:t,void 0)}function lT({inContextDualMatchUp:t,drawDefinition:e,tournamentId:n,dualMatchUp:r,eventId:i}){if(r){t||(t=nT({matchUpId:r.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);const o=ca(dp({element:e,attribute:"lineUps",name:fd})??{},!1,!0),a=({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,...s}=r.sides?.find(({sideNumber:e})=>e===t.sideNumber)??{},c=i?.length?i:n;return{...a(t),...s,lineUp:c}}),Yl({context:"ensureSidLineUps",matchUp:r,drawDefinition:e,tournamentId:n,eventId:i})}}function mT(t){if(t)return ca(t,!1,!0)}function fT(t){const e=fu(t,[{[hc]:!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),o=r.map(t=>(t.drawDefinitions??[]).map(({drawId:t})=>t)).flat();return e.tournamentIdMap[n].push(...i,...o),e.eventIds.push(...i),e.drawIds.push(...o),e},{eventIds:[],drawIds:[],tournamentIdMap:{}})}function hT({tournamentRecords:t,eventId:e,drawId:n}){const{tournamentIdMap:r}=fT({tournamentRecords:t});return(r?Object.keys(r):[]).find(t=>e&&r?.[t].includes(e)||n&&r?.[t].includes(n))}function gT(t){const{exitWhenNoValues:e,drawDefinition:n,matchUpStatus:r,removeScore:i,matchUpsMap:o,matchUpId:a,event:s}=t,c=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord?.tournamentId]:t.tournamentRecord}||{},u=t.tournamentId||t.tournamentRecord?.tournamentId;c&&hT({tournamentRecords:c,...t});const d=u&&c[u];if(!d)return{error:rt};const p=nT({drawDefinition:n,event:s,matchUpId:a});if(p.error)return p;if(!p.matchUp)return{error:ge};const{matchUp:l,structure:m}=p;if(!l.tieMatchUps)return{error:ye};lT({tournamentId:d?.tournamentId,eventId:s?.eventId,dualMatchUp:l,drawDefinition:n});if(dp({element:l,attribute:"disableAutoCalc",name:ad})){if(!i)return{...Y,score:l.score};sp({element:l,attribute:"disableAutoCalc",name:ad,value:void 0})}const f=Rf({drawDefinition:n,structure:m,matchUp:l,event:s})?.tieFormat;l.tieFormat=mT(f);const h=dT({drawDefinition:n,matchUpsMap:o,structure:m,matchUp:l,event:s}),{winningSide:g,set:I,scoreStringSide1:S,scoreStringSide2:y}=h,v=I?.side1Score||I?.side2Score;if(e&&!l.score&&!v)return{...Y};const U={scoreStringSide1:S,scoreStringSide2:y,sets:I?[I]:[]},P=g&&[1,2].includes(g),T=P&&vp||uI({matchUpStatus:r??l.matchUpStatus,tieMatchUps:l.tieMatchUps,winningSide:l.winningSide,score:U})&&Dp||Ap,w=!(!l.winningSide||P),D=l.tieMatchUps.find(({score:t,winningSide:e,matchUpStatus:n})=>t?.sets?.length&&(t.sets[0].side1Score||t.sets[0].side2Score)||n&&_p.includes(n)||e);let R;if(l.tieFormat&&!P&&!D){const t=Rf({drawDefinition:n,structure:m,event:s})?.tieFormat;t&&JSON.stringify(f)===JSON.stringify(t)&&(l.tieFormatId=void 0,l.tieFormat=void 0,R=!0)}return aT({appliedPolicies:t.appliedPolicies,matchUpStatus:T,score:U,removeWinningSide:w,tournamentRecord:d,drawDefinition:n,removeScore:i,winningSide:g,matchUpId:a,matchUp:l,event:s}),{...Y,score:U,removeWinningSide:w,tieFormatRemoved:R,winningSide:g}}function IT({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,projectedWinningSide:n,sourceMatchUpStatus:r,winningDrawPosition:i,tournamentRecord:o,winnerTargetLink:a,sourceMatchUpId:s,drawDefinition:c,winnerMatchUp:u,dualMatchUp:d,matchUpsMap:p,event:l}){const m="directWinner";if(a){const n=function({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,winningDrawPosition:r,tournamentRecord:i,winnerTargetLink:o,sourceMatchUpId:a,drawDefinition:s,winnerMatchUp:c,matchUpsMap:u,event:d,stack:p}){const l=c.drawPositions??[],m=l[t],f=o.source.structureId,h=ol({structureId:f,drawDefinition:s});if(h.error)return h;const{structure:g}=h,{positionAssignments:I}=ul({structureId:f,drawDefinition:s}),S=I?.find(t=>t.drawPosition===r),y=S?.participantId,v=o.target.structureId,{positionAssignments:U}=ul({structureId:v,drawDefinition:s}),P=U?.find(t=>t.participantId===y),T=P?.drawPosition,w=U?.filter(t=>{const e=l.includes(t.drawPosition),n=!t.participantId&&!t.bye&&!t.qualifier;return e&&n}).map(t=>t.drawPosition),D=w?.includes(m);if(y&&1===o.target.roundNumber&&D)av({drawPosition:m,participantId:y,structureId:v,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:s,matchUpsMap:u,event:d});else if(y&&w?.length){const t=w.pop();t&&av({participantId:y,structureId:v,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:s,drawPosition:t,matchUpsMap:u,event:d})}else if(T){const t=Zy({drawPosition:T,matchUpId:c.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:s,matchUpsMap:u});if(t.error)return Ci({result:t,stack:p})}else if(g?.stage!==ds){const t="winner target position unavaiallble";console.log(t),Ci({stack:p,result:{error:t}})}if(g?.seedAssignments&&g.structureId!==v){const t=g.seedAssignments.find(({participantId:t})=>t===y),e=t?.participantId;t&&e&&zy({eventId:c?.eventId,structureId:v,...t,tournamentRecord:i,drawDefinition:s,participantId:e})}return}({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,winningDrawPosition:i,tournamentRecord:o,winnerTargetLink:a,sourceMatchUpId:s,drawDefinition:c,winnerMatchUp:u,matchUpsMap:p,event:l,stack:m});if(n?.error)return n}else{const t=Zy({matchUpId:u.matchUpId,drawPosition:i,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:o,sourceMatchUpId:s,drawDefinition:c,matchUpsMap:p});if(t.error)return t}return d&&n&&function({projectedWinningSide:t,tournamentRecord:e,drawDefinition:n,winnerMatchUp:r,dualMatchUp:i,matchUpsMap:o,stack:a}){const s=i.sides?.find(e=>e.sideNumber===t);if(!s?.lineUp)return;const c=i.roundPosition,u=r.roundPosition,d=c===u&&1!==c||Math.floor(c/2)===u?2:1,p=o?.drawMatchUps?.find(({matchUpId:t})=>t===r.matchUpId),l=[1,2].map(t=>({...p.sides?.find(e=>e.sideNumber===t)??{},sideNumber:t}));p.sides=l;const m=p.sides.find(t=>t.sideNumber===d);if(m){const t=s.lineUp?.filter(t=>t?.participantId);m.lineUp=ev({lineUp:t}),Yl({tournamentId:e?.tournamentId,eventId:r?.eventId,matchUp:p,context:a,drawDefinition:n})}}({projectedWinningSide:n,tournamentRecord:o,drawDefinition:c,winnerMatchUp:u,dualMatchUp:d,matchUpsMap:p,stack:m}),{...Y}}function ST(t){const{loserMatchUpDrawPositionIndex:e,inContextDrawMatchUps:n,projectedWinningSide:r,propagateExitStatus:i,sourceMatchUpStatus:o,loserDrawPosition:a,tournamentRecord:s,loserTargetLink:c,drawDefinition:u,loserMatchUp:p,dualMatchUp:l,matchUpsMap:m,event:f}=t,h="directLoser",g=c.linkCondition,I=p.drawPositions??[],S=g===Os&&2===p.roundNumber&&Math.min(...I.filter(Boolean)),y=S||I[e],v=S||I[1-e],U=c.source.structureId,{structure:P}=ol({structureId:U,drawDefinition:u}),{matchUps:T}=Fg({afterRecoveryTimes:!1,inContext:!0,drawDefinition:u,structure:P,event:f}),w=T.filter(t=>t.drawPositions?.includes(a)).filter(t=>{const e=t.sides.find(t=>t.drawPosition===a),n=t.matchUpStatus===Ep||t.matchUpStatus===Pp&&!aI(t);return e?.sideNumber===t.winningSide&&!n}),D=g===Os&&0===w.length,{positionAssignments:R}=ul({structureId:U,drawDefinition:u}),b=R?.find(t=>t.drawPosition===a),N=b?.participantId,M={loserParticipantId:N},A=c.target.structureId,{positionAssignments:E}=ul({structureId:A,drawDefinition:u}),C=E?.filter(({drawPosition:t})=>I.includes(t)),O=C?.some(t=>t.participantId&&N&&t.participantId===N),k=i&&[Np,Ep,Pp].includes(o||"");if(O)return{...Y,stack:h};const F=C?.filter(t=>{const e=I.includes(t.drawPosition),n=!t.participantId&&!t.bye&&!t.qualifier;return e&&n}).map(t=>t.drawPosition),x=F?.includes(y),_=c.target.roundNumber>1&&F?.length,L=function({fedDrawPositionFMLC:t,isFirstRoundValidDrawPosition:e,loserParticipantId:n,isFeedRound:r,unfilledTargetMatchUpDrawPositions:i,targetDrawPositionIsUnfilled:o,validForConsolation:a,targetMatchUpDrawPosition:s,loserBackdrawPosition:c,targetStructureId:u,inContextDrawMatchUps:p,sourceMatchUpStatus:l,validExitToPropagate:m,propagateExitStatus:f,loserDrawPosition:h,loserTargetLink:g,tournamentRecord:I,drawDefinition:S,matchUpsMap:y,event:v}){const U=()=>{const t=n?av({drawPosition:s,participantId:n,structureId:u,inContextDrawMatchUps:p,sourceMatchUpStatus:l,tournamentRecord:I,drawDefinition:S,matchUpsMap:y,event:v}):{error:sn};return!t.error&&m&&f?{context:{progressExitStatus:!0}}:Ci({result:t,stack:"assignLoserDrawPosition"})};if(t){const t="loserLinkFedFMLC";if(a)return Ci({result:U(),stack:t});return Ci({result:Ci({result:SI({drawPosition:c,structureId:u,tournamentRecord:I,drawDefinition:S,event:v}),stack:"assignLoserPositionBye"}),stack:t})}if(e)return U();if(n&&(r||i?.length)){i.sort(d);const t=i[0],e=av({participantId:n,structureId:u,drawPosition:t,inContextDrawMatchUps:p,sourceMatchUpStatus:l,tournamentRecord:I,drawDefinition:S,matchUpsMap:y,event:v});return e.error?e:m&&f?{earlyReturn:{stack:"directLoser",context:{progressExitStatus:!0,loserParticipantId:n}}}:{...Y}}const P=o?Pt:Ut;return{context:{loserDrawPosition:h,loserTargetLink:g,targetDrawPositionIsUnfilled:o},error:P}}({fedDrawPositionFMLC:S,isFirstRoundValidDrawPosition:1===c.target.roundNumber&&x,loserParticipantId:N,isFeedRound:_,unfilledTargetMatchUpDrawPositions:F,targetDrawPositionIsUnfilled:x,validForConsolation:D,targetMatchUpDrawPosition:y,loserBackdrawPosition:v,targetStructureId:A,inContextDrawMatchUps:n,sourceMatchUpStatus:o,validExitToPropagate:k,propagateExitStatus:i,loserDrawPosition:a,loserTargetLink:c,tournamentRecord:s,drawDefinition:u,matchUpsMap:m,event:f});return L.context&&Object.assign(M,L.context),L.error?Ci({result:L,stack:h}):L.earlyReturn?L.earlyReturn:(function({loserParticipantId:t,targetStructureId:e,tournamentRecord:n,drawDefinition:r,loserMatchUp:i,structure:o}){if(!o?.seedAssignments||o.structureId===e)return;const a=o.seedAssignments.find(({participantId:e})=>e===t),s=a?.participantId;a&&s&&zy({eventId:i?.eventId,structureId:e,...a,tournamentRecord:n,drawDefinition:r,participantId:s})}({loserParticipantId:N,targetStructureId:A,tournamentRecord:s,drawDefinition:u,loserMatchUp:p,structure:P}),function({projectedWinningSide:t,tournamentRecord:e,drawDefinition:n,loserMatchUp:r,dualMatchUp:i,matchUpsMap:o,stack:a}){if(!i||!t)return;const s=i.sides?.find(e=>e.sideNumber===3-t);if(!s?.lineUp)return;const{roundNumber:c,eventId:u}=r,{roundPosition:d}=i,p=1===c?2-d%2:1,l=o?.drawMatchUps?.find(({matchUpId:t})=>t===r.matchUpId),m=[1,2].map(t=>({...l.sides?.find(e=>e.sideNumber===t)??{},sideNumber:t}));l.sides=m;const f=l.sides.find(t=>t.sideNumber===p);f&&(f.lineUp=ev({lineUp:s.lineUp}),Yl({tournamentId:e?.tournamentId,matchUp:l,context:a,drawDefinition:n,eventId:u}))}({projectedWinningSide:r,tournamentRecord:s,drawDefinition:u,loserMatchUp:p,dualMatchUp:l,matchUpsMap:m,stack:h}),Ci({result:{...Y},stack:h,context:M}))}function yT(t){const e="directParticipants",n=sT(t);if(n.error)return Ci({result:n,stack:e});const r=sI({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:i,inContextDrawMatchUps:o,projectedWinningSide:a,propagateExitStatus:s,matchUpStatusCodes:c,tournamentRecord:u,drawDefinition:d,matchUpStatus:p,dualMatchUp:l,matchUpsMap:m,winningSide:f,targetData:h,matchUpId:g,structure:I,matchUp:S,event:y}=t,v=Boolean(S.collectionId),U=Hf({structure:I});let P,T=S.drawPositions;if(v){const{matchUpTieId:n,matchUpsMap:r}=t,a=gT({appliedPolicies:t.appliedPolicies,matchUpId:n,tournamentRecord:u,drawDefinition:d,matchUpsMap:r,event:y});P=a&&{tieMatchUpResult:a};const s=o.find(({matchUpId:t})=>t===n);if(T=s?.drawPositions,!i)return Ci({result:{...Y,...P},stack:e})}return U?Ci({result:{...Y,...P},stack:e}):T?function({matchUpStatusIsValid:t,inContextDrawMatchUps:e,projectedWinningSide:n,propagateExitStatus:r,matchUpStatusCodes:i,tournamentRecord:o,drawDefinition:a,drawPositions:s,matchUpStatus:c,dualMatchUp:u,matchUpsMap:d,winningSide:p,targetData:l,matchUpId:m,structure:f,annotate:h,matchUp:g,stack:I,event:S}){const y=n?n-1:p-1,v=1-y,U=s[y],P=s[v],T={},{targetLinks:{loserTargetLink:w,winnerTargetLink:D,byeTargetLink:R},targetMatchUps:{winnerMatchUpDrawPositionIndex:b,loserMatchUpDrawPositionIndex:N,winnerMatchUp:M,loserMatchUp:A,byeMatchUp:E}}=l,C=qf(a?.drawType),O=function(t,e,n){if(!t||!e.roundNumber||!n?.matchUps)return!1;const r=n.matchUps.filter(t=>t.roundNumber===e.roundNumber).length;return r%2!=0}(C,g,f),k=!C||!O,F=t&&c||vp;if(M&&k){const t=IT({sourceMatchUpStatus:F,winnerMatchUpDrawPositionIndex:b,sourceMatchUpId:m,inContextDrawMatchUps:e,projectedWinningSide:n,winningDrawPosition:U,tournamentRecord:o,winnerTargetLink:D,drawDefinition:a,winnerMatchUp:M,dualMatchUp:u,matchUpsMap:d,event:S});if(t.error)return Ci({result:t,stack:I})}if(A&&k){const t=ST({sourceMatchUpStatus:F,loserMatchUpDrawPositionIndex:N,inContextDrawMatchUps:e,projectedWinningSide:n,propagateExitStatus:r,loserDrawPosition:P,tournamentRecord:o,loserTargetLink:w,drawDefinition:a,loserMatchUp:A,matchUpsMap:d,dualMatchUp:u,event:S});if(t.context?.progressExitStatus&&Object.assign(T,t.context,{sourceMatchUpStatus:F,sourceMatchUpStatusCodes:i??[],loserMatchUp:A,matchUpsMap:d}),t.error)return Ci({result:t,stack:I})}if(E){const t=E.drawPositions??[],e=SI({drawPosition:Math.min(...t.filter(Boolean)),structureId:R.target.structureId,tournamentRecord:o,drawDefinition:a,event:S});if(e.error)return Ci({result:e,stack:I})}return Ci({result:{...Y,...h},stack:I,context:T})}({matchUpStatusIsValid:r,inContextDrawMatchUps:o,projectedWinningSide:a,propagateExitStatus:s,matchUpStatusCodes:c,tournamentRecord:u,drawDefinition:d,drawPositions:T,matchUpStatus:p,dualMatchUp:l,matchUpsMap:m,winningSide:f,targetData:h,matchUpId:g,structure:I,annotate:P,matchUp:S,stack:e,event:y}):Ci({result:{error:yt},stack:e})}function vT(t){const e="genPlayoffStructure",n=function(t,e){if(!t.drawDefinition)return{error:!0,earlyReturn:Ci({result:{error:st},stack:e})};const n=bv(t);if(n.error)return{error:!0,earlyReturn:Ci({result:n,stack:e})};const{structureId:r,addNameBaseToAttributeName:i,playoffStructureNameBase:o,finishingPositionNaming:a,finishingPositionLimit:s,playoffAttributes:c,playoffPositions:u,roundOffsetLimit:d,tournamentRecord:p,exitProfileLimit:l,playoffGroups:m,roundProfiles:f,roundNumbers:h,idPrefix:g,isMock:I,event:S,uuids:y}=t,v=ca(t.drawDefinition,!1,!0),{structure:U}=ol({structureId:r,drawDefinition:v});if(!U)return{error:!0,earlyReturn:Ci({result:{error:Vt},stack:e})};if(U.structureType===Ds||U.structures)return{error:!0,earlyReturn:ZP({sourceStructureId:U.structureId,...t,...n,drawDefinition:v})};if(m?.length)return{error:!0,earlyReturn:UT({sourceStructureId:r,tournamentRecord:p,drawDefinition:v,playoffGroups:m,structure:U,idPrefix:g,isMock:I,event:S,uuids:y,stack:e})};return{addNameBaseToAttributeName:i,playoffStructureNameBase:o,finishingPositionNaming:a,finishingPositionLimit:s,availabilityResult:n,sourceStructureId:r,playoffAttributes:c,playoffPositions:u,roundOffsetLimit:d,tournamentRecord:p,exitProfileLimit:l,drawDefinition:v,roundProfiles:f,roundNumbers:h,structure:U,idPrefix:g,isMock:I,event:S,uuids:y}}(t,e);if(n.error||n.earlyReturn)return n.earlyReturn??n;const{addNameBaseToAttributeName:r,playoffStructureNameBase:i,finishingPositionNaming:o,finishingPositionLimit:s,availabilityResult:c,sourceStructureId:u,playoffAttributes:d,playoffPositions:l,roundOffsetLimit:m,tournamentRecord:f,exitProfileLimit:h,drawDefinition:g,roundProfiles:I,roundNumbers:S,structure:y,idPrefix:v,isMock:U,event:P,uuids:T}=n,{playoffRoundsRanges:w,playoffRounds:D}=c,{playoffPositionsReturned:R,error:b,playoffSourceRounds:N,playoffRoundsRanges:M}=Rv(t);if(b)return Ci({result:{error:b},stack:e});const A=I?.length&&Object.assign({},...I),E=S||"object"==typeof I&&I.flatMap(t=>Object.keys(t)),C=Array.isArray(E)&&E.map(t=>!Number.isNaN(Number(t))&&p(t)).filter(Boolean);if(C){if(!Array.isArray(C))return Ci({result:{error:sr},context:{validRoundNumbers:C},stack:e});C.forEach(t=>{if(!D?.includes(t))return Ci({result:{error:sr},context:{roundNumber:t},stack:e})})}l&&l.forEach(t=>{if(!R?.includes(t))return Ci({result:{error:sr},context:{playoffPosition:t},stack:e})});const O=C||N,k=C?w:M,F=[],x=[],_=qf(g.drawType);for(const t of O??[]){const n=k?.find(e=>e.roundNumber===t);if(!n)return Ci({result:{error:sr},context:{roundNumber:t},stack:e});const a=PT({finishingPositionsCount:n.finishingPositions.length,isLuckyDraw:_,roundNumber:t,structure:y}),c=Math.min(...n.finishingPositions)-1,p=2,l=t&&A?.[t]&&p+A[t]-1,f=yv({exitProfile:`0-${t}`,addNameBaseToAttributeName:r,playoffStructureNameBase:i,finishingPositionOffset:c,playoffAttributes:d,exitProfileLimit:h,stage:ms,roundOffset:0,drawDefinition:g,sequenceLimit:l,stageSequence:p,drawSize:a,idPrefix:v,isMock:U,uuids:T,finishingPositionNaming:o,finishingPositionLimit:s,roundOffsetLimit:m});if(f.error)return Ci({result:f,stack:e});const{structures:I,links:S}=f;if(I?.length&&F.push(...I),S?.length&&x.push(...S),f.structureId&&t){const e={linkType:Cs,source:{structureId:u,roundNumber:t},target:{structureId:f.structureId,feedProfile:Ns,roundNumber:1}};x.push(e)}}if(!F.length)return Ci({result:{error:sr},info:"No structures generated",stack:e});g.structures.push(...F),g.links.push(...x);const{matchUps:L,matchUpsMap:B}=zg({inContext:!0,drawDefinition:g}),V=new Set(F.map(({structureId:t})=>t)),G=L?.filter(({structureId:t})=>V.has(t)).map(tl),j=B?.drawMatchUps?.filter(({matchUpId:t})=>G?.includes(t));if(j?.length){const t=Rf({drawDefinition:g,event:P})?.tieFormat;t&&j.forEach(e=>{const{tieMatchUps:n}=BP({matchUp:e,tieFormat:t,isMock:U});Object.assign(e,{tieMatchUps:n,matchUpType:a})})}TT({inContextDrawMatchUps:L,sourceStructureId:u,tournamentRecord:f,drawDefinition:g,matchUpsMap:B,structure:y,event:P}),wT({inContextDrawMatchUps:L,sourceStructureId:u,tournamentRecord:f,drawDefinition:g,event:P});const q=function({inContextDrawMatchUps:t,sourceStructureId:e,tournamentRecord:n,drawDefinition:r,matchUpsMap:i,params:o,stack:a}){const s=[],c=rI({inContextDrawMatchUps:t,drawDefinition:r,matchUpsMap:i}).goesToMap,{structure:u}=ol({drawDefinition:o.drawDefinition,structureId:e}),{matchUps:d}=Fg({structure:u});return d.forEach(t=>{const e=c?.loserMatchUpIds[t.matchUpId];if(e&&t.loserMatchUpId!==e){t.loserMatchUpId=e;const r={tournamentId:n?.tournamentId,eventId:o.event?.eventId,context:a,matchUp:t};s.push(r)}const r=c?.winnerMatchUpIds[t.matchUpId];if(r&&t.winnerMatchUpId!==r){t.winnerMatchUpId=r;const e={tournamentId:n?.tournamentId,eventId:o.event?.eventId,context:a,matchUp:t};s.push(e)}}),s}({inContextDrawMatchUps:L,sourceStructureId:u,tournamentRecord:f,drawDefinition:g,matchUpsMap:B,params:t,stack:e});return{structures:F,matchUpModifications:q,links:x,drawDefinition:g,...Y}}function UT({sourceStructureId:t,tournamentRecord:e,drawDefinition:n,playoffGroups:r,structure:i,idPrefix:o,isMock:a,event:s,uuids:c,stack:u}){const d=Bv({requireSequential:!1,matchUpType:s?.eventType,sourceStructureId:t,drawDefinition:n,playoffGroups:r,groupCount:1,idPrefix:o,isMock:a,uuids:c});if(d.error)return Ci({result:d,stack:u});const{structures:p,links:l}=d;if(!p?.length)return Ci({result:{error:sr},info:"No playoff structures generated",stack:u});n.structures.push(...p),l?.length&&n.links.push(...l);const{matchUps:m,matchUpsMap:f}=zg({inContext:!0,drawDefinition:n});return TT({inContextDrawMatchUps:m,sourceStructureId:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:f,structure:i,event:s}),wT({inContextDrawMatchUps:m,sourceStructureId:t,tournamentRecord:e,drawDefinition:n,event:s}),{structures:p,links:l,matchUpModifications:[],drawDefinition:n,...Y}}function PT({finishingPositionsCount:t,isLuckyDraw:e,roundNumber:n,structure:r}){let i=t;if(e&&r){const t=(r.matchUps??[]).filter(t=>t.roundNumber===n).length;if(1===t||t%2==0)i=w(i);else{const e=t-1,n=e%2==0?e:e+1;let r=1;for(;r<n;)r*=2;i=r}}return i}function TT({inContextDrawMatchUps:t,sourceStructureId:e,tournamentRecord:n,drawDefinition:r,matchUpsMap:i,structure:o,event:a}){const s=t?.filter(t=>_g({matchUp:t})&&t.structureId===e);s?.forEach(e=>{const{matchUpId:s,score:c,winningSide:u}=e,d=jg({inContextDrawMatchUps:t,drawDefinition:r,matchUpId:s}),p=yT({inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:r,matchUpsMap:i,winningSide:u,targetData:d,matchUpId:s,structure:o,matchUp:e,score:c,event:a});p.error&&console.log(p.error)})}function wT({inContextDrawMatchUps:t,sourceStructureId:e,tournamentRecord:n,drawDefinition:r,event:i}){const o=t?.filter(t=>t.matchUpStatus===Sp&&t.structureId===e);o?.forEach(e=>{const{matchUpId:o}=e,a=jg({inContextDrawMatchUps:t,drawDefinition:r,matchUpId:o}),{targetLinks:{loserTargetLink:s},targetMatchUps:{loserMatchUpDrawPositionIndex:c,loserMatchUp:u}}=a;if(s&&u){const t=s.target.structureId,e=SI({drawPosition:u.drawPositions[c],structureId:t,tournamentRecord:n,drawDefinition:r,event:i});e.error&&console.log(e.error)}})}function DT(t){const{structures:e,links:n,matchUpModifications:r,error:i}=vT(t);if(i)return{error:i};const o=t.drawDefinition;return sU({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:r,drawDefinition:o,structures:e,links:n})}function RT(t){const e=fu(t,[{_anyOf:{[hc]:!1,[Ic]:!1,[yc]:!1,[zc]:!1},[gc]:!0}]);if(e.error)return e;const n=[],r=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(r){const e=bT(t,r);if(e.error)return e;n.push(...e?.applied??[]),t.drawDefinition&&Ql({drawDefinition:t.drawDefinition,tournamentId:t.tournamentId})}else{if(!t.tournamentRecords)return{error:rt};{const e=Object.keys(t.tournamentRecords);if(!e.length)return{error:rt};for(const r of e){const e=bT(t,t.tournamentRecords[r]);if(e.error)return e;n.push(...e?.applied??[])}}}return n.length?{...Y,applied:n}:{error:De}}function bT(t,e){const n=xd(t).appliedPolicies??{};e.extensions??=[];const r=[],i=Object.keys(t.policyDefinitions);if(!i.length)return{error:Ue};for(const e of i)if(!n[e]||t.allowReplacement){const i=t.policyDefinitions[e];if(!i)continue;if(!f(i))return{error:sr};const{policyName:o,...a}=i;if(!a||!Object.keys(a).length||o&&!m(o))return{error:sr};n[e]=t.policyDefinitions[e],r.push(e)}if(r?.length){return{...$u({element:e,extension:{name:ed,value:n}}),applied:r}}return{applied:r,error:De}}function NT({tournamentRecord:t,drawDefinition:e,flightProfile:n,drawName:r,drawId:i,event:o}){if(!r||"string"!=typeof r)return Ci({result:{error:sr},context:{drawName:r}});n||(n=Tg({event:o}).flightProfile);const a=n?.flights?.find(t=>t.drawId===i);return a&&(a.drawName=r,sp({element:o,attribute:"flightProfile",name:ld,value:{...n,flights:n.flights}})),e&&(e.drawName=r,Ql({tournamentId:t?.tournamentId,drawDefinition:e})),a||e?{...Y,flight:a}:{error:st}}function MT({tournamentRecord:t,drawDefinition:e,drawUpdates:n,drawId:r,event:i}){if(!f(n))return{error:sr};const o=Tg({event:i}).flightProfile,a=n.drawName&&NT({drawName:n.drawName,tournamentRecord:t,drawDefinition:e,flightProfile:o,drawId:r,event:i});if(a?.error)return a?.error;const s=a?.flight||o?.flights?.find(t=>t.drawId===r);return s||e?(s&&sp({element:i,attribute:"flightProfile",name:ld,value:{...o,flights:o.flights}}),e&&(n.policyDefinitions&&RT({policyDefinitions:n.policyDefinitions,drawDefinition:e}),Ql({tournamentId:t?.tournamentId,drawDefinition:e})),{...Y}):{error:st}}function AT({tournamentRecord:t,removeScheduling:e,removeAssignments:n,drawDefinition:r}){if(!r)return{error:st};const i=qf(r.drawType),o=bf({drawDefinition:r}),a=t=>o?.drawMatchUps?.find(e=>e.matchUpId===t);for(const s of r.structures??[]){const{stage:c}=s;c!==ls?(CT({structure:s,isLuckyDraw:i,removeAssignments:n}),OT({removeScheduling:e,tournamentRecord:t,drawDefinition:r,getRawMatchUp:a,isLuckyDraw:i,matchUpsMap:o,structure:s,removeAssignments:n})):ET(s)}r.entries?.length&&(r.entries=r.entries.filter(t=>t.entryStage!==ls)),r.extensions=r.extensions.filter(t=>t.name!==yd&&t.name!==ud),delete r.draftState;return Ql({drawDefinition:r,structureIds:(r.structures??[]).map(({structureId:t})=>t)}),{...Y}}function ET(t){t.matchUps=[],t.positionAssignments&&(t.positionAssignments=t.positionAssignments.map(t=>(delete t.participantId,t))),t.seedAssignments=[]}function CT({structure:t,isLuckyDraw:e,removeAssignments:n}){const{positionAssignments:r,stage:i,stageSequence:o}=t,a=1===o&&[ds,us].includes(i);e&&r?function({structure:t,positionAssignments:e,isMainOrQualifyingFirst:n,removeAssignments:r}){const i=new Set((t.matchUps??[]).filter(t=>1===t.roundNumber).flatMap(t=>t.drawPositions??[]).filter(Boolean));n?(t.positionAssignments=e.filter(t=>i.has(t.drawPosition)).map(t=>(r&&(delete t.bye,delete t.participantId),t)),r&&(t.seedAssignments=[])):(t.positionAssignments=[],t.seedAssignments=[])}({structure:t,positionAssignments:r,isMainOrQualifyingFirst:a,removeAssignments:n}):!r||a&&!n||(t.positionAssignments=r.map(t=>(delete t.participantId,t)),t.seedAssignments=[])}function OT({removeScheduling:t,tournamentRecord:e,removeAssignments:n,drawDefinition:r,getRawMatchUp:i,isLuckyDraw:o,matchUpsMap:a,structure:s}){const{matchUps:c,isRoundRobin:u}=Fg({afterRecoveryTimes:!1,inContext:!0,matchUpsMap:a,structure:s});for(const a of c){const{matchUpId:s,roundNumber:c}=a,d=a.sides??[],p=i(s);p&&(delete p.extensions,delete p.notes,kT({matchUp:p,isLuckyDraw:o,removeAssignments:n,roundNumber:c,sides:d,isRoundRobin:u}),FT({matchUp:p,removeScheduling:t}),Yl({tournamentId:e?.tournamentId,context:"resetDrawDefinition",drawDefinition:r,matchUp:p}))}}function kT({matchUp:t,isLuckyDraw:e,removeAssignments:n,roundNumber:r,sides:i,isRoundRobin:o}){if(e)(n||t.matchUpStatus!==Sp)&&Object.assign(t,oT),r&&r>1&&(t.drawPositions=[]);else if(t.matchUpStatus!==Sp&&Object.assign(t,oT),r&&r>1&&t.drawPositions?.length&&!o){const e=i?.map(({drawPosition:t,participantFed:e})=>!e&&t).filter(Boolean),n=t.drawPositions.map(t=>e.includes(t)?void 0:t);t.drawPositions=n}}function FT({matchUp:t,removeScheduling:e}){e?delete t.timeItems:t.timeItems?.length&&(t.timeItems=t.timeItems.filter(t=>t.itemType&&![Zf,th,Xf,oh,nh,rh,ah,eh].includes(t.itemType)))}function xT({tournamentRecord:t}){if(!t)return{error:rt};const e={positionsNoOutcomes:[],canBePruned:[],matchPlay:[],inactive:[],drawAnalysis:{}},n={},r=t.events?.flatMap(t=>{const e=t.eventId;return n[e]=t,(t?.drawDefinitions??[]).map(t=>({drawDefinition:t,eventId:e}))}).filter(Boolean);return r.forEach(({drawDefinition:t,eventId:r})=>{let i=0,o=0,a=0;const{allStructuresLinked:s}=eP({drawDefinition:t}),c=n[r],u=(t?.structures??[]).map(e=>{const{stage:n,stageSequence:r,structureId:s}=e,u=hs[n],{inContextStructureMatchUps:d}=dI({drawDefinition:t,structureId:s,structure:e,event:c}),p=d?.filter(({winningSide:t})=>t),l=p.filter(Boolean).length||0;o+=l,a+=d.length-o;const m=Math.max(p.filter(({roundNumber:t})=>1===t).map(({roundPosition:t})=>t)),{positionAssignments:f}=cl({structure:e}),h=f?.filter(({participantId:t})=>t);i+=h?.length??0;const g=(f?.length??0)-(h?.length??0),{roundMatchUps:I,roundProfile:S,roundNumbers:y,maxMatchUpsCount:v}=Bf({matchUps:d}),U=S&&Object.keys(S).filter(t=>!S[t].inactiveRound).map(t=>Number.parseInt(t)),P=S&&Object.keys(S).filter(t=>S[t].inactiveRound).map(t=>Number.parseInt(t)),T=S&&Object.values(S).every(t=>t.inactiveRound);return{positionsAssignedCount:h?.length??0,maxWinningSideFirstRoundPosition:m,unassignedPositionsCount:g,inactiveStructure:T,maxMatchUpsCount:v,inactiveRounds:P,roundMatchUps:I,activeRounds:U,roundNumbers:y,roundProfile:S,structureId:s,stageSequence:r,orderNumber:u,stage:n}}),d=u.find(t=>2===t.orderNumber&&1===t.stageSequence),l=u.filter(({inactiveStructure:t})=>!t).length,{links:m}=Vg({structureId:d.structureId,drawDefinition:t}),f=1===p(d.activeRounds[0])&&1===d.activeRounds.length&&1===l,h=u?.every(({inactiveStructure:t})=>t),g=!m.length&&d.activeRounds.length&&(d.roundProfile[1].inactiveCount||d.inactiveRounds.length),I=t.drawId;i&&!o&&e.positionsNoOutcomes.push(I),h&&e.inactive.push(I),f&&e.matchPlay.push(I),g&&e.canBePruned.push(I);const S={matchUpsWithWinningSideCount:o,matchUpsNoOutcomeCount:a,positionsAssignedCount:i,allStructuresLinked:s,structuresData:u,inactiveDraw:h,isMatchPlay:f,drawId:I};e.drawAnalysis[I]=S}),{...Y,drawsAnalysis:e}}function _T({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:n,drawId:r}){if(!e)return{error:rt};if(!n)return{error:st};let i=[];const{drawsAnalysis:o}=xT({tournamentRecord:e});if(o.canBePruned.includes(r)){const a=o.matchPlay.includes(r),s=o.drawAnalysis[r],{structures:[c]}=al({stageSequence:1,drawDefinition:n,stage:us}),u=s.structuresData.find(({structureId:t})=>c.structureId===t),d=(c.matchUps??[]).sort((t,e)=>t.roundPosition-e.roundPosition);i=d.filter(({roundNumber:t})=>!u.inactiveRounds.includes(t));const p=i.map(tl),l=d.map(tl).filter(t=>!p.includes(t));if(a){const e=i.filter(({roundNumber:t})=>!u.inactiveRounds.includes(t)).filter(({winningSide:t})=>t),n=e.map(tl),r=p.filter(t=>!n.includes(t));l.push(...r);const o=e.flatMap(t=>t.drawPositions??[]).filter(Boolean).flat(),a=Object.assign({},...o.map((t,e)=>({[t]:e+1})));if(e.forEach(e=>{t?e.drawPositions=e.drawPositions.map(t=>a[t]):delete e.drawPositions}),t){const t=c?.positionAssignments?.filter(t=>o.includes(t.drawPosition)).map(t=>(t.drawPosition=a[t.drawPosition],t));c.positionAssignments=t}else c.positionAssignments=[];c.matchUps=e,i=e}zl({tournamentId:e?.tournamentId,matchUpIds:l,drawDefinition:n}),Ql({drawDefinition:n})}return{...Y,matchUps:i}}function LT({isPositionAction:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,loserMatchUp:i,matchUpsMap:o,structureId:a,structure:s,event:c}){if(!n)return{error:st};if(s||({structure:s}=ol({drawDefinition:n,structureId:a})),!s)return{error:Vt};a||({structureId:a}=s);const u="assignDrawPositionQualifier";fI({method:u,color:"cyan",drawPosition:r}),o??=bf({drawDefinition:n});const{positionAssignments:d}=cl({structure:s}),{activeDrawPositions:p}=dI({drawDefinition:n,structureId:a}),l=d?.find(t=>t.drawPosition===r);if(l?.qualifier)return{...Y};const m=!(!i||!o.drawMatchUps.some(t=>t.loserMatchUpId===i?.matchUpId&&II(t.matchUpStatus))),f=p?.includes(r);if(f&&!m)return{error:vt};const h=d?.find(t=>t.drawPosition===r);if(!h)return{error:Pt};const{containsQualifier:g,containsParticipant:I}=gI(h);if(g)return{...Y};const S=xd({tournamentRecord:e,drawDefinition:n,event:c}).appliedPolicies??{};return d?.forEach(t=>{t.drawPosition===r&&(t.qualifier=!0,m&&(t.participantId=void 0,console.log("oddity: invalid participantId on qualifier position cleared")))}),Xl({tournamentId:e?.tournamentId,drawDefinition:n,structure:s,event:c}),function({assignedParticipantId:t,isPositionAction:e,appliedPolicies:n,drawDefinition:r,drawPosition:i,structureId:o,stack:a}){if(e){em({appliedPolicies:n,drawDefinition:r,positionAction:{removedParticipantId:t,drawPosition:i,structureId:o,name:a}})}return Ci({result:{...Y},stack:a})}({assignedParticipantId:I,isPositionAction:t,appliedPolicies:S,drawDefinition:n,drawPosition:r,structureId:a,stack:u})}function BT({tournamentRecord:t,drawDefinition:e,participantId:n,drawPosition:r,structureId:i,qualifier:o,event:a,bye:s}){if(!e)return{error:st};if(!r)return{error:Tt};if(!i)return{error:Bt};if(s){const n=SI({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:i,event:a});if(n.error)return n}else if(o){const n=LT({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:i,event:a});if(n.error)return n}else{const o=av({participantId:n,tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:i,event:a});if(o.error)return o}return{...Y}}function VT({tournamentRecord:t,drawDefinition:e,scaleAttributes:n,preferencesCount:r=3,tierMethod:i,ascending:o,structureId:a,tierCount:s,event:c,force:u}){if(!e)return{error:st};if(void 0!==s&&s<1)return{error:sr};if(r<1)return{error:sr};if(!a){const t=e.structures?.filter(t=>t.stage===us);1===t?.length&&(a=t[0].structureId)}if(!a)return{error:Bt};const{structure:d}=ol({drawDefinition:e,structureId:a});if(!d)return{error:Bt};const p=dp({element:e,attribute:"draftState",name:ud});if(p?.status&&"COMPLETE"!==p.status&&!u)return{error:Fn};const{positionAssignments:l}=cl({drawDefinition:e,structureId:a}),m=l?.filter(t=>!t.participantId&&!t.bye&&!t.qualifier).map(t=>t.drawPosition);if(!m?.length)return{error:pr};const f=d.seedAssignments??[],h=new Set(f.map(t=>t.participantId).filter(Boolean)),g=l?.filter(t=>t.participantId).map(t=>t.participantId)??[],I=e.entries?.filter(t=>!h.has(t.participantId)&&!g.includes(t.participantId)),S=I?.map(t=>t.participantId)??[],y=i??"ENTRY_ORDER",v=n??function(t,e){if("RANKING"===t)return{scaleType:Iu};if("RATING"===t){const t=e?.category?.ratingType;return t?{scaleType:Su,scaleName:t}:void 0}return}(y,c),U=o??"RANKING"===y,P=function({participantIds:t,tierMethod:e,scaleAttributes:n,ascending:r,tournamentRecord:i}){if("ENTRY_ORDER"===e||!n||!i)return t;const o=[],a=[];for(const e of t){const{scaleItem:t}=_S({tournamentRecord:i,scaleAttributes:n,participantId:e}),r=t?.scaleValue,s=GT(r);void 0===s?a.push(e):o.push({participantId:e,scaleValue:s})}return o.sort((t,e)=>r?t.scaleValue-e.scaleValue:e.scaleValue-t.scaleValue),[...o.map(t=>t.participantId),...a]}({participantIds:S,tierMethod:y,scaleAttributes:v,ascending:U,tournamentRecord:t}),T=s??(w=P.length,D=h.size,w<4?1:D>0&&w>=24?3:2);var w,D;const R=function(t,e){const n=[],r=Math.floor(t.length/e),i=t.length%e;let o=0;for(let a=0;a<e;a++){const e=r+(a<i?1:0);n.push({participantIds:t.slice(o,o+e),resolved:!1}),o+=e}return n}(P,Math.min(T,P.length)),b={status:"SEEDS_PLACED",structureId:a,preferencesCount:r,tierMethod:y,scaleAttributes:v,ascending:U,tiers:R,preferences:{},unassignedDrawPositions:m};return sp({element:e,attribute:"draftState",name:ud,value:b}),{...Y,draftState:b,unassignedDrawPositions:m,tiers:R}}function GT(t){if(null!=t){if("number"==typeof t)return t;if("string"==typeof t){const e=Number.parseFloat(t);return Number.isNaN(e)?void 0:e}if("object"==typeof t)for(const e of Object.values(t)){if("number"==typeof e)return e;if("string"==typeof e){const t=Number.parseFloat(e);if(!Number.isNaN(t))return t}}}}function jT(t){let e=t.matchUpIds??[];const{drawDefinition:n}=t,r=t.structureId??n?.structures?.find(t=>t.matchUps?.some(({matchUpId:t})=>e.includes(t)))?.structureId??n?.structures?.[0]?.structureId;if(!r)return{error:Vt};const i=n.structures?.find(t=>t.structureId===r);if(!i)return{error:Vt};const o=i?.matchUps,a=o?.find(t=>!!t.roundPosition);if(i.structures||a||i.finishingPosition===lc)return{error:dt};const s=o.filter(({roundNumber:e})=>t.roundNumbers?.includes(e)).map(tl);return e=e.filter(t=>!s.includes(t)),t.roundNumbers&&!e.length&&(e=s),{existingMatchUps:o,matchUpIds:e,structureId:r,structure:i}}function qT(t){const e=fu(t,[{[yc]:!0},{[du]:{[Mc]:!1,roundNumbers:!1},[su]:sr,[cu]:iu}]);if(e.error)return e;const{removeIncomplete:n=!1,removeUnAssigned:r=!0,removeCompleted:i=!1,tournamentRecord:a,drawDefinition:s,event:c}=t,u=jT(t);if(u.error)return u;const{structure:d,structureId:p,existingMatchUps:l,matchUpIds:m}=u,f=[],h=l?.filter(({matchUpId:t,score:e,winningSide:o})=>{if(o&&!i)return!1;if(o||aI({score:e})){if(!o&&!n)return!1;f.push(t)}else if(!r)return!1;return m?.includes(t)})??[],g=h.map(tl),I=h.map(({tieMatchUps:t})=>t?.map(tl)).filter(Boolean).flat();if(g.length){d.matchUps=(d.matchUps??[]).filter(({matchUpId:t})=>!g.includes(t)),zl({tournamentId:a?.tournamentId,matchUpIds:[...I,...g],action:"deleteAdHocMatchUps",eventId:c?.eventId,drawDefinition:s});const t=function(t,e=1){return Array.isArray(t)&&t.every(R)?L(Math.min(...t,e),Math.max(...t)+1).filter(e=>!t.includes(e)):[]}(M(d.matchUps.map(eI("roundNumber"))));if(t.length){t.reverse();for(const e of t)d.matchUps.forEach(t=>{t.roundNumber&&t.roundNumber>e&&(t.roundNumber-=1,Yl({tournamentId:a?.tournamentId,context:["adHoc round deletion"],eventId:c?.eventId,drawDefinition:s,matchUp:t}))})}if(f.length){d.positionAssignments=M(d.matchUps.flatMap(t=>(t.sides??[]).map(t=>t.participantId)).filter(Boolean)).map(t=>({participantId:t}));const t=d?.matchUpFormat??s?.matchUpFormat??c?.matchUpFormat,e=u.existingMatchUps.some(t=>t.matchUpType===o)?{matchUpTypes:[o]}:void 0,{matchUps:n}=Fg({afterRecoveryTimes:!1,inContext:!0,matchUpFilters:e,structure:d,event:c});Hf({structure:d})&&(d.positionAssignments=M(n.flatMap(t=>(t.sides??[]).map(t=>t.participantId)).filter(Boolean)).map(t=>({participantId:t})));const r=tT({positionAssignments:d.positionAssignments,tournamentRecord:a,drawDefinition:s,matchUpFormat:t,matchUps:n,event:c});r.error&&console.log(r)}Ql({structureIds:[p],eventId:c?.eventId,drawDefinition:s})}return!g.length&&m.length?{error:br}:{...Y,deletedMatchUpsCount:[...g,...I].length}}function WT({removeCompletedMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:r,roundNumber:i,event:o}){const a=dl({tournamentRecord:e,drawDefinition:n},[Ic,yc]);if(a.error)return a;if(!i)return Ci({result:{error:Ae},info:"roundNumber required"});const s=ol({drawDefinition:n,structureId:r});if(s.error)return s;const c=s.structure;if(c?.structures)return{error:dt};return Hf({structure:c})?function({removeCompletedMatchUps:t,drawDefinition:e,tournamentId:n,roundNumber:r,structure:i,eventId:o}){const a=i?.matchUps??[],s=[],c=[];let u=!1;const p=a.reduce((t,e)=>{const n=e?.roundNumber;return n?t.includes(n)?t:t.concat(n):t},[]).sort(d);if(p.includes(r)){const d=a.filter(e=>{const n=e.roundNumber===r&&(!_p.includes(e.matchUpStatus)||t);return n&&(c.push(e.matchUpId),e.tieMatchUps&&s.push(...e.tieMatchUps.map(tl))),!n});if(c.length){zl({matchUpIds:[...s,...c],drawDefinition:e,tournamentId:n,eventId:o});d.some(t=>t.roundNumber===r)||(d.forEach(t=>{t.roundNumber>r&&(t.roundNumber-=1,Yl({drawDefinition:e,tournamentId:n,eventId:o,matchUp:t}))}),u=!0),i.matchUps=d}}return{deletedMatchUpsCount:c.length,roundRemoved:u,...Y}}({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:o.eventId,drawDefinition:n,roundNumber:i,structure:c}):(console.log("not implemented"),{...Y})}function $T(t){const{suppressNotifications:e,tournamentRecord:n,drawDefinition:r,matchUps:i,event:o}=t;if("object"!=typeof r)return{error:st};let a=t?.structureId;if(a||1!==r.structures?.length||(a=r.structures?.[0]?.structureId),"string"!=typeof a)return{error:Bt};if(!Lf(i))return{error:sr,info:nv("matchUps")};const s=r.structures?.find(t=>t.structureId===a);if(!s)return{error:Vt};const c=s?.matchUps,u=c.find(t=>!!t.roundPosition);if(s.structures||u||s.finishingPosition===lc)return{error:dt};if(j(Qg({tournamentRecord:n,inContext:!1})?.matchUps?.map(tl)??[],i.map(tl)))return{error:Sr,info:"One or more matchUpIds already present in tournamentRecord"};s.matchUps.push(...i);const d=i.map(({tieMatchUps:t})=>t).filter(Boolean).flat();return e||(Hl({tournamentId:n?.tournamentId,matchUps:[...d,...i],eventId:o?.eventId,drawDefinition:r}),Ql({drawDefinition:r,structureIds:[a]})),{...Y}}function HT({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:r,subOrder:i,event:o}){if(!e)return{error:st};if(!r)return{error:Bt};if(!n)return{error:Tt};const{structure:s}=ol({drawDefinition:e,structureId:r});if(!s)return{error:Vt};let c=s;s.structures&&s.structureType===Ds&&(c=s.structures?.find(t=>t.positionAssignments?.find(t=>t.drawPosition===n)));const u=c?.positionAssignments,d=u?.find(t=>t.drawPosition===n);d&&sp({element:d,attribute:"subOrder",name:Dd,value:i});const p=(o?.eventType===a||e.matchUpType===a||(o?.tieFormat??e?.tieFormat??s?.tieFormat))&&{matchUpTypes:[a]},{matchUps:l}=Fg({structure:c,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:p,event:o});return tT({positionAssignments:u,tournamentRecord:t,drawDefinition:e,matchUpFormat:s?.matchUpFormat??e.matchUpFormat,matchUps:l,event:o}),Ql({drawDefinition:e,structureIds:[r]}),{...Y}}var zT={__proto__:null,adHocPositionSwap:WP,addAdHocMatchUps:$T,addDrawDefinitionTimeItem:sP,addLinkedConsolationStructure:dU,addPlayoffStructures:DT,addQualifyingStructure:jP,addVoluntaryConsolationStructure:My,alternateDrawPositionAssignment:lU,assignDrawPosition:BT,assignDrawPositionBye:SI,attachConsolationStructures:aU,attachPlayoffStructures:sU,attachQualifyingStructure:oP,attachStructures:cU,automatedPlayoffPositioning:XU,automatedPositioning:JU,deleteAdHocMatchUps:qT,initializeDraft:VT,luckyDrawAdvancement:KP,luckyLoserDrawPositionAssignment:cv,modifyDrawDefinition:MT,modifyDrawName:NT,modifySeedAssignment:ZU,pruneDrawDefinition:_T,qualifierDrawPositionAssignment:SU,qualifierProgression:wU,remapDrawDefinitionMatchUpIds:mU,removeDrawPositionAssignment:wy,removeRoundMatchUps:WT,removeSeededParticipant:_P,removeStructure:lP,renameStructures:aP,resetDrawDefinition:AT,resetQualifyingStructure:pP,resetVoluntaryConsolationStructure:Zl,resolveDraftPositions:uP,seedWithdrawalCascade:qP,setDrawParticipantRepresentativeIds:nl,setDrawPositionPreferences:pU,setPositionAssignments:lv,setStructureOrder:tP,setSubOrder:HT,shiftAdHocRounds:pv,swapAdHocRounds:mv,swapDrawPositionAssignments:FP,updateTeamLineUp:iv,withdrawParticipantAtDrawPosition:Dy};function YT({excludedMatchUpStatuses:t=[],includeEventParticipants:e,includeQualifyingStage:n,finishingRoundLimit:r,policyDefinitions:i,roundNumberLimit:o,tournamentRecord:a,drawDefinition:s,matchUpsLimit:c,requirePlay:u,requireLoss:d,allEntries:p,winsLimit:l,event:m}){if(!s)return{error:st};const f=[us,ms];n&&f.push(ds);const h=function({includeEventParticipants:t,tournamentRecord:e,drawDefinition:n,stages:r,event:i}){const o=i?.eventType?{matchUpTypes:[i.eventType]}:void 0,a=n?.matchUpType?{matchUpTypes:[n.matchUpType]}:void 0;if(t&&i)return Kg({contextFilters:{stages:r},matchUpFilters:o,tournamentRecord:e,inContext:!0,event:i})?.matchUps??[];return Zg({contextFilters:{stages:r},matchUpFilters:a,tournamentRecord:e,inContext:!0,drawDefinition:n})?.matchUps??[]}({includeEventParticipants:e,tournamentRecord:a,drawDefinition:s,stages:f,event:m}),g=Pf({stage:ls,drawDefinition:s}),I=new Set(g.map(({participantId:t})=>t)),S=function({excludedMatchUpStatuses:t,includeEventParticipants:e,finishingRoundLimit:n,policyDefinitions:r,roundNumberLimit:i,tournamentRecord:o,drawDefinition:a,matchUpsLimit:s,requirePlay:c,requireLoss:u,allEntries:d,winsLimit:p,event:l}){const m=r??_d({policyTypes:[wu],tournamentRecord:o,drawDefinition:a,event:l}).policyDefinitions,f=m?.[wu],h=t.length&&t||(f?.excludedMatchUpStatuses??[]);return{includeEventParticipants:e??f?.includeEventParticipants,finishingRoundLimit:n??f?.finishingRoundLimit,excludedMatchUpStatuses:h,roundNumberLimit:i??f?.roundNumberLimit,matchUpsLimit:s??f?.matchUpsLimit,requirePlay:c??f?.requirePlay??!0,requireLoss:u??f?.requireLoss??!0,allEntries:d??f?.allEntries,winsLimit:p??f?.winsLimit}}({excludedMatchUpStatuses:t,includeEventParticipants:e,finishingRoundLimit:r,policyDefinitions:i,roundNumberLimit:o,tournamentRecord:a,drawDefinition:s,matchUpsLimit:c,requirePlay:u,requireLoss:d,allEntries:p,winsLimit:l,event:m}),{participantMatchUps:y,losingParticipants:v,matchUpParticipants:U,participantWins:P}=function({excludedMatchUpStatuses:t,finishingRoundLimit:e,roundNumberLimit:n,requirePlay:r,matchUps:i}){const o={},a={},s={},c={},u=new Set(t);for(const t of i)KT({matchUp:t,requirePlay:r,finishingRoundLimit:e,roundNumberLimit:n})&&QT({matchUp:t,requirePlay:r,excludedSet:u,participantMatchUps:o,losingParticipants:a,matchUpParticipants:s,participantWins:c});return{participantMatchUps:o,losingParticipants:a,matchUpParticipants:s,participantWins:c}}({excludedMatchUpStatuses:S.excludedMatchUpStatuses,finishingRoundLimit:S.finishingRoundLimit,roundNumberLimit:S.roundNumberLimit,requirePlay:S.requirePlay,matchUps:h}),T=Object.keys(v),w=function({includeEventParticipants:t,matchUpParticipants:e,losingParticipants:n,tournamentRecord:r,drawDefinition:i,requireLoss:o,requirePlay:a,allEntries:s,event:c}){const u=r?.participants&&!a&&!o&&s;let d;d=t&&c?c.entries:i.entries;const p=new Set([ff,pf]),l=u?(d??[]).filter(t=>!p.has(t.entryStatus)).map(({participantId:t})=>t):[];if(u){const t=new Set(l);return(r?.participants??[]).filter(({participantId:e})=>t.has(e))}if(o)return Object.values(n);return Object.values(e)}({includeEventParticipants:S.includeEventParticipants,requireLoss:S.requireLoss,requirePlay:S.requirePlay,allEntries:S.allEntries,matchUpParticipants:U,losingParticipants:v,tournamentRecord:a,drawDefinition:s,event:m}),D=new Set(T),R=w.filter(t=>function({voluntaryConsolationEntryIds:t,losingParticipantIdSet:e,participantMatchUps:n,participantWins:r,resolvedPolicy:i,participant:o}){const a=o.participantId,s=!i.requireLoss||e.has(a),c=!i.requirePlay||(n[a]||0)>=0,u=!i.winsLimit||(r[a]||0)<=i.winsLimit,d=!i.matchUpsLimit||n[a]<=i.matchUpsLimit,p=!t.has(a);return s&&c&&u&&d&&p}({voluntaryConsolationEntryIds:I,losingParticipantIdSet:D,participantMatchUps:y,participantWins:P,resolvedPolicy:S,participant:t})).map(t=>({...t,individualParticipants:t.individualParticipantIds?.map(t=>a?.participants?.find(e=>e.participantId===t))}));return{eligibleParticipants:R,losingParticipantIds:T,...Y}}function KT({matchUp:t,requirePlay:e,finishingRoundLimit:n,roundNumberLimit:r}){return!(e&&t.winningSide&&![1,2].includes(t.winningSide)&&t.matchUpStatus!==wp)&&(!(t.finishingRound&&n&&t.finishingRound>=n)&&!(t.finishingRound&&r&&t.finishingRound<=r))}function QT({matchUp:t,requirePlay:e,excludedSet:n,participantMatchUps:r,losingParticipants:i,matchUpParticipants:o,participantWins:a}){const s=t.sides?.find(({sideNumber:e})=>t.winningSide&&e===3-t.winningSide),c=t.sides?.find(({sideNumber:e})=>t.winningSide&&e===t.winningSide);if(t.sides?.forEach(a=>{const s=a?.participant?.participantId;s&&(o[s]=a.participant,t.matchUpStatus!==wp||e||(i[s]=a.participant,r[s]||(r[s]=0),t.matchUpStatus&&n.has(t.matchUpStatus)||(r[s]+=1)))}),s?.participant){const e=s.participant.participantId;i[e]=s.participant,r[e]||(r[e]=0),t.matchUpStatus&&!n.has(t.matchUpStatus)&&(r[e]+=1)}if(c?.participant){const e=c.participant.participantId;a[e]||(a[e]=0),a[e]+=1,r[e]||(r[e]=0),t.matchUpStatus&&!n.has(t.matchUpStatus)&&(r[e]+=1)}}function JT(t){const e=fu(t,[{drawDefinition:!0}]);if(e.error)return e;const{drawDefinition:n,roundNumber:r}=t,i=t.structureId??(1===n.structures?.length&&n.structures?.[0]?.structureId);if("string"!=typeof i)return{error:Bt};const o=n.structures?.find(t=>t.structureId===i);if(!o)return{error:Vt};let a;const s=o.matchUps??[],c=s?.reduce((t,e)=>(e.roundPosition&&(a=!0),(e?.roundNumber||0)>t?e.roundNumber:t),0);if(o.structures||a||o.finishingPosition===lc)return{error:dt};const u=n?.entries?.filter(t=>{const e=t.entryStatus;return Sf.includes(e)})??[],d=Math.floor(u?.length/2)||1,p=r??c??1,l=d-(o.matchUps?.filter(t=>t.roundNumber===p)?.length??0),m=l>0?l:0;return{...Y,availableMatchUpsCount:m,lastRoundNumber:c,roundMatchUpsCount:d}}function XT({drawDefinition:t}){const e=td({name:"participantRepresentatives",element:t});if(e.error)return e;return{representativeParticipantIds:e.extension?.value??[]}}function ZT(t){const e=Math.min(1-1e-9,Math.max(1e-9,t));return Math.log(e/(1-e))}function tw(t,e){const n=ZT(t.probability)-ZT(e.probability),r=e.delta-t.delta,i=0===r?0:n/r;return{k:i,x0:0===i?t.delta:t.delta+ZT(t.probability)/i}}function ew({k:t,x0:e},n){return 0===t?.5:1/(1+Math.exp(t*(n-e)))}function nw(t,e){const[n,r]=e.competitiveAnchors,[i,o]=e.decisiveAnchors;if(!(n&&r&&i&&o))return{competitive:0,decisive:0,routine:1};const a=ew(tw(n,r),t),s=1-ew(tw({delta:i.delta,probability:1-i.probability},{delta:o.delta,probability:1-o.probability}),t),c=Math.min(1,Math.max(0,a)),u=Math.min(1,Math.max(0,s)),d=1-c-u,p=Math.max(0,d);if(d<0){const t=c+u;return{competitive:c/t,decisive:u/t,routine:0}}return{competitive:c,decisive:u,routine:p}}const rw=new Set([Ls,Bs,Vs,Gs,Ys,Hs,xs,js,qs]),iw=new Set([ic,rc,oc]),ow=new Set([nc]),aw=Hm[Du].predictionModel;function sw(t){const e=[];for(let n=0;n<t.length;n++)for(let r=n+1;r<t.length;r++)e.push([t[n],t[r]]);return e}function cw(t,e,n){return"BALANCED_BRACKET"===e?function(t){const e=[],n=Math.floor(t.length/2);for(let r=0;r<n;r++)e.push([t[r],t[t.length-1-r]]);return e}(t):"ROUND_ROBIN"===e?function(t,e){if(!e||e<2)return sw(t);const n=[];for(let r=0;r<t.length;r+=e){const i=t.slice(r,r+e);i.length>=2&&n.push(...sw(i))}return n}(t,n):function(t){const e=[],n=t.length-t.length%2;for(let r=0;r<n;r+=2)e.push([t[r],t[r+1]]);return e}(t)}function uw({tournamentRecord:t,projectionMode:e,predictionModel:n,groupSize:r,ratings:i,drawType:o}){if(!Array.isArray(i)||i.length<2)return{competitive:0,decisive:0,routine:0,error:sr};const a=e??(o?function(t){return rw.has(t)?"BALANCED_BRACKET":iw.has(t)?"ROUND_ROBIN":ow.has(t)?"MIN_DELTA":void 0}(o):void 0);if(!a)return{competitive:0,decisive:0,routine:0,error:sr};const s=function(t,e){if(t)return t;if(e){const{policy:t}=Qm({policyType:Du,tournamentRecord:e});if(t?.predictionModel)return t.predictionModel}return aw}(n,t),c=cw([...i].sort((t,e)=>e-t),a,r),u=c.map(([t,e])=>nw(Math.abs(t-e),s));return{...function(t){if(0===t.length)return{competitive:0,decisive:0,routine:0};const e=t.reduce((t,e)=>(t.competitive+=e.competitive,t.decisive+=e.decisive,t.routine+=e.routine,t),{competitive:0,decisive:0,routine:0}),n=t.length;return{competitive:e.competitive/n,decisive:e.decisive/n,routine:e.routine/n}}(u),perMatchUpPredictions:u,projectionMode:a,projectedPairs:c,expectedMatchCount:c.length}}function dw({tournamentRecord:t,drawDefinition:e,stage:n=us,structureId:r,structure:i}){if(!t)return{error:rt};if(!i&&!e)return{error:st};if(i||r||1!==e?.structures?.filter(t=>t.stage===n).length||(i=e.structures.find(t=>t.stage===n)),!i&&!r)return{error:Bt};const{error:o,positionAssignments:a}=cl({drawDefinition:e,structureId:r,structure:i});return{positionAssignments:a??[],structureId:i?.structureId,error:o}}function pw({dates:t=[],disabledValue:e,extension:n}){const r=void 0!==e?e:n?.value;if(void 0===r)return!1;if("boolean"==typeof r&&r)return!0;if(!t.length)return!1;const i=f(r)?r?.dates:void 0;if(Array.isArray(i)){if(!i?.length)return!1;return!!i.filter(e=>!t.length||t.includes(e)).length}}function lw({inContextCourt:t,venue:e}){const{defaultStartTime:n,defaultEndTime:r,dateAvailability:i}=e;if(!(n||r||i?.length))return;const o=t.dateAvailability;o?.length?t.dateAvailability=o.map(t=>{const e=function({date:t,venueDateAvailability:e,defaultStartTime:n,defaultEndTime:r}){if(e?.length){if(t){const n=e.find(e=>e.date===t);if(n)return n}const n=e.find(t=>!t.date);if(n)return n}if(n||r)return{startTime:n,endTime:r};return}({date:t.date,venueDateAvailability:i,defaultStartTime:n,defaultEndTime:r});if(!e)return t;const o=(a=t.startTime,s=e.startTime,a?s?a>s?a:s:a:s);var a,s;const c=function(t,e){return t?e?t<e?t:e:t:e}(t.endTime,e.endTime),u=function(t,e){const n=[];t?.length&&n.push(...t);e?.length&&n.push(...e);return n}(t.bookings,e.bookings);return{...t,startTime:o,endTime:c,...u.length?{bookings:u}:{}}}):i?.length?t.dateAvailability=i.map(t=>({...t})):n&&r&&(t.dateAvailability=[{startTime:n,endTime:r}])}function mw({convertExtensions:t,ignoreDisabled:e,venue:n,court:r}){const i={...ca(r,t,!0),venueId:n.venueId},o=dp({element:r,attribute:"disabled",name:od});if(e&&void 0!==o){const t=f(o)?o?.dates:void 0,e=!0===o?[]:i.dateAvailability.map(e=>{const n=e.date;if(n&&!t.includes(n))return e}).filter(Boolean);i.dateAvailability=e}return lw({inContextCourt:i,venue:n}),{inContextCourt:i}}function fw(t,e,n){if(e.length&&!e.includes(t.venueId))return!1;if(n){if(dp({element:t,attribute:"disabled",name:od}))return!1}return!0}function hw({venue:t,convertExtensions:e,ignoreDisabled:n,dates:r,uniqueVenueIds:i,venues:o,uniqueCourtIds:a,courts:s}){i.includes(t.venueId)||(o.push(ca(t,e,!0)),i.push(t.venueId));for(const i of t.courts??[])if(!a.includes(i.courtId)){if(n){if(pw({disabledValue:dp({element:i,attribute:"disabled",name:od}),dates:r}))continue}const{inContextCourt:o}=mw({convertExtensions:e,ignoreDisabled:n,venue:t,court:i});s.push(o),a.push(i.courtId)}}function gw(t){const{convertExtensions:e,ignoreDisabled:n,venueIds:r=[],dates:i}=t,o=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},a=[],s=[],c=[],u=[];return Object.keys(o).filter(e=>!t.tournamentId||e===t.tournamentId).forEach(t=>{const d=o[t];for(const t of d.venues??[])fw(t,r,!!n)&&hw({venue:t,convertExtensions:e,ignoreDisabled:n,dates:i,uniqueVenueIds:a,venues:u,uniqueCourtIds:s,courts:c})}),{courts:c,venues:u,...Y}}function Iw({tournamentRecords:t,requireCourts:e,dates:n}){if("object"!=typeof t||!Object.keys(t).length)return{error:nt};return Object.keys(t).reduce((r,i)=>{const o=t[i],{venues:a}=function({convertExtensions:t,tournamentRecord:e,ignoreDisabled:n,dates:r}){if(!e)return{error:nt};const i=ca(e.venues??[],t).filter(t=>n?!dp({element:t,attribute:"disabled",name:od})&&t:t).filter(Boolean),o=i.reduce((e,i)=>{const o=(i?.courts??[]).filter(t=>n||r?.length?pw({disabledValue:dp({element:t,attribute:"disabled",name:od}),dates:r}):t).filter(Boolean).map(e=>{const{inContextCourt:r}=mw({convertExtensions:t,ignoreDisabled:n,venue:i,court:e});return r});return o.length?e.concat(o):e},[]);return{venues:i,courts:o}}({tournamentRecord:o,dates:n});return a?.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 Sw({event:t}){const{surfaceCategory:e,onlineResources:n,matchUpFormat:r,discipline:i,eventLevel:o,eventName:a,eventType:s,startDate:c,category:u,ballType:d,eventId:p,endDate:l,gender:m,notes:f}=t,h=t.entries?.length??0;return{eventInfo:{drawDefinitionCount:t.drawDefinitions?.length,entriesCount:h,surfaceCategory:e,onlineResources:n,matchUpFormat:r,discipline:i,eventLevel:o,eventName:a,eventType:s,ballType:d,startDate:c,category:u,endDate:l,eventId:p,gender:m,notes:f}}}const yw="tournamentImage",vw={TOURNAMENT_IMAGE_RESOURCE_NAME:yw,IN_PROGRESS:"IN_PROGRESS",ABANDONED:"ABANDONED",CANCELLED:"CANCELLED",COMPLETED:"COMPLETED",ACTIVE:"ACTIVE"},Uw={[Eu]:{policyName:"Staff Privacy Policy",participant:{contacts:!1,individualParticipants:!1,individualParticipantIds:!1,onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantRoleResponsibilities:!0,participantStatus:!0,penalties:!1,representing:!0,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}}}};function Pw(t){const{tournamentRecord:e,withMatchUpStats:n,withStructureDetails:r,withVenueData:i}=t??{};if(!e)return{error:rt};const o=(({tournamentId:t,tournamentRank:e,tournamentStatus:n,formalName:r,tournamentName:i,promotionalName:o,onlineResources:a,localTimeZone:s,activeDates:c,startDate:u,endDate:d,hostCountryCode:p,venues:l,notes:m,registrationProfile:f,updatedAt:h})=>({tournamentId:t,tournamentRank:e,tournamentStatus:n,formalName:r,tournamentName:i,promotionalName:o,onlineResources:a,localTimeZone:s,activeDates:c,startDate:u,endDate:d,hostCountryCode:p,venues:l,notes:m,registrationProfile:f,updatedAt:h}))(e),a=e.venues?.find(t=>t.isPrimary);a?.addresses?.length&&(o.tournamentAddress=a.addresses[0]);const s=xS({participantFilters:{participantRoles:[ay,dy,cy,uy,ly]},policyDefinitions:Uw,tournamentRecord:e}),c=s?.participants??[];c&&(o.tournamentContacts=c);const u=e?.onlineResources?.find(t=>t.name===yw&&"URL"===t.resourceType)?.identifier;u&&(o.imageUrl=u);const d=mS({tournamentRecord:e})?.publishState,p=d?.tournament?.status?.publishedEventIds??[],l=[];for(const n of e.events??[])if(!t?.usePublishState||p.includes(n.eventId)){const t=Sw({event:n}).eventInfo;t&&l.push(t)}o.timeItemValues=eU({element:e}),o.publishState=d?.tournament,o.eventInfo=l;const m=[],f=[];if(n||r)for(const t of e.events??[])for(const e of t.drawDefinitions??[])for(const n of e.structures??[])f.push(...n.matchUps??[]),m.push(Ei({eventId:t.eventId,eventName:t.eventName,eventType:t.eventType,drawId:e.drawId,drawName:e.drawName,drawType:e.drawType,structureId:n.structureId,structureName:n.structureName,stage:n.stage,stageSequence:n.stageSequence,positionAssignments:n.positionAssignments,seedAssignments:n.seedAssignments,matchUpFormat:n.matchUpFormat}));if(r&&(o.structures=m),n){const t=e.participants?.filter(t=>t.participantType===gm).length??0,n=e.participants?.filter(t=>t.participantType===ym).length??0,r=e.events?.length??0,i=f?.filter(t=>t.matchUpStatus!==Sp),a=i?.length,s=i?.filter(t=>_p.includes(t.matchUpStatus)||t.winningSide)?.length,c=i?.filter(t=>ng({matchUp:t})?.scheduledDate||eg({matchUp:t})?.scheduledTime)?.length,u=a>0?Math.round(s/a*100):0;o.matchUpStats={total:a,completed:s,scheduled:c,percentComplete:u},o.individualParticipantCount=t,o.teamParticipantCount=n,o.eventCount=r}if(i){const{venues:t}=gw({tournamentRecord:e});o.venues=t??[]}return{tournamentInfo:ca(Ei(o),!1,!0),...Y}}function Tw({publishStatus:t,drawId:e}){return t?.drawDetails?Cg(t.drawDetails?.[e]?.publishingDetail):!t?.drawIds||t.drawIds.includes(e)}const ww="PUBLIC",Dw={PUBLIC_DISPLAY:ww,ADMIN_DISPLAY:"ADMIN"};function Rw(t){const{tournamentParticipants:e=[],includePositionAssignments:n,policyDefinitions:r,tournamentRecord:i,inContext:a=!0,usePublishState:s,status:c=Th,pressureRating:u,refreshResults:d,contextProfile:p,drawDefinition:l,noDeepCopy:m,sortConfig:f,context:h,event:g}=t;if(!l)return{error:st};const{matchUpFormat:I,updatedAt:S,drawType:y,drawName:v,drawId:U}=l,P={matchUpFormat:I,updatedAt:S,drawName:v,drawType:y,drawId:U};P.display=td({element:l,name:cd}).extension?.value;const T={};let w,D;const{allStructuresLinked:R,sourceStructureIds:b,hasDrawFeedProfile:N,structureGroups:M}=eP({drawDefinition:l});if(!R)return{error:Wt};const A=t?.eventPublishState??mS({event:g}).publishState,E=t?.publishStatus??pS({event:g,status:c}),C=A?.status?.drawDetails?.[l.drawId],O=!!A?.status?.published,k=C?.structureDetails;let F=!1,x=!1;const _=M.map(c=>{const m={},I=c.map(t=>{const{structure:e}=ol({drawDefinition:l,structureId:t}),{seedAssignments:n}=Tf({drawDefinition:l,structure:e});return e?.stage===us&&1===e.stageSequence&&(w=n),e?.stage===ds&&(T[e.stageSequence??0]=n),e}).sort((t,e)=>rl(t,e,f)).map(n=>{if(!n)return;const c=n?.structureId;let f=[];n.stage&&[us,ps,ms].includes(n.stage)&&(f=w),n?.stage===ds&&(f=T[n.stageSequence??0]);const{matchUps:I,roundMatchUps:S,roundProfile:y}=Fg({seedAssignments:n?.seedAssignments?.length?void 0:f,context:{drawId:P.drawId,...h},hydrateParticipants:t.hydrateParticipants,participantsProfile:t.participantsProfile,tournamentParticipants:e,policyDefinitions:r,tournamentRecord:i,usePublishState:s,publishStatus:E,contextProfile:p,drawDefinition:l,inContext:a,structure:n,event:g}),{positionAssignments:v}=cl({structure:n});let U=v?.filter(eI(Pc)).map(t=>{const e=dp({element:t,attribute:"tally",name:Rd}),{drawPosition:n,participantId:r}=t;return x=!0,{participantResult:e,participantId:r,drawPosition:n}});if(I.length&&(!U?.length&&t.allParticipantResults||d&&!n.structures)){const{subOrderMap:t}=cS({positionAssignments:v}),e=I.some(t=>t.matchUpType===o)?I.filter(t=>t.matchUpType===o):I,i=aS({matchUpFormat:n.matchUpFormat,matchUps:e,policyDefinitions:r,pressureRating:u,subOrderMap:t});D=i?.report,U=v?.filter(eI(Pc)).map(t=>{const{drawPosition:e,participantId:n}=t;return x=!0,{participantResult:n&&i?.participantResults?.[n],participantId:n,drawPosition:e}})}const R=n?{stageSequence:n.stageSequence,structureName:n.structureName,structureType:n.structureType,finishingPosition:n.finishingPosition,matchUpFormat:n.matchUpFormat,stage:n.stage}:{},M=td({element:n,name:cd}).extension?.value;R.display=M?.[ww]??M,R.sourceStructureIds=b[c],R.hasDrawFeedProfile=N[c],R.positionAssignments=v,R.structureActive=I.reduce((t,e)=>{const n=[wp,Tp,Dp,vp,yp,Pp,Np,Ep].includes(e.matchUpStatus);return t||n||!!e.winningSide||!!e.score?.scoreStringSide1},!1);const A=I.every(t=>[..._p,Sp].includes(t.matchUpStatus));return R.structureCompleted=A,m[c]=A,R.structureActive&&(F=!0),{...R,participantResults:U,seedAssignments:f,roundMatchUps:S,roundProfile:y,structureId:c,report:D}});return I.forEach(t=>{n||delete t.positionAssignments,t.sourceStructuresComplete=t.sourceStructureIds?.every(t=>m[t])}),I}),L=_.flat().filter(t=>!s||Cg(k?.[t?.structureId])||!0);return P.drawActive=F,P.participantPlacements=x,P.drawGenerated=L?.reduce((t,e)=>t||!!e?.roundMatchUps,!1),P.drawCompleted=L?.reduce((t,e)=>t&&e.structureCompleted,!0),P.drawPublished=s?O&&Tw({publishStatus:E,drawId:P.drawId}):void 0,{structures:!s||P.drawPublished?m&&L||ca(L,!1,!0):void 0,drawInfo:m?P:ca(P,!1,!0),...Y}}function bw(t){const{includePositionAssignments:e,participantsProfile:n,policyDefinitions:r,usePublishState:i,status:o=Th,contextProfile:a,sortConfig:s}=t,c=fu(t,[{tournamentRecord:!0},{[uu]:{event:!1,eventId:!1}}]);if(c.error)return c;const u=ca(t.tournamentRecord,!1,!0),d=null==t.event?wg({tournamentRecord:u,eventId:t.eventId}).event:void 0,p=t.event?ca(t.event,!1,!0):d&&ca(d,!1,!0)||void 0;if(!p)return{error:zt};const{eventId:l}=p,{tournamentId:m,endDate:f}=u,h=pS({event:p,status:o}),g=mS({event:p}).publishState??{},I=!!g?.status?.published,{participants:S}=xS({participantFilters:t.participantFilters,withEvents:!1,withDraws:!1,policyDefinitions:r,...n,tournamentRecord:u}),y=p.drawDefinitions??[],v=!i||I?y.filter(({drawId:t})=>!i||Tw({publishStatus:h,drawId:t})).map(n=>(({drawInfo:t,structures:e})=>({...t,structures:e}))(Rw({allParticipantResults:t.allParticipantResults,hydrateParticipants:t.hydrateParticipants,context:{eventId:l,tournamentId:m,endDate:f},pressureRating:t.pressureRating,refreshResults:t.refreshResults,includePositionAssignments:e,tournamentParticipants:S,eventPublishState:g,noDeepCopy:!0,policyDefinitions:r,tournamentRecord:u,usePublishState:i,contextProfile:a,drawDefinition:n,publishStatus:h,sortConfig:s,event:p}))).map(({structures:t,...e})=>{const n=t?.filter(({stage:t,structureId:n})=>(({structureId:t,drawId:e})=>{if(!i)return!0;const n=h?.drawDetails?.[e]?.structureDetails;return!n||!Object.keys(n).length||Cg(n[t])})({structureId:n,drawId:e.drawId})&&(({stage:t,drawId:e})=>{if(!i)return!0;const n=h?.drawDetails?.[e]?.stageDetails;return!n||!Object.keys(n).length||Cg(n[t])})({stage:t,drawId:e.drawId})).map(t=>(({drawId:t,drawType:e,structure:n})=>{if(!i)return n;if(!KS(e))return n;const r=h?.drawDetails?.[t]?.structureDetails?.[n.structureId]?.roundLimit;if(R(r)){const t=L(1,r+1),e={},i={};for(const r of t)n.roundMatchUps[r]&&(e[r]=n.roundMatchUps[r],i[r]=n.roundProfile[r]);n.roundMatchUps=e,n.roundProfile=i}return n})({drawId:e.drawId,drawType:e.drawType,structure:t}));return{...e,structures:n}}).filter(t=>t.structures?.length):void 0,U=(Array.isArray(u.venues)?u.venues:[]).map(t=>{const{venueData:e}=Pg({venueId:t.venueId,tournamentRecord:u});return{...e}}),P=(({eventId:t,eventName:e,eventType:n,eventLevel:r,surfaceCategory:i,matchUpFormat:o,category:a,gender:s,startDate:c,endDate:u,ballType:d,discipline:p})=>({eventId:t,eventName:e,eventType:n,eventLevel:r,surfaceCategory:i,matchUpFormat:o,category:a,gender:s,startDate:c,endDate:u,ballType:d,discipline:p}))(p);P.display=td({element:p,name:cd}).extension?.value;const{tournamentInfo:T}=Pw({tournamentRecord:u}),w={tournamentInfo:T,venuesData:U,eventInfo:P,drawsData:v};return w.eventInfo.publishState=g,w.eventInfo.published=g?.status?.published,{...Y,eventData:w,participants:S}}function Nw({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:n,event:r}){if(!n)return{error:st};const{participantIds:i,participantIdMatchUps:o}=function({tournamentParticipants:t,drawDefinition:e,event:n}){if(!e)return{error:st};const r=ca(zg({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)),[])),o=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:o}}({tournamentParticipants:e?.participants,drawDefinition:n}),a=Object.values(o).some(t=>t.some(t=>t.containerStructureId)),s=a&&bw({tournamentRecord:e,event:r}),c=s?.eventData?.drawsData?.find(t=>t.drawId===n.drawId)?.structures,u=n?.structures?.find(t=>t.stage===us&&1===t.stageSequence),d=u?.structureType===Ds&&u.structures,p=a?dw({tournamentRecord:e,drawDefinition:n,structureId:u?.structureId})?.positionAssignments:void 0,l=p?.length||0,m=i?.map(e=>{const r=o[e].filter(t=>[vp,Sp].includes(t.matchUpStatus)||t.winningSide),i=r.map(r=>{const i=r.sides.find(t=>t.bye),o=r.sides.find(t=>t.participantId===e).sideNumber;if(r.containerStructureId){const t=function({containedStructures:t,drawPositionsCount:e,drawDataStructures:n,drawDefinition:r,participantId:i,matchUp:o}){const a=t?.find(t=>t.structureId===o.structureId),s=a?.positionAssignments?.length,c=n.find(t=>t.structureId===o.containerStructureId)?.participantResults?.find(t=>t.participantId===i)?.participantResult,{ties:u,groupOrder:d,provisionalOrder:p}=c??{},l=t?.length,m=r.structure?.find(t=>t.stage===ms);$r()&&console.log({drawPositionsCount:e,provisionalOrder:p,bracketsCount:l,bracketSize:s,groupOrder:d,ties:u});if(e===s&&d)return[d,d];if(l>1&&d&&!m)return[1,l];if(l>1&&d&&m){const t=r.links?.find(t=>t.source.structureId===o.containerStructureId)?.source?.finishingPositions,n=t.length*l;if(d in t)return[1,n];return[n+1,e-(s-d)*l]}return}({containedStructures:d,drawPositionsCount:l,drawDataStructures:c,drawDefinition:n,participantId:e,matchUp:r});if(t)return t}return(r.winningSide||t&&i&&o)===o?r.finishingPositionRange.winner:r.finishingPositionRange.loser}),a=t=>Math.abs(t[0]-t[1]),s=i.reduce((t,e)=>t&&a(t)<a(e)?t:e,void 0);return{[e]:{finishingPositionRanges:i,finishingPositionRange:s,relevantMatchUps:r}}})??[];return Object.assign({},...m)}function Mw({tournamentRecords:t,tournamentRecord:e,tournamentId:n,drawId:r}){if(!e&&!t)return{error:rt};if(!r)return{error:bt};if(!e&&t){if("string"!=typeof n&&!(n=hT({tournamentRecords:t,drawId:r})))return{error:ot};if(!(e=t[n]))return{error:rt}}const i=e&&wg({tournamentRecord:e,drawId:r});return i?.drawDefinition?{drawDefinition:i.drawDefinition,event:i.event,tournamentRecord:e,...Y}:Ci({result:{error:ut},stack:"findDrawDefinition"})}function Aw(t){const{drawDefinition:e,error:n}=Mw(t);return n?{error:n}:{drawDefinition:ca(e)}}function Ew({tournamentParticipants:t,returnParticipants:e,drawPosition:n,participant:r,drawId:i,event:o}){const a=o?.entries?.filter(({entryStatus:t})=>[pf,lf].includes(t)).map(({participantId:t})=>t)??[];if(a.length){const o=r.individualParticipantIds,s=e?t.filter(({participantId:t})=>a.includes(t)):void 0,c=e?t.filter(({participantId:t})=>o.includes(t)):void 0;return{validModifyAssignedPairAction:Ei({payload:{participantId:r.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:n,drawId:i},method:"modifyPairAssignment",availableIndividualParticipantIds:a,availableIndividualParticipants:s,existingIndividualParticipantIds:o,existingIndividualParticipants:c,type:vP},!1,!1,!0)}}return{}}function Cw(t){const{inContextDrawMatchUps:e,targetData:n,drawDefinition:r,relevantLink:i}=t;if(i?.linkCondition===Os&&n?.matchUp?.matchUpStatus===Sp)return!1;const{targetMatchUps:{loserMatchUp:o,winnerMatchUp:a},targetLinks:s}=n,c=o&&jg({matchUpId:o.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),u=c?.targetMatchUps?.loserMatchUp,d=c?.targetMatchUps?.loserMatchUpDrawPositionIndex,p=u?.sides[d]?.participant,l=II(o?.matchUpStatus),m=l&&!p,f=o?.sides?.filter(t=>t?.participant).length??0,h=o?.winningSide&&l&&1===f,g=a?.drawPositions?.filter(Boolean).length||0;if(!h&&(o?.winningSide&&!m||a?.winningSide&&2===g&&(!a.feedRound||!II(a?.matchUpStatus))))return!0;const I=a&&jg({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),S=c&&Cw({relevantLink:s?.loserTargetLink,targetData:c,inContextDrawMatchUps:e,drawDefinition:r});return!(!(I&&Cw({targetData:I,inContextDrawMatchUps:e,drawDefinition:r}))&&!S)}const Ow={[bu]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[ds,us],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[MP,EP,UP,AP],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}},kw="positionAction",Fw="matchUpAction";function xw({actionType:t=kw,appliedPolicies:e,drawDefinition:n,structure:r}){const i=t===kw&&bu||t===Fw&&Nu,o=t===kw&&Ow||t===Fw&&ty,a=i&&(e?.[i]||o?.[i]),s=n.links?.filter(t=>t?.target?.structureId===r?.structureId),c=s?.map(({target:t})=>t.feedProfile)??[],{enabledStructures:u,disabledStructures:d}=a??{},p=d?.find(t=>{const{stages:e,stageSequences:n,structureTypes:i,feedProfiles:o}=t;return(!o?.length||Array.isArray(o)&&o.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:a}}function _w({activePositionOverrides:t,activeDrawPositions:e,action:n}){return!(!n||!t.includes(n))||!e.length}function Lw({enabledStructures:t,drawDefinition:e,structure:n}){if(!1===t)return{};if(!t?.length)return{policyActions:{enabledActions:[],disabledActions:[]}};const{stage:r,stageSequence:i,structureType:o}=n??{},a=e.links?.filter(t=>t?.target?.structureId===n?.structureId),s=a?.map(({target:t})=>t.feedProfile)??[];return{policyActions:t.find(t=>{const{stages:e,stageSequences:n,structureTypes:a,feedProfiles:c}=t??{},u=!e?.length||Array.isArray(e)&&e.includes(r),d=!n?.length||Array.isArray(n)&&n.includes(i),p=!a?.length||Array.isArray(a)&&a.includes(o),l=!c?.length||Array.isArray(c)&&c.some(t=>s.includes(t));return d&&p&&l&&t&&u})}}function Bw({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 Vw="replaceTieMatchUpParticipantId",Gw="assignTieMatchUpParticipantId",jw="removeTieMatchUpParticipantId",qw="assignMatchUpSideParticipant",Ww="substituteParticipant",$w="REMOVE_SUBSTITUTION",Hw="REPLACE_PARTICIPANT",zw="REMOVE_PARTICIPANT",Yw="setMatchUpStatus",Kw="SUBSTITUTION",Qw="SCHEDULE",Jw="REFEREE",Xw="STATUS",Zw="START",tD="SCORE",eD="END",nD={REPLACE_TEAM_POSITION_METHOD:Vw,ASSIGN_TEAM_POSITION_METHOD:Gw,REMOVE_TEAM_POSITION_METHOD:jw,REPLACE_PARTICIPANT:Hw,SUBSTITUTION_METHOD:Ww,REMOVE_SUBSTITUTION:$w,REMOVE_PARTICIPANT:zw,SCHEDULE_METHOD:Yw,SUBSTITUTION:Kw,SCHEDULE:Qw,PENALTY:"PENALTY",REFEREE:Jw,STATUS:Xw,SCORE:tD,START:Zw,END:eD};function rD({tournamentParticipants:t=[],possiblyDisablingAction:e,activeDrawPositions:n,positionAssignments:r,returnParticipants:i,appliedPolicies:o,drawDefinition:a,drawPosition:s,validActions:c,structureId:u,structure:d,drawId:p,event:l}){if(n.includes(s))return{};const m=c.find(t=>t.type===wP)?.availableParticipantIds,f=o?.[bu]?.otherFlightEntries,h=o?.[bu]?.restrictQualifyingAlternates,g=(a.entries??[]).filter(({entryStage:t})=>!h||(d.stage===ds?t===ds:t!==ds)).sort((t,e)=>(t.entryPosition??1/0)-(e.entryPosition??1/0)).map(({participantId:t})=>t).filter(Boolean),{allPositionedParticipantIds:I}=sl({drawDefinition:a}),S=r.map(t=>t.participantId).filter(Boolean),y=g.filter(t=>d.stage&&[ds,us,ms].includes(d.stage)?!I?.includes(t):!S.includes(t)),v=(l?.entries??[]).filter(t=>t.entryStatus===ef&&iD({restrictQualifyingAlternates:h,structure:d,entry:t})&&(d.stage&&[ds,us,ms].includes(d.stage)?!I?.includes(t.participantId):!S.includes(t.participantId))).sort((t,e)=>(t.entryPosition??1/0)-(e.entryPosition??1/0)).map(t=>t.participantId);let U=M(y.concat(v));if(f){const t=l?Tg({event:l}).flightProfile:void 0,e=t?.flights?.filter(t=>t.drawId!==p).map(t=>t.drawEntries.filter(t=>t.participantId&&![ff,pf,lf].includes(t.entryStatus)&&!g.includes(t.participantId)).map(({participantId:t})=>t)).flat().filter(Boolean);e?.length&&U.push(...e)}m?.length&&(U=U.filter(t=>!m.includes(t)));const P=i?t?.filter(t=>U.includes(t.participantId)):void 0;if(P?.forEach(t=>{const e=(a.entries??[]).find(e=>e.participantId===t.participantId);t.entryPosition=e?.entryPosition}),P?.sort((t,e)=>(t.entryPosition||1/0)-(e.entryPosition||1/0)),U.length){return{validAlternatesAction:Ei({payload:{drawId:p,structureId:u,drawPosition:s},willDisableLinks:e,method:"alternateDrawPositionAssignment",availableAlternatesParticipantIds:U,type:PP,availableAlternates:P})}}return{}}function iD({restrictQualifyingAlternates:t,structure:e,entry:n}){const{stage:r}=e;if(!n.entryStage||n.entryStage===r||r===ds&&!t||n.entryStage===us&&r===ps)return!0}function oD({restrictAdHocRoundParticipants:t,tournamentParticipants:e,matchUpParticipantIds:n,otherFlightEntries:r,drawDefinition:i,structureId:o,sideNumber:a,matchUpId:s,structure:c,matchUp:u,drawId:d,event:p}){const l=[],m=c?.matchUps??[],f=u.sides?.find(t=>t.sideNumber===a),h=f?.participantId,g=m.filter(({roundNumber:t})=>t===u.roundNumber),I=i?.entries?.filter(({entryStatus:t})=>t&&If.includes(t)).map(Xp)??[],S=g.map(t=>(t.sides??[]).flatMap(Xp)).flat().filter(Boolean),y=I.filter(e=>!(n.includes(e)||t&&S.includes(e))),v=e?.filter(t=>y?.includes(t.participantId)).map(t=>ca(t,void 0,!0));v?.forEach(t=>{const e=(i.entries??[]).find(e=>e.participantId===t.participantId);t.entryPosition=e?.entryPosition}),y.length&&l.push({payload:{drawId:d,matchUpId:s,structureId:o,sideNumber:a},method:qw,type:wP,availableParticipantIds:y,participantsAvailable:v});const U=function({eventEntries:t,structure:e}){return t.filter(t=>t.entryStatus===ef&&iD({structure:e,entry:t})).sort((t,e)=>(t.entryPosition||1/0)-(e.entryPosition||1/0)).map(Xp)}({eventEntries:p?.entries??[],structure:c});let P=M(I.concat(U));if(r){const t=p?Tg({event:p}):void 0,e=t?.flights?.filter(t=>t.drawId!==d).flatMap(t=>t.drawEntries.filter(t=>t.participantId&&![ff,pf,lf].includes(t.entryStatus)).map(({participantId:t})=>t)).filter(Boolean);e?.length&&P.push(...e)}P=P.filter(e=>!(n.includes(e)||y.includes(e)||t&&S.includes(e)));const T=e?.filter(t=>P.includes(t.participantId)).map(t=>ca(t,void 0,!0));if(T?.forEach(t=>{const e=(i.entries??[]).find(e=>e.participantId===t.participantId);t.entryPosition=e?.entryPosition}),T?.sort((t,e)=>(t.entryPosition||1/0)-(e.entryPosition||1/0)),P.length&&l.push({payload:{drawId:d,matchUpId:s,structureId:o,sideNumber:a},availableParticipantIds:P,participantsAvailable:T,method:qw,type:ef}),!aI(u)&&a&&h){l.push({payload:{drawId:d,matchUpId:s,structureId:o,sideNumber:a},method:"removeMatchUpSideParticipant",type:zw});const t=t=>t.sides.map(Xp),n=({matchUpId:t})=>t!==u.matchUpId,r=t=>!aI(t),i=u.sides?.find(t=>t.sideNumber!==a)?.participantId,c=[i,...m.filter(({roundNumber:t})=>t!==u.roundNumber).filter(n).map(t).filter(t=>t.includes(h)).flat()].filter(Boolean),p=t=>!c.flat().includes(t),f=g.filter(r).filter(n).map(t).flat().filter(p);if(f.length){const t=e?.filter(t=>f.includes(t.participantId)).map(t=>ca(t,void 0,!0));l.push({payload:{participantIds:[h],roundNumber:u.roundNumber,structureId:o,sideNumber:a,matchUpId:s,drawId:d},swappableParticipantIds:f,method:"adHocPositionSwap",type:NP,swappableParticipants:t})}}return l}function aD(t){if(!t)return{error:sr};let{drawDefinition:n,event:i}=t;const{restrictAdHocRoundParticipants:o=!0,policyDefinitions:a,enforceGender:s,participantId:c,sideNumber:u,matchUpId:d}=t,p=t.tournamentRecord??(t.tournamentId&&m(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!p)return{error:rt};if(!d||!m(d))return{error:fe};if(u&&![1,2].includes(u))return Ci({result:{error:sr},context:{sideNumber:u}});if(!n){const t=function({tournamentRecord:t,matchUpId:e}){const n=Qg({tournamentRecord:t}).matchUps??[],r=n.find(t=>t.matchUpId===e),i=(t?.events??[]).find(t=>t.eventId===r?.eventId),o=(i?.drawDefinitions??[]).find(t=>t.drawId===r?.drawId);return{drawDefinition:o,event:i}}({tournamentRecord:p,matchUpId:d});t.drawDefinition&&(n=t.drawDefinition),t.event&&(i=t.event)}if(!n)return{error:st};const l=xS({withIndividualParticipants:!0,tournamentRecord:p}).participants,{drawId:f}=n,{matchUp:h,structure:g}=nT({drawDefinition:n,matchUpId:d,event:i});if(!h)return{error:ge};const{appliedPolicies:I,policyActions:S,matchUpActionsPolicy:y,otherFlightEntries:v}=function({specifiedPolicyDefinitions:t,tournamentRecord:e,drawDefinition:n,structure:r,event:i}){const o=xd({tournamentRecord:e,drawDefinition:n,structure:r,event:i}).appliedPolicies??{};Object.assign(o,t??{});const a=o?.[bu]?.otherFlightEntries,s=o?.[Nu]??ty[Nu],{enabledStructures:c}=xw({actionType:Fw,appliedPolicies:o,drawDefinition:n,structure:r}),{policyActions:u}=Lw({enabledStructures:c,drawDefinition:n,structure:r});return{appliedPolicies:o,policyActions:u,matchUpActionsPolicy:s,otherFlightEntries:a}}({specifiedPolicyDefinitions:a,tournamentRecord:p,drawDefinition:n,structure:g,event:i}),U=t.matchUpsMap??bf({drawDefinition:n}),P=t.inContextDrawMatchUps??zg({tournamentParticipants:l,inContext:!0,drawDefinition:n,matchUpsMap:U,event:i}).matchUps,T=P?.find(t=>t.matchUpId===d),w=u&&T?.sides?.find(t=>t.sideNumber===u),D=T?.sides?.map(t=>t.participantId||t.participant?.participantid).filter(Boolean)??[],{assignedPositions:R,allPositionsAssigned:b}=ul({structure:g}),{structureId:N}=g??{},M=[];if(!N)return{validActions:M};const A=Boolean(h.collectionId);Hf({structure:g})&&!A&&M.push(...oD({restrictAdHocRoundParticipants:o,tournamentParticipants:l,matchUpParticipantIds:D,otherFlightEntries:v,drawDefinition:n,structureId:N,sideNumber:u,matchUpId:d,structure:g,matchUp:h,drawId:f,event:i}));const E=PU({drawDefinition:n,structure:g}),C=function({matchUp:t,isCollectionMatchUp:e,assignedPositions:n}){const r=n?.filter(t=>t.bye).map(t=>t.drawPosition);return t.matchUpStatus===Sp||!e&&t.drawPositions?.reduce((t,e)=>r?.includes(e)||t,!1)}({matchUp:h,isCollectionMatchUp:A,assignedPositions:R});if(C)return{validActions:M,isByeMatchUp:C};const O=h.matchUpStatus&&[wp,Tp].includes(h.matchUpStatus);return function({validActions:t,policyActions:n,matchUpActionsPolicy:i,specifiedPolicyDefinitions:o,inContextDrawMatchUps:a,matchUpParticipantIds:s,allPositionsAssigned:c,inContextMatchUp:u,assignedPositions:d,appliedPolicies:p,isCollectionMatchUp:l,enforceGender:m,participantId:f,isDoubleExit:h,sideNumber:g,matchUpId:I,structure:S,matchUp:y,drawId:v,drawDefinition:U,side:P}){Bw({policyActions:n,action:Jw})&&t.push({type:Jw,payload:{matchUpId:I}});const T=!sI({matchUpStatus:y.matchUpStatus}),w=function({appliedPolicies:t,allPositionsAssigned:e,structure:n}){const r=t?.scoring?.structures,i=n?.stage&&r?.stage?.[n.stage],o=n?.stageSequence&&i?.stageSequence?.[n.stageSequence],a=t?.scoring?.requireAllPositionsAssigned||i?.requireAllPositionsAssigned||o?.requireAllPositionsAssigned;return!a||e}({appliedPolicies:p,allPositionsAssigned:c,structure:S}),D=2===y.sides?.filter(t=>t?.participantId).length,R=jg({inContextDrawMatchUps:a,drawDefinition:U,matchUpId:I}),b=Cw({inContextDrawMatchUps:a,drawDefinition:U,targetData:R}),N=d?.filter(t=>t.participantId).map(t=>t.drawPosition),M=2===u?.drawPositions?.length&&u.drawPositions.every(t=>N?.includes(t))&&2===u?.sides?.length&&u.sides.every(({participantId:t})=>t),A=(M||D)&&!(h&&b);T&&t.push({payload:{drawId:v,matchUpId:I,schedule:{}},method:Yw,type:Qw});Bw({policyActions:n,action:EP})&&(P?.participant||!g&&s?.length)&&t.push({method:yP,type:EP,payload:{drawId:v,matchUpId:I,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}});T&&A&&t.push({type:Xw});w&&A&&(t.push({info:"set outcome and winningSide",method:Yw,type:tD,payload:{drawId:v,matchUpId:I,matchUpFormat:y.matchUpFormat,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0}}),Bw({policyActions:n,action:Zw})&&t.push({type:Zw}),Bw({policyActions:n,action:eD})&&t.push({type:eD}));l&&u&&t.push(...function({specifiedPolicyDefinitions:t,inContextDrawMatchUps:n,matchUpParticipantIds:i,matchUpActionsPolicy:o,inContextMatchUp:a,policyActions:s,enforceGender:c,participantId:u,sideNumber:d,matchUpId:p,matchUp:l,drawId:m,side:f}){const h=[],g=a.sides?.find(t=>t.participant),I=$i(a.gender)&&a.sideNumber&&1===a.sides?.filter(t=>t.particiapntId).length&&g?.participant?.person?.sex,S=a.matchUpType,y=!1!==(c??o?.participants?.enforceGender)?a.gender:void 0,v=a.sides?.flatMap(t=>t.participant?.individualParticipants||t.participant).filter(Boolean),U=v?.map(Xp),P=a.sides?.filter(t=>!d||t.sideNumber===d).flatMap(t=>t.participant?.individualParticipants||t.participant).filter(Boolean),T=P?.map(Xp),w=n?.find(t=>t.matchUpId===a.matchUpTieId),D=w?.sides?.map(t=>t?.participant?.individualParticipants?.filter(({participantId:t,person:e})=>!T?.includes(t)&&(!y||Hi(y)||e.sex===y||$i(y)&&!I||I&&e.sex!==I))),R=d?D?.[d-1]:D?.map((t,e)=>({participants:t,sideNumber:e+1})),b=d?D?.[d-1]?.map(Xp):D?.map((t,e)=>({participants:t?.map(Xp),sideNumber:e+1})),N=d&&(bh(e)(S)&&!T?.length||bh(r)(S)&&(T?.length??0)<2)||!d&&(bh(e)(S)&&(T?.length??0)<2||bh(r)(S)&&(T?.length??0)<4),M=b?.filter(t=>!U?.includes(t)),A=R?.filter(({participantId:t})=>M.includes(t));if(N&&M?.length&&h.push({availableParticipantIds:M,method:Gw,availableParticipants:A,type:wP,payload:{participantId:void 0,tieMatchUpId:p,sideNumber:d,drawId:m}}),!T?.length||aI(l)&&!f?.substitutions?.length||h.push({method:jw,type:zw,existingParticipantIds:T,payload:{participantId:void 0,tieMatchUpId:p,drawId:m}}),A?.length&&(!d&&T?.length||d&&f?.participant)&&h.push({availableParticipantIds:M,method:Vw,availableParticipants:A,type:Hw,existingParticipantIds:T,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:p,drawId:m}}),Bw({policyActions:s,action:$w})&&f?.substitutions?.length){const t=f.participant?.participantType===gm&&[f.participantId]||f.participant?.participantType===Sm&&f.participant.individualParticipantIds||[],e=f.substitutions.map(t=>t.participantId).filter(e=>t.includes(e));u&&!e.includes(u)||h.push({method:jw,type:$w,substitutedParticipantIds:e,payload:{participantId:void 0,tieMatchUpId:p,drawId:m}})}const E=t?.[Nu],C=E?.substituteWithoutScore,O=E?.substituteAfterCompleted;if(Bw({policyActions:s,action:Kw})&&2===i.length&&(!d&&T?.length||d&&f?.participant)&&(C||aI(l))&&(O||l.matchUpStatus&&!_p.includes(l.matchUpStatus))&&P?.length&&R.length){const t=P.map(Xp);h.push({info:"list of team players available for substitution",method:Ww,availableParticipantIds:b,existingParticipantIds:t,availableParticipants:R,existingParticipants:P,type:Kw,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:d,matchUpId:p,drawId:m}})}return h}({specifiedPolicyDefinitions:o,inContextDrawMatchUps:a,matchUpParticipantIds:s,matchUpActionsPolicy:i,inContextMatchUp:u,policyActions:n,enforceGender:m,participantId:f,sideNumber:g,matchUpId:I,matchUp:y,drawId:v,side:P}))}({validActions:M,policyActions:S,matchUpActionsPolicy:y,specifiedPolicyDefinitions:a,inContextDrawMatchUps:P,matchUpParticipantIds:D,allPositionsAssigned:b,inContextMatchUp:T,assignedPositions:R,appliedPolicies:I,isCollectionMatchUp:A,enforceGender:s,participantId:c,isDoubleExit:O,sideNumber:u,matchUpId:d,structure:g,matchUp:h,drawId:f,drawDefinition:n,side:w}),{structureIsComplete:E,validActions:M,isDoubleExit:O,...Y}}function sD({tournamentParticipants:t=[],sourceStructuresComplete:e,possiblyDisablingAction:n,isWinRatioFedStructure:r,activeDrawPositions:i,positionAssignments:o,drawDefinition:a,drawPosition:s,structureId:c,structure:u,drawId:d,event:p}){if(i.includes(s)||r&&!e)return{};const{sourceStructureIds:l,targetStructureIds:m}=a.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=a.links?.filter(t=>t.target?.structureId===u.structureId)??[];for(const t of h){const e=t?.source?.structureId,{structure:n}=ol({structureId:e,drawDefinition:a}),r={};if(n?.finishingPosition===lc&&(1!==l?.length||1!==m?.length)){const{matchUps:t}=Fg({drawDefinition:a,structure:u,event:p}),{initialRoundNumber:e}=pI({drawPosition:s,matchUps:t}),n=a.links?.find(t=>t.target?.structureId===u?.structureId&&t.target.roundNumber===e),i=n?.source?.roundNumber;r.roundNumbers=[i]}const{completedMatchUps:i}=Lg({structureId:e,inContext:!0,matchUpFilters:r,drawDefinition:a}),c=o.map(t=>t.participantId).filter(Boolean),d=i?.filter(({matchUpType:t,winningSide:e})=>e&&(p?.eventType!==is||t===is)).map(({winningSide:t,sides:e})=>t&&e?.[1-(t-1)]).map(Xp).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=(a.entries??[]).find(e=>e.participantId===t.participantId);t.entryPosition=e?.entryPosition}),f?.length){return{validLuckyLosersAction:{type:RP,method:"luckyLoserDrawPositionAssignment",availableLuckyLosers:g,availableLuckyLoserParticipantIds:f,willDisableLinks:n,payload:{drawId:d,structureId:c,drawPosition:s}}}}return{}}function cD({positionSourceStructureIds:t,unassignedParticipantIds:e,possiblyDisablingAction:n,provisionalPositioning:r,tournamentParticipants:i,isWinRatioFedStructure:o,positionAssignments:a,returnParticipants:s,appliedPolicies:c,drawDefinition:u,seedingProfile:d,isByePosition:p,drawPosition:l,structureId:m,event:f}){const{drawId:h}=u,g=[];let I,S,y=[];const v=c?.[xu]?.validSeedPositions?.ignore;if(!v){const t=$y({provisionalPositioning:r,returnAllProxies:!0,randomize:!0,drawDefinition:u,seedingProfile:d,structureId:m});({unplacedSeedParticipantIds:I,unplacedSeedAssignments:S,unfilledPositions:y}=t)}if(y?.length||(y=a.filter(t=>!t.participantId&&!t.bye&&!t.qualifier).map(t=>t.drawPosition)),p||g.push({payload:{drawId:h,structureId:m,drawPosition:l,isPositionAction:!0},willDisableLinks:n,method:"assignDrawPositionBye",type:OP}),o&&v){const e=a.map(t=>t.participantId).filter(Boolean),r={structureIds:t},{completedMatchUps:o}=Yg({inContext:!0,matchUpFilters:r,drawDefinition:u}),c=M((o??[]).filter(({matchUpType:t})=>f?.eventType!==is||t===is)?.map(({sides:t})=>t?.map(Xp)).flat().filter(t=>t&&!e.includes(t))),d=s?i?.filter(t=>c?.includes(t.participantId)).map(t=>ca(t,void 0,!0)):void 0;return d?.forEach(t=>{const e=(u.entries??[]).find(e=>e.participantId===t.participantId);t.entryPosition=e?.entryPosition}),d?.length&&g.push(Ei({payload:{drawId:h,structureId:m,drawPosition:l},willDisableLinks:n,method:SP,type:wP,availableParticipantIds:c,participantsAvailable:d})),{validAssignmentActions:g}}if(y.includes(l)||p){let t;if(S?.length){const e=S.filter(t=>I?.includes(t.participantId));e.sort(uD),t=e.map(t=>t.participantId)}else t=e;const r=s?i?.filter(e=>t.includes(e.participantId)).map(t=>ca(t,void 0,!0)):void 0;r?.length&&g.push(Ei({payload:{drawId:h,structureId:m,drawPosition:l},willDisableLinks:n,method:SP,type:wP,availableParticipantIds:t,participantsAvailable:r}))}return{validAssignmentActions:g}}function uD(t,e){return t.bye||Vy(t.seedValue)<Vy(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function dD({drawPositionInitialRounds:t,tournamentParticipants:e,positionAssignments:n,returnParticipants:r,appliedPolicies:i,drawDefinition:o,drawPosition:a,structureId:s,drawId:c}){const u=[],d=[],p=[],l=[],m=new Set(n.map(t=>t.participantId).filter(Boolean)),f=i?.[bu],h=!f?.disableRoundRestrictions&&t[a],g=f?.requireCompletedStructures,{sourceStructureIds:I,relevantLinks:S}=IU({targetRoundNumber:h,linkType:Es,drawDefinition:o,structureId:s})??{};I?.length&&l.push(...I);const{sourceStructureIds:y,relevantLinks:v}=IU({targetRoundNumber:h,linkType:As,drawDefinition:o,structureId:s})??{};return y?.length&&l.push(...y),function({requireCompletedStructures:t,tournamentParticipants:e,assignedParticipantIds:n,eliminationSourceLinks:r,qualifyingParticipantIds:i,qualifyingParticipants:o,returnParticipants:a,drawDefinition:s}){for(const c of r){const r=s.structures?.find(t=>t.structureId===c.source.structureId);if(r?.stage!==ds)continue;const u=PU({structureId:c.source.structureId,drawDefinition:s});if(t&&!u)continue;const d=r.qualifyingRoundNumber,{matchUps:p}=Fg({matchUpFilters:{roundNumbers:[d],isCollectionMatchUp:!1,hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:e,inContext:!0,structure:r});for(const t of p){const e=t.sides.find(e=>e?.sideNumber===t.winningSide),r=t.matchUpStatus===Sp&&t.sides?.find(({participantId:t})=>t);if(e||r){const{participantId:t,participant:s}=e||(r??{});t&&!n.has(t)&&(s&&a&&o.push(s),i.push(t))}}}}({requireCompletedStructures:g,tournamentParticipants:e,assignedParticipantIds:m,eliminationSourceLinks:S,qualifyingParticipantIds:d,qualifyingParticipants:u,returnParticipants:r,drawDefinition:o}),function({requireCompletedStructures:t,tournamentParticipants:e,assignedParticipantIds:n,qualifyingParticipantIds:r,qualifyingParticipants:i,roundRobinSourceLinks:o,returnParticipants:a,drawDefinition:s}){for(const c of o){const o=s.structures?.find(t=>t.structureId===c.source.structureId);if(o?.stage!==ds)continue;const u=PU({structureId:c.source.structureId,drawDefinition:s});if(t&&!u)continue;const{positionAssignments:d}=cl({structure:o}),p=d?.map(t=>{const e=t.participantId,n=dp({element:t,attribute:"tally",name:Rd});return n?{participantId:e,groupOrder:n?.groupOrder}:{}}).filter(({groupOrder:t,participantId:e})=>1===t&&!n.has(e)).map(({participantId:t})=>t)??[];if(p&&r.push(...p),a){const t=new Set(p),n=e.filter(({participantId:e})=>t.has(e));i.push(...n)}}}({requireCompletedStructures:g,tournamentParticipants:e,assignedParticipantIds:m,qualifyingParticipantIds:d,qualifyingParticipants:u,roundRobinSourceLinks:v,returnParticipants:r,drawDefinition:o}),d.length&&p.push(Ei({qualifyingParticipants:r?u:void 0,method:"qualifierDrawPositionAssignment",type:UP,qualifyingParticipantIds:d,payload:{qualifyingParticipantId:void 0,drawPosition:a,structureId:s,drawId:c}})),{validAssignmentActions:p,sourceStructureIds:l}}function pD({onlyAssignedPositions:t=!0,possiblyDisablingAction:e,tournamentParticipants:n,inactiveDrawPositions:r,activeDrawPositions:i,positionAssignments:o,returnParticipants:a,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=o?.filter(e=>(e=>!t||e.participantId||e.qualifier||e.bye)(e)&&h?.includes(e.drawPosition))??[],I=g.map(({drawPosition:t})=>t),{matchUps:S}=Fg({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:l,event:f}),y=S.filter(({drawPositions:t})=>j(t,I)),v=Object.assign({},...y.map(t=>t.sides?.filter(({sourceDrawPositionRange:t})=>t).map(({drawPosition:t,sourceDrawPositionRange:e})=>({[t]:e}))).flat()),U=g.map(t=>t.participantId).filter(Boolean),P=(n??[]).filter(t=>U.includes(t.participantId)),T=Object.assign({},...P.map(t=>({[t.participantId]:t}))),w=g.map(t=>{const e=T?.[t.participantId],n=v[t.drawPosition];return Ei({...t,participant:a?ca(e,!1,!0):void 0,sourceDrawPositionRange:n})});if(w.length){return{validSwapAction:{payload:{drawId:m,structureId:p,drawPositions:[d]},willDisableLinks:e,method:IP,type:NP,availableAssignments:w}}}return{}}function lD(t){return function(t){const e=function(t){const e=fu(t,[{event:!0,drawDefinition:!0,structureId:!0}]);if(e.error)return{earlyReturn:e};const{policyDefinitions:n,returnParticipants:r=!0,provisionalPositioning:i,tournamentRecord:o,drawDefinition:a,drawPosition:s,event:c}=t,u=t.tournamentParticipants??(o&&xS({withIndividualParticipants:!0,tournamentRecord:o}).participants)??[];let d=ol({structureId:t.structureId,drawDefinition:a});if(d.error)return{earlyReturn:d};const p=d.containingStructure||d.structure;if(!p)return{earlyReturn:{error:Vt}};const l=p.structureId;if(d=dI({drawDefinition:a,structureId:l}),void 0===s&&!d.isAdHoc)return{earlyReturn:{error:Tt}};if(d.isAdHoc)return{earlyReturn:aD(t)};if(d.error)return{earlyReturn:d};const{drawPositionInitialRounds:m,inactiveDrawPositions:f,activeDrawPositions:h,byeDrawPositions:g}=d,I=xd({tournamentRecord:o,drawDefinition:a,structure:p,event:c}).appliedPolicies??{};Object.assign(I,n??{});const{actionsPolicy:S,enabledStructures:y,actionsDisabled:v}=xw({actionType:kw,appliedPolicies:I,drawDefinition:a,structure:p}),U=S?.activePositionOverrides??[],{sourceStructureIds:P}=IU({finishingPosition:pc,targetRoundNumber:1,linkType:As,drawDefinition:a,structureId:l})??{};let T;P?.length&&(T=P.every(t=>PU({structureId:t,drawDefinition:a})));const w=P.length,D=P.length&&!T,{policyActions:R}=Lw({enabledStructures:y,drawDefinition:a,structure:p}),b=![ds,us].includes(p.stage)||1!==p.stageSequence,{drawId:N}=a,{assignedPositions:M,positionAssignments:A}=ul({structure:p}),E=M?.find(t=>t.drawPosition===s),C=!!E,O=A?.map(t=>t.drawPosition);if(!O?.includes(s)){if(!(p.matchUps?.flatMap(t=>t.drawPositions??[])??[]).includes(s))return{earlyReturn:{error:Pt}}}const{stage:k,stageSequence:F}=p,x=[k];k===ps&&x.push(us);k===us&&x.push(ps);const _=Pf({entryStatuses:If,provisionalPositioning:i,drawDefinition:a,stageSequence:F,structureId:l,stages:x}),L=bI({drawDefinition:a,stages:x}).assignedParticipantIds??[],B=function(t,e){return t.filter(t=>!e.includes(t.participantId)).map(t=>t.participantId)}(_,L),V=g.includes(s),G=h.includes(s),j=qf(a.drawType)&&m?.[s]>1;if(v)return{earlyReturn:{info:"Actions Disabled for structure",isActiveDrawPosition:G,isDrawPosition:!0,hasPositionAssigned:C,validActions:[],isByePosition:V}};return{positionSourceStructureIds:P,isLuckyDrawAdvancedPosition:j,drawPositionInitialRounds:m,unassignedParticipantIds:B,sourceStructuresComplete:T,activePositionOverrides:U,tournamentParticipants:u,disablePlacementActions:D,possiblyDisablingAction:b,isWinRatioFedStructure:w,inactiveDrawPositions:f,isActiveDrawPosition:G,positionAssignments:A,hasPositionAssigned:C,positionAssignment:E,activeDrawPositions:h,returnParticipants:r,byeDrawPositions:g,appliedPolicies:I,drawDefinition:a,policyActions:R,isByePosition:V,drawPosition:s,structureId:l,structure:p,drawId:N,event:c}}(t);if("earlyReturn"in e)return e.earlyReturn;const{positionSourceStructureIds:n,isLuckyDrawAdvancedPosition:r,drawPositionInitialRounds:i,unassignedParticipantIds:o,sourceStructuresComplete:a,activePositionOverrides:s,tournamentParticipants:c,disablePlacementActions:u,possiblyDisablingAction:d,isWinRatioFedStructure:p,inactiveDrawPositions:l,isActiveDrawPosition:m,positionAssignments:f,hasPositionAssigned:h,positionAssignment:g,activeDrawPositions:I,returnParticipants:S,byeDrawPositions:y,appliedPolicies:v,drawDefinition:U,policyActions:P,isByePosition:T,drawPosition:w,structureId:D,structure:R,drawId:b,event:N}=e,M=[];(function({validActions:t,policyActions:e,isActiveDrawPosition:n,positionAssignments:r,disablePlacementActions:i,positionAssignment:o,isByePosition:a,getValidAssignmentActions:s,positionSourceStructureIds:c,unassignedParticipantIds:u,possiblyDisablingAction:d,isWinRatioFedStructure:p,tournamentParticipants:l,returnParticipants:m,appliedPolicies:f,drawDefinition:h,drawPosition:g,structureId:I,event:S}){if(Bw({policyActions:e,action:wP})&&!n&&r&&!i&&(!o||a)){const{validAssignmentActions:e}=s({positionSourceStructureIds:c,unassignedParticipantIds:u,possiblyDisablingAction:d,isWinRatioFedStructure:p,tournamentParticipants:l,positionAssignments:r,returnParticipants:m,appliedPolicies:f,drawDefinition:h,isByePosition:a,drawPosition:g,structureId:I,event:S});e?.forEach(e=>t.push(e))}})({validActions:M,policyActions:P,isActiveDrawPosition:m,positionAssignments:f,disablePlacementActions:u,positionAssignment:g,isByePosition:T,getValidAssignmentActions:cD,positionSourceStructureIds:n,unassignedParticipantIds:o,possiblyDisablingAction:d,isWinRatioFedStructure:p,tournamentParticipants:c,returnParticipants:S,appliedPolicies:v,drawDefinition:U,drawPosition:w,structureId:D,event:N}),function({validActions:t,policyActions:e,isActiveDrawPosition:n,getValidQualifiersAction:r,drawPositionInitialRounds:i,tournamentParticipants:o,positionAssignments:a,returnParticipants:s,appliedPolicies:c,drawDefinition:u,drawPosition:d,structureId:p,drawId:l}){if(Bw({policyActions:e,action:UP})&&!n){const{validAssignmentActions:e}=r({drawPositionInitialRounds:i,tournamentParticipants:o,positionAssignments:a,returnParticipants:s,appliedPolicies:c,drawDefinition:u,drawPosition:d,structureId:p,drawId:l});e?.forEach(e=>t.push(e))}}({validActions:M,policyActions:P,isActiveDrawPosition:m,getValidQualifiersAction:dD,drawPositionInitialRounds:i,tournamentParticipants:c,positionAssignments:f,returnParticipants:S,appliedPolicies:v,drawDefinition:U,drawPosition:w,structureId:D,drawId:b});const{participantId:A}=g??{},E=A&&c.find(t=>t.participantId===A);if(g){if(function({isLuckyDrawAdvancedPosition:t,validActions:e,policyActions:n,isActiveDrawPosition:r,drawId:i,structureId:o,drawPosition:a,possiblyDisablingAction:s,isByePosition:c}){Bw({policyActions:n,action:DP})&&!r&&(e.push({type:DP,method:gP,payload:{drawId:i,structureId:o,drawPosition:a},willDisableLinks:s}),c||t||e.push({type:TP,method:"withdrawParticipantAtDrawPosition",payload:{drawId:i,structureId:o,drawPosition:a},willDisableLinks:s}),!Bw({policyActions:n,action:OP})||c||t||e.push({type:OP,method:gP,payload:{drawId:i,structureId:o,drawPosition:a,replaceWithBye:!0},willDisableLinks:s}))}({isLuckyDrawAdvancedPosition:r,validActions:M,policyActions:P,isActiveDrawPosition:m,drawId:b,structureId:D,drawPosition:w,possiblyDisablingAction:d,isByePosition:T}),r||function({validActions:t,policyActions:e,activePositionsCheck:n,activePositionOverrides:r,activeDrawPositions:i,drawDefinition:o,structureId:a,drawPosition:s,structure:c,isByePosition:u,participantId:d,participant:p,drawId:l}){const m=c.stage===ds||c.stage===us&&1===c.stageSequence;if(!u&&n({activePositionOverrides:r,activeDrawPositions:i,action:AP})&&Bw({policyActions:e,action:AP})&&Wy({drawDefinition:o,structureId:a,drawPosition:s})&&m){const{seedAssignments:e}=Tf({returnAllProxies:!0,drawDefinition:o,structure:c}),{seedNumber:n,seedValue:r}=e?.find(t=>t.participantId===d)??{};t.push({type:AP,method:"modifySeedAssignment",participant:p,seedNumber:n,payload:{drawId:l,structureId:a,participantId:d,seedValue:r}})}if(!u&&n({activePositionOverrides:r,activeDrawPositions:i,action:bP})&&Bw({policyActions:e,action:bP})&&Wy({drawDefinition:o,structureId:a,drawPosition:s})&&m){const{seedAssignments:e}=Tf({returnAllProxies:!0,drawDefinition:o,structure:c}),{seedNumber:n}=e?.find(t=>t.participantId===d)??{};t.push({method:"removeSeededParticipant",type:bP,participant:p,seedNumber:n,payload:{participantId:d,structureId:a,drawId:l}})}}({validActions:M,policyActions:P,activePositionsCheck:_w,activePositionOverrides:s,activeDrawPositions:I,drawDefinition:U,structureId:D,drawPosition:w,structure:R,isByePosition:T,participantId:A,participant:E,drawId:b}),!r&&!T){const{validSeedCascadeAction:t}=function({positionAssignments:t,activeDrawPositions:e,drawDefinition:n,isByePosition:r,structure:i,drawPosition:o,structureId:a,drawId:s}){if(i.stage!==us||1!==i.stageSequence)return{};if(i.structureType===Ds)return{};if(r)return{};if(e.length)return{};const c=t.find(t=>t.drawPosition===o);if(!c?.participantId)return{};const{seedAssignments:u}=Tf({drawDefinition:n,structure:i});if(!u?.length)return{};const d=u.find(t=>t.participantId===c.participantId);if(!d)return{};const{validSeedBlocks:p}=Gy({drawDefinition:n,structure:i});if(!p?.length)return{};const l=p.findIndex(t=>t.seedNumbers.includes(d.seedNumber));return l<0||l>=p.length-1?{}:p.slice(l+1).some(t=>u.some(e=>t.seedNumbers.includes(e.seedNumber)&&e.participantId))?{validSeedCascadeAction:{type:CP,method:"seedWithdrawalCascade",payload:{drawId:s,structureId:a,drawPosition:o}}}:{}}({positionAssignments:f,activeDrawPositions:I,drawDefinition:U,isByePosition:T,structure:R,drawPosition:w,structureId:D,drawId:b});t&&M.push(t)}!function({validActions:t,policyActions:e,isByePosition:n,participantId:r,participant:i,drawId:o}){if(!n&&r){if(Bw({policyActions:e,action:EP})){const e={type:EP,method:yP,participant:i,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:o}};t.push(e)}if(Bw({policyActions:e,action:MP})){const e={type:MP,method:"modifyParticipantOtherName",participant:i,payload:{participantId:r,otherName:void 0}};t.push(e)}}}({validActions:M,policyActions:P,isByePosition:T,participantId:A,participant:E,drawId:b}),function({validActions:t,policyActions:e,getValidSwapAction:n,possiblyDisablingAction:r,tournamentParticipants:i,inactiveDrawPositions:o,activeDrawPositions:a,positionAssignments:s,returnParticipants:c,byeDrawPositions:u,drawDefinition:d,isByePosition:p,drawPosition:l,structureId:m,structure:f,drawId:h}){if(Bw({policyActions:e,action:NP})){const{validSwapAction:e}=n({possiblyDisablingAction:r,tournamentParticipants:i,inactiveDrawPositions:o,activeDrawPositions:a,positionAssignments:s,returnParticipants:c,byeDrawPositions:u,drawDefinition:d,isByePosition:p,drawPosition:l,structureId:m,structure:f,drawId:h});e&&t.push(e)}}({validActions:M,policyActions:P,getValidSwapAction:pD,possiblyDisablingAction:d,tournamentParticipants:c,inactiveDrawPositions:l,activeDrawPositions:I,positionAssignments:f,returnParticipants:S,byeDrawPositions:y,drawDefinition:U,isByePosition:T,drawPosition:w,structureId:D,structure:R,drawId:b})}return function({validActions:t,policyActions:e,getValidAlternatesAction:n,possiblyDisablingAction:r,tournamentParticipants:i,positionAssignments:o,activeDrawPositions:a,returnParticipants:s,appliedPolicies:c,drawDefinition:u,drawPosition:d,structureId:p,structure:l,drawId:m,event:f,disablePlacementActions:h}){if(Bw({policyActions:e,action:PP})&&!h){const{validAlternatesAction:e}=n({possiblyDisablingAction:r,tournamentParticipants:i,positionAssignments:o,activeDrawPositions:a,returnParticipants:s,appliedPolicies:c,drawDefinition:u,drawPosition:d,validActions:t,structureId:p,structure:l,drawId:m,event:f});e&&t.push(e)}}({validActions:M,policyActions:P,getValidAlternatesAction:rD,possiblyDisablingAction:d,tournamentParticipants:c,positionAssignments:f,activeDrawPositions:I,returnParticipants:S,appliedPolicies:v,drawDefinition:U,drawPosition:w,structureId:D,structure:R,drawId:b,event:N,disablePlacementActions:u}),function({validActions:t,policyActions:e,getValidLuckyLosersAction:n,sourceStructuresComplete:r,possiblyDisablingAction:i,isWinRatioFedStructure:o,tournamentParticipants:a,activeDrawPositions:s,positionAssignments:c,drawDefinition:u,drawPosition:d,structureId:p,structure:l,drawId:m,disablePlacementActions:f,isActiveDrawPosition:h}){if(Bw({policyActions:e,action:RP})&&!f&&!h&&c){const{validLuckyLosersAction:e}=n({sourceStructuresComplete:r,possiblyDisablingAction:i,isWinRatioFedStructure:o,tournamentParticipants:a,activeDrawPositions:s,positionAssignments:c,drawDefinition:u,drawPosition:d,structureId:p,structure:l,drawId:m});e&&t.push(e)}}({validActions:M,policyActions:P,getValidLuckyLosersAction:sD,sourceStructuresComplete:a,possiblyDisablingAction:d,isWinRatioFedStructure:p,tournamentParticipants:c,activeDrawPositions:I,positionAssignments:f,drawDefinition:U,drawPosition:w,structureId:D,structure:R,drawId:b,disablePlacementActions:u,isActiveDrawPosition:m}),function({validActions:t,policyActions:e,getValidModifyAssignedPairAction:n,participant:r,tournamentParticipants:i,returnParticipants:o,drawPosition:a,drawId:s,event:c}){if(r?.participantType===Sm&&Bw({policyActions:e,action:vP})){const{validModifyAssignedPairAction:e}=n({tournamentParticipants:i,returnParticipants:o,drawPosition:a,participant:r,drawId:s,event:c});e&&t.push(e)}}({validActions:M,policyActions:P,getValidModifyAssignedPairAction:Ew,participant:E,tournamentParticipants:c,returnParticipants:S,drawPosition:w,drawId:b,event:N}),{isActiveDrawPosition:m,isDrawPosition:!0,hasPositionAssigned:h,isByePosition:T,validActions:M,...Y}}(t)}function mD({policyDefinitions:t,appliedPolicies:e,drawType:n}){const r=t?.[Bu]?.drawTypeCoercion,i=e?.[Bu]?.drawTypeCoercion;return("boolean"==typeof r?r:void 0)??(n&&r?.[n])??("boolean"==typeof i?i:void 0)??(n&&i?.[n])??!0}const fD=({drawDefinition:t,random:e})=>{const n=fu({drawDefinition:t},[{[yc]:!0}]);if(n.error)return n;const r=t.structures?.find(t=>t.stage===us&&1===t.stageSequence);if(!r)return Ci({result:{error:qt}});const{qualifierPositions:i}=ul({structure:r}),o=e??Math.random;return L(0,i.length).sort(()=>o()-.5)};function hD({participantIds:t,matchUps:e,allowDraws:n=!1}){const r=new Map;for(const e of t)r.set(e,{participantId:e,wins:0,losses:0,draws:0,points:0,opponentIds:[],opponentOutcomes:new Map,roundPoints:[]});for(const t of e){if(t.matchUpStatus!==vp)continue;if(!t.sides||t.sides.length<2)continue;const e=Xp(t.sides[0]),i=Xp(t.sides[1]);if(!e||!i)continue;const o=r.get(e),a=r.get(i);o&&a&&(o.opponentIds.includes(i)||o.opponentIds.push(i),a.opponentIds.includes(e)||a.opponentIds.push(e),1===t.winningSide?(o.wins+=1,o.points+=1,a.losses+=1,o.opponentOutcomes.set(i,"WIN"),a.opponentOutcomes.set(e,"LOSS"),o.roundPoints.push(1),a.roundPoints.push(0)):2===t.winningSide?(a.wins+=1,a.points+=1,o.losses+=1,a.opponentOutcomes.set(e,"WIN"),o.opponentOutcomes.set(i,"LOSS"),o.roundPoints.push(0),a.roundPoints.push(1)):n&&(o.draws+=1,a.draws+=1,o.points+=.5,a.points+=.5,o.opponentOutcomes.set(i,"DRAW"),a.opponentOutcomes.set(e,"DRAW"),o.roundPoints.push(.5),a.roundPoints.push(.5)))}const i=new Map;for(const[t,e]of r){const n=`${e.wins}-${e.losses}-${e.draws}`,r=i.get(n)??[];r.push(t),i.set(n,r)}const o=[];for(const[t,e]of i){const[n,r,i]=t.split("-").map(Number);o.push({wins:n,losses:r,draws:i,participantIds:e})}return o.sort((t,e)=>{const n=t.wins+.5*t.draws,r=e.wins+.5*e.draws;return r!==n?r-n:t.losses-e.losses}),{scoreGroups:o,records:r}}function gD({records:t,tiebreakMethods:e=["BUCHHOLZ","SONNEBORN_BERGER"]}){const n=[];for(const[r,i]of t){const o={participantId:r,wins:i.wins,losses:i.losses,draws:i.draws,points:i.points,opponentIds:i.opponentIds,rank:0};e.includes("BUCHHOLZ")&&(o.buchholz=ID(r,t)),e.includes("MEDIAN_BUCHHOLZ")&&(o.medianBuchholz=SD(r,t)),e.includes("SONNEBORN_BERGER")&&(o.sonnebornBerger=yD(r,t)),e.includes("PROGRESSIVE_SCORE")&&(o.progressiveScore=vD(i)),n.push(o)}!function(t,e){t.sort((t,n)=>{if(n.points!==t.points)return n.points-t.points;for(const r of e){const e=UD(t,r),i=UD(n,r);if(i!==e)return i-e}return 0})}(n,e);for(let t=0;t<n.length;t++)n[t].rank=t+1;return n}function ID(t,e){const n=e.get(t);return n?n.opponentIds.reduce((t,n)=>{const r=e.get(n);return t+(r?.points??0)},0):0}function SD(t,e){const n=e.get(t);if(!n||n.opponentIds.length<3)return ID(t,e);return n.opponentIds.map(t=>e.get(t)?.points??0).sort((t,e)=>t-e).slice(1,-1).reduce((t,e)=>t+e,0)}function yD(t,e){const n=e.get(t);if(!n)return 0;let r=0;for(const t of n.opponentIds){const i=e.get(t);if(!i)continue;const o=n.opponentOutcomes.get(t);"WIN"===o?r+=i.points:"DRAW"===o&&(r+=.5*i.points)}return r}function vD(t){let e=0,n=0;for(const r of t.roundPoints)e+=r,n+=e;return n}function UD(t,e){switch(e){case"BUCHHOLZ":return t.buchholz??0;case"MEDIAN_BUCHHOLZ":return t.medianBuchholz??0;case"SONNEBORN_BERGER":return t.sonnebornBerger??0;case"PROGRESSIVE_SCORE":return t.progressiveScore??0;default:return 0}}function PD({tiebreakMethods:t=["BUCHHOLZ","SONNEBORN_BERGER"],drawDefinition:e,structureId:n}){if(!e)return{error:st};const r=n?ol({drawDefinition:e,structureId:n}).structure:e.structures?.find(t=>Hf({structure:t}));if(!r)return{error:Vt};const i=r.matchUps??[],o=(e.entries??[]).filter(t=>Sf.includes(t.entryStatus??"")).map(Xp).filter(Boolean);if(!o.length)return{standings:[],scoreGroups:[],roundsPlayed:0,...Y};const{scoreGroups:a,records:s}=hD({participantIds:o,matchUps:i}),c=gD({records:s,tiebreakMethods:t}),u=i.filter(t=>t.winningSide);return{standings:c,scoreGroups:a,roundsPlayed:[...new Set(u.map(t=>t.roundNumber).filter(Boolean))].length,...Y}}function TD({structureId:t,drawDefinition:e}){if(!e)return{error:st};if(!m(t))return{error:sr};const n=Vg({drawDefinition:e,structureId:t});if(n.error)return n;const r=n.links.target.flatMap(t=>t.target.feedProfile).filter(Boolean),i=!V([Ms,Ns,bs,Ts],r).length;return{...Y,valid:i}}function wD({positionAssignment:t}){if(!t)return{error:ee};const e=dp({element:t,attribute:"tally",name:Rd});return void 0===e?{error:mr}:{tally:e}}function DD({drawDefinition:t,structureId:e}){if(!t)return{error:st};const n=e?ol({drawDefinition:t,structureId:e}).structure:t.structures?.find(t=>Hf({structure:t}));if(!n)return{error:Vt};const r=n.matchUps??[],i=(t.entries??[]).filter(t=>Sf.includes(t.entryStatus??"")).map(Xp).filter(Boolean);if(!i.length)return{rounds:[],totalRounds:0,...Y};const o=[...new Set(r.map(t=>t.roundNumber).filter(Boolean))].sort((t,e)=>(t??0)-(e??0)),a=[];a.push({roundNumber:0,nodes:[{wins:0,losses:0,draws:0,participantIds:[...i]}]});for(const t of o){const e=r.filter(e=>e.matchUpStatus===vp&&(e.roundNumber??0)<=(t??0)),{scoreGroups:n}=hD({matchUps:e,participantIds:i});a.push({roundNumber:t??0,nodes:n.map(t=>({wins:t.wins,losses:t.losses,draws:t.draws,participantIds:[...t.participantIds]}))})}return{rounds:a,totalRounds:o.length,...Y}}function RD({drawDefinition:t}){if(!t)return{error:st};const e=dp({element:t,attribute:"draftState",name:ud});if(!e)return{error:mr,info:"No draft found"};const n=e.tiers?.reduce((t,e)=>t+(e.participantIds?.length??0),0),r=Object.keys(e.preferences??{}).length,i=e.tiers?.filter(t=>t.resolved).length??0;return{draftState:e,summary:{status:e.status,totalParticipants:n,preferencesSubmitted:r,preferencesOutstanding:n-r,tiersTotal:e.tiers?.length??0,tiersResolved:i,unassignedDrawPositions:e.unassignedDrawPositions,preferencesCount:e.preferencesCount}}}function bD({participantsCount:t,participantCount:e}){if(!(t=t??e))return{error:sr};const n=w(t);return n?{drawSize:n}:Ci({result:{error:sr},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function ND(t){let{drawSizeProgression:e=!1,policyDefinitions:n,drawSize:r}=t??{};const{requireParticipantCount:i=!0,tournamentRecord:o,drawDefinition:a,event:s}=t??{},c="getSeedsCount",u=t?.participantsCount??t?.participantCount;if(!n){const t=_d({tournamentRecord:o,drawDefinition:a,event:s});if(t.error)return Ci({result:t,stack:c});n=t.policyDefinitions}const d=R(u);if(u&&!d)return Ci({result:{error:sr},context:{participantsCount:u},stack:c});if(i&&!d)return Ci({result:{error:mn},stack:c});if(Number.isNaN(Number(r))){if(!u)return Ci({result:{error:Rt},stack:c});({drawSize:r}=bD({participantsCount:u}))}const p=i&&u||r;if(p&&p>r)return{error:Sn};const l=n?.[xu];if(!l)return{error:we};const m=l.seedsCountThresholds;if(!m)return{error:Et};void 0!==l.drawSizeProgression&&(e=l.drawSizeProgression);return{seedsCount:m.filter(t=>e?t.drawSize<=r:r===t.drawSize).reduce((t,e)=>u&&u>=e.minimumParticipantCount?e.seedsCount:t,0)}}function MD({consideredEntries:t,policyDefinitions:e,tournamentRecord:n,appliedPolicies:r,participantMap:i,enforceGender:o,participants:a,event:s}){if(a&&i||!n||({participants:a,participantMap:i}=xS({tournamentRecord:n})),!a)return{error:an};if(!Array.isArray(a))return{error:sr};if(!s)return{error:Ht};const c=e?.[Nu]??r?.[Nu]??ty[Nu],u=!1!==(o??c?.participants?.enforceGender),{eventType:d,gender:p}=s,l=d===rs,m=d===os&&ym||l&&Sm||gm,f=Object.assign({},...(t??s.entries??[]).map(t=>({[t.participantId]:t.entryStatus}))),h=Object.keys(f),g=a.filter(t=>h.includes(t.participantId)).filter(t=>{const e=function({participant:t,participantType:e,eventType:n,entryStatusMap:r}){if(n===ss&&[gm,Sm].includes(t.participantType))return!1;const i=r[t.participantId],o=n&&[rs,os].includes(n)&&t.participantType===gm&&(MI(i)||i===ff);return t.participantType!==e&&!o}({participant:t,participantType:m,eventType:d,entryStatusMap:f}),n=function(t){const{participant:e,participantMap:n,eventGender:r,mismatch:i,isDoubles:o,genderEnforced:a}=t,s=!i&&o&&M(e?.individualParticipantIds?.map(t=>n?.[t]?.participant?.person?.sex).filter(Boolean)??[])||[],c=!r||!s?.length||Hi(r)||Yi(r)&&zi(s[0])===zi(r)||$i(r)&&(1===s.length&&1===e.individualParticipantIds?.length||2===s.length),u=e?.person?.sex,d=!e?.person||!r||$i(r)||Hi(r)||Yi(r)&&zi(u)===zi(r);return!a||c&&d}({genderEnforced:u,participantMap:i,eventGender:p,participant:t,isDoubles:l,mismatch:e});return e||!n});if(g.length){const t=g.map(t=>t.participantId);return{error:Qt,invalidParticipantIds:t}}return{...Y,valid:!0}}var AD={__proto__:null,addGoesTo:rI,allPlayoffPositionsFilled:TU,checkValidEntries:MD,findDrawDefinition:Aw,getAssignedParticipantIds:bI,getAvailableMatchUpsCount:JT,getAvailablePlayoffProfiles:bv,getDraftState:RD,getDrawDefinitionTimeItem:Mm,getDrawParticipantRepresentativeIds:XT,getDrawStructures:al,getDrawTypeCoercion:mD,getEligibleVoluntaryConsolationParticipants:YT,getLuckyDrawRoundStatus:zP,getMatchUpsMap:bf,getParticipantIdFinishingPositions:Nw,getPositionAssignments:dw,getPositionsPlayedOff:Dv,getRandomQualifierList:fD,getSeedingThresholds:By,getSeedsCount:ND,getStructureSeedAssignments:Tf,getSwissChart:DD,getSwissStandings:PD,getTally:wD,getTeamLineUp:Ng,getValidGroupSizes:xy,hasLuckyRounds:Wf,isAdHoc:Hf,isCompletedStructure:PU,isValidForQualifying:TD,positionActions:lD,predictDrawCompetitiveBands:uw,validatePlayoffGroups:Mv};function ED({hasExistingDrawDefinition:t,qualifyingProfiles:e,appliedPolicies:n,qualifyingOnly:r,tieFormat:i,idPrefix:o,isMock:a,uuids:s}){const c=[],u=[],d=[],p=(t,e)=>t.stageSequence-e.stageSequence,l=(t,e)=>t.roundTarget-e.roundTarget;let m,f=0,h=0,g=1;for(const I of e.sort(l)){const l=I.structureProfiles??[];g=I.roundTarget||g;let S,y,v,U=1,P=0;for(const c of(l??[]).sort(p)){const p=CD({structureProfile:c,qualifyingProfiles:e,structureProfiles:l,hasExistingDrawDefinition:t,appliedPolicies:n,qualifyingOnly:r,stageSequence:U,roundTarget:g,tieFormat:i,idPrefix:o,isMock:a,uuids:s,stack:"generateQualifyingSTructures",finalQualifyingStructureId:y,finalQualifyingRoundNumber:S,qualifyingDrawPositionsCount:f,targetRoundQualifiersCount:P,finishingPositions:m,linkType:v,links:d,structures:u});if(p.error)return p;({qualifyingDrawPositionsCount:f,targetRoundQualifiersCount:P,finalQualifyingStructureId:y,finalQualifyingRoundNumber:S,finishingPositions:m,linkType:v,stageSequence:U}=p)}h+=P,c.push({qualifiersCount:P,finalQualifyingRoundNumber:S,finalQualifyingStructureId:y,finishingPositions:m,roundTarget:g,linkType:v}),g+=1}return{qualifiersCount:h,qualifyingDrawPositionsCount:f,qualifyingDetails:c,structures:u,...Y,links:d}}function CD({structureProfile:t,qualifyingProfiles:e,structureProfiles:n,hasExistingDrawDefinition:r,appliedPolicies:i,qualifyingOnly:o,stageSequence:a,roundTarget:s,tieFormat:c,idPrefix:u,isMock:d,uuids:p,stack:l,finalQualifyingStructureId:m,finalQualifyingRoundNumber:f,qualifyingDrawPositionsCount:h,targetRoundQualifiersCount:g,finishingPositions:I,linkType:S,links:y,structures:U}){let P=v(t.drawSize||t.participantsCount);const{qualifyingRoundNumber:T,structureOptions:w,matchUpFormat:D,structureName:b,structureId:N,drawType:M}=t,A=t.matchUpType,E=t.qualifyingPositions||function({drawSize:t,qualifyingRoundNumber:e}){let n=t,r=0;for(;r<e;)n=Math.floor(n/2),r+=1;return n}({drawSize:P,qualifyingRoundNumber:T});if(!R(P))return Ci({result:{error:Rt},stack:l});const C=e.length>1?`${s}-`:"",O=n.length>1||C?a:"",k=b||(C||O?`${Ny(ds)} ${C}${O}`:Ny(ds));let F,x,_;if(M===ic){const e=Fy({structureName:t.structureName||k,structureId:N||p?.pop(),hasExistingDrawDefinition:r,stage:ds,structureOptions:w,appliedPolicies:i,qualifyingOnly:o,stageSequence:a,matchUpType:A,roundTarget:s,tieFormat:c,drawSize:P,idPrefix:u,isMock:d,uuids:p});g=e.groupCount,F=e.maxRoundNumber,x=e.structures[0],I=[1]}else({drawSize:P,matchUps:_,roundLimit:F}=Sv({qualifyingRoundNumber:T,qualifyingPositions:E,matchUpType:A,drawSize:P,idPrefix:u,isMock:d,uuids:p})),x=Ry({structureName:t.structureName||k,structureId:N||p?.pop(),qualifyingRoundNumber:F,hasExistingDrawDefinition:r,stage:ds,qualifyingOnly:o,matchUpFormat:D,stageSequence:a,matchUpType:A,roundLimit:F,tieFormat:c,matchUps:_}),s&&sp({element:x,attribute:"roundTarget",name:vd,value:s}),g=_?.filter(t=>t.roundNumber===F)?.length||0;if(a>1){const{link:t}=LP({sourceStructureId:m,sourceRoundNumber:f,targetStructureId:x.structureId,finishingPositions:S===As?[1]:void 0,linkType:S});y.push(t),h+=(P||0)-g}else h+=P||0;return S=M===ic?As:Es,m=x.structureId,f=F,c&&(_=Fg({structure:x})?.matchUps??[],_?.forEach(t=>{const{tieMatchUps:e}=BP({tieFormat:c,matchUp:t,isMock:d});Object.assign(t,{tieMatchUps:e,matchUpType:A})})),U.push(x),{qualifyingDrawPositionsCount:h,targetRoundQualifiersCount:g,finalQualifyingStructureId:m,finalQualifyingRoundNumber:f,finishingPositions:I,stageSequence:a+=1,linkType:S}}function OD(t){const{drawTypeCoercion:e,enforceMinimumDrawSize:n}=t,r=p(t.drawSize);let i=e&&!KS(t.drawType)&&("boolean"==typeof e||e<=2)&&2===r&&Ls||t.drawType||Ls;const o=mc.includes(i);if(r&&o)if(e&&("boolean"==typeof e&&r<4||r<=e))i=Ls;else if(r<4&&n)return{...Ci({context:{enforceMinimumDrawSize:n,drawSize:r,drawType:i},result:{error:Dt},stack:"getCoercedDrawType"}),drawType:i};return{drawType:i}}function kD(t){const{enforceMinimumDrawSize:e=!0,overwriteExisting:r,appliedPolicies:i,qualifyingOnly:o,staggeredEntry:a,drawDefinition:s,tieFormat:c,isMock:u,uuids:d}=t??{},l=p(t.drawSize),m=t.drawTypeCoercion??mD({appliedPolicies:i,drawType:t.drawType}),f=OD({drawType:t.drawType,enforceMinimumDrawSize:e,drawTypeCoercion:m,drawSize:l});if(f.error)return f;const h=f.drawType,g=[],I=[],y=t?.matchUpType??n,{existingQualifyingDrawPositionsCount:v,mainStructureIsPlaceholder:U,existingQualifyingLinks:P,existingMainStructure:T,existingQualifiersCount:w}=function({drawDefinition:t,structures:e}){const n=t?.structures?.filter(({stage:t})=>t===ds);n&&e.push(...n);const r=n?.map(({structureId:t})=>t),i=t?.structures?.find(({stage:t,stageSequence:e})=>t===us&&1===e),o=t?.links?.filter(t=>t.target.structureId===i?.structureId&&r?.includes(t.source.structureId)),a=n?.map(e=>{const n=o?.find(t=>t.target.structureId===e.structureId),r=cl({structure:e})?.positionAssignments?.length??0;if(!n)return r;const i=n?.source.structureId,a=t.structures?.find(t=>t.structureId===i);return r-(FD(n,a)||0)}).filter(Boolean).reduce((t,e)=>t+e,0),s=o?.map(t=>{const e=t.source.structureId,r=n?.find(t=>t.structureId===e);return FD(t,r)}).filter(Boolean).reduce((t,e)=>t+e,0),c=!(!i||i?.matchUps?.length);return{existingQualifyingDrawPositionsCount:a,mainStructureIsPlaceholder:c,existingQualifyingLinks:o,existingMainStructure:i,existingQualifiersCount:s}}({drawDefinition:s,structures:g});if(s?.structures?.filter(({stage:t})=>t===ds)?.length&&!U)return{error:yr};const D=!s?.structures?.filter(({stage:t})=>t===ds)?.length&&t.qualifyingProfiles,R=D?.length&&ED({idPrefix:t.idPrefix,qualifyingProfiles:D,appliedPolicies:i,qualifyingOnly:o,tieFormat:c,isMock:u,uuids:d});if(R?.error)return R;const{qualifyingDrawPositionsCount:b,qualifyingDetails:N,qualifiersCount:M}=R||{qualifyingDrawPositionsCount:v,qualifiersCount:w},A=M||t.qualifiersCount||0;b&&(R?.structures&&g.push(...R.structures),R?.links&&I.push(...R.links)),Object.assign(t,Ei({drawSize:l,matchUpType:y,tieFormat:c}));const E=function({drawType:t,drawSize:e,staggeredEntry:n}){return!(KS(t)||!(!e||e<2||[js,qs].includes(t)&&!S(e)&&e<5||!n&&![Fs,js,qs].includes(t)&&([oc,ic].includes(t)&&e<3||![ic,oc].includes(t)&&!S(e))))}({drawType:h,drawSize:l,staggeredEntry:a});if(E&&!b)return Ci({context:{drawSize:l,invalidDrawSize:E},result:{error:Dt},stack:"generateDrawStructuresAndLinks"});const{generators:C,error:O}=tU(t);if(O)return{error:O};const k=C[h];if(!k)return{error:St};const F=k?.();if(F.error)return F;const{structures:x,links:_}=F;if(x?.length){const t=function({mainStructureIsPlaceholder:t,existingMainStructure:e,generatedStructures:n,overwriteExisting:r,generatedLinks:i,structures:o}){const a=n.find(({stage:t,stageSequence:e})=>t===us&&1===e);if(e&&a)if(t)!function(t,e,n){const r=t.structureId;t.structureId=e;for(const t of n??[])t.source.structureId===r&&(t.source.structureId=e),t.target.structureId===r&&(t.target.structureId=e)}(a,e.structureId,i);else if(!r)return{error:yr};return void o.push(...n)}({mainStructureIsPlaceholder:U,existingMainStructure:T,generatedStructures:x,overwriteExisting:r,generatedLinks:_,structures:g});if(t?.error)return t}g.sort(rl),_?.length&&I.push(..._);const L=F.structures.find(({stage:t,stageSequence:e})=>t===us&&1===e);for(const t of N??[]){const{finalQualifyingRoundNumber:e,finalQualifyingStructureId:n,roundTarget:r,finishingPositions:i,linkType:o}=t,a=L&&LP({targetStructureId:L.structureId,sourceStructureId:n,sourceRoundNumber:e,finishingPositions:i,targetEntryRound:r,linkType:o})?.link;if(a?.error)return a;a&&I.push(a)}return P&&I.push(...P),{...Y,qualifyingResult:{qualifyingDrawPositionsCount:b,qualifiersCount:A},structures:g,links:I}}function FD(t,e){if(t.linkType===As&&e?.structures){const n=t.source.finishingPositions??[];return e.structures.length*n.length}if(t.linkType===Es&&e?.matchUps?.length){const n=t.source.roundNumber;return e.matchUps.filter(({roundNumber:t})=>t===n).length}}function xD(t){const{modifyOriginal:e=!0,isMock:r}=t??{},i="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return Ci({result:{error:st},stack:i});const o=e?t.drawDefinition:ca(t.drawDefinition,!1,!0);let{tieFormat:a,matchUpType:s}=t;if(a){const t=na({tieFormat:a});if(t.error)return t}a=mT(a??Rf({drawDefinition:o})?.tieFormat),s=s??(o.matchUpType||n),t.tieFormat=a,t.matchUpType=s;const c=HS({drawDefinition:o,stage:us});t.drawSize=t.drawSize??c;const u=new Set(bf({drawDefinition:o}).drawMatchUps.map(tl)),d=kD(t);if(d.error)return Ci({result:d,stack:i});const{structures:p,links:l}=d;o.structures=p,o.links=l;const m=t.drawSize??c;Object.assign(t,Ei({drawSize:m,matchUpType:s,tieFormat:a}));const{matchUps:f,matchUpsMap:h}=zg({drawDefinition:o});a&&f?.forEach(t=>{if(!u.has(t.matchUpId)){const{tieMatchUps:e}=BP({tieFormat:a,matchUp:t,isMock:r});Object.assign(t,{tieMatchUps:e,matchUpType:s})}});const{inContextDrawMatchUps:g}=rI({drawDefinition:o,matchUpsMap:h});return Ql({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:o}),{inContextDrawMatchUps:g,drawDefinition:o,matchUpsMap:h,...Y,structures:p,matchUps:f,links:l}}function _D(t){const{removePriorValues:e,tournamentRecord:n,participantId:r,scaleItem:i}=t;let o,a;if(!BD({scaleItem:i}))return{error:Jn};if(r&&Array.isArray(n.participants)&&(a=n.participants.find(t=>t.participantId===r),a)){if(a.participantType===hm&&i?.eventType!==os)return{error:Jn};const t=VD({removePriorValues:e,participant:a,scaleItem:i});if(t.error)return t;o=!t.valueChanged;const{topics:r}=gi();r.includes(bl)&&di({topic:bl,payload:{tournamentId:n.tournamentId,participants:[a]}})}return o&&{...Y,info:lr,existingValue:i?.scaleValue}||a&&{...Y,newValue:i?.scaleValue}||{error:un}}function LD(t){const{scaleItemsWithParticipantIds:e=[],removePriorValues:n,tournamentRecord:r,auditData:i,context:o}=t,a=dl({tournamentRecord:r},[Ic]);if(a.error)return a;if(!r.participants)return{error:an};const s=function(t){const e={};for(const n of t){const t=n?.participantId;if(Array.isArray(n?.scaleItems))for(const r of n.scaleItems){if(!BD({scaleItem:r}))return{error:Jn};Array.isArray(e[t])||(e[t]=[]),e[t].push(r)}}return e}(e);if(s.error)return s;const{modificationsApplied:c,modifiedParticipants:u,error:d}=function({participants:t,participantScaleItemsMap:e,removePriorValues:n}){let r=0;const i=[];for(const o of t){const{participantId:t}=o??{};if(Array.isArray(e[t]))for(const a of e[t]){if(o.participantType===hm&&a?.eventType!==os)return{error:Ci({context:{participantId:t,scaleItem:a,participantType:o.participantType},info:"Invalid participantType for eventType",result:{error:Jn}}),modificationsApplied:r,modifiedParticipants:i};VD({participant:o,scaleItem:a,removePriorValues:n}),i.push(o),r++}}return{modificationsApplied:r,modifiedParticipants:i,error:void 0}}({participants:r.participants,participantScaleItemsMap:s,removePriorValues:n});if(d)return d;const p=c?void 0:Zn,{topics:l}=gi();return l.includes(bl)&&c&&di({topic:bl,payload:{tournamentId:r.tournamentId,participants:u}}),function({context:t,tournamentRecord:e}){if(!t)return;const{eventId:n,drawId:r,...i}=t,o=i.scaleAttributes?.scaleType&&[i.scaleAttributes.scaleType];if(!Object.keys(i).length)return;const a={itemType:fl,itemValue:i};o&&(a.itemSubTypes=o);if(r||n){const{drawDefinition:t,event:i}=wg({tournamentRecord:e,eventId:n,drawId:r});r&&sP({drawDefinition:t,timeItem:a}),n&&oU({event:i,timeItem:a})}else iU({tournamentRecord:e,timeItem:a})}({context:o,tournamentRecord:r}),i&&l.includes(Il)&&di({topic:Il,payload:i}),Ei({...Y,modificationsApplied:c,info:p})}function BD({scaleItem:t}){const e=t&&Object.keys(t),n=["scaleType","eventType","scaleName"];return!!(n.filter(t=>e?.includes(t)).length===n.length)}function VD({removePriorValues:t,participant:e,scaleItem:n}){if(!e)return{error:on};const r=n&&Object.keys(n),i=["scaleType","eventType","scaleName"];if(!(i.filter(t=>r.includes(t)&&n[t]).length===i.length))return{error:Jn};const o=(new Date).toISOString();e.timeItems??=[];const{scaleItem:a}=Vd({scaleAttributes:n,participant:e}),s=t=>[void 0,null,""].includes(t),c=!(s(a?.scaleValue)&&s(n.scaleValue))&&JSON.stringify(a?.scaleValue)!==JSON.stringify(n.scaleValue);if(c){if(n.scaleDate&&"string"==typeof n.scaleDate&&!Do(n.scaleDate))return{error:_e};const{scaleType:r,eventType:i,scaleName:a}=n,s=[yu,r,i,a].join("."),c=Ei({itemValue:n.scaleValue,itemDate:n.scaleDate,createdAt:o,itemType:s});n.scaleId&&(c.itemSubTypes=[n.scaleId]),t&&(e.timeItems=e.timeItems.filter(t=>t.itemType!==s)),e.timeItems.push(c)}return{...Y,valueChanged:c,newValue:n.scaleValue}}function GD(t){const{tournamentRecord:e,modifiedScaleValues:n,removePriorValues:r}=t,i=fu(t,[{[Ic]:!0},{modifiedScaleValues:!0,[cu]:ru}]);if(i.error)return i;for(const t in n){const i=_D({scaleItem:n[t],removePriorValues:r,tournamentRecord:e,participantId:t});if(i.error)return i}return{...Y}}const jD={nSpread:400,diffThreshold:.125,kCalc:(t=0)=>250/Math.pow(t+5,.4),kMultiplier:function(t=3,e=2){const n=t/e;return Number.isNaN(n)?jD.kDefault():n},kDefault:()=>1};function qD(t){let{winnerRating:e,loserRating:n}=t;const{ratings:r=rp,winnerCountables:i=1,loserCountables:o=0,ratingType:a=jd,maxCountables:s,countables:c}=t??{},u=r?.[a];if(!u)return{error:Ae};const d=u.range||t.ratingRange;e=e||u.defaultInitialization,n=n||u.defaultInitialization;const p=d[0]>d[1],l=u.decimalsCount||0,m=p?d.slice().reverse():d,f=(t,e)=>Number.parseFloat(e)>=Math.min(...t)&&Number.parseFloat(e)<=Math.max(...t);f(d,e)&&f(d,n)||(f(d,e)||(e=u.defaultInitialization),f(d,n)||(n=u.defaultInitialization));const h=Gd({targetRange:rp[jd].range,sourceRange:m,value:p?d[0]-e:e}),g=Gd({targetRange:rp[jd].range,sourceRange:m,value:p?d[0]-n:n}),I=(t,e)=>1/(1+Math.pow(10,(e-t)/jD.nSpread)),S=I(h,g),y=I(g,h),v=jD.kCalc(i),U=jD.kCalc(o),P=jD.kMultiplier(s,c),T=h+P*v*(1-S),w=g+P*U*(0-y),D=Gd({sourceRange:rp[jd].range,value:T,targetRange:m}),R=Gd({sourceRange:rp[jd].range,value:w,targetRange:m}),b=p?d[0]-D:D;let N=Number.parseFloat(b.toFixed(l));const M=p?d[0]-R:R;let A=Number.parseFloat(M.toFixed(l));const E=Math.max(...d)?Math.abs(e-n)/Math.max(...d):0;return(D>R&&E>jD.diffThreshold||N<0||A<0)&&(N=e,A=n),{newWinnerRating:N,newLoserRating:A}}const WD=t=>t?.reduce((t,e)=>(e.winningSide&&(t[e.winningSide-1]+=1),t),[0,0])||[0,0];function $D(t){const e=fu(t,[{[Ic]:!0},{matchUpIds:!0,[cu]:iu,[Hc]:he},{ratingType:!1,[ou]:t=>rp[t]}]);if(e.error)return e;const{updateParticipantRatings:n,removePriorValues:r=!0,tournamentRecord:i,ratingType:o=jd,convertToELO:a,refreshDynamic:s,considerGames:c,drawDefinition:u,matchUpIds:d,asDynamic:p}=t,l=rp[o],m=a&&o!==jd,f=m?jd:o,h=rp[f],g=l.accessor,I=h.accessor,S={},y=(t.matchUps||s&&Zg({drawDefinition:u,tournamentRecord:i,inContext:!0,matchUpFilters:{matchUpStatuses:_p}}).matchUps||Qg({matchUpFilters:{matchUpIds:d,matchUpStatuses:_p},tournamentRecord:i,inContext:!0}).matchUps)??[],v=`${f}.${gu}`,U=p?v:f;y.sort(Xg);for(const t of y){const{endDate:e,matchUpFormat:a,score:u,sides:d,winningSide:p}=t,l=t.matchUpType,h={eventType:l,scaleName:o,scaleType:Su},y={scaleName:v,eventType:l,scaleType:Su},P=m?{scaleName:`${o}.${gu}`,eventType:l,scaleType:Su}:void 0,T=Object.assign({},...(d??[]).map(t=>{const{sideNumber:e,participant:n}=t;return e&&{[e]:[n?.participantId,...n?.individualParticipantIds??[]].filter(Boolean).flat()}})),w=Object.assign({},...Object.values(T).flat().map(t=>HD({participantId:t,modifiedScaleValues:S,refreshDynamic:s,dynamicScaleAttributes:y,sourceDynamicScaleAttributes:P,scaleAttributes:h,tournamentRecord:i,sourceAccessor:g,outputScaleName:U,ratingType:o,isEloNative:m,accessor:I,matchUpType:l,endDate:e}))),D=a?co(a):{},R=D?.bestOf||1,b=c?R&(D?.setsTo||1):R,N=u?.sets&&WD(u.sets)||1===p&&[1,0]||[0,1];zD({sideParticipantIds:T,computeRatingType:f,outputScaleName:U,scaleItemMap:w,winningSide:p,countables:N,maxCountables:b,accessor:I}),Object.assign(S,w),n&&GD({tournamentRecord:i,modifiedScaleValues:S,removePriorValues:r})}const P=y.map(({matchUpId:t})=>t);return{...Y,modifiedScaleValues:S,outputScaleName:U,processedMatchUpIds:P,...m&&{sourceRatingType:o}}}function HD({participantId:t,modifiedScaleValues:e,refreshDynamic:n,dynamicScaleAttributes:r,sourceDynamicScaleAttributes:i,scaleAttributes:o,tournamentRecord:a,sourceAccessor:s,outputScaleName:c,ratingType:u,isEloNative:d,accessor:p,matchUpType:l,endDate:m}){const f=e[t],h=!n||f;let g=h?_S({scaleAttributes:r,tournamentRecord:a,participantId:t}).scaleItem:void 0;!g&&i&&h&&(g=function({sourceDynamicScaleAttributes:t,tournamentRecord:e,participantId:n,sourceAccessor:r,outputScaleName:i,ratingType:o}){const a=_S({scaleAttributes:t,tournamentRecord:e,participantId:n}).scaleItem;if(!a)return;const s=a.scaleValue,c=r&&"object"==typeof s?s[r]:s;if(null!=c)return{...a,scaleName:i,scaleValue:ip({sourceRatingType:o,sourceRating:c})};return}({sourceDynamicScaleAttributes:i,tournamentRecord:a,participantId:t,sourceAccessor:s,outputScaleName:c,ratingType:u}));const I=_S({tournamentRecord:a,scaleAttributes:o,participantId:t}).scaleItem;let S=g??I;if(!g&&I&&d){const t=I.scaleValue,e=s&&"object"==typeof t?t[s]:t;null!=e&&(S={...I,scaleName:c,scaleValue:ip({sourceRatingType:u,sourceRating:e})})}const y=p?{[p]:void 0}:void 0;return t&&{[t]:S??{scaleName:c,eventType:l,scaleDate:m,scaleType:Su,scaleValue:y}}}function zD({sideParticipantIds:t,computeRatingType:e,outputScaleName:n,scaleItemMap:r,winningSide:i,countables:o,maxCountables:a,accessor:s}){const c=i?t[i]:[],u=i?t[3-i]:[];for(const t of c){const c=r[t]?.scaleValue,d="object"==typeof c?c[s]:c;for(const p of u){const u=r[p]?.scaleValue,l="object"==typeof u?u[s]:u,m=i?o[i]:[0,0],f=i?o[3-i]:[0,0],{newWinnerRating:h,newLoserRating:g}=qD({ratingType:e,winnerCountables:m,loserCountables:f,maxCountables:a,winnerRating:d,loserRating:l}),I=s?{...c,[s]:h}:h,S=s?{...u,[s]:g}:g;r[t].scaleValue=I,r[p].scaleValue=S,r[t].scaleName=n,r[p].scaleName=n}}}function YD(t){const{matchUpIds:e=[],drawDefinition:n,roundNumber:r,newRound:i,isMock:o,event:s}=t;if("object"!=typeof n)return{error:st};let{participantIdPairings:c,matchUpsCount:u}=t;const d=JT(t);if(d.error)return Ci({result:d});const{lastRoundNumber:p,availableMatchUpsCount:l=0,roundMatchUpsCount:m=0}=d;if(u){if(u>m&&!1!==t.restrictMatchUpsCount)return Ci({result:{error:sr,info:"matchUpsCount error",context:{roundMatchUpsCount:m}}})}else i?u=m:l>0&&(u=l);if(c&&!Array.isArray(c)||u&&!R(u)||e&&!Array.isArray(e)||!c&&!u)return{error:sr,info:"matchUpsCount or pairings error"};if(u&&!1!==t.restrictMatchUpsCount&&u>32)return{error:sr,info:"matchUpsCount must be less than 33"};if(r&&!t.ignoreLastRoundNumber&&r-1>(p||0))return{error:sr,info:"roundNumber error"};const f=r??(i&&(p??0)+1||p||1);c=c??L(0,u).map(()=>({participantIds:[void 0,void 0]}));const h=c?.map((r,i)=>{const o=r?.participantIds??[void 0,void 0];o.push(void 0,void 0);const a=o.slice(0,2).map((t,e)=>Ei({sideNumber:e+1,participantId:t})),s=e[i]??(e=>{if(!t.idPrefix)return;return`${n.drawId}-${t.idPrefix??"ah"}-${f}-${e}`})(i)??pa();return{roundNumber:f,matchUpStatus:Ap,matchUpId:s,sides:a}});if(h?.length){const t=Rf({drawDefinition:n,event:s})?.tieFormat;t&&h.forEach(e=>{const{tieMatchUps:n}=BP({tieFormat:t,matchUp:e,isMock:o});Object.assign(e,{tieMatchUps:n,matchUpType:a})})}return{roundNumber:f,matchUpsCount:h?.length??0,matchUps:h,...Y}}function KD(t){return t.participantIdPairings.map(({participantIds:t})=>t.sort().join("|")).sort().join("/")}function QD({valueSortedPairings:t,stipulated:e=[],pairingValueMap:n,deltaObjects:r,valueObjects:i,actorsCount:o,random:a}){const s=a??Math.random,c=e.flat(),u=[];let d=0;e.filter(Boolean).forEach(t=>{const[e,r]=t,i=JD(e,r),o=n[i];u.push({participantIds:t,value:o}),d+=n[i]});q(t,o).flatMap(t=>A(t,a).map(t=>({...t,value:t.value+s()*Math.round(s())}))).forEach(t=>{const e=t.pairing.split("|");if(!e.reduce((t,e)=>c.includes(e)||t,!1)){c.push(...e);const n=t.value;d+=n,u.push({participantIds:e,value:n})}}),u.sort((t,e)=>t.value-e.value);const p=u.reduce((t,e)=>{const[n,i]=e.participantIds,o=JD(n,i),a=r[o];return Math.max(a,t)},0),l=u.reduce((t,e)=>{const[n,r]=e.participantIds,o=JD(n,r),a=i[o];return Math.max(a,t)},0);return{value:d,participantIdPairings:u,maxDelta:p,maxDiff:l}}function JD(t,e){return[t,e].sort(TS).join("|")}function XD({participantIds:t}){const e={},n=[];t.forEach(r=>{e[r]=t.filter(t=>t!==r),e[r].forEach(t=>{const e=JD(t,r);n.includes(e)||n.push(e)})});const r=Object.assign({},...n.map(t=>({[t]:0})));return{uniquePairings:n,possiblePairings:e,deltaObjects:r}}function ZD({matchUps:t}){const e=[];for(const n of t){const t=n.sides.map(Xp);if(2===t.length){const[n,r]=t,i=JD(n,r);e.includes(i)||e.push(i)}}return{encounters:e}}function tR(t){const{tournamentParticipants:e,adHocRatings:n={},possiblePairings:r,uniquePairings:i,maxIterations:o,minimizeDelta:a,deltaObjects:s,valueObjects:c,eventType:u,scaleName:d,salted:p}=t;i.forEach(r=>{const i=function({tournamentParticipants:t,adHocRatings:e,eventType:n,scaleName:r,pairing:i}){const o=rp[r]?.defaultInitialization??0;return i.split("|").map(r=>{if(n===ns){const n=t?.find(t=>t.participantId===r)?.individualParticipantIds;return n?n?.map(t=>e[t]||o):2*o}return e[r]||o})}({tournamentParticipants:e,adHocRatings:n,scaleName:d,eventType:u,pairing:r}),o="number"==typeof p&&p||.5,a=t.random??Math.random,l=p&&(Math.round(a())?o:-1*o)||0,m=Math.abs(i[0]-i[1])+l,f=Math.abs(i[0]-i[1]);s[r]=f,c[r]||(c[r]=0),c[r]+=m?Math.pow(m,2):0});const l=i.map(t=>({pairing:t,value:c[t]})).sort((t,e)=>t.value-e.value),{pairingValues:m}=function({possiblePairings:t,valueObjects:e}){const n={};for(const e of Object.keys(t)){const i=t[e].map(t=>r(e,t));n[e]=i.sort((t,e)=>t.value-e.value)}function r(t,n){const r=JD(t,n);return{opponent:n,value:e[r]}}return{pairingValues:n}}({possiblePairings:r,valueObjects:c}),{candidate:f,candidatesCount:h,deltaCandidate:g,iterations:I}=function({maxIterations:t=4e3,valueSortedPairings:e,pairingValues:n,valueObjects:r,deltaObjects:i,random:o}){const a=o??Math.random,s=Object.assign({},...e.map(t=>({[t.pairing]:t.value}))),c=Object.keys(n);let u=[];const d=QD({actorsCount:c.length,valueSortedPairings:e,pairingValueMap:s,deltaObjects:i,valueObjects:r,random:o}),p=[KD(d)];u.push(d);let l,m=d.value,f=d,h=1,g=0,I=c.length;do{I-=1,l=c.length*n[c[0]].length}while(l>t&&I>5);const S=[];c.forEach(t=>{n[t].slice(0,I).forEach(n=>{g+=1;const d=JD(t,n.opponent);if(!S.includes(d)){const l=QD({stipulated:[[t,n.opponent]],actorsCount:c.length,valueSortedPairings:e,pairingValueMap:s,deltaObjects:i,valueObjects:r,random:o});if(!p.includes(KD(l))){p.push(KD(l)),u.push(l);const{maxDelta:t,value:e}=l;t<f.maxDelta&&(f=l),(e<m||e===m&&Math.round(a()))&&(m=e),S.push(d),h+=1}}}),u=u.filter(t=>Math.abs(t.value-m)<5)}),u.sort((t,e)=>t.maxDiff-e.maxDiff);const y=x(u,o);return{candidatesCount:h,deltaCandidate:f,maxIterations:t,iterations:g,candidate:y}}({random:t.random,valueSortedPairings:l,maxIterations:o,pairingValues:m,deltaObjects:s,valueObjects:c}),{participantIdPairings:S}=a?g:f;return{participantIdPairings:S,candidatesCount:h,deltaCandidate:g,iterations:I,candidate:f}}const eR=100,nR=100,rR=4e3;function iR(t){const{encounterValue:e=eR,sameTeamValue:n=nR,maxIterations:r=rR,updateParticipantRatings:i,generateMatchUps:o=!0,ignoreLastRoundNumber:a,iterationMatchUps:s,tournamentRecord:c,dynamicRatings:u,convertToELO:d,refreshDynamic:p,participantIds:l,drawDefinition:m,roundNumber:h,structureId:g,matchUpIds:I,eventType:S,scaleName:y,idPrefix:v,isMock:U,salted:P,event:T}=t;if(!m)return{error:st};if(!t.structure&&!g)return{error:Vt};const w=t.structure||ol({drawDefinition:m,structureId:g}).structure;if(!f(w))return{error:jt};if(!l?.length)return{error:ln};const D=[...s??[],...w?.matchUps??[]],{encounters:R}=ZD({matchUps:D}),b=c?.participants??[];let N,A={};const{competitionPolicy:E}=Ld({tournamentRecord:c,drawDefinition:m,event:T}),{competitionState:C}=E?pp({drawDefinition:m}):{competitionState:void 0};if(E&&C&&"DYNAMIC_FORM"===E.pairingPolicy.ratingSource)for(const[t,e]of Object.entries(C.participantStates))A[t]=e.dynamicFormRating;else if(u){const t=M(w?.matchUps?w.matchUps.map(({roundNumber:t})=>t):[]),e=Math.max(...t,0);if(e){const t=w?.matchUps?.filter(({roundNumber:t})=>t===e).map(({matchUpId:t})=>t),n=$D({ratingType:y??T?.category?.ratingType,updateParticipantRatings:i,tournamentRecord:c,asDynamic:!0,convertToELO:d,refreshDynamic:p,drawDefinition:m,matchUpIds:t});if(n.error)return n;n.modifiedScaleValues&&(A=n.modifiedScaleValues),n.sourceRatingType&&(N=n.sourceRatingType)}}const{valueObjects:O}=function({encounters:t,tournamentParticipants:e,encounterValue:n,sameTeamValue:r}){const i={};for(const e of t)i[e]||(i[e]=0),i[e]+=n;const o=e?.filter(({participantType:t})=>t===ym);if(o)for(const t of o){const e=t.individualParticipantIds??[],{uniquePairings:n}=XD({participantIds:e});for(const t of n)i[t]||(i[t]=0),i[t]+=r}return{valueObjects:i}}({tournamentParticipants:b,encounterValue:e,sameTeamValue:n,encounters:R}),{uniquePairings:k,possiblePairings:F,deltaObjects:x}=XD({participantIds:l}),_={tournamentParticipants:b,possiblePairings:F,uniquePairings:k,maxIterations:r,adHocRatings:Object.values(A).length?A:t.adHocRatings,deltaObjects:x,valueObjects:O,random:t.random,eventType:S,scaleName:y,salted:P},{candidatesCount:L,participantIdPairings:B,deltaCandidate:V,iterations:G,candidate:j}=tR(_);if(!L)return{error:er};let q,W;if(o){const t=YD({structureId:w?.structureId,ignoreLastRoundNumber:a,participantIdPairings:B,newRound:!0,drawDefinition:m,roundNumber:h,matchUpIds:I,idPrefix:v,isMock:U,event:T});if(t.error)return t;q=t.roundNumber,W=t.matchUps}const{maxDelta:$,maxDiff:H}=j;return{roundNumber:q,participantIdPairings:B,modifiedScaleValues:A,sourceRatingType:N,candidatesCount:L,deltaCandidate:V,...Y,iterations:G,matchUps:W,maxDelta:$,maxDiff:H}}function oR(t){const{drawType:e=Ls,applyPositioning:n=!0,tournamentRecord:r,staggeredEntry:i,automated:o,placeByes:a,isMock:s,event:c}=t;let u=t?.drawDefinition;if(!u)return{error:st};const d=ls,p=Pf({entryStatuses:hf,stageSequence:1,drawDefinition:u,stage:d}),l=[ic,Bs,oc,js].includes(e)?p.length:w(p.length);if(!i&&e===Fs&&p.length<2||e===ic&&p.length<3)return{error:Dt};let{tieFormat:m,matchUpType:f}=t;if(m){const t=na({tieFormat:m});if(t.error)return t}m=mT(m??Rf({drawDefinition:u})?.tieFormat),f=f??u.matchUpType;const{structures:h}=al({stageSequence:1,drawDefinition:u,stage:d});if(h.length>1)return{error:te};if(h?.[0]?.matchUps?.length)return{error:vr};const g=h?.[0]?.structureId;Object.assign(t,Ei({structureName:t.structureName??Ny(ls),structureId:g,matchUpType:f,tieFormat:m,drawSize:l,stage:d}));const I=tU(t);if(I.error)return I;const S=I.generators[e];if(!S)return{error:St};const y=S?.();if(y.error)return y;const{structures:v,links:U}=y,P=v.flatMap(t=>Fg({structure:t}).matchUps);m&&P.forEach(t=>{const{tieMatchUps:e}=BP({matchUp:t,tieFormat:m,isMock:s});Object.assign(t,{tieMatchUps:e,matchUpType:f})});const T=ca(u,!1,!0);T.links??=[],U.length&&T.links.push(...U);const D=new Set(v.map(({structureId:t})=>t));T.structures??=[];const R=new Set(T.structures.map(({structureId:t})=>t));T.structures=T.structures.map(t=>D.has(t.structureId)?v.find(({structureId:e})=>e===t.structureId):t);const b=v.filter(({structureId:t})=>!R.has(t));if(b.length&&T.structures.push(...b),o&&n){const e=v[0],i=(e?.structures?.length||0)>1;JU({structureId:g||e?.structureId,seedingProfile:t.seedingProfile,drawDefinition:T,random:t.random,multipleStructures:i,applyPositioning:n,tournamentRecord:r,placeByes:a,event:c})}return{links:U,structures:T.structures.filter(({structureId:t})=>D.has(t)),...Y}}function aR(t){const{winnerFirst:e=!0,setTBlast:n=!0,addOutcomeString:r,reversed:i=!1,matchUpStatus:o,matchUpFormat:a,autoComplete:s,winningSide:c,sets:u}=t;if(!u)return{error:Ae,info:"missing sets"};const d=a&&co(a),{bestOf:p,finalSetFormat:l,setFormat:m}=d??{},f=i||!(!e||!c||1===c),h=r?function({matchUpStatus:t}){const e={[Np]:"RET",[Ep]:"WO",[Tp]:"DF/DF",[wp]:"WO/WO",[Mp]:"SUS",[gp]:"ABN",[Pp]:"DEF",[Up]:"DR"};return t&&e[t]||""}({matchUpStatus:o}):"",g=u?.sort(sR).map(function(t){const e=p&&t.setNumber===p&&l?l:m,r=t=>P(t?.side1Score)||P(t?.side2Score),i=(I=t,P(I?.side1TiebreakScore)||P(I?.side2TiebreakScore)),o=e?.tiebreakSet||!r(t)&&i,{side1Score:a,side2Score:c,side1TiebreakScore:u,side2TiebreakScore:d}=t,h=u||(P(u)||i&&s?0:""),g=d||(P(d)||i&&s?0:"");var I;if(o){const e=r(t)&&!i,n=e?a:h,o=e?c:g;return`[${(f?[o,n]:[n,o]).join("-")}]`}const S=i?Math.min(h,g):"",y=S===h?1:2,v=P(S)?`(${S})`:"",U=a||(P(a)||s?0:""),T=c||(P(c)||s?0:""),w=t=>n||y!==t?"":v,D=`${U}${w(1)}`,R=`${T}${w(2)}`,b=n&&i?`(${S})`:"";let N=f?`${[R,D].join("-")}${b}`:`${[D,R].join("-")}${b}`;["-"," "].includes(N)&&(N="");return N}).filter(Boolean).join(" ")||"";return h?2===c?`${h} ${g}`:`${g} ${h}`:g}function sR(t,e){return t.setNumber-e.setNumber}function cR(t){if(!t?.score)return{error:Ae};const{sets:e}=t.score,n=e.map(t=>{const{side1TiebreakScore:e,side2TiebreakScore:n,side1PointScore:r,side2PointScore:i,winningSide:o,side1Score:a,side2Score:s,setNumber:c}=t;return Ei({winningSide:o?3-o:void 0,side1TiebreakScore:n,side2TiebreakScore:e,side1PointScore:i,side2PointScore:r,side1Score:s,side2Score:a,setNumber:c})}),r=t?.setTBlast;return{reversedScore:{sets:n,scoreStringSide1:aR({setTBlast:r,sets:n}),scoreStringSide2:aR({sets:n,reversed:!0,setTBlast:r})},...Y}}const uR={A:"Ace",D:"Double Fault",S:"Serve Winner",R:"Return Winner",W:"Winner",E:"Unforced Error",F:"Forced Error"},dR=new Set(["A","S"]),pR=new Set(["D","R","E","F"]);function lR(t,e){const n={...t};return n.server=e.server,n.index=e.index,n.set=e.set,n.game=e.game,n.code&&!n.winner&&(n.winner=function(t,e){if(dR.has(t))return e;if(pR.has(t))return 1-e;return e}(n.code,e.server)),n.code&&!n.result&&(n.result=uR[n.code]),n.first_serve?n.serve=2:n.serve||(n.serve=1),n}function mR(t,e){const n={players:{},teams:{}};for(let t=0;t<2;t++)n.players[t]={},n.teams[t]={};let r,i=t;return void 0!==e?.setFilter&&(i=t.filter(t=>t.set===e.setFilter)),i.forEach((t,e)=>{if(void 0===t.winner)return void($r()&&console.warn("Point missing winner:",t));const{winner:i,loser:o}=function(t){const e=[],n=[],r=t.result?.toLowerCase()||"";return r.includes("ace")&&e.push("aces"),(r.includes("winner")||r.includes("ace"))&&e.push("winners"),r.includes("double fault")&&n.push("doubleFaults"),r.includes("unforced error")&&n.push("unforcedErrors"),r.includes("forced error")&&n.push("forcedErrors"),t.winner===t.server?(e.push("servesWon"),1===t.serve?e.push("serves1stWon"):2===t.serve&&e.push("serves2ndWon")):(e.push("returns"),1===t.serve?e.push("received1stWon"):2===t.serve&&e.push("received2ndWon")),e.push("pointsWon"),{winner:e,loser:n}}(t),a=t.winner,s=1-a;hR(n,a,i,t),hR(n,s,o,t),function(t,e){if(void 0===e.server)return;const n=e.server;fR(t.teams,n,"pointsServed",e),1===e.serve?fR(t.teams,n,"serves1stIn",e):2===e.serve&&fR(t.teams,n,"serves2ndIn",e)}(n,t),function(t,e,n,r){e.hand&&fR(t.teams,n,e.hand,{point:e,index:r})}(n,t,a,e),function(t,e,n){if(!function(t,e){if(!e)return!1;if(void 0!==t.game&&void 0!==e.game)return t.game!==e.game;return!1}(e,n)||void 0===n?.winner)return;const r=n.winner;fR(t.teams,r,"gamesWon",n),fR(t.players,r,"gamesWon",n)}(n,t,r),function(t,e,n){if(!e.breakpoint)return;const r=e.server;fR(t.teams,r,"breakpointsFaced",e),n===r&&fR(t.teams,r,"breakpointsSaved",e)}(n,t,a),r=t}),n}function fR(t,e,n,r){t[e][n]||(t[e][n]=[]),t[e][n].push(r)}function hR(t,e,n,r){n.forEach(n=>{fR(t.teams,e,n,r),fR(t.players,e,n,r)})}function gR(t,e,n){switch(t.calc){case"number":return function(t,e,n){const r=IR(t.numerators,e,n);return{value:r,display:String(r),numerators:t.numerators}}(t,e,n);case"percentage":return function(t,e,n){const r=IR(t.numerators,e,n),i=IR(t.denominators??[],e,n);if(!i)return{value:0,display:"0",numerators:t.numerators};const o=Math.round(r/i*100);return{value:o,display:`${o}% (${r}/${i})`,numerators:t.numerators}}(t,e,n);case"maxConsecutive":return function(t,e,n){const r=t.numerators[0],i=t.attribute||"index";if(!e[n][r])return{value:0,display:"0"};const o=e[n][r];let a,s=0,c=o.length?1:0;o.forEach(t=>{const e=t[i];void 0!==a&&e===a+1?c++:(c>s&&(s=c),c=1),a=e}),c>s&&(s=c);return{value:s,display:String(s)}}(t,e,n);case"difference":return function(t,e,n){const r=IR(t.numerators,e,n),i=IR(t.denominators??[],e,n);if(!i)return{value:0,display:"0",numerators:t.numerators};const o=Math.abs(i-r),a=Math.round(o/i*100);return{value:a,display:`${a}% (${o}/${i})`,numerators:t.numerators}}(t,e,n);case"aggressiveMargin":return function(t,e,n){const r=IR(t.denominators??[],e,n),i=IR(t.numerators,e,n),o=r-i;return{value:o,display:String(o)}}(t,e,n)}}function IR(t,e,n){return t?t.reduce((t,r)=>{const i=r.startsWith("-");r.includes("*");let o=r.replace("-","").replace("*","");const a=i?1-n:n,s=e[a]?.[o];return s?t+s.length:t},0):0}function SR(t,e,n){const r=mR(e??[],n),i=function(t){if(!t?.teams)return[];const e=[];return Object.values({Aces:{category:"Aces",numerators:["aces"],calc:"number"},"Double Faults":{category:"Double Faults",numerators:["doubleFaults"],calc:"number"},Winners:{category:"Winners",numerators:["winners"],calc:"number"},"Unforced Errors":{category:"Unforced Errors",numerators:["unforcedErrors"],calc:"number"},"Forced Errors":{category:"Forced Errors",numerators:["forcedErrors"],calc:"number"},"Total Points Won":{category:"Total Points Won",numerators:["pointsWon"],calc:"number"},"Max Pts/Row":{category:"Max Pts/Row",numerators:["pointsWon"],calc:"maxConsecutive",attribute:"index"},"Max Games/Row":{category:"Max Games/Row",numerators:["gamesWon"],calc:"maxConsecutive",attribute:"game"},"First Serve %":{category:"First Serve %",numerators:["serves1stIn"],denominators:["pointsServed"],calc:"percentage"},"Points Won 1st":{category:"Points Won 1st",numerators:["serves1stWon"],denominators:["serves1stIn"],calc:"percentage"},"Points Won 2nd":{category:"Points Won 2nd",numerators:["serves2ndWon"],denominators:["serves2ndIn"],calc:"percentage"},"Points Won Receiving":{category:"Points Won Receiving",numerators:["received1stWon","received2ndWon"],denominators:["-pointsServed"],calc:"percentage"},"Breakpoints Saved":{category:"Breakpoints Saved",numerators:["breakpointsSaved"],denominators:["breakpointsFaced"],calc:"percentage"},"Breakpoints Converted":{category:"Breakpoints Converted",numerators:["-breakpointsSaved"],denominators:["-breakpointsFaced"],calc:"difference"},"Games Won":{category:"Games Won",numerators:["gamesWon"],calc:"number"},"Service Points Won":{category:"Service Points Won",numerators:["servesWon"],denominators:["pointsServed"],calc:"percentage"},"Aggressive Margin":{category:"Aggressive Margin",numerators:["*doubleFaults","*unforcedErrors"],denominators:["*aces","*winners","-*forcedErrors"],calc:"aggressiveMargin"}}).forEach(n=>{const r=[gR(n,t.teams,0),gR(n,t.teams,1)];0===r[0].value&&0===r[1].value||e.push({category:n.category,teams:r})}),e}(r),o=function(t){const e={totalPoints:0,byTeam:[0,0],byCategory:{}};for(let n=0;n<2;n++)if(t.teams[n].pointsWon){const r=t.teams[n].pointsWon.length;e.byTeam[n]=r,e.totalPoints+=r}const n=new Set;for(let e=0;e<2;e++)Object.keys(t.teams[e]).forEach(t=>n.add(t));return n.forEach(n=>{e.byCategory[n]=0;for(let r=0;r<2;r++)t.teams[r][n]&&(e.byCategory[n]+=t.teams[r][n].length)}),e}(r);return{counters:r,calculated:i,summary:o}}function yR(t){if(!t)return[];const e=[];return t.forEach((t,n)=>{const r=lR(t,{server:0,index:n,set:0,game:0});e.push(r)}),e}function vR(t,e){const n=mR(t??[],e);return{aces:[n.teams[0].aces?.length||0,n.teams[1].aces?.length||0],doubleFaults:[n.teams[0].doubleFaults?.length||0,n.teams[1].doubleFaults?.length||0],winners:[n.teams[0].winners?.length||0,n.teams[1].winners?.length||0],unforcedErrors:[n.teams[0].unforcedErrors?.length||0,n.teams[1].unforcedErrors?.length||0],totalPoints:[n.teams[0].pointsWon?.length||0,n.teams[1].pointsWon?.length||0]}}function UR(t,e,n){return t.teams[e]?.[n]?.length??0}function PR(t,e){return e&&t?Number.parseFloat((t/e*100).toFixed(2)):0}function TR(t,e,n){const r=t.find(t=>t.category===e);return r?.teams[n]?.value??0}function wR(t){if(!t?.counters?.teams)return[];const{counters:e,calculated:n}=t,r=[];r.push({name:"Aces",numerator:[UR(e,0,"aces"),UR(e,1,"aces")],default:"numerator"},{name:"Double Faults",numerator:[UR(e,0,"doubleFaults"),UR(e,1,"doubleFaults")],default:"numerator"});const i=[UR(e,0,"serves1stWon"),UR(e,1,"serves1stWon")],o=[UR(e,0,"servesWon"),UR(e,1,"servesWon")];if(i[0]+i[1]>0&&(o[0]!==i[0]||o[1]!==i[1])){const t=[UR(e,0,"pointsServed"),UR(e,1,"pointsServed")],n=[UR(e,0,"serves1stIn"),UR(e,1,"serves1stIn")],o=[UR(e,0,"serves2ndWon"),UR(e,1,"serves2ndWon")],a=[UR(e,0,"serves2ndIn"),UR(e,1,"serves2ndIn")];r.push({name:"1st Serve In",numerator:n,denominator:t,pct:[PR(n[0],t[0]),PR(n[1],t[1])]},{name:"1st Serve Points Won",numerator:i,denominator:n,pct:[PR(i[0],n[0]),PR(i[1],n[1])]},{name:"2nd Serve Points Won",numerator:o,denominator:a,pct:[PR(o[0],a[0]),PR(o[1],a[1])]})}r.push({name:"Total Points Won",numerator:[UR(e,0,"pointsWon"),UR(e,1,"pointsWon")],default:"numerator"});const a=UR(e,0,"received1stWon")+UR(e,0,"received2ndWon"),s=UR(e,1,"received1stWon")+UR(e,1,"received2ndWon"),c=UR(e,1,"pointsServed"),u=UR(e,0,"pointsServed");r.push({name:"Receiving Points Won",numerator:[a,s],denominator:[c,u],pct:[PR(a,c),PR(s,u)]});const d=UR(e,1,"breakpointsFaced")-UR(e,1,"breakpointsSaved"),p=UR(e,0,"breakpointsFaced")-UR(e,0,"breakpointsSaved"),l=UR(e,1,"breakpointsFaced"),m=UR(e,0,"breakpointsFaced");r.push({name:"Break Points Won",numerator:[d,p],denominator:[l,m],pct:[PR(d,l),PR(p,m)]});const f=UR(e,0,"breakpointsSaved"),h=UR(e,1,"breakpointsSaved"),g=UR(e,0,"breakpointsFaced"),I=UR(e,1,"breakpointsFaced");r.push({name:"Break Points Saved",numerator:[f,h],denominator:[g,I],pct:[PR(f,g),PR(h,I)]},{name:"Winners",numerator:[UR(e,0,"winners"),UR(e,1,"winners")],default:"numerator"},{name:"Unforced Errors",numerator:[UR(e,0,"unforcedErrors"),UR(e,1,"unforcedErrors")],default:"numerator"},{name:"Forced Errors",numerator:[UR(e,0,"forcedErrors"),UR(e,1,"forcedErrors")],default:"numerator"});const S=o,y=[UR(e,0,"pointsServed"),UR(e,1,"pointsServed")];return r.push({name:"Service Points Won",numerator:S,denominator:y,pct:[PR(S[0],y[0]),PR(S[1],y[1])]},{name:"Games Won",numerator:[UR(e,0,"gamesWon"),UR(e,1,"gamesWon")]},{name:"Most Consecutive Points Won",numerator:[TR(n,"Max Pts/Row",0),TR(n,"Max Pts/Row",1)]},{name:"Most Consecutive Games Won",numerator:[TR(n,"Max Games/Row",0),TR(n,"Max Games/Row",1)]}),r}function DR(t){return!!t&&!!t.aggregate}function RR(t,e){const n=t.bestOf||t.exactly||3,r=Math.ceil(n/2);if(e[0]===r-1&&e[1]===r-1&&t.finalSetFormat){const e=t.finalSetFormat;return e.tiebreakSet?"matchTiebreak":e.timed?"timed":"standard"}const i=t.setFormat;return i?i.tiebreakSet?"tiebreakOnly":i.timed?"timed":"standard":"standard"}function bR(t){const{matchUpId:e=pa(),matchUpFormat:n,participants:r=[],isDoubles:i=!1,matchUpType:o}=t,a=o||(i?"DOUBLES":"SINGLES"),s=r.map((t,e)=>({sideNumber:e+1,participantId:t.participantId,participant:t}));0===s.length&&s.push({sideNumber:1},{sideNumber:2});return{matchUpId:e,matchUpFormat:n,matchUpStatus:"TO_BE_PLAYED",matchUpType:a,sides:s,score:{sets:[]},createdAt:(new Date).toISOString()}}function NR(t,e){const n=t.score.sets;if(0===n.length)return"0-0";const r=e?.perspective,i=n.map(t=>{let e=t.side1Score||0,n=t.side2Score||0;if(1===r&&([e,n]=[n,e]),void 0!==t.side1TiebreakScore||void 0!==t.side2TiebreakScore){let i=t.side1TiebreakScore||0,o=t.side2TiebreakScore||0;return 1===r&&([i,o]=[o,i]),e>n?`${e}-${n}(${o})`:`${e}(${i})-${n}`}return`${e}-${n}`}),o=n.at(-1);if("IN_PROGRESS"===t.matchUpStatus&&o&&!o.winningSide){const e=o.side1GameScores??[],n=e.length-1;if(n>=0&&e.length>0){let a=e[n]||0,s=(o.side2GameScores??[])[n]||0;if(0===a&&0===s)return i.join(", ");1===r&&([a,s]=[s,a]);const c=o.side1Score||0,u=o.side2Score||0,d=t.matchUpFormat?co(t.matchUpFormat):void 0,p=d?.setFormat?.setTo||6,l=("number"==typeof d?.setFormat?.tiebreakAt?d.setFormat.tiebreakAt:void 0)??p,m=c===l&&u===l,f="CONSECUTIVE"===d?.gameFormat?.type,h=i.at(-1),g=`${i.slice(0,-1).join(", ")}${i.length>1?", ":""}${h}`;if(m||f)return`${g} (${a}-${s})`;{const t=function(t,e){const n=["0","15","30","40"];if(t<=3&&e<=3)return`${n[t]}-${n[e]}`;if(t>=3&&e>=3){const n=t-e;return 0===n?"40-40":1===n?"A-40":-1===n?"40-A":n>=2?"G-40":"40-G"}if(t>=3)return"G-40";if(e>=3)return"40-G";return`${n[t]}-${n[e]}`}(a,s);return`${g} (${t})`}}}return i.join(", ")}function MR(t){if(!t)return[];const e=t.history?.points;if(!e||0===e.length)return[];const n=[];for(let r=0;r<e.length;r++){const i=e[r],o=r<e.length-1?e[r+1]:void 0,a=r===e.length-1,s="COMPLETED"===t.matchUpStatus,c=i.set??0,u=i.game??0,d=i.number??0,{gameComplete:p,setComplete:l}=AR({nextPoint:o,isLastPoint:a,isCompleted:s,pointSet:c,pointGame:u}),m=p?i.winner:void 0,f=ER(l,t,c),h=CR(i),g=o?.server??i.server??0,I=OR(t,c,u);n.push({action:"addPoint",point:{index:r,number:d,winner:i.winner,server:i.server,score:i.score,result:i.result},game:{index:u,isTiebreak:I,complete:p,winner:m},set:{index:c,complete:l,winner:f},needed:h,nextService:g,result:i.result,complete:a&&s})}return n}function AR({nextPoint:t,isLastPoint:e,isCompleted:n,pointSet:r,pointGame:i}){const o=t?t.set??0:void 0,a=t?t.game??0:void 0;return{gameComplete:e?n||void 0===o&&void 0===a:o!==r||a!==i,setComplete:e?n||!1:void 0!==t&&o!==r}}function ER(t,e,n){if(!t)return;const r=e.score.sets[n];return void 0!==r?.winningSide?r.winningSide-1:void 0}function CR(t){const e={};return t.pointsToGame&&(e.pointsToGame=t.pointsToGame),t.pointsToSet&&(e.pointsToSet=t.pointsToSet),t.pointsToMatch&&(e.pointsToMatch=t.pointsToMatch),t.gamesToSet&&(e.gamesToSet=t.gamesToSet),void 0!==t.isBreakpoint&&(e.isBreakpoint=t.isBreakpoint),e}function OR(t,e,n){const r=t.score.sets[e];return!!(r?.isTiebreakOnly||n>0&&void 0!==r?.side1Score&&void 0!==r?.side2Score&&!r?.isTiebreakOnly)}function kR(t){return"COMPLETED"===t.matchUpStatus}function FR(t){if("COMPLETED"===t.matchUpStatus)return t.winningSide}function xR(t,e,n,r,i){if("timed"===n)return;if(!r)return;const o=function(t){const e=t.score.sets;if(0===e.length)return;const n=e.at(-1);return void 0===n?.winningSide?n:void 0}(t),a=function(t){const e=[0,0];return t.score.sets.forEach(t=>{1===t.winningSide&&e[0]++,2===t.winningSide&&e[1]++}),e}(t),s=e.exactly||e.bestOf||3,c=Math.ceil(s/2),{side1Points:u,side2Points:d}=function(t){if(!t)return{side1Points:0,side2Points:0};const e=t.side1GameScores??[],n=t.side2GameScores??[];if(0===e.length&&0===n.length)return{side1Points:0,side2Points:0};const r=Math.max(e.length,n.length)-1;return{side1Points:e[r]??0,side2Points:n[r]??0}}(o),p=function(t,e,n,r,i,o){if("tiebreakOnly"===r){return LR(t,e,n.tiebreakSet?.tiebreakTo||11,n.tiebreakSet?.NoAD||!1)}if("matchTiebreak"===r){return LR(t,e,i.finalSetFormat?.tiebreakSet?.tiebreakTo||10,i.finalSetFormat?.tiebreakSet?.NoAD||!1)}if(o){const r=o.side1Score||0,i=o.side2Score||0,a=n.setTo||6,s=("number"==typeof n.tiebreakAt?n.tiebreakAt:void 0)??a;if(!(n.noTiebreak||!1)&&r===s&&i===s){return LR(t,e,n.tiebreakFormat?.tiebreakTo||7,n.tiebreakFormat?.NoAD||!1)}}if("CONSECUTIVE"===i.gameFormat?.type){const t=i.gameFormat.count||3;return[t,t]}return function(t,e,n,r){const i=n.gameFormat?.NoAD||n.NoAD||!1,o=r?.gameFormat?.deuceAfter,a=4;return[_R(t,e,a,i,o),_R(e,t,a,i,o)]}(t,e,n,i)}(u,d,r,n,e,o),l=function(t,e,n){if("tiebreakOnly"===n||"matchTiebreak"===n)return t&&t.winningSide,[1,1];const r=t?.side1Score||0,i=t?.side2Score||0,o=e.setTo||6,a=("number"==typeof e.tiebreakAt?e.tiebreakAt:void 0)??o,s=e.noTiebreak||!1,c=e.winBy||2;return[VR(r,i,o,a,s,c),VR(i,r,o,a,s,c)]}(o,r,n),m=function(t,e,n,r){if("tiebreakOnly"===r||"matchTiebreak"===r)return[...t];const i=4;return[GR(t[0],e[0],i),GR(t[1],e[1],i)]}(p,l,0,n),f=function(t,e,n,r){const i=r.setFormat,o=function(t,e){if(!t)return 24;if(t.tiebreakSet)return t.tiebreakSet.tiebreakTo||11;if(t.timed)return 0;const n=t.setTo||6,r=e.gameFormat?.type,i="CONSECUTIVE"===r?e.gameFormat?.count||3:4;return n*i}(i,r);return[jR(t[0],e[0],n,o),jR(t[1],e[1],n,o)]}(m,a,c,e),h=function(t,e){if(void 0===e)return!1;const n=1-e;return 1===t[n]}(p,i);return{pointsToGame:p,pointsToSet:m,pointsToMatch:f,gamesToSet:l,isBreakpoint:h}}function _R(t,e,n,r,i){if(t>=n-1&&e>=n-1){if(r)return t>e?0:t===e?1:2;if(i&&t>=2+i&&e>=2+i)return t>e?0:t===e?1:2;const n=t-e;return n>=2?0:1===n?1:2}return t>=n?0:n-t}function LR(t,e,n,r){return[BR(t,e,n,r),BR(e,t,n,r)]}function BR(t,e,n,r){if(t>=n&&(t-e>=2||r&&t>e))return 0;if(t>=n-1&&e>=n-1){if(r)return t>e?0:t===e?1:2;const n=t-e;return n>=2?0:1===n?1:2}return t>=n?0:n-t}function VR(t,e,n,r,i,o){if(!i&&t===r&&e===r)return 1;if(t>=n){const n=t-e;return n>=o?0:o-n}const a=n-t;if(e>=n-1&&t>=n-1){if(!i)return Math.max(1,n-t);const r=t-e;return r>=o?0:o-r}return a}function GR(t,e,n){if(e<=0)return 0;return t+Math.max(0,e-1)*n}function jR(t,e,n,r){if(e>=n)return 0;return t+Math.max(0,n-e-1)*r}function qR(t,e,n){if("timed"===n)return;const r=function(t){const e=t.score.sets;if(0===e.length)return;const n=e[e.length-1];return void 0===n.winningSide?n:void 0}(t);return DR(e)?function(t,e){let n=0;for(const e of t.score.sets)void 0!==e.winningSide&&(void 0!==e.side1TiebreakScore?n+=(e.side1TiebreakScore??0)+(e.side2TiebreakScore??0):n+=(e.side1Score??0)+(e.side2Score??0));if(e&&void 0===e.winningSide){const t=e.side1GameScores??[],r=e.side2GameScores??[];if(t.length>0||r.length>0){const e=Math.max(t.length,r.length)-1;n+=(t[e]??0)+(r[e]??0)}else n+=(e.side1Score??0)+(e.side2Score??0)}return n%2==0?"deuce":"ad"}(t,r):"tiebreakOnly"===n||"matchTiebreak"===n?function(t){if(!t)return"deuce";const e=t.side1GameScores??[],n=t.side2GameScores??[];if(0===e.length&&0===n.length)return"deuce";return((e[0]??0)+(n[0]??0))%2==0?"deuce":"ad"}(r):function(t,e,n){if(!n)return"deuce";const r=n.side1GameScores??[],i=n.side2GameScores??[];if(0===r.length&&0===i.length)return"deuce";const o=Math.max(r.length,i.length)-1;return((r[o]??0)+(i[o]??0))%2==0?"deuce":"ad"}(0,0,r)}function WR(t,e){if(!e.length)return 1;for(const{condition:n,value:r}of e){if(n.results&&t.result&&n.results.includes(t.result))return r;if(n.strokes&&t.stroke&&n.strokes.includes(t.stroke))return r}return 1}function $R(t,e,n){if(!f(e))return t;let r=e.winner,i=e.server;const{timestamp:o}=e;if(void 0===r&&void 0!==e.winningSide&&(r=e.winningSide-1),void 0===i&&void 0!==e.serverSideNumber&&(i=e.serverSideNumber-1),null==r)return t;const a=t;a.history??={points:[]};const s=co(t.matchUpFormat);if(!s)throw new Error(`Invalid matchUpFormat: ${t.matchUpFormat}`);const c=s.exactly||s.bestOf||3,u=Math.ceil(c/2),d=a.history.points.length+1,p=a.history.points.length,l=[0,0];a.score.sets.forEach(t=>{1===t.winningSide&&l[0]++,2===t.winningSide&&l[1]++});const m=RR(s,l),h=l[0]===u-1&&l[1]===u-1,g=h&&s.finalSetFormat?s.finalSetFormat:s.setFormat;void 0!==i||!("RALLY"!==g?.tiebreakSet?.modifier&&"RALLY"!==g?.modifier)||(i=QR(a,s,m));let I=e.code;I||void 0===r||void 0===i||(I=r===i?"S":"R");const S={...e,pointNumber:d,winner:r,winningSide:r+1,server:i,serverSideNumber:void 0===i?void 0:i+1,serverParticipantId:e.serverParticipantId,timestamp:o||(new Date).toISOString()};I&&(S.code=I),S.index=p;const y=xR(a,s,m,g,i);y&&(S.pointsToGame=y.pointsToGame,S.pointsToSet=y.pointsToSet,S.pointsToMatch=y.pointsToMatch,S.gamesToSet=y.gamesToSet,S.isBreakpoint=y.isBreakpoint);const v=qR(a,s,m);void 0!==v&&(S.serveSide=v);const U=n?.pointMultipliers??[],P=e.scoreValue??WR(S,U);switch(1!==P&&(S.scoreValue=P),a.history.points.push(S),"TO_BE_PLAYED"===a.matchUpStatus&&(a.matchUpStatus="IN_PROGRESS"),m){case"tiebreakOnly":!function(t,e,n,r,i,o,a=1){const s=HR(t,!0,!1),c=t.score.sets.indexOf(s),u=i.tiebreakSet.tiebreakTo||11,d=i.tiebreakSet.NoAD||!1,p=s.side1GameScores??[],l=s.side2GameScores??[];0===p.length&&0===l.length&&(p.push(0),l.push(0),s.side1GameScores=p,s.side2GameScores=l);let m=p[0]||0,f=l[0]||0;e.set=c,e.game=0,e.number=m+f,0===n?(m+=a,p[0]=m):(f+=a,l[0]=f);s.side1GameScores=p,s.side2GameScores=l;const h=YR(m,f,u,d);e.score=void 0===h?`${m}-${f}`:"0-0",void 0!==h&&(s.winningSide=h+1,s.side1TiebreakScore=m,s.side2TiebreakScore=f,s.side1Score=0===h?1:0,s.side2Score=0===h?0:1,zR(t,r,o))}(a,S,r,s,g,u,P);break;case"matchTiebreak":!function(t,e,n,r,i,o=1){const a=r.finalSetFormat?.tiebreakSet?.tiebreakTo||10,s=r.finalSetFormat?.tiebreakSet?.NoAD||!1,c=HR(t,!1,!1),u=t.score.sets.indexOf(c),d=c.side1GameScores??[],p=c.side2GameScores??[];0===d.length&&0===p.length&&(d.push(0),p.push(0),c.side1GameScores=d,c.side2GameScores=p);let l=d[0]||0,m=p[0]||0;e.set=u,e.game=0,e.number=l+m,0===n?(l+=o,d[0]=l):(m+=o,p[0]=m);c.side1GameScores=d,c.side2GameScores=p;const f=YR(l,m,a,s);e.score=void 0===f?`${l}-${m}`:"0-0",void 0!==f&&(c.side1TiebreakScore=l,c.side2TiebreakScore=m,c.side1Score=0===f?1:0,c.side2Score=0===f?0:1,c.winningSide=f+1,zR(t,r,i))}(a,S,r,s,u,P);break;case"timed":!function(t,e,n,r,i=1){const o=HR(t,!1,!0),a=t.score.sets.indexOf(o);e.set=a,e.game=0,e.number=(o.side1Score||0)+(o.side2Score||0),0===n?o.side1Score=(o.side1Score||0)+i:o.side2Score=(o.side2Score||0)+i;const s=o.side1Score||0,c=o.side2Score||0;e.score=`${s}-${c}`}(a,S,r,0,P);break;default:!function(t,e,n,r,i,o,a){const s=HR(t,!1,!1),c=t.score.sets.indexOf(s),u=s.side1Score||0,d=s.side2Score||0,p=s.side1GameScores??[],l=s.side2GameScores??[];0===p.length&&0===l.length&&(p.push(0),l.push(0));const m=Math.max(p.length,l.length)-1;let f=m>=0?p[m]??0:0,h=m>=0?l[m]??0:0;const g=Math.max(p.length,l.length)-1,I=u+d-g;e.set=c,e.game=I+m,e.number=f+h;const S=i.setTo||6,y=("number"==typeof i.tiebreakAt?i.tiebreakAt:void 0)??S,v=a&&r.finalSetFormat?.noTiebreak;0===n?(f++,p[p.length-1]=f):(h++,l[l.length-1]=h);s.side1GameScores=p,s.side2GameScores=l;const U="CONSECUTIVE"===r.gameFormat?.type,P=r.gameFormat?.count||3;if(U){const t=s.currentStreak;s.currentStreak=t?.side===n?{side:n,count:t.count+1}:{side:n,count:1}}const T=!v&&u===y&&d===y;let w;w=U&&!T?s.currentStreak.count>=P?s.currentStreak.side:void 0:function(t,e,n,r,i){const o=n.gameFormat?.NoAD||n.NoAD||!1;if(r){return YR(t,e,n.tiebreakFormat?.tiebreakTo||7,n.tiebreakFormat?.NoAD||!1)}const a=4,s=Math.abs(t-e);if(o)return t>=a||e>=a?t>e?0:1:void 0;const c=i?.gameFormat?.deuceAfter;if(c&&t>=2+c&&e>=2+c)return t!==e?t>e?0:1:void 0;if((t>=a||e>=a)&&s>=2)return t>e?0:1;return}(f,h,i,T,r);const D=void 0===w?XR(f,h,T,U&&!T):"0-0";e.score=D,void 0!==w&&function(t,e,n,r,i,o,a,s,c,u,d,p,l){s&&(t.currentStreak=void 0);0===e?t.side1Score=n+1:t.side2Score=r+1;a&&(t.side1TiebreakScore=i,t.side2TiebreakScore=o);const m=KR(t.side1Score||0,t.side2Score||0,d,p,u.finalSetFormat);"number"==typeof m?(t.winningSide=m+1,zR(c,u,l)):(t.side1GameScores.push(0),t.side2GameScores.push(0))}(s,w,u,d,f,h,T,U,t,r,i,a,o)}(a,S,r,s,g,u,h)}return a}function HR(t,e,n){const r=t.score.sets.length-1,i=r>=0?t.score.sets[r]:void 0;if(i&&void 0===i.winningSide&&!i.segmentComplete)return i;const o={setNumber:t.score.sets.length+1,side1Score:0,side2Score:0,side1GameScores:[],side2GameScores:[]};return e&&(o.isTiebreakOnly=!0),n&&(o.isTimed=!0),t.score.sets.push(o),o}function zR(t,e,n){const r=[0,0];t.score.sets.forEach(t=>{1===t.winningSide&&r[0]++,2===t.winningSide&&r[1]++});const i=DR(e),o=e.exactly;if(i){const n=o||e.bestOf||3;if(t.score.sets.length<n)return;const r=t.score.sets.reduce((t,e)=>(void 0!==e.side1TiebreakScore&&void 0!==e.side2TiebreakScore?(t[0]+=e.side1TiebreakScore,t[1]+=e.side2TiebreakScore):(t[0]+=e.side1Score??0,t[1]+=e.side2Score??0),t),[0,0]);return void(r[0]!==r[1]&&(t.matchUpStatus="COMPLETED",t.winningSide=r[0]>r[1]?1:2,t.endTime=(new Date).toISOString()))}if(!(r[0]>=n||r[1]>=n))return;if(o){if(t.score.sets.filter(t=>void 0!==t.winningSide).length<o)return}const a=r[0]>=n?0:1;t.matchUpStatus="COMPLETED",t.winningSide=a+1,t.endTime=(new Date).toISOString()}function YR(t,e,n,r=!1){const i=Math.abs(t-e);if((t>=n||e>=n)&&i>=(r?1:2))return t>e?0:1}function KR(t,e,n,r,i){const o=n.setTo||6,a=("number"==typeof n.tiebreakAt?n.tiebreakAt:void 0)??o,s=r&&i?.noTiebreak;if(1===o)return t>=1||e>=1?t>e?0:1:void 0;const c=(r&&i?i:n).winBy||2;if(!s&&(t===a+1||e===a+1))return t>e?0:1;if(t>=o||e>=o){if(Math.abs(t-e)>=c)return t>e?0:1}}function QR(t,e,n){const r=JR(t,e,n);if(void 0!==t.serverFlip)return t.serverFlip?1-r:r;const i=t.history?.points?.[0];if(void 0!==i?.server){const e=i.set??0,n=i.game??0;let o=0;for(let n=0;n<e;n++){const e=t.score.sets[n];o+=(e.side1Score||0)+(e.side2Score||0)}o+=n;const a=o%2;if(i.server!==a)return 1-r}return r}function JR(t,e,n){const r=t.score.sets.length-1,i=r>=0?t.score.sets[r]:void 0;if("tiebreakOnly"===n||"matchTiebreak"===n)return function(t,e){const n=e?.side1GameScores??[],r=e?.side2GameScores??[],i=(n[0]||0)+(r[0]||0);let o=0;for(let e=0;e<t.score.sets.length-1;e++){const n=t.score.sets[e];o+=(n.side1Score||0)+(n.side2Score||0)}const a=o%2,s=Math.floor(i/2)%2;return(a+s)%2}(t,i);if("timed"===n)return function(t){const e=(t?.side1Score||0)+(t?.side2Score||0);return e%2}(i);const o=i?.side1Score||0,a=i?.side2Score||0;let s=0;for(let e=0;e<t.score.sets.length-1;e++){const n=t.score.sets[e];s+=(n.side1Score||0)+(n.side2Score||0)}const c=e.setFormat?.setTo||6,u=("number"==typeof e.setFormat?.tiebreakAt?e.setFormat.tiebreakAt:void 0)??c,d=e.finalSetFormat?.noTiebreak;if(!d&&o===u&&a===u){const t=i?.side1GameScores??[],e=i?.side2GameScores??[],n=(t.at(-1)||0)+(e.at(-1)||0);return((s+o+a)%2+Math.floor(n/2)%2)%2}return(s+o+a)%2}function XR(t,e,n,r){if(n||r)return`${t}-${e}`;const i=["0","15","30","40"];if(t<4&&e<4)return`${i[t]}-${i[e]}`;if(t>=3&&e>=3&&t===e)return"40-40";if(t>=3&&e>=3){const n=t-e;if(1===n)return"A-40";if(-1===n)return"40-A";if(n>=2)return"G-40";if(n<=-2)return"40-G"}return t>=3?`40-${e<4?i[e]:"40"}`:e>=3?`${t<4?i[t]:"40"}-40`:`${t<4?i[t]:"0"}-${e<4?i[e]:"0"}`}function ZR(t,e){const n=t.score.sets,r=function(t,e=!1){const n=t.score.sets;if(0===n.length)return"0-0";const r=n.map(t=>{const n=t.side1Score||0,r=t.side2Score||0;if(void 0!==t.side1TiebreakScore||void 0!==t.side2TiebreakScore){const i=t.side1TiebreakScore||0,o=t.side2TiebreakScore||0;return e&&(0===n&&1===r||1===n&&0===r)?`[${i}-${o}]`:n>r?`${n}-${r}(${o})`:`${n}(${i})-${r}`}return`${n}-${r}`});return r.join(", ")}(t,e?.useBracketNotation),i=n.length>0?n.at(-1):null,o=i&&void 0===i.winningSide?[i.side1Score||0,i.side2Score||0]:[0,0];let a=[0,0];if(i?.side1GameScores&&i.side2GameScores){const t=Math.max(i.side1GameScores.length,i.side2GameScores.length)-1;t>=0&&(a=[i.side1GameScores[t]||0,i.side2GameScores[t]||0])}const s=function(t,e){if("COMPLETED"===t.matchUpStatus||"TO_BE_PLAYED"===t.matchUpStatus)return;const n=co(t.matchUpFormat);if(!n)return;const r=t.score.sets.at(-1);if(!r||void 0!==r.winningSide)return;const i=[0,0];t.score.sets.forEach(t=>{1===t.winningSide&&i[0]++,2===t.winningSide&&i[1]++});const o=RR(n,i),a="tiebreakOnly"===o||"matchTiebreak"===o,s="CONSECUTIVE"===n.gameFormat?.type;let c=a;if(!c&&"standard"===o){const t=n.exactly||n.bestOf||3,e=Math.ceil(t/2),o=i[0]===e-1&&i[1]===e-1,a=o&&n.finalSetFormat?n.finalSetFormat:n.setFormat;if(a){const t=r.side1Score||0,e=r.side2Score||0,i=a.setTo||6,s=("number"==typeof a.tiebreakAt?a.tiebreakAt:void 0)??i,u=a.noTiebreak||!1,d=o&&n.finalSetFormat?.noTiebreak;c=!u&&!d&&t===s&&e===s}}const u=XR(e[0],e[1],c,s&&!c),d=u.split("-");if(2===d.length)return[d[0],d[1]];return[String(e[0]),String(e[1])]}(t,a),c=function(t){if("COMPLETED"===t.matchUpStatus||"TO_BE_PLAYED"===t.matchUpStatus)return;const e=co(t.matchUpFormat);if(!e)return;const n=e.exactly||e.bestOf||3,r=Math.ceil(n/2),i=[0,0];t.score.sets.forEach(t=>{1===t.winningSide&&i[0]++,2===t.winningSide&&i[1]++});const o=RR(e,i),a=i[0]===r-1&&i[1]===r-1,s=a&&e.finalSetFormat?e.finalSetFormat:e.setFormat;let c;"RALLY"!==s?.tiebreakSet?.modifier&&"RALLY"!==s?.modifier&&(c=QR(t,e,o));const u=xR(t,e,o,s,c);if(!u)return{isBreakPoint:!1,isGamePoint:!1,isSetPoint:!1,isMatchPoint:!1,isGoldenPoint:!1,isTiebreak:!1,server:c};const{pointsToGame:d,pointsToSet:p,pointsToMatch:l,isBreakpoint:m}=u;let f="tiebreakOnly"===o||"matchTiebreak"===o;if(!f&&"standard"===o&&s){const n=t.score.sets.at(-1);if(n){const t=n.side1Score||0,r=n.side2Score||0,i=s.setTo||6,o=("number"==typeof s.tiebreakAt?s.tiebreakAt:void 0)??i,c=s.noTiebreak||!1,u=a&&e.finalSetFormat?.noTiebreak;f=!c&&!u&&t===o&&r===o}}const h=!!(s?.NoAD||s?.gameFormat?.NoAD||f&&(s?.tiebreakFormat?.NoAD||s?.tiebreakSet?.NoAD||e.finalSetFormat?.tiebreakSet?.NoAD)),g=e.gameFormat?.deuceAfter,I=1===d[0]&&1===d[1]&&(h||!!g&&!f),S=void 0!==c&&1===d[c],y=1===Math.min(p[0],p[1]),v=1===Math.min(l[0],l[1]);return{isBreakPoint:m,isGamePoint:S,isSetPoint:y,isMatchPoint:v,isGoldenPoint:I,isTiebreak:f,server:c}}(t);return{sets:n,scoreString:r,games:o,points:a,pointDisplay:s,situation:c}}class tb{constructor(t={}){this.pointMultipliers=[],this.redoStack=[],t.competitionFormat?(this.competitionFormat=t.competitionFormat,this.matchUpFormat=t.matchUpFormat||t.competitionFormat.matchUpFormat||"SET3-S:6/TB7",this.pointMultipliers=t.pointMultipliers||(t.competitionFormat.pointMultipliers??[])):(this.matchUpFormat=t.matchUpFormat||"SET3-S:6/TB7",this.pointMultipliers=t.pointMultipliers??[]),this.matchUpId=t.matchUpId,this.isDoubles=t.isDoubles||!1,this.eventHandlers=t.eventHandlers,this.state=bR({matchUpFormat:this.matchUpFormat,matchUpId:this.matchUpId,isDoubles:this.isDoubles}),this.cacheFormatStructure()}setState(t){this.state=t,this.matchUpFormat=t.matchUpFormat,this.matchUpId=t.matchUpId,this.isDoubles="DOUBLES"===t.matchUpType,this.redoStack=[],this.initialScore=void 0,this.cacheFormatStructure()}getState(){return JSON.parse(JSON.stringify(this.state))}addPoint(t){const e=this.state.history?.points.length||0,n=this.state.score.sets.reduce((t,e)=>t+(e.side1Score||0)+(e.side2Score||0),0),r=this.state.score.sets.filter(t=>void 0!==t.winningSide).length,i="COMPLETED"===this.state.matchUpStatus,o=this.hasLineUp()?this.getActivePlayers():void 0;if(this.state=$R(this.state,t,{pointMultipliers:this.pointMultipliers}),o){const t=this.state.history.points[this.state.history.points.length-1];this.isDoubles?t.activePlayers=[o.side1,o.side2]:t.activePlayers=[o.side1[0]||"",o.side2[0]||""]}if(t.penaltyType){this.state.history.points[this.state.history.points.length-1].penaltyType=t.penaltyType}if(this.ensureHistory(),this.state.history.entries.push({type:"point",data:{winner:t.winner,winningSide:t.winningSide,server:t.server,serverSideNumber:t.serverSideNumber,serverParticipantId:t.serverParticipantId,timestamp:t.timestamp,rallyLength:t.rallyLength,result:t.result,penaltyType:t.penaltyType},timestamp:t.timestamp||(new Date).toISOString(),pointIndex:e}),this.redoStack=[],this.eventHandlers){const e=this.buildEventContext();this.eventHandlers.onPoint?.(e);this.state.score.sets.reduce((t,e)=>t+(e.side1Score||0)+(e.side2Score||0),0)>n&&this.eventHandlers.onGameComplete?.({...e,gameWinner:t.winner});if(this.state.score.sets.filter(t=>void 0!==t.winningSide).length>r){const t=this.state.score.sets.findLast(t=>void 0!==t.winningSide),n=1===t?.winningSide?0:1;this.eventHandlers.onSetComplete?.({...e,setWinner:n})}if(!i&&"COMPLETED"===this.state.matchUpStatus){const t=1===this.state.winningSide?0:1;this.eventHandlers.onMatchComplete?.({...e,matchWinner:t})}}}addSet(t){this.applyAddSet(t),this.ensureHistory();const e=this.state.score.sets.at(-1)?.winningSide;this.state.history.entries.push({type:"set",data:{...t,winningSide:e},timestamp:t.timestamp||(new Date).toISOString()}),this.redoStack=[]}addGame(t){this.applyAddGame(t),this.ensureHistory(),this.state.history.entries.push({type:"game",data:t,timestamp:t.timestamp||(new Date).toISOString()}),this.redoStack=[]}endSegment(t){this.applyEndSegment(t),this.ensureHistory();const e=(t?.setNumber??this.state.score.sets.length)-1;this.state.history.entries.push({type:"endSegment",data:{setNumber:e+1,...t},timestamp:t?.timestamp||(new Date).toISOString()})}setInitialScore(t){this.initialScore=t,this.redoStack=[],this.applyInitialScore(this.state,t),this.ensureHistory(),this.state.history.entries.push({type:"setInitialScore",data:t,timestamp:(new Date).toISOString()}),"TO_BE_PLAYED"===this.state.matchUpStatus&&(this.state.matchUpStatus="IN_PROGRESS")}undo(t=1){const e=this.state.history?.entries;if(e&&e.length>0){const n=Math.min(t,e.length);for(let t=0;t<n;t++){const t=e.pop();this.redoStack.push(t),"point"===t.type&&this.state.history.points.pop()}return this.rebuildFromEntries(),this.eventHandlers?.onUndo?.(this.buildEventContext()),!0}const n=this.state.history?.points??[];if(0===n.length)return!1;const r=Math.min(t,n.length);for(let t=0;t<r;t++){const t=n.pop();this.redoStack.push({type:"point",data:{winner:t.winner,server:t.server,timestamp:t.timestamp,rallyLength:t.rallyLength},timestamp:t.timestamp||""})}return this.rebuildState(),this.eventHandlers?.onUndo?.(this.buildEventContext()),!0}redo(t=1){if(0===this.redoStack.length)return!1;const e=Math.min(t,this.redoStack.length);for(let t=0;t<e;t++){const t=this.redoStack.pop();this.ensureHistory(),this.state.history.entries.push(t),t.type}return this.rebuildFromEntries(),this.eventHandlers?.onRedo?.(this.buildEventContext()),!0}canUndo(){const t=this.state.history?.entries;return!!(t&&t.length>0)||(this.state.history?.points.length||0)>0}canRedo(){return this.redoStack.length>0}getUndoDepth(){const t=this.state.history?.entries;return t&&t.length>0?t.length:this.state.history?.points.length||0}getRedoDepth(){return this.redoStack.length}getScore(){return ZR(this.state)}getScoreboard(t){return NR(this.state,t)}getWinner(){return FR(this.state)}isComplete(){return kR(this.state)}getPointCount(){return this.state.history?.points.length||0}getFormat(){return this.state.matchUpFormat}getStatistics(t){const e=this.state.history?.points??[];return SR(this.state,e,t)}getStatObjects(t){return wR(this.getStatistics(t))}getNextServer(){const t=this.competitionFormat?.serverRule;if("WINNER_SERVES"===t){const t=this.state.history?.points.at(-1);return t?t.winner:0}if(!this.cachedFormatStructure)return 0;const e=[0,0];this.state.score.sets.forEach(t=>{1===t.winningSide&&e[0]++,2===t.winningSide&&e[1]++});const n=RR(this.cachedFormatStructure,e);return QR(this.state,this.cachedFormatStructure,n)}setServer(t,e){if(!this.cachedFormatStructure)return;const n=[0,0];this.state.score.sets.forEach(t=>{1===t.winningSide&&n[0]++,2===t.winningSide&&n[1]++});const r=RR(this.cachedFormatStructure,n),i=JR(this.state,this.cachedFormatStructure,r);this.state.serverFlip=t!==i,!1!==e?.recordEntry&&(this.ensureHistory(),this.state.history.entries.push({type:"setServer",data:{side:t},timestamp:(new Date).toISOString()}),this.redoStack=[])}getEpisodes(){return MR(this.state)}isNoAd(){return!(!this.cachedFormatStructure?.setFormat?.NoAD&&!this.cachedFormatStructure?.setFormat?.gameFormat?.NoAD)}getSetsToWin(){if(!this.cachedFormatStructure)return 2;const t=this.cachedFormatStructure.exactly||this.cachedFormatStructure.bestOf||3;return Math.ceil(t/2)}getTiebreakAt(){const t=this.cachedFormatStructure?.setFormat;if(!t)return null;if(t.tiebreakSet)return null;if(t.timed)return null;if(t.noTiebreak)return null;const e=t.setTo||6;return("number"==typeof t.tiebreakAt?t.tiebreakAt:void 0)??e}hasFinalSetTiebreak(){const t=this.cachedFormatStructure?.finalSetFormat;return t?!!t.tiebreakSet||!t.noTiebreak&&!(!t.tiebreakFormat&&void 0===t.tiebreakAt):null!==this.getTiebreakAt()}getFormatStructure(){return this.cachedFormatStructure}getInputMode(){const t=this.state.history?.entries??[];if(0===t.length)return(this.state.history?.points.length||0)>0?"points":"none";const e=new Set(t.filter(t=>"setInitialScore"!==t.type&&"endSegment"!==t.type).map(t=>t.type));if(0===e.size)return"none";if(1===e.size){const t=e.values().next().value;if("point"===t)return"points";if("game"===t)return"games";if("set"===t)return"sets"}return"mixed"}setLineUp(t,e){const n=this.state.sides.find(e=>e.sideNumber===t);n&&(n.lineUp=e),this.initialLineUps??={},this.initialLineUps[t]=e.map(t=>({...t}))}substitute(t){const e=this.state.sides.find(e=>e.sideNumber===t.sideNumber);if(!e?.lineUp)return;const n=e.lineUp.findIndex(e=>e.participantId===t.outParticipantId);if(-1===n)return;this.ensureHistory(),this.state.history.substitutions??=[];const r={sideNumber:t.sideNumber,outParticipantId:t.outParticipantId,inParticipantId:t.inParticipantId,beforePointIndex:this.state.history.points.length,timestamp:t.timestamp};this.state.history.substitutions.push(r),e.lineUp[n]={...e.lineUp[n],participantId:t.inParticipantId},this.state.history.entries.push({type:"substitution",data:r,timestamp:t.timestamp||(new Date).toISOString()}),this.redoStack=[]}getActivePlayers(){const t=this.state.sides.find(t=>1===t.sideNumber),e=this.state.sides.find(t=>2===t.sideNumber);return{side1:t?.lineUp?.map(t=>t.participantId)??[],side2:e?.lineUp?.map(t=>t.participantId)??[]}}hasLineUp(){return this.state.sides.some(t=>t.lineUp&&t.lineUp.length>0)}setPointMultipliers(t){this.pointMultipliers=t}getPointMultipliers(){return this.pointMultipliers}getSupplementaryState(){return{redoStack:[...this.redoStack],initialLineUps:this.initialLineUps?Object.fromEntries(Object.entries(this.initialLineUps).map(([t,e])=>[t,e.map(t=>({...t}))])):void 0}}loadSupplementaryState(t){t.redoStack&&(this.redoStack=[...t.redoStack]),t.initialLineUps&&(this.initialLineUps=Object.fromEntries(Object.entries(t.initialLineUps).map(([t,e])=>[t,e.map(t=>({...t}))])))}getPenaltyProfile(){return this.competitionFormat?.penaltyProfile}getPointProfile(){return this.competitionFormat?.pointProfile}getTimerProfile(){return this.competitionFormat?.timerProfile}getTimeoutRules(){return this.competitionFormat?.timeoutRules}getPenaltyBoxProfile(){return this.competitionFormat?.penaltyBoxProfile}getSubstitutionRules(){return this.competitionFormat?.substitutionRules}getPlayerRules(){return this.competitionFormat?.playerRules}setEventHandlers(t){this.eventHandlers=t}getEventHandlers(){return this.eventHandlers}decoratePoint(t,e){const n=this.state.history?.points[t];n&&Object.assign(n,e)}markHardBoundary(t){const e=this.state.score.sets[t.setIndex];e&&(e.hardBoundaries??=[],e.hardBoundaries.includes(t.gameIndex)||(e.hardBoundaries.push(t.gameIndex),e.hardBoundaries.sort((t,e)=>t-e)))}editPoint(t,e,n){const r=this.state.history?.points;if(!r||t<0||t>=r.length)return;const i=!1!==n?.recalculate,o=r[t];if(void 0!==e.winner&&(o.winner=e.winner),void 0!==e.server&&(o.server=e.server),void 0!==e.timestamp&&(o.timestamp=e.timestamp),void 0!==e.rallyLength&&(o.rallyLength=e.rallyLength),void 0!==e.wrongSide&&(o.wrongSide=e.wrongSide),void 0!==e.wrongServer&&(o.wrongServer=e.wrongServer),void 0!==e.penaltyPoint&&(o.penaltyPoint=e.penaltyPoint),!i)return;const a=this.state.history?.entries;if(a){const n=a.find(e=>"point"===e.type&&e.pointIndex===t);n&&(void 0!==e.winner&&(n.data.winner=e.winner),void 0!==e.server&&(n.data.server=e.server))}a&&a.length>0?this.rebuildFromEntries():this.rebuildState(),this.redoStack=[]}removePoint(t,e){const n=this.state.history?.points;if(!n||t<0||t>=n.length)return;const r=!1!==e?.recalculate;n.splice(t,1);const i=this.state.history?.entries;if(i){const e=i.findIndex(e=>"point"===e.type&&e.pointIndex===t);-1!==e&&i.splice(e,1);for(const e of i)"point"===e.type&&e.pointIndex>t&&(e.pointIndex-=1)}r&&(i&&i.length>0?this.rebuildFromEntries():this.rebuildState(),this.redoStack=[])}reset(){this.state=bR({matchUpFormat:this.matchUpFormat,matchUpId:this.matchUpId,isDoubles:this.isDoubles}),this.redoStack=[],this.initialScore=void 0,this.initialLineUps=void 0,this.eventHandlers?.onReset?.(this.buildEventContext())}ensureHistory(){this.state.history??={points:[]},this.state.history.entries??=[]}buildEventContext(){return{state:this.state,score:ZR(this.state)}}cacheFormatStructure(){this.cachedFormatStructure=co(this.matchUpFormat)}getInitialLineUps(){return this.initialLineUps}applyAddSet(t){const{side1Score:e,side2Score:n,side1TiebreakScore:r,side2TiebreakScore:i}=t;let o=t.winningSide;void 0===o&&(e>n?o=1:n>e&&(o=2));const a={setNumber:this.state.score.sets.length+1,side1Score:e,side2Score:n,winningSide:o};void 0!==r&&(a.side1TiebreakScore=r),void 0!==i&&(a.side2TiebreakScore=i),this.state.score.sets.push(a),"TO_BE_PLAYED"===this.state.matchUpStatus&&(this.state.matchUpStatus="IN_PROGRESS"),void 0!==o&&this.checkMatchCompletion()}applyAddGame(t){const{winner:e,tiebreakScore:n}=t;let r=this.state.score.sets.length>0?this.state.score.sets.at(-1):void 0;r&&void 0===r.winningSide||(r={setNumber:this.state.score.sets.length+1,side1Score:0,side2Score:0},this.state.score.sets.push(r)),0===e?r.side1Score=(r.side1Score||0)+1:r.side2Score=(r.side2Score||0)+1,(r.side1GameScores?.length||r.side2GameScores?.length)&&(r.side1GameScores=r.side1GameScores??[],r.side2GameScores=r.side2GameScores??[],r.side1GameScores.push(0),r.side2GameScores.push(0)),n&&(r.side1TiebreakScore=n[0],r.side2TiebreakScore=n[1]),"TO_BE_PLAYED"===this.state.matchUpStatus&&(this.state.matchUpStatus="IN_PROGRESS"),this.checkSetCompletion(r),void 0!==r.winningSide&&this.checkMatchCompletion()}applySubstitution(t){const e=this.state.sides.find(e=>e.sideNumber===t.sideNumber);if(!e?.lineUp)return;const n=e.lineUp.findIndex(e=>e.participantId===t.outParticipantId);-1!==n&&(e.lineUp[n]={...e.lineUp[n],participantId:t.inParticipantId},this.state.history??={points:[]},this.state.history.substitutions??=[],this.state.history.substitutions.push(t))}applyEndSegment(t){const e=(t?.setNumber??this.state.score.sets.length)-1,n=this.state.score.sets[e];if(!n||void 0!==n.winningSide)return;const r=n.side1Score||0,i=n.side2Score||0;r>i?n.winningSide=1:i>r&&(n.winningSide=2),n.segmentComplete=!0,this.checkMatchCompletion()}checkSetCompletion(t){const e=co(this.state.matchUpFormat);if(!e)return;const n=e.exactly||e.bestOf||3,r=Math.ceil(n/2),i=[0,0];this.state.score.sets.forEach(t=>{1===t.winningSide&&i[0]++,2===t.winningSide&&i[1]++});const o=i[0]===r-1&&i[1]===r-1,a=o&&e.finalSetFormat?e.finalSetFormat:e.setFormat;if(!a)return;const s=t.side1Score||0,c=t.side2Score||0;if(a.tiebreakSet){const e=a.tiebreakSet.tiebreakTo||11,n=a.tiebreakSet.NoAD||!1?1:2;(s>=e||c>=e)&&Math.abs(s-c)>=n&&(t.winningSide=s>c?1:2)}else if(!a.timed){const n=KR(s,c,a,o,e.finalSetFormat);"number"==typeof n&&(t.winningSide=n+1)}}checkMatchCompletion(){const t=co(this.state.matchUpFormat);if(!t)return;const e=t.exactly||t.bestOf||3,n=Math.ceil(e/2);zR(this.state,t,n)}rebuildFromEntries(){const t=this.state.history?.entries??[],e=this.prepareRebuildState(t);this.state=e;for(const n of t)switch(n.type){case"point":this.state=$R(this.state,n.data,{pointMultipliers:this.pointMultipliers}),this.state.history.entries=e.history.entries;break;case"set":this.applyAddSet(n.data);break;case"game":this.applyAddGame(n.data);break;case"endSegment":this.applyEndSegment(n.data);break;case"substitution":this.applySubstitution(n.data);break;case"setInitialScore":break;case"setServer":this.replaySetServerEntry(n.data)}}prepareRebuildState(t){const e=this.getInitialLineUps(),n=bR({matchUpFormat:this.matchUpFormat,matchUpId:this.matchUpId,isDoubles:this.isDoubles});if(e)for(const t of n.sides)e[t.sideNumber]&&(t.lineUp=e[t.sideNumber].map(t=>({...t})));return this.initialScore&&(this.applyInitialScore(n,this.initialScore),"TO_BE_PLAYED"===n.matchUpStatus&&(n.matchUpStatus="IN_PROGRESS")),n.history={points:[],entries:[...t]},n}replaySetServerEntry(t){const e=[0,0];this.state.score.sets.forEach(t=>{1===t.winningSide&&e[0]++,2===t.winningSide&&e[1]++});const n=RR(this.cachedFormatStructure,e),r=JR(this.state,this.cachedFormatStructure,n);this.state.serverFlip=t.side!==r}rebuildState(){const t=this.state.history?.points??[];let e=bR({matchUpFormat:this.matchUpFormat,matchUpId:this.matchUpId,isDoubles:this.isDoubles});this.initialScore&&(this.applyInitialScore(e,this.initialScore),"TO_BE_PLAYED"===e.matchUpStatus&&(e.matchUpStatus="IN_PROGRESS"));for(const n of t)e=$R(e,{winner:n.winner,server:n.server,timestamp:n.timestamp,rallyLength:n.rallyLength,result:n.result},{pointMultipliers:this.pointMultipliers});this.state=e}applyInitialScore(t,e){t.score.sets=[];for(let n=0;n<e.sets.length;n++){const r=e.sets[n],i={setNumber:n+1,side1Score:r.side1Score,side2Score:r.side2Score};if(void 0!==r.side1TiebreakScore&&(i.side1TiebreakScore=r.side1TiebreakScore),void 0!==r.side2TiebreakScore&&(i.side2TiebreakScore=r.side2TiebreakScore),void 0===r.winningSide){const t=this.cachedFormatStructure,e=t?.finalSetFormat&&n===(t.bestOf??t.exactly??3)-1?t.finalSetFormat:t?.setFormat,o=e?.setTo;o&&(r.side1Score>=o||r.side2Score>=o)&&(r.side1Score>r.side2Score?i.winningSide=1:r.side2Score>r.side1Score&&(i.winningSide=2))}else i.winningSide=r.winningSide;t.score.sets.push(i)}if(e.currentSetScore){const n={setNumber:t.score.sets.length+1,side1Score:e.currentSetScore.side1Score,side2Score:e.currentSetScore.side2Score,side1GameScores:[],side2GameScores:[]};e.currentGameScore?(n.side1GameScores=[e.currentGameScore.side1Points],n.side2GameScores=[e.currentGameScore.side2Points]):(n.side1GameScores=[0],n.side2GameScores=[0]),t.score.sets.push(n)}}}var eb={__proto__:null,ScoringEngine:tb,generateScoreString:aR,generateTieMatchUpScore:dT,reverseScore:cR},nb={__proto__:null,addPoint:$R,calculatePointsTo:xR,createMatchUp:bR,inferServeSide:qR,resolvePointValue:WR};const rb=" ",ib="DEF",ob="WO",ab=["RET",ib,ob,"WO/WO","ABN","SUS","INT"],sb="DEFAULTED",cb="WALKOVER",ub="ABANDONED",db="SUSPENDED",pb="RETIRED",lb="INTERRUPTED",mb=[pb,sb,cb],fb="()",hb="[]",gb=["up","left","shift+tab"],Ib=["enter","down","tab","right"],Sb="backspace",yb=["r","d","w","a","s","i"],vb="space",Ub=["[","("],Pb=[...gb,...Ib,vb,"]"],Tb="-",wb="-",Db=["/"],Rb=["0","1","2","3","4","5","6","7","8","9"].concat(yb),bb=Rb.map(t=>`shift+${t}`),Nb=[Tb,Sb].concat(Pb,Db),Mb=[Rb,bb,Nb].join(","),Ab=[Mb,gb,Ib,["=","+","num_1","num_2","shift+=","shift+-"]].join(",");[].concat(...Rb,...Rb,...Nb,...Rb,...Rb,...Rb,...Rb,...Rb,...Rb);const Eb={OUTCOMEKEYS:yb,SIDE1KEYS:Rb,SIDE2KEYS:bb,MODIFIERS:Nb,PROMPT:"Enter Score",MOVEUP:gb,MOVEDOWN:Ib,HOTKEYS:Ab};function Cb({scoreString:t,lowSide:e,outcome:n}){if(({scoreString:t}=Ob({scoreString:t})),2===e){const e=t?.[t.length-1];return t+(e===rb?"":rb)+n}return n+rb+t}function Ob({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(const n of ab){const r=t?.indexOf(n);0===r?t=t.slice(n.length+1).trim()+rb:r>0&&(t=t.slice(0,r)),r>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function kb({analysis:t,scoreString:e,sets:n,lowSide:r}){let i,o;if(!e)return{scoreString:e,sets:n};const{scoreString:a,removed:s}=Ob({scoreString:e});if(e=a,s)return{scoreString:e,sets:n,outcomeRemoved:!0};let c=n.at(-1)??{};const u=Object.values(c).filter(t=>void 0!==t).length;c.setNumber&&1===u&&(c=(n=n.slice(0,-1)).at(-1)??{});const{tiebreakSet:d}=t.setFormat,{tiebreakTo:p,NoAD:l}=d??{},{isTiebreakEntry:m}=Fb({brackets:hb,scoreString:e}),f=function(t){const e=t.split("").reduce((t,e,n)=>(e.match(/\d+/g)&&t.push(n),t),[]);return e.pop()}(e);if(f>=0){i=e.slice(0,f);const{isTiebreakEntry:a}=Fb({brackets:fb,scoreString:i}),{lastOpenBracketIndex:s,isTiebreakEntry:u}=Fb({brackets:hb,scoreString:i}),d=i?.length?i[i.length-1].trim():void 0,h=i&&!isNaN(d);let g=t.isIncompleteSetScore;return m&&u&&({newScore:i,isIncompleteScore:g}=function({newScore:t,scoreString:e,lastMatchTiebreakOpenBracketIndex:n,lastSet:r,lowSide:i,NoAD:o,tiebreakTo:a}){const s=t.slice(n+1).split(wb),c=s?.length>0&&void 0!==s[0]&&!Number.isNaN(Number.parseInt(s[0]))&&Number.parseInt(s[0])||void 0,u=s?.length>1&&void 0!==s[1]&&!Number.isNaN(Number.parseInt(s[1]))&&Number.parseInt(s[1])||void 0,d=[c,u];let p=!1;if(u){const r=1===i?1:0;d[r]=(d?.[1-r]||0)+(o?1:2),(d[r]||0)<a&&(d[r]=a),t=e.slice(0,n+1),t+=d.join(wb)}else void 0===c?(t=e.slice(0,n),p=!0):(t=e.slice(0,n+1),t+=c);return r.side1TiebreakScore=d[0]||0,r.side2TiebreakScore=d[1]||0,{newScore:t,isIncompleteScore:p}}({newScore:i,scoreString:e,lastMatchTiebreakOpenBracketIndex:s,lastSet:c,lowSide:r,NoAD:l,tiebreakTo:p})),i.length||(i=void 0),g?o=function({lastSet:t,sets:e,analysis:n}){const r=t.side1Score?.toString();if(r){const e=r?.slice(0,-1);t.side1Score=Number.parseInt(e)&&!Number.isNaN(Number.parseInt(e))||void 0,void 0===t.side1Score&&(t.side2Score=void 0)}let i;return n.isTimedSet?(i=t.side1Score?e:e?.slice(0,-1)??[],i[e.length-1]=t):i=e?.slice(0,-1)??[],i}({lastSet:c,sets:n,analysis:t}):h?o=function({lastSet:t,sets:e,analysis:n}){const r=t.side2Score?.toString(),i=t.side1Score?.toString();if(!n.isTiebreakEntry&&!n.isMatchTiebreak)if(t.side2Score){const e=r?.slice(0,-1);t.side2Score=!isNaN(e)&&parseInt(e)||void 0}else{const e=i?.slice(0,-1);t.side1Score=!isNaN(e)&&parseInt(e)||void 0}let o;return n.isTimedSet?t.side1Score?(o=e??[],o[e.length-1]=t):o=e?.slice(0,e.length-1)??[]:(o=e??[],o[e.length-1]=t),o[o.length-1]&&Object.assign(o[o.length-1],{winningSide:void 0}),o}({lastSet:c,sets:n,analysis:t}):a?(o=n??[],Object.assign(o[o.length-1]??{},{winningSide:void 0,side1TiebreakScore:void 0,side2TiebreakScore:void 0})):(m&&!u?o=n?.slice(0,-1)??[]:(o=n,o[n.length-1]=c),m||(o[o.length-1].side2Score=0,o[o.length-1].winningSide=void 0)),{scoreString:i,sets:o}}return{scoreString:e,sets:n}}function Fb({brackets:t=fb,scoreString:e}){if(!e)return{};const[n,r]=t.split(""),i=e.split(""),o=Math.max(...B(n,i));return{isTiebreakEntry:o>Math.max(...B(r,i)),lastOpenBracketIndex:o}}function xb(t){const{lowValue:e=0,NoAD:n=!1,tiebreakTo:r}=t??{};return e+1>=r?e+(n?1:2):parseInt(r)}function _b({matchUpFormat:t,matchUpStatus:e,winningSide:n,sets:r}){const i=co(t),{bestOf:o}=i,a=Math.ceil(o/2),s=r?.reduce((t,e)=>{const{winningSide:n}=e;return n&&t[n-1]++,t},[0,0]);let c=s?.indexOf(a)+1||void 0;return mb.includes(e)&&n&&(c=n),{matchUpWinningSide:c}}function Lb({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:n,isTiebreakSet:r,isDecidingSet:i,isTimedSet:o,set:a}){if(!a)return{error:Ae,info:"missing set"};e=e||n&&co(n);const s=i&&e.finalSetFormat||(e?.setFormat??{}),{side1Score:c,side2Score:u}=a,{setTo:d,tiebreakAt:p}=s,l=c||u,m=Bb({set:a}),f=Math.abs(c-u),h=c>=d||u>=d,g=r||c>=d&&u>=d||p&&p<d&&(c===p||u===p),I=t||g&&(1===m&&a.side1TiebreakScore>a.side2TiebreakScore||2===m&&a.side2TiebreakScore>a.side1TiebreakScore),S=!g&&s.NoAD||g||r&&s.tiebreakFormat?.NoAD?1:2;return!(!(o&&l||h&&(f>=S||g)||r)||g&&!I)}function Bb({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 Vb({analysis:t,set:e}){const n=Bb({set:e}),{isDecidingSet:r,isTiebreakSet:i,matchUpScoringFormat:o}=t;return Lb({matchUpScoringFormat:o,isDecidingSet:r,isTiebreakSet:i,set:e})&&n}function Gb({lowSide:t,value:e,sets:n,scoreString:r,winningSide:i,matchUpStatus:o}){let a;return"r"===e?r?(a=!0,r=Cb({scoreString:r,lowSide:t,outcome:"RET"}),i=2===t?1:2,o=pb):(a=!0,r=Cb({scoreString:r,lowSide:t,outcome:ib}),i=2===t?1:2,o=sb):"d"===e?(a=!0,r=Cb({scoreString:r,lowSide:t,outcome:ib}),i=2===t?1:2,o=sb):"w"===e?(a=!0,n=[],r=ob,i=2===t?1:2,o=cb):"s"===e&&r?(a=!0,r=Cb({scoreString:r,lowSide:t,outcome:"SUS"}),o=db,i=void 0):"a"===e?(a=!0,r=Cb({scoreString:r,lowSide:t,outcome:"ABN"}),o=ub,i=void 0):"i"===e&&r&&(a=!0,r=Cb({scoreString:r,lowSide:t,outcome:"INT"}),o=lb,i=void 0),{updated:a,sets:n,scoreString:r,matchUpStatus:o,winningSide:i}}function jb(t){let{sets:e,info:n,scoreString:r,winningSide:i,matchUpStatus:o}=t;const{analysis:a,lowSide:s,value:c}=t;let u,d;e?.length||c===Sb||(e=[{setNumber:1}]);const l=e.length-1;if(yb.includes(c))({sets:e,info:n,scoreString:r,winningSide:i,matchUpStatus:o,updated:u}=function({sets:t,info:e,scoreString:n,winningSide:r,matchUpStatus:i,analysis:o,lowSide:a,value:s}){let c;const u=t.at(-1)??{},{side1Score:d,side2Score:p}=u;d&&!p?e="missing side2Score":o.finalSetIsComplete||r?e="final set is already complete":o.isIncompleteSetScore?e="incomplete set scoreString":({sets:t,scoreString:n,winningSide:r,matchUpStatus:i,updated:c}=Gb({lowSide:a,value:s,sets:t,scoreString:n,matchUpStatus:i,winningSide:r}));return{sets:t,info:e,scoreString:n,winningSide:r,matchUpStatus:i,updated:c}}({sets:e,info:n,scoreString:r,winningSide:i,matchUpStatus:o,analysis:a,lowSide:s,value:c}));else if(c===Sb)({scoreString:r,sets:e,outcomeRemoved:d}=kb({analysis:a,scoreString:r,sets:e})),({sets:e,scoreString:r,winningSide:i,matchUpStatus:o,updated:u}=function({sets:t,scoreString:e,outcomeRemoved:n}){let r=e,i=t;""===r?.trim()&&(r=r.trim());r||(i=[]);if(n){const t=i.at(-1)??{},{side1Score:e,side2Score:n}=t;if(e&&n){const r=(e>n?1:n>e&&2)||void 0;r&&(t.winningSide=r,i.push({setNumber:i.length+1}))}}return{sets:i,scoreString:r,winningSide:void 0,matchUpStatus:void 0,updated:!0}}({sets:e,scoreString:r,outcomeRemoved:d}));else if(a.hasOutcome)n="has outcome";else{if(i)return{sets:e,scoreString:r,winningSide:i,matchUpStatus:o,updated:!1,info:"matchUp is complete"};c===vb?({sets:e,scoreString:r,updated:u}=function({sets:t,scoreString:e,winningSide:n,analysis:r}){let i,o=e;const a=t.at(-1)??{},{side1Score:s,side2Score:c}=a,u=(s>c?1:c>s&&2)||void 0;!u||n||r.isIncompleteSetScore||(t.at(-1).winningSide=u,t.push({setNumber:t.length+1}),o+=" ",i=!0);return{sets:t,scoreString:o,updated:i}}({sets:e,scoreString:r,winningSide:i,analysis:a})):c===Tb&&void 0!==e[l].side1Score&&void 0===e[l].side2Score&&r&&a.isNumericEnding?(r+="-",e[l].side2Score=0,o=void 0,i=void 0,u=!0):Number.isNaN(Number(c))||({sets:e,scoreString:r,updated:u}=function({sets:t,setIndex:e,value:n,scoreString:r}){let i,o,a=r;if(void 0===t[e].side2Score){const r=p((t[e].side1Score||0).toString()+n).toString().slice(0,2);t[e].side1Score=p(r),i=t[e].side1Score.toString(),o=!0}else{const r=p((t[e].side2Score||0).toString()+n).toString().slice(0,2);t[e].side2Score=p(r),i=[t[e].side1Score,t[e].side2Score].join("-"),o=!0}if(o){const n=(t.slice(0,e)??[]).filter(t=>t).map(t=>[t.side1Score,t.side2Score].join("-")).join(" ");a=n?n+" "+i:i}return{sets:t,scoreString:a,updated:o}}({sets:e,setIndex:l,value:c,scoreString:r}))}return{sets:e,scoreString:r,winningSide:i,matchUpStatus:o,info:n,updated:u}}function qb({matchUpFormat:t,scoreString:e,winningSide:n,value:r,sets:i}){const o=(i?.filter(t=>t?.winningSide)?.length||0)+(n?0:1),a=co(t),s=o===a?.bestOf,c=s&&a?.finalSetFormat||(a?.setFormat??{}),u=c?.timed,d=s&&i[a?.bestOf-1],p=d?.winningSide,{isTiebreakEntry:l}=Fb({brackets:fb,scoreString:e}),{isTiebreakEntry:m}=Fb({brackets:hb,scoreString:e}),f=l||m,h=!!c.tiebreakSet,g=e?.[e.length-1]?.trim(),I=e&&!isNaN(g),S=!f&&g===Tb,y=l&&Ub.includes(g),v=m&&Ub.includes(g),U=m&&g===wb,P=e?.split(""),[T]=hb.split(""),w=P&&Math.max(...B(T,P)),D=P&&Math.max(...B(wb,P)),R=P&&D>w,b=i[i.length-1]?.winningSide,N=i?.length&&!b,M=ab.find(t=>e?.indexOf(t)>=0),A=!isNaN(r),E=r===vb,C=Pb.includes(r),O=e?.split("").find(t=>Ub.includes(t)),k=C&&m&&!v&&(U||!function({scoreString:t}){if(!t)return!1;const e=t?.[t.length-1].trim(),n=t&&!isNaN(e),[r,i]=hb.split(""),o=t.split(""),a=Math.max(...B(r,o)),s=Math.max(...B(i,o)),c=Math.max(...B(wb,o));return n&&a>s&&c>a}({scoreString:e}));return{isTiebreakSetValue:h&&A,matchUpScoringFormat:a,setNumber:o,setFormat:c,matchTiebreakHasJoiner:R,isGameScoreEntry:N,isSpace:E,isCloser:C,isTiebreakCloser:C&&O&&f&&I,isDecidingSet:s,isTiebreakSet:h,isTimedSet:u,isNumericEnding:I,isNumericValue:A,hasOpener:O,hasOutcome:M,finalSet:d,finalSetIsComplete:p,lastSetIsComplete:b,isInvalidSetTiebreakValue:E&&f&&y,isInvalidMatchTiebreakValue:k,isTiebreakEntry:f,isSetTiebreakEntry:l,isMatchTiebreakEntry:m,isIncompleteSetScore:S,isIncompleteSetTiebreak:y,isIncompleteMatchTiebreak:v,isPartialMatchTiebreakValue:U}}function Wb({analysis:t,lowSide:e,scoreString:n,sets:r,value:i}){const{scoreString:o,set:a}=function({analysis:t,lowSide:e,scoreString:n,value:r}){const{setTo:i,tiebreakAt:o,NoAD:a}=t?.setFormat??{},s=r===parseInt(o||i);if(o&&o<i&&r>o)return{scoreString:n};if(a&&r===i&&!s||r>i)return{scoreString:n};const c=s?r+1:r+1===i?r+(a?1:2):i,u=[r,c];2===e&&u.reverse();const d=fb.split("")[0];n=(n||"")+(u.join(Tb)+(s?d:rb));const p={side1Score:u[0],side2Score:u[1]},l=Vb({analysis:t,set:p});return p.winningSide=l||void 0,{scoreString:n,set:p}}({analysis:t,lowSide:e,scoreString:n,value:p(i)});return a&&(a.setNumber=r?.length+1||1),{scoreString:n=o||void 0,sets:r=r?.concat(a).filter(Boolean)||[a],updated:!0}}function $b(t){let{lowSide:e=1,value:n}=t,{scoreString:r,sets:i,winningSide:o,matchUpStatus:a}=t;const{matchUpFormat:s,shiftFirst:c,auto:u=!0}=t;if(!Mb.includes(n))return{updated:!1,info:"invalid key"};c&&(e=3-e);const d=c&&2===e||!c&&1===e,{matchUpWinningSide:l}=_b({sets:i,winningSide:o,matchUpStatus:a,matchUpFormat:s});o=l;const m=qb({value:n,winningSide:o,scoreString:r,sets:i,matchUpFormat:s});({value:n,scoreString:r}=function({analysis:t,value:e,scoreString:n,isShifted:r}){let i=e,o=n;Db.includes(i)&&(i=Tb);t.hasOpener&&t.isTiebreakEntry&&!t.isTiebreakSet&&r&&0===p(i)&&(t.isTiebreakCloser=!0);Pb.includes(i)&&t.hasOpener&&(i="");Pb.includes(i)&&(i=vb);if(t.lastSetIsComplete){const t=o?.length&&o.at(-1);o&&" "!==t&&(o+=" ")}return{value:i,scoreString:o}}({analysis:m,value:n,scoreString:r,isShifted:d}));const f=function({analysis:t,lowSide:e,sets:n,scoreString:r,matchUpStatus:i,winningSide:o,value:a,auto:s}){let c,u,d=n,l=r,m=i,f=o;if(t.isTimedSet)({info:c,sets:d,scoreString:l,updated:u,matchUpStatus:m,winningSide:f}=jb({analysis:t,lowSide:e,scoreString:r,sets:n,matchUpStatus:i,winningSide:o,value:a}));else if(yb.includes(a))({info:c,sets:d,scoreString:l,matchUpStatus:m,winningSide:f,updated:u}=function({analysis:t,lowSide:e,sets:n,scoreString:r,matchUpStatus:i,winningSide:o,value:a}){let s,c;return t.finalSetIsComplete||o?s="final set is already complete":t.isTiebreakEntry||t.isIncompleteSetScore?t.isTiebreakEntry||t.isIncompleteSetScore?s="incomplete set scoreString or tiebreak entry":console.log("handle case",{value:a}):({sets:n,scoreString:r,matchUpStatus:i,winningSide:o,updated:c}=Gb({lowSide:e,sets:n,scoreString:r,matchUpStatus:i,winningSide:o,value:a})),{info:s,sets:n,scoreString:r,matchUpStatus:i,winningSide:o,updated:c}}({analysis:t,lowSide:e,sets:n,scoreString:r,matchUpStatus:i,winningSide:o,value:a}));else if(a===Sb)({scoreString:l,sets:d,updated:u,matchUpStatus:m,winningSide:f}=function({analysis:t,scoreString:e,sets:n,lowSide:r}){return({scoreString:e,sets:n}=kb({analysis:t,scoreString:e,sets:n,lowSide:r})),e||(n=[]),{scoreString:e,sets:n,updated:!0,matchUpStatus:void 0,winningSide:void 0}}({analysis:t,scoreString:r,sets:n,lowSide:e}));else if(t.hasOutcome)c="has outcome";else if(a!==Tb||t.isMatchTiebreakEntry)if(a===wb&&t.isMatchTiebreakEntry&&!t.isSetTiebreakEntry)({info:c,scoreString:l,updated:u}=function({analysis:t,scoreString:e}){let n,r;return t.matchTiebreakHasJoiner?n="existing joiner":t.isNumericEnding&&(r=!0,e+=wb),{info:n,scoreString:e,updated:r}}({analysis:t,scoreString:r}));else if([Tb,wb].includes(a))c="invalid location for joiner";else{if(o)return{earlyReturn:!0,updated:!1,info:"matchUp is complete"};({info:c,updated:u,sets:d,scoreString:l}=function({analysis:t,auto:e,lowSide:n,scoreString:r,sets:i,value:o}){let a,s,c=i,u=r;t.isIncompleteSetScore?t.isNumericValue&&({sets:c,scoreString:u,updated:s}=function({analysis:t,scoreString:e,sets:n,value:r}){let i;if(!n?.length)return{sets:[]};const o=n[n.length-1];r=p(r);const{validSide2Score:a,requiresTiebreak:s}=function({analysis:t,set:e={},value:n}){const r=t.isDecidingSet&&t.matchUpScoringFormat.finalSetFormat||t.matchUpScoringFormat.setFormat,{tiebreakAt:i,setTo:o,NoAD:a}=r,{side1Score:s}=e;let c,u;return c=i&&i<o?s===i?n<=o:n<=i:s===o?a?n<o:n<=o+1:s===o-1?a?n<=o:n<=o+1:s===o+1?n===o||n===o-1:n<=o,c&&(u=i&&i<o?s===o&&n===i||s===i&&n===o:s>=o&&n>=o&&s!==n),{validSide2Score:c,requiresTiebreak:u}}({analysis:t,set:o,value:r});if(a){i=!0,e=(e||"")+r,o.side2Score=r;const a=Vb({analysis:t,set:n[n.length-1]});o.winningSide=a||void 0,s?e+=fb.split("")[0]:t.isDecidingSet||(e+=rb)}return{sets:n,scoreString:e,updated:i}}({analysis:t,scoreString:r,sets:i,value:o})):t.isInvalidMatchTiebreakValue?a="invalid matchUp tiebreak character":t.isInvalidSetTiebreakValue?a="invalid set tiebreak character":t.isTiebreakCloser?({scoreString:u,sets:c,updated:s}=function({analysis:t,scoreString:e,sets:n}){const r=t.isSetTiebreakEntry?fb:hb,i=r.split("").reverse()[0],o=r.split("")[0],a=n[n.length-1],{tiebreakFormat:s}=t.setFormat,{tiebreakTo:c,NoAD:u}=s??{},d=Bb({set:a});if(!t.isTiebreakSet){const t=Number.parseInt(e.split(o).reverse()[0]),n=xb({lowValue:t,tiebreakTo:c,NoAD:u});1===d?(a.side1TiebreakScore=n,a.side2TiebreakScore=t):(a.side1TiebreakScore=t,a.side2TiebreakScore=n)}e=(e||"")+i,t.isDecidingSet||(e+=rb);const p=Vb({analysis:t,set:a});return a.winningSide=p||void 0,{scoreString:e,sets:n,updated:!0}}({analysis:t,scoreString:r,sets:i})):t.isTiebreakSetValue?({info:a,scoreString:u,sets:c,updated:s}=function({analysis:t,auto:e,lowSide:n,scoreString:r="",sets:i,value:o}){let a,s;const{tiebreakSet:{tiebreakTo:c,NoAD:u}}=t.setFormat,[d]=hb.split("");if(t.isMatchTiebreakEntry||(r+=d),i[t.setNumber-1]){const{lastOpenBracketIndex:t}=Fb({brackets:hb,scoreString:r}),d=(r.slice((t??0)+1)+(e?"":o)).split(wb);if((d[n-1]?.length||0)>=2)s="tiebreak digit limit";else if(e){1===n&&(d[0]=(d[0]||"")+o),2===n&&(d[1]=(d[1]||"")+o);const e=[d[0]||0,d[1]||0].map(t=>p(t)),s=1===n?1:0;e[s]=e[1-s]+(u?1:2),e[s]<c&&(e[s]=c);const l=i[i.length-1];l.side1TiebreakScore=e[0],l.side2TiebreakScore=e[1],r=r.slice(0,(t??0)+1),r+=e.join(wb),a=!0}else{const t=[d[0]||0,d[1]||0].map(t=>p(t)),e=i[i.length-1];e.side1TiebreakScore=t[0],e.side2TiebreakScore=t[1],r+=o,a=!0}}else{const t=xb({lowValue:p(o||0),tiebreakTo:c,NoAD:u}),e=[p(o),t];2===n&&e.reverse();const s={side1TiebreakScore:e[0],side2TiebreakScore:e[1],setNumber:i?.length+1||1};i.push(s),r+=e.join(wb),a=!0}return{info:s,scoreString:r,sets:i,updated:a}}({analysis:t,auto:e,lowSide:n,scoreString:r,sets:i,value:o})):t.isSetTiebreakEntry?({info:a,scoreString:u,updated:s}=function({analysis:t,scoreString:e,value:n}){let r,i;const[o]=fb.split(""),a=Math.max(...B(o,e.split(""))),s=e.slice(a+1),c=s&&0===p(s),u=p(s?s+n:n),{tiebreakFormat:d}=t.setFormat,{tiebreakTo:l,NoAD:m}=d??{};return!c&&s.length<2?m&&u>l-1?r="invalid low value for NoAD tiebreak":(i=!0,e=(e||"")+n):r=c?"tiebreak begins with zero":"tiebreak digit limit",{info:r,scoreString:e,updated:i}}({analysis:t,scoreString:r,value:o})):t.isCloser?a=`invalid key: ${o}`:t.isGameScoreEntry?a="game scoreString entry":t.lastSetIsComplete||!i.length?({scoreString:u,sets:c,updated:s}=Wb({analysis:t,lowSide:n,scoreString:r,sets:i,value:o})):console.log("error: unknown outcome");return{info:a,updated:s,sets:c,scoreString:u}}({analysis:t,auto:s,lowSide:e,scoreString:r,sets:n,value:a}))}else({scoreString:l,sets:d,updated:u,matchUpStatus:m}=function({analysis:t,scoreString:e,sets:n,lowSide:r}){let i,o;return(!t.isSetTiebreakEntry||t.isSetTiebreakEntry&&!t.isNumericEnding)&&(i=!0,({scoreString:e,sets:n}=kb({analysis:t,scoreString:e,sets:n,lowSide:r})),o=void 0),{scoreString:e,sets:n,updated:i,matchUpStatus:o}}({analysis:t,scoreString:r,sets:n,lowSide:e}));return{info:c,updated:u,sets:d,scoreString:l,matchUpStatus:m,winningSide:f}}({analysis:m,lowSide:e,sets:i,scoreString:r,matchUpStatus:a,winningSide:o,value:n,auto:u});if(f.earlyReturn)return{updated:f.updated,info:f.info};({sets:i,scoreString:r,matchUpStatus:a,winningSide:o}=f);const{updated:h,info:g}=f;return h?function({sets:t,winningSide:e,matchUpStatus:n,matchUpFormat:r,scoreString:i,info:o}){t=t?.filter(Boolean);const{matchUpWinningSide:a}=_b({sets:t,winningSide:e,matchUpStatus:n,matchUpFormat:r});return e=a,!a||n&&![Ap,Rp].includes(n)?!i||e||[db,ub,lb].includes(n)||(n=void 0):(n="COMPLETED",t=t.filter(t=>{const{side1Score:e,side2Score:n,side1TiebreakScore:r,side2TiebreakScore:i}=t;return e||n||r||i})),{updated:!0,scoreString:i,sets:t,winningSide:e,matchUpStatus:n,info:o}}({sets:i,winningSide:o,matchUpStatus:a,matchUpFormat:s,scoreString:r,info:g}):{updated:h,scoreString:r,sets:i,winningSide:o,matchUpStatus:a,info:g}}var Hb={__proto__:null,keyValueScore:$b,parseMatchUpFormat:co,stringifyMatchUpFormat:ro};function zb(t,e,n,r,i,o,a){if(n&&r){const i=function(t,e,n,r){const i=r===n?n+1:n;return t!==i?{isValid:!1,error:`Tiebreak set winner must have ${i} games, got ${t}`}:e!==r?{isValid:!1,error:`Tiebreak set loser must have ${r} games, got ${e}`}:{isValid:!0}}(t,e,n,r);if(!i.isValid)return i}return(void 0!==i||void 0!==o)&&a?function(t,e,n){const r=Math.max(t||0,e||0),i=Math.min(t||0,e||0),o=r-i,a=n.tiebreakTo||7;return r<a?{isValid:!1,error:`Tiebreak winner must reach ${a} points, got ${r}`}:o<2?{isValid:!1,error:`Tiebreak must be won by 2 points, got ${r}-${i}`}:i>=a-1&&o>2?{isValid:!1,error:`Tiebreak score ${r}-${i} is invalid`}:{isValid:!0}}(i,o,a):{isValid:!0}}function Yb(t,e,n,r){if(!e)return{isValid:!0};const i=co(e);if(!i)return{isValid:!0};const o=n&&i.finalSetFormat?i.finalSetFormat:i.setFormat;if(!o)return{isValid:!0};if(o.timed){if(!r){const e=t.side1Score??0,n=t.side2Score??0;if(0===e&&0===n)return{isValid:!1,error:"Timed set requires at least one side to have scored"};if("P"===o.based&&e===n&&e>0&&o.tiebreakFormat){if(!(void 0!==t.side1TiebreakScore||void 0!==t.side2TiebreakScore))return{isValid:!1,error:"Tied timed set requires tiebreak"}}}return{isValid:!0}}const{setTo:a,tiebreakAt:s,tiebreakFormat:c,tiebreakSet:u}=o,d=u?.tiebreakTo,p=!!d&&!a,l=void 0!==t.side1TiebreakScore&&void 0!==t.side2TiebreakScore,{side1Score:m,side2Score:f,side1TiebreakScore:h,side2TiebreakScore:g}=function(t,e,n){const r=t.side1TiebreakScore,i=t.side2TiebreakScore;return{side1Score:e&&n?r:t.side1Score||t.side1||0,side2Score:e&&n?i:t.side2Score||t.side2||0,side1TiebreakScore:r,side2TiebreakScore:i}}(t,p,l),I=Math.max(m,f),S=Math.min(m,f),y=I-S;if(p){return function(t,e,n,r,i,o=!1){return i?{isValid:!0}:0===t&&0===e?{isValid:!1,error:"Tiebreak-only set requires both scores"}:t<r?{isValid:!1,error:`Tiebreak-only set winner must reach at least ${r}, got ${t}`}:n<(o?1:2)?{isValid:!1,error:o?`Tiebreak-only set (NoAD) must be won by at least 1 point, got ${t}-${e}`:`Tiebreak-only set must be won by at least 2 points, got ${t}-${e}`}:o?{isValid:!0}:t===r&&e>r-2?{isValid:!1,error:`Tiebreak-only set at ${r}-${e} requires playing past ${r}`}:t>r&&2!==n?{isValid:!1,error:`Tiebreak-only set past ${r} must be won by exactly 2 points, got ${t}-${e}`}:{isValid:!0}}(I,S,y,d,r??!1,t.NoAD??o.tiebreakSet?.NoAD??!1)}return void 0!==h||void 0!==g||a&&I===a+1&&S===a?zb(I,S,a,s,h,g,c):function(t,e,n){const{side1:r,side2:i,winner:o,loser:a,diff:s}=t,{setTo:c,tiebreakAt:u,winBy:d}=e;if(c&&u){const t=function(t,e,n,r){return r?t===n+1&&e<n-1?{isValid:!1,error:`With tiebreak format, if side 1 has ${n+1} games, side 2 must be at least ${n-1}, got ${e}`}:e===n+1&&t<n-1?{isValid:!1,error:`With tiebreak format, if side 2 has ${n+1} games, side 1 must be at least ${n-1}, got ${t}`}:{isValid:!0}:{isValid:!0}}(r,i,c,u);if(!t.isValid)return t}return n?function(t,e,n){return n&&(t>n+10||e>n+10)?{isValid:!1,error:`Set score ${t}-${e} exceeds expected range for ${n}-game sets`}:{isValid:!0}}(o,a,c):c?function(t,e,n,r,i,o=2){if(t<r)return{isValid:!1,error:`Set winner must reach ${r} games, got ${t}`};const a=i&&t===r&&e===i&&1===n;if(n<o&&!a)return{isValid:!1,error:`Set must be won by at least ${o} game${1===o?"":"s"}, got ${t}-${e}`};if(i){if(e>=i&&!a)return{isValid:!1,error:`When tied at ${i}-${i}, must play tiebreak. Use format like ${i+1}-${i}(5)`};const n=i===r?r+1:r;if(t>n)return{isValid:!1,error:`With tiebreak format, set score cannot exceed ${n}-${i}. Got ${t}-${e}`}}else if(t>r+10)return{isValid:!1,error:`Set score ${t}-${e} exceeds reasonable limits`};return{isValid:!0}}(o,a,s,c,u,d):{isValid:!0}}({side1:m,side2:f,winner:I,loser:S,diff:y},{setTo:a,tiebreakAt:s,winBy:o.winBy},r)}function Kb(t,e,n){if(!t||0===t.length)return{isValid:!0};const r=e?.match(/SET(\d+)/)?.[1],i=r?Number.parseInt(r):3,o=[Np,Ep,Pp].includes(n||"");for(let r=0;r<t.length;r++){const a=t[r],s=r+1===i,c=void 0!==a.winningSide,u=Yb(a,e,s,o||void 0===n&&!c);if(!u.isValid)return{isValid:!1,error:`Set ${r+1}: ${u.error}`}}return{isValid:!0}}function Qb(t){return!!t?.aggregate}function Jb(t,e,n,r,i,o){const a=e+1===r,{side1Score:s,side2Score:c,side1TiebreakScore:u,side2TiebreakScore:d,winningSide:p}=t,l=Math.max(s??0,c??0),m=u??d,{finalSetFormat:f,setFormat:h}=n,g=a&&f||h;if(m){const t=function(t,e,n,r,i,o){const{tiebreakTo:a,NoAD:s}=t??{},c=Math.max(e??0,n??0);if(s&&c>a)return!1;if(c<a&&r){if(i&&!o)return!1;if(!i)return!1}return!0}(g?.tiebreakFormat,u,d,p,i,o);if(!t)return!1}if(!g.setTo)return!0;return!(!g.noTiebreak&&l>g.setTo+1)}function Xb({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:n,winningSide:r,score:i}){const o=i?.sets??[],a=(o?.filter(t=>t?.winningSide)??[]).reduce((t,e)=>{const{winningSide:n}=e;if(!n)return t;return t[n-1]++,t},[0,0]),s=r?r-1:void 0,c=void 0!==s&&[0,1].includes(s)?1-s:void 0,u=void 0!==s&&a[s],d=void 0!==c&&a[c],p=e?co(e):void 0,l=Math.max(...a),m=C(a)[l],f=p?.setFormat?.timed||p?.finalSetFormat?.timed,h=p?.bestOf||p?.exactly,g=h&&Math.ceil(h/2)||1,I=n??t,S=!(!I||![Pp,Np,Ep].includes(I)),y=!p||!o.length||o.every((t,e)=>Jb(t,e,p,h??0,e===o.length-1,S)),v=p?.exactly,U=!v||!I||I!==vp||S||o.length>=v,P=Qb(p),T=P&&o.length>0?function(t){const e=t.reduce((t,e)=>(void 0===e.side1Score&&void 0===e.side2Score||(t[0]+=e.side1Score??0,t[1]+=e.side2Score??0),t),[0,0]);if(e[0]>e[1])return 1;if(e[1]>e[0])return 2;{const e=t.find(t=>void 0!==t.side1TiebreakScore||void 0!==t.side2TiebreakScore);return e?.winningSide}}(o):function(t,e,n,r,i){return(!i||t===e)&&1===n&&r.indexOf(t)+1||void 0}(l,g,m,a,e);return{valid:!!(y&&U&&(r&&P&&r===T||r&&!P&&u>d&&r===T||r&&S||!r&&!T&&(![vp,Pp,Np,Ep].includes(I)||f&&I===vp)))}}function Zb({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:n,winningSide:r,score:i}){if("object"!=typeof i)return{error:sr};const{sets:o,scoreStringSide1:a,scoreStringSide2:s}=i,c="scoreString must be a string!";if(void 0!==a&&"string"!=typeof a)return{error:sr,info:c};if(void 0!==s&&"string"!=typeof s)return{error:sr,info:c};if(void 0!==o&&!Array.isArray(o))return{error:sr,info:nv("sets")};if(o?.length){const a=o.map(t=>t?.setNumber).filter(Boolean);if(a.length!==M(a).length)return{error:sr,info:"setNumbers not unique"};for(const t of o){const{side1Score:e,side2Score:n,side1TiebreakScore:r,side2TiebreakScore:i,side1PointScore:o,side2PointScore:a,winningSide:s,setNumber:c}=t;if(![[e,n],[r,i]].filter(t=>t.some(t=>![void 0,null].includes(t))).every(t=>t.every(t=>R(t))))return{error:sr,info:"non-numeric values"};const u=[o,a];if(u.some(t=>null!=t)&&!u.every(t=>null!=t))return{error:sr,info:"both sides must have point scores if one does"};if(![c,s].filter(t=>![void 0,null].includes(t)).every(t=>R(t)))return{error:sr,info:"non-numeric values"};if(s&&![1,2].includes(s))return{error:sr,info:"winningSide must be 1 or 2"}}const{valid:s}=Xb({existingMatchUpStatus:t,matchUpStatus:n,matchUpFormat:e,winningSide:r,score:i});if(!s)return{error:We,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}const tN=t=>{const{isSide1:e,lowValue:n,setTo:r,tiebreakAt:i,NoAD:o,winBy:a}=t;if(void 0===n)return!1;let s,c=p(n);c?.toString().length>2&&(c=Number.parseInt(c.toString().slice(0,2))),i&&i<r&&c>i&&(c=i),s=i||1!==a?o&&!i?c>r||c<r?r:r-1:c+1<r&&r||i&&i<r&&c===i&&r||!i&&c+2||r+1:r;return[e?c:s,e?s:c]},eN=t=>{const{isSide1:e,lowValue:n,tiebreakTo:r,tiebreakNoAd:i}=t;if(void 0===n)return!1;let o="string"==typeof n?Number.parseInt(n):n;o?.toString().length>2&&(o=Number.parseInt(o.toString().slice(0,2))),i&&o>r-1&&(o=r-1);const a=function(t){const{lowValue:e,NoAD:n,tiebreakTo:r}=t,i=n?1:2;if(e+1>=r)return e+i;return r}({lowValue:o,NoAD:i,tiebreakTo:r});return[e?o:a,e?a:o]};function nN(t,e){return(t>e?1:t<e&&2)||void 0}function rN({tiebreakTo:t=7,scoreString:e="",matchUpFormat:n}){let r,i=3;if(n)try{r=co(n);const t=/SET(\d+)/.exec(n)?.[1];i=t?Number.parseInt(t):3}catch{}return e?.split(" ").filter(Boolean).map((t,e)=>function({set:t,setNumber:e}){const n=/\[([^\]]+)\]/,a=/\(([^)]+)\)/.exec(t),s=n.exec(t),c=t?.startsWith("[")&&s,u=function(t,e){if(!r||!e)return!1;const n=t===i,o=n&&r.finalSetFormat?r.finalSetFormat:r.setFormat;if(!o)return!1;const a=o.tiebreakSet?.tiebreakTo,s=o.setTo;return!!a&&!s}(e,!!c),d=o(e),p=u&&1===d;let l;if(c){l=function(t,e){return e?{side1Score:t[0],side2Score:t[1],winningSide:nN(t[0],t[1])}:{side1TiebreakScore:t[0],side2TiebreakScore:t[1],winningSide:nN(t[0],t[1])}}(s[1].split("-").map(t=>Number.parseInt(t)),u)}else l=function(t,e,n,r){const i=e&&t.replace(e[0],"")||n&&t.replace(n[0],"")||t,a=i.split("-").map(t=>Number.parseInt(t)),s=a[0],c=a[1],u=nN(s,c);let d,p;e&&([d,p]=function(t,e,n){const r=t[1],i=o(n),a=eN({lowValue:r,isSide1:2===e,tiebreakTo:i});if(Array.isArray(a))return[a[0],a[1]];return[void 0,void 0]}(e,u,r));if(n){const t=n[1].split("-").map(t=>Number.parseInt(t));d=t[0],p=t[1]}return{side1Score:s,side2Score:c,side1TiebreakScore:d,side2TiebreakScore:p,winningSide:u}}(t,a,s,e);return{side1Score:l.side1Score,side2Score:l.side2Score,side1TiebreakScore:l.side1TiebreakScore,side2TiebreakScore:l.side2TiebreakScore,winningSide:l.winningSide,setNumber:e,...p&&{NoAD:!0},...u&&{tiebreakSet:!0}}}({set:t,setNumber:e+1}));function o(e){if(!r)return t;const n=e===i&&r.finalSetFormat?r.finalSetFormat:r.setFormat;return n?.tiebreakSet?.tiebreakTo??n?.tiebreakFormat?.tiebreakTo??t}}function iN(t){const{setObject:e,matchUpScoringFormat:n}=t;if(!e)return{error:Ne};const{setNumber:r}=e??{},{bestOf:i,exactly:o}=n??{},a=i||o,s=!(!r||!a||r!==a),c=s&&n?.finalSetFormat||n?.setFormat,u=!!c?.tiebreakSet,d=!!c?.timed,p=!u&&!d,l=!!(r&&a&&r<=a),m=function(t){return{sideGameScores:[t?.side1Score,t?.side2Score],sidePointScores:[t?.side1PointScore,t?.side2PointScore],sideTiebreakScores:[t?.side1TiebreakScore,t?.side2TiebreakScore]}}(e),{sideGameScores:f,sidePointScores:h,sideTiebreakScores:g}=m,I=f.filter(t=>void 0!==t).length,S=h.filter(t=>void 0!==t).length,y=g.filter(t=>void 0!==t).length,v=f?.filter(t=>"number"==typeof t&&!Number.isNaN(t)).length,U=g?.filter(t=>"number"==typeof t&&!Number.isNaN(t)).length,{tiebreakAt:P}=c??{},T=P&&2===f.filter(t=>t>=P).length,w=function(t,e){return t?e[0]>e[1]?1:e[1]>e[0]?2:void 0:void 0}(T,f),D=!(!U||v),R=!!e?.winningSide,{error:b,result:N}=function({setObject:t,setFormat:e,sideGameScores:n,sideTiebreakScores:r}){if(!t)return{result:!1,error:Ne};const i=!!e?.tiebreakSet,o=!!e?.timed;if(!e||i||o)return{result:!1,error:sr};const a=2===n?.filter(t=>"number"==typeof t&&!Number.isNaN(t)).length;if(!a)return{result:!1,error:qe};const{setTo:s,tiebreakAt:c,tiebreakFormat:u,NoAD:d}=e??{},p=!(!s||!n?.find(t=>t>=s));if(!p)return{result:!1,error:qe};const l=new Set([1,2]).has(t?.winningSide);if(!t||!l)return{result:!1,error:$e};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 S=function({winningSideGameScore:t,sideTiebreakScores:e,winningSideIndex:n,losingSideIndex:r,sideGameScores:i,gamesDifference:o,tiebreakFormat:a,tiebreakAt:s,setTo:c}){const u=s&&a;if(!u)return;const d=2===e?.filter(t=>"number"==typeof t&&!Number.isNaN(t)).length,p=e?.[n],l=e?.[r],m=s&&2===i.filter(t=>t>=s).length,{NoAD:f,tiebreakTo:h}=a;if(m){if(o>1)return{result:!1,error:{message:"invalid winning game scoreString (5)"}};if(!d)return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if("number"!=typeof h||Number.isNaN(h))return{result:!1,error:{message:"tiebreakTo error"}};if(!!(!h||!e?.find(t=>t>=h)))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};if(t>(s<c?c:c+1))return{result:!1,error:{message:"invalid winning game scoreString (1)"}};if(!p||!l||p<l)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};const n=p-l;if(n&&l>=h-1&&n<(f?1:2))return{result:!1,error:{message:"invalid tiebreak scores (3)"}}}const g=t>c;if(g&&!m)return{result:!1,error:{message:"invalid winning game scoreString (2)"}};return}({winningSideGameScore:h,sideTiebreakScores:r,winningSideIndex:m,losingSideIndex:f,sideGameScores:n,gamesDifference:I,tiebreakFormat:u,tiebreakAt:c,setTo:s});if(S)return S;const y=c&&2===n.filter(t=>t>=c).length,v=d?1:2,U=g>=s-1,P=I&&U&&!y&&I<v;if(P)return{result:!1,error:{message:"invalid winning game scoreString (3)"}};if(I>v&&h>s)return{result:!1,error:{message:"invalid winning game scoreString (4)"}};return{result:!0}}({sideTiebreakScores:g,sideGameScores:f,setFormat:c,setObject:e}),{error:M,result:A}=function({setObject:t,setFormat:e,sideTiebreakScores:n}){if(!t)return{result:!1,error:Ne};const r=!!e?.tiebreakSet,i=!!e?.timed;if(!e||!r||i)return{result:!1,error:{message:"not tiebreak set"}};const o=new Set([1,2]).has(t?.winningSide);if(!t||!o)return{result:!1,error:$e};const{tiebreakSet:a}=e??{},{NoAD:s,tiebreakTo:c}=a??{},u=2===n?.filter(t=>"number"==typeof t&&!Number.isNaN(t)).length;if(!u)return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(Number.isNaN(c))return{result:!1,error:{message:"tiebreakTo error"}};const d=!!n?.find(t=>t>=c);if(!d)return{result:!1,error:{message:"invalid tiebreak scores (2)"}};const p=t?.winningSide-1,l=1-p,m=n[p],f=n[l];if(!m||!f||m<f)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};const h=s?1:2,g=m-f,I=f>=c-1;if(g&&I&&g<h)return{result:!1,error:{message:"invalid tiebreak scores (3)"}};return{result:!0}}({sideTiebreakScores:g,setObject:e,setFormat:c}),E=function({isValidStandardSetOutcome:t,isValidTiebreakSetOutcome:e,expectStandardSet:n,expectTiebreakSet:r,expectTimedSet:i,isTiebreakSet:o}){return n&&!o&&t||r&&o&&e||i}({isValidStandardSetOutcome:N,isValidTiebreakSetOutcome:A,expectStandardSet:p,expectTiebreakSet:u,expectTimedSet:d,isTiebreakSet:D}),C=l&&!(u&&!D)&&!(p&&D)&&(!R||E),O=function({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:n,isTimedSet:r,setObject:i}){if(!i)return;const o=Bb({set:i});return Lb({matchUpScoringFormat:t,set:i,isDecidingSet:e,isTiebreakSet:n,isTimedSet:r})&&o||void 0}({isTimedSet:d,matchUpScoringFormat:n,isDecidingSet:s,isTiebreakSet:D,setObject:e}),k={expectTiebreakSet:u,expectTimedSet:d,hasTiebreakCondition:T,isCompletedSet:R,isDecidingSet:s,isTiebreakSet:D,isValidSet:C,isValidSetNumber:l,isValidSetOutcome:E,leadingSide:w,setFormat:c,sideGameScores:f,sideGameScoresCount:I,sidePointScores:h,sidePointScoresCount:S,sideTiebreakScores:g,sideTiebreakScoresCount:y,winningSide:O};return void 0!==e?.winningSide&&function({isValidStandardSetOutcome:t,isValidTiebreakSetOutcome:e,standardSetError:n,tiebreakSetError:r,isTiebreakSet:i,analysis:o}){i?(o.isValidTiebreakSetOutcome=e,e||(o.tiebreakSetError=r)):(o.isValidStandardSetOutcome=t,t||(o.standardSetError=n))}({isValidStandardSetOutcome:N,isValidTiebreakSetOutcome:A,standardSetError:b,tiebreakSetError:M,isTiebreakSet:D,analysis:k}),k}const oN="SET3-S:6/TB7";function aN(t){const e=t.split(/[\s,]+/).filter(t=>t.length>0);if(0===e.length)return oN;const n=1===(r=e.length)?1:2===r?3:5;var r;const i=function(t,e){for(const n of t){const t=sN(n);if(2===t.length){const n=Math.max(...t),r=Math.min(...t);if(10===n||n>10&&n-r<=2)return`SET${e}-S:TB10`}}return}(e,n);if(i)return i;const o=function(t){const e=t.find(t=>/\(/.test(t));if(e)return function(t){const e=sN(t);if(0===e.length)return;const n=Math.max(...e),r=Math.min(...e);if(n===r+1)return r;return n-1}(e);return function(t){const e=[];for(const n of t){const t=sN(n);t.length>0&&e.push(Math.max(...t))}if(0===e.length)return;const n=Math.max(...e);return n>=6?6:n}(t)}(e);if(void 0===o)return oN;const a=function(t,e){if(t.length<3)return!1;const n=t.at(-1),r=sN(n);if(2!==r.length)return!1;const i=Math.max(...r),o=Math.min(...r);return i>e+1&&i-o===2}(e,o);return function(t,e,n){let r;r=6===e?`SET${t}-S:6/TB7`:4===e?`SET${t}-S:4/TB7`:`SET${t}-S:${e}/TB7`;n&&(r+=`-F:${e}`);return r}(n,o,a)}function sN(t){const e=t.replaceAll(/\([^)]*\)/g,"");return e.match(/(\d+)/g)?.map(t=>Number.parseInt(t,10))??[]}var cN={__proto__:null,analyzeScore:Xb,analyzeSet:iN,calculateMatchStatistics:SR,checkScoreHasValue:aI,checkSetIsComplete:Lb,deduceMatchUpFormat:aN,enrichPointHistory:yR,getEpisodes:MR,getQuickStats:vR,getScore:ZR,getScoreboard:NR,getSetComplement:tN,getTiebreakComplement:eN,getWinner:FR,isComplete:kR,isValidMatchUpFormat:Io,parseScoreString:rN,toStatObjects:wR,validateMatchUpScore:Kb,validateScore:Zb,validateSetScore:Yb,validateTieFormat:na};function uN(t){const{matchUp:e,expectedScore:n}=t;if(!e)return{isValid:!1,errors:["No matchUp provided"],warnings:[],actual:{sets:[],scoreString:""},expected:{sets:n?.sets,scoreString:n?.scoreString},pointsProcessed:0,pointsRejected:0};const r=[],i=[];let o=bR({matchUpFormat:e?.matchUpFormat,matchUpId:e?.matchUpId,participants:e?.sides?.map(t=>t.participant).filter(t=>void 0!==t)});const a=e?.history?.points??[];0===a.length&&i.push("No points found to validate");let s=0,c=0;for(const t of a)try{o=$R(o,{winner:t.winner,server:t.server}),s++}catch(e){c++;const n=e instanceof Error?e.message:String(e);r.push(`Point ${t.pointNumber||s+1}: ${n}`)}const u=ZR(o);return n&&(n.sets&&(u.sets.length!==n.sets.length&&r.push(`Set count mismatch: expected ${n.sets.length}, got ${u.sets.length}`),n.sets.forEach((t,e)=>{const n=u.sets[e];n?(void 0!==t.side1Score&&n.side1Score!==t.side1Score&&r.push(`Set ${e+1} side1Score: expected ${t.side1Score}, got ${n.side1Score}`),void 0!==t.side2Score&&n.side2Score!==t.side2Score&&r.push(`Set ${e+1} side2Score: expected ${t.side2Score}, got ${n.side2Score}`),void 0!==t.side1TiebreakScore&&n.side1TiebreakScore!==t.side1TiebreakScore&&r.push(`Set ${e+1} side1TiebreakScore: expected ${t.side1TiebreakScore}, got ${n.side1TiebreakScore}`),void 0!==t.side2TiebreakScore&&n.side2TiebreakScore!==t.side2TiebreakScore&&r.push(`Set ${e+1} side2TiebreakScore: expected ${t.side2TiebreakScore}, got ${n.side2TiebreakScore}`)):r.push(`Missing set ${e+1}`)})),n.scoreString&&u.scoreString!==n.scoreString&&r.push(`Score string mismatch: expected "${n.scoreString}", got "${u.scoreString}"`)),{isValid:0===r.length,errors:r,warnings:i,actual:{sets:u.sets,scoreString:u.scoreString},expected:{sets:n?.sets,scoreString:n?.scoreString},pointsProcessed:s,pointsRejected:c}}function dN(t){return t.replace(/\s+/g,"").replace(/,/g,", ").toLowerCase()}const pN={4:"Wide",5:"Body",6:"T"},lN={f:"Forehand",r:"Forehand Slice",v:"Forehand Volley",o:"Overhead Smash",u:"Forehand Drop Shot",l:"Forehand Lob",h:"Forehand Half-volley",j:"Forehand Drive Volley"},mN={b:"Backhand",s:"Backhand Slice",z:"Backhand Volley",p:"Backhand Overhead Smash",y:"Backhand Drop Shot",m:"Backhand Lob",i:"Backhand Half-volley",k:"Backhand Drive Volley"},fN={...lN,...mN,t:"Trick Shot",q:"Unknown Shot"},hN={7:"shallow",8:"deep",9:"very deep"},gN={1:1,2:2,3:3},IN={"+":"approach","-":"net","=":"baseline"},SN={n:"Net",w:"Out Wide",d:"Out Long",x:"Out Wide and Long",g:"Foot Fault",e:"Unknown","!":"Shank"};function yN(t){const e=[];let n="";for(let r=0;r<t.length;r++){const i=t[r];i&&("fbrsvzouymlhijkpqt".includes(i)||"456".includes(i)?(n&&e.push(n),n=i):n+=i)}return n&&e.push(n),e}function vN(t){return t.includes("*")?"*":t.includes("#")?"#":t.includes("@")?"@":void 0}function UN(t){if(t)for(const e of Object.keys(SN))if(t.includes(e))return e}function PN(t){if(!m(t))return{serves:[],rally:[]};let e,n,r;const i=t.split("c").length-1,o=yN(t=t.split("c").join(""));let a=o;for(let t=o.length-1;t>=0;t--){const i=o[t];if(i&&(n=vN(i),n)){a=o.slice(0,t+1),r=o.slice(t+1),e=i;break}}const s=function(t){const e=[];for(const n of t){if(!n)continue;const t=n[0];if(!t||!/[456]/.test(t))break;e.push(n)}return e}(a),c=s.length?a.slice(s.length):a;if(!n&&!s.length&&1===c.length){const t=c[0];t&&["S","P","Q","R"].includes(t)&&(e=t,c.length=0)}const u={serves:s,rally:c};return i&&(u.lets=i),n&&(u.terminator=n),e&&(u.result=e),u}function TN(t){const e=t.join("|"),n=wN(t[0],1);if("S"===n.winner||!t[1])return n.serve=1,n.code=e,n;const r=wN(t[1],2);return r.serve=2,r.first_serve={serves:n.serves},n.lets&&(r.first_serve.lets=n.lets),n.error&&(r.first_serve.error=n.error),n.parse_notes&&(r.first_serve.parse_notes=n.parse_notes),r.code=e,r}function wN(t,e){const n=PN(t);if(["Q","S"].includes(n.result||""))return n.winner="S",n;if(["P","R"].includes(n.result||""))return n.winner="R",n;if(!n.terminator&&!UN(n.serves[0])&&n.serves.length>2)return n.winner="R",n;const r=(n.serves.length+n.rally.length)%2==0?"R":"S";let i;return n.rally.length>0?i=n.rally[n.rally.length-1]:n.serves.length>0&&(i=n.serves[n.serves.length-1]),i?n.rally.length?function(t,e,n){if(1===t.rally.length&&n.includes("#")){t.result="Serve Winner",t.winner="S";const e=UN(n);return e&&(t.error=SN[e]),t}n.includes("#")?(t.result="Forced Error",t.error=SN[UN(n)],t.winner="R"===e?"S":"R"):n.includes("*")?(t.result="Winner",t.winner=e):n.includes("@")?(t.result="Unforced Error",t.error=SN[UN(n)],t.winner="R"===e?"S":"R"):UN(t.serves[0])?1===t.rally.length&&UN(n)&&(t.error=SN[UN(n)],t.winner="R"===e?"S":"R"):t.serves.length&&t.rally.length?(t.parse_notes="no terminator: receiver wins point",t.result="Unknown",t.winner="R"):1===t.rally.length&&UN(n)&&(t.error=SN[UN(n)],t.winner="R"===e?"S":"R");return t}(n,r,i):function(t,e){if("*"===t.terminator)t.result="Ace",t.winner="S";else if("#"===t.terminator)t.result="Serve Winner",t.winner="S";else{const n=UN(t.serves[0]);n?(t.error=SN[n],2===e&&(t.result="Double Fault",t.winner="R")):(t.parse_notes="treated as a fault",2===e&&(t.result="Double Fault",t.winner="R"))}return t}(n,e):{...n,winner:void 0}}function DN(t){if(t)for(const e of t){const t=fN[e];if(t)return t}}function RN(t,e){const n=function(t,e){return t.PtWinner===t.Svr?e:1-e}(t,e),r=t["1st"]||"",i=t["2nd"]||"";if(!r&&!i)return{winner:n,server:e,result:"Unknown"};const o=TN([r,i]),a={winner:n,server:e};o.result&&(a.result=o.result),o.serve&&(a.serve=o.serve);const s=function(t){if(t)for(const e of t){const t=pN[e];if(t)return t}}(1===o.serve?r:i);s&&(a.serveLocation=s);const c=o.rally[o.rally.length-1];if(c){const t=DN(c);t&&(a.stroke=t,Object.values(lN).includes(t)?a.hand="Forehand":Object.values(mN).includes(t)&&(a.hand="Backhand"))}const u=function(t,e,n){const r=[];let i=1,o=n;if(t.length>0&&!UN(t[t.length-1])){const e=t[t.length-1],n=DN(e)||"Forehand";r.push({shotNumber:i++,player:o,stroke:n,code:e}),o=1-o}for(const t of e){const e=DN(t);if(!e)continue;const n={shotNumber:i++,player:o,stroke:e,code:t};for(const e of t){const t=gN[e];void 0!==t&&(n.direction=t)}for(const e of t){const t=hN[e];t&&(n.depth=t)}for(const e of t){const t=IN[e];t&&(n.position=t)}r.push(n),o=1-o}return r}(o.serves,o.rally,e);return u.length>0&&(a.rally=u,a.rallyLength=u.length),o.code&&(a.code=o.code),a}function bN(t){if(!t||!m(t))return[];const e=t.trim().split("\n");if(e.length<2)return[];const n=e[0]?.split(",")??[],r=[];for(let t=1;t<e.length;t++){const i=e[t];if(!i)continue;const o=i.split(","),a={};for(let t=0;t<n.length;t++){const e=n[t];e&&(a[e]=o[t]||"")}r.push(a)}return r}function NN(t){if(!Array.isArray(t))return[];const e=new Map;for(const n of t){const t=n.match_id;e.has(t)||e.set(t,[]),e.get(t).push(n)}return Array.from(e.entries()).map(([t,e])=>({match_id:t,points:e}))}function MN(t,e={}){const{matchUpFormat:n,validateScore:r=!0,debug:i=!1}=e,o=[],a=[],s=function(t){const e=t?.split("-")??[];if(e.length<6)return{player1:"Player 1",player2:"Player 2"};const n=e[0],r=e[2]?.replaceAll("_"," ");return{player1:e[4]?.replaceAll("_"," ")||"Player 1",player2:e[5]?.replaceAll("_"," ")||"Player 2",date:n,tournament:r}}(t.match_id),c=function(t){if(!t||0===t.length)return;const e=t.at(-1);if(!e)return;const n=e.Set1,r=e.Set2,i=e.Set3,o=e.Set4,a=e.Set5,s=[];return n&&s.push(`${n}-${r}`),i&&s.push(`${i}-${r||"0"}`),o&&s.push(`${o}-${r||"0"}`),a&&s.push(`${a}-${r||"0"}`),s.length>0?s.join(", "):void 0}(t.points);let u,d=!1;n?u=n:c?(u=aN(c),d=!0,i&&console.log(`Deduced format: ${u} from score: ${c}`)):(u="SET3-S:6/TB7",d=!0,a.push("No format provided, using default SET3-S:6/TB7")),i&&(console.log(`Validating match: ${s.player1} vs ${s.player2}`),console.log(`Format: ${u}`),console.log(`Total points: ${t.points.length}`),c&&console.log(`Expected score: ${c}`));let p=bR({matchUpFormat:u,matchUpId:t.match_id});p.sides[0]&&(p.sides[0].participant={participantId:"player1",participantName:s.player1,participantType:"INDIVIDUAL",participantRole:"COMPETITOR"}),p.sides[1]&&(p.sides[1].participant={participantId:"player2",participantName:s.player2,participantType:"INDIVIDUAL",participantRole:"COMPETITOR"});const l=function(t,e,n){const{errors:r,debug:i}=n;let o=e,a=0;const s={aces:0,doubleFaults:0,winners:0,unforcedErrors:0,forcedErrors:0};for(let e=0;e<t?.length;e++){const n=t[e];if(!n)continue;const c=AN(n,o,e,t.length,i,r,s);o=c.matchUp,c.processed&&a++}return{matchUp:o,pointsProcessed:a,...s}}(t.points,p,{errors:o,debug:i});p=l.matchUp;const m=function(t,e,n){const{errors:r,warnings:i,validateScore:o,debug:a}=n,s=ZR(t),c=s.scoreString,u="COMPLETED"===t.matchUpStatus;u||i.push(`Match not complete. Final score: ${c}`);let d;if(o&&e){const t=EN(e),n=EN(c);d=t===n,d||r.push(`Score mismatch: expected "${e}", got "${c}"`),a&&(console.log(`Expected: ${e} → ${t}`),console.log(`Actual: ${c} → ${n}`),console.log(`Score matches: ${d}`))}a&&(console.log(`Final score: ${c}`),console.log(`Match complete: ${u}`),console.log("Stats logged in processValidationPoints"));return{actualScore:c,scoreMatches:d}}(p,c,{errors:o,warnings:a,validateScore:r,debug:i});return{valid:0===o.length,errors:o,warnings:a,matchUp:p,pointsProcessed:l.pointsProcessed,expectedScore:c,actualScore:m.actualScore,scoreMatches:m.scoreMatches,formatDeduced:d,aces:l.aces,doubleFaults:l.doubleFaults,winners:l.winners,unforcedErrors:l.unforcedErrors,forcedErrors:l.forcedErrors}}function AN(t,e,n,r,i,o,a){const s="1"===t.Svr?0:1;try{const o=RN(t,s);if(function(t,e){if(t.history?.points&&t.history.points.length>0){const n=t.history.points.at(-1);n&&(e.result&&(n.result=e.result),e.stroke&&(n.stroke=e.stroke),e.hand&&(n.hand=e.hand),e.serve&&(n.serve=e.serve),e.serveLocation&&(n.serveLocation=e.serveLocation),e.rally&&(n.rally=e.rally),e.rallyLength&&(n.rallyLength=e.rallyLength),e.code&&(n.code=e.code))}}(e=$R(e,{winner:o.winner,server:o.server}),o),function(t,e){"Ace"===t&&e.aces++,"Double Fault"===t&&e.doubleFaults++,"Winner"===t&&e.winners++,"Unforced Error"===t&&e.unforcedErrors++,"Forced Error"===t&&e.forcedErrors++}(o.result,a),i&&(n<5||n===r-1)){const t=ZR(e);console.log(`Point ${n+1}: ${o.result||"Rally"} → ${t.scoreString}`)}return{matchUp:e,processed:!0}}catch(t){const r=t instanceof Error?t.message:String(t);return o.push(`Point ${n+1}: ${r}`),i&&console.error(`Point ${n+1} failed:`,r),{matchUp:e,processed:!1}}}function EN(t){return t.replaceAll(/\s+/g,"").replaceAll(",",", ").toLowerCase()}var CN={__proto__:null,ScoringEngine:tb,addPoint:$R,analyzeScore:Xb,analyzeSequence:PN,analyzeSet:iN,calculateMatchStatistics:SR,calculatePointsTo:xR,checkScoreHasValue:aI,checkSetIsComplete:Lb,createMatchUp:bR,deduceMatchUpFormat:aN,enrichPointHistory:yR,exportMatchUpJSON:function(t){return JSON.stringify(t,null,2)},generate:eb,generateScoreString:aR,generateTieMatchUpScore:dT,getEpisodes:MR,getQuickStats:vR,getScore:ZR,getScoreboard:NR,getSetComplement:tN,getSetScoreString:function(t){const e=t?.side1Score||0,n=t?.side2Score||0;if(void 0!==t?.side1TiebreakScore||void 0!==t?.side2TiebreakScore){const r=t?.side1TiebreakScore||0;return e>n?`${e}-${n}(${t?.side2TiebreakScore||0})`:`${e}(${r})-${n}`}return`${e}-${n}`},getTiebreakComplement:eN,getWinner:FR,groupByMatch:NN,helpers:Hb,inferServeSide:qR,isComplete:kR,isValidMatchUpFormat:Io,keyValueScore:$b,mcpValidator:function(t){const{csvData:e,matchId:n,matchUpFormat:r,debug:i=!1}=t,o=[],a=[],s=[];let c;try{c=bN(e)}catch(t){const e=t instanceof Error?t.message:String(t);return o.push(`Failed to parse CSV: ${e}`),{valid:!1,errors:o,warnings:a,matchesProcessed:0,pointsProcessed:0,matchUps:[],totalAces:0,totalDoubleFaults:0,totalWinners:0,totalUnforcedErrors:0,totalForcedErrors:0}}const u=NN(c);i&&console.log(`Parsed ${c.length} points from ${u.length} matches`);const d=n?u.filter(t=>t.match_id===n):u;if(0===d.length)return o.push(n?`Match ID not found: ${n}`:"No matches found in CSV data"),{valid:!1,errors:o,warnings:a,matchesProcessed:0,pointsProcessed:0,matchUps:[],totalAces:0,totalDoubleFaults:0,totalWinners:0,totalUnforcedErrors:0,totalForcedErrors:0};let p=0,l=0,m=0,f=0,h=0,g=0;for(const t of d){const e=MN(t,{matchUpFormat:r,debug:i});e.valid||o.push(...e.errors),a.push(...e.warnings),s.push(e.matchUp),p+=e.pointsProcessed,l+=e.aces,m+=e.doubleFaults,f+=e.winners,h+=e.unforcedErrors,g+=e.forcedErrors}return{valid:0===o.length,errors:o,warnings:a,matchesProcessed:d.length,pointsProcessed:p,matchUps:s,totalAces:l,totalDoubleFaults:m,totalWinners:f,totalUnforcedErrors:h,totalForcedErrors:g}},mutate:nb,parseCSV:bN,parseMCPPoint:RN,parseMatchUpFormat:co,parseScoreString:rN,pbpValidator:function(t){const{points:e,expectedScore:n,matchUpFormat:r,allowExtraPoints:i=!1,debug:o=!1}=t,a=[],s=[],c=[];let u,d=!1;r?u=r:n?(u=aN(n),d=!0,o&&console.log(`Deduced format: ${u} from score: ${n}`)):(u="SET3-S:6/TB7",d=!0,s.push("No format provided, using default SET3-S:6/TB7"));let p=bR({matchUpFormat:u});const l=e?.split("").map(t=>{const e=Number.parseInt(t,10);return Number.isNaN(e)||0!==e&&1!==e?null:e}).filter(t=>null!==t);if(0===l?.length)return a.push("No valid points found in point string"),{valid:!1,errors:a,warnings:s,pointsProcessed:0,pointsRejected:[],actualScore:"0-0",matchUpFormat:u,formatDeduced:d,sets:[]};let m=0;for(let t=0;t<l?.length;t++){const e=l[t];if("COMPLETED"!==p.matchUpStatus||i)try{if(p=$R(p,{winner:e}),m++,o){const n=ZR(p);console.log(`Point ${t+1}: ${e} → ${n.scoreString}`)}}catch(n){c.push(e);const r=n instanceof Error?n.message:String(n);a.push(`Point ${t+1}: ${r}`),o&&console.log(`Point ${t+1}: Error - ${r}`)}else c.push(e),o&&console.log(`Point ${t+1}: Rejected (match complete)`)}const f=ZR(p),h=f.scoreString,g=f.sets.map(t=>{const e=[t.side1Score||0,t.side2Score||0],n=void 0===t.side1TiebreakScore?void 0:[t.side1TiebreakScore,t.side2TiebreakScore||0];let r=`${e[0]}-${e[1]}`;return n&&(r=e[0]>e[1]?`${e[0]}-${e[1]}(${n[1]})`:`${e[0]}(${n[0]})-${e[1]}`),{games:e,tiebreak:n,scoreString:r}});let I=!0;if(n){dN(n)!==dN(h)&&(I=!1,a.push(`Score mismatch: expected "${n}", got "${h}"`))}return c.length>0&&s.push(`${c.length} excess points after match complete`),a.length>0&&(I=!1),{valid:I,errors:a,warnings:s,pointsProcessed:m,pointsRejected:c,expectedScore:n,actualScore:h,matchUpFormat:u,formatDeduced:d,sets:g}},pointParser:TN,query:cN,resolvePointValue:WR,reverseScore:cR,shotParser:wN,shotSplitter:yN,stringifyMatchUpFormat:ro,toStatObjects:wR,validateMCPMatch:MN,validateMatchUp:uN,validateMatchUpScore:Kb,validateScore:Zb,validateSet:function(t){const{points:e,matchUpFormat:n,expectedGames:r,expectedTiebreak:i}=t;return uN({matchUp:{matchUpId:"validation",matchUpFormat:n,matchUpStatus:"TO_BE_PLAYED",matchUpType:"SINGLES",sides:[{sideNumber:1},{sideNumber:2}],score:{sets:[]},history:{points:e?.map((t,e)=>({...t,pointNumber:e+1,timestamp:"",winner:t.winner,server:t.server}))}},expectedScore:{sets:[{side1Score:r?.[0],side2Score:r?.[1],side1TiebreakScore:i?.[0],side2TiebreakScore:i?.[1]}]}})},validateSetScore:Yb,validateTieFormat:na};function ON(t){const e=t.drawDefinition,{existingQualifyingPlaceholderStructureId:n,appliedPolicies:r,qualifyingOnly:i,drawEntries:o,structureId:a,tieFormat:s,idPrefix:c,isMock:u,event:d}=t,p=t.qualifyingProfiles,l=p?.length?ED({hasExistingDrawDefinition:!0,uuids:t.uuids,qualifyingProfiles:p,appliedPolicies:r,qualifyingOnly:i,tieFormat:s,idPrefix:c,isMock:u}):void 0;if(l?.error)return l;e.structures=e.structures?.filter(({structureId:t})=>t!==n);const m=new Set((e.structures??[]).map(t=>t.structureId));e.links=e.links?.filter(({source:t})=>t.structureId!==n&&m.has(t.structureId));const{qualifyingDrawPositionsCount:f,qualifyingDetails:h}=l??{};f&&(l?.structures&&e.structures?.push(...l.structures),l?.links&&e.links?.push(...l.links));const g=e.structures?.find(({stage:t,stageSequence:e})=>t===us&&1===e);!function({drawDefinition:t,drawEntries:e,event:n}){for(const r of(e??[]).filter(({entryStage:t})=>t===ds)){QS({...r,entryStage:r.entryStage??us,drawDefinition:t,event:n})}}({drawDefinition:e,drawEntries:o,event:d});const I=function({mainStructure:t,qualifyingDetails:e,drawDefinition:n}){for(const r of e??[]){const{finalQualifyingRoundNumber:e,finalQualifyingStructureId:i,roundTarget:o,finishingPositions:a,linkType:s}=r,c=t&&LP({targetStructureId:t.structureId,sourceStructureId:i,sourceRoundNumber:e,finishingPositions:a,targetEntryRound:o,linkType:s})?.link;if(c?.error)return c;c&&(n.links??=[],n.links.push(c))}return{error:void 0}}({mainStructure:g,qualifyingDetails:h,drawDefinition:e});return I.error?I:{drawDefinition:e,structureId:a}}function kN(t){let{participantIds:e}=t;const n=t.targetStage,r=t.drawDefinition?.entries?.filter(e=>{const r=e.entryStatus;if(t.restrictEntryStatus&&!Sf.includes(r))return!1;if(n){if((e.entryStage??us)!==n)return!1}return!0}).map(Xp)??[];if(e){const t=e.filter(t=>!r?.includes(t));if(t?.length)return Ci({result:{error:Ze},info:{invalidParticipantIds:t}})}else e=r;return t.roundsCount&&!1!==t.restrictRoundsCount&&t.roundsCount>e.length-1&&(!t.enableDoubleRobin||t.roundsCount>2*(e.length-1))?{error:sr,info:"Not enough participants for roundsCount"}:t.roundsCount&&!1!==t.restrictRoundsCount&&t.roundsCount>31?{error:sr,info:"roundsCount must be less than 32"}:{participantIds:e}}function FN(t){const e=[],{roundsCount:n=1,drawDefinition:r,matchUpsCount:i,structureId:o,idPrefix:a,isMock:s,event:c}=t;let u;const d=kN(t);if(d.error)return d;for(const d of L(1,n+1)){const n=YD({restrictMatchUpsCount:t.restrictMatchUpsCount,ignoreLastRoundNumber:!!u,newRound:!u,drawDefinition:r,matchUpsCount:i,structureId:o,roundNumber:u,idPrefix:a,isMock:s,event:c});if(n.error)return Ci({result:n,info:{iteration:d}});n.matchUps?.length&&e.push(...n.matchUps),u=(n?.roundNumber??1)+1}return{matchUps:e}}function xN(t){const e=function(t){if(t.roundsCount&&"number"!=typeof t.roundsCount)return{error:sr,info:"roundsCount must be a number"};if("object"!=typeof t.drawDefinition)return{error:at};if(!t.structureId&&t.drawDefinition.drawType&&!KS(t.drawDefinition.drawType))return{error:at};if(!Array.isArray(t.drawDefinition?.entries)&&t.participantIds&&!Array.isArray(t.participantIds))return{error:sr,info:"Missing Entries"};return{error:void 0}}(t);if(e?.error)return e;const n=kN(t);if(n.error)return n;const r=function(t){if(t.structureId)return t.structureId;const e=t.drawDefinition,n=e?.structures?.filter(t=>1===t.stageSequence)?.reduce((t,e)=>{const n=e.stage&&hs[e.stage];return Hf({structure:e})&&n>(hs[t?.stage]||1)?e:t},void 0),r=e?.structures?.find(t=>t.structureId===n?.structureId);if(!r)return{error:Vt};return Hf({structure:r})?{structure:r}:{error:at}}(t);if(r.error)return r;let i=op(t);const o=t.tournamentRecord?.isMock??t.isMock,a=t.eventType??t.event?.eventType,s=[],c=[];let u;for(const e of L(1,(t.roundsCount??1)+1)){const d=iR({...t,participantIds:n.participantIds,structure:r.structure,ignoreLastRoundNumber:!0,iterationMatchUps:s,adHocRatings:i,roundNumber:u,eventType:a,isMock:o});if(d.error)return d;const{matchUps:p,...l}=d;l.modifiedScaleValues&&(i=l.modifiedScaleValues),c.push({...l,iteration:e,matchUpsCount:p?.length}),u=(l?.roundNumber??1)+1,p?.length&&s.push(...p)}return{...Y,matchUps:s,roundResults:c}}function _N(t){const{tournamentRecord:e,drawDefinition:n,structureId:r,idPrefix:i,isMock:o,event:a}=t,s=a?.entries?.filter(({entryStage:t,entryStatus:e})=>(!t||t===us)&&e&&Sf.includes(e)),c=s?.map(Xp),u=s?Math.floor(s.length/2):0;if(t.automated)return function(t){const{restrictEntryStatus:e,generateMatchUps:n,structureId:r,matchUpIds:i,scaleName:o,scaleAccessor:a,convertToELO:s,dynamicRatings:c}=t.drawMatic??{},u=xN({...t,eventType:t.drawMatic?.eventType??t.matchUpType,generateMatchUps:n??!0,scaleAccessor:a??t.scaleAccessor,scaleName:o??t.scaleName,participantIds:t.participantIds,roundsCount:t.roundsCount,restrictEntryStatus:e,dynamicRatings:c,convertToELO:s,structureId:r,matchUpIds:i});return u.error?u:(u?.matchUps?.length&&$T({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,suppressNotifications:!0,matchUps:u.matchUps,event:t.event,structureId:r}),{...Y})}({...t,participantIds:c});{const s=FN({roundsCount:t.roundsCount,drawDefinition:n,matchUpsCount:u,idPrefix:i,isMock:o,event:a});if(s.error)return s;s.matchUps?.length&&$T({matchUps:s.matchUps,suppressNotifications:!0,tournamentRecord:e,drawDefinition:n,structureId:r,event:a})}return{...Y}}function LN({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:n,scaleSortMethod:r,stageSequence:i,entries:o,event:a,stage:s}){if(!e)return{error:rt};const c=(o=o??a?.entries??[]).filter(t=>(!s||!t.entryStage||t.entryStage===s)&&(!i||!t.entryStageSequence||t.entryStageSequence===i)&&Sf.includes(t.entryStatus)),u={...n};return{scaledEntries:c.map(t=>{const{participantId:r}=t,{scaleItem:i}=_S({tournamentRecord:e,scaleAttributes:n,participantId:r});return{...t,...i}}).filter(t=>{const e=t.scaleValue;return!!(r||!Number.isNaN(e)&&Number.parseFloat(e))&&e}).sort(r||(t||!1===u?.ascending?function(t,e){return d(e)-d(t)}:function(t,e){return d(t)-d(e)}))};function d(e){return Number.parseFloat(e.scaleValue||(t?-1:1e5))}}function BN(t){const e="prepareStage",{drawDefinition:n}=t,{structures:r}=al({stageSequence:t.stageSequence||1,roundTarget:t.roundTarget,stage:t.stage,drawDefinition:n}),i=t.preparedStructureIds??[],o=r?.find(({structureId:t})=>!i.includes(t));if(!o)return Ci({result:{error:Vt},stack:e});const a=o?.structureId,{seedsCount:s,stageEntries:c,seedLimit:u}=function(t){let{seedsCount:e}=t;t.seededParticipants&&(e=t.seededParticipants.length);e>t.drawSize&&(e=t.drawSize);const n=function({entries:t,stage:e,stageSequence:n,roundTarget:r}){return t.filter(t=>{const i=td({name:vd,element:t})?.extension?.value;return(!t.entryStage||t.entryStage===e)&&(!n||!t.entryStageSequence||t.entryStageSequence===n)&&(!r||!i||i===r)&&If.includes(t.entryStatus)})}(t);e>n.length&&(e=n.length);const{seedLimit:r}=function({requireParticipantCount:t=!0,enforcePolicyLimits:e=!0,drawSizeProgression:n,participantsCount:r,participantCount:i,appliedPolicies:o,drawDefinition:a,seedingProfile:s,structureId:c,seedsCount:u}){r=r??i;const d=ol({drawDefinition:a,structureId:c});if(d.error)return d;const p=d.structure;if(!p)return{error:Vt};const{positionAssignments:l}=ul({structure:p}),m=l?.length||0;if(u>m)return{error:At};const f=p.structures?.length,h=R(s?.groupSeedingThreshold)&&s?.groupSeedingThreshold,g=Ly({roundRobinGroupsCount:f,drawSize:m})?.seedGroups,{seedsCount:I}=ND({policyDefinitions:o,requireParticipantCount:t,drawSizeProgression:n,participantsCount:r,drawSize:m});return I&&o?.[xu]&&u>I&&e&&(u=I),p.seedLimit=u,p.seedAssignments=L(1,u+1).map(t=>{const e=g?.find(e=>e.includes(t)),n=e&&Math.min(...e);return{participantId:void 0,seedNumber:t,seedValue:h&&t>=h?n:t}}),Ql({drawDefinition:a,structureIds:[c]}),{...Y,seedLimit:u}}({enforcePolicyLimits:t.enforcePolicyLimits??!0,appliedPolicies:t.appliedPolicies,participantsCount:n.length,seedingProfile:t.seedingProfile,drawDefinition:t.drawDefinition,structureId:t.structureId,seedsCount:e});r&&r<e&&(e=r);return{seedsCount:e,stageEntries:n,seedLimit:r}}({...t,structureId:a});(t.seededParticipants||t.event||t.seedingScaleName)&&function(t){const{seededParticipants:e,seedingScaleName:n,entries:r,event:i}=t,o=r.map(Xp);e?function(t){const{provisionalPositioning:e,enteredParticipantIds:n,seededParticipants:r,tournamentRecord:i,appliedPolicies:o,drawDefinition:a,seedingProfile:s,structureId:c,structure:u,event:d}=t,p=u?Gy({provisionalPositioning:e,appliedPolicies:o,drawDefinition:a,seedingProfile:s,structure:u}):void 0;r.filter(({participantId:t})=>n.includes(t)).filter(t=>!t.seedNumber||t.seedNumber<=r.length).sort((t,e)=>t.seedNumber<e.seedNumber?-1:t.seedNumber<e.seedNumber?1:0).forEach(t=>{const{participantId:n,seedNumber:r,seedValue:o}=t;zy({provisionalPositioning:e,tournamentRecord:i,drawDefinition:a,seedingProfile:s,participantId:n,seedBlockInfo:p,structureId:c,seedNumber:r,seedValue:o,event:d})})}({...t,enteredParticipantIds:o}):(i||n)&&function(t){let e=t.seedsCount;const{provisionalPositioning:n,enteredParticipantIds:r,seedAssignmentProfile:i,assignSeedsCount:o,tournamentRecord:a,drawDefinition:s,seedByRanking:c,seedingProfile:u,structureId:d,event:p}=t,{categoryName:l,ageCategoryCode:m}=p?.category??{};const f=function(t){const{tournamentRecord:e,seedingScaleName:n,stageSequence:r,entries:i,stage:o,event:a}=t,{categoryName:s,ageCategoryCode:c}=a?.category??{},u=a?.eventType,d={scaleName:n||s||c||a.eventId,scaleType:vu,eventType:u};return LN({scaleAttributes:d,tournamentRecord:e,stageSequence:r,entries:i,stage:o}).scaledEntries}({...t})||c&&function(t){const{tournamentRecord:e,stageSequence:n,event:r,entries:i,stage:o}=t,{categoryName:a,ageCategoryCode:s}=r?.category??{},c=r?.eventType,u={scaleName:a||s,scaleType:Iu,eventType:c};return LN({scaleAttributes:u,tournamentRecord:e,stageSequence:n,entries:i,stage:o}).scaledEntries}({...t}),h=f?.length??0;h<e&&(e=h);f?.filter(({participantId:t})=>r.includes(t)).slice(0,o||e).forEach((t,e)=>{const r=e+1,{participantId:o,scaleValue:c}=t;zy({provisionalPositioning:n,tournamentRecord:a,drawDefinition:s,seedingProfile:u,participantId:o,structureId:d,seedNumber:r,seedValue:i?.[r]||c||r,event:p})})}({...t,enteredParticipantIds:o})}({...t,seedsCount:s,structure:o,structureId:a});const d=!(!1===t.automated||KS(t.drawType)||t.qualifyingOnly&&t.stage!==ds),p=(r?.length||0)>1,l=d?function(t){const e="object"==typeof t.automated&&t.automated.seedsOnly,n=JU({...t,seedsOnly:e});if(n.error)return n;const r=n?.positionAssignments,i=n?.positioningReport;return{conflicts:n.conflicts,positionAssignments:r,positioningReport:i}}({...t,multipleStructures:p,seedLimit:u,structureId:a}):{};if(l?.error)return Ci({result:l,stack:e});if(!d&&KS(t.drawType)&&o?.positionAssignments?.length){const e=t.qualifiersCount||0;if(e>0){const t=o.positionAssignments.filter(t=>!t.participantId&&!t.qualifier&&!t.bye);for(let n=0;n<e&&n<t.length;n++)t[n].qualifier=!0}}return{...l,stageEntries:c,structureId:a,seedsCount:s}}function VN(t){const e=xD({...t,modifyOriginal:!1});if(e.error)return e;const n=e.drawDefinition,{suppressDuplicateEntries:r=!0,ignoreStageSpace:i,appliedPolicies:o,qualifyingOnly:a,seedingProfile:s,participants:c,drawEntries:u,placeByes:d,drawSize:l,drawType:m,entries:f}=t,h=[];let g=[];const I=function(t){const{ignoreStageSpace:e,drawDefinition:n,drawEntries:r,drawType:i,qualifyingOnly:o,entries:a}=t;for(const s of a){if(s.entryStatus===ff)continue;const a=!(!r||!s.entryStage||s.entryStage===us||o&&s.entryStage===ds),c=QS({...s,ignoreStageSpace:e??(a||KS(i)),entryStage:s.entryStage??us,event:t.event,drawDefinition:n,drawType:i});if(r&&!a&&c.error)return c}return{error:void 0}}({ignoreStageSpace:i,qualifyingOnly:a,drawDefinition:n,drawEntries:u,drawType:m,entries:f});if(I.error)return I;const{qualifyingPlaceholder:S,qualifyingProfiles:y,qualifiersCount:v}=t,U=n?.structures?.find(t=>t.stage===us&&1===t.stageSequence)?.structureId,P=U&&n?.links?.some(t=>t.target?.structureId===U&&t.source?.structureId);if(S&&!y?.length&&v&&n&&U&&!P){const e=Ry({structureName:Ny(ds),stage:ds,qualifyingOnly:a,tieFormat:t.tieFormat}),{link:r}=LP({sourceStructureId:e.structureId,targetStructureId:U,qualifyingPositions:v,sourceRoundNumber:0,linkType:As});n.structures??=[],n.structures.push(e),n.links??=[],n.links.push(r)}const T=qf(m)?0:p(t.seedsCount??0),w=BN({...t,qualifyingOnly:!l||a,appliedPolicies:o,drawDefinition:n,seedingProfile:s,participants:c,stage:us,seedsCount:T,placeByes:d,drawSize:l,entries:f});if(w.error&&!w.conflicts)return w;w.positioningReport?.length&&h.push({[us]:w.positioningReport});const D=w.structureId;return w.conflicts&&(g=w.conflicts),KS(m)&&t.roundsCount&&_N({...t,drawDefinition:n,structureId:D}),{drawDefinition:n,positioningReports:h,conflicts:g,structureId:D}}function GN(t){let e=t.structureIds;const{tournamentRecord:n,drawDefinition:r,matchUpFormat:i,structureId:o,matchUpId:a,event:s}=t,c=fu(t,[{[yc]:!0,[Uc]:!0}]);if(c.error)return c;if(!Io({matchUpFormat:i}))return{error:oe};if(a){const t=nT({drawDefinition:r,matchUpId:a,event:s});if(t.error)return t;const e=t.matchUp;if(e?.matchUpType===is)return{info:"Cannot set matchUpFormat when { matchUpType: TEAM }",error:ye};e&&(e.matchUpFormat=i,Yl({tournamentId:n?.tournamentId,eventId:s?.eventId,context:"setMatchUpFormat",drawDefinition:r,matchUp:e}))}else if(Array.isArray(e)){if(s?.eventType===is)return{error:$t};for(const t of e){const e=ol({drawDefinition:r,structureId:t});if(e.error)return e;e.structure&&(e.structure.matchUpFormat=i)}}else if(o){if(s?.eventType===is)return{error:$t};const t=ol({drawDefinition:r,structureId:o});if(t.error)return t;t.structure&&(t.structure.matchUpFormat=i)}else r&&(r.matchUpFormat=i);return e=e??(o?[o]:void 0),Ql({drawDefinition:r,structureIds:e}),{...Y}}function jN({existingQualifyingStructures:t,tournamentRecord:e,drawDefinition:n,matchUpFormat:r,matchUpType:i,tieFormat:o,event:a}){if(r||o){if(!(r&&a?.matchUpFormat===r||a?.tieFormat&&o&&JSON.stringify(a.tieFormat)===JSON.stringify(o))){if(o){const e=function({tieFormat:t}){const e=na({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(const e of t.collectionDefinitions)e.collectionId??=pa();return{tieFormat:t}}({tieFormat:o});if(e.error)return e;const r=t?.every(t=>t.tieFormat);t?.length&&!r||(n.tieFormat=e.tieFormat??o)}else if(r){const t=GN({tournamentRecord:e,drawDefinition:n,matchUpFormat:r,event:a});if(t.error)return{info:"matchUpFormat or tieFormat error",error:t.error}}i&&(n.matchUpType=i)}}return{error:void 0}}function qN(t){const e=fu(t,[{[Ec]:!0,_anyOf:{[hc]:!1,[Ic]:!1,[yc]:!1,[zc]:!1}}]);if(e.error)return e;let n;const r=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(r)return WN(t,r);if(!t.tournamentRecords)return{error:rt};{const e=Object.keys(t.tournamentRecords);if(!e.length)return{error:rt};for(const r of e){const e=WN(t,t.tournamentRecords[r]);if(e.error)return e;n=!0}}return n?{...Y}:{error:Re}}function WN(t,e){const n=xd(t).appliedPolicies??{};if(n[t.policyType]){if(delete n[t.policyType],Object.keys(n).length){$u({element:e,extension:{name:ed,value:n}})}else qu({element:e,name:ed});return{...Y}}return{error:Re}}var $N={__proto__:null,attachPolicies:RT,findPolicy:Qm,getAppliedPolicies:xd,getPolicyDefinitions:_d,mutate:{__proto__:null,attachPolicies:RT,removePolicy:qN},query:{__proto__:null,findPolicy:Qm,getAppliedPolicies:xd,getPolicyDefinitions:_d},removePolicy:qN};const HN={[xu]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[oc]:{positioning:Ts},[ic]:{positioning:Ts}},positioning:Ps},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 zN({appliedPolicies:t,policyDefinitions:e,drawDefinition:n,stack:r}){if(e&&"object"!=typeof e)return Ci({info:"policyDefinitions must be an object",result:{error:sr},stack:r});const i={[ku]:t?.[ku]};return e?function({policyDefinitions:t,appliedPolicies:e,policiesToAttach:n,drawDefinition:r}){for(const r of Object.keys(t))JSON.stringify(e?.[r])!==JSON.stringify(t[r])&&(n[r]=t[r]);Object.keys(n).length&&(RT({policyDefinitions:n,drawDefinition:r}),e&&Object.assign(e,n))}({policyDefinitions:e,appliedPolicies:t,policiesToAttach:i,drawDefinition:n}):i.avoidance&&RT({drawDefinition:n,policyDefinitions:i}),t?.[xu]||e?.[xu]||(RT({policyDefinitions:HN,drawDefinition:n}),t&&Object.assign(t,HN)),{error:void 0}}function YN(t){const{tournamentRecord:e,policyDefinitions:n,appliedPolicies:r,matchUpFormat:i,matchUpType:o,tieFormat:a,drawType:s,stack:c,event:u}=t,d=t.drawId?u?.drawDefinitions?.find(e=>e.drawId===t.drawId):void 0,p=d?.structures?.find(t=>t.stage===us&&1===t.stageSequence)?.structureId,l=d?d.structures?.filter(t=>t.stage===ds):[],m=1===l?.length&&!l[0].matchUps?.length&&l[0].structureId;d&&s!==d.drawType&&!m&&(d.drawType=s);const f=d??function(t){const{drawId:e=pa(),processCodes:n,matchUpType:r,drawType:i}=t??{},o={matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]};return Object.assign(o,{processCodes:n,matchUpType:r,drawType:i,drawId:e})}({processCodes:t.processCodes,drawId:t.drawId,drawType:s}),h=jN({existingQualifyingStructures:l,tournamentRecord:e,drawDefinition:f,matchUpFormat:i,matchUpType:o,tieFormat:a,event:u});if(h.error)return Ci({result:h,stack:c});const g=zN({appliedPolicies:r,policyDefinitions:n,drawDefinition:f,stack:c});return g.error?g:{drawDefinition:f,structureId:p,existingDrawDefinition:d,existingQualifyingPlaceholderStructureId:m}}function KN(t){const{qualifyingPlaceholder:e,existingDrawDefinition:n,positioningReports:r,qualifyingProfiles:i,appliedPolicies:o,qualifyingOnly:a,drawDefinition:s,seedingProfile:c,participants:u,structureId:d,tieFormat:p,entries:l,stack:m}=t,f=e&&!i?.length&&!n,h=[];if(i){const e=function({qualifyingProfiles:t,qualifyingConflicts:e,positioningReports:n,seedingProfile:r,appliedPolicies:i,drawDefinition:o,qualifyingOnly:a,participants:s,entries:c,params:u,stack:d}){const p=(t,e)=>t.stageSequence-e.stageSequence,l=(t,e)=>t.roundTarget-e.roundTarget,m=[];let f=1;t.sort(l);for(const l of t){if(!Array.isArray(l.structureProfiles))return Ci({info:nv("structureProfiles"),result:{error:Ae},stack:d});f=l.roundTarget||f;const t=l.structureProfiles?.sort(p)??[];let h=1;for(const d of t){const t=QN({structureProfile:d,preparedStructureIds:m,seedingProfile:r,appliedPolicies:i,drawDefinition:o,qualifyingOnly:a,participants:s,roundTarget:f,sequence:h,entries:c,params:u});if(t.error)return t;t.structureId&&m.push(t.structureId),h+=1,t.conflicts?.length&&e.push(...t.conflicts),t.positioningReport?.length&&n.push({[ds]:t.positioningReport})}f+=1}return}({qualifyingProfiles:i,qualifyingConflicts:h,positioningReports:r,seedingProfile:c,appliedPolicies:o,drawDefinition:s,qualifyingOnly:a,participants:u,entries:l,params:t,stack:m});if(e?.error)return e}else if(d&&f){const e=s.structures?.find(t=>t.stage===ds&&!t.matchUps?.length);if(!e){const e=Ry({structureName:Ny(ds),stage:ds,qualifyingOnly:a,tieFormat:p}),n=t.qualifiersCount,{link:r}=LP({sourceStructureId:e.structureId,targetStructureId:d,sourceRoundNumber:0,qualifyingPositions:n,linkType:As});s.structures??=[],s.structures.push(e),s.links??=[],s.links.push(r)}}return{qualifyingConflicts:h,error:void 0}}function QN({structureProfile:t,preparedStructureIds:e,seedingProfile:n,appliedPolicies:r,drawDefinition:i,qualifyingOnly:o,participants:a,roundTarget:s,sequence:c,entries:u,params:d}){const{qualifyingRoundNumber:p,qualifyingPositions:l,seededParticipants:m,seedingScaleName:f,seedsCount:h=0,seedByRanking:g,placeByes:I,drawSize:S}=t;return BN({...d,seedingProfile:t.seedingProfile??n,stageSequence:c,qualifyingRoundNumber:p,preparedStructureIds:e,qualifyingPositions:l,seededParticipants:m,stage:ds,seedingScaleName:f,appliedPolicies:r,drawDefinition:i,qualifyingOnly:o,seedByRanking:g,participants:a,roundTarget:s,seedsCount:h,placeByes:I,drawSize:S,entries:u})}function JN(t){const{drawDefinition:e,appliedPolicies:n}=t,r=n?.[Au],i=bf({drawDefinition:e});return e.structures?.forEach(t=>{const n=Nf({structureId:t.structureId,matchUpsMap:i}),o=Yf({roundNamingPolicy:r,drawDefinition:e,structure:t,matchUps:n}),{roundNamingProfile:a,roundProfile:s}=o;(t.structures||[t]).forEach(t=>{(t.matchUps??[]).forEach(t=>{const e=t?.roundNumber?.toString();if(e){const n=a?.[e]?.roundName,r=a?.[e]?.abbreviatedRoundName,i=s?.[e]?.feedRound;Object.assign(t,{abbreviatedRoundName:r,feedRound:i,roundName:n})}})})}),{drawDefinition:e}}function XN(t){const{tournamentRecords:e}=t??{};if("object"!=typeof e||!Object.keys(e).length)return{error:nt};const n=[],r={},i={},o={},a=[],s={},c=[];for(const u of Object.values(e)){const{participantIdsWithConflicts:e,mappedMatchUps:d,participantMap:p,participants:l,matchUps:m,derivedEventInfo:f,derivedDrawInfo:h}=xS({...t,tournamentRecord:u});Object.assign(s,d),Object.assign(r,p),Object.assign(i,f),Object.assign(o,h),n.push(...l??[]),a.push(...m??[]),e?.forEach(t=>{c.includes(t)||c.push(t)})}return{participantIdsWithConflicts:c,derivedEventInfo:i,derivedDrawInfo:o,participantMap:r,mappedMatchUps:s,participants:n,...Y,matchUps:a}}function ZN({tournamentRecord:t,participantId:e}){const n=dl({tournamentRecord:t,participantId:e},[Ic,Pc]);if(n.error)return n;const r=[e].concat((t.participants??[]).filter(t=>t?.participantType&&[ym,Sm].includes(t.participantType)&&t.individualParticipantIds?.includes(e)).map(t=>t.participantId));return{eventDetails:(t.events??[]).filter(t=>j((t?.entries??[]).map(t=>t.participantId),r)).map(t=>({eventName:t.eventName,eventId:t.eventId}))}}function tM({tournamentRecord:t,participantId:e}){const n=dl({tournamentRecord:t,participantId:e},[Ic,Pc]);if(n.error)return n;const{participants:r}=xS({participantFilters:{participantTypes:[ym,Sm,Im]},tournamentRecord:t});return(r??[]).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 eM({participantFilters:t={},tournamentRecord:e}){if(!e)return{error:rt};if("object"!=typeof t)return{error:ir,context:{participantFilters:t}};const n=Qg({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),o=iI({tournamentRecord:e,matchUps:n}).sourceMatchUpIds??[],a={};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??[]);o[t.matchUpId]&&!n&&(n=(o[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;a[n]||(a[n]={potentialMatchUps:[],participant:e,matchUps:[]}),a[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;a[n]||(a[n]={potentialMatchUps:[],participant:e,matchUps:[]}),a[n].potentialMatchUps.push(t)}}return{participantSchedules:Object.values(a).filter(({participant:e})=>!(t.participantIds&&!t.participantIds.includes(e.participantId)||t.participantTypes&&!t.participantTypes.includes(e.participantType))),...Y}}function nM({tournamentRecord:t,participantId:e}){const n=dl({tournamentRecord:t,participantId:e},[Ic,Pc]);if(n.error)return n;const{participant:r}=Rm({tournamentRecord:t,participantId:e});if(!r)return{error:un};const{timeItem:i}=Nm({itemType:cm,element:r});return i&&fm.includes(i.itemValue)?i.itemValue:void 0}function rM({tournamentRecord:t,participantId:e}){const n=dl({tournamentRecord:t,participantId:e},[Ic,Pc]);if(n.error)return n;const{participant:r}=Rm({tournamentRecord:t,participantId:e});if(!r)return{error:un};const{timeItem:i}=Nm({itemType:om,element:r});return i&&i.itemValue===sm&&sm}var iM={__proto__:null,filterParticipants:kS,getCompetitionParticipants:XN,getPairedParticipant:bg,getParticipantEventDetails:ZN,getParticipantMembership:tM,getParticipantPaymentStatus:nM,getParticipantScaleItem:_S,getParticipantSchedules:eM,getParticipantSignInStatus:rM,getParticipantTimeItem:Cm,getParticipants:xS,getScaleValues:Pu,participantScaleItem:Vd,validateLineUp:rv};function oM({tournamentRecord:t,categoryName:e,categoryType:n}){if(!t)return{error:rt};const{appliedPolicies:r}=xd({tournamentRecord:t}),i=r?.[Fu];return(i?.matchUpFormats??[]).filter(({categoryNames:t,categoryTypes:r})=>!e&&!r||e&&t?.includes(e)||n&&r?.includes(n))}function aM({tournamentRecord:t,categoryName:e,categoryType:n}){if(!t)return{error:rt};const{appliedPolicies:r}=xd({tournamentRecord:t}),i=r?.[Bu];return(i?.allowedDrawTypes??[]).filter(({categoryNames:t,categoryTypes:r})=>!e&&!r||e&&t?.includes(e)||n&&r?.includes(n))}const sM="splitEven",cM="teamOnly",uM=["ageCategoryCodes","genders","categoryNames","categoryTypes","ratingTypes","ballTypes","wheelchairClasses","subTypes"],dM=["eventTypes","drawTypes","drawSizes","maxDrawSize","stages","stageSequences","levels","maxLevel","flights","maxFlightNumber","participationOrder","dateRanges"],pM={RANKING_POINTS:"RANKING_POINTS",QUALITY_WIN:"QUALITY_WIN",FULL_TO_EACH:"fullToEach",SPLIT_EVEN:sM,TEAM_ONLY:cM,CATEGORY_SCOPE_FIELDS:uM,PROFILE_SCOPE_FIELDS:dM};function lM(t){const{participation:e={},awardProfiles:n,wheelchairClass:r,startDate:i,eventType:o,drawSize:a,drawType:s,category:c,endDate:u,gender:d,level:p}=t,{participationOrder:l,flightNumber:m,rankingStage:f}=e,h=n.filter(t=>(t=>!i&&!u||!t.dateRanges||t.dateRanges.some(t=>{const e=!i||!t.startDate||new Date(i)>new Date(t.startDate),n=!u||!t.endDate||new Date(u)<=new Date(t.endDate);return e&&n}))(t)&&(!t.maxFlightNumber||m<=t.maxFlightNumber)&&(!t.drawTypes?.length||t.drawTypes?.includes(s))&&(!t.drawSizes?.length||t.drawSizes.includes(a))&&(!t.stages?.length||t.stages.includes(f))&&(!t.levels?.length||t.levels.includes(p))&&(!t.maxDrawSize||a<=t.maxDrawSize)&&(!t.drawSize||t.drawSize===a)&&(!t.maxLevel||p<=t.maxLevel)&&(!m||!t.flights?.flightNumbers?.length||t.flights.flightNumbers.includes(m))&&(!t.participationOrder||t.participationOrder===l)&&(t=>{if(!t)return!0;const e=c??{};return!(t.ageCategoryCodes?.length&&!t.ageCategoryCodes.includes(e.ageCategoryCode)||t.genders?.length&&!t.genders.includes(d)||t.categoryNames?.length&&!t.categoryNames.includes(e.categoryName)||t.categoryTypes?.length&&!t.categoryTypes.includes(e.type)||t.ratingTypes?.length&&!t.ratingTypes.includes(e.ratingType)||t.ballTypes?.length&&!t.ballTypes.includes(e.ballType)||t.wheelchairClasses?.length&&!t.wheelchairClasses.includes(r)||t.subTypes?.length&&!t.subTypes.includes(e.subType))})(t.category)&&(!t.eventTypes?.length||t.eventTypes?.includes(o)));if(0===h.length)return{awardProfile:void 0};if(1===h.length)return{awardProfile:h[0]};const g=h.filter(t=>void 0!==t.priority);if(g.length){const t=Math.max(...g.map(t=>t.priority));return{awardProfile:g.find(e=>e.priority===t)}}const I=h.map((t,e)=>({profile:t,score:mM(t),index:e}));return I.sort((t,e)=>e.score-t.score||t.index-e.index),{awardProfile:I[0].profile}}function mM(t){let e=0;for(const n of dM){const r=t[n];if(null!=r){if(Array.isArray(r)&&0===r.length)continue;e+=1}}if(t.category)for(const n of uM){const r=t.category[n];Array.isArray(r)&&r.length>0&&(e+=1)}return e}const fM=[{rankingStage:us,participationOrder:1,flightNumber:1},{rankingStage:us,participationOrder:2,flightNumber:1},{rankingStage:ds,participationOrder:1,flightNumber:1},{rankingStage:ds,participationOrder:2,flightNumber:1}];function hM({policyDefinitions:t,tournamentRecord:e,eventId:n,drawId:r}){if(!e)return{error:rt};const{policyDefinitions:i}=_d({policyTypes:[Mu],tournamentRecord:e}),o=t?.[Mu]??i?.[Mu];if(!o)return{error:Ue};const a=o.awardProfiles;if(!a?.length)return{levels:[],...Y};const s=function(t){const e=new Set;for(const n of t)if(n.levels?.length)for(const t of n.levels)e.add(t);const n=t.filter(t=>void 0!==t.maxLevel).map(t=>t.maxLevel);if(n.length){const t=Math.max(...n);for(let n=1;n<=t;n++)e.add(n)}return[...e].sort((t,e)=>t-e)}(a);if(!n&&!r)return{levels:s,...Y};const c=function({tournamentRecord:t,eventId:e,drawId:n}){const r=wg({tournamentRecord:t,eventId:e,drawId:n}),i=r.event,o=r.drawDefinition;return{eventType:i?.eventType,category:i?.category,gender:i?.gender,drawType:o?.drawType}}({tournamentRecord:e,eventId:n,drawId:r}),u=function(t,e,n){const{eventType:r,drawType:i,category:o,gender:a}=n;return t.filter(t=>fM.some(n=>lM({awardProfiles:e,participation:n,eventType:r,drawType:i,category:o,gender:a,level:t}).awardProfile))}(s,a,c);return{levels:u,...Y}}function gM(t){const{tournamentRecord:e}=t;if(!e)return{error:rt};const n=(new Date).toISOString();let r=0;const i=t=>{const{extension:e}=td({element:t,name:gd});if(!e?.value?.locks?.length)return;const i=e.value,o=i.locks.length;i.locks=i.locks.filter(t=>null===t.expiresAt||t.expiresAt>n);const a=o-i.locks.length;a>0&&(r+=a,$u({element:t,extension:{name:gd,value:i},creationTime:!1}))};i(e);const o=e.events??[];for(const t of o){i(t);const e=t.drawDefinitions??[];for(const t of e)i(t)}const a=e.venues??[];for(const t of a)i(t);return{...Y,removedCount:r}}function IM({tournamentRecord:t}){if(!t)return{error:rt};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 SM({tournamentRecords:t}){if("object"!=typeof t||!Object.keys(t).length)return{error:nt};const e=[];for(const n of Object.values(t)){const{penalties:t}=IM({tournamentRecord:n});e.push(...t??[])}return{penalties:e}}function yM({tournamentRecords:t}){if(!f(t))return{error:nt};const e=Object.keys(t??{}).reduce((e,n)=>{const r=t[n],{tournamentInfo:{startDate:i,endDate:o}}=Pw({tournamentRecord:r}),a=i&&Lo(i),s=a&&new Date(a);(!e.startDate||s&&s<e.startDate)&&(e.startDate=s);const c=o&&Lo(o),u=c&&new Date(c);return(!e.endDate||u&&u>e.endDate)&&(e.endDate=u),e},{startDate:void 0,endDate:void 0}),n=e.startDate&&Lo(e.startDate.toISOString()),r=e.endDate&&Lo(e.endDate.toISOString());return n&&r?{startDate:n,endDate:r}:{error:Ce}}function vM(t){if(!t?.tournamentRecord)return{error:rt};const{tournamentRecord:e}=t;return{registrationProfile:e.registrationProfile?ca(e.registrationProfile):void 0}}function UM(t){const e=fu(t,[{[Ic]:!0}]);if(e.error)return e;const n=t.finishingPositionRangeBounsPoints??{},r={},i=t=>{const e=t?.individualParticipants?.map(t=>1===t.teams?.length&&t.teams[0]);return 1===t?.teams?.length&&t?.teams?.[0]||e?.[0].participantId===e?.[1].participantId&&e?.[0]},{matchUps:o,participants:a}=xS({participantFilters:{participantTypes:[gm]},withRankingProfile:!0,withStatistics:!0,...t});for(const t of a??[]){if(t.participantType===hm)continue;"draw-0-3"===t.draws?.[0]?.drawId&&console.log(t.participantType,t.draws[0].finishingPositionRange);const e=i(t);if(e)for(const i of t?.draws??[]){const t=i?.finishingPositionRange?.join("-");if(t&&n?.[t]){const o=e?.participantId,a=i?.drawId;r[`${o}|${a}|${t}`]=n[t]}}}const{individualResults:s,teamResults:c}=function({getTeamParticipant:t,initializeResults:e,increment:n,matchUps:r}){const i={},o={};for(const a of r??[]){const{sides:r,matchUpFormat:s}=a,c=s&&co(s);if(2===r?.length&&c.setFormat?.timed&&(!c.finalSetFormat||c.finalSetFormat?.timed))for(const s of r)PM({side:s,matchUp:a,getTeamParticipant:t,initializeResults:e,increment:n,individualResults:i,teamResults:o})}return{individualResults:i,teamResults:o}}({getTeamParticipant:i,initializeResults:t=>({teamName:t,standingPoints:0,pointsPlayed:0,pointsPct:0,points:0,bonus:0,diff:0,loss:0,win:0}),increment:(t,e,n)=>{void 0===t[e]&&(t[e]=0),t[e]+=n},matchUps:o});return function({teamBonusPointHashes:t,teamResults:e}){for(const n of Object.keys(t)){const[r]=n.split("|");e[r]&&(e[r].bonus+=t[n],e[r].pointsPct=parseFloat((e[r].points/e[r].pointsPlayed).toFixed(2)),e[r].standingPoints=e[r].win+e[r].bonus)}}({teamBonusPointHashes:r,teamResults:c}),function(t){for(const e of Object.keys(t))t[e].pointsPct=parseFloat((t[e].points/t[e].pointsPlayed).toFixed(2))}(s),{...Y,individualResults:s,teamResults:c}}function PM({side:t,matchUp:e,getTeamParticipant:n,initializeResults:r,increment:i,individualResults:o,teamResults:a}){const s=n(t.participant),c=s?.participantId,u=t.participant?.participantId,d=s?.participantName,p=t.sideNumber,l=t.participant?.individualParticipantIds||((u&&[u])??[]);if(l.forEach(t=>{t&&!o[t]&&(o[t]=r(d))}),c&&p){a[c]||(a[c]=r(d));const t=[...l.map(t=>o[t]),a[c]];e.winningSide&&(p===e.winningSide?t.forEach(t=>i(t,"win",1)):t.forEach(t=>i(t,"loss",1)));const n=e.score?.sets??[];for(const e of n){const n=e?.[`side${3-p}Score`]||0,r=e?.[`side${p}Score`]||0,o=r-n;t.forEach(t=>i(t,"pointsPlayed",r+n)),t.forEach(t=>i(t,"points",r)),t.forEach(t=>i(t,"diff",o))}}}function TM({tournamentRecord:t,participantFilters:e}){if(!t)return{error:rt};let n=t.participants??[];e&&(n=kS({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 wM(t,e){return t&&e&&Array.isArray(e)&&e[t-1]||"object"==typeof e&&e[t]}function DM({qualityWinProfiles:t,wonMatchUpIds:e,mappedMatchUps:n,participantSideMap:r,tournamentParticipants:i,tournamentStartDate:o,level:a}){let s=0;const c=[],u={};for(const t of i)u[t.participantId]=t;for(const i of t){const{rankingScaleName:t,rankingSnapshot:d="latestAvailable",includeWalkovers:p=!1,rankingRanges:l=[],maxBonusPerTournament:m}=i;let f=0;for(const i of e){const e=RM({matchUpId:i,mappedMatchUps:n,participantSideMap:r,participantById:u,includeWalkovers:p,rankingScaleName:t,rankingSnapshot:d,tournamentStartDate:o,rankingRanges:l,level:a});e&&(f+=e.points,c.push(e))}void 0!==m&&f>m&&(f=m),s+=f}return{qualityWinPoints:s,qualityWins:c}}function RM({matchUpId:t,mappedMatchUps:e,participantSideMap:n,participantById:r,includeWalkovers:i,rankingScaleName:o,rankingSnapshot:a,tournamentStartDate:s,rankingRanges:c,level:u}){const d=e[t];if(!d)return;const{matchUpStatus:p,sides:l=[],winningSide:m}=d;if(!i&&(p===Ep||p===Pp))return;const f=n[t];if(!f||m!==f)return;const h=l.find(t=>t.sideNumber!==f),g=h?.participantId;if(!g)return;const I=r[g];if(!I)return;const S=function({participant:t,rankingScaleName:e,rankingSnapshot:n,tournamentStartDate:r}){const i=(t.timeItems??[]).filter(t=>{if(!t?.itemType)return!1;const n=t.itemType.split(".");return n[0]===yu&&n[1]===Iu&&n[3]===e});if(!i.length)return;let o=i;if("tournamentStart"===n&&r){const t=new Date(r).getTime();o=i.filter(e=>(e.itemDate?new Date(e.itemDate).getTime():0)<=t)}if(!o.length)return;o.sort((t,e)=>(t.createdAt?new Date(t.createdAt).getTime():0)-(e.createdAt?new Date(e.createdAt).getTime():0));const a=o.at(-1),s=a?.itemValue;return"number"==typeof s?s:void 0}({participant:I,rankingScaleName:o,rankingSnapshot:a,tournamentStartDate:s});if(!S)return;const y=c.find(t=>S>=t.rankRange[0]&&S<=t.rankRange[1]);if(!y)return;let v;if("number"==typeof y.value)v=y.value;else if("object"==typeof y.value){const t=wM(u,y.value.level??y.value);"number"==typeof t&&(v=t)}return v?{opponentParticipantId:g,opponentRank:S,points:v,matchUpId:t}:void 0}function bM({participantWon:t,flightNumber:e,valueObj:n,drawSize:r,flights:i,level:o}){const a=(t,e)=>{const n=t?.value||t?.v||(R(t)?t:0),r=wM(o,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||R(r)&&r||n}};let s,c,u,d,p=0;const l=(t?"won":!1===t&&"lost")||void 0;if(Array.isArray(n)){let t=n.find(t=>t.drawSize===r||t.drawSizes?.includes(r)),i=n.find(t=>t.drawSize&&t.threshold&&r>t.drawSize),o=n.find(t=>!t.drawSize&&!t.drawSizes?.length);void 0!==l&&(t=t?.[l],i=i?.[l],o=o?.[l]),c=a(t,e).value,u=a(i,e).value,d=a(o,e).value,p=c||u||d,s=c&&t.requireWin||u&&i.requireWin||o?.requireWin}else if("object"==typeof n){let t=n?.drawSizes?.[r],i=n;void 0!==l&&(t=t?.[l],i=i?.[l]),c=a(t,e).value,d=a(i,e).value,p=c||d,s=c?t.requireWin:i?.requireWin}else R(n)&&void 0===l&&(p=n);return e&&i?.pct?.[e]&&(p=Math.round(p*i.pct[e])),{awardPoints:p,requireWin:s}}const NM=new Map;function MM(t,e){return`${t}::${e}`}const AM={register:function({policyType:t,name:e,version:n,definition:r}){const i=MM(t,e),o=(NM.get(i)??[]).filter(t=>t.version!==n);o.push({policyType:t,name:e,version:n,definition:r}),NM.set(i,o)},lookup:function({policyType:t,name:e,version:n}){const r=NM.get(MM(t,e));if(r?.length)return n?r.find(t=>t.version===n)?.definition:r.at(-1)?.definition},list:function({policyType:t}={}){const e=[];for(const n of NM.values())for(const r of n)t&&r.policyType!==t||e.push(r);return e},clear:function({policyType:t,name:e}={}){if(!t&&!e)return void NM.clear();if(t&&e)return void NM.delete(MM(t,e));const n=[];for(const[r,i]of NM.entries()){i.some(n=>(!t||n.policyType===t)&&(!e||n.name===e))&&n.push(r)}for(const t of n)NM.delete(t)}};function EM(t,e){if("object"==typeof t&&t.line){if(t.limit&&e>t.limit)return;return t.line[e-1]}if("number"==typeof t)return t}function CM({tieMatchUp:t,lineValue:e,participantIndividualIdsMap:n,participantPersonMap:r,personPoints:i,pointsAuthority:o,eventType:a,drawId:s}){const{collectionPosition:c}=t;for(const u of t.sides??[]){if(u.sideNumber!==t.winningSide)continue;const d=u.participantId;if(!d)continue;const p=n[d]||[d];for(const t of p){const n=r[t];n&&(i[n]||(i[n]=[]),i[n].push({linePoints:e,collectionPosition:c,pointsAuthority:o,eventType:a,drawId:s}))}}}function OM({participantType:t,participantId:e,awardProfile:n,participant:r,participation:i,mappedMatchUps:o,levelValue:a,participantIndividualIdsMap:s,participantPersonMap:c,personPoints:u,pointsAuthority:d,eventType:p,drawId:l}){if(t!==hm||!n||!a)return;const m=(r.matchUps??[]).filter(({structureId:t})=>t===i.structureId);for(const{matchUpId:t}of m){const n=o[t],r=n?.sides?.find(t=>t.participantId===e)?.sideNumber;if(r&&n.winningSide===r)for(const t of n.tieMatchUps??[]){if(!t.winningSide)continue;const e=EM(a,t.collectionPosition);e&&CM({tieMatchUp:t,lineValue:e,participantIndividualIdsMap:s,participantPersonMap:c,personPoints:u,pointsAuthority:d,eventType:p,drawId:l})}}}function kM({participation:t,awardProfiles:e,wheelchairClass:n,eventType:r,startDate:i,category:o,drawInfo:a,drawType:s,endDate:c,gender:u,level:d,accum:p}){const{finishingPositionRange:l,rankingStage:m,winCount:f}=t;if(p.totalWinsCount+=f||0,Array.isArray(l)&&l.length){const t=Math.min(...l);(void 0===p.bestFinishingPosition||t<p.bestFinishingPosition)&&(p.bestFinishingPosition=t)}const h=a?.drawSize,{awardProfile:g}=lM({wheelchairClass:n,awardProfiles:e,participation:t,eventType:r,startDate:i,category:o,drawSize:h,drawType:s,endDate:c,gender:u,level:d});if(g){if(!h)return{awardProfile:g,skip:!0};g.profileName&&(p.profileName=g.profileName),void 0===p.primaryAwardProfile&&(p.primaryAwardProfile=g,p.rankingStage=m),p.maxCountable=function(t,e,n){if(void 0!==n||void 0===t.maxCountableMatches)return n;const r=t.maxCountableMatches;if("number"==typeof r)return r;if("object"==typeof r){const t=wM(e,r.level??r);if("number"==typeof t)return t}return n}(g,d,p.maxCountable);const{awardPoints:e,winRequired:n,accessor:r}=function({awardProfile:t,participation:e,level:n,drawSize:r}){const{finishingPositionRange:i,participationOrder:o,participantWon:a,flightNumber:s,rankingStage:c}=e;let u=Array.isArray(i)&&Math.max(...i);c===ds&&u&&e.finishingRound&&(u=a?1:Math.pow(2,e.finishingRound));const{finishingPositionPoints:d={},finishingPositionRanges:p,finishingRound:l,flights:m}=t,f=d.participationOrders;let h,g=0;if((!f||f.includes(o))&&p&&u){const t=p[u];t&&({awardPoints:g,requireWin:h}=bM({flightNumber:s,valueObj:t,drawSize:r,flights:m,level:n}))}if(!g&&l&&1===o&&u){const t=l[u];t&&({awardPoints:g,requireWin:h}=bM({participantWon:a,flightNumber:s,valueObj:t,drawSize:r,flights:m,level:n}))}return{awardPoints:g,winRequired:h,accessor:u}}({awardProfile:g,participation:t,drawSize:h,level:d}),i=r&&m!==ds&&l?.includes(h);if(void 0!==g.requireWinForPoints&&(p.requireWin=g.requireWinForPoints),void 0!==g.requireWinFirstRound&&(p.requireWinFirstRound=g.requireWinFirstRound),i&&void 0!==p.requireWinFirstRound&&(p.requireWin=p.requireWinFirstRound),void 0!==n&&(p.requireWin=n),e>p.positionPoints&&(!p.requireWin||f)&&(p.positionPoints=e,p.rangeAccessor=r,p.primaryAwardProfile=g,p.rankingStage=m),!e){const e=function({awardProfile:t,participation:e,level:n,maxCountable:r,countedWins:i}){const{participationOrder:o,winCount:a}=e,{pointsPerWin:s}=t,c=void 0!==r&&r>0?Math.min(a||0,Math.max(0,r-i)):a,u=M(e.finishingPositionRange??[]).join("-");let d,p=0,l=0;s&&c&&(p+=c*s,l+=c,d=u);const m=Array.isArray(t.perWinPoints)?t.perWinPoints?.find(t=>t.participationOrders?.includes(o)):t.perWinPoints;if(a&&m){const t=wM(n,m?.level);"number"==typeof t?(p+=(c||0)*t,l+=c||0):!t&&m.value&&(p+=(c||0)*m.value,l+=c||0)}return{perWin:p,counted:l,rangeAccessor:d}}({awardProfile:g,participation:t,maxCountable:p.maxCountable,countedWins:p.countedWins,level:d});p.perWinPoints+=e.perWin,p.countedWins+=e.counted,e.rangeAccessor&&(p.rangeAccessor=e.rangeAccessor)}}return{awardProfile:g,skip:!1}}function FM({participant:t,draw:e,eventInfo:n,drawInfo:r,mappedMatchUps:i,awardProfiles:o,requireWinForPoints:a,requireWinFirstRound:s,doublesAttribution:c,qualityWinProfiles:u,personPoints:d,pairPoints:p,teamPoints:l,participantPersonMap:m,participantIndividualIdsMap:f,pointsAuthority:h,level:g,devContext:I,tournamentRecord:S}){const{participantType:y,participantId:v,person:U}=t,{drawId:P,structureParticipation:T}=e,w=r?.drawType,{category:D,eventType:R,gender:b,wheelchairClass:N}=n??{},M=e.startDate||n.startDate||S.startDate,A=e.endDate||n.endDate||S.endDate;if(R===os&&y!==hm)return;if(R===ns&&y!==Sm)return;let E;if(o&&T){const e=function({initialRequireWinFirstRound:t,requireWinForPoints:e}){return{requireWinFirstRound:t,requireWin:e,bestFinishingPosition:void 0,primaryAwardProfile:void 0,maxCountable:void 0,rangeAccessor:void 0,profileName:void 0,rankingStage:void 0,totalWinsCount:0,positionPoints:0,perWinPoints:0,countedWins:0}}({initialRequireWinFirstRound:s,requireWinForPoints:a});!function({structureParticipation:t,awardProfiles:e,wheelchairClass:n,participantType:r,participantId:i,participant:o,eventType:a,startDate:s,category:c,drawInfo:u,drawType:d,endDate:p,gender:l,level:m,accum:f,mappedMatchUps:h,participantIndividualIdsMap:g,participantPersonMap:I,personPoints:S,pointsAuthority:y,drawId:v}){for(const U of t){const{awardProfile:t,skip:P}=kM({participation:U,awardProfiles:e,wheelchairClass:n,eventType:a,startDate:s,category:c,drawInfo:u,drawType:d,endDate:p,gender:l,level:m,accum:f});if(!P&&(r===hm&&t)){const e=Array.isArray(t.perWinPoints)?t.perWinPoints?.find(t=>t.participationOrders?.includes(U.participationOrder)):t.perWinPoints,n=e&&wM(m,e.level);OM({participantType:r,participantId:i,awardProfile:t,participant:o,participation:U,mappedMatchUps:h,levelValue:n,participantIndividualIdsMap:g,participantPersonMap:I,personPoints:S,pointsAuthority:t.pointsAuthority??y,eventType:a,drawId:v})}}}({structureParticipation:T,awardProfiles:o,wheelchairClass:N,participantType:y,participantId:v,participant:t,eventType:R,startDate:M,category:D,drawInfo:r,drawType:w,endDate:A,gender:b,level:g,accum:e,mappedMatchUps:i,participantIndividualIdsMap:f,participantPersonMap:m,personPoints:d,pointsAuthority:h,drawId:P});const n=function(t,e,n){let r=0;if(t?.bonusPoints&&void 0!==e)for(const i of t.bonusPoints)if(i.finishingPositions?.includes(e)){const t=i.value;if("number"==typeof t)r=t;else if("object"==typeof t){const e=wM(n,t.level??t);"number"==typeof e&&(r=e)}break}return r}(e.primaryAwardProfile,e.bestFinishingPosition,g);E=e.positionPoints+e.perWinPoints+n,(e.perWinPoints||e.positionPoints||n)&&function({accum:t,bonusPoints:e,points:n,eventType:r,drawId:i,category:o,drawType:a,startDate:s,endDate:c,level:u,devContext:d,participantType:p,participantId:l,person:m,personPoints:f,pairPoints:h,teamPoints:g,doublesAttribution:I,participantIndividualIdsMap:S,participantPersonMap:y,pointsAuthority:v}){const U=t.primaryAwardProfile?.pointsAuthority??v,P={winCount:t.totalWinsCount,positionPoints:t.positionPoints,rangeAccessor:t.rangeAccessor,perWinPoints:t.perWinPoints,bonusPoints:e,pointsAuthority:U,stage:t.rankingStage,eventType:r,drawId:i,points:n,category:o,drawType:a,startDate:s,endDate:c,level:u};d&&t.profileName&&(P.profileName=t.profileName);!function({award:t,participantType:e,participantId:n,person:r,personPoints:i,pairPoints:o,teamPoints:a,doublesAttribution:s,participantIndividualIdsMap:c,participantPersonMap:u}){const d=r?.personId;if(d)return i[d]||(i[d]=[]),void i[d].push(t);if(e===Sm){if(!s||s===cM)return o[n]||(o[n]=[]),void o[n].push(t);const e=s===sM?.5:1,r=c[n]??[];for(const n of r){const r=u[n];if(!r)continue;const o={...t,points:Math.round(t.points*e),positionPoints:Math.round(t.positionPoints*e),perWinPoints:Math.round(t.perWinPoints*e),bonusPoints:Math.round(t.bonusPoints*e)};i[r]||(i[r]=[]),i[r].push(o)}return}e===hm&&(a[n]||(a[n]=[]),a[n].push(t))}({award:P,participantType:p,participantId:l,person:m,personPoints:f,pairPoints:h,teamPoints:g,doublesAttribution:I,participantIndividualIdsMap:S,participantPersonMap:y})}({accum:e,bonusPoints:n,points:E,eventType:R,drawId:P,category:D,drawType:w,startDate:M,endDate:A,level:g,devContext:I,participantType:y,participantId:v,person:U,personPoints:d,pairPoints:p,teamPoints:l,doublesAttribution:c,participantIndividualIdsMap:f,participantPersonMap:m,pointsAuthority:h}),function({qualityWinProfiles:t,participant:e,drawId:n,mappedMatchUps:r,participantId:i,person:o,tournamentRecord:a,level:s,personPoints:c,pointsAuthority:u,eventType:d}){if(!t?.length||!e.matchUps)return;const p=Object.values(e.matchUps).filter(t=>t.drawId===n&&t.participantWon);if(!p.length)return;const l=p.map(t=>t.matchUpId),m={};for(const t of p)m[t.matchUpId]=t.sideNumber;const{qualityWinPoints:f,qualityWins:h}=DM({qualityWinProfiles:t,wonMatchUpIds:l,mappedMatchUps:r,participantSideMap:m,tournamentParticipants:a.participants??[],tournamentStartDate:a.startDate,level:s});if(f>0){const t=o?.personId;t&&(c[t]||(c[t]=[]),c[t].push({qualityWinPoints:f,qualityWins:h,pointsAuthority:u,eventType:d,drawId:n}))}}({qualityWinProfiles:u,participant:t,drawId:P,mappedMatchUps:i,participantId:v,person:U,tournamentRecord:S,level:g,personPoints:d,pointsAuthority:e.primaryAwardProfile?.pointsAuthority??h,eventType:R})}}function xM({participantFilters:t,policyDefinitions:e,tournamentRecord:n,policyName:r,level:i}){if(!n)return{error:rt};const o=$r(),{policyDefinitions:a}=_d({policyTypes:[Mu],tournamentRecord:n}),s=e?.[Mu]??a?.[Mu]??(r?AM.lookup({policyType:Mu,name:r}):void 0);if(!s)return{error:Ue};const c=s.awardProfiles;let u=s.requireWinFirstRound;const d=s.requireWinForPoints,p=s.doublesAttribution,l=s.qualityWinProfiles,m=s.pointsAuthority,{participants:f,derivedEventInfo:h,derivedDrawInfo:g,mappedMatchUps:I}=xS({withRankingProfile:!0,participantFilters:t,tournamentRecord:n}),S=f?.filter(t=>t.draws?.length),y={},v={};for(const t of n.participants??[])t.person?.personId&&(y[t.participantId]=t.person.personId),t.individualParticipantIds?.length&&(v[t.participantId]=t.individualParticipantIds);const U={},P={},T={};for(const t of S??[])for(const e of t.draws){FM({participant:t,draw:e,eventInfo:h[e.eventId],drawInfo:g[e.drawId],mappedMatchUps:I,awardProfiles:c,requireWinForPoints:d,requireWinFirstRound:u,doublesAttribution:p,qualityWinProfiles:l,personPoints:U,pairPoints:T,teamPoints:P,participantPersonMap:y,participantIndividualIdsMap:v,pointsAuthority:m,level:i,devContext:o,tournamentRecord:n})}return{participantsWithOutcomes:S,personPoints:U,pairPoints:T,teamPoints:P,...Y}}function _M({policyDefinitions:t,tournamentRecord:e,policyName:n,eventId:r,level:i}){if(!e)return{error:rt};if(!r)return{error:Ht};const o=e.events?.find(t=>t.eventId===r);if(!o)return{error:Ht};const a=t?.[Mu]??(n?AM.lookup({policyType:Mu,name:n}):void 0);if(!a)return{error:Ue};const s=i??function(t,e){if(!t?.system||!t?.value)return;const n=e?.tierToLevel?.[t.system]?.[t.value];return n??t.numericRank}(o.eventTier??e.tournamentTier,a),c=xM({participantFilters:{eventIds:[r]},policyDefinitions:t??{[Mu]:a},level:s,tournamentRecord:e});if(c.error)return c;const{personPoints:u={},pairPoints:d={},teamPoints:p={}}=c,{participants:l}=xS({tournamentRecord:e}),m={},f={};for(const t of l??[])f[t.participantId]={participantName:t.participantName??"",personId:t.person?.personId},t.person?.personId&&(m[t.person.personId]={participantId:t.participantId,participantName:t.participantName??""});const h=new Set((o.drawDefinitions??[]).map(t=>t.drawId)),g=[];!function({personPoints:t,personToParticipant:e,eventDrawIds:n,eventAwards:r}){for(const[i,o]of Object.entries(t)){const t=e[i];if(t)for(const e of o)n.has(e.drawId)&&r.push({...e,participantId:t.participantId,participantName:t.participantName,personId:i})}}({personPoints:u,personToParticipant:m,eventDrawIds:h,eventAwards:g}),LM({points:d,participantLookup:f,eventDrawIds:h,eventAwards:g}),LM({points:p,participantLookup:f,eventDrawIds:h,eventAwards:g}),g.sort((t,e)=>(e.points||0)-(t.points||0)||(t.participantName??"").localeCompare(e.participantName??""));const I=o.eventType===ns;return{eventAwards:g,eventName:o.eventName,eventType:o.eventType,isDoubles:I,...Y}}function LM({points:t,participantLookup:e,eventDrawIds:n,eventAwards:r}){for(const[i,o]of Object.entries(t)){const t=e[i];if(t)for(const e of o)n.has(e.drawId)&&r.push({...e,participantId:i,participantName:t.participantName})}}const BM={histogram:[],count:0,stddev:0,median:0,mean:0,iqr:0,min:0,max:0,gaps:[]};function VM(t,e){if(0===t.length)return 0;if(1===t.length)return t[0];const n=(t.length-1)*e,r=Math.floor(n),i=Math.ceil(n);if(r===i)return t[r];const o=n-r;return t[r]+(t[i]-t[r])*o}function GM(t,e,n,r){if(0===t.length||r<=0)return[];const i=Math.floor(e/r)*r,o=Math.ceil(n/r)*r,a=[];for(let t=i;(t<o||t===i)&&(a.push({binStart:t,binEnd:t+r,count:0}),!(t>=o));t+=r);for(const e of t){a[Math.min(a.length-1,Math.floor((e-i)/r))].count++}return a}function jM(t,e){const n=[];for(let r=1;r<t.length;r++){const i=t[r]-t[r-1];i>=e&&n.push({start:t[r-1],end:t[r],size:i})}return n.sort((t,e)=>e.size-t.size)}function qM({binWidth:t=.5,gapThreshold:e=.5,ratings:n}){if(!Array.isArray(n)||0===n.length)return BM;const r=[...n].sort((t,e)=>t-e),i=r.length,o=r[0],a=r[i-1],s=r.reduce((t,e)=>t+e,0)/i,c=VM(r,.5),u=r.reduce((t,e)=>t+(e-s)**2,0)/i,d=Math.sqrt(u),p=VM(r,.25),l=VM(r,.75)-p;return{histogram:GM(r,o,a,t),gaps:jM(r,e),count:i,stddev:d,median:c,mean:s,iqr:l,min:o,max:a}}const WM=[2,3,4,6],$M=[.5,1];function HM(t,e){return{participantIds:e.map(t=>t.participantId),ratings:e.map(t=>t.rating),label:t}}function zM(t,e,n){return`${t} ${e+1} of ${n}`}function YM(t,e){if(e>t.length)return;const n=function(t,e){if(e<=0)return[];const n=[],r=Math.floor(t.length/e),i=t.length%e;let o=0;for(let a=0;a<e;a++){const e=r+(a<i?1:0);n.push(t.slice(o,o+e)),o+=e}return n}(t,e);if(n.some(t=>t.length<4))return;const r=n.map((t,n)=>HM(zM("Tier",n,e),t));return{type:"EQUAL_COUNT",variant:`k=${e}`,flights:r}}function KM(t,e){if(0===t.length||e<=0)return;const n=t[0].rating,r=t.at(-1)?.rating??0,i=new Map;for(const r of t){const t=Math.floor((n-r.rating)/e);i.has(t)||i.set(t,[]),i.get(t).push(r)}const o=[...i.keys()].sort((t,e)=>t-e),a=[];for(const t of o){const o=i.get(t);if(o.length<4)continue;const s=n-t*e,c=`${Math.max(r,s-e).toFixed(2)} – ${s.toFixed(2)}`;a.push(HM(c,o))}return a.length<2?void 0:{type:"EQUAL_BAND",variant:`width=${e}`,flights:a}}function QM(t){if(t.length<8)return;const e=qM({ratings:t.map(t=>t.rating)}).gaps.map(t=>t.start),n=new Set;for(const t of e)n.add(t);const r=[];let i=[];for(const e of t)n.has(e.rating)&&i.length>=4&&(r.push(i),i=[]),i.push(e);i.length>0&&r.push(i);const o=function(t){const e=[];for(const n of t)if(n.length>=4||0===e.length)e.push(n);else{const t=e.at(-1);t&&t.push(...n)}return e}(r);if(o.length<2)return;return{type:"NATURAL_CLUSTER",flights:o.map((t,e)=>HM(zM("Cluster",e,o.length),t))}}function JM(t){if(!Array.isArray(t)||t.length<4)return[];const e=function(t){return[...t].sort((t,e)=>e.rating-t.rating)}(t),n=(r=t.length)<=8?1:r<=16?2:r<=32?4:r<=64?6:8;var r;const i=[];for(const t of WM){if(t>n)continue;const r=YM(e,t);r&&i.push(r)}for(const t of $M){const r=KM(e,t);r&&r.flights.length<=n&&i.push(r)}const o=QM(e);return o&&o.flights.length<=n&&i.push(o),i.push(function(t){return{type:"STAGGERED_SINGLE",flights:[HM("All Levels",t)]}}(e)),i}const XM=[4,6,8],ZM=[3,5,7],tA=[3,5],eA={NONE:["SINGLE_ELIMINATION","ROUND_ROBIN","SWISS","DRAW_MATIC","LUCKY_DRAW","FEED_IN"],LIGHT:["SINGLE_ELIMINATION","ROUND_ROBIN","SWISS","DRAW_MATIC","LUCKY_DRAW","FEED_IN","FIRST_MATCH_LOSER_CONSOLATION","ROUND_ROBIN_WITH_PLAYOFF","DOUBLE_ELIMINATION"],FULL:["SINGLE_ELIMINATION","ROUND_ROBIN","SWISS","DRAW_MATIC","LUCKY_DRAW","FEED_IN","FIRST_MATCH_LOSER_CONSOLATION","ROUND_ROBIN_WITH_PLAYOFF","DOUBLE_ELIMINATION","FIRST_ROUND_LOSER_CONSOLATION","COMPASS","ADAPTIVE"]},nA={ROUND_ROBIN:0,ROUND_ROBIN_WITH_PLAYOFF:0,SWISS:0,SINGLE_ELIMINATION:0,FEED_IN:.05,DOUBLE_ELIMINATION:.1,DRAW_MATIC:.1,LUCKY_DRAW:.1,FIRST_MATCH_LOSER_CONSOLATION:.2,FIRST_ROUND_LOSER_CONSOLATION:.25,COMPASS:.3,ADAPTIVE:.3};function rA(t){return t<=1?1:2**Math.ceil(Math.log2(t))}function iA(t,e,n,r={}){return{withdrawalRiskFactor:nA[t],minMatchesPerPlayer:e,totalMatches:n,kind:t,...r}}function oA(t){if(t<2)return[];const e=rA(t),n=t-1,r=Math.max(1,Math.ceil(Math.log2(e)));return[iA("SINGLE_ELIMINATION",1,n),iA("FIRST_MATCH_LOSER_CONSOLATION",2,Math.round(1.5*n),{variantId:"FMLC"}),iA("FIRST_ROUND_LOSER_CONSOLATION",r,Math.round(1.7*n),{variantId:"FRLC",rounds:r}),iA("DOUBLE_ELIMINATION",2,2*n-1)]}function aA(t){return t>=7&&t<=8?[iA("COMPASS",3,12,{variantId:"COMPASS_8"})]:t>=13&&t<=16?[iA("COMPASS",4,28,{variantId:"COMPASS_16"})]:[]}function sA(t){if(t<2||t>8)return[];return[iA("ROUND_ROBIN",t-1,t*(t-1)/2,{groupSize:t})]}function cA(t){const e=XM.flatMap(e=>function(t,e){if(t<2*e||t%e!==0)return[];const n=t/e,r=e*(e-1)/2*n,i=rA(n),o=i-1;return[iA("ROUND_ROBIN",e-1,r,{variantId:`RR_${e}x${n}`,groupSize:e}),iA("ROUND_ROBIN_WITH_PLAYOFF",e-1+Math.max(0,Math.ceil(Math.log2(i))),r+o,{variantId:`RR_${e}x${n}_PLAYOFF`,groupSize:e})]}(t,e));return[...sA(t),...e]}function uA(t){if(t<2)return[];const e=Math.max(3,Math.ceil(Math.log2(t)));return ZM.filter(e=>e<=t-1).map(n=>iA("SWISS",n,Math.floor(t*n/2),{variantId:`SWISS_R${n}${n===e?"_REC":""}`,rounds:n}))}function dA(t){return t<2?[]:tA.filter(e=>e<=t-1).map(e=>iA("DRAW_MATIC",e,Math.floor(t*e/2),{variantId:`DRAW_MATIC_R${e}`,rounds:e}))}function pA(t){if(t<2)return[];if((e=t)>0&&!(e&e-1))return[];var e;return[iA("LUCKY_DRAW",1,t-1)]}function lA(t){if(t<4)return[];return[iA("ADAPTIVE",Math.max(2,Math.ceil(Math.log2(t))),Math.round(1.6*t))]}function mA(t,e){if(0===t.length||e<4)return[];const n=rA(Math.max(2,Math.floor(.5*e))),r=Math.max(0,n-1);return t.map(t=>({...t,voluntaryConsolation:!0,totalMatches:t.totalMatches+r,variantId:t.variantId?`${t.variantId}_VC`:"VC"}))}function fA(t,e){const n=[...oA(t),...aA(t),...cA(t),...uA(t),...dA(t),...pA(t),...lA(t)];return e&&n.push(...function(t){if(t<8)return[];const e=Math.max(2,Math.ceil(Math.log2(t))),n=t-1,r=[iA("FEED_IN",1,n,{rounds:e,variantId:`FEED_IN_${e}_TIERS`})];return t>=8&&r.push(iA("FEED_IN",2,Math.round(1.4*n),{rounds:e,variantId:"FIC_SF"})),t>=12&&r.push(iA("FEED_IN",2,Math.round(1.6*n),{rounds:e,variantId:"FIC_QF"})),t>=16&&(r.push(iA("FEED_IN",3,Math.round(1.8*n),{rounds:e,variantId:"FIC_R16"})),r.push(iA("FEED_IN",3,Math.round(2*n),{rounds:e,variantId:"FIC"})),r.push(iA("FEED_IN",2,Math.round(1.7*n),{rounds:e,variantId:"MFIC"}))),r}(t)),n}const hA={SINGLE_ELIMINATION:Ls,FIRST_MATCH_LOSER_CONSOLATION:Vs,FIRST_ROUND_LOSER_CONSOLATION:Gs,DOUBLE_ELIMINATION:Bs,COMPASS:xs,LUCKY_DRAW:js,ADAPTIVE:qs,ROUND_ROBIN:ic,ROUND_ROBIN_WITH_PLAYOFF:oc,SWISS:nc},gA={competitive:60,floor:20,utilization:15,withdrawal:5};function IA({predictionModel:t,structure:e,flight:n}){const{kind:r}=e,i=n.ratings;if("DRAW_MATIC"===r)return uw({ratings:i,projectionMode:"MIN_DELTA",predictionModel:t});if("FEED_IN"===r)return uw({ratings:i,projectionMode:"BALANCED_BRACKET",predictionModel:t});const o=hA[r];return o?uw({ratings:i,drawType:o,groupSize:e.groupSize,predictionModel:t}):nw(0,t??{competitiveAnchors:[],decisiveAnchors:[]})}function SA({minMatchesPerPlayer:t,flightStructures:e,courtUtilization:n,constraints:r,competitive:i}){const o=function(t,e){if("number"!=typeof t)return e;const n=Math.abs(e-t);return Math.max(0,1-n)}(r.targetCompetitivePct,i),a=function(t,e){return"number"!=typeof e||t>=e?1:Math.max(0,t/e)}(t,r.targetMatchesPerPlayer),s=function(t){return Number.isFinite(t)?t>1?Math.max(0,2-t):t:0}(n),c=function(t){return 0===t.length?1:1-Math.max(...t.map(t=>t.structure.withdrawalRiskFactor))}(e);return(o*gA.competitive+a*gA.floor+s*gA.utilization+c*gA.withdrawal)/Object.values(gA).reduce((t,e)=>t+e,0)}function yA({recommendationsByFlightSize:t,predictionModel:e,constraints:n,strategy:r}){if(0===r.flights.length)return[];const i=1===r.flights.length,o=new Set(r.flights.map(t=>t.participantIds.length)),a=new Map;for(const e of o)a.set(e,t(e,i));const s=function(t,e){if(0===t.length)return[];const n=t[0].participantIds.length,r=e.get(n)??[];return r.filter(n=>t.every(t=>(e.get(t.participantIds.length)??[]).some(t=>vA(t,n))))}(r.flights,a),c=[];for(const t of s){const i=r.flights.map(n=>{const r=a.get(n.participantIds.length).find(e=>vA(e,t));return{predictedBands:IA({flight:n,structure:r,predictionModel:e}),structure:r,flight:n}}),o=UA({strategy:r,flightStructures:i,constraints:n});c.push(o)}return c}function vA(t,e){return t.kind===e.kind&&(t.variantId??"")===(e.variantId??"")&&(t.groupSize??0)===(e.groupSize??0)}function UA({flightStructures:t,constraints:e,strategy:n}){const r=function(t){const e=t.reduce((t,e)=>{const n=e.structure.totalMatches;return t.competitive+=e.predictedBands.competitive*n,t.decisive+=e.predictedBands.decisive*n,t.routine+=e.predictedBands.routine*n,t.totalMatches+=n,t},{competitive:0,decisive:0,routine:0,totalMatches:0});return 0===e.totalMatches?{competitive:0,decisive:0,routine:0,totalMatches:0}:{competitive:e.competitive/e.totalMatches,decisive:e.decisive/e.totalMatches,routine:e.routine/e.totalMatches,totalMatches:e.totalMatches}}(t),i=function(t){if(0===t.length)return{minMatchesPerPlayer:0};let e=1/0;for(const n of t)n.structure.minMatchesPerPlayer<e&&(e=n.structure.minMatchesPerPlayer);return{minMatchesPerPlayer:e}}(t),o=function(t,e){const n=e.avgMinutes??90,r=e.hoursPerDay??8,i=t*n/60,o=e.courts*e.days*r;return{courtHoursRequired:i,courtHoursAvailable:o,courtUtilization:o>0?i/o:1/0}}(r.totalMatches,e),a={minMatchesPerPlayer:i.minMatchesPerPlayer,courtHoursRequired:o.courtHoursRequired,courtHoursAvailable:o.courtHoursAvailable,courtUtilization:o.courtUtilization,totalMatches:r.totalMatches,competitive:r.competitive,decisive:r.decisive,routine:r.routine},s=function({minMatchesPerPlayer:t,flightStructures:e,courtUtilization:n,constraints:r}){const i=[];return"number"==typeof r.targetMatchesPerPlayer&&t<r.targetMatchesPerPlayer&&i.push("BELOW_FLOOR"),n>1&&i.push("OVER_CAPACITY"),e.some(t=>t.structure.withdrawalRiskFactor>=.2)&&i.push("WITHDRAWAL_RISK"),i}({minMatchesPerPlayer:i.minMatchesPerPlayer,courtUtilization:o.courtUtilization,flightStructures:t,constraints:e}),c=SA({minMatchesPerPlayer:i.minMatchesPerPlayer,courtUtilization:o.courtUtilization,competitive:r.competitive,flightStructures:t,constraints:e});return{strategy:n.type,variant:n.variant,flightStructures:t,aggregate:a,warnings:s,score:c}}const PA=Hm[Du].predictionModel,TA={histogram:[],count:0,stddev:0,median:0,mean:0,iqr:0,min:0,max:0,gaps:[]};function wA({predictionModel:t,tournamentRecord:e,participants:n,governance:r,constraints:i}){if(!Array.isArray(n)||n.length<2)return{plans:[],distribution:TA,error:sr};if(!i||"number"!=typeof i.courts||"number"!=typeof i.days)return{plans:[],distribution:TA,error:sr};const o=qM({ratings:n.map(t=>t.rating)}),a=JM(n),s=function(t,e){if(t)return t;if(e){const{policy:t}=Qm({policyType:Du,tournamentRecord:e});if(t?.predictionModel)return t.predictionModel}return PA}(t,e),c=(t,e)=>function({consolationAppetite:t="LIGHT",voluntaryConsolation:e=!1,allowedDrawTypes:n,singleFlight:r=!0,flightSize:i}){const o=new Set(eA[t]),a=n&&n.length>0?new Set(n):void 0,s=fA(i,r).filter(t=>!(!o.has(t.kind)||a&&!a.has(t.kind)));return e?[...s,...mA(s,i)]:s}({consolationAppetite:i.consolationAppetite,voluntaryConsolation:i.voluntaryConsolation,allowedDrawTypes:r?.allowedDrawTypes,singleFlight:e,flightSize:t}),u=[],d=[];for(const t of a){const e=yA({recommendationsByFlightSize:c,predictionModel:s,constraints:i,strategy:t});0!==e.length?d.push(...e):u.push({strategy:t.type,reason:"NO_ELIGIBLE_STRUCTURE"})}return{rejected:u.length>0?u:void 0,plans:(p=d,[...p].sort((t,e)=>e.score-t.score).map((t,e)=>({...t,rank:e+1}))),distribution:o};var p}function DA(t){const e=t.participants?.filter(({participantType:t})=>t===ym),n=2===e?.length,r=1===t.events?.length&&t.events[0],i=1===r?.drawDefinitions?.length&&r.drawDefinitions[0],o=1===i?.structures?.length&&i.structures[0],a=2===o?.positionAssignments?.length;return!!(r.tieFormat&&n&&a)}function RA({tournamentRecord:t}){if(!t)return{error:rt};const{drawsAnalysis:e}=xT({tournamentRecord:t}),n={isDual:DA(t),drawsAnalysis:e},r=xS({tournamentRecord:t});return r.missingParticipantIds?.length&&(n.missingParticipantIds=r.missingParticipantIds),{...Y,analysis:n}}function bA(t){const{tournamentRecord:e,scope:n}=t;if(!e)return{error:rt};const r=(new Date).toISOString(),i=[],o=(t,e)=>{const{extension:o}=td({element:t,name:gd}),a=o?.value??{locks:[]};for(const t of a.locks)null!==t.expiresAt&&t.expiresAt<=r||n&&t.scope!==n||i.push({...t,...e})};o(e);const a=e.events??[];for(const t of a){o(t,{eventId:t.eventId});const e=t.drawDefinitions??[];for(const n of e)o(n,{eventId:t.eventId,drawId:n.drawId})}const s=e.venues??[];for(const t of s)o(t,{venueId:t.venueId});return{...Y,mutationLocks:i}}var NA={__proto__:null,analyzeDraws:xT,analyzeTournament:RA,cleanExpiredMutationLocks:gM,getAggregateTeamResults:UM,getAllowedDrawTypes:aM,getAllowedMatchUpFormats:oM,getApplicableAwardProfileLevels:hM,getAppliedPolicies:xd,getCompetitionDateRange:yM,getCompetitionPenalties:SM,getEventRankingPoints:_M,getMutationLocks:bA,getPolicyDefinitions:_d,getRegistrationProfile:vM,getTournamentInfo:Pw,getTournamentPenalties:IM,getTournamentPersons:TM,getTournamentPoints:xM,getTournamentStructures:UU,getTournamentTimeItem:Em,suggestFormatPlans:wA};function MA(t){if(!t)return{};const e=[],n=t.tieFormatName,i=t.collectionDefinitions?.map(t=>{const{matchUpType:n,matchUpFormat:i,matchUpCount:o,category:a,gender:s}=t;e.includes(i)||e.push(i);const c=a?.ageCategoryCode;return[o,n===r?"D":"S",c,i,s].join(";")}).join("|");return{tieFormatName:t&&n||"UNNAMED",matchUpFormats:e,tieFormatDesc:i}}function AA({considerations:t={},descendant:e,ancestor:n}){const r={},i={},{matchUpFormats:o,tieFormatDesc:a}=MA(e),{matchUpFormats:s,tieFormatDesc:c}=MA(n),u=M((o??[]).filter(t=>!(s??[]).includes(t)).concat((s??[]).filter(t=>!(o??[]).includes(t)))),d=!(!t?.collectionName||e.collectionDefinitions.map(({collectionName:t})=>t).join("|")===n.collectionDefinitions.map(({collectionName:t})=>t).join("|")),p=!(!t?.collectionOrder||e.collectionDefinitions.map(({collectionOrder:t})=>t).join("|")===n.collectionDefinitions.map(({collectionOrder:t})=>t).join("|")),l=Object.assign({},...(e?.collectionDefinitions??[]).map(t=>({[t.collectionId]:t}))),m=Object.assign({},...(n?.collectionDefinitions??[]).map(t=>({[t.collectionId]:t})));r.collectionIds=G(Object.keys(l),Object.keys(m)),i.collectionIds=G(Object.keys(m),Object.keys(l)),r.collectionsValue=EA(l),i.collectionsValue=EA(m),r.groupsCount=n?.collectionGroups?.length??(0-(e?.collectionGroups?.length??0)||0),i.groupsCount=r.groupsCount?-1*r.groupsCount:0;const f=r.collectionsValue.totalValue-i.collectionsValue.totalValue,h=r.collectionsValue.totalMatchUps-i.collectionsValue.totalMatchUps,g=i.collectionsValue.assignmentValues.length!==r.collectionsValue.assignmentValues.length,I=i.collectionsValue.assignmentValues.some((t,e)=>{const n=r.collectionsValue.assignmentValues[e];return!n||(t.valueKey!==n.valueKey||(t.value!==n.value||!!Array.isArray(t.value)&&t.value.every((t,e)=>n.value[e]===t)))}),S=d||p||c!==a||g||I||0!==f,y=[...i.collectionsValue.invalidValues,...r.collectionsValue.invalidValues],v=y.length&&y;return{matchUpFormatDifferences:u,matchUpCountDifference:h,descendantDifferences:r,ancestorDifferences:i,orderDifference:p,valueDifference:f,nameDifference:d,descendantDesc:a,ancestorDesc:c,...Y,different:S,invalid:v}}function EA(t){const e=[],n=[];let r=0;return{totalValue:Object.keys(t).sort(TS).reduce((i,o)=>{const a=t[o],{collectionValueProfiles:s,collectionValue:c,matchUpCount:u,matchUpValue:d,scoreValue:p,setValue:l}=a,m={collectionValueProfiles:s,collectionValue:c,matchUpValue:d,scoreValue:p,setValue:l},f=Object.keys(m).filter(t=>![void 0,null].includes(m[t])&&(!Array.isArray(m[t])||m[t].length>0));1!==f.length&&e.push({collectionId:o});const h=f[0];if(h){const t="collectionValueProfiles"===h?Object.values(s):m[h];n.push({valueKey:h,value:t})}return r+=u,s?.length?i+s.reduce((t,e)=>t+e.value,0):u?R(d)?i+d*u:R(p)?i+p*u:R(l)?i+l*u:i+c:i},0),totalMatchUps:r,invalidValues:e,assignmentValues:n}}function CA(t){Object.assign(t,{inContext:!0});const{matchUp:e,error:n}=OA(t);return{matchUp:ca(e,!0,!0),error:n}}function OA({participantsProfile:t,afterRecoveryTimes:e,tournamentRecord:n,contextContent:r,contextProfile:i,drawDefinition:o,nextMatchUps:a,matchUpId:s,inContext:c,eventId:u,drawId:d,event:p}){if(!n)return{error:rt};if("string"!=typeof s)return{error:fe};if(!o||!p){const t=(Qg({tournamentRecord:n,nextMatchUps:a}).matchUps??[]).find(t=>t.matchUpId===s);if(!t)return{error:ge};({eventId:u,drawId:d}=t),({event:p,drawDefinition:o}=wg({tournamentRecord:n,eventId:u,drawId:d}))}if(!o)return{error:ut};i&&!r&&(r=zm({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=[]}=Bm({participantsProfile:t,tournamentRecord:n,contextProfile:i,inContext:c});if(a){const t=(Zg({context:c?l:void 0,participants:m,afterRecoveryTimes:e,contextContent:r,contextProfile:i,drawDefinition:o,nextMatchUps:a,inContext:c,event:p}).matchUps??[]).find(t=>t.matchUpId===s);if(!t)return{error:ge};const n=o?.structures?.find(e=>e.structureId===t.structureId);return{drawDefinition:o,structure:n,matchUp:t}}{const{matchUp:n,structure:a}=nT({context:c?l:void 0,tournamentParticipants:m,participantsProfile:t,afterRecoveryTimes:e,contextContent:r,drawDefinition:o,contextProfile:i,matchUpId:s,inContext:c,event:p});return{matchUp:n,structure:a,drawDefinition:o}}}function kA({tournamentRecord:t,drawDefinition:e,structureId:n,matchUpId:r,structure:i,eventId:o,drawId:a,event:s}){if(!t)return{error:rt};if(!(a||s||n||r))return Ci({result:{error:Ae},stack:"getTieFormat"});o&&!s&&(s=t.events?.find(t=>t.eventId===o));const c=CA({tournamentRecord:t,drawDefinition:e,matchUpId:r,drawId:a,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:bt};const t=ol({drawDefinition:e,structureId:n});if(t.error)return t;i=t.structure}const u=(i?.tieFormat||i?.tieFormatId)&&Rf({structure:i,drawDefinition:e,event:s})?.tieFormat,d=(e?.tieFormat||e?.tieFormatId)&&Rf({drawDefinition:e,event:s})?.tieFormat,p=Rf({event:s})?.tieFormat,l=Rf({matchUp:c?.matchUp,drawDefinition:e,structure:i,event:s})?.tieFormat;return{...Y,matchUp:c?.matchUp,structureDefaultTieFormat:mT(u),eventDefaultTieFormat:mT(p),drawDefaultTieFormat:mT(d),tieFormat:mT(l),structure:i}}var FA={__proto__:null,compareTieFormats:AA,getTieFormat:kA,tieFormatGenderValidityCheck:Ki,validateCollectionDefinition:ea};function xA({tournamentRecord:t,outcomes:e}){if(!t)return{error:rt};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=pS({event:t}),{drawDetails:r,drawIds:i}=e??{},{eventId:o}=t;return n[o].filter(t=>{const n=r?Object.keys(e.drawDetails).filter(t=>lS({drawId:t,drawDetails:r})):[];return i?.includes(t)||n.includes(t)}).length}).map(t=>t.eventId),eventIdPublishedDrawIdsMap:n}}function _A(t,e){if(!t||!e?.length)return;const n=t.roundLimit,r=t.scheduledRounds??{},i=e.reduce((t,e)=>Math.max(t,e.roundNumber||0),0);if(0===i)return;const o={};let a=!1;for(let t=1;t<=i;t++){const e={};null!=n&&t>n&&(e.hidden=!0,a=!0);const i=r[t];i&&Eg(i)&&(e.embargoed=!0,a=!0),(e.hidden||e.embargoed)&&(o[t]=e)}return a?o:void 0}function LA({tournamentRecord:t,policyDefinitions:e}){if(!t)return{error:rt};const n=t.events??[],r=t?.participants??[],{tournamentInfo:i}=Pw({tournamentRecord:t}),{venues:o}=gw({tournamentRecord:t}),a=n.map(n=>{const{eventId:i}=n,o=Sw({event:n}).eventInfo,a=Jm({tournamentRecord:t,event:n}).scheduleTiming,s=(n.drawDefinitions??[]).map(o=>{const{drawId:s,drawName:c,matchUpFormat:u,updatedAt:d}=o,p={drawId:s,drawName:c,matchUpFormat:u,updatedAt:d},{abandonedMatchUps:l,completedMatchUps:m,upcomingMatchUps:f,pendingMatchUps:h}=Yg({requireParticipants:!0,tournamentParticipants:r,context:{eventId:i},policyDefinitions:e,tournamentRecord:t,inContext:!0,scheduleTiming:a,drawDefinition:o,event:n});return{drawInfo:p,matchUps:{abandonedMatchUps:l,completedMatchUps:m,upcomingMatchUps:f,pendingMatchUps:h}}}),c=pS({event:n});return Object.assign(o,{drawsData:s,publish:c}),o});return{allEventData:{tournamentInfo:i,venuesData:o,eventsData:a}}}var BA={__proto__:null,bulkUpdatePublishedEventIds:xA,getAllEventData:LA,getCourtInfo:Ug,getDrawData:Rw,getEventData:bw,getEventPublishStatus:pS,getPublishState:mS,getRoundVisibilityState:_A,getTournamentPublishStatus:dS,getVenueData:Pg,isEmbargoed:Eg,isVisiblyPublished:Cg};function VA({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:e,timeAfterRecovery:n,matchUp:r}){const{individualParticipantIds:i}=rm(r);n=n??r.schedule?.timeAfterRecovery;const o=e=>{t[e]||(t[e]=[]),t[e]=M(t[e].concat(...i))},a=t=>{n&&(!e[t]||n>e[t])&&(e[t]=n)},s=r.winnerTo?.matchUpId||r.winnerMatchUpId;s&&(n&&a(s),o(s));const c=r.loserTo?.matchUpId||r.loserMatchUpId;c&&(n&&a(c),o(c)),r.sidesTo?.length&&r.sidesTo.forEach(({matchUpId:t})=>{t&&(n&&a(t),o(t))})}function GA(t){const e=fu(t,[{[Gc]:!0}]);if(e.error)return e;const{matchUpPotentialParticipantIds:n,dateScheduledMatchUpIds:r=[],scheduleCompletedMatchUps:i,matchUpNotBeforeTimes:o,matchUpScheduleTimes:a,orderedMatchUpIds:s,clearDate:c,matchUps:u}=t,d=a?Object.keys(a):[],p=(s??[]).map(t=>u.find(e=>e.matchUpId===t)).filter(Boolean).filter(t=>{const e=!c&&(r.includes(t.matchUpId)||d.includes(t.matchUpId)),n=[Sp,Pp,vp,gp,Np,Ep,wp,Tp].includes(t?.matchUpStatus);return i||!e&&!t.winningSide&&!n}),l=n&&o?p.reduce((t,e)=>{const{drawId:r,tournamentId:i}=e;return t.matchUpMap[i]||(t.matchUpMap[i]={}),t.matchUpMap[i][r]?t.matchUpMap[i][r].push(e):t.matchUpMap[i][r]=[e],VA({matchUpPotentialParticipantIds:n,matchUpNotBeforeTimes:o,matchUp:e}),t},{matchUpMap:{}}).matchUpMap:{};return{matchUpsToSchedule:p,matchUpMap:l}}function jA({defaultRecoveryMinutes:t=0,defaultAverageMinutes:e,tournamentRecords:n,matchUpFormat:r,categoryName:i,categoryType:o,tournamentId:a,eventType:s,eventId:c}){if(!Io({matchUpFormat:r}))return{error:oe};let u;return Object.keys(n).filter(t=>!a||t===a).forEach(t=>{if(u)return;const e=n[t],a=c?wg({tournamentRecord:e,eventId:c})?.event:void 0;return u=Jh({tournamentRecord:e,matchUpFormat:r,categoryName:i,categoryType:o,eventType:s,event:a}),u?.averageMinutes||u?.recoveryMinutes}),{recoveryMinutes:u?.recoveryMinutes||t,averageMinutes:u?.averageMinutes||e,typeChangeRecoveryMinutes:u?.typeChangeRecoveryMinutes||u?.recoveryMinutes||t}}function qA(t){const e=fu(t,[{[uu]:{tournamentRecords:!1,tournamentRecord:!1}},{rounds:!0,[cu]:iu}]);if(e.error)return e;const{scheduleCompletedMatchUps:n,periodLength:r=30}=t,i=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{};if("object"!=typeof i)return{error:nt};const o={},a=[],s=t.rounds.toSorted((t,e)=>(t.sortOrder??0)-(e.sortOrder??0)),c=t.containedStructureIds??Object.assign({},...Object.values(i).map(t=>nm({tournamentRecord:t}).containedStructures)),u=t.matchUps??Jg({nextMatchUps:!0,tournamentRecords:i}).matchUps;let d=0;const p={},l={},m={},f=s.flatMap(t=>{const e=t.periodLength||r,s=[];c?.[t.structureId]?s.push(...c[t.structureId]):s.push(t.structureId);let f=u?kg({tournamentIds:[t.tournamentId],roundNumbers:[t.roundNumber],matchUpIds:t.matchUpIds,eventIds:[t.eventId],drawIds:[t.drawId],processContext:!0,structureIds:s,matchUps:u}).sort(Xg):[];const{segmentNumber:h,segmentsCount:g}=t.roundSegment??{};if(R(h)&&S(f?.length)&&S(g)&&h>0&&h<=g&&g<f?.length&&!t.matchUpIds?.length){const t=f.length/g,e=t*(h-1);f=f.slice(e,e+t)}const I=i[t.tournamentId],y=wg({drawId:t.drawId,tournamentRecord:I}).event,v=[];for(const t of f){const e=t.matchUpFormat;e&&(o[e]||(o[e]=[],o[e].push(t)),v.push(e))}for(const r of v){const{eventType:o,category:s}=y??{},{categoryName:c,ageCategoryCode:u}=s??{},{typeChangeRecoveryMinutes:h,recoveryMinutes:g,averageMinutes:I,error:S}=jA({categoryName:c??u,categoryType:s?.categoryType,tournamentId:t.tournamentId,eventId:t.eventId,tournamentRecords:i,matchUpFormat:r,eventType:o});if(S)return{error:S,round:t};const v=f.filter(t=>(n||!_p.includes(t.matchUpStatus))&&t.matchUpStatus!==Sp).map(tl);v.forEach(t=>{m[t]={typeChangeRecoveryMinutes:h,recoveryMinutes:g,averageMinutes:I},p[t]=g,l[t]=I}),a.push(...v),d=Math.max(I||0,d);return{roundPeriodLength:e,recoveryMinutes:g,averageMinutes:I,matchUpIds:v,hash:`${I}|${e}`}}});return{scheduledRoundsDetails:f,greatestAverageMinutes:d,matchUpFormatCohorts:o,recoveryMinutesMap:p,averageMinutesMap:l,orderedMatchUpIds:a,minutesMap:m,...Y}}function WA({schedulingProfile:t,venueIds:e,eventIds:n,drawIds:r}){const i=[],o=t?.map(t=>{const o=Lo(t?.scheduleDate);if(!o)return void i.push(`Invalid date: ${t?.scheduledDate}`);const a=(t?.venues??[]).map(t=>{const{rounds:o,venueId:a}=t,s=e?.includes(a);if(!s)return void i.push(`Missing venueId: ${a}`);const c=o.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:a,rounds:c}:void 0}).filter(Boolean);return a.length&&o&&{...t,venues:a}}).filter(Boolean);return{updatedSchedulingProfile:o,modifications:i.length,issues:i}}function $A({tournamentRecords:t,schedulingProfile:e}){if(!e)return{valid:!0};if(!Array.isArray(e))return{valid:!1,error:sr};const{venueIds:n,tournamentsMap:r}=function(t){const e=(t?.tournamentRecords&&Object.values(t?.tournamentRecords))??[],n={},{venueIds:r,eventIds:i,drawIds:o,structureIds:a,tournamentIds:s}=e.reduce((t,e)=>{const{tournamentIds:r,tournamentMap:i,structureIds:o,venueIds:a,eventIds:s,drawIds:c}=function(t){const{tournamentRecord:e={},tournamentMap:n={},requireCourts:r}=t,i=[],o=[],a=[],s=[],c=(e?.venues??[]).map(({venueId:t,courts:e})=>(!r||e?.length)&&t),u=e?.tournamentId;if(u){i.push(u),n[u]={};const t=e?.events??[];for(const e of t){const t=e.eventId;a.push(t),n[u][t]={};const r=t=>parseInt(t);for(const i of e.drawDefinitions??[]){const e=i.drawId;s.push(e),n[u][t][e]={};const{structures:a}=al({drawDefinition:i});for(const i of a??[]){const a=i.structureId,{matchUps:s}=Fg({structure:i}),{roundMatchUps:c}=Bf({matchUps:s}),d=c&&Object.keys(c).map(r);if(n[u][t][e][a]=d,o.push(a),i.structures?.length)for(const r of i.structures)o.push(r.structureId),n[u][t][e][r.structureId]=d}}}}return{tournamentMap:n,tournamentIds:i,structureIds:o,venueIds:c,eventIds:a,drawIds:s}}({tournamentRecord:e});return a.forEach(e=>{t.venueIds.includes(e)||t.venueIds.push(e)}),t.tournamentIds.push(...r),t.structureIds.push(...o),t.eventIds.push(...s),t.drawIds.push(...c),Object.assign(n,i),t},{tournamentIds:[],structureIds:[],venueIds:[],eventIds:[],drawIds:[]});return{tournamentsMap:n,tournamentIds:s,structureIds:a,venueIds:r,eventIds:i,drawIds:o}}({tournamentRecords:t});let i,o;const a=e.every(t=>{const{scheduleDate:e,venues:a}=t;return!!Do(e)&&a.every(t=>{const{venueId:e,rounds:a}=t;if("string"!=typeof e)return o="venueId should be a string",!1;if(!Array.isArray(a))return o="rounds should be an array",!1;if(!n.includes(e))return i=Ln,!1;const s=a.every(t=>{if(!t)return o="empty round",!1;const{roundSegment:e,tournamentId:n,structureId:i,roundNumber:a,eventId:s,drawId:c}=t,u=r?.[n]?.[s]?.[c]?.[i],d=u?.includes(a);d||(o="Invalid rounds");const{segmentNumber:p,segmentsCount:l}=e??{},m=!e||R(p)&&S(l)&&p<=l;return m||(o="Invalid segment"),d&&m});return!!s})});return a||i||(i=sr),{valid:!!a,error:i,info:o}}function HA({tournamentRecords:t,tournamentRecord:e}){if("object"!=typeof t||!Object.keys(t).length)return{error:nt};const n=t=>t&&Km({element:t,groupAttribute:"scheduling",leafAttribute:"profile",name:wd});let r=n(e)??Object.values(t).map(n).find(t=>void 0!==t)??[];if(r.length){const{venueIds:n}=Iw({requireCourts:!0,tournamentRecords:t}),{eventIds:i,drawIds:o}=fT({tournamentRecords:t}),{updatedSchedulingProfile:a,modifications:s,issues:c}=WA({schedulingProfile:r,venueIds:n,eventIds:i,drawIds:o});if(s){r=a;const n=zA({tournamentRecords:t,tournamentRecord:e,schedulingProfile:r});return n.error?n:{schedulingProfile:r,modifications:s,issues:c}}}return{schedulingProfile:r,modifications:0}}function zA({tournamentRecords:t,tournamentRecord:e,schedulingProfile:n}){const r=$A({tournamentRecords:t,schedulingProfile:n});if(r.error)return r;const i=e?[e]:Object.values(t??{});for(const t of i)Ym({element:t,groupAttribute:"scheduling",leafAttribute:"profile",name:wd,value:n});return{...Y}}function YA(t){const{tournamentRecord:e}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!t.schedulingProfile){const{modifications:t,issues:r}=HA({tournamentRecords:n,tournamentRecord:e});return{success:!t,modifications:t,issues:r}}const{venueIds:r}=Iw({tournamentRecords:n}),{eventIds:i,drawIds:o}=fT({tournamentRecords:n}),{updatedSchedulingProfile:a,modifications:s,issues:c}=WA({schedulingProfile:t.schedulingProfile,venueIds:r,eventIds:i,drawIds:o});return s?{...zA({schedulingProfile:a,tournamentRecords:n}),modifications:s,issues:c}:{...Y,modifications:s,issues:c}}function KA(t){const{scheduleDates:e=[],tournamentRecords:n,periodLength:r=30}=t??{};if("object"!=typeof n)return{error:it};if(!Array.isArray(e))return{error:sr};if(!e.every(Do))return{error:_e};const i=[];let o=0;const a={},{schedulingProfile:s}=HA({tournamentRecords:n});if(!s)return{issues:i,...Y};const{matchUps:c}=Jg({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}=qA({tournamentRecords:n,periodLength:r,matchUps:c,rounds:e}),{matchUpDependencies:l}=iI({tournamentRecords:n,matchUps:c}),m=t=>{let e;return p?.find((n,r)=>{const i=n.matchUpIds.includes(t);return i&&(e=r),i}),e};if(d?.forEach((t,e)=>{const n=V(d.slice(e+1),l?.[t]?.matchUpIds??[]);n.length&&u.push({matchUpId:t,shouldBeAfter:n})}),u.length){o+=u.length;const t=u.map(({matchUpId:t,shouldBeAfter:e})=>{const n=m(t),r=M(e.map(m));return a[s]||(a[s]={}),a[s][n]||(a[s][n]=[]),r.forEach(t=>{a[s][n].includes(t)||a[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:o,profileIssues:u,roundIndexShouldBeAfter:a,...Y}}function QA(t){const{tournamentRecords:e,requestType:n}=t,r=fu(t,[{[hc]:!0}]);if(r.error)return r;const i={};for(const t of Object.values(e)){const{extension:e}=td({element:t,name:Sd}),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,...Y}}function JA(t){const{containerStructureId:e,roundSegment:n,isRoundRobin:r,tournamentId:i,roundNumber:o,structureId:a,eventId:s,drawId:c}=t,u=r?e:a,d=[i,s,c,u,o].join("|");return Ei({structureId:u,roundSegment:n,tournamentId:i,roundNumber:o,eventId:s,drawId:c,id:d})}function XA({round:t,matchUps:e,events:n,tournamentRecords:r}){const i=n.find(e=>e.eventId===t.eventId),{eventType:o,category:a,categoryType:s}=i??{},{categoryName:c,ageCategoryCode:u}=a??{},d=C(e.map(({matchUpFormat:t})=>t));let p=0;return Object.keys(d).forEach(e=>{const n=d[e],i=jA({categoryName:c||u,tournamentId:t.tournamentId,eventId:t.eventId,tournamentRecords:r,matchUpFormat:e,categoryType:s,eventType:o});if(i.error)return i;const a=i.averageMinutes*n;isNaN(p)||(p+=a)}),{roundMinutes:p}}function ZA(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||_p.includes(e)).length||0,i=t.filter(({schedule:t,matchUpStatus:e})=>t?.scheduledDate&&t?.scheduledTime&&e!==Sp).length||0,o=e-n;return{unscheduledCount:o-i,incompleteCount:o-i,scheduledCount:i,completedCount:r,matchUpsCount:e,isScheduled:o===i,isComplete:o===r,byeCount:n}}function tE({tournamentRecords:t,schedulingProfile:e,tournamentRecord:n,withRoundId:r}){if(n&&!t){if("object"!=typeof n)return{error:it};t={[n.tournamentId]:n}}if(e){const n=$A({tournamentRecords:t,schedulingProfile:e});if(n.error)return n}if(!e&&t){const n=HA({tournamentRecords:t});if(n.error)return n;e=n.schedulingProfile}if(!e)return{error:mr};const i={};return{profileRounds:e.map(({venues:t,scheduleDate:e})=>t.map(({rounds:t})=>t.map(t=>{const n=JA(t);return n.roundSegment?.segmentsCount&&(i[n.id]=n.roundSegment.segmentsCount),Ei({id:r?n.id:void 0,scheduleDate:e,...n})}))).flat(1/0),segmentedRounds:i}}function eE({court:t,date:e}){const n=e&&t.dateAvailability?.find(t=>Ko(t.date,e)),r=t.dateAvailability?.find(t=>!t.date);return n||r}function nE({courtPrefix:t="C|",minRowsCount:e,courtsData:n,scheduledDate:r}){if(!Array.isArray(n))return{error:sr};const i=n?.reduce((t,e)=>{const n=e.matchUps??[],r=Math.max(0,...n.map(t=>t.schedule.courtOrder||0));return Math.max(r,t)},1),o=L(0,Math.max(e||0,i)).map(t=>({matchUps:L(0,n.length).map(e=>{const i=n[e],{courtId:o,venueId:a}=i;if(r){const{gridBookings:e}=function({court:t,date:e}){const n=eE({court:t,date:e}),r=new Map,i=[];return(n?.bookings??[]).forEach(t=>{if("number"==typeof t.courtOrder){const e=t.rowCount||1;for(let n=0;n<e;n++)r.set(t.courtOrder+n,t)}else i.push(t)}),{gridBookings:r,timeBookings:i}}({court:i,date:r});if(e.has(t+1)){const n=e.get(t+1);return{schedule:{courtOrder:t+1,venueId:a,courtId:o},isBlocked:!0,booking:n}}}return{schedule:{courtOrder:t+1,venueId:a,courtId:o}}})}));return n.forEach((t,e)=>{for(const n of t.matchUps){const t=n.schedule?.courtOrder;t&&(o[t-1].matchUps[e]=n)}}),{courtPrefix:t,rows:o.map((e,n)=>Object.assign({rowId:`rowId-${n+1}`},...e.matchUps.map((e,n)=>({[`${t}${n}`]:e}))))}}var rE={__proto__:null,courtGridRows:nE,findVenue:Ig,getMatchUpsToSchedule:GA,getPersonRequests:QA,getProfileRounds:tE,getScheduledRoundsDetails:qA,getSchedulingProfile:HA,getSchedulingProfileIssues:KA,publicFindCourt:vg};function iE({policyDefinitions:t,drawDefinition:e,drawSize:n,drawId:r,event:i,stage:o}){if(!i)return{error:Ht};const{entries:a,stageEntries:s}=vy({drawDefinition:e,drawId:r,stage:o,event:i}),c=s.length,{drawSize:u}=bD({participantsCount:c}),d=ND({drawSize:n??u,participantsCount:c,policyDefinitions:t});if(d.error)return Ci({result:d,stack:"getEntriesAndSeedsCount"});const{seedsCount:p}=d;return{entries:a,seedsCount:p,stageEntries:s}}function oE(t){const{entries:e=[],entryStatus:n,stage:r}=t;return Math.max(...e.filter(t=>!(r&&r!==t.entryStage||n&&t.entryStatus!==n||isNaN(t.entryPosition))).map(({entryPosition:t})=>p(t||0)),0)}var aE={__proto__:null,getEntriesAndSeedsCount:iE,getMaxEntryPosition:oE};function sE({tournamentRecords:t,extensionName:e}){if("object"!=typeof t||!Object.keys(t).length)return{error:nt};const n=[];let r;for(const i of Object.values(t)){const{extension:t}=td({element:i,name:e});t&&!r&&(n.push({params:{extension:t,discover:!0},method:"addExtension"}),r=!0);const o=i.events??[];for(const t of o){const{eventId:r}=t,{extension:i}=td({name:e,element:t});i&&n.push({params:{eventId:r,extension:i},method:"addEventExtension"})}}return{methods:n}}function cE({tournamentRecords:t}){return sE({extensionName:Td,tournamentRecords:t})}function uE({tournamentRecord:t,matchUpFormats:e,categoryType:n,event:r}){if(!r)return{error:Ht};let i,o;if(e?.length){const t=[];i=e.map(e=>{const n="string"==typeof e?{matchUpFormat:e}:e;if(!t.includes(n?.matchUpFormat)&&Io({matchUpFormat:n?.matchUpFormat}))return t.push(n.matchUpFormat),n}).filter(Boolean)}else{const{policy:e}=Qm({policyType:Fu,tournamentRecord:t,event:r});if(e?.matchUpFormats)i=e?.matchUpFormats;else{const{extension:t}=td({name:Td,element:r});let e,n;({matchUpAverageTimes:e,matchUpRecoveryTimes:n}=t?.value?t.value:kh[Ou]),i=M([...(e??[]).map(t=>t.matchUpFormatCodes),...(n??[]).map(t=>t.matchUpFormatCodes)].flat()).map(t=>({matchUpFormat:t})),o="default scheduling policy in use"}}const{eventType:a,eventId:s,category:c}=r,u=c?.categoryName??c?.ageCategoryCode??s;if(!s)return{error:Ht};const d=i.map(({matchUpFormat:e,description:i})=>({matchUpFormat:e,description:i,...Jh({tournamentRecord:t,matchUpFormat:e,categoryName:u,categoryType:n,eventType:a,event:r})}));return Ei({eventMatchUpFormatTiming:d,info:o})}function dE(t){const e=fu(t,[{[Ic]:!0},{[ou]:t=>Io({matchUpFormat:t}),[su]:oe,[Uc]:!0}]);if(e.error)return e;const{tournamentRecord:n,matchUpFormat:r,event:i}=t,{extension:o}=td({name:Td,element:i}),a=o?.value,s=Km({element:n,groupAttribute:"scheduling",leafAttribute:"timing",name:Td}),c=[a?.matchUpAverageTimes&&Nh({...a,matchUpFormat:r}),s?.matchUpAverageTimes&&Nh({...s,matchUpFormat:r})].find(t=>t);return{matchUpFormat:r,recoveryTimes:[a?.matchUpRecoveryTimes&&Mh({...a,matchUpFormat:r}),s?.matchUpRecoveryTimes&&Mh({...s,matchUpFormat:r})].find(t=>t),averageTimes:c}}const pE=Hm[Du].predictionModel;function lE({tournamentRecord:t,predictionModel:e,side1Rating:n,side2Rating:r}){if("number"!=typeof n||"number"!=typeof r)return{competitive:0,decisive:0,routine:0,error:sr};const i=function(t,e){if(t)return t;if(e){const{policy:t}=Qm({policyType:Du,tournamentRecord:e});if(t?.predictionModel)return t.predictionModel}return pE}(e,t),o=Math.abs(n-r);return{...nw(o,i),delta:o}}const mE=({scheduleAttributes:t=["scheduledDate","scheduledTime"],schedule:e={}})=>!!Object.keys(e).filter(e=>t.includes(e)).filter(t=>e[t]).length;function fE({scheduleAttributes:t=["scheduledDate","scheduledTime"],matchUps:e=[]}){if(!Lf(e))return{error:Ie};if(!Array.isArray(t))return{error:sr};const n=e.filter(Boolean).filter(({schedule:e})=>mE({schedule:e,scheduleAttributes:t})).reduce((t,e)=>{const{schedule:n}=e,r=Lo(n?.scheduledDate),i=_o(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)=>jo(_o(t.schedule?.scheduledTime),_o(e.schedule?.scheduledTime)))}),{...Y,scheduledMatchUps:n}}function hE({tournamentRecords:t}){return sE({extensionName:Pd,tournamentRecords:t})}function gE({schedulingProfile:t,matchUps:e=[]}){const n={},r=({eventId:t,drawId:e,structureId:n,roundNumber:r})=>`${t}|${e}|${n}${r}`;if(t?.length){t.flatMap(({venues:t})=>t.map(({rounds:t})=>t)).forEach(t=>{t.sort((t,e)=>(t.sortOrder||0)-(e.sortOrder||0)).forEach(({eventId:t,drawId:e,structureId:i,roundNumber:o},a)=>{const s=r({eventId:t,drawId:e,structureId:i,roundNumber:o});n[s]=a})})}const i=[],o={noScheduledDate:[]};for(const t of e){const e=t.schedule??{},n=e.scheduledDate&&Lo(e.scheduledDate)||e.scheduledTime&&Lo(e.scheduledTime)||"noScheduledDate";o[n]||(o[n]=[]),o[n].push(t)}const a=Object.keys(o).sort((t,e)=>t.localeCompare(e));for(const t of a){const e=o[t],a={noScheduledTime:[]};for(const t of e){const e=t.schedule??{},n=e.scheduledTime&&_o(e.scheduledTime)||"noScheduledTime";a[n]||(a[n]=[]),a[n].push(t)}for(const t of Object.keys(a)){const e=a[t].sort((t,e)=>(t.roundNumber||0)-(e.roundNumber||0));a[t]=e}const s=Object.keys(a).sort((t,e)=>t.localeCompare(e));for(const t of s){const e=a[t];e.sort((t,e)=>(n[r(t)]||0)-(n[r(e)]||0)),i.push(...e)}}return i}function IE(t){let{participants:e,contextContent:n,participantMap:r}=t;const{tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,participantsProfile:a,afterRecoveryTimes:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:d,usePublishState:p,contextFilters:l,matchUpFilters:m,contextProfile:f,nextMatchUps:h,tournamentId:g,inContext:I,context:S,event:y}=t;if(!y)return{error:Ht};const{eventId:v,eventName:U,endDate:P,eventType:T,category:w,gender:D}=y??{},R={...S,...Ei({surfaceCategory:y.surfaceCategory??d?.surfaceCategory,indoorOutDoor:y.indoorOutdoor??d?.indoorOutdoor,tournamentId:g??d?.tournamentId,endDate:P??d?.endDate,eventName:U,eventType:T,category:w,eventId:v,gender:D})};let b;!e&&d&&({participants:e,participantMap:r,groupInfo:b}=Bm({participantsProfile:a,useParticipantMap:u,tournamentRecord:d,contextProfile:f,inContext:I})),f&&!n&&(n=zm({policyDefinitions:c,tournamentRecord:d,contextProfile:f,event:y}));const N=pS({event:y});return{...(y.drawDefinitions??[]).reduce((u,g)=>{const S=Yg({hydrateParticipants:t.hydrateParticipants,context:R,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,participantsProfile:a,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:d,usePublishState:p,contextContent:n,contextFilters:l,matchUpFilters:m,participantMap:r,publishStatus:N,contextProfile:f,drawDefinition:g,nextMatchUps:h,inContext:I,event:y}),v=Object.keys(S);return v?.forEach(t=>{Array.isArray(S[t])&&(u[t]||(u[t]=[]),u[t]=u[t].concat(S[t]))}),u},{}),...Y,groupInfo:b}}function SE(t){if(!t?.tournamentRecord)return{error:rt};let e=t.contextContent;const{scheduleVisibilityFilters:n,participantsProfile:r,afterRecoveryTimes:i,policyDefinitions:o,tournamentRecord:a,inContext:s=!0,usePublishState:c,contextFilters:u,matchUpFilters:d,contextProfile:p,nextMatchUps:l,context:m}=t,f=t.tournamentId??a.tournamentId,h=a?.events??[],{participants:g,participantMap:I,groupInfo:S}=Bm({participantsProfile:r,tournamentRecord:a,contextProfile:p,inContext:s});p&&!e&&(e=zm({policyDefinitions:o,tournamentRecord:a,contextProfile:p}));const{appliedPolicies:y}=xd({tournamentRecord:a}),v=u?.eventIds??[];return{...h.filter(t=>!v.includes(t.eventId)).map(h=>{const S=Tg({event:h}).flightProfile,v={eventDrawsCount:S?.flights?.length||h.drawDefinitions?.length||0,...m};return IE({hydrateParticipants:t.hydrateParticipants,context:v,tournamentAppliedPolicies:y,scheduleVisibilityFilters:n,participantsProfile:r,afterRecoveryTimes:i,policyDefinitions:o,tournamentRecord:a,usePublishState:c,contextFilters:u,contextProfile:p,contextContent:e,matchUpFilters:d,participantMap:I,participants:g,tournamentId:f,nextMatchUps:l,inContext:s,event:h})}).reduce((t,e)=>{const n=e&&Object.keys(e).filter(t=>!["success","matchUpsMap"].includes(t));return n?.forEach(n=>{Array.isArray(e[n])&&(t[n]||(t[n]=[]),t[n]=t[n].concat(e[n]),void 0!==t.matchUpsCount?t.matchUpsCount+=e[n].length:t.matchUpsCount=e[n].length)}),t},{matchUpsCount:0}),groupInfo:S,participants:g}}function yE({scheduleVisibilityFilters:t,hydrateParticipants:e,participantsProfile:n,tournamentRecords:r,useParticipantMap:i,policyDefinitions:o,usePublishState:a,matchUpFilters:s,contextFilters:c,nextMatchUps:u,inContext:d}){if("object"!=typeof r||!Object.keys(r).length)return{error:nt};const p=Object.keys(r).map(i=>{const p=r[i];return SE({scheduleVisibilityFilters:t,hydrateParticipants:e,participantsProfile:n,policyDefinitions:o,tournamentRecord:p,usePublishState:a,matchUpFilters:s,contextFilters:c,nextMatchUps:u,inContext:d})}),l={},m={};return{...p.reduce((t,e)=>(Object.keys(e).forEach(n=>{if("groupInfo"===n)Object.assign(m,e[n]);else if("participants"===n)for(const t of e[n]??[])l[t.participantId]=t;else Array.isArray(e[n])&&(t[n]||(t[n]=[]),t[n]=t[n].concat(e[n]))}),t),{}),groupInfo:m,mappedParticipants:l}}function vE(t){if("object"!=typeof t?.tournamentRecords||!Object.keys(t?.tournamentRecords).length)return{error:nt};const{courts:e,venues:n}=gw(t),r=HA(t).schedulingProfile,{sortDateMatchUps:i=!0,courtCompletedMatchUps:o,alwaysReturnCompleted:a,activeTournamentId:s,tournamentRecords:c,withCourtGridRows:u,minCourtGridRows:d,usePublishState:p,status:l=Th,sortCourtsData:m}=t,h=s??yi()??Object.keys(c)[0],g=p?dS({tournamentRecord:c[h],status:l}):void 0,I=a?yE({...t,matchUpFilters:{...t.matchUpFilters,matchUpStatuses:[vp]},contextFilters:t.contextFilters}).completedMatchUps:[];if(p&&!Cg(g?.orderOfPlay))return{completedMatchUps:I,dateMatchUps:[],courtsData:[],venues:n};let S,y;p&&({drawIds:S,detailsMap:y}=function({tournamentRecords:t}){const e={},n=[];for(const r of Object.values(t))for(const t of r.events??[]){const r=pS({event:t}),i=r?.drawDetails;f(i)?(Object.assign(e,i),n.push(...Object.keys(i).filter(t=>lS({drawId:t,drawDetails:i})))):r?.drawIds?.length&&n.push(...r.drawIds)}return{drawIds:n,detailsMap:e}}({tournamentRecords:c})),S?.length&&(t.contextFilters??={},t.contextFilters.drawIds?t.contextFilters.drawIds=t.contextFilters.drawIds.filter(t=>S.includes(t)):t.contextFilters.drawIds=S);const v=g?.orderOfPlay;!function(t,e){if(!e?.eventIds?.length)return;t.matchUpFilters??={},t.matchUpFilters?.eventIds&&t.matchUpFilters.eventIds.length?t.matchUpFilters.eventIds=t.matchUpFilters.eventIds.filter(t=>e.eventIds.includes(t)):t.matchUpFilters.eventIds=e.eventIds}(t,v);const U=function(t,e,{allCompletedMatchUps:n,alwaysReturnCompleted:r,venues:i}){if(!e?.scheduledDates?.length)return;t.matchUpFilters??={},t.matchUpFilters.scheduledDate&&!t.matchUpFilters.scheduledDates&&(t.matchUpFilters.scheduledDates=[t.matchUpFilters.scheduledDate]);const o=t.matchUpFilters.scheduledDates&&t.matchUpFilters.scheduledDates.length>0;t.matchUpFilters.scheduledDates&&t.matchUpFilters.scheduledDates.length?t.matchUpFilters.scheduledDates=t.matchUpFilters.scheduledDates.filter(t=>e.scheduledDates.includes(t)):t.matchUpFilters.scheduledDates=e.scheduledDates;if(o&&!t.matchUpFilters.scheduledDates?.length)return{completedMatchUps:r?n:[],dateMatchUps:[],courtsData:[],venues:i,...Y};return void delete t.matchUpFilters.scheduledDate}(t,v,{allCompletedMatchUps:I,alwaysReturnCompleted:a,venues:n});if(U)return U;!function(t,e){if(!e)return;t.matchUpFilters??={},t.matchUpFilters?.excludeMatchUpStatuses?.length?t.matchUpFilters.excludeMatchUpStatuses.includes(vp)||t.matchUpFilters.excludeMatchUpStatuses.push(vp):t.matchUpFilters.excludeMatchUpStatuses=[vp]}(t,a);const{completedMatchUps:P,upcomingMatchUps:T,pendingMatchUps:w,abandonedMatchUps:D,groupInfo:b,mappedParticipants:N}=yE({...t,matchUpFilters:t.matchUpFilters,contextFilters:t.contextFilters});let M=[...T??[],...w??[]];!y||S?.length&&!Object.keys(y).length||(M=M.filter(t=>function(t,e){const{drawId:n,structureId:r,stage:i}=t;if(!Cg(e?.[n]?.publishingDetail))return!1;const o=Object.keys(e[n].stageDetails??{});if(o.length){const t=o.filter(t=>!Cg(e[n].stageDetails[t])),r=o.filter(t=>Cg(e[n].stageDetails[t]));return(!t.length||!t.includes(i))&&(!(!r.length||!r.includes(i))||t.length&&!t.includes(i)&&!r.length)}const a=Object.keys(e[n].structureDetails??{});if(a.length){const t=a.filter(t=>!Cg(e[n].structureDetails[t])),i=a.filter(t=>Cg(e[n].structureDetails[t]));return(!t.length||!t.includes(r))&&(!(!i.length||!i.includes(r))||t.length&&!t.includes(r)&&!i.length)}return!0}(t,y))),y&&p&&(M=M.filter(t=>function(t,e){const{drawId:n,structureId:r,roundNumber:i}=t;if(!R(i))return!0;const o=e[n]?.structureDetails?.[r];if(!o)return!0;const{scheduledRounds:a,roundLimit:s}=o;if(R(s)&&i>s)return!1;if(a){const e=a[i];if(!e)return!0;if(!e.published)return!1;if(Eg(e))return t.schedule=void 0,!0}return!0}(t,y)));const A=i?gE({matchUps:M,schedulingProfile:r}):M,E=e?.map(t=>{const e=function({courtId:t}){const e=(o?A.concat(P??[],D??[]):A).filter(e=>e.schedule?.courtId===t||e.schedule?.allocatedCourts?.map(({courtId:t})=>t).includes(t));return m?gE({matchUps:e,schedulingProfile:r}):e}(t);return{surfaceCategory:t?.surfaceCategory??"",matchUps:e,...t}}),C={completedMatchUps:a?I:P,mappedParticipants:t.hydrateParticipants?void 0:N,dateMatchUps:A,courtsData:E,groupInfo:b,venues:n};if(u){const e=t.matchUpFilters?.scheduledDate,n=A.filter(t=>!t.schedule?.courtId&&!t.schedule?.allocatedCourts?.length).length,{rows:r,courtPrefix:i}=nE({minRowsCount:Math.max(d||0,n),scheduledDate:e,courtsData:E});C.courtPrefix=i,C.rows=r}return{...C,...Y}}function UE(t,e){if(!f(t))return{error:sr};if(!Array.isArray(e))return{error:sr};const n={};for(const{param:r,error:i,attr:o}of e){const e=PE({params:t,param:r,attr:o,error:i});if(e?.error)return e;n[r]=e}return n}function PE({params:t,param:e,attr:n,error:r}){if(e===_c&&f(t.drawDefinition)&&m(t.structureId)){const e=(t.drawDefinition.structures??[]).find(({structureId:e})=>e===t.structureId);return!e.length&&r?{error:r}:{structure:e}}if(e===Wc){const e=OA({...t,...n});return e.error&&r?{...e,error:r}:e}return{error:mr,info:{param:e}}}function TE(t){const{structureId:e,matchUpId:n,event:r}=t;let i=t.drawDefinition;const o=fu(t,[{[Ic]:!0},{[uu]:{[bc]:!1,[kc]:!1,[$c]:!1,[zc]:!1}}]);if(o[Hc])return o;const a=UE(t,[{[Yc]:Wc,[Hc]:Ae}]),s=a?.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:bt};const t=ol({drawDefinition:i,structureId:e});if(t.error)return t;c=t.structure}const u=c?.competitionFormat,d=i?.competitionFormat,p=r?.competitionFormat,l=u||d||p;return{...Y,structureDefaultCompetitionFormat:u,drawDefaultCompetitionFormat:d,eventDefaultCompetitionFormat:p,competitionFormat:l}}function wE({tournamentRecords:t,tournamentId:e}){if("object"!=typeof t||!Object.keys(t).length)return{error:nt};let n;return Object.keys(t).filter(t=>!e||t===e).forEach(e=>{const r=t[e],{matchUpDailyLimits:i}=function(t){const e=fu(t,[{[Ic]:!0}]);if(e.error)return e;const{tournamentRecord:n}=t,{policy:r}=Qm({policyType:Ou,tournamentRecord:n}),i=Km({element:n,groupAttribute:"scheduling",leafAttribute:"dailyLimits",name:Pd}),o=i?.dailyLimits,a=r?.defaultDailyLimits;return{matchUpDailyLimits:o||a}}({tournamentRecord:r});n=i}),{matchUpDailyLimits:n}}function DE(t){let{matchUps:e}=t;const{singlesForDoubles:r,tournamentRecord:o,drawDefinition:a,excludeMargin:s,exclusionRule:c,zoneDoubling:u,matchUpType:d,scaleName:p,eventId:l,zonePct:m,drawId:f,event:h}=t;if(!o&&!e)return{error:rt};if(d&&![n,i].includes(d))return{error:sr,info:{matchUpType:d}};if(e&&!Lf(e))return{error:sr,context:{matchUps:e}};const g=rp[p],I=g?.ascending??t.ascending??!1,S=g?.accessor??t.valueAccessor,y=Array.isArray(g?.range)?Math.abs(g.range[0]-g.range[1]):0,v=R(m)&&y?(m??0)*y:t.zoneMargin??y,U={withScaleValues:!0,withCompetitiveness:!0},P={matchUpTypes:d?[d]:[n,i]},T=o?.participants;e?.[0]?.hasContext?f?e=e.filter(t=>t.drawId===f):l&&(e=e.filter(t=>t.eventId===l)):e??=f&&!a&&[]||!f&&l&&!h&&[]||f&&Zg({inContext:!0,drawDefinition:a,contextFilters:P,contextProfile:U,participants:T})?.matchUps||!f&&l&&Kg({inContext:!0,contextFilters:P,contextProfile:U,participants:T,event:h})?.matchUps||Qg({tournamentRecord:o,contextFilters:P,contextProfile:U})?.matchUps||[],d&&(e=e.filter(t=>t.matchUpType===d));const w=e.filter(({winningSide:t,score:e,sides:n,matchUpStatus:r})=>![Np,Pp,Ep,Up,gp].includes(r??"")&&aI({score:e})&&2===n?.length&&t),D=function({excludeMargin:t,exclusionRule:e,valueAccessor:n,ascending:r,scaleName:i,matchUps:o}){const a={affirmative:[],negative:[],excluded:[]};for(const s of o)NE({matchUp:s,accuracy:a,excludeMargin:t,exclusionRule:e,valueAccessor:n,ascending:r,scaleName:i});const s=a.affirmative.length+a.negative.length,c=s&&a.affirmative.length/s*100;return a.percent=c?Math.round(100*c)/100:0,a}({matchUps:w,excludeMargin:s,exclusionRule:c,valueAccessor:S,ascending:I,scaleName:p}),b=!u||bh(n)(d)?v:2*(v||0),N=v?w.map(({competitiveProfile:t,matchUpType:e,score:n,sides:i})=>{const o=RE({singlesForDoubles:r,valueAccessor:S,matchUpType:e,scaleName:p,sides:i}),a=Math.abs(o[0].value-o[1].value);return{competitiveness:t?.competitiveness,valuesGap:a,score:n}}).filter(({valuesGap:t})=>t<=b):[],M=function({zoneData:t}){const e={[jm]:[],[qm]:[],[Wm]:[]};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:N}),A=M&&Object.values(M).flat().length,E=A&&Object.assign({},...Object.keys(M).map(t=>({[t]:Math.round(1e4*M[t].length/A)/100}))),C=w.length-(N?.length||0);return{...Y,relevantMatchUps:w,zoneDistribution:E,zoneData:N,accuracy:D,nonZone:C}}function RE({singlesForDoubles:t,exclusionRule:e,valueAccessor:n,matchUpType:r,scaleName:i,sides:o}){const a=e?.range.slice().sort((t,e)=>t-e),s=t=>{const n=t?.[e?.valueAccessor];return{exclude:e&&n>=a[0]&&n<=a[1],exclusionValue:n}};return o.sort((t,e)=>t.sideNumber-e.sideNumber).map(({participant:e})=>{const o=[],a=e?.individualParticipants;if(a?.length){const c=[];let u=0;for(const e of a){const{scaleValue:a,value:d}=bE({singlesForDoubles:t,valueAccessor:n,participant:e,matchUpType:r,scaleName:i}),{exclude:p,exclusionValue:l}=s(a);p&&o.push(l),c.push(a),d&&!Number.isNaN(Number(u))?u+=d:u=void 0}return{participantName:e.participantName,exclusionValues:o,scaleValues:c,value:u}}if(e){const{scaleValue:a,value:c}=bE({singlesForDoubles:t,valueAccessor:n,matchUpType:r,participant:e,scaleName:i}),{exclude:u,exclusionValue:d}=s(a);return u&&o.push(d),{participantName:e.participantName,exclusionValues:o,scaleValue:a,value:c}}return{}})}function bE({singlesForDoubles:t,valueAccessor:e,matchUpType:r,participant:i,scaleName:o}){const a=t?n:r,s=i?.rankings?.[a]?.find(t=>t.scaleName===o),c=i?.ratings?.[a]?.find(t=>t.scaleName===o),u=(c||s)?.scaleValue;return{scaleValue:u,value:e?u?.[e]:u}}function NE({matchUp:t,accuracy:e,excludeMargin:n,exclusionRule:r,valueAccessor:i,ascending:o,scaleName:a}){const{matchUpType:s,sides:c,score:u,winningSide:d}=t;if(!d)return;if(r&&(!r.valueAccessor||!r.range))return void(e.error={info:"exclusionRule requires valueAccessor and range",error:Ae});const p=d-1,l=RE({exclusionRule:r,valueAccessor:i,matchUpType:s,scaleName:a,sides:c});if(function({exclusionRule:t,sideValues:e,accuracy:n,score:r,winningSide:i}){if(t){const t=e.flatMap(({exclusionValues:t})=>t);if(t.length)return n.excluded.push({scoreString:r?.scoreStringSide1,exclusionValues:t,winningSide:i,sideValues:e}),!0}return!1}({exclusionRule:r,sideValues:l,accuracy:e,score:u,winningSide:d}))return;if(function(t){return t.filter(t=>![void 0,"",null].includes(t.value)).length<2}(l))return void e.excluded.push({scoreString:u?.scoreStringSide1,missingValues:!0,winningSide:d,sideValues:l});const m=l[p].value-l[1-p].value;if(function({excludeMargin:t,valuesGap:e}){const n=Number.parseFloat(t||0);return n&&Math.abs(e)<n}({excludeMargin:n,valuesGap:m}))return void e.excluded.push({scoreString:u?.scoreStringSide1,excludeMargin:n,winningSide:d,excludeGap:!0,sideValues:l,valuesGap:m});const f=o?-m:m,h=1===d?u?.scoreStringSide1:u?.scoreStringSide2;f>0?e.affirmative.push({winningScoreString:h,winningSide:d,sideValues:l,valuesGap:m,score:u}):e.negative.push({winningScoreString:h,winningSide:d,sideValues:l,valuesGap:m,score:u})}function ME({matchUps:t,matchUpId:e}){if(!Lf(t))return{error:sr};const n=t.find(t=>t.matchUpId===e),{drawId:r,eventId:i,structureId:o,tournamentId:a}=n??{};return{matchUpId:e,drawId:r,eventId:i,structureId:o,tournamentId:a}}function AE(t){const{timeStamp:e,schedule:n,matchUp:r}=t,i=fu(t,[{[Wc]:!0}]);if(i.error)return i;const{itemValue:o,timeStamp:a}=tg({timeItems:r?.timeItems??[],itemType:ih});return!n||a&&e&&new Date(a).getTime()>new Date(e).getTime()?{homeParticipantId:o}:n}function EE({collectionDefinitions:t=[],collectionGroups:e=[]}){let n=0;const{groupValueNumbers:r}=cT({collectionGroups:e});let i;for(const e of t??[]){const{collectionValueProfiles:t,collectionGroupNumber:o,collectionValue:a,matchUpCount:s,matchUpValue:c,scoreValue:u,setValue:d}=e,p=o&&r.includes(o);if(R(d||u))i=!0;else{if(p)continue;if("number"==typeof a&&R(a))n+=a;else if(Array.isArray(t)&&t?.length)for(const e of t)n+=e.matchUpValue;else"number"==typeof c&&R(c)&&(n+=(s??0)*c)}}for(const t of e)n+=t.groupValue??0;if(i||!n)return{aggregateValue:!0,...Y};return{valueGoal:Math.floor(n/2)+1,...Y}}function CE(t){const{structureId:e,matchUpId:n,event:r}=t;let i=t.drawDefinition;const o=fu(t,[{[Ic]:!0},{[uu]:{[bc]:!1,[kc]:!1,[$c]:!1,[zc]:!1}}]);if(o[Hc])return o;const a=UE(t,[{[Yc]:Wc,[Hc]:Ae}]),s=a?.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:bt};const t=ol({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 OE({profileBands:t,tournamentRecord:e,matchUps:n}){if(!Lf(n))return{error:Ie};const r=!t&&Qm({policyType:Du,tournamentRecord:e}).policy,i=t||r?.profileBands||Hm[Du].profileBands,o=n.filter(({winningSide:t})=>t),a=o.filter(({matchUpStatus:t})=>t===Ep||t===Pp).length,s=o.map(Cf),c=kf(s).reduce((t,e)=>((t,e)=>(t[Ef(e,i)]+=1,t))(t,e),{[jm]:0,[qm]:0,[Wm]:0,[Vm]:a}),u=Object.keys(c).reduce((t,e)=>(c[e]||0)+t,0),d=Object.keys(c).map(t=>{const e=Number.parseFloat((c[t]/u).toFixed(4));return{[t]:100*e}}),p=o.filter(({matchUpStatus:t})=>t===Gm).length;return d.push({[Gm]:100*Number.parseFloat((p/u).toFixed(4))}),{competitiveBands:Object.assign({},...d),...Y}}const{stageOrder:kE}=fc;function FE(t,e){return t.eventName.localeCompare(e.eventName)||t.eventId.localeCompare(e.eventId)||(kE[t?.stage]||0)-(kE[e?.stage]||0)||e.matchUpsCount-t.matchUpsCount||`${t.stageSequence}-${t.roundNumber}-${t.minFinishingSum}`.localeCompare(`${e.stageSequence}-${e.roundNumber}-${e.minFinishingSum}`)}function xE({excludeScheduleDateProfileRounds:t,excludeScheduledRounds:e,excludeCompletedRounds:n,inContextMatchUps:r,tournamentRecords:i,schedulingProfile:o,tournamentRecord:a,withSplitRounds:s,matchUpFilters:c,scheduleDate:u,withRoundId:d,venueId:p,context:l}){if(r&&!Array.isArray(r||"object"!=typeof r[0]))return{error:sr,inContextMatchUps:r};if(a&&!i){if("object"!=typeof a)return{error:it};i={[a.tournamentId]:a}}const m="object"!=typeof i||!Object.keys(i).length;if((p||u||!r||!o&&(t||n||o||s))&&m)return{error:nt};const f=Object.assign({},...Object.values(i??{}).map(({venues:t=[],tournamentId:e})=>({[e]:t?.map(({venueId:t})=>t)}))),h=Object.values(i??{}).flatMap(({events:t=[],tournamentId:e,startDate:n,endDate:r})=>t.map(t=>({...t,validVenueIds:f[e],startDate:t.startDate??n,endDate:t.endDate??r}))),{segmentedRounds:g,profileRounds:I}=i&&(t||n||o||s)&&tE({tournamentRecords:i,schedulingProfile:o})||{},S=t&&Object.assign({},...I.map(t=>({[t.id]:t}))),y=r||i&&Jg({tournamentRecords:i,matchUpFilters:c})?.matchUps||[],v=[],U=y&&Object.values(y.reduce((t,e)=>{const n=JA(e).id,r=g?.[n],i=[...t[n]?.matchUps??[],e],{containerStructureId:o,stageSequence:a,structureName:s,tournamentId:c,isRoundRobin:u,matchUpType:p,roundNumber:l,roundOffset:m,structureId:f,eventName:h,roundName:I,drawName:S,eventId:y,drawId:v}=e,U=u?o:f;return{...t,[n]:{id:d?n:void 0,structureId:U,stageSequence:a,segmentsCount:r,structureName:s,tournamentId:c,matchUpType:p,roundNumber:l,roundOffset:m,eventName:h,roundName:I,drawName:S,matchUps:i,eventId:y,drawId:v}}},{})).flatMap(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 o=t.matchUps.length/r;return q(t.matchUps.sort((t,e)=>t.roundPosition-e.roundPosition),o).map((o,a)=>{const{unscheduledCount:s,incompleteCount:c,matchUpsCount:u,isScheduled:d,isComplete:p,byeCount:m}=ZA(o),f=XA({matchUps:t.matchUps,tournamentRecords:i,events:h,round:t});return Ei({...t,...l,roundSegment:{segmentsCount:r,segmentNumber:a+1},winnerFinishingPositionRange:n,unscheduledCount:s,incompleteCount:c,minFinishingSum:e,matchUpsCount:u,isScheduled:d,roundTiming:f,isComplete:p,byeCount:m,matchUps:o})})}const{unscheduledCount:o,incompleteCount:a,matchUpsCount:s,isScheduled:c,isComplete:u,byeCount:d}=ZA(t.matchUps),p=XA({matchUps:t.matchUps,tournamentRecords:i,events:h,round:t});return Ei({...t,...l,winnerFinishingPositionRange:n,unscheduledCount:o,incompleteCount:a,minFinishingSum:e,matchUpsCount:s,isScheduled:c,roundTiming:p,isComplete:u,byeCount:d})}).filter(r=>{if(t){const e=Lo(t),n=d?r.id:JA(r).id;if(e&&S[n]&&Lo(S[n].scheduleDate)===e)return!1}const{isComplete:i,isScheduled:o}=r,s=!n||!i,c=!e||!o,l=p||u?h?.find(({eventId:t})=>t===r.eventId):void 0,m=l?.startDate??a?.startDate,f=l?.endDate??a?.endDate,g=!u||!m||new Date(u)>=new Date(m),I=!u||!f||new Date(u)<=new Date(f),y=g&&I,U=!p||l?.validVenueIds.includes(p),P=s&&c&&U&&y;return P||v.push(r),P}).sort(FE)||[];return{...Y,rounds:U,excludedRounds:v}}function _E({participants:t,tournamentAppliedPolicies:e,scheduleVisibilityFilters:n,participantsProfile:r,afterRecoveryTimes:i,policyDefinitions:o,useParticipantMap:a,tournamentRecord:s,usePublishState:c,contextFilters:u,contextContent:d,matchUpFilters:p,participantMap:l,publishStatus:m,contextProfile:f,drawDefinition:h,nextMatchUps:g,tournamentId:I,inContext:S,context:y,event:v}){const{eventId:U,eventName:P,endDate:T,eventType:w,category:D,gender:R}=v??{},b={...y,...Ei({surfaceCategory:v?.surfaceCategory??s?.surfaceCategory,indoorOutDoor:v?.indoorOutdoor??s?.indoorOutdoor,endDate:T??v?.endDate??s?.endDate,tournamentId:I??s?.tournamentId,eventName:P,eventType:w,category:D,eventId:U,gender:R})};let N;!t?.length&&s&&({participants:t,participantMap:l,groupInfo:N}=Bm({participantsProfile:r,useParticipantMap:a,tournamentRecord:s,contextProfile:f,inContext:S})),v&&f&&!d&&(d=zm({policyDefinitions:o,tournamentRecord:s,contextProfile:f,drawDefinition:h,event:v}));return{...Yg({context:b,tournamentAppliedPolicies:e,scheduleVisibilityFilters:n,tournamentParticipants:t,participantsProfile:r,afterRecoveryTimes:i,policyDefinitions:o,tournamentRecord:s,usePublishState:c,participantMap:l,contextContent:d,contextFilters:u,matchUpFilters:p,publishStatus:m,contextProfile:f,drawDefinition:h,nextMatchUps:g,inContext:S,event:v}),groupInfo:N}}function LE(t){const{matchUp:e,sideNumber:n,setNumber:r,isTiebreakValue:i,isPointValue:o}=t??{};let{matchUpFormat:a}=t??{};if(!e)return{error:Se};a=a||e?.matchUpFormat;const s=co(a),c=!!e?.winningSide,u=e.score?.sets,d=u?.length,p=r&&r-1,l=!!u?.find((t,e)=>t.setNumber===r&&e===p),m=u?.filter(t=>t?.winningSide)??[],f=m?.length||0,h=(r&&u?.slice(r))??[],g=!!(d&&r&&h?.reduce((t,e)=>(!e||!e.side1Score&&!e.side2Score&&!e.side1TiebreakScore&&!e.side2TiebreakScore&&!e.side1PointScore&&!e.side2PointScore)&&t,!0)),I=r<=d&&u.find(t=>t.setNumber===r),S=I&&iN({setObject:I,matchUpScoringFormat:s}),{isCompletedSet:y,sideGameScores:v,sideTiebreakScores:U}=S??{},P=!!(I&&!y&&g||r&&r===d+1&&!c),T=[1,2].includes(n),w=T?n-1:0,D=I&&T&&(!i&&!o&&void 0!==v[w]&&v[w]||i&&void 0!==U[w]&&U[w]),R=!!D,b=m?.map(t=>iN({setObject:t,matchUpScoringFormat:s}).isValidSetOutcome).reduce((t,e)=>t&&e,!0),N=m.reduce((t,e)=>{const{winningSide:n}=e;return t[n-1]++,t},[0,0]),M=e?.winningSide,A=M&&M-1,E=1-A,O=N[A],k=N[E],F=Math.max(...N),x=C(N)[F],{bestOf:_,exactly:L}=s??{},B=F===Math.ceil((_||L||1)/2)&&1===x&&N.indexOf(F)+1||void 0,V=O>k&&M===B;return{completedSetsHaveValidOutcomes:b,validMatchUpWinningSide:V,calculatedWinningSide:B,matchUpScoringFormat:s,validMatchUpOutcome:B&&b&&V,isLastSetWithValues:g,completedSetsCount:f,isCompletedMatchUp:c,isValidSideNumber:T,hasExistingValue:R,existingValue:D,isExistingSet:l,isActiveSet:P,...S}}function BE({tournamentRecord:t,venueId:e,venueIds:n}){if(!t)return{error:rt};return{courts:(t.venues??[]).filter(t=>e?t.venueId===e:!n||n.includes(t.venueId)).map(t=>{const{venueId:e}=t,n=ca(t.courts??[]);return n.forEach(t=>Object.assign(t,{venueId:e})),n}).flat()}}var VE={__proto__:null,getCompetitionVenues:Iw,getCourts:BE,getVenuesAndCourts:gw,publicFindVenue:Sg};function GE({tournamentRecord:t,event:e}){const n=dl({tournamentRecord:t,event:e},[Ic,zc]);if(n.error)return n;const r=e.entries??[],i=t.participants??[],o=e.category?.categoryName||e.category?.ageCategoryCode,{eventType:a}=e,s=new Set(r.map(t=>t.participantId));let c,u,d;return{entryScaleAttributes:i.filter(t=>s.has(t.participantId)).map(t=>{const{participantId:e,participantName:n,name:r}=t;let i={scaleType:Uh,eventType:a,scaleName:o};const s=Vd({participant:t,scaleAttributes:i})?.scaleItem?.scaleValue;i={scaleType:vh,eventType:a,scaleName:o};const p=Vd({participant:t,scaleAttributes:i})?.scaleItem?.scaleValue;i={scaleType:yh,eventType:a,scaleName:o};const l=Vd({participant:t,scaleAttributes:i})?.scaleItem?.scaleValue;return c=!(!c&&!s),u=!(!u&&!p),d=!(!d&&!l),{participantId:e,participantName:n||r,seed:s,ranking:p,rating:l}}),hasSeededParticipants:c,hasRankedParticipants:u,hasRatedParticipants:d}}function jE(t){return t.reduce((t,e)=>t+Number.parseFloat(e),0)}function qE(t){const e={};for(const n of Object.keys(t)){const r=t[n];if(!r.length)continue;const i=y(r)?.toFixed(2);e[n]={avg:Number.parseFloat((jE(r)/r.length).toFixed(2)),median:i?Number.parseFloat(i):void 0,max:Math.max(...r),min:Math.min(...r)}}return e}function WE(t,e,n){if(t?.ratings?.[e])for(const r of t?.ratings?.[e]??[]){const t=r.scaleName;n.ratings[t]||(n.ratings[t]=[]);const e=rp[t]?.accessor;if(e){const i=Number.parseFloat(r.scaleValue?.[e]);i&&n.ratings[t].push(i)}}if(t?.rankings?.[e])for(const r of t?.rankings?.[e]??[]){const t=r.scaleName;n.ranking[t]||(n.ranking[t]=[]),r.scaleValue&&n.ranking[t].push(r.scaleValue)}}function $E(t,e,n,r){for(const i of t.filter(Boolean)){const t=e?.[i]?.participant;if(t?.participantType===gm)WE(t,n,r);else for(const i of t?.individualParticipantIds??[]){const t=e?.[i]?.participant;WE(t,n,r)}}}function HE({tournamentRecord:t,withScaleValues:e,scaleEventType:n,inContext:r,eventIds:i,drawIds:o,context:a}){if(!t)return{error:rt};const{tournamentId:s}=t,c=(t.events??[]).filter(({eventId:t})=>!i||Array.isArray(i)&&i.includes(t)).map(t=>{const e=t.drawDefinitions?.map(el);if(o?.length&&!V(o,e).length)return;const n=ca(t);return r&&Object.assign(n,{tournamentId:s}),a&&Object.assign(n,a),n}).filter(Boolean),u=e?function({eventCopies:t,scaleEventType:e,tournamentRecord:n,drawIds:r}){const i={},o=xS({withScaleValues:!0,tournamentRecord:n}).participantMap;for(const n of t){const t=e??n.eventType,a=n.eventId;i[a]||(i[a]={ratingsStats:{},ratings:{},ranking:{},draws:{}}),$E((n.entries??[]).filter(({entryStatus:t})=>Sf.includes(t)).map(Xp),o,t,i[a]),i[a].ratingsStats=qE(i[a].ratings);const s=[],c=t=>r?.length&&r.includes(t)||s.includes(t);for(const e of n.drawDefinitions??[]){const n=e.drawId;if(c(n))continue;const r=bI({drawDefinition:e}).assignedParticipantIds??[];i[a].draws[n]||(i[a].draws[n]={ratingsStats:{},ratings:{},ranking:{}}),s.push(n),$E(r,o,t,i[a].draws[n])}const u=Tg({event:n}).flightProfile;for(const e of u?.flights??[]){const n=e.drawId;c(n)||$E(e.drawEntries.map(Xp),o,t,i[a].draws[n])}for(const t of s)i[a].draws[t].ratingsStats=qE(i[a].draws[t].ratings)}return i}({eventCopies:c,scaleEventType:n,tournamentRecord:t,drawIds:o}):{};return Ei({eventScaleValues:u,events:c,...Y})}function zE({tournamentRecord:t,drawDefinition:e,context:n,event:r}){const i=dl({tournamentRecord:t,event:r},[Ic,zc]);if(i.error)return i;const o=ca(r);n&&Object.assign(o,n);return Ei({drawDefinition:e&&o.drawDefinitions?.find(({drawId:t})=>e.drawId===t),event:o})}var YE={__proto__:null,addGoesTo:rI,allCompetitionMatchUps:Jg,allDrawMatchUps:Zg,allEventMatchUps:Kg,allPlayoffPositionsFilled:TU,allTournamentMatchUps:Qg,analyzeDraws:xT,analyzeMatchUp:LE,analyzeTournament:RA,bulkUpdatePublishedEventIds:xA,calculateMatchUpMargin:HP,calculateWinCriteria:EE,categoryCanContain:ta,checkMatchUpIsComplete:_g,checkValidEntries:MD,cleanExpiredMutationLocks:gM,compareTieFormats:AA,competitionScheduleMatchUps:vE,courtGridRows:nE,credits:function(){return"\n This project would not have been possible without the generous input and patience\n of tournament organizers and directors who worked with early versions of CourtHive/TMX.\n\n Thanks to Miro, Pavel, Ivan, Mladen, Zdenko, Antonia, Jakov, Kreso, Barry, Jeff, Bobby... to name just a few. \n\n The project would not have even begun without the support of Miro, or the introduction by Sretchko.\n The project would not have succeeded without the enthusiasm of Randy and Bruce.\n Thanks to serendipity and Luca and the ensuing TODS conversations with ITF.\n Thanks to Scott and Jake for sanity checks, suggestions, and camaraderie.\n Thanks to Zoran for inspiring the async support and getting into the weeds with subscriptions.\n Thanks to Dave for backing the conversion of TMX 1.x source into the factory repository.\n Thanks to Vuk and Pavle and Rich and Chris and Deepa for the direct engagement with the APIs.\n Thanks to Joe for repeatedly challenging me and the many pointers to useful tooling.\n Thanks to Shannon for the validation of the approach from his deep domain experience.\n Thanks to Nikola for the ongoing camaraderie and explorations of what we can do with TODS.\n\n And a special thanks to my family for putting up with the long days and weeks and months of coding\n and conversations at all hours.\n "},drawMatchUps:_E,eventMatchUps:IE,filterMatchUps:kg,filterParticipants:kS,findDrawDefinition:Aw,findExtension:td,findVenue:Ig,getAggregateTeamResults:UM,getAllDrawMatchUps:zg,getAllEventData:LA,getAllStructureMatchUps:Fg,getAllowedDrawTypes:aM,getAllowedMatchUpFormats:oM,getApplicableAwardProfileLevels:hM,getAppliedPolicies:xd,getAssignedParticipantIds:bI,getAvailableMatchUpsCount:JT,getAvailablePlayoffProfiles:bv,getCategoryAgeDetails:Xo,getCheckedInParticipantIds:Rh,getCompetitionDateRange:yM,getCompetitionFormat:TE,getCompetitionLeaderboard:Wp,getCompetitionMatchUps:yE,getCompetitionParticipantState:qp,getCompetitionParticipants:XN,getCompetitionPenalties:SM,getCompetitionPolicy:Ld,getCompetitionState:pp,getCompetitionVenues:Iw,getCourtInfo:Ug,getCourts:BE,getDraftState:RD,getDrawData:Rw,getDrawDefinitionTimeItem:Mm,getDrawParticipantRepresentativeIds:XT,getDrawStructures:al,getDrawTypeCoercion:mD,getEligibleVoluntaryConsolationParticipants:YT,getEntriesAndSeedsCount:iE,getEvent:zE,getEventData:bw,getEventMatchUpFormatTiming:uE,getEventProperties:GE,getEventPublishStatus:pS,getEventRankingPoints:_M,getEventStructures:vU,getEventTimeItem:Am,getEvents:HE,getFlightProfile:Tg,getHomeParticipantId:AE,getLinkedTournamentIds:zp,getLuckyDrawRoundStatus:zP,getMatchUpCompetitiveProfile:Ff,getMatchUpContextIds:ME,getMatchUpDailyLimits:wE,getMatchUpDailyLimitsUpdate:hE,getMatchUpDependencies:iI,getMatchUpFormat:CE,getMatchUpFormatTiming:Jh,getMatchUpFormatTimingUpdate:cE,getMatchUpScheduleDetails:Dg,getMatchUpType:Mg,getMatchUpsMap:bf,getMatchUpsStats:OE,getMatchUpsToSchedule:GA,getMaxEntryPosition:oE,getModifiedMatchUpFormatTiming:dE,getMutationLocks:bA,getPairedParticipant:bg,getParticipantEventDetails:ZN,getParticipantIdFinishingPositions:Nw,getParticipantMembership:tM,getParticipantPaymentStatus:nM,getParticipantResults:BI,getParticipantScaleItem:_S,getParticipantSchedules:eM,getParticipantSignInStatus:rM,getParticipantTimeItem:Cm,getParticipants:xS,getPersonRequests:QA,getPolicyDefinitions:_d,getPositionAssignments:dw,getPositionsPlayedOff:Dv,getPredictiveAccuracy:DE,getProfileRounds:tE,getPublishState:mS,getRandomQualifierList:fD,getRegistrationProfile:vM,getRoundMatchUps:Bf,getRoundVisibilityState:_A,getRounds:xE,getScaleValues:Pu,getScaledEntries:LN,getScheduledRoundsDetails:qA,getSchedulingProfile:HA,getSchedulingProfileIssues:KA,getSeedingThresholds:By,getSeedsCount:ND,getStructureSeedAssignments:Tf,getSwissChart:DD,getSwissStandings:PD,getTally:wD,getTeamLineUp:Ng,getTieFormat:kA,getTimeItem:Nm,getTournamentIds:Ed,getTournamentInfo:Pw,getTournamentPenalties:IM,getTournamentPersons:TM,getTournamentPoints:xM,getTournamentPublishStatus:dS,getTournamentStructures:UU,getTournamentTimeItem:Em,getValidGroupSizes:xy,getVenueData:Pg,getVenuesAndCourts:gw,hasLuckyRounds:Wf,isAdHoc:Hf,isCompletedStructure:PU,isEmbargoed:Eg,isValidForQualifying:TD,isValidMatchUpFormat:Io,isVisiblyPublished:Cg,matchUpActions:aD,participantScaleItem:Vd,participantScheduledMatchUps:fE,positionActions:lD,predictDrawCompetitiveBands:uw,predictMatchUpCompetitiveBands:lE,publicFindCourt:vg,publicFindVenue:Sg,suggestFormatPlans:wA,tallyParticipantResults:aS,tieFormatGenderValidityCheck:Ki,tournamentMatchUps:SE,validMatchUp:_f,validMatchUps:Lf,validateCollectionDefinition:ea,validateLineUp:rv,validatePlayoffGroups:Mv};function KE(t){const e="validateAndDeriveDrawValues",{appliedPolicies:n,policyDefinitions:r}=function(t){const{tournamentRecord:e,event:n}=t,r={...t?.appliedPolicies,...xd({tournamentRecord:e,event:n}).appliedPolicies},i=ca(t.policyDefinitions??{},!1,!0);return{appliedPolicies:r,policyDefinitions:i}}(t),i=function({enforceGender:t,policyDefinitions:e,appliedPolicies:n}){return t??e?.[Nu]?.participants?.enforceGender??n?.[Nu]?.participants?.enforceGender}({...t,policyDefinitions:r,appliedPolicies:n}),o=function({considerEventEntries:t=!0,drawEntries:e,eventEntries:n,qualifyingOnly:r}){return(r&&[]||QE(e)||(t?n:[])).filter(({entryStage:t})=>!t||t===us)}(t),a=function(t){const{consideredEntries:e,appliedPolicies:n,policyDefinitions:r,enforceGender:i,participantMap:o,participants:a,event:s}=t;return s&&a&&MD({consideredEntries:e,policyDefinitions:r,appliedPolicies:n,participantMap:o,enforceGender:i,participants:a,event:s})}({...t,consideredEntries:o,appliedPolicies:n});if(a?.error)return Ci({result:a,stack:e});const s=function(t){const e=!t.drawSize&&t.consideredEntries.length&&![ks,Bs,Fs,ic,oc,nc].includes(t.drawType??"")&&w(t.consideredEntries.length);return e||t.drawSize&&p(t.drawSize)||!1}({...t,consideredEntries:o}),c=function(t){const{policyDefinitions:e,appliedPolicies:n,enforceMinimumDrawSize:r=!0,drawSize:i}=t,o=t.drawTypeCoercion??mD({drawType:t.drawType,policyDefinitions:e,appliedPolicies:n}),a=OD({drawType:t.drawType,enforceMinimumDrawSize:r,drawTypeCoercion:o,drawSize:i});return a.error?a:{drawType:a.drawType}}({...t,appliedPolicies:n,policyDefinitions:r,drawSize:s});if(c.error)return Ci({result:c,stack:e});const u=c.drawType;if(Number.isNaN(s)&&!KS(u))return Ci({result:{error:Rt},stack:e});const d=r?.[xu]??n?.[xu],l=t.seedingProfile??d?.seedingProfile?.drawTypes?.[u??""]??d?.seedingProfile;t.seedingProfile&&(r[xu]||(r[xu]={...HN[xu]}),r[xu].seedingProfile=l);const m=function(t){const{tournamentRecord:e,event:n,ignoreAllowedDrawTypes:r,drawType:i}=t,o=!r&&e&&aM({tournamentRecord:e,categoryType:n?.category?.categoryType,categoryName:n?.category?.categoryName});if(o?.length&&!o.includes(i))return{error:wt};return{...Y}}({...t,drawType:u});return m?.error?Ci({result:m,stack:e}):{drawSize:s,drawType:u,enforceGender:i,seedingProfile:l,appliedPolicies:n,policyDefinitions:r}}function QE(t){return t?.filter(t=>t.entryStatus&&[...Sf,uf].includes(t.entryStatus))}function JE(t){const{voluntaryConsolation:e,withPlayoffs:n,targetMatchUpIds:r,tournamentRecord:i,event:o}=t,a="generateDrawDefinition",{participants:s,participantMap:c}=xS({withIndividualParticipants:!0,convertExtensions:!0,internalUse:!0,tournamentRecord:i}),u=QE(o?.entries)??[],d=KE({...t,participantMap:c,participants:s,eventEntries:u});if(d.error)return Ci({result:d,stack:a});const{appliedPolicies:p,policyDefinitions:l,drawSize:m,drawType:f,enforceGender:h,seedingProfile:g}=d,I=o?.eventType,S=t.matchUpType??I,y=function(t){const{existingDrawDefinition:e,hydrateCollections:n,enforceGender:r,tieFormatName:i,tieFormatId:o,matchUpType:a,eventType:s,isMock:c,event:u}=t;let{tieFormat:d,matchUpFormat:p}=t;if(a===is&&s===is){const t=e?.structures?.find(({stage:t})=>t===us)?.tieFormat,r=o&&u?.tieFormats?.find(t=>t.tieFormatId===o),a=wf(u);d=d||r||t||i&&u?.tieFormats?.find(t=>t.tieFormatName===i)||i&&a?.tieFormatName===i&&a||i&&Za({namedFormat:i,hydrateCollections:n,isMock:c,event:u})||a||Za({event:u,isMock:c,hydrateCollections:n}),p=void 0}else p||(d=void 0,u?.matchUpFormat||(p=va));if(d){const t=na({gender:u?.gender,enforceGender:r,tieFormat:d});if(t.error)return t}return{tieFormat:d,matchUpFormat:p}}({...t,enforceGender:h,eventType:I,matchUpType:S});if(y.error)return Ci({result:y,stack:a});const{matchUpFormat:v,tieFormat:U}=y;if(t.drawId&&"string"!=typeof t.drawId)return Ci({result:{error:sr},stack:a});const P=function(t){const e="generateOrGetExisting",n=[],r=[],i=YN(t);if(i.error)return Ci({result:i,stack:e});const o=i.existingDrawDefinition;let a,s;const c=t.drawEntries??t.eventEntries??[],u=!(!i.existingDrawDefinition||!i.structureId||i.existingQualifyingPlaceholderStructureId||!t.qualifyingProfiles?.length),d=(i.existingQualifyingPlaceholderStructureId||u)&&ON({...t,...i})||VN({...t,...i,entries:c});return d.error?Ci({result:d,stack:e}):(d.positioningReports?.length&&n.push(...d.positioningReports??[]),d.conflicts?.length&&r.push(...d.conflicts??[]),a=d.drawDefinition,s=d.structureId,{existingDrawDefinition:o,positioningReports:n,drawDefinition:a,structureId:s,conflicts:r,entries:c})}({...t,policyDefinitions:l,tournamentRecord:i,appliedPolicies:p,matchUpFormat:v,seedingProfile:g,participants:s,eventEntries:u,matchUpType:S,tieFormat:U,drawSize:m,drawType:f,event:o});if(P.error)return Ci({result:P,stack:a});const{existingDrawDefinition:T,positioningReports:w,drawDefinition:D,structureId:R,conflicts:b,entries:N}=P;if(!D)return Ci({result:{error:sr},stack:a});const M=KN({...t,existingDrawDefinition:T,positioningReports:w,appliedPolicies:p,drawDefinition:D,seedingProfile:g,participants:s,structureId:R,entries:N,params:t,stack:a});if(M.error)return M;const{qualifyingConflicts:A}=M;if(D.drawName=t.drawName??(f&&Ny(f)),m&&"object"==typeof e&&m>=4&&My({...e,drawDefinition:D,matchUpType:S}),n&&R){const e=XE({withPlayoffs:n,tournamentRecord:i,drawDefinition:D,structureId:R,event:o,idPrefix:t.idPrefix,isMock:t.isMock});if(e?.error)return Ci({result:e,stack:a})}if(t.hydrateRoundNames){const t=p?.[Au];t&&JN({drawDefinition:D,appliedPolicies:p})}return r?.length&&mU({targetMatchUpIds:r,drawDefinition:D}),{existingDrawDefinition:!!T,qualifyingConflicts:A,positioningReports:w,drawDefinition:D,structureId:R,...Y,conflicts:b}}function XE({withPlayoffs:t,drawDefinition:e,structureId:n,...r}){const{roundPlayoffs:i,...o}=t,a=new Set(e.links?.filter(t=>t.linkType===Cs&&t.source?.structureId===n).map(t=>t.source?.roundNumber)??[]),s=DT({...o,drawDefinition:e,structureId:n,...r});if(s?.error)return s;if(i){const t=e.links?.filter(t=>t.linkType===Cs&&t.source?.structureId===n&&!a.has(t.source?.roundNumber))??[];for(const[n,o]of Object.entries(i)){const i=Number(n),a=t.find(t=>t.source?.roundNumber===i);if(a){const t=XE({withPlayoffs:o,structureId:a.target?.structureId,drawDefinition:e,...r});if(t?.error)return t}}}return s}function ZE(t,e){return[...t].sort((t,n)=>{const r=e?.[t]??0;return(e?.[n]??0)-r})}function tC({group:t,adHocRatings:e}){return[...t].sort((t,n)=>(e?.[t]??0)-(e?.[n]??0))[0]}function eC({participantIds:t,encounterSet:e,adHocRatings:n}){if(t.length<2)return[];const r=ZE(t,n),i=Math.floor(r.length/2),o=r.slice(0,i),a=r.slice(i),s=[],c=new Set;for(const t of o){let r=-1,i=1/0;for(let o=0;o<a.length;o++){if(c.has(o))continue;const s=a[o],u=JD(t,s);if(e.has(u))continue;const d=Math.abs((n?.[t]??0)-(n?.[s]??0));d<i&&(i=d,r=o)}if(-1===r)for(let t=0;t<a.length;t++)if(!c.has(t)){r=t;break}r>=0&&(c.add(r),s.push({participantIds:[t,a[r]]}))}return s}function nC({matchUps:t,roundNumber:e}){return t.filter(t=>t.roundNumber===e).sort((t,e)=>t.roundPosition-e.roundPosition)}function rC(t){return t.matchUpStatus===Sp?t.sides.reduce((t,e)=>e.participantId||t,void 0):t.winningSide?t.sides.reduce((e,n)=>n.sideNumber===t.winningSide?n.participantId:e,void 0):void 0}function iC({scaleAttributes:t,scaledEntries:e,stageEntries:n,seedsCount:r,scaleName:i}){if(!t)return{error:Ae,info:"missing scaleAttributes"};const o=Object.assign({},...(e??[]).slice(0,r).map(({participantId:t},e)=>({[t]:e+1})));i=i||t.scaleName;const a=(new Date).toISOString();return{scaleItemsWithParticipantIds:n.map(({participantId:e})=>({scaleItems:[{scaleValue:o[e],eventType:t.eventType,scaleType:vu,scaleName:i,scaleDate:a}],participantId:e}))}}var oC={__proto__:null,adHocPositionSwap:WP,addAdHocMatchUps:$T,addDrawDefinitionTimeItem:sP,addFinishingRounds:nI,addGoesTo:rI,addLinkedConsolationStructure:dU,addPlayoffStructures:DT,addQualifyingStructure:jP,addVoluntaryConsolationStructure:My,allPlayoffPositionsFilled:TU,alternateDrawPositionAssignment:lU,assignDrawPosition:BT,assignDrawPositionBye:SI,attachConsolationStructures:aU,attachPlayoffStructures:sU,attachQualifyingStructure:oP,attachStructures:cU,autoSeeding:function({tournamentRecord:t,drawDefinition:e,policyDefinitions:n,scaleAttributes:r,scaleName:i,drawSize:o,drawId:a,event:s,stage:c,sortDescending:u,scaleSortMethod:d}){const p=iE({policyDefinitions:n,drawDefinition:e,drawSize:o,drawId:a,event:s,stage:c});if(p.error)return p;const{entries:l,seedsCount:m,stageEntries:f}=p;if(!f||!m)return{error:sr};const h=LN({tournamentRecord:t,scaleAttributes:r,scaleSortMethod:d,sortDescending:u,entries:l,stage:c}).scaledEntries??[],{scaleItemsWithParticipantIds:g}=iC({scaleAttributes:r,scaledEntries:h,stageEntries:f,seedsCount:m,scaleName:i});return{scaleItemsWithParticipantIds:g}},automatedPlayoffPositioning:XU,automatedPositioning:JU,buildDrawHierarchy:function({matchUps:t,matchUpType:e}){if(!t)return{error:Ie};let r=[],o=[],s=0;e&&(t=t.filter(t=>t.matchUpType===e));const c=M(t.map(({matchUpType:t})=>t));if(c.length>1)if(z(c,a))t=t.filter(bh(a));else if(z(c,n))t=t.filter(bh(n));else{if(!z(c,i))return{};t=t.filter(bh(i))}if(!Lf(t)||!t.length)return{};const u=(t,e)=>p(t)-p(e),d=M(t.flatMap(t=>t.drawPositions).filter(Boolean)).sort(u),l=L(1,Math.max(...d)+1).filter(t=>!d.includes(t)).sort(u),{roundMatchUps:m}=Bf({matchUps:t}),f=m?.[1],h=m?.[2]??[],g=f?.[0],I=g?.drawId,S=g?.structureId,y=m?Object.keys(m).map(t=>p(t)):[],v=Math.max(...y),U=m?.[v]?.length??0,P=Math.ceil(Math.log(U)/Math.log(2)),T=L(1,P+1).map(t=>{const e=Math.pow(2,t-1),n=v+P-t+1;return L(1,e+1).map(e=>({drawId:I,structureId:S,matchUpId:pa(),drawPositions:[],sides:[],roundNumber:n,roundPosition:e,finishingRound:t}))});P&&(t=t.concat(...T.flat()));const w=f?.map(t=>t.drawPositions),D=w?.flat(1/0),R=h.map(t=>t.drawPositions).flat(1/0).filter(t=>!D?.includes(t)).sort(u),b=h.filter(t=>t.drawPositions?.find(t=>R.includes(t))).map(t=>{const e=t.drawPositions?.find(t=>R.includes(t)),n=e&&t.drawPositions?.indexOf(e),r=void 0!==n&&t.sides?.[n];return e&&{[e]:r}});if(l?.length&&R?.length===l?.length){const e=R.map((t,e)=>[t,l[e]].sort(u)),n=Object.assign({},...b),r=ca(f?.[0].finishingRound,!1,!0),i=ca(f?.[0].finishingPositionRange,!1,!0);o=e.map((t,e)=>{const o=Math.max(...t??[])/2,a=t?.map(t=>n[t]||{bye:!0,drawPosition:t});return{finishingPositionRange:i,sideNumber:e+1,matchUpStatus:"BYE",matchUpId:pa(),finishingRound:r,roundNumber:1,drawPositions:t,roundPosition:o,structureId:S,drawId:I,sides:a}}),t=t.concat(...o)}const N=v+P;return L(1,N+1).forEach(e=>{const n=[],i=nC({matchUps:t,roundNumber:e}),o=nC({matchUps:t,roundNumber:e-1}),a=new Set(o.map(rC).filter(Boolean)),c=i?.length===r?.length,u=i?.length===r?.length/2;1===e&&i.forEach(t=>{const e=t.drawPositions??[],{matchUpId:r,structureId:i}=t,o=[{...t.sides[0],drawPosition:e[0],matchUpId:r,structureId:i},{...t.sides[1],drawPosition:e[1],matchUpId:r,structureId:i}],a={...t,children:o};n.push(a)}),c?(s++,i.forEach((t,e)=>{const i=t.drawPositions??[],{matchUpId:o,structureId:c}=t,u=i.filter(Boolean).reduce((t,e)=>D?.includes(e)?t:e,void 0),d=[{...t.sides.filter(Boolean).reduce((t,e)=>e.participantId&&!a.has(e.participantId)?e:t,void 0),drawPosition:u,feedRoundNumber:s,sides:t.sides,matchUpId:o,structureId:c},r[e]],p={...t,children:d};n.push(p)})):u&&i.forEach((t,e)=>{const i={...t,children:[r[2*e],r[2*e+1]]};n.push(i)}),r=n}),{hierarchy:r[0],missingMatchUps:o,maxRound:v,finalRound:N,matchUps:t}},checkValidEntries:MD,deleteAdHocMatchUps:qT,drawMatic:xN,findDrawDefinition:Aw,generateAdHocMatchUps:YD,generateAdHocRounds:FN,generateAndPopulatePlayoffStructures:vT,generateConsolationStructure:uU,generateDrawDefinition:JE,generateDrawMaticRound:iR,generateDrawStructuresAndLinks:kD,generateDrawTypeAndModifyDrawDefinition:xD,generateQualifyingStructure:GP,generateSwissRound:function(t){const{drawDefinition:e,tournamentRecord:n,event:r}=t;if(!e)return{error:st};const i=t.structureId?ol({drawDefinition:e,structureId:t.structureId}).structure:e.structures?.find(t=>"MAIN"===t.stage&&Hf({structure:t}))??e.structures?.find(t=>Hf({structure:t}));if(!i)return{error:Vt};const o=kN({...t,restrictEntryStatus:!0,targetStage:i.stage});if(o.error)return o;const a=o.participantIds??[],s=i.positionAssignments?.map(t=>t.participantId).filter(t=>!!t)??[],c=function({drawDefinition:t,targetStructureId:e}){const n=t.links??[],r=n.filter(t=>t.linkType===Es&&t.target?.structureId===e),i=[];for(const e of r){const n=t.structures?.find(t=>t.structureId===e.source?.structureId);if(n?.stage!==ds)continue;const r=e.source?.roundNumber;if(!r)continue;const{matchUps:o}=Fg({matchUpFilters:{roundNumbers:[r],isCollectionMatchUp:!1,hasWinningSide:!0},afterRecoveryTimes:!1,structure:n,inContext:!0});for(const t of o??[]){const e=t.sides?.find(e=>e?.sideNumber===t.winningSide);e?.participantId&&i.push(e.participantId)}}return i}({drawDefinition:e,targetStructureId:i.structureId}),u=Array.from(new Set([...a,...s,...c])),{competitionPolicy:d}=Ld({tournamentRecord:n,drawDefinition:e,event:r}),{competitionState:p}=d?pp({drawDefinition:e}):{competitionState:void 0};let l;if(d&&p&&"DYNAMIC_FORM"===d.pairingPolicy.ratingSource){l={};for(const[t,e]of Object.entries(p.participantStates))l[t]=e.dynamicFormRating}else l=op({participantIds:u,tournamentRecord:n,scaleName:t.scaleName});const m=t.swissPolicy??td({element:e,name:"swissPolicy"})?.extension?.value,f=i.matchUps??[],{participantIdPairings:h,byeParticipantId:g}=function({participantIds:t,adHocRatings:e,allowDraws:n,matchUps:r}){const i=r.filter(t=>t.winningSide),{scoreGroups:o,records:a}=hD({matchUps:i,participantIds:t,allowDraws:n}),{encounters:s}=ZD({matchUps:[...r]}),c=new Set(s),u=0===i.length;let d;const p=[...t];if(p.length%2!=0){d=function({scoreGroups:t,records:e,adHocRatings:n}){const r=t.at(-1);if(!r)return"";return[...r.participantIds].sort((t,r)=>{const i=e.get(t),o=e.get(r),a=(i?.points??0)-(o?.points??0);return 0!==a?a:(n?.[t]??0)-(n?.[r]??0)})[0]}({scoreGroups:o,records:a,adHocRatings:e});const t=p.indexOf(d);t>=0&&p.splice(t,1);for(const t of o){const e=t.participantIds.indexOf(d);if(e>=0){t.participantIds.splice(e,1);break}}}const l=[],m=new Set;if(u){const t=ZE(p,e),n=Math.floor(t.length/2);for(let e=0;e<n;e++)l.push({participantIds:[t[e],t[n+e]]}),m.add(t[e]),m.add(t[n+e])}else{const t=o.map(t=>[...t.participantIds]);for(let n=0;n<t.length;n++){const r=t[n].filter(t=>!m.has(t));if(r.length%2!=0&&n<t.length-1){const i=tC({group:r,adHocRatings:e}),o=r.indexOf(i);r.splice(o,1),t[n+1].push(i)}const i=eC({participantIds:r,encounterSet:c,adHocRatings:e});for(const t of i)l.push(t),m.add(t.participantIds[0]),m.add(t.participantIds[1])}const n=p.filter(t=>!m.has(t));for(let t=0;t<n.length-1;t+=2)l.push({participantIds:[n[t],n[t+1]]})}return{participantIdPairings:l,scoreGroups:o,records:a,byeParticipantId:d}}({allowDraws:m?.allowDraws,matchUps:f,participantIds:u,adHocRatings:l}),I=YD({structureId:i.structureId,participantIdPairings:h,matchUpIds:t.matchUpIds,idPrefix:t.idPrefix,isMock:t.isMock,drawDefinition:e,newRound:!0,event:r});return I.error?I:{roundNumber:I.roundNumber,matchUps:I.matchUps,byeParticipantId:g,...Y}},generateVoluntaryConsolation:oR,getAssignedParticipantIds:bI,getAvailableMatchUpsCount:JT,getAvailablePlayoffProfiles:bv,getDraftState:RD,getDrawDefinitionTimeItem:Mm,getDrawParticipantRepresentativeIds:XT,getDrawStructures:al,getDrawTypeCoercion:mD,getEligibleVoluntaryConsolationParticipants:YT,getLuckyDrawRoundStatus:zP,getMatchUpsMap:bf,getParticipantIdFinishingPositions:Nw,getPositionAssignments:dw,getPositionsPlayedOff:Dv,getRandomQualifierList:fD,getSeedingThresholds:By,getSeedsCount:ND,getStructureSeedAssignments:Tf,getSwissChart:DD,getSwissStandings:PD,getTally:wD,getTeamLineUp:Ng,getValidGroupSizes:xy,hasLuckyRounds:Wf,initializeDraft:VT,isAdHoc:Hf,isCompletedStructure:PU,isValidForQualifying:TD,luckyDrawAdvancement:KP,luckyLoserDrawPositionAssignment:cv,modifyDrawDefinition:MT,modifyDrawName:NT,modifySeedAssignment:ZU,mutate:zT,positionActions:lD,predictDrawCompetitiveBands:uw,pruneDrawDefinition:_T,qualifierDrawPositionAssignment:SU,qualifierProgression:wU,query:AD,remapDrawDefinitionMatchUpIds:mU,removeDrawPositionAssignment:wy,removeRoundMatchUps:WT,removeSeededParticipant:_P,removeStructure:lP,renameStructures:aP,resetDrawDefinition:AT,resetQualifyingStructure:pP,resetVoluntaryConsolationStructure:Zl,resolveDraftPositions:uP,seedWithdrawalCascade:qP,setDrawParticipantRepresentativeIds:nl,setDrawPositionPreferences:pU,setPositionAssignments:lv,setStructureOrder:tP,setSubOrder:HT,shiftAdHocRounds:pv,swapAdHocRounds:mv,swapDrawPositionAssignments:FP,updateTeamLineUp:iv,validatePlayoffGroups:Mv,withdrawParticipantAtDrawPosition:Dy};function aC({tournamentRecord:t,drawDefinition:e,participantId:n,entryPosition:r,skipRefresh:i,event:o}){const a=dl({tournamentRecord:t,participantId:n},[Ic,Pc]);if(a.error)return a;if(void 0!==r&&!Number.isSafeInteger(r))return{error:sr,entryPosition:r};(o?.entries??[]).forEach(t=>{t.participantId===n&&(t.entryPosition=r)}),(e?.entries??[]).forEach(t=>{t.participantId===n&&(t.entryPosition=r)});const s=t=>{t.entries.forEach(t=>{t.entryPosition===r&&t.participantId!==n&&(t.entryPosition+=.1)})};return i||(o?.entries&&(s(o),o.entries=NI({entries:o.entries})),e?.entries&&(s(e),e.entries=NI({entries:e.entries}))),{...Y}}function sC({tournamentRecord:t,entryPositions:e,drawDefinition:n,event:r}){const i=dl({tournamentRecord:t},[Ic]);if(i.error)return i;if(!Array.isArray(e))return{error:sr};for(const i of e){const{participantId:e,entryPosition:o}=i,a=aC({skipRefresh:!0,tournamentRecord:t,drawDefinition:n,participantId:e,entryPosition:o,event:r});if(a.error)return a}return r?.entries&&(r.entries=NI({entries:r.entries})),n?.entries&&(n.entries=NI({entries:n.entries})),{...Y}}function cC(t){const{participantId:e}=t;return e&&"string"!=typeof e?{error:sr,participantId:e}:uC({...t,participantIds:[e].filter(Boolean)})}function uC({tournamentRecord:t,drawDefinition:e,participantIds:n,stageSequence:r,stage:i=us,eventId:o,event:a}){const s=dl({tournamentRecord:t,event:a},[Ic,zc]);if(s.error)return s;if(!Array.isArray(n))return{error:sr,participantIds:n};if(a){const t=dC({element:a,participantIds:n,stageSequence:r,stage:i});if(t.error)return t}if(e){const t=dC({element:e,participantIds:n,stageSequence:r,stage:i});if(t.error)return o?Ci({context:{drawPromotionError:t.error,drawId:e.drawId},result:{...Y},stack:"promoteAlternates"}):t}return{...Y}}function dC({participantIds:t,stageSequence:e,element:n,stage:r}){const i=(n.entries??[]).filter(t=>t.entryStatus===ef),o=(n.entries??[]).filter(e=>t.includes(e.participantId)),a=i.reduce((t,e)=>{const{entryPosition:n}=e;return Number.isNaN(Number(n))&&t||(!t||n<t.entryPosition)&&e||t},void 0),s=o.length?o:[a].filter(Boolean);if(!s?.length)return{error:vn};const c=s.filter(({entryStatus:t})=>t!==ef);if(c.length)return{error:yn,invalidEntryStatus:c};const u=s.filter(({entryStage:t})=>t&&t!==r);if(u.length)return{error:Un,invalidStage:u};const d=e&&s.filter(t=>t.stageSequence!==e);if(d?.length)return{error:Pn,invalidStageSequence:d};for(const t of s){t.entryStatus=rf;const e=t?.entryPosition;Number.isNaN(Number(e))||n.entries.forEach(t=>{t.entryStatus===ef&&t.entryPosition>e&&(t.entryPosition=t.entryPosition-1)});const r=Math.max(...n.entries.filter(t=>t.entryStatus===rf&&!Number.isNaN(Number(t.entryPosition))).map(({entryPosition:t})=>p(t||0)),0);t.entryPosition=r||0}return{...Y}}function pC({drawDefinition:t,entryStage:e}){return t?e?(t.entries&&(t.entries=t.entries.filter(t=>t.entryStage!==e)),{...Y}):{error:sr}:{error:st}}function lC({autoEntryPositions:t=!0,participantIds:e,drawDefinition:n,drawId:r,stages:i,event:o}){if(!o)return{error:Ht};if(!r)return{error:bt};if(!e?.length)return{error:ln};if(j(bI({drawDefinition:n,stages:i}).assignedParticipantIds??[],e))return{error:gn};const a=t=>{const n=t.participantId;return!e.includes(n)},{flightProfile:s}=Tg({event:o}),c=s?.flights?.find(t=>t.drawId===r);return c?.drawEntries&&(c.drawEntries=c.drawEntries.filter(a),t&&(c.drawEntries=NI({entries:c.drawEntries}))),n?.entries&&(n.entries=n.entries.filter(a),t&&(n.entries=NI({entries:n.entries}))),{...Y}}function mC(t){const{allowDuplicateParticipantIdPairs:e,returnParticipant:n,disableNotice:r,pairOverride:i,participant:o}=t,a=t.tournamentId?t.tournamentRecords?.[t.tournamentId]:t.tournamentRecord??(t.activeTournamentId&&t.tournamentRecords?.[t.activeTournamentId]);if(!a)return{error:rt};const s=function(t,e){if(!t)return{error:on};t.participantId??=pa(),e.participants??=[];const{participantId:n}=t;if(e.participants.reduce((t,e)=>e.participantId===n||t,!1))return{error:dn};const{participantType:r,participantRole:i}=t;return r&&Object.keys(vm).includes(r)?i?r!==gm&&t.person?{error:sr,person:t.person}:t.individualParticipantIds&&!Array.isArray(t.individualParticipantIds)?{error:sr,individualParticipantIds:t.individualParticipantIds}:void 0:{error:rn}:{error:nn,participantType:r}}(o,a);if(s)return Ci({result:s,stack:"addParticipant"});const{participantType:c}=o,u=a.participants??[],d=u.filter(t=>t.participantType===gm).map(t=>t.participantId);if(c===Sm){const t=function({participant:t,tournamentParticipants:e,pairOverride:n,allowDuplicateParticipantIdPairs:r,returnParticipant:i}){const o="addParticipant";if(t.person)return{error:sr,person:t.person};if(!t.individualParticipantIds)return Ci({result:{error:ln},stack:o});if(2!==t.individualParticipantIds.length&&!n)return Ci({info:"PAIR must be 2 individualParticipantIds",result:{error:tn},stack:o});const a=new Set(e.filter(t=>t.participantType===gm).map(t=>t.participantId));if(!Array.isArray(t.individualParticipantIds))return Ci({result:{error:tn},stack:o});if(!t.individualParticipantIds.reduce((t,e)=>a.has(e)&&t,!0))return Ci({result:{error:tn},stack:o});const s=e.filter(t=>t.participantType===Sm).map(t=>({individualParticipantIds:t.individualParticipantIds,participant:t})).find(e=>2===V(e.individualParticipantIds,t.individualParticipantIds).length);if(s&&!r)return{earlyReturn:!0,...Y,existingParticipant:!0,participant:i&&ca(s.participant)};if(!t.participantName){const n=e.filter(e=>t.individualParticipantIds?.includes(e.participantId));let r=n.map(t=>t.person?.standardFamilyName||t.participantOtherName||t.participantName||"").filter(Boolean).join("/");1===n.length&&(r+="/Unknown"),t.participantName=r}}({participant:o,tournamentParticipants:u,pairOverride:i,allowDuplicateParticipantIdPairs:e,returnParticipant:n});if(t?.earlyReturn){const{earlyReturn:e,...n}=t;return n}if(t)return t}else if(c===gm){const t=o.person?.standardFamilyName&&o.person?.standardGivenName,e=o.participantOtherName||o.participantName;if(!t&&!e)return{error:hn};o.participantName||(o.participantName=t?`${o.person.standardGivenName} ${o.person.standardFamilyName}`:o.participantOtherName??"")}else{if(!c||![ym,Im].includes(c))return{error:nn};{const t=function({participant:t,tournamentIndividualParticipantIds:e}){const n="addParticipant";if(t.individualParticipantIds??=[],t.individualParticipantIds?.length)for(const r of t.individualParticipantIds){if("string"!=typeof r)return Ci({result:{participantId:r,error:sr},stack:n});if(!e.includes(r))return Ci({result:{participantId:r,error:un},stack:n})}}({participant:o,tournamentIndividualParticipantIds:d});if(t)return t}}a.participants?.push(o),r||di({payload:{tournamentId:a.tournamentId,participants:[o]},topic:ml});return Ei({participant:n&&ca(o),...Y})}function fC({allowDuplicateParticipantIdPairs:t,returnParticipants:e,tournamentRecord:n,participants:r=[]}){if(!n)return{error:rt};n.participants??=[];const i=n.participants.map(t=>t.participantId)??[];r.forEach(t=>{t.participantId??=pa()});const o=r.filter(t=>!i.includes(t.participantId)),a=r.filter(t=>i.includes(t.participantId)),s=o.filter(t=>t.participantType===gm),c=o.filter(t=>t.participantType!==gm),u=s.concat(...c),d=[];if(u.length){for(const e of u){const r=mC({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&&di({topic:ml,payload:{tournamentId:n.tournamentId,participants:d}});const r={participants:e&&ca(d),addedCount:d.length,...Y};return a.length&&Object.assign(r,{notAdded:a,info:In}),Ei(r)}return{info:"No new participants to add",addedCount:0,...Y}}function hC(t){const e=fu(t,[{[Ic]:!0,[zc]:!0}]);if(e.error)return e;const{allowDuplicateParticipantIdPairs:n,entryStatus:r=ef,participantIdPairs:o=[],entryStage:a=us,tournamentRecord:s,enforceCategory:c,drawDefinition:u,event:d,uuids:p}=t;if(d.eventType!==i)return{error:$t};const l=[],m=new Map;for(const t of s.participants??[]){const{participantType:e,participantId:n,person:r,individualParticipantIds:i}=t;e===gm&&r?.sex?m.set(n,r.sex):e===Sm&&i&&l.push(i)}const f=o.filter(t=>{if(2!==t.length)return!0;if(!d.gender||Hi(d.gender))return!1;if(!m.has(t[0])||!m.has(t[1]))return!0;const e=t.map(t=>m.get(t));let n=Wi(d.gender)&&(!Wi(e[0])||!Wi(e[1]))||qi(d.gender)&&(!qi(e[0])||!qi(e[1]));return $i(d.gender)&&(e.sort(TS),qi(e[0])&&Wi(e[1])||(n=!0)),n});if(f.length)return{error:tn,invalidParticipantIdPairs:f};const h=o.map(t=>({participantId:p?.pop()??pa(),participantRole:sy,individualParticipantIds:t,participantType:Sm})),g=n?h:h.filter(t=>!l.some(e=>2===V(e,t.individualParticipantIds).length));let I,S=[];if(g){const t=fC({allowDuplicateParticipantIdPairs:n,participants:g,returnParticipants:!0,tournamentRecord:s});if(t.error)return t;S=t.participants??[],I=t.info}const y=oy({participantIds:o.map(t=>{const e=S.find(e=>2===V(e.individualParticipantIds,t).length);if(e)return e;const{participant:n}=bg({tournamentRecord:s,participantIds:t});return n}).map(t=>t.participantId),tournamentRecord:s,enforceCategory:c,drawDefinition:u,entryStatus:r,entryStage:a,event:d});g.length&&di({payload:{participants:g},topic:ml});return{...y,info:I,newParticipantIds:g.map(Xp)}}function gC({entryStatus:t=rf,unpairedParticipantIds:e=[],participantIdPairs:n=[],entryStage:r=us,tournamentRecord:i,event:o}){const a=dl({tournamentRecord:i,event:o},[Ic,zc]);if(a.error)return a;const s=i.participants??[],c=s.filter(t=>t.participantType===gm).map(t=>t.participantId),u=e.concat(...n).flat(1/0).filter(t=>!c.includes(t));if(u.length)return{error:tn,invalidParticipantIds:u};const d=n.filter(t=>2!==t.length);if(d.length)return{error:tn,invalidParticipantIdPairs:d};const p=s.filter(t=>t.participantType===Sm).map(t=>t.individualParticipantIds),l=n.filter(t=>!p.find(e=>2===V(e,t).length)).map(t=>({participantType:Sm,participantRole:sy,individualParticipantIds:t})),m=fC({participants:l,tournamentRecord:i});if(m.error)return m;const f=n.map(t=>{const{participant:e}=bg({tournamentRecord:i,participantIds:t});return e}).map(e=>({participantId:e,entryStatus:t,entryStage:r})),h=e.map(t=>({entryStatus:pf,participantId:t,entryStage:r}));return o.entries=(o.entries??[]).filter(t=>t.entryStage===r),o.entries=o.entries.concat(...f,...h),{...Y}}var IC={__proto__:null,addDrawEntries:JS,addEventEntries:oy,addEventEntryPairs:hC,destroyPairEntries:Ty,destroyPairEntry:Py,getEntriesAndSeedsCount:iE,getMaxEntryPosition:oE,modifyEntriesStatus:AI,modifyEventEntries:gC,mutate:{__proto__:null,addDrawEntries:JS,addEventEntries:oy,addEventEntryPairs:hC,destroyPairEntries:Ty,destroyPairEntry:Py,modifyEntriesStatus:AI,modifyEventEntries:gC,promoteAlternate:cC,promoteAlternates:uC,removeDrawEntries:lC,removeEventEntries:ZS,removeStageEntries:pC,setEntryPosition:aC,setEntryPositions:sC},promoteAlternate:cC,promoteAlternates:uC,query:aE,removeDrawEntries:lC,removeEventEntries:ZS,removeStageEntries:pC,setEntryPosition:aC,setEntryPositions:sC};const SC={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:Ta,DOMINANT_DUO_MIXED:Ia,LAVER_CUP:Ma,TEAM_DOUBLES_3_AGGREGATION:ma,USTA_BREWER_CUP:Sa,USTA_OZAKI_CUP:ya,USTA_COLLEGE:wa,USTA_GOLD_TEAM_CHALLENGE:la,USTA_INTERSECTIONAL:ga,USTA_LEVEL_1:Da,USTA_SECTION_BATTLE:ha,USTA_SOUTHERN_LEVEL_5:fa,USTA_TOC:Aa,USTA_WTT_ITT:Ra,USTA_ZONAL:Na};function yC({suppressNotifications:t,tournamentRecord:e,internalUse:n,event:r}){const i=dl({tournamentRecord:e,event:r},[Ic,zc]);if(i.error)return i;e.events??=[];const{startDate:o,endDate:a}=e;if(!n&&(r.entries?.length||r.drawDefinitions?.length)){const t=Ei({drawDefinitions:!!r.drawDefinitions?.length,entries:!!r.entries?.length});return{info:"entries/drawDefinitions cannot exist",error:sr,context:t}}const s={eventType:es,drawDefinitions:[],entries:[],startDate:o,endDate:a,...r};if(r.eventType===os)if(r.tieFormat){const t=na({tieFormat:r.tieFormat});if(t.error)return t}else if(r.tieFormatName){if(!SC[r.tieFormatName])return{context:{tieFormatName:r.tieFormatName},error:sr};const t=Za({isMock:e?.isMock,namedFormat:r.tieFormatName,event:r});s.tieFormat=t}s.eventId??=pa();const c=e.events.reduce((t,e)=>t||e.eventId===s.eventId,void 0);if(c)return{error:Yt};const u=s;if(e.events.push(u),!t){const{topics:t}=gi();if(t.includes(ll)){const t=Kg({event:r}).matchUps??[];Hl({tournamentId:e?.tournamentId,eventId:r.eventId,matchUps:t})}const{drawDefinitions:n,...i}=r;for(const t of n??[])Kl({drawDefinition:t});!function({tournamentId:t,event:e}){e&&di({payload:{tournamentId:t,event:e},key:e.eventId,topic:hl})}({tournamentId:e?.tournamentId,event:i})}return{...Y,event:s}}function vC(t){const e=fu(t,[{[du]:{[Fc]:!0,[vc]:!0}},{[Ic]:!0}]);if(e.error)return e;const n=t.tieFormat||Za({namedFormat:t.tieFormatName}),r=t.uuids||[da(n.collectionDefinitions.length)],i=t.addEntriesFromTeams?function(t){const e={[Vi]:[],[_i]:[]},n=t.participants?.filter(t=>t.participantType===hm),r=new Set(n?.flatMap(t=>t.individualParticipantIds??[]));for(const n of t.participants??[])if(r.has(n.participantId)){const t=n.person?.sex;if(t&&Yi(t)){const r=zi(t);r&&e[r].push(n.participantId)}}return e}(t.tournamentRecord):{[Vi]:[],[_i]:[]},o=[];for(const e of n.collectionDefinitions??[]){const n=r?.pop()?.toString()||pa(),a={matchUpFormat:e.matchUpFormat,eventName:e.collectionName,category:e.category,gender:e.gender,eventType:e.matchUpType,eventId:n};if(t.addEntriesFromTeams){const n=UC({genderedParticipants:i,collectionDefinition:e,entryStatus:t.entryStatus,event:a});if(n?.error)return n}if(o.push(a),!1!==t.addEvents){const e=yC({internalUse:!0,tournamentRecord:t.tournamentRecord,event:a});if(e.error)return e}}return{...Y,events:o}}function UC({genderedParticipants:t,collectionDefinition:e,entryStatus:n,event:r}){const i=e.matchUpType,o=e.gender,a=i===rs?pf:n||rf,s=$i(o)?[...t[Vi],...t[_i]]:t[zi(o)||Li]??[];if(s.length)return oy({participantIds:s,entryStatus:a,event:r})}function PC({removePriorValues:t=!0,status:e=Th,statusObject:n,event:r}){if(!f(n))return{error:sr};const i=pS({event:r,status:e}),o=`${Ph}.${wh}`;return oU({timeItem:{itemValue:{[e]:{...i,...n}},itemType:o},removePriorValues:t,event:r})}function TC(t){const e=fu(t,[{[Ic]:!0,[zc]:!0},{eventDataParams:!1,[cu]:ru}]);if(e.error)return e;const{includePositionAssignments:n,removePriorValues:r,tournamentRecord:i,status:o=Th,event:a,drawIdsToRemove:s,drawIdsToAdd:c}=t,{appliedPolicies:u}=xd({tournamentRecord:i,event:a}),d={...u,...t.policyDefinitions},p=a?.drawDefinitions?.map(({drawId:t})=>t)??[],l=t.drawDetails?Object.keys(t.drawDetails):[],m=l.length?[]:t.drawIds,f=(c??[]).concat(...s??[],...m??[],...l),h=function({drawIdsToValidate:t,eventDrawIds:e}){const n=t.filter(t=>!e.includes(t));if(n.length)return Ci({result:{error:ut},context:{invalidDrawIds:n}});return}({drawIdsToValidate:f,eventDrawIds:p});if(h?.error)return h;const g=function(t){if(!t)return;for(const e of Object.keys(t)){const n=t[e];if(wC(n.publishingDetail?.embargo))return{error:je};const r=DC(n.stageDetails);if(r)return r;const i=RC(n.structureDetails);if(i)return i}return}(t.drawDetails);if(g?.error)return g;const I=function({pubStatus:t,eventDrawIds:e}){return Object.keys(t?.drawDetails??{}).filter(t=>e.includes(t)).reduce((e,n)=>(e[n]=t.drawDetails[n],e),{})}({pubStatus:pS({event:a,status:o}),eventDrawIds:p});!function({drawDetails:t,eventDrawIds:e,drawIdsToValidate:n,drawIdsToRemove:r,drawIdsToAdd:i,specifiedDrawIds:o}){for(const a of e)n.length&&!n.includes(a)||(r?.includes(a)||o?.length&&!o.includes(a)?t[a]={...t[a],publishingDetail:{published:!1}}:(i?.includes(a)||o?.includes(a)||!o?.length)&&(t[a]={...t[a],publishingDetail:{published:!0}}))}({drawDetails:I,eventDrawIds:p,drawIdsToValidate:f,drawIdsToRemove:s,drawIdsToAdd:c,specifiedDrawIds:m});for(const e of p)if(t.drawDetails?.[e]){const n=bC({drawDetails:I,drawId:e,newDetail:t.drawDetails[e],event:a});if(n?.error)return n}PC({statusObject:{drawDetails:I},removePriorValues:r,status:o,event:a});const{topics:S}=gi(),y=S.includes(Ol),v=y||t.returnEventData?bw({includePositionAssignments:n,...t.eventDataParams,usePublishState:!0,tournamentRecord:i,policyDefinitions:d,event:a})?.eventData:void 0;return y&&di({payload:{eventData:v,tournamentId:i.tournamentId},topic:Ol}),{...Y,eventData:v}}function wC(t){return!!t&&!Oo(t)}function DC(t){if(t)for(const e of Object.keys(t))if(wC(t[e].embargo))return{error:je}}function RC(t){if(t)for(const e of Object.keys(t)){const n=t[e];if(wC(n.embargo))return{error:je};if(n.scheduledRounds){const t=DC(n.scheduledRounds);if(t)return t}}}function bC({drawDetails:t,drawId:e,newDetail:n,event:r}){let i=n.structureDetails??t[e].structureDetails;const o=n.stageDetails??t[e].stageDetails??{},{structureIdsToRemove:a=[],structureIdsToAdd:s=[],publishingDetail:c={},stagesToRemove:u=[],stagesToAdd:d=[]}=n;if((s||d)&&(c.published=!0),t[e]={publishingDetail:c,structureDetails:i,stageDetails:o},s.length||a.length){const n=function({drawDetails:t,drawId:e,structureIdsToAdd:n,structureIdsToRemove:r,structureDetails:i,event:o}){const a=(o?.drawDefinitions?.find(t=>t.drawId===e)?.structures??[]).map(({structureId:t})=>t),s=(n??[]).concat(r??[]),c=s.filter(t=>!a.includes(t));if(c.length)return Ci({result:{error:Vt},context:{invalidStructureIds:c}});i=i??{};for(const t of a)r.includes(t)?i[t]={published:!1}:i[t]={published:!0};return void(t[e].structureDetails=i)}({drawDetails:t,drawId:e,structureIdsToAdd:s,structureIdsToRemove:a,structureDetails:i,event:r});if(n?.error)return n}!function({stageDetails:t,stagesToAdd:e,stagesToRemove:n,drawStages:r}){if(e.length){for(const n of e)t[n]={published:!0};for(const e of r)t[e]||(t[e]={published:!1})}if(e.length||n.length){for(const e of n)t[e]={published:!1};for(const e of r)t[e]||(t[e]={published:!0})}}({stageDetails:o,stagesToAdd:d,stagesToRemove:u,drawStages:(r?.drawDefinitions?.find(t=>t.drawId===e)?.structures??[]).map(({stage:t})=>t)}),(d.length||u.length)&&(t[e].stageDetails=o)}const NC="deleteDrawDefinitions",MC="autoSchedulingAudit",AC="deleteEvents",EC={AUTO_SCHEDULING_AUDIT:MC,DELETE_EVENTS:AC,DELETE_DRAW_DEFINITIONS:NC};function CC(t){if(!t.tournamentRecord)return{error:rt};const e="deleteDrawDefinitions";let n=t.drawIds??[],r=t.event;const{autoPublish:i=!0,tournamentRecord:o,auditData:a,eventId:s,force:c}=t,{appliedPolicies:u}=xd({tournamentRecord:o,event:r}),d={...u,...t.policyDefinitions},p=Array.isArray(n)?n[0]:void 0;if(!r){const t=wg({tournamentRecord:o,eventId:s,drawId:p});if(t.error)return t;r=t.event}const l=[],m=[],f=[];if(!r?.drawDefinitions)return Ci({info:"event has no drawDefinition",result:{...Y},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 Ci({info:"nothing to do; no matching drawIds in event.",result:{...Y},stack:e});const g=ca(Tg({event:r}).flightProfile,!1,!0),I=({participantId:t,drawPosition:e,qualifier:n,bye:r})=>({bye:r,qualifier:n,drawPosition:e,participantId:t}),S=c??u?.[Fu]?.allowDeletionWithScoresPresent?.drawDefinitions,y=pS({event:r})??{};let v,U=y.drawIds??(y.drawDetails&&Object.keys(y.drawDetails))??[];const P=[],T=r.drawDefinitions.filter(t=>{if(n.includes(t.drawId)){const e=Zg({event:r,drawDefinition:t})?.matchUps??[];if(e.some(({score:t})=>aI({score:t}))&&!S)return P.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=>Sf.includes(t.entryStatus))),U.includes(n)&&(U=U.filter(t=>t!==n),v=!0);const d=al({stageSequence:1,drawDefinition:t,stage:us})?.structures?.[0],p=d?dw({structureId:d.structureId,tournamentRecord:o,drawDefinition:t}):void 0,h=p?.positionAssignments?.map(I),y=al({stage:ds,drawDefinition:t})?.structures,T=y?.length?y.map(e=>{const n=e.stageSequence,r=dw({structureId:e.structureId,tournamentRecord:o,drawDefinition:t}),i=r?.positionAssignments.map(I);return{positionAssignments:i,stageSequence:n}}):void 0,w={action:NC,payload:{drawDefinitions:[t],eventId:s??r?.eventId,auditData:a}};f.push(w),l.push(Ei({tournamentId:o.tournamentId,eventId:s??r?.eventId,qualifyingPositionAssignments:T,positionAssignments:h,auditData:a,drawType:i,drawName:c,drawId:n})),e?.forEach(({matchUpId:t})=>m.push(t))}return!n.includes(t.drawId)});if(P.length&&!c)return Ci({context:{drawIdsWithScoresPresent:P},result:{error:br},stack:e});if(r.drawDefinitions=T,g&&sp({element:r,attribute:"flightProfile",name:ld,value:g}),YA({tournamentRecord:o}),v){const t={};for(const e of U)t[e]=y.drawDetails?.[e]??{published:!0};const e=PC({statusObject:{drawDetails:t},event:r});if(e.error)return{error:e.error}}if(f.length&&function({tournamentId:t,deletedDrawsDetail:e,appliedPolicies:n,auditTrail:r,auditData:i,event:o}){const a=Ii(Il);a&&di({topic:Il,payload:{tournamentId:t,detail:r}});if(ei()||!Zr())return;if(a){const t=Nm({element:o,itemType:dd});nU({element:o,timeItem:{itemType:dd,itemValue:(t?.timeItem?.itemValue||0)+1},removePriorValues:!0})}else!function({appliedPolicies:t,event:e,deletedDrawsDetail:n,auditData:r}){if(!1===t?.audit?.[dd])return;const{extension:i}=td({name:dd,element:e}),o={...r,deletedDrawsDetail:n},a={value:Array.isArray(i?.value)?i?.value.concat(o):[o],name:dd};$u({element:e,extension:a})}({appliedPolicies:n,event:o,deletedDrawsDetail:e,auditData:i})}({tournamentId:o.tournamentId,deletedDrawsDetail:l,appliedPolicies:u,auditTrail:f,auditData:a,event:r}),m.length&&zl({tournamentId:o?.tournamentId,matchUpIds:m}),n.forEach(t=>function({tournamentId:t,eventId:e,drawId:n}){return di({payload:{drawId:n,tournamentId:t,eventId:e},topic:Ul,key:n}),fi({key:n}),{...Y}}({drawId:t})),i&&v){const e=TC({...t.eventDataParams,drawIdsToRemove:n,policyDefinitions:d,tournamentRecord:o,event:r});if(e.error)return{...Y,info:e.error}}return{...Y}}function OC({autoPublish:t=!0,tournamentRecord:e,auditData:n,event:r,force:i}){const o=dl({tournamentRecord:e,event:r},[Ic,zc]);if(o.error)return o;const{flightProfile:a}=Tg({event:r});if(a){const o=a.flights?.map(({drawId:t})=>t).filter(Boolean),s=CC({eventId:r.eventId,tournamentRecord:e,autoPublish:t,auditData:n,drawIds:o,event:r,force:i});return s.error?s:sp({element:r,attribute:"flightProfile",name:ld,value:void 0})}return{...Y}}function kC(t){const{matchUpFormat:e,recoveryTimes:n,averageTimes:r,tournamentId:i,eventId:o}=t,a=t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{};if(!Object.keys(a).length)return{error:nt};const s=Object.keys(a).filter(t=>!i||i===t);if(i&&!s.includes(i))return{error:sr};let c;for(const t of s){const i=a[t],{event:s}=wg({tournamentRecord:i,eventId:o});o&&s&&(c=!0);const u=FC({tournamentRecord:i,event:s,matchUpFormat:e,averageTimes:r,recoveryTimes:n});if(u.error)return u}return!o||c?{...Y}:{error:zt}}function FC({tournamentRecord:t,recoveryTimes:e,matchUpFormat:n,averageTimes:r,event:i}){if(!t)return{error:rt};if(r&&!Array.isArray(r))return{error:sr};if(e&&!Array.isArray(e))return{error:sr};const o=Td;if(i){const{extension:t}=td({element:i,name:o});$u({element:i,extension:{name:o,value:xC({...t?.value??{},matchUpFormat:n,averageTimes:r,recoveryTimes:e})}})}else{Ym({element:t,groupAttribute:"scheduling",leafAttribute:"timing",name:o,value:xC({...Km({element:t,groupAttribute:"scheduling",leafAttribute:"timing",name:o})??{},matchUpFormat:n,averageTimes:r,recoveryTimes:e})})}return{...Y}}function xC(t){const{matchUpRecoveryTimes:e=[],matchUpAverageTimes:n=[],matchUpFormat:r}=t;let{averageTimes:i,recoveryTimes:o}=t;i=(i??[]).filter(t=>t?.categoryNames?.length||t?.categoryTypes?.length);const a=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});o=(o??[]).filter(t=>t?.categoryNames?.length||t?.categoryTypes?.length);const s=o?.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:o});return{matchUpAverageTimes:a?.length&&a||n,matchUpRecoveryTimes:s?.length&&s||e}}function _C(t){const{tournamentRecord:e,recoveryMinutes:r,averageMinutes:i,matchUpFormat:o,categoryType:a,eventId:s,event:c}=t,u=dl({tournamentRecord:e},[Ic]);if(u.error)return u;if(!Io({matchUpFormat:o}))return{error:sr};const d=dl({event:c},[zc]);if(d.error)return d;const{averageTimes:l=[],recoveryTimes:m=[]}=dE({tournamentRecord:e,matchUpFormat:o,event:c}),f=c.category,h=f?.categoryName||f?.ageCategoryCode||c?.eventId;let g={categoryNames:[h],minutes:{}};const I={categoryNames:[h],minutes:{}},S=t=>{if(t.categoryTypes?.includes(a)&&console.log("encountered:",{categoryType:a}),!t.categoryNames?.includes(h)||(t.categoryNames=t.categoryNames.filter(t=>t!==h),g={minutes:t.minutes,categoryNames:[h]},t.categoryNames.length))return t},y=i&&!isNaN(p(i)),v=r&&!isNaN(p(r)),U=l.map(S).filter(t=>t?.categoryNames?.length),P=m.map(S).filter(t=>t?.categoryNames?.length);return y&&(Object.assign(g.minutes,{[c?.eventType||n]:i}),U.push(g)),v&&(Object.assign(I.minutes,{[c?.eventType||n]:r}),P.push(I)),y||v?kC({averageTimes:y&&U,recoveryTimes:v&&P,tournamentRecord:e,matchUpFormat:o,eventId:s}):{error:sr}}function LC(t){if(t.event)return BC({event:t.event});{t.tournamentRecord&&!t.tournamentRecords&&(t.tournamentRecords={[t.tournamentRecord.tournamentId]:t.tournamentRecord});const e=fu(t,[{[hc]:!0,[qc]:!0}]);if(e.error)return e;const{tournamentRecords:n,eventId:r}=t;for(const t of Object.values(n??{})){const{event:e}=wg({tournamentRecord:t,eventId:r});if(e)return BC({event:e})}}return{error:zt}}function BC({event:t}){return Xu({event:t,name:Td})}const VC={MON:"MON",TUE:"TUE",WED:"WED",THU:"THU",FRI:"FRI",SAT:"SAT",SUN:"SUN"};function GC(t){return!!Array.isArray(t)&&(M(t).length===t.length&&t.every(t=>Object.keys(VC).includes(t)))}function jC({tournamentRecord:t,event:e,startDate:n}){const r=dl({tournamentRecord:t,event:e},[Ic,zc]);if(r.error)return r;if(!vo.test(n))return{error:_e};const i=$C(t),o="setEventStartDate";if(i.error)return Ci({result:i,stack:o});const{tournamentStartDate:a,tournamentEndDate:s}=i,c=new Date(Lo(n)).getTime();if(!a||!s||c<a||c>s)return Ci({result:{error:_e},stack:o,info:"startDate must be within tournament start and end dates"});const u=e.endDate&&new Date(Lo(e.endDate)).getTime();return u&&c>u&&(e.endDate=n),e.startDate=n,{...Y}}function qC(t){const{tournamentRecord:e,event:n,endDate:r}=t,i=dl({tournamentRecord:e,event:n},[Ic,zc]);if(i.error)return i;if(!vo.test(r))return{error:_e};const o=$C(e);if(o.error)return o;const{tournamentStartDate:a,tournamentEndDate:s}=o,c=new Date(Lo(r)).getTime();if(!a||!s||c<a||c>s)return{error:_e};const u=n.startDate&&new Date(Lo(n.startDate)).getTime();return u&&c<u&&(n.startDate=r),n.endDate=r,{...Y}}function WC(t){const e="setEventDates",n=fu(t,[{tournamentRecord:!0,event:!0},{[ou]:t=>vo.test(t),[su]:_e,startDate:!1,endDate:!1},{[ou]:t=>t.filter(Boolean).every(t=>vo.test(t)),[su]:_e,activeDates:!1},{[ou]:GC,weekdays:!1}]);if(n.error)return n;const{tournamentRecord:r,weekdays:i,event:o,startDate:a,endDate:s}=t,c=t.activeDates?.filter(Boolean);if(a&&s){if(new Date(Lo(a)).getTime()>new Date(Lo(s)).getTime())return Ci({result:{error:sr},stack:e,info:"startDate cannot be after endDate"})}if(c){const t=a||r.startDate,n=s||r.endDate,i=!t||c.every(e=>new Date(e)>=new Date(t)),o=!n||c.every(t=>new Date(t)<=new Date(n));if(!i||!o)return Ci({result:{error:_e},stack:e})}if(a){const t=jC({tournamentRecord:r,event:o,startDate:a});if(t.error)return Ci({result:t,stack:e})}if(s){const t=qC({tournamentRecord:r,event:o,endDate:s});if(t.error)return Ci({result:t,stack:e})}return c&&(o.activeDates=c),i&&(o.weekdays=i),{...Y}}function $C(t){const{startDate:e,endDate:n}=t;return vo.test(e)&&vo.test(n)?{tournamentStartDate:new Date(Lo(e)).getTime(),tournamentEndDate:new Date(Lo(n)).getTime()}:Ci({result:{error:Be},context:{startDate:e,endDate:n}})}function HC({event:t,orderedDrawIdsMap:e}){if("object"!=typeof t)return{error:Ht};if(!e)return{error:Ae,info:"Missing drawIdsOrderMap"};if("object"!=typeof e)return{error:sr,info:"orderedDrawIdsMap must be an object"};const n=Object.values(e);if(!n.every(t=>!Number.isNaN(Number(t))))return{error:sr,info:"drawOrder must be numeric"};if(M(n).length!==n.length)return{info:"drawOrder values must be unique",error:sr};if(t.drawDefinitions?.length){const n=(t.drawDefinitions??[]).map(({drawId:t})=>t),r=Object.keys(e);if(r?.length&&V(n,r).length!==n.length)return{error:sr,info:"Missing drawIds"};t.drawDefinitions.forEach(t=>{t.drawOrder=e[t.drawId]})}const{flightProfile:r}=Tg({event:t});return r?.flights?.forEach(t=>{t.flightNumber=e[t.drawId]}),{...Y}}function zC({tournamentRecord:t,event:e}){const n=dl({tournamentRecord:t,event:e},[Ic,zc]);if(n.error)return n;const{flightProfile:r}=Tg({event:e}),i=r?.flights?.sort((t,e)=>t.flightNumber-e.flightNumber).map(t=>t.drawId).filter(Boolean),o=e.drawDefinitions?.sort((t,e)=>t.drawOrder-e.drawOrder).map(t=>t.drawId).filter(Boolean).filter(t=>!i?.includes(t)),a=Object.assign({},...[...i??[],...o??[]].map((t,e)=>({[t]:e+1})));return a?HC({event:e,orderedDrawIdsMap:a}):{...Y}}function YC({autoPublish:t=!0,tournamentRecord:e,auditData:n,drawId:r,event:i,force:o}){const a=dl({tournamentRecord:e,drawId:r,event:i},[Ic,$c,zc]);if(a.error)return a;const{flightProfile:s}=Tg({event:i});if(s){const t=s.flights?.find(t=>t.drawId===r);if(t){const t=s.flights.filter(t=>t.drawId!==r);sp({element:i,attribute:"flightProfile",name:ld,value:{...s,flights:t}})}}const c=i.drawDefinitions?.find(t=>t.drawId===r);if(c){const a=CC({drawIds:[r],eventId:i.eventId,tournamentRecord:e,autoPublish:t,auditData:n,event:i,force:o});if(a.error)return a}return zC({tournamentRecord:e,event:i})}function KC(t){const e=fu(t,[{[zc]:!0,[Ic]:!0,[Kc]:!1},{replacementIndividualParticipantId:!0,[ou]:t=>m(t),existingIndividualParticipantId:!0,[Hc]:sn,participantId:!0}]),{replacementIndividualParticipantId:n,existingIndividualParticipantId:r,tournamentRecord:i,drawDefinition:o,participantId:a,event:s,uuids:c}=t;if(e.error)return e;if(s?.eventType!==ns)return{error:$t};const u=s?.entries?.filter(({entryStatus:t})=>[pf,lf].includes(t)).map(({participantId:t})=>t)??[];if(!u.includes(n))return{error:Ze};const d=(i.participants??[]).find(t=>t.participantId===a);if(d?.participantType!==Sm)return{error:Xe,participant:d};const p=d.individualParticipantIds,l=[n,...p.filter(t=>t!==r)],{participant:f}=bg({participantIds:l,tournamentRecord:i});let h;if(f)h=f.participantId;else{const t=mC({participant:{participantId:c?.pop(),participantRole:sy,individualParticipantIds:l,participantType:Sm},returnParticipant:!0,tournamentRecord:i});if(t.error)return t;h=t.participant.participantId}const{flightProfile:g}=Tg({event:s});if(o){const t=g?.flights?.find(({drawId:t})=>t===o.drawId);t&&(t.drawEntries=t.drawEntries.map(t=>t.participantId===a?{...t,participantId:h}:t)),o.entries=o.entries.map(t=>t.participantId===a?{...t,participantId:h}:t);for(const t of o.structures??[])if(t.structures){t.positionAssignments=void 0;for(const e of t.structures)e.positionAssignments=e.positionAssignments.map(t=>t.participantId===a?{...t,participantId:h}:t)}else t.positionAssignments&&(t.positionAssignments=t.positionAssignments.map(t=>t.participantId===a?{...t,participantId:h}:t))}s.entries=s.entries.map(t=>t.participantId===a&&{...t,participantId:h}||t.participantId===n&&{...t,participantId:r}||t);const I=i.events.some(({entries:t,eventId:e,drawDefinitions:n})=>s.eventId===e?n.some(({drawId:t,entries:e})=>t!==o?.drawId&&e?.find(t=>t.participantId===a)):t?.find(t=>t.participantId===a));if(!I){const t=yy({addIndividualParticipantsToEvents:!1,participantIds:[a],tournamentRecord:i});if(t.error)return t}return{...Y,participantOtherEntries:I,newPairParticipantId:h}}function QC(t){const{flight:e,suppressNotifications:n,modifyEventEntries:r,existingDrawCount:i,allowReplacement:o,checkEntryStatus:a,tournamentRecord:s,drawDefinition:c,event:u}=t;if(!c)return{error:st};if(!u)return{error:Ht};u.drawDefinitions??=[];const{drawId:d,drawName:l,entries:m}=c,{entries:f}=u;let h=0;if(void 0!==i&&i!==u.drawDefinitions.length)return{error:sr,info:"drawDefintions count mismatch"};const{flightProfile:g}=Tg({event:u}),I=e&&g?.flights?.find(t=>t.flightNumber===e.flightNumber),S=g?.links?.find(t=>t?.target?.drawId===d)?.source?.drawId,y=S&&!u.drawDefinitions.some(t=>t.drawId===S);if(y)return Ci({result:{error:st},info:{sourceDrawId:S}});if(I&&I.drawId!==c.drawId)return Ci({result:{error:at},info:{relevantFlight:I}});const v=function({drawEntries:t,eventEntries:e,relevantFlight:n,checkEntryStatus:r}){const i=t?.every(({participantId:t,entryStatus:e})=>{const r=n?.drawEntries.find(e=>e.participantId===t);return!e||r?.entryStatus===e}),o=!r||e&&t?.every(({participantId:t,entryStatus:n,entryStage:r})=>{const i=e.find(e=>e.participantId===t&&(!e.entryStage||e.entryStage===r));return i?.entryStatus===n});if(n&&!i)return Ci({result:{error:at},context:{drawEntriesPresentInFlight:i,matchingEventEntries:o,relevantFlight:n},info:"Draw entries are not present in flight or do not match entryStatuses"});return{drawEntriesPresentInFlight:i,matchingEventEntries:o}}({drawEntries:m,eventEntries:f,relevantFlight:I,checkEntryStatus:a});if(v?.error)return v;const{matchingEventEntries:U}=v;if(r&&(h=function({drawEntries:t,eventEntries:e}){let n=0;return t?.filter(Boolean).forEach(t=>{if(t?.entryStatus&&Sf.includes(t?.entryStatus)){const r=e?.filter(Boolean).find(e=>e.participantId===t.participantId);r&&t.entryStatus&&r?.entryStatus!==t.entryStatus&&(r.entryStatus=t.entryStatus,n+=1)}}),n}({drawEntries:m,eventEntries:f})),f&&!U)return Ci({result:{info:"Draw entries do not match event entryStatuses",context:{matchingEventEntries:U,eventEntries:f},error:at}});const P=g?.flights?.map(({flightNumber:t})=>!Number.isNaN(Number(t))&&p(t))?.filter(Boolean)??[],T=u.drawDefinitions.map(({drawOrder:t})=>t&&p(t))?.filter(Boolean)||[];let w=Math.max(0,...T,...P)+1;const D=g?.flights?.find(t=>t.drawId===d);let R;if(D){D.drawName=c.drawName,R={...g,flights:g.flights};const t=D.flightNumber;t&&!T.includes(t)?w=t:D.flightNumber=w}else{const t=g?.flights??[];t.push({manuallyAdded:!0,flightNumber:w,drawEntries:m,drawName:l,drawId:d}),R={...g,flights:t}}sp({element:u,attribute:"flightProfile",name:ld,value:R}),Object.assign(c,{drawOrder:w});const b=u.drawDefinitions.find(t=>t.drawId===d),N=s?.tournamentId,M=u.eventId;if(b){if(!o)return{error:Nt};!function({existingDrawDefinition:t,suppressNotifications:e,drawDefinition:n,tournamentId:r,eventId:i,event:o,drawId:a}){const s=Zg({drawDefinition:t})?.matchUps,c=s?.map(tl)??[],u=Zg({drawDefinition:n})?.matchUps;if(!e){c?.length&&zl({matchUpIds:c,action:"modifyDrawDefinition",tournamentId:r,eventId:i}),u?.length&&Hl({matchUps:u,tournamentId:r,eventId:i}),o.drawDefinitions=o.drawDefinitions.map(t=>t.drawId===a?n:t);const t=n.structures?.map(({structureId:t})=>t);Ql({drawDefinition:n,tournamentId:r,structureIds:t,eventId:i})}}({existingDrawDefinition:b,suppressNotifications:n,drawDefinition:c,tournamentId:N,eventId:M,event:u,drawId:d})}else!function({suppressNotifications:t,tournamentRecord:e,drawDefinition:n,tournamentId:r,eventId:i,event:o}){if(o.drawDefinitions.push(n),!t){const{matchUps:t}=Zg({drawDefinition:n,event:o});t&&Hl({tournamentId:e?.tournamentId,matchUps:t}),Kl({drawDefinition:n,tournamentId:r,eventId:i})}}({suppressNotifications:n,tournamentRecord:s,drawDefinition:c,tournamentId:N,eventId:M,event:u});return{...Y,modifiedEventEntryStatusCount:h}}function JC(t){const{provisionalPositioning:e,useExistingSeedLimit:n,tournamentRecord:r,drawDefinition:i,seedingProfile:o,structureId:a,assignments:s,drawId:c,event:u}=t;let d=0;if(!s?.length)return{error:Jt};const p=dl({tournamentRecord:r,drawId:c},[Ic,$c]);if(p.error)return p;const l=Tf({provisionalPositioning:e,drawDefinition:i,structureId:a});if(l.error)return l;const{seedAssignments:m,seedLimit:f}=l,h=Object.assign({},...(m??[]).filter(t=>t.seedNumber).map(t=>({[t.seedNumber]:t})));s.forEach(t=>{const{seedNumber:e}=t;f&&e<=f&&(!n||h[e])&&(h[e]=t)});const g=Object.values(h),I=g.map(t=>t?.participantId).filter(Boolean);if(I.length!==F(I).length)return{error:Mt};for(const t of g){const n=zy({...t,provisionalPositioning:e,tournamentRecord:r,drawDefinition:i,seedingProfile:o,structureId:a,event:u});if(n?.error)return n;n?.success&&d++}return d?{...Y,modifications:d}:{error:Zn}}function XC({deleteExisting:t,event:e,flightProfile:n}){const r="attachFlightProfile";if(!n)return Ci({result:{error:Ae},stack:r});if(!e)return Ci({result:{error:Ht},stack:r});const{flightProfile:i}=Tg({event:e});return i&&!t?Ci({result:{error:gr},stack:r}):e.drawDefinitions?.length?Ci({result:{error:ct},stack:r}):(sp({element:e,attribute:"flightProfile",name:ld,value:n}),{flightProfile:ca(n,!1,!0),...Y})}function ZC({tournamentRecord:t,scaleAttributes:e,drawDefinition:n,entryStatuses:r,drawId:i,event:o,stage:a}){if(!o)return{error:Ht};if(r&&!Array.isArray(r))return Ci({result:{error:sr},info:nv("entryStatus"),stack:"removeScaleValues"});let s=o.entries;if(i){const{flightProfile:t}=Tg({event:o}),e=t?.flights?.find(t=>t.drawId===i);s=e?e.drawEntries:n?.entries}return function({tournamentRecord:t,scaleAttributes:e,participantIds:n}){const r=dl({tournamentRecord:t},[Ic]);if(r.error)return r;if(!n)return{error:ln};if(!e)return{error:Ae,info:"scaleAttributes required"};const{scaleType:i,eventType:o,scaleName:a}=e,s=[Sh,i,o,a].join(".");return t.participants?.forEach(t=>{n.includes(t.participantId)&&t.timeItems&&(t.timeItems=t.timeItems.filter(t=>t&&t?.itemType!==s))}),{...Y}}({tournamentRecord:t,scaleAttributes:e,participantIds:(s??[]).filter(t=>(!a||!t.entryStage||t.entryStage===a)&&(!r||r.includes(t.entryStatus))).map(Xp)})}function tO({removePriorValues:t,tournamentRecord:e,displaySettings:n,status:r=Th,event:i}){if(!e)return Ci({result:{error:rt}});if(!i)return Ci({result:{error:Ht}});if(!f(n))return Ci({result:{error:Ae}});if(f(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=>h(e.attributes,t.attributes));e?.dates&&t.dates?e.dates.push(...t.dates):r.push(t)}n.draws[t].scheduleDetails=r}}const o=PC({statusObject:{displaySettings:n},removePriorValues:t,status:r,event:i});return o.error?o:{...Y}}function eO({tournamentRecord:t,drawDefinition:e,entryStatuses:n,scaleName:r,drawId:i,event:o,stage:a}){const s=dl({tournamentRecord:t,event:o},[Ic,zc]);if(s.error)return s;r=r||o.category?.categoryName||o.category?.ageCategoryCode;return ZC({tournamentRecord:t,scaleAttributes:{eventType:o.eventType,scaleType:vu,scaleName:r},drawDefinition:e,entryStatuses:n,drawId:i,event:o,stage:a})}function nO(t){const e=fu(t,[{[Ic]:!0},{eventIds:!0,[cu]:iu}]);if(e.error)return e;const{removePairParticipants:n,tournamentRecord:r,eventIds:i}=t,o=[],a=[],s=[],c=[];if(r.events=(r.events??[]).filter(t=>{if(i.includes(t.eventId)){const e={action:AC,payload:{events:[t]}};o.push(e),a.push({tournamentId:r.tournamentId,eventName:t.eventName,eventType:t.eventType,category:t.category,eventId:t.eventId,gender:t.gender})}const e=t.eventType===ns?(t.entries??[]).map(({entryStatus:t,participantId:e})=>t!==pf&&e).filter(Boolean):[],n=i.includes(t.eventId);return n?c.push(...e):s.push(...e),!n}),n){const t=new Set(c.filter(t=>!s.includes(t)));r.participants=r.participants.filter(({participantId:e})=>!t.has(e))}if(YA({tournamentRecord:r}),o.length)if(Ii(Il)){const t=r.tournamentId;di({topic:Il,payload:{type:AC,tournamentId:t,detail:o}})}else{iU({tournamentRecord:r,timeItem:{itemValue:a,itemType:AC}})}return{...Y}}function rO(t){const e=fu(t,[{tournamentRecord:!0,eventId:!0,event:!0},{eventUpdates:!0,_ofType:ru}]);if(e.error)return e;const{eventUpdates:n,event:r}=t,i="modifyEvent",o=function(t){const{tournamentRecord:e,event:n}=t,r=n?.entries?.filter(({entryStatus:t})=>{const e=t;return[...Sf,ef].includes(e)}).map(({participantId:t})=>t)??[];return r?xS({participantFilters:{participantIds:r},withIndividualParticipants:!0,tournamentRecord:e}).participants??[]:[]}(t),a=function({enteredParticipants:t}){const e=[],n=t.reduce((t,n)=>{const r=n.person?.sex?[n.person.sex]:n.individualParticpants?.map(t=>t.person?.sex)??[];return e.push(...r),t.includes(n.participantType)?t:t.concat(n.participantType)},[]),r=M(e);return{enteredParticipantTypes:n,enteredParticipantGenders:r}}({enteredParticipants:o}),{enteredParticipantGenders:s,enteredParticipantTypes:c}=a,u=Tg({event:r})?.flightProfile?.flights,d=function({noFlightsNoDraws:t,enteredParticipantGenders:e,eventUpdates:n,stack:r}){const i=!e.length||!n.gender||Hi(n.gender)||1===e.length&&e[0]===n.gender||t&&$i(n.gender);return n.gender&&!i?Ci({context:{gender:n.gender,validGender:i},result:{error:or},stack:r}):{...Y}}({noFlightsNoDraws:!r.drawDefinitions?.length&&!u?.length,enteredParticipantGenders:s,eventUpdates:n,stack:i});if(d.error)return d;const p=function({enteredParticipantTypes:t,eventUpdates:e,stack:n}){const r=t.includes(gm)&&t.includes(Sm),i=r&&[as]||t.includes(is)&&[is]||t.includes(gm)&&[ts,as]||t.includes(Sm)&&[ns,as]||[ns,ts,is,as],o=i.includes(e.eventType??"");return e.eventType&&!o?Ci({context:{participantType:e.eventType,validEventType:o},result:{error:$t},stack:n}):{...Y}}({enteredParticipantTypes:c,eventUpdates:n,stack:i});if(p.error)return p;const l=function(t){const e=t.eventUpdates?.category;if(!e)return{...Y};const n=Zo({category:e});if(n.error)return n;if(t.event.eventType===is){const e=function(t){const e=t.event?.drawDefinitions?.map(t=>wf(t))??[],n=wf(t.event),r=Kg(t)?.matchUps??[],i=r.map(t=>wf(t))??[],o=[n,...e,...i].filter(Boolean),a=o.every(e=>e.collectionDefinitions.every(e=>!e.category||ta({category:t.eventUpdates.category,childCategory:e.category})));return a?{...Y}:Ci({result:{error:ar},stack:t.stack})}(t);if(e.error)return e}if(t.enteredParticipants?.length){const n=function(t,e){const n=t.eventUpdates.startDate||t.event.startDate||t.tournamentRecord.startDate,r=t.eventUpdates.endDate||t.event.endDate||t.tournamentRecord.endDate,i=t.enteredParticipants.flatMap(t=>t.participantType===gm?[t]:t.individualParticpants??[]),o=Xo({category:e,consideredDate:n}),a=Xo({category:e,consideredDate:r});if(o?.ageMinDate||o?.ageMaxDate||a?.ageMinDate||a?.ageMaxDate)for(const e of i){const n=e.person?.birthDate,r=e.person?.birthYear;if(!n&&void 0===r)return Ci({result:{error:Ee},stack:t.stack});const i=new Date(n??`${r}-07-01`).getTime(),s=iO(i,o,t.stack);if(s)return s;const c=iO(i,a,t.stack);if(c)return c}return{...Y}}(t,e);if(n.error)return n}return{...Y}}({...t,...a,enteredParticipants:o,stack:i});if(l.error)return l;const m=function(t){const{tournamentRecord:e,eventUpdates:n,event:r,stack:i}=t;if(n.startDate||n.endDate){const t=WC({startDate:n.startDate||r.startDate||e.startDate,endDate:n.endDate||r.endDate||e.endDate,tournamentRecord:e,event:r});if(t.error)return Ci({result:t,stack:i})}return{...Y}}({...t,stack:i});return m.error?m:(n.eventType&&(r.eventType=n.eventType),n.eventName&&(r.eventName=n.eventName),n.gender&&(r.gender=n.gender),{...Y})}function iO(t,e,n){if(!e)return null;if(e.ageMinDate||e.ageMaxDate){const r=new Date(e.ageMinDate).getTime(),i=new Date(e.ageMaxDate).getTime();if(t<r||t>i)return Ci({result:{error:Qe},stack:n})}return null}function oO({qualifyingPositions:t,drawEntries:e=[],drawName:n,drawId:r,event:i,stage:o}){const a="addFlight";if(!i)return Ci({result:{error:Ht},stack:a});if(!n)return Ci({result:{error:Ae},stack:a});if(e?.length){const t=(i.entries??[]).map(Xp),n=e.map(Xp);if(V(n,t).length!==n.length)return Ci({result:{error:sr},stack:a})}const s=Tg({event:i})?.flightProfile,c=s?.flights?.map(({flightNumber:t})=>!Number.isNaN(Number(t))&&p(t))?.filter(Boolean)??[],u=Math.max(0,...c)+1,d={drawId:r||pa(),flightNumber:u,drawEntries:e,drawName:n};o&&(d.stage=o),t&&(d.qualifyingPositions=t);const l=(s?.flights??[]).find(({drawId:t})=>t===d.drawId);if(l)return Ci({result:{error:hr},stack:a});const m=(s?.flights??[]).concat(d);return sp({element:i,attribute:"flightProfile",name:ld,value:{...s,flights:m}})}var aO={__proto__:null,addDrawDefinition:QC,addEvent:yC,addFlight:oO,assignSeedPositions:JC,attachFlightProfile:XC,categoryCanContain:ta,deleteDrawDefinitions:CC,deleteEvents:nO,deleteFlightAndFlightDraw:YC,deleteFlightProfileAndFlightDraws:OC,generate:{__proto__:null,generateEventsFromTieFormat:vC},generateEventsFromTieFormat:vC,getCategoryAgeDetails:Xo,getEvent:zE,getEventProperties:GE,getEventStructures:vU,getEventTimeItem:Am,getEvents:HE,getFlightProfile:Tg,getScaledEntries:LN,modifyEvent:rO,modifyEventMatchUpFormatTiming:_C,modifyPairAssignment:KC,mutate:{__proto__:null,addDrawDefinition:QC,addEvent:yC,addFlight:oO,assignSeedPositions:JC,attachFlightProfile:XC,deleteDrawDefinitions:CC,deleteEvents:nO,deleteFlightAndFlightDraw:YC,deleteFlightProfileAndFlightDraws:OC,modifyEvent:rO,modifyEventMatchUpFormatTiming:_C,modifyPairAssignment:KC,refreshEventDrawOrder:zC,removeEventMatchUpFormatTiming:LC,removeScaleValues:ZC,removeSeeding:eO,setEventDates:WC,setEventDisplay:tO,setEventEndDate:qC,setEventStartDate:jC,updateDrawIdsOrder:HC,validateCategory:Zo},query:{__proto__:null,categoryCanContain:ta,getCategoryAgeDetails:Xo,getEvent:zE,getEventProperties:GE,getEventStructures:vU,getEventTimeItem:Am,getEvents:HE,getFlightProfile:Tg,getScaledEntries:LN},refreshEventDrawOrder:zC,removeEventMatchUpFormatTiming:LC,removeScaleValues:ZC,removeSeeding:eO,setEventDates:WC,setEventDisplay:tO,setEventEndDate:qC,setEventStartDate:jC,updateDrawIdsOrder:HC,validateCategory:Zo};const sO="splitWaterfall",cO="splitShuttle",uO={SPLIT_LEVEL_BASED:"splitLevelBased",SPLIT_WATERFALL:sO,SPLIT_SHUTTLE:cO};function dO({json:t,tagName:e}){const n=Object.keys(t).filter(e=>Array.isArray(t[e])).map(e=>({key:e,value:t[e].filter(t=>"object"==typeof t&&1===Object.keys(t).length)})),r=Object.keys(t).filter(e=>"object"==typeof t[e]&&!Array.isArray(t[e])).map(e=>({key:e,value:t[e]}));return pO({tagName:e,attributes:Object.keys(t).filter(e=>["string","number"].includes(typeof t[e])).map(e=>({key:e,value:t[e]})),childArrays:n,childObjects:r})}function pO(t){const{tagName:e,attributes:n=[],childArrays:r=[],childObjects:i}=t,o="\r\n",a=t=>{const e=Object.keys(t)[0];return{key:e,value:t[e]}},s=r?.map(({key:t,value:e})=>pO({tagName:t,childObjects:e.map(a)})).join("\r\n"),c=i?.map(({key:t,value:e})=>dO({tagName:t,json:e??[]})).join("\r\n"),u=n?.map(({key:t,value:e})=>`${t}="${e}"`).join(" ");if("childArray"===e)return c;return`<${e}${u?` ${u}`:""}>${c?.length?`${o}${c}${o}`:""}${s?.length?`${o}${s}${o}`:""}</${e}>`}function lO({teamParticipants:t,mappedMatchUps:e,participantMap:n,tournamentName:r,tournamentId:i,teamMatchUp:o,tournament:a,startDate:s,doubles:c,singles:u}){const d=t?.find(t=>t.participantRoleResponsibilities?.includes("Home")),p=t?.filter(t=>t.participantId!==d?.participantId),l=bo(s,"/","MDY"),m=d?.participantName||p?.[1]?.participantName,f=d?.participantId||p?.[1]?.participantId,h=p?.[0]?.participantName,g=p?.[0]?.participantId,I={},S=t.map(t=>({team:{...fO({teamParticipant:t,teamMatchUp:o,uniValues:I,participantMap:n,mappedMatchUps:e,homeid:f})}})),y=Ei({venue:{tournamentname:a?r:void 0,neutralgame:d?"N":"Y",gameid:i,officials:{},tournament:a,rules:{},homename:m,visname:h,homeid:f,visid:g,date:l},childArray:S,singles_matches:u?.map(t=>hO({matchUp:t,homeid:f,uniValues:I})),doubles_matches:c?.map(t=>hO({matchUp:t,homeid:f,uniValues:I}))});return{json:y,xml:dO({json:y,tagName:"tngame"})}}function mO({homeid:t,uniValues:e,participant:n}){if(!n)return{};const r=2===n.individualParticipants?.length,i=r?M(n.individualParticipants?.map(t=>t.teams?.[0]?.participantId)):[],o=r?M(n.individualParticipants?.map(t=>t.teams?.[0]?.teamId)):[],a=!r&&n.teams?.[0]?.participantId||1===i?.length&&i[0]||void 0,s=!r&&n.teams?.[0]?.teamId||1===o?.length&&o[0]||a,c=r?void 0:n.participantName,u=n.individualParticipants?.[0]?.participantName,d=n.individualParticipants?.[1]?.participantName;return Ei({vh:t&&(a===t?"H":"V")||"",uni:r?void 0:e[a][n.participantId],uni_1:e[a][n.individualParticipants?.[0]?.participantId],uni_2:e[a][n.individualParticipants?.[1]?.participantId],team:s,name:c,name_1:u,name_2:d})}function fO({teamParticipant:t,teamMatchUp:e,participantMap:r,mappedMatchUps:o,homeid:a,uniValues:s}){const{participantId:c,participantName:u}=t,d=a&&(c===a?"H":"V")||"",p=r?.[c]?.matchUps,l=p&&Object.keys(p),m=e?.sides?.find(({participant:t})=>t.participantId===c)?.sideNumber,f=e?.score?.sets?.[0]?.[`side${m}Score`]??0;s[c]={};const h={SINGLES:{w:0,l:0},DOUBLES:{w:0,l:0}},g=[],I=[];let S=0;for(const t of l??[]){const e=o?.[t],r=e.sides.find(({participant:t})=>t.participantId===c)?.sideNumber;S+=e.score?.sets?.[0]?.[`side${r}Score`]??0;for(const t of e.tieMatchUps??[]){const{matchUpType:e,winningSide:o}=t,a=o&&(o===r?"w":"l")||"";a&&(h[e][a]+=1);const s="w"===a?"1":"0",c="l"===a?"1":"0";if(e===n){const t=I.length+1;I.push({singles_pair:{pair:t,won:s,lost:c,tied:"0"}})}else if(e===i){const t=g.length+1;g.push({doubles_pair:{pair:t,won:s,lost:c,tied:"0"}})}}}const y=[{singles:{childArray:I,won:h.SINGLES.w,lost:h.SINGLES.l}},{doubles:{childArray:g,won:h.DOUBLES.w,lost:h.DOUBLES.l}}],v=[];let U=1;for(const e of t.individualParticipantIds){const t=r?.[e];if(t){const{participant:e,counters:n}=t,r={won:n?.DOUBLES?.wins||0,lost:n?.DOUBLES?.losses||0},i={won:n?.SINGLES?.wins||0,lost:n?.SINGLES?.losses||0},{participantName:o,participantId:a}=e;s[c][a]=U,v.push({player:{name:o,uni:U,singles:i,doubles:r}})}U+=1}return{vh:d,id:c,name:u,score:f||S,totals:y,childArray:v}}function hO({matchUp:t,homeid:e,uniValues:r}){const{collectionPosition:i,orderOfFinish:o,matchUpType:a,sides:s}=t??{},c=s?.map(i=>{const{sideNumber:o,participant:s}=i,c=function({sets:t,sideNumber:e}){return Object.assign({},...t?.map(t=>{const{setNumber:n,side1Score:r,side2Score:i,side1TiebreakScore:o,side2TiebreakScore:a}=t,s=`set_${n}`,c=`tie_${n}`,u=1===e?r:i,d=1===e?o:a;return{[s]:u,[c]:d}})??[])}({sets:t.score?.sets,sideNumber:o}),u=a===n?"singles_score":"doubles_score";return{[u]:{...mO({homeid:e,uniValues:r,participant:s}),...c}}}),u=a===n?"singles_match":"doubles_match";return{[u]:{match:i,order:o,childArray:c}}}const gO="DESC",IO={ASC:"ASC",ASCENDING:"ASC",DESC:"DESC",DESCENDING:gO};function SO(t){let{tieFormat:n}=t;const{useDefaultEventRanking:i,tournamentRecord:o,drawDefinition:a,scaleAccessor:s,singlesOnly:c,attach:u,event:d}=t;if(d?.eventType!==os)return{error:$t};if(!o)return{error:rt};if(!n&&!a)return{error:ut};if(n=n??Rf({drawDefinition:a,event:d})?.tieFormat,na({tieFormat:n}).error)return{error:ue};if("object"!=typeof s&&!i)return{error:sr,context:{scaleAccessor:s}};const p={},l=(a?.entries??d?.entries??[]).filter(t=>t?.entryStatus===rf).map(Xp),{participants:m=[]}=xS({withIndividualParticipants:!0,withScaleValues:!0,tournamentRecord:o}),f=m.filter(({participantId:t})=>l.includes(t)),h=d?.category?.categoryName??d?.category?.ageCategoryCode,{scaleName:g=h,scaleType:I=Iu,sortOrder:S,accessor:y}=s??{},v=I===Iu?"rankings":"ratings";const U=(t,n)=>{let r=t[v]?.[n];if(!r&&i&&(r=t[v]?.[e]),Array.isArray(r)){const t=r.find(t=>t.scaleName===g)?.scaleValue;if(P(t))return t;if(y&&"object"==typeof t)return t[y]}return 0},T=(t,e,n)=>{const r=S===gO?t:e;return U(S===gO?e:t,n)-U(r,n)},w=(t,n)=>T(t,n,e),D=(t,e)=>T(t,e,r),R=[],b=n?.collectionDefinitions??[];for(const t of f){const n=t.individualParticipants?.sort(w)??[],r=c?n:t.individualParticipants?.sort(D)??[],i={};for(const t of b){const o=[],{collectionId:a,matchUpCount:s,matchUpType:c,gender:u}=t,d=bh(e)(c);L(0,s).forEach(t=>{const e=d?n:r??[],s=t+1,c=[];L(0,d?1:2).forEach(t=>{const n=e?.find(e=>{const n=zi(u),r=n&&(Yi(u)&&n||$i(u)&&[Vi,_i][t]);return!(r&&r!==e.person?.sex||o.includes(e.participantId))})?.participantId;n&&(c.push(n),o.push(n),i[n]||(i[n]=[]),i[n].push({collectionPosition:s,collectionId:a}))}),d||R.push(c)})}const o=Object.keys(i).map(t=>({collectionAssignments:i[t],participantId:t}));p[t.participantId]=o}const N=[];for(const t of R){const{participant:e}=bg({tournamentParticipants:m,participantIds:t});if(!e){const e={individualParticipantIds:t,participantRole:sy,participantType:Sm};N.push(e)}}if(u){for(;N.length;)mC({participant:N.pop(),tournamentRecord:o});sp({element:a,attribute:"lineUps",name:fd,value:p})}return{...Y,lineUps:p,participantsToAdd:N}}function yO(t){if(!t)return{error:Ae};const e=fu(t,[{dates:!1,[ou]:t=>Array.isArray(t)&&t.every(Do)},{uuids:!1,[ou]:t=>Array.isArray(t)&&t.every(m)},{startTime:!1,endTime:!1,[ou]:ko},{idPrefix:!1,namePrefix:!1,[ou]:m},{count:!0,[ou]:P}]);if(e.error)return e;const{startDate:n,endDate:r}=t.tournamentRecord??{},i=t.dates??(n&&r?Ao(n,r):[]),o=L(1,t.count+1).map(e=>Ei({courtId:t.uuids?.pop()??(t.idPrefix&&`${t.idPrefix}-${e}`)??pa(),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{...Y,courts:o}}function vO(t){const e=fu(t,[{courtDate:!0,_ofType:ru}]);if(e.error)return e;const{includeBookingTypes:n=[],courtDate:r}=t,i=[];let o=Wo(r.startTime);(r.bookings??[]).filter(t=>!t.bookingType||!n.includes(t.bookingType)).sort((t,e)=>(xo(t.startTime)||"").localeCompare(xo(e.startTime)||"")).forEach(t=>{const e={startTime:_o(o.toISOString()),endTime:t.startTime};Wo(t.startTime)>o&&i.push(e),Wo(t.endTime)>o&&(o=Wo(t.endTime))});const a={startTime:_o(o.toISOString()),endTime:r.endTime};return Wo(r.endTime)>o&&i.push(a),{timeSlots:i}}function UO(t){const e=fu(t,[{periodStart:!0,date:!0},{courts:!0,_ofType:iu}]);if(e.error)return e;const{averageMatchUpMinutes:n,includeBookingTypes:r,periodStart:i,date:o}=t,a=t.courts,s=Wo(i),c=zo(s,n),{enoughTime:u}=function({averageMatchUpMinutes:t,includeBookingTypes:e,periodStartTime:n,periodEndTime:r}){function i(e){const i=Wo(e.startTime),o=Wo(e.endTime);return!(i>n)&&(!(o<r)&&$o(n,o)>=t)}return{enoughTime:t=>{const{timeSlots:n}=vO({includeBookingTypes:e,courtDate:t}),r=n?.filter(i);return!!r?.length}}}({averageMatchUpMinutes:n,includeBookingTypes:r,periodStartTime:s,periodEndTime:c});return{availableToScheduleCount:(a?.filter(t=>{if(!Array.isArray(t.dateAvailability))return!1;const e=eE({date:o,court:t});return!(!e||!u(e))})??[]).length,...Y}}function PO(t){const{remainingScheduleTimes:e=[],clearScheduleDates:n,periodLength:r=30,scheduleDate:i,courts:o=[]}=t;let{bookings:a=[]}=t;if(!Array.isArray(o)||!o.length)return{error:sr,courts:o};if(!Array.isArray(a))return{error:ke};if(!Do(i))return{error:_e};n&&(Array.isArray(n)?n.includes(i)&&(a=[]):a=[]);const{courtBookings:s,unassignedBookings:c}=a.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=o.map((t,n)=>{const{courtId:r,courtName:o}=t,a=s[r]??[],c=eE({date:i,court:t})??{},{bookings:u=[],startTime:d,endTime:p,date:l}=c;return{courtId:r,courtName:o,dateAvailability:{bookings:[e[n]&&{startTime:d,endTime:e[n]},...ca(u,!1,!0),...a].filter(Boolean),startTime:d,endTime:p,date:l}}});c.sort((t,e)=>Fo(t.startTime)-Fo(e.startTime));const d=()=>u.flatMap(t=>{const e=t.dateAvailability,{timeSlots:n=[]}=vO({courtDate:e});return{courtName:t.courtName,courtId:t.courtId,timeSlots:n}}),p=[];for(const t of c){const{startTime:e,endTime:n,averageMinutes:i,recoveryMinutes:o,matchUpId:a}=t,s=Fo(e),c=Fo(n),l=d().reduce((t,{courtId:e,courtName:n,timeSlots:i})=>{let o;const a=i.find(({startTime:e,endTime:n})=>{o=Fo(e)-s;const i=s>=Fo(e);return c<=Fo(n)&&0!==t.startDifference&&((0===o||o+r>=0)&&(void 0===t.startDifference||o<t.startDifference)||i)});return a?{courtName:n,courtId:e,startDifference:o}:t},{});if(l.courtId){const t={averageMinutes:i,recoveryMinutes:o,matchUpId:a,startTime:e,endTime:n};p.push(t);const r=u.find(({courtId:t})=>t===l.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:p}}function TO({averageMatchUpMinutes:t,periodLength:e=30,recoveryMinutes:n}){const r=(t||90)+(n||0);return e>r?r:e||30}function wO(t){const{startTime:e="8:00",endTime:n="20:30",count:r=10,date:i}=t??{};return L(0,r).map(()=>({dateAvailability:[{date:i,startTime:e,endTime:n}]}))}function DO({scheduleDate:t,startTime:e,endTime:n,courts:r}){const i=(e?"startTime":n&&"endTime")||void 0;return r.reduce((r,o)=>{const a=eE({date:t,court:o}),s=i&&(a?.[i]||o[i]);return s&&(!r||e&&Fo(s)<Fo(r)||n&&Fo(s)>Fo(r))?s:r},void 0)}function RO(t){const e=fu(t,[{courts:!0,_ofType:iu}]);if(e.error)return e;let{date:n=Ro(),startTime:r="08:00",endTime:i="19:00",periodLength:o,courts:a}=t;const{calculateStartTimeFromCourts:s=!0,remainingScheduleTimes:c,averageMatchUpMinutes:u,clearScheduleDates:d,courtsCount:l,bookings:m}=t;o=o||TO({averageMatchUpMinutes:u}),n=Lo(n),r=_o(r),i=_o(i);let f=0,h=0,g=0,I=0,S=0;!a&&l&&(a=wO({startTime:r,endTime:i,count:l,date:n}));const{virtualCourts:y}=PO({remainingScheduleTimes:c,clearScheduleDates:d,scheduleDate:n,periodLength:o,bookings:m,courts:a}),{firstTimeSlotStartTime:v}=function({averageMinutes:t,startTime:e,endTime:n,courts:r,date:i}){let o;if(e=e||DO({courts:r,scheduleDate:i,startTime:!0}),n=n||DO({courts:r,scheduleDate:i,endTime:!0}),e&&n){const a=Wo(e),s=Wo(n);for(const e of r??[]){if(!Array.isArray(e.dateAvailability))continue;const n=eE({court:e,date:i}),{timeSlots:r}=vO({courtDate:n});r?.forEach(e=>{const n=Wo(e.startTime),r=Wo(e.endTime);if(n>s||n<a)return!1;if(r<a)return!1;if($o(n,r)>=t){const t=_o(n.toISOString());t&&(!o||t<o)&&(o=t)}})}}return{firstTimeSlotStartTime:o}}({averageMinutes:u,courts:y,startTime:r,endTime:i,date:n});s&&v&&(r=v??r);const U=Fo(r),P=Fo(i)-U,T=L(0,Math.floor(P/o)+1).map(t=>{const e=function(t){let e=Math.floor(t/60);const n=t-60*e;return e>23&&(e%=24),[Yo(e),Yo(n)].join(":")}(U+t*o),r=UO({courts:y??[],averageMatchUpMinutes:u,periodStart:e,date:n});if(r.error)return{error:r.error};const{availableToScheduleCount:i=0}=r,a=i>h?i-h:0;S+=t?i:0;const s=t?S/t:i,c=t?o*s/u*(t-1)+s:s,d=i?h&&c-f||a:0;f=c,h=i,g+=d;const l=p(g)-I;return I+=l,{periodStart:e,add:l,availableToScheduleCount:i,newCourts:a,totalMatchUps:I}});return{scheduleTimes:T.reduce((t,e)=>{const n=L(0,e.add).map(()=>({scheduleTime:e.periodStart}));return t.concat(...n)},[]).flat(),timingProfile:T,totalMatchUps:I}}const bO={getCourtsAvailableAtPeriodStart:UO,generateTimeSlots:vO,getScheduleTimes:RO,courtGenerator:wO};var NO={__proto__:null,drawMatic:xN,garman:{__proto__:null,default:bO,garman:bO},generateAdHocMatchUps:YD,generateAdHocRounds:FN,generateAndPopulatePlayoffStructures:vT,generateCourts:yO,generateDrawDefinition:JE,generateDrawMaticRound:iR,generateDrawStructuresAndLinks:kD,generateDrawTypeAndModifyDrawDefinition:xD,generateFlightProfile:function(t){const{drawNameRoot:e="Flight",attachFlightProfile:n,tournamentRecord:r,scaleAttributes:i,scaleSortMethod:o,deleteExisting:a,sortDescending:s,drawNames:c=[],flightsCount:u,splitMethod:d,uuids:p=[],random:l,event:m,stage:f}=t;if(!m)return{error:Ht};const h=m.entries??[],{flightProfile:g}=Tg({event:m});if(g&&n&&!a)return{error:gr};const I=t.scaledEntries??LN({tournamentRecord:r,scaleAttributes:i,scaleSortMethod:o,sortDescending:s,event:m,stage:f}).scaledEntries,S=new Set(I.map(Xp)),y=A(h.filter(({participantId:t})=>!S.has(t)).filter(t=>(!f||!t.entryStage||t.entryStage===f)&&(!t.entryStatus||If.includes(t.entryStatus))),l),v=I.concat(...y),U=v.length;let P=q(v,Math.ceil(U/u));d===sO?P=H(v,u):d===cO&&(P=H(v,u,!0));const T=L(0,u).map(t=>{const n=t+1;return{flightNumber:n,drawId:p?.pop()??pa(void 0,l),drawEntries:(r=P[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}),w={scaleAttributes:i,splitMethod:d,flights:T};if(n){const t=XC({flightProfile:w,deleteExisting:a,event:m});return{splitEntries:$r()&&P||void 0,...t}}return{flightProfile:w,...Y}},generateLineUps:SO,generateQualifyingStructure:GP,generateSeedingScaleItems:iC,generateStatCrew:function(t){const e=fu(t,[{[Ic]:!0}]);if(e.error)return e;const{tournamentRecord:r}=t,{startDate:o,tournamentId:a,tournamentName:s}=r,{participantMap:c,matchUps:u,mappedMatchUps:d}=xS({withMatchUps:!0,withEvents:!0,tournamentRecord:r}),p=r.participants.filter(t=>t.participantType===ym),l=u?.filter(t=>t.matchUpType===ym)??[],m=l?.reduce((t,e)=>{const n=e?.tieMatchUps??[];return n?[...t,...n]:n},[])??[],f=u?.filter(t=>t.matchUpType===n)??[],h=u?.filter(t=>t.matchUpType===i)??[],g=m.length===f.length+h.length,I=1===l.length&&g,S={mappedMatchUps:d,participantMap:c,tournamentName:s,tournamentId:a,tournament:g?"N":"Y",startDate:o},y=[],v=[];if(I){const t=l[0],{json:e,xml:n}=lO({teamParticipants:p,teamMatchUp:t,...S,doubles:h,singles:f});v.push(e),y.push(n)}else for(const t of l){const e=t?.sides?.map(({participant:t})=>t?.participantId).filter(Boolean);if(2!==e?.length)continue;const r=e.map(t=>t&&c?.[t]?.participant),{xml:o,json:a}=lO({doubles:t.tieMatchUps?.filter(t=>t.matchUpType===i),singles:t.tieMatchUps?.filter(t=>t.matchUpType===n),teamParticipants:r,teamMatchUp:t,...S});v.push(a),y.push(o)}return{json:v,xml:y,...Y}},generateVoluntaryConsolation:oR,roundRobinGroups:ky},MO={__proto__:null,isAggregateFormat:Qb,isValid:Io,isValidMatchUpFormat:Io,parse:co,stringify:ro};function AO({tournamentRecord:t,drawDefinition:e,participantId:n,sideNumber:r,matchUpId:i,event:o}){if(n&&"string"!=typeof n)return{error:Ze};if(!e)return{error:st};if(!i)return{error:fe};const a=void 0===r;if(a&&(r=1),![1,2].includes(r))return Ci({result:{error:sr,context:{sideNumber:r}}});const{matchUp:s,structure:c}=nT({drawDefinition:e,matchUpId:i,event:o});if(!s)return{error:ge};if(!!(c?.structures||e.drawType&&!KS(e.drawType)||c?.matchUps?.find(({roundPosition:t})=>!!t)))return{error:wt};if(!n&&(s?.score?.scoreStringSide1||_p.includes(s?.matchUpstatus)||s?.matchUpStatus&&[wp,Tp].includes(s.matchUpStatus)))return{error:Ke,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}),a)for(const t of s.sides)t.sideNumber&&(t.sideNumber=3-t.sideNumber);Yl({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:s})}return{...Y,sidesSwapped:a}}function EO({removePriorValues:t,tournamentRecord:e,duplicateValues:n,drawDefinition:r,disableNotice:i,matchUpId:o,timeItem:a,event:s}){const{matchUp:c}=nT({drawDefinition:r,event:s,matchUpId:o});if(!c)return{error:ge};const u=nU({removePriorValues:t,element:c,duplicateValues:n,timeItem:a});return i||Yl({tournamentId:e?.tournamentId,eventId:s?.eventId,context:"addTimeItem",drawDefinition:r,matchUp:c}),u}function CO(t){const e=fu(t,[{[Ic]:!0},{[yc]:!0},{[Pc]:!0},{[kc]:!0}]);if(e.error)return e;const n=UE(t,[{[Yc]:Wc,attr:{[xc]:!0}}]);if(n.error)return n;const{tournamentRecord:r,drawDefinition:i,participantId:o,matchUpId:a}=t,s=n?.matchUp?.matchUp,{matchUpStatus:c,score:u}=s??{};if(c&&Lp.includes(c)||c&&_p.includes(c)||aI({score:u}))return{error:Ct};const d=Rh({matchUp:s});if(d?.error)return d;const{checkedInParticipantIds:p,allRelevantParticipantIds:l}=d??{};if(!l?.includes(o))return{error:Ze};if(!p?.includes(o))return{error:fn};const m=Kf({matchUp:s});if(m?.error)return m;const{sideParticipantIds:f,nestedIndividualParticipantIds:h}=m??{},g=f?.indexOf(o);void 0!==g&&[0,1].includes(g)&&(h?.[g]??[]).forEach(t=>{EO({drawDefinition:i,matchUpId:a,timeItem:{itemType:Jf,itemValue:t}})});return EO({tournamentRecord:r,drawDefinition:i,matchUpId:a,timeItem:{itemValue:o,itemType:Jf}}),{...Y,checkedOut:!0}}function OO(t){const e=fu(t,[{[Ic]:!0},{[yc]:!0},{[Pc]:!0},{[kc]:!0}]);if(e[Hc])return e;const n=UE(t,[{[Yc]:Wc,attr:{[xc]:!0}}]);if(n[Hc])return n;const{tournamentRecord:r,drawDefinition:i,participantId:o,matchUpId:a}=t,s=Rh({matchUp:n?.matchUp?.matchUp});if(s?.error)return s;const{checkedInParticipantIds:c,allRelevantParticipantIds:u}=s??{};if(!u?.includes(o))return{[Hc]:Ze};const d={...Y,checkedIn:!0};if(c?.includes(o))return d;return EO({tournamentRecord:r,drawDefinition:i,matchUpId:a,timeItem:{itemValue:o,itemType:Qf}}),d}function kO(t){const e=fu(t,[{[Pc]:!0,[yc]:!0,[kc]:!0}]);if(e.error)return e;const n=t.tournamentId??t.activeTournamentId,r=t.tournamentRecord??(n&&t.tournamentRecords?.[n]);if(!r)return{error:rt};const i=UE(t,[{[Yc]:Wc,attr:{[xc]:!0},[Hc]:ge}]),o=i.matchUp?.matchUp;if(!o)return{error:ge};const{checkedInParticipantIds:a=[]}=Rh({matchUp:o}),{participantId:s,matchUpId:c,drawDefinition:u}=t;return s&&a.includes(s)?CO({tournamentRecord:r,drawDefinition:u,participantId:s,matchUpId:c,matchUp:o}):OO({tournamentRecord:r,drawDefinition:u,participantId:s,matchUpId:c,matchUp:o})}function FO({tournamentRecord:t,drawDefinition:e,tieMatchUpId:r,event:o}){if(!t)return{error:rt};if(!e)return{error:bt};if(!o)return{error:zt};const a=bf({drawDefinition:e}),{matchUp:s}=nT({matchUpId:r,drawDefinition:e,matchUpsMap:a});if(!s)return{error:ge};const{matchUp:c,structure:u}=nT({tournamentParticipants:t.participants,matchUpId:r,inContext:!0,drawDefinition:e,matchUpsMap:a,event:o});if(!c)return{error:ge};const{collectionPosition:d,drawPositions:p,collectionId:l,matchUpTieId:m,matchUpType:f}=c;if(f&&!z([n,i],f))return{error:ye};const{positionAssignments:h}=cl({structure:u}),g=h?.filter(t=>p?.includes(t.drawPosition)),{matchUp:I}=nT({matchUpId:m,drawDefinition:e,matchUpsMap:a}),S=[...I?.sides?.map(Xp)??[],...g?.map(Xp)??[]],{participants:y}=xS({tournamentRecord:t,participantFilters:{participantTypes:[ym],participantIds:S}}),{matchUp:v}=nT({matchUpId:m,inContext:!0,drawDefinition:e,matchUpsMap:a}),U=Rf({matchUp:I,drawDefinition:e,structure:u,event:o})?.tieFormat;return{inContextDualMatchUp:v,inContextTieMatchUp:c,relevantAssignments:g,collectionPosition:d,teamParticipants:y,collectionId:l,matchUpType:f,dualMatchUp:I,tieMatchUp:s,tieFormat:U,structure:u,...Y}}function xO(t){const e=FO(t);if(e.error)return e;const n="replaceTieMatchUpParticipantid",{existingParticipantId:r,tournamentRecord:o,newParticipantId:a,drawDefinition:s,substitution:c,event:u}=t;if(!r||!a)return Ci({result:{error:sn},stack:n});if(r===a)return{...Y};const{inContextDualMatchUp:d,inContextTieMatchUp:p,collectionPosition:l,collectionId:m,dualMatchUp:f,tieMatchUp:h,tieFormat:g}=e,I=p?.matchUpType,S=p?.sides?.find(t=>t.participant?.participantId===r||t.participant?.individualParticipantIds?.includes(r));if(!S)return{error:un};const y=function({existingParticipantId:t,inContextTieMatchUp:e,newParticipantId:n,tournamentRecord:r,drawDefinition:i,params:o,event:a,stack:s}){const c=xS({tournamentRecord:r,participantFilters:{participantIds:[t,n]}})?.participants??[];if(2!==c.length)return Ci({result:{error:sn},stack:s});if(c[0].participantType!==c[1].participantType)return Ci({result:{error:nn},stack:s});const{appliedPolicies:u}=xd({tournamentRecord:r,drawDefinition:i,event:a}),d=o.policyDefinitions?.[Nu]??u?.[Nu]??ty[Nu],p=c.find(({participantId:t})=>t===n),l=!1!==(o.enforceGender??d?.participants?.enforceGender);if(l&&Yi(e?.gender)&&zi(e?.gender)!==zi(p?.person?.sex))return{error:Xe,info:"Gender mismatch"};return}({existingParticipantId:r,inContextTieMatchUp:p,newParticipantId:a,tournamentRecord:o,drawDefinition:s,params:t,event:u,stack:n});if(y)return y;const{appliedPolicies:v}=xd({tournamentRecord:o,drawDefinition:s,event:u}),U=t.policyDefinitions?.[Nu]??v?.[Nu]??ty[Nu],P=U?.processCodes?.substitution;lT({tournamentId:o.tournamentId,eventId:u.eventId,inContextDualMatchUp:d,drawDefinition:s,dualMatchUp:f});const T=f?.sides?.find(({sideNumber:t})=>t===S.sideNumber);if(!T)return Ci({result:{sideNumber:S.sideNumber,existingParticipantId:r,error:mr},stack:n});const w=p?.sides?.flatMap(t=>t.participant?.individualParticipantIds||(t.participant?.participantId??[]));if(w?.includes(a))return Ci({result:{error:In},stack:n});const D=d?.sides?.find(({sideNumber:t})=>t===S.sideNumber)?.participantId,R=T.lineUp,b=function({existingParticipantId:t,collectionPosition:e,newParticipantId:n,substitution:r,collectionId:i,teamLineUp:o}){const a=o?.find(({participantId:t})=>n===t),s=o?.reduce((t,e)=>e.substitutionOrder>t?e.substitutionOrder:t,0),c=o?.map(o=>{const a=ca(o,!1,!0);if(![t,n].includes(a.participantId))return a;if(!r&&[t,n].includes(a.participantId)&&(a.collectionAssignments=a.collectionAssignments?.filter(t=>!(t.collectionPosition===e&&t.collectionId===i))),r&&t===a.participantId&&(a.collectionAssignments=a.collectionAssignments.map(t=>t.collectionPosition===e&&t.collectionId===i&&void 0===t.substitutionOrder?{...t,substitutionOrder:s}:t)),a.participantId===n){a.collectionAssignments??=[];const n={collectionId:i,collectionPosition:e};r&&(n.previousParticipantId=t,n.substitutionOrder=(s??0)+1),a.collectionAssignments.push(n)}return a})??[];if(!a){const o={collectionId:i,collectionPosition:e};r&&(o.substitutionOrder=(s??0)+1,o.previousParticipantId=t);const a={collectionAssignments:[o],participantId:n};c.push(a)}return c}({existingParticipantId:r,collectionPosition:l,newParticipantId:a,substitution:c,collectionId:m,teamLineUp:R}),N=I===i,{assignedParticipantIds:A}=Rg({lineUp:R,collectionPosition:l,collectionId:m}),{assignedParticipantIds:E}=Rg({lineUp:b,collectionPosition:l,collectionId:m});if(T.lineUp=b,D&&g){const t=iv({participantId:D,lineUp:b,drawDefinition:s,tieFormat:g});if(t.error)return Ci({result:t,stack:n})}else console.log("team participantId not found");const{participantAdded:C,participantRemoved:O}=N?function({existingIndividualParticipantIds:t,individualParticipantIds:e,tournamentRecord:n,stack:r}){let i,o,a=bg({participantIds:e,tournamentRecord:n});if(!a.participant){const t=mC({returnParticipant:!0,pairOverride:!0,tournamentRecord:n,participant:{participantRole:sy,individualParticipantIds:e,participantType:Sm}});if(t.error)return Ci({result:t,stack:r});i=t.participant?.participantId}a=bg({participantIds:t,tournamentRecord:n});const s=a.participant?.participantId;if(s){yy({participantIds:[s],tournamentRecord:n}).success&&(o=s)}return{participantAdded:i,participantRemoved:o}}({existingIndividualParticipantIds:A,individualParticipantIds:E,tournamentRecord:o,stack:n}):{participantAdded:void 0,participantRemoved:void 0};return function({substitutionProcessCodes:t,tournamentRecord:e,drawDefinition:n,substitution:r,tieMatchUp:i,stack:o,side:a}){if(r||1===a.substitutions?.length){if(r)t&&i&&(i.processCodes=M([...i?.processCodes??[],...t]));else for(const e of t??[]){const t=i?.processCodes?.lastIndexOf(e);void 0!==t&&i?.processCodes?.splice(t,1)}i&&Yl({tournamentId:e?.tournamentId,matchUp:i,context:o,drawDefinition:n})}}({substitutionProcessCodes:P,tournamentRecord:o,drawDefinition:s,substitution:c,tieMatchUp:h,stack:n,side:S}),f&&Yl({tournamentId:o?.tournamentId,matchUp:f,context:n,drawDefinition:s}),{...Y,modifiedLineUp:b,participantRemoved:O,participantAdded:C}}function _O({collectionPosition:t,teamParticipantId:e,dualMatchUpSide:n,drawDefinition:r,participantIds:i,collectionId:o}){if(!o||!t||!Array.isArray(i))return{modifiedLineUp:n?.lineUp??[],error:sr};const a=n?.lineUp||Ng({participantId:e,drawDefinition:r})?.lineUp,s=[],c=[];return{modifiedLineUp:a?.map(e=>{if(!i.includes(e.participantId))return e;const n=e.collectionAssignments?.filter(n=>{const r=n.collectionId===o&&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 LO({individualParticipantIds:t,groupingParticipantId:e,removeFromOtherTeams:n,tournamentRecord:r}){const i="addIndividualParticipantIds";if(!r)return Ci({result:{error:rt},stack:i});if(!e||!t)return Ci({result:{error:Ae},stack:i});const o=r.participants??[],a=o.find(t=>t.participantId===e);if(!a)return Ci({result:{error:un},stack:i});if(a?.participantType&&![ym,Im].includes(a.participantType))return Ci({context:{participantType:a.participantType},result:{error:nn},stack:i});const s=t.filter(t=>{const e=o.find(e=>e.participantId===t);return e?.participantType!==gm});if(s.length)return Ci({result:{error:tn,invalidParticipantIds:s},stack:i});a.individualParticipantIds??=[];const c=a.individualParticipantIds,u=t.filter(t=>!c.includes(t));u.length&&(n&&Sy({individualParticipantIds:u,tournamentRecord:r}),a.individualParticipantIds=a.individualParticipantIds.concat(...u));const{topics:d}=gi();if(d.includes(bl)){const t=o.find(({participantId:t})=>t===e);di({topic:bl,payload:{participants:[t]}})}return function({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}){const r=(n.events??[]).filter(t=>t?.eventType===is&&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}=Tg({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:ca(a,!1,!0),added:u.length,...Y}}function BO(t){const{updateParticipantName:e=!0,groupingParticipantId:n,removeFromOtherTeams:r,tournamentRecord:i,pairOverride:o,participant:s}=t,c=dl({tournamentRecord:i,participant:s},[Ic,Nc]);if(c.error)return c;if(!s.participantId)return mC({tournamentRecord:i,participant:s});const{participant:u}=Rm({participantId:s.participantId,tournamentRecord:i});if(!u)return mC({tournamentRecord:i,participant:s});const{participantRoleResponsibilties:d,individualParticipantIds:p,participantOtherName:l,participantName:f,participantRole:h,participantType:g,onlineResources:I,contacts:S,person:y}=s;if(g&&u.participantType!==g)return{error:Ye};const v={};if(S&&(v.contacts=S),I&&(v.onlineResources=I),void 0!==l&&(v.participantOtherName=l||void 0),f&&m(f)&&(v.participantName=f),Array.isArray(p)&&function({individualParticipantIds:t,updateParticipantName:e,existingParticipant:n,participantType:r,tournamentRecord:i,pairOverride:o,newValues:s}){const{participants:c}=xS({participantFilters:{participantTypes:[gm]},tournamentRecord:i}),u=c?.map(Xp);if(!u)return;const d=t.filter(t=>m(t)&&u.includes(t));([Im,a].includes(r||n.participantType)||r===Sm&&(2===d.length||o))&&(s.individualParticipantIds=d);n.participantType===vm.PAIR&&e&&(s.participantName=function({individualParticipants:t,newValues:e}){const n=e.individualParticipantIds;let r=t.filter(({participantId:t})=>n.includes(t)).map(t=>t.person?.standardFamilyName||t.participantOtherName||t.participantName||"").filter(Boolean).sort().join("/");1===n.length&&(r+="/Unknown");return r}({individualParticipants:c,newValues:s}))}({individualParticipantIds:p,updateParticipantName:e,existingParticipant:u,participantType:g,tournamentRecord:i,pairOverride:o,newValues:v}),Object.keys(my).includes(h)&&(v.participantRole=h),Object.keys(vm).includes(g)&&(v.participantType=g),Array.isArray(d)&&(v.participantRoleResponsibilties=d),u.participantType===vm.INDIVIDUAL&&y){const t=function({updateParticipantName:t,existingParticipant:e,newValues:n,person:r}){const i={},{standardFamilyName:o,standardGivenName:a,nationalityCode:s,personId:c,birthdate:u,tennisId:d,sex:p}=r;p&&Object.keys(ji).includes(p)&&(i.sex=p);let l;m(c)&&(i.personId=c);s&&m(s)&&(f=s,wm.flatMap(({iso:t,ioc:e})=>[t,e]).filter(Boolean).includes(f)||""===s)&&(i.nationalityCode=s);var f;o&&(m(o),1)&&o.length>1&&(i.standardFamilyName=o,l=!0);a&&(m(a),1)&&a.length>1&&(i.standardGivenName=a,l=!0);if(l&&t){const t=i.standardGivenName||e.person?.standardGivenName,r=i.standardFamilyName||e.person?.standardFamilyName;if(t&&r)n.participantName=`${t} ${r}`;else{const i=[t,r].filter(Boolean).join(" ");n.participantName=i||e.participantOtherName||e.participantName}}if(u){if(!Do(u))return{error:_e};const t=new Date(u).getFullYear();if(new Date(u)>new Date||t<1900)return{error:_e,info:"birthdate must be a past date"};i.birthdate=u}d&&m(d)&&(i.tennisId=d);return void Object.assign(e.person,i)}({updateParticipantName:e,existingParticipant:u,newValues:v,person:y});if(t?.error)return t}return Object.assign(u,Ei(v)),n&&LO({individualParticipantIds:[u.participantId],groupingParticipantId:n,removeFromOtherTeams:r,tournamentRecord:i}),di({topic:bl,payload:{tournamentId:i.tournamentId,participants:[u]}}),{participant:ca(u),...Y}}function VO(t){const e=FO(t);if(e.error)return e;const r="assignTieMatchUpParticipantId";let o=t.teamParticipantId;const{tournamentRecord:a,drawDefinition:s,participantId:c,event:u}=t;if(!c)return Ci({result:{error:sn},stack:r});const d=new Set([1,2]);if(t.sideNumber&&!d.has(t.sideNumber))return Ci({result:{error:be},stack:r});const{inContextDualMatchUp:p,inContextTieMatchUp:l,relevantAssignments:m,collectionPosition:f,teamParticipants:h,collectionId:g,matchUpType:I,dualMatchUp:S,tieFormat:y}=e,v=function(t,e){const n=t?.sides?.flatMap(t=>t.participant?.individualParticipantIds||(t.participant?.participantId??[]));return n?.includes(e)}(l,c);if(v)return Ci({result:{...Y},stack:r});o=function({teamParticipantId:t,inContextDualMatchUp:e,sideNumber:n}){return t||(n?e?.sides?.find(t=>t.sideNumber===n)?.participantId:void 0)}({teamParticipantId:o,inContextDualMatchUp:p,sideNumber:t.sideNumber});const U=xS({participantFilters:{participantIds:[c]},tournamentRecord:a})?.participants?.[0];if(!U)return Ci({result:{error:un},stack:r});const P=function({policyDefinitions:t,inContextTieMatchUp:e,participantToAssign:n,tournamentRecord:r,drawDefinition:i,enforceGender:o,event:a}){const{appliedPolicies:s}=xd({tournamentRecord:r,drawDefinition:i,event:a}),c=t?.[Nu]??s?.[Nu]??ty[Nu];if(!1!==(o??c?.participants?.enforceGender)&&Yi(e?.gender)&&zi(e?.gender)!==zi(n.person?.sex))return{error:Xe,info:"Gender mismatch"};return}({policyDefinitions:t.policyDefinitions,inContextTieMatchUp:l,participantToAssign:U,tournamentRecord:a,drawDefinition:s,enforceGender:t.enforceGender,event:u});if(P)return P;const{individualParticipantIds:T,participantType:w}=U;if(bh(n)(I)&&w!==gm)return{error:nn};const D=w===gm?[c]:T,R=o&&h?.find(({participantId:t})=>t===o)||h?.find(({individualParticipantIds:t})=>j(D,t));if(!R)return{error:ur};if(o||(o=R.participantId),!o)return{error:un};const b=function({inContextTieMatchUp:t,teamParticipantId:e,relevantAssignments:n,participantTeam:r,dualMatchUp:i,sideNumber:o}){const a=n?.find(t=>t.participantId===r?.participantId),s=a?.drawPosition,c=i?.sides?.find(t=>t.participantId===e)?.sideNumber,u=t?.sides?.find(t=>s&&t.drawPosition===s)?.sideNumber;return c??u??o}({inContextTieMatchUp:l,teamParticipantId:o,relevantAssignments:m,participantTeam:R,dualMatchUp:S,sideNumber:t.sideNumber});if(!y)return{error:me};const N=y.collectionDefinitions?.find(t=>t.collectionId===g);if(!N)return{error:le};lT({tournamentId:a.tournamentId,eventId:u.eventId,inContextDualMatchUp:p,drawDefinition:s,dualMatchUp:S});const M=S?.sides?.find(t=>t.sideNumber===b),A=l?.sides?.find(t=>t.sideNumber===b),E=M?.lineUp??Ng({participantId:o,drawDefinition:s})?.lineUp,C=E?.filter(t=>t.collectionAssignments?.find(t=>t.collectionPosition===f&&t.collectionId===g&&!t.previousParticipantId)),O=C?.map(t=>t?.participantId),k=O?.length>1&&O||(w===Sm?U.individualParticipantIds:[c]),F=_O({collectionPosition:f,teamParticipantId:o,dualMatchUpSide:M,drawDefinition:s,participantIds:k,collectionId:g});if(F.error)return Ci({result:F,stack:r});const{modifiedLineUp:x}=F;let _;if(I===i){const t=function({collectionPosition:t,teamParticipantId:e,tournamentRecord:n,dualMatchUpSide:r,participantType:i,drawDefinition:o,tieMatchUpSide:a,modifiedLineUp:s,participantIds:c,participantId:u,dualMatchUp:d,collectionId:p,tieFormat:l,stack:m}){let f;if(i!==Sm){let i=GO({collectionPosition:t,teamParticipantId:e,drawDefinition:o,modifiedLineUp:s,participantId:u,collectionId:p,tieFormat:l});if(i?.error)return Ci({result:i,stack:m});if(i=function({side:t,tournamentRecord:e,participantId:n}){let r;if(t.participant){const i=t.participant.individualParticipantIds??[];if(1===i.filter(Boolean).length){const{participant:t}=bg({participantIds:i,tournamentRecord:e});i.push(n);const{participant:o}=bg({participantIds:i,tournamentRecord:e});if(!o&&t){t.individualParticipantIds=i;const n=BO({pairOverride:!0,tournamentRecord:e,participant:t});if(n.error)return n}else r=t?.participantId}}else{const t=mC({participant:{individualParticipantIds:[n],participantRole:sy,participantType:Sm},pairOverride:!0,tournamentRecord:e});if(t.error)return t}return{...Y,deletedParticipantId:r}}({side:a,tournamentRecord:n,participantId:u}),i.error)return i;f=i.deletedParticipantId,r&&(r.lineUp=s),d&&Yl({tournamentId:n?.tournamentId,matchUp:d,context:m,drawDefinition:o})}else for(const n of c)GO({collectionPosition:t,teamParticipantId:e,drawDefinition:o,modifiedLineUp:s,participantId:n,collectionId:p,tieFormat:l});return{...Y,deletedParticipantId:f}}({collectionPosition:f,teamParticipantId:o,tournamentRecord:a,dualMatchUpSide:M,participantType:w,drawDefinition:s,tieMatchUpSide:A,modifiedLineUp:x,participantIds:k,participantId:c,dualMatchUp:S,collectionId:g,tieFormat:y,stack:r});if(t.error)return t;_=t.deletedParticipantId}else{const t=GO({collectionPosition:f,teamParticipantId:o,drawDefinition:s,modifiedLineUp:x,participantId:c,collectionId:g,tieFormat:y});if(t?.error)return t}if(M&&(M.lineUp=x),S&&Yl({tournamentId:a?.tournamentId,matchUp:S,context:r,drawDefinition:s}),_){const{error:t}=yy({participantIds:[_],tournamentRecord:a});t&&console.log("cleanup")}return{...Y,modifiedLineUp:x}}function GO({collectionPosition:t,teamParticipantId:e,drawDefinition:n,modifiedLineUp:r,participantId:i,collectionId:o,tieFormat:a}){const s=Ng({participantId:e,drawDefinition:n})?.lineUp,c=(r||s)?.find(t=>t?.participantId===i),u={collectionId:o,collectionPosition:t};if(c)c.collectionAssignments.push(u);else{const t={collectionAssignments:[u],participantId:i};r.push(t)}return iv({participantId:e,lineUp:r,drawDefinition:n,tieFormat:a})}function jO({inContextTieMatchUp:t,previousParticipantIds:e,dualMatchUpSide:n,tournamentRecord:r,participantId:i,stack:o}){const a=t?.sides?.find(t=>t.sideNumber===n?.sideNumber),{participantId:s}=a??{},c=s&&xS({participantFilters:{participantIds:[s]},tournamentRecord:r,withDraws:!0})?.participants?.[0];if(!c)return Ci({result:{error:un},stack:o});const u=c?.individualParticipantIds?.filter(t=>t!==i)??[];return e&&u.push(...e),u.length>2?Ci({result:{error:tn},stack:o}):c.draws?.length?1===u.length?function({individualParticipantIds:t,tournamentRecord:e,stack:n}){const{participant:r}=bg({participantIds:t,tournamentRecord:e});if(!r){const r=mC({participant:{participantRole:sy,individualParticipantIds:t,participantType:Sm},pairOverride:!0,tournamentRecord:e});if(r.error)return Ci({result:r,stack:n})}return}({individualParticipantIds:u,tournamentRecord:r,stack:o}):void 0:function({individualParticipantIds:t,pairParticipantId:e,tournamentRecord:n,pairParticipant:r,stack:i}){if(t.length){r.individualParticipantIds=t;const e=BO({participant:r,pairOverride:!0,tournamentRecord:n});if(e.error)return Ci({result:e,stack:i})}else{const t=yy({participantIds:[e],tournamentRecord:n});t.error&&console.log("cleanup",{result:t})}return}({individualParticipantIds:u,pairParticipantId:s,tournamentRecord:r,pairParticipant:c,stack:o})}function qO(t){const{tournamentRecord:e,drawDefinition:r,participantId:o,event:a}=t,s="removeTieMatchUpParticiapantId";if(!o)return Ci({result:{error:sn},stack:s});const c=FO(t);if(c.error)return c;const{appliedPolicies:u}=xd({tournamentRecord:e,drawDefinition:r,event:a}),d=t.policyDefinitions?.[Nu]??u?.[Nu]??ty[Nu],p=d?.processCodes?.substitution,{inContextDualMatchUp:l,inContextTieMatchUp:m,relevantAssignments:f,collectionPosition:h,teamParticipants:g,collectionId:I,matchUpType:S,dualMatchUp:y,tieMatchUp:v,tieFormat:U}=c;if(!y)return Ci({result:{error:Se},stack:s});const P=m?.sides?.find(t=>t.participant?.participantId===o||t.participant?.individualParticipantIds?.includes(o));if(!P)return Ci({result:{error:un},stack:s});const T=t.policyDefinitions?.[Fu]??u?.[Fu];if(!P.substitutions?.length&&(aI({score:m?.score})||m?.winningSide)&&!1!==T?.requireParticipantsForScoring)return Ci({result:{error:Ir},stack:s});const w=l?.sides?.find(({sideNumber:t})=>t===P.sideNumber)?.participantId;if(!w)return Ci({result:{error:un},stack:s});const D=xS({participantFilters:{participantIds:[o]},tournamentRecord:e})?.participants?.[0];if(!D)return Ci({result:{error:un},stack:s});if(S===n&&D.participantType===Sm)return Ci({result:{error:Xe},stack:s});const R=D.participantType===gm?[o]:D.individualParticipantIds;lT({tournamentId:e.tournamentId,eventId:a.eventId,inContextDualMatchUp:l,drawDefinition:r,dualMatchUp:y});let b=y.sides?.find(({sideNumber:t})=>t===P.sideNumber);if(!b&&(y.sides?.filter(({lineUp:t})=>!t).length||0)<2){const t=g?.map(({participantId:t})=>({drawPosition:f?.find(e=>e.participantId===t)?.drawPosition,teamParticipantId:t}));b=y.sides?.find(e=>t?.find(({drawPosition:t})=>t===e.drawPosition)?.teamParticipantId===w)}if(!b)return Ci({result:{error:un,context:{participantId:o}}});const{modifiedLineUp:N,previousParticipantIds:M}=_O({collectionPosition:h,teamParticipantId:w,dualMatchUpSide:b,participantIds:R,drawDefinition:r,collectionId:I});if(b.lineUp=N,w&&U&&iv({participantId:w,lineUp:N,drawDefinition:r,tieFormat:U}),S===i&&D.participantType===gm){const t=jO({inContextTieMatchUp:m,previousParticipantIds:M,dualMatchUpSide:b,tournamentRecord:e,participantId:o,stack:s});if(t?.error)return t}return 1===P.substitutions?.length&&function({substitutionProcessCodes:t,inContextTieMatchUp:e,tournamentRecord:n,drawDefinition:r,tieMatchUp:i,stack:o,side:a}){const s=e?.sides?.find(t=>t.sideNumber!==a.sideNumber);if(!s?.substitutions?.length&&i?.processCodes?.length){for(const e of t??[]){const t=i.processCodes.lastIndexOf(e);i.processCodes.splice(t,1)}Yl({tournamentId:n?.tournamentId,matchUp:i,context:o,drawDefinition:r})}}({substitutionProcessCodes:p,inContextTieMatchUp:m,tournamentRecord:e,drawDefinition:r,tieMatchUp:v,stack:s,side:P}),Yl({tournamentId:e?.tournamentId,matchUp:y,context:s,drawDefinition:r}),{...Y,modifiedLineUp:N}}function WO(t){const e=fu(t,[{[Ic]:!0,[yc]:!0,[kc]:!0}]);if(e.error)return e;const{drawDefinition:n,sideNumber:r,matchUpId:i,event:o}=t;if(r&&![1,2].includes(r))return{error:sr,sideNumber:r};const{matchUp:a,structure:s}=nT({drawDefinition:n,matchUpId:i,event:o});return a?Hf({structure:s})?(a.sides?.forEach(t=>{r&&t.sideNumber!==r||delete t.participantId}),Yl({tournamentId:t.tournamentRecord?.tournamentId,context:"assignSideParticipant",drawDefinition:n,matchUp:a}),{...Y}):{error:wt}:{error:ge}}function $O({inContextDrawMatchUps:t,positionAssignments:e,sourceMatchUpStatus:n,targetDrawPosition:r,tournamentRecord:i,sourceMatchUpId:o,drawDefinition:a,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&&Sp||II(u.matchUpStatus)&&u.matchUpStatus||Ap,II(u.matchUpStatus)&&(u.winningSide=void 0),u.matchUpStatusCodes&&Jy({inContextDrawMatchUps:t,sourceMatchUpStatus:n,sourceMatchUpId:o,matchUpsMap:c,matchUp:u}),Yl({tournamentId:i?.tournamentId,eventId:d?.eventId,context:`removeSubsequentDrawPosition-${r}`,drawDefinition:a,matchUp:u}),{...Y}}function HO(t){const{dualWinningSideChange:e,inContextDrawMatchUps:n,tournamentRecord:r,drawDefinition:i,matchUpStatus:o,matchUpsMap:a,dualMatchUp:s,targetData:c,matchUpId:u,structure:d,event:p}=t,l=Boolean(t.matchUp.collectionId),m=Hf({structure:d}),{drawPositions:f,winningSide:h}=c.matchUp??{};if(!m&&!f)return{error:yt};const{targetLinks:{loserTargetLink:g,winnerTargetLink:I,byeTargetLink:S},targetMatchUps:{loserMatchUp:y,winnerMatchUp:v,byeMatchUp:U}}=c,P=aT({...t,matchUpStatus:o||Ap,removeWinningSide:!0});if(P.error)return P;let T;if(l){const{matchUpTieId:n,matchUpsMap:o}=t;if(T=gT({appliedPolicies:t.appliedPolicies,matchUpId:n,tournamentRecord:r,drawDefinition:i,matchUpsMap:o,event:p}),!e&&!T.removeWinningSide)return{...Y}}if(m)return{...Y};const{matchUps:w}=Fg({afterRecoveryTimes:!1,inContext:!0,drawDefinition:i,matchUpsMap:a,structure:d}),{positionAssignments:D}=ul({structure:d}),R=h-1,b=1-R,N=f[R],M=f[b],{winnerParticipantId:A,loserParticipantId:E}=D?.reduce((t,e)=>(e.drawPosition===M&&(t.loserParticipantId=e.participantId),e.drawPosition===N&&(t.winnerParticipantId=e.participantId),t),{winnerParticipantId:void 0,loserParticipantId:void 0})??{},C=w.filter(t=>t.drawPositions?.includes(M));if(v&&zO({sourceMatchUpStatus:o,sourceMatchUpId:u,inContextDrawMatchUps:n,winningDrawPosition:N,winnerParticipantId:A,tournamentRecord:r,winnerTargetLink:I,drawDefinition:i,winnerMatchUp:v,dualMatchUp:s,matchUpsMap:a}),y){const{winnerHadMatchUpStatus:t}=function({matchUpStatuses:t=[Sp,Ep,Pp],drawPositionMatchUps:e,loserDrawPosition:n,sourceMatchUps:r}){const i=e?.reduce((t,e)=>!t||e.roundNumber>t.roundNumber?e:t,void 0),o=i?.drawPositions?.find(t=>t!==n),a=r.filter(t=>t?.drawPositions?.includes(o)).map(t=>t.matchUpStatus),s=r.filter(t=>t?.drawPositions?.includes(n)).map(t=>t.matchUpStatus);return{sourceMatchUp:i,winnerHadMatchUpStatus:j(a??[],t),winnerMatchUpStatuses:a,loserHadMatchUpStatus:j(s??[],t),loserMatchUpStatuses:s}}({drawPositionMatchUps:C,loserDrawPosition:M,sourceMatchUps:w}),e=g.linkCondition;if(t&&e===Os){YO({targetLink:g,inContextDrawMatchUps:n,drawDefinition:i,drawPosition:Math.min(...y.drawPositions),matchUpsMap:a,event:p})}const c=function({sourceMatchUpStatus:t,loserParticipantId:e,tournamentRecord:n,loserTargetLink:r,sourceMatchUpId:i,drawDefinition:o,loserMatchUp:a,matchUpsMap:s,dualMatchUp:c,event:u}){const d="removeDirectedLoser",p=r.target.structureId,{structure:l}=ol({drawDefinition:o,structureId:p});if(!l)return{error:Vt};const{positionAssignments:m}=ul({structure:l}),f=m?.find(t=>t.participantId===e)?.drawPosition;if(m?.forEach(t=>{t.participantId===e&&delete t.participantId}),i&&t){const e=s?.drawMatchUps?.find(({matchUpId:t})=>t===a.matchUpId);e.matchUpStatusCodes=t===wp?["WO","WO"]:[]}if(l.seedAssignments=(l.seedAssignments??[]).filter(t=>t.participantId!==e),c){const t=a?.sides.reduce((t,e,n)=>e.drawPosition===f?n:t,void 0),e=s?.drawMatchUps?.find(({matchUpId:t})=>t===a.matchUpId),r=e?.sides?.[t];r&&(delete r.lineUp,Yl({tournamentId:n?.tournamentId,eventId:u?.eventId,matchUp:e,context:d,drawDefinition:o}))}return{...Y}}({sourceMatchUpStatus:o,sourceMatchUpId:u,loserParticipantId:E,tournamentRecord:r,loserTargetLink:g,drawDefinition:i,loserMatchUp:y,dualMatchUp:s,matchUpsMap:a,event:p});if(c.error)return c}if(U){YO({targetLink:S,inContextDrawMatchUps:n,drawDefinition:i,drawPosition:Math.min(...U.drawPositions),matchUpsMap:a,event:p})}const O=T&&{tieMatchUpResult:T};return{...Y,...O}}function zO({inContextDrawMatchUps:t,winningDrawPosition:e,sourceMatchUpStatus:n,winnerParticipantId:r,tournamentRecord:i,winnerTargetLink:o,sourceMatchUpId:a,drawDefinition:s,winnerMatchUp:c,matchUpsMap:u,dualMatchUp:d,event:p}){const{structureId:l,roundNumber:m}=c;if(o){const t=o.target.structureId,{structure:e}=ol({drawDefinition:s,structureId:t});if(!e)return{error:Vt};const{positionAssignments:n}=ul({structure:e});e.seedAssignments=(e.seedAssignments??[]).filter(t=>t.participantId!==r);const a=n?.find(t=>t.participantId===r),d=a?.drawPosition,{matchUps:l}=Fg({drawDefinition:s,structure:e,event:p}),m=C(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:o})}const f=u?.drawMatchUps?.find(({matchUpId:t})=>t===c.matchUpId);f&&Yl({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:o,structureId:a,dualMatchUp:s,roundNumber:c,matchUpsMap:u,event:d}){const{structure:p}=ol({drawDefinition:o,structureId:a});if(p?.structureType===Ds)return{...Y};u=u??bf({drawDefinition:o});const l=(u?.mappedMatchUps??{})[a].matchUps,{initialRoundNumber:m}=pI({drawPosition:n,matchUps:l}),f=l?.filter(t=>t.roundNumber>=c&&t.roundNumber!==m&&t.drawPositions?.includes(n)),{positionAssignments:h}=cl({drawDefinition:o,structureId:a});for(const a of f??[])$O({inContextDrawMatchUps:t,sourceMatchUpStatus:e,positionAssignments:h,targetDrawPosition:n,tournamentRecord:r,sourceMatchUpId:i,drawDefinition:o,dualMatchUp:s,matchUpsMap:u,matchUp:a,event:d})}({targetDrawPosition:e,inContextDrawMatchUps:t,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:s,dualMatchUp:d,matchUpsMap:u,roundNumber:m,structureId:l}),{...Y}}function YO({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,matchUpsMap:i,targetLink:o,event:a}){const s=o.target.structureId,c="removeDirectedBye";fI({color:"brightyellow",method:c,drawPosition:r});return Ci({result:wI({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,matchUpsMap:i,structureId:s,event:a}),stack:c})}function KO(t,e){fI({method:t,...e})}function QO(t){const{tournamentRecord:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:i,targetData:o,structure:a,event:s}=t,c="doubleExitAdvancement";if(a.structureType===Ds)return Ci({result:{...Y},stack:c});const{matchUp:u,targetMatchUps:d,targetLinks:p}=o,{loserMatchUp:l,winnerMatchUp:m,loserTargetDrawPosition:f}=d,h=II(l?.matchUpStatus)&&!l.sides?.map(t=>t.participantId??t.participant).filter(Boolean).length,g=l?.matchUpStatus===wp;if(KO(c,{newline:!0,color:"brightyellow",keyColors:{sourceMatchUpId:"brightcyan",loserMatchUpId:"brightmagenta",winnerMatchUpId:"brightgreen"},sourceMatchUpId:u?.matchUpId,sourceStatus:t.matchUpStatus,sourceDP:JSON.stringify(u?.drawPositions),loserMatchUpId:l?.matchUpId,loserStatus:l?.matchUpStatus,loserDP:JSON.stringify(l?.drawPositions),loserTargetDP:f,loserIsEmptyExit:h,loserIsDoubleExit:g,loserSides:JSON.stringify(l?.sides?.map(t=>({sn:t.sideNumber,pid:t.participantId?.slice(0,8),fed:t.participantFed}))),winnerMatchUpId:m?.matchUpId,winnerStatus:m?.matchUpStatus,winnerDP:JSON.stringify(m?.drawPositions)}),l&&l.matchUpStatus!==Sp){const o=function({loserMatchUpIsEmptyExit:t,loserMatchUpIsDoubleExit:e,loserTargetDrawPosition:n,appliedPolicies:r,tournamentRecord:i,drawDefinition:o,sourceMatchUp:a,loserMatchUp:s,targetLinks:c,matchUpsMap:u,params:d,event:p,stack:l}){const{loserTargetLink:m}=c,f=r?.progression?.doubleExitPropagateBye,h=s.feedRound&&s.sides?.[0]?.participantFed;if(f||h)return KO(l,{color:"cyan",decision:"advanceByeToLoserMatchUp",propagateBye:f,targetFedIn:!!h}),XO({loserTargetDrawPosition:n,tournamentRecord:i,loserTargetLink:m,drawDefinition:o,loserMatchUp:s,matchUpsMap:u,event:p});if(t)return function({loserMatchUp:t,matchUpsMap:e,params:n,stack:r}){const i=n.matchUpStatus===Tp?Tp:wp,o=n.matchUpStatus===Tp?Pp:Ep,a=e.drawMatchUps.find(e=>e.matchUpId===t.matchUpId);if(KO(r,{color:"brightred",decision:"EMPTY_EXIT_converting_to_DOUBLE_EXIT",loserMatchUpId:t.matchUpId,currentStatus:t.matchUpStatus,newStatus:i}),a){const e=[{matchUpStatus:o,previousMatchUpStatus:i,sideNumber:1},{matchUpStatus:o,previousMatchUpStatus:n.matchUpStatus,sideNumber:2}].map(t=>Ei(t));return aT({...n,matchUp:a,matchUpId:t.matchUpId,matchUpStatus:i,matchUpStatusCodes:e,winningSide:void 0,removeScore:!0})}return{...Y}}({loserMatchUp:s,matchUpsMap:u,params:d,stack:l});if(e)return KO(l,{color:"brightyellow",decision:"SKIP_loserMatchUp_already_doubleExit",loserMatchUpId:s.matchUpId}),{...Y};const{feedRound:g,drawPositions:I,matchUpId:S}=s,y=g?2:2-I.indexOf(n);return KO(l,{color:"cyan",decision:"conditionallyAdvanceLoser",feedRound:g,walkoverWinningSide:y,loserMatchUpId:S}),JO({...d,targetMatchUp:s,walkoverWinningSide:y,tournamentRecord:i,sourceMatchUp:a,matchUpId:S})}({loserMatchUpIsEmptyExit:h,loserMatchUpIsDoubleExit:g,loserTargetDrawPosition:f,appliedPolicies:n,tournamentRecord:e,drawDefinition:r,sourceMatchUp:u,loserMatchUp:l,targetLinks:p,matchUpsMap:i,params:t,event:s,stack:c});if(o?.error)return Ci({result:o,stack:c})}if(m){KO(c,{color:"cyan",decision:"conditionallyAdvanceWinner",winnerMatchUpId:m.matchUpId});const n=JO({...t,matchUpId:m.matchUpId,targetMatchUp:m,tournamentRecord:e,sourceMatchUp:u});if(n.error)return Ci({result:n,stack:c})}return Ci({result:{...Y},stack:c})}function JO(t){const{inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,sourceMatchUp:i,targetMatchUp:o,matchUpsMap:a}=t,s=r.structures.find(({structureId:t})=>t===o.structureId),c=t.matchUpStatus===Tp?Tp:wp,u=t.matchUpStatus===Tp?Pp:Ep,d="conditionallyAdvanceDrawPosition",p=a.drawMatchUps.find(t=>t.matchUpId===o.matchUpId);if(!p)return{error:Se};const l=i?.drawPositions??[];let m=p.drawPositions?.filter(Boolean);const f=i?.structureId===o.structureId;if(KO(d,{newline:!0,color:"magenta",keyColors:{targetMatchUpId:"brightcyan",sourceMatchUpId:"brightyellow"},targetMatchUpId:o.matchUpId,targetStructureId:o.structureId?.slice(0,8),targetRound:[o.roundNumber,o.roundPosition],targetDP:JSON.stringify(p.drawPositions),targetStatus:p.matchUpStatus,targetFeedRound:o.feedRound,sourceMatchUpId:i?.matchUpId,sourceStructureId:i?.structureId?.slice(0,8),sourceRound:i?[i.roundNumber,i.roundPosition]:void 0,sourceDP:JSON.stringify(l),sameStructure:f,paramMatchUpStatus:t.matchUpStatus,EXIT:u,DOUBLE_EXIT:c}),f&&j(l,m)&&(m=m.filter(t=>!l.includes(t))),f&&m.length>1)return Ci({result:{error:mt},stack:d});const{pairedPreviousMatchUpIsDoubleExit:h,pairedPreviousMatchUp:g}=Ky({...t,structure:s});KO(d,{color:"magenta",keyColors:{pairedMatchUpId:"brightcyan"},pairedMatchUpId:g?.matchUpId,pairedRound:g?[g.roundNumber,g.roundPosition]:void 0,pairedStatus:g?.matchUpStatus,pairedStructureId:g?.structureId?.slice(0,8),pairedIsDoubleExit:h});const I=jg({matchUpId:o.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),{targetMatchUps:S,targetLinks:y}=I,{loserTargetDrawPosition:v,winnerMatchUp:U,loserMatchUp:P}=S;if(P){const{loserTargetLink:t}=y,e=XO({loserTargetDrawPosition:v,loserMatchUp:P,tournamentRecord:n,loserTargetLink:t,drawDefinition:r,matchUpsMap:a});if(e.error)return Ci({result:e,stack:d})}const T=p.drawPositions?.filter(Boolean)??[],w=1===T.length,D=t.walkoverWinningSide||w&&Xy({drawPosition:T[0],matchUpId:o.matchUpId,inContextDrawMatchUps:e})||void 0,R=II(p.matchUpStatus)&&!T.length,b=R?c:u;KO(d,{color:"brightyellow",keyColors:{matchUpStatus:"brightgreen",existingExit:"brightred"},existingExit:R,matchUpStatus:b,targetCurrentStatus:p.matchUpStatus,targetDP:JSON.stringify(T),hasDrawPosition:w,walkoverWinningSide:D});const N=function({inContextPairedPreviousMatchUp:t,pairedPreviousMatchUp:e,walkoverWinningSide:n,sourceMatchUp:r,targetMatchUp:i,stack:o}){if(!r)return;let a;r?.structureId===t?.structureId?a=r.roundPosition<e?.roundPosition?1:2:i.feedRound?a=r.structureId===i.structureId?2:1:n&&(a=3-n);return KO(o,{color:"cyan",keyColors:{sourceSideNumber:"brightgreen"},sourceSideNumber:a,sourceStructureId:r.structureId?.slice(0,8),pairedStructureId:t?.structureId?.slice(0,8),targetStructureId:i.structureId?.slice(0,8),sameStructureAsPaired:r?.structureId===t?.structureId,targetFeedRound:i.feedRound,sourceRP:r.roundPosition,pairedRP:e?.roundPosition}),a}({inContextPairedPreviousMatchUp:e.find(t=>t.matchUpId===g.matchUpId),pairedPreviousMatchUp:g,walkoverWinningSide:D,sourceMatchUp:i,targetMatchUp:o,stack:d}),M=t.matchUpStatus,A=g?.matchUpStatus,E=function({sourceMatchUpStatus:t,pairedMatchUpStatus:e,sourceSideNumber:n}){let r=[];1===n?r=[{matchUpStatus:ZO(t),previousMatchUpStatus:t,sideNumber:1},{matchUpStatus:ZO(e),previousMatchUpStatus:e,sideNumber:2}]:2===n&&(r=[{matchUpStatus:ZO(e),previousMatchUpStatus:e,sideNumber:1},{matchUpStatus:ZO(t),previousMatchUpStatus:t,sideNumber:2}]);r.length&&(r=r.map(t=>Ei(t)));return r}({sourceMatchUpStatus:M,pairedMatchUpStatus:A,sourceSideNumber:N});KO(d,{color:"brightgreen",keyColors:{matchUpStatus:"brightcyan",winningSide:"brightyellow"},action:"modifyMatchUpScore",targetMatchUpId:p.matchUpId,matchUpStatus:b,winningSide:D,matchUpStatusCodes:JSON.stringify(E),sourceStatus:M,pairedStatus:A});const C=aT({...t,winningSide:D,matchUp:p,matchUpStatusCodes:E,matchUpStatus:b});return C.error?Ci({result:C,stack:d}):function({pairedPreviousMatchUpIsDoubleExit:t,targetMatchUpDrawPositions:e,noContextTargetMatchUp:n,inContextDrawMatchUps:r,walkoverWinningSide:i,nextWinnerMatchUp:o,drawDefinition:a,existingExit:s,matchUpStatus:c,targetMatchUp:u,matchUpsMap:d,targetData:p,DOUBLE_EXIT:l,structure:m,params:f,stack:h,EXIT:g}){if(s)return KO(h,{color:"brightred",decision:"EXISTING_EXIT_triggers_recursive_doubleExitAdvancement",targetMatchUpId:n.matchUpId,matchUpStatus:c}),QO({...f,matchUpStatus:c,targetData:p});if(!o)return Ci({result:{...Y},stack:h});const I=2===e.length?e[i-1]:e[0],{positionAssignments:S}=cl({structure:m}),y=S?.find(t=>t.drawPosition===I),v=d.drawMatchUps.find(t=>t.matchUpId===o.matchUpId),U=v?.drawPositions?.filter(Boolean),P=1===U.length;if(I)return y?.bye?function({nextWinnerMatchUpDrawPositions:t,nextWinnerMatchUpHasDrawPosition:e,noContextNextWinnerMatchUp:n,inContextDrawMatchUps:r,nextWinnerMatchUp:i,drawDefinition:o,matchUpStatus:a,matchUpsMap:s,params:c,stack:u,EXIT:d}){const p=jg({matchUpId:n.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(e){const e=t.find(Boolean),i=Xy({drawPosition:e,matchUpId:n.matchUpId,inContextDrawMatchUps:r}),a=aT({appliedPolicies:c.appliedPolicies,matchUpId:n.matchUpId,matchUp:n,matchUpStatus:d,matchUpStatusCodes:[],removeScore:!0,drawDefinition:o,winningSide:i});return a.error?Ci({result:a,stack:u}):UI({drawPositionToAdvance:e,matchUpId:n.matchUpId,inContextDrawMatchUps:r,drawDefinition:o,matchUpsMap:s})}if(II(i.matchUpStatus)){const t=QO({...c,matchUpId:n.matchUpId,matchUpStatus:a,targetData:p});if(t.error)return Ci({result:t,stack:u})}return Ci({result:{...Y},stack:u})}({nextWinnerMatchUpDrawPositions:U,nextWinnerMatchUpHasDrawPosition:P,noContextNextWinnerMatchUp:v,inContextDrawMatchUps:r,nextWinnerMatchUp:o,drawDefinition:a,matchUpStatus:c,matchUpsMap:d,params:f,stack:h,EXIT:g}):Zy({matchUpId:o.matchUpId,drawPosition:I,inContextDrawMatchUps:r,drawDefinition:a});if(t){if(!v)return{error:Se};if(P){const t=U[0],e=Xy({matchUpId:u.matchUpId,inContextDrawMatchUps:r,drawPosition:t});console.log("existing drawPosition is winningSide",{walkoverWinningSide:e})}const t=II(v.matchUpStatus)?g:l,e=aT({matchUpId:v.matchUpId,appliedPolicies:f.appliedPolicies,matchUp:v,matchUpStatus:t,matchUpStatusCodes:[],removeScore:!0,drawDefinition:a});if(e.error)return Ci({result:e,stack:h});if(t===l){const e=jg({matchUpId:u.matchUpId,inContextDrawMatchUps:r,drawDefinition:a}),n=QO({...f,matchUpId:u.matchUpId,matchUpStatus:t,targetData:e});if(n.error)return n}}return Ci({result:{...Y},stack:h})}({pairedPreviousMatchUpIsDoubleExit:h,targetMatchUpDrawPositions:m,noContextTargetMatchUp:p,inContextDrawMatchUps:e,walkoverWinningSide:D,nextWinnerMatchUp:U,drawDefinition:r,existingExit:R,matchUpStatus:b,targetMatchUp:o,matchUpsMap:a,targetData:I,DOUBLE_EXIT:c,structure:s,params:t,stack:d,EXIT:u})}function XO(t){const{loserTargetDrawPosition:e,tournamentRecord:n,loserTargetLink:r,drawDefinition:i,matchUpsMap:o,event:a,loserMatchUp:s}=t,c=r?.target?.structureId,{structure:u}=ol({drawDefinition:i,structureId:c});return u?SI({drawPosition:e,tournamentRecord:n,drawDefinition:i,structureId:c,matchUpsMap:o,loserMatchUp:s,event:a}):{error:jt}}function ZO(t){return t===wp?Ep:t===Tp?Pp:t}function tk(t){const{tournamentRecord:e,drawDefinition:n,matchUpStatus:r,structure:i,matchUp:o}=t,a=!(!o.tieMatchUps||o.rondPosition||!t.inContextDrawMatchUps.find(t=>t.matchUpId===o.matchUpId).containerStructureId),s="attemptToSetMatchUpStatus",c=r===Sp,u=o.winningSide,d=[wp,Tp].includes(r),p=sI({matchUpStatus:r}),l=cI({matchUpStatus:r}),m=!p&&!l,f=t.matchUpTieId||u&&p&&!d,h=u&&d;fI({method:s,newline:!0,color:"brightyellow",keyColors:{matchUpStatus:"brightcyan",matchUpId:"brightmagenta"},matchUpId:o.matchUpId,matchUpStatus:r,existingStatus:o.matchUpStatus,existingWinningSide:u,isDoubleExit:d,isBYE:c,directing:p,nonDirecting:l,unrecognized:m,onlyModifyScore:f,changeCompletedToDoubleExit:h,propagateExitStatus:t.propagateExitStatus,teamRoundRobinContext:a});return fI({method:s,color:"brightgreen",keyColors:{route:"brightcyan"},route:(m?"unrecognized":f&&"onlyModifyScore")||h&&"changeCompletedToDoubleExit"||u&&"existingWinningSide_removeDirected"||l&&"nonDirecting_clearScore"||c&&"isBYE"||!p&&"notDirecting_error"||d&&"isDoubleExit_modifyAndAdvance"||a&&"teamRoundRobinContext"||t.propagateExitStatus&&"propagateExitStatus"||"fallthrough_error",matchUpId:o.matchUpId}),m&&{error:ie}||f&&ek(t)||h&&function(t){const e=HO(t);return e.error?e:QO(t)}(t)||u&&HO(t)||l&&aT({...t,removeScore:[yp,Ep].includes(r),matchUpStatus:r||Ap})||c&&function({tournamentRecord:t,drawDefinition:e,structure:n,matchUp:r}){const i="attemptToSetMatchUpStatusBYE";if(r?.winningSide)return Ci({result:{error:ce},context:{matchUpStatus:Sp},stack:i});const{positionAssignments:o}=ul({structure:n}),a=o?.filter(t=>t.bye).map(t=>t.drawPosition),s=r.drawPositions?.some(t=>a?.includes(t));return s?(r.matchUpStatus=Sp,r.matchUpStatusCodes=[],Yl({tournamentId:t?.tournamentId,context:i,drawDefinition:e,matchUp:r}),{...Y}):Ci({result:{error:ne},info:"matchUp does not include BYE",stack:i})}({tournamentRecord:e,drawDefinition:n,structure:i,matchUp:o})||!p&&{error:ie}||d&&function(t){const e=ek({...t,removeScore:!0});return e.error?e:QO(t)}(t)||a&&ek(t)||t.propagateExitStatus&&ek(t)||Ci({result:{error:ce,info:"matchUpStatus: "+r},stack:s})}function ek(t){const e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){const n=HO(t);if(n.error)return Ci({result:n,stack:e})}const n=Boolean(t.matchUp.collectionId),r=aT({...t});if(n){const{matchUpTieId:n,drawDefinition:i,matchUpsMap:o}=t,a=gT({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:n,event:t.event,drawDefinition:i,matchUpsMap:o});if(a.error)return Ci({result:a,stack:e});Object.assign(r,{tieMatchUpResult:a})}return Ci({result:r,stack:e})}function nk({drawDefinition:t,structure:e,matchUp:n}){const r=[];if(e.finishingPosition===pc){if(PU({drawDefinition:t,structure:e})){const{structureIds:i}=function({drawDefinition:t,structure:e,matchUp:n}){const{drawPositions:r}=n,{positionAssignments:i}=cl({drawDefinition:t,structure:e}),o=i?.filter(({drawPosition:t})=>r?.includes(t)),a=o?.map(t=>{const e=dp({element:t,attribute:"tally",name:Rd});return e?.groupOrder}),{containerStructures:s}=nm({drawDefinition:t}),c=s[e.structureId],u=Vg({drawDefinition:t,structureId:c})?.links?.source,d=u?.filter(t=>j(a,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 rk(t){const{inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:r,winningSide:i,random:o}=t,a=t.targetData.targetLinks?.winnerTargetLink;if(a.target.feedProfile!==Rs)return{...Y,qualifierPlaced:void 0};const s=n.sides.find(({sideNumber:t})=>t===i)?.participantId,c=function({inContextDrawMatchUps:t,winnerTargetLink:e,random:n}){const r=t.filter(t=>t.structureId===e.target.structureId&&t.roundNumber===e.target.roundNumber&&t.sides.some(({participantId:t,qualifier:e})=>e&&!t));return _(r,n)}({inContextDrawMatchUps:e,winnerTargetLink:a,random:o});if(c?.matchUpStatus!==Ap)return{...Y,qualifierPlaced:void 0};return Cw({inContextDrawMatchUps:e,drawDefinition:r,targetData:jg({matchUpId:c.matchUpId,inContextDrawMatchUps:e,drawDefinition:r})})?{...Y,qualifierPlaced:void 0}:function({mainDrawTargetMatchUp:t,winningQualifierId:e,drawDefinition:n,params:r}){const i=t.sides.find(t=>t.qualifier&&!t.participantId)?.drawPosition,{structure:o}=ol({structureId:t.structureId,drawDefinition:n});if(!o)return{error:Vt};const a=cl({structure:o}).positionAssignments;let s;for(const t of a??[])t.drawPosition!==i||t.participantId||(t.participantId=e,ik(o,a),Xl({tournamentId:r.tournamentRecord?.tournamentId,event:r.event,drawDefinition:n,structure:o}),s=!0);return{...Y,qualifierPlaced:s}}({mainDrawTargetMatchUp:c,winningQualifierId:s,drawDefinition:r,params:t})}function ik(t,e){if(t.positionAssignments)t.positionAssignments=e;else if(t.structures){const n=Object.assign({},...(e??[]).map(t=>({[t.drawPosition]:t.participantId})));for(const e of t.structures)e.positionAssignments?.forEach(t=>t.participantId=n[t.drawPosition])}}function ok(t){const e="attemptToSetWinningSide";let n;const r={},{appliedPolicies:i,disableAutoCalc:o,drawDefinition:a,dualMatchUp:s,winningSide:c,structure:u,matchUp:d}=t;if(s?._disableAutoCalc&&!1!==o)return sT(t);if(d.winningSide&&d.winningSide!==c){const{connectedStructureIds:e}=nk({drawDefinition:a,structure:u,matchUp:d});e.length&&(n=!0);const r=HO(t);if(r.error)return r}const p=yT(t);if(p.context?.progressExitStatus&&Object.assign(r,p.context),p.error)return Ci({result:p,stack:e});let l,m;return t.qualifierChanging&&i?.[Cu]?.autoReplaceQualifiers&&(l=function(t){let e;const{inContextDrawMatchUps:n,inContextMatchUp:r,drawDefinition:i,winningSide:o}=t,a=t.targetData.targetLinks?.winnerTargetLink;if(a.target.feedProfile===Rs){const s=r.sides.find(({sideNumber:t})=>t!==o).participantId,c=n.find(t=>t.structureId===a.target.structureId&&t.roundNumber===a.target.roundNumber&&t.sides.some(({participantId:t})=>t===s));if(c?.matchUpStatus===Ap&&!Cw({inContextDrawMatchUps:n,drawDefinition:i,targetData:jg({matchUpId:c.matchUpId,inContextDrawMatchUps:n,drawDefinition:i})})){const{structure:n}=ol({structureId:c.structureId,drawDefinition:i}),a=cl({structure:n}).positionAssignments;for(const c of a??[])if(c.participantId===s){const s=r.sides.find(({sideNumber:t})=>t===o).participantId;if(c.participantId=s,n?.positionAssignments)n.positionAssignments=a;else if(n?.structures){const t=Object.assign({},...(a??[]).map(t=>({[t.drawPosition]:t.participantId})));for(const e of n.structures)e.positionAssignments?.forEach(e=>e.participantId=t[e.drawPosition])}Xl({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:i,structure:n}),e=!0}}}return{...Y,qualifierReplaced:e}}(t).qualifierReplaced),t.qualifierAdvancing&&i?.[Cu]?.autoPlaceQualifiers&&(m=rk(t).qualifierPlaced),Ci({result:Ei({...Y,...p,connectedStructures:n,qualifierReplaced:l,qualifierPlaced:m,context:r}),stack:e})}const ak={drawPositionToRemove:"green",iteration:"brightred",winner:"green",loser:"brightred"};function sk(t){const{inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:i,targetData:o,matchUp:a}=t,{matchUpId:s}=a;let{iteration:c=0}=t;c+=1;const u="removeDoubleExit";fI({color:"brightyellow",method:u,matchUpId:s,iteration:c,keyColors:ak});const{targetMatchUps:{loserMatchUp:d,winnerMatchUp:p,loserTargetDrawPosition:l},targetLinks:{loserTargetLink:m}}=o;if(p&&p.matchUpStatus!==Sp){const{stage:e,roundNumber:n,roundPosition:r,structureName:i}=p;fI({winner:"winner",roundPosition:r,structureName:i,roundNumber:n,keyColors:ak,stage:e}),ck({...t,targetMatchUp:p,sourceMatchUp:a,iteration:c})}const f=d?.matchUpStatus===Sp&&(d?.feedRound||1===d?.roundNumber);if(f&&o?.targetLinks?.loserTargetLink?.linkCondition===Os){const t=e.filter(({roundNumber:t,structureId:e})=>e===a.structureId&&1===t),n=q(t.map(({roundPosition:t})=>t).sort((t,e)=>t-e),2).find(t=>t.includes(a.roundPosition)),r=t.filter(({roundPosition:t})=>n.includes(t))?.map(({matchUpStatus:t})=>t);if(r.every(t=>[Tp,wp].includes(t)))return Ci({result:{...Y},stack:u})}if(d&&(d.matchUpStatus!==Sp||f)){const o=e.find(({matchUpId:t})=>t===d.matchUpId),{structure:a}=ol({drawDefinition:r,structureId:o.structureId}),{stage:s,roundNumber:p,roundPosition:h,feedRound:g,structureName:I}=d;if(fI({loser:"loser",roundPosition:h,structureName:I,roundNumber:p,keyColors:ak,feedRound:g,stage:s}),n?.progression?.doubleExitPropagateBye||f)YO({drawPosition:l,targetLink:m,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:i});else{const e=ck({...t,targetMatchUp:d,structure:a,iteration:c});if(e.error)return Ci({result:e,stack:u})}}return Ci({result:{...Y},stack:u})}function ck(t){const{inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,sourceMatchUp:i,targetMatchUp:o,matchUpsMap:a,structure:s,iteration:c}=t,u="conditionallyRemoveDrawPosition";fI({method:u,structureName:s?.structureName,iteration:c});const d=jg({matchUpId:o.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),{targetMatchUps:{winnerMatchUp:p}}=d,l=a?.drawMatchUps.find(t=>t.matchUpId===o.matchUpId);let m,f,h;if(o.feedRound){const t=p?.drawPositions?.filter(Boolean);h=t?.find(t=>o.drawPositions.includes(t))}else if(null==i)h=V(o?.drawPositions??[],p?.drawPositions??[])?.[0];else{f=Qy({structureId:s.structureId,matchUp:i,matchUpsMap:a})?.pairedPreviousMatchUp,m=[wp,Tp].includes(f?.matchUpStatus);let t=f?.drawPositions?.filter(Boolean)??[];if([..._p,Sp].includes(f?.matchUpStatus)||f?.winningSide){const e=i.drawPositions??[];let n=o.drawPositions?.filter(Boolean);j(e,n)&&(n=n?.filter(t=>!e.includes(t)));h=e.concat(t).find(t=>n?.includes(t))}}if(p&&h){const{stage:t,roundNumber:n,roundPosition:i,structureName:o}=p;fI({method:"removeDirectedWinner",drawPositionToRemove:h,color:"brightgreen",roundPosition:i,structureName:o,roundNumber:n,keyColors:ak,stage:t}),zO({winningDrawPosition:h,winnerMatchUp:p,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:a})}let g=sk({targetData:d,matchUp:o,inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:a,structure:s,iteration:c});if(g.error)return Ci({result:g,stack:u});const I=function({pairedPreviousDoubleExit:t,noContextTargetMatchUp:e}){return e.matchUpStatus===Sp?Sp:t?[Tp,Pp].includes(e?.matchUpStatus)?Pp:Ep:Ap}({pairedPreviousDoubleExit:m,noContextTargetMatchUp:l}),S=!m;return g=aT({...t,matchUpId:o.matchUpId,matchUp:l,removeWinningSide:!0,matchUpStatusCodes:[],matchUpStatus:I,removeScore:S,score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0}}),g.error?Ci({result:g,stack:u}):{...Y}}function uk(t){const{matchUp:e,matchUpStatus:n,score:r,winningSide:i}=t,o="noDownStreamDependencies";if([wp,Tp].includes(e?.matchUpStatus)&&![wp,Tp].includes(n)){const e=sk(t);if(e.error)return Ci({result:e,stack:o})}const a=n===wp,s=[Dp,Mp,yp,gp,Rp],c=aI({score:r})&&!a&&!s.includes(n)&&(t.isCollectionMatchUp&&!t.projectedWinningSide||!i),u=t?.inContextMatchUp?.collectionId&&function(t){const{matchUpFormat:e,score:n}=t,r=n?.sets?.length,i=e&&co(e),{setFormat:o,finalSetFormat:a,bestOf:s}=i??{},c=s&&r===s&&a||o;return c?.timed||!1}(t.inContextMatchUp),d=t.removeScore||!u&&![Rp,gp].includes(n||Rp),p=t.isCollectionMatchUp&&t.dualMatchUp.winningSide&&!t.projectedWinningSide||e.winningSide&&!i&&!aI({score:r}),l=n=>{let r;const{structure:i,drawDefinition:o,dualMatchUp:a,disableAutoCalc:s}=t;if(a?._disableAutoCalc&&!1!==s)return sT({...t,removeWinningSide:p});const{connectedStructureIds:c}=nk({drawDefinition:o,structure:i,matchUp:e});c.length&&(r=!0),Object.assign(t,{removeScore:n});const u=HO(t);if(u.error)return u;if(t.removingQualifier&&t.appliedPolicies?.[Cu]?.autoRemoveQualifiers){const e=function(t){let e;const{inContextDrawMatchUps:n,inContextMatchUp:r,drawDefinition:i}=t,o=t.targetData.targetLinks?.winnerTargetLink;if(o.target.feedProfile===Rs){const a=r.sides?.find(({sideNumber:t})=>t===r.winningSide)?.participantId,s=n.find(t=>t.structureId===o.target.structureId&&t.roundNumber===o.target.roundNumber&&t.sides?.some(({participantId:t})=>t===a));if(s&&s.matchUpStatus===Ap&&!Cw({inContextDrawMatchUps:n,drawDefinition:i,targetData:jg({matchUpId:s.matchUpId,inContextDrawMatchUps:n,drawDefinition:i})})){const{structure:n}=ol({structureId:s.structureId,drawDefinition:i}),r=cl({structure:n}).positionAssignments;for(const o of r??[])if(o.participantId===a){if(o.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])}Xl({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:i,structure:n}),e=!0}}}return{qualifierRemoved:e}}(t);return{...Y,connectedStructures:r,...e}}return{...Y,connectedStructures:r}};if(p&&i&&t.isCollectionMatchUp)return dk(t);const m=[yp,gp].includes(n)&&t.dualWinningSideChange,f=n&&n!==Ap,h=t.propagateExitStatus&&II(n);return Ci({result:(i||m||h)&&ok(t)||c&&l(d)||f&&tk(t)||p&&l(d)||e&&dk({...t,removeScore:!0})||{...Y},stack:o})}function dk(t){if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide&&!t.autoCalcDisabled){const e=HO(t);if(e.error)return e}const e=aT({...t});if(t.isCollectionMatchUp){const{matchUpTieId:e,drawDefinition:n,event:r,matchUpsMap:i}=t,{removeWinningSide:o}=gT({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:e,drawDefinition:n,matchUpsMap:i,event:r});o&&console.log("REMOVE WINNING SIDE")}return Ci({result:e,stack:"ndd:scoreModification"})}function pk(t){const e="setFirstClassOrTimeItem",n=function(t){return"object"!=typeof t?{error:Ae}:t.element&&"object"==typeof t.element&&"string"==typeof t.attribute&&t.attribute&&"string"==typeof t.itemType&&t.itemType?null:{error:sr}}(t);if(n)return Ci({result:n,stack:e});const{element:r,scheduleObject:i="schedule",attribute:o,itemType:a,value:s}=t;if(Qr()&&(function(t,e,n,r){null!=r?(t[e]||(t[e]={}),t[e][n]=r):t[e]&&delete t[e][n]}(r,i,o,s),function(t,e){Array.isArray(t.timeItems)&&(t.timeItems=t.timeItems.filter(t=>t?.itemType!==e))}(r,a)),!Jr())return{...Y};const c=function(t){const{element:e,itemType:n,value:r,itemSubTypes:i,itemDate:o,removePriorValues:a,duplicateValues:s}=t,c={itemType:n,itemValue:r};return i?.length&&(c.itemSubTypes=i),o&&(c.itemDate=o),nU({element:e,timeItem:c,removePriorValues:a,duplicateValues:s})}({element:r,itemType:a,value:s,itemSubTypes:t?.itemSubTypes,itemDate:t?.itemDate,removePriorValues:t?.removePriorValues,duplicateValues:t?.duplicateValues});return c.error?Ci({result:c,stack:e}):{...Y}}function lk({tournamentRecord:t,removePriorValues:e,duplicateValues:n,drawDefinition:r,disableNotice:i,itemSubTypes:o,itemDate:a,matchUpId:s,attribute:c,itemType:u,value:d,event:p}){const{matchUp:l}=nT({drawDefinition:r,event:p,matchUpId:s});if(!l)return{error:ge};const m=pk({element:l,scheduleObject:"schedule",removePriorValues:e,duplicateValues:n,itemSubTypes:o,itemDate:a,attribute:c,itemType:u,value:d});return m.error||i||Yl({tournamentId:t?.tournamentId,eventId:p?.eventId,context:"setFirstClassOrTimeItem",drawDefinition:r,matchUp:l}),m}function mk(t){const e=fu(t,[{[Ic]:!0,[yc]:!0,[kc]:!0},{homeParticipantId:!0,[Hc]:sn}]);if(e.error)return e;const n=UE(t,[{[Yc]:Wc,attr:{[xc]:!0}}]);if(n.error)return n;const r=n?.matchUp?.matchUp?.sides?.map(t=>t?.participantId);if(t.homeParticipantId&&!r?.includes(t.homeParticipantId))return{error:Ze};const{disableNotice:i,homeParticipantId:o,removePriorValues:a,tournamentRecord:s,drawDefinition:c,matchUpId:u}=t;return lk({duplicateValues:!1,attribute:"homeParticipantId",itemType:ih,value:o,removePriorValues:a,tournamentRecord:s,drawDefinition:c,disableNotice:i,matchUpId:u})}function fk({timeStamp:t,schedule:e,matchUp:n}){const{itemValue:r,timeStamp:i}=tg({timeItems:n?.timeItems??[],itemType:ph});return!e||i&&t&&new Date(i).getTime()>new Date(t).getTime()?{timeModifiers:r}:e}function hk(t){const e="addMatchUpScheduledTime";let n=t.matchUp;const{removePriorValues:r,tournamentRecord:i,drawDefinition:o,disableNotice:a,scheduledTime:s,matchUpId:c}=t;if(!c)return Ci({result:{error:fe},stack:e});if(!wo(s))return Ci({result:{error:Le},stack:e});if(!n){const t=nT({drawDefinition:o,matchUpId:c});if(t.error)return Ci({result:t,stack:e});n=t.matchUp}const u=Lo(s),d=ng({matchUp:n}).scheduledDate,p=u&&!d,l=fk({matchUp:n}).timeModifiers??[];if(l?.length){const t=gk({disableNotice:!0,removePriorValues:r,tournamentRecord:i,timeModifiers:[],drawDefinition:o,matchUpId:c,matchUp:n});if(t?.error)return Ci({result:t,stack:e})}const m=Go(s,!0,p);return lk({duplicateValues:!1,attribute:"scheduledTime",itemType:ah,value:m,removePriorValues:r,tournamentRecord:i,drawDefinition:o,disableNotice:a,matchUpId:c})}function gk({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,timeModifiers:i,matchUpId:o,matchUp:a}){const s="addMatchUpTimeModifiers";if(!o)return Ci({result:{error:fe},stack:s});if(void 0!==i&&!Array.isArray(i))return Ci({info:nv("timeModifiers"),result:{error:sr},stack:s});if(!a){const t=nT({drawDefinition:n,matchUpId:o});if(t.error)return Ci({result:t,stack:s});a=t.matchUp}let c=fk({matchUp:a}).timeModifiers??[];const u=i.filter(t=>!c.includes(t));if(i.length&&!u.length)return{...Y};if(u.some(t=>Ih.includes(t))){c=c.filter(t=>!Ih.includes(t));const r=hk({disableNotice:!0,removePriorValues:t,scheduledTime:"",tournamentRecord:e,drawDefinition:n,matchUpId:o});if(r.error)return Ci({result:r,stack:s})}const d=i?.length?[...u,...c]:void 0;return lk({duplicateValues:!1,attribute:"timeModifiers",itemType:ph,value:d,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:o})}function Ik({scheduledDate:t,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o}){if(!o)return{error:fe};const a=t&&vo.test(t);if(t&&!a)return{error:_e};const s=Lo(t);if(s&&n?.startDate&&n?.endDate){const t=new Date(s).getTime(),e=new Date(Lo(n.startDate)).getTime(),r=new Date(Lo(n.endDate)).getTime();if(t<e||t>r)return Ci({result:{error:_e},info:"scheduledDate must be within tournament start and end dates",stack:"addMatchUpScheduledDate"})}return lk({duplicateValues:!1,attribute:"scheduledDate",itemType:rh,value:s,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o})}function Sk({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,courtDayDate:a,matchUpId:s,courtIds:c}){if(!n&&!e)return{error:rt};if(!s)return{error:fe};const u=nT({drawDefinition:r,matchUpId:s});if(u.error)return u;if(u?.matchUp?.matchUpType!==o)return{error:ye};if(!(void 0===c||Array.isArray(c)&&c.length&&c.every(t=>"string"==typeof t)))return{error:sr,context:{courtIds:c}};let d;if(c){const t=gw({tournamentRecords:e||n&&{[n.tournamentId]:n}});if(t.error)return t;const r=t.courts?.filter(t=>c.includes(t.courtId));if(r?.length!==c.length)return{error:sr,context:{courtIds:c}};d=r?.map(t=>({venueId:t.venueId,courtId:t.courtId}))}return lk({duplicateValues:!1,attribute:"allocatedCourts",itemType:Zf,itemDate:a,value:d,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:s})}function yk({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o,venueId:a}){if(!n)return{error:rt};if(!o)return{error:fe};if(a){const t=Ig({tournamentRecords:e,tournamentRecord:n,venueId:a});if(t.error)return t}return lk({duplicateValues:!1,attribute:"venueId",itemType:Xf,value:a,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o})}function vk({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,courtDayDate:o,matchUpId:a,courtId:s}){if(!n&&!e)return{error:rt};if(!a)return{error:fe};if(s){const t=yg({tournamentRecords:e,tournamentRecord:n,courtId:s});if(t.error)return t;const o=t.venue?.venueId;yk({tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a,venueId:o})}return lk({duplicateValues:!1,attribute:"courtId",itemType:th,itemDate:o,value:s,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:a})}function Uk(t,e){const n=yo.test(t)?t:_o(t),r=Lo(t)||Lo(e)||bo(new Date);return new Date(`${r}T${n}`).getTime()}function Pk({proConflictDetection:t,removePriorValues:e,tournamentRecords:n,tournamentRecord:r,drawDefinition:i,homeParticipantId:o,timeModifiers:a,courtAnnotation:s,scheduledDate:c,courtOrder:u,courtIds:d,courtId:l,venueId:f,matchUpId:h,matchUp:g,stack:I}){if(void 0!==d){const t=Sk({disableNotice:!0,removePriorValues:e,tournamentRecord:r,drawDefinition:i,matchUpId:h,courtIds:d});if(t?.error)return Ci({result:t,stack:I,context:{courtIds:d}})}const S=function({proConflictDetection:t,tournamentRecord:e,scheduledDate:n,courtOrder:r,matchUpId:i,courtId:o,stack:a}){if(!t||void 0===o||void 0===n||void 0===r||!R(r))return;const s=p(r),c=Qg({tournamentRecord:e})?.matchUps??[],u=c.find(t=>{if(t.matchUpId===i)return!1;const e=t.schedule?.courtOrder?p(t.schedule.courtOrder):void 0;return t.schedule?.courtId===o&&e===s&&t.schedule?.scheduledDate===n});if(u)return Ci({result:{error:ht,info:`Court slot already occupied by matchUp ${u.matchUpId}`},stack:a,context:{courtId:o,courtOrder:r,scheduledDate:n}});return}({proConflictDetection:t,tournamentRecord:r,scheduledDate:c,courtOrder:u,matchUpId:h,courtId:l,stack:I});if(S)return S;if(void 0!==l&&void 0!==c){const t=vk({courtDayDate:c,disableNotice:!0,removePriorValues:e,tournamentRecords:n,tournamentRecord:r,drawDefinition:i,matchUpId:h,courtId:l});if(t?.error)return Ci({result:t,stack:I,context:{courtId:l}})}if(void 0!==f){const t=yk({disableNotice:!0,removePriorValues:e,tournamentRecords:n,tournamentRecord:r,drawDefinition:i,matchUpId:h,venueId:f});if(t?.error)return Ci({result:t,stack:I,context:{venueId:f}})}if(void 0!==u){const t=wk({disableNotice:!0,removePriorValues:e,tournamentRecord:r,drawDefinition:i,courtOrder:u,matchUpId:h});if(t?.error)return Ci({result:t,stack:I,context:{courtOrder:u}})}if(void 0!==s){const t=function({removePriorValues:t,tournamentRecord:e,drawDefinition:n,courtAnnotation:r,disableNotice:i,matchUpId:o}){if(!o)return{error:fe};const a=r||void 0;return lk({duplicateValues:!1,attribute:"courtAnnotation",itemType:nh,value:a,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:i,matchUpId:o})}({disableNotice:!0,removePriorValues:e,tournamentRecord:r,drawDefinition:i,courtAnnotation:s,matchUpId:h});if(t?.error)return Ci({result:t,stack:I,context:{courtAnnotation:s}})}if(void 0!==a){const t=gk({disableNotice:!0,removePriorValues:e,tournamentRecord:r,drawDefinition:i,timeModifiers:a,matchUpId:h,matchUp:g});if(t?.error)return Ci({result:t,stack:I,context:{timeModifiers:a}})}m(o)&&mk({disableNotice:!0,homeParticipantId:o,removePriorValues:e,tournamentRecord:r,drawDefinition:i,matchUpId:h})}function Tk(t){const e="addMatchUpScheduleItems",n=fu(t,[{drawDefinition:!0,matchUpId:!0},{schedule:!0,[cu]:ru}],e);if(n.error)return n;let{matchUpDependencies:r,inContextMatchUps:i}=t;const{proConflictDetection:o=!1,errorOnAnachronism:a=!1,checkChronology:s=!0,removePriorValues:c,tournamentRecords:u,tournamentRecord:d,drawDefinition:p,disableNotice:l,drawMatchUps:m,matchUpId:f,schedule:h,event:g}=t;let I,S;if(m)I=m.find(t=>t.matchUpId===f);else{const t=nT({drawDefinition:p,event:g,matchUpId:f});if(t.error)return t;I=t.matchUp}const{endTime:y,courtId:v,courtIds:U,courtAnnotation:P,courtOrder:T,resumeTime:w,homeParticipantId:D,scheduledDate:R,scheduledTime:b,startTime:N,stopTime:M,timeModifiers:A,venueId:E}=h;!s||r&&i||({matchUpDependencies:r,matchUps:i}=iI({drawDefinition:p}));const C=r?.[f]?.matchUpIds;if(h.scheduledDate&&s&&C){const t=i?.filter(t=>(t.schedule?.scheduledDate||Lo(t.schedule?.scheduledTime))&&C.includes(t.matchUpId)).map(({schedule:t})=>{const e=Po(t);return new Date(e??"").getTime()});if(t?.length){const n=Po(h),r=new Date(n??"").getTime();if(Math.max(...t)>=r){if(a)return Ci({result:{error:X},stack:e});S=X}}}const O=function({removePriorValues:t,tournamentRecord:e,drawDefinition:n,scheduledDate:r,scheduledTime:i,startTime:o,stopTime:a,resumeTime:s,endTime:c,matchUpId:u,matchUp:d,event:p,stack:l}){if(void 0!==r){const i=Ik({disableNotice:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,scheduledDate:r,matchUpId:u});if(i?.error)return Ci({result:i,stack:l,context:{scheduledDate:r}})}if(void 0!==i){const r=hk({disableNotice:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,scheduledTime:i,matchUpId:u,matchUp:d});if(r?.error)return Ci({result:r,stack:l,context:{scheduledTime:i}})}if(void 0!==o){const r=Rk({disableNotice:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,matchUpId:u,startTime:o,event:p});if(r?.error)return Ci({result:r,stack:l,context:{startTime:o}})}if(void 0!==a){const r=Mk({disableNotice:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,matchUpId:u,stopTime:a,event:p});if(r?.error)return Ci({result:r,stack:l,context:{stopTime:a}})}if(void 0!==s){const r=Ak({disableNotice:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,resumeTime:s,matchUpId:u,event:p});if(r?.error)return Ci({result:r,stack:l,context:{resumeTime:s}})}if(void 0!==c){const r=bk({disableNotice:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,matchUpId:u,endTime:c,event:p});if(r?.error)return Ci({result:r,stack:l,context:{endTime:c}})}}({removePriorValues:c,tournamentRecord:d,drawDefinition:p,scheduledDate:R,scheduledTime:b,startTime:N,stopTime:M,resumeTime:w,endTime:y,matchUpId:f,matchUp:I,event:g,stack:e});if(O?.error)return O;const k=Pk({proConflictDetection:o,removePriorValues:c,tournamentRecords:u,tournamentRecord:d,drawDefinition:p,homeParticipantId:D,timeModifiers:A,courtAnnotation:P,scheduledDate:R,courtOrder:T,courtIds:U,courtId:v,venueId:E,matchUpId:f,matchUp:I,stack:e});return k?.error?k:(l||Yl({tournamentId:d?.tournamentId,eventId:g?.eventId,context:e,drawDefinition:p,matchUp:I}),S?{...Y,warnings:[S]}:{...Y})}function wk({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,courtOrder:i,matchUpId:o}){if(!o)return{error:fe};if(i&&!R(i))return{error:sr,info:"courtOrder must be numeric"};const a=i&&p(i);return lk({duplicateValues:!1,attribute:"courtOrder",itemType:eh,value:a,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:o})}function Dk({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,participantId:i,officialType:o,matchUpId:a}){if(!a)return{error:fe};if(!i)return{error:sn};if(e){if(!ju({tournamentParticipants:xS({tournamentRecord:e,participantFilters:{participantTypes:[gm],participantRoles:[dy]}}).participants??[],participantId:i}))return{error:un}}return lk({duplicateValues:!1,attribute:"official",itemType:"SCHEDULE.ASSIGNMENT.OFFICIAL",itemSubTypes:o?[o]:void 0,value:i,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:a})}function Rk({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,startTime:o,event:a}){if(!i)return{error:fe};if(!wo(o))return{error:Le};const{matchUp:s}=nT({drawDefinition:n,event:a,matchUpId:i}),{scheduledDate:c}=ng({matchUp:s}),u=(s?.timeItems??[]).filter(t=>[ch,uh,dh].includes(t?.itemType)).map(t=>Uk(t.itemValue,c)).reduce((t,e)=>!t||e<t?e:t,void 0);if(!u||Uk(o,c)<u){s?.timeItems&&(s.timeItems=s.timeItems.filter(t=>t.itemType!==sh));const a=Go(o,!0,!0);return EO({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,timeItem:{itemType:sh,itemValue:a}})}return{error:qn}}function bk({validateTimeSeries:t=!0,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o,endTime:a,event:s}){if(!o)return{error:fe};if(!wo(a))return{error:Le};const{matchUp:c}=nT({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:u}=ng({matchUp:c}),d=(c?.timeItems??[]).filter(t=>[sh,uh,ch].includes(t?.itemType)).map(t=>Uk(t.itemValue,u)).reduce((t,e)=>!t||e>t?e:t,void 0);if(!t||!d||Uk(a,u)>d){c?.timeItems&&(c.timeItems=c.timeItems.filter(t=>t.itemType!==dh));const t=Go(a,!0,!0);return EO({duplicateValues:!1,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:i,matchUpId:o,timeItem:{itemType:dh,itemValue:t}})}return{error:Vn}}function Nk({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,invalidError:i,matchUpId:o,itemType:a,timeValue:s,event:c}){if(!o)return{error:fe};if(!wo(s))return{error:Le};const{matchUp:u}=nT({drawDefinition:n,event:c,matchUpId:o}),{scheduledDate:d}=ng({matchUp:u}),p=u?.timeItems??[];if(p.reduce((t,e)=>e.itemType===dh||t,void 0))return{error:Gn};const l=p.filter(t=>[sh,uh,ch].includes(t?.itemType)).sort((t,e)=>Uk(t.itemValue,d)-Uk(e.itemValue,d)),m=l.at(-1),f=m?.itemType===a,h=l.filter(t=>!f||t!==m).map(t=>Uk(t.itemValue,d)).reduce((t,e)=>!t||e>t?e:t,void 0);if(Uk(s,d)>h){u?.timeItems&&f&&(u.timeItems=u.timeItems.filter(t=>t!==m));return EO({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:o,timeItem:{itemValue:Go(s,!0,!0),itemType:a}})}return{error:i}}function Mk({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,stopTime:o,event:a}){return Nk({invalidError:jn,timeValue:o,itemType:ch,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,event:a})}function Ak({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,resumeTime:i,matchUpId:o,event:a}){return Nk({invalidError:Wn,timeValue:i,itemType:uh,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:o,event:a})}function Ek(t){t.matchUpStatus&&[Ep,wp].includes(t.matchUpStatus)&&(t.score=void 0);const{disableScoreValidation:e,propagateExitStatus:n,tournamentRecord:r,disableAutoCalc:i,enableAutoCalc:o,drawDefinition:s,matchUpStatus:c,winningSide:u,matchUpId:d,event:p,score:l}=t,m=function({drawDefinition:t,matchUpStatus:e,winningSide:n}){if(!t)return{error:st};if(e&&[yp,Rp,gp,Ap].includes(e)&&n)return{error:sr,winningSide:n,matchUpStatus:e};if(![void 0,...kp].includes(e))return Ci({result:{error:ce},info:"matchUpStatus does not exist",stack:"setMatchUpStatus"});return}({drawDefinition:s,matchUpStatus:c,winningSide:u});if(m)return m;const h=function({tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r,matchUpStatus:i,winningSide:o}){const s=bf({drawDefinition:e}),{matchUps:c}=zg({nextMatchUps:!0,tournamentRecord:t,inContext:!0,drawDefinition:e,matchUpsMap:s,event:r}),u=s.drawMatchUps.find(t=>t.matchUpId===n),d=c?.find(t=>t.matchUpId===n);if(!u||!c)return{error:ge};if((u.winningSide||o)&&i===Sp)return{context:"Cannot have Bye with winningSide",error:ae,matchUpStatus:i};const p=d?.structureId,{structure:l}=ol({drawDefinition:e,structureId:p}),m=bh(a)(u.matchUpType),f=d?.drawPositions?.filter(Boolean),h=d?.matchUpTieId;return{inContextDrawMatchUps:c,assignedDrawPositions:f,inContextMatchUp:d,matchUpTieId:h,matchUpsMap:s,structure:l,matchUp:u,isTeam:m}}({tournamentRecord:r,drawDefinition:s,matchUpId:d,event:p,matchUpStatus:c,winningSide:u});if(h.error)return h;const{matchUp:g,inContextMatchUp:I,inContextDrawMatchUps:S,matchUpsMap:y,structure:v,isTeam:U,assignedDrawPositions:P,matchUpTieId:T}=h,w=jg({matchUpId:T||d,inContextDrawMatchUps:S,drawDefinition:s});Object.assign(t,{inContextDrawMatchUps:S,inContextMatchUp:I,matchUpTieId:T,matchUpsMap:y,targetData:w,structure:v,matchUp:g});const D=c===Ap&&""===l?.scoreStringSide1&&""===l?.scoreStringSide2&&!u,R=function(t){const{targetData:e,matchUpsMap:n}=t,{targetMatchUps:{loserMatchUp:r}}=e,i=II(r?.matchUpStatus),o=!!n?.drawMatchUps.find(t=>t.loserMatchUpId===r?.matchUpId&&II(t.matchUpStatus));return o&&r?.matchUpStatus===wp||o&&i}(t);if(R&&D)return{error:se};const b=Cw(t);let N;if(U){const e=function({tournamentRecord:t,inContextMatchUp:e,activeDownstream:n,disableAutoCalc:r,enableAutoCalc:i,drawDefinition:o,winningSide:a,matchUpsMap:s,structure:c,matchUp:u,params:d,event:p}){let l;if(r)sp({element:u,attribute:"disableAutoCalc",name:ad,value:!0});else if(i){const t=u.winningSide,{winningSide:e,scoreStringSide1:r,scoreStringSide2:i,set:m}=dT({drawDefinition:o,matchUpsMap:s,structure:c,matchUp:u,event:p}),f={scoreStringSide1:r,scoreStringSide2:i,sets:m?[m]:[]};if(l=e!==t,n&&l)return Ci({stack:"winningSideWithDownstreamDependencies",result:{error:Je},context:{winningSide:a,matchUp:u}});sp({element:u,attribute:"disableAutoCalc",name:ad,value:void 0}),Object.assign(d,{winningSide:e,dualWinningSideChange:l,projectedWinningSide:e,score:f})}return lT({tournamentId:t?.tournamentId,inContextDualMatchUp:e,eventId:p?.eventId,dualMatchUp:u,drawDefinition:o}),{dualWinningSideChange:l}}({tournamentRecord:r,inContextMatchUp:I,activeDownstream:b,disableAutoCalc:i,enableAutoCalc:o,drawDefinition:s,winningSide:u,matchUpsMap:y,structure:v,matchUp:g,params:t,event:p});if(e?.error)return e;void 0!==e?.dualWinningSideChange&&(N=e.dualWinningSideChange)}if(U&&c&&[Ip].includes(c))return{info:"Not supported for matchUpType: TEAM",error:sr};if(l&&!U&&!e){const t=g.matchUpFormat??v?.matchUpFormat??s?.matchUpFormat??p?.matchUpFormat,e=Zb({existingMatchUpStatus:g.matchUpStatus,matchUpFormat:t,matchUpStatus:c,winningSide:u,score:l});if(e.error)return e}const M=xd({policyTypes:[Cu,Fu],tournamentRecord:r,drawDefinition:s,event:p})?.appliedPolicies??{};f(t.policyDefinitions)&&Object.assign(M,t.policyDefinitions);const A=function({assignedDrawPositions:t,propagateExitStatus:e,inContextMatchUp:n,appliedPolicies:r,drawDefinition:i,matchUpStatus:o,structure:a,matchUp:s}){if(!1===r?.[Fu]?.requireParticipantsForScoring)return{...Y};const c=n?.sides?.map(t=>t.participantId).filter(Boolean).length,u=s?.sides?[]:cl({structureId:a?.structureId,drawDefinition:i}).positionAssignments,d=c&&2===c||s.collectionId&&Hf({structure:a})&&c&&c>=1||2===t?.length&&u?.filter(e=>t.includes(e.drawPosition)).every(t=>t.participantId);if(o&&[Ep,Pp,wp].includes(o)&&1===c&&e)return{...Y};if(o&&Op.includes(o)&&!d)return Ci({info:"matchUpStatus requires assigned participants",context:{matchUpStatus:o,requiredParticipants:d},result:{error:ce}});return{...Y}}({assignedDrawPositions:P,propagateExitStatus:n,inContextMatchUp:I,appliedPolicies:M,drawDefinition:s,matchUpStatus:c,structure:v,matchUp:g});if(A?.error)return A;const{qualifierAdvancing:E,qualifierChanging:C,removingQualifier:O}=function({inContextMatchUp:t,winningSide:e,matchUp:n,params:r}){const i=t?.stage===ds&&1===t.finishingRound,o=i&&e,a=i&&n.winningSide&&!e&&(!r.matchUpStatus||r.matchUpStatus&&cI({matchUpStatus:r.matchUpStatus}))&&(!r.outcome||!aI({outcome:r.outcome})),s=o&&e!==n.winningSide&&n.winningSide;return{qualifierAdvancing:o,qualifierChanging:s,removingQualifier:a}}({inContextMatchUp:I,winningSide:u,matchUp:g,params:t});if(Object.assign(t,{qualifierAdvancing:E,qualifierChanging:C,removingQualifier:O,appliedPolicies:M}),T){const e=function({drawDefinition:t,matchUpStatus:e,matchUpTieId:n,matchUpsMap:r,winningSide:i,structure:o,matchUp:a,event:s,score:c}){const{matchUp:u}=nT({matchUpId:n,inContext:!0,drawDefinition:t,matchUpsMap:r,event:s});if(!u)return;const d=Rf({matchUp:u,drawDefinition:t,structure:o,event:s})?.tieFormat,{projectedWinningSide:p}=function({drawDefinition:t,matchUpStatus:e,matchUpsMap:n,winningSide:r,dualMatchUp:i,tieFormat:o,structure:a,matchUp:s,event:c,score:u}){const d=ca(i,void 0,!0);for(const t of d?.tieMatchUps??[])t.matchUpId===s.matchUpId&&(t.winningSide=r,t.score=u,aI({score:u})||e?e&&(t.matchUpStatus=e):Object.assign(t,{...oT}));o=o??Rf({matchUp:s,structure:a,drawDefinition:t,event:c})?.tieFormat;const{winningSide:p}=dT({matchUp:d,drawDefinition:t,matchUpsMap:n,structure:a,tieFormat:o,event:c});return{projectedWinningSide:p}}({drawDefinition:t,matchUpStatus:e,dualMatchUp:u,matchUpsMap:r,winningSide:i,tieFormat:d,structure:o,matchUp:a,event:s,score:c}),l=u.winningSide,m=p!==l,f=u._disableAutoCalc;return{isCollectionMatchUp:!0,dualWinningSideChange:m,projectedWinningSide:p,autoCalcDisabled:f,matchUpTieId:n,dualMatchUp:u,tieFormat:d}}({drawDefinition:s,matchUpStatus:c,matchUpTieId:T,matchUpsMap:y,winningSide:u,structure:v,matchUp:g,event:p,score:l});e&&(N=e.dualWinningSideChange,Object.assign(t,e))}const k=function({matchUpTieId:t,activeDownstream:e,matchUpStatus:n,winningSide:r,matchUp:i}){const o=sI({matchUpStatus:n});if(!t){if(e&&!r&&(n&&cI({matchUpStatus:n})||n&&[wp,Tp].includes(n)))return{error:ae,activeDownstream:e,winningSide:r};if(r&&r===i.winningSide&&n&&!o)return{context:"winningSide must include directing matchUpStatus",error:ae,directingMatchUpStatus:o,matchUpStatus:n}}return}({matchUpTieId:T,activeDownstream:b,matchUpStatus:c,winningSide:u,matchUp:g});return k||function({params:t,isTeam:e,dualWinningSideChange:n,activeDownstream:r,stack:i}){const{allowChangePropagation:o,tournamentRecords:a,tournamentRecord:s,drawDefinition:c,winningSide:u,matchUpId:d,matchUpTieId:p,matchUp:l}=t,{schedule:m}=t;if(m){const t=Tk({disableNotice:!0,tournamentRecords:a,tournamentRecord:s,drawDefinition:c,matchUpId:d,schedule:m});if(t.error)return t}const f=!e&&!n&&u&&l.winningSide&&l.winningSide!==u;if(o&&f&&l.roundPosition)return function(t){const{tournamentRecord:e,inContextMatchUp:n,structure:r,drawDefinition:i}=t,o=n.roundNumber,a=n.sides.find(t=>t.sideNumber===n.winningSide),s=n.sides.find(t=>t.sideNumber!==n.winningSide),{drawPosition:c,participantId:u}=a,{drawPosition:d,participantId:p}=s,{matchUps:l}=Fg(t),m=l.filter(({drawPositions:t,roundNumber:e})=>t?.includes(c)&&e>o);$r({changeWinner:!0})&&console.log({existingWinnerSubsequentMatchUps:m}),m.forEach(n=>{n.drawPositions=n.drawPositions?.map(t=>t===c?d:t)??[],Yl({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:S}}=t.targetData,y=[I?.target.structureId,S?.target?.structureId].filter(Boolean);return i.structures.filter(({stage:t,structureId:e})=>t!==f&&y.includes(e)).forEach(({stage:t,stageSequence:e,structureId:n})=>{g.includes(n)||g.push(n),i.structures.filter(({stage:n,stageSequence:r})=>n===t&&r>e).forEach(({structureId:t})=>{g.includes(t)||g.push(t)})}),i.structures.filter(({structureId:t})=>g.includes(t)).forEach(t=>{const{positionAssignments:e}=cl({structure:t}),n=e?.find(({participantId:t})=>t===u),r=e?.find(({participantId:t})=>t===p);n&&(n.participantId=p),r&&(r.participantId=u)}),aT({...t})}(t);const h=u&&!p||t.projectedWinningSide,g=sI({matchUpStatus:t.matchUpStatus});let I;fI({activeDownstream:r,matchUpWinner:h,method:i,winningSide:u}),I=r?h?function(t){const{matchUp:e,winningSide:n,matchUpTieId:r,dualWinningSideChange:i}=t;return n===e.winningSide||r&&!i?Ck(t):Ci({stack:"winningSideWithDownstreamDependencies",result:{error:Je},context:{winningSide:n,matchUp:e}})}(t):g||t.autoCalcDisabled?Ck(t):{error:dr}:uk(t);return Ci({result:I,stack:i})}({params:t,isTeam:U,dualWinningSideChange:N,activeDownstream:b,stack:"setMatchUpStatus"})}function Ck(t){const{tournamentRecord:e,matchUp:n,event:r}=t,i=t.isCollectionMatchUp&&n.winningSide&&!t.winningSide&&!aI({score:t.score}),o=t.isCollectionMatchUp?t.matchUpStatus||i&&Ap||t.winningSide&&vp||Rp:t.matchUpStatus||vp,a=t.removeScore||[yp,Ep].includes(o)&&![Rp,gp].includes(o),s=aT({...t,matchUpStatus:o,removeWinningSide:i,removeScore:a});if(s.error)return s;if(t.isCollectionMatchUp){const{matchUpTieId:n,drawDefinition:i,matchUpsMap:o}=t,a=gT({appliedPolicies:t.appliedPolicies,matchUpId:n,tournamentRecord:e,drawDefinition:i,matchUpsMap:o,event:r});if(a.error)return a;Object.assign(s,{tieMatchUpResult:a})}return s}function Ok({tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r}){if(!e)return{error:st};const{matchUp:i}=nT({drawDefinition:e,matchUpId:n,event:r});return i?.matchUpType!==o?{error:ye}:Ek({enableAutoCalc:!0,tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r})}function kk({drawDefinition:t,event:e,matchUpId:n}){const r=dl({drawDefinition:t,matchUpId:n},[yc,kc]);if(r.error)return r;const{matchUp:i}=nT({drawDefinition:t,event:e,matchUpId:n});return i?sp({element:i,attribute:"delegatedOutcome",name:id,value:void 0}):{error:ge}}function Fk(t){return function({substituteParticipantId:t,existingParticipantId:e,tournamentRecord:n,drawDefinition:r,sideNumber:i,matchUpId:o,event:a}){const s="substituteParticipant";if(!r)return{error:st};if(!o)return{error:fe};if(!e||!t)return Ci({result:{error:sn},stack:s});const{matchUp:c}=nT({drawDefinition:r,matchUpId:o,event:a});if(!c)return{error:ge};if(!c.collectionId)return Ci({result:{error:ye},stack:s});const u=bf({drawDefinition:r}),{matchUps:d}=zg({tournamentParticipants:n?.participants,inContext:!0,drawDefinition:r,matchUpsMap:u}),p=d?.find(t=>t.matchUpId===o),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:Ze};const f=m.participant?.individualParticipants?.map(Xp).filter(t=>t!==e);return f?.includes(t)?xO({newParticipantId:t,tieMatchUpId:o,existingParticipantId:e,substitution:!0,tournamentRecord:n,drawDefinition:r,event:a}):Ci({result:{error:Ze},stack:s})}(t)}function xk({drawDefinition:t,matchUpId:e,event:n}){if(!t)return{error:st};const{matchUp:r}=nT({drawDefinition:t,matchUpId:e,event:n});return sp({element:r,attribute:"disableAutoCalc",name:ad,value:!0})}function _k(t){const e="setMatchUpFormat",n=fu(t,[{tournamentRecord:!0},{[ou]:t=>Io({matchUpFormat:t}),[su]:oe,matchUpFormat:!0}]);if(n.error)return Ci({result:n,stack:e});const{tournamentRecord:r,drawDefinition:i,scheduledDates:o,stageSequences:a,matchUpFormat:s,structureId:c,eventType:u,matchUpId:d,eventId:p,stages:l,drawId:m,event:f,force:h}=t;if(o&&!Array.isArray(o))return Ci({result:{error:sr,scheduledDates:o},stack:e});if(u&&!z([ts,ns],u))return Ci({result:{error:$t},stack:e});let g=0;const I=t.structureIds??(c?[c]:[]),S=t.eventIds??(p?[p]:[]),y=t.drawIds??(m?[m]:[]);if((c||I?.length)&&!i)return Ci({result:{error:st},stack:e});if(m&&d&&i){const t=GN({tournamentRecord:r,drawDefinition:i,matchUpFormat:s,structureIds:I,structureId:c,matchUpId:d});if(t.error)return t;g+=1}return g+=function({tournamentRecord:t,processStructures:e,stageSequences:n,matchUpFormat:r,structureIds:i,eventType:o,eventIds:a,drawIds:s,stages:c}){let u=0;for(const d of t?.events??[])if(!(a?.length&&!a.includes(d.eventId)||o&&o!==d.eventType||o===is))if(Array.isArray(n)||Array.isArray(c)||i?.length||s?.length)for(const t of d.drawDefinitions??[]){if(Array.isArray(s)&&!s.includes(t.drawId))continue;const n=e(t);u+=n.modificationsCount,Ql({structureIds:n.modifiedStructureIds,drawDefinition:t})}else d.matchUpFormat!==r&&(d.matchUpFormat=r,u+=1);return u}({tournamentRecord:r,processStructures:t=>{const n=function({drawDefinition:t,tournamentRecord:e,stageSequences:n,scheduledDates:r,matchUpFormat:i,structureIds:o,stack:a,force:s,event:c,stages:u}){const d=[];let p=0;for(const l of t.structures??[]){if(Array.isArray(u)&&!u.includes(l.stage)||Array.isArray(n)&&!n.includes(l.stageSequence)||o?.length&&!o.includes(l.structureId))continue;o?.length&&l.matchUpFormat!==i&&(l.matchUpFormat=i,d.push(l.structureId),p+=1);const m=((s||r)&&Fg({matchUpFilters:{matchUpStatuses:[Ap]},structure:l}).matchUps)??[],f=(r&&Fg({matchUpFilters:{matchUpStatuses:[Ap]},contextFilters:{scheduledDates:r},afterRecoveryTimes:!1,inContext:!0,structure:l}).matchUps)??[];if(m?.length){const n=f?f.map(tl):m.map(tl);for(const o of m)n.includes(o.matchUpId)&&(o.matchUpFormat=r?.length?i:void 0,Yl({tournamentId:e?.tournamentId,eventId:c?.eventId,context:a,drawDefinition:t,matchUp:o}))}}d.length||t.matchUpFormat===i||(t.matchUpFormat=i,p+=1);return{modifiedStructureIds:d,modificationsCount:p}}({drawDefinition:t,tournamentRecord:r,stageSequences:a,scheduledDates:o,matchUpFormat:s,structureIds:I,stack:e,force:h,event:f,stages:l});return n},stageSequences:a,matchUpFormat:s,structureIds:I,eventType:u,eventIds:S,drawIds:y,stages:l}),g?{...Y,modificationsCount:g}:{...Y,info:Zn}}function Lk({inheritance:t=!0,tournamentRecord:e,drawDefinition:n,matchUpId:r,event:i}){if(!n)return{error:st};const o=nT({drawDefinition:n,matchUpId:r})?.matchUp;if(!o?.tieMatchUps)return{error:ye};const a=nT({inContext:!0,drawDefinition:n,matchUpId:r,event:i})?.matchUp;let s=0;return(o?.sides??[]).forEach(t=>{t.lineUp&&delete t.lineUp}),(a?.sides??[]).forEach(r=>{if(s+=1,!1===t){const t=a?.tieFormat,e=r.participantId;t&&e&&iv({drawDefinition:n,participantId:e,lineUp:[],tieFormat:t})}Yl({tournamentId:e?.tournamentId,context:"resetMatchUpLineUps",eventId:i?.eventId,drawDefinition:n,matchUp:o})}),{...Y,modificationsCount:s}}function Bk(t){const{matchUpFormat:e,matchUpStatus:n,winningSide:r,score:i,setTBlast:o}=t;if(!i)return{sets:[]};const a=i.sets??[];let s=aR({winnerFirst:!1,matchUpFormat:e,matchUpStatus:n,setTBlast:o,sets:a}),c=aR({winnerFirst:!1,reversed:!0,matchUpFormat:e,matchUpStatus:n,setTBlast:o,sets:a});const u=aR({matchUpFormat:e,matchUpStatus:n,winningSide:r,setTBlast:o,sets:a}),d=s===u?c:s;return r&&(s=1===r?u:d,c=2===r?u:d),{score:{sets:a,scoreStringSide1:s,scoreStringSide2:c}}}function Vk({sourceMatchUpStatusCodes:t,propagateExitStatus:e,sourceMatchUpStatus:n,loserParticipantId:r,tournamentRecord:i,drawDefinition:o,loserMatchUp:a,matchUpsMap:s,event:c}){const u="progressExitStatus";fI({method:u,newline:!0,color:"magenta",keyColors:{loserMatchUpId:"brightcyan",sourceMatchUpStatus:"brightyellow"},loserMatchUpId:a?.matchUpId,loserMatchUpStatus:a?.matchUpStatus,sourceMatchUpStatus:n,sourceMatchUpStatusCodes:JSON.stringify(t),loserParticipantId:r?.slice(0,8),propagateExitStatus:e});const d=II(n)&&n!==Np&&n||Ep,p=zg({inContext:!0,drawDefinition:o,matchUpsMap:s})?.matchUps;let l=d;const m=p?.find(t=>t.matchUpId===a?.matchUpId);if(fI({method:u,color:"magenta",carryOverMatchUpStatus:d,updatedLoserMatchUpId:m?.matchUpId,updatedLoserStatus:m?.matchUpStatus,updatedLoserSides:JSON.stringify(m?.sides?.map(t=>({sn:t.sideNumber,pid:t.participantId?.slice(0,8),bye:t.bye}))),updatedLoserDP:JSON.stringify(m?.drawPositions),existingStatusCodes:JSON.stringify(m?.matchUpStatusCodes)}),m?.matchUpId&&l){let n;const s=m.matchUpStatusCodes?.map(t=>"string"==typeof t?t:ob)??[],d=m.sides?.find(t=>t.participantId===r);if(d?.sideNumber){const e=m?.sides?.reduce((t,e)=>e?.participantId?t+1:t,0);if(fI({method:u,color:"brightyellow",keyColors:{decision:"brightgreen"},loserSideNumber:d.sideNumber,participantsCount:e,statusCodesLength:s.length,existingStatusCodes:JSON.stringify(s),loserMatchUpIsExit:II(a.matchUpStatus),loserMatchUpOriginalStatus:a.matchUpStatus}),1===e&&0===s.length)n=1===d.sideNumber?2:1,s[0]=t[0],fI({method:u,color:"brightgreen",decision:"SINGLE_PARTICIPANT_no_existing_codes",winningSide:n,statusCodes:JSON.stringify(s)});else if(II(a.matchUpStatus)){const e=s[0];s[d.sideNumber-1]=t[0];s[(1===d.sideNumber?2:1)-1]=e,l=wp,n=void 0,fI({method:u,color:"brightred",decision:"BOTH_EXITS_converting_to_DOUBLE_WALKOVER",loserMatchUpStatus:l,winningSide:n,statusCodes:JSON.stringify(s)})}else n=1===d.sideNumber?2:1,s[0]=t[0],fI({method:u,color:"brightgreen",decision:"TWO_PARTICIPANTS_not_exit",winningSide:n,statusCodes:JSON.stringify(s)})}else fI({method:u,color:"brightyellow",decision:"NO_LOSER_PARTICIPANT_SIDE_FOUND",loserParticipantId:r?.slice(0,8),availableSides:JSON.stringify(m.sides?.map(t=>({sn:t.sideNumber,pid:t.participantId?.slice(0,8)})))});fI({method:u,color:"brightmagenta",keyColors:{finalStatus:"brightgreen",finalWinningSide:"brightyellow"},action:"calling_setMatchUpState",loserMatchUpId:a.matchUpId,finalStatus:l,finalWinningSide:n,finalStatusCodes:JSON.stringify(s)});return Ci({result:Ek({matchUpStatus:l,matchUpId:a.matchUpId,matchUpStatusCodes:s,allowChangePropagation:!0,propagateExitStatus:e,tournamentRecord:i,drawDefinition:o,winningSide:n,event:c}),stack:u,context:{progressExitStatus:!0}})}return Ci({result:{error:Se},stack:u})}function Gk(t){const e=fu(t,[{[kc]:!0,[yc]:!0}]);if(e.error)return e;const n=im(t);if(!t.drawDefinition){const e=t.tournamentRecord??(t.tournamentId&&n[t.tournamentId]);t.tournamentRecord??=e;const r=wg({eventId:t.eventId,drawId:t.drawId,tournamentRecord:e});if(r.error)return r;r.drawDefinition&&(t.drawDefinition=r.drawDefinition),t.event=r.event}const{disableScoreValidation:r,propagateExitStatus:i,policyDefinitions:o,tournamentRecord:a,disableAutoCalc:s,enableAutoCalc:c,drawDefinition:u,matchUpId:d,schedule:p,event:l,notes:m}=t,f=t.matchUpFormat||t.outcome?.matchUpFormat,{policy:h}=Qm({policyType:Fu,tournamentRecord:a,event:l}),g=void 0!==t.allowChangePropagation&&t.allowChangePropagation||void 0!==h?.allowChangePropagation&&h.allowChangePropagation||void 0,{outcome:I,setTBlast:S}=t;if(I?.winningSide&&![1,2].includes(I.winningSide))return{error:$e};if(f){const t=GN({tournamentRecord:a,drawDefinition:u,matchUpFormat:f,matchUpId:d,event:l});if(t.error)return t}if(I?.score?.sets&&!I.score.scoreStringSide1){const{score:t}=Bk({...I,setTBlast:S});I.score=t,I.score.sets=I.score.sets.filter(t=>t.side1Score||t.side2Score||t.side1TiebreakScore||t.side2TiebreakScore||t.side1PointScore||t.side2PointScore)}const y=Ek({matchUpStatusCodes:I?.matchUpStatusCodes,matchUpStatus:I?.matchUpStatus,winningSide:I?.winningSide,allowChangePropagation:g,disableScoreValidation:r,score:I?.score,propagateExitStatus:i,tournamentRecords:n,policyDefinitions:o,tournamentRecord:a,disableAutoCalc:s,enableAutoCalc:c,drawDefinition:u,matchUpFormat:f,matchUpId:d,schedule:p,event:l,notes:m});if(y.context?.progressExitStatus){let e=!0,n=0;for(;e&&n<10;){e=!1,n+=1;const r=Vk({sourceMatchUpStatusCodes:y.context.sourceMatchUpStatusCodes,sourceMatchUpStatus:y.context.sourceMatchUpStatus,loserParticipantId:y.context.loserParticipantId,propagateExitStatus:t.propagateExitStatus,tournamentRecord:t.tournamentRecord,loserMatchUp:y.context.loserMatchUp,matchUpsMap:y.context.matchUpsMap,drawDefinition:t.drawDefinition,event:t.event});r.context?.loserMatchUp&&(Object.assign(y.context,r.context),e=!0)}}return Ci({result:y,stack:"setMatchUpStatus"})}function jk(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:rt};const i=n.filter(e=>e.tournamentId===t);if(i.length){const t=qk({outcomes:i,tournamentRecord:r});if(t.error)return t}}return{...Y}}function qk(t){const{tournamentRecords:e,tournamentRecord:n,outcomes:r,policyDefinitions:i}=t,o={};r.forEach(t=>{const{eventId:e}=t;o[e]||(o[e]=[]),o[e].push(t)});for(const t of Object.keys(o)){const{event:r}=wg({tournamentRecord:n,eventId:t});for(const a of o[t]){const{drawId:t}=a,o=r?.drawDefinitions?.find(e=>e.drawId===t);if(o&&t){const{matchUpFormat:s,matchUpId:c}=a,u=Gk({schedule:a?.schedule,tournamentRecords:e,policyDefinitions:i,tournamentRecord:n,drawDefinition:o,matchUpFormat:s,matchUpId:c,outcome:a,drawId:t,event:r});if(u.error)return u}}}return{...Y}}function Wk(t){return function({drawDefinition:t,matchUpId:e,outcome:n,matchUp:r}){if(!r&&!t)return{error:st};if(!n)return{error:Ae,info:"missing outcome"};if(!r&&!e)return{error:Se};if(!r){const n=nT({drawDefinition:t,matchUpId:e});if(n.error)return n;r=n.matchUp}return"object"==typeof n&&n.score?.scoreStringSide1&&n.score?.scoreStringSide2?sp({element:r,attribute:"delegatedOutcome",name:id,value:n}):{error:sr}}(t)}function $k({target:t,tieFormat:e,event:n}){if(t){if(t.tieFormatId&&n?.tieFormats?.length){const r=t.tieFormatId,i=function({event:t,tieFormatId:e}){let n=0;t.tieFormatId===e&&n++;for(const r of t.drawDefinitions??[]){r.tieFormatId===e&&n++;for(const t of r.structures??[])t.tieFormatId===e&&n++}const r=Kg({matchUpFilters:{matchUpTypes:[o]},event:t});for(const t of r.matchUps??[])t.tieFormatId===e&&n++;return n}({event:n,tieFormatId:r});if(i<=1){const t=n.tieFormats.findIndex(t=>t.tieFormatId===r);if(t>=0){const i=ca(e,void 0,!0);return i.tieFormatId=r,void(n.tieFormats[t]=i)}}const a=ca(e,void 0,!0);return a.tieFormatId=pa(),n.tieFormats.push(a),t.tieFormatId=a.tieFormatId,void delete t.tieFormat}t.tieFormat=e}}function Hk({event:t}){if(!t?.tieFormats?.length)return;const e=new Set;t.tieFormatId&&e.add(t.tieFormatId);for(const n of t.drawDefinitions??[]){n.tieFormatId&&e.add(n.tieFormatId);for(const t of n.structures??[])t.tieFormatId&&e.add(t.tieFormatId)}const n=Kg({matchUpFilters:{matchUpTypes:[o]},event:t});for(const t of n.matchUps??[])t.tieFormatId&&e.add(t.tieFormatId);t.tieFormats=t.tieFormats.filter(t=>t.tieFormatId&&e.has(t.tieFormatId)),t.tieFormats.length||delete t.tieFormats}function zk(t){const e="resetTieFormat",{drawDefinition:n,event:r,uuids:i}=t,o=fu(t,[{[Ic]:!0,[kc]:!0}],e);if(o.error)return o;const a=UE(t,[{[Yc]:Wc}]);if(a[Hc])return a;const s=t.tournamentRecord?.tournamentId,{matchUp:c,structure:u}=a?.matchUp??{};if(!c?.tieMatchUps)return Ci({result:{error:ye},info:"Must be a TEAM matchUp",stack:e});if(!c.tieFormat&&!c.tieFormatId)return{...Y};const d=Rf({structure:u,drawDefinition:n,event:r})?.tieFormat;if(!d)return Ci({result:{error:mr},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===Ap?1:0)-(e.matchUpStatus===Ap?1:0)),m.push(...r.slice(0,e)),p.push(...r.slice(3).map(tl));else if(m.push(...r),r.length<e){const n=VP({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),Hl({eventId:r?.eventId,matchUps:f,drawDefinition:n,tournamentId:s})),p.length&&zl({matchUpIds:p,eventId:r?.eventId,drawDefinition:n,tournamentId:s}),c&&(c.tieMatchUps=m,c.tieFormatId=void 0,c.tieFormat=void 0,r&&Hk({event:r}),Yl({structureId:u?.structureId,eventId:r?.eventId,context:e,drawDefinition:n,tournamentId:s,matchUp:c})),{...Y,newMatchUps:f,deletedMatchUpIds:p}}function Yk(t){const{tournamentRecord:e,drawDefinition:n,matchUpId:r,event:i}=t,o="resetScorecard";if(!n)return Ci({result:{error:st},stack:o});if(!r)return Ci({result:{error:fe},stack:o});if(!m(r))return Ci({result:{error:sr,matchUpId:r},stack:o});const a=bf({drawDefinition:n}),{matchUps:s}=zg({nextMatchUps:!0,inContext:!0,drawDefinition:n,matchUpsMap:a}),c=a.drawMatchUps.find(t=>t.matchUpId===r),u=s?.find(t=>t.matchUpId===r);if(!c||!s)return{error:ge};if(c.matchUpType!==os)return{error:ye};const d=jg({inContextDrawMatchUps:s,drawDefinition:n,matchUpId:r}),p=u?.structureId,{structure:l}=ol({drawDefinition:n,structureId:p});Object.assign(t,{inContextDrawMatchUps:s,inContextMatchUp:u,matchUpsMap:a,targetData:d,structure:l,matchUp:c});if(Cw(t))return{error:Je};if(c.tieMatchUps?.length)for(const t of c.tieMatchUps){const a=Ek({matchUpId:t.matchUpId,matchUpTieId:r,winningSide:void 0,removeScore:!0,tournamentRecord:e,drawDefinition:n,event:i});if(a.error)return Ci({result:a,stack:o})}const f=xd({tournamentRecord:e,drawDefinition:n,event:i})?.appliedPolicies,h=gT({event:t.event,removeScore:!0,tournamentRecord:e,appliedPolicies:f,drawDefinition:n,matchUpsMap:a,matchUpId:r});if(h.error)return Ci({result:h,stack:o});if(t.tiebreakReset&&!h.tieFormatRemoved){const t=Rf({drawDefinition:n,structure:l,event:i})?.tieFormat;if(c.tieFormat&&t){const{matchUpCountDifference:o,descendantDifferences:a,ancestorDifferences:s,valueDifference:u}=AA({descendant:c.tieFormat,ancestor:t});if(1===a.collectionIds.length&&!s.collectionIds.length&&!s.groupsCount&&1===o&&1===u){const t=zk({tournamentRecord:e,drawDefinition:n,matchUpId:r,event:i});if(t.error)return t}}}return{...Y}}function Kk(t){const e=fu(t,[{[yc]:!0,[zc]:!0},{[du]:{[Mc]:!1,roundNumbers:!1},[au]:"At least one must be provided",[cu]:iu}]);if(e.error)return e;const n=jT(t);if(n.error)return n;const{matchUpIds:r}=n,i=bh(os)(t.event.eventType),{tournamentRecord:o,drawDefinition:a,event:s}=t;for(const e of r){if(i){const n=Yk({tiebreakReset:!0,tournamentRecord:o,drawDefinition:a,matchUpId:e,event:s});if(n.error)return n;if(t.removeAssignments){const t=Lk({inheritance:!1,drawDefinition:a,matchUpId:e});if(t.error)return t}}const n=Ek({winningSide:void 0,removeScore:!0,tournamentRecord:o,drawDefinition:a,matchUpId:e,event:s});if(n.error)return n;if(t.removeAssignments){const n=WO({...t,matchUpId:e});if(n.error)return n}}return{...Y}}function Qk(t){return function({tournamentRecord:t,drawDefinition:e,finishingOrder:n}){if(!e)return{error:st};const r="setOrderOfFinish";if(!Array.isArray(n))return Ci({info:nv("finishingOrder"),result:{error:sr},stack:r});const{completedMatchUps:i,matchUpsMap:o}=Yg({inContext:!0,drawDefinition:e}),a=i?.map(tl)??[],s=n.map(tl),{matchUpTypes:c,roundNumbers:u,structureIds:d,matchUpTieIds:p}=(i??[]).filter(({matchUpId:t})=>s.includes(t)).reduce((t,e)=>{const{matchUpTieId:n,matchUpType:r,roundNumber:i,structureId:o}=e;return t.matchUpTypes.includes(r)||t.matchUpTypes.push(r),t.roundNumbers.includes(i)||t.roundNumbers.push(i),t.structureIds.includes(o)||t.structureIds.push(o),t.matchUpTieIds.includes(n)||t.matchUpTieIds.push(n),t},{matchUpTypes:[],roundNumbers:[],structureIds:[],matchUpTieIds:[]});if(c.length>1||p.length>1||u.length>1||d.length>1)return Ci({info:"matchUpType, structureId and roundNumber must be equivalent",result:{error:sr},stack:r});let l,m;const f={},h=[],g=[],I=n.every(({orderOfFinish:t,matchUpId:e})=>(h.push(e),t&&g.push(t),f[e]=t,l=a.includes(e),m=void 0===t||R(t)&&Math.floor(t)>0,l&&m));if(!I)return Ci({result:{error:l?sr:ce},info:(l?!m&&"orderOfFinish must be integer > 0 or undefined":"matchUps must be completed")||void 0,stack:r});const S=i?.filter(t=>t.structureId===d[0]&&t.roundNumber===u[0]&&t.matchUpType===c[0]&&t.matchUpTieId===p[0]&&!h.includes(t.matchUpId));for(const t of S??[]){const{orderOfFinish:e}=t??{};if(e){if(!R(e))return Ci({context:{orderOfFinish:e,matchUp:t},result:{error:sr},stack:r});g.push(e)}}if(F(g).length!==g.length||Math.max(...g)>g.length)return Ci({info:"Values not unique or greater than expected number of values",result:{error:sr},stack:r});if(d.length){const n=Lg({matchUpFilters:{matchUpIds:s},structureId:d[0],drawDefinition:e,matchUpsMap:o});if(n.error)return Ci({result:n,stack:r});n.completedMatchUps?.forEach(n=>{n.orderOfFinish=f[n.matchUpId],Yl({tournamentId:t.tournamentId,context:"setOrderOfFinish",drawDefinition:e,matchUp:n})})}return{...Y}}(t)}function Jk(t){const{tournamentRecord:e,drawDefinition:n,matchUpId:r,lineUps:i,event:o}=t,s="applyLineUps",c=fu(t,[{[Ic]:!0,[yc]:!0,[kc]:!0},{lineUps:!0,[cu]:iu}],s);if(c.error)return c;const u=e.participants??[];let d=nT({tournamentParticipants:u,inContext:!0,drawDefinition:n,matchUpId:r});if(d.error)return d;if(!d.matchUp)return{error:ge};const{matchUp:p,structure:l}=d,{drawPositions:m,matchUpType:f}=p;if(f!==a)return{error:ye};if(!m?.length)return{error:yt};const h=Rf({matchUp:p,drawDefinition:n,structure:l,event:o})?.tieFormat,g={};for(const t of i){if(!Array.isArray(t))return{error:sr,lineUp:t};const n=Xk({tournamentParticipants:u,inContextMatchUp:p,tieFormat:h,lineUp:t});if(n.error)return n;const{collectionParticipantIds:r,sideNumbers:i}=n,o=Zk({collectionParticipantIds:r,tournamentParticipants:u,tournamentRecord:e});if(o?.error)return o;const a=tF(i),s=Object.keys(g).map(t=>Number.parseInt(t));a&&!s.includes(a)&&(g[a]=t)}if(!Object.keys(g).length)return{error:lr};if(d=nT({drawDefinition:n,matchUpId:r}),d.error)return d;if(!d.matchUp)return{error:ge};const{matchUp:I}=d;I.sides??=[];for(const t of[1,2]){const e=I.sides.find(e=>e.sideNumber===t),n=g[t];n&&(e?e.lineUp=n:I.sides.push({lineUp:n,sideNumber:t}))}return Yl({tournamentId:e?.tournamentId,context:s,drawDefinition:n,matchUp:I}),{...Y}}function Xk({tournamentParticipants:t,inContextMatchUp:e,tieFormat:r,lineUp:o}){const a={},s=[];for(const c of o){if("object"!=typeof c)return{error:sr,lineUpAssignment:c};const{participantId:o,collectionAssignments:u=[]}=c;if(!Array.isArray(u))return{error:sr,collectionAssignments:u};const d=t.find(t=>t.participantId===o);if(!d)return{error:un};if(d.participantType!==gm)return{error:nn};const p=e.sides?.find(t=>t.participant?.individualParticipantIds?.includes(o))?.sideNumber;p&&s.push(p);for(const t of u){if("object"!=typeof t)return{error:sr,collectionAssignment:t};const{collectionId:e,collectionPosition:s}=t,c=r?.collectionDefinitions?.find(t=>t.collectionId===e);if(!c)return{error:sr,collectionId:e};const u=`${e}-${s}`;a[u]||(a[u]=[]);const d=a[u].length;if(bh(n)(c.matchUpType)&&d||c.matchUpType===i&&d>1)return{info:"Excessive collectionPosition assignments",error:sr};a[u].push(o)}}return{collectionParticipantIds:a,sideNumbers:s}}function Zk({collectionParticipantIds:t,tournamentParticipants:e,tournamentRecord:n}){const r=Object.values(t);for(const t of r)if(2===t.length){const{participant:r}=bg({tournamentParticipants:e,participantIds:t});if(!r){const e=mC({participant:{participantType:Sm,participantRole:sy,individualParticipantIds:t},pairOverride:!0,tournamentRecord:n});if(e.error)return e}}}function tF(t){const e=C(t);return((e[1]||0)>(e[2]||0)?1:(e[2]||0)>(e[1]||0)&&2)||void 0}var eF={__proto__:null,allCompetitionMatchUps:Jg,allDrawMatchUps:Zg,allEventMatchUps:Kg,allTournamentMatchUps:Qg,analyzeMatchUp:LE,applyLineUps:Jk,assignMatchUpSideParticipant:AO,assignTieMatchUpParticipantId:VO,bulkMatchUpStatusUpdate:jk,calculateMatchUpMargin:HP,calculateWinCriteria:EE,checkInParticipant:OO,checkMatchUpIsComplete:_g,checkOutParticipant:CO,competitionScheduleMatchUps:vE,disableTieAutoCalc:xk,drawMatchUps:_E,enableTieAutoCalc:Ok,eventMatchUps:IE,filterMatchUps:kg,findMatchUp:CA,getAllDrawMatchUps:zg,getAllStructureMatchUps:Fg,getCheckedInParticipantIds:Rh,getCompetitionFormat:TE,getCompetitionMatchUps:yE,getEventMatchUpFormatTiming:uE,getHomeParticipantId:AE,getMatchUpCompetitiveProfile:Ff,getMatchUpContextIds:ME,getMatchUpDailyLimits:wE,getMatchUpDailyLimitsUpdate:hE,getMatchUpDependencies:iI,getMatchUpFormat:CE,getMatchUpFormatTiming:Jh,getMatchUpFormatTimingUpdate:cE,getMatchUpScheduleDetails:Dg,getMatchUpType:Mg,getMatchUpsStats:OE,getModifiedMatchUpFormatTiming:dE,getParticipantResults:BI,getPredictiveAccuracy:DE,getRoundMatchUps:Bf,getRounds:xE,isValidMatchUpFormat:Io,matchUpActions:aD,mutate:{__proto__:null,applyLineUps:Jk,assignMatchUpSideParticipant:AO,assignTieMatchUpParticipantId:VO,bulkMatchUpStatusUpdate:jk,checkInParticipant:OO,checkOutParticipant:CO,disableTieAutoCalc:xk,enableTieAutoCalc:Ok,findMatchUp:CA,removeDelegatedOutcome:kk,removeMatchUpSideParticipant:WO,removeTieMatchUpParticipantId:qO,replaceTieMatchUpParticipantId:xO,resetAdHocMatchUps:Kk,resetMatchUpLineUps:Lk,resetScorecard:Yk,resetTieFormat:zk,setDelegatedOutcome:Wk,setMatchUpFormat:_k,setMatchUpState:Ek,setMatchUpStatus:Gk,setOrderOfFinish:Qk,substituteParticipant:Fk,toggleParticipantCheckInState:kO,updateTieMatchUpScore:gT},participantScheduledMatchUps:fE,predictMatchUpCompetitiveBands:lE,query:{__proto__:null,allCompetitionMatchUps:Jg,allDrawMatchUps:Zg,allEventMatchUps:Kg,allTournamentMatchUps:Qg,analyzeMatchUp:LE,calculateMatchUpMargin:HP,calculateWinCriteria:EE,checkMatchUpIsComplete:_g,competitionScheduleMatchUps:vE,drawMatchUps:_E,eventMatchUps:IE,filterMatchUps:kg,getAllDrawMatchUps:zg,getAllStructureMatchUps:Fg,getCheckedInParticipantIds:Rh,getCompetitionFormat:TE,getCompetitionMatchUps:yE,getEventMatchUpFormatTiming:uE,getHomeParticipantId:AE,getMatchUpCompetitiveProfile:Ff,getMatchUpContextIds:ME,getMatchUpDailyLimits:wE,getMatchUpDailyLimitsUpdate:hE,getMatchUpDependencies:iI,getMatchUpFormat:CE,getMatchUpFormatTiming:Jh,getMatchUpFormatTimingUpdate:cE,getMatchUpScheduleDetails:Dg,getMatchUpType:Mg,getMatchUpsStats:OE,getModifiedMatchUpFormatTiming:dE,getParticipantResults:BI,getPredictiveAccuracy:DE,getRoundMatchUps:Bf,getRounds:xE,isValidMatchUpFormat:Io,matchUpActions:aD,participantScheduledMatchUps:fE,predictMatchUpCompetitiveBands:lE,tallyParticipantResults:aS,tournamentMatchUps:SE,validMatchUp:_f,validMatchUps:Lf},removeDelegatedOutcome:kk,removeMatchUpSideParticipant:WO,removeTieMatchUpParticipantId:qO,replaceTieMatchUpParticipantId:xO,resetAdHocMatchUps:Kk,resetMatchUpLineUps:Lk,resetScorecard:Yk,resetTieFormat:zk,setDelegatedOutcome:Wk,setMatchUpFormat:_k,setMatchUpState:Ek,setMatchUpStatus:Gk,setOrderOfFinish:Qk,substituteParticipant:Fk,tallyParticipantResults:aS,toggleParticipantCheckInState:kO,tournamentMatchUps:SE,updateTieMatchUpScore:gT,validMatchUp:_f,validMatchUps:Lf};function nF(t){const{matchUpFormat:e,matchUpStatus:n,winningSide:r,scoreString:i,setTBlast:o,preserveSideOrder:a=!1}=t;if(!i)return{outcome:{...oT,winningSide:r,matchUpStatus:n}};if(r&&![1,2,void 0].includes(r))return{error:sr,winningSide:r};const s=i&&rN({scoreString:i,matchUpFormat:e}),c=i?.trim().startsWith("["),u=function(t,e,n){return!t&&e&&n?Qb(co(e))?function(t){const e=t.reduce((t,e)=>(void 0===e.side1Score&&void 0===e.side2Score||(t.side1+=e.side1Score??0,t.side2+=e.side2Score??0),t),{side1:0,side2:0});if(e.side1>e.side2)return 1;if(e.side2>e.side1)return 2;const n=t.find(t=>void 0!==t.side1TiebreakScore||void 0!==t.side2TiebreakScore);return n?.winningSide}(n):function(t){const e={side1:0,side2:0};return t.forEach(t=>{1===t.winningSide?e.side1++:2===t.winningSide&&e.side2++}),e.side1>e.side2?1:e.side2>e.side1?2:void 0}(n):t}(r,e,s),d=co(e),p=a||c||Qb(d)?function(t,e,n){const r=rN({scoreString:t,matchUpFormat:e});return{sets:r,scoreStringSide1:aR({sets:r,matchUpFormat:e,setTBlast:n}),scoreStringSide2:aR({sets:r,reversed:!0,matchUpFormat:e,setTBlast:n})}}(i,e,o):function(t,e,n,r){const i=aR({sets:t,matchUpFormat:n,setTBlast:r}),o=aR({sets:t,reversed:!0,matchUpFormat:n,setTBlast:r});if("string"!=typeof i)return i;if("string"!=typeof o)return o;const a=2===e?o:i,s=2===e?i:o;return{sets:rN({scoreString:a,matchUpFormat:n}),scoreStringSide1:a,scoreStringSide2:s}}(s,u,e,o);return Ei({outcome:{matchUpStatus:n,winningSide:u,score:p}})}function rF({matchUpScheduleTimes:t,matchUpDependencies:e,allDateMatchUpIds:n,matchUp:r}){const i=(e?.[r.matchUpId]?.matchUpIds??[]).filter(t=>n.includes(t)),o=i.filter(e=>!t[e]);return{dependenciesScheduled:!o?.length,remainingDependencies:o}}function iF({individualParticipantProfiles:t,participantId:e}){t[e]||(t[e]={typeChangeTimeAfterRecovery:void 0,timeAfterRecovery:void 0,priorMatchUpType:void 0,potentialRecovery:{},potentialCounted:{},potentialBookings:{},bookings:[],counters:{}})}function oF({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,typeChangeRecoveryMinutes:n,averageMatchUpMinutes:r=0,matchUpNotBeforeTimes:i,matchUpDependencies:o,recoveryMinutes:a=0,scheduleTime:s,matchUp:c}){const u=_o(c?.schedule?.endTime),d=u?Ho(u,p(a)):Ho(s,p(r)+p(a)),l=n&&(u?Ho(_o(u),n):Ho(s,p(r)+p(n))),m=o?.[c.matchUpId]?.participantIds??[],f=(c.roundPosition&&t[c.matchUpId]||[]).flat();m.forEach(t=>{iF({individualParticipantProfiles:e,participantId:t});const n=e[t].priorMatchUpType!==c.matchUpType&&l||d;f.includes(t)?function({individualParticipantProfiles:t,recoveryValue:e,participantId:n,scheduleTime:r,drawId:i}){t[n].potentialRecovery[i]||(t[n].potentialRecovery[i]=[]),t[n].potentialRecovery[i].push(e),t[n].potentialBookings[i]||(t[n].potentialBookings[i]=[]),t[n].potentialBookings[i].push({timeAfterRecovery:e,scheduleTime:r})}({individualParticipantProfiles:e,drawId:c.drawId,recoveryValue:n,participantId:t,scheduleTime:s}):(e[t].timeAfterRecovery=n,e[t].bookings.push({scheduleTime:s,timeAfterRecovery:n}))}),VA({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:i,timeAfterRecovery:d,matchUp:c})}function aF({matchUpScheduleTimes:t,matchUpDependencies:e,scheduleTime:n,matchUpId:r,details:i}){let o;const a=i.minutesMap?.[r]?.recoveryMinutes,s=i.minutesMap?.[r]?.averageMinutes,c=Ho(n,(s||0)+(a||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||Fo(r)<Fo(e.scheduleTime)?i:e},{});e.scheduleTime&&Fo(c)>Fo(e.scheduleTime)&&(o=e)}return{scheduledDependent:o}}const sF="DO_NOT_SCHEDULE",cF={DO_NOT_SCHEDULE:sF};function uF({averageMatchUpMinutes:t=90,requestConflicts:e={},potentials:n=!0,personRequests:r,scheduleTime:o,scheduleDate:a,matchUp:s}){const c=function(t){const{sides:e,matchUpType:n}=t??{};return(e??[]).map(t=>n===i&&(t?.participant?.individualParticipants??[])||t?.participant&&[t.participant]||[]).flat()}(s).map(({person:t})=>t?.personId);if(n){const t=(s?.potentialParticipants??[]).flat().map(({person:t})=>t?.personId);c.push(...t)}const u=c.map(t=>r[t]?.map(e=>({...e,personId:t}))).filter(Boolean).flat().filter(t=>t.requestType===sF&&Ko(a,t.date)),d=[],p=s?.matchUpId,l=Wo(_o(o),Lo(a)),m=_o(zo(l,t).toISOString());for(const t of u){const{requestId:n,startTime:r,endTime:i}=t;(o>r&&o<i||m&&m>r&&m<i)&&(d.push({matchUpId:p,request:t,scheduleTime:o}),e[n]?(e[n].scheduleTimes.includes(o)||e[n].scheduleTimes.push(o),e[n].matchUpIds.includes(p)||e[n].matchUpIds.push(p)):e[n]={request:t,scheduleTimes:[o],matchUpIds:[p]})}return{conflicts:d}}function dF({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUp:n,value:r}){const{matchUpType:i}=n,{individualParticipantIds:o}=rm(n),a=(t[n.matchUpId]??[]).filter(t=>!j(t,o)).flat();[...o,...a].forEach(t=>{if(iF({individualParticipantProfiles:e,participantId:t}),!e[t].potentialCounted[n.drawId]){const o=e[t].counters;o[i]?o[i]+=r:r>0&&(o[i]=r),o[_h]?o[_h]+=r:r>0&&(o[_h]=r),a.includes(t)&&(e[t].potentialCounted[n.drawId]=!0)}})}function pF({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,excludeNoDateCompleted:n=!0,dateScheduledMatchUpIds:r,greatestAverageMinutes:i,dateScheduledMatchUps:o,matchUpNotBeforeTimes:a,matchUpScheduleTimes:s,excludePriorDates:c=!0,matchUpDependencies:u,clearScheduleDates:d,scheduleDate:p,minutesMap:l,matchUps:m}){const f=[];r||(o=m?.filter(t=>{const e=t.schedule??{},n=t.matchUpStatus===Sp;return n&&f.push({tournamentId:t.tournamentId,matchUpId:t.matchUpId}),!n&&mE({schedule:e})&&(!p||t.schedule?.scheduledDate===p)}),r=o.map(tl));const h=Array.isArray(d)?d.includes(p):d,g=h?[]:m.filter(({matchUpId:t})=>r.includes(t)),I=c&&p?Lo(p):void 0,S=t=>{const e=t.schedule??{},r=t.matchUpStatus;if(n&&(r===vp||r===Sp)&&!e.scheduledDate)return!0;if(I&&e.scheduledDate){const t=Lo(e.scheduledDate);if(t&&t<I)return!0}return!1};for(const n of g){if(S(n))continue;dF({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,value:1,matchUp:n});const r=n.schedule?.scheduledTime;if(r){s[n.matchUpId]=r;const o=l?.[n.matchUpId]?.recoveryMinutes;oF({individualParticipantProfiles:e,matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:a,matchUpDependencies:u,averageMatchUpMinutes:i,recoveryMinutes:o,scheduleTime:r,matchUp:n})}}return{dateScheduledMatchUpIds:r,byeScheduledMatchUpDetails:f,dateScheduledMatchUps:o,clearDate:h}}function lF({defaultRecoveryMinutes:t=0,averageMatchUpMinutes:e=90,dateScheduledMatchUps:n,tournamentRecords:r,venueIds:i=[],periodLength:o,scheduleDate:a,matchUps:s}){if("object"!=typeof r)return{error:nt};if(!Lf(s)&&!Array.isArray(n))return{error:Ie};o=o??TO({recoveryMinutes:t,averageMatchUpMinutes:e});const c=Object.assign({},...Object.values(r).flatMap(t=>(t.events??[]).map(e=>{const{scheduleTiming:n}=Jm({tournamentRecord:t,event:e});return{[e.eventId]:{event:e,scheduleTiming:n}}}))),u={averageTimes:[{minutes:{default:e}}],recoveryTimes:[{minutes:{default:t}}]};n??=s?.filter(t=>{const e=t.schedule;return mE({schedule:e})&&(!a||e?.scheduledDate===a)});const d=n?.filter(t=>(!i.length||i.includes(t.schedule?.venueId??""))&&t.matchUpStatus!==Sp),p=d?.map(({eventId:t,schedule:e,matchUpFormat:n})=>{const{event:r,scheduleTiming:i}=c[t],a=r?.eventType,s={...i,defaultTiming:u,matchUpFormat:n},{averageMinutes:d,recoveryMinutes:p}=Xh({timingDetails:s,eventType:a}),{courtId:l,venueId:m}=e??{},f=_o(e?.scheduledTime),h=Ho(f,d);return{recoveryMinutes:p,averageMinutes:d,periodLength:o,startTime:f,courtId:l,endTime:h,venueId:m}}).filter(Boolean);return{bookings:p,relevantMatchUps:d,dateScheduledMatchUps:n}}function mF({calculateStartTimeFromCourts:t=!0,remainingScheduleTimes:e,defaultRecoveryMinutes:n,averageMatchUpMinutes:r,clearScheduleDates:i,tournamentRecords:o,tournamentRecord:a,periodLength:s,scheduleDate:c,startTime:u,venueIds:d,matchUps:p,endTime:l}){if(a&&!o&&(o={[a.tournamentId]:a}),"object"!=typeof o||!Object.keys(o).length)return{error:nt};s=s??TO({recoveryMinutes:n,averageMatchUpMinutes:r});const{courts:m,venues:f}=gw({dates:[c],ignoreDisabled:!0,tournamentRecords:o}),h=m?.filter(t=>!d||d.includes(t.venueId))??[];u=u??DO({courts:h,scheduleDate:c,startTime:!0}),l=l??DO({courts:h,scheduleDate:c,endTime:!0});const{bookings:g,dateScheduledMatchUps:I}=lF({defaultRecoveryMinutes:n,averageMatchUpMinutes:r,tournamentRecords:o,scheduleDate:c,periodLength:s,venueIds:d,matchUps:p}),S={calculateStartTimeFromCourts:t,remainingScheduleTimes:e,averageMatchUpMinutes:r,clearScheduleDates:i,date:c,periodLength:s,startTime:u,bookings:g,endTime:l,courts:h},{scheduleTimes:y}=RO(S),v=1===d?.length&&d[0]||1===f?.length&&f[0].venueId||void 0,U=I?.map(eI("matchUpId"));return{dateScheduledMatchUpIds:U,dateScheduledMatchUps:I,scheduleTimes:y,venueId:v}}function fF({scheduledRoundsDetails:t,greatestAverageMinutes:e,garmanSinglePass:n}){const r=[];let i,o,a,s,c=[];for(const r of t.filter(Boolean))s||(s=r.hash),(r.hash===s||n)&&(c=c.concat(r.matchUpIds)),r.hash,a=e,o=r.recoveryMinutes,i=r.roundPeriodLength;return c.length&&r.push({matchUpIds:c,roundPeriodLength:i,recoveryMinutes:o,averageMinutes:a}),{groupedRounds:r}}function hF({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,scheduleCompletedMatchUps:n,excludeNoDateCompleted:r,containedStructureIds:i,matchUpNotBeforeTimes:o,matchUpScheduleTimes:a,matchUpDependencies:s,excludePriorDates:c,clearScheduleDates:u,tournamentRecords:d,periodLength:p,scheduleDate:l,useGarman:m,matchUps:f,courts:h,venues:g}){const I={},S=[],y=[],v=[];for(const U of g){const{rounds:g=[],venueId:P}=U,{scheduledRoundsDetails:T,greatestAverageMinutes:w,orderedMatchUpIds:D,minutesMap:R}=qA({scheduleCompletedMatchUps:n,containedStructureIds:i,tournamentRecords:d,periodLength:p,matchUps:f,rounds:g});v.push(...D??[]);const{groupedRounds:b}=fF({scheduledRoundsDetails:T,greatestAverageMinutes:w,garmanSinglePass:!0});let N,M=[];m&&({scheduleTimes:M,dateScheduledMatchUpIds:N}=mF({averageMatchUpMinutes:b[0]?.averageMinutes,scheduleDate:Lo(l),venueIds:[U.venueId],clearScheduleDates:u,tournamentRecords:d,periodLength:p,matchUps:f}));const A=pF({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,excludeNoDateCompleted:r,dateScheduledMatchUpIds:N,greatestAverageMinutes:w,matchUpNotBeforeTimes:o,matchUpScheduleTimes:a,excludePriorDates:c,matchUpDependencies:s,clearScheduleDates:u,scheduleDate:l,minutesMap:R,matchUps:f});({dateScheduledMatchUpIds:N}=A);const E=A,{byeScheduledMatchUpDetails:C,clearDate:O}=A;C?.length&&y.push(...C);const{matchUpsToSchedule:k,matchUpMap:F}=GA({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:n,dateScheduledMatchUpIds:N,matchUpNotBeforeTimes:o,matchUpScheduleTimes:a,orderedMatchUpIds:D,clearDate:O,matchUps:f}),x=h.filter(t=>t.venueId===P);I[P]={previousRemainingScheduleTimes:[],courtsCount:x.length,greatestAverageMinutes:w,scheduledRoundsDetails:T,dateScheduledMatchUps:E,matchUpsToSchedule:k,scheduleTimes:M,groupedRounds:b,venueCourts:x,minutesMap:R,matchUpMap:F},u||S.push(...N)}return{allDateScheduledByeMatchUpDetails:y,allDateScheduledMatchUpIds:S,venueScheduledRoundDetails:I,allDateMatchUpIds:v}}function gF(t,e){const n=Fo(t.scheduleTime),r=Fo(t.timeAfterRecovery),i=Fo(e.scheduleTime),o=Fo(e.timeAfterRecovery),a=n>i&&n<o,s=i>n&&i<r,c=r>i&&r<o,u=o>n&&o<r;return Ei({hasOverlap:n===i||r===o||a||c||s||u,startAisContained:a,endAisContained:c,startBisContained:s,endBisContained:u},!0)}function IF({individualParticipantProfiles:t,matchUpNotBeforeTimes:e,matchUpDependencies:n,scheduleTime:r,matchUp:i,details:o}){const a=(n?.[i.matchUpId]?.participantIds??[]).flat(),s=o?.minutesMap?.[i.matchUpId]?.averageMinutes||0,c=o?.minutesMap?.[i.matchUpId]?.recoveryMinutes||0,u=[];for(const e of a){iF({individualParticipantProfiles:t,participantId:e});const n=t[e];if(!n.timeAfterRecovery)continue;const o=_o(i?.schedule?.endTime),a=o?Ho(o,p(c)):Ho(r,p(s)+p(c));[...Object.keys(n.potentialBookings).filter(t=>t!==i.drawId).flatMap(t=>n.potentialBookings[t]),...n.bookings].some(t=>gF({scheduleTime:r,timeAfterRecovery:a},t).hasOverlap)&&u.push(e)}const d=0===u.length,l=e[i.matchUpId],m=l?$o(Wo(l),Wo(r),!1):0;return{enoughTime:d&&m>=0,blockingParticipantIds:u,notBeforeTime:l}}function SF({autoSchedulingAudit:t,tournamentRecords:e}){di({topic:Il,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},o={itemType:MC,itemValue:i};for(const t of Object.values(e)){const e=t.tournamentId;Ii(Il)?di({payload:{type:MC,tournamentId:e,detail:i},topic:Il}):iU({tournamentRecord:t,timeItem:o})}}function yF({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUpDailyLimits:n={},matchUp:r}){const{enteredIndividualParticipantIds:i}=rm(r),{matchUpId:o,matchUpType:a}=r,s=((r.roundPosition&&t[o])??[]).flat(),c=M(i.concat(...s));c.forEach(t=>{iF({individualParticipantProfiles:e,participantId:t})});return{participantIdsAtLimit:c.filter(t=>{const r=e[t];if(r)return[a,_h].find(t=>{const e=r.counters?.[t]||0,i=n[t]||0;return e&&i&&e>=i})}),relevantParticipantIds:c}}function vF({scheduleCompletedMatchUps:t=!1,scheduleByeMatchUps:e=!1,errorOnAnachronism:n=!1,checkChronology:r=!0,matchUpDependencies:i,removePriorValues:o,tournamentRecords:a,tournamentRecord:s,matchUpDetails:c,matchUpIds:u,schedule:d}){if(!s)return{error:rt};if(!(c||u&&Array.isArray(u)))return{error:he};if(!(c||d&&"object"==typeof d))return{error:Qn};let p;const l=[];let m=0;if(r&&!i){const t=iI({tournamentRecords:a,tournamentRecord:s});i=t.matchUpDependencies,p=t.matchUps}p||(p=Qg({tournamentRecord:s})?.matchUps??[]);const f=p.reduce((n,r)=>{const{matchUpId:i,drawId:o,matchUpStatus:a}=r;return!e&&a===Sp||!t&&_p.includes(a)||(n[o]?n[o].push(i):n[o]=[i]),n},{}),h=c?.map(t=>t.matchUpId);for(const t of Object.keys(f)){const{drawDefinition:e}=Mw({tournamentRecord:s,drawId:t});if(!e)continue;const g=f[t].filter(t=>u?.includes(t)??h?.includes(t)),I=Zg({inContext:!1,drawDefinition:e}).matchUps;for(const t of g){const u=Tk({schedule:c?.find(e=>e.matchUpId===t)?.schedule||d,matchUpDependencies:i,errorOnAnachronism:n,removePriorValues:o,inContextMatchUps:p,tournamentRecords:a,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?{...Y,scheduled:m,warnings:l}:{...Y,scheduled:m}}function UF(t){const{scheduleCompletedMatchUps:e=!1,scheduleByeMatchUps:n=!1,errorOnAnachronism:r,matchUpContextIds:i,removePriorValues:o,tournamentRecords:a,checkChronology:s,matchUpDetails:c,schedule:u}=t;if(t.matchUpIds&&!i)return vF(t);const d=fu(t,[{[hc]:!0},{[du]:{matchUpContextIds:!1,matchUpDetails:!1},[su]:sr,[cu]:iu}]);if(d.error)return d;if((!c||i)&&!u)return{error:Ae,info:"schedule is required"};const p=[];let l=0;const{matchUpDependencies:m}=iI({tournamentRecords:a});for(const t of Object.values(a)){const{tournamentId:d}=t,f=i?.filter(t=>t.tournamentId===d).map(tl),h=c?.filter(t=>t?.tournamentId===d);if(f?.length||h?.length){const i=vF({matchUpDetails:h,scheduleCompletedMatchUps:e,scheduleByeMatchUps:n,matchUpDependencies:m,errorOnAnachronism:r,removePriorValues:o,tournamentRecords:a,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?{...Y,scheduled:l,warnings:p}:{...Y,scheduled:l}}function PF({recoveryTimeDeferredMatchUpIds:t,dependencyDeferredMatchUpIds:e,scheduleTimesRemaining:n,skippedScheduleTimes:r,scheduledMatchUpIds:i,overLimitMatchUpDetails:o,overLimitMatchUpIds:a,noTimeMatchUpIds:s,requestConflicts:c,scheduleDate:u}){t[u]={},e[u]={},n[u]={},r[u]={},i[u]=[],o[u]=[],a[u]=[],s[u]=[],c[u]=[]}function TF({checkPotentialRequestConflicts:t,recoveryTimeDeferredMatchUpIds:e,dependencyDeferredMatchUpIds:n,individualParticipantProfiles:r,matchUpPotentialParticipantIds:i,scheduleDateRequestConflicts:o,matchUpScheduleTimes:a,matchUpNotBeforeTimes:s,overLimitMatchUpDetails:c,overLimitMatchUpIds:u,matchUpDependencies:d,matchUpDailyLimits:p,allDateMatchUpIds:l,requestConflicts:m,personRequests:f,scheduleTime:h,scheduleDate:g,details:I,matchUp:S}){const{matchUpId:y,matchUpType:v}=S,{participantIdsAtLimit:U,relevantParticipantIds:P}=yF({matchUpPotentialParticipantIds:i,individualParticipantProfiles:r,matchUpDailyLimits:p,matchUp:S});if(U.length)return u[g].includes(y)||u[g].push(y),function({overLimitMatchUpDetails:t,individualParticipantProfiles:e,participantIdsAtLimit:n,matchUpDailyLimits:r,matchUpType:i,scheduleDate:o,scheduleTime:a,matchUpId:s}){const c=[i,_h],u=n.map(t=>{const n=e[t]?.counters||{};return{participantId:t,atLimitCounters:c.filter(t=>{const e=n[t]||0,i=r[t]||0;return e&&i&&e>=i}).map(t=>({counter:t,count:n[t],limit:r[t]}))}});t[o].push({matchUpId:s,attemptedTime:a,participants:u})}({overLimitMatchUpDetails:c,individualParticipantProfiles:r,participantIdsAtLimit:U,matchUpDailyLimits:p,matchUpType:v,scheduleDate:g,scheduleTime:h,matchUpId:y}),!1;const{scheduledDependent:T}=aF({matchUpScheduleTimes:a,matchUpDependencies:d,scheduleTime:h,matchUpId:y,details:I});if(T)return!1;const{dependenciesScheduled:w,remainingDependencies:D}=rF({matchUpScheduleTimes:a,matchUpDependencies:d,allDateMatchUpIds:l,matchUp:S});if(!w)return n[g][y]||(n[g][y]=[]),n[g][y].push({scheduleTime:h,remainingDependencies:D}),!1;const{enoughTime:R,blockingParticipantIds:b,notBeforeTime:N}=IF({individualParticipantProfiles:r,matchUpNotBeforeTimes:s,matchUpDependencies:d,scheduleTime:h,details:I,matchUp:S});if(!R)return e[g][y]||(e[g][y]=[]),e[g][y].push({scheduleTime:h,blockingParticipantIds:b,notBeforeTime:N}),!1;const M=I.greatestAverageMinutes,{conflicts:A}=uF({potentials:t,averageMatchUpMinutes:M,requestConflicts:m,personRequests:f,scheduleTime:h,scheduleDate:g,matchUp:S});if(A?.length)return o[g]||(o[g]=[]),o[g].push(...A),!1;!function(t,e,n){t.forEach(t=>{const r=n[t].counters;r[e]?r[e]+=1:r[e]=1,r[_h]?r[_h]+=1:r[_h]=1})}(P,v,r);const E=I.minutesMap?.[y]?.recoveryMinutes;return oF({matchUpPotentialParticipantIds:i,individualParticipantProfiles:r,matchUpNotBeforeTimes:s,averageMatchUpMinutes:M,matchUpDependencies:d,recoveryMinutes:E,scheduleTime:h,matchUp:S}),a[y]=h,!0}function wF({checkPotentialRequestConflicts:t,recoveryTimeDeferredMatchUpIds:e,dependencyDeferredMatchUpIds:n,individualParticipantProfiles:r,matchUpPotentialParticipantIds:i,scheduleDateRequestConflicts:o,venueScheduledRoundDetails:a,matchUpScheduleTimes:s,matchUpNotBeforeTimes:c,overLimitMatchUpDetails:u,overLimitMatchUpIds:d,skippedScheduleTimes:p,matchUpDependencies:l,matchUpDailyLimits:m,allDateMatchUpIds:f,requestConflicts:h,personRequests:g,scheduleDate:I,venues:S}){let y,v=0;for(;!y;){for(const{venueId:y}of S){let S=0;const v=a[y];for(;v.courtsCount&&v.scheduleTimes?.length&&v.matchUpsToSchedule?.length&&S<=v.courtsCount;){const{scheduleTime:a,attempts:U=0}=v.scheduleTimes.shift(),P=v.matchUpsToSchedule.find(p=>TF({checkPotentialRequestConflicts:t,recoveryTimeDeferredMatchUpIds:e,dependencyDeferredMatchUpIds:n,individualParticipantProfiles:r,matchUpPotentialParticipantIds:i,scheduleDateRequestConflicts:o,matchUpScheduleTimes:s,matchUpNotBeforeTimes:c,overLimitMatchUpDetails:u,overLimitMatchUpIds:d,matchUpDependencies:l,matchUpDailyLimits:m,allDateMatchUpIds:f,requestConflicts:h,personRequests:g,scheduleTime:a,scheduleDate:I,details:v,matchUp:p}));v.matchUpsToSchedule=v.matchUpsToSchedule.filter(({matchUpId:t})=>t!==P?.matchUpId),P?S+=1:(p[I][y]||(p[I][y]=[]),p[I][y].push({scheduleTime:a,attempts:U+1}))}v.matchUpsToSchedule?.length&&(p[I][y]=p[I][y]?.filter(t=>{const e=t.attempts<10;return e&&v.scheduleTimes.push(t),!e})),v.scheduleTimes?.length&&v.matchUpsToSchedule?.length||(v.complete=!0)}v+=1,y=S.every(({venueId:t})=>a[t].complete)||10===v}}function DF({venueScheduledRoundDetails:t,scheduleTimesRemaining:e,matchUpScheduleTimes:n,scheduledMatchUpIds:r,tournamentRecords:i,noTimeMatchUpIds:o,scheduleDate:a,venues:s,dryRun:c}){for(const{venueId:u}of s){const s=t[u].matchUpMap;Object.keys(s).forEach(t=>{const e=i[t];e&&Object.keys(s[t]).forEach(i=>{const{drawDefinition:o}=Mw({tournamentRecord:e,drawId:i});if(!o)return;s[t][i].forEach(({matchUpId:t})=>{RF({scheduledMatchUpIds:r,drawDefinition:o,matchUpScheduleTimes:n,tournamentRecord:e,scheduleDate:a,matchUpId:t,venueId:u,dryRun:c})})})}),o[a]=t[u].matchUpsToSchedule.map(tl),e[a][u]=t[u].scheduleTimes.sort((t,e)=>Fo(t.scheduleTime)-Fo(e.scheduleTime))}}function RF({scheduledMatchUpIds:t,drawDefinition:e,matchUpScheduleTimes:n,tournamentRecord:r,scheduleDate:i,matchUpId:o,venueId:a,dryRun:s}){const c=n[o];if(!c)return;const u=c.split(":").map(Yo).join(":"),d=Lo(i);if(s)return void t[i].push(o);Ik({tournamentRecord:r,drawDefinition:e,scheduledDate:d,matchUpId:o});hk({drawDefinition:e,scheduledTime:u,matchUpId:o}).success&&t[i].push(o),a&&yk({tournamentRecord:r,drawDefinition:e,matchUpId:o,venueId:a})}function bF({allDateScheduledByeMatchUpDetails:t,tournamentRecords:e,dryRun:n}){!n&&t?.length&&UF({matchUpDetails:t,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:e,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}})}function NF({scheduledMatchUpIds:t,dateSchedulingProfile:e,scheduleDate:n}){for(const r of e.venues)for(const e of r.rounds){const r=e.matchUps?.map(({matchUpId:t})=>t)??[],i=r.filter(e=>t[n].includes(e));e.canScheduledMatchUpIds=i;let o=Math.round(i.length/e.matchUpsCount*1e4)/100;(o===1/0||Number.isNaN(o))&&(o=0),e.possibleToSchedulePct=o,e.matchUpsCount===i.length&&(e.possibleToSchedule=!0)}}function MF({averageMinutes:t,startTime:e,endTime:n,court:r,date:i}){if(!Array.isArray(r.dateAvailability))return{error:Ae,stack:"getEarliestCourtTime"};const o=DO({scheduleDate:i,courts:[r],startTime:!0}),a=DO({scheduleDate:i,courts:[r],endTime:!0});e=e||o,n=n||a;const s=eE({court:r,date:i}),{timeSlots:c}=vO({courtDate:s}),u=Wo(e),d=Wo(n),p=c?.reduce((e,n)=>{const r=Wo(n.startTime),i=Wo(n.endTime);if(r>d||i<u)return e;const o=u>r?u:r;if($o(o,i)>=t){const t=_o(o.toISOString());t&&(!e||t<e)&&(e=t)}return e},void 0);return{earliestCourtTime:p,courtStartTime:o,courtEndTime:a}}function AF({recoveryTimeDeferredMatchUpIds:t,checkPotentialRequestConflicts:e,matchUpPotentialParticipantIds:n,individualParticipantProfiles:r,matchUpNotBeforeTimes:i,venueEarliestCourtTime:o,schedulingConflicts:a,matchUpScheduleTimes:s,matchUpDependencies:c,relevantParticipantIds:u,courtIdsScheduled:d,requestConflicts:p,personRequests:l,scheduleDate:m,bumpLimits:f,matchUpType:h,dateCourts:g,matchUpId:I,matchUp:S,details:y}){return g?.reduce((g,v)=>d.includes(v.courtId)?g:function({recoveryTimeDeferredMatchUpIds:t,checkPotentialRequestConflicts:e,matchUpPotentialParticipantIds:n,individualParticipantProfiles:r,matchUpNotBeforeTimes:i,venueEarliestCourtTime:o,schedulingConflicts:a,matchUpScheduleTimes:s,matchUpDependencies:c,relevantParticipantIds:u,requestConflicts:d,personRequests:p,scheduleDate:l,bumpLimits:m,matchUpType:f,matchUpId:h,courtTime:g,matchUp:I,details:S,court:y}){const{earliestCourtTime:v}=MF({averageMinutes:S.greatestAverageMinutes,startTime:o,date:l,court:y});if(g.scheduleTime&&Fo(v)>=Fo(g.scheduleTime))return g;const{scheduledDependent:U}=aF({matchUpScheduleTimes:s,matchUpDependencies:c,scheduleTime:v,matchUpId:h,details:S});if(U)return g;const{enoughTime:P}=IF({individualParticipantProfiles:r,matchUpNotBeforeTimes:i,matchUpDependencies:c,scheduleTime:v,details:S,matchUp:I});if(!P)return t[l][h]||(t[l][h]=[]),t[l][h].includes(v)||t[l][h].push(v),g;const T=S.minutesMap?.[h]?.averageMinutes||S.greatestAverageMinutes,{conflicts:w}=uF({potentials:e,averageMatchUpMinutes:T,requestConflicts:d,personRequests:p,scheduleTime:v,scheduleDate:l,matchUp:I});if(w?.length)return a.push(...w),!1;m(u,f);const D=S.minutesMap?.[h]?.recoveryMinutes;return oF({matchUpPotentialParticipantIds:n,individualParticipantProfiles:r,matchUpNotBeforeTimes:i,averageMatchUpMinutes:T,matchUpDependencies:c,recoveryMinutes:D,scheduleTime:v,matchUp:I}),(!g.scheduleTime||Fo(v)<Fo(g.scheduleTime))&&(g.averageMatchUpMinutes=T,g.recoveryMinutes=D,g.scheduleTime=v,g.courtName=y.courtName,g.courtId=y.courtId),g}({recoveryTimeDeferredMatchUpIds:t,checkPotentialRequestConflicts:e,matchUpPotentialParticipantIds:n,individualParticipantProfiles:r,matchUpNotBeforeTimes:i,venueEarliestCourtTime:o,schedulingConflicts:a,matchUpScheduleTimes:s,matchUpDependencies:c,relevantParticipantIds:u,requestConflicts:p,personRequests:l,scheduleDate:m,bumpLimits:f,matchUpType:h,matchUpId:I,courtTime:g,matchUp:S,details:y,court:v}),{})}function EF({recoveryTimeDeferredMatchUpIds:t,checkPotentialRequestConflicts:e,dependencyDeferredMatchUpIds:n,matchUpPotentialParticipantIds:r,individualParticipantProfiles:i,scheduleDateRequestConflicts:o,matchUpNotBeforeTimes:a,venueEarliestCourtTime:s,matchUpScheduleCourtIds:c,overLimitMatchUpIds:u,matchUpScheduleTimes:d,matchUpDependencies:p,matchUpDailyLimits:l,courtIdsScheduled:m,requestConflicts:f,allDateMatchUpIds:h,personRequests:g,periodLength:I,scheduleDate:S,bumpLimits:y,dateCourts:v,matchUp:U,details:P,venueId:T}){const{matchUpId:w,matchUpType:D}=U,{participantIdsAtLimit:R,relevantParticipantIds:b}=yF({matchUpPotentialParticipantIds:r,individualParticipantProfiles:i,matchUpDailyLimits:l,matchUp:U});if(R.length)return u[S].includes(w)||u[S].push(w),{skipped:"overLimit"};const{dependenciesScheduled:N,remainingDependencies:M}=rF({matchUpScheduleTimes:d,matchUpDependencies:p,allDateMatchUpIds:h,matchUp:U});if(!N)return n[S][w]||(n[S][w]=[]),n[S][w].push({remainingDependencies:M}),{skipped:"dependencyDeferred"};const A=[],E=AF({recoveryTimeDeferredMatchUpIds:t,checkPotentialRequestConflicts:e,matchUpPotentialParticipantIds:r,individualParticipantProfiles:i,matchUpNotBeforeTimes:a,venueEarliestCourtTime:s,schedulingConflicts:A,matchUpScheduleTimes:d,matchUpDependencies:p,relevantParticipantIds:b,courtIdsScheduled:m,requestConflicts:f,personRequests:g,scheduleDate:S,bumpLimits:y,matchUpType:D,dateCourts:v,matchUpId:w,matchUp:U,details:P});if(E.scheduleTime){const{averageMatchUpMinutes:t,recoveryMinutes:e,scheduleTime:n,courtId:r}=E;d[w]=n,c[w]=r;return{scheduled:!0,matchUpId:w,courtId:r,booking:{averageMatchUpMinutes:t,recoveryMinutes:e,periodLength:I,matchUpId:w,startTime:n,courtId:r,endTime:Ho(n,t),venueId:T}}}return A?.length&&(o[S]||(o[S]=[]),o[S].push(...A)),{scheduled:!1}}function CF({venueScheduledRoundDetails:t,matchUpScheduleCourtIds:e,scheduledMatchUpIds:n,matchUpScheduleTimes:r,noTimeMatchUpIds:i,tournamentRecords:o,scheduleDate:a,venues:s,dryRun:c}){for(const{venueId:u}of s){const s=t[u].matchUpMap;Object.keys(s).forEach(t=>{const i=o[t];i&&Object.keys(s[t]).forEach(u=>{const{drawDefinition:d}=Mw({tournamentRecord:i,drawId:u});if(d){s[t][u].forEach(({matchUpId:t})=>{const s=r[t],u=e[t];if(s){const e=s.split(":").map(Yo).join(":"),r=`${Lo(a)}T${e}`;c||(hk({drawDefinition:d,scheduledTime:r,matchUpId:t}),vk({courtDayDate:a,tournamentRecords:o,tournamentRecord:i,drawDefinition:d,matchUpId:t,courtId:u})),n[a].push(t)}})}})}),i[a]=t[u].matchUpsToSchedule.map(tl)}}function OF({recoveryTimeDeferredMatchUpIds:t,checkPotentialRequestConflicts:e,dependencyDeferredMatchUpIds:n,matchUpPotentialParticipantIds:r,individualParticipantProfiles:i,scheduleDateRequestConflicts:o,matchUpNotBeforeTimes:a,venueEarliestCourtTime:s,matchUpScheduleCourtIds:c,addDateCourtBooking:u,overLimitMatchUpIds:d,matchUpScheduleTimes:p,matchUpDependencies:l,matchUpDailyLimits:m,requestConflicts:f,allDateMatchUpIds:h,personRequests:g,periodLength:I,scheduleDate:S,bumpLimits:y,dateCourts:v,details:U,venueId:P}){const T=U.matchUpsToSchedule.length,w=[],D=[];let R,b=0;for(;!R;){for(const T of U.matchUpsToSchedule){if(D.length===U.courtsCount||w.length===U.courtsCount){R=!0;break}const b=EF({recoveryTimeDeferredMatchUpIds:t,checkPotentialRequestConflicts:e,dependencyDeferredMatchUpIds:n,matchUpPotentialParticipantIds:r,individualParticipantProfiles:i,scheduleDateRequestConflicts:o,matchUpNotBeforeTimes:a,venueEarliestCourtTime:s,matchUpScheduleCourtIds:c,overLimitMatchUpIds:d,matchUpScheduleTimes:p,matchUpDependencies:l,matchUpDailyLimits:m,courtIdsScheduled:D,requestConflicts:f,allDateMatchUpIds:h,personRequests:g,periodLength:I,scheduleDate:S,bumpLimits:y,dateCourts:v,matchUp:T,details:U,venueId:P});if(!b.skipped&&b.scheduled){const{matchUpId:t,courtId:e,booking:n}=b;w.push(t),D.push(e),u({courtId:e,booking:n}),U.matchUpsToSchedule=U.matchUpsToSchedule.filter(e=>e.matchUpId!==t)}}D.length!==U.courtsCount&&w.length!==U.courtsCount&&U.matchUpsToSchedule.length||(R=!0),b+=1,!R&&b>=T&&(R=!0)}return{matchUpIdsScheduled:w}}function kF({recoveryTimeDeferredMatchUpIds:t,checkPotentialRequestConflicts:e,dependencyDeferredMatchUpIds:n,matchUpPotentialParticipantIds:r,individualParticipantProfiles:i,scheduleDateRequestConflicts:o,venueScheduledRoundDetails:a,matchUpNotBeforeTimes:s,venueEarliestCourtTime:c,matchUpScheduleCourtIds:u,addDateCourtBooking:d,overLimitMatchUpIds:p,matchUpScheduleTimes:l,matchUpDependencies:m,matchUpDailyLimits:f,venueTimeBoundaries:h,requestConflicts:g,allDateMatchUpIds:I,personRequests:S,periodLength:y,scheduleDate:v,bumpLimits:U,dateCourts:P,venues:T}){let w,D=0;for(;!w;){for(const{venueId:w}of T){const T=a[w],{matchUpIdsScheduled:D}=OF({recoveryTimeDeferredMatchUpIds:t,checkPotentialRequestConflicts:e,dependencyDeferredMatchUpIds:n,matchUpPotentialParticipantIds:r,individualParticipantProfiles:i,scheduleDateRequestConflicts:o,matchUpNotBeforeTimes:s,venueEarliestCourtTime:c,matchUpScheduleCourtIds:u,addDateCourtBooking:d,overLimitMatchUpIds:p,matchUpScheduleTimes:l,matchUpDependencies:m,matchUpDailyLimits:f,requestConflicts:g,allDateMatchUpIds:I,personRequests:S,periodLength:y,scheduleDate:v,bumpLimits:U,dateCourts:P,details:T,venueId:w});T.matchUpsToSchedule.length&&D<T.courtsCount&&(Wo(c)<Wo(h.endTime)?c=Ho(c,y):T.complete=!0),T.matchUpsToSchedule?.length||(T.complete=!0)}D+=1,w=T.every(({venueId:t})=>a[t].complete)||10===D}return c}function FF({dateSchedulingProfile:t,scheduledMatchUpIds:e,scheduleDate:n}){for(const r of t.venues)for(const t of r.rounds){const r=(t.matchUps??[]).map(({matchUpId:t})=>t),i=r?.filter(t=>e[n].includes(t));t.canScheduledMatchUpIds=i;let o=Math.round((i?.length||0)/t.matchUpsCount*1e4)/100;(o===1/0||isNaN(o))&&(o=void 0),t.possibleToSchedulePct=o,t.matchUpsCount===i?.length&&(t.possibleToSchedule=!0)}}function xF(t){const{scheduleAttributes:e=["scheduledDate","scheduledTime","courtOrder"],ignoreMatchUpStatuses:n=_p,scheduledDates:r,venueIds:i}=t,o=im(t),a=f(o)?Object.values(o).map(({tournamentId:t})=>t).filter(Boolean):[];if(!a?.length)return{error:nt};let s=0;for(const t of a){const a=_F({ignoreMatchUpStatuses:n,scheduleAttributes:e,tournamentRecord:o[t],scheduledDates:r,venueIds:i});if(a.error)return a;s+=a.clearedScheduleCount??0}return{...Y,clearedScheduleCount:s}}function _F({scheduleAttributes:t=["scheduledDate","scheduledTime","courtOrder"],ignoreMatchUpStatuses:e=_p,tournamentRecord:n,scheduledDates:r,venueIds:i=[]}){if("object"!=typeof n)return{error:rt};if(!Array.isArray(e)||!Array.isArray(i))return{error:sr};i.length&&t.push("venueId");const o=Qg({matchUpFilters:{scheduledDates:r},tournamentRecord:n}).matchUps??[],a={};o.forEach(({matchUpStatus:n,schedule:r,drawId:o,matchUpId:s})=>{n&&e.includes(n)||!mE({schedule:r,scheduleAttributes:t})||i?.length&&!i.includes(r?.venueId??"")||(a[o]||(a[o]=[]),a[o].push(s))});const s=n.tournamentId;let c=0;for(const t in a){const{event:e,drawDefinition:r}=wg({tournamentRecord:n,drawId:t}),i=Zg({drawDefinition:r,matchUpFilters:{matchUpIds:a[t]}}).matchUps??[];for(const t of i){let n=!1;t.timeItems=(t.timeItems??[]).filter(t=>{const e=t?.itemType&&![Zf,th,Xf,nh,eh,rh,ah].includes(t?.itemType);return e||(n=!0),e}),n&&(Yl({context:"clear schedules",eventId:e?.eventId,drawDefinition:r,tournamentId:s,matchUp:t}),c+=1)}}return{...Y,clearedScheduleCount:c}}function LF(t){const{checkPotentialRequestConflicts:e=!0,excludeNoDateCompleted:r=!0,scheduleCompletedMatchUps:o,excludePriorDates:a=!0,clearScheduleDates:s,scheduleDates:c=[],tournamentRecords:u,periodLength:d,useGarman:p,courtIds:l,dryRun:m,pro:f}=t,h=fu(t,[{[hc]:!0},{[ou]:t=>!t||Array.isArray(t)&&t.every(Do),[Tc]:!1,[cu]:iu}]);if(h.error)return h;const g=HA({tournamentRecords:u});if(g.error)return g;if(!g.schedulingProfile.length)return{...Y};const{modifications:I,issues:S=[],schedulingProfile:y=[]}=g,v=Object.assign({},...Object.values(u).map(t=>nm({tournamentRecord:t}).containedStructures)),U=new Set(c.map(t=>{if(Do(t))return Lo(t)}).filter(Boolean)),P=y.map(t=>t.scheduleDate).map(t=>Do(t)&&Lo(t)).filter(t=>t&&(!c.length||U.has(t)));if(!P.length)return{error:Oe};if(s&&!m){xF({tournamentRecords:u,scheduledDates:Array.isArray(s)?s:[]})}const T=gw({ignoreDisabled:!1,tournamentRecords:u}).courts,w=Array.isArray(l)?T.filter(t=>l.includes(t.courtId)):T,{matchUps:D}=Jg({matchUpFilters:{matchUpTypes:[n,i]},afterRecoveryTimes:!0,nextMatchUps:!0,tournamentRecords:u}),{matchUpDependencies:R}=iI({includeParticipantDependencies:!0,tournamentRecords:u,matchUps:D}),{matchUpDailyLimits:b}=wE({tournamentRecords:u}),{personRequests:N}=QA({requestType:sF,tournamentRecords:u}),M={schedulingProfileModifications:I,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:o,excludeNoDateCompleted:r,schedulingProfileIssues:S,dateSchedulingProfiles:y.filter(t=>{const e=Lo(t?.scheduleDate);return P.includes(e)}).sort((t,e)=>new Date(t.scheduleDate).getTime()-new Date(e.scheduleDate).getTime()),containedStructureIds:v,matchUpDependencies:R,matchUpDailyLimits:b,excludePriorDates:a,clearScheduleDates:s,tournamentRecords:u,schedulingProfile:y,personRequests:N,periodLength:d,matchUps:D,dryRun:m,courts:w};return f?function({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:n,excludeNoDateCompleted:r,schedulingProfileIssues:i,dateSchedulingProfiles:o,containedStructureIds:a,matchUpDependencies:s,matchUpDailyLimits:c,excludePriorDates:u,clearScheduleDates:d,tournamentRecords:p,periodLength:l=30,schedulingProfile:m,personRequests:f,matchUps:h=[],courts:g,dryRun:I}){const S={},y={},v={},U={},P={},T={},w={},D={},R={};for(const t of o??[]){const i=Lo(t?.scheduleDate),o=t?.venues??[],m={},b={},N=(t,e)=>{t.forEach(t=>{const n=b[t].counters;n[e]?n[e]+=1:n[e]=1,n[_h]?n[_h]+=1:n[_h]=1})};S[i]={},y[i]={},T[i]=[],w[i]=[],D[i]=[],R[i]=[];const M={};h?.forEach(t=>{t.schedule?.scheduledDate&&Ko(i,Lo(t.schedule.scheduledDate))&&VA({matchUpPotentialParticipantIds:m,matchUpNotBeforeTimes:M,matchUp:t})});const{allDateScheduledByeMatchUpDetails:A,allDateScheduledMatchUpIds:E,venueScheduledRoundDetails:C,allDateMatchUpIds:O}=hF({matchUpPotentialParticipantIds:m,individualParticipantProfiles:b,scheduleCompletedMatchUps:n,excludeNoDateCompleted:r,containedStructureIds:a,matchUpNotBeforeTimes:M,matchUpScheduleTimes:P,matchUpDependencies:s,excludePriorDates:u,clearScheduleDates:d,tournamentRecords:p,periodLength:l,scheduleDate:i,matchUps:h,courts:g,venues:o}),k=h?.filter(({matchUpId:t})=>E.includes(t)),{bookings:F}=lF({dateScheduledMatchUps:k,tournamentRecords:p,scheduleDate:i,periodLength:l}),{virtualCourts:x}=PO({scheduleDate:i,periodLength:l,bookings:F,courts:g}),_=x?.reduce((t,e)=>{const{earliestCourtTime:n,courtEndTime:r}=MF({date:i,averageMinutes:0,court:e});return(!t.startTime||Wo(n)<Wo(t.startTime))&&(t.startTime=n),(!t.endTime||Wo(r)>Wo(t.endTime))&&(t.endTime=r),t},{});let L=_.startTime;kF({recoveryTimeDeferredMatchUpIds:S,checkPotentialRequestConflicts:e,dependencyDeferredMatchUpIds:y,matchUpPotentialParticipantIds:m,individualParticipantProfiles:b,scheduleDateRequestConflicts:v,venueScheduledRoundDetails:C,matchUpNotBeforeTimes:M,venueEarliestCourtTime:L,matchUpScheduleCourtIds:U,addDateCourtBooking:({courtId:t,booking:e})=>x?.find(e=>e.courtId===t)?.dateAvailability[0].bookings.push(e),overLimitMatchUpIds:w,matchUpScheduleTimes:P,matchUpDependencies:s,matchUpDailyLimits:c,venueTimeBoundaries:_,requestConflicts:R,allDateMatchUpIds:O,personRequests:f,periodLength:l,scheduleDate:i,bumpLimits:N,dateCourts:x,venues:o}),CF({venueScheduledRoundDetails:C,matchUpScheduleCourtIds:U,scheduledMatchUpIds:T,matchUpScheduleTimes:P,noTimeMatchUpIds:D,tournamentRecords:p,scheduleDate:i,venues:o,dryRun:I}),!I&&A?.length&&UF({matchUpDetails:A,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:p,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}}),FF({dateSchedulingProfile:t,scheduledMatchUpIds:T,scheduleDate:i})}const b=(o??[]).map(({scheduleDate:t})=>t);return SF({tournamentRecords:p,autoSchedulingAudit:{timeStamp:Date.now(),overLimitMatchUpIds:w,scheduledMatchUpIds:T,schedulingProfile:m,noTimeMatchUpIds:D,requestConflicts:R,scheduledDates:b}}),{...Y,schedulingProfileModifications:t,schedulingProfileIssues:i,dateSchedulingProfiles:o,recoveryTimeDeferredMatchUpIds:S,dependencyDeferredMatchUpIds:y,matchUpScheduleTimes:P,overLimitMatchUpIds:w,scheduledMatchUpIds:T,noTimeMatchUpIds:D,requestConflicts:R,scheduledDates:b}}(M):function({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:n,excludeNoDateCompleted:r,schedulingProfileIssues:i,dateSchedulingProfiles:o,containedStructureIds:a,matchUpDependencies:s,matchUpDailyLimits:c,excludePriorDates:u,clearScheduleDates:d,tournamentRecords:p,schedulingProfile:l,personRequests:m,periodLength:f,matchUps:h,courts:g,dryRun:I}){const S={},y={},v={},U={},P={},T={},w={},D={},R={},b={},N={};for(const t of o){const i=Lo(t?.scheduleDate),o=t?.venues??[],l={},M={};PF({recoveryTimeDeferredMatchUpIds:v,dependencyDeferredMatchUpIds:U,scheduleTimesRemaining:S,skippedScheduleTimes:y,scheduledMatchUpIds:w,overLimitMatchUpIds:D,overLimitMatchUpDetails:R,noTimeMatchUpIds:b,requestConflicts:N,scheduleDate:i});const A={};h.forEach(t=>{t.schedule?.scheduledDate&&Ko(i,Lo(t.schedule.scheduledDate))&&VA({matchUpPotentialParticipantIds:l,matchUpNotBeforeTimes:A,matchUp:t})});const{allDateScheduledByeMatchUpDetails:E,venueScheduledRoundDetails:C,allDateMatchUpIds:O}=hF({matchUpPotentialParticipantIds:l,individualParticipantProfiles:M,scheduleCompletedMatchUps:n,excludeNoDateCompleted:r,containedStructureIds:a,matchUpNotBeforeTimes:A,matchUpScheduleTimes:T,matchUpDependencies:s,excludePriorDates:u,clearScheduleDates:d,tournamentRecords:p,useGarman:!0,periodLength:f,scheduleDate:i,matchUps:h,courts:g,venues:o});wF({checkPotentialRequestConflicts:e,recoveryTimeDeferredMatchUpIds:v,dependencyDeferredMatchUpIds:U,individualParticipantProfiles:M,matchUpPotentialParticipantIds:l,scheduleDateRequestConflicts:P,venueScheduledRoundDetails:C,matchUpScheduleTimes:T,matchUpNotBeforeTimes:A,overLimitMatchUpDetails:R,overLimitMatchUpIds:D,skippedScheduleTimes:y,matchUpDependencies:s,matchUpDailyLimits:c,allDateMatchUpIds:O,requestConflicts:N,personRequests:m,scheduleDate:i,venues:o}),DF({venueScheduledRoundDetails:C,scheduleTimesRemaining:S,matchUpScheduleTimes:T,scheduledMatchUpIds:w,tournamentRecords:p,noTimeMatchUpIds:b,scheduleDate:i,venues:o,dryRun:I}),bF({allDateScheduledByeMatchUpDetails:E,tournamentRecords:p,dryRun:I}),NF({scheduledMatchUpIds:w,dateSchedulingProfile:t,scheduleDate:i})}const M=o.map(({scheduleDate:t})=>t);return SF({tournamentRecords:p,autoSchedulingAudit:{timeStamp:Date.now(),overLimitMatchUpIds:D,scheduledMatchUpIds:w,schedulingProfile:l,noTimeMatchUpIds:b,requestConflicts:N,scheduledDates:M}}),{...Y,schedulingProfileModifications:t,schedulingProfileIssues:i,scheduleTimesRemaining:S,dateSchedulingProfiles:o,skippedScheduleTimes:y,recoveryTimeDeferredMatchUpIds:v,dependencyDeferredMatchUpIds:U,matchUpScheduleTimes:T,overLimitMatchUpDetails:R,overLimitMatchUpIds:D,scheduledMatchUpIds:w,noTimeMatchUpIds:b,requestConflicts:N,scheduledDates:M}}(M)}function BF(t){if(!t||"string"!=typeof t)return!1;try{return Intl.DateTimeFormat(void 0,{timeZone:t}),!0}catch{return!1}}function VF(t,e){const n=e??new Date,r=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"longOffset"}).formatToParts(n).find(t=>"timeZoneName"===t.type),i=r?.value??"";if("GMT"===i)return 0;const o=i.match(/GMT([+-])(\d{2}):(\d{2})/);if(!o)return 0;return("+"===o[1]?1:-1)*(60*Number.parseInt(o[2],10)+Number.parseInt(o[3],10))}function GF(t,e,n){if(!BF(n))return{error:Ge};const[r,i]=e.split(":").map(Number),[o,a,s]=t.split("-").map(Number),c=new Date(Date.UTC(o,a-1,s,r,i,0,0)),u=VF(n,c),d=c.getTime()-60*u*1e3,p=new Date(d),l=VF(n,p);if(l!==u){const t=c.getTime()-60*l*1e3;return new Date(t).toISOString()}return p.toISOString()}const jF={isValidIANATimeZone:BF,getTimeZoneOffsetMinutes:VF,wallClockToUTC:GF,utcToWallClock:function(t,e){if(!BF(e))return{error:Ge};const n=new Date(t),r=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(n),i=t=>r.find(e=>e.type===t)?.value??"";return{date:`${i("year")}-${i("month")}-${i("day")}`,time:`${"24"===i("hour")?"00":i("hour")}:${i("minute")}`}},toEmbargoUTC:function(t,e,n){const r=GF(t,e,n);return"string"!=typeof r||Oo(r)?r:{error:Ge}}};function qF(t){const{tournamentRecord:e,tournamentRecords:n,activeTournamentId:r,...i}=t??{};if(i.tournamentId??=pa(),i.startDate&&!Co(i.startDate)&&!So.test(i.startDate))return{error:_e};if(i.endDate&&!Co(i.endDate)&&!So.test(i.endDate))return{error:_e};if(i.activeDates){const t=i.activeDates.filter(Boolean);if(!t.every(t=>Co(t)||So.test(t)))return{error:_e};if(t.length){const e=[...t].sort();i.startDate??=e[0],i.endDate??=e[e.length-1];const n=t.every(t=>new Date(t)>=new Date(i.startDate)),r=t.every(t=>new Date(t)<=new Date(i.endDate));if(!n||!r)return{error:_e}}i.activeDates=t}return i.localTimeZone&&!BF(i.localTimeZone)?{error:Ge}:(i.extensions&&(i.extensions=i.extensions.filter(Wu)),{...i})}function WF({addParticipants:t=!0,participantAttribute:e,tournamentRecord:n,personAttribute:r,teamNames:i,accessor:o,uuids:a}){if(!n)return{error:rt};const s={},c=(n.participants??[]).filter(({participantType:t,participantRole:e})=>t===gm&&e===sy);let u=0;for(const t of c){const n=o&&Bd({element:t,accessor:o})?.value||r&&t.person?.[r]||e&&t[e];if(n){if(!Object.keys(s).includes(n)){s[n]={participantName:i?.[u]??n,participantId:a?.pop()??pa(),individualParticipantIds:[],participantRole:sy,participantType:ym};const t={value:r??e,name:md};$u({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!==ym)return;if(t.participantRole!==sy)return;const{extension:e}=td({name:md,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??=[],t&&n.participants.push(r),m.push(r),l++)}),t&&l?(di({payload:{tournamentId:n.tournamentId,participants:m},topic:ml}),{...Y,participantsAdded:l}):m.length?{...Y,newParticipants:m}:{error:He}}var $F=[{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"}],HF=["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 zF({count:t=1,participantsCount:e=32,random:n}={}){const r=A(HF,n),i=r.slice(0,t);return{cities:L(0,e).map(e=>e<Math.min(t,r.length)?i[e]:_(i,n))}}function YF({count:t=1,participantsCount:e=32,random:n}={}){const r=A($F,n),i=r.slice(0,t).flatMap(t=>Object.keys(t));return{states:L(0,e).map(e=>e<Math.min(t,r.length)?i[e]:_(i,n))}}function KF({count:t=1,participantsCount:e=32,random:n}={}){const r=L(0,t).map(()=>L(0,5).map(()=>D(0,9,n)).join(""));return{postalCodes:L(0,e).map(e=>e<t?r[e]:_(r,n))}}function QF({idPrefix:t,participantType:e,index:n,uuids:r,random:i}){const o=m(e)?e[0]:"X";return t?`${t}-${o}-${n}`:r?.pop()||pa(void 0,i)}function JF(t){const{cities:e,states:n,postalCodes:r,nationalityCode:i,participantIndex:o}=t;return{postalCode:r?.[o],state:n?.[o],city:e?.[o],countryCode:i}}var XF={lastNames:["Abbey","Ahern","Ampleforth","Ananiadis","Andelic","Assange","Atreides","Austen","Bach","Banks","Barrington","Batty","Bauers","Beals","Beer","Bennett","Berry","Bonaparte","Brewer","Brockovich","Bukowski","Cassidy","Catton","Calvino","Carlin","Carson","Chip","Constant","Crane","Crowne","Cummings","Curie","Dallas","Diamond","Deckard","Drazic","Dunbar","Earhart","Eisenstein","Eldritch","Elliot","Ellul","Escher","Eyre","Faulkner","Fulcher","Fukuoka","Godel","Goldstein","Greer","Hedges","Herbert","Holmgren","Humperdinck","Huxley","Illich","Jeffers","Jensen","Jevons","Johnson","Johnstone","Jovovich","Kingsnorth","Langer","Fernwright","Fuller","Le Guin","Lem","Lovelace","Mander","McLuhan","Midgely","Mond","Montoya","Moore","Murry","Nagle","Nearing","Ogden","Ophuls","Parks","Paz","Peet","Perfect","Pendejo","Pevensie","Postman","Ripley","Rodda","Rumfoord","Runciter","Rugen","Sale","Schumacher","Shaftoe","Shelley","Shepard","Smith","Stratton","Stewart","Swift","Tillich","Turing","Tyrell","Twain","Yeats","Veblen","Yates","Vonnegut","Waterhouse","Watson","Wolin","Wirt","Waschuk","Wormwood","Zecic"],firstFemale:["Ada","Amelia","Amelie","America","Anne","Antonia","Aravis","Astrid","Beatrice","Brienne","Buttercup","Caitlin","Cimorene","Cordelia","Desdemona","Ellen","Elizabeth","Emily","Emmie","Erin","Eva","Evelyn","Heather","Helen","Hermia","Hypatia","Imogen","Jane","Jasmine","Juliana","Juliet","Katniss","Leeloo","Lenina","Lilith","Linda","Lizzie","Louise","Lucy","Marie","Mary","Martha","Matilda","Milla","Miranda","Meg","Melba","Nicole","Ola","Portia","Pris","Rachael","Rachel","Rebecca","River","Rosa","Rosalind","Scout","Sharn","Susanne","Titania","Uhura","Ursula","Valentina","Viola","Virginia","Xena","Zoe"],firstMale:["Alan","Aldous","August","Axel","Barda","Barry","Bill","Bruce","Charles","Chris","Constantine","Darwin","David","Derrick","Edward","Emmanuel","Ernst","Estlin","Fezzik","Filby","Frank","Frito","George","Glen","Helmholtz","Inigo","Italo","Ivan","Jacques","James","Jared","Jerry","Joe","Johann","Julian","John Michael","Jonathan","Korben","Kirkpatrick","Kurt","Lief","Malachi","Mark","Marhsall","Masanobu","Maurits","Michael","Miro","Mustapha","Neil","Nikola","Octavio","Palmer","Paul","Pierre","Robinson","Rick","Rincewind","Roy","Shannon","Sheldon","Stafford","Stanislaw","Stanley","Syme","Thorstein","Thomas","Tyrone","Vizzini","Walton","Walker","Warren","Wendell","Westley","William","Winston","Zoran"]};function ZF(t){const{count:e=100,random:n,sex:r}=t??{};if(!e||r&&!Yi(r))return{personData:[],error:sr};const i=Math.ceil(1.3*e),{lastNames:o,firstFemale:a,firstMale:s}=XF,c=wm.map(({iso:t})=>t).filter(Boolean),u=Math.ceil(i/o.length),d=Math.ceil(i/a.length),p=Math.ceil(i/s.length),l=L(0,u).flatMap(()=>{const t=ca(o,!1,!0);return L(0,o.length).map(()=>x(t,n))}),m=L(0,d).flatMap(()=>{const t=ca(a,!1,!0);return L(0,a.length).map(()=>x(t,n))}),f=L(0,p).flatMap(()=>{const t=ca(s,!1,!0);return L(0,s.length).map(()=>x(t,n))}),h={};for(let t=0;t<i;t++){const t=l.pop(),e=r||_([Vi,_i],n),i=e===Vi?f.pop():m.pop(),o=_(c,n);h[`${i}${t}`]={nationalityCode:o,sex:e,firstName:i,lastName:t}}return{personData:Object.values(h).slice(0,e)}}function tx(t){let e=t?.count||1;const{personExtensions:n,consideredDate:r,isMock:i=!0,gendersCount:o,personData:a,random:s,category:c,sex:u}=t??{};if(Number.isNaN(Number(e)))return{error:sr};const d=o?.[Vi]||Wi(u)&&e||0,l=o?.[_i]||qi(u)&&e||0;e=Math.max(e,d+l);const m=e-(d+l),f=[...d&&ZF({count:d,sex:Vi,random:s}).personData||[],...l&&ZF({count:l,sex:_i,random:s}).personData||[],...m&&ZF({count:m,random:s}).personData||[]];let h=f.filter(t=>!u||d&&l||t.sex===u);const g=[];if(Array.isArray(a)){const t=a.filter(t=>"string"==typeof t.firstName&&("string"==typeof t.lastName&&(!(t.sex&&![Vi,_i].includes(t.sex))&&(!(t.nationalityCode&&("string"!=typeof t.nationalityCode||t.nationalityCode.length>3||!wm.some(({iso:e,ioc:n})=>[e,n].includes(t.nationalityCode))))&&(t.nationalityCode&&g.push(t.nationalityCode),!0)))));if(!t.length)return{error:sr};h=t}const I=a?h:A(h,s);if(I.length<e){const{maleFirstNames:t,maleLastNames:n,femaleFirstNames:r,femaleLastNames:i,nationalityCodes:o}=f.reduce((t,e)=>{const{firstName:n,lastName:r,nationalityCode:i}=e;return e.sex===Vi?(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:[]});L(0,e-I.length).forEach(()=>{const e=u||_([Vi,_i],s),a=_(o,s),c={firstName:_(e===Vi?t:r,s),lastName:_(e===Vi?n:i,s),sex:e,nationalityCode:a};I.push(c)})}const{ageMinDate:S,ageMaxDate:y}=Xo({consideredDate:r,category:c}),v=p(S?.slice(0,4)||0)||p(y?.slice(0,4)||0)-3,U=p(y?.slice(0,4)||0)||p(S?.slice(0,4)||0)+3,P=(S||y)&&[v,U],T=I.slice(0,e).map((t,e)=>{const[r,o]=P??[],a=P&&x(L(r,o),s),c=x(L(0,365),s),u=a&&function(t,e,n){const r=new Date(t,0);return bo(new Date(r.setDate(e)),n)}(a,c);return Object.assign(Ei({extensions:n||[{name:"regionCode",value:e+1}],birthDate:u,isMock:i}),t)});return{persons:T.length&&T||I[0],nationalityCodes:g}}var ex=["Ace Academy","Avengers","Ball Bouncers","Baseliners","Captivators","Civil Disobedients","Continentals","Court Royal","Court Sharks","Diamond Dogs","Danger Zone","Doubles Dominators","Double Faults","Tricksters","Eliminators","Court Crusaders","Fuzz Busters","Game Changers","Goal Gurus","Good Volley","Green Machine","Hawk Eyes","Inside Outers","Killer Instinct","Line Toers","Masters of Mayhem","Matter Catchers","Cheap Shot","Mean Machines","Mindspace Invaders","Net Centric","Net Positive","Smash Mullet","Over Your Head","Spin Meisters","Aggressors","Racket Machine","Slice Happy","Refs Nightmare","Sandeaters","Sun Seekers","Slicer Dicers","Stacked Deck","Cross Stringers","The Emergence","Total Demolition","Touch and Go","Unreturnables","Upside Downers","Vertically Challenged","Visual Spectacle"];function nx({nameRoot:t="TEAM",count:e=1,random:n}={}){const r=A(ex,n).slice(0,e);return r.length<e&&L(0,e-r.length).forEach(e=>r.push(`${t} ${e+1}`)),{names:r}}function rx(t){let{scaledParticipantsCount:e,rankingRange:n}=t;const{ratingsParameters:i=rp,valuesInstanceLimit:o,ratingsValues:a=[],consideredDate:s,categories:c,category:u,nationalityCodesCount:d,nationalityCodeType:p,nationalityCodes:l,participantsCount:m=32,participantType:h,teamSize:g=8,personIds:I,idPrefix:S,uuids:y,personExtensions:v,addressProps:U,gendersCount:T,matchUpType:w,personData:D,sex:R,participantRole:b,inContext:N,withISO2:M,withIOC:E,scaleAllParticipants:C,random:O}=t,k=b||sy,F=h===Sm||w===r,x=h===ym||w===ym;!n||Array.isArray(n)&&n.every(t=>P(t))&&2===n.length||(n=void 0),e=C?m:e;n=n||[1,e&&e>1e3?e:1e3],n[1]+=1;const _=m*((F?2:x&&(g??8))||1),B=tx({count:_,personExtensions:v,consideredDate:s,gendersCount:T,personData:D,category:u,random:O,sex:R});if(B.error)return B;const{nationalityCodes:V,persons:G}=B,j={},q={},W={},$={},H=t=>{Object.assign(j,t.doublesRankings),Object.assign(q,t.singlesRankings),Object.assign($,t.doublesRatings),Object.assign(W,t.singlesRatings)};if(f(u)){const t=ox({scaledParticipantsCount:e,ratingsParameters:i,participantType:h,ratingsValues:a,rankingRange:n,category:u,random:O});H(t)}Array.isArray(c)&&c.forEach(t=>{const r=ox({scaledParticipantsCount:e,ratingsParameters:i,participantType:h,ratingsValues:a,rankingRange:n,category:t,random:O});H(r)});const z=wm.filter(t=>"IOC"===p&&t.ioc||t.iso);const{postalCodesProfile:K,postalCodesCount:Q,statesProfile:J,citiesProfile:X,citiesCount:Z,statesCount:tt}=U??{},et=t=>Object.keys(t).flatMap(t=>L(0,J[t]).map(()=>t)),nt={cities:X&&et(X)||U?.cities||zF({count:Z||_,participantsCount:_}).cities,states:J&&et(J)||U?.states||YF({count:tt||_,participantsCount:_}).states,postalCodes:K&&et(K)||U?.postalCodes||KF({count:Q||_,participantsCount:_}).postalCodes},rt=function(t){const e=Math.ceil(_/t);return o&&e>o?Math.ceil(_/o):t}(d),it=rt?A(z,O).slice(0,d):l&&z.filter(t=>l.includes(t.iso))||z,ot=A(L(0,Math.ceil(_/(rt||1))).map(()=>it).flat(1/0),O),at=nx({count:m,random:O}).names,st=L(0,m).flatMap(t=>{const e=(F?2:x&&(g??8))||1,n=L(0,e).map(n=>function(t){const e=G[t],{nationalityCode:n,participantExtensions:r,participantTimeItems:i,extensions:o,firstName:a,birthDate:s,lastName:d,personId:l,sex:m}=e??{},f=a||"GivenName",h=d||"FamilyName",g=`${f} ${h}`,v=ot[t],U=V?.length&&n||v&&("IOC"===p?v.ioc||v.iso:v.iso||v.ioc)||n;!ot?.length||U||n||console.log("%c Invalid Nationality Code",{participantIndex:t,country:v});const P=JF({...nt,participantIndex:t,nationalityCode:U}),T=Ei({participantId:QF({participantType:gm,index:t,idPrefix:S,random:O,uuids:y}),extensions:r,timeItems:i,participantRole:k,participantType:gm,participantName:g,person:{personId:l||I?.length&&I[t]||pa(void 0,O),birthDate:Do(s)?s:void 0,addresses:[P],standardFamilyName:h,standardGivenName:f,nationalityCode:U,extensions:o,sex:m}});if(E&&U){const t=wm.find(({iso:t})=>t===U);t?.ioc&&(T.person.iocNationalityCode=t.ioc),t?.label&&(T.person.countryName=t.label)}if(M&&U){const t=wm.find(({iso:t})=>t===U);t?.iso2&&(T.person.iso2NationalityCode=t.iso2),t?.label&&(T.person.countryName=t.label)}const w=e=>{const n=e.categoryName||e.ratingType||e.ageCategoryCode,r=q[n]?.[t],i=j[n]?.[t];ix({scaleValue:r,eventType:es,scaleType:Iu,participant:T,category:e}),ix({scaleValue:i,eventType:rs,scaleType:Iu,participant:T,category:e});const o=W[n]?.[t],a=$[n]?.[t];ix({scaleValue:o,eventType:es,scaleType:Su,participant:T,category:e}),ix({scaleValue:a,eventType:rs,scaleType:Su,participant:T,category:e})};Array.isArray(c)?c.forEach(t=>w(t)):u&&w(u);return T}(t*e+n)),r=n.map(t=>t.participantId),i=n.map(t=>t.person.standardFamilyName).join("/"),o=F?Sm:ym,a={participantId:QF({participantType:o,index:t,idPrefix:S,random:O,uuids:y}),participantName:F?i:at[t],participantRole:k,individualParticipantIds:r,participantType:o};return N&&(a.individualParticipants=n),F||x?[a,...n]:n});return{participants:st,...Y}}function ix({scaleValue:t,participant:e,eventType:n,scaleType:r,category:i}){const o=i.categoryName||i.ratingType||i.ageCategoryCode,a={itemValue:t,itemType:[yu,r,n,o].join(".")};o&&t&&(e.timeItems??=[],e.timeItems.push(a))}function ox(t){const{category:e,scaledParticipantsCount:n,ratingsParameters:r,participantType:i,random:o,ratingsValues:a=[]}=t,s=e.rankingRange||t.rankingRange||[1,1e3],c={},u={},d={},p={},{categoryName:l,ageCategoryCode:m,ratingType:f}=e,h=e.categoryName||e.ratingType||e.ageCategoryCode;if((l||m)&&!f){const[t,e]=s??[];if(u[h]=A(L(t,e),o).slice(0,n||D(20,30,o)),[Sm,ym].includes(i)){const[t,e]=s??[];c[h]=A(L(t,e),o).slice(0,n||D(20,30,o))}}if(f&&r[f]){const{ratingMax:t,ratingMin:s,ratingAttributes:c}=e,u={...r[f],...c??{}},{attributes:l={},decimalsCount:m,accessors:g,range:I,step:S}=u,y=t=>{const e={},n=Object.keys(t??{});for(const r of n){const n=t[r];if("object"==typeof n&&n.generator){const{range:t}=n,[i,a]=t.slice().sort((t,e)=>t-e);e[r]=D(i,a,o)}else e[r]=n}return e},v=I[0]>I[1]?2:.7,[U,P]=I.slice().sort((t,e)=>t-e),T=(()=>L(0,2e3).map(()=>b(U,P,v,S,m,o)).filter(e=>(!t||e<=t)&&(!s||e>=s)).slice(0,n||D(20,30,o)).map(t=>g?Object.assign({},...g.map(e=>({[e]:t})),y(l)):t))();d[h]=[...a,...T],[Sm,ym].includes(i)&&(p[h]=[...a,...T])}return{singlesRankings:u,doublesRankings:c,singlesRatings:d,doublesRatings:p}}function ax(t){const{alternatesCount:e=0,tieFormatName:r,drawSize:o}=t;let a=0,s=0,c=0,u=0;const d={},p={[Vi]:0,[_i]:0,[Bi]:0,[Li]:0,[Gi]:0},l=f(t.tieFormat)?t.tieFormat:Za({namedFormat:r});l?.collectionDefinitions?.filter(Boolean).forEach(e=>{const{category:r,collectionId:o,matchUpType:l,matchUpCount:m,gender:f}=e;if(Yi(f)){const t=zi(f),e=m*(l===i?2:1);t&&p[t]<e&&(p[t]=e)}else $i(f)&&(p[Vi]<m&&(p[Vi]=m),p[_i]<m&&(p[_i]=m));if(r){const t=JSON.stringify(r);d[t]=r}if(o||(e.collectionId=pa(void 0,t.random)),bh(i)(l)){const t=m;u+=m,a=Math.max(a,t)}if(bh(n)(l)){const t=m;c+=m,s=Math.max(s,t)}});const m=Object.keys(d).length?Math.max(c,2*u):Math.max(s,2*a);return{maxDoublesDraw:a*(o+e),maxSinglesDraw:s*(o+e),teamSize:m,genders:p}}function sx({participantsProfile:t,tournamentRecord:e,eventProfiles:n,drawProfiles:r,startDate:i,random:o,uuids:a}){if(0===t?.participantsCount)return{addedCount:0,...Y};const{participantsCount:s,participantType:c,largestTeamDraw:u,largestTeamSize:d,gendersCount:p}=function({participantsProfile:t,eventProfiles:e,drawProfiles:n}){let{participantsCount:r,participantType:i=gm}=t??{};const o=r||0,a={[_i]:0,[Bi]:0,[Li]:0,[Vi]:0,[Gi]: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:o,category:l,gender:m,stage:f})=>{const h=i===ns,g=i===is,I=Boolean(e||f===ds||l||m&&m!==Gi);if(g){d=Math.max(d,r+t),o="object"==typeof o?o:Za({namedFormat:n});const{teamSize:e,maxDoublesDraw:i,maxSinglesDraw:p,genders:l}=ax({alternatesCount:t,tieFormatName:n,tieFormat:o,drawSize:r});u=Math.max(u,e),c=Math.max(c,p),I||(s=Math.max(s,i)),Object.keys(l).forEach(t=>a[t]+=l[t])}else if(h)if(I){const e=2*(r+t);p+=e,m&&(a[m]+=e)}else r+t&&r+t>s&&(s=r+t);else if(I){const e=r+t;m&&(a[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:o,gender:a}=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:o,gender:a})}}),Array.isArray(n))for(const t of n)l(t);const m=Math.max(d*u,2*s,c);return s&&(i=Sm),(r||o)<m&&(r=m),r&&s&&[Sm,is].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<o&&(r=o),{uniqueParticipantsCount:p,participantsCount:r,largestTeamDraw:d,largestTeamSize:u,participantType:i,gendersCount:a}}({participantsProfile:t,eventProfiles:n,drawProfiles:r}),l=t?.teamKey,m=rx({consideredDate:i,...t,participantsCount:s,participantType:c,gendersCount:p,random:o,uuids:a}).participants;let f=0,h=fC({tournamentRecord:e,participants:m});if(h.error)return h;if(f+=h.addedCount,l){const t=WF({tournamentRecord:e,...l});if(t.error)return t}const g=m.filter(({participantType:t})=>t===gm).map(Xp),I=t?.idPrefix?`${ym}-${t.idPrefix}`:void 0;return h=fC({participants:L(0,u).map(t=>{const e=g.slice(t*d,(t+1)*d),n=QF({index:t,participantType:c,idPrefix:I,random:o,uuids:a});return{participantName:`Team ${t+1}`,participantRole:sy,individualParticipantIds:e,participantType:ym,participantId:n}}),tournamentRecord:e}),h.error?h:(f+=h.addedCount,{addedCount:f,...Y})}function cx({drawProfiles:t,category:e,gender:n,useExistingParticipants:r=!1}){const i={},o=t?.reduce((t,o)=>{const{qualifyingPositions:a=0,participantsCount:s=0,uniqueParticipants:c,stage:u=us,drawSize:d=0}=o??{};Object.keys(t).includes(u)||(t[u]=0);const p=(s||d)-a;return!r&&(c||n&&n!==Gi||e||u===ds)?(Object.keys(i).includes(u)||(i[u]=0),i[u]+=p):t[u]=Math.max(t[u],p),t},{}),a=Object.keys(i);return a.forEach(t=>o[t]+=i[t]),{stageParticipantsCount:o,uniqueParticipantsCount:i,uniqueParticipantStages:a}}function ux({allUniqueParticipantIds:t,stageParticipantsCount:e,eventParticipantType:n,targetParticipants:r,gender:i}){const o=e[us]||0,a=e[ds]||0,s=function(t,e){if(!t||$i(t)||Hi(t))return()=>!0;const n=zi(t);return t=>{if(t.participantType===Sm){const r=t.individualParticipantIds??[];return r.length>0&&r.every(t=>zi(e.get(t)?.person?.sex)===n)}return t.participantType!==gm||zi(t.person?.sex)===n}}(i,new Map((r??[]).map(t=>[t.participantId,t]))),c=(r??[]).filter(({participantType:t})=>t===n).filter(({participantId:e})=>!t.includes(e)).filter(s);return{stageParticipants:{QUALIFYING:c.slice(0,a),MAIN:c.slice(a,a+o)}}}const dx={[Ep]:2,[wp]:1,[Tp]:1,[Np]:1,[Pp]:4},px=new Set([Np,Pp,Rp,Mp]),lx=new Set([wp,Tp]),mx=new Set(Object.keys(Vp));function fx({parsedFormat:t,winningSide:e,adjustSet:n,random:r,sets:i}){let o=i.reduce((t,e)=>t+(e.side1Score??0),0),a=i.reduce((t,e)=>t+(e.side2Score??0),0);const s=t?.setFormat?.outs?3*t.setFormat.outs:void 0;if(e){return(1===e&&o<=a||2===e&&a<=o)&&function({maxSetScore:t,side1Total:e,side2Total:n,winningSide:r,adjustSet:i,random:o,sets:a}){if(t){if(e!==n)for(const t of a)[t.side1Score,t.side2Score]=[t.side2Score,t.side1Score],t.winningSide&&(t.winningSide=1===t.winningSide?2:1);a.reduce((t,e)=>t+(e.side1Score??0),0)===a.reduce((t,e)=>t+(e.side2Score??0),0)&&Sx(a,r,1,t,i)}else{const t=Math.abs(e-n)+D(1,3,o);1===r?a[i].side1Score+=t:a[i].side2Score+=t}}({sets:i,winningSide:e,side1Total:o,side2Total:a,maxSetScore:s,adjustSet:n,random:r}),e}if(o===a){const t=D(1,2,r);return Sx(i,t,1,s,n),t}return o>a?1:2}function hx(t){const{winningSide:e,defaultWithScorePercent:n=2}=t,{matchUpStatusProfile:r=dx,matchUpFormat:i=va,pointsPerMinute:o=2.5,sideWeight:a=4,random:s}=t,c=Math.min(n,100),u=function({matchUpStatusProfile:t,defaultWithScorePercent:e,pointsPerMinute:n,sideWeight:r,matchUpFormat:i}){return Io({matchUpFormat:i})?"object"!=typeof t||Number.isNaN(Number(e))||Number.isNaN(Number(n))||Number.isNaN(Number(r))?{error:sr}:void 0:{error:de}}({defaultWithScorePercent:c,matchUpStatusProfile:r,pointsPerMinute:o,matchUpFormat:i,sideWeight:a});if(u?.error)return u;const d=function({matchUpStatusProfile:t,random:e}){const n=Object.keys(t).filter(t=>mx.has(t)&&t!==vp);if(Object.keys(n).reduce((e,n)=>e+t[n],0)>100)return{error:sr,matchUpStatusProfile:t};const r=n.reduce((e,n)=>(e.pointer=e.pointer+t[n],e.valueMap.push([e.pointer,n]),e),{pointer:0,valueMap:[]}),i=D(1,100,e);return{matchUpStatus:(r.valueMap.find(t=>i<=t[0])??[100,vp])[1]}}({matchUpStatusProfile:r,random:s});if(d.error)return d;const{matchUpStatus:p}=d,l=function({matchUpStatus:t,winningSide:e,defaultWithScorePercent:n,random:r}){const i={sets:[],scoreStringSide1:"",side2ScoreString:""};if(II(t)){const o={score:i,matchUpStatus:t,winningSide:e||D(1,2,r)};if(!(t===Pp&&D(1,100,r)>100-n))return{outcome:o}}else if(lx.has(t))return{outcome:{score:i,matchUpStatus:t}};return}({defaultWithScorePercent:c,winningSide:e,matchUpStatus:p,random:s});if(l)return l;return function({pointsPerMinute:t,matchUpFormat:e,matchUpStatus:n,winningSide:r,sideWeight:i,random:o}){const a=co(e),{bestOf:s=1,exactly:c,setFormat:u,finalSetFormat:d}=a??{},p=[],l=D(0,1,o),m=r?[r-1]:[...L(0,i).map(()=>l),1-l],f=px.has(n),h=f&&(x(L(1,c||s),o)||1);let g;const I=L(1,(c??s)+1);for(const r of I){const i=r===(c??s),{set:l,incomplete:f,winningSideNumber:I}=gx({setFormat:i&&d||u,incomplete:h===r,pointsPerMinute:t,matchUpStatus:n,weightedRange:m,setNumber:r,random:o});if(p.push(l),f){g=I;break}if(LE({matchUp:{score:{sets:p},matchUpFormat:e}}).calculatedWinningSide&&!a?.aggregate)break}const S=function({weightedWinningSide:t,matchUpFormat:e,parsedFormat:n,winningSide:r,random:i,sets:o}){if(t)return r||t;if(n?.aggregate&&o.length>0){return fx({parsedFormat:n,winningSide:r,adjustSet:D(0,o.length-1,i),random:i,sets:o})}const a=LE({matchUp:{score:{sets:o},matchUpFormat:e,winningSide:r}});return a.calculatedWinningSide}({weightedWinningSide:g,matchUpFormat:e,parsedFormat:a,winningSide:r,random:o,sets:p}),{score:y}=Bk({winningSide:S,score:{sets:p},matchUpStatus:n}),v={winningSide:S,matchUpStatus:n,score:y};return{outcome:v}}({pointsPerMinute:o,matchUpFormat:i,matchUpStatus:p,winningSide:II(p)?e||D(1,2,s):e,sideWeight:a,random:s})}function gx({weightedRange:t=[0,1],pointsPerMinute:e,matchUpStatus:n,incomplete:r,setFormat:i,setNumber:o,random:a}){const s={setNumber:o},{setTo:c,tiebreakFormat:u,tiebreakAt:d,tiebreakSet:p,timed:l,minutes:m,outs:f}=i,h=D(0,t.length-1,a),g=t[h];return l?function({pointsPerMinute:t,reverseScores:e,weightedRange:n,matchUpStatus:r,weightIndex:i,incomplete:o,minutes:a,random:s,set:c}){const u=a*t,d=Math.round(.2*u),p=u+x([1,-1],s)*d,l=function(t=1,e=3,n=!0,r){const i=r??Math.random;let o=0;for(let n=0;n<e;n++)o+=i()*(t/e);return n&&t>1?Math.round(o):o}(p,2,void 0,s),m=[l,p-l];e&&m.reverse();const f=n[i]+1;if(o){const[t,e]=m;return Object.assign(c,{side1Score:t,side2Score:e}),_p.includes(r)?{set:c,incomplete:o,winningSideNumber:f}:{set:c,incomplete:o}}m[0]>m[1]||m[1]>m[0]||(m[D(0,1,s)]+=1);(m[0]>m[1]?1:2)!==f&&m.reverse();const[h,g]=m;return Object.assign(c,{side1Score:h,side2Score:g,winningSide:f}),{set:c}}({set:s,minutes:m,pointsPerMinute:e,reverseScores:g,weightedRange:t,weightIndex:h,incomplete:r,matchUpStatus:n,random:a}):f?function({reverseScores:t,weightedRange:e,matchUpStatus:n,weightIndex:r,incomplete:i,random:o,outs:a,set:s}){const c=3*a,u=[D(0,c,o),D(0,c,o)],d=e[r]+1;t&&u.reverse();if(i){const[t,e]=u;return Object.assign(s,{side1Score:t,side2Score:e}),_p.includes(n)?{set:s,incomplete:i,winningSideNumber:d}:{set:s,incomplete:i}}const[p,l]=u;Object.assign(s,{side1Score:p,side2Score:l}),p!==l&&(s.winningSide=p>l?1:2);return{set:s}}({set:s,outs:f,reverseScores:g,weightedRange:t,weightIndex:h,incomplete:r,matchUpStatus:n,random:a}):r?function({matchUpStatus:t,weightedRange:e,tiebreakAt:n,weightIndex:r,random:i,set:o}){let a;o.side1Score=D(0,n,i),o.side2Score=D(0,n,i),_p.includes(t)&&(a=e[r]+1);return{set:o,incomplete:!0,winningSideNumber:a}}({set:s,tiebreakAt:d,weightedRange:t,weightIndex:h,matchUpStatus:n,random:a}):function({tiebreakFormat:t,reverseScores:e,weightedRange:n,weightIndex:r,tiebreakSet:i,tiebreakAt:o,setFormat:a,random:s,setTo:c,set:u}){const d=L(1,c+1).flatMap(t=>L(0,c+2-t).map(()=>t)),p=d[D(0,d.length-1,s)],l=c&&tN({isSide1:!0,tiebreakAt:o,lowValue:p,setTo:c}),m=!l,f=1===n.length&&n[r]+1;if(l){Ix({scores:l,specifiedWinningSide:f,reverseScores:e});const[t,n]=l;Object.assign(u,{side1Score:t,side2Score:n})}const h=iN({matchUpScoringFormat:{setFormat:a},setObject:u});let g;(h.hasTiebreakCondition||m)&&(g=function({specifiedWinningSide:t,tiebreakFormat:e,reverseScores:n,isTiebreakSet:r,tiebreakSet:i,setAnalysis:o,random:a,set:s}){const{NoAD:c,tiebreakTo:u}=e||(i??{}),d=L(1,u+1).flatMap(t=>L(0,u+2-t).map(()=>t)),p=d[D(0,d.length-1,a)],l=eN({isSide1:!0,tiebreakNoAd:c,tiebreakTo:u,lowValue:p});if(!l)return;if(r)return Ix({scores:l,specifiedWinningSide:t,reverseScores:n}),[s.side1TiebreakScore,s.side2TiebreakScore]=l,(l[0]>l[1]?1:l[1]>l[0]&&2)||void 0;2===o.leadingSide?[s.side1TiebreakScore,s.side2TiebreakScore]=l:[s.side2TiebreakScore,s.side1TiebreakScore]=l;return}({specifiedWinningSide:f,tiebreakFormat:t,reverseScores:e,isTiebreakSet:m,tiebreakSet:i,setAnalysis:h,random:s,set:u}));return u.winningSide=h.winningSide||h.leadingSide||f||g,{set:u}}({tiebreakFormat:u,reverseScores:g,weightedRange:t,weightIndex:h,tiebreakSet:p,tiebreakAt:d,setFormat:i,random:a,setTo:c,set:s})}function Ix({scores:t,specifiedWinningSide:e,reverseScores:n}){if(e){(t[0]>t[1]?1:2)!==e&&t.reverse()}else n&&t.reverse()}function Sx(t,e,n,r,i){const o=1===e?"side1Score":"side2Score",a=1===e?"side2Score":"side1Score";if(!r)return void(t[i][o]+=n);let s=n;for(let e=0;s>0&&e<t.length;e++){const n=(i+e)%t.length,r=t[n][a]??0;if(r>0){const e=Math.min(s,r);t[n][a]-=e,s-=e}}for(let e=0;s>0&&e<t.length;e++){const n=(i+e)%t.length,a=r-(t[n][o]??0);if(a>0){const e=Math.min(s,a);t[n][o]+=e,s-=e}}}function yx({firstRoundDualMatchUps:t,event:e,tournamentRecord:r,drawDefinition:o}){const s=e?.category?.ageCategoryCode||e?.category?.categoryName;if(s){const t=SO({singlesOnly:!0,tournamentRecord:r,drawDefinition:o,scaleAccessor:{scaleName:s,sortOrder:"ASC",scaleType:Iu},event:e});if(t.error)return t;const{lineUps:n,participantsToAdd:i}=t;return fC({tournamentRecord:r,participants:i}),void sp({element:o,attribute:"lineUps",name:fd,value:n})}const c=t[0]?.structureId,{positionAssignments:u}=cl({drawDefinition:o,structureId:c});if(!u?.length)return;const{participants:d}=xS({participantFilters:{participantTypes:[a]},tournamentRecord:r});function p(t){return d?.find(e=>{const{participantId:n}=e,r=u.find(t=>t.participantId===n);return r?.drawPosition===t})}t.forEach(t=>{const a=t.tieMatchUps.filter(bh(n)),s=t.tieMatchUps.filter(bh(i));a.forEach((t,n)=>{!function(t,n,i){t.sides.forEach(t=>{const{drawPosition:a}=t,s=p(a);if(s){const t=s.individualParticipantIds?.[n];return void(t&&VO({teamParticipantId:s.participantId,participantId:t,tournamentRecord:r,drawDefinition:o,tieMatchUpId:i,event:e}))}})}(t,n,t.matchUpId)}),s.forEach((t,n)=>{!function(t,n,i){t.sides.forEach(t=>{const{drawPosition:a}=t,s=p(a);if(s){const t=s.individualParticipantIds?.slice(2*n,2*n+2);t?.forEach(t=>{VO({teamParticipantId:s.participantId,participantId:t,tournamentRecord:r,drawDefinition:o,tieMatchUpId:i,event:e})})}})}(t,n,t.matchUpId)})})}function vx({structure:t,matchUpsMap:e,drawDefinition:r,tournamentRecord:o,event:a,matchUpStatusProfile:s,matchUpFormat:c,matchUpStatus:u,scoreString:d,randomWinningSide:p,completionGoal:l,completedCount:m,roundNumber:f,random:h}){const g=Fg({contextFilters:{matchUpTypes:[i,n]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:r,matchUpsMap:e,structure:t,event:a}).matchUps.filter(({winningSide:t,roundNumber:e})=>!(t||f&&e!==f)).sort(Xg).map(tl);for(const f of g){if(!Number.isNaN(Number(l))&&m.value>=l)break;const{matchUps:g}=Fg({matchUpFilters:{matchUpTypes:[i,n]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:r,matchUpsMap:e,structure:t,event:a}),I=g.find(t=>t.matchUpId===f),S=[wp,Tp].includes(I.matchUpStatus);if(I?.readyToScore&&!S){const t=Tx({matchUpStatusProfile:s,tournamentRecord:o,drawDefinition:r,targetMatchUp:I,matchUpFormat:c,matchUpStatus:u,scoreString:d,winningSide:!p&&1,random:h,event:a});if(t?.error)return t;m.value+=1}}}function Ux(t){const{matchUpStatusProfile:e,completeAllMatchUps:n,randomWinningSide:r,tournamentRecord:i,completionGoal:o,drawDefinition:s,roundNumber:c,stageSequence:u,random:d,stage:p,event:l}=t;if(!s)return{error:st};const m=t.matchUpFormat||s.matchUpFormat||l?.matchUpFormat,f=s.structures.slice().sort(rl),h={value:0},{matchUps:g}=zg({matchUpFilters:{matchUpTypes:[a],roundNumbers:[1]},contextFilters:{stages:[us,ds]},inContext:!0,drawDefinition:s});if(g?.length){const t=yx({firstRoundDualMatchUps:g,event:l,tournamentRecord:i,drawDefinition:s});if(t?.error)return t}const I="string"==typeof n&&n,S=I&&vp,y=2===f.length&&f[0].finishingPosition===pc&&2===V(f.map(({stage:t})=>t),[us,ms]).length,v=f.map(({structureId:t})=>t);let U=0,P=-1;for(;h.value>P&&(void 0===o||h.value<o)&&U<10;){U++,P=h.value;const{matchUpsMap:n}=zg({matchUpFilters:{matchUpTypes:[a],roundNumbers:[1]},contextFilters:{stages:[us,ds]},inContext:!0,drawDefinition:s});for(const a of v){if(h.value>=o)break;const f=s.structures.find(t=>t.structureId===a);if(p&&f.stage!==p)continue;if(u&&f.stageSequence!==u)continue;const g=vx({structure:f,matchUpsMap:n,drawDefinition:s,tournamentRecord:i,event:l,matchUpStatusProfile:e,matchUpFormat:m,matchUpStatus:S,scoreString:I,randomWinningSide:r,completionGoal:o,completedCount:h,roundNumber:c,random:d});if(g?.error)return g;y&&f.finishingPosition===pc&&t.completeRoundRobinPlayoffs&&XU({structureId:f.structureId,applyPositioning:!0,drawDefinition:s})}}return{...Y,completedCount:h.value}}function Px(t){const{matchUpStatusCodes:e,policyDefinitions:n,tournamentRecord:r,drawDefinition:i,targetMatchUp:o,matchUpStatus:a,matchUpFormat:s,scoreString:c,winningSide:u,event:d}=t;if(!o||o.matchUpStatus===Sp)return;const{matchUpId:p}=o??{},{outcome:l}=nF({matchUpFormat:s,matchUpStatus:a,scoreString:c,winningSide:u});return e&&(l.matchUpStatusCodes=e),Gk({tournamentRecord:r,policyDefinitions:n,drawDefinition:i,matchUpFormat:s,matchUpId:p,outcome:l,event:d})}function Tx(t){const{matchUpStatusProfile:e={},tournamentRecord:n,policyDefinitions:r,drawDefinition:i,matchUpStatus:o,matchUpFormat:a,targetMatchUp:s,scoreString:c,winningSide:u,random:d,event:p}=t,l=s?.matchUpFormat||a;if(c||o)return Px({...t,matchUpFormat:l});const{matchUpId:m}=s??{},f=hx({matchUpStatusProfile:e,matchUpFormat:l,winningSide:u,random:d}),{outcome:h}=f;return Gk({policyDefinitions:r,tournamentRecord:n,drawDefinition:i,matchUpFormat:l,matchUpId:m,outcome:h,event:p})}function wx({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:n,tournamentRecord:r,drawProfiles:i,random:o,isMock:a,event:s}){const c=Tg({event:s}).flightProfile,{eventName:u,eventType:d,category:p}=s,{startDate:l}=r,m=[],f=p?.categoryName||p?.ageCategoryCode||p?.ratingType,h=s.drawDefinitions?.map(({drawId:t})=>t),g=new Set(h??[]);if(!Array.isArray(c?.flights))return{...Y,drawIds:m};for(const[p,h]of c.flights.entries()){const{drawId:c,stage:I,drawName:S,drawEntries:y}=h;m.push(h.drawId);const v=i[p],{seedsCount:U,generate:P=!0}=v??{};if(!P)continue;const T=f||u;if(Dx({drawParticipantIds:y.filter(eI(Pc)).map(eI(Pc)),seedingScaleName:T,tournamentRecord:r,seedsCount:U,startDate:l,eventType:d}),g.has(c))break;const w=Rx({drawProfile:i[p],seedingScaleName:T,tournamentRecord:r,drawEntries:y,eventType:d,drawName:S,drawId:c,isMock:a,random:o,event:s,stage:I});if(w.error)return{error:w.error,drawIds:[]};const{drawDefinition:D}=w,R=!1===i[p]?.automated,b=i[p]?.completionGoal;if(!R&&(e||b)){const a=bx({matchUpFormat:i[p]?.matchUpFormat,drawType:i[p]?.drawType,matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:n,tournamentRecord:r,drawDefinition:D,completionGoal:b,random:o,event:s});if(a?.error)return{error:a.error,drawIds:[]}}}return{...Y,drawIds:m}}function Dx({drawParticipantIds:t,seedingScaleName:e,tournamentRecord:n,seedsCount:r,startDate:i,eventType:o}){if(!n||!r||r>t.length)return;L(1,r+1).forEach((r,a)=>{const s={scaleValue:r,scaleName:e,scaleType:vu,eventType:o,scaleDate:i},c=t[a];_D({tournamentRecord:n,participantId:c,scaleItem:s})})}function Rx({seedingScaleName:t,tournamentRecord:e,drawProfile:n,drawEntries:r,eventType:i,drawName:o,drawId:a,isMock:s,random:c,event:u,stage:d}){let p=JE({...n,matchUpType:i,seedingScaleName:t,tournamentRecord:e,drawEntries:r,drawName:o,drawId:a,isMock:s,random:c,event:u,stage:d});if(p.error)return{error:p.error};const{drawDefinition:l}=p;if(!l)return{error:ut};const m=n?.drawExtensions;return Array.isArray(m)&&m.filter(Wu).forEach(t=>$u({element:l,extension:t})),p=QC({suppressNotifications:!0,tournamentRecord:e,drawDefinition:l,event:u}),p.error?{error:p.error}:{drawDefinition:l}}function bx({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:n,tournamentRecord:r,drawDefinition:i,completionGoal:o,matchUpFormat:a,drawType:s,random:c,event:u}){const d=Ux({completeAllMatchUps:!o&&e,matchUpStatusProfile:t,randomWinningSide:n,tournamentRecord:r,completionGoal:o,drawDefinition:i,matchUpFormat:a,random:c,event:u});if(d.error)return d;if(s!==oc)return;const p=i.structures?.find(t=>t.stage===us);if(!p)return{error:Vt};const l=XU({structureId:p.structureId,tournamentRecord:r,drawDefinition:i});if(l.error)return l;const m=d.completedCount,f=Ux({completeAllMatchUps:!o&&e,completionGoal:o?o?o-(m??0):void 0:void 0,matchUpStatusProfile:t,randomWinningSide:n,tournamentRecord:r,drawDefinition:i,matchUpFormat:a,random:c,event:u});return f.error?f:void 0}function Nx(t){const e=t.filter(t=>t.participantType===Sm),n=t.filter(t=>t.participantType===gm),r=n.filter(t=>t.person?.sex===Vi),i=n.filter(t=>t.person?.sex===_i);for(let t=0;t<e.length;t++){const n=r[t],o=i[t];if(!n||!o)continue;const a=e[t];a.individualParticipantIds=[n.participantId,o.participantId];const s=n.person?.standardFamilyName??"",c=o.person?.standardFamilyName??"";a.participantName=`${s}/${c}`}}function Mx(t){const{participantsProfile:e={},uniqueParticipantsCount:n,ratingsParameters:r,tournamentRecord:i,eventProfile:o,eventIndex:a,event:s,uuids:c}=t,{category:u,gender:d,eventType:p}=s,l=bh(ts)(p)&&gm||bh(ns)(p)&&Sm||p,m=n[us]||0,f=n[ds]||0,h=o.drawProfiles?.length?m+f:o.participantsProfile?.participantsCount??0,g=Yi(d)?d:void 0,I=l===Sm&&d===Bi,S=I?{[Vi]:h,[_i]:h}:void 0,y=e?.idPrefix?`E-${a}-${e?.idPrefix}`:void 0,{participants:v}=rx({uuids:o.uuids||c,...e,scaledParticipantsCount:o.scaledParticipantsCount,consideredDate:i?.startDate,rankingRange:o.rankingRange,participantType:l,participantsCount:h,ratingsParameters:r,gendersCount:S,category:u,idPrefix:y,sex:g}),U=v;I&&Nx(U);const P=fC({tournamentRecord:i,participants:U});if(P.error)return P;const T=v?.filter(({participantType:t})=>t===l),w=v?.map(Xp);return{uniqueDrawParticipants:T,uniqueParticipantIds:w}}function Ax({autoEntryPositions:t,tournamentRecord:e,drawParticipants:n,drawProfile:r,event:i}){const{drawType:o=Ls,qualifyingPositions:a=0,stage:s=us,drawSize:c=0,drawName:u,drawId:d}=r,p=c-a,l=n.slice(0,p).map(Xp);if(l.length){const n=oy({participantIds:l,autoEntryPositions:t,entryStage:s,tournamentRecord:e,event:i});if(n.error)return n}const m=oO({drawName:u||o,qualifyingPositions:a,drawEntries:l.map(t=>({entryStatus:rf,entryStage:s,participantId:t})),drawId:d,event:i,stage:s});return m.error?m:{...Y}}function Ex({uniqueDrawParticipants:t,useExistingParticipants:e=!1,autoEntryPositions:n,stageParticipants:r,tournamentRecord:i,drawProfiles:o,category:a,gender:s,event:c}){let u=0;for(const d of o){const{qualifyingPositions:o=0,uniqueParticipants:p,stage:l=us,drawSize:m=0}=d,f=m-o,h=!e&&(p||s&&s!==Gi||a||l===ds),g=h?t.slice(u,u+f):r[l||us]??[];h&&(u+=f);const I=Ax({autoEntryPositions:n,drawParticipants:g,tournamentRecord:i,drawProfile:d,event:c});if(I.error)return I}return{...Y}}function Cx(t){const{allUniqueParticipantIds:e,useExistingParticipants:n,matchUpStatusProfile:r,participantsProfile:i,completeAllMatchUps:o,autoEntryPositions:a,hydrateCollections:s,randomWinningSide:c,ratingsParameters:u,tournamentRecord:d,eventProfile:p,eventIndex:l,publish:m,random:f,isMock:h,uuids:g}=t;let I=p.gender,S=p.eventName;const{eventType:y=ts,policyDefinitions:v,drawProfiles:U=[],eventExtensions:P,surfaceCategory:T,tieFormatName:w,processCodes:D,discipline:R,eventLevel:b,timeItems:N,ballType:M,category:A}=p,E=p.eventId||pa(void 0,f),C=p.tieFormat||(y===is?Za({namedFormat:w,event:{eventId:E,category:A,gender:I},hydrateCollections:s,isMock:h}):void 0),O=d.participants;for(const t of U)!I&&t.gender&&(I=t?.gender);const{stageParticipantsCount:k,uniqueParticipantsCount:F,uniqueParticipantStages:x}=cx({drawProfiles:U,category:A,gender:I,useExistingParticipants:n}),_=bh(ts)(y)&&gm||bh(ns)(y)&&Sm||y,{uniqueDrawParticipants:L=[],uniqueParticipantIds:B=[]}=x?Mx({event:{eventType:y,category:A,gender:I},uniqueParticipantsCount:F,participantsProfile:i,ratingsParameters:u,tournamentRecord:d,eventProfile:p,eventIndex:l,uuids:g}):{},V=A?.categoryName||A?.ageCategoryCode||A?.ratingType;S=S||V||"Generated Event";const G=function({eventProfile:t,surfaceCategory:e,processCodes:n,discipline:r,eventLevel:i,eventExtensions:o,policyDefinitions:a,timeItems:s,eventName:c,eventType:u,tieFormat:d,ballType:p,category:l,eventId:m,gender:f,categoryName:h}){let{eventAttributes:g}=t;"object"!=typeof g&&(g={});const I={...g,surfaceCategory:e,processCodes:n,discipline:r,eventLevel:i,eventName:c,eventType:u,tieFormat:d,ballType:p,category:l,eventId:m,gender:f};if(o?.length&&Array.isArray(o)){const t=o.filter(Wu);t?.length&&Object.assign(I,{extensions:t})}Array.isArray(s)&&s.forEach(t=>oU({event:I,timeItem:t}));if("object"==typeof a)for(const t of Object.keys(a))RT({policyDefinitions:{[t]:a[t]},event:I});I.category&&(I.category.categoryName=h);return I}({eventProfile:p,surfaceCategory:T,processCodes:D,discipline:R,eventLevel:b,eventExtensions:P,policyDefinitions:v,timeItems:N,eventName:S,eventType:y,tieFormat:C,ballType:M,category:A,eventId:E,gender:I,categoryName:V});let j;const q=yC({suppressNotifications:!1,internalUse:!0,tournamentRecord:d,event:G});if(q.error)return q;const W=q?.event,{stageParticipants:$}=ux({allUniqueParticipantIds:e,stageParticipantsCount:k,eventParticipantType:_,targetParticipants:O,gender:I});if(U?.length){const t=Ex({uniqueDrawParticipants:L,useExistingParticipants:n,autoEntryPositions:a,stageParticipants:$,tournamentRecord:d,drawProfiles:U,category:A,gender:I,event:W});if(t.error)return t;const e=wx({matchUpStatusProfile:r,completeAllMatchUps:o,randomWinningSide:c,tournamentRecord:d,drawProfiles:U,random:f,isMock:h,event:W});if(e.error)return e;j=e.drawIds}else if(p?.participantsProfile?.participantsCount){const t=L.map(Xp);if(t.length){const e=oy({participantIds:t,autoEntryPositions:a,tournamentRecord:d,entryStage:us,event:W});if(e.error)return e}}m&&TC({tournamentRecord:d,event:W});const H=n?[...$.MAIN??[],...$.QUALIFYING??[]].map(t=>t.participantId):[];return{drawIds:j,eventId:E,uniqueParticipantIds:[...new Set([...B,...H])]}}function Ox({tournamentRecords:t,scheduleDate:e,venueId:n,round:r}){if(!Do(e))return{error:_e};const i=Object.values(t??{}).map(t=>Km({element:t,groupAttribute:"scheduling",leafAttribute:"profile",name:wd})).find(t=>void 0!==t)??[];let o=i.find(t=>Ko(e,t.scheduleDate));if(!o){const{startDate:n,endDate:r}=yM({tournamentRecords:t}),a=new Date(e);if(n&&a<new Date(n)||r&&a>new Date(r))return{error:_e};o={scheduleDate:e,venues:[]},i.push(o)}let a=o.venues.find(t=>t.venueId===n);a||(a={venueId:n,rounds:[]},o.venues.push(a));const s=["notBeforeTime"],c=t=>Object.keys(t).filter(t=>!s.includes(t)).sort().map(e=>f(t[e])?c(t[e]):t[e]).flat().join("|");if(a.rounds.find(t=>c(t)===c(r)))return Ci({result:{error:Lt},stack:"addSchedulingProfileRound"});a.rounds.push(r);const u=zA({tournamentRecords:t,schedulingProfile:i});return u.error?u:{...Y}}function kx({qualifyingParticipantsCount:t,participantsProfile:e,drawParticipantsCount:n,ratingsParameters:r,tournamentRecord:i,drawProfileCopy:o,participantType:a,categoryName:s,drawProfile:c,buildTeams:u,eventType:d,drawSize:p,isHybrid:l,drawIndex:m,category:f,gender:h,random:g,event:I,uuids:S}){let y=n;const v={[Vi]:0,[_i]:0};let U,P;const T=d===ns&&h===Bi;if(T&&(v[Vi]=n,v[_i]=n),l){const t=Math.floor(n/2);y=n-t+2*t}if(d===ym){({teamSize:U,genders:P}=ax({tieFormatName:o.tieFormatName,tieFormat:o.tieFormat,alternatesCount:o.alternatesCount||0,drawSize:p,random:g}));const e=o.teamGenders;if(e){for(const t of Object.keys(e))void 0!==P[t]&&e[t]>P[t]&&(P[t]=e[t]);const t=(P[Vi]||0)+(P[_i]||0);t>U&&(U=t)}Object.keys(P).forEach(t=>{const e=zi(t);e&&Yi(t)&&P[e]&&(v[e]=p*P[e])}),y=U*((p||0)+t)}const w=e?.idPrefix?`D-${m}-${e?.idPrefix}`:void 0,D=rx({...e,scaledParticipantsCount:c.scaledParticipantsCount||e.scaledParticipantsCount,participantsCount:y,consideredDate:i?.startDate,sex:h||e?.sex,rankingRange:c.rankingRange,uuids:c.uuids||S,ratingsParameters:r,participantType:a,gendersCount:v,idPrefix:w,category:f,random:g}).participants;if(I.category&&(I.category.categoryName=s),T&&Nx(D),i){const t=fC({participants:D,tournamentRecord:i});if(t.error)return t}const R=[];D.forEach(({participantId:t})=>R.push(t));let b=D;if(d===ym){const t=function({drawParticipantsCount:t,tournamentRecord:e,drawProfileCopy:n,buildTeams:r,genders:i,teamSize:o,unique:a,random:s}){const c=i[Vi]?a.filter(({participantType:t,person:e})=>t===gm&&e?.sex===Vi).map(Xp):[],u=i[_i]?a.filter(({participantType:t,person:e})=>t===gm&&qi(e?.sex)).map(Xp):[],d=new Set(c),p=new Set(u),l=a.filter(({participantType:t})=>t===gm).map(Xp).filter(t=>!d.has(t)&&!p.has(t)),m=[...n.teamNames??[],...nx({count:t,random:s}).names],f=o-(i[Vi]+i[_i]);let h=0,g=0,I=0;const S=L(0,t).map(t=>{const e=u.slice(h,h+i[_i]),n=c.slice(g,g+i[Vi]),o=l.slice(I,I+f);h+=i[_i],g+=i[Vi],I+=f;const d=!1!==r?[...e,...n,...o]:[],p=m[t]||`Team ${t+1}`,S=pa(void 0,s);if(!1!==r){let t=1;for(const e of d){const n=a.find(t=>t.participantId===e);n?.person&&(n.person.biographicalInformation||(n.person.biographicalInformation={}),n.person.biographicalInformation.teamAttributes||(n.person.biographicalInformation.teamAttributes=[]),n.person.biographicalInformation.teamAttributes.push({jerseyName:n.person.standardFamilyName?.toUpperCase(),jerseyNumber:String(t),teamName:p,teamId:S}),t+=1)}}return{participantOtherName:`TM${t+1}`,participantName:p,participantId:S,participantRole:sy,individualParticipantIds:d,participantType:ym,useOtherName:!1}}),y=fC({participants:S,tournamentRecord:e});return y.success?{teamParticipants:S}:y}({drawParticipantsCount:n,tournamentRecord:i,drawProfileCopy:o,buildTeams:u,genders:P,teamSize:U,unique:D,random:g});if(t.error)return t;b=t.teamParticipants}if(l){const t=function({drawParticipantsCount:t,tournamentRecord:e,unique:n,random:r}){const i=n.filter(({participantType:t})=>t===gm),o=t-Math.floor(t/2),a=i.slice(o),s=[];for(let t=0;t+1<a.length;t+=2){const e=a[t],n=a[t+1];s.push({participantName:`${e.person?.standardGivenName??"A"} / ${n.person?.standardGivenName??"B"}`,individualParticipantIds:[e.participantId,n.participantId],participantRole:sy,participantType:Sm,participantId:pa(void 0,r)})}if(s.length&&e){const t=fC({participants:s,tournamentRecord:e});if(!t.success)return t}return{targetParticipants:[...i.slice(0,o),...s]}}({drawParticipantsCount:n,tournamentRecord:i,unique:D,random:g});if(t.error)return t;b=t.targetParticipants}return{uniqueParticipantIds:R,targetParticipants:b}}function Fx({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:n,tournamentRecord:r,drawDefinition:i,completionGoal:o,matchUpFormat:a,drawProfile:s,drawType:c,random:u,event:d}){const p=s=>{const p=Ux({completeAllMatchUps:s.completeAllMatchUps,completionGoal:s.completionGoal,matchUpStatusProfile:t,randomWinningSide:n,tournamentRecord:r,drawDefinition:i,matchUpFormat:a,random:u,event:d});if(p.error)return p;if(c===oc){const s=function({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:n,tournamentRecord:r,drawDefinition:i,completedCount:o,completionGoal:a,matchUpFormat:s,random:c,event:u}){const d=i.structures?.find(t=>t.stage===us);if(!d)return{error:Vt};XU({structureId:d.structureId,tournamentRecord:r,drawDefinition:i});const p=a?a-(o??0):void 0,l=Ux({completionGoal:a?p:void 0,matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:n,tournamentRecord:r,drawDefinition:i,matchUpFormat:s,random:c,event:u});return l.error?l:void 0}({completedCount:p.completedCount,matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:n,tournamentRecord:r,drawDefinition:i,completionGoal:o,matchUpFormat:a,random:u,event:d});if(s?.error)return s}};if(o&&p({completionGoal:o}),s.outcomes){const t=function({tournamentRecord:t,drawDefinition:e,outcomes:n,event:r}){const{matchUps:i}=Zg({inContext:!0,drawDefinition:e,event:r}),o=function(t){const e=t?.reduce((t,e)=>{const{structureId:n,matchUpId:r}=e;return t[n]?t[n].push(r):t[n]=[r],t},{})??[];return Object.assign({},...Object.keys(e).map((t,e)=>({[t]:e+1})))}(i);for(const r of n){const{matchUpStatus:n=vp,matchUpStatusCodes:a,stageSequence:s=1,matchUpIndex:c=0,structureOrder:u,matchUpFormat:d,drawPositions:p,roundPosition:l,stage:m=us,roundNumber:f,winningSide:h,scoreString:g}=r,I=i?.filter(t=>!(m&&t.stage!==m||s&&t.stageSequence!==s||f&&t.roundNumber!==f||l&&t.roundPosition!==l||u&&o[t.structureId]!==u||p&&2!==V(p,t.drawPositions).length)),S=I?.[c],y=Px({matchUpStatusCodes:a,tournamentRecord:t,drawDefinition:e,targetMatchUp:S,matchUpFormat:d,matchUpStatus:n,scoreString:g,winningSide:h});if(y?.error)return y}return}({outcomes:s.outcomes,tournamentRecord:r,drawDefinition:i,event:d});if(t?.error)return t}return e&&p({completeAllMatchUps:e}),{goComplete:p}}function xx({qualifyingParticipantsCount:t,consideredParticipants:e,isEventParticipantType:n,excessParticipantAlternates:r,tournamentAlternates:i,autoEntryPositions:o,qualifyingProfiles:a,participantsCount:s,alternatesCount:c,tournamentRecord:u,participantIds:d,isEventGender:p,drawSize:l,isMock:m,event:f,stage:h}){if(m&&d?.length){const t=oy({autoEntryPositions:o,entryStage:h,tournamentRecord:u,participantIds:d,event:f});if(t.error)return t}const g=t?e.slice(s,s+t).map(t=>t.participantId):0;if(m&&g?.length){const t=function({qualifyingParticipantIds:t,autoEntryPositions:e,qualifyingProfiles:n,tournamentRecord:r,event:i}){let o=0,a=1;const s=(t,e)=>t.stageSequence-e.stageSequence,c=(t,e)=>t.roundTarget-e.roundTarget;for(const u of n.sort(c)){a=u.roundTarget||a;let n,c=1;for(const d of u.structureProfiles.sort(s)){const s=(d.drawSize||v(d.participantsCount))-(n||0),u=t.slice(o,o+s),p=oy({entryStage:ds,entryStageSequence:c,autoEntryPositions:e,tournamentRecord:r,participantIds:u,roundTarget:a,event:i});if(p.error)return p;n=d.qualifyingPositions,o+=s,c+=1}a+=1}}({qualifyingParticipantIds:g,autoEntryPositions:o,qualifyingProfiles:a,tournamentRecord:u,event:f});if(t?.error)return t}const I=new Set(d),S=r&&u?.participants?.filter(({participantId:t})=>!I.has(t)).filter(n).filter(p).slice(0,c||l-s||i).map(t=>t.participantId);if(m&&S?.length){const t=oy({participantIds:S,autoEntryPositions:!1,entryStatus:ef,tournamentRecord:u,event:f});if(t.error)return t.error}}function _x({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:n,tournamentRecord:r,drawProfileCopy:i,seedingScaleName:o,drawExtensions:a,iterativeAdHoc:s,completionGoal:c,matchUpFormat:u,drawProfile:d,drawType:p,category:l,generate:m,drawName:f,isMock:h,random:g,eventId:I,publish:S,event:y,qualifyingPositions:v,stage:U}){const P=JE({...s?{...ca(d,!1,!0),roundsCount:1}:ca(d,!1,!0),tournamentRecord:r,seedingScaleName:o,matchUpFormat:u,eventId:I,isMock:h,random:g,event:y});if(P.error)return P;if(!P.drawDefinition)return{error:ut};const{drawDefinition:T}=P,w=T.drawId;if(Array.isArray(a)&&a.filter(Wu).forEach(t=>$u({element:T,extension:t})),m){QC({drawDefinition:T,event:y,suppressNotifications:!0});const o=!1===d.automated;if(h&&!o){const o=Fx({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:n,tournamentRecord:r,drawDefinition:T,completionGoal:c,matchUpFormat:u,drawProfile:d,drawType:p,random:g,event:y});if(o?.error)return o;if(s){const t=function({tournamentRecord:t,drawDefinition:e,drawProfileCopy:n,drawProfile:r,goComplete:i,category:o,isMock:a,event:s}){const c=n.roundsCount,u=r.drawMatic?.scaleName??r.scaleName??o?.ratingType;for(let n=2;n<=c;n++){const n=xN({eventType:r.drawMatic?.eventType??r.matchUpType,updateParticipantRatings:!!u,dynamicRatings:!!u,generateMatchUps:!0,tournamentRecord:t,drawDefinition:e,roundsCount:1,scaleName:u,isMock:a,event:s});if(n.error)return n;if(n.matchUps?.length){const r=$T({matchUps:n.matchUps,suppressNotifications:!0,tournamentRecord:t,drawDefinition:e,event:s});if(r.error)return r}const o=i({completeAllMatchUps:!0});if(o?.error)return o}}({goComplete:o.goComplete,tournamentRecord:r,drawDefinition:T,drawProfileCopy:i,drawProfile:d,category:l,isMock:h,event:y});if(t?.error)return t}}S&&TC({tournamentRecord:r,event:y})}else{const t=oO({drawEntries:T.entries,drawName:f||p,qualifyingPositions:v,drawId:w,event:y,stage:U});if(t.error)return t}return{drawDefinition:T,drawId:w}}function Lx(t){const e=fu(t,[{drawProfile:!0,_ofType:ru}]);if(e.error)return e;const{allUniqueParticipantIds:n=[],useExistingParticipants:r,participantsProfile:i={},matchUpStatusProfile:o,completeAllMatchUps:a,autoEntryPositions:s,hydrateCollections:c,randomWinningSide:u,ratingsParameters:d,tournamentRecord:p,isMock:l=!0,drawProfile:m,startDate:h,drawIndex:g,random:I,uuids:S}=t,y=ca(m,!1,!0),{excessParticipantAlternates:v=!0,matchUpFormat:U=va,drawType:P=Ls,tournamentAlternates:T=0,alternatesCount:w=0,qualifyingPositions:D,qualifyingProfiles:R,generate:b=!0,eventExtensions:N,drawExtensions:M,completionGoal:A,tieFormatName:E,buildTeams:C,seedsCount:O,timeItems:k,drawName:F,category:x,publish:_,gender:B,stage:V}=y,G=y.drawSize||(y.ignoreDefaults?void 0:32),j=y.eventId||pa(void 0,I),q=m.eventType||m.matchUpType||ts,W=q===as,$=q===ns?Sm:gm,H=function({drawProfile:t,tournamentRecord:e,eventId:n,eventType:r,category:i,gender:o,tieFormatName:a,hydrateCollections:s,isMock:c}){if(f(t.tieFormat))return t.tieFormat;if(t.tieFormatId){const r=e?.events?.find(t=>t.eventId===n)?.tieFormats?.find(e=>e.tieFormatId===t.tieFormatId);if(r)return r}if(r===ym)return Za({event:{eventId:n,category:i,gender:o},namedFormat:a,hydrateCollections:s,isMock:c});return}({drawProfile:m,tournamentRecord:p,eventId:j,eventType:q,category:x,gender:B,tieFormatName:E,hydrateCollections:c,isMock:l}),z=x?.categoryName||x?.ageCategoryCode||x?.ratingType,K=m.eventName||z||`Generated ${q}`;let Q=p?.participants??[];const J=function({qualifyingProfiles:t,participantType:e}){const n=t?.flatMap(t=>t.structureProfiles??[]).reduce((t,e)=>t+(!e.participantsCount||e.participantsCount>e.drawSize?e.drawSize:e.participantsCount||0),0)||0;return n*(e===Sm?2:1)}({qualifyingProfiles:R,participantType:$}),X=(!m.participantsCount||m.participantsCount>G?G:m.participantsCount)||0,Z=function({eventName:t,eventType:e,tieFormat:n,category:r,eventId:i,gender:o,timeItems:a,drawProfile:s,eventExtensions:c}){const u={eventName:t,eventType:e,tieFormat:n,category:r,eventId:i,gender:o};Array.isArray(a)&&a.forEach(t=>oU({event:u,timeItem:t}));let{eventAttributes:d}=s;"object"!=typeof d&&(d={});if(Object.assign(u,d),c?.length&&Array.isArray(c)){const t=c.filter(Wu);t?.length&&Object.assign(u,{extensions:t})}return u}({eventName:K,eventType:q,tieFormat:H,category:x,eventId:j,gender:B,timeItems:k,drawProfile:m,eventExtensions:N}),tt=[];if(!r&&(0===i?.participantsCount||m.uniqueParticipants||J||!p||B&&B!==Gi||x||W)){const t=kx({qualifyingParticipantsCount:J,participantsProfile:i,drawParticipantsCount:(X||0)+w+J,ratingsParameters:d,tournamentRecord:p,drawProfileCopy:y,participantType:$,categoryName:z,drawProfile:m,buildTeams:C,eventType:q,drawSize:G,isHybrid:W,drawIndex:g,category:x,gender:B,random:I,event:Z,uuids:S});if(t.error)return t;t.uniqueParticipantIds.forEach(t=>tt.push(t)),Q=t.targetParticipants}const{consideredParticipants:et,participantIds:nt,isEventParticipantType:rt,isEventGender:it}=function({allUniqueParticipantIds:t,targetParticipants:e,participantsCount:n,drawProfile:r,eventType:i,isHybrid:o}){const a=t=>{const{participantType:e}=t;return!(!o||e!==gm&&e!==Sm)||(!(!bh(ts)(i)||e!==gm)||(!(!bh(ns)(i)||e!==Sm)||i===ym&&e===ym))},s=t=>!r.gender||(r.gender===Gi||(r.gender===Bi&&t.participantType===gm||(t.person?.sex===r.gender||t.individualParticipantIds?.some(t=>{const n=e.find(e=>e.participantId===t);return n&&s(n)})))),c=new Set(t),u=e.filter(a).filter(s).filter(({participantId:t})=>!c.has(t)),d=u.slice(0,n).map(t=>t.participantId);return{consideredParticipants:u,participantIds:d,isEventParticipantType:a,isEventGender:s}}({allUniqueParticipantIds:n,targetParticipants:Q,participantsCount:X,drawProfile:m,eventType:q,isHybrid:W}),ot=xx({qualifyingParticipantsCount:J,consideredParticipants:et,isEventParticipantType:rt,excessParticipantAlternates:v,tournamentAlternates:T,autoEntryPositions:s,qualifyingProfiles:R,participantsCount:X,alternatesCount:w,tournamentRecord:p,participantIds:nt,isEventGender:it,drawSize:G,isMock:l,event:Z,stage:V});if(ot?.error)return ot;const at=z||K;!function({tournamentRecord:t,participantIds:e,seedingScaleName:n,seedsCount:r,startDate:i,eventType:o}){t&&r&&r<=e.length&&L(1,r+1).forEach((r,a)=>{const s={scaleName:n,scaleDate:i,scaleType:Uh,scaleValue:r,eventType:o},c=e[a];_D({tournamentRecord:t,participantId:c,scaleItem:s})})}({tournamentRecord:p,participantIds:nt,seedingScaleName:at,seedsCount:O,startDate:h,eventType:q});const st=_x({matchUpStatusProfile:o,completeAllMatchUps:a,randomWinningSide:u,tournamentRecord:p,drawProfileCopy:y,seedingScaleName:at,drawExtensions:M,iterativeAdHoc:KS(P)&&a&&!1!==m.automated&&(y.roundsCount??1)>1,completionGoal:A,matchUpFormat:U,drawProfile:m,drawType:P,category:x,generate:b,drawName:F,isMock:l,random:I,eventId:j,publish:_,event:Z,qualifyingPositions:D,stage:V});return st.error?st:{...Y,event:Ei(Z),drawDefinition:st.drawDefinition,uniqueParticipantIds:tt,targetParticipants:Q,eventId:j,drawId:st.drawId}}function Bx({tournamentRecord:t,disableNotice:e,venueId:n,courtId:r,court:i}){const{venue:o}=Ig({tournamentRecord:t,venueId:n});if(!o)return{error:Ln};o.courts??=[];const a={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,indoorOutdoor:void 0,floodlit:void 0,dateAvailability:[],onlineResources:[],pace:void 0,notes:void 0,venueId:n,courtId:r};a.courtId||(a.courtId=pa());if(o.courts.some(t=>t.courtId===a.courtId))return{error:On};{const r=(i?.dateAvailability??[]).map(t=>({...t,date:Lo(t.date),startTime:_o(t.startTime),endTime:_o(t.endTime),bookings:t.bookings?.map(({startTime:t,endTime:e,bookingType:n})=>({startTime:_o(t),endTime:_o(e),bookingType:n}))})),s=Object.keys(a);for(const t of s)if(i?.[t])if("dateAvailability"===t){const t=cg({dateAvailability:r});if(!t.valid&&t.error)return t;a.dateAvailability=r}else a[t]=i[t];const c=a;return o.courts.push(c),e||di({payload:{venue:o,tournamentId:t.tournamentId},topic:El,key:o.venueId}),{...Y,court:ca(a),venueId:n}}}function Vx(t){const{tournamentRecord:e,venueId:n}=t;if("string"!=typeof n||!n)return{error:Bn};const r=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},i=[];let o;for(const e of Object.values(r)){const{venue:r}=Ig({tournamentRecord:e,venueId:n});if(r){const n=Gx({...t,tournamentRecord:e});for(const t of n?.courts??[])i.push(t?.courtId);if(n.error)return n;o=!0}}return o?{...Y,courtIds:i}:{error:Ln}}function Gx({courtNameRoot:t="Court",dateAvailability:e=[],venueAbbreviationRoot:n,tournamentRecord:r,courtNames:i=[],courtTimings:o,courtsCount:a,startTime:s,courtIds:c,endTime:u,idPrefix:d,venueId:p,dates:l}){if(!p)return{error:Bn};const m=Ig({tournamentRecord:r,venueId:p});if(m.error)return m;const{venue:f}=m;if(!P(a)||!i)return{error:En};const h=L(0,a=a??i.length).map(r=>{const a=o?.[r],c=a?l.map(t=>({date:bo(t),startTime:s,endTime:u,...a})):e;return a&&s&&u&&c.push({startTime:s,endTime:u}),{courtName:i[r]||n&&f?.venueAbbreviation&&`${f?.venueAbbreviation} ${r+1}`||`${t} ${r+1}`,dateAvailability:c}}).map((t,e)=>{const n=c?.pop()||d&&`${d}-${e+1}`;return Bx({disableNotice:!0,tournamentRecord:r,courtId:n,venueId:p,court:t})}).map(t=>t.court).filter(Boolean);return h.length!==a?Ci({info:"not all courts could be generated",result:{error:sr}}):(f&&di({payload:{venue:f,tournamentId:r.tournamentId},topic:El,key:f.venueId}),{...Y,courts:ca(h)})}function jx({tournamentRecord:t,ignoreExistingVenues:e,venueProfiles:n,uuids:r}){const{startDate:i,endDate:o}=t,a=[];for(const[s,c]of n.entries()){const{venueAbbreviation:n,venueId:u=r?.pop()??pa(),dateAvailability:d,venueDateAvailability:p,defaultStartTime:l,defaultEndTime:m,startTime:f="07:00",endTime:h="19:00",courtTimings:g,courtsCount:I,courtNames:S,venueName:y,idPrefix:v,courtIds:U}=c,P={venueName:y||`Venue ${s+1}`,venueAbbreviation:n,venueId:u};l&&(P.defaultStartTime=l),m&&(P.defaultEndTime=m),c.isPrimary&&(P.isPrimary=!0),p&&(P.dateAvailability=p);const T=hg({tournamentRecord:t,venue:P});if(T.error){if(e)continue;return T}a.push(u);const w=Ao(i,o),D=!Array.isArray(d)&&[{startTime:f,endTime:h}].concat(w.map(t=>({date:bo(t),startTime:f,endTime:h})));if(I||S){const e=Vx({dateAvailability:d||D,tournamentRecord:t,courtTimings:g,courtsCount:I,courtNames:S,startTime:f,idPrefix:v,courtIds:U,endTime:h,venueId:u,dates:w});if(e.error)return e}}return a}const qx=["Generated Tournament","CourtHive Challenge","Replication Crisis","Open Competition","Factory Follies","Mock Tournament","Atomic Culture","Racket Rally","Stats Fail"];function Wx(t){let{startDate:e,endDate:n}=t??{};const{tournamentName:r=x(qx,t?.random),ratingsParameters:i=rp,tournamentExtensions:o,policyDefinitions:a,schedulingProfile:s,venueProfiles:c,uuids:u}=t??{},d=!1!==t?.isMock||void 0;if(e&&!Do(e)||n&&!Do(n))return{error:_e};if(!function(t){return!(t.leagueProfiles&&!Array.isArray(t.leagueProfiles)||t.eventProfiles&&!Array.isArray(t.eventProfiles)||t.drawProfiles&&!Array.isArray(t.drawProfiles))}(t))return{error:sr};({startDate:e,endDate:n}=function(t,e){let n=t,r=e;if(!n){const t=new Date;n=bo(r??t),r=bo(t.setDate(t.getDate()+7))}if(!r){const t=new Date(n);r=bo(t.setDate(t.getDate()+7))}return{startDate:n,endDate:r}}(e,n));const p=qF({...t.tournamentAttributes,tournamentName:r,startDate:e,endDate:n,isMock:d}),l=c?.length?jx({tournamentRecord:p,venueProfiles:c,uuids:u}):[];if(o?.length&&Array.isArray(o)){const t=o.filter(t=>Wu({extension:t}));t?.length&&Object.assign(p,{extensions:t,isMock:d})}if("object"==typeof a)for(const t of Object.keys(a))RT({policyDefinitions:{[t]:a[t]},tournamentRecord:p});const m=Boolean(t?.participants?.length);if(m){const e=fC({tournamentRecord:p,participants:t.participants});if(e.error)return e}else{if(!t?.leagueProfiles?.length||t.eventProfiles?.length||t.drawProfiles?.length||t.participantsProfile){const e=sx({tournamentRecord:p,...t});if(!e.success)return e}}const h=[],g=[],I=function({allUniqueParticipantIds:t,useExistingParticipants:e,ratingsParameters:n,tournamentRecord:r,params:i,eventIds:o,venueIds:a,drawIds:s}){if(i.leagueProfiles){const e=function(t){const{tournamentRecord:e,leagueProfiles:n,eventIds:r,venueIds:i,drawIds:o,allUniqueParticipantIds:a,random:s,uuids:c}=t;let u=0;for(const d of n){const n=[],{tieFormatName:p=Ea,teamProfiles:l=[],teamsCount:m=0,category:h,idPrefix:g,gender:I}=d,S=d.leagueName??d.eventName??`League ${u+1}`,y=d.leagueId??d.eventId??c?.pop()??pa(void 0,s);r.push(y);const v=f(d.tieFormat)&&d.tieFormat||Za({event:{eventId:y,category:h,gender:I},namedFormat:p,isMock:t.isMock})||void 0;if(!v)return{error:me};const U=Math.max(m,l.length),T=L(0,U),{genders:w,teamSize:D}=ax({tieFormat:v,drawSize:U,random:s}),R={[_i]:0,[Bi]:0,[Li]:0,[Vi]:0,[Gi]:0};Object.keys(w).forEach(t=>R[t]+=w[t]);for(const r of T){const o=l?.[r]?.teamName??`Team ${r+1}`,u=l?.[r]?.teamId||c?.pop()||pa(void 0,s),p=d.startDate??t.startDate,m=rx({...d?.participantsProfile,participantsCount:D,consideredDate:p,gendersCount:R,category:h,random:s,uuids:c}).participants,f=m.map(t=>t.participantId),I=ym,S=u??QF({participantType:I,idPrefix:g,random:s,index:r,uuids:c});n.push({participantId:S,entryStatus:rf,entryStage:us});const y=l?.[r]?.venueIds??[],v={participantId:S,participantRole:sy,participantName:o,individualParticipantIds:f,participantType:I,homeVenueIds:y};y.forEach(t=>!i.includes(t)&&i.push(t)),a.push(...f,S);const U=fC({participants:[v,...m],tournamentRecord:e});if(U.error)return U}const b={eventName:S,entries:n,eventType:ym,tieFormat:v,category:h,eventId:y,gender:I};if(e.events??=[],e.events.push(b),n.length){const t=(P(d.roundsCount)&&d.roundsCount)??d.roundsCount===rc?2*(U-1):U-1,n=JE({automated:d.automated,tournamentRecord:e,drawType:ks,roundsCount:t,drawSize:U,event:b});if(n.error)return n;const{drawDefinition:r}=n;if(r){const t=r?.drawId;QC({drawDefinition:r,event:b,suppressNotifications:!0}),o.push(t)}}u++}jx({tournamentRecord:e,ignoreExistingVenues:!0,venueProfiles:i.map(t=>({venueId:t})),uuids:c})}({allUniqueParticipantIds:t,tournamentRecord:r,...i,eventIds:o,venueIds:a,drawIds:s});if(e?.error)return e}if(i.drawProfiles){const a=function(t){const{tournamentRecord:e,drawProfiles:n,allUniqueParticipantIds:r,eventIds:i,drawIds:o}=t;let a=0;for(const s of n){let n=Lx({allUniqueParticipantIds:r,tournamentRecord:e,drawProfile:s,drawIndex:a,...t});if(n.error)return n;const{drawId:c,eventId:u,event:d,uniqueParticipantIds:p}=n;if(!1!==s?.addEvent){if(n=yC({suppressNotifications:!1,internalUse:!0,tournamentRecord:e,event:d}),n.error)return n;c&&o.push(c),i.push(u)}p?.length&&r.push(...p),a+=1}}({allUniqueParticipantIds:t,useExistingParticipants:e,ratingsParameters:n,tournamentRecord:r,...i,eventIds:o,drawIds:s});if(a?.error)return a}if(i.eventProfiles){const a=function(t){const{eventProfiles:e,allUniqueParticipantIds:n,eventIds:r,drawIds:i}=t;let o=0;for(const a of e){const e=Cx({...t,eventIndex:o,eventProfile:a});if(e.error)return e;const{eventId:s,drawIds:c,uniqueParticipantIds:u}=e;c&&i.push(...c),r.push(s),u?.length&&n.push(...u),o+=1}}({allUniqueParticipantIds:t,useExistingParticipants:e,ratingsParameters:n,tournamentRecord:r,...i,eventIds:o,drawIds:s});if(a?.error)return a}return}({allUniqueParticipantIds:[],useExistingParticipants:m,ratingsParameters:i,tournamentRecord:p,params:t,eventIds:h,venueIds:l,drawIds:g});if(I?.error)return I;const{scheduledRounds:S,schedulerResult:y={}}=s?function(t){const{schedulingProfile:e,tournamentRecord:n,autoSchedule:r,periodLength:i,scheduleCompletedMatchUps:o}=t,a=function({schedulingProfile:t,tournamentRecord:e}){if("object"!=typeof t)return{error:sr};const n=nm({tournamentRecord:e}).containedStructures,r=Qg({tournamentRecord:e}).matchUps??[],{tournamentId:i}=e,o=[];for(const a of t){const{scheduleDate:t,venues:s=[]}=a;for(const a of s){const{rounds:s,venueId:c}=a;for(const a of s){const{drawId:s,winnerFinishingPositionRange:u,roundSegment:d}=a,p=r.filter(t=>{const e=u?.indexOf("-")>0&&u.split("-").map(t=>+t),n=t.finishingPositionRange?.winner;return!(t.drawId!==s||a.roundNumber&&t.roundNumber!==a.roundNumber||n&&e&&2!==V(n,e).length&&(M(n).length!==M(e).length||V(n,e).length!==M(n).length))})[0];if(p){const{eventId:r,roundNumber:a,drawName:l,structureName:m,roundName:f}=p;let h=p.structureId;a&&!u&&(h=Object.keys(n).find(t=>n[t].includes(h))??h);const g={tournamentId:i,structureId:h,roundNumber:a,roundSegment:d,eventId:r,drawId:s},I=Ox({tournamentRecords:{[i]:e},round:g,scheduleDate:t,venueId:c});if(I.error)return I;o.push({structureName:m,roundName:f,drawName:l,...g})}}}}return{scheduledRounds:o}}({schedulingProfile:e,tournamentRecord:n});if(a.error)return a;const s=a.scheduledRounds;if(r){const{tournamentId:t}=n;return{schedulerResult:LF({scheduleCompletedMatchUps:o,tournamentRecords:{[t]:n},periodLength:i}),scheduledRounds:s}}return{scheduledRounds:s}}({...t,tournamentRecord:p}):{};return ui(),Ei({...Y,tournamentRecord:p,scheduledRounds:S,schedulerResult:y,eventIds:h,venueIds:l,drawIds:g})}function $x({keepExtensions:t=[],anonymizeParticipantNames:e=!0,tournamentRecord:n,tournamentName:r,personIds:i=[],tournamentId:o}){if(!n)return{error:rt};const a=Array.isArray(t)?Md.concat(...t):Md,s=e=>Array.isArray(t)?e?.extensions?.filter(t=>a.includes(t.name)):e?.extensions,c={};return function({tournamentRecord:t,filterExtensions:e,idMap:n,tournamentId:r,tournamentName:i}){t.extensions=e(t);const o=r||pa();n[t.tournamentId]=o,t.tournamentId=o,t.createdAt=(new Date).toISOString(),t.tournamentName=i||`Anonymized: ${bo(new Date)}`,t.isMock=!0,delete t.parentOrganisation}({tournamentRecord:n,filterExtensions:s,idMap:c,tournamentId:o,tournamentName:r}),function({tournamentRecord:t,filterExtensions:e,idMap:n}){for(const r of t.participants??[]){r.extensions=e(r),r.onlineResources=[];const t=pa();n[r.participantId]=t,r.participantId=t}for(const e of t.participants??[])Array.isArray(e.individualParticipantIds)&&(e.individualParticipantIds=e.individualParticipantIds.map(t=>n[t]))}({tournamentRecord:n,filterExtensions:s,idMap:c}),function({tournamentRecord:t,filterExtensions:e,idMap:n}){let r=0;for(const i of t.venues??[]){i.venueAbbreviation=`V${r}`,i.extensions=e(i),i.venueName=`Venue #${r}`,i.onlineResources=[],i.addresses=[];const t=pa();n[i.venueId]=t,i.isMock=!0,r+=1;let o=0;for(const t of i.courts??[])t.courtName=`V${r}C${o}`,t.extensions=e(t),t.onlineResources=[],t.isMock=!0,o+=1}}({tournamentRecord:n,filterExtensions:s,idMap:c}),function({tournamentRecord:t,filterExtensions:e,idMap:n}){let r=1;for(const i of t.events??[]){i.extensions=e(i),i.onlineResources=[],i.isMock=!0;const t=pa();n[i.eventId]=t,i.eventId=t;const o=i.category?.categoryName||i.category?.ageCategoryCode||i.category?.ratingType||i.gender;if(i.eventName=`Event ${r} ${o}`,Array.isArray(i.entries))for(const t of i.entries)t.participantId=n[t.participantId];for(const t of i.drawDefinitions??[])Yx({drawDefinition:t,filterExtensions:e,idMap:n});Array.isArray(i.flightProfile?.flights)&&zx(i.flightProfile,n);const{extension:a}=td({name:ld,element:i});Array.isArray(a?.value?.flights)&&zx(a.value,n),r+=1}}({tournamentRecord:n,filterExtensions:s,idMap:c}),function({anonymizeParticipantNames:t,tournamentRecord:e,filterExtensions:n,personIds:r,idMap:i}){const o=e.startDate||bo(new Date),a=(e.participants??[]).filter(({participantType:t})=>t===gm),s=a.reduce((t,e)=>{const n=e.person?.sex,r=zi(n);return r&&Yi(n)?t[r]+=1:t[Li]+=1,t},{[Vi]:0,[_i]:0,[Li]:0}),c=Object.assign({},...Object.keys(s).map(t=>({[t]:tx({category:{ageCategoryCode:"O18"},count:s[t],personExtensions:[],consideredDate:o,sex:t})?.persons??[]}))),u={[Vi]:0,[_i]:0,[Li]:0},d=a.length,p=function(t,e){const n=t.reduce((t,e)=>{const n=e.person?.addresses?.[0]??{},{city:r,state:i,postalCode:o}=n;return t.cities.includes(r)||t.cities.push(r),t.states.includes(i)||t.states.push(i),t.postalCodes.includes(o)||t.postalCodes.push(o),t},{cities:[],postalCodes:[],states:[]}),r=n.postalCodes.length,i=n.cities.length,o=n.states.length,{cities:a}=zF({count:i||e,participantsCount:e}),{states:s}=YF({count:o||e,participantsCount:e}),{postalCodes:c}=KF({count:r||e,participantsCount:e});return{cities:a,states:s,postalCodes:c}}(a,d);a.forEach((e,o)=>{!function({anonymizeParticipantNames:t,individualParticipant:e,filterExtensions:n,participantIndex:r,genderedPersons:i,genderedIndices:o,addressValues:a,personIds:s,idMap:c}){const u=e?.person,d=u?.sex||Li,p=Lo(u?.birthDate)?.split("-")[0],l=o[d],m=i[d][l];if(o[d]+=1,p){const[,t,e]=m?.birthDate?.split("-")??[],n=[p,t,e].join("-");m.birthDate=n}if(u?.addresses){const t=JF({...a,participantIndex:r,nationalityCode:m.nationalityCode});m.addresses=[t]}m.personId=s?.[r]||pa(),t?(m.standardFamilyName=m.lastName,m.standardGivenName=m.firstName,e.participantName=`${m.standardGivenName} ${m.standardFamilyName}`):(m.standardFamilyName=u?.standardFamilyName,m.standardGivenName=u?.standardGivenName);delete m.firstName,delete m.lastName,m.extensions=n(u),e.person=m,c[u?.personId]=m.personId}({anonymizeParticipantNames:t,individualParticipant:e,filterExtensions:n,participantIndex:o,genderedPersons:c,genderedIndices:u,addressValues:p,personIds:r,idMap:i})})}({anonymizeParticipantNames:e,tournamentRecord:n,filterExtensions:s,personIds:i,idMap:c}),function({tournamentRecord:t}){const e=(t.participants??[]).filter(({participantType:t})=>t===gm),n=(t.participants??[]).filter(({participantType:t})=>t===Sm);n.forEach(t=>{const{individualParticipantIds:n}=t;t.participantName=function({individualParticipantIds:t,individualParticipants:e}){let n=e.filter(({participantId:e})=>t.includes(e)).map(t=>t.person?.standardFamilyName||t.participantOtherName||t.participantName||"").filter(Boolean).sort().join("/");1===t.length&&(n+="/Unknown");return n}({individualParticipantIds:n,individualParticipants:e})});const r=(t.participants??[]).filter(({participantType:t})=>t===ym),i=nx({count:r.length}).names;r.forEach((t,e)=>{t.participantName=i[e]});const o=(t.participants??[]).filter(({participantType:t})=>t===Im),a=nx({count:o.length,nameRoot:"Group"}).names;o.forEach((t,e)=>{t.participantName=a[e]})}({tournamentRecord:n}),function({tournamentRecord:t,idMap:e}){const{extension:n}=td({element:t,name:wd});Array.isArray(n?.value)&&Hx(n.value,e);Array.isArray(t.scheduling?.profile)&&Hx(t.scheduling.profile,e);const{extension:r}=td({element:t,name:Sd});Array.isArray(r?.value)&&r?.value.forEach(t=>{t.personId=e[t.personId]})}({tournamentRecord:n,idMap:c}),{...Y}}function Hx(t,e){for(const n of t)n.tournamentId=e[n.tournamentId],n.structureId=e[n.structureId],n.eventId=e[n.eventId],n.drawId=e[n.drawId]}function zx(t,e){for(const n of t.flights)if(n.drawId=e[n.drawId],Array.isArray(n.drawEntries))for(const t of n.drawEntries)t.participantId=e[t.participantId]}function Yx({drawDefinition:t,filterExtensions:e,idMap:n}){t.extensions=e(t);const r=pa();if(n[t.drawId]=r,t.drawId=r,t.isMock=!0,Array.isArray(t.entries))for(const e of t.entries)e.participantId=n[e.participantId];const i=t=>{t.extensions=e(t);const r=pa();n[t.structureId]=r,t.structureId=r;for(const e of t.positionAssignments??[])e.participantId&&(e.participantId=n[e.participantId]);for(const e of t.seedAssignments??[])e.participantId&&(e.participantId=n[e.participantId]);for(const e of t.matchUps??[]){e.isMock=!0;for(const t of e.sides??[])t.lineUp&&(t.lineUp=t.lineUp.map(({participantId:t,collectionAssignments:e})=>({participantId:n[t],collectionAssignments:e})))}};for(const e of t.structures??[])if(i(e),Array.isArray(e.structures))for(const t of e.structures)i(t);for(const e of t.links??[])e.source.structureId=n[e.source.structureId],e.target.structureId=n[e.target.structureId]}function Kx({tournamentRecord:t,drawId:e,matchUpId:n,event:r,drawDefinition:i}){if(!i&&e&&t){const n=wg({tournamentRecord:t,drawId:e});if(n.error)return n;i=n.drawDefinition,r||(r=n.event)}return Gk({outcome:oT,tournamentRecord:t,drawDefinition:i,matchUpId:n,event:r})}function Qx(t,e){return t?.find((t,n)=>void 0!==e.eventIndex&&n===e.eventIndex||e.eventName&&t.eventName===e.eventName||e.eventId&&t.eventId===e.eventId)}function Jx({event:t,eventProfile:e,tournamentRecord:n,allUniqueParticipantIds:r,drawIds:i,params:o}){const a=function({event:t,eventProfile:e,tournamentRecord:n,allUniqueParticipantIds:r,drawIds:i}){const{gender:o,category:a,eventType:s}=t,{drawProfiles:c,publish:u}=e,d=bh(ts)(s)&&gm||bh(ns)(s)&&Sm||s;if(c){const{stageParticipantsCount:u,uniqueParticipantsCount:p,uniqueParticipantStages:l}=cx({drawProfiles:c,category:a,gender:o}),{uniqueDrawParticipants:m=[],uniqueParticipantIds:f=[]}=l?Mx({event:{eventType:s,category:a,gender:o},uniqueParticipantsCount:p,participantsProfile:e.participantsProfile,ratingsParameters:e.ratingsParameters,tournamentRecord:n,eventProfile:e,uuids:e.uuids}):{};r.push(...f);const{stageParticipants:h}=ux({targetParticipants:n.participants??[],allUniqueParticipantIds:r,stageParticipantsCount:u,eventParticipantType:d,gender:o});let g=Ex({uniqueDrawParticipants:m,autoEntryPositions:e.autoEntryPositions,stageParticipants:h,tournamentRecord:n,drawProfiles:c,category:a,gender:o,event:t});if(g.error)return g;if(g=wx({matchUpStatusProfile:e.matchUpStatusProfile,completeAllMatchUps:e.completeAllMatchUps,randomWinningSide:e.randomWinningSide,tournamentRecord:n,drawProfiles:c,isMock:e.isMock,event:t}),g.error)return g;i.push(...g.drawIds)}return u&&TC({tournamentRecord:n,event:t}),Y}({event:t,eventProfile:{...e,...o},tournamentRecord:n,allUniqueParticipantIds:r,drawIds:i});return a}function Xx({eventProfile:t,tournamentRecord:e,allUniqueParticipantIds:n,eventIds:r,drawIds:i,params:o,eventIndex:a}){const s=Cx({startDate:e.startDate,allUniqueParticipantIds:n,matchUpStatusProfile:o.matchUpStatusProfile,participantsProfile:o.participantsProfile,completeAllMatchUps:o.completeAllMatchUps,autoEntryPositions:o.autoEntryPositions,randomWinningSide:o.randomWinningSide,ratingsParameters:t.ratingsParameters,tournamentRecord:e,eventProfile:t,eventIndex:a,uuids:o.uuids});if(s.error)return s;const{eventId:c,drawIds:u,uniqueParticipantIds:d}=s;return u&&i.push(...u),r.push(c),d?.length&&n.push(...d),{eventIndexIncrement:1}}function Zx(t){const{participantsProfile:e={},schedulingProfile:n,tournamentRecord:r,autoSchedule:i,eventProfiles:o,periodLength:a,venueProfiles:s,drawProfiles:c,uuids:u}=t;if(!r)return{error:rt};const d=[],p=[],l=[];o?.forEach(t=>{const e=Qx(r.events,t);e?.gender&&(t.gender=e.gender)});const m=r.participants?.length||void 0;m&&e?.idPrefix&&(e.idPrefix=`${e.idPrefix}-${m}`);const f=sx({startDate:r.startDate,participantsProfile:e,tournamentRecord:r,eventProfiles:o,drawProfiles:c,uuids:u});if(!f.success)return f;if(o){const e=function({eventProfiles:t,tournamentRecord:e,allUniqueParticipantIds:n,eventIds:r,drawIds:i,params:o}){let a=e.events?.length||0;for(const s of t){const t=Qx(e.events,s);if(t){const r=Jx({event:t,eventProfile:s,tournamentRecord:e,allUniqueParticipantIds:n,drawIds:i,params:o});if(r?.error)return r}else{const t=Xx({eventProfile:s,tournamentRecord:e,allUniqueParticipantIds:n,eventIds:r,drawIds:i,params:o,eventIndex:a});if(t?.error)return t;a+=t?.eventIndexIncrement||1}}return Y}({eventProfiles:o,tournamentRecord:r,allUniqueParticipantIds:d,eventIds:p,drawIds:l,params:t});if(e.error)return e}if(c){const e=function({drawProfiles:t,tournamentRecord:e,allUniqueParticipantIds:n,eventIds:r,drawIds:i,params:o}){let a=(e.events??[]).flatMap(t=>t.drawDefinitions?.map(()=>1)??[]).reduce((t,e)=>t+e,0);for(const s of t){let t=Lx({startDate:e.startDate,allUniqueParticipantIds:n,matchUpStatusProfile:o.matchUpStatusProfile,participantsProfile:o.participantsProfile,completeAllMatchUps:o.completeAllMatchUps,autoEntryPositions:o.autoEntryPositions,hydrateCollections:o.hydrateCollections,randomWinningSide:o.randomWinningSide,ratingsParameters:o.ratingsParameters,tournamentRecord:e,drawProfile:s,drawIndex:a,uuids:o.uuids});if(t.error)return t;const{drawId:c,eventId:u,event:d,uniqueParticipantIds:p}=t;if(t=yC({tournamentRecord:e,event:d,internalUse:!0}),t.error)return t;c&&i.push(c),r.push(u),p?.length&&n.push(...p),a+=1}return Y}({drawProfiles:c,tournamentRecord:r,allUniqueParticipantIds:d,eventIds:p,drawIds:l,params:t});if(e.error)return e}const h=s?.length?jx({tournamentRecord:r,venueProfiles:s}):[],g=function({schedulingProfile:t,autoSchedule:e,periodLength:n,tournamentRecord:r}){let i={};if(t?.length){const o=zA({tournamentRecords:{[r.tournamentId]:r},schedulingProfile:t});if(o.error)return o;if(e){const{tournamentId:t}=r;i=LF({tournamentRecords:{[t]:r},periodLength:n})}}return{scheduledRounds:[],schedulerResult:i}}({tournamentRecord:r,schedulingProfile:n,autoSchedule:i,periodLength:a});if(g.error)return g;const{scheduledRounds:I,schedulerResult:S}=g;return{totalParticipantsCount:r.participants.length,scheduledRounds:I,schedulerResult:S,...Y,eventIds:p,venueIds:h,drawIds:l}}var t_={__proto__:null,anonymizeTournamentRecord:$x,completeDrawMatchUps:Ux,generate:{__proto__:null,generateEventWithDraw:Lx,generateOutcome:hx,generateOutcomeFromScoreString:nF,generateParticipants:rx,generateTournamentRecord:Wx},generateEventWithDraw:Lx,generateOutcome:hx,generateOutcomeFromScoreString:nF,generateParticipants:rx,generateTournamentRecord:Wx,modifyTournamentRecord:Zx,mutate:{__proto__:null,anonymizeTournamentRecord:$x,completeDrawMatchUps:Ux,modifyTournamentRecord:Zx,removeMatchUpOutcome:Kx},removeMatchUpOutcome:Kx};function e_(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 n_({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===sF&&(e=Lo(e),n=_o(n),r=_o(r),e&&n&&r)?{date:e,startTime:n,endTime:r,requestType:t.requestType}:t}).filter(Boolean);for(const n of r)n.requestId=e_(),t[e].push(n);return{mergeCount:r.length}}function r_(t){const{tournamentRecords:e,personRequests:n}=t,r=fu(t,[{[hc]:!0}]);if(r.error)return r;if(!n)return{...Y};const i=Object.values(e);for(const t of i){const e=t.participants??[],r=[];for(const t of Object.keys(n))if(ju({tournamentParticipants:e,personId:t})){const e=n[t];e.length&&r.push({personId:t,requests:e})}if(Object.keys(r).length){$u({element:t,extension:{value:r,name:Sd}})}}return{...Y}}function i_(t){const{tournamentRecords:e,requests:n,personId:r}=t,i=fu(t,[{[hc]:!0},{requests:!0,[cu]:iu,[su]:sr}]);if(i.error)return i;const o=n.map(({requestId:t})=>t).filter(Boolean),{personRequests:a}=QA({tournamentRecords:e}),s=t=>{a&&(a[t]=a[t].map(t=>{if(!o.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&&a?.[r])s(r);else if(a)for(const t of Object.keys(a))s(t);const c=n.filter(t=>!t.requestId);return c.length&&n_({personRequests:a,personId:r,requests:c}),r_({tournamentRecords:e,personRequests:a})}function o_(t){const{tournamentRecords:e,requestType:n,requestId:r,personId:i,date:o}=t,a=fu(t,[{[hc]:!0}]);if(a.error)return a;const{personRequests:s}=QA({tournamentRecords:e}),c=t=>{s&&(s[t]=s[t].filter(t=>!(n&&t.requestType===n||r&&t.requestId===r||o&&t.date===o)),s?.[t]?.length||delete s[t])},u=!(n||r||i||o);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?r_({tournamentRecords:e,personRequests:s}):qu({name:Sd,tournamentRecords:e,discover:!0})}function a_(t){const{tournamentRecords:e,personId:n,requests:r}=t,i=fu(t,[{[hc]:!0,[Bc]:!0},{requests:!0,[cu]:iu,[su]:sr}]);if(i.error)return i;const{personRequests:o}=QA({tournamentRecords:e}),{mergeCount:a}=n_({personRequests:o,personId:n,requests:r});return a&&o?r_({tournamentRecords:e,personRequests:o}):{error:sr}}function s_({tournamentRecord:t,participantIds:e,paymentState:n}){const r=dl({tournamentRecord:t},[Ic]);if(r.error)return r;if(!Array.isArray(e))return{error:Ae};if(!fm.includes(n))return{error:sr,paymentState:n};const i=t.participants??[];if(!i.length)return{error:an};const o=new Set(i.map(Xp)),a=e.filter(t=>!o.has(t));if(a.length)return{error:sr,context:{invalidParticipantIds:a}};const s=[],c=(new Date).toISOString();for(const r of i){const{participantId:i}=r;if(e.includes(i)){const e=rU({duplicateValues:!1,tournamentRecord:t,participantId:i,timeItem:{itemType:cm,itemValue:n,createdAt:c}});if(e.error)return e;s.push(r)}}const{topics:u}=gi();return s.length&&u.includes(bl)&&di({topic:bl,payload:{tournamentId:t.tournamentId,participants:s}}),{...Y}}function c_({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}){const r="modifyIndividualParticipantIds";if(!n)return Ci({result:{error:rt},stack:r});if(!e||!t)return Ci({result:{error:Ae},stack:r});const i=n.participants??[],o=i.find(t=>t.participantId===e);if(!o)return Ci({result:{error:un},stack:r});if(![ym,Im].includes(o.participantType))return Ci({result:{error:nn},context:{participantType:o.participantType},stack:r});const a=t.filter(t=>{const e=i.find(e=>e.participantId===t);return e?.participantType!==gm});if(a.length)return Ci({result:{error:tn,invalidParticipantIds:a},stack:r});const s=o.individualParticipantIds??[],c=t.filter(t=>!s.includes(t)),u=s.filter(e=>!t.includes(e)),d=LO({individualParticipantIds:c,groupingParticipantId:e,tournamentRecord:n});if(d.error)return Ci({result:d,stack:r});const p=fy({individualParticipantIds:u,groupingParticipantId:e,tournamentRecord:n});if(p.error)return Ci({result:p,stack:r});const{topics:l}=gi();if(l.includes(bl)){const t=i.find(({participantId:t})=>t===e);di({topic:bl,payload:{tournamentId:n.tournamentId,participants:[t]}})}return{...d,...p}}function u_({tournamentRecord:t,participantIds:e,signInState:n}){const r=dl({tournamentRecord:t},[Ic]);if(r.error)return r;if(!Array.isArray(e))return{error:Ae};if(![sm,am].includes(n))return{error:sr,signInState:n};const i=t.participants??[];if(!i.length)return{error:an};const o=new Set(i.map(Xp)),a=e.filter(t=>!o.has(t));if(a.length)return{error:sr,context:{invalidParticipantIds:a}};const s=[],c=(new Date).toISOString();for(const r of i){const{participantId:i}=r;if(e.includes(i)){const e=rU({duplicateValues:!1,tournamentRecord:t,participantId:i,timeItem:{itemType:om,itemValue:n,createdAt:c}});if(e.error)return e;s.push(r)}}const{topics:u}=gi();return s.length&&u.includes(bl)&&di({topic:bl,payload:{tournamentId:t.tournamentId,participants:s}}),{...Y}}function d_({tournamentRecord:t,participantId:e,participantOtherName:n}){const r=dl({tournamentRecord:t,participantId:e},[Ic,Pc]);if(r.error)return r;const{participant:i}=Rm({tournamentRecord:t,participantId:e});if(!i)return{error:un};i.participantOtherName=n;const{topics:o}=gi();return o.includes(bl)&&di({topic:bl,payload:{tournamentId:t.tournamentId,participants:[i]}}),{...Y}}function p_({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 o=t.indexOf(" ")>0?" ":"";let a=by(e?.standardGivenName??""),s=by(e?.standardFamilyName??"");if(!t)return`${a}${o}${s}`;!(t=>t.toLowerCase().indexOf("f.")>=0)(t)||i(t)||r(t)||(a=`${a[0]}.`),(t=>/^[a-z]*$/.test(n(t)))(t)?(a=a.toLowerCase(),s=s.toLowerCase()):(t=>/^[A-Z]*$/.test(n(t)))(t)?(a=a.toUpperCase(),s=s.toUpperCase()):(t=>/^[LAST]{4}/.test(n(t)))(t)&&(s=s.toUpperCase());let c=`${a}${o}${s}`;return(t=>t.toLowerCase().indexOf("f")<0)(t)?c=s:r(t)&&(c=i(t)?`${s},${o}${a}`:`${s}${o}${a}`),c}function l_({participantMap:t,participant:e,formats:n}){const{participantType:r,individualParticipantIds:i,person:o}=e,a=r&&n[r];if(r!==hm&&a){const{personFormat:n,doublesJoiner:s}=a;if(r===gm){(o?.standardGivenName||o?.standardFamilyName)&&(e.participantName=p_({person:o,personFormat:n}))}r===Sm&&(e.participantName=i?.map(e=>{const r=t[e],i=r?.person;return i?.standardGivenName||i?.standardFamilyName?p_({person:i,personFormat:n}):r?.participantOtherName||r?.participantName||""}).filter(Boolean).join(s??"/"))}}function m_({tournamentRecord:t,formats:e}){if(!t)return{error:rt};if(!f(e))return{error:Ae};const n=t.participants??[],r=g(n,"participantId");for(const t of n)l_({participant:t,participantMap:r,formats:e});return{...Y}}function f_(t){const{tournamentRecord:e,policyDefinitions:n,contextProfile:r,participantId:i,personId:o}=t,a=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if("string"!=typeof i&&"string"!=typeof o)return{error:Ae,stack:"publicFindParticipant"};let s,c;for(const t of Object.values(a)){c=t.tournamentId;if(s=ju({tournamentParticipants:t.participants??[],internalUse:!0,policyDefinitions:n,contextProfile:r,participantId:i,personId:o}),s)break}return{participant:s,tournamentId:c,...Y}}function h_({individualParticipantIds:t=[],participantRoleResponsibilities:e,participantRole:n=py,tournamentRecord:r,participantId:i,groupName:o}){const a=dl({tournamentRecord:r},[Ic]);if(a.error)return a;if(!o)return{error:Ae,info:"Missing groupName"};if(!Array.isArray(t))return{info:"Invalid individualParticipantIds",error:sr};const s=(xS({participantFilters:{participantTypes:[gm]},tournamentRecord:r}).participants??[]).map(t=>t.participantId);for(const e of t)if(!s.includes(e))return{error:nn,participantId:e};const c=Ei({participantId:i||pa(),participantRoleResponsibilities:e,participantName:o,individualParticipantIds:t,participantType:Im,participantRole:n}),u=mC({participant:c,tournamentRecord:r});if(u.error)return u;const{topics:d}=gi();return d.includes(ml)&&di({topic:ml,payload:{tournamentId:r.tournamentId,participants:[c]}}),{...Y,participant:ca(c)}}function g_({tournamentRecord:t,participantName:e,participantId:n}){const r=dl({tournamentRecord:t,participantId:n},[Ic,Pc]);if(r.error)return r;if(!e)return{error:Ae,info:"Missing participantName"};const{participant:i}=Rm({tournamentRecord:t,participantId:n});if(!i)return{error:un};i.participantName=e;const{topics:o}=gi();return o.includes(bl)&&di({topic:bl,payload:{tournamentId:t.tournamentId,participants:[i]}}),{...Y}}function I_({clearExistingAssignments:t=!0,individualParticipantIds:e,reverseAssignmentOrder:n,initialTeamIndex:r=0,scaledParticipants:i=[],teamParticipantIds:o,tournamentRecord:a,scaleAttributes:s,teamNameBase:c,teamsCount:u,eventId:d,event:p}){if(!a)return{error:rt};const l=function({teamParticipantIds:t,teamsCount:e,eventId:n,initialTeamIndex:r,scaledParticipants:i,scaleAttributes:o,individualParticipantIds:a}){return!Array.isArray(t)&&!R(e)&&!n||!R(r)||i&&!Array.isArray(i)||o&&("object"!=typeof o||!Object.keys(o).length)?{error:sr}:(o||i.length)&&(i||a&&o)?void 0:{error:Ae,info:"Missing scaling details"}}({teamParticipantIds:o,teamsCount:u,eventId:d,initialTeamIndex:r,scaledParticipants:i,scaleAttributes:s,individualParticipantIds:e});if(l)return l;const m=function({eventId:t,event:e,teamParticipantIds:n}){return t&&!n?e?.eventType!==os?{error:$t}:{teamParticipantIds:e?.entries?.filter(({entryStatus:t})=>t===rf).map(Xp)}:{teamParticipantIds:n}}({eventId:d,event:p,teamParticipantIds:o});if(m.error)return m;if(o=m.teamParticipantIds,!o?.length&&!u)return{info:"Missing teamParticipantIds or teamsCount",error:Ae};let f=e??i.map(({participantId:t})=>t);n&&(o?.reverse(),r+=1),r>(o?.length||0)-1&&(r=0);const h=function({tournamentRecord:t,orderedTeamParticipantIds:e}){const n=[];for(const r of t.participants??[]){const{participantId:t,participantType:i}=r;if(e.includes(t)){if(i!==hm)return{error:nn,participant:r};n.push(r)}}return{relevantTeams:n}}({tournamentRecord:a,orderedTeamParticipantIds:o?.slice(r).concat(...o.slice(0,r))??[]});if(h.error)return h;const{relevantTeams:g}=h;if(function({teamsCount:t,relevantTeams:e,teamNameBase:n,tournamentRecord:r}){if(t&&e.length<t){const i=n??"Team",o=L(0,t-(e?.length||0)).map(t=>({participantName:`${i} ${t+1}`,participantType:hm,participantRole:sy})),{participants:a=[]}=fC({participants:o,returnParticipants:!0,tournamentRecord:r}),s=new Set(a.map(Xp)),c=r.participants?.filter(({participantId:t})=>s.has(t))??[];e.push(...c)}}({teamsCount:u,relevantTeams:g,teamNameBase:c,tournamentRecord:a}),!g.length)return{error:ur};if(t)for(const t of g)t.individualParticipantIds=[];else{const t=new Set(g.flat());e?.length?f=f.filter(e=>!t.has(e)):i=i?.filter(({participantId:e})=>!t.has(e))}if(!e?.length&&!i?.length)return{error:er,info:"Nothing to be done"};if(!i.length){const t=function({tournamentRecord:t,participantIdsToAssign:e,scaleAttributes:n,scaledParticipants:r}){for(const i of t.participants??[]){const{participantId:t,participantType:o}=i;if(!e.includes(t))continue;if(o!==gm)return{error:nn,participant:i};const a=Vd({scaleAttributes:n,participant:i})?.scaleItem,s=n?.accessor?a?.scaleValue?.[n?.accessor]:a?.scaleValue;r.push({participantId:t,scaleValue:s})}if(!r.length)return{error:un}}({tournamentRecord:a,participantIdsToAssign:f,scaleAttributes:s,scaledParticipants:i});if(t)return t}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:sr,scaledParticipant:t};return function({scaledParticipants:t,relevantTeams:e}){let n=0;for(;n<t.length;){for(const r of e){if(n+1>t.length)break;const e=t[n];r.individualParticipantIds.push(e.participantId),n++}e.reverse()}}({scaledParticipants:i,relevantTeams:g}),function({tournamentRecord:t,relevantTeams:e}){const n=new Set(e.map(Xp));for(const r of t.events??[]){if(r.eventType!==os)continue;const t=(r.entries??[]).filter(t=>n.has(t.participantId));for(const n of t){const t=e.find(t=>t.participantId===n.participantId),i=t?.individualParticipantIds;r.entries=(r.entries??[]).filter(t=>!i.includes(t.participantId)),(r.drawDefinitions??[]).forEach(t=>{t.entries=(t.entries??[]).filter(t=>!i.includes(t.participantId))});const{flightProfile:o}=Tg({event:r});(o?.flights??[]).forEach(t=>{t.drawEntries=(t.drawEntries??[]).filter(t=>!i.includes(t.participantId))})}}}({tournamentRecord:a,relevantTeams:g}),{...Y,scaledParticipants:i}}function S_(t){const e=fu(t,[{[Ic]:!0,[Oc]:!0},{ratingType:!1,[ou]:t=>rp[t]}]);if(e.error)return e;const n=`${t.ratingType}.${gu}`,r=t.asDynamic?n:t.ratingType,i=[yu,Su,t.eventType,r].join("."),o=t.tournamentRecord.participants??[];for(const t of o)t.timeItems&&(t.timeItems=t.timeItems.filter(t=>t.itemType!==i));return{...Y}}function y_(t){const{tournamentRecords:e}=t;if("object"!=typeof e||!Object.keys(e).length)return{error:nt};for(const n of Object.values(e)){const e=v_({...t,tournamentRecord:n});if(e.error&&e.error!==An)return e}return{...Y}}function v_({tournamentRecord:t,penaltyId:e}){const n=dl({tournamentRecord:t,penaltyId:e},[Ic,Jc]);if(n.error)return n;const r=[];let i,o=!1;return(t?.participants??[]).forEach(t=>{let n=!1;t.penalties=(t.penalties??[]).filter(a=>(a.penaltyId===e&&(n=!0,o||(i=a,o=!0)),n&&r.push(t),a.penaltyId!==e))}),i&&di({topic:bl,payload:{tournamentId:t.tournamentId,participants:r}}),i?{...Y,penalty:i}:{error:An}}const U_=({penaltyId:t=pa()}={})=>({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 P_(t){const{tournamentRecords:e}=t;if("object"!=typeof e||!Object.keys(e).length)return{error:nt};for(const n of Object.values(e)){const e=T_({...t,tournamentRecord:n});if(e.error&&e.error!==An)return e;if(e.success)return e}return{error:An}}function T_({tournamentRecord:t,modifications:e,penaltyId:n}){const r=dl({tournamentRecord:t,penaltyId:n},[Ic,Jc]);if(r.error)return r;if(!e)return{error:sr,modifications:e};const i=t?.participants??[],o=Object.keys(U_()).filter(t=>"penaltyId"!==t),a=Object.keys(e).filter(t=>o.includes(t));if(!a.length)return{error:pr};let s;const c=[];return i.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]})),s??=t),t)),r&&c.push(t)}),s&&di({topic:bl,payload:{tournamentId:t.tournamentId,participants:c}}),s?{...Y,penalty:s}:{error:An}}function w_(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]=w_(t[i],e[i],n):r[i]=e[i];else r[i]=e[i];else r[i]=t[i];return r},{})}function D_({participants:t=[],tournamentRecord:e,arraysToMerge:n}){if(!e)return{error:rt};e.participants??=[];const r=t.filter(eI(Pc)).map(t=>({[t.participantId]:t})),i=Object.assign({},...r),o=[];e.participants=e.participants.map(t=>{if(i[t.participantId]){const e=w_(t,i[t.participantId],n);return o.push(e),e}return t});const a=e.participants.map(eI(Pc))??[],s=t.filter(({participantId:t})=>!a.includes(t)),{topics:c}=gi();return s.length&&(e.participants=e.participants.concat(...s),c.includes(ml)&&di({topic:ml,payload:{participants:s}})),o.length&&c.includes(bl)&&di({topic:bl,payload:{tournamentId:e.tournamentId,participants:o}}),{modifiedParticipantsCount:o.length,newParticipantsCount:s.length,...Y}}function R_({tournamentRecord:t,participantId:e,organisationId:n,personId:r}){const i=dl({tournamentRecord:t,participantId:e},[Ic,Pc]);if(i.error)return i;if(!n)return{error:Ae,info:"Missing organisationId"};if(!r)return{error:Ae,info:"Missing personId"};const{participant:o}=Rm({tournamentRecord:t,participantId:e});if(!o)return{error:un};if(!o.person)return{error:sr,info:"Participant has no person — only INDIVIDUAL participants accept personOtherIds"};const a=o.person;a.personOtherIds??=[];const s=a.personOtherIds.find(t=>t?.organisationId===n);if(s){if(s.personId===r)return{...Y};s.personId=r,s.updatedAt=(new Date).toISOString()}else a.personOtherIds.push({organisationId:n,personId:r,createdAt:(new Date).toISOString()});const{topics:c}=gi();return c.includes(bl)&&di({topic:bl,payload:{tournamentId:t.tournamentId,participants:[o]}}),{...Y}}function b_(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=xS({tournamentRecord:e}).participants??[],o=r?.map(Xp).filter(t=>n.includes(t));if(o.length){i=N_({...t,penaltyId:t.penaltyId??i,tournamentRecord:e,participantIds:o}).penaltyId}}return i?{...Y,penaltyId:i}:{error:un}}function N_({refereeParticipantId:t,tournamentRecord:e,participantIds:n,penaltyCode:r,penaltyType:i,extensions:o,penaltyId:a,matchUpId:s,issuedAt:c,notes:u}){const d=dl({tournamentRecord:e,penaltyType:i},[Ic,Qc]);if(d.error)return d;if(!n)return{error:sn};const p=(e?.participants??[]).filter(t=>n.includes(t.participantId));if(!p.length)return{error:un};const l=(new Date).toISOString(),m=Object.assign(U_({penaltyId:a}),{refereeParticipantId:t,penaltyCode:r,penaltyType:i,matchUpId:s,createdAt:l,issuedAt:c,notes:u});return Array.isArray(o)&&o.forEach(t=>$u({element:m,extension:t})),p.forEach(t=>{t.penalties??=[],t.penalties.push(m)}),di({topic:bl,payload:{tournamentId:e.tournamentId,participants:p}}),{...Y,penaltyId:m.penaltyId}}function M_({participantRole:t=sy,tournamentRecord:e,persons:n}){if(!e)return{error:rt};if(!Array.isArray(n))return{error:sr};if(!Object.keys(my).includes(t))return{error:en};const r=new Set((e.participants??[]).map(({person:t})=>t?.personId).filter(Boolean)),i=[],o=n.filter(t=>t&&(!t.personId||!r.has(t.personId))).map(t=>(t.personId??=pa(),i.push(t.personId),t));let a,s=0,c=fC({participants:o.map(e=>{return Ei({extensions:e.participantExtensions,timeItems:e.participantTimeItems,participantType:gm,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;a=c.addedCount||0;const u=[],d=xS({participantFilters:{participantTypes:[gm]},tournamentRecord:e})?.participants??[];if(t===sy&&n.filter(({pairedPersons:t})=>t).forEach(({personId:t,pairedPersons:e})=>{Array.isArray(e)&&e.forEach(e=>{const n=[t,e.personId].map(t=>ju({tournamentParticipants:d,personId:t})).filter(Boolean);if(2===n.length){const t=n.map(Xp);u.push(Ei({extensions:e.participantExtensions,timeItems:e.timeItems,participantRole:sy,individualParticipantIds:t,participantType:Sm}))}})}),u.length){if(c=fC({participants:u,tournamentRecord:e}),c.error)return c;s=c.addedCount||0}const p=a+s;return{...Y,addedCount:p,newPersonIds:i}}var A_={__proto__:null,addDynamicRatings:GD,addIndividualParticipantIds:LO,addParticipant:mC,addParticipants:fC,addPenalty:b_,addPersonOtherId:R_,addPersonRequests:a_,addPersons:M_,createGroupParticipant:h_,createTeamsFromParticipantAttributes:WF,deleteParticipants:yy,filterParticipants:kS,findParticipant:f_,getCompetitionParticipants:XN,getPairedParticipant:bg,getParticipantEventDetails:ZN,getParticipantMembership:tM,getParticipantPaymentStatus:nM,getParticipantScaleItem:_S,getParticipantSchedules:eM,getParticipantSignInStatus:rM,getParticipantTimeItem:Cm,getParticipants:xS,getScaleValues:Pu,mergeParticipants:D_,modifyIndividualParticipantIds:c_,modifyParticipant:BO,modifyParticipantName:g_,modifyParticipantOtherName:d_,modifyParticipantsPaymentStatus:s_,modifyParticipantsSignInStatus:u_,modifyPenalty:P_,modifyPersonRequests:i_,mutate:{__proto__:null,addDynamicRatings:GD,addIndividualParticipantIds:LO,addParticipant:mC,addParticipants:fC,addPenalty:b_,addPersonOtherId:R_,addPersonRequests:a_,addPersons:M_,createGroupParticipant:h_,createTeamsFromParticipantAttributes:WF,deleteParticipants:yy,findParticipant:f_,mergeParticipants:D_,modifyIndividualParticipantIds:c_,modifyParticipant:BO,modifyParticipantName:g_,modifyParticipantOtherName:d_,modifyParticipantsPaymentStatus:s_,modifyParticipantsSignInStatus:u_,modifyPenalty:P_,modifyPersonRequests:i_,regenerateParticipantNames:m_,removeIndividualParticipantIds:fy,removeParticipantIdsFromAllTeams:Sy,removePenalty:y_,removePersonRequests:o_,removeRatings:S_,scaledTeamAssignment:I_,setParticipantScaleItem:_D,setParticipantScaleItems:LD},participantScaleItem:Vd,query:iM,regenerateParticipantNames:m_,removeIndividualParticipantIds:fy,removeParticipantIdsFromAllTeams:Sy,removePenalty:y_,removePersonRequests:o_,removeRatings:S_,scaledTeamAssignment:I_,setParticipantScaleItem:_D,setParticipantScaleItems:LD,validateLineUp:rv};function E_({removePriorValues:t=!0,stageSeedingScaleNames:e,seedingScaleNames:n,tournamentRecord:r,status:i=Th,drawIds:o=[],event:a}){const s=dl({tournamentRecord:r,event:a},[Ic,zc]);if(s.error)return s;const c=pS({event:a,status:i}),u=(c?.seeding?.seedingScaleNames||n)&&{...c?.seeding?.seedingScaleNames,...n};return PC({statusObject:{seeding:Ei({stageSeedingScaleNames:(c?.seeding?.stageSeedingScaleNames||e)&&{...c?.seeding?.stageSeedingScaleNames,...e},seedingScaleNames:u,published:!0,drawIds:o})},removePriorValues:t,status:i,event:a}),di({topic:kl,payload:{tournamentId:r.tournamentId,eventId:a.eventId,drawIds:o}}),{...Y}}function C_({removePriorValues:t=!0,seedingScaleNames:e,tournamentRecord:n,status:r=Th,drawIds:i,stages:o,event:a}){const s=dl({tournamentRecord:n,event:a},[Ic,zc]);if(s.error)return s;const c=pS({event:a});if(c){const n=c.seeding;if(Array.isArray(o)&&n.stageSeedingScaleNames)for(const t of o)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)&&(o||e||i?.length)||(delete n.stageSeedingScaleNames,delete n.seedingScaleNames,delete n.drawIds,n.published=!1),PC({statusObject:{seeding:n},removePriorValues:t,status:r,event:a})}return di({topic:Ll,payload:{tournamentId:n.tournamentId,eventId:a.eventId}}),{...Y}}function O_({tournamentRecord:t}){if(!Ii(Gl))return;const e=dS({tournamentRecord:t});if(!e?.orderOfPlay?.published&&!e?.participants?.published){for(const e of t.events??[]){const t=pS({event:e}),n=t?.drawDetails??{};for(const t of e.drawDefinitions?.map(el)??[])if(lS({drawDetails:n,drawId:t,ignoreEmbargo:!0}))return}di({topic:Gl,payload:{tournamentId:t.tournamentId}})}}function k_(t){const e=im(t);if(!Object.keys(e).length)return{error:nt};for(const n of Object.values(e)){const e=F_({tournamentRecord:n,...t});if(e.error)return e}return{...Y}}function F_({removePriorValues:t=!0,tournamentRecord:e,status:n=Th}){if(!e)return{error:rt};const r=`${Ph}.${wh}`,{timeItem:i}=Nm({element:e,itemType:r}),o=i?.itemValue||{[n]:{}};o[n]&&delete o[n].participants;return nU({timeItem:{itemValue:o,itemType:r},element:e,removePriorValues:t}),di({payload:{tournamentId:e.tournamentId},topic:Vl}),O_({tournamentRecord:e}),{...Y}}function x_(t){const e=im(t);if(!Object.keys(e).length)return{error:nt};for(const n of Object.values(e)){const e=__({tournamentRecord:n,...t});if(e.error)return e}return{...Y}}function __({removePriorValues:t=!0,tournamentRecord:e,status:n=Th}){if(!e)return{error:rt};const r=`${Ph}.${wh}`,{timeItem:i}=Nm({element:e,itemType:r}),o=i?.itemValue||{[n]:{}};o[n]&&delete o[n].orderOfPlay;return nU({timeItem:{itemValue:o,itemType:r},element:e,removePriorValues:t}),di({topic:Bl,payload:{tournamentId:e.tournamentId}}),O_({tournamentRecord:e}),{...Y}}function L_(t){const e=im(t);if(!Object.keys(e).length)return{error:nt};for(const n of Object.values(e)){const e=B_({tournamentRecord:n,...t});if(e.error)return e}return{...Y}}function B_({removePriorValues:t,tournamentRecord:e,status:n=Th,embargo:r,columns:i,language:o}){if(!e)return{error:rt};const a=`${Ph}.${wh}`,{timeItem:s}=Nm({element:e,itemType:a}),c=s?.itemValue||{[n]:{}},u={published:!0};if(r&&!Oo(r))return{error:je};r&&(u.embargo=r),i&&(u.columns=i),c[n].participants=u,o&&(c[n].language=o);return nU({timeItem:{itemValue:c,itemType:a},element:e,removePriorValues:t}),di({payload:{tournamentId:e.tournamentId},topic:xl}),{...Y}}function V_(t){const e=im(t);if(!Object.keys(e).length)return{error:nt};for(const n of Object.values(e)){const e=G_({tournamentRecord:n,...t});if(e.error)return e}return{...Y}}function G_({scheduledDates:t,removePriorValues:e,tournamentRecord:n,status:r=Th,eventIds:i,embargo:o,language:a}){if(!n)return{error:rt};const s=`${Ph}.${wh}`,{timeItem:c}=Nm({element:n,itemType:s}),u=c?.itemValue||{[r]:{}},d={published:!0};if(void 0!==t&&(d.scheduledDates=t),void 0!==i&&(d.eventIds=i),o&&!Oo(o))return{error:je};o&&(d.embargo=o),u[r].orderOfPlay=d,a&&(u[r].language=a);return nU({timeItem:{itemValue:u,itemType:s},element:n,removePriorValues:e}),di({topic:Fl,payload:{tournamentId:n.tournamentId,scheduledDates:t,eventIds:i}}),{...Y}}function j_({removePriorValues:t=!0,tournamentRecord:e,status:n=Th,event:r}){const i=dl({tournamentRecord:e,event:r},[Ic,zc]);if(i.error)return i;const o=`${Ph}.${wh}`,{timeItem:a}=Am({itemType:o,event:r}),s=a?.itemValue||{[n]:{}};delete s[n].structureIds,delete s[n].drawDetails,delete s[n].drawIds;return oU({event:r,timeItem:{itemValue:s,itemType:o},removePriorValues:t}),PC({statusObject:{structureIds:void 0,drawIds:void 0,seeding:void 0},removePriorValues:t,status:n,event:r}),di({topic:_l,payload:{tournamentId:e.tournamentId,eventId:r.eventId}}),O_({tournamentRecord:e}),{eventId:r.eventId,...Y}}var q_={__proto__:null,bulkUpdatePublishedEventIds:xA,getAllEventData:LA,getCourtInfo:Ug,getDrawData:Rw,getEventData:bw,getEventPublishStatus:pS,getPublishState:mS,getRoundVisibilityState:_A,getTournamentPublishStatus:dS,getVenueData:Pg,isEmbargoed:Eg,isVisiblyPublished:Cg,mutate:{__proto__:null,publishEvent:TC,publishEventSeeding:E_,publishOrderOfPlay:V_,publishParticipants:L_,setEventDisplay:tO,unPublishEvent:j_,unPublishEventSeeding:C_,unPublishOrderOfPlay:x_,unPublishParticipants:k_},publishEvent:TC,publishEventSeeding:E_,publishOrderOfPlay:V_,publishParticipants:L_,query:BA,setEventDisplay:tO,unPublishEvent:j_,unPublishEventSeeding:C_,unPublishOrderOfPlay:x_,unPublishParticipants:k_};function W_({participantFilters:t,policyDefinitions:e,tournamentRecord:n,level:r}){if(!n)return{error:rt};const i=xM({participantFilters:t,policyDefinitions:e,tournamentRecord:n,level:r});if(i.error)return i;const{personPoints:o={},pairPoints:a={},teamPoints:s={}}=i,c=n.tournamentId,u=n.endDate,{participants:d=[]}=xS({tournamentRecord:n}),p={},l={};for(const t of d)l[t.participantId]={participantName:t.participantName??"",personId:t.person?.personId},t.person?.personId&&(p[t.person.personId]={participantId:t.participantId,participantName:t.participantName??""});const m=[];for(const[t,e]of Object.entries(o)){const n=p[t];for(const r of e)m.push({...r,personId:t,participantId:n?.participantId??r.participantId,participantName:n?.participantName,tournamentId:r.tournamentId??c,endDate:r.endDate??u})}for(const[t,e]of Object.entries(a)){const n=l[t];for(const r of e)m.push({...r,participantId:t,participantName:n?.participantName,tournamentId:r.tournamentId??c,endDate:r.endDate??u})}for(const[t,e]of Object.entries(s)){const n=l[t];for(const r of e)m.push({...r,participantId:t,participantName:n?.participantName,tournamentId:r.tournamentId??c,endDate:r.endDate??u})}return{pointAwards:m,...Y}}function $_({awards:t,pointComponents:e,bestOfCount:n,maxResultsPerLevel:r,mandatoryRules:i}){const o=t.map(t=>{let n=0;for(const r of e)n+="number"==typeof t[r]?t[r]:0;return{award:t,value:n}});o.sort((t,e)=>e.value-t.value);let a=o,s=[];if(r){const t={};a=[];for(const e of o){const n=e.award.level;void 0!==n&&r[n]?(t[n]=(t[n]||0)+1,t[n]<=r[n]?a.push(e):s.push(e)):a.push(e)}}if(i?.length)return function(t,e,n,r){const i=new Set;for(const e of r){const n=new Set(e.levels),r=[];for(let e=0;e<t.length;e++){const i=t[e].award.level;void 0!==i&&n.has(i)&&r.push(e)}const o=e.bestOfCount?r.slice(0,e.bestOfCount):r;for(const t of o)i.add(t)}const o=[],a=[];for(let e=0;e<t.length;e++)i.has(e)?o.push(t[e]):a.push(t[e]);let s,c;if(n>0){const t=Math.max(0,n-o.length);s=a.slice(0,t),c=a.slice(t)}else s=a,c=[];const u=[...o,...s],d=[...c,...e],p=u.reduce((t,e)=>t+e.value,0);return{counting:u,dropped:d,bucketTotal:p}}(a,s,n,i);const c=n>0?a.slice(0,n):a,u=[...n>0?a.slice(n):[],...s],d=c.reduce((t,e)=>t+e.value,0);return{counting:c,dropped:u,bucketTotal:d}}function H_({pointAwards:t,personId:e,aggregationRules:n={}}){const{countingBuckets:r,maxResultsPerLevel:i,bestOfCount:o}=n,a=t.filter(t=>t.personId===e);if(r?.length){const t=[];let e=0;for(const n of r){const{bucketName:r,eventTypes:i,pointComponents:o,bestOfCount:s,maxResultsPerLevel:c,mandatoryRules:u}=n;let d=a;i?.length&&(d=d.filter(t=>t.eventType&&i.includes(t.eventType)));const{counting:p,dropped:l,bucketTotal:m}=$_({awards:d,pointComponents:o,bestOfCount:s,maxResultsPerLevel:c,mandatoryRules:u});e+=m,t.push({bucketName:r,countingResults:p.map(t=>t.award),droppedResults:l.map(t=>t.award),bucketTotal:m})}return{buckets:t,totalPoints:e}}const{counting:s,dropped:c,bucketTotal:u}=$_({awards:a,pointComponents:["points","qualityWinPoints"],bestOfCount:o||0,maxResultsPerLevel:i});return{buckets:[{bucketName:"All",countingResults:s.map(t=>t.award),droppedResults:c.map(t=>t.award),bucketTotal:u}],totalPoints:u}}function z_({entries:t,filter:e,asOfDate:n,participantContext:r}){const i=t.filter(t=>function(t,e,n,r){if(e.ageRange){if(!r?.ageAtDate)return!1;const i=r.ageAtDate(t.personId,n);if(void 0===i)return!1;if(void 0!==e.ageRange.min&&i<e.ageRange.min)return!1;if(void 0!==e.ageRange.max&&i>e.ageRange.max)return!1}if(e.excludePlayersAgingUp){if(!r?.isAgingUpAtPeriodEnd)return!0;if(r.isAgingUpAtPeriodEnd(t.personId))return!1}return!0}(t,e,n,r));return i.map((t,e)=>({...t,rank:e+1}))}function Y_({pointAwards:t,aggregationRules:e={},categoryFilter:n,asOfDate:r,pointPoolModel:i="per-category"}){const{rollingPeriodDays:o,countingBuckets:a,tiebreakCriteria:s=[],minCountableResults:c=0,maxResultsPerLevel:u,bestOfCount:d,categoryAggregation:p=[]}=e,l=function(t,e,n,r){let i=t;e&&(i=i.filter(t=>{if(e.ageCategoryCodes?.length){const n=t.category?.ageCategoryCode;if(!n||!e.ageCategoryCodes.includes(n))return!1}if(e.genders?.length){const n=t.category?.gender||t.gender;if(!n||!e.genders.includes(n))return!1}return!(e.eventTypes?.length&&(!t.eventType||!e.eventTypes.includes(t.eventType)))}));if(n&&r){const t=new Date(r);t.setDate(t.getDate()-n);const e=t.getTime();i=i.filter(t=>!t.endDate||new Date(t.endDate).getTime()>=e)}return i}(t,n,o,r),m=function(t){const e={};for(const n of t){const t=n.personId;t&&(e[t]||(e[t]=[]),e[t].push(n))}return e}(l),f="shared"===i?{}:function({pointAwards:t,rules:e,categoryFilter:n,rollingPeriodDays:r,asOfDate:i}){const o={};if(!e.length)return o;for(const a of e){if(!K_(a.target,n))continue;const e=X_(t.filter(t=>Q_(t,a.source)&&!J_(t,a.excludedSourceFilters)),r,i),s={};for(const t of e){const e=t.personId;if(!e)continue;const n=Z_(t,a);s[e]||(s[e]=[]),s[e].push(n)}for(const[t,e]of Object.entries(s)){const n=[...e].sort((t,e)=>(e.points??0)-(t.points??0)),r=a.maxCarriedResults?n.slice(0,a.maxCarriedResults):n;o[t]||(o[t]=[]),o[t].push(...r)}}return o}({pointAwards:t,rules:p,categoryFilter:n,rollingPeriodDays:o,asOfDate:r}),h=function({nativeByPerson:t,carriedByPerson:e,rules:n,categoryFilter:r}){const i=new Set([...Object.keys(t),...Object.keys(e)]),o=[],a=n.filter(t=>K_(t.target,r));for(const e of i){const n=t[e]?.length??0;a.every(t=>(!t.requireParticipationInTarget||0!==n)&&!(void 0!==t.minResultsFromTarget&&n<t.minResultsFromTarget))&&o.push(e)}return o}({nativeByPerson:m,carriedByPerson:f,rules:"shared"===i?[]:p,categoryFilter:n}),g=[];for(const t of h){const e=tL({countingBuckets:a,minCountableResults:c,maxResultsPerLevel:u,bestOfCount:d,personId:t,awards:[...m[t]??[],...f[t]??[]]});g.push(e)}return function(t,e){t.sort((t,e)=>e.totalPoints-t.totalPoints),e.length&&t.sort((t,n)=>{if(t.totalPoints!==n.totalPoints)return n.totalPoints-t.totalPoints;for(const r of e){const e=nL(r,t,n);if(0!==e)return e}return 0});let n=1;for(let r=0;r<t.length;r++){if(r>0&&t[r].totalPoints===t[r-1].totalPoints){const i=e.some(e=>0!==nL(e,t[r-1],t[r]));t[r].rank=i?n:t[r-1].rank}else t[r].rank=n;n=r+2}}(g,s),g}function K_(t,e){if(!e)return!0;if(!(!e.ageCategoryCodes?.length||!t.ageCategoryCodes?.length||t.ageCategoryCodes.some(t=>e.ageCategoryCodes.includes(t))))return!1;return!e.genders?.length||!t.genders?.length||t.genders.some(t=>e.genders.includes(t))}function Q_(t,e){if(e.ageCategoryCodes?.length){const n=t.category?.ageCategoryCode;if(!n||!e.ageCategoryCodes.includes(n))return!1}if(e.genders?.length){const n=t.category?.gender||t.gender;if(!n||!e.genders.includes(n))return!1}if(e.categoryNames?.length){const n=t.category?.categoryName;if(!n||!e.categoryNames.includes(n))return!1}if(e.ratingTypes?.length){const n=t.category?.ratingType;if(!n||!e.ratingTypes.includes(n))return!1}return!0}function J_(t,e){return!!e?.length&&e.some(e=>!(!e.levels?.length||void 0===t.level||!e.levels.includes(t.level))||(!!(e.drawTypes?.length&&t.drawType&&e.drawTypes.includes(t.drawType))||!!(e.eventTiers?.length&&t.eventTier&&e.eventTiers.includes(t.eventTier))))}function X_(t,e,n){if(!e||!n)return t;const r=new Date(n);r.setDate(r.getDate()-e);const i=r.getTime();return t.filter(t=>!t.endDate||new Date(t.endDate).getTime()>=i)}function Z_(t,e){const n=e.multiplier??1,r=e.carryComponents??["positionPoints","perWinPoints","qualityWinPoints","bonusPoints"],i={...t,carriedFromRule:e.ruleName,subjectToBucketLimits:e.subjectToBucketLimits??!0},o=["positionPoints","perWinPoints","qualityWinPoints","bonusPoints"];for(const t of o)r.includes(t)||(i[t]=0);i.points=Math.round((t.points??0)*n);for(const e of r)"number"==typeof t[e]&&(i[e]=Math.round(t[e]*n));return"number"==typeof t.linePoints&&(i.linePoints=Math.round(t.linePoints*n)),i}function tL({countingBuckets:t,minCountableResults:e,maxResultsPerLevel:n,bestOfCount:r,personId:i,awards:o}){let a,s=0,c=[],u=[];if(t?.length){a=[];for(const e of t){const{bucketName:t,eventTypes:n,pointComponents:r,bestOfCount:i,maxResultsPerLevel:d,mandatoryRules:p}=e;let l=o;n?.length&&(l=l.filter(t=>t.eventType&&n.includes(t.eventType)));const m=l.filter(t=>!1!==t.subjectToBucketLimits),f=l.filter(t=>!1===t.subjectToBucketLimits),{counting:h,dropped:g,bucketTotal:I}=$_({awards:m,pointComponents:r,bestOfCount:i,maxResultsPerLevel:d,mandatoryRules:p}),S=f.map(t=>({award:t,value:eL(t,r)})),y=I+S.reduce((t,e)=>t+e.value,0);s+=y,c.push(...h.map(t=>t.award)),c.push(...S.map(t=>t.award)),u.push(...g.map(t=>t.award)),a.push({bucketName:t,countingResults:[...h.map(t=>t.award),...S.map(t=>t.award)],droppedResults:g.map(t=>t.award),bucketTotal:y})}}else{const t=o.filter(t=>!1!==t.subjectToBucketLimits),e=o.filter(t=>!1===t.subjectToBucketLimits),{counting:i,dropped:a,bucketTotal:d}=$_({awards:t,pointComponents:["points","qualityWinPoints"],bestOfCount:r||0,maxResultsPerLevel:n}),p=e.map(t=>({award:t,value:eL(t,["points","qualityWinPoints"])}));s=d+p.reduce((t,e)=>t+e.value,0),c=[...i.map(t=>t.award),...p.map(t=>t.award)],u=a.map(t=>t.award)}const d={personId:i,totalPoints:s,rank:0,meetsMinimum:c.length>=e,countingResults:c,droppedResults:u};return a&&(d.bucketBreakdown=a),d}function eL(t,e){const n=e??["points"];let r=0;for(const e of n)"number"==typeof t[e]&&(r+=t[e]);return r}function nL(t,e,n){switch(t){case"highestSingleResult":{const t=Math.max(0,...e.countingResults.map(t=>t.points||0));return Math.max(0,...n.countingResults.map(t=>t.points||0))-t}case"mostCountingResults":return n.countingResults.length-e.countingResults.length;case"mostWins":{const t=e.countingResults.reduce((t,e)=>t+(e.winCount||0),0);return n.countingResults.reduce((t,e)=>t+(e.winCount||0),0)-t}default:return 0}}function rL({tournamentRecord:t,policyDefinitions:e,participantFilters:n,scaleName:r="RANKING_POINTS",level:i,removePriorValues:o}){if(!t)return{error:rt};const a=xM({tournamentRecord:t,policyDefinitions:e,participantFilters:n,level:i});if(a.error)return a;const{personPoints:s,pairPoints:c,teamPoints:u}=a,d={};for(const e of t.participants??[])e.person?.personId&&(d[e.person.personId]=e.participantId);const p=t.endDate;let l=0;for(const[e,n]of Object.entries(s)){const i=d[e];if(!i)continue;const a={};for(const t of n){const e=t.eventType||"SINGLES";a[e]||(a[e]=[]),a[e].push(t)}for(const[e,n]of Object.entries(a)){const a=n.reduce((t,e)=>t+(e.points||0)+(e.qualityWinPoints||0)+(e.linePoints||0),0),s=_D({tournamentRecord:t,participantId:i,scaleItem:{scaleType:Iu,scaleName:r,eventType:e,scaleDate:p,scaleValue:{points:a,awards:n}},removePriorValues:o});if(s.error)return s;l++}}return{...Y,personPoints:s,pairPoints:c,teamPoints:u,modificationsApplied:l}}var iL={__proto__:null,applyDerivedRankings:z_,applyTournamentRankingPoints:rL,generateRankingList:Y_,getApplicableAwardProfileLevels:hM,getAwardPoints:bM,getAwardProfile:lM,getEventRankingPoints:_M,getParticipantPoints:H_,getQualityWinPoints:DM,getTournamentPointAwards:W_,getTournamentPoints:xM,mutate:{__proto__:null,applyTournamentRankingPoints:rL},query:{__proto__:null,applyDerivedRankings:z_,generateRankingList:Y_,getApplicableAwardProfileLevels:hM,getAwardPoints:bM,getAwardProfile:lM,getEventRankingPoints:_M,getParticipantPoints:H_,getQualityWinPoints:DM,getTournamentPointAwards:W_,getTournamentPoints:xM}};function oL({withCompetitiveProfiles:t,opponentParticipantId:e,withIndividualStats:n,teamParticipantId:r,tournamentRecord:i,withScaleValues:a,tallyPolicy:s,matchUps:c}){if(!i)return{error:rt};if(c&&!Array.isArray(c))return{error:ye};if(c=c??Qg({tournamentRecord:i,participantsProfile:a?{withScaleValues:a}:void 0}).matchUps,!c?.length)return{error:Ie};const u=[];e&&u.push(e),r&&u.push(r);const d=xS({participantFilters:u.length?{participantIds:u}:{participantTypes:[hm]},tournamentRecord:i}).participants??[];if(!d.every(({participantType:t})=>t===hm))return{error:tn};u.length||u.push(...d.map(Xp));const p=new Map,l=new Map,m=new Map,h=new Map,g=(t,e="")=>l.get(t)||l.set(t,{participantName:e,participantId:t,competitorIds:[],competitiveness:{},matchUpStatuses:{},tiebreaks:[0,0],matchUps:[0,0],points:[0,0],games:[0,0],sets:[0,0]})&&l.get(t);for(const t of d){const{participantId:e,individualParticipantIds:n}=t;h.set(e,n??[]),g(e,t.participantName)}if(r&&!h.get(r))return Ci({result:{error:un},context:{teamParticipantId:r}});if(e&&!h.get(e))return Ci({result:{error:un},context:{opponentParticipantId:e}});const I=[];for(const i of c){if(!f(i))return{error:ye};const{matchUpStatus:a,matchUpFormat:c,matchUpType:u,winningSide:d,score:m,sides:S}=i;if(!S||!m||u===o||a===Sp)continue;const y=sL({sides:S,participantDetails:p,participantStats:l,teamMap:h,withIndividualStats:n,teamParticipantId:r,opponentParticipantId:e});if(!y.filter(Boolean).length)continue;const v=t&&d&&Ff({matchUp:i})?.competitiveness;I.push(i);const U=OI({matchUpStatus:a,matchUpFormat:c,tallyPolicy:s,winningSide:d,score:m}),P=kI({matchUpStatus:a,matchUpFormat:c,tallyPolicy:s,winningSide:d,score:m}),{pointsTally:T,tiebreaksTally:w}=FI({matchUpFormat:c,score:m});dL({tallies:{setsTally:U,gamesTally:P,pointsTally:T,tiebreaksTally:w},sideParticipantIds:y,participantDetails:p,competitiveness:v,matchUpStatus:a,winningSide:d,initStats:g})}const S=function(t,e){const n=new Map,r=(t,e)=>(t??0)+(e??0);for(const[i,o]of t.entries()){for(const t of cL){const a=o[t].reduce(r);if(a){const r=o[t][0]/a,s=`${t}Ratio`,c=parseFloat(r.toFixed(2));o[s]=c,e.set(i,!0),n.has(s)||n.set(s,[]),n.get(s)?.push(c)}}for(const t of uL){const e=o.competitiveness?.[t]?.reduce(r);if(e){const n=o.competitiveness[t][0]/e,r=`${t}Ratio`,i=parseFloat(n.toFixed(2));o[r]=i}}}return n}(l,m);r||function(t,e){const n=(t,e)=>e-t;for(const r of t.values())for(const t of cL){const i=`${t}Ratio`;if("number"==typeof r[i]){const o=e.get(i)?.sort(n).indexOf(r[i]);if("number"==typeof o&&o>=0){r[`${t}Rank`]=o+1}}}}(l,S);const y={relevantMatchUps:I,...Y};return r?(y.teamStats=l.get(r),e&&(y.opponentStats=l.get(e))):y.participatingTeamsCount=m.size,y.allParticipantStats=[...l.values()],y}function aL({side:t,individualParticipantIds:e}){return t.participantId&&(!e?.length||e.includes(t.participantId))&&[t.participantId]||t.participant?.individualParticipantIds?.length&&(!e?.length||V(e,t.participant?.individualParticipantIds).length===t.participant?.individualParticipantIds?.length)&&t.participant.individualParticipantIds}function sL({sides:t,participantDetails:e,participantStats:n,teamMap:r,withIndividualStats:i,teamParticipantId:o,opponentParticipantId:a}){const s=[[],[]];for(const r of t){const t=r.participant;if(t?.participantName){e.set(t.participantId,{participantName:t.participantName,ratings:t.ratings});const r=n.get(t.participantId);r&&(r.participantName=t.participantName)}}if(r.size)!function({sides:t,sideParticipantIds:e,participantStats:n,teamMap:r,withIndividualStats:i,teamParticipantId:o,opponentParticipantId:a}){const s=(r,o)=>{for(const a of t){if(!a.participant)continue;const t=aL({individualParticipantIds:o,side:a});if(t?.length){const o=a.sideNumber;if(!o)continue;const s=[r];i&&s.push(...t),e[o-1]=s;const c=n.get(r);for(const e of t.filter(Boolean))c&&!c.competitorIds.includes(e)&&c.competitorIds.push(e)}}};if(o){(!a||t.every(t=>t.participant&&(aL({individualParticipantIds:r.get(o),side:t})||aL({individualParticipantIds:r.get(a),side:t}))))&&s(o,r.get(o))}else for(const[t,e]of r)s(t,e)}({sides:t,sideParticipantIds:s,participantStats:n,teamMap:r,withIndividualStats:i,teamParticipantId:o,opponentParticipantId:a});else if(i)for(const e of t){if(!e.participant)continue;const t=aL({individualParticipantIds:[],side:e}),n=e.sideNumber;n&&(s[n-1]=t)}return s}const cL=["tiebreaks","matchUps","points","games","sets"],uL=["competitive","routine","decisive"];function dL({tallies:t,sideParticipantIds:e,participantDetails:n,competitiveness:r,matchUpStatus:i,winningSide:o,initStats:a}){e.forEach((e,s)=>{for(const c of e){const e=n.get(c)?.participantName,u=a(c,e);u&&(pL({stats:u,tallies:t,index:s}),lL({stats:u,winningSide:o,index:s}),mL({stats:u,competitiveness:r,index:s}),fL({stats:u,matchUpStatus:i}))}})}function pL({stats:t,tallies:e,index:n}){const{setsTally:r,gamesTally:i,pointsTally:o,tiebreaksTally:a}=e,s=(e,n)=>n.forEach((n,r)=>t[e][r]+=n);s("tiebreaks",n?[...a].reverse():a),s("points",n?[...o].reverse():o),s("games",n?[...i].reverse():i),s("sets",n?[...r].reverse():r)}function lL({stats:t,winningSide:e,index:n}){if(e){const r=e-1===n?0:1;t.matchUps[r]+=1}}function mL({stats:t,competitiveness:e,index:n}){if(e){const r=e.toLowerCase();t.competitiveness[r]||(t.competitiveness[r]=[0,0]),t.competitiveness[r][n]+=1}}function fL({stats:t,matchUpStatus:e}){if(e){const n=e.toLowerCase();t.matchUpStatuses[n]||(t.matchUpStatuses[n]=0),t.matchUpStatuses[n]+=1}}const hL="entries.entryStatus",gL="structure.drawReport",IL="participant.teamStats",SL="participant.results",yL="venue.utilization",vL="matchUp.results",UL="matchUp.statusSummary",PL="participant.seedingPerformance",TL="matchUp.competitiveness",wL="audit.drawRevisions",DL="audit.schedulingChurn",RL="audit.mutationLog",bL="audit.positionChanges",NL={ENTRIES:"Entries",DRAWS:"Draws",MATCHUPS:"MatchUps",PARTICIPANTS:"Participants",SCHEDULING:"Scheduling",AUDIT:"Audit"},ML={FACTORY:"factory",SERVER:"server"};var AL={__proto__:null,COMPETITIVENESS_REPORT:TL,DRAW_REVISIONS_REPORT:wL,ENTRY_STATUS_REPORT:hL,MATCHUP_STATUS_REPORT:UL,MATCH_RESULTS_REPORT:vL,MUTATION_LOG_REPORT:RL,PARTICIPANT_RESULTS_REPORT:SL,PARTICIPANT_STATS_REPORT:IL,POSITION_CHANGES_REPORT:bL,REPORT_CATEGORIES:NL,REPORT_SOURCE:ML,SCHEDULING_CHURN_REPORT:DL,SEEDING_PERFORMANCE_REPORT:PL,STRUCTURE_REPORT:gL,VENUE_UTILIZATION_REPORT:yL};const EL=[{reportId:hL,name:"Entry Status Report",description:"Entry statuses and participant details across all events and draws",category:NL.ENTRIES},{reportId:gL,name:"Draw Structure Report",description:"Draw structures with size, matchUp counts, winners, and seeding basis",category:NL.DRAWS},{reportId:vL,name:"Match Results",description:"All completed match results by round with scores",category:NL.MATCHUPS},{reportId:UL,name:"MatchUp Status Summary",description:"Completed, walkovers, defaults, and retirements aggregated by event",category:NL.MATCHUPS},{reportId:TL,name:"Match Competitiveness",description:"Competitive profile of each match — decisive, routine, or competitive",category:NL.MATCHUPS},{reportId:SL,name:"Participant Results",description:"Per-participant wins, losses, sets, and games across all events",category:NL.PARTICIPANTS},{reportId:PL,name:"Seeding Performance",description:"Seeded participants — expected vs actual finishing position",category:NL.PARTICIPANTS},{reportId:IL,name:"Team Statistics",description:"Team participant win/loss statistics across matchUps, sets, games, and tiebreaks",category:NL.PARTICIPANTS},{reportId:yL,name:"Venue Utilization",description:"Court availability and scheduling utilization by venue and date",category:NL.SCHEDULING},{reportId:RL,name:"Mutation Log",description:"Chronological log of all server mutations with user attribution",category:NL.AUDIT,source:ML.SERVER},{reportId:wL,name:"Draw Revision History",description:"Timeline of draw changes — position assignments, seeding, generation",category:NL.AUDIT,source:ML.SERVER},{reportId:DL,name:"Scheduling Churn",description:"Scheduling changes — bulk schedules, reschedules, clears",category:NL.AUDIT,source:ML.SERVER},{reportId:bL,name:"Position Changes",description:"Draw position assignment changes over time",category:NL.AUDIT,source:ML.SERVER}];function CL({participant:t,eventType:e}){const n=t?.person?.personId,r=t?.person?.personOtherIds?.[0],i=t?.person?.tennisId,o=t?.ratings?.[e]?.find(({scaleName:t})=>t===$d),a=o?.scaleValue,{wtnRating:s,confidence:c}=a??{};return{timeStamp:o?.scaleDate,personOtherId:r,confidence:c,wtnRating:s,personId:n,tennisId:i}}function OL({tournamentRecord:t}){if(!t)return{error:rt};const n=t.tournamentId,{participantMap:i}=xS({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:t,withDraws:!0}),o=(Qg({matchUpFilters:{matchUpTypes:[e,r]},tournamentRecord:t}).matchUps??[]).flatMap(({sides:t,matchUpType:e})=>t?.flatMap(t=>e===r?t?.participant?.individualParticipantIds:t?.participant?.participantId||t.participantId).filter(Boolean)).filter(Boolean),a=[],s={},c={},u={};let d=0;const p=({id:t,entry:e,eventId:r,eventType:o})=>{const{qualifyingSeeding:c,mainSeeding:u,entryStatus:d,entryStage:p,drawId:l}=e;s[t]||(s[t]=[]);const{participant:m,events:f}=i?.[t]??{},h=CL({participant:m,eventType:o}),g=f?.[r]?.ranking;d===TP&&a.push(t),s[t].push({participantType:m?.participantType,participantId:t,tournamentId:n,eventType:o,eventId:r,drawId:l,entryStatus:d,entryStage:p,...h,ranking:g,mainSeeding:u,qualifyingSeeding:c})};for(const e of t.events??[]){const t={},r=e=>{t[e]||(t[e]={count:0}),t[e].count+=1},{drawDefinitions:a=[],eventType:s,eventId:l}=e,m=a.flatMap(t=>{const{drawId:e,entries:n}=t;d+=1;const o=(t.structures??[]).filter(({stage:t,stageSequence:e})=>t===us&&1===e||t===ds).flatMap(({positionAssignments:t})=>t).filter(Boolean).map(({participantId:t})=>t);return n?.filter(({participantId:t})=>o.includes(t)).map(t=>{const{participantId:n,entryStatus:o,entryStage:a}=t;r(o);const s=i?.[n]?.draws?.[e]?.seedAssignments,c=s?.[us]?.seedValue??s?.[us]?.seedNumber;return{qualifyingSeeding:s?.[ds]?.seedValue??s?.[ds]?.seedNumber,participantId:n,mainSeeding:c,entryStatus:o,entryStage:a,drawId:e}})}),f=t=>{const e=t.participantId,n=i?.[e].participant.individualParticipantIds?.filter(t=>o.includes(t));return e&&{[e]:{individualParticipantIds:n}}};s===rs?(()=>{const t=Object.assign({},...m.map(f).filter(Boolean));m.forEach(e=>{t[e.participantId].individualParticipantIds.forEach(t=>{p({id:t,eventType:s,eventId:l,entry:e})})})})():m.forEach(t=>{p({id:t?.participantId,eventType:s,eventId:l,entry:t})});const h=Object.values(t).reduce((t,e)=>t+e.count,0);Object.keys(t).forEach(e=>{t[e].pct=t[e].count/h*100}),u[l]={tournamentId:n,eventId:l,entries:m,entryStatuses:t};const g=Object.assign({},...Sf.flatMap(e=>[{[e+"_count"]:t[e]?.count},{[e+"_pct"]:t[e]?.pct}]));c[l]={tournamentId:n,eventId:l,...g}}const l=Object.values(i??{}).filter(({participant:{participantType:t,participantRole:e}})=>t===gm&&e===sy),m=l.filter(({participant:t})=>!o.includes(t.participantId)).map(({participant:t})=>t.participantId),f={nonParticipatingEntriesCount:m.length,individualParticipantsCount:l.length,eventsCount:Object.values(u).length,nonParticipatingParticipantIds:m,drawDefinitionsCount:d,tournamentId:n};return{entryStatusReports:Object.values(c).flat(),participantEntryReports:Object.values(s).flat(),eventReports:Object.values(u).flat(),withDrawnParticipantIds:a,tournamentEntryReport:f}}function kL({eventType:t,matchUps:e,eventId:n,drawId:r}){const i={},o=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),{}),a=Object.values(o),s=a.map(e=>CL({participant:e,eventType:t})).filter(({wtnRating:t})=>t),c=(a.length-s.length)/a.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}}function FL(t){const{tournamentRecord:e,extensionProfiles:n,firstFlightOnly:r,firstStageSequenceOnly:i=!0}=t;if(!e)return{error:ot};const o=[],a={},s={},c=[],u=Object.assign({},...(n??[]).map(({name:t,label:n,accessor:r})=>{const i=td({element:e,name:t})?.extension?.value,o=r?Bd({element:i,accessor:r})?.value:i;return{[n??t]:o}})),d=e?.tournamentId,p=Qg({participantsProfile:{withScaleValues:!0},tournamentRecord:e}).matchUps??[],l=t=>{const e=Nm({itemType:fl,itemSubTypes:[vu],element:{timeItems:t}})?.timeItem;return e?.itemValue?.scaleBasis},m=e?.events?.flatMap(({timeItems:t,drawDefinitions:e=[],extensions:n,eventType:c,eventName:m,eventId:f,category:h,flightProfile:g})=>{const I=g??n?.find(t=>t.name===ld)?.value,S=I?.flights?.map(t=>({[t.drawId]:t.flightNumber})),y=S&&Object.assign({},...S),v=n?.find(t=>t.name===dd),U=t?.find(t=>t.itemType===dd),P=v?.value?.length??U?.itemValue??0,T=Object.values(y??{}),w=y&&Math.min(...T),D=l(t);return s[f]={seedingBasis:D?JSON.stringify(D):void 0,totalPositionManipulations:0,maxPositionManipulations:0,generatedDrawsCount:0,drawDeletionsCount:P,tournamentId:d,eventId:f},e.filter(t=>!r||!S||y[t.drawId]===w).flatMap(t=>{const{matchUpFormat:e,tieFormat:n,timeItems:r,extensions:g,structures:I,drawName:S,drawType:v,drawId:U}=t,{matchUpFormatCounts:P,matchUpsCount:T,avgConfidence:w,pctNoRating:R,avgWTN:b}=kL({eventType:c,matchUps:p,drawId:U}),N=l(r)??D,M=function({extensions:t}){return t?.find(({name:t})=>t===yd)?.value?.slice(1)}({extensions:g}),A=M?.length??0;return(({positionManipulations:t})=>{t?.forEach(t=>{const{structureId:e,name:n}=t,r=t.drawPositions??[t.drawPosition];a[e]??=[],a[e].push(`${n}: ${r.join("/")}`)})})({positionManipulations:M}),s[f].totalPositionManipulations+=A,s[f].generatedDrawsCount+=1,A>s[f].maxPositionManipulations&&(s[f].maxPositionManipulations=A),I?.filter(t=>(1===t.stageSequence||!i)&&[ds,us,ps,ms].includes(t.stage)).map(t=>{const r=[us,ms].includes(t.stage)?function(t,e){return t.find(t=>t.structureId===e&&1===t.finishingRound&&t.winningSide)}(p,t.structureId):void 0;t.stage===us&&o.push({eventName:m,drawName:S,structureId:t.structureId});const i=function(t){return t?.sides?t.sides.find(e=>e.sideNumber===t.winningSide):void 0}(r),a=i?.participant,s=function(t){return t?.participantType===hm?t.participantId:void 0}(a),l=function(t){return t?.participantType===Sm?t.individualParticipants??[]:[]}(a),g=CL({participant:l?.[0]??a,eventType:c}),{personId:I,personOtherId:D,tennisId:A,confidence:E,wtnRating:C}=g??{},O=CL({participant:l?.[1],eventType:c}),{personId:k,personOtherId:F,tennisId:x,confidence:_,wtnRating:L}=O??{},{ageCategoryCode:B,categoryName:V,subType:G}=h??{},j=t.matchUpFormat??e,q=(P[j]??0)/T*100,{tieFormatName:W,tieFormatDesc:$}=MA(n),{tieFormatName:H,tieFormatDesc:z}=MA(t.tieFormat),Y=$===z,K=!Y&&H,Q=t.tieFormat&&!Y&&z,J=M?.filter((X=t.structureId,t=>t.structureId===X))?.length??0;var X;return{...u,tournamentId:d,eventId:f,structureId:t.structureId,drawId:U,eventType:c,category:G,categoryName:V,ageCategoryCode:B,flightNumber:y?.[U],drawType:v,stage:t.stage,seedingBasis:N?JSON.stringify(N):void 0,winningPersonId:I,winningPersonOtherId:D,winningPersonTennisId:A,winningPersonWTNrating:C,winningPersonWTNconfidence:E,winningPerson2Id:k,winningPerson2OtherId:F,winningPerson2TennisId:x,winningPerson2WTNrating:L,winningPerson2WTNconfidence:_,winningTeamId:s,positionManipulations:J,pctNoRating:R,matchUpFormat:j,pctInitialMatchUpFormat:q,matchUpsCount:T,drawTieFormatName:W,drawTieFormatDesc:$,tieFormatName:K,tieFormatDesc:Q,avgConfidence:w,avgWTN:b}})})});return o.forEach(({eventName:t,drawName:e,structureId:n})=>{a[n]?.length&&c.push({eventName:t,drawName:e,actions:a[n]})}),{eventStructureReports:Object.values(s),structureReports:m,flightReports:c}}function xL(t,e){return t&&e?t<e?"Overperformed":t>e?"Underperformed":"As expected":""}function _L(t){const e=t?.finishingPositionRange,n=e?.[0]??"",r=e?.[1]??n;return n===r?`${n}`:`${n}-${r}`}function LL(t,e,n,r){const i=Nw({drawDefinition:e,tournamentRecord:r,event:t});if(!i||i.error)return[];const o=[];for(const[r,a]of Object.entries(i)){const i=n?.[r];if(!i)continue;const s=i.draws?.[e.drawId]?.seedAssignments?.[us],c=s?.seedValue??s?.seedNumber;if(!c)continue;const u=_L(a),d=a.finishingPositionRange?.[0]??0;o.push({participantId:r,participantName:i.participant?.participantName??"",eventName:t.eventName??"",drawName:e.drawName??"",seedValue:c,finishingPosition:u,expectedPosition:`${c}`,performance:xL(d,c)})}return o}function BL(t,e){return t?e===r?t.participant?.individualParticipantIds??[t.participantId].filter(Boolean):[t.participantId??t.participant?.participantId].filter(Boolean):[]}function VL({ignoreDisabled:t=!0,tournamentRecords:e,tournamentId:n,venueIds:r=[],dates:i=[]}){if(!Array.isArray(i))return{error:sr,dates:i};if(!Array.isArray(r))return{error:sr,venueIds:r};if(!((e&&Object.keys(e).filter(t=>!n||t===n))??[]).length)return{error:nt};if(!i.every(Do))return{error:_e};const o=gw({tournamentRecords:e,ignoreDisabled:t,dates:i});if(o.error)return o;const a=o?.venues?.filter(({venueId:t})=>!r?.length||r.includes(t)),s=o.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:a?.map(({venueId:t})=>t)},{matchUps:u}=Jg({afterRecoveryTimes:!0,tournamentRecords:e,matchUpFilters:c}),d=a?.map(t=>function(t,e,n){const{venueId:r,courts:i,venueName:o}=e,a={};return t.forEach(t=>{let e=0,o=0,s=0;for(const n of i){const r=n.dateAvailability.find(e=>e.date===t),i=r&&vO({courtDate:r}).timeSlots,o=i?.reduce((t,e)=>{const{startTime:n,endTime:r}=e;return t+(Fo(r)-Fo(n))},0);o&&(s+=1),e+=o}const c=n.filter(({schedule:e})=>e.venueId===r&&Ko(t,e.scheduledDate));c.forEach(({schedule:t})=>{const e=_o(t.scheduledTime),n=Fo(Ho(e,t.averageMinutes))-Fo(e);o+=n});const u=e?(o/e*100).toFixed(2):"100";a[t]={scheduledMatchUpsCount:c.length,availableCourts:s,availableMinutes:e,scheduledMinutes:o,percentUtilization:u}}),{venueId:r,venueName:o,venueReport:a}}(s,t,u));return{venuesReport:d}}const GL={error:"Invalid reportId"},jL={[hL]:function({tournamentRecord:t}){const e=OL({tournamentRecord:t});if(e.error)return e;const n={};for(const e of t.participants??[])n[e.participantId]=e.participantName??"";const r={},i={};for(const e of t.events??[]){r[e.eventId]=e.eventName??"";for(const t of e.drawDefinitions??[])i[t.drawId]=t.drawName??""}const o=(e.participantEntryReports??[]).map(t=>({participantId:t.participantId??"",participantName:n[t.participantId]||"",eventId:t.eventId??"",eventName:r[t.eventId]||"",drawId:t.drawId??"",drawName:i[t.drawId]||"",entryStatus:t.entryStatus??"",entryStage:t.entryStage??"",ranking:t.ranking??"",mainSeeding:t.mainSeeding??"",qualifyingSeeding:t.qualifyingSeeding??""}));return{reportId:hL,generatedAt:(new Date).toISOString(),columns:[{key:"participantName",title:"Participant",type:"string"},{key:"eventName",title:"Event",type:"string"},{key:"drawName",title:"Draw",type:"string"},{key:"entryStatus",title:"Entry Status",type:"string"},{key:"entryStage",title:"Stage",type:"string"},{key:"ranking",title:"Ranking",type:"number"},{key:"mainSeeding",title:"Main Seed",type:"number"},{key:"qualifyingSeeding",title:"Qualifying Seed",type:"number"}],rows:o,summary:e.tournamentEntryReport??{}}},[gL]:function({tournamentRecord:t}){const e=FL({tournamentRecord:t});if(e.error)return e;const n={},r={},i={};for(const e of t.events??[]){n[e.eventId]=e.eventName??"";for(const t of e.drawDefinitions??[]){r[t.drawId]=t.drawName??"";const e=t.structures?.find(t=>"MAIN"===t.stage&&1===t.stageSequence);e?.positionAssignments&&(i[t.drawId]=e.positionAssignments.length)}}const o={};for(const e of t.participants??[])o[e.participantId]=e.participantName??"",e.person?.personId&&(o[e.person.personId]=e.participantName??"");const a=(e.structureReports??[]).map(t=>{const e=o[t.winningPersonId]||o[t.winningTeamId]||"";return{eventId:t.eventId??"",eventName:n[t.eventId]||"",drawId:t.drawId??"",drawName:r[t.drawId]||"",stage:t.stage??"",drawType:t.drawType??"",drawSize:i[t.drawId]??"",matchUpsCount:t.matchUpsCount??"",winner:e,seedingBasis:t.seedingBasis??""}});return{reportId:gL,generatedAt:(new Date).toISOString(),columns:[{key:"eventName",title:"Event",type:"string"},{key:"drawName",title:"Draw",type:"string"},{key:"stage",title:"Stage",type:"string"},{key:"drawType",title:"Draw Type",type:"string"},{key:"drawSize",title:"Draw Size",type:"number"},{key:"matchUpsCount",title:"MatchUps",type:"number"},{key:"winner",title:"Winner",type:"string"},{key:"seedingBasis",title:"Seeding Basis",type:"string"}],rows:a,summary:{eventStructureReports:e.eventStructureReports??[],flightReports:e.flightReports??[]}}},[vL]:function({tournamentRecord:t}){const{matchUps:e}=Qg({tournamentRecord:t});if(!e)return{error:"No matchUps found"};const n=e.filter(t=>_p.includes(t.matchUpStatus)).toSorted((t,e)=>(t.roundNumber??0)-(e.roundNumber??0)||(t.roundPosition??0)-(e.roundPosition??0)).map(t=>{const e=t.sides?.[0]?.participant?.participantName??"",n=t.sides?.[1]?.participant?.participantName??"",r=t.winningSide?t.sides?.[t.winningSide-1]:void 0,i=t.score?.scoreStringSide1??"";return{roundName:t.roundName??`R${t.roundNumber??""}`,side1:e,side2:n,score:i,matchUpStatus:t.matchUpStatus??"",winnerName:r?.participant?.participantName??""}});return{reportId:vL,generatedAt:(new Date).toISOString(),columns:[{key:"roundName",title:"Round",type:"string"},{key:"side1",title:"Side 1",type:"string"},{key:"side2",title:"Side 2",type:"string"},{key:"score",title:"Score",type:"string"},{key:"matchUpStatus",title:"Status",type:"string"},{key:"winnerName",title:"Winner",type:"string"}],rows:n}},[UL]:function({tournamentRecord:t}){const{matchUps:e}=Qg({tournamentRecord:t});if(!e)return{error:"No matchUps found"};const n=e.filter(t=>_p.includes(t.matchUpStatus)),r={},i={};for(const e of t.events??[]){r[e.eventId]=e.eventName??"";for(const t of e.drawDefinitions??[])i[t.drawId]=t.drawName??""}const o={};for(const t of n){const e=t.eventId??"unknown",n=t.matchUpStatus??"UNKNOWN";o[e]??={},o[e][n]=(o[e][n]??0)+1}const a=[];for(const[t,e]of Object.entries(o)){const n=Object.values(e).reduce((t,e)=>t+e,0);for(const[i,o]of Object.entries(e))a.push({eventId:t,eventName:r[t]||t,status:i,count:o,percentage:n>0?Math.round(o/n*100):0})}return a.sort((t,e)=>t.eventName.localeCompare(e.eventName)||e.count-t.count),{reportId:UL,generatedAt:(new Date).toISOString(),columns:[{key:"eventName",title:"Event",type:"string"},{key:"status",title:"Status",type:"string"},{key:"count",title:"Count",type:"number"},{key:"percentage",title:"% of Event",type:"number"}],rows:a}},[TL]:function({tournamentRecord:t}){const{matchUps:e}=Qg({tournamentRecord:t});if(!e)return{error:"No matchUps found"};const n=e.filter(t=>_p.includes(t.matchUpStatus)).toSorted((t,e)=>(t.roundNumber??0)-(e.roundNumber??0)||(t.roundPosition??0)-(e.roundPosition??0)).map(e=>{const n=Ff({matchUp:e,tournamentRecord:t});return{roundName:e.roundName??`R${e.roundNumber??""}`,side1:e.sides?.[0]?.participant?.participantName??"",side2:e.sides?.[1]?.participant?.participantName??"",score:e.score?.scoreStringSide1??"",competitiveness:n.competitiveness??"",pctSpread:n.pctSpread??""}});return{reportId:TL,generatedAt:(new Date).toISOString(),columns:[{key:"roundName",title:"Round",type:"string"},{key:"side1",title:"Side 1",type:"string"},{key:"side2",title:"Side 2",type:"string"},{key:"score",title:"Score",type:"string"},{key:"competitiveness",title:"Competitiveness",type:"string"},{key:"pctSpread",title:"Spread %",type:"number"}],rows:n}},[SL]:function({tournamentRecord:t}){const{participantMap:n}=xS({tournamentRecord:t}),{matchUps:i}=Qg({matchUpFilters:{matchUpTypes:[e,r]},tournamentRecord:t});if(!i)return{error:"No matchUps found"};const o=i.filter(t=>_p.includes(t.matchUpStatus)),a={},s=t=>{a[t]||(a[t]={wins:0,losses:0,setsWon:0,setsLost:0,gamesWon:0,gamesLost:0})};for(const t of o){const e=BL(t.sides?.[0],t.matchUpType??""),n=BL(t.sides?.[1],t.matchUpType??""),r=t.winningSide??0,i=[[],e,n][r]??[],o=[[],n,e][r]??[],c=t.score?.sets??[];let u=0,d=0,p=0,l=0;for(const t of c){const e=t.side1Score??0,n=t.side2Score??0;p+=e,l+=n,e>n?u++:n>e&&d++}for(const t of i)s(t),a[t].wins++;for(const t of o)s(t),a[t].losses++;const m={setsWon:u,setsLost:d,gamesWon:p,gamesLost:l},f={setsWon:d,setsLost:u,gamesWon:l,gamesLost:p};for(const t of e)s(t),a[t].setsWon+=m.setsWon,a[t].setsLost+=m.setsLost,a[t].gamesWon+=m.gamesWon,a[t].gamesLost+=m.gamesLost;for(const t of n)s(t),a[t].setsWon+=f.setsWon,a[t].setsLost+=f.setsLost,a[t].gamesWon+=f.gamesWon,a[t].gamesLost+=f.gamesLost}const c=Object.entries(a).map(([t,e])=>{const r=n?.[t]?.participant?.participantName??t,i=e.wins+e.losses,o=i>0?Math.round(e.wins/i*100):0;return{participantId:t,participantName:r,wins:e.wins,losses:e.losses,winPct:o,setsWon:e.setsWon,setsLost:e.setsLost,gamesWon:e.gamesWon,gamesLost:e.gamesLost}}).sort((t,e)=>e.wins-t.wins||t.losses-e.losses);return{reportId:SL,generatedAt:(new Date).toISOString(),columns:[{key:"participantName",title:"Participant",type:"string"},{key:"wins",title:"Wins",type:"number"},{key:"losses",title:"Losses",type:"number"},{key:"winPct",title:"Win %",type:"number"},{key:"setsWon",title:"Sets Won",type:"number"},{key:"setsLost",title:"Sets Lost",type:"number"},{key:"gamesWon",title:"Games Won",type:"number"},{key:"gamesLost",title:"Games Lost",type:"number"}],rows:c}},[PL]:function({tournamentRecord:t}){const{participantMap:e}=xS({withSeeding:!0,withDraws:!0,tournamentRecord:t}),n=[];for(const r of t.events??[])for(const i of r.drawDefinitions??[])n.push(...LL(r,i,e,t));return n.sort((t,e)=>(t.seedValue??99)-(e.seedValue??99)),{reportId:PL,generatedAt:(new Date).toISOString(),columns:[{key:"participantName",title:"Participant",type:"string"},{key:"eventName",title:"Event",type:"string"},{key:"drawName",title:"Draw",type:"string"},{key:"seedValue",title:"Seed",type:"number"},{key:"finishingPosition",title:"Finish",type:"string"},{key:"expectedPosition",title:"Expected",type:"string"},{key:"performance",title:"Performance",type:"string"}],rows:n}},[IL]:function({tournamentRecord:t}){const e=oL({tournamentRecord:t});if(e.error)return e;const n=(e.allParticipantStats??[]).map(t=>({participantName:t.participantName??"",matchUpsWon:t.matchUps?.[0]??0,matchUpsLost:t.matchUps?.[1]??0,matchUpsRatio:t.matchUpsRatio??0,setsWon:t.sets?.[0]??0,setsLost:t.sets?.[1]??0,gamesWon:t.games?.[0]??0,gamesLost:t.games?.[1]??0,tiebreaksWon:t.tiebreaks?.[0]??0,tiebreaksLost:t.tiebreaks?.[1]??0}));return{reportId:IL,generatedAt:(new Date).toISOString(),columns:[{key:"participantName",title:"Participant",type:"string"},{key:"matchUpsWon",title:"Wins",type:"number"},{key:"matchUpsLost",title:"Losses",type:"number"},{key:"matchUpsRatio",title:"Win %",type:"number"},{key:"setsWon",title:"Sets Won",type:"number"},{key:"setsLost",title:"Sets Lost",type:"number"},{key:"gamesWon",title:"Games Won",type:"number"},{key:"gamesLost",title:"Games Lost",type:"number"},{key:"tiebreaksWon",title:"TBs Won",type:"number"},{key:"tiebreaksLost",title:"TBs Lost",type:"number"}],rows:n,summary:{participatingTeamsCount:e.participatingTeamsCount??0}}},[yL]:function({tournamentRecord:t}){const e=t?.tournamentId,n=VL({tournamentRecords:e?{[e]:t}:{}});if(n.error)return n;const r=[];for(const t of n.venuesReport??[])for(const[e,n]of Object.entries(t.venueReport??{})){const i=n;r.push({venueName:t.venueName??"",date:e,availableCourts:i.availableCourts??0,scheduledMatchUpsCount:i.scheduledMatchUpsCount??0,availableMinutes:i.availableMinutes??0,scheduledMinutes:i.scheduledMinutes??0,percentUtilization:i.percentUtilization??"0"})}return{reportId:yL,generatedAt:(new Date).toISOString(),columns:[{key:"venueName",title:"Venue",type:"string"},{key:"date",title:"Date",type:"date"},{key:"availableCourts",title:"Courts",type:"number"},{key:"scheduledMatchUpsCount",title:"Scheduled MatchUps",type:"number"},{key:"availableMinutes",title:"Available Minutes",type:"number"},{key:"scheduledMinutes",title:"Scheduled Minutes",type:"number"},{key:"percentUtilization",title:"Utilization %",type:"number"}],rows:r}}};var qL={__proto__:null,buildReportContext:function({tournamentRecord:t}){if(!t)return{error:rt};const{participantMap:e}=xS({withScaleValues:!0,withSeeding:!0,withEvents:!0,withDraws:!0,tournamentRecord:t}),{matchUps:n}=Qg({tournamentRecord:t});return{venues:t.venues??[],participantMap:e??{},matchUps:n??[],tournamentRecord:t}},generateReport:function({tournamentRecord:t,reportId:e}){if(!t)return{error:rt};const n=jL[e];return n?n({tournamentRecord:t}):GL},getAvailableReports:function({tournamentRecord:t}){if(!t)return{error:rt};const e=(t.events?.length??0)>0,n=(t.venues?.length??0)>0,r=(t.events??[]).some(t=>(t.drawDefinitions??[]).some(t=>(t.structures??[]).some(t=>(t.positionAssignments??[]).length>0))),i=(t.events??[]).some(t=>(t.drawDefinitions??[]).some(t=>(t.structures??[]).some(t=>(t.seedAssignments??[]).length>0))),o=(t.participants??[]).some(t=>t.participantType===hm),a={[hL]:e,[gL]:e,[vL]:r,[UL]:r,[TL]:r,[SL]:r,[PL]:i,[IL]:o,[yL]:n,[RL]:!0,[wL]:!0,[DL]:!0,[bL]:!0};return{availableReports:EL.map(t=>({...t,computableNow:a[t.reportId]??!1}))}},getEntryStatusReports:OL,getParticipantStats:oL,getStructureReports:FL,getVenuesReport:VL};function WL({calculateStartTimeFromCourts:t=!0,defaultRecoveryMinutes:e=0,averageMatchUpMinutes:n=90,remainingScheduleTimes:r,clearScheduleDates:i,tournamentRecords:o,periodLength:a,scheduleDate:s,startTime:c,venueIds:u,endTime:d}){if("object"!=typeof o||!Object.keys(o).length)return{error:nt};a=a??TO({recoveryMinutes:e,averageMatchUpMinutes:n});const{courts:p,venues:l}=gw({dates:[s],ignoreDisabled:!0,tournamentRecords:o}),m=p?.filter(t=>!u||u.includes(t.venueId));c||(c=m?.reduce((t,e)=>{const n=e.dateAvailability?.find(t=>!t.date||Ko(s,t.date)),r=n?.startTime??e.startTime;return r&&(!t||Fo(r)<Fo(t))?r:t},void 0)),d||(d=m?.reduce((t,e)=>{const n=e.dateAvailability?.find(t=>!t.date||Ko(s,t.date)),r=n?.endTime??e.endTime;return r&&(!t||Fo(r)>Fo(t))?r:t},void 0));const f=Object.values(o),h=Object.assign({},...f.map(t=>(t.events??[]).map(e=>{const{scheduleTiming:n}=Jm({tournamentRecord:t,event:e});return{[e.eventId]:{event:e,scheduleTiming:n}}})).flat()),g=vE({sortDateMatchUps:!1,tournamentRecords:o,matchUpFilters:{scheduledDate:s,venueIds:u}}),I=g?.dateMatchUps??[],S=g?.completedMatchUps??[],y=[];y.push(...I),y.push(...S);const v={averageTimes:[{minutes:{default:n}}],recoveryTimes:[{minutes:{default:e}}]},U=y?.map(({eventId:t,schedule:e,matchUpFormat:n})=>{const{event:r,scheduleTiming:i}=h[t],o=r?.eventType,s={...i,defaultTiming:v,matchUpFormat:n},{averageMinutes:c,recoveryMinutes:u}=Xh({eventType:o,timingDetails:s}),{courtId:d,venueId:p}=e,l=_o(e.scheduledTime),m=Ho(l,c);return{recoveryMinutes:u,averageMinutes:c,periodLength:a,startTime:l,endTime:m,courtId:d,venueId:p}}),P={calculateStartTimeFromCourts:t,remainingScheduleTimes:r,averageMatchUpMinutes:n,date:s,clearScheduleDates:i,periodLength:a,startTime:c,endTime:d,bookings:U,courts:m},{scheduleTimes:T}=RO(P);return{venueId:1===u?.length&&u[0]||1===l?.length&&l[0].venueId||void 0,scheduleTimes:T,dateScheduledMatchUpIds:y.map(tl)}}function $L(t){const e=fu(t,[{[hc]:!0}]);if(e.error)return e;const{removePriorValues:n,tournamentRecords:r,tournamentId:i,courtDayDate:a,matchUpId:s,courtId:c,drawId:u}=t,d=r[i];if(!d)return{error:rt};const{drawDefinition:p,event:l}=Mw({tournamentRecord:d,drawId:u});if(!p)return{error:st};const m=nT({drawDefinition:p,event:l,matchUpId:s});if(m.error)return m;if(m?.matchUp?.matchUpType===o){const{itemValue:t}=tg({timeItems:m.matchUp.timeItems??[],itemType:Zf}),e=c&&t.filter(t=>t.courtId!==c);return EO({duplicateValues:!1,removePriorValues:n,tournamentRecord:d,drawDefinition:p,matchUpId:s,timeItem:{itemType:Zf,itemValue:e}})}return vk({tournamentRecord:d,drawDefinition:p,courtDayDate:a,courtId:"",matchUpId:s})}function HL(t,e){const n=t?.schedule?.scheduledDate,r=e?.schedule?.scheduledDate,i=t?.schedule?.scheduledTime,o=e?.schedule?.scheduledTime;if(n&&r){if(n!==r)return n.localeCompare(r);if(i&&o&&i!==o)return i.localeCompare(o)}return 0}function zL({matchUpDailyLimits:t,minCourtGridRows:e=10,tournamentRecords:n,scheduledDate:r,courtIds:i,matchUps:o}){if(!Lf(o))return{error:sr};if(o.some(({hasContext:t})=>!t))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Kn};let a=vE({courtCompletedMatchUps:!0,withCourtGridRows:!0,minCourtGridRows:e,tournamentRecords:n,matchUpFilters:{localPerspective:!0,scheduledDate:r}});if(a.error)return a;const{rows:s}=a,c=[],u=t=>[(t.sides??[]).map(t=>[t.participantId,t.participant?.individualParticipantIds]),(t.potentialParticipants??[]).flat().map(t=>[t.participantId,t.individualParticipantIds])].flat(1/0).filter(Boolean),d=s?.reduce((t,e)=>{const n=[],r=[];Object.values(e).forEach(t=>{if(f(t)&&(t.matchUpId&&(n.push(t.matchUpId),c.push(t)),t.sides)){const e=u(t);r.push(...e)}});const o=Object.values(e).filter(t=>f(t)&&!t.matchUpId&&!t.isBlocked&&(!i?.length||i.includes(t.schedule?.courtId)));return t.concat({matchUpIds:n,availableCourts:o,rowId:e.rowId,participantIds:r})},[]);o.sort(HL);const p=iI({matchUps:o.concat(c),includeParticipantDependencies:!0,tournamentRecords:n}).matchUpDependencies,l=!!t&&Object.keys(t).length>0,m={},h={},g=[];if(l){!function(t,e,n){for(const r of t)dF({matchUpPotentialParticipantIds:n,individualParticipantProfiles:e,value:1,matchUp:r})}(c,m,h);for(const t of c)VA({matchUpPotentialParticipantIds:h,matchUpNotBeforeTimes:{},matchUp:t})}const I=[],S=[];for(;o.length&&d.length;){const e=d.shift(),n=[];for(;o.length&&e.availableCourts.length;){const r=o.concat(n).map(t=>t.matchUpId),i=o.shift(),a=YL({matchUp:i,row:e,deps:p,previousRowMatchUpIds:S,unscheduledMatchUpIds:r,getMatchUpParticipantIds:u,enforceLimits:l,matchUpDailyLimits:t,individualParticipantProfiles:m,matchUpPotentialParticipantIds:h});if(a.canPlace&&i){const t=e.availableCourts.shift();i.schedule??={},Object.assign(i.schedule,t.schedule),Object.assign(t,i),I.push(i),l&&(dF({matchUpPotentialParticipantIds:h,individualParticipantProfiles:m,value:1,matchUp:i}),VA({matchUpPotentialParticipantIds:h,matchUpNotBeforeTimes:{},matchUp:i})),e.participantIds.push(...a.participantIds),e.matchUpIds.push(i.matchUpId)}else i&&a.atLimit?(g.includes(i.matchUpId)||g.push(i.matchUpId),VA({matchUpPotentialParticipantIds:h,matchUpNotBeforeTimes:{},matchUp:i})):i&&n.push(i)}o.push(...n),S.push(...e.matchUpIds)}const y=I.map(({matchUpId:t,tournamentId:e,schedule:n,drawId:i})=>({tournamentId:e,matchUpId:t,drawId:i,schedule:{...n,scheduledDate:r}}));a=UF({tournamentRecords:n,matchUpDetails:y});const v=o;return{...a,scheduled:I,notScheduled:v,overLimitMatchUpIds:g}}function YL({matchUp:t,row:e,deps:n,previousRowMatchUpIds:r,unscheduledMatchUpIds:i,getMatchUpParticipantIds:o,enforceLimits:a,matchUpDailyLimits:s,individualParticipantProfiles:c,matchUpPotentialParticipantIds:u}){if(!t)return{canPlace:!1,atLimit:!1,participantIds:[]};const d=t.matchUpId,p=n[d].matchUpIds.concat(n[d].dependentMatchUpIds),l=i.some(t=>n[d].matchUpIds.includes(t)),m=r.some(t=>n[d].dependentMatchUpIds.includes(t)),f=e.matchUpIds.some(t=>p.includes(t)),h=o(t),g=e.participantIds.some(t=>h.includes(t));let I=[];if(a){I=yF({matchUpPotentialParticipantIds:u,individualParticipantProfiles:c,matchUpDailyLimits:s,matchUp:t}).participantIdsAtLimit}const S=I.length>0;return{canPlace:!(f||l||g||m||S),atLimit:S,participantIds:h}}function KL(t){const{courtDayDate:e}=t,n=fu(t,[{courtAssignments:!0,[cu]:iu,[su]:Ae},{[hc]:!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 o=t[hc][n];if(!o)return i={error:rt},!1;const a=r[n].reduce((t,e)=>{const{drawId:n}=e;return t[n]||(t[n]=[]),t[n].push(e),t},{});Object.keys(a).every(t=>{const{drawDefinition:n}=wg({tournamentRecord:o,drawId:t});return n?(a[t].every(t=>{const{matchUpId:r,courtId:a}=t,s=vk({tournamentRecord:o,drawDefinition:n,courtDayDate:e,matchUpId:r,courtId:a});if(s.success)return s?.success;i={error:tr}}),!0):(i={error:st},!1)})}),i||Y}function QL(t){const{tournamentRecords:e,allDateMatchUpIds:n=[],averageMatchUpMinutes:r=90,recoveryMinutes:i=0,recoveryMinutesMap:o,matchUpPotentialParticipantIds:a={},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:S,dryRun:y}=t,v=fu(t,[{[hc]:!0,[Mc]:!0},{[ou]:Do,[su]:_e,[Dc]:!0},{[ou]:t=>!t||!isNaN(t),[tu]:!1,[su]:sr,[eu]:!1,[nu]:!1}]);if(v.error)return v;const U=t.competitionMatchUps??Jg({nextMatchUps:!0,tournamentRecords:e}).matchUps??[],P=t.matchUpDependencies??iI({includeParticipantDependencies:!0,matchUps:U,tournamentRecords:e}).matchUpDependencies;U.forEach(t=>{t.schedule?.scheduledDate&&Ko(f,Lo(t.schedule.scheduledDate))&&VA({matchUpPotentialParticipantIds:a,matchUpNotBeforeTimes:c,matchUp:t})});const T=h.map(t=>U.find(e=>e.matchUpId===t)).filter(Boolean),{venueId:w,scheduleTimes:D,dateScheduledMatchUpIds:R}=WL({tournamentRecords:e,remainingScheduleTimes:p,startTime:_o(I),endTime:_o(S),scheduleDate:Lo(f),averageMatchUpMinutes:r,clearScheduleDates:l,periodLength:m,venueIds:g}),b={},N=[],M={},A={},E={},C=U.filter(({matchUpId:t})=>R?.includes(t));C.forEach(t=>{dF({matchUpPotentialParticipantIds:a,individualParticipantProfiles:s,matchUp:t,value:1});const e=t.schedule?.scheduledTime;if(e){M[t.matchUpId]=e;const n=o?.[t.matchUpId];oF({recoveryMinutes:n||i,matchUpPotentialParticipantIds:a,individualParticipantProfiles:s,matchUpNotBeforeTimes:c,averageMatchUpMinutes:r,matchUpDependencies:P,scheduleTime:e,matchUp:t})}});let O=T.filter(t=>{const e=R?.includes(t.matchUpId),n=[Sp,Pp,vp,gp,Np,Ep].includes(t?.matchUpStatus);return!e&&!t.winningSide&&!n});const{matchUpMap:k,overLimitMatchUpIds:F,participantIdsAtLimit:x}=O.reduce((t,e)=>{const{drawId:n,tournamentId:r,matchUpType:i}=e,{participantIdsAtLimit:o,relevantParticipantIds:d}=yF({individualParticipantProfiles:s,matchUpPotentialParticipantIds:a,matchUpDailyLimits:u,matchUp:e});return o?.length?(t.overLimitMatchUpIds.push(e.matchUpId),t.participantIdsAtLimit.push(...o),t):(d.forEach(t=>{iF({individualParticipantProfiles:s,participantId:t});const e=s[t].counters;e[i]?e[i]+=1:e[i]=1,e[_h]?e[_h]+=1:e[_h]=1}),t.matchUpMap[r]||(t.matchUpMap[r]={}),t.matchUpMap[r][n]?t.matchUpMap[r][n].push(e):t.matchUpMap[r][n]=[e],VA({matchUpPotentialParticipantIds:a,matchUpNotBeforeTimes:c,matchUp:e}),t)},{matchUpMap:{},overLimitMatchUpIds:[],participantIdsAtLimit:[]});O=O.filter(({matchUpId:t})=>!F.includes(t));let _=0;const L=D?.length??0,{personRequests:B}=QA({tournamentRecords:e,requestType:sF});for(;D?.length&&O.length&&_<=L;){_++;const{scheduleTime:t}=D.shift(),e=O.find(e=>{const{matchUpId:u}=e,{dependenciesScheduled:p,remainingDependencies:l}=rF({matchUpScheduleTimes:M,matchUpDependencies:P,allDateMatchUpIds:n,matchUp:e});if(!p)return E[u]||(E[u]=[]),E[u].push({scheduleTime:t,remainingDependencies:l}),!1;const{enoughTime:m}=IF({individualParticipantProfiles:s,matchUpNotBeforeTimes:c,matchUpDependencies:P,scheduleTime:t,matchUp:e});if(!m)return A[u]||(A[u]=[]),A[u].push({scheduleTime:t}),!1;const{conflicts:h}=uF({potentials:d,averageMatchUpMinutes:r,requestConflicts:b,personRequests:B,scheduleTime:t,scheduleDate:f,matchUp:e});if(h?.length)return!1;const g=o?.[e.matchUpId];return oF({recoveryMinutes:g||i,matchUpPotentialParticipantIds:a,individualParticipantProfiles:s,matchUpNotBeforeTimes:c,averageMatchUpMinutes:r,matchUpDependencies:P,scheduleTime:t,matchUp:e}),M[e.matchUpId]=t,!0});O=O.filter(({matchUpId:t})=>t!==e?.matchUpId),e||N.push(t)}O.forEach(t=>{dF({individualParticipantProfiles:s,matchUpPotentialParticipantIds:a,value:-1,matchUp:t})});const V=[];Object.keys(k).forEach(t=>{const n=e[t];n&&Object.keys(k[t]).forEach(r=>{const{drawDefinition:i}=Mw({tournamentRecord:n,drawId:r});if(i){k[t][r].forEach(({matchUpId:t})=>{const r=M[t];if(r){const o=r.split(":").map(Yo).join(":"),a=`${Lo(f)}T${o}`;if(y)V.push(t);else{hk({drawDefinition:i,matchUpId:t,scheduledTime:a}).success&&V.push(t),w&&yk({tournamentRecords:e,tournamentRecord:n,drawDefinition:i,matchUpId:t,venueId:w})}}})}})});const G=Qp(O);return{...Y,requestConflicts:Object.values(b),remainingScheduleTimes:D?.map(({scheduleTime:t})=>t),individualParticipantProfiles:s,matchUpNotBeforeTimes:c,participantIdsAtLimit:x,skippedScheduleTimes:N,overLimitMatchUpIds:F,scheduledMatchUpIds:V,noTimeMatchUpIds:G,recoveryTimeDeferred:A,dependencyDeferred:E}}function JL({useDeepDependencies:t=!1,tournamentRecords:e,matchUps:n}){if(!Lf(n))return{error:Ie};if(n.some(({matchUpId:t,hasContext:e})=>t&&!e))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Kn};const r=L(1,Math.max(...n.map(({schedule:t})=>t?.courtOrder||1).map(t=>p(t)))+1).map(t=>n.filter(e=>p(e.schedule?.courtOrder)===t)),i={},o={},a={};r.flat().filter(Boolean).sort(Xg).forEach(({schedule:t})=>{t&&delete t[Yh]});const s=iI({includeParticipantDependencies:!0,tournamentRecords:e,drawIds:M(n.map(({drawId:t})=>t))}),c=s.matchUpDependencies,u=t?s.positionDependencies??{}:{},d=r.map((t,e)=>t.reduce((t,n)=>{if(!n.matchUpId)return t;const{matchUpId:r,winnerMatchUpId:s,loserMatchUpId:u,schedule:d,sides:p,potentialParticipants:l}=n,m=d?.courtId;i[r]=e,m&&(o[m]=[]),t.matchUpIds.push(r),a[r]=n;const f=c[r].matchUpIds;f.length&&t.sourceMatchUpIds.push(...f);const h=p?.flatMap(t=>[t.participant?.individualParticipantIds,t.participantId]).flat().filter(Boolean)??[],g=l?.flat().flatMap(({individualParticipantIds:t,participantId:e})=>[t,e]).flat().filter(Boolean)??[];return t.participantIds.push(...g,...h),s&&t.targetMatchUpIds.push(s),u&&t.targetMatchUpIds.push(u),t},{sourceMatchUpIds:[],targetMatchUpIds:[],participantIds:[],matchUpIds:[]})),l=(t,e)=>c[t].sources.reduce((t,n,r)=>n.includes(e)&&r+1||t,0),m=d.map(()=>[]),f=(t,e,n)=>{e.participantIds.filter(e=>t.participantIds.includes(e)).forEach(r=>{const i=e.matchUpIds.concat(t.matchUpIds).filter(t=>c[t].participantIds.includes(r));i.forEach(t=>{((t,e,n)=>{n[t]||(n[t]={}),n[t][$h]||(n[t][$h]=e.filter(e=>e!==t))})(t,i,n)})})},h=t=>{const e={},n=C(t.participantIds),r=new Set(Object.keys(n).filter(t=>n[t]>1)),i=t.matchUpIds.filter(t=>c[t].participantIds.some(t=>r.has(t)));return i.forEach(t=>{((t,e,n)=>{n[t]||(n[t]={}),n[t][Wh]||(n[t][Wh]=e.filter(e=>e!==t))})(t,i,e)}),e},g=(t,e,n,r)=>{if(!a[t].schedule[Yh]){a[t].schedule[Yh]=e,a[t].schedule[qh]=r,m[i[t]].push({matchUpId:t,issueType:n,issueIds:r,issue:e});const s=a[t].schedule.courtId;o[s]||(o[s]=[]),o[s].push({matchUpId:t,issue:e,issueType:n,issueIds:r})}};if(d.forEach((t,e)=>{const n=e?d[e-1]:void 0,i=d.slice(e+1),o=h(t),s=(t=>{const e={},n={};return t.forEach(t=>{const{matchUpId:e,schedule:r}=t;if(!e||!r?.courtId||!r?.scheduledDate)return;const i=`${r.courtId}|${r.scheduledDate}`;n[i]||(n[i]=[]),n[i].push(e)}),Object.values(n).forEach(t=>{t.length>1&&t.forEach(n=>{e[n]=t.filter(t=>t!==n)})}),e})(r[e].filter(e=>t.matchUpIds.includes(e.matchUpId)));n&&f(n,t,o),t.matchUpIds.forEach(e=>{const r=c[e].matchUpIds;for(const t of i){const n=t.matchUpIds.filter(t=>r.includes(t));n?.length&&(n.forEach(t=>g(t,Hh,Vh,[e])),g(e,Hh,Vh,n))}if(s[e]&&g(e,Wh,Gh,s[e]),o[e]?.[Wh]&&g(e,Wh,Lh,o[e][Wh]),t.sourceMatchUpIds.includes(e)){const n=t.matchUpIds.filter(t=>c[t].matchUpIds.includes(e));g(e,Wh,Vh,n),t.matchUpIds.filter(t=>c[t].matchUpIds.includes(e)).forEach(t=>g(t,Wh,Vh,[e]))}const u=n?.matchUpIds?.filter(t=>l(e,t)>1);if(u?.length&&(g(e,zh,Vh,u),u.forEach(t=>g(t,zh,Vh,[e]))),o[e]?.[$h]&&g(e,$h,Lh,o[e][$h]),n?.targetMatchUpIds?.includes(e)){const t=a[e].schedule.courtId,i=r.filter(t=>n.matchUpIds.includes(t));i.some(e=>a[e].schedule.courtId===t)||(i.forEach(t=>g(t,$h,Vh,[e])),g(e,$h,Vh,i))}})}),t){const t=new Set(Object.keys(i)),e={};for(const n of t)e[n]=new Set(c[n]?.dependentMatchUpIds??[]);let n=0;for(const e of t){const t=c[e]?.sources?.length??0;t>n&&(n=t)}const r=t=>{const e=new Set(t.participantIds),n={};for(const r of t.matchUpIds){const t=c[r]?.participantIds??[];for(const i of t)e.has(i)||(n[i]||(n[i]=new Set),n[i].add(r))}return n};if(d.forEach((t,e)=>{const n=r(t);for(const[,t]of Object.entries(n))if(t.size>1){const e=[...t];for(const t of e)g(t,$h,Bh,e.filter(e=>e!==t))}if(e>0){const t=d[e-1],i=r(t);for(const[t,e]of Object.entries(n))if(i[t]){const n=[...new Set([...e,...i[t]])];for(const t of n)g(t,$h,Bh,n.filter(e=>e!==t))}}}),d.forEach((t,e)=>{for(const r of t.matchUpIds)for(let t=2;t<=Math.min(e,n);t++){const n=d[e-t];for(const e of n.matchUpIds){const n=l(r,e);n>0&&t<n&&(g(r,zh,Vh,[e]),g(e,zh,Vh,[r]))}}}),d.forEach((t,n)=>{for(const r of t.matchUpIds){const i=e[r];if(!i?.size)continue;for(let t=0;t<n;t++){const e=d[t].matchUpIds.filter(t=>i.has(t));if(e.length){for(const t of e)g(t,Hh,Vh,[r]);g(r,Hh,Vh,e)}}const o=t.matchUpIds.filter(t=>t!==r&&i.has(t));if(o.length){for(const t of o)g(t,Wh,Vh,[r]);g(r,Wh,Vh,o)}}}),Object.keys(u).length){const e=new Set(Object.values(u).flat());d.forEach(n=>{for(const r of n.matchUpIds){const n=(c[r]?.matchUpIds??[]).filter(t=>e.has(t)).filter(e=>!t.has(e));n.length&&g(r,$h,jh,n)}})}}return{courtIssues:o,rowIssues:m}}function XL(t){const e="reorderUpcomingMatchUps",{tournamentRecords:n}=t;if("object"!=typeof n||!Object.keys(n).length)return Ci({result:{error:nt},stack:e});const{matchUpsContextIds:r,firstToLast:i}=t;if(!r)return Ci({result:{error:Ae},stack:e});const o=r?.length;if(!o)return{...Y};let a=0;return r.forEach((t,e)=>{const{tournamentId:s,drawId:c,matchUpId:u}=t;let d=e+(i?-1:1);d<0&&(d=o-1),d===o&&(d=0);const p=function({tournamentId:t,scheduledTime:e,matchUpId:r,drawId:i}){const o=n[t],{drawDefinition:a}=Mw({tournamentRecord:o,drawId:i});return a?hk({drawDefinition:a,scheduledTime:e,matchUpId:r}):{error:ut}}({tournamentId:s,scheduledTime:r[d].schedule.scheduledTime,matchUpId:u,drawId:c});if(!p.success)return p;a++}),a===o?Y:Ci({result:{error:Xn},stack:e})}function ZL(t){const{scheduleChange:e,matchUpIds:n,dryRun:r}=t;if(!n||!Array.isArray(n))return{error:he};if("object"!=typeof e)return{error:sr};const i=im(t),o=[];let a=[];for(const t of Object.values(i)){const i=tB({tournamentRecord:t,scheduleChange:e,matchUpIds:n,dryRun:r});if(i.error)return i;Array.isArray(i.notRescheduled)&&a.push(...i.notRescheduled);const s=Qp(i.notRescheduled),c=[];i.rescheduled?.forEach(t=>{const{matchUpId:e}=t;s.includes(e)&&c.push(e),o.push(t)}),c.length&&(a=i?.notRescheduled?.filter(({matchUpId:t})=>!c.includes(t))??[])}const s=!(!o.length||a.length);return{...Y,rescheduled:o,notRescheduled:a,allRescheduled:s}}function tB({tournamentRecord:t,scheduleChange:e,matchUpIds:n,dryRun:r}){if(!t)return{error:rt};if(!n||!Array.isArray(n))return{error:he};if("object"!=typeof e)return{error:sr};const{minutesChange:i,daysChange:o}=e;if(!i&&!o)return{...Y};if(i&&isNaN(i))return{error:sr};if(o&&isNaN(o))return{error:sr};const a=function({tournamentRecord:t,matchUpIds:e}){const{matchUps:n}=Qg({matchUpFilters:{matchUpIds:e},tournamentRecord:t}),r=({matchUpStatus:t})=>!_p.includes(t);return n?.filter(t=>mE({schedule:t.schedule})).filter(t=>r({matchUpStatus:t.matchUpStatus}))}({tournamentRecord:t,matchUpIds:n});if(!a?.length)return{...Y};const{tournamentInfo:s}=Pw({tournamentRecord:t}),{startDate:c,endDate:u}=s,d=a.reduce((t,e)=>{const{matchUpId:n,drawId:r}=e;return t[r]?t[r].push(n):t[r]=[n],t},{});const p=[],l=[];for(const e of Object.keys(d)){const s=Mw({tournamentRecord:t,drawId:e});if(s.error)return s;const m=s.drawDefinition,f=d[e].filter(t=>n.includes(t));for(const t of f){if(!t||!m)continue;const e=eB({scheduledNotCompletedMatchUps:a,rescheduledMatchUpIds:p,notRescheduledMatchUpIds:l,drawDefinition:m,minutesChange:i,daysChange:o,startDate:c,matchUpId:t,endDate:u,dryRun:r});if(e?.error)return e}}const m=Qg({matchUpFilters:{matchUpIds:n},tournamentRecord:t}).matchUps??[],f=m.filter(({matchUpId:t})=>p.includes(t)),h=m.filter(({matchUpId:t})=>l.includes(t)),g=f.length&&!h.length;return{...Y,rescheduled:f,notRescheduled:h,allRescheduled:g}}function eB({scheduledNotCompletedMatchUps:t,rescheduledMatchUpIds:e,notRescheduledMatchUpIds:n,drawDefinition:r,minutesChange:i,daysChange:o,startDate:a,matchUpId:s,endDate:c,dryRun:u}){const d=t.find(t=>t.matchUpId===s),p=d?.schedule,{scheduledTime:l,scheduledDate:m}=p;let f,h,g;if(!f&&o&&m){g=Bo(Lo(m),o),f=new Date(g)<new Date(a)||new Date(g)>new Date(c)}if(i&&l){const t=Lo(l),e=Fo(_o(l))+i;if(f=e<0||e>1440,!f){const e=Ho(l,i),n=t&&g||m===t&&t;h=n?`${n}T${e}`:e}}if(f)n.push(s);else{if(!u){if(h){const t=hk({scheduledTime:h,drawDefinition:r,matchUpId:s});if(t.error)return t}if(g){const t=Ik({scheduledDate:g,drawDefinition:r,matchUpId:s});if(t.error)return t}}(h||g)&&e.push(s)}}function nB(t){const e="matchUpScheduleChange",{tournamentRecords:n}=t;if("object"!=typeof n||!Object.keys(n).length)return{error:nt};const{sourceMatchUpContextIds:r,targetMatchUpContextIds:i,sourceCourtId:o,targetCourtId:s,courtDayDate:c}=t??{},{drawId:u,matchUpId:d,tournamentId:p}=r??{},{drawId:l,matchUpId:m,tournamentId:f}=i??{};if(!d&&!m)return Ci({result:{error:Ae},stack:e});const{matchUps:h}=Jg({matchUpFilters:{matchUpIds:[d,m].filter(Boolean),drawIds:[u,l].filter(Boolean)},tournamentRecords:t.tournamentRecords}),g=h?.find(({matchUpId:t})=>t===d),I=h?.find(({matchUpId:t})=>t===m);let S=0;if(s&&d&&!m){const t=y({tournamentId:p,matchUpId:d,courtId:s,matchUp:g,drawId:u,tournamentRecords:n,sourceCourtId:o,courtDayDate:c});if(t?.success&&S++,t.error)return Ci({result:t,stack:e})}else{if(!(o&&s&&d&&m))return{error:Ae};{const t=y({tournamentId:p,matchUpId:d,courtId:s,matchUp:g,drawId:u,tournamentRecords:n,sourceCourtId:o,courtDayDate:c});if(t.success&&S++,t.error)return Ci({result:t,stack:e,info:"source"});const r=y({tournamentId:f,sourceCourtId:s,matchUpId:m,matchUp:I,courtId:o,drawId:l,tournamentRecords:n,courtDayDate:c});if(r.success&&S++,r.error)return Ci({result:r,stack:e,info:"target"})}}return S?Y:Ci({result:{error:Zn},stack:e});function y(t){const{tournamentRecords:e,tournamentId:n,matchUp:r,drawId:i}=t,o=e[n],{drawDefinition:s}=Mw({tournamentRecord:o,drawId:i});return r.matchUpType===a?function({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,sourceCourtId:i,courtDayDate:o,matchUpId:a,matchUp:s,courtId:c}){const u=[c].concat(s.schedule.allocatedCourts.map(({courtId:t})=>t).filter(t=>t!==i));return Sk({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,courtDayDate:o,matchUpId:a,courtIds:u})}({...t,tournamentRecord:o,drawDefinition:s}):vk({...t,tournamentRecord:o,drawDefinition:s})}}function rB(t,e,n,r){const{structureId:i,roundNumber:o,drawId:a,roundSegment:s}=t,c=n[i]??i,u=s?new Set(function(t,e,n,r,i,o){const a=t.filter(t=>t.structureId===e&&t.roundNumber===n&&t.drawId===r),s=Math.ceil(a.length/i),c=(o-1)*s;return a.sort((t,e)=>(t.roundPosition??0)-(e.roundPosition??0)).map(t=>t.matchUpId).slice(c,c+s)}(e,i,o,a,s.segmentsCount,s.segmentNumber)):null;return e.filter(t=>{if(t.matchUpStatus===Sp)return!1;if(!r&&_p.includes(t.matchUpStatus))return!1;if(t.schedule?.courtId)return!1;if(t.schedule?.courtOrder)return!1;if(t.roundNumber!==o)return!1;if(t.drawId!==a)return!1;return(n[t.structureId]??t.structureId)===c&&(!u||u.has(t.matchUpId))})}function iB(t,e){return e||t.length?t:void 0}function oB(t,e,n,r,i,o){const a=[],s=[];for(const c of t.venues??[]){const t=e.get(c.venueId)??[],u=n?t.filter(t=>n.has(t)):t;s.push(...u);for(const t of c.rounds??[])a.push(...rB(t,r,i,o))}return{dateMatchUps:a,dateCourtIds:s}}function aB(t){const{scheduleCompletedMatchUps:e,matchUpDailyLimits:r,minCourtGridRows:o=10,clearScheduleDates:a,scheduleDates:s=[],tournamentRecords:c,courtIds:u}=t,d=Array.isArray(u)?new Set(u):null,p=fu(t,[{[hc]:!0},{[ou]:t=>!t||Array.isArray(t)&&t.every(t=>Do(t)),[Tc]:!1,[cu]:iu}]);if(p.error)return p;const l=HA({tournamentRecords:c});if(l.error)return l;if(!l.schedulingProfile.length)return{...Y};const{schedulingProfile:m=[]}=l,f=Object.assign({},...Object.values(c).map(t=>nm({tournamentRecord:t}).containedStructures)),h=new Set(s.map(t=>Do(t)?Lo(t):void 0).filter(Boolean)),g=m.map(t=>t.scheduleDate).map(t=>Do(t)&&Lo(t)).filter(t=>t&&(!s.length||h.has(t)));if(!g.length)return{error:Oe};if(a){xF({tournamentRecords:c,scheduledDates:Array.isArray(a)?a:[]})}const{matchUps:I}=Jg({matchUpFilters:{matchUpTypes:[n,i]},nextMatchUps:!0,tournamentRecords:c}),{courts:S}=gw({ignoreDisabled:!1,tournamentRecords:c}),y=new Map;for(const t of S??[]){const e=t.venueId;y.has(e)||y.set(e,[]),y.get(e)?.push(t.courtId)}const v=m.filter(t=>{const e=Lo(t?.scheduleDate);return g.includes(e)}).sort((t,e)=>new Date(t.scheduleDate).getTime()-new Date(e.scheduleDate).getTime()),U={},P={},T={},w=[];for(const t of v){const n=Lo(t.scheduleDate),{dateMatchUps:i,dateCourtIds:a}=oB(t,y,d,I??[],f,e);if(!i.length)continue;if(d&&!a.length)continue;const s=zL({courtIds:iB(a,d),matchUpDailyLimits:r,minCourtGridRows:o,tournamentRecords:c,matchUps:i,scheduledDate:n});if(s.error)continue;const u=(s.scheduled??[]).map(t=>t.matchUpId),p=(s.notScheduled??[]).map(t=>t.matchUpId),l=s.overLimitMatchUpIds??[];u.length&&(U[n]=u,w.push(n)),p.length&&(P[n]=p),l.length&&(T[n]=l)}return{...Y,scheduledMatchUpIds:U,notScheduledMatchUpIds:P,overLimitMatchUpIds:T,scheduledDates:w}}const sB={[Zf]:"allocatedCourts",[th]:"courtId",[oh]:"official",[Xf]:"venueId",[nh]:"courtAnnotation",[eh]:"courtOrder",[ih]:"homeParticipantId",[rh]:"scheduledDate",[ah]:"scheduledTime",[ph]:"timeModifiers"};function cB({scheduleAttributes:t=[Zf,th,Xf,rh,ah,sh,dh,uh,ch],tournamentRecord:e,drawDefinition:n,matchUpId:r}){const i=n?Zg({matchUpFilters:{matchUpIds:[r]},inContext:!1,drawDefinition:n}).matchUps?.[0]:Qg({matchUpFilters:{matchUpIds:[r]},tournamentRecord:e,inContext:!1}).matchUps?.[0];if(!i)return{error:ge};const o=(i.timeItems??[]).filter(e=>e?.itemType&&!t.includes(e?.itemType));if(i.timeItems=o,i.schedule){for(const e of t){const t=sB[e];t&&delete i.schedule[t]}0===Object.keys(i.schedule).length&&delete i.schedule}return Yl({tournamentId:e.tournamentId,context:"clearMatchUpSchedule",drawDefinition:n,matchUp:i}),{...Y}}function uB(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:nt};if("object"!=typeof r)return{error:ir};const o=Object.keys(i).filter(t=>!n||n===t);if(n&&!o.includes(n))return{error:sr};for(const t of o){const e=Ym({element:i[t],groupAttribute:"scheduling",leafAttribute:"dailyLimits",name:Pd,value:{dailyLimits:r}});if(e.error)return e}return{...Y}}function dB(t){const e="setMatchUpCalledAt",{tournamentRecord:n,drawDefinition:r,disableNotice:i,calledAt:o,matchUpId:a,event:s}=t;if(!r)return Ci({result:{error:st},stack:e});if(!a)return Ci({result:{error:fe},stack:e});if(null!=o&&"string"!=typeof o)return Ci({result:{error:sr},stack:e,info:"calledAt must be an ISO string"});const{matchUp:c}=nT({drawDefinition:r,event:s,matchUpId:a});return c?(null==o?c.schedule&&delete c.schedule.calledAt:(c.schedule||(c.schedule={}),c.schedule.calledAt=o),i||Yl({drawDefinition:r,tournamentId:n?.tournamentId,context:e,matchUp:c}),{...Y}):Ci({result:{error:ge},stack:e})}function pB(t){const{tournamentRecord:e,disableNotice:n,scheduledDate:r,bookingType:i,courtOrder:o,rowCount:a=1,courtId:s,notes:c}=t;if(!e)return Ci({result:{error:sr},info:"tournamentRecord is required"});if(!s)return{error:Cn};if(!r)return Ci({result:{error:sr},info:"scheduledDate is required"});if(!i)return Ci({result:{error:sr},info:"bookingType is required"});if(null==o)return Ci({result:{error:sr},info:"courtOrder is required"});if(!Number.isInteger(o)||o<1)return Ci({result:{error:sr},info:"courtOrder must be a positive integer"});if(!Number.isInteger(a)||a<1)return Ci({result:{error:sr},info:"rowCount must be a positive integer"});const{court:u,venue:d}=yg({tournamentRecord:e,courtId:s});if(!u)return{error:Cn};if(!eE({court:u,date:r})){u.dateAvailability??=[];const t={date:r,bookings:[]};u.dateAvailability.push(t)}const p=eE({court:u,date:r});if(p.bookings)for(const t of p.bookings)if("number"==typeof t.courtOrder){const e=t.courtOrder,n=e+(t.rowCount||1)-1;if(o<=n&&o+a-1>=e)return Ci({result:{error:xn},info:`Booking conflicts with existing booking at rows ${e}-${n}`})}const l={courtOrder:o,rowCount:a,bookingType:i,notes:c,createdAt:(new Date).toISOString()};return p.bookings??=[],p.bookings.push(l),!n&&d&&di({payload:{venue:d,tournamentId:e.tournamentId},topic:El,key:d.venueId}),{...Y,booking:l}}function lB(t){const{tournamentRecord:e,disableNotice:n,scheduledDate:r,courtOrder:i,courtId:o}=t;if(!e)return Ci({result:{error:sr},info:"tournamentRecord is required"});if(!o)return{error:Cn};if(!r)return Ci({result:{error:sr},info:"scheduledDate is required"});if(null==i)return Ci({result:{error:sr},info:"courtOrder is required"});const{court:a,venue:s}=yg({tournamentRecord:e,courtId:o});if(!a)return{error:Cn};const c=eE({court:a,date:r});if(!c?.bookings)return Ci({result:{error:kn},info:"No bookings found for this date"});const u=c.bookings.findIndex(t=>t.courtOrder===i);if(-1===u)return Ci({result:{error:kn},info:`No booking found at row ${i}`});const d=c.bookings.splice(u,1)[0];return!n&&s&&di({payload:{venue:s,tournamentId:e.tournamentId},topic:El,key:s.venueId}),{...Y,booking:d}}var mB={__proto__:null,addCourtGridBooking:pB,addMatchUpCourtOrder:wk,addMatchUpEndTime:bk,addMatchUpOfficial:Dk,addMatchUpResumeTime:Ak,addMatchUpScheduleItems:Tk,addMatchUpScheduledDate:Ik,addMatchUpScheduledTime:hk,addMatchUpStartTime:Rk,addMatchUpStopTime:Mk,addSchedulingProfileRound:Ox,allocateTeamMatchUpCourts:Sk,assignMatchUpCourt:vk,assignMatchUpVenue:yk,bulkRescheduleMatchUps:ZL,bulkScheduleMatchUps:UF,bulkScheduleTournamentMatchUps:vF,bulkUpdateCourtAssignments:KL,calculateScheduleTimes:WL,clearMatchUpSchedule:cB,clearScheduledMatchUps:xF,courtGridRows:nE,findMatchUpFormatTiming:jA,findVenue:Ig,generateBookings:lF,generateVirtualCourts:PO,getMatchUpsToSchedule:GA,getPersonRequests:QA,getProfileRounds:tE,getScheduledRoundsDetails:qA,getSchedulingProfile:HA,getSchedulingProfileIssues:KA,matchUpScheduleChange:nB,modifyMatchUpFormatTiming:kC,mutate:{__proto__:null,addCourtGridBooking:pB,addMatchUpCourtOrder:wk,addMatchUpEndTime:bk,addMatchUpOfficial:Dk,addMatchUpResumeTime:Ak,addMatchUpScheduleItems:Tk,addMatchUpScheduledDate:Ik,addMatchUpScheduledTime:hk,addMatchUpStartTime:Rk,addMatchUpStopTime:Mk,addSchedulingProfileRound:Ox,allocateTeamMatchUpCourts:Sk,assignMatchUpCourt:vk,assignMatchUpVenue:yk,bulkRescheduleMatchUps:ZL,bulkScheduleMatchUps:UF,bulkScheduleTournamentMatchUps:vF,bulkUpdateCourtAssignments:KL,calculateScheduleTimes:WL,clearMatchUpSchedule:cB,clearScheduledMatchUps:xF,findMatchUpFormatTiming:jA,generateBookings:lF,generateVirtualCourts:PO,matchUpScheduleChange:nB,modifyMatchUpFormatTiming:kC,proAutoSchedule:zL,proConflicts:JL,removeCourtGridBooking:lB,removeEventMatchUpFormatTiming:LC,removeMatchUpCourtAssignment:$L,reorderUpcomingMatchUps:XL,scheduleMatchUps:QL,scheduleProfileGrid:aB,scheduleProfileRounds:LF,setMatchUpCalledAt:dB,setMatchUpDailyLimits:uB,setMatchUpHomeParticipantId:mk,setSchedulingProfile:zA,toggleParticipantCheckInState:kO,validateSchedulingProfile:$A},proAutoSchedule:zL,proConflicts:JL,publicFindCourt:vg,query:rE,removeCourtGridBooking:lB,removeEventMatchUpFormatTiming:LC,removeMatchUpCourtAssignment:$L,reorderUpcomingMatchUps:XL,scheduleMatchUps:QL,scheduleProfileGrid:aB,scheduleProfileRounds:LF,setMatchUpCalledAt:dB,setMatchUpDailyLimits:uB,setMatchUpHomeParticipantId:mk,setSchedulingProfile:zA,toggleParticipantCheckInState:kO,validateSchedulingProfile:$A};function fB({drawDefinition:t,structureId:e,matchUpId:n,structure:r,matchUp:i,eventId:a,event:s}){const c="getTieFormat";let u;if(e=r?.structureId??e,((n=i?.matchUpId??n)||e)&&!t)return{error:st};if(a&&s)u=wf(s);else if(n){if(t&&(!i||!r)){const e=nT({drawDefinition:t,matchUpId:n});if(e.error)return e;if(e.matchUp?.matchUpType!==o)return Ci({result:{error:ye},stack:c});r||(r=e.structure),i||(i=e.matchUp)}u=Df({item:i,drawDefinition:t,structure:r,event:s})||Df({item:r,drawDefinition:t,structure:r,event:s})||wf(t)||wf(s)}else if(t&&e){if(!r){const n=ol({drawDefinition:t,structureId:e});if(n.error)return n;r=n?.structure}u=Df({item:r,drawDefinition:t,structure:r,event:s})||wf(t)||wf(s)}else u=wf(t)||wf(s);return u?{...Y,structure:r,tieFormat:u,matchUp:i}:Ci({result:{error:me},stack:c})}function hB({matchUp:t,updateInProgressMatchUps:e}){return!t.winningSide&&![_p].includes(t.matchUpStatus)&&(e||t.matchUpStatus!==Dp&&!aI(t))}function gB({from:t,to:e}){const n=Object.keys(t),r=V(n,Object.keys(e)).length===n.length,i=n.filter(n=>t[n]!==e[n]).map(n=>({countChange:e[n]-t[n],collectionId:n})),o=n.every(n=>t[n]===e[n]);return{equivalent:r&&o,matchUpsCountChanges:i}}function IB({check:t,matchUp:e}){let n="";const r=[];return{changesArePossible:t.matchUpsCountChanges.every(({collectionId:t,countChange:i})=>{const o=e.tieMatchUps.filter(e=>e.collectionId===t&&e.matchUpStatus===Ap).map(eI("matchUpId")),a=o.length+i>=0||i>0;return!a&&i<0&&(n="Insufficient TO_BE_PLAYED matchUps"),r.push({toBePlayedTieMatchUpIds:o,collectionId:t,countChange:i}),a}),changes:r,cannotChangeReaon:n}}function SB({appliedPolicies:t,drawDefinition:e,auditData:n}){if(!t?.audit?.[bd])return;const{extension:r}=td({name:bd,element:e});$u({element:e,extension:{value:Array.isArray(r?.value)?r?.value.concat(n):[n],name:bd}})}function yB({updateInProgressMatchUps:t=!1,tournamentRecord:e,collectionOrder:n,collectionName:r,tieFormatName:i,drawDefinition:o,matchUpFormat:s,matchUpCount:c,collectionId:u,matchUpType:d,structureId:p,matchUpId:l,category:m,eventId:f,gender:h,event:g,collectionValueProfiles:I,collectionValue:S,matchUpValue:y,scoreValue:v,setValue:U}){const P="modifyCollectionDefinition",T={collectionValueProfiles:I,collectionValue:S,matchUpValue:y,scoreValue:v,setValue:U},w=function({collectionName:t,matchUpFormat:e,matchUpCount:n,matchUpType:r,collectionOrder:i,valueAssignments:o,category:a,gender:s,stack:c}){if(e&&!Io({matchUpFormat:e}))return Ci({result:{error:sr},context:{matchUpFormat:e},stack:c});if(t&&"string"!=typeof t)return Ci({result:{error:sr},context:{collectionName:t},stack:c});if(s&&!Object.values(ji).includes(s))return Ci({result:{error:sr},context:{gender:s},stack:c});if(a&&"object"!=typeof a)return Ci({result:{error:sr},context:{category:a},stack:c});const u=Object.values(o).filter(Boolean).length;if(!(u||i||t||e||n||r))return Ci({result:{error:Ae},stack:c});if(u>1)return Ci({info:"Only one value assignment allowed per collectionDefinition",result:{error:sr},stack:c});return}({collectionName:r,matchUpFormat:s,matchUpCount:c,matchUpType:d,collectionOrder:n,valueAssignments:T,category:m,gender:h,stack:P});if(w)return w;let D=fB({drawDefinition:o,structureId:p,matchUpId:l,eventId:f,event:g});if(D.error)return Ci({result:D,stack:P});const{matchUp:b,structure:N,tieFormat:M}=D,A=mT(M),E=M?.collectionDefinitions.find(t=>t.collectionId===u),O=A?.collectionDefinitions.find(t=>t.collectionId===u);if(!E)return Ci({info:"source collectionDefinition",result:{error:mr},context:{collectionId:u},stack:P});const k=function({collectionValueProfiles:t,sourceCollectionDefinition:e,collectionValue:n,matchUpValue:r,matchUpCount:i,scoreValue:o,setValue:a,stack:s}){const c=n??r??o??a;if(t?.length){const n=J({matchUpCount:i??e?.matchUpCount??0,collectionValueProfiles:t});if(n.errors)return Ci({result:{error:sr},info:n.errors,stack:s})}else if(c&&!R(c))return Ci({result:{error:sr},info:"value is not an integer",context:{value:c},stack:s});return}({collectionValueProfiles:I,sourceCollectionDefinition:E,collectionValue:S,matchUpValue:y,matchUpCount:c,scoreValue:v,setValue:U,stack:P});if(k?.error)return k;const F=[],x=function({collectionValueProfiles:t,sourceCollectionDefinition:e,collectionValue:n,matchUpValue:r,scoreValue:i,setValue:o}){const a=(t,e)=>V(Object.keys(t),Object.keys(e)).length===Object.keys(t).length&&V(Object.values(t),Object.values(e)).length===Object.values(t).length,s=t&&(!e.collectionValueProfiles||!a(e.collectionValueProfiles,t));return R(n)&&e.collectionValue!==n||R(r)&&e.matchUpValue!==r||R(i)&&e.scoreValue!==i||R(o)&&e.setValue!==o||s}({collectionValueProfiles:I,sourceCollectionDefinition:E,collectionValue:S,matchUpValue:y,scoreValue:v,setValue:U});if(x&&(O.collectionValueProfiles=void 0,O.collectionValue=void 0,O.matchUpValue=void 0,O.scoreValue=void 0,O.setValue=void 0,Object.assign(O,T),F.push({collectionId:u,...Ei(T)})),(R(v)||R(U))&&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),F.push({collectionId:u,change:"collectionGroupNumber removed"})}const{aggregateValue:_,valueGoal:L}=EE(A),B=Ei({aggregateValue:_,valueGoal:L});B.aggregateValue===M?.winCriteria.aggregateValue&&B.valueGoal===M?.winCriteria.valueGoal||(A.winCriteria=B,F.push({collectionId:u,winCriteria:B}));const G=function({targetCollectionDefinition:t,sourceCollectionDefinition:e,collectionOrder:n,collectionName:r,matchUpFormat:i,matchUpCount:o,matchUpType:a,collectionId:s,modifications:c,category:u,gender:d,stack:p}){R(n)&&e.collectionOrder!==n&&(t.collectionOrder=n,c.push({collectionId:s,collectionOrder:n}));r&&e.collectionName!==r&&(t.collectionName=r,c.push({collectionId:s,collectionName:r}));i&&e.matchUpFormat!==i&&(t.matchUpFormat=i,c.push({collectionId:s,matchUpFormat:i}));R(o)&&e.matchUpCount!==o&&(t.matchUpCount=o,c.push({collectionId:s,matchUpCount:o}));if(a&&e.matchUpType!==a)return Ci({result:{error:fr},context:{matchUpType:a},stack:p});u&&e.category!==u&&(t.category=u,c.push({collectionId:s,category:u}));d&&e.gender!==d&&(t.gender=d,c.push({collectionId:s,gender:d}));return}({targetCollectionDefinition:O,sourceCollectionDefinition:E,collectionOrder:n,collectionName:r,matchUpFormat:s,matchUpCount:c,matchUpType:d,collectionId:u,modifications:F,category:m,gender:h,stack:P});if(G?.error)return G;const j=Ei(A);if(D=na({tieFormat:j}),D.error)return Ci({result:D,stack:P});if(!F.length)return Ci({result:{...Y,modifications:F}});if(M?.tieFormatName!==i?(j.tieFormatName=i,F.push({tieFormatName:i})):F.length&&(delete j.tieFormatName,F.push("tieFormatName removed: modifications without new tieFormatName")),D=function({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:n,structure:r,tieFormat:i,eventId:o,matchUp:s,event:c,uuids:u}){const d="updateTieFormat",p=e?.tournamentId;let l=0,m=0,f=0,h=0;const g=i?.collectionDefinitions.reduce((t,e)=>(t[e.collectionId]=(t[e.collectionId]||0)+e.matchUpCount,t),{}),I=({tieFormat:t})=>{const e=t?.collectionDefinitions.reduce((t,e)=>(t[e.collectionId]=(t[e.collectionId]||0)+e.matchUpCount,t),{});return gB({from:e,to:g}).equivalent},S=fB({drawDefinition:n})?.tieFormat,y=fB({event:c})?.tieFormat;if(c&&o){for(const t of c.drawDefinitions??[])v({drawDefinition:t});$k({target:c,tieFormat:mT(i),event:c}),h+=1}else if(s){if(!s.tieMatchUps)return Ci({result:{error:ye},stack:d});const e=C(s.tieMatchUps?.map(({collectionId:t})=>t)),r=gB({to:g,from:e}),{changes:o,changesArePossible:a,cannotChangeReaon:l}=IB({matchUp:s,check:r});if(r.equivalent){if(!hB({matchUp:s,updateInProgressMatchUps:t}))return Ci({result:{error:ze},info:"matchUp is IN_PROGRESS or COMPLETE",stack:d});$k({target:s,tieFormat:mT(i),event:c}),h+=1}else{if(!a)return Ci({context:{collectionMap:g,matchUpMap:e},result:{error:ue},info:l||"specified changes not possible",stack:d});P({tieFormat:i,matchUp:s,changes:o,uuids:u})}m+=1,Yl({eventId:c?.eventId,context:d,drawDefinition:n,tournamentId:p,matchUp:s})}else if(r){const t=S??y,e=U({inheritedTieFormat:t,structure:r})?.modifiedMatchUpsCount;e&&(m+=e,l+=1,h+=1);const o=r.tieFormat??(r.tieFormatId?fB({drawDefinition:n,structure:r,event:c})?.tieFormat:void 0),a=!o||AA({ancestor:o,descendant:i}).different;a&&($k({target:r,tieFormat:mT(i),event:c}),l+=1,h+=1),(e||a)&&n&&Ql({structureIds:[r.structureId],eventId:c?.eventId,drawDefinition:n})}else{if(!n)return{error:st};v({drawDefinition:n}),$k({target:n,tieFormat:mT(i),event:c}),h+=1}return{modifiedStructuresCount:l,modifiedMatchUpsCount:m,addedMatchUpsCount:f,modifiedCount:h,...Y,tieFormat:i};function v({drawDefinition:t}){const e=t.structures??[],n=[];for(const t of e){if(t.tieFormat||t.tieFormatId)continue;const e=y,r=U({inheritedTieFormat:e,structure:t})?.modifiedMatchUpsCount;if(r){l+=1,m+=r;const e=t.structureId;n.push(e)}}return Ql({structureIds:n,eventId:c?.eventId,drawDefinition:t}),n.length}function U({inheritedTieFormat:r,structure:s}){let p=0;const l=Fg({matchUpFilters:{matchUpTypes:[a]},structure:s})?.matchUps??[];for(const a of l){const s=hB({matchUp:a,updateInProgressMatchUps:t});let l=!1;const m=gB({from:C(a.tieMatchUps?.map(({collectionId:t})=>t)),to:g});if(m.equivalent)(a.tieFormat||a.tieFormatId)&&I(a)&&s&&($k({target:a,tieFormat:mT(i),event:c}),l=!0);else{const{changes:t,changesArePossible:e}=IB({matchUp:a,check:m});if(!e||a.tieFormat||a.tieFormatId){if(!r)return Ci({result:{error:me},stack:d});{const t=a.tieFormat??(a.tieFormatId?c?.tieFormats?.find(t=>t.tieFormatId===a.tieFormatId):void 0);(!t||AA({ancestor:r,descendant:t}).different)&&($k({target:a,tieFormat:r,event:c}),l=!0)}}else P({changes:t,matchUp:a,tieFormat:i,uuids:u})}l&&(p+=1,Yl({tournamentId:e?.tournamentId,drawDefinition:n,context:d,eventId:o,matchUp:a}))}return{modifiedMatchUpsCount:p}}function P({uuids:t,matchUp:e,tieFormat:r,changes:i}){$k({target:e,tieFormat:mT(r),event:c});const a=[],s=[];return i.forEach(n=>{if(n.countChange>0){const i=Math.max(0,...e.tieMatchUps.filter(t=>t.collectionId===n.collectionId).map(eI("collectionPosition"))),o=r.collectionDefinitions.find(t=>t.collectionId===n.collectionId),a=VP({matchUpsLimit:n.countChange,collectionPositionOffset:i,collectionDefinition:o,matchUp:e,uuids:t});s.push(...ca(a,!1,!0)),f+=s.length,e.tieMatchUps.push(...a)}else{const t=n.toBePlayedTieMatchUpIds.slice(0,Math.abs(n.countChange));a.push(...t),e.tieMatchUps=e.tieMatchUps.filter(({matchUpId:e})=>!t.includes(e))}}),s.length&&Hl({matchUps:s,drawDefinition:n,tournamentId:p,eventId:o}),a.length&&zl({matchUpIds:a,action:"updateTieFormat",drawDefinition:n,tournamentId:p,eventId:o}),{matchUpIdsRemoved:a,matchUpsAdded:s}}}({tieFormat:j,updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:o,structure:N,eventId:f,matchUp:b,event:g}),!D.error){if(h&&E.gender!==h){const t=function({matchUp:t,structure:e,drawDefinition:n}){if(t)return[t];if(e)return Fg({matchUpFilters:{matchUpTypes:[a]},structure:e})?.matchUps??[];if(n){const t=[];for(const e of n.structures??[]){const n=Fg({matchUpFilters:{matchUpTypes:[a]},structure:e})?.matchUps??[];t.push(...n)}return t}return[]}({matchUp:b,structure:N,drawDefinition:o});for(const e of t)vB(e,u)}const{appliedPolicies:t}=xd({tournamentRecord:e});SB({appliedPolicies:t,drawDefinition:o,auditData:Ei({collectionDefinition:O,drawId:o?.drawId,action:P,structureId:p,matchUpId:l,eventId:f})})}return Ci({result:{...D,modifications:F},stack:P})}function vB(t,e){for(const n of t?.sides??[])n.lineUp=(n.lineUp??[]).map(t=>({participantId:t.participantId,collectionAssignments:(t?.collectionAssignments??[]).filter(t=>t.collectionId!==e)}))}function UB({tieFormat:t,orderMap:e}){const n=mT(t);return n.collectionDefinitions?.forEach(t=>{const n=e[t.collectionId];n&&(t.collectionOrder=n)}),n.collectionDefinitions?.sort((t,e)=>E(t.collectionOrder)-E(e.collectionOrder)),n}function PB({tournamentRecord:t,drawDefinition:e,structureId:n,matchUpId:r,orderMap:i,eventId:o,matchUp:a,event:s}){if("object"!=typeof i||!Object.values(i).every(t=>R(t)))return Ci({result:{error:sr},context:{orderMap:i}});const c=n?ol({drawDefinition:e,structureId:n}):void 0;if(c?.error)return c;const u=c?.structure;if(o&&s?.tieFormat)TB({tournamentRecord:t,event:s,orderMap:i});else if(r){const n=e&&nT({drawDefinition:e,matchUpId:r});if(n?.error)return n;if(!(a=n.matchUp))return{error:Se};const o=kA({tournamentRecord:t,matchUpId:r,structure:u,drawDefinition:e,event:s})?.tieFormat;a.tieFormat=UB({tieFormat:o,orderMap:i}),Yl({tournamentId:t?.tournamentId,eventId:s?.eventId,drawDefinition:e,matchUp:a})}else if(n)if(u?.tieFormat)u.tieFormat=UB({tieFormat:u.tieFormat,orderMap:i}),DB({eventId:s?.eventId,tournamentRecord:t,drawDefinition:e,structure:u,orderMap:i}),Ql({drawDefinition:e,structureIds:[u.structureId]});else if(e.tieFormat)wB({structureIds:[n],tournamentRecord:t,drawDefinition:e,orderMap:i,event:s});else{if(!s?.tieFormat)return{error:mr};TB({structureIds:[n],tournamentRecord:t,orderMap:i,event:s})}else{if(!e?.tieFormat)return{error:mr};wB({tournamentRecord:t,drawDefinition:e,orderMap:i,event:s})}return{...Y}}function TB({tournamentRecord:t,structureIds:e,orderMap:n,event:r}){const i=UB({tieFormat:r.tieFormat,orderMap:n});e?.length||(r.tieFormat=i);for(const i of r.drawDefinitions??[])wB({tournamentRecord:t,drawDefinition:i,structureIds:e,orderMap:n,event:r})}function wB({tournamentRecord:t,drawDefinition:e,structureIds:n,orderMap:r,event:i}){const o=UB({tieFormat:e.tieFormat??i?.tieFormat,orderMap:r});n?.length||(e.tieFormat=o);const a=[];for(const o of e.structures??[])n?.length&&!n.includes(o.structureId)||((o.tieFormat||n?.includes(o.structureId))&&(o.tieFormat=UB({tieFormat:o.tieFormat??e.tieFormat??i?.tieFormat,orderMap:r})),DB({eventId:i?.eventId,tournamentRecord:t,drawDefinition:e,structure:o,orderMap:r}),a.push(o.structureId));Ql({drawDefinition:e,structureIds:a})}function DB({tournamentRecord:t,drawDefinition:e,structure:n,orderMap:r,eventId:i}){const o=Fg({matchUpFilters:{matchUpTypes:[a]},structure:n})?.matchUps;for(const n of o)n.tieFormat&&(n.tieFormat=UB({tieFormat:n.tieFormat,orderMap:r}),Yl({tournamentId:t?.tournamentId,drawDefinition:e,eventId:i,matchUp:n}))}function RB({updateInProgressMatchUps:t=!0,tieFormatComparison:e,tournamentRecord:n,drawDefinition:r,tieFormatName:i,collectionId:o,structureId:s,matchUpId:c,eventId:u,matchUp:d,event:p}){const l="removeCollectionDefinition";let m=d?void 0:fB({drawDefinition:r,structureId:s,matchUpId:c,eventId:u,event:p});if(m?.error)return Ci({result:m,stack:l});const f=m?.structure;d=d??m?.matchUp;const h=m?.tieFormat,g=mT(h);if(m=na({tieFormat:g}),m.error)return Ci({result:m,stack:l});const I=g?.collectionDefinitions?.find(t=>t.collectionId===o);if(!I)return Ci({result:{error:mr,collectionId:o}});g.collectionDefinitions=g.collectionDefinitions.filter(t=>t.collectionId!==o),I.collectionGroupNumber&&(g.collectionDefinitions=g.collectionDefinitions.map(t=>{const{collectionGroupNumber:e,...n}=t;return n}),g.collectionGroups=g.collectionGroups.filter(({groupNumber:t})=>t!==I.collectionGroupNumber));const{aggregateValue:S,valueGoal:y}=EE(g);g.winCriteria=Ei({aggregateValue:S,valueGoal:y});const v=h?.winCriteria.valueGoal,U=h?.winCriteria.aggregateValue;(v&&v!==y||S&&!U)&&(i?g.tieFormatName=i:delete g.tieFormatName);const P=function({matchUpId:t,matchUp:e,structureId:n,structure:r,drawDefinition:i,event:o}){if(t&&e)return[e];if(n&&r)return Fg({matchUpFilters:{matchUpTypes:[a]},structure:r})?.matchUps??[];if(i)return Zg({matchUpFilters:{matchUpTypes:[a]},drawDefinition:i})?.matchUps??[];if(o)return Kg({matchUpFilters:{matchUpTypes:[a]}})?.matchUps??[];return[]}({matchUpId:c,matchUp:d,structureId:s,structure:f,drawDefinition:r,event:p}),T=function({updateInProgressMatchUps:t,tieFormatComparison:e,collectionId:n,tieFormat:r,matchUps:i}){return(i??[]).filter(i=>{const o=i.tieMatchUps?.filter(t=>t.collectionId===n),a=o?.some(aI);if(t&&!a)return!0;if(i.winningSide||i.matchUpStatus===vp)return!1;const s=!(!e||!i.tieFormat)&&AA({descendant:i.tieFormat,ancestor:r})?.different;return t||i.matchUpStatus!==Dp&&!aI(i)&&!s})}({updateInProgressMatchUps:t,tieFormatComparison:e,collectionId:o,tieFormat:g,matchUps:P});if(!T.length)return{error:Zn};const{appliedPolicies:w}=xd({tournamentRecord:n});if(c&&d&&t){const t=function({tournamentRecord:t,appliedPolicies:e,drawDefinition:n,collectionId:r,matchUpId:i,matchUp:o,event:a}){const s=o.tieMatchUps?.filter(t=>t.collectionId===r);let c=o;for(const r of s??[]){let o=Ek({matchUpId:r.matchUpId,tieMatchUpId:c?.matchUpId,winningSide:void 0,removeScore:!0,tournamentRecord:t,appliedPolicies:e,drawDefinition:n,event:a});if(o.error)return o;if(o=nT({drawDefinition:n,matchUpId:i}),o.error)return o;c=o?.matchUp}return{matchUp:c}}({tournamentRecord:n,appliedPolicies:w,drawDefinition:r,collectionId:o,matchUpId:c,matchUp:d,event:p});if(t.error)return t;d=t.matchUp}const D=[];for(const e of T){bB({deletedMatchUpIds:D,tournamentRecord:n,drawDefinition:r,collectionId:o,tieFormat:g,stack:l,event:p,matchUp:e});const i=NB({updateInProgressMatchUps:t,tournamentRecord:n,appliedPolicies:w,drawDefinition:r,matchUp:e,event:p});if(i?.error)return i}D.length&&zl({tournamentId:n?.tournamentId,matchUpIds:D,eventId:p?.eventId,drawDefinition:r});const R=Ei(g);if(m=na({tieFormat:R}),m.error)return Ci({result:m,stack:l});if(u&&p)$k({target:p,tieFormat:R,event:p});else if(c&&d)$k({target:d,tieFormat:R,event:p});else if(f)$k({target:f,tieFormat:R,event:p});else if(r)$k({target:r,tieFormat:R,event:p});else if(!d||!r)return{error:st};Ql({drawDefinition:r,eventId:p?.eventId});return SB({appliedPolicies:w,drawDefinition:r,auditData:Ei({drawId:r?.drawId,action:l,collectionId:o,structureId:s,matchUpId:c,eventId:u})}),{tieFormat:R,deletedMatchUpIds:D,targetMatchUps:T,...Y}}function bB({deletedMatchUpIds:t,collectionId:e,tieFormat:n,stack:r,event:i,matchUp:o,tournamentRecord:a,drawDefinition:s}){for(const t of o?.sides??[])t.lineUp=(t.lineUp??[]).map(t=>({participantId:t.participantId,collectionAssignments:(t?.collectionAssignments??[]).filter(t=>t.collectionId!==e)}));o.tieMatchUps=(o.tieMatchUps??[]).filter(n=>{const r=n.collectionId===e;return r&&t.push(n.matchUpId),!r}),(o.tieFormat||o.tieFormatId)&&$k({target:o,tieFormat:mT(n),event:i}),Yl({tournamentId:a?.tournamentId,eventId:i?.eventId,drawDefinition:s,context:r,matchUp:o})}function NB({updateInProgressMatchUps:t,tournamentRecord:e,appliedPolicies:n,drawDefinition:r,matchUp:i,event:o}){if(t)return gT({matchUpId:i.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,appliedPolicies:n,drawDefinition:r,event:o})}function MB({updateInProgressMatchUps:t=!0,collectionDefinition:e,referenceCategory:n,tournamentRecord:r,policyDefinitions:i,enforceCategory:o,referenceGender:a,drawDefinition:s,tieFormatName:c,enforceGender:u,structureId:d,matchUpId:p,matchUp:l,eventId:m,uuids:f,event:h}){const g="addCollectionDefinition",I=xd({tournamentRecord:r,drawDefinition:s,event:h}).appliedPolicies??{},{checkCategory:S,checkGender:y}=function({policyDefinitions:t,appliedPolicies:e,enforceCategory:n,enforceGender:r,referenceCategory:i,referenceGender:o,event:a}){const s=t?.[Nu]??e?.[Nu],c=n??s?.participants?.enforceCategory,u=!1!==(r??s?.participants?.enforceGender),d=!(!(i??a?.category)||!1===c),p=!(!(o??a?.gender)||!u);return{checkCategory:d,checkGender:p}}({policyDefinitions:i,appliedPolicies:I,enforceCategory:o,enforceGender:u,referenceCategory:n,referenceGender:a,event:h}),v=ea({referenceCategory:n??h?.category,collectionDefinition:e,referenceGender:a,checkCategory:S,checkGender:y,event:h});if(v.error)return Ci({result:v,stack:g});let U=l?.tieFormat?void 0:fB({drawDefinition:s,structureId:d,matchUpId:p,eventId:m,event:h});if(U?.error)return Ci({result:{error:U.error},stack:g});const P=U?.structure;l=l??U?.matchUp;const T=l?.tieFormat??U?.tieFormat,w=mT(T);if(U=na({tieFormat:w}),U?.error)return Ci({result:{error:U.error},stack:g});if(e.collectionId){if(w.collectionDefinitions.map(({collectionId:t})=>t).includes(e.collectionId))return Ci({context:{collectionId:e.collectionId},result:{error:cr}})}else e.collectionId=pa();w.collectionDefinitions.push(e),w.collectionDefinitions.sort((t,e)=>(t.collectionOrder||0)-(e.collectionOrder||0)).forEach((t,e)=>t.collectionOrder=e+1);const{aggregateValue:D,valueGoal:R}=EE(w);w.winCriteria=Ei({aggregateValue:D,valueGoal:R});const b=T?.winCriteria.valueGoal,N=T?.winCriteria.aggregateValue;(b&&b!==R||D&&!N)&&(c?w.tieFormatName=c:delete w.tieFormatName);const M=[];let A=[];const E=Ei(w);if(U=na({tieFormat:E}),U?.error)return Ci({result:{error:U.error},stack:g});const C=function({updateInProgressMatchUps:t,collectionDefinition:e,modifiedStructureIds:n,prunedTieFormat:r,tournamentRecord:i,drawDefinition:o,targetMatchUps:a,addedMatchUps:s,structureId:c,structure:u,matchUpId:d,matchUp:p,eventId:l,event:m,uuids:f,stack:h}){if(l&&m){$k({target:m,tieFormat:r,event:m});for(const r of m.drawDefinitions??[])if(!r.tieFormat&&!r.tieFormatId)for(const i of r.structures??[]){if(i.tieFormat||i.tieFormatId)continue;const r=AB({updateInProgressMatchUps:t,collectionDefinition:e,structure:i,uuids:f});s.push(...r.newMatchUps),a.push(...r.targetMatchUps),n.push(i.structureId)}return EB({modifiedMatchUps:a,eventId:m?.eventId,modifiedStructureIds:n,tournamentRecord:i,drawDefinition:o,addedMatchUps:s,stack:h}),{targetMatchUps:a}}if(c&&u){$k({target:u,tieFormat:r,event:m});const a=AB({updateInProgressMatchUps:t,collectionDefinition:e,structure:u,uuids:f});s.push(...a.newMatchUps);const c=a.targetMatchUps;return EB({modifiedMatchUps:c,eventId:m?.eventId,modifiedStructureIds:n,tournamentRecord:i,drawDefinition:o,addedMatchUps:s,stack:h}),{targetMatchUps:c}}if(d&&p){if(!hB({matchUp:p,updateInProgressMatchUps:t}))return Ci({result:{error:ze},stack:h});$k({target:p,tieFormat:r,event:m});const c=VP({collectionDefinition:e,matchUp:p,uuids:f});return Array.isArray(p.tieMatchUps)||(p.tieMatchUps=[]),p.tieMatchUps.push(...c),s.push(...c),EB({modifiedMatchUps:[p],eventId:m?.eventId,modifiedStructureIds:n,tournamentRecord:i,drawDefinition:o,addedMatchUps:s,stack:h}),{targetMatchUps:a}}if(o){$k({target:o,tieFormat:r,event:m});for(const r of o.structures??[]){const i=AB({updateInProgressMatchUps:t,collectionDefinition:e,structure:r,uuids:f});n.push(r.structureId),s.push(...i.newMatchUps),a.push(...i.targetMatchUps)}return EB({modifiedMatchUps:a,eventId:m?.eventId,tournamentRecord:i,drawDefinition:o,addedMatchUps:s,stack:h}),{targetMatchUps:a}}return{error:st}}({updateInProgressMatchUps:t,collectionDefinition:e,modifiedStructureIds:[],prunedTieFormat:E,tournamentRecord:r,drawDefinition:s,targetMatchUps:A,addedMatchUps:M,structureId:d,structure:P,matchUpId:p,matchUp:l,eventId:m,event:h,uuids:f,stack:g});if(C?.error)return C;A=C?.targetMatchUps??A;return SB({appliedPolicies:I,drawDefinition:s,auditData:Ei({drawId:s?.drawId,collectionDefinition:e,action:g,structureId:d,matchUpId:p,eventId:m})}),{tieFormat:E,targetMatchUps:A,addedMatchUps:M,...Y}}function AB({updateInProgressMatchUps:t,collectionDefinition:e,structure:n,uuids:r}){const i=[],o=Fg({matchUpFilters:{matchUpTypes:[a]},structure:n})?.matchUps,s=o.filter(e=>hB({matchUp:e,updateInProgressMatchUps:t})&&!e.tieFormat&&!e.tieFormatId);for(const t of s){const n=VP({collectionDefinition:e,matchUp:t,uuids:r});Array.isArray(t.tieMatchUps)||(t.tieMatchUps=[]),t.tieMatchUps.push(...n),i.push(...n)}return{newMatchUps:i,targetMatchUps:s}}function EB({modifiedStructureIds:t,tournamentRecord:e,modifiedMatchUps:n,drawDefinition:r,addedMatchUps:i,eventId:o,stack:a}){Hl({tournamentId:e?.tournamentId,matchUps:i,drawDefinition:r,eventId:o}),n?.forEach(t=>{Yl({tournamentId:e?.tournamentId,drawDefinition:r,context:a,matchUp:t,eventId:o})}),Ql({structureIds:t,drawDefinition:r,eventId:o})}function CB({updateInProgressMatchUps:t,originalValueGoal:e,tournamentRecord:n,wasAggregateValue:r,tieFormatName:i,drawDefinition:o,structureId:s,structure:c,tieFormat:u,matchUpId:d,matchUp:p,eventId:l,event:m}){const{aggregateValue:f,valueGoal:h}=EE(u);u.winCriteria=Ei({aggregateValue:f,valueGoal:h}),(e&&e!==h||f&&!r)&&(i?u.tieFormatName=i:delete u.tieFormatName);const{targetMatchUps:g}=function({updateInProgressMatchUps:t,drawDefinition:e,structureId:n,structure:r,matchUpId:i,matchUp:o}){let s=[];i&&o?s=[o]:n&&r?s=Fg({matchUpFilters:{matchUpTypes:[a]},structure:r})?.matchUps??[]:e&&(s=Zg({matchUpFilters:{matchUpTypes:[a]},drawDefinition:e})?.matchUps??[]);const c=s.filter(e=>!e.winningSide&&e.matchUpStatus!==vp&&(t||e.matchUpStatus!==Dp&&!aI(e)));return{targetMatchUps:c}}({updateInProgressMatchUps:t,drawDefinition:o,structureId:s,structure:c,matchUpId:d,matchUp:p});!function({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:n,targetMatchUps:r,tieFormat:i,event:o}){for(const a of r){const r=!!a.tieFormat;let s;if(r&&(a.tieFormat=mT(i)),t){const t=xd({tournamentRecord:e,drawDefinition:n,event:o}).appliedPolicies,r=gT({matchUpId:a.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,appliedPolicies:t,drawDefinition:n,event:o});if(r.error)return r;s=r.score}r&&!s&&Yl({tournamentId:e?.tournamentId,context:"updateTargetTeamMatchUps",eventId:o?.eventId,matchUp:a,drawDefinition:n})}}({updateInProgressMatchUps:t,tournamentRecord:n,targetMatchUps:g,drawDefinition:o,tieFormat:u,event:m});const I=Ei(u),S=na({tieFormat:I});if(S.error)return S;if(l&&m)$k({target:m,tieFormat:I,event:m});else if(d&&p)$k({target:p,tieFormat:I,event:m});else if(c)$k({target:c,tieFormat:I,event:m});else if(o)$k({target:o,tieFormat:I,event:m});else if(!p||!o)return{error:st};return Ql({drawDefinition:o,eventId:m?.eventId}),{...Y}}function OB({updateInProgressMatchUps:t=!0,collectionGroupNumber:e,tournamentRecord:n,drawDefinition:r,tieFormatName:i,structureId:o,matchUpId:a,matchUp:s,eventId:c,event:u}){if(!e)return{error:Ae};if(Number.isNaN(Number(e)))return{error:sr};const d="removeCollectionGroup";let p=s?void 0:fB({drawDefinition:r,structureId:o,matchUpId:a,eventId:c,event:u});if(p?.error)return Ci({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=mT(m);if(p=na({tieFormat:g}),p.error)return Ci({result:p,stack:d});const I=[];if(g.collectionDefinitions=(g.collectionDefinitions??[]).map(t=>{const{collectionGroupNumber:n,...r}=t;return n===e?(I.push(t.collectionId),r):t}),g.collectionGroups=(g.collectionGroups??[]).filter(({groupNumber:t})=>t!==e),p=CB({updateInProgressMatchUps:t,originalValueGoal:f,wasAggregateValue:h,tournamentRecord:n,drawDefinition:r,tieFormatName:i,structureId:o,structure:l,tieFormat:g,matchUpId:a,matchUp:s,eventId:c,event:u}),!p.error){const{appliedPolicies:t}=xd({tournamentRecord:n});SB({appliedPolicies:t,drawDefinition:r,auditData:Ei({drawId:r?.drawId,collectionGroupNumber:e,action:d,structureId:o,matchUpId:a,eventId:c})})}return Ci({result:{...p,modifiedCollectionIds:I},stack:d})}function kB({tournamentRecord:t}){if(!t)return{error:rt};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){AA({descendant:t.tieFormat,ancestor:e}).different||(n=e.tieFormatId)}if(n)t.tieFormatId=n,delete t.tieFormat;else{const n=ca(t.tieFormat,void 0,!0);n.tieFormatId??=pa(),t.tieFormatId=n.tieFormatId,delete t.tieFormat,r.push(n),e+=1}};i(n);for(const t of n.drawDefinitions??[]){i(t);for(const e of t.structures??[])i(e)}const a=(e,r)=>{const i=c.matchUps?.find(t=>t.matchUpId===e);i&&(i.tieFormatId=r,delete i.tieFormat,Yl({tournamentId:t?.tournamentId,eventId:n.eventId,matchUp:i}))},s=t=>{const n=ca(t.tieFormat,void 0,!0);n.tieFormatId??=pa(),r.push(n),e+=1,a(t.matchUpId,n.tieFormatId)},c=Kg({matchUpFilters:{matchUpTypes:[o]},event:n}),u=c.matchUps??[];for(const t of u){let e;for(const n of r){t.tieFormat&&AA({descendant:t.tieFormat,ancestor:n}).different||(e=n.tieFormatId)}e?a(t.matchUpId,e):s(t)}r.length&&(n.tieFormats=r)}return{...Y,addedCount:e}}function FB({updateInProgressMatchUps:t=!0,tournamentRecord:e,groupDefinition:n,drawDefinition:r,collectionIds:i,tieFormatName:o,structureId:a,matchUpId:s,matchUp:c,eventId:u,event:d}){const p="addCollectionGroup";if(!Array.isArray(i))return Ci({result:{error:Ae},stack:p});let l=c?void 0:fB({drawDefinition:r,structureId:a,matchUpId:s,eventId:u,event:d});if(l?.error)return Ci({result:l,stack:p});const m=l?.structure;c=c||l?.matchUp;const f=l?.tieFormat,h=f?.winCriteria.valueGoal,g=mT(f);if(l=na({tieFormat:g}),l.error)return Ci({result:l,stack:p});for(const t of g.collectionDefinitions){const{collectionId:e,collectionGroupNumber:n}=t;if(n&&i.includes(e))return Ci({info:"collectionIds cannot be part of other collectionGroups",result:{error:sr},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],CB({updateInProgressMatchUps:t,originalValueGoal:h,tournamentRecord:e,drawDefinition:r,tieFormatName:o,structureId:a,structure:m,tieFormat:g,matchUpId:s,matchUp:c,eventId:u,event:d})}function xB({updateInProgressMatchUps:t=!1,tieFormatComparison:e,modifiedTieFormat:n,tournamentRecord:r,considerations:i,drawDefinition:o,structureId:a,matchUpId:s,eventId:c,uuids:u,event:d}){const p="modifyTieFormat";if(!na({tieFormat:n}).valid)return Ci({result:{error:ue},info:"falied validation",stack:p});const l=fB({drawDefinition:o,structureId:a,matchUpId:s,eventId:c,event:d});if(l.error)return Ci({result:l,stack:p});const{matchUp:m,tieFormat:f}=l,h=mT(f),g=AA({descendant:n,ancestor:h,considerations:i});if(g.invalid)return Ci({context:{invalid:g.invalid},result:{error:ue},stack:p});if(!g?.different)return Ci({result:{...Y},info:"Nothing to do",stack:p});const I=h.collectionDefinitions.map(({collectionId:t})=>t),S=n.collectionDefinitions.map(({collectionId:t})=>t),y=I.filter(t=>!S.includes(t)),v=n.collectionDefinitions.filter(({collectionId:t})=>!I.includes(t)),U=v.map(eI("collectionId")),P=[];let T;const w=n.tieFormatName;for(const e of n.collectionDefinitions){if(U.includes(e.collectionId))continue;const n=yB({updateInProgressMatchUps:t,...e,tournamentRecord:r,tieFormatName:w,drawDefinition:o,structureId:a,matchUpId:s,eventId:c,event:d});if(n.modifications&&P.push(...n.modifications),n.error)return Ci({result:n,stack:p});n.tieFormat&&(T=n.tieFormat)}for(const e of v){const n=MB({updateInProgressMatchUps:t,collectionDefinition:e,tournamentRecord:r,drawDefinition:o,tieFormatName:w,structureId:a,matchUpId:s,matchUp:m,eventId:c,uuids:u,event:d});if(n.error)return Ci({result:n,stack:p});n.tieFormat&&(T=n.tieFormat)}for(const n of y){const i=RB({updateInProgressMatchUps:t,tieFormatComparison:e,tournamentRecord:r,drawDefinition:o,tieFormatName:w,collectionId:n,structureId:a,matchUpId:s,eventId:c,matchUp:m,event:d});if(i.error)return Ci({result:i,stack:p});i.tieFormat&&(T=i.tieFormat)}return f?.tieFormatName!==w?(T.tieFormatName=w,P.push({tieFormatName:w})):(P.length||U.length||y.length)&&(delete T.tieFormatName,P.push("tieFormatName removed: modifications without new tieFormatName")),T.collectionDefinitions=T.collectionDefinitions.sort((t,e)=>E(t.collectionOrder)-E(e.collectionOrder)).map((t,e)=>({...t,collectionOrder:e+1})),{processedTieFormat:mT(T),modifications:P,...Y}}var _B={__proto__:null,addCollectionDefinition:MB,addCollectionGroup:FB,aggregateTieFormats:kB,compareTieFormats:AA,getTieFormat:kA,modifyCollectionDefinition:yB,modifyTieFormat:xB,mutate:{__proto__:null,addCollectionDefinition:MB,addCollectionGroup:FB,aggregateTieFormats:kB,modifyCollectionDefinition:yB,modifyTieFormat:xB,orderCollectionDefinitions:PB,removeCollectionDefinition:RB,removeCollectionGroup:OB,removeOrphanedTieFormats:Hk},orderCollectionDefinitions:PB,query:FA,removeCollectionDefinition:RB,removeCollectionGroup:OB,removeOrphanedTieFormats:Hk,tieFormatGenderValidityCheck:Ki,validateCollectionDefinition:ea};function LB(t){const e=fu(t,[{tournamentRecord:!0,startDate:!0,endDate:!1,tournamentName:!0}]);if(e.error)return e;const{startDate:n,endDate:r}=t.tournamentRecord,i=(n&&r?new Date(Lo(r)).getTime()-new Date(Lo(n)).getTime():0)/864e5,o=t.endDate||qo(t.startDate,i),a=e=>e?.filter(({itemType:e})=>t.itemTypeList?.includes(e)),s=e=>e?.filter(({name:e})=>t.extensionList?.includes(e)),c={participants:t.copyParticipants?t.tournamentRecord.participants?.map(t=>{const{timeItems:e,extensions:n,...r}=t;return ca({...r,timeItems:a(e),extensions:s(n)},!1,!0)})??[]:[],parentOrganisation:ca({...t.tournamentRecord.parentOrganisation},!1,!0),venues:ca(t.tournamentRecord.venues??[],!1,!0),extensions:s(t.tournamentRecord.extensions),timeItems:a(t.tournamentRecord.timeItems),events:t.tournamentRecord.events?.map(e=>{const{drawDefinitions:n,timeItems:r,extensions:i,startDate:c,endDate:u,...d}=e;return ca({extensions:s(i),timeItems:a(r),startDate:t.startDate,endDate:o,...d},!1,!0)})??[],weekdays:[...t.tournamentRecord.weekdays??[]],tournamentName:t.tournamentName,startDate:t.startDate,tournamentId:pa(),endDate:o};return{...Y,tournamentRecord:c}}const BB=[{itemType:rh,attribute:"scheduledDate"},{itemType:ah,attribute:"scheduledTime"},{itemType:th,attribute:"courtId"},{itemType:Xf,attribute:"venueId"},{itemType:eh,attribute:"courtOrder"},{itemType:nh,attribute:"courtAnnotation"},{itemType:Zf,attribute:"allocatedCourts"},{itemType:ph,attribute:"timeModifiers"},{itemType:ih,attribute:"homeParticipantId"},{itemType:oh,attribute:"official"}];function VB(t,e,n){const r=t?.extensions;if(!Array.isArray(r))return!1;const i=r.findIndex(t=>t?.name===e.name);if(-1===i)return!1;const o=r[i].value,a=e.translate?e.translate(o):o;return void 0===t[e.attribute]&&(t[e.attribute]=a),n&&r.splice(i,1),!0}function GB(t,e,n){const r=t?.extensions;if(!Array.isArray(r))return!1;const i=r.findIndex(t=>t?.name===e.name);return-1!==i&&(t[e.groupAttribute]||(t[e.groupAttribute]={}),void 0===t[e.groupAttribute][e.leafAttribute]&&(t[e.groupAttribute][e.leafAttribute]=r[i].value),n&&r.splice(i,1),!0)}function jB(t,e,n,r){const i=t?.timeItems;if(!Array.isArray(i))return!1;const o=i.filter(t=>t?.itemType===e);if(!o.length)return!1;const a=o.toSorted((t,e)=>(t.createdAt?new Date(t.createdAt).getTime():0)-(e.createdAt?new Date(e.createdAt).getTime():0))[o.length-1];return void 0===a.itemValue||null===a.itemValue?(r&&(t.timeItems=i.filter(t=>t?.itemType!==e)),!0):(t.schedule=t.schedule??{},void 0===t.schedule[n]&&(t.schedule[n]=a.itemValue),r&&(t.timeItems=i.filter(t=>t?.itemType!==e)),!0)}const qB=[{name:pd,attribute:"factory"},{name:hd,attribute:"linkedTournamentIds",translate:t=>t?.tournamentIds??t}],WB=[{name:wd,groupAttribute:"scheduling",leafAttribute:"profile"},{name:Pd,groupAttribute:"scheduling",leafAttribute:"dailyLimits"},{name:Td,groupAttribute:"scheduling",leafAttribute:"timing"}],$B=[{name:ld,attribute:"flightProfile"}],HB=[{name:vd,attribute:"roundTarget"}],zB=[{name:ld,attribute:"flightProfile"},{name:fd,attribute:"lineUps"},{name:ud,attribute:"draftState"},{name:nd,attribute:"competitionState"}],YB=[{name:vd,attribute:"roundTarget"}],KB=[{name:Rd,attribute:"tally"},{name:Dd,attribute:"subOrder"},{name:sd,attribute:"disableLinks"}],QB=[{name:id,attribute:"delegatedOutcome"},{name:ad,attribute:"disableAutoCalc"}],JB=[{name:od,attribute:"disabled"}],XB=[{name:od,attribute:"disabled"}];function ZB(t,e,n){let r=0;for(const i of e)VB(t,i,n)&&(r+=1);return r}function tV(t,e,n){e.tournament+=ZB(t,qB,n),e.tournament+=function(t,e,n){let r=0;for(const i of e)GB(t,i,n)&&(r+=1);return r}(t,WB,n)}function eV(t,e,n){e.drawDefinitions+=ZB(t,zB,n);for(const r of t.entries??[])e.entries+=ZB(r,HB,n);aV(t.structures??[],e,n)}function nV(t,e,n){e.events+=ZB(t,$B,n);for(const r of t.entries??[])e.entries+=ZB(r,HB,n);for(const r of t.drawDefinitions??[])eV(r,e,n)}function rV(t){let e=0;for(const n of Object.values(t))e+=n;return e}function iV({tournamentRecord:t,clearLegacy:e=!0}){if(!t||"object"!=typeof t)return{error:rt};const n={tournament:0,events:0,entries:0,drawDefinitions:0,structures:0,positionAssignments:0,matchUps:0,matchUpScheduleTimeItems:0,venues:0,courts:0};tV(t,n,e),function(t,e,n){for(const r of t.venues??[]){e.venues+=ZB(r,JB,n);for(const t of r.courts??[])e.courts+=ZB(t,XB,n)}}(t,n,e);for(const r of t.events??[])nV(r,n,e);return{...Y,promoted:n,totalPromoted:rV(n)}}function oV(t,e,n){for(const{itemType:r,attribute:i}of BB)jB(t,r,i,n)&&(e.matchUpScheduleTimeItems+=1)}function aV(t,e,n){for(const r of t){e.structures+=ZB(r,YB,n);for(const t of r.positionAssignments??[])e.positionAssignments+=ZB(t,KB,n);for(const t of r.matchUps??[])e.matchUps+=ZB(t,QB,n),oV(t,e,n);Array.isArray(r.structures)&&aV(r.structures,e,n)}}function sV(t){const{tournamentRecord:e,drawDefinition:n,event:r,venueId:i,lockId:o,scope:a,lockToken:s,forceRelease:c}=t;if(!e)return{error:rt};if(!o&&!a)return{error:Ae,info:"Provide lockId or scope to identify the lock"};let u;if(n)u=n;else if(r)u=r;else if(i){const t=Ig({tournamentRecord:e,venueId:i});if(t.error)return{error:t.error};u=t.venue}else u=e;const{extension:d}=td({element:u,name:gd}),p=d?.value??{locks:[]},l=p.locks.findIndex(t=>o?t.lockId===o:t.scope===a);if(-1===l)return{error:wr};const m=p.locks[l];return c||m.lockToken===s?(p.locks.splice(l,1),$u({element:u,extension:{name:gd,value:p},creationTime:!1}),{...Y}):{error:Dr}}function cV(t){const{tournamentRecord:e,drawDefinition:n,event:r,venueId:i,scope:o,lockToken:a,methods:s}=t,c=t.expiresAt??null;if(!e)return{error:rt};if(!o||!a)return{error:Ae,info:o?"Missing lockToken":"Missing scope"};if(null!==c&&isNaN(Date.parse(c)))return{error:sr,info:"Invalid expiresAt; must be ISO 8601 or null"};let u;if(n)u=n;else if(r)u=r;else if(i){const t=Ig({tournamentRecord:e,venueId:i});if(t.error)return{error:t.error};u=t.venue}else u=e;const{extension:d}=td({element:u,name:gd}),p=d?.value??{locks:[]},l=(new Date).toISOString();p.locks=p.locks.filter(t=>null===t.expiresAt||t.expiresAt>l);const m=p.locks.find(t=>t.scope===o&&(!t.methods||!s||t.methods.some(t=>s.includes(t))));if(m)return m.lockToken===a?(m.expiresAt=c,s?m.methods=s:delete m.methods,$u({element:u,extension:{name:gd,value:p},creationTime:!1}),{...Y,lockId:m.lockId}):{error:Tr};const f=pa(),h={lockId:f,lockToken:a,scope:o,expiresAt:c,createdAt:l,...s&&{methods:s}};return p.locks.push(h),$u({element:u,extension:{name:gd,value:p},creationTime:!1}),function(t,e){if(e===t){const{extension:e}=td({element:t,name:gd});return void(e?.value&&!e.value.enabled&&(e.value.enabled=!0,$u({element:t,extension:{name:gd,value:e.value},creationTime:!1})))}const{extension:n}=td({element:t,name:gd});n?.value?n.value.enabled||(n.value.enabled=!0,$u({element:t,extension:{name:gd,value:n.value},creationTime:!1})):$u({element:t,extension:{name:gd,value:{enabled:!0,locks:[]}},creationTime:!1})}(e,u),{...Y,lockId:f}}function uV(t){const{tournamentRecord:e,eventProfiles:n=[],directives:r,policyDefinitions:i}=t;if(!e)return{error:rt};return(e.events??[]).forEach(t=>{const e=n.find(e=>e.eventId&&e.eventId===t.eventId);(e?.directives?.hydrateRoundNames||r?.hydrateRoundNames)&&t.drawDefinitions?.forEach(t=>{(e?.policyDefinitions?.[Au]||i?.[Au])&&JN({drawDefinition:t,appliedPolicies:i})})}),{tournamentRecord:e}}function dV({tournamentRecord:t,status:e}){return t?e&&!Object.keys(vw).includes(e)?{error:sr,info:"Unknown status"}:(t.tournamentStatus=e,{...Y}):{error:rt}}function pV(t){const e=fu(t,[{tournamentRecord:!0,onlineResource:!0}]);if(e.error)return e;const{tournamentRecord:n,onlineResource:r,organisationId:i,participantId:o,personId:a,courtId:s,venueId:c}=t;if(i){if(n.parentOrganisation?.parentOrganisationId!==i)return Ci({result:{error:mr}});lV({element:n.parentOrganisation,onlineResource:r})}else if(o||a){const t=(n.participants??[]).find(t=>a&&t.person?.personId===a||t.participantId===o);if(!t)return Ci(a?{result:{error:mr}}:{result:{error:un}});if(a){if(t.person?.personId!==a)return Ci({result:{error:Xe}});lV({element:t.person,onlineResource:r})}else lV({element:t,onlineResource:r})}else if(s){const t=(n.venues??[]).filter(t=>!c||t.venueId===c).flatMap(t=>(t.courts??[]).filter(t=>t.courtId===s))?.[0];if(!t)return Ci({result:{error:Cn}});lV({element:t,onlineResource:r})}else if(c){const t=(n.venues??[]).find(t=>t.venueId===c);if(!t)return Ci({result:{error:Ln}});lV({element:t,onlineResource:r})}else lV({element:n,onlineResource:r}),di({payload:{parentOrganisation:n.parentOrganisation,onlineResources:n.onlineResources,tournamentId:n.tournamentId},topic:Al});return{...Y}}function lV({element:t,onlineResource:e}){const n=(t.onlineResources??[]).filter(t=>!(t?.[ra]===e[ra]&&t?.[ia]===e[ia]&&t?.[oa]===e[oa]));t.onlineResources=n}function mV(t){const e=fu(t,[{tournamentRecord:!0,onlineResource:!0}]);if(e.error)return e;const{tournamentRecord:n,onlineResource:r,organisationId:i,participantId:o,personId:a,courtId:s,venueId:c}=t;if(i){if(n.parentOrganisation?.parentOrganisationId!==i)return Ci({result:{error:mr}});fV({element:n.parentOrganisation,onlineResource:r})}else{if(o&&a&&o!==a)return Ci({result:{error:Xe}});if(o||a){const t=(n.participants??[]).find(t=>a&&t.person?.personId===a||t.participantId===o);if(!t)return Ci(a?{result:{error:mr}}:{result:{error:un}});if(a){if(t.person?.personId!==a)return Ci({result:{error:Xe}});fV({element:t.person,onlineResource:r})}else fV({element:t,onlineResource:r})}else if(s){const t=(n.venues??[]).filter(t=>!c||t.venueId===c).flatMap(t=>(t.courts??[]).filter(t=>t.courtId===s))?.[0];if(!t)return Ci({result:{error:Cn}});fV({element:t,onlineResource:r})}else if(c){const t=(n.venues??[]).find(t=>t.venueId===c);if(!t)return Ci({result:{error:Ln}});fV({element:t,onlineResource:r})}else fV({element:n,onlineResource:r}),di({payload:{parentOrganisation:n.parentOrganisation,onlineResources:n.onlineResources,tournamentId:n.tournamentId},topic:Al})}return{...Y}}function fV({element:t,onlineResource:e}){const n=(t.onlineResources??[]).filter(t=>t?.[aa]!==e[aa]&&t?.[oa]!==e[oa]);return n.push(e),t.onlineResources=n,{...Y}}function hV({tournamentRecord:t,promotionalName:e,tournamentName:n,formalName:r}){const i=dl({tournamentRecord:t},[Ic]);if(i.error)return i;const o=t.tournamentId,a={tournamentId:o};return n&&n!==t.tournamentName&&(t.tournamentName=n,a.tournamentName=n),e&&e!==t.promotionalName&&(t.promotionalName=e,a.promotionalName=e),r&&r!==t.formalName&&(t.formalName=r,a.formalName=r),t.promotionalName===t.tournamentName&&(delete t.promotionalName,a.promotionalName=""),t.formalName===t.tournamentName&&(delete t.formalName,a.formalName=""),Object.keys(a).length>1&&di({topic:Al,payload:{parentOrganisation:t.parentOrganisation,tournamentId:o,...a}}),{...Y}}function gV({tournamentRecord:t,notes:e}){const n=dl({tournamentRecord:t},[Ic]);if(n.error)return n;const r=e?rT({element:t,notes:e}):iT({element:t});return r.error?r:(di({topic:Al,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,notes:e??""}}),{...Y})}function IV({tournamentRecord:t,localTimeZone:e}){const n=dl({tournamentRecord:t},[Ic]);if(n.error)return n;const r="string"==typeof e?e.trim():"";if(r)try{new Intl.DateTimeFormat(void 0,{timeZone:r})}catch{return{error:Ge}}return r===(t.localTimeZone??"")||(r?t.localTimeZone=r:delete t.localTimeZone,di({topic:Al,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,localTimeZone:r}})),{...Y}}function SV({tournamentRecord:t,tournamentTier:e}){const n=dl({tournamentRecord:t},[Ic]);if(n.error)return n;if(e&&"object"==typeof e){if(!e.system||!e.value)return{error:"TierClassification requires system and value"};t.tournamentTier={system:String(e.system).trim(),value:String(e.value).trim(),...void 0!==e.numericRank?{numericRank:Number(e.numericRank)}:{}}}else delete t.tournamentTier;return di({topic:Al,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,tournamentTier:t.tournamentTier??null}}),{...Y}}function yV({tournamentRecord:t,registrationProfile:e}){const n=dl({tournamentRecord:t},[Ic]);return n.error?n:(e&&"object"==typeof e?t.registrationProfile={...t.registrationProfile,...e}:delete t.registrationProfile,di({topic:Al,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,registrationProfile:t.registrationProfile??null}}),{...Y})}function vV({tournamentRecord:t,categories:e}){const n=dl({tournamentRecord:t},[Ic]);if(n.error)return n;e=(e??[]).filter(t=>t.categoryName&&t.type);const r=new Set,i=new Set;for(const t of e)t.ageCategoryCode&&r.add(t.ageCategoryCode),t.categoryName&&i.add(t.categoryName);const o=[];for(const e of t.events??[]){const t=e?.category;if(!t)continue;const n=t.ageCategoryCode,a=t.categoryName;!n||r.has(n)||i.has(n)?!a||i.has(a)||r.has(a)||o.push(a):o.push(n)}return o.length?{error:Nr,referenced:[...new Set(o)]}:(t.tournamentCategories=e,di({topic:Al,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,categories:e}}),{...Y})}function UV(t){const{tournamentRecord:e,startDate:n,endDate:r,weekdays:i}=t,o=t.activeDates?.filter(Boolean),a=fu(t,[{tournamentRecord:!0},{[ou]:t=>vo.test(t),[su]:_e,startDate:!1,endDate:!1},{[ou]:t=>t.filter(Boolean).every(t=>vo.test(t)),[su]:_e,activeDates:!1},{[ou]:GC,weekdays:!1}]);if(a.error)return a;if(r&&n&&new Date(r)<new Date(n))return{error:sr};if(r&&n&&new Date(n)>new Date(r))return{error:sr};if(o?.length){const t=n||e.startDate,i=r||e.endDate,a=!t||o.every(e=>new Date(e)>=new Date(t)),s=!i||o.every(t=>new Date(t)<=new Date(i));if(!a||!s)return{error:_e}}let s;(n&&e.startDate&&new Date(n)>new Date(e.startDate)||r&&e.endDate&&new Date(r)<new Date(e.endDate))&&(s=!0);const c=Ao(e.startDate,e.endDate);n&&(e.startDate=n),r&&(e.endDate=r);const u=Ao(e.startDate,e.endDate),d=c.filter(t=>!u.includes(t)),p=u.filter(t=>!c.includes(t));if(function({tournamentRecord:t,startDate:e,endDate:n}){for(const r of t.events??[])e&&r.startDate&&new Date(r.startDate)<new Date(e)&&(r.startDate=e),n&&r.startDate&&new Date(r.startDate)>new Date(n)&&(r.startDate=e??n),n&&r.endDate&&new Date(r.endDate)>new Date(n)&&(r.endDate=n),e&&r.endDate&&new Date(r.endDate)<new Date(e)&&(r.endDate=n??e)}({tournamentRecord:e,startDate:n,endDate:r}),function({tournamentRecord:t,startDate:e,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)}({tournamentRecord:e,startDate:n,endDate:r}),o){const t=function({tournamentRecord:t,activeDates:e}){const n=t.activeDates??[],r=new Set(e),i=n.filter(t=>!r.has(t));if(i.length){const e=Qg({tournamentRecord:t}).matchUps??[],n=new Set(i),r=e.filter(t=>t.schedule?.scheduledDate&&n.has(t.schedule.scheduledDate));if(r.length){const t=[...new Set(r.map(t=>t.schedule.scheduledDate))].sort();return{error:{...sr,message:`Cannot remove active dates with scheduled matchUps: ${t.join(", ")}`},info:`${r.length} matchUp(s) scheduled on dates being removed`}}}return void(t.activeDates=e)}({tournamentRecord:e,activeDates:o});if(t)return t}i&&(e.weekdays=i);const l=s&&function({tournamentRecord:t}){const e=Qg({tournamentRecord:t}).matchUps??[],n=t.startDate&&new Date(t.startDate),r=t.endDate&&new Date(t.endDate),i=[],o=[];for(const t of e){const{schedule:e,matchUpId:a}=t;if(e&&e.scheduledDate){const t=new Date(e.scheduledDate);(n&&t<n||r&&t>r)&&(o.push(a),i.includes(e.scheduledDate)||i.push(e.scheduledDate))}}if(i.length){if(!xF({scheduledDates:i,tournamentRecord:t}).clearedScheduleCount)return{error:ft}}return{unscheduledMatchUpIds:o}}({tournamentRecord:e})?.unscheduledMatchUpIds;return function({tournamentRecord:t}){if(!t)return{error:rt};const{startDate:e,endDate:n}=t,r=Ao(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=Fo(t.startTime),r=Fo(t.endTime);return e.startTime&&Fo(e.startTime)<n&&(t.startTime=e.startTime),e.endTime&&Fo(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}}),o=t.dateAvailability?.find(t=>!t.date);o&&i.unshift(o),t.dateAvailability=i}}({tournamentRecord:e}),di({payload:Ei({parentOrganisation:e.parentOrganisation,tournamentId:e.tournamentId,activeDates:o,startDate:n,weekdays:i,endDate:r}),topic:Al}),{...Y,unscheduledMatchUpIds:l,datesAdded:p,datesRemoved:d}}function PV({tournamentRecord:t,startDate:e}){return e?UV({tournamentRecord:t,startDate:e}):{error:_e}}function TV({tournamentRecord:t,endDate:e}){return e?UV({tournamentRecord:t,endDate:e}):{error:_e}}var wV={__proto__:null,addDrawDefinitionExtension:zu,addEventExtension:Yu,addEventTimeItem:oU,addExtension:$u,addMutationLock:cV,addNotes:rT,addOnlineResource:mV,addParticipantExtension:Ku,addParticipantTimeItem:rU,addTimeItem:nU,addTournamentExtension:Hu,addTournamentTimeItem:iU,analyzeDraws:xT,analyzeTournament:RA,cleanExpiredMutationLocks:gM,copyTournamentRecord:LB,createTournamentRecord:qF,generate:{__proto__:null,copyTournamentRecord:LB,createTournamentRecord:qF},getAggregateTeamResults:UM,getAllowedDrawTypes:aM,getAllowedMatchUpFormats:oM,getApplicableAwardProfileLevels:hM,getAppliedPolicies:xd,getCompetitionDateRange:yM,getCompetitionPenalties:SM,getEventRankingPoints:_M,getMutationLocks:bA,getPolicyDefinitions:_d,getRegistrationProfile:vM,getTournamentInfo:Pw,getTournamentPenalties:IM,getTournamentPersons:TM,getTournamentPoints:xM,getTournamentStructures:UU,getTournamentTimeItem:Em,hydrateTournamentRecord:uV,migrateTournamentRecord:iV,mutate:{__proto__:null,addDrawDefinitionExtension:zu,addEventExtension:Yu,addEventTimeItem:oU,addExtension:$u,addMutationLock:cV,addNotes:rT,addOnlineResource:mV,addParticipantExtension:Ku,addParticipantTimeItem:rU,addTimeItem:nU,addTournamentExtension:Hu,addTournamentTimeItem:iU,hydrateTournamentRecord:uV,migrateTournamentRecord:iV,removeDrawDefinitionExtension:Ju,removeEventExtension:Xu,removeExtension:qu,removeMutationLock:sV,removeNotes:iT,removeOnlineResource:pV,removeParticipantExtension:Zu,removeTournamentExtension:Qu,setRegistrationProfile:yV,setTournamentCategories:vV,setTournamentDates:UV,setTournamentEndDate:TV,setTournamentLocalTimeZone:IV,setTournamentName:hV,setTournamentNotes:gV,setTournamentStartDate:PV,setTournamentStatus:dV,setTournamentTier:SV},query:NA,removeDrawDefinitionExtension:Ju,removeEventExtension:Xu,removeExtension:qu,removeMutationLock:sV,removeNotes:iT,removeOnlineResource:pV,removeParticipantExtension:Zu,removeTournamentExtension:Qu,setRegistrationProfile:yV,setTournamentCategories:vV,setTournamentDates:UV,setTournamentEndDate:TV,setTournamentLocalTimeZone:IV,setTournamentName:hV,setTournamentNotes:gV,setTournamentStartDate:PV,setTournamentStatus:dV,setTournamentTier:SV,suggestFormatPlans:wA};const DV={MAINTENANCE:"MAINTENANCE",PRACTICE:"PRACTICE",RESERVED:"RESERVED",BLOCKED:"BLOCKED",CLOSED:"CLOSED",SCHEDULED:"SCHEDULED",SOFT_BLOCK:"SOFT_BLOCK",HARD_BLOCK:"HARD_BLOCK",LOCKED:"LOCKED",AVAILABLE:"AVAILABLE",UNSPECIFIED:"UNSPECIFIED"};function RV(t,e){return`${t.tournamentId}|${t.venueId}|${t.courtId}|${e}`}function bV(t){return`${t.tournamentId}|${t.venueId}|${t.courtId}`}function NV(t,e){return`${t}|${e}`}function MV(t,e,n){return`${t}|${e}|${n}`}function AV(t){return t.venueId||t.venueName||"unknown-venue"}function EV(t){return t.courtId||t.courtName||"unknown-court"}function CV(t,e){const n=t.start,r=t.end,i=e?.start,o=e?.end;if(r<=i||n>=o)return null;const a=n<i?i:n,s=r>o?o:r;return{...t,start:a,end:s}}function OV(t,e){return t?.start<e?.end&&e?.start<t?.end}function kV(t,e){return{start:t?.start>e?.start?t?.start:e?.start,end:t?.end<e?.end?t?.end:e?.end}}function FV(t,e){const n=new Date(t),r=(new Date(e).getTime()-n.getTime())/6e4;return Number.isNaN(r)?0:r}function xV(t,e,n){if(0===t.length||!n||0===n.length)return DV.AVAILABLE;const r=new Map(n.map((t,e)=>[t,e]));let i=DV.AVAILABLE,o=1/0;for(const n of t){const t=e.get(n);if(!t)continue;const a=r.get(t.type);void 0!==a&&a<o&&(o=a,i=t.type)}return i}function _V(t){const e=[];if(!Array.isArray(t))return e;for(const n of t)e.push({time:n.start,type:"START",blockId:n.id}),e.push({time:n.end,type:"END",blockId:n.id});return e}function LV(t){return Array.isArray(t)?t.slice().sort((t,e)=>{const n=t.time.localeCompare(e.time);return 0!==n?n:"END"===t.type&&"START"===e.type?-1:"START"===t.type&&"END"===e.type?1:0}):[]}function BV(t,e,n){if(!Array.isArray(t)||!e||!n)return[];const r=t.map(t=>CV(t,e)).filter(t=>null!==t);if(0===r.length)return[{start:e.start,end:e.end,status:DV.AVAILABLE,contributingBlocks:[]}];const i=new Map(r.map(t=>[t.id,t])),o=LV(_V(r)),a=new Set,s=[];let c=e.start;for(const t of o){const e=t.time;if(e>c){const t=Array.from(a),r=xV(t,i,n.typePrecedence);s.push({start:c,end:e,status:r,contributingBlocks:t})}"START"===t.type?a.add(t.blockId):a.delete(t.blockId),c=e}if(c<e.end){const t=Array.from(a),r=xV(t,i,n.typePrecedence);s.push({start:c,end:e.end,status:r,contributingBlocks:t})}return VV(s)}function VV(t){if(0===t.length)return t;const e=[];let n={...t[0]};for(let r=1;r<t.length;r++){const i=t[r],o=n.status===i.status,a=n.contributingBlocks.length===i.contributingBlocks.length&&n.contributingBlocks.every(t=>i.contributingBlocks.includes(t)),s=n.end===i.start;o&&a&&s?n.end=i.end:(e.push(n),n={...i})}return e.push(n),e}function GV(t){return Lo(t)}function jV(t,e){return{start:`${t}T${e?.dayStartTime}:00`,end:`${t}T${e?.dayEndTime}:00`}}function qV(t){for(let e=0;e<t.length;e++){const n=t[e];if(n.start>=n.end)return!1;if(e<t.length-1){const r=t[e+1];if(n.end>r.start)return!1;if(n.end!==r.start)return!1}}return!0}function WV(t,e){const n=new Set;if(!Array.isArray(e))return{day:t,points:[]};for(const t of e)for(const e of t.rails)for(const t of e.segments)n.add(t.start),n.add(t.end);const r=Array.from(n).sort(),i=r.map(t=>({time:t,courtsAvailable:0,courtsSoftBlocked:0,courtsHardBlocked:0}));for(const t of e)for(const e of t.rails)for(let t=0;t<r.length;t++){const n=r[t],o=$V(e.segments,n);if(o){HV(o,i[t])}}return{day:t,points:i}}function $V(t,e){for(const n of t)if(e>=n.start&&e<n.end)return n;return null}function HV(t,e){switch(t.status){case DV.AVAILABLE:e.courtsAvailable++;break;case DV.RESERVED:case DV.SOFT_BLOCK:case DV.BLOCKED:case DV.PRACTICE:case DV.MAINTENANCE:case DV.CLOSED:e.courtsSoftBlocked++;break;case DV.SCHEDULED:case DV.HARD_BLOCK:case DV.LOCKED:e.courtsHardBlocked++;case DV.UNSPECIFIED:}}function zV(t){if(!t.points||0===t.points.length)return{peakAvailable:0,peakTime:"",minAvailable:0,minTime:"",avgAvailable:0,totalCourtHours:0,utilizationPercent:0,peakUnavailable:0,peakUnavailableTime:"",totalCourts:0,totalAvailableHours:0,totalUnavailableHours:0,availablePercent:0,avgBlockedHoursPerCourt:0};let e=0,n=t.points[0].time,r=1/0,i=t.points[0].time,o=0,a=t.points[0].time,s=0,c=0,u=0;for(let d=0;d<t.points.length-1;d++){const p=t.points[d],l=t.points[d+1],m=(new Date(l.time).getTime()-new Date(p.time).getTime())/36e5,f=p.courtsAvailable+p.courtsSoftBlocked+p.courtsHardBlocked;u=Math.max(u,f);const h=p.courtsSoftBlocked+p.courtsHardBlocked;p.courtsAvailable>e&&(e=p.courtsAvailable,n=p.time),p.courtsAvailable<r&&(r=p.courtsAvailable,i=p.time),h>o&&(o=h,a=p.time),s+=p.courtsAvailable*m,c+=h*m}const d=u*((new Date(t.points.at(-1).time).getTime()-new Date(t.points[0].time).getTime())/36e5),p=d>0?s/d*100:0,l=d>0?c/d*100:0,m=u>0?c/u:0;return{peakAvailable:e,peakTime:n,minAvailable:r===1/0?0:r,minTime:i,avgAvailable:t.points.length>1?t.points.slice(0,-1).reduce((t,e)=>t+e.courtsAvailable,0)/(t.points.length-1):0,totalCourtHours:d,utilizationPercent:l,peakUnavailable:o,peakUnavailableTime:a,totalCourts:u,totalAvailableHours:s,totalUnavailableHours:c,availablePercent:p,avgBlockedHoursPerCourt:m}}function YV(t,e){const n=t.points?.filter(t=>t.time>=e.start&&t.time<=e.end);return{...t,points:n}}function KV(t,e){if(!t.points||0===t.points.length)return t;const n=[],r=new Date(t.points[0].time),i=new Date(t.points.at(-1).time);let o=new Date(r);for(;o<=i;){const r=o.toISOString(),i=QV(t.points,r);i&&n.push(i),o=new Date(o.getTime()+60*e*1e3)}return{...t,points:n}}function QV(t,e){for(let n=t.length-1;n>=0;n--)if(t[n].time<=e)return{time:e,courtsAvailable:t[n].courtsAvailable,courtsSoftBlocked:t[n].courtsSoftBlocked,courtsHardBlocked:t[n].courtsHardBlocked};return null}function JV(t,e){const n=[],r=new Set;t.points?.forEach(t=>r.add(t.time)),e?.points?.forEach(t=>r.add(t.time));const i=Array.from(r).sort();for(const r of i){const i=t.points?.find(t=>t.time===r)||{courtsAvailable:0,courtsSoftBlocked:0,courtsHardBlocked:0},o=e.points?.find(t=>t.time===r)||{courtsAvailable:0,courtsSoftBlocked:0,courtsHardBlocked:0};n.push({time:r,availableDelta:o.courtsAvailable-i.courtsAvailable,softBlockedDelta:o.courtsSoftBlocked-i.courtsSoftBlocked,hardBlockedDelta:o.courtsHardBlocked-i.courtsHardBlocked})}return n}function XV(t){return new Date(t?.endsWith("Z")?t:t+"Z").getTime()}function ZV(t,e){return XV(t.start)<XV(e.end)&&XV(t.end)>XV(e.start)}function tG(t,e){return XV(e?.start)<=t&&t<XV(e?.end)}function eG(t,e){return Array.isArray(e)?e.filter(e=>tG(t,e)):[]}function nG(t,e,n){const r=e>=t?"forward":"backward",i=Math.min(t,e),o=Math.max(t,e);return"forward"===r?function(t,e,n){let r,i=e,o=!1;for(const a of n){const n=XV(a.start);n>t&&n<e&&n<i&&(i=n,o=!0,r=a);const s=XV(a.end);n<e&&s>t&&n<i&&n>t&&(i=n,o=!0,r=a)}return{start:t,end:i,clamped:o,clampedBy:r,direction:"forward"}}(t,o,n):function(t,e,n){let r,i=e,o=!1;if(Array.isArray(n))for(const a of n){const n=XV(a.end);n<t&&n>e&&n>i&&(i=n,o=!0,r=a);XV(a.start)<t&&n>e&&n>i&&n<t&&(i=n,o=!0,r=a)}return{start:i,end:t,clamped:o,clampedBy:r,direction:"backward"}}(t,i,n)}function rG(t){Array.isArray(t)&&t.sort((t,e)=>XV(t.start)-XV(e.start))}const iG={id:"COURT_OVERLAP",description:"Prevent double-booking courts or overriding hard blocks",evaluate:(t,e)=>{const n=[];for(const r of e){if("REMOVE_BLOCK"===r.kind)continue;const e=r.block,i=Lo(e.start),o=`${e.court.tournamentId}|${e.court.venueId}|${e.court.courtId}|${i}`,a=t.blocksByCourtDay.get(o)??[];for(const r of a){if(r===e.id)continue;const i=t.blocksById.get(r);if(i&&OV(e,i)){const t=i.type===DV.HARD_BLOCK||i.type===DV.LOCKED||e.type===DV.HARD_BLOCK||e.type===DV.LOCKED?"ERROR":"WARN",r=e.start>i.start?e.start:i.start,o=e.end<i.end?e.end:i.end;n.push({code:"COURT_OVERLAP",message:`Block overlaps existing ${i.type.toLowerCase()} (${i.reason||"no reason"}) on court ${e.court.courtId}`,severity:t,timeRange:{start:r,end:o},courts:[e.court]})}}}return n}},oG={id:"MATCH_WINDOW",description:"Ensure availability windows are large enough for typical matches",evaluate:(t,e)=>{const n=[],r=new Set;for(const t of e){const e=t.block,n=Lo(e.start),i=`${e.court.tournamentId}|${e.court.venueId}|${e.court.courtId}|${n}`;r.add(i)}for(const e of r){const r=(t.blocksByCourtDay.get(e)??[]).map(e=>t.blocksById.get(e)).filter(Boolean).slice().sort((t,e)=>t.start.localeCompare(e.start));let i=null;for(const t of r)if(t.type!==DV.AVAILABLE&&t.type!==DV.SOFT_BLOCK&&t.type!==DV.RESERVED){if(i){const e=FV(i,t.start);e>0&&e<60&&n.push({code:"MATCH_WINDOW_TOO_SMALL",message:`Availability window (${e} minutes) is smaller than typical match duration (60 minutes)`,severity:"WARN",timeRange:{start:i,end:t.start},courts:[t.court]})}i=t.end}}return n}},aG={id:"ADJACENT_BLOCK",description:"Warn about blocks with no transition time",evaluate:(t,e)=>{const n=[];for(const r of e){if("REMOVE_BLOCK"===r.kind)continue;const e=r.block,i=Lo(e.start),o=`${e.court.tournamentId}|${e.court.venueId}|${e.court.courtId}|${i}`,a=t.blocksByCourtDay.get(o)??[];for(const r of a){if(r===e.id)continue;const i=t.blocksById.get(r);if(!i)continue;(i.end===e.start||e.end===i.start)&&i.type!==e.type&&n.push({code:"NO_TRANSITION_TIME",message:`${e.type} immediately follows ${i.type} with no transition time (recommended: 15 minutes)`,severity:"INFO",timeRange:{start:i.end,end:e.start},courts:[e.court]})}}return n}},sG={id:"LIGHTING",description:"Prevent scheduling on unlit courts after sunset",evaluate:(t,e)=>{const n=[],r="19:00";for(const t of e){if("REMOVE_BLOCK"===t.kind)continue;const e=t.block;e.end.slice(11,16)>r&&(e.type===DV.AVAILABLE||e.type===DV.RESERVED)&&n.push({code:"AFTER_SUNSET",message:`Court scheduled after sunset (${r}). Verify court has adequate lighting.`,severity:"WARN",timeRange:{start:`${e.start.slice(0,11)}${r}:00`,end:e.end},courts:[e.court]})}return n}},cG={id:"BLOCK_DURATION",description:"Validate block durations are reasonable",evaluate:(t,e)=>{const n=[];for(const t of e){if("REMOVE_BLOCK"===t.kind)continue;const e=t.block,r=FV(e.start,e.end);r<15?n.push({code:"BLOCK_TOO_SHORT",message:`Block duration (${r} minutes) is unusually short. Minimum recommended: 15 minutes.`,severity:"WARN",timeRange:e,courts:[e.court]}):r>720&&n.push({code:"BLOCK_TOO_LONG",message:`Block duration (${r/60} hours) is unusually long. Maximum recommended: 12 hours.`,severity:"WARN",timeRange:e,courts:[e.court]})}return n}},uG={id:"DAY_BOUNDARY",description:"Ensure blocks do not span multiple days",evaluate:(t,e)=>{const n=[];for(const t of e){if("REMOVE_BLOCK"===t.kind)continue;const e=t.block,r=Lo(e.start),i=Lo(e.end);r!==i&&n.push({code:"SPANS_MULTIPLE_DAYS",message:`Block spans from ${r} to ${i}. Blocks should be contained within a single day.`,severity:"ERROR",timeRange:e,courts:[e.court]})}return n}},dG={id:"MAINTENANCE_WINDOW",description:"Validate maintenance scheduling practices",evaluate:(t,e)=>{const n=[],r="09:00",i="17:00";for(const t of e){if("REMOVE_BLOCK"===t.kind)continue;const e=t.block;if(e.type===DV.MAINTENANCE){const t=e.start.slice(11,16),o=e.end.slice(11,16),a=FV(e.start,e.end);(t>=r&&t<i||o>r&&o<=i)&&n.push({code:"MAINTENANCE_DURING_PEAK",message:`Maintenance scheduled during peak hours (${r}-${i}). Consider scheduling during off-peak times.`,severity:"INFO",timeRange:e,courts:[e.court]}),a<30&&n.push({code:"MAINTENANCE_TOO_SHORT",message:`Maintenance duration (${a} minutes) may be insufficient. Recommended minimum: 30 minutes.`,severity:"INFO",timeRange:e,courts:[e.court]})}}return n}},pG=[iG,uG,cG,oG,aG,sG,dG];class lG{constructor(){this.evaluators=new Map}register(t){this.evaluators.set(t.id,t)}unregister(t){this.evaluators.delete(t)}get(t){return this.evaluators.get(t)}getAll(){return Array.from(this.evaluators.values())}clear(){this.evaluators.clear()}}const mG=t=>({id:"FOLLOW_BY",description:"Player rest and follow-by conflicts using Competition Factory",evaluate:(t,e)=>[]});function fG(t){return Array.isArray(t)?{errors:t?.filter(t=>"ERROR"===t.severity),warnings:t.filter(t=>"WARN"===t.severity),info:t.filter(t=>"INFO"===t.severity)}:{errors:[],warnings:[],info:[]}}function hG(t){return Array.isArray(t)?t.some(t=>"ERROR"===t.severity)?"ERROR":t.some(t=>"WARN"===t.severity)?"WARN":t.some(t=>"INFO"===t.severity)?"INFO":null:null}function gG(t){return Array.isArray(t)?t.map(t=>{const e=t.courts.map(t=>t.courtId).join(", "),n=`${t.timeRange.start.slice(11,16)}-${t.timeRange.end.slice(11,16)}`;return`[${t.severity}] ${t.code}: ${t.message} (${e} @ ${n})`}):[]}function IG(t){if("string"!=typeof t)return 0;const[e,n]=t.split(":").map(Number);return 60*e+n}function SG(t){const e=Math.max(0,Math.min(1439,Math.round(t))),n=Math.floor(e/60),r=e%60;return`${String(n).padStart(2,"0")}:${String(r).padStart(2,"0")}`}function yG(t,e,n="round"){if(e<=0)return t;switch(n){case"floor":return Math.floor(t/e)*e;case"ceil":return Math.ceil(t/e)*e;case"round":return Math.round(t/e)*e}}function vG(t,e,n="round"){if(!t||"string"!=typeof t)return t;return`${t.slice(0,10)}T${SG(yG(IG(t.slice(11,16)),e,n))}:00`}function*UG(t,e,n){if(n<=0)return;const r=IG(t),i=IG(e);for(let t=r;t<i;t+=n)yield SG(t)}function PG(t){const e=[t.day,t.venueId,t.eventId];return t.drawId&&e.push(t.drawId),e.push(`R${t.roundNumber}`),e.join("|")}function TG(t){const[e,n]=t.split(":").map(Number);return 60*e+n}const wG=["PRECHECK","INTEGRITY","ORDERING","CAPACITY"],DG={PRECHECK:function(t,e){const n=[],r=new Set(t.getTournamentDays()),i=t.listCourtMeta(),o=new Set(i.map(t=>t.ref.venueId));for(const t of e){r.has(t.day)||n.push({ruleId:"PRECHECK_INVALID_DAY",phase:"PRECHECK",severity:"ERROR",message:`Day '${t.day}' is not within the tournament date range`,context:{day:t.day}});for(const e of t.items)o.has(e.venueId)||n.push({ruleId:"PRECHECK_INVALID_VENUE",phase:"PRECHECK",severity:"ERROR",message:`Venue '${e.venueId}' does not exist in the tournament record`,context:{day:t.day,venueId:e.venueId,planItemId:e.planItemId}}),e.notBeforeTime&&!/^\d{2}:\d{2}$/.test(e.notBeforeTime)&&n.push({ruleId:"PRECHECK_INVALID_TIME_FORMAT",phase:"PRECHECK",severity:"ERROR",message:`notBeforeTime '${e.notBeforeTime}' is not valid HH:MM format`,context:{day:t.day,planItemId:e.planItemId}}),e.roundNumber<1&&n.push({ruleId:"PRECHECK_INVALID_ROUND",phase:"PRECHECK",severity:"ERROR",message:`roundNumber must be >= 1, got ${e.roundNumber}`,context:{day:t.day,planItemId:e.planItemId}})}return n},INTEGRITY:function(t,e){const n=[],r=new Set;for(const t of e)for(const e of t.items)r.has(e.planItemId)&&n.push({ruleId:"INTEGRITY_DUPLICATE_PLAN_ITEM",phase:"INTEGRITY",severity:"ERROR",message:`Duplicate plan item '${e.planItemId}'`,context:{day:t.day,planItemId:e.planItemId}}),r.add(e.planItemId);return n},ORDERING:function(t,e){const n=[],r=new Map;for(const t of e)for(const e of t.items){const n=`${e.eventId}|${e.drawId||""}`,i=r.get(n)??[];i.push({day:t.day,roundNumber:e.roundNumber,planItemId:e.planItemId}),r.set(n,i)}for(const[t,e]of r.entries()){if(e.length<2)continue;const r=[...e].sort((t,e)=>t.roundNumber-e.roundNumber);for(let e=1;e<r.length;e++){const i=r[e-1],o=r[e];o.day<i.day&&n.push({ruleId:"ORDERING_ROUND_DAY_SEQUENCE",phase:"ORDERING",severity:"WARN",message:`Round ${o.roundNumber} is scheduled on ${o.day} which is before round ${i.roundNumber} on ${i.day} (event: ${t.split("|")[0]})`,context:{day:o.day,planItemId:o.planItemId},fixAction:{type:"MOVE_PLAN_ITEM",description:`Move round ${o.roundNumber} to ${i.day} or later`,payload:{planItemId:o.planItemId,suggestedDay:i.day}}})}}return n},CAPACITY:function(t,e){const n=[];for(const r of e){let e=0;const i=r.items.filter(t=>t.estimatedDurationMinutes);for(const t of i)e+=t.estimatedDurationMinutes;if(0===e)continue;const o=t.getVisibleTimeRange(r.day),a=TG(o.startTime),s=TG(o.endTime)-a,c=t.listCourtMeta(),u=new Set(r.items.map(t=>t.venueId)),d=(1===u.size?c.filter(t=>t.ref.venueId===[...u][0]):c).length*s;e>d?n.push({ruleId:"CAPACITY_DEMAND_EXCEEDS_SUPPLY",phase:"CAPACITY",severity:"WARN",message:`Estimated demand (${Math.round(e/60)}h) exceeds available court-hours (${Math.round(d/60)}h) on ${r.day}`,context:{day:r.day}}):e>.9*d&&n.push({ruleId:"CAPACITY_NEAR_LIMIT",phase:"CAPACITY",severity:"INFO",message:`Demand is at ${Math.round(e/d*100)}% of capacity on ${r.day}`,context:{day:r.day}})}return n}};function RG(t){const{engine:e,day:n,phases:r}=t;let i;if(n){const t=e.getDayPlan(n);i=t?[t]:[]}else i=e?.getAllPlans();const o=r?wG.filter(t=>r.includes(t)):wG,a=[];for(const t of o){const n=(0,DG[t])(e,i);if(a.push(...n),"PRECHECK"===t&&n.some(t=>"ERROR"===t.severity))break}const s=new Map;for(const t of a){const e=t.context?.planItemId||"__global__",n=s.get(e)??[];n.push(t),s.set(e,n)}return{results:a,issueIndex:s}}const bG={courtToCourtId:t=>t.courtId,isSchedulableStatus:t=>t===DV.AVAILABLE||t===DV.SOFT_BLOCK||t===DV.RESERVED,aggregateByVenue:!1};function NG(t,e={}){const n={...bG,...e},r=[];for(const e of t){const{day:t,venueId:i,rails:o}=e;for(const e of o){const{court:o,segments:a}=e,s=n.courtToCourtId(o),c=MG(a,n);for(const e of c)r.push({date:t,startTime:AG(e.start),endTime:AG(e.end),venueId:i,courtIds:[s]})}}return n.aggregateByVenue?function(t){const e=new Map;for(const n of t){const t=`${n.venueId}|${n.date}|${n.startTime}|${n.endTime}`;if(e.has(t)){const r=e.get(t);n.courtIds&&(r.courtIds=[...r.courtIds??[],...n.courtIds])}else e.set(t,{...n})}return Array.from(e.values())}(r):r}function MG(t,e){const n=[];let r=null,i=null;for(const o of t){e.isSchedulableStatus(o.status)?(r||(r=o.start),i=o.end):(r&&i&&n.push({start:r,end:i}),r=null,i=null)}return r&&i&&n.push({start:r,end:i}),n}function AG(t){return t.slice(11,16)}function EG(t){const{tournamentRecord:e,timelines:n,config:r={},engine:i}=t,o=NG(n,r),a=structuredClone(e),s=new Map;for(const t of o){const e=s.get(t.venueId)??[];e.push(t),s.set(t.venueId,e)}if(a.venues&&Array.isArray(a.venues)){const t=i?.getConfig(),e=t?.tournamentId;for(const t of a.venues){const n=AV(t),r=s.get(n);if(r&&(t.dateAvailability=r),i&&e){const r=i.getVenueAvailability(e,n);r&&(t.defaultStartTime=r.startTime,t.defaultEndTime=r.endTime)}}}return a}function CG(t){const e=[];for(const n of t)n.scheduleDate&&n.venueIds.length&&e.push({scheduleDate:n.scheduleDate,venueIds:n.venueIds,rounds:n.rounds??[]});return e}function OG(t){const{venue:e,tournamentId:n,blockType:r=DV.AVAILABLE}=t,i=[];if(!e.dateAvailability)return i;const o=AV(e);for(const t of e.dateAvailability){const{date:a,startTime:s,endTime:c,courtIds:u}=t;if(u&&u.length>0)for(const t of u)i.push({court:{tournamentId:n,venueId:o,courtId:t},start:`${a}T${s}:00`,end:`${a}T${c}:00`,type:r});else if(e.courts&&e.courts.length>0)for(const t of e.courts){const e=EV(t);i.push({court:{tournamentId:n,venueId:o,courtId:e},start:`${a}T${s}:00`,end:`${a}T${c}:00`,type:r})}}return i}function kG(t){const e=[];if(!Array.isArray(t))return e.push("Profile must be an array"),{valid:!1,errors:e};for(let n=0;n<t.length;n++){const r=t[n];if(r.scheduleDate?/^\d{4}-\d{2}-\d{2}$/.test(r.scheduleDate)||e.push(`Item ${n}: invalid scheduleDate format (expected YYYY-MM-DD)`):e.push(`Item ${n}: missing scheduleDate`),r.venueIds&&Array.isArray(r.venueIds)&&0!==r.venueIds.length||e.push(`Item ${n}: missing or empty venueIds array`),r.rounds)if(Array.isArray(r.rounds))for(let t=0;t<r.rounds.length;t++){r.rounds[t].eventId||e.push(`Item ${n}, round ${t}: missing eventId`)}else e.push(`Item ${n}: rounds must be an array`)}return{valid:0===e.length,errors:e}}function FG(t){const e=[];if(!Array.isArray(t))return e.push("Entries must be an array"),{valid:!1,errors:e};for(let n=0;n<t.length;n++){const r=t[n];r.date&&/^\d{4}-\d{2}-\d{2}$/.test(r.date)||e.push(`Entry ${n}: invalid or missing date`),r.startTime&&/^\d{2}:\d{2}$/.test(r.startTime)||e.push(`Entry ${n}: invalid or missing startTime (expected HH:MM)`),r.endTime&&/^\d{2}:\d{2}$/.test(r.endTime)||e.push(`Entry ${n}: invalid or missing endTime (expected HH:MM)`),r.startTime&&r.endTime&&r.startTime>=r.endTime&&e.push(`Entry ${n}: startTime must be before endTime`),r.venueId||e.push(`Entry ${n}: missing venueId`)}return{valid:0===e.length,errors:e}}function xG(t){if(0===t.length)return t;const e=new Map;for(const n of t){const t=`${n.venueId}|${n.date}`,r=e.get(t)??[];r.push(n),e.set(t,r)}const n=[];for(const t of e.values()){t.sort((t,e)=>t.startTime.localeCompare(e.startTime));let e={...t[0]};for(let r=1;r<t.length;r++){const i=t[r];i.startTime<=e.endTime?(e.endTime=i.endTime>e.endTime?i.endTime:e.endTime,e.courtIds&&i.courtIds&&(e.courtIds=[...new Set([...e.courtIds,...i.courtIds])])):(n.push(e),e={...i})}n.push(e)}return n}function _G(t){let e=0;for(const n of t){const t=LG(n.startTime);e+=(LG(n.endTime)-t)/60*(n.courtIds?.length||1)}return e}function LG(t){const[e,n]=t.split(":").map(Number);return 60*e+n}var BG={__proto__:null,BLOCK_TYPES:DV,EvaluatorRegistry:lG,adjacentBlockEvaluator:aG,applyAvailabilityToTournamentRecord:EG,blockDurationEvaluator:cG,buildDayRange:jV,buildEdges:_V,buildSchedulingProfileFromUISelections:CG,calculateCapacityStats:zV,calculateCourtHours:_G,clampDragToCollisions:nG,clampToDayRange:CV,compareCapacityCurves:JV,computePlanItemId:PG,courtDayKey:RV,courtKey:bV,courtOverlapEvaluator:iG,createFollowByEvaluator:mG,dayBoundaryEvaluator:uG,defaultEvaluators:pG,deriveRailSegments:BV,diffMinutes:FV,extractDay:GV,filterCapacityCurve:YV,findBlocksContainingTime:eG,formatConflicts:gG,generateCapacityCurve:WV,getHighestSeverity:hG,groupConflictsBySeverity:fG,hhmmToMinutes:IG,intervalsOverlap:ZV,iterateDayTicks:UG,lightingEvaluator:sG,maintenanceWindowEvaluator:dG,matchWindowEvaluator:oG,mergeAdjacentSegments:VV,mergeOverlappingAvailability:xG,minutesToHhmm:SG,overlappingRange:kV,railsToDateAvailability:NG,rangesOverlap:OV,resolveCourtId:EV,resolveStatus:xV,resolveVenueId:AV,runValidationPipeline:RG,sampleCapacityCurve:KV,snapIsoToGranularity:vG,snapToGranularity:yG,sortBlocksByStart:rG,sortEdges:LV,timeInsideBlock:tG,todsAvailabilityToBlocks:OG,validateDateAvailability:FG,validateSchedulingProfileFormat:kG,validateSegments:qV,venueDayKey:MV,venueKey:NV};const VG="ACTIVE",GG="EXPIRED",jG="SUSPENDED",qG="REVOKED",WG="PENDING_RENEWAL",$G="DRAFT",HG="SUBMITTED",zG="REVIEWED",YG="APPROVED",KG="REJECTED",QG="PROPOSED",JG="CONFIRMED",XG="DECLINED",ZG="CANCELLED",tj="COMPLETED",ej={ACTIVE:[GG,jG,qG,WG],EXPIRED:[VG,WG],SUSPENDED:[VG,qG],REVOKED:[],PENDING_RENEWAL:[VG,GG]},nj={DRAFT:[HG],SUBMITTED:[zG,KG],REVIEWED:[YG,KG],APPROVED:[],REJECTED:[$G]},rj={PROPOSED:[JG,XG,ZG],CONFIRMED:[ZG,tj],DECLINED:[],CANCELLED:[],COMPLETED:[]},ij=[$G,KG],oj=[{value:1,label:"Unsatisfactory"},{value:2,label:"Below Average"},{value:3,label:"Average"},{value:4,label:"Good"},{value:5,label:"Excellent"}],aj={message:"Missing officialRecord",code:"ERR_MISSING_OFFICIAL_RECORD"},sj={message:"OfficialRecord not found",code:"ERR_NOT_FOUND_OFFICIAL_RECORD"},cj={message:"OfficialRecord already exists",code:"ERR_EXISTING_OFFICIAL_RECORD"},uj={message:"Certification not found",code:"ERR_NOT_FOUND_CERTIFICATION"},dj={message:"Certification has expired",code:"ERR_CERTIFICATION_EXPIRED"},pj={message:"Evaluation not found",code:"ERR_NOT_FOUND_EVALUATION"},lj={message:"Evaluation is not editable in current status",code:"ERR_EVALUATION_NOT_EDITABLE"},mj={message:"Assignment not found",code:"ERR_NOT_FOUND_ASSIGNMENT"},fj={message:"Evaluation scores do not satisfy policy requirements",code:"ERR_INVALID_EVALUATION_SCORES"},hj={message:"Invalid status transition",code:"ERR_INVALID_OFFICIATING_STATUS_TRANSITION"},gj={message:"Suspension not found",code:"ERR_NOT_FOUND_SUSPENSION"},Ij={message:"Missing evaluation policy",code:"ERR_MISSING_EVALUATION_POLICY"},Sj={CERT_ACTIVE:VG,CERT_EXPIRED:GG,CERT_SUSPENDED:jG,CERT_REVOKED:qG,CERT_PENDING_RENEWAL:WG,EVAL_DRAFT:$G,EVAL_SUBMITTED:HG,EVAL_REVIEWED:zG,EVAL_APPROVED:YG,EVAL_REJECTED:KG,ASSIGN_PROPOSED:QG,ASSIGN_CONFIRMED:JG,ASSIGN_DECLINED:XG,ASSIGN_CANCELLED:ZG,ASSIGN_COMPLETED:tj,VALID_CERTIFICATION_TRANSITIONS:ej,VALID_EVALUATION_TRANSITIONS:nj,VALID_ASSIGNMENT_TRANSITIONS:rj,CERTIFICATION_TERMINAL:[qG],EVALUATION_TERMINAL:[YG],ASSIGNMENT_TERMINAL:[XG,ZG,tj],EVALUATION_EDITABLE:ij,EVALUATION_SCALE_OPTIONS:oj};function yj({officialRecord:t,certificationId:e,toStatus:n,transitionedBy:r,reason:i}){if(!t)return{error:aj};if(!e)return{error:sr,context:{message:"Missing certificationId"}};if(!n)return{error:sr,context:{message:"Missing toStatus"}};const o=t.certifications.find(t=>t.certificationId===e);if(!o)return{error:uj,context:{certificationId:e}};const a=ej[o.status];if(!a?.includes(n))return{error:hj,context:{fromStatus:o.status,toStatus:n,validTargets:a}};const s=(new Date).toISOString();return o.statusHistory??=[],o.statusHistory.push({fromStatus:o.status,toStatus:n,transitionedAt:s,transitionedBy:r,reason:i}),o.status=n,t.updatedAt=s,{...Y,certification:o}}function vj({officialRecord:t,evaluationId:e,toStatus:n,transitionedBy:r,reason:i}){if(!t)return{error:aj};if(!e)return{error:sr,context:{message:"Missing evaluationId"}};if(!n)return{error:sr,context:{message:"Missing toStatus"}};const o=t.evaluations.find(t=>t.evaluationId===e);if(!o)return{error:pj,context:{evaluationId:e}};const a=nj[o.status];if(!a?.includes(n))return{error:hj,context:{fromStatus:o.status,toStatus:n,validTargets:a}};if(n===HG&&o.policyName){const e=t.evaluationPolicies.find(t=>t.policyName===o.policyName);if(e){const t=e.sections.flatMap(t=>t.criteria.filter(t=>t.required)),n=new Set(o.scores.map(t=>t.criterionId)),r=t.filter(t=>!n.has(t.criterionId));if(r.length>0)return{error:fj,context:{missingCriteria:r.map(t=>t.criterionId)}}}}const s=(new Date).toISOString();return o.statusHistory??=[],o.statusHistory.push({fromStatus:o.status,toStatus:n,transitionedAt:s,transitionedBy:r,reason:i}),o.status=n,t.updatedAt=s,{...Y,evaluation:o}}function Uj({officialRecord:t,requirementId:e,certificationFamily:n,certificationLevel:r,organisationId:i,description:o,requirements:a,prerequisiteLevels:s,minimumAssignments:c,minimumEvaluationScore:u,validityPeriodMonths:d,extensions:p}){if(!t)return{error:aj};if(!n)return{error:sr,context:{message:"Missing certificationFamily"}};if(!r)return{error:sr,context:{message:"Missing certificationLevel"}};if(!i)return{error:sr,context:{message:"Missing organisationId"}};if(!Array.isArray(a)||0===a.length)return{error:sr,context:{message:"Requirements must be a non-empty array"}};const l={requirementId:e||pa(),certificationFamily:n,certificationLevel:r,organisationId:i,description:o,requirements:a.map(t=>({...t,itemId:t.itemId||pa()})),prerequisiteLevels:s,minimumAssignments:c,minimumEvaluationScore:u,validityPeriodMonths:d,extensions:p??[]};return t.certificationRequirements.push(l),t.updatedAt=(new Date).toISOString(),{...Y,certificationRequirement:l}}function Pj({officialRecord:t,assignmentId:e,toStatus:n,transitionedBy:r,reason:i}){if(!t)return{error:aj};if(!e)return{error:sr,context:{message:"Missing assignmentId"}};if(!n)return{error:sr,context:{message:"Missing toStatus"}};const o=t.assignments.find(t=>t.assignmentId===e);if(!o)return{error:mj,context:{assignmentId:e}};const a=rj[o.status];if(!a?.includes(n))return{error:hj,context:{fromStatus:o.status,toStatus:n,validTargets:a}};const s=(new Date).toISOString();return o.statusHistory??=[],o.statusHistory.push({fromStatus:o.status,toStatus:n,transitionedAt:s,transitionedBy:r,reason:i}),o.status=n,t.updatedAt=s,{...Y,assignment:o}}function Tj({officialRecord:t,assignmentId:e}){if(!t)return{error:aj};if(!e)return{error:sr,context:{message:"Missing assignmentId"}};const n=t.assignments.findIndex(t=>t.assignmentId===e);return-1===n?{error:mj,context:{assignmentId:e}}:(t.assignments.splice(n,1),t.updatedAt=(new Date).toISOString(),{...Y})}function wj({officialRecord:t,evaluationPolicy:e}){return t?e?e.policyName?Array.isArray(e.sections)&&0!==e.sections.length?(t.evaluationPolicies.push(e),t.updatedAt=(new Date).toISOString(),{...Y,evaluationPolicy:e}):{error:sr,context:{message:"Policy must include at least one section"}}:{error:sr,context:{message:"Missing policyName"}}:{error:sr,context:{message:"Missing evaluationPolicy"}}:{error:aj}}function Dj({officialRecordId:t,personId:e,organisationId:n,extensions:r}){if(!e)return{error:sr,context:{message:"Missing personId"}};const i=(new Date).toISOString(),o={officialRecordId:t||pa(),personId:e,organisationId:n,certifications:[],evaluations:[],assignments:[],suspensions:[],certificationRequirements:[],evaluationPolicies:[],createdAt:i,updatedAt:i,extensions:r??[]};return{...Y,officialRecord:o}}function Rj({officialRecord:t,certificationId:e,updates:n}){if(!t)return{error:aj};if(!e)return{error:sr,context:{message:"Missing certificationId"}};const r=t.certifications.find(t=>t.certificationId===e);return r?(void 0!==n.certificationLevel&&(r.certificationLevel=n.certificationLevel),void 0!==n.validFrom&&(r.validFrom=n.validFrom),void 0!==n.validUntil&&(r.validUntil=n.validUntil),void 0!==n.documentReferences&&(r.documentReferences=n.documentReferences),void 0!==n.notes&&(r.notes=n.notes),void 0!==n.extensions&&(r.extensions=n.extensions),t.updatedAt=(new Date).toISOString(),{...Y,certification:r}):{error:uj,context:{certificationId:e}}}function bj({officialRecord:t,certificationId:e}){if(!t)return{error:aj};if(!e)return{error:sr,context:{message:"Missing certificationId"}};const n=t.certifications.findIndex(t=>t.certificationId===e);return-1===n?{error:uj,context:{certificationId:e}}:(t.certifications.splice(n,1),t.updatedAt=(new Date).toISOString(),{...Y})}function Nj({officialRecord:t,evaluationId:e,updates:n}){if(!t)return{error:aj};if(!e)return{error:sr,context:{message:"Missing evaluationId"}};const r=t.evaluations.find(t=>t.evaluationId===e);return r?ij.includes(r.status)?(void 0!==n.overallRating&&(r.overallRating=n.overallRating),void 0!==n.scores&&(r.scores=n.scores),void 0!==n.comments&&(r.comments=n.comments),void 0!==n.documentReference&&(r.documentReference=n.documentReference),void 0!==n.tournamentId&&(r.tournamentId=n.tournamentId),void 0!==n.tournamentName&&(r.tournamentName=n.tournamentName),void 0!==n.matchUpId&&(r.matchUpId=n.matchUpId),void 0!==n.policyName&&(r.policyName=n.policyName),void 0!==n.extensions&&(r.extensions=n.extensions),t.updatedAt=(new Date).toISOString(),{...Y,evaluation:r}):{error:lj,context:{status:r.status}}:{error:pj,context:{evaluationId:e}}}function Mj({officialRecord:t,evaluationId:e}){if(!t)return{error:aj};if(!e)return{error:sr,context:{message:"Missing evaluationId"}};const n=t.evaluations.findIndex(t=>t.evaluationId===e);return-1===n?{error:pj,context:{evaluationId:e}}:(t.evaluations.splice(n,1),t.updatedAt=(new Date).toISOString(),{...Y})}function Aj({officialRecord:t,suspensionId:e}){if(!t)return{error:aj};if(!e)return{error:sr,context:{message:"Missing suspensionId"}};const n=t.suspensions.findIndex(t=>t.suspensionId===e);return-1===n?{error:gj,context:{suspensionId:e}}:(t.suspensions.splice(n,1),t.updatedAt=(new Date).toISOString(),{...Y})}function Ej({officialRecord:t,certificationId:e,organisationId:n,certificationFamily:r,certificationLevel:i,status:o,validFrom:a,validUntil:s,documentReferences:c,notes:u,extensions:d}){if(!t)return{error:aj};if(!n)return{error:sr,context:{message:"Missing organisationId"}};if(!r)return{error:sr,context:{message:"Missing certificationFamily"}};const p=(new Date).toISOString(),l={certificationId:e||pa(),personId:t.personId,organisationId:n,certificationFamily:r,certificationLevel:i,status:o??VG,validFrom:a,validUntil:s,documentReferences:c??[],notes:u,statusHistory:[{fromStatus:o??VG,toStatus:o??VG,transitionedAt:p,reason:"Certification created"}],extensions:d??[]};return t.certifications.push(l),t.updatedAt=p,{...Y,certification:l}}function Cj({officialRecord:t,assignmentId:e,tournamentId:n,roleSubtype:r,assignedDate:i,startDate:o,endDate:a,assignedBy:s,notes:c,extensions:u}){if(!t)return{error:aj};if(!n)return{error:sr,context:{message:"Missing tournamentId"}};if(!r)return{error:sr,context:{message:"Missing roleSubtype"}};const d=(new Date).toISOString(),p={assignmentId:e||pa(),personId:t.personId,tournamentId:n,roleSubtype:r,status:QG,assignedDate:i??d.split("T")[0],startDate:o,endDate:a,assignedBy:s,notes:c,statusHistory:[{fromStatus:QG,toStatus:QG,transitionedAt:d,reason:"Assignment created"}],extensions:u??[]};return t.assignments.push(p),t.updatedAt=d,{...Y,assignment:p}}function Oj({officialRecord:t,suspensionId:e,organisationId:n,suspensionType:r,suspensionNotes:i,suspendedFrom:o,suspendedUntil:a,extensions:s}){if(!t)return{error:aj};const c={suspensionId:e||pa(),personId:t.personId,organisationId:n,suspensionType:r,suspensionNotes:i,suspendedFrom:o,suspendedUntil:a,extensions:s??[]};return t.suspensions.push(c),t.updatedAt=(new Date).toISOString(),{...Y,suspension:c}}function kj({officialRecord:t,evaluationId:e,evaluatorPersonId:n,subjectPersonId:r,tournamentId:i,tournamentName:o,matchUpId:a,evaluationDate:s,overallRating:c,policyName:u,scores:d,comments:p,documentReference:l,extensions:m}){if(!t)return{error:aj};if(!n)return{error:sr,context:{message:"Missing evaluatorPersonId"}};if(null==c)return{error:sr,context:{message:"Missing overallRating"}};if("number"!=typeof c||c<0)return{error:sr,context:{message:"overallRating must be a non-negative number"}};const f=(new Date).toISOString(),h={evaluationId:e||pa(),evaluatorPersonId:n,subjectPersonId:r??t.personId,tournamentId:i,tournamentName:o,matchUpId:a,evaluationDate:s??f.split("T")[0],overallRating:c,status:$G,policyName:u,scores:d??[],comments:p,documentReference:l,statusHistory:[{fromStatus:$G,toStatus:$G,transitionedAt:f,reason:"Evaluation created"}],extensions:m??[]};return t.evaluations.push(h),t.updatedAt=f,{...Y,evaluation:h}}function Fj({entityType:t,fromStatus:e,toStatus:n}){let r;switch(t){case"certification":r=ej;break;case"evaluation":r=nj;break;case"assignment":r=rj;break;default:return{error:sr,context:{message:`Unknown entityType: ${t}`}}}const i=r[e];return i?i.includes(n)?{...Y,valid:!0}:{error:hj,context:{entityType:t,fromStatus:e,toStatus:n,validTargets:i}}:{error:hj,context:{entityType:t,fromStatus:e,message:`Unknown status: ${e}`}}}function xj({officialRecord:t,certificationFamily:e,certificationLevel:n,organisationId:r,activeOnly:i}){if(!t)return{error:aj};let o=[...t.certifications];return e&&(o=o.filter(t=>t.certificationFamily===e)),n&&(o=o.filter(t=>t.certificationLevel===n)),r&&(o=o.filter(t=>t.organisationId===r)),i&&(o=o.filter(t=>"ACTIVE"===t.status)),{...Y,certifications:o}}function _j({officialRecord:t,certificationId:e,asOfDate:n}){if(!t)return{error:aj};if(!e)return{error:sr,context:{message:"Missing certificationId"}};const r=t.certifications.find(t=>t.certificationId===e);if(!r)return{error:uj,context:{certificationId:e}};const i=[],o=n??(new Date).toISOString().split("T")[0];"ACTIVE"!==r.status&&i.push(`Certification status is ${r.status}`),r.validUntil&&r.validUntil<o&&i.push(`Certification expired on ${r.validUntil}`),r.validFrom&&r.validFrom>o&&i.push(`Certification not yet valid until ${r.validFrom}`);const a=0===i.length;return!a&&r.validUntil&&r.validUntil<o?{error:dj,valid:a,certification:r,reasons:i}:{...Y,valid:a,certification:r,reasons:i}}function Lj({officialRecord:t,policyName:e,evaluationPolicy:n}){let r=n;if(!r&&e){if(!t)return{error:aj};r=t.evaluationPolicies.find(t=>t.policyName===e)}if(!r)return e?{error:Ij,context:{policyName:e}}:{error:sr,context:{message:"Missing evaluationPolicy or policyName"}};const i=[];for(const t of r.sections)for(const e of t.criteria)i.push({fieldId:`${t.sectionId}.${e.criterionId}`,sectionId:t.sectionId,sectionName:t.sectionName,criterionId:e.criterionId,criterionName:e.criterionName,description:e.description,scoringType:e.scoringType,scaleOptions:e.scaleOptions,numericRange:e.numericRange,required:e.required,weight:e.weight,sectionWeight:t.weight});return{...Y,fields:i,evaluationPolicy:r}}function Bj({officialRecord:t,certificationFamily:e,certificationLevel:n,organisationId:r,asOfDate:i}){if(!t)return{error:aj};const o=[],a=i??(new Date).toISOString().split("T")[0];t.suspensions.filter(t=>{const e=t.suspendedFrom??"0000-00-00",n=t.suspendedUntil??"9999-12-31";return e<=a&&n>=a}).length>0&&o.push("Official has active suspension(s)");let s=t.certifications.filter(t=>t.certificationFamily===e&&"ACTIVE"===t.status);if(r&&(s=s.filter(t=>t.organisationId===r)),n&&(s=s.filter(t=>t.certificationLevel===n)),0===s.length){const t=n?` ${n}`:"";o.push(`No active ${e}${t} certification`)}const c=s.filter(t=>!(t.validUntil&&t.validUntil<a)&&!(t.validFrom&&t.validFrom>a));if(s.length>0&&0===c.length&&o.push("Matching certification(s) are expired or not yet valid"),n){const i=t.certificationRequirements.find(t=>t.certificationFamily===e&&t.certificationLevel===n&&(!r||t.organisationId===r));i&&function({certificationFamily:t,officialRecord:e,requirement:n,reasons:r}){if(void 0!==n.minimumAssignments){const t=e.assignments.filter(t=>"COMPLETED"===t.status);t.length<n.minimumAssignments&&r.push(`Insufficient completed assignments: ${t.length}/${n.minimumAssignments}`)}void 0!==n.minimumEvaluationScore&&function({officialRecord:t,requirement:e,reasons:n}){const r=t.evaluations.filter(t=>"APPROVED"===t.status);if(0===r.length)return void n.push("No approved evaluations");const i=r.reduce((t,e)=>t+e.overallRating,0)/r.length;i<e.minimumEvaluationScore&&n.push(`Average evaluation score ${i.toFixed(2)} below minimum ${e.minimumEvaluationScore}`)}({officialRecord:e,requirement:n,reasons:r});if(n.prerequisiteLevels?.length){n.prerequisiteLevels.some(n=>e.certifications.some(e=>e.certificationFamily===t&&e.certificationLevel===n&&("ACTIVE"===e.status||"EXPIRED"===e.status)))||r.push(`Missing prerequisite certification level: ${n.prerequisiteLevels.join(" or ")}`)}}({certificationFamily:e,officialRecord:t,requirement:i,reasons:o})}const u=0===o.length;return{...Y,eligible:u,reasons:o}}function Vj({officialRecord:t,tournamentId:e,roleSubtype:n,status:r}){if(!t)return{error:aj};let i=[...t.assignments];return e&&(i=i.filter(t=>t.tournamentId===e)),n&&(i=i.filter(t=>t.roleSubtype===n)),r&&(i=i.filter(t=>t.status===r)),{...Y,assignments:i}}function Gj({officialRecord:t,policyName:e,approvedOnly:n=!0}){if(!t)return{error:aj};let r=t.evaluations;if(n&&(r=r.filter(t=>"APPROVED"===t.status)),0===r.length)return{...Y,summary:{evaluationCount:0,averageRating:0}};const i=r.map(t=>t.overallRating),o=i.reduce((t,e)=>t+e,0)/i.length,a=[...r].sort((t,e)=>e.evaluationDate>t.evaluationDate?1:-1)[0],s={evaluationCount:r.length,averageRating:Math.round(100*o)/100,latestRating:a.overallRating,latestDate:a.evaluationDate};if(e){const n=t.evaluationPolicies.find(t=>t.policyName===e);if(n){const t=r.filter(t=>t.policyName===e);t.length>0&&(s.sectionAverages=n.sections.map(e=>{const n=new Set(e.criteria.map(t=>t.criterionId)),r=[];for(const e of t){const t=e.scores.filter(t=>n.has(t.criterionId)&&"number"==typeof t.value).map(t=>t.value);t.length>0&&r.push(t.reduce((t,e)=>t+e,0)/t.length)}return{sectionId:e.sectionId,sectionName:e.sectionName,average:r.length>0?Math.round(r.reduce((t,e)=>t+e,0)/r.length*100)/100:0}}),void 0!==n.passingThreshold&&(s.meetsThreshold=s.averageRating>=n.passingThreshold))}}return{...Y,summary:s}}function jj({officialRecord:t}){return t?{...Y,officialRecord:t}:{error:aj}}function qj({officialRecord:t,evaluatorPersonId:e,status:n,tournamentId:r,policyName:i}){if(!t)return{error:aj};let o=[...t.evaluations];return e&&(o=o.filter(t=>t.evaluatorPersonId===e)),n&&(o=o.filter(t=>t.status===n)),r&&(o=o.filter(t=>t.tournamentId===r)),i&&(o=o.filter(t=>t.policyName===i)),{...Y,evaluations:o}}var Wj={__proto__:null,addCertification:Ej,addCertificationRequirement:Uj,addEvaluation:kj,addEvaluationPolicy:wj,addSuspension:Oj,assignOfficial:Cj,createOfficialRecord:Dj,getEvaluationSummary:Gj,getEvaluationTemplate:Lj,getEvaluations:qj,getOfficialAssignments:Vj,getOfficialCertifications:xj,getOfficialEligibility:Bj,modifyCertification:Rj,modifyEvaluation:Nj,mutate:{__proto__:null,addCertification:Ej,addCertificationRequirement:Uj,addEvaluation:kj,addEvaluationPolicy:wj,addSuspension:Oj,assignOfficial:Cj,createOfficialRecord:Dj,modifyCertification:Rj,modifyEvaluation:Nj,removeCertification:bj,removeEvaluation:Mj,removeOfficialAssignment:Tj,removeSuspension:Aj,transitionAssignmentStatus:Pj,transitionCertificationStatus:yj,transitionEvaluationStatus:vj},query:{__proto__:null,getEvaluationSummary:Gj,getEvaluationTemplate:Lj,getEvaluations:qj,getOfficialAssignments:Vj,getOfficialCertifications:xj,getOfficialEligibility:Bj,queryOfficialRecord:jj,validateCertification:_j,validateOfficiatingStatusTransition:Fj},queryOfficialRecord:jj,removeCertification:bj,removeEvaluation:Mj,removeOfficialAssignment:Tj,removeSuspension:Aj,transitionAssignmentStatus:Pj,transitionCertificationStatus:yj,transitionEvaluationStatus:vj,validateCertification:_j,validateOfficiatingStatusTransition:Fj};function $j({tournamentRecord:t,booking:e}){if(void 0!==e.capacity)return e.capacity;const n=t.scheduling?.practice?.defaultCapacity;return n??null}function Hj({booking:t,startTime:e,endTime:n,excludeRegistrationId:r}){return(t.registrations??[]).filter(t=>t.registrationId!==r&&("CANCELLED"!==t.status&&(t.startTime<n&&t.endTime>e))).length}function zj({tournamentRecord:t,participantId:e,date:n,startTime:r,endTime:i,excludeRegistrationId:o}){const a=function({tournamentRecord:t,participantId:e,date:n,startTime:r,endTime:i}){const{matchUps:o}=Qg({tournamentRecord:t});return o?o.filter(t=>{if(_p.includes(t.matchUpStatus))return!1;if(t.winningSide)return!1;const{scheduledDate:o,scheduledTime:a}=t.schedule??{};if(!o||!a)return!1;if(!Ko(o,n))return!1;const s=function(t){const e=t.sides??[],n=[];for(const t of e){t?.participantId&&n.push(t.participantId);const e=t?.participant?.individualParticipantIds??[];n.push(...e)}return n}(t);return!!s.includes(e)&&(a>=r&&a<i)}).map(t=>({matchUpId:t.matchUpId,scheduledDate:t.schedule?.scheduledDate,scheduledTime:t.schedule?.scheduledTime})):[]}({tournamentRecord:t,participantId:e,date:n,startTime:r,endTime:i}),s=function({tournamentRecord:t,...e}){const n=[];for(const r of t.venues??[])for(const t of r.courts??[])Yj({court:t,filter:e,conflicts:n});return n}({tournamentRecord:t,participantId:e,date:n,startTime:r,endTime:i,excludeRegistrationId:o});return{matchUps:a,practiceRegistrations:s}}function Yj({court:t,filter:e,conflicts:n}){for(const r of t.dateAvailability??[]){const i=r.date;if(i&&Ko(i,e.date))for(const o of r.bookings??[])Kj({bookingId:o.bookingId,registrations:o.registrations??[],courtId:t.courtId,date:i,filter:e,conflicts:n})}}function Kj({bookingId:t,registrations:e,courtId:n,date:r,filter:i,conflicts:o}){for(const a of e)Qj({registration:a,filter:i})&&o.push({bookingId:t,courtId:n,date:r,registrationId:a.registrationId,startTime:a.startTime,endTime:a.endTime})}function Qj({registration:t,filter:e}){return t.registrationId!==e.excludeRegistrationId&&("CANCELLED"!==t.status&&(t.participantId===e.participantId&&(!(t.startTime>=e.endTime)&&!(t.endTime<=e.startTime))))}function Jj({tournamentRecord:t,courtId:e,date:n,bookingId:r}){const i=yg({tournamentRecord:t,courtId:e});if(i.error)return i;const{court:o,venue:a}=i;if(!o)return{error:Cn};const s=eE({court:o,date:n});if(!s?.bookings?.length)return{error:kn};const c=s.bookings.find(t=>{if(t.bookingType!==Kh)return!1;if(t.bookingId===r)return!0;return Xj({courtId:e,date:n,startTime:t.startTime})===r});return c?(c.bookingId??=r,{court:o,venue:a,availability:s,booking:c}):{error:kn}}function Xj({courtId:t,date:e,startTime:n}){return`${t}-${e??""}-${n??""}`}function Zj(t){const{tournamentRecord:e,courtId:n,date:r,bookingId:i,participantId:o,startTime:a,endTime:s,notes:c,disableNotice:u}=t,d=dl({tournamentRecord:e,courtId:n,participantId:o},[Ic,jc,Pc]);if(d.error)return d;if(!r)return{error:sr,info:"date is required"};if(!i)return{error:sr,info:"bookingId is required"};if(!a||!s)return{error:sr,info:"startTime and endTime are required"};if(a>=s)return{error:sr,info:"startTime must be before endTime"};const p=e.participants?.some(t=>t.participantId===o);if(!p)return{error:un};const l=Jj({tournamentRecord:e,courtId:n,date:r,bookingId:i});if(l.error)return{error:l.error};const{booking:m,venue:f}=l;if(!m)return{error:sr,info:"booking lookup returned no booking"};if(!((!m.startTime||a>=m.startTime)&&(!m.endTime||s<=m.endTime)))return{error:sr,info:"sub-window must fall inside the booking window"};const h=function({tournamentRecord:t,booking:e,startTime:n,endTime:r}){const i=$j({tournamentRecord:t,booking:e});if(null===i)return;if(0===i)return Ar;const o=Hj({booking:e,startTime:n,endTime:r});return o+1>i?Ar:void 0}({tournamentRecord:e,booking:m,startTime:a,endTime:s});if(h)return{error:h};const g=zj({tournamentRecord:e,participantId:o,date:r,startTime:a,endTime:s}),I={registrationId:pa("reg"),participantId:o,startTime:a,endTime:s,status:"CONFIRMED",registeredAt:(new Date).toISOString(),createdAt:(new Date).toISOString()};c&&(I.notes=c),m.registrations??=[],m.registrations.push(I),m.updatedAt=(new Date).toISOString(),!u&&f&&di({payload:{venue:f,tournamentId:e.tournamentId},topic:El,key:f.venueId});const S={...Y,registration:I};return(g.matchUps.length||g.practiceRegistrations.length)&&(S.conflicts=g),S}function tq(t){const{tournamentRecord:e,courtId:n,date:r,bookingId:i,registrationId:o,disableNotice:a}=t,s=dl({tournamentRecord:e,courtId:n},[Ic,jc]);if(s.error)return s;if(!r)return{error:sr,info:"date is required"};if(!i)return{error:sr,info:"bookingId is required"};if(!o)return{error:sr,info:"registrationId is required"};const c=Jj({tournamentRecord:e,courtId:n,date:r,bookingId:i});if(c.error)return{error:c.error};const{booking:u,venue:d}=c;if(!u)return{error:sr,info:"booking lookup returned no booking"};const p=u.registrations?.findIndex(t=>t.registrationId===o)??-1;return p<0?{error:Mr}:(u.registrations.splice(p,1),u.updatedAt=(new Date).toISOString(),!a&&d&&di({payload:{venue:d,tournamentId:e.tournamentId},topic:El,key:d.venueId}),{...Y})}function eq({tournamentRecord:t,defaultCapacity:e,disableNotice:n}){const r=dl({tournamentRecord:t},[Ic]);if(r.error)return r;return null!==e&&("number"!=typeof e||!Number.isInteger(e)||e<0)?{error:sr,info:"defaultCapacity must be a non-negative integer or null"}:(t.scheduling??={},t.scheduling.practice??={},t.scheduling.practice.defaultCapacity=e,n||di({payload:{tournamentId:t.tournamentId},topic:Al,key:t.tournamentId}),{...Y})}function nq(t){const{tournamentRecord:e,courtId:n,date:r,bookingId:i,registrationId:o,updates:a,disableNotice:s}=t,c=dl({tournamentRecord:e,courtId:n},[Ic,jc]);if(c.error)return c;if(!r)return{error:sr,info:"date is required"};if(!i)return{error:sr,info:"bookingId is required"};if(!o)return{error:sr,info:"registrationId is required"};if(!a||!Object.keys(a).length)return{error:sr,info:"updates payload is required"};const u=Jj({tournamentRecord:e,courtId:n,date:r,bookingId:i});if(u.error)return{error:u.error};const{booking:d,venue:p}=u;if(!d)return{error:sr,info:"booking lookup returned no booking"};const l=d.registrations?.find(t=>t.registrationId===o);if(!l)return{error:Mr};const m=a.startTime??l.startTime,f=a.endTime??l.endTime;if(m>=f)return{error:sr,info:"startTime must be before endTime"};if(!((!d.startTime||m>=d.startTime)&&(!d.endTime||f<=d.endTime)))return{error:sr,info:"sub-window must fall inside the booking window"};const h=a.status??l.status??"CONFIRMED",g="CONFIRMED"===h;if(g){const t=function({tournamentRecord:t,booking:e,startTime:n,endTime:r,excludeRegistrationId:i}){const o=$j({tournamentRecord:t,booking:e});if(null===o)return;if(0===o)return Ar;const a=Hj({booking:e,startTime:n,endTime:r,excludeRegistrationId:i});return a+1>o?Ar:void 0}({tournamentRecord:e,booking:d,startTime:m,endTime:f,excludeRegistrationId:o});if(t)return{error:t}}l.startTime=m,l.endTime=f,l.status=h,void 0!==a.notes&&(l.notes=a.notes),"CANCELLED"===h?l.cancelledAt=(new Date).toISOString():delete l.cancelledAt,l.updatedAt=(new Date).toISOString(),d.updatedAt=l.updatedAt,!s&&p&&di({payload:{venue:p,tournamentId:e.tournamentId},topic:El,key:p.venueId});const I={...Y,registration:l};if(g){const t=zj({tournamentRecord:e,participantId:l.participantId,date:r,startTime:m,endTime:f,excludeRegistrationId:o});(t.matchUps.length||t.practiceRegistrations.length)&&(I.conflicts=t)}return I}function rq(t){const{tournamentRecord:e,...n}=t??{},r=[];if(!e)return{registrations:r};for(const t of e.venues??[])for(const e of t.courts??[])n.courtId&&e.courtId!==n.courtId||iq({venueId:t.venueId,court:e,filter:n,out:r});return{registrations:r}}function iq({venueId:t,court:e,filter:n,out:r}){for(const i of e.dateAvailability??[]){const o=i.date;if(o&&(!n.date||Ko(o,n.date)))for(const a of i.bookings??[])a.bookingType===Kh&&oq({booking:a,venueId:t,courtId:e.courtId,date:o,filter:n,out:r})}}function oq({booking:t,venueId:e,courtId:n,date:r,filter:i,out:o}){const a=t.bookingId??Xj({courtId:n,date:r,startTime:t.startTime});for(const s of t.registrations??[])(i.includeCancelled||"CANCELLED"!==s.status)&&(i.participantId&&s.participantId!==i.participantId||o.push({registration:s,courtId:n,venueId:e,date:r,bookingId:a,bookingStartTime:t.startTime,bookingEndTime:t.endTime}))}var aq={__proto__:null,addPracticeRegistration:Zj,getPracticeRegistrations:rq,mutate:{__proto__:null,addPracticeRegistration:Zj,removePracticeRegistration:tq,setPracticeDefaultCapacity:eq,updatePracticeRegistration:nq},query:{__proto__:null,getPracticeRegistrations:rq},removePracticeRegistration:tq,setPracticeDefaultCapacity:eq,updatePracticeRegistration:nq};function sq(t){if(!t?.tournamentRecord&&!Array.isArray(t?.venueMatchUps))return{error:rt};if(!t?.courtId)return{error:Me};const{scheduleVisibilityFilters:e,tournamentRecord:n,matchUpFilters:r,venueMatchUps:i,courtId:o}=t,{schedulingProfile:a}=HA({tournamentRecord:n});if(Array.isArray(i))return{matchUps:c({matchUps:i,courtId:o})};const{matchUps:s}=Qg({scheduleVisibilityFilters:e,tournamentRecord:n,matchUpFilters:r});return{matchUps:c({matchUps:s,courtId:o})};function c({matchUps:t,courtId:e}){return gE({matchUps:t.filter(t=>{const n=t.schedule?.allocatedCourts?.map(({courtId:t})=>t);return t.schedule?.courtId===e||n?.includes(e)}),schedulingProfile:a})}}function cq({tournamentRecord:t,dateAvailability:e,disableNotice:n,venueMatchUps:r,courtId:i,force:o}){const a=dl({tournamentRecord:t,courtId:i},[Ic,jc]);if(a.error)return a;const s=cg({dateAvailability:e});if(s.error)return s;const{updatedDateAvailability:c,totalMergeCount:u}=function(t){let e=0;const n=t.reduce((t,e)=>{const{date:n,startTime:r,endTime:i,bookings:o}=e;return t[n]||(t[n]=[]),t[n].push({startTime:r,endTime:i,bookings:o}),t},{}),r=[];return Object.keys(n).forEach(t=>{n[t].sort(sg);const{mergedAvailability:i,mergeCount:o}=function(t){let e,n,r,i=t.length,o=0;const a=[];for(;t.length&&i;){const s=t.shift(),{startTime:c,endTime:u,bookings:d}=s;if(i-=1,e){if($o(Wo(n),Wo(c),!1)>0){const t={startTime:e,endTime:n};r?.length&&(t.bookings=r),a.push(t),e=c,r=d,n=u}else d&&(r?r.push(d):r=d),n=u,o+=1}else e=c,r=d,n=u}const s={startTime:e,endTime:n};r?.length&&(s.bookings=r);return a.push(s),{mergedAvailability:a,mergeCount:o}}(n[t]);r.push(...i.map(e=>({date:t,...e}))),e+=o}),{updatedDateAvailability:r,totalMergeCount:e}}(e);e=c;const d=yg({tournamentRecord:t,courtId:i});if(d.error)return d;const{court:p,venue:l}=d,{matchUps:m}=sq({tournamentRecord:t,venueMatchUps:r,courtId:i});if(m?.length){const n=xd({tournamentRecord:t})?.appliedPolicies,r=o??n?.[Ou]?.allowDeletionWithScoresPresent?.courts,i=m.filter(t=>{if(_p.includes(t.matchUpStatus))return!1;if(t.winningSide)return!1;const{scheduledDate:n,scheduledTime:r}=t.schedule??{};if(!n||!r)return!1;const i=e.filter(t=>t.date===n);if(!i.length)return!0;const o=Wo(r);return!i.some(t=>{const e=Wo(t.startTime),n=Wo(t.endTime);return $o(e,o,!1)<=0&&$o(o,n,!1)<=0})});if(i.length&&!r)return{error:gt,info:`${i.length} matchUp(s) scheduled outside new availability`,matchUpIds:i.map(t=>t.matchUpId)}}return p&&(p.dateAvailability=e,!n&&l&&di({payload:{venue:l,tournamentId:t.tournamentId},topic:El,key:l.venueId})),{...Y,totalMergeCount:u}}function uq({tournamentRecord:t,drawDefinition:e,matchUpId:n,drawId:r}){if(!n)return{error:fe};if(!e&&!r)return{error:bt};let i;if(!e){if(!t)return{error:rt};({drawDefinition:e}=wg({tournamentRecord:t,drawId:r}))}if(e)({matchUp:i}=nT({drawDefinition:e,matchUpId:n}));else{if(!t)return{error:rt};const e=Qg({tournamentRecord:t,inContext:!1}).matchUps??[];({matchUp:i}=eT({matchUps:e,matchUpId:n}))}if(!i)return{error:ge};if(i.timeItems){i.timeItems.find(t=>[th,Zf].includes(t.itemType))&&(i.timeItems=i.timeItems.filter(({itemType:t})=>![th,Zf].includes(t)),Yl({tournamentId:t?.tournamentId,context:"removeCourtAssignment",drawDefinition:e,matchUp:i}))}return{...Y}}function dq({matchUpsCount:t=0}){return{error:Rr,info:`Schedule would be deleted from ${t} ${1===t?"matchUp":"matchUps"}; use { force: true }`}}function pq(t){const{courtId:e,disableNotice:n,force:r}=t,i=im(t),o=fu(t,[{[hc]:!0,[jc]:!0}]);if(o.error)return o;let a,s;for(const t of Object.values(i)){if(s=lq({tournamentRecord:t,disableNotice:n,courtId:e,force:r}),s.error&&s.error!==Cn)return s;s.success&&(a=!0)}return a?{...Y}:s}function lq({tournamentRecord:t,disableNotice:e,courtId:n,force:r}){const i=yg({tournamentRecord:t,courtId:n});if(i.error)return i;const o=i.venue,{matchUps:a}=sq({tournamentRecord:t,courtId:n}),s=xd({tournamentRecord:t})?.appliedPolicies,c=r??s?.[Ou]?.allowDeletionWithScoresPresent?.courts;if(a?.length&&!c)return dq({matchUpsCount:a.length});for(const e of a??[]){const n=uq({matchUpId:e.matchUpId,drawId:e.drawId,tournamentRecord:t});if(n.error)return n}return o&&(o.courts=(o.courts??[]).filter(t=>t.courtId!==n),e||di({payload:{venue:o,tournamentId:t.tournamentId},topic:El,key:o.venueId})),{...Y}}function mq(t){const{tournamentRecord:e,courtIds:n,force:r}=t;if(!e)return{error:rt};if(!Array.isArray(n))return{error:sr};for(const t of n){const n=lq({tournamentRecord:e,courtId:t,force:r});if(n.error)return n}return{...Y}}function fq(t){if("string"!=typeof t?.venueId)return{error:Bn};const{tournamentRecord:e,venueId:n,force:r}=t,i=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!Object.keys(i).length)return{error:rt};const o=Jg({tournamentRecords:i,contextFilters:{venueIds:[n]}}).matchUps??[],a=xd({tournamentRecord:e})?.appliedPolicies,s=r??a?.[Ou]?.allowDeletionWithScoresPresent?.venues;if(o.length&&!s)return dq({matchUpsCount:o.length});for(const t of Object.values(i)){for(const e of o){const n=uq({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&&di({payload:{venueId:n,tournamentId:t.tournamentId},topic:vl,key:n})}return YA({tournamentRecords:i}),{...Y}}function hq({tournamentRecord:t,venueIds:e,force:n}){if(!t)return{error:rt};if(!Array.isArray(e))return{error:sr};for(const r of t.venues??[]){const{venueId:i}=r;if(e.includes(i)){const{venueId:e}=r,i=fq({tournamentRecord:t,venueId:e,force:n});if(i.error)return i}}return{...Y}}function gq(t){const{courtIds:e,dates:n}=t,r=im(t),i=fu(t,[{[hc]:!0,[Lc]:!0}]);if(i.error)return i;for(const t of Object.values(r))Iq({tournamentRecord:t,courtIds:e,dates:n});return{...Y}}function Iq({tournamentRecord:t,courtIds:e,dates:n}){const r=!Array.isArray(n)||!n.length||{dates:n},i=t=>sp({element:t,attribute:"disabled",name:od,value:r,creationTime:!1});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{...Y}}function Sq(t){const{tournamentRecords:e,tournamentId:n,venueIds:r}=t,i=fu(t,[{[hc]:!0,[Vc]:!0}]);if(i.error)return i;const o=Object.keys(e).filter(t=>!n||t===n);for(const t of o){yq({tournamentRecord:e[t],venueIds:r})}return{...Y}}function yq({tournamentRecord:t,venueIds:e}){for(const n of t.venues??[])if(e?.includes(n.venueId)){const t=sp({element:n,attribute:"disabled",name:od,value:!0,creationTime:!1});if(t.error)return t}return{...Y}}function vq(t){const e=im(t),n=[{[hc]:!0}];!t.enableAll&&n.push({[Lc]:!0});const r=fu(t,n);if(r.error)return r;const{enableAll:i,courtIds:o,dates:a}=t;for(const t of Object.values(e))Uq({tournamentRecord:t,courtIds:o,enableAll:i,dates:a});return{...Y}}function Uq({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 e=dp({element:t,attribute:"disabled",name:od});e&&(Array.isArray(e.dates)&&(e.dates=e.dates.filter(t=>!r.includes(t))),sp({element:t,attribute:"disabled",name:od,value:e,creationTime:!1}))}else sp({element:t,attribute:"disabled",name:od,value:void 0});return{...Y}}function Pq(t){const e=im(t),n=[{[hc]:!0}];!t.enableAll&&n.push({[Vc]:!0});const r=fu(t,n);if(r.error)return r;const{venueIds:i,enableAll:o}=t;for(const t of Object.values(e))for(const e of t.venues??[])(o||i?.includes(e.venueId))&&sp({element:e,attribute:"disabled",name:od,value:void 0});return{...Y}}function Tq(t){const{disableNotice:e,modifications:n,courtId:r,force:i,venueMatchUps:o}=t,a=im(t);if(!Object.keys(a).length)return{error:nt};let s;for(const t of Object.values(a)){const a=wq({tournamentRecord:t,disableNotice:e,venueMatchUps:o,modifications:n,courtId:r,force:i});if(a?.error)return a;s=!0}return s?{...Y}:void 0}function wq({tournamentRecord:t,disableNotice:e,venueMatchUps:n,modifications:r,courtId:i,force:o}){const a=dl({tournamentRecord:t,courtId:i},[Ic,jc]);if(a.error)return a;if(!r||"object"!=typeof r)return{error:ir};const s=yg({tournamentRecord:t,courtId:i});if(s.error)return s;const{venue:c,court:u}=s,d=Object.keys({altitude:void 0,courtId:void 0,courtName:"",courtDimensions:void 0,latitude:void 0,longitude:void 0,surfaceCategory:void 0,surfaceType:void 0,surfacedDate:void 0,indoorOutdoor:void 0,floodlit:void 0,dateAvailability:[],onlineResources:[],pace:void 0,notes:void 0}).filter(t=>"courtId"!==t);if(!Object.keys(r).filter(t=>d.includes(t)).length)return{error:pr};const p=new Set(d.filter(t=>!["dateAvailability"].includes(t))),l=Object.keys(r).filter(t=>p.has(t));if(u&&l.forEach(t=>Object.assign(u,{[t]:r[t]})),r.dateAvailability){const a=cq({dateAvailability:r.dateAvailability,tournamentRecord:t,venueMatchUps:n,disableNotice:e,courtId:i,force:o});if(a.error)return a}return e||di({payload:{venue:c,tournamentId:t.tournamentId},topic:El,key:c?.venueId}),{...Y,court:ca(u)}}function Dq(t){const{modifications:e,venueId:n,force:r}=t,i=im(t);if(!Object.keys(i).length)return{error:nt};if("string"!=typeof n)return{error:Bn};let o,a;for(const t of Object.values(i)){const i=Rq({tournamentRecord:t,modifications:e,venueId:n,force:r});if(i.success&&(a=!0),i.error&&(o=i.error),i.error&&i.error!==Ln)return i}return YA({tournamentRecords:i}),a?{...Y}:{error:o}}function Rq({tournamentRecord:t,modifications:e,venueId:n,force:r}){const i=dl({tournamentRecord:t,venueId:n},[Ic,Xc]);if(i.error)return i;if(!e||"object"!=typeof e)return{error:ir};const o=t,a=xd({tournamentRecord:o})?.appliedPolicies,s=r??a?.[Ou]?.allowDeletionWithScoresPresent?.venues,{matchUps:c}=function({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:n,venueId:r}){const i=dl({tournamentRecord:e,venueId:r},[Ic,Xc]);if(i.error)return i;const{schedulingProfile:o}=HA({tournamentRecord:e}),{matchUps:a}=Qg({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:n}),s=function({matchUps:t,venueId:e}){return gE({matchUps:t.filter(t=>{const n=t.schedule?.allocatedCourts?.map(({venueId:t})=>t);return t.schedule?.venueId===e||n?.includes(e)}),schedulingProfile:o})}({matchUps:a,venueId:r});return{matchUps:s}}({tournamentRecord:o,venueId:n}),u=Ig({tournamentRecord:o,venueId:n});if(u.error)return u;const d=u.venue,p=Object.keys({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,defaultStartTime:void 0,defaultEndTime:void 0,isPrimary:void 0,dateAvailability:[],addresses:[],contacts:[],courts:[],roles:[]}).filter(t=>"venueId"!==t);if(!Object.keys(e).filter(t=>p.includes(t)).length)return{error:pr};const l=new Set(p.filter(t=>!["courts","onlineResources","dateAvailability","isPrimary"].includes(t))),m=Object.keys(e).filter(t=>l.has(t));if(!d)return{error:Ln};const f=e.defaultStartTime??d.defaultStartTime,h=e.defaultEndTime??d.defaultEndTime;if(f||h){if(!f||!h)return{error:sr,info:"both defaultStartTime and defaultEndTime are required"};if(!ag({startTime:f,endTime:h}))return{error:sr,info:"defaultEndTime must be after defaultStartTime"}}if(m.forEach(t=>Object.assign(d,{[t]:e[t]})),"isPrimary"in e&&(e.isPrimary?(fg({tournamentRecord:o}),d.isPrimary=!0):delete d.isPrimary),void 0!==e.dateAvailability){if(Array.isArray(e.dateAvailability)&&e.dateAvailability.length){const t=cg({dateAvailability:e.dateAvailability});if(t.error)return t}d.dateAvailability=e.dateAvailability}const g=function({venue:t,modifications:e,tournamentRecord:n,venueMatchUps:r,allowModificationWhenMatchUpsScheduled:i}){const o=t?.courts?.map(t=>t.courtId)??[],a=e.courts?.map(t=>t.courtId)??[],s=a.length?o.filter(t=>!a.includes(t)):e?.courts&&o,c=[];if(s?.length){const e=t?.courts?.filter(t=>s.includes(t.courtId)),o=e?.map(t=>{const e=sq({courtId:t.courtId,tournamentRecord:n,venueMatchUps:r});for(const t of e.matchUps??[])c.push({matchUpId:t.matchUpId,drawId:t.drawId});return e.matchUps?.length??0}).reduce((t,e)=>t+e);return!t||o&&!i?dq({matchUpsCount:o}):(t.courts=t.courts?.filter(t=>a.includes(t.courtId)),vF({schedule:{courtId:"",scheduledDate:""},matchUpDetails:c,removePriorValues:!0,tournamentRecord:n}),{success:!0})}return{success:!0}}({venue:d,modifications:e,tournamentRecord:o,venueMatchUps:c,allowModificationWhenMatchUpsScheduled:s});if("error"in g&&g.error)return g;const I=function({modifications:t,tournamentRecord:e,venueMatchUps:n,venueId:r,force:i}){if(t.courts)for(const o of t.courts){const{courtId:t}=o??{};let a=Tq({modifications:o,disableNotice:!0,tournamentRecord:e,venueMatchUps:n,courtId:t,force:i});if(a?.error===Cn&&(a=Bx({disableNotice:!0,tournamentRecord:e,venueId:r,court:o})),a?.error)return a}return{success:!0}}({modifications:e,tournamentRecord:o,venueMatchUps:c,venueId:n,force:r});return I?.error?I:(YA({tournamentRecord:o}),d&&di({payload:{venue:d,tournamentId:o.tournamentId},topic:El,key:d?.venueId}),{...Y,venue:ca(d)})}var bq={__proto__:null,addCourt:Bx,addCourts:Vx,addVenue:hg,deleteCourt:pq,deleteCourts:mq,deleteVenue:fq,deleteVenues:hq,disableCourts:gq,disableVenues:Sq,enableCourts:vq,enableVenues:Pq,generate:{__proto__:null,generateCourts:yO},generateCourts:yO,getCompetitionVenues:Iw,getCourts:BE,getVenuesAndCourts:gw,modifyCourt:Tq,modifyCourtAvailability:cq,modifyVenue:Dq,mutate:{__proto__:null,addCourt:Bx,addCourts:Vx,addVenue:hg,deleteCourt:pq,deleteCourts:mq,deleteVenue:fq,deleteVenues:hq,disableCourts:gq,disableVenues:Sq,enableCourts:vq,enableVenues:Pq,modifyCourt:Tq,modifyCourtAvailability:cq,modifyVenue:Dq},publicFindVenue:Sg,query:VE},Nq={__proto__:null,availabilityGovernor:BG,competitionGovernor:Yp,drawsGovernor:oC,entriesGovernor:IC,eventGovernor:aO,generationGovernor:NO,matchUpFormatGovernor:MO,matchUpGovernor:eF,mocksGovernor:t_,officiatingGovernor:Wj,participantGovernor:A_,policyGovernor:$N,practiceGovernor:aq,publishingGovernor:q_,queryGovernor:YE,rankingGovernor:iL,reportGovernor:qL,scheduleGovernor:mB,scoreGovernor:CN,tieFormatGovernor:_B,tournamentGovernor:wV,venueGovernor:bq};const{extractTime:Mq,timeStringMinutes:Aq}=Qo;const Eq=["collectionId","collectionPosition","drawPositions","extensions","finishingPositionRange","finishingRound","isMock","matchUpId","matchUpStatus","matchUpStatusCodes","orderOfFinish","processCodes","roundNumber","tieFormat","tieMatchUps","roundPosition","score","sides","winnerMatchUpId","loserMatchUpId","matchUpDuration","winningSide"];function Cq(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,Cq(t[i],e,n.concat(i))),{})}var Oq={__proto__:null,JSON2CSV:function(t,e){if(e&&"object"!=typeof e)return{error:sr};let{columnTransform:n={}}=e??{};const{includeTransformAccessors:r,includeHeaderRow:i=!0,returnTransformedJSON:o,removeEmptyColumns:a,onlyHeaderRow:s,columnAccessors:c=[],functionMap:u={},columnMap:d={},valuesMap:p={},context:m={},delimiter:f='"',columnJoiner:h=",",rowJoiner:g="\r\n",keyJoiner:I="."}=e??{};if(!Array.isArray(t)||!Array.isArray(c)||"object"!=typeof m||"object"!=typeof d||"object"!=typeof n||"object"!=typeof u||"object"!=typeof p||"string"!=typeof h||"string"!=typeof g||"string"!=typeof I||"string"!=typeof f)return{error:sr};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 S=t.filter(Boolean).map(t=>Cq(t,I)),y=Object.values(n).flat();r&&c.push(...y);const v=S.reduce((t,e)=>Object.keys(e).every(e=>!t.includes(e)&&t.push(e)||!0)&&t,[]).filter(t=>!c?.length||c.includes(t)),U=Object.assign({},...Object.keys(n).reverse().map(t=>n[t].map(e=>({[e]:t})).flat()).flat()),T=v.reduce((t,e)=>{const n=U[e];return n?t.includes(n)||t.push(n):t.push(e),t},[]).sort((t,n)=>e?.sortOrder?e.sortOrder.includes(t)&&e.sortOrder.includes(n)&&e.sortOrder.indexOf(t)-e.sortOrder.indexOf(n)||!e.sortOrder.includes(n)&&-1:0);Object.keys(d).forEach(t=>!T.includes(t)&&T.unshift(t)),Object.keys(n).forEach(t=>!T.includes(t)&&T.unshift(t)),"object"==typeof m&&Object.keys(m).forEach(t=>!T.includes(t)&&T.unshift(t));let w=T.map(t=>d[t]||t);if(s)return[w];const D=t=>`${f}${t}${f}`,R=[];let b=S.map(t=>Object.values(T.reduce((e,r,i)=>{const o=n[r],a=(o?.length?t[o.find(e=>t[e])]:t[r])||m?.[r]||"",s=p[r]?.[a]||a,c=l(u[r])?u[r](s):s;return e[r]=D(c),c&&(R[i]=(R[i]||0)+1),e},{})));const N=a&&[...R].map((t,e)=>!t&&e).filter(P).reverse();if(N){const t=t=>t.filter((t,e)=>!N.includes(e));b=b.map(t),w=t(w)}const M=b.map(t=>t.join(h));return o?M.map(t=>{const e=t.split(h);return Object.assign({},...e.map((t,e)=>({[w[e]]:t})))}):i?[w.map(D).join(h),...M].join(g):M.join(g)},UUID:pa,UUIDS:da,allNumeric:W,attributeFilter:Tu,chunkArray:q,chunkByNth:H,chunkSizeProfile:function t(e,[n,...r]){return e.length?[e.slice(0,n),...t(e.slice(n),[...r,n])]:[]},constantToString:Ny,countValues:function(t){return O(C(t))},createMap:g,dateTime:Qo,definedAttributes:Ei,dehydrateMatchUps:function({tournamentRecord:t}){if(!t)return{error:rt};if("object"!=typeof t||!t.tournamentId)return{error:sr};const{matchUps:e}=Qg({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,o=e[t]||e[r]||e[i],a=n.matchUpFormat===o?void 0:n.matchUpFormat;for(const t of Object.keys(n))Eq.includes(t)||delete n[t];n.sides&&n.drawPositions&&!n.tieMatchUps&&delete n.sides,a&&(n.matchUpFormat=a)}}(e,n)}return{...Y}},extractAttributes:tI,flattenJSON:Cq,generateDateRange:Ao,generateHashCode:function(t){if(null===t||"object"!=typeof t)return;const e=JSON.stringify(t),n=I(t),r=e.split("").reduce((t,e)=>t+e.charCodeAt(0),0);return[e.length,n,r].map(t=>t.toString(36)).join("")},generateRange:L,generateTimeCode:e_,groupValues:O,hasAttributeValues:t=>e=>Object.keys(t).every(n=>e[n]===t[n]),instanceCount:C,intersection:V,isConvertableInteger:R,isNumeric:P,isOdd:T,isPowerOf2:S,isValidEmbargoDate:Oo,makeDeepCopy:ca,matchUpChronologicalSort:HL,matchUpScheduleSort:function(t,e){const n=t.schedule??{},r=e.schedule??{};if(n.scheduledDate&&!r.scheduledDate)return 1;if(r.scheduledDate&&!n.scheduledDate)return-1;if(n.scheduledDate&&r.scheduledDate){if(n.scheduledDate===r.scheduledDate){if(n.scheduledTime&&!r.scheduledTime)return 1;if(r.scheduledTime&&!n.scheduledTime)return-1;if(n.scheduledTime&&r.scheduledTime){return Aq(Mq(n.scheduledTime))-Aq(Mq(r.scheduledTime))}}return new Date(n.scheduledDate).getTime()-new Date(r.scheduledDate).getTime()}return 0},matchUpSort:Xg,nearestPowerOf2:U,nextPowerOf2:w,noNulls:function(t){return Array.isArray(t)?t?.map(t=>null===t?void 0:t):t},noNumeric:$,numericSort:d,occurrences:function(t,e){return Array.isArray(e)&&e.reduce((t,e)=>(t[e]=1+t[e]||1,t),{})[t]||0},overlap:j,randomMember:_,randomPop:x,shuffleArray:A,structureSort:rl,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)):[]},timeZone:jF,undefinedToNull:function t(e,n){if(void 0===e)return null;if(!f(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}){mI.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=>{fI({color:"blue",method:"draw",structure:r[e],keyColors:{structure:"magenta"}},!0);const n=t.filter(t=>t.structureId===e),i=Bf({matchUps:n})?.roundMatchUps||[];Object.keys(i).forEach(t=>{fI({roundNumber:t,keyColors:{roundNumber:"brightcyan"}},!0),i[t].forEach(({matchUpId:t,schedule:e})=>{fI({matchUpId:t,time:_o(e.scheduledTime),date:e.scheduledDate,venue:e.venueId,keyColors:{time:"brightcyan",date:"brightcyan",matchUpId:"yellow",venue:"magenta"}},!0)})})}),e&&hI()}};function kq(t){return t?t.split("."):[]}function Fq(t,e){if(null==t)return;const n=kq(e);let r=t;for(const t of n){if(null==r)return;r=r[t]}return r}function xq(t,e,n){const r=kq(e);return r.length?_q(t,r,0,n):t}function _q(t,e,n,r){const i=e[n],o=n===e.length-1,a=e[n+1],s=void 0!==a&&/^\d+$/.test(a),c=t&&"object"==typeof t?t[i]:void 0,u=o?r:_q(c??(s?[]:{}),e,n+1,r);if(Array.isArray(t)){const e=t.slice();return e[Number(i)]=u,e}return{...t??{},[i]:u}}function Lq(t,e){const n=kq(e);return n.length?Bq(t,n,0):t}function Bq(t,e,n){const r=e[n];if(n===e.length-1){if(Array.isArray(t)){const e=t.slice();return e.splice(Number(r),1),e}const e={...t??{}};return delete e[r],e}const i=t?.[r];if(void 0===i)return t;const o=Bq(i,e,n+1);if(Array.isArray(t)){const e=t.slice();return e[Number(r)]=o,e}return{...t??{},[r]:o}}function Vq(t,e){return e&&function(t,e){return!!e&&!(!t||"object"!=typeof t)&&Object.prototype.hasOwnProperty.call(t,e)}(t,e)?t[e]??{}:t??{}}function Gq(t,e){return e?{[e]:t}:t}function jq(t){const{policyType:e,definition:n}=t;return{get:t=>Fq(n,t),extend(t){const r=Vq(t,e),i=w_(n,r);return jq({policyType:e,definition:i})},set(t,r){const i=xq(n,t,r);return jq({policyType:e,definition:i})},merge(t,r){const i=Fq(n,t),o=i&&"object"==typeof i?w_(i,r):r,a=xq(n,t,o);return jq({policyType:e,definition:a})},unset(t){const r=Lq(n,t);return jq({policyType:e,definition:r})},from({name:t,version:n}){if(!e)throw new Error("policyComposer.from() requires the composer to be scoped to a policyType");const r=AM.lookup({policyType:e,name:t,version:n});if(!r){throw new Error(`policyComposer.from(): no registry entry for ${e}::${t}${n?` version ${n}`:""}`)}return jq({policyType:e,definition:r})},build:()=>Gq(n,e),register({name:t,version:r}){if(!e)throw new Error("policyComposer.register() requires the composer to be scoped to a policyType");return AM.register({policyType:e,name:t,version:r,definition:n}),Gq(n,e)}}}const qq=new Map([["ERR_MISSING_TOURNAMENT",()=>["Call tournamentEngine.setState({ tournamentRecord }) before this method.","Or pass `tournamentRecord` directly in the method params."]],["ERR_MISSING_TOURNAMENTS",()=>["Call tournamentEngine.setState({ tournamentRecords }) before this method.","Or pass `tournamentRecords` directly in the method params."]],["ERR_MISSING_DRAWDEF",()=>["Pass `drawId` in the method params — the engine will resolve drawDefinition from state.","Or check that the tournament actually contains the expected drawDefinition."]],["ERR_MISSING_EVENT_ID",()=>["Pass `eventId` in the method params.","Or pass `event` directly (the resolved Event object)."]],["ERR_MISSING_VALUE",t=>{const e=t&&"object"==typeof t&&"key"in t?String(t.key):void 0;return e?[`A required parameter \`${e}\` is missing — check the method signature.`]:["A required parameter is missing — check the method signature for required fields."]}],["ERR_INVALID_VALUES",t=>{const e=t&&"object"==typeof t?Object.keys(t):[];return e.length?[`Check value(s) for: ${e.join(", ")}. Confirm types and ranges match the method signature.`]:["Check the value(s) passed match the expected types and ranges declared by the method."]}],["ERR_INVALID_DATE",()=>["Use ISO 8601 format: `YYYY-MM-DD` for dates, full ISO timestamp for date-times.","Confirm the date is within the tournament `startDate` / `endDate` window if scheduling."]],["ERR_NOT_FOUND_PARTICIPANT",()=>["Confirm the participantId exists in `tournamentRecord.participants`.","Participants are auto-added when registered via `addParticipants`; manual draws may need explicit add."]],["ERR_NOT_FOUND_STRUCTURE",()=>["Pass a valid `structureId` from `drawDefinition.structures[].structureId`.","The structure may have been removed by an earlier mutation; re-read drawDefinition after."]],["ERR_NOT_FOUND_MATCHUP",()=>["Pass a valid `matchUpId` from the structure / tieMatchUps the matchUp belongs to.","Adhoc matchUps need to be added via `addAdHocMatchUps` before they can be looked up."]],["ERR_NOT_FOUND_EVENT",()=>["Pass a valid `eventId` from `tournamentRecord.events[].eventId`.","Event may have been deleted by an earlier mutation; re-read events after."]],["ERR_MISSING_SANCTIONING_RECORD",()=>["Initialize the sanctioning record via the sanctioning engine before this call.","Or pass `sanctioningRecord` directly in the params."]],["ERR_MISSING_OFFICIAL_RECORD",()=>["Initialize the officiating record via the officiating engine before this call.","Or pass `officialRecord` directly in the params."]],["ENGINE_RETURNED_UNDEFINED",()=>["The engine method returned no result. Check that state is loaded (call `setState` first).","Or confirm the method name exists on the engine (typos surface here)."]]]);function Wq(t,e){qq.set(t,e)}function $q(t,e){const n=qq.get(t);if(!n)return[];try{return n(e)??[]}catch{return[]}}class Hq extends Error{constructor(t,e,n){super(e,void 0!==n?.cause?{cause:n.cause}:void 0),this.name=this.constructor.name,this.code=t,void 0!==n?.methodName&&(this.methodName=n.methodName),void 0!==n?.path&&(this.path=n.path),void 0!==n?.context&&(this.context=n.context),void 0!==n?.info&&(this.info=n.info)}get suggestions(){return $q(this.code,this.context)}toJSON(){return{message:this.message,code:this.code,...void 0!==this.info?{info:this.info}:{}}}}class zq extends Hq{constructor(t){super("ERR_MISSING_TOURNAMENT","Missing tournamentRecord",t)}}class Yq extends Hq{constructor(t){super("ERR_MISSING_TOURNAMENTS","Missing tournamentRecords",t)}}class Kq extends Hq{constructor(t){super("ERR_MISSING_DRAWDEF","Missing drawDefinition",t)}}class Qq extends Hq{constructor(t){super("ERR_MISSING_EVENT_ID","Missing event / eventId",t)}}class Jq extends Hq{constructor(t){super("ERR_MISSING_VALUE","Missing value",t)}}class Xq extends Hq{constructor(t){super("ERR_MISSING_SANCTIONING_RECORD","Missing sanctioningRecord",t)}}class Zq extends Hq{constructor(t){super("ERR_MISSING_OFFICIAL_RECORD","Missing officialRecord",t)}}class tW extends Hq{constructor(t){super("ERR_INVALID_VALUES","Invalid values",t)}}class eW extends Hq{constructor(t){super("ERR_INVALID_DATE","Invalid Date",t)}}class nW extends Hq{constructor(t){super("ERR_NOT_FOUND_PARTICIPANT","Participant Not Found",t)}}class rW extends Hq{constructor(t){super("ERR_NOT_FOUND_STRUCTURE","structure not found",t)}}class iW extends Hq{constructor(t){super("ERR_NOT_FOUND_MATCHUP","matchUp not found",t)}}class oW extends Hq{constructor(t){super("ERR_NOT_FOUND_EVENT","Event not found",t)}}const aW={ERR_MISSING_TOURNAMENT:zq,ERR_MISSING_TOURNAMENTS:Yq,ERR_MISSING_DRAWDEF:Kq,ERR_MISSING_EVENT_ID:Qq,ERR_MISSING_VALUE:Jq,ERR_MISSING_SANCTIONING_RECORD:Xq,ERR_MISSING_OFFICIAL_RECORD:Zq,ERR_INVALID_VALUES:tW,ERR_INVALID_DATE:eW,ERR_NOT_FOUND_PARTICIPANT:nW,ERR_NOT_FOUND_STRUCTURE:rW,ERR_NOT_FOUND_MATCHUP:iW,ERR_NOT_FOUND_EVENT:oW};function sW(t,e,n){const r=aW[t];return r?new r(n):new Hq(t,e,n)}var cW={__proto__:null,EventNotFoundError:oW,FactoryError:Hq,InvalidDateError:eW,InvalidValuesError:tW,MatchUpNotFoundError:iW,MissingDrawDefinitionError:Kq,MissingEventError:Qq,MissingOfficialRecordError:Zq,MissingSanctioningRecordError:Xq,MissingTournamentRecordError:zq,MissingTournamentRecordsError:Yq,MissingValueError:Jq,ParticipantNotFoundError:nW,StructureNotFoundError:rW,constructFactoryError:sW,getSuggestions:$q,registerSuggestions:Wq};const uW={tournament:{method:"getTournament",key:"tournamentRecord"},tournamentInfo:{method:"getTournamentInfo",key:"tournamentInfo"},tournamentTimeItem:{method:"getTournamentTimeItem",key:"timeItem"},linkedTournamentIds:{method:"getLinkedTournamentIds",key:"linkedTournamentIds"},policyDefinitions:{method:"getPolicyDefinitions",key:"policyDefinitions"},participants:{method:"getParticipants",key:"participants",fallback:[]},event:{method:"getEvent",key:"event"},events:{method:"getEvents",key:"events",fallback:[]},eventData:{method:"getEventData",key:"eventData"},eventRankingPoints:{method:"getEventRankingPoints",key:"eventRankingPoints"},flightProfile:{method:"getFlightProfile",key:"flightProfile"},drawDefinition:{method:"findDrawDefinition",key:"drawDefinition"},draftState:{method:"getDraftState",key:"draftState"},publishState:{method:"getPublishState",key:"publishState"},availablePlayoffProfiles:{method:"getAvailablePlayoffProfiles",key:"availablePlayoffProfiles",fallback:[]},validGroupSizes:{method:"getValidGroupSizes",key:"validGroupSizes",fallback:[]},assignedParticipantIds:{method:"getAssignedParticipantIds",key:"assignedParticipantIds",fallback:[]},swissChart:{method:"getSwissChart",key:"swissChart"},structureSeedAssignments:{method:"getStructureSeedAssignments",key:"seedAssignments",fallback:[]},positionAssignments:{method:"getPositionAssignments",key:"positionAssignments",fallback:[]},matchUp:{method:"findMatchUp",key:"matchUp"},matchUps:{method:"allTournamentMatchUps",key:"matchUps",fallback:[]},drawMatchUps:{method:"allDrawMatchUps",key:"matchUps",fallback:[]},eventMatchUps:{method:"allEventMatchUps",key:"matchUps",fallback:[]},competitionMatchUps:{method:"getCompetitionMatchUps",key:"matchUps",fallback:[]},matchUpsMap:{method:"getMatchUpsMap",key:"matchUpsMap"},venue:{method:"findVenue",key:"venue"},venuesAndCourts:{method:"getVenuesAndCourts",key:"venues",fallback:[]},tally:{method:"getTally",key:"tally"},extension:{method:"findExtension",key:"extension"},competitionVenues:{method:"getCompetitionVenues",key:"venues",fallback:[]},competitionParticipants:{method:"getCompetitionParticipants",key:"participants",fallback:[]}};function dW(t){return!!(t&&"object"==typeof t&&"error"in t&&t.error)}function pW(t){return String(t).replace(/~/g,"~0").replace(/\//g,"~1")}function lW(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function mW(t,e){const n=[];return fW(t,e,"",n),n}function fW(t,e,n,r){if((i=t)===(o=e)||"number"==typeof i&&"number"==typeof o&&Number.isNaN(i)&&Number.isNaN(o))return;var i,o;const a=Array.isArray(t),s=Array.isArray(e),c=lW(t),u=lW(e);a===s&&c===u?a&&s?function(t,e,n,r){const i=t.length,o=e.length,a=Math.min(i,o);for(let i=0;i<a;i++)fW(t[i],e[i],`${n}/${i}`,r);if(o>i)for(let t=i;t<o;t++)r.push({op:"add",path:`${n}/${t}`,value:e[t]});else if(i>o)for(let t=i-1;t>=o;t--)r.push({op:"remove",path:`${n}/${t}`})}(t,e,n,r):c&&u?function(t,e,n,r){for(const i of Object.keys(t))i in e||r.push({op:"remove",path:`${n}/${pW(i)}`});for(const i of Object.keys(e)){const o=`${n}/${pW(i)}`;i in t?fW(t[i],e[i],o,r):r.push({op:"add",path:o,value:e[i]})}}(t,e,n,r):r.push({op:"replace",path:n,value:e}):r.push({op:"replace",path:n,value:e})}function hW({engineType:t,methodName:e,elapsed:n,params:r,result:i}){const o=$r();if("object"!=typeof o)return;const a={method:e},s=i?.error&&(!0===o.errors||Array.isArray(o.errors)&&o.errors.includes(e)),c=Array.isArray(o.params)&&o.params?.includes(e),u=o.params&&!Array.isArray(o.params)||c,d=Array.isArray(o.exclude)&&o.exclude.includes(e);!d&&![void 0,!1].includes(o.perf)&&!isNaN(o.perf)&&n>=o.perf&&(a.elapsed=n),d||!s&&!u||(a.params=r),!d&&(s||o.result&&!Array.isArray(o.result)&&(!Array.isArray(o.params)||c)||Array.isArray(o.result)&&o.result?.includes(e))&&(a.result=i),Object.keys(a).length>1&&Ni(a,t)}const gW={setMatchUpHomeParticipantId:"SCHEDULING",calculateScheduleTimes:"SCHEDULING",addMatchUpScheduledDate:"SCHEDULING",bulkScheduleTournamentMatchUps:"SCHEDULING",toggleParticipantCheckInState:"SCHEDULING",removeMatchUpCourtAssignment:"SCHEDULING",proAutoSchedule:"SCHEDULING",bulkUpdateCourtAssignments:"SCHEDULING",allocateTeamMatchUpCourts:"SCHEDULING",scheduleMatchUps:"SCHEDULING",addSchedulingProfileRound:"SCHEDULING",proConflicts:"SCHEDULING",reorderUpcomingMatchUps:"SCHEDULING",generateVirtualCourts:"SCHEDULING",bulkRescheduleMatchUps:"SCHEDULING",clearScheduledMatchUps:"SCHEDULING",matchUpScheduleChange:"SCHEDULING",bulkScheduleMatchUps:"SCHEDULING",scheduleProfileRounds:"SCHEDULING",clearMatchUpSchedule:"SCHEDULING",addMatchUpScheduledTime:"SCHEDULING",setMatchUpDailyLimits:"SCHEDULING",assignMatchUpCourt:"SCHEDULING",assignMatchUpVenue:"SCHEDULING",generateBookings:"SCHEDULING",validateSchedulingProfile:"SCHEDULING",setSchedulingProfile:"SCHEDULING",addCourtGridBooking:"SCHEDULING",removeCourtGridBooking:"SCHEDULING",addMatchUpCourtOrder:"SCHEDULING",addMatchUpStartTime:"SCHEDULING",addMatchUpEndTime:"SCHEDULING",addMatchUpStopTime:"SCHEDULING",addMatchUpResumeTime:"SCHEDULING",addMatchUpOfficial:"SCHEDULING",addMatchUpScheduleItems:"SCHEDULING",setDrawParticipantRepresentativeIds:"DRAWS",resetVoluntaryConsolationStructure:"DRAWS",withdrawParticipantAtDrawPosition:"DRAWS",addVoluntaryConsolationStructure:"DRAWS",luckyLoserDrawPositionAssignment:"DRAWS",luckyDrawAdvancement:"DRAWS",shiftAdHocRounds:"DRAWS",setPositionAssignments:"DRAWS",swapAdHocRounds:"DRAWS",alternateDrawPositionAssignment:"DRAWS",removeDrawPositionAssignment:"DRAWS",automatedPlayoffPositioning:"DRAWS",modifySeedAssignment:"DRAWS",qualifierDrawPositionAssignment:"DRAWS",qualifierProgression:"DRAWS",setStructureOrder:"DRAWS",attachQualifyingStructure:"DRAWS",renameStructures:"DRAWS",assignDrawPositionBye:"DRAWS",addDrawDefinitionTimeItem:"DRAWS",removeStructure:"DRAWS",resetQualifyingStructure:"DRAWS",swapDrawPositionAssignments:"DRAWS",removeSeededParticipant:"DRAWS",addQualifyingStructure:"DRAWS",adHocPositionSwap:"DRAWS",addPlayoffStructures:"DRAWS",automatedPositioning:"DRAWS",modifyDrawDefinition:"DRAWS",resetDrawDefinition:"DRAWS",pruneDrawDefinition:"DRAWS",assignDrawPosition:"DRAWS",deleteAdHocMatchUps:"DRAWS",removeRoundMatchUps:"DRAWS",updateTeamLineUp:"DRAWS",addAdHocMatchUps:"DRAWS",modifyDrawName:"DRAWS",setSubOrder:"DRAWS",addLinkedConsolationStructure:"DRAWS",attachConsolationStructures:"DRAWS",attachPlayoffStructures:"DRAWS",attachStructures:"DRAWS",generateDrawTypeAndModifyDrawDefinition:"DRAWS",generateAndPopulatePlayoffStructures:"DRAWS",generateDrawMaticRound:"DRAWS",generateDrawDefinition:"DRAWS",generateQualifyingStructure:"DRAWS",generateDrawStructuresAndLinks:"DRAWS",generateAdHocMatchUps:"DRAWS",generateAdHocRounds:"DRAWS",drawMatic:"DRAWS",addFinishingRounds:"DRAWS",buildDrawHierarchy:"DRAWS",autoSeeding:"DRAWS",setMatchUpStatus:"SCORING",setMatchUpState:"SCORING",bulkMatchUpStatusUpdate:"SCORING",setDelegatedOutcome:"SCORING",removeDelegatedOutcome:"SCORING",updateTieMatchUpScore:"SCORING",resetScorecard:"SCORING",setOrderOfFinish:"SCORING",resetAdHocMatchUps:"SCORING",applyLineUps:"SCORING",resetTieFormat:"SCORING",enableTieAutoCalc:"SCORING",disableTieAutoCalc:"SCORING",resetMatchUpLineUps:"SCORING",assignMatchUpSideParticipant:"MATCHUPS",replaceTieMatchUpParticipantId:"MATCHUPS",assignTieMatchUpParticipantId:"MATCHUPS",removeTieMatchUpParticipantId:"MATCHUPS",removeMatchUpSideParticipant:"MATCHUPS",substituteParticipant:"MATCHUPS",checkOutParticipant:"MATCHUPS",checkInParticipant:"MATCHUPS",setMatchUpFormat:"MATCHUPS",createMatchUp:"SCORING",addPoint:"SCORING",resolvePointValue:"SCORING",calculatePointsTo:"SCORING",inferServeSide:"SCORING",modifyPersonRequests:"PARTICIPANTS",removePersonRequests:"PARTICIPANTS",addPersonRequests:"PARTICIPANTS",setParticipantScaleItems:"PARTICIPANTS",setParticipantScaleItem:"PARTICIPANTS",modifyIndividualParticipantIds:"PARTICIPANTS",createTeamsFromParticipantAttributes:"PARTICIPANTS",modifyParticipantsPaymentStatus:"PARTICIPANTS",modifyParticipantsSignInStatus:"PARTICIPANTS",addIndividualParticipantIds:"PARTICIPANTS",modifyParticipantOtherName:"PARTICIPANTS",regenerateParticipantNames:"PARTICIPANTS",addDynamicRatings:"PARTICIPANTS",createGroupParticipant:"PARTICIPANTS",modifyParticipantName:"PARTICIPANTS",scaledTeamAssignment:"PARTICIPANTS",removeRatings:"PARTICIPANTS",removePenalty:"PARTICIPANTS",modifyPenalty:"PARTICIPANTS",deleteParticipants:"PARTICIPANTS",mergeParticipants:"PARTICIPANTS",modifyParticipant:"PARTICIPANTS",addParticipants:"PARTICIPANTS",addPenalty:"PARTICIPANTS",addParticipant:"PARTICIPANTS",addPersons:"PARTICIPANTS",addPersonOtherId:"PARTICIPANTS",removeIndividualParticipantIds:"PARTICIPANTS",removeParticipantIdsFromAllTeams:"PARTICIPANTS",destroyPairEntries:"ENTRIES",destroyPairEntry:"ENTRIES",setEntryPosition:"ENTRIES",setEntryPositions:"ENTRIES",promoteAlternate:"ENTRIES",promoteAlternates:"ENTRIES",removeStageEntries:"ENTRIES",removeDrawEntries:"ENTRIES",modifyEntriesStatus:"ENTRIES",addEventEntryPairs:"ENTRIES",removeEventEntries:"ENTRIES",modifyEventEntries:"ENTRIES",addDrawEntries:"ENTRIES",addEventEntries:"ENTRIES",deleteFlightProfileAndFlightDraws:"EVENTS",modifyEventMatchUpFormatTiming:"EVENTS",removeEventMatchUpFormatTiming:"EVENTS",setEventDates:"EVENTS",setEventEndDate:"EVENTS",setEventStartDate:"EVENTS",deleteFlightAndFlightDraw:"EVENTS",refreshEventDrawOrder:"EVENTS",modifyPairAssignment:"EVENTS",updateDrawIdsOrder:"EVENTS",addDrawDefinition:"EVENTS",deleteDrawDefinitions:"EVENTS",assignSeedPositions:"EVENTS",attachFlightProfile:"EVENTS",removeScaleValues:"EVENTS",setEventDisplay:"EVENTS",validateCategory:"EVENTS",removeSeeding:"EVENTS",deleteEvents:"EVENTS",modifyEvent:"EVENTS",addFlight:"EVENTS",addEvent:"EVENTS",generateEventsFromTieFormat:"EVENTS",modifyCourtAvailability:"VENUES",deleteVenue:"VENUES",deleteVenues:"VENUES",addCourt:"VENUES",addCourts:"VENUES",disableCourts:"VENUES",disableVenues:"VENUES",enableCourts:"VENUES",enableVenues:"VENUES",deleteCourt:"VENUES",deleteCourts:"VENUES",modifyCourt:"VENUES",modifyVenue:"VENUES",addVenue:"VENUES",publishEventSeeding:"PUBLISHING",unPublishEventSeeding:"PUBLISHING",unPublishParticipants:"PUBLISHING",unPublishOrderOfPlay:"PUBLISHING",publishParticipants:"PUBLISHING",publishOrderOfPlay:"PUBLISHING",unPublishEvent:"PUBLISHING",publishEvent:"PUBLISHING",setTournamentStatus:"TOURNAMENT",setTournamentName:"TOURNAMENT",setTournamentNotes:"TOURNAMENT",setTournamentLocalTimeZone:"TOURNAMENT",setTournamentCategories:"TOURNAMENT",setTournamentDates:"TOURNAMENT",setTournamentEndDate:"TOURNAMENT",setTournamentStartDate:"TOURNAMENT",addTournamentExtension:"TOURNAMENT",removeTournamentExtension:"TOURNAMENT",modifyCollectionDefinition:"TIE_FORMAT",removeCollectionGroup:"TIE_FORMAT",orderCollectionDefinitions:"TIE_FORMAT",removeCollectionDefinition:"TIE_FORMAT",addCollectionGroup:"TIE_FORMAT",addCollectionDefinition:"TIE_FORMAT",modifyTieFormat:"TIE_FORMAT",aggregateTieFormats:"TIE_FORMAT",attachPolicies:"POLICY",removePolicy:"POLICY",linkTournaments:"COMPETITION",unlinkTournament:"COMPETITION",unlinkTournaments:"COMPETITION",applyTournamentRankingPoints:"RANKING"};function IW({element:t,scope:e,methodName:n,lockToken:r,now:i,label:o}){const{extension:a}=td({element:t,name:gd});if(!a?.value?.locks?.length)return;const s=a.value;let c=!1;for(let a=s.locks.length-1;a>=0;a--){const u=s.locks[a];if(u.scope===e&&(!u.methods||u.methods.includes(n))){if(!(null!==u.expiresAt&&u.expiresAt<=i))return r&&r===u.lockToken?void(c&&$u({element:t,extension:{name:gd,value:s},creationTime:!1})):(c&&$u({element:t,extension:{name:gd,value:s},creationTime:!1}),{error:Pr,info:`Locked by ${o} (scope: ${u.scope}, lockId: ${u.lockId})`});s.locks.splice(a,1),c=!0}}c&&$u({element:t,extension:{name:gd,value:s},creationTime:!1})}function SW(t,e,n,r,i){delete t.success,delete t.error;const o=Date.now(),a=yi();n&&(n.activeTournamentId=a);const s=n?.tournamentRecord||vi(a),c="object"==typeof n?.tournamentRecord&&{[n?.tournamentRecord.tournamentId]:n.tournamentRecord}||Ui(),u=n?ca(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:rt};const n=e.drawId||e.matchUp?.drawId;if(n){const{event:r,drawDefinition:i,tournamentId:o}=wg({tournamentRecords:t,drawId:n});i&&(e.drawDefinition=i),o&&(e.tournamentId=o),r&&(e.event=r)}if(e.eventId&&!e.event){const{event:n,tournamentId:r}=wg({eventId:e.eventId,tournamentRecords:t});if(!n)return{error:zt};e.tournamentId=r,e.event=n}const r=e.tournamentId??yi();if(!r&&e)return e;const i=t[r];return r&&!i?{error:rt}:i?(e.tournamentRecord=i,e):e}(c,n):void 0;if(d?.error)return d;const p=function(t,e,n){if(!e||!n)return;const r=n.extensions?.find(t=>t?.name===gd);if(!r?.value?.enabled)return;const i=gW[t];if(!i)return;const o=e.lockToken,a=(new Date).toISOString(),s=[];if(e.drawDefinition&&s.push({element:e.drawDefinition,label:`draw:${e.drawDefinition.drawId}`}),e.event&&s.push({element:e.event,label:`event:${e.event.eventId}`}),e.venueId){const t=Ig({tournamentRecord:n,venueId:e.venueId});t.venue&&s.push({element:t.venue,label:`venue:${e.venueId}`})}s.push({element:n,label:"tournament"});for(const{element:e,label:n}of s){const r=IW({element:e,scope:i,methodName:t,lockToken:o,now:a,label:n});if(r)return r}}(r,d,s);if(p)return p;const l=function({tournamentRecords:t,tournamentRecord:e,params:n,methodName:r,method:i}){if($r())return i({tournamentRecords:t,tournamentRecord:e,...n});try{return i({tournamentRecords:t,tournamentRecord:e,...n})}catch(t){return bi({engineName:"engine",methodName:r,params:n,err:t})}}({params:d,tournamentRecords:c,tournamentRecord:s,methodName:r,method:e});return hW({result:l,methodName:r,elapsed:Date.now()-o,params:u,engineType:i}),l}function yW(t,e=!0){return"object"!=typeof t||Array.isArray(t)?{error:ir}:t?.tournamentId?Pi(e?ca(t):t):{error:sr}}function vW(t,e=!0){if("object"!=typeof t)return{error:ir};if(wi(),Array.isArray(t)){if(!(t.filter(t=>t?.tournamentId).length===t.length))return{error:et};t=Object.assign({},...t.map(t=>({[t.tournamentId]:t})))}else if(t?.tournamentId)wi((t={[t.tournamentId]:t}).tournamentId);else{if(!Object.keys(t).every(e=>t[e].tournamentId===e))return{error:et}}return Ti(e?ca(t):t)}function UW(t,e){if(!Array.isArray(e))return{wouldSucceed:!1,results:[],patch:[],willEmitNotices:[],error:{...sr,message:"directives must be an array"},rolledBack:!0};const n=pi(),r=ca(Ui(),!1,!0),i=[];let o;for(const r of e){if("object"!=typeof r){o={...sr,message:"directive must be an object"};break}if(r.params&&"object"!=typeof r.params){o={...sr,message:"params must be an object"};break}const{method:e,pipe:a}=r,s=r.params?{...r.params}:{};if(!n[e]){o={...sr,message:`method '${e}' not found`};break}if(a){const t=i.at(-1),e=Object.keys(a);for(const n of e)t?.[n]&&(s[n]=t[n])}const c=SW(t,n[e],s,e,"sync");if(i.push({...c,methodName:e}),c?.error){o=c.error;break}}const a=mW(r,ca(Ui(),!1,!0)),s=[],{topics:c}=gi();for(const t of c){const e=li({topic:t});e?.length&&s.push({topic:t,payloads:e})}return hi(),vW(r),{wouldSucceed:!o,results:i,patch:a,willEmitNotices:s,...o?{error:o}:{},rolledBack:!0}}function PW(t,e,n){const r=UW(t,[{method:e,params:n}]);return{wouldSucceed:r.wouldSucceed,...r.error?{reason:r.error}:{},willEmitTopics:r.willEmitNotices.map(t=>t.topic),touchesPaths:r.patch.map(t=>t.path),detail:r}}function TW(t){const e={tournaments:0,events:0,drawDefinitions:0,structures:0,matchUps:0,participants:0,venues:0,courts:0};for(const n of Object.values(t??{})){e.tournaments+=1,e.events+=n?.events?.length??0,e.venues+=n?.venues?.length??0,e.participants+=n?.participants?.length??0;for(const t of n?.events??[]){e.drawDefinitions+=t?.drawDefinitions?.length??0;for(const n of t?.drawDefinitions??[]){e.structures+=n?.structures?.length??0;for(const t of n?.structures??[])e.matchUps+=t?.matchUps?.length??0}}for(const t of n?.venues??[])e.courts+=t?.courts?.length??0}return e}function wW(){const t=new Map;function e(e){let n=t.get(e);return n||(n=new Set,t.set(e,n),ai({subscriptions:{[e]:t=>{!function(t,e,n){for(const r of n)for(const n of e)try{n(r)}catch(e){console.error(`[engine.on] handler error on topic "${t}":`,e)}}(e,Array.from(n),t)}}}),n)}function n(e){const n=t.get(e);!n||n.size>0||(t.delete(e),ai({subscriptions:{[e]:null}}))}function r(t,r){const i=e(t);i.add(r);let o=!0;return()=>{o&&(o=!1,i.delete(r),n(t))}}return{on:r,once:function(t,e){const n=r(t,t=>{n(),e(t)});return n},off:function(e,r){const i=t.get(e);i&&(r?i.delete(r):i.clear(),n(e))},waitFor:function(t,e){return new Promise(n=>{const i=r(t,t=>{e&&!e(t)||(i(),n(t))})})}}}class DW{constructor(t,e){this.eventState={},this.engine=t,this._eventId=pa(),e&&Object.assign(this.eventState,e)}singles(){return this.eventState.eventType=ts,this}doubles(){return this.eventState.eventType=ns,this}team(t){return this.eventState.eventType=is,"string"==typeof t?this.eventState.tieFormatName=t:t&&(this.eventState.tieFormat=t),this}hybrid(){return this.eventState.eventType=as,this}named(t){return this.eventState.eventName=t,this}gender(t){return this.eventState.gender=t,this}category(t){return this.eventState.category=t,this}dates(t,e){return this.eventState.startDate=t,this.eventState.endDate=e,this}tieFormat(t){return"string"==typeof t?this.eventState.tieFormatName=t:this.eventState.tieFormat=t,this}entries(t,e){return this.entriesSpec={participantIds:t,opts:e},this}draw(t,e={}){if(this.drawSpec)throw new Error("EventBuilder.draw() can be called once per event in v1. Multi-flight builders are a v2 addition.");return this.drawSpec={drawId:pa(),drawSize:t,opts:e},this}get eventId(){return this._eventId}get drawIds(){return this.drawSpec?[this.drawSpec.drawId]:[]}toDirectives(){const t=[],e={eventId:this._eventId,...this.eventState};if(t.push({method:"addEvent",params:{event:e}}),this.drawSpec){const{drawId:e,drawSize:n,opts:r}=this.drawSpec;t.push({method:"generateDrawDefinition",params:{eventId:this._eventId,drawId:e,drawSize:n,...r},pipe:{event:!0}}),t.push({method:"addDrawDefinition",params:{eventId:this._eventId},pipe:{drawDefinition:!0}})}if(this.entriesSpec){const{participantIds:e,opts:n}=this.entriesSpec,r={eventId:this._eventId,participantIds:e,entryStage:n?.entryStage??us,entryStatus:n?.entryStatus??rf};void 0!==n?.enforceGender&&(r.enforceGender=n.enforceGender),void 0!==n?.enforceCategory&&(r.enforceCategory=n.enforceCategory),t.push({method:"addEventEntries",params:r})}return t}toRequest(){return{directives:this.toDirectives(),eventId:this._eventId,drawIds:this.drawIds}}create(t){const e=this.toDirectives(),n=this.engine.executionQueue(e,t?.rollbackOnError);return n?.error?{success:!1,error:n.error,eventId:this._eventId,drawIds:this.drawIds,directives:e,results:n.results}:{success:!!n?.success,eventId:this._eventId,drawIds:this.drawIds,directives:e,results:n?.results}}}class RW{constructor(t){this.participantRole=sy,this.engine=t,this._participantId=pa()}individual(t){return this.shape={kind:"individual",person:t},this}pair(t,e){return this.shape={kind:"pair",ids:t,name:e},this}team(t,e){return this.shape={kind:"team",name:t,ids:e},this}role(t){return this.participantRole=t,this}get participantId(){return this._participantId}buildParticipant(){if(!this.shape)throw new Error("ParticipantBuilder requires .individual()/.pair()/.team() before terminating.");if("individual"===this.shape.kind){const{givenName:t,familyName:e,sex:n,nationalityCode:r,personId:i}=this.shape.person;return{participantId:this._participantId,participantType:gm,participantRole:this.participantRole,person:{personId:i??pa(),standardGivenName:t,standardFamilyName:e,sex:n,nationalityCode:r}}}return"pair"===this.shape.kind?{participantId:this._participantId,participantType:Sm,participantRole:this.participantRole,individualParticipantIds:this.shape.ids,participantName:this.shape.name}:{participantId:this._participantId,participantType:ym,participantRole:this.participantRole,individualParticipantIds:this.shape.ids??[],participantName:this.shape.name}}toDirectives(){return[{method:"addParticipant",params:{participant:this.buildParticipant()}}]}toRequest(){return{directives:this.toDirectives(),participantId:this._participantId}}create(t){const e=this.toDirectives(),n=this.engine.executionQueue(e,t?.rollbackOnError);return n?.error?{success:!1,error:n.error,participantId:this._participantId,directives:e,results:n.results}:{success:!!n?.success,participantId:this._participantId,directives:e,results:n?.results}}}const{FACTORY:bW}=Nd;function NW({timeStamp:t}){const e=Ui(),n=ui();return n&&Object.values(e).forEach(e=>{!function({tournamentRecord:t,value:e}){const n=dp({element:t,attribute:"factory",name:bW});sp({element:t,attribute:"factory",name:bW,value:{...n,...e}})}({tournamentRecord:e,value:{version:"5.2.4",timeStamp:t}})}),n}function MW({methodName:t,params:e,start:n}){const r={error:Ur,methodName:t};return hW({result:r,methodName:t,elapsed:n?Date.now()-n:0,params:e,engineType:"sync"}),r}function AW(t){const{mutationStatus:e,tournamentId:n,directives:r,timeStamp:i}=t??{},{topics:o}=gi();for(const t of[...o].sort(OW)){const e=li({topic:t});e?.length&&Si({topic:t,payloads:e,notices:e})}if(e&&i&&o.includes(Cl)){const t=[{tournamentId:n,directives:r,timeStamp:i}];Si({payloads:t,notices:t,topic:Cl})}}async function EW(t){const{mutationStatus:e,tournamentId:n,directives:r,timeStamp:i}=t??{},{topics:o}=gi();for(const t of[...o].sort(OW)){const e=li({topic:t});e&&await Si({topic:t,payloads:e,notices:e})}if(e&&i&&o.includes(Cl)){const t=[{tournamentId:n,directives:r,timeStamp:i}];Si({payloads:t,notices:t,topic:Cl})}}const CW={[Ll]:5,[_l]:5,[Bl]:5,[Ml]:5,[Nl]:5,[Tl]:5,[wl]:5,[Dl]:5,[Gl]:1,[Rl]:1,[jl]:1,[bl]:5,[El]:5,[Pl]:4,[yl]:4,[vl]:4,[Ul]:4,[ll]:3,[pl]:2};function OW(t,e){return(CW[e]||0)-(CW[t]||0)}async function kW(t,e){if(!f(e))return{error:sr,message:"args must be an object"};const n=Object.values(e).filter(l).length;if(n>1)return{message:"there must be only one arg with typeof function",error:sr};const r=n?Object.keys(e).find(t=>l(e[t])):m(e.method)&&e.method;if(!r)return{error:Ur};const{[r]:i,...o}=e,a=e?.params?{...e.params}:{...o},s=a.rollbackOnError&&ca(Ui(),!1,!0),c=i||t[r]||Fr()[r];if(!c)return MW({methodName:r,params:a});const u=await SW(t,c,a,r,"async")??{};u?.error&&s&&vW(s);const d=Date.now(),p=NW({timeStamp:d}),h=u?.success&&!0!==a?.delayNotify&&!0!==a?.doNotNotify;return h&&await EW({directives:[{method:c,params:a}],mutationStatus:p,timeStamp:d}),(h||!u?.success||a?.doNotNotify)&&hi(),u}function FW(t,e){return e?.error?(t.error=e.error,t.success=!1):(t.error=void 0,t.success=!0),t}function xW(t,e){t.importMethods=(n,r,i,o)=>function(t,e,n,r,i,o){const a=Mi(n,r,i,o);if(a.error)return a;const s=a.methods??[];return Object.keys(s).filter(t=>l(s[t])).forEach(n=>{t[n]=r=>{const i=()=>e(t,{[n]:s[n],...r});if($r())return i();try{return i()}catch(t){bi({engineName:"engine",methodName:n,params:r,err:t})}}}),{...Y,...t}}(t,e,n,r,i,o),t.getTournament=t=>function(t){const{convertExtensions:e=!1,removeExtensions:n=!1}=t??{},r=t?.tournamentId??yi();return"string"!=typeof r?{}:{tournamentRecord:ca(vi(r),e,!1,n)}}(t),t.getState=t=>function({convertExtensions:t,removeExtensions:e}){const n=Ui();return{tournamentId:yi(),tournamentRecords:ca(n,t,!1,e)}}({convertExtensions:t?.convertExtensions,removeExtensions:t?.removeExtensions}),t.version=()=>"5.2.4",t.reset=()=>(Ti({}),FW(t)),t.devContext=e=>(zr(e),FW(t)),t.getDevContext=t=>$r(t),t.schemaWriteMode=e=>{const n=Yr(e);return FW(t,n)},t.getSchemaWriteMode=()=>Kr(),t.saveDrawDeletions=e=>{const n=Xr(e);return FW(t,n)},t.getSaveDrawDeletions=()=>Zr(),t.auditAuthorityServer=e=>{const n=ti(e);return FW(t,n)},t.getAuditAuthorityServer=()=>ei(),t.newTournamentRecord=(t={})=>{const e=qF(t),n=e.tournamentId;return e.error?e:(yW(e),wi(n),{...Y,tournamentId:n})},t.setState=(e,n,r)=>{ii(n,r);const i=vW(e,n);return FW(t,i)},t.setTournamentId=t=>wi(t),t.getTournamentId=()=>yi(),t.setTournamentRecord=(e,n,r)=>{ii(n,r);const i=yW(e,n);return FW(t,i)},t.removeTournamentRecord=e=>{const n=Di(e);return FW(t,n)},t.removeUnlinkedTournamentRecords=()=>{const e=function(){const t=Ui(),e=new Set;for(const n of Object.values(t))for(const t of Ad(n))e.add(t);return Object.keys(t).forEach(n=>{e.has(n)||delete t[n]}),Ti(t)}();return FW(t,e)},t.q=function(t){const e={};for(const[n,r]of Object.entries(uW))e[n]=e=>{const n=t?.[r.method];if("function"!=typeof n)return r.fallback;const i=n(e);if(!i||void 0!==i.error)return r.fallback;const o=i[r.key];return void 0!==o?o:r.fallback};return e}(t),t.inspect=()=>function(){const t=Ui()??{},e=Object.keys(t),n=yi()||void 0,r=gi(),i=Array.isArray(r?.topics)?r.topics:[];return{version:"5.2.4",schemaWriteMode:Kr(),saveDrawDeletions:Zr(),auditAuthorityServer:ei(),loaded:{tournamentIds:e,currentTournamentId:n,counts:TW(t)},subscriptions:{topics:i},devContext:$r()}}(),t.dryRun=e=>UW(t,e),t.explain=(e,n)=>PW(t,e,n);const n=wW();t.on=n.on,t.once=n.once,t.off=n.off,t.waitFor=n.waitFor,t.build=function(t){return{event:e=>new DW(t,e),participant:()=>new RW(t)}}(t)}function _W(t){const e=Wr();if(e.error&&!t)return e;const n={executionQueue:(t,e)=>async function(t,e,n){if(!Array.isArray(e))return{error:sr,message:"directives must be an array"};const r=pi(),i=Date.now(),o=n&&ca(Ui(),!1,!0),a=[];for(const n of e){if("object"!=typeof n)return{error:sr,message:"directive must be an object"};const{method:e,pipe:s}=n,c=n.params?{...n.params}:{};if(!r[e])return MW({methodName:e,start:i,params:c});if(s){const t=a.at(-1),e=Object.keys(s);for(const n of e)t[n]&&(c[n]=t[n])}const u=SW(t,r[e],c,e,"async");if(u?.error)return o&&vW(o),{...u,rolledBack:!!o};a.push({...u,methodName:e})}const s=Date.now(),c=NW({timeStamp:s});return await EW({directives:e,mutationStatus:c,timeStamp:s}),hi(),{success:a.every(t=>t.success),results:a}}(n,t,e),execute:t=>kW(n,t)};return xW(n,kW),n}function LW(t,e){if(!f(e))return{error:sr,message:"args must be an object"};const n=Object.values(e).filter(l).length;if(n>1)return{message:"there must be only one arg with typeof function",error:sr};const r=n?Object.keys(e).find(t=>l(e[t])):m(e.method)&&e.method;if(!r)return{error:Ur};const{[r]:i,...o}=e,a=e?.params?{...e.params}:{...o},s=a.rollbackOnError&&ca(Ui(),!1,!0),c=i||t[r]||Fr()[r];if(!c)return MW({methodName:r,params:a});const u=SW(t,c,a,r,"sync")??{};u?.error&&s&&vW(s);const d=Date.now(),p=NW({timeStamp:d}),h=u?.success&&!0!==a?.delayNotify&&!0!==a?.doNotNotify;return h&&AW({directives:[{method:c,params:a}],mutationStatus:p,timeStamp:d}),(h||!u?.success||a?.doNotNotify)&&hi(),u}const BW=(()=>{const t={executionQueue:(e,n)=>function(t,e,n){if(!Array.isArray(e))return{error:sr,message:"directives must be an array"};const r=pi(),i=Date.now(),o=n&&ca(Ui(),!1,!0),a=[];for(const n of e){if("object"!=typeof n)return{error:sr,message:"directive must be an object"};if(n.params&&"object"!=typeof n.params)return{error:sr,message:"params must be an object"};const{method:e,pipe:s}=n,c=n.params?{...n.params}:{};if(!r[e])return MW({methodName:e,start:i,params:c});if(s){const t=a.at(-1),e=Object.keys(s);for(const n of e)t[n]&&(c[n]=t[n])}const u=SW(t,r[e],c,e,"sync");if(u?.error)return o&&vW(o),{...u,rolledBack:!!o};a.push({...u,methodName:e})}const s=Date.now();return AW({directives:e,mutationStatus:NW({timeStamp:s}),timeStamp:s}),hi(),{success:a.every(t=>t.success),results:a}}(t,e,n),execute:e=>LW(t,e)};return xW(t,LW),t})();function VW(t,e){if(!f(e))return{error:sr,message:"args must be an object"};const n=Object.values(e).filter(l).length;if(n>1)return{message:"there must be only one arg with typeof function",error:sr};const r=n?Object.keys(e).find(t=>l(e[t])):m(e.method)&&e.method;if(!r)return{error:Ur};const{[r]:i,...o}=e,a=e?.params?{...e.params}:{...o},s=i||t[r]||Fr()[r];return s?SW(t,s,a,r,"ask"):MW({methodName:r,params:a})}const GW=(()=>{const t={execute:e=>VW(t,e)};return xW(t,VW),t})();let jW,qW={};function WW(t,e=!0){if(!t)return{error:Ae};if("object"!=typeof t)return{error:ir};if(t.matchUpId)jW=t.matchUpId,qW[jW]=e?ca(t):t;else{!function(t,e){for(const n of t)n.matchUpId&&(qW[n.matchUpId]=e?ca(n):n,jW||(jW=n.matchUpId))}(Array.isArray(t)?[...t].reverse():Object.values(t),e)}return e?ca(t):t}const $W=(()=>{const t={getState:t=>function(t){return ca(qW[jW],t?.convertExtensions,!1,t?.removeExtensions)}(t),version:()=>"5.2.4",reset:()=>(jW=void 0,qW={},{...Y}),drawId:void 0,error:void 0,success:!1,devContext:e=>(zr(e),t),setState:(e,n,r)=>{ii(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}(WW(e))}};return function(t,e){e.forEach(e=>{Object.keys(e).forEach(n=>{t[n]=r=>{if($r())return HW(t,{params:r,governor:e,methodName:n});try{return HW(t,{params:r,governor:e,methodName:n})}catch(t){bi({engineName:"matchUpEngine",methodName:n,params:r,err:t})}}})})}(t,[CN]),t})();function HW(t,{params:e,governor:n,methodName:r}){t.error=void 0,t.success=!1;const i=e?.matchUp||qW[jW],o=e?.matchUps||Object.values(qW),a=e?.rollbackOnError&&ca(i,!1,!0);e={...e,matchUpId:i?.matchUpId,matchUps:o,matchUp:i};const s=n[r](e);if(s?.error)return a&&WW(a),{...s,rolledBack:!!a};const c=s?.success&&!0!==e?.delayNotify&&!0!==e?.doNotNotify;return c&&AW(),(c||!s?.success||e?.doNotNotify)&&hi(),s}function zW(t){let e=Math.trunc(t);return()=>{e=Math.trunc(e+1831565813);let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}let YW=!1;const KW=(()=>{const t={version:()=>"5.2.4",setDeepCopy:(e,n)=>(ii(e,n),t),devContext:e=>(zr(e),YW=!0,t)};return function(n){n.forEach(n=>{Object.keys(n).forEach(r=>{t[r]=function(t,n){return r=>{if("number"==typeof r?.nonRandom&&(r={...r,random:zW(r.nonRandom)}),$r()){const i=e(t[n],r);return!i?.error&&r?.setState&&i?.tournamentRecord&&vW(i.tournamentRecord),i}try{const i=e(t[n],r);return!i?.error&&r?.setState&&i?.tournamentRecord&&vW(i.tournamentRecord),i}catch(t){let e;"string"==typeof t?e=t.toUpperCase():t instanceof Error&&(e=t.message),console.log("ERROR",{params:JSON.stringify(r),method:n,error:e})}}}(n,r)})})}([t_]),t;function e(t,e){const n=t({...e});return n?.error||AW(),hi(),YW&&(zr(!1),YW=!1),n}})();class QW{constructor(){this.tournamentRecord=null,this.blocksById=new Map,this.blocksByCourtDay=new Map,this.courtDayAvailability=new Map,this.venueDayAvailability=new Map,this.templates=new Map,this.rules=new Map,this.plans=new Map,this.subscribers=[],this.resolvedGranularity=15,this.nextBlockId=1}init(t,e){this.tournamentRecord=t,this.config={tournamentId:e?.tournamentId||t?.tournamentId||"tournament-1",dayStartTime:e?.dayStartTime||"06:00",dayEndTime:e?.dayEndTime||"23:00",slotMinutes:e?.slotMinutes||15,granularityMinutes:e?.granularityMinutes,typePrecedence:e?.typePrecedence||[DV.HARD_BLOCK,DV.LOCKED,DV.SCHEDULED,DV.MAINTENANCE,DV.CLOSED,DV.BLOCKED,DV.PRACTICE,DV.RESERVED,DV.SOFT_BLOCK,DV.AVAILABLE,DV.UNSPECIFIED],conflictEvaluators:e?.conflictEvaluators??[]},this.resolvedGranularity=this.config.granularityMinutes??this.config.slotMinutes??15,this.plans.clear(),this.loadBlocksFromTournamentRecord(),this.emit({type:"STATE_CHANGED",payload:{reason:"INIT"}})}updateTournamentRecord(t){this.tournamentRecord=t,this.loadBlocksFromTournamentRecord(),this.emit({type:"STATE_CHANGED",payload:{reason:"TOURNAMENT_RECORD_UPDATED"}})}getConfig(){return{...this.config}}getResolvedGranularityMinutes(){return this.resolvedGranularity}getCourtAvailability(t,e){const n=bV(t),r=this.courtDayAvailability.get(`${n}|${e}`)??this.courtDayAvailability.get(`${n}|DEFAULT`)??null,i=NV(t.tournamentId,t.venueId),o=this.venueDayAvailability.get(`${i}|${e}`)??this.venueDayAvailability.get(`${i}|DEFAULT`)??null;if(r&&o){const t=r.startTime>o.startTime?r.startTime:o.startTime,e=r.endTime<o.endTime?r.endTime:o.endTime;return t>=e?o:{startTime:t,endTime:e}}if(r)return r;if(o)return o;const a=this.courtDayAvailability.get("GLOBAL|DEFAULT");return a||{startTime:this.config.dayStartTime,endTime:this.config.dayEndTime}}setCourtAvailability(t,e,n){const r=bV(t);this.courtDayAvailability.set(`${r}|${e}`,n),this.emit({type:"AVAILABILITY_CHANGED",payload:{court:t,day:e,avail:n}})}setCourtAvailabilityAllDays(t,e){const n=bV(t);this.courtDayAvailability.set(`${n}|DEFAULT`,e),this.emit({type:"AVAILABILITY_CHANGED",payload:{court:t,scope:"all-days",avail:e}})}setAllCourtsDefaultAvailability(t){this.courtDayAvailability.set("GLOBAL|DEFAULT",t),this.emit({type:"AVAILABILITY_CHANGED",payload:{scope:"global",avail:t}})}clearCourtAvailabilityForVenue(t,e){const n=`${t}|${e}|`;for(const t of this.courtDayAvailability.keys())t.startsWith(n)&&this.courtDayAvailability.delete(t);this.emit({type:"AVAILABILITY_CHANGED",payload:{tournamentId:t,venueId:e,scope:"clear-venue-courts"}})}getCourtAvailabilityKeys(t){const e=`${bV(t)}|`,n=[];for(const t of this.courtDayAvailability.keys())t.startsWith(e)&&n.push(t.slice(e.length));return n}getVenueAvailability(t,e,n){const r=NV(t,e);if(n){const t=this.venueDayAvailability.get(`${r}|${n}`);if(t)return t}return this.venueDayAvailability.get(`${r}|DEFAULT`)??null}setVenueDefaultAvailability(t,e,n){const r=NV(t,e);this.venueDayAvailability.set(`${r}|DEFAULT`,n),this.emit({type:"AVAILABILITY_CHANGED",payload:{tournamentId:t,venueId:e,scope:"venue",avail:n}})}setVenueDayAvailability(t,e,n,r){const i=NV(t,e);this.venueDayAvailability.set(`${i}|${n}`,r),this.emit({type:"AVAILABILITY_CHANGED",payload:{tournamentId:t,venueId:e,day:n,scope:"venue-day",avail:r}})}getVisibleTimeRange(t,e){const n=e&&e.length>0?e:this.getAllCourtsFromTournamentRecord();let r="23:59",i="00:00";for(const e of n){const n=this.getCourtAvailability(e,t);n.startTime<r&&(r=n.startTime),n.endTime>i&&(i=n.endTime)}return 0===n.length?{startTime:this.config.dayStartTime,endTime:this.config.dayEndTime}:{startTime:r,endTime:i}}getTournamentDays(){if(!this.tournamentRecord?.startDate)return[];const t=this.tournamentRecord.startDate,e=this.tournamentRecord.endDate||t,n=[],r=new Date(t+"T00:00:00"),i=new Date(e+"T00:00:00");for(;r<=i;){const t=r.getFullYear(),e=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");n.push(`${t}-${e}-${i}`),r.setDate(r.getDate()+1)}return n}getActiveDays(){const t=this.tournamentRecord?.activeDates;return Array.isArray(t)&&t.length>0?t.map(t=>"string"==typeof t?t:Lo(t.toISOString())).sort():this.getTournamentDays()}getDayTimeline(t){const e=this.getAllCourtsFromTournamentRecord(),n=new Map;for(const t of e){const e=n.get(t.venueId)??[];e.push(t),n.set(t.venueId,e)}const r=[];for(const[e,i]of n.entries()){const n=[];for(const e of i){const r=this.getCourtRail(t,e);r&&n.push(r)}r.push({day:t,venueId:e,rails:n})}return r}getVenueTimeline(t,e){return this.getDayTimeline(t).find(t=>t.venueId===e)||null}getCourtRail(t,e){const n=this.getCourtAvailability(e,t),r={start:`${t}T${n.startTime}:00`,end:`${t}T${n.endTime}:00`},i=RV(e,t);return{court:e,segments:BV((this.blocksByCourtDay.get(i)??[]).map(t=>this.blocksById.get(t)).filter(t=>!!t),r,this.config)}}getCourtSchedulingSummary(t){let e=0,n=0,r=0;for(const i of this.getTournamentDays()){const o=this.getCourtRail(i,t);if(o)for(const t of o.segments){const i=new Date(t.start).getTime(),o=(new Date(t.end).getTime()-i)/6e4;t.status===DV.SCHEDULED||t.status===DV.LOCKED?e+=o:t.status===DV.AVAILABLE?n+=o:r+=o}}return{scheduledMinutes:e,availableMinutes:n,blockedMinutes:r}}getCapacityCurve(t){return WV(t,this.getDayTimeline(t))}getDayBlocks(t){const e=[];for(const n of this.blocksById.values()){GV(n.start)===t&&e.push(n)}return e}getAllBlocks(){return Array.from(this.blocksById.values())}getTemplates(){return Array.from(this.templates.values())}getTemplate(t){return this.templates.get(t)||null}getRules(){return Array.from(this.rules.values())}getRule(t){return this.rules.get(t)||null}addPlanItem(t){const e=PG(t),n={...t,planItemId:e},r=this.plans.get(t.day)||{day:t.day,items:[]};return r.items=r.items.filter(t=>t.planItemId!==e),r.items.push(n),this.plans.set(t.day,r),this.emit({type:"PLAN_CHANGED",payload:{action:"ADD",planItem:n}}),this.emit({type:"STATE_CHANGED",payload:{reason:"PLAN_CHANGED"}}),n}removePlanItem(t){for(const[e,n]of this.plans.entries()){const r=n.items.findIndex(e=>e.planItemId===t);if(-1!==r){const t=n.items.splice(r,1)[0];return 0===n.items.length&&this.plans.delete(e),this.emit({type:"PLAN_CHANGED",payload:{action:"REMOVE",planItem:t}}),this.emit({type:"STATE_CHANGED",payload:{reason:"PLAN_CHANGED"}}),!0}}return!1}updatePlanItem(t,e){for(const n of this.plans.values()){const r=n.items.find(e=>e.planItemId===t);if(r)return Object.assign(r,e),this.emit({type:"PLAN_CHANGED",payload:{action:"UPDATE",planItem:r}}),this.emit({type:"STATE_CHANGED",payload:{reason:"PLAN_CHANGED"}}),r}return null}movePlanItem(t,e){let n=null;for(const[e,r]of this.plans.entries()){const i=r.items.findIndex(e=>e.planItemId===t);if(-1!==i){n=r.items.splice(i,1)[0],0===r.items.length&&this.plans.delete(e);break}}if(!n)return null;const r={...n,day:e};r.planItemId=PG(r);const i=this.plans.get(e)||{day:e,items:[]};return i.items=i.items.filter(t=>t.planItemId!==r.planItemId),i.items.push(r),this.plans.set(e,i),this.emit({type:"PLAN_CHANGED",payload:{action:"MOVE",planItem:r,fromDay:n.day}}),this.emit({type:"STATE_CHANGED",payload:{reason:"PLAN_CHANGED"}}),r}getDayPlan(t){return this.plans.get(t)||null}getAllPlans(){return Array.from(this.plans.values())}applyBlock(t){const e=[];for(const n of t.courts){const r=GV(t.timeRange.start),i=this.clampToAvailability(n,r,t.timeRange.start,t.timeRange.end);if(!i)continue;const o={id:this.generateBlockId(),court:n,start:i.start,end:i.end,type:t.type,reason:t.reason,hardSoft:t.hardSoft,source:t.source||"USER"};e.push({kind:"ADD_BLOCK",block:o})}return this.applyMutations(e)}moveBlock(t){const e=this.blocksById.get(t.blockId);if(!e)return{applied:[],rejected:[],warnings:[{code:"BLOCK_NOT_FOUND",message:`Block ${t.blockId} not found`}],conflicts:[]};const n=t.newCourt||e.court,r=GV(t.newTimeRange.start),i=this.clampToAvailability(n,r,t.newTimeRange.start,t.newTimeRange.end);if(!i)return{applied:[],rejected:[],warnings:[{code:"OUTSIDE_AVAILABILITY",message:"Block falls outside court availability"}],conflicts:[]};const o={...e,start:i.start,end:i.end,court:n};return this.applyMutations([{kind:"UPDATE_BLOCK",block:o,previousBlock:e}])}resizeBlock(t){const e=this.blocksById.get(t.blockId);if(!e)return{applied:[],rejected:[],warnings:[{code:"BLOCK_NOT_FOUND",message:`Block ${t.blockId} not found`}],conflicts:[]};const n=GV(t.newTimeRange.start),r=this.clampToAvailability(e.court,n,t.newTimeRange.start,t.newTimeRange.end);if(!r)return{applied:[],rejected:[],warnings:[{code:"OUTSIDE_AVAILABILITY",message:"Block falls outside court availability"}],conflicts:[]};const i={...e,start:r.start,end:r.end};return this.applyMutations([{kind:"UPDATE_BLOCK",block:i,previousBlock:e}])}removeBlock(t){const e=this.blocksById.get(t);return e?this.applyMutations([{kind:"REMOVE_BLOCK",block:e}]):{applied:[],rejected:[],warnings:[{code:"BLOCK_NOT_FOUND",message:`Block ${t} not found`}],conflicts:[]}}applyTemplate(t){return this.templates.get(t.templateId)?{applied:[],rejected:[],warnings:[],conflicts:[]}:{applied:[],rejected:[],warnings:[{code:"TEMPLATE_NOT_FOUND",message:`Template ${t.templateId} not found`}],conflicts:[]}}importScheduledMatchUps(t){const e=[];for(const t of this.blocksById.values())t.type===DV.SCHEDULED&&"SYSTEM"===t.source&&e.push({kind:"REMOVE_BLOCK",block:t});for(const t of e)this.applyMutation(t);const n=[];for(const e of t){const t=5===e.startTime.length?`${e.startTime}:00`:e.startTime,r=this.timeToMinutes(t)+e.durationMinutes,i=Math.floor(r/60),o=r%60,a=`${String(i).padStart(2,"0")}:${String(o).padStart(2,"0")}:00`,s={id:this.generateBlockId(),court:{tournamentId:this.config.tournamentId,venueId:e.venueId,courtId:e.courtId},start:`${e.date}T${t}`,end:`${e.date}T${a}`,type:DV.SCHEDULED,source:"SYSTEM",matchUpId:e.matchUpId,reason:"Scheduled Match"};n.push({kind:"ADD_BLOCK",block:s})}const r=this.applyMutations(n);return{...r,applied:[...e,...r.applied]}}timeToMinutes(t){const e=t.split(":").map(Number);return 60*e[0]+e[1]}simulateBlocks(t,e){const n=this.createSnapshot(),r=n.applyMutations(t),i=e||this.getFirstAvailableDay();return{previewRails:i?n.getDayTimeline(i):[],capacityImpact:i?n.getCapacityCurve(i):void 0,conflicts:r.conflicts}}subscribe(t){return this.subscribers.push(t),()=>{const e=this.subscribers.indexOf(t);e>-1&&this.subscribers.splice(e,1)}}emit(t){for(const e of this.subscribers)try{e(t)}catch(t){console.error("Error in event listener:",t)}}applyMutations(t){const e=this.evaluateConflicts(t);if(e.filter(t=>"ERROR"===t.severity).length>0)return{applied:[],rejected:t,warnings:[],conflicts:e};const n=[];for(const e of t)this.applyMutation(e),n.push(e);return this.emit({type:"BLOCKS_CHANGED",payload:{mutations:n}}),this.emit({type:"STATE_CHANGED",payload:{reason:"BLOCKS_MUTATED"}}),e.length>0&&this.emit({type:"CONFLICTS_CHANGED",payload:{conflicts:e}}),{applied:n,rejected:[],warnings:e.filter(t=>"WARN"===t.severity).map(t=>({code:t.code,message:t.message})),conflicts:e}}applyMutation(t){const{kind:e,block:n,previousBlock:r}=t;switch(e){case"ADD_BLOCK":this.blocksById.set(n.id,n),this.indexBlock(n);break;case"UPDATE_BLOCK":r&&this.unindexBlock(r),this.blocksById.set(n.id,n),this.indexBlock(n);break;case"REMOVE_BLOCK":this.unindexBlock(n),this.blocksById.delete(n.id)}}indexBlock(t){const e=GV(t.start),n=RV(t.court,e),r=this.blocksByCourtDay.get(n)??[];r.includes(t.id)||(r.push(t.id),this.blocksByCourtDay.set(n,r))}unindexBlock(t){const e=GV(t.start),n=RV(t.court,e),r=(this.blocksByCourtDay.get(n)??[]).filter(e=>e!==t.id);r.length>0?this.blocksByCourtDay.set(n,r):this.blocksByCourtDay.delete(n)}evaluateConflicts(t){const e=this.createContext(),n=[];for(const r of this.config.conflictEvaluators??[])try{const i=r.evaluate(e,t);n.push(...i)}catch(t){console.error(`Error in evaluator ${r.id}:`,t)}return n}createContext(){return{config:this.config,tournamentRecord:this.tournamentRecord,blocksById:new Map(this.blocksById),blocksByCourtDay:new Map(this.blocksByCourtDay),templates:new Map(this.templates),rules:new Map(this.rules)}}createSnapshot(){const t=new QW;return t.config={...this.config},t.tournamentRecord=this.tournamentRecord,t.blocksById=new Map(this.blocksById),t.blocksByCourtDay=new Map(this.blocksByCourtDay),t.courtDayAvailability=new Map(this.courtDayAvailability),t.venueDayAvailability=new Map(this.venueDayAvailability),t.templates=new Map(this.templates),t.rules=new Map(this.rules),t.plans=new Map([...this.plans.entries()].map(([t,e])=>[t,{...e,items:[...e.items]}])),t.nextBlockId=this.nextBlockId,t.resolvedGranularity=this.resolvedGranularity,t}loadBlocksFromTournamentRecord(){if(this.blocksById.clear(),this.blocksByCourtDay.clear(),this.courtDayAvailability.clear(),this.venueDayAvailability.clear(),this.tournamentRecord?.venues)for(const t of this.tournamentRecord.venues){const e=AV(t),n=NV(this.config.tournamentId,e);this.loadVenueAvailability(t,e,n),this.loadCourtAvailability(t,e)}}loadVenueAvailability(t,e,n){if(t.defaultStartTime&&t.defaultEndTime&&this.venueDayAvailability.set(`${n}|DEFAULT`,{startTime:t.defaultStartTime,endTime:t.defaultEndTime}),t.dateAvailability?.length)for(const r of t.dateAvailability)if(r.date?r.startTime&&r.endTime&&this.venueDayAvailability.set(`${n}|${r.date}`,{startTime:r.startTime,endTime:r.endTime}):r.startTime&&r.endTime&&this.venueDayAvailability.set(`${n}|DEFAULT`,{startTime:r.startTime,endTime:r.endTime}),r.bookings?.length&&t.courts?.length){const n=r.date||this.tournamentRecord.startDate;for(const i of r.bookings)for(const r of t.courts){const t={tournamentId:this.config.tournamentId,venueId:e,courtId:EV(r)};this.createBlockFromBooking(i,t,n)}}}loadCourtAvailability(t,e){for(const n of t.courts??[]){if(!n.dateAvailability?.length)continue;const t={tournamentId:this.config.tournamentId,venueId:e,courtId:EV(n)};for(const e of n.dateAvailability){const n=e.date||this.tournamentRecord.startDate;if(e.startTime&&e.endTime){const r=bV(t);this.courtDayAvailability.set(`${r}|${n}`,{startTime:e.startTime,endTime:e.endTime})}if(e.bookings?.length)for(const r of e.bookings)this.createBlockFromBooking(r,t,n)}}}createBlockFromBooking(t,e,n){if(!t.startTime||!t.endTime)return;const r=5===t.startTime.length?`${t.startTime}:00`:t.startTime,i=5===t.endTime.length?`${t.endTime}:00`:t.endTime,o=QW.BOOKING_TYPE_MAP[(t.bookingType||"").toUpperCase()]||DV.RESERVED,a=this.generateBlockId(),s={id:a,court:e,start:`${n}T${r}`,end:`${n}T${i}`,type:o,reason:t.bookingType||"Booking",source:"SYSTEM"};this.blocksById.set(a,s),this.indexBlock(s)}getAllCourtsFromTournamentRecord(){if(!this.tournamentRecord?.venues)return[];const t=[];for(const e of this.tournamentRecord.venues){const n=AV(e);if(e.courts)for(const r of e.courts)t.push({tournamentId:this.config.tournamentId,venueId:n,courtId:EV(r)})}return t}getFirstAvailableDay(){return this.tournamentRecord?.startDate?Lo(this.tournamentRecord.startDate):null}generateBlockId(){return"block-"+this.nextBlockId++}clampToAvailability(t,e,n,r){const i=this.getCourtAvailability(t,e),o=`${e}T${i.startTime}:00`,a=`${e}T${i.endTime}:00`,s=n<o?o:n,c=r>a?a:r;return s>=c?null:{start:s,end:c}}listCourtMeta(){return this.getAllCourtsFromTournamentRecord().map(t=>this.getCourtMeta(t))}getCourtMeta(t){if(this.tournamentRecord?.venues)for(const e of this.tournamentRecord.venues){if(AV(e)===t.venueId)for(const n of e.courts??[]){if(EV(n)!==t.courtId)continue;const e=this.getFirstAvailableDay(),r=e?this.getCourtAvailability(t,e):void 0;return{ref:t,name:n.courtName||n.courtId,surface:n.surfaceCategory||n.surfaceType||"hard",indoor:"INDOOR"===n.indoorOutdoor||n.indoor||!1,hasLights:n.hasLights||!1,tags:[],openTime:r?.startTime,closeTime:r?.endTime}}}return{ref:t,name:t.courtId,surface:"hard",indoor:!1,hasLights:!1,tags:[]}}}QW.BOOKING_TYPE_MAP={MAINTENANCE:DV.MAINTENANCE,PRACTICE:DV.PRACTICE,RESERVED:DV.RESERVED,MATCH:DV.SCHEDULED,SCHEDULED:DV.SCHEDULED};var JW={__proto__:null,AvailabilityEngine:QW,BLOCK_TYPES:DV,EvaluatorRegistry:lG,adjacentBlockEvaluator:aG,applyAvailabilityToTournamentRecord:EG,blockDurationEvaluator:cG,buildDayRange:jV,buildEdges:_V,buildSchedulingProfileFromUISelections:CG,calculateCapacityStats:zV,calculateCourtHours:_G,clampDragToCollisions:nG,clampToDayRange:CV,compareCapacityCurves:JV,computePlanItemId:PG,courtDayKey:RV,courtKey:bV,courtOverlapEvaluator:iG,createFollowByEvaluator:mG,dayBoundaryEvaluator:uG,defaultEvaluators:pG,deriveRailSegments:BV,diffMinutes:FV,extractDay:GV,filterCapacityCurve:YV,findBlocksContainingTime:eG,formatConflicts:gG,generateCapacityCurve:WV,getHighestSeverity:hG,groupConflictsBySeverity:fG,hhmmToMinutes:IG,intervalsOverlap:ZV,iterateDayTicks:UG,lightingEvaluator:sG,maintenanceWindowEvaluator:dG,matchWindowEvaluator:oG,mergeAdjacentSegments:VV,mergeOverlappingAvailability:xG,minutesToHhmm:SG,overlappingRange:kV,railsToDateAvailability:NG,rangesOverlap:OV,resolveCourtId:EV,resolveStatus:xV,resolveVenueId:AV,runValidationPipeline:RG,sampleCapacityCurve:KV,snapIsoToGranularity:vG,snapToGranularity:yG,sortBlocksByStart:rG,sortEdges:LV,timeInsideBlock:tG,todsAvailabilityToBlocks:OG,validateDateAvailability:FG,validateSchedulingProfileFormat:kG,validateSegments:qV,venueDayKey:MV,venueKey:NV};const XW={calculateNewRatings:qD,generateDynamicRatings:$D};BW.importMethods({...iL,...XW});const ZW="DRAFT",t$="SUBMITTED",e$="UNDER_REVIEW",n$="APPROVED",r$="CONDITIONALLY_APPROVED",i$="REJECTED",o$="WITHDRAWN",a$="MODIFICATION_REQUESTED",s$="ACTIVE",c$="POST_EVENT",u$="CLOSED",d$="ISSUES_FLAGGED",p$={DRAFT:[t$,o$],SUBMITTED:[e$,o$],UNDER_REVIEW:[n$,r$,i$,a$],APPROVED:[s$,a$,o$],CONDITIONALLY_APPROVED:[n$,i$,o$],REJECTED:[],WITHDRAWN:[],MODIFICATION_REQUESTED:[t$,o$],ACTIVE:[c$],POST_EVENT:[u$,d$],CLOSED:[],ISSUES_FLAGGED:[u$]},l$=[ZW,a$],m$=[n$,s$],f$={message:"Missing sanctioningRecord",code:"ERR_MISSING_SANCTIONING_RECORD"},h$={message:"SanctioningRecord not found",code:"ERR_NOT_FOUND_SANCTIONING_RECORD"},g$={message:"SanctioningRecord already exists",code:"ERR_EXISTING_SANCTIONING_RECORD"},I$={message:"Invalid status transition",code:"ERR_INVALID_STATUS_TRANSITION"},S$={message:"Missing proposal",code:"ERR_MISSING_PROPOSAL"},y$={message:"Missing event proposal",code:"ERR_MISSING_EVENT_PROPOSAL"},v$={message:"Event proposal not found",code:"ERR_NOT_FOUND_EVENT_PROPOSAL"},U$={message:"Proposal is not editable in current status",code:"ERR_PROPOSAL_NOT_EDITABLE"},P$={message:"Endorsement is required before submission",code:"ERR_ENDORSEMENT_REQUIRED"},T$={message:"Missing endorsement",code:"ERR_MISSING_ENDORSEMENT"},w$={message:"Missing sanctioning policy",code:"ERR_MISSING_SANCTIONING_POLICY"},D$={message:"Condition not found",code:"ERR_NOT_FOUND_CONDITION"},R$={message:"Amendment not found",code:"ERR_NOT_FOUND_AMENDMENT"},b$={message:"Amendments not allowed in current status",code:"ERR_AMENDMENT_NOT_ALLOWED"},N$={message:"Change window has closed; modifications not permitted",code:"ERR_CHANGE_WINDOW_CLOSED"},M$={message:"Compliance tracking not applicable in current status",code:"ERR_COMPLIANCE_NOT_APPLICABLE"},A$={message:"Outstanding compliance items from prior sanctioning must be resolved",code:"ERR_OUTSTANDING_COMPLIANCE"},E$={DRAFT:ZW,SUBMITTED:t$,UNDER_REVIEW:e$,APPROVED:n$,CONDITIONALLY_APPROVED:r$,REJECTED:i$,WITHDRAWN:o$,MODIFICATION_REQUESTED:a$,ACTIVE:s$,POST_EVENT:c$,CLOSED:u$,ISSUES_FLAGGED:d$,VALID_STATUS_TRANSITIONS:p$,TERMINAL_STATUSES:[i$,o$,u$],EDITABLE_STATUSES:l$,AMENDABLE_STATUSES:m$};function C$(t){t.endorsements?.length&&(t.endorsement=t.endorsements[0])}function O$(t,e){return e&&t.endorsements?.length?t.endorsements.find(t=>t.endorserId===e):t.endorsement??t.endorsements?.[0]}function k$({sanctioningRecord:t,toStatus:e,sanctioningPolicy:n,transitionedBy:r,reason:i}){if(!t)return{error:f$};const o=function({fromStatus:t,toStatus:e}){const n=p$[t];return n?n.includes(e)?{...Y,valid:!0}:{error:I$,context:{fromStatus:t,toStatus:e,validTargets:n}}:{error:I$,context:{fromStatus:t,message:`Unknown status: ${t}`}}}({fromStatus:t.status,toStatus:e});if(o.error)return o;const a=n??t.policySnapshot;if(a?.transitionGuards?.length){const n=function({sanctioningRecord:t,guards:e,from:n,to:r}){const i=e.filter(t=>t.from===n&&t.to===r).filter(e=>!e.tiers?.length||e.tiers.includes(t.sanctioningLevel??""));for(const e of i){if(!F$(t,e))return{error:I$,context:{guard:e.guard,message:e.message??`Transition guard failed: ${e.guard}`}}}return{...Y}}({sanctioningRecord:t,guards:a.transitionGuards,from:t.status,to:e});if(n.error)return n}const s=(new Date).toISOString(),c={fromStatus:t.status,toStatus:e,transitionedAt:s,transitionedBy:r,reason:i};return t.statusHistory??=[],t.statusHistory.push(c),t.status=e,t.updatedAt=s,t.version+=1,{...Y}}function F$(t,e){switch(e.guard){case"ENDORSEMENT_REQUIRED":return(t.endorsements??(t.endorsement?[t.endorsement]:[])).some(t=>"ENDORSED"===t.status||"NOT_REQUIRED"===t.status);case"PROPOSAL_VALID":return!!(t.proposal?.tournamentName&&t.proposal?.proposedStartDate&&t.proposal?.events?.length);case"ALL_CONDITIONS_MET":return t.conditions?.every(t=>t.met)??!0;case"COMPLIANCE_COMPLETE":return(t.compliance?.items?.filter(t=>t.required)??[]).every(t=>"VERIFIED"===t.status||"WAIVED"===t.status);case"CUSTOM":return!e.customGuardField||(n=t,!!e.customGuardField.split(".").reduce((t,e)=>t?.[e],n));default:return!0}var n}function x$({sanctioningRecord:t,changes:e,sanctioningPolicy:n,proposedBy:r}){if(!t)return{error:f$};if(!Array.isArray(e)||0===e.length)return{error:sr,context:{message:"At least one change is required"}};if(!m$.includes(t.status))return{error:b$,context:{status:t.status}};const i=n??t.policySnapshot,o=i?.amendmentRules,a=function(t,e){if(!e)return{blocked:!1};const n=new Date(t.proposal.proposedStartDate),r=new Date,i=(n.getTime()-r.getTime())/6048e5;if(e.noChangeWindowWeeks&&i<e.noChangeWindowWeeks)return{blocked:!0,reason:`No changes permitted within ${e.noChangeWindowWeeks} weeks of event (${Math.floor(i)} weeks remaining)`};const o=void 0===e.substantialChangeWindowWeeks?void 0:i>=e.substantialChangeWindowWeeks;return{blocked:!1,withinSubstantialWindow:o}}(t,o);if(a.blocked)return{error:N$,context:{message:a.reason}};const s=function(t,e){if(!e?.substantialChangeFields?.length)return"MINOR";const n=t.some(t=>{const n=t.field.replaceAll(/\[(\d+)\]/g,".$1");return e.substantialChangeFields.some(t=>new RegExp("^"+t.replaceAll(".*.",String.raw`\.[^.]+\.`).replaceAll("*","[^.]+")+"$").test(n))});return n?"SUBSTANTIAL":"MINOR"}(e,o),c=(new Date).toISOString(),u={amendmentId:pa(),status:"PROPOSED",proposedAt:c,proposedBy:r,changes:e,severity:s,withinTimeline:!1!==a.withinSubstantialWindow};return"MINOR"===s&&!1!==a.withinSubstantialWindow&&(u.status="APPROVED",u.resolvedAt=c,B$(t,e)),t.amendments??=[],t.amendments.push(u),t.updatedAt=c,t.version+=1,{...Y,amendmentId:u.amendmentId,severity:s,autoApproved:"APPROVED"===u.status}}const _$=new Set(["tournamentName","formalName","promotionalName","proposedStartDate","proposedEndDate","hostCountryCode","surfaceCategory","indoorOutdoor","localTimeZone","sanctioningTier","totalPrizeMoney","entryFees","calendarSection","events","venues","officials","tournamentDirector","referee","registrationProfile"]);function L$(t){const e=t.replaceAll(/\[\d+\]/g,".*").split(".")[0];return _$.has(e)}function B$(t,e){for(const n of e){if("REMOVED"===n.changeType)continue;if(!L$(n.field))continue;const e=n.field.split(".");let r=t.proposal;for(let t=0;t<e.length-1;t++){const n=e[t],i=new RegExp(/^(\w+)\[(\d+)\]$/).exec(n);if(i){const t=r[i[1]],e=Number.parseInt(i[2]);if(!Array.isArray(t)||e<0||e>=t.length){r=void 0;break}r=t[e]}else r=r?.[n];if(null==r)break}if(null!=r){const t=e.at(-1),i=t?.match(/^(\w+)\[(\d+)\]$/);if(i){const t=r[i[1]],e=Number.parseInt(i[2]);Array.isArray(t)&&e>=0&&e<t.length&&(t[e]=n.proposedValue)}else t&&(r[t]=n.proposedValue)}}}function V$(t){return t.tournamentName??t.sanctioningId??"existing event"}function G$({sanctioningRecord:t,calendarContext:e}){if(!t)return{error:f$};if(!e)return{error:sr,context:{message:"Missing calendarContext"}};const{existingEvents:n}=e,r=e.calendarRules??t.policySnapshot?.calendarRules??{},{proposal:i}=t,o=[],a=new Date(i.proposedStartDate),s=new Date(i.proposedEndDate);!function(t,e,n,r){if(!t.blackoutDates?.length)return;for(const i of t.blackoutDates){const t=new Date(i);t>=e&&t<=n&&r.push({type:"BLACKOUT",severity:"error",message:`Proposed dates overlap with blackout date: ${i}`})}}(r,a,s,o);for(const e of n)j$(r,i,t,a,s,e,o),q$(r,i,a,s,e,o);!function(t,e,n,r){if(!t.maxEventsPerWeek)return;const i=$$(n),o=e.filter(t=>$$(new Date(t.startDate)).getTime()===i.getTime());o.length>=t.maxEventsPerWeek&&r.push({type:"MAX_EVENTS_PER_WEEK",severity:"warning",message:`Week already has ${o.length} events (max ${t.maxEventsPerWeek})`})}(r,n,a,o);const c=o.filter(t=>"error"===t.severity),u=o.filter(t=>"warning"===t.severity);return{...Y,conflicts:o,errors:c,warnings:u,hasConflicts:o.length>0}}function j$(t,e,n,r,i,o,a){if(!t.proximityWeeks)return;const s=new Date(o.startDate),c=new Date(o.endDate),u=7*t.proximityWeeks*24*60*60*1e3,{gap:d,isOverlapping:p}=function(t,e,n,r){const i=t<=r&&e>=n;let o;return o=i?0:t>r?t.getTime()-r.getTime():n.getTime()-e.getTime(),{gap:o,isOverlapping:i}}(r,i,s,c);if(d>=u)return;const l=!e.calendarSection||!o.calendarSection||e.calendarSection===o.calendarSection,m=!n.sanctioningLevel||!o.sanctioningTier||n.sanctioningLevel===o.sanctioningTier;l&&m&&(p?a.push({type:"SAME_WEEK",severity:"error",message:`Overlapping dates with ${V$(o)} (${o.startDate} - ${o.endDate})`,conflictingEvent:o}):a.push({type:"PROXIMITY",severity:"warning",message:`Within ${t.proximityWeeks} week(s) of ${V$(o)} (${o.startDate} - ${o.endDate})`,conflictingEvent:o}))}function q$(t,e,n,r,i,o){if(!t.proximityRadiusKm||!e.venues?.length||!i.coordinates)return;const a=e.venues.find(t=>t.coordinates)?.coordinates;if(!a)return;const s=new Date(i.startDate),c=new Date(i.endDate),u=function(t,e){const n=6371,r=W$(e.latitude-t.latitude),i=W$(e.longitude-t.longitude),o=Math.sin(r/2),a=Math.sin(i/2),s=o*o+Math.cos(W$(t.latitude))*Math.cos(W$(e.latitude))*a*a;return 2*n*Math.atan2(Math.sqrt(s),Math.sqrt(1-s))}(a,i.coordinates);if(u>=t.proximityRadiusKm)return;n<=c&&r>=s&&o.push({type:"PROXIMITY",severity:"error",message:`Within ${Math.round(u)}km of ${V$(i)} (min ${t.proximityRadiusKm}km required)`,conflictingEvent:i})}function W$(t){return t*Math.PI/180}function $$(t){const e=new Date(t),n=e.getDay();return e.setDate(e.getDate()-n),e.setHours(0,0,0,0),e}function H$({proposal:t,sanctioningPolicy:e,sanctioningTier:n}){if(!t)return{error:S$};if(!e)return{error:w$};const r=[],i=n?e.tiers.find(t=>t.tierName===n):void 0;if(e.requireInsurance&&!t.insuranceCertificate&&r.push({field:"insuranceCertificate",message:"Insurance certificate required",severity:"error"}),e.requireSafetyPlan&&!t.safetyPlan&&r.push({field:"safetyPlan",message:"Safety plan required",severity:"error"}),e.requireMedicalPlan&&!t.medicalPlan&&r.push({field:"medicalPlan",message:"Medical plan required",severity:"error"}),e.requireAntiCorruption&&!t.antiCorruptionCompliance&&r.push({field:"antiCorruptionCompliance",message:"Anti-corruption compliance required",severity:"error"}),e.requireSafeguarding&&!t.safeguardingCompliance&&r.push({field:"safeguardingCompliance",message:"Safeguarding compliance required",severity:"error"}),e.minimumLeadWeeks||i?.minimumLeadWeeks){const n=i?.minimumLeadWeeks??e.minimumLeadWeeks??0,o=new Date(t.proposedStartDate),a=new Date,s=(o.getTime()-a.getTime())/6048e5;s<n&&r.push({field:"proposedStartDate",message:`Minimum ${n} weeks lead time required; ${Math.floor(s)} weeks remaining`,severity:"error"})}if(i&&function({proposal:t,tier:e,issues:n}){(function(t,e,n){if(!t.totalPrizeMoney?.length)return;const r=t.totalPrizeMoney.reduce((t,e)=>t+e.amount,0);void 0!==e.minimumPrizeMoney&&r<e.minimumPrizeMoney&&n.push({field:"totalPrizeMoney",message:`Minimum prize money for ${e.tierName}: ${e.minimumPrizeMoney}; proposed: ${r}`,severity:"error"});void 0!==e.maximumPrizeMoney&&r>e.maximumPrizeMoney&&n.push({field:"totalPrizeMoney",message:`Maximum prize money for ${e.tierName}: ${e.maximumPrizeMoney}; proposed: ${r}`,severity:"error"})})(t,e,n),function(t,e,n){if(void 0===e.minimumCourts)return;const r=t.venues?.reduce((t,e)=>t+(e.numberOfCourts??0),0)??0;r<e.minimumCourts&&n.push({field:"venues",message:`Minimum ${e.minimumCourts} courts required; proposed: ${r}`,severity:"error"})}(t,e,n);for(let r=0;r<t.events.length;r++)z$(t.events[r],r,e,n)}({proposal:t,tier:i,issues:r}),e.personnelRules)for(const n of e.personnelRules.roles){if(!n.required)continue;const e=K$(t,n);e.found?e.certificationIssue&&r.push({field:`personnel.${n.roleName}.certification`,message:e.certificationIssue,severity:"error"}):r.push({field:`personnel.${n.roleName}`,message:`Required role not filled: ${n.roleName}`,severity:"error"})}const o=r.filter(t=>"error"===t.severity),a=r.filter(t=>"warning"===t.severity),s=0===o.length;return{...Y,valid:s,issues:r,errors:o,warnings:a}}function z$(t,e,n,r){const i=`events[${e}]`,o=n.tierName;n.allowedEventTypes?.length&&!n.allowedEventTypes.includes(t.eventType)&&r.push({field:`${i}.eventType`,message:`Event type '${t.eventType}' not allowed for tier ${o}`,severity:"error"}),n.allowedDrawTypes?.length&&t.drawType&&!n.allowedDrawTypes.includes(t.drawType)&&r.push({field:`${i}.drawType`,message:`Draw type '${t.drawType}' not allowed for tier ${o}`,severity:"error"}),n.allowedDrawSizes?.length&&t.drawSize&&!n.allowedDrawSizes.includes(t.drawSize)&&r.push({field:`${i}.drawSize`,message:`Draw size ${t.drawSize} not allowed for tier ${o}; allowed: ${n.allowedDrawSizes.join(", ")}`,severity:"error"}),n.allowedMatchUpFormats?.length&&t.matchUpFormat&&!n.allowedMatchUpFormats.includes(t.matchUpFormat)&&r.push({field:`${i}.matchUpFormat`,message:`Match format '${t.matchUpFormat}' not allowed for tier ${o}`,severity:"error"}),n.allowedGenders?.length&&t.gender&&!n.allowedGenders.includes(t.gender)&&r.push({field:`${i}.gender`,message:`Gender '${t.gender}' not allowed for tier ${o}`,severity:"error"}),function(t,e,n,r){if(!t.qualifyingDrawSize)return;!1===n.qualifyingAllowed?r.push({field:`${e}.qualifyingDrawSize`,message:`Qualifying not allowed for tier ${n.tierName}`,severity:"error"}):n.maxQualifyingDrawSize&&t.qualifyingDrawSize>n.maxQualifyingDrawSize&&r.push({field:`${e}.qualifyingDrawSize`,message:`Qualifying draw size ${t.qualifyingDrawSize} exceeds maximum ${n.maxQualifyingDrawSize}`,severity:"error"})}(t,i,n,r)}const Y$=["White Badge","Bronze Badge","Silver Badge","Gold Badge","Sectional","National","International"];function K$(t,e){const n=function(t,e){if(e.includes("director")&&t.tournamentDirector?.personName)return t.tournamentDirector;if(e.includes("referee")&&t.referee?.personName)return t.referee;const n=t.officials?.find(t=>t.role.toLowerCase().includes(e));return n?{personName:n.personName,certificationLevel:n.certificationLevel}:void 0}(t,e.roleName.toLowerCase());if(!n?.personName?.trim())return{found:!1};if(e.certificationRequired){if(!n.certificationLevel)return{found:!0,certificationIssue:`${e.roleName} requires '${e.certificationRequired}' certification but none specified`};if(!function(t,e){if(!e)return!0;if(!t)return!1;const n=Y$,r=n.findIndex(e=>e.toLowerCase()===t.toLowerCase()),i=n.findIndex(t=>t.toLowerCase()===e.toLowerCase());return r<0||i<0?t.toLowerCase()===e.toLowerCase():r>=i}(n.certificationLevel,e.certificationRequired))return{found:!0,certificationIssue:`${e.roleName} has '${n.certificationLevel}' but '${e.certificationRequired}' or higher is required`}}return{found:!0}}function Q$(t){return null!=t&&("string"==typeof t?t.trim().length>0:"number"==typeof t||("boolean"==typeof t||(Array.isArray(t)?t.length>0:"object"==typeof t||!!t)))}const J$={sanctioningRecords:{},activeSanctioningId:void 0,methods:{}};function X$(){return J$.sanctioningRecords}function Z$(t){const e=t??J$.activeSanctioningId;return e?J$.sanctioningRecords[e]:void 0}function tH(t){return t?.sanctioningId?(J$.sanctioningRecords[t.sanctioningId]=t,{...Y}):{error:sr,context:{message:"Missing sanctioningId"}}}function eH(t){J$.sanctioningRecords=t??{};const e=Object.keys(J$.sanctioningRecords);return J$.activeSanctioningId=1===e.length?e[0]:void 0,{...Y}}function nH(){return J$.activeSanctioningId}function rH(t){return t&&!J$.sanctioningRecords[t]?{error:h$,context:{sanctioningId:t}}:(J$.activeSanctioningId=t,{...Y})}const iH="Missing itemId";function oH(t){if(!t.compliance)return;const e=t.compliance.items,n=e.filter(t=>t.required).every(t=>"VERIFIED"===t.status||"WAIVED"===t.status),r=e.some(t=>"OVERDUE"===t.status),i=e.some(t=>"SUBMITTED"===t.status||"VERIFIED"===t.status||"WAIVED"===t.status);t.compliance.status=n?"COMPLIANT":r?"ISSUES_FLAGGED":i?"IN_PROGRESS":"PENDING"}function aH(t){return Z$(t??nH())}const sH=(()=>{const t={version:()=>"5.2.4",reset:()=>(J$.sanctioningRecords={},J$.activeSanctioningId=void 0,J$.methods={},{...Y}),getState:()=>({...Y,sanctioningRecords:ca(X$(),!1,!0)}),setState:t=>(eH(t),{...Y}),setSanctioningRecord:t=>tH(t),removeSanctioningRecord:t=>function(t){return J$.sanctioningRecords[t]?(delete J$.sanctioningRecords[t],J$.activeSanctioningId===t&&(J$.activeSanctioningId=void 0),{...Y}):{error:h$,context:{sanctioningId:t}}}(t),setActiveSanctioningId:t=>rH(t),getActiveSanctioningId:()=>nH(),createSanctioningRecord:t=>{const e=function({sanctioningId:t,governingBodyId:e,applicantProviderId:n,applicant:r,proposal:i,sanctioningLevel:o,sanctioningPolicy:a,extensions:s}){if(!e)return{error:sr,context:{message:"Missing governingBodyId"}};if(!r)return{error:sr,context:{message:"Missing applicant"}};if(!i)return{error:sr,context:{message:"Missing proposal"}};if(!i.tournamentName)return{error:sr,context:{message:"Missing proposal.tournamentName"}};if(!i.proposedStartDate)return{error:sr,context:{message:"Missing proposal.proposedStartDate"}};if(!i.proposedEndDate)return{error:sr,context:{message:"Missing proposal.proposedEndDate"}};if(!Array.isArray(i.events)||0===i.events.length)return{error:sr,context:{message:"Proposal must include at least one event"}};const c=(new Date).toISOString(),u={sanctioningId:t||pa(),status:ZW,version:1,createdAt:c,updatedAt:c,applicant:r,proposal:{...i,events:i.events.map(t=>({...t,eventProposalId:t.eventProposalId||pa()}))},governingBodyId:e,applicantProviderId:n,sanctioningLevel:o,sanctioningPolicy:a,statusHistory:[{fromStatus:ZW,toStatus:ZW,transitionedAt:c,reason:"Record created"}],extensions:s??[],timeItems:[]};return{...Y,sanctioningRecord:u}}(t);if(e.error)return e;const{sanctioningRecord:n}=e;if(!n)return e;return Z$(n.sanctioningId)?{error:g$}:(tH(n),rH(n.sanctioningId),e)},updateProposal:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,updates:e}){if(!t)return{error:f$};if(!e||"object"!=typeof e)return{error:sr,context:{message:"Missing updates"}};if(!l$.includes(t.status))return{error:U$,context:{status:t.status}};const{events:n,...r}=e;return Object.assign(t.proposal,r),t.updatedAt=(new Date).toISOString(),t.version+=1,{...Y}}({...t,sanctioningRecord:e})},addEventProposal:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,eventProposal:e}){if(!t)return{error:f$};if(!e)return{error:y$};if(!e.eventName)return{error:sr,context:{message:"Missing eventName"}};if(!e.eventType)return{error:sr,context:{message:"Missing eventType"}};if(!l$.includes(t.status))return{error:U$,context:{status:t.status}};const n={...e,eventProposalId:e.eventProposalId||pa()};return t.proposal.events.push(n),t.updatedAt=(new Date).toISOString(),t.version+=1,{...Y,eventProposalId:n.eventProposalId}}({...t,sanctioningRecord:e})},removeEventProposal:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,eventProposalId:e}){if(!t)return{error:f$};if(!e)return{error:sr,context:{message:"Missing eventProposalId"}};if(!l$.includes(t.status))return{error:U$,context:{status:t.status}};const n=t.proposal.events.findIndex(t=>t.eventProposalId===e);return n<0?{error:v$,context:{eventProposalId:e}}:(t.proposal.events.splice(n,1),t.updatedAt=(new Date).toISOString(),t.version+=1,{...Y})}({...t,sanctioningRecord:e})},updateEventProposal:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,eventProposalId:e,updates:n}){if(!t)return{error:f$};if(!e)return{error:sr,context:{message:"Missing eventProposalId"}};if(!n||"object"!=typeof n)return{error:sr,context:{message:"Missing updates"}};if(!l$.includes(t.status))return{error:U$,context:{status:t.status}};const r=t.proposal.events.find(t=>t.eventProposalId===e);if(!r)return{error:v$,context:{eventProposalId:e}};const{eventProposalId:i,...o}=n;return Object.assign(r,o),t.updatedAt=(new Date).toISOString(),t.version+=1,{...Y}}({...t,sanctioningRecord:e})},submitApplication:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,sanctioningPolicy:e,priorSanctioningRecords:n,submittedBy:r}){if(!t)return{error:f$};if(n?.length&&n.some(t=>"ISSUES_FLAGGED"===t.compliance?.status||t.compliance?.items?.some(t=>"OVERDUE"===t.status&&t.required)))return{error:A$};if(e?.requireEndorsement){const n=e?.requiredEndorsementCount??1;if((t.endorsements??(t.endorsement?[t.endorsement]:[])).filter(t=>"ENDORSED"===t.status||"NOT_REQUIRED"===t.status).length<n)return{error:P$}}const i=k$({sanctioningRecord:t,toStatus:t$,transitionedBy:r,reason:"Application submitted"});return i.error||(t.submittedAt=t.updatedAt,e&&(t.policyVersion=e.policyVersion,t.policySnapshot=ca(e,!1,!0))),i}({...t,sanctioningRecord:e})},reviewApplication:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,reviewer:e}){if(!t)return{error:f$};const n=k$({sanctioningRecord:t,toStatus:e$,transitionedBy:e?.reviewerName,reason:"Application under review"});return n.error||(e&&(t.reviewer=e),t.reviewedAt=t.updatedAt),n}({...t,sanctioningRecord:e})},approveApplication:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,approvedBy:e,reason:n}){if(!t)return{error:f$};const r=k$({sanctioningRecord:t,toStatus:n$,transitionedBy:e,reason:n??"Application approved"});return r.error||(t.approvedAt=t.updatedAt),r}({...t,sanctioningRecord:e})},conditionallyApprove:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,conditions:e,approvedBy:n}){if(!t)return{error:f$};if(!Array.isArray(e)||0===e.length)return{error:sr,context:{message:"At least one condition is required"}};const r=k$({sanctioningRecord:t,toStatus:r$,transitionedBy:n,reason:"Conditionally approved pending conditions"});if(r.error)return r;const i=(new Date).toISOString();t.conditions??=[];for(const n of e){const e={conditionId:pa(),description:n.description,met:!1,createdAt:i};t.conditions.push(e)}return r}({...t,sanctioningRecord:e})},meetCondition:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,conditionId:e,metNotes:n}){if(!t)return{error:f$};if(!e)return{error:sr,context:{message:"Missing conditionId"}};const r=t.conditions?.find(t=>t.conditionId===e);if(!r)return{error:D$,context:{conditionId:e}};r.met=!0,r.metAt=(new Date).toISOString(),n&&(r.metNotes=n),t.updatedAt=(new Date).toISOString(),t.version+=1;const i=t.conditions?.every(t=>t.met)??!1;return{...Y,allConditionsMet:i}}({...t,sanctioningRecord:e})},rejectApplication:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,rejectedBy:e,reason:n}){return t?k$({sanctioningRecord:t,toStatus:i$,transitionedBy:e,reason:n??"Application rejected"}):{error:f$}}({...t,sanctioningRecord:e})},withdrawApplication:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,withdrawnBy:e,reason:n}){return t?k$({sanctioningRecord:t,toStatus:o$,transitionedBy:e,reason:n??"Application withdrawn"}):{error:f$}}({...t,sanctioningRecord:e})},requestModification:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,requestedBy:e,note:n}){if(!t)return{error:f$};const r=k$({sanctioningRecord:t,toStatus:a$,transitionedBy:e,reason:n??"Modifications requested"});if(r.error)return r;if(n){t.reviewNotes??=[];const r={noteId:pa(),reviewerId:e,note:n,createdAt:t.updatedAt};t.reviewNotes.push(r)}return r}({...t,sanctioningRecord:e})},requestEndorsement:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,endorserId:e,endorserName:n,endorserContact:r,endorsementLevel:i,prerequisiteEndorserId:o}){if(!t)return{error:f$};if(!e)return{error:sr,context:{message:"Missing endorserId"}};const a={status:"PENDING",endorserId:e,endorserName:n,endorserContact:r,endorsementLevel:i,prerequisiteEndorserId:o};t.endorsements??=[];const s=t.endorsements.findIndex(t=>t.endorserId===e);return s>=0?t.endorsements[s]=a:t.endorsements.push(a),C$(t),t.updatedAt=(new Date).toISOString(),t.version+=1,{...Y}}({...t,sanctioningRecord:e})},endorseApplication:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,endorserId:e,endorserNotes:n,conditions:r}){if(!t)return{error:f$};const i=O$(t,e);return i?(i.status="ENDORSED",i.endorsedAt=(new Date).toISOString(),n&&(i.endorserNotes=n),r&&(i.conditions=r),C$(t),t.updatedAt=(new Date).toISOString(),t.version+=1,{...Y}):{error:T$}}({...t,sanctioningRecord:e})},declineEndorsement:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,endorserId:e,declineReason:n}){if(!t)return{error:f$};const r=O$(t,e);return r?(r.status="DECLINED",r.declinedAt=(new Date).toISOString(),n&&(r.declineReason=n),C$(t),t.updatedAt=(new Date).toISOString(),t.version+=1,{...Y}):{error:T$}}({...t,sanctioningRecord:e})},addReviewNote:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,note:e,reviewerId:n,reviewerName:r}){if(!t)return{error:f$};if(!e)return{error:sr,context:{message:"Missing note"}};t.reviewNotes??=[];const i={noteId:pa(),reviewerId:n,reviewerName:r,note:e,createdAt:(new Date).toISOString()};return t.reviewNotes.push(i),t.updatedAt=(new Date).toISOString(),t.version+=1,{...Y,noteId:i.noteId}}({...t,sanctioningRecord:e})},activateFromSanctioning:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,sanctioningPolicy:e}){if(!t)return{error:f$};if("APPROVED"!==t.status)return{error:sr,context:{message:`Cannot activate from status: ${t.status}; must be APPROVED`}};const{proposal:n}=t,r={tournamentId:pa(),tournamentName:n.tournamentName,formalName:n.formalName,promotionalName:n.promotionalName,startDate:n.proposedStartDate,endDate:n.proposedEndDate,hostCountryCode:n.hostCountryCode,indoorOutdoor:n.indoorOutdoor,surfaceCategory:n.surfaceCategory,localTimeZone:n.localTimeZone,tournamentLevel:n.tournamentLevel,totalPrizeMoney:n.totalPrizeMoney,registrationProfile:n.registrationProfile,tournamentStatus:"ACTIVE",processCodes:["SANCTIONED"],parentOrganisationId:t.governingBodyId,parentOrganisation:t.governingBody,tournamentCategories:n.events.filter(t=>t.category).map(t=>t.category).filter((t,e,n)=>n.findIndex(e=>e.categoryName===t.categoryName)===e),events:n.events.map(t=>{const e={eventId:pa(),eventName:t.eventName,eventType:t.eventType,gender:t.gender,category:t.category,matchUpFormat:t.matchUpFormat,indoorOutdoor:t.indoorOutdoor,surfaceCategory:t.surfaceCategory,wheelchairClass:t.wheelchairClass,tieFormat:t.tieFormat,drawDefinitions:[],entries:[]};return t.allowedDrawTypes?.length?e.allowedDrawTypes=[...t.allowedDrawTypes]:t.drawType&&(e.allowedDrawTypes=[t.drawType]),e}),extensions:[{name:"sanctioningId",value:t.sanctioningId},...t.sanctioningLevel?[{name:"sanctioningTier",value:t.sanctioningLevel}]:[]],venues:[],participants:[],timeItems:[]},i=k$({sanctioningRecord:t,toStatus:s$,reason:`Tournament ${r.tournamentId} created`});if(i.error)return i;const o=e??t.policySnapshot;if(o?.postEventRequirements?.length){const e=new Date(n.proposedEndDate),r={status:"PENDING",items:o.postEventRequirements.filter(e=>!e.tiers?.length||e.tiers.includes(t.sanctioningLevel??"")).map(t=>{const n=new Date(e);return n.setDate(n.getDate()+t.deadlineDays),{itemId:pa(),itemType:t.itemType,description:t.description,required:t.required,status:"PENDING",deadline:n.toISOString().split("T")[0]}})};t.compliance=r}return{...Y,tournamentRecord:r}}({...t,sanctioningRecord:e})},proposeAmendment:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return x$({...t,sanctioningRecord:e})},reviewAmendment:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,amendmentId:e,approved:n,reviewerNotes:r}){if(!t)return{error:f$};if(!e)return{error:sr,context:{message:"Missing amendmentId"}};const i=t.amendments?.find(t=>t.amendmentId===e);if(!i)return{error:R$,context:{amendmentId:e}};if("PROPOSED"!==i.status)return{error:sr,context:{message:`Amendment is ${i.status}, not PROPOSED`}};const o=(new Date).toISOString();return i.resolvedAt=o,r&&(i.reviewerNotes=r),n?(i.status="APPROVED",B$(t,i.changes)):i.status="REJECTED",t.updatedAt=o,t.version+=1,{...Y,approved:n}}({...t,sanctioningRecord:e})},transitionToPostEvent:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,transitionedBy:e}){return t?k$({sanctioningRecord:t,toStatus:c$,transitionedBy:e,reason:"Tournament completed; entering post-event compliance phase"}):{error:f$}}({...t,sanctioningRecord:e})},submitComplianceItem:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,itemId:e,value:n}){if(!t)return{error:f$};if(!t.compliance)return{error:M$};if(!e)return{error:sr,context:{message:iH}};const r=t.compliance.items.find(t=>t.itemId===e);return r?"VERIFIED"===r.status||"WAIVED"===r.status?{error:sr,context:{message:`Item already ${r.status}; cannot resubmit`}}:(r.status="SUBMITTED",r.submittedAt=(new Date).toISOString(),void 0!==n&&(r.value=n),oH(t),t.updatedAt=(new Date).toISOString(),t.version+=1,{...Y}):{error:sr,context:{message:`Item not found: ${e}`}}}({...t,sanctioningRecord:e})},verifyComplianceItem:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,itemId:e}){if(!t)return{error:f$};if(!t.compliance)return{error:M$};if(!e)return{error:sr,context:{message:iH}};const n=t.compliance.items.find(t=>t.itemId===e);if(!n)return{error:sr,context:{message:`Item not found: ${e}`}};n.status="VERIFIED",n.verifiedAt=(new Date).toISOString(),oH(t),t.updatedAt=(new Date).toISOString(),t.version+=1;const r=t.compliance.items.filter(t=>t.required).every(t=>"VERIFIED"===t.status||"WAIVED"===t.status);return{...Y,allCompliant:r}}({...t,sanctioningRecord:e})},waiveComplianceItem:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,itemId:e,reason:n}){if(!t)return{error:f$};if(!t.compliance)return{error:M$};if(!e)return{error:sr,context:{message:iH}};const r=t.compliance.items.find(t=>t.itemId===e);return r?(r.status="WAIVED",n&&(r.extensions??=[],r.extensions.push({name:"waiveReason",value:n})),oH(t),t.updatedAt=(new Date).toISOString(),t.version+=1,{...Y}):{error:sr,context:{message:`Item not found: ${e}`}}}({...t,sanctioningRecord:e})},flagComplianceIssues:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,transitionedBy:e,reason:n}){return t?k$({sanctioningRecord:t,toStatus:d$,transitionedBy:e,reason:n??"Compliance issues flagged"}):{error:f$}}({...t,sanctioningRecord:e})},closeApplication:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,closedBy:e,reason:n}){if(!t)return{error:f$};const r=k$({sanctioningRecord:t,toStatus:u$,transitionedBy:e,reason:n??"Application closed"});return r.error||t.compliance&&(t.compliance.status="COMPLIANT",t.compliance.completedAt=t.updatedAt),r}({...t,sanctioningRecord:e})},checkComplianceDeadlines:t=>{const e=t.sanctioningRecord??aH(t.sanctioningId);return function({sanctioningRecord:t,asOfDate:e}){if(!t)return{error:f$};if(!t.compliance)return{error:M$};const n=e?new Date(e):new Date;let r=0;for(const e of t.compliance.items)"PENDING"===e.status&&e.deadline&&new Date(e.deadline)<n&&(e.status="OVERDUE",r++);return r>0&&(oH(t),t.updatedAt=(new Date).toISOString(),t.version+=1),{...Y,overdueCount:r}}({...t,sanctioningRecord:e})},getSanctioningRecord:t=>function({sanctioningRecord:t}){return t?{...Y,sanctioningRecord:ca(t,!1,!0)}:{error:f$}}({sanctioningRecord:t?.sanctioningRecord??aH(t?.sanctioningId)}),getAvailableTransitions:t=>function({sanctioningRecord:t}){if(!t)return{error:f$};const e=p$[t.status]??[];return{...Y,availableTransitions:[...e]}}({sanctioningRecord:t?.sanctioningRecord??aH(t?.sanctioningId)}),getStatusHistory:t=>function({sanctioningRecord:t}){if(!t)return{error:f$};const e=ca(t.statusHistory??[],!1,!0);return{...Y,statusHistory:e}}({sanctioningRecord:t?.sanctioningRecord??aH(t?.sanctioningId)}),getCompleteness:t=>function({sanctioningRecord:t,sanctioningPolicy:e}){if(!t)return{error:f$};const{proposal:n,applicant:r,endorsement:i}=t,o=[],a=[["proposal.tournamentName",n?.tournamentName],["proposal.proposedStartDate",n?.proposedStartDate],["proposal.proposedEndDate",n?.proposedEndDate],["proposal.events",n?.events?.length],["applicant.organisationName",r?.organisationName],["applicant.contactName",r?.contactName],["applicant.contactEmail",r?.contactEmail]],s=[["proposal.hostCountryCode",n?.hostCountryCode],["proposal.surfaceCategory",n?.surfaceCategory],["proposal.indoorOutdoor",n?.indoorOutdoor],["proposal.venues",n?.venues?.length],["proposal.tournamentDirector",n?.tournamentDirector?.personName],["proposal.referee",n?.referee?.personName],["proposal.totalPrizeMoney",n?.totalPrizeMoney?.length]],c=[];e&&(e.requireInsurance&&c.push(["proposal.insuranceCertificate",n?.insuranceCertificate]),e.requireSafetyPlan&&c.push(["proposal.safetyPlan",n?.safetyPlan]),e.requireMedicalPlan&&c.push(["proposal.medicalPlan",n?.medicalPlan]),e.requireEndorsement&&c.push(["endorsement","ENDORSED"===i?.status||"NOT_REQUIRED"===i?.status]),e.requireAntiCorruption&&c.push(["proposal.antiCorruptionCompliance",n?.antiCorruptionCompliance]),e.requireSafeguarding&&c.push(["proposal.safeguardingCompliance",n?.safeguardingCompliance]));const u=[...a,...s,...c];let d=0;for(const[t,e]of u)Q$(e)?d++:o.push(t);const p={score:u.length>0?Math.round(d/u.length*100):0,totalFields:u.length,completedFields:d,missingFields:o};return{...Y,completeness:p}}({sanctioningRecord:t?.sanctioningRecord??aH(t?.sanctioningId),...t}),getEligibleTiers:t=>{const e=t?.sanctioningRecord??aH(t?.sanctioningId);return function({proposal:t,sanctioningPolicy:e}){if(!t)return{error:S$};if(!e)return{error:w$};const n=e.tiers.map(e=>{const n=[];if(void 0!==e.minimumPrizeMoney&&t.totalPrizeMoney?.length){const r=t.totalPrizeMoney.reduce((t,e)=>t+e.amount,0);r<e.minimumPrizeMoney&&n.push(`Prize money ${r} below minimum ${e.minimumPrizeMoney}`)}if(void 0!==e.maximumPrizeMoney&&t.totalPrizeMoney?.length){const r=t.totalPrizeMoney.reduce((t,e)=>t+e.amount,0);r>e.maximumPrizeMoney&&n.push(`Prize money ${r} above maximum ${e.maximumPrizeMoney}`)}if(void 0!==e.minimumCourts){const r=t.venues?.reduce((t,e)=>t+(e.numberOfCourts??0),0)??0;r<e.minimumCourts&&n.push(`Courts ${r} below minimum ${e.minimumCourts}`)}if(e.allowedEventTypes?.length){const r=t.events.filter(t=>!e.allowedEventTypes.includes(t.eventType)).map(t=>t.eventType);r.length&&n.push(`Disallowed event types: ${[...new Set(r)].join(", ")}`)}if(e.allowedDrawSizes?.length){const r=t.events.filter(t=>t.drawSize&&!e.allowedDrawSizes.includes(t.drawSize)).map(t=>t.drawSize);r.length&&n.push(`Disallowed draw sizes: ${[...new Set(r)].join(", ")}`)}return{tierName:e.tierName,tierLevel:e.tierLevel,eligible:0===n.length,reasons:n}}),r=n.filter(t=>t.eligible);return{...Y,tierEligibilities:n,eligibleTiers:r}}({proposal:t.proposal??e?.proposal,...t})},validateProposal:t=>{const e=t?.sanctioningRecord??aH(t?.sanctioningId);return H$({proposal:t.proposal??e?.proposal,...t})},getCalendarConflicts:t=>G$({sanctioningRecord:t?.sanctioningRecord??aH(t?.sanctioningId),...t}),executionQueue:(e,n)=>{if(!Array.isArray(e))return{error:sr,context:{message:"directives must be an array"}};const r=n?ca(X$(),!1,!0):void 0,i=[];for(const n of e){if("object"!=typeof n)return{error:sr,context:{message:"directive must be an object"}};const{method:e,pipe:o}=n,a=n.params?{...n.params}:{},s=t[e];if(!s)return r&&eH(r),{error:sr,context:{message:`Method not found: ${e}`},rolledBack:!!r};if(o&&i.length){const t=i.at(-1);for(const e of Object.keys(o))void 0!==t[e]&&(a[e]=t[e])}const c=s(a);if(c?.error)return r&&eH(r),{...c,rolledBack:!!r};i.push({...c,methodName:e})}return{success:i.every(t=>t.success),results:i}}};return t})(),cH={officialRecords:{},activeOfficialRecordId:void 0,methods:{}};function uH(){return cH.officialRecords}function dH(t){const e=t??cH.activeOfficialRecordId;return e?cH.officialRecords[e]:void 0}function pH(t){return t?.officialRecordId?(cH.officialRecords[t.officialRecordId]=t,{...Y}):{error:sr,context:{message:"Missing officialRecordId"}}}function lH(t){cH.officialRecords=t??{};const e=Object.keys(cH.officialRecords);return cH.activeOfficialRecordId=1===e.length?e[0]:void 0,{...Y}}function mH(){return cH.activeOfficialRecordId}function fH(t){return t&&!cH.officialRecords[t]?{error:sj,context:{officialRecordId:t}}:(cH.activeOfficialRecordId=t,{...Y})}function hH(t){return dH(t??mH())}const gH=(()=>{const t={version:()=>"5.2.4",reset:()=>(cH.officialRecords={},cH.activeOfficialRecordId=void 0,cH.methods={},{...Y}),getState:()=>({...Y,officialRecords:ca(uH(),!1,!0)}),setState:t=>(lH(t),{...Y}),setOfficialRecord:t=>pH(t),removeOfficialRecord:t=>function(t){return cH.officialRecords[t]?(delete cH.officialRecords[t],cH.activeOfficialRecordId===t&&(cH.activeOfficialRecordId=void 0),{...Y}):{error:sj,context:{officialRecordId:t}}}(t),setActiveOfficialRecordId:t=>fH(t),getActiveOfficialRecordId:()=>mH(),createOfficialRecord:t=>{const e=Dj(t);if(e.error)return e;const{officialRecord:n}=e;if(!n)return e;return dH(n.officialRecordId)?{error:cj}:(pH(n),fH(n.officialRecordId),e)},addCertification:t=>{const e=t.officialRecord??hH(t.officialRecordId);return Ej({...t,officialRecord:e})},modifyCertification:t=>{const e=t.officialRecord??hH(t.officialRecordId);return Rj({...t,officialRecord:e})},removeCertification:t=>{const e=t.officialRecord??hH(t.officialRecordId);return bj({...t,officialRecord:e})},transitionCertificationStatus:t=>{const e=t.officialRecord??hH(t.officialRecordId);return yj({...t,officialRecord:e})},addEvaluation:t=>{const e=t.officialRecord??hH(t.officialRecordId);return kj({...t,officialRecord:e})},modifyEvaluation:t=>{const e=t.officialRecord??hH(t.officialRecordId);return Nj({...t,officialRecord:e})},removeEvaluation:t=>{const e=t.officialRecord??hH(t.officialRecordId);return Mj({...t,officialRecord:e})},transitionEvaluationStatus:t=>{const e=t.officialRecord??hH(t.officialRecordId);return vj({...t,officialRecord:e})},assignOfficial:t=>{const e=t.officialRecord??hH(t.officialRecordId);return Cj({...t,officialRecord:e})},removeOfficialAssignment:t=>{const e=t.officialRecord??hH(t.officialRecordId);return Tj({...t,officialRecord:e})},transitionAssignmentStatus:t=>{const e=t.officialRecord??hH(t.officialRecordId);return Pj({...t,officialRecord:e})},addCertificationRequirement:t=>{const e=t.officialRecord??hH(t.officialRecordId);return Uj({...t,officialRecord:e})},addSuspension:t=>{const e=t.officialRecord??hH(t.officialRecordId);return Oj({...t,officialRecord:e})},removeSuspension:t=>{const e=t.officialRecord??hH(t.officialRecordId);return Aj({...t,officialRecord:e})},addEvaluationPolicy:t=>{const e=t.officialRecord??hH(t.officialRecordId);return wj({...t,officialRecord:e})},getOfficialRecord:t=>jj({officialRecord:t?.officialRecord??hH(t?.officialRecordId)}),getOfficialCertifications:t=>xj({officialRecord:t?.officialRecord??hH(t?.officialRecordId),...t}),validateCertification:t=>{const e=t?.officialRecord??hH(t?.officialRecordId);return _j({...t,officialRecord:e})},getEvaluations:t=>qj({officialRecord:t?.officialRecord??hH(t?.officialRecordId),...t}),getEvaluationSummary:t=>Gj({officialRecord:t?.officialRecord??hH(t?.officialRecordId),...t}),getOfficialEligibility:t=>{const e=t?.officialRecord??hH(t?.officialRecordId);return Bj({...t,officialRecord:e})},getOfficialAssignments:t=>Vj({officialRecord:t?.officialRecord??hH(t?.officialRecordId),...t}),getEvaluationTemplate:t=>{const e=t?.officialRecord??hH(t?.officialRecordId);return Lj({...t,officialRecord:e})},executionQueue:(e,n)=>{if(!Array.isArray(e))return{error:sr,context:{message:"directives must be an array"}};const r=n?ca(uH(),!1,!0):void 0,i=[];for(const n of e){if("object"!=typeof n)return{error:sr,context:{message:"directive must be an object"}};const{method:e,pipe:o}=n,a=n.params?{...n.params}:{},s=t[e];if(!s)return r&&lH(r),{error:sr,context:{message:`Method not found: ${e}`},rolledBack:!!r};if(o&&i.length){const t=i.at(-1);for(const e of Object.keys(o))void 0!==t[e]&&(a[e]=t[e])}const c=s(a);if(c?.error)return r&&lH(r),{...c,rolledBack:!!r};i.push({...c,methodName:e})}return{success:i.every(t=>t.success),results:i}}};return t})();BW.importMethods(Nq,!0,1);const IH=BW,SH=BW,yH=BW,vH=BW,UH=_W(!0);UH.importMethods(Nq,!0,1);const PH=UH,TH=UH;const wH={INTENNSE_STANDARD:{competitionFormatName:"INTENNSE_STANDARD",matchUpFormat:"SET7XA-S:T10P",sport:"INTENNSE",timerProfile:{shotClockSeconds:14,segmentTimers:[{segmentType:"set",direction:"down",minutes:10}],changeoverSeconds:0,setBreakSeconds:120},timeoutRules:{count:5,per:"MATCHUP",durationSeconds:60,maxPerSide:5},substitutionRules:{allowed:!0,allowedMatchUpTypes:["SINGLES","DOUBLES"],timing:"BETWEEN_POINTS"},playerRules:{maxMinutesPerSegment:6,matchUpTypes:["SINGLES"]},penaltyBoxProfile:{durationSeconds:120},penaltyProfile:{sport:"INTENNSE",penaltyTypes:[{penaltyType:"UNSPORTSMANLIKE_CONDUCT",label:"Unsportsmanlike",category:"conduct"},{penaltyType:"BALL_ABUSE",label:"Ball Abuse",category:"conduct"},{penaltyType:"RACKET_ABUSE",label:"Racket Abuse",category:"conduct"}],escalation:[{step:1,consequence:"warning"},{step:2,consequence:"point"},{step:3,consequence:"game"},{step:4,consequence:"default"}]},pointProfile:{sport:"INTENNSE",pointResults:[{result:"Ace",label:"Ace",isServe:!0},{result:"Winner",label:"Winner"},{result:"Serve Winner",label:"Serve Winner",isServe:!0},{result:"Forced Error",label:"Forced Error",isError:!0},{result:"Unforced Error",label:"Unforced Error",isError:!0},{result:"Double Fault",label:"Double Fault",isServe:!0,isError:!0},{result:"Touch",label:"Touch"},{result:"Penalty",label:"Penalty"}]},pointMultipliers:[{condition:{results:["Ace"]},value:2},{condition:{results:["Winner"]},value:2}]},TENNIS_STANDARD:{competitionFormatName:"TENNIS_STANDARD",matchUpFormat:"SET3-S:6/TB7",sport:"TENNIS",timerProfile:{changeoverSeconds:90,setBreakSeconds:120},timeoutRules:{count:0,per:"MATCHUP"},substitutionRules:{allowed:!1},penaltyProfile:{sport:"TENNIS",penaltyTypes:[{penaltyType:"TIME_VIOLATION",label:"Time Violation",category:"time_violation"},{penaltyType:"COACHING",label:"Coaching",category:"code_violation"},{penaltyType:"UNSPORTSMANLIKE_CONDUCT",label:"Unsportsmanlike",category:"conduct"},{penaltyType:"BALL_ABUSE",label:"Ball Abuse",category:"conduct"},{penaltyType:"RACKET_ABUSE",label:"Racket Abuse",category:"conduct"},{penaltyType:"VERBAL_ABUSE",label:"Verbal Abuse",category:"conduct"},{penaltyType:"AUDIBLE_OBSCENITY",label:"Audible Obscenity",category:"conduct"},{penaltyType:"VISIBLE_OBSCENITY",label:"Visible Obscenity",category:"conduct"}],escalation:[{step:1,consequence:"warning"},{step:2,consequence:"point"},{step:3,consequence:"game"},{step:4,consequence:"default"}]},pointProfile:{sport:"TENNIS",pointResults:[{result:"Ace",label:"Ace",isServe:!0},{result:"Winner",label:"Winner"},{result:"Serve Winner",label:"Serve Winner",isServe:!0},{result:"Forced Error",label:"Forced Error",isError:!0},{result:"Unforced Error",label:"Unforced Error",isError:!0},{result:"Double Fault",label:"Double Fault",isServe:!0,isError:!0},{result:"Penalty",label:"Penalty"}]},pointMultipliers:[]}},DH={[ku]:{roundsToSeparate:void 0,policyName:"Nationality Code",policyAttributes:[{key:"person.nationalityCode"},{key:"individualParticipants.person.nationalityCode"}]}},RH={[Lu]:{policyName:"Standard DrawMatic Competition",ratingPolicy:{baselineRating:{source:"SCALE",frozenDuringEvent:!0},dynamicFormRating:{enabled:!0,initializeFrom:"BASELINE",kFactor:24,logisticScale:400}},pairingPolicy:{method:"DRAW_MATIC",ratingSource:"DYNAMIC_FORM",avoidRepeatOpponents:!0,sameTeamValue:100},victoryPolicy:{primaryRanking:"WINS",tiebreakOrder:["POINT_DIFFERENTIAL","HEAD_TO_HEAD","DYNAMIC_FORM_RATING"]},processingGranularity:"PER_ROUND"}},bH={[Lu]:{policyName:"Pressure DrawMatic Competition",ratingPolicy:{baselineRating:{source:"SCALE",frozenDuringEvent:!0},dynamicFormRating:{enabled:!0,initializeFrom:"BASELINE",kFactor:24,logisticScale:400},pressureRating:{enabled:!0,expectationSource:"BASELINE_ONLY",actualOutputMethod:"POINT_SHARE",weights:{pointShare:1,pointDifferential:0,contextFactor:0}}},pairingPolicy:{method:"DRAW_MATIC",ratingSource:"DYNAMIC_FORM",avoidRepeatOpponents:!0,sameTeamValue:100},victoryPolicy:{primaryRanking:"PRESSURE_RATING",tiebreakOrder:["HEAD_TO_HEAD_PRESSURE","POINT_DIFFERENTIAL","STRENGTH_OF_OPPOSITION"]},processingGranularity:"PER_MATCHUP"}},NH={[Lu]:{policyName:"Swiss Competition with Pressure",ratingPolicy:{baselineRating:{source:"SCALE",frozenDuringEvent:!0},dynamicFormRating:{enabled:!0,initializeFrom:"BASELINE",kFactor:24,logisticScale:400},pressureRating:{enabled:!0,expectationSource:"BASELINE_ONLY",actualOutputMethod:"POINT_SHARE",weights:{pointShare:1}}},pairingPolicy:{method:"SWISS",ratingSource:"DYNAMIC_FORM",avoidRepeatOpponents:!0},victoryPolicy:{primaryRanking:"WINS",tiebreakOrder:["BUCHHOLZ","SONNEBORN_BERGER","HEAD_TO_HEAD","PRESSURE_RATING"]},processingGranularity:"PER_ROUND"}},MH={[bu]:{policyName:"positionActionsUnrestricted",enabledStructures:[],otherFlightEntries:!0,disableRoundRestrictions:!0,activePositionOverrides:[AP,bP]}},AH={[bu]:{policyName:"positionActionsNoMovement",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[AP,MP,EP],disabledActions:[]}]}},EH={[bu]:{policyName:"positionActionsDisabled",enabledStructures:!1}},CH="ATP",OH="WTA",kH="ITF",FH="ITF_JUNIOR",xH="ITF_WHEELCHAIR",_H="TENNIS_EUROPE",LH="USTA",BH="UNSPECIFIED",VH={ATP:CH,WTA:OH,ITF:kH,ITF_JUNIOR:FH,ITF_WHEELCHAIR:xH,TENNIS_EUROPE:_H,USTA:LH,LTA:"LTA",FFT:"FFT",DTB:"DTB",PPA:"PPA",BWF:"BWF",UTR:"UTR",UNSPECIFIED:BH,POINTS_AUTHORITIES:[CH,OH,kH,FH,xH,_H,LH,"LTA","FFT","DTB","PPA","BWF","UTR",BH]},GH={rollingPeriodDays:364,separateByGender:!0,perCategory:!1,countingBuckets:[{bucketName:"Singles",eventTypes:[ts],bestOfCount:6,pointComponents:["positionPoints"]},{bucketName:"Doubles",eventTypes:[ns],bestOfCount:6,pointComponents:["positionPoints"],weight:.25}]},jH=[{profileName:"Junior Masters Singles",levels:[2],drawTypes:[ic],eventTypes:[ts],finishingPositionRanges:{1:75e3,2:45e3,3:32e3,4:25e3,5:2e4,6:18500,7:16500,8:15e3}},{profileName:"Grand Slam Singles",levels:[1],eventTypes:[ts],stages:[us],finishingPositionRanges:{1:1e5,2:7e4,4:49e3,8:3e4,16:18e3,32:9e3}},{profileName:"Grand Slam Qualifying Singles",levels:[1],eventTypes:[ts],stages:[ds],finishingPositionRanges:{1:3e3,2:2e3}},{profileName:"Grand Slam Doubles",levels:[1],eventTypes:[ns],stages:[us],finishingPositionRanges:{1:19e3,2:15200,4:11400,8:7600,16:3800}},{profileName:"European Championships Singles",levels:[3],eventTypes:[ts],stages:[us],finishingPositionRanges:{1:75e3,2:55e3,4:39500,8:25e3,16:14e3,32:7e3}},{profileName:"European Championships Doubles",levels:[3],eventTypes:[ns],stages:[us],finishingPositionRanges:{1:14e3,2:11200,4:8400,8:5600,16:2800}},{profileName:"Qualifying Singles",levels:[4,5,6,7,8,9],eventTypes:[ts],stages:[ds],finishingPositionRanges:{1:{level:{4:2e3,5:1250,6:650,7:350,8:250,9:175}},2:{level:{4:1e3,5:700,6:400,7:250,8:175,9:100}}}},{profileName:"Standard Singles",levels:[4,5,6,7,8,9],eventTypes:[ts],stages:[us],finishingPositionRanges:{1:{level:{4:5e4,5:3e4,6:2e4,7:1e4,8:6e3,9:3e3}},2:{level:{4:4e4,5:24e3,6:16e3,7:8e3,8:4800,9:2400}},4:{level:{4:3e4,5:18e3,6:12e3,7:6e3,8:3600,9:1800}},8:{level:{4:2e4,5:12e3,6:8e3,7:4e3,8:2400,9:1200}},16:{level:{4:1e4,5:6e3,6:4e3,7:2e3,8:1200,9:600}},32:{level:{4:5e3,5:3e3,6:2e3,7:1e3,8:600,9:300}}}},{profileName:"Standard Doubles",levels:[4,5,6,7,8,9],eventTypes:[ns],stages:[us],finishingPositionRanges:{1:{level:{4:9500,5:5700,6:3750,7:1875,8:1125,9:600}},2:{level:{4:7600,5:4600,6:3e3,7:1500,8:900,9:480}},4:{level:{4:5700,5:3400,6:2250,7:1125,8:675,9:360}},8:{level:{4:3800,5:2250,6:1500,7:750,8:450,9:240}},16:{level:{4:1900,5:1150,6:750,7:375,8:225,9:120}}}}],qH={[Mu]:{policyName:"ITF World Tennis Tour Juniors",policyVersion:"2025.01",pointsAuthority:FH,validDateRange:{startDate:"2025-01-01"},awardProfiles:jH,aggregationRules:GH,doublesAttribution:"fullToEach"}},WH=[{profileName:"ITF WTT Qualifying Singles",levels:[1,2,3,4],drawTypes:[Ls],eventTypes:[ts],stages:[ds],finishingPositionRanges:{1:{level:{1:4,2:3,3:3,4:2}},2:1}},{profileName:"ITF WTT Qualifying Doubles",levels:[1,2,3,4],drawTypes:[Ls],eventTypes:[ns],stages:[ds],finishingPositionRanges:{1:{level:{1:4,2:3,3:3,4:2}},2:1}}],$H={[Mu]:{policyName:"ITF World Tennis Tour 2020",policyVersion:"2020.01",pointsAuthority:kH,validDateRange:{startDate:"2020-01-01"},awardProfiles:WH,aggregationRules:{rollingPeriodDays:364,separateByGender:!0,perCategory:!1,bestOfCount:14},doublesAttribution:"fullToEach"}},HH={[Mu]:{policyName:"Basic Ranking Points",policyVersion:"1.0",awardProfiles:[{profileName:"Basic finishing position points",finishingPositionRanges:{1:100,2:70,4:50,8:30,16:15,32:8,64:4,128:1}}],requireWinForPoints:!0,doublesAttribution:"fullToEach"}},zH={rollingPeriodDays:364,separateByGender:!1,perCategory:!1,countingBuckets:[{bucketName:"Singles",eventTypes:[ts],bestOfCount:19,pointComponents:["positionPoints","perWinPoints","bonusPoints"],mandatoryRules:[{ruleName:"Grand Slams",levels:[1]},{ruleName:"ATP 1000",levels:[3,4]}]},{bucketName:"Doubles",eventTypes:[ns],bestOfCount:18,pointComponents:["positionPoints","perWinPoints","bonusPoints"]}]},YH=[{profileName:"ATP Finals Singles",levels:[2],drawTypes:[oc],eventTypes:[ts],finishingPositionPoints:{participationOrders:[2]},finishingPositionRanges:{1:900,2:400,4:0},perWinPoints:{participationOrders:[1],value:200}},{profileName:"ATP Finals Doubles",levels:[2],drawTypes:[oc],eventTypes:[ns],finishingPositionPoints:{participationOrders:[2]},finishingPositionRanges:{1:900,2:400,4:0},perWinPoints:{participationOrders:[1],value:200}},{profileName:"Grand Slam Singles",levels:[1],eventTypes:[ts],stages:[us],finishingPositionRanges:{1:2e3,2:1300,4:800,8:400,16:200,32:100,64:50,128:10}},{profileName:"Grand Slam Qualifying Singles",levels:[1],eventTypes:[ts],stages:[ds],finishingPositionRanges:{1:30,2:16,4:8}},{profileName:"Grand Slam Doubles",levels:[1],eventTypes:[ns],stages:[us],finishingPositionRanges:{1:2e3,2:1200,4:720,8:360,16:180,32:90}},{profileName:"ATP 1000 Singles",levels:[3,4],eventTypes:[ts],stages:[us],finishingPositionRanges:{1:1e3,2:650,4:400,8:200,16:100,32:50,64:{level:{3:30,4:10}},128:{level:{3:10}}}},{profileName:"ATP 1000 Doubles",levels:[3,4],eventTypes:[ns],stages:[us],finishingPositionRanges:{1:1e3,2:600,4:360,8:180,16:90}},{profileName:"ATP 500 Singles",levels:[5,6],eventTypes:[ts],stages:[us],finishingPositionRanges:{1:500,2:330,4:200,8:100,16:50,32:{level:{5:25}}}},{profileName:"ATP 500 Doubles",levels:[5,6],eventTypes:[ns],stages:[us],finishingPositionRanges:{1:500,2:300,4:180,8:90}},{profileName:"ATP 250 Singles",levels:[7,8],eventTypes:[ts],stages:[us],finishingPositionRanges:{1:250,2:165,4:100,8:50,16:25,32:{level:{7:13}}}},{profileName:"ATP 250 Doubles",levels:[7,8],eventTypes:[ns],stages:[us],finishingPositionRanges:{1:250,2:150,4:90,8:45,16:{level:{7:20}}}},{profileName:"Qualifying Singles",levels:[3,4,5,6,7,8,9,10,11,12,13],eventTypes:[ts],stages:[ds],finishingPositionRanges:{1:{level:{3:20,4:30,5:16,6:25,7:8,8:13,9:6,10:5,11:4,12:4,13:3}},2:{level:{3:10,4:16,5:8,6:13,7:4,8:7,9:3,10:3,11:2,12:2,13:1}}}},{profileName:"Challenger & ITF Singles",levels:[9,10,11,12,13,14,15],eventTypes:[ts],stages:[us],finishingPositionRanges:{1:{level:{9:175,10:125,11:100,12:75,13:50,14:25,15:15}},2:{level:{9:90,10:64,11:50,12:44,13:25,14:14,15:8}},4:{level:{9:50,10:35,11:25,12:22,13:14,14:7,15:4}},8:{level:{9:25,10:16,11:14,12:12,13:8,14:3,15:2}},16:{level:{9:13,10:8,11:7,12:6,13:4,14:1,15:1}}}},{profileName:"Challenger & ITF Doubles",levels:[9,10,11,12,13,14,15],eventTypes:[ns],stages:[us],finishingPositionRanges:{1:{level:{9:175,10:125,11:100,12:75,13:50,14:25,15:15}},2:{level:{9:100,10:75,11:60,12:50,13:30,14:14,15:8}},4:{level:{9:60,10:45,11:36,12:30,13:17,14:7,15:4}},8:{level:{9:32,10:25,11:20,12:16,13:9,14:3,15:2}}}},{profileName:"United Cup",eventTypes:[os],finishingPositionRanges:{1:500}}],KH={[Mu]:{policyName:"PIF ATP Rankings 2026",policyVersion:"2026.01",pointsAuthority:CH,validDateRange:{startDate:"2026-01-01"},awardProfiles:YH,aggregationRules:zH,doublesAttribution:"fullToEach"}},QH={rollingPeriodDays:364,separateByGender:!1,perCategory:!1,minCountableResults:3,countingBuckets:[{bucketName:"Singles",eventTypes:[ts],bestOfCount:19,pointComponents:["positionPoints","perWinPoints","bonusPoints"],mandatoryRules:[{ruleName:"Grand Slams",levels:[1]},{ruleName:"WTA 1000 Combined",levels:[3],bestOfCount:6}]},{bucketName:"Doubles",eventTypes:[ns],bestOfCount:12,pointComponents:["positionPoints","perWinPoints","bonusPoints"]}],tiebreakCriteria:["highestSingleResult","mostCountingResults"]},JH=[{profileName:"WTA Finals Singles",levels:[2],eventTypes:[ts],finishingPositionRanges:{1:1500,2:1080,4:750,8:375}},{profileName:"WTA Finals Doubles",levels:[2],eventTypes:[ns],finishingPositionRanges:{1:1500,2:1080,4:750,8:375}},{profileName:"Grand Slam Singles",levels:[1],eventTypes:[ts],stages:[us],finishingPositionRanges:{1:2e3,2:1300,4:780,8:430,16:240,32:130,64:70,128:10}},{profileName:"Grand Slam Doubles",levels:[1],eventTypes:[ns],stages:[us],finishingPositionRanges:{1:2e3,2:1300,4:780,8:430,16:240,32:130,64:10}},{profileName:"Grand Slam Doubles Qualifying",levels:[1],eventTypes:[ns],stages:[ds],finishingPositionRanges:{1:40}},{profileName:"WTA 1000 Singles",levels:[3],eventTypes:[ts],stages:[us],finishingPositionRanges:{1:1e3,2:650,4:390,8:215,16:120,32:65,64:[{drawSize:64,threshold:!0,value:35},{value:10}],128:10}},{profileName:"WTA 1000 Doubles",levels:[3],eventTypes:[ns],stages:[us],finishingPositionRanges:{1:1e3,2:650,4:390,8:215,16:120,32:10}},{profileName:"WTA 500 Singles",levels:[4],eventTypes:[ts],stages:[us],finishingPositionRanges:{1:500,2:325,4:195,8:108,16:60,32:[{drawSize:48,threshold:!0,value:32},{value:1}],64:1}},{profileName:"WTA 500 Doubles",levels:[4],eventTypes:[ns],stages:[us],finishingPositionRanges:{1:500,2:325,4:195,8:108,16:1}},{profileName:"WTA 250 Singles",levels:[5],eventTypes:[ts],stages:[us],finishingPositionRanges:{1:250,2:163,4:98,8:54,16:30,32:1}},{profileName:"WTA 125 Singles",levels:[6],eventTypes:[ts],stages:[us],finishingPositionRanges:{1:125,2:81,4:49,8:27,16:15,32:1}},{profileName:"WTA Qualifying Singles",levels:[1,3,4,5,6,7,8,9,10],eventTypes:[ts],stages:[ds],finishingPositionRanges:{1:{level:{1:40,3:30,4:25,5:18,6:6,7:5,8:3,9:2,10:1}},2:{level:{1:30,3:20,4:13,5:12,6:4,7:3,8:2,9:1}},4:{level:{1:20,3:2,4:1,5:1,6:1}},8:{level:{1:2}}}},{profileName:"ITF Circuit Singles",levels:[7,8,9,10,11],eventTypes:[ts],stages:[us],finishingPositionRanges:{1:{level:{7:100,8:75,9:50,10:35,11:15}},2:{level:{7:65,8:49,9:33,10:23,11:10}},4:{level:{7:39,8:29,9:20,10:14,11:6}},8:{level:{7:21,8:16,9:11,10:8,11:3}},16:[{drawSize:48,threshold:!0,level:{7:7,8:5,9:6,10:4,11:1}},{level:{7:12,8:9,9:6,10:3,11:1}}],32:[{drawSize:48,threshold:!0,level:{7:1,8:1,9:3,10:2}},{level:{7:1,8:1,9:1}}],64:{level:{9:1,10:1}}}},{profileName:"WTA 250–ITF W35 Doubles",levels:[5,6,7,8,9,10],eventTypes:[ns],stages:[us],finishingPositionRanges:{1:{level:{5:250,6:125,7:100,8:75,9:50,10:35}},2:{level:{5:163,6:81,7:65,8:49,9:33,10:23}},4:{level:{5:98,6:49,7:39,8:29,9:20,10:14}},8:{level:{5:54,6:27,7:21,8:16,9:11,10:8}},16:1}},{profileName:"ITF W15 Doubles",levels:[11],eventTypes:[ns],stages:[us],finishingPositionRanges:{1:15,2:10,4:6,8:3}}],XH={[Mu]:{policyName:"PIF WTA Rankings 2026",policyVersion:"2026.01",pointsAuthority:OH,validDateRange:{startDate:"2026-01-01"},awardProfiles:JH,aggregationRules:QH,doublesAttribution:"fullToEach"}},ZH={[Eu]:{policyName:"Participant Privacy Policy",participant:{contacts:!1,individualParticipants:{onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,rankings:!0,ratings:!0,representing:!0,participantRoleResponsibilities:!1,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}},individualParticipantIds:!0,onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,rankings:!0,ratings:!0,representing:!0,participantRoleResponsibilities:!1,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}}}},tz={policyName:"ITF_CHAIR_UMPIRE_EVALUATION",policyVersion:"1.0.0",organisationId:"ITF",officialRoleSubtype:"CHAIR_UMPIRE",scoringMethod:"WEIGHTED_AVERAGE",passingThreshold:3,sections:[{sectionId:"pre_match",sectionName:"Pre-match Preparation",weight:.2,criteria:[{criterionId:"rules_knowledge",criterionName:"Rules Knowledge",description:"Demonstrates thorough understanding of the Rules of Tennis and Code of Conduct",scoringType:"SCALE",scaleOptions:[...oj],required:!0,weight:.4},{criterionId:"court_preparation",criterionName:"Court Preparation",description:"Ensures court, equipment, and scoring systems are properly set up before the match",scoringType:"SCALE",scaleOptions:[...oj],required:!0,weight:.3},{criterionId:"equipment_check",criterionName:"Equipment Check",description:"Verifies net height, ball condition, and court surface",scoringType:"SCALE",scaleOptions:[...oj],required:!0,weight:.3}]},{sectionId:"match_management",sectionName:"Match Management",weight:.6,criteria:[{criterionId:"score_calling",criterionName:"Score Calling",description:"Clear, audible, and correct score announcements",scoringType:"SCALE",scaleOptions:[...oj],required:!0,weight:.25},{criterionId:"overrule_accuracy",criterionName:"Overrule Accuracy",description:"Appropriate and accurate overrules of line calls",scoringType:"SCALE",scaleOptions:[...oj],required:!0,weight:.25},{criterionId:"time_management",criterionName:"Time Management",description:"Enforces time violations and maintains match pace appropriately",scoringType:"SCALE",scaleOptions:[...oj],required:!0,weight:.25},{criterionId:"player_interactions",criterionName:"Player Interactions",description:"Professional, calm, and fair interactions with players",scoringType:"SCALE",scaleOptions:[...oj],required:!0,weight:.25}]},{sectionId:"post_match",sectionName:"Post-match",weight:.2,criteria:[{criterionId:"scorecard_accuracy",criterionName:"Scorecard Accuracy",description:"Complete and accurate scorecard with all required information",scoringType:"SCALE",scaleOptions:[...oj],required:!0,weight:.5},{criterionId:"incident_reporting",criterionName:"Incident Reporting",description:"Timely and thorough reporting of any incidents or code violations",scoringType:"SCALE",scaleOptions:[...oj],required:!1,weight:.3},{criterionId:"general_comments",criterionName:"General Comments",description:"Any additional observations or recommendations",scoringType:"TEXT",required:!1,weight:.2}]}]},ez={policyName:"ITF_REFEREE_EVALUATION",policyVersion:"1.0.0",organisationId:"ITF",officialRoleSubtype:"REFEREE",scoringMethod:"WEIGHTED_AVERAGE",passingThreshold:3,sections:[{sectionId:"tournament_preparation",sectionName:"Tournament Preparation",weight:.25,criteria:[{criterionId:"draw_management",criterionName:"Draw Management",description:"Correct draw creation, seeding, and qualification procedures",scoringType:"SCALE",scaleOptions:[...oj],required:!0,weight:.4},{criterionId:"schedule_planning",criterionName:"Schedule Planning",description:"Efficient and fair order of play scheduling",scoringType:"SCALE",scaleOptions:[...oj],required:!0,weight:.3},{criterionId:"official_management",criterionName:"Official Management",description:"Appropriate allocation and supervision of chair umpires and line umpires",scoringType:"SCALE",scaleOptions:[...oj],required:!0,weight:.3}]},{sectionId:"decision_making",sectionName:"Decision Making",weight:.4,criteria:[{criterionId:"rules_application",criterionName:"Rules Application",description:"Correct and consistent application of rules in disputes and appeals",scoringType:"SCALE",scaleOptions:[...oj],required:!0,weight:.35},{criterionId:"conflict_resolution",criterionName:"Conflict Resolution",description:"Effective handling of player disputes, defaults, and disciplinary matters",scoringType:"SCALE",scaleOptions:[...oj],required:!0,weight:.35},{criterionId:"weather_contingency",criterionName:"Weather & Contingency Management",description:"Handling of weather delays, court changes, and schedule adjustments",scoringType:"SCALE",scaleOptions:[...oj],required:!0,weight:.3}]},{sectionId:"administration",sectionName:"Administration & Reporting",weight:.2,criteria:[{criterionId:"results_reporting",criterionName:"Results Reporting",description:"Timely and accurate submission of tournament results",scoringType:"SCALE",scaleOptions:[...oj],required:!0,weight:.5},{criterionId:"documentation",criterionName:"Documentation",description:"Complete tournament report, incident logs, and official assessments",scoringType:"SCALE",scaleOptions:[...oj],required:!0,weight:.5}]},{sectionId:"overall",sectionName:"Overall Assessment",weight:.15,criteria:[{criterionId:"professionalism",criterionName:"Professionalism",description:"Professional demeanor, appearance, and communication throughout the tournament",scoringType:"SCALE",scaleOptions:[...oj],required:!0,weight:1},{criterionId:"referee_comments",criterionName:"Comments",description:"Additional observations, strengths, and areas for improvement",scoringType:"TEXT",required:!1}]}]},nz="Personal circumstance",rz={competitionFormats:wH,ratingsParameters:rp,matchUpFormats:Pa,countryToFlag:Tm,tieFormats:SC,countries:wm,policies:{POLICY_AVOIDANCE_COUNTRY:DH,POLICY_COMPETITION_STANDARD:RH,POLICY_COMPETITION_PRESSURE:bH,POLICY_COMPETITION_SWISS:NH,POLICY_POSITION_ACTIONS_DEFAULT:Ow,POLICY_POSITION_ACTIONS_DISABLED:EH,POLICY_POSITION_ACTIONS_NO_MOVEMENT:AH,POLICY_POSITION_ACTIONS_UNRESTRICTED:MH,POLICY_PRIVACY_DEFAULT:ZH,POLICY_RANKING_POINTS_ITF_JUNIOR:qH,POLICY_RANKING_POINTS_ITF_WTT:$H,POLICY_RANKING_POINTS_BASIC:HH,POLICY_RANKING_POINTS_ATP:KH,POLICY_RANKING_POINTS_WTA:XH,POLICY_ROUND_NAMING_DEFAULT:zf,POLICY_SCHEDULING_DEFAULT:kh,POLICY_SCORING_DEFAULT:{[Fu]:{processCodes:{incompleteAssignmentsOnDefault:["RANKING.IGNORE"]},defaultMatchUpFormat:va,allowDeletionWithScoresPresent:{drawDefinitions:!1,structures:!1},requireParticipantsForScoring:!1,requireAllPositionsAssigned:void 0,allowChangePropagation:!1,stage:{[us]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},matchUpFormats:[],matchUpStatusCodes:{[gp]:[],[yp]:[],[Pp]:[],[Rp]:[],[Np]:[],[Ep]:[]}}},POLICY_SCORING_USTA:{[Fu]:{requireAllPositionsAssigned:!1,stage:{[us]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},defaultMatchUpFormat:va,matchUpFormats:[{description:"Best of 3 tiebreak sets",matchUpFormat:va,categoryNames:[],categoryTypes:[]},{description:"Two tiebreak sets, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:6/TB7-F:TB7"},{description:"Two tiebreak sets, 10-point match tiebreak at one set all",matchUpFormat:"SET3-S:6/TB7-F:TB10"},{description:"One standard tiebreak set to 6, 7-point tiebreak at 6 games all",matchUpFormat:"SET1-S:6/TB7"},{description:"Best of 3 sets to 4",matchUpFormat:"SET3-S:4/TB7"},{description:"Two out of three short sets to 4 with 5-point tiebreak at 3 games all",matchUpFormat:"SET3-S:4/TB5@3"},{description:"One short set to 4, 7-point tiebreak at 4 games all",matchUpFormat:"SET1-S:4/TB7"},{description:"One short set to 4, 5-point tiebreak at 3 games all",matchUpFormat:"SET1-S:4/TB5@3"},{description:"Two short sets to 4, 10-point match tiebreak at one set all",matchUpFormat:"SET3-S:4/TB7-F:TB10"},{description:"Two short sets to 4, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:4/TB7-F:TB7"},{description:"One no advantage set to 5, tiebreak to 9 at 4-4",matchUpFormat:"SET1-S:5/TB9@4"},{description:"One set to 6 with deciding game at 5 games all",matchUpFormat:"SET1-S:6NOAD"},{description:"One short set to 4, deciding game is played at 3 games all",matchUpFormat:"SET1-S:4NOAD"},{description:"Two short sets to 4 with deciding game at 3-3, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:4NOAD-F:TB7"},{description:"8 game pro-set with 7 point tiebreak at 8 games all",matchUpFormat:"SET1-S:8/TB7"},{description:"8 game pro-set with 7 point tiebreak at 7 games all",matchUpFormat:"SET1-S:8/TB7@7"},{description:"Best of 3 10-point tiebreak games",matchUpFormat:"SET3-S:TB10"},{description:"One 10-point tiebreak game",matchUpFormat:"SET1-S:TB10"},{description:"Timed 20 minute game - game based",matchUpFormat:"SET1-S:T20"}],matchUpStatusCodes:{[gp]:[{matchUpStatusCodeDisplay:"Abandoned",label:"Abandoned match",matchUpStatusCode:"OA"}],[yp]:[{matchUpStatusCodeDisplay:"Unplayed or Cancelled",label:"Cancelled match",matchUpStatusCode:"OC"}],[Rp]:[{matchUpStatusCodeDisplay:"Incomplete",label:"Incomplete match",matchUpStatusCode:"OI"}],[Pp]:[{description:"Disqualification for cause or ineligibility",label:"Disqualification (ineligibility)",matchUpStatusCodeDisplay:"Def [dq]",matchUpStatusCode:"DQ"},{description:"Misconduct before or between matches",label:"Misconduct",matchUpStatusCodeDisplay:"Def [cond]",matchUpStatusCode:"DM"},{description:"Failure to start match because of adult discipline",label:"Fail. (adult discipline)",matchUpStatusCodeDisplay:"Def [ad]",matchUpStatusCode:"D5"},{description:"Refusal to start match for reason other than adult discipline, injury, illness, or personal circumstance. (After the Referee has conclusively confirmed that a player refuses to play a match, the Referee need not wait until the scheduled time of the match to records the result.)",label:"Refusal to start match",matchUpStatusCodeDisplay:"Def [refsl]",matchUpStatusCode:"D4"},{label:"Not showing up",matchUpStatusCodeDisplay:"Def [ns]",matchUpStatusCode:"D6"},{description:"Lateness for match including, but not limited to, intending to play but mistakenly arriving at the wrong time, location, or without proper equipment",label:"Lateness for match",matchUpStatusCodeDisplay:"Score + Def [late]",matchUpStatusCode:"D7"},{label:"Double default",matchUpStatusCodeDisplay:"Def/Def",matchUpStatusCode:"DD"},{description:"Refusal to continue playing a match for reason other than injury, illness, personal circumstance, or adult discipline",label:"Refusal to continue match",matchUpStatusCodeDisplay:"Def [refsl]",matchUpStatusCode:"D9"},{description:"Default for receiving an injection, IV, or supplemental oxygen",label:"Default (PEDs)",matchUpStatusCodeDisplay:"Def [med]",matchUpStatusCode:"DI"},{description:"Default under Point Penalty System",label:"Default (Point Penalty System)",matchUpStatusCodeDisplay:"Def [pps]",matchUpStatusCode:"DP"}],[Ep]:[{matchUpStatusCodeDisplay:"Wo [inj]",matchUpStatusCode:"W1",label:"Injury"},{matchUpStatusCodeDisplay:"Wo [ill]",matchUpStatusCode:"W2",label:"Illness"},{matchUpStatusCodeDisplay:"Wo [pc]",label:nz,matchUpStatusCode:"W3"},{matchUpStatusCodeDisplay:"Wo/Wo",matchUpStatusCode:"WOWO",label:"Double walkover"},{matchUpStatusCodeDisplay:"Wo [Tae]",label:"Tournament Administrative Error",matchUpStatusCode:"W4"},{matchUpStatusCodeDisplay:"Wo/Withdrawn",matchUpStatusCode:"W5",label:"Withdrawn"}],[Np]:[{matchUpStatusCodeDisplay:"Ret [inj]",matchUpStatusCode:"RJ",label:"Injury"},{matchUpStatusCodeDisplay:"Ret [ill]",matchUpStatusCode:"RI",label:"Illness"},{matchUpStatusCodeDisplay:"Ret [pc]",label:nz,matchUpStatusCode:"RC"},{description:"Retirement because of adult discipline",label:"Ret. (adult discipline)",matchUpStatusCodeDisplay:"Ret [ad]",matchUpStatusCode:"RD"},{description:"A player who retires from a match remains eligible for consolations, place playoffs, doubles and subsequent round robin matches",matchUpStatusCodeDisplay:"Ret [elg]",label:"Ret. (eligible)",matchUpStatusCode:"RU"}],[ff]:[{matchUpStatusCodeDisplay:"Wd [inj]",matchUpStatusCode:"WD.INJ",label:"Injury"},{matchUpStatusCodeDisplay:"Wd [ill]",matchUpStatusCode:"WD.ILL",label:"Illness"},{matchUpStatusCodeDisplay:"Wd [pc]",label:nz,matchUpStatusCode:"WD.PC"},{matchUpStatusCodeDisplay:"Wd/Wd",matchUpStatusCode:"WD.WD",label:"Double withdrawal"},{label:"Tournament Administrative Error",matchUpStatusCodeDisplay:"Wd [Tae]",matchUpStatusCode:"WD.TAE"}]}}},POLICY_SEEDING_ITF:{[xu]:{seedingProfile:{positioning:vs},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:HN,POLICY_OFFICIATING_EVALUATION_CHAIR_UMPIRE:tz,POLICY_OFFICIATING_EVALUATION_REFEREE:ez,POLICY_PRINT_DEFAULT:{[Vu]:{policyName:"Default Print Configuration"}}},flagIOC:function(t){return Tm(Object.assign({},...wm.filter(t=>t.ioc).map(t=>({[t.ioc]:t.iso})))[t])}},iz={INTENNSE_STANDARD:"INTENNSE_STANDARD",TENNIS_STANDARD:"TENNIS_STANDARD",MATCHUP:"MATCHUP",SET:"SET",HALF:"HALF",SEGMENT:"SEGMENT",BETWEEN_GAMES:"BETWEEN_GAMES",BETWEEN_POINTS:"BETWEEN_POINTS",ANY:"ANY"},oz={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"},az={CLAY:"CLAY",HARD:"HARD",GRASS:"GRASS",CARPET:"CARPET",ARTIFICIAL:"ARTIFICIAL"},sz={BUCHHOLZ:"BUCHHOLZ",MEDIAN_BUCHHOLZ:"MEDIAN_BUCHHOLZ",PROGRESSIVE_SCORE:"PROGRESSIVE_SCORE",RATING_BASED:"RATING_BASED",SCORE_GROUP:"SCORE_GROUP",SONNEBORN_BERGER:"SONNEBORN_BERGER"},cz={INDOOR:"INDOOR",OUTDOOR:"OUTDOOR"};var uz={__proto__:null,activeMatchUpStatuses:Lp,auditConstants:EC,competitionFormatConstants:iz,completedMatchUpStatuses:_p,directingMatchUpStatuses:Fp,displayConstants:Dw,drawDefinitionConstants:fc,entryStatusConstants:vf,errorConditionConstants:Er,eventConstants:cs,extensionConstants:Nd,flightConstants:uO,genderConstants:ji,keyValueConstants:Eb,matchUpActionConstants:nD,matchUpStatusConstants:Vp,matchUpTypes:c,nonDirectingMatchUpStatuses:xp,officiatingConstants:Sj,particicipantsRequiredMatchUpStatuses:Op,participantConstants:Um,participantRoles:my,participantTypes:vm,penaltyConstants:oz,pointsAuthorityConstants:VH,policyConstants:Gu,positionActionConstants:kP,rankingConstants:pM,ratingConstants:np,recoveryTimeRequiredMatchUpStatuses:Cp,reportConstants:AL,requestConstants:cF,resourceContants:sa,resultConstants:Q,sanctioningConstants:E$,scaleConstants:Uu,scheduleConstants:Qh,sortingConstants:IO,surfaceConstants:az,swissConstants:sz,tallyConstants:tf,tieFormatConstants:Qa,timeItemConstants:Dh,topicConstants:ql,tournamentConstants:vw,upcomingMatchUpStatuses:Bp,validMatchUpStatuses:kp,venueConstants:cz,weekdayConstants:VC};exports.AvailabilityEngine=QW,exports.EventNotFoundError=oW,exports.FactoryError=Hq,exports.InvalidDateError=eW,exports.InvalidValuesError=tW,exports.MatchUpNotFoundError=iW,exports.MissingDrawDefinitionError=Kq,exports.MissingEventError=Qq,exports.MissingOfficialRecordError=Zq,exports.MissingSanctioningRecordError=Xq,exports.MissingTournamentRecordError=zq,exports.MissingTournamentRecordsError=Yq,exports.MissingValueError=Jq,exports.ParticipantNotFoundError=nW,exports.StructureNotFoundError=rW,exports.activeMatchUpStatuses=Lp,exports.askEngine=GW,exports.asyncEngine=_W,exports.auditConstants=EC,exports.availability=JW,exports.availabilityGovernor=BG,exports.calculateMatchStatistics=SR,exports.competitionEngine=IH,exports.competitionEngineAsync=PH,exports.competitionEngineUntyped=yH,exports.competitionFormatConstants=iz,exports.competitionGovernor=Yp,exports.completedMatchUpStatuses=_p,exports.computeRatingDistributionStats=qM,exports.constructFactoryError=sW,exports.directingMatchUpStatuses=Fp,exports.displayConstants=Dw,exports.drawDefinitionConstants=fc,exports.drawsGovernor=oC,exports.dryRun=UW,exports.entriesGovernor=IC,exports.entryStatusConstants=vf,exports.errorConditionConstants=Er,exports.errors=cW,exports.eventConstants=cs,exports.eventGovernor=aO,exports.explain=PW,exports.extensionConstants=Nd,exports.factoryConstants=uz,exports.fixtures=rz,exports.flightConstants=uO,exports.forge={},exports.genderConstants=ji,exports.generatePatch=mW,exports.generationGovernor=NO,exports.globalState=Ai,exports.governors=Nq,exports.keyValueConstants=Eb,exports.matchUpActionConstants=nD,exports.matchUpEngine=$W,exports.matchUpFormatCode=MO,exports.matchUpFormatGovernor=MO,exports.matchUpGovernor=eF,exports.matchUpStatusConstants=Vp,exports.matchUpTypes=c,exports.mocksEngine=KW,exports.mocksGovernor=t_,exports.nonDirectingMatchUpStatuses=xp,exports.officiatingConstants=Sj,exports.officiatingEngine=gH,exports.officiatingGovernor=Wj,exports.particicipantsRequiredMatchUpStatuses=Op,exports.participantConstants=Um,exports.participantGovernor=A_,exports.participantRoles=my,exports.participantTypes=vm,exports.penaltyConstants=oz,exports.pointsAuthorityConstants=VH,exports.policyComposer=function(t){return jq({policyType:t,definition:{}})},exports.policyConstants=Gu,exports.policyGovernor=$N,exports.policyRegistry=AM,exports.positionActionConstants=kP,exports.practiceGovernor=aq,exports.publishingGovernor=q_,exports.queryGovernor=YE,exports.rankingConstants=pM,exports.rankingGovernor=iL,exports.ratingConstants=np,exports.recoveryTimeRequiredMatchUpStatuses=Cp,exports.registerSuggestions=Wq,exports.reportConstants=AL,exports.reportGovernor=qL,exports.requestConstants=cF,exports.resourceContants=sa,exports.resultConstants=Q,exports.sanctioningConstants=E$,exports.sanctioningEngine=sH,exports.scaleConstants=Uu,exports.scaleEngine=BW,exports.scheduleConstants=Qh,exports.scheduleGovernor=mB,exports.scoreGovernor=CN,exports.sortingConstants=IO,exports.surfaceConstants=az,exports.swissConstants=sz,exports.syncEngine=BW,exports.tallyConstants=tf,exports.tieFormatConstants=Qa,exports.tieFormatGovernor=_B,exports.timeItemConstants=Dh,exports.toStatObjects=wR,exports.tools=Oq,exports.topicConstants=ql,exports.tournamentConstants=vw,exports.tournamentEngine=SH,exports.tournamentEngineAsync=TH,exports.tournamentEngineUntyped=vH,exports.tournamentGovernor=wV,exports.unwrap=function(t,e){if(null==t)throw new Hq("ENGINE_RETURNED_UNDEFINED","engine returned no result",{methodName:e?.methodName});if(dW(t)){const n=t.error;if(n instanceof Hq)throw n;throw sW(n.code??"UNKNOWN_ERROR",n.message??"Unknown error returned by engine",{info:n.info,methodName:e?.methodName})}return t},exports.unwrapOr=function(t,e){return null==t||dW(t)?e:t},exports.upcomingMatchUpStatuses=Bp,exports.utilities=Oq,exports.validMatchUpStatuses=kp,exports.venueConstants=cz,exports.venueGovernor=bq,exports.version=t,exports.weekdayConstants=VC;
//# sourceMappingURL=tods-competition-factory.production.cjs.min.js.map