tods-competition-factory 2.0.0-alpha.1 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  function factoryVersion() {
6
- return '2.0.0-alpha.1';
6
+ return '2.0.0-beta.1';
7
7
  }
8
8
 
9
9
  /******************************************************************************
@@ -2103,141 +2103,6 @@ var eventConstants = {
2103
2103
  TEAM: TEAM$2,
2104
2104
  };
2105
2105
 
2106
- function getScaleValues(_a) {
2107
- var e_1, _b;
2108
- var _c;
2109
- var participant = _a.participant;
2110
- var scaleItems = (_c = participant.timeItems) === null || _c === void 0 ? void 0 : _c.filter(function (_a) {
2111
- var itemType = _a.itemType;
2112
- return (itemType === null || itemType === void 0 ? void 0 : itemType.startsWith(SCALE$1)) &&
2113
- [RANKING$1, RATING$2, SEEDING$1].includes(itemType.split('.')[1]);
2114
- });
2115
- var scales = { ratings: {}, rankings: {}, seedings: {} };
2116
- if (scaleItems === null || scaleItems === void 0 ? void 0 : scaleItems.length) {
2117
- var latestScaleItem = function (scaleType) {
2118
- return scaleItems
2119
- .filter(function (timeItem) { return (timeItem === null || timeItem === void 0 ? void 0 : timeItem.itemType) === scaleType; })
2120
- .sort(function (a, b) {
2121
- return new Date(a.createdAt || undefined).getTime() -
2122
- new Date(b.createdAt || undefined).getTime();
2123
- })
2124
- .pop();
2125
- };
2126
- var itemTypes = unique(scaleItems.map(function (_a) {
2127
- var itemType = _a.itemType;
2128
- return itemType;
2129
- }));
2130
- try {
2131
- for (var itemTypes_1 = __values(itemTypes), itemTypes_1_1 = itemTypes_1.next(); !itemTypes_1_1.done; itemTypes_1_1 = itemTypes_1.next()) {
2132
- var itemType = itemTypes_1_1.value;
2133
- var scaleItem = latestScaleItem(itemType);
2134
- if (scaleItem) {
2135
- var _d = __read(scaleItem.itemType.split('.'), 5), type = _d[1], format = _d[2], scaleName = _d[3], modifier = _d[4];
2136
- var namedScale = modifier ? "".concat(scaleName, ".").concat(modifier) : scaleName;
2137
- var scaleType = (type === SEEDING$1 && 'seedings') ||
2138
- (type === RANKING$1 && 'rankings') ||
2139
- 'ratings';
2140
- if (!scales[scaleType][format])
2141
- scales[scaleType][format] = [];
2142
- scales[scaleType][format].push({
2143
- scaleValue: scaleItem.itemValue,
2144
- scaleDate: scaleItem.itemDate,
2145
- scaleName: namedScale,
2146
- });
2147
- }
2148
- }
2149
- }
2150
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2151
- finally {
2152
- try {
2153
- if (itemTypes_1_1 && !itemTypes_1_1.done && (_b = itemTypes_1.return)) _b.call(itemTypes_1);
2154
- }
2155
- finally { if (e_1) throw e_1.error; }
2156
- }
2157
- }
2158
- return __assign(__assign({}, SUCCESS), scales);
2159
- }
2160
-
2161
- // NOTE: type really does need to be any!
2162
- function attributeFilter(params) {
2163
- if (params === null)
2164
- return {};
2165
- var _a = params || {}, source = _a.source, template = _a.template;
2166
- if (!template)
2167
- return source;
2168
- var target = {};
2169
- attributeCopy(source, template, target);
2170
- return target;
2171
- function attributeCopy(valuesObject, templateObject, outputObject) {
2172
- var e_1, _a;
2173
- if (!valuesObject || !templateObject)
2174
- return undefined;
2175
- var vKeys = Object.keys(valuesObject);
2176
- var oKeys = Object.keys(templateObject);
2177
- // the orMap allows spcification of { 'a||b': boolean } so that filter templates can apply to multiple attributes
2178
- var orMap = Object.assign.apply(Object, __spreadArray([{}], __read(oKeys
2179
- .filter(function (key) { return key.indexOf('||'); })
2180
- .map(function (key) { return key.split('||').map(function (or) {
2181
- var _a;
2182
- return (_a = {}, _a[or] = key, _a);
2183
- }); })
2184
- .flat()), false));
2185
- var allKeys = oKeys.concat.apply(oKeys, __spreadArray([], __read(Object.keys(orMap)), false));
2186
- var wildcard = allKeys.includes('*');
2187
- var _loop_1 = function (vKey) {
2188
- if (allKeys.indexOf(vKey) >= 0 || wildcard) {
2189
- var templateKey = orMap[vKey] || vKey;
2190
- var tobj_1 = templateObject[templateKey] || wildcard;
2191
- var vobj = valuesObject[vKey];
2192
- if (typeof tobj_1 === 'object' &&
2193
- typeof vobj !== 'function' &&
2194
- !Array.isArray(tobj_1)) {
2195
- if (Array.isArray(vobj)) {
2196
- var mappedElements = vobj
2197
- .map(function (arrayMember) {
2198
- var target = {};
2199
- var result = attributeCopy(arrayMember, tobj_1, target);
2200
- return result !== false ? target : undefined;
2201
- })
2202
- .filter(Boolean);
2203
- outputObject[vKey] = mappedElements;
2204
- }
2205
- else if (vobj) {
2206
- outputObject[vKey] = {};
2207
- attributeCopy(vobj, tobj_1, outputObject[vKey]);
2208
- }
2209
- }
2210
- else {
2211
- var value = valuesObject[vKey];
2212
- var exclude = Array.isArray(tobj_1) && !tobj_1.includes(value);
2213
- if (exclude)
2214
- return { value: false };
2215
- if (templateObject[vKey] ||
2216
- (wildcard && templateObject[vKey] !== false)) {
2217
- outputObject[vKey] = value;
2218
- }
2219
- }
2220
- }
2221
- };
2222
- try {
2223
- for (var vKeys_1 = __values(vKeys), vKeys_1_1 = vKeys_1.next(); !vKeys_1_1.done; vKeys_1_1 = vKeys_1.next()) {
2224
- var vKey = vKeys_1_1.value;
2225
- var state_1 = _loop_1(vKey);
2226
- if (typeof state_1 === "object")
2227
- return state_1.value;
2228
- }
2229
- }
2230
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2231
- finally {
2232
- try {
2233
- if (vKeys_1_1 && !vKeys_1_1.done && (_a = vKeys_1.return)) _a.call(vKeys_1);
2234
- }
2235
- finally { if (e_1) throw e_1.error; }
2236
- }
2237
- return undefined;
2238
- }
2239
- }
2240
-
2241
2106
  var validDateString = /^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/;
2242
2107
  var validTimeString = /^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/;
2243
2108
  var dateValidation = /^([\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?$/;
@@ -2669,238 +2534,6 @@ function extensionsToAttributes(extensions) {
2669
2534
  }).filter(Boolean);
2670
2535
  }
2671
2536
 
2672
- var POLICY_TYPE_VOLUNTARY_CONSOLATION = 'voluntaryConsolation';
2673
- var POLICY_TYPE_COMPETITIVE_BANDS = 'competitiveBands';
2674
- var POLICY_TYPE_ROUND_ROBIN_TALLY = 'roundRobinTally';
2675
- var POLICY_TYPE_POSITION_ACTIONS = 'positionActions';
2676
- var POLICY_TYPE_MATCHUP_ACTIONS = 'matchUpActions';
2677
- var POLICY_TYPE_RANKING_POINTS = 'rankingPoints';
2678
- var POLICY_TYPE_ROUND_NAMING = 'roundNaming';
2679
- var POLICY_TYPE_PARTICIPANT = 'participant';
2680
- var POLICY_TYPE_PROGRESSION = 'progression';
2681
- var POLICY_TYPE_SCHEDULING = 'scheduling';
2682
- var POLICY_TYPE_AVOIDANCE = 'avoidance';
2683
- var POLICY_TYPE_DISPLAY = 'display'; // storage for client type displays, e.g. { public: {}, admin: {} }
2684
- var POLICY_TYPE_SCORING = 'scoring';
2685
- var POLICY_TYPE_SEEDING = 'seeding';
2686
- var POLICY_TYPE_FEED_IN = 'feedIn';
2687
- var POLICY_TYPE_AUDIT = 'audit';
2688
- var POLICY_TYPE_DRAWS = 'draws';
2689
- var policyConstants = {
2690
- POLICY_TYPE_VOLUNTARY_CONSOLATION: POLICY_TYPE_VOLUNTARY_CONSOLATION,
2691
- POLICY_TYPE_COMPETITIVE_BANDS: POLICY_TYPE_COMPETITIVE_BANDS,
2692
- POLICY_TYPE_ROUND_ROBIN_TALLY: POLICY_TYPE_ROUND_ROBIN_TALLY,
2693
- POLICY_TYPE_POSITION_ACTIONS: POLICY_TYPE_POSITION_ACTIONS,
2694
- POLICY_TYPE_MATCHUP_ACTIONS: POLICY_TYPE_MATCHUP_ACTIONS,
2695
- POLICY_TYPE_RANKING_POINTS: POLICY_TYPE_RANKING_POINTS,
2696
- POLICY_TYPE_ROUND_NAMING: POLICY_TYPE_ROUND_NAMING,
2697
- POLICY_TYPE_PARTICIPANT: POLICY_TYPE_PARTICIPANT,
2698
- POLICY_TYPE_PROGRESSION: POLICY_TYPE_PROGRESSION,
2699
- POLICY_TYPE_SCHEDULING: POLICY_TYPE_SCHEDULING,
2700
- POLICY_TYPE_AVOIDANCE: POLICY_TYPE_AVOIDANCE,
2701
- POLICY_TYPE_DISPLAY: POLICY_TYPE_DISPLAY,
2702
- POLICY_TYPE_FEED_IN: POLICY_TYPE_FEED_IN,
2703
- POLICY_TYPE_SCORING: POLICY_TYPE_SCORING,
2704
- POLICY_TYPE_SEEDING: POLICY_TYPE_SEEDING,
2705
- POLICY_TYPE_AUDIT: POLICY_TYPE_AUDIT,
2706
- POLICY_TYPE_DRAWS: POLICY_TYPE_DRAWS,
2707
- };
2708
-
2709
- function findParticipant(_a) {
2710
- var _b = _a.tournamentParticipants, tournamentParticipants = _b === void 0 ? [] : _b, _c = _a.policyDefinitions, policyDefinitions = _c === void 0 ? {} : _c, contextProfile = _a.contextProfile, participantId = _a.participantId, internalUse = _a.internalUse, personId = _a.personId;
2711
- var foundParticipant = tournamentParticipants.find(function (candidate) {
2712
- return (participantId && candidate.participantId === participantId) ||
2713
- (personId && candidate.person && candidate.person.personId === personId);
2714
- });
2715
- var participant = makeDeepCopy(foundParticipant, false, internalUse);
2716
- if (participant) {
2717
- var participantAttributes = policyDefinitions === null || policyDefinitions === void 0 ? void 0 : policyDefinitions[POLICY_TYPE_PARTICIPANT];
2718
- if (contextProfile === null || contextProfile === void 0 ? void 0 : contextProfile.withScaleValues) {
2719
- var _d = getScaleValues({ participant: participant }), ratings = _d.ratings, rankings = _d.rankings;
2720
- participant.rankings = rankings;
2721
- participant.ratings = ratings;
2722
- }
2723
- if (participantAttributes === null || participantAttributes === void 0 ? void 0 : participantAttributes.participant) {
2724
- return attributeFilter({
2725
- template: participantAttributes.participant,
2726
- source: participant,
2727
- });
2728
- }
2729
- }
2730
- return participant;
2731
- }
2732
-
2733
- function addTournamentExtension(params) {
2734
- if (!params || typeof params !== 'object')
2735
- return { error: MISSING_VALUE };
2736
- if (!params.tournamentRecord)
2737
- return { error: MISSING_TOURNAMENT_RECORD };
2738
- return addExtension({
2739
- creationTime: params.creationTime,
2740
- element: params.tournamentRecord,
2741
- extension: params.extension,
2742
- });
2743
- }
2744
- function addDrawDefinitionExtension(params) {
2745
- if (!params || typeof params !== 'object')
2746
- return { error: MISSING_VALUE };
2747
- if (!params.drawDefinition)
2748
- return { error: DRAW_DEFINITION_NOT_FOUND };
2749
- return addExtension({
2750
- creationTime: params.creationTime,
2751
- element: params.drawDefinition,
2752
- extension: params.extension,
2753
- });
2754
- }
2755
- function addEventExtension(params) {
2756
- if (!params || typeof params !== 'object')
2757
- return { error: MISSING_VALUE };
2758
- if (!params.event)
2759
- return { error: EVENT_NOT_FOUND };
2760
- return addExtension({
2761
- creationTime: params.creationTime,
2762
- extension: params.extension,
2763
- element: params.event,
2764
- });
2765
- }
2766
- function addParticipantExtension(params) {
2767
- var _a;
2768
- if (!params || typeof params !== 'object')
2769
- return { error: MISSING_VALUE };
2770
- if (!params.participantId)
2771
- return { error: MISSING_PARTICIPANT_ID };
2772
- var tournamentParticipants = ((_a = params.tournamentRecord) === null || _a === void 0 ? void 0 : _a.participants) || [];
2773
- var participant = findParticipant({
2774
- participantId: params.participantId,
2775
- tournamentParticipants: tournamentParticipants,
2776
- });
2777
- if (!participant)
2778
- return { error: PARTICIPANT_NOT_FOUND };
2779
- return addExtension({
2780
- creationTime: params.creationTime,
2781
- extension: params.extension,
2782
- element: participant,
2783
- });
2784
- }
2785
- function removeTournamentExtension(params) {
2786
- if (!params || typeof params !== 'object')
2787
- return { error: MISSING_VALUE };
2788
- if (!params.tournamentRecord)
2789
- return { error: MISSING_TOURNAMENT_RECORD };
2790
- return removeExtension({
2791
- element: params.tournamentRecord,
2792
- name: params.name,
2793
- });
2794
- }
2795
- function removeDrawDefinitionExtension(params) {
2796
- if (!params || typeof params !== 'object')
2797
- return { error: MISSING_VALUE };
2798
- if (!params.drawDefinition)
2799
- return { error: DRAW_DEFINITION_NOT_FOUND };
2800
- return removeExtension({ element: params.drawDefinition, name: params.name });
2801
- }
2802
- function removeEventExtension(params) {
2803
- if (!params || typeof params !== 'object')
2804
- return { error: MISSING_VALUE };
2805
- if (!(params === null || params === void 0 ? void 0 : params.event))
2806
- return { error: EVENT_NOT_FOUND };
2807
- return removeExtension({ element: params.event, name: params.name });
2808
- }
2809
- function removeParticipantExtension(params) {
2810
- var _a;
2811
- if (!params || typeof params !== 'object')
2812
- return { error: MISSING_VALUE };
2813
- if (!params.participantId)
2814
- return { error: MISSING_PARTICIPANT_ID };
2815
- var tournamentParticipants = ((_a = params.tournamentRecord) === null || _a === void 0 ? void 0 : _a.participants) || [];
2816
- var participant = findParticipant({
2817
- participantId: params.participantId,
2818
- tournamentParticipants: tournamentParticipants,
2819
- });
2820
- if (!participant)
2821
- return { error: PARTICIPANT_NOT_FOUND };
2822
- return removeExtension({ element: participant, name: params.name });
2823
- }
2824
-
2825
- var ACTIVE_SUSPENSION = 'activeSuspension';
2826
- var APPLIED_POLICIES = 'appliedPolicies';
2827
- var AUDIT_POSITION_ACTIONS = 'positionActions';
2828
- var CONTEXT = 'context';
2829
- var DELEGATED_OUTCOME = 'delegatedOutcome';
2830
- var DISABLED = 'disabled';
2831
- var DISABLE_LINKS = 'disableLinks';
2832
- var DISABLE_AUTO_CALC = 'disableAutoCalc';
2833
- var DRAW_DELETIONS = 'drawDeletions';
2834
- var DRAW_PROFILE = 'drawProfile';
2835
- var ENTRY_PROFILE = 'entryProfile';
2836
- var EVENT_PROFILE = 'eventProfile';
2837
- var EVENT_WITHDRAWAL_REQUESTS = 'eventWithdrawalRequests';
2838
- var FACTORY$1 = 'factory';
2839
- var FLIGHT_PROFILE = 'flightProfile';
2840
- var GROUPING_ATTRIBUTE = 'groupingAttribute';
2841
- var LINEUPS = 'lineUps';
2842
- var LINKED_TOURNAMENTS = 'linkedTournamentsIds';
2843
- var MATCHUP_HISTORY = 'matchUpHistory';
2844
- var PARTICIPANT_REPRESENTATIVES = 'participantRepresentatives';
2845
- var PERSON_REQUESTS = 'personRequests';
2846
- var RANKING_POINTS = 'rankingPoints';
2847
- var ROUND_TARGET = 'roundTarget';
2848
- var SCHEDULE_LIMITS = 'scheduleLimits';
2849
- var SCHEDULE_TIMING = 'scheduleTiming';
2850
- var SCHEDULING_PROFILE = 'schedulingProfile';
2851
- var STATUS_DETAIL = 'statusDetail';
2852
- var SUB_ORDER = 'subOrder';
2853
- var TALLY = 'tally';
2854
- var TIE_FORMAT_MODIFICATIONS = 'tieFormatModification';
2855
- var extensionConstants = {
2856
- ACTIVE_SUSPENSION: ACTIVE_SUSPENSION,
2857
- APPLIED_POLICIES: APPLIED_POLICIES,
2858
- AUDIT_POSITION_ACTIONS: AUDIT_POSITION_ACTIONS,
2859
- CONTEXT: CONTEXT, // used to capture, e.g. context in which a venue was added
2860
- DELEGATED_OUTCOME: DELEGATED_OUTCOME,
2861
- DISABLED: DISABLED,
2862
- DISABLE_LINKS: DISABLE_LINKS,
2863
- DISABLE_AUTO_CALC: DISABLE_AUTO_CALC,
2864
- DRAW_DELETIONS: DRAW_DELETIONS,
2865
- DRAW_PROFILE: DRAW_PROFILE,
2866
- ENTRY_PROFILE: ENTRY_PROFILE, // used for drawGeneration; not relevant for anonymized tournaments
2867
- EVENT_PROFILE: EVENT_PROFILE,
2868
- EVENT_WITHDRAWAL_REQUESTS: EVENT_WITHDRAWAL_REQUESTS,
2869
- FLIGHT_PROFILE: FLIGHT_PROFILE,
2870
- GROUPING_ATTRIBUTE: GROUPING_ATTRIBUTE, // for generating teams; not relevant for anonymized tournaments
2871
- LINEUPS: LINEUPS,
2872
- LINKED_TOURNAMENTS: LINKED_TOURNAMENTS,
2873
- MATCHUP_HISTORY: MATCHUP_HISTORY,
2874
- PARTICIPANT_REPRESENTATIVES: PARTICIPANT_REPRESENTATIVES,
2875
- PERSON_REQUESTS: PERSON_REQUESTS,
2876
- RANKING_POINTS: RANKING_POINTS, // for attaching points awarded to tournamentRecord
2877
- ROUND_TARGET: ROUND_TARGET,
2878
- SCHEDULE_LIMITS: SCHEDULE_LIMITS,
2879
- SCHEDULE_TIMING: SCHEDULE_TIMING,
2880
- SCHEDULING_PROFILE: SCHEDULING_PROFILE,
2881
- STATUS_DETAIL: STATUS_DETAIL, // attached to event.entries
2882
- SUB_ORDER: SUB_ORDER,
2883
- TALLY: TALLY,
2884
- TIE_FORMAT_MODIFICATIONS: TIE_FORMAT_MODIFICATIONS, // for auditing, not important when anonymized
2885
- FACTORY: FACTORY$1,
2886
- };
2887
- var internalExtensions = [
2888
- DELEGATED_OUTCOME,
2889
- DISABLED,
2890
- DISABLE_LINKS,
2891
- FLIGHT_PROFILE,
2892
- LINEUPS,
2893
- MATCHUP_HISTORY,
2894
- PARTICIPANT_REPRESENTATIVES,
2895
- PERSON_REQUESTS,
2896
- ROUND_TARGET,
2897
- SCHEDULE_LIMITS,
2898
- SCHEDULE_TIMING,
2899
- SCHEDULING_PROFILE,
2900
- SUB_ORDER,
2901
- TALLY,
2902
- ];
2903
-
2904
2537
  function getAccessorValue(_a) {
2905
2538
  var element = _a.element, accessor = _a.accessor;
2906
2539
  if (typeof accessor !== 'string')
@@ -3091,94 +2724,625 @@ function generateHashCode(o) {
3091
2724
  return [str.length, keyCount, charSum].map(function (e) { return e.toString(36); }).join('');
3092
2725
  }
3093
2726
 
3094
- function getTournamentIds(_a) {
3095
- var tournamentRecords = _a.tournamentRecords;
3096
- var tournamentIds = isObject(tournamentRecords)
3097
- ? Object.keys(tournamentRecords)
3098
- : [];
3099
- return __assign({ tournamentIds: tournamentIds }, SUCCESS);
3100
- }
2727
+ var TOURNAMENT_RECORDS = 'tournamentRecords';
2728
+ var POLICY_DEFINITIONS = 'policyDefinitions';
2729
+ var TOURNAMENT_RECORD = 'tournamentRecord';
2730
+ var DRAW_DEFINITION = 'drawDefinition';
2731
+ var MATCHUP_FORMAT = 'matchUpFormat';
2732
+ var PARTICIPANT_ID = 'participantId';
2733
+ var SCHEDULE_DATES = 'scheduleDates';
2734
+ var TOURNAMENT_ID = 'tournamentId';
2735
+ var SCHEDULE_DATE = 'scheduleDate';
2736
+ var STRUCTURE_ID = 'structureId';
2737
+ var PARTICIPANT = 'participant';
2738
+ var MATCHUP_IDS = 'matchUpIds';
2739
+ var POLICY_TYPE = 'policyType';
2740
+ var STRUCTURES = 'structures';
2741
+ var MATCHUP_ID = 'matchUpId';
2742
+ var IN_CONTEXT = 'inContext';
2743
+ var STRUCTURE = 'structure';
2744
+ var COURT_IDS = 'courtIds';
2745
+ var PERSON_ID = 'personId';
2746
+ var VENUE_IDS = 'venueIds';
2747
+ var MATCHUPS = 'matchUps';
2748
+ var COURT_ID = 'courtId';
2749
+ var EVENT_ID = 'eventId';
2750
+ var MATCHUP = 'matchUp';
2751
+ var DRAW_ID = 'drawId';
2752
+ var ERROR = 'error';
2753
+ var EVENT = 'event';
2754
+ var PARAM = 'param';
2755
+ var AVERAGE_MATCHUP_MINUTES = 'averageMatchUpMinutes';
2756
+ var RECOVERY_MINUTES = 'recoveryMinutes';
2757
+ var PERIOD_LENGTH = 'periodLength';
2758
+ var OBJECT = 'object';
2759
+ var ARRAY = 'array';
2760
+ var VALIDATE = 'validate';
2761
+ var INVALID = 'invalid';
2762
+ var OF_TYPE = '_ofType';
2763
+ var ANY_OF = '_anyOf';
2764
+ var ONE_OF = '_oneOf';
3101
2765
 
3102
- /**
3103
- * Links all tournaments which are currently loaded into competitionEngine state
3104
- */
3105
- function linkTournaments(_a) {
3106
- var tournamentRecords = _a.tournamentRecords;
3107
- if (typeof tournamentRecords !== 'object' ||
3108
- !Object.keys(tournamentRecords).length)
3109
- return { error: MISSING_TOURNAMENT_RECORDS };
3110
- var result = getTournamentIds({ tournamentRecords: tournamentRecords });
3111
- var tournamentIds = result.tournamentIds;
3112
- if ((tournamentIds === null || tournamentIds === void 0 ? void 0 : tournamentIds.length) > 1) {
3113
- var extension = {
3114
- name: LINKED_TOURNAMENTS,
3115
- value: { tournamentIds: tournamentIds },
3116
- };
3117
- return addExtension({
3118
- tournamentRecords: tournamentRecords,
3119
- discover: true,
3120
- extension: extension,
3121
- });
3122
- }
3123
- return __assign({}, SUCCESS);
3124
- }
3125
- function unlinkTournaments(_a) {
3126
- var tournamentRecords = _a.tournamentRecords;
3127
- if (typeof tournamentRecords !== 'object' ||
3128
- !Object.keys(tournamentRecords).length)
3129
- return { error: MISSING_TOURNAMENT_RECORDS };
3130
- var result = removeExtension({
3131
- name: LINKED_TOURNAMENTS,
3132
- tournamentRecords: tournamentRecords,
3133
- discover: true,
2766
+ var _a$k, _b$8;
2767
+ var errors = (_a$k = {},
2768
+ _a$k[TOURNAMENT_RECORDS] = MISSING_TOURNAMENT_RECORDS,
2769
+ _a$k[TOURNAMENT_RECORD] = MISSING_TOURNAMENT_RECORD,
2770
+ _a$k[POLICY_DEFINITIONS] = MISSING_POLICY_DEFINITION,
2771
+ _a$k[DRAW_DEFINITION] = MISSING_DRAW_DEFINITION,
2772
+ _a$k[PARTICIPANT_ID] = MISSING_PARTICIPANT_ID,
2773
+ _a$k[TOURNAMENT_ID] = MISSING_TOURNAMENT_ID,
2774
+ _a$k[STRUCTURE_ID] = MISSING_STRUCTURE_ID,
2775
+ _a$k[MATCHUP_IDS] = MISSING_MATCHUP_IDS,
2776
+ _a$k[PARTICIPANT] = MISSING_PARTICIPANT,
2777
+ _a$k[STRUCTURES] = MISSING_STRUCTURES,
2778
+ _a$k[MATCHUP_ID] = MISSING_MATCHUP_ID,
2779
+ _a$k[STRUCTURE] = MISSING_STRUCTURE,
2780
+ _a$k[COURT_ID] = MISSING_COURT_ID,
2781
+ _a$k[MATCHUPS] = MISSING_MATCHUPS,
2782
+ _a$k[MATCHUP] = MISSING_MATCHUP,
2783
+ _a$k[COURT_IDS] = MISSING_VALUE,
2784
+ _a$k[VENUE_IDS] = MISSING_VALUE,
2785
+ _a$k[DRAW_ID] = MISSING_DRAW_ID,
2786
+ _a$k[EVENT_ID] = MISSING_EVENT,
2787
+ _a$k[EVENT] = EVENT_NOT_FOUND,
2788
+ _a$k);
2789
+ var paramTypes = (_b$8 = {},
2790
+ _b$8[TOURNAMENT_RECORDS] = OBJECT,
2791
+ _b$8[POLICY_DEFINITIONS] = OBJECT,
2792
+ _b$8[TOURNAMENT_RECORD] = OBJECT,
2793
+ _b$8[DRAW_DEFINITION] = OBJECT,
2794
+ _b$8[SCHEDULE_DATES] = ARRAY,
2795
+ _b$8[PARTICIPANT] = OBJECT,
2796
+ _b$8[MATCHUP_IDS] = ARRAY,
2797
+ _b$8[STRUCTURES] = ARRAY,
2798
+ _b$8[STRUCTURE] = OBJECT,
2799
+ _b$8[COURT_IDS] = ARRAY,
2800
+ _b$8[VENUE_IDS] = ARRAY,
2801
+ _b$8[MATCHUPS] = ARRAY,
2802
+ _b$8[MATCHUP] = OBJECT,
2803
+ _b$8[EVENT] = OBJECT,
2804
+ _b$8);
2805
+ function checkRequiredParameters(params, requiredParams, stack) {
2806
+ if (!params && !isObject(params))
2807
+ return { error: INVALID_VALUES };
2808
+ if (!(requiredParams === null || requiredParams === void 0 ? void 0 : requiredParams.length) || (params === null || params === void 0 ? void 0 : params._bypassParamCheck))
2809
+ return { valid: true };
2810
+ if (!Array.isArray(requiredParams))
2811
+ return { error: INVALID_VALUES };
2812
+ var _a = findParamError(params, requiredParams), paramError = _a.paramError, errorParam = _a.errorParam;
2813
+ if (!paramError)
2814
+ return { valid: true };
2815
+ var error = params[errorParam] === undefined
2816
+ ? errors[errorParam] || INVALID_VALUES
2817
+ : (paramError.validate && paramError.invalid) || INVALID_VALUES;
2818
+ return decorateResult({
2819
+ info: { param: errorParam },
2820
+ result: { error: error },
2821
+ stack: stack,
3134
2822
  });
3135
- // TODO: check the integrity of the venues attached to each tournment...
3136
- // get all competitionScheduleMatchUps and ensure that each tournamentRecord has all venues for scheduled matchUps
3137
- return decorateResult({ result: result, stack: 'unlinkTournaments' });
3138
2823
  }
3139
- function unlinkTournament(_a) {
3140
- var tournamentRecords = _a.tournamentRecords, tournamentId = _a.tournamentId;
3141
- if (typeof tournamentRecords !== 'object')
2824
+ function getIntersection(params, constraint) {
2825
+ var paramKeys = Object.keys(params);
2826
+ var constraintKeys = Object.keys(constraint);
2827
+ return intersection(paramKeys, constraintKeys);
2828
+ }
2829
+ function getOneOf(params, _oneOf) {
2830
+ if (!_oneOf)
2831
+ return;
2832
+ var overlap = getIntersection(params, _oneOf);
2833
+ if (overlap.length !== 1)
3142
2834
  return { error: INVALID_VALUES };
3143
- if (!tournamentId)
3144
- return { error: MISSING_TOURNAMENT_ID };
3145
- var result = getTournamentIds({ tournamentRecords: tournamentRecords });
3146
- var tournamentIds = result.tournamentIds;
3147
- if (!tournamentIds.includes(tournamentId))
3148
- return { error: MISSING_TOURNAMENT_ID };
3149
- // not using bulk update function here to handle scenario where
3150
- // tournamentRecords loaded into state are not all linked
3151
- var unlinkError;
3152
- tournamentIds.every(function (currentTournamentId) {
2835
+ return overlap.reduce(function (attr, param) {
3153
2836
  var _a;
3154
- var tournamentRecord = tournamentRecords[currentTournamentId];
3155
- var extension = findExtension({
3156
- element: tournamentRecord,
3157
- name: LINKED_TOURNAMENTS,
3158
- }).extension;
3159
- // if there is no extension return { ...SUCCESS } because no links exist
3160
- if (!extension)
3161
- return true;
3162
- var linkedTournamentIds = ((_a = extension === null || extension === void 0 ? void 0 : extension.value) === null || _a === void 0 ? void 0 : _a.tournamentIds) || [];
3163
- // if there are no tournamentIds
3164
- if (!(linkedTournamentIds === null || linkedTournamentIds === void 0 ? void 0 : linkedTournamentIds.length) ||
3165
- (linkedTournamentIds.length === 1 &&
3166
- linkedTournamentIds.includes(tournamentId)) ||
3167
- currentTournamentId === tournamentId) {
3168
- var result_1 = removeTournamentExtension({
3169
- name: LINKED_TOURNAMENTS,
3170
- tournamentRecord: tournamentRecord,
3171
- });
3172
- if (result_1.error)
3173
- unlinkError = result_1.error;
3174
- return result_1.success;
3175
- }
3176
- var tournamentIds = linkedTournamentIds.filter(function (linkedTournamentId) { return linkedTournamentId !== tournamentId; });
3177
- extension.value = { tournamentIds: tournamentIds };
3178
- var result = addTournamentExtension({ tournamentRecord: tournamentRecord, extension: extension });
3179
- if (result.error)
3180
- unlinkError = result.error;
3181
- return result.success;
2837
+ return (__assign(__assign({}, attr), (_a = {}, _a[param] = true, _a)));
2838
+ }, {});
2839
+ }
2840
+ function getAnyOf(params, _anyOf) {
2841
+ if (!_anyOf)
2842
+ return;
2843
+ var overlap = getIntersection(params, _anyOf).filter(function (param) { return params[param]; });
2844
+ if (overlap.length < 1)
2845
+ return { error: INVALID_VALUES };
2846
+ return overlap.reduce(function (attr, param) {
2847
+ var _a;
2848
+ return (__assign(__assign({}, attr), (_a = {}, _a[param] = true, _a)));
2849
+ }, {});
2850
+ }
2851
+ function findParamError(params, requiredParams) {
2852
+ var errorParam;
2853
+ var paramError = requiredParams.find(function (_a) {
2854
+ var _ofType = _a._ofType, _oneOf = _a._oneOf, _anyOf = _a._anyOf, validate = _a.validate, attrs = __rest(_a, ["_ofType", "_oneOf", "_anyOf", "validate"]);
2855
+ var oneOf = _oneOf && getOneOf(params, _oneOf);
2856
+ if (oneOf === null || oneOf === void 0 ? void 0 : oneOf.error)
2857
+ return oneOf.error;
2858
+ oneOf && Object.assign(attrs, oneOf);
2859
+ var anyOf = _anyOf && getAnyOf(params, _anyOf);
2860
+ if (anyOf === null || anyOf === void 0 ? void 0 : anyOf.error)
2861
+ return anyOf.error;
2862
+ anyOf && Object.assign(attrs, anyOf);
2863
+ var booleanParams = Object.keys(attrs).filter(function (key) { return typeof attrs[key] === 'boolean'; });
2864
+ var invalidParam = booleanParams.find(function (param) {
2865
+ var invalid = !isFunction(validate) &&
2866
+ (params[param] === undefined || invalidType(params, param, _ofType));
2867
+ var hasError = invalid || (validate && !checkValidation(params[param], validate));
2868
+ if (hasError)
2869
+ errorParam = param;
2870
+ return hasError;
2871
+ });
2872
+ return !booleanParams.length || invalidParam;
2873
+ });
2874
+ return { paramError: paramError, errorParam: errorParam };
2875
+ }
2876
+ function invalidType(params, param, _ofType) {
2877
+ _ofType = _ofType || paramTypes[param] || 'string';
2878
+ if (_ofType === 'array') {
2879
+ return !Array.isArray(params[param]);
2880
+ }
2881
+ return typeof params[param] !== _ofType;
2882
+ }
2883
+ function checkValidation(value, validate) {
2884
+ if (isFunction(validate))
2885
+ return validate(value);
2886
+ return true;
2887
+ }
2888
+
2889
+ function getScaleValues(params) {
2890
+ var e_1, _a;
2891
+ var _b;
2892
+ var paramCheck = checkRequiredParameters(params, [{ participant: true }]);
2893
+ if (paramCheck.error)
2894
+ return paramCheck;
2895
+ var scaleItems = (_b = params.participant.timeItems) === null || _b === void 0 ? void 0 : _b.filter(function (_a) {
2896
+ var itemType = _a.itemType;
2897
+ return (itemType === null || itemType === void 0 ? void 0 : itemType.startsWith(SCALE$1)) &&
2898
+ [RANKING$1, RATING$2, SEEDING$1].includes(itemType.split('.')[1]);
2899
+ });
2900
+ var scales = { ratings: {}, rankings: {}, seedings: {} };
2901
+ if (scaleItems === null || scaleItems === void 0 ? void 0 : scaleItems.length) {
2902
+ var latestScaleItem = function (scaleType) {
2903
+ return scaleItems
2904
+ .filter(function (timeItem) { return (timeItem === null || timeItem === void 0 ? void 0 : timeItem.itemType) === scaleType; })
2905
+ .sort(function (a, b) {
2906
+ return new Date(a.createdAt || undefined).getTime() -
2907
+ new Date(b.createdAt || undefined).getTime();
2908
+ })
2909
+ .pop();
2910
+ };
2911
+ var itemTypes = unique(scaleItems.map(function (_a) {
2912
+ var itemType = _a.itemType;
2913
+ return itemType;
2914
+ }));
2915
+ try {
2916
+ for (var itemTypes_1 = __values(itemTypes), itemTypes_1_1 = itemTypes_1.next(); !itemTypes_1_1.done; itemTypes_1_1 = itemTypes_1.next()) {
2917
+ var itemType = itemTypes_1_1.value;
2918
+ var scaleItem = latestScaleItem(itemType);
2919
+ if (scaleItem) {
2920
+ var _c = __read(scaleItem.itemType.split('.'), 5), type = _c[1], format = _c[2], scaleName = _c[3], modifier = _c[4];
2921
+ var namedScale = modifier ? "".concat(scaleName, ".").concat(modifier) : scaleName;
2922
+ var scaleType = (type === SEEDING$1 && 'seedings') ||
2923
+ (type === RANKING$1 && 'rankings') ||
2924
+ 'ratings';
2925
+ if (!scales[scaleType][format])
2926
+ scales[scaleType][format] = [];
2927
+ scales[scaleType][format].push({
2928
+ scaleValue: scaleItem.itemValue,
2929
+ scaleDate: scaleItem.itemDate,
2930
+ scaleName: namedScale,
2931
+ });
2932
+ }
2933
+ }
2934
+ }
2935
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2936
+ finally {
2937
+ try {
2938
+ if (itemTypes_1_1 && !itemTypes_1_1.done && (_a = itemTypes_1.return)) _a.call(itemTypes_1);
2939
+ }
2940
+ finally { if (e_1) throw e_1.error; }
2941
+ }
2942
+ }
2943
+ return __assign(__assign({}, SUCCESS), scales);
2944
+ }
2945
+
2946
+ // NOTE: type really does need to be any!
2947
+ function attributeFilter(params) {
2948
+ if (params === null)
2949
+ return {};
2950
+ var _a = params || {}, source = _a.source, template = _a.template;
2951
+ if (!template)
2952
+ return source;
2953
+ var target = {};
2954
+ attributeCopy(source, template, target);
2955
+ return target;
2956
+ function attributeCopy(valuesObject, templateObject, outputObject) {
2957
+ var e_1, _a;
2958
+ if (!valuesObject || !templateObject)
2959
+ return undefined;
2960
+ var vKeys = Object.keys(valuesObject);
2961
+ var oKeys = Object.keys(templateObject);
2962
+ // the orMap allows spcification of { 'a||b': boolean } so that filter templates can apply to multiple attributes
2963
+ var orMap = Object.assign.apply(Object, __spreadArray([{}], __read(oKeys
2964
+ .filter(function (key) { return key.indexOf('||'); })
2965
+ .map(function (key) { return key.split('||').map(function (or) {
2966
+ var _a;
2967
+ return (_a = {}, _a[or] = key, _a);
2968
+ }); })
2969
+ .flat()), false));
2970
+ var allKeys = oKeys.concat.apply(oKeys, __spreadArray([], __read(Object.keys(orMap)), false));
2971
+ var wildcard = allKeys.includes('*');
2972
+ var _loop_1 = function (vKey) {
2973
+ if (allKeys.indexOf(vKey) >= 0 || wildcard) {
2974
+ var templateKey = orMap[vKey] || vKey;
2975
+ var tobj_1 = templateObject[templateKey] || wildcard;
2976
+ var vobj = valuesObject[vKey];
2977
+ if (typeof tobj_1 === 'object' &&
2978
+ typeof vobj !== 'function' &&
2979
+ !Array.isArray(tobj_1)) {
2980
+ if (Array.isArray(vobj)) {
2981
+ var mappedElements = vobj
2982
+ .map(function (arrayMember) {
2983
+ var target = {};
2984
+ var result = attributeCopy(arrayMember, tobj_1, target);
2985
+ return result !== false ? target : undefined;
2986
+ })
2987
+ .filter(Boolean);
2988
+ outputObject[vKey] = mappedElements;
2989
+ }
2990
+ else if (vobj) {
2991
+ outputObject[vKey] = {};
2992
+ attributeCopy(vobj, tobj_1, outputObject[vKey]);
2993
+ }
2994
+ }
2995
+ else {
2996
+ var value = valuesObject[vKey];
2997
+ var exclude = Array.isArray(tobj_1) && !tobj_1.includes(value);
2998
+ if (exclude)
2999
+ return { value: false };
3000
+ if (templateObject[vKey] ||
3001
+ (wildcard && templateObject[vKey] !== false)) {
3002
+ outputObject[vKey] = value;
3003
+ }
3004
+ }
3005
+ }
3006
+ };
3007
+ try {
3008
+ for (var vKeys_1 = __values(vKeys), vKeys_1_1 = vKeys_1.next(); !vKeys_1_1.done; vKeys_1_1 = vKeys_1.next()) {
3009
+ var vKey = vKeys_1_1.value;
3010
+ var state_1 = _loop_1(vKey);
3011
+ if (typeof state_1 === "object")
3012
+ return state_1.value;
3013
+ }
3014
+ }
3015
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3016
+ finally {
3017
+ try {
3018
+ if (vKeys_1_1 && !vKeys_1_1.done && (_a = vKeys_1.return)) _a.call(vKeys_1);
3019
+ }
3020
+ finally { if (e_1) throw e_1.error; }
3021
+ }
3022
+ return undefined;
3023
+ }
3024
+ }
3025
+
3026
+ var POLICY_TYPE_VOLUNTARY_CONSOLATION = 'voluntaryConsolation';
3027
+ var POLICY_TYPE_COMPETITIVE_BANDS = 'competitiveBands';
3028
+ var POLICY_TYPE_ROUND_ROBIN_TALLY = 'roundRobinTally';
3029
+ var POLICY_TYPE_POSITION_ACTIONS = 'positionActions';
3030
+ var POLICY_TYPE_MATCHUP_ACTIONS = 'matchUpActions';
3031
+ var POLICY_TYPE_RANKING_POINTS = 'rankingPoints';
3032
+ var POLICY_TYPE_ROUND_NAMING = 'roundNaming';
3033
+ var POLICY_TYPE_PARTICIPANT = 'participant';
3034
+ var POLICY_TYPE_PROGRESSION = 'progression';
3035
+ var POLICY_TYPE_SCHEDULING = 'scheduling';
3036
+ var POLICY_TYPE_AVOIDANCE = 'avoidance';
3037
+ var POLICY_TYPE_DISPLAY = 'display'; // storage for client type displays, e.g. { public: {}, admin: {} }
3038
+ var POLICY_TYPE_SCORING = 'scoring';
3039
+ var POLICY_TYPE_SEEDING = 'seeding';
3040
+ var POLICY_TYPE_FEED_IN = 'feedIn';
3041
+ var POLICY_TYPE_AUDIT = 'audit';
3042
+ var POLICY_TYPE_DRAWS = 'draws';
3043
+ var policyConstants = {
3044
+ POLICY_TYPE_VOLUNTARY_CONSOLATION: POLICY_TYPE_VOLUNTARY_CONSOLATION,
3045
+ POLICY_TYPE_COMPETITIVE_BANDS: POLICY_TYPE_COMPETITIVE_BANDS,
3046
+ POLICY_TYPE_ROUND_ROBIN_TALLY: POLICY_TYPE_ROUND_ROBIN_TALLY,
3047
+ POLICY_TYPE_POSITION_ACTIONS: POLICY_TYPE_POSITION_ACTIONS,
3048
+ POLICY_TYPE_MATCHUP_ACTIONS: POLICY_TYPE_MATCHUP_ACTIONS,
3049
+ POLICY_TYPE_RANKING_POINTS: POLICY_TYPE_RANKING_POINTS,
3050
+ POLICY_TYPE_ROUND_NAMING: POLICY_TYPE_ROUND_NAMING,
3051
+ POLICY_TYPE_PARTICIPANT: POLICY_TYPE_PARTICIPANT,
3052
+ POLICY_TYPE_PROGRESSION: POLICY_TYPE_PROGRESSION,
3053
+ POLICY_TYPE_SCHEDULING: POLICY_TYPE_SCHEDULING,
3054
+ POLICY_TYPE_AVOIDANCE: POLICY_TYPE_AVOIDANCE,
3055
+ POLICY_TYPE_DISPLAY: POLICY_TYPE_DISPLAY,
3056
+ POLICY_TYPE_FEED_IN: POLICY_TYPE_FEED_IN,
3057
+ POLICY_TYPE_SCORING: POLICY_TYPE_SCORING,
3058
+ POLICY_TYPE_SEEDING: POLICY_TYPE_SEEDING,
3059
+ POLICY_TYPE_AUDIT: POLICY_TYPE_AUDIT,
3060
+ POLICY_TYPE_DRAWS: POLICY_TYPE_DRAWS,
3061
+ };
3062
+
3063
+ function findParticipant(_a) {
3064
+ var _b = _a.tournamentParticipants, tournamentParticipants = _b === void 0 ? [] : _b, _c = _a.policyDefinitions, policyDefinitions = _c === void 0 ? {} : _c, contextProfile = _a.contextProfile, participantId = _a.participantId, internalUse = _a.internalUse, personId = _a.personId;
3065
+ var foundParticipant = tournamentParticipants.find(function (candidate) {
3066
+ return (participantId && candidate.participantId === participantId) ||
3067
+ (personId && candidate.person && candidate.person.personId === personId);
3068
+ });
3069
+ var participant = makeDeepCopy(foundParticipant, false, internalUse);
3070
+ if (participant) {
3071
+ var participantAttributes = policyDefinitions === null || policyDefinitions === void 0 ? void 0 : policyDefinitions[POLICY_TYPE_PARTICIPANT];
3072
+ if (contextProfile === null || contextProfile === void 0 ? void 0 : contextProfile.withScaleValues) {
3073
+ var _d = getScaleValues({ participant: participant }), ratings = _d.ratings, rankings = _d.rankings;
3074
+ participant.rankings = rankings;
3075
+ participant.ratings = ratings;
3076
+ }
3077
+ if (participantAttributes === null || participantAttributes === void 0 ? void 0 : participantAttributes.participant) {
3078
+ return attributeFilter({
3079
+ template: participantAttributes.participant,
3080
+ source: participant,
3081
+ });
3082
+ }
3083
+ }
3084
+ return participant;
3085
+ }
3086
+
3087
+ function addTournamentExtension(params) {
3088
+ if (!params || typeof params !== 'object')
3089
+ return { error: MISSING_VALUE };
3090
+ if (!params.tournamentRecord)
3091
+ return { error: MISSING_TOURNAMENT_RECORD };
3092
+ return addExtension({
3093
+ creationTime: params.creationTime,
3094
+ element: params.tournamentRecord,
3095
+ extension: params.extension,
3096
+ });
3097
+ }
3098
+ function addDrawDefinitionExtension(params) {
3099
+ if (!params || typeof params !== 'object')
3100
+ return { error: MISSING_VALUE };
3101
+ if (!params.drawDefinition)
3102
+ return { error: DRAW_DEFINITION_NOT_FOUND };
3103
+ return addExtension({
3104
+ creationTime: params.creationTime,
3105
+ element: params.drawDefinition,
3106
+ extension: params.extension,
3107
+ });
3108
+ }
3109
+ function addEventExtension(params) {
3110
+ if (!params || typeof params !== 'object')
3111
+ return { error: MISSING_VALUE };
3112
+ if (!params.event)
3113
+ return { error: EVENT_NOT_FOUND };
3114
+ return addExtension({
3115
+ creationTime: params.creationTime,
3116
+ extension: params.extension,
3117
+ element: params.event,
3118
+ });
3119
+ }
3120
+ function addParticipantExtension(params) {
3121
+ var _a;
3122
+ if (!params || typeof params !== 'object')
3123
+ return { error: MISSING_VALUE };
3124
+ if (!params.participantId)
3125
+ return { error: MISSING_PARTICIPANT_ID };
3126
+ var tournamentParticipants = ((_a = params.tournamentRecord) === null || _a === void 0 ? void 0 : _a.participants) || [];
3127
+ var participant = findParticipant({
3128
+ participantId: params.participantId,
3129
+ tournamentParticipants: tournamentParticipants,
3130
+ });
3131
+ if (!participant)
3132
+ return { error: PARTICIPANT_NOT_FOUND };
3133
+ return addExtension({
3134
+ creationTime: params.creationTime,
3135
+ extension: params.extension,
3136
+ element: participant,
3137
+ });
3138
+ }
3139
+ function removeTournamentExtension(params) {
3140
+ if (!params || typeof params !== 'object')
3141
+ return { error: MISSING_VALUE };
3142
+ if (!params.tournamentRecord)
3143
+ return { error: MISSING_TOURNAMENT_RECORD };
3144
+ return removeExtension({
3145
+ element: params.tournamentRecord,
3146
+ name: params.name,
3147
+ });
3148
+ }
3149
+ function removeDrawDefinitionExtension(params) {
3150
+ if (!params || typeof params !== 'object')
3151
+ return { error: MISSING_VALUE };
3152
+ if (!params.drawDefinition)
3153
+ return { error: DRAW_DEFINITION_NOT_FOUND };
3154
+ return removeExtension({ element: params.drawDefinition, name: params.name });
3155
+ }
3156
+ function removeEventExtension(params) {
3157
+ if (!params || typeof params !== 'object')
3158
+ return { error: MISSING_VALUE };
3159
+ if (!(params === null || params === void 0 ? void 0 : params.event))
3160
+ return { error: EVENT_NOT_FOUND };
3161
+ return removeExtension({ element: params.event, name: params.name });
3162
+ }
3163
+ function removeParticipantExtension(params) {
3164
+ var _a;
3165
+ if (!params || typeof params !== 'object')
3166
+ return { error: MISSING_VALUE };
3167
+ if (!params.participantId)
3168
+ return { error: MISSING_PARTICIPANT_ID };
3169
+ var tournamentParticipants = ((_a = params.tournamentRecord) === null || _a === void 0 ? void 0 : _a.participants) || [];
3170
+ var participant = findParticipant({
3171
+ participantId: params.participantId,
3172
+ tournamentParticipants: tournamentParticipants,
3173
+ });
3174
+ if (!participant)
3175
+ return { error: PARTICIPANT_NOT_FOUND };
3176
+ return removeExtension({ element: participant, name: params.name });
3177
+ }
3178
+
3179
+ var ACTIVE_SUSPENSION = 'activeSuspension';
3180
+ var APPLIED_POLICIES = 'appliedPolicies';
3181
+ var AUDIT_POSITION_ACTIONS = 'positionActions';
3182
+ var CONTEXT = 'context';
3183
+ var DELEGATED_OUTCOME = 'delegatedOutcome';
3184
+ var DISABLED = 'disabled';
3185
+ var DISABLE_LINKS = 'disableLinks';
3186
+ var DISABLE_AUTO_CALC = 'disableAutoCalc';
3187
+ var DRAW_DELETIONS = 'drawDeletions';
3188
+ var DRAW_PROFILE = 'drawProfile';
3189
+ var ENTRY_PROFILE = 'entryProfile';
3190
+ var EVENT_PROFILE = 'eventProfile';
3191
+ var EVENT_WITHDRAWAL_REQUESTS = 'eventWithdrawalRequests';
3192
+ var FACTORY$1 = 'factory';
3193
+ var FLIGHT_PROFILE = 'flightProfile';
3194
+ var GROUPING_ATTRIBUTE = 'groupingAttribute';
3195
+ var LINEUPS = 'lineUps';
3196
+ var LINKED_TOURNAMENTS = 'linkedTournamentsIds';
3197
+ var MATCHUP_HISTORY = 'matchUpHistory';
3198
+ var PARTICIPANT_REPRESENTATIVES = 'participantRepresentatives';
3199
+ var PERSON_REQUESTS = 'personRequests';
3200
+ var RANKING_POINTS = 'rankingPoints';
3201
+ var ROUND_TARGET = 'roundTarget';
3202
+ var SCHEDULE_LIMITS = 'scheduleLimits';
3203
+ var SCHEDULE_TIMING = 'scheduleTiming';
3204
+ var SCHEDULING_PROFILE = 'schedulingProfile';
3205
+ var STATUS_DETAIL = 'statusDetail';
3206
+ var SUB_ORDER = 'subOrder';
3207
+ var TALLY = 'tally';
3208
+ var TIE_FORMAT_MODIFICATIONS = 'tieFormatModification';
3209
+ var extensionConstants = {
3210
+ ACTIVE_SUSPENSION: ACTIVE_SUSPENSION,
3211
+ APPLIED_POLICIES: APPLIED_POLICIES,
3212
+ AUDIT_POSITION_ACTIONS: AUDIT_POSITION_ACTIONS,
3213
+ CONTEXT: CONTEXT, // used to capture, e.g. context in which a venue was added
3214
+ DELEGATED_OUTCOME: DELEGATED_OUTCOME,
3215
+ DISABLED: DISABLED,
3216
+ DISABLE_LINKS: DISABLE_LINKS,
3217
+ DISABLE_AUTO_CALC: DISABLE_AUTO_CALC,
3218
+ DRAW_DELETIONS: DRAW_DELETIONS,
3219
+ DRAW_PROFILE: DRAW_PROFILE,
3220
+ ENTRY_PROFILE: ENTRY_PROFILE, // used for drawGeneration; not relevant for anonymized tournaments
3221
+ EVENT_PROFILE: EVENT_PROFILE,
3222
+ EVENT_WITHDRAWAL_REQUESTS: EVENT_WITHDRAWAL_REQUESTS,
3223
+ FLIGHT_PROFILE: FLIGHT_PROFILE,
3224
+ GROUPING_ATTRIBUTE: GROUPING_ATTRIBUTE, // for generating teams; not relevant for anonymized tournaments
3225
+ LINEUPS: LINEUPS,
3226
+ LINKED_TOURNAMENTS: LINKED_TOURNAMENTS,
3227
+ MATCHUP_HISTORY: MATCHUP_HISTORY,
3228
+ PARTICIPANT_REPRESENTATIVES: PARTICIPANT_REPRESENTATIVES,
3229
+ PERSON_REQUESTS: PERSON_REQUESTS,
3230
+ RANKING_POINTS: RANKING_POINTS, // for attaching points awarded to tournamentRecord
3231
+ ROUND_TARGET: ROUND_TARGET,
3232
+ SCHEDULE_LIMITS: SCHEDULE_LIMITS,
3233
+ SCHEDULE_TIMING: SCHEDULE_TIMING,
3234
+ SCHEDULING_PROFILE: SCHEDULING_PROFILE,
3235
+ STATUS_DETAIL: STATUS_DETAIL, // attached to event.entries
3236
+ SUB_ORDER: SUB_ORDER,
3237
+ TALLY: TALLY,
3238
+ TIE_FORMAT_MODIFICATIONS: TIE_FORMAT_MODIFICATIONS, // for auditing, not important when anonymized
3239
+ FACTORY: FACTORY$1,
3240
+ };
3241
+ var internalExtensions = [
3242
+ DELEGATED_OUTCOME,
3243
+ DISABLED,
3244
+ DISABLE_LINKS,
3245
+ FLIGHT_PROFILE,
3246
+ LINEUPS,
3247
+ MATCHUP_HISTORY,
3248
+ PARTICIPANT_REPRESENTATIVES,
3249
+ PERSON_REQUESTS,
3250
+ ROUND_TARGET,
3251
+ SCHEDULE_LIMITS,
3252
+ SCHEDULE_TIMING,
3253
+ SCHEDULING_PROFILE,
3254
+ SUB_ORDER,
3255
+ TALLY,
3256
+ ];
3257
+
3258
+ function getTournamentIds(_a) {
3259
+ var tournamentRecords = _a.tournamentRecords;
3260
+ var tournamentIds = isObject(tournamentRecords)
3261
+ ? Object.keys(tournamentRecords)
3262
+ : [];
3263
+ return __assign({ tournamentIds: tournamentIds }, SUCCESS);
3264
+ }
3265
+
3266
+ /**
3267
+ * Links all tournaments which are currently loaded into competitionEngine state
3268
+ */
3269
+ function linkTournaments(_a) {
3270
+ var tournamentRecords = _a.tournamentRecords;
3271
+ if (typeof tournamentRecords !== 'object' ||
3272
+ !Object.keys(tournamentRecords).length)
3273
+ return { error: MISSING_TOURNAMENT_RECORDS };
3274
+ var result = getTournamentIds({ tournamentRecords: tournamentRecords });
3275
+ var tournamentIds = result.tournamentIds;
3276
+ if ((tournamentIds === null || tournamentIds === void 0 ? void 0 : tournamentIds.length) > 1) {
3277
+ var extension = {
3278
+ name: LINKED_TOURNAMENTS,
3279
+ value: { tournamentIds: tournamentIds },
3280
+ };
3281
+ return addExtension({
3282
+ tournamentRecords: tournamentRecords,
3283
+ discover: true,
3284
+ extension: extension,
3285
+ });
3286
+ }
3287
+ return __assign({}, SUCCESS);
3288
+ }
3289
+ function unlinkTournaments(_a) {
3290
+ var tournamentRecords = _a.tournamentRecords;
3291
+ if (typeof tournamentRecords !== 'object' ||
3292
+ !Object.keys(tournamentRecords).length)
3293
+ return { error: MISSING_TOURNAMENT_RECORDS };
3294
+ var result = removeExtension({
3295
+ name: LINKED_TOURNAMENTS,
3296
+ tournamentRecords: tournamentRecords,
3297
+ discover: true,
3298
+ });
3299
+ // TODO: check the integrity of the venues attached to each tournment...
3300
+ // get all competitionScheduleMatchUps and ensure that each tournamentRecord has all venues for scheduled matchUps
3301
+ return decorateResult({ result: result, stack: 'unlinkTournaments' });
3302
+ }
3303
+ function unlinkTournament(_a) {
3304
+ var tournamentRecords = _a.tournamentRecords, tournamentId = _a.tournamentId;
3305
+ if (typeof tournamentRecords !== 'object')
3306
+ return { error: INVALID_VALUES };
3307
+ if (!tournamentId)
3308
+ return { error: MISSING_TOURNAMENT_ID };
3309
+ var result = getTournamentIds({ tournamentRecords: tournamentRecords });
3310
+ var tournamentIds = result.tournamentIds;
3311
+ if (!tournamentIds.includes(tournamentId))
3312
+ return { error: MISSING_TOURNAMENT_ID };
3313
+ // not using bulk update function here to handle scenario where
3314
+ // tournamentRecords loaded into state are not all linked
3315
+ var unlinkError;
3316
+ tournamentIds.every(function (currentTournamentId) {
3317
+ var _a;
3318
+ var tournamentRecord = tournamentRecords[currentTournamentId];
3319
+ var extension = findExtension({
3320
+ element: tournamentRecord,
3321
+ name: LINKED_TOURNAMENTS,
3322
+ }).extension;
3323
+ // if there is no extension return { ...SUCCESS } because no links exist
3324
+ if (!extension)
3325
+ return true;
3326
+ var linkedTournamentIds = ((_a = extension === null || extension === void 0 ? void 0 : extension.value) === null || _a === void 0 ? void 0 : _a.tournamentIds) || [];
3327
+ // if there are no tournamentIds
3328
+ if (!(linkedTournamentIds === null || linkedTournamentIds === void 0 ? void 0 : linkedTournamentIds.length) ||
3329
+ (linkedTournamentIds.length === 1 &&
3330
+ linkedTournamentIds.includes(tournamentId)) ||
3331
+ currentTournamentId === tournamentId) {
3332
+ var result_1 = removeTournamentExtension({
3333
+ name: LINKED_TOURNAMENTS,
3334
+ tournamentRecord: tournamentRecord,
3335
+ });
3336
+ if (result_1.error)
3337
+ unlinkError = result_1.error;
3338
+ return result_1.success;
3339
+ }
3340
+ var tournamentIds = linkedTournamentIds.filter(function (linkedTournamentId) { return linkedTournamentId !== tournamentId; });
3341
+ extension.value = { tournamentIds: tournamentIds };
3342
+ var result = addTournamentExtension({ tournamentRecord: tournamentRecord, extension: extension });
3343
+ if (result.error)
3344
+ unlinkError = result.error;
3345
+ return result.success;
3182
3346
  });
3183
3347
  return unlinkError ? { error: unlinkError } : __assign({}, SUCCESS);
3184
3348
  }
@@ -3350,7 +3514,7 @@ var matchUpStatusConstants = {
3350
3514
  WALKOVER: WALKOVER$2,
3351
3515
  };
3352
3516
 
3353
- var _a$k, _b$8, _c$1;
3517
+ var _a$j, _b$7, _c$1;
3354
3518
  // stage types
3355
3519
  var MAIN = 'MAIN';
3356
3520
  var QUALIFYING = 'QUALIFYING';
@@ -3364,22 +3528,22 @@ var validStages = [
3364
3528
  PLAY_OFF,
3365
3529
  VOLUNTARY_CONSOLATION,
3366
3530
  ];
3367
- var stageOrder$1 = (_a$k = {},
3368
- _a$k[QUALIFYING] = 1,
3369
- _a$k[MAIN] = 2,
3370
- _a$k[PLAY_OFF] = 3,
3371
- _a$k[CONSOLATION] = 3,
3372
- _a$k[VOLUNTARY_CONSOLATION] = 4,
3373
- _a$k);
3531
+ var stageOrder$1 = (_a$j = {},
3532
+ _a$j[QUALIFYING] = 1,
3533
+ _a$j[MAIN] = 2,
3534
+ _a$j[PLAY_OFF] = 3,
3535
+ _a$j[CONSOLATION] = 3,
3536
+ _a$j[VOLUNTARY_CONSOLATION] = 4,
3537
+ _a$j);
3374
3538
  var FINISHING_POSITIONS = 'finishingPositions';
3375
3539
  var AGGREGATE_EVENT_STRUCTURES = 'aggregateEventStructures';
3376
- var finishOrder = (_b$8 = {},
3377
- _b$8[MAIN] = 1,
3378
- _b$8[PLAY_OFF] = 2,
3379
- _b$8[CONSOLATION] = 3,
3380
- _b$8[QUALIFYING] = 4,
3381
- _b$8[VOLUNTARY_CONSOLATION] = 5,
3382
- _b$8);
3540
+ var finishOrder = (_b$7 = {},
3541
+ _b$7[MAIN] = 1,
3542
+ _b$7[PLAY_OFF] = 2,
3543
+ _b$7[CONSOLATION] = 3,
3544
+ _b$7[QUALIFYING] = 4,
3545
+ _b$7[VOLUNTARY_CONSOLATION] = 5,
3546
+ _b$7);
3383
3547
  // for aggregateOrder { stage: MAIN, stageSequence: 1 } is always first
3384
3548
  var aggregateOrder = (_c$1 = {},
3385
3549
  _c$1[PLAY_OFF] = 1,
@@ -5157,16 +5321,16 @@ var ROUTINE = 'ROUTINE';
5157
5321
  var DECISIVE = 'DECISIVE';
5158
5322
  var WIN_RATIO = 'winRatio';
5159
5323
 
5160
- var _a$j, _b$7;
5161
- var POLICY_COMPETITIVE_BANDS_DEFAULT = (_a$j = {},
5162
- _a$j[POLICY_TYPE_COMPETITIVE_BANDS] = {
5324
+ var _a$i, _b$6;
5325
+ var POLICY_COMPETITIVE_BANDS_DEFAULT = (_a$i = {},
5326
+ _a$i[POLICY_TYPE_COMPETITIVE_BANDS] = {
5163
5327
  policyName: 'Competitive Bands Default',
5164
- profileBands: (_b$7 = {},
5165
- _b$7[DECISIVE] = 20,
5166
- _b$7[ROUTINE] = 50,
5167
- _b$7),
5328
+ profileBands: (_b$6 = {},
5329
+ _b$6[DECISIVE] = 20,
5330
+ _b$6[ROUTINE] = 50,
5331
+ _b$6),
5168
5332
  },
5169
- _a$j);
5333
+ _a$i);
5170
5334
 
5171
5335
  function getContextContent(_a) {
5172
5336
  var _b, _c;
@@ -7844,9 +8008,9 @@ function isAdHoc(_a) {
7844
8008
  !hasDrawPosition);
7845
8009
  }
7846
8010
 
7847
- var _a$i, _b$6;
7848
- var POLICY_ROUND_NAMING_DEFAULT = (_a$i = {},
7849
- _a$i[POLICY_TYPE_ROUND_NAMING] = {
8011
+ var _a$h, _b$5;
8012
+ var POLICY_ROUND_NAMING_DEFAULT = (_a$h = {},
8013
+ _a$h[POLICY_TYPE_ROUND_NAMING] = {
7850
8014
  policyName: 'Round Naming Default',
7851
8015
  namingConventions: {
7852
8016
  round: 'Round',
@@ -7871,14 +8035,14 @@ var POLICY_ROUND_NAMING_DEFAULT = (_a$i = {},
7871
8035
  preFeedRound: 'Q',
7872
8036
  preQualifying: 'P',
7873
8037
  },
7874
- stageConstants: (_b$6 = {},
7875
- _b$6[MAIN] = '',
7876
- _b$6[PLAY_OFF] = 'P',
7877
- _b$6[QUALIFYING] = 'Q',
7878
- _b$6[CONSOLATION] = 'C',
7879
- _b$6),
8038
+ stageConstants: (_b$5 = {},
8039
+ _b$5[MAIN] = '',
8040
+ _b$5[PLAY_OFF] = 'P',
8041
+ _b$5[QUALIFYING] = 'Q',
8042
+ _b$5[CONSOLATION] = 'C',
8043
+ _b$5),
7880
8044
  },
7881
- _a$i);
8045
+ _a$h);
7882
8046
 
7883
8047
  function getRoundContextProfile(_a) {
7884
8048
  var _b, _c, _d, _e, _f, _g;
@@ -7976,165 +8140,6 @@ function getRoundContextProfile(_a) {
7976
8140
  return { roundNamingProfile: roundNamingProfile, roundProfile: roundProfile, roundMatchUps: roundMatchUps };
7977
8141
  }
7978
8142
 
7979
- var TOURNAMENT_RECORDS = 'tournamentRecords';
7980
- var POLICY_DEFINITIONS = 'policyDefinitions';
7981
- var TOURNAMENT_RECORD = 'tournamentRecord';
7982
- var DRAW_DEFINITION = 'drawDefinition';
7983
- var MATCHUP_FORMAT = 'matchUpFormat';
7984
- var PARTICIPANT_ID = 'participantId';
7985
- var SCHEDULE_DATES = 'scheduleDates';
7986
- var TOURNAMENT_ID = 'tournamentId';
7987
- var SCHEDULE_DATE = 'scheduleDate';
7988
- var STRUCTURE_ID = 'structureId';
7989
- var MATCHUP_IDS = 'matchUpIds';
7990
- var POLICY_TYPE = 'policyType';
7991
- var STRUCTURES = 'structures';
7992
- var MATCHUP_ID = 'matchUpId';
7993
- var IN_CONTEXT = 'inContext';
7994
- var STRUCTURE = 'structure';
7995
- var COURT_IDS = 'courtIds';
7996
- var PERSON_ID = 'personId';
7997
- var VENUE_IDS = 'venueIds';
7998
- var MATCHUPS = 'matchUps';
7999
- var COURT_ID = 'courtId';
8000
- var EVENT_ID = 'eventId';
8001
- var MATCHUP = 'matchUp';
8002
- var DRAW_ID = 'drawId';
8003
- var ERROR = 'error';
8004
- var EVENT = 'event';
8005
- var PARAM = 'param';
8006
- var AVERAGE_MATCHUP_MINUTES = 'averageMatchUpMinutes';
8007
- var RECOVERY_MINUTES = 'recoveryMinutes';
8008
- var PERIOD_LENGTH = 'periodLength';
8009
- var OBJECT = 'object';
8010
- var ARRAY = 'array';
8011
- var VALIDATE = 'validate';
8012
- var INVALID = 'invalid';
8013
- var OF_TYPE = '_ofType';
8014
- var ANY_OF = '_anyOf';
8015
- var ONE_OF = '_oneOf';
8016
-
8017
- var _a$h, _b$5;
8018
- var errors = (_a$h = {},
8019
- _a$h[TOURNAMENT_RECORDS] = MISSING_TOURNAMENT_RECORDS,
8020
- _a$h[TOURNAMENT_RECORD] = MISSING_TOURNAMENT_RECORD,
8021
- _a$h[POLICY_DEFINITIONS] = MISSING_POLICY_DEFINITION,
8022
- _a$h[DRAW_DEFINITION] = MISSING_DRAW_DEFINITION,
8023
- _a$h[PARTICIPANT_ID] = MISSING_PARTICIPANT_ID,
8024
- _a$h[TOURNAMENT_ID] = MISSING_TOURNAMENT_ID,
8025
- _a$h[STRUCTURE_ID] = MISSING_STRUCTURE_ID,
8026
- _a$h[MATCHUP_IDS] = MISSING_MATCHUP_IDS,
8027
- _a$h[STRUCTURES] = MISSING_STRUCTURES,
8028
- _a$h[MATCHUP_ID] = MISSING_MATCHUP_ID,
8029
- _a$h[STRUCTURE] = MISSING_STRUCTURE,
8030
- _a$h[COURT_ID] = MISSING_COURT_ID,
8031
- _a$h[MATCHUPS] = MISSING_MATCHUPS,
8032
- _a$h[MATCHUP] = MISSING_MATCHUP,
8033
- _a$h[COURT_IDS] = MISSING_VALUE,
8034
- _a$h[VENUE_IDS] = MISSING_VALUE,
8035
- _a$h[DRAW_ID] = MISSING_DRAW_ID,
8036
- _a$h[EVENT_ID] = MISSING_EVENT,
8037
- _a$h[EVENT] = EVENT_NOT_FOUND,
8038
- _a$h);
8039
- var paramTypes = (_b$5 = {},
8040
- _b$5[TOURNAMENT_RECORDS] = OBJECT,
8041
- _b$5[POLICY_DEFINITIONS] = OBJECT,
8042
- _b$5[TOURNAMENT_RECORD] = OBJECT,
8043
- _b$5[DRAW_DEFINITION] = OBJECT,
8044
- _b$5[SCHEDULE_DATES] = ARRAY,
8045
- _b$5[MATCHUP_IDS] = ARRAY,
8046
- _b$5[STRUCTURES] = ARRAY,
8047
- _b$5[STRUCTURE] = OBJECT,
8048
- _b$5[COURT_IDS] = ARRAY,
8049
- _b$5[VENUE_IDS] = ARRAY,
8050
- _b$5[MATCHUPS] = ARRAY,
8051
- _b$5[MATCHUP] = OBJECT,
8052
- _b$5[EVENT] = OBJECT,
8053
- _b$5);
8054
- function checkRequiredParameters(params, requiredParams, stack) {
8055
- if (!params && !isObject(params))
8056
- return { error: INVALID_VALUES };
8057
- if (!(requiredParams === null || requiredParams === void 0 ? void 0 : requiredParams.length) || (params === null || params === void 0 ? void 0 : params._bypassParamCheck))
8058
- return { valid: true };
8059
- if (!Array.isArray(requiredParams))
8060
- return { error: INVALID_VALUES };
8061
- var _a = findParamError(params, requiredParams), paramError = _a.paramError, errorParam = _a.errorParam;
8062
- if (!paramError)
8063
- return { valid: true };
8064
- var error = params[errorParam] === undefined
8065
- ? errors[errorParam] || INVALID_VALUES
8066
- : (paramError.validate && paramError.invalid) || INVALID_VALUES;
8067
- return decorateResult({
8068
- info: { param: errorParam },
8069
- result: { error: error },
8070
- stack: stack,
8071
- });
8072
- }
8073
- function getIntersection(params, constraint) {
8074
- var paramKeys = Object.keys(params);
8075
- var constraintKeys = Object.keys(constraint);
8076
- return intersection(paramKeys, constraintKeys);
8077
- }
8078
- function getOneOf(params, _oneOf) {
8079
- if (!_oneOf)
8080
- return;
8081
- var overlap = getIntersection(params, _oneOf);
8082
- if (overlap.length !== 1)
8083
- return { error: INVALID_VALUES };
8084
- return overlap.reduce(function (attr, param) {
8085
- var _a;
8086
- return (__assign(__assign({}, attr), (_a = {}, _a[param] = true, _a)));
8087
- }, {});
8088
- }
8089
- function getAnyOf(params, _anyOf) {
8090
- if (!_anyOf)
8091
- return;
8092
- var overlap = getIntersection(params, _anyOf).filter(function (param) { return params[param]; });
8093
- if (overlap.length < 1)
8094
- return { error: INVALID_VALUES };
8095
- return overlap.reduce(function (attr, param) {
8096
- var _a;
8097
- return (__assign(__assign({}, attr), (_a = {}, _a[param] = true, _a)));
8098
- }, {});
8099
- }
8100
- function findParamError(params, requiredParams) {
8101
- var errorParam;
8102
- var paramError = requiredParams.find(function (_a) {
8103
- var _ofType = _a._ofType, _oneOf = _a._oneOf, _anyOf = _a._anyOf, validate = _a.validate, attrs = __rest(_a, ["_ofType", "_oneOf", "_anyOf", "validate"]);
8104
- var oneOf = _oneOf && getOneOf(params, _oneOf);
8105
- if (oneOf === null || oneOf === void 0 ? void 0 : oneOf.error)
8106
- return oneOf.error;
8107
- oneOf && Object.assign(attrs, oneOf);
8108
- var anyOf = _anyOf && getAnyOf(params, _anyOf);
8109
- if (anyOf === null || anyOf === void 0 ? void 0 : anyOf.error)
8110
- return anyOf.error;
8111
- anyOf && Object.assign(attrs, anyOf);
8112
- var booleanParams = Object.keys(attrs).filter(function (key) { return typeof attrs[key] === 'boolean'; });
8113
- var invalidParam = booleanParams.find(function (param) {
8114
- var invalid = !isFunction(validate) &&
8115
- (params[param] === undefined || invalidType(params, param, _ofType));
8116
- var hasError = invalid || (validate && !checkValidation(params[param], validate));
8117
- if (hasError)
8118
- errorParam = param;
8119
- return hasError;
8120
- });
8121
- return !booleanParams.length || invalidParam;
8122
- });
8123
- return { paramError: paramError, errorParam: errorParam };
8124
- }
8125
- function invalidType(params, param, _ofType) {
8126
- _ofType = _ofType || paramTypes[param] || 'string';
8127
- if (_ofType === 'array') {
8128
- return !Array.isArray(params[param]);
8129
- }
8130
- return typeof params[param] !== _ofType;
8131
- }
8132
- function checkValidation(value, validate) {
8133
- if (isFunction(validate))
8134
- return validate(value);
8135
- return true;
8136
- }
8137
-
8138
8143
  // derive matchUpType from participants when not defined on matchUp
8139
8144
  function getMatchUpType(params) {
8140
8145
  var _a;
@@ -19925,7 +19930,7 @@ function qualifierDrawPositionAssignment(params) {
19925
19930
  }
19926
19931
 
19927
19932
  function getTieMatchUpContext(_a) {
19928
- var _b;
19933
+ var _b, _c, _d, _e;
19929
19934
  var tournamentRecord = _a.tournamentRecord, drawDefinition = _a.drawDefinition, tieMatchUpId = _a.tieMatchUpId, event = _a.event;
19930
19935
  if (!tournamentRecord)
19931
19936
  return { error: MISSING_TOURNAMENT_RECORD };
@@ -19942,14 +19947,14 @@ function getTieMatchUpContext(_a) {
19942
19947
  }).matchUp;
19943
19948
  if (!tieMatchUp)
19944
19949
  return { error: MATCHUP_NOT_FOUND };
19945
- var _c = findDrawMatchUp({
19950
+ var _f = findDrawMatchUp({
19946
19951
  tournamentParticipants: tournamentRecord.participants,
19947
19952
  matchUpId: tieMatchUpId,
19948
19953
  inContext: true,
19949
19954
  drawDefinition: drawDefinition,
19950
19955
  matchUpsMap: matchUpsMap,
19951
19956
  event: event,
19952
- }), inContextTieMatchUp = _c.matchUp, structure = _c.structure;
19957
+ }), inContextTieMatchUp = _f.matchUp, structure = _f.structure;
19953
19958
  if (!inContextTieMatchUp)
19954
19959
  return { error: MATCHUP_NOT_FOUND };
19955
19960
  var collectionPosition = inContextTieMatchUp.collectionPosition, drawPositions = inContextTieMatchUp.drawPositions, collectionId = inContextTieMatchUp.collectionId, matchUpTieId = inContextTieMatchUp.matchUpTieId, matchUpType = inContextTieMatchUp.matchUpType;
@@ -19957,7 +19962,14 @@ function getTieMatchUpContext(_a) {
19957
19962
  return { error: INVALID_MATCHUP };
19958
19963
  var positionAssignments = getPositionAssignments$1({ structure: structure }).positionAssignments;
19959
19964
  var relevantAssignments = positionAssignments === null || positionAssignments === void 0 ? void 0 : positionAssignments.filter(function (assignment) { return drawPositions === null || drawPositions === void 0 ? void 0 : drawPositions.includes(assignment.drawPosition); });
19960
- var participantIds = relevantAssignments === null || relevantAssignments === void 0 ? void 0 : relevantAssignments.map(extractAttributes('participantId'));
19965
+ var dualMatchUp = findDrawMatchUp({
19966
+ matchUpId: matchUpTieId,
19967
+ drawDefinition: drawDefinition,
19968
+ matchUpsMap: matchUpsMap,
19969
+ }).matchUp;
19970
+ var sideParticipantIds = (_c = (_b = dualMatchUp === null || dualMatchUp === void 0 ? void 0 : dualMatchUp.sides) === null || _b === void 0 ? void 0 : _b.map(extractAttributes('participantId'))) !== null && _c !== void 0 ? _c : [];
19971
+ var assignedParticipantIds = (_d = relevantAssignments === null || relevantAssignments === void 0 ? void 0 : relevantAssignments.map(extractAttributes('participantId'))) !== null && _d !== void 0 ? _d : [];
19972
+ var participantIds = __spreadArray(__spreadArray([], __read(sideParticipantIds), false), __read(assignedParticipantIds), false);
19961
19973
  var teamParticipants = getParticipants({
19962
19974
  tournamentRecord: tournamentRecord,
19963
19975
  participantFilters: {
@@ -19965,23 +19977,18 @@ function getTieMatchUpContext(_a) {
19965
19977
  participantIds: participantIds,
19966
19978
  },
19967
19979
  }).participants;
19968
- var dualMatchUp = findDrawMatchUp({
19969
- matchUpId: matchUpTieId,
19970
- drawDefinition: drawDefinition,
19971
- matchUpsMap: matchUpsMap,
19972
- }).matchUp;
19973
19980
  var inContextDualMatchUp = findDrawMatchUp({
19974
19981
  matchUpId: matchUpTieId,
19975
19982
  inContext: true,
19976
19983
  drawDefinition: drawDefinition,
19977
19984
  matchUpsMap: matchUpsMap,
19978
19985
  }).matchUp;
19979
- var tieFormat = (_b = resolveTieFormat({
19986
+ var tieFormat = (_e = resolveTieFormat({
19980
19987
  matchUp: dualMatchUp,
19981
19988
  drawDefinition: drawDefinition,
19982
19989
  structure: structure,
19983
19990
  event: event,
19984
- })) === null || _b === void 0 ? void 0 : _b.tieFormat;
19991
+ })) === null || _e === void 0 ? void 0 : _e.tieFormat;
19985
19992
  return __assign({ inContextDualMatchUp: inContextDualMatchUp, inContextTieMatchUp: inContextTieMatchUp, relevantAssignments: relevantAssignments, collectionPosition: collectionPosition, teamParticipants: teamParticipants, collectionId: collectionId, matchUpType: matchUpType, dualMatchUp: dualMatchUp, tieMatchUp: tieMatchUp, tieFormat: tieFormat, structure: structure }, SUCCESS);
19986
19993
  }
19987
19994
 
@@ -20814,9 +20821,8 @@ function assignTieMatchUpParticipantId(params) {
20814
20821
  var individualParticipantIds = _a.individualParticipantIds;
20815
20822
  return overlap(relevantParticipantIds, individualParticipantIds);
20816
20823
  }));
20817
- if (!participantTeam) {
20824
+ if (!participantTeam)
20818
20825
  return { error: TEAM_NOT_FOUND };
20819
- }
20820
20826
  if (!teamParticipantId)
20821
20827
  teamParticipantId = participantTeam.participantId;
20822
20828
  if (!teamParticipantId)
@@ -21424,9 +21430,9 @@ function calculateWinCriteria(_a) {
21424
21430
  finally { if (e_3) throw e_3.error; }
21425
21431
  }
21426
21432
  if (aggregateValueImperative || !valueTotal)
21427
- return { aggregateValue: true };
21433
+ return __assign({ aggregateValue: true }, SUCCESS);
21428
21434
  var valueGoal = Math.floor(valueTotal / 2) + 1;
21429
- return { valueGoal: valueGoal };
21435
+ return __assign({ valueGoal: valueGoal }, SUCCESS);
21430
21436
  }
21431
21437
 
21432
21438
  function getTieFormat$1(_a) {
@@ -21586,7 +21592,8 @@ function tiebreakFormat(tieobject) {
21586
21592
  return undefined;
21587
21593
  }
21588
21594
 
21589
- function isValidMatchUpFormat(matchUpFormat) {
21595
+ function isValidMatchUpFormat(_a) {
21596
+ var matchUpFormat = _a.matchUpFormat;
21590
21597
  if (typeof matchUpFormat !== 'string')
21591
21598
  return false;
21592
21599
  var parsedFormat = parse(matchUpFormat);
@@ -21968,7 +21975,8 @@ function validateCollectionDefinition(_a) {
21968
21975
  if (collectionGroupNumber && typeof collectionGroupNumber !== 'number') {
21969
21976
  errors.push("collectionGroupNumber is not type number: ".concat(collectionValue));
21970
21977
  }
21971
- if (matchUpFormat && !matchUpFormatCode.isValidMatchUpFormat(matchUpFormat)) {
21978
+ if (matchUpFormat &&
21979
+ !matchUpFormatCode.isValidMatchUpFormat({ matchUpFormat: matchUpFormat })) {
21972
21980
  errors.push("Invalid matchUpFormat: ".concat(matchUpFormat));
21973
21981
  }
21974
21982
  if (checkGender) {
@@ -22653,7 +22661,7 @@ function modifyCollectionDefinition(_a) {
22653
22661
  // value assignment, only one is allowed to have a value
22654
22662
  collectionValueProfiles = _a.collectionValueProfiles, collectionValue = _a.collectionValue, matchUpValue = _a.matchUpValue, scoreValue = _a.scoreValue, setValue = _a.setValue;
22655
22663
  var stack = 'modifyCollectionDefinition';
22656
- if (matchUpFormat && !isValidMatchUpFormat(matchUpFormat)) {
22664
+ if (matchUpFormat && !isValidMatchUpFormat({ matchUpFormat: matchUpFormat })) {
22657
22665
  return decorateResult({
22658
22666
  result: { error: INVALID_VALUES },
22659
22667
  context: { matchUpFormat: matchUpFormat },
@@ -26950,7 +26958,7 @@ function tallyParticipantResults(_a) {
26950
26958
  var completedTieMatchUps = matchUps.every(function (_a) {
26951
26959
  var matchUpType = _a.matchUpType, tieMatchUps = _a.tieMatchUps;
26952
26960
  return matchUpType === TEAM$1 &&
26953
- tieMatchUps.every(function (matchUp) { return checkMatchUpIsComplete({ matchUp: matchUp }); });
26961
+ (tieMatchUps === null || tieMatchUps === void 0 ? void 0 : tieMatchUps.every(function (matchUp) { return checkMatchUpIsComplete({ matchUp: matchUp }); }));
26954
26962
  });
26955
26963
  var tallyPolicy = policyDefinitions === null || policyDefinitions === void 0 ? void 0 : policyDefinitions[POLICY_TYPE_ROUND_ROBIN_TALLY];
26956
26964
  var consideredMatchUps = matchUps.filter(function (matchUp) {
@@ -32909,7 +32917,7 @@ function setMatchUpMatchUpFormat(params) {
32909
32917
  return { error: MISSING_DRAW_DEFINITION };
32910
32918
  if (!matchUpFormat)
32911
32919
  return { error: MISSING_MATCHUP_FORMAT };
32912
- if (!isValidMatchUpFormat(matchUpFormat))
32920
+ if (!isValidMatchUpFormat({ matchUpFormat: matchUpFormat }))
32913
32921
  return { error: UNRECOGNIZED_MATCHUP_FORMAT };
32914
32922
  var stack = 'setMatchUpFormat';
32915
32923
  if (matchUpId) {
@@ -32992,7 +33000,7 @@ function setMatchUpFormat(params) {
32992
33000
  return { error: MISSING_TOURNAMENT_RECORD };
32993
33001
  if (!matchUpFormat)
32994
33002
  return { error: MISSING_MATCHUP_FORMAT };
32995
- if (matchUpFormat && !isValidMatchUpFormat(matchUpFormat))
33003
+ if (matchUpFormat && !isValidMatchUpFormat({ matchUpFormat: matchUpFormat }))
32996
33004
  return decorateResult({
32997
33005
  result: { error: UNRECOGNIZED_MATCHUP_FORMAT, matchUpFormat: matchUpFormat },
32998
33006
  stack: stack,
@@ -36328,49 +36336,6 @@ function removeAdHocRound(_a) {
36328
36336
  return __assign({ deletedMatchUpsCount: deletedMatchUpIds.length, roundRemoved: roundRemoved }, SUCCESS);
36329
36337
  }
36330
36338
 
36331
- function addAdHocMatchUps(_a) {
36332
- var _b;
36333
- var _c, _d, _e, _f, _g, _h, _j;
36334
- var tournamentRecord = _a.tournamentRecord, drawDefinition = _a.drawDefinition, structureId = _a.structureId, matchUps = _a.matchUps;
36335
- if (typeof drawDefinition !== 'object')
36336
- return { error: MISSING_DRAW_DEFINITION };
36337
- if (!structureId && ((_c = drawDefinition.structures) === null || _c === void 0 ? void 0 : _c.length) === 1)
36338
- structureId = (_e = (_d = drawDefinition.structures) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.structureId;
36339
- if (typeof structureId !== 'string')
36340
- return { error: MISSING_STRUCTURE_ID };
36341
- if (!validMatchUps(matchUps))
36342
- return { error: INVALID_VALUES, info: mustBeAnArray('matchUps') };
36343
- var structure = (_f = drawDefinition.structures) === null || _f === void 0 ? void 0 : _f.find(function (structure) { return structure.structureId === structureId; });
36344
- if (!structure)
36345
- return { error: STRUCTURE_NOT_FOUND };
36346
- var existingMatchUps = structure === null || structure === void 0 ? void 0 : structure.matchUps;
36347
- var structureHasRoundPositions = existingMatchUps.find(function (matchUp) { return !!matchUp.roundPosition; });
36348
- if (structure.structures ||
36349
- structureHasRoundPositions ||
36350
- structure.finishingPosition === ROUND_OUTCOME) {
36351
- return { error: INVALID_STRUCTURE };
36352
- }
36353
- var existingMatchUpIds = (_j = (_h = (_g = allTournamentMatchUps({
36354
- tournamentRecord: tournamentRecord,
36355
- inContext: false,
36356
- })) === null || _g === void 0 ? void 0 : _g.matchUps) === null || _h === void 0 ? void 0 : _h.map(getMatchUpId)) !== null && _j !== void 0 ? _j : [];
36357
- var newMatchUpIds = matchUps.map(getMatchUpId);
36358
- if (overlap(existingMatchUpIds, newMatchUpIds)) {
36359
- return {
36360
- error: EXISTING_MATCHUP_ID,
36361
- info: 'One or more matchUpIds already present in tournamentRecord',
36362
- };
36363
- }
36364
- (_b = structure.matchUps).push.apply(_b, __spreadArray([], __read(matchUps), false));
36365
- addMatchUpsNotice({
36366
- tournamentId: tournamentRecord === null || tournamentRecord === void 0 ? void 0 : tournamentRecord.tournamentId,
36367
- drawDefinition: drawDefinition,
36368
- matchUps: matchUps,
36369
- });
36370
- modifyDrawNotice({ drawDefinition: drawDefinition, structureIds: [structureId] });
36371
- return __assign({}, SUCCESS);
36372
- }
36373
-
36374
36339
  function aggregateTieFormats(_a) {
36375
36340
  var e_1, _b;
36376
36341
  var _c, _d, _e, _f, _g;
@@ -37264,822 +37229,241 @@ function modifyEventEntries(_a) {
37264
37229
  return __assign({}, SUCCESS);
37265
37230
  }
37266
37231
 
37267
- function attachFlightProfile(_a) {
37268
- var _b;
37269
- var deleteExisting = _a.deleteExisting, event = _a.event, flightProfile = _a.flightProfile;
37270
- var stack = 'attachFlightProfile';
37271
- if (!flightProfile)
37272
- return decorateResult({ result: { error: MISSING_VALUE }, stack: stack });
37273
- if (!event)
37274
- return decorateResult({ result: { error: MISSING_EVENT }, stack: stack });
37275
- var existingFlightProfile = getFlightProfile({ event: event }).flightProfile;
37276
- if (existingFlightProfile && !deleteExisting)
37277
- return decorateResult({ result: { error: EXISTING_PROFILE }, stack: stack });
37278
- if ((_b = event.drawDefinitions) === null || _b === void 0 ? void 0 : _b.length)
37279
- return decorateResult({
37280
- result: { error: EXISTING_DRAW_DEFINITIONS },
37281
- stack: stack,
37232
+ function generateAdHocMatchUps(_a) {
37233
+ var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
37234
+ var participantIdPairings = _a.participantIdPairings, _q = _a.matchUpIds, matchUpIds = _q === void 0 ? [] : _q, drawDefinition = _a.drawDefinition, matchUpsCount = _a.matchUpsCount, roundNumber = _a.roundNumber, structureId = _a.structureId, newRound = _a.newRound, isMock = _a.isMock, event = _a.event;
37235
+ if (typeof drawDefinition !== 'object')
37236
+ return { error: MISSING_DRAW_DEFINITION };
37237
+ if (!structureId && ((_b = drawDefinition.structures) === null || _b === void 0 ? void 0 : _b.length) === 1)
37238
+ structureId = (_d = (_c = drawDefinition.structures) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.structureId;
37239
+ if (typeof structureId !== 'string')
37240
+ return { error: MISSING_STRUCTURE_ID };
37241
+ // if drawDefinition and structureId are provided it is possible to infer roundNumber
37242
+ var structure = (_e = drawDefinition.structures) === null || _e === void 0 ? void 0 : _e.find(function (structure) { return structure.structureId === structureId; });
37243
+ if (!structure)
37244
+ return { error: STRUCTURE_NOT_FOUND };
37245
+ var structureHasRoundPositions;
37246
+ var existingMatchUps = (_f = structure.matchUps) !== null && _f !== void 0 ? _f : [];
37247
+ var lastRoundNumber = existingMatchUps === null || existingMatchUps === void 0 ? void 0 : existingMatchUps.reduce(function (roundNumber, matchUp) {
37248
+ if (matchUp.roundPosition)
37249
+ structureHasRoundPositions = true;
37250
+ return ((matchUp === null || matchUp === void 0 ? void 0 : matchUp.roundNumber) || 0) > roundNumber
37251
+ ? matchUp.roundNumber
37252
+ : roundNumber;
37253
+ }, 0);
37254
+ if (!matchUpsCount) {
37255
+ var selectedEntries = (_h = (_g = drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.entries) === null || _g === void 0 ? void 0 : _g.filter(function (entry) {
37256
+ var entryStatus = entry.entryStatus;
37257
+ return STRUCTURE_SELECTED_STATUSES.includes(entryStatus);
37258
+ })) !== null && _h !== void 0 ? _h : [];
37259
+ var roundMatchUpsCount = Math.floor((selectedEntries === null || selectedEntries === void 0 ? void 0 : selectedEntries.length) / 2) || 1;
37260
+ if (newRound) {
37261
+ matchUpsCount = roundMatchUpsCount;
37262
+ }
37263
+ else {
37264
+ var targetRoundNumber_1 = (_j = roundNumber !== null && roundNumber !== void 0 ? roundNumber : lastRoundNumber) !== null && _j !== void 0 ? _j : 1;
37265
+ var existingRoundMatchUps = (_m = (_l = (_k = structure.matchUps) === null || _k === void 0 ? void 0 : _k.filter(function (matchUp) { return matchUp.roundNumber === targetRoundNumber_1; })) === null || _l === void 0 ? void 0 : _l.length) !== null && _m !== void 0 ? _m : 0;
37266
+ var maxRemaining = roundMatchUpsCount - existingRoundMatchUps;
37267
+ if (maxRemaining > 0)
37268
+ matchUpsCount = maxRemaining;
37269
+ }
37270
+ }
37271
+ if ((participantIdPairings && !Array.isArray(participantIdPairings)) ||
37272
+ (matchUpsCount && !isConvertableInteger(matchUpsCount)) ||
37273
+ (matchUpIds && !Array.isArray(matchUpIds)) ||
37274
+ (!participantIdPairings && !matchUpsCount)) {
37275
+ return { error: INVALID_VALUES, info: 'matchUpsCount or pairings error' };
37276
+ }
37277
+ // structure must not be a container of other structures
37278
+ // structure must not contain matchUps with roundPosition
37279
+ // structure must not determine finishingPosition by ROUND_OUTCOME
37280
+ if (structure.structures ||
37281
+ structureHasRoundPositions ||
37282
+ structure.finishingPosition === ROUND_OUTCOME) {
37283
+ return { error: INVALID_STRUCTURE };
37284
+ }
37285
+ if (roundNumber && roundNumber - 1 > (lastRoundNumber || 0))
37286
+ return { error: INVALID_VALUES, info: 'roundNumber error' };
37287
+ var nextRoundNumber = roundNumber !== null && roundNumber !== void 0 ? roundNumber : ((newRound && (lastRoundNumber !== null && lastRoundNumber !== void 0 ? lastRoundNumber : 0) + 1) || lastRoundNumber || 1);
37288
+ participantIdPairings =
37289
+ participantIdPairings !== null && participantIdPairings !== void 0 ? participantIdPairings : generateRange(0, matchUpsCount).map(function () { return ({
37290
+ participantIds: [undefined, undefined],
37291
+ }); });
37292
+ var matchUps = participantIdPairings === null || participantIdPairings === void 0 ? void 0 : participantIdPairings.map(function (pairing) {
37293
+ var _a, _b;
37294
+ var idStack = (_a = pairing === null || pairing === void 0 ? void 0 : pairing.participantIds) !== null && _a !== void 0 ? _a : [undefined, undefined];
37295
+ // ensure there are always 2 sides in generated matchUps
37296
+ idStack.push.apply(idStack, [undefined, undefined]);
37297
+ var participantIds = idStack.slice(0, 2);
37298
+ var sides = participantIds.map(function (participantId, i) {
37299
+ return definedAttributes({
37300
+ sideNumber: i + 1,
37301
+ participantId: participantId,
37302
+ });
37282
37303
  });
37283
- var extension = {
37284
- name: FLIGHT_PROFILE,
37285
- value: flightProfile,
37286
- };
37287
- addEventExtension({ event: event, extension: extension });
37288
- return __assign({ flightProfile: makeDeepCopy(flightProfile, false, true) }, SUCCESS);
37289
- }
37290
-
37291
- /**
37292
- *
37293
- * @param {object} tournamentRecord - passed automatically if tournamentEngine.setState()
37294
- * @param {string[]} participantIds
37295
- * @param {string} scaleAttributes - { scaleType, scaleName, eventType }
37296
- * @returns {boolean} { success: true } or { error }
37297
- */
37298
- function removeParticipantsScaleItems(_a) {
37299
- var _b;
37300
- var tournamentRecord = _a.tournamentRecord, scaleAttributes = _a.scaleAttributes, participantIds = _a.participantIds;
37301
- if (!tournamentRecord)
37302
- return { error: MISSING_TOURNAMENT_RECORD };
37303
- if (!participantIds)
37304
- return { error: MISSING_PARTICIPANT_IDS };
37305
- if (!scaleAttributes)
37306
- return { error: MISSING_VALUE, info: 'scaleAttributes required' };
37307
- var scaleType = scaleAttributes.scaleType, eventType = scaleAttributes.eventType, scaleName = scaleAttributes.scaleName;
37308
- var itemType = [SCALE, scaleType, eventType, scaleName].join('.');
37309
- (_b = tournamentRecord.participants) === null || _b === void 0 ? void 0 : _b.forEach(function (participant) {
37310
- if (participantIds.includes(participant.participantId) &&
37311
- participant.timeItems) {
37312
- participant.timeItems = participant.timeItems.filter(function (timeItem) {
37313
- return timeItem && (timeItem === null || timeItem === void 0 ? void 0 : timeItem.itemType) !== itemType;
37304
+ return {
37305
+ matchUpId: (_b = matchUpIds.pop()) !== null && _b !== void 0 ? _b : UUID(),
37306
+ roundNumber: nextRoundNumber,
37307
+ matchUpStatus: TO_BE_PLAYED,
37308
+ sides: sides,
37309
+ };
37310
+ });
37311
+ if (matchUps === null || matchUps === void 0 ? void 0 : matchUps.length) {
37312
+ var tieFormat_1 = (_o = resolveTieFormat({ drawDefinition: drawDefinition, event: event })) === null || _o === void 0 ? void 0 : _o.tieFormat;
37313
+ if (tieFormat_1) {
37314
+ matchUps.forEach(function (matchUp) {
37315
+ var tieMatchUps = generateTieMatchUps({ tieFormat: tieFormat_1, isMock: isMock }).tieMatchUps;
37316
+ Object.assign(matchUp, { tieMatchUps: tieMatchUps, matchUpType: TEAM$1 });
37314
37317
  });
37315
37318
  }
37316
- });
37317
- return __assign({}, SUCCESS);
37319
+ }
37320
+ return __assign({ matchUpsCount: (_p = matchUps === null || matchUps === void 0 ? void 0 : matchUps.length) !== null && _p !== void 0 ? _p : 0, matchUps: matchUps }, SUCCESS);
37318
37321
  }
37319
37322
 
37320
- /**
37321
- *
37322
- * @param {object} tournamentRecord - passed automatically if tournamentEngine.setState()
37323
- * @param {string} eventId - resolves to event
37324
- * @param {string} drawId - OPTIONAL - resolves drawDefinition - scopes participants to clear to drawDefinition.entries or flightProfile.flight.drawEntries
37325
- * @param {string} scaleAttributes - { scaleType, scaleName, eventType }
37326
- * @param {string} stage - OPTIONAL - filter event or draw entries by stage
37327
- * @returns {boolean} { success: true } or { error }
37328
- */
37329
- function removeScaleValues(_a) {
37330
- var _b;
37331
- var tournamentRecord = _a.tournamentRecord, scaleAttributes = _a.scaleAttributes, drawDefinition = _a.drawDefinition, entryStatuses = _a.entryStatuses, drawId = _a.drawId, event = _a.event, stage = _a.stage;
37332
- if (!event)
37333
- return { error: MISSING_EVENT };
37334
- if (entryStatuses && !Array.isArray(entryStatuses))
37335
- return decorateResult({
37336
- result: { error: INVALID_VALUES },
37337
- info: mustBeAnArray('entryStatus'),
37338
- stack: 'removeScaleValues',
37323
+ function generateCandidate(_a) {
37324
+ var _b = _a.maxIterations, maxIterations = _b === void 0 ? 4000 : _b, // cap the processing intensity of the candidate generator
37325
+ valueSortedPairings = _a.valueSortedPairings, // pairings sorted by value from low to high
37326
+ pairingValues = _a.pairingValues, valueObjects = _a.valueObjects, deltaObjects = _a.deltaObjects;
37327
+ var pairingValueMap = Object.assign.apply(Object, __spreadArray([{}], __read(valueSortedPairings.map(function (rm) {
37328
+ var _a;
37329
+ return (_a = {}, _a[rm.pairing] = rm.value, _a);
37330
+ })), false));
37331
+ var actors = Object.keys(pairingValues);
37332
+ var proposedCandidates = [];
37333
+ // generate an initial candidate value with no stipulated pairings
37334
+ var initialProposal = roundCandidate({
37335
+ actorsCount: actors.length,
37336
+ valueSortedPairings: valueSortedPairings,
37337
+ pairingValueMap: pairingValueMap,
37338
+ deltaObjects: deltaObjects,
37339
+ valueObjects: valueObjects,
37340
+ });
37341
+ var candidateHashes = [candidateHash(initialProposal)];
37342
+ proposedCandidates.push(initialProposal);
37343
+ var lowCandidateValue = initialProposal.value;
37344
+ var deltaCandidate = initialProposal;
37345
+ // iterations is the number of loops over valueSortedPairings
37346
+ var candidatesCount = 0;
37347
+ var iterations = 0;
37348
+ var opponentCount = actors.length;
37349
+ var calculatedIterations;
37350
+ // calculate the number of opponents to consider for each participantId
37351
+ do {
37352
+ opponentCount -= 1;
37353
+ calculatedIterations = actors.length * pairingValues[actors[0]].length;
37354
+ } while (calculatedIterations > maxIterations && opponentCount > 5);
37355
+ // keep track of proposed pairings
37356
+ var stipulatedPairs = [];
37357
+ // for each actor generate a roundCandidate using opponentCount of pairing values
37358
+ actors.forEach(function (actor) {
37359
+ var participantIdPairings = pairingValues[actor];
37360
+ // opponentCount limits the number of opponents to consider
37361
+ participantIdPairings.slice(0, opponentCount).forEach(function (pairing) {
37362
+ iterations += 1;
37363
+ var stipulatedPair = pairingHash(actor, pairing.opponent);
37364
+ if (!stipulatedPairs.includes(stipulatedPair)) {
37365
+ var proposed = roundCandidate({
37366
+ // each roundCandidate starts with stipulated pairings
37367
+ stipulated: [[actor, pairing.opponent]],
37368
+ actorsCount: actors.length,
37369
+ valueSortedPairings: valueSortedPairings,
37370
+ pairingValueMap: pairingValueMap,
37371
+ deltaObjects: deltaObjects,
37372
+ valueObjects: valueObjects,
37373
+ });
37374
+ // ensure no duplicate candidates are considered
37375
+ if (!candidateHashes.includes(candidateHash(proposed))) {
37376
+ candidateHashes.push(candidateHash(proposed));
37377
+ proposedCandidates.push(proposed);
37378
+ var maxDelta = proposed.maxDelta, value = proposed.value;
37379
+ if (maxDelta < deltaCandidate.maxDelta)
37380
+ deltaCandidate = proposed;
37381
+ if (value < lowCandidateValue ||
37382
+ (value === lowCandidateValue && Math.round(Math.random())) // randomize if equivalent values
37383
+ ) {
37384
+ lowCandidateValue = value;
37385
+ }
37386
+ stipulatedPairs.push(stipulatedPair);
37387
+ candidatesCount += 1;
37388
+ }
37389
+ }
37339
37390
  });
37340
- var entries = event.entries;
37341
- if (drawId) {
37342
- var flightProfile = getFlightProfile({ event: event }).flightProfile;
37343
- var flight = (_b = flightProfile === null || flightProfile === void 0 ? void 0 : flightProfile.flights) === null || _b === void 0 ? void 0 : _b.find(function (flight) { return flight.drawId === drawId; });
37344
- if (flight) {
37345
- entries = flight.drawEntries;
37346
- }
37347
- else {
37348
- entries = drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.entries;
37349
- }
37350
- }
37351
- var stageEntries = (entries || []).filter(function (entry) {
37352
- return (!stage || !entry.entryStage || entry.entryStage === stage) &&
37353
- (!entryStatuses || entryStatuses.includes(entry.entryStatus));
37391
+ proposedCandidates = proposedCandidates.filter(function (proposed) { return Math.abs(proposed.value - lowCandidateValue) < 5; });
37354
37392
  });
37355
- var participantIds = stageEntries.map(getParticipantId);
37356
- return removeParticipantsScaleItems({
37357
- tournamentRecord: tournamentRecord,
37358
- scaleAttributes: scaleAttributes,
37359
- participantIds: participantIds,
37393
+ proposedCandidates.sort(function (a, b) { return a.maxDiff - b.maxDiff; });
37394
+ var candidate = randomPop(proposedCandidates);
37395
+ return {
37396
+ candidatesCount: candidatesCount,
37397
+ deltaCandidate: deltaCandidate,
37398
+ maxIterations: maxIterations,
37399
+ iterations: iterations,
37400
+ candidate: candidate,
37401
+ };
37402
+ }
37403
+ function candidateHash(candidate) {
37404
+ return candidate.participantIdPairings
37405
+ .map(function (_a) {
37406
+ var participantIds = _a.participantIds;
37407
+ return participantIds.sort().join('|');
37408
+ })
37409
+ .sort()
37410
+ .join('/');
37411
+ }
37412
+ function roundCandidate(_a) {
37413
+ var valueSortedPairings = _a.valueSortedPairings, _b = _a.stipulated, stipulated = _b === void 0 ? [] : _b, pairingValueMap = _a.pairingValueMap, deltaObjects = _a.deltaObjects, valueObjects = _a.valueObjects, actorsCount = _a.actorsCount;
37414
+ // roundPlayers starts with the stipulated pairing
37415
+ var roundPlayers = [].concat.apply([], __spreadArray([], __read(stipulated), false));
37416
+ // aggregates the pairings generated for a roundCandidate
37417
+ var participantIdPairings = [];
37418
+ // candidateValue is the sum of all participantIdPairings in a roundCandidate
37419
+ // the winning candidate has the LOWEST total value
37420
+ var candidateValue = 0;
37421
+ // candidateValue is initialized with any stipulated pairings
37422
+ stipulated.filter(Boolean).forEach(function (participantIds) {
37423
+ var _a = __read(participantIds, 2), p1 = _a[0], p2 = _a[1];
37424
+ var pairing = pairingHash(p1, p2);
37425
+ var value = pairingValueMap[pairing];
37426
+ participantIdPairings.push({ participantIds: participantIds, value: value });
37427
+ candidateValue += pairingValueMap[pairing];
37428
+ });
37429
+ // valueSortedPairings is an array sorted from lowest value to highest value
37430
+ // introduce random shuffling of chunks of valueSortedPairings
37431
+ var consideredPairings = chunkArray(valueSortedPairings, actorsCount)
37432
+ .map(function (pairings) {
37433
+ return shuffleArray(pairings).map(function (pairing) { return (__assign(__assign({}, pairing), { value: pairing.value + Math.random() * Math.round(Math.random()) })); });
37434
+ })
37435
+ .flat();
37436
+ // go through the valueSortedPairings (of all possible unique pairings)
37437
+ consideredPairings.forEach(function (rankedPairing) {
37438
+ var participantIds = rankedPairing.pairing.split('|');
37439
+ var opponentExists = participantIds.reduce(function (p, c) { return roundPlayers.includes(c) || p; }, false);
37440
+ if (!opponentExists) {
37441
+ roundPlayers.push.apply(roundPlayers, __spreadArray([], __read(participantIds), false));
37442
+ var value = rankedPairing.value;
37443
+ candidateValue += value;
37444
+ participantIdPairings.push({ participantIds: participantIds, value: value });
37445
+ }
37360
37446
  });
37361
- }
37362
-
37363
- function applyLineUps(_a) {
37364
- var e_1, _b, e_2, _c, e_3, _d, e_4, _e;
37365
- var _f, _g, _h, _j;
37366
- var tournamentRecord = _a.tournamentRecord, drawDefinition = _a.drawDefinition, matchUpId = _a.matchUpId, lineUps = _a.lineUps, event = _a.event;
37367
- if (!tournamentRecord)
37368
- return { error: MISSING_TOURNAMENT_RECORD };
37369
- if (!drawDefinition)
37370
- return { error: DRAW_DEFINITION_NOT_FOUND };
37371
- if (typeof matchUpId !== 'string')
37372
- return { error: INVALID_MATCHUP };
37373
- if (!Array.isArray(lineUps))
37374
- return { error: INVALID_VALUES, lineUps: lineUps };
37375
- var stack = 'applyLineUps';
37376
- var tournamentParticipants = tournamentRecord.participants || [];
37377
- var result = findDrawMatchUp({
37378
- tournamentParticipants: tournamentParticipants,
37379
- inContext: true,
37380
- drawDefinition: drawDefinition,
37381
- matchUpId: matchUpId,
37382
- });
37383
- if (result.error)
37384
- return result;
37385
- if (!result.matchUp)
37386
- return { error: MATCHUP_NOT_FOUND };
37387
- var inContextMatchUp = result.matchUp, structure = result.structure;
37388
- var drawPositions = inContextMatchUp.drawPositions, matchUpType = inContextMatchUp.matchUpType;
37389
- if (matchUpType !== TEAM$1)
37390
- return { error: INVALID_MATCHUP };
37391
- if (!(drawPositions === null || drawPositions === void 0 ? void 0 : drawPositions.length))
37392
- return { error: MISSING_DRAW_POSITIONS };
37393
- var tieFormat = (_f = resolveTieFormat({
37394
- matchUp: inContextMatchUp,
37395
- drawDefinition: drawDefinition,
37396
- structure: structure,
37397
- event: event,
37398
- })) === null || _f === void 0 ? void 0 : _f.tieFormat;
37399
- // verify integrity of lineUps...
37400
- // 1. all participantIds must be valid individualParticipantIds
37401
- // 2. there should be at most one participantId for a given collectionPosition in singles
37402
- // 3. there should be at most two participantIds for a given collectionPosition in doubles
37403
- var sideAssignments = {};
37404
- try {
37405
- for (var lineUps_1 = __values(lineUps), lineUps_1_1 = lineUps_1.next(); !lineUps_1_1.done; lineUps_1_1 = lineUps_1.next()) {
37406
- var lineUp = lineUps_1_1.value;
37407
- if (!Array.isArray(lineUp))
37408
- return { error: INVALID_VALUES, lineUp: lineUp };
37409
- // maintain mapping of collectionId|collectionPosition to the participantIds assigned
37410
- var collectionParticipantIds = {};
37411
- var sideNumbers = [];
37412
- var _loop_1 = function (lineUpAssignment) {
37413
- var e_5, _m;
37414
- if (typeof lineUpAssignment !== 'object')
37415
- return { value: { error: INVALID_VALUES, lineUpAssignment: lineUpAssignment } };
37416
- var participantId = lineUpAssignment.participantId, _o = lineUpAssignment.collectionAssignments, collectionAssignments = _o === void 0 ? [] : _o;
37417
- if (!Array.isArray(collectionAssignments))
37418
- return { value: { error: INVALID_VALUES, collectionAssignments: collectionAssignments } };
37419
- var participant = tournamentParticipants.find(function (participant) { return participant.participantId === participantId; });
37420
- if (!participant)
37421
- return { value: { error: PARTICIPANT_NOT_FOUND } };
37422
- if (participant.participantType !== INDIVIDUAL)
37423
- return { value: { error: INVALID_PARTICIPANT_TYPE } };
37424
- var sideNumber_1 = (_h = (_g = inContextMatchUp.sides) === null || _g === void 0 ? void 0 : _g.find(function (side) { var _a, _b; return (_b = (_a = side.participant) === null || _a === void 0 ? void 0 : _a.individualParticipantIds) === null || _b === void 0 ? void 0 : _b.includes(participantId); })) === null || _h === void 0 ? void 0 : _h.sideNumber;
37425
- if (sideNumber_1)
37426
- sideNumbers.push(sideNumber_1);
37427
- var _loop_3 = function (collectionAssignment) {
37428
- if (typeof collectionAssignment !== 'object')
37429
- return { value: { error: INVALID_VALUES, collectionAssignment: collectionAssignment } };
37430
- var collectionId = collectionAssignment.collectionId, collectionPosition = collectionAssignment.collectionPosition;
37431
- var collectionDefinition = (_j = tieFormat === null || tieFormat === void 0 ? void 0 : tieFormat.collectionDefinitions) === null || _j === void 0 ? void 0 : _j.find(function (collectionDefinition) {
37432
- return collectionDefinition.collectionId === collectionId;
37433
- });
37434
- // all collectionIds in the lineUp must be present in the tieFormat collectionDefinitions
37435
- if (!collectionDefinition)
37436
- return { value: { error: INVALID_VALUES, collectionId: collectionId } };
37437
- var aggregator = "".concat(collectionId, "-").concat(collectionPosition);
37438
- if (!collectionParticipantIds[aggregator]) {
37439
- collectionParticipantIds[aggregator] = [];
37440
- }
37441
- var participantsCount = collectionParticipantIds[aggregator].length;
37442
- if ((collectionDefinition.matchUpType === SINGLES && participantsCount) ||
37443
- (collectionDefinition.matchUpType === DOUBLES &&
37444
- participantsCount > 1)) {
37445
- return { value: {
37446
- info: 'Excessive collectionPosition assignments',
37447
- error: INVALID_VALUES,
37448
- } };
37449
- }
37450
- collectionParticipantIds[aggregator].push(participantId);
37451
- };
37452
- try {
37453
- for (var collectionAssignments_1 = (e_5 = void 0, __values(collectionAssignments)), collectionAssignments_1_1 = collectionAssignments_1.next(); !collectionAssignments_1_1.done; collectionAssignments_1_1 = collectionAssignments_1.next()) {
37454
- var collectionAssignment = collectionAssignments_1_1.value;
37455
- var state_2 = _loop_3(collectionAssignment);
37456
- if (typeof state_2 === "object")
37457
- return state_2;
37458
- }
37459
- }
37460
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
37461
- finally {
37462
- try {
37463
- if (collectionAssignments_1_1 && !collectionAssignments_1_1.done && (_m = collectionAssignments_1.return)) _m.call(collectionAssignments_1);
37464
- }
37465
- finally { if (e_5) throw e_5.error; }
37466
- }
37467
- };
37468
- try {
37469
- for (var lineUp_1 = (e_2 = void 0, __values(lineUp)), lineUp_1_1 = lineUp_1.next(); !lineUp_1_1.done; lineUp_1_1 = lineUp_1.next()) {
37470
- var lineUpAssignment = lineUp_1_1.value;
37471
- var state_1 = _loop_1(lineUpAssignment);
37472
- if (typeof state_1 === "object")
37473
- return state_1.value;
37474
- }
37475
- }
37476
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
37477
- finally {
37478
- try {
37479
- if (lineUp_1_1 && !lineUp_1_1.done && (_c = lineUp_1.return)) _c.call(lineUp_1);
37480
- }
37481
- finally { if (e_2) throw e_2.error; }
37482
- }
37483
- // ensure that doubles pair participants exist, otherwise create
37484
- var collectionParticipantIdPairs = Object.values(collectionParticipantIds);
37485
- try {
37486
- for (var collectionParticipantIdPairs_1 = (e_3 = void 0, __values(collectionParticipantIdPairs)), collectionParticipantIdPairs_1_1 = collectionParticipantIdPairs_1.next(); !collectionParticipantIdPairs_1_1.done; collectionParticipantIdPairs_1_1 = collectionParticipantIdPairs_1.next()) {
37487
- var participantIds = collectionParticipantIdPairs_1_1.value;
37488
- if (participantIds.length === 2) {
37489
- var pairedParticipant = getPairedParticipant({
37490
- tournamentParticipants: tournamentParticipants,
37491
- participantIds: participantIds,
37492
- }).participant;
37493
- if (!pairedParticipant) {
37494
- // create pair participant
37495
- var newPairParticipant = {
37496
- participantType: PAIR,
37497
- participantRole: COMPETITOR,
37498
- individualParticipantIds: participantIds,
37499
- };
37500
- var result_1 = addParticipant({
37501
- participant: newPairParticipant,
37502
- pairOverride: true,
37503
- tournamentRecord: tournamentRecord,
37504
- });
37505
- if (result_1.error)
37506
- return result_1;
37507
- }
37508
- }
37509
- }
37510
- }
37511
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
37512
- finally {
37513
- try {
37514
- if (collectionParticipantIdPairs_1_1 && !collectionParticipantIdPairs_1_1.done && (_d = collectionParticipantIdPairs_1.return)) _d.call(collectionParticipantIdPairs_1);
37515
- }
37516
- finally { if (e_3) throw e_3.error; }
37517
- }
37518
- // determine sideNumber based on instances of participants appearing in team participants assigned to sides
37519
- // allows for some team members to be "borrowed"
37520
- var instances = instanceCount(sideNumbers);
37521
- var sideNumber = ((instances[1] || 0) > (instances[2] || 0) && 1) ||
37522
- ((instances[2] || 0) > (instances[1] || 0) && 2) ||
37523
- undefined;
37524
- // if side not previously assigned, map sideNumber to lineUp
37525
- var sideAssignmentKeys = Object.keys(sideAssignments).map(function (key) {
37526
- return parseInt(key);
37527
- });
37528
- if (sideNumber && !sideAssignmentKeys.includes(sideNumber)) {
37529
- sideAssignments[sideNumber] = lineUp;
37530
- }
37531
- }
37532
- }
37533
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
37534
- finally {
37535
- try {
37536
- if (lineUps_1_1 && !lineUps_1_1.done && (_b = lineUps_1.return)) _b.call(lineUps_1);
37537
- }
37538
- finally { if (e_1) throw e_1.error; }
37539
- }
37540
- if (!Object.keys(sideAssignments).length)
37541
- return { error: VALUE_UNCHANGED };
37542
- result = findDrawMatchUp({ drawDefinition: drawDefinition, matchUpId: matchUpId });
37543
- if (result.error)
37544
- return result;
37545
- if (!result.matchUp)
37546
- return { error: MATCHUP_NOT_FOUND };
37547
- var matchUp = result.matchUp;
37548
- if (!matchUp.sides)
37549
- matchUp.sides = [];
37550
- var _loop_2 = function (sideNumber) {
37551
- var side = matchUp.sides.find(function (side) { return side.sideNumber === sideNumber; });
37552
- var assignment = sideAssignments[sideNumber];
37553
- if (!assignment) {
37554
- return "continue";
37555
- }
37556
- else if (!side) {
37557
- matchUp.sides.push({ lineUp: assignment, sideNumber: sideNumber });
37558
- }
37559
- else {
37560
- side.lineUp = assignment;
37561
- }
37562
- };
37563
- try {
37564
- for (var _k = __values([1, 2]), _l = _k.next(); !_l.done; _l = _k.next()) {
37565
- var sideNumber = _l.value;
37566
- _loop_2(sideNumber);
37567
- }
37568
- }
37569
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
37570
- finally {
37571
- try {
37572
- if (_l && !_l.done && (_e = _k.return)) _e.call(_k);
37573
- }
37574
- finally { if (e_4) throw e_4.error; }
37575
- }
37576
- modifyMatchUpNotice({
37577
- tournamentId: tournamentRecord === null || tournamentRecord === void 0 ? void 0 : tournamentRecord.tournamentId,
37578
- context: stack,
37579
- drawDefinition: drawDefinition,
37580
- matchUp: matchUp,
37581
- });
37582
- return __assign({}, SUCCESS);
37583
- }
37584
-
37585
- function resetTieFormat(params) {
37586
- var _a, _b, e_1, _c, e_2, _d;
37587
- var _e, _f, _g;
37588
- var stack = 'resetTieFormat';
37589
- var drawDefinition = params.drawDefinition, event = params.event, uuids = params.uuids;
37590
- var paramCheck = checkRequiredParameters(params, [(_a = {}, _a[TOURNAMENT_RECORD] = true, _a[MATCHUP_ID] = true, _a)], stack);
37591
- if (paramCheck.error)
37592
- return paramCheck;
37593
- var resolutions = resolveFromParameters(params, [(_b = {}, _b[PARAM] = MATCHUP, _b)]);
37594
- if (resolutions[ERROR])
37595
- return resolutions;
37596
- var tournamentId = (_e = params.tournamentRecord) === null || _e === void 0 ? void 0 : _e.tournamentId;
37597
- var _h = (_f = resolutions === null || resolutions === void 0 ? void 0 : resolutions.matchUp) !== null && _f !== void 0 ? _f : {}, matchUp = _h.matchUp, structure = _h.structure;
37598
- if (!(matchUp === null || matchUp === void 0 ? void 0 : matchUp.tieMatchUps))
37599
- return decorateResult({
37600
- result: { error: INVALID_MATCHUP },
37601
- info: 'Must be a TEAM matchUp',
37602
- stack: stack,
37603
- });
37604
- // if there is no tieFormat there is nothing to do
37605
- if (!matchUp.tieFormat)
37606
- return __assign({}, SUCCESS);
37607
- var tieFormat = (_g = resolveTieFormat({
37608
- structure: structure,
37609
- drawDefinition: drawDefinition,
37610
- event: event,
37611
- })) === null || _g === void 0 ? void 0 : _g.tieFormat;
37612
- if (!tieFormat)
37613
- return decorateResult({
37614
- result: { error: NOT_FOUND },
37615
- info: 'No inherited tieFormat',
37616
- stack: stack,
37617
- });
37618
- var deletedMatchUpIds = [];
37619
- var collectionIds = [];
37620
- var tieMatchUps = [];
37621
- var newMatchUps = [];
37622
- var _loop_1 = function (collectionDefinition) {
37623
- // delete any matchUp.tieMatchUps that are not found in the ancestor tieFormat collectionDefinitions
37624
- var matchUpCount = collectionDefinition.matchUpCount, collectionId = collectionDefinition.collectionId;
37625
- collectionIds.push(collectionId);
37626
- var existingCollectionMatchUps = (matchUp.tieMatchUps || []).filter(function (matchUp) { return matchUp.collectionId === collectionId; });
37627
- if (existingCollectionMatchUps.length > matchUpCount) {
37628
- // sort by matchUpStatus to prioritize active or completed matchUpsA
37629
- existingCollectionMatchUps.sort(function (a, b) {
37630
- return (a.matchUpStatus === TO_BE_PLAYED ? 1 : 0) -
37631
- (b.matchUpStatus === TO_BE_PLAYED ? 1 : 0);
37632
- });
37633
- tieMatchUps.push.apply(tieMatchUps, __spreadArray([], __read(existingCollectionMatchUps.slice(0, matchUpCount)), false));
37634
- deletedMatchUpIds.push.apply(deletedMatchUpIds, __spreadArray([], __read(existingCollectionMatchUps.slice(3).map(getMatchUpId)), false));
37635
- }
37636
- else {
37637
- tieMatchUps.push.apply(tieMatchUps, __spreadArray([], __read(existingCollectionMatchUps), false));
37638
- if (existingCollectionMatchUps.length < matchUpCount) {
37639
- var matchUpsLimit = matchUpCount - existingCollectionMatchUps.length;
37640
- var matchUps = generateCollectionMatchUps({
37641
- collectionDefinition: collectionDefinition,
37642
- matchUpsLimit: matchUpsLimit,
37643
- uuids: uuids,
37644
- });
37645
- newMatchUps.push.apply(newMatchUps, __spreadArray([], __read(matchUps), false));
37646
- }
37647
- }
37648
- };
37649
- try {
37650
- for (var _j = __values(tieFormat.collectionDefinitions), _k = _j.next(); !_k.done; _k = _j.next()) {
37651
- var collectionDefinition = _k.value;
37652
- _loop_1(collectionDefinition);
37653
- }
37654
- }
37655
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
37656
- finally {
37657
- try {
37658
- if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
37659
- }
37660
- finally { if (e_1) throw e_1.error; }
37661
- }
37662
- try {
37663
- for (var _l = __values((matchUp === null || matchUp === void 0 ? void 0 : matchUp.tieMatchUps) || []), _m = _l.next(); !_m.done; _m = _l.next()) {
37664
- var tieMatchUp = _m.value;
37665
- if (tieMatchUp.collectionId &&
37666
- !collectionIds.includes(tieMatchUp.collectionId))
37667
- deletedMatchUpIds.push(tieMatchUp.matchUpId);
37668
- }
37669
- }
37670
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
37671
- finally {
37672
- try {
37673
- if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
37674
- }
37675
- finally { if (e_2) throw e_2.error; }
37676
- }
37677
- if (newMatchUps.length) {
37678
- tieMatchUps.push.apply(tieMatchUps, __spreadArray([], __read(newMatchUps), false));
37679
- addMatchUpsNotice({
37680
- eventId: event === null || event === void 0 ? void 0 : event.eventId,
37681
- matchUps: newMatchUps,
37682
- drawDefinition: drawDefinition,
37683
- tournamentId: tournamentId,
37684
- });
37685
- }
37686
- if (deletedMatchUpIds.length) {
37687
- deleteMatchUpsNotice({
37688
- matchUpIds: deletedMatchUpIds,
37689
- eventId: event === null || event === void 0 ? void 0 : event.eventId,
37690
- drawDefinition: drawDefinition,
37691
- tournamentId: tournamentId,
37692
- });
37693
- }
37694
- if (matchUp) {
37695
- matchUp.tieMatchUps = tieMatchUps;
37696
- matchUp.tieFormatId = undefined;
37697
- matchUp.tieFormat = undefined;
37698
- modifyMatchUpNotice({
37699
- structureId: structure === null || structure === void 0 ? void 0 : structure.structureId,
37700
- eventId: event === null || event === void 0 ? void 0 : event.eventId,
37701
- context: stack,
37702
- drawDefinition: drawDefinition,
37703
- tournamentId: tournamentId,
37704
- matchUp: matchUp,
37705
- });
37706
- }
37707
- return __assign(__assign({}, SUCCESS), { newMatchUps: newMatchUps, deletedMatchUpIds: deletedMatchUpIds });
37708
- }
37709
-
37710
- function resetScorecard(params) {
37711
- var e_1, _a;
37712
- var _b, _c;
37713
- var tournamentRecord = params.tournamentRecord, drawDefinition = params.drawDefinition, matchUpId = params.matchUpId, event = params.event;
37714
- var stack = 'resetScorecard';
37715
- // Check for missing parameters ---------------------------------------------
37716
- if (!drawDefinition)
37717
- return decorateResult({
37718
- result: { error: MISSING_DRAW_DEFINITION },
37719
- stack: stack,
37720
- });
37721
- if (!matchUpId)
37722
- return decorateResult({ result: { error: MISSING_MATCHUP_ID }, stack: stack });
37723
- if (!isString(matchUpId))
37724
- return decorateResult({
37725
- result: { error: INVALID_VALUES, matchUpId: matchUpId },
37726
- stack: stack,
37727
- });
37728
- // Get map of all drawMatchUps and inContextDrawMatchUPs ---------------------
37729
- var matchUpsMap = getMatchUpsMap({ drawDefinition: drawDefinition });
37730
- var inContextDrawMatchUps = getAllDrawMatchUps({
37731
- nextMatchUps: true,
37732
- inContext: true,
37733
- drawDefinition: drawDefinition,
37734
- matchUpsMap: matchUpsMap,
37735
- }).matchUps;
37736
- // Find target matchUp ------------------------------------------------------
37737
- var matchUp = matchUpsMap.drawMatchUps.find(function (matchUp) { return matchUp.matchUpId === matchUpId; });
37738
- var inContextMatchUp = inContextDrawMatchUps === null || inContextDrawMatchUps === void 0 ? void 0 : inContextDrawMatchUps.find(function (matchUp) { return matchUp.matchUpId === matchUpId; });
37739
- if (!matchUp || !inContextDrawMatchUps)
37740
- return { error: MATCHUP_NOT_FOUND };
37741
- // only accept matchUpType: TEAM
37742
- if (matchUp.matchUpType !== TEAM_EVENT)
37743
- return { error: INVALID_MATCHUP };
37744
- // Get winner/loser position targets ----------------------------------------
37745
- var targetData = positionTargets({
37746
- inContextDrawMatchUps: inContextDrawMatchUps,
37747
- drawDefinition: drawDefinition,
37748
- matchUpId: matchUpId,
37749
- });
37750
- var structureId = inContextMatchUp === null || inContextMatchUp === void 0 ? void 0 : inContextMatchUp.structureId;
37751
- var structure = findStructure({ drawDefinition: drawDefinition, structureId: structureId }).structure;
37752
- Object.assign(params, {
37753
- inContextDrawMatchUps: inContextDrawMatchUps,
37754
- inContextMatchUp: inContextMatchUp,
37755
- matchUpsMap: matchUpsMap,
37756
- targetData: targetData,
37757
- structure: structure,
37758
- matchUp: matchUp,
37759
- });
37760
- // with propagating winningSide changes, activeDownstream only applies to eventType: TEAM
37761
- var activeDownstream = isActiveDownstream(params);
37762
- if (activeDownstream)
37763
- return { error: CANNOT_CHANGE_WINNING_SIDE };
37764
- if ((_b = matchUp.tieMatchUps) === null || _b === void 0 ? void 0 : _b.length) {
37765
- try {
37766
- for (var _d = __values(matchUp.tieMatchUps), _e = _d.next(); !_e.done; _e = _d.next()) {
37767
- var tieMatchUp = _e.value;
37768
- var result_1 = setMatchUpState({
37769
- matchUpId: tieMatchUp.matchUpId,
37770
- matchUpTieId: matchUpId,
37771
- winningSide: undefined,
37772
- removeScore: true,
37773
- tournamentRecord: tournamentRecord,
37774
- drawDefinition: drawDefinition,
37775
- event: event,
37776
- });
37777
- if (result_1.error)
37778
- return decorateResult({ result: result_1, stack: stack });
37779
- }
37780
- }
37781
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
37782
- finally {
37783
- try {
37784
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
37785
- }
37786
- finally { if (e_1) throw e_1.error; }
37787
- }
37788
- }
37789
- var result = updateTieMatchUpScore({
37790
- event: params.event,
37791
- removeScore: true,
37792
- tournamentRecord: tournamentRecord,
37793
- drawDefinition: drawDefinition,
37794
- matchUpsMap: matchUpsMap,
37795
- matchUpId: matchUpId,
37796
- });
37797
- if (result.error)
37798
- return decorateResult({ result: result, stack: stack });
37799
- if (params.tiebreakReset && !result.tieFormatRemoved) {
37800
- // check for scenarios where an added "Tiebreaker" collectionDefinition/matchUp has been added
37801
- var inheritedTieFormat = (_c = resolveTieFormat({
37802
- drawDefinition: drawDefinition,
37803
- structure: structure,
37804
- event: event,
37805
- })) === null || _c === void 0 ? void 0 : _c.tieFormat;
37806
- if (matchUp.tieFormat && inheritedTieFormat) {
37807
- var _f = compareTieFormats({
37808
- descendant: matchUp.tieFormat,
37809
- ancestor: inheritedTieFormat,
37810
- }), matchUpCountDifference = _f.matchUpCountDifference, descendantDifferences = _f.descendantDifferences, ancestorDifferences = _f.ancestorDifferences, valueDifference = _f.valueDifference;
37811
- if (descendantDifferences.collectionIds.length === 1 &&
37812
- !ancestorDifferences.collectionIds.length &&
37813
- !ancestorDifferences.groupsCount &&
37814
- matchUpCountDifference === 1 &&
37815
- valueDifference === 1) {
37816
- var result_2 = resetTieFormat({
37817
- tournamentRecord: tournamentRecord,
37818
- drawDefinition: drawDefinition,
37819
- matchUpId: matchUpId,
37820
- event: event,
37821
- });
37822
- if (result_2.error)
37823
- return result_2;
37824
- }
37825
- }
37826
- }
37827
- return __assign({}, SUCCESS);
37828
- }
37829
-
37830
- function removeSeeding(_a) {
37831
- var _b, _c;
37832
- var tournamentRecord = _a.tournamentRecord, drawDefinition = _a.drawDefinition, entryStatuses = _a.entryStatuses, scaleName = _a.scaleName, drawId = _a.drawId, event = _a.event, stage = _a.stage;
37833
- if (!tournamentRecord)
37834
- return { error: MISSING_TOURNAMENT_RECORD };
37835
- if (!event)
37836
- return { error: MISSING_EVENT };
37837
- scaleName =
37838
- scaleName ||
37839
- ((_b = event.category) === null || _b === void 0 ? void 0 : _b.categoryName) ||
37840
- ((_c = event.category) === null || _c === void 0 ? void 0 : _c.ageCategoryCode);
37841
- var scaleAttributes = {
37842
- eventType: event.eventType,
37843
- scaleType: SEEDING$1,
37844
- scaleName: scaleName,
37845
- };
37846
- return removeScaleValues({
37847
- tournamentRecord: tournamentRecord,
37848
- scaleAttributes: scaleAttributes,
37849
- drawDefinition: drawDefinition,
37850
- entryStatuses: entryStatuses,
37851
- drawId: drawId,
37852
- event: event,
37853
- stage: stage,
37854
- });
37855
- }
37856
-
37857
- function generateAdHocMatchUps(_a) {
37858
- var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
37859
- var participantIdPairings = _a.participantIdPairings, _p = _a.matchUpIds, matchUpIds = _p === void 0 ? [] : _p, drawDefinition = _a.drawDefinition, matchUpsCount = _a.matchUpsCount, roundNumber = _a.roundNumber, structureId = _a.structureId, newRound = _a.newRound;
37860
- if (typeof drawDefinition !== 'object')
37861
- return { error: MISSING_DRAW_DEFINITION };
37862
- if (!structureId && ((_b = drawDefinition.structures) === null || _b === void 0 ? void 0 : _b.length) === 1)
37863
- structureId = (_d = (_c = drawDefinition.structures) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.structureId;
37864
- if (typeof structureId !== 'string')
37865
- return { error: MISSING_STRUCTURE_ID };
37866
- // if drawDefinition and structureId are provided it is possible to infer roundNumber
37867
- var structure = (_e = drawDefinition.structures) === null || _e === void 0 ? void 0 : _e.find(function (structure) { return structure.structureId === structureId; });
37868
- if (!structure)
37869
- return { error: STRUCTURE_NOT_FOUND };
37870
- var structureHasRoundPositions;
37871
- var existingMatchUps = (_f = structure.matchUps) !== null && _f !== void 0 ? _f : [];
37872
- var lastRoundNumber = existingMatchUps === null || existingMatchUps === void 0 ? void 0 : existingMatchUps.reduce(function (roundNumber, matchUp) {
37873
- if (matchUp.roundPosition)
37874
- structureHasRoundPositions = true;
37875
- return ((matchUp === null || matchUp === void 0 ? void 0 : matchUp.roundNumber) || 0) > roundNumber
37876
- ? matchUp.roundNumber
37877
- : roundNumber;
37878
- }, 0);
37879
- if (!matchUpsCount) {
37880
- var selectedEntries = (_h = (_g = drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.entries) === null || _g === void 0 ? void 0 : _g.filter(function (entry) {
37881
- var entryStatus = entry.entryStatus;
37882
- return STRUCTURE_SELECTED_STATUSES.includes(entryStatus);
37883
- })) !== null && _h !== void 0 ? _h : [];
37884
- var roundMatchUpsCount = Math.floor((selectedEntries === null || selectedEntries === void 0 ? void 0 : selectedEntries.length) / 2) || 1;
37885
- if (newRound) {
37886
- matchUpsCount = roundMatchUpsCount;
37887
- }
37888
- else {
37889
- var targetRoundNumber_1 = (_j = roundNumber !== null && roundNumber !== void 0 ? roundNumber : lastRoundNumber) !== null && _j !== void 0 ? _j : 1;
37890
- var existingRoundMatchUps = (_m = (_l = (_k = structure.matchUps) === null || _k === void 0 ? void 0 : _k.filter(function (matchUp) { return matchUp.roundNumber === targetRoundNumber_1; })) === null || _l === void 0 ? void 0 : _l.length) !== null && _m !== void 0 ? _m : 0;
37891
- var maxRemaining = roundMatchUpsCount - existingRoundMatchUps;
37892
- if (maxRemaining > 0)
37893
- matchUpsCount = maxRemaining;
37894
- }
37895
- }
37896
- if ((participantIdPairings && !Array.isArray(participantIdPairings)) ||
37897
- (matchUpsCount && !isConvertableInteger(matchUpsCount)) ||
37898
- (matchUpIds && !Array.isArray(matchUpIds)) ||
37899
- (!participantIdPairings && !matchUpsCount)) {
37900
- return { error: INVALID_VALUES, info: 'matchUpsCount or pairings error' };
37901
- }
37902
- // structure must not be a container of other structures
37903
- // structure must not contain matchUps with roundPosition
37904
- // structure must not determine finishingPosition by ROUND_OUTCOME
37905
- if (structure.structures ||
37906
- structureHasRoundPositions ||
37907
- structure.finishingPosition === ROUND_OUTCOME) {
37908
- return { error: INVALID_STRUCTURE };
37909
- }
37910
- if (roundNumber && roundNumber - 1 > (lastRoundNumber || 0))
37911
- return { error: INVALID_VALUES, info: 'roundNumber error' };
37912
- var nextRoundNumber = roundNumber !== null && roundNumber !== void 0 ? roundNumber : ((newRound && (lastRoundNumber !== null && lastRoundNumber !== void 0 ? lastRoundNumber : 0) + 1) || lastRoundNumber || 1);
37913
- participantIdPairings =
37914
- participantIdPairings !== null && participantIdPairings !== void 0 ? participantIdPairings : generateRange(0, matchUpsCount).map(function () { return ({
37915
- participantIds: [undefined, undefined],
37916
- }); });
37917
- var matchUps = participantIdPairings === null || participantIdPairings === void 0 ? void 0 : participantIdPairings.map(function (pairing) {
37918
- var _a, _b;
37919
- var idStack = (_a = pairing === null || pairing === void 0 ? void 0 : pairing.participantIds) !== null && _a !== void 0 ? _a : [undefined, undefined];
37920
- // ensure there are always 2 sides in generated matchUps
37921
- idStack.push.apply(idStack, [undefined, undefined]);
37922
- var participantIds = idStack.slice(0, 2);
37923
- var sides = participantIds.map(function (participantId, i) {
37924
- return definedAttributes({
37925
- sideNumber: i + 1,
37926
- participantId: participantId,
37927
- });
37928
- });
37929
- return {
37930
- matchUpId: (_b = matchUpIds.pop()) !== null && _b !== void 0 ? _b : UUID(),
37931
- roundNumber: nextRoundNumber,
37932
- matchUpStatus: TO_BE_PLAYED,
37933
- sides: sides,
37934
- };
37935
- });
37936
- return __assign({ matchUpsCount: (_o = matchUps === null || matchUps === void 0 ? void 0 : matchUps.length) !== null && _o !== void 0 ? _o : 0, matchUps: matchUps }, SUCCESS);
37937
- }
37938
-
37939
- function generateCandidate(_a) {
37940
- var _b = _a.maxIterations, maxIterations = _b === void 0 ? 4000 : _b, // cap the processing intensity of the candidate generator
37941
- valueSortedPairings = _a.valueSortedPairings, // pairings sorted by value from low to high
37942
- pairingValues = _a.pairingValues, valueObjects = _a.valueObjects, deltaObjects = _a.deltaObjects;
37943
- var pairingValueMap = Object.assign.apply(Object, __spreadArray([{}], __read(valueSortedPairings.map(function (rm) {
37944
- var _a;
37945
- return (_a = {}, _a[rm.pairing] = rm.value, _a);
37946
- })), false));
37947
- var actors = Object.keys(pairingValues);
37948
- var proposedCandidates = [];
37949
- // generate an initial candidate value with no stipulated pairings
37950
- var initialProposal = roundCandidate({
37951
- actorsCount: actors.length,
37952
- valueSortedPairings: valueSortedPairings,
37953
- pairingValueMap: pairingValueMap,
37954
- deltaObjects: deltaObjects,
37955
- valueObjects: valueObjects,
37956
- });
37957
- var candidateHashes = [candidateHash(initialProposal)];
37958
- proposedCandidates.push(initialProposal);
37959
- var lowCandidateValue = initialProposal.value;
37960
- var deltaCandidate = initialProposal;
37961
- // iterations is the number of loops over valueSortedPairings
37962
- var candidatesCount = 0;
37963
- var iterations = 0;
37964
- var opponentCount = actors.length;
37965
- var calculatedIterations;
37966
- // calculate the number of opponents to consider for each participantId
37967
- do {
37968
- opponentCount -= 1;
37969
- calculatedIterations = actors.length * pairingValues[actors[0]].length;
37970
- } while (calculatedIterations > maxIterations && opponentCount > 5);
37971
- // keep track of proposed pairings
37972
- var stipulatedPairs = [];
37973
- // for each actor generate a roundCandidate using opponentCount of pairing values
37974
- actors.forEach(function (actor) {
37975
- var participantIdPairings = pairingValues[actor];
37976
- // opponentCount limits the number of opponents to consider
37977
- participantIdPairings.slice(0, opponentCount).forEach(function (pairing) {
37978
- iterations += 1;
37979
- var stipulatedPair = pairingHash(actor, pairing.opponent);
37980
- if (!stipulatedPairs.includes(stipulatedPair)) {
37981
- var proposed = roundCandidate({
37982
- // each roundCandidate starts with stipulated pairings
37983
- stipulated: [[actor, pairing.opponent]],
37984
- actorsCount: actors.length,
37985
- valueSortedPairings: valueSortedPairings,
37986
- pairingValueMap: pairingValueMap,
37987
- deltaObjects: deltaObjects,
37988
- valueObjects: valueObjects,
37989
- });
37990
- // ensure no duplicate candidates are considered
37991
- if (!candidateHashes.includes(candidateHash(proposed))) {
37992
- candidateHashes.push(candidateHash(proposed));
37993
- proposedCandidates.push(proposed);
37994
- var maxDelta = proposed.maxDelta, value = proposed.value;
37995
- if (maxDelta < deltaCandidate.maxDelta)
37996
- deltaCandidate = proposed;
37997
- if (value < lowCandidateValue ||
37998
- (value === lowCandidateValue && Math.round(Math.random())) // randomize if equivalent values
37999
- ) {
38000
- lowCandidateValue = value;
38001
- }
38002
- stipulatedPairs.push(stipulatedPair);
38003
- candidatesCount += 1;
38004
- }
38005
- }
38006
- });
38007
- proposedCandidates = proposedCandidates.filter(function (proposed) { return Math.abs(proposed.value - lowCandidateValue) < 5; });
38008
- });
38009
- proposedCandidates.sort(function (a, b) { return a.maxDiff - b.maxDiff; });
38010
- var candidate = randomPop(proposedCandidates);
38011
- return {
38012
- candidatesCount: candidatesCount,
38013
- deltaCandidate: deltaCandidate,
38014
- maxIterations: maxIterations,
38015
- iterations: iterations,
38016
- candidate: candidate,
38017
- };
38018
- }
38019
- function candidateHash(candidate) {
38020
- return candidate.participantIdPairings
38021
- .map(function (_a) {
38022
- var participantIds = _a.participantIds;
38023
- return participantIds.sort().join('|');
38024
- })
38025
- .sort()
38026
- .join('/');
38027
- }
38028
- function roundCandidate(_a) {
38029
- var valueSortedPairings = _a.valueSortedPairings, _b = _a.stipulated, stipulated = _b === void 0 ? [] : _b, pairingValueMap = _a.pairingValueMap, deltaObjects = _a.deltaObjects, valueObjects = _a.valueObjects, actorsCount = _a.actorsCount;
38030
- // roundPlayers starts with the stipulated pairing
38031
- var roundPlayers = [].concat.apply([], __spreadArray([], __read(stipulated), false));
38032
- // aggregates the pairings generated for a roundCandidate
38033
- var participantIdPairings = [];
38034
- // candidateValue is the sum of all participantIdPairings in a roundCandidate
38035
- // the winning candidate has the LOWEST total value
38036
- var candidateValue = 0;
38037
- // candidateValue is initialized with any stipulated pairings
38038
- stipulated.filter(Boolean).forEach(function (participantIds) {
38039
- var _a = __read(participantIds, 2), p1 = _a[0], p2 = _a[1];
38040
- var pairing = pairingHash(p1, p2);
38041
- var value = pairingValueMap[pairing];
38042
- participantIdPairings.push({ participantIds: participantIds, value: value });
38043
- candidateValue += pairingValueMap[pairing];
38044
- });
38045
- // valueSortedPairings is an array sorted from lowest value to highest value
38046
- // introduce random shuffling of chunks of valueSortedPairings
38047
- var consideredPairings = chunkArray(valueSortedPairings, actorsCount)
38048
- .map(function (pairings) {
38049
- return shuffleArray(pairings).map(function (pairing) { return (__assign(__assign({}, pairing), { value: pairing.value + Math.random() * Math.round(Math.random()) })); });
38050
- })
38051
- .flat();
38052
- // go through the valueSortedPairings (of all possible unique pairings)
38053
- consideredPairings.forEach(function (rankedPairing) {
38054
- var participantIds = rankedPairing.pairing.split('|');
38055
- var opponentExists = participantIds.reduce(function (p, c) { return roundPlayers.includes(c) || p; }, false);
38056
- if (!opponentExists) {
38057
- roundPlayers.push.apply(roundPlayers, __spreadArray([], __read(participantIds), false));
38058
- var value = rankedPairing.value;
38059
- candidateValue += value;
38060
- participantIdPairings.push({ participantIds: participantIds, value: value });
38061
- }
38062
- });
38063
- // sort the candidate's proposed pairings by value
38064
- participantIdPairings.sort(function (a, b) { return a.value - b.value; });
38065
- // determine the greatest delta in the candidate's pairings
38066
- var maxDelta = participantIdPairings.reduce(function (p, c) {
38067
- var _a = __read(c.participantIds, 2), p1 = _a[0], p2 = _a[1];
38068
- var hash = pairingHash(p1, p2);
38069
- var delta = deltaObjects[hash];
38070
- return delta > p ? delta : p;
38071
- }, 0);
38072
- // determine the greatest delta in the candidate's pairings
38073
- var maxDiff = participantIdPairings.reduce(function (p, c) {
38074
- var _a = __read(c.participantIds, 2), p1 = _a[0], p2 = _a[1];
38075
- var hash = pairingHash(p1, p2);
38076
- var diff = valueObjects[hash];
38077
- return diff > p ? diff : p;
38078
- }, 0);
38079
- return { value: candidateValue, participantIdPairings: participantIdPairings, maxDelta: maxDelta, maxDiff: maxDiff };
38080
- }
38081
- function pairingHash(id1, id2) {
38082
- return [id1, id2].sort(stringSort).join('|');
37447
+ // sort the candidate's proposed pairings by value
37448
+ participantIdPairings.sort(function (a, b) { return a.value - b.value; });
37449
+ // determine the greatest delta in the candidate's pairings
37450
+ var maxDelta = participantIdPairings.reduce(function (p, c) {
37451
+ var _a = __read(c.participantIds, 2), p1 = _a[0], p2 = _a[1];
37452
+ var hash = pairingHash(p1, p2);
37453
+ var delta = deltaObjects[hash];
37454
+ return delta > p ? delta : p;
37455
+ }, 0);
37456
+ // determine the greatest delta in the candidate's pairings
37457
+ var maxDiff = participantIdPairings.reduce(function (p, c) {
37458
+ var _a = __read(c.participantIds, 2), p1 = _a[0], p2 = _a[1];
37459
+ var hash = pairingHash(p1, p2);
37460
+ var diff = valueObjects[hash];
37461
+ return diff > p ? diff : p;
37462
+ }, 0);
37463
+ return { value: candidateValue, participantIdPairings: participantIdPairings, maxDelta: maxDelta, maxDiff: maxDiff };
37464
+ }
37465
+ function pairingHash(id1, id2) {
37466
+ return [id1, id2].sort(stringSort).join('|');
38083
37467
  }
38084
37468
 
38085
37469
  function getPairingsData(_a) {
@@ -38292,7 +37676,7 @@ var MAX_ITERATIONS = 4000;
38292
37676
  function generateDrawMaticRound(_a) {
38293
37677
  var e_1, _b, e_2, _c, e_3, _d;
38294
37678
  var _e, _f;
38295
- var _g = _a.encounterValue, encounterValue = _g === void 0 ? ENCOUNTER_VALUE : _g, _h = _a.sameTeamValue, sameTeamValue = _h === void 0 ? SAME_TEAM_VALUE : _h, _j = _a.maxIterations, maxIterations = _j === void 0 ? MAX_ITERATIONS : _j, _k = _a.generateMatchUps, generateMatchUps = _k === void 0 ? true : _k, tournamentParticipants = _a.tournamentParticipants, participantIds = _a.participantIds, drawDefinition = _a.drawDefinition, adHocRatings = _a.adHocRatings, structureId = _a.structureId, _l = _a.salted, salted = _l === void 0 ? 0.5 : _l, matchUpIds = _a.matchUpIds, eventType = _a.eventType, structure = _a.structure, scaleName = _a.scaleName;
37679
+ var _g = _a.encounterValue, encounterValue = _g === void 0 ? ENCOUNTER_VALUE : _g, _h = _a.sameTeamValue, sameTeamValue = _h === void 0 ? SAME_TEAM_VALUE : _h, _j = _a.maxIterations, maxIterations = _j === void 0 ? MAX_ITERATIONS : _j, _k = _a.generateMatchUps, generateMatchUps = _k === void 0 ? true : _k, tournamentParticipants = _a.tournamentParticipants, participantIds = _a.participantIds, drawDefinition = _a.drawDefinition, adHocRatings = _a.adHocRatings, structureId = _a.structureId, _l = _a.salted, salted = _l === void 0 ? 0.5 : _l, matchUpIds = _a.matchUpIds, eventType = _a.eventType, structure = _a.structure, scaleName = _a.scaleName, isMock = _a.isMock, event = _a.event;
38296
37680
  if (!drawDefinition)
38297
37681
  return { error: MISSING_DRAW_DEFINITION };
38298
37682
  if (!structure && !structureId)
@@ -38400,6 +37784,8 @@ function generateDrawMaticRound(_a) {
38400
37784
  newRound: true,
38401
37785
  drawDefinition: drawDefinition,
38402
37786
  matchUpIds: matchUpIds,
37787
+ isMock: isMock,
37788
+ event: event,
38403
37789
  });
38404
37790
  if (result.error)
38405
37791
  return result;
@@ -38409,11 +37795,11 @@ function generateDrawMaticRound(_a) {
38409
37795
  return __assign(__assign({}, SUCCESS), { participantIdPairings: participantIdPairings, candidatesCount: candidatesCount, iterations: iterations, matchUps: matchUps, maxDelta: maxDelta, maxDiff: maxDiff });
38410
37796
  }
38411
37797
 
38412
- function drawMatic$1(_a) {
37798
+ function drawMatic(_a) {
38413
37799
  var e_1, _b;
38414
37800
  var _c, _d, _e, _f, _g;
38415
- var tournamentParticipants = _a.tournamentParticipants, restrictEntryStatus = _a.restrictEntryStatus, _h = _a.adHocRatings, adHocRatings = _h === void 0 ? {} : _h, generateMatchUps = _a.generateMatchUps, tournamentRecord = _a.tournamentRecord, participantIds = _a.participantIds, encounterValue = _a.encounterValue, sameTeamValue = _a.sameTeamValue, drawDefinition = _a.drawDefinition, scaleAccessor = _a.scaleAccessor, maxIterations = _a.maxIterations, structureId = _a.structureId, matchUpIds = _a.matchUpIds, scaleName = _a.scaleName, // custom rating name to seed dynamic ratings
38416
- eventType = _a.eventType, salted = _a.salted, event = _a.event;
37801
+ var restrictEntryStatus = _a.restrictEntryStatus, _h = _a.adHocRatings, adHocRatings = _h === void 0 ? {} : _h, generateMatchUps = _a.generateMatchUps, tournamentRecord = _a.tournamentRecord, participantIds = _a.participantIds, encounterValue = _a.encounterValue, sameTeamValue = _a.sameTeamValue, drawDefinition = _a.drawDefinition, scaleAccessor = _a.scaleAccessor, maxIterations = _a.maxIterations, structureId = _a.structureId, matchUpIds = _a.matchUpIds, scaleName = _a.scaleName, // custom rating name to seed dynamic ratings
37802
+ eventType = _a.eventType, isMock = _a.isMock, salted = _a.salted, event = _a.event;
38417
37803
  if (typeof drawDefinition !== 'object' ||
38418
37804
  (drawDefinition.drawType && drawDefinition.drawType !== AD_HOC)) {
38419
37805
  return { error: INVALID_DRAW_DEFINITION };
@@ -38441,102 +37827,729 @@ function drawMatic$1(_a) {
38441
37827
  else {
38442
37828
  participantIds = enteredParticipantIds;
38443
37829
  }
38444
- // if no structureId is specified find the latest AD_HOC stage which has matchUps
38445
- if (!structureId) {
38446
- var targetStructure = (_e = (_d = drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.structures) === null || _d === void 0 ? void 0 : _d.filter(function (structure) { return structure.stageSequence === 1; })) === null || _e === void 0 ? void 0 : _e.reduce(function (targetStructure, structure) {
38447
- var orderNumber = structure.stage && stageOrder$1[structure.stage];
38448
- var structureIsAdHoc = isAdHoc({ drawDefinition: drawDefinition, structure: structure });
38449
- return structureIsAdHoc &&
38450
- orderNumber > (stageOrder$1[targetStructure === null || targetStructure === void 0 ? void 0 : targetStructure.stage] || 1)
38451
- ? structure
38452
- : targetStructure;
38453
- }, undefined);
38454
- structureId = targetStructure === null || targetStructure === void 0 ? void 0 : targetStructure.structureId;
37830
+ // if no structureId is specified find the latest AD_HOC stage which has matchUps
37831
+ if (!structureId) {
37832
+ var targetStructure = (_e = (_d = drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.structures) === null || _d === void 0 ? void 0 : _d.filter(function (structure) { return structure.stageSequence === 1; })) === null || _e === void 0 ? void 0 : _e.reduce(function (targetStructure, structure) {
37833
+ var orderNumber = structure.stage && stageOrder$1[structure.stage];
37834
+ var structureIsAdHoc = isAdHoc({ drawDefinition: drawDefinition, structure: structure });
37835
+ return structureIsAdHoc &&
37836
+ orderNumber > (stageOrder$1[targetStructure === null || targetStructure === void 0 ? void 0 : targetStructure.stage] || 1)
37837
+ ? structure
37838
+ : targetStructure;
37839
+ }, undefined);
37840
+ structureId = targetStructure === null || targetStructure === void 0 ? void 0 : targetStructure.structureId;
37841
+ }
37842
+ var structure = (_f = drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.structures) === null || _f === void 0 ? void 0 : _f.find(function (structure) { return structure.structureId === structureId; });
37843
+ if (!structure)
37844
+ return { error: STRUCTURE_NOT_FOUND };
37845
+ // an AD_HOC structure is one that has no child structures and in which no matchUps have roundPosition
37846
+ var structureIsAdHoc = isAdHoc({ drawDefinition: drawDefinition, structure: structure });
37847
+ if (!structureIsAdHoc)
37848
+ return { error: INVALID_DRAW_DEFINITION };
37849
+ var tournamentParticipants = (_g = tournamentRecord.participants) !== null && _g !== void 0 ? _g : [];
37850
+ var _loop_1 = function (participantId) {
37851
+ var participant = tournamentParticipants === null || tournamentParticipants === void 0 ? void 0 : tournamentParticipants.find(function (participant) { return participant.participantId === participantId; });
37852
+ // first see if there is already a dynamic value
37853
+ var scaleValue = getScaleValue({
37854
+ scaleName: "".concat(scaleName, ".").concat(DYNAMIC),
37855
+ scaleAccessor: scaleAccessor,
37856
+ participant: participant,
37857
+ eventType: eventType,
37858
+ });
37859
+ // if no dynamic value found and a seeding scaleValue is provided...
37860
+ if (!scaleValue && scaleName) {
37861
+ scaleValue = getScaleValue({
37862
+ scaleAccessor: scaleAccessor,
37863
+ participant: participant,
37864
+ scaleName: scaleName,
37865
+ eventType: eventType,
37866
+ });
37867
+ }
37868
+ if (scaleValue && !adHocRatings[participantId])
37869
+ adHocRatings[participantId] = scaleValue;
37870
+ };
37871
+ try {
37872
+ for (var _j = __values(participantIds !== null && participantIds !== void 0 ? participantIds : []), _k = _j.next(); !_k.done; _k = _j.next()) {
37873
+ var participantId = _k.value;
37874
+ _loop_1(participantId);
37875
+ }
37876
+ }
37877
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
37878
+ finally {
37879
+ try {
37880
+ if (_k && !_k.done && (_b = _j.return)) _b.call(_j);
37881
+ }
37882
+ finally { if (e_1) throw e_1.error; }
37883
+ }
37884
+ // TODO: update dynamic ratings based on matchUps present from last played round
37885
+ // use scaleEngine.generateDynamicRatings(); see dynamicCalculations.test.ts
37886
+ return generateDrawMaticRound({
37887
+ tournamentParticipants: tournamentParticipants,
37888
+ generateMatchUps: generateMatchUps,
37889
+ participantIds: participantIds,
37890
+ encounterValue: encounterValue,
37891
+ sameTeamValue: sameTeamValue,
37892
+ drawDefinition: drawDefinition,
37893
+ maxIterations: maxIterations,
37894
+ adHocRatings: adHocRatings,
37895
+ matchUpIds: matchUpIds,
37896
+ structure: structure,
37897
+ eventType: eventType,
37898
+ salted: salted,
37899
+ isMock: isMock,
37900
+ event: event,
37901
+ });
37902
+ }
37903
+ function getScaleValue(_a) {
37904
+ var _b;
37905
+ var _c = _a.scaleType, scaleType = _c === void 0 ? RATING$2 : _c, scaleAccessor = _a.scaleAccessor, participant = _a.participant, scaleName = _a.scaleName, eventType = _a.eventType;
37906
+ var scaleAttributes = {
37907
+ eventType: eventType !== null && eventType !== void 0 ? eventType : SINGLES_EVENT,
37908
+ scaleType: scaleType,
37909
+ scaleName: scaleName,
37910
+ };
37911
+ var result = participant &&
37912
+ participantScaleItem({
37913
+ scaleAttributes: scaleAttributes,
37914
+ participant: participant,
37915
+ });
37916
+ var scaleValue = (_b = result === null || result === void 0 ? void 0 : result.scaleItem) === null || _b === void 0 ? void 0 : _b.scaleValue;
37917
+ return scaleAccessor && isObject(scaleValue)
37918
+ ? scaleValue[scaleAccessor]
37919
+ : scaleValue;
37920
+ }
37921
+
37922
+ function addAdHocMatchUps(_a) {
37923
+ var _b;
37924
+ var _c, _d, _e, _f, _g, _h, _j;
37925
+ var tournamentRecord = _a.tournamentRecord, drawDefinition = _a.drawDefinition, structureId = _a.structureId, matchUps = _a.matchUps;
37926
+ if (typeof drawDefinition !== 'object')
37927
+ return { error: MISSING_DRAW_DEFINITION };
37928
+ if (!structureId && ((_c = drawDefinition.structures) === null || _c === void 0 ? void 0 : _c.length) === 1)
37929
+ structureId = (_e = (_d = drawDefinition.structures) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.structureId;
37930
+ if (typeof structureId !== 'string')
37931
+ return { error: MISSING_STRUCTURE_ID };
37932
+ if (!validMatchUps(matchUps))
37933
+ return { error: INVALID_VALUES, info: mustBeAnArray('matchUps') };
37934
+ var structure = (_f = drawDefinition.structures) === null || _f === void 0 ? void 0 : _f.find(function (structure) { return structure.structureId === structureId; });
37935
+ if (!structure)
37936
+ return { error: STRUCTURE_NOT_FOUND };
37937
+ var existingMatchUps = structure === null || structure === void 0 ? void 0 : structure.matchUps;
37938
+ var structureHasRoundPositions = existingMatchUps.find(function (matchUp) { return !!matchUp.roundPosition; });
37939
+ if (structure.structures ||
37940
+ structureHasRoundPositions ||
37941
+ structure.finishingPosition === ROUND_OUTCOME) {
37942
+ return { error: INVALID_STRUCTURE };
37943
+ }
37944
+ var existingMatchUpIds = (_j = (_h = (_g = allTournamentMatchUps({
37945
+ tournamentRecord: tournamentRecord,
37946
+ inContext: false,
37947
+ })) === null || _g === void 0 ? void 0 : _g.matchUps) === null || _h === void 0 ? void 0 : _h.map(getMatchUpId)) !== null && _j !== void 0 ? _j : [];
37948
+ var newMatchUpIds = matchUps.map(getMatchUpId);
37949
+ if (overlap(existingMatchUpIds, newMatchUpIds)) {
37950
+ return {
37951
+ error: EXISTING_MATCHUP_ID,
37952
+ info: 'One or more matchUpIds already present in tournamentRecord',
37953
+ };
37954
+ }
37955
+ (_b = structure.matchUps).push.apply(_b, __spreadArray([], __read(matchUps), false));
37956
+ addMatchUpsNotice({
37957
+ tournamentId: tournamentRecord === null || tournamentRecord === void 0 ? void 0 : tournamentRecord.tournamentId,
37958
+ drawDefinition: drawDefinition,
37959
+ matchUps: matchUps,
37960
+ });
37961
+ modifyDrawNotice({ drawDefinition: drawDefinition, structureIds: [structureId] });
37962
+ return __assign({}, SUCCESS);
37963
+ }
37964
+
37965
+ function attachFlightProfile(_a) {
37966
+ var _b;
37967
+ var deleteExisting = _a.deleteExisting, event = _a.event, flightProfile = _a.flightProfile;
37968
+ var stack = 'attachFlightProfile';
37969
+ if (!flightProfile)
37970
+ return decorateResult({ result: { error: MISSING_VALUE }, stack: stack });
37971
+ if (!event)
37972
+ return decorateResult({ result: { error: MISSING_EVENT }, stack: stack });
37973
+ var existingFlightProfile = getFlightProfile({ event: event }).flightProfile;
37974
+ if (existingFlightProfile && !deleteExisting)
37975
+ return decorateResult({ result: { error: EXISTING_PROFILE }, stack: stack });
37976
+ if ((_b = event.drawDefinitions) === null || _b === void 0 ? void 0 : _b.length)
37977
+ return decorateResult({
37978
+ result: { error: EXISTING_DRAW_DEFINITIONS },
37979
+ stack: stack,
37980
+ });
37981
+ var extension = {
37982
+ name: FLIGHT_PROFILE,
37983
+ value: flightProfile,
37984
+ };
37985
+ addEventExtension({ event: event, extension: extension });
37986
+ return __assign({ flightProfile: makeDeepCopy(flightProfile, false, true) }, SUCCESS);
37987
+ }
37988
+
37989
+ /**
37990
+ *
37991
+ * @param {object} tournamentRecord - passed automatically if tournamentEngine.setState()
37992
+ * @param {string[]} participantIds
37993
+ * @param {string} scaleAttributes - { scaleType, scaleName, eventType }
37994
+ * @returns {boolean} { success: true } or { error }
37995
+ */
37996
+ function removeParticipantsScaleItems(_a) {
37997
+ var _b;
37998
+ var tournamentRecord = _a.tournamentRecord, scaleAttributes = _a.scaleAttributes, participantIds = _a.participantIds;
37999
+ if (!tournamentRecord)
38000
+ return { error: MISSING_TOURNAMENT_RECORD };
38001
+ if (!participantIds)
38002
+ return { error: MISSING_PARTICIPANT_IDS };
38003
+ if (!scaleAttributes)
38004
+ return { error: MISSING_VALUE, info: 'scaleAttributes required' };
38005
+ var scaleType = scaleAttributes.scaleType, eventType = scaleAttributes.eventType, scaleName = scaleAttributes.scaleName;
38006
+ var itemType = [SCALE, scaleType, eventType, scaleName].join('.');
38007
+ (_b = tournamentRecord.participants) === null || _b === void 0 ? void 0 : _b.forEach(function (participant) {
38008
+ if (participantIds.includes(participant.participantId) &&
38009
+ participant.timeItems) {
38010
+ participant.timeItems = participant.timeItems.filter(function (timeItem) {
38011
+ return timeItem && (timeItem === null || timeItem === void 0 ? void 0 : timeItem.itemType) !== itemType;
38012
+ });
38013
+ }
38014
+ });
38015
+ return __assign({}, SUCCESS);
38016
+ }
38017
+
38018
+ /**
38019
+ *
38020
+ * @param {object} tournamentRecord - passed automatically if tournamentEngine.setState()
38021
+ * @param {string} eventId - resolves to event
38022
+ * @param {string} drawId - OPTIONAL - resolves drawDefinition - scopes participants to clear to drawDefinition.entries or flightProfile.flight.drawEntries
38023
+ * @param {string} scaleAttributes - { scaleType, scaleName, eventType }
38024
+ * @param {string} stage - OPTIONAL - filter event or draw entries by stage
38025
+ * @returns {boolean} { success: true } or { error }
38026
+ */
38027
+ function removeScaleValues(_a) {
38028
+ var _b;
38029
+ var tournamentRecord = _a.tournamentRecord, scaleAttributes = _a.scaleAttributes, drawDefinition = _a.drawDefinition, entryStatuses = _a.entryStatuses, drawId = _a.drawId, event = _a.event, stage = _a.stage;
38030
+ if (!event)
38031
+ return { error: MISSING_EVENT };
38032
+ if (entryStatuses && !Array.isArray(entryStatuses))
38033
+ return decorateResult({
38034
+ result: { error: INVALID_VALUES },
38035
+ info: mustBeAnArray('entryStatus'),
38036
+ stack: 'removeScaleValues',
38037
+ });
38038
+ var entries = event.entries;
38039
+ if (drawId) {
38040
+ var flightProfile = getFlightProfile({ event: event }).flightProfile;
38041
+ var flight = (_b = flightProfile === null || flightProfile === void 0 ? void 0 : flightProfile.flights) === null || _b === void 0 ? void 0 : _b.find(function (flight) { return flight.drawId === drawId; });
38042
+ if (flight) {
38043
+ entries = flight.drawEntries;
38044
+ }
38045
+ else {
38046
+ entries = drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.entries;
38047
+ }
38048
+ }
38049
+ var stageEntries = (entries || []).filter(function (entry) {
38050
+ return (!stage || !entry.entryStage || entry.entryStage === stage) &&
38051
+ (!entryStatuses || entryStatuses.includes(entry.entryStatus));
38052
+ });
38053
+ var participantIds = stageEntries.map(getParticipantId);
38054
+ return removeParticipantsScaleItems({
38055
+ tournamentRecord: tournamentRecord,
38056
+ scaleAttributes: scaleAttributes,
38057
+ participantIds: participantIds,
38058
+ });
38059
+ }
38060
+
38061
+ function applyLineUps(_a) {
38062
+ var e_1, _b, e_2, _c, e_3, _d, e_4, _e;
38063
+ var _f, _g, _h, _j;
38064
+ var tournamentRecord = _a.tournamentRecord, drawDefinition = _a.drawDefinition, matchUpId = _a.matchUpId, lineUps = _a.lineUps, event = _a.event;
38065
+ if (!tournamentRecord)
38066
+ return { error: MISSING_TOURNAMENT_RECORD };
38067
+ if (!drawDefinition)
38068
+ return { error: DRAW_DEFINITION_NOT_FOUND };
38069
+ if (typeof matchUpId !== 'string')
38070
+ return { error: INVALID_MATCHUP };
38071
+ if (!Array.isArray(lineUps))
38072
+ return { error: INVALID_VALUES, lineUps: lineUps };
38073
+ var stack = 'applyLineUps';
38074
+ var tournamentParticipants = tournamentRecord.participants || [];
38075
+ var result = findDrawMatchUp({
38076
+ tournamentParticipants: tournamentParticipants,
38077
+ inContext: true,
38078
+ drawDefinition: drawDefinition,
38079
+ matchUpId: matchUpId,
38080
+ });
38081
+ if (result.error)
38082
+ return result;
38083
+ if (!result.matchUp)
38084
+ return { error: MATCHUP_NOT_FOUND };
38085
+ var inContextMatchUp = result.matchUp, structure = result.structure;
38086
+ var drawPositions = inContextMatchUp.drawPositions, matchUpType = inContextMatchUp.matchUpType;
38087
+ if (matchUpType !== TEAM$1)
38088
+ return { error: INVALID_MATCHUP };
38089
+ if (!(drawPositions === null || drawPositions === void 0 ? void 0 : drawPositions.length))
38090
+ return { error: MISSING_DRAW_POSITIONS };
38091
+ var tieFormat = (_f = resolveTieFormat({
38092
+ matchUp: inContextMatchUp,
38093
+ drawDefinition: drawDefinition,
38094
+ structure: structure,
38095
+ event: event,
38096
+ })) === null || _f === void 0 ? void 0 : _f.tieFormat;
38097
+ // verify integrity of lineUps...
38098
+ // 1. all participantIds must be valid individualParticipantIds
38099
+ // 2. there should be at most one participantId for a given collectionPosition in singles
38100
+ // 3. there should be at most two participantIds for a given collectionPosition in doubles
38101
+ var sideAssignments = {};
38102
+ try {
38103
+ for (var lineUps_1 = __values(lineUps), lineUps_1_1 = lineUps_1.next(); !lineUps_1_1.done; lineUps_1_1 = lineUps_1.next()) {
38104
+ var lineUp = lineUps_1_1.value;
38105
+ if (!Array.isArray(lineUp))
38106
+ return { error: INVALID_VALUES, lineUp: lineUp };
38107
+ // maintain mapping of collectionId|collectionPosition to the participantIds assigned
38108
+ var collectionParticipantIds = {};
38109
+ var sideNumbers = [];
38110
+ var _loop_1 = function (lineUpAssignment) {
38111
+ var e_5, _m;
38112
+ if (typeof lineUpAssignment !== 'object')
38113
+ return { value: { error: INVALID_VALUES, lineUpAssignment: lineUpAssignment } };
38114
+ var participantId = lineUpAssignment.participantId, _o = lineUpAssignment.collectionAssignments, collectionAssignments = _o === void 0 ? [] : _o;
38115
+ if (!Array.isArray(collectionAssignments))
38116
+ return { value: { error: INVALID_VALUES, collectionAssignments: collectionAssignments } };
38117
+ var participant = tournamentParticipants.find(function (participant) { return participant.participantId === participantId; });
38118
+ if (!participant)
38119
+ return { value: { error: PARTICIPANT_NOT_FOUND } };
38120
+ if (participant.participantType !== INDIVIDUAL)
38121
+ return { value: { error: INVALID_PARTICIPANT_TYPE } };
38122
+ var sideNumber_1 = (_h = (_g = inContextMatchUp.sides) === null || _g === void 0 ? void 0 : _g.find(function (side) { var _a, _b; return (_b = (_a = side.participant) === null || _a === void 0 ? void 0 : _a.individualParticipantIds) === null || _b === void 0 ? void 0 : _b.includes(participantId); })) === null || _h === void 0 ? void 0 : _h.sideNumber;
38123
+ if (sideNumber_1)
38124
+ sideNumbers.push(sideNumber_1);
38125
+ var _loop_3 = function (collectionAssignment) {
38126
+ if (typeof collectionAssignment !== 'object')
38127
+ return { value: { error: INVALID_VALUES, collectionAssignment: collectionAssignment } };
38128
+ var collectionId = collectionAssignment.collectionId, collectionPosition = collectionAssignment.collectionPosition;
38129
+ var collectionDefinition = (_j = tieFormat === null || tieFormat === void 0 ? void 0 : tieFormat.collectionDefinitions) === null || _j === void 0 ? void 0 : _j.find(function (collectionDefinition) {
38130
+ return collectionDefinition.collectionId === collectionId;
38131
+ });
38132
+ // all collectionIds in the lineUp must be present in the tieFormat collectionDefinitions
38133
+ if (!collectionDefinition)
38134
+ return { value: { error: INVALID_VALUES, collectionId: collectionId } };
38135
+ var aggregator = "".concat(collectionId, "-").concat(collectionPosition);
38136
+ if (!collectionParticipantIds[aggregator]) {
38137
+ collectionParticipantIds[aggregator] = [];
38138
+ }
38139
+ var participantsCount = collectionParticipantIds[aggregator].length;
38140
+ if ((collectionDefinition.matchUpType === SINGLES && participantsCount) ||
38141
+ (collectionDefinition.matchUpType === DOUBLES &&
38142
+ participantsCount > 1)) {
38143
+ return { value: {
38144
+ info: 'Excessive collectionPosition assignments',
38145
+ error: INVALID_VALUES,
38146
+ } };
38147
+ }
38148
+ collectionParticipantIds[aggregator].push(participantId);
38149
+ };
38150
+ try {
38151
+ for (var collectionAssignments_1 = (e_5 = void 0, __values(collectionAssignments)), collectionAssignments_1_1 = collectionAssignments_1.next(); !collectionAssignments_1_1.done; collectionAssignments_1_1 = collectionAssignments_1.next()) {
38152
+ var collectionAssignment = collectionAssignments_1_1.value;
38153
+ var state_2 = _loop_3(collectionAssignment);
38154
+ if (typeof state_2 === "object")
38155
+ return state_2;
38156
+ }
38157
+ }
38158
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
38159
+ finally {
38160
+ try {
38161
+ if (collectionAssignments_1_1 && !collectionAssignments_1_1.done && (_m = collectionAssignments_1.return)) _m.call(collectionAssignments_1);
38162
+ }
38163
+ finally { if (e_5) throw e_5.error; }
38164
+ }
38165
+ };
38166
+ try {
38167
+ for (var lineUp_1 = (e_2 = void 0, __values(lineUp)), lineUp_1_1 = lineUp_1.next(); !lineUp_1_1.done; lineUp_1_1 = lineUp_1.next()) {
38168
+ var lineUpAssignment = lineUp_1_1.value;
38169
+ var state_1 = _loop_1(lineUpAssignment);
38170
+ if (typeof state_1 === "object")
38171
+ return state_1.value;
38172
+ }
38173
+ }
38174
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
38175
+ finally {
38176
+ try {
38177
+ if (lineUp_1_1 && !lineUp_1_1.done && (_c = lineUp_1.return)) _c.call(lineUp_1);
38178
+ }
38179
+ finally { if (e_2) throw e_2.error; }
38180
+ }
38181
+ // ensure that doubles pair participants exist, otherwise create
38182
+ var collectionParticipantIdPairs = Object.values(collectionParticipantIds);
38183
+ try {
38184
+ for (var collectionParticipantIdPairs_1 = (e_3 = void 0, __values(collectionParticipantIdPairs)), collectionParticipantIdPairs_1_1 = collectionParticipantIdPairs_1.next(); !collectionParticipantIdPairs_1_1.done; collectionParticipantIdPairs_1_1 = collectionParticipantIdPairs_1.next()) {
38185
+ var participantIds = collectionParticipantIdPairs_1_1.value;
38186
+ if (participantIds.length === 2) {
38187
+ var pairedParticipant = getPairedParticipant({
38188
+ tournamentParticipants: tournamentParticipants,
38189
+ participantIds: participantIds,
38190
+ }).participant;
38191
+ if (!pairedParticipant) {
38192
+ // create pair participant
38193
+ var newPairParticipant = {
38194
+ participantType: PAIR,
38195
+ participantRole: COMPETITOR,
38196
+ individualParticipantIds: participantIds,
38197
+ };
38198
+ var result_1 = addParticipant({
38199
+ participant: newPairParticipant,
38200
+ pairOverride: true,
38201
+ tournamentRecord: tournamentRecord,
38202
+ });
38203
+ if (result_1.error)
38204
+ return result_1;
38205
+ }
38206
+ }
38207
+ }
38208
+ }
38209
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
38210
+ finally {
38211
+ try {
38212
+ if (collectionParticipantIdPairs_1_1 && !collectionParticipantIdPairs_1_1.done && (_d = collectionParticipantIdPairs_1.return)) _d.call(collectionParticipantIdPairs_1);
38213
+ }
38214
+ finally { if (e_3) throw e_3.error; }
38215
+ }
38216
+ // determine sideNumber based on instances of participants appearing in team participants assigned to sides
38217
+ // allows for some team members to be "borrowed"
38218
+ var instances = instanceCount(sideNumbers);
38219
+ var sideNumber = ((instances[1] || 0) > (instances[2] || 0) && 1) ||
38220
+ ((instances[2] || 0) > (instances[1] || 0) && 2) ||
38221
+ undefined;
38222
+ // if side not previously assigned, map sideNumber to lineUp
38223
+ var sideAssignmentKeys = Object.keys(sideAssignments).map(function (key) {
38224
+ return parseInt(key);
38225
+ });
38226
+ if (sideNumber && !sideAssignmentKeys.includes(sideNumber)) {
38227
+ sideAssignments[sideNumber] = lineUp;
38228
+ }
38229
+ }
38230
+ }
38231
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
38232
+ finally {
38233
+ try {
38234
+ if (lineUps_1_1 && !lineUps_1_1.done && (_b = lineUps_1.return)) _b.call(lineUps_1);
38235
+ }
38236
+ finally { if (e_1) throw e_1.error; }
38237
+ }
38238
+ if (!Object.keys(sideAssignments).length)
38239
+ return { error: VALUE_UNCHANGED };
38240
+ result = findDrawMatchUp({ drawDefinition: drawDefinition, matchUpId: matchUpId });
38241
+ if (result.error)
38242
+ return result;
38243
+ if (!result.matchUp)
38244
+ return { error: MATCHUP_NOT_FOUND };
38245
+ var matchUp = result.matchUp;
38246
+ if (!matchUp.sides)
38247
+ matchUp.sides = [];
38248
+ var _loop_2 = function (sideNumber) {
38249
+ var side = matchUp.sides.find(function (side) { return side.sideNumber === sideNumber; });
38250
+ var assignment = sideAssignments[sideNumber];
38251
+ if (!assignment) {
38252
+ return "continue";
38253
+ }
38254
+ else if (!side) {
38255
+ matchUp.sides.push({ lineUp: assignment, sideNumber: sideNumber });
38256
+ }
38257
+ else {
38258
+ side.lineUp = assignment;
38259
+ }
38260
+ };
38261
+ try {
38262
+ for (var _k = __values([1, 2]), _l = _k.next(); !_l.done; _l = _k.next()) {
38263
+ var sideNumber = _l.value;
38264
+ _loop_2(sideNumber);
38265
+ }
38266
+ }
38267
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
38268
+ finally {
38269
+ try {
38270
+ if (_l && !_l.done && (_e = _k.return)) _e.call(_k);
38271
+ }
38272
+ finally { if (e_4) throw e_4.error; }
38455
38273
  }
38456
- var structure = (_f = drawDefinition === null || drawDefinition === void 0 ? void 0 : drawDefinition.structures) === null || _f === void 0 ? void 0 : _f.find(function (structure) { return structure.structureId === structureId; });
38457
- if (!structure)
38458
- return { error: STRUCTURE_NOT_FOUND };
38459
- // an AD_HOC structure is one that has no child structures and in which no matchUps have roundPosition
38460
- var structureIsAdHoc = isAdHoc({ drawDefinition: drawDefinition, structure: structure });
38461
- if (!structureIsAdHoc)
38462
- return { error: INVALID_DRAW_DEFINITION };
38463
- tournamentParticipants =
38464
- (_g = tournamentParticipants !== null && tournamentParticipants !== void 0 ? tournamentParticipants : tournamentRecord.participants) !== null && _g !== void 0 ? _g : [];
38465
- var _loop_1 = function (participantId) {
38466
- var participant = tournamentParticipants === null || tournamentParticipants === void 0 ? void 0 : tournamentParticipants.find(function (participant) { return participant.participantId === participantId; });
38467
- // first see if there is already a dynamic value
38468
- var scaleValue = getScaleValue({
38469
- scaleName: "".concat(scaleName, ".").concat(DYNAMIC),
38470
- scaleAccessor: scaleAccessor,
38471
- participant: participant,
38472
- eventType: eventType,
38274
+ modifyMatchUpNotice({
38275
+ tournamentId: tournamentRecord === null || tournamentRecord === void 0 ? void 0 : tournamentRecord.tournamentId,
38276
+ context: stack,
38277
+ drawDefinition: drawDefinition,
38278
+ matchUp: matchUp,
38279
+ });
38280
+ return __assign({}, SUCCESS);
38281
+ }
38282
+
38283
+ function resetTieFormat(params) {
38284
+ var _a, _b, e_1, _c, e_2, _d;
38285
+ var _e, _f, _g;
38286
+ var stack = 'resetTieFormat';
38287
+ var drawDefinition = params.drawDefinition, event = params.event, uuids = params.uuids;
38288
+ var paramCheck = checkRequiredParameters(params, [(_a = {}, _a[TOURNAMENT_RECORD] = true, _a[MATCHUP_ID] = true, _a)], stack);
38289
+ if (paramCheck.error)
38290
+ return paramCheck;
38291
+ var resolutions = resolveFromParameters(params, [(_b = {}, _b[PARAM] = MATCHUP, _b)]);
38292
+ if (resolutions[ERROR])
38293
+ return resolutions;
38294
+ var tournamentId = (_e = params.tournamentRecord) === null || _e === void 0 ? void 0 : _e.tournamentId;
38295
+ var _h = (_f = resolutions === null || resolutions === void 0 ? void 0 : resolutions.matchUp) !== null && _f !== void 0 ? _f : {}, matchUp = _h.matchUp, structure = _h.structure;
38296
+ if (!(matchUp === null || matchUp === void 0 ? void 0 : matchUp.tieMatchUps))
38297
+ return decorateResult({
38298
+ result: { error: INVALID_MATCHUP },
38299
+ info: 'Must be a TEAM matchUp',
38300
+ stack: stack,
38473
38301
  });
38474
- // if no dynamic value found and a seeding scaleValue is provided...
38475
- if (!scaleValue && scaleName) {
38476
- scaleValue = getScaleValue({
38477
- scaleAccessor: scaleAccessor,
38478
- participant: participant,
38479
- scaleName: scaleName,
38480
- eventType: eventType,
38302
+ // if there is no tieFormat there is nothing to do
38303
+ if (!matchUp.tieFormat)
38304
+ return __assign({}, SUCCESS);
38305
+ var tieFormat = (_g = resolveTieFormat({
38306
+ structure: structure,
38307
+ drawDefinition: drawDefinition,
38308
+ event: event,
38309
+ })) === null || _g === void 0 ? void 0 : _g.tieFormat;
38310
+ if (!tieFormat)
38311
+ return decorateResult({
38312
+ result: { error: NOT_FOUND },
38313
+ info: 'No inherited tieFormat',
38314
+ stack: stack,
38315
+ });
38316
+ var deletedMatchUpIds = [];
38317
+ var collectionIds = [];
38318
+ var tieMatchUps = [];
38319
+ var newMatchUps = [];
38320
+ var _loop_1 = function (collectionDefinition) {
38321
+ // delete any matchUp.tieMatchUps that are not found in the ancestor tieFormat collectionDefinitions
38322
+ var matchUpCount = collectionDefinition.matchUpCount, collectionId = collectionDefinition.collectionId;
38323
+ collectionIds.push(collectionId);
38324
+ var existingCollectionMatchUps = (matchUp.tieMatchUps || []).filter(function (matchUp) { return matchUp.collectionId === collectionId; });
38325
+ if (existingCollectionMatchUps.length > matchUpCount) {
38326
+ // sort by matchUpStatus to prioritize active or completed matchUpsA
38327
+ existingCollectionMatchUps.sort(function (a, b) {
38328
+ return (a.matchUpStatus === TO_BE_PLAYED ? 1 : 0) -
38329
+ (b.matchUpStatus === TO_BE_PLAYED ? 1 : 0);
38481
38330
  });
38331
+ tieMatchUps.push.apply(tieMatchUps, __spreadArray([], __read(existingCollectionMatchUps.slice(0, matchUpCount)), false));
38332
+ deletedMatchUpIds.push.apply(deletedMatchUpIds, __spreadArray([], __read(existingCollectionMatchUps.slice(3).map(getMatchUpId)), false));
38333
+ }
38334
+ else {
38335
+ tieMatchUps.push.apply(tieMatchUps, __spreadArray([], __read(existingCollectionMatchUps), false));
38336
+ if (existingCollectionMatchUps.length < matchUpCount) {
38337
+ var matchUpsLimit = matchUpCount - existingCollectionMatchUps.length;
38338
+ var matchUps = generateCollectionMatchUps({
38339
+ collectionDefinition: collectionDefinition,
38340
+ matchUpsLimit: matchUpsLimit,
38341
+ uuids: uuids,
38342
+ });
38343
+ newMatchUps.push.apply(newMatchUps, __spreadArray([], __read(matchUps), false));
38344
+ }
38482
38345
  }
38483
- if (scaleValue && !adHocRatings[participantId])
38484
- adHocRatings[participantId] = scaleValue;
38485
38346
  };
38486
38347
  try {
38487
- for (var _j = __values(participantIds !== null && participantIds !== void 0 ? participantIds : []), _k = _j.next(); !_k.done; _k = _j.next()) {
38488
- var participantId = _k.value;
38489
- _loop_1(participantId);
38348
+ for (var _j = __values(tieFormat.collectionDefinitions), _k = _j.next(); !_k.done; _k = _j.next()) {
38349
+ var collectionDefinition = _k.value;
38350
+ _loop_1(collectionDefinition);
38490
38351
  }
38491
38352
  }
38492
38353
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
38493
38354
  finally {
38494
38355
  try {
38495
- if (_k && !_k.done && (_b = _j.return)) _b.call(_j);
38356
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
38496
38357
  }
38497
38358
  finally { if (e_1) throw e_1.error; }
38498
38359
  }
38499
- // TODO: update dynamic ratings based on matchUps present from last played round
38500
- // use scaleEngine.generateDynamicRatings(); see dynamicCalculations.test.ts
38501
- return generateDrawMaticRound({
38502
- tournamentParticipants: tournamentParticipants,
38503
- generateMatchUps: generateMatchUps,
38504
- participantIds: participantIds,
38505
- encounterValue: encounterValue,
38506
- sameTeamValue: sameTeamValue,
38360
+ try {
38361
+ for (var _l = __values((matchUp === null || matchUp === void 0 ? void 0 : matchUp.tieMatchUps) || []), _m = _l.next(); !_m.done; _m = _l.next()) {
38362
+ var tieMatchUp = _m.value;
38363
+ if (tieMatchUp.collectionId &&
38364
+ !collectionIds.includes(tieMatchUp.collectionId))
38365
+ deletedMatchUpIds.push(tieMatchUp.matchUpId);
38366
+ }
38367
+ }
38368
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
38369
+ finally {
38370
+ try {
38371
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
38372
+ }
38373
+ finally { if (e_2) throw e_2.error; }
38374
+ }
38375
+ if (newMatchUps.length) {
38376
+ tieMatchUps.push.apply(tieMatchUps, __spreadArray([], __read(newMatchUps), false));
38377
+ addMatchUpsNotice({
38378
+ eventId: event === null || event === void 0 ? void 0 : event.eventId,
38379
+ matchUps: newMatchUps,
38380
+ drawDefinition: drawDefinition,
38381
+ tournamentId: tournamentId,
38382
+ });
38383
+ }
38384
+ if (deletedMatchUpIds.length) {
38385
+ deleteMatchUpsNotice({
38386
+ matchUpIds: deletedMatchUpIds,
38387
+ eventId: event === null || event === void 0 ? void 0 : event.eventId,
38388
+ drawDefinition: drawDefinition,
38389
+ tournamentId: tournamentId,
38390
+ });
38391
+ }
38392
+ if (matchUp) {
38393
+ matchUp.tieMatchUps = tieMatchUps;
38394
+ matchUp.tieFormatId = undefined;
38395
+ matchUp.tieFormat = undefined;
38396
+ modifyMatchUpNotice({
38397
+ structureId: structure === null || structure === void 0 ? void 0 : structure.structureId,
38398
+ eventId: event === null || event === void 0 ? void 0 : event.eventId,
38399
+ context: stack,
38400
+ drawDefinition: drawDefinition,
38401
+ tournamentId: tournamentId,
38402
+ matchUp: matchUp,
38403
+ });
38404
+ }
38405
+ return __assign(__assign({}, SUCCESS), { newMatchUps: newMatchUps, deletedMatchUpIds: deletedMatchUpIds });
38406
+ }
38407
+
38408
+ function resetScorecard(params) {
38409
+ var e_1, _a;
38410
+ var _b, _c;
38411
+ var tournamentRecord = params.tournamentRecord, drawDefinition = params.drawDefinition, matchUpId = params.matchUpId, event = params.event;
38412
+ var stack = 'resetScorecard';
38413
+ // Check for missing parameters ---------------------------------------------
38414
+ if (!drawDefinition)
38415
+ return decorateResult({
38416
+ result: { error: MISSING_DRAW_DEFINITION },
38417
+ stack: stack,
38418
+ });
38419
+ if (!matchUpId)
38420
+ return decorateResult({ result: { error: MISSING_MATCHUP_ID }, stack: stack });
38421
+ if (!isString(matchUpId))
38422
+ return decorateResult({
38423
+ result: { error: INVALID_VALUES, matchUpId: matchUpId },
38424
+ stack: stack,
38425
+ });
38426
+ // Get map of all drawMatchUps and inContextDrawMatchUPs ---------------------
38427
+ var matchUpsMap = getMatchUpsMap({ drawDefinition: drawDefinition });
38428
+ var inContextDrawMatchUps = getAllDrawMatchUps({
38429
+ nextMatchUps: true,
38430
+ inContext: true,
38507
38431
  drawDefinition: drawDefinition,
38508
- maxIterations: maxIterations,
38509
- adHocRatings: adHocRatings,
38510
- matchUpIds: matchUpIds,
38432
+ matchUpsMap: matchUpsMap,
38433
+ }).matchUps;
38434
+ // Find target matchUp ------------------------------------------------------
38435
+ var matchUp = matchUpsMap.drawMatchUps.find(function (matchUp) { return matchUp.matchUpId === matchUpId; });
38436
+ var inContextMatchUp = inContextDrawMatchUps === null || inContextDrawMatchUps === void 0 ? void 0 : inContextDrawMatchUps.find(function (matchUp) { return matchUp.matchUpId === matchUpId; });
38437
+ if (!matchUp || !inContextDrawMatchUps)
38438
+ return { error: MATCHUP_NOT_FOUND };
38439
+ // only accept matchUpType: TEAM
38440
+ if (matchUp.matchUpType !== TEAM_EVENT)
38441
+ return { error: INVALID_MATCHUP };
38442
+ // Get winner/loser position targets ----------------------------------------
38443
+ var targetData = positionTargets({
38444
+ inContextDrawMatchUps: inContextDrawMatchUps,
38445
+ drawDefinition: drawDefinition,
38446
+ matchUpId: matchUpId,
38447
+ });
38448
+ var structureId = inContextMatchUp === null || inContextMatchUp === void 0 ? void 0 : inContextMatchUp.structureId;
38449
+ var structure = findStructure({ drawDefinition: drawDefinition, structureId: structureId }).structure;
38450
+ Object.assign(params, {
38451
+ inContextDrawMatchUps: inContextDrawMatchUps,
38452
+ inContextMatchUp: inContextMatchUp,
38453
+ matchUpsMap: matchUpsMap,
38454
+ targetData: targetData,
38511
38455
  structure: structure,
38512
- eventType: eventType,
38513
- salted: salted,
38456
+ matchUp: matchUp,
38457
+ });
38458
+ // with propagating winningSide changes, activeDownstream only applies to eventType: TEAM
38459
+ var activeDownstream = isActiveDownstream(params);
38460
+ if (activeDownstream)
38461
+ return { error: CANNOT_CHANGE_WINNING_SIDE };
38462
+ if ((_b = matchUp.tieMatchUps) === null || _b === void 0 ? void 0 : _b.length) {
38463
+ try {
38464
+ for (var _d = __values(matchUp.tieMatchUps), _e = _d.next(); !_e.done; _e = _d.next()) {
38465
+ var tieMatchUp = _e.value;
38466
+ var result_1 = setMatchUpState({
38467
+ matchUpId: tieMatchUp.matchUpId,
38468
+ matchUpTieId: matchUpId,
38469
+ winningSide: undefined,
38470
+ removeScore: true,
38471
+ tournamentRecord: tournamentRecord,
38472
+ drawDefinition: drawDefinition,
38473
+ event: event,
38474
+ });
38475
+ if (result_1.error)
38476
+ return decorateResult({ result: result_1, stack: stack });
38477
+ }
38478
+ }
38479
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
38480
+ finally {
38481
+ try {
38482
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
38483
+ }
38484
+ finally { if (e_1) throw e_1.error; }
38485
+ }
38486
+ }
38487
+ var result = updateTieMatchUpScore({
38488
+ event: params.event,
38489
+ removeScore: true,
38490
+ tournamentRecord: tournamentRecord,
38491
+ drawDefinition: drawDefinition,
38492
+ matchUpsMap: matchUpsMap,
38493
+ matchUpId: matchUpId,
38514
38494
  });
38495
+ if (result.error)
38496
+ return decorateResult({ result: result, stack: stack });
38497
+ if (params.tiebreakReset && !result.tieFormatRemoved) {
38498
+ // check for scenarios where an added "Tiebreaker" collectionDefinition/matchUp has been added
38499
+ var inheritedTieFormat = (_c = resolveTieFormat({
38500
+ drawDefinition: drawDefinition,
38501
+ structure: structure,
38502
+ event: event,
38503
+ })) === null || _c === void 0 ? void 0 : _c.tieFormat;
38504
+ if (matchUp.tieFormat && inheritedTieFormat) {
38505
+ var _f = compareTieFormats({
38506
+ descendant: matchUp.tieFormat,
38507
+ ancestor: inheritedTieFormat,
38508
+ }), matchUpCountDifference = _f.matchUpCountDifference, descendantDifferences = _f.descendantDifferences, ancestorDifferences = _f.ancestorDifferences, valueDifference = _f.valueDifference;
38509
+ if (descendantDifferences.collectionIds.length === 1 &&
38510
+ !ancestorDifferences.collectionIds.length &&
38511
+ !ancestorDifferences.groupsCount &&
38512
+ matchUpCountDifference === 1 &&
38513
+ valueDifference === 1) {
38514
+ var result_2 = resetTieFormat({
38515
+ tournamentRecord: tournamentRecord,
38516
+ drawDefinition: drawDefinition,
38517
+ matchUpId: matchUpId,
38518
+ event: event,
38519
+ });
38520
+ if (result_2.error)
38521
+ return result_2;
38522
+ }
38523
+ }
38524
+ }
38525
+ return __assign({}, SUCCESS);
38515
38526
  }
38516
- function getScaleValue(_a) {
38517
- var _b;
38518
- var _c = _a.scaleType, scaleType = _c === void 0 ? RATING$2 : _c, scaleAccessor = _a.scaleAccessor, participant = _a.participant, scaleName = _a.scaleName, eventType = _a.eventType;
38527
+
38528
+ function removeSeeding(_a) {
38529
+ var _b, _c;
38530
+ var tournamentRecord = _a.tournamentRecord, drawDefinition = _a.drawDefinition, entryStatuses = _a.entryStatuses, scaleName = _a.scaleName, drawId = _a.drawId, event = _a.event, stage = _a.stage;
38531
+ if (!tournamentRecord)
38532
+ return { error: MISSING_TOURNAMENT_RECORD };
38533
+ if (!event)
38534
+ return { error: MISSING_EVENT };
38535
+ scaleName =
38536
+ scaleName ||
38537
+ ((_b = event.category) === null || _b === void 0 ? void 0 : _b.categoryName) ||
38538
+ ((_c = event.category) === null || _c === void 0 ? void 0 : _c.ageCategoryCode);
38519
38539
  var scaleAttributes = {
38520
- eventType: eventType !== null && eventType !== void 0 ? eventType : SINGLES_EVENT,
38521
- scaleType: scaleType,
38540
+ eventType: event.eventType,
38541
+ scaleType: SEEDING$1,
38522
38542
  scaleName: scaleName,
38523
38543
  };
38524
- var result = participant &&
38525
- participantScaleItem({
38526
- scaleAttributes: scaleAttributes,
38527
- participant: participant,
38528
- });
38529
- var scaleValue = (_b = result === null || result === void 0 ? void 0 : result.scaleItem) === null || _b === void 0 ? void 0 : _b.scaleValue;
38530
- return scaleAccessor && isObject(scaleValue)
38531
- ? scaleValue[scaleAccessor]
38532
- : scaleValue;
38533
- }
38534
-
38535
- function drawMatic(params) {
38536
- var _a;
38537
- var tournamentParticipants = (_a = params.tournamentRecord) === null || _a === void 0 ? void 0 : _a.participants;
38538
- Object.assign(params, { tournamentParticipants: tournamentParticipants });
38539
- return drawMatic$1(params);
38544
+ return removeScaleValues({
38545
+ tournamentRecord: tournamentRecord,
38546
+ scaleAttributes: scaleAttributes,
38547
+ drawDefinition: drawDefinition,
38548
+ entryStatuses: entryStatuses,
38549
+ drawId: drawId,
38550
+ event: event,
38551
+ stage: stage,
38552
+ });
38540
38553
  }
38541
38554
 
38542
38555
  function setSubOrder(_a) {
@@ -42596,7 +42609,7 @@ function generateDrawDefinition(params) {
42596
42609
  var _a, _b, _c;
42597
42610
  if (params.automated) {
42598
42611
  var _d = (_a = params.drawMatic) !== null && _a !== void 0 ? _a : {}, restrictEntryStatus = _d.restrictEntryStatus, generateMatchUps = _d.generateMatchUps, structureId_1 = _d.structureId, matchUpIds = _d.matchUpIds, scaleName = _d.scaleName;
42599
- var matchUps = drawMatic$1({
42612
+ var matchUps = drawMatic({
42600
42613
  eventType: (_c = (_b = params.drawMatic) === null || _b === void 0 ? void 0 : _b.eventType) !== null && _c !== void 0 ? _c : matchUpType,
42601
42614
  generateMatchUps: generateMatchUps !== null && generateMatchUps !== void 0 ? generateMatchUps : true,
42602
42615
  restrictEntryStatus: restrictEntryStatus,
@@ -42605,7 +42618,8 @@ function generateDrawDefinition(params) {
42605
42618
  drawDefinition: drawDefinition,
42606
42619
  structureId: structureId_1,
42607
42620
  matchUpIds: matchUpIds,
42608
- scaleName: scaleName,
42621
+ scaleName: scaleName, // custom rating name to seed dynamic ratings
42622
+ event: event,
42609
42623
  }).matchUps;
42610
42624
  addAdHocMatchUps({
42611
42625
  tournamentRecord: tournamentRecord,
@@ -42619,6 +42633,7 @@ function generateDrawDefinition(params) {
42619
42633
  newRound: true,
42620
42634
  drawDefinition: drawDefinition,
42621
42635
  matchUpsCount: matchUpsCount_1,
42636
+ event: event,
42622
42637
  }).matchUps;
42623
42638
  addAdHocMatchUps({
42624
42639
  tournamentRecord: tournamentRecord,
@@ -45203,7 +45218,7 @@ function checkRequestConflicts(_a) {
45203
45218
 
45204
45219
  function findMatchUpFormatTiming(_a) {
45205
45220
  var _b = _a.defaultRecoveryMinutes, defaultRecoveryMinutes = _b === void 0 ? 0 : _b, defaultAverageMinutes = _a.defaultAverageMinutes, tournamentRecords = _a.tournamentRecords, matchUpFormat = _a.matchUpFormat, categoryName = _a.categoryName, categoryType = _a.categoryType, tournamentId = _a.tournamentId, eventType = _a.eventType, eventId = _a.eventId;
45206
- if (!isValidMatchUpFormat(matchUpFormat))
45221
+ if (!isValidMatchUpFormat({ matchUpFormat: matchUpFormat }))
45207
45222
  return { error: UNRECOGNIZED_MATCHUP_FORMAT };
45208
45223
  var tournamentIds = Object.keys(tournamentRecords).filter(function (currentTournamentId) {
45209
45224
  return !tournamentId || currentTournamentId === tournamentId;
@@ -49074,7 +49089,7 @@ function generateOutcome(params) {
49074
49089
  var _d = params.matchUpStatusProfile, matchUpStatusProfile = _d === void 0 ? defaultStatusProfile : _d, // { matchUpStatusProfile: {} } will always return only { matchUpStatus: COMPLETED }
49075
49090
  _e = params.matchUpFormat, // { matchUpStatusProfile: {} } will always return only { matchUpStatus: COMPLETED }
49076
49091
  matchUpFormat = _e === void 0 ? FORMAT_STANDARD : _e, _f = params.pointsPerMinute, pointsPerMinute = _f === void 0 ? 1 : _f, _g = params.sideWeight, sideWeight = _g === void 0 ? 4 : _g;
49077
- if (!isValidMatchUpFormat(matchUpFormat))
49092
+ if (!isValidMatchUpFormat({ matchUpFormat: matchUpFormat }))
49078
49093
  return { error: INVALID_MATCHUP_FORMAT };
49079
49094
  if (typeof matchUpStatusProfile !== 'object')
49080
49095
  return { error: INVALID_VALUES };
@@ -52549,7 +52564,6 @@ var publishingGovernor = {
52549
52564
  getDrawData: getDrawData,
52550
52565
  getEventData: getEventData,
52551
52566
  getPublishState: getPublishState,
52552
- getTournamentInfo: getTournamentInfo,
52553
52567
  getVenueData: getVenueData,
52554
52568
  publishEvent: publishEvent,
52555
52569
  publishEventSeeding: publishEventSeeding,
@@ -53094,7 +53108,9 @@ function getEventMatchUpFormatTiming(_a) {
53094
53108
  : definition;
53095
53109
  if (uniqueMatchUpFormats_1.includes(definitionObject === null || definitionObject === void 0 ? void 0 : definitionObject.matchUpFormat))
53096
53110
  return;
53097
- if (!isValidMatchUpFormat(definitionObject === null || definitionObject === void 0 ? void 0 : definitionObject.matchUpFormat))
53111
+ if (!isValidMatchUpFormat({
53112
+ matchUpFormat: definitionObject === null || definitionObject === void 0 ? void 0 : definitionObject.matchUpFormat,
53113
+ }))
53098
53114
  return;
53099
53115
  uniqueMatchUpFormats_1.push(definitionObject.matchUpFormat);
53100
53116
  return definitionObject;
@@ -53125,8 +53141,8 @@ function getModifiedMatchUpFormatTiming(params) {
53125
53141
  var paramCheck = checkRequiredParameters(params, [
53126
53142
  (_a = {}, _a[TOURNAMENT_RECORD] = true, _a),
53127
53143
  (_b = {},
53144
+ _b[VALIDATE] = function (matchUpFormat) { return isValidMatchUpFormat({ matchUpFormat: matchUpFormat }); },
53128
53145
  _b[INVALID] = UNRECOGNIZED_MATCHUP_FORMAT,
53129
- _b[VALIDATE] = isValidMatchUpFormat,
53130
53146
  _b[MATCHUP_FORMAT] = true,
53131
53147
  _b),
53132
53148
  ]);
@@ -54126,6 +54142,53 @@ function getParticipantMembership(_a) {
54126
54142
  }, {});
54127
54143
  }
54128
54144
 
54145
+ /**
54146
+ *
54147
+ * @param {object[]} outcomes - array of outcomes to be applied to matchUps, relevent attributes: { eventId: string; drawId: string; }
54148
+ *
54149
+ */
54150
+ function bulkUpdatePublishedEventIds(_a) {
54151
+ var _b;
54152
+ var tournamentRecord = _a.tournamentRecord, outcomes = _a.outcomes;
54153
+ if (!tournamentRecord)
54154
+ return { error: MISSING_TOURNAMENT_RECORD };
54155
+ if (!(outcomes === null || outcomes === void 0 ? void 0 : outcomes.length))
54156
+ return { error: MISSING_VALUE, info: 'Missing outcomes' };
54157
+ var eventIdsMap = outcomes.reduce(function (eventIdsMap, outcome) {
54158
+ var drawId = outcome.drawId, eventId = outcome.eventId;
54159
+ if (eventId && drawId) {
54160
+ if (!eventIdsMap[eventId]) {
54161
+ eventIdsMap[eventId] = [drawId];
54162
+ }
54163
+ else if (!eventIdsMap[eventId].includes(drawId)) {
54164
+ eventIdsMap[eventId].push(drawId);
54165
+ }
54166
+ }
54167
+ return eventIdsMap;
54168
+ }, {});
54169
+ var relevantEventsIds = Object.keys(eventIdsMap);
54170
+ var relevantEvents = (_b = tournamentRecord.events) === null || _b === void 0 ? void 0 : _b.filter(function (event) {
54171
+ return relevantEventsIds.includes(event.eventId);
54172
+ });
54173
+ var publishedEventIds = relevantEvents
54174
+ .filter(function (event) {
54175
+ var pubStatus = getEventPublishStatus({ event: event });
54176
+ var _a = pubStatus !== null && pubStatus !== void 0 ? pubStatus : {}, drawDetails = _a.drawDetails, drawIds = _a.drawIds;
54177
+ var eventId = event.eventId;
54178
+ var publishedDrawIds = eventIdsMap[eventId].filter(function (drawId) {
54179
+ var keyedDrawIds = drawDetails
54180
+ ? Object.keys(pubStatus.drawDetails).filter(function (drawId) {
54181
+ return getDrawPublishStatus({ drawId: drawId, drawDetails: drawDetails });
54182
+ })
54183
+ : [];
54184
+ return (drawIds === null || drawIds === void 0 ? void 0 : drawIds.includes(drawId)) || keyedDrawIds.includes(drawId);
54185
+ });
54186
+ return publishedDrawIds.length;
54187
+ })
54188
+ .map(function (event) { return event.eventId; });
54189
+ return { publishedEventIds: publishedEventIds, eventIdPublishedDrawIdsMap: eventIdsMap };
54190
+ }
54191
+
54129
54192
  function getSourceStructureIdsAndRelevantLinks(_a) {
54130
54193
  var targetRoundNumber = _a.targetRoundNumber, finishingPosition = _a.finishingPosition, drawDefinition = _a.drawDefinition, structureId = _a.structureId, // structure for which source and target links are to be found
54131
54194
  linkType = _a.linkType;
@@ -56371,6 +56434,15 @@ function getParticipantSignInStatus(_a) {
56371
56434
  return timeItem && timeItem.itemValue === SIGNED_IN && SIGNED_IN;
56372
56435
  }
56373
56436
 
56437
+ function getMatchUpContextIds(_a) {
56438
+ var matchUps = _a.matchUps, matchUpId = _a.matchUpId;
56439
+ if (!validMatchUps(matchUps))
56440
+ return { error: INVALID_VALUES };
56441
+ var matchUp = matchUps.find(function (matchUp) { return matchUp.matchUpId === matchUpId; });
56442
+ var _b = matchUp || {}, drawId = _b.drawId, eventId = _b.eventId, structureId = _b.structureId, tournamentId = _b.tournamentId;
56443
+ return { matchUpId: matchUpId, drawId: drawId, eventId: eventId, structureId: structureId, tournamentId: tournamentId };
56444
+ }
56445
+
56374
56446
  function getMaxEntryPosition(params) {
56375
56447
  var _a = params.entries, entries = _a === void 0 ? [] : _a, entryStatus = params.entryStatus, stage = params.stage;
56376
56448
  return Math.max.apply(Math, __spreadArray(__spreadArray([], __read(entries
@@ -56463,53 +56535,6 @@ function getMatchUpFormat(params) {
56463
56535
  };
56464
56536
  }
56465
56537
 
56466
- /**
56467
- *
56468
- * @param {object[]} outcomes - array of outcomes to be applied to matchUps, relevent attributes: { eventId: string; drawId: string; }
56469
- *
56470
- */
56471
- function bulkUpdatePublishedEventIds(_a) {
56472
- var _b;
56473
- var tournamentRecord = _a.tournamentRecord, outcomes = _a.outcomes;
56474
- if (!tournamentRecord)
56475
- return { error: MISSING_TOURNAMENT_RECORD };
56476
- if (!(outcomes === null || outcomes === void 0 ? void 0 : outcomes.length))
56477
- return { error: MISSING_VALUE, info: 'Missing outcomes' };
56478
- var eventIdsMap = outcomes.reduce(function (eventIdsMap, outcome) {
56479
- var drawId = outcome.drawId, eventId = outcome.eventId;
56480
- if (eventId && drawId) {
56481
- if (!eventIdsMap[eventId]) {
56482
- eventIdsMap[eventId] = [drawId];
56483
- }
56484
- else if (!eventIdsMap[eventId].includes(drawId)) {
56485
- eventIdsMap[eventId].push(drawId);
56486
- }
56487
- }
56488
- return eventIdsMap;
56489
- }, {});
56490
- var relevantEventsIds = Object.keys(eventIdsMap);
56491
- var relevantEvents = (_b = tournamentRecord.events) === null || _b === void 0 ? void 0 : _b.filter(function (event) {
56492
- return relevantEventsIds.includes(event.eventId);
56493
- });
56494
- var publishedEventIds = relevantEvents
56495
- .filter(function (event) {
56496
- var pubStatus = getEventPublishStatus({ event: event });
56497
- var _a = pubStatus !== null && pubStatus !== void 0 ? pubStatus : {}, drawDetails = _a.drawDetails, drawIds = _a.drawIds;
56498
- var eventId = event.eventId;
56499
- var publishedDrawIds = eventIdsMap[eventId].filter(function (drawId) {
56500
- var keyedDrawIds = drawDetails
56501
- ? Object.keys(pubStatus.drawDetails).filter(function (drawId) {
56502
- return getDrawPublishStatus({ drawId: drawId, drawDetails: drawDetails });
56503
- })
56504
- : [];
56505
- return (drawIds === null || drawIds === void 0 ? void 0 : drawIds.includes(drawId)) || keyedDrawIds.includes(drawId);
56506
- });
56507
- return publishedDrawIds.length;
56508
- })
56509
- .map(function (event) { return event.eventId; });
56510
- return { publishedEventIds: publishedEventIds, eventIdPublishedDrawIdsMap: eventIdsMap };
56511
- }
56512
-
56513
56538
  function publicFindParticipant(params) {
56514
56539
  var _a, e_1, _b;
56515
56540
  var tournamentRecord = params.tournamentRecord, policyDefinitions = params.policyDefinitions, contextProfile = params.contextProfile, participantId = params.participantId, personId = params.personId;
@@ -57656,6 +57681,7 @@ var queryGovernor = {
57656
57681
  getTeamLineUp: getTeamLineUp,
57657
57682
  getTieFormat: getTieFormat,
57658
57683
  getTournamentIds: getTournamentIds,
57684
+ getTournamentInfo: getTournamentInfo,
57659
57685
  getTournamentPenalties: getTournamentPenalties,
57660
57686
  getTournamentPersons: getTournamentPersons,
57661
57687
  getTournamentStructures: getTournamentStructures,
@@ -57674,6 +57700,20 @@ var queryGovernor = {
57674
57700
  validateLineUp: validateLineUp,
57675
57701
  validMatchUp: validMatchUp,
57676
57702
  validMatchUps: validMatchUps,
57703
+ allPlayoffPositionsFilled: allPlayoffPositionsFilled,
57704
+ getCategoryAgeDetails: getCategoryAgeDetails,
57705
+ calculateWinCriteria: calculateWinCriteria,
57706
+ compareTieFormats: compareTieFormats,
57707
+ getMatchUpContextIds: getMatchUpContextIds,
57708
+ getScaleValues: getScaleValues,
57709
+ getSeedingThresholds: getSeedingThresholds,
57710
+ getTimeItem: getTimeItem,
57711
+ getValidGroupSizes: getValidGroupSizes,
57712
+ isAdHoc: isAdHoc,
57713
+ isCompletedStructure: isCompletedStructure,
57714
+ roundRobinGroups: roundRobinGroups,
57715
+ tieFormatGenderValidityCheck: tieFormatGenderValidityCheck,
57716
+ validateCategory: validateCategory,
57677
57717
  };
57678
57718
 
57679
57719
  function getDetailsWTN(_a) {
@@ -59044,7 +59084,7 @@ function modifyEventMatchUpFormatTiming(params) {
59044
59084
  var tournamentRecord = params.tournamentRecord, recoveryMinutes = params.recoveryMinutes, averageMinutes = params.averageMinutes, matchUpFormat = params.matchUpFormat, categoryType = params.categoryType, eventId = params.eventId, event = params.event;
59045
59085
  if (!tournamentRecord)
59046
59086
  return { error: MISSING_TOURNAMENT_RECORD };
59047
- if (!isValidMatchUpFormat(matchUpFormat))
59087
+ if (!isValidMatchUpFormat({ matchUpFormat: matchUpFormat }))
59048
59088
  return { error: INVALID_VALUES };
59049
59089
  if (!event)
59050
59090
  return { error: MISSING_EVENT };
@@ -63585,7 +63625,7 @@ function calculateHistoryScore(params) {
63585
63625
  var matchUpFormat = matchUp.matchUpFormat;
63586
63626
  if (!matchUpFormat)
63587
63627
  return { error: MISSING_MATCHUP_FORMAT };
63588
- if (!isValidMatchUpFormat(matchUpFormat))
63628
+ if (!isValidMatchUpFormat({ matchUpFormat: matchUpFormat }))
63589
63629
  return { error: INVALID_MATCHUP_FORMAT };
63590
63630
  var parsedFormat = parse(matchUpFormat);
63591
63631
  var bestOf = parsedFormat.bestOf, finalSetFormat = parsedFormat.finalSetFormat, setFormat = parsedFormat.setFormat;
@@ -64309,15 +64349,6 @@ function visualizeScheduledMatchUps(_a) {
64309
64349
  printGlobalLog();
64310
64350
  }
64311
64351
 
64312
- function getMatchUpContextIds(_a) {
64313
- var matchUps = _a.matchUps, matchUpId = _a.matchUpId;
64314
- if (!validMatchUps(matchUps))
64315
- return { error: INVALID_VALUES };
64316
- var matchUp = matchUps.find(function (matchUp) { return matchUp.matchUpId === matchUpId; });
64317
- var _b = matchUp || {}, drawId = _b.drawId, eventId = _b.eventId, structureId = _b.structureId, tournamentId = _b.tournamentId;
64318
- return { matchUpId: matchUpId, drawId: drawId, eventId: eventId, structureId: structureId, tournamentId: tournamentId };
64319
- }
64320
-
64321
64352
  function dehydrateMatchUps(_a) {
64322
64353
  var tournamentRecord = _a.tournamentRecord;
64323
64354
  if (!tournamentRecord)
@@ -64640,38 +64671,29 @@ function flattenJSON(obj, keyJoiner, path) {
64640
64671
  }
64641
64672
 
64642
64673
  var utilitiesGovernor = {
64674
+ visualizeScheduledMatchUps: visualizeScheduledMatchUps,
64675
+ dehydrateMatchUps: dehydrateMatchUps,
64676
+ structureSort: structureSort,
64643
64677
  allNumeric: allNumeric$1,
64644
- allPlayoffPositionsFilled: allPlayoffPositionsFilled,
64645
64678
  attributeFilter: attributeFilter,
64646
- calculateWinCriteria: calculateWinCriteria,
64647
64679
  chunkArray: chunkArray,
64648
64680
  chunkByNth: chunkByNth,
64649
64681
  chunkSizeProfile: chunkSizeProfile,
64650
- compareTieFormats: compareTieFormats,
64651
64682
  constantToString: constantToString,
64652
64683
  countValues: countValues,
64653
64684
  createMap: createMap,
64654
64685
  dateRange: dateRange,
64655
64686
  dateTime: dateTime,
64656
64687
  definedAttributes: definedAttributes,
64657
- dehydrateMatchUps: dehydrateMatchUps,
64658
64688
  extractAttributes: extractAttributes,
64659
64689
  flattenJSON: flattenJSON,
64660
64690
  generateHashCode: generateHashCode,
64661
64691
  generateRange: generateRange,
64662
64692
  generateTimeCode: generateTimeCode,
64663
- getCategoryAgeDetails: getCategoryAgeDetails,
64664
- getMatchUpContextIds: getMatchUpContextIds,
64665
- getScaleValues: getScaleValues,
64666
- getSeedingThresholds: getSeedingThresholds,
64667
- getTimeItem: getTimeItem,
64668
- getValidGroupSizes: getValidGroupSizes,
64669
64693
  groupValues: groupValues,
64670
64694
  hasAttributeValues: hasAttributeValues,
64671
64695
  instanceCount: instanceCount,
64672
64696
  intersection: intersection,
64673
- isAdHoc: isAdHoc,
64674
- isCompletedStructure: isCompletedStructure,
64675
64697
  isConvertableInteger: isConvertableInteger,
64676
64698
  isNumeric: isNumeric,
64677
64699
  isOdd: isOdd,
@@ -64688,17 +64710,12 @@ var utilitiesGovernor = {
64688
64710
  overlap: overlap,
64689
64711
  randomMember: randomMember,
64690
64712
  randomPop: randomPop,
64691
- roundRobinGroups: roundRobinGroups,
64692
64713
  shuffleArray: shuffleArray,
64693
- structureSort: structureSort,
64694
64714
  subSort: subSort,
64695
- tieFormatGenderValidityCheck: tieFormatGenderValidityCheck,
64696
64715
  undefinedToNull: undefinedToNull,
64697
64716
  unique: unique,
64698
64717
  UUID: UUID,
64699
64718
  UUIDS: UUIDS,
64700
- validateCategory: validateCategory,
64701
- visualizeScheduledMatchUps: visualizeScheduledMatchUps,
64702
64719
  };
64703
64720
  var utilities = utilitiesGovernor;
64704
64721
 
@@ -66043,7 +66060,7 @@ function asyncExecutionQueue(engine, directives, rollbackOnError) {
66043
66060
  var e_1, _a;
66044
66061
  return __generator(this, function (_b) {
66045
66062
  if (!Array.isArray(directives))
66046
- return [2 /*return*/, { error: INVALID_VALUES }];
66063
+ return [2 /*return*/, { error: INVALID_VALUES, message: 'directives must be an array' }];
66047
66064
  methods = getMethods();
66048
66065
  start = Date.now();
66049
66066
  snapshot = rollbackOnError && makeDeepCopy(getTournamentRecords(), false, true);
@@ -66052,7 +66069,7 @@ function asyncExecutionQueue(engine, directives, rollbackOnError) {
66052
66069
  for (directives_1 = __values(directives), directives_1_1 = directives_1.next(); !directives_1_1.done; directives_1_1 = directives_1.next()) {
66053
66070
  directive = directives_1_1.value;
66054
66071
  if (typeof directive !== 'object')
66055
- return [2 /*return*/, { error: INVALID_VALUES }];
66072
+ return [2 /*return*/, { error: INVALID_VALUES, message: 'directive must be an object' }];
66056
66073
  methodName = directive.method, params = directive.params;
66057
66074
  if (!methods[methodName])
66058
66075
  return [2 /*return*/, logMethodNotFound({ methodName: methodName, start: start, params: params })];
@@ -66090,15 +66107,18 @@ function asyncEngineInvoke(engine, args) {
66090
66107
  switch (_d.label) {
66091
66108
  case 0:
66092
66109
  if (!isObject(args))
66093
- return [2 /*return*/, { error: INVALID_VALUES }];
66110
+ return [2 /*return*/, { error: INVALID_VALUES, message: 'args must be an object' }];
66094
66111
  methodsCount = Object.values(args).filter(isFunction).length;
66095
66112
  if (methodsCount > 1)
66096
- return [2 /*return*/, { error: INVALID_VALUES }];
66113
+ return [2 /*return*/, {
66114
+ message: 'there must be only one arg with typeof function',
66115
+ error: INVALID_VALUES,
66116
+ }];
66097
66117
  methodName = methodsCount
66098
66118
  ? Object.keys(args).find(function (key) { return isFunction(args[key]); })
66099
66119
  : isString(args.method) && args.method;
66100
66120
  if (!methodName)
66101
- return [2 /*return*/, { error: INVALID_VALUES }];
66121
+ return [2 /*return*/, { error: METHOD_NOT_FOUND }];
66102
66122
  _b = args, _c = methodName, passedMethod = _b[_c], remainingArgs = __rest(_b, [typeof _c === "symbol" ? _c : _c + ""]);
66103
66123
  params = (args === null || args === void 0 ? void 0 : args.params) || __assign({}, remainingArgs);
66104
66124
  snapshot = params.rollbackOnError && makeDeepCopy(getTournamentRecords(), false, true);
@@ -66253,15 +66273,18 @@ function asyncEngine(test) {
66253
66273
 
66254
66274
  function askInvoke(engine, args) {
66255
66275
  if (!isObject(args))
66256
- return { error: INVALID_VALUES };
66276
+ return { error: INVALID_VALUES, message: 'args must be an object' };
66257
66277
  var methodsCount = Object.values(args).filter(isFunction).length;
66258
66278
  if (methodsCount > 1)
66259
- return { error: INVALID_VALUES };
66279
+ return {
66280
+ message: 'there must be only one arg with typeof function',
66281
+ error: INVALID_VALUES,
66282
+ };
66260
66283
  var methodName = methodsCount
66261
66284
  ? Object.keys(args).find(function (key) { return isFunction(args[key]); })
66262
66285
  : isString(args.method) && args.method;
66263
66286
  if (!methodName)
66264
- return { error: INVALID_VALUES };
66287
+ return { error: METHOD_NOT_FOUND };
66265
66288
  var _a = args, _b = methodName, passedMethod = _a[_b], remainingArgs = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
66266
66289
  var params = (args === null || args === void 0 ? void 0 : args.params) || __assign({}, remainingArgs);
66267
66290
  var method = passedMethod || engine[methodName] || getMethods$1()[methodName];
@@ -66281,7 +66304,7 @@ var askEngine = (function () {
66281
66304
  function executionQueue(engine, directives, rollbackOnError) {
66282
66305
  var e_1, _a;
66283
66306
  if (!Array.isArray(directives))
66284
- return { error: INVALID_VALUES };
66307
+ return { error: INVALID_VALUES, message: 'directives must be an array' };
66285
66308
  var methods = getMethods();
66286
66309
  var start = Date.now();
66287
66310
  var snapshot = rollbackOnError && makeDeepCopy(getTournamentRecords(), false, true);
@@ -66290,7 +66313,7 @@ function executionQueue(engine, directives, rollbackOnError) {
66290
66313
  for (var directives_1 = __values(directives), directives_1_1 = directives_1.next(); !directives_1_1.done; directives_1_1 = directives_1.next()) {
66291
66314
  var directive = directives_1_1.value;
66292
66315
  if (typeof directive !== 'object')
66293
- return { error: INVALID_VALUES };
66316
+ return { error: INVALID_VALUES, message: 'directive must be an object' };
66294
66317
  var methodName = directive.method, params = directive.params;
66295
66318
  if (!methods[methodName])
66296
66319
  return logMethodNotFound({ methodName: methodName, start: start, params: params });
@@ -66321,15 +66344,18 @@ function executionQueue(engine, directives, rollbackOnError) {
66321
66344
  function engineInvoke(engine, args) {
66322
66345
  var _a;
66323
66346
  if (!isObject(args))
66324
- return { error: INVALID_VALUES };
66347
+ return { error: INVALID_VALUES, message: 'args must be an object' };
66325
66348
  var methodsCount = Object.values(args).filter(isFunction).length;
66326
66349
  if (methodsCount > 1)
66327
- return { error: INVALID_VALUES };
66350
+ return {
66351
+ message: 'there must be only one arg with typeof function',
66352
+ error: INVALID_VALUES,
66353
+ };
66328
66354
  var methodName = methodsCount
66329
66355
  ? Object.keys(args).find(function (key) { return isFunction(args[key]); })
66330
66356
  : isString(args.method) && args.method;
66331
66357
  if (!methodName)
66332
- return { error: INVALID_VALUES };
66358
+ return { error: METHOD_NOT_FOUND };
66333
66359
  var _b = args, _c = methodName, passedMethod = _b[_c], remainingArgs = __rest(_b, [typeof _c === "symbol" ? _c : _c + ""]);
66334
66360
  var params = (args === null || args === void 0 ? void 0 : args.params) || __assign({}, remainingArgs);
66335
66361
  var snapshot = params.rollbackOnError && makeDeepCopy(getTournamentRecords(), false, true);
@@ -67686,7 +67712,6 @@ exports.positionActionConstants = positionActionConstants;
67686
67712
  exports.resultConstants = resultConstants;
67687
67713
  exports.scaleConstants = scaleConstants;
67688
67714
  exports.scaleEngine = scaleEngine;
67689
- exports.scoreGovernor = scoreGovernor;
67690
67715
  exports.surfaceConstants = surfaceConstants;
67691
67716
  exports.syncEngine = engine;
67692
67717
  exports.timeItemConstants = timeItemConstants;