@outbuild-company/schedule-core 1.12.0 → 1.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cdn/schedule-core.global.js +1 -1
- package/dist/cdn/schedule-core.global.js.map +1 -1
- package/dist/index.cjs +1239 -633
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +136 -32
- package/dist/index.d.ts +136 -32
- package/dist/index.js +1237 -634
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var ScheduleCore=(()=>{var fn=Object.defineProperty;var Ou=Object.getOwnPropertyDescriptor;var bu=Object.getOwnPropertyNames;var Nu=Object.prototype.hasOwnProperty;var wu=(e,t)=>{for(var r in t)fn(e,r,{get:t[r],enumerable:!0})},Fu=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of bu(t))!Nu.call(e,n)&&n!==r&&fn(e,n,{get:()=>t[n],enumerable:!(i=Ou(t,n))||i.enumerable});return e};var xu=e=>Fu(fn({},"__esModule",{value:!0}),e);var $A={};wu($A,{ACTIVITY_BATCH_ACTION_KIND:()=>Fr,ACTIVITY_BATCH_MODE:()=>ot,ACTIVITY_DATE_EDGE:()=>sr,ACTIVITY_FIELD:()=>lt,ACTIVITY_PONDERATOR_CRITERION:()=>dt,ACTIVITY_TYPE:()=>Dt,CALENDAR_UNIT:()=>pt,CHANGE_SET_SOURCE_KIND:()=>Gt,COLUMN:()=>S,COMPLETED_PROGRESS:()=>ur,CONSTRAINT_TYPE:()=>H,CONSTRAINT_TYPE_TO_LABEL:()=>Eu,CONSTRAINT_WARNING_KIND:()=>yi,CREATION_KIND:()=>Pu,DATE_GESTURE_KIND:()=>nr,DEFAULT_HOURS_PER_DAY:()=>Ru,DISPATCH_ACTION_KIND:()=>P,DISPATCH_ACTION_KINDS:()=>po,DISPATCH_LINK_OPERATION_KIND:()=>tt,DISPATCH_TRACK_EVENT:()=>Ot,FILTER_FIELD:()=>B,FILTER_LOGIC:()=>Ur,FILTER_OPERATOR:()=>w,FILTER_REJECTION_REASON:()=>ft,FILTER_VALUE_KIND:()=>E,LINK_BATCH_OPERATION_KIND:()=>Ne,LINK_CODE_TO_TYPE:()=>me,LINK_REJECTION_REASON:()=>ut,LINK_RELATIONSHIP:()=>fe,LINK_TYPE:()=>U,LINK_TYPE_CODE:()=>es,NEW_ACTIVITY_DEFAULTS:()=>bi,NOT_STARTED_PROGRESS:()=>jo,ORDER_DIRECTION:()=>ye,REJECTION_REASON:()=>v,ROOT_PARENT_ID:()=>x,SCHEDULE_CORE_STATUS:()=>Bt,SCHEDULE_EFFECT_KIND:()=>fi,SIR_AUTO_REJECT_REASON:()=>pi,STATUS:()=>mt,STATUS_CRITERIA:()=>Jt,ScheduleCore:()=>ar,WORK_TIME_DIRECTION:()=>rt,checkNoUpdatedLinks:()=>Ud,computeExpectedProgress:()=>Hn,createSchedule:()=>Du,expectedProgressFromBaseline:()=>$e,getActiveBaseline:()=>gt,getUnsavedActivities:()=>_u,isRootParent:()=>N,normalizeParentKey:()=>Qt,parseFromBackend:()=>nn,willRunCriticalPath:()=>md,yieldToBrowser:()=>it});var rt={FUTURE:"future",PAST:"past"},pt={HOUR:"hour",DAY:"day"},dt={DURATION:"DURATION",COST:"COST",WORK_HOURS:"HH"},Jt={BASELINE:"Baseline",ACTUAL:"Actual"},mt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var H={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},Mu={mso:()=>!0,mfo:()=>!0,snlt:(e,t)=>e<t,snet:(e,t)=>e>t,fnlt:(e,t)=>e<t,fnet:(e,t)=>e>t};function co(e,t,r){if(!t)return{violated:!1};let i=Mu[e];return i?i(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var Uu=new Set(["mso","snet","snlt"]);function or(e,t,r){return Uu.has(e)?t:r}function lo(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var Bu={snet:{startOfDay:!0,direction:rt.FUTURE},snlt:{startOfDay:!0,direction:rt.PAST},fnet:{startOfDay:!1,direction:rt.FUTURE},fnlt:{startOfDay:!1,direction:rt.PAST},mso:{startOfDay:!0,direction:rt.FUTURE},mfo:{startOfDay:!1,direction:rt.PAST}},wr=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),so=(e,t)=>new Date(e.getTime()+t*864e5),Wu=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function pn(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=Bu[e.constraintType];if(!r)return e.constraintDate;let i=e.constraintDate,n=t.getClosestWorkTime({date:wr(i),dir:rt.FUTURE,task:e});if(Wu(n,i))return i.getTime()!==wr(i).getTime()?i:r.startOfDay?n:t.getClosestWorkTime({date:so(wr(i),1),dir:rt.PAST,task:e});let a=wr(t.getClosestWorkTime({date:i,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:a,dir:rt.FUTURE,task:e}):t.getClosestWorkTime({date:so(a,1),dir:rt.PAST,task:e})}function uo(e,t){let r={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},i=e.constraintType;if(!i||i==="asap"||i==="alap")return r;let n=pn(e,t);if(!n)return r;let a=s=>t.calculateEndDate({startDate:s,durationHours:e.durationHours,task:e}),o=s=>t.calculateEndDate({startDate:s,durationHours:-e.durationHours,task:e});switch(i){case"snet":return{earliestStart:n,latestStart:null,earliestEnd:a(n),latestEnd:null};case"snlt":return{earliestStart:null,latestStart:n,earliestEnd:null,latestEnd:a(n)};case"fnet":return{earliestStart:o(n),latestStart:null,earliestEnd:n,latestEnd:null};case"fnlt":return{earliestStart:null,latestStart:o(n),earliestEnd:null,latestEnd:n};case"mso":{let s=a(n);return{earliestStart:n,latestStart:n,earliestEnd:s,latestEnd:s}}case"mfo":{let s=o(n);return{earliestStart:s,latestStart:s,earliestEnd:n,latestEnd:n}}default:return r}}function fo(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function yn(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var U={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"};var Hu={TEXT:"text",DESCRIPTION:"description",DURATION:"duration",PROGRESS:"progress",COST:"cost",USED_COST:"used_cost",HH_WORK_TIME:"hhWorkTime",START_DATE:"start_date",END_DATE:"end_date",CONSTRAINT_TYPE:"constraint_type",CONSTRAINT_DATE:"constraint_date",CALENDAR_ID:"calendar_id",CUSTOM_ID:"custom_id",SUBCONTRACT_ID:"subcontractId",RESPONSABLES:"responsables",TAGS:"tags",CUSTOM_PREDECESSORS:"custom_predecessors",CUSTOM_SUCESSORS:"custom_sucessors"},ju={REAL_WORK:"real_work",REAL_COST:"real_cost",EXPECTED_PROGRESS:"expected_progress",EXPECTED_PROGRESS_BASE:"expected_progress_base",START_BASE:"start_base",END_BASE:"end_base",DURATION_BASE:"duration_base",COST_BASE:"cost_base",WORK_BASE:"work_base",CALENDAR_DURATION:"calendarDuration",IS_CRITICAL:"is_critical",EARLY_START:"earlyStart",EARLY_FINISH:"earlyFinish",LATE_START:"lateStart",LATE_FINISH:"lateFinish",FREE_SLACK:"freeSlack",TOTAL_SLACK:"totalSlack",CORRELATIVE_ID:"correlative_id",UNIQUE_CORRELATIVE_ID:"unique_correlative_id",PONDERATOR:"ponderator",STATUS:"status"},S={...Hu,...ju};var be={CREATE:"create",UPDATE:"update",DELETE:"delete"},ut={SELF_LINK:"self-link",CYCLE:"cycle",DUPLICATE:"duplicate",ACTIVITY_MISSING:"activity-missing",LINK_MISSING:"link-missing",HIERARCHY_LINK:"hierarchy-link"};var P={ACTIVITY_CLIPBOARD_CLEAR:"activity-clipboard-clear",ACTIVITY_COPY:"activity-copy",CALENDAR_RECONCILE:"calendar-reconcile",ACTIVITY_PASTE_COPIED:"activity-paste-copied",PERSISTENCE_ACKNOWLEDGE:"persistence-acknowledge",BASELINE_APPLY:"baseline-apply",PONDERATOR_CRITERION_SET:"ponderator-criterion-set",STATUS_CRITERIA_SET:"status-criteria-set",INLINE_EDIT:"inline-edit",DATES_BATCH:"dates-batch",BULK_EDIT:"bulk-edit",LINK_CREATE:"link-create",LINK_UPDATE:"link-update",LINK_DELETE:"link-delete",LINKS_BATCH:"links-batch",ACTIVITY_CREATE:"activity-create",ACTIVITY_DELETE:"activity-delete",ACTIVITY_MOVE:"activity-move",ACTIVITY_INDENT:"activity-indent",ACTIVITY_OUTDENT:"activity-outdent",ACTIVITY_SET_PROGRESS:"activity-set-progress",SELECTION_TOGGLE:"selection-toggle",SELECTION_REPLACE:"selection-replace",VISIBILITY_SET:"visibility-set",FILTER_SET:"filter-set",SORT_SET:"sort-set",SIR_SYNC:"sir-sync",ACTIVITY_LOOKAHEAD_SYNC:"activity-lookahead-sync"},Fr="activity-batch",tt=be,po=Object.values(P);function gt(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isActiveVersion)??null}var lt={NAME:"name",DESCRIPTION:"description",DURATION_DAYS:"durationDays",PROGRESS:"progress",COST:"cost",USED_COST:"usedCost",WORK_HOURS:"workHours",START_DATE:"startDate",END_DATE:"endDate",CONSTRAINT_TYPE:"constraintType",CONSTRAINT_DATE:"constraintDate",CALENDAR_ID:"calendarId",CUSTOM_ID:"customId",SUBCONTRACT_ID:"subcontractId",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds"},sr={START:"start",END:"end"},fe={FINISH_TO_START:"finish-to-start",START_TO_START:"start-to-start",FINISH_TO_FINISH:"finish-to-finish",START_TO_FINISH:"start-to-finish"},Ne={CREATE:"create",UPDATE:"update",REMOVE:"remove"};var Vu={[lt.NAME]:S.TEXT,[lt.DESCRIPTION]:S.DESCRIPTION,[lt.DURATION_DAYS]:S.DURATION,[lt.PROGRESS]:S.PROGRESS,[lt.COST]:S.COST,[lt.USED_COST]:S.USED_COST,[lt.WORK_HOURS]:S.HH_WORK_TIME,[lt.START_DATE]:S.START_DATE,[lt.END_DATE]:S.END_DATE,[lt.CONSTRAINT_TYPE]:S.CONSTRAINT_TYPE,[lt.CONSTRAINT_DATE]:S.CONSTRAINT_DATE,[lt.CALENDAR_ID]:S.CALENDAR_ID,[lt.CUSTOM_ID]:S.CUSTOM_ID,[lt.SUBCONTRACT_ID]:S.SUBCONTRACT_ID,[lt.RESPONSABLE_IDS]:S.RESPONSABLES,[lt.TAG_IDS]:S.TAGS};function hn(e,t){return{activityId:e,column:Vu[t.field],newValue:t.value}}var Ku={[fe.FINISH_TO_START]:U.FINISH_TO_START,[fe.START_TO_START]:U.START_TO_START,[fe.FINISH_TO_FINISH]:U.FINISH_TO_FINISH,[fe.START_TO_FINISH]:U.START_TO_FINISH};function cr(e){return Ku[e]}function Yu(e){return e.kind===Ne.CREATE?{kind:tt.CREATE,source:e.sourceId,target:e.targetId,type:cr(e.relationship),...e.lagDays===void 0?{}:{lag:e.lagDays},...e.linkId===void 0?{}:{linkId:e.linkId}}:e.kind===Ne.UPDATE?{kind:tt.UPDATE,linkId:e.linkId,...e.relationship===void 0?{}:{type:cr(e.relationship)},...e.lagDays===void 0?{}:{lag:e.lagDays}}:e.kind===Ne.REMOVE?{kind:tt.DELETE,linkId:e.linkId}:e}function Gu(e){return e===sr.START?S.START_DATE:e===sr.END?S.END_DATE:e}function $u(e){return{kind:Fr,mode:e.mode,items:e.items,links:e.links.map(t=>({source:t.source,target:t.target,type:cr(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}})),...e.eventSource===void 0?{}:{eventSource:e.eventSource}}}function zu(e){return{get:t=>e.getActivityView(t),list:()=>e.getAllActivitiesView(),ids:()=>e.getAllIds(),forEachId:t=>e.forEachActivityId(t),property:(t,r)=>e.getProperty(t,r),children:t=>e.getChildrenView(t),childIds:t=>e.getChildrenIds(t),hasChildren:t=>e.hasChild(t),indentTargetParentIds:t=>e.getIndentTargetParentIds(t),isCustomIdInUse:(t,r)=>e.isCustomIdInUse(t,r??null),create:(t,r)=>e.dispatch({...t,kind:P.ACTIVITY_CREATE},r),applyBatch:(t,r)=>e.applyActivityBatch($u(t),r),editInline:(t,r,i)=>e.dispatch({...hn(t,r),kind:P.INLINE_EDIT},i),applyDragBatch:(t,r)=>e.dispatch({kind:P.DATES_BATCH,edits:t.map(i=>({activityId:i.activityId,column:Gu(i.edge),newValue:i.value}))},r),editFields:(t,r)=>e.dispatch({kind:P.BULK_EDIT,edits:t.map(i=>hn(i.activityId,i))},r),remove:(t,r={})=>e.dispatch({...r,kind:P.ACTIVITY_DELETE,activityIds:t}),move:(t,r)=>e.dispatch({...t,kind:P.ACTIVITY_MOVE},r),indent:(t,r={})=>e.dispatch({...r,kind:P.ACTIVITY_INDENT,activityIds:t}),outdent:(t,r={})=>e.dispatch({...r,kind:P.ACTIVITY_OUTDENT,activityIds:t}),setProgress:(t,r,i={})=>e.dispatch({...i,kind:P.ACTIVITY_SET_PROGRESS,activityId:t,newValue:r}),copy:(t={})=>e.dispatch({...t,kind:P.ACTIVITY_COPY}),paste:(t,r={})=>e.dispatch({...r,kind:P.ACTIVITY_PASTE_COPIED,destination:{afterSiblingId:t}}),clearClipboard:(t={})=>e.dispatch({...t,kind:P.ACTIVITY_CLIPBOARD_CLEAR}),lookaheadSync:t=>e.dispatch({...t,kind:P.ACTIVITY_LOOKAHEAD_SYNC}),createDateGesturePreview:t=>e.createDateGesturePreview(t)}}function qu(e){return{get:t=>e.getLinkView(t),list:()=>e.getAllLinksView(),forActivity:t=>e.getLinksForActivityView(t),create:(t,r)=>e.dispatch({kind:P.LINK_CREATE,source:t.sourceId,target:t.targetId,type:cr(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}},r),update:(t,r,i)=>e.dispatch({kind:P.LINK_UPDATE,linkId:t,...r.relationship===void 0?{}:{type:cr(r.relationship)},...r.lagDays===void 0?{}:{lag:r.lagDays}},i),remove:(t,r)=>e.dispatch({kind:P.LINK_DELETE,linkId:t},r),batch:(t,r)=>e.dispatch({kind:P.LINKS_BATCH,operations:t.map(Yu)},r)}}function yo(e){let t=(r,i)=>e.dispatch({kind:P.BASELINE_APPLY,points:r},i);return{activities:zu(e),links:qu(e),calendars:{get:r=>e.getCalendar(r),list:()=>e.getAllCalendars(),listBase:()=>e.getBaseCalendars(),projectWorkHours:()=>e.getProjectWorkHours(),reconcile:r=>e.dispatch({kind:P.CALENDAR_RECONCILE},r)},selection:{ids:()=>e.getSelectedActivityIds(),toggle:({checked:r,...i})=>e.dispatch({...i,kind:P.SELECTION_TOGGLE,isChecked:r}),replace:(r,i={})=>e.dispatch({...i,kind:P.SELECTION_REPLACE,activityIds:r})},view:{hiddenActivityIds:()=>e.getHiddenActivityIds(),visibleActivityIds:()=>e.getVisibleActivityIds(),visualOrderIds:()=>e.getVisualOrderIds(),filter:()=>e.getActiveFilter(),setFilter:r=>e.dispatch({...r,kind:P.FILTER_SET}),order:()=>e.getActiveOrder(),setOrder:(r,i={})=>e.dispatch({...i,kind:P.SORT_SET,rules:r}),setVisibility:(r,i={})=>e.dispatch({...i,kind:P.VISIBILITY_SET,visibleIds:r}),setStatusCriteria:(r,i)=>e.dispatch({kind:P.STATUS_CRITERIA_SET,criteria:r},i)},baselines:{refresh:t,setVisibility:t,setPonderatorCriterion:(r,i)=>e.dispatch({kind:P.PONDERATOR_CRITERION_SET,criterion:r},i),activeFor:r=>gt(r)},impactRequests:{sync:r=>e.dispatch({...r,kind:P.SIR_SYNC})},persistence:{hasChanges:()=>e.hasUnsavedChanges(),modifiedActivities:()=>e.getModifiedActivities(),modifiedActivityFields:()=>e.getModifiedActivityFields(),newActivities:()=>e.getNewActivities(),deletedActivities:()=>e.getDeletedActivitiesSinceLastSave(),modifiedLinks:()=>e.getModifiedLinks(),newLinks:()=>e.getNewLinks(),deletedLinks:()=>e.getDeletedLinksSinceLastSave(),captureHistoryBoundary:()=>e.capturePersistenceHistoryBoundary(),readSnapshot:()=>({activities:e.getAllActivitiesView(),links:e.getAllLinksView(),historyBoundary:e.capturePersistenceHistoryBoundary()}),acknowledge:r=>e.dispatch({kind:P.PERSISTENCE_ACKNOWLEDGE,checkpoint:r})},history:{undo:r=>e.undo(r),redo:r=>e.redo(r),canUndo:()=>e.canUndo(),canRedo:()=>e.canRedo(),clear:()=>e.clearHistory(),depth:()=>e.undoDepth()},projection:{changeSetFrom:r=>e.createProjectionChangeSetFrom(r)},criticalPath:{get ready(){return e.criticalPathReady},recompute:()=>e.recomputeCriticalPath(),isSettled:()=>e.isCriticalPathSettled(),whenSettled:()=>e.whenCriticalPathSettled()},diagnostics:{auditEffectiveGraph:()=>e.auditEffectiveGraph(),revision:()=>e.getScheduleRevision(),canonicalDigest:()=>e.getCanonicalDigest()}}}var Tt=class{items=[];head=0;enqueue(t){this.items.push(t)}dequeue(){if(this.head>=this.items.length)return;let t=this.items[this.head];return this.head+=1,t}peek(){if(!(this.head>=this.items.length))return this.items[this.head]}get size(){return this.items.length-this.head}isEmpty(){return this.head>=this.items.length}};var xr=e=>String(e);function ho(e){let{clickedId:t,isChecked:r,currentSelection:i,hierarchy:n,isFrozen:a,exists:o,autoCheckParents:s}=e,c=xr(t),l=new Set([...i].map(String)),d=new Set(l),u=Ju(c,n).filter(o),f=u.filter(y=>!a(y)),p=r&&f.length<u.length;r&&!p?d.add(c):d.delete(c);for(let y of f)r?d.add(y):d.delete(y);return p||Xu({id:c,isChecked:r,autoCheckParents:s,hierarchy:n,isFrozen:a,exists:o,next:d}),{nextSelection:d,changed:Qu(l,d),parentBlocked:p}}function Ju(e,t){let r=[],i=new Tt;i.enqueue(e);let n=new Set([e]);for(;!i.isEmpty();){let a=i.dequeue();for(let o of t.getChildrenIds(a)){let s=xr(o);n.has(s)||(n.add(s),r.push(s),i.enqueue(s))}}return r}function Xu(e){let{id:t,isChecked:r,autoCheckParents:i,hierarchy:n,isFrozen:a,exists:o,next:s}=e,c=n.getParentId(t);for(;c!==null&&typeof c<"u";){let l=xr(c);if(a(l))return;let d=n.getChildrenIds(l).map(xr).filter(o),u=d.some(a),f=d.filter(g=>!a(g)),y=f.length>0&&f.every(g=>s.has(g))&&!u;if(r){if(!i||!y||s.has(l))return;s.add(l)}else{if(y||!s.has(l))return;s.delete(l)}c=n.getParentId(l)}}function Qu(e,t){let r=[],i=[];for(let n of t)e.has(n)||r.push(n);for(let n of e)t.has(n)||i.push(n);return{checked:r,unchecked:i}}function we(e){return(e.pendingRequestIds?.length??0)>0}var v={CANNOT_EDIT:"cannot_edit",PARSE_ERROR:"parse_error",INVALID:"invalid",CUSTOM_ID_DUPLICATE:"custom_id_duplicate",INVALID_LINK_TYPE:"invalid_link_type",INVALID_LINK_LAG:"invalid_link_lag",INVALID_VALUE:"invalid_value",NO_PIPELINE_FOR_COLUMN:"no_pipeline_for_column",ACTIVITY_NOT_FOUND:"activity_not_found",PARENT_NOT_FOUND:"parent_not_found",ACTIVITY_IDS_EMPTY:"activity_ids_empty",NO_ACTIVITY_SELECTION:"no_activity_selection",CLIPBOARD_EMPTY:"clipboard_empty",ACTIVITY_PASTE_INVARIANT_FAILED:"activity_paste_invariant_failed",ANCHOR_SIBLING_CONFLICT:"anchor_sibling_conflict",ANCHOR_SIBLING_NOT_FOUND:"anchor_sibling_not_found",ANCHOR_SIBLING_WRONG_PARENT:"anchor_sibling_wrong_parent",PARENT_FROZEN_BY_SIR:"parent_frozen_by_sir",CANNOT_MOVE_INTO_OWN_DESCENDANT:"cannot_move_into_own_descendant",INDENT_NO_ELIGIBLE_SIBLING:"indent_no_eligible_sibling",OUTDENT_ROOT_LEVEL_NOT_EDITABLE:"outdent_root_level_not_editable",HIERARCHY_CYCLE:"hierarchy_cycle",SANDBOX_PERSISTENCE_FORBIDDEN:"sandbox_persistence_forbidden",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var mo=(e,t)=>{let r=e.getActivity(t);return r!=null&&we(r)},go=(e,t,r)=>{let i=[],n=(a,o)=>{let s=t.isChecked(a);t.setChecked(a,o)&&i.push({activityId:a,checked:{before:s,after:o}})};for(let a of r.checked)n(a,!0);for(let a of r.unchecked)n(a,!1);return{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:i}};function Ao(e,t){let{adapter:r}=t,i=e.activityId;if(!r.getActivity(i))return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};let n=e.frozenIds?new Set(e.frozenIds):null,a=n?s=>n.has(s):s=>mo(r,s),o=ho({clickedId:i,isChecked:e.isChecked,currentSelection:new Set(r.checkedIds().map(String)),hierarchy:{getChildrenIds:s=>r.getChildren(s),getParentId:s=>{let c=r.getParentId(s);return!c||c==="0"?null:String(c)}},isFrozen:a,exists:s=>r.activityExists(s),autoCheckParents:e.autoCheckParents??!1});return{ok:!0,changes:go(e,r,o.changed)}}function Mr(e,t){let{adapter:r}=t,i=new Set(e.activityIds.map(String).filter(o=>r.activityExists(o)).filter(o=>!mo(r,o))),n=new Set(r.checkedIds().map(String)),a={checked:[...i].filter(o=>!n.has(o)),unchecked:[...n].filter(o=>!i.has(o))};return{ok:!0,changes:go(e,r,a)}}function Fe(e,t,r=e.getAllIds()){let i=[];for(let n of r){let a=String(n),o=t.has(a),s=e.isVisible(a);s!==o&&(e.setVisible(a,o),i.push({activityId:a,visible:{before:s,after:o}}))}return i}function Io(e,t){let{adapter:r}=t,i=new Set(e.visibleIds.map(String)),n=Fe(r,i);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:n}}}var Dt={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},vo={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var E={STRING:"string",NUMBER:"number",DATE:"date",ID_ARRAY:"id-array",ENUM:"enum",BOOLEAN:"boolean",REFERENCE:"reference"},B={NAME:"name",DESCRIPTION:"description",CUSTOM_ID:"customId",CORRELATIVE_ID:"correlativeId",UNIQUE_CORRELATIVE_ID:"uniqueCorrelativeId",PROGRESS:"progress",DURATION_DAYS:"durationDays",CALENDAR_DURATION:"calendarDuration",COST:"cost",USED_COST:"usedCost",REAL_COST:"realCost",WORK_HOURS:"workHours",REAL_WORK_HOURS:"realWorkHours",PONDERATOR:"ponderator",FREE_SLACK_DAYS:"freeSlackDays",TOTAL_SLACK_DAYS:"totalSlackDays",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",BASELINE_DURATION_DAYS:"baselineDurationDays",BASELINE_COST:"baselineCost",BASELINE_WORK_HOURS:"baselineWorkHours",EXPECTED_PROGRESS:"expectedProgress",START_DATE:"startDate",END_DATE:"endDate",CONSTRAINT_DATE:"constraintDate",BASELINE_START_DATE:"baselineStartDate",BASELINE_END_DATE:"baselineEndDate",EARLY_START:"earlyStart",EARLY_FINISH:"earlyFinish",LATE_START:"lateStart",LATE_FINISH:"lateFinish",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds",STATUS:"status",CONSTRAINT_TYPE:"constraintType",CALENDAR_ID:"calendarId",SUBCONTRACT_ID:"subcontractId",IS_CRITICAL:"isCritical"},w={INCLUDES:"includes",NOT_INCLUDES:"notIncludes",IS:"is",IS_NOT:"isNot",EQUALS:"equals",NOT_EQUALS:"notEquals",GREATER_THAN:"greaterThan",LESS_THAN:"lessThan",GREATER_OR_EQUAL:"greaterOrEqual",LESS_OR_EQUAL:"lessOrEqual",AFTER:"after",BEFORE:"before",BETWEEN:"between",SOME_OF:"someOf",NOT_SOME_OF:"notSomeOf"},Ur={AND:"and",OR:"or"};var Zu=2,tf=[mt.WAITING,mt.DONE,mt.DOING,mt.OVERDUE,mt.ADVANCEMENT],ef=[H.MFO,H.MSO,H.SNLT,H.SNET,H.ALAP,H.ASAP,H.FNET,H.FNLT],rf=1e3*60*60*24;function mn(e,t){return e===null||t<=0?null:e/t}function nf(e,t){let r=Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()),i=Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate());return Math.floor((i-r)/rf)+1}var af={[B.NAME]:{valueKind:E.STRING,extract:e=>e.name},[B.DESCRIPTION]:{valueKind:E.STRING,extract:e=>e.description},[B.CUSTOM_ID]:{valueKind:E.STRING,extract:e=>e.customId},[B.CORRELATIVE_ID]:{valueKind:E.NUMBER,extract:e=>e.correlativeId},[B.UNIQUE_CORRELATIVE_ID]:{valueKind:E.NUMBER,extract:e=>{let t=Number(e.uniqueCorrelativeId);return Number.isFinite(t)?t:null}},[B.PROGRESS]:{valueKind:E.NUMBER,extract:e=>e.progress},[B.DURATION_DAYS]:{valueKind:E.NUMBER,extract:(e,t)=>mn(e.durationHours,t.hoursPerDay)},[B.CALENDAR_DURATION]:{valueKind:E.NUMBER,extract:e=>e.type===Dt.MILESTONE?0:nf(e.startDate,e.endDate)},[B.COST]:{valueKind:E.NUMBER,extract:e=>e.cost},[B.USED_COST]:{valueKind:E.NUMBER,extract:e=>e.usedCost},[B.REAL_COST]:{valueKind:E.NUMBER,extract:e=>e.realCost},[B.WORK_HOURS]:{valueKind:E.NUMBER,extract:e=>e.workHours},[B.REAL_WORK_HOURS]:{valueKind:E.NUMBER,extract:e=>e.realWorkHours},[B.PONDERATOR]:{valueKind:E.NUMBER,extract:e=>e.ponderator},[B.FREE_SLACK_DAYS]:{valueKind:E.NUMBER,extract:(e,t)=>mn(e.freeSlackHours,t.hoursPerDay)},[B.TOTAL_SLACK_DAYS]:{valueKind:E.NUMBER,extract:(e,t)=>mn(e.criticalPath?.totalSlackHours??null,t.hoursPerDay)},[B.EXPECTED_PROGRESS_BASELINE]:{valueKind:E.NUMBER,equalityPrecision:Zu,extract:e=>e.expectedProgressBaseline},[B.EXPECTED_PROGRESS]:{valueKind:E.NUMBER,extract:e=>e.expectedProgress},[B.BASELINE_DURATION_DAYS]:{valueKind:E.NUMBER,extract:e=>e.baselineSnapshot?.durationDays??null},[B.BASELINE_COST]:{valueKind:E.NUMBER,extract:e=>e.baselineSnapshot?.cost??null},[B.BASELINE_WORK_HOURS]:{valueKind:E.NUMBER,extract:e=>e.baselineSnapshot?.workHours??null},[B.START_DATE]:{valueKind:E.DATE,extract:e=>e.startDate},[B.END_DATE]:{valueKind:E.DATE,extract:e=>e.endDate},[B.CONSTRAINT_DATE]:{valueKind:E.DATE,extract:e=>e.constraintDate},[B.BASELINE_START_DATE]:{valueKind:E.DATE,extract:e=>e.baselineSnapshot?.startDate??null},[B.BASELINE_END_DATE]:{valueKind:E.DATE,extract:e=>e.baselineSnapshot?.endDate??null},[B.EARLY_START]:{valueKind:E.DATE,extract:e=>e.criticalPath?.earlyStart??null},[B.EARLY_FINISH]:{valueKind:E.DATE,extract:e=>e.criticalPath?.earlyFinish??null},[B.LATE_START]:{valueKind:E.DATE,extract:e=>e.criticalPath?.lateStart??null},[B.LATE_FINISH]:{valueKind:E.DATE,extract:e=>e.criticalPath?.lateFinish??null},[B.RESPONSABLE_IDS]:{valueKind:E.ID_ARRAY,extract:e=>e.responsableIds},[B.TAG_IDS]:{valueKind:E.ID_ARRAY,extract:e=>e.tagIds},[B.STATUS]:{valueKind:E.ENUM,order:tf,extract:e=>e.status},[B.CONSTRAINT_TYPE]:{valueKind:E.ENUM,order:ef,extract:e=>e.constraintType},[B.CALENDAR_ID]:{valueKind:E.REFERENCE,extract:e=>e.calendarId===null?null:String(e.calendarId)},[B.SUBCONTRACT_ID]:{valueKind:E.REFERENCE,extract:e=>e.subcontractId===null?null:String(e.subcontractId)},[B.IS_CRITICAL]:{valueKind:E.BOOLEAN,extract:e=>e.isCritical}};function Xt(e){return af[e]??null}function gn(e){return e instanceof Date?e:typeof e=="string"||typeof e=="number"?new Date(e):new Date(Number.NaN)}function jt(e){return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())}function of(e,t,r){let i=e===null;return r===w.INCLUDES?!i&&String(e).toLowerCase().includes(t.toLowerCase()):r===w.NOT_INCLUDES?i||!String(e).toLowerCase().includes(t.toLowerCase()):r===w.IS?!i&&String(e)===t:r===w.IS_NOT?i||String(e)!==t:!1}function sf(e,t,r,i){if(e===null||typeof e!="number")return r===w.NOT_EQUALS;let n=i===void 0?e:Number(e.toFixed(i));return r===w.EQUALS?n===t:r===w.NOT_EQUALS?n!==t:r===w.GREATER_THAN?e>t:r===w.LESS_THAN?e<t:r===w.GREATER_OR_EQUAL?e>=t:r===w.LESS_OR_EQUAL?e<=t:!1}function cf(e,t,r){return typeof e=="number"&&e>=t&&e<=r}function lf(e,t,r){if(!(e instanceof Date))return!1;let i=jt(e),n=jt(t);return r===w.AFTER?i>n:r===w.BEFORE?i<n:!1}function df(e,t,r){if(!(e instanceof Date))return!1;let i=jt(e);return i>=jt(t)&&i<=jt(r)}function uf(e,t,r){let n=(Array.isArray(e)?e:[]).some(a=>t.has(String(a)));return r===w.SOME_OF?n:r===w.NOT_SOME_OF?!n:!1}function ff(e,t,r){let i=e!==null&&t.has(String(e));return r===w.SOME_OF?i:r===w.NOT_SOME_OF?!i:!1}function Co(e){let t=Array.isArray(e)?e:[e];return new Set(t.map(r=>String(r)))}function So(e,t,r){let i=Xt(t.field);if(i===null)return!1;let n=i.extract(e,r),{operator:a}=t;return a===w.BETWEEN?i.valueKind===E.NUMBER?cf(n,Number(t.value),Number(t.valueTo)):i.valueKind===E.DATE?df(n,gn(t.value),gn(t.valueTo)):!1:i.valueKind===E.STRING?of(n,String(t.value),a):i.valueKind===E.NUMBER?sf(n,Number(t.value),a,i.equalityPrecision):i.valueKind===E.DATE?lf(n,gn(t.value),a):i.valueKind===E.ID_ARRAY?uf(n,Co(t.value),a):ff(n,Co(t.value),a)}function pf(e,t,r){return t.criteria.length===0?!0:t.logic===Ur.OR?t.criteria.some(i=>So(e,i,r)):t.criteria.every(i=>So(e,i,r))}function yf(e,t){let r=jt(e.startDate),i=jt(e.endDate),n=jt(t.start),a=jt(t.end),o=r>=n&&i<=a,s=r>=n&&r<=a,c=n>=r&&n<=i;return o||s||c}function An(e,t,r){let i=pf(e,t,r),n=t.dateRange,a=n===void 0||yf(e,n);return i&&a}function hf(e,t,r){let i=t(e);for(;i!==null&&!r.has(String(i));)r.add(String(i)),i=t(i)}function ko(e){let{activities:t,parentOf:r,filter:i,context:n}=e,a=new Set,o=[];for(let s of t)An(s,i,n)&&(a.add(String(s.id)),o.push(s.id));for(let s of o)hf(s,r,a);return a}function mf(e){let{activities:t,parentOf:r,filter:i,context:n}=e,a=new Set,o=new Map,s=new Map,c=new Map;for(let l of t){let d=String(l.id),u=r(d);s.set(d,u),c.set(d,c.get(d)??0),u!==null&&c.set(u,(c.get(u)??0)+1);let f=An(l,i,n);o.set(d,f?1:0),f&&a.add(d)}return{matchedIds:a,visibleReferenceCounts:o,parentIds:s,remainingChildren:c}}function gf(e){let{visibleReferenceCounts:t,parentIds:r,remainingChildren:i}=e,n=[];for(let a of r.keys())i.get(a)===0&&n.push(a);for(;n.length>0;){let a=n.pop();if(a===void 0)break;let o=r.get(a);if(o==null)continue;let s=t.get(a)??0;t.set(o,(t.get(o)??0)+s);let c=(i.get(o)??1)-1;i.set(o,c),c===0&&n.push(o)}}function Af(e){let t=new Set;for(let[r,i]of e)i>0&&t.add(r);return t}function Br(e){let t=mf(e);gf(t);let r=Af(t.visibleReferenceCounts);return{filter:e.filter,context:e.context,matchedIds:t.matchedIds,visibleIds:r,visibleReferenceCounts:t.visibleReferenceCounts}}function To(e,t,r){let i=new Set;for(let n of t){let a=String(n.id);i.add(a);let o=e.matchedIds.has(a),s=An(n,e.filter,e.context);if(o===s)continue;s?e.matchedIds.add(a):e.matchedIds.delete(a);let c=s?1:-1,l=a;for(;l!==null;){let d=e.visibleReferenceCounts.get(l)??0,u=d+c;e.visibleReferenceCounts.set(l,u);let f=d>0,p=u>0;f!==p&&(i.add(l),p?e.visibleIds.add(l):e.visibleIds.delete(l)),l=r(l)}}return i}function pe(e){return{hoursPerDay:e,locale:"en"}}var ft={UNKNOWN_FIELD:"unknown_field",UNKNOWN_OPERATOR:"unknown_operator",INVALID_VALUE:"invalid_value"},If={[E.STRING]:new Set([w.INCLUDES,w.NOT_INCLUDES,w.IS,w.IS_NOT]),[E.NUMBER]:new Set([w.EQUALS,w.NOT_EQUALS,w.GREATER_THAN,w.LESS_THAN,w.GREATER_OR_EQUAL,w.LESS_OR_EQUAL,w.BETWEEN]),[E.DATE]:new Set([w.AFTER,w.BEFORE,w.BETWEEN]),[E.ID_ARRAY]:new Set([w.SOME_OF,w.NOT_SOME_OF]),[E.ENUM]:new Set([w.SOME_OF,w.NOT_SOME_OF]),[E.BOOLEAN]:new Set([w.SOME_OF,w.NOT_SOME_OF]),[E.REFERENCE]:new Set([w.SOME_OF,w.NOT_SOME_OF])};function Do(e){if(e===void 0)return{ok:!0,dateRange:void 0};if(typeof e!="object"||e===null)return{ok:!1,reason:ft.INVALID_VALUE};let{start:t,end:r}=e;if(!(t instanceof Date)||!(r instanceof Date))return{ok:!1,reason:ft.INVALID_VALUE};let i=t.getTime(),n=r.getTime();return!Number.isFinite(i)||!Number.isFinite(n)||i>n?{ok:!1,reason:ft.INVALID_VALUE}:{ok:!0,dateRange:{start:new Date(i),end:new Date(n)}}}function _o(e){let t=Xt(e.field);if(t===null)return{ok:!1,reason:ft.UNKNOWN_FIELD};if(!If[t.valueKind].has(e.operator))return{ok:!1,reason:ft.UNKNOWN_OPERATOR};if(e.operator===w.BETWEEN)return vf(e,t.valueKind);if(t.valueKind===E.NUMBER){let i=In(e.value);return i===null?{ok:!1,reason:ft.INVALID_VALUE}:{ok:!0,criterion:{...e,value:i}}}if(t.valueKind===E.DATE){let i=vn(e.value);return i===null?{ok:!1,reason:ft.INVALID_VALUE}:{ok:!0,criterion:{...e,value:i}}}let r=Cf(e,t.valueKind);return r!==null?{ok:!1,reason:r}:t.valueKind===E.BOOLEAN?{ok:!0,criterion:{...e,value:[...new Set(e.value)]}}:t.valueKind===E.ID_ARRAY||t.valueKind===E.ENUM||t.valueKind===E.REFERENCE?{ok:!0,criterion:{...e,value:[...new Set(e.value.map(String))]}}:{ok:!0,criterion:e}}function vf(e,t){if(t===E.NUMBER){let r=In(e.value),i=In(e.valueTo);return r===null||i===null||r>i?{ok:!1,reason:ft.INVALID_VALUE}:{ok:!0,criterion:{...e,value:r,valueTo:i}}}if(t===E.DATE){let r=vn(e.value),i=vn(e.valueTo);return r===null||i===null||r.getTime()>i.getTime()?{ok:!1,reason:ft.INVALID_VALUE}:{ok:!0,criterion:{...e,value:r,valueTo:i}}}return{ok:!1,reason:ft.UNKNOWN_OPERATOR}}function Cf(e,t){let{value:r}=e;return t===E.BOOLEAN?Array.isArray(r)&&r.every(i=>typeof i=="boolean")?null:ft.INVALID_VALUE:t===E.ID_ARRAY||t===E.ENUM||t===E.REFERENCE?Array.isArray(r)&&r.every(i=>typeof i=="string"||typeof i=="number")?null:ft.INVALID_VALUE:Array.isArray(r)?ft.INVALID_VALUE:null}function In(e){if(typeof e=="string"&&e.trim()===""||typeof e!="string"&&typeof e!="number")return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function vn(e){let t;if(e instanceof Date)t=new Date(e.getTime());else if(typeof e=="string")t=new Date(e);else if(typeof e=="number")t=new Date(e);else return null;return Number.isFinite(t.getTime())?t:null}function O(e){return structuredClone(e)}function Eo(e){return e.criteria.length===0&&e.dateRange===void 0}function Sf(e,t,r){let i=e.getAllActivities();if(Eo(t))return{visibleIds:ko({activities:i,parentOf:a=>e.getParentId(a),filter:t,context:pe(r)}),projection:null};let n=Br({activities:i,parentOf:a=>e.getParentId(a),filter:t,context:pe(r)});return{visibleIds:n.visibleIds,projection:n}}function Ro(e,t){let{adapter:r,hoursPerDay:i}=t,n=[];for(let u of e.criteria){let f=_o(u);if(!f.ok)return{ok:!1,reason:f.reason};n.push(f.criterion)}let a=Do(e.dateRange);if(!a.ok)return{ok:!1,reason:a.reason};let o=O(a.dateRange===void 0?{criteria:n,logic:e.logic}:{criteria:n,logic:e.logic,dateRange:a.dateRange});r.setActiveFilter(Eo(o)?null:o);let{visibleIds:s,projection:c}=Sf(r,o,i);r.setFilterProjection(c);let l=Fe(r,s);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:l}}}var ye={ASCENDING:"asc",DESCENDING:"desc"};var x="0";function N(e){return e==null||e===0||e==="0"}function Qt(e){return N(e)?"0":String(e)}var Cn=Number.MAX_SAFE_INTEGER;function Rt(e,t){let r=lr(e,t),i=t.getOrderComparator?.()??null;return r.sort(i===null?Wr:(n,a)=>i(n,a)||Wr(n,a)),r.map(n=>String(n.id))}function Lo(e){let t=[],r=n=>{t.push(n);let a=Rt(String(n.id),e);for(let o of a){let s=e.getActivity(o);s&&r(s)}},i=Rt("0",e);for(let n of i){let a=e.getActivity(n);a&&r(a)}return t}function Oo(e,t,r){let i=r.getActivity(e);if(!i)return null;let n=bo(i),a=Rt(n,r),o=a.findIndex(s=>String(s)===String(e));if(o<=0)return null;for(let s=o-1;s>=0;s--){let c=a[s];if(c!==void 0&&!kf(t,c))return c}return null}function Sn(e,t){let r=t.getActivity(e);if(!r)return-1;let i=bo(r);return Rt(i,t).findIndex(a=>String(a)===String(e))}function lr(e,t){let r=String(e)==="0"?t.getRootIds?.()??t.getChildren("0"):t.getChildren(e),i=[];for(let n of r){let a=t.getActivity(n);a&&i.push(a)}return i}function Wr(e,t){let r=Po(e),i=Po(t);return r!==i?r-i:String(e.id).localeCompare(String(t.id))}function Po(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Cn}function bo(e){let t=e.parentId;return t===null?"0":t}function kf(e,t){return e.has(t)?!0:e.has(String(t))}function xe(e){let t=[],r=i=>{let n=Rt(i,e);n.length>1&&t.push({parentId:i,childIds:n});for(let a of n)r(a)};return r("0"),t}function kn(e,t){let r=[];for(let i of t){let n=Rt(i,e);n.length>1&&r.push({parentId:i,childIds:n})}return r}function Tf(e){return Xt(e.field)===null?ft.UNKNOWN_FIELD:e.direction!==ye.ASCENDING&&e.direction!==ye.DESCENDING?ft.UNKNOWN_OPERATOR:null}function No(e,t){let{adapter:r}=t;for(let a of e.rules){let o=Tf(a);if(o!==null)return{ok:!1,reason:o}}let i=e.rules.length===0?null:O({rules:e.rules});return r.setActiveOrder(i),{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],order:xe(r)}}}function wo(e,t){throw new Error(t)}function Fo(e,t){return()=>t()===e}var Tn=typeof window>"u",Df=!Tn&&typeof MessageChannel<"u";function it(){return Df?new Promise(e=>{let t=new MessageChannel;t.port1.onmessage=()=>{t.port1.close(),t.port2.close(),e()},t.port2.postMessage(null)}):Promise.resolve()}async function Hr(e,t){return performance.now()-e<vo.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await it(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function Me(e){return Tn||await it(),e()?{aborted:!1}:{aborted:!0}}function jr(e,t){let{inDegree:r,successors:i}=_f(e,t),n=Ef(r),a=Rf(n,r,i),o=a.length<e.length,s=o?Pf(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:o,cycleNodes:s}}function _f(e,t){let r=new Map,i=new Map;for(let n of e)r.set(n,0),i.set(n,[]);for(let n of t){let a=n.source,o=n.target;!r.has(a)||!r.has(o)||(i.get(a).push(o),r.set(o,(r.get(o)??0)+1))}return{inDegree:r,successors:i}}function Ef(e){let t=new Tt;for(let[r,i]of e)i===0&&t.enqueue(r);return t}function Rf(e,t,r){let i=[];for(;!e.isEmpty();){let n=e.dequeue();i.push(n);for(let a of r.get(n)??[]){let o=(t.get(a)??1)-1;t.set(a,o),o===0&&e.enqueue(a)}}return i}function Pf(e,t){let r=new Set(t);return e.filter(i=>!r.has(i))}var Vr=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=jr(t,r),this.cached)}};function xo(e,t){let r=[];for(let i of e)t.has(i)&&r.push(i);return r}var Dn={project:{alwaysSummary:!0,holdsConstraint:!1,carriesCustomId:!1,forcedDuration:null,ponderatorWeight:"recursive-leaf-sum",promotesToProjectOnFirstChild:!1},task:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:null,ponderatorWeight:"own-baseline",promotesToProjectOnFirstChild:!0},milestone:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:0,ponderatorWeight:"zero",promotesToProjectOnFirstChild:!0}};function Mo(e){return e==="project"||e==="task"||e==="milestone"}function wt(e,t){return t||Mo(e)&&Dn[e].alwaysSummary}function Vt(e){return e==="milestone"}function Zt(e){return Mo(e)&&Dn[e].promotesToProjectOnFirstChild}var _n="project",Ue="task";function dr(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function Kr(e,t){let r=t.getActivity(e);return r?wt(r.type,t.getChildren(e).length>0):!1}function Yr(e,t,r){let i=String(t),n=r.getActivity(e);for(;n?.parentId&&String(n.parentId)!=="0";){if(String(n.parentId)===i)return!0;n=r.getActivity(n.parentId)}return!1}function En(e,t,r){let i=Kr(e,r);return Kr(t,r)&&Yr(e,t,r)||i&&Yr(t,e,r)}function Wo(e,t){let r=[],i=[e];for(;i.length>0;){let n=i.pop(),a=t.getChildren(n);if(a.length===0){String(n)!==String(e)&&r.push(n);continue}for(let o of a)i.push(o)}return r}function Lf(e){let t=new Map;for(let r of e)Uo(t,String(r.source),r),Uo(t,String(r.target),r);return t}function Uo(e,t,r){let i=e.get(t);if(i){i.push(r);return}e.set(t,[r])}function Of(e,t,r,i){if(e.length<=1)return e;let n=new Set(e.map(String)),a=[];for(let o of e)bf(o,n,t,r,i)||a.push(o);return a.length>0?a:e}function bf(e,t,r,i,n){let a=String(e),o=r.getActivity(e);if(!o||o.autoScheduling===!1)return!1;let s=i.get(a)??[];for(let c of s)if(Nf(c,a,o,t,r,n))return!0;return!1}function Nf(e,t,r,i,n,a){if(wf(e)||!(a?String(e.source)===t:String(e.target)===t))return!1;let s=Ff(e,t);if(!i.has(String(s)))return!1;let c=n.getActivity(s);return!!(c?.autoScheduling!==!1&&c&&xf(e,r,c))}function wf(e){return e.source===e.target}function Ff(e,t){return String(e.source)===t?e.target:e.source}function xf(e,t,r){let i=e.lag??0,n=Math.abs(i);return String(e.target)===String(r.id)&&n<=r.durationHours||String(e.target)===String(t.id)&&n<=t.durationHours}function $r(e,t){let r=[],i=Lf(e),n=0;for(let a of e){let o=Kr(a.source,t),s=Kr(a.target,t);if(Mf(a,o,s,t))continue;if(!o&&!s){r.push(a);continue}let c=Bo(a.source,o,t,i,!0),l=Bo(a.target,s,t,i,!1);n=Kf(r,c,l,a,t,n,i)}return r}function Mf(e,t,r,i){return r&&Yr(e.source,e.target,i)||t&&Yr(e.target,e.source,i)}function Bo(e,t,r,i,n){return t?Of(Wo(e,r),r,i,n):[e]}function Uf(e,t,r){let i=Wo(e,t);if(i.length===0)return null;let n=null,a=null;for(let o of i){let s=r(o);if(!s)continue;(n===null||s.startDate<n)&&(n=s.startDate),(a===null||s.endDate>a)&&(a=s.endDate)}return n===null||a===null?null:{startDate:n,endDate:a}}function Gr(e,t){return Uf(e,t,r=>{let i=t.getActivity(r);return i?{startDate:i.startDate,endDate:i.endDate}:null})}function Bf(e,t,r){return e?t?r.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function Wf(e,t,r,i){if(!t)return 0;let n=i.getActivity(e);return!r||!n?-t.durationHours:-i.calculateDuration({startDate:r.startDate,endDate:n.endDate,task:t})}function Hf(e,t){let r=String(e);return(t.get(r)??[]).some(n=>String(n.target)===r)}function jf(e,t,r,i,n){if(Hf(e,n))return 0;let a=i.getActivity(e);return!t||!a||!r?0:i.calculateDuration({startDate:t,endDate:a.startDate,task:r})}function Vf(e,t){let r=t.getActivity(e.source),i=t.getActivity(e.target),n=Gr(e.source,t),a=Gr(e.target,t),o=e.type===U.START_TO_START||e.type===U.START_TO_FINISH,s=e.type===U.FINISH_TO_FINISH||e.type===U.START_TO_FINISH;return{source:r,sourceBounds:n,targetStart:a?.startDate??i?.startDate,userLag:e.lag??0,sourceEndpointIsStart:o,targetLag:s?-Bf(i,a,t):0,summarySourceId:e.type===U.START_TO_START&&n?e.source:void 0,finishAnchoredSummaryTargetId:s&&a?e.target:void 0}}function Kf(e,t,r,i,n,a,o){let s=Vf(i,n),{source:c,sourceBounds:l,targetStart:d,userLag:u}=s,{sourceEndpointIsStart:f,targetLag:p,summarySourceId:y,finishAnchoredSummaryTargetId:g}=s,C=a;for(let R of t){let A=f?Wf(R,c,l,n):0;for(let k of r){if(String(R)===String(k))continue;let m=jf(k,d,c,n,o);e.push(Yf(i,R,k,C,A,p,u+m,y,g??(m!==0&&p===0?i.target:void 0))),C+=1}}return C}function Yf(e,t,r,i,n,a,o,s,c){return{id:`virtual_${e.id}_${i}`,source:t,target:r,type:e.type,lag:e.lag,freeSlackHours:null,isCritical:!1,_sourceLag:n,_targetLag:a,_trueLag:o,...s===void 0?{}:{_summarySourceId:s},...c===void 0?{}:{_summaryTargetId:c}}}var zr=class{invalidate(){}get(t,r){return $r(t,r)}};function Gf(e){let t=new Map,r=i=>(t.has(i)||t.set(i,new Set),t.get(i));for(let i of e)r(i.source).add(i.id),r(i.target).add(i.id);return{neighbors:t}}function $f(e,t,r){let i=new Set,n=new Map,a=new Tt;for(a.enqueue(e);!a.isEmpty();){let o=a.dequeue(),s=String(o);if(i.has(s))continue;i.add(s);let c=r.neighbors.get(o);if(c)for(let l of c){let d=t.get(l);if(!d)continue;let u=`${d.source}-${d.target}-${d.type}`;n.has(u)||n.set(u,d);let f=String(d.source)===s?d.target:d.source;i.has(String(f))||a.enqueue(f)}}return Array.from(n.values())}function Ho(e,t){let r=new Map;for(let o of t)r.set(o.id,o);let i=Gf(t),n=$f(e,r,i),a=new Set([String(e)]);for(let o of n)a.add(String(o.source)),a.add(String(o.target));return{activityIds:a,links:n}}var jo=0,ur=100;function he(e){return e===0}function Vo(e,t,r){let i=r.type===U.FINISH_TO_START,n=r.type===U.FINISH_TO_FINISH;if(r._targetLag!==void 0)return{sourceLag:r._sourceLag??0,targetLag:r._targetLag,trueLag:r._trueLag??r.lag??0,isFS:i,isFF:n,isZeroDurationCase:!1};let a=r.lag??0;switch(r.type){case U.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case U.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case U.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case U.START_TO_FINISH:return{sourceLag:-e.durationHours,targetLag:-t.durationHours,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};default:return{sourceLag:0,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1}}}function zf(e,t,r){if(e._summarySourceId===void 0)return null;let i=r.getActivity(e._summarySourceId);if(!i)return null;let n=Gr(e._summarySourceId,r);return n?-r.calculateDuration({startDate:n.startDate,endDate:t.endDate,task:i}):null}function qf(e,t,r,i,n){let a=t.durationHours===0&&n;return{successorStart:i.getClosestWorkTime({date:e.endDate,dir:a?"past":"future",task:t}),link:r}}function Ko(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:o,isFS:s,isFF:c}=Vo(e,t,r),l=zf(r,e,i)??n,d=l+a+o;if(!(t.durationHours===0?d!==0:l!==0||a!==0||o!==0))return qf(e,t,r,i,s||c);let p=s?t:e,y=i.getClosestWorkTime({date:e.endDate,dir:"future",task:p});if(l!==0&&(y=i.calculateEndDate({startDate:y,durationHours:l,task:e})),a!==0&&(y=i.calculateEndDate({startDate:y,durationHours:a,task:t})),o!==0&&(y=i.calculateEndDate({startDate:y,durationHours:o,task:t})),t.durationHours===0){if(s||c)return{successorStart:i.getClosestWorkTime({date:y,dir:"past",task:t}),link:r};let g=new Date(Date.UTC(y.getUTCFullYear(),y.getUTCMonth(),y.getUTCDate()));return{successorStart:i.getClosestWorkTime({date:g,dir:"future",task:t}),link:r}}return{successorStart:i.getClosestWorkTime({date:y,dir:"future",task:t}),link:r}}function Yo(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:o}=Vo(t,e,r),s=i.getClosestWorkTime({date:e.startDate,dir:"past",task:e});return o!==0&&(s=i.calculateEndDate({startDate:s,durationHours:-o,task:e})),a!==0&&(s=i.calculateEndDate({startDate:s,durationHours:-a,task:e})),n!==0&&(s=i.calculateEndDate({startDate:s,durationHours:-n,task:t})),s}function Go(e,t,r){for(let i of e){let n=t.getActivity(i);if(!n)continue;let a=n.constraintType;if(!a||a===H.ASAP||a===H.ALAP)continue;let o=uo(n,t);!o.earliestStart&&!o.latestStart&&!o.earliestEnd&&!o.latestEnd||r.set(i,{activityId:i,startDate:n.startDate,endDate:n.endDate,drivingLinkId:null,kind:"asap",conflict:!1,earliestStart:o.earliestStart,latestStart:o.latestStart,earliestEnd:o.earliestEnd,latestEnd:o.latestEnd})}}function qr(e,t,r){let i={earliestStart:t.earliestStart??null,latestStart:t.latestStart??null,earliestEnd:t.earliestEnd??null,latestEnd:t.latestEnd??null},n=t.earliestSchedulingStart??t.latestSchedulingStart??null,a;n===null?a=yn(e.startDate,i):fo(n,i)?a=n:a=yn(n,i),t.startDate=a,t.endDate=r.calculateEndDate({startDate:a,durationHours:e.durationHours,task:e})}function $o(e,t){if(!e||!t)return new Date;let{constraintType:r,constraintDate:i}=e;if(!r||!i)return t;switch(r){case H.MSO:case H.MFO:return new Date(i);case H.SNET:case H.FNET:return i>t?new Date(i):t;case H.SNLT:case H.FNLT:return i<t?new Date(i):t;default:return t}}function Jf(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function zo(e,t,r){return Rn(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function Rn(e,t,r){return t.dragWithMultiple&&Jf(e,r)}async function qo(e,t,r,i,n,a){let o=new Map;for(let u of t){let f=String(u.target);o.has(f)||o.set(f,[]),o.get(f).push(u)}let s=u=>{let f=a.get(u);if(f?.startDate&&f.endDate)return{startDate:f.startDate,endDate:f.endDate};let p=r.getActivity(u);return p?{startDate:p.startDate,endDate:p.endDate}:{startDate:new Date,endDate:new Date}},c=r.getFlags(),l=i.draggedIds??[],d=performance.now();for(let u of e){let f=await Hr(d,n);if(f.aborted)return a;d=f.newSliceStart;let p=r.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||Xf(p,r))continue;let y=o.get(String(u))??[],g=null,C=null,R=!1;for(let F of y){let T=r.getActivity(F.source);if(!T)continue;let I=s(F.source),_=I.startDate.getTime()!==T.startDate.getTime()||I.endDate.getTime()!==T.endDate.getTime(),j={...T,startDate:I.startDate,endDate:I.endDate},W=zo(j,c,l),Z={...j,startDate:W.startDate,endDate:W.endDate},J=Rn(F.source,c,l)?{...F,lag:0}:F,ht=Ko(Z,p,J,r);(!g||ht.successorStart>g)&&(g=ht.successorStart,C=String(F.id),R=F._summaryTargetId!==void 0&&!_&&(F._targetLag===0||i.preventSummaryTargetPullback===!0))}g!==null&&R&&g<p.startDate&&(g=new Date(p.startDate));let k=a.get(u),m=k?{...k}:{activityId:u,startDate:p.startDate,endDate:p.endDate,drivingLinkId:null,kind:"asap",conflict:!1},L=m.earliestStart||m.latestStart||m.earliestEnd||m.latestEnd;if(!(!g&&!L)){if(g){let F=g;p.type===Dt.MILESTONE&&(F=$o(p,g)),m.drivingLinkId=C,m.startDate=F,m.endDate=r.calculateEndDate({startDate:F,durationHours:p.durationHours,task:p}),m.earliestSchedulingStart=F,m.earliestSchedulingEnd=m.endDate}else p.constraintType===H.MSO?m.earliestStart&&(m.startDate=m.earliestStart,m.endDate=m.earliestEnd??r.calculateEndDate({startDate:m.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===H.MFO&&m.latestStart&&(m.startDate=m.latestStart,m.endDate=m.latestEnd??r.calculateEndDate({startDate:m.latestStart,durationHours:p.durationHours,task:p}));qr(p,m,r),a.set(u,m)}}return a}function Xf(e,t){return wt(e.type,t.getChildren(e.id).length>0)}async function Jo(e,t,r,i,n,a){let o=new Map(r),s=i.getAllActivities(),c=s.length,l=[];for(let C of s)C.constraintType===H.ALAP&&l.push(C.id);if(l.length===0)return o;let d=new Map,u=new Map;for(let C of t){let R=String(C.source);d.has(R)||d.set(R,[]),d.get(R).push(C);let A=String(C.target);u.has(A)||u.set(A,[]),u.get(A).push(C)}let f=C=>{let R=o.get(C);if(R)return{startDate:R.startDate,endDate:R.endDate};let A=i.getActivity(C);return A?{startDate:A.startDate,endDate:A.endDate}:{startDate:new Date,endDate:new Date}},p=C=>!C.parentId||N(C.parentId)?i.getProjectEnd():f(C.parentId).endDate,y=(C,R)=>{let A=C,k=0;for(;A&&!N(A)&&k++<c+1;){if(String(A)===String(R))return!0;let m=i.getActivity(A);if(!m||!m.parentId)break;A=m.parentId}return!1},g=performance.now();for(let C of e){let R=await Hr(g,a);if(R.aborted)return o;g=R.newSliceStart;let A=i.getActivity(C);if(!A||A.constraintType!==H.ALAP||!A.autoScheduling||A.progress===100||wt(A.type,i.getChildren(C).length>0))continue;let k=p(A);if(!k)continue;let m=k,L=null,F=!1,T=d.get(String(C))??[];for(let Nt of T){if((Nt.lag??0)<0)continue;let Oe=i.getActivity(Nt.target);if(!Oe||Oe.autoScheduling===!1)continue;let oo=f(Nt.target),Lu={...Oe,startDate:oo.startDate,endDate:oo.endDate},Nr=Yo(Lu,A,Nt,i);Nr<m&&(m=Nr),(L===null||Nr<L)&&(L=Nr,F=A.parentId&&!N(A.parentId)?y(Nt.target,A.parentId):!1)}if(L!==null)if(F)m=L;else{let Nt=f(C).endDate,Oe=Nt.getTime()>k.getTime()?Nt:k;m=L<Oe?L:Oe}else m>k&&(m=k);let _=(u.get(String(C))??[]).some(Nt=>Nt.type===U.FINISH_TO_START||Nt.type===U.FINISH_TO_FINISH),j=new Date(Date.UTC(m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate())),W=()=>i.getClosestWorkTime({date:j,dir:"past",task:A}),Z=i.getClosestWorkTime({date:m,dir:"future",task:A}).getTime()===m.getTime(),J;A.durationHours===0&&L===null?J=_&&Z?W():i.getClosestWorkTime({date:m,dir:"past",task:A}):A.durationHours===0?_?J=W():J=i.getClosestWorkTime({date:m,dir:"future",task:A}):J=i.getClosestWorkTime({date:m,dir:"future",task:A});let ht=i.calculateEndDate({startDate:J,durationHours:-A.durationHours,task:A}),kt=o.get(C),ct=kt?{...kt}:{activityId:C,startDate:ht,endDate:J,drivingLinkId:null,kind:"alap",conflict:!1};ct.startDate=ht,ct.endDate=J,ct.drivingLinkId=null,ct.kind="alap";let Pe=ct.earliestSchedulingStart??null;ct.earliestSchedulingStart=null,ct.earliestSchedulingEnd=null;let Le=Pe!==null&&Pe.getTime()>ht.getTime()?Pe:ht;ct.latestSchedulingStart=Le,ct.latestSchedulingEnd=Le===ht?J:i.calculateEndDate({startDate:Le,durationHours:A.durationHours,task:A}),qr(A,ct,i),o.set(C,ct)}return o}var Be={warn(){},error(){}};function Wt(e){if(e.type==="milestone")return 0;let t=e.startDate?.getTime(),r=e.endDate?.getTime();return t==null||r==null||Number.isNaN(t)||Number.isNaN(r)?null:Math.floor((r-t)/864e5)+1}function fr(e,t){t.cancelled||t.updatedIds.length===0||e.batchUpdate(()=>{for(let r of t.updatedIds){let i=t.plans.get(r);if(!i)continue;let n=e.getLiveActivity(r);n&&(n.startDate=i.startDate,n.endDate=i.endDate,n.calendarDuration=Wt(n),e.updateActivity(r))}})}function Pn(e,t){let r=String(t.source),i=String(t.target);if(r===i)return!0;let n=new Map;for(let a of e){let o=String(a.source),s=String(a.target),c=n.get(o)??[];c.push(s),n.set(o,c)}return Qf(n,i,r)}function pr(e){let t=new Map,r=new Map;for(let a of e){let o=String(a.source),s=String(a.target),c=t.get(o)??[];c.push(s),t.set(o,c),r.set(o,r.get(o)??0),r.set(s,(r.get(s)??0)+1)}let i=new Tt;for(let[a,o]of r)o===0&&i.enqueue(a);let n=0;for(;!i.isEmpty();){let a=i.dequeue();n+=1;for(let o of t.get(a)??[]){let s=r.get(o)-1;r.set(o,s),s===0&&i.enqueue(o)}}return n!==r.size}function Qf(e,t,r){if(t===r)return!0;let i=new Set([t]),n=new Tt;for(n.enqueue(t);!n.isEmpty();){let a=n.dequeue(),o=e.get(a)??[];for(let s of o){if(s===r)return!0;i.has(s)||(i.add(s),n.enqueue(s))}}return!1}function Jr(e){let t=Zf(e);for(let r of t.adjacency.keys())t.records.has(r)||tp(r,t);return t.components}function Zf(e){let t=new Map,r=new Set;for(let i of e){let n=String(i.source),a=String(i.target),o=Xo(t,n);if(Xo(t,a),n===a){r.add(n);continue}o.push(a)}return{adjacency:t,selfLooped:r,records:new Map,componentStack:[],nextIndex:0,components:[]}}function Xo(e,t){let r=e.get(t);if(r)return r;let i=[];return e.set(t,i),i}function tp(e,t){let r=[];for(r.push({node:e,record:Qo(e,t),neighborCursor:0});r.length>0;){let i=r[r.length-1];if(i===void 0)break;let n=t.adjacency.get(i.node)??[];if(i.neighborCursor<n.length){let s=n[i.neighborCursor];if(i.neighborCursor+=1,s===void 0)continue;ep(i,s,r,t);continue}r.pop();let a=r[r.length-1];a&&i.record.lowLink<a.record.lowLink&&(a.record.lowLink=i.record.lowLink),i.record.lowLink===i.record.visitIndex&&rp(i.node,t)}}function ep(e,t,r,i){let n=i.records.get(t);if(!n){r.push({node:t,record:Qo(t,i),neighborCursor:0});return}n.onStack&&n.visitIndex<e.record.lowLink&&(e.record.lowLink=n.visitIndex)}function Qo(e,t){let r={visitIndex:t.nextIndex,lowLink:t.nextIndex,onStack:!0};return t.nextIndex+=1,t.records.set(e,r),t.componentStack.push({node:e,record:r}),r}function rp(e,t){let r=[];for(;;){let o=t.componentStack.pop();if(o===void 0||(o.record.onStack=!1,r.push(o.node),o.node===e))break}let i=r[0],n=r.length===1&&i!==void 0&&t.selfLooped.has(i);(r.length>1||n)&&t.components.push(r)}function yr(e,t,r){let i=r?new Ln(e,r):e;return $r([...t],i)}var Ln=class{constructor(t,r){this.base=t;for(let[i,n]of r.reparented){let a=String(i),o=n===null||N(n)?null:n,s=t.getActivity(i)?.parentId??null,c=s===null||N(s)?null:String(s),l=o===null?null:String(o);if(c!==l){if(this.reparented.set(a,o),c!==null){let d=this.movedOutByParent.get(c)??new Set;d.add(a),this.movedOutByParent.set(c,d)}if(l!==null){let d=this.movedInByParent.get(l)??[];d.push(i),this.movedInByParent.set(l,d)}}}}base;reparented=new Map;movedOutByParent=new Map;movedInByParent=new Map;withOverride(t){if(!t)return null;let r=this.reparented.get(String(t.id));return r===void 0?t:{...t,parentId:r}}getActivity(t){return this.withOverride(this.base.getActivity(t))}getLiveActivity(t){return this.withOverride(this.base.getLiveActivity(t))}getAllActivities(){return this.base.getAllActivities().map(t=>this.withOverride(t)??t)}getChildren(t){let r=String(t),i=this.movedOutByParent.get(r),n=this.base.getChildren(t),a=i?n.filter(s=>!i.has(String(s))):[...n],o=this.movedInByParent.get(r);return o&&a.push(...o),a}getParent(t){let r=this.reparented.get(String(t));return r===void 0?this.base.getParent(t):r===null?null:this.getActivity(r)}isChildOf(t,r){let i=String(r),n=new Set,a=this.getActivity(t);for(;a;){let o=a.parentId;if(o===null||N(o))return!1;let s=String(o);if(s===i)return!0;if(n.has(s))return!1;n.add(s),a=this.getActivity(o)}return!1}getAllLinks(){return this.base.getAllLinks()}getAllIds(){return this.base.getAllIds()}getLink(t){return this.base.getLink(t)}activityExists(t){return this.base.activityExists(t)}getOutgoingLinkIds(t){return this.base.getOutgoingLinkIds(t)}getIncomingLinkIds(t){return this.base.getIncomingLinkIds(t)}getClosestWorkTime(t){return this.base.getClosestWorkTime(t)}calculateEndDate(t){return this.base.calculateEndDate(t)}calculateDuration(t){return this.base.calculateDuration(t)}batchUpdate(t){this.base.batchUpdate(t)}updateActivity(t){this.base.updateActivity(t)}getFlags(){return this.base.getFlags()}getProjectEnd(){return this.base.getProjectEnd()}};function hr(e){let{port:t,currentLinks:r,proposedLinks:i,proposal:n}=e,a=yr(t,i,n);if(!pr(a))return{ok:!0};let o=yr(t,r),s=Zo(o),l=[...Zo(a)].filter(d=>!s.has(d));return l.length===0?{ok:!0}:{ok:!1,newlyCyclicActivityIds:l}}function Zo(e){let t=new Set;for(let r of Jr(e))for(let i of r)t.add(i);return t}function te(e,t){switch(e.kind){case be.CREATE:return ip(e,t);case be.UPDATE:return mr(e,t.port);case be.DELETE:return np(e,t)}}function Qr(e,t){if(e.length===0)return{applied:!0};let r=t.port.getAllLinks(),i=new Map,n=[];for(let l of r){let d=ts(l);i.has(d)||i.set(d,l.id),n.push({source:l.source,target:l.target})}let a=pr(n),o=null;for(let{operation:l,linkId:d}of e){if(String(l.source)===String(l.target)){o={applied:!1,rejected:ut.SELF_LINK};break}if(!t.port.getActivity(l.source)||!t.port.getActivity(l.target)){o={applied:!1,rejected:ut.ACTIVITY_MISSING};break}if(En(l.source,l.target,t.port)){o={applied:!1,rejected:ut.HIERARCHY_LINK};break}let u=ts(l),f=i.get(u);if(f!==void 0){o={applied:!1,rejected:ut.DUPLICATE,linkId:f};break}if(i.set(u,d),a&&Pn(n,{source:l.source,target:l.target}))return{applied:!1,rejected:ut.CYCLE};n.push({source:l.source,target:l.target})}if(!a&&pr(n))return{applied:!1,rejected:ut.CYCLE};if(o)return o;let s=[...r,...e.map(({operation:l,linkId:d})=>({id:d,source:l.source,target:l.target,type:l.type,lag:l.lag,freeSlackHours:null,isCritical:!1}))];if(!hr({port:t.port,currentLinks:r,proposedLinks:s}).ok)return{applied:!1,rejected:ut.CYCLE};for(let{operation:l,linkId:d}of e){let u=t.preserved?.get(d);t.port.addLink({id:d,source:l.source,target:l.target,type:l.type,lag:l.lag,freeSlackHours:null,isCritical:!1,...u?.ganttId===void 0?{}:{ganttId:u.ganttId},...u?.sectorId===void 0?{}:{sectorId:u.sectorId},...u?.proplannerId===void 0?{}:{proplannerId:u.proplannerId}})}return{applied:!0}}function ts(e){return JSON.stringify([String(e.source),String(e.target),e.type])}function ip(e,t){let{port:r}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:ut.SELF_LINK};let i=r.getActivity(e.source),n=r.getActivity(e.target);if(!i||!n)return{applied:!1,rejected:ut.ACTIVITY_MISSING};if(En(e.source,e.target,r))return{applied:!1,rejected:ut.HIERARCHY_LINK};let a=r.getAllLinks();for(let d of a)if(String(d.source)===String(e.source)&&String(d.target)===String(e.target)&&d.type===e.type)return{applied:!1,rejected:ut.DUPLICATE,linkId:d.id};let o=a.map(d=>({source:d.source,target:d.target}));if(Pn(o,{source:e.source,target:e.target}))return{applied:!1,rejected:ut.CYCLE};let s=(t.newLinkId??ap)(),c={id:s,source:e.source,target:e.target,type:e.type,lag:e.lag,freeSlackHours:null,isCritical:!1};return hr({port:r,currentLinks:a,proposedLinks:[...a,c]}).ok?(r.addLink(c),{applied:!0,linkId:s}):{applied:!1,rejected:ut.CYCLE}}function mr(e,t){return t.getLink(e.linkId)?(e.lag!==void 0&&t.setLinkField(e.linkId,"lag",e.lag),e.type!==void 0&&t.setLinkField(e.linkId,"type",e.type),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:ut.LINK_MISSING}}function np(e,t){let{port:r}=t;return r.getLink(e.linkId)?(r.removeLink(e.linkId),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:ut.LINK_MISSING}}var Xr=null;function ap(){return Xr===null&&(Xr=Date.now()),Xr+=1,String(Xr)}var es={[U.FINISH_TO_START]:"fs",[U.START_TO_START]:"ss",[U.FINISH_TO_FINISH]:"ff",[U.START_TO_FINISH]:"sf"},me={fs:U.FINISH_TO_START,ss:U.START_TO_START,ff:U.FINISH_TO_FINISH,sf:U.START_TO_FINISH},rs="fs";function is(e){if(e in me)return me[e]}var ns=";",as=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function Zr(e){let t=[],r=[],i=e.replace(/\s+/g,"");if(i.length===0)return{specs:t,errors:r};for(let n of i.split(ns)){if(n.length===0)continue;let a=op(n);a?t.push(a):r.push(n)}return{specs:t,errors:r}}function op(e){let t=e.toLowerCase(),r=as.exec(t);if(!r)return null;let[,i,n,a,o]=r,s=n?me[n]:me[rs],c=0;if(o!==void 0){let l=Number(o);if(Number.isNaN(l))return null;c=a==="-"?-l:l}return{correlativeId:i,type:s,lag:c}}function ei(e){let{targetActivityId:t,currentLinks:r,desiredSpecs:i}=e,n=[],a=new Map;for(let c of i){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=ti(l,c.type);a.has(d)||a.set(d,{source:l,type:c.type,lag:c.lag})}let o=new Map;for(let c of r)String(c.target)===String(t)&&o.set(ti(c.source,c.type),c);let s=[];for(let[c,l]of o)a.has(c)||s.push({kind:"delete",linkId:l.id});for(let[c,l]of a){let d=o.get(c);d&&d.lag!==l.lag&&s.push({kind:"update",linkId:d.id,lag:l.lag})}for(let[c,l]of a)o.has(c)||s.push({kind:"create",source:l.source,target:t,type:l.type,lag:l.lag});return{operations:s,unresolved:n}}function ti(e,t){return`${String(e)}::${t}`}function ri(e){let{sourceActivityId:t,currentLinks:r,desiredSpecs:i}=e,n=[],a=new Map;for(let c of i){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=ti(l,c.type);a.has(d)||a.set(d,{target:l,type:c.type,lag:c.lag})}let o=new Map;for(let c of r)String(c.source)===String(t)&&o.set(ti(c.target,c.type),c);let s=[];for(let[c,l]of o)a.has(c)||s.push({kind:"delete",linkId:l.id});for(let[c,l]of a){let d=o.get(c);d&&d.lag!==l.lag&&s.push({kind:"update",linkId:d.id,lag:l.lag})}for(let[c,l]of a)o.has(c)||s.push({kind:"create",source:t,target:l.target,type:l.type,lag:l.lag});return{operations:s,unresolved:n}}function ii(e){let t=Math.sign(e)*Math.round(Math.abs(e));return Object.is(t,-0)?0:t}function Pt(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var os={rawInputToConstraintDate(e,t){let r=new Date(e);return r.setUTCHours(0,0,0,0),r.getTime()===e.getTime()?t.getClosestWorkTime({direction:rt.FUTURE,date:e,unit:pt.HOUR}):t.isWorkTime(e,pt.HOUR)?e:r},computeLagBetweenTasks(e,t,r){return r.calculateDuration(e,t)}};function On(e,t,r){switch(r){case"0":return{sourceDate:e.endDate,targetDate:t.startDate};case"1":return{sourceDate:e.startDate,targetDate:t.startDate};case"2":return{sourceDate:e.endDate,targetDate:t.endDate};case"3":return{sourceDate:e.startDate,targetDate:t.endDate}}}var bn=os;var We=class{adapter;reporter;currentCalculationId=0;topoCache=new Vr;expandedLinksCache=new zr;constructor(t,r=Be){this.adapter=t,this.reporter=r}getCurrentCalculationId(){return this.currentCalculationId}invalidateTopoCache(){this.topoCache.invalidate()}invalidateExpandedLinksCache(){this.expandedLinksCache.invalidate()}invalidateAllCaches(){this.topoCache.invalidate(),this.expandedLinksCache.invalidate()}async schedule(t={}){let r=++this.currentCalculationId,i=Fo(r,()=>this.currentCalculationId),n={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{lp(this.adapter);let a=ee("schedule.total"),o=ee("schedule.expandParentLinks"),s=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(s,this.adapter);Kt(o);let l=c;if((await Me(i)).aborted)return{...n,cancelled:!0};let d=ee("schedule.scoping"),u=this.adapter.getAllIds(),f=dp(t,l,this.adapter),p=f.links,y=f.idSet;Kt(d);let g=ee("schedule.topologicalSort"),C=fp(this.topoCache,u,l,y);if(Kt(g),C.hasCycles)return Kt(a),{...n,cycles:[C.cycleNodes]};if((await Me(i)).aborted)return{...n,cancelled:!0};let R=ee("schedule.processConstraints"),A=new Map;if(Go(C.ordered,this.adapter,A),Kt(R),(await Me(i)).aborted)return{...n,cancelled:!0};let k=ee("schedule.asapPass"),m=await qo(C.ordered,p,this.adapter,t,i,A);if(Kt(k),(await Me(i)).aborted)return{...n,cancelled:!0};let L=ee("schedule.alapPass"),F=await Jo(C.reversed,p,m,this.adapter,t,i);if(Kt(L),(await Me(i)).aborted)return{...n,cancelled:!0};let T=ee("schedule.diff"),I=[];for(let[_,j]of F){let W=this.adapter.getActivity(_);if(!W)continue;let Z=W.startDate.getTime()!==j.startDate.getTime(),J=W.endDate.getTime()!==j.endDate.getTime();(Z||J)&&I.push(_)}return Kt(T),Kt(a),{plans:F,updatedIds:I,cycles:[],cancelled:!1}}catch(a){return this.reporter.error("[AutoScheduler] Error during scheduling",a),n}}},sp=!1;function cp(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:sp}function ee(e){return{name:e,startedAt:performance.now()}}function lp(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function Kt(e){if(!cp())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function dp(e,t,r){let i=e.triggerId;if(i==null)return{idSet:null,links:t};let n=Ho(i,t);return up(n,t,r)}function up(e,t,r){let i=new Set(e.activityIds),n=new Set;for(let o of r.getAllActivities()){let s=String(o.id);o.constraintType===H.ALAP&&!i.has(s)&&(n.add(s),i.add(s))}if(n.size===0)return{idSet:i,links:e.links};let a=[...e.links];for(let o of t)(n.has(String(o.source))||n.has(String(o.target)))&&a.push(o);return{idSet:i,links:a}}function fp(e,t,r,i){let n=e.get(t,r);if(n.hasCycles){let o=i?Array.from(i):t;return jr(o,r)}if(!i)return n;let a=xo(n.ordered,i);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function ss(e,t,r){let i=t.getActivity(e);if(!i)return;let n=r?{...i,endDate:r.endDate}:i,a=t.calendarReader.getCalendar(String(i.calendarId));for(let o of t.getIncomingLinkIds(e)){let s=t.getLink(o);if(!s)continue;let c=t.getActivity(s.source);if(!c||c.constraintType==="alap"||Vt(i.type)&&(s.type===U.START_TO_FINISH||s.type===U.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=On(c,n,s.type),f=bn.computeLagBetweenTasks(d,u,a);f!==s.lag&&mr({kind:"update",linkId:s.id,lag:f},t)}}function cs(e,t){let r=t.getActivity(e);r&&Vt(r.type)&&(r.durationHours=0)}function ni(e){let t=0,r=!1;for(let i of e)i.ponderator>0&&(t+=i.ponderator/100*i.progress,r=!0);return r?t:null}function ls(e){return Number(e.toFixed(2))}function gr(e){for(let t of pp(e))us(t,e)}function ds(e,t){for(let r of e)us(r,t)}function pp(e){let t=new Set;e.forEachActivity((i,n)=>{e.getChildren(n).length>0&&t.add(n)});let r=new Map;for(let i of t)r.set(i,yp(i,e));return[...t].sort((i,n)=>(r.get(n)??0)-(r.get(i)??0))}function yp(e,t){let r=0,i=e;for(;i&&i!=="0"&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function us(e,t){let r=t.getChildren(e);if(r.length===0)return;let i=[];for(let n of r){let a=t.getActivity(n);a&&i.push({progress:Number(a.progress??0),ponderator:Number(a.ponderator??0)})}Nn(e,i,t)}function Nn(e,t,r){let i=r.getActivity(e);if(!i)return;let n=ni(t);if(n===null){let a=r.getProgressFallback(e);a!==null&&r.setActivityField(e,S.PROGRESS,a);return}r.getProgressFallback(e)===null&&r.setProgressFallback(e,Number(i.progress??0)),r.setActivityField(e,S.PROGRESS,ls(n))}function fs(e,t,r){let i=[e];for(;i.length>0;){let n=i.pop();if(n===void 0)continue;let a=r.getChildren(n);a.length!==0&&(r.setProgressFallback(n,t),i.push(...a))}}function Ct(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function He(e,t,r=!0,i={}){let n=t?Ar(e,t):vp(e),a=r?i.progressMode??"freeze-when-no-contribution":"skip";await hp(n,e,a,{recomputeRealWork:i.recomputeRealWork??!1})}function ai(e,t){ps(e,t,"skip")}async function hp(e,t,r,i={recomputeRealWork:!1}){let a=0;for(let o of e)ps(o,t,r,i.recomputeRealWork),a+=1,a%200===0&&await it()}function Ar(e,t){let r=new Set,i=new Map;for(let o of t)mp(o,e,r,i);if(r.size===0)return[];let n=Array.from(r),a=gp(n,i);return ys(n,a)}function mp(e,t,r,i){let n=t.getParentId(e);for(;n&&!N(n);){if(r.has(n))return;r.add(n);let a=t.getParentId(n);i.set(n,a),n=a}}function gp(e,t){let r=new Map;for(let i of e){if(r.has(i))continue;let n=[],a=new Set,o=i;for(;o&&!N(o)&&!r.has(o)&&!a.has(o);)n.push(o),a.add(o),o=t.get(o)??null;let s=o?r.get(o)??0:0;for(let c=n.length-1;c>=0;c-=1)s+=1,r.set(n[c],s)}return r}function Ap(e,t,r){let i=null,n=null,a=0,o=[];for(let s of e){let c=t.getActivity(s);if(!c)continue;let l=c.startDate.getTime(),d=c.endDate.getTime();(i===null||l<i)&&(i=l),(n===null||d>n)&&(n=d),r&&(a+=Ip(c,t.getChildren(s).length>0)),o.push({progress:Number(c.progress??0),ponderator:Number(c.ponderator??0)})}return{minStart:i,maxEnd:n,realWorkSum:a,weightedChildren:o}}function ps(e,t,r="freeze-when-no-contribution",i=!1){let n=t.getActivity(e);if(!n)return;let a=t.getChildren(e);if(a.length===0)return;let o=Ap(a,t,i);if(o.minStart===null||o.maxEnd===null)return;let s=String(n.calendarId??""),c=t.calendarReader.getCalendar(s),l=new Date(o.minStart),d=new Date(o.maxEnd),u=c.calculateDuration(l,d);t.setActivityField(e,"startDate",l),t.setActivityField(e,"endDate",d),t.setActivityField(e,"durationHours",u),r!=="skip"&&Nn(e,o.weightedChildren,t),i&&t.setActivityField(e,"realWorkHours",o.realWorkSum)}function Ip(e,t){return t?Number(e.realWorkHours)||0:Ct(e.workHours,e.progress)}function vp(e){let t=Cp(e),r=Sp(t,e);return ys(t,r)}function Cp(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function Sp(e,t){let r=new Map;for(let i of e)r.set(i,kp(i,t));return r}function kp(e,t){let r=0,i=e;for(;i&&!N(i)&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function ys(e,t){return[...e].sort((r,i)=>(t.get(i)??0)-(t.get(r)??0))}var hs={updateActivityDuration:cs,updateTaskTiming:Dp("updateTaskTiming"),adjustLinkLagOnTaskMove:ss,recordLastStartDate:Tp};function Tp(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function re(e,t,r,i){for(let n of t){let a=n in hs?hs[n]:void 0;if(!a){console.warn(`[replay post-processors] unknown: ${n} \u2014 skipping. Add an entry in POST_PROCESSORS if a fixture needs it.`);continue}a(e,r,i??null)}}function Dp(e){return()=>{console.debug(`[replay post-processors] ${e}: not yet ported to adapter \u2014 no-op.`)}}function M(e,t){return t!==void 0?{ok:!0,value:e,raw:t}:{ok:!0,value:e}}function V(e){return{ok:!1,reason:e}}function $(){return{valid:!0}}function nt(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function Y(){return{allowed:!0}}function X(e,t){return t!==void 0?{allowed:!1,reason:e,alertKey:t}:{allowed:!1,reason:e}}function G(e,t={}){return{patch:e,needsAutoSchedule:t.autoSchedule??!1,postProcessors:t.postProcessors??[],...t.cascadeMutations!==void 0?{cascadeMutations:t.cascadeMutations}:{},...t.trackingEvents!==void 0?{trackingEvents:t.trackingEvents}:{}}}var ms={targetField:"name",canEdit(){return Y()},parseInput(e){return typeof e!="string"?V("not_a_string"):M(e)},validate(){return $()},transform(e,t){return G({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var gs={targetField:"description",canEdit(){return Y()},parseInput(e){return typeof e!="string"?V("not_a_string"):M(e.trim())},validate(){return $()},transform(e,t){return G({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_description_entry"};function Ft(e){return e.constraintType??H.ASAP}var oi=100;function ie(e){return e.progress>=oi}function at(e,t){return wt(e.type,t.hasChildren(e.id))}function As(e){return e.progress>0}function Is(e){return e.hasLookaheadTasks}function ge(e,t){return Math.round(Math.ceil(e*t*60)/60)}var je=e=>({endDate:e});function ne(e,t){if(t){let r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=n=>Number(r.find(a=>a.type===n)?.value);return new Date(Date.UTC(i("year"),i("month")-1,i("day")))}return new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()))}function ci(e,t){if(!t||t==="UTC"){let f=new Date(e);return f.setUTCHours(23,59,0,0),f}let r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=f=>Number(r.find(p=>p.type===f)?.value),n=i("year"),a=i("month"),o=i("day"),s=Date.UTC(n,a-1,o,23,59,0,0),c=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(new Date(s)),l=f=>Number(c.find(p=>p.type===f)?.value),u=Date.UTC(l("year"),l("month")-1,l("day"),l("hour")===24?0:l("hour"),l("minute"),l("second"))-s;return new Date(s-u)}function _p(e,t){let r=ne(t,"UTC");for(;!e.isWorkTime(r,pt.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=ne(r,"UTC");return r}function wn(e,t){return e.getClosestWorkTime({direction:rt.FUTURE,date:t,unit:pt.HOUR})}function Fn(e,t){let r=_p(e,t),i=new Date(r);return i.setUTCDate(i.getUTCDate()+1),i.setUTCHours(0,0,0,0),e.getClosestWorkTime({direction:rt.PAST,date:i,unit:pt.HOUR})}var si=new Set(["snet","snlt","mso"]),xn=new Set(["fnet","fnlt","mfo"]),ae=new Set(["asap","alap"]),li="snet";function Yt(e,t,r){let i=ne(e,"UTC");if(!si.has(r)&&!xn.has(r))return i;let n=si.has(r)?wn(t,i):Fn(t,i),a=new Date(i);return a.setUTCHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),a}var oe=()=>({constraintType:li});var Ae=e=>({constraintDate:e}),vs=e=>({constraintDate:e});var Cs={UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var Ss={UNCHANGED:"unchanged",OUT_OF_RANGE:"out_of_range",NEGATIVE_DURATION:"negative_duration",NOT_WORKING_DAY:"not_working_day",BEFORE_PARENT_START:"before_parent_start",BEFORE_START_DATE:"before_start_date",BEFORE_DATE_ORIGIN:"before_date_origin",CONSTRAINT_VIOLATION:"constraint_violation",MISSING_ID:"missing_id",UNKNOWN_CALENDAR:"unknown_calendar"};function Ve(e,t,r){return co(e,t,r)}function Ke(e,t,r){return lo(e,t,r)}var Ts={targetField:"durationHours",canEdit(e,t){return ie(e)?X("completed","cant_edit_completed_activity"):at(e,t)?X("summary","summary_column_value"):Y()},parseInput(e,t,r){let i=parseFloat(String(e));return Number.isFinite(i)?M(ge(i,r.hoursPerDay)):V("not_a_number")},validate(e,t,r){return ks(r)?nt(Ss.NEGATIVE_DURATION):Ep(t,r)?nt("unchanged"):$()},transform(e,t,r){if(ks(t))return G({},{autoSchedule:!1,postProcessors:[]});let i=Rp(e,t,r),n=Pp(e,t,r,i.violated);return{...G(n,{autoSchedule:!0,postProcessors:[Cs.RECORD_LAST_START_DATE]}),...i.violated?{constraintWarning:Ke(i.constraintType,i.constraintDate,Ds(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function ks(e){return Math.sign(e)===-1}function Ep(e,t){return e===t}function Rp(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return{violated:!1};let n=e.constraintType;if(n!=="fnet"&&n!=="fnlt"&&n!=="mfo")return{violated:!1};let a=i.calculateEndDate(e.startDate,t);return Ve(n,e.constraintDate,a)}function Pp(e,t,r,i=!1){let n={};i&&Object.assign(n,oe(),Ae(e.startDate));let a=dr(e.durationHours,t);a&&(n.type=a),n.durationHours=t;let o=Ds(e,t,r);return o&&Object.assign(n,je(o)),n}function Ds(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateEndDate(e.startDate,t):null}var Ye=e=>({realWorkHours:e});var Lp=0,Op=oi,_s={targetField:"progress",canEdit(e,t){return Is(e)?X("has_lookahead_tasks","cant_edit_actvity_with_task"):at(e,t)?X("summary","summary_column_value"):Y()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?V("not_a_number"):M(t)},validate(e,t,r){return bp(r)?nt("out_of_range"):$()},transform(e,t,r){let i=he(t),n=e.progress!==t&&i,a=Np(t),o=xp(e,t,r.hierarchy),s={progress:t,autoScheduling:i,...Ye(o.get(e.id)??0)},c=a?wp(e,t,i,r.hierarchy,o):[],l=a?Up(e,t,r.hierarchy):[],d=c.length+l.length>0?[...c,...l]:void 0,u=[],f=a?Wp(e,t):void 0;return G(s,{autoSchedule:n,postProcessors:u,cascadeMutations:d,trackingEvents:f})},trackEvent:"activity_progress_entry"};function bp(e){return e<Lp||e>Op}function Np(e){return e===oi||he(e)}function wp(e,t,r,i,n){return i.getDescendantIds(e.id).map(o=>({activityId:o,fields:Fp(t,r,n.get(o)??0)}))}function Fp(e,t,r){return{progress:e,autoScheduling:t,...Ye(r)}}function xp(e,t,r){let i=new Map,n=o=>{let s=0;for(let c of r.getChildHhInfo(o)){let l=r.hasChildren(c.id)?n(c.id):Ct(c.workHours,t);i.set(c.id,l),s+=l}return s},a=r.hasChildren(e.id)?n(e.id):Ct(e.workHours,t);return i.set(e.id,a),i}function Mp(e,t){let r=[e.id,...t.getDescendantIds(e.id)],i=a=>t.getChildProgressInfo(a).some(o=>t.hasChildren(o.id)),n=a=>t.getAncestorIds(a).length;return r.filter(a=>i(String(a))).map(String).sort((a,o)=>n(o)-n(a))}function Up(e,t,r){let i=new Map;i.set(e.id,t);for(let o of r.getDescendantIds(e.id))i.set(o,t);let n=[...Mp(e,r),...r.getAncestorIds(e.id)],a=[];for(let o of n){let s=Bp(o,i,r);s!==null&&(i.set(o,s),a.push({activityId:o,fields:{progress:s}}))}return a}function Bp(e,t,r){let i=r.getChildProgressInfo(e).map(a=>({progress:t.has(a.id)?t.get(a.id):a.progress,ponderator:a.ponderator??0})),n=ni(i);return n===null?null:Number(n.toFixed(2))}function Wp(e,t){return[{name:"activity_progress_update_radio_button",properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var Es={targetField:"cost",canEdit(e,t){return at(e,t)?X("summary","summary_column_value"):Y()},parseInput(e){if(String(e).trim()==="")return M(0);let t=parseFloat(String(e));return Number.isNaN(t)?V("not_a_number"):M(t)},validate(){return $()},transform(e,t,r){let i=Hp(e,t,r.hierarchy);return G({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_budgeted_entry"};function Hp(e,t,r){let i=new Map;i.set(e.id,t);let n=[];for(let a of r.getAncestorIds(e.id)){let o=0;for(let s of r.getChildCostInfo(a))o+=i.has(s.id)?i.get(s.id):s.cost;i.set(a,o),n.push({activityId:a,fields:{cost:o}})}return n}var Rs={targetField:"usedCost",canEdit(e,t){return at(e,t)?X("summary","summary_column_value"):Y()},parseInput(e){if(String(e).trim()==="")return M(0);let t=parseFloat(String(e));return Number.isNaN(t)?V("not_a_number"):M(t)},validate(){return $()},transform(e,t,r){let i=jp(e,t,r.hierarchy);return G({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_spent_entry"};function jp(e,t,r){let i=new Map;i.set(e.id,t);let n=[];for(let a of r.getAncestorIds(e.id)){let o=0;for(let s of r.getChildUsedCostInfo(a))o+=i.has(s.id)?i.get(s.id):s.usedCost;i.set(a,o),n.push({activityId:a,fields:{usedCost:o}})}return n}var Ps={targetField:"workHours",canEdit(e,t){return at(e,t)?X("summary","summary_column_value"):Y()},parseInput(e){if(String(e).trim()==="")return M(0,e);let t=parseFloat(String(e));return Number.isNaN(t)?V("not_a_number"):M(t)},validate(){return $()},transform(e,t,r,i){let n=Ls(t,e.progress),a=String(i).trim()===""?[]:Vp(e,t,n,r.hierarchy);return G({workHours:t,...Ye(n)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function Ls(e,t){return Ct(e,t)}function Vp(e,t,r,i){let n=new Map,a=new Map;n.set(e.id,t),a.set(e.id,r);let o=[];for(let s of i.getAncestorIds(e.id)){let c=0,l=0;for(let d of i.getChildHhInfo(s)){let u=n.has(d.id)?n.get(d.id):d.workHours,f=a.has(d.id)?a.get(d.id):d.realWorkHours??Ls(d.workHours,d.progress);c+=u,l+=f}n.set(s,c),a.set(s,l),o.push({activityId:s,fields:{workHours:c,...Ye(l)}})}return o}function Ir(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function Mn(e,t){return e.getTime()<t.getTime()}function Ie(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var di=e=>({durationHours:e});var Kp="sir-apply",Os={targetField:"startDate",canEdit(e,t,r){return at(e,t)?X("summary","summary_column_value"):As(e)?r?.eventSource!==Kp?X("has_progress","cant_edit_activity_with_progress"):ie(e)?X("completed","cant_edit_completed_activity"):Ie(r.newValue)?Ir(e.startDate,r.newValue)?Y():r.newValue.getTime()>e.startDate.getTime()?X("sir_start_after_progress","sir_cant_move_start_after_progress"):Y():Y():Y()},parseInput(e,t,r){return Ie(e)?M(ne(e,"UTC")):V("invalid_date")},validate(e,t,r,i){if(Ir(t,r))return nt("unchanged");let n=Yp(e,r,i);return n||$()},transform(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)throw new Error("startDatePipeline: no calendar resolved (integrity)");let n=wn(i,t),a=e.type==="milestone",o=a?n:i.calculateEndDate(n,e.durationHours),s=n;return{...G({startDate:n,...je(o),...a?di(0):{},...oe(),...Ae(s)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:Gp(e,n,i)}},trackEvent:"activity_start_date_entry"};function Yp(e,t,r){let i=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!i)return null;let n=ne(i,"UTC");return t.getTime()<n.getTime()?nt("before_parent_start"):null}function Gp(e,t,r){let i=r.calculateEndDate(t,e.durationHours),n=or(Ft(e),t,i),a=Ve(Ft(e),e.constraintDate,n);if(a.violated)return Ke(a.constraintType,a.constraintDate,n)}var $p=99.999,Ns={targetField:"endDate",canEdit(e,t){return at(e,t)?X("summary","summary_column_value"):zp(e)?X("completed","cant_edit_completed_activity"):Y()},parseInput(e,t,r){if(!Ie(e))return V("invalid_date");let i=ne(e,"UTC"),n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(i,pt.DAY)?M(Fn(n,i)):M(n.getClosestWorkTime({direction:"past",date:i,unit:pt.HOUR})):M(i)},validate(e,t,r,i){if(Ir(e.endDate,r))return nt("unchanged");if(qp(r,e))return nt("before_date_origin");if(Jp(r,e))return nt("before_start_date");let n=Xp(r,e,i);return n||$()},transform(e,t,r){let i=Qp(e,t),n=Zp(e,t,r,!!i);return{...G(n,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...i?{constraintWarning:i}:{}}},trackEvent:"activity_end_date_entry"};function zp(e){return e.progress>=$p}function qp(e,t){return t.dateOrigin?Mn(e,t.dateOrigin):!1}function Jp(e,t){return Mn(e,t.startDate)}function Xp(e,t,r){let i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(e,pt.DAY)?null:nt("not_working_day"):null}function Qp(e,t){if(Ft(e)===H.MSO)return;let i=or(Ft(e),e.startDate,t),n=Ve(Ft(e),e.constraintDate,i);if(n.violated)return Ke(n.constraintType,n.constraintDate,i)}function Zp(e,t,r,i=!1){let n={};Vt(e.type)&&!i&&bs(e)?Object.assign(n,Ae(e.startDate)):(i||bs(e))&&Object.assign(n,oe(),Ae(e.startDate));let s=ty(e,t,r),c=dr(e.durationHours,s);return c&&(n.type=c),Object.assign(n,di(s)),n.endDate=t,n}function bs(e){return ae.has(Ft(e))}function ty(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateDuration(e.startDate,t):e.durationHours}var ey=new Set(Object.values(H)),ws={targetField:"constraintType",canEdit(e,t){return ie(e)?X("completed","cant_edit_completed_activity"):at(e,t)?X("summary","summary_column_value"):Y()},parseInput(e){let t=String(e).toLowerCase();return ry(t)?M(t):V("invalid_constraint_type")},validate(){return $()},transform(e,t,r){let i=iy(e,t,r);return G(i,{autoSchedule:!0})}};function ry(e){return ey.has(e)}function iy(e,t,r){let i=ay(e,t);return{constraintType:t,...vs(ny(e,t,i,r))}}function ny(e,t,r,i){if(e.type!=="milestone"||!r)return r;let n=i.calendars.getCalendar(String(e.calendarId));return n?Yt(r,n,t):r}function ay(e,t){return ae.has(t)?null:si.has(t)?e.startDate:xn.has(t)?e.endDate:e.constraintDate}var Fs={targetField:"constraintDate",canEdit(e,t){return ie(e)?X("completed","cant_edit_completed_activity"):at(e,t)?X("summary","summary_column_value"):Y()},parseInput(e){return Ie(e)?M(e):V("invalid_date")},validate(){return $()},transform(e,t,r){let i=xs(e)?li:Ft(e),n=r.calendars.getCalendar(e.calendarId);if(!n)throw new Error("constraintDatePipeline: no calendar resolved (integrity)");let a=Yt(t,n,i),o=oy(e,a);return G(o,{autoSchedule:!0})}};function oy(e,t){return{constraintDate:t,...xs(e)?oe():{}}}function xs(e){return ae.has(Ft(e))||!e.constraintType}var Ms={targetField:"calendarId",canEdit(){return Y()},parseInput(e){let t=String(e).trim();return sy(t)?V("empty_calendar"):M(t)},validate(e,t,r,i){return cy(e.calendarId,r)?nt("unchanged"):i.calendars.getCalendar(r)?$():nt("unknown_calendar")},transform(e,t,r){return G(ly(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function sy(e){return e===""}function cy(e,t){return e===t}function ly(e,t,r){let i={calendarId:t,assignedDefaultCalendar:!1},n=r.calendars.getCalendar(t);if(n){let a=e.durationHours===0,o=a?dy(e.startDate):e.startDate,s=n.getClosestWorkTime({date:o,direction:"future",unit:"hour"});if((!e.autoScheduling||a||n.getWorkHours(e.startDate).length===0)&&(i.startDate=s),!e.autoScheduling)return i;let c=i.startDate??e.startDate;Object.assign(i,je(n.calculateEndDate(c,e.durationHours)))}return i}function dy(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var Us={targetField:"customId",canEdit(e,t){return at(e,t)?X("summary","summary_column_value"):Y()},parseInput(e){if(e==null)return V("empty_custom_id");if(typeof e!="string")return V("not_a_string");let t=e.trim();return t.length===0?V("empty_custom_id"):t.length>20?V("exceeds_max_length"):M(t)},validate(){return $()},transform(e,t){return G({customId:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var Bs={targetField:"subcontractId",canEdit(){return Y()},parseInput(e){if(e==null)return M(null);if(typeof e=="string"){let t=e.trim();if(t.length===0)return M(null);let r=Number(t);return!Number.isFinite(r)||!Number.isInteger(r)?V("not_an_integer"):M(r)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?V("not_an_integer"):M(e):V("not_an_integer")},validate(){return $()},transform(e,t){return G({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function vr(e){if(e==null)return null;if(typeof e=="object"){if(!("id"in e))return null;let t=e.id;return t==null?null:String(t)}return String(e)}function ui(e){return e.some(t=>vr(t)===null)}var Ws={targetField:"responsableIds",canEdit(){return Y()},parseInput(e){return e==null?M([]):Array.isArray(e)?M(e):V("not_an_array")},validate(e,t,r){return ui(r)?nt("missing_id"):$()},transform(e,t){let r=t.map(vr).filter(i=>i!==null);return G({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var Hs={targetField:"tagIds",canEdit(){return Y()},parseInput(e){return e==null?M([]):Array.isArray(e)?M(e):V("not_an_array")},validate(e,t,r){return ui(r)?nt("missing_id"):$()},transform(e,t){let r=t.map(vr).filter(i=>i!==null);return G({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var uy=new Map([[S.TEXT,ms],[S.DESCRIPTION,gs],[S.DURATION,Ts],[S.PROGRESS,_s],[S.COST,Es],[S.USED_COST,Rs],[S.HH_WORK_TIME,Ps],[S.START_DATE,Os],[S.END_DATE,Ns],[S.CONSTRAINT_TYPE,ws],[S.CONSTRAINT_DATE,Fs],[S.CALENDAR_ID,Ms],[S.CUSTOM_ID,Us],[S.SUBCONTRACT_ID,Bs],[S.RESPONSABLES,Ws],[S.TAGS,Hs]]);function se(e){return uy.get(e)}var ot={APPEND:"append",REPLACE:"replace"},fi={SIR_AUTO_REJECT:"sir-auto-reject"},pi={DATE_CHANGED:"date_changed",ACTIVITY_DELETED:"activity_deleted"},yi={VIOLATION:"constraint_violation"},Gt={INIT:"init",UNDO:"undo",REDO:"redo"};function Ge(e,t){if(!t||t.type!=="constraint")return null;let r=t.data;return!r?.constraintType||!r.constraintDate?null:{kind:yi.VIOLATION,activityId:e,constraintType:r.constraintType,constraintDate:r.constraintDate,projectedDate:r.projectedDate??r.constraintDate,messageKey:t.messageKey}}var fy=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],js=new Set(fy);var b={ID:"id",PROPLANNER_ID:"proplannerId",PARENT:"parentId",NAME:"name",DESCRIPTION:"description",TYPE:"type",START_DATE:"startDate",END_DATE:"endDate",DURATION_HOURS:"durationHours",CONSTRAINT_TYPE:"constraintType",CONSTRAINT_DATE:"constraintDate",AUTO_SCHEDULING:"autoScheduling",CALENDAR_ID:"calendarId",ASSIGNED_DEFAULT_CALENDAR:"assignedDefaultCalendar",DATE_ORIGIN:"dateOrigin",PROGRESS:"progress",COST:"cost",USED_COST:"usedCost",REAL_COST:"realCost",WORK_HOURS:"workHours",REAL_WORK_HOURS:"realWorkHours",PONDERATOR:"ponderator",HAS_CUSTOM_PONDERATOR:"hasCustomPonderator",CORRELATIVE_ID:"correlativeId",UNIQUE_CORRELATIVE_ID:"uniqueCorrelativeId",CUSTOM_ID:"customId",SUBCONTRACT_ID:"subcontractId",IS_LOOKAHEAD:"isLookahead",HAS_LOOKAHEAD_TASKS:"hasLookaheadTasks",NEW_ACTIVITIES_ARRAY:"newActivityIds",HAS_NEW_ACTIVITIES:"hasNewActivities",IS_NEW_ACTIVITY:"isNewActivity",PENDING_REQUEST_IDS:"pendingRequestIds",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds",BASELINE_POINTS:"baselinePoints",BASELINE_SNAPSHOT:"baselineSnapshot",SUM_OF_DURATION_RECURSIVELY:"recursiveDurationHours",CALENDAR_DURATION:"calendarDuration",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath"},Cr={ID:"id",SOURCE:"source",TARGET:"target",TYPE:"type",LAG:"lag",FREE_SLACK_HOURS:"freeSlackHours",IS_CRITICAL:"isCritical",SOURCE_LAG:"_sourceLag",TARGET_LAG:"_targetLag",TRUE_LAG:"_trueLag",SUMMARY_SOURCE_ID:"_summarySourceId",SUMMARY_TARGET_ID:"_summaryTargetId",GANTT_ID:"ganttId",SECTOR_ID:"sectorId",PROPLANNER_ID:"proplannerId"};function st(e,t,r,i){e.setActivityFieldDynamic(t,r,i)}function Vs(e,t,r,i){e.setLinkFieldDynamic(t,r,i)}function $t(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:Ht(e.constraintDate),dateOrigin:Ht(e.dateOrigin),newActivityIds:[...e.newActivityIds],pendingRequestIds:[...e.pendingRequestIds],responsableIds:[...e.responsableIds],tagIds:[...e.tagIds],baselinePoints:e.baselinePoints.map(t=>({...t,startDate:Ht(t.startDate),endDate:Ht(t.endDate)})),baselineSnapshot:py(e.baselineSnapshot),criticalPath:yy(e.criticalPath)}}function Ht(e){return e===null?null:new Date(e)}function py(e){return e===null?null:{...e,startDate:Ht(e.startDate),endDate:Ht(e.endDate)}}function yy(e){return e===null?null:{...e,earlyStart:Ht(e.earlyStart),earlyFinish:Ht(e.earlyFinish),lateStart:Ht(e.lateStart),lateFinish:Ht(e.lateFinish)}}var Gs=200;function ce(e,t){let r=new Set([String(e)]);for(let i of t.cascadeMutations??[])r.add(String(i.activityId));return r}async function Q(e,t){let r=new Map,i=0;for(let n of t){i+=1,i%Gs===0&&await it();let a=e.getActivity(n);a&&r.set(n,et(a))}return r}function et(e){return $t(e)}function hi(e,t){let r=e.getActivity(t);return r?$t(r):null}function le(e,t,r){Ks(e,t,r.patch);for(let i of r.cascadeMutations??[])Ks(e,i.activityId,i.fields)}function Ks(e,t,r){for(let[i,n]of Object.entries(r)){if(!js.has(i))throw new Error(`applyFieldChanges: column write to non-writable field "${i}"`);st(e,t,i,n)}}async function mi(e,t,r,i){let n=[],a=0;for(let o of r){a+=1,a%Gs===0&&await it();let s=hy(e,t,o,i);s&&n.push(s)}return n}function hy(e,t,r,i){let n=e.getActivity(r);if(!n)return{id:r,kind:"deleted",after:null};let a=t.get(r);if(!a&&i?.has(r))return my(r,i.get(r),n);let o=Bn(a,n);return gy(o,i,r,n),a&&Object.keys(o).length===0?null:{id:r,kind:a?"updated":"created",fields:o,after:et(n)}}function my(e,t,r){return t===r.correlativeId?null:{id:e,kind:"updated",fields:{correlativeId:{before:t,after:r.correlativeId}},after:et(r)}}function gy(e,t,r,i){if(!t?.has(r)||Object.hasOwn(e,"correlativeId"))return;let n=t.get(r);n!==i.correlativeId&&(e.correlativeId={before:n,after:i.correlativeId})}function Bn(e,t){let r={},i=e??{},n=t,a=new Set([...Object.keys(i),...Object.keys(n)]);a.delete(b.CALENDAR_DURATION);for(let o of a)(Object.hasOwn(i,o)!==Object.hasOwn(n,o)||!Un(i[o],n[o]))&&(r[o]={before:Ys(i[o]),after:Ys(n[o])});return r}function Ys(e){return e===null||typeof e!="object"?e:O(e)}function Un(e,t){if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e==null||t==null)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((o,s)=>Un(o,t[s]));if(typeof e!="object"||typeof t!="object")return!1;let r=e,i=t,n=Object.keys(r),a=Object.keys(i);return n.length!==a.length?!1:n.every(o=>Object.hasOwn(i,o)&&Un(r[o],i[o]))}function gi(e,t,r){let i=new Set;i.add(e);for(let n of t)i.add(n);for(let n of r)i.add(n);return i}function Wn(e,t){let r=new Set;for(let i of e)r.add(String(i));for(let i of t)r.add(i);return r}function Ai(e,t,r,i,n){for(let a of t){if(r.has(a.activityId)||(n.add(a.activityId),i.has(a.activityId)))continue;let o=e.getActivity(a.activityId);if(!o)continue;let s=et(o);a.before!==void 0&&(s.correlativeId=a.before),i.set(a.activityId,s)}}var Ay=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function zt(e){if(e==null||e==="")throw new Error(`[parseFromBackend] expected a date string, got "${e}"`);if(e.includes("T")||e.endsWith("Z")){let s=new Date(e);if(Number.isNaN(s.getTime()))throw new Error(`[parseFromBackend] invalid ISO date "${e}"`);return s}let t=e.match(Ay);if(!t)throw new Error(`[parseFromBackend] unsupported date format "${e}" (expected "YYYY/MM/DD H:MM" or ISO)`);let[,r,i,n,a,o]=t;return new Date(Date.UTC(Number(r),Number(i)-1,Number(n),Number(a),Number(o)))}function $e(e,t,r,i){if(e.getTime()>r.getTime())return 0;if(t.getTime()<r.getTime()||e.getTime()===t.getTime())return 100;let n=i.calculateDuration(e,r),a=i.calculateDuration(e,t);return a===0?0:n*100/a}var Iy=e=>e.type==="project",vy=(e,t,r)=>{let i=e.calendarId,n=i!=null?r.calendarReader.getCalendar(String(i)):null;if(!n)return 0;let a=o=>o instanceof Date?o:zt(String(o));return $e(a(e.startDate),a(e.endDate),t,n)};function Cy(e,t,r){let i=[],n=(o,s)=>{let c=r.getActivity(o);c&&c.expectedProgress!==s&&(r.setActivityField(o,"expectedProgress",s),i.push(String(o)))},a=o=>{let s=r.getActivity(o);if(!s)return 0;if(!Iy(s)){let d=vy(s,t,r);return n(o,d),d}let c=0;for(let d of r.getChildren(o)){let u=a(d),f=r.getActivity(d),p=typeof f?.ponderator=="number"?f.ponderator:0;c+=u*p}let l=c/100;return n(o,l),l};for(let o of e)a(o);return i}function Ce(e,t){let r=[];e.forEachActivity((i,n)=>{i.parentId===null&&r.push(n)}),Cy(r,t,e)}var Sy=e=>e.type==="project",ky=e=>gt(e),Ty=(e,t,r,i)=>{let n=ky(e);if(!n)return 0;let a=(n.baseCalendarId!=null?r.getBaseCalendar(`${n.baseCalendarId}-base`):null)??(i?r.getBaseCalendar(i):null);return!a||!n.startDate||!n.endDate?0:$e(n.startDate,n.endDate,t,a)};function Hn(e,t,r,i=null){let n=[],a=(s,c)=>{let l=r.getActivity(s);l&&l.expectedProgressBaseline!==c&&(r.setActivityField(s,"expectedProgressBaseline",c),n.push(s))},o=s=>{let c=r.getActivity(s);if(!c)return 0;if(!Sy(c)){let u=Ty(c,t,r,i);return a(s,u),u}let l=0;for(let u of r.getChildrenIds(s)){let f=o(u),p=r.getActivity(u),y=typeof p?.ponderator=="number"?p.ponderator:0;l+=f*y}let d=l/100;return a(s,d),d};for(let s of e)o(s);return n}function ze(e,t,r=null){let i={getChildrenIds:a=>e.getChildren(String(a)).map(o=>String(o)),getActivity:a=>e.getActivity(a),setActivityField:(a,o,s)=>st(e,a,o,s),getBaseCalendar:a=>e.calendarReader.getCalendar(a)},n=[];return e.forEachActivity((a,o)=>{a.parentId===null&&n.push(o)}),Hn(n,t,i,r)}var jn=Jt.BASELINE;function Ii(e){return e===Jt.ACTUAL?Jt.ACTUAL:jn}var $s=e=>Math.round(e*100)/100;function Dy(e,t){return(t===Jt.BASELINE?e.expectedProgressBaseline:e.expectedProgress)??void 0}function _y(e,t){let r=$s(e),i=$s(t);return r>99.99?mt.DONE:i>r?mt.OVERDUE:e>0&&r>i?mt.ADVANCEMENT:e===0&&t===0?mt.WAITING:e>0&&r<i?mt.DOING:mt.WAITING}function qt(e,t){let r=[];return e.forEachActivity((i,n)=>{let a=typeof i.progress=="number"?i.progress:0,o=_y(a,Dy(i,t));i.status!==o&&(st(e,n,S.STATUS,o),r.push(n))}),r}function Vn(e){let t=e instanceof Date?new Date(e.getTime()):e&&typeof e=="object"&&typeof e.valueOf=="function"?new Date(e.valueOf()):new Date(e),r=(n,a)=>o=>o===void 0?t[n]():(t[a](o),i),i={__isMomentShim:!0,clone:()=>Vn(t),hours:r("getUTCHours","setUTCHours"),minutes:r("getUTCMinutes","setUTCMinutes"),seconds:r("getUTCSeconds","setUTCSeconds"),milliseconds:r("getUTCMilliseconds","setUTCMilliseconds"),valueOf:()=>t.getTime(),toDate:()=>new Date(t.getTime()),getTime:()=>t.getTime()};return i}Vn.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var Lt=Vn;function Ey(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function vi(e){return Ey(e)&&!isNaN(e.getTime())}function D(e,t,r,i){if(!vi(new Date(t)))throw new Error(`Invalid date argument for calculateEndDate method. Date: ${t}, Activity: ${JSON.stringify(i)}`);let n=t;return e.calculateEndDate({start_date:new Date(n),duration:r,unit:"hour",task:i})}function _t(e){if(!vi(new Date(e.dateBaseToCalculate)))throw new Error("Invalid date argument for getClosestWorkTime method");let{dateBaseToCalculate:t,activityCalendar:r,direction:i,activity:n}=e;return r.$gantt.getClosestWorkTime({date:new Date(t),dir:i,unit:"hour",task:n})}var Ry=e=>e?e.$level===1:!1,Py=e=>e.type==="project",Ly=e=>e.$level!==0,Oy=e=>e.type==="task",by=e=>e.type==="task"||e.type==="milestone",vt={byFirstLevel:Ry,filterByParentType:Py,avoidSubproject:Ly,byTaskType:Oy,byTaskTypeAndMilestone:by};var h=Object.freeze({MFO:"mfo",MSO:"mso",FNLT:"fnlt",FNET:"fnet",SNET:"snet",SNLT:"snlt",ALAP:"alap",ASAP:"asap"});var z=Object.freeze({FS:"fs",SS:"ss",FF:"ff",SF:"sf"});function Se(e){return{0:"fs",1:"ss",2:"ff",3:"sf"}[Number(e)]||"sf"}function zs(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:i,linkProperty:n}=e;try{let a=Ny({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let o=wy({gantt:t,subprojectsWithNoLinks:a}),s=Fy({gantt:t,childrenIds:o,linkProperty:n,getArrayOfLinkedActivities:xy,calculations:i});return new Set(s.map(c=>c.id))}catch(a){throw a}}function Ny(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(vt.filterByParentType).filter(i=>r.has(i.id)).map(i=>i.id)}function wy(e){let{gantt:t,subprojectsWithNoLinks:r}=e,i=new Set;for(let n of r)t.getChildren(n).filter(s=>{let c=t.getTask(s),l=vt.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(s=>i.add(s));return[...i]}function Fy(e){let{gantt:t,childrenIds:r,linkProperty:i,getArrayOfLinkedActivities:n,calculations:a}=e,o=[];for(let s of r){let c=t.getTask(s),l=c[i]||[];n({gantt:t,links:l,linkDirection:i==="$source"?"target":"source"}).every(f=>a.has(f))&&o.push(c)}return o}function xy(e){let{gantt:t,links:r,linkDirection:i}=e,n=[];for(let a of r){let o=t.getLink(a);if(!o){`${a}`;continue}let s=Number(o[i]);n.push(s)}return n}function qs({gantt:e,linkProperty:t,direction:r}){try{let i=My(e,t);if(r==="forward")return{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return Uy(i,e,t)}catch(i){throw console.log("Critical Path",i),i}}function My(e,t){return e.getTaskByTime().filter(vt.avoidSubproject).filter(vt.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function Uy(e,t,r){let i=[],n=new Set;return e.forEach(a=>{let o=Number(a.parent),s=t.getTask(o);s&&(s[r].length>0?n.add(a.id):s.constraint_type!=="fnlt"&&i.push(a))}),{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:n}}function Js({gantt:e,direction:t,linkProperty:r}){try{let i=By(e),n=new Set,a=new Set,o=new Set;t==="backward"&&jy(i).forEach(d=>{n.add(d.id)});let s=Wy(i,t,r),c=Hy(i,s);return s.forEach(l=>{a.add(l.id)}),c.forEach(l=>{o.add(l.id)}),{parentsWithFullProgress:n,pendingParentsWithNoLinks:a,pendingParentsWithLinks:o}}catch(i){throw i}}function By(e){return e.getTaskByTime().filter(vt.filterByParentType).filter(vt.avoidSubproject)}function Wy(e,t,r){return e.filter(i=>{let n=i[r];if(!Array.isArray(n))return!1;let a=n.length>0,o=i.constraint_type||"",s=o!=="fnlt";return t==="forward"?!a&&s&&o!=="snet":!a&&s})}function Hy(e,t){let r=new Set(t.map(i=>i.id));return e.filter(i=>!r.has(i.id))}function jy(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function Xs({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let i=new Set;return e.forEach(n=>{let a=t.getTask(n),o=Vy(r),s=Ky(r),c=a[o];if(!Array.isArray(c))return;Yy(t,c,s).forEach(d=>{i.add(d)})}),i}catch(i){throw i}}function Vy(e){return e==="forward"?"$source":"$target"}function Ky(e){return e==="forward"?"target":"source"}function Yy(e,t,r){return t.map(i=>{let a=e.getLink(i)[r];return Number(a)})}var Sr={identifySecondLevelActivities:zs,identifyInitialActivities:qs,identifyParentsWithAndWithoutLinks:Js,identifyForbiddenActivities:Xs};function Ci(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function Kn({linkType:e,lag:t,predecessorTime:r,activityCalendar:i,activity:n}){return e===z.FS&&t===0?_t({predecessorTime:r,activityCalendar:i,direction:"future",activity:n}):kr(r,e,i,n)}function Qs({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t);return{es:D(r,n,e,i),ef:n}}function Zs({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t),a=D(r,n,e,i);return{es:n,ef:a}}function kr(e,t,r,i){if(![z.FS,z.SS,z.FF].includes(t))return e;let a=[z.FS,z.SS].includes(t)?"future":"past";return _t({dateBaseToCalculate:e,activityCalendar:r,direction:a,activity:i})}var Yn=class{constructor(t,r,i,n){if(this.linkedActivitiesData=t,this.activity=r,this.gantt=i,this.linkCandidates=n,this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`)}calculate(){let t=this.calculateLinks(),r=Ci(t),i=this.activity.constraint_type;return i==="snet"?this.handleSNETConstraint(r):i==="fnlt"?this.handleFNLTConstraint(r):r}calculateLinks(){let t=[];for(let r of this.linkedActivitiesData){let i=r.linkType,n=Se(i),a=r.linkLag,o=r.es,s=r.ef,c=null;if(n==="ss")c=this.calculateSSLink({lag:a,predecessorEs:o});else if(n==="ff")c=this.calculateFFLink({lag:a,predecessorEf:s});else if(n==="fs")c=this.calculateFSLink({lag:a,predecessorEf:s});else if(n==="sf")c=this.calculateSFLink({lag:a,predecessorEs:o,predecessorEf:s});else continue;c&&(this.linkCandidates?.set(r.linkId,{targetId:String(this.activity.id),...c}),t.push(c))}return t}handleSNETConstraint(t){let r=Zs({duration:this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t&&t.ef>r.ef?t:r}handleFNLTConstraint(t){let r=Qs({duration:-this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t?t.ef>r.ef?r:t:r}calculateSSLink({lag:t,predecessorEs:r}){let i=Kn({linkType:"ss",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=D(this.activityCalendar,i,t,this.activity);t>0&&(n=kr(n,"ss",this.activityCalendar,this.activity));let a=D(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:a}}calculateFFLink({lag:t,predecessorEf:r}){let i=Kn({linkType:"ff",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=D(this.activityCalendar,i,t,this.activity),a=D(this.activityCalendar,n,-this.activity.duration,this.activity);return t>0&&(a=kr(a,"ff",this.activityCalendar,this.activity)),{es:a,ef:n}}calculateFSLink({lag:t,predecessorEf:r}){let i=r;t===0&&(i=_t({dateBaseToCalculate:r,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let n=D(this.activityCalendar,i,t,this.activity),a=D(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:a}}calculateSFLink({lag:t,predecessorEs:r}){let i=D(this.activityCalendar,r,t,this.activity),n=D(this.activityCalendar,i,-this.activity.duration,this.activity);return t>0&&(n=kr(n,"sf",this.activityCalendar,this.activity)),{es:n,ef:i}}},tc=Yn;var Gn=class{constructor(t){this.linkedActivitiesData=t.linksWithActivityData,this.activity=t.activity,this.gantt=t.gantt}calculate(){if(this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`);let t=[];for(let r of this.linkedActivitiesData){let i=Se(r.linkType);if(r.type==="task"&&Number(r.progress)>0||r.type==="project"&&Number(r.progress)===100)continue;let n=r.linkLag,a=r.ls,o=r.lf;if(i==="ss"){let s={lag:n,workTime:a,lsDataCalculation:-n,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSSLink(s);t.push({ls:c,lf:l})}if(i==="ff"){let s={lag:n,workTime:o,lsDataCalculation:-this.activity.duration,lfDataCalculation:-n},{ls:c,lf:l}=this.calculateFFLink(s);t.push({ls:c,lf:l})}if(i==="fs"){let s={lag:n,workTime:a,lsDataCalculation:-this.activity.duration,lfDataCalculation:-n},{ls:c,lf:l}=this.calculateFsLink(s);t.push({ls:c,lf:l})}if(i==="sf"){let s={lag:n,workTime:o,lsDataCalculation:-n,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSFLink(s);t.push({ls:c,lf:l})}}if(this.activity.constraint_type==="fnlt"){let r=this.getMinLfFromLinks(t),i=this.calculateSfRestrictionDates();return r?this.getMinLfFromLinks([i,r]):i}else{let r=this.getMinLfFromLinks(t);if(r===!1){let i=this.gantt.getSubtaskDates();return{ls:D(this.activityCalendar,i.end_date,-this.activity.duration,this.activity),lf:i.end_date}}return r}}calculateFFLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n}){let a=null,o=null;if(t===0)return a=D(this.activityCalendar,r,n,this.activity),o=D(this.activityCalendar,a,i,this.activity),{ls:o,lf:a};let s=r;return t>0&&(s=this.getLastWorkingHour(s,this.activityCalendar,"past")),a=D(this.activityCalendar,s,n,this.activity),o=D(this.activityCalendar,a,i,this.activity),{ls:o,lf:a}}calculateFsLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n,isMilestone:a=!1}){let o=null,s=null;if(t===0){let l=this.getLastWorkingHour(r,this.activityCalendar,"past");return o=D(this.activityCalendar,l,n,this.activity),o=this.getLastWorkingHour(o,this.activityCalendar,"past"),s=D(this.activityCalendar,o,i,this.activity),{ls:s,lf:o}}let c=r;return a||(c=this.getLastWorkingHour(r,this.activityCalendar)),o=D(this.activityCalendar,c,n,this.activity),s=D(this.activityCalendar,o,i,this.activity),a||(o=this.getLastWorkingHour(o,this.activityCalendar,"past")),{ls:s,lf:o}}calculateSFLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n}){let a=null,o=null,s=r;return o=D(this.activityCalendar,s,i,this.activity),a=D(this.activityCalendar,o,n,this.activity),{ls:o,lf:a}}calculateSSLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n,isMilestone:a=!1}){let o=null,s=null;if(t===0)return s=D(this.activityCalendar,r,i,this.activity),o=D(this.activityCalendar,s,n,this.activity),{ls:s,lf:o};let c=r;return t<0&&!a&&(c=this.getLastWorkingHour(c,this.activityCalendar,"future")),s=D(this.activityCalendar,c,i,this.activity),o=D(this.activityCalendar,s,n,this.activity),{ls:s,lf:o}}getMinLfFromLinks(t=[]){return t.length?t.reduce((r,i)=>i.lf<r.lf?i:r):!1}calculateSfRestrictionDates(){let t=this.activity.constraint_date,r=this.activity.duration;return{ls:D(this.activityCalendar,t,-r,this.activity),lf:t}}getLastWorkingHour(t,r,i="past"){let n=t instanceof Date?t:new Date(t),a=Lt(n).clone();return this.isActivityInInitHour(r,n)&&i==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),_t({dateBaseToCalculate:new Date(a),direction:i,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let i=r instanceof Date?r:new Date(r),a=t.getWorkHours(i)[0];if(!a||!a.includes("-"))return!1;let o=a.split("-")[0];if(!o.includes(":"))return!1;let s=o.split(":");return s.length<2?!1:(o=parseInt(s[0],10),Lt.isMoment(r)?r.hours()===o:i.getUTCHours()===o)}},ec=Gn;function rc(e){let{parent:t,linkProperty:r,linkDirection:i,calculations:n,gantt:a,direction:o,linkCandidates:s}=e,c=t[r],l=Gy(t),d=null;if(o==="forward"){let u=$y(c,i,n,a);d=new tc(u,t,a,s),d=d.calculate()}else{let u=zy(c,i,n,a);d=new ec({linksWithActivityData:u,activity:t,parentData:l,gantt:a}).calculate()}return d}function Gy(e){return{duration:e.duration,calendarId:e.calendar_id}}function $y(e,t,r,i){return e.length===0?[]:e.map(n=>{let a=i.getLink(n);if(!a)return console.warn(`Link not found: ${n}`),null;let o=Number(a[t]),s=r.get(o);return s?{linkId:String(a.id),es:s.es,ef:s.ef,linkLag:a.lag,linkType:a.type}:(console.warn(`Calculations not found for activity: ${o}`),null)}).filter(Boolean)}function zy(e,t,r,i){return e.length===0?[]:e.map(n=>{let a=i.getLink(n);if(!a)return console.warn(`Link not found: ${n}`),null;let o=Number(a[t]),s=r.get(o);if(!s)return null;let c=i.getTask(o);return c?{ls:s.ls,lf:s.lf,linkLag:a.lag||0,linkType:a.type,progress:c.progress,type:c.type}:null}).filter(Boolean)}function ac(e){let{activityData:t,calculations:r,singleParents:i,direction:n}=e;if(qy(t.id,r))return null;let a=Jy(t.id,i),o=Xy(a,r);return o.length===0?null:Qy(o,n)}function qy(e,t){return t.has(e)}function Jy(e,t){let r=t.get(e);return r?r.childrens:[]}function Xy(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function Qy(e,t){if(t==="forward"){let r=ic(e,"es"),i=nc(e,"ef");return{es:r,ef:i}}else{let r=ic(e,"ls"),i=nc(e,"lf");return{ls:r,lf:i}}}function ic(e,t){return e.reduce((r,i)=>i[t]<r[t]?i:r)[t]}function nc(e,t){return e.reduce((r,i)=>i[t]>r[t]?i:r)[t]}var $n={parentWithLinks:rc,parentWithNoLinks:ac};var zn=class{constructor(t){this.activity=t.activity,this.direction=t.direction,this.linkProperty=t.direction==="forward"?"$target":"$source",this.linkDirection=t.direction==="forward"?"source":"target",this.calculationsOfParentThatImpactChildrens=t.calculationsOfParentThatImpactChildrens,this.calculations=t.calculations,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.parentCalculationFromChildren=t.parentCalculationFromChildren,this.linkCandidates=t.linkCandidates,this.gantt=t.gantt}handleParentWithLinks(){try{let t=this.getArrayOfIdOfLinkedActivities(this.activity[this.linkProperty]);if(this.direction==="backward"){let i=[h.FNLT];if(this.shouldCalculateParentWithLinksBackward(i)){this.calculateAndStoreParentWithLinks(this.activity);return}if(this.shouldSetDatesToParentsWithLinks(i)){this.setDatesToParentsWithLinksBackward();return}}if(this.areAllLinksCalculated(t)&&this.calculationsOfParentThatImpactChildrens.has(this.activity.id)){this.direction==="forward"&&this.setDatesToParentsWithLinks(),this.direction==="backward"&&this.setDatesToParentsWithLinksBackward();return}this.calculateAndStoreParentWithLinks(this.activity)}catch(t){throw t}}shouldCalculateParentWithLinksBackward(t){let r=t.includes(this.activity.constraint_type),i=!this.calculationOfParentsFromLinks.has(this.activity.id);return r&&i}calculateAndStoreParentWithLinks(t){let r=$n.parentWithLinks({parent:t,linkProperty:this.linkProperty,linkDirection:this.linkDirection,gantt:this.gantt,calculations:this.calculations,direction:this.direction,linkCandidates:this.linkCandidates});this.calculationsOfParentThatImpactChildrens.set(t.id,r),this.calculationOfParentsFromLinks.add(t.id)}areAllLinksCalculated(t){return t.every(r=>this.calculations.has(r))}shouldSetDatesToParentsWithLinks(t){let r=t.includes(this.activity.constraint_type),i=this.calculationOfParentsFromLinks.has(this.activity.id);return r&&i}handleParentWithNoLinks(){let t=$n.parentWithNoLinks({activityData:this.activity,gantt:this.gantt,singleParents:this.singleParents,calculations:this.calculations,direction:this.direction});t&&this.calculations.set(this.activity.id,t)}setDatesToParentsWithLinks(){if(!this.activity)throw new Error("Error trying to get parent",{cause:{parentActivity:this.activity}});let t=this.singleParents.get(this.activity.id)?.childrens,i=Array.from(this.calculations).filter(o=>t.includes(o[0])).map(o=>o[1]),{minEs:n,maxEf:a}=i.reduce((o,{es:s,ef:c})=>({minEs:new Date(Math.min(o.minEs.getTime(),new Date(s).getTime())),maxEf:new Date(Math.max(o.maxEf.getTime(),new Date(c).getTime()))}),{minEs:new Date(i[0].es),maxEf:new Date(i[0].ef)});this.calculations.set(this.activity.id,{es:n,ef:a}),this.parentCalculationFromChildren.add(this.activity.id)}setDatesToParentsWithLinksBackward(){if(!this.activity)throw new Error("Error trying to get parent",{cause:{parentActivity:this.activity}});let t=this.singleParents.get(this.activity.id)?.childrens,i=Array.from(this.calculations).filter(o=>t.includes(o[0])).map(o=>o[1]),{minLs:n,maxLf:a}=i.reduce((o,{ls:s,lf:c})=>({minLs:new Date(Math.min(o.minLs.getTime(),new Date(s).getTime())),maxLf:new Date(Math.max(o.maxLf.getTime(),new Date(c).getTime()))}),{minLs:new Date(i[0].ls),maxLf:new Date(i[0].lf)});this.calculations.set(this.activity.id,{ls:n,lf:a})}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(i=>{let a=this.gantt.getLink(i)[r||this.linkDirection];return Number(a)})}},oc=zn;var qn=class{constructor({gantt:t,linkProperty:r}){this.gantt=t,this.linkProperty=r,this.structureOfParents=new Map,this.singleParents=new Map}identifyThirdLevelActivities(){try{let t=this.getFirstLevelParents();for(let r of t){let i=this.processEachActivity(r),{activitiesByLevel:n}=i,a=this.getAllLevels(n),o=this.getDeepestLevel(a),s=this.createResult(r,i,o,a);this.structureOfParents.set(r.id,s)}return{structureOfParents:this.structureOfParents,singleParents:this.singleParents}}catch(t){throw t}}getFirstLevelParents(){return this.gantt.getTaskByTime().filter(vt.byFirstLevel).filter(vt.filterByParentType)}processEachActivity(t){let r=new Set,i=new Set,n=new Map;return this.initializeParent(t),this.gantt.eachTask(a=>{this.processActivity(a,r,i,n)},t.id),{parentsIds:r,allTasks:i,activitiesByLevel:n}}initializeParent(t){let r=Number(t.id),i=!!t[this.linkProperty]?.length,n=t.$level;this.singleParents.set(r,{level:n,hasLink:i,childrens:[]})}processActivity(t,r,i,n){let a=Number(t.id),o=Number(t.parent);i.add(a),this.isProjectActivity(t)&&this.addParentInfo(t,r);let c=this.doesParentExist(o);o!=null&&c&&this.addChildToParent(o,a),this.addActivityToLevel(t,n)}isProjectActivity(t){return t.type==="project"}hasLink(t){return!!t[this.linkProperty]?.length}addParentInfo(t,r){let i=Number(t.id),n=t.$level,a=this.hasLink(t),o={level:n,hasLink:a,childrens:[]};r.add(i),this.singleParents.set(i,o)}doesParentExist(t){return this.singleParents.has(t)}addChildToParent(t,r){this.singleParents.get(t).childrens.push(r)}addActivityToLevel(t,r){let i=t.$level,n=Number(t.parent);r.has(i)||r.set(i,new Map);let a=r.get(i);a.has(n)||a.set(n,[]),a.get(n).push({id:Number(t.id),isParent:this.isProjectActivity(t),calculated:!1})}getAllLevels(t){return new Set(t.keys())}getDeepestLevel(t){return t.size===0?0:Math.max(...t)}createResult(t,r,i,n){let{activitiesByLevel:a,parentsIds:o,allTasks:s}=r;return{parent:t.id,isALinkedParent:this.hasLink(t),levels:n,allParentChildrens:o,allChildrens:s,childrensByLevel:a,currentResolutionLevel:i,canBeCalculated:!1}}},sc=qn;var Jn=class{constructor(t,r){this.direction=r,this.gantt=t,this.linkProperty=this.direction==="forward"?"$target":"$source",this.linkDirection=this.direction==="forward"?"source":"target",this.projectDates=t.getSubtaskDates()}tryToCalculateLastLevelChildrens(){this.structureOfParents.forEach(t=>{let{currentResolutionLevel:r,childrensByLevel:i,isALinkedParent:n}=t;if(n)return;let a=i.get(r);for(let[o,s]of a)if(s.filter(l=>!this.calculations.has(l.id)).length===0){let l=this.gantt.getTask(o);this.calculateParentWithNoLinks(l,s);return}})}initActivitiesWaitingForCalculation(){try{this.gantt.getTaskByTime().filter(vt.avoidSubproject).forEach(t=>{this.activitiesWaitingForCalculation.add(t.id)})}catch(t){throw t}}identifyParentsWithAndWithoutLinks(){try{let{parentsWithFullProgress:t,pendingParentsWithNoLinks:r,pendingParentsWithLinks:i}=Sr.identifyParentsWithAndWithoutLinks({gantt:this.gantt,direction:this.direction,linkProperty:this.linkProperty});this.parentsWithFullProgress=t,this.pendingParentsWithNoLinks=r,this.pendingParentsWithLinks=i}catch(t){throw t}}identifyForbiddenActivitiesLinkedToParentsWithLinks(){try{this.forbiddenActivitiesLinkedToParentsWithLinks=Sr.identifyForbiddenActivities({pendingParentsWithLinks:this.pendingParentsWithLinks,gantt:this.gantt,direction:this.direction})}catch(t){throw t}}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(i=>{let a=this.gantt.getLink(i)[r||this.linkDirection];return Number(a)})}async identifyThirdLevelActivities(){try{let{structureOfParents:t,singleParents:r}=new sc({gantt:this.gantt,linkProperty:this.linkProperty}).identifyThirdLevelActivities();this.structureOfParents=t,this.singleParents=r}catch(t){throw t}}processEachActivity(t){let r=new Set,i=new Set,n=new Map,a=new Map;return this.singleParents.set(Number(t.id),{level:t.$level,hasLink:!!t[this.linkProperty].length,childrens:[]}),new Promise((o,s)=>{this.gantt.eachTask(function(c){let l=Number(c.parent);if(i.add(c.id),c.type==="project"){let u={level:c.$level,hasLink:!!c[this.linkProperty].length,childrens:[]};r.add(c.id),this.singleParents.set(Number(c.id),u)}l&&this.singleParents.has(l)&&this.singleParents.get(l).childrens.push(c.id),n.has(c.$level)||n.set(c.$level,new Map);let d=n.get(c.$level);d.has(Number(c.parent))||d.set(Number(c.parent),[]),d.get(Number(c.parent)).push({id:c.id,isParent:c.type==="project",calculated:!1})}.bind(this),t.id),o({parentsIds:r,allTasks:i,activitiesByLevel:n,singleParents:a})})}identifySecondLevelActivities(){try{let t=Sr.identifySecondLevelActivities({gantt:this.gantt,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,calculations:this.calculations,linkProperty:this.linkProperty});this.secondLevelActivities=new Set([...this.secondLevelActivities,...t])}catch(t){throw t}}identifyInitialActivities(){try{let{chainStartActivities:t,activitiesStartChainButChildrenOfLinkedParents:r}=Sr.identifyInitialActivities({gantt:this.gantt,linkProperty:this.linkProperty,direction:this.direction});this.chainStartActivities=t,r&&(this.activitiesStartChainButChildrenOfLinkedParents=r)}catch(t){throw new Error("Error in identifyInitialActivities",{cause:t})}}calculateSecondLevelActivities(){try{this.direction==="forward"?this.recursiveCalculateEfAndEs(Array.from(this.secondLevelActivities),0,"secondLevel"):this.recursiveCalculateLfAndLs(Array.from(this.secondLevelActivities))}catch(t){throw t}}calculateStartAndFinishOfActivitiesThatStartChain(){try{this.chainStartActivities.forEach(t=>{if(!t||t.progress>100||t.type==="project")return;let r=this.calculateStartAndFinishOfChainOrigin(t,this.direction);if(this.direction==="forward"){let{es:i,ef:n}=r;this.calculations.set(t.id,{es:i,ef:n,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}else{let{ls:i,lf:n}=r;this.calculations.set(t.id,{ls:i,lf:n,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}})}catch(t){throw t}}buildDependencyGraph(t){let r=new Map,i=new Set(this.calculations.keys()),n=new Map;return t.forEach(a=>{a&&n.set(a.id,a)}),n.forEach((a,o)=>{if(i.has(o))return;let s=[];(a[this.linkDirection]||[]).forEach(l=>{let d=this.gantt.getLink(l);if(d){let u=Number(d[this.linkProperty]);s.push(u)}}),s=s.filter(l=>n.has(l)||i.has(l)),r.set(o,s)}),{graph:r,activityMap:n,calculatedActivities:i}}topologicalSort(t,r){let i=new Set,n=new Set,a=[],o=s=>{if(n.has(s))throw new Error("Cyclical dependency detected",{cause:{nodeId:s}});if(!i.has(s)&&!r.has(s)){n.add(s);let c=t.get(s)||[];for(let l of c)o(l);n.delete(s),i.add(s),a.push(s)}};for(let s of t.keys())!i.has(s)&&!r.has(s)&&o(s);return a.reverse()}calculateStartAndFinishOfChainOrigin(t=null,r=null){try{let i=t,n=Number(i.progress);n==="0.00"&&(n=0);let a=this.gantt.getCalendar(i.calendar_id);if(!a)throw new Error(`Error trying to get calendar with id: ${i.calendar_id}`);if((r||this.direction)==="forward"){let s=i.start_date,c=i.end_date;return{es:s,ef:c}}else{if(n>=100)return{ls:Lt(i.start_date).clone(),lf:Lt(i.end_date).clone()};if(n===0)return this.calculateBackwardWhenZeroProgress(i,a);if(n<100&&n>0)return this.calculateWhenProgressIsBetweenZeroAndOneHundred(i,a)}}catch(i){throw i}}calculateBackwardWhenZeroProgress(t,r){let i=Lt(t.start_date).clone(),n=Lt(t.end_date).clone(),a=t.duration,o=[h.ASAP,h.ALAP,h.SNET,h.FNET],s=t.constraint_type||h.ASAP;if(o.includes(s))n=this.projectDates.end_date,i=D(r,n,-a,t);else{let c=[h.SNLT,h.MSO],l=[h.FNLT,h.MFO];c.includes(s)&&(i=t.constraint_date,n=D(r,i,a,t)),l.includes(s)&&(n=t.constraint_date,i=D(r,n,-a,t))}return{ls:i,lf:n}}calculateWhenProgressIsBetweenZeroAndOneHundred(t){let r=t.start_date,i=null,n=t.constraint_type||h.ASAP,a=this.projectDates.end_date,o=[h.ASAP,h.ALAP,h.SNET,h.FNET],s=[h.SNLT,h.FNLT];if(o.includes(n))i=Math.max(t.end_date,a);else if(n===h.MSO)i=t.end_date;else if(n===h.MFO||s.includes(n)){let c=Math.min(a,t.constraint_date);i=Math.max(c,t.end_date)}return{ls:r,lf:new Date(i)}}initializeActivitiesWithFullProgress(){try{Array.from(this.activitiesWaitingForCalculation).filter(i=>Number(this.gantt.getTask(i).progress)===100).map(i=>this.gantt.getTask(i)).forEach(i=>{let n=i.type==="project";this.setDatesForActivityWithFullProgress(i),this.activitiesWaitingForCalculation.delete(i.id),n&&this.pendingParentsWithLinks.has(i.id)&&(this.parentCalculationFromChildren.add(i.id),this.calculationsOfParentThatImpactChildrens.set(i.id,{[this.direction==="forward"?"es":"ls"]:i.start_date,[this.direction==="forward"?"ef":"lf"]:i.end_date}),this.calculationOfParentsFromLinks.add(i.id))})}catch(t){throw t}}doCalculationForParentType(t){let r=new oc({activity:t,direction:this.direction,calculationsOfParentThatImpactChildrens:this.calculationsOfParentThatImpactChildrens,calculations:this.calculations,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,parentCalculationFromChildren:this.parentCalculationFromChildren,linkCandidates:this.linkCandidates,gantt:this.gantt});this.pendingParentsWithLinks.has(t.id)?r.handleParentWithLinks():r.handleParentWithNoLinks()}},de=Jn;function Zy(e,t,r){let i={es:null,ef:null};if(!e)return i;if([h.SNET,h.SNLT].includes(t)){let n=new Date(e.constraint_date);i.es=n,i.ef=D(r,n,e.duration,e)}else if([h.FNLT,h.FNET].includes(t)){let n=new Date(e.constraint_date);i.es=D(r,n,-e.duration,e),i.ef=n}else if(t===h.MSO){let n=new Date(e.constraint_date);i.es=n,i.ef=D(r,n,e.duration,e)}else if(t===h.MFO){let n=new Date(e.constraint_date);i.es=D(r,n,-e.duration,e),i.ef=n}return i}var Si=Zy;var Xn=class{constructor(t){this.referenceActivity=t.activity,this.activityToCalculate=null,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.alapMap=t.calculatedAlapsMap,this.parentsWithLinks=t.parentsWithLinks,this.parentsCalculations=t.parentsCalculations,this.gantt=t.ganttInstance,this.linkCandidates=t.linkCandidates}getEsAndEfFromPreviousCalculatedActivities(t){return this.alapMap.has(t)?this.alapMap.get(Number(t)):this.calculatedActivities.get(Number(t))}calculateSucessorTimes(t,r,i=0,n,a=z.FS){let o=this.gantt.getCalendar(this.referenceActivity.calendar_id);if(!o)throw new Error(`Error trying to get calendar with id: ${this.referenceActivity.calendar_id}`);let s=t,c=null,l=null,d=this.referenceActivity.type==="milestone";return d||(a===z.FS&&n===0?s=_t({dateBaseToCalculate:s,activityCalendar:o,direction:"future",activity:this.referenceActivity}):s=this.mutateTheDateToFutureOrPastInBaseRestriction(t,a,o)),[z.FF,z.SF].includes(a)?(l=D(o,s,i,this.referenceActivity),c=D(o,l,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,o))):(c=D(o,s,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,o)),l=D(o,c,i,this.referenceActivity)),{es:c,ef:l}}calculateSS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,a=this.referenceActivity.duration,o=t.lag||0;return this.calculateSucessorTimes(r.es,i,a,o,z.SS)}calculateFF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,a=t.lag||0,o=t.lag||0;return this.calculateSucessorTimes(r.ef,n,a,o,z.FF)}calculateFS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,a=this.referenceActivity.duration,o=t.lag||0;return this.calculateSucessorTimes(r.ef,i,a,o,z.FS)}calculateSF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,a=t.lag||0,o=t.lag||0;return this.calculateSucessorTimes(r.es,n,a,o,z.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,r,i){if(![z.FS,z.SS,z.FF].includes(r))return t;let a=[z.FS,z.SS].includes(r)?"future":"past";return _t({dateBaseToCalculate:t,activityCalendar:i,direction:a,activity:this.referenceActivity})}},cc=Xn;var Tr=class extends cc{constructor(t){super(t)}calculate(){if(this.links.length===0)return new de(this.gantt,"forward").calculateStartAndFinishOfChainOrigin(this.referenceActivity);let t=this.links.map(i=>{let n=this.gantt.getLink(i);if(!n)throw new Error("Link data not found",{cause:{linkId:i}});let a=this.calculateLink(n);return this.linkCandidates?.set(String(n.id),{targetId:String(this.referenceActivity.id),...a}),a}),r=Number(this.referenceActivity.parent);if(this.parentsWithLinks.has(r)){let i=this.gantt.getCalendar(this.referenceActivity.calendar_id),n=this.parentsCalculations.get(r).es,a=D(i,n,this.referenceActivity.duration,this.referenceActivity);t.push({es:n,ef:a})}return Ci(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var Qn=class{constructor(t){this.gantt=t.gantt,this.direction=t.direction,this.pendingParentsWithNoLinks=t.pendingParentsWithNoLinks,this.pendingParentsWithLinks=t.pendingParentsWithLinks,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.calculations=t.calculations,this.activitiesStartChainButChildrenOfLinkedParents=t.activitiesStartChainButChildrenOfLinkedParents,this.linkProperty=t.linkProperty,this.linkDirection=t.linkDirection}checkActivitiesThatNowCanBeCalculated(t){let r=new Set,i=new Set(t);for(let n of t){let a=this.gantt.getTask(n);a.type==="project"?this.handleProjectActivity(n,a,r,i):this.handleNonProjectActivity(n,a,r,i)}return{activitiesThatCanBeCalculated:r,pendingActivities:i}}handleProjectActivity(t,r,i,n){let a=this.pendingParentsWithNoLinks.has(t),o=this.pendingParentsWithLinks.has(t),s=this.calculationOfParentsFromLinks.has(t);if(a){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(i.add(t),n.delete(t));return}if(o&&s){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(i.add(t),n.delete(t));return}o&&!s&&this.canCalculateParentActivity(r)&&(i.add(t),n.delete(t))}canCalculateParentActivity(t){let r=(t[this.linkProperty]||[]).length===0,i=t.constraint_type;return(this.direction==="forward"?i==="fnlt"||i==="snlt":i==="fnlt")&&r?!0:this.getArrayOfLinkedActivities(t[this.linkProperty]).every(o=>this.calculations.has(o))}handleNonProjectActivity(t,r,i,n){let a=Number(r.parent),o=this.pendingParentsWithLinks.has(a),s=this.calculationOfParentsFromLinks.has(a);if(o&&!s||this.direction==="backward"&&this.activitiesStartChainButChildrenOfLinkedParents.has(t)&&!s)return;if(r.$target.length===0&&r.$source.length===0){i.add(t),n.delete(t);return}let c=this.getLinkedActivities(r[this.linkProperty]),l=c.every(d=>this.calculations.has(d.id));if(this.direction==="backward"&&(c.length===0||l)&&s){i.add(t),n.delete(t);return}l&&(i.add(t),n.delete(t))}getLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let i of t){let n=this.gantt.getLink(i);if(!n)continue;let a=n[this.linkDirection],o=this.gantt.getTask(a);o&&r.push(o)}return r}getArrayOfLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let i of t){let n=this.gantt.getLink(i);n&&r.push(Number(n[this.linkDirection]))}return r}},ki=Qn;var Zn=(e,t)=>()=>t()===e;var ta=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var th=16,ke=async e=>performance.now()-e>th?(await it(),performance.now()):e;var Dr=async({pending:e,activityCalculator:t,calculateFn:r,shouldKeepPending:i,isCalculated:n,onActivityProcessed:a,isCurrent:o})=>{let s=new Set(e),c=performance.now();for(;s.size>0;){if(!o())return;c=await ke(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(s);if(l.size===0)break;for(let u of l){if(!o())return;c=await ke(c),r([u])}for(let u of l){if(!o())return;i(u)&&d.add(u),a(u),n(u)&&d.delete(u)}s=d}};var ea=class extends de{constructor(t){super(t,"forward"),this.gantt=t,this.chainStartActivities=new Set,this.secondLevelActivities=new Set,this.pendingParentsWithLinks=new Set,this.pendingParentsWithNoLinks=new Set,this.structureOfParents=new Map,this.singleParents=new Map,this.calculations=new Map,this.calculationsOfParentThatImpactChildrens=new Map,this.alapMap=new Map,this.activitiesWaitingForCalculation=new Set,this.constraintsMap=new Map,this.totalFloatSnltFnlt=new Map,this.totalFloatForMsoMfo=new Map,this.totalFloatForAsap=new Map,this.linkCandidates=new Map,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateEfAndEs(t))))))}async iterativeCalculateEfAndEs(t){let r=new ki({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await Dr({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:i=>this.calculateStartAndFinishTimes(i),shouldKeepPending:i=>this.calculationOfParentsFromLinks.has(i)&&!this.calculations.has(i),isCalculated:i=>this.calculations.has(i),onActivityProcessed:i=>this.activitiesWaitingForCalculation.delete(i),isCurrent:t})}calculateStartAndFinishTimes(t){t.forEach(r=>{let i=this.gantt.getTask(r);if(i.type==="project")return this.doCalculationForParentType(i);if(!i)throw new Error("Error trying to get activity",{cause:{activityId:r}});let n=i.$target,a=i.constraint_type||h.ASAP,o=[h.SNET,h.SNLT,h.FNLT,h.FNET],s=[h.ASAP,h.ALAP,h.SNET,h.FNET,h.SNLT,h.FNLT],c=this.gantt.getCalendar(i.calendar_id);if(!c)throw new Error(`Error trying to get calendar with id: ${i.calendar_id}`);let l=Number(i.progress),d=null,u=null,f=null;if(l===100){this.setDatesForActivityWithFullProgress(i);return}l>0&&s.includes(a)?({es:d,ef:u}=this.getDatesForActivityWithZeroProgress(i),f=new Tr({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),a===h.ASAP&&this.totalFloatForAsap.set(r,{es:f.es,ef:f.ef,text:i.text})):{es:d,ef:u}=new Tr({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),a===h.ALAP&&this.alapMap.set(r,{es:i.start_date,ef:i.end_date,text:i.text});let p=Si(i,a,c);if(o.includes(a)&&(this.constraintsMap.set(r,p),this.totalFloatSnltFnlt.set(r,{es:d,ef:u}),{es:d,ef:u}=this.recalculateInBaseConstraint(a,p,{es:d,ef:u})),[h.MSO,h.MFO].includes(a))if(this.totalFloatForMsoMfo.set(r,{es:d,ef:u}),this.constraintsMap.set(r,p),i.progress===0)d=p.es,u=p.ef;else{let y=i.end_date;a===h.MFO&&(y=Math.max(p.ef,i.end_date)),d=i.start_date,u=y}this.calculations.set(r,{es:d,ef:u}),this.activitiesWaitingForCalculation.delete(r)})}getTheGreatesDateBetweenRestrictionAndEsEf(t,r,i="greater"){if(i==="greater")return r.ef>t.ef?r:t;if(i==="less")return r.ef<t.ef?r:t}setDatesForActivityWithFullProgress(t){this.calculations.set(t.id,{es:t.start_date,ef:t.end_date})}getDatesForActivityWithZeroProgress(t){return{es:t.start_date,ef:t.end_date}}recalculateInBaseConstraint(t,r,i){let n=[h.SNET,h.FNET].includes(t)?"greater":"less",{es:a,ef:o}=this.getTheGreatesDateBetweenRestrictionAndEsEf(r,i,n);return{es:a,ef:o}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let i=this.gantt.getLink(r);if(!i)throw new Error("Error trying to get link",{cause:{linkId:r}});let n=i.source,a=i.target;if(!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type==="project")&&!(!this.gantt.getTask(a)||this.gantt.getTask(a)?.type==="project"))return r}).filter(Boolean)}},lc=ea;var ra=class{constructor(t){this.activity=t.activity,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.forwardPathCalculations=t.calculatedForwardActivitiesMap,this.gantt=t.ganttInstance}getForwardOrBackwardCalculations(t,r=null){return r===h.ALAP?this.forwardPathCalculations.get(t):this.calculatedActivities.get(t)}calculateSuccessorTimes(t,r,i=0,n,a=z.FS){let o=this.gantt.getCalendar(this.activity.calendar_id);if(!o)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`);let s=t,c=this.activity.type==="milestone";if(c&&n===0){let d=D(o,s,r,this.activity),u=D(o,d,i,this.activity);return{ls:d,lf:u}}let l={lag:n,workTime:s,activityCalendar:o,lsDataCalculation:r,lfDataCalculation:i,isMilestone:c};if(a===z.FS){let{ls:d,lf:u}=this.calculateFsLink(l);return{ls:d,lf:u}}if(a===z.FF){let{ls:d,lf:u}=this.calculateFFLink(l);return{ls:d,lf:u}}if(a===z.SS){let{ls:d,lf:u}=this.calculateSSlink(l);return{ls:d,lf:u}}if(a===z.SF){let{ls:d,lf:u}=this.calculateSFLink(l);return{ls:d,lf:u}}}calculateSS(t,r=!1){let i=this.getValueForSS(t,r),n=-t.lag||0,a=this.activity.duration,o=t.lag;return this.calculateSuccessorTimes(i,n,a,o,z.SS)}calculateFF(t,r){let i=this.getForwardOrBackwardCalculations(Number(t.target)),n=r===h.ALAP?"ef":"lf",a=i[n],o=-this.activity.duration,s=-t.lag||0,c=t.lag;return this.calculateSuccessorTimes(a,o,s,c,z.FF)}calculateFS(t,r){let i="ls";i=r===h.ALAP?"es":"ls";let n=this.getForwardOrBackwardCalculations(Number(t.target),r),a=-this.activity.duration,o=t.lag||0,s=-t.lag||0;return this.calculateSuccessorTimes(n[i],a,s,o,z.FS)}calculateSF(t,r=!1){let i=r?this.getEarlyStartFromForwardPath(Number(t.target)).ef:this.getForwardOrBackwardCalculations(Number(t.target)).lf,n=-t.lag||0,a=this.activity.duration,o=t.lag;return this.calculateSuccessorTimes(i,n,a,o,z.SF)}getEarlyStartFromForwardPath(t){return this.forwardPathCalculations.get(t)}getValueForSS(t,r){return r?this.getEarlyStartFromForwardPath(Number(t.target)).es:this.getForwardOrBackwardCalculations(Number(t.target))["ls"]}calculateDate(t,r,i){let n=Lt(r).clone();return D(t,new Date(n),i,this.activity)}getLastWorkingHour(t,r,i="past"){let n=t instanceof Date?t:new Date(t),a=Lt(n).clone();return this.isActivityInInitHour(r,n)&&i==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),_t({dateBaseToCalculate:new Date(a),direction:i,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let i=r instanceof Date?r:new Date(r),a=t.getWorkHours(i)[0];if(!a||!a.includes("-"))return!1;let o=a.split("-")[0];if(!o.includes(":"))return!1;let s=o.split(":");return s.length<2?!1:(o=parseInt(s[0],10),Lt.isMoment(r)?r.hours()===o:i.getUTCHours()===o)}calculateFsLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a,isMilestone:o=!1}){let s=null,c=null;if(t===0){let d=this.getLastWorkingHour(r,i,"past");return s=D(i,d,a,this.activity),s=this.getLastWorkingHour(s,i,"past"),c=D(i,s,n,this.activity),{ls:c,lf:s}}let l=r;return o||(l=this.getLastWorkingHour(r,i)),s=D(i,l,a,this.activity),c=D(i,s,n,this.activity),o||(s=this.getLastWorkingHour(s,i,"past",!0)),{ls:c,lf:s}}calculateFFLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a}){let o=null,s=null;if(t===0)return o=D(i,r,a,this.activity),s=D(i,o,n,this.activity),{ls:s,lf:o};let c=r;return t>0&&(c=this.getLastWorkingHour(c,i,"past")),o=D(i,c,a,this.activity),s=D(i,o,n,this.activity),{ls:s,lf:o}}calculateSSlink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a,isMilestone:o=!1}){let s=null,c=null;if(t===0)return c=D(i,r,n,this.activity),s=D(i,c,a,this.activity),{ls:c,lf:s};let l=r;return t<0&&!o&&(l=this.getLastWorkingHour(l,i,"future")),c=D(i,l,n,this.activity),s=D(i,c,a,this.activity),{ls:c,lf:s}}calculateSFLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a}){let o=null,s=null;return t===0?(s=D(i,r,n),o=D(i,s,a,this.activity),{ls:s,lf:o}):(s=D(i,r,n,this.activity),o=D(i,s,a,this.activity),{ls:s,lf:o})}},dc=ra;var ia=class extends dc{constructor(t){super(t),this.constraint=t.constraint||h.ASAP,this.parentsWithFullProgress=t.parentsWithFullProgress,this.parentsThatImpactChildrens=t.parentsThatImpactChildrens,this.projectDates=this.gantt.getSubtaskDates()}calculate(){if(this.links.length===0)return new de(this.gantt,"backward").calculateStartAndFinishOfChainOrigin(this.activity);let t=this.activity.progress>0&&this.activity.progress<100,r=this.gantt.getTask(this.activity.parent),i=!1;r&&(i=this.parentsThatImpactChildrens.has(Number(this.activity.parent)));let n=this.links.map(o=>{let s=this.gantt.getLink(o);if(!s)throw new Error("Link not found",{cause:{linkId:o}});if(!this.parentsWithFullProgress.has(Number(s.target)))return this.calculateLink(s)}).filter(o=>o);if(n.length!==0){let o=this.getMinLfFromLinks(n);if(n.push(this.calculateTheLsAndLfForTheActivity()),i){let d=this.parentsThatImpactChildrens.get(Number(this.activity.parent));n.push(this.calculateTheLsAndLfForTheActivity(d))}let s=this.getMinDateFromLinks(n),c=s.ls,l=s.lf;return t&&(c=this.activity.start_date,l=this.getMinCalculationLogic(s)),{ls:c,lf:l,minFromLinks:o}}if(i){n.push(this.calculateTheLsAndLfForTheActivity());let s=this.parentsThatImpactChildrens.get(Number(this.activity.parent)).lf,c=D(this.gantt.getCalendar(this.activity.calendar_id),s,-this.activity.duration,this.activity);n.push({ls:c,lf:s});let l=this.getMinDateFromLinks(n);return{ls:l.ls,lf:l.lf,minFromLinks:l}}let a=this.calculateTheLsAndLfForTheActivity();return{ls:a.ls,lf:a.lf,minFromLinks:a}}calculateTheLsAndLfForTheActivity(t=null){try{let r=this.activity.duration,i=this.gantt.getCalendar(this.activity.calendar_id);if(!i)throw new Error(`Calendar not found with id ${this.activity.calendar_id}`);let n=t?t.lf:this.projectDates.end_date;if(!n)throw new Error("End date not found for activity",{cause:{activityId:this.activity.id}});return{ls:D(i,n,-r,this.activity),lf:n}}catch(r){throw Error(r.message)}}SnetSnltMsoMinDate(t){let r=Math.min(t.lf,this.projectDates.end_date);return new Date(Math.max(r,this.activity.end_date))}calculateLink(t){let r=this.gantt.getTask(t.target);if(!r||r.progress>0&&r.type!=="project")return;let i=this.getSpecialCalculationParamForConstraintLink(),n=this.getSpecialParamForSf(),a=this.getSpecialParamForFF();return{0:()=>this.calculateFS(t,i),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t,a),3:()=>this.calculateSF(t,n)}[t.type]()}getSpecialCalculationParamForConstraintLink(){if(this.constraint===h.ALAP)return h.ALAP;if(this.constraint===h.FNET||this.constraint===h.SNET)return"snet-fnet";if(this.constraint===h.FNLT)return h.FNLT}getSpecialParamForSf(){return!![h.ALAP].includes(this.constraint)}getSpecialParamForFF(){return!![h.MFO,h.MSO].includes(this.constraint)}getMinCalculationLogic(t){if(this.constraint===h.ALAP)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.FNET)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.FNLT)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.MFO)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.SNET||this.constraint===h.SNLT||this.constraint===h.MSO)return this.SnetSnltMsoMinDate(t);if(this.constraint===h.ASAP)return this.getMinDateBasedOnConstraint(t)}getMinDateFromLinks(t){try{return this.constraint===h.ALAP||this.constraint===h.ASAP?t.reduce((i,n)=>n.lf<i.lf?n:i):t.reduce((r,i)=>i.ls<r.ls?i:r)}catch(r){throw new Error(`Function: getMinDateFromLinks in LinksConstraintCalculator - ${r.message}`)}}getMinLfFromLinks(t){return t.reduce((r,i)=>i.lf<r.lf?i:r)}getMinDateBasedOnConstraint(t,r=this.constraint){let i=Math.min(t.lf,this.projectDates.end_date),n=this.activity.end_date,a=this.activity.constraint_date;if(r===h.ASAP)return new Date(Math.max(i,n));if(r===h.FNET||r===h.FNLT){let o=Math.min(i,a);return new Date(Math.max(i,o))}if(r===h.ALAP)return new Date(Math.min(i,n))}},uc=ia;function eh(e,t,r){let i={ls:null,lf:null};return r===h.MSO&&(i.ls=t.constraint_date,i.lf=D(e,i.ls,t.duration,t)),r===h.MFO&&(i.lf=t.constraint_date,i.ls=D(e,i.lf,-t.duration,t)),i}var fc=eh;var na=class extends de{constructor(t,r,i){super(t,"backward"),this.gantt=t,this.chainStartActivities=new Set,this.secondLevelActivities=new Set,this.pendingParentsWithLinks=new Set,this.pendingParentsWithNoLinks=new Set,this.structureOfParents=new Map,this.singleParents=new Map,this.calculationsOfParentThatImpactChildrens=new Map,this.activitiesWaitingForCalculation=new Set,this.calculations=new Map,this.mapOfRelationsWithActivitiesIds=new Map,this.activitiesWaitingForCalculation=new Set,this.forwardPathCalculations=r,this.forwardConstraintsMap=i,this.constraintMap=new Map,this.minFromLinks=new Map,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.parentsWithFullProgress=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateLfAndLs(t))))))}async iterativeCalculateLfAndLs(t){let r=new ki({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await Dr({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:i=>this.calculateStartAndFinishTimes(i),shouldKeepPending:i=>this.calculationOfParentsFromLinks.has(i)&&!this.calculations.has(i),isCalculated:i=>this.calculations.has(i),onActivityProcessed:i=>this.activitiesWaitingForCalculation.delete(i),isCurrent:t})}setDatesToParentsWithLinks(t){if(!t)throw new Error("Error trying to get parent",{cause:{receivedParentData:t}});let r=this.singleParents.get(t.id).childrens,n=Array.from(this.calculations).filter(s=>r.includes(s[0])).map(s=>s[1]),{minLs:a,maxLf:o}=n.reduce((s,{ls:c,lf:l})=>({minLs:new Date(Math.min(s.minLs.getTime(),new Date(c).getTime())),maxLf:new Date(Math.max(s.maxLf.getTime(),new Date(l).getTime()))}),{minLs:new Date(n[0].ls),maxLf:new Date(n[0].lf)});this.calculations.set(t.id,{ls:a,lf:o})}calculateStartAndFinishTimes(t){t.forEach(r=>{let i=this.gantt.getTask(r);if(!i)throw new Error("Activity not found",{cause:{activityId:r}});let n=i.$source,a=i.constraint_type||h.ASAP,o=Number(i.progress);if(this.activitiesStartChainButChildrenOfLinkedParents.has(r)){if(this.calculationsOfParentThatImpactChildrens.has(Number(i.parent))&&this.calculationsOfParentThatImpactChildrens.get(Number(i.parent))===!1){let{ls:d,lf:u}=this.calculateStartAndFinishOfChainOrigin(i,this.direction);this.setCalculations(i,d,u);return}return this.doCalculationForActivitiesThatStartLinkButHisParentIsLinked(i)}if(i.type==="project")return this.doCalculationForParentType(i);if(o===100){this.setDatesForActivityWithFullProgress(i);return}if(this.allLinkedActivitiesHasProgress(n,i)){this.setWhenAllLinkedActivitiesHasProgress(i);return}if(o>0&&o<100&&(a===h.MSO||a===h.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(i,a);return}if(a===h.MSO||a===h.MFO){this.recalculateInBaseRestriction(i,a);return}let{ls:s,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(n,i,a,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(a===h.SNLT||a===h.FNLT)&&({ls:s,lf:c}=this.getTheLessLateInBasEsEfConstraint(i.id,{ls:s,lf:c},a)),this.setCalculations(i,s,c),this.minFromLinks.set(i.id,{ls:l.ls,lf:l.lf})})}getTheLessLateInBasEsEfConstraint(t,r,i){let n=this.forwardConstraintsMap.get(t);if(!n){let a=this.gantt.getTask(t),o=this.gantt.getCalendar(a.calendar_id);n=Si(a,i,o)}return r.lf<n.ef?r:{ls:n.es,lf:n.ef}}allLinkedActivitiesHasProgress(t){try{let r=!0;for(let i of t){let n=this.gantt.getLink(i);if(!n)continue;let a=this.gantt.getTask(n.target);a&&(a.type==="project"&&(r=!1),a.progress===0&&(r=!1))}return r}catch(r){throw new Error(r.message)}}setDatesForActivityWithFullProgress(t){this.setCalculations(t,t.start_date,t.end_date)}setWhenAllLinkedActivitiesHasProgress(t){let r=Number(t.parent),{ls:i,lf:n}=this.calculateStartAndFinishOfChainOrigin(t,"backward");if(this.calculationsOfParentThatImpactChildrens.has(r)){i=t.start_date;let a=this.calculationsOfParentThatImpactChildrens.get(r);a&&typeof a=="object"&&a.lf!=null&&(n=new Date(Math.min(n,a.lf)))}this.setCalculations(t,i,n)}setWhenActivitiesHasProgressButLessThanOneHundred(t,r){if(r===h.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(r===h.MFO){let i=Math.min(t.constraint_date,this.projectDates.end_date),n=new Date(Math.max(i,t.end_date));this.setCalculations(t,t.start_date,n);return}}setCalculations(t,r,i){this.calculations.set(t.id,{ls:r,lf:i,text:t.text})}calculateLfandLsFromLinks(t,r,i,n,a){return new uc({links:t,activity:r,calculatedActivitiesMap:this.calculations,calculatedForwardActivitiesMap:this.forwardPathCalculations,constraint:i,parentsWithFullProgress:n,parentsThatImpactChildrens:a,ganttInstance:this.gantt}).calculate()}recalculateInBaseRestriction(t,r){try{let i=this.gantt.getCalendar(t.calendar_id);if(!i)throw new Error(`Error trying to get calendar with id: ${t.calendar_id}`);let n=fc(i,t,r);this.constraintMap.set(t,n),this.setCalculations(t,n.ls,n.lf)}catch(i){throw new Error(i.message)}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let i=this.gantt.getLink(r).source,n=this.gantt.getLink(r).target;if(!(!this.gantt.getTask(i)||this.gantt.getTask(i)?.type==="project")&&!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type==="project"))return r}).filter(Boolean)}doCalculationForActivitiesThatStartLinkButHisParentIsLinked(t){let r=Number(t.parent),i=this.calculationsOfParentThatImpactChildrens.get(r),n=0,a=0;if([h.ASAP,h.ALAP,h.SNET,h.FNET].includes(t.constraint_type))if(Number(t.progress)>0){let l=this.projectDates.end_date;a=new Date(Math.min(l,i.lf)),n=t.start_date}else a=i.lf,n=D(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t);if([h.SNLT].includes(t.constraint_type)){let l=this.calculationsOfParentThatImpactChildrens.get(r),d=D(this.gantt.getCalendar(t.calendar_id),l.lf,-t.duration,t),u=t.constraint_date??d;n=new Date(Math.min(u.getTime(),d.getTime())),a=D(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}if([h.FNLT].includes(t.constraint_type)){let l=this.calculationsOfParentThatImpactChildrens.get(r),d=t.constraint_date??l.lf;n=new Date(Math.min(d.getTime(),l.lf.getTime())),a=D(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}[h.MSO].includes(t.constraint_type)&&(n=t.constraint_date,a=D(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)),[h.MFO].includes(t.constraint_type)&&(a=t.constraint_date,n=D(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t));let o=this.projectDates.end_date,s=[{ls:n,lf:a}];s.push({ls:D(this.gantt.getCalendar(t.calendar_id),o,-t.duration,t),lf:o});let c=this.getMinLfFromLinks(s);this.calculations.set(t.id,{ls:c.ls,lf:c.lf,text:t.text})}getMinLfFromLinks(t=[]){return t.length?t.reduce((r,i)=>i.lf<r.lf?i:r):!1}},pc=na;function yc(){return null}var hc=({forward:e,backward:t,id:r,activity:i,gantt:n,projectDates:a})=>({totalFloat:{es:e.calculations.get(r)?.es||0,ef:e.calculations.get(r)?.ef||0,ls:t.calculations.get(r)?.ls||0,lf:t.calculations.get(r)?.lf||0,constraintsMap:e.constraintsMap.get(r),totalFloatSnltFnlt:e.totalFloatSnltFnlt.get(r),totalFloatForMsoMfo:e.totalFloatForMsoMfo.get(r),minFromLinks:t.minFromLinks.get(r),activity:i,gantt:n},freeFloat:{forwardMap:e.calculations||new Map,backwardMap:t.calculations||new Map,activity:i,projectDates:a,gantt:n}});var aa=class{constructor(t){this.gantt=t.gantt,this.activity=t.activity,this.es=t.es,this.ef=t.ef,this.ls=t.ls,this.lf=t.lf,this.constrainstMap=t.constraintsMap,this.totalFloatSnltFnlt=t.totalFloatSnltFnlt,this.totalFloatForMsoMfo=t.totalFloatForMsoMfo,this.minFromLinks=t.minFromLinks}getTotalFloat(){let{constraint_type:t}=this.activity,r=Number(this.activity.progress);if(r===100)return 0;if(t||(t=h.ASAP),t===h.ASAP||!t)return r===0?this.calculateAsap():this.calculateAsapWithProgress();if(t===h.ALAP)return r===0?this.calculateAlap():this.calculateAlapWithProgress();if(t===h.SNET||t===h.FNET)return r===0?this.calculateSnetFet():this.calculateSnetFnetSnltWithProgress();if(t===h.SNLT)return r===0?this.calculateSnltFnlt():this.calculateSnetFnetSnltWithProgress();if(t===h.FNLT)return r===0?this.calculateSnltFnlt():this.calculateFnltWithProgress();if(t===h.MSO||t===h.MFO)return r===0?this.calculateMsoMfo():this.calculateMsoMfoWithProgress()}calculateAsap(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateAsapWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let r=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateAlap(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r),n=this.calculationWithCalendar(this.lf,this.activity.end_date);return this.getMinValue(i,n)/this.gantt.config.hoursPerDay}calculateAlapWithProgress(){return this.calculationWithCalendar(this.lf,this.ef)/this.gantt.config.hoursPerDay}calculateSnetFnetSnltWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let r=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateFnltWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef),r=this.calculationWithCalendar(this.activity.constraint_date,this.ef);if(this.minFromLinks){let i=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r,i)/this.gantt.config.hoursPerDay}return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateMsoMfoWithProgress(){return this.calculationWithCalendar(this.lf,this.ef)/this.gantt.config.hoursPerDay}calculateSnetFet(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateSnltFnlt(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r);if(!this.totalFloatSnltFnlt&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let n=0;return this.activity.constraint_type===h.SNLT?n=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatSnltFnlt.es):n=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatSnltFnlt.ef),this.getMinValue(n,i)/this.gantt.config.hoursPerDay}calculateMsoMfo(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r);if(!this.totalFloatForMsoMfo&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let n=0;return this.activity.constraint_type===h.MSO?n=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatForMsoMfo.es):n=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatForMsoMfo.ef),this.getMinValue(n,i)/this.gantt.config.hoursPerDay}getMinValue(...t){return Math.min(...t)}calculationWithCalendar(t,r){return this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)})}},mc=aa;var oa=class{constructor(t){this.gantt=t.gantt,this.activity=t.activity,this.forwardMap=t.forwardMap,this.backwardMap=t.backwardMap,this.projectDates=t.projectDates,this.linksFreeFloatArray=[],this.linksFreeFloatObject={},this.durationCache=new Map}getFreeFloat(){let t=Number(this.activity.progress),r=this.getConstraintType();return this.calculateFreeFloatOfLink(r),{activityFreeFloat:t===100?0:this.getFreeFloatBaseConstraint(r),linksFreeFloat:this.linksFreeFloatObject}}getFreeFloatBaseConstraint(t){return t===h.MSO||t===h.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=h.ASAP){let r=this.activity.$source.map(i=>{let{LINK:n,LINK_TYPE:a}=this.getLinkData(i),o=this.gantt.getTask(n.target);if(!o)return{linkId:n.id,freeFloat:null,hasProgress:!1};let s=Number(o.progress)>0,{sucessorDateToCalculate:c,predecessorDateToCalculate:l}=this.getDatesFromSucessorAndPredecessor(a,t,o),d=this.calculationWithCalendar(c,l),u=this.parseHoursToDays(d)-this.parseHoursToDays(n.lag),f=Math.max(0,u);return this.linksFreeFloatObject[n.id]=f,{linkId:n.id,freeFloat:f,hasProgress:s}}).filter(i=>i.freeFloat!==null&&i.freeFloat!==void 0);return this.linksFreeFloatArray=r,r}calculateGeneral(t=h.ASAP){let r=this.getMinFloat(this.linksFreeFloatArray),i=this.calculateFreeFloatForEndOfProject(t),n=0;return[h.SNLT,h.FNLT].includes(t)?n=this.doCalculationForSnltFnlt(t,i,r):n=this.doGeneralCalculation(i,r),Math.max(0,n)}getConstraintType(){let{constraint_type:t}=this.activity;return t||(t=h.ASAP),t}getDatesFromSucessorAndPredecessor(t,r,i){let n=i.constraint_type===h.ALAP,a=this.getSucessorAndPredecessorDates({constraint:r,isSuscessorAlap:n,sucessorId:i.id,predecessorId:this.activity.id}),o=new Date,s=new Date;return o=a[t].sucessor,s=a[t].predecessor,{sucessorDateToCalculate:o,predecessorDateToCalculate:s}}doGeneralCalculation(t,r){return r===null?t:this.getMinValue(r,t)}doCalculationForSnltFnlt(t,r,i){let n=this.calculateFreeFloatOfRestriction(t);return this.getMinValue(i,r,n)}calculateFreeFloatForEndOfProject(t){let r=t===h.ALAP?this.backwardMap.get(this.activity.id):this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===h.ALAP?r?.lf:r?.ef))}calculateFreeFloatOfRestriction(t){let r=this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.activity.constraint_date,t===h.FNLT?r?.ef:r?.es))}getLinkData(t){let r=this.gantt.getLink(t)||{},i=Se(r.type);return{LINK:r,LINK_TYPE:i}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:r,sucessorId:i,predecessorId:n}){let a=(r?this.backwardMap:this.forwardMap).get(i),o=(t===h.ALAP?this.backwardMap:this.forwardMap).get(n),s=t===h.ALAP?o?.ls:o?.es,c=t===h.ALAP?o?.lf:o?.ef;return{fs:{sucessor:a?.ls??a?.es,predecessor:c},ss:{sucessor:a?.ls??a?.es,predecessor:s},ff:{sucessor:a?.lf??a?.ef,predecessor:c},sf:{sucessor:a?.lf??a?.ef,predecessor:s}}}calculateMsoMfo(t){let r=this.activity.constraint_date||new Date,i=this.forwardMap.get(this.activity.id),n=t===h.MSO?i?.es:i?.ef,a=this.calculationWithCalendar(r,n);return Math.max(0,this.parseHoursToDays(a))}getMinValue(...t){let r=t.filter(i=>i!=null);return r.length?Math.min(...r):0}calculationWithCalendar(t,r){if(!(t instanceof Date)||!(r instanceof Date)||!Number.isFinite(t.getTime())||!Number.isFinite(r.getTime()))return Number.NaN;let i=`${r.getTime()}_${t.getTime()}`;if(this.durationCache.has(i))return this.durationCache.get(i);let a=this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)});return this.durationCache.set(i,a),a}parseHoursToDays(t){return t==null?0:t/this.gantt.config.hoursPerDay}getMinFloat(t){if(!t?.length)return null;let r=t.filter(i=>!i.hasProgress).map(i=>i.freeFloat);return r.length===0?null:Math.min(...r)}},gc=oa;var Ac=e=>({totalFloat:new mc(e.totalFloat).getTotalFloat(),freeFloat:new gc(e.freeFloat).getFreeFloat()});var sa=async({activityIds:e,forward:t,backward:r,gantt:i,projectDates:n,isCurrent:a})=>{let o=performance.now(),s=new Map,c=new Map;for(let l of e){if(a&&!a())return{totalFloatMap:s,freeFloatMap:c};let d=i.getTask(l);if(!d)continue;let u=hc({forward:t,backward:r,id:l,activity:d,gantt:i,projectDates:n}),{totalFloat:f,freeFloat:p}=Ac(u);s.set(l,f),c.set(l,p),o=await ke(o)}return{totalFloatMap:s,freeFloatMap:c}};var ca=class{constructor(t){this.gantt=t,this.forwardPathCalculations=null,this.backwardPathCalculations=null,this.totalFloat=new Map,this.freeFloat=new Map,this.linkResidualHours=new Map,this.currentCalculationId=0}getCurrentCalculationId=()=>this.currentCalculationId;async calculate(t,r=()=>!0){let i=++this.currentCalculationId,n=Zn(i,this.getCurrentCalculationId),a=()=>n()&&r();try{let o=t||this.gantt;if(this.gantt=o||yc(),ta(this.gantt))return!1;let s=new lc(this.gantt);if(await s.calculateAsync(a),!a())return!1;let c=s.calculations,l=s.constraintsMap,d=new pc(this.gantt,c,l);if(await d.calculateAsync(a),!a())return!1;this.forwardPathCalculations=c,this.backwardPathCalculations=d.calculations;let u=await this.calculateLinkResidualHours(s.linkCandidates,c,a);if(!u||!a())return!1;this.linkResidualHours=u;let{totalFloatMap:f,freeFloatMap:p}=await this.calculateFloatsAsync(s,d,a);return a()?(this.totalFloat=f,this.freeFloat=p,this.gantt.refreshData(),!0):!1}catch(o){throw this.forwardPathCalculations?.size,o}}async calculateLinkResidualHours(t,r,i=()=>!0){let n=new Map,a=performance.now();for(let[o,s]of t){if(a=await ke(a),!i())return null;let c=Number(s.targetId),l=this.gantt.getTask(c),d=r.get(c),u=s.ef,f=d?.ef,p=l&&this.gantt.getCalendar(l.calendar_id);if(!p||!(u instanceof Date)||!(f instanceof Date)||!Number.isFinite(u.getTime())||!Number.isFinite(f.getTime())){n.set(o,null);continue}let y=u.getTime(),C=f.getTime()>=y?p.calculateDuration({start_date:u,end_date:f}):-p.calculateDuration({start_date:f,end_date:u});n.set(o,Number.isFinite(C)?Object.is(C,-0)?0:C:null)}return n}async calculateFloatsAsync(t,r,i){try{let n=this.gantt.getSubtaskDates(),a=Array.from(this.forwardPathCalculations.keys());return await sa({activityIds:a,forward:t,backward:r,gantt:this.gantt,projectDates:n,isCurrent:i})}catch(n){throw this.forwardPathCalculations?.size,n}}},Ic=ca;var rh=e=>e==="fnet"||e==="fnlt"||e==="mfo",ih=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function nh(e,t){let r=e.constraintDate;if(!r||!rh(e.constraintType))return r;let i=ih(r);if(r.getTime()!==i.getTime())return r;let n=t.getClosestWorkTime({date:i,dir:"future",task:e});return n.getUTCFullYear()===r.getUTCFullYear()&&n.getUTCMonth()===r.getUTCMonth()&&n.getUTCDate()===r.getUTCDate()?pn(e,t):r}function ah(e){let t=new Map,r=new Map,i=new Map;return{calculateEndDate:({start_date:n,duration:a})=>{let o=`${n.getTime()}|${a}`,s=t.get(o);if(s!==void 0)return new Date(s);let c=e.calculateEndDate(n,a);return t.set(o,c.getTime()),c},calculateDuration:({start_date:n,end_date:a})=>{let o=`${n.getTime()}|${a.getTime()}`,s=r.get(o);if(s!==void 0)return s;let c=e.calculateDuration(n,a);return r.set(o,c),c},getWorkHours:n=>e.getWorkHours(n),$gantt:{getClosestWorkTime:({date:n,dir:a,unit:o})=>{let s=o??"hour",c=`${n.getTime()}|${a}|${s}`,l=i.get(c);if(l!==void 0)return new Date(l);let d=e.getClosestWorkTime({date:n,direction:a,unit:s});return i.set(c,d.getTime()),d}}}}function oh(e){let t=new Map;e.forEachActivity((n,a)=>t.set(String(a),n));let r=new Map,i=(n,a)=>{let o=r.get(n);if(o!=null)return o;let c=t.get(n)?.parentId??null,l=0;return c!==null&&!a.has(n)&&(a.add(n),l=i(String(c),a)+1),r.set(n,l),l};for(let n of t.keys())i(n,new Set);return r}function sh(e){let t=new Set;e.forEachActivity((s,c)=>{t.add(String(c)),s.parentId!==null&&t.add(String(s.parentId))});let r=new Map;for(let s of t){let c=Number(s);Number.isSafeInteger(c)&&c!==0&&r.set(c,(r.get(c)??0)+1)}let i=new Map,n=new Map;for(let s of t){let c=Number(s);Number.isSafeInteger(c)&&c!==0&&r.get(c)===1&&(i.set(s,c),n.set(c,s))}let a=1,o=s=>{let c=String(s),l=i.get(c);if(l!==void 0)return l;for(;n.has(a);)a+=1;return i.set(c,a),n.set(a,c),a++};for(let s of t)o(s);return{toLegacy:o,toCanonical:s=>typeof s=="number"?n.get(s)??null:i.has(String(s))?String(s):null}}function ch(e,t){let r=oh(e),i=new Map;return e.forEachActivity((n,a)=>{let o=String(a);i.set(o,{id:t.toLegacy(o),parent:n.parentId===null?0:t.toLegacy(n.parentId),$level:r.get(o)??0,$source:e.getOutgoingLinkIds(o),$target:e.getIncomingLinkIds(o),start_date:n.startDate,end_date:n.endDate,duration:n.durationHours,progress:n.progress,type:n.type,calendar_id:n.calendarId,constraint_type:n.constraintType,constraint_date:nh(n,e)})}),i}function lh(e){let t=new Map;for(let o of e.values()){let s=t.get(o.parent);s?s.push(o):t.set(o.parent,[o])}let r=[],i=new Set,n=[],a=o=>{if(o)for(let s=o.length-1;s>=0;s-=1)n.push(o[s])};for(a(t.get(0));n.length>0;){let o=n.pop();i.has(o)||(i.add(o),r.push(o),a(t.get(o.id)))}if(r.length<e.size)for(let o of e.values())i.has(o)||r.push(o);return r}function dh(e){let t=null,r=null;return e.forEachActivity(i=>{if(i.startDate){let n=i.startDate.getTime();t=t==null?n:Math.min(t,n)}if(i.endDate){let n=i.endDate.getTime();r=r==null?n:Math.max(r,n)}}),{start_date:new Date(t??0),end_date:new Date(r??0)}}async function vc(e,t){let r=new Map,i=l=>{let d=l==null?"__default__":String(l),u=r.get(d);if(u)return u;let f=e.calendarReader.getCalendar(String(l)),p=ah(f);return r.set(d,p),p},n=dh(e);await it();let a=sh(e),o=ch(e,a);await it();let s=[...o.values()].sort((l,d)=>(l.start_date?.getTime()??0)-(d.start_date?.getTime()??0));await it();let c=lh(o);return{fullyParsed:!0,config:{hoursPerDay:t},getTask:l=>{let d=a.toCanonical(l);return d===null?null:o.get(d)??null},getLink:l=>{let d=e.getLink(l);return d?{...d,source:a.toLegacy(d.source),target:a.toLegacy(d.target),lag:d.lag}:null},getCalendar:i,getChildren:l=>{let d=a.toCanonical(l);return d===null?[]:e.getChildren(d).map(a.toLegacy)},eachTask:l=>{for(let d of c)l(d)},getTaskByTime:()=>s,getSubtaskDates:()=>n,getCanonicalActivityId:a.toCanonical,refreshData:()=>{}}}var da=1e3,uh=e=>typeof e!="number"||!Number.isFinite(e)?null:Object.is(e,-0)?0:e,fh=(e,t)=>typeof e!="number"||e<0?null:la(e,t);function ph(e){let t=fh(e.freeFloatDays,e.hoursPerDay),r=uh(e.residualHours);return{freeSlackHours:t,isCritical:r!==null&&r<=0&&e.sourceIsCritical&&e.targetIsCritical&&e.targetProgress===0}}async function yh(e,t){let r=new Map,i=0;for(let n of e.values())for(let a in n.linksFreeFloat)if(Object.hasOwn(n.linksFreeFloat,a)){if(++i>=da&&(i=0,await it(),!t()))return null;r.set(String(a),n.linksFreeFloat[a])}return t()?r:null}async function hh(e,t,r,i,n){let a=new Map,o=0;for(let s of t.forward?.keys()??[]){if(++o>=da&&(o=0,await it(),!n()))return null;let c=i(s);if(c===null)continue;let l=e.getActivity(c);l&&a.set(String(c),gh(s,Number(l.progress??0),t,r))}return n()?a:null}async function mh(e,t,r,i,n,a){let o=new Map,s=0;for(let c of e.getAllLinks()){if(++s>=da&&(s=0,await it(),!a()))return null;o.set(String(c.id),ph({freeFloatDays:t.get(String(c.id)),residualHours:r.get(String(c.id)),hoursPerDay:n,sourceIsCritical:i.get(c.source)?.isCritical===!0,targetIsCritical:i.get(c.target)?.isCritical===!0,targetProgress:e.getActivity(c.target)?.progress}))}return a()?o:null}var la=(e,t)=>{if(typeof e!="number"||!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return null;let r=e*t;return Number.isFinite(r)?Object.is(r,-0)?0:r:null};function gh(e,t,r,i){let n=c=>{if(c==null)return null;let l=new Date(c);return Number.isFinite(l.getTime())?l:null},a=r.forward?.get(e),o=r.backward?.get(e),s=la(r.totalFloat.get(e),i);return{criticalPath:{earlyStart:n(a?.es),earlyFinish:n(a?.ef),lateStart:n(o?.ls),lateFinish:n(o?.lf),totalSlackHours:s},isCritical:t<100&&s!==null&&s<=0,freeSlackHours:la(r.freeFloat.get(e)?.activityFreeFloat,i)}}var Ti=(e,t)=>e===t||e!==null&&t!==null&&e.getTime()===t.getTime();function ua(e,t,r){let i=e.getActivity(t),n=i?.criticalPath,a=r.criticalPath;i&&n&&Ti(n.earlyStart,a.earlyStart)&&Ti(n.earlyFinish,a.earlyFinish)&&Ti(n.lateStart,a.lateStart)&&Ti(n.lateFinish,a.lateFinish)&&Object.is(n.totalSlackHours,a.totalSlackHours)&&Object.is(i.isCritical,r.isCritical)&&Object.is(i.freeSlackHours,r.freeSlackHours)||e.setActivityFields(t,r)}function fa(e,t,r){let i=e.getLink(t);!i||Object.is(i.freeSlackHours,r.freeSlackHours)&&Object.is(i.isCritical,r.isCritical)||(e.setLinkField(t,"freeSlackHours",r.freeSlackHours),e.setLinkField(t,"isCritical",r.isCritical))}async function pa(e,t,r=()=>!0){if(!r())return null;let i=await vc(e,t);if(!r())return null;let n=new Ic(i);if(!await n.calculate(i,r)){if(!r())return null;throw new Error("critical path calculation aborted")}if(!r())return null;let o={forward:n.forwardPathCalculations,backward:n.backwardPathCalculations,totalFloat:n.totalFloat,freeFloat:n.freeFloat},s=await hh(e,o,t,i.getCanonicalActivityId,r);if(!s)return null;let c=await yh(o.freeFloat,r);if(!c)return null;let l=await mh(e,c,n.linkResidualHours,s,t,r);return l?{activities:s,links:l}:null}async function Cc(e,t,r=()=>!0){let i=await pa(e,t,r);if(!i||!r())return!1;for(let[n,a]of i.activities){if(!r())return!1;ua(e,n,a)}for(let[n,a]of i.links){if(!r())return!1;fa(e,n,a)}return!0}function qe(e){let t=[],r=[];e.forEachActivity((n,a)=>{n.parentId===null&&t.push(String(a))});let i=n=>{let a=e.getActivity(String(n));if(!a)return 0;let o=[...e.getChildren(String(n))],s;if(o.length===0){let c=gt(a),l=c&&Number(c.cost)||0;s=(Number(a.progress)||0)/100*l}else{let c=0;for(let l of o)c+=i(String(l));s=c}return e.setActivityField(String(n),b.REAL_COST,s),r.push(String(n)),s};for(let n of t)i(n);return r}var Sc=new Set;var kc=new Set(["activity-outdent","activity-indent"]);var _r=new Set([S.TEXT,S.DESCRIPTION,S.COST,S.USED_COST,S.CUSTOM_ID,S.RESPONSABLES,S.SUBCONTRACT_ID,S.TAGS]),Ah=new Set(["activity-clipboard-clear","activity-copy","selection-toggle","selection-replace","visibility-set","filter-set","sort-set","sir-sync","activity-lookahead-sync","persistence-acknowledge","baseline-apply","ponderator-criterion-set","status-criteria-set"]),Ih=new Set(["activity-clipboard-clear","activity-copy","selection-toggle","selection-replace","visibility-set","filter-set","sort-set"]);function Dc(e){return!Ih.has(e.kind)}var vh=new Set;function Ch(e){return e.kind==="inline-edit"?_r.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>_r.has(t.column)):!1}function ya(e,t){return!(Ah.has(e.kind)||t.has(e.kind)||Ch(e))}function ha(e){return e.kind==="activity-lookahead-sync"?e.persistedProgress!==void 0:ya(e,vh)}function Te(e){return e.kind==="activity-lookahead-sync"?e.persistedProgress!==void 0:ya(e,Sc)}function _c(e){return ya(e,kc)}function ma(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?e.column===S.PROGRESS:e.kind==="bulk-edit"?e.edits.some(t=>t.column===S.PROGRESS):!1}function Sh(e){return _c(e)&&ma(e)}var Tc=new Set([S.PROGRESS,S.HH_WORK_TIME,S.DURATION,S.COST,S.USED_COST,S.REAL_COST]);function kh(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?Tc.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>Tc.has(t.column)):!1}var yt={AUTOSCHEDULE:"autoschedule",PARENT_BOUNDS:"parent-bounds",PARENT_PROGRESS:"parent-progress",REAL_WORK:"real-work",EXPECTED_PROGRESS:"expected-progress",REAL_COST:"real-cost",CRITICAL_PATH:"critical-path"};function Ec(e,t,r){let i=new Set;t.ran&&i.add(yt.AUTOSCHEDULE),i.add(yt.PARENT_BOUNDS),kh(e)&&i.add(yt.PARENT_PROGRESS),ma(e)&&i.add(yt.REAL_WORK);let n=!r.skipAutoSchedule;return n&&_c(e)&&i.add(yt.EXPECTED_PROGRESS),n&&Sh(e)&&i.add(yt.REAL_COST),n&&Te(e)&&!r.skipCriticalPath&&i.add(yt.CRITICAL_PATH),i}async function q(e,t){let r=Dh(e.adapter),i=Th(t,r);i.has(yt.AUTOSCHEDULE)&&await Oh(e.adapter,t);let n=i.has(yt.AUTOSCHEDULE)?await Rh(e,t.autoscheduleFrom,t.preventSummaryTargetPullback):Lh();return await bh(e.adapter,t,n.scheduledIds,i,r),await wh(e,i,t.now),n}function Th(e,t){let r=e.autoscheduleFrom!==null,i=!e.options.skipAutoSchedule&&r,n=new Set(Ec(e.action,{requested:r,ran:i},e.options));return(e.recomputeParentProgress||t.affectedParents.size>0)&&n.add(yt.PARENT_PROGRESS),n}function Dh(e){let t=new Set,r=new Set,i=e.peekWriteCapture();if(!i)return{affectedParents:t,dirtySeeds:r};let n=a=>{if(a===null||N(a))return;let o=String(a);t.add(o);let s=e.getChildren(o)[0];s!==void 0&&r.add(s)};return _h(e,i.ops,n),Eh(e,i.before,r,n),{affectedParents:t,dirtySeeds:r}}function _h(e,t,r){for(let i of t)if(i.kind==="insert"){let n=e.getActivity(i.activityId);n&&r(n.parentId)}else i.kind==="remove"&&r(i.before.parentId)}function Eh(e,t,r,i){for(let[n,a]of t){let o=e.getActivity(n);if(!o)continue;let s=!Object.is(a.progress,o.progress),c=!Object.is(a.ponderator,o.ponderator),l=!Object.is(a.parentId,o.parentId);(s||c)&&(i(o.parentId),r.add(String(n))),l&&(i(a.parentId),i(o.parentId),r.add(String(n)))}}async function Rh(e,t,r=!1){let i=t==="roots"?{}:{triggerId:t};r&&(i.preventSummaryTargetPullback=!0);let n=await e.scheduler.schedule(i),a=Ph(e.adapter,n.updatedIds);return fr(e.adapter,n),a}function Ph(e,t){let r=[];for(let i of t){let n=String(i);r.push(n);let a=e.getActivity(n);a&&e.noteScheduledBefore(n,a)}return{scheduledIds:r}}function Lh(){return{scheduledIds:[]}}async function Oh(e,t){let r=t.collectDirty?t.collectDirty([]):Wn(t.recomputeParentsFrom,[]);r.size!==0&&await He(e,r,!1)}async function bh(e,t,r,i,n){i.has(yt.PARENT_PROGRESS)&&Nh(e,n.affectedParents);let a=t.collectDirty?t.collectDirty(r):Wn(t.recomputeParentsFrom,r);for(let o of n.dirtySeeds)a.add(o);await He(e,a,i.has(yt.PARENT_PROGRESS),{recomputeRealWork:i.has(yt.REAL_WORK),progressMode:"freeze-when-no-contribution"})}function Nh(e,t){for(let r of t){if(e.hasChildren(r))continue;let i=e.getProgressFallback(r);i!==null&&(e.setActivityField(r,"progress",i),e.setProgressFallback(r,null))}}async function wh(e,t,r){t.has(yt.EXPECTED_PROGRESS)&&r!==null&&(Fh(e.adapter)&&ze(e.adapter,r,e.defaultBaseCalendarId??null),Ce(e.adapter,r),qt(e.adapter,e.sector.statusCriteria)),t.has(yt.REAL_COST)&&qe(e.adapter),t.has(yt.CRITICAL_PATH)&&await Cc(e.adapter,e.sector.hoursPerDay)}function Fh(e){let t=!1;return e.forEachActivity(r=>{gt(r)&&(t=!0)}),t}var xh=new Set([S.CONSTRAINT_TYPE,S.CONSTRAINT_DATE]),Mh=new Set(["mso","mfo"]);function Di(e){return xh.has(e)}function _i(e){return e===S.CONSTRAINT_DATE}function Ei(e,t,r,i){let n=r.getActivity(e);if(!n)return!1;let a=n.constraintType;if(!a||ae.has(a)||Mh.has(a))return!1;let o=ga(n.startDate),s=ga(r.getLastStartDate(e));if(!s||!o||o.getTime()!==s.getTime())return!1;let c=Uh(t,a,String(n.calendarId??""),i),l=ga(n.constraintDate);return Bh(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function Uh(e,t,r,i){if(e===null)return null;let n=i.getCalendar(r);return n?Yt(e,n,t):e}function ga(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function Bh(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function Ri(e,{postMutationArgs:t,revertTargets:r,revert:i}){let{scheduledIds:n}=await q(e,Rc(t)),a=!1;for(let{activityId:o,priorConstraintDate:s}of r){let c=i(o,s);a=a||c}if(a){let o=await q(e,Rc(t));n=Hh(n,o.scheduledIds)}return Te(t.action)&&await q(e,Wh(t)),{scheduledIds:n}}function Rc(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function Wh(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function Hh(e,t){let r=new Set(e);for(let i of t)r.add(i);return[...r]}function Aa(e,t,r){let i=[];for(let n of r){let a=e.get(n);if(!a)continue;let o=a.pendingRequestIds??[];if(we({pendingRequestIds:o})&&t.getActivity(n)==null)for(let s of o)i.push({kind:fi.SIR_AUTO_REJECT,activityId:n,sirId:s,reason:pi.ACTIVITY_DELETED})}return i}function St(e){let t={id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag),freeSlackHours:typeof e.freeSlackHours=="number"&&Number.isFinite(e.freeSlackHours)?e.freeSlackHours:null,isCritical:e.isCritical===!0};return e.proplannerId!=null&&(t.proplannerId=Number(e.proplannerId)),e.ganttId!=null&&(t.ganttId=Number(e.ganttId)),e.sectorId!=null&&(t.sectorId=Number(e.sectorId)),t}async function K(e,t){let r=Yh(e,t),i=new Map(t.beforeSnap),n=e.peekWriteCapture();if(n){let f=$h(n);Gh(e,n,f,i,r)}let a=t.sirDetection,o=a==="before-diff"?Aa(i,e,r):[],s=Kh(t.correlativeShifts,r),c=await mi(e,i,r,s),l=a==="after-diff"?Aa(i,e,r):o,d=t.warnings??[],u=Vh(t.links??[],n?jh(e,n):[]);return{source:t.source,activities:c,links:u,calendars:[],trackingEvents:t.trackingEvents??[],...l.length>0?{effects:l}:{},...d.length>0?{warnings:d}:{}}}function jh(e,t){let r=[];for(let i of t.ops){if(i.kind!=="link-field")continue;let n=e.getLink(i.linkId);if(!n)continue;let a={};for(let o of["freeSlackHours","isCritical"])Object.is(i.before[o],n[o])||(a[o]={before:i.before[o],after:n[o]});Object.keys(a).length!==0&&r.push({id:i.linkId,kind:"updated",fields:a,after:St(n)})}return r}function Vh(e,t){let r=[],i=new Map;for(let n of e){let a=i.get(n.id);if(a===void 0){i.set(n.id,r.length),r.push(n);continue}let o=r[a];if((o.kind==="updated"||o.kind==="created")&&n.kind==="updated"){r[a]={...o,fields:{...o.fields,...n.fields},after:n.after};continue}r[a]=n}for(let n of t){let a=i.get(n.id);if(a===void 0){i.set(n.id,r.length),r.push(n);continue}let o=r[a];if(o.kind==="deleted")continue;let s=o.kind==="created"?Object.fromEntries(Object.entries(n.fields??{}).map(([c,l])=>[c,{before:void 0,after:l.after}])):n.fields;r[a]={...o,fields:{...o.fields,...s},after:n.after}}return r}function Kh(e,t){if(!e||e.length===0)return;let r=new Map;for(let i of e)r.set(i.activityId,i.before),t.add(i.activityId);return r}function Yh(e,t){let r=new Set;for(let i of t.touchedIds)r.add(i);for(let i of t.scheduledIds)r.add(i);if(t.includeAllIds)for(let i of e.getAllIds())r.add(i);return r}function Gh(e,t,r,i,n){for(let a of t.dirty){if(r.has(a)||i.has(a))continue;let o=t.before.get(a),s=e.getActivity(a);!o||!s||Object.keys(Bn(o,s)).length!==0&&(i.set(a,o),n.add(a))}}function $h(e){return new Set(e.ops.filter(t=>t.kind==="insert").map(t=>t.activityId))}function Je(e,t,r){let i=[];for(let{op:n,finalLinkId:a,rejected:o}of e){if(o!==null)continue;if(n.kind==="create"){if(!a)continue;let d=r.getLink(a);if(!d)continue;let u=t.get(a);if(u){let f={};String(u.source)!==String(d.source)&&(f.source={before:String(u.source),after:String(d.source)}),String(u.target)!==String(d.target)&&(f.target={before:String(u.target),after:String(d.target)}),u.type!==d.type&&(f.type={before:u.type,after:d.type}),Number(u.lag)!==Number(d.lag)&&(f.lag={before:Number(u.lag),after:Number(d.lag)}),Object.keys(f).length>0&&i.push({id:String(a),kind:"updated",fields:f,after:St(d)});continue}i.push({id:String(a),kind:"created",fields:{source:{before:void 0,after:String(d.source)},target:{before:void 0,after:String(d.target)},type:{before:void 0,after:d.type},lag:{before:void 0,after:Number(d.lag)}},after:St(d)});continue}if(n.kind==="delete"){if(r.getLink(n.linkId))continue;let d=t.get(n.linkId);i.push({id:String(n.linkId),kind:"deleted",fields:d?{source:{before:String(d.source),after:void 0},target:{before:String(d.target),after:void 0},type:{before:d.type,after:void 0},lag:{before:Number(d.lag),after:void 0}}:void 0,after:null});continue}let s=t.get(n.linkId),c=r.getLink(n.linkId);if(!c)continue;let l={};s&&s.type!==c.type&&(l.type={before:s.type,after:c.type}),s&&Number(s.lag)!==Number(c.lag)&&(l.lag={before:Number(s.lag),after:Number(c.lag)}),i.push({id:String(n.linkId),kind:"updated",fields:l,after:St(c)})}return i}function Xe(e,t){let r=new Map;if(!e.getActivity(t))return r;for(let i of e.getIncomingLinkIds(t)){let n=e.getLink(i);n&&r.set(String(n.id),Number(n.lag))}return r}function Qe(e,t,r){let i=[];if(!t.getActivity(r))return i;for(let n of t.getIncomingLinkIds(r)){let a=t.getLink(n);if(!a)continue;let o=e.get(String(a.id));o===void 0||o===Number(a.lag)||i.push({id:String(a.id),kind:"updated",fields:{lag:{before:o,after:Number(a.lag)}},after:St(a)})}return i}function Pi(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function Pc(e,t,r){let{adapter:i,ctx:n,scheduler:a,sector:o}=r,s=se(e.column);if(!s)return{ok:!1,reason:v.NO_PIPELINE_FOR_COLUMN};e.column===S.DURATION&&a.invalidateExpandedLinksCache();let c=n.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};let l=s.canEdit(c,n.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??v.CANNOT_EDIT,alertKey:l.alertKey};let d=s.parseInput(e.newValue,c,n);if(!d.ok)return{ok:!1,reason:d.reason??v.PARSE_ERROR};let u=Reflect.get(c,s.targetField),f=s.validate(c,u,d.value,n);if(!f.valid)return{ok:!1,reason:f.reason??v.INVALID,alertKey:f.notification?.messageKey};if(e.column===S.CUSTOM_ID&&d.value!==null){let I=i.getActivity(e.activityId),_=I?I.customId:null,j=typeof _=="string"?_:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),j))return{ok:!1,reason:v.CUSTOM_ID_DUPLICATE}}let p=s.transform(c,d.value,n,d.raw),y=ce(e.activityId,p),g=await Q(i,y),C=Xe(i,String(e.activityId)),R=c.constraintDate;le(i,e.activityId,p),re(e.activityId,p.postProcessors??[],i,g.get(String(e.activityId))??null);let A=Qe(C,i,String(e.activityId));if(e.column===S.CUSTOM_ID){let I=g.get(String(e.activityId)),_=I?I.customId:null,j=typeof _=="string"?_:null,W=typeof d.value=="string"?d.value:null;j!==W&&r.customIdTracker.trackCustomIdChange(j,W)}let k=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:I=>gi(e.activityId,y,I),now:r.now,options:t}),m=Di(e.column),{scheduledIds:L}=await(m?Ri({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:k(),revertTargets:_i(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:R}],revert:(I,_)=>Ei(I,_,i,n.calendars)}):q({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},k())),F=(p.trackingEvents??[]).map(I=>({name:I.name,properties:I.properties??{}})),T=Ge(e.activityId,p.constraintWarning);return{ok:!0,changes:await K(i,{source:e,beforeSnap:g,touchedIds:y,scheduledIds:L,sirDetection:"before-diff",links:A,trackingEvents:F,...T?{warnings:[T]}:{},hoursPerDay:o.hoursPerDay})}}var zh=new Set(Object.values(U));function Li(e){return typeof e=="string"&&zh.has(e)}function Oi(e,t){return Object.hasOwn(e,t)}function qh(e){if(e.kind===P.LINK_CREATE)return Li(e.type)?e.lag===void 0||Number.isFinite(e.lag)?null:v.INVALID_LINK_LAG:v.INVALID_LINK_TYPE;if(e.kind===P.LINK_UPDATE){if(Oi(e,"type")&&!Li(e.type))return v.INVALID_LINK_TYPE;if(Oi(e,"lag")&&!Number.isFinite(e.lag))return v.INVALID_LINK_LAG}return null}function Jh(e){return e.kind===tt.CREATE?Li(e.type)?e.lag===void 0||Number.isFinite(e.lag)?null:v.INVALID_LINK_LAG:v.INVALID_LINK_TYPE:e.kind===tt.UPDATE?Oi(e,"type")&&!Li(e.type)?v.INVALID_LINK_TYPE:!Oi(e,"lag")||Number.isFinite(e.lag)?null:v.INVALID_LINK_LAG:e.kind===tt.DELETE?null:v.INVALID_VALUE}function Xh(e){for(let t of e){let r=Jh(t);if(r!==null)return r}return null}function Qh(e,t){let r=new Set,i=new Map;for(let n of e){if(n.kind===tt.CREATE){r.add(String(n.source)),r.add(String(n.target));continue}let a=t.getLink(n.linkId);a&&(r.add(String(a.source)),r.add(String(a.target)),i.set(n.linkId,{...a}))}return{activityIds:r,links:i}}function Zh(e,t,r,i){return e.map((n,a)=>{let o=n.kind===tt.CREATE?i?.get(a):void 0,s=te(n,{port:t,newLinkId:o?()=>o:r.next});return{op:n,finalLinkId:s.applied?s.linkId:null,rejected:s.applied?null:s.rejected??v.INVALID}})}function tm(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function Lc(e,t,r){let i=qh(e);return i!==null?{ok:!1,reason:i}:Ia([om(e,r.sector.hoursPerDay)],e,t,r,e.kind===P.LINK_CREATE&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function Oc(e,t,r){let i=Xh(e.operations);if(i!==null)return{ok:!1,reason:i};let{hoursPerDay:n}=r.sector,a=e.operations.map(s=>im(s,n)),o=em(e.operations);return Ia(a,e,t,r,o)}function em(e){let t=new Map;return e.forEach((r,i)=>{r.kind===tt.CREATE&&r.linkId&&t.set(i,r.linkId)}),t.size>0?t:void 0}function rm(e,t){if(e===void 0)return;let r=new Map,i=new Set,n=()=>{let a=t.linkIdGen.next();for(;t.adapter.getLink(a)!==null||t.isLinkIdReserved(String(a))||i.has(String(a));)a=t.linkIdGen.next();return a};for(let[a,o]of e){let s=t.adapter.getLink(o)!==null||t.isLinkIdReserved(String(o))||i.has(String(o)),c=s?n():o;s||t.linkIdGen.bump(o),i.add(String(c)),r.set(a,c)}return r}function im(e,t){return e.kind===tt.CREATE?{kind:tt.CREATE,source:e.source,target:e.target,type:e.type,lag:Pt(e.lag??0,t)}:e.kind===tt.UPDATE?{kind:tt.UPDATE,linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:Pt(e.lag,t)}:{kind:tt.DELETE,linkId:e.linkId}}async function Ia(e,t,r,i,n){let{adapter:a,scheduler:o,sector:s,linkIdGen:c}=i;o.invalidateAllCaches();let{activityIds:l,links:d}=Qh(e,a),u=await Q(a,l),f=Zh(e,a,c,rm(n,i));if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!==P.INLINE_EDIT)return{ok:!1,reason:f[0].rejected};let p=nm(f,d,a),{scheduledIds:y}=await q({adapter:a,scheduler:o,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:i.now,options:r}),g=Je(f,d,a);return{ok:!0,linkVerdicts:f.map((C,R)=>C.rejected===null?{operationIndex:R,kind:C.op.kind,ok:!0,linkId:String(C.finalLinkId)}:{operationIndex:R,kind:C.op.kind,ok:!1,reason:C.rejected}),__beforeLinks:tm(d),changes:await K(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:y,links:g,hoursPerDay:s.hoursPerDay})}}function nm(e,t,r){for(let i of e){if(i.rejected!==null)continue;let n=am(i.op,t,r);if(n!==null)return r.hasChildren(n)?"roots":String(n)}return null}function am(e,t,r){return e.kind===tt.CREATE?e.target:e.kind===tt.DELETE?t.get(e.linkId)?.target??null:r.getLink(e.linkId)?.target??null}function om(e,t){return e.kind===P.LINK_CREATE?{kind:tt.CREATE,source:e.source,target:e.target,type:e.type,lag:Pt(e.lag??0,t)}:e.kind===P.LINK_UPDATE?{kind:tt.UPDATE,linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:Pt(e.lag,t)}:{kind:tt.DELETE,linkId:e.linkId}}async function bc(e,t,r){let{adapter:i,sector:n}=r;if(typeof e.newValue!="string")return{ok:!1,reason:v.INVALID_VALUE};if(!i.getActivity(e.activityId))return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};let o=e.column===S.CUSTOM_PREDECESSORS,{specs:s}=Zr(e.newValue),c=s.map(y=>({...y,lag:Pt(ii(y.lag),n.hoursPerDay)})),l=new Map;i.forEachActivity(y=>{y.correlativeId!=null&&l.set(String(y.correlativeId),y.id)});let d=y=>l.get(y)??null,u=o?i.getIncomingLinkIds(e.activityId):i.getOutgoingLinkIds(e.activityId),f=[];for(let y of u){let g=i.getLink(y);g&&f.push(g)}let p=o?ei({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):ri({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return Ia(p.operations,e,t,r)}var Ot={ACTIVITY_CREATION:"schedule_activity_creation",ACTIVITY_DELETION:"schedule_activity_deletion",ACTIVITY_MOVE:"schedule_activity_move",ACTIVITY_INDENT:"schedule_activity_indent",ACTIVITY_OUTDENT:"schedule_activity_outdent"};function At(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(a=>{N(a.parentId)&&t.push(a)}),t.sort(Fc);let r=[];Nc(r,t);let i=[],n=0;for(;r.length>0;){let a=r.pop();if(a.correlativeId!==n){let s=typeof a.correlativeId=="number"?a.correlativeId:void 0;i.push({activityId:String(a.id),before:s}),s!==void 0&&e.noteCorrelativeBefore?.(String(a.id),s),sm(a,n)}n+=1;let o=lr(String(a.id),e);o.sort(Fc),Nc(r,o)}return i}function Nc(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function wc(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Cn}var Fc=(e,t)=>wc(e)-wc(t);function sm(e,t){e.correlativeId=t}function va(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let{workHours:i,realWorkHours:n}=Uc(r,t);t.setActivityField(r,b.WORK_HOURS,i),t.setActivityField(r,b.REAL_WORK_HOURS,n);let a=t.getActivity(r);if(!a)break;let o=a.parentId;if(!o||N(o))break;r=o}}function xc(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||N(i)||va(i,t)}function Mc(e,t,r){for(let i of e){if(r.hasChildren(i))continue;let n=r.getActivity(i);n&&r.setActivityField(i,b.REAL_WORK_HOURS,Ct(Er(n,b.WORK_HOURS),Er(n,b.PROGRESS)))}for(let i of t)r.setActivityField(i,b.REAL_WORK_HOURS,Uc(i,r).realWorkHours)}function Uc(e,t){let r=0,i=0;for(let n of t.getChildren(e)){let a=t.getActivity(n);if(!a)continue;let o=Er(a,b.WORK_HOURS);r+=o,i+=cm(n,a,o,t)}return{workHours:r,realWorkHours:i}}function Er(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function cm(e,t,r,i){return i.hasChildren(e)?Er(t,b.REAL_WORK_HOURS):Ct(r,Er(t,b.PROGRESS))}function Ca(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0;for(let s of i){let c=t.getActivity(s);c&&(n+=lm(c,b.USED_COST))}t.setActivityField(r,b.USED_COST,n);let a=t.getActivity(r);if(!a)break;let o=a.parentId;if(!o||N(o))break;r=o}}function Bc(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||N(i)||Ca(i,t)}function lm(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Sa(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0;for(let s of i){let c=t.getActivity(s);c&&(n+=dm(c,b.COST))}t.setActivityField(r,b.COST,n);let a=t.getActivity(r);if(!a)break;let o=a.parentId;if(!o||N(o))break;r=o}}function Wc(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||N(i)||Sa(i,t)}function dm(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var bi=Object.freeze({proplannerId:null,description:"",type:"task",progress:0,constraintType:"asap",constraintDate:null,autoScheduling:!0,assignedDefaultCalendar:!1,dateOrigin:null,cost:0,usedCost:0,realCost:0,workHours:0,realWorkHours:0,ponderator:0,hasCustomPonderator:!1,correlativeId:0,customId:null,subcontractId:null,isLookahead:!1,hasLookaheadTasks:!1,newActivityIds:[],hasNewActivities:!1,pendingRequestIds:[],responsableIds:[],tagIds:[],baselinePoints:[],baselineSnapshot:null,recursiveDurationHours:0,isCritical:!1,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}),Hc="New Master Plan",jc="New Activity";var um=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],Ni=new Set(um);function fm(e){let t=Object.getPrototypeOf(e);if(t!==null&&t!==Object.prototype)throw new Error("activity-create: override bag must be a plain object with no custom prototype");for(let r of Reflect.ownKeys(e))if(typeof r=="symbol"||!Ni.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function Vc(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,i=fm(e.activityOverrides??{}),n=e.numTasksInGantt===0?Hc:jc,a=i.name??n,o=i.durationHours??e.sector.hoursPerDay,s=i.calendarId??e.sector.defaultCalendar,c=pm(r,e.fallbackStartDate,i.startDate),l={...bi,...i,id:e.id,parentId:e.parentId,uniqueCorrelativeId:e.nextUniqueCorrelativeId,name:a,durationHours:o,calendarId:s,startDate:c,endDate:c},d=i.startDate?new Date(l.startDate):t.getClosestWorkTime({date:l.startDate,dir:rt.FUTURE,task:l});if(!i.startDate&&r&&Vt(r.type)){let p=new Date(r.startDate);p.setUTCHours(0,0,0,0);let y=new Date(d);y.setUTCHours(0,0,0,0),y.getTime()!==p.getTime()&&(d=t.getClosestWorkTime({date:p,dir:rt.FUTURE,task:l}))}let u=t.calculateEndDate({startDate:d,durationHours:l.durationHours,task:l});return{newTask:{...l,startDate:d,endDate:u,calendarDuration:Wt({type:l.type,startDate:d,endDate:u}),newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function pm(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function ym(e){let t=e.type;if(t!=="task"&&t!=="milestone")return null;let r=e.startDate,i=e.endDate;return!(r instanceof Date)||!(i instanceof Date)?null:{type:t,startDate:new Date(r),endDate:new Date(i),durationHours:Number(e.durationHours??0),expectedProgressBaseline:typeof e.expectedProgressBaseline=="number"?e.expectedProgressBaseline:null,constraintType:e.constraintType??null,constraintDate:e.constraintDate instanceof Date?new Date(e.constraintDate):null,progress:Number(e.progress??0)}}function Ze(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&Zt(t.type):hm(t),i=Array.isArray(t.newActivityIds)?t.newActivityIds:[],a={isLookahead:!1,hasNewActivities:!0,newActivityIds:i.some(o=>String(o)===String(e.newChildId))?[...i]:[...i,e.newChildId]};return t.customId!=null&&t.customId!==""&&(a.customId=null),r&&(a.type=_n,(e.promotionSource??"create")==="create"&&(a.constraintType=H.ASAP,a.constraintDate=null)),{parentId:e.parentId,fields:a,promotionSnapshot:ym(t)}}function hm(e){return Zt(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function wi(e,t,r,i){let n=t,a=n==="0",o=ka(e,n);if(i!==void 0){let c=o.find(l=>l.id===i);if(c){let l=It(c),d=o.map(It).filter(f=>f<l);return d.length===0?l-1:(Math.max(...d)+l)/2}}if(r!==void 0){let c=o.find(l=>l.id===r);if(c){let l=It(c),d=o.map(It).filter(f=>f>l);if(d.length===0)return l+1;let u=Math.min(...d);return(l+u)/2}}return o.length===0?0:Math.max(...o.map(It))+1}var De=Number.MAX_SAFE_INTEGER,Kc=Number.MAX_SAFE_INTEGER-1;function It(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:De}function ka(e,t){return lr(t,e)}function Yc(e,t,r){let i=e,n=ue(e,r);for(;n!=null&&t.has(n);)i=n,n=ue(n,r);return i}function Fi(e,t,r){let i=new Set([e]),n=Qt(r.getActivity(e)?.parentId);for(;n!=="0"&&!i.has(n);){if(t.has(n))return!0;i.add(n),n=Qt(r.getActivity(n)?.parentId)}return!1}function ue(e,t){let r=t.getActivity(e);if(!r)return null;let i=Qt(r.parentId),n=Rt(i,t),a=n.findIndex(o=>String(o)===String(e));return a<=0?null:n[a-1]??null}function Gc(e,t,r,i){let n=Rt(t,e).filter(c=>String(c)!==String(i)).map(c=>e.getActivity(c)).filter(c=>c!==null);if(n.length===0)return 0;let a=n.map(It);if(r<=0)return a[0]-1;if(r>=a.length)return a[a.length-1]+1;let o=a[r-1],s=a[r];return(o+s)/2}var mm=new Set([...[...Ni].filter(e=>e!=="durationHours"),"durationDays"]);function xi(e,t){if(e===void 0)return{ok:!0,value:{}};let r=Object.getPrototypeOf(e);if(r!==null&&r!==Object.prototype)return{ok:!1,reason:v.INVALID_VALUE};for(let a of Reflect.ownKeys(e))if(typeof a=="symbol"||!mm.has(a))return{ok:!1,reason:v.INVALID_VALUE};let{durationDays:i,...n}=e;return i!==void 0&&(!Number.isFinite(i)||i<0)?{ok:!1,reason:v.INVALID_VALUE}:{ok:!0,value:{...n,...i===0&&(n.type===void 0||n.type==="task")?{type:"milestone"}:{},...i===void 0?{}:{durationHours:ge(i,t)}}}}async function Rr(e,t,r={}){let{adapter:i,scheduler:n,sector:a,calendars:o,activityIdGen:s,uidGen:c}=t;r.skipCacheInvalidation||n.invalidateAllCaches();let l=gm(e,i);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=Im(e.activityId,i,s,t.isActivityIdReserved),y=c.next(),g={id:p,parentId:f?null:e.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:Dm(o)},numTasksInGantt:i.activityCount(),nextUniqueCorrelativeId:y,activityOverrides:e.overrides??{}},R=Vc(g,{getActivity:I=>i.getActivity(I),calculateEndDate:I=>i.calculateEndDate(I),getClosestWorkTime:I=>i.getClosestWorkTime(I)}).newTask;R.realWorkHours=Ct(R.workHours,R.progress),Cm(R,e,t,u,d,r);let A=r.insertionCorrelativeId??wi(i,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);R.correlativeId=A;let k=new Set([p]);d&&k.add(d.id);let m=d!==null&&i.getChildren(d.id).length===0,L=m?d?.customId:null,F=r.skipBeforeSnap?new Map:await Q(i,k);i.addActivity(R),Sm(e,p,d,i,m),L&&t.customIdTracker.releaseCustomId(L),r.skipRollupCascades||(xc(p,i),Bc(p,i),Wc(p,i));let T=km(i,p,k,r);return{ok:!0,newId:p,parent:d,newActivity:R,beforeSnap:F,initialTouched:k,correlativeShifts:T}}function gm(e,t){let r=N(e.parentId),i=r?null:t.getActivity(e.parentId);if(!r&&!i)return{ok:!1,reason:v.PARENT_NOT_FOUND};if(i!==null&&we(i))return{ok:!1,reason:v.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:v.ANCHOR_SIBLING_CONFLICT};let o=e.afterSiblingId??e.beforeSiblingId,s=Am(e,t,r,o);return s||{ok:!0,parent:i,anchorSiblingId:o,isRoot:r}}function Am(e,t,r,i){if(i===void 0)return null;let n=t.getActivity(i);if(!n)return{ok:!1,reason:v.ANCHOR_SIBLING_NOT_FOUND};let a=r?"0":e.parentId;return(n.parentId==null?"0":String(n.parentId))!==a?{ok:!1,reason:v.ANCHOR_SIBLING_WRONG_PARENT}:null}function Im(e,t,r,i){let n=()=>{let a=r.next();for(;t.activityExists(a)||i(String(a));)a=r.next();return a};return e===void 0||t.activityExists(e)||i(String(e))?n():(r.bump(e),e)}function vm(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function Cm(e,t,r,i,n,a){let{adapter:o,customIdTracker:s}=r,c=vm(t);if(c!==void 0){if(c.length===0)return;if(!s.isCustomIdInUse(c)){s.registerCustomId(c);return}}let l=a.customIdReferenceId??i,d=l!==void 0,u=d?o.getActivity(l):n;e.customId=s.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function Sm(e,t,r,i,n){if(!r)return;let a=Ze({parentId:e.parentId,newChildId:t,isCurrentlyLeaf:n,getParent:o=>i.getActivity(o)??null});if(a){for(let[o,s]of Object.entries(a.fields))st(i,a.parentId,o,s);a.promotionSnapshot&&i.setPromotionSnapshot(a.parentId,a.promotionSnapshot)}}function km(e,t,r,i){if(i.skipCorrelativeRecompute)return[];let n=At(e).filter(a=>a.activityId!==String(t));for(let a of n)r.add(a.activityId);return n}async function Tm(e,t,r,i,n){let{newId:a,newActivity:o,beforeSnap:s,initialTouched:c,correlativeShifts:l}=r,d={name:Ot.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:a,created_duration:o.durationHours}};return t.eventSource!==void 0&&(d.properties.event_source=t.eventSource),K(e,{source:t,beforeSnap:s,touchedIds:c,scheduledIds:i,correlativeShifts:l,trackingEvents:[d],hoursPerDay:n})}async function $c(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,o=xi(e.overrides,a.hoursPerDay);if(!o.ok)return o;let s=await Rr({...e,overrides:o.value},r);if(!s.ok)return s;let{newId:c}=s,l=s.newActivity.autoScheduling;i.setActivityField(c,"autoScheduling",!1);let d;try{d=await q({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:c,recomputeParentsFrom:[c],preventSummaryTargetPullback:!0,now:r.now,options:t})}finally{i.setActivityField(c,"autoScheduling",l)}let{scheduledIds:u}=d;return{ok:!0,changes:await Tm(i,e,s,u,a.hoursPerDay)}}function Dm(e){for(let r of e.values())if(r.is_default)return r.id;let t=e.values().next();return!t.done&&t.value?t.value.id:"global"}function xt(e,t){va(e,t),Ca(e,t),Sa(e,t)}function zc(e,t){let r=new Set,i=[];for(let n of e){let a=String(n);r.has(a)||(r.add(a),i.push(a))}for(;i.length>0;){let n=i.pop(),a=t.getChildren(n);for(let o of a){let s=String(o);r.has(s)||(r.add(s),i.push(s))}}return r}function qc(e,t){let r=new Set;for(let i of e){for(let n of t.getOutgoingLinkIds(i))r.add(String(n));for(let n of t.getIncomingLinkIds(i))r.add(String(n))}return[...r]}function _m(e){return e?{type:e.type,startDate:new Date(e.startDate),endDate:new Date(e.endDate),durationHours:e.durationHours,expectedProgressBaseline:e.expectedProgressBaseline,constraintType:e.constraintType,constraintDate:e.constraintDate?new Date(e.constraintDate):null,progress:e.progress}:null}function Em(e,t,r){let i=e.startDate;return!r||!(i instanceof Date)?{}:{endDate:r(i,t)}}function tr(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,i=Number.isFinite(r),n=_m(e.promotionSnapshot)??(i?{type:Ue,durationHours:r,progress:0,autoScheduling:!0,constraintType:"asap",constraintDate:null,hasNewActivities:!1,...Em(t,r,e.computeEndDate)}:{type:Ue});if(e.idsRemoved&&e.idsRemoved.size>0){let a=Array.isArray(t.newActivityIds)?t.newActivityIds:[];if(a.length>0){let o=a.filter(s=>!e.idsRemoved.has(s)&&!e.idsRemoved.has(String(s)));o.length!==a.length&&(n.newActivityIds=o)}}return t.hasLookaheadTasks&&(n.isLookahead=!0),{parentId:String(t.id),fields:n}}function Jc(e){if(e.idsRemoved.size===0)return null;let t=e.parent.newActivityIds;if(!Array.isArray(t)||t.length===0)return null;let r=t,i=r.filter(n=>!e.idsRemoved.has(n)&&!e.idsRemoved.has(String(n)));return i.length===r.length?null:{parentId:String(e.parent.id),fields:{newActivityIds:[...i],hasNewActivities:i.length>0}}}var Xc=200;async function Qc(e,t,r){let{adapter:i,scheduler:n,customIdTracker:a,sector:o}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:v.ACTIVITY_IDS_EMPTY};for(let I of e.activityIds)if(!i.getActivity(I))return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};let s=e.activityIds.filter(I=>{let _=i.getActivity(I);return!(_?.correlativeId===0&&_.type===Dt.PROJECT)}),c=zc(s,i),l=qc(c,i),d=new Set;for(let I of e.activityIds){let _=i.getActivity(I);if(!_)continue;let j=_.parentId;if(N(j))continue;let W=String(j);c.has(W)||d.add(W)}let u=new Set([...c,...d]),f=await Q(i,u),p=new Map;for(let I of l){let _=i.getLink(I);_&&p.set(I,{..._})}let y=new Set,g=0;for(let I of c){g+=1,g%Xc===0&&await it();let _=i.getActivity(I);if(!_)continue;let j=N(_.parentId)?null:i.getActivity(String(_.parentId)),W=j?.hasNewActivities===!0&&j.newActivityIds.some(J=>String(J)===String(I));(_.isNewActivity===!0||W)&&y.add(I);let Z=_.customId;typeof Z=="string"&&Z.length>0&&a.releaseCustomId(Z)}for(let I of l)i.removeLink(I);let C=Ta(i,c),R=0;for(let I of c)R+=1,R%Xc===0&&await it(),i.removeActivity(I);for(let I of d){let _=i.getActivity(I);if(!_)continue;Pm(_,y,i);let j=i.getChildren(I),W=tr({parent:_,remainingChildIds:j.map(String),defaultDurationHours:o.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(I),computeEndDate:(Z,J)=>i.calculateEndDate({startDate:Z,durationHours:J,task:_}),idsRemoved:c});if(!W){ai(I,i);continue}for(let[Z,J]of Object.entries(W.fields))st(i,I,Z,J);if(_.customId==null||_.customId===""){let Z=ue(I,i),J=Z?i.getActivity(Z)?.customId:null,ht=a.generateCustomIdForRestoredChild(typeof J=="string"&&J?J:null);i.setActivityField(I,b.CUSTOM_ID,ht)}}for(let I of d)xt(I,i);let A=At(i),{scheduledIds:k}=await q({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:d,now:r.now,options:t}),m={name:Ot.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:c.size}};e.eventSource!==void 0&&(m.properties.event_source=e.eventSource);let L=new Map;for(let[I,_]of p)L.set(I,_);let F=new Map;for(let I of c){let _=f.get(String(I));_&&F.set(String(I),_)}let T=await K(i,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:k,sirDetection:"after-diff",links:Lm(p),trackingEvents:[m],hoursPerDay:o.hoursPerDay,correlativeShifts:A});return{ok:!0,changes:C.length>0?{...T,viewState:C}:T,__beforeSnap:F,__beforeLinks:L}}function Pm(e,t,r){let i=Jc({parent:e,idsRemoved:t});if(i)for(let[n,a]of Object.entries(i.fields))st(r,i.parentId,n,a)}function Ta(e,t){let r=[];for(let i of t){let n=e.isChecked(i),a=e.isVisible(i);!n&&a||r.push({activityId:String(i),...n?{checked:{before:!0,after:!1}}:{},...a?{}:{visible:{before:!1,after:!0}}})}return r}function Lm(e){let t=[];for(let[r,i]of e.entries())t.push({id:r,kind:"deleted",fields:{source:{before:String(i.source),after:void 0},target:{before:String(i.target),after:void 0},type:{before:i.type,after:void 0},lag:{before:Number(i.lag),after:void 0}},after:null});return t}async function el(e,t,r){let i=Om(e,r);if(i)return{ok:!1,reason:i};let n=Nm(e,r);if(!n.ok)return n;let a=e.mode===ot.REPLACE?new Set(r.adapter.getAllIds().map(m=>String(m))):new Set,o=e.mode===ot.REPLACE?await Q(r.adapter,a):new Map,s=e.mode===ot.REPLACE?Bm(r):new Map,c=e.mode===ot.REPLACE?Ta(r.adapter,a):[];r.scheduler.invalidateAllCaches();let l=[];if(e.mode===ot.REPLACE){for(let m of s.keys()){let L=te({kind:tt.DELETE,linkId:m},{port:r.adapter});if(!L.applied)return{ok:!1,reason:L.rejected??v.INVALID};l.push({op:{kind:tt.DELETE,linkId:m},finalLinkId:m,rejected:null})}for(let m of a){let L=r.adapter.getActivity(m)?.customId;typeof L=="string"&&L.length>0&&r.customIdTracker.releaseCustomId(L),r.adapter.removeActivity(m)}}let d=await Um(e,n.plan.items,r);if(!d.ok)return d;let u=rl(e)?[]:At(r.adapter),f=new Set(n.plan.items.map(m=>String(m.activityId))),p=u.filter(m=>!f.has(m.activityId)),y=e.mode===ot.REPLACE?new Set(a):new Set;Ai(r.adapter,u,f,o,y);for(let m of n.plan.items)y.add(String(m.activityId));let g=n.plan.links.map(m=>({operation:{kind:tt.CREATE,source:m.source,target:m.target,type:m.type,lag:Pt(m.lag??0,r.sector.hoursPerDay)},linkId:m.linkId})),C=Qr(g,{port:r.adapter,preserved:s});if(!C.applied)return{ok:!1,reason:C.rejected??v.INVALID};for(let{operation:m,linkId:L}of g)l.push({op:m,finalLinkId:L,rejected:null});let R=n.plan.items.map(m=>m.activityId),{scheduledIds:A}=await q({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.items.length>0||e.links.length>0?"roots":null,recomputeParentsFrom:R,now:r.now,options:t}),k=await K(r.adapter,{source:e,beforeSnap:o,touchedIds:y,scheduledIds:A,links:Je(l,s,r.adapter),hoursPerDay:r.sector.hoursPerDay,correlativeShifts:p,...e.mode===ot.REPLACE?{sirDetection:"after-diff"}:{}});return{ok:!0,changes:c.length>0?{...k,viewState:c}:k,...e.mode===ot.REPLACE?{__beforeSnap:o,__beforeLinks:Wm(s)}:{}}}function Om(e,t){if(e.mode!==ot.APPEND&&e.mode!==ot.REPLACE)return v.INVALID;let r=new Set,i=new Set;for(let a of e.items){if(a.batchId.length===0||r.has(a.batchId))return v.INVALID;if(r.add(a.batchId),a.index!==void 0&&(!Number.isInteger(a.index)||a.index<0))return v.INVALID;if(a.activityId!==void 0){let o=String(a.activityId);if(o.length===0||o==="0"||i.has(o))return v.INVALID;i.add(o)}}for(let a of e.items)if(!Da(a.parent,!0,e.mode,r,t))return v.PARENT_NOT_FOUND;if(bm(e.items))return v.INVALID;let n=new Set;for(let a of e.links){if(!Object.values(U).includes(a.type))return v.INVALID_LINK_TYPE;if(a.lag!==void 0&&!Number.isFinite(a.lag))return v.INVALID_LINK_LAG;if(!Da(a.source,!1,e.mode,r,t)||!Da(a.target,!1,e.mode,r,t))return v.ACTIVITY_NOT_FOUND;if(a.linkId!==void 0){let o=String(a.linkId);if(o.length===0||n.has(o))return v.INVALID;n.add(o)}}return null}function Da(e,t,r,i,n){return typeof e=="string"?e==="0"?t:r===ot.APPEND&&n.adapter.getActivity(String(e))!==null:e!==null&&e.batchId.length>0&&i.has(e.batchId)}function bm(e){let t=new Map;for(let i of e)typeof i.parent!="string"&&t.set(i.batchId,i.parent.batchId);let r=new Set;for(let i of e){let n=new Set,a=i.batchId;for(;a!==void 0&&!r.has(a);){if(n.has(a))return!0;n.add(a),a=t.get(a)}for(let o of n)r.add(o)}return!1}function Nm(e,t){let r=new Map;for(let d of e.items){let u=xi(d.overrides,t.sector.hoursPerDay);if(!u.ok)return u;r.set(d.batchId,u.value)}let i=new Map,n=new Set;for(let d of e.items){let u=wm(d.activityId,e.mode,n,t);n.add(String(u)),i.set(d.batchId,u)}let a=new Set,o=e.links.map(d=>{let u=Fm(d.linkId,e.mode,a,t);return a.add(String(u)),u}),s=xm(e,i,t),c=[];for(let d of e.items){let u=i.get(d.batchId),f=s.get(d.batchId);if(u===void 0||f===void 0)return{ok:!1,reason:v.INVALID};let p=typeof d.parent=="string"?null:d.parent.batchId,y=typeof d.parent=="string"?d.parent:i.get(d.parent.batchId);if(y===void 0)return{ok:!1,reason:v.PARENT_NOT_FOUND};c.push({input:d,activityId:u,parentId:y,parentBatchId:p,insertionCorrelativeId:f,overrides:r.get(d.batchId)??{}})}let l=[];for(let[d,u]of e.links.entries()){let f=tl(u.source,i),p=tl(u.target,i),y=o[d];if(f===null||p===null||y===void 0)return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};l.push({source:f,target:p,type:u.type,lag:u.lag??0,linkId:y})}return{ok:!0,plan:{items:c,links:l}}}function wm(e,t,r,i){if(e!==void 0&&(t===ot.REPLACE||i.adapter.getActivity(e)===null&&!i.isActivityIdReserved(String(e)))&&!r.has(String(e)))return i.activityIdGen.bump(e),e;let a=i.activityIdGen.next();for(;r.has(String(a))||t===ot.APPEND&&(i.adapter.getActivity(a)!==null||i.isActivityIdReserved(String(a)));)a=i.activityIdGen.next();return a}function Fm(e,t,r,i){if(e!==void 0&&(t===ot.REPLACE||i.adapter.getLink(e)===null&&!i.isLinkIdReserved(String(e)))&&!r.has(String(e)))return i.linkIdGen.bump(e),e;let a=i.linkIdGen.next();for(;r.has(String(a))||t===ot.APPEND&&(i.adapter.getLink(a)!==null||i.isLinkIdReserved(String(a)));)a=i.linkIdGen.next();return a}function xm(e,t,r){if(rl(e)){let s=r.adapter.activityCount();return new Map(e.items.map((c,l)=>[c.batchId,s+l]))}let i=new Set(Array.from(t.values(),s=>String(s))),n=new Map;for(let s of e.items){let c=t.get(s.batchId);if(c===void 0)continue;let l=typeof s.parent=="string"?s.parent:t.get(s.parent.batchId);if(l===void 0)continue;let d=String(l),u=n.get(d);u||(u={existing:e.mode===ot.REPLACE||typeof s.parent!="string"&&t.has(s.parent.batchId)?[]:ka(r.adapter,d).sort((g,C)=>It(g)-It(C)||String(g.id).localeCompare(String(C.id))).map(g=>String(g.id)),newIdsByTarget:new Map},n.set(d,u));let f=s.index===void 0?u.existing.length:Math.min(s.index,u.existing.length),p=u.newIdsByTarget.get(f)??[];p.push(String(c)),u.newIdsByTarget.set(f,p)}let a=new Map,o=new Map(Array.from(t,([s,c])=>[String(c),s]));for(let s of n.values()){let c=[];for(let d=0;d<=s.existing.length;d+=1){for(let f of s.newIdsByTarget.get(d)??[])c.push(f);let u=s.existing[d];u!==void 0&&c.push(u)}let l=0;for(;l<c.length;){if(!i.has(c[l])){l+=1;continue}let d=l;for(;l<c.length&&i.has(c[l]);)l+=1;let u=l-d,f=d>0?Zc(c[d-1],r):null,p=l<c.length?Zc(c[l],r):null;for(let y=0;y<u;y+=1){let g=c[d+y],C=o.get(g);C!==void 0&&a.set(C,Mm(f,p,y+1,u))}}}return a}function rl(e){return e.mode===ot.APPEND&&e.items.every(t=>t.parent==="0"&&t.index===void 0)}function Zc(e,t){let r=t.adapter.getActivity(e);return r?It(r):0}function Mm(e,t,r,i){return e!==null&&t!==null&&t>e?e+(t-e)*r/(i+1):e!==null?e+r:t!==null?t-(i-r+1):r-1}async function Um(e,t,r){let i=new Map,n=[];for(let o of t){if(o.parentBatchId===null){n.push(o);continue}let s=i.get(o.parentBatchId)??[];s.push(o),i.set(o.parentBatchId,s)}for(let o=0;o<n.length;o+=1){let s=n[o],c=await Rr({kind:P.ACTIVITY_CREATE,parentId:s.parentId,activityId:s.activityId,overrides:s.overrides,...e.eventSource===void 0?{}:{eventSource:e.eventSource}},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,skipCacheInvalidation:!0,skipRollupCascades:!0,insertionCorrelativeId:s.insertionCorrelativeId});if(!c.ok)return c;for(let l of i.get(s.input.batchId)??[])n.push(l)}if(n.length!==t.length)return{ok:!1,reason:v.INVALID};let a=new Set;for(let o=n.length-1;o>=0;o-=1){let s=n[o].parentId;s==="0"||a.has(String(s))||(a.add(String(s)),xt(s,r.adapter))}return{ok:!0}}function tl(e,t){return typeof e=="string"?e:t.get(e.batchId)??null}function Bm(e){return new Map(e.adapter.getAllLinks().map(t=>[String(t.id),{...t}]))}function Wm(e){return new Map(Array.from(e,([t,r])=>[String(t),r]))}function il(e,t){let{adapter:r}=t,i=e.activityId,n=r.getActivity(i);if(!n)return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};let a=n.pendingRequestIds??[],o=e.pendingRequests.map(l=>l.id);r.setActivityField(e.activityId,"pendingRequestIds",o);let s=r.getActivity(i);if(!s)return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};let c={id:i,kind:"updated",fields:{pendingRequestIds:{before:a,after:o}},after:et(s)};return{ok:!0,changes:{source:e,activities:[c],links:[],calendars:[],trackingEvents:[]}}}function nl(e){let t=new Map;for(let r of e){let i=r.proplannerId;typeof i=="number"&&Number.isSafeInteger(i)&&i>0&&t.set(i,String(r.id))}return t}function al(e,t,r){let i=new Set(t.map(({id:n})=>String(n)));for(let n of e)if((n.proplannerId==null||n.proplannerId===0)&&!i.has(String(n.id)))throw new Error(`persistence-acknowledge: missing ${r} proplannerId for "${String(n.id)}"`)}function Hm(e,t,r,i,n,a){let o=String(e.id);if(o.length===0||n.has(o))throw new Error(`persistence-acknowledge: duplicate or empty ${t} id "${o}"`);if(!Number.isSafeInteger(e.proplannerId)||e.proplannerId<=0)throw new Error(`persistence-acknowledge: invalid ${t} proplannerId ${String(e.proplannerId)}`);if(a.has(e.proplannerId))throw new Error(`persistence-acknowledge: duplicate ${t} proplannerId ${String(e.proplannerId)}`);let s=r(o);if(!s.exists)throw new Error(`persistence-acknowledge: unknown ${t} id "${o}"`);if(s.current!==null&&s.current!==0&&s.current!==e.proplannerId)throw new Error(`persistence-acknowledge: ${t} "${o}" already has proplannerId ${String(s.current)}`);let c=i.get(e.proplannerId);if(c!==void 0&&c!==o)throw new Error(`persistence-acknowledge: ${t} proplannerId ${String(e.proplannerId)} already belongs to "${c}"`);n.add(o),a.add(e.proplannerId)}function ol(e,t,r,i){let n=new Set,a=new Set;for(let o of e)Hm(o,t,r,i,n,a)}async function sl(e,t){let r=e.filter(s=>{let c=t.adapter.getActivity(String(s.activityId));return c!==null&&c.progress!==s.progress}),i=new Set(r.map(s=>String(s.activityId))),n=Ar(t.adapter,i),a=new Set(i);for(let s of n)a.add(String(s));let o=await Q(t.adapter,a);return t.adapter.batchUpdate(()=>{for(let s of r){let c=String(s.activityId);t.adapter.setActivityField(c,"progress",s.progress),t.adapter.setActivityField(c,"autoScheduling",he(s.progress))}ds(n,t.adapter),Mc(i,n,t.adapter)}),[...await mi(t.adapter,o,a)]}async function cl(e,t){let r=e.activities??[],i=e.links??[],n=t.adapter.getAllActivities(),a=t.adapter.getAllLinks(),o=e.checkpoint?.activities??n,s=e.checkpoint?.links??a,c=new Map(o.map(y=>[String(y.id),y])),l=new Map(s.map(y=>[String(y.id),y])),d=nl(o),u=nl(s);ol(r,"activity",y=>{let g=c.get(y);return{exists:g!==void 0,current:g?.proplannerId??null}},d),ol(i,"link",y=>{let g=l.get(y);return{exists:g!==void 0,current:g?.proplannerId??null}},u),al(o,r,"activity"),al(s,i,"link");let f=[],p=[];return t.adapter.batchUpdate(()=>{for(let y of r){let g=t.adapter.getActivity(y.id);if(!g||g.proplannerId===y.proplannerId)continue;let C=g.proplannerId;t.adapter.setActivityField(y.id,"proplannerId",y.proplannerId),f.push({id:y.id,kind:"updated",fields:{proplannerId:{before:C,after:y.proplannerId}},after:{...g,proplannerId:y.proplannerId}})}for(let y of i){let g=t.adapter.getLink(y.id);if(!g||g.proplannerId===y.proplannerId)continue;let C=g.proplannerId;t.adapter.setLinkProplannerId(y.id,y.proplannerId),p.push({id:y.id,kind:"updated",fields:{proplannerId:{before:C,after:y.proplannerId}},after:{...g,proplannerId:y.proplannerId}})}}),{ok:!0,changes:{source:e,activities:f,links:p,calendars:[],trackingEvents:[]}}}async function ll(e,t,r){if(jm(e))return{ok:!1,reason:v.INVALID_VALUE};let i=[...new Set(e.activityIds.map(String))];if(e.acknowledgePersistedLookahead===!0&&i.some(s=>!r.isActivityIdReserved(s)))return{ok:!1,reason:v.INVALID};let a=i.map(s=>r.adapter.getActivity(s));if(a.some(s=>!s))return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};let o=[];for(let[s,c]of i.entries()){let l=a[s];if(!l)continue;let d={};l.isLookahead!==e.isLookahead&&(d.isLookahead={before:l.isLookahead,after:e.isLookahead},r.adapter.setActivityField(c,"isLookahead",e.isLookahead)),l.hasLookaheadTasks!==e.hasLookaheadTasks&&(d.hasLookaheadTasks={before:l.hasLookaheadTasks,after:e.hasLookaheadTasks},r.adapter.setActivityField(c,"hasLookaheadTasks",e.hasLookaheadTasks)),Object.keys(d).length!==0&&o.push({id:c,kind:"updated",fields:d,after:{...l,isLookahead:e.isLookahead,hasLookaheadTasks:e.hasLookaheadTasks}})}return e.persistedProgress!==void 0&&(await sl([{activityId:i[0],progress:e.persistedProgress}],r)).length>0?(await q({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.persistedProgress===0?i[0]:null,recomputeParentsFrom:[],now:r.now,options:t}),{ok:!0,changes:await K(r.adapter,{source:e,beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:r.sector.hoursPerDay})}):{ok:!0,changes:{source:e,activities:o,links:[],calendars:[],trackingEvents:[]}}}function jm(e){let t=e.persistedProgress;return t!==void 0&&(e.activityIds.length!==1||!Number.isFinite(t)||t<0||t>100)}function Mi(e,t){let r=new Set;for(let n of e)r.add(String(n));let i=[];for(let n of t.getAllLinks()){let a=String(n.source),o=String(n.target);!r.has(a)&&!r.has(o)||(dl(o,a,t)||dl(a,o,t))&&i.push(String(n.id))}return i}function dl(e,t,r){let i=String(e),n=new Set;for(;i!=null;){if(n.has(i))return!1;n.add(i);let a=r.getActivity(i);if(!a)return!1;let o=a.parentId;if(o===null||N(o))return!1;let s=o;if(s===t)return!0;i=s}return!1}function Ui(e,t){let r=e.getAllLinks();return!hr({port:e,currentLinks:r,proposedLinks:r,proposal:{reparented:t}}).ok}function Bi(e,t){let r=new Set;if(e.length===0)return r;let i=new Map(e.map(a=>[a.activityId,a.newParentId]));if(!Ui(t,i))return r;let n=new Map;for(let a of e){let o=new Map(n);if(o.set(a.activityId,a.newParentId),Ui(t,o)){r.add(a.activityId);continue}n.set(a.activityId,a.newParentId)}return r}async function ul(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;n.invalidateAllCaches();let o=i.getActivity(e.activityId);if(!o)return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};let s=N(e.parentId);if(!s&&!i.getActivity(e.parentId))return{ok:!1,reason:v.PARENT_NOT_FOUND};if(!s&&(e.parentId===e.activityId||i.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:v.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:v.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let L=i.getActivity(c);if(!L)return{ok:!1,reason:v.ANCHOR_SIBLING_NOT_FOUND};if((L.parentId===null?"0":String(L.parentId))!==e.parentId)return{ok:!1,reason:v.ANCHOR_SIBLING_WRONG_PARENT}}let l=o.parentId,d=Qt(l),u=String(e.parentId),f=d!==u;if(f){let L=new Map([[e.activityId,s?null:e.parentId]]);if(Ui(i,L))return{ok:!1,reason:v.HIERARCHY_CYCLE}}let p=new Set([e.activityId]);f?(d!=="0"&&p.add(d),u!=="0"&&p.add(u)):d!=="0"&&p.add(d);let y=await Q(i,p);f&&i.setActivityField(e.activityId,b.PARENT,u);let g=wi(i,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(i.setActivityField(e.activityId,b.CORRELATIVE_ID,g),f){if(!s){let L=i.getActivity(e.parentId);if(L){let F=L.customId,T=Zt(L.type)&&i.getChildren(e.parentId).filter(_=>_!==e.activityId).length===0,I=Ze({parentId:e.parentId,newChildId:e.activityId,getParent:_=>i.getActivity(_)??null,isCurrentlyLeaf:T,promotionSource:"reparent"});if(I){for(let[_,j]of Object.entries(I.fields))st(i,I.parentId,_,j);I.promotionSnapshot&&i.setPromotionSnapshot(I.parentId,I.promotionSnapshot),I.fields.customId===null&&Pi(F,r.customIdTracker)}}}if(d!=="0"){let L=i.getActivity(d);if(L){let F=i.getChildren(d),T=tr({parent:L,remainingChildIds:F.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(d),computeEndDate:(I,_)=>i.calculateEndDate({startDate:I,durationHours:_,task:L}),idsRemoved:new Set([e.activityId])});if(T){for(let[Z,J]of Object.entries(T.fields))st(i,d,Z,J);let I=ue(d,i),_=I?i.getActivity(I)?.customId:null,j=typeof _=="string"&&_?_:null,W=r.customIdTracker.generateCustomIdForRestoredChild(j);i.setActivityField(d,b.CUSTOM_ID,W)}}}}f&&(d!=="0"&&xt(d,i),s||xt(e.parentId,i));let C=At(i);for(let L of C){if(p.add(L.activityId),y.has(L.activityId))continue;let F=i.getActivity(L.activityId);if(!F)continue;let T=et(F);L.before!==void 0&&(T.correlativeId=L.before),y.set(L.activityId,T)}let R=f&&d!=="0"?i.getChildren(d).map(String):[],{scheduledIds:A}=await q({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,...R],now:r.now,options:t,recomputeParentProgress:f}),k=f?Mi([e.activityId],i):[],m={name:Ot.ACTIVITY_MOVE,properties:{activity_id:e.activityId,new_parent_id:e.parentId,after_sibling_id:e.afterSiblingId??null,before_sibling_id:e.beforeSiblingId??null,invalid_link_ids:k.map(String)}};return e.eventSource!==void 0&&(m.properties.event_source=e.eventSource),{ok:!0,changes:await K(i,{source:e,beforeSnap:y,touchedIds:p,scheduledIds:A,sirDetection:"before-diff",trackingEvents:[m],hoursPerDay:a.hoursPerDay})}}function Wi(e,t){let r=new Set(e),i=[],n=[],a=new Set,o=new Set(r),s=[...e].sort((d,u)=>{let f=t.getActivity(d),p=t.getActivity(u),y=f?It(f):De,g=p?It(p):De;return y-g});for(let d of s){if(!t.getActivity(d)){i.push({activityId:d,reason:v.ACTIVITY_NOT_FOUND}),o.delete(d);continue}if(Fi(d,a,t))continue;let f=Oo(d,o,t);if(f==null){i.push({activityId:d,reason:v.INDENT_NO_ELIGIBLE_SIBLING}),o.delete(d);continue}let p=t.getActivity(d)?.parentId,y=N(p)?"0":String(p);n.push({activityId:d,newParentId:f,oldParentId:y}),a.add(d)}let c=Bi(n,t);for(let d of c)i.push({activityId:d,reason:v.HIERARCHY_CYCLE});let l=n.filter(d=>!c.has(d.activityId));return{moves:n,cyclicMoveIds:c,allowedMoves:l,failed:i}}async function fl(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:v.ACTIVITY_IDS_EMPTY};let o=new Set,s=[],c=Wi(e.activityIds,i),l=[...c.failed];for(let A of c.moves)o.add(String(A.activityId)),o.add(String(A.newParentId)),A.oldParentId!=="0"&&o.add(String(A.oldParentId));let d=c.allowedMoves,u=await Q(i,o);for(let{activityId:A,newParentId:k}of d)i.setActivityField(A,b.PARENT,k),i.setActivityField(A,b.CORRELATIVE_ID,Kc),s.push(A);let f=new Set;for(let{activityId:A,newParentId:k}of d){if(f.has(k))continue;f.add(k);let m=i.getActivity(k);if(!m)continue;let L=m.customId,F=Zt(m.type)&&i.getChildren(k).filter(_=>!s.includes(_)).length===0,T=m.hasNewActivities&&m.newActivityIds.some(_=>String(_)===String(A)),I=Ze({parentId:k,newChildId:A,getParent:_=>i.getActivity(_)??null,isCurrentlyLeaf:F,promotionSource:"reparent"});if(I){for(let[_,j]of Object.entries(I.fields))st(i,I.parentId,_,j);I.promotionSnapshot&&i.setPromotionSnapshot(I.parentId,I.promotionSnapshot),T||(i.setActivityField(k,b.HAS_NEW_ACTIVITIES,!1),i.setActivityField(k,b.NEW_ACTIVITIES_ARRAY,[]))}i.setActivityField(k,b.CONSTRAINT_TYPE,"asap"),i.setActivityField(k,b.CONSTRAINT_DATE,null),i.setActivityField(k,b.CUSTOM_ID,null),Pi(L,r.customIdTracker)}let p=new Set;for(let A of d)A.oldParentId!=="0"&&p.add(A.oldParentId),p.add(A.newParentId);for(let A of p)xt(A,i);let y=At(i);for(let A of y){if(o.add(A.activityId),u.has(A.activityId))continue;let k=i.getActivity(A.activityId);if(!k)continue;let m=et(k);A.before!==void 0&&(m.correlativeId=A.before),u.set(A.activityId,m)}let{scheduledIds:g}=await q({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:s,now:r.now,options:t}),C=Mi(s,i),R={name:Ot.ACTIVITY_INDENT,properties:{activity_ids:s,failed:l.map(A=>({activity_id:A.activityId,reason:A.reason})),invalid_link_ids:C}};return e.eventSource!==void 0&&(R.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(A=>{let k=l.find(m=>String(m.activityId)===String(A));return k?{activityId:String(A),ok:!1,reason:k.reason}:{activityId:String(A),ok:!0}}),changes:await K(i,{source:e,beforeSnap:u,touchedIds:o,scheduledIds:g,trackingEvents:[R],hoursPerDay:a.hoursPerDay})}}async function pl(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:v.ACTIVITY_IDS_EMPTY};let o=new Set(e.activityIds),s=new Map,c=new Map;for(let T of e.activityIds){let I=T;i.getActivity(I)&&(s.set(I,Sn(I,i)),c.set(I,Yc(I,o,i)))}let l=new Set,d=[],u=[],f=new Set,p=[],y=new Set,g=[...e.activityIds].sort((T,I)=>{let _=i.getActivity(T),j=i.getActivity(I),W=_?It(_):De,Z=j?It(j):De;return W-Z});for(let T of g){let I=T,_=i.getActivity(I);if(!_){d.push({activityId:I,reason:v.ACTIVITY_NOT_FOUND});continue}if(Fi(I,y,i))continue;let j=_.parentId;if(N(j)){d.push({activityId:I,reason:v.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let W=String(j),Z=i.getActivity(W);if(!Z){d.push({activityId:I,reason:v.ACTIVITY_NOT_FOUND});continue}let J=Z.parentId;if(N(J)){d.push({activityId:I,reason:v.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let ht=String(J),kt=Sn(W,i)+1,ct=c.get(I);if(ct!=null&&o.has(ct)){let Pe=s.get(ct)??-1,Le=s.get(I)??-1;Pe>=0&&Le>=0&&(kt+=Le-Pe)}p.push({activityId:I,grandparentKey:ht,oldParentKey:W,targetIndexInGrandparent:kt}),y.add(I),l.add(String(I)),l.add(String(W)),ht!=="0"&&l.add(String(ht)),f.add(W)}let C=Bi(p.map(T=>({activityId:T.activityId,newParentId:T.grandparentKey})),i);for(let T of C)d.push({activityId:T,reason:v.HIERARCHY_CYCLE});let R=p.filter(T=>!C.has(T.activityId)),A=await Q(i,l);for(let T of R){i.setActivityField(T.activityId,b.PARENT,T.grandparentKey);let I=Gc(i,T.grandparentKey,T.targetIndexInGrandparent,T.activityId);i.setActivityField(T.activityId,b.CORRELATIVE_ID,I),u.push(T.activityId)}for(let T of f){let I=i.getActivity(T);if(!I)continue;let _=i.getChildren(T),j=tr({parent:I,remainingChildIds:_.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(T),computeEndDate:(kt,ct)=>i.calculateEndDate({startDate:kt,durationHours:ct,task:I}),idsRemoved:new Set(R.filter(kt=>kt.oldParentKey===T).map(kt=>kt.activityId))});if(!j){ai(T,i);continue}for(let[kt,ct]of Object.entries(j.fields))st(i,T,kt,ct);let W=ue(T,i),Z=W?i.getActivity(W)?.customId:null,J=typeof Z=="string"&&Z?Z:null,ht=r.customIdTracker.generateCustomIdForRestoredChild(J);i.setActivityField(T,b.CUSTOM_ID,ht)}let k=new Set;for(let T of f)k.add(String(T));for(let T of R)T.grandparentKey!=="0"&&k.add(String(T.grandparentKey));for(let T of k)xt(T,i);let m=At(i);for(let T of m){if(l.add(T.activityId),A.has(T.activityId))continue;let I=i.getActivity(T.activityId);if(!I)continue;let _=et(I);T.before!==void 0&&(_.correlativeId=T.before),A.set(T.activityId,_)}let{scheduledIds:L}=await q({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:u.length>0?"roots":null,recomputeParentsFrom:u,now:r.now,options:t}),F={name:Ot.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(T=>({activity_id:String(T.activityId),reason:T.reason}))}};return e.eventSource!==void 0&&(F.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(T=>{let I=d.find(_=>String(_.activityId)===String(T));return I?{activityId:String(T),ok:!1,reason:I.reason}:{activityId:String(T),ok:!0}}),changes:await K(i,{source:e,beforeSnap:A,touchedIds:l,scheduledIds:L,trackingEvents:[F],hoursPerDay:a.hoursPerDay})}}async function yl(e,t,r){let{adapter:i,ctx:n,scheduler:a,sector:o}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:v.INVALID_PROGRESS_VALUE};let s=n.activityReader.getActivity(e.activityId);if(!s)return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};let c=se(S.PROGRESS);if(!c)throw new Error("[ScheduleCore] progressPipeline not registered \u2014 cannot dispatch activity-set-progress");let l=c.canEdit(s,n.hierarchy);if(!l.allowed&&!(e.origin==="action-button"&&(l.reason==="has_lookahead_tasks"||l.reason==="summary")))return{ok:!1,reason:l.reason,...l.alertKey?{alertKey:l.alertKey}:{}};let d=c.transform(s,e.newValue,n,e.newValue),u=ce(e.activityId,d),f=await Q(i,u);le(i,e.activityId,d),fs(e.activityId,e.newValue,i),re(e.activityId,d.postProcessors??[],i);let{scheduledIds:p}=await q({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:d.needsAutoSchedule?e.activityId:null,recomputeParentsFrom:[],collectDirty:g=>gi(e.activityId,u,g),now:r.now,options:t}),y=(d.trackingEvents??[]).map(g=>({name:g.name,properties:g.properties??{}}));return{ok:!0,changes:await K(i,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:p,trackingEvents:y,hoursPerDay:o.hoursPerDay})}}function Vm(e){return e===S.START_DATE||e===S.END_DATE}async function hl(e,t,r){if(e.edits.some(y=>!Vm(y.column)))return{ok:!1,reason:v.INVALID_VALUE};let{adapter:i,scheduler:n,sector:a}=r,o=[],s=new Map,c=new Set,l=[],d=[],u=[],f=!1;for(let y of e.edits){let g=Km(y,r);if(o.push(g.verdict),!g.verdict.ok||!g.changes)continue;let C=ce(y.activityId,g.changes);Ym(s,C,r);for(let m of C)c.add(m);let R=Xe(i,y.activityId),A=hi(i,String(y.activityId));le(i,y.activityId,g.changes),re(y.activityId,g.changes.postProcessors??[],i,A),d.push(...Qe(R,i,y.activityId)),f||=!!g.changes.needsAutoSchedule;for(let m of g.changes.trackingEvents??[])l.push({name:m.name,properties:m.properties??{}});let k=Ge(y.activityId,g.changes.constraintWarning);k&&u.push(k)}let{scheduledIds:p}=await q({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:f?"roots":null,recomputeParentsFrom:c,now:r.now,options:t});return{ok:!0,verdicts:o,changes:await K(i,{source:e,beforeSnap:s,touchedIds:c,scheduledIds:p,sirDetection:"before-diff",links:d,trackingEvents:l,warnings:u,hoursPerDay:a.hoursPerDay})}}function Km(e,t){let{ctx:r}=t,i=e.activityId,n=se(e.column);if(!n)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);let a=r.activityReader.getActivity(e.activityId);if(!a)throw new Error(`[ScheduleCore] activity "${e.activityId}" not found`);let o=n.canEdit(a,r.hierarchy);if(!o.allowed)return{verdict:{activityId:i,ok:!1,reason:o.reason??v.CANNOT_EDIT,...o.alertKey?{alertKey:o.alertKey}:{}},changes:null};let s=n.parseInput(e.newValue,a,r);if(!s.ok)return{verdict:{activityId:i,ok:!1,reason:s.reason??v.PARSE_ERROR},changes:null};let c=Reflect.get(a,n.targetField),l=n.validate(a,c,s.value,r);if(!l.valid)return{verdict:{activityId:i,ok:!1,reason:l.reason??v.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};let d=n.transform(a,s.value,r,s.raw);return{verdict:{activityId:i,ok:!0},changes:d}}function Ym(e,t,r){let i=new Set;for(let n of t)e.has(n)||i.add(n);if(i.size!==0)for(let n of i){let a=r.adapter.getActivity(n);a&&e.set(n,et(a))}}var _a=S.CUSTOM_ID;async function ml(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;e.edits.some(k=>k.column===S.DURATION)&&n.invalidateExpandedLinksCache();let s=[],c=new Map,l=new Map,d=new Set,u=new Set,f=[],p=[],y=[],g=!1;for(let k of e.edits){let m=Gm(k,r,e.eventSource);if(s.push(m.verdict),!m.verdict.ok||!m.changes)continue;let L=Ge(k.activityId,m.changes.constraintWarning);L&&y.push(L);let F=ce(k.activityId,m.changes);Jm(c,F,r);for(let W of F)u.add(W);qm(l,k,c),_i(k.column)&&d.add(String(k.activityId));let T=Xe(i,k.activityId),I=hi(i,String(k.activityId)),_=$m(k,r),j=m.changes;le(i,k.activityId,j),re(k.activityId,m.changes.postProcessors??[],i,I),zm(k,_,r),p.push(...Qe(T,i,k.activityId)),g||=!!m.changes.needsAutoSchedule;for(let W of m.changes.trackingEvents??[])f.push({name:W.name,properties:W.properties??{}})}let C={action:e,autoscheduleFrom:g?"roots":null,recomputeParentsFrom:u,now:r.now,options:t},R=l.size>0,{scheduledIds:A}=await(R?Ri({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:C,revertTargets:[...l].filter(([k])=>!d.has(k)).map(([k,m])=>({activityId:k,priorConstraintDate:m})),revert:(k,m)=>Ei(k,m,i,r.ctx.calendars)}):q({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},C));return{ok:!0,verdicts:s,changes:await K(i,{source:e,beforeSnap:c,touchedIds:u,scheduledIds:A,sirDetection:"before-diff",links:p,trackingEvents:f,warnings:y,hoursPerDay:a.hoursPerDay})}}function Gm(e,t,r){let{ctx:i}=t,n=e.activityId,a=se(e.column);if(!a)return{verdict:{activityId:n,ok:!1,reason:v.NO_PIPELINE_FOR_COLUMN},changes:null};let o=i.activityReader.getActivity(e.activityId);if(!o)return{verdict:{activityId:n,ok:!1,reason:v.ACTIVITY_NOT_FOUND},changes:null};let s=a.canEdit(o,i.hierarchy,{eventSource:r,newValue:e.newValue});if(!s.allowed)return{verdict:{activityId:n,ok:!1,reason:s.reason??v.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let c=a.parseInput(e.newValue,o,i);if(!c.ok)return{verdict:{activityId:n,ok:!1,reason:c.reason??v.PARSE_ERROR},changes:null};let l=Reflect.get(o,a.targetField),d=a.validate(o,l,c.value,i);if(!d.valid)return{verdict:{activityId:n,ok:!1,reason:d.reason??v.INVALID,...d.notification?.messageKey?{alertKey:d.notification.messageKey}:{}},changes:null};if(e.column===_a&&c.value!==null){let f=t.adapter.getActivity(e.activityId),p=f?f.customId:null,y=typeof p=="string"?p:null;if(t.customIdTracker.isCustomIdInUse(String(c.value),y))return{verdict:{activityId:n,ok:!1,reason:v.CUSTOM_ID_DUPLICATE},changes:null}}let u=a.transform(o,c.value,i,c.raw);return{verdict:{activityId:n,ok:!0},changes:u}}function $m(e,t){if(e.column!==_a)return null;let r=t.adapter.getActivity(e.activityId),i=r?r.customId:null;return typeof i=="string"?i:null}function zm(e,t,r){if(e.column!==_a)return;let i=r.adapter.getActivity(e.activityId),n=i?i.customId:null,a=typeof n=="string"?n:null;t!==a&&r.customIdTracker.trackCustomIdChange(t,a)}function qm(e,t,r){if(!Di(t.column))return;let i=String(t.activityId);if(e.has(i))return;let n=r.get(i);n&&e.set(i,n.constraintDate??null)}function Jm(e,t,r){let i=new Set;for(let n of t)e.has(n)||i.add(n);if(i.size!==0)for(let n of i){let a=r.adapter.getActivity(n);a&&e.set(n,et(a))}}function gl(e){return typeof e=="string"&&e.length>0?zt(e):e instanceof Date?e:null}function Ea(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):Number.NaN;return!Number.isFinite(t)||t<0?null:t}function Hi(e,t){let r=Ea(e.duration),i=Ea(e.cost),n=Ea(e.hh_work);return r===null||i===null||n===null?(t.warn(`[baseline] dropping point with non-finite/negative magnitude \u2014 duration=${JSON.stringify(e.duration)}, cost=${JSON.stringify(e.cost)}, hh_work=${JSON.stringify(e.hh_work)}`),null):{startDate:gl(e.start_date),endDate:gl(e.end_date),durationDays:r,cost:i,workHours:n,versionId:typeof e.sectorbaselineversionId=="number"?e.sectorbaselineversionId:null,isActiveVersion:!!e.sectorbaselineversion?.active,isVisibleVersion:!!e.sectorbaselineversion?.visible,baseCalendarId:e.baseCalendarId!=null?String(e.baseCalendarId):null,hoursPerDay:typeof e.hoursPerDay=="number"?e.hoursPerDay:null,hoursPerWeek:typeof e.hoursPerWeek=="number"?e.hoursPerWeek:null}}function Al(e,t,r){let i=new Map;e.forEachActivity((o,s)=>{let c=o.proplannerId;typeof c=="number"&&i.set(c,s)});let n=new Map;for(let o of t){let s=o.activityId;if(typeof s!="number")continue;let c=i.get(s);if(c===void 0)continue;let l=n.get(c);l?l.push(o):n.set(c,[o])}let a=[];for(let[o,s]of n)e.setActivityField(o,"baselinePoints",s.map(c=>Hi(c,r)).filter(c=>c!==null)),a.push(o);return e.forEachActivity((o,s)=>{if(n.has(s))return;let c=o.baselinePoints;Array.isArray(c)&&c.length>0&&(e.setActivityField(s,"baselinePoints",[]),a.push(s))}),a}function Xm(e){let t=gt(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function Il(e){let t=[];return e.forEachActivity((r,i)=>{let n=Xm(r);if(!n){r.baselineSnapshot!==null&&(e.setActivityField(i,"baselineSnapshot",null),t.push(i));return}e.setActivityField(i,"baselineSnapshot",n),t.push(i)}),t}function ji(e,t,r,i,n=null){let a=new Set;for(let o of Al(e,t,i))a.add(o);if(r)for(let o of ze(e,r,n))a.add(o);for(let o of Il(e))a.add(o);for(let o of qe(e))a.add(o);return[...a]}function vl(e,t,r){if(!e||e==="0")return;let i=r.getChildren(e);if(i.length===0)return;let n=new Map,a=0;for(let s of i){let c=Qm(String(s),t,r);n.set(String(s),c),a+=c}let o=a?100/a:0;for(let s of i){let c=r.getActivity(s);if(!c)continue;let l=c.baselinePoints;if(gt(c)){let u=n.get(String(s))??0;r.setActivityField(s,S.PONDERATOR,o*u)}else(!Array.isArray(l)||l.length===0)&&r.setActivityField(s,S.PONDERATOR,0)}}function Qm(e,t,r){let i=r.getActivity(e);if(!i)return 0;let n=gt(i);if(!n)return 0;if(t===dt.COST)return Vi(n.cost);if(t===dt.WORK_HOURS)return Vi(n.workHours);let{type:a}=i;return a===Dt.PROJECT?Cl(e,r):a===Dt.MILESTONE?0:Vi(n.durationDays)}function Cl(e,t){let r=0;for(let i of t.getChildren(e)){let n=t.getActivity(i);if(!n)continue;let a=gt(n);if(!a)continue;let{type:o}=n;o===Dt.PROJECT?r+=Cl(String(i),t):o!==Dt.MILESTONE&&(r+=Vi(a.durationDays))}return r}function Vi(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function Sl(e,t){t.forEachActivity((r,i)=>{t.setActivityField(i,S.PONDERATOR,0)}),t.forEachActivity((r,i)=>{t.getChildren(i).length>0&&vl(String(i),e,t)})}function Ki(e,t){Sl(t,e.adapter),gr(e.adapter),e.now&&(ze(e.adapter,e.now,e.defaultBaseCalendarId??null),Ce(e.adapter,e.now)),qe(e.adapter),e.now&&qt(e.adapter,e.sector.statusCriteria)}function kl(e){return JSON.stringify(e.adapter.getAllIds().map(t=>{let r=e.adapter.getActivity(t)?.baselinePoints.find(i=>i.isActiveVersion);return r?[String(t),r.versionId,r.startDate?.getTime()??null,r.endDate?.getTime()??null,r.durationDays,r.cost,r.workHours,r.baseCalendarId,r.hoursPerDay,r.hoursPerWeek]:[String(t),null]}))}async function Tl(e,t){let r=await Q(t.adapter,new Set(t.adapter.getAllIds())),i=kl(t),n=ji(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return kl(t)!==i&&Ki(t,t.sector.activityCreter??dt.DURATION),{ok:!0,changes:await K(t.adapter,{source:e,beforeSnap:r,touchedIds:n,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function Zm(e){return Object.values(dt).includes(e)}async function Dl(e,t){if(!Zm(e.criterion))return{ok:!1,reason:v.INVALID_VALUE};let r=new Set(t.adapter.getAllIds()),i=await Q(t.adapter,r);return Ki(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:await K(t.adapter,{source:e,beforeSnap:i,touchedIds:r,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function _l(e,t){let r=Ii(e.criteria),i=new Set(t.adapter.getAllIds()),n=await Q(t.adapter,i),a=qt(t.adapter,r);return t.sector.statusCriteria=r,{ok:!0,changes:await K(t.adapter,{source:e,beforeSnap:n,touchedIds:a,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function Rl(e,t,r){let i=new Map,n=new Set;for(let o of r.adapter.getAllActivities()){if(!tg(o,r))continue;let s=r.ctx.calendars.getCalendar(o.calendarId);if(!s)continue;let c=s.getClosestWorkTime({date:o.startDate,direction:rt.FUTURE,unit:pt.HOUR}),l=s.calculateEndDate(c,o.durationHours);if(El(c,o.startDate)&&El(l,o.endDate))continue;let d=String(o.id);i.set(d,et(o)),n.add(d),r.adapter.setActivityFields(d,{startDate:c,endDate:l})}let{scheduledIds:a}=await q({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:n,now:r.now,options:t});return{ok:!0,changes:await K(r.adapter,{source:e,beforeSnap:i,touchedIds:n,scheduledIds:a,hoursPerDay:r.sector.hoursPerDay})}}function tg(e,t){return e.progress===0&&!wt(e.type,t.adapter.hasChildren(e.id))}function El(e,t){return e.getTime()===t.getTime()}var Pl=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","cost","hasCustomPonderator","subcontractId","responsableIds","tagIds"];function eg(e){let t={};for(let r of Pl)Object.assign(t,{[r]:O(e[r])});return t}function rg(e,t){let r=[],i=n=>{t.has(String(n))&&r.push(n);for(let a of e.getChildren(n))i(a)};for(let n of e.getRootIds())i(n);return r}function Ll(e,t){let r=new Set(t.adapter.checkedIds().map(String));if(r.size===0)return{ok:!1,reason:v.NO_ACTIVITY_SELECTION};let i=rg(t.adapter,r);t.clipboard.value={activities:i.map(a=>{let o=t.adapter.getActivity(a);if(o===null)throw new Error(`Selected activity ${a} is missing`);return{originalId:a,originalParentId:o.parentId??"0",overrides:eg(o)}}),links:t.adapter.getAllLinks().filter(a=>r.has(String(a.source))&&r.has(String(a.target))).map(a=>O(a))};let n=Mr({kind:"selection-replace",activityIds:[]},{adapter:t.adapter});return n.ok?{...n,changes:{...n.changes,source:e}}:n}function Ol(e,t){return t.value=null,{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}}function ig(e,t){let r=t.getActivity(e);return r?r.parentId==null?t.getRootIds().length===1?{ok:!0,parentId:r.id}:{ok:!0,parentId:"0",afterSiblingId:e}:{ok:!0,parentId:String(r.parentId),afterSiblingId:e}:{ok:!1,reason:v.ANCHOR_SIBLING_NOT_FOUND}}var bl=()=>({ok:!1,reason:v.ACTIVITY_PASTE_INVARIANT_FAILED});async function Nl(e,t,r){let i=r.activityClipboard.value;if(i===null)return{ok:!1,reason:v.CLIPBOARD_EMPTY};let n=ig(e.destination.afterSiblingId,r.adapter);if(!n.ok)return n;let a=await Q(r.adapter,new Set),o=new Set,s=new Map,c=[],l;for(let g of i.activities){let C=s.get(g.originalParentId),R=C===void 0?l??n.afterSiblingId:void 0,A=await Rr({kind:"activity-create",parentId:C??n.parentId,...R===void 0?{}:{afterSiblingId:R},overrides:O(g.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:e.destination.afterSiblingId});if(!A.ok)return A;s.set(g.originalId,A.newId),c.push(A.newId),C===void 0&&(l=A.newId)}let d=At(r.adapter),u=new Set(c.map(String));Ai(r.adapter,d,u,a,o);for(let g of c)o.add(String(g));let f=[];for(let g of i.links){let C=s.get(g.source),R=s.get(g.target);if(C===void 0||R===void 0)return bl();let A={kind:"create",source:C,target:R,type:g.type,lag:g.lag},k=te(A,{port:r.adapter,newLinkId:r.linkIdGen.next});if(!k.applied)return bl();f.push({op:A,finalLinkId:k.linkId,rejected:null})}let{scheduledIds:p}=await q({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:c[0]??null,recomputeParentsFrom:c,now:r.now,options:t}),y=Je(f,new Map,r.adapter);return{ok:!0,changes:await K(r.adapter,{source:e,beforeSnap:a,touchedIds:o,scheduledIds:p,links:y,hoursPerDay:r.sector.hoursPerDay})}}async function wl(e,t,r){return e.kind==="activity-copy"?Ll(e,{adapter:r.adapter,clipboard:r.activityClipboard}):e.kind==="calendar-reconcile"?Rl(e,t,r):e.kind==="activity-clipboard-clear"?Ol(e,r.activityClipboard):e.kind==="activity-paste-copied"?Nl(e,t,r):e.kind==="activity-batch"?el(e,t,r):e.kind==="persistence-acknowledge"?cl(e,r):e.kind==="baseline-apply"?Tl(e,r):e.kind==="ponderator-criterion-set"?Dl(e,r):e.kind==="status-criteria-set"?_l(e,r):e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?Lc(e,t,r):e.kind==="links-batch"?Oc(e,t,r):e.kind==="activity-create"?$c(e,t,r):e.kind==="activity-delete"?Qc(e,t,r):e.kind==="activity-move"?ul(e,t,r):e.kind==="activity-indent"?fl(e,t,r):e.kind==="activity-outdent"?pl(e,t,r):e.kind==="activity-set-progress"?yl(e,t,r):e.kind==="dates-batch"?hl(e,t,r):e.kind==="bulk-edit"?ml(e,t,r):e.kind==="selection-toggle"?Ao(e,Ra(r)):e.kind==="selection-replace"?Mr(e,Ra(r)):e.kind==="visibility-set"?Io(e,Ra(r)):e.kind==="filter-set"?Ro(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind==="sort-set"?No(e,{adapter:r.adapter}):e.kind==="sir-sync"?il(e,r):e.kind==="activity-lookahead-sync"?ll(e,t,r):e.kind==="inline-edit"&&(e.column===S.CUSTOM_PREDECESSORS||e.column===S.CUSTOM_SUCESSORS)?bc(e,t,r):e.kind!=="inline-edit"?wo(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):Pc(e,t,r)}function Ra(e){return{adapter:e.adapter}}var ng=new Set(["startDate","endDate","constraintDate"]);function Fl(e,t){return ng.has(e)&&typeof t=="string"?new Date(t):t}function xl(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(i){let n=e.getCalendar(String(i));return n?ag(n,r):null}}}function ag(e,t){return{getClosestWorkTime(r){return e.getClosestWorkTime({date:r.date,dir:r.direction,unit:r.unit})},calculateEndDate(r,i){return e.calculateEndDate({start_date:r,duration:i,unit:t})},calculateDuration(r,i){return e.calculateDuration({start_date:r,end_date:i,unit:t})},isWorkTime(r,i){return e.isWorkTime({date:r,unit:i})},getWorkHours(r){return e.getWorkHours(r)}}}function og(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function _e(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function Ee(e){return _e(e)&&!isNaN(e.getTime())}var sg={}.constructor.toString();function cg(e){var t=e.constructor.toString();return t!==sg}function lg(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function Mt(e){var t,r;if(e&&typeof e=="object")switch(!0){case _e(e):r=new Date(e);break;case og(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=Mt(e[t]);break;default:if(cg(e))r=Object.create(e);else{if(lg(e))return r=e,r;r={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(r[t]=Mt(e[t]));break}return r||e}function er(e,t,r){for(var i in t)(e[i]===void 0||r)&&(e[i]=t[i]);return e}function Ml(e){return typeof e<"u"}var Yi;function Pa(){return Yi||(Yi=new Date().valueOf()),Yi++,Yi}function Et(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var ug=(e,t,r)=>{e=e.replace(/%[a-zA-Z]/g,n=>{switch(n){case"%d":return`"+to_fixed(date.get${t?"UTC":""}Date())+"`;case"%m":return`"+to_fixed((date.get${t?"UTC":""}Month()+1))+"`;case"%j":return`"+date.get${t?"UTC":""}Date()+"`;case"%n":return`"+(date.get${t?"UTC":""}Month()+1)+"`;case"%y":return`"+to_fixed(date.get${t?"UTC":""}FullYear()%100)+"`;case"%Y":return`"+date.get${t?"UTC":""}FullYear()+"`;case"%D":return`"+locale.date.day_short[date.get${t?"UTC":""}Day()]+"`;case"%l":return`"+locale.date.day_full[date.get${t?"UTC":""}Day()]+"`;case"%M":return`"+locale.date.month_short[date.get${t?"UTC":""}Month()]+"`;case"%F":return`"+locale.date.month_full[date.get${t?"UTC":""}Month()]+"`;case"%h":return`"+to_fixed((date.get${t?"UTC":""}Hours()+11)%12+1)+"`;case"%g":return`"+((date.get${t?"UTC":""}Hours()+11)%12+1)+"`;case"%G":return`"+date.get${t?"UTC":""}Hours()+"`;case"%H":return`"+to_fixed(date.get${t?"UTC":""}Hours())+"`;case"%i":return`"+to_fixed(date.get${t?"UTC":""}Minutes())+"`;case"%a":return`"+(date.get${t?"UTC":""}Hours()>11?"pm":"am")+"`;case"%A":return`"+(date.get${t?"UTC":""}Hours()>11?"PM":"AM")+"`;case"%s":return`"+to_fixed(date.get${t?"UTC":""}Seconds())+"`;case"%W":return'"+to_fixed(getISOWeek(date))+"';case"%w":return'"+to_fixed(getWeek(date))+"';default:return n}});let i=new Function("date","to_fixed","locale","getISOWeek","getWeek",`return "${e}";`);return n=>i(n,r.date.to_fixed,r.locale,r.date.getISOWeek,r.date.getWeek)},fg=(e,t,r)=>{let i="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);",n=e.match(/%[a-zA-Z]/g);for(let s=0;s<n.length;s++)switch(n[s]){case"%j":case"%d":i+=`set[2]=temp[${s}]||1;`;break;case"%n":case"%m":i+=`set[1]=(temp[${s}]||1)-1;`;break;case"%y":i+=`set[0]=temp[${s}]*1+(temp[${s}]>50?1900:2000);`;break;case"%g":case"%G":case"%h":case"%H":i+=`set[3]=temp[${s}]||0;`;break;case"%i":i+=`set[4]=temp[${s}]||0;`;break;case"%Y":i+=`set[0]=temp[${s}]||0;`;break;case"%a":case"%A":i+=`set[3]=set[3]%12+((temp[${s}]||'').toLowerCase()=='am'?0:12);`;break;case"%s":i+=`set[5]=temp[${s}]||0;`;break;case"%M":i+=`set[1]=locale.date.month_short_hash[temp[${s}]]||0;`;break;case"%F":i+=`set[1]=locale.date.month_full_hash[temp[${s}]]||0;`;break}let a="set[0],set[1],set[2],set[3],set[4],set[5]";t&&(a=` Date.UTC(${a})`);let o=new Function("date","locale",`var set=[0,0,1,0,0,0]; ${i} return new Date(${a});`);return s=>o(s,r.locale)},Ul={date_to_str:ug,str_to_date:fg},pg=(e,t,r)=>i=>e.replace(/%[a-zA-Z]/g,n=>{switch(n){case"%d":return t?r.date.to_fixed(i.getUTCDate()):r.date.to_fixed(i.getDate());case"%m":return t?r.date.to_fixed(i.getUTCMonth()+1):r.date.to_fixed(i.getMonth()+1);case"%j":return t?i.getUTCDate():i.getDate();case"%n":return t?i.getUTCMonth()+1:i.getMonth()+1;case"%y":return t?r.date.to_fixed(i.getUTCFullYear()%100):r.date.to_fixed(i.getFullYear()%100);case"%Y":return t?i.getUTCFullYear():i.getFullYear();case"%D":return t?r.locale.date.day_short[i.getUTCDay()]:r.locale.date.day_short[i.getDay()];case"%l":return t?r.locale.date.day_full[i.getUTCDay()]:r.locale.date.day_full[i.getDay()];case"%M":return t?r.locale.date.month_short[i.getUTCMonth()]:r.locale.date.month_short[i.getMonth()];case"%F":return t?r.locale.date.month_full[i.getUTCMonth()]:r.locale.date.month_full[i.getMonth()];case"%h":return t?r.date.to_fixed((i.getUTCHours()+11)%12+1):r.date.to_fixed((i.getHours()+11)%12+1);case"%g":return t?(i.getUTCHours()+11)%12+1:(i.getHours()+11)%12+1;case"%G":return t?i.getUTCHours():i.getHours();case"%H":return t?r.date.to_fixed(i.getUTCHours()):r.date.to_fixed(i.getHours());case"%i":return t?r.date.to_fixed(i.getUTCMinutes()):r.date.to_fixed(i.getMinutes());case"%a":return t?i.getUTCHours()>11?"pm":"am":i.getHours()>11?"pm":"am";case"%A":return t?i.getUTCHours()>11?"PM":"AM":i.getHours()>11?"PM":"AM";case"%s":return t?r.date.to_fixed(i.getUTCSeconds()):r.date.to_fixed(i.getSeconds());case"%W":return t?r.date.to_fixed(r.date.getUTCISOWeek(i)):r.date.to_fixed(r.date.getISOWeek(i));case"%w":return r.date.to_fixed(r.date.getWeek(i));default:return n}}),yg=(e,t,r)=>i=>{let n=[0,0,1,0,0,0],a=i.match(/[a-zA-Z]+|[0-9]+/g),o=e.match(/%[a-zA-Z]/g);for(let s=0;s<o.length;s++)switch(o[s]){case"%j":case"%d":n[2]=a[s]||1;break;case"%n":case"%m":n[1]=(a[s]||1)-1;break;case"%y":n[0]=a[s]*1+(a[s]>50?1900:2e3);break;case"%g":case"%G":case"%h":case"%H":n[3]=a[s]||0;break;case"%i":n[4]=a[s]||0;break;case"%Y":n[0]=a[s]||0;break;case"%a":case"%A":n[3]=n[3]%12+((a[s]||"").toLowerCase()==="am"?0:12);break;case"%s":n[5]=a[s]||0;break;case"%M":n[1]=r.locale.date.month_short_hash[a[s]]||0;break;case"%F":n[1]=r.locale.date.month_full_hash[a[s]]||0;break}return t?new Date(Date.UTC(n[0],n[1],n[2],n[3],n[4],n[5])):new Date(n[0],n[1],n[2],n[3],n[4],n[5])},Bl={date_to_str:pg,str_to_date:yg};function Wl(e){var t=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function r(s){var c=new Date(s);return isNaN(c.getTime())?null:c}var i=null;function n(){try{new Function("canUseCsp = false;")}catch{i=!0}}function a(){var s=!1;return e.config.csp==="auto"?(i===null&&n(),s=i):s=e.config.csp,s}var o={_isoDateDetected:!1,_isoDateOnly:!1,formatISODate:function(s){return s.toISOString()},formatISODateOnly:function(s){return s.getUTCFullYear()+"-"+e.date.to_fixed(s.getUTCMonth()+1)+"-"+e.date.to_fixed(s.getUTCDate())},init:function(){for(var s=e.locale,l=s.date.month_short,d=s.date.month_short_hash={},c=0;c<l.length;c++)d[l[c]]=c;for(var l=s.date.month_full,d=s.date.month_full_hash={},c=0;c<l.length;c++)d[l[c]]=c},date_part:function(s){return s.setUTCHours(0,0,0,0),s},time_part:function(s){return s.valueOf()/1e3%86400},week_start:function(s){var c=s.getUTCDay();return e.config.start_on_monday&&(c===0?c=6:c--),this.date_part(this.add(s,-1*c,"day"))},month_start:function(s){return s.setUTCDate(1),this.date_part(s)},quarter_start:function(s){this.month_start(s);var c=s.getUTCMonth(),l;return c>=9?l=9:c>=6?l=6:c>=3?l=3:l=0,s.setUTCMonth(l),s},year_start:function(s){return s.setUTCMonth(0),this.month_start(s)},day_start:function(s){return this.date_part(s)},hour_start:function(s){return s.getUTCMinutes()&&s.setUTCMinutes(0),this.minute_start(s),s},minute_start:function(s){return s.getUTCSeconds()&&s.setUTCSeconds(0),s.getUTCMilliseconds()&&s.setUTCMilliseconds(0),s},_add_days:function(s,c,l){return s.setUTCDate(s.getUTCDate()+c),s},add:function(s,c,l){var d=new Date(s.valueOf());switch(l){case"day":d=this._add_days(d,c,s);break;case"week":d=this._add_days(d,c*7,s);break;case"month":d.setUTCMonth(d.getUTCMonth()+c);break;case"year":d.setUTCFullYear(d.getUTCFullYear()+c);break;case"hour":d.setTime(d.getTime()+c*60*60*1e3);break;case"minute":d.setTime(d.getTime()+c*60*1e3);break;default:return this["add_"+l](s,c,l)}return d},add_quarter:function(s,c){return this.add(s,c*3,"month")},to_fixed:function(s){return s<10?"0"+s:s},copy:function(s){return new Date(s.valueOf())},date_to_str:function(s,c){var l=Ul;return a()&&(l=Bl),l.date_to_str(s,c,e)},str_to_date:function(s,c){var l=Ul;return a()&&(l=Bl),l.str_to_date(s,c,e)},getISOWeek:function(s){return e.date._getWeekNumber(s,!0)},_getWeekNumber:function(s,c){if(!s)return!1;var l=s.getUTCDay();c&&l===0&&(l=7);var d=new Date(s.valueOf());d.setUTCDate(s.getUTCDate()+(4-l));var u=d.getUTCFullYear(),f=Math.round((d.getTime()-Date.UTC(u,0,1))/864e5),p=1+Math.floor(f/7);return p},getWeek:function(s){return e.date._getWeekNumber(s,e.config.start_on_monday)},getUTCISOWeek:function(s){return e.date.getISOWeek(s)},parseDate:function(s,c){if(s&&!s.getFullYear){var l=!c||c==="parse_date"||c==="xml_date",d=l&&(e.defined(e.templates.xml_date)||e.templates.parse_date&&!e.templates.parse_date._ganttAuto);if(!d&&typeof s=="string"&&t.test(s)){var u=s.indexOf("T")!==-1,f=r(s);if(f)return o._isoDateDetected?u&&(o._isoDateOnly=!1):(o._isoDateDetected=!0,o._isoDateOnly=!u),f}typeof c!="function"&&(typeof c=="string"?c==="parse_date"||c==="xml_date"?c=e.defined(e.templates.xml_date)?e.templates.xml_date:e.templates.parse_date:c=e.defined(e.templates[c])?e.templates[c]:e.date.str_to_date(c,!0):c=e.defined(e.templates.xml_date)?e.templates.xml_date:e.templates.parse_date),s?s=c(s):s=null}return s}};return o}function La(e,t,r,i,n){return this.date=e,this.unit=t,this.task=r,this.id=i,this.calendar=n,this}function Oa(e,t,r,i,n,a){return this.date=e,this.dir=t,this.unit=r,this.task=i,this.id=n,this.calendar=a,this}function ba(e,t,r,i,n,a,o){return this.start_date=e,this.duration=t,this.unit=r,this.step=i,this.task=n,this.id=a,this.calendar=o,this}function hg(e,t,r,i){return this.start_date=e,this.end_date=t,this.task=r,this.calendar=i,this.unit=null,this.step=null,this}var Hl=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(_e(t)?t={date:t}:t=er({},t),!Ee(t.date))throw e.assert(!1,"Invalid date argument for getWorkHours method"),new Error("Invalid date argument for getWorkHours method");return t},setWorkTimeArguments:function(){return arguments[0]},unsetWorkTimeArguments:function(){return arguments[0]},isWorkTimeArguments:function(){var t=arguments[0];if(t instanceof La)return t;var r;if(t.date?r=new La(t.date,t.unit,t.task,null,t.calendar):r=new La(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!Ee(r.date))throw e.assert(!1,"Invalid date argument for isWorkTime method"),new Error("Invalid date argument for isWorkTime method");return r},getClosestWorkTimeArguments:function(t){var r=arguments[0];if(r instanceof Oa)return r;var i;if(_e(r)?i=new Oa(r):i=new Oa(r.date,r.dir,r.unit,r.task,null,r.calendar),r.id&&(i.task=r),i.dir=r.dir||"any",i.unit=r.unit||e.config.duration_unit,!Ee(i.date))throw e.assert(!1,"Invalid date argument for getClosestWorkTime method"),new Error("Invalid date argument for getClosestWorkTime method");return i},_getStartEndConfig:function(t){var r=hg,i;if(t instanceof r)return t;if(_e(t)?i=new r(arguments[0],arguments[1],arguments[2],arguments[3]):(i=new r(t.start_date,t.end_date,t.task),t.id!==null&&t.id!==void 0&&(i.task=t)),i.unit=i.unit||e.config.duration_unit,i.step=i.step||e.config.duration_step,i.start_date=i.start_date||i.start||i.date,!Ee(i.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!Ee(i.end_date))throw e.assert(!1,"Invalid end_date argument for getDuration method"),new Error("Invalid end_date argument for getDuration method");return i},getDurationArguments:function(t,r,i,n){return this._getStartEndConfig.apply(this,arguments)},hasDurationArguments:function(t,r,i,n){return this._getStartEndConfig.apply(this,arguments)},calculateEndDateArguments:function(t,r,i,n){var a=arguments[0];if(a instanceof ba)return a;var o;if(_e(a)?o=new ba(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):o=new ba(a.start_date,a.duration,a.unit,a.step,a.task,null,a.calendar),a.id!==null&&a.id!==void 0&&(o.task=a,o.unit=null,o.step=null),o.unit=o.unit||e.config.duration_unit,o.step=o.step||e.config.duration_step,!Ee(o.start_date))throw e.assert(!1,"Invalid start_date argument for calculateEndDate method"),new Error("Invalid start_date argument for calculateEndDate method");return o}}};function jl(){}jl.prototype={_getIntervals:function(e){for(var t=[],r=0;r<e.length;r+=2)t.push({start:e[r],end:e[r+1]});return t},_toHoursArray:function(e){var t=[];function r(a){var o=String(a);return o.length<2&&(o="0"+o),o}function i(a){var o=Math.floor(a/3600),s=a-o*60*60,c=Math.floor(s/60);return o+":"+r(c)}for(var n=0;n<e.length;n++)t.push(i(e[n].start)+"-"+i(e[n].end));return t},_intersectHourRanges:function(e,t){var n=[],r=e.length>t.length?e:t,i=e===r?t:e;r=r.slice(),i=i.slice();for(var n=[],a=0;a<r.length;a++)for(var o=r[a],s=0;s<i.length;s++){var c=i[s];c.start<o.end&&c.end>o.start&&(n.push({start:Math.max(o.start,c.start),end:Math.min(o.end,c.end)}),o.end>c.end&&(i.splice(s,1),s--,a--))}return n},_mergeAdjacentIntervals:function(e){var t=e.slice();t.sort(function(a,o){return a.start-o.start});for(var r=t[0],i=1;i<t.length;i++){var n=t[i];n.start<=r.end?(n.end>r.end&&(r.end=n.end),t.splice(i,1),i--):r=n}return t},_mergeHoursConfig:function(e,t){return this._mergeAdjacentIntervals(this._intersectHourRanges(e,t))},merge:function(e,t){let r=Mt(e.getConfig()),i=Mt(t.getConfig()),n=r.parsed,a=i.parsed;n.customWeeks=r.customWeeks,a.customWeeks=i.customWeeks;var o={hours:this._toHoursArray(this._mergeHoursConfig(n.hours,a.hours)),dates:{},customWeeks:{}};let s=(l,d)=>{for(let u in l.dates){let f=l.dates[u];+u>1e3&&(o.dates[u]=!1);for(let p in d.dates){let y=d.dates[p];if(p==u&&(o.dates[u]=!!(f&&y)),Array.isArray(f)){let g=Array.isArray(y)?y:d.hours;o.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,g))}}}};if(s(n,a),s(a,n),n.customWeeks)for(var c in n.customWeeks)o.customWeeks[c]=n.customWeeks[c];if(a.customWeeks)for(var c in a.customWeeks)o.customWeeks[c]?o.customWeeks[c+"_second"]=a.customWeeks[c]:o.customWeeks[c]=a.customWeeks[c];return o}};var Na=class{constructor(){this.clear()}getItem(t,r,i){if(this._cache.has(t)){let a=this._cache.get(t)[i.getUTCFullYear()];if(a&&a.has(r))return a.get(r)}return-1}setItem(t,r,i,n){if(!t||!r)return;let a=this._cache,o=n.getUTCFullYear(),s;a.has(t)?s=a.get(t):(s=[],a.set(t,s));let c=s[o];c||(c=s[o]=new Map),c.set(r,i)}clear(){this._cache=new Map}},wa=class{constructor(){this.clear()}getItem(t,r,i){let n=this._cache;if(n&&n[t]){let a=n[t];if(a===void 0)return-1;let o=a[i.getUTCFullYear()];if(o&&o[r]!==void 0)return o[r]}return-1}setItem(t,r,i,n){if(!t||!r)return;let a=this._cache;if(!a)return;a[t]||(a[t]=[]);let o=a[t],s=n.getUTCFullYear(),c=o[s];c||(c=o[s]={}),c[r]=i}clear(){this._cache={}}},Fa=class{constructor(t){this.getMinutesPerWeek=r=>{let i=r.valueOf();if(this._weekCache.has(i))return this._weekCache.get(i);let n=this._calendar,a=this._calendar.$gantt,o=0,s=a.date.week_start(new Date(r));for(let c=0;c<7;c++)o+=n.getHoursPerDay(s)*60,s=a.date.add(s,1,"day");return this._weekCache.set(i,o),o},this.getMinutesPerMonth=r=>{let i=r.valueOf();if(this._monthCache.has(i))return this._monthCache.get(i);let n=this._calendar,a=this._calendar.$gantt,o=0,s=a.date.week_start(new Date(r)),c=a.date.add(s,1,"month").valueOf();for(;s.valueOf()<c;)o+=n.getHoursPerDay(s)*60,s=a.date.add(s,1,"day");return this._monthCache.set(i,o),o},this.clear=()=>{this._weekCache=new Map,this._monthCache=new Map},this.clear(),this._calendar=t}};function mg(){return typeof Map<"u"?new Na:new wa}var xa=class{constructor(){this.clear()}_getCacheObject(t,r,i){let n=this._cache;n[r]||(n[r]=[]);let a=n[r];a||(a=n[r]={});let o=a[i];o||(o=a[i]={});let s=t.getUTCFullYear(),c=o[s];return c||(c=o[s]={durations:{},endDates:{}}),c}_endDateCacheKey(t,r){return String(t)+"-"+String(r)}_durationCacheKey(t,r){return String(t)+"-"+String(r)}getEndDate(t,r,i,n,a){let o=this._getCacheObject(t,i,n),s=t.valueOf(),c=this._endDateCacheKey(s,r),l;if(o.endDates[c]===void 0){let d=a(),u=d.valueOf();o.endDates[c]=u,o.durations[this._durationCacheKey(s,u)]=r,l=d}else l=new Date(o.endDates[c]);return l}getDuration(t,r,i,n,a){let o=this._getCacheObject(t,i,n),s=t.valueOf(),c=r.valueOf(),l=this._durationCacheKey(s,c),d;if(o.durations[l]===void 0){let u=a();o.durations[l]=u.valueOf(),d=u}else d=o.durations[l];return d}clear(){this._cache={}}};function Ma(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=mg(),this._largeUnitsCache=new Fa(this),this._dateDurationCache=new xa,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}Ma.prototype={units:["year","month","week","day","hour","minute"],_clearCaches:function(){this._workingUnitsCache.clear(),this._largeUnitsCache.clear(),this._dateDurationCache.clear()},_getUnitOrder:function(e){for(var t=0,r=this.units.length;t<r;t++)if(this.units[t]==e)return t},_resetTimestampCache:function(){this._cached_timestamps={},this._cached_timestamps_count=0},_timestamp:function(e){this._cached_timestamps_count>1e6&&this._resetTimestampCache();var t=null;if(e.day||e.day===0)t=e.day;else if(e.date){var r=String(e.date.valueOf());this._cached_timestamps[r]?t=this._cached_timestamps[r]:(t=Date.UTC(e.date.getUTCFullYear(),e.date.getUTCMonth(),e.date.getUTCDate()),this._cached_timestamps[r]=t,this._cached_timestamps_count++)}return t},_checkIfWorkingUnit:function(e,t){if(!this["_is_work_"+t]){let r=this.$gantt.date[`${t}_start`](new Date(e)),i=this.$gantt.date.add(r,1,t);return this.hasDuration(r,i)}return this["_is_work_"+t](e)},_is_work_day:function(e){var t=this._getWorkHours(e);return Array.isArray(t)?t.length>0:!1},_is_work_hour:function(e){for(var t=this._getWorkHours(e),r=e.getUTCHours(),i=0;i<t.length;i++)if(r>=t[i].startHour&&r<t[i].endHour)return!0;return!1},_getTimeOfDayStamp:function(e,t){var r=e.getUTCHours();return!e.getUTCHours()&&!e.getUTCMinutes()&&t&&(r=24),r*60*60+e.getUTCMinutes()*60},_is_work_minute:function(e){for(var t=this._getWorkHours(e),r=this._getTimeOfDayStamp(e),i=0;i<t.length;i++)if(r>=t[i].start&&r<t[i].end)return!0;return!1},_nextDate:function(e,t,r){return this.$gantt.date.add(e,r,t)},_getWorkUnitsBetweenGeneric:function(e,t,r,i){var n=this.$gantt.date,a=new Date(e),o=new Date(t);i=i||1;var s=0,c=null,l,d,u=!1;l=n[r+"_start"](new Date(a)),l.valueOf()!=a.valueOf()&&(u=!0);var f=!1;d=n[r+"_start"](new Date(t)),d.valueOf()!=t.valueOf()&&(f=!0);for(var p=!1;a.valueOf()<o.valueOf();){if(c=this._nextDate(a,r,i),p=c.valueOf()>o.valueOf(),this._isWorkTime(a,r))(u||f&&p)&&(l=n[r+"_start"](new Date(a)),d=n.add(l,i,r)),u?(u=!1,c=this._nextDate(l,r,i),s+=(d.valueOf()-a.valueOf())/(d.valueOf()-l.valueOf())):f&&p?(f=!1,s+=(o.valueOf()-a.valueOf())/(d.valueOf()-l.valueOf())):s++;else{var y=this._getUnitOrder(r),g=this.units[y-1];g&&!this._isWorkTime(a,g)&&(c=this._getClosestWorkTimeFuture(a,g))}a=c}return s},_getMinutesPerHour:function(e){var t=this._getTimeOfDayStamp(e),r=this._getTimeOfDayStamp(this._nextDate(e,"hour",1));r===0&&(r=1440*60);for(var i=this._getWorkHours(e),n=0;n<i.length;n++){var a=i[n];if(t>=a.start&&r<=a.end)return 60;if(t<a.end&&r>a.start){var o=Math.min(r,a.end)-Math.max(t,a.start);return o/60}}return 0},_getMinutesPerDay:function(e){var t=this._getWorkHours(e),r=0;return t.forEach(function(i){r+=i.durationMinutes}),r},getHoursPerDay:function(e){var t=this._getWorkHours(e),r=0;return t.forEach(function(i){r+=i.durationHours}),r},_getWorkUnitsForRange:function(e,t,r,i){var n=0,a=new Date(e),o=new Date(t),s;for(r=="minute"?s=Et(this._getMinutesPerDay,this):s=Et(this.getHoursPerDay,this);a.valueOf()<o.valueOf();){if(o-a>1e3*60*60*24*32&&a.getUTCDate()===0){var c=this._largeUnitsCache.getMinutesPerMonth(a);r=="hour"&&(c=c/60),n+=c,a=this.$gantt.date.add(a,1,"month");continue}else if(o-a>1e3*60*60*24*16){var l=this.$gantt.date.week_start(new Date(a));if(a.valueOf()===l.valueOf()){var c=this._largeUnitsCache.getMinutesPerWeek(a);r=="hour"&&(c=c/60),n+=c,a=this.$gantt.date.add(a,7,"day");continue}}n+=s(a),a=this._nextDate(a,"day",1)}return n/i},_getMinutesBetweenSingleDay:function(e,t){for(var r=this._getIntervalTimestamp(e,t),i=this._getWorkHours(e),n=0,a=0;a<i.length;a++){var o=i[a];if(r.end>=o.start&&r.start<=o.end){var s=Math.max(o.start,r.start),c=Math.min(o.end,r.end);n+=(c-s)/60,r.start=c}}return Math.floor(n)},_getMinutesBetween:function(e,t,r,i){var n=new Date(e),a=new Date(t);i=i||1;var o=new Date(n),s=this.$gantt.date.add(this.$gantt.date.day_start(new Date(n)),1,"day");if(a.valueOf()<=s.valueOf())return this._getMinutesBetweenSingleDay(e,t);var c=this.$gantt.date.day_start(new Date(a)),l=a,d=this._getMinutesBetweenSingleDay(o,s),u=this._getMinutesBetweenSingleDay(c,l),f=this._getWorkUnitsForRange(s,c,r,i),p=d+f+u;return p},_getHoursBetween:function(e,t,r,i){var n=new Date(e),a=new Date(t);i=i||1;var o=new Date(n),s=this.$gantt.date.add(this.$gantt.date.day_start(new Date(n)),1,"day");if(a.valueOf()<=s.valueOf())return Math.round(this._getMinutesBetweenSingleDay(e,t)/60);var c=this.$gantt.date.day_start(new Date(a)),l=a,d=this._getMinutesBetweenSingleDay(o,s,r,i)/60,u=this._getMinutesBetweenSingleDay(c,l,r,i)/60,f=this._getWorkUnitsForRange(s,c,r,i),p=d+f+u;return Math.round(p)},getConfig:function(){return this._worktime},_setConfig:function(e){this._worktime=e,this._parseSettings(),this._clearCaches()},_parseSettings:function(){var e=this.getConfig();e.parsed={dates:{},hours:null,haveCustomWeeks:!1,customWeeks:{},customWeeksRangeStart:null,customWeeksRangeEnd:null,customWeeksBoundaries:[]},e.parsed.hours=this._parseHours(e.hours);for(var t in e.dates)e.parsed.dates[t]=this._parseHours(e.dates[t]);if(e.customWeeks){var r=null,i=null;for(var t in e.customWeeks){var n=e.customWeeks[t];if(n.from&&n.to){var a=n.from,o=n.to;(!r||r>a.valueOf())&&(r=a.valueOf()),(!i||i<o.valueOf())&&(i=o.valueOf()),e.parsed.customWeeksBoundaries.push({from:a.valueOf(),fromReadable:new Date(a),to:o.valueOf(),toReadable:new Date(o),name:t}),e.parsed.haveCustomWeeks=!0;var s=e.parsed.customWeeks[t]={from:n.from,to:n.to,hours:this._parseHours(n.hours),dates:{}};if(n.days&&!n.dates){n.dates=n.dates||{};for(var t=0;t<n.days.length;t++)n.dates[t]=n.days[t],n.days[t]instanceof Array||(n.dates[t]=!!n.days[t]);delete n.days}for(var c in n.dates)s.dates[c]=this._parseHours(n.dates[c])}}e.parsed.customWeeksRangeStart=r,e.parsed.customWeeksRangeEnd=i}},_tryChangeCalendarSettings:function(e){var t=JSON.stringify(this.getConfig());return e(),this.hasWorkTime()?!0:(this._setConfig(JSON.parse(t)),this._clearCaches(),!1)},_arraysEqual:function(e,t){if(e===t)return!0;if(!e||!t||e.length!=t.length)return!1;for(var r=0;r<e.length;++r)if(e[r]!==t[r])return!1;return!0},_compareSettings:function(e,t){if(!this._arraysEqual(e.hours,t.hours))return!1;var r=Object.keys(e.dates),i=Object.keys(t.dates);if(r.sort(),i.sort(),!this._arraysEqual(r,i))return!1;for(var n=0;n<r.length;n++){var a=r[n],o=e.dates[a],s=t.dates[a];if(o!==s&&!(Array.isArray(o)&&Array.isArray(s)&&this._arraysEqual(o,s)))return!1}return!0},equals:function(e){if(!(e instanceof Ma))return!1;var t=this.getConfig(),r=e.getConfig();if(!this._compareSettings(t,r))return!1;if(t.parsed.haveCustomWeeks&&r.parsed.haveCustomWeeks){if(t.parsed.customWeeksBoundaries.length!=r.parsed.customWeeksBoundaries.length)return!1;for(var i in t.parsed.customWeeks){var n=t.parsed.customWeeks[i],a=r.parsed.customWeeks[i];if(!a||!this._compareSettings(n,a))return!1}}else if(t.parse.haveCustomWeeks!==r.parsed.haveCustomWeeks)return!1;return!0},getWorkHours:function(){var e=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);return this._getWorkHours(e.date,!1)},_getWorkHours:function(e,t){var r=this.getConfig();if(t!==!1&&(r=r.parsed),!e)return r.hours;let i=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));var n=this._timestamp({date:i});if(r.haveCustomWeeks&&r.customWeeksRangeStart<=n&&r.customWeeksRangeEnd>n){for(var a=0;a<r.customWeeksBoundaries.length;a++)if(r.customWeeksBoundaries[a].from<=n&&r.customWeeksBoundaries[a].to>n){r=r.customWeeks[r.customWeeksBoundaries[a].name];break}}var o=!0;return r.dates[n]!==void 0?o=r.dates[n]:r.dates[e.getUTCDay()]!==void 0&&(o=r.dates[e.getUTCDay()]),o===!0?r.hours:o||[]},_getIntervalTimestamp:function(e,t){var r={start:0,end:0};r.start=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds();var i=t.getUTCHours();return!i&&!t.getUTCMinutes()&&!t.getUTCSeconds()&&e.valueOf()<t.valueOf()&&(i=24),r.end=i*60*60+t.getUTCMinutes()*60+t.getUTCSeconds(),r},_parseHours:function(e){if(Array.isArray(e)){var t=[];e.forEach(function(s){typeof s=="number"?t.push(s*60*60):typeof s=="string"&&s.split("-").map(function(c){return c.trim()}).forEach(function(c){var l=c.split(":").map(function(u){return u.trim()}),d=parseInt(l[0]*60*60);l[1]&&(d+=parseInt(l[1]*60)),l[2]&&(d+=parseInt(l[2])),t.push(d)})});for(var r=[],i=0;i<t.length;i+=2){var n=t[i],a=t[i+1],o=a-n;r.push({start:n,end:a,startHour:Math.floor(n/3600),startMinute:Math.floor(n/60),endHour:Math.ceil(a/3600),endMinute:Math.ceil(a/60),durationSeconds:o,durationMinutes:o/60,durationHours:o/3600})}return r}else return e},setWorkTime:function(e){return this._tryChangeCalendarSettings(Et(function(){var t=e.hours!==void 0?e.hours:!0,r=this._timestamp(e),i=this.getConfig();if(r!==null?i.dates[r]=t:e.customWeeks||(i.hours=t),e.customWeeks){if(i.customWeeks||(i.customWeeks={}),typeof e.customWeeks=="string")r!==null?i.customWeeks[e.customWeeks].dates[r]=t:e.customWeeks||(i.customWeeks[e.customWeeks].hours=t);else if(typeof e.customWeeks=="object"&&e.customWeeks.constructor===Object)for(var n in e.customWeeks)i.customWeeks[n]=e.customWeeks[n]}this._parseSettings(),this._clearCaches()},this))},unsetWorkTime:function(e){return this._tryChangeCalendarSettings(Et(function(){if(!e)this.reset_calendar();else{var t=this._timestamp(e);t!==null&&delete this.getConfig().dates[t]}this._parseSettings(),this._clearCaches()},this))},_isWorkTime:function(e,t){var r=-1,i=null;return i=String(e.valueOf()),r=this._workingUnitsCache.getItem(t,i,e),r==-1&&(r=this._checkIfWorkingUnit(e,t),this._workingUnitsCache.setItem(t,i,r,e)),r},isWorkTime:function(){var e=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._isWorkTime(e.date,e.unit)},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments);if(!e.unit)return!1;var t=this;return this._dateDurationCache.getDuration(e.start_date,e.end_date,e.unit,e.step,function(){return t._calculateDuration(e.start_date,e.end_date,e.unit,e.step)})},_calculateDuration:function(e,t,r,i){var n=0,a=1;if(e.valueOf()>t.valueOf()){var o=t;t=e,e=o,a=-1}return r=="hour"&&i==1?n=this._getHoursBetween(e,t,r,i):r=="minute"&&i==1?n=this._getMinutesBetween(e,t,r,i):n=this._getWorkUnitsBetweenGeneric(e,t,r,i),a*Math.round(n)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit,n=e.step;if(!i)return!1;var a=new Date(t),o=new Date(r);for(n=n||1;a.valueOf()<o.valueOf();){if(this._isWorkTime(a,i))return!0;a=this._nextDate(a,i,n)}return!1},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,i=e.unit,n=e.step;if(!i)return!1;var a=e.duration>=0?1:-1;r=Math.abs(r*1);var o=this;return this._dateDurationCache.getEndDate(t,r,i,n*a,function(){return o._calculateEndDate(t,r,i,n*a)})},_calculateEndDate:function(e,t,r,i){if(!r)return!1;if(i==1&&r=="minute")return this._calculateMinuteEndDate(e,t,i);if(i==-1&&r=="minute")return this._subtractMinuteDate(e,t,i);if(i==1&&r=="hour")return this._calculateHourEndDate(e,t,i);var n=this._addInterval(e,t,r,i,null);return n.end},_addInterval:function(e,t,r,i,n){for(var a=0,o=e;a<t&&!(n&&n(o));){var s=this._nextDate(o,r,i),c=new Date(s.valueOf()+1);i>0&&(c=new Date(s.valueOf()-1));var l=this._isWorkTime(c,r);l&&a++,o=s}return{end:o,start:e,added:a}},_addHoursUntilDayEnd:function(e,t){for(var r=this.$gantt.date.add(this.$gantt.date.day_start(new Date(e)),1,"day"),i=0,n=t,a=this._getIntervalTimestamp(e,r),o=this._getWorkHours(e),s=0;s<o.length&&i<t;s++){var c=o[s];if(a.end>=c.start&&a.start<=c.end){var l=Math.max(c.start,a.start),d=Math.min(c.end,a.end),u=(d-l)/3600;u>n&&(u=n,d=l+n*60*60);var f=Math.round((d-l)/3600);i+=f,n-=f,a.start=d}}var p=r;return i===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:i,end:p}},_calculateHourEndDate:function(e,t,r){var i=new Date(e),n=0;r=r||1,t=Math.abs(t*1);var a=this._addHoursUntilDayEnd(i,t);n=a.added,i=a.end;var o=t-n;if(o){for(var s=i;n<t;){var c=this._nextDate(s,"day",r);c.setUTCHours(0),c.setUTCMinutes(0),c.setUTCSeconds(0);var l=0;if(r>0?l=this.getHoursPerDay(new Date(c.valueOf()-1)):l=this.getHoursPerDay(new Date(c.valueOf()+1)),n+l>=t)break;n+=l,s=c}i=s}if(n<t){var o=t-n;a=this._addHoursUntilDayEnd(i,o),i=a.end}return i},_addMinutesUntilHourEnd:function(e,t){if(e.getUTCMinutes()===0)return{added:0,end:new Date(e)};for(var r=this.$gantt.date.add(this.$gantt.date.hour_start(new Date(e)),1,"hour"),i=0,n=t,a=this._getIntervalTimestamp(e,r),o=this._getWorkHours(e),s=0;s<o.length&&i<t;s++){var c=o[s];if(a.end>=c.start&&a.start<=c.end){var l=Math.max(c.start,a.start),d=Math.min(c.end,a.end),u=(d-l)/60;u>n&&(u=n,d=l+n*60);var f=Math.round((d-l)/60);n-=f,i+=f,a.start=d}}var p=r;return i===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:i,end:p}},_subtractMinutesUntilHourStart:function(e,t){for(var r=this.$gantt.date.hour_start(new Date(e)),i=0,n=t,a=r.getUTCHours()*60*60+r.getUTCMinutes()*60+r.getUTCSeconds(),o=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds(),s=this._getWorkHours(e),c=s.length-1;c>=0&&i<t;c--){var l=s[c];if(o>l.start&&a<=l.end){var d=Math.min(o,l.end),u=Math.max(a,l.start),f=(d-u)/60;f>n&&(f=n,u=d-n*60);var p=Math.abs(Math.round((d-u)/60));n-=p,i+=p,o=u}}var y=r;return i===t&&(y=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,o))),{added:i,end:y}},_subtractMinuteDate:function(e,t,r){var i=this.getClosestWorkTime({date:e,dir:"past",unit:"minute"}),n=0;r=r||-1,t=Math.abs(t*1),t=Math.round(t);let a=this._isMinutePrecision(i),o=this._subtractMinutesUntilHourStart(i,t);n+=o.added,i=o.end;for(var s=0,c=[],l=0;n<t;){var d=this.$gantt.date.day_start(new Date(i)),u=!1;i.valueOf()===d.valueOf()&&(d=this.$gantt.date.add(d,-1,"day"),u=!0);var f=new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),23,59,59,999)).valueOf();f!==s&&(c=this._getWorkHours(d),l=this._getMinutesPerDay(d),s=f);var p=t-n,y=this._getTimeOfDayStamp(i,u);if(!c.length||!l){i=this.$gantt.date.add(i,-1,"day");continue}if(c[c.length-1].end<=y&&p>l){n+=l,i=this.$gantt.date.add(i,-1,"day");continue}for(var g=!1,C=null,R=null,A=c.length-1;A>=0;A--)if(c[A].start<y-1&&c[A].end>=y-1){g=!0,C=c[A],R=c[A-1];break}if(g)if(y===C.end&&p>=C.durationMinutes)n+=C.durationMinutes,i=this.$gantt.date.add(i,-C.durationMinutes,"minute");else if(!a&&p<=y/60-C.startMinute)n+=p,i=this.$gantt.date.add(i,-p,"minute");else if(a)p<=y/60-C.startMinute?(n+=p,i=this.$gantt.date.add(i,-p,"minute")):(n+=y/60-C.startMinute,R?i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,R.end)):i=this.$gantt.date.day_start(i));else{var k=this._getMinutesPerHour(i);k<=p?(n+=k,i=this._nextDate(i,"hour",r)):(o=this._subtractMinutesUntilHourStart(i,p),n+=o.added,i=o.end)}else if(i.getUTCHours()===0&&i.getUTCMinutes()===0&&i.getUTCSeconds()===0){var m=this._getClosestWorkTimePast(i,"hour");if(m.valueOf()===i.valueOf()){var m=this.$gantt.date.add(i,-1,"day"),L=this._getWorkHours(m);if(L.length){var F=L[L.length-1];m.setUTCSeconds(F.durationSeconds)}}i=m}else i=this._getClosestWorkTimePast(new Date(i-1),"hour")}if(n<t){var T=t-n;o=this._subtractMinutesUntilHourStart(i,T),n+=o.added,i=o.end}return i},_calculateMinuteEndDate:function(e,t,r){var i=new Date(e),n=0;r=r||1,t=Math.abs(t*1),t=Math.round(t);var a=this._addMinutesUntilHourEnd(i,t);n+=a.added,i=a.end;for(var o=0,s=[],c=0,l=this._isMinutePrecision(i);n<t;){var d=this.$gantt.date.day_start(new Date(i)).valueOf();d!==o&&(s=this._getWorkHours(i),c=this._getMinutesPerDay(i),o=d);var u=t-n,f=this._getTimeOfDayStamp(i);if(!s.length||!c){i=this.$gantt.date.add(this.$gantt.date.day_start(i),1,"day");continue}if(s[0].start>=f&&u>=c){if(n+=c,u==c){i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,s[s.length-1].end));break}else i=this.$gantt.date.add(i,1,"day"),i=this.$gantt.date.day_start(i);continue}for(var p=!1,y=null,g=0;g<s.length;g++)if(s[g].start<=f&&s[g].end>f){p=!0,y=s[g];break}if(p)if(f===y.start&&u>=y.durationMinutes)n+=y.durationMinutes,i=this.$gantt.date.add(i,y.durationMinutes,"minute");else if(u<=y.endMinute-f/60)n+=u,i=this.$gantt.date.add(i,u,"minute");else{var C=this._getMinutesPerHour(i);C<=u?(n+=C,l?i=this.$gantt.date.add(i,C,"minute"):i=this._nextDate(i,"hour",r)):(a=this._addMinutesUntilHourEnd(i,u),n+=a.added,i=a.end)}else i=this._getClosestWorkTimeFuture(i,"hour")}if(n<t){var R=t-n;a=this._addMinutesUntilHourEnd(i,R),n+=a.added,i=a.end}return i},getClosestWorkTime:function(){var e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._getClosestWorkTime(e.date,e.unit,e.dir)},_getClosestWorkTime:function(e,t,r){var i=new Date(e);if(this._isWorkTime(i,t))return i;if(i=this.$gantt.date[t+"_start"](i),r=="any"||!r){var n=this._getClosestWorkTimeFuture(i,t),a=this._getClosestWorkTimePast(i,t);Math.abs(n-e)<=Math.abs(e-a)?i=n:i=a}else r=="past"?i=this._getClosestWorkTimePast(i,t):i=this._getClosestWorkTimeFuture(i,t);return i},_getClosestWorkTimeFuture:function(e,t){return this._getClosestWorkTimeGeneric(e,t,1)},_getClosestWorkTimePast:function(e,t){var r=this._getClosestWorkTimeGeneric(e,t,-1);return this.$gantt.date.add(r,1,t)},_findClosestTimeInDay:function(e,t,r){var i=new Date(e),n=null,a=!1;this._getWorkHours(i).length||(i=this._getClosestWorkTime(i,"day",t<0?"past":"future"),t<0&&(i=new Date(i.valueOf()-1),a=!0),r=this._getWorkHours(i));var o=this._getTimeOfDayStamp(i);if(a&&(o=this._getTimeOfDayStamp(new Date(i.valueOf()+1),a)),t>0){for(var s=0;s<r.length;s++)if(r[s].start>=o){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,r[s].start));break}}else for(var s=r.length-1;s>=0;s--)if(r[s].end<=o){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,r[s].end));break}else if(r[s].end>o&&r[s].start<=o){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,o));break}return n},_getClosestWorkMinute:function(e,t,r){var i=new Date(e),n=this._getWorkHours(i),a=this._findClosestTimeInDay(i,r,n);return a||(r>0?(i=this.calculateEndDate(i,r,t),i=this.$gantt.date.day_start(i)):(i=this.calculateEndDate(i,r,"day"),i=this.$gantt.date.day_start(i),i=this.$gantt.date.add(i,1,"day"),i=new Date(i.valueOf()-1)),n=this._getWorkHours(i),a=this._findClosestTimeInDay(i,r,n)),r<0&&(a=this.$gantt.date.add(a,-1,t)),a},_getClosestWorkTimeGeneric:function(e,t,r){if(t==="hour"||t==="minute")return this._getClosestWorkMinute(e,t,r);for(var i=this._getUnitOrder(t),n=this.units[i-1],a=e,o=3e3,s=0;!this._isWorkTime(a,t)&&!(n&&!this._isWorkTime(a,n)&&(r>0?a=this._getClosestWorkTimeFuture(a,n):a=this._getClosestWorkTimePast(a,n),this._isWorkTime(a,t)));){if(s++,s>o)return this.$gantt.assert(!1,"Invalid working time check"),!1;a=this.$gantt.date.add(a,r,t),this.$gantt.date[t+"_start"]&&(a=this.$gantt.date[t+"_start"](a))}return a},hasWorkTime:function(){var e=this.getConfig(),t=e.dates,r=[0,1,2,3,4,5,6];for(var i in e.dates);var n=this._checkWorkHours(e.hours),a=!1;return r.forEach((function(o){if(!a){var s=t[o];s===!0?a=n:Array.isArray(s)&&(a=this._checkWorkHours(s))}}).bind(this)),a},_checkWorkHours:function(e){if(e.length===0)return!1;for(var t=!1,r=0;r<e.length;r+=2)e[r]!==e[r+1]&&(t=!0);return t},_isMinutePrecision:function(e){let t=!1;return this._getWorkHours(e).forEach(function(r){(r.startMinute%60||r.endMinute%60)&&(t=!0)}),t}};var Pr={isLegacyResourceCalendarFormat:function(e){if(!e)return!1;for(var t in e)if(e[t]&&typeof e[t]=="object")return!0;return!1},getResourceProperty:function(e){var t=e.resource_calendars,r=e.resource_property;if(this.isLegacyResourceCalendarFormat(t))for(var i in e){r=i;break}return r},getCalendarIdFromLegacyConfig:function(e,t){if(t)for(var r in t){var i=t[r];if(e[r]){var n=i[e[r]];if(n)return n}}return null}};function gg(){function e(n){return n.map(function(a){return a&&a.resource_id?a.resource_id:a}).sort().join("-")}var t={};function r(n,a){return a.mergeCalendars(n.map(function(o){var s=o&&o.resource_id?o.resource_id:o;return a.getResourceCalendar(s)}))}function i(n,a){var o=e(n);if(n.length){if(n.length===1)return a.getResourceCalendar(o).id;if(t[o])return t[o].id;var s=r(n,a);return t[o]=s,a.addCalendar(s)}else return null}return{getCalendarIdFromMultipleResources:i}}var Ag=gg();function Vl(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=Pr.isLegacyResourceCalendarFormat(this.$gantt.config.resource_calendars))}).bind(this)),this.$gantt.attachEvent("onBeforeGanttReady",(function(){this.createDefaultCalendars()}).bind(this)),this.$gantt.attachEvent("onBeforeGanttRender",(function(){this.createDefaultCalendars()}).bind(this))}Vl.prototype={_calendars:{},_convertWorkTimeSettings:function(e){let t=e.days;if(typeof t=="object"&&!Array.isArray(t)&&t!==null){let r={};if(t?.weekdays)for(let i=0;i<7;i++)r[i]=t.weekdays[i];t?.dates&&Object.entries(t.dates).forEach(([i,n])=>{r[new Date(i).valueOf()]=n}),Object.entries(r).forEach(([i,n])=>{n instanceof Array||(r[i]=!!n)}),e={...e,dates:r}}else if(t&&!e.dates){e.dates=e.dates||{};for(let r=0;r<t.length;r++)e.dates[r]=t[r],t[r]instanceof Array||(e.dates[r]=!!t[r])}return delete e.days,e},mergeCalendars:function(){var e=[],t=arguments;if(Array.isArray(t[0]))e=t[0].slice();else for(var r=0;r<arguments.length;r++)e.push(arguments[r]);var i=new jl,n;return e.forEach((function(a){n?n=this._createCalendarFromConfig(i.merge(n,a)):n=a}).bind(this)),this.createCalendar(n)},_createCalendarFromConfig:function(e){var t=new Ma(this.$gantt,Hl(this.$gantt));t.id=String(Pa());var r=this._convertWorkTimeSettings(e);if(r.customWeeks)for(var i in r.customWeeks)r.customWeeks[i]=this._convertWorkTimeSettings(r.customWeeks[i]);return t._setConfig(r),t},createCalendar:function(e){var t;e||(e={}),e.getConfig?t=Mt(e.getConfig()):e.worktime?t=Mt(e.worktime):t=Mt(e);var r=Mt(this.defaults.fulltime.worktime);return er(t,r),this._createCalendarFromConfig(t)},getCalendar:function(e){e=e||"global";var t=this._calendars[e];return t||(this.createDefaultCalendars(),t=this._calendars[e]),t},getCalendars:function(){var e=[];for(var t in this._calendars)e.push(this.getCalendar(t));return e},_getOwnCalendar:function(e){var t=this.$gantt.config;if(e[t.calendar_property])return this.getCalendar(e[t.calendar_property]);if(t.resource_calendars){var r,i,n;if(this._legacyConfig===!1?n=t.resource_property:n=Pr.getResourceProperty(t),Array.isArray(e[n])&&e[n].length)t.dynamic_resource_calendars?i=Ag.getCalendarIdFromMultipleResources(e[n],this):r=this.getResourceCalendar(e[n]);else if(this._legacyConfig===void 0&&(this._legacyConfig=Pr.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var i=Pr.getCalendarIdFromLegacyConfig(e,t.resource_calendars);else if(n&&e[n]&&t.resource_calendars[e[n]])var r=this.getResourceCalendar(e[n]);if(i&&(r=this.getCalendar(i)),r)return r}return null},getResourceCalendar:function(e){if(e==null)return this.getCalendar();var t=null;typeof e=="number"||typeof e=="string"?t=e:t=e.id||e.key;var r=this.$gantt.config,i=r.resource_calendars,n=null;if(Array.isArray(e)&&e.length===1&&(typeof e[0]=="object"?t=e[0].resource_id:t=e[0]),i){if(this._legacyConfig===void 0&&(this._legacyConfig=Pr.isLegacyResourceCalendarFormat(r.resource_calendars)),this._legacyConfig){for(var a in i)if(i[a][t]){n=i[a][t];break}}else var n=i[t];if(n)return this.getCalendar(n)}return this.getCalendar()},getTaskCalendar:function(e){var t=this.$gantt,r;if(e==null)return this.getCalendar();if((typeof e=="number"||typeof e=="string")&&t.isTaskExists(e)?r=t.getTask(e):r=e,!r)return this.getCalendar();var i=this._getOwnCalendar(r),n=!!t.getState().group_mode;if(!i&&t.config.inherit_calendar&&t.isTaskExists(r.parent)){for(var a=r;t.isTaskExists(a.parent)&&(a=t.getTask(a.parent),!(t.isSummaryTask(a)&&(i=this._getOwnCalendar(a),i))););n&&!i&&e.$effective_calendar&&(i=this.getCalendar(e.$effective_calendar))}return i||this.getCalendar()},addCalendar:function(e){if(!this.isCalendar(e)){var t=e.id;e=this.createCalendar(e),e.id=t}if(e._tryChangeCalendarSettings(function(){})){var r=this.$gantt.config;return e.id=e.id||Pa(),this._calendars[e.id]=e,r.worktimes||(r.worktimes={}),r.worktimes[e.id]=e.getConfig(),e.id}else return this.$gantt.callEvent("onCalendarError",[{message:"Invalid calendar settings, no worktime available"},e]),null},deleteCalendar:function(e){var t=this.$gantt.config;return e&&this._calendars[e]?(delete this._calendars[e],t.worktimes&&t.worktimes[e]&&delete t.worktimes[e],!0):!1},restoreConfigCalendars:function(e){for(var t in e)if(!this._calendars[t]){var r=e[t],i=this.createCalendar(r);i.id=t,this.addCalendar(i)}},defaults:{global:{id:"global",worktime:{hours:[8,12,13,17],days:[0,1,1,1,1,1,0]}},fulltime:{id:"fulltime",worktime:{hours:[0,24],days:[1,1,1,1,1,1,1]}}},createDefaultCalendars:function(){var e=this.$gantt.config;this.restoreConfigCalendars(this.defaults),this.restoreConfigCalendars(e.worktimes)},isCalendar:function(e){var t=[e.isWorkTime,e.setWorkTime,e.getWorkHours,e.unsetWorkTime,e.getClosestWorkTime,e.calculateDuration,e.hasDuration,e.calculateEndDate];return t.every(function(r){return r instanceof Function})}};function Ua(e,t){this.argumentsHelper=t,this.$gantt=e}Ua.prototype={getWorkHours:function(){return[0,24]},setWorkTime:function(){return!0},unsetWorkTime:function(){return!0},isWorkTime:function(){return!0},getClosestWorkTime:function(t){var t=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return t.date},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit,n=e.step;return this._calculateDuration(t,r,i,n)},_calculateDuration:function(e,t,r,i){var n=this.$gantt.date,a={week:1e3*60*60*24*7,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60},o=0;if(a[r])o=Math.round((t-e)/(i*a[r]));else{for(var s=new Date(e),c=new Date(t);s.valueOf()<c.valueOf();)o+=1,s=n.add(s,i,r);s.valueOf()!=t.valueOf()&&(o+=(c-s)/(n.add(s,i,r)-s))}return Math.round(o)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit;return i?(t=new Date(t),r=new Date(r),t.valueOf()<r.valueOf()):!1},hasWorkTime:function(){return!0},equals:function(e){return e instanceof Ua},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,i=e.unit,n=e.step;return this.$gantt.date.add(t,n*r,i)}};function Kl(e){this.$gantt=e.$gantt,this.argumentsHelper=Hl(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new Ua(this.$gantt,this.argumentsHelper)}Kl.prototype={_getCalendar:function(e){var t;if(!this.$gantt.config.work_time)t=this.$disabledCalendar;else{var r=this.calendarManager;e.task?t=r.getTaskCalendar(e.task):e.id?t=r.getTaskCalendar(e):e.calendar&&(t=e.calendar),t||(t=r.getTaskCalendar())}return t},getWorkHours:function(e){e=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);var t=this._getCalendar(e);return t.getWorkHours(e.date)},setWorkTime:function(e,t){return e=this.argumentsHelper.setWorkTimeArguments.apply(this.argumentsHelper,arguments),t||(t=this.calendarManager.getCalendar()),t.setWorkTime(e)},unsetWorkTime:function(e,t){return e=this.argumentsHelper.unsetWorkTimeArguments.apply(this.argumentsHelper,arguments),t||(t=this.calendarManager.getCalendar()),t.unsetWorkTime(e)},isWorkTime:function(e,t,r,i){var n=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return i=this._getCalendar(n),i.isWorkTime(n)},getClosestWorkTime:function(e){e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);var t=this._getCalendar(e);return t.getClosestWorkTime(e)},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=this._getCalendar(e);return t.calculateDuration(e)},hasDuration:function(){var e=this.argumentsHelper.hasDurationArguments.apply(this.argumentsHelper,arguments),t=this._getCalendar(e);return t.hasDuration(e)},calculateEndDate:function(t){var t=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),r=this._getCalendar(t);return r.calculateEndDate(t)}};var Ig=function(e,t){return{getWorkHours:function(r){return t.getWorkHours(r)},setWorkTime:function(r){return t.setWorkTime(r)},unsetWorkTime:function(r){t.unsetWorkTime(r)},isWorkTime:function(r,i,n){return t.isWorkTime(r,i,n)},getClosestWorkTime:function(r){return t.getClosestWorkTime(r)},calculateDuration:function(r,i,n){return t.calculateDuration(r,i,n)},_hasDuration:function(r,i,n){return t.hasDuration(r,i,n)},calculateEndDate:function(r,i,n,a){return t.calculateEndDate(r,i,n,a)},mergeCalendars:Et(e.mergeCalendars,e),createCalendar:Et(e.createCalendar,e),addCalendar:Et(e.addCalendar,e),getCalendar:Et(e.getCalendar,e),getCalendars:Et(e.getCalendars,e),getResourceCalendar:Et(e.getResourceCalendar,e),getTaskCalendar:Et(e.getTaskCalendar,e),deleteCalendar:Et(e.deleteCalendar,e)}},vg={create:Ig};function Yl(e){var t=new Vl(e),r=new Kl(t),i=vg.create(t,r);er(e,i)}var Gl={date:{month_full:["January","February","March","April","May","June","July","August","September","October","November","December"],month_short:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],day_full:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],day_short:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},labels:{}};function $l(e={}){let t=e.config||{},r={config:Object.assign({duration_unit:"hour",duration_step:1,work_time:!1,worktimes:{},work_days:null,inherit_calendar:!1,calendar_property:"calendar_id",resource_property:"resource_id",resource_calendars:{},dynamic_resource_calendars:!1,start_on_monday:!0,server_utc:!0,csp:"auto",show_errors:!1},t),locale:e.locale||Gl,templates:e.templates||{},getTask:e.getTask||function(i){return null},isTaskExists:e.isTaskExists||function(i){return!1},isSummaryTask:e.isSummaryTask||function(i){return!1},getState:function(){return{group_mode:!1}},callEvent:function(i,n){let a=e.onEvent;return a&&a(i,n),!0},attachEvent:function(){return 0},checkEvent:function(){return!1},detachEvent:function(){},defined:Ml,mixin:er,copy:Mt,assert:function(i,n){if(!i){if(e.throwOnAssert)throw new Error("[calendar] "+n);e.silent!==!0&&console.error("[calendar]",n)}},$services:{getService:function(){return null}},$ui:{getView:function(){return null}}};return r._correct_dst_change=function(i){return i},r.date=Wl(r),r.date.init(),Yl(r),r}function Cg(e={}){let t=$l(e);return{addCalendar:function(r){return t.addCalendar(r)},deleteCalendar:function(r){return t.deleteCalendar(r)},getCalendar:function(r){return t.getCalendar(r)},getCalendars:function(){return t.getCalendars()},mergeCalendars:function(){return t.mergeCalendars.apply(t,arguments)},getTaskCalendar:function(r){return t.getTaskCalendar(r)},getResourceCalendar:function(r){return t.getResourceCalendar(r)},setWorkTime:function(r){return t.setWorkTime(r)},unsetWorkTime:function(r){return t.unsetWorkTime(r)},isWorkTime:function(){return t.isWorkTime.apply(t,arguments)},getClosestWorkTime:function(){return t.getClosestWorkTime.apply(t,arguments)},getWorkHours:function(){return t.getWorkHours.apply(t,arguments)},calculateDuration:function(){return t.calculateDuration.apply(t,arguments)},calculateEndDate:function(){return t.calculateEndDate.apply(t,arguments)},_internals:t}}var zl={createCalendar:Cg};var gF=3600*1e3;function Ql(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:Sg}=zl,Lr="__replay_default__";function kg(e){if(!e||e.length===0||typeof e[0]=="string")return e;let t=e.map(Number);if(t.some(a=>Number.isNaN(a)))return e;let r=t[0],i=t[t.length-1];return t.every((a,o)=>a===r+o)?[`${r}:00-${i+1}:00`]:e}var ql={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},Jl="__main_global__",Tg={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function Xl(e){return!e||e.hours===void 0||e.hours.length>0||e.days?.some(t=>Array.isArray(t)&&t.length>0)===!0?!0:Object.values(e.dates??{}).some(t=>Array.isArray(t)&&t.length>0)}function Dg(e){let t={};if(Array.isArray(e.days))for(let i=0;i<e.days.length;i+=1)t[i]=e.days[i];if(e.dates)for(let[i,n]of Object.entries(e.dates))t[i]=n;let r={hours:kg(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function Zl(e){let t=Sg({config:{work_time:!0}});t.addCalendar({id:Lr,worktime:ql}),t.addCalendar({id:Jl,worktime:Tg});let r=new Set(e.filter(d=>!Xl(d.worktime)).map(d=>String(d.id))),i=e.filter(d=>Xl(d.worktime));for(let d of i)t.addCalendar({id:d.id,worktime:d.worktime?Dg(d.worktime):ql});let n=xl(t),a=n.getCalendar(Lr),o=n.getCalendar(Jl);if(!a||!o)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let s=new Set([Lr]);for(let d of i)s.add(String(d.id));let c=new Map;return{reader:{getCalendar(d){let u=String(d),f=c.get(u);if(f)return f;let p=a;return s.has(u)?p=n.getCalendar(d)??a:r.has(u)&&(p=o),c.set(u,p),p}}}}function td(e){return{hasChildren(t){return e.hasChildren(t)},getParentStartDateIfHasPredecessors(t){let r=e.getActivity(t);if(!r)return null;let i=e.getParent(r.id);return!i||e.getIncomingLinkIds(i.id).length===0?null:i.startDate},getDescendantIds(t){return _g(e,t).map(r=>String(r))},getAncestorIds(t){let r=[],i=e.getActivity(t);for(;i;){let n=i.parentId;if(n===null)break;let a=e.getActivity(n);if(!a)break;r.push(String(n)),i=a}return r},getChildProgressInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,progress:Number(n?.progress??0),ponderator:Number(n?.ponderator??0)}})},getChildHhInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,workHours:Number(n?.workHours??0),progress:Number(n?.progress??0),realWorkHours:Number(n?.realWorkHours??0)}})},getChildUsedCostInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,usedCost:Number(n?.usedCost??0)}})},getChildCostInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,cost:Number(n?.cost??0)}})}}}function _g(e,t){let r=[],i=new Tt;for(let n of e.getChildren(t))i.enqueue(n);for(;!i.isEmpty();){let n=i.dequeue();r.push(n);for(let a of e.getChildren(n))i.enqueue(a)}return r}var Gi=class{_journal=null;begin(){this._journal={dirty:new Set,before:new Map,ops:[],linkFieldCaptured:new Set,correlativeBefore:new Map,scheduledBefore:new Map,progressFallbackBefore:new Map}}peek(){return this._journal}end(){this._journal=null}note(t,r){let i=this._journal;i&&(i.before.has(t)||i.before.set(t,$t(r)),i.dirty.add(t))}noteInsert(t){this._journal?.ops.push({kind:"insert",activityId:t})}noteRemove(t,r){this._journal?.ops.push({kind:"remove",activityId:t,before:$t(r)})}noteLinkAdd(t){this._journal?.ops.push({kind:"link-add",linkId:t})}noteLinkRemove(t,r){this._journal?.ops.push({kind:"link-remove",linkId:t,before:ed(r)})}noteCorrelativeBefore(t,r){let i=this._journal;!i||i.correlativeBefore.has(t)||i.correlativeBefore.set(t,r)}noteScheduledBefore(t,r){let i=this._journal;if(!i)return;let n=$t(r);i.scheduledBefore.has(t)||i.scheduledBefore.set(t,n),i.before.has(t)||i.before.set(t,n),i.dirty.add(t)}noteLinkField(t,r){let i=this._journal;!i||i.linkFieldCaptured.has(t)||(i.linkFieldCaptured.add(t),i.ops.push({kind:"link-field",linkId:t,before:ed(r)}))}noteProgressFallback(t,r){let i=this._journal;!i||i.progressFallbackBefore.has(t)||i.progressFallbackBefore.set(t,r)}};function ed(e){return{...e}}var $i=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=rd(t);return this.reader.getCalendar(r??Lr)}getClosestWorkTime(t){let r=`${Wa(t.task)}|${t.dir}|${t.date.getTime()}`;return Ba(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:pt.HOUR}))}calculateEndDate(t){let r=`${Wa(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return Ba(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${Wa(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return Ba(this._cache.duration,r,()=>this.resolveCalendar(t.task).calculateDuration(t.startDate,t.endDate))}clearCache(){this._cache.closestWorkTime.clear(),this._cache.endDate.clear(),this._cache.duration.clear()}};function Ba(e,t,r){let i=e.get(t);if(i!==void 0)return i;let n=r();return e.set(t,n),n}var Eg="__default__";function rd(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function Wa(e){return rd(e)??Eg}var zi=class{constructor(t){this.activities=t}activities;_childrenByParent=new Map;_roots=[];_dirty=!1;markDirty(){this._dirty=!0}getChildren(t){return this._dirty&&(this.rebuild(),this._dirty=!1),this._childrenByParent.get(String(t))??[]}hasChildren(t){return this._dirty&&(this.rebuild(),this._dirty=!1),(this._childrenByParent.get(String(t))?.length??0)>0}getRootIds(){return this._dirty&&(this.rebuild(),this._dirty=!1),[...this._roots]}isChildOf(t,r){let i=this.activities.get(t)?.parentId,n=0,a=this.activities.size;for(;i&&!N(i);){if(i===r)return!0;if(++n>a)return!1;i=this.activities.get(i)?.parentId}return!1}getParent(t){let r=this.activities.get(t)?.parentId;return!r||N(r)?null:this.activities.get(r)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,r){if(this._dirty)return;if(N(t)){this._roots.push(r);return}let i=String(t),n=this._childrenByParent.get(i);n?n.push(r):this._childrenByParent.set(i,[r])}rebuild(){this._childrenByParent.clear(),this._roots=[];for(let r of this.activities.values()){if(N(r.parentId)){this._roots.push(r.id);continue}let i=String(r.parentId),n=this._childrenByParent.get(i)??[];n.push(r.id),this._childrenByParent.set(i,n)}let t=(r,i)=>{let n=this.activities.get(r),a=this.activities.get(i);return n&&a?Wr(n,a):String(r).localeCompare(String(i))};this._roots.sort(t);for(let r of this._childrenByParent.values())r.sort(t)}};var qi=class{checkedSet=new Set;hiddenSet=new Set;activeFilter=null;activeOrder=null;isChecked(t){return this.checkedSet.has(t)}isVisible(t){return!this.hiddenSet.has(t)}hiddenIds(){return[...this.hiddenSet]}getActiveFilter(){return this.activeFilter}setActiveFilter(t){this.activeFilter=t}getActiveOrder(){return this.activeOrder}setActiveOrder(t){this.activeOrder=t}checkedIds(){return[...this.checkedSet]}checkedCount(){return this.checkedSet.size}setChecked(t,r){return r===this.checkedSet.has(t)?!1:(r?this.checkedSet.add(t):this.checkedSet.delete(t),!0)}setVisible(t,r){return r===!this.hiddenSet.has(t)?!1:(r?this.hiddenSet.delete(t):this.hiddenSet.add(t),!0)}forget(t){this.checkedSet.delete(t),this.hiddenSet.delete(t)}hydrate(t){this.checkedSet=new Set(t.checkedIds??[]),this.hiddenSet=new Set(t.hiddenIds??[]),this.activeFilter=null,this.activeOrder=null}snapshot(){return{checked:new Set(this.checkedSet),hidden:new Set(this.hiddenSet),activeFilter:this.activeFilter,activeOrder:this.activeOrder}}restore(t){this.checkedSet=new Set(t.checked),this.hiddenSet=new Set(t.hidden),this.activeFilter=t.activeFilter,this.activeOrder=t.activeOrder}};var rr=class e{_activities=new Map;_lastStartDate=new Map;_promotionSnapshot=new Map;_progressFallback=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_buildOrderComparator;_cache={ids:null,visualOrderIds:null,orderComparator:null};_writeCapture=new Gi;_viewState=new qi;_filterProjection=null;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_calendar;_flags;_calendarSnapshot;constructor(t,r=()=>null){this._buildOrderComparator=r,this._calendarSnapshot=O(t.calendars);for(let i of t.activities)this._activities.set(i.id,i);for(let i of t.links){let n={...i,freeSlackHours:i.freeSlackHours??null,isCritical:i.isCritical===!0};this._links.set(String(i.id),n),this._indexLink(n)}this._calendar=new $i(Zl(this._calendarSnapshot)),this._flags=Pg(t),this._hierarchy=new zi(this._activities),this._hierarchy.rebuild()}fork(){let t=new e({activities:this.getAllActivities().map($t),links:this.getAllLinks().map(r=>({...r})),calendars:O(this._calendarSnapshot)},this._buildOrderComparator);return t._viewState.restore(O(this._viewState.snapshot())),t._lastStartDate=new Map(Array.from(this._lastStartDate,([r,i])=>[r,new Date(i)])),t._promotionSnapshot=new Map(Array.from(this._promotionSnapshot,([r,i])=>[r,O(i)])),t._progressFallback=new Map(this._progressFallback),t._flags=O(this._flags),t._filterProjection=O(this._filterProjection),t}getAllActivities(){return Array.from(this._activities.values())}getAllLinks(){return Array.from(this._links.values())}getAllIds(){return this._cache.ids?this._cache.ids:(this._cache.ids=Array.from(this._activities.keys()),this._cache.ids)}activityCount(){return this._activities.size}getVisualOrderIds(){return this._cache.visualOrderIds?this._cache.visualOrderIds:(this._cache.visualOrderIds=Lo(this).map(t=>String(t.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null}forEachActivity(t){for(let[r,i]of this._activities)t(i,r)}getParentId(t){return this._hierarchy.getParentId(t)}getActivity(t){return this._activities.get(String(t))??null}getLastStartDate(t){return this._lastStartDate.get(String(t))??null}setLastStartDate(t,r){this._captureLastStartDateOnce(),this._lastStartDate.set(String(t),r)}getPromotionSnapshot(t){return this._promotionSnapshot.get(String(t))??null}setPromotionSnapshot(t,r){this._capturePromotionSnapshotOnce(),this._promotionSnapshot.set(String(t),r)}getProgressFallback(t){return this._progressFallback.get(String(t))??null}setProgressFallback(t,r){let i=String(t),n=this._progressFallback.get(i)??null;Object.is(n,r)||(this._writeCapture.noteProgressFallback(i,n),r===null?this._progressFallback.delete(i):this._progressFallback.set(i,r))}_capturePromotionSnapshotOnce(){this._writeCapture.peek()!==null&&this._promotionSnapshotBefore===null&&(this._promotionSnapshotBefore=new Map(this._promotionSnapshot))}_captureLastStartDateOnce(){this._writeCapture.peek()!==null&&this._lastStartDateBefore===null&&(this._lastStartDateBefore=new Map(this._lastStartDate))}getLink(t){return this._links.get(String(t))??null}activityExists(t){return this._activities.has(String(t))}isChecked(t){return this._viewState.isChecked(String(t))}isVisible(t){return this._viewState.isVisible(String(t))}checkedIds(){return this._viewState.checkedIds()}hiddenIds(){return this._viewState.hiddenIds()}setChecked(t,r){return this._captureViewStateOnce(),this._viewState.setChecked(String(t),r)}setVisible(t,r){return this._captureViewStateOnce(),this._viewState.setVisible(String(t),r)}getActiveFilter(){return this._viewState.getActiveFilter()}setActiveFilter(t){this._captureViewStateOnce(),this._viewState.setActiveFilter(t),this._filterProjection=null}getFilterProjection(){return this._filterProjection}setFilterProjection(t){this._filterProjection=t}getActiveOrder(){return this._viewState.getActiveOrder()}setActiveOrder(t){this._captureViewStateOnce(),this._viewState.setActiveOrder(t),this.invalidateDerivedOrder()}getOrderComparator(){let t=this._viewState.getActiveOrder();return t===null?(this._cache.orderComparator=null,null):this._cache.orderComparator?this._cache.orderComparator:(this._cache.orderComparator=this._buildOrderComparator(t),this._cache.orderComparator)}invalidateDerivedOrder(){this._cache.orderComparator=null,this._cache.visualOrderIds=null}hydrateViewState(t){this._viewState.hydrate(t),this._filterProjection=null,this.invalidateDerivedOrder()}_captureViewStateOnce(){this._writeCapture.peek()!==null&&this._viewStateBefore===null&&(this._viewStateBefore=this._viewState.snapshot())}getOutgoingLinkIds(t){return this._outgoing.get(String(t))??id}getIncomingLinkIds(t){return this._incoming.get(String(t))??id}getChildren(t){return this._hierarchy.getChildren(t)}hasChildren(t){return this._hierarchy.hasChildren(t)}isChildOf(t,r){return this._hierarchy.isChildOf(t,r)}getParent(t){return this._hierarchy.getParent(t)}getRootIds(){return this._hierarchy.getRootIds()}getClosestWorkTime(t){return this._calendar.getClosestWorkTime(t)}calculateEndDate(t){return this._calendar.calculateEndDate(t)}calculateDuration(t){return this._calendar.calculateDuration(t)}clearCalendarCache(){this._calendar.clearCache()}get calendarReader(){return this._calendar.reader}batchUpdate(t){t()}updateActivity(t){}getLiveActivity(t){return this.getActivity(t)}getFlags(){return{...this._flags,allCheckedTaskIds:this._viewState.checkedIds()}}getProjectEnd(){return null}beginWriteCapture(){this._writeCapture.begin(),this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=null}peekWriteCapture(){return this._writeCapture.peek()}endWriteCapture(){this._writeCapture.end(),this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=null}setActivityField(t,r,i){let n=this.getActivity(t);n&&(this._writeCapture.note(String(t),n),n[r]=i,ja(n,r),r===b.PARENT&&this._hierarchy.markDirty(),Ha(r)&&(this._cache.visualOrderIds=null))}setActivityFieldDynamic(t,r,i){let n=this.getActivity(t);if(n){if(!Object.hasOwn(n,r))throw new Error(`setActivityFieldDynamic: unknown CoreActivity field "${r}"`);this._writeCapture.note(String(t),n),Reflect.set(n,r,Fl(r,i)),ja(n,r),r===b.PARENT&&this._hierarchy.markDirty(),Ha(r)&&(this._cache.visualOrderIds=null)}}setActivityFields(t,r){let i=this.getActivity(t);if(!i)return;this._writeCapture.note(String(t),i);let n=!1;for(let a of Object.keys(r))Reflect.set(i,a,Reflect.get(r,a)),ja(i,a),a===b.PARENT&&(n=!0),Ha(a)&&(this._cache.visualOrderIds=null);n&&this._hierarchy.markDirty()}addLink(t){this._writeCapture.noteLinkAdd(String(t.id));let r=this._links.get(String(t.id));r&&this._deindexLink(r);let i={...t,freeSlackHours:t.freeSlackHours??null,isCritical:t.isCritical===!0};this._links.set(String(t.id),i),this._indexLink(i)}_indexLink(t){ad(this._outgoing,String(t.source),t.id),ad(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),nd(r,t.id));let i=this._incoming.get(String(t.target));i&&this._incoming.set(String(t.target),nd(i,t.id))}setLinkField(t,r,i){let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),n[r]=i)}setLinkFieldDynamic(t,r,i){if(!Rg(r))return;let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),Reflect.set(n,r,i))}setLinkProplannerId(t,r){let i=this.getLink(t);i&&(this._writeCapture.noteLinkField(String(t),i),i.proplannerId=r)}removeLink(t){let r=this.getLink(t);r&&(this._writeCapture.noteLinkRemove(String(t),r),this._links.delete(String(t)),this._deindexLink(r))}addActivity(t){this._writeCapture.noteInsert(String(t.id)),this._activities.set(t.id,t),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.addChild(t.parentId,t.id)}removeActivity(t){let r=this.getActivity(t);r&&this._writeCapture.noteRemove(String(t),r);let i=String(t);this.setProgressFallback(i,null),(this._viewState.isChecked(i)||!this._viewState.isVisible(i))&&this._captureViewStateOnce(),this._viewState.forget(i),this._activities.delete(t),this._lastStartDate.has(String(t))&&(this._captureLastStartDateOnce(),this._lastStartDate.delete(String(t))),this._outgoing.delete(String(t)),this._incoming.delete(String(t)),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}noteCorrelativeBefore(t,r){this._writeCapture.noteCorrelativeBefore(t,r)}noteScheduledBefore(t,r){this._writeCapture.noteScheduledBefore(t,r)}restoreFromCapture(){let t=this._writeCapture.peek();if(!t)return;let{ops:r,before:i,correlativeBefore:n,scheduledBefore:a,progressFallbackBefore:o}=t;this._undoLinkAdds(r),this._undoInserts(r),this._reInsertRemovedActivities(r),this._reAddRemovedLinks(r),this._restoreLinkFields(r),this._restoreCorrelatives(n),this._restoreActivityFields(a),this._restoreActivityFields(i),this._restoreProgressFallbacks(o),this._viewStateBefore!==null&&(this._viewState.restore(this._viewStateBefore),this._filterProjection=null,this.invalidateDerivedOrder()),this._promotionSnapshotBefore!==null&&(this._promotionSnapshot=this._promotionSnapshotBefore),this._lastStartDateBefore!==null&&(this._lastStartDate=this._lastStartDateBefore),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}_restoreProgressFallbacks(t){for(let[r,i]of t)i===null?this._progressFallback.delete(r):this._progressFallback.set(r,i)}_restoreCorrelatives(t){for(let[r,i]of t){let n=this._activities.get(r);n&&(n.correlativeId=i)}}_undoLinkAdds(t){for(let r of t)r.kind==="link-add"&&this._detachLink(r.linkId)}_undoInserts(t){for(let r of t)r.kind==="insert"&&this._activities.delete(r.activityId)}_reInsertRemovedActivities(t){for(let r of t)r.kind==="remove"&&this._activities.set(r.activityId,r.before)}_reAddRemovedLinks(t){for(let r of t)r.kind==="link-remove"&&this._attachLink(r.before)}_restoreLinkFields(t){for(let r of t)r.kind==="link-field"&&this._links.has(r.linkId)&&this._links.set(r.linkId,r.before)}_restoreActivityFields(t){for(let[r,i]of t){let n=this._activities.get(r);n&&this._restoreScalarFields(n,i)}}_restoreScalarFields(t,r){for(let i of Object.keys(t))Object.hasOwn(r,i)||Reflect.deleteProperty(t,i);for(let i of Object.keys(r))Reflect.set(t,i,Reflect.get(r,i))}_attachLink(t){this._links.set(String(t.id),{...t}),this._indexLink(t)}_detachLink(t){let r=this.getLink(t);r&&(this._links.delete(String(t)),this._deindexLink(r))}},id=[];function Rg(e){return e===Cr.LAG||e===Cr.TYPE||e===Cr.FREE_SLACK_HOURS||e===Cr.IS_CRITICAL}function Ha(e){return e===b.PARENT||e===b.CORRELATIVE_ID}function ja(e,t){t!==b.START_DATE&&t!==b.END_DATE&&t!==b.TYPE||(e.calendarDuration=Wt(e))}function nd(e,t){return e.filter(r=>String(r)!==String(t))}function ad(e,t,r){let i=e.get(t);i?i.push(r):e.set(t,[r])}function Pg(e){let t=e.runtimeFlags??{};return{isPasting:!!t.isPasting,isBulkOperation:!!t.isBulkOperation,dragWithMultiple:!!t.dragWithMultiple,draggingSingleMilestone:!!t.draggingSingleMilestone,creatingActivity:!1,avoidAutoScheduleBeforeDrag:!1,maxPerformance:!!t.maxPerformance,allCheckedTaskIds:[]}}function od(e,t){let r=e.getActivity(t);return r?O(r):null}function sd(e){return e.getAllActivities().map(O)}function cd(e){return e.getAllIds().map(String)}function ld(e,t){e.forEachActivity((r,i)=>t(i))}function dd(e,t){let r=t==="0"?Va(e,"0"):e.getChildren(t),i=[];for(let n of r){let a=e.getActivity(n);a&&i.push(O(a))}return i.sort((n,a)=>(n.correlativeId??0)-(a.correlativeId??0)),i}function Va(e,t){return Rt(t,e)}function ud(e){return e.checkedIds().map(String)}function fd(e,t){if(t==="0"){let r=!1;return e.forEachActivity(i=>{r||=N(i.parentId)}),r}return e.getChildren(t).length>0}function Ka(e,t){let r=e.getLink(t);return r?St(r):null}function pd(e){return e.getAllLinks().map(t=>St(t))}function Ji(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function Lg(e){return e.reduce((t,r)=>Ji(r)<Ji(t)?r:t)}function Og(e){return e.reduce((t,r)=>Ji(r)>Ji(t)?r:t)}function bg(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function yd(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=bg(t);if(r.length===0)return null;let i=r.map(a=>a.split("-")[0]),n=r.map(a=>a.split("-")[1]);return{startHour:Lg(i),endHour:Og(n)}}function hd(e,t){return{calendars:e.calendarReader,hierarchy:td(e),activityReader:Ql(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay}}function md(e){return Te(e)}var Ng=new Set(["freeSlackHours","isCritical"]);function wg(e,t){let r=Object.fromEntries(Object.entries(e.fields??{}).filter(([i])=>!t.has(i)));return e.kind==="updated"&&Object.keys(r).length===0?null:{...e,...e.fields===void 0?{}:{fields:r},after:null}}function vd(e){let t=e.activities.map(n=>({...n,after:null})),r=e.links.map(n=>wg(n,Ng)).filter(n=>n!==null),i=e.source.kind==="activity-batch"?{...e.source,items:[],links:[]}:e.source;return O({...e,source:i,activities:t,links:r})}function Ya(e,t,r,i,n,a,o){return{changeSet:e,beforeSnap:t,beforeLinks:gd(r),afterSnap:i,afterLinks:gd(n),progressFallbackBefore:a,progressFallbackAfter:o}}function gd(e){if(e)return new Map(Array.from(e,([t,r])=>[t,{...r,freeSlackHours:null,isCritical:!1}]))}function Cd(e,t){let r=new Map,i=new Map;for(let n of t.activities){if(n.kind!=="created")continue;let a=e.getActivity(String(n.id));a&&r.set(String(n.id),et(a))}for(let n of t.links){if(n.kind==="deleted")continue;let a=e.getLink(String(n.id));a&&i.set(String(n.id),{...a})}return{afterSnap:r,afterLinks:i}}function Sd(e){return e.kind!==P.INLINE_EDIT||!_r.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function Ad(e){return e.changeSet.activities.length===1&&e.changeSet.activities[0]?.kind==="updated"&&e.changeSet.links.length===0&&!e.beforeSnap?.size&&!e.afterSnap?.size}function kd(e,t){if(!Ad(e)||!Ad(t))return!1;let r=e.changeSet.activities[0],i=t.changeSet.activities[0];return!!r&&!!i&&String(r.id)===String(i.id)}function Td(e,t){let r=e.changeSet.activities[0],i=t.changeSet.activities[0];if(!r||!i)return t;let n=r.fields??{},a=i.fields??{},o={};for(let c of new Set([...Object.keys(n),...Object.keys(a)])){let l=n[c],d=a[c];o[c]={before:l?l.before:d?.before,after:d?d.after:l?.after}}let s={...t.changeSet,activities:[{...i,fields:o}]};return Ya(s)}function Dd(e){return e.kind===P.PERSISTENCE_ACKNOWLEDGE?"checkpoint-on-success":e.kind===P.SIR_SYNC||e.kind===P.CALENDAR_RECONCILE||e.kind===P.ACTIVITY_LOOKAHEAD_SYNC||e.kind===P.BASELINE_APPLY||e.kind===P.PONDERATOR_CRITERION_SET||e.kind===P.STATUS_CRITERIA_SET||e.kind===P.ACTIVITY_CLIPBOARD_CLEAR||e.kind===P.ACTIVITY_COPY||e.kind===P.SELECTION_TOGGLE||e.kind===P.SELECTION_REPLACE||e.kind===P.VISIBILITY_SET||e.kind===P.FILTER_SET||e.kind===P.SORT_SET?"skip":"record"}function Ga(e){for(let t of e.changeSet.activities)if(t.kind==="created"||t.kind==="deleted"||t.kind==="updated"&&t.fields&&S.CUSTOM_ID in t.fields)return!0;return!1}function $a(e,t,r){let i=[],n=[];for(let o of t.changeSet.activities){let s=String(o.id);if(o.kind==="updated"){let c=e.getActivity(s);i.push({id:s,kind:"updated",fields:Id(o.fields,r),after:c?et(c):null})}else if(o.kind==="deleted")if(r==="before"){let c=e.getActivity(s);i.push({id:s,kind:"created",after:c?et(c):null})}else i.push({id:s,kind:"deleted",after:null});else if(r==="before")i.push({id:s,kind:"deleted",after:null});else{let c=e.getActivity(s);i.push({id:s,kind:"created",after:c?et(c):null})}}for(let o of t.changeSet.links){let s=String(o.id);if(o.kind==="updated"){let c=e.getLink(s);n.push({id:s,kind:"updated",fields:Id(o.fields,r),after:c?St(c):null})}else if(o.kind==="deleted")if(r==="before"){let c=e.getLink(s);n.push({id:s,kind:"created",after:c?St(c):null})}else n.push({id:s,kind:"deleted",after:null});else if(r==="before")n.push({id:s,kind:"deleted",after:null});else{let c=e.getLink(s);n.push({id:s,kind:"created",after:c?St(c):null})}}let a=(t.changeSet.viewState??[]).map(o=>r==="before"?Fg(o):o);return{source:{kind:r==="before"?Gt.UNDO:Gt.REDO},activities:i,links:n,calendars:[],trackingEvents:[],effects:[],viewState:a}}function Id(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([r,i])=>[r,t==="before"?{before:O(i.after),after:O(i.before)}:{before:O(i.before),after:O(i.after)}]))}function Fg(e){return{activityId:e.activityId,...e.checked?{checked:{before:e.checked.after,after:e.checked.before}}:{},...e.visible?{visible:{before:e.visible.after,after:e.visible.before}}:{}}}function za(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function _d(e,t){Rd(e,t,"before")}function Ed(e,t){Rd(e,t,"after")}function Rd(e,t,r){let i=t.changeSet;for(let a of i.activities)if(a.kind==="updated"){if(!a.fields)continue;for(let[o,s]of Object.entries(a.fields))st(e,a.id,o,r==="before"?s.before:s.after)}else if(a.kind==="deleted")if(r==="before"){let o=t.beforeSnap?.get(String(a.id));if(!o)throw new Error(`undo: missing beforeSnap for resurrecting activity ${a.id}`);e.addActivity(et(o))}else e.removeActivity(String(a.id));else if(r==="before")e.removeActivity(String(a.id));else{let o=t.afterSnap?.get(String(a.id));if(!o)throw new Error(`redo: missing afterSnap for re-creating activity ${a.id}`);e.addActivity(et(o))}for(let a of i.links)if(a.kind==="updated"){if(!a.fields)continue;if(Object.hasOwn(a.fields,"source")||Object.hasOwn(a.fields,"target")){let o=r==="before"?t.beforeLinks?.get(String(a.id)):t.afterLinks?.get(String(a.id));if(!o)throw new Error(`${r==="before"?"undo":"redo"}: missing link snapshot for ${a.id}`);e.removeLink(String(a.id)),e.addLink({...o});continue}for(let[o,s]of Object.entries(a.fields))Vs(e,String(a.id),o,r==="before"?s.before:s.after)}else if(a.kind==="deleted")if(r==="before"){let o=t.beforeLinks?.get(String(a.id));if(!o)throw new Error(`undo: missing beforeLinks for re-adding link ${a.id}`);e.addLink(o)}else e.removeLink(String(a.id));else if(r==="before")e.removeLink(String(a.id));else{let o=t.afterLinks?.get(String(a.id));if(!o)throw new Error(`redo: missing afterLinks for re-creating link ${a.id}`);e.addLink(o)}for(let a of i.viewState??[])a.checked&&e.setChecked(a.activityId,r==="before"?a.checked.before:a.checked.after),a.visible&&e.setVisible(a.activityId,r==="before"?a.visible.before:a.visible.after);let n=r==="before"?t.progressFallbackBefore:t.progressFallbackAfter;for(let[a,o]of n??[])e.setProgressFallback(a,o)}var xg=100,Mg=600,Xi=class e{constructor(t=xg){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];sequence=0;_lastKey=null;_lastTime=0;fork(){let t=new e(this.maxDepth);return t.undoStack.push(...O(this.undoStack)),t.redoStack.push(...O(this.redoStack)),t.sequence=this.sequence,t._lastKey=this._lastKey,t._lastTime=this._lastTime,t}record(t,r=null,i=0){let n=this.undoStack[this.undoStack.length-1];r!=null&&r===this._lastKey&&i-this._lastTime<=Mg&&n!==void 0&&kd(n.entry,t)?(n.entry=Td(n.entry,t),n.touchedAt=this.touch()):(this.undoStack.push({entry:t,touchedAt:this.touch()}),this.undoStack.length>this.maxDepth&&this.undoStack.splice(0,this.undoStack.length-this.maxDepth)),this._lastKey=r,this._lastTime=i,this.redoStack.length=0}resetCoalesce(){this._lastKey=null}takeUndo(){return this.undoStack.pop()?.entry??null}takeRedo(){return this.redoStack.pop()?.entry??null}pushRedo(t){this.redoStack.push({entry:t,touchedAt:this.touch()})}pushUndo(t){this.undoStack.push({entry:t,touchedAt:this.touch()})}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undoDepth(){return this.undoStack.length}capturePersistenceBoundary(){return this.resetCoalesce(),this.sequence}discardThrough(t){this.removeEntriesThrough(this.undoStack,t),this.removeEntriesThrough(this.redoStack,t),this.resetCoalesce()}applyPersistedIdentities(t,r){let i=new Map(t.map(({id:a,proplannerId:o})=>[String(a),o])),n=new Map(r.map(({id:a,proplannerId:o})=>[String(a),o]));for(let a of[...this.undoStack,...this.redoStack])a.entry=this.withPersistedIdentities(a.entry,i,n)}clear(){this.undoStack.length=0,this.redoStack.length=0,this.resetCoalesce()}touch(){return this.sequence+=1,this.sequence}removeEntriesThrough(t,r){let i=t.filter(({touchedAt:n})=>n>r);t.splice(0,t.length,...i)}withPersistedIdentities(t,r,i){let n=o=>o===void 0?void 0:new Map(Array.from(o,([s,c])=>[s,r.has(s)?{...c,proplannerId:r.get(s)}:c])),a=o=>o===void 0?void 0:new Map(Array.from(o,([s,c])=>[s,i.has(s)?{...c,proplannerId:i.get(s)}:c]));return{...t,beforeSnap:n(t.beforeSnap),afterSnap:n(t.afterSnap),beforeLinks:a(t.beforeLinks),afterLinks:a(t.afterLinks)}}};var Ug=["parentId","correlativeId"];function Ld(e,t){let r=new Set,i=n=>{let a=t(n);r.add(a===null?"0":String(a))};for(let n of e.activities){let a=String(n.id);if(n.kind==="created"){i(a);continue}if(n.kind==="deleted"){let c=n.fields;c&&"parentId"in c&&r.add(Pd(c.parentId?.before));continue}let o=n.fields;!o||!Ug.some(c=>c in o)||(i(a),"parentId"in o&&r.add(Pd(o.parentId?.before)))}return r}function Pd(e){return e==null?"0":String(e)}function Bg(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function Wg(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function Od(e){return{id:String(e.id),worktime:Wg(e.worktime)}}function Qi(e,t,r,i=[]){let n=t.map(Bg),a=[...r.map(Od),...i.map(Od)];return{activities:[...e],links:n,calendars:a}}var bd={id:"ignored",proplannerId:"ignored",parentId:"tracked",name:"tracked",description:"tracked",type:"tracked",startDate:"tracked",endDate:"tracked",durationHours:"tracked",constraintType:"tracked",constraintDate:"tracked",autoScheduling:"tracked",calendarId:"tracked",assignedDefaultCalendar:"ignored",dateOrigin:"tracked",progress:"tracked",cost:"tracked",usedCost:"tracked",realCost:"tracked",workHours:"tracked",realWorkHours:"tracked",ponderator:"tracked",hasCustomPonderator:"tracked",correlativeId:"tracked",uniqueCorrelativeId:"tracked",customId:"tracked",subcontractId:"tracked",isLookahead:"tracked",hasLookaheadTasks:"ignored",newActivityIds:"tracked",hasNewActivities:"tracked",isNewActivity:"ignored",pendingRequestIds:"ignored",responsableIds:"tracked",tagIds:"tracked",baselinePoints:"ignored",baselineSnapshot:"ignored",recursiveDurationHours:"ignored",isCritical:"ignored",freeSlackHours:"ignored",calendarDuration:"ignored",expectedProgress:"ignored",expectedProgressBaseline:"ignored",status:"ignored",criticalPath:"ignored"},Nd=Object.keys(bd).filter(e=>bd[e]==="tracked"),wd=new Set(["startDate","endDate","constraintDate","dateOrigin"]),Fd=new Set(["newActivityIds","responsableIds","tagIds"]);function xd(e){let t=Nd.map(r=>[r,Hg(r,e[r])]);return Object.fromEntries(t)}function Hg(e,t){return wd.has(e)?t instanceof Date?new Date(t):null:Fd.has(e)?Array.isArray(t)?[...t]:[]:t}function Or(e,t){return qa(e,t).length>0}function qa(e,t){return Nd.filter(r=>!jg(r,e[r],t[r]))}function jg(e,t,r){return wd.has(e)?Vg(t,r):Fd.has(e)?Kg(t,r):(t??null)===(r??null)}function Vg(e,t){let r=e instanceof Date?e.getTime():null,i=t instanceof Date?t.getTime():null;return r===i}function Kg(e,t){let r=new Set(Array.isArray(e)?e.map(String):[]),i=new Set(Array.isArray(t)?t.map(String):[]);if(r.size!==i.size)return!1;for(let n of r)if(!i.has(n))return!1;return!0}var Md={id:"ignored",source:"tracked",target:"tracked",type:"tracked",lag:"tracked",freeSlackHours:"ignored",isCritical:"ignored",ganttId:"ignored",sectorId:"ignored",proplannerId:"ignored"},Yg=Object.keys(Md).filter(e=>Md[e]==="tracked");function Zi(e,t){return Yg.some(r=>e[r]!==t[r])}function Ud(e,t){let r=new Map(e.map(i=>[String(i.id),i]));return t.filter(i=>{let n=r.get(String(i.id));return n?Zi(n,i):!1})}function Ut(e){if(e==null||e===0)return!1;if(!(typeof e=="number"&&Number.isSafeInteger(e)&&e>0))throw new Error(`invalid proplannerId ${String(e)}`);return!0}function Bd(e,t){for(let r of e)Ut(r.proplannerId);for(let r of t)Ut(r.proplannerId)}var tn=class e{trackingEnabled;initialized=!1;dirtyActivityIds=new Set;dirtyLinkIds=new Set;initialCalendarRepairIds=new Set;linksAtLastSave=new Map;activitiesAtLastSave=new Map;constructor(t=!0){this.trackingEnabled=t}fork(){let t=new e(!1);t.initialized=this.initialized;for(let[r,i]of this.linksAtLastSave)t.linksAtLastSave.set(r,O(i));for(let[r,i]of this.activitiesAtLastSave)t.activitiesAtLastSave.set(r,O(i));return t}init(t,r){if(this.trackingEnabled){Bd(t,r),this.snapshotActivities(t),this.snapshotLinks(r);for(let i of t)if(i.assignedDefaultCalendar){let n=String(i.id);this.initialCalendarRepairIds.add(n),this.dirtyActivityIds.add(n)}this.initialized=!0}}acknowledge(t,r,i=[],n=[],a,o){if(!this.trackingEnabled)return;let s=new Map(i.map(({id:p,proplannerId:y})=>[String(p),y])),c=new Map(n.map(({id:p,proplannerId:y})=>[String(p),y])),l=t.map(p=>({...p,proplannerId:s.get(String(p.id))??p.proplannerId})),d=r.map(p=>{let y=c.get(String(p.id));return y===void 0?{...p}:{...p,proplannerId:y}});if(Bd(l,d),this.snapshotActivities(l),this.snapshotLinks(d),!a||!o)return;let u=new Map(a.map(p=>[String(p.id),p])),f=new Map(o.map(p=>[String(p.id),p]));for(let p of l){let y=String(p.id);this.activityIsDirty(y,u.get(y)??null)&&this.dirtyActivityIds.add(y)}for(let p of a){let y=String(p.id);this.activityIsDirty(y,p)&&this.dirtyActivityIds.add(y)}for(let p of d){let y=String(p.id);this.linkIsDirty(y,f.get(y)??null)&&this.dirtyLinkIds.add(y)}for(let p of o){let y=String(p.id);this.linkIsDirty(y,p)&&this.dirtyLinkIds.add(y)}}snapshotActivities(t){if(this.trackingEnabled){this.activitiesAtLastSave.clear(),this.dirtyActivityIds.clear(),this.initialCalendarRepairIds.clear();for(let r of t){let i=String(r.id);if(!Ut(r.proplannerId)){this.dirtyActivityIds.add(i);continue}let n=xd(r);this.activitiesAtLastSave.set(String(r.id),{persistable:n,deletedSnapshot:{id:r.id,proplannerId:r.proplannerId,parentId:r.parentId,hadBaseline:r.baselineSnapshot!==null||r.baselinePoints.length>0}}),Or(r,n)&&this.dirtyActivityIds.add(i)}}}snapshotLinks(t){if(this.trackingEnabled){this.linksAtLastSave.clear(),this.dirtyLinkIds.clear();for(let r of t){let i=String(r.id);if(!Ut(r.proplannerId)){this.dirtyLinkIds.add(i);continue}this.linksAtLastSave.set(String(r.id),{id:r.id,proplannerId:r.proplannerId,source:r.source,target:r.target,lag:r.lag,type:r.type})}}}recordChanges(t,r,i,n){if(!(!this.trackingEnabled||!this.initialized)){for(let a of t){let o=String(a.id),s=i(o);this.activityIsDirty(o,s)?this.dirtyActivityIds.add(o):this.dirtyActivityIds.delete(o)}for(let a of r){let o=String(a.id),s=n(o);this.linkIsDirty(o,s)?this.dirtyLinkIds.add(o):this.dirtyLinkIds.delete(o)}}}activityIsDirty(t,r){let i=this.activitiesAtLastSave.get(t);return r===null?i!==void 0:this.initialCalendarRepairIds.has(t)||!Ut(r.proplannerId)||i===void 0||Or(r,i.persistable)}linkIsDirty(t,r){let i=this.linksAtLastSave.get(t);return r===null?i!==void 0:!Ut(r.proplannerId)||i===void 0||Zi(i,r)}acknowledgePersistedLookahead(t,r){if(!this.trackingEnabled||!this.initialized)return;let i=t.map(n=>{let a=typeof n=="string"?n:String(n.id),o=r(a),s=this.activitiesAtLastSave.get(a);if(o===null||s===void 0)throw new Error(`unknown persisted activity "${a}"`);return{activityId:a,acknowledgesLookahead:typeof n=="string"||!!n.fields?.isLookahead,acknowledgesProgress:typeof n!="string"&&!!n.fields?.progress,current:o,saved:s}});for(let{activityId:n,acknowledgesLookahead:a,acknowledgesProgress:o,current:s,saved:c}of i){let l={...c.persistable,...a?{isLookahead:s.isLookahead}:{},...o?{progress:s.progress,autoScheduling:s.autoScheduling}:{}};this.activitiesAtLastSave.set(n,{...c,persistable:l}),this.initialCalendarRepairIds.has(n)||!Ut(s.proplannerId)||Or(s,l)?this.dirtyActivityIds.add(n):this.dirtyActivityIds.delete(n)}}hasCheckpointActivityId(t){return this.activitiesAtLastSave.has(t)}hasCheckpointLinkId(t){return this.linksAtLastSave.has(t)}hasUnsavedChanges(){return this.trackingEnabled&&this.initialized&&(this.dirtyActivityIds.size>0||this.dirtyLinkIds.size>0)}newActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let i of this.dirtyActivityIds){let n=t(i);n!==null&&!Ut(n.proplannerId)&&r.push(n)}return r}newLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let i of this.dirtyLinkIds){let n=t(i);n!==null&&!Ut(n.proplannerId)&&r.push(n)}return r}deletedActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let i of this.dirtyActivityIds){let n=this.activitiesAtLastSave.get(i);n&&t(i)===null&&r.push({...n.deletedSnapshot})}return r}deletedLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let i of this.dirtyLinkIds){let n=this.linksAtLastSave.get(i);n&&t(i)===null&&r.push({...n})}return r}modifiedActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let i of this.dirtyActivityIds){let n=t(i);if(n===null||!Ut(n.proplannerId))continue;let a=this.activitiesAtLastSave.get(i);(a===void 0||this.initialCalendarRepairIds.has(i)||Or(n,a.persistable))&&r.push(n)}return r}modifiedActivityFields(t){let r=new Map;if(!this.trackingEnabled||!this.initialized)return r;for(let i of this.dirtyActivityIds){let n=t(i),a=this.activitiesAtLastSave.get(i);if(!n||!a)continue;let o=qa(n,a.persistable);o.length>0&&r.set(i,o)}return r}modifiedLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let i of this.dirtyLinkIds){let n=t(i);if(n===null||!Ut(n.proplannerId))continue;let a=this.linksAtLastSave.get(i);(a===void 0||Zi(a,n))&&r.push(n)}return r}clear(){this.initialized=!1,this.dirtyActivityIds.clear(),this.dirtyLinkIds.clear(),this.initialCalendarRepairIds.clear(),this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear()}};var Wd=1440*60*1e3,Hd=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/,en=7,Ja=[!1,!0,!0,!0,!0,!0,!1],jd=new Set(["1","true"]),Xa=dt.DURATION,Vd="asap",Kd={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo","AS SOON AS POSSIBLE":"asap","AS LATE AS POSSIBLE":"alap","START NO EARLIER THAN":"snet","START NO LATER THAN":"snlt","FINISH NO EARLIER THAN":"fnet","FINISH NO LATER THAN":"fnlt","MUST START ON":"mso","MUST FINISH ON":"mfo"};function Yd(e,t){let r=[],i=e.map(a=>{let o=eA(a,t);return a.should_be_showed===!1&&r.push(o.id),o});iA(i);let n=new Set(i.map(a=>a.id));return nA(i,n,t.reporter),{activities:i,activityIds:n,hiddenIds:r}}function Gg(e,t){if(!e)return null;let r=Kd[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),Vd):r}function $g(e,t){let r=Gg(e.constraint,t),n=r!=="asap"&&r!=="alap"&&e.constraint_date?zt(e.constraint_date):null;return{constraintType:r,constraintDate:n}}function zg(e,t,r){if(e==null)return r;let i=String(e);return t.has(i)?i:r}function qg(e){if(e==null||e==="")return[];if(Array.isArray(e))return e.map(String);if(typeof e!="string")return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.map(String):[]}catch{return[]}}function Jg(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function Qa(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)Jg(r)&&t.push(String(r.id));return t}function Xg(e){return e==="0"?null:String(e)}function Qg(e){if(e==null)return null;if(!(typeof e=="number"&&(e===0||Number.isSafeInteger(e)&&e>0)))throw new Error(`invalid activity proplannerId ${String(e)}`);return e}function Zg(e,t){return typeof e.is_critical=="boolean"?e.is_critical:(t.error("[parseFromBackend] invalid activity is_critical \u2014 defaulting to false",new TypeError(`activity "${e.unique_id}" received ${typeof e.is_critical}`)),!1)}function tA(e,t){return Array.isArray(e)?e.map(r=>Hi(r,t)).filter(r=>r!==null):[]}function eA(e,t){let r=zg(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),i=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),n=Number(e.progress),{constraintType:a,constraintDate:o}=$g(e,t.reporter),s=e.type==="milestone",c=zt(e.start_date),l=s?c:zt(e.end_date),d=s?0:Number(e.duration),u=Zg(e,t.reporter);return{id:String(e.unique_id),proplannerId:Qg(e.id),parentId:Xg(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:ge(d,t.hoursPerDay),constraintType:a,constraintDate:o,autoScheduling:he(n),calendarId:r,assignedDefaultCalendar:r!=null&&i,dateOrigin:e.date_origin==null?null:zt(e.date_origin),progress:n,cost:Number(e.cost),usedCost:Number(e.used_cost??0),realCost:Number(e.real_cost??0),workHours:Number(e.hhWorkTime),realWorkHours:Number(e.real_work??0),ponderator:Number(e.ponderator??0),hasCustomPonderator:e.hasCustomPonderator,correlativeId:e.correlative_id,uniqueCorrelativeId:e.unique_correlative_id,customId:rA(e),subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:qg(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:Qa(e.pendingRequests),responsableIds:Qa(e.responsables),tagIds:Qa(e.tags),baselinePoints:tA(e.baseline_points,t.reporter),baselineSnapshot:null,recursiveDurationHours:ge(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),calendarDuration:Wt({type:e.type,startDate:c,endDate:l}),isCritical:u,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function rA(e){return e.has_childs?null:e.custom_id}function iA(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function nA(e,t,r){for(let i of e)i.parentId!==null&&(t.has(i.parentId)||(r.warn(`[parseFromBackend] activity "${i.id}" references unknown parent "${i.parentId}" \u2014 re-parenting to root (null)`),i.parentId=null))}function qd(e,t,r,i=null){let o=(e!==void 0&&e.length>0?e:t??[]).map(c=>oA(c,i)),s=(r??[]).map(c=>sA(c,i));return{calendars:o,baseCalendars:s,knownCalendarIds:new Set(o.map(c=>c.id)),defaultCalendarId:aA(o)}}function aA(e){let t=e.find(i=>i.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function Jd(e,t){let r=pA(e.working_days),{days:i,hours:n}=fA(e,r),a=cA(t.exceptionsSource,t.exceptionRange),o={days:i,hours:n};return a&&(o.dates=a),{id:`${String(e.id)}${t.idSuffix}`,name:e.name,is_default:t.isDefault,...t.baseDefault!==void 0?{baseDefault:t.baseDefault}:{},worktime:o}}function oA(e,t){let r=e.baseDefault,i=typeof r=="boolean"?r:void 0;return Jd(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:i,exceptionsSource:e.exceptiondays,exceptionRange:t})}function sA(e,t){return Jd(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function cA(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let i of e){if(!i)continue;let n=lA(i.from_date,i.to_date,t);if(n.length===0)continue;let a=dA(i);if(a!==void 0)for(let o of n)r[o]=a}return Object.keys(r).length>0?r:null}function lA(e,t,r){let i=Gd(e),n=Gd(t);if(i===null||n===null)return[];if(r&&(n<r.start||i>r.end))return[];let a=[],o=r?Math.max(i,r.start):i,s=r?Math.min(n,r.end):n;for(;o<=s;)a.push(String(o)),o+=Wd;return a}function Gd(e){if(typeof e!="string")return null;let t=Hd.exec(e.trim());if(!t)return null;let r=Number(t[1]),i=Number(t[2]),n=Number(t[3]);return Number.isFinite(r)&&Number.isFinite(i)&&Number.isFinite(n)?Date.UTC(r,i-1,n):null}function dA(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=uA(t);if(r.length>0)return r}}var $d=/^\d{1,2}:\d{2}$/;function uA(e){let t=[];for(let r of e){let i=Zd(r?.shift_string);if(!i)continue;if(!i.startsCsv.includes(",")&&!i.endsCsv.includes(",")){let s=i.startsCsv.trim(),c=i.endsCsv.trim();!rn(s)&&!rn(c)&&$d.test(s)&&$d.test(c)&&t.push(`${s}-${c}`);continue}let o=Qd(i.startsCsv,i.endsCsv).find(s=>s!==null);o&&t.push(o)}return t.sort(Xd),t}function zd(e){let t=e.indexOf("-"),r=t>0?e.slice(0,t):e,[i,n]=r.split(":");return(Number(i)||0)*60+(Number(n)||0)}function Xd(e,t){return zd(e)-zd(t)}function fA(e,t){let r=Array.from({length:7},()=>[]),i=(l,d)=>{let u=Qd(l,d);for(let f=0;f<7;f+=1){let p=u[f],y=r[f];p&&y&&y.push(p)}},n=Array.isArray(e.shifts)&&e.shifts.length>0,a=typeof e.shift_start=="string"&&typeof e.shift_end=="string";if(n)for(let l of e.shifts){let d=Zd(l?.shift_string);d&&i(d.startsCsv,d.endsCsv)}else a&&i(e.shift_start,e.shift_end);for(let l of r)l.sort(Xd);let s=r.find((l,d)=>!!t[d]&&l.length>0)??[];return{days:t.map((l,d)=>{if(!l)return!1;let u=r[d];return u&&u.length>0?u:s}),hours:s}}function Qd(e,t){let r=Array.from({length:en},()=>null);if(typeof e!="string"||typeof t!="string")return r;let i=e.split(",").map(s=>s.trim()),n=t.split(",").map(s=>s.trim());if(!(i.length===n.length&&i.length>0&&i.length<=en))return r;let o=[...r];for(let s=0;s<i.length;s+=1){let c=i[s],l=n[s];rn(c)||rn(l)||(o[s]=`${c}-${l}`)}return o}function Zd(e){if(typeof e!="string")return null;let t=e.indexOf("-");return t<=0?null:{startsCsv:e.slice(0,t),endsCsv:e.slice(t+1)}}function pA(e){if(typeof e!="string")return[...Ja];let t=e.split(",").map(r=>r.trim());return t.length!==en?[...Ja]:t.map(r=>jd.has(r))}var yA=new Set(["false","null"]);function rn(e){return!e||yA.has(e)}function hA(e){return e==="0"||e==="1"||e==="2"||e==="3"}function mA(e){if(typeof e!="string")return null;let t=is(e);return t||(hA(e)?e:null)}function gA(e){if(e==null)return;if(!(typeof e=="number"&&(e===0||Number.isSafeInteger(e)&&e>0)))throw new Error(`invalid link proplannerId ${String(e)}`);return e}function eu(e,t){let r=[];for(let i of e)try{r.push(AA(i,t.knownActivityIds,t.hoursPerDay))}catch(n){t.reporter.warn("[parseFromBackend] dropping invalid link",n)}return IA(r)}function AA(e,t,r){let i=String(e.unique_id??e.id),n=String(e.source_id??e.source??""),a=String(e.target_id??e.target??"");if(!t.has(n))throw new Error(`[parseFromBackend] link "${i}" source "${n}" does not exist`);if(!t.has(a))throw new Error(`[parseFromBackend] link "${i}" target "${a}" does not exist`);let o=mA(e.type);if(o===null)throw new Error(`[parseFromBackend] link "${i}" has invalid type "${String(e.type)}"`);let s=e.ganttId,c=e.sectorId,l=gA(e.id);return{id:i,source:n,target:a,type:o,lag:Pt(Number(e.lag??0),r),freeSlackHours:null,isCritical:!1,...typeof s=="number"?{ganttId:s}:{},...typeof c=="number"?{sectorId:c}:{},...l===void 0?{}:{proplannerId:l}}}function IA(e){let t=new Map;for(let r of e){let i=`${r.source}-${r.target}-${r.type}`,n=t.get(i);(!n||tu(r)>tu(n))&&t.set(i,r)}return[...t.values()]}function tu(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function vA(e){if(typeof e!="string")return Xa;switch(e.toUpperCase()){case dt.DURATION:return dt.DURATION;case dt.COST:return dt.COST;case dt.WORK_HOURS:return dt.WORK_HOURS;default:return Xa}}function CA(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function SA(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function ru(e){let t=CA(e),r=SA(e),i=e.update_duration_for_primavera_for_end_date===!0;return{id:String(e.id),name:e.name,hoursPerDay:e.hoursPerDay,hoursPerWeek:e.hoursPerWeek,dateFormat:e.dateFormat,projectId:e.projectId,companyId:e.companyId,...t!==void 0?{customIdPrefix:t}:{},...r!==void 0?{customIdIncrement:r}:{},...i?{updateDurationForPrimaveraEndDate:!0}:{},activityCreter:vA(e.activity_creter),statusCriteria:jn,ganttId:null}}function nn(e,t=Be){let r=ru(e.sector),{calendars:i,baseCalendars:n,knownCalendarIds:a,defaultCalendarId:o}=qd(e.calendars,e.sector.calendars,e.baseCalendars,kA(e.activities)),{activities:s,activityIds:c,hiddenIds:l}=Yd(e.activities,{knownCalendarIds:a,defaultCalendarId:o,hoursPerDay:r.hoursPerDay,reporter:t}),d=eu(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:s,links:d,calendars:i,baseCalendars:n,viewStateSeed:{hiddenIds:l}}}function kA(e){let t=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let a of e){let o=new Date(a.start_date).getTime(),s=new Date(a.end_date).getTime();Number.isFinite(o)&&(t=Math.min(t,o)),Number.isFinite(s)&&(r=Math.max(r,s))}if(!Number.isFinite(t)||!Number.isFinite(r))return null;let i=new Date(t),n=new Date(r);return i.setFullYear(i.getFullYear()-1),n.setFullYear(n.getFullYear()+1),{start:i.getTime(),end:n.getTime()}}function Za(e={}){let t=e.seed??0,r=i=>{i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}return{fork(){return Za({seed:t})},next(){return t+=1,String(t)},bump(i){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)},snapshot(){return t},restore(i){t=i}}}function to(e={}){let t=e.seed??0,r=i=>{i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}return{fork(){return to({seed:t})},next(){return t+=1,String(t)},bump(i){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)},snapshot(){return t},restore(i){t=i}}}function eo(e={}){let t=e.seed??0,r=i=>{Number.isFinite(i)&&i>0&&i<=9999999&&i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){if(i==null)continue;let n=typeof i=="number"?i:Number(i);r(n)}return{fork(){return eo({seed:t})},next(){return t+=1,String(t)},bump(i){if(i==null)return;let n=typeof i=="number"?i:Number(i);r(n)},snapshot(){return t},restore(i){t=i}}}function iu(e){return!!e&&typeof e=="string"&&e.trim().length>0}function an(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function on(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function nu(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function au(e,t){return!t&&iu(e)}function ou(e,t){return t&&iu(e)}function br(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function sn(e){if(!br(e))return 0n;try{return BigInt(e)}catch{return 0n}}function TA(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!br(t))return r;let i=t.length;return r.padStart(i,"0")}function bt(e,t){let r=sn(e),i=sn(t),n=r+i;return TA(n,e)}function cn(e,t){let r=sn(e),i=sn(t);return r<i?-1:r>i?1:0}function ln(e,t){return cn(e,t)<=0?e:t}function dn(e,t){return cn(e,t)>=0?e:t}function su(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>ln(t,r))}function cu(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>dn(t,r))}function lu(e){return{prefix:e,baseSuffix:null}}function du(e,t){let r=on(e);return{prefix:an(e),baseSuffix:bt(r,t)}}function uu(e){return{prefix:e,baseSuffix:null}}function fu(e,t){return au(e,t)?"parentConversion":ou(e,t)?"pasteReference":"noContext"}function pu(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var un=class e{prefixMap=new Map;processedIds=new Set;_journalPrefixBefore=null;_journalIds=null;beginCustomIdTransaction(){this._journalPrefixBefore=new Map,this._journalIds=[]}commitCustomIdTransaction(){this._journalPrefixBefore=null,this._journalIds=null}rollbackCustomIdTransaction(){let t=this._journalPrefixBefore,r=this._journalIds;if(!(t===null||r===null)){for(let[i,n]of t)n===null?this.prefixMap.delete(i):this.prefixMap.set(i,n);for(let i of[...r].reverse())i.hadId?this.processedIds.add(i.customId):this.processedIds.delete(i.customId);this._journalPrefixBefore=null,this._journalIds=null}}_noteCustomIdBefore(t){if(this._journalPrefixBefore===null||this._journalIds===null)return;let{prefix:r}=this.analyzeCustomId(t);if(!this._journalPrefixBefore.has(r)){let i=this.prefixMap.get(r);this._journalPrefixBefore.set(r,i?pu(i):null)}this._journalIds.push({customId:t,hadId:this.processedIds.has(t)})}_ensureFreshBounds(t){let r=this.prefixMap.get(t);if(!r?.boundsDirty)return;r.boundsDirty=!1;let i=Array.from(r.usedSuffixes);r.min=su(i),r.max=cu(i),r.quantity=i.length,this._recalculateNext(t)}defaultPrefix;suffixIncrement;constructor(t={}){this.defaultPrefix=t.defaultPrefix??"A",this.suffixIncrement=t.suffixIncrement??"10"}fork(){let t=new e({defaultPrefix:this.defaultPrefix,suffixIncrement:this.suffixIncrement});for(let[r,i]of this.prefixMap)t.prefixMap.set(r,pu(i));for(let r of this.processedIds)t.processedIds.add(r);return t}extractPrefix(t){return an(t)}extractSuffix(t){return on(t)}analyzeCustomId(t){return{prefix:this.extractPrefix(t),suffix:this.extractSuffix(t)}}_updatePrefixStats(t,r){if(this._ensureFreshBounds(t),!this.prefixMap.has(t)){this.prefixMap.set(t,{min:r,max:r,next:r,quantity:1,usedSuffixes:new Set([r])}),this._recalculateNext(t);return}let i=this.prefixMap.get(t);i.usedSuffixes.has(r)||(i.usedSuffixes.add(r),i.min=ln(r,i.min),i.max=dn(r,i.max),i.quantity+=1,this._recalculateNext(t))}_recalculateNext(t){let r=this.prefixMap.get(t);if(!r)return;let i=this.getNextAvailableSuffix(t);r.next=i??this.suffixIncrement}getPrefixStats(t){this._ensureFreshBounds(t);let r=this.prefixMap.get(t);return r?{min:r.min,max:r.max,next:r.next,quantity:r.quantity}:null}getNextSuffix(t){this._ensureFreshBounds(t);let r=this.prefixMap.get(t);return r?r.next:this.suffixIncrement}getAllPrefixes(){return Array.from(this.prefixMap.keys())}registerCustomId(t){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:i}=this.analyzeCustomId(t);if(!r&&!i)return{prefix:r,suffix:i};if(this._noteCustomIdBefore(t),this._ensureFreshBounds(r),this.prefixMap.has(r)){let n=this.prefixMap.get(r);n.usedSuffixes.has(i)||(n.usedSuffixes.add(i),n.min=ln(i,n.min),n.max=dn(i,n.max),n.quantity+=1,this._recalculateNext(r))}else this.prefixMap.set(r,{min:i,max:i,next:bt(i,this.suffixIncrement),quantity:1,usedSuffixes:new Set([i])});return this.processedIds.add(t),{prefix:r,suffix:i}}releaseCustomId(t=null){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:i}=this.analyzeCustomId(t);if(!this.prefixMap.has(r))return{prefix:r,suffix:i};this._noteCustomIdBefore(t);let n=this.prefixMap.get(r);return n.usedSuffixes.has(i)&&(n.usedSuffixes.delete(i),n.quantity-=1,n.usedSuffixes.size===0?this.prefixMap.delete(r):n.boundsDirty=!0),this.processedIds.delete(t),{prefix:r,suffix:i}}trackCustomIdChange(t,r){let i=this.releaseCustomId(t),n=this.registerCustomId(r);return{oldPrefix:i.prefix,oldSuffix:i.suffix,newPrefix:n.prefix,newSuffix:n.suffix}}_exceedsMaxLength(t){return t.length>20}_shouldSearchForGaps(t){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return!1;let r=this.prefixMap.get(t);return`${t}${bt(r.max,this.suffixIncrement)}`.length>20}_suffixForUnknownPrefix(t,r){let i=r&&br(r)?r:this.suffixIncrement;return`${t}${i}`.length>20?null:i}_findFirstAvailableGap(t){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return null;let r=this.prefixMap.get(t),i=this.suffixIncrement;for(;cn(i,r.max)<0;){if(`${t}${i}`.length>20)return null;if(!r.usedSuffixes.has(i))return i;i=bt(i,this.suffixIncrement)}return null}_generateDefaultCustomId(){let t=this.getNextAvailableSuffix(this.defaultPrefix);if(t===null){if(this._shouldSearchForGaps(this.defaultPrefix)){let r=this._findFirstAvailableGap(this.defaultPrefix);if(r!==null)return`${this.defaultPrefix}${r}`}return`${this.defaultPrefix}${this.suffixIncrement}`}return`${this.defaultPrefix}${t}`}getNextAvailableSuffix(t,r=null){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return this._suffixForUnknownPrefix(t,r);let i=this.prefixMap.get(t),n=this.suffixIncrement;if(!r||!br(r)){let s=bt(i.max,n);return`${t}${s}`.length>20?null:s}let a=r;for(let s=0;s<100;s++){if(`${t}${a}`.length>20)return null;if(!i.usedSuffixes.has(a))return a;a=bt(a,n)}let o=bt(i.max,n);return`${t}${o}`.length>20?null:o}generateNextCustomId(t){let r=this.getNextAvailableSuffix(t);if(r===null)return this._generateDefaultCustomId();if(this.prefixMap.has(t)){let n=this.prefixMap.get(t),a=0;for(;n.usedSuffixes.has(r)&&a<1e4;){let o=this.getNextAvailableSuffix(t,bt(r,this.suffixIncrement));if(o===null)return this._generateDefaultCustomId();r=o,a++}}let i=`${t}${r}`;return this._exceedsMaxLength(i)&&(i=this._generateDefaultCustomId()),i}populateFromActivities(t){if(!Array.isArray(t))return this;let r=[...new Set(t.filter(i=>i&&typeof i.customId=="string"&&i.customId).map(i=>i.customId))];for(let i of r){if(this.processedIds.has(i))continue;let{prefix:n,suffix:a}=this.analyzeCustomId(i);(n||a)&&(this._updatePrefixStats(n,a),this.processedIds.add(i))}return this}getDefaults(){return{prefix:this.defaultPrefix,increment:this.suffixIncrement}}generateCustomIdForNewChild(t){let{activity:r,useActivityCustomIdAsReference:i=!1}=t,n=nu(r),a=fu(n,i),{prefix:o,baseSuffix:s}=this._applyGenerationStrategy(a,n),c=null;if(a==="parentConversion"&&this.prefixMap.has(o)){this._ensureFreshBounds(o);let f=this.prefixMap.get(o).max;c=bt(f,this.suffixIncrement)}a==="parentConversion"&&this.releaseCustomId(n);let l=a==="parentConversion"&&c?c:s,d=this.getNextAvailableSuffix(o,l);if(d===null){let f=this._generateDefaultCustomId();return this.registerCustomId(f),f}let u=`${o}${d}`;return this._exceedsMaxLength(u)&&(u=this._generateDefaultCustomId()),this.registerCustomId(u),u}_applyGenerationStrategy(t,r){switch(t){case"parentConversion":return lu(this.defaultPrefix);case"pasteReference":return du(r,this.suffixIncrement);default:return uu(this.defaultPrefix)}}generateCustomIdForRestoredChild(t=null){if(t){let i=t.trim();if(i.length>0){let n=this.extractPrefix(i),a=this.extractSuffix(i),o=bt(a,this.suffixIncrement),s=this.getNextAvailableSuffix(n,o);if(s===null){let l=this._generateDefaultCustomId();return this.registerCustomId(l),l}let c=`${n}${s}`;return this._exceedsMaxLength(c)&&(c=this._generateDefaultCustomId()),this.registerCustomId(c),c}}let r=this.generateNextCustomId(this.defaultPrefix);return this.registerCustomId(r),r}clear(){this.prefixMap.clear(),this.processedIds.clear()}getTotalPrefixes(){return this.prefixMap.size}hasPrefix(t){return this.prefixMap.has(t)}isCustomIdInUse(t,r=null){if(!t||typeof t!="string"||!t.trim())return!1;let i=t.trim();return r&&i===r.trim()?!1:this.processedIds.has(i)}};var DA=1,_A=-1;function EA(e,t){return!e&&!t?null:e&&t?0:e?DA:_A}function yu(e){return e==null}function hu(e,t){let r=t.indexOf(String(e));return r===-1?t.length:r}function RA(e,t,r){return e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="number"&&typeof t=="number"?e-t:typeof e=="boolean"&&typeof t=="boolean"?Number(e)-Number(t):Array.isArray(e)&&Array.isArray(t)?e.length-t.length:String(e).localeCompare(String(t),r,{sensitivity:"base",numeric:!0})}function PA(e,t){let r=Xt(e.field);return r===null?null:(i,n)=>{let a=r.extract(i,t),o=r.extract(n,t),s=EA(yu(a),yu(o));if(s!==null)return s;let c=r.valueKind===E.ENUM?hu(a,r.order)-hu(o,r.order):RA(a,o,t.locale);return e.direction===ye.DESCENDING?-c:c}}function mu(e,t){let r=e.rules.map(i=>PA(i,t)).filter(i=>i!==null);return r.length===0?null:(i,n)=>{for(let a of r){let o=a(i,n);if(o!==0)return o}return 0}}function gu(e){let t=[];e.forEachActivity((r,i)=>{r.type==="project"&&e.getChildren(String(i)).length===0&&t.push(String(i))});for(let r of t)e.setActivityField(r,b.TYPE,Ue),LA(e,r)}function LA(e,t){let r=e.getActivity(t);if(!r||!r.startDate||r.durationHours==null)return;let i=new Date(r.startDate);i.setUTCHours(0,0,0,0);let n=e.getClosestWorkTime({date:i,dir:rt.FUTURE,task:r});if(n.getTime()===r.startDate.getTime())return;let a=e.calculateEndDate({startDate:n,durationHours:r.durationHours,task:r});e.setActivityField(t,b.START_DATE,n),e.setActivityField(t,b.END_DATE,a)}function Au(e){let t=[],r=[];e.forEachActivity((n,a)=>{n.parentId===null&&t.push(String(a))});let i=n=>{let a=e.getActivity(n);if(!a)return 0;let o=[...e.getChildren(n)],s=o.length===0?Ct(a.workHours,a.progress):o.reduce((c,l)=>c+i(String(l)),0);return e.setActivityField(n,b.REAL_WORK_HOURS,s),r.push(n),s};for(let n of t)i(n);return r}async function Iu(e){let{state:t,sector:r,scheduler:i,skipAutoSchedule:n,now:a}=e;if(At(t),r.updateDurationForPrimaveraEndDate&&bA(t),NA(t),Au(t),n){gr(t),a&&(Ce(t,a),qt(t,r.statusCriteria));return}let o=await i.schedule({});fr(t,o),wA(t),OA(t),await He(t,void 0,!1),gr(t),a&&(Ce(t,a),qt(t,r.statusCriteria))}function OA(e){e.forEachActivity(t=>{t.autoScheduling||!t.startDate||t.durationHours==null||e.getChildren(t.id).length>0||(t.endDate=e.calculateEndDate({startDate:t.startDate,durationHours:t.durationHours,task:t}),t.calendarDuration=Wt(t))})}function bA(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function NA(e){e.forEachActivity(t=>{let r=t.constraintType;if(!r||!t.constraintDate)return;let i=t.constraintDate;if(t.type==="milestone"&&(i.getUTCHours()!==0||i.getUTCMinutes()!==0))return;let n=e.calendarReader.getCalendar(String(t.calendarId));n&&(t.constraintDate=Yt(t.constraintDate,n,r))})}function wA(e){e.forEachActivity(t=>{if(t.type!=="milestone")return;let r=t.constraintType;if(!r||!t.constraintDate)return;let i=e.calendarReader.getCalendar(String(t.calendarId));i&&(t.constraintDate=Yt(t.constraintDate,i,r))})}var Bt={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function vu(e){let t=e.clock??null,r=t?.()??null,i=r?ci(r):null,n=e.reporter??Be,a=nn({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},n),o=a.sector;o.statusCriteria=Ii(e.statusCriteria),o.ganttId=e.ganttId??null;let s=a.calendars,c=a.baseCalendars??[],l=Qi(a.activities,a.links,a.calendars,c),d=A=>mu(A,pe(o.hoursPerDay)),u=new rr(l,d);u.hydrateViewState({hiddenIds:a.viewStateSeed.hiddenIds});let f=new We(u,n);gu(u);let p=Za({knownIds:a.activities.map(A=>A.id)}),y=to({seed:r?.getTime()??0,knownIds:a.links.map(A=>A.id)}),g=eo({knownIds:a.activities.map(A=>A.uniqueCorrelativeId)}),C=new un({defaultPrefix:o.customIdPrefix,suffixIncrement:o.customIdIncrement});if(C.populateFromActivities(a.activities),e.baselinePoints&&e.baselinePoints.length>0){let A=c.find(k=>k.baseDefault)?.id??null;ji(u,e.baselinePoints,i,n,A)}let R=Iu({state:u,sector:o,scheduler:f,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:i??void 0});return{sector:o,state:u,scheduler:f,activityIdGen:p,linkIdGen:y,uidGen:g,customIdTracker:C,calendars:s,baseCalendars:c,clock:t,reporter:n,initPromise:R}}function ir(e){if(e===void 0)return["undefined"];if(e===null)return["null"];if(typeof e=="string")return["string",e];if(typeof e=="boolean")return["boolean",e];if(typeof e=="number")return["number",Object.is(e,-0)?"-0":String(e)];if(typeof e=="bigint")return["bigint",String(e)];if(e instanceof Date)return["date",String(e.getTime())];if(Array.isArray(e))return["array",e.map(ir)];if(e instanceof Map)return["map",Array.from(e,([t,r])=>[ir(t),ir(r)]).sort((t,r)=>JSON.stringify(t).localeCompare(JSON.stringify(r)))];if(e instanceof Set)return["set",Array.from(e,ir).sort((t,r)=>JSON.stringify(t).localeCompare(JSON.stringify(r)))];if(typeof e=="object")return["object",Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,ir(r)])];throw new TypeError(`Unsupported canonical value: ${typeof e}`)}function Re(e){return JSON.stringify(ir(e))}function ro(e,t){let r=new Map(e.map(o=>[String(o.id),o])),i=new Map(t.map(o=>[String(o.id),o])),n=[...new Set([...r.keys(),...i.keys()])].sort(),a=[];for(let o of n){let s=i.get(o),c=r.get(o);if(c===void 0){a.push({id:o,kind:"deleted",after:null});continue}if(s===void 0){a.push({id:o,kind:"created",after:O(c)});continue}let l=FA(s,c);Object.keys(l).length>0&&a.push({id:o,kind:"updated",fields:l,after:O(c)})}return a}function FA(e,t){let r={},i=[...new Set([...Object.keys(e),...Object.keys(t)])].sort();for(let n of i)Re(e[n])!==Re(t[n])&&(r[n]={before:O(e[n]),after:O(t[n])});return r}function xA(e,t){let r=new Set(t.selectedIds.map(String)),i=new Set(e.selectedIds.map(String)),n=new Set(t.hiddenIds.map(String)),a=new Set(e.hiddenIds.map(String)),o=e.activities.map(({id:c})=>String(c)).sort(),s=[];for(let c of o){let l=r.has(c),d=i.has(c),u=!n.has(c),f=!a.has(c);l===d&&u===f||s.push({activityId:c,...l===d?{}:{checked:{before:l,after:d}},...u===f?{}:{visible:{before:u,after:f}}})}return s}function Cu(e,t){let r=Re(e.order)!==Re(t.order);return{source:{kind:Gt.INIT},activities:ro(e.activities,t.activities),links:ro(e.links,t.links),calendars:ro(e.calendars,t.calendars),trackingEvents:[],effects:[],viewState:xA(e,t),...r?{order:O(e.order)}:{}}}var nr={MOVE:"move",RESIZE_START:"resize-start",RESIZE_END:"resize-end"},MA=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),io=(e,t)=>e===null?t:Math.min(e,t),no=(e,t)=>e===null?t:Math.max(e,t);function ku(e,t,r){let i=[...new Set(t.kind===nr.MOVE?t.activityIds.map(String):[String(t.activityId)])];if(i.length===0)throw new Error("[ScheduleCore] date gesture has no participants");let n=UA(e,t,i);return BA(e,i,n),{getDates(a,o){if(r(),!Number.isFinite(o))throw new Error("[ScheduleCore] invalid date gesture edge");let s=n.get(String(a));if(!s)return null;let c=HA(s,o),l=jA(s,o);if(c===null||l===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(a)}`);return{startTimeMs:c,endTimeMs:l}}}}function UA(e,t,r){let i=new Map,n=t.kind===nr.MOVE?String(t.anchorActivityId):null,a=n===null?null:Su(e,n);if(n!==null&&!r.includes(n))throw new Error("[ScheduleCore] move anchor is not a participant");for(let o of r){let s=Su(e,o);if(t.kind===nr.MOVE){let c=a.startDate.getTime();i.set(o,{constantStart:null,variableStartOffset:s.startDate.getTime()-c,constantEnd:null,variableEndOffset:s.endDate.getTime()-c})}else t.kind===nr.RESIZE_START?i.set(o,{constantStart:null,variableStartOffset:0,constantEnd:s.endDate.getTime(),variableEndOffset:null}):i.set(o,{constantStart:s.startDate.getTime(),variableStartOffset:null,constantEnd:null,variableEndOffset:0})}return i}function BA(e,t,r){let i=Ar(e,new Set(t));for(let n of i){let a=MA();for(let o of e.getChildren(n)){let s=r.get(o);if(s){WA(a,s);continue}let c=e.getActivity(o);if(!c)throw new Error(`[ScheduleCore] missing child ${o} while previewing parent ${n}`);a.constantStart=io(a.constantStart,c.startDate.getTime()),a.constantEnd=no(a.constantEnd,c.endDate.getTime())}r.set(n,a)}}function Su(e,t){let r=e.getActivity(t);if(!r)throw new Error(`[ScheduleCore] missing date gesture activity ${t}`);if(e.hasChildren(t))throw new Error(`[ScheduleCore] summary activity ${t} cannot be dragged directly`);return r}function WA(e,t){t.constantStart!==null&&(e.constantStart=io(e.constantStart,t.constantStart)),t.variableStartOffset!==null&&(e.variableStartOffset=io(e.variableStartOffset,t.variableStartOffset)),t.constantEnd!==null&&(e.constantEnd=no(e.constantEnd,t.constantEnd)),t.variableEndOffset!==null&&(e.variableEndOffset=no(e.variableEndOffset,t.variableEndOffset))}function HA(e,t){if(e.variableStartOffset===null)return e.constantStart;let r=t+e.variableStartOffset;return e.constantStart===null?r:Math.min(e.constantStart,r)}function jA(e,t){if(e.variableEndOffset===null)return e.constantEnd;let r=t+e.variableEndOffset;return e.constantEnd===null?r:Math.max(e.constantEnd,r)}var ao=Symbol("ScheduleCore.fork.source");function VA(e){return e.kind===P.PERSISTENCE_ACKNOWLEDGE||e.kind===P.ACTIVITY_LOOKAHEAD_SYNC&&e.acknowledgePersistedLookahead===!0}function KA(e){for(let t of e.activities)if(t.kind==="deleted"||t.kind==="updated"&&t.fields!==void 0&&"parentId"in t.fields)return!0;return!1}function YA(e,t){let r=[];for(let i of e.activities){let n=t.getActivity(i.id);if(n===null)return null;r.push(n)}return r}function GA(e,t,r){if(e===null||e.filter!==t)return!1;let i=e.context.hoursPerDay===r.hoursPerDay,n=e.context.locale===r.locale;return i&&n}var ar=class e{activities;links;calendars;selection;view;baselines;impactRequests;persistence;history;projection;criticalPath;diagnostics;_activityClipboard={value:null};_status=Bt.READY;coreRuntime;_isFork;_undo=new Xi;_opQueue=Promise.resolve();_scheduleRevision=0;_pendingScheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){if(Object.assign(this,yo(this)),ao in t){this._isFork=!0;let n=t[ao],a=n.coreRuntime.state.fork();this.coreRuntime={state:a,scheduler:new We(a,n.coreRuntime.reporter),sector:O(n.coreRuntime.sector),activityIdGenerator:n.coreRuntime.activityIdGenerator.fork(),linkIdGenerator:n.coreRuntime.linkIdGenerator.fork(),uniqueCorrelativeIdGenerator:n.coreRuntime.uniqueCorrelativeIdGenerator.fork(),customIdTracker:n.coreRuntime.customIdTracker.fork(),calendars:new Map(Array.from(n.coreRuntime.calendars,([o,s])=>[o,O(s)])),baseCalendars:O(n.coreRuntime.baseCalendars),clock:n.coreRuntime.clock,reporter:n.coreRuntime.reporter},this._activityClipboard.value=O(n._activityClipboard.value),this._undo=n._undo.fork(),this._saveTracker=n._saveTracker.fork(),this._scheduleRevision=n._scheduleRevision,this._pendingScheduleRevision=n._scheduleRevision,this._criticalPathRevision=n._criticalPathRevision,this._initPromise=Promise.resolve(),this._criticalPathReady=Promise.resolve(null),this._ready=this._initPromise;return}this._isFork=!1;let r=vu(t);this.coreRuntime={state:r.state,scheduler:r.scheduler,sector:r.sector,activityIdGenerator:r.activityIdGen,linkIdGenerator:r.linkIdGen,uniqueCorrelativeIdGenerator:r.uidGen,customIdTracker:r.customIdTracker,clock:r.clock,calendars:new Map(r.calendars.map(n=>[n.id,n])),baseCalendars:r.baseCalendars,reporter:r.reporter},this._initPromise=r.initPromise.then(()=>{this._status!==Bt.DESTROYED&&this._saveTracker.init(this.coreRuntime.state.getAllActivities(),this.getAllLinksView())}),this._criticalPathReady=this._initPromise.then(()=>this._startCriticalPathForCurrentRevision());let i=t.criticalPathOnLoad===!0;this._ready=i?this._criticalPathReady.then(()=>{}):this._initPromise}get ready(){return this._ready}fork(){return this._enqueue(async()=>(await this._ready,this.assertReady(),new e({[ao]:this})))}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return O(this.coreRuntime.sector)}getActivityView(t){return this.assertReady(),od(this.coreRuntime.state,t)}createDateGesturePreview(t){this.assertReady();let r=this._scheduleRevision;return ku(this.coreRuntime.state,t,()=>{if(this.assertReady(),this._scheduleRevision!==r)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),sd(this.coreRuntime.state)}getIndentTargetParentIds(t){this.assertReady();let r=Wi(t.map(i=>String(i)),this.coreRuntime.state);return[...new Set(r.allowedMoves.map(i=>String(i.newParentId)))]}getChildrenView(t){return this.assertReady(),dd(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),Ka(this.coreRuntime.state,t)}getLinksForActivityView(t){this.assertReady();let r=this.coreRuntime.state,i=[],n=new Set,a=o=>{if(n.has(o))return;n.add(o);let s=Ka(r,o);s&&i.push(s)};for(let o of r.getOutgoingLinkIds(t))a(o);for(let o of r.getIncomingLinkIds(t))a(o);return i}getAllLinksView(){return this.assertReady(),pd(this.coreRuntime.state)}auditEffectiveGraph(){this.assertReady();let t=this.coreRuntime.state,r=t.getAllLinks(),i=yr(t,r),n=Jr(i),a=0;for(let o of n)o.length>a&&(a=o.length);return{activityCount:t.getAllIds().length,logicalLinkCount:r.length,effectiveEdgeCount:i.length,circularComponents:n,largestComponentSize:a}}getProperty(t,r){this.assertReady();let i=this.coreRuntime.state.getActivity(t);return i?O(i[r]):null}getAllIds(){return this.assertReady(),cd(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),ld(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),Va(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),ud(this.coreRuntime.state)}getHiddenActivityIds(){return this.assertReady(),this.coreRuntime.state.hiddenIds().map(String)}getVisibleActivityIds(){this.assertReady();let t=new Set(this.coreRuntime.state.hiddenIds().map(String));return this.coreRuntime.state.getAllIds().map(String).filter(r=>!t.has(r))}getActiveFilter(){return this.assertReady(),O(this.coreRuntime.state.getActiveFilter())}getActiveOrder(){return this.assertReady(),O(this.coreRuntime.state.getActiveOrder())}getVisualOrderIds(){return this.assertReady(),[...this.coreRuntime.state.getVisualOrderIds()]}hasChild(t){return this.assertReady(),fd(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let r=this.coreRuntime.calendars.get(t);return r?O(r):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),t=>O(t))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(t=>O(t))}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),yd(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(t=>this.coreRuntime.state.getLink(t)).map(O)}getNewLinks(){return this.assertReady(),this._saveTracker.newLinks(t=>this.coreRuntime.state.getLink(t)).map(O)}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(t=>this.coreRuntime.state.getActivity(t)).map(O)}getModifiedActivityFields(){return this.assertReady(),O(this._saveTracker.modifiedActivityFields(t=>this.coreRuntime.state.getActivity(t)))}getNewActivities(){return this.assertReady(),this._saveTracker.newActivities(t=>this.coreRuntime.state.getActivity(t)).map(O)}hasUnsavedChanges(){return this.assertReady(),this._saveTracker.hasUnsavedChanges()}getScheduleRevision(){return this._scheduleRevision}capturePersistenceHistoryBoundary(){return this.assertReady(),this._undo.capturePersistenceBoundary()}getCanonicalDigest(){this.assertReady();let t=(r,i)=>String(r.id).localeCompare(String(i.id));return Re({sector:this.getSector(),activities:[...this.getAllActivitiesView()].sort(t),links:[...this.getAllLinksView()].sort(t),calendars:[...this.getAllCalendars()].sort(t),baseCalendars:[...this.getBaseCalendars()].sort(t)})}createProjectionChangeSetFrom(t){this.assertReady(),t.assertReady();let r=i=>({activities:i.getAllActivitiesView(),links:i.getAllLinksView(),calendars:i.getAllCalendars(),selectedIds:i.getSelectedActivityIds(),hiddenIds:i.getHiddenActivityIds(),order:xe(i.coreRuntime.state)});return Cu(r(this),r(t))}getDeletedActivitiesSinceLastSave(){return this.assertReady(),this._saveTracker.deletedActivities(t=>this.coreRuntime.state.getActivity(t)).map(O)}getDeletedLinksSinceLastSave(){return this.assertReady(),this._saveTracker.deletedLinks(t=>this.coreRuntime.state.getLink(t)).map(O)}_enqueue(t){let r=this._opQueue.then(t,t);return this._opQueue=r.then(()=>{},()=>{}),r}_beginScheduleMutation(t){return ha(t)?this._admitScheduleMutation():!1}_admitScheduleMutation(){return this._pendingScheduleRevision++,this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),!0}_settleScheduleMutation(t,r){t&&(r||(this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision-1,this._scheduleRevision),this._pendingScheduleRevision===this._scheduleRevision&&this._criticalPathRevision!==this._scheduleRevision&&this.recomputeCriticalPath().catch(i=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path re-arm after a barren mutation failed",i)})))}async dispatch(t,r={}){let i=this._beginScheduleMutation(t);return this._enqueue(()=>this._dispatchInner(t,r,i))}async applyActivityBatch(t,r={}){let i=this._beginScheduleMutation(t);return this._enqueue(()=>this._dispatchInner(t,r,i))}async _dispatchInner(t,r={},i=!1){let n=!1;try{let a=await this._runDispatch(t,r);return n=a.changedState,a.result}finally{this._settleScheduleMutation(i,n)}}async _runDispatch(t,r){if(this.assertReady(),this._isFork&&VA(t))return{result:{ok:!1,reason:v.SANDBOX_PERSISTENCE_FORBIDDEN},changedState:!1};let i=hd(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat}),n=Dd(t),a=[this.coreRuntime.activityIdGenerator.snapshot(),this.coreRuntime.linkIdGenerator.snapshot(),this.coreRuntime.uniqueCorrelativeIdGenerator.snapshot()];this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let o,s;try{o=await wl(t,r,{adapter:this.coreRuntime.state,ctx:i,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,linkIdGen:this.coreRuntime.linkIdGenerator,isActivityIdReserved:l=>this._saveTracker.hasCheckpointActivityId(l),isLinkIdReserved:l=>this._saveTracker.hasCheckpointLinkId(l),uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,reporter:this.coreRuntime.reporter,activityClipboard:this._activityClipboard,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(l=>l.baseDefault)?.id??null,now:this.coreRuntime.clock?ci(this.coreRuntime.clock()):null});let c=this.coreRuntime.state.peekWriteCapture()?.progressFallbackBefore;c&&c.size>0&&(s=new Map(c)),o.ok||this._rollback(a)}catch(c){throw this._rollback(a),c}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(o.ok&&n==="record"&&za(o.changes)){let c=Cd(this.coreRuntime.state,o.changes),l=s?new Map(Array.from(s.keys(),d=>[d,this.coreRuntime.state.getProgressFallback(d)])):void 0;this._undo.record(Ya(vd(o.changes),o.__beforeSnap,o.__beforeLinks,c.afterSnap,c.afterLinks,s,l),Sd(t),Date.now())}if(o.ok)if(n==="checkpoint-on-success"){if(t.kind!==P.PERSISTENCE_ACKNOWLEDGE)throw new Error("checkpoint-on-success requires persistence acknowledge");let c=this.coreRuntime.state.getAllActivities(),l=this.coreRuntime.state.getAllLinks(),d=t.checkpoint,u=d?.historyBoundary??this._undo.capturePersistenceBoundary();this._saveTracker.acknowledge(d?.activities??c,d?.links??l,t.activities,t.links,c,l),this._undo.discardThrough(u),this._undo.applyPersistedIdentities(t.activities??[],t.links??[])}else t.kind===P.ACTIVITY_LOOKAHEAD_SYNC&&t.acknowledgePersistedLookahead===!0?(this._saveTracker.acknowledgePersistedLookahead(o.changes.activities,c=>this.coreRuntime.state.getActivity(c)),t.persistedProgress!==void 0&&this._undo.clear()):this._saveTracker.recordChanges(o.changes.activities,o.changes.links,c=>this.coreRuntime.state.getActivity(c),c=>this.coreRuntime.state.getLink(c));return o=this._withReappliedViewState(t,o),o.ok?ha(t)&&za(o.changes)?(this._recordScheduleMutation(r.skipAutoSchedule!==!0&&r.skipCriticalPath!==!0&&Te(t)),{result:Tu(o),changedState:!0}):{result:Tu(o),changedState:!1}:{result:o,changedState:!1}}recomputeCriticalPath(){let t=this._enqueue(async()=>({job:this._startCriticalPathForCurrentRevision()})).then(({job:r})=>r);return this._criticalPathReady=t,t}isCriticalPathSettled(){return this._criticalPathRevision===this._scheduleRevision&&this._pendingScheduleRevision===this._scheduleRevision&&this._activeCriticalPath===null}async whenCriticalPathSettled(){for(;!this.isCriticalPathSettled();)await this.recomputeCriticalPath()}_withReappliedViewState(t,r){if(!r.ok||(t.kind===P.VISIBILITY_SET&&this.coreRuntime.state.setFilterProjection(null),!Dc(t)))return r;let i=this._reapplyViewState(r.changes);return i===null?r:{...r,changes:i}}_reapplyViewState(t){let r=this._reapplyActiveFilter(t),i=this._emitTouchedBranchOrder(r??t);return this._reapplyActiveOrder(i.changes??r??t,i.touchedParents)??i.changes??r}_emitTouchedBranchOrder(t){let r=this.coreRuntime.state,i=Ld(t,a=>r.getParentId(a));if(r.getActiveOrder()!==null)return{changes:null,touchedParents:i};if(i.size===0)return{changes:null,touchedParents:i};let n=kn(r,i);return n.length===0?{changes:null,touchedParents:i}:{changes:{...t,order:n},touchedParents:i}}_reapplyActiveOrder(t,r){let i=this.coreRuntime.state;if(i.getActiveOrder()===null)return null;if(i.invalidateDerivedOrder(),t.links.length>0||t.calendars.length>0)return{...t,order:xe(i)};let a=new Set(r);for(let s of t.activities){if(s.kind==="deleted")return{...t,order:xe(i)};let c=i.getParentId(s.id);a.add(c===null?"0":String(c))}let o=kn(i,a);return o.length===0?null:{...t,order:o}}_reapplyActiveFilter(t){let r=this.coreRuntime.state,i=r.getActiveFilter();if(i===null)return null;let n=pe(this.coreRuntime.sector.hoursPerDay),a=r.getFilterProjection(),o=GA(a,i,n),s=KA(t)?null:YA(t,r),c,l;if(s===null||!o){let f=Br({activities:r.getAllActivities(),parentOf:p=>r.getParentId(p),filter:i,context:n});r.setFilterProjection(f),l=f.visibleIds,c=r.getAllIds()}else c=To(a,s,f=>r.getParentId(f)),l=a.visibleIds;let u=Fe(r,l,c);return u.length===0?null:{...t,viewState:[...t.viewState??[],...u]}}_recordScheduleMutation(t){this._scheduleRevision++,this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision,this._scheduleRevision),this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),t&&(this._criticalPathRevision=this._scheduleRevision)}_startCriticalPathForCurrentRevision(){if(this._status===Bt.DESTROYED)return Promise.resolve(null);let t=this._scheduleRevision;if(this._criticalPathRevision===t)return Promise.resolve(null);if(this._activeCriticalPath?.revision===t)return this._activeCriticalPath.promise;this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0);let r={cancelled:!1},i=new rr(Qi(this.coreRuntime.state.getAllActivities().map(s=>et(s)),this.coreRuntime.state.getAllLinks().map(s=>({...s})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),n=()=>!r.cancelled&&this._status!==Bt.DESTROYED&&this._scheduleRevision===t&&this._pendingScheduleRevision===this._scheduleRevision,a=(async()=>{let s=await pa(i,this.coreRuntime.sector.hoursPerDay,n);return!n()||s===null?null:this._enqueue(async()=>{if(!n())return null;this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let c;try{for(let[l,d]of s.activities)ua(this.coreRuntime.state,l,d);for(let[l,d]of s.links)fa(this.coreRuntime.state,l,d);c=await K(this.coreRuntime.state,{source:{kind:Gt.INIT},beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay}),this._criticalPathRevision=t}catch(l){throw this._rollback(),l}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return{changes:c}})})();this._activeCriticalPath={revision:t,cancellation:r,promise:a};let o=()=>{this._activeCriticalPath?.promise===a&&(this._activeCriticalPath=null)};return a.then(o,o),a}undo(t={}){let r=this._admitScheduleMutation(),i=!1,n=this._enqueue(async()=>{try{return await this._runUndo(t,a=>{i=a})}finally{this._settleScheduleMutation(r,i)}});return n.then(a=>{a&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(o=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after undo failed",o)})},()=>{}),n}async _runUndo(t,r){{if(this.assertReady(),t.expectedUndoDepth!==void 0&&this._undo.undoDepth()!==t.expectedUndoDepth)return null;let i=this._undo.takeUndo();if(!i)return null;_d(this.coreRuntime.state,i),this._recordScheduleMutation(!1),r(!0),Ga(i)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(i),this._undo.resetCoalesce();let n=$a(this.coreRuntime.state,i,"before");return this._saveTracker.recordChanges(n.activities,n.links,a=>this.coreRuntime.state.getActivity(a),a=>this.coreRuntime.state.getLink(a)),this._reapplyViewState(n)??n}}redo(t={}){let r=this._admitScheduleMutation(),i=!1,n=this._enqueue(async()=>{try{return await this._runRedo(a=>{i=a})}finally{this._settleScheduleMutation(r,i)}});return n.then(a=>{a&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(o=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after redo failed",o)})},()=>{}),n}async _runRedo(t){this.assertReady();let r=this._undo.takeRedo();if(!r)return null;Ed(this.coreRuntime.state,r),this._recordScheduleMutation(!1),t(!0),Ga(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce();let i=$a(this.coreRuntime.state,r,"after");return this._saveTracker.recordChanges(i.activities,i.links,n=>this.coreRuntime.state.getActivity(n),n=>this.coreRuntime.state.getLink(n)),this._reapplyViewState(i)??i}canUndo(){return this._undo.canUndo()}canRedo(){return this._undo.canRedo()}clearHistory(){this._undo.clear()}undoDepth(){return this._undo.undoDepth()}_resyncCustomIdTrackerFromModel(){this.coreRuntime.customIdTracker.clear(),this.coreRuntime.customIdTracker.populateFromActivities(this.coreRuntime.state.getAllActivities())}destroy(){this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),this.coreRuntime.calendars.clear(),this._saveTracker.clear(),this._status=Bt.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new tn;assertReady(){if(this._status===Bt.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===Bt.POISONED)throw new Error("[ScheduleCore] instance is poisoned (a rollback failed) \u2014 reload from backend")}_rollback(t){try{this.coreRuntime.state.restoreFromCapture(),this.coreRuntime.customIdTracker.rollbackCustomIdTransaction(),t&&(this.coreRuntime.activityIdGenerator.restore(t[0]),this.coreRuntime.linkIdGenerator.restore(t[1]),this.coreRuntime.uniqueCorrelativeIdGenerator.restore(t[2]))}catch(r){throw this._status=Bt.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",r),r}}};function Tu(e){let{__beforeSnap:t,__beforeLinks:r,...i}=e;return i}async function Du(e){let t=new ar(e);return await t.ready,t}var _u=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var Eu={asap:"AS SOON AS POSSIBLE",alap:"AS LATE AS POSSIBLE",snet:"START NO EARLIER THAN",snlt:"START NO LATER THAN",fnet:"FINISH NO EARLIER THAN",fnlt:"FINISH NO LATER THAN",mso:"MUST START ON",mfo:"MUST FINISH ON"};var Ru=8;var Pu={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return xu($A);})();
|
|
1
|
+
"use strict";var ScheduleCore=(()=>{var Un=Object.defineProperty;var df=Object.getOwnPropertyDescriptor;var uf=Object.getOwnPropertyNames;var ff=Object.prototype.hasOwnProperty;var pf=(e,t)=>{for(var r in t)Un(e,r,{get:t[r],enumerable:!0})},yf=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of uf(t))!ff.call(e,n)&&n!==r&&Un(e,n,{get:()=>t[n],enumerable:!(i=df(t,n))||i.enumerable});return e};var hf=e=>yf(Un({},"__esModule",{value:!0}),e);var MA={};pf(MA,{ACTIVITY_BATCH_ACTION_KIND:()=>ue,ACTIVITY_BATCH_MODE:()=>pt,ACTIVITY_DATE_EDGE:()=>Rr,ACTIVITY_FIELD:()=>It,ACTIVITY_PONDERATOR_CRITERION:()=>gt,ACTIVITY_PROGRESS_ORIGIN:()=>Mi,ACTIVITY_TYPE:()=>D,CALENDAR_UNIT:()=>mt,CHANGE_SET_SOURCE_KIND:()=>oe,COLUMN:()=>_,COMPLETED_PROGRESS:()=>Nr,CONSTRAINT_TYPE:()=>A,CONSTRAINT_TYPE_TO_LABEL:()=>af,CONSTRAINT_WARNING_KIND:()=>Hi,CREATION_KIND:()=>cf,DATE_GESTURE_KIND:()=>Dr,DEFAULT_HOURS_PER_DAY:()=>sf,DISPATCH_ACTION_KIND:()=>m,DISPATCH_ACTION_KINDS:()=>Ya,DISPATCH_LINK_OPERATION_KIND:()=>at,DISPATCH_TRACK_EVENT:()=>jt,ENTITY_CHANGE_KIND:()=>N,FILTER_FIELD:()=>Y,FILTER_LOGIC:()=>si,FILTER_OPERATOR:()=>W,FILTER_REJECTION_REASON:()=>vt,FILTER_VALUE_KIND:()=>O,LINK_BATCH_OPERATION_KIND:()=>ze,LINK_CODE:()=>Ct,LINK_CODE_TO_TYPE:()=>Oe,LINK_REJECTION_REASON:()=>At,LINK_RELATIONSHIP:()=>_e,LINK_TYPE:()=>H,LINK_TYPE_CODE:()=>Si,NEW_ACTIVITY_DEFAULTS:()=>on,NOT_STARTED_PROGRESS:()=>As,ORDER_DIRECTION:()=>Re,REJECTION_REASON:()=>S,ROOT_PARENT_ID:()=>V,SCHEDULE_CORE_STATUS:()=>Zt,SCHEDULE_EFFECT_KIND:()=>Ui,SIR_AUTO_REJECT_REASON:()=>Bi,STATUS:()=>_t,STATUS_CRITERIA:()=>de,ScheduleCore:()=>_r,WORK_TIME_DIRECTION:()=>j,checkNoUpdatedLinks:()=>mu,computeExpectedProgress:()=>Io,createSchedule:()=>nf,expectedProgressFromBaseline:()=>lr,getActiveBaseline:()=>kt,getUnsavedActivities:()=>of,isRootParent:()=>M,normalizeParentKey:()=>Gt,parseFromBackend:()=>Ln,willRunCriticalPath:()=>zd,yieldToBrowser:()=>st});var D={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},mf=Object.values(D);function Bn(e){return mf.includes(e)}var ri={CONSTRAINT:"constraint",ALERT:"alert",WARNING:"warning"},j={FUTURE:"future",PAST:"past"},mt={HOUR:"hour",DAY:"day"},gt={DURATION:"DURATION",COST:"COST",WORK_HOURS:"HH"},de={BASELINE:"Baseline",ACTUAL:"Actual"},_t={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"},N={CREATED:"created",UPDATED:"updated",DELETED:"deleted"};var A={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},If={[A.MSO]:()=>!0,[A.MFO]:()=>!0,[A.SNLT]:(e,t)=>e<t,[A.SNET]:(e,t)=>e>t,[A.FNLT]:(e,t)=>e<t,[A.FNET]:(e,t)=>e>t};function Wa(e,t,r){if(!t)return{violated:!1};let i=If[e];return i?i(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var gf=new Set([A.MSO,A.SNET,A.SNLT]);function kr(e,t,r){return gf.has(e)?t:r}function Va(e,t,r){return{type:ri.CONSTRAINT,messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var Af={[A.SNET]:{startOfDay:!0,direction:j.FUTURE},[A.SNLT]:{startOfDay:!0,direction:j.PAST},[A.FNET]:{startOfDay:!1,direction:j.FUTURE},[A.FNLT]:{startOfDay:!1,direction:j.PAST},[A.MSO]:{startOfDay:!0,direction:j.FUTURE},[A.MFO]:{startOfDay:!1,direction:j.PAST}},ii=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),Ha=(e,t)=>new Date(e.getTime()+t*864e5),vf=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function Hn(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=Af[e.constraintType];if(!r)return e.constraintDate;let i=e.constraintDate,n=t.getClosestWorkTime({date:ii(i),dir:j.FUTURE,task:e});if(vf(n,i))return i.getTime()!==ii(i).getTime()?i:r.startOfDay?n:t.getClosestWorkTime({date:Ha(ii(i),1),dir:j.PAST,task:e});let o=ii(t.getClosestWorkTime({date:i,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:o,dir:j.FUTURE,task:e}):t.getClosestWorkTime({date:Ha(o,1),dir:j.PAST,task:e})}function ja(e,t){let r={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},i=e.constraintType;if(!i||i===A.ASAP||i===A.ALAP)return r;let n=Hn(e,t);if(!n)return r;let o=s=>t.calculateEndDate({startDate:s,durationHours:e.durationHours,task:e}),a=s=>t.calculateEndDate({startDate:s,durationHours:-e.durationHours,task:e});switch(i){case A.SNET:return{earliestStart:n,latestStart:null,earliestEnd:o(n),latestEnd:null};case A.SNLT:return{earliestStart:null,latestStart:n,earliestEnd:null,latestEnd:o(n)};case A.FNET:return{earliestStart:a(n),latestStart:null,earliestEnd:n,latestEnd:null};case A.FNLT:return{earliestStart:null,latestStart:a(n),earliestEnd:null,latestEnd:n};case A.MSO:{let s=o(n);return{earliestStart:n,latestStart:n,earliestEnd:s,latestEnd:s}}case A.MFO:{let s=a(n);return{earliestStart:s,latestStart:s,earliestEnd:n,latestEnd:n}}default:return r}}function Ka(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function Wn(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var H={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"},Cf=Object.values(H);function ni(e){return Cf.includes(e)}var Sf={TEXT:"text",DESCRIPTION:"description",DURATION:"duration",PROGRESS:"progress",COST:"cost",USED_COST:"used_cost",HH_WORK_TIME:"hhWorkTime",START_DATE:"start_date",END_DATE:"end_date",CONSTRAINT_TYPE:"constraint_type",CONSTRAINT_DATE:"constraint_date",CALENDAR_ID:"calendar_id",CUSTOM_ID:"custom_id",SUBCONTRACT_ID:"subcontractId",RESPONSABLES:"responsables",TAGS:"tags",CUSTOM_PREDECESSORS:"custom_predecessors",CUSTOM_SUCESSORS:"custom_sucessors"},Tf={REAL_WORK:"real_work",REAL_COST:"real_cost",EXPECTED_PROGRESS:"expected_progress",EXPECTED_PROGRESS_BASE:"expected_progress_base",START_BASE:"start_base",END_BASE:"end_base",DURATION_BASE:"duration_base",COST_BASE:"cost_base",WORK_BASE:"work_base",CALENDAR_DURATION:"calendarDuration",IS_CRITICAL:"is_critical",EARLY_START:"earlyStart",EARLY_FINISH:"earlyFinish",LATE_START:"lateStart",LATE_FINISH:"lateFinish",FREE_SLACK:"freeSlack",TOTAL_SLACK:"totalSlack",CORRELATIVE_ID:"correlative_id",UNIQUE_CORRELATIVE_ID:"unique_correlative_id",PONDERATOR:"ponderator",STATUS:"status"},_={...Sf,...Tf};var dt={CREATE:"create",UPDATE:"update",DELETE:"delete"},At={SELF_LINK:"self-link",CYCLE:"cycle",DUPLICATE:"duplicate",ACTIVITY_MISSING:"activity-missing",LINK_MISSING:"link-missing",HIERARCHY_LINK:"hierarchy-link"};var m={ACTIVITY_CLIPBOARD_CLEAR:"activity-clipboard-clear",ACTIVITY_COPY:"activity-copy",CALENDAR_RECONCILE:"calendar-reconcile",ACTIVITY_PASTE_COPIED:"activity-paste-copied",PERSISTENCE_ACKNOWLEDGE:"persistence-acknowledge",BASELINE_APPLY:"baseline-apply",PONDERATOR_CRITERION_SET:"ponderator-criterion-set",STATUS_CRITERIA_SET:"status-criteria-set",INLINE_EDIT:"inline-edit",DATES_BATCH:"dates-batch",BULK_EDIT:"bulk-edit",LINK_CREATE:"link-create",LINK_UPDATE:"link-update",LINK_DELETE:"link-delete",LINKS_BATCH:"links-batch",ACTIVITY_CREATE:"activity-create",ACTIVITY_DELETE:"activity-delete",ACTIVITY_MOVE:"activity-move",ACTIVITY_INDENT:"activity-indent",ACTIVITY_OUTDENT:"activity-outdent",ACTIVITY_SET_PROGRESS:"activity-set-progress",ACTIVITY_LOOKAHEAD_CONVERT:"activity-lookahead-convert",SELECTION_TOGGLE:"selection-toggle",SELECTION_REPLACE:"selection-replace",VISIBILITY_SET:"visibility-set",FILTER_SET:"filter-set",SORT_SET:"sort-set",SIR_SYNC:"sir-sync",ACTIVITY_LOOKAHEAD_SYNC:"activity-lookahead-sync"},ue="activity-batch",at=dt,Ya=Object.values(m);function kt(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isActiveVersion)??null}var It={NAME:"name",DESCRIPTION:"description",DURATION_DAYS:"durationDays",PROGRESS:"progress",COST:"cost",USED_COST:"usedCost",WORK_HOURS:"workHours",START_DATE:"startDate",END_DATE:"endDate",CONSTRAINT_TYPE:"constraintType",CONSTRAINT_DATE:"constraintDate",CALENDAR_ID:"calendarId",CUSTOM_ID:"customId",SUBCONTRACT_ID:"subcontractId",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds"},Rr={START:"start",END:"end"},_e={FINISH_TO_START:"finish-to-start",START_TO_START:"start-to-start",FINISH_TO_FINISH:"finish-to-finish",START_TO_FINISH:"start-to-finish"},ze={CREATE:"create",UPDATE:"update",REMOVE:"remove"};var Ef={[It.NAME]:_.TEXT,[It.DESCRIPTION]:_.DESCRIPTION,[It.DURATION_DAYS]:_.DURATION,[It.PROGRESS]:_.PROGRESS,[It.COST]:_.COST,[It.USED_COST]:_.USED_COST,[It.WORK_HOURS]:_.HH_WORK_TIME,[It.START_DATE]:_.START_DATE,[It.END_DATE]:_.END_DATE,[It.CONSTRAINT_TYPE]:_.CONSTRAINT_TYPE,[It.CONSTRAINT_DATE]:_.CONSTRAINT_DATE,[It.CALENDAR_ID]:_.CALENDAR_ID,[It.CUSTOM_ID]:_.CUSTOM_ID,[It.SUBCONTRACT_ID]:_.SUBCONTRACT_ID,[It.RESPONSABLE_IDS]:_.RESPONSABLES,[It.TAG_IDS]:_.TAGS};function Vn(e,t){return{activityId:e,column:Ef[t.field],newValue:t.value}}var Df={[_e.FINISH_TO_START]:H.FINISH_TO_START,[_e.START_TO_START]:H.START_TO_START,[_e.FINISH_TO_FINISH]:H.FINISH_TO_FINISH,[_e.START_TO_FINISH]:H.START_TO_FINISH};function Pr(e){return Df[e]}function _f(e){return e.kind===ze.CREATE?{kind:at.CREATE,source:e.sourceId,target:e.targetId,type:Pr(e.relationship),...e.lagDays===void 0?{}:{lag:e.lagDays},...e.linkId===void 0?{}:{linkId:e.linkId}}:e.kind===ze.UPDATE?{kind:at.UPDATE,linkId:e.linkId,...e.relationship===void 0?{}:{type:Pr(e.relationship)},...e.lagDays===void 0?{}:{lag:e.lagDays}}:e.kind===ze.REMOVE?{kind:at.DELETE,linkId:e.linkId}:e}function kf(e){return e===Rr.START?_.START_DATE:e===Rr.END?_.END_DATE:e}function Rf(e){return{kind:ue,mode:e.mode,items:e.items,links:e.links.map(t=>({source:t.source,target:t.target,type:Pr(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}})),...e.eventSource===void 0?{}:{eventSource:e.eventSource}}}function Pf(e){return{get:t=>e.getActivityView(t),list:()=>e.getAllActivitiesView(),ids:()=>e.getAllIds(),forEachId:t=>e.forEachActivityId(t),property:(t,r)=>e.getProperty(t,r),children:t=>e.getChildrenView(t),childIds:t=>e.getChildrenIds(t),hasChildren:t=>e.hasChild(t),indentTargetParentIds:t=>e.getIndentTargetParentIds(t),isCustomIdInUse:(t,r)=>e.isCustomIdInUse(t,r??null),create:(t,r)=>e.dispatch({...t,kind:m.ACTIVITY_CREATE},r),applyBatch:(t,r)=>e.applyActivityBatch(Rf(t),r),editInline:(t,r,i)=>e.dispatch({...Vn(t,r),kind:m.INLINE_EDIT},i),applyDragBatch:(t,r)=>e.dispatch({kind:m.DATES_BATCH,edits:t.map(i=>({activityId:i.activityId,column:kf(i.edge),newValue:i.value}))},r),editFields:(t,r)=>e.dispatch({kind:m.BULK_EDIT,edits:t.map(i=>Vn(i.activityId,i))},r),remove:(t,r={})=>e.dispatch({...r,kind:m.ACTIVITY_DELETE,activityIds:t}),move:(t,r)=>e.dispatch({...t,kind:m.ACTIVITY_MOVE},r),planLookaheadConversion:t=>e.planLookaheadConversion(t),applyLookaheadConversion:t=>e.applyLookaheadConversion(t),indent:(t,r={})=>e.dispatch({...r,kind:m.ACTIVITY_INDENT,activityIds:t}),outdent:(t,r={})=>e.dispatch({...r,kind:m.ACTIVITY_OUTDENT,activityIds:t}),setProgress:(t,r,i={})=>e.dispatch({...i,kind:m.ACTIVITY_SET_PROGRESS,activityId:t,newValue:r}),copy:(t={})=>e.dispatch({...t,kind:m.ACTIVITY_COPY}),paste:(t,r={})=>e.dispatch({...r,kind:m.ACTIVITY_PASTE_COPIED,destination:{afterSiblingId:t}}),clearClipboard:(t={})=>e.dispatch({...t,kind:m.ACTIVITY_CLIPBOARD_CLEAR}),lookaheadSync:t=>e.dispatch({...t,kind:m.ACTIVITY_LOOKAHEAD_SYNC}),createDateGesturePreview:t=>e.createDateGesturePreview(t)}}function Lf(e){return{get:t=>e.getLinkView(t),list:()=>e.getAllLinksView(),forActivity:t=>e.getLinksForActivityView(t),create:(t,r)=>e.dispatch({kind:m.LINK_CREATE,source:t.sourceId,target:t.targetId,type:Pr(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}},r),update:(t,r,i)=>e.dispatch({kind:m.LINK_UPDATE,linkId:t,...r.relationship===void 0?{}:{type:Pr(r.relationship)},...r.lagDays===void 0?{}:{lag:r.lagDays}},i),remove:(t,r)=>e.dispatch({kind:m.LINK_DELETE,linkId:t},r),batch:(t,r)=>e.dispatch({kind:m.LINKS_BATCH,operations:t.map(_f)},r)}}function Ga(e){let t=(r,i)=>e.dispatch({kind:m.BASELINE_APPLY,points:r},i);return{activities:Pf(e),links:Lf(e),calendars:{get:r=>e.getCalendar(r),list:()=>e.getAllCalendars(),listBase:()=>e.getBaseCalendars(),projectWorkHours:()=>e.getProjectWorkHours(),reconcile:r=>e.dispatch({kind:m.CALENDAR_RECONCILE},r)},selection:{ids:()=>e.getSelectedActivityIds(),toggle:({checked:r,...i})=>e.dispatch({...i,kind:m.SELECTION_TOGGLE,isChecked:r}),replace:(r,i={})=>e.dispatch({...i,kind:m.SELECTION_REPLACE,activityIds:r})},view:{hiddenActivityIds:()=>e.getHiddenActivityIds(),visibleActivityIds:()=>e.getVisibleActivityIds(),visualOrderIds:()=>e.getVisualOrderIds(),filter:()=>e.getActiveFilter(),setFilter:r=>e.dispatch({...r,kind:m.FILTER_SET}),order:()=>e.getActiveOrder(),setOrder:(r,i={})=>e.dispatch({...i,kind:m.SORT_SET,rules:r}),setVisibility:(r,i={})=>e.dispatch({...i,kind:m.VISIBILITY_SET,visibleIds:r}),setStatusCriteria:(r,i)=>e.dispatch({kind:m.STATUS_CRITERIA_SET,criteria:r},i)},baselines:{refresh:t,setVisibility:t,setPonderatorCriterion:(r,i)=>e.dispatch({kind:m.PONDERATOR_CRITERION_SET,criterion:r},i),activeFor:r=>kt(r)},impactRequests:{sync:r=>e.dispatch({...r,kind:m.SIR_SYNC})},persistence:{hasChanges:()=>e.hasUnsavedChanges(),modifiedActivities:()=>e.getModifiedActivities(),modifiedActivityFields:()=>e.getModifiedActivityFields(),newActivities:()=>e.getNewActivities(),deletedActivities:()=>e.getDeletedActivitiesSinceLastSave(),modifiedLinks:()=>e.getModifiedLinks(),newLinks:()=>e.getNewLinks(),deletedLinks:()=>e.getDeletedLinksSinceLastSave(),captureHistoryBoundary:()=>e.capturePersistenceHistoryBoundary(),readSnapshot:()=>({activities:e.getAllActivitiesView(),links:e.getAllLinksView(),historyBoundary:e.capturePersistenceHistoryBoundary()}),acknowledge:r=>e.dispatch({kind:m.PERSISTENCE_ACKNOWLEDGE,checkpoint:r})},history:{undo:r=>e.undo(r),redo:r=>e.redo(r),canUndo:()=>e.canUndo(),canRedo:()=>e.canRedo(),clear:()=>e.clearHistory(),depth:()=>e.undoDepth()},projection:{changeSetFrom:r=>e.createProjectionChangeSetFrom(r)},criticalPath:{get ready(){return e.criticalPathReady},recompute:()=>e.recomputeCriticalPath(),isSettled:()=>e.isCriticalPathSettled(),whenSettled:()=>e.whenCriticalPathSettled()},diagnostics:{auditEffectiveGraph:()=>e.auditEffectiveGraph(),revision:()=>e.getScheduleRevision(),stateRevision:()=>e.getStateRevision(),canonicalDigest:()=>e.getCanonicalDigest()}}}var xt=class{items=[];head=0;enqueue(t){this.items.push(t)}dequeue(){if(this.head>=this.items.length)return;let t=this.items[this.head];return this.head+=1,t}peek(){if(!(this.head>=this.items.length))return this.items[this.head]}get size(){return this.items.length-this.head}isEmpty(){return this.head>=this.items.length}};var oi=e=>String(e);function $a(e){let{clickedId:t,isChecked:r,currentSelection:i,hierarchy:n,isFrozen:o,exists:a,autoCheckParents:s}=e,c=oi(t),l=new Set([...i].map(String)),d=new Set(l),u=Of(c,n).filter(a),f=u.filter(y=>!o(y)),p=r&&f.length<u.length;r&&!p?d.add(c):d.delete(c);for(let y of f)r?d.add(y):d.delete(y);return p||Nf({id:c,isChecked:r,autoCheckParents:s,hierarchy:n,isFrozen:o,exists:a,next:d}),{nextSelection:d,changed:bf(l,d),parentBlocked:p}}function Of(e,t){let r=[],i=new xt;i.enqueue(e);let n=new Set([e]);for(;!i.isEmpty();){let o=i.dequeue();for(let a of t.getChildrenIds(o)){let s=oi(a);n.has(s)||(n.add(s),r.push(s),i.enqueue(s))}}return r}function Nf(e){let{id:t,isChecked:r,autoCheckParents:i,hierarchy:n,isFrozen:o,exists:a,next:s}=e,c=n.getParentId(t);for(;c!==null&&typeof c<"u";){let l=oi(c);if(o(l))return;let d=n.getChildrenIds(l).map(oi).filter(a),u=d.some(o),f=d.filter(g=>!o(g)),y=f.length>0&&f.every(g=>s.has(g))&&!u;if(r){if(!i||!y||s.has(l))return;s.add(l)}else{if(y||!s.has(l))return;s.delete(l)}c=n.getParentId(l)}}function bf(e,t){let r=[],i=[];for(let n of t)e.has(n)||r.push(n);for(let n of e)t.has(n)||i.push(n);return{checked:r,unchecked:i}}function qe(e){return(e.pendingRequestIds?.length??0)>0}var S={CANNOT_EDIT:"cannot_edit",PARSE_ERROR:"parse_error",INVALID:"invalid",CUSTOM_ID_DUPLICATE:"custom_id_duplicate",INVALID_LINK_TYPE:"invalid_link_type",INVALID_LINK_LAG:"invalid_link_lag",INVALID_VALUE:"invalid_value",NO_PIPELINE_FOR_COLUMN:"no_pipeline_for_column",ACTIVITY_NOT_FOUND:"activity_not_found",PARENT_NOT_FOUND:"parent_not_found",ACTIVITY_IDS_EMPTY:"activity_ids_empty",NO_ACTIVITY_SELECTION:"no_activity_selection",CLIPBOARD_EMPTY:"clipboard_empty",ACTIVITY_PASTE_INVARIANT_FAILED:"activity_paste_invariant_failed",ANCHOR_SIBLING_CONFLICT:"anchor_sibling_conflict",ANCHOR_SIBLING_NOT_FOUND:"anchor_sibling_not_found",ANCHOR_SIBLING_WRONG_PARENT:"anchor_sibling_wrong_parent",PARENT_FROZEN_BY_SIR:"parent_frozen_by_sir",CANNOT_MOVE_INTO_OWN_DESCENDANT:"cannot_move_into_own_descendant",INDENT_NO_ELIGIBLE_SIBLING:"indent_no_eligible_sibling",OUTDENT_ROOT_LEVEL_NOT_EDITABLE:"outdent_root_level_not_editable",HIERARCHY_CYCLE:"hierarchy_cycle",SANDBOX_PERSISTENCE_FORBIDDEN:"sandbox_persistence_forbidden",STALE_STATE_REVISION:"stale-state-revision",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var za=(e,t)=>{let r=e.getActivity(t);return r!=null&&qe(r)},qa=(e,t,r)=>{let i=[],n=(o,a)=>{let s=t.isChecked(o);t.setChecked(o,a)&&i.push({activityId:o,checked:{before:s,after:a}})};for(let o of r.checked)n(o,!0);for(let o of r.unchecked)n(o,!1);return{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:i}};function Ja(e,t){let{adapter:r}=t,i=e.activityId;if(!r.getActivity(i))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let n=e.frozenIds?new Set(e.frozenIds):null,o=n?s=>n.has(s):s=>za(r,s),a=$a({clickedId:i,isChecked:e.isChecked,currentSelection:new Set(r.checkedIds().map(String)),hierarchy:{getChildrenIds:s=>r.getChildren(s),getParentId:s=>{let c=r.getParentId(s);return!c||c==="0"?null:String(c)}},isFrozen:o,exists:s=>r.activityExists(s),autoCheckParents:e.autoCheckParents??!1});return{ok:!0,changes:qa(e,r,a.changed)}}function ai(e,t){let{adapter:r}=t,i=new Set(e.activityIds.map(String).filter(a=>r.activityExists(a)).filter(a=>!za(r,a))),n=new Set(r.checkedIds().map(String)),o={checked:[...i].filter(a=>!n.has(a)),unchecked:[...n].filter(a=>!i.has(a))};return{ok:!0,changes:qa(e,r,o)}}function Je(e,t,r=e.getAllIds()){let i=[];for(let n of r){let o=String(n),a=t.has(o),s=e.isVisible(o);s!==a&&(e.setVisible(o,a),i.push({activityId:o,visible:{before:s,after:a}}))}return i}function Xa(e,t){let{adapter:r}=t,i=new Set(e.visibleIds.map(String)),n=Je(r,i);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:n}}}var Za={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var O={STRING:"string",NUMBER:"number",DATE:"date",ID_ARRAY:"id-array",ENUM:"enum",BOOLEAN:"boolean",REFERENCE:"reference"},Y={NAME:"name",DESCRIPTION:"description",CUSTOM_ID:"customId",CORRELATIVE_ID:"correlativeId",UNIQUE_CORRELATIVE_ID:"uniqueCorrelativeId",PROGRESS:"progress",DURATION_DAYS:"durationDays",CALENDAR_DURATION:"calendarDuration",COST:"cost",USED_COST:"usedCost",REAL_COST:"realCost",WORK_HOURS:"workHours",REAL_WORK_HOURS:"realWorkHours",PONDERATOR:"ponderator",FREE_SLACK_DAYS:"freeSlackDays",TOTAL_SLACK_DAYS:"totalSlackDays",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",BASELINE_DURATION_DAYS:"baselineDurationDays",BASELINE_COST:"baselineCost",BASELINE_WORK_HOURS:"baselineWorkHours",EXPECTED_PROGRESS:"expectedProgress",START_DATE:"startDate",END_DATE:"endDate",CONSTRAINT_DATE:"constraintDate",BASELINE_START_DATE:"baselineStartDate",BASELINE_END_DATE:"baselineEndDate",EARLY_START:"earlyStart",EARLY_FINISH:"earlyFinish",LATE_START:"lateStart",LATE_FINISH:"lateFinish",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds",STATUS:"status",CONSTRAINT_TYPE:"constraintType",CALENDAR_ID:"calendarId",SUBCONTRACT_ID:"subcontractId",IS_CRITICAL:"isCritical"},W={INCLUDES:"includes",NOT_INCLUDES:"notIncludes",IS:"is",IS_NOT:"isNot",EQUALS:"equals",NOT_EQUALS:"notEquals",GREATER_THAN:"greaterThan",LESS_THAN:"lessThan",GREATER_OR_EQUAL:"greaterOrEqual",LESS_OR_EQUAL:"lessOrEqual",AFTER:"after",BEFORE:"before",BETWEEN:"between",SOME_OF:"someOf",NOT_SOME_OF:"notSomeOf"},si={AND:"and",OR:"or"};var Ff=2,wf=[_t.WAITING,_t.DONE,_t.DOING,_t.OVERDUE,_t.ADVANCEMENT],xf=[A.MFO,A.MSO,A.SNLT,A.SNET,A.ALAP,A.ASAP,A.FNET,A.FNLT],Mf=1e3*60*60*24;function jn(e,t){return e===null||t<=0?null:e/t}function Uf(e,t){let r=Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()),i=Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate());return Math.floor((i-r)/Mf)+1}var Bf={[Y.NAME]:{valueKind:O.STRING,extract:e=>e.name},[Y.DESCRIPTION]:{valueKind:O.STRING,extract:e=>e.description},[Y.CUSTOM_ID]:{valueKind:O.STRING,extract:e=>e.customId},[Y.CORRELATIVE_ID]:{valueKind:O.NUMBER,extract:e=>e.correlativeId},[Y.UNIQUE_CORRELATIVE_ID]:{valueKind:O.NUMBER,extract:e=>{let t=Number(e.uniqueCorrelativeId);return Number.isFinite(t)?t:null}},[Y.PROGRESS]:{valueKind:O.NUMBER,extract:e=>e.progress},[Y.DURATION_DAYS]:{valueKind:O.NUMBER,extract:(e,t)=>jn(e.durationHours,t.hoursPerDay)},[Y.CALENDAR_DURATION]:{valueKind:O.NUMBER,extract:e=>e.type===D.MILESTONE?0:Uf(e.startDate,e.endDate)},[Y.COST]:{valueKind:O.NUMBER,extract:e=>e.cost},[Y.USED_COST]:{valueKind:O.NUMBER,extract:e=>e.usedCost},[Y.REAL_COST]:{valueKind:O.NUMBER,extract:e=>e.realCost},[Y.WORK_HOURS]:{valueKind:O.NUMBER,extract:e=>e.workHours},[Y.REAL_WORK_HOURS]:{valueKind:O.NUMBER,extract:e=>e.realWorkHours},[Y.PONDERATOR]:{valueKind:O.NUMBER,extract:e=>e.ponderator},[Y.FREE_SLACK_DAYS]:{valueKind:O.NUMBER,extract:(e,t)=>jn(e.freeSlackHours,t.hoursPerDay)},[Y.TOTAL_SLACK_DAYS]:{valueKind:O.NUMBER,extract:(e,t)=>jn(e.criticalPath?.totalSlackHours??null,t.hoursPerDay)},[Y.EXPECTED_PROGRESS_BASELINE]:{valueKind:O.NUMBER,equalityPrecision:Ff,extract:e=>e.expectedProgressBaseline},[Y.EXPECTED_PROGRESS]:{valueKind:O.NUMBER,extract:e=>e.expectedProgress},[Y.BASELINE_DURATION_DAYS]:{valueKind:O.NUMBER,extract:e=>e.baselineSnapshot?.durationDays??null},[Y.BASELINE_COST]:{valueKind:O.NUMBER,extract:e=>e.baselineSnapshot?.cost??null},[Y.BASELINE_WORK_HOURS]:{valueKind:O.NUMBER,extract:e=>e.baselineSnapshot?.workHours??null},[Y.START_DATE]:{valueKind:O.DATE,extract:e=>e.startDate},[Y.END_DATE]:{valueKind:O.DATE,extract:e=>e.endDate},[Y.CONSTRAINT_DATE]:{valueKind:O.DATE,extract:e=>e.constraintDate},[Y.BASELINE_START_DATE]:{valueKind:O.DATE,extract:e=>e.baselineSnapshot?.startDate??null},[Y.BASELINE_END_DATE]:{valueKind:O.DATE,extract:e=>e.baselineSnapshot?.endDate??null},[Y.EARLY_START]:{valueKind:O.DATE,extract:e=>e.criticalPath?.earlyStart??null},[Y.EARLY_FINISH]:{valueKind:O.DATE,extract:e=>e.criticalPath?.earlyFinish??null},[Y.LATE_START]:{valueKind:O.DATE,extract:e=>e.criticalPath?.lateStart??null},[Y.LATE_FINISH]:{valueKind:O.DATE,extract:e=>e.criticalPath?.lateFinish??null},[Y.RESPONSABLE_IDS]:{valueKind:O.ID_ARRAY,extract:e=>e.responsableIds},[Y.TAG_IDS]:{valueKind:O.ID_ARRAY,extract:e=>e.tagIds},[Y.STATUS]:{valueKind:O.ENUM,order:wf,extract:e=>e.status},[Y.CONSTRAINT_TYPE]:{valueKind:O.ENUM,order:xf,extract:e=>e.constraintType},[Y.CALENDAR_ID]:{valueKind:O.REFERENCE,extract:e=>e.calendarId===null?null:String(e.calendarId)},[Y.SUBCONTRACT_ID]:{valueKind:O.REFERENCE,extract:e=>e.subcontractId===null?null:String(e.subcontractId)},[Y.IS_CRITICAL]:{valueKind:O.BOOLEAN,extract:e=>e.isCritical}};function fe(e){return Bf[e]??null}function Kn(e){return e instanceof Date?e:typeof e=="string"||typeof e=="number"?new Date(e):new Date(Number.NaN)}function ee(e){return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())}function Hf(e,t,r){let i=e===null;return r===W.INCLUDES?!i&&String(e).toLowerCase().includes(t.toLowerCase()):r===W.NOT_INCLUDES?i||!String(e).toLowerCase().includes(t.toLowerCase()):r===W.IS?!i&&String(e)===t:r===W.IS_NOT?i||String(e)!==t:!1}function Wf(e,t,r,i){if(e===null||typeof e!="number")return r===W.NOT_EQUALS;let n=i===void 0?e:Number(e.toFixed(i));return r===W.EQUALS?n===t:r===W.NOT_EQUALS?n!==t:r===W.GREATER_THAN?e>t:r===W.LESS_THAN?e<t:r===W.GREATER_OR_EQUAL?e>=t:r===W.LESS_OR_EQUAL?e<=t:!1}function Vf(e,t,r){return typeof e=="number"&&e>=t&&e<=r}function jf(e,t,r){if(!(e instanceof Date))return!1;let i=ee(e),n=ee(t);return r===W.AFTER?i>n:r===W.BEFORE?i<n:!1}function Kf(e,t,r){if(!(e instanceof Date))return!1;let i=ee(e);return i>=ee(t)&&i<=ee(r)}function Yf(e,t,r){let n=(Array.isArray(e)?e:[]).some(o=>t.has(String(o)));return r===W.SOME_OF?n:r===W.NOT_SOME_OF?!n:!1}function Gf(e,t,r){let i=e!==null&&t.has(String(e));return r===W.SOME_OF?i:r===W.NOT_SOME_OF?!i:!1}function Qa(e){let t=Array.isArray(e)?e:[e];return new Set(t.map(r=>String(r)))}function ts(e,t,r){let i=fe(t.field);if(i===null)return!1;let n=i.extract(e,r),{operator:o}=t;return o===W.BETWEEN?i.valueKind===O.NUMBER?Vf(n,Number(t.value),Number(t.valueTo)):i.valueKind===O.DATE?Kf(n,Kn(t.value),Kn(t.valueTo)):!1:i.valueKind===O.STRING?Hf(n,String(t.value),o):i.valueKind===O.NUMBER?Wf(n,Number(t.value),o,i.equalityPrecision):i.valueKind===O.DATE?jf(n,Kn(t.value),o):i.valueKind===O.ID_ARRAY?Yf(n,Qa(t.value),o):Gf(n,Qa(t.value),o)}function $f(e,t,r){return t.criteria.length===0?!0:t.logic===si.OR?t.criteria.some(i=>ts(e,i,r)):t.criteria.every(i=>ts(e,i,r))}function zf(e,t){let r=ee(e.startDate),i=ee(e.endDate),n=ee(t.start),o=ee(t.end),a=r>=n&&i<=o,s=r>=n&&r<=o,c=n>=r&&n<=i;return a||s||c}function Yn(e,t,r){let i=$f(e,t,r),n=t.dateRange,o=n===void 0||zf(e,n);return i&&o}function qf(e,t,r){let i=t(e);for(;i!==null&&!r.has(String(i));)r.add(String(i)),i=t(i)}function es(e){let{activities:t,parentOf:r,filter:i,context:n}=e,o=new Set,a=[];for(let s of t)Yn(s,i,n)&&(o.add(String(s.id)),a.push(s.id));for(let s of a)qf(s,r,o);return o}function Jf(e){let{activities:t,parentOf:r,filter:i,context:n}=e,o=new Set,a=new Map,s=new Map,c=new Map;for(let l of t){let d=String(l.id),u=r(d);s.set(d,u),c.set(d,c.get(d)??0),u!==null&&c.set(u,(c.get(u)??0)+1);let f=Yn(l,i,n);a.set(d,f?1:0),f&&o.add(d)}return{matchedIds:o,visibleReferenceCounts:a,parentIds:s,remainingChildren:c}}function Xf(e){let{visibleReferenceCounts:t,parentIds:r,remainingChildren:i}=e,n=[];for(let o of r.keys())i.get(o)===0&&n.push(o);for(;n.length>0;){let o=n.pop();if(o===void 0)break;let a=r.get(o);if(a==null)continue;let s=t.get(o)??0;t.set(a,(t.get(a)??0)+s);let c=(i.get(a)??1)-1;i.set(a,c),c===0&&n.push(a)}}function Zf(e){let t=new Set;for(let[r,i]of e)i>0&&t.add(r);return t}function ci(e){let t=Jf(e);Xf(t);let r=Zf(t.visibleReferenceCounts);return{filter:e.filter,context:e.context,matchedIds:t.matchedIds,visibleIds:r,visibleReferenceCounts:t.visibleReferenceCounts}}function rs(e,t,r){let i=new Set;for(let n of t){let o=String(n.id);i.add(o);let a=e.matchedIds.has(o),s=Yn(n,e.filter,e.context);if(a===s)continue;s?e.matchedIds.add(o):e.matchedIds.delete(o);let c=s?1:-1,l=o;for(;l!==null;){let d=e.visibleReferenceCounts.get(l)??0,u=d+c;e.visibleReferenceCounts.set(l,u);let f=d>0,p=u>0;f!==p&&(i.add(l),p?e.visibleIds.add(l):e.visibleIds.delete(l)),l=r(l)}}return i}function ke(e){return{hoursPerDay:e,locale:"en"}}var vt={UNKNOWN_FIELD:"unknown_field",UNKNOWN_OPERATOR:"unknown_operator",INVALID_VALUE:"invalid_value"},Qf={[O.STRING]:new Set([W.INCLUDES,W.NOT_INCLUDES,W.IS,W.IS_NOT]),[O.NUMBER]:new Set([W.EQUALS,W.NOT_EQUALS,W.GREATER_THAN,W.LESS_THAN,W.GREATER_OR_EQUAL,W.LESS_OR_EQUAL,W.BETWEEN]),[O.DATE]:new Set([W.AFTER,W.BEFORE,W.BETWEEN]),[O.ID_ARRAY]:new Set([W.SOME_OF,W.NOT_SOME_OF]),[O.ENUM]:new Set([W.SOME_OF,W.NOT_SOME_OF]),[O.BOOLEAN]:new Set([W.SOME_OF,W.NOT_SOME_OF]),[O.REFERENCE]:new Set([W.SOME_OF,W.NOT_SOME_OF])};function is(e){if(e===void 0)return{ok:!0,dateRange:void 0};if(typeof e!="object"||e===null)return{ok:!1,reason:vt.INVALID_VALUE};let{start:t,end:r}=e;if(!(t instanceof Date)||!(r instanceof Date))return{ok:!1,reason:vt.INVALID_VALUE};let i=t.getTime(),n=r.getTime();return!Number.isFinite(i)||!Number.isFinite(n)||i>n?{ok:!1,reason:vt.INVALID_VALUE}:{ok:!0,dateRange:{start:new Date(i),end:new Date(n)}}}function ns(e){let t=fe(e.field);if(t===null)return{ok:!1,reason:vt.UNKNOWN_FIELD};if(!Qf[t.valueKind].has(e.operator))return{ok:!1,reason:vt.UNKNOWN_OPERATOR};if(e.operator===W.BETWEEN)return tp(e,t.valueKind);if(t.valueKind===O.NUMBER){let i=Gn(e.value);return i===null?{ok:!1,reason:vt.INVALID_VALUE}:{ok:!0,criterion:{...e,value:i}}}if(t.valueKind===O.DATE){let i=$n(e.value);return i===null?{ok:!1,reason:vt.INVALID_VALUE}:{ok:!0,criterion:{...e,value:i}}}let r=ep(e,t.valueKind);return r!==null?{ok:!1,reason:r}:t.valueKind===O.BOOLEAN?{ok:!0,criterion:{...e,value:[...new Set(e.value)]}}:t.valueKind===O.ID_ARRAY||t.valueKind===O.ENUM||t.valueKind===O.REFERENCE?{ok:!0,criterion:{...e,value:[...new Set(e.value.map(String))]}}:{ok:!0,criterion:e}}function tp(e,t){if(t===O.NUMBER){let r=Gn(e.value),i=Gn(e.valueTo);return r===null||i===null||r>i?{ok:!1,reason:vt.INVALID_VALUE}:{ok:!0,criterion:{...e,value:r,valueTo:i}}}if(t===O.DATE){let r=$n(e.value),i=$n(e.valueTo);return r===null||i===null||r.getTime()>i.getTime()?{ok:!1,reason:vt.INVALID_VALUE}:{ok:!0,criterion:{...e,value:r,valueTo:i}}}return{ok:!1,reason:vt.UNKNOWN_OPERATOR}}function ep(e,t){let{value:r}=e;return t===O.BOOLEAN?Array.isArray(r)&&r.every(i=>typeof i=="boolean")?null:vt.INVALID_VALUE:t===O.ID_ARRAY||t===O.ENUM||t===O.REFERENCE?Array.isArray(r)&&r.every(i=>typeof i=="string"||typeof i=="number")?null:vt.INVALID_VALUE:Array.isArray(r)?vt.INVALID_VALUE:null}function Gn(e){if(typeof e=="string"&&e.trim()===""||typeof e!="string"&&typeof e!="number")return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function $n(e){let t;if(e instanceof Date)t=new Date(e.getTime());else if(typeof e=="string")t=new Date(e);else if(typeof e=="number")t=new Date(e);else return null;return Number.isFinite(t.getTime())?t:null}function F(e){return structuredClone(e)}function os(e){return e.criteria.length===0&&e.dateRange===void 0}function rp(e,t,r){let i=e.getAllActivities();if(os(t))return{visibleIds:es({activities:i,parentOf:o=>e.getParentId(o),filter:t,context:ke(r)}),projection:null};let n=ci({activities:i,parentOf:o=>e.getParentId(o),filter:t,context:ke(r)});return{visibleIds:n.visibleIds,projection:n}}function as(e,t){let{adapter:r,hoursPerDay:i}=t,n=[];for(let u of e.criteria){let f=ns(u);if(!f.ok)return{ok:!1,reason:f.reason};n.push(f.criterion)}let o=is(e.dateRange);if(!o.ok)return{ok:!1,reason:o.reason};let a=F(o.dateRange===void 0?{criteria:n,logic:e.logic}:{criteria:n,logic:e.logic,dateRange:o.dateRange});r.setActiveFilter(os(a)?null:a);let{visibleIds:s,projection:c}=rp(r,a,i);r.setFilterProjection(c);let l=Je(r,s);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:l}}}var Re={ASCENDING:"asc",DESCENDING:"desc"};var V="0";function M(e){return e==null||e===0||e==="0"}function Gt(e){return M(e)?"0":String(e)}var zn=Number.MAX_SAFE_INTEGER;function Ht(e,t){let r=Lr(e,t),i=t.getOrderComparator?.()??null;return r.sort(i===null?li:(n,o)=>i(n,o)||li(n,o)),r.map(n=>String(n.id))}function cs(e){let t=[],r=n=>{t.push(n);let o=Ht(String(n.id),e);for(let a of o){let s=e.getActivity(a);s&&r(s)}},i=Ht("0",e);for(let n of i){let o=e.getActivity(n);o&&r(o)}return t}function ls(e,t,r){let i=r.getActivity(e);if(!i)return null;let n=ds(i),o=Ht(n,r),a=o.findIndex(s=>String(s)===String(e));if(a<=0)return null;for(let s=a-1;s>=0;s--){let c=o[s];if(c!==void 0&&!ip(t,c))return c}return null}function qn(e,t){let r=t.getActivity(e);if(!r)return-1;let i=ds(r);return Ht(i,t).findIndex(o=>String(o)===String(e))}function Lr(e,t){let r=String(e)==="0"?t.getRootIds?.()??t.getChildren("0"):t.getChildren(e),i=[];for(let n of r){let o=t.getActivity(n);o&&i.push(o)}return i}function li(e,t){let r=ss(e),i=ss(t);return r!==i?r-i:String(e.id).localeCompare(String(t.id))}function ss(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:zn}function ds(e){let t=e.parentId;return t===null?"0":t}function ip(e,t){return e.has(t)?!0:e.has(String(t))}function Xe(e){let t=[],r=i=>{let n=Ht(i,e);n.length>1&&t.push({parentId:i,childIds:n});for(let o of n)r(o)};return r("0"),t}function Jn(e,t){let r=[];for(let i of t){let n=Ht(i,e);n.length>1&&r.push({parentId:i,childIds:n})}return r}function np(e){return fe(e.field)===null?vt.UNKNOWN_FIELD:e.direction!==Re.ASCENDING&&e.direction!==Re.DESCENDING?vt.UNKNOWN_OPERATOR:null}function us(e,t){let{adapter:r}=t;for(let o of e.rules){let a=np(o);if(a!==null)return{ok:!1,reason:a}}let i=e.rules.length===0?null:F({rules:e.rules});return r.setActiveOrder(i),{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],order:Xe(r)}}}function fs(e,t){throw new Error(t)}function ps(e,t){return()=>t()===e}var Xn=typeof window>"u",op=!Xn&&typeof MessageChannel<"u";function st(){return op?new Promise(e=>{let t=new MessageChannel;t.port1.onmessage=()=>{t.port1.close(),t.port2.close(),e()},t.port2.postMessage(null)}):Promise.resolve()}async function di(e,t){return performance.now()-e<Za.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await st(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function Ze(e){return Xn||await st(),e()?{aborted:!1}:{aborted:!0}}function ui(e,t){let{inDegree:r,successors:i}=ap(e,t),n=sp(r),o=cp(n,r,i),a=o.length<e.length,s=a?lp(e,o):[],c=[...o].reverse();return{ordered:o,reversed:c,hasCycles:a,cycleNodes:s}}function ap(e,t){let r=new Map,i=new Map;for(let n of e)r.set(n,0),i.set(n,[]);for(let n of t){let o=n.source,a=n.target;!r.has(o)||!r.has(a)||(i.get(o).push(a),r.set(a,(r.get(a)??0)+1))}return{inDegree:r,successors:i}}function sp(e){let t=new xt;for(let[r,i]of e)i===0&&t.enqueue(r);return t}function cp(e,t,r){let i=[];for(;!e.isEmpty();){let n=e.dequeue();i.push(n);for(let o of r.get(n)??[]){let a=(t.get(o)??1)-1;t.set(o,a),a===0&&e.enqueue(o)}}return i}function lp(e,t){let r=new Set(t);return e.filter(i=>!r.has(i))}var fi=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=ui(t,r),this.cached)}};function ys(e,t){let r=[];for(let i of e)t.has(i)&&r.push(i);return r}var Zn={OWN_BASELINE:"own-baseline",RECURSIVE_LEAF_SUM:"recursive-leaf-sum",ZERO:"zero"},Qn={[D.PROJECT]:{alwaysSummary:!0,holdsConstraint:!1,carriesCustomId:!1,forcedDuration:null,ponderatorWeight:Zn.RECURSIVE_LEAF_SUM,promotesToProjectOnFirstChild:!1},[D.TASK]:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:null,ponderatorWeight:Zn.OWN_BASELINE,promotesToProjectOnFirstChild:!0},[D.MILESTONE]:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:0,ponderatorWeight:Zn.ZERO,promotesToProjectOnFirstChild:!0}};function $t(e,t){return t||Bn(e)&&Qn[e].alwaysSummary}function re(e){return e===D.MILESTONE}function pe(e){return Bn(e)&&Qn[e].promotesToProjectOnFirstChild}var to=D.PROJECT,Qe=D.TASK;function Or(e,t){return t===0?D.MILESTONE:e===0&&t>0?D.TASK:null}function pi(e,t){let r=t.getActivity(e);return r?$t(r.type,t.getChildren(e).length>0):!1}function yi(e,t,r){let i=String(t),n=r.getActivity(e);for(;n?.parentId&&String(n.parentId)!=="0";){if(String(n.parentId)===i)return!0;n=r.getActivity(n.parentId)}return!1}function eo(e,t,r){let i=pi(e,r);return pi(t,r)&&yi(e,t,r)||i&&yi(t,e,r)}function Is(e,t){let r=[],i=[e];for(;i.length>0;){let n=i.pop(),o=t.getChildren(n);if(o.length===0){String(n)!==String(e)&&r.push(n);continue}for(let a of o)i.push(a)}return r}function dp(e){let t=new Map;for(let r of e)hs(t,String(r.source),r),hs(t,String(r.target),r);return t}function hs(e,t,r){let i=e.get(t);if(i){i.push(r);return}e.set(t,[r])}function up(e,t,r,i){if(e.length<=1)return e;let n=new Set(e.map(String)),o=[];for(let a of e)fp(a,n,t,r,i)||o.push(a);return o.length>0?o:e}function fp(e,t,r,i,n){let o=String(e),a=r.getActivity(e);if(!a||a.autoScheduling===!1)return!1;let s=i.get(o)??[];for(let c of s)if(pp(c,o,a,t,r,n))return!0;return!1}function pp(e,t,r,i,n,o){if(yp(e)||!(o?String(e.source)===t:String(e.target)===t))return!1;let s=hp(e,t);if(!i.has(String(s)))return!1;let c=n.getActivity(s);return!!(c?.autoScheduling!==!1&&c&&mp(e,r,c))}function yp(e){return e.source===e.target}function hp(e,t){return String(e.source)===t?e.target:e.source}function mp(e,t,r){let i=e.lag??0,n=Math.abs(i);return String(e.target)===String(r.id)&&n<=r.durationHours||String(e.target)===String(t.id)&&n<=t.durationHours}function mi(e,t){let r=[],i=dp(e),n=0;for(let o of e){let a=pi(o.source,t),s=pi(o.target,t);if(Ip(o,a,s,t))continue;if(!a&&!s){r.push(o);continue}let c=ms(o.source,a,t,i,!0),l=ms(o.target,s,t,i,!1);n=Ep(r,c,l,o,t,n,i)}return r}function Ip(e,t,r,i){return r&&yi(e.source,e.target,i)||t&&yi(e.target,e.source,i)}function ms(e,t,r,i,n){return t?up(Is(e,r),r,i,n):[e]}function gp(e,t,r){let i=Is(e,t);if(i.length===0)return null;let n=null,o=null;for(let a of i){let s=r(a);if(!s)continue;(n===null||s.startDate<n)&&(n=s.startDate),(o===null||s.endDate>o)&&(o=s.endDate)}return n===null||o===null?null:{startDate:n,endDate:o}}function hi(e,t){return gp(e,t,r=>{let i=t.getActivity(r);return i?{startDate:i.startDate,endDate:i.endDate}:null})}function Ap(e,t,r){return e?t?r.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function vp(e,t,r,i){if(!t)return 0;let n=i.getActivity(e);return!r||!n?-t.durationHours:-i.calculateDuration({startDate:r.startDate,endDate:n.endDate,task:t})}function Cp(e,t){let r=String(e);return(t.get(r)??[]).some(n=>String(n.target)===r)}function Sp(e,t,r,i,n){if(Cp(e,n))return 0;let o=i.getActivity(e);return!t||!o||!r?0:i.calculateDuration({startDate:t,endDate:o.startDate,task:r})}function Tp(e,t){let r=t.getActivity(e.source),i=t.getActivity(e.target),n=hi(e.source,t),o=hi(e.target,t),a=e.type===H.START_TO_START||e.type===H.START_TO_FINISH,s=e.type===H.FINISH_TO_FINISH||e.type===H.START_TO_FINISH;return{source:r,sourceBounds:n,targetStart:o?.startDate??i?.startDate,userLag:e.lag??0,sourceEndpointIsStart:a,targetLag:s?-Ap(i,o,t):0,summarySourceId:e.type===H.START_TO_START&&n?e.source:void 0,finishAnchoredSummaryTargetId:s&&o?e.target:void 0}}function Ep(e,t,r,i,n,o,a){let s=Tp(i,n),{source:c,sourceBounds:l,targetStart:d,userLag:u}=s,{sourceEndpointIsStart:f,targetLag:p,summarySourceId:y,finishAnchoredSummaryTargetId:g}=s,T=o;for(let L of t){let C=f?vp(L,c,l,n):0;for(let E of r){if(String(L)===String(E))continue;let I=Sp(E,d,c,n,a);e.push(Dp(i,L,E,T,C,p,u+I,y,g??(I!==0&&p===0?i.target:void 0))),T+=1}}return T}function Dp(e,t,r,i,n,o,a,s,c){return{id:`virtual_${e.id}_${i}`,source:t,target:r,type:e.type,lag:e.lag,freeSlackHours:null,isCritical:!1,_sourceLag:n,_targetLag:o,_trueLag:a,...s===void 0?{}:{_summarySourceId:s},...c===void 0?{}:{_summaryTargetId:c}}}var Ii=class{invalidate(){}get(t,r){return mi(t,r)}};function _p(e){let t=new Map,r=i=>(t.has(i)||t.set(i,new Set),t.get(i));for(let i of e)r(i.source).add(i.id),r(i.target).add(i.id);return{neighbors:t}}function kp(e,t,r){let i=new Set,n=new Map,o=new xt;for(o.enqueue(e);!o.isEmpty();){let a=o.dequeue(),s=String(a);if(i.has(s))continue;i.add(s);let c=r.neighbors.get(a);if(c)for(let l of c){let d=t.get(l);if(!d)continue;let u=`${d.source}-${d.target}-${d.type}`;n.has(u)||n.set(u,d);let f=String(d.source)===s?d.target:d.source;i.has(String(f))||o.enqueue(f)}}return Array.from(n.values())}function gs(e,t){let r=new Map;for(let a of t)r.set(a.id,a);let i=_p(t),n=kp(e,r,i),o=new Set([String(e)]);for(let a of n)o.add(String(a.source)),o.add(String(a.target));return{activityIds:o,links:n}}var As=0,Nr=100;function Pe(e){return e===0}function vs(e,t,r){let i=r.type===H.FINISH_TO_START,n=r.type===H.FINISH_TO_FINISH;if(r._targetLag!==void 0)return{sourceLag:r._sourceLag??0,targetLag:r._targetLag,trueLag:r._trueLag??r.lag??0,isFS:i,isFF:n,isZeroDurationCase:!1};let o=r.lag??0;switch(r.type){case H.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:o,isFS:i,isFF:n,isZeroDurationCase:!1};case H.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:o,isFS:i,isFF:n,isZeroDurationCase:!1};case H.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:o,isFS:i,isFF:n,isZeroDurationCase:!1};case H.START_TO_FINISH:return{sourceLag:-e.durationHours,targetLag:-t.durationHours,trueLag:o,isFS:i,isFF:n,isZeroDurationCase:!1};default:return{sourceLag:0,targetLag:0,trueLag:o,isFS:i,isFF:n,isZeroDurationCase:!1}}}function Rp(e,t,r){if(e._summarySourceId===void 0)return null;let i=r.getActivity(e._summarySourceId);if(!i)return null;let n=hi(e._summarySourceId,r);return n?-r.calculateDuration({startDate:n.startDate,endDate:t.endDate,task:i}):null}function Pp(e,t,r,i,n){let o=t.durationHours===0&&n;return{successorStart:i.getClosestWorkTime({date:e.endDate,dir:o?"past":"future",task:t}),link:r}}function Cs(e,t,r,i){let{sourceLag:n,targetLag:o,trueLag:a,isFS:s,isFF:c}=vs(e,t,r),l=Rp(r,e,i)??n,d=l+o+a;if(!(t.durationHours===0?d!==0:l!==0||o!==0||a!==0))return Pp(e,t,r,i,s||c);let p=s?t:e,y=i.getClosestWorkTime({date:e.endDate,dir:"future",task:p});if(l!==0&&(y=i.calculateEndDate({startDate:y,durationHours:l,task:e})),o!==0&&(y=i.calculateEndDate({startDate:y,durationHours:o,task:t})),a!==0&&(y=i.calculateEndDate({startDate:y,durationHours:a,task:t})),t.durationHours===0){if(s||c)return{successorStart:i.getClosestWorkTime({date:y,dir:"past",task:t}),link:r};let g=new Date(Date.UTC(y.getUTCFullYear(),y.getUTCMonth(),y.getUTCDate()));return{successorStart:i.getClosestWorkTime({date:g,dir:"future",task:t}),link:r}}return{successorStart:i.getClosestWorkTime({date:y,dir:"future",task:t}),link:r}}function Ss(e,t,r,i){let{sourceLag:n,targetLag:o,trueLag:a}=vs(t,e,r),s=i.getClosestWorkTime({date:e.startDate,dir:"past",task:e});return a!==0&&(s=i.calculateEndDate({startDate:s,durationHours:-a,task:e})),o!==0&&(s=i.calculateEndDate({startDate:s,durationHours:-o,task:e})),n!==0&&(s=i.calculateEndDate({startDate:s,durationHours:-n,task:t})),s}function Ts(e,t,r){for(let i of e){let n=t.getActivity(i);if(!n)continue;let o=n.constraintType;if(!o||o===A.ASAP||o===A.ALAP)continue;let a=ja(n,t);!a.earliestStart&&!a.latestStart&&!a.earliestEnd&&!a.latestEnd||r.set(i,{activityId:i,startDate:n.startDate,endDate:n.endDate,drivingLinkId:null,kind:A.ASAP,conflict:!1,earliestStart:a.earliestStart,latestStart:a.latestStart,earliestEnd:a.earliestEnd,latestEnd:a.latestEnd})}}function gi(e,t,r){let i={earliestStart:t.earliestStart??null,latestStart:t.latestStart??null,earliestEnd:t.earliestEnd??null,latestEnd:t.latestEnd??null},n=t.earliestSchedulingStart??t.latestSchedulingStart??null,o;n===null?o=Wn(e.startDate,i):Ka(n,i)?o=n:o=Wn(n,i),t.startDate=o,t.endDate=r.calculateEndDate({startDate:o,durationHours:e.durationHours,task:e})}function Es(e,t){if(!e||!t)return new Date;let{constraintType:r,constraintDate:i}=e;if(!r||!i)return t;switch(r){case A.MSO:case A.MFO:return new Date(i);case A.SNET:case A.FNET:return i>t?new Date(i):t;case A.SNLT:case A.FNLT:return i<t?new Date(i):t;default:return t}}function Lp(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function Ds(e,t,r){return ro(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function ro(e,t,r){return t.dragWithMultiple&&Lp(e,r)}async function _s(e,t,r,i,n,o){let a=new Map;for(let u of t){let f=String(u.target);a.has(f)||a.set(f,[]),a.get(f).push(u)}let s=u=>{let f=o.get(u);if(f?.startDate&&f.endDate)return{startDate:f.startDate,endDate:f.endDate};let p=r.getActivity(u);return p?{startDate:p.startDate,endDate:p.endDate}:{startDate:new Date,endDate:new Date}},c=r.getFlags(),l=i.draggedIds??[],d=performance.now();for(let u of e){let f=await di(d,n);if(f.aborted)return o;d=f.newSliceStart;let p=r.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||Op(p,r))continue;let y=a.get(String(u))??[],g=null,T=null,L=!1;for(let B of y){let k=r.getActivity(B.source);if(!k)continue;let v=s(B.source),P=v.startDate.getTime()!==k.startDate.getTime()||v.endDate.getTime()!==k.endDate.getTime(),q={...k,startDate:v.startDate,endDate:v.endDate},$=Ds(q,c,l),ot={...q,startDate:$.startDate,endDate:$.endDate},it=ro(B.source,c,l)?{...B,lag:0}:B,Dt=Cs(ot,p,it,r);(!g||Dt.successorStart>g)&&(g=Dt.successorStart,T=String(B.id),L=B._summaryTargetId!==void 0&&!P&&(B._targetLag===0||i.preventSummaryTargetPullback===!0))}g!==null&&L&&g<p.startDate&&(g=new Date(p.startDate));let E=o.get(u),I=E?{...E}:{activityId:u,startDate:p.startDate,endDate:p.endDate,drivingLinkId:null,kind:A.ASAP,conflict:!1},b=I.earliestStart||I.latestStart||I.earliestEnd||I.latestEnd;if(!(!g&&!b)){if(g){let B=g;p.type===D.MILESTONE&&(B=Es(p,g)),I.drivingLinkId=T,I.startDate=B,I.endDate=r.calculateEndDate({startDate:B,durationHours:p.durationHours,task:p}),I.earliestSchedulingStart=B,I.earliestSchedulingEnd=I.endDate}else p.constraintType===A.MSO?I.earliestStart&&(I.startDate=I.earliestStart,I.endDate=I.earliestEnd??r.calculateEndDate({startDate:I.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===A.MFO&&I.latestStart&&(I.startDate=I.latestStart,I.endDate=I.latestEnd??r.calculateEndDate({startDate:I.latestStart,durationHours:p.durationHours,task:p}));gi(p,I,r),o.set(u,I)}}return o}function Op(e,t){return $t(e.type,t.getChildren(e.id).length>0)}async function ks(e,t,r,i,n,o){let a=new Map(r),s=i.getAllActivities(),c=s.length,l=[];for(let T of s)T.constraintType===A.ALAP&&l.push(T.id);if(l.length===0)return a;let d=new Map,u=new Map;for(let T of t){let L=String(T.source);d.has(L)||d.set(L,[]),d.get(L).push(T);let C=String(T.target);u.has(C)||u.set(C,[]),u.get(C).push(T)}let f=T=>{let L=a.get(T);if(L)return{startDate:L.startDate,endDate:L.endDate};let C=i.getActivity(T);return C?{startDate:C.startDate,endDate:C.endDate}:{startDate:new Date,endDate:new Date}},p=T=>!T.parentId||M(T.parentId)?i.getProjectEnd():f(T.parentId).endDate,y=(T,L)=>{let C=T,E=0;for(;C&&!M(C)&&E++<c+1;){if(String(C)===String(L))return!0;let I=i.getActivity(C);if(!I||!I.parentId)break;C=I.parentId}return!1},g=performance.now();for(let T of e){let L=await di(g,o);if(L.aborted)return a;g=L.newSliceStart;let C=i.getActivity(T);if(!C||C.constraintType!==A.ALAP||!C.autoScheduling||C.progress===100||$t(C.type,i.getChildren(T).length>0))continue;let E=p(C);if(!E)continue;let I=E,b=null,B=!1,k=d.get(String(T))??[];for(let Yt of k){if((Yt.lag??0)<0)continue;let $e=i.getActivity(Yt.target);if(!$e||$e.autoScheduling===!1)continue;let Ba=f(Yt.target),lf={...$e,startDate:Ba.startDate,endDate:Ba.endDate},ei=Ss(lf,C,Yt,i);ei<I&&(I=ei),(b===null||ei<b)&&(b=ei,B=C.parentId&&!M(C.parentId)?y(Yt.target,C.parentId):!1)}if(b!==null)if(B)I=b;else{let Yt=f(T).endDate,$e=Yt.getTime()>E.getTime()?Yt:E;I=b<$e?b:$e}else I>E&&(I=E);let P=(u.get(String(T))??[]).some(Yt=>Yt.type===H.FINISH_TO_START||Yt.type===H.FINISH_TO_FINISH),q=new Date(Date.UTC(I.getUTCFullYear(),I.getUTCMonth(),I.getUTCDate())),$=()=>i.getClosestWorkTime({date:q,dir:"past",task:C}),ot=i.getClosestWorkTime({date:I,dir:"future",task:C}).getTime()===I.getTime(),it;C.durationHours===0&&b===null?it=P&&ot?$():i.getClosestWorkTime({date:I,dir:"past",task:C}):C.durationHours===0?P?it=$():it=i.getClosestWorkTime({date:I,dir:"future",task:C}):it=i.getClosestWorkTime({date:I,dir:"future",task:C});let Dt=i.calculateEndDate({startDate:it,durationHours:-C.durationHours,task:C}),wt=a.get(T),ht=wt?{...wt}:{activityId:T,startDate:Dt,endDate:it,drivingLinkId:null,kind:A.ALAP,conflict:!1};ht.startDate=Dt,ht.endDate=it,ht.drivingLinkId=null,ht.kind=A.ALAP;let Ye=ht.earliestSchedulingStart??null;ht.earliestSchedulingStart=null,ht.earliestSchedulingEnd=null;let Ge=Ye!==null&&Ye.getTime()>Dt.getTime()?Ye:Dt;ht.latestSchedulingStart=Ge,ht.latestSchedulingEnd=Ge===Dt?it:i.calculateEndDate({startDate:Ge,durationHours:C.durationHours,task:C}),gi(C,ht,i),a.set(T,ht)}return a}var tr={warn(){},error(){}};var Np=864e5;function Qt(e){if(e.type===D.MILESTONE)return 0;let t=e.startDate?.getTime(),r=e.endDate?.getTime();return t==null||r==null||Number.isNaN(t)||Number.isNaN(r)?null:Math.floor((r-t)/Np)+1}function br(e,t){t.cancelled||t.updatedIds.length===0||e.batchUpdate(()=>{for(let r of t.updatedIds){let i=t.plans.get(r);if(!i)continue;let n=e.getLiveActivity(r);n&&(n.startDate=i.startDate,n.endDate=i.endDate,n.calendarDuration=Qt(n),e.updateActivity(r))}})}function io(e,t){let r=String(t.source),i=String(t.target);if(r===i)return!0;let n=new Map;for(let o of e){let a=String(o.source),s=String(o.target),c=n.get(a)??[];c.push(s),n.set(a,c)}return bp(n,i,r)}function Fr(e){let t=new Map,r=new Map;for(let o of e){let a=String(o.source),s=String(o.target),c=t.get(a)??[];c.push(s),t.set(a,c),r.set(a,r.get(a)??0),r.set(s,(r.get(s)??0)+1)}let i=new xt;for(let[o,a]of r)a===0&&i.enqueue(o);let n=0;for(;!i.isEmpty();){let o=i.dequeue();n+=1;for(let a of t.get(o)??[]){let s=r.get(a)-1;r.set(a,s),s===0&&i.enqueue(a)}}return n!==r.size}function bp(e,t,r){if(t===r)return!0;let i=new Set([t]),n=new xt;for(n.enqueue(t);!n.isEmpty();){let o=n.dequeue(),a=e.get(o)??[];for(let s of a){if(s===r)return!0;i.has(s)||(i.add(s),n.enqueue(s))}}return!1}function Ai(e){let t=Fp(e);for(let r of t.adjacency.keys())t.records.has(r)||wp(r,t);return t.components}function Fp(e){let t=new Map,r=new Set;for(let i of e){let n=String(i.source),o=String(i.target),a=Rs(t,n);if(Rs(t,o),n===o){r.add(n);continue}a.push(o)}return{adjacency:t,selfLooped:r,records:new Map,componentStack:[],nextIndex:0,components:[]}}function Rs(e,t){let r=e.get(t);if(r)return r;let i=[];return e.set(t,i),i}function wp(e,t){let r=[];for(r.push({node:e,record:Ps(e,t),neighborCursor:0});r.length>0;){let i=r[r.length-1];if(i===void 0)break;let n=t.adjacency.get(i.node)??[];if(i.neighborCursor<n.length){let s=n[i.neighborCursor];if(i.neighborCursor+=1,s===void 0)continue;xp(i,s,r,t);continue}r.pop();let o=r[r.length-1];o&&i.record.lowLink<o.record.lowLink&&(o.record.lowLink=i.record.lowLink),i.record.lowLink===i.record.visitIndex&&Mp(i.node,t)}}function xp(e,t,r,i){let n=i.records.get(t);if(!n){r.push({node:t,record:Ps(t,i),neighborCursor:0});return}n.onStack&&n.visitIndex<e.record.lowLink&&(e.record.lowLink=n.visitIndex)}function Ps(e,t){let r={visitIndex:t.nextIndex,lowLink:t.nextIndex,onStack:!0};return t.nextIndex+=1,t.records.set(e,r),t.componentStack.push({node:e,record:r}),r}function Mp(e,t){let r=[];for(;;){let a=t.componentStack.pop();if(a===void 0||(a.record.onStack=!1,r.push(a.node),a.node===e))break}let i=r[0],n=r.length===1&&i!==void 0&&t.selfLooped.has(i);(r.length>1||n)&&t.components.push(r)}function wr(e,t,r){let i=r?new no(e,r):e;return mi([...t],i)}var no=class{constructor(t,r){this.base=t;for(let[i,n]of r.reparented){let o=String(i),a=n===null||M(n)?null:n,s=t.getActivity(i)?.parentId??null,c=s===null||M(s)?null:String(s),l=a===null?null:String(a);if(c!==l){if(this.reparented.set(o,a),c!==null){let d=this.movedOutByParent.get(c)??new Set;d.add(o),this.movedOutByParent.set(c,d)}if(l!==null){let d=this.movedInByParent.get(l)??[];d.push(i),this.movedInByParent.set(l,d)}}}}base;reparented=new Map;movedOutByParent=new Map;movedInByParent=new Map;withOverride(t){if(!t)return null;let r=this.reparented.get(String(t.id));return r===void 0?t:{...t,parentId:r}}getActivity(t){return this.withOverride(this.base.getActivity(t))}getLiveActivity(t){return this.withOverride(this.base.getLiveActivity(t))}getAllActivities(){return this.base.getAllActivities().map(t=>this.withOverride(t)??t)}getChildren(t){let r=String(t),i=this.movedOutByParent.get(r),n=this.base.getChildren(t),o=i?n.filter(s=>!i.has(String(s))):[...n],a=this.movedInByParent.get(r);return a&&o.push(...a),o}getParent(t){let r=this.reparented.get(String(t));return r===void 0?this.base.getParent(t):r===null?null:this.getActivity(r)}isChildOf(t,r){let i=String(r),n=new Set,o=this.getActivity(t);for(;o;){let a=o.parentId;if(a===null||M(a))return!1;let s=String(a);if(s===i)return!0;if(n.has(s))return!1;n.add(s),o=this.getActivity(a)}return!1}getAllLinks(){return this.base.getAllLinks()}getAllIds(){return this.base.getAllIds()}getLink(t){return this.base.getLink(t)}activityExists(t){return this.base.activityExists(t)}getOutgoingLinkIds(t){return this.base.getOutgoingLinkIds(t)}getIncomingLinkIds(t){return this.base.getIncomingLinkIds(t)}getClosestWorkTime(t){return this.base.getClosestWorkTime(t)}calculateEndDate(t){return this.base.calculateEndDate(t)}calculateDuration(t){return this.base.calculateDuration(t)}batchUpdate(t){this.base.batchUpdate(t)}updateActivity(t){this.base.updateActivity(t)}getFlags(){return this.base.getFlags()}getProjectEnd(){return this.base.getProjectEnd()}};function Le(e){let{port:t,proposedPort:r,currentLinks:i,proposedLinks:n,proposal:o}=e,a=wr(r??t,n,o);if(!Fr(a))return{ok:!0};let s=wr(t,i),c=Ls(s),d=[...Ls(a)].filter(u=>!c.has(u));return d.length===0?{ok:!0}:{ok:!1,newlyCyclicActivityIds:d}}function Ls(e){let t=new Set;for(let r of Ai(e))for(let i of r)t.add(i);return t}function ye(e,t){switch(e.kind){case dt.CREATE:return Up(e,t);case dt.UPDATE:return xr(e,t.port);case dt.DELETE:return Bp(e,t)}}function Ci(e,t){if(e.length===0)return{applied:!0};let r=t.port.getAllLinks(),i=new Map,n=[];for(let l of r){let d=Os(l);i.has(d)||i.set(d,l.id),n.push({source:l.source,target:l.target})}let o=Fr(n),a=null;for(let{operation:l,linkId:d}of e){if(String(l.source)===String(l.target)){a={applied:!1,rejected:At.SELF_LINK};break}if(!t.port.getActivity(l.source)||!t.port.getActivity(l.target)){a={applied:!1,rejected:At.ACTIVITY_MISSING};break}if(eo(l.source,l.target,t.port)){a={applied:!1,rejected:At.HIERARCHY_LINK};break}let u=Os(l),f=i.get(u);if(f!==void 0){a={applied:!1,rejected:At.DUPLICATE,linkId:f};break}if(i.set(u,d),o&&io(n,{source:l.source,target:l.target}))return{applied:!1,rejected:At.CYCLE};n.push({source:l.source,target:l.target})}if(!o&&Fr(n))return{applied:!1,rejected:At.CYCLE};if(a)return a;let s=[...r,...e.map(({operation:l,linkId:d})=>({id:d,source:l.source,target:l.target,type:l.type,lag:l.lag,freeSlackHours:null,isCritical:!1}))];if(!Le({port:t.port,currentLinks:r,proposedLinks:s}).ok)return{applied:!1,rejected:At.CYCLE};for(let{operation:l,linkId:d}of e){let u=t.preserved?.get(d);t.port.addLink({id:d,source:l.source,target:l.target,type:l.type,lag:l.lag,freeSlackHours:null,isCritical:!1,...u?.ganttId===void 0?{}:{ganttId:u.ganttId},...u?.sectorId===void 0?{}:{sectorId:u.sectorId},...u?.proplannerId===void 0?{}:{proplannerId:u.proplannerId}})}return{applied:!0}}function Os(e){return JSON.stringify([String(e.source),String(e.target),e.type])}function Up(e,t){let{port:r}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:At.SELF_LINK};let i=r.getActivity(e.source),n=r.getActivity(e.target);if(!i||!n)return{applied:!1,rejected:At.ACTIVITY_MISSING};if(eo(e.source,e.target,r))return{applied:!1,rejected:At.HIERARCHY_LINK};let o=r.getAllLinks();for(let d of o)if(String(d.source)===String(e.source)&&String(d.target)===String(e.target)&&d.type===e.type)return{applied:!1,rejected:At.DUPLICATE,linkId:d.id};let a=o.map(d=>({source:d.source,target:d.target}));if(io(a,{source:e.source,target:e.target}))return{applied:!1,rejected:At.CYCLE};let s=(t.newLinkId??Hp)(),c={id:s,source:e.source,target:e.target,type:e.type,lag:e.lag,freeSlackHours:null,isCritical:!1};return Le({port:r,currentLinks:o,proposedLinks:[...o,c]}).ok?(r.addLink(c),{applied:!0,linkId:s}):{applied:!1,rejected:At.CYCLE}}function xr(e,t){return t.getLink(e.linkId)?(e.lag!==void 0&&t.setLinkField(e.linkId,"lag",e.lag),e.type!==void 0&&t.setLinkField(e.linkId,"type",e.type),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:At.LINK_MISSING}}function Bp(e,t){let{port:r}=t;return r.getLink(e.linkId)?(r.removeLink(e.linkId),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:At.LINK_MISSING}}var vi=null;function Hp(){return vi===null&&(vi=Date.now()),vi+=1,String(vi)}var Ct={FINISH_TO_START:"fs",START_TO_START:"ss",FINISH_TO_FINISH:"ff",START_TO_FINISH:"sf"},Si={[H.FINISH_TO_START]:Ct.FINISH_TO_START,[H.START_TO_START]:Ct.START_TO_START,[H.FINISH_TO_FINISH]:Ct.FINISH_TO_FINISH,[H.START_TO_FINISH]:Ct.START_TO_FINISH},Oe={[Ct.FINISH_TO_START]:H.FINISH_TO_START,[Ct.START_TO_START]:H.START_TO_START,[Ct.FINISH_TO_FINISH]:H.FINISH_TO_FINISH,[Ct.START_TO_FINISH]:H.START_TO_FINISH},Ns=Ct.FINISH_TO_START;function bs(e){if(e in Oe)return Oe[e]}var Fs=";",ws=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function Ti(e){let t=[],r=[],i=e.replace(/\s+/g,"");if(i.length===0)return{specs:t,errors:r};for(let n of i.split(Fs)){if(n.length===0)continue;let o=Wp(n);o?t.push(o):r.push(n)}return{specs:t,errors:r}}function Wp(e){let t=e.toLowerCase(),r=ws.exec(t);if(!r)return null;let[,i,n,o,a]=r,s=n?Oe[n]:Oe[Ns],c=0;if(a!==void 0){let l=Number(a);if(Number.isNaN(l))return null;c=o==="-"?-l:l}return{correlativeId:i,type:s,lag:c}}function Di(e){let{targetActivityId:t,currentLinks:r,desiredSpecs:i}=e,n=[],o=new Map;for(let c of i){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=Ei(l,c.type);o.has(d)||o.set(d,{source:l,type:c.type,lag:c.lag})}let a=new Map;for(let c of r)String(c.target)===String(t)&&a.set(Ei(c.source,c.type),c);let s=[];for(let[c,l]of a)o.has(c)||s.push({kind:dt.DELETE,linkId:l.id});for(let[c,l]of o){let d=a.get(c);d&&d.lag!==l.lag&&s.push({kind:dt.UPDATE,linkId:d.id,lag:l.lag})}for(let[c,l]of o)a.has(c)||s.push({kind:dt.CREATE,source:l.source,target:t,type:l.type,lag:l.lag});return{operations:s,unresolved:n}}function Ei(e,t){return`${String(e)}::${t}`}function _i(e){let{sourceActivityId:t,currentLinks:r,desiredSpecs:i}=e,n=[],o=new Map;for(let c of i){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=Ei(l,c.type);o.has(d)||o.set(d,{target:l,type:c.type,lag:c.lag})}let a=new Map;for(let c of r)String(c.source)===String(t)&&a.set(Ei(c.target,c.type),c);let s=[];for(let[c,l]of a)o.has(c)||s.push({kind:dt.DELETE,linkId:l.id});for(let[c,l]of o){let d=a.get(c);d&&d.lag!==l.lag&&s.push({kind:dt.UPDATE,linkId:d.id,lag:l.lag})}for(let[c,l]of o)a.has(c)||s.push({kind:dt.CREATE,source:t,target:l.target,type:l.type,lag:l.lag});return{operations:s,unresolved:n}}function ki(e){let t=Math.sign(e)*Math.round(Math.abs(e));return Object.is(t,-0)?0:t}function Wt(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var xs={rawInputToConstraintDate(e,t){let r=new Date(e);return r.setUTCHours(0,0,0,0),r.getTime()===e.getTime()?t.getClosestWorkTime({direction:j.FUTURE,date:e,unit:mt.HOUR}):t.isWorkTime(e,mt.HOUR)?e:r},computeLagBetweenTasks(e,t,r){return r.calculateDuration(e,t)}};function oo(e,t,r){switch(r){case H.FINISH_TO_START:return{sourceDate:e.endDate,targetDate:t.startDate};case H.START_TO_START:return{sourceDate:e.startDate,targetDate:t.startDate};case H.FINISH_TO_FINISH:return{sourceDate:e.endDate,targetDate:t.endDate};case H.START_TO_FINISH:return{sourceDate:e.startDate,targetDate:t.endDate}}}var ao=xs;var er=class{adapter;reporter;currentCalculationId=0;topoCache=new fi;expandedLinksCache=new Ii;constructor(t,r=tr){this.adapter=t,this.reporter=r}getCurrentCalculationId(){return this.currentCalculationId}invalidateTopoCache(){this.topoCache.invalidate()}invalidateExpandedLinksCache(){this.expandedLinksCache.invalidate()}invalidateAllCaches(){this.topoCache.invalidate(),this.expandedLinksCache.invalidate()}async schedule(t={}){let r=++this.currentCalculationId,i=ps(r,()=>this.currentCalculationId),n={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{Kp(this.adapter);let o=he("schedule.total"),a=he("schedule.expandParentLinks"),s=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(s,this.adapter);ie(a);let l=c;if((await Ze(i)).aborted)return{...n,cancelled:!0};let d=he("schedule.scoping"),u=this.adapter.getAllIds(),f=Yp(t,l,this.adapter),p=f.links,y=f.idSet;ie(d);let g=he("schedule.topologicalSort"),T=$p(this.topoCache,u,l,y);if(ie(g),T.hasCycles)return ie(o),{...n,cycles:[T.cycleNodes]};if((await Ze(i)).aborted)return{...n,cancelled:!0};let L=he("schedule.processConstraints"),C=new Map;if(Ts(T.ordered,this.adapter,C),ie(L),(await Ze(i)).aborted)return{...n,cancelled:!0};let E=he("schedule.asapPass"),I=await _s(T.ordered,p,this.adapter,t,i,C);if(ie(E),(await Ze(i)).aborted)return{...n,cancelled:!0};let b=he("schedule.alapPass"),B=await ks(T.reversed,p,I,this.adapter,t,i);if(ie(b),(await Ze(i)).aborted)return{...n,cancelled:!0};let k=he("schedule.diff"),v=[];for(let[P,q]of B){let $=this.adapter.getActivity(P);if(!$)continue;let ot=$.startDate.getTime()!==q.startDate.getTime(),it=$.endDate.getTime()!==q.endDate.getTime();(ot||it)&&v.push(P)}return ie(k),ie(o),{plans:B,updatedIds:v,cycles:[],cancelled:!1}}catch(o){throw this.reporter.error("[AutoScheduler] Error during scheduling",o),o}}},Vp=!1;function jp(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:Vp}function he(e){return{name:e,startedAt:performance.now()}}function Kp(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function ie(e){if(!jp())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function Yp(e,t,r){let i=e.triggerId;if(i==null)return{idSet:null,links:t};let n=gs(i,t);return Gp(n,t,r)}function Gp(e,t,r){let i=new Set(e.activityIds),n=new Set;for(let a of r.getAllActivities()){let s=String(a.id);a.constraintType===A.ALAP&&!i.has(s)&&(n.add(s),i.add(s))}if(n.size===0)return{idSet:i,links:e.links};let o=[...e.links];for(let a of t)(n.has(String(a.source))||n.has(String(a.target)))&&o.push(a);return{idSet:i,links:o}}function $p(e,t,r,i){let n=e.get(t,r);if(n.hasCycles){let a=i?Array.from(i):t;return ui(a,r)}if(!i)return n;let o=ys(n.ordered,i);return{ordered:o,reversed:[...o].reverse(),hasCycles:!1,cycleNodes:[]}}function Ms(e,t,r){let i=t.getActivity(e);if(!i)return;let n=r?{...i,endDate:r.endDate}:i,o=t.calendarReader.getCalendar(String(i.calendarId));for(let a of t.getIncomingLinkIds(e)){let s=t.getLink(a);if(!s)continue;let c=t.getActivity(s.source);if(!c||c.constraintType===A.ALAP||re(i.type)&&(s.type===H.START_TO_FINISH||s.type===H.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=oo(c,n,s.type),f=ao.computeLagBetweenTasks(d,u,o);f!==s.lag&&xr({kind:dt.UPDATE,linkId:s.id,lag:f},t)}}function Us(e,t){let r=t.getActivity(e);r&&re(r.type)&&(r.durationHours=0)}function Ri(e){let t=0,r=!1;for(let i of e)i.ponderator>0&&(t+=i.ponderator/100*i.progress,r=!0);return r?t:null}function Bs(e){return Number(e.toFixed(2))}function Mr(e){for(let t of zp(e))Ws(t,e)}function Hs(e,t){for(let r of e)Ws(r,t)}function zp(e){let t=new Set;e.forEachActivity((i,n)=>{e.getChildren(n).length>0&&t.add(n)});let r=new Map;for(let i of t)r.set(i,qp(i,e));return[...t].sort((i,n)=>(r.get(n)??0)-(r.get(i)??0))}function qp(e,t){let r=0,i=e;for(;i&&i!=="0"&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function Ws(e,t){let r=t.getChildren(e);if(r.length===0)return;let i=[];for(let n of r){let o=t.getActivity(n);o&&i.push({progress:Number(o.progress??0),ponderator:Number(o.ponderator??0)})}so(e,i,t)}function so(e,t,r){let i=r.getActivity(e);if(!i)return;let n=Ri(t);if(n===null){let o=r.getProgressFallback(e);o!==null&&r.setActivityField(e,_.PROGRESS,o);return}r.getProgressFallback(e)===null&&r.setProgressFallback(e,Number(i.progress??0)),r.setActivityField(e,_.PROGRESS,Bs(n))}function Vs(e,t,r){let i=[e];for(;i.length>0;){let n=i.pop();if(n===void 0)continue;let o=r.getChildren(n);o.length!==0&&(r.setProgressFallback(n,t),i.push(...o))}}function Nt(e,t){return(Number(e)||0)*(Number(t)||0)/100}var Ur={SKIP:"skip",FREEZE_WITHOUT_CONTRIBUTION:"freeze-when-no-contribution"};async function rr(e,t,r=!0,i={}){let n=t?Br(e,t):ey(e),o=r?i.progressMode??Ur.FREEZE_WITHOUT_CONTRIBUTION:Ur.SKIP;await Jp(n,e,o,{recomputeRealWork:i.recomputeRealWork??!1})}function Pi(e,t){js(e,t,Ur.SKIP)}async function Jp(e,t,r,i={recomputeRealWork:!1}){let o=0;for(let a of e)js(a,t,r,i.recomputeRealWork),o+=1,o%200===0&&await st()}function Br(e,t){let r=new Set,i=new Map;for(let a of t)Xp(a,e,r,i);if(r.size===0)return[];let n=Array.from(r),o=Zp(n,i);return Ks(n,o)}function Xp(e,t,r,i){let n=t.getParentId(e);for(;n&&!M(n);){if(r.has(n))return;r.add(n);let o=t.getParentId(n);i.set(n,o),n=o}}function Zp(e,t){let r=new Map;for(let i of e){if(r.has(i))continue;let n=[],o=new Set,a=i;for(;a&&!M(a)&&!r.has(a)&&!o.has(a);)n.push(a),o.add(a),a=t.get(a)??null;let s=a?r.get(a)??0:0;for(let c=n.length-1;c>=0;c-=1)s+=1,r.set(n[c],s)}return r}function Qp(e,t,r){let i=null,n=null,o=0,a=[];for(let s of e){let c=t.getActivity(s);if(!c)continue;let l=c.startDate.getTime(),d=c.endDate.getTime();(i===null||l<i)&&(i=l),(n===null||d>n)&&(n=d),r&&(o+=ty(c,t.getChildren(s).length>0)),a.push({progress:Number(c.progress??0),ponderator:Number(c.ponderator??0)})}return{minStart:i,maxEnd:n,realWorkSum:o,weightedChildren:a}}function js(e,t,r=Ur.FREEZE_WITHOUT_CONTRIBUTION,i=!1){let n=t.getActivity(e);if(!n)return;let o=t.getChildren(e);if(o.length===0)return;let a=Qp(o,t,i);if(a.minStart===null||a.maxEnd===null)return;let s=String(n.calendarId??""),c=t.calendarReader.getCalendar(s),l=new Date(a.minStart),d=new Date(a.maxEnd),u=c.calculateDuration(l,d);t.setActivityField(e,"startDate",l),t.setActivityField(e,"endDate",d),t.setActivityField(e,"durationHours",u),r!==Ur.SKIP&&so(e,a.weightedChildren,t),i&&t.setActivityField(e,"realWorkHours",a.realWorkSum)}function ty(e,t){return t?Number(e.realWorkHours)||0:Nt(e.workHours,e.progress)}function ey(e){let t=ry(e),r=iy(t,e);return Ks(t,r)}function ry(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function iy(e,t){let r=new Map;for(let i of e)r.set(i,ny(i,t));return r}function ny(e,t){let r=0,i=e;for(;i&&!M(i)&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function Ks(e,t){return[...e].sort((r,i)=>(t.get(i)??0)-(t.get(r)??0))}var Ys={updateActivityDuration:Us,updateTaskTiming:ay("updateTaskTiming"),adjustLinkLagOnTaskMove:Ms,recordLastStartDate:oy};function oy(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function me(e,t,r,i){for(let n of t){let o=n in Ys?Ys[n]:void 0;if(!o){console.warn(`[replay post-processors] unknown: ${n} \u2014 skipping. Add an entry in POST_PROCESSORS if a fixture needs it.`);continue}o(e,r,i??null)}}function ay(e){return()=>{console.debug(`[replay post-processors] ${e}: not yet ported to adapter \u2014 no-op.`)}}function K(e,t){return t!==void 0?{ok:!0,value:e,raw:t}:{ok:!0,value:e}}function J(e){return{ok:!1,reason:e}}function tt(){return{valid:!0}}function ut(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function X(){return{allowed:!0}}function nt(e,t){return t!==void 0?{allowed:!1,reason:e,alertKey:t}:{allowed:!1,reason:e}}function Q(e,t={}){return{patch:e,needsAutoSchedule:t.autoSchedule??!1,postProcessors:t.postProcessors??[],...t.cascadeMutations!==void 0?{cascadeMutations:t.cascadeMutations}:{},...t.trackingEvents!==void 0?{trackingEvents:t.trackingEvents}:{}}}var lt={PROGRESS_ENTRY:"activity_progress_entry",PROGRESS_UPDATE_RADIO_BUTTON:"activity_progress_update_radio_button",DURATION_ENTRY:"activity_duration_entry",START_DATE_ENTRY:"activity_start_date_entry",END_DATE_ENTRY:"activity_end_date_entry",NAME_ENTRY:"activity_name_entry",DESCRIPTION_ENTRY:"activity_description_entry",CALENDAR_ASSIGNMENT:"activity_calendar_assignment",COST_BUDGETED_ENTRY:"activity_cost_budgeted_entry",COST_SPENT_ENTRY:"activity_cost_spent_entry",LABOR_HOURS_BUDGETED_ENTRY:"activity_labor_hours_budgeted_entry"};var Gs={targetField:"name",canEdit(){return X()},parseInput(e){return typeof e!="string"?J("not_a_string"):K(e)},validate(){return tt()},transform(e,t){return Q({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:lt.NAME_ENTRY};var $s={targetField:"description",canEdit(){return X()},parseInput(e){return typeof e!="string"?J("not_a_string"):K(e.trim())},validate(){return tt()},transform(e,t){return Q({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:lt.DESCRIPTION_ENTRY};function zt(e){return e.constraintType??A.ASAP}var Li=100;function Ie(e){return e.progress>=Li}function ft(e,t){return $t(e.type,t.hasChildren(e.id))}function zs(e){return e.progress>0}function qs(e){return e.hasLookaheadTasks}function Ne(e,t){return Math.round(Math.ceil(e*t*60)/60)}var ir=e=>({endDate:e});var Oi="UTC";function ge(e,t){if(t){let r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=n=>Number(r.find(o=>o.type===n)?.value);return new Date(Date.UTC(i("year"),i("month")-1,i("day")))}return new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()))}function bi(e,t){if(!t||t===Oi){let f=new Date(e);return f.setUTCHours(23,59,0,0),f}let r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=f=>Number(r.find(p=>p.type===f)?.value),n=i("year"),o=i("month"),a=i("day"),s=Date.UTC(n,o-1,a,23,59,0,0),c=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(new Date(s)),l=f=>Number(c.find(p=>p.type===f)?.value),u=Date.UTC(l("year"),l("month")-1,l("day"),l("hour")===24?0:l("hour"),l("minute"),l("second"))-s;return new Date(s-u)}function sy(e,t){let r=ge(t,Oi);for(;!e.isWorkTime(r,mt.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=ge(r,Oi);return r}function co(e,t){return e.getClosestWorkTime({direction:j.FUTURE,date:t,unit:mt.HOUR})}function lo(e,t){let r=sy(e,t),i=new Date(r);return i.setUTCDate(i.getUTCDate()+1),i.setUTCHours(0,0,0,0),e.getClosestWorkTime({direction:j.PAST,date:i,unit:mt.HOUR})}var Ni=new Set([A.SNET,A.SNLT,A.MSO]),uo=new Set([A.FNET,A.FNLT,A.MFO]),Ae=new Set([A.ASAP,A.ALAP]),Fi=A.SNET;function ne(e,t,r){let i=ge(e,Oi);if(!Ni.has(r)&&!uo.has(r))return i;let n=Ni.has(r)?co(t,i):lo(t,i),o=new Date(i);return o.setUTCHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),o}var ve=()=>({constraintType:Fi});var be=e=>({constraintDate:e}),Js=e=>({constraintDate:e});var Xs={UPDATE_ACTIVITY_DURATION:"updateActivityDuration",UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var Zs={UNCHANGED:"unchanged",OUT_OF_RANGE:"out_of_range",NEGATIVE_DURATION:"negative_duration",NOT_WORKING_DAY:"not_working_day",BEFORE_PARENT_START:"before_parent_start",BEFORE_START_DATE:"before_start_date",BEFORE_DATE_ORIGIN:"before_date_origin",CONSTRAINT_VIOLATION:"constraint_violation",MISSING_ID:"missing_id",UNKNOWN_CALENDAR:"unknown_calendar"},fo={COMPLETED:"completed",SUMMARY:"summary",HAS_PROGRESS:"has_progress",HAS_LOOKAHEAD_TASKS:"has_lookahead_tasks",SIR_START_AFTER_PROGRESS:"sir_start_after_progress"};function nr(e,t,r){return Wa(e,t,r)}function or(e,t,r){return Va(e,t,r)}var tc={targetField:"durationHours",canEdit(e,t){return Ie(e)?nt("completed","cant_edit_completed_activity"):ft(e,t)?nt("summary","summary_column_value"):X()},parseInput(e,t,r){let i=parseFloat(String(e));return Number.isFinite(i)?K(Ne(i,r.hoursPerDay)):J("not_a_number")},validate(e,t,r){return Qs(r)?ut(Zs.NEGATIVE_DURATION):cy(t,r)?ut("unchanged"):tt()},transform(e,t,r){if(Qs(t))return Q({},{autoSchedule:!1,postProcessors:[]});let i=ly(e,t,r),n=dy(e,t,r,i.violated);return{...Q(n,{autoSchedule:!0,postProcessors:[Xs.RECORD_LAST_START_DATE]}),...i.violated?{constraintWarning:or(i.constraintType,i.constraintDate,ec(e,t,r)??void 0)}:{}}},trackEvent:lt.DURATION_ENTRY};function Qs(e){return Math.sign(e)===-1}function cy(e,t){return e===t}function ly(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return{violated:!1};let n=e.constraintType;if(n!==A.FNET&&n!==A.FNLT&&n!==A.MFO)return{violated:!1};let o=i.calculateEndDate(e.startDate,t);return nr(n,e.constraintDate,o)}function dy(e,t,r,i=!1){let n={};i&&Object.assign(n,ve(),be(e.startDate));let o=Or(e.durationHours,t);o&&(n.type=o),n.durationHours=t;let a=ec(e,t,r);return a&&Object.assign(n,ir(a)),n}function ec(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateEndDate(e.startDate,t):null}var ar=e=>({realWorkHours:e});var uy=0,fy=Li,rc={targetField:"progress",canEdit(e,t){return qs(e)?nt("has_lookahead_tasks","cant_edit_actvity_with_task"):ft(e,t)?nt("summary","summary_column_value"):X()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?J("not_a_number"):K(t)},validate(e,t,r){return py(r)?ut("out_of_range"):tt()},transform(e,t,r){let i=Pe(t),n=e.progress!==t&&i,o=yy(t),a=Iy(e,t,r.hierarchy),s={progress:t,autoScheduling:i,...ar(a.get(e.id)??0)},c=o?hy(e,t,i,r.hierarchy,a):[],l=o?Ay(e,t,r.hierarchy):[],d=c.length+l.length>0?[...c,...l]:void 0,u=[],f=o?Cy(e,t):void 0;return Q(s,{autoSchedule:n,postProcessors:u,cascadeMutations:d,trackingEvents:f})},trackEvent:lt.PROGRESS_ENTRY};function py(e){return e<uy||e>fy}function yy(e){return e===Li||Pe(e)}function hy(e,t,r,i,n){return i.getDescendantIds(e.id).map(a=>({activityId:a,fields:my(t,r,n.get(a)??0)}))}function my(e,t,r){return{progress:e,autoScheduling:t,...ar(r)}}function Iy(e,t,r){let i=new Map,n=a=>{let s=0;for(let c of r.getChildHhInfo(a)){let l=r.hasChildren(c.id)?n(c.id):Nt(c.workHours,t);i.set(c.id,l),s+=l}return s},o=r.hasChildren(e.id)?n(e.id):Nt(e.workHours,t);return i.set(e.id,o),i}function gy(e,t){let r=[e.id,...t.getDescendantIds(e.id)],i=o=>t.getChildProgressInfo(o).some(a=>t.hasChildren(a.id)),n=o=>t.getAncestorIds(o).length;return r.filter(o=>i(String(o))).map(String).sort((o,a)=>n(a)-n(o))}function Ay(e,t,r){let i=new Map;i.set(e.id,t);for(let a of r.getDescendantIds(e.id))i.set(a,t);let n=[...gy(e,r),...r.getAncestorIds(e.id)],o=[];for(let a of n){let s=vy(a,i,r);s!==null&&(i.set(a,s),o.push({activityId:a,fields:{progress:s}}))}return o}function vy(e,t,r){let i=r.getChildProgressInfo(e).map(o=>({progress:t.has(o.id)?t.get(o.id):o.progress,ponderator:o.ponderator??0})),n=Ri(i);return n===null?null:Number(n.toFixed(2))}function Cy(e,t){return[{name:lt.PROGRESS_UPDATE_RADIO_BUTTON,properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var ic={targetField:"cost",canEdit(e,t){return ft(e,t)?nt("summary","summary_column_value"):X()},parseInput(e){if(String(e).trim()==="")return K(0);let t=parseFloat(String(e));return Number.isNaN(t)?J("not_a_number"):K(t)},validate(){return tt()},transform(e,t,r){let i=Sy(e,t,r.hierarchy);return Q({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:lt.COST_BUDGETED_ENTRY};function Sy(e,t,r){let i=new Map;i.set(e.id,t);let n=[];for(let o of r.getAncestorIds(e.id)){let a=0;for(let s of r.getChildCostInfo(o))a+=i.has(s.id)?i.get(s.id):s.cost;i.set(o,a),n.push({activityId:o,fields:{cost:a}})}return n}var nc={targetField:"usedCost",canEdit(e,t){return ft(e,t)?nt("summary","summary_column_value"):X()},parseInput(e){if(String(e).trim()==="")return K(0);let t=parseFloat(String(e));return Number.isNaN(t)?J("not_a_number"):K(t)},validate(){return tt()},transform(e,t,r){let i=Ty(e,t,r.hierarchy);return Q({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:lt.COST_SPENT_ENTRY};function Ty(e,t,r){let i=new Map;i.set(e.id,t);let n=[];for(let o of r.getAncestorIds(e.id)){let a=0;for(let s of r.getChildUsedCostInfo(o))a+=i.has(s.id)?i.get(s.id):s.usedCost;i.set(o,a),n.push({activityId:o,fields:{usedCost:a}})}return n}var oc={targetField:"workHours",canEdit(e,t){return ft(e,t)?nt("summary","summary_column_value"):X()},parseInput(e){if(String(e).trim()==="")return K(0,e);let t=parseFloat(String(e));return Number.isNaN(t)?J("not_a_number"):K(t)},validate(){return tt()},transform(e,t,r,i){let n=ac(t,e.progress),o=String(i).trim()===""?[]:Ey(e,t,n,r.hierarchy);return Q({workHours:t,...ar(n)},{autoSchedule:!1,postProcessors:[],cascadeMutations:o})},trackEvent:lt.LABOR_HOURS_BUDGETED_ENTRY};function ac(e,t){return Nt(e,t)}function Ey(e,t,r,i){let n=new Map,o=new Map;n.set(e.id,t),o.set(e.id,r);let a=[];for(let s of i.getAncestorIds(e.id)){let c=0,l=0;for(let d of i.getChildHhInfo(s)){let u=n.has(d.id)?n.get(d.id):d.workHours,f=o.has(d.id)?o.get(d.id):d.realWorkHours??ac(d.workHours,d.progress);c+=u,l+=f}n.set(s,c),o.set(s,l),a.push({activityId:s,fields:{workHours:c,...ar(l)}})}return a}function Hr(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function po(e,t){return e.getTime()<t.getTime()}function Fe(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var wi=e=>({durationHours:e});var Dy="sir-apply",sc={targetField:"startDate",canEdit(e,t,r){return ft(e,t)?nt("summary","summary_column_value"):zs(e)?r?.eventSource!==Dy?nt("has_progress","cant_edit_activity_with_progress"):Ie(e)?nt("completed","cant_edit_completed_activity"):Fe(r.newValue)?Hr(e.startDate,r.newValue)?X():r.newValue.getTime()>e.startDate.getTime()?nt("sir_start_after_progress","sir_cant_move_start_after_progress"):X():X():X()},parseInput(e,t,r){return Fe(e)?K(ge(e,"UTC")):J("invalid_date")},validate(e,t,r,i){if(Hr(t,r))return ut("unchanged");let n=_y(e,r,i);return n||tt()},transform(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)throw new Error("startDatePipeline: no calendar resolved (integrity)");let n=co(i,t),o=e.type===D.MILESTONE,a=o?n:i.calculateEndDate(n,e.durationHours),s=n;return{...Q({startDate:n,...ir(a),...o?wi(0):{},...ve(),...be(s)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:ky(e,n,i)}},trackEvent:lt.START_DATE_ENTRY};function _y(e,t,r){let i=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!i)return null;let n=ge(i,"UTC");return t.getTime()<n.getTime()?ut("before_parent_start"):null}function ky(e,t,r){let i=r.calculateEndDate(t,e.durationHours),n=kr(zt(e),t,i),o=nr(zt(e),e.constraintDate,n);if(o.violated)return or(o.constraintType,o.constraintDate,n)}var Ry=99.999,lc={targetField:"endDate",canEdit(e,t){return ft(e,t)?nt("summary","summary_column_value"):Py(e)?nt("completed","cant_edit_completed_activity"):X()},parseInput(e,t,r){if(!Fe(e))return J("invalid_date");let i=ge(e,"UTC"),n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(i,mt.DAY)?K(lo(n,i)):K(n.getClosestWorkTime({direction:"past",date:i,unit:mt.HOUR})):K(i)},validate(e,t,r,i){if(Hr(e.endDate,r))return ut("unchanged");if(Ly(r,e))return ut("before_date_origin");if(Oy(r,e))return ut("before_start_date");let n=Ny(r,e,i);return n||tt()},transform(e,t,r){let i=by(e,t),n=Fy(e,t,r,!!i);return{...Q(n,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...i?{constraintWarning:i}:{}}},trackEvent:lt.END_DATE_ENTRY};function Py(e){return e.progress>=Ry}function Ly(e,t){return t.dateOrigin?po(e,t.dateOrigin):!1}function Oy(e,t){return po(e,t.startDate)}function Ny(e,t,r){let i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(e,mt.DAY)?null:ut("not_working_day"):null}function by(e,t){if(zt(e)===A.MSO)return;let i=kr(zt(e),e.startDate,t),n=nr(zt(e),e.constraintDate,i);if(n.violated)return or(n.constraintType,n.constraintDate,i)}function Fy(e,t,r,i=!1){let n={};re(e.type)&&!i&&cc(e)?Object.assign(n,be(e.startDate)):(i||cc(e))&&Object.assign(n,ve(),be(e.startDate));let s=wy(e,t,r),c=Or(e.durationHours,s);return c&&(n.type=c),Object.assign(n,wi(s)),n.endDate=t,n}function cc(e){return Ae.has(zt(e))}function wy(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateDuration(e.startDate,t):e.durationHours}var xy=new Set(Object.values(A)),dc={targetField:"constraintType",canEdit(e,t){return Ie(e)?nt("completed","cant_edit_completed_activity"):ft(e,t)?nt("summary","summary_column_value"):X()},parseInput(e){let t=String(e).toLowerCase();return My(t)?K(t):J("invalid_constraint_type")},validate(){return tt()},transform(e,t,r){let i=Uy(e,t,r);return Q(i,{autoSchedule:!0})}};function My(e){return xy.has(e)}function Uy(e,t,r){let i=Hy(e,t);return{constraintType:t,...Js(By(e,t,i,r))}}function By(e,t,r,i){if(e.type!==D.MILESTONE||!r)return r;let n=i.calendars.getCalendar(String(e.calendarId));return n?ne(r,n,t):r}function Hy(e,t){return Ae.has(t)?null:Ni.has(t)?e.startDate:uo.has(t)?e.endDate:e.constraintDate}var uc={targetField:"constraintDate",canEdit(e,t){return Ie(e)?nt("completed","cant_edit_completed_activity"):ft(e,t)?nt("summary","summary_column_value"):X()},parseInput(e){return Fe(e)?K(e):J("invalid_date")},validate(){return tt()},transform(e,t,r){let i=fc(e)?Fi:zt(e),n=r.calendars.getCalendar(e.calendarId);if(!n)throw new Error("constraintDatePipeline: no calendar resolved (integrity)");let o=ne(t,n,i),a=Wy(e,o);return Q(a,{autoSchedule:!0})}};function Wy(e,t){return{constraintDate:t,...fc(e)?ve():{}}}function fc(e){return Ae.has(zt(e))||!e.constraintType}var pc={targetField:"calendarId",canEdit(){return X()},parseInput(e){let t=String(e).trim();return Vy(t)?J("empty_calendar"):K(t)},validate(e,t,r,i){return jy(e.calendarId,r)?ut("unchanged"):i.calendars.getCalendar(r)?tt():ut("unknown_calendar")},transform(e,t,r){return Q(Ky(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:lt.CALENDAR_ASSIGNMENT};function Vy(e){return e===""}function jy(e,t){return e===t}function Ky(e,t,r){let i={calendarId:t,assignedDefaultCalendar:!1},n=r.calendars.getCalendar(t);if(n){let o=e.durationHours===0,a=o?Yy(e.startDate):e.startDate,s=n.getClosestWorkTime({date:a,direction:"future",unit:"hour"});if((!e.autoScheduling||o||n.getWorkHours(e.startDate).length===0)&&(i.startDate=s),!e.autoScheduling)return i;let c=i.startDate??e.startDate;Object.assign(i,ir(n.calculateEndDate(c,e.durationHours)))}return i}function Yy(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var yc={targetField:"customId",canEdit(e,t){return ft(e,t)?nt("summary","summary_column_value"):X()},parseInput(e){if(e==null)return J("empty_custom_id");if(typeof e!="string")return J("not_a_string");let t=e.trim();return t.length===0?J("empty_custom_id"):t.length>20?J("exceeds_max_length"):K(t)},validate(){return tt()},transform(e,t){return Q({customId:t},{autoSchedule:!1,postProcessors:[]})}};var hc={targetField:"subcontractId",canEdit(){return X()},parseInput(e){if(e==null)return K(null);if(typeof e=="string"){let t=e.trim();if(t.length===0)return K(null);let r=Number(t);return!Number.isFinite(r)||!Number.isInteger(r)?J("not_an_integer"):K(r)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?J("not_an_integer"):K(e):J("not_an_integer")},validate(){return tt()},transform(e,t){return Q({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function Wr(e){if(e==null)return null;if(typeof e=="object"){if(!("id"in e))return null;let t=e.id;return t==null?null:String(t)}return String(e)}function xi(e){return e.some(t=>Wr(t)===null)}var mc={targetField:"responsableIds",canEdit(){return X()},parseInput(e){return e==null?K([]):Array.isArray(e)?K(e):J("not_an_array")},validate(e,t,r){return xi(r)?ut("missing_id"):tt()},transform(e,t){let r=t.map(Wr).filter(i=>i!==null);return Q({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var Ic={targetField:"tagIds",canEdit(){return X()},parseInput(e){return e==null?K([]):Array.isArray(e)?K(e):J("not_an_array")},validate(e,t,r){return xi(r)?ut("missing_id"):tt()},transform(e,t){let r=t.map(Wr).filter(i=>i!==null);return Q({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var Gy=new Map([[_.TEXT,Gs],[_.DESCRIPTION,$s],[_.DURATION,tc],[_.PROGRESS,rc],[_.COST,ic],[_.USED_COST,nc],[_.HH_WORK_TIME,oc],[_.START_DATE,sc],[_.END_DATE,lc],[_.CONSTRAINT_TYPE,dc],[_.CONSTRAINT_DATE,uc],[_.CALENDAR_ID,pc],[_.CUSTOM_ID,yc],[_.SUBCONTRACT_ID,hc],[_.RESPONSABLES,mc],[_.TAGS,Ic]]);function Ce(e){return Gy.get(e)}var pt={APPEND:"append",REPLACE:"replace"},Mi={ACTION_BUTTON:"action-button"},Ui={SIR_AUTO_REJECT:"sir-auto-reject"},Bi={DATE_CHANGED:"date_changed",ACTIVITY_DELETED:"activity_deleted"},Hi={VIOLATION:"constraint_violation"},oe={INIT:"init",UNDO:"undo",REDO:"redo"};function sr(e,t){if(!t||t.type!==ri.CONSTRAINT)return null;let r=t.data;return!r?.constraintType||!r.constraintDate?null:{kind:Hi.VIOLATION,activityId:e,constraintType:r.constraintType,constraintDate:r.constraintDate,projectedDate:r.projectedDate??r.constraintDate,messageKey:t.messageKey}}var $y=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],gc=new Set($y);var x={ID:"id",PROPLANNER_ID:"proplannerId",PARENT:"parentId",NAME:"name",DESCRIPTION:"description",TYPE:"type",START_DATE:"startDate",END_DATE:"endDate",DURATION_HOURS:"durationHours",CONSTRAINT_TYPE:"constraintType",CONSTRAINT_DATE:"constraintDate",AUTO_SCHEDULING:"autoScheduling",CALENDAR_ID:"calendarId",ASSIGNED_DEFAULT_CALENDAR:"assignedDefaultCalendar",DATE_ORIGIN:"dateOrigin",PROGRESS:"progress",COST:"cost",USED_COST:"usedCost",REAL_COST:"realCost",WORK_HOURS:"workHours",REAL_WORK_HOURS:"realWorkHours",PONDERATOR:"ponderator",HAS_CUSTOM_PONDERATOR:"hasCustomPonderator",CORRELATIVE_ID:"correlativeId",UNIQUE_CORRELATIVE_ID:"uniqueCorrelativeId",CUSTOM_ID:"customId",SUBCONTRACT_ID:"subcontractId",IS_LOOKAHEAD:"isLookahead",HAS_LOOKAHEAD_TASKS:"hasLookaheadTasks",NEW_ACTIVITIES_ARRAY:"newActivityIds",HAS_NEW_ACTIVITIES:"hasNewActivities",IS_NEW_ACTIVITY:"isNewActivity",PENDING_REQUEST_IDS:"pendingRequestIds",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds",BASELINE_POINTS:"baselinePoints",BASELINE_SNAPSHOT:"baselineSnapshot",SUM_OF_DURATION_RECURSIVELY:"recursiveDurationHours",CALENDAR_DURATION:"calendarDuration",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath"},Vr={ID:"id",SOURCE:"source",TARGET:"target",TYPE:"type",LAG:"lag",FREE_SLACK_HOURS:"freeSlackHours",IS_CRITICAL:"isCritical",SOURCE_LAG:"_sourceLag",TARGET_LAG:"_targetLag",TRUE_LAG:"_trueLag",SUMMARY_SOURCE_ID:"_summarySourceId",SUMMARY_TARGET_ID:"_summaryTargetId",GANTT_ID:"ganttId",SECTOR_ID:"sectorId",PROPLANNER_ID:"proplannerId"};function yt(e,t,r,i){e.setActivityFieldDynamic(t,r,i)}function Ac(e,t,r,i){e.setLinkFieldDynamic(t,r,i)}function ae(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:te(e.constraintDate),dateOrigin:te(e.dateOrigin),newActivityIds:[...e.newActivityIds],pendingRequestIds:[...e.pendingRequestIds],responsableIds:[...e.responsableIds],tagIds:[...e.tagIds],baselinePoints:e.baselinePoints.map(t=>({...t,startDate:te(t.startDate),endDate:te(t.endDate)})),baselineSnapshot:zy(e.baselineSnapshot),criticalPath:qy(e.criticalPath)}}function te(e){return e===null?null:new Date(e)}function zy(e){return e===null?null:{...e,startDate:te(e.startDate),endDate:te(e.endDate)}}function qy(e){return e===null?null:{...e,earlyStart:te(e.earlyStart),earlyFinish:te(e.earlyFinish),lateStart:te(e.lateStart),lateFinish:te(e.lateFinish)}}var Sc=200;function Se(e,t){let r=new Set([String(e)]);for(let i of t.cascadeMutations??[])r.add(String(i.activityId));return r}async function rt(e,t){let r=new Map,i=0;for(let n of t){i+=1,i%Sc===0&&await st();let o=e.getActivity(n);o&&r.set(n,et(o))}return r}function et(e){return ae(e)}function Wi(e,t){let r=e.getActivity(t);return r?ae(r):null}function Te(e,t,r){vc(e,t,r.patch);for(let i of r.cascadeMutations??[])vc(e,i.activityId,i.fields)}function vc(e,t,r){for(let[i,n]of Object.entries(r)){if(!gc.has(i))throw new Error(`applyFieldChanges: column write to non-writable field "${i}"`);yt(e,t,i,n)}}async function Vi(e,t,r,i){let n=[],o=0;for(let a of r){o+=1,o%Sc===0&&await st();let s=Jy(e,t,a,i);s&&n.push(s)}return n}function Jy(e,t,r,i){let n=e.getActivity(r);if(!n)return{id:r,kind:N.DELETED,after:null};let o=t.get(r);if(!o&&i?.has(r))return Xy(r,i.get(r),n);let a=ho(o,n);return Zy(a,i,r,n),o&&Object.keys(a).length===0?null:{id:r,kind:o?N.UPDATED:N.CREATED,fields:a,after:et(n)}}function Xy(e,t,r){return t===r.correlativeId?null:{id:e,kind:N.UPDATED,fields:{correlativeId:{before:t,after:r.correlativeId}},after:et(r)}}function Zy(e,t,r,i){if(!t?.has(r)||Object.hasOwn(e,"correlativeId"))return;let n=t.get(r);n!==i.correlativeId&&(e.correlativeId={before:n,after:i.correlativeId})}function ho(e,t){let r={},i=e??{},n=t,o=new Set([...Object.keys(i),...Object.keys(n)]);o.delete(x.CALENDAR_DURATION);for(let a of o)(Object.hasOwn(i,a)!==Object.hasOwn(n,a)||!yo(i[a],n[a]))&&(r[a]={before:Cc(i[a]),after:Cc(n[a])});return r}function Cc(e){return e===null||typeof e!="object"?e:F(e)}function yo(e,t){if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e==null||t==null)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((a,s)=>yo(a,t[s]));if(typeof e!="object"||typeof t!="object")return!1;let r=e,i=t,n=Object.keys(r),o=Object.keys(i);return n.length!==o.length?!1:n.every(a=>Object.hasOwn(i,a)&&yo(r[a],i[a]))}function ji(e,t,r){let i=new Set;i.add(e);for(let n of t)i.add(n);for(let n of r)i.add(n);return i}function mo(e,t){let r=new Set;for(let i of e)r.add(String(i));for(let i of t)r.add(i);return r}function cr(e,t,r,i,n){for(let o of t){if(r.has(o.activityId)||(n.add(o.activityId),i.has(o.activityId)))continue;let a=e.getActivity(o.activityId);if(!a)continue;let s=et(a);o.before!==void 0&&(s.correlativeId=o.before),i.set(o.activityId,s)}}var Qy=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function se(e){if(e==null||e==="")throw new Error(`[parseFromBackend] expected a date string, got "${e}"`);if(e.includes("T")||e.endsWith("Z")){let s=new Date(e);if(Number.isNaN(s.getTime()))throw new Error(`[parseFromBackend] invalid ISO date "${e}"`);return s}let t=e.match(Qy);if(!t)throw new Error(`[parseFromBackend] unsupported date format "${e}" (expected "YYYY/MM/DD H:MM" or ISO)`);let[,r,i,n,o,a]=t;return new Date(Date.UTC(Number(r),Number(i)-1,Number(n),Number(o),Number(a)))}function lr(e,t,r,i){if(e.getTime()>r.getTime())return 0;if(t.getTime()<r.getTime()||e.getTime()===t.getTime())return 100;let n=i.calculateDuration(e,r),o=i.calculateDuration(e,t);return o===0?0:n*100/o}var th=e=>e.type===D.PROJECT,eh=(e,t,r)=>{let i=e.calendarId,n=i!=null?r.calendarReader.getCalendar(String(i)):null;if(!n)return 0;let o=a=>a instanceof Date?a:se(String(a));return lr(o(e.startDate),o(e.endDate),t,n)};function rh(e,t,r){let i=[],n=(a,s)=>{let c=r.getActivity(a);c&&c.expectedProgress!==s&&(r.setActivityField(a,"expectedProgress",s),i.push(String(a)))},o=a=>{let s=r.getActivity(a);if(!s)return 0;if(!th(s)){let d=eh(s,t,r);return n(a,d),d}let c=0;for(let d of r.getChildren(a)){let u=o(d),f=r.getActivity(d),p=typeof f?.ponderator=="number"?f.ponderator:0;c+=u*p}let l=c/100;return n(a,l),l};for(let a of e)o(a);return i}function xe(e,t){let r=[];e.forEachActivity((i,n)=>{i.parentId===null&&r.push(n)}),rh(r,t,e)}var ih=e=>e.type===D.PROJECT,nh=e=>kt(e),oh=(e,t,r,i)=>{let n=nh(e);if(!n)return 0;let o=(n.baseCalendarId!=null?r.getBaseCalendar(`${n.baseCalendarId}-base`):null)??(i?r.getBaseCalendar(i):null);return!o||!n.startDate||!n.endDate?0:lr(n.startDate,n.endDate,t,o)};function Io(e,t,r,i=null){let n=[],o=(s,c)=>{let l=r.getActivity(s);l&&l.expectedProgressBaseline!==c&&(r.setActivityField(s,"expectedProgressBaseline",c),n.push(s))},a=s=>{let c=r.getActivity(s);if(!c)return 0;if(!ih(c)){let u=oh(c,t,r,i);return o(s,u),u}let l=0;for(let u of r.getChildrenIds(s)){let f=a(u),p=r.getActivity(u),y=typeof p?.ponderator=="number"?p.ponderator:0;l+=f*y}let d=l/100;return o(s,d),d};for(let s of e)a(s);return n}function dr(e,t,r=null){let i={getChildrenIds:o=>e.getChildren(String(o)).map(a=>String(a)),getActivity:o=>e.getActivity(o),setActivityField:(o,a,s)=>yt(e,o,a,s),getBaseCalendar:o=>e.calendarReader.getCalendar(o)},n=[];return e.forEachActivity((o,a)=>{o.parentId===null&&n.push(a)}),Io(n,t,i,r)}var go=de.BASELINE;function Ki(e){return e===de.ACTUAL?de.ACTUAL:go}var Tc=e=>Math.round(e*100)/100;function ah(e,t){return(t===de.BASELINE?e.expectedProgressBaseline:e.expectedProgress)??void 0}function sh(e,t){let r=Tc(e),i=Tc(t);return r>99.99?_t.DONE:i>r?_t.OVERDUE:e>0&&r>i?_t.ADVANCEMENT:e===0&&t===0?_t.WAITING:e>0&&r<i?_t.DOING:_t.WAITING}function ce(e,t){let r=[];return e.forEachActivity((i,n)=>{let o=typeof i.progress=="number"?i.progress:0,a=sh(o,ah(i,t));i.status!==a&&(yt(e,n,_.STATUS,a),r.push(n))}),r}function Ao(e){let t=e instanceof Date?new Date(e.getTime()):e&&typeof e=="object"&&typeof e.valueOf=="function"?new Date(e.valueOf()):new Date(e),r=(n,o)=>a=>a===void 0?t[n]():(t[o](a),i),i={__isMomentShim:!0,clone:()=>Ao(t),hours:r("getUTCHours","setUTCHours"),minutes:r("getUTCMinutes","setUTCMinutes"),seconds:r("getUTCSeconds","setUTCSeconds"),milliseconds:r("getUTCMilliseconds","setUTCMilliseconds"),valueOf:()=>t.getTime(),toDate:()=>new Date(t.getTime()),getTime:()=>t.getTime()};return i}Ao.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var Vt=Ao;function ch(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function Yi(e){return ch(e)&&!isNaN(e.getTime())}function R(e,t,r,i){if(!Yi(new Date(t)))throw new Error(`Invalid date argument for calculateEndDate method. Date: ${t}, Activity: ${JSON.stringify(i)}`);let n=t;return e.calculateEndDate({start_date:new Date(n),duration:r,unit:"hour",task:i})}function Mt(e){if(!Yi(new Date(e.dateBaseToCalculate)))throw new Error("Invalid date argument for getClosestWorkTime method");let{dateBaseToCalculate:t,activityCalendar:r,direction:i,activity:n}=e;return r.$gantt.getClosestWorkTime({date:new Date(t),dir:i,unit:"hour",task:n})}var h=A;var U=Object.freeze({FS:Ct.FINISH_TO_START,SS:Ct.START_TO_START,FF:Ct.FINISH_TO_FINISH,SF:Ct.START_TO_FINISH});function Me(e){return Si[String(Number(e))]??Ct.START_TO_FINISH}var G=Object.freeze({FORWARD:"forward",BACKWARD:"backward"}),Ue=Object.freeze({GREATER:"greater",LESS:"less"}),qt=Object.freeze({SOURCE:"$source"});var lh=e=>e?e.$level===1:!1,dh=e=>e.type===D.PROJECT,uh=e=>e.$level!==0,fh=e=>e.type===D.TASK,ph=e=>e.type===D.TASK||e.type===D.MILESTONE,Lt={byFirstLevel:lh,filterByParentType:dh,avoidSubproject:uh,byTaskType:fh,byTaskTypeAndMilestone:ph};function Ec(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:i,linkProperty:n}=e;try{let o=yh({gantt:t,pendingParentsWithNoLinks:r});if(o.length===0)return new Set;let a=hh({gantt:t,subprojectsWithNoLinks:o}),s=mh({gantt:t,childrenIds:a,linkProperty:n,getArrayOfLinkedActivities:Ih,calculations:i});return new Set(s.map(c=>c.id))}catch(o){throw o}}function yh(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(Lt.filterByParentType).filter(i=>r.has(i.id)).map(i=>i.id)}function hh(e){let{gantt:t,subprojectsWithNoLinks:r}=e,i=new Set;for(let n of r)t.getChildren(n).filter(s=>{let c=t.getTask(s),l=Lt.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(s=>i.add(s));return[...i]}function mh(e){let{gantt:t,childrenIds:r,linkProperty:i,getArrayOfLinkedActivities:n,calculations:o}=e,a=[];for(let s of r){let c=t.getTask(s),l=c[i]||[];n({gantt:t,links:l,linkDirection:i===qt.SOURCE?"target":"source"}).every(f=>o.has(f))&&a.push(c)}return a}function Ih(e){let{gantt:t,links:r,linkDirection:i}=e,n=[];for(let o of r){let a=t.getLink(o);if(!a){`${o}`;continue}let s=Number(a[i]);n.push(s)}return n}function Dc({gantt:e,linkProperty:t,direction:r}){try{let i=gh(e,t);if(r===G.FORWARD)return{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:null};if(r===G.BACKWARD)return Ah(i,e,t)}catch(i){throw console.log("Critical Path",i),i}}function gh(e,t){return e.getTaskByTime().filter(Lt.avoidSubproject).filter(Lt.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function Ah(e,t,r){let i=[],n=new Set;return e.forEach(o=>{let a=Number(o.parent),s=t.getTask(a);s&&(s[r].length>0?n.add(o.id):s.constraint_type!==h.FNLT&&i.push(o))}),{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:n}}function _c({gantt:e,direction:t,linkProperty:r}){try{let i=vh(e),n=new Set,o=new Set,a=new Set;t===G.BACKWARD&&Th(i).forEach(d=>{n.add(d.id)});let s=Ch(i,t,r),c=Sh(i,s);return s.forEach(l=>{o.add(l.id)}),c.forEach(l=>{a.add(l.id)}),{parentsWithFullProgress:n,pendingParentsWithNoLinks:o,pendingParentsWithLinks:a}}catch(i){throw i}}function vh(e){return e.getTaskByTime().filter(Lt.filterByParentType).filter(Lt.avoidSubproject)}function Ch(e,t,r){return e.filter(i=>{let n=i[r];if(!Array.isArray(n))return!1;let o=n.length>0,a=i.constraint_type||"",s=a!==h.FNLT;if(t===G.FORWARD){let c=a!==h.SNET;return!o&&s&&c}else return!o&&s})}function Sh(e,t){let r=new Set(t.map(i=>i.id));return e.filter(i=>!r.has(i.id))}function Th(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function kc({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let i=new Set;return e.forEach(n=>{let o=t.getTask(n),a=Eh(r),s=Dh(r),c=o[a];if(!Array.isArray(c))return;_h(t,c,s).forEach(d=>{i.add(d)})}),i}catch(i){throw i}}function Eh(e){return e===G.FORWARD?qt.SOURCE:"$target"}function Dh(e){return e===G.FORWARD?"target":"source"}function _h(e,t,r){return t.map(i=>{let o=e.getLink(i)[r];return Number(o)})}var jr={identifySecondLevelActivities:Ec,identifyInitialActivities:Dc,identifyParentsWithAndWithoutLinks:_c,identifyForbiddenActivities:kc};function Gi(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function vo({linkType:e,lag:t,predecessorTime:r,activityCalendar:i,activity:n}){return e===U.FS&&t===0?Mt({predecessorTime:r,activityCalendar:i,direction:"future",activity:n}):Kr(r,e,i,n)}function Rc({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t);return{es:R(r,n,e,i),ef:n}}function Pc({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t),o=R(r,n,e,i);return{es:n,ef:o}}function Kr(e,t,r,i){if(![U.FS,U.SS,U.FF].includes(t))return e;let o=[U.FS,U.SS].includes(t)?"future":"past";return Mt({dateBaseToCalculate:e,activityCalendar:r,direction:o,activity:i})}var Co=class{constructor(t,r,i,n){if(this.linkedActivitiesData=t,this.activity=r,this.gantt=i,this.linkCandidates=n,this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`)}calculate(){let t=this.calculateLinks(),r=Gi(t),i=this.activity.constraint_type;return i===h.SNET?this.handleSNETConstraint(r):i===h.FNLT?this.handleFNLTConstraint(r):r}calculateLinks(){let t=[];for(let r of this.linkedActivitiesData){let i=r.linkType,n=Me(i),o=r.linkLag,a=r.es,s=r.ef,c=null;if(n===U.SS)c=this.calculateSSLink({lag:o,predecessorEs:a});else if(n===U.FF)c=this.calculateFFLink({lag:o,predecessorEf:s});else if(n===U.FS)c=this.calculateFSLink({lag:o,predecessorEf:s});else if(n===U.SF)c=this.calculateSFLink({lag:o,predecessorEs:a,predecessorEf:s});else continue;c&&(this.linkCandidates?.set(r.linkId,{targetId:String(this.activity.id),...c}),t.push(c))}return t}handleSNETConstraint(t){let r=Pc({duration:this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t&&t.ef>r.ef?t:r}handleFNLTConstraint(t){let r=Rc({duration:-this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t?t.ef>r.ef?r:t:r}calculateSSLink({lag:t,predecessorEs:r}){let i=vo({linkType:U.SS,lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=R(this.activityCalendar,i,t,this.activity);t>0&&(n=Kr(n,U.SS,this.activityCalendar,this.activity));let o=R(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:o}}calculateFFLink({lag:t,predecessorEf:r}){let i=vo({linkType:U.FF,lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=R(this.activityCalendar,i,t,this.activity),o=R(this.activityCalendar,n,-this.activity.duration,this.activity);return t>0&&(o=Kr(o,U.FF,this.activityCalendar,this.activity)),{es:o,ef:n}}calculateFSLink({lag:t,predecessorEf:r}){let i=r;t===0&&(i=Mt({dateBaseToCalculate:r,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let n=R(this.activityCalendar,i,t,this.activity),o=R(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:o}}calculateSFLink({lag:t,predecessorEs:r}){let i=R(this.activityCalendar,r,t,this.activity),n=R(this.activityCalendar,i,-this.activity.duration,this.activity);return t>0&&(n=Kr(n,U.SF,this.activityCalendar,this.activity)),{es:n,ef:i}}},Lc=Co;var So=class{constructor(t){this.linkedActivitiesData=t.linksWithActivityData,this.activity=t.activity,this.gantt=t.gantt}calculate(){if(this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`);let t=[];for(let r of this.linkedActivitiesData){let i=Me(r.linkType);if(r.type===D.TASK&&Number(r.progress)>0||r.type===D.PROJECT&&Number(r.progress)===100)continue;let n=r.linkLag,o=r.ls,a=r.lf;if(i===U.SS){let s={lag:n,workTime:o,lsDataCalculation:-n,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSSLink(s);t.push({ls:c,lf:l})}if(i===U.FF){let s={lag:n,workTime:a,lsDataCalculation:-this.activity.duration,lfDataCalculation:-n},{ls:c,lf:l}=this.calculateFFLink(s);t.push({ls:c,lf:l})}if(i===U.FS){let s={lag:n,workTime:o,lsDataCalculation:-this.activity.duration,lfDataCalculation:-n},{ls:c,lf:l}=this.calculateFsLink(s);t.push({ls:c,lf:l})}if(i===U.SF){let s={lag:n,workTime:a,lsDataCalculation:-n,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSFLink(s);t.push({ls:c,lf:l})}}if(this.activity.constraint_type===h.FNLT){let r=this.getMinLfFromLinks(t),i=this.calculateSfRestrictionDates();return r?this.getMinLfFromLinks([i,r]):i}else{let r=this.getMinLfFromLinks(t);if(r===!1){let i=this.gantt.getSubtaskDates();return{ls:R(this.activityCalendar,i.end_date,-this.activity.duration,this.activity),lf:i.end_date}}return r}}calculateFFLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n}){let o=null,a=null;if(t===0)return o=R(this.activityCalendar,r,n,this.activity),a=R(this.activityCalendar,o,i,this.activity),{ls:a,lf:o};let s=r;return t>0&&(s=this.getLastWorkingHour(s,this.activityCalendar,j.PAST)),o=R(this.activityCalendar,s,n,this.activity),a=R(this.activityCalendar,o,i,this.activity),{ls:a,lf:o}}calculateFsLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n,isMilestone:o=!1}){let a=null,s=null;if(t===0){let l=this.getLastWorkingHour(r,this.activityCalendar,j.PAST);return a=R(this.activityCalendar,l,n,this.activity),a=this.getLastWorkingHour(a,this.activityCalendar,j.PAST),s=R(this.activityCalendar,a,i,this.activity),{ls:s,lf:a}}let c=r;return o||(c=this.getLastWorkingHour(r,this.activityCalendar)),a=R(this.activityCalendar,c,n,this.activity),s=R(this.activityCalendar,a,i,this.activity),o||(a=this.getLastWorkingHour(a,this.activityCalendar,j.PAST)),{ls:s,lf:a}}calculateSFLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n}){let o=null,a=null,s=r;return a=R(this.activityCalendar,s,i,this.activity),o=R(this.activityCalendar,a,n,this.activity),{ls:a,lf:o}}calculateSSLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n,isMilestone:o=!1}){let a=null,s=null;if(t===0)return s=R(this.activityCalendar,r,i,this.activity),a=R(this.activityCalendar,s,n,this.activity),{ls:s,lf:a};let c=r;return t<0&&!o&&(c=this.getLastWorkingHour(c,this.activityCalendar,"future")),s=R(this.activityCalendar,c,i,this.activity),a=R(this.activityCalendar,s,n,this.activity),{ls:s,lf:a}}getMinLfFromLinks(t=[]){return t.length?t.reduce((r,i)=>i.lf<r.lf?i:r):!1}calculateSfRestrictionDates(){let t=this.activity.constraint_date,r=this.activity.duration;return{ls:R(this.activityCalendar,t,-r,this.activity),lf:t}}getLastWorkingHour(t,r,i=j.PAST){let n=t instanceof Date?t:new Date(t),o=Vt(n).clone();return this.isActivityInInitHour(r,n)&&i===j.PAST&&(o=o.hours(0).minutes(0).seconds(0).milliseconds(0)),Mt({dateBaseToCalculate:new Date(o),direction:i,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let i=r instanceof Date?r:new Date(r),o=t.getWorkHours(i)[0];if(!o||!o.includes("-"))return!1;let a=o.split("-")[0];if(!a.includes(":"))return!1;let s=a.split(":");return s.length<2?!1:(a=parseInt(s[0],10),Vt.isMoment(r)?r.hours()===a:i.getUTCHours()===a)}},Oc=So;function Nc(e){let{parent:t,linkProperty:r,linkDirection:i,calculations:n,gantt:o,direction:a,linkCandidates:s}=e,c=t[r],l=kh(t),d=null;if(a===G.FORWARD){let u=Rh(c,i,n,o);d=new Lc(u,t,o,s),d=d.calculate()}else{let u=Ph(c,i,n,o);d=new Oc({linksWithActivityData:u,activity:t,parentData:l,gantt:o}).calculate()}return d}function kh(e){return{duration:e.duration,calendarId:e.calendar_id}}function Rh(e,t,r,i){return e.length===0?[]:e.map(n=>{let o=i.getLink(n);if(!o)return console.warn(`Link not found: ${n}`),null;let a=Number(o[t]),s=r.get(a);return s?{linkId:String(o.id),es:s.es,ef:s.ef,linkLag:o.lag,linkType:o.type}:(console.warn(`Calculations not found for activity: ${a}`),null)}).filter(Boolean)}function Ph(e,t,r,i){return e.length===0?[]:e.map(n=>{let o=i.getLink(n);if(!o)return console.warn(`Link not found: ${n}`),null;let a=Number(o[t]),s=r.get(a);if(!s)return null;let c=i.getTask(a);return c?{ls:s.ls,lf:s.lf,linkLag:o.lag||0,linkType:o.type,progress:c.progress,type:c.type}:null}).filter(Boolean)}function wc(e){let{activityData:t,calculations:r,singleParents:i,direction:n}=e;if(Lh(t.id,r))return null;let o=Oh(t.id,i),a=Nh(o,r);return a.length===0?null:bh(a,n)}function Lh(e,t){return t.has(e)}function Oh(e,t){let r=t.get(e);return r?r.childrens:[]}function Nh(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function bh(e,t){if(t===G.FORWARD){let r=bc(e,"es"),i=Fc(e,"ef");return{es:r,ef:i}}else{let r=bc(e,"ls"),i=Fc(e,"lf");return{ls:r,lf:i}}}function bc(e,t){return e.reduce((r,i)=>i[t]<r[t]?i:r)[t]}function Fc(e,t){return e.reduce((r,i)=>i[t]>r[t]?i:r)[t]}var To={parentWithLinks:Nc,parentWithNoLinks:wc};var Eo=class{constructor(t){this.activity=t.activity,this.direction=t.direction,this.linkProperty=t.direction===G.FORWARD?"$target":qt.SOURCE,this.linkDirection=t.direction===G.FORWARD?"source":"target",this.calculationsOfParentThatImpactChildrens=t.calculationsOfParentThatImpactChildrens,this.calculations=t.calculations,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.parentCalculationFromChildren=t.parentCalculationFromChildren,this.linkCandidates=t.linkCandidates,this.gantt=t.gantt}handleParentWithLinks(){try{let t=this.getArrayOfIdOfLinkedActivities(this.activity[this.linkProperty]);if(this.direction===G.BACKWARD){let i=[h.FNLT];if(this.shouldCalculateParentWithLinksBackward(i)){this.calculateAndStoreParentWithLinks(this.activity);return}if(this.shouldSetDatesToParentsWithLinks(i)){this.setDatesToParentsWithLinksBackward();return}}if(this.areAllLinksCalculated(t)&&this.calculationsOfParentThatImpactChildrens.has(this.activity.id)){this.direction===G.FORWARD&&this.setDatesToParentsWithLinks(),this.direction===G.BACKWARD&&this.setDatesToParentsWithLinksBackward();return}this.calculateAndStoreParentWithLinks(this.activity)}catch(t){throw t}}shouldCalculateParentWithLinksBackward(t){let r=t.includes(this.activity.constraint_type),i=!this.calculationOfParentsFromLinks.has(this.activity.id);return r&&i}calculateAndStoreParentWithLinks(t){let r=To.parentWithLinks({parent:t,linkProperty:this.linkProperty,linkDirection:this.linkDirection,gantt:this.gantt,calculations:this.calculations,direction:this.direction,linkCandidates:this.linkCandidates});this.calculationsOfParentThatImpactChildrens.set(t.id,r),this.calculationOfParentsFromLinks.add(t.id)}areAllLinksCalculated(t){return t.every(r=>this.calculations.has(r))}shouldSetDatesToParentsWithLinks(t){let r=t.includes(this.activity.constraint_type),i=this.calculationOfParentsFromLinks.has(this.activity.id);return r&&i}handleParentWithNoLinks(){let t=To.parentWithNoLinks({activityData:this.activity,gantt:this.gantt,singleParents:this.singleParents,calculations:this.calculations,direction:this.direction});t&&this.calculations.set(this.activity.id,t)}setDatesToParentsWithLinks(){if(!this.activity)throw new Error("Error trying to get parent",{cause:{parentActivity:this.activity}});let t=this.singleParents.get(this.activity.id)?.childrens,i=Array.from(this.calculations).filter(a=>t.includes(a[0])).map(a=>a[1]),{minEs:n,maxEf:o}=i.reduce((a,{es:s,ef:c})=>({minEs:new Date(Math.min(a.minEs.getTime(),new Date(s).getTime())),maxEf:new Date(Math.max(a.maxEf.getTime(),new Date(c).getTime()))}),{minEs:new Date(i[0].es),maxEf:new Date(i[0].ef)});this.calculations.set(this.activity.id,{es:n,ef:o}),this.parentCalculationFromChildren.add(this.activity.id)}setDatesToParentsWithLinksBackward(){if(!this.activity)throw new Error("Error trying to get parent",{cause:{parentActivity:this.activity}});let t=this.singleParents.get(this.activity.id)?.childrens,i=Array.from(this.calculations).filter(a=>t.includes(a[0])).map(a=>a[1]),{minLs:n,maxLf:o}=i.reduce((a,{ls:s,lf:c})=>({minLs:new Date(Math.min(a.minLs.getTime(),new Date(s).getTime())),maxLf:new Date(Math.max(a.maxLf.getTime(),new Date(c).getTime()))}),{minLs:new Date(i[0].ls),maxLf:new Date(i[0].lf)});this.calculations.set(this.activity.id,{ls:n,lf:o})}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(i=>{let o=this.gantt.getLink(i)[r||this.linkDirection];return Number(o)})}},xc=Eo;var Do=class{constructor({gantt:t,linkProperty:r}){this.gantt=t,this.linkProperty=r,this.structureOfParents=new Map,this.singleParents=new Map}identifyThirdLevelActivities(){try{let t=this.getFirstLevelParents();for(let r of t){let i=this.processEachActivity(r),{activitiesByLevel:n}=i,o=this.getAllLevels(n),a=this.getDeepestLevel(o),s=this.createResult(r,i,a,o);this.structureOfParents.set(r.id,s)}return{structureOfParents:this.structureOfParents,singleParents:this.singleParents}}catch(t){throw t}}getFirstLevelParents(){return this.gantt.getTaskByTime().filter(Lt.byFirstLevel).filter(Lt.filterByParentType)}processEachActivity(t){let r=new Set,i=new Set,n=new Map;return this.initializeParent(t),this.gantt.eachTask(o=>{this.processActivity(o,r,i,n)},t.id),{parentsIds:r,allTasks:i,activitiesByLevel:n}}initializeParent(t){let r=Number(t.id),i=!!t[this.linkProperty]?.length,n=t.$level;this.singleParents.set(r,{level:n,hasLink:i,childrens:[]})}processActivity(t,r,i,n){let o=Number(t.id),a=Number(t.parent);i.add(o),this.isProjectActivity(t)&&this.addParentInfo(t,r);let c=this.doesParentExist(a);a!=null&&c&&this.addChildToParent(a,o),this.addActivityToLevel(t,n)}isProjectActivity(t){return t.type===D.PROJECT}hasLink(t){return!!t[this.linkProperty]?.length}addParentInfo(t,r){let i=Number(t.id),n=t.$level,o=this.hasLink(t),a={level:n,hasLink:o,childrens:[]};r.add(i),this.singleParents.set(i,a)}doesParentExist(t){return this.singleParents.has(t)}addChildToParent(t,r){this.singleParents.get(t).childrens.push(r)}addActivityToLevel(t,r){let i=t.$level,n=Number(t.parent);r.has(i)||r.set(i,new Map);let o=r.get(i);o.has(n)||o.set(n,[]),o.get(n).push({id:Number(t.id),isParent:this.isProjectActivity(t),calculated:!1})}getAllLevels(t){return new Set(t.keys())}getDeepestLevel(t){return t.size===0?0:Math.max(...t)}createResult(t,r,i,n){let{activitiesByLevel:o,parentsIds:a,allTasks:s}=r;return{parent:t.id,isALinkedParent:this.hasLink(t),levels:n,allParentChildrens:a,allChildrens:s,childrensByLevel:o,currentResolutionLevel:i,canBeCalculated:!1}}},Mc=Do;var _o=class{constructor(t,r){this.direction=r,this.gantt=t,this.linkProperty=this.direction===G.FORWARD?"$target":qt.SOURCE,this.linkDirection=this.direction===G.FORWARD?"source":"target",this.projectDates=t.getSubtaskDates()}tryToCalculateLastLevelChildrens(){this.structureOfParents.forEach(t=>{let{currentResolutionLevel:r,childrensByLevel:i,isALinkedParent:n}=t;if(n)return;let o=i.get(r);for(let[a,s]of o)if(s.filter(l=>!this.calculations.has(l.id)).length===0){let l=this.gantt.getTask(a);this.calculateParentWithNoLinks(l,s);return}})}initActivitiesWaitingForCalculation(){try{this.gantt.getTaskByTime().filter(Lt.avoidSubproject).forEach(t=>{this.activitiesWaitingForCalculation.add(t.id)})}catch(t){throw t}}identifyParentsWithAndWithoutLinks(){try{let{parentsWithFullProgress:t,pendingParentsWithNoLinks:r,pendingParentsWithLinks:i}=jr.identifyParentsWithAndWithoutLinks({gantt:this.gantt,direction:this.direction,linkProperty:this.linkProperty});this.parentsWithFullProgress=t,this.pendingParentsWithNoLinks=r,this.pendingParentsWithLinks=i}catch(t){throw t}}identifyForbiddenActivitiesLinkedToParentsWithLinks(){try{this.forbiddenActivitiesLinkedToParentsWithLinks=jr.identifyForbiddenActivities({pendingParentsWithLinks:this.pendingParentsWithLinks,gantt:this.gantt,direction:this.direction})}catch(t){throw t}}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(i=>{let o=this.gantt.getLink(i)[r||this.linkDirection];return Number(o)})}async identifyThirdLevelActivities(){try{let{structureOfParents:t,singleParents:r}=new Mc({gantt:this.gantt,linkProperty:this.linkProperty}).identifyThirdLevelActivities();this.structureOfParents=t,this.singleParents=r}catch(t){throw t}}processEachActivity(t){let r=new Set,i=new Set,n=new Map,o=new Map;return this.singleParents.set(Number(t.id),{level:t.$level,hasLink:!!t[this.linkProperty].length,childrens:[]}),new Promise((a,s)=>{this.gantt.eachTask(function(c){let l=Number(c.parent);if(i.add(c.id),c.type===D.PROJECT){let u={level:c.$level,hasLink:!!c[this.linkProperty].length,childrens:[]};r.add(c.id),this.singleParents.set(Number(c.id),u)}l&&this.singleParents.has(l)&&this.singleParents.get(l).childrens.push(c.id),n.has(c.$level)||n.set(c.$level,new Map);let d=n.get(c.$level);d.has(Number(c.parent))||d.set(Number(c.parent),[]),d.get(Number(c.parent)).push({id:c.id,isParent:c.type===D.PROJECT,calculated:!1})}.bind(this),t.id),a({parentsIds:r,allTasks:i,activitiesByLevel:n,singleParents:o})})}identifySecondLevelActivities(){try{let t=jr.identifySecondLevelActivities({gantt:this.gantt,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,calculations:this.calculations,linkProperty:this.linkProperty});this.secondLevelActivities=new Set([...this.secondLevelActivities,...t])}catch(t){throw t}}identifyInitialActivities(){try{let{chainStartActivities:t,activitiesStartChainButChildrenOfLinkedParents:r}=jr.identifyInitialActivities({gantt:this.gantt,linkProperty:this.linkProperty,direction:this.direction});this.chainStartActivities=t,r&&(this.activitiesStartChainButChildrenOfLinkedParents=r)}catch(t){throw new Error("Error in identifyInitialActivities",{cause:t})}}calculateSecondLevelActivities(){try{this.direction===G.FORWARD?this.recursiveCalculateEfAndEs(Array.from(this.secondLevelActivities),0,"secondLevel"):this.recursiveCalculateLfAndLs(Array.from(this.secondLevelActivities))}catch(t){throw t}}calculateStartAndFinishOfActivitiesThatStartChain(){try{this.chainStartActivities.forEach(t=>{if(!t||t.progress>100||t.type===D.PROJECT)return;let r=this.calculateStartAndFinishOfChainOrigin(t,this.direction);if(this.direction===G.FORWARD){let{es:i,ef:n}=r;this.calculations.set(t.id,{es:i,ef:n,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}else{let{ls:i,lf:n}=r;this.calculations.set(t.id,{ls:i,lf:n,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}})}catch(t){throw t}}buildDependencyGraph(t){let r=new Map,i=new Set(this.calculations.keys()),n=new Map;return t.forEach(o=>{o&&n.set(o.id,o)}),n.forEach((o,a)=>{if(i.has(a))return;let s=[];(o[this.linkDirection]||[]).forEach(l=>{let d=this.gantt.getLink(l);if(d){let u=Number(d[this.linkProperty]);s.push(u)}}),s=s.filter(l=>n.has(l)||i.has(l)),r.set(a,s)}),{graph:r,activityMap:n,calculatedActivities:i}}topologicalSort(t,r){let i=new Set,n=new Set,o=[],a=s=>{if(n.has(s))throw new Error("Cyclical dependency detected",{cause:{nodeId:s}});if(!i.has(s)&&!r.has(s)){n.add(s);let c=t.get(s)||[];for(let l of c)a(l);n.delete(s),i.add(s),o.push(s)}};for(let s of t.keys())!i.has(s)&&!r.has(s)&&a(s);return o.reverse()}calculateStartAndFinishOfChainOrigin(t=null,r=null){try{let i=t,n=Number(i.progress);n==="0.00"&&(n=0);let o=this.gantt.getCalendar(i.calendar_id);if(!o)throw new Error(`Error trying to get calendar with id: ${i.calendar_id}`);if((r||this.direction)===G.FORWARD){let s=i.start_date,c=i.end_date;return{es:s,ef:c}}else{if(n>=100)return{ls:Vt(i.start_date).clone(),lf:Vt(i.end_date).clone()};if(n===0)return this.calculateBackwardWhenZeroProgress(i,o);if(n<100&&n>0)return this.calculateWhenProgressIsBetweenZeroAndOneHundred(i,o)}}catch(i){throw i}}calculateBackwardWhenZeroProgress(t,r){let i=Vt(t.start_date).clone(),n=Vt(t.end_date).clone(),o=t.duration,a=[h.ASAP,h.ALAP,h.SNET,h.FNET],s=t.constraint_type||h.ASAP;if(a.includes(s))n=this.projectDates.end_date,i=R(r,n,-o,t);else{let c=[h.SNLT,h.MSO],l=[h.FNLT,h.MFO];c.includes(s)&&(i=t.constraint_date,n=R(r,i,o,t)),l.includes(s)&&(n=t.constraint_date,i=R(r,n,-o,t))}return{ls:i,lf:n}}calculateWhenProgressIsBetweenZeroAndOneHundred(t){let r=t.start_date,i=null,n=t.constraint_type||h.ASAP,o=this.projectDates.end_date,a=[h.ASAP,h.ALAP,h.SNET,h.FNET],s=[h.SNLT,h.FNLT];if(a.includes(n))i=Math.max(t.end_date,o);else if(n===h.MSO)i=t.end_date;else if(n===h.MFO||s.includes(n)){let c=Math.min(o,t.constraint_date);i=Math.max(c,t.end_date)}return{ls:r,lf:new Date(i)}}initializeActivitiesWithFullProgress(){try{Array.from(this.activitiesWaitingForCalculation).filter(i=>Number(this.gantt.getTask(i).progress)===100).map(i=>this.gantt.getTask(i)).forEach(i=>{let n=i.type===D.PROJECT;this.setDatesForActivityWithFullProgress(i),this.activitiesWaitingForCalculation.delete(i.id),n&&this.pendingParentsWithLinks.has(i.id)&&(this.parentCalculationFromChildren.add(i.id),this.calculationsOfParentThatImpactChildrens.set(i.id,{[this.direction===G.FORWARD?"es":"ls"]:i.start_date,[this.direction===G.FORWARD?"ef":"lf"]:i.end_date}),this.calculationOfParentsFromLinks.add(i.id))})}catch(t){throw t}}doCalculationForParentType(t){let r=new xc({activity:t,direction:this.direction,calculationsOfParentThatImpactChildrens:this.calculationsOfParentThatImpactChildrens,calculations:this.calculations,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,parentCalculationFromChildren:this.parentCalculationFromChildren,linkCandidates:this.linkCandidates,gantt:this.gantt});this.pendingParentsWithLinks.has(t.id)?r.handleParentWithLinks():r.handleParentWithNoLinks()}},Ee=_o;function Fh(e,t,r){let i={es:null,ef:null};if(!e)return i;if([h.SNET,h.SNLT].includes(t)){let n=new Date(e.constraint_date);i.es=n,i.ef=R(r,n,e.duration,e)}else if([h.FNLT,h.FNET].includes(t)){let n=new Date(e.constraint_date);i.es=R(r,n,-e.duration,e),i.ef=n}else if(t===h.MSO){let n=new Date(e.constraint_date);i.es=n,i.ef=R(r,n,e.duration,e)}else if(t===h.MFO){let n=new Date(e.constraint_date);i.es=R(r,n,-e.duration,e),i.ef=n}return i}var $i=Fh;var ko=class{constructor(t){this.referenceActivity=t.activity,this.activityToCalculate=null,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.alapMap=t.calculatedAlapsMap,this.parentsWithLinks=t.parentsWithLinks,this.parentsCalculations=t.parentsCalculations,this.gantt=t.ganttInstance,this.linkCandidates=t.linkCandidates}getEsAndEfFromPreviousCalculatedActivities(t){return this.alapMap.has(t)?this.alapMap.get(Number(t)):this.calculatedActivities.get(Number(t))}calculateSucessorTimes(t,r,i=0,n,o=U.FS){let a=this.gantt.getCalendar(this.referenceActivity.calendar_id);if(!a)throw new Error(`Error trying to get calendar with id: ${this.referenceActivity.calendar_id}`);let s=t,c=null,l=null,d=this.referenceActivity.type===D.MILESTONE;return d||(o===U.FS&&n===0?s=Mt({dateBaseToCalculate:s,activityCalendar:a,direction:"future",activity:this.referenceActivity}):s=this.mutateTheDateToFutureOrPastInBaseRestriction(t,o,a)),[U.FF,U.SF].includes(o)?(l=R(a,s,i,this.referenceActivity),c=R(a,l,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,o,a))):(c=R(a,s,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,o,a)),l=R(a,c,i,this.referenceActivity)),{es:c,ef:l}}calculateSS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,o=this.referenceActivity.duration,a=t.lag||0;return this.calculateSucessorTimes(r.es,i,o,a,U.SS)}calculateFF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,o=t.lag||0,a=t.lag||0;return this.calculateSucessorTimes(r.ef,n,o,a,U.FF)}calculateFS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,o=this.referenceActivity.duration,a=t.lag||0;return this.calculateSucessorTimes(r.ef,i,o,a,U.FS)}calculateSF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,o=t.lag||0,a=t.lag||0;return this.calculateSucessorTimes(r.es,n,o,a,U.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,r,i){if(![U.FS,U.SS,U.FF].includes(r))return t;let o=[U.FS,U.SS].includes(r)?"future":j.PAST;return Mt({dateBaseToCalculate:t,activityCalendar:i,direction:o,activity:this.referenceActivity})}},Uc=ko;var Yr=class extends Uc{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Ee(this.gantt,"forward").calculateStartAndFinishOfChainOrigin(this.referenceActivity);let t=this.links.map(i=>{let n=this.gantt.getLink(i);if(!n)throw new Error("Link data not found",{cause:{linkId:i}});let o=this.calculateLink(n);return this.linkCandidates?.set(String(n.id),{targetId:String(this.referenceActivity.id),...o}),o}),r=Number(this.referenceActivity.parent);if(this.parentsWithLinks.has(r)){let i=this.gantt.getCalendar(this.referenceActivity.calendar_id),n=this.parentsCalculations.get(r).es,o=R(i,n,this.referenceActivity.duration,this.referenceActivity);t.push({es:n,ef:o})}return Gi(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var Ro=class{constructor(t){this.gantt=t.gantt,this.direction=t.direction,this.pendingParentsWithNoLinks=t.pendingParentsWithNoLinks,this.pendingParentsWithLinks=t.pendingParentsWithLinks,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.calculations=t.calculations,this.activitiesStartChainButChildrenOfLinkedParents=t.activitiesStartChainButChildrenOfLinkedParents,this.linkProperty=t.linkProperty,this.linkDirection=t.linkDirection}checkActivitiesThatNowCanBeCalculated(t){let r=new Set,i=new Set(t);for(let n of t){let o=this.gantt.getTask(n);o.type===D.PROJECT?this.handleProjectActivity(n,o,r,i):this.handleNonProjectActivity(n,o,r,i)}return{activitiesThatCanBeCalculated:r,pendingActivities:i}}handleProjectActivity(t,r,i,n){let o=this.pendingParentsWithNoLinks.has(t),a=this.pendingParentsWithLinks.has(t),s=this.calculationOfParentsFromLinks.has(t);if(o){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(i.add(t),n.delete(t));return}if(a&&s){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(i.add(t),n.delete(t));return}a&&!s&&this.canCalculateParentActivity(r)&&(i.add(t),n.delete(t))}canCalculateParentActivity(t){let r=(t[this.linkProperty]||[]).length===0,i=t.constraint_type;return(this.direction===G.FORWARD?i===h.FNLT||i===h.SNLT:i===h.FNLT)&&r?!0:this.getArrayOfLinkedActivities(t[this.linkProperty]).every(a=>this.calculations.has(a))}handleNonProjectActivity(t,r,i,n){let o=Number(r.parent),a=this.pendingParentsWithLinks.has(o),s=this.calculationOfParentsFromLinks.has(o);if(a&&!s||this.direction===G.BACKWARD&&this.activitiesStartChainButChildrenOfLinkedParents.has(t)&&!s)return;if(r.$target.length===0&&r[qt.SOURCE].length===0){i.add(t),n.delete(t);return}let c=this.getLinkedActivities(r[this.linkProperty]),l=c.every(d=>this.calculations.has(d.id));if(this.direction===G.BACKWARD&&(c.length===0||l)&&s){i.add(t),n.delete(t);return}l&&(i.add(t),n.delete(t))}getLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let i of t){let n=this.gantt.getLink(i);if(!n)continue;let o=n[this.linkDirection],a=this.gantt.getTask(o);a&&r.push(a)}return r}getArrayOfLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let i of t){let n=this.gantt.getLink(i);n&&r.push(Number(n[this.linkDirection]))}return r}},zi=Ro;var Po=(e,t)=>()=>t()===e;var Lo=e=>!e?.fullyParsed;var wh=16,Be=async e=>performance.now()-e>wh?(await st(),performance.now()):e;var Gr=async({pending:e,activityCalculator:t,calculateFn:r,shouldKeepPending:i,isCalculated:n,onActivityProcessed:o,isCurrent:a})=>{let s=new Set(e),c=performance.now();for(;s.size>0;){if(!a())return;c=await Be(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(s);if(l.size===0)break;for(let u of l){if(!a())return;c=await Be(c),r([u])}for(let u of l){if(!a())return;i(u)&&d.add(u),o(u),n(u)&&d.delete(u)}s=d}};var Oo=class extends Ee{constructor(t){super(t,G.FORWARD),this.gantt=t,this.chainStartActivities=new Set,this.secondLevelActivities=new Set,this.pendingParentsWithLinks=new Set,this.pendingParentsWithNoLinks=new Set,this.structureOfParents=new Map,this.singleParents=new Map,this.calculations=new Map,this.calculationsOfParentThatImpactChildrens=new Map,this.alapMap=new Map,this.activitiesWaitingForCalculation=new Set,this.constraintsMap=new Map,this.totalFloatSnltFnlt=new Map,this.totalFloatForMsoMfo=new Map,this.totalFloatForAsap=new Map,this.linkCandidates=new Map,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateEfAndEs(t))))))}async iterativeCalculateEfAndEs(t){let r=new zi({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await Gr({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:i=>this.calculateStartAndFinishTimes(i),shouldKeepPending:i=>this.calculationOfParentsFromLinks.has(i)&&!this.calculations.has(i),isCalculated:i=>this.calculations.has(i),onActivityProcessed:i=>this.activitiesWaitingForCalculation.delete(i),isCurrent:t})}calculateStartAndFinishTimes(t){t.forEach(r=>{let i=this.gantt.getTask(r);if(i.type===D.PROJECT)return this.doCalculationForParentType(i);if(!i)throw new Error("Error trying to get activity",{cause:{activityId:r}});let n=i.$target,o=i.constraint_type||h.ASAP,a=[h.SNET,h.SNLT,h.FNLT,h.FNET],s=[h.ASAP,h.ALAP,h.SNET,h.FNET,h.SNLT,h.FNLT],c=this.gantt.getCalendar(i.calendar_id);if(!c)throw new Error(`Error trying to get calendar with id: ${i.calendar_id}`);let l=Number(i.progress),d=null,u=null,f=null;if(l===100){this.setDatesForActivityWithFullProgress(i);return}l>0&&s.includes(o)?({es:d,ef:u}=this.getDatesForActivityWithZeroProgress(i),f=new Yr({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:o,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),o===h.ASAP&&this.totalFloatForAsap.set(r,{es:f.es,ef:f.ef,text:i.text})):{es:d,ef:u}=new Yr({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:o,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),o===h.ALAP&&this.alapMap.set(r,{es:i.start_date,ef:i.end_date,text:i.text});let p=$i(i,o,c);if(a.includes(o)&&(this.constraintsMap.set(r,p),this.totalFloatSnltFnlt.set(r,{es:d,ef:u}),{es:d,ef:u}=this.recalculateInBaseConstraint(o,p,{es:d,ef:u})),[h.MSO,h.MFO].includes(o))if(this.totalFloatForMsoMfo.set(r,{es:d,ef:u}),this.constraintsMap.set(r,p),i.progress===0)d=p.es,u=p.ef;else{let y=i.end_date;o===h.MFO&&(y=Math.max(p.ef,i.end_date)),d=i.start_date,u=y}this.calculations.set(r,{es:d,ef:u}),this.activitiesWaitingForCalculation.delete(r)})}getTheGreatesDateBetweenRestrictionAndEsEf(t,r,i=Ue.GREATER){if(i===Ue.GREATER)return r.ef>t.ef?r:t;if(i===Ue.LESS)return r.ef<t.ef?r:t}setDatesForActivityWithFullProgress(t){this.calculations.set(t.id,{es:t.start_date,ef:t.end_date})}getDatesForActivityWithZeroProgress(t){return{es:t.start_date,ef:t.end_date}}recalculateInBaseConstraint(t,r,i){let n=[h.SNET,h.FNET].includes(t)?Ue.GREATER:Ue.LESS,{es:o,ef:a}=this.getTheGreatesDateBetweenRestrictionAndEsEf(r,i,n);return{es:o,ef:a}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let i=this.gantt.getLink(r);if(!i)throw new Error("Error trying to get link",{cause:{linkId:r}});let n=i.source,o=i.target;if(!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type===D.PROJECT)&&!(!this.gantt.getTask(o)||this.gantt.getTask(o)?.type===D.PROJECT))return r}).filter(Boolean)}},Bc=Oo;var No=class{constructor(t){this.activity=t.activity,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.forwardPathCalculations=t.calculatedForwardActivitiesMap,this.gantt=t.ganttInstance}getForwardOrBackwardCalculations(t,r=null){return r===h.ALAP?this.forwardPathCalculations.get(t):this.calculatedActivities.get(t)}calculateSuccessorTimes(t,r,i=0,n,o=U.FS){let a=this.gantt.getCalendar(this.activity.calendar_id);if(!a)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`);let s=t,c=this.activity.type===D.MILESTONE;if(c&&n===0){let d=R(a,s,r,this.activity),u=R(a,d,i,this.activity);return{ls:d,lf:u}}let l={lag:n,workTime:s,activityCalendar:a,lsDataCalculation:r,lfDataCalculation:i,isMilestone:c};if(o===U.FS){let{ls:d,lf:u}=this.calculateFsLink(l);return{ls:d,lf:u}}if(o===U.FF){let{ls:d,lf:u}=this.calculateFFLink(l);return{ls:d,lf:u}}if(o===U.SS){let{ls:d,lf:u}=this.calculateSSlink(l);return{ls:d,lf:u}}if(o===U.SF){let{ls:d,lf:u}=this.calculateSFLink(l);return{ls:d,lf:u}}}calculateSS(t,r=!1){let i=this.getValueForSS(t,r),n=-t.lag||0,o=this.activity.duration,a=t.lag;return this.calculateSuccessorTimes(i,n,o,a,U.SS)}calculateFF(t,r){let i=this.getForwardOrBackwardCalculations(Number(t.target)),n=r===h.ALAP?"ef":"lf",o=i[n],a=-this.activity.duration,s=-t.lag||0,c=t.lag;return this.calculateSuccessorTimes(o,a,s,c,U.FF)}calculateFS(t,r){let i="ls";i=r===h.ALAP?"es":"ls";let n=this.getForwardOrBackwardCalculations(Number(t.target),r),o=-this.activity.duration,a=t.lag||0,s=-t.lag||0;return this.calculateSuccessorTimes(n[i],o,s,a,U.FS)}calculateSF(t,r=!1){let i=r?this.getEarlyStartFromForwardPath(Number(t.target)).ef:this.getForwardOrBackwardCalculations(Number(t.target)).lf,n=-t.lag||0,o=this.activity.duration,a=t.lag;return this.calculateSuccessorTimes(i,n,o,a,U.SF)}getEarlyStartFromForwardPath(t){return this.forwardPathCalculations.get(t)}getValueForSS(t,r){return r?this.getEarlyStartFromForwardPath(Number(t.target)).es:this.getForwardOrBackwardCalculations(Number(t.target))["ls"]}calculateDate(t,r,i){let n=Vt(r).clone();return R(t,new Date(n),i,this.activity)}getLastWorkingHour(t,r,i=j.PAST){let n=t instanceof Date?t:new Date(t),o=Vt(n).clone();return this.isActivityInInitHour(r,n)&&i===j.PAST&&(o=o.hours(0).minutes(0).seconds(0).milliseconds(0)),Mt({dateBaseToCalculate:new Date(o),direction:i,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let i=r instanceof Date?r:new Date(r),o=t.getWorkHours(i)[0];if(!o||!o.includes("-"))return!1;let a=o.split("-")[0];if(!a.includes(":"))return!1;let s=a.split(":");return s.length<2?!1:(a=parseInt(s[0],10),Vt.isMoment(r)?r.hours()===a:i.getUTCHours()===a)}calculateFsLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:o,isMilestone:a=!1}){let s=null,c=null;if(t===0){let d=this.getLastWorkingHour(r,i,j.PAST);return s=R(i,d,o,this.activity),s=this.getLastWorkingHour(s,i,j.PAST),c=R(i,s,n,this.activity),{ls:c,lf:s}}let l=r;return a||(l=this.getLastWorkingHour(r,i)),s=R(i,l,o,this.activity),c=R(i,s,n,this.activity),a||(s=this.getLastWorkingHour(s,i,j.PAST,!0)),{ls:c,lf:s}}calculateFFLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:o}){let a=null,s=null;if(t===0)return a=R(i,r,o,this.activity),s=R(i,a,n,this.activity),{ls:s,lf:a};let c=r;return t>0&&(c=this.getLastWorkingHour(c,i,j.PAST)),a=R(i,c,o,this.activity),s=R(i,a,n,this.activity),{ls:s,lf:a}}calculateSSlink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:o,isMilestone:a=!1}){let s=null,c=null;if(t===0)return c=R(i,r,n,this.activity),s=R(i,c,o,this.activity),{ls:c,lf:s};let l=r;return t<0&&!a&&(l=this.getLastWorkingHour(l,i,"future")),c=R(i,l,n,this.activity),s=R(i,c,o,this.activity),{ls:c,lf:s}}calculateSFLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:o}){let a=null,s=null;return t===0?(s=R(i,r,n),a=R(i,s,o,this.activity),{ls:s,lf:a}):(s=R(i,r,n,this.activity),a=R(i,s,o,this.activity),{ls:s,lf:a})}},Hc=No;var bo=class extends Hc{constructor(t){super(t),this.constraint=t.constraint||h.ASAP,this.parentsWithFullProgress=t.parentsWithFullProgress,this.parentsThatImpactChildrens=t.parentsThatImpactChildrens,this.projectDates=this.gantt.getSubtaskDates()}calculate(){if(this.links.length===0)return new Ee(this.gantt,G.BACKWARD).calculateStartAndFinishOfChainOrigin(this.activity);let t=this.activity.progress>0&&this.activity.progress<100,r=this.gantt.getTask(this.activity.parent),i=!1;r&&(i=this.parentsThatImpactChildrens.has(Number(this.activity.parent)));let n=this.links.map(a=>{let s=this.gantt.getLink(a);if(!s)throw new Error("Link not found",{cause:{linkId:a}});if(!this.parentsWithFullProgress.has(Number(s.target)))return this.calculateLink(s)}).filter(a=>a);if(n.length!==0){let a=this.getMinLfFromLinks(n);if(n.push(this.calculateTheLsAndLfForTheActivity()),i){let d=this.parentsThatImpactChildrens.get(Number(this.activity.parent));n.push(this.calculateTheLsAndLfForTheActivity(d))}let s=this.getMinDateFromLinks(n),c=s.ls,l=s.lf;return t&&(c=this.activity.start_date,l=this.getMinCalculationLogic(s)),{ls:c,lf:l,minFromLinks:a}}if(i){n.push(this.calculateTheLsAndLfForTheActivity());let s=this.parentsThatImpactChildrens.get(Number(this.activity.parent)).lf,c=R(this.gantt.getCalendar(this.activity.calendar_id),s,-this.activity.duration,this.activity);n.push({ls:c,lf:s});let l=this.getMinDateFromLinks(n);return{ls:l.ls,lf:l.lf,minFromLinks:l}}let o=this.calculateTheLsAndLfForTheActivity();return{ls:o.ls,lf:o.lf,minFromLinks:o}}calculateTheLsAndLfForTheActivity(t=null){try{let r=this.activity.duration,i=this.gantt.getCalendar(this.activity.calendar_id);if(!i)throw new Error(`Calendar not found with id ${this.activity.calendar_id}`);let n=t?t.lf:this.projectDates.end_date;if(!n)throw new Error("End date not found for activity",{cause:{activityId:this.activity.id}});return{ls:R(i,n,-r,this.activity),lf:n}}catch(r){throw Error(r.message)}}SnetSnltMsoMinDate(t){let r=Math.min(t.lf,this.projectDates.end_date);return new Date(Math.max(r,this.activity.end_date))}calculateLink(t){let r=this.gantt.getTask(t.target);if(!r||r.progress>0&&r.type!==D.PROJECT)return;let i=this.getSpecialCalculationParamForConstraintLink(),n=this.getSpecialParamForSf(),o=this.getSpecialParamForFF();return{0:()=>this.calculateFS(t,i),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t,o),3:()=>this.calculateSF(t,n)}[t.type]()}getSpecialCalculationParamForConstraintLink(){if(this.constraint===h.ALAP)return h.ALAP;if(this.constraint===h.FNET||this.constraint===h.SNET)return"snet-fnet";if(this.constraint===h.FNLT)return h.FNLT}getSpecialParamForSf(){return!![h.ALAP].includes(this.constraint)}getSpecialParamForFF(){return!![h.MFO,h.MSO].includes(this.constraint)}getMinCalculationLogic(t){if(this.constraint===h.ALAP)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.FNET)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.FNLT)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.MFO)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.SNET||this.constraint===h.SNLT||this.constraint===h.MSO)return this.SnetSnltMsoMinDate(t);if(this.constraint===h.ASAP)return this.getMinDateBasedOnConstraint(t)}getMinDateFromLinks(t){try{return this.constraint===h.ALAP||this.constraint===h.ASAP?t.reduce((i,n)=>n.lf<i.lf?n:i):t.reduce((r,i)=>i.ls<r.ls?i:r)}catch(r){throw new Error(`Function: getMinDateFromLinks in LinksConstraintCalculator - ${r.message}`)}}getMinLfFromLinks(t){return t.reduce((r,i)=>i.lf<r.lf?i:r)}getMinDateBasedOnConstraint(t,r=this.constraint){let i=Math.min(t.lf,this.projectDates.end_date),n=this.activity.end_date,o=this.activity.constraint_date;if(r===h.ASAP)return new Date(Math.max(i,n));if(r===h.FNET||r===h.FNLT){let a=Math.min(i,o);return new Date(Math.max(i,a))}if(r===h.ALAP)return new Date(Math.min(i,n))}},Wc=bo;function xh(e,t,r){let i={ls:null,lf:null};return r===h.MSO&&(i.ls=t.constraint_date,i.lf=R(e,i.ls,t.duration,t)),r===h.MFO&&(i.lf=t.constraint_date,i.ls=R(e,i.lf,-t.duration,t)),i}var Vc=xh;var Fo=class extends Ee{constructor(t,r,i){super(t,G.BACKWARD),this.gantt=t,this.chainStartActivities=new Set,this.secondLevelActivities=new Set,this.pendingParentsWithLinks=new Set,this.pendingParentsWithNoLinks=new Set,this.structureOfParents=new Map,this.singleParents=new Map,this.calculationsOfParentThatImpactChildrens=new Map,this.activitiesWaitingForCalculation=new Set,this.calculations=new Map,this.mapOfRelationsWithActivitiesIds=new Map,this.activitiesWaitingForCalculation=new Set,this.forwardPathCalculations=r,this.forwardConstraintsMap=i,this.constraintMap=new Map,this.minFromLinks=new Map,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.parentsWithFullProgress=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateLfAndLs(t))))))}async iterativeCalculateLfAndLs(t){let r=new zi({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await Gr({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:i=>this.calculateStartAndFinishTimes(i),shouldKeepPending:i=>this.calculationOfParentsFromLinks.has(i)&&!this.calculations.has(i),isCalculated:i=>this.calculations.has(i),onActivityProcessed:i=>this.activitiesWaitingForCalculation.delete(i),isCurrent:t})}setDatesToParentsWithLinks(t){if(!t)throw new Error("Error trying to get parent",{cause:{receivedParentData:t}});let r=this.singleParents.get(t.id).childrens,n=Array.from(this.calculations).filter(s=>r.includes(s[0])).map(s=>s[1]),{minLs:o,maxLf:a}=n.reduce((s,{ls:c,lf:l})=>({minLs:new Date(Math.min(s.minLs.getTime(),new Date(c).getTime())),maxLf:new Date(Math.max(s.maxLf.getTime(),new Date(l).getTime()))}),{minLs:new Date(n[0].ls),maxLf:new Date(n[0].lf)});this.calculations.set(t.id,{ls:o,lf:a})}calculateStartAndFinishTimes(t){t.forEach(r=>{let i=this.gantt.getTask(r);if(!i)throw new Error("Activity not found",{cause:{activityId:r}});let n=i.$source,o=i.constraint_type||h.ASAP,a=Number(i.progress);if(this.activitiesStartChainButChildrenOfLinkedParents.has(r)){if(this.calculationsOfParentThatImpactChildrens.has(Number(i.parent))&&this.calculationsOfParentThatImpactChildrens.get(Number(i.parent))===!1){let{ls:d,lf:u}=this.calculateStartAndFinishOfChainOrigin(i,this.direction);this.setCalculations(i,d,u);return}return this.doCalculationForActivitiesThatStartLinkButHisParentIsLinked(i)}if(i.type===D.PROJECT)return this.doCalculationForParentType(i);if(a===100){this.setDatesForActivityWithFullProgress(i);return}if(this.allLinkedActivitiesHasProgress(n,i)){this.setWhenAllLinkedActivitiesHasProgress(i);return}if(a>0&&a<100&&(o===h.MSO||o===h.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(i,o);return}if(o===h.MSO||o===h.MFO){this.recalculateInBaseRestriction(i,o);return}let{ls:s,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(n,i,o,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(o===h.SNLT||o===h.FNLT)&&({ls:s,lf:c}=this.getTheLessLateInBasEsEfConstraint(i.id,{ls:s,lf:c},o)),this.setCalculations(i,s,c),this.minFromLinks.set(i.id,{ls:l.ls,lf:l.lf})})}getTheLessLateInBasEsEfConstraint(t,r,i){let n=this.forwardConstraintsMap.get(t);if(!n){let o=this.gantt.getTask(t),a=this.gantt.getCalendar(o.calendar_id);n=$i(o,i,a)}return r.lf<n.ef?r:{ls:n.es,lf:n.ef}}allLinkedActivitiesHasProgress(t){try{let r=!0;for(let i of t){let n=this.gantt.getLink(i);if(!n)continue;let o=this.gantt.getTask(n.target);o&&(o.type===D.PROJECT&&(r=!1),o.progress===0&&(r=!1))}return r}catch(r){throw new Error(r.message)}}setDatesForActivityWithFullProgress(t){this.setCalculations(t,t.start_date,t.end_date)}setWhenAllLinkedActivitiesHasProgress(t){let r=Number(t.parent),{ls:i,lf:n}=this.calculateStartAndFinishOfChainOrigin(t,G.BACKWARD);if(this.calculationsOfParentThatImpactChildrens.has(r)){i=t.start_date;let o=this.calculationsOfParentThatImpactChildrens.get(r);o&&typeof o=="object"&&o.lf!=null&&(n=new Date(Math.min(n,o.lf)))}this.setCalculations(t,i,n)}setWhenActivitiesHasProgressButLessThanOneHundred(t,r){if(r===h.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(r===h.MFO){let i=Math.min(t.constraint_date,this.projectDates.end_date),n=new Date(Math.max(i,t.end_date));this.setCalculations(t,t.start_date,n);return}}setCalculations(t,r,i){this.calculations.set(t.id,{ls:r,lf:i,text:t.text})}calculateLfandLsFromLinks(t,r,i,n,o){return new Wc({links:t,activity:r,calculatedActivitiesMap:this.calculations,calculatedForwardActivitiesMap:this.forwardPathCalculations,constraint:i,parentsWithFullProgress:n,parentsThatImpactChildrens:o,ganttInstance:this.gantt}).calculate()}recalculateInBaseRestriction(t,r){try{let i=this.gantt.getCalendar(t.calendar_id);if(!i)throw new Error(`Error trying to get calendar with id: ${t.calendar_id}`);let n=Vc(i,t,r);this.constraintMap.set(t,n),this.setCalculations(t,n.ls,n.lf)}catch(i){throw new Error(i.message)}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let i=this.gantt.getLink(r).source,n=this.gantt.getLink(r).target;if(!(!this.gantt.getTask(i)||this.gantt.getTask(i)?.type===D.PROJECT)&&!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type===D.PROJECT))return r}).filter(Boolean)}doCalculationForActivitiesThatStartLinkButHisParentIsLinked(t){let r=Number(t.parent),i=this.calculationsOfParentThatImpactChildrens.get(r),n=0,o=0;if([h.ASAP,h.ALAP,h.SNET,h.FNET].includes(t.constraint_type))if(Number(t.progress)>0){let l=this.projectDates.end_date;o=new Date(Math.min(l,i.lf)),n=t.start_date}else o=i.lf,n=R(this.gantt.getCalendar(t.calendar_id),o,-t.duration,t);if([h.SNLT].includes(t.constraint_type)){let l=this.calculationsOfParentThatImpactChildrens.get(r),d=R(this.gantt.getCalendar(t.calendar_id),l.lf,-t.duration,t),u=t.constraint_date??d;n=new Date(Math.min(u.getTime(),d.getTime())),o=R(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}if([h.FNLT].includes(t.constraint_type)){let l=this.calculationsOfParentThatImpactChildrens.get(r),d=t.constraint_date??l.lf;n=new Date(Math.min(d.getTime(),l.lf.getTime())),o=R(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}[h.MSO].includes(t.constraint_type)&&(n=t.constraint_date,o=R(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)),[h.MFO].includes(t.constraint_type)&&(o=t.constraint_date,n=R(this.gantt.getCalendar(t.calendar_id),o,-t.duration,t));let a=this.projectDates.end_date,s=[{ls:n,lf:o}];s.push({ls:R(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t),lf:a});let c=this.getMinLfFromLinks(s);this.calculations.set(t.id,{ls:c.ls,lf:c.lf,text:t.text})}getMinLfFromLinks(t=[]){return t.length?t.reduce((r,i)=>i.lf<r.lf?i:r):!1}},jc=Fo;function Kc(){return null}var Yc=({forward:e,backward:t,id:r,activity:i,gantt:n,projectDates:o})=>({totalFloat:{es:e.calculations.get(r)?.es||0,ef:e.calculations.get(r)?.ef||0,ls:t.calculations.get(r)?.ls||0,lf:t.calculations.get(r)?.lf||0,constraintsMap:e.constraintsMap.get(r),totalFloatSnltFnlt:e.totalFloatSnltFnlt.get(r),totalFloatForMsoMfo:e.totalFloatForMsoMfo.get(r),minFromLinks:t.minFromLinks.get(r),activity:i,gantt:n},freeFloat:{forwardMap:e.calculations||new Map,backwardMap:t.calculations||new Map,activity:i,projectDates:o,gantt:n}});var wo=class{constructor(t){this.gantt=t.gantt,this.activity=t.activity,this.es=t.es,this.ef=t.ef,this.ls=t.ls,this.lf=t.lf,this.constrainstMap=t.constraintsMap,this.totalFloatSnltFnlt=t.totalFloatSnltFnlt,this.totalFloatForMsoMfo=t.totalFloatForMsoMfo,this.minFromLinks=t.minFromLinks}getTotalFloat(){let{constraint_type:t}=this.activity,r=Number(this.activity.progress);if(r===100)return 0;if(t||(t=h.ASAP),t===h.ASAP||!t)return r===0?this.calculateAsap():this.calculateAsapWithProgress();if(t===h.ALAP)return r===0?this.calculateAlap():this.calculateAlapWithProgress();if(t===h.SNET||t===h.FNET)return r===0?this.calculateSnetFet():this.calculateSnetFnetSnltWithProgress();if(t===h.SNLT)return r===0?this.calculateSnltFnlt():this.calculateSnetFnetSnltWithProgress();if(t===h.FNLT)return r===0?this.calculateSnltFnlt():this.calculateFnltWithProgress();if(t===h.MSO||t===h.MFO)return r===0?this.calculateMsoMfo():this.calculateMsoMfoWithProgress()}calculateAsap(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateAsapWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let r=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateAlap(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r),n=this.calculationWithCalendar(this.lf,this.activity.end_date);return this.getMinValue(i,n)/this.gantt.config.hoursPerDay}calculateAlapWithProgress(){return this.calculationWithCalendar(this.lf,this.ef)/this.gantt.config.hoursPerDay}calculateSnetFnetSnltWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let r=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateFnltWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef),r=this.calculationWithCalendar(this.activity.constraint_date,this.ef);if(this.minFromLinks){let i=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r,i)/this.gantt.config.hoursPerDay}return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateMsoMfoWithProgress(){return this.calculationWithCalendar(this.lf,this.ef)/this.gantt.config.hoursPerDay}calculateSnetFet(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateSnltFnlt(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r);if(!this.totalFloatSnltFnlt&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let n=0;return this.activity.constraint_type===h.SNLT?n=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatSnltFnlt.es):n=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatSnltFnlt.ef),this.getMinValue(n,i)/this.gantt.config.hoursPerDay}calculateMsoMfo(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r);if(!this.totalFloatForMsoMfo&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let n=0;return this.activity.constraint_type===h.MSO?n=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatForMsoMfo.es):n=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatForMsoMfo.ef),this.getMinValue(n,i)/this.gantt.config.hoursPerDay}getMinValue(...t){return Math.min(...t)}calculationWithCalendar(t,r){return this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)})}},Gc=wo;var xo=class{constructor(t){this.gantt=t.gantt,this.activity=t.activity,this.forwardMap=t.forwardMap,this.backwardMap=t.backwardMap,this.projectDates=t.projectDates,this.linksFreeFloatArray=[],this.linksFreeFloatObject={},this.durationCache=new Map}getFreeFloat(){let t=Number(this.activity.progress),r=this.getConstraintType();return this.calculateFreeFloatOfLink(r),{activityFreeFloat:t===100?0:this.getFreeFloatBaseConstraint(r),linksFreeFloat:this.linksFreeFloatObject}}getFreeFloatBaseConstraint(t){return t===h.MSO||t===h.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=h.ASAP){let r=this.activity.$source.map(i=>{let{LINK:n,LINK_TYPE:o}=this.getLinkData(i),a=this.gantt.getTask(n.target);if(!a)return{linkId:n.id,freeFloat:null,hasProgress:!1};let s=Number(a.progress)>0,{sucessorDateToCalculate:c,predecessorDateToCalculate:l}=this.getDatesFromSucessorAndPredecessor(o,t,a),d=this.calculationWithCalendar(c,l),u=this.parseHoursToDays(d)-this.parseHoursToDays(n.lag),f=Math.max(0,u);return this.linksFreeFloatObject[n.id]=f,{linkId:n.id,freeFloat:f,hasProgress:s}}).filter(i=>i.freeFloat!==null&&i.freeFloat!==void 0);return this.linksFreeFloatArray=r,r}calculateGeneral(t=h.ASAP){let r=this.getMinFloat(this.linksFreeFloatArray),i=this.calculateFreeFloatForEndOfProject(t),n=0;return[h.SNLT,h.FNLT].includes(t)?n=this.doCalculationForSnltFnlt(t,i,r):n=this.doGeneralCalculation(i,r),Math.max(0,n)}getConstraintType(){let{constraint_type:t}=this.activity;return t||(t=h.ASAP),t}getDatesFromSucessorAndPredecessor(t,r,i){let n=i.constraint_type===h.ALAP,o=this.getSucessorAndPredecessorDates({constraint:r,isSuscessorAlap:n,sucessorId:i.id,predecessorId:this.activity.id}),a=new Date,s=new Date;return a=o[t].sucessor,s=o[t].predecessor,{sucessorDateToCalculate:a,predecessorDateToCalculate:s}}doGeneralCalculation(t,r){return r===null?t:this.getMinValue(r,t)}doCalculationForSnltFnlt(t,r,i){let n=this.calculateFreeFloatOfRestriction(t);return this.getMinValue(i,r,n)}calculateFreeFloatForEndOfProject(t){let r=t===h.ALAP?this.backwardMap.get(this.activity.id):this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===h.ALAP?r?.lf:r?.ef))}calculateFreeFloatOfRestriction(t){let r=this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.activity.constraint_date,t===h.FNLT?r?.ef:r?.es))}getLinkData(t){let r=this.gantt.getLink(t)||{},i=Me(r.type);return{LINK:r,LINK_TYPE:i}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:r,sucessorId:i,predecessorId:n}){let o=(r?this.backwardMap:this.forwardMap).get(i),a=(t===h.ALAP?this.backwardMap:this.forwardMap).get(n),s=t===h.ALAP?a?.ls:a?.es,c=t===h.ALAP?a?.lf:a?.ef;return{fs:{sucessor:o?.ls??o?.es,predecessor:c},ss:{sucessor:o?.ls??o?.es,predecessor:s},ff:{sucessor:o?.lf??o?.ef,predecessor:c},sf:{sucessor:o?.lf??o?.ef,predecessor:s}}}calculateMsoMfo(t){let r=this.activity.constraint_date||new Date,i=this.forwardMap.get(this.activity.id),n=t===h.MSO?i?.es:i?.ef,o=this.calculationWithCalendar(r,n);return Math.max(0,this.parseHoursToDays(o))}getMinValue(...t){let r=t.filter(i=>i!=null);return r.length?Math.min(...r):0}calculationWithCalendar(t,r){if(!(t instanceof Date)||!(r instanceof Date)||!Number.isFinite(t.getTime())||!Number.isFinite(r.getTime()))return Number.NaN;let i=`${r.getTime()}_${t.getTime()}`;if(this.durationCache.has(i))return this.durationCache.get(i);let o=this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)});return this.durationCache.set(i,o),o}parseHoursToDays(t){return t==null?0:t/this.gantt.config.hoursPerDay}getMinFloat(t){if(!t?.length)return null;let r=t.filter(i=>!i.hasProgress).map(i=>i.freeFloat);return r.length===0?null:Math.min(...r)}},$c=xo;var zc=e=>({totalFloat:new Gc(e.totalFloat).getTotalFloat(),freeFloat:new $c(e.freeFloat).getFreeFloat()});var Mo=async({activityIds:e,forward:t,backward:r,gantt:i,projectDates:n,isCurrent:o})=>{let a=performance.now(),s=new Map,c=new Map;for(let l of e){if(o&&!o())return{totalFloatMap:s,freeFloatMap:c};let d=i.getTask(l);if(!d)continue;let u=Yc({forward:t,backward:r,id:l,activity:d,gantt:i,projectDates:n}),{totalFloat:f,freeFloat:p}=zc(u);s.set(l,f),c.set(l,p),a=await Be(a)}return{totalFloatMap:s,freeFloatMap:c}};var Uo=class{constructor(t){this.gantt=t,this.forwardPathCalculations=null,this.backwardPathCalculations=null,this.totalFloat=new Map,this.freeFloat=new Map,this.linkResidualHours=new Map,this.currentCalculationId=0}getCurrentCalculationId=()=>this.currentCalculationId;async calculate(t,r=()=>!0){let i=++this.currentCalculationId,n=Po(i,this.getCurrentCalculationId),o=()=>n()&&r();try{let a=t||this.gantt;if(this.gantt=a||Kc(),Lo(this.gantt))return!1;let s=new Bc(this.gantt);if(await s.calculateAsync(o),!o())return!1;let c=s.calculations,l=s.constraintsMap,d=new jc(this.gantt,c,l);if(await d.calculateAsync(o),!o())return!1;this.forwardPathCalculations=c,this.backwardPathCalculations=d.calculations;let u=await this.calculateLinkResidualHours(s.linkCandidates,c,o);if(!u||!o())return!1;this.linkResidualHours=u;let{totalFloatMap:f,freeFloatMap:p}=await this.calculateFloatsAsync(s,d,o);return o()?(this.totalFloat=f,this.freeFloat=p,this.gantt.refreshData(),!0):!1}catch(a){throw this.forwardPathCalculations?.size,a}}async calculateLinkResidualHours(t,r,i=()=>!0){let n=new Map,o=performance.now();for(let[a,s]of t){if(o=await Be(o),!i())return null;let c=Number(s.targetId),l=this.gantt.getTask(c),d=r.get(c),u=s.ef,f=d?.ef,p=l&&this.gantt.getCalendar(l.calendar_id);if(!p||!(u instanceof Date)||!(f instanceof Date)||!Number.isFinite(u.getTime())||!Number.isFinite(f.getTime())){n.set(a,null);continue}let y=u.getTime(),T=f.getTime()>=y?p.calculateDuration({start_date:u,end_date:f}):-p.calculateDuration({start_date:f,end_date:u});n.set(a,Number.isFinite(T)?Object.is(T,-0)?0:T:null)}return n}async calculateFloatsAsync(t,r,i){try{let n=this.gantt.getSubtaskDates(),o=Array.from(this.forwardPathCalculations.keys());return await Mo({activityIds:o,forward:t,backward:r,gantt:this.gantt,projectDates:n,isCurrent:i})}catch(n){throw this.forwardPathCalculations?.size,n}}},qc=Uo;var Mh=e=>e===A.FNET||e===A.FNLT||e===A.MFO,Uh=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function Bh(e,t){let r=e.constraintDate;if(!r||!Mh(e.constraintType))return r;let i=Uh(r);if(r.getTime()!==i.getTime())return r;let n=t.getClosestWorkTime({date:i,dir:"future",task:e});return n.getUTCFullYear()===r.getUTCFullYear()&&n.getUTCMonth()===r.getUTCMonth()&&n.getUTCDate()===r.getUTCDate()?Hn(e,t):r}function Hh(e){let t=new Map,r=new Map,i=new Map;return{calculateEndDate:({start_date:n,duration:o})=>{let a=`${n.getTime()}|${o}`,s=t.get(a);if(s!==void 0)return new Date(s);let c=e.calculateEndDate(n,o);return t.set(a,c.getTime()),c},calculateDuration:({start_date:n,end_date:o})=>{let a=`${n.getTime()}|${o.getTime()}`,s=r.get(a);if(s!==void 0)return s;let c=e.calculateDuration(n,o);return r.set(a,c),c},getWorkHours:n=>e.getWorkHours(n),$gantt:{getClosestWorkTime:({date:n,dir:o,unit:a})=>{let s=a??"hour",c=`${n.getTime()}|${o}|${s}`,l=i.get(c);if(l!==void 0)return new Date(l);let d=e.getClosestWorkTime({date:n,direction:o,unit:s});return i.set(c,d.getTime()),d}}}}function Wh(e){let t=new Map;e.forEachActivity((n,o)=>t.set(String(o),n));let r=new Map,i=(n,o)=>{let a=r.get(n);if(a!=null)return a;let c=t.get(n)?.parentId??null,l=0;return c!==null&&!o.has(n)&&(o.add(n),l=i(String(c),o)+1),r.set(n,l),l};for(let n of t.keys())i(n,new Set);return r}function Vh(e){let t=new Set;e.forEachActivity((s,c)=>{t.add(String(c)),s.parentId!==null&&t.add(String(s.parentId))});let r=new Map;for(let s of t){let c=Number(s);Number.isSafeInteger(c)&&c!==0&&r.set(c,(r.get(c)??0)+1)}let i=new Map,n=new Map;for(let s of t){let c=Number(s);Number.isSafeInteger(c)&&c!==0&&r.get(c)===1&&(i.set(s,c),n.set(c,s))}let o=1,a=s=>{let c=String(s),l=i.get(c);if(l!==void 0)return l;for(;n.has(o);)o+=1;return i.set(c,o),n.set(o,c),o++};for(let s of t)a(s);return{toLegacy:a,toCanonical:s=>typeof s=="number"?n.get(s)??null:i.has(String(s))?String(s):null}}function jh(e,t){let r=Wh(e),i=new Map;return e.forEachActivity((n,o)=>{let a=String(o);i.set(a,{id:t.toLegacy(a),parent:n.parentId===null?0:t.toLegacy(n.parentId),$level:r.get(a)??0,$source:e.getOutgoingLinkIds(a),$target:e.getIncomingLinkIds(a),start_date:n.startDate,end_date:n.endDate,duration:n.durationHours,progress:n.progress,type:n.type,calendar_id:n.calendarId,constraint_type:n.constraintType,constraint_date:Bh(n,e)})}),i}function Kh(e){let t=new Map;for(let a of e.values()){let s=t.get(a.parent);s?s.push(a):t.set(a.parent,[a])}let r=[],i=new Set,n=[],o=a=>{if(a)for(let s=a.length-1;s>=0;s-=1)n.push(a[s])};for(o(t.get(0));n.length>0;){let a=n.pop();i.has(a)||(i.add(a),r.push(a),o(t.get(a.id)))}if(r.length<e.size)for(let a of e.values())i.has(a)||r.push(a);return r}function Yh(e){let t=null,r=null;return e.forEachActivity(i=>{if(i.startDate){let n=i.startDate.getTime();t=t==null?n:Math.min(t,n)}if(i.endDate){let n=i.endDate.getTime();r=r==null?n:Math.max(r,n)}}),{start_date:new Date(t??0),end_date:new Date(r??0)}}async function Jc(e,t){let r=new Map,i=l=>{let d=l==null?"__default__":String(l),u=r.get(d);if(u)return u;let f=e.calendarReader.getCalendar(String(l)),p=Hh(f);return r.set(d,p),p},n=Yh(e);await st();let o=Vh(e),a=jh(e,o);await st();let s=[...a.values()].sort((l,d)=>(l.start_date?.getTime()??0)-(d.start_date?.getTime()??0));await st();let c=Kh(a);return{fullyParsed:!0,config:{hoursPerDay:t},getTask:l=>{let d=o.toCanonical(l);return d===null?null:a.get(d)??null},getLink:l=>{let d=e.getLink(l);return d?{...d,source:o.toLegacy(d.source),target:o.toLegacy(d.target),lag:d.lag}:null},getCalendar:i,getChildren:l=>{let d=o.toCanonical(l);return d===null?[]:e.getChildren(d).map(o.toLegacy)},eachTask:l=>{for(let d of c)l(d)},getTaskByTime:()=>s,getSubtaskDates:()=>n,getCanonicalActivityId:o.toCanonical,refreshData:()=>{}}}var Ho=1e3,Gh=e=>typeof e!="number"||!Number.isFinite(e)?null:Object.is(e,-0)?0:e,$h=(e,t)=>typeof e!="number"||e<0?null:Bo(e,t);function zh(e){let t=$h(e.freeFloatDays,e.hoursPerDay),r=Gh(e.residualHours);return{freeSlackHours:t,isCritical:r!==null&&r<=0&&e.sourceIsCritical&&e.targetIsCritical&&e.targetProgress===0}}async function qh(e,t){let r=new Map,i=0;for(let n of e.values())for(let o in n.linksFreeFloat)if(Object.hasOwn(n.linksFreeFloat,o)){if(++i>=Ho&&(i=0,await st(),!t()))return null;r.set(String(o),n.linksFreeFloat[o])}return t()?r:null}async function Jh(e,t,r,i,n){let o=new Map,a=0;for(let s of t.forward?.keys()??[]){if(++a>=Ho&&(a=0,await st(),!n()))return null;let c=i(s);if(c===null)continue;let l=e.getActivity(c);l&&o.set(String(c),Zh(s,Number(l.progress??0),t,r))}return n()?o:null}async function Xh(e,t,r,i,n,o){let a=new Map,s=0;for(let c of e.getAllLinks()){if(++s>=Ho&&(s=0,await st(),!o()))return null;a.set(String(c.id),zh({freeFloatDays:t.get(String(c.id)),residualHours:r.get(String(c.id)),hoursPerDay:n,sourceIsCritical:i.get(c.source)?.isCritical===!0,targetIsCritical:i.get(c.target)?.isCritical===!0,targetProgress:e.getActivity(c.target)?.progress}))}return o()?a:null}var Bo=(e,t)=>{if(typeof e!="number"||!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return null;let r=e*t;return Number.isFinite(r)?Object.is(r,-0)?0:r:null};function Zh(e,t,r,i){let n=c=>{if(c==null)return null;let l=new Date(c);return Number.isFinite(l.getTime())?l:null},o=r.forward?.get(e),a=r.backward?.get(e),s=Bo(r.totalFloat.get(e),i);return{criticalPath:{earlyStart:n(o?.es),earlyFinish:n(o?.ef),lateStart:n(a?.ls),lateFinish:n(a?.lf),totalSlackHours:s},isCritical:t<100&&s!==null&&s<=0,freeSlackHours:Bo(r.freeFloat.get(e)?.activityFreeFloat,i)}}var qi=(e,t)=>e===t||e!==null&&t!==null&&e.getTime()===t.getTime();function Wo(e,t,r){let i=e.getActivity(t),n=i?.criticalPath,o=r.criticalPath;i&&n&&qi(n.earlyStart,o.earlyStart)&&qi(n.earlyFinish,o.earlyFinish)&&qi(n.lateStart,o.lateStart)&&qi(n.lateFinish,o.lateFinish)&&Object.is(n.totalSlackHours,o.totalSlackHours)&&Object.is(i.isCritical,r.isCritical)&&Object.is(i.freeSlackHours,r.freeSlackHours)||e.setActivityFields(t,r)}function Vo(e,t,r){let i=e.getLink(t);!i||Object.is(i.freeSlackHours,r.freeSlackHours)&&Object.is(i.isCritical,r.isCritical)||(e.setLinkField(t,"freeSlackHours",r.freeSlackHours),e.setLinkField(t,"isCritical",r.isCritical))}async function jo(e,t,r=()=>!0){if(!r())return null;let i=await Jc(e,t);if(!r())return null;let n=new qc(i);if(!await n.calculate(i,r)){if(!r())return null;throw new Error("critical path calculation aborted")}if(!r())return null;let a={forward:n.forwardPathCalculations,backward:n.backwardPathCalculations,totalFloat:n.totalFloat,freeFloat:n.freeFloat},s=await Jh(e,a,t,i.getCanonicalActivityId,r);if(!s)return null;let c=await qh(a.freeFloat,r);if(!c)return null;let l=await Xh(e,c,n.linkResidualHours,s,t,r);return l?{activities:s,links:l}:null}async function Xc(e,t,r=()=>!0){let i=await jo(e,t,r);if(!i||!r())return!1;for(let[n,o]of i.activities){if(!r())return!1;Wo(e,n,o)}for(let[n,o]of i.links){if(!r())return!1;Vo(e,n,o)}return!0}function ur(e){let t=[],r=[];e.forEachActivity((n,o)=>{n.parentId===null&&t.push(String(o))});let i=n=>{let o=e.getActivity(String(n));if(!o)return 0;let a=[...e.getChildren(String(n))],s;if(a.length===0){let c=kt(o),l=c&&Number(c.cost)||0;s=(Number(o.progress)||0)/100*l}else{let c=0;for(let l of a)c+=i(String(l));s=c}return e.setActivityField(String(n),x.REAL_COST,s),r.push(String(n)),s};for(let n of t)i(n);return r}var Zc=new Set;var Qc=new Set(["activity-outdent","activity-indent"]);var $r=new Set([_.TEXT,_.DESCRIPTION,_.COST,_.USED_COST,_.CUSTOM_ID,_.RESPONSABLES,_.SUBCONTRACT_ID,_.TAGS]),Qh=new Set([m.ACTIVITY_CLIPBOARD_CLEAR,m.ACTIVITY_COPY,m.SELECTION_TOGGLE,m.SELECTION_REPLACE,m.VISIBILITY_SET,m.FILTER_SET,m.SORT_SET,m.SIR_SYNC,m.ACTIVITY_LOOKAHEAD_SYNC,m.PERSISTENCE_ACKNOWLEDGE,m.BASELINE_APPLY,m.PONDERATOR_CRITERION_SET,m.STATUS_CRITERIA_SET]),tm=new Set([m.ACTIVITY_CLIPBOARD_CLEAR,m.ACTIVITY_COPY,m.SELECTION_TOGGLE,m.SELECTION_REPLACE,m.VISIBILITY_SET,m.FILTER_SET,m.SORT_SET]);function el(e){return!tm.has(e.kind)}var em=new Set;function rm(e){return e.kind===m.INLINE_EDIT?$r.has(e.column):e.kind===m.BULK_EDIT?e.edits.every(t=>$r.has(t.column)):!1}function Ko(e,t){return!(Qh.has(e.kind)||t.has(e.kind)||rm(e))}function Yo(e){return e.kind===m.ACTIVITY_LOOKAHEAD_SYNC?e.persistedProgress!==void 0:Ko(e,em)}function He(e){return e.kind===m.ACTIVITY_LOOKAHEAD_SYNC?e.persistedProgress!==void 0:Ko(e,Zc)}function rl(e){return Ko(e,Qc)}function Go(e){return e.kind===m.ACTIVITY_SET_PROGRESS?!0:e.kind===m.INLINE_EDIT?e.column===_.PROGRESS:e.kind===m.BULK_EDIT?e.edits.some(t=>t.column===_.PROGRESS):!1}function im(e){return rl(e)&&Go(e)}var tl=new Set([_.PROGRESS,_.HH_WORK_TIME,_.DURATION,_.COST,_.USED_COST,_.REAL_COST]);function nm(e){return e.kind===m.ACTIVITY_SET_PROGRESS?!0:e.kind===m.INLINE_EDIT?tl.has(e.column):e.kind===m.BULK_EDIT?e.edits.some(t=>tl.has(t.column)):!1}var Tt={AUTOSCHEDULE:"autoschedule",PARENT_BOUNDS:"parent-bounds",PARENT_PROGRESS:"parent-progress",REAL_WORK:"real-work",EXPECTED_PROGRESS:"expected-progress",REAL_COST:"real-cost",CRITICAL_PATH:"critical-path"};function il(e,t,r){let i=new Set;t.ran&&i.add(Tt.AUTOSCHEDULE),i.add(Tt.PARENT_BOUNDS),nm(e)&&i.add(Tt.PARENT_PROGRESS),Go(e)&&i.add(Tt.REAL_WORK);let n=!r.skipAutoSchedule;return n&&rl(e)&&i.add(Tt.EXPECTED_PROGRESS),n&&im(e)&&i.add(Tt.REAL_COST),n&&He(e)&&!r.skipCriticalPath&&i.add(Tt.CRITICAL_PATH),i}var Et={INSERT:"insert",REMOVE:"remove",LINK_ADD:"link-add",LINK_REMOVE:"link-remove",LINK_FIELD:"link-field"},Ji=class{_journal=null;begin(){this._journal={dirty:new Set,before:new Map,ops:[],linkFieldCaptured:new Set,correlativeBefore:new Map,scheduledBefore:new Map,progressFallbackBefore:new Map}}peek(){return this._journal}end(){this._journal=null}note(t,r){let i=this._journal;i&&(i.before.has(t)||i.before.set(t,ae(r)),i.dirty.add(t))}noteInsert(t){this._journal?.ops.push({kind:Et.INSERT,activityId:t})}noteRemove(t,r){this._journal?.ops.push({kind:Et.REMOVE,activityId:t,before:ae(r)})}noteLinkAdd(t){this._journal?.ops.push({kind:Et.LINK_ADD,linkId:t})}noteLinkRemove(t,r){this._journal?.ops.push({kind:Et.LINK_REMOVE,linkId:t,before:nl(r)})}noteCorrelativeBefore(t,r){let i=this._journal;if(!i||i.correlativeBefore.has(t))return;let n=i.before.get(t)?.correlativeId;i.correlativeBefore.set(t,typeof n=="number"?n:r)}noteScheduledBefore(t,r){let i=this._journal;if(!i)return;let n=ae(r);i.scheduledBefore.has(t)||i.scheduledBefore.set(t,n),i.before.has(t)||i.before.set(t,n),i.dirty.add(t)}noteLinkField(t,r){let i=this._journal;!i||i.linkFieldCaptured.has(t)||(i.linkFieldCaptured.add(t),i.ops.push({kind:Et.LINK_FIELD,linkId:t,before:nl(r)}))}noteProgressFallback(t,r){let i=this._journal;!i||i.progressFallbackBefore.has(t)||i.progressFallbackBefore.set(t,r)}};function nl(e){return{...e}}var Ot={ROOTS:"roots"};async function Z(e,t){let r=am(e.adapter),i=om(t,r);i.has(Tt.AUTOSCHEDULE)&&await fm(e.adapter,t);let n=i.has(Tt.AUTOSCHEDULE)?await lm(e,t.autoscheduleFrom,t.preventSummaryTargetPullback):um();return await pm(e.adapter,t,n.scheduledIds,i,r),await hm(e,i,t.now),n}function om(e,t){let r=e.autoscheduleFrom!==null,i=!e.options.skipAutoSchedule&&r,n=new Set(il(e.action,{requested:r,ran:i},e.options));return(e.recomputeParentProgress||t.affectedParents.size>0)&&n.add(Tt.PARENT_PROGRESS),n}function am(e){let t=new Set,r=new Set,i=e.peekWriteCapture();if(!i)return{affectedParents:t,dirtySeeds:r};let n=o=>{if(o===null||M(o))return;let a=String(o);t.add(a);let s=e.getChildren(a)[0];s!==void 0&&r.add(s)};return sm(e,i.ops,n),cm(e,i.before,r,n),{affectedParents:t,dirtySeeds:r}}function sm(e,t,r){for(let i of t)if(i.kind===Et.INSERT){let n=e.getActivity(i.activityId);n&&r(n.parentId)}else i.kind===Et.REMOVE&&r(i.before.parentId)}function cm(e,t,r,i){for(let[n,o]of t){let a=e.getActivity(n);if(!a)continue;let s=!Object.is(o.progress,a.progress),c=!Object.is(o.ponderator,a.ponderator),l=!Object.is(o.parentId,a.parentId);(s||c)&&(i(a.parentId),r.add(String(n))),l&&(i(o.parentId),i(a.parentId),r.add(String(n)))}}async function lm(e,t,r=!1){let i=t===Ot.ROOTS?{}:{triggerId:t};r&&(i.preventSummaryTargetPullback=!0);let n=await e.scheduler.schedule(i),o=dm(e.adapter,n.updatedIds);return br(e.adapter,n),o}function dm(e,t){let r=[];for(let i of t){let n=String(i);r.push(n);let o=e.getActivity(n);o&&e.noteScheduledBefore(n,o)}return{scheduledIds:r}}function um(){return{scheduledIds:[]}}async function fm(e,t){let r=t.collectDirty?t.collectDirty([]):mo(t.recomputeParentsFrom,[]);r.size!==0&&await rr(e,r,!1)}async function pm(e,t,r,i,n){i.has(Tt.PARENT_PROGRESS)&&ym(e,n.affectedParents);let o=t.collectDirty?t.collectDirty(r):mo(t.recomputeParentsFrom,r);for(let a of n.dirtySeeds)o.add(a);await rr(e,o,i.has(Tt.PARENT_PROGRESS),{recomputeRealWork:i.has(Tt.REAL_WORK),progressMode:"freeze-when-no-contribution"})}function ym(e,t){for(let r of t){if(e.hasChildren(r))continue;let i=e.getProgressFallback(r);i!==null&&(e.setActivityField(r,"progress",i),e.setProgressFallback(r,null))}}async function hm(e,t,r){t.has(Tt.EXPECTED_PROGRESS)&&r!==null&&(mm(e.adapter)&&dr(e.adapter,r,e.defaultBaseCalendarId??null),xe(e.adapter,r),ce(e.adapter,e.sector.statusCriteria)),t.has(Tt.REAL_COST)&&ur(e.adapter),t.has(Tt.CRITICAL_PATH)&&await Xc(e.adapter,e.sector.hoursPerDay)}function mm(e){let t=!1;return e.forEachActivity(r=>{kt(r)&&(t=!0)}),t}var Im=new Set([_.CONSTRAINT_TYPE,_.CONSTRAINT_DATE]),gm=new Set([A.MSO,A.MFO]);function Xi(e){return Im.has(e)}function Zi(e){return e===_.CONSTRAINT_DATE}function Qi(e,t,r,i){let n=r.getActivity(e);if(!n)return!1;let o=n.constraintType;if(!o||Ae.has(o)||gm.has(o))return!1;let a=$o(n.startDate),s=$o(r.getLastStartDate(e));if(!s||!a||a.getTime()!==s.getTime())return!1;let c=Am(t,o,String(n.calendarId??""),i),l=$o(n.constraintDate);return vm(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function Am(e,t,r,i){if(e===null)return null;let n=i.getCalendar(r);return n?ne(e,n,t):e}function $o(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function vm(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function tn(e,{postMutationArgs:t,revertTargets:r,revert:i}){let{scheduledIds:n}=await Z(e,ol(t)),o=!1;for(let{activityId:a,priorConstraintDate:s}of r){let c=i(a,s);o=o||c}if(o){let a=await Z(e,ol(t));n=Sm(n,a.scheduledIds)}return He(t.action)&&await Z(e,Cm(t)),{scheduledIds:n}}function ol(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function Cm(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function Sm(e,t){let r=new Set(e);for(let i of t)r.add(i);return[...r]}function zo(e,t,r){let i=[];for(let n of r){let o=e.get(n);if(!o)continue;let a=o.pendingRequestIds??[];if(qe({pendingRequestIds:a})&&t.getActivity(n)==null)for(let s of a)i.push({kind:Ui.SIR_AUTO_REJECT,activityId:n,sirId:s,reason:Bi.ACTIVITY_DELETED})}return i}function bt(e){let t={id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag),freeSlackHours:typeof e.freeSlackHours=="number"&&Number.isFinite(e.freeSlackHours)?e.freeSlackHours:null,isCritical:e.isCritical===!0};return e.proplannerId!=null&&(t.proplannerId=Number(e.proplannerId)),e.ganttId!=null&&(t.ganttId=Number(e.ganttId)),e.sectorId!=null&&(t.sectorId=Number(e.sectorId)),t}var Ft={BEFORE_DIFF:"before-diff",AFTER_DIFF:"after-diff"};async function z(e,t){let r=_m(e,t),i=new Map(t.beforeSnap),n=e.peekWriteCapture();if(n){let f=Rm(n);km(e,n,f,i,r)}let o=t.sirDetection,a=o===Ft.BEFORE_DIFF?zo(i,e,r):[],s=Dm(t.correlativeShifts,r),c=await Vi(e,i,r,s),l=o===Ft.AFTER_DIFF?zo(i,e,r):a,d=t.warnings??[],u=Em(t.links??[],n?Tm(e,n):[]);return{source:t.source,activities:c,links:u,calendars:[],trackingEvents:t.trackingEvents??[],...l.length>0?{effects:l}:{},...d.length>0?{warnings:d}:{}}}function Tm(e,t){let r=[];for(let i of t.ops){if(i.kind!==Et.LINK_FIELD)continue;let n=e.getLink(i.linkId);if(!n)continue;let o={};for(let a of["freeSlackHours","isCritical"])Object.is(i.before[a],n[a])||(o[a]={before:i.before[a],after:n[a]});Object.keys(o).length!==0&&r.push({id:i.linkId,kind:N.UPDATED,fields:o,after:bt(n)})}return r}function Em(e,t){let r=[],i=new Map;for(let n of e){let o=i.get(n.id);if(o===void 0){i.set(n.id,r.length),r.push(n);continue}let a=r[o];if((a.kind===N.UPDATED||a.kind===N.CREATED)&&n.kind===N.UPDATED){r[o]={...a,fields:{...a.fields,...n.fields},after:n.after};continue}r[o]=n}for(let n of t){let o=i.get(n.id);if(o===void 0){i.set(n.id,r.length),r.push(n);continue}let a=r[o];if(a.kind===N.DELETED)continue;let s=a.kind===N.CREATED?Object.fromEntries(Object.entries(n.fields??{}).map(([c,l])=>[c,{before:void 0,after:l.after}])):n.fields;r[o]={...a,fields:{...a.fields,...s},after:n.after}}return r}function Dm(e,t){if(!e||e.length===0)return;let r=new Map;for(let i of e)r.set(i.activityId,i.before),t.add(i.activityId);return r}function _m(e,t){let r=new Set;for(let i of t.touchedIds)r.add(i);for(let i of t.scheduledIds)r.add(i);if(t.includeAllIds)for(let i of e.getAllIds())r.add(i);return r}function km(e,t,r,i,n){for(let o of t.dirty){if(r.has(o)||i.has(o))continue;let a=t.before.get(o),s=e.getActivity(o);!a||!s||Object.keys(ho(a,s)).length!==0&&(i.set(o,a),n.add(o))}}function Rm(e){return new Set(e.ops.filter(t=>t.kind===Et.INSERT).map(t=>t.activityId))}function fr(e,t,r){let i=[];for(let{op:n,finalLinkId:o,rejected:a}of e){if(a!==null)continue;if(n.kind===dt.CREATE){if(!o)continue;let d=r.getLink(o);if(!d)continue;let u=t.get(o);if(u){let f={};String(u.source)!==String(d.source)&&(f.source={before:String(u.source),after:String(d.source)}),String(u.target)!==String(d.target)&&(f.target={before:String(u.target),after:String(d.target)}),u.type!==d.type&&(f.type={before:u.type,after:d.type}),Number(u.lag)!==Number(d.lag)&&(f.lag={before:Number(u.lag),after:Number(d.lag)}),Object.keys(f).length>0&&i.push({id:String(o),kind:N.UPDATED,fields:f,after:bt(d)});continue}i.push({id:String(o),kind:N.CREATED,fields:{source:{before:void 0,after:String(d.source)},target:{before:void 0,after:String(d.target)},type:{before:void 0,after:d.type},lag:{before:void 0,after:Number(d.lag)}},after:bt(d)});continue}if(n.kind===dt.DELETE){if(r.getLink(n.linkId))continue;let d=t.get(n.linkId);i.push({id:String(n.linkId),kind:N.DELETED,fields:d?{source:{before:String(d.source),after:void 0},target:{before:String(d.target),after:void 0},type:{before:d.type,after:void 0},lag:{before:Number(d.lag),after:void 0}}:void 0,after:null});continue}let s=t.get(n.linkId),c=r.getLink(n.linkId);if(!c)continue;let l={};s&&s.type!==c.type&&(l.type={before:s.type,after:c.type}),s&&Number(s.lag)!==Number(c.lag)&&(l.lag={before:Number(s.lag),after:Number(c.lag)}),i.push({id:String(n.linkId),kind:N.UPDATED,fields:l,after:bt(c)})}return i}function pr(e,t){let r=new Map;if(!e.getActivity(t))return r;for(let i of e.getIncomingLinkIds(t)){let n=e.getLink(i);n&&r.set(String(n.id),Number(n.lag))}return r}function yr(e,t,r){let i=[];if(!t.getActivity(r))return i;for(let n of t.getIncomingLinkIds(r)){let o=t.getLink(n);if(!o)continue;let a=e.get(String(o.id));a===void 0||a===Number(o.lag)||i.push({id:String(o.id),kind:N.UPDATED,fields:{lag:{before:a,after:Number(o.lag)}},after:bt(o)})}return i}function en(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function al(e,t,r){let{adapter:i,ctx:n,scheduler:o,sector:a}=r,s=Ce(e.column);if(!s)return{ok:!1,reason:S.NO_PIPELINE_FOR_COLUMN};e.column===_.DURATION&&o.invalidateExpandedLinksCache();let c=n.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let l=s.canEdit(c,n.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??S.CANNOT_EDIT,alertKey:l.alertKey};let d=s.parseInput(e.newValue,c,n);if(!d.ok)return{ok:!1,reason:d.reason??S.PARSE_ERROR};let u=Reflect.get(c,s.targetField),f=s.validate(c,u,d.value,n);if(!f.valid)return{ok:!1,reason:f.reason??S.INVALID,alertKey:f.notification?.messageKey};if(e.column===_.CUSTOM_ID&&d.value!==null){let v=i.getActivity(e.activityId),P=v?v.customId:null,q=typeof P=="string"?P:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),q))return{ok:!1,reason:S.CUSTOM_ID_DUPLICATE}}let p=s.transform(c,d.value,n,d.raw),y=Se(e.activityId,p),g=await rt(i,y),T=pr(i,String(e.activityId)),L=c.constraintDate;Te(i,e.activityId,p),me(e.activityId,p.postProcessors??[],i,g.get(String(e.activityId))??null);let C=yr(T,i,String(e.activityId));if(e.column===_.CUSTOM_ID){let v=g.get(String(e.activityId)),P=v?v.customId:null,q=typeof P=="string"?P:null,$=typeof d.value=="string"?d.value:null;q!==$&&r.customIdTracker.trackCustomIdChange(q,$)}let E=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:v=>ji(e.activityId,y,v),now:r.now,options:t}),I=Xi(e.column),{scheduledIds:b}=await(I?tn({adapter:i,scheduler:o,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:E(),revertTargets:Zi(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:L}],revert:(v,P)=>Qi(v,P,i,n.calendars)}):Z({adapter:i,scheduler:o,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},E())),B=(p.trackingEvents??[]).map(v=>({name:v.name,properties:v.properties??{}}));s.trackEvent&&!(e.column===_.PROGRESS&&Number(d.value)<=0)&&B.unshift({name:s.trackEvent,properties:{activity_name:c.name,activity_id:c.id,activity_index:c.correlativeId}});let k=sr(e.activityId,p.constraintWarning);return{ok:!0,changes:await z(i,{source:e,beforeSnap:g,touchedIds:y,scheduledIds:b,sirDetection:Ft.BEFORE_DIFF,links:C,trackingEvents:B,...k?{warnings:[k]}:{},hoursPerDay:a.hoursPerDay})}}function rn(e){return ni(e)}function nn(e,t){return Object.hasOwn(e,t)}function Pm(e){if(e.kind===m.LINK_CREATE)return rn(e.type)?e.lag===void 0||Number.isFinite(e.lag)?null:S.INVALID_LINK_LAG:S.INVALID_LINK_TYPE;if(e.kind===m.LINK_UPDATE){if(nn(e,"type")&&!rn(e.type))return S.INVALID_LINK_TYPE;if(nn(e,"lag")&&!Number.isFinite(e.lag))return S.INVALID_LINK_LAG}return null}function Lm(e){return e.kind===at.CREATE?rn(e.type)?e.lag===void 0||Number.isFinite(e.lag)?null:S.INVALID_LINK_LAG:S.INVALID_LINK_TYPE:e.kind===at.UPDATE?nn(e,"type")&&!rn(e.type)?S.INVALID_LINK_TYPE:!nn(e,"lag")||Number.isFinite(e.lag)?null:S.INVALID_LINK_LAG:e.kind===at.DELETE?null:S.INVALID_VALUE}function Om(e){for(let t of e){let r=Lm(t);if(r!==null)return r}return null}function Nm(e,t){let r=new Set,i=new Map;for(let n of e){if(n.kind===at.CREATE){r.add(String(n.source)),r.add(String(n.target));continue}let o=t.getLink(n.linkId);o&&(r.add(String(o.source)),r.add(String(o.target)),i.set(n.linkId,{...o}))}return{activityIds:r,links:i}}function bm(e,t,r,i){return e.map((n,o)=>{let a=n.kind===at.CREATE?i?.get(o):void 0,s=ye(n,{port:t,newLinkId:a?()=>a:r.next});return{op:n,finalLinkId:s.applied?s.linkId:null,rejected:s.applied?null:s.rejected??S.INVALID}})}function Fm(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function sl(e,t,r){let i=Pm(e);return i!==null?{ok:!1,reason:i}:qo([Hm(e,r.sector.hoursPerDay)],e,t,r,e.kind===m.LINK_CREATE&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function cl(e,t,r){let i=Om(e.operations);if(i!==null)return{ok:!1,reason:i};let{hoursPerDay:n}=r.sector,o=e.operations.map(s=>Mm(s,n)),a=wm(e.operations);return qo(o,e,t,r,a)}function wm(e){let t=new Map;return e.forEach((r,i)=>{r.kind===at.CREATE&&r.linkId&&t.set(i,r.linkId)}),t.size>0?t:void 0}function xm(e,t){if(e===void 0)return;let r=new Map,i=new Set,n=()=>{let o=t.linkIdGen.next();for(;t.adapter.getLink(o)!==null||t.isLinkIdReserved(String(o))||i.has(String(o));)o=t.linkIdGen.next();return o};for(let[o,a]of e){let s=t.adapter.getLink(a)!==null||t.isLinkIdReserved(String(a))||i.has(String(a)),c=s?n():a;s||t.linkIdGen.bump(a),i.add(String(c)),r.set(o,c)}return r}function Mm(e,t){return e.kind===at.CREATE?{kind:at.CREATE,source:e.source,target:e.target,type:e.type,lag:Wt(e.lag??0,t)}:e.kind===at.UPDATE?{kind:at.UPDATE,linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:Wt(e.lag,t)}:{kind:at.DELETE,linkId:e.linkId}}async function qo(e,t,r,i,n){let{adapter:o,scheduler:a,sector:s,linkIdGen:c}=i;a.invalidateAllCaches();let{activityIds:l,links:d}=Nm(e,o),u=await rt(o,l),f=bm(e,o,c,xm(n,i));if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!==m.INLINE_EDIT)return{ok:!1,reason:f[0].rejected};let p=Um(f,d,o),{scheduledIds:y}=await Z({adapter:o,scheduler:a,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:i.now,options:r}),g=fr(f,d,o);return{ok:!0,linkVerdicts:f.map((T,L)=>T.rejected===null?{operationIndex:L,kind:T.op.kind,ok:!0,linkId:String(T.finalLinkId)}:{operationIndex:L,kind:T.op.kind,ok:!1,reason:T.rejected}),__beforeLinks:Fm(d),changes:await z(o,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:y,links:g,hoursPerDay:s.hoursPerDay})}}function Um(e,t,r){for(let i of e){if(i.rejected!==null)continue;let n=Bm(i.op,t,r);if(n!==null)return r.hasChildren(n)?Ot.ROOTS:String(n)}return null}function Bm(e,t,r){return e.kind===at.CREATE?e.target:e.kind===at.DELETE?t.get(e.linkId)?.target??null:r.getLink(e.linkId)?.target??null}function Hm(e,t){return e.kind===m.LINK_CREATE?{kind:at.CREATE,source:e.source,target:e.target,type:e.type,lag:Wt(e.lag??0,t)}:e.kind===m.LINK_UPDATE?{kind:at.UPDATE,linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:Wt(e.lag,t)}:{kind:at.DELETE,linkId:e.linkId}}async function ll(e,t,r){let{adapter:i,sector:n}=r;if(typeof e.newValue!="string")return{ok:!1,reason:S.INVALID_VALUE};if(!i.getActivity(e.activityId))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let a=e.column===_.CUSTOM_PREDECESSORS,{specs:s}=Ti(e.newValue),c=s.map(y=>({...y,lag:Wt(ki(y.lag),n.hoursPerDay)})),l=new Map;i.forEachActivity(y=>{y.correlativeId!=null&&l.set(String(y.correlativeId),y.id)});let d=y=>l.get(y)??null,u=a?i.getIncomingLinkIds(e.activityId):i.getOutgoingLinkIds(e.activityId),f=[];for(let y of u){let g=i.getLink(y);g&&f.push(g)}let p=a?Di({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):_i({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return qo(p.operations,e,t,r)}var jt={ACTIVITY_CREATION:"schedule_activity_creation",ACTIVITY_DELETION:"schedule_activity_deletion",ACTIVITY_MOVE:"schedule_activity_move",ACTIVITY_INDENT:"schedule_activity_indent",ACTIVITY_OUTDENT:"schedule_activity_outdent"};function St(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(o=>{M(o.parentId)&&t.push(o)}),t.sort(fl);let r=[];dl(r,t);let i=[],n=0;for(;r.length>0;){let o=r.pop();if(o.correlativeId!==n){let s=typeof o.correlativeId=="number"?o.correlativeId:void 0;i.push({activityId:String(o.id),before:s}),s!==void 0&&e.noteCorrelativeBefore?.(String(o.id),s),Wm(o,n)}n+=1;let a=Lr(String(o.id),e);a.sort(fl),dl(r,a)}return i}function dl(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function ul(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:zn}var fl=(e,t)=>ul(e)-ul(t);function Wm(e,t){e.correlativeId=t}function Jo(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let{workHours:i,realWorkHours:n}=hl(r,t);t.setActivityField(r,x.WORK_HOURS,i),t.setActivityField(r,x.REAL_WORK_HOURS,n);let o=t.getActivity(r);if(!o)break;let a=o.parentId;if(!a||M(a))break;r=a}}function pl(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||M(i)||Jo(i,t)}function yl(e,t,r){for(let i of e){if(r.hasChildren(i))continue;let n=r.getActivity(i);n&&r.setActivityField(i,x.REAL_WORK_HOURS,Nt(zr(n,x.WORK_HOURS),zr(n,x.PROGRESS)))}for(let i of t)r.setActivityField(i,x.REAL_WORK_HOURS,hl(i,r).realWorkHours)}function hl(e,t){let r=0,i=0;for(let n of t.getChildren(e)){let o=t.getActivity(n);if(!o)continue;let a=zr(o,x.WORK_HOURS);r+=a,i+=Vm(n,o,a,t)}return{workHours:r,realWorkHours:i}}function zr(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Vm(e,t,r,i){return i.hasChildren(e)?zr(t,x.REAL_WORK_HOURS):Nt(r,zr(t,x.PROGRESS))}function Xo(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0;for(let s of i){let c=t.getActivity(s);c&&(n+=jm(c,x.USED_COST))}t.setActivityField(r,x.USED_COST,n);let o=t.getActivity(r);if(!o)break;let a=o.parentId;if(!a||M(a))break;r=a}}function ml(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||M(i)||Xo(i,t)}function jm(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Zo(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0;for(let s of i){let c=t.getActivity(s);c&&(n+=Km(c,x.COST))}t.setActivityField(r,x.COST,n);let o=t.getActivity(r);if(!o)break;let a=o.parentId;if(!a||M(a))break;r=a}}function Il(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||M(i)||Zo(i,t)}function Km(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var on=Object.freeze({proplannerId:null,description:"",type:D.TASK,progress:0,constraintType:A.ASAP,constraintDate:null,autoScheduling:!0,assignedDefaultCalendar:!1,dateOrigin:null,cost:0,usedCost:0,realCost:0,workHours:0,realWorkHours:0,ponderator:0,hasCustomPonderator:!1,correlativeId:0,customId:null,subcontractId:null,isLookahead:!1,hasLookaheadTasks:!1,newActivityIds:[],hasNewActivities:!1,pendingRequestIds:[],responsableIds:[],tagIds:[],baselinePoints:[],baselineSnapshot:null,recursiveDurationHours:0,isCritical:!1,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}),gl="New Master Plan",Al="New Activity";var Ym=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],an=new Set(Ym);function Gm(e){let t=Object.getPrototypeOf(e);if(t!==null&&t!==Object.prototype)throw new Error("activity-create: override bag must be a plain object with no custom prototype");for(let r of Reflect.ownKeys(e))if(typeof r=="symbol"||!an.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function vl(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,i=Gm(e.activityOverrides??{}),n=e.numTasksInGantt===0?gl:Al,o=i.name??n,a=i.durationHours??e.sector.hoursPerDay,s=i.calendarId??e.sector.defaultCalendar,c=$m(r,e.fallbackStartDate,i.startDate),l={...on,...i,id:e.id,parentId:e.parentId,uniqueCorrelativeId:e.nextUniqueCorrelativeId,name:o,durationHours:a,calendarId:s,startDate:c,endDate:c},d=i.startDate?new Date(l.startDate):t.getClosestWorkTime({date:l.startDate,dir:j.FUTURE,task:l});if(!i.startDate&&r&&re(r.type)){let p=new Date(r.startDate);p.setUTCHours(0,0,0,0);let y=new Date(d);y.setUTCHours(0,0,0,0),y.getTime()!==p.getTime()&&(d=t.getClosestWorkTime({date:p,dir:j.FUTURE,task:l}))}let u=t.calculateEndDate({startDate:d,durationHours:l.durationHours,task:l});return{newTask:{...l,startDate:d,endDate:u,calendarDuration:Qt({type:l.type,startDate:d,endDate:u}),newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function $m(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}var hr={CREATE:"create",REPARENT:"reparent"};function zm(e){let t=e.type;if(t!==D.TASK&&t!==D.MILESTONE)return null;let r=e.startDate,i=e.endDate;return!(r instanceof Date)||!(i instanceof Date)?null:{type:t,startDate:new Date(r),endDate:new Date(i),durationHours:Number(e.durationHours??0),expectedProgressBaseline:typeof e.expectedProgressBaseline=="number"?e.expectedProgressBaseline:null,constraintType:e.constraintType??null,constraintDate:e.constraintDate instanceof Date?new Date(e.constraintDate):null,progress:Number(e.progress??0)}}function mr(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&pe(t.type):qm(t),i=Array.isArray(t.newActivityIds)?t.newActivityIds:[],o={isLookahead:!1,hasNewActivities:!0,newActivityIds:i.some(a=>String(a)===String(e.newChildId))?[...i]:[...i,e.newChildId]};return t.customId!=null&&t.customId!==""&&(o.customId=null),r&&(o.type=to,(e.promotionSource??hr.CREATE)===hr.CREATE&&(o.constraintType=A.ASAP,o.constraintDate=null)),{parentId:e.parentId,fields:o,promotionSnapshot:zm(t)}}function qm(e){return pe(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function Ir(e,t,r,i){let n=t,o=n==="0",a=Qo(e,n);if(i!==void 0){let c=a.find(l=>l.id===i);if(c){let l=Rt(c),d=a.map(Rt).filter(f=>f<l);return d.length===0?l-1:(Math.max(...d)+l)/2}}if(r!==void 0){let c=a.find(l=>l.id===r);if(c){let l=Rt(c),d=a.map(Rt).filter(f=>f>l);if(d.length===0)return l+1;let u=Math.min(...d);return(l+u)/2}}return a.length===0?0:Math.max(...a.map(Rt))+1}var We=Number.MAX_SAFE_INTEGER,Cl=Number.MAX_SAFE_INTEGER-1;function Rt(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:We}function Qo(e,t){return Lr(t,e)}function Sl(e,t,r){let i=e,n=De(e,r);for(;n!=null&&t.has(n);)i=n,n=De(n,r);return i}function gr(e,t,r){let i=new Set([e]),n=Gt(r.getActivity(e)?.parentId);for(;n!=="0"&&!i.has(n);){if(t.has(n))return!0;i.add(n),n=Gt(r.getActivity(n)?.parentId)}return!1}function De(e,t){let r=t.getActivity(e);if(!r)return null;let i=Gt(r.parentId),n=Ht(i,t),o=n.findIndex(a=>String(a)===String(e));return o<=0?null:n[o-1]??null}function Tl(e,t,r,i){let n=Ht(t,e).filter(c=>String(c)!==String(i)).map(c=>e.getActivity(c)).filter(c=>c!==null);if(n.length===0)return 0;let o=n.map(Rt);if(r<=0)return o[0]-1;if(r>=o.length)return o[o.length-1]+1;let a=o[r-1],s=o[r];return(a+s)/2}var Jm=new Set([...[...an].filter(e=>e!==x.DURATION_HOURS),"durationDays"]);function sn(e,t){if(e===void 0)return{ok:!0,value:{}};let r=Object.getPrototypeOf(e);if(r!==null&&r!==Object.prototype)return{ok:!1,reason:S.INVALID_VALUE};for(let o of Reflect.ownKeys(e))if(typeof o=="symbol"||!Jm.has(o))return{ok:!1,reason:S.INVALID_VALUE};let{durationDays:i,...n}=e;return i!==void 0&&(!Number.isFinite(i)||i<0)?{ok:!1,reason:S.INVALID_VALUE}:{ok:!0,value:{...n,...i===0&&(n.type===void 0||n.type===D.TASK)?{type:D.MILESTONE}:{},...i===void 0?{}:{durationHours:Ne(i,t)}}}}async function qr(e,t,r={}){let{adapter:i,scheduler:n,sector:o,calendars:a,activityIdGen:s,uidGen:c}=t;r.skipCacheInvalidation||n.invalidateAllCaches();let l=Xm(e,i);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=Qm(e.activityId,i,s,t.isActivityIdReserved),y=c.next(),g={id:p,parentId:f?null:e.parentId,sector:{id:o.id,hoursPerDay:o.hoursPerDay,defaultCalendar:oI(a)},numTasksInGantt:i.activityCount(),nextUniqueCorrelativeId:y,activityOverrides:e.overrides??{}},L=vl(g,{getActivity:v=>i.getActivity(v),calculateEndDate:v=>i.calculateEndDate(v),getClosestWorkTime:v=>i.getClosestWorkTime(v)}).newTask;L.realWorkHours=Nt(L.workHours,L.progress),eI(L,e,t,u,d,r);let C=r.insertionCorrelativeId??Ir(i,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);L.correlativeId=C;let E=new Set([p]);d&&E.add(d.id);let I=d!==null&&i.getChildren(d.id).length===0,b=I?d?.customId:null,B=r.skipBeforeSnap?new Map:await rt(i,E);i.addActivity(L),rI(e,p,d,i,I),b&&t.customIdTracker.releaseCustomId(b),r.skipRollupCascades||(pl(p,i),ml(p,i),Il(p,i));let k=iI(i,p,E,r);return{ok:!0,newId:p,parent:d,newActivity:L,beforeSnap:B,initialTouched:E,correlativeShifts:k}}function Xm(e,t){let r=M(e.parentId),i=r?null:t.getActivity(e.parentId);if(!r&&!i)return{ok:!1,reason:S.PARENT_NOT_FOUND};if(i!==null&&qe(i))return{ok:!1,reason:S.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:S.ANCHOR_SIBLING_CONFLICT};let a=e.afterSiblingId??e.beforeSiblingId,s=Zm(e,t,r,a);return s||{ok:!0,parent:i,anchorSiblingId:a,isRoot:r}}function Zm(e,t,r,i){if(i===void 0)return null;let n=t.getActivity(i);if(!n)return{ok:!1,reason:S.ANCHOR_SIBLING_NOT_FOUND};let o=r?"0":e.parentId;return(n.parentId==null?"0":String(n.parentId))!==o?{ok:!1,reason:S.ANCHOR_SIBLING_WRONG_PARENT}:null}function Qm(e,t,r,i){let n=()=>{let o=r.next();for(;t.activityExists(o)||i(String(o));)o=r.next();return o};return e===void 0||t.activityExists(e)||i(String(e))?n():(r.bump(e),e)}function tI(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function eI(e,t,r,i,n,o){let{adapter:a,customIdTracker:s}=r,c=tI(t);if(c!==void 0){if(c.length===0)return;if(!s.isCustomIdInUse(c)){s.registerCustomId(c);return}}let l=o.customIdReferenceId??i,d=l!==void 0,u=d?a.getActivity(l):n;e.customId=s.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function rI(e,t,r,i,n){if(!r)return;let o=mr({parentId:e.parentId,newChildId:t,isCurrentlyLeaf:n,getParent:a=>i.getActivity(a)??null});if(o){for(let[a,s]of Object.entries(o.fields))yt(i,o.parentId,a,s);o.promotionSnapshot&&i.setPromotionSnapshot(o.parentId,o.promotionSnapshot)}}function iI(e,t,r,i){if(i.skipCorrelativeRecompute)return[];let n=St(e).filter(o=>o.activityId!==String(t));for(let o of n)r.add(o.activityId);return n}async function nI(e,t,r,i,n){let{newId:o,newActivity:a,beforeSnap:s,initialTouched:c,correlativeShifts:l}=r,d={name:jt.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:o,created_duration:a.durationHours}};return t.eventSource!==void 0&&(d.properties.event_source=t.eventSource),z(e,{source:t,beforeSnap:s,touchedIds:c,scheduledIds:i,correlativeShifts:l,trackingEvents:[d],hoursPerDay:n})}async function El(e,t,r){let{adapter:i,scheduler:n,sector:o}=r,a=sn(e.overrides,o.hoursPerDay);if(!a.ok)return a;let s=await qr({...e,overrides:a.value},r);if(!s.ok)return s;let{newId:c}=s,l=s.newActivity.autoScheduling;i.setActivityField(c,"autoScheduling",!1);let d;try{d=await Z({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:c,recomputeParentsFrom:[c],preventSummaryTargetPullback:!0,now:r.now,options:t})}finally{i.setActivityField(c,"autoScheduling",l)}let{scheduledIds:u}=d;return{ok:!0,changes:await nI(i,e,s,u,o.hoursPerDay)}}function oI(e){for(let r of e.values())if(r.is_default)return r.id;let t=e.values().next();return!t.done&&t.value?t.value.id:"global"}function Ut(e,t){Jo(e,t),Xo(e,t),Zo(e,t)}function cn(e,t){let r=new Set,i=[];for(let n of e){let o=String(n);r.has(o)||(r.add(o),i.push(o))}for(;i.length>0;){let n=i.pop(),o=t.getChildren(n);for(let a of o){let s=String(a);r.has(s)||(r.add(s),i.push(s))}}return r}function ln(e,t){let r=new Set;for(let i of e){for(let n of t.getOutgoingLinkIds(i))r.add(String(n));for(let n of t.getIncomingLinkIds(i))r.add(String(n))}return[...r]}function aI(e){return e?{type:e.type,startDate:new Date(e.startDate),endDate:new Date(e.endDate),durationHours:e.durationHours,expectedProgressBaseline:e.expectedProgressBaseline,constraintType:e.constraintType,constraintDate:e.constraintDate?new Date(e.constraintDate):null,progress:e.progress}:null}function sI(e,t,r){let i=e.startDate;return!r||!(i instanceof Date)?{}:{endDate:r(i,t)}}function Ar(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,i=Number.isFinite(r),n=aI(e.promotionSnapshot)??(i?{type:Qe,durationHours:r,progress:0,autoScheduling:!0,constraintType:A.ASAP,constraintDate:null,hasNewActivities:!1,...sI(t,r,e.computeEndDate)}:{type:Qe});if(e.idsRemoved&&e.idsRemoved.size>0){let o=Array.isArray(t.newActivityIds)?t.newActivityIds:[];if(o.length>0){let a=o.filter(s=>!e.idsRemoved.has(s)&&!e.idsRemoved.has(String(s)));a.length!==o.length&&(n.newActivityIds=a)}}return t.hasLookaheadTasks&&(n.isLookahead=!0),{parentId:String(t.id),fields:n}}function dn(e){if(e.idsRemoved.size===0)return null;let t=e.parent.newActivityIds;if(!Array.isArray(t)||t.length===0)return null;let r=t,i=r.filter(n=>!e.idsRemoved.has(n)&&!e.idsRemoved.has(String(n)));return i.length===r.length?null:{parentId:String(e.parent.id),fields:{newActivityIds:[...i],hasNewActivities:i.length>0}}}var Dl=200;async function _l(e,t,r){let{adapter:i,scheduler:n,customIdTracker:o,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:S.ACTIVITY_IDS_EMPTY};for(let v of e.activityIds)if(!i.getActivity(v))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let s=e.activityIds.filter(v=>{let P=i.getActivity(v);return!(P?.correlativeId===0&&P.type===D.PROJECT)}),c=cn(s,i),l=ln(c,i),d=new Set;for(let v of e.activityIds){let P=i.getActivity(v);if(!P)continue;let q=P.parentId;if(M(q))continue;let $=String(q);c.has($)||d.add($)}let u=new Set([...c,...d]),f=await rt(i,u),p=new Map;for(let v of l){let P=i.getLink(v);P&&p.set(v,{...P})}let y=new Set,g=0;for(let v of c){g+=1,g%Dl===0&&await st();let P=i.getActivity(v);if(!P)continue;let q=M(P.parentId)?null:i.getActivity(String(P.parentId)),$=q?.hasNewActivities===!0&&q.newActivityIds.some(it=>String(it)===String(v));(P.isNewActivity===!0||$)&&y.add(v);let ot=P.customId;typeof ot=="string"&&ot.length>0&&o.releaseCustomId(ot)}for(let v of l)i.removeLink(v);let T=Jr(i,c),L=0;for(let v of c)L+=1,L%Dl===0&&await st(),i.removeActivity(v);for(let v of d){let P=i.getActivity(v);if(!P)continue;cI(P,y,i);let q=i.getChildren(v),$=Ar({parent:P,remainingChildIds:q.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(v),computeEndDate:(ot,it)=>i.calculateEndDate({startDate:ot,durationHours:it,task:P}),idsRemoved:c});if(!$){Pi(v,i);continue}for(let[ot,it]of Object.entries($.fields))yt(i,v,ot,it);if(P.customId==null||P.customId===""){let ot=De(v,i),it=ot?i.getActivity(ot)?.customId:null,Dt=o.generateCustomIdForRestoredChild(typeof it=="string"&&it?it:null);i.setActivityField(v,x.CUSTOM_ID,Dt)}}for(let v of d)Ut(v,i);let C=St(i),{scheduledIds:E}=await Z({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:Ot.ROOTS,recomputeParentsFrom:d,now:r.now,options:t}),I={name:jt.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:c.size}};e.eventSource!==void 0&&(I.properties.event_source=e.eventSource);let b=new Map;for(let[v,P]of p)b.set(v,P);let B=new Map;for(let v of c){let P=f.get(String(v));P&&B.set(String(v),P)}let k=await z(i,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:E,sirDetection:Ft.AFTER_DIFF,links:ea(p),trackingEvents:[I],hoursPerDay:a.hoursPerDay,correlativeShifts:C});return{ok:!0,changes:T.length>0?{...k,viewState:T}:k,__beforeSnap:B,__beforeLinks:b}}function cI(e,t,r){let i=dn({parent:e,idsRemoved:t});if(i)for(let[n,o]of Object.entries(i.fields))yt(r,i.parentId,n,o)}function Jr(e,t){let r=[];for(let i of t){let n=e.isChecked(i),o=e.isVisible(i);!n&&o||r.push({activityId:String(i),...n?{checked:{before:!0,after:!1}}:{},...o?{}:{visible:{before:!1,after:!0}}})}return r}function ea(e){let t=[];for(let[r,i]of e.entries())t.push({id:r,kind:N.DELETED,fields:{source:{before:String(i.source),after:void 0},target:{before:String(i.target),after:void 0},type:{before:i.type,after:void 0},lag:{before:Number(i.lag),after:void 0}},after:null});return t}async function Pl(e,t,r){let i=lI(e,r);if(i)return{ok:!1,reason:i};let n=uI(e,r);if(!n.ok)return n;let o=e.mode===pt.REPLACE?new Set(r.adapter.getAllIds().map(I=>String(I))):new Set,a=e.mode===pt.REPLACE?await rt(r.adapter,o):new Map,s=e.mode===pt.REPLACE?II(r):new Map,c=e.mode===pt.REPLACE?Jr(r.adapter,o):[];r.scheduler.invalidateAllCaches();let l=[];if(e.mode===pt.REPLACE){for(let I of s.keys()){let b=ye({kind:at.DELETE,linkId:I},{port:r.adapter});if(!b.applied)return{ok:!1,reason:b.rejected??S.INVALID};l.push({op:{kind:at.DELETE,linkId:I},finalLinkId:I,rejected:null})}for(let I of o){let b=r.adapter.getActivity(I)?.customId;typeof b=="string"&&b.length>0&&r.customIdTracker.releaseCustomId(b),r.adapter.removeActivity(I)}}let d=await mI(e,n.plan.items,r);if(!d.ok)return d;let u=Ll(e)?[]:St(r.adapter),f=new Set(n.plan.items.map(I=>String(I.activityId))),p=u.filter(I=>!f.has(I.activityId)),y=e.mode===pt.REPLACE?new Set(o):new Set;cr(r.adapter,u,f,a,y);for(let I of n.plan.items)y.add(String(I.activityId));let g=n.plan.links.map(I=>({operation:{kind:at.CREATE,source:I.source,target:I.target,type:I.type,lag:Wt(I.lag??0,r.sector.hoursPerDay)},linkId:I.linkId})),T=Ci(g,{port:r.adapter,preserved:s});if(!T.applied)return{ok:!1,reason:T.rejected??S.INVALID};for(let{operation:I,linkId:b}of g)l.push({op:I,finalLinkId:b,rejected:null});let L=n.plan.items.map(I=>I.activityId),{scheduledIds:C}=await Z({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.items.length>0||e.links.length>0?Ot.ROOTS:null,recomputeParentsFrom:L,now:r.now,options:t}),E=await z(r.adapter,{source:e,beforeSnap:a,touchedIds:y,scheduledIds:C,links:fr(l,s,r.adapter),hoursPerDay:r.sector.hoursPerDay,correlativeShifts:p,...e.mode===pt.REPLACE?{sirDetection:Ft.AFTER_DIFF}:{}});return{ok:!0,changes:c.length>0?{...E,viewState:c}:E,...e.mode===pt.REPLACE?{__beforeSnap:a,__beforeLinks:gI(s)}:{}}}function lI(e,t){if(e.mode!==pt.APPEND&&e.mode!==pt.REPLACE)return S.INVALID;let r=new Set,i=new Set;for(let o of e.items){if(o.batchId.length===0||r.has(o.batchId))return S.INVALID;if(r.add(o.batchId),o.index!==void 0&&(!Number.isInteger(o.index)||o.index<0))return S.INVALID;if(o.activityId!==void 0){let a=String(o.activityId);if(a.length===0||a==="0"||i.has(a))return S.INVALID;i.add(a)}}for(let o of e.items)if(!ra(o.parent,!0,e.mode,r,t))return S.PARENT_NOT_FOUND;if(dI(e.items))return S.INVALID;let n=new Set;for(let o of e.links){if(!Object.values(H).includes(o.type))return S.INVALID_LINK_TYPE;if(o.lag!==void 0&&!Number.isFinite(o.lag))return S.INVALID_LINK_LAG;if(!ra(o.source,!1,e.mode,r,t)||!ra(o.target,!1,e.mode,r,t))return S.ACTIVITY_NOT_FOUND;if(o.linkId!==void 0){let a=String(o.linkId);if(a.length===0||n.has(a))return S.INVALID;n.add(a)}}return null}function ra(e,t,r,i,n){return typeof e=="string"?e==="0"?t:r===pt.APPEND&&n.adapter.getActivity(String(e))!==null:e!==null&&e.batchId.length>0&&i.has(e.batchId)}function dI(e){let t=new Map;for(let i of e)typeof i.parent!="string"&&t.set(i.batchId,i.parent.batchId);let r=new Set;for(let i of e){let n=new Set,o=i.batchId;for(;o!==void 0&&!r.has(o);){if(n.has(o))return!0;n.add(o),o=t.get(o)}for(let a of n)r.add(a)}return!1}function uI(e,t){let r=new Map;for(let d of e.items){let u=sn(d.overrides,t.sector.hoursPerDay);if(!u.ok)return u;r.set(d.batchId,u.value)}let i=new Map,n=new Set;for(let d of e.items){let u=fI(d.activityId,e.mode,n,t);n.add(String(u)),i.set(d.batchId,u)}let o=new Set,a=e.links.map(d=>{let u=pI(d.linkId,e.mode,o,t);return o.add(String(u)),u}),s=yI(e,i,t),c=[];for(let d of e.items){let u=i.get(d.batchId),f=s.get(d.batchId);if(u===void 0||f===void 0)return{ok:!1,reason:S.INVALID};let p=typeof d.parent=="string"?null:d.parent.batchId,y=typeof d.parent=="string"?d.parent:i.get(d.parent.batchId);if(y===void 0)return{ok:!1,reason:S.PARENT_NOT_FOUND};c.push({input:d,activityId:u,parentId:y,parentBatchId:p,insertionCorrelativeId:f,overrides:r.get(d.batchId)??{}})}let l=[];for(let[d,u]of e.links.entries()){let f=Rl(u.source,i),p=Rl(u.target,i),y=a[d];if(f===null||p===null||y===void 0)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};l.push({source:f,target:p,type:u.type,lag:u.lag??0,linkId:y})}return{ok:!0,plan:{items:c,links:l}}}function fI(e,t,r,i){if(e!==void 0&&(t===pt.REPLACE||i.adapter.getActivity(e)===null&&!i.isActivityIdReserved(String(e)))&&!r.has(String(e)))return i.activityIdGen.bump(e),e;let o=i.activityIdGen.next();for(;r.has(String(o))||t===pt.APPEND&&(i.adapter.getActivity(o)!==null||i.isActivityIdReserved(String(o)));)o=i.activityIdGen.next();return o}function pI(e,t,r,i){if(e!==void 0&&(t===pt.REPLACE||i.adapter.getLink(e)===null&&!i.isLinkIdReserved(String(e)))&&!r.has(String(e)))return i.linkIdGen.bump(e),e;let o=i.linkIdGen.next();for(;r.has(String(o))||t===pt.APPEND&&(i.adapter.getLink(o)!==null||i.isLinkIdReserved(String(o)));)o=i.linkIdGen.next();return o}function yI(e,t,r){if(Ll(e)){let s=r.adapter.activityCount();return new Map(e.items.map((c,l)=>[c.batchId,s+l]))}let i=new Set(Array.from(t.values(),s=>String(s))),n=new Map;for(let s of e.items){let c=t.get(s.batchId);if(c===void 0)continue;let l=typeof s.parent=="string"?s.parent:t.get(s.parent.batchId);if(l===void 0)continue;let d=String(l),u=n.get(d);u||(u={existing:e.mode===pt.REPLACE||typeof s.parent!="string"&&t.has(s.parent.batchId)?[]:Qo(r.adapter,d).sort((g,T)=>Rt(g)-Rt(T)||String(g.id).localeCompare(String(T.id))).map(g=>String(g.id)),newIdsByTarget:new Map},n.set(d,u));let f=s.index===void 0?u.existing.length:Math.min(s.index,u.existing.length),p=u.newIdsByTarget.get(f)??[];p.push(String(c)),u.newIdsByTarget.set(f,p)}let o=new Map,a=new Map(Array.from(t,([s,c])=>[String(c),s]));for(let s of n.values()){let c=[];for(let d=0;d<=s.existing.length;d+=1){for(let f of s.newIdsByTarget.get(d)??[])c.push(f);let u=s.existing[d];u!==void 0&&c.push(u)}let l=0;for(;l<c.length;){if(!i.has(c[l])){l+=1;continue}let d=l;for(;l<c.length&&i.has(c[l]);)l+=1;let u=l-d,f=d>0?kl(c[d-1],r):null,p=l<c.length?kl(c[l],r):null;for(let y=0;y<u;y+=1){let g=c[d+y],T=a.get(g);T!==void 0&&o.set(T,hI(f,p,y+1,u))}}}return o}function Ll(e){return e.mode===pt.APPEND&&e.items.every(t=>t.parent==="0"&&t.index===void 0)}function kl(e,t){let r=t.adapter.getActivity(e);return r?Rt(r):0}function hI(e,t,r,i){return e!==null&&t!==null&&t>e?e+(t-e)*r/(i+1):e!==null?e+r:t!==null?t-(i-r+1):r-1}async function mI(e,t,r){let i=new Map,n=[];for(let a of t){if(a.parentBatchId===null){n.push(a);continue}let s=i.get(a.parentBatchId)??[];s.push(a),i.set(a.parentBatchId,s)}for(let a=0;a<n.length;a+=1){let s=n[a],c=await qr({kind:m.ACTIVITY_CREATE,parentId:s.parentId,activityId:s.activityId,overrides:s.overrides,...e.eventSource===void 0?{}:{eventSource:e.eventSource}},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,skipCacheInvalidation:!0,skipRollupCascades:!0,insertionCorrelativeId:s.insertionCorrelativeId});if(!c.ok)return c;for(let l of i.get(s.input.batchId)??[])n.push(l)}if(n.length!==t.length)return{ok:!1,reason:S.INVALID};let o=new Set;for(let a=n.length-1;a>=0;a-=1){let s=n[a].parentId;s==="0"||o.has(String(s))||(o.add(String(s)),Ut(s,r.adapter))}return{ok:!0}}function Rl(e,t){return typeof e=="string"?e:t.get(e.batchId)??null}function II(e){return new Map(e.adapter.getAllLinks().map(t=>[String(t.id),{...t}]))}function gI(e){return new Map(Array.from(e,([t,r])=>[String(t),r]))}function Ol(e,t){let{adapter:r}=t,i=e.activityId,n=r.getActivity(i);if(!n)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let o=n.pendingRequestIds??[],a=e.pendingRequests.map(l=>l.id);r.setActivityField(e.activityId,"pendingRequestIds",a);let s=r.getActivity(i);if(!s)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let c={id:i,kind:N.UPDATED,fields:{pendingRequestIds:{before:o,after:a}},after:et(s)};return{ok:!0,changes:{source:e,activities:[c],links:[],calendars:[],trackingEvents:[]}}}function Nl(e){let t=new Map;for(let r of e){let i=r.proplannerId;typeof i=="number"&&Number.isSafeInteger(i)&&i>0&&t.set(i,String(r.id))}return t}function bl(e,t,r){let i=new Set(t.map(({id:n})=>String(n)));for(let n of e)if((n.proplannerId==null||n.proplannerId===0)&&!i.has(String(n.id)))throw new Error(`persistence-acknowledge: missing ${r} proplannerId for "${String(n.id)}"`)}function AI(e,t,r,i,n,o){let a=String(e.id);if(a.length===0||n.has(a))throw new Error(`persistence-acknowledge: duplicate or empty ${t} id "${a}"`);if(!Number.isSafeInteger(e.proplannerId)||e.proplannerId<=0)throw new Error(`persistence-acknowledge: invalid ${t} proplannerId ${String(e.proplannerId)}`);if(o.has(e.proplannerId))throw new Error(`persistence-acknowledge: duplicate ${t} proplannerId ${String(e.proplannerId)}`);let s=r(a);if(!s.exists)throw new Error(`persistence-acknowledge: unknown ${t} id "${a}"`);if(s.current!==null&&s.current!==0&&s.current!==e.proplannerId)throw new Error(`persistence-acknowledge: ${t} "${a}" already has proplannerId ${String(s.current)}`);let c=i.get(e.proplannerId);if(c!==void 0&&c!==a)throw new Error(`persistence-acknowledge: ${t} proplannerId ${String(e.proplannerId)} already belongs to "${c}"`);n.add(a),o.add(e.proplannerId)}function Fl(e,t,r,i){let n=new Set,o=new Set;for(let a of e)AI(a,t,r,i,n,o)}async function wl(e,t){let r=e.filter(s=>{let c=t.adapter.getActivity(String(s.activityId));return c!==null&&c.progress!==s.progress}),i=new Set(r.map(s=>String(s.activityId))),n=Br(t.adapter,i),o=new Set(i);for(let s of n)o.add(String(s));let a=await rt(t.adapter,o);return t.adapter.batchUpdate(()=>{for(let s of r){let c=String(s.activityId);t.adapter.setActivityField(c,"progress",s.progress),t.adapter.setActivityField(c,"autoScheduling",Pe(s.progress))}Hs(n,t.adapter),yl(i,n,t.adapter)}),[...await Vi(t.adapter,a,o)]}async function xl(e,t){let r=e.activities??[],i=e.links??[],n=t.adapter.getAllActivities(),o=t.adapter.getAllLinks(),a=e.checkpoint?.activities??n,s=e.checkpoint?.links??o,c=new Map(a.map(y=>[String(y.id),y])),l=new Map(s.map(y=>[String(y.id),y])),d=Nl(a),u=Nl(s);Fl(r,"activity",y=>{let g=c.get(y);return{exists:g!==void 0,current:g?.proplannerId??null}},d),Fl(i,"link",y=>{let g=l.get(y);return{exists:g!==void 0,current:g?.proplannerId??null}},u),bl(a,r,"activity"),bl(s,i,"link");let f=[],p=[];return t.adapter.batchUpdate(()=>{for(let y of r){let g=t.adapter.getActivity(y.id);if(!g||g.proplannerId===y.proplannerId)continue;let T=g.proplannerId;t.adapter.setActivityField(y.id,"proplannerId",y.proplannerId),f.push({id:y.id,kind:N.UPDATED,fields:{proplannerId:{before:T,after:y.proplannerId}},after:{...g,proplannerId:y.proplannerId}})}for(let y of i){let g=t.adapter.getLink(y.id);if(!g||g.proplannerId===y.proplannerId)continue;let T=g.proplannerId;t.adapter.setLinkProplannerId(y.id,y.proplannerId),p.push({id:y.id,kind:N.UPDATED,fields:{proplannerId:{before:T,after:y.proplannerId}},after:{...g,proplannerId:y.proplannerId}})}}),{ok:!0,changes:{source:e,activities:f,links:p,calendars:[],trackingEvents:[]}}}async function Ml(e,t,r){if(vI(e))return{ok:!1,reason:S.INVALID_VALUE};let i=[...new Set(e.activityIds.map(String))];if(e.acknowledgePersistedLookahead===!0&&i.some(s=>!r.isActivityIdReserved(s)))return{ok:!1,reason:S.INVALID};let o=i.map(s=>r.adapter.getActivity(s));if(o.some(s=>!s))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let a=[];for(let[s,c]of i.entries()){let l=o[s];if(!l)continue;let d={};l.isLookahead!==e.isLookahead&&(d.isLookahead={before:l.isLookahead,after:e.isLookahead},r.adapter.setActivityField(c,"isLookahead",e.isLookahead)),l.hasLookaheadTasks!==e.hasLookaheadTasks&&(d.hasLookaheadTasks={before:l.hasLookaheadTasks,after:e.hasLookaheadTasks},r.adapter.setActivityField(c,"hasLookaheadTasks",e.hasLookaheadTasks)),Object.keys(d).length!==0&&a.push({id:c,kind:N.UPDATED,fields:d,after:{...l,isLookahead:e.isLookahead,hasLookaheadTasks:e.hasLookaheadTasks}})}return e.persistedProgress!==void 0&&(await wl([{activityId:i[0],progress:e.persistedProgress}],r)).length>0?(await Z({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.persistedProgress===0?i[0]:null,recomputeParentsFrom:[],now:r.now,options:t}),{ok:!0,changes:await z(r.adapter,{source:e,beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:r.sector.hoursPerDay})}):{ok:!0,changes:{source:e,activities:a,links:[],calendars:[],trackingEvents:[]}}}function vI(e){let t=e.persistedProgress;return t!==void 0&&(e.activityIds.length!==1||!Number.isFinite(t)||t<0||t>100)}function na(e,t){let{adapter:r}=t,i=new Set(e.conversionRootIds.map(f=>String(f)));if(i.size===0)throw new Error("Conversion requires at least one root");for(let f of i)LI(f,r);let n=r.getVisualOrderIds().filter(f=>i.has(f)&&!gr(f,i,r)),o=n.map(f=>CI(f,r)),a=o.map(({conversionRootId:f,convertedActivities:p})=>({conversionRootId:f,convertedActivities:p})),s=o.flatMap(f=>f.milestoneMoves),c=o.flatMap(f=>f.activityIdsToDelete),l=o.map(f=>f.formerParent),d=new Set(c),u=ln(d,r);return{sourceStateRevision:t.stateRevision,conversionRootIds:n,conversionGroups:a,milestoneMoves:s,activityIdsToDelete:c,linkIdsToDelete:u,formerParents:l}}async function Hl(e,t,r){if(e.expectedStateRevision!==r.stateRevision)return{ok:!1,reason:S.STALE_STATE_REVISION};let i=na(e,r);if(!OI(i,r.adapter))return{ok:!1,reason:S.HIERARCHY_CYCLE};let{adapter:n,scheduler:o}=r;o.invalidateAllCaches();let a=await DI(i,n);_I(i,r),Wl(i,n),kI(i,a.deletedIds,n);let s=RI(i,n);cr(n,s,a.deletedIds,a.beforeSnap,a.touchedIds);let{scheduledIds:c}=await Z({adapter:n,scheduler:o,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:a.touchedIds,now:r.now,options:t,recomputeParentProgress:!0}),l=await z(n,{source:e,beforeSnap:a.beforeSnap,touchedIds:a.touchedIds,scheduledIds:c,sirDetection:"after-diff",links:ea(a.beforeLinks),hoursPerDay:r.sector.hoursPerDay,correlativeShifts:s});return PI(i,a,l)}function CI(e,t){let r=ia(e,t),i=cn([e],t);if(i.delete(e),i.size===0)throw new Error(`Conversion root ${e} has no descendants`);let n=t.getVisualOrderIds().filter(c=>i.has(c)).map(c=>ia(c,t));Bl(r);for(let c of n)Bl(c);let o=n.filter(c=>c.type!==D.MILESTONE),a=n.filter(c=>c.type===D.MILESTONE),s=SI(r,o);return{conversionRootId:e,convertedActivities:o.map(c=>TI(c,s)),milestoneMoves:EI(r,a),activityIdsToDelete:o.map(c=>c.id),formerParent:{activity:et(r),hasConvertedActivities:o.length>0}}}function SI(e,t){let r=new Map;t.length>0&&r.set(e.id,Ul(e));for(let i of t)r.set(i.id,Ul(i));return r}function TI(e,t){let r=et(e),i=Gt(e.parentId),n=t.get(i);return r.parentId=n===void 0?null:String(n),r}function EI(e,t){let r=[],i=Gt(e.parentId),n=e.id;for(let o of t)r.push({activityId:o.id,parentId:i,afterSiblingId:n}),n=o.id;return r}async function DI(e,t){let r=new Set(e.activityIdsToDelete),i=new Set([...e.conversionRootIds,...e.activityIdsToDelete,...e.milestoneMoves.map(({activityId:n})=>n),...e.milestoneMoves.map(({parentId:n})=>n).filter(n=>n!=="0")]);return{deletedIds:r,touchedIds:i,beforeSnap:await rt(t,i),beforeLinks:NI(e.linkIdsToDelete,t),viewStateChanges:Jr(t,r)}}function _I(e,t){for(let r of e.activityIdsToDelete){let i=t.adapter.getActivity(r)?.customId;i&&t.customIdTracker.releaseCustomId(i)}}function Wl(e,t){for(let r of e.milestoneMoves)t.setActivityFields(r.activityId,{parentId:r.parentId,correlativeId:Ir(t,r.parentId,r.afterSiblingId,void 0)});for(let r of e.linkIdsToDelete)t.removeLink(r);for(let r of[...e.activityIdsToDelete].reverse())t.removeActivity(r);for(let{activity:r}of e.formerParents)t.setActivityField(r.id,x.TYPE,D.TASK)}function kI(e,t,r){for(let{activity:i,hasConvertedActivities:n}of e.formerParents){let o=ia(i.id,r),a=dn({parent:o,idsRemoved:t});r.setActivityFields(i.id,{isLookahead:i.isLookahead||n,hasLookaheadTasks:i.hasLookaheadTasks||n,...a?.fields??{}})}}function RI(e,t){for(let{activity:r}of e.formerParents)Ut(r.parentId,t);return St(t)}function PI(e,t,r){let i=new Map;for(let n of t.deletedIds){let o=t.beforeSnap.get(n);o&&i.set(n,o)}return{ok:!0,changes:t.viewStateChanges.length===0?r:{...r,viewState:t.viewStateChanges},conversionGroups:e.conversionGroups.map(({conversionRootId:n,convertedActivities:o})=>({conversionRootId:n,convertedActivities:o.map(a=>et(a))})),__beforeSnap:i,__beforeLinks:t.beforeLinks}}function LI(e,t){let r=t.getActivity(e);if(!r)throw new Error(`Conversion root ${e} was not found`);if(r.type===D.PROJECT&&r.correlativeId===0)throw new Error(`Conversion root ${e} is the visual project root`)}function ia(e,t){let r=t.getActivity(e);if(!r)throw new Error(`Conversion activity ${e} is missing`);return r}function Ul(e){if(e.proplannerId==null)throw new Error(`Conversion activity ${e.id} has no persisted identifier`);return e.proplannerId}function Bl(e){if(!Number.isFinite(e.startDate.getTime()))throw new Error(`Conversion activity ${e.id} has invalid startDate`);if(!Number.isFinite(e.endDate.getTime()))throw new Error(`Conversion activity ${e.id} has invalid endDate`)}function OI(e,t){let r=t.fork();return Wl(e,r),Le({port:t,proposedPort:r,currentLinks:t.getAllLinks(),proposedLinks:r.getAllLinks()}).ok}function NI(e,t){let r=new Map;for(let i of e){let n=t.getLink(i);n&&r.set(i,{...n})}return r}function un(e,t){let r=new Set;for(let n of e)r.add(String(n));let i=[];for(let n of t.getAllLinks()){let o=String(n.source),a=String(n.target);!r.has(o)&&!r.has(a)||(Vl(a,o,t)||Vl(o,a,t))&&i.push(String(n.id))}return i}function Vl(e,t,r){let i=String(e),n=new Set;for(;i!=null;){if(n.has(i))return!1;n.add(i);let o=r.getActivity(i);if(!o)return!1;let a=o.parentId;if(a===null||M(a))return!1;let s=a;if(s===t)return!0;i=s}return!1}function fn(e,t){let r=e.getAllLinks();return!Le({port:e,currentLinks:r,proposedLinks:r,proposal:{reparented:t}}).ok}function pn(e,t){let r=new Set;if(e.length===0)return r;let i=new Map(e.map(o=>[o.activityId,o.newParentId]));if(!fn(t,i))return r;let n=new Map;for(let o of e){let a=new Map(n);if(a.set(o.activityId,o.newParentId),fn(t,a)){r.add(o.activityId);continue}n.set(o.activityId,o.newParentId)}return r}async function jl(e,t,r){let{adapter:i,scheduler:n,sector:o}=r;n.invalidateAllCaches();let a=i.getActivity(e.activityId);if(!a)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let s=M(e.parentId);if(!s&&!i.getActivity(e.parentId))return{ok:!1,reason:S.PARENT_NOT_FOUND};if(!s&&(e.parentId===e.activityId||i.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:S.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:S.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let b=i.getActivity(c);if(!b)return{ok:!1,reason:S.ANCHOR_SIBLING_NOT_FOUND};if((b.parentId===null?"0":String(b.parentId))!==e.parentId)return{ok:!1,reason:S.ANCHOR_SIBLING_WRONG_PARENT}}let l=a.parentId,d=Gt(l),u=String(e.parentId),f=d!==u;if(f){let b=new Map([[e.activityId,s?null:e.parentId]]);if(fn(i,b))return{ok:!1,reason:S.HIERARCHY_CYCLE}}let p=new Set([e.activityId]);f?(d!=="0"&&p.add(d),u!=="0"&&p.add(u)):d!=="0"&&p.add(d);let y=await rt(i,p);f&&i.setActivityField(e.activityId,x.PARENT,u);let g=Ir(i,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(i.setActivityField(e.activityId,x.CORRELATIVE_ID,g),f){if(!s){let b=i.getActivity(e.parentId);if(b){let B=b.customId,k=pe(b.type)&&i.getChildren(e.parentId).filter(P=>P!==e.activityId).length===0,v=mr({parentId:e.parentId,newChildId:e.activityId,getParent:P=>i.getActivity(P)??null,isCurrentlyLeaf:k,promotionSource:hr.REPARENT});if(v){for(let[P,q]of Object.entries(v.fields))yt(i,v.parentId,P,q);v.promotionSnapshot&&i.setPromotionSnapshot(v.parentId,v.promotionSnapshot),v.fields.customId===null&&en(B,r.customIdTracker)}}}if(d!=="0"){let b=i.getActivity(d);if(b){let B=i.getChildren(d),k=Ar({parent:b,remainingChildIds:B.map(String),defaultDurationHours:o.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(d),computeEndDate:(v,P)=>i.calculateEndDate({startDate:v,durationHours:P,task:b}),idsRemoved:new Set([e.activityId])});if(k){for(let[ot,it]of Object.entries(k.fields))yt(i,d,ot,it);let v=De(d,i),P=v?i.getActivity(v)?.customId:null,q=typeof P=="string"&&P?P:null,$=r.customIdTracker.generateCustomIdForRestoredChild(q);i.setActivityField(d,x.CUSTOM_ID,$)}}}}f&&(d!=="0"&&Ut(d,i),s||Ut(e.parentId,i));let T=St(i);for(let b of T){if(p.add(b.activityId),y.has(b.activityId))continue;let B=i.getActivity(b.activityId);if(!B)continue;let k=et(B);b.before!==void 0&&(k.correlativeId=b.before),y.set(b.activityId,k)}let L=f&&d!=="0"?i.getChildren(d).map(String):[],{scheduledIds:C}=await Z({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,...L],now:r.now,options:t,recomputeParentProgress:f}),E=f?un([e.activityId],i):[],I={name:jt.ACTIVITY_MOVE,properties:{activity_id:e.activityId,new_parent_id:e.parentId,after_sibling_id:e.afterSiblingId??null,before_sibling_id:e.beforeSiblingId??null,invalid_link_ids:E.map(String)}};return e.eventSource!==void 0&&(I.properties.event_source=e.eventSource),{ok:!0,changes:await z(i,{source:e,beforeSnap:y,touchedIds:p,scheduledIds:C,sirDetection:Ft.BEFORE_DIFF,trackingEvents:[I],hoursPerDay:o.hoursPerDay})}}function yn(e,t){let r=new Set(e),i=[],n=[],o=new Set,a=new Set(r),s=[...e].sort((d,u)=>{let f=t.getActivity(d),p=t.getActivity(u),y=f?Rt(f):We,g=p?Rt(p):We;return y-g});for(let d of s){if(!t.getActivity(d)){i.push({activityId:d,reason:S.ACTIVITY_NOT_FOUND}),a.delete(d);continue}if(gr(d,o,t))continue;let f=ls(d,a,t);if(f==null){i.push({activityId:d,reason:S.INDENT_NO_ELIGIBLE_SIBLING}),a.delete(d);continue}let p=t.getActivity(d)?.parentId,y=M(p)?"0":String(p);n.push({activityId:d,newParentId:f,oldParentId:y}),o.add(d)}let c=pn(n,t);for(let d of c)i.push({activityId:d,reason:S.HIERARCHY_CYCLE});let l=n.filter(d=>!c.has(d.activityId));return{moves:n,cyclicMoveIds:c,allowedMoves:l,failed:i}}async function Kl(e,t,r){let{adapter:i,scheduler:n,sector:o}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:S.ACTIVITY_IDS_EMPTY};let a=new Set,s=[],c=yn(e.activityIds,i),l=[...c.failed];for(let C of c.moves)a.add(String(C.activityId)),a.add(String(C.newParentId)),C.oldParentId!=="0"&&a.add(String(C.oldParentId));let d=c.allowedMoves,u=await rt(i,a);for(let{activityId:C,newParentId:E}of d)i.setActivityField(C,x.PARENT,E),i.setActivityField(C,x.CORRELATIVE_ID,Cl),s.push(C);let f=new Set;for(let{activityId:C,newParentId:E}of d){if(f.has(E))continue;f.add(E);let I=i.getActivity(E);if(!I)continue;let b=I.customId,B=pe(I.type)&&i.getChildren(E).filter(P=>!s.includes(P)).length===0,k=I.hasNewActivities&&I.newActivityIds.some(P=>String(P)===String(C)),v=mr({parentId:E,newChildId:C,getParent:P=>i.getActivity(P)??null,isCurrentlyLeaf:B,promotionSource:hr.REPARENT});if(v){for(let[P,q]of Object.entries(v.fields))yt(i,v.parentId,P,q);v.promotionSnapshot&&i.setPromotionSnapshot(v.parentId,v.promotionSnapshot),k||(i.setActivityField(E,x.HAS_NEW_ACTIVITIES,!1),i.setActivityField(E,x.NEW_ACTIVITIES_ARRAY,[]))}i.setActivityField(E,x.CONSTRAINT_TYPE,A.ASAP),i.setActivityField(E,x.CONSTRAINT_DATE,null),i.setActivityField(E,x.CUSTOM_ID,null),en(b,r.customIdTracker)}let p=new Set;for(let C of d)C.oldParentId!=="0"&&p.add(C.oldParentId),p.add(C.newParentId);for(let C of p)Ut(C,i);let y=St(i);for(let C of y){if(a.add(C.activityId),u.has(C.activityId))continue;let E=i.getActivity(C.activityId);if(!E)continue;let I=et(E);C.before!==void 0&&(I.correlativeId=C.before),u.set(C.activityId,I)}let{scheduledIds:g}=await Z({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:s,now:r.now,options:t}),T=un(s,i),L={name:jt.ACTIVITY_INDENT,properties:{activity_ids:s,failed:l.map(C=>({activity_id:C.activityId,reason:C.reason})),invalid_link_ids:T}};return e.eventSource!==void 0&&(L.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(C=>{let E=l.find(I=>String(I.activityId)===String(C));return E?{activityId:String(C),ok:!1,reason:E.reason}:{activityId:String(C),ok:!0}}),changes:await z(i,{source:e,beforeSnap:u,touchedIds:a,scheduledIds:g,trackingEvents:[L],hoursPerDay:o.hoursPerDay})}}async function Yl(e,t,r){let{adapter:i,scheduler:n,sector:o}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:S.ACTIVITY_IDS_EMPTY};let a=new Set(e.activityIds),s=new Map,c=new Map;for(let k of e.activityIds){let v=k;i.getActivity(v)&&(s.set(v,qn(v,i)),c.set(v,Sl(v,a,i)))}let l=new Set,d=[],u=[],f=new Set,p=[],y=new Set,g=[...e.activityIds].sort((k,v)=>{let P=i.getActivity(k),q=i.getActivity(v),$=P?Rt(P):We,ot=q?Rt(q):We;return $-ot});for(let k of g){let v=k,P=i.getActivity(v);if(!P){d.push({activityId:v,reason:S.ACTIVITY_NOT_FOUND});continue}if(gr(v,y,i))continue;let q=P.parentId;if(M(q)){d.push({activityId:v,reason:S.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let $=String(q),ot=i.getActivity($);if(!ot){d.push({activityId:v,reason:S.ACTIVITY_NOT_FOUND});continue}let it=ot.parentId;if(M(it)){d.push({activityId:v,reason:S.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let Dt=String(it),wt=qn($,i)+1,ht=c.get(v);if(ht!=null&&a.has(ht)){let Ye=s.get(ht)??-1,Ge=s.get(v)??-1;Ye>=0&&Ge>=0&&(wt+=Ge-Ye)}p.push({activityId:v,grandparentKey:Dt,oldParentKey:$,targetIndexInGrandparent:wt}),y.add(v),l.add(String(v)),l.add(String($)),Dt!=="0"&&l.add(String(Dt)),f.add($)}let T=pn(p.map(k=>({activityId:k.activityId,newParentId:k.grandparentKey})),i);for(let k of T)d.push({activityId:k,reason:S.HIERARCHY_CYCLE});let L=p.filter(k=>!T.has(k.activityId)),C=await rt(i,l);for(let k of L){i.setActivityField(k.activityId,x.PARENT,k.grandparentKey);let v=Tl(i,k.grandparentKey,k.targetIndexInGrandparent,k.activityId);i.setActivityField(k.activityId,x.CORRELATIVE_ID,v),u.push(k.activityId)}for(let k of f){let v=i.getActivity(k);if(!v)continue;let P=i.getChildren(k),q=Ar({parent:v,remainingChildIds:P.map(String),defaultDurationHours:o.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(k),computeEndDate:(wt,ht)=>i.calculateEndDate({startDate:wt,durationHours:ht,task:v}),idsRemoved:new Set(L.filter(wt=>wt.oldParentKey===k).map(wt=>wt.activityId))});if(!q){Pi(k,i);continue}for(let[wt,ht]of Object.entries(q.fields))yt(i,k,wt,ht);let $=De(k,i),ot=$?i.getActivity($)?.customId:null,it=typeof ot=="string"&&ot?ot:null,Dt=r.customIdTracker.generateCustomIdForRestoredChild(it);i.setActivityField(k,x.CUSTOM_ID,Dt)}let E=new Set;for(let k of f)E.add(String(k));for(let k of L)k.grandparentKey!=="0"&&E.add(String(k.grandparentKey));for(let k of E)Ut(k,i);let I=St(i);for(let k of I){if(l.add(k.activityId),C.has(k.activityId))continue;let v=i.getActivity(k.activityId);if(!v)continue;let P=et(v);k.before!==void 0&&(P.correlativeId=k.before),C.set(k.activityId,P)}let{scheduledIds:b}=await Z({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:u.length>0?Ot.ROOTS:null,recomputeParentsFrom:u,now:r.now,options:t}),B={name:jt.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(k=>({activity_id:String(k.activityId),reason:k.reason}))}};return e.eventSource!==void 0&&(B.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(k=>{let v=d.find(P=>String(P.activityId)===String(k));return v?{activityId:String(k),ok:!1,reason:v.reason}:{activityId:String(k),ok:!0}}),changes:await z(i,{source:e,beforeSnap:C,touchedIds:l,scheduledIds:b,trackingEvents:[B],hoursPerDay:o.hoursPerDay})}}async function Gl(e,t,r){let{adapter:i,ctx:n,scheduler:o,sector:a}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:S.INVALID_PROGRESS_VALUE};let s=n.activityReader.getActivity(e.activityId);if(!s)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let c=Ce(_.PROGRESS);if(!c)throw new Error("[ScheduleCore] progressPipeline not registered \u2014 cannot dispatch activity-set-progress");let l=c.canEdit(s,n.hierarchy);if(!l.allowed&&!(e.origin===Mi.ACTION_BUTTON&&(l.reason===fo.HAS_LOOKAHEAD_TASKS||l.reason===fo.SUMMARY)))return{ok:!1,reason:l.reason,...l.alertKey?{alertKey:l.alertKey}:{}};let d=c.transform(s,e.newValue,n,e.newValue),u=Se(e.activityId,d),f=await rt(i,u);Te(i,e.activityId,d),Vs(e.activityId,e.newValue,i),me(e.activityId,d.postProcessors??[],i);let{scheduledIds:p}=await Z({adapter:i,scheduler:o,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:d.needsAutoSchedule?e.activityId:null,recomputeParentsFrom:[],collectDirty:g=>ji(e.activityId,u,g),now:r.now,options:t}),y=(d.trackingEvents??[]).map(g=>({name:g.name,properties:g.properties??{}}));return{ok:!0,changes:await z(i,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:p,trackingEvents:y,hoursPerDay:a.hoursPerDay})}}function bI(e){return e===_.START_DATE||e===_.END_DATE}async function $l(e,t,r){if(e.edits.some(y=>!bI(y.column)))return{ok:!1,reason:S.INVALID_VALUE};let{adapter:i,scheduler:n,sector:o}=r,a=[],s=new Map,c=new Set,l=[],d=[],u=[],f=!1;for(let y of e.edits){let g=FI(y,r);if(a.push(g.verdict),!g.verdict.ok||!g.changes)continue;let T=Se(y.activityId,g.changes);wI(s,T,r);for(let I of T)c.add(I);let L=pr(i,y.activityId),C=Wi(i,String(y.activityId));Te(i,y.activityId,g.changes),me(y.activityId,g.changes.postProcessors??[],i,C),d.push(...yr(L,i,y.activityId)),f||=!!g.changes.needsAutoSchedule;for(let I of g.changes.trackingEvents??[])l.push({name:I.name,properties:I.properties??{}});let E=sr(y.activityId,g.changes.constraintWarning);E&&u.push(E)}let{scheduledIds:p}=await Z({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:f?Ot.ROOTS:null,recomputeParentsFrom:c,now:r.now,options:t});return{ok:!0,verdicts:a,changes:await z(i,{source:e,beforeSnap:s,touchedIds:c,scheduledIds:p,sirDetection:Ft.BEFORE_DIFF,links:d,trackingEvents:l,warnings:u,hoursPerDay:o.hoursPerDay})}}function FI(e,t){let{ctx:r}=t,i=e.activityId,n=Ce(e.column);if(!n)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);let o=r.activityReader.getActivity(e.activityId);if(!o)throw new Error(`[ScheduleCore] activity "${e.activityId}" not found`);let a=n.canEdit(o,r.hierarchy);if(!a.allowed)return{verdict:{activityId:i,ok:!1,reason:a.reason??S.CANNOT_EDIT,...a.alertKey?{alertKey:a.alertKey}:{}},changes:null};let s=n.parseInput(e.newValue,o,r);if(!s.ok)return{verdict:{activityId:i,ok:!1,reason:s.reason??S.PARSE_ERROR},changes:null};let c=Reflect.get(o,n.targetField),l=n.validate(o,c,s.value,r);if(!l.valid)return{verdict:{activityId:i,ok:!1,reason:l.reason??S.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};let d=n.transform(o,s.value,r,s.raw);return{verdict:{activityId:i,ok:!0},changes:d}}function wI(e,t,r){let i=new Set;for(let n of t)e.has(n)||i.add(n);if(i.size!==0)for(let n of i){let o=r.adapter.getActivity(n);o&&e.set(n,et(o))}}var oa=_.CUSTOM_ID;async function zl(e,t,r){let{adapter:i,scheduler:n,sector:o}=r;e.edits.some(E=>E.column===_.DURATION)&&n.invalidateExpandedLinksCache();let s=[],c=new Map,l=new Map,d=new Set,u=new Set,f=[],p=[],y=[],g=!1;for(let E of e.edits){let I=xI(E,r,e.eventSource);if(s.push(I.verdict),!I.verdict.ok||!I.changes)continue;let b=sr(E.activityId,I.changes.constraintWarning);b&&y.push(b);let B=Se(E.activityId,I.changes);HI(c,B,r);for(let $ of B)u.add($);BI(l,E,c),Zi(E.column)&&d.add(String(E.activityId));let k=pr(i,E.activityId),v=Wi(i,String(E.activityId)),P=MI(E,r),q=I.changes;Te(i,E.activityId,q),me(E.activityId,I.changes.postProcessors??[],i,v),UI(E,P,r),p.push(...yr(k,i,E.activityId)),g||=!!I.changes.needsAutoSchedule;for(let $ of I.changes.trackingEvents??[])f.push({name:$.name,properties:$.properties??{}})}let T={action:e,autoscheduleFrom:g?Ot.ROOTS:null,recomputeParentsFrom:u,now:r.now,options:t},L=l.size>0,{scheduledIds:C}=await(L?tn({adapter:i,scheduler:n,sector:o,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:T,revertTargets:[...l].filter(([E])=>!d.has(E)).map(([E,I])=>({activityId:E,priorConstraintDate:I})),revert:(E,I)=>Qi(E,I,i,r.ctx.calendars)}):Z({adapter:i,scheduler:n,sector:o,defaultBaseCalendarId:r.defaultBaseCalendarId},T));return{ok:!0,verdicts:s,changes:await z(i,{source:e,beforeSnap:c,touchedIds:u,scheduledIds:C,sirDetection:Ft.BEFORE_DIFF,links:p,trackingEvents:f,warnings:y,hoursPerDay:o.hoursPerDay})}}function xI(e,t,r){let{ctx:i}=t,n=e.activityId,o=Ce(e.column);if(!o)return{verdict:{activityId:n,ok:!1,reason:S.NO_PIPELINE_FOR_COLUMN},changes:null};let a=i.activityReader.getActivity(e.activityId);if(!a)return{verdict:{activityId:n,ok:!1,reason:S.ACTIVITY_NOT_FOUND},changes:null};let s=o.canEdit(a,i.hierarchy,{eventSource:r,newValue:e.newValue});if(!s.allowed)return{verdict:{activityId:n,ok:!1,reason:s.reason??S.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let c=o.parseInput(e.newValue,a,i);if(!c.ok)return{verdict:{activityId:n,ok:!1,reason:c.reason??S.PARSE_ERROR},changes:null};let l=Reflect.get(a,o.targetField),d=o.validate(a,l,c.value,i);if(!d.valid)return{verdict:{activityId:n,ok:!1,reason:d.reason??S.INVALID,...d.notification?.messageKey?{alertKey:d.notification.messageKey}:{}},changes:null};if(e.column===oa&&c.value!==null){let f=t.adapter.getActivity(e.activityId),p=f?f.customId:null,y=typeof p=="string"?p:null;if(t.customIdTracker.isCustomIdInUse(String(c.value),y))return{verdict:{activityId:n,ok:!1,reason:S.CUSTOM_ID_DUPLICATE},changes:null}}let u=o.transform(a,c.value,i,c.raw);return{verdict:{activityId:n,ok:!0},changes:u}}function MI(e,t){if(e.column!==oa)return null;let r=t.adapter.getActivity(e.activityId),i=r?r.customId:null;return typeof i=="string"?i:null}function UI(e,t,r){if(e.column!==oa)return;let i=r.adapter.getActivity(e.activityId),n=i?i.customId:null,o=typeof n=="string"?n:null;t!==o&&r.customIdTracker.trackCustomIdChange(t,o)}function BI(e,t,r){if(!Xi(t.column))return;let i=String(t.activityId);if(e.has(i))return;let n=r.get(i);n&&e.set(i,n.constraintDate??null)}function HI(e,t,r){let i=new Set;for(let n of t)e.has(n)||i.add(n);if(i.size!==0)for(let n of i){let o=r.adapter.getActivity(n);o&&e.set(n,et(o))}}var Pt={INVALID_BASELINE_POINT:"invalid_baseline_point",UNKNOWN_CONSTRAINT:"unknown_constraint",ORPHAN_ACTIVITY:"orphan_activity",INVALID_LINK:"invalid_link",DUPLICATE_LINK:"duplicate_link"},WI=[Pt.INVALID_BASELINE_POINT,Pt.UNKNOWN_CONSTRAINT,Pt.ORPHAN_ACTIVITY,Pt.INVALID_LINK,Pt.DUPLICATE_LINK],vr=()=>{};function ql(){let e=new Map,t=new Map;return{record:(n,o)=>{e.set(n,(e.get(n)??0)+1);let a=t.get(n)??[];a.length<10&&!a.includes(o)&&(a.push(o),t.set(n,a))},snapshot:()=>Object.freeze(WI.flatMap(n=>{let o=e.get(n);return o===void 0?[]:[Object.freeze({code:n,count:o,sampleIds:Object.freeze([...t.get(n)??[]])})]}))}}function Jl(e){return typeof e=="string"&&e.length>0?se(e):e instanceof Date?e:null}function aa(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):Number.NaN;return!Number.isFinite(t)||t<0?null:t}function hn(e,t,r){let i=aa(e.duration),n=aa(e.cost),o=aa(e.hh_work);return i===null||n===null||o===null?(r&&r.record(Pt.INVALID_BASELINE_POINT,r.sampleId),t.warn(`[baseline] dropping point with non-finite/negative magnitude \u2014 duration=${JSON.stringify(e.duration)}, cost=${JSON.stringify(e.cost)}, hh_work=${JSON.stringify(e.hh_work)}`),null):{startDate:Jl(e.start_date),endDate:Jl(e.end_date),durationDays:i,cost:n,workHours:o,versionId:typeof e.sectorbaselineversionId=="number"?e.sectorbaselineversionId:null,isActiveVersion:!!e.sectorbaselineversion?.active,isVisibleVersion:!!e.sectorbaselineversion?.visible,baseCalendarId:e.baseCalendarId!=null?String(e.baseCalendarId):null,hoursPerDay:typeof e.hoursPerDay=="number"?e.hoursPerDay:null,hoursPerWeek:typeof e.hoursPerWeek=="number"?e.hoursPerWeek:null}}function Xl(e,t,r,i=vr){let n=new Map;e.forEachActivity((s,c)=>{let l=s.proplannerId;typeof l=="number"&&n.set(l,c)});let o=new Map;for(let s of t){let c=s.activityId;if(typeof c!="number"){i(Pt.INVALID_BASELINE_POINT,String(c??"unknown"));continue}let l=n.get(c);if(l===void 0){i(Pt.INVALID_BASELINE_POINT,String(c));continue}let d=o.get(l);d?d.push(s):o.set(l,[s])}let a=[];for(let[s,c]of o)e.setActivityField(s,"baselinePoints",c.map(l=>hn(l,r,{record:i,sampleId:s})).filter(l=>l!==null)),a.push(s);return e.forEachActivity((s,c)=>{if(o.has(c))return;let l=s.baselinePoints;Array.isArray(l)&&l.length>0&&(e.setActivityField(c,"baselinePoints",[]),a.push(c))}),a}function VI(e){let t=kt(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function Zl(e){let t=[];return e.forEachActivity((r,i)=>{let n=VI(r);if(!n){r.baselineSnapshot!==null&&(e.setActivityField(i,"baselineSnapshot",null),t.push(i));return}e.setActivityField(i,"baselineSnapshot",n),t.push(i)}),t}function mn(e,t,r,i,n=null,o=vr){let a=new Set;for(let s of Xl(e,t,i,o))a.add(s);if(r)for(let s of dr(e,r,n))a.add(s);for(let s of Zl(e))a.add(s);for(let s of ur(e))a.add(s);return[...a]}function Ql(e,t,r){if(!e||e==="0")return;let i=r.getChildren(e);if(i.length===0)return;let n=new Map,o=0;for(let s of i){let c=jI(String(s),t,r);n.set(String(s),c),o+=c}let a=o?100/o:0;for(let s of i){let c=r.getActivity(s);if(!c)continue;let l=c.baselinePoints;if(kt(c)){let u=n.get(String(s))??0;r.setActivityField(s,_.PONDERATOR,a*u)}else(!Array.isArray(l)||l.length===0)&&r.setActivityField(s,_.PONDERATOR,0)}}function jI(e,t,r){let i=r.getActivity(e);if(!i)return 0;let n=kt(i);if(!n)return 0;if(t===gt.COST)return In(n.cost);if(t===gt.WORK_HOURS)return In(n.workHours);let{type:o}=i;return o===D.PROJECT?td(e,r):o===D.MILESTONE?0:In(n.durationDays)}function td(e,t){let r=0;for(let i of t.getChildren(e)){let n=t.getActivity(i);if(!n)continue;let o=kt(n);if(!o)continue;let{type:a}=n;a===D.PROJECT?r+=td(String(i),t):a!==D.MILESTONE&&(r+=In(o.durationDays))}return r}function In(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function ed(e,t){t.forEachActivity((r,i)=>{t.setActivityField(i,_.PONDERATOR,0)}),t.forEachActivity((r,i)=>{t.getChildren(i).length>0&&Ql(String(i),e,t)})}function gn(e,t){ed(t,e.adapter),Mr(e.adapter),e.now&&(dr(e.adapter,e.now,e.defaultBaseCalendarId??null),xe(e.adapter,e.now)),ur(e.adapter),e.now&&ce(e.adapter,e.sector.statusCriteria)}function rd(e){return JSON.stringify(e.adapter.getAllIds().map(t=>{let r=e.adapter.getActivity(t)?.baselinePoints.find(i=>i.isActiveVersion);return r?[String(t),r.versionId,r.startDate?.getTime()??null,r.endDate?.getTime()??null,r.durationDays,r.cost,r.workHours,r.baseCalendarId,r.hoursPerDay,r.hoursPerWeek]:[String(t),null]}))}async function id(e,t){let r=await rt(t.adapter,new Set(t.adapter.getAllIds())),i=rd(t),n=mn(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return rd(t)!==i&&gn(t,t.sector.activityCreter??gt.DURATION),{ok:!0,changes:await z(t.adapter,{source:e,beforeSnap:r,touchedIds:n,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function KI(e){return Object.values(gt).includes(e)}async function nd(e,t){if(!KI(e.criterion))return{ok:!1,reason:S.INVALID_VALUE};let r=new Set(t.adapter.getAllIds()),i=await rt(t.adapter,r);return gn(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:await z(t.adapter,{source:e,beforeSnap:i,touchedIds:r,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function od(e,t){let r=Ki(e.criteria),i=new Set(t.adapter.getAllIds()),n=await rt(t.adapter,i),o=ce(t.adapter,r);return t.sector.statusCriteria=r,{ok:!0,changes:await z(t.adapter,{source:e,beforeSnap:n,touchedIds:o,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function sd(e,t,r){let i=new Map,n=new Set;for(let a of r.adapter.getAllActivities()){if(!YI(a,r))continue;let s=r.ctx.calendars.getCalendar(a.calendarId);if(!s)continue;let c=s.getClosestWorkTime({date:a.startDate,direction:j.FUTURE,unit:mt.HOUR}),l=s.calculateEndDate(c,a.durationHours);if(ad(c,a.startDate)&&ad(l,a.endDate))continue;let d=String(a.id);i.set(d,et(a)),n.add(d),r.adapter.setActivityFields(d,{startDate:c,endDate:l})}let{scheduledIds:o}=await Z({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:Ot.ROOTS,recomputeParentsFrom:n,now:r.now,options:t});return{ok:!0,changes:await z(r.adapter,{source:e,beforeSnap:i,touchedIds:n,scheduledIds:o,hoursPerDay:r.sector.hoursPerDay})}}function YI(e,t){return e.progress===0&&!$t(e.type,t.adapter.hasChildren(e.id))}function ad(e,t){return e.getTime()===t.getTime()}var cd=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","cost","hasCustomPonderator","subcontractId","responsableIds","tagIds"];function GI(e){let t={};for(let r of cd)Object.assign(t,{[r]:F(e[r])});return t}function $I(e,t){let r=[],i=n=>{t.has(String(n))&&r.push(n);for(let o of e.getChildren(n))i(o)};for(let n of e.getRootIds())i(n);return r}function ld(e,t){let r=new Set(t.adapter.checkedIds().map(String));if(r.size===0)return{ok:!1,reason:S.NO_ACTIVITY_SELECTION};let i=$I(t.adapter,r);t.clipboard.value={activities:i.map(o=>{let a=t.adapter.getActivity(o);if(a===null)throw new Error(`Selected activity ${o} is missing`);return{originalId:o,originalParentId:a.parentId??"0",overrides:GI(a)}}),links:t.adapter.getAllLinks().filter(o=>r.has(String(o.source))&&r.has(String(o.target))).map(o=>F(o))};let n=ai({kind:m.SELECTION_REPLACE,activityIds:[]},{adapter:t.adapter});return n.ok?{...n,changes:{...n.changes,source:e}}:n}function dd(e,t){return t.value=null,{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}}function zI(e,t){let r=t.getActivity(e);return r?r.parentId==null?t.getRootIds().length===1?{ok:!0,parentId:r.id}:{ok:!0,parentId:"0",afterSiblingId:e}:{ok:!0,parentId:String(r.parentId),afterSiblingId:e}:{ok:!1,reason:S.ANCHOR_SIBLING_NOT_FOUND}}var ud=()=>({ok:!1,reason:S.ACTIVITY_PASTE_INVARIANT_FAILED});async function fd(e,t,r){let i=r.activityClipboard.value;if(i===null)return{ok:!1,reason:S.CLIPBOARD_EMPTY};let n=zI(e.destination.afterSiblingId,r.adapter);if(!n.ok)return n;let o=await rt(r.adapter,new Set),a=new Set,s=new Map,c=[],l;for(let g of i.activities){let T=s.get(g.originalParentId),L=T===void 0?l??n.afterSiblingId:void 0,C=await qr({kind:m.ACTIVITY_CREATE,parentId:T??n.parentId,...L===void 0?{}:{afterSiblingId:L},overrides:F(g.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:e.destination.afterSiblingId});if(!C.ok)return C;s.set(g.originalId,C.newId),c.push(C.newId),T===void 0&&(l=C.newId)}let d=St(r.adapter),u=new Set(c.map(String));cr(r.adapter,d,u,o,a);for(let g of c)a.add(String(g));let f=[];for(let g of i.links){let T=s.get(g.source),L=s.get(g.target);if(T===void 0||L===void 0)return ud();let C={kind:dt.CREATE,source:T,target:L,type:g.type,lag:g.lag},E=ye(C,{port:r.adapter,newLinkId:r.linkIdGen.next});if(!E.applied)return ud();f.push({op:C,finalLinkId:E.linkId,rejected:null})}let{scheduledIds:p}=await Z({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:c[0]??null,recomputeParentsFrom:c,now:r.now,options:t}),y=fr(f,new Map,r.adapter);return{ok:!0,changes:await z(r.adapter,{source:e,beforeSnap:o,touchedIds:a,scheduledIds:p,links:y,hoursPerDay:r.sector.hoursPerDay})}}async function pd(e,t,r){return e.kind===m.ACTIVITY_COPY?ld(e,{adapter:r.adapter,clipboard:r.activityClipboard}):e.kind===m.CALENDAR_RECONCILE?sd(e,t,r):e.kind===m.ACTIVITY_CLIPBOARD_CLEAR?dd(e,r.activityClipboard):e.kind===m.ACTIVITY_PASTE_COPIED?fd(e,t,r):e.kind===ue?Pl(e,t,r):e.kind===m.PERSISTENCE_ACKNOWLEDGE?xl(e,r):e.kind===m.BASELINE_APPLY?id(e,r):e.kind===m.PONDERATOR_CRITERION_SET?nd(e,r):e.kind===m.STATUS_CRITERIA_SET?od(e,r):e.kind===m.LINK_CREATE||e.kind===m.LINK_UPDATE||e.kind===m.LINK_DELETE?sl(e,t,r):e.kind===m.LINKS_BATCH?cl(e,t,r):e.kind===m.ACTIVITY_CREATE?El(e,t,r):e.kind===m.ACTIVITY_DELETE?_l(e,t,r):e.kind===m.ACTIVITY_MOVE?jl(e,t,r):e.kind===m.ACTIVITY_INDENT?Kl(e,t,r):e.kind===m.ACTIVITY_OUTDENT?Yl(e,t,r):e.kind===m.ACTIVITY_SET_PROGRESS?Gl(e,t,r):e.kind===m.DATES_BATCH?$l(e,t,r):e.kind===m.BULK_EDIT?zl(e,t,r):e.kind===m.SELECTION_TOGGLE?Ja(e,sa(r)):e.kind===m.SELECTION_REPLACE?ai(e,sa(r)):e.kind===m.VISIBILITY_SET?Xa(e,sa(r)):e.kind===m.FILTER_SET?as(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind===m.SORT_SET?us(e,{adapter:r.adapter}):e.kind===m.SIR_SYNC?Ol(e,r):e.kind===m.ACTIVITY_LOOKAHEAD_SYNC?Ml(e,t,r):e.kind===m.ACTIVITY_LOOKAHEAD_CONVERT?Hl(e,t,r):e.kind===m.INLINE_EDIT&&(e.column===_.CUSTOM_PREDECESSORS||e.column===_.CUSTOM_SUCESSORS)?ll(e,t,r):e.kind!==m.INLINE_EDIT?fs(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):al(e,t,r)}function sa(e){return{adapter:e.adapter}}var qI=new Set(["startDate","endDate","constraintDate"]);function yd(e,t){return qI.has(e)&&typeof t=="string"?new Date(t):t}function hd(e,t={}){let r=t.defaultUnit??mt.HOUR;return{getCalendar(i){let n=e.getCalendar(String(i));return n?JI(n,r):null}}}function JI(e,t){return{getClosestWorkTime(r){return e.getClosestWorkTime({date:r.date,dir:r.direction,unit:r.unit})},calculateEndDate(r,i){return e.calculateEndDate({start_date:r,duration:i,unit:t})},calculateDuration(r,i){return e.calculateDuration({start_date:r,end_date:i,unit:t})},isWorkTime(r,i){return e.isWorkTime({date:r,unit:i})},getWorkHours(r){return e.getWorkHours(r)}}}function XI(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function Ve(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function je(e){return Ve(e)&&!isNaN(e.getTime())}var ZI={}.constructor.toString();function QI(e){var t=e.constructor.toString();return t!==ZI}function tg(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function Jt(e){var t,r;if(e&&typeof e=="object")switch(!0){case Ve(e):r=new Date(e);break;case XI(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=Jt(e[t]);break;default:if(QI(e))r=Object.create(e);else{if(tg(e))return r=e,r;r={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(r[t]=Jt(e[t]));break}return r||e}function Cr(e,t,r){for(var i in t)(e[i]===void 0||r)&&(e[i]=t[i]);return e}function md(e){return typeof e<"u"}var An;function ca(){return An||(An=new Date().valueOf()),An++,An}function Bt(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var rg=(e,t,r)=>{e=e.replace(/%[a-zA-Z]/g,n=>{switch(n){case"%d":return`"+to_fixed(date.get${t?"UTC":""}Date())+"`;case"%m":return`"+to_fixed((date.get${t?"UTC":""}Month()+1))+"`;case"%j":return`"+date.get${t?"UTC":""}Date()+"`;case"%n":return`"+(date.get${t?"UTC":""}Month()+1)+"`;case"%y":return`"+to_fixed(date.get${t?"UTC":""}FullYear()%100)+"`;case"%Y":return`"+date.get${t?"UTC":""}FullYear()+"`;case"%D":return`"+locale.date.day_short[date.get${t?"UTC":""}Day()]+"`;case"%l":return`"+locale.date.day_full[date.get${t?"UTC":""}Day()]+"`;case"%M":return`"+locale.date.month_short[date.get${t?"UTC":""}Month()]+"`;case"%F":return`"+locale.date.month_full[date.get${t?"UTC":""}Month()]+"`;case"%h":return`"+to_fixed((date.get${t?"UTC":""}Hours()+11)%12+1)+"`;case"%g":return`"+((date.get${t?"UTC":""}Hours()+11)%12+1)+"`;case"%G":return`"+date.get${t?"UTC":""}Hours()+"`;case"%H":return`"+to_fixed(date.get${t?"UTC":""}Hours())+"`;case"%i":return`"+to_fixed(date.get${t?"UTC":""}Minutes())+"`;case"%a":return`"+(date.get${t?"UTC":""}Hours()>11?"pm":"am")+"`;case"%A":return`"+(date.get${t?"UTC":""}Hours()>11?"PM":"AM")+"`;case"%s":return`"+to_fixed(date.get${t?"UTC":""}Seconds())+"`;case"%W":return'"+to_fixed(getISOWeek(date))+"';case"%w":return'"+to_fixed(getWeek(date))+"';default:return n}});let i=new Function("date","to_fixed","locale","getISOWeek","getWeek",`return "${e}";`);return n=>i(n,r.date.to_fixed,r.locale,r.date.getISOWeek,r.date.getWeek)},ig=(e,t,r)=>{let i="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);",n=e.match(/%[a-zA-Z]/g);for(let s=0;s<n.length;s++)switch(n[s]){case"%j":case"%d":i+=`set[2]=temp[${s}]||1;`;break;case"%n":case"%m":i+=`set[1]=(temp[${s}]||1)-1;`;break;case"%y":i+=`set[0]=temp[${s}]*1+(temp[${s}]>50?1900:2000);`;break;case"%g":case"%G":case"%h":case"%H":i+=`set[3]=temp[${s}]||0;`;break;case"%i":i+=`set[4]=temp[${s}]||0;`;break;case"%Y":i+=`set[0]=temp[${s}]||0;`;break;case"%a":case"%A":i+=`set[3]=set[3]%12+((temp[${s}]||'').toLowerCase()=='am'?0:12);`;break;case"%s":i+=`set[5]=temp[${s}]||0;`;break;case"%M":i+=`set[1]=locale.date.month_short_hash[temp[${s}]]||0;`;break;case"%F":i+=`set[1]=locale.date.month_full_hash[temp[${s}]]||0;`;break}let o="set[0],set[1],set[2],set[3],set[4],set[5]";t&&(o=` Date.UTC(${o})`);let a=new Function("date","locale",`var set=[0,0,1,0,0,0]; ${i} return new Date(${o});`);return s=>a(s,r.locale)},Id={date_to_str:rg,str_to_date:ig},ng=(e,t,r)=>i=>e.replace(/%[a-zA-Z]/g,n=>{switch(n){case"%d":return t?r.date.to_fixed(i.getUTCDate()):r.date.to_fixed(i.getDate());case"%m":return t?r.date.to_fixed(i.getUTCMonth()+1):r.date.to_fixed(i.getMonth()+1);case"%j":return t?i.getUTCDate():i.getDate();case"%n":return t?i.getUTCMonth()+1:i.getMonth()+1;case"%y":return t?r.date.to_fixed(i.getUTCFullYear()%100):r.date.to_fixed(i.getFullYear()%100);case"%Y":return t?i.getUTCFullYear():i.getFullYear();case"%D":return t?r.locale.date.day_short[i.getUTCDay()]:r.locale.date.day_short[i.getDay()];case"%l":return t?r.locale.date.day_full[i.getUTCDay()]:r.locale.date.day_full[i.getDay()];case"%M":return t?r.locale.date.month_short[i.getUTCMonth()]:r.locale.date.month_short[i.getMonth()];case"%F":return t?r.locale.date.month_full[i.getUTCMonth()]:r.locale.date.month_full[i.getMonth()];case"%h":return t?r.date.to_fixed((i.getUTCHours()+11)%12+1):r.date.to_fixed((i.getHours()+11)%12+1);case"%g":return t?(i.getUTCHours()+11)%12+1:(i.getHours()+11)%12+1;case"%G":return t?i.getUTCHours():i.getHours();case"%H":return t?r.date.to_fixed(i.getUTCHours()):r.date.to_fixed(i.getHours());case"%i":return t?r.date.to_fixed(i.getUTCMinutes()):r.date.to_fixed(i.getMinutes());case"%a":return t?i.getUTCHours()>11?"pm":"am":i.getHours()>11?"pm":"am";case"%A":return t?i.getUTCHours()>11?"PM":"AM":i.getHours()>11?"PM":"AM";case"%s":return t?r.date.to_fixed(i.getUTCSeconds()):r.date.to_fixed(i.getSeconds());case"%W":return t?r.date.to_fixed(r.date.getUTCISOWeek(i)):r.date.to_fixed(r.date.getISOWeek(i));case"%w":return r.date.to_fixed(r.date.getWeek(i));default:return n}}),og=(e,t,r)=>i=>{let n=[0,0,1,0,0,0],o=i.match(/[a-zA-Z]+|[0-9]+/g),a=e.match(/%[a-zA-Z]/g);for(let s=0;s<a.length;s++)switch(a[s]){case"%j":case"%d":n[2]=o[s]||1;break;case"%n":case"%m":n[1]=(o[s]||1)-1;break;case"%y":n[0]=o[s]*1+(o[s]>50?1900:2e3);break;case"%g":case"%G":case"%h":case"%H":n[3]=o[s]||0;break;case"%i":n[4]=o[s]||0;break;case"%Y":n[0]=o[s]||0;break;case"%a":case"%A":n[3]=n[3]%12+((o[s]||"").toLowerCase()==="am"?0:12);break;case"%s":n[5]=o[s]||0;break;case"%M":n[1]=r.locale.date.month_short_hash[o[s]]||0;break;case"%F":n[1]=r.locale.date.month_full_hash[o[s]]||0;break}return t?new Date(Date.UTC(n[0],n[1],n[2],n[3],n[4],n[5])):new Date(n[0],n[1],n[2],n[3],n[4],n[5])},gd={date_to_str:ng,str_to_date:og};function Ad(e){var t=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function r(s){var c=new Date(s);return isNaN(c.getTime())?null:c}var i=null;function n(){try{new Function("canUseCsp = false;")}catch{i=!0}}function o(){var s=!1;return e.config.csp==="auto"?(i===null&&n(),s=i):s=e.config.csp,s}var a={_isoDateDetected:!1,_isoDateOnly:!1,formatISODate:function(s){return s.toISOString()},formatISODateOnly:function(s){return s.getUTCFullYear()+"-"+e.date.to_fixed(s.getUTCMonth()+1)+"-"+e.date.to_fixed(s.getUTCDate())},init:function(){for(var s=e.locale,l=s.date.month_short,d=s.date.month_short_hash={},c=0;c<l.length;c++)d[l[c]]=c;for(var l=s.date.month_full,d=s.date.month_full_hash={},c=0;c<l.length;c++)d[l[c]]=c},date_part:function(s){return s.setUTCHours(0,0,0,0),s},time_part:function(s){return s.valueOf()/1e3%86400},week_start:function(s){var c=s.getUTCDay();return e.config.start_on_monday&&(c===0?c=6:c--),this.date_part(this.add(s,-1*c,"day"))},month_start:function(s){return s.setUTCDate(1),this.date_part(s)},quarter_start:function(s){this.month_start(s);var c=s.getUTCMonth(),l;return c>=9?l=9:c>=6?l=6:c>=3?l=3:l=0,s.setUTCMonth(l),s},year_start:function(s){return s.setUTCMonth(0),this.month_start(s)},day_start:function(s){return this.date_part(s)},hour_start:function(s){return s.getUTCMinutes()&&s.setUTCMinutes(0),this.minute_start(s),s},minute_start:function(s){return s.getUTCSeconds()&&s.setUTCSeconds(0),s.getUTCMilliseconds()&&s.setUTCMilliseconds(0),s},_add_days:function(s,c,l){return s.setUTCDate(s.getUTCDate()+c),s},add:function(s,c,l){var d=new Date(s.valueOf());switch(l){case"day":d=this._add_days(d,c,s);break;case"week":d=this._add_days(d,c*7,s);break;case"month":d.setUTCMonth(d.getUTCMonth()+c);break;case"year":d.setUTCFullYear(d.getUTCFullYear()+c);break;case"hour":d.setTime(d.getTime()+c*60*60*1e3);break;case"minute":d.setTime(d.getTime()+c*60*1e3);break;default:return this["add_"+l](s,c,l)}return d},add_quarter:function(s,c){return this.add(s,c*3,"month")},to_fixed:function(s){return s<10?"0"+s:s},copy:function(s){return new Date(s.valueOf())},date_to_str:function(s,c){var l=Id;return o()&&(l=gd),l.date_to_str(s,c,e)},str_to_date:function(s,c){var l=Id;return o()&&(l=gd),l.str_to_date(s,c,e)},getISOWeek:function(s){return e.date._getWeekNumber(s,!0)},_getWeekNumber:function(s,c){if(!s)return!1;var l=s.getUTCDay();c&&l===0&&(l=7);var d=new Date(s.valueOf());d.setUTCDate(s.getUTCDate()+(4-l));var u=d.getUTCFullYear(),f=Math.round((d.getTime()-Date.UTC(u,0,1))/864e5),p=1+Math.floor(f/7);return p},getWeek:function(s){return e.date._getWeekNumber(s,e.config.start_on_monday)},getUTCISOWeek:function(s){return e.date.getISOWeek(s)},parseDate:function(s,c){if(s&&!s.getFullYear){var l=!c||c==="parse_date"||c==="xml_date",d=l&&(e.defined(e.templates.xml_date)||e.templates.parse_date&&!e.templates.parse_date._ganttAuto);if(!d&&typeof s=="string"&&t.test(s)){var u=s.indexOf("T")!==-1,f=r(s);if(f)return a._isoDateDetected?u&&(a._isoDateOnly=!1):(a._isoDateDetected=!0,a._isoDateOnly=!u),f}typeof c!="function"&&(typeof c=="string"?c==="parse_date"||c==="xml_date"?c=e.defined(e.templates.xml_date)?e.templates.xml_date:e.templates.parse_date:c=e.defined(e.templates[c])?e.templates[c]:e.date.str_to_date(c,!0):c=e.defined(e.templates.xml_date)?e.templates.xml_date:e.templates.parse_date),s?s=c(s):s=null}return s}};return a}function la(e,t,r,i,n){return this.date=e,this.unit=t,this.task=r,this.id=i,this.calendar=n,this}function da(e,t,r,i,n,o){return this.date=e,this.dir=t,this.unit=r,this.task=i,this.id=n,this.calendar=o,this}function ua(e,t,r,i,n,o,a){return this.start_date=e,this.duration=t,this.unit=r,this.step=i,this.task=n,this.id=o,this.calendar=a,this}function ag(e,t,r,i){return this.start_date=e,this.end_date=t,this.task=r,this.calendar=i,this.unit=null,this.step=null,this}var vd=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(Ve(t)?t={date:t}:t=Cr({},t),!je(t.date))throw e.assert(!1,"Invalid date argument for getWorkHours method"),new Error("Invalid date argument for getWorkHours method");return t},setWorkTimeArguments:function(){return arguments[0]},unsetWorkTimeArguments:function(){return arguments[0]},isWorkTimeArguments:function(){var t=arguments[0];if(t instanceof la)return t;var r;if(t.date?r=new la(t.date,t.unit,t.task,null,t.calendar):r=new la(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!je(r.date))throw e.assert(!1,"Invalid date argument for isWorkTime method"),new Error("Invalid date argument for isWorkTime method");return r},getClosestWorkTimeArguments:function(t){var r=arguments[0];if(r instanceof da)return r;var i;if(Ve(r)?i=new da(r):i=new da(r.date,r.dir,r.unit,r.task,null,r.calendar),r.id&&(i.task=r),i.dir=r.dir||"any",i.unit=r.unit||e.config.duration_unit,!je(i.date))throw e.assert(!1,"Invalid date argument for getClosestWorkTime method"),new Error("Invalid date argument for getClosestWorkTime method");return i},_getStartEndConfig:function(t){var r=ag,i;if(t instanceof r)return t;if(Ve(t)?i=new r(arguments[0],arguments[1],arguments[2],arguments[3]):(i=new r(t.start_date,t.end_date,t.task),t.id!==null&&t.id!==void 0&&(i.task=t)),i.unit=i.unit||e.config.duration_unit,i.step=i.step||e.config.duration_step,i.start_date=i.start_date||i.start||i.date,!je(i.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!je(i.end_date))throw e.assert(!1,"Invalid end_date argument for getDuration method"),new Error("Invalid end_date argument for getDuration method");return i},getDurationArguments:function(t,r,i,n){return this._getStartEndConfig.apply(this,arguments)},hasDurationArguments:function(t,r,i,n){return this._getStartEndConfig.apply(this,arguments)},calculateEndDateArguments:function(t,r,i,n){var o=arguments[0];if(o instanceof ua)return o;var a;if(Ve(o)?a=new ua(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):a=new ua(o.start_date,o.duration,o.unit,o.step,o.task,null,o.calendar),o.id!==null&&o.id!==void 0&&(a.task=o,a.unit=null,a.step=null),a.unit=a.unit||e.config.duration_unit,a.step=a.step||e.config.duration_step,!je(a.start_date))throw e.assert(!1,"Invalid start_date argument for calculateEndDate method"),new Error("Invalid start_date argument for calculateEndDate method");return a}}};function Cd(){}Cd.prototype={_getIntervals:function(e){for(var t=[],r=0;r<e.length;r+=2)t.push({start:e[r],end:e[r+1]});return t},_toHoursArray:function(e){var t=[];function r(o){var a=String(o);return a.length<2&&(a="0"+a),a}function i(o){var a=Math.floor(o/3600),s=o-a*60*60,c=Math.floor(s/60);return a+":"+r(c)}for(var n=0;n<e.length;n++)t.push(i(e[n].start)+"-"+i(e[n].end));return t},_intersectHourRanges:function(e,t){var n=[],r=e.length>t.length?e:t,i=e===r?t:e;r=r.slice(),i=i.slice();for(var n=[],o=0;o<r.length;o++)for(var a=r[o],s=0;s<i.length;s++){var c=i[s];c.start<a.end&&c.end>a.start&&(n.push({start:Math.max(a.start,c.start),end:Math.min(a.end,c.end)}),a.end>c.end&&(i.splice(s,1),s--,o--))}return n},_mergeAdjacentIntervals:function(e){var t=e.slice();t.sort(function(o,a){return o.start-a.start});for(var r=t[0],i=1;i<t.length;i++){var n=t[i];n.start<=r.end?(n.end>r.end&&(r.end=n.end),t.splice(i,1),i--):r=n}return t},_mergeHoursConfig:function(e,t){return this._mergeAdjacentIntervals(this._intersectHourRanges(e,t))},merge:function(e,t){let r=Jt(e.getConfig()),i=Jt(t.getConfig()),n=r.parsed,o=i.parsed;n.customWeeks=r.customWeeks,o.customWeeks=i.customWeeks;var a={hours:this._toHoursArray(this._mergeHoursConfig(n.hours,o.hours)),dates:{},customWeeks:{}};let s=(l,d)=>{for(let u in l.dates){let f=l.dates[u];+u>1e3&&(a.dates[u]=!1);for(let p in d.dates){let y=d.dates[p];if(p==u&&(a.dates[u]=!!(f&&y)),Array.isArray(f)){let g=Array.isArray(y)?y:d.hours;a.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,g))}}}};if(s(n,o),s(o,n),n.customWeeks)for(var c in n.customWeeks)a.customWeeks[c]=n.customWeeks[c];if(o.customWeeks)for(var c in o.customWeeks)a.customWeeks[c]?a.customWeeks[c+"_second"]=o.customWeeks[c]:a.customWeeks[c]=o.customWeeks[c];return a}};var fa=class{constructor(){this.clear()}getItem(t,r,i){if(this._cache.has(t)){let o=this._cache.get(t)[i.getUTCFullYear()];if(o&&o.has(r))return o.get(r)}return-1}setItem(t,r,i,n){if(!t||!r)return;let o=this._cache,a=n.getUTCFullYear(),s;o.has(t)?s=o.get(t):(s=[],o.set(t,s));let c=s[a];c||(c=s[a]=new Map),c.set(r,i)}clear(){this._cache=new Map}},pa=class{constructor(){this.clear()}getItem(t,r,i){let n=this._cache;if(n&&n[t]){let o=n[t];if(o===void 0)return-1;let a=o[i.getUTCFullYear()];if(a&&a[r]!==void 0)return a[r]}return-1}setItem(t,r,i,n){if(!t||!r)return;let o=this._cache;if(!o)return;o[t]||(o[t]=[]);let a=o[t],s=n.getUTCFullYear(),c=a[s];c||(c=a[s]={}),c[r]=i}clear(){this._cache={}}},ya=class{constructor(t){this.getMinutesPerWeek=r=>{let i=r.valueOf();if(this._weekCache.has(i))return this._weekCache.get(i);let n=this._calendar,o=this._calendar.$gantt,a=0,s=o.date.week_start(new Date(r));for(let c=0;c<7;c++)a+=n.getHoursPerDay(s)*60,s=o.date.add(s,1,"day");return this._weekCache.set(i,a),a},this.getMinutesPerMonth=r=>{let i=r.valueOf();if(this._monthCache.has(i))return this._monthCache.get(i);let n=this._calendar,o=this._calendar.$gantt,a=0,s=o.date.week_start(new Date(r)),c=o.date.add(s,1,"month").valueOf();for(;s.valueOf()<c;)a+=n.getHoursPerDay(s)*60,s=o.date.add(s,1,"day");return this._monthCache.set(i,a),a},this.clear=()=>{this._weekCache=new Map,this._monthCache=new Map},this.clear(),this._calendar=t}};function sg(){return typeof Map<"u"?new fa:new pa}var ha=class{constructor(){this.clear()}_getCacheObject(t,r,i){let n=this._cache;n[r]||(n[r]=[]);let o=n[r];o||(o=n[r]={});let a=o[i];a||(a=o[i]={});let s=t.getUTCFullYear(),c=a[s];return c||(c=a[s]={durations:{},endDates:{}}),c}_endDateCacheKey(t,r){return String(t)+"-"+String(r)}_durationCacheKey(t,r){return String(t)+"-"+String(r)}getEndDate(t,r,i,n,o){let a=this._getCacheObject(t,i,n),s=t.valueOf(),c=this._endDateCacheKey(s,r),l;if(a.endDates[c]===void 0){let d=o(),u=d.valueOf();a.endDates[c]=u,a.durations[this._durationCacheKey(s,u)]=r,l=d}else l=new Date(a.endDates[c]);return l}getDuration(t,r,i,n,o){let a=this._getCacheObject(t,i,n),s=t.valueOf(),c=r.valueOf(),l=this._durationCacheKey(s,c),d;if(a.durations[l]===void 0){let u=o();a.durations[l]=u.valueOf(),d=u}else d=a.durations[l];return d}clear(){this._cache={}}};function ma(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=sg(),this._largeUnitsCache=new ya(this),this._dateDurationCache=new ha,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}ma.prototype={units:["year","month","week","day","hour","minute"],_clearCaches:function(){this._workingUnitsCache.clear(),this._largeUnitsCache.clear(),this._dateDurationCache.clear()},_getUnitOrder:function(e){for(var t=0,r=this.units.length;t<r;t++)if(this.units[t]==e)return t},_resetTimestampCache:function(){this._cached_timestamps={},this._cached_timestamps_count=0},_timestamp:function(e){this._cached_timestamps_count>1e6&&this._resetTimestampCache();var t=null;if(e.day||e.day===0)t=e.day;else if(e.date){var r=String(e.date.valueOf());this._cached_timestamps[r]?t=this._cached_timestamps[r]:(t=Date.UTC(e.date.getUTCFullYear(),e.date.getUTCMonth(),e.date.getUTCDate()),this._cached_timestamps[r]=t,this._cached_timestamps_count++)}return t},_checkIfWorkingUnit:function(e,t){if(!this["_is_work_"+t]){let r=this.$gantt.date[`${t}_start`](new Date(e)),i=this.$gantt.date.add(r,1,t);return this.hasDuration(r,i)}return this["_is_work_"+t](e)},_is_work_day:function(e){var t=this._getWorkHours(e);return Array.isArray(t)?t.length>0:!1},_is_work_hour:function(e){for(var t=this._getWorkHours(e),r=e.getUTCHours(),i=0;i<t.length;i++)if(r>=t[i].startHour&&r<t[i].endHour)return!0;return!1},_getTimeOfDayStamp:function(e,t){var r=e.getUTCHours();return!e.getUTCHours()&&!e.getUTCMinutes()&&t&&(r=24),r*60*60+e.getUTCMinutes()*60},_is_work_minute:function(e){for(var t=this._getWorkHours(e),r=this._getTimeOfDayStamp(e),i=0;i<t.length;i++)if(r>=t[i].start&&r<t[i].end)return!0;return!1},_nextDate:function(e,t,r){return this.$gantt.date.add(e,r,t)},_getWorkUnitsBetweenGeneric:function(e,t,r,i){var n=this.$gantt.date,o=new Date(e),a=new Date(t);i=i||1;var s=0,c=null,l,d,u=!1;l=n[r+"_start"](new Date(o)),l.valueOf()!=o.valueOf()&&(u=!0);var f=!1;d=n[r+"_start"](new Date(t)),d.valueOf()!=t.valueOf()&&(f=!0);for(var p=!1;o.valueOf()<a.valueOf();){if(c=this._nextDate(o,r,i),p=c.valueOf()>a.valueOf(),this._isWorkTime(o,r))(u||f&&p)&&(l=n[r+"_start"](new Date(o)),d=n.add(l,i,r)),u?(u=!1,c=this._nextDate(l,r,i),s+=(d.valueOf()-o.valueOf())/(d.valueOf()-l.valueOf())):f&&p?(f=!1,s+=(a.valueOf()-o.valueOf())/(d.valueOf()-l.valueOf())):s++;else{var y=this._getUnitOrder(r),g=this.units[y-1];g&&!this._isWorkTime(o,g)&&(c=this._getClosestWorkTimeFuture(o,g))}o=c}return s},_getMinutesPerHour:function(e){var t=this._getTimeOfDayStamp(e),r=this._getTimeOfDayStamp(this._nextDate(e,"hour",1));r===0&&(r=1440*60);for(var i=this._getWorkHours(e),n=0;n<i.length;n++){var o=i[n];if(t>=o.start&&r<=o.end)return 60;if(t<o.end&&r>o.start){var a=Math.min(r,o.end)-Math.max(t,o.start);return a/60}}return 0},_getMinutesPerDay:function(e){var t=this._getWorkHours(e),r=0;return t.forEach(function(i){r+=i.durationMinutes}),r},getHoursPerDay:function(e){var t=this._getWorkHours(e),r=0;return t.forEach(function(i){r+=i.durationHours}),r},_getWorkUnitsForRange:function(e,t,r,i){var n=0,o=new Date(e),a=new Date(t),s;for(r=="minute"?s=Bt(this._getMinutesPerDay,this):s=Bt(this.getHoursPerDay,this);o.valueOf()<a.valueOf();){if(a-o>1e3*60*60*24*32&&o.getUTCDate()===0){var c=this._largeUnitsCache.getMinutesPerMonth(o);r=="hour"&&(c=c/60),n+=c,o=this.$gantt.date.add(o,1,"month");continue}else if(a-o>1e3*60*60*24*16){var l=this.$gantt.date.week_start(new Date(o));if(o.valueOf()===l.valueOf()){var c=this._largeUnitsCache.getMinutesPerWeek(o);r=="hour"&&(c=c/60),n+=c,o=this.$gantt.date.add(o,7,"day");continue}}n+=s(o),o=this._nextDate(o,"day",1)}return n/i},_getMinutesBetweenSingleDay:function(e,t){for(var r=this._getIntervalTimestamp(e,t),i=this._getWorkHours(e),n=0,o=0;o<i.length;o++){var a=i[o];if(r.end>=a.start&&r.start<=a.end){var s=Math.max(a.start,r.start),c=Math.min(a.end,r.end);n+=(c-s)/60,r.start=c}}return Math.floor(n)},_getMinutesBetween:function(e,t,r,i){var n=new Date(e),o=new Date(t);i=i||1;var a=new Date(n),s=this.$gantt.date.add(this.$gantt.date.day_start(new Date(n)),1,"day");if(o.valueOf()<=s.valueOf())return this._getMinutesBetweenSingleDay(e,t);var c=this.$gantt.date.day_start(new Date(o)),l=o,d=this._getMinutesBetweenSingleDay(a,s),u=this._getMinutesBetweenSingleDay(c,l),f=this._getWorkUnitsForRange(s,c,r,i),p=d+f+u;return p},_getHoursBetween:function(e,t,r,i){var n=new Date(e),o=new Date(t);i=i||1;var a=new Date(n),s=this.$gantt.date.add(this.$gantt.date.day_start(new Date(n)),1,"day");if(o.valueOf()<=s.valueOf())return Math.round(this._getMinutesBetweenSingleDay(e,t)/60);var c=this.$gantt.date.day_start(new Date(o)),l=o,d=this._getMinutesBetweenSingleDay(a,s,r,i)/60,u=this._getMinutesBetweenSingleDay(c,l,r,i)/60,f=this._getWorkUnitsForRange(s,c,r,i),p=d+f+u;return Math.round(p)},getConfig:function(){return this._worktime},_setConfig:function(e){this._worktime=e,this._parseSettings(),this._clearCaches()},_parseSettings:function(){var e=this.getConfig();e.parsed={dates:{},hours:null,haveCustomWeeks:!1,customWeeks:{},customWeeksRangeStart:null,customWeeksRangeEnd:null,customWeeksBoundaries:[]},e.parsed.hours=this._parseHours(e.hours);for(var t in e.dates)e.parsed.dates[t]=this._parseHours(e.dates[t]);if(e.customWeeks){var r=null,i=null;for(var t in e.customWeeks){var n=e.customWeeks[t];if(n.from&&n.to){var o=n.from,a=n.to;(!r||r>o.valueOf())&&(r=o.valueOf()),(!i||i<a.valueOf())&&(i=a.valueOf()),e.parsed.customWeeksBoundaries.push({from:o.valueOf(),fromReadable:new Date(o),to:a.valueOf(),toReadable:new Date(a),name:t}),e.parsed.haveCustomWeeks=!0;var s=e.parsed.customWeeks[t]={from:n.from,to:n.to,hours:this._parseHours(n.hours),dates:{}};if(n.days&&!n.dates){n.dates=n.dates||{};for(var t=0;t<n.days.length;t++)n.dates[t]=n.days[t],n.days[t]instanceof Array||(n.dates[t]=!!n.days[t]);delete n.days}for(var c in n.dates)s.dates[c]=this._parseHours(n.dates[c])}}e.parsed.customWeeksRangeStart=r,e.parsed.customWeeksRangeEnd=i}},_tryChangeCalendarSettings:function(e){var t=JSON.stringify(this.getConfig());return e(),this.hasWorkTime()?!0:(this._setConfig(JSON.parse(t)),this._clearCaches(),!1)},_arraysEqual:function(e,t){if(e===t)return!0;if(!e||!t||e.length!=t.length)return!1;for(var r=0;r<e.length;++r)if(e[r]!==t[r])return!1;return!0},_compareSettings:function(e,t){if(!this._arraysEqual(e.hours,t.hours))return!1;var r=Object.keys(e.dates),i=Object.keys(t.dates);if(r.sort(),i.sort(),!this._arraysEqual(r,i))return!1;for(var n=0;n<r.length;n++){var o=r[n],a=e.dates[o],s=t.dates[o];if(a!==s&&!(Array.isArray(a)&&Array.isArray(s)&&this._arraysEqual(a,s)))return!1}return!0},equals:function(e){if(!(e instanceof ma))return!1;var t=this.getConfig(),r=e.getConfig();if(!this._compareSettings(t,r))return!1;if(t.parsed.haveCustomWeeks&&r.parsed.haveCustomWeeks){if(t.parsed.customWeeksBoundaries.length!=r.parsed.customWeeksBoundaries.length)return!1;for(var i in t.parsed.customWeeks){var n=t.parsed.customWeeks[i],o=r.parsed.customWeeks[i];if(!o||!this._compareSettings(n,o))return!1}}else if(t.parse.haveCustomWeeks!==r.parsed.haveCustomWeeks)return!1;return!0},getWorkHours:function(){var e=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);return this._getWorkHours(e.date,!1)},_getWorkHours:function(e,t){var r=this.getConfig();if(t!==!1&&(r=r.parsed),!e)return r.hours;let i=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));var n=this._timestamp({date:i});if(r.haveCustomWeeks&&r.customWeeksRangeStart<=n&&r.customWeeksRangeEnd>n){for(var o=0;o<r.customWeeksBoundaries.length;o++)if(r.customWeeksBoundaries[o].from<=n&&r.customWeeksBoundaries[o].to>n){r=r.customWeeks[r.customWeeksBoundaries[o].name];break}}var a=!0;return r.dates[n]!==void 0?a=r.dates[n]:r.dates[e.getUTCDay()]!==void 0&&(a=r.dates[e.getUTCDay()]),a===!0?r.hours:a||[]},_getIntervalTimestamp:function(e,t){var r={start:0,end:0};r.start=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds();var i=t.getUTCHours();return!i&&!t.getUTCMinutes()&&!t.getUTCSeconds()&&e.valueOf()<t.valueOf()&&(i=24),r.end=i*60*60+t.getUTCMinutes()*60+t.getUTCSeconds(),r},_parseHours:function(e){if(Array.isArray(e)){var t=[];e.forEach(function(s){typeof s=="number"?t.push(s*60*60):typeof s=="string"&&s.split("-").map(function(c){return c.trim()}).forEach(function(c){var l=c.split(":").map(function(u){return u.trim()}),d=parseInt(l[0]*60*60);l[1]&&(d+=parseInt(l[1]*60)),l[2]&&(d+=parseInt(l[2])),t.push(d)})});for(var r=[],i=0;i<t.length;i+=2){var n=t[i],o=t[i+1],a=o-n;r.push({start:n,end:o,startHour:Math.floor(n/3600),startMinute:Math.floor(n/60),endHour:Math.ceil(o/3600),endMinute:Math.ceil(o/60),durationSeconds:a,durationMinutes:a/60,durationHours:a/3600})}return r}else return e},setWorkTime:function(e){return this._tryChangeCalendarSettings(Bt(function(){var t=e.hours!==void 0?e.hours:!0,r=this._timestamp(e),i=this.getConfig();if(r!==null?i.dates[r]=t:e.customWeeks||(i.hours=t),e.customWeeks){if(i.customWeeks||(i.customWeeks={}),typeof e.customWeeks=="string")r!==null?i.customWeeks[e.customWeeks].dates[r]=t:e.customWeeks||(i.customWeeks[e.customWeeks].hours=t);else if(typeof e.customWeeks=="object"&&e.customWeeks.constructor===Object)for(var n in e.customWeeks)i.customWeeks[n]=e.customWeeks[n]}this._parseSettings(),this._clearCaches()},this))},unsetWorkTime:function(e){return this._tryChangeCalendarSettings(Bt(function(){if(!e)this.reset_calendar();else{var t=this._timestamp(e);t!==null&&delete this.getConfig().dates[t]}this._parseSettings(),this._clearCaches()},this))},_isWorkTime:function(e,t){var r=-1,i=null;return i=String(e.valueOf()),r=this._workingUnitsCache.getItem(t,i,e),r==-1&&(r=this._checkIfWorkingUnit(e,t),this._workingUnitsCache.setItem(t,i,r,e)),r},isWorkTime:function(){var e=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._isWorkTime(e.date,e.unit)},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments);if(!e.unit)return!1;var t=this;return this._dateDurationCache.getDuration(e.start_date,e.end_date,e.unit,e.step,function(){return t._calculateDuration(e.start_date,e.end_date,e.unit,e.step)})},_calculateDuration:function(e,t,r,i){var n=0,o=1;if(e.valueOf()>t.valueOf()){var a=t;t=e,e=a,o=-1}return r=="hour"&&i==1?n=this._getHoursBetween(e,t,r,i):r=="minute"&&i==1?n=this._getMinutesBetween(e,t,r,i):n=this._getWorkUnitsBetweenGeneric(e,t,r,i),o*Math.round(n)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit,n=e.step;if(!i)return!1;var o=new Date(t),a=new Date(r);for(n=n||1;o.valueOf()<a.valueOf();){if(this._isWorkTime(o,i))return!0;o=this._nextDate(o,i,n)}return!1},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,i=e.unit,n=e.step;if(!i)return!1;var o=e.duration>=0?1:-1;r=Math.abs(r*1);var a=this;return this._dateDurationCache.getEndDate(t,r,i,n*o,function(){return a._calculateEndDate(t,r,i,n*o)})},_calculateEndDate:function(e,t,r,i){if(!r)return!1;if(i==1&&r=="minute")return this._calculateMinuteEndDate(e,t,i);if(i==-1&&r=="minute")return this._subtractMinuteDate(e,t,i);if(i==1&&r=="hour")return this._calculateHourEndDate(e,t,i);var n=this._addInterval(e,t,r,i,null);return n.end},_addInterval:function(e,t,r,i,n){for(var o=0,a=e;o<t&&!(n&&n(a));){var s=this._nextDate(a,r,i),c=new Date(s.valueOf()+1);i>0&&(c=new Date(s.valueOf()-1));var l=this._isWorkTime(c,r);l&&o++,a=s}return{end:a,start:e,added:o}},_addHoursUntilDayEnd:function(e,t){for(var r=this.$gantt.date.add(this.$gantt.date.day_start(new Date(e)),1,"day"),i=0,n=t,o=this._getIntervalTimestamp(e,r),a=this._getWorkHours(e),s=0;s<a.length&&i<t;s++){var c=a[s];if(o.end>=c.start&&o.start<=c.end){var l=Math.max(c.start,o.start),d=Math.min(c.end,o.end),u=(d-l)/3600;u>n&&(u=n,d=l+n*60*60);var f=Math.round((d-l)/3600);i+=f,n-=f,o.start=d}}var p=r;return i===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,o.start))),{added:i,end:p}},_calculateHourEndDate:function(e,t,r){var i=new Date(e),n=0;r=r||1,t=Math.abs(t*1);var o=this._addHoursUntilDayEnd(i,t);n=o.added,i=o.end;var a=t-n;if(a){for(var s=i;n<t;){var c=this._nextDate(s,"day",r);c.setUTCHours(0),c.setUTCMinutes(0),c.setUTCSeconds(0);var l=0;if(r>0?l=this.getHoursPerDay(new Date(c.valueOf()-1)):l=this.getHoursPerDay(new Date(c.valueOf()+1)),n+l>=t)break;n+=l,s=c}i=s}if(n<t){var a=t-n;o=this._addHoursUntilDayEnd(i,a),i=o.end}return i},_addMinutesUntilHourEnd:function(e,t){if(e.getUTCMinutes()===0)return{added:0,end:new Date(e)};for(var r=this.$gantt.date.add(this.$gantt.date.hour_start(new Date(e)),1,"hour"),i=0,n=t,o=this._getIntervalTimestamp(e,r),a=this._getWorkHours(e),s=0;s<a.length&&i<t;s++){var c=a[s];if(o.end>=c.start&&o.start<=c.end){var l=Math.max(c.start,o.start),d=Math.min(c.end,o.end),u=(d-l)/60;u>n&&(u=n,d=l+n*60);var f=Math.round((d-l)/60);n-=f,i+=f,o.start=d}}var p=r;return i===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,o.start))),{added:i,end:p}},_subtractMinutesUntilHourStart:function(e,t){for(var r=this.$gantt.date.hour_start(new Date(e)),i=0,n=t,o=r.getUTCHours()*60*60+r.getUTCMinutes()*60+r.getUTCSeconds(),a=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds(),s=this._getWorkHours(e),c=s.length-1;c>=0&&i<t;c--){var l=s[c];if(a>l.start&&o<=l.end){var d=Math.min(a,l.end),u=Math.max(o,l.start),f=(d-u)/60;f>n&&(f=n,u=d-n*60);var p=Math.abs(Math.round((d-u)/60));n-=p,i+=p,a=u}}var y=r;return i===t&&(y=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a))),{added:i,end:y}},_subtractMinuteDate:function(e,t,r){var i=this.getClosestWorkTime({date:e,dir:"past",unit:"minute"}),n=0;r=r||-1,t=Math.abs(t*1),t=Math.round(t);let o=this._isMinutePrecision(i),a=this._subtractMinutesUntilHourStart(i,t);n+=a.added,i=a.end;for(var s=0,c=[],l=0;n<t;){var d=this.$gantt.date.day_start(new Date(i)),u=!1;i.valueOf()===d.valueOf()&&(d=this.$gantt.date.add(d,-1,"day"),u=!0);var f=new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),23,59,59,999)).valueOf();f!==s&&(c=this._getWorkHours(d),l=this._getMinutesPerDay(d),s=f);var p=t-n,y=this._getTimeOfDayStamp(i,u);if(!c.length||!l){i=this.$gantt.date.add(i,-1,"day");continue}if(c[c.length-1].end<=y&&p>l){n+=l,i=this.$gantt.date.add(i,-1,"day");continue}for(var g=!1,T=null,L=null,C=c.length-1;C>=0;C--)if(c[C].start<y-1&&c[C].end>=y-1){g=!0,T=c[C],L=c[C-1];break}if(g)if(y===T.end&&p>=T.durationMinutes)n+=T.durationMinutes,i=this.$gantt.date.add(i,-T.durationMinutes,"minute");else if(!o&&p<=y/60-T.startMinute)n+=p,i=this.$gantt.date.add(i,-p,"minute");else if(o)p<=y/60-T.startMinute?(n+=p,i=this.$gantt.date.add(i,-p,"minute")):(n+=y/60-T.startMinute,L?i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,L.end)):i=this.$gantt.date.day_start(i));else{var E=this._getMinutesPerHour(i);E<=p?(n+=E,i=this._nextDate(i,"hour",r)):(a=this._subtractMinutesUntilHourStart(i,p),n+=a.added,i=a.end)}else if(i.getUTCHours()===0&&i.getUTCMinutes()===0&&i.getUTCSeconds()===0){var I=this._getClosestWorkTimePast(i,"hour");if(I.valueOf()===i.valueOf()){var I=this.$gantt.date.add(i,-1,"day"),b=this._getWorkHours(I);if(b.length){var B=b[b.length-1];I.setUTCSeconds(B.durationSeconds)}}i=I}else i=this._getClosestWorkTimePast(new Date(i-1),"hour")}if(n<t){var k=t-n;a=this._subtractMinutesUntilHourStart(i,k),n+=a.added,i=a.end}return i},_calculateMinuteEndDate:function(e,t,r){var i=new Date(e),n=0;r=r||1,t=Math.abs(t*1),t=Math.round(t);var o=this._addMinutesUntilHourEnd(i,t);n+=o.added,i=o.end;for(var a=0,s=[],c=0,l=this._isMinutePrecision(i);n<t;){var d=this.$gantt.date.day_start(new Date(i)).valueOf();d!==a&&(s=this._getWorkHours(i),c=this._getMinutesPerDay(i),a=d);var u=t-n,f=this._getTimeOfDayStamp(i);if(!s.length||!c){i=this.$gantt.date.add(this.$gantt.date.day_start(i),1,"day");continue}if(s[0].start>=f&&u>=c){if(n+=c,u==c){i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,s[s.length-1].end));break}else i=this.$gantt.date.add(i,1,"day"),i=this.$gantt.date.day_start(i);continue}for(var p=!1,y=null,g=0;g<s.length;g++)if(s[g].start<=f&&s[g].end>f){p=!0,y=s[g];break}if(p)if(f===y.start&&u>=y.durationMinutes)n+=y.durationMinutes,i=this.$gantt.date.add(i,y.durationMinutes,"minute");else if(u<=y.endMinute-f/60)n+=u,i=this.$gantt.date.add(i,u,"minute");else{var T=this._getMinutesPerHour(i);T<=u?(n+=T,l?i=this.$gantt.date.add(i,T,"minute"):i=this._nextDate(i,"hour",r)):(o=this._addMinutesUntilHourEnd(i,u),n+=o.added,i=o.end)}else i=this._getClosestWorkTimeFuture(i,"hour")}if(n<t){var L=t-n;o=this._addMinutesUntilHourEnd(i,L),n+=o.added,i=o.end}return i},getClosestWorkTime:function(){var e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._getClosestWorkTime(e.date,e.unit,e.dir)},_getClosestWorkTime:function(e,t,r){var i=new Date(e);if(this._isWorkTime(i,t))return i;if(i=this.$gantt.date[t+"_start"](i),r=="any"||!r){var n=this._getClosestWorkTimeFuture(i,t),o=this._getClosestWorkTimePast(i,t);Math.abs(n-e)<=Math.abs(e-o)?i=n:i=o}else r=="past"?i=this._getClosestWorkTimePast(i,t):i=this._getClosestWorkTimeFuture(i,t);return i},_getClosestWorkTimeFuture:function(e,t){return this._getClosestWorkTimeGeneric(e,t,1)},_getClosestWorkTimePast:function(e,t){var r=this._getClosestWorkTimeGeneric(e,t,-1);return this.$gantt.date.add(r,1,t)},_findClosestTimeInDay:function(e,t,r){var i=new Date(e),n=null,o=!1;this._getWorkHours(i).length||(i=this._getClosestWorkTime(i,"day",t<0?"past":"future"),t<0&&(i=new Date(i.valueOf()-1),o=!0),r=this._getWorkHours(i));var a=this._getTimeOfDayStamp(i);if(o&&(a=this._getTimeOfDayStamp(new Date(i.valueOf()+1),o)),t>0){for(var s=0;s<r.length;s++)if(r[s].start>=a){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,r[s].start));break}}else for(var s=r.length-1;s>=0;s--)if(r[s].end<=a){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,r[s].end));break}else if(r[s].end>a&&r[s].start<=a){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,a));break}return n},_getClosestWorkMinute:function(e,t,r){var i=new Date(e),n=this._getWorkHours(i),o=this._findClosestTimeInDay(i,r,n);return o||(r>0?(i=this.calculateEndDate(i,r,t),i=this.$gantt.date.day_start(i)):(i=this.calculateEndDate(i,r,"day"),i=this.$gantt.date.day_start(i),i=this.$gantt.date.add(i,1,"day"),i=new Date(i.valueOf()-1)),n=this._getWorkHours(i),o=this._findClosestTimeInDay(i,r,n)),r<0&&(o=this.$gantt.date.add(o,-1,t)),o},_getClosestWorkTimeGeneric:function(e,t,r){if(t==="hour"||t==="minute")return this._getClosestWorkMinute(e,t,r);for(var i=this._getUnitOrder(t),n=this.units[i-1],o=e,a=3e3,s=0;!this._isWorkTime(o,t)&&!(n&&!this._isWorkTime(o,n)&&(r>0?o=this._getClosestWorkTimeFuture(o,n):o=this._getClosestWorkTimePast(o,n),this._isWorkTime(o,t)));){if(s++,s>a)return this.$gantt.assert(!1,"Invalid working time check"),!1;o=this.$gantt.date.add(o,r,t),this.$gantt.date[t+"_start"]&&(o=this.$gantt.date[t+"_start"](o))}return o},hasWorkTime:function(){var e=this.getConfig(),t=e.dates,r=[0,1,2,3,4,5,6];for(var i in e.dates);var n=this._checkWorkHours(e.hours),o=!1;return r.forEach((function(a){if(!o){var s=t[a];s===!0?o=n:Array.isArray(s)&&(o=this._checkWorkHours(s))}}).bind(this)),o},_checkWorkHours:function(e){if(e.length===0)return!1;for(var t=!1,r=0;r<e.length;r+=2)e[r]!==e[r+1]&&(t=!0);return t},_isMinutePrecision:function(e){let t=!1;return this._getWorkHours(e).forEach(function(r){(r.startMinute%60||r.endMinute%60)&&(t=!0)}),t}};var Xr={isLegacyResourceCalendarFormat:function(e){if(!e)return!1;for(var t in e)if(e[t]&&typeof e[t]=="object")return!0;return!1},getResourceProperty:function(e){var t=e.resource_calendars,r=e.resource_property;if(this.isLegacyResourceCalendarFormat(t))for(var i in e){r=i;break}return r},getCalendarIdFromLegacyConfig:function(e,t){if(t)for(var r in t){var i=t[r];if(e[r]){var n=i[e[r]];if(n)return n}}return null}};function cg(){function e(n){return n.map(function(o){return o&&o.resource_id?o.resource_id:o}).sort().join("-")}var t={};function r(n,o){return o.mergeCalendars(n.map(function(a){var s=a&&a.resource_id?a.resource_id:a;return o.getResourceCalendar(s)}))}function i(n,o){var a=e(n);if(n.length){if(n.length===1)return o.getResourceCalendar(a).id;if(t[a])return t[a].id;var s=r(n,o);return t[a]=s,o.addCalendar(s)}else return null}return{getCalendarIdFromMultipleResources:i}}var lg=cg();function Sd(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=Xr.isLegacyResourceCalendarFormat(this.$gantt.config.resource_calendars))}).bind(this)),this.$gantt.attachEvent("onBeforeGanttReady",(function(){this.createDefaultCalendars()}).bind(this)),this.$gantt.attachEvent("onBeforeGanttRender",(function(){this.createDefaultCalendars()}).bind(this))}Sd.prototype={_calendars:{},_convertWorkTimeSettings:function(e){let t=e.days;if(typeof t=="object"&&!Array.isArray(t)&&t!==null){let r={};if(t?.weekdays)for(let i=0;i<7;i++)r[i]=t.weekdays[i];t?.dates&&Object.entries(t.dates).forEach(([i,n])=>{r[new Date(i).valueOf()]=n}),Object.entries(r).forEach(([i,n])=>{n instanceof Array||(r[i]=!!n)}),e={...e,dates:r}}else if(t&&!e.dates){e.dates=e.dates||{};for(let r=0;r<t.length;r++)e.dates[r]=t[r],t[r]instanceof Array||(e.dates[r]=!!t[r])}return delete e.days,e},mergeCalendars:function(){var e=[],t=arguments;if(Array.isArray(t[0]))e=t[0].slice();else for(var r=0;r<arguments.length;r++)e.push(arguments[r]);var i=new Cd,n;return e.forEach((function(o){n?n=this._createCalendarFromConfig(i.merge(n,o)):n=o}).bind(this)),this.createCalendar(n)},_createCalendarFromConfig:function(e){var t=new ma(this.$gantt,vd(this.$gantt));t.id=String(ca());var r=this._convertWorkTimeSettings(e);if(r.customWeeks)for(var i in r.customWeeks)r.customWeeks[i]=this._convertWorkTimeSettings(r.customWeeks[i]);return t._setConfig(r),t},createCalendar:function(e){var t;e||(e={}),e.getConfig?t=Jt(e.getConfig()):e.worktime?t=Jt(e.worktime):t=Jt(e);var r=Jt(this.defaults.fulltime.worktime);return Cr(t,r),this._createCalendarFromConfig(t)},getCalendar:function(e){e=e||"global";var t=this._calendars[e];return t||(this.createDefaultCalendars(),t=this._calendars[e]),t},getCalendars:function(){var e=[];for(var t in this._calendars)e.push(this.getCalendar(t));return e},_getOwnCalendar:function(e){var t=this.$gantt.config;if(e[t.calendar_property])return this.getCalendar(e[t.calendar_property]);if(t.resource_calendars){var r,i,n;if(this._legacyConfig===!1?n=t.resource_property:n=Xr.getResourceProperty(t),Array.isArray(e[n])&&e[n].length)t.dynamic_resource_calendars?i=lg.getCalendarIdFromMultipleResources(e[n],this):r=this.getResourceCalendar(e[n]);else if(this._legacyConfig===void 0&&(this._legacyConfig=Xr.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var i=Xr.getCalendarIdFromLegacyConfig(e,t.resource_calendars);else if(n&&e[n]&&t.resource_calendars[e[n]])var r=this.getResourceCalendar(e[n]);if(i&&(r=this.getCalendar(i)),r)return r}return null},getResourceCalendar:function(e){if(e==null)return this.getCalendar();var t=null;typeof e=="number"||typeof e=="string"?t=e:t=e.id||e.key;var r=this.$gantt.config,i=r.resource_calendars,n=null;if(Array.isArray(e)&&e.length===1&&(typeof e[0]=="object"?t=e[0].resource_id:t=e[0]),i){if(this._legacyConfig===void 0&&(this._legacyConfig=Xr.isLegacyResourceCalendarFormat(r.resource_calendars)),this._legacyConfig){for(var o in i)if(i[o][t]){n=i[o][t];break}}else var n=i[t];if(n)return this.getCalendar(n)}return this.getCalendar()},getTaskCalendar:function(e){var t=this.$gantt,r;if(e==null)return this.getCalendar();if((typeof e=="number"||typeof e=="string")&&t.isTaskExists(e)?r=t.getTask(e):r=e,!r)return this.getCalendar();var i=this._getOwnCalendar(r),n=!!t.getState().group_mode;if(!i&&t.config.inherit_calendar&&t.isTaskExists(r.parent)){for(var o=r;t.isTaskExists(o.parent)&&(o=t.getTask(o.parent),!(t.isSummaryTask(o)&&(i=this._getOwnCalendar(o),i))););n&&!i&&e.$effective_calendar&&(i=this.getCalendar(e.$effective_calendar))}return i||this.getCalendar()},addCalendar:function(e){if(!this.isCalendar(e)){var t=e.id;e=this.createCalendar(e),e.id=t}if(e._tryChangeCalendarSettings(function(){})){var r=this.$gantt.config;return e.id=e.id||ca(),this._calendars[e.id]=e,r.worktimes||(r.worktimes={}),r.worktimes[e.id]=e.getConfig(),e.id}else return this.$gantt.callEvent("onCalendarError",[{message:"Invalid calendar settings, no worktime available"},e]),null},deleteCalendar:function(e){var t=this.$gantt.config;return e&&this._calendars[e]?(delete this._calendars[e],t.worktimes&&t.worktimes[e]&&delete t.worktimes[e],!0):!1},restoreConfigCalendars:function(e){for(var t in e)if(!this._calendars[t]){var r=e[t],i=this.createCalendar(r);i.id=t,this.addCalendar(i)}},defaults:{global:{id:"global",worktime:{hours:[8,12,13,17],days:[0,1,1,1,1,1,0]}},fulltime:{id:"fulltime",worktime:{hours:[0,24],days:[1,1,1,1,1,1,1]}}},createDefaultCalendars:function(){var e=this.$gantt.config;this.restoreConfigCalendars(this.defaults),this.restoreConfigCalendars(e.worktimes)},isCalendar:function(e){var t=[e.isWorkTime,e.setWorkTime,e.getWorkHours,e.unsetWorkTime,e.getClosestWorkTime,e.calculateDuration,e.hasDuration,e.calculateEndDate];return t.every(function(r){return r instanceof Function})}};function Ia(e,t){this.argumentsHelper=t,this.$gantt=e}Ia.prototype={getWorkHours:function(){return[0,24]},setWorkTime:function(){return!0},unsetWorkTime:function(){return!0},isWorkTime:function(){return!0},getClosestWorkTime:function(t){var t=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return t.date},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit,n=e.step;return this._calculateDuration(t,r,i,n)},_calculateDuration:function(e,t,r,i){var n=this.$gantt.date,o={week:1e3*60*60*24*7,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60},a=0;if(o[r])a=Math.round((t-e)/(i*o[r]));else{for(var s=new Date(e),c=new Date(t);s.valueOf()<c.valueOf();)a+=1,s=n.add(s,i,r);s.valueOf()!=t.valueOf()&&(a+=(c-s)/(n.add(s,i,r)-s))}return Math.round(a)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit;return i?(t=new Date(t),r=new Date(r),t.valueOf()<r.valueOf()):!1},hasWorkTime:function(){return!0},equals:function(e){return e instanceof Ia},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,i=e.unit,n=e.step;return this.$gantt.date.add(t,n*r,i)}};function Td(e){this.$gantt=e.$gantt,this.argumentsHelper=vd(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new Ia(this.$gantt,this.argumentsHelper)}Td.prototype={_getCalendar:function(e){var t;if(!this.$gantt.config.work_time)t=this.$disabledCalendar;else{var r=this.calendarManager;e.task?t=r.getTaskCalendar(e.task):e.id?t=r.getTaskCalendar(e):e.calendar&&(t=e.calendar),t||(t=r.getTaskCalendar())}return t},getWorkHours:function(e){e=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);var t=this._getCalendar(e);return t.getWorkHours(e.date)},setWorkTime:function(e,t){return e=this.argumentsHelper.setWorkTimeArguments.apply(this.argumentsHelper,arguments),t||(t=this.calendarManager.getCalendar()),t.setWorkTime(e)},unsetWorkTime:function(e,t){return e=this.argumentsHelper.unsetWorkTimeArguments.apply(this.argumentsHelper,arguments),t||(t=this.calendarManager.getCalendar()),t.unsetWorkTime(e)},isWorkTime:function(e,t,r,i){var n=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return i=this._getCalendar(n),i.isWorkTime(n)},getClosestWorkTime:function(e){e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);var t=this._getCalendar(e);return t.getClosestWorkTime(e)},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=this._getCalendar(e);return t.calculateDuration(e)},hasDuration:function(){var e=this.argumentsHelper.hasDurationArguments.apply(this.argumentsHelper,arguments),t=this._getCalendar(e);return t.hasDuration(e)},calculateEndDate:function(t){var t=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),r=this._getCalendar(t);return r.calculateEndDate(t)}};var dg=function(e,t){return{getWorkHours:function(r){return t.getWorkHours(r)},setWorkTime:function(r){return t.setWorkTime(r)},unsetWorkTime:function(r){t.unsetWorkTime(r)},isWorkTime:function(r,i,n){return t.isWorkTime(r,i,n)},getClosestWorkTime:function(r){return t.getClosestWorkTime(r)},calculateDuration:function(r,i,n){return t.calculateDuration(r,i,n)},_hasDuration:function(r,i,n){return t.hasDuration(r,i,n)},calculateEndDate:function(r,i,n,o){return t.calculateEndDate(r,i,n,o)},mergeCalendars:Bt(e.mergeCalendars,e),createCalendar:Bt(e.createCalendar,e),addCalendar:Bt(e.addCalendar,e),getCalendar:Bt(e.getCalendar,e),getCalendars:Bt(e.getCalendars,e),getResourceCalendar:Bt(e.getResourceCalendar,e),getTaskCalendar:Bt(e.getTaskCalendar,e),deleteCalendar:Bt(e.deleteCalendar,e)}},ug={create:dg};function Ed(e){var t=new Sd(e),r=new Td(t),i=ug.create(t,r);Cr(e,i)}var Dd={date:{month_full:["January","February","March","April","May","June","July","August","September","October","November","December"],month_short:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],day_full:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],day_short:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},labels:{}};function _d(e={}){let t=e.config||{},r={config:Object.assign({duration_unit:"hour",duration_step:1,work_time:!1,worktimes:{},work_days:null,inherit_calendar:!1,calendar_property:"calendar_id",resource_property:"resource_id",resource_calendars:{},dynamic_resource_calendars:!1,start_on_monday:!0,server_utc:!0,csp:"auto",show_errors:!1},t),locale:e.locale||Dd,templates:e.templates||{},getTask:e.getTask||function(i){return null},isTaskExists:e.isTaskExists||function(i){return!1},isSummaryTask:e.isSummaryTask||function(i){return!1},getState:function(){return{group_mode:!1}},callEvent:function(i,n){let o=e.onEvent;return o&&o(i,n),!0},attachEvent:function(){return 0},checkEvent:function(){return!1},detachEvent:function(){},defined:md,mixin:Cr,copy:Jt,assert:function(i,n){if(!i){if(e.throwOnAssert)throw new Error("[calendar] "+n);e.silent!==!0&&console.error("[calendar]",n)}},$services:{getService:function(){return null}},$ui:{getView:function(){return null}}};return r._correct_dst_change=function(i){return i},r.date=Ad(r),r.date.init(),Ed(r),r}function fg(e={}){let t=_d(e);return{addCalendar:function(r){return t.addCalendar(r)},deleteCalendar:function(r){return t.deleteCalendar(r)},getCalendar:function(r){return t.getCalendar(r)},getCalendars:function(){return t.getCalendars()},mergeCalendars:function(){return t.mergeCalendars.apply(t,arguments)},getTaskCalendar:function(r){return t.getTaskCalendar(r)},getResourceCalendar:function(r){return t.getResourceCalendar(r)},setWorkTime:function(r){return t.setWorkTime(r)},unsetWorkTime:function(r){return t.unsetWorkTime(r)},isWorkTime:function(){return t.isWorkTime.apply(t,arguments)},getClosestWorkTime:function(){return t.getClosestWorkTime.apply(t,arguments)},getWorkHours:function(){return t.getWorkHours.apply(t,arguments)},calculateDuration:function(){return t.calculateDuration.apply(t,arguments)},calculateEndDate:function(){return t.calculateEndDate.apply(t,arguments)},_internals:t}}var kd={createCalendar:fg};var sU=3600*1e3;function Od(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:pg}=kd,Zr="__replay_default__";function yg(e){if(!e||e.length===0||typeof e[0]=="string")return e;let t=e.map(Number);if(t.some(o=>Number.isNaN(o)))return e;let r=t[0],i=t[t.length-1];return t.every((o,a)=>o===r+a)?[`${r}:00-${i+1}:00`]:e}var Rd={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},Pd="__main_global__",hg={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function Ld(e){return!e||e.hours===void 0||e.hours.length>0||e.days?.some(t=>Array.isArray(t)&&t.length>0)===!0?!0:Object.values(e.dates??{}).some(t=>Array.isArray(t)&&t.length>0)}function mg(e){let t={};if(Array.isArray(e.days))for(let i=0;i<e.days.length;i+=1)t[i]=e.days[i];if(e.dates)for(let[i,n]of Object.entries(e.dates))t[i]=n;let r={hours:yg(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function Nd(e){let t=pg({config:{work_time:!0}});t.addCalendar({id:Zr,worktime:Rd}),t.addCalendar({id:Pd,worktime:hg});let r=new Set(e.filter(d=>!Ld(d.worktime)).map(d=>String(d.id))),i=e.filter(d=>Ld(d.worktime));for(let d of i)t.addCalendar({id:d.id,worktime:d.worktime?mg(d.worktime):Rd});let n=hd(t),o=n.getCalendar(Zr),a=n.getCalendar(Pd);if(!o||!a)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let s=new Set([Zr]);for(let d of i)s.add(String(d.id));let c=new Map;return{reader:{getCalendar(d){let u=String(d),f=c.get(u);if(f)return f;let p=o;return s.has(u)?p=n.getCalendar(d)??o:r.has(u)&&(p=a),c.set(u,p),p}}}}function bd(e){return{hasChildren(t){return e.hasChildren(t)},getParentStartDateIfHasPredecessors(t){let r=e.getActivity(t);if(!r)return null;let i=e.getParent(r.id);return!i||e.getIncomingLinkIds(i.id).length===0?null:i.startDate},getDescendantIds(t){return Ig(e,t).map(r=>String(r))},getAncestorIds(t){let r=[],i=e.getActivity(t);for(;i;){let n=i.parentId;if(n===null)break;let o=e.getActivity(n);if(!o)break;r.push(String(n)),i=o}return r},getChildProgressInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,progress:Number(n?.progress??0),ponderator:Number(n?.ponderator??0)}})},getChildHhInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,workHours:Number(n?.workHours??0),progress:Number(n?.progress??0),realWorkHours:Number(n?.realWorkHours??0)}})},getChildUsedCostInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,usedCost:Number(n?.usedCost??0)}})},getChildCostInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,cost:Number(n?.cost??0)}})}}}function Ig(e,t){let r=[],i=new xt;for(let n of e.getChildren(t))i.enqueue(n);for(;!i.isEmpty();){let n=i.dequeue();r.push(n);for(let o of e.getChildren(n))i.enqueue(o)}return r}var vn=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=Fd(t);return this.reader.getCalendar(r??Zr)}getClosestWorkTime(t){let r=`${Aa(t.task)}|${t.dir}|${t.date.getTime()}`;return ga(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:mt.HOUR}))}calculateEndDate(t){let r=`${Aa(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return ga(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${Aa(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return ga(this._cache.duration,r,()=>this.resolveCalendar(t.task).calculateDuration(t.startDate,t.endDate))}clearCache(){this._cache.closestWorkTime.clear(),this._cache.endDate.clear(),this._cache.duration.clear()}};function ga(e,t,r){let i=e.get(t);if(i!==void 0)return i;let n=r();return e.set(t,n),n}var gg="__default__";function Fd(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function Aa(e){return Fd(e)??gg}var Cn=class{constructor(t){this.activities=t}activities;_childrenByParent=new Map;_roots=[];_dirty=!1;markDirty(){this._dirty=!0}getChildren(t){return this._dirty&&(this.rebuild(),this._dirty=!1),this._childrenByParent.get(String(t))??[]}hasChildren(t){return this._dirty&&(this.rebuild(),this._dirty=!1),(this._childrenByParent.get(String(t))?.length??0)>0}getRootIds(){return this._dirty&&(this.rebuild(),this._dirty=!1),[...this._roots]}isChildOf(t,r){let i=this.activities.get(t)?.parentId,n=0,o=this.activities.size;for(;i&&!M(i);){if(i===r)return!0;if(++n>o)return!1;i=this.activities.get(i)?.parentId}return!1}getParent(t){let r=this.activities.get(t)?.parentId;return!r||M(r)?null:this.activities.get(r)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,r){if(this._dirty)return;if(M(t)){this._roots.push(r);return}let i=String(t),n=this._childrenByParent.get(i);n?n.push(r):this._childrenByParent.set(i,[r])}rebuild(){this._childrenByParent.clear(),this._roots=[];for(let r of this.activities.values()){if(M(r.parentId)){this._roots.push(r.id);continue}let i=String(r.parentId),n=this._childrenByParent.get(i)??[];n.push(r.id),this._childrenByParent.set(i,n)}let t=(r,i)=>{let n=this.activities.get(r),o=this.activities.get(i);return n&&o?li(n,o):String(r).localeCompare(String(i))};this._roots.sort(t);for(let r of this._childrenByParent.values())r.sort(t)}};var Sn=class{checkedSet=new Set;hiddenSet=new Set;activeFilter=null;activeOrder=null;isChecked(t){return this.checkedSet.has(t)}isVisible(t){return!this.hiddenSet.has(t)}hiddenIds(){return[...this.hiddenSet]}getActiveFilter(){return this.activeFilter}setActiveFilter(t){this.activeFilter=t}getActiveOrder(){return this.activeOrder}setActiveOrder(t){this.activeOrder=t}checkedIds(){return[...this.checkedSet]}checkedCount(){return this.checkedSet.size}setChecked(t,r){return r===this.checkedSet.has(t)?!1:(r?this.checkedSet.add(t):this.checkedSet.delete(t),!0)}setVisible(t,r){return r===!this.hiddenSet.has(t)?!1:(r?this.hiddenSet.delete(t):this.hiddenSet.add(t),!0)}forget(t){this.checkedSet.delete(t),this.hiddenSet.delete(t)}hydrate(t){this.checkedSet=new Set(t.checkedIds??[]),this.hiddenSet=new Set(t.hiddenIds??[]),this.activeFilter=null,this.activeOrder=null}snapshot(){return{checked:new Set(this.checkedSet),hidden:new Set(this.hiddenSet),activeFilter:this.activeFilter,activeOrder:this.activeOrder}}restore(t){this.checkedSet=new Set(t.checked),this.hiddenSet=new Set(t.hidden),this.activeFilter=t.activeFilter,this.activeOrder=t.activeOrder}};var Sr=class e{_activities=new Map;_lastStartDate=new Map;_promotionSnapshot=new Map;_progressFallback=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_buildOrderComparator;_cache={ids:null,visualOrderIds:null,orderComparator:null};_writeCapture=new Ji;_viewState=new Sn;_filterProjection=null;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_calendar;_flags;_calendarSnapshot;constructor(t,r=()=>null){this._buildOrderComparator=r,this._calendarSnapshot=F(t.calendars);for(let i of t.activities)this._activities.set(i.id,i);for(let i of t.links){let n={...i,freeSlackHours:i.freeSlackHours??null,isCritical:i.isCritical===!0};this._links.set(String(i.id),n),this._indexLink(n)}this._calendar=new vn(Nd(this._calendarSnapshot)),this._flags=vg(t),this._hierarchy=new Cn(this._activities),this._hierarchy.rebuild()}fork(){let t=new e({activities:this.getAllActivities().map(ae),links:this.getAllLinks().map(r=>({...r})),calendars:F(this._calendarSnapshot)},this._buildOrderComparator);return t._viewState.restore(F(this._viewState.snapshot())),t._lastStartDate=new Map(Array.from(this._lastStartDate,([r,i])=>[r,new Date(i)])),t._promotionSnapshot=new Map(Array.from(this._promotionSnapshot,([r,i])=>[r,F(i)])),t._progressFallback=new Map(this._progressFallback),t._flags=F(this._flags),t._filterProjection=F(this._filterProjection),t}getAllActivities(){return Array.from(this._activities.values())}getAllLinks(){return Array.from(this._links.values())}getAllIds(){return this._cache.ids?this._cache.ids:(this._cache.ids=Array.from(this._activities.keys()),this._cache.ids)}activityCount(){return this._activities.size}getVisualOrderIds(){return this._cache.visualOrderIds?this._cache.visualOrderIds:(this._cache.visualOrderIds=cs(this).map(t=>String(t.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null}forEachActivity(t){for(let[r,i]of this._activities)t(i,r)}getParentId(t){return this._hierarchy.getParentId(t)}getActivity(t){return this._activities.get(String(t))??null}getLastStartDate(t){return this._lastStartDate.get(String(t))??null}setLastStartDate(t,r){this._captureLastStartDateOnce(),this._lastStartDate.set(String(t),r)}getPromotionSnapshot(t){return this._promotionSnapshot.get(String(t))??null}setPromotionSnapshot(t,r){this._capturePromotionSnapshotOnce(),this._promotionSnapshot.set(String(t),r)}getProgressFallback(t){return this._progressFallback.get(String(t))??null}setProgressFallback(t,r){let i=String(t),n=this._progressFallback.get(i)??null;Object.is(n,r)||(this._writeCapture.noteProgressFallback(i,n),r===null?this._progressFallback.delete(i):this._progressFallback.set(i,r))}_capturePromotionSnapshotOnce(){this._writeCapture.peek()!==null&&this._promotionSnapshotBefore===null&&(this._promotionSnapshotBefore=new Map(this._promotionSnapshot))}_captureLastStartDateOnce(){this._writeCapture.peek()!==null&&this._lastStartDateBefore===null&&(this._lastStartDateBefore=new Map(this._lastStartDate))}getLink(t){return this._links.get(String(t))??null}activityExists(t){return this._activities.has(String(t))}isChecked(t){return this._viewState.isChecked(String(t))}isVisible(t){return this._viewState.isVisible(String(t))}checkedIds(){return this._viewState.checkedIds()}hiddenIds(){return this._viewState.hiddenIds()}setChecked(t,r){return this._captureViewStateOnce(),this._viewState.setChecked(String(t),r)}setVisible(t,r){return this._captureViewStateOnce(),this._viewState.setVisible(String(t),r)}getActiveFilter(){return this._viewState.getActiveFilter()}setActiveFilter(t){this._captureViewStateOnce(),this._viewState.setActiveFilter(t),this._filterProjection=null}getFilterProjection(){return this._filterProjection}setFilterProjection(t){this._filterProjection=t}getActiveOrder(){return this._viewState.getActiveOrder()}setActiveOrder(t){this._captureViewStateOnce(),this._viewState.setActiveOrder(t),this.invalidateDerivedOrder()}getOrderComparator(){let t=this._viewState.getActiveOrder();return t===null?(this._cache.orderComparator=null,null):this._cache.orderComparator?this._cache.orderComparator:(this._cache.orderComparator=this._buildOrderComparator(t),this._cache.orderComparator)}invalidateDerivedOrder(){this._cache.orderComparator=null,this._cache.visualOrderIds=null}hydrateViewState(t){this._viewState.hydrate(t),this._filterProjection=null,this.invalidateDerivedOrder()}_captureViewStateOnce(){this._writeCapture.peek()!==null&&this._viewStateBefore===null&&(this._viewStateBefore=this._viewState.snapshot())}getOutgoingLinkIds(t){return this._outgoing.get(String(t))??wd}getIncomingLinkIds(t){return this._incoming.get(String(t))??wd}getChildren(t){return this._hierarchy.getChildren(t)}hasChildren(t){return this._hierarchy.hasChildren(t)}isChildOf(t,r){return this._hierarchy.isChildOf(t,r)}getParent(t){return this._hierarchy.getParent(t)}getRootIds(){return this._hierarchy.getRootIds()}getClosestWorkTime(t){return this._calendar.getClosestWorkTime(t)}calculateEndDate(t){return this._calendar.calculateEndDate(t)}calculateDuration(t){return this._calendar.calculateDuration(t)}clearCalendarCache(){this._calendar.clearCache()}get calendarReader(){return this._calendar.reader}batchUpdate(t){t()}updateActivity(t){}getLiveActivity(t){return this.getActivity(t)}getFlags(){return{...this._flags,allCheckedTaskIds:this._viewState.checkedIds()}}getProjectEnd(){return null}beginWriteCapture(){this._writeCapture.begin(),this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=null}peekWriteCapture(){return this._writeCapture.peek()}endWriteCapture(){this._writeCapture.end(),this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=null}setActivityField(t,r,i){let n=this.getActivity(t);n&&(this._writeCapture.note(String(t),n),n[r]=i,Ca(n,r),r===x.PARENT&&this._hierarchy.markDirty(),va(r)&&(this._cache.visualOrderIds=null))}setActivityFieldDynamic(t,r,i){let n=this.getActivity(t);if(n){if(!Object.hasOwn(n,r))throw new Error(`setActivityFieldDynamic: unknown CoreActivity field "${r}"`);this._writeCapture.note(String(t),n),Reflect.set(n,r,yd(r,i)),Ca(n,r),r===x.PARENT&&this._hierarchy.markDirty(),va(r)&&(this._cache.visualOrderIds=null)}}setActivityFields(t,r){let i=this.getActivity(t);if(!i)return;this._writeCapture.note(String(t),i);let n=!1;for(let o of Object.keys(r))Reflect.set(i,o,Reflect.get(r,o)),Ca(i,o),o===x.PARENT&&(n=!0),va(o)&&(this._cache.visualOrderIds=null);n&&this._hierarchy.markDirty()}addLink(t){this._writeCapture.noteLinkAdd(String(t.id));let r=this._links.get(String(t.id));r&&this._deindexLink(r);let i={...t,freeSlackHours:t.freeSlackHours??null,isCritical:t.isCritical===!0};this._links.set(String(t.id),i),this._indexLink(i)}_indexLink(t){Md(this._outgoing,String(t.source),t.id),Md(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),xd(r,t.id));let i=this._incoming.get(String(t.target));i&&this._incoming.set(String(t.target),xd(i,t.id))}setLinkField(t,r,i){let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),n[r]=i)}setLinkFieldDynamic(t,r,i){if(!Ag(r))return;let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),Reflect.set(n,r,i))}setLinkProplannerId(t,r){let i=this.getLink(t);i&&(this._writeCapture.noteLinkField(String(t),i),i.proplannerId=r)}removeLink(t){let r=this.getLink(t);r&&(this._writeCapture.noteLinkRemove(String(t),r),this._links.delete(String(t)),this._deindexLink(r))}addActivity(t){this._writeCapture.noteInsert(String(t.id)),this._activities.set(t.id,t),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.addChild(t.parentId,t.id)}removeActivity(t){let r=this.getActivity(t);r&&this._writeCapture.noteRemove(String(t),r);let i=String(t);this.setProgressFallback(i,null),(this._viewState.isChecked(i)||!this._viewState.isVisible(i))&&this._captureViewStateOnce(),this._viewState.forget(i),this._activities.delete(t),this._lastStartDate.has(String(t))&&(this._captureLastStartDateOnce(),this._lastStartDate.delete(String(t))),this._outgoing.delete(String(t)),this._incoming.delete(String(t)),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}noteCorrelativeBefore(t,r){this._writeCapture.noteCorrelativeBefore(t,r)}noteScheduledBefore(t,r){this._writeCapture.noteScheduledBefore(t,r)}restoreFromCapture(){let t=this._writeCapture.peek();if(!t)return;let{ops:r,before:i,correlativeBefore:n,scheduledBefore:o,progressFallbackBefore:a}=t;this._undoLinkAdds(r),this._undoInserts(r),this._reInsertRemovedActivities(r),this._reAddRemovedLinks(r),this._restoreLinkFields(r),this._restoreActivityFields(o),this._restoreActivityFields(i),this._restoreCorrelatives(n),this._restoreProgressFallbacks(a),this._viewStateBefore!==null&&(this._viewState.restore(this._viewStateBefore),this._filterProjection=null,this.invalidateDerivedOrder()),this._promotionSnapshotBefore!==null&&(this._promotionSnapshot=this._promotionSnapshotBefore),this._lastStartDateBefore!==null&&(this._lastStartDate=this._lastStartDateBefore),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}_restoreProgressFallbacks(t){for(let[r,i]of t)i===null?this._progressFallback.delete(r):this._progressFallback.set(r,i)}_restoreCorrelatives(t){for(let[r,i]of t){let n=this._activities.get(r);n&&(n.correlativeId=i)}}_undoLinkAdds(t){for(let r of t)r.kind===Et.LINK_ADD&&this._detachLink(r.linkId)}_undoInserts(t){for(let r of t)r.kind===Et.INSERT&&this._activities.delete(r.activityId)}_reInsertRemovedActivities(t){for(let r of t)r.kind===Et.REMOVE&&this._activities.set(r.activityId,r.before)}_reAddRemovedLinks(t){for(let r of t)r.kind===Et.LINK_REMOVE&&this._attachLink(r.before)}_restoreLinkFields(t){for(let r of t)r.kind===Et.LINK_FIELD&&this._links.has(r.linkId)&&this._links.set(r.linkId,r.before)}_restoreActivityFields(t){for(let[r,i]of t){let n=this._activities.get(r);n&&this._restoreScalarFields(n,i)}}_restoreScalarFields(t,r){for(let i of Object.keys(t))Object.hasOwn(r,i)||Reflect.deleteProperty(t,i);for(let i of Object.keys(r))Reflect.set(t,i,Reflect.get(r,i))}_attachLink(t){this._links.set(String(t.id),{...t}),this._indexLink(t)}_detachLink(t){let r=this.getLink(t);r&&(this._links.delete(String(t)),this._deindexLink(r))}},wd=[];function Ag(e){return e===Vr.LAG||e===Vr.TYPE||e===Vr.FREE_SLACK_HOURS||e===Vr.IS_CRITICAL}function va(e){return e===x.PARENT||e===x.CORRELATIVE_ID}function Ca(e,t){t!==x.START_DATE&&t!==x.END_DATE&&t!==x.TYPE||(e.calendarDuration=Qt(e))}function xd(e,t){return e.filter(r=>String(r)!==String(t))}function Md(e,t,r){let i=e.get(t);i?i.push(r):e.set(t,[r])}function vg(e){let t=e.runtimeFlags??{};return{isPasting:!!t.isPasting,isBulkOperation:!!t.isBulkOperation,dragWithMultiple:!!t.dragWithMultiple,draggingSingleMilestone:!!t.draggingSingleMilestone,creatingActivity:!1,avoidAutoScheduleBeforeDrag:!1,maxPerformance:!!t.maxPerformance,allCheckedTaskIds:[]}}function Ud(e,t){let r=e.getActivity(t);return r?F(r):null}function Bd(e){return e.getAllActivities().map(F)}function Hd(e){return e.getAllIds().map(String)}function Wd(e,t){e.forEachActivity((r,i)=>t(i))}function Vd(e,t){let r=t==="0"?Sa(e,"0"):e.getChildren(t),i=[];for(let n of r){let o=e.getActivity(n);o&&i.push(F(o))}return i.sort((n,o)=>(n.correlativeId??0)-(o.correlativeId??0)),i}function Sa(e,t){return Ht(t,e)}function jd(e){return e.checkedIds().map(String)}function Kd(e,t){if(t==="0"){let r=!1;return e.forEachActivity(i=>{r||=M(i.parentId)}),r}return e.getChildren(t).length>0}function Ta(e,t){let r=e.getLink(t);return r?bt(r):null}function Yd(e){return e.getAllLinks().map(t=>bt(t))}function Tn(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function Cg(e){return e.reduce((t,r)=>Tn(r)<Tn(t)?r:t)}function Sg(e){return e.reduce((t,r)=>Tn(r)>Tn(t)?r:t)}function Tg(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function Gd(e){let t=[...e].find(o=>o.is_default);if(!t)return null;let r=Tg(t);if(r.length===0)return null;let i=r.map(o=>o.split("-")[0]),n=r.map(o=>o.split("-")[1]);return{startHour:Cg(i),endHour:Sg(n)}}function $d(e,t){return{calendars:e.calendarReader,hierarchy:bd(e),activityReader:Od(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay}}function zd(e){return He(e)}var Eg=new Set(["freeSlackHours","isCritical"]);function Dg(e,t){let r=Object.fromEntries(Object.entries(e.fields??{}).filter(([i])=>!t.has(i)));return e.kind===N.UPDATED&&Object.keys(r).length===0?null:{...e,...e.fields===void 0?{}:{fields:r},after:null}}function Zd(e){let t=e.activities.map(n=>({...n,after:null})),r=e.links.map(n=>Dg(n,Eg)).filter(n=>n!==null),i=e.source.kind===ue?{...e.source,items:[],links:[]}:e.source;return F({...e,source:i,activities:t,links:r})}function Ea(e,t,r,i,n,o,a){return{changeSet:e,beforeSnap:t,beforeLinks:qd(r),afterSnap:i,afterLinks:qd(n),progressFallbackBefore:o,progressFallbackAfter:a}}function qd(e){if(e)return new Map(Array.from(e,([t,r])=>[t,{...r,freeSlackHours:null,isCritical:!1}]))}function Qd(e,t){let r=new Map,i=new Map;for(let n of t.activities){if(n.kind!==N.CREATED)continue;let o=e.getActivity(String(n.id));o&&r.set(String(n.id),et(o))}for(let n of t.links){if(n.kind===N.DELETED)continue;let o=e.getLink(String(n.id));o&&i.set(String(n.id),{...o})}return{afterSnap:r,afterLinks:i}}function tu(e){return e.kind!==m.INLINE_EDIT||!$r.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function Jd(e){return e.changeSet.activities.length===1&&e.changeSet.activities[0]?.kind===N.UPDATED&&e.changeSet.links.length===0&&!e.beforeSnap?.size&&!e.afterSnap?.size}function eu(e,t){if(!Jd(e)||!Jd(t))return!1;let r=e.changeSet.activities[0],i=t.changeSet.activities[0];return!!r&&!!i&&String(r.id)===String(i.id)}function ru(e,t){let r=e.changeSet.activities[0],i=t.changeSet.activities[0];if(!r||!i)return t;let n=r.fields??{},o=i.fields??{},a={};for(let c of new Set([...Object.keys(n),...Object.keys(o)])){let l=n[c],d=o[c];a[c]={before:l?l.before:d?.before,after:d?d.after:l?.after}}let s={...t.changeSet,activities:[{...i,fields:a}]};return Ea(s)}var Tr={RECORD:"record",SKIP:"skip",CHECKPOINT_ON_SUCCESS:"checkpoint-on-success"},ct={BEFORE:"before",AFTER:"after"};function iu(e){return e.kind===m.PERSISTENCE_ACKNOWLEDGE?Tr.CHECKPOINT_ON_SUCCESS:e.kind===m.SIR_SYNC||e.kind===m.CALENDAR_RECONCILE||e.kind===m.ACTIVITY_LOOKAHEAD_SYNC||e.kind===m.BASELINE_APPLY||e.kind===m.PONDERATOR_CRITERION_SET||e.kind===m.STATUS_CRITERIA_SET||e.kind===m.ACTIVITY_CLIPBOARD_CLEAR||e.kind===m.ACTIVITY_COPY||e.kind===m.SELECTION_TOGGLE||e.kind===m.SELECTION_REPLACE||e.kind===m.VISIBILITY_SET||e.kind===m.FILTER_SET||e.kind===m.SORT_SET?Tr.SKIP:Tr.RECORD}function Da(e){for(let t of e.changeSet.activities)if(t.kind===N.CREATED||t.kind===N.DELETED||t.kind===N.UPDATED&&t.fields&&_.CUSTOM_ID in t.fields)return!0;return!1}function _a(e,t,r){let i=[],n=[];for(let a of t.changeSet.activities){let s=String(a.id);if(a.kind===N.UPDATED){let c=e.getActivity(s);i.push({id:s,kind:N.UPDATED,fields:Xd(a.fields,r),after:c?et(c):null})}else if(a.kind===N.DELETED)if(r===ct.BEFORE){let c=e.getActivity(s);i.push({id:s,kind:N.CREATED,after:c?et(c):null})}else i.push({id:s,kind:N.DELETED,after:null});else if(r===ct.BEFORE)i.push({id:s,kind:N.DELETED,after:null});else{let c=e.getActivity(s);i.push({id:s,kind:N.CREATED,after:c?et(c):null})}}for(let a of t.changeSet.links){let s=String(a.id);if(a.kind===N.UPDATED){let c=e.getLink(s);n.push({id:s,kind:N.UPDATED,fields:Xd(a.fields,r),after:c?bt(c):null})}else if(a.kind===N.DELETED)if(r===ct.BEFORE){let c=e.getLink(s);n.push({id:s,kind:N.CREATED,after:c?bt(c):null})}else n.push({id:s,kind:N.DELETED,after:null});else if(r===ct.BEFORE)n.push({id:s,kind:N.DELETED,after:null});else{let c=e.getLink(s);n.push({id:s,kind:N.CREATED,after:c?bt(c):null})}}let o=(t.changeSet.viewState??[]).map(a=>r===ct.BEFORE?_g(a):a);return{source:{kind:r===ct.BEFORE?oe.UNDO:oe.REDO},activities:i,links:n,calendars:[],trackingEvents:[],effects:[],viewState:o}}function Xd(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([r,i])=>[r,t===ct.BEFORE?{before:F(i.after),after:F(i.before)}:{before:F(i.before),after:F(i.after)}]))}function _g(e){return{activityId:e.activityId,...e.checked?{checked:{before:e.checked.after,after:e.checked.before}}:{},...e.visible?{visible:{before:e.visible.after,after:e.visible.before}}:{}}}function ka(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function nu(e,t){au(e,t,ct.BEFORE)}function ou(e,t){au(e,t,ct.AFTER)}function au(e,t,r){let i=t.changeSet;for(let o of i.activities)if(o.kind===N.UPDATED){if(!o.fields)continue;for(let[a,s]of Object.entries(o.fields))yt(e,o.id,a,r===ct.BEFORE?s.before:s.after)}else if(o.kind===N.DELETED)if(r===ct.BEFORE){let a=t.beforeSnap?.get(String(o.id));if(!a)throw new Error(`undo: missing beforeSnap for resurrecting activity ${o.id}`);e.addActivity(et(a))}else e.removeActivity(String(o.id));else if(r===ct.BEFORE)e.removeActivity(String(o.id));else{let a=t.afterSnap?.get(String(o.id));if(!a)throw new Error(`redo: missing afterSnap for re-creating activity ${o.id}`);e.addActivity(et(a))}for(let o of i.links)if(o.kind===N.UPDATED){if(!o.fields)continue;if(Object.hasOwn(o.fields,"source")||Object.hasOwn(o.fields,"target")){let a=r===ct.BEFORE?t.beforeLinks?.get(String(o.id)):t.afterLinks?.get(String(o.id));if(!a)throw new Error(`${r===ct.BEFORE?"undo":"redo"}: missing link snapshot for ${o.id}`);e.removeLink(String(o.id)),e.addLink({...a});continue}for(let[a,s]of Object.entries(o.fields))Ac(e,String(o.id),a,r===ct.BEFORE?s.before:s.after)}else if(o.kind===N.DELETED)if(r===ct.BEFORE){let a=t.beforeLinks?.get(String(o.id));if(!a)throw new Error(`undo: missing beforeLinks for re-adding link ${o.id}`);e.addLink(a)}else e.removeLink(String(o.id));else if(r===ct.BEFORE)e.removeLink(String(o.id));else{let a=t.afterLinks?.get(String(o.id));if(!a)throw new Error(`redo: missing afterLinks for re-creating link ${o.id}`);e.addLink(a)}for(let o of i.viewState??[])o.checked&&e.setChecked(o.activityId,r===ct.BEFORE?o.checked.before:o.checked.after),o.visible&&e.setVisible(o.activityId,r===ct.BEFORE?o.visible.before:o.visible.after);let n=r===ct.BEFORE?t.progressFallbackBefore:t.progressFallbackAfter;for(let[o,a]of n??[])e.setProgressFallback(o,a)}var kg=100,Rg=600,En=class e{constructor(t=kg){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];sequence=0;_lastKey=null;_lastTime=0;fork(){let t=new e(this.maxDepth);return t.undoStack.push(...F(this.undoStack)),t.redoStack.push(...F(this.redoStack)),t.sequence=this.sequence,t._lastKey=this._lastKey,t._lastTime=this._lastTime,t}record(t,r=null,i=0){let n=this.undoStack[this.undoStack.length-1];r!=null&&r===this._lastKey&&i-this._lastTime<=Rg&&n!==void 0&&eu(n.entry,t)?(n.entry=ru(n.entry,t),n.touchedAt=this.touch()):(this.undoStack.push({entry:t,touchedAt:this.touch()}),this.undoStack.length>this.maxDepth&&this.undoStack.splice(0,this.undoStack.length-this.maxDepth)),this._lastKey=r,this._lastTime=i,this.redoStack.length=0}resetCoalesce(){this._lastKey=null}takeUndo(){return this.undoStack.pop()?.entry??null}takeRedo(){return this.redoStack.pop()?.entry??null}pushRedo(t){this.redoStack.push({entry:t,touchedAt:this.touch()})}pushUndo(t){this.undoStack.push({entry:t,touchedAt:this.touch()})}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undoDepth(){return this.undoStack.length}capturePersistenceBoundary(){return this.resetCoalesce(),this.sequence}discardThrough(t){this.removeEntriesThrough(this.undoStack,t),this.removeEntriesThrough(this.redoStack,t),this.resetCoalesce()}applyPersistedIdentities(t,r){let i=new Map(t.map(({id:o,proplannerId:a})=>[String(o),a])),n=new Map(r.map(({id:o,proplannerId:a})=>[String(o),a]));for(let o of[...this.undoStack,...this.redoStack])o.entry=this.withPersistedIdentities(o.entry,i,n)}clear(){this.undoStack.length=0,this.redoStack.length=0,this.resetCoalesce()}touch(){return this.sequence+=1,this.sequence}removeEntriesThrough(t,r){let i=t.filter(({touchedAt:n})=>n>r);t.splice(0,t.length,...i)}withPersistedIdentities(t,r,i){let n=a=>a===void 0?void 0:new Map(Array.from(a,([s,c])=>[s,r.has(s)?{...c,proplannerId:r.get(s)}:c])),o=a=>a===void 0?void 0:new Map(Array.from(a,([s,c])=>[s,i.has(s)?{...c,proplannerId:i.get(s)}:c]));return{...t,beforeSnap:n(t.beforeSnap),afterSnap:n(t.afterSnap),beforeLinks:o(t.beforeLinks),afterLinks:o(t.afterLinks)}}};var Pg=["parentId","correlativeId"];function cu(e,t){let r=new Set,i=n=>{let o=t(n);r.add(o===null?"0":String(o))};for(let n of e.activities){let o=String(n.id);if(n.kind===N.CREATED){i(o);continue}if(n.kind===N.DELETED){let c=n.fields;c&&"parentId"in c&&r.add(su(c.parentId?.before));continue}let a=n.fields;!a||!Pg.some(c=>c in a)||(i(o),"parentId"in a&&r.add(su(a.parentId?.before)))}return r}function su(e){return e==null?"0":String(e)}function Lg(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function Og(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function lu(e){return{id:String(e.id),worktime:Og(e.worktime)}}function Dn(e,t,r,i=[]){let n=t.map(Lg),o=[...r.map(lu),...i.map(lu)];return{activities:[...e],links:n,calendars:o}}var w={TRACKED:"tracked",IGNORED:"ignored"};var du={id:w.IGNORED,proplannerId:w.IGNORED,parentId:w.TRACKED,name:w.TRACKED,description:w.TRACKED,type:w.TRACKED,startDate:w.TRACKED,endDate:w.TRACKED,durationHours:w.TRACKED,constraintType:w.TRACKED,constraintDate:w.TRACKED,autoScheduling:w.TRACKED,calendarId:w.TRACKED,assignedDefaultCalendar:w.IGNORED,dateOrigin:w.TRACKED,progress:w.TRACKED,cost:w.TRACKED,usedCost:w.TRACKED,realCost:w.TRACKED,workHours:w.TRACKED,realWorkHours:w.TRACKED,ponderator:w.TRACKED,hasCustomPonderator:w.TRACKED,correlativeId:w.TRACKED,uniqueCorrelativeId:w.TRACKED,customId:w.TRACKED,subcontractId:w.TRACKED,isLookahead:w.TRACKED,hasLookaheadTasks:w.IGNORED,newActivityIds:w.TRACKED,hasNewActivities:w.TRACKED,isNewActivity:w.IGNORED,pendingRequestIds:w.IGNORED,responsableIds:w.TRACKED,tagIds:w.TRACKED,baselinePoints:w.IGNORED,baselineSnapshot:w.IGNORED,recursiveDurationHours:w.IGNORED,isCritical:w.IGNORED,freeSlackHours:w.IGNORED,calendarDuration:w.IGNORED,expectedProgress:w.IGNORED,expectedProgressBaseline:w.IGNORED,status:w.IGNORED,criticalPath:w.IGNORED},uu=Object.keys(du).filter(e=>du[e]===w.TRACKED),fu=new Set(["startDate","endDate","constraintDate","dateOrigin"]),pu=new Set(["newActivityIds","responsableIds","tagIds"]);function yu(e){let t=uu.map(r=>[r,Ng(r,e[r])]);return Object.fromEntries(t)}function Ng(e,t){return fu.has(e)?t instanceof Date?new Date(t):null:pu.has(e)?Array.isArray(t)?[...t]:[]:t}function Qr(e,t){return Ra(e,t).length>0}function Ra(e,t){return uu.filter(r=>!bg(r,e[r],t[r]))}function bg(e,t,r){return fu.has(e)?Fg(t,r):pu.has(e)?wg(t,r):(t??null)===(r??null)}function Fg(e,t){let r=e instanceof Date?e.getTime():null,i=t instanceof Date?t.getTime():null;return r===i}function wg(e,t){let r=new Set(Array.isArray(e)?e.map(String):[]),i=new Set(Array.isArray(t)?t.map(String):[]);if(r.size!==i.size)return!1;for(let n of r)if(!i.has(n))return!1;return!0}var hu={id:w.IGNORED,source:w.TRACKED,target:w.TRACKED,type:w.TRACKED,lag:w.TRACKED,freeSlackHours:w.IGNORED,isCritical:w.IGNORED,ganttId:w.IGNORED,sectorId:w.IGNORED,proplannerId:w.IGNORED},xg=Object.keys(hu).filter(e=>hu[e]===w.TRACKED);function _n(e,t){return xg.some(r=>e[r]!==t[r])}function mu(e,t){let r=new Map(e.map(i=>[String(i.id),i]));return t.filter(i=>{let n=r.get(String(i.id));return n?_n(n,i):!1})}function Xt(e){if(e==null||e===0)return!1;if(!(typeof e=="number"&&Number.isSafeInteger(e)&&e>0))throw new Error(`invalid proplannerId ${String(e)}`);return!0}function Iu(e,t){for(let r of e)Xt(r.proplannerId);for(let r of t)Xt(r.proplannerId)}var kn=class e{trackingEnabled;initialized=!1;dirtyActivityIds=new Set;dirtyLinkIds=new Set;initialCalendarRepairIds=new Set;linksAtLastSave=new Map;activitiesAtLastSave=new Map;constructor(t=!0){this.trackingEnabled=t}fork(){let t=new e(!1);t.initialized=this.initialized;for(let[r,i]of this.linksAtLastSave)t.linksAtLastSave.set(r,F(i));for(let[r,i]of this.activitiesAtLastSave)t.activitiesAtLastSave.set(r,F(i));return t}init(t,r){if(this.trackingEnabled){Iu(t,r),this.snapshotActivities(t),this.snapshotLinks(r);for(let i of t)if(i.assignedDefaultCalendar){let n=String(i.id);this.initialCalendarRepairIds.add(n),this.dirtyActivityIds.add(n)}this.initialized=!0}}acknowledge(t,r,i=[],n=[],o,a){if(!this.trackingEnabled)return;let s=new Map(i.map(({id:p,proplannerId:y})=>[String(p),y])),c=new Map(n.map(({id:p,proplannerId:y})=>[String(p),y])),l=t.map(p=>({...p,proplannerId:s.get(String(p.id))??p.proplannerId})),d=r.map(p=>{let y=c.get(String(p.id));return y===void 0?{...p}:{...p,proplannerId:y}});if(Iu(l,d),this.snapshotActivities(l),this.snapshotLinks(d),!o||!a)return;let u=new Map(o.map(p=>[String(p.id),p])),f=new Map(a.map(p=>[String(p.id),p]));for(let p of l){let y=String(p.id);this.activityIsDirty(y,u.get(y)??null)&&this.dirtyActivityIds.add(y)}for(let p of o){let y=String(p.id);this.activityIsDirty(y,p)&&this.dirtyActivityIds.add(y)}for(let p of d){let y=String(p.id);this.linkIsDirty(y,f.get(y)??null)&&this.dirtyLinkIds.add(y)}for(let p of a){let y=String(p.id);this.linkIsDirty(y,p)&&this.dirtyLinkIds.add(y)}}snapshotActivities(t){if(this.trackingEnabled){this.activitiesAtLastSave.clear(),this.dirtyActivityIds.clear(),this.initialCalendarRepairIds.clear();for(let r of t){let i=String(r.id);if(!Xt(r.proplannerId)){this.dirtyActivityIds.add(i);continue}let n=yu(r);this.activitiesAtLastSave.set(String(r.id),{persistable:n,deletedSnapshot:{id:r.id,proplannerId:r.proplannerId,parentId:r.parentId,hadBaseline:r.baselineSnapshot!==null||r.baselinePoints.length>0}}),Qr(r,n)&&this.dirtyActivityIds.add(i)}}}snapshotLinks(t){if(this.trackingEnabled){this.linksAtLastSave.clear(),this.dirtyLinkIds.clear();for(let r of t){let i=String(r.id);if(!Xt(r.proplannerId)){this.dirtyLinkIds.add(i);continue}this.linksAtLastSave.set(String(r.id),{id:r.id,proplannerId:r.proplannerId,source:r.source,target:r.target,lag:r.lag,type:r.type})}}}recordChanges(t,r,i,n){if(!(!this.trackingEnabled||!this.initialized)){for(let o of t){let a=String(o.id),s=i(a);this.activityIsDirty(a,s)?this.dirtyActivityIds.add(a):this.dirtyActivityIds.delete(a)}for(let o of r){let a=String(o.id),s=n(a);this.linkIsDirty(a,s)?this.dirtyLinkIds.add(a):this.dirtyLinkIds.delete(a)}}}activityIsDirty(t,r){let i=this.activitiesAtLastSave.get(t);return r===null?i!==void 0:this.initialCalendarRepairIds.has(t)||!Xt(r.proplannerId)||i===void 0||Qr(r,i.persistable)}linkIsDirty(t,r){let i=this.linksAtLastSave.get(t);return r===null?i!==void 0:!Xt(r.proplannerId)||i===void 0||_n(i,r)}acknowledgePersistedLookahead(t,r){if(!this.trackingEnabled||!this.initialized)return;let i=t.map(n=>{let o=typeof n=="string"?n:String(n.id),a=r(o),s=this.activitiesAtLastSave.get(o);if(a===null||s===void 0)throw new Error(`unknown persisted activity "${o}"`);return{activityId:o,acknowledgesLookahead:typeof n=="string"||!!n.fields?.isLookahead,acknowledgesProgress:typeof n!="string"&&!!n.fields?.progress,current:a,saved:s}});for(let{activityId:n,acknowledgesLookahead:o,acknowledgesProgress:a,current:s,saved:c}of i){let l={...c.persistable,...o?{isLookahead:s.isLookahead}:{},...a?{progress:s.progress,autoScheduling:s.autoScheduling}:{}};this.activitiesAtLastSave.set(n,{...c,persistable:l}),this.initialCalendarRepairIds.has(n)||!Xt(s.proplannerId)||Qr(s,l)?this.dirtyActivityIds.add(n):this.dirtyActivityIds.delete(n)}}hasCheckpointActivityId(t){return this.activitiesAtLastSave.has(t)}hasCheckpointLinkId(t){return this.linksAtLastSave.has(t)}hasUnsavedChanges(){return this.trackingEnabled&&this.initialized&&(this.dirtyActivityIds.size>0||this.dirtyLinkIds.size>0)}newActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let i of this.dirtyActivityIds){let n=t(i);n!==null&&!Xt(n.proplannerId)&&r.push(n)}return r}newLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let i of this.dirtyLinkIds){let n=t(i);n!==null&&!Xt(n.proplannerId)&&r.push(n)}return r}deletedActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let i of this.dirtyActivityIds){let n=this.activitiesAtLastSave.get(i);n&&t(i)===null&&r.push({...n.deletedSnapshot})}return r}deletedLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let i of this.dirtyLinkIds){let n=this.linksAtLastSave.get(i);n&&t(i)===null&&r.push({...n})}return r}modifiedActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let i of this.dirtyActivityIds){let n=t(i);if(n===null||!Xt(n.proplannerId))continue;let o=this.activitiesAtLastSave.get(i);(o===void 0||this.initialCalendarRepairIds.has(i)||Qr(n,o.persistable))&&r.push(n)}return r}modifiedActivityFields(t){let r=new Map;if(!this.trackingEnabled||!this.initialized)return r;for(let i of this.dirtyActivityIds){let n=t(i),o=this.activitiesAtLastSave.get(i);if(!n||!o)continue;let a=Ra(n,o.persistable);a.length>0&&r.set(i,a)}return r}modifiedLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let i of this.dirtyLinkIds){let n=t(i);if(n===null||!Xt(n.proplannerId))continue;let o=this.linksAtLastSave.get(i);(o===void 0||_n(o,n))&&r.push(n)}return r}clear(){this.initialized=!1,this.dirtyActivityIds.clear(),this.dirtyLinkIds.clear(),this.initialCalendarRepairIds.clear(),this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear()}};var gu=1440*60*1e3,Au=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/,Rn=7,Pa=[!1,!0,!0,!0,!0,!0,!1],vu=new Set(["1","true"]),La=gt.DURATION,Cu=A.ASAP,Su={ASAP:A.ASAP,ALAP:A.ALAP,SNET:A.SNET,SNLT:A.SNLT,FNET:A.FNET,FNLT:A.FNLT,MSO:A.MSO,MFO:A.MFO,"AS SOON AS POSSIBLE":A.ASAP,"AS LATE AS POSSIBLE":A.ALAP,"START NO EARLIER THAN":A.SNET,"START NO LATER THAN":A.SNLT,"FINISH NO EARLIER THAN":A.FNET,"FINISH NO LATER THAN":A.FNLT,"MUST START ON":A.MSO,"MUST FINISH ON":A.MFO};function Tu(e,t){let r=[],i=e.map(o=>{let a=Gg(o,t);return o.should_be_showed===!1&&r.push(a.id),a});zg(i);let n=new Set(i.map(o=>o.id));return qg(i,n,t.reporter,t.recordDiagnostic),{activities:i,activityIds:n,hiddenIds:r}}function Mg(e,t,r,i){if(!e)return null;let n=Su[e.toUpperCase()];return n===void 0?(r(Pt.UNKNOWN_CONSTRAINT,i),t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),Cu):n}function Ug(e,t,r){let i=Mg(e.constraint,t,r,String(e.unique_id)),o=i!==A.ASAP&&i!==A.ALAP&&e.constraint_date?se(e.constraint_date):null;return{constraintType:i,constraintDate:o}}function Bg(e,t,r){if(e==null)return r;let i=String(e);return t.has(i)?i:r}function Hg(e){if(e==null||e==="")return[];if(Array.isArray(e))return e.map(String);if(typeof e!="string")return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.map(String):[]}catch{return[]}}function Wg(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function Oa(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)Wg(r)&&t.push(String(r.id));return t}function Vg(e){return e==="0"?null:String(e)}function jg(e){if(e==null)return null;if(!(typeof e=="number"&&(e===0||Number.isSafeInteger(e)&&e>0)))throw new Error(`invalid activity proplannerId ${String(e)}`);return e}function Kg(e,t){return typeof e.is_critical=="boolean"?e.is_critical:(t.error("[parseFromBackend] invalid activity is_critical \u2014 defaulting to false",new TypeError(`activity "${e.unique_id}" received ${typeof e.is_critical}`)),!1)}function Yg(e,t,r,i){return Array.isArray(e)?e.map(n=>hn(n,t,{record:r,sampleId:i})).filter(n=>n!==null):[]}function Gg(e,t){let r=Bg(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),i=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),n=Number(e.progress),{constraintType:o,constraintDate:a}=Ug(e,t.reporter,t.recordDiagnostic),s=e.type===D.MILESTONE,c=se(e.start_date),l=s?c:se(e.end_date),d=s?0:Number(e.duration),u=Kg(e,t.reporter);return{id:String(e.unique_id),proplannerId:jg(e.id),parentId:Vg(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:Ne(d,t.hoursPerDay),constraintType:o,constraintDate:a,autoScheduling:Pe(n),calendarId:r,assignedDefaultCalendar:r!=null&&i,dateOrigin:e.date_origin==null?null:se(e.date_origin),progress:n,cost:Number(e.cost),usedCost:Number(e.used_cost??0),realCost:Number(e.real_cost??0),workHours:Number(e.hhWorkTime),realWorkHours:Number(e.real_work??0),ponderator:Number(e.ponderator??0),hasCustomPonderator:e.hasCustomPonderator,correlativeId:e.correlative_id,uniqueCorrelativeId:e.unique_correlative_id,customId:$g(e),subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:Hg(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:Oa(e.pendingRequests),responsableIds:Oa(e.responsables),tagIds:Oa(e.tags),baselinePoints:Yg(e.baseline_points,t.reporter,t.recordDiagnostic,String(e.unique_id)),baselineSnapshot:null,recursiveDurationHours:Ne(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),calendarDuration:Qt({type:e.type,startDate:c,endDate:l}),isCritical:u,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function $g(e){return e.has_childs?null:e.custom_id}function zg(e){let t=e.find(r=>r.correlativeId===0&&r.type===D.PROJECT);t&&(t.parentId=null)}function qg(e,t,r,i){for(let n of e)n.parentId!==null&&(t.has(n.parentId)||(r.warn(`[parseFromBackend] activity "${n.id}" references unknown parent "${n.parentId}" \u2014 re-parenting to root (null)`),i(Pt.ORPHAN_ACTIVITY,n.id),n.parentId=null))}function ku(e,t,r,i=null){let a=(e!==void 0&&e.length>0?e:t??[]).map(c=>Xg(c,i)),s=(r??[]).map(c=>Zg(c,i));return{calendars:a,baseCalendars:s,knownCalendarIds:new Set(a.map(c=>c.id)),defaultCalendarId:Jg(a)}}function Jg(e){let t=e.find(i=>i.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function Ru(e,t){let r=nA(e.working_days),{days:i,hours:n}=iA(e,r),o=Qg(t.exceptionsSource,t.exceptionRange),a={days:i,hours:n};return o&&(a.dates=o),{id:`${String(e.id)}${t.idSuffix}`,name:e.name,is_default:t.isDefault,...t.baseDefault!==void 0?{baseDefault:t.baseDefault}:{},worktime:a}}function Xg(e,t){let r=e.baseDefault,i=typeof r=="boolean"?r:void 0;return Ru(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:i,exceptionsSource:e.exceptiondays,exceptionRange:t})}function Zg(e,t){return Ru(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function Qg(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let i of e){if(!i)continue;let n=tA(i.from_date,i.to_date,t);if(n.length===0)continue;let o=eA(i);if(o!==void 0)for(let a of n)r[a]=o}return Object.keys(r).length>0?r:null}function tA(e,t,r){let i=Eu(e),n=Eu(t);if(i===null||n===null)return[];if(r&&(n<r.start||i>r.end))return[];let o=[],a=r?Math.max(i,r.start):i,s=r?Math.min(n,r.end):n;for(;a<=s;)o.push(String(a)),a+=gu;return o}function Eu(e){if(typeof e!="string")return null;let t=Au.exec(e.trim());if(!t)return null;let r=Number(t[1]),i=Number(t[2]),n=Number(t[3]);return Number.isFinite(r)&&Number.isFinite(i)&&Number.isFinite(n)?Date.UTC(r,i-1,n):null}function eA(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=rA(t);if(r.length>0)return r}}var Du=/^\d{1,2}:\d{2}$/;function rA(e){let t=[];for(let r of e){let i=Ou(r?.shift_string);if(!i)continue;if(!i.startsCsv.includes(",")&&!i.endsCsv.includes(",")){let s=i.startsCsv.trim(),c=i.endsCsv.trim();!Pn(s)&&!Pn(c)&&Du.test(s)&&Du.test(c)&&t.push(`${s}-${c}`);continue}let a=Lu(i.startsCsv,i.endsCsv).find(s=>s!==null);a&&t.push(a)}return t.sort(Pu),t}function _u(e){let t=e.indexOf("-"),r=t>0?e.slice(0,t):e,[i,n]=r.split(":");return(Number(i)||0)*60+(Number(n)||0)}function Pu(e,t){return _u(e)-_u(t)}function iA(e,t){let r=Array.from({length:7},()=>[]),i=(l,d)=>{let u=Lu(l,d);for(let f=0;f<7;f+=1){let p=u[f],y=r[f];p&&y&&y.push(p)}},n=Array.isArray(e.shifts)&&e.shifts.length>0,o=typeof e.shift_start=="string"&&typeof e.shift_end=="string";if(n)for(let l of e.shifts){let d=Ou(l?.shift_string);d&&i(d.startsCsv,d.endsCsv)}else o&&i(e.shift_start,e.shift_end);for(let l of r)l.sort(Pu);let s=r.find((l,d)=>!!t[d]&&l.length>0)??[];return{days:t.map((l,d)=>{if(!l)return!1;let u=r[d];return u&&u.length>0?u:s}),hours:s}}function Lu(e,t){let r=Array.from({length:Rn},()=>null);if(typeof e!="string"||typeof t!="string")return r;let i=e.split(",").map(s=>s.trim()),n=t.split(",").map(s=>s.trim());if(!(i.length===n.length&&i.length>0&&i.length<=Rn))return r;let a=[...r];for(let s=0;s<i.length;s+=1){let c=i[s],l=n[s];Pn(c)||Pn(l)||(a[s]=`${c}-${l}`)}return a}function Ou(e){if(typeof e!="string")return null;let t=e.indexOf("-");return t<=0?null:{startsCsv:e.slice(0,t),endsCsv:e.slice(t+1)}}function nA(e){if(typeof e!="string")return[...Pa];let t=e.split(",").map(r=>r.trim());return t.length!==Rn?[...Pa]:t.map(r=>vu.has(r))}var oA=new Set(["false","null"]);function Pn(e){return!e||oA.has(e)}function aA(e){if(typeof e!="string")return null;let t=bs(e);return t||(ni(e)?e:null)}function sA(e){if(e==null)return;if(!(typeof e=="number"&&(e===0||Number.isSafeInteger(e)&&e>0)))throw new Error(`invalid link proplannerId ${String(e)}`);return e}function bu(e,t){let r=[];for(let i of e)try{r.push(cA(i,t.knownActivityIds,t.hoursPerDay))}catch(n){t.recordDiagnostic(Pt.INVALID_LINK,String(i.unique_id??i.id)),t.reporter.warn("[parseFromBackend] dropping invalid link",n)}return lA(r,t.recordDiagnostic)}function cA(e,t,r){let i=String(e.unique_id??e.id),n=String(e.source_id??e.source??""),o=String(e.target_id??e.target??"");if(!t.has(n))throw new Error(`[parseFromBackend] link "${i}" source "${n}" does not exist`);if(!t.has(o))throw new Error(`[parseFromBackend] link "${i}" target "${o}" does not exist`);let a=aA(e.type);if(a===null)throw new Error(`[parseFromBackend] link "${i}" has invalid type "${String(e.type)}"`);let s=e.ganttId,c=e.sectorId,l=sA(e.id);return{id:i,source:n,target:o,type:a,lag:Wt(Number(e.lag??0),r),freeSlackHours:null,isCritical:!1,...typeof s=="number"?{ganttId:s}:{},...typeof c=="number"?{sectorId:c}:{},...l===void 0?{}:{proplannerId:l}}}function lA(e,t){let r=new Map;for(let i of e){let n=`${i.source}-${i.target}-${i.type}`,o=r.get(n);if(!o){r.set(n,i);continue}let a=Nu(i)>Nu(o),s=a?o:i;t(Pt.DUPLICATE_LINK,s.id),a&&r.set(n,i)}return[...r.values()]}function Nu(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function dA(e){if(typeof e!="string")return La;switch(e.toUpperCase()){case gt.DURATION:return gt.DURATION;case gt.COST:return gt.COST;case gt.WORK_HOURS:return gt.WORK_HOURS;default:return La}}function uA(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function fA(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function Fu(e){let t=uA(e),r=fA(e),i=e.update_duration_for_primavera_for_end_date===!0;return{id:String(e.id),name:e.name,hoursPerDay:e.hoursPerDay,hoursPerWeek:e.hoursPerWeek,dateFormat:e.dateFormat,projectId:e.projectId,companyId:e.companyId,...t!==void 0?{customIdPrefix:t}:{},...r!==void 0?{customIdIncrement:r}:{},...i?{updateDurationForPrimaveraEndDate:!0}:{},activityCreter:dA(e.activity_creter),statusCriteria:go,ganttId:null}}function Ln(e,t=tr,r=vr){let i=Fu(e.sector),{calendars:n,baseCalendars:o,knownCalendarIds:a,defaultCalendarId:s}=ku(e.calendars,e.sector.calendars,e.baseCalendars,pA(e.activities)),{activities:c,activityIds:l,hiddenIds:d}=Tu(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:i.hoursPerDay,reporter:t,recordDiagnostic:r}),u=bu(e.links,{knownActivityIds:l,hoursPerDay:i.hoursPerDay,reporter:t,recordDiagnostic:r});return{sector:i,activities:c,links:u,calendars:n,baseCalendars:o,viewStateSeed:{hiddenIds:d}}}function pA(e){let t=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let o of e){let a=new Date(o.start_date).getTime(),s=new Date(o.end_date).getTime();Number.isFinite(a)&&(t=Math.min(t,a)),Number.isFinite(s)&&(r=Math.max(r,s))}if(!Number.isFinite(t)||!Number.isFinite(r))return null;let i=new Date(t),n=new Date(r);return i.setFullYear(i.getFullYear()-1),n.setFullYear(n.getFullYear()+1),{start:i.getTime(),end:n.getTime()}}function Na(e={}){let t=e.seed??0,r=i=>{i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}return{fork(){return Na({seed:t})},next(){return t+=1,String(t)},bump(i){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)},snapshot(){return t},restore(i){t=i}}}function ba(e={}){let t=e.seed??0,r=i=>{i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}return{fork(){return ba({seed:t})},next(){return t+=1,String(t)},bump(i){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)},snapshot(){return t},restore(i){t=i}}}function Fa(e={}){let t=e.seed??0,r=i=>{Number.isFinite(i)&&i>0&&i<=9999999&&i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){if(i==null)continue;let n=typeof i=="number"?i:Number(i);r(n)}return{fork(){return Fa({seed:t})},next(){return t+=1,String(t)},bump(i){if(i==null)return;let n=typeof i=="number"?i:Number(i);r(n)},snapshot(){return t},restore(i){t=i}}}function wu(e){return!!e&&typeof e=="string"&&e.trim().length>0}function On(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function Nn(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function xu(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function Mu(e,t){return!t&&wu(e)}function Uu(e,t){return t&&wu(e)}function ti(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function bn(e){if(!ti(e))return 0n;try{return BigInt(e)}catch{return 0n}}function yA(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!ti(t))return r;let i=t.length;return r.padStart(i,"0")}function Kt(e,t){let r=bn(e),i=bn(t),n=r+i;return yA(n,e)}function Fn(e,t){let r=bn(e),i=bn(t);return r<i?-1:r>i?1:0}function wn(e,t){return Fn(e,t)<=0?e:t}function xn(e,t){return Fn(e,t)>=0?e:t}function Bu(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>wn(t,r))}function Hu(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>xn(t,r))}var le={PARENT_CONVERSION:"parentConversion",PASTE_REFERENCE:"pasteReference",NO_CONTEXT:"noContext"};function Wu(e){return{prefix:e,baseSuffix:null}}function Vu(e,t){let r=Nn(e);return{prefix:On(e),baseSuffix:Kt(r,t)}}function ju(e){return{prefix:e,baseSuffix:null}}function Ku(e,t){return Mu(e,t)?le.PARENT_CONVERSION:Uu(e,t)?le.PASTE_REFERENCE:le.NO_CONTEXT}function Yu(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var Mn=class e{prefixMap=new Map;processedIds=new Set;_journalPrefixBefore=null;_journalIds=null;beginCustomIdTransaction(){this._journalPrefixBefore=new Map,this._journalIds=[]}commitCustomIdTransaction(){this._journalPrefixBefore=null,this._journalIds=null}rollbackCustomIdTransaction(){let t=this._journalPrefixBefore,r=this._journalIds;if(!(t===null||r===null)){for(let[i,n]of t)n===null?this.prefixMap.delete(i):this.prefixMap.set(i,n);for(let i of[...r].reverse())i.hadId?this.processedIds.add(i.customId):this.processedIds.delete(i.customId);this._journalPrefixBefore=null,this._journalIds=null}}_noteCustomIdBefore(t){if(this._journalPrefixBefore===null||this._journalIds===null)return;let{prefix:r}=this.analyzeCustomId(t);if(!this._journalPrefixBefore.has(r)){let i=this.prefixMap.get(r);this._journalPrefixBefore.set(r,i?Yu(i):null)}this._journalIds.push({customId:t,hadId:this.processedIds.has(t)})}_ensureFreshBounds(t){let r=this.prefixMap.get(t);if(!r?.boundsDirty)return;r.boundsDirty=!1;let i=Array.from(r.usedSuffixes);r.min=Bu(i),r.max=Hu(i),r.quantity=i.length,this._recalculateNext(t)}defaultPrefix;suffixIncrement;constructor(t={}){this.defaultPrefix=t.defaultPrefix??"A",this.suffixIncrement=t.suffixIncrement??"10"}fork(){let t=new e({defaultPrefix:this.defaultPrefix,suffixIncrement:this.suffixIncrement});for(let[r,i]of this.prefixMap)t.prefixMap.set(r,Yu(i));for(let r of this.processedIds)t.processedIds.add(r);return t}extractPrefix(t){return On(t)}extractSuffix(t){return Nn(t)}analyzeCustomId(t){return{prefix:this.extractPrefix(t),suffix:this.extractSuffix(t)}}_updatePrefixStats(t,r){if(this._ensureFreshBounds(t),!this.prefixMap.has(t)){this.prefixMap.set(t,{min:r,max:r,next:r,quantity:1,usedSuffixes:new Set([r])}),this._recalculateNext(t);return}let i=this.prefixMap.get(t);i.usedSuffixes.has(r)||(i.usedSuffixes.add(r),i.min=wn(r,i.min),i.max=xn(r,i.max),i.quantity+=1,this._recalculateNext(t))}_recalculateNext(t){let r=this.prefixMap.get(t);if(!r)return;let i=this.getNextAvailableSuffix(t);r.next=i??this.suffixIncrement}getPrefixStats(t){this._ensureFreshBounds(t);let r=this.prefixMap.get(t);return r?{min:r.min,max:r.max,next:r.next,quantity:r.quantity}:null}getNextSuffix(t){this._ensureFreshBounds(t);let r=this.prefixMap.get(t);return r?r.next:this.suffixIncrement}getAllPrefixes(){return Array.from(this.prefixMap.keys())}registerCustomId(t){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:i}=this.analyzeCustomId(t);if(!r&&!i)return{prefix:r,suffix:i};if(this._noteCustomIdBefore(t),this._ensureFreshBounds(r),this.prefixMap.has(r)){let n=this.prefixMap.get(r);n.usedSuffixes.has(i)||(n.usedSuffixes.add(i),n.min=wn(i,n.min),n.max=xn(i,n.max),n.quantity+=1,this._recalculateNext(r))}else this.prefixMap.set(r,{min:i,max:i,next:Kt(i,this.suffixIncrement),quantity:1,usedSuffixes:new Set([i])});return this.processedIds.add(t),{prefix:r,suffix:i}}releaseCustomId(t=null){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:i}=this.analyzeCustomId(t);if(!this.prefixMap.has(r))return{prefix:r,suffix:i};this._noteCustomIdBefore(t);let n=this.prefixMap.get(r);return n.usedSuffixes.has(i)&&(n.usedSuffixes.delete(i),n.quantity-=1,n.usedSuffixes.size===0?this.prefixMap.delete(r):n.boundsDirty=!0),this.processedIds.delete(t),{prefix:r,suffix:i}}trackCustomIdChange(t,r){let i=this.releaseCustomId(t),n=this.registerCustomId(r);return{oldPrefix:i.prefix,oldSuffix:i.suffix,newPrefix:n.prefix,newSuffix:n.suffix}}_exceedsMaxLength(t){return t.length>20}_shouldSearchForGaps(t){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return!1;let r=this.prefixMap.get(t);return`${t}${Kt(r.max,this.suffixIncrement)}`.length>20}_suffixForUnknownPrefix(t,r){let i=r&&ti(r)?r:this.suffixIncrement;return`${t}${i}`.length>20?null:i}_findFirstAvailableGap(t){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return null;let r=this.prefixMap.get(t),i=this.suffixIncrement;for(;Fn(i,r.max)<0;){if(`${t}${i}`.length>20)return null;if(!r.usedSuffixes.has(i))return i;i=Kt(i,this.suffixIncrement)}return null}_generateDefaultCustomId(){let t=this.getNextAvailableSuffix(this.defaultPrefix);if(t===null){if(this._shouldSearchForGaps(this.defaultPrefix)){let r=this._findFirstAvailableGap(this.defaultPrefix);if(r!==null)return`${this.defaultPrefix}${r}`}return`${this.defaultPrefix}${this.suffixIncrement}`}return`${this.defaultPrefix}${t}`}getNextAvailableSuffix(t,r=null){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return this._suffixForUnknownPrefix(t,r);let i=this.prefixMap.get(t),n=this.suffixIncrement;if(!r||!ti(r)){let s=Kt(i.max,n);return`${t}${s}`.length>20?null:s}let o=r;for(let s=0;s<100;s++){if(`${t}${o}`.length>20)return null;if(!i.usedSuffixes.has(o))return o;o=Kt(o,n)}let a=Kt(i.max,n);return`${t}${a}`.length>20?null:a}generateNextCustomId(t){let r=this.getNextAvailableSuffix(t);if(r===null)return this._generateDefaultCustomId();if(this.prefixMap.has(t)){let n=this.prefixMap.get(t),o=0;for(;n.usedSuffixes.has(r)&&o<1e4;){let a=this.getNextAvailableSuffix(t,Kt(r,this.suffixIncrement));if(a===null)return this._generateDefaultCustomId();r=a,o++}}let i=`${t}${r}`;return this._exceedsMaxLength(i)&&(i=this._generateDefaultCustomId()),i}populateFromActivities(t){if(!Array.isArray(t))return this;let r=[...new Set(t.filter(i=>i&&typeof i.customId=="string"&&i.customId).map(i=>i.customId))];for(let i of r){if(this.processedIds.has(i))continue;let{prefix:n,suffix:o}=this.analyzeCustomId(i);(n||o)&&(this._updatePrefixStats(n,o),this.processedIds.add(i))}return this}getDefaults(){return{prefix:this.defaultPrefix,increment:this.suffixIncrement}}generateCustomIdForNewChild(t){let{activity:r,useActivityCustomIdAsReference:i=!1}=t,n=xu(r),o=Ku(n,i),{prefix:a,baseSuffix:s}=this._applyGenerationStrategy(o,n),c=null;if(o===le.PARENT_CONVERSION&&this.prefixMap.has(a)){this._ensureFreshBounds(a);let f=this.prefixMap.get(a).max;c=Kt(f,this.suffixIncrement)}o===le.PARENT_CONVERSION&&this.releaseCustomId(n);let l=o===le.PARENT_CONVERSION&&c?c:s,d=this.getNextAvailableSuffix(a,l);if(d===null){let f=this._generateDefaultCustomId();return this.registerCustomId(f),f}let u=`${a}${d}`;return this._exceedsMaxLength(u)&&(u=this._generateDefaultCustomId()),this.registerCustomId(u),u}_applyGenerationStrategy(t,r){switch(t){case le.PARENT_CONVERSION:return Wu(this.defaultPrefix);case le.PASTE_REFERENCE:return Vu(r,this.suffixIncrement);default:return ju(this.defaultPrefix)}}generateCustomIdForRestoredChild(t=null){if(t){let i=t.trim();if(i.length>0){let n=this.extractPrefix(i),o=this.extractSuffix(i),a=Kt(o,this.suffixIncrement),s=this.getNextAvailableSuffix(n,a);if(s===null){let l=this._generateDefaultCustomId();return this.registerCustomId(l),l}let c=`${n}${s}`;return this._exceedsMaxLength(c)&&(c=this._generateDefaultCustomId()),this.registerCustomId(c),c}}let r=this.generateNextCustomId(this.defaultPrefix);return this.registerCustomId(r),r}clear(){this.prefixMap.clear(),this.processedIds.clear()}getTotalPrefixes(){return this.prefixMap.size}hasPrefix(t){return this.prefixMap.has(t)}isCustomIdInUse(t,r=null){if(!t||typeof t!="string"||!t.trim())return!1;let i=t.trim();return r&&i===r.trim()?!1:this.processedIds.has(i)}};var hA=1,mA=-1;function IA(e,t){return!e&&!t?null:e&&t?0:e?hA:mA}function Gu(e){return e==null}function $u(e,t){let r=t.indexOf(String(e));return r===-1?t.length:r}function gA(e,t,r){return e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="number"&&typeof t=="number"?e-t:typeof e=="boolean"&&typeof t=="boolean"?Number(e)-Number(t):Array.isArray(e)&&Array.isArray(t)?e.length-t.length:String(e).localeCompare(String(t),r,{sensitivity:"base",numeric:!0})}function AA(e,t){let r=fe(e.field);return r===null?null:(i,n)=>{let o=r.extract(i,t),a=r.extract(n,t),s=IA(Gu(o),Gu(a));if(s!==null)return s;let c=r.valueKind===O.ENUM?$u(o,r.order)-$u(a,r.order):gA(o,a,t.locale);return e.direction===Re.DESCENDING?-c:c}}function zu(e,t){let r=e.rules.map(i=>AA(i,t)).filter(i=>i!==null);return r.length===0?null:(i,n)=>{for(let o of r){let a=o(i,n);if(a!==0)return a}return 0}}function qu(e){let t=[];e.forEachActivity((r,i)=>{r.type===D.PROJECT&&e.getChildren(String(i)).length===0&&t.push(String(i))});for(let r of t)e.setActivityField(r,x.TYPE,Qe),vA(e,r)}function vA(e,t){let r=e.getActivity(t);if(!r||!r.startDate||r.durationHours==null)return;let i=new Date(r.startDate);i.setUTCHours(0,0,0,0);let n=e.getClosestWorkTime({date:i,dir:j.FUTURE,task:r});if(n.getTime()===r.startDate.getTime())return;let o=e.calculateEndDate({startDate:n,durationHours:r.durationHours,task:r});e.setActivityField(t,x.START_DATE,n),e.setActivityField(t,x.END_DATE,o)}function Ju(e){let t=[],r=[];e.forEachActivity((n,o)=>{n.parentId===null&&t.push(String(o))});let i=n=>{let o=e.getActivity(n);if(!o)return 0;let a=[...e.getChildren(n)],s=a.length===0?Nt(o.workHours,o.progress):a.reduce((c,l)=>c+i(String(l)),0);return e.setActivityField(n,x.REAL_WORK_HOURS,s),r.push(n),s};for(let n of t)i(n);return r}async function Xu(e){let{state:t,sector:r,scheduler:i,skipAutoSchedule:n,now:o}=e;if(St(t),r.updateDurationForPrimaveraEndDate&&SA(t),TA(t),Ju(t),n){Mr(t),o&&(xe(t,o),ce(t,r.statusCriteria));return}let a=await i.schedule({});br(t,a),EA(t),CA(t),await rr(t,void 0,!1),Mr(t),o&&(xe(t,o),ce(t,r.statusCriteria))}function CA(e){e.forEachActivity(t=>{t.autoScheduling||!t.startDate||t.durationHours==null||e.getChildren(t.id).length>0||(t.endDate=e.calculateEndDate({startDate:t.startDate,durationHours:t.durationHours,task:t}),t.calendarDuration=Qt(t))})}function SA(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function TA(e){e.forEachActivity(t=>{let r=t.constraintType;if(!r||!t.constraintDate)return;let i=t.constraintDate;if(t.type===D.MILESTONE&&(i.getUTCHours()!==0||i.getUTCMinutes()!==0))return;let n=e.calendarReader.getCalendar(String(t.calendarId));n&&(t.constraintDate=ne(t.constraintDate,n,r))})}function EA(e){e.forEachActivity(t=>{if(t.type!==D.MILESTONE)return;let r=t.constraintType;if(!r||!t.constraintDate)return;let i=e.calendarReader.getCalendar(String(t.calendarId));i&&(t.constraintDate=ne(t.constraintDate,i,r))})}var Zt={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function Zu(e){let t=e.clock??null,r=t?.()??null,i=r?bi(r):null,n=e.reporter??tr,o=ql(),a=Ln({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},n,o.record),s=a.sector;s.statusCriteria=Ki(e.statusCriteria),s.ganttId=e.ganttId??null;let c=a.calendars,l=a.baseCalendars??[],d=Dn(a.activities,a.links,a.calendars,l),u=E=>zu(E,ke(s.hoursPerDay)),f=new Sr(d,u);f.hydrateViewState({hiddenIds:a.viewStateSeed.hiddenIds});let p=new er(f,n);qu(f);let y=Na({knownIds:a.activities.map(E=>E.id)}),g=ba({seed:r?.getTime()??0,knownIds:a.links.map(E=>E.id)}),T=Fa({knownIds:a.activities.map(E=>E.uniqueCorrelativeId)}),L=new Mn({defaultPrefix:s.customIdPrefix,suffixIncrement:s.customIdIncrement});if(L.populateFromActivities(a.activities),e.baselinePoints&&e.baselinePoints.length>0){let E=l.find(I=>I.baseDefault)?.id??null;mn(f,e.baselinePoints,i,n,E,o.record)}let C=Xu({state:f,sector:s,scheduler:p,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:i??void 0});return{sector:s,state:f,scheduler:p,activityIdGen:y,linkIdGen:g,uidGen:T,customIdTracker:L,calendars:c,baseCalendars:l,clock:t,reporter:n,loadDiagnostics:o.snapshot,initPromise:C}}function Er(e){if(e===void 0)return["undefined"];if(e===null)return["null"];if(typeof e=="string")return["string",e];if(typeof e=="boolean")return["boolean",e];if(typeof e=="number")return["number",Object.is(e,-0)?"-0":String(e)];if(typeof e=="bigint")return["bigint",String(e)];if(e instanceof Date)return["date",String(e.getTime())];if(Array.isArray(e))return["array",e.map(Er)];if(e instanceof Map)return["map",Array.from(e,([t,r])=>[Er(t),Er(r)]).sort((t,r)=>JSON.stringify(t).localeCompare(JSON.stringify(r)))];if(e instanceof Set)return["set",Array.from(e,Er).sort((t,r)=>JSON.stringify(t).localeCompare(JSON.stringify(r)))];if(typeof e=="object")return["object",Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Er(r)])];throw new TypeError(`Unsupported canonical value: ${typeof e}`)}function Ke(e){return JSON.stringify(Er(e))}function wa(e,t){let r=new Map(e.map(a=>[String(a.id),a])),i=new Map(t.map(a=>[String(a.id),a])),n=[...new Set([...r.keys(),...i.keys()])].sort(),o=[];for(let a of n){let s=i.get(a),c=r.get(a);if(c===void 0){o.push({id:a,kind:N.DELETED,after:null});continue}if(s===void 0){o.push({id:a,kind:N.CREATED,after:F(c)});continue}let l=DA(s,c);Object.keys(l).length>0&&o.push({id:a,kind:N.UPDATED,fields:l,after:F(c)})}return o}function DA(e,t){let r={},i=[...new Set([...Object.keys(e),...Object.keys(t)])].sort();for(let n of i)Ke(e[n])!==Ke(t[n])&&(r[n]={before:F(e[n]),after:F(t[n])});return r}function _A(e,t){let r=new Set(t.selectedIds.map(String)),i=new Set(e.selectedIds.map(String)),n=new Set(t.hiddenIds.map(String)),o=new Set(e.hiddenIds.map(String)),a=e.activities.map(({id:c})=>String(c)).sort(),s=[];for(let c of a){let l=r.has(c),d=i.has(c),u=!n.has(c),f=!o.has(c);l===d&&u===f||s.push({activityId:c,...l===d?{}:{checked:{before:l,after:d}},...u===f?{}:{visible:{before:u,after:f}}})}return s}function Qu(e,t){let r=Ke(e.order)!==Ke(t.order);return{source:{kind:oe.INIT},activities:wa(e.activities,t.activities),links:wa(e.links,t.links),calendars:wa(e.calendars,t.calendars),trackingEvents:[],effects:[],viewState:_A(e,t),...r?{order:F(e.order)}:{}}}var Dr={MOVE:"move",RESIZE_START:"resize-start",RESIZE_END:"resize-end"},kA=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),xa=(e,t)=>e===null?t:Math.min(e,t),Ma=(e,t)=>e===null?t:Math.max(e,t);function ef(e,t,r){let i=[...new Set(t.kind===Dr.MOVE?t.activityIds.map(String):[String(t.activityId)])];if(i.length===0)throw new Error("[ScheduleCore] date gesture has no participants");let n=RA(e,t,i);return PA(e,i,n),{getDates(o,a){if(r(),!Number.isFinite(a))throw new Error("[ScheduleCore] invalid date gesture edge");let s=n.get(String(o));if(!s)return null;let c=OA(s,a),l=NA(s,a);if(c===null||l===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(o)}`);return{startTimeMs:c,endTimeMs:l}}}}function RA(e,t,r){let i=new Map,n=t.kind===Dr.MOVE?String(t.anchorActivityId):null,o=n===null?null:tf(e,n);if(n!==null&&!r.includes(n))throw new Error("[ScheduleCore] move anchor is not a participant");for(let a of r){let s=tf(e,a);if(t.kind===Dr.MOVE){let c=o.startDate.getTime();i.set(a,{constantStart:null,variableStartOffset:s.startDate.getTime()-c,constantEnd:null,variableEndOffset:s.endDate.getTime()-c})}else t.kind===Dr.RESIZE_START?i.set(a,{constantStart:null,variableStartOffset:0,constantEnd:s.endDate.getTime(),variableEndOffset:null}):i.set(a,{constantStart:s.startDate.getTime(),variableStartOffset:null,constantEnd:null,variableEndOffset:0})}return i}function PA(e,t,r){let i=Br(e,new Set(t));for(let n of i){let o=kA();for(let a of e.getChildren(n)){let s=r.get(a);if(s){LA(o,s);continue}let c=e.getActivity(a);if(!c)throw new Error(`[ScheduleCore] missing child ${a} while previewing parent ${n}`);o.constantStart=xa(o.constantStart,c.startDate.getTime()),o.constantEnd=Ma(o.constantEnd,c.endDate.getTime())}r.set(n,o)}}function tf(e,t){let r=e.getActivity(t);if(!r)throw new Error(`[ScheduleCore] missing date gesture activity ${t}`);if(e.hasChildren(t))throw new Error(`[ScheduleCore] summary activity ${t} cannot be dragged directly`);return r}function LA(e,t){t.constantStart!==null&&(e.constantStart=xa(e.constantStart,t.constantStart)),t.variableStartOffset!==null&&(e.variableStartOffset=xa(e.variableStartOffset,t.variableStartOffset)),t.constantEnd!==null&&(e.constantEnd=Ma(e.constantEnd,t.constantEnd)),t.variableEndOffset!==null&&(e.variableEndOffset=Ma(e.variableEndOffset,t.variableEndOffset))}function OA(e,t){if(e.variableStartOffset===null)return e.constantStart;let r=t+e.variableStartOffset;return e.constantStart===null?r:Math.min(e.constantStart,r)}function NA(e,t){if(e.variableEndOffset===null)return e.constantEnd;let r=t+e.variableEndOffset;return e.constantEnd===null?r:Math.max(e.constantEnd,r)}var Ua=Symbol("ScheduleCore.fork.source");function bA(e){return e.kind===m.PERSISTENCE_ACKNOWLEDGE||e.kind===m.ACTIVITY_LOOKAHEAD_SYNC&&e.acknowledgePersistedLookahead===!0}function FA(e){for(let t of e.activities)if(t.kind===N.DELETED||t.kind===N.UPDATED&&t.fields!==void 0&&"parentId"in t.fields)return!0;return!1}function wA(e,t){let r=[];for(let i of e.activities){let n=t.getActivity(i.id);if(n===null)return null;r.push(n)}return r}function xA(e,t,r){if(e===null||e.filter!==t)return!1;let i=e.context.hoursPerDay===r.hoursPerDay,n=e.context.locale===r.locale;return i&&n}var _r=class e{activities;links;calendars;selection;view;baselines;impactRequests;persistence;history;projection;criticalPath;diagnostics;_activityClipboard={value:null};_status=Zt.READY;coreRuntime;_isFork;_undo=new En;_opQueue=Promise.resolve();_scheduleRevision=0;_stateRevision=0;_pendingScheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){if(Object.assign(this,Ga(this)),Ua in t){this._isFork=!0;let n=t[Ua],o=n.coreRuntime.state.fork();this.coreRuntime={state:o,scheduler:new er(o,n.coreRuntime.reporter),sector:F(n.coreRuntime.sector),activityIdGenerator:n.coreRuntime.activityIdGenerator.fork(),linkIdGenerator:n.coreRuntime.linkIdGenerator.fork(),uniqueCorrelativeIdGenerator:n.coreRuntime.uniqueCorrelativeIdGenerator.fork(),customIdTracker:n.coreRuntime.customIdTracker.fork(),calendars:new Map(Array.from(n.coreRuntime.calendars,([a,s])=>[a,F(s)])),baseCalendars:F(n.coreRuntime.baseCalendars),clock:n.coreRuntime.clock,reporter:n.coreRuntime.reporter,loadDiagnostics:n.coreRuntime.loadDiagnostics},this._activityClipboard.value=F(n._activityClipboard.value),this._undo=n._undo.fork(),this._saveTracker=n._saveTracker.fork(),this._scheduleRevision=n._scheduleRevision,this._stateRevision=n._stateRevision,this._pendingScheduleRevision=n._scheduleRevision,this._criticalPathRevision=n._criticalPathRevision,this._initPromise=Promise.resolve(),this._criticalPathReady=Promise.resolve(null),this._ready=this._initPromise;return}this._isFork=!1;let r=Zu(t);this.coreRuntime={state:r.state,scheduler:r.scheduler,sector:r.sector,activityIdGenerator:r.activityIdGen,linkIdGenerator:r.linkIdGen,uniqueCorrelativeIdGenerator:r.uidGen,customIdTracker:r.customIdTracker,clock:r.clock,calendars:new Map(r.calendars.map(n=>[n.id,n])),baseCalendars:r.baseCalendars,reporter:r.reporter,loadDiagnostics:r.loadDiagnostics},this._initPromise=r.initPromise.then(()=>{this._status!==Zt.DESTROYED&&this._saveTracker.init(this.coreRuntime.state.getAllActivities(),this.getAllLinksView())}),this._criticalPathReady=this._initPromise.then(()=>this._startCriticalPathForCurrentRevision());let i=t.criticalPathOnLoad===!0;this._ready=i?this._criticalPathReady.then(()=>{}):this._initPromise}get ready(){return this._ready}fork(){return this._enqueue(async()=>(await this._ready,this.assertReady(),new e({[Ua]:this})))}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return F(this.coreRuntime.sector)}getLoadDiagnostics(){return this.assertReady(),this.coreRuntime.loadDiagnostics()}getActivityView(t){return this.assertReady(),Ud(this.coreRuntime.state,t)}createDateGesturePreview(t){this.assertReady();let r=this._scheduleRevision;return ef(this.coreRuntime.state,t,()=>{if(this.assertReady(),this._scheduleRevision!==r)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),Bd(this.coreRuntime.state)}getIndentTargetParentIds(t){this.assertReady();let r=yn(t.map(i=>String(i)),this.coreRuntime.state);return[...new Set(r.allowedMoves.map(i=>String(i.newParentId)))]}getChildrenView(t){return this.assertReady(),Vd(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),Ta(this.coreRuntime.state,t)}getLinksForActivityView(t){this.assertReady();let r=this.coreRuntime.state,i=[],n=new Set,o=a=>{if(n.has(a))return;n.add(a);let s=Ta(r,a);s&&i.push(s)};for(let a of r.getOutgoingLinkIds(t))o(a);for(let a of r.getIncomingLinkIds(t))o(a);return i}getAllLinksView(){return this.assertReady(),Yd(this.coreRuntime.state)}auditEffectiveGraph(){this.assertReady();let t=this.coreRuntime.state,r=t.getAllLinks(),i=wr(t,r),n=Ai(i),o=0;for(let a of n)a.length>o&&(o=a.length);return{activityCount:t.getAllIds().length,logicalLinkCount:r.length,effectiveEdgeCount:i.length,circularComponents:n,largestComponentSize:o}}getProperty(t,r){this.assertReady();let i=this.coreRuntime.state.getActivity(t);return i?F(i[r]):null}getAllIds(){return this.assertReady(),Hd(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),Wd(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),Sa(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),jd(this.coreRuntime.state)}getHiddenActivityIds(){return this.assertReady(),this.coreRuntime.state.hiddenIds().map(String)}getVisibleActivityIds(){this.assertReady();let t=new Set(this.coreRuntime.state.hiddenIds().map(String));return this.coreRuntime.state.getAllIds().map(String).filter(r=>!t.has(r))}getActiveFilter(){return this.assertReady(),F(this.coreRuntime.state.getActiveFilter())}getActiveOrder(){return this.assertReady(),F(this.coreRuntime.state.getActiveOrder())}getVisualOrderIds(){return this.assertReady(),[...this.coreRuntime.state.getVisualOrderIds()]}hasChild(t){return this.assertReady(),Kd(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let r=this.coreRuntime.calendars.get(t);return r?F(r):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),t=>F(t))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(t=>F(t))}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),Gd(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(t=>this.coreRuntime.state.getLink(t)).map(F)}getNewLinks(){return this.assertReady(),this._saveTracker.newLinks(t=>this.coreRuntime.state.getLink(t)).map(F)}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(t=>this.coreRuntime.state.getActivity(t)).map(F)}getModifiedActivityFields(){return this.assertReady(),F(this._saveTracker.modifiedActivityFields(t=>this.coreRuntime.state.getActivity(t)))}getNewActivities(){return this.assertReady(),this._saveTracker.newActivities(t=>this.coreRuntime.state.getActivity(t)).map(F)}hasUnsavedChanges(){return this.assertReady(),this._saveTracker.hasUnsavedChanges()}getScheduleRevision(){return this._scheduleRevision}getStateRevision(){return this._stateRevision}capturePersistenceHistoryBoundary(){return this.assertReady(),this._undo.capturePersistenceBoundary()}getCanonicalDigest(){this.assertReady();let t=(r,i)=>String(r.id).localeCompare(String(i.id));return Ke({sector:this.getSector(),activities:[...this.getAllActivitiesView()].sort(t),links:[...this.getAllLinksView()].sort(t),calendars:[...this.getAllCalendars()].sort(t),baseCalendars:[...this.getBaseCalendars()].sort(t)})}createProjectionChangeSetFrom(t){this.assertReady(),t.assertReady();let r=i=>({activities:i.getAllActivitiesView(),links:i.getAllLinksView(),calendars:i.getAllCalendars(),selectedIds:i.getSelectedActivityIds(),hiddenIds:i.getHiddenActivityIds(),order:Xe(i.coreRuntime.state)});return Qu(r(this),r(t))}getDeletedActivitiesSinceLastSave(){return this.assertReady(),this._saveTracker.deletedActivities(t=>this.coreRuntime.state.getActivity(t)).map(F)}getDeletedLinksSinceLastSave(){return this.assertReady(),this._saveTracker.deletedLinks(t=>this.coreRuntime.state.getLink(t)).map(F)}_enqueue(t){let r=this._opQueue.then(t,t);return this._opQueue=r.then(()=>{},()=>{}),r}_beginScheduleMutation(t){return Yo(t)?this._admitScheduleMutation():!1}_admitScheduleMutation(){return this._pendingScheduleRevision++,this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),!0}_settleScheduleMutation(t,r){t&&(r||(this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision-1,this._scheduleRevision),this._pendingScheduleRevision===this._scheduleRevision&&this._criticalPathRevision!==this._scheduleRevision&&this.recomputeCriticalPath().catch(i=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path re-arm after a barren mutation failed",i)})))}async dispatch(t,r={}){let i=this._beginScheduleMutation(t);return this._enqueue(()=>this._dispatchInner(t,r,i))}async applyActivityBatch(t,r={}){let i=this._beginScheduleMutation(t);return this._enqueue(()=>this._dispatchInner(t,r,i))}planLookaheadConversion(t){return this.assertReady(),na(t,{adapter:this.coreRuntime.state,stateRevision:this._stateRevision})}applyLookaheadConversion(t){return this.dispatch({...t,kind:m.ACTIVITY_LOOKAHEAD_CONVERT})}async _dispatchInner(t,r={},i=!1){let n=!1;try{let o=await this._runDispatch(t,r);return n=o.changedState,o.result}finally{this._settleScheduleMutation(i,n)}}async _runDispatch(t,r){if(this.assertReady(),this._isFork&&bA(t))return{result:{ok:!1,reason:S.SANDBOX_PERSISTENCE_FORBIDDEN},changedState:!1};let i=$d(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat}),n=iu(t),o=[this.coreRuntime.activityIdGenerator.snapshot(),this.coreRuntime.linkIdGenerator.snapshot(),this.coreRuntime.uniqueCorrelativeIdGenerator.snapshot()];this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let a,s;try{a=await pd(t,r,{adapter:this.coreRuntime.state,ctx:i,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,linkIdGen:this.coreRuntime.linkIdGenerator,isActivityIdReserved:d=>this._saveTracker.hasCheckpointActivityId(d),isLinkIdReserved:d=>this._saveTracker.hasCheckpointLinkId(d),uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,reporter:this.coreRuntime.reporter,activityClipboard:this._activityClipboard,stateRevision:this._stateRevision,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(d=>d.baseDefault)?.id??null,now:this.coreRuntime.clock?bi(this.coreRuntime.clock()):null});let l=this.coreRuntime.state.peekWriteCapture()?.progressFallbackBefore;l&&l.size>0&&(s=new Map(l)),a.ok||this._rollback(o)}catch(l){throw this._rollback(o),l}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(a.ok&&n===Tr.RECORD&&ka(a.changes)){let l=Qd(this.coreRuntime.state,a.changes),d=s?new Map(Array.from(s.keys(),u=>[u,this.coreRuntime.state.getProgressFallback(u)])):void 0;this._undo.record(Ea(Zd(a.changes),a.__beforeSnap,a.__beforeLinks,l.afterSnap,l.afterLinks,s,d),tu(t),Date.now())}if(a.ok)if(n===Tr.CHECKPOINT_ON_SUCCESS){if(t.kind!==m.PERSISTENCE_ACKNOWLEDGE)throw new Error("checkpoint-on-success requires persistence acknowledge");let l=this.coreRuntime.state.getAllActivities(),d=this.coreRuntime.state.getAllLinks(),u=t.checkpoint,f=u?.historyBoundary??this._undo.capturePersistenceBoundary();this._saveTracker.acknowledge(u?.activities??l,u?.links??d,t.activities,t.links,l,d),this._undo.discardThrough(f),this._undo.applyPersistedIdentities(t.activities??[],t.links??[])}else t.kind===m.ACTIVITY_LOOKAHEAD_SYNC&&t.acknowledgePersistedLookahead===!0?(this._saveTracker.acknowledgePersistedLookahead(a.changes.activities,l=>this.coreRuntime.state.getActivity(l)),t.persistedProgress!==void 0&&this._undo.clear()):this._saveTracker.recordChanges(a.changes.activities,a.changes.links,l=>this.coreRuntime.state.getActivity(l),l=>this.coreRuntime.state.getLink(l));if(a=this._withReappliedViewState(t,a),!a.ok)return{result:a,changedState:!1};let c=ka(a.changes);return c&&this._stateRevision++,Yo(t)&&c?(this._recordScheduleMutation(r.skipAutoSchedule!==!0&&r.skipCriticalPath!==!0&&He(t)),{result:rf(a),changedState:!0}):{result:rf(a),changedState:!1}}recomputeCriticalPath(){let t=this._enqueue(async()=>({job:this._startCriticalPathForCurrentRevision()})).then(({job:r})=>r);return this._criticalPathReady=t,t}isCriticalPathSettled(){return this._criticalPathRevision===this._scheduleRevision&&this._pendingScheduleRevision===this._scheduleRevision&&this._activeCriticalPath===null}async whenCriticalPathSettled(){for(;!this.isCriticalPathSettled();)await this.recomputeCriticalPath()}_withReappliedViewState(t,r){if(!r.ok||(t.kind===m.VISIBILITY_SET&&this.coreRuntime.state.setFilterProjection(null),!el(t)))return r;let i=this._reapplyViewState(r.changes);return i===null?r:{...r,changes:i}}_reapplyViewState(t){let r=this._reapplyActiveFilter(t),i=this._emitTouchedBranchOrder(r??t);return this._reapplyActiveOrder(i.changes??r??t,i.touchedParents)??i.changes??r}_emitTouchedBranchOrder(t){let r=this.coreRuntime.state,i=cu(t,o=>r.getParentId(o));if(r.getActiveOrder()!==null)return{changes:null,touchedParents:i};if(i.size===0)return{changes:null,touchedParents:i};let n=Jn(r,i);return n.length===0?{changes:null,touchedParents:i}:{changes:{...t,order:n},touchedParents:i}}_reapplyActiveOrder(t,r){let i=this.coreRuntime.state;if(i.getActiveOrder()===null)return null;if(i.invalidateDerivedOrder(),t.links.length>0||t.calendars.length>0)return{...t,order:Xe(i)};let o=new Set(r);for(let s of t.activities){if(s.kind===N.DELETED)return{...t,order:Xe(i)};let c=i.getParentId(s.id);o.add(c===null?"0":String(c))}let a=Jn(i,o);return a.length===0?null:{...t,order:a}}_reapplyActiveFilter(t){let r=this.coreRuntime.state,i=r.getActiveFilter();if(i===null)return null;let n=ke(this.coreRuntime.sector.hoursPerDay),o=r.getFilterProjection(),a=xA(o,i,n),s=FA(t)?null:wA(t,r),c,l;if(s===null||!a){let f=ci({activities:r.getAllActivities(),parentOf:p=>r.getParentId(p),filter:i,context:n});r.setFilterProjection(f),l=f.visibleIds,c=r.getAllIds()}else c=rs(o,s,f=>r.getParentId(f)),l=o.visibleIds;let u=Je(r,l,c);return u.length===0?null:{...t,viewState:[...t.viewState??[],...u]}}_recordScheduleMutation(t){this._scheduleRevision++,this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision,this._scheduleRevision),this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),t&&(this._criticalPathRevision=this._scheduleRevision)}_startCriticalPathForCurrentRevision(){if(this._status===Zt.DESTROYED)return Promise.resolve(null);let t=this._scheduleRevision;if(this._criticalPathRevision===t)return Promise.resolve(null);if(this._activeCriticalPath?.revision===t)return this._activeCriticalPath.promise;this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0);let r={cancelled:!1},i=new Sr(Dn(this.coreRuntime.state.getAllActivities().map(s=>et(s)),this.coreRuntime.state.getAllLinks().map(s=>({...s})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),n=()=>!r.cancelled&&this._status!==Zt.DESTROYED&&this._scheduleRevision===t&&this._pendingScheduleRevision===this._scheduleRevision,o=(async()=>{let s=await jo(i,this.coreRuntime.sector.hoursPerDay,n);return!n()||s===null?null:this._enqueue(async()=>{if(!n())return null;this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let c;try{for(let[l,d]of s.activities)Wo(this.coreRuntime.state,l,d);for(let[l,d]of s.links)Vo(this.coreRuntime.state,l,d);c=await z(this.coreRuntime.state,{source:{kind:oe.INIT},beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay}),this._criticalPathRevision=t}catch(l){throw this._rollback(),l}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return{changes:c}})})();this._activeCriticalPath={revision:t,cancellation:r,promise:o};let a=()=>{this._activeCriticalPath?.promise===o&&(this._activeCriticalPath=null)};return o.then(a,a),o}undo(t={}){let r=this._admitScheduleMutation(),i=!1,n=this._enqueue(async()=>{try{return await this._runUndo(t,o=>{i=o})}finally{this._settleScheduleMutation(r,i)}});return n.then(o=>{o&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(a=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after undo failed",a)})},()=>{}),n}async _runUndo(t,r){{if(this.assertReady(),t.expectedUndoDepth!==void 0&&this._undo.undoDepth()!==t.expectedUndoDepth)return null;let i=this._undo.takeUndo();if(!i)return null;nu(this.coreRuntime.state,i),this._recordScheduleMutation(!1),r(!0),Da(i)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(i),this._undo.resetCoalesce();let n=_a(this.coreRuntime.state,i,ct.BEFORE);return this._saveTracker.recordChanges(n.activities,n.links,o=>this.coreRuntime.state.getActivity(o),o=>this.coreRuntime.state.getLink(o)),this._reapplyViewState(n)??n}}redo(t={}){let r=this._admitScheduleMutation(),i=!1,n=this._enqueue(async()=>{try{return await this._runRedo(o=>{i=o})}finally{this._settleScheduleMutation(r,i)}});return n.then(o=>{o&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(a=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after redo failed",a)})},()=>{}),n}async _runRedo(t){this.assertReady();let r=this._undo.takeRedo();if(!r)return null;ou(this.coreRuntime.state,r),this._recordScheduleMutation(!1),t(!0),Da(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce();let i=_a(this.coreRuntime.state,r,ct.AFTER);return this._saveTracker.recordChanges(i.activities,i.links,n=>this.coreRuntime.state.getActivity(n),n=>this.coreRuntime.state.getLink(n)),this._reapplyViewState(i)??i}canUndo(){return this._undo.canUndo()}canRedo(){return this._undo.canRedo()}clearHistory(){this._undo.clear()}undoDepth(){return this._undo.undoDepth()}_resyncCustomIdTrackerFromModel(){this.coreRuntime.customIdTracker.clear(),this.coreRuntime.customIdTracker.populateFromActivities(this.coreRuntime.state.getAllActivities())}destroy(){this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),this.coreRuntime.calendars.clear(),this._saveTracker.clear(),this._status=Zt.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new kn;assertReady(){if(this._status===Zt.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===Zt.POISONED)throw new Error("[ScheduleCore] instance is poisoned (a rollback failed) \u2014 reload from backend")}_rollback(t){try{this.coreRuntime.state.restoreFromCapture(),this.coreRuntime.scheduler.invalidateAllCaches(),this.coreRuntime.customIdTracker.rollbackCustomIdTransaction(),t&&(this.coreRuntime.activityIdGenerator.restore(t[0]),this.coreRuntime.linkIdGenerator.restore(t[1]),this.coreRuntime.uniqueCorrelativeIdGenerator.restore(t[2]))}catch(r){throw this._status=Zt.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",r),r}}};function rf(e){let{__beforeSnap:t,__beforeLinks:r,...i}=e;return i}async function nf(e){let t=new _r(e);return await t.ready,t}var of=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var af={asap:"AS SOON AS POSSIBLE",alap:"AS LATE AS POSSIBLE",snet:"START NO EARLIER THAN",snlt:"START NO LATER THAN",fnet:"FINISH NO EARLIER THAN",fnlt:"FINISH NO LATER THAN",mso:"MUST START ON",mfo:"MUST FINISH ON"};var sf=8;var cf={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return hf(MA);})();
|
|
2
2
|
//# sourceMappingURL=schedule-core.global.js.map
|