@outbuild-company/schedule-core 1.16.0 → 1.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var ScheduleCore=(()=>{var lo=Object.defineProperty;var Xf=Object.getOwnPropertyDescriptor;var Zf=Object.getOwnPropertyNames;var Qf=Object.prototype.hasOwnProperty;var tp=(e,t)=>{for(var r in t)lo(e,r,{get:t[r],enumerable:!0})},ep=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Zf(t))!Qf.call(e,n)&&n!==r&&lo(e,n,{get:()=>t[n],enumerable:!(i=Xf(t,n))||i.enumerable});return e};var rp=e=>ep(lo({},"__esModule",{value:!0}),e);var Jv={};tp(Jv,{ACTIVITY_BATCH_ACTION_KIND:()=>me,ACTIVITY_BATCH_MODE:()=>ht,ACTIVITY_DATE_EDGE:()=>Vr,ACTIVITY_FIELD:()=>vt,ACTIVITY_PONDERATOR_CRITERION:()=>mt,ACTIVITY_PROGRESS_ORIGIN:()=>dn,ACTIVITY_TYPE:()=>T,CALENDAR_UNIT:()=>ft,CHANGE_SET_SOURCE_KIND:()=>ne,COLUMN:()=>D,COMPLETED_PROGRESS:()=>Gr,CONSTRAINT_TYPE:()=>v,CONSTRAINT_TYPE_TO_LABEL:()=>$f,CONSTRAINT_WARNING_KIND:()=>ze,CREATION_KIND:()=>zf,DATE_GESTURE_KIND:()=>Ur,DEFAULT_HOURS_PER_DAY:()=>qf,DISPATCH_ACTION_KIND:()=>h,DISPATCH_ACTION_KINDS:()=>Is,DISPATCH_LINK_OPERATION_KIND:()=>nt,DISPATCH_TRACK_EVENT:()=>Gt,EDIT_ALERT_KEY:()=>Nc,EDIT_DENIAL_REASON:()=>ti,ENTITY_CHANGE_KIND:()=>N,FILTER_FIELD:()=>q,FILTER_LOGIC:()=>dr,FILTER_OPERATOR:()=>U,FILTER_REJECTION_REASON:()=>at,FILTER_VALUE_KIND:()=>P,GROUP_ID_PREFIX:()=>So,GROUP_ID_SEPARATOR:()=>Ri,LINK_BATCH_OPERATION_KIND:()=>cr,LINK_CODE:()=>Tt,LINK_CODE_TO_TYPE:()=>Ke,LINK_REJECTION_REASON:()=>st,LINK_RELATIONSHIP:()=>xe,LINK_TYPE:()=>W,LINK_TYPE_CODE:()=>$i,MINIMUM_GROUP_DEPTH:()=>Li,NEW_ACTIVITY_DEFAULTS:()=>Ln,NOT_STARTED_PROGRESS:()=>Qs,ORDER_DIRECTION:()=>Pt,REJECTION_REASON:()=>C,ROOT_PARENT_ID:()=>j,SCHEDULE_CORE_STATUS:()=>ee,SCHEDULE_EFFECT_KIND:()=>un,SIR_AUTO_REJECT_REASON:()=>fn,STATUS:()=>Rt,STATUS_CRITERIA:()=>he,ScheduleCore:()=>Br,UNASSIGNED_GROUP_LABEL:()=>Pi,UNASSIGNED_VALUE_ID:()=>Ve,VIEW_ATTRIBUTE_KIND:()=>Ue,VISUAL_ROW_KIND:()=>We,WORK_TIME_DIRECTION:()=>K,buildGroupRowId:()=>Oi,checkNoUpdatedLinks:()=>nf,computeExpectedProgress:()=>Vo,createSchedule:()=>Yf,expectedProgressFromBaseline:()=>Sr,getActiveBaseline:()=>At,getUnsavedActivities:()=>Gf,isRootParent:()=>B,isViewAttributeCriterion:()=>Be,isViewAttributeOrderRule:()=>ur,normalizeParentKey:()=>qt,parseFromBackend:()=>to,willRunCriticalPath:()=>Fu,yieldToBrowser:()=>dt});var T={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},ip=Object.values(T);function Hr(e){return ip.includes(e)}var mi={CONSTRAINT:"constraint",ALERT:"alert",WARNING:"warning"},K={FUTURE:"future",PAST:"past"},ft={HOUR:"hour",DAY:"day"},mt={DURATION:"DURATION",COST:"COST",WORK_HOURS:"HH"},he={BASELINE:"Baseline",ACTUAL:"Actual"},Rt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"},N={CREATED:"created",UPDATED:"updated",DELETED:"deleted"};var v={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},np={[v.MSO]:()=>!0,[v.MFO]:()=>!0,[v.SNLT]:(e,t)=>e<t,[v.SNET]:(e,t)=>e>t,[v.FNLT]:(e,t)=>e<t,[v.FNET]:(e,t)=>e>t};function gi(e,t,r){if(!t)return{violated:!1};let i=np[e];return i?i(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var op=new Set([v.MSO,v.SNET,v.SNLT]);function Fe(e,t,r){return op.has(e)?t:r}function Ai(e,t,r){return{type:mi.CONSTRAINT,messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var ap={[v.SNET]:{startOfDay:!0,direction:K.FUTURE},[v.SNLT]:{startOfDay:!0,direction:K.PAST},[v.FNET]:{startOfDay:!1,direction:K.FUTURE},[v.FNLT]:{startOfDay:!1,direction:K.PAST},[v.MSO]:{startOfDay:!0,direction:K.FUTURE},[v.MFO]:{startOfDay:!1,direction:K.PAST}},Ii=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),ys=(e,t)=>new Date(e.getTime()+t*864e5),sp=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function Wr(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=ap[e.constraintType];if(!r)return e.constraintDate;let i=e.constraintDate,n=t.getClosestWorkTime({date:Ii(i),dir:K.FUTURE,task:e});if(sp(n,i))return i.getTime()!==Ii(i).getTime()?i:r.startOfDay?n:t.getClosestWorkTime({date:ys(Ii(i),1),dir:K.PAST,task:e});let o=Ii(t.getClosestWorkTime({date:i,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:o,dir:K.FUTURE,task:e}):t.getClosestWorkTime({date:ys(o,1),dir:K.PAST,task:e})}function hs(e,t){let r={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},i=e.constraintType;if(!i||i===v.ASAP||i===v.ALAP)return r;let n=Wr(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 v.SNET:return{earliestStart:n,latestStart:null,earliestEnd:o(n),latestEnd:null};case v.SNLT:return{earliestStart:null,latestStart:n,earliestEnd:null,latestEnd:o(n)};case v.FNET:return{earliestStart:a(n),latestStart:null,earliestEnd:n,latestEnd:null};case v.FNLT:return{earliestStart:null,latestStart:a(n),earliestEnd:null,latestEnd:n};case v.MSO:{let s=o(n);return{earliestStart:n,latestStart:n,earliestEnd:s,latestEnd:s}}case v.MFO:{let s=a(n);return{earliestStart:s,latestStart:s,earliestEnd:n,latestEnd:n}}default:return r}}function ms(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function uo(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var W={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"},cp=Object.values(W);function vi(e){return cp.includes(e)}var lp={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"},dp={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"},D={...lp,...dp};var St={CREATE:"create",UPDATE:"update",DELETE:"delete"},st={SELF_LINK:"self-link",CYCLE:"cycle",DUPLICATE:"duplicate",ACTIVITY_MISSING:"activity-missing",LINK_MISSING:"link-missing",HIERARCHY_LINK:"hierarchy-link"};var h={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_TYPE_SET:"activity-type-set",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",VIEW_ATTRIBUTES_SET:"view-attributes-set",GROUP_SET:"group-set",SIR_SYNC:"sir-sync",ACTIVITY_LOOKAHEAD_SYNC:"activity-lookahead-sync",SCHEDULE_AUTO_SCHEDULE:"schedule-auto-schedule"},me="activity-batch",nt=St,Is=Object.values(h);function At(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isActiveVersion)??null}var vt={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"},Vr={START:"start",END:"end"},xe={FINISH_TO_START:"finish-to-start",START_TO_START:"start-to-start",FINISH_TO_FINISH:"finish-to-finish",START_TO_FINISH:"start-to-finish"},cr={CREATE:"create",UPDATE:"update",REMOVE:"remove"};var up={[vt.NAME]:D.TEXT,[vt.DESCRIPTION]:D.DESCRIPTION,[vt.DURATION_DAYS]:D.DURATION,[vt.PROGRESS]:D.PROGRESS,[vt.COST]:D.COST,[vt.USED_COST]:D.USED_COST,[vt.WORK_HOURS]:D.HH_WORK_TIME,[vt.START_DATE]:D.START_DATE,[vt.END_DATE]:D.END_DATE,[vt.CONSTRAINT_TYPE]:D.CONSTRAINT_TYPE,[vt.CONSTRAINT_DATE]:D.CONSTRAINT_DATE,[vt.CALENDAR_ID]:D.CALENDAR_ID,[vt.CUSTOM_ID]:D.CUSTOM_ID,[vt.SUBCONTRACT_ID]:D.SUBCONTRACT_ID,[vt.RESPONSABLE_IDS]:D.RESPONSABLES,[vt.TAG_IDS]:D.TAGS};function fo(e,t){return{activityId:e,column:up[t.field],newValue:t.value}}var fp={[xe.FINISH_TO_START]:W.FINISH_TO_START,[xe.START_TO_START]:W.START_TO_START,[xe.FINISH_TO_FINISH]:W.FINISH_TO_FINISH,[xe.START_TO_FINISH]:W.START_TO_FINISH};function jr(e){return fp[e]}function pp(e){return e.kind===cr.CREATE?{kind:nt.CREATE,source:e.sourceId,target:e.targetId,type:jr(e.relationship),...e.lagDays===void 0?{}:{lag:e.lagDays},...e.linkId===void 0?{}:{linkId:e.linkId}}:e.kind===cr.UPDATE?{kind:nt.UPDATE,linkId:e.linkId,...e.sourceId===void 0?{}:{source:e.sourceId},...e.targetId===void 0?{}:{target:e.targetId},...e.relationship===void 0?{}:{type:jr(e.relationship)},...e.lagDays===void 0?{}:{lag:e.lagDays}}:e.kind===cr.REMOVE?{kind:nt.DELETE,linkId:e.linkId}:e}function yp(e){return e===Vr.START?D.START_DATE:e===Vr.END?D.END_DATE:e}function hp(e){return{kind:me,mode:e.mode,items:e.items,links:e.links.map(t=>({source:t.source,target:t.target,type:jr(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}})),...e.eventSource===void 0?{}:{eventSource:e.eventSource}}}function mp(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:h.ACTIVITY_CREATE},r),applyBatch:(t,r)=>e.applyActivityBatch(hp(t),r),editInline:(t,r,i)=>e.dispatch({...fo(t,r),kind:h.INLINE_EDIT},i),setType:(t,r,i)=>e.dispatch({kind:h.ACTIVITY_TYPE_SET,activityId:t,type:r},i),applyDragBatch:(t,r)=>e.dispatch({kind:h.DATES_BATCH,edits:t.map(i=>({activityId:i.activityId,column:yp(i.edge),newValue:i.value}))},r),editFields:(t,r)=>e.dispatch({kind:h.BULK_EDIT,edits:t.map(i=>fo(i.activityId,i))},r),remove:(t,r={})=>e.dispatch({...r,kind:h.ACTIVITY_DELETE,activityIds:t}),move:(t,r)=>e.dispatch({...t,kind:h.ACTIVITY_MOVE},r),planLookaheadConversion:t=>e.planLookaheadConversion(t),applyLookaheadConversion:t=>e.applyLookaheadConversion(t),indent:(t,r={})=>e.dispatch({...r,kind:h.ACTIVITY_INDENT,activityIds:t}),outdent:(t,r={})=>e.dispatch({...r,kind:h.ACTIVITY_OUTDENT,activityIds:t}),setProgress:(t,r,i={})=>e.dispatch({...i,kind:h.ACTIVITY_SET_PROGRESS,activityId:t,newValue:r}),copy:(t={})=>e.dispatch({...t,kind:h.ACTIVITY_COPY}),paste:(t,r={})=>e.dispatch({...r,kind:h.ACTIVITY_PASTE_COPIED,destination:{afterSiblingId:t}}),clearClipboard:(t={})=>e.dispatch({...t,kind:h.ACTIVITY_CLIPBOARD_CLEAR}),lookaheadSync:t=>e.dispatch({...t,kind:h.ACTIVITY_LOOKAHEAD_SYNC}),autoSchedule:(t,r)=>e.dispatch({kind:h.SCHEDULE_AUTO_SCHEDULE,...t===void 0?{}:{activityId:t}},r),createDateGesturePreview:t=>e.createDateGesturePreview(t)}}function Ip(e){return{get:t=>e.getLinkView(t),list:()=>e.getAllLinksView(),forActivity:t=>e.getLinksForActivityView(t),create:(t,r)=>e.dispatch({kind:h.LINK_CREATE,source:t.sourceId,target:t.targetId,type:jr(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}},r),update:(t,r,i)=>e.dispatch({kind:h.LINK_UPDATE,linkId:t,...r.sourceId===void 0?{}:{source:r.sourceId},...r.targetId===void 0?{}:{target:r.targetId},...r.relationship===void 0?{}:{type:jr(r.relationship)},...r.lagDays===void 0?{}:{lag:r.lagDays}},i),remove:(t,r)=>e.dispatch({kind:h.LINK_DELETE,linkId:t},r),batch:(t,r)=>e.dispatch({kind:h.LINKS_BATCH,operations:t.map(pp)},r)}}function gs(e){let t=(r,i)=>e.dispatch({kind:h.BASELINE_APPLY,points:r},i);return{activities:mp(e),links:Ip(e),calendars:{get:r=>e.getCalendar(r),list:()=>e.getAllCalendars(),listBase:()=>e.getBaseCalendars(),projectWorkHours:()=>e.getProjectWorkHours(),reconcile:r=>e.dispatch({kind:h.CALENDAR_RECONCILE},r)},selection:{ids:()=>e.getSelectedActivityIds(),toggle:({checked:r,...i})=>e.dispatch({...i,kind:h.SELECTION_TOGGLE,isChecked:r}),replace:(r,i={})=>e.dispatch({...i,kind:h.SELECTION_REPLACE,activityIds:r})},view:{hiddenActivityIds:()=>e.getHiddenActivityIds(),visibleActivityIds:()=>e.getVisibleActivityIds(),visualOrderIds:()=>e.getVisualOrderIds(),visualRows:()=>e.getVisualRows(),filter:()=>e.getActiveFilter(),setFilter:r=>e.dispatch({...r,kind:h.FILTER_SET}),order:()=>e.getActiveOrder(),setOrder:(r,i={})=>e.dispatch({...i,kind:h.SORT_SET,rules:r}),group:()=>e.getActiveGroup(),setViewAttributes:(r,i={})=>e.dispatch({...i,kind:h.VIEW_ATTRIBUTES_SET,catalogs:r}),setGroup:(r,i={})=>e.dispatch({...i,kind:h.GROUP_SET,group:r}),setVisibility:(r,i={})=>e.dispatch({...i,kind:h.VISIBILITY_SET,visibleIds:r}),setStatusCriteria:(r,i)=>e.dispatch({kind:h.STATUS_CRITERIA_SET,criteria:r},i)},baselines:{refresh:t,setVisibility:t,setPonderatorCriterion:(r,i)=>e.dispatch({kind:h.PONDERATOR_CRITERION_SET,criterion:r},i),activeFor:r=>At(r)},impactRequests:{sync:r=>e.dispatch({...r,kind:h.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:h.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 Bt=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 Ci=e=>String(e);function As(e){let{clickedId:t,isChecked:r,currentSelection:i,hierarchy:n,isFrozen:o,exists:a,autoCheckParents:s}=e,c=Ci(t),l=new Set([...i].map(String)),d=new Set(l),u=gp(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||Ap({id:c,isChecked:r,autoCheckParents:s,hierarchy:n,isFrozen:o,exists:a,next:d}),{nextSelection:d,changed:vp(l,d),parentBlocked:p}}function gp(e,t){let r=[],i=new Bt;i.enqueue(e);let n=new Set([e]);for(;!i.isEmpty();){let o=i.dequeue();for(let a of t.getChildrenIds(o)){let s=Ci(a);n.has(s)||(n.add(s),r.push(s),i.enqueue(s))}}return r}function Ap(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=Ci(c);if(o(l))return;let d=n.getChildrenIds(l).map(Ci).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 vp(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 lr(e){return(e.pendingRequestIds?.length??0)>0}var C={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 vs=(e,t)=>{let r=e.getActivity(t);return r!=null&&lr(r)},Cs=(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 Ss(e,t){let{adapter:r}=t,i=e.activityId;if(!r.getActivity(i))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let n=e.frozenIds?new Set(e.frozenIds):null,o=n?s=>n.has(s):s=>vs(r,s),a=As({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:Cs(e,r,a.changed)}}function Si(e,t){let{adapter:r}=t,i=new Set(e.activityIds.map(String).filter(a=>r.activityExists(a)).filter(a=>!vs(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:Cs(e,r,o)}}function Me(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 Ts(e,t){let{adapter:r}=t,i=new Set(e.visibleIds.map(String)),n=Me(r,i);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:n}}}var Es={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var Ue="viewAttribute";var P={STRING:"string",NUMBER:"number",DATE:"date",ID_ARRAY:"id-array",ENUM:"enum",BOOLEAN:"boolean",REFERENCE:"reference"},q={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"},U={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"};function Be(e){return"kind"in e&&e.kind===Ue}var dr={AND:"and",OR:"or"};var Cp=2,Sp=[Rt.WAITING,Rt.DONE,Rt.DOING,Rt.OVERDUE,Rt.ADVANCEMENT],Tp=[v.MFO,v.MSO,v.SNLT,v.SNET,v.ALAP,v.ASAP,v.FNET,v.FNLT],Ep=1e3*60*60*24;function po(e,t){return e===null||t<=0?null:e/t}function Dp(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)/Ep)+1}var _p={[q.NAME]:{valueKind:P.STRING,extract:e=>e.name},[q.DESCRIPTION]:{valueKind:P.STRING,extract:e=>e.description},[q.CUSTOM_ID]:{valueKind:P.STRING,extract:e=>e.customId},[q.CORRELATIVE_ID]:{valueKind:P.NUMBER,extract:e=>e.correlativeId},[q.UNIQUE_CORRELATIVE_ID]:{valueKind:P.NUMBER,extract:e=>{let t=Number(e.uniqueCorrelativeId);return Number.isFinite(t)?t:null}},[q.PROGRESS]:{valueKind:P.NUMBER,extract:e=>e.progress},[q.DURATION_DAYS]:{valueKind:P.NUMBER,extract:(e,t)=>po(e.durationHours,t.hoursPerDay)},[q.CALENDAR_DURATION]:{valueKind:P.NUMBER,extract:e=>e.type===T.MILESTONE?0:Dp(e.startDate,e.endDate)},[q.COST]:{valueKind:P.NUMBER,extract:e=>e.cost},[q.USED_COST]:{valueKind:P.NUMBER,extract:e=>e.usedCost},[q.REAL_COST]:{valueKind:P.NUMBER,extract:e=>e.realCost},[q.WORK_HOURS]:{valueKind:P.NUMBER,extract:e=>e.workHours},[q.REAL_WORK_HOURS]:{valueKind:P.NUMBER,extract:e=>e.realWorkHours},[q.PONDERATOR]:{valueKind:P.NUMBER,extract:e=>e.ponderator},[q.FREE_SLACK_DAYS]:{valueKind:P.NUMBER,extract:(e,t)=>po(e.freeSlackHours,t.hoursPerDay)},[q.TOTAL_SLACK_DAYS]:{valueKind:P.NUMBER,extract:(e,t)=>po(e.criticalPath?.totalSlackHours??null,t.hoursPerDay)},[q.EXPECTED_PROGRESS_BASELINE]:{valueKind:P.NUMBER,equalityPrecision:Cp,extract:e=>e.expectedProgressBaseline},[q.EXPECTED_PROGRESS]:{valueKind:P.NUMBER,extract:e=>e.expectedProgress},[q.BASELINE_DURATION_DAYS]:{valueKind:P.NUMBER,extract:e=>e.baselineSnapshot?.durationDays??null},[q.BASELINE_COST]:{valueKind:P.NUMBER,extract:e=>e.baselineSnapshot?.cost??null},[q.BASELINE_WORK_HOURS]:{valueKind:P.NUMBER,extract:e=>e.baselineSnapshot?.workHours??null},[q.START_DATE]:{valueKind:P.DATE,extract:e=>e.startDate},[q.END_DATE]:{valueKind:P.DATE,extract:e=>e.endDate},[q.CONSTRAINT_DATE]:{valueKind:P.DATE,extract:e=>e.constraintDate},[q.BASELINE_START_DATE]:{valueKind:P.DATE,extract:e=>e.baselineSnapshot?.startDate??null},[q.BASELINE_END_DATE]:{valueKind:P.DATE,extract:e=>e.baselineSnapshot?.endDate??null},[q.EARLY_START]:{valueKind:P.DATE,extract:e=>e.criticalPath?.earlyStart??null},[q.EARLY_FINISH]:{valueKind:P.DATE,extract:e=>e.criticalPath?.earlyFinish??null},[q.LATE_START]:{valueKind:P.DATE,extract:e=>e.criticalPath?.lateStart??null},[q.LATE_FINISH]:{valueKind:P.DATE,extract:e=>e.criticalPath?.lateFinish??null},[q.RESPONSABLE_IDS]:{valueKind:P.ID_ARRAY,extract:e=>e.responsableIds},[q.TAG_IDS]:{valueKind:P.ID_ARRAY,extract:e=>e.tagIds},[q.STATUS]:{valueKind:P.ENUM,order:Sp,extract:e=>e.status},[q.CONSTRAINT_TYPE]:{valueKind:P.ENUM,order:Tp,extract:e=>e.constraintType},[q.CALENDAR_ID]:{valueKind:P.REFERENCE,extract:e=>e.calendarId===null?null:String(e.calendarId)},[q.SUBCONTRACT_ID]:{valueKind:P.REFERENCE,extract:e=>e.subcontractId===null?null:String(e.subcontractId)},[q.IS_CRITICAL]:{valueKind:P.BOOLEAN,extract:e=>e.isCritical}};function Ie(e){return _p[e]??null}function Ds(e){return e===null?"":e}function _s(e){let t=new Map,r=new Map;for(let c of e.values){t.set(c.id,c);let l=Ds(c.parentId),d=r.get(l)??[];d.push(c),r.set(l,d)}for(let c of r.values())c.sort((l,d)=>l.sequence!==d.sequence?l.sequence-d.sequence:l.id.localeCompare(d.id));let i=new Map,n=new Map,o=(c,l,d)=>{let u=r.get(Ds(c))??[];for(let f of u){let p=[...l,f.id],y=[...d,f.sequence];i.set(f.id,p),n.set(f.id,y),o(f.id,p,y)}};o(null,[],[]);let a=new Map;for(let c of t.keys()){let l=new Set([c]);for(let[d,u]of i)u.includes(c)&&l.add(d);a.set(c,l)}let s=new Map;for(let c of e.assignments)t.has(c.valueId)&&s.set(String(c.activityId),c.valueId);return{key:e.key,valueById:t,pathByValueId:i,sequencePathByValueId:n,descendantIdsByValueId:a,assignmentByActivityId:s}}var Ti=new Map;function ks(e,t){let r=new Set;for(let i of t){let n=e.descendantIdsByValueId.get(i);if(n===void 0){r.add(i);continue}for(let o of n)r.add(o)}return r}function Rs(e,t,r){let i=e.pathByValueId.get(t);return i===void 0||i.length===0?[t]:i.slice(0,Math.max(r,1))}function Ps(e,t,r){let i=r.get(t.key),n=i?.assignmentByActivityId.get(String(e.id))??null,o=i?ks(i,t.value):new Set(t.value),a=n!==null&&o.has(n);return t.operator===U.SOME_OF?a:t.operator===U.NOT_SOME_OF?!a:!1}function yo(e){return e instanceof Date?e:typeof e=="string"||typeof e=="number"?new Date(e):new Date(Number.NaN)}function se(e){return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())}function kp(e,t,r){let i=e===null;return r===U.INCLUDES?!i&&String(e).toLowerCase().includes(t.toLowerCase()):r===U.NOT_INCLUDES?i||!String(e).toLowerCase().includes(t.toLowerCase()):r===U.IS?!i&&String(e)===t:r===U.IS_NOT?i||String(e)!==t:!1}function Rp(e,t,r,i){if(e===null||typeof e!="number")return r===U.NOT_EQUALS;let n=i===void 0?e:Number(e.toFixed(i));return r===U.EQUALS?n===t:r===U.NOT_EQUALS?n!==t:r===U.GREATER_THAN?e>t:r===U.LESS_THAN?e<t:r===U.GREATER_OR_EQUAL?e>=t:r===U.LESS_OR_EQUAL?e<=t:!1}function Pp(e,t,r){return typeof e=="number"&&e>=t&&e<=r}function Lp(e,t,r){if(!(e instanceof Date))return!1;let i=se(e),n=se(t);return r===U.AFTER?i>n:r===U.BEFORE?i<n:!1}function Op(e,t,r){if(!(e instanceof Date))return!1;let i=se(e);return i>=se(t)&&i<=se(r)}function Np(e,t,r){let n=(Array.isArray(e)?e:[]).some(o=>t.has(String(o)));return r===U.SOME_OF?n:r===U.NOT_SOME_OF?!n:!1}function bp(e,t,r){let i=e!==null&&t.has(String(e));return r===U.SOME_OF?i:r===U.NOT_SOME_OF?!i:!1}function Ls(e){let t=Array.isArray(e)?e:[e];return new Set(t.map(r=>String(r)))}function Di(e){return e.viewAttributeCatalogs??Ti}function Ei(e,t,r,i){if(Be(t))return Ps(e,t,i);let n=Ie(t.field);if(n===null)return!1;let o=n.extract(e,r),{operator:a}=t;return a===U.BETWEEN?n.valueKind===P.NUMBER?Pp(o,Number(t.value),Number(t.valueTo)):n.valueKind===P.DATE?Op(o,yo(t.value),yo(t.valueTo)):!1:n.valueKind===P.STRING?kp(o,String(t.value),a):n.valueKind===P.NUMBER?Rp(o,Number(t.value),a,n.equalityPrecision):n.valueKind===P.DATE?Lp(o,yo(t.value),a):n.valueKind===P.ID_ARRAY?Np(o,Ls(t.value),a):bp(o,Ls(t.value),a)}function Os(e,t,r,i){return t.criteria.length===0?!0:t.logic===dr.OR?t.criteria.some(n=>Ei(e,n,r,i)):t.criteria.every(n=>Ei(e,n,r,i))}function wp(e,t,r,i){return t.groups&&t.groups.length>0?t.logic===dr.OR?t.groups.some(n=>Os(e,n,r,i)):t.groups.every(n=>Os(e,n,r,i)):t.criteria.length===0?!0:t.logic===dr.OR?t.criteria.some(n=>Ei(e,n,r,i)):t.criteria.every(n=>Ei(e,n,r,i))}function Fp(e,t){let r=se(e.startDate),i=se(e.endDate),n=se(t.start),o=se(t.end),a=r>=n&&i<=o,s=r>=n&&r<=o,c=n>=r&&n<=i;return a||s||c}function ho(e,t,r,i){let n=wp(e,t,r,i),o=t.dateRange,a=o===void 0||Fp(e,o);return n&&a}function xp(e,t,r){let i=t(e);for(;i!==null&&!r.has(String(i));)r.add(String(i)),i=t(i)}function Ns(e){let{activities:t,parentOf:r,filter:i,context:n}=e,o=Di(e),a=new Set,s=[];for(let c of t)ho(c,i,n,o)&&(a.add(String(c.id)),s.push(c.id));for(let c of s)xp(c,r,a);return a}function Mp(e){let{activities:t,parentOf:r,filter:i,context:n}=e,o=Di(e),a=new Set,s=new Map,c=new Map,l=new Map;for(let d of t){let u=String(d.id),f=r(u);c.set(u,f),l.set(u,l.get(u)??0),f!==null&&l.set(f,(l.get(f)??0)+1);let p=ho(d,i,n,o);s.set(u,p?1:0),p&&a.add(u)}return{matchedIds:a,visibleReferenceCounts:s,parentIds:c,remainingChildren:l}}function Up(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 Bp(e){let t=new Set;for(let[r,i]of e)i>0&&t.add(r);return t}function _i(e){let t=Mp(e);Up(t);let r=Bp(t.visibleReferenceCounts);return{filter:e.filter,context:e.context,matchedIds:t.matchedIds,visibleIds:r,visibleReferenceCounts:t.visibleReferenceCounts,viewAttributeCatalogs:Di(e)}}function bs(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=ho(n,e.filter,e.context,Di(e));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 He(e){return{hoursPerDay:e,locale:"en"}}var at={UNKNOWN_FIELD:"unknown_field",UNKNOWN_OPERATOR:"unknown_operator",INVALID_VALUE:"invalid_value"},Hp={[P.STRING]:new Set([U.INCLUDES,U.NOT_INCLUDES,U.IS,U.IS_NOT]),[P.NUMBER]:new Set([U.EQUALS,U.NOT_EQUALS,U.GREATER_THAN,U.LESS_THAN,U.GREATER_OR_EQUAL,U.LESS_OR_EQUAL,U.BETWEEN]),[P.DATE]:new Set([U.AFTER,U.BEFORE,U.BETWEEN]),[P.ID_ARRAY]:new Set([U.SOME_OF,U.NOT_SOME_OF]),[P.ENUM]:new Set([U.SOME_OF,U.NOT_SOME_OF]),[P.BOOLEAN]:new Set([U.SOME_OF,U.NOT_SOME_OF]),[P.REFERENCE]:new Set([U.SOME_OF,U.NOT_SOME_OF])};function ws(e){if(e===void 0)return{ok:!0,dateRange:void 0};if(typeof e!="object"||e===null)return{ok:!1,reason:at.INVALID_VALUE};let{start:t,end:r}=e;if(!(t instanceof Date)||!(r instanceof Date))return{ok:!1,reason:at.INVALID_VALUE};let i=t.getTime(),n=r.getTime();return!Number.isFinite(i)||!Number.isFinite(n)||i>n?{ok:!1,reason:at.INVALID_VALUE}:{ok:!0,dateRange:{start:new Date(i),end:new Date(n)}}}function go(e){if(Be(e))return Vp(e);let t=Ie(e.field);if(t===null)return{ok:!1,reason:at.UNKNOWN_FIELD};if(!Hp[t.valueKind].has(e.operator))return{ok:!1,reason:at.UNKNOWN_OPERATOR};if(e.operator===U.BETWEEN)return Wp(e,t.valueKind);if(t.valueKind===P.NUMBER){let i=mo(e.value);return i===null?{ok:!1,reason:at.INVALID_VALUE}:{ok:!0,criterion:{...e,value:i}}}if(t.valueKind===P.DATE){let i=Io(e.value);return i===null?{ok:!1,reason:at.INVALID_VALUE}:{ok:!0,criterion:{...e,value:i}}}let r=jp(e,t.valueKind);return r!==null?{ok:!1,reason:r}:t.valueKind===P.BOOLEAN?{ok:!0,criterion:{...e,value:[...new Set(e.value)]}}:t.valueKind===P.ID_ARRAY||t.valueKind===P.ENUM||t.valueKind===P.REFERENCE?{ok:!0,criterion:{...e,value:[...new Set(e.value.map(String))]}}:{ok:!0,criterion:e}}function Wp(e,t){if(t===P.NUMBER){let r=mo(e.value),i=mo(e.valueTo);return r===null||i===null||r>i?{ok:!1,reason:at.INVALID_VALUE}:{ok:!0,criterion:{...e,value:r,valueTo:i}}}if(t===P.DATE){let r=Io(e.value),i=Io(e.valueTo);return r===null||i===null||r.getTime()>i.getTime()?{ok:!1,reason:at.INVALID_VALUE}:{ok:!0,criterion:{...e,value:r,valueTo:i}}}return{ok:!1,reason:at.UNKNOWN_OPERATOR}}function Vp(e){return Be(e)?typeof e.key!="string"||e.key.length===0?{ok:!1,reason:at.UNKNOWN_FIELD}:e.operator!==U.SOME_OF&&e.operator!==U.NOT_SOME_OF?{ok:!1,reason:at.UNKNOWN_OPERATOR}:!Array.isArray(e.value)||e.value.some(t=>typeof t!="string")?{ok:!1,reason:at.INVALID_VALUE}:{ok:!0,criterion:e}:{ok:!1,reason:at.UNKNOWN_FIELD}}function jp(e,t){let{value:r}=e;return t===P.BOOLEAN?Array.isArray(r)&&r.every(i=>typeof i=="boolean")?null:at.INVALID_VALUE:t===P.ID_ARRAY||t===P.ENUM||t===P.REFERENCE?Array.isArray(r)&&r.every(i=>typeof i=="string"||typeof i=="number")?null:at.INVALID_VALUE:Array.isArray(r)?at.INVALID_VALUE:null}function mo(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 Io(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 Fs(e){return!(e.groups!==void 0&&e.groups.some(r=>r.criteria.length>0))&&e.criteria.length===0&&e.dateRange===void 0}function xs(e,t,r){let i=e.getAllActivities();if(Fs(t))return{visibleIds:Ns({activities:i,parentOf:o=>e.getParentId(o),filter:t,context:He(r),viewAttributeCatalogs:e.getViewAttributeCatalogMap()}),projection:null};let n=_i({activities:i,parentOf:o=>e.getParentId(o),filter:t,context:He(r),viewAttributeCatalogs:e.getViewAttributeCatalogMap()});return{visibleIds:n.visibleIds,projection:n}}function Kp(e){if(!e||e.length===0)return{ok:!0,groups:[]};let t=[];for(let r of e){let i=[];for(let n of r.criteria){let o=go(n);if(!o.ok)return{ok:!1,reason:o.reason};i.push(o.criterion)}t.push({criteria:i,logic:r.logic})}return{ok:!0,groups:t}}function Ms(e,t){let{adapter:r,hoursPerDay:i}=t,n=[];for(let f of e.criteria){let p=go(f);if(!p.ok)return{ok:!1,reason:p.reason};n.push(p.criterion)}let o=Kp(e.groups);if(!o.ok)return{ok:!1,reason:o.reason};let a=ws(e.dateRange);if(!a.ok)return{ok:!1,reason:a.reason};let s=F({criteria:n,logic:e.logic,...o.groups.length>0?{groups:o.groups}:{},...a.dateRange!==void 0?{dateRange:a.dateRange}:{}});r.setActiveFilter(Fs(s)?null:s);let{visibleIds:c,projection:l}=xs(r,s,i);r.setFilterProjection(l);let d=Me(r,c);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:d}}}function Us(e,t){let r=e.getActiveFilter();if(r===null)return[];let{visibleIds:i,projection:n}=xs(e,r,t);return e.setFilterProjection(n),Me(e,i)}var Pt={ASCENDING:"asc",DESCENDING:"desc"};function ur(e){return"kind"in e&&e.kind===Ue&&"key"in e&&"direction"in e&&!("operator"in e)}var j="0";function B(e){return e==null||e===0||e==="0"}function qt(e){return B(e)?"0":String(e)}var Ao=Number.MAX_SAFE_INTEGER;function jt(e,t){let r=Kr(e,t),i=t.getOrderComparator?.()??null;return r.sort(i===null?ki:(n,o)=>i(n,o)||ki(n,o)),r.map(n=>String(n.id))}function Hs(e){let t=[],r=n=>{t.push(n);let o=jt(String(n.id),e);for(let a of o){let s=e.getActivity(a);s&&r(s)}},i=jt("0",e);for(let n of i){let o=e.getActivity(n);o&&r(o)}return t}function Ws(e,t,r){let i=r.getActivity(e);if(!i)return null;let n=Vs(i),o=jt(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&&!Yp(t,c))return c}return null}function vo(e,t){let r=t.getActivity(e);if(!r)return-1;let i=Vs(r);return jt(i,t).findIndex(o=>String(o)===String(e))}function Kr(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 ki(e,t){let r=Bs(e),i=Bs(t);return r!==i?r-i:String(e.id).localeCompare(String(t.id))}function Bs(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Ao}function Vs(e){let t=e.parentId;return t===null?"0":t}function Yp(e,t){return e.has(t)?!0:e.has(String(t))}function ge(e){let t=[],r=i=>{let n=jt(i,e);n.length>1&&t.push({parentId:i,childIds:n});for(let o of n)r(o)};return r("0"),t}function Co(e,t){let r=[];for(let i of t){let n=jt(i,e);n.length>1&&r.push({parentId:i,childIds:n})}return r}function Gp(e){return ur(e)?typeof e.key!="string"||e.key.length===0?at.UNKNOWN_FIELD:e.direction!==Pt.ASCENDING&&e.direction!==Pt.DESCENDING?at.UNKNOWN_OPERATOR:null:Ie(e.field)===null?at.UNKNOWN_FIELD:e.direction!==Pt.ASCENDING&&e.direction!==Pt.DESCENDING?at.UNKNOWN_OPERATOR:null}function js(e,t){let{adapter:r}=t;for(let o of e.rules){let a=Gp(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:ge(r)}}}var We={GROUP:"group",ACTIVITY:"activity"},Ve="unassigned",So="g",Ri=":",Pi="Unassigned",Li=1;function Oi(e,t){return`${So}${Ri}${e}${Ri}${t}`}function $p(e){return Number.isInteger(e)&&Number.isFinite(e)}function qp(e){return typeof e.attributeKey!="string"||e.attributeKey.length===0||!$p(e.depth)||e.depth<Li||e.direction!==Pt.ASCENDING&&e.direction!==Pt.DESCENDING||typeof e.includeWbs!="boolean"||!Array.isArray(e.collapsedIds)||e.collapsedIds.some(t=>typeof t!="string")?null:{attributeKey:e.attributeKey,depth:e.depth,direction:e.direction,includeWbs:e.includeWbs,collapsedIds:new Set(e.collapsedIds)}}function To(e){return{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}function Ks(e,t){let{adapter:r,hoursPerDay:i}=t;if(!Array.isArray(e.catalogs))return{ok:!1,reason:at.INVALID_VALUE};r.setViewAttributeCatalogs(e.catalogs);let n=Us(r,i),o=r.getActiveOrder();return{ok:!0,changes:{...To(e),viewState:n,...o===null?{}:{order:ge(r)}}}}function Ys(e,t){let{adapter:r}=t;if(e.group===null)return r.setGroup(null),{ok:!0,changes:To(e)};let i=qp(e.group);return i===null?{ok:!1,reason:at.INVALID_VALUE}:(r.setGroup(i),{ok:!0,changes:To(e)})}function Gs(e,t){throw new Error(t)}var Eo={OWN_BASELINE:"own-baseline",RECURSIVE_LEAF_SUM:"recursive-leaf-sum",ZERO:"zero"},Do={[T.PROJECT]:{alwaysSummary:!0,holdsConstraint:!1,carriesCustomId:!1,forcedDuration:null,ponderatorWeight:Eo.RECURSIVE_LEAF_SUM,promotesToProjectOnFirstChild:!1},[T.TASK]:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:null,ponderatorWeight:Eo.OWN_BASELINE,promotesToProjectOnFirstChild:!0},[T.MILESTONE]:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:0,ponderatorWeight:Eo.ZERO,promotesToProjectOnFirstChild:!0}};function zt(e,t){return t||Hr(e)&&Do[e].alwaysSummary}function ce(e){return e===T.MILESTONE}function Ae(e){return Hr(e)&&Do[e].promotesToProjectOnFirstChild}var _o=T.PROJECT,fr=T.TASK;function Yr(e,t){return t===0?T.MILESTONE:e===0&&t>0?T.TASK:null}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"},xt={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 $s(e,t){return()=>t()===e}var ko=typeof window>"u",zp=!ko&&typeof MessageChannel<"u";function dt(){return zp?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 Ni(e,t){return performance.now()-e<Es.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await dt(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function pr(e){return ko||await dt(),e()?{aborted:!1}:{aborted:!0}}function bi(e,t){let{inDegree:r,successors:i}=Jp(e,t),n=Xp(r),o=Zp(n,r,i),a=o.length<e.length,s=a?Qp(e,o):[],c=[...o].reverse();return{ordered:o,reversed:c,hasCycles:a,cycleNodes:s}}function Jp(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 Xp(e){let t=new Bt;for(let[r,i]of e)i===0&&t.enqueue(r);return t}function Zp(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 Qp(e,t){let r=new Set(t);return e.filter(i=>!r.has(i))}var wi=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=bi(t,r),this.cached)}};function qs(e,t){let r=[];for(let i of e)t.has(i)&&r.push(i);return r}function Fi(e,t){let r=t.getActivity(e);return r?zt(r.type,t.getChildren(e).length>0):!1}function xi(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 Ui(e,t,r){let i=Fi(e,r);return Fi(t,r)&&xi(e,t,r)||i&&xi(t,e,r)}function Xs(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 ty(e){let t=new Map;for(let r of e)zs(t,String(r.source),r),zs(t,String(r.target),r);return t}function zs(e,t,r){let i=e.get(t);if(i){i.push(r);return}e.set(t,[r])}function ey(e,t,r,i){if(e.length<=1)return e;let n=new Set(e.map(String)),o=[];for(let a of e)ry(a,n,t,r,i)||o.push(a);return o.length>0?o:e}function ry(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(iy(c,o,a,t,r,n))return!0;return!1}function iy(e,t,r,i,n,o){if(ny(e)||!(o?String(e.source)===t:String(e.target)===t))return!1;let s=oy(e,t);if(!i.has(String(s)))return!1;let c=n.getActivity(s);return!!(c?.autoScheduling!==!1&&c&&ay(e,r,c))}function ny(e){return e.source===e.target}function oy(e,t){return String(e.source)===t?e.target:e.source}function ay(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 Bi(e,t){let r=[],i=ty(e),n=0;for(let o of e){let a=Fi(o.source,t),s=Fi(o.target,t);if(sy(o,a,s,t))continue;if(!a&&!s){r.push(o);continue}let c=Js(o.source,a,t,i,!0),l=Js(o.target,s,t,i,!1);n=yy(r,c,l,o,t,n,i)}return r}function sy(e,t,r,i){return r&&xi(e.source,e.target,i)||t&&xi(e.target,e.source,i)}function Js(e,t,r,i,n){return t?ey(Xs(e,r),r,i,n):[e]}function cy(e,t,r){let i=Xs(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 Mi(e,t){return cy(e,t,r=>{let i=t.getActivity(r);return i?{startDate:i.startDate,endDate:i.endDate}:null})}function ly(e,t,r){return e?t?r.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function dy(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 uy(e,t){let r=String(e);return(t.get(r)??[]).some(n=>String(n.target)===r)}function fy(e,t,r,i,n){if(uy(e,n))return 0;let o=i.getActivity(e);return!t||!o||!r?0:i.calculateDuration({startDate:t,endDate:o.startDate,task:r})}function py(e,t){let r=t.getActivity(e.source),i=t.getActivity(e.target),n=Mi(e.source,t),o=Mi(e.target,t),a=e.type===W.START_TO_START||e.type===W.START_TO_FINISH,s=e.type===W.FINISH_TO_FINISH||e.type===W.START_TO_FINISH;return{source:r,sourceBounds:n,targetStart:o?.startDate??i?.startDate,userLag:e.lag??0,sourceEndpointIsStart:a,targetLag:s?-ly(i,o,t):0,summarySourceId:e.type===W.START_TO_START&&n?e.source:void 0,finishAnchoredSummaryTargetId:s&&o?e.target:void 0}}function yy(e,t,r,i,n,o,a){let s=py(i,n),{source:c,sourceBounds:l,targetStart:d,userLag:u}=s,{sourceEndpointIsStart:f,targetLag:p,summarySourceId:y,finishAnchoredSummaryTargetId:g}=s,A=o;for(let k of t){let _=f?dy(k,c,l,n):0;for(let L of r){if(String(k)===String(L))continue;let m=fy(L,d,c,n,a);e.push(hy(i,k,L,A,_,p,u+m,y,g??(m!==0&&p===0?i.target:void 0))),A+=1}}return A}function hy(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 Hi=class{invalidate(){}get(t,r){return Bi(t,r)}};function my(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 Iy(e,t,r){let i=new Set,n=new Map,o=new Bt;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 Zs(e,t){let r=new Map;for(let a of t)r.set(a.id,a);let i=my(t),n=Iy(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 Qs=0,Gr=100;function je(e){return e===0}function tc(e,t,r){let i=r.type===W.FINISH_TO_START,n=r.type===W.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 W.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:o,isFS:i,isFF:n,isZeroDurationCase:!1};case W.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:o,isFS:i,isFF:n,isZeroDurationCase:!1};case W.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:o,isFS:i,isFF:n,isZeroDurationCase:!1};case W.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 gy(e,t,r){if(e._summarySourceId===void 0)return null;let i=r.getActivity(e._summarySourceId);if(!i)return null;let n=Mi(e._summarySourceId,r);return n?-r.calculateDuration({startDate:n.startDate,endDate:t.endDate,task:i}):null}function Ay(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 ec(e,t,r,i){let{sourceLag:n,targetLag:o,trueLag:a,isFS:s,isFF:c}=tc(e,t,r),l=gy(r,e,i)??n,d=l+o+a;if(!(t.durationHours===0?d!==0:l!==0||o!==0||a!==0))return Ay(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 rc(e,t,r,i){let{sourceLag:n,targetLag:o,trueLag:a}=tc(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 ic(e,t,r){for(let i of e){let n=t.getActivity(i);if(!n)continue;let o=n.constraintType;if(!o||o===v.ASAP||o===v.ALAP)continue;let a=hs(n,t);!a.earliestStart&&!a.latestStart&&!a.earliestEnd&&!a.latestEnd||r.set(i,{activityId:i,startDate:n.startDate,endDate:n.endDate,drivingLinkId:null,kind:v.ASAP,conflict:!1,earliestStart:a.earliestStart,latestStart:a.latestStart,earliestEnd:a.earliestEnd,latestEnd:a.latestEnd})}}function Wi(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=uo(e.startDate,i):ms(n,i)?o=n:o=uo(n,i),t.startDate=o,t.endDate=r.calculateEndDate({startDate:o,durationHours:e.durationHours,task:e})}function nc(e,t){if(!e||!t)return new Date;let{constraintType:r,constraintDate:i}=e;if(!r||!i)return t;switch(r){case v.MSO:case v.MFO:return new Date(i);case v.SNET:case v.FNET:return i>t?new Date(i):t;case v.SNLT:case v.FNLT:return i<t?new Date(i):t;default:return t}}function vy(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function oc(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&&vy(e,r)}async function ac(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 Ni(d,n);if(f.aborted)return o;d=f.newSliceStart;let p=r.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||Cy(p,r))continue;let y=a.get(String(u))??[],g=null,A=null,k=!1;for(let w of y){let E=r.getActivity(w.source);if(!E)continue;let S=s(w.source),O=S.startDate.getTime()!==E.startDate.getTime()||S.endDate.getTime()!==E.endDate.getTime(),V={...E,startDate:S.startDate,endDate:S.endDate},$=oc(V,c,l),et={...V,startDate:$.startDate,endDate:$.endDate},ct=Ro(w.source,c,l)?{...w,lag:0}:w,lt=ec(et,p,ct,r);(!g||lt.successorStart>g)&&(g=lt.successorStart,A=String(w.id),k=w._summaryTargetId!==void 0&&!O&&(w._targetLag===0||i.preventSummaryTargetPullback===!0))}g!==null&&k&&g<p.startDate&&(g=new Date(p.startDate));let L=o.get(u),m=L?{...L}:{activityId:u,startDate:p.startDate,endDate:p.endDate,drivingLinkId:null,kind:v.ASAP,conflict:!1},b=m.earliestStart||m.latestStart||m.earliestEnd||m.latestEnd;if(!(!g&&!b)){if(g){let w=g;p.type===T.MILESTONE&&(w=nc(p,g)),m.drivingLinkId=A,m.startDate=w,m.endDate=r.calculateEndDate({startDate:w,durationHours:p.durationHours,task:p}),m.earliestSchedulingStart=w,m.earliestSchedulingEnd=m.endDate}else p.constraintType===v.MSO?m.earliestStart&&(m.startDate=m.earliestStart,m.endDate=m.earliestEnd??r.calculateEndDate({startDate:m.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===v.MFO&&m.latestStart&&(m.startDate=m.latestStart,m.endDate=m.latestEnd??r.calculateEndDate({startDate:m.latestStart,durationHours:p.durationHours,task:p}));Wi(p,m,r),o.set(u,m)}}return o}function Cy(e,t){return zt(e.type,t.getChildren(e.id).length>0)}async function sc(e,t,r,i,n,o){let a=new Map(r),s=i.getAllActivities(),c=s.length,l=[];for(let A of s)A.constraintType===v.ALAP&&l.push(A.id);if(l.length===0)return a;let d=new Map,u=new Map;for(let A of t){let k=String(A.source);d.has(k)||d.set(k,[]),d.get(k).push(A);let _=String(A.target);u.has(_)||u.set(_,[]),u.get(_).push(A)}let f=A=>{let k=a.get(A);if(k)return{startDate:k.startDate,endDate:k.endDate};let _=i.getActivity(A);return _?{startDate:_.startDate,endDate:_.endDate}:{startDate:new Date,endDate:new Date}},p=A=>!A.parentId||B(A.parentId)?i.getProjectEnd():f(A.parentId).endDate,y=(A,k)=>{let _=A,L=0;for(;_&&!B(_)&&L++<c+1;){if(String(_)===String(k))return!0;let m=i.getActivity(_);if(!m||!m.parentId)break;_=m.parentId}return!1},g=performance.now();for(let A of e){let k=await Ni(g,o);if(k.aborted)return a;g=k.newSliceStart;let _=i.getActivity(A);if(!_||_.constraintType!==v.ALAP||!_.autoScheduling||_.progress===100||zt(_.type,i.getChildren(A).length>0))continue;let L=p(_),m=L,b=null,w=null,E=!1,S=d.get(String(A))??[];for(let Vt of S){if((Vt.lag??0)<0)continue;let sr=i.getActivity(Vt.target);if(!sr||sr.autoScheduling===!1)continue;let ps=f(Vt.target),Jf={...sr,startDate:ps.startDate,endDate:ps.endDate},hi=rc(Jf,_,Vt,i);(m===null||hi<m)&&(m=hi),(b===null||hi<b)&&(b=hi,w=Vt.type,E=_.parentId&&!B(_.parentId)?y(Vt.target,_.parentId):!1)}if(b!==null)if(E||L===null)m=b;else{let Vt=f(A).endDate,sr=Vt.getTime()>L.getTime()?Vt:L;m=b<sr?b:sr}else{if(L===null||m===null)continue;m>L&&(m=L)}if(m===null)continue;let V=(u.get(String(A))??[]).some(Vt=>Vt.type===W.FINISH_TO_START||Vt.type===W.FINISH_TO_FINISH),$=new Date(Date.UTC(m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate())),et=()=>i.getClosestWorkTime({date:$,dir:"past",task:_}),ct=i.getClosestWorkTime({date:m,dir:"future",task:_}).getTime()===m.getTime(),lt;_.durationHours===0&&b===null?lt=V&&ct?et():i.getClosestWorkTime({date:m,dir:"past",task:_}):_.durationHours===0?b!==null&&w===W.FINISH_TO_START&&m.getTime()===b.getTime()?lt=m:V?lt=et():lt=i.getClosestWorkTime({date:m,dir:"future",task:_}):lt=i.getClosestWorkTime({date:m,dir:"future",task:_});let pt=i.calculateEndDate({startDate:lt,durationHours:-_.durationHours,task:_}),re=a.get(A),Ft=re?{...re}:{activityId:A,startDate:pt,endDate:lt,drivingLinkId:null,kind:v.ALAP,conflict:!1};Ft.startDate=pt,Ft.endDate=lt,Ft.drivingLinkId=null,Ft.kind=v.ALAP;let ar=Ft.earliestSchedulingStart??null;Ft.earliestSchedulingStart=null,Ft.earliestSchedulingEnd=null;let co=ar!==null&&ar.getTime()>pt.getTime()?ar:pt;Ft.latestSchedulingStart=co,Ft.latestSchedulingEnd=co===pt?lt:i.calculateEndDate({startDate:co,durationHours:_.durationHours,task:_}),Wi(_,Ft,i),a.set(A,Ft)}return a}var yr={warn(){},error(){}};var Sy=864e5;function ie(e){if(e.type===T.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)/Sy)+1}function $r(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=ie(n),e.updateActivity(r))}})}function Po(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 Ty(n,i,r)}function qr(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 Bt;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 Ty(e,t,r){if(t===r)return!0;let i=new Set([t]),n=new Bt;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 Vi(e){let t=Ey(e);for(let r of t.adjacency.keys())t.records.has(r)||Dy(r,t);return t.components}function Ey(e){let t=new Map,r=new Set;for(let i of e){let n=String(i.source),o=String(i.target),a=cc(t,n);if(cc(t,o),n===o){r.add(n);continue}a.push(o)}return{adjacency:t,selfLooped:r,records:new Map,componentStack:[],nextIndex:0,components:[]}}function cc(e,t){let r=e.get(t);if(r)return r;let i=[];return e.set(t,i),i}function Dy(e,t){let r=[];for(r.push({node:e,record:lc(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;_y(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&&ky(i.node,t)}}function _y(e,t,r,i){let n=i.records.get(t);if(!n){r.push({node:t,record:lc(t,i),neighborCursor:0});return}n.onStack&&n.visitIndex<e.record.lowLink&&(e.record.lowLink=n.visitIndex)}function lc(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 ky(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 zr(e,t,r){let i=r?new Lo(e,r):e;return Bi([...t],i)}var Lo=class{constructor(t,r){this.base=t;for(let[i,n]of r.reparented){let o=String(i),a=n===null||B(n)?null:n,s=t.getActivity(i)?.parentId??null,c=s===null||B(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||B(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 ve(e){let{port:t,proposedPort:r,currentLinks:i,proposedLinks:n,proposal:o}=e,a=zr(r??t,n,o);if(!qr(a))return{ok:!0};let s=zr(t,i),c=dc(s),d=[...dc(a)].filter(u=>!c.has(u));return d.length===0?{ok:!0}:{ok:!1,newlyCyclicActivityIds:d}}function dc(e){let t=new Set;for(let r of Vi(e))for(let i of r)t.add(i);return t}function Ki(e,t,r){return r.getChildren(e).length>0||r.getChildren(t).length>0}function Ce(e,t){switch(e.kind){case St.CREATE:return Ry(e,t);case St.UPDATE:return Py(e,t.port,t.rejectParentLinkMutations??!1);case St.DELETE:return Ly(e,t)}}function Gi(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=Yi(l);i.has(d)||i.set(d,l.id),n.push({source:l.source,target:l.target})}let o=qr(n),a=null;for(let{operation:l,linkId:d}of e){if(String(l.source)===String(l.target)){a={applied:!1,rejected:st.SELF_LINK};break}if(!t.port.getActivity(l.source)||!t.port.getActivity(l.target)){a={applied:!1,rejected:st.ACTIVITY_MISSING};break}if(t.rejectParentLinkMutations&&Ki(l.source,l.target,t.port)){a={applied:!1,rejected:st.HIERARCHY_LINK};break}if(Ui(l.source,l.target,t.port)){a={applied:!1,rejected:st.HIERARCHY_LINK};break}let u=Yi(l),f=i.get(u);if(f!==void 0){a={applied:!1,rejected:st.DUPLICATE,linkId:f};break}if(i.set(u,d),o&&Po(n,{source:l.source,target:l.target}))return{applied:!1,rejected:st.CYCLE};n.push({source:l.source,target:l.target})}if(!o&&qr(n))return{applied:!1,rejected:st.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(!ve({port:t.port,currentLinks:r,proposedLinks:s}).ok)return{applied:!1,rejected:st.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 Yi(e){return JSON.stringify([String(e.source),String(e.target),e.type])}function Ry(e,t){let{port:r}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:st.SELF_LINK};let i=r.getActivity(e.source),n=r.getActivity(e.target);if(!i||!n)return{applied:!1,rejected:st.ACTIVITY_MISSING};if(t.rejectParentLinkMutations&&Ki(e.source,e.target,r))return{applied:!1,rejected:st.HIERARCHY_LINK};if(Ui(e.source,e.target,r))return{applied:!1,rejected:st.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:st.DUPLICATE,linkId:d.id};let a=o.map(d=>({source:d.source,target:d.target}));if(Po(a,{source:e.source,target:e.target}))return{applied:!1,rejected:st.CYCLE};let s=(t.newLinkId??Oy)(),c={id:s,source:e.source,target:e.target,type:e.type,lag:e.lag,freeSlackHours:null,isCritical:!1};return ve({port:r,currentLinks:o,proposedLinks:[...o,c]}).ok?(r.addLink(c),{applied:!0,linkId:s}):{applied:!1,rejected:st.CYCLE}}function Py(e,t,r){let i=t.getLink(e.linkId);if(!i)return{applied:!1,rejected:st.LINK_MISSING};let n={...i,source:e.source??i.source,target:e.target??i.target,type:e.type??i.type,lag:e.lag??i.lag};if(String(n.source)===String(n.target))return{applied:!1,rejected:st.SELF_LINK};if(!t.getActivity(n.source)||!t.getActivity(n.target))return{applied:!1,rejected:st.ACTIVITY_MISSING};if(r&&(Ki(i.source,i.target,t)||Ki(n.source,n.target,t)))return{applied:!1,rejected:st.HIERARCHY_LINK};if(Ui(n.source,n.target,t))return{applied:!1,rejected:st.HIERARCHY_LINK};let o=t.getAllLinks(),a=o.find(l=>String(l.id)!==String(e.linkId)&&Yi(l)===Yi(n));if(a)return{applied:!1,rejected:st.DUPLICATE,linkId:a.id};let s=o.map(l=>String(l.id)===String(e.linkId)?n:l);return ve({port:t,currentLinks:o,proposedLinks:s}).ok?((String(i.source)!==String(n.source)||String(i.target)!==String(n.target))&&t.setLinkEndpoints(e.linkId,n.source,n.target),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:st.CYCLE}}function Ly(e,t){let{port:r}=t;return r.getLink(e.linkId)?(r.removeLink(e.linkId),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:st.LINK_MISSING}}var ji=null;function Oy(){return ji===null&&(ji=Date.now()),ji+=1,String(ji)}var Tt={FINISH_TO_START:"fs",START_TO_START:"ss",FINISH_TO_FINISH:"ff",START_TO_FINISH:"sf"},$i={[W.FINISH_TO_START]:Tt.FINISH_TO_START,[W.START_TO_START]:Tt.START_TO_START,[W.FINISH_TO_FINISH]:Tt.FINISH_TO_FINISH,[W.START_TO_FINISH]:Tt.START_TO_FINISH},Ke={[Tt.FINISH_TO_START]:W.FINISH_TO_START,[Tt.START_TO_START]:W.START_TO_START,[Tt.FINISH_TO_FINISH]:W.FINISH_TO_FINISH,[Tt.START_TO_FINISH]:W.START_TO_FINISH},uc=Tt.FINISH_TO_START;function fc(e){if(e in Ke)return Ke[e]}var pc=";",Se={DAY:"d",WEEK:"w",WEEK_DHTMLX:"wk",MONTH:"m",MONTH_DHTMLX:"mon",YEAR:"y"},yc=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)(weeks?|wk|w|months?|mon|m|days?|d|years?|y)?)?$/i;var Ny=5,qi=30,Oo=365,by={[Se.DAY]:1,day:1,days:1,[Se.MONTH]:qi,[Se.MONTH_DHTMLX]:qi,month:qi,months:qi,[Se.YEAR]:Oo,year:Oo,years:Oo},wy=new Set([Se.WEEK,Se.WEEK_DHTMLX,"week","weeks"]);function zi(e,t={}){let r=[],i=[],n=t.daysPerWeek!==void 0&&Number.isFinite(t.daysPerWeek)&&t.daysPerWeek>0?t.daysPerWeek:Ny,o=e.replace(/\s+/g,"");if(o.length===0)return{specs:r,errors:i};for(let a of o.split(pc)){if(a.length===0)continue;let s=Fy(a,n);s?r.push(s):i.push(a)}return{specs:r,errors:i}}function Fy(e,t){let r=e.toLowerCase(),i=yc.exec(r);if(!i)return null;let[,n,o,a,s,c]=i,l=o?Ke[o]:Ke[uc],d=0;if(s!==void 0){let u=Number(s);if(Number.isNaN(u))return null;let f=c!==void 0&&wy.has(c)?t:by[c??Se.DAY],p=u*f;d=a==="-"?-p:p}return{correlativeId:n,type:l,lag:d}}function Xi(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=Ji(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(Ji(c.source,c.type),c);let s=[];for(let[c,l]of a)o.has(c)||s.push({kind:St.DELETE,linkId:l.id});for(let[c,l]of o){let d=a.get(c);d&&d.lag!==l.lag&&s.push({kind:St.UPDATE,linkId:d.id,lag:l.lag})}for(let[c,l]of o)a.has(c)||s.push({kind:St.CREATE,source:l.source,target:t,type:l.type,lag:l.lag});return{operations:s,unresolved:n}}function Ji(e,t){return`${String(e)}::${t}`}function Zi(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=Ji(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(Ji(c.target,c.type),c);let s=[];for(let[c,l]of a)o.has(c)||s.push({kind:St.DELETE,linkId:l.id});for(let[c,l]of o){let d=a.get(c);d&&d.lag!==l.lag&&s.push({kind:St.UPDATE,linkId:d.id,lag:l.lag})}for(let[c,l]of o)a.has(c)||s.push({kind:St.CREATE,source:t,target:l.target,type:l.type,lag:l.lag});return{operations:s,unresolved:n}}function Qi(e){let t=Math.sign(e)*Math.round(Math.abs(e));return Object.is(t,-0)?0:t}function Kt(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var hc={rawInputToConstraintDate(e,t){let r=new Date(e);return r.setUTCHours(0,0,0,0),r.getTime()===e.getTime()?t.getClosestWorkTime({direction:K.FUTURE,date:e,unit:ft.HOUR}):t.isWorkTime(e,ft.HOUR)?e:r},computeLagBetweenTasks(e,t,r){return r.calculateDuration(e,t)}};function No(e,t,r){switch(r){case W.FINISH_TO_START:return{sourceDate:e.endDate,targetDate:t.startDate};case W.START_TO_START:return{sourceDate:e.startDate,targetDate:t.startDate};case W.FINISH_TO_FINISH:return{sourceDate:e.endDate,targetDate:t.endDate};case W.START_TO_FINISH:return{sourceDate:e.startDate,targetDate:t.endDate}}}var bo=hc;var hr=class{adapter;reporter;currentCalculationId=0;topoCache=new wi;expandedLinksCache=new Hi;constructor(t,r=yr){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=$s(r,()=>this.currentCalculationId),n={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{Uy(this.adapter);let o=Te("schedule.total"),a=Te("schedule.expandParentLinks"),s=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(s,this.adapter);le(a);let l=c;if((await pr(i)).aborted)return{...n,cancelled:!0};let d=Te("schedule.scoping"),u=this.adapter.getAllIds(),f=By(t,l,this.adapter),p=f.links,y=f.idSet;le(d);let g=Te("schedule.topologicalSort"),A=Wy(this.topoCache,u,l,y);if(le(g),A.hasCycles)return le(o),{...n,cycles:[A.cycleNodes]};if((await pr(i)).aborted)return{...n,cancelled:!0};let k=Te("schedule.processConstraints"),_=new Map;if(ic(A.ordered,this.adapter,_),le(k),(await pr(i)).aborted)return{...n,cancelled:!0};let L=Te("schedule.asapPass"),m=await ac(A.ordered,p,this.adapter,t,i,_);if(le(L),(await pr(i)).aborted)return{...n,cancelled:!0};let b=Te("schedule.alapPass"),w=await sc(A.reversed,p,m,this.adapter,t,i);if(le(b),(await pr(i)).aborted)return{...n,cancelled:!0};let E=Te("schedule.diff"),S=[];for(let[O,V]of w){let $=this.adapter.getActivity(O);if(!$)continue;let et=$.startDate.getTime()!==V.startDate.getTime(),ct=$.endDate.getTime()!==V.endDate.getTime();(et||ct)&&S.push(O)}return le(E),le(o),{plans:w,updatedIds:S,cycles:[],cancelled:!1}}catch(o){throw this.reporter.error("[AutoScheduler] Error during scheduling",o),o}}},xy=!1;function My(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:xy}function Te(e){return{name:e,startedAt:performance.now()}}function Uy(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function le(e){if(!My())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function By(e,t,r){let i=e.triggerId;if(i==null)return{idSet:null,links:t};let n=Zs(i,t);return Hy(n,t,r)}function Hy(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===v.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 Wy(e,t,r,i){let n=e.get(t,r);if(n.hasCycles){let a=i?Array.from(i):t;return bi(a,r)}if(!i)return n;let o=qs(n.ordered,i);return{ordered:o,reversed:[...o].reverse(),hasCycles:!1,cycleNodes:[]}}function mc(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===v.ALAP||ce(i.type)&&(s.type===W.START_TO_FINISH||s.type===W.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=No(c,n,s.type),f=bo.computeLagBetweenTasks(d,u,o);f!==s.lag&&t.setLinkField(s.id,xt.LAG,f)}}function Ic(e,t){let r=t.getActivity(e);r&&ce(r.type)&&(r.durationHours=0)}function tn(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 gc(e){return Number(e.toFixed(2))}function Jr(e){for(let t of Vy(e))vc(t,e)}function Ac(e,t){for(let r of e)vc(r,t)}function Vy(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,jy(i,e));return[...t].sort((i,n)=>(r.get(n)??0)-(r.get(i)??0))}function jy(e,t){let r=0,i=e;for(;i&&i!=="0"&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function vc(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)})}wo(e,i,t)}function wo(e,t,r){let i=r.getActivity(e);if(!i)return;let n=tn(t);if(n===null){let o=r.getProgressFallback(e);o!==null&&r.setActivityField(e,D.PROGRESS,o);return}r.getProgressFallback(e)===null&&r.setProgressFallback(e,Number(i.progress??0)),r.setActivityField(e,D.PROGRESS,gc(n))}function Cc(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 Mt(e,t){return(Number(e)||0)*(Number(t)||0)/100}var Xr={SKIP:"skip",FREEZE_WITHOUT_CONTRIBUTION:"freeze-when-no-contribution"};async function mr(e,t,r=!0,i={}){let n=t?Zr(e,t):zy(e),o=r?i.progressMode??Xr.FREEZE_WITHOUT_CONTRIBUTION:Xr.SKIP;await Ky(n,e,o,{recomputeRealWork:i.recomputeRealWork??!1})}function en(e,t){Sc(e,t,Xr.SKIP)}async function Ky(e,t,r,i={recomputeRealWork:!1}){let o=0;for(let a of e)Sc(a,t,r,i.recomputeRealWork),o+=1,o%200===0&&await dt()}function Zr(e,t){let r=new Set,i=new Map;for(let a of t)Yy(a,e,r,i);if(r.size===0)return[];let n=Array.from(r),o=Gy(n,i);return Tc(n,o)}function Yy(e,t,r,i){let n=t.getParentId(e);for(;n&&!B(n);){if(r.has(n))return;r.add(n);let o=t.getParentId(n);i.set(n,o),n=o}}function Gy(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&&!B(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 $y(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+=qy(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 Sc(e,t,r=Xr.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=$y(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!==Xr.SKIP&&wo(e,a.weightedChildren,t),i&&t.setActivityField(e,"realWorkHours",a.realWorkSum)}function qy(e,t){return t?Number(e.realWorkHours)||0:Mt(e.workHours,e.progress)}function zy(e){let t=Jy(e),r=Xy(t,e);return Tc(t,r)}function Jy(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function Xy(e,t){let r=new Map;for(let i of e)r.set(i,Zy(i,t));return r}function Zy(e,t){let r=0,i=e;for(;i&&!B(i)&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function Tc(e,t){return[...e].sort((r,i)=>(t.get(i)??0)-(t.get(r)??0))}var Ec={updateActivityDuration:Ic,updateTaskTiming:th("updateTaskTiming"),adjustLinkLagOnTaskMove:mc,recordLastStartDate:Qy};function Qy(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function Ee(e,t,r,i){for(let n of t){let o=n in Ec?Ec[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 th(e){return()=>{console.debug(`[replay post-processors] ${e}: not yet ported to adapter \u2014 no-op.`)}}function Y(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 rt(){return{valid:!0}}function It(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function Z(){return{allowed:!0}}function ot(e,t){return t!==void 0?{allowed:!1,reason:e,alertKey:t}:{allowed:!1,reason:e}}function tt(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 yt={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 Dc={targetField:"name",canEdit(){return Z()},parseInput(e){return typeof e!="string"?J("not_a_string"):Y(e)},validate(){return rt()},transform(e,t){return tt({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:yt.NAME_ENTRY};var _c={targetField:"description",canEdit(){return Z()},parseInput(e){return typeof e!="string"?J("not_a_string"):Y(e.trim())},validate(){return rt()},transform(e,t){return tt({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:yt.DESCRIPTION_ENTRY};function Jt(e){return e.constraintType??v.ASAP}var rn=100;function De(e){return e.progress>=rn}function gt(e,t){return zt(e.type,t.hasChildren(e.id))}function kc(e){return e.progress>0}function Rc(e){return e.hasLookaheadTasks}function Ye(e,t){return Math.round(Math.ceil(e*t*60)/60)}var Ir=e=>({endDate:e});var nn="UTC";function _e(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 on(e,t){if(!t||t===nn){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 eh(e,t){let r=_e(t,nn);for(;!e.isWorkTime(r,ft.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=_e(r,nn);return r}function Fo(e,t){return e.getClosestWorkTime({direction:K.FUTURE,date:t,unit:ft.HOUR})}function xo(e,t){let r=eh(e,t),i=new Date(r);return i.setUTCDate(i.getUTCDate()+1),i.setUTCHours(0,0,0,0),e.getClosestWorkTime({direction:K.PAST,date:i,unit:ft.HOUR})}var Qr=new Set([v.SNET,v.SNLT,v.MSO]),Mo=new Set([v.FNET,v.FNLT,v.MFO]),ke=new Set([v.ASAP,v.ALAP]),an=v.SNET;function de(e,t,r){let i=_e(e,nn);if(!Qr.has(r)&&!Mo.has(r))return i;let n=Qr.has(r)?Fo(t,i):xo(t,i),o=new Date(i);return o.setUTCHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),o}var Re=()=>({constraintType:an});var Ge=e=>({constraintDate:e}),Pc=e=>({constraintDate:e});var Lc={UPDATE_ACTIVITY_DURATION:"updateActivityDuration",UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var Oc={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"},ti={COMPLETED:"completed",SUMMARY:"summary",HAS_PROGRESS:"has_progress",HAS_LOOKAHEAD_TASKS:"has_lookahead_tasks",SIR_START_AFTER_PROGRESS:"sir_start_after_progress"},Nc={CANT_EDIT_COMPLETED:"cant_edit_completed_activity",SUMMARY_COLUMN_VALUE:"summary_column_value",CANT_EDIT_WITH_PROGRESS:"cant_edit_activity_with_progress",SIR_CANT_MOVE_START_AFTER_PROGRESS:"sir_cant_move_start_after_progress",CANT_EDIT_WITH_TASK:"cant_edit_actvity_with_task"};function gr(e,t,r){return gi(e,t,r)}function Ar(e,t,r){return Ai(e,t,r)}var wc={targetField:"durationHours",canEdit(e,t){return De(e)?ot("completed","cant_edit_completed_activity"):gt(e,t)?ot("summary","summary_column_value"):Z()},parseInput(e,t,r){let i=parseFloat(String(e));return Number.isFinite(i)?Y(Ye(i,r.hoursPerDay)):J("not_a_number")},validate(e,t,r){return bc(r)?It(Oc.NEGATIVE_DURATION):rh(t,r)?It("unchanged"):rt()},transform(e,t,r){if(bc(t))return tt({},{autoSchedule:!1,postProcessors:[]});let i=ih(e,t,r),n=nh(e,t,r,i.violated);return{...tt(n,{autoSchedule:!0,postProcessors:[Lc.RECORD_LAST_START_DATE]}),...i.violated?{constraintWarning:Ar(i.constraintType,i.constraintDate,Fc(e,t,r)??void 0)}:{}}},trackEvent:yt.DURATION_ENTRY};function bc(e){return Math.sign(e)===-1}function rh(e,t){return e===t}function ih(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return{violated:!1};let n=e.constraintType;if(n!==v.FNET&&n!==v.FNLT&&n!==v.MFO)return{violated:!1};let o=i.calculateEndDate(e.startDate,t);return gr(n,e.constraintDate,o)}function nh(e,t,r,i=!1){let n={};i&&Object.assign(n,Re(),Ge(e.startDate));let o=Yr(e.durationHours,t);o&&(n.type=o),n.durationHours=t;let a=Fc(e,t,r);return a&&Object.assign(n,Ir(a)),n}function Fc(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateEndDate(e.startDate,t):null}var vr=e=>({realWorkHours:e});var oh=0,ah=rn,sn={targetField:"progress",canEdit(e,t){return gt(e,t)?ot("summary","summary_column_value"):Rc(e)?ot("has_lookahead_tasks","cant_edit_actvity_with_task"):Z()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?J("not_a_number"):Y(t)},validate(e,t,r){return sh(r)?It("out_of_range"):rt()},transform(e,t,r){let i=je(t),n=e.progress!==t&&i,o=ch(t),a=uh(e,t,r.hierarchy),s={progress:t,autoScheduling:i,...vr(a.get(e.id)??0)},c=o?lh(e,t,i,r.hierarchy,a):[],l=o?ph(e,t,r.hierarchy):[],d=c.length+l.length>0?[...c,...l]:void 0,u=[],f=o?hh(e,t):void 0;return tt(s,{autoSchedule:n,postProcessors:u,cascadeMutations:d,trackingEvents:f})},trackEvent:yt.PROGRESS_ENTRY};function sh(e){return e<oh||e>ah}function ch(e){return e===rn||je(e)}function lh(e,t,r,i,n){return i.getDescendantIds(e.id).map(a=>({activityId:a,fields:dh(t,r,n.get(a)??0)}))}function dh(e,t,r){return{progress:e,autoScheduling:t,...vr(r)}}function uh(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):Mt(c.workHours,t);i.set(c.id,l),s+=l}return s},o=r.hasChildren(e.id)?n(e.id):Mt(e.workHours,t);return i.set(e.id,o),i}function fh(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 ph(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=[...fh(e,r),...r.getAncestorIds(e.id)],o=[];for(let a of n){let s=yh(a,i,r);s!==null&&(i.set(a,s),o.push({activityId:a,fields:{progress:s}}))}return o}function yh(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=tn(i);return n===null?null:Number(n.toFixed(2))}function hh(e,t){return[{name:yt.PROGRESS_UPDATE_RADIO_BUTTON,properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var xc={targetField:"cost",canEdit(e,t){return gt(e,t)?ot("summary","summary_column_value"):Z()},parseInput(e){if(String(e).trim()==="")return Y(0);let t=parseFloat(String(e));return Number.isNaN(t)?J("not_a_number"):Y(t)},validate(){return rt()},transform(e,t,r){let i=mh(e,t,r.hierarchy);return tt({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:yt.COST_BUDGETED_ENTRY};function mh(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 Mc={targetField:"usedCost",canEdit(e,t){return gt(e,t)?ot("summary","summary_column_value"):Z()},parseInput(e){if(String(e).trim()==="")return Y(0);let t=parseFloat(String(e));return Number.isNaN(t)?J("not_a_number"):Y(t)},validate(){return rt()},transform(e,t,r){let i=Ih(e,t,r.hierarchy);return tt({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:yt.COST_SPENT_ENTRY};function Ih(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 Uc={targetField:"workHours",canEdit(e,t){return gt(e,t)?ot("summary","summary_column_value"):Z()},parseInput(e){if(String(e).trim()==="")return Y(0,e);let t=parseFloat(String(e));return Number.isNaN(t)?J("not_a_number"):Y(t)},validate(){return rt()},transform(e,t,r,i){let n=Bc(t,e.progress),o=String(i).trim()===""?[]:gh(e,t,n,r.hierarchy);return tt({workHours:t,...vr(n)},{autoSchedule:!1,postProcessors:[],cascadeMutations:o})},trackEvent:yt.LABOR_HOURS_BUDGETED_ENTRY};function Bc(e,t){return Mt(e,t)}function gh(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??Bc(d.workHours,d.progress);c+=u,l+=f}n.set(s,c),o.set(s,l),a.push({activityId:s,fields:{workHours:c,...vr(l)}})}return a}function ei(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function Uo(e,t){return e.getTime()<t.getTime()}function $e(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var cn=e=>({durationHours:e});var Ah="sir-apply",Hc={targetField:"startDate",canEdit(e,t,r){return gt(e,t)?ot("summary","summary_column_value"):kc(e)?r?.eventSource!==Ah?ot("has_progress","cant_edit_activity_with_progress"):De(e)?ot("completed","cant_edit_completed_activity"):$e(r.newValue)?ei(e.startDate,r.newValue)?Z():r.newValue.getTime()>e.startDate.getTime()?ot("sir_start_after_progress","sir_cant_move_start_after_progress"):Z():Z():Z()},parseInput(e,t,r){return $e(e)?Y(_e(e,"UTC")):J("invalid_date")},validate(e,t,r,i){if(ei(t,r))return It("unchanged");let n=vh(e,r,i);return n||rt()},transform(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)throw new Error("startDatePipeline: no calendar resolved (integrity)");let n=Fo(i,t),o=e.type===T.MILESTONE,a=o?n:i.calculateEndDate(n,e.durationHours),s=n;return{...tt({startDate:n,...Ir(a),...o?cn(0):{},...Re(),...Ge(s)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:Ch(e,n,i)}},trackEvent:yt.START_DATE_ENTRY};function vh(e,t,r){let i=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!i)return null;let n=_e(i,"UTC");return t.getTime()<n.getTime()?It("before_parent_start"):null}function Ch(e,t,r){let i=r.calculateEndDate(t,e.durationHours),n=Fe(Jt(e),t,i),o=gr(Jt(e),e.constraintDate,n);if(o.violated)return Ar(o.constraintType,o.constraintDate,n)}var Sh=99.999,Vc={targetField:"endDate",canEdit(e,t){return gt(e,t)?ot("summary","summary_column_value"):Th(e)?ot("completed","cant_edit_completed_activity"):Z()},parseInput(e,t,r){if(!$e(e))return J("invalid_date");let i=_e(e,"UTC"),n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(i,ft.DAY)?Y(xo(n,i)):Y(n.getClosestWorkTime({direction:"past",date:i,unit:ft.HOUR})):Y(i)},validate(e,t,r,i){if(ei(e.endDate,r))return It("unchanged");if(Eh(r,e))return It("before_date_origin");if(Dh(r,e))return It("before_start_date");let n=_h(r,e,i);return n||rt()},transform(e,t,r){let i=kh(e,t),n=Rh(e,t,r,!!i);return{...tt(n,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...i?{constraintWarning:i}:{}}},trackEvent:yt.END_DATE_ENTRY};function Th(e){return e.progress>=Sh}function Eh(e,t){return t.dateOrigin?Uo(e,t.dateOrigin):!1}function Dh(e,t){return Uo(e,t.startDate)}function _h(e,t,r){let i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(e,ft.DAY)?null:It("not_working_day"):null}function kh(e,t){if(Jt(e)===v.MSO)return;let i=Fe(Jt(e),e.startDate,t),n=gr(Jt(e),e.constraintDate,i);if(n.violated)return Ar(n.constraintType,n.constraintDate,i)}function Rh(e,t,r,i=!1){let n={};ce(e.type)&&!i&&Wc(e)?Object.assign(n,Ge(e.startDate)):(i||Wc(e))&&Object.assign(n,Re(),Ge(e.startDate));let s=Ph(e,t,r),c=Yr(e.durationHours,s);return c&&(n.type=c),Object.assign(n,cn(s)),n.endDate=t,n}function Wc(e){return ke.has(Jt(e))}function Ph(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateDuration(e.startDate,t):e.durationHours}var Lh=new Set(Object.values(v)),jc={targetField:"constraintType",canEdit(e,t){return De(e)?ot("completed","cant_edit_completed_activity"):gt(e,t)?ot("summary","summary_column_value"):Z()},parseInput(e){let t=String(e).toLowerCase();return Oh(t)?Y(t):J("invalid_constraint_type")},validate(){return rt()},transform(e,t,r){let i=Nh(e,t,r);return tt(i,{autoSchedule:!0})}};function Oh(e){return Lh.has(e)}function Nh(e,t,r){let i=wh(e,t);return{constraintType:t,...Pc(bh(e,t,i,r))}}function bh(e,t,r,i){if(e.type!==T.MILESTONE||!r||Qr.has(t))return r;let n=i.calendars.getCalendar(String(e.calendarId));return n?de(r,n,t):r}function wh(e,t){return ke.has(t)?null:Qr.has(t)?e.startDate:Mo.has(t)?e.endDate:e.constraintDate}var Kc={targetField:"constraintDate",canEdit(e,t){return De(e)?ot("completed","cant_edit_completed_activity"):gt(e,t)?ot("summary","summary_column_value"):Z()},parseInput(e){return $e(e)?Y(e):J("invalid_date")},validate(){return rt()},transform(e,t,r){let i=Yc(e)?an:Jt(e),n=r.calendars.getCalendar(e.calendarId);if(!n)throw new Error("constraintDatePipeline: no calendar resolved (integrity)");let o=de(t,n,i),a=Fh(e,o);return tt(a,{autoSchedule:!0})}};function Fh(e,t){return{constraintDate:t,...Yc(e)?Re():{}}}function Yc(e){return ke.has(Jt(e))||!e.constraintType}var Gc={targetField:"calendarId",canEdit(){return Z()},parseInput(e){let t=String(e).trim();return xh(t)?J("empty_calendar"):Y(t)},validate(e,t,r,i){return Mh(e.calendarId,r)?It("unchanged"):i.calendars.getCalendar(r)?rt():It("unknown_calendar")},transform(e,t,r){return tt(Uh(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:yt.CALENDAR_ASSIGNMENT};function xh(e){return e===""}function Mh(e,t){return e===t}function Uh(e,t,r){let i={calendarId:t,assignedDefaultCalendar:!1},n=r.calendars.getCalendar(t);if(n){let o=n.isWorkTime(e.startDate,"hour"),a=n.getClosestWorkTime({date:o?$c(e.startDate):e.startDate,direction:"future",unit:"hour"});i.startDate=a;let s=Bh(e,n);if(s&&(i.constraintDate=s),!e.autoScheduling)return i;Object.assign(i,Ir(n.calculateEndDate(a,e.durationHours)))}return i}function Bh(e,t){return!e.constraintDate||!e.constraintType?null:Wr({...e,constraintDate:$c(e.constraintDate)},{getClosestWorkTime:({date:r,dir:i})=>t.getClosestWorkTime({date:r,direction:i,unit:ft.HOUR})})}function $c(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var qc={targetField:"customId",canEdit(e,t){return gt(e,t)?ot("summary","summary_column_value"):Z()},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"):Y(t)},validate(){return rt()},transform(e,t){return tt({customId:t},{autoSchedule:!1,postProcessors:[]})}};var zc={targetField:"subcontractId",canEdit(){return Z()},parseInput(e){if(e==null)return Y(null);if(typeof e=="string"){let t=e.trim();if(t.length===0)return Y(null);let r=Number(t);return!Number.isFinite(r)||!Number.isInteger(r)?J("not_an_integer"):Y(r)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?J("not_an_integer"):Y(e):J("not_an_integer")},validate(){return rt()},transform(e,t){return tt({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function ri(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 ln(e){return e.some(t=>ri(t)===null)}var Jc={targetField:"responsableIds",canEdit(){return Z()},parseInput(e){return e==null?Y([]):Array.isArray(e)?Y(e):J("not_an_array")},validate(e,t,r){return ln(r)?It("missing_id"):rt()},transform(e,t){let r=t.map(ri).filter(i=>i!==null);return tt({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var Xc={targetField:"tagIds",canEdit(){return Z()},parseInput(e){return e==null?Y([]):Array.isArray(e)?Y(e):J("not_an_array")},validate(e,t,r){return ln(r)?It("missing_id"):rt()},transform(e,t){let r=t.map(ri).filter(i=>i!==null);return tt({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var Hh=new Map([[D.TEXT,Dc],[D.DESCRIPTION,_c],[D.DURATION,wc],[D.PROGRESS,sn],[D.COST,xc],[D.USED_COST,Mc],[D.HH_WORK_TIME,Uc],[D.START_DATE,Hc],[D.END_DATE,Vc],[D.CONSTRAINT_TYPE,jc],[D.CONSTRAINT_DATE,Kc],[D.CALENDAR_ID,Gc],[D.CUSTOM_ID,qc],[D.SUBCONTRACT_ID,zc],[D.RESPONSABLES,Jc],[D.TAGS,Xc]]);function Pe(e){return Hh.get(e)}var ht={APPEND:"append",REPLACE:"replace"},dn={ACTION_BUTTON:"action-button"},un={SIR_AUTO_REJECT:"sir-auto-reject"},fn={DATE_CHANGED:"date_changed",ACTIVITY_DELETED:"activity_deleted"},ze={VIOLATION:"constraint_violation"},ne={DISPATCH_MANY:"dispatch-many",INIT:"init",UNDO:"undo",REDO:"redo"};function Je(e,t){if(!t||t.type!==mi.CONSTRAINT)return null;let r=t.data;return!r?.constraintType||!r.constraintDate?null:{kind:ze.VIOLATION,activityId:e,constraintType:r.constraintType,constraintDate:r.constraintDate,projectedDate:r.projectedDate??r.constraintDate,messageKey:t.messageKey}}var Wh=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],Zc=new Set(Wh);function Ct(e,t,r,i){e.setActivityFieldDynamic(t,r,i)}function Qc(e,t,r,i){e.setLinkFieldDynamic(t,r,i)}function ue(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:oe(e.constraintDate),dateOrigin:oe(e.dateOrigin),newActivityIds:[...e.newActivityIds],pendingRequestIds:[...e.pendingRequestIds],responsableIds:[...e.responsableIds],tagIds:[...e.tagIds],baselinePoints:e.baselinePoints.map(t=>({...t,startDate:oe(t.startDate),endDate:oe(t.endDate)})),baselineSnapshot:Vh(e.baselineSnapshot),criticalPath:jh(e.criticalPath)}}function oe(e){return e===null?null:new Date(e)}function Vh(e){return e===null?null:{...e,startDate:oe(e.startDate),endDate:oe(e.endDate)}}function jh(e){return e===null?null:{...e,earlyStart:oe(e.earlyStart),earlyFinish:oe(e.earlyFinish),lateStart:oe(e.lateStart),lateFinish:oe(e.lateFinish)}}var rl=200;function Le(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%rl===0&&await dt();let o=e.getActivity(n);o&&r.set(n,it(o))}return r}function it(e){return ue(e)}function pn(e,t){let r=e.getActivity(t);return r?ue(r):null}function Oe(e,t,r){tl(e,t,r.patch);for(let i of r.cascadeMutations??[])tl(e,i.activityId,i.fields)}function tl(e,t,r){for(let[i,n]of Object.entries(r)){if(!Zc.has(i))throw new Error(`applyFieldChanges: column write to non-writable field "${i}"`);Ct(e,t,i,n)}}async function yn(e,t,r,i){let n=[],o=0;for(let a of r){o+=1,o%rl===0&&await dt();let s=Kh(e,t,a,i);s&&n.push(s)}return n}function Kh(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 Yh(r,i.get(r),n);let a=Ho(o,n);return Gh(a,i,r,n),o&&Object.keys(a).length===0?null:{id:r,kind:o?N.UPDATED:N.CREATED,fields:a,after:it(n)}}function Yh(e,t,r){return t===r.correlativeId?null:{id:e,kind:N.UPDATED,fields:{correlativeId:{before:t,after:r.correlativeId}},after:it(r)}}function Gh(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)||!Bo(i[a],n[a]))&&(r[a]={before:el(i[a]),after:el(n[a])});return r}function el(e){return e===null||typeof e!="object"?e:F(e)}function Bo(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)=>Bo(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)&&Bo(r[a],i[a]))}function hn(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 Wo(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=it(a);o.before!==void 0&&(s.correlativeId=o.before),i.set(o.activityId,s)}}var $h=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function fe(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($h);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 Sr(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 qh=e=>e.type===T.PROJECT,zh=(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:fe(String(a));return Sr(o(e.startDate),o(e.endDate),t,n)};function Jh(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(!qh(s)){let d=zh(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)}),Jh(r,t,e)}var Xh=e=>e.type===T.PROJECT,Zh=e=>At(e),Qh=(e,t,r,i)=>{let n=Zh(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:Sr(n.startDate,n.endDate,t,o)};function Vo(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(!Xh(c)){let u=Qh(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 Tr(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)=>Ct(e,o,a,s),getBaseCalendar:o=>e.calendarReader.getCalendar(o)},n=[];return e.forEachActivity((o,a)=>{o.parentId===null&&n.push(a)}),Vo(n,t,i,r)}var jo=he.BASELINE;function mn(e){return e===he.ACTUAL?he.ACTUAL:jo}var il=e=>Math.round(e*100)/100;function tm(e,t){return(t===he.BASELINE?e.expectedProgressBaseline:e.expectedProgress)??void 0}function em(e,t){let r=il(e),i=il(t);return r>99.99?Rt.DONE:i>r?Rt.OVERDUE:e>0&&r>i?Rt.ADVANCEMENT:e===0&&t===0?Rt.WAITING:e>0&&r<i?Rt.DOING:Rt.WAITING}function pe(e,t){let r=[];return e.forEachActivity((i,n)=>{let o=typeof i.progress=="number"?i.progress:0,a=em(o,tm(i,t));i.status!==a&&(Ct(e,n,D.STATUS,a),r.push(n))}),r}function Ko(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:()=>Ko(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}Ko.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var Yt=Ko;function rm(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function In(e){return rm(e)&&!isNaN(e.getTime())}function R(e,t,r,i){if(!In(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 Ht(e){if(!In(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 I=v;var H=Object.freeze({FS:Tt.FINISH_TO_START,SS:Tt.START_TO_START,FF:Tt.FINISH_TO_FINISH,SF:Tt.START_TO_FINISH});function Ze(e){return $i[String(Number(e))]??Tt.START_TO_FINISH}var z=Object.freeze({FORWARD:"forward",BACKWARD:"backward"}),Qe=Object.freeze({GREATER:"greater",LESS:"less"}),Xt=Object.freeze({SOURCE:"$source"});var im=e=>e?e.$level===1:!1,nm=e=>e.type===T.PROJECT,om=e=>e.$level!==0,am=e=>e.type===T.TASK,sm=e=>e.type===T.TASK||e.type===T.MILESTONE,bt={byFirstLevel:im,filterByParentType:nm,avoidSubproject:om,byTaskType:am,byTaskTypeAndMilestone:sm};function nl(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:i,linkProperty:n}=e;try{let o=cm({gantt:t,pendingParentsWithNoLinks:r});if(o.length===0)return new Set;let a=lm({gantt:t,subprojectsWithNoLinks:o}),s=dm({gantt:t,childrenIds:a,linkProperty:n,getArrayOfLinkedActivities:um,calculations:i});return new Set(s.map(c=>c.id))}catch(o){throw o}}function cm(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(bt.filterByParentType).filter(i=>r.has(i.id)).map(i=>i.id)}function lm(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=bt.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(s=>i.add(s));return[...i]}function dm(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===Xt.SOURCE?"target":"source"}).every(f=>o.has(f))&&a.push(c)}return a}function um(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 ol({gantt:e,linkProperty:t,direction:r}){try{let i=fm(e,t);if(r===z.FORWARD)return{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:null};if(r===z.BACKWARD)return pm(i,e,t)}catch(i){throw console.log("Critical Path",i),i}}function fm(e,t){return e.getTaskByTime().filter(bt.avoidSubproject).filter(bt.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function pm(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!==I.FNLT&&i.push(o))}),{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:n}}function al({gantt:e,direction:t,linkProperty:r}){try{let i=ym(e),n=new Set,o=new Set,a=new Set;t===z.BACKWARD&&Im(i).forEach(d=>{n.add(d.id)});let s=hm(i,t,r),c=mm(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 ym(e){return e.getTaskByTime().filter(bt.filterByParentType).filter(bt.avoidSubproject)}function hm(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!==I.FNLT;if(t===z.FORWARD){let c=a!==I.SNET;return!o&&s&&c}else return!o&&s})}function mm(e,t){let r=new Set(t.map(i=>i.id));return e.filter(i=>!r.has(i.id))}function Im(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function sl({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let i=new Set;return e.forEach(n=>{let o=t.getTask(n),a=gm(r),s=Am(r),c=o[a];if(!Array.isArray(c))return;vm(t,c,s).forEach(d=>{i.add(d)})}),i}catch(i){throw i}}function gm(e){return e===z.FORWARD?Xt.SOURCE:"$target"}function Am(e){return e===z.FORWARD?"target":"source"}function vm(e,t,r){return t.map(i=>{let o=e.getLink(i)[r];return Number(o)})}var ii={identifySecondLevelActivities:nl,identifyInitialActivities:ol,identifyParentsWithAndWithoutLinks:al,identifyForbiddenActivities:sl};function gn(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function Yo({linkType:e,lag:t,predecessorTime:r,activityCalendar:i,activity:n}){return e===H.FS&&t===0?Ht({predecessorTime:r,activityCalendar:i,direction:"future",activity:n}):ni(r,e,i,n)}function cl({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t);return{es:R(r,n,e,i),ef:n}}function ll({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 ni(e,t,r,i){if(![H.FS,H.SS,H.FF].includes(t))return e;let o=[H.FS,H.SS].includes(t)?"future":"past";return Ht({dateBaseToCalculate:e,activityCalendar:r,direction:o,activity:i})}var Go=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=gn(t),i=this.activity.constraint_type;return i===I.SNET?this.handleSNETConstraint(r):i===I.FNLT?this.handleFNLTConstraint(r):r}calculateLinks(){let t=[];for(let r of this.linkedActivitiesData){let i=r.linkType,n=Ze(i),o=r.linkLag,a=r.es,s=r.ef,c=null;if(n===H.SS)c=this.calculateSSLink({lag:o,predecessorEs:a});else if(n===H.FF)c=this.calculateFFLink({lag:o,predecessorEf:s});else if(n===H.FS)c=this.calculateFSLink({lag:o,predecessorEf:s});else if(n===H.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=ll({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=cl({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=Yo({linkType:H.SS,lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=R(this.activityCalendar,i,t,this.activity);t>0&&(n=ni(n,H.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=Yo({linkType:H.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=ni(o,H.FF,this.activityCalendar,this.activity)),{es:o,ef:n}}calculateFSLink({lag:t,predecessorEf:r}){let i=r;t===0&&(i=Ht({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=ni(n,H.SF,this.activityCalendar,this.activity)),{es:n,ef:i}}},dl=Go;var $o=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=Ze(r.linkType);if(r.type===T.TASK&&Number(r.progress)>0||r.type===T.PROJECT&&Number(r.progress)===100)continue;let n=r.linkLag,o=r.ls,a=r.lf;if(i===H.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===H.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===H.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===H.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===I.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,K.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,K.PAST);return a=R(this.activityCalendar,l,n,this.activity),a=this.getLastWorkingHour(a,this.activityCalendar,K.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,K.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=K.PAST){let n=t instanceof Date?t:new Date(t),o=Yt(n).clone();return this.isActivityInInitHour(r,n)&&i===K.PAST&&(o=o.hours(0).minutes(0).seconds(0).milliseconds(0)),Ht({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),Yt.isMoment(r)?r.hours()===a:i.getUTCHours()===a)}},ul=$o;function fl(e){let{parent:t,linkProperty:r,linkDirection:i,calculations:n,gantt:o,direction:a,linkCandidates:s}=e,c=t[r],l=Cm(t),d=null;if(a===z.FORWARD){let u=Sm(c,i,n,o);d=new dl(u,t,o,s),d=d.calculate()}else{let u=Tm(c,i,n,o);d=new ul({linksWithActivityData:u,activity:t,parentData:l,gantt:o}).calculate()}return d}function Cm(e){return{duration:e.duration,calendarId:e.calendar_id}}function Sm(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 Tm(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 hl(e){let{activityData:t,calculations:r,singleParents:i,direction:n}=e;if(Em(t.id,r))return null;let o=Dm(t.id,i),a=_m(o,r);return a.length===0?null:km(a,n)}function Em(e,t){return t.has(e)}function Dm(e,t){let r=t.get(e);return r?r.childrens:[]}function _m(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function km(e,t){if(t===z.FORWARD){let r=pl(e,"es"),i=yl(e,"ef");return{es:r,ef:i}}else{let r=pl(e,"ls"),i=yl(e,"lf");return{ls:r,lf:i}}}function pl(e,t){return e.reduce((r,i)=>i[t]<r[t]?i:r)[t]}function yl(e,t){return e.reduce((r,i)=>i[t]>r[t]?i:r)[t]}var qo={parentWithLinks:fl,parentWithNoLinks:hl};var zo=class{constructor(t){this.activity=t.activity,this.direction=t.direction,this.linkProperty=t.direction===z.FORWARD?"$target":Xt.SOURCE,this.linkDirection=t.direction===z.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===z.BACKWARD){let i=[I.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===z.FORWARD&&this.setDatesToParentsWithLinks(),this.direction===z.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=qo.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=qo.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)})}},ml=zo;var Jo=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(bt.byFirstLevel).filter(bt.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===T.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}}},Il=Jo;var Xo=class{constructor(t,r){this.direction=r,this.gantt=t,this.linkProperty=this.direction===z.FORWARD?"$target":Xt.SOURCE,this.linkDirection=this.direction===z.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(bt.avoidSubproject).forEach(t=>{this.activitiesWaitingForCalculation.add(t.id)})}catch(t){throw t}}identifyParentsWithAndWithoutLinks(){try{let{parentsWithFullProgress:t,pendingParentsWithNoLinks:r,pendingParentsWithLinks:i}=ii.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=ii.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 Il({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===T.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===T.PROJECT,calculated:!1})}.bind(this),t.id),a({parentsIds:r,allTasks:i,activitiesByLevel:n,singleParents:o})})}identifySecondLevelActivities(){try{let t=ii.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}=ii.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===z.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===T.PROJECT)return;let r=this.calculateStartAndFinishOfChainOrigin(t,this.direction);if(this.direction===z.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)===z.FORWARD){let s=i.start_date,c=i.end_date;return{es:s,ef:c}}else{if(n>=100)return{ls:Yt(i.start_date).clone(),lf:Yt(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=Yt(t.start_date).clone(),n=Yt(t.end_date).clone(),o=t.duration,a=[I.ASAP,I.ALAP,I.SNET,I.FNET],s=t.constraint_type||I.ASAP;if(a.includes(s))n=this.projectDates.end_date,i=R(r,n,-o,t);else{let c=[I.SNLT,I.MSO],l=[I.FNLT,I.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||I.ASAP,o=this.projectDates.end_date,a=[I.ASAP,I.ALAP,I.SNET,I.FNET],s=[I.SNLT,I.FNLT];if(a.includes(n))i=Math.max(t.end_date,o);else if(n===I.MSO)i=t.end_date;else if(n===I.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===T.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===z.FORWARD?"es":"ls"]:i.start_date,[this.direction===z.FORWARD?"ef":"lf"]:i.end_date}),this.calculationOfParentsFromLinks.add(i.id))})}catch(t){throw t}}doCalculationForParentType(t){let r=new ml({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()}},Ne=Xo;function Rm(e,t,r){let i={es:null,ef:null};if(!e)return i;if([I.SNET,I.SNLT].includes(t)){let n=new Date(e.constraint_date);i.es=n,i.ef=R(r,n,e.duration,e)}else if([I.FNLT,I.FNET].includes(t)){let n=new Date(e.constraint_date);i.es=R(r,n,-e.duration,e),i.ef=n}else if(t===I.MSO){let n=new Date(e.constraint_date);i.es=n,i.ef=R(r,n,e.duration,e)}else if(t===I.MFO){let n=new Date(e.constraint_date);i.es=R(r,n,-e.duration,e),i.ef=n}return i}var An=Rm;var Zo=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=H.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===T.MILESTONE;return d||(o===H.FS&&n===0?s=Ht({dateBaseToCalculate:s,activityCalendar:a,direction:"future",activity:this.referenceActivity}):s=this.mutateTheDateToFutureOrPastInBaseRestriction(t,o,a)),[H.FF,H.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,H.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,H.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,H.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,H.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,r,i){if(![H.FS,H.SS,H.FF].includes(r))return t;let o=[H.FS,H.SS].includes(r)?"future":K.PAST;return Ht({dateBaseToCalculate:t,activityCalendar:i,direction:o,activity:this.referenceActivity})}},gl=Zo;var oi=class extends gl{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Ne(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 gn(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var Qo=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===T.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===z.FORWARD?i===I.FNLT||i===I.SNLT:i===I.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===z.BACKWARD&&this.activitiesStartChainButChildrenOfLinkedParents.has(t)&&!s)return;if(r.$target.length===0&&r[Xt.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===z.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}},vn=Qo;var ta=(e,t)=>()=>t()===e;var ea=e=>!e?.fullyParsed;var Pm=16,tr=async e=>performance.now()-e>Pm?(await dt(),performance.now()):e;var ai=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 tr(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(s);if(l.size===0)break;for(let u of l){if(!a())return;c=await tr(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 ra=class extends Ne{constructor(t){super(t,z.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 vn({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 ai({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===T.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||I.ASAP,a=[I.SNET,I.SNLT,I.FNLT,I.FNET],s=[I.ASAP,I.ALAP,I.SNET,I.FNET,I.SNLT,I.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 oi({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===I.ASAP&&this.totalFloatForAsap.set(r,{es:f.es,ef:f.ef,text:i.text})):{es:d,ef:u}=new oi({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===I.ALAP&&this.alapMap.set(r,{es:i.start_date,ef:i.end_date,text:i.text});let p=An(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})),[I.MSO,I.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===I.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=Qe.GREATER){if(i===Qe.GREATER)return r.ef>t.ef?r:t;if(i===Qe.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=[I.SNET,I.FNET].includes(t)?Qe.GREATER:Qe.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===T.PROJECT)&&!(!this.gantt.getTask(o)||this.gantt.getTask(o)?.type===T.PROJECT))return r}).filter(Boolean)}},Al=ra;var ia=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===I.ALAP?this.forwardPathCalculations.get(t):this.calculatedActivities.get(t)}calculateSuccessorTimes(t,r,i=0,n,o=H.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===T.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===H.FS){let{ls:d,lf:u}=this.calculateFsLink(l);return{ls:d,lf:u}}if(o===H.FF){let{ls:d,lf:u}=this.calculateFFLink(l);return{ls:d,lf:u}}if(o===H.SS){let{ls:d,lf:u}=this.calculateSSlink(l);return{ls:d,lf:u}}if(o===H.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,H.SS)}calculateFF(t,r){let i=this.getForwardOrBackwardCalculations(Number(t.target)),n=r===I.ALAP?"ef":"lf",o=i[n],a=-this.activity.duration,s=-t.lag||0,c=t.lag;return this.calculateSuccessorTimes(o,a,s,c,H.FF)}calculateFS(t,r){let i="ls";i=r===I.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,H.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,H.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=Yt(r).clone();return R(t,new Date(n),i,this.activity)}getLastWorkingHour(t,r,i=K.PAST){let n=t instanceof Date?t:new Date(t),o=Yt(n).clone();return this.isActivityInInitHour(r,n)&&i===K.PAST&&(o=o.hours(0).minutes(0).seconds(0).milliseconds(0)),Ht({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),Yt.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,K.PAST);return s=R(i,d,o,this.activity),s=this.getLastWorkingHour(s,i,K.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,K.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,K.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})}},vl=ia;var na=class extends vl{constructor(t){super(t),this.constraint=t.constraint||I.ASAP,this.parentsWithFullProgress=t.parentsWithFullProgress,this.parentsThatImpactChildrens=t.parentsThatImpactChildrens,this.projectDates=this.gantt.getSubtaskDates()}calculate(){if(this.links.length===0)return new Ne(this.gantt,z.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!==T.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===I.ALAP)return I.ALAP;if(this.constraint===I.FNET||this.constraint===I.SNET)return"snet-fnet";if(this.constraint===I.FNLT)return I.FNLT}getSpecialParamForSf(){return!![I.ALAP].includes(this.constraint)}getSpecialParamForFF(){return!![I.MFO,I.MSO].includes(this.constraint)}getMinCalculationLogic(t){if(this.constraint===I.ALAP)return this.getMinDateBasedOnConstraint(t);if(this.constraint===I.FNET)return this.getMinDateBasedOnConstraint(t);if(this.constraint===I.FNLT)return this.getMinDateBasedOnConstraint(t);if(this.constraint===I.MFO)return this.getMinDateBasedOnConstraint(t);if(this.constraint===I.SNET||this.constraint===I.SNLT||this.constraint===I.MSO)return this.SnetSnltMsoMinDate(t);if(this.constraint===I.ASAP)return this.getMinDateBasedOnConstraint(t)}getMinDateFromLinks(t){try{return this.constraint===I.ALAP||this.constraint===I.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===I.ASAP)return new Date(Math.max(i,n));if(r===I.FNET||r===I.FNLT){let a=Math.min(i,o);return new Date(Math.max(i,a))}if(r===I.ALAP)return new Date(Math.min(i,n))}},Cl=na;function Lm(e,t,r){let i={ls:null,lf:null};return r===I.MSO&&(i.ls=t.constraint_date,i.lf=R(e,i.ls,t.duration,t)),r===I.MFO&&(i.lf=t.constraint_date,i.ls=R(e,i.lf,-t.duration,t)),i}var Sl=Lm;var oa=class extends Ne{constructor(t,r,i){super(t,z.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 vn({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 ai({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||I.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===T.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===I.MSO||o===I.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(i,o);return}if(o===I.MSO||o===I.MFO){this.recalculateInBaseRestriction(i,o);return}let{ls:s,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(n,i,o,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(o===I.SNLT||o===I.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=An(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===T.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,z.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===I.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(r===I.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 Cl({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=Sl(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===T.PROJECT)&&!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type===T.PROJECT))return r}).filter(Boolean)}doCalculationForActivitiesThatStartLinkButHisParentIsLinked(t){let r=Number(t.parent),i=this.calculationsOfParentThatImpactChildrens.get(r),n=0,o=0;if([I.ASAP,I.ALAP,I.SNET,I.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([I.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([I.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)}[I.MSO].includes(t.constraint_type)&&(n=t.constraint_date,o=R(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)),[I.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}},Tl=oa;function El(){return null}var Dl=({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 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=I.ASAP),t===I.ASAP||!t)return r===0?this.calculateAsap():this.calculateAsapWithProgress();if(t===I.ALAP)return r===0?this.calculateAlap():this.calculateAlapWithProgress();if(t===I.SNET||t===I.FNET)return r===0?this.calculateSnetFet():this.calculateSnetFnetSnltWithProgress();if(t===I.SNLT)return r===0?this.calculateSnltFnlt():this.calculateSnetFnetSnltWithProgress();if(t===I.FNLT)return r===0?this.calculateSnltFnlt():this.calculateFnltWithProgress();if(t===I.MSO||t===I.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===I.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===I.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)})}},_l=aa;var sa=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===I.MSO||t===I.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=I.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=I.ASAP){let r=this.getMinFloat(this.linksFreeFloatArray),i=this.calculateFreeFloatForEndOfProject(t),n=[I.SNLT,I.FNLT].includes(t)&&r===null?this.doCalculationForSnltFnlt(t,i,r):this.doGeneralCalculation(i,r);return Math.max(0,n)}getConstraintType(){let{constraint_type:t}=this.activity;return t||(t=I.ASAP),t}getDatesFromSucessorAndPredecessor(t,r,i){let n=i.constraint_type===I.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===I.ALAP?this.backwardMap.get(this.activity.id):this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===I.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===I.FNLT?r?.ef:r?.es))}getLinkData(t){let r=this.gantt.getLink(t)||{},i=Ze(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===I.ALAP?this.backwardMap:this.forwardMap).get(n),s=t===I.ALAP?a?.ls:a?.es,c=t===I.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===I.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)}},kl=sa;var Rl=e=>({totalFloat:new _l(e.totalFloat).getTotalFloat(),freeFloat:new kl(e.freeFloat).getFreeFloat()});var ca=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=Dl({forward:t,backward:r,id:l,activity:d,gantt:i,projectDates:n}),{totalFloat:f,freeFloat:p}=Rl(u);s.set(l,f),c.set(l,p),a=await tr(a)}return{totalFloatMap:s,freeFloatMap:c}};var la=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=ta(i,this.getCurrentCalculationId),o=()=>n()&&r();try{let a=t||this.gantt;if(this.gantt=a||El(),ea(this.gantt))return!1;let s=new Al(this.gantt);if(await s.calculateAsync(o),!o())return!1;let c=s.calculations,l=s.constraintsMap,d=new Tl(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 tr(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(),A=f.getTime()>=y?p.calculateDuration({start_date:u,end_date:f}):-p.calculateDuration({start_date:f,end_date:u});n.set(a,Number.isFinite(A)?Object.is(A,-0)?0:A:null)}return n}async calculateFloatsAsync(t,r,i){try{let n=this.gantt.getSubtaskDates(),o=Array.from(this.forwardPathCalculations.keys());return await ca({activityIds:o,forward:t,backward:r,gantt:this.gantt,projectDates:n,isCurrent:i})}catch(n){throw this.forwardPathCalculations?.size,n}}},Pl=la;var Om=e=>e===v.FNET||e===v.FNLT||e===v.MFO,Nm=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function bm(e,t){let r=e.constraintDate;if(!r||!Om(e.constraintType))return r;let i=Nm(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()?Wr(e,t):r}function wm(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 Fm(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 xm(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 Mm(e,t){let r=Fm(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:bm(n,e)})}),i}function Um(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 Bm(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 Ll(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=wm(f);return r.set(d,p),p},n=Bm(e);await dt();let o=xm(e),a=Mm(e,o);await dt();let s=[...a.values()].sort((l,d)=>(l.start_date?.getTime()??0)-(d.start_date?.getTime()??0));await dt();let c=Um(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 ua=1e3,Hm=e=>typeof e!="number"||!Number.isFinite(e)?null:Object.is(e,-0)?0:e,Wm=(e,t)=>typeof e!="number"||e<0?null:da(e,t);function Vm(e){let t=Wm(e.freeFloatDays,e.hoursPerDay),r=Hm(e.residualHours);return{freeSlackHours:t,isCritical:r!==null&&r<=0&&e.sourceIsCritical&&e.targetIsCritical&&e.targetProgress===0}}async function jm(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>=ua&&(i=0,await dt(),!t()))return null;r.set(String(o),n.linksFreeFloat[o])}return t()?r:null}async function Km(e,t,r,i,n){let o=new Map,a=0;for(let s of t.forward?.keys()??[]){if(++a>=ua&&(a=0,await dt(),!n()))return null;let c=i(s);if(c===null)continue;let l=e.getActivity(c);l&&o.set(String(c),Gm(s,Number(l.progress??0),t,r))}return n()?o:null}async function Ym(e,t,r,i,n,o){let a=new Map,s=0;for(let c of e.getAllLinks()){if(++s>=ua&&(s=0,await dt(),!o()))return null;a.set(String(c.id),Vm({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 da=(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 Gm(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=da(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:da(r.freeFloat.get(e)?.activityFreeFloat,i)}}var Cn=(e,t)=>e===t||e!==null&&t!==null&&e.getTime()===t.getTime();function fa(e,t,r){let i=e.getActivity(t),n=i?.criticalPath,o=r.criticalPath;i&&n&&Cn(n.earlyStart,o.earlyStart)&&Cn(n.earlyFinish,o.earlyFinish)&&Cn(n.lateStart,o.lateStart)&&Cn(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 pa(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 ya(e,t,r=()=>!0){if(!r())return null;let i=await Ll(e,t);if(!r())return null;let n=new Pl(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 Km(e,a,t,i.getCanonicalActivityId,r);if(!s)return null;let c=await jm(a.freeFloat,r);if(!c)return null;let l=await Ym(e,c,n.linkResidualHours,s,t,r);return l?{activities:s,links:l}:null}async function Ol(e,t,r=()=>!0){let i=await ya(e,t,r);if(!i||!r())return!1;for(let[n,o]of i.activities){if(!r())return!1;fa(e,n,o)}for(let[n,o]of i.links){if(!r())return!1;pa(e,n,o)}return!0}function Er(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=At(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 Nl=new Set;var bl=new Set(["activity-outdent","activity-indent"]);var si=new Set([D.TEXT,D.DESCRIPTION,D.COST,D.USED_COST,D.CUSTOM_ID,D.RESPONSABLES,D.SUBCONTRACT_ID,D.TAGS]),$m=new Set([h.ACTIVITY_CLIPBOARD_CLEAR,h.ACTIVITY_COPY,h.SELECTION_TOGGLE,h.SELECTION_REPLACE,h.VISIBILITY_SET,h.FILTER_SET,h.SORT_SET,h.VIEW_ATTRIBUTES_SET,h.GROUP_SET,h.SIR_SYNC,h.ACTIVITY_LOOKAHEAD_SYNC,h.PERSISTENCE_ACKNOWLEDGE,h.BASELINE_APPLY,h.PONDERATOR_CRITERION_SET,h.STATUS_CRITERIA_SET]),qm=new Set([h.ACTIVITY_CLIPBOARD_CLEAR,h.ACTIVITY_COPY,h.SELECTION_TOGGLE,h.SELECTION_REPLACE,h.VISIBILITY_SET,h.FILTER_SET,h.SORT_SET,h.VIEW_ATTRIBUTES_SET,h.GROUP_SET]);function Fl(e){return!qm.has(e.kind)}var zm=new Set;function Jm(e){return e.kind===h.INLINE_EDIT?si.has(e.column):e.kind===h.BULK_EDIT?e.edits.every(t=>si.has(t.column)):!1}function ha(e,t){return!($m.has(e.kind)||t.has(e.kind)||Jm(e))}function Sn(e){return e.kind===h.ACTIVITY_LOOKAHEAD_SYNC?e.persistedProgress!==void 0:ha(e,zm)}function er(e){return e.kind===h.ACTIVITY_LOOKAHEAD_SYNC?e.persistedProgress!==void 0:ha(e,Nl)}function xl(e){return ha(e,bl)}function ma(e){return e.kind===h.ACTIVITY_SET_PROGRESS?!0:e.kind===h.INLINE_EDIT?e.column===D.PROGRESS:e.kind===h.BULK_EDIT?e.edits.some(t=>t.column===D.PROGRESS):!1}function Xm(e){return xl(e)&&ma(e)}var wl=new Set([D.PROGRESS,D.HH_WORK_TIME,D.DURATION,D.COST,D.USED_COST,D.REAL_COST]);function Zm(e){return e.kind===h.ACTIVITY_SET_PROGRESS?!0:e.kind===h.INLINE_EDIT?wl.has(e.column):e.kind===h.BULK_EDIT?e.edits.some(t=>wl.has(t.column)):!1}var _t={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 Ml(e,t,r){let i=new Set;t.ran&&i.add(_t.AUTOSCHEDULE),i.add(_t.PARENT_BOUNDS),Zm(e)&&i.add(_t.PARENT_PROGRESS),ma(e)&&i.add(_t.REAL_WORK);let n=!r.skipAutoSchedule;return n&&xl(e)&&i.add(_t.EXPECTED_PROGRESS),n&&Xm(e)&&i.add(_t.REAL_COST),n&&er(e)&&!r.skipCriticalPath&&i.add(_t.CRITICAL_PATH),i}var kt={INSERT:"insert",REMOVE:"remove",LINK_ADD:"link-add",LINK_REMOVE:"link-remove",LINK_FIELD:"link-field"},Tn=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,ue(r)),i.dirty.add(t))}noteInsert(t){this._journal?.ops.push({kind:kt.INSERT,activityId:t})}noteRemove(t,r){this._journal?.ops.push({kind:kt.REMOVE,activityId:t,before:ue(r)})}noteLinkAdd(t){this._journal?.ops.push({kind:kt.LINK_ADD,linkId:t})}noteLinkRemove(t,r){this._journal?.ops.push({kind:kt.LINK_REMOVE,linkId:t,before:Ul(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=ue(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:kt.LINK_FIELD,linkId:t,before:Ul(r)}))}noteProgressFallback(t,r){let i=this._journal;!i||i.progressFallbackBefore.has(t)||i.progressFallbackBefore.set(t,r)}};function Ul(e){return{...e}}function Ia(e,t,r){let i=[];for(let n of r){let o=e.get(n);if(!o)continue;let a=o.pendingRequestIds??[];if(lr({pendingRequestIds:a})&&t.getActivity(n)==null)for(let s of a)i.push({kind:un.SIR_AUTO_REJECT,activityId:n,sirId:s,reason:fn.ACTIVITY_DELETED})}return i}function Ut(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 Lt={BEFORE_DIFF:"before-diff",AFTER_DIFF:"after-diff"};async function G(e,t){let r=rI(e,t),i=new Map(t.beforeSnap),n=e.peekWriteCapture();if(n){let f=nI(n);iI(e,n,f,i,r)}let o=t.sirDetection,a=o===Lt.BEFORE_DIFF?Ia(i,e,r):[],s=eI(t.correlativeShifts,r),c=await yn(e,i,r,s),l=o===Lt.AFTER_DIFF?Ia(i,e,r):a,d=t.warnings??[],u=tI(t.links??[],n?Qm(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 Qm(e,t){let r=[];for(let i of t.ops){if(i.kind!==kt.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:Ut(n)})}return r}function tI(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 eI(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 rI(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 iI(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 nI(e){return new Set(e.ops.filter(t=>t.kind===kt.INSERT).map(t=>t.activityId))}function En(e,t,r){if(!e||e==="0")return;let i=r.getChildren(e);if(i.length===0)return;let n=new Map,o=new Set,a=0;for(let l of i){let d=aI(String(l),t,r);n.set(String(l),d),a+=d,Bl(String(l),r)&&o.add(String(l))}let s=a?100/a:0,c=o.size?100/o.size:0;for(let l of i){let d=r.getActivity(l);if(!d)continue;let u=oI(String(l),d,n,o,a,s,c);u!==null&&r.setActivityField(l,D.PONDERATOR,u)}}function oI(e,t,r,i,n,o,a){return t.type===T.PROJECT||At(t)?n?o*(r.get(e)??0):i.has(e)?a:0:!Array.isArray(t.baselinePoints)||t.baselinePoints.length===0?0:null}function Bl(e,t){let r=t.getActivity(e);return r?At(r)?!0:r.type!==T.PROJECT?!1:t.getChildren(e).some(i=>Bl(String(i),t)):!1}function aI(e,t,r){let i=r.getActivity(e);if(!i)return 0;if(i.type===T.PROJECT)return Hl(e,t,r);let n=At(i);return!n||i.type===T.MILESTONE?0:Wl(n,t)}function Hl(e,t,r){let i=0;for(let n of r.getChildren(e)){let o=r.getActivity(n);if(!o)continue;if(o.type===T.PROJECT){i+=Hl(String(n),t,r);continue}let a=At(o);a&&o.type!==T.MILESTONE&&(i+=Wl(a,t))}return i}function Wl(e,t){return t===mt.COST?ga(e.cost):t===mt.WORK_HOURS?ga(e.workHours):ga(e.durationDays)}function ga(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}var Et={ROOTS:"roots"};async function X(e,t){sI(e);let r=dI(e.adapter),i=lI(t,r);i.has(_t.AUTOSCHEDULE)&&await II(e.adapter,t);let n=i.has(_t.AUTOSCHEDULE)?await pI(e,t.autoscheduleFrom,t.preventSummaryTargetPullback):mI();return await gI(e.adapter,t,n.scheduledIds,i,r),await vI(e,i,t.now),n}function sI(e){let t=e.adapter.peekWriteCapture();if(!t)return;let r=new Set,i=e.sector.activityCreter??mt.DURATION;for(let[n,o]of t.before){let a=e.adapter.getActivity(n);if(o.type===T.PROJECT||a?.type!==T.PROJECT||At(a)||!cI(n,e.adapter))continue;let s=n;for(;s!==null&&!B(s);)r.has(s)||(En(s,i,e.adapter),r.add(s)),s=e.adapter.getParentId(s)}}function cI(e,t){let r=[...t.getChildren(e)];for(;r.length>0;){let i=r.pop();if(i===void 0)continue;let n=t.getActivity(i);if(n&&At(n))return!0;r.push(...t.getChildren(i))}return!1}async function Vl(e,t,r){if(e.activityId!==void 0&&!r.adapter.activityExists(e.activityId))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let i=await Q(r.adapter,new Set(r.adapter.getAllIds()));r.scheduler.invalidateAllCaches();let n=e.activityId===void 0?r.adapter.getRootIds():[e.activityId],{scheduledIds:o}=await X({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId??Et.ROOTS,recomputeParentsFrom:n,now:r.now,options:t});return{ok:!0,changes:await G(r.adapter,{source:e,beforeSnap:i,touchedIds:n,scheduledIds:o,hoursPerDay:r.sector.hoursPerDay})}}function lI(e,t){let r=e.autoscheduleFrom!==null,i=!e.options.skipAutoSchedule&&r,n=new Set(Ml(e.action,{requested:r,ran:i},e.options));return(e.recomputeParentProgress||t.affectedParents.size>0)&&n.add(_t.PARENT_PROGRESS),n}function dI(e){let t=new Set,r=new Set,i=e.peekWriteCapture();if(!i)return{affectedParents:t,dirtySeeds:r};let n=o=>{if(o===null||B(o))return;let a=String(o);t.add(a);let s=e.getChildren(a)[0];s!==void 0&&r.add(s)};return uI(e,i.ops,n),fI(e,i.before,r,n),{affectedParents:t,dirtySeeds:r}}function uI(e,t,r){for(let i of t)if(i.kind===kt.INSERT){let n=e.getActivity(i.activityId);n&&r(n.parentId)}else i.kind===kt.REMOVE&&r(i.before.parentId)}function fI(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 pI(e,t,r=!1){let i=t===Et.ROOTS?{}:{triggerId:t};r&&(i.preventSummaryTargetPullback=!0);let n=await e.scheduler.schedule(i),o=hI(e.adapter,n.updatedIds),a=yI(e.adapter,n);return $r(e.adapter,n),{...o,warnings:a}}function yI(e,t){let r=[];for(let i of t.plans.values()){let n=i.earliestSchedulingStart;if(!n||i.startDate>=n)continue;let o=e.getActivity(i.activityId);!o?.constraintType||!o.constraintDate||r.push({kind:ze.VIOLATION,activityId:o.id,constraintType:o.constraintType,constraintDate:o.constraintDate,projectedDate:n,messageKey:ze.VIOLATION})}return r}function hI(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,warnings:[]}}function mI(){return{scheduledIds:[],warnings:[]}}async function II(e,t){let r=t.collectDirty?t.collectDirty([]):Wo(t.recomputeParentsFrom,[]);r.size!==0&&await mr(e,r,!1)}async function gI(e,t,r,i,n){i.has(_t.PARENT_PROGRESS)&&AI(e,n.affectedParents);let o=t.collectDirty?t.collectDirty(r):Wo(t.recomputeParentsFrom,r);for(let a of n.dirtySeeds)o.add(a);await mr(e,o,i.has(_t.PARENT_PROGRESS),{recomputeRealWork:i.has(_t.REAL_WORK),progressMode:"freeze-when-no-contribution"})}function AI(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 vI(e,t,r){t.has(_t.EXPECTED_PROGRESS)&&r!==null&&(CI(e.adapter)&&Tr(e.adapter,r,e.defaultBaseCalendarId??null),Xe(e.adapter,r),pe(e.adapter,e.sector.statusCriteria)),t.has(_t.REAL_COST)&&Er(e.adapter),t.has(_t.CRITICAL_PATH)&&await Ol(e.adapter,e.sector.hoursPerDay)}function CI(e){let t=!1;return e.forEachActivity(r=>{At(r)&&(t=!0)}),t}var SI=new Set([D.CONSTRAINT_TYPE,D.CONSTRAINT_DATE]),TI=new Set([v.MSO,v.MFO]);function Dr(e){return SI.has(e)}function Dn(e){return e===D.CONSTRAINT_DATE}function _n(e,t,r,i){let n=r.getActivity(e);if(!n)return!1;let o=n.constraintType;if(!o||ke.has(o)||TI.has(o))return!1;let a=Aa(n.startDate),s=Aa(r.getLastStartDate(e));if(!s||!a||a.getTime()!==s.getTime())return!1;let c=EI(t,o,String(n.calendarId??""),i),l=Aa(n.constraintDate);return DI(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function EI(e,t,r,i){if(e===null)return null;let n=i.getCalendar(r);return n?de(e,n,t):e}function Aa(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 DI(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function kn(e,{postMutationArgs:t,revertTargets:r,revert:i}){let{scheduledIds:n}=await X(e,jl(t)),o=!1;for(let{activityId:a,priorConstraintDate:s}of r){let c=i(a,s);o=o||c}if(o){let a=await X(e,jl(t));n=kI(n,a.scheduledIds)}return er(t.action)&&await X(e,_I(t)),{scheduledIds:n}}function jl(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function _I(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function kI(e,t){let r=new Set(e);for(let i of t)r.add(i);return[...r]}function _r(e,t,r){let i=[];for(let{op:n,finalLinkId:o,rejected:a}of e){if(a!==null)continue;if(n.kind===St.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:Ut(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:Ut(d)});continue}if(n.kind===St.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&&String(s.source)!==String(c.source)&&(l.source={before:String(s.source),after:String(c.source)}),s&&String(s.target)!==String(c.target)&&(l.target={before:String(s.target),after:String(c.target)}),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:Ut(c)})}return i}function kr(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 Rr(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:Ut(o)})}return i}function Kl(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function Yl(e,t,r){let{adapter:i,ctx:n,scheduler:o,sector:a}=r,s=Pe(e.column);if(!s)return{ok:!1,reason:C.NO_PIPELINE_FOR_COLUMN};e.column===D.DURATION&&o.invalidateExpandedLinksCache();let c=n.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let l=s.canEdit(c,n.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??C.CANNOT_EDIT,alertKey:l.alertKey};let d=s.parseInput(e.newValue,c,n);if(!d.ok)return{ok:!1,reason:d.reason??C.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??C.INVALID,alertKey:f.notification?.messageKey};if(e.column===D.CUSTOM_ID&&d.value!==null){let S=i.getActivity(e.activityId),O=S?S.customId:null,V=typeof O=="string"?O:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),V))return{ok:!1,reason:C.CUSTOM_ID_DUPLICATE}}let p=s.transform(c,d.value,n,d.raw),y=Le(e.activityId,p),g=await Q(i,y),A=kr(i,String(e.activityId)),k=c.constraintDate;Oe(i,e.activityId,p),Ee(e.activityId,p.postProcessors??[],i,g.get(String(e.activityId))??null);let _=Rr(A,i,String(e.activityId));if(e.column===D.CUSTOM_ID){let S=g.get(String(e.activityId)),O=S?S.customId:null,V=typeof O=="string"?O:null,$=typeof d.value=="string"?d.value:null;V!==$&&r.customIdTracker.trackCustomIdChange(V,$)}let L=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:S=>hn(e.activityId,y,S),now:r.now,options:t}),m=Dr(e.column),{scheduledIds:b}=await(m?kn({adapter:i,scheduler:o,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:L(),revertTargets:Dn(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:k}],revert:(S,O)=>_n(S,O,i,n.calendars)}):X({adapter:i,scheduler:o,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},L())),w=(p.trackingEvents??[]).map(S=>({name:S.name,properties:S.properties??{}}));s.trackEvent&&!(e.column===D.PROGRESS&&Number(d.value)<=0)&&w.unshift({name:s.trackEvent,properties:{activity_name:c.name,activity_id:c.id,activity_index:c.correlativeId}});let E=Je(e.activityId,p.constraintWarning);return{ok:!0,changes:await G(i,{source:e,beforeSnap:g,touchedIds:y,scheduledIds:b,sirDetection:Lt.BEFORE_DIFF,links:_,trackingEvents:w,...E?{warnings:[E]}:{},hoursPerDay:a.hoursPerDay})}}function Rn(e){return vi(e)}function Pn(e,t){return Object.hasOwn(e,t)}function RI(e){if(e.kind===h.LINK_CREATE)return Rn(e.type)?e.lag===void 0||Number.isFinite(e.lag)?null:C.INVALID_LINK_LAG:C.INVALID_LINK_TYPE;if(e.kind===h.LINK_UPDATE){if(Pn(e,"type")&&!Rn(e.type))return C.INVALID_LINK_TYPE;if(Pn(e,"lag")&&!Number.isFinite(e.lag))return C.INVALID_LINK_LAG}return null}function PI(e){return e.kind===nt.CREATE?Rn(e.type)?e.lag===void 0||Number.isFinite(e.lag)?null:C.INVALID_LINK_LAG:C.INVALID_LINK_TYPE:e.kind===nt.UPDATE?Pn(e,"type")&&!Rn(e.type)?C.INVALID_LINK_TYPE:!Pn(e,"lag")||Number.isFinite(e.lag)?null:C.INVALID_LINK_LAG:e.kind===nt.DELETE?null:C.INVALID_VALUE}function LI(e){for(let t of e){let r=PI(t);if(r!==null)return r}return null}function OI(e,t){let r=new Set,i=new Map;for(let n of e){if(n.kind===nt.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)),n.kind===nt.UPDATE&&(n.source!==void 0&&r.add(String(n.source)),n.target!==void 0&&r.add(String(n.target))),i.set(n.linkId,{...o}))}return{activityIds:r,links:i}}function NI(e,t,r,i,n=!1){return e.map((o,a)=>{let s=o.kind===nt.CREATE?i?.get(a):void 0,c=Ce(o,{port:t,newLinkId:s?()=>s:r.next,rejectParentLinkMutations:n});return{op:o,finalLinkId:c.applied?c.linkId:null,rejected:c.applied?null:c.rejected??C.INVALID}})}function bI(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function Gl(e,t,r){let i=RI(e);return i!==null?{ok:!1,reason:i}:va([BI(e,r.sector.hoursPerDay)],e,t,r,e.kind===h.LINK_CREATE&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function $l(e,t,r){let i=LI(e.operations);if(i!==null)return{ok:!1,reason:i};let{hoursPerDay:n}=r.sector,o=e.operations.map(s=>xI(s,n)),a=wI(e.operations);return va(o,e,t,r,a)}function wI(e){let t=new Map;return e.forEach((r,i)=>{r.kind===nt.CREATE&&r.linkId&&t.set(i,r.linkId)}),t.size>0?t:void 0}function FI(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 xI(e,t){return e.kind===nt.CREATE?{kind:nt.CREATE,source:e.source,target:e.target,type:e.type,lag:Kt(e.lag??0,t)}:e.kind===nt.UPDATE?{kind:nt.UPDATE,linkId:e.linkId,source:e.source,target:e.target,type:e.type,lag:e.lag===void 0?void 0:Kt(e.lag,t)}:{kind:nt.DELETE,linkId:e.linkId}}async function va(e,t,r,i,n){let{adapter:o,scheduler:a,sector:s,linkIdGen:c}=i;a.invalidateAllCaches();let{activityIds:l,links:d}=OI(e,o),u=await Q(o,l),f=NI(e,o,c,FI(n,i),r.rejectParentLinkMutations);if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!==h.INLINE_EDIT)return{ok:!1,reason:f[0].rejected};let p=MI(f,d,o),{scheduledIds:y,warnings:g}=await X({adapter:o,scheduler:a,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:i.now,options:r}),A=_r(f,d,o);return{ok:!0,linkVerdicts:f.map((k,_)=>k.rejected===null?{operationIndex:_,kind:k.op.kind,ok:!0,linkId:String(k.finalLinkId)}:{operationIndex:_,kind:k.op.kind,ok:!1,reason:k.rejected}),__beforeLinks:bI(d),changes:await G(o,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:y,links:A,warnings:g,hoursPerDay:s.hoursPerDay})}}function MI(e,t,r){for(let i of e){if(i.rejected!==null)continue;let n=UI(i.op,t,r);if(n!==null)return r.hasChildren(n)?Et.ROOTS:String(n)}return null}function UI(e,t,r){return e.kind===nt.CREATE?e.target:e.kind===nt.DELETE?t.get(e.linkId)?.target??null:r.getLink(e.linkId)?.target??null}function BI(e,t){return e.kind===h.LINK_CREATE?{kind:nt.CREATE,source:e.source,target:e.target,type:e.type,lag:Kt(e.lag??0,t)}:e.kind===h.LINK_UPDATE?{kind:nt.UPDATE,linkId:e.linkId,source:e.source,target:e.target,type:e.type,lag:e.lag===void 0?void 0:Kt(e.lag,t)}:{kind:nt.DELETE,linkId:e.linkId}}async function ql(e,t,r){let{adapter:i,sector:n}=r;if(typeof e.newValue!="string")return{ok:!1,reason:C.INVALID_VALUE};if(!i.getActivity(e.activityId))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let a=e.column===D.CUSTOM_PREDECESSORS,{specs:s,errors:c}=zi(e.newValue,{daysPerWeek:n.hoursPerWeek/n.hoursPerDay});if(c.length>0)return{ok:!1,reason:C.INVALID_VALUE};let l=s.map(g=>({...g,lag:Kt(Qi(g.lag),n.hoursPerDay)})),d=new Map;i.forEachActivity(g=>{g.correlativeId!=null&&d.set(String(g.correlativeId),g.id)});let u=g=>d.get(g)??null,f=a?i.getIncomingLinkIds(e.activityId):i.getOutgoingLinkIds(e.activityId),p=[];for(let g of f){let A=i.getLink(g);A&&p.push(A)}let y=a?Xi({targetActivityId:e.activityId,currentLinks:p,desiredSpecs:l,resolveActivityByCorrelative:u}):Zi({sourceActivityId:e.activityId,currentLinks:p,desiredSpecs:l,resolveActivityByCorrelative:u});return va(y.operations,e,t,r)}var Gt={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 Dt(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(o=>{B(o.parentId)&&t.push(o)}),t.sort(Xl);let r=[];zl(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),HI(o,n)}n+=1;let a=Kr(String(o.id),e);a.sort(Xl),zl(r,a)}return i}function zl(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function Jl(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Ao}var Xl=(e,t)=>Jl(e)-Jl(t);function HI(e,t){e.correlativeId=t}function Ca(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let{workHours:i,realWorkHours:n}=td(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||B(a))break;r=a}}function Zl(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||B(i)||Ca(i,t)}function Ql(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,Mt(ci(n,x.WORK_HOURS),ci(n,x.PROGRESS)))}for(let i of t)r.setActivityField(i,x.REAL_WORK_HOURS,td(i,r).realWorkHours)}function td(e,t){let r=0,i=0;for(let n of t.getChildren(e)){let o=t.getActivity(n);if(!o)continue;let a=ci(o,x.WORK_HOURS);r+=a,i+=WI(n,o,a,t)}return{workHours:r,realWorkHours:i}}function ci(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function WI(e,t,r,i){return i.hasChildren(e)?ci(t,x.REAL_WORK_HOURS):Mt(r,ci(t,x.PROGRESS))}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+=VI(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||B(a))break;r=a}}function ed(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||B(i)||Sa(i,t)}function VI(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Ta(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+=jI(c,x.COST))}t.setActivityField(r,x.COST,n);let o=t.getActivity(r);if(!o)break;let a=o.parentId;if(!a||B(a))break;r=a}}function rd(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||B(i)||Ta(i,t)}function jI(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var Ln=Object.freeze({proplannerId:null,description:"",type:T.TASK,progress:0,constraintType:v.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}),id="New Master Plan",nd="New Activity";var KI=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],On=new Set(KI);function YI(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"||!On.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function od(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,i=YI(e.activityOverrides??{}),n=e.numTasksInGantt===0?id:nd,o=i.name??n,a=i.durationHours??e.sector.hoursPerDay,s=i.calendarId??e.sector.defaultCalendar,c=GI(r,e.fallbackStartDate,i.startDate),l={...Ln,...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:K.FUTURE,task:l});if(!i.startDate&&r&&ce(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:K.FUTURE,task:l}))}let u=t.calculateEndDate({startDate:d,durationHours:l.durationHours,task:l});return{newTask:{...l,startDate:d,endDate:u,calendarDuration:ie({type:l.type,startDate:d,endDate:u}),newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function GI(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function Pr(e,t,r,i){let n=t,o=n==="0",a=Ea(e,n);if(i!==void 0){let c=a.find(l=>l.id===i);if(c){let l=Ot(c),d=a.map(Ot).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=Ot(c),d=a.map(Ot).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(Ot))+1}var rr=Number.MAX_SAFE_INTEGER,ad=Number.MAX_SAFE_INTEGER-1;function Ot(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:rr}function Ea(e,t){return Kr(t,e)}function sd(e,t,r){let i=e,n=ae(e,r);for(;n!=null&&t.has(n);)i=n,n=ae(n,r);return i}function Lr(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 ae(e,t){let r=t.getActivity(e);if(!r)return null;let i=qt(r.parentId),n=jt(i,t),o=n.findIndex(a=>String(a)===String(e));return o<=0?null:n[o-1]??null}function cd(e,t,r,i){let n=jt(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(Ot);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 $I=new Set([...[...On].filter(e=>e!==x.DURATION_HOURS),"durationDays"]);function Nn(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:C.INVALID_VALUE};for(let o of Reflect.ownKeys(e))if(typeof o=="symbol"||!$I.has(o))return{ok:!1,reason:C.INVALID_VALUE};let{durationDays:i,...n}=e;return i!==void 0&&(!Number.isFinite(i)||i<0)?{ok:!1,reason:C.INVALID_VALUE}:{ok:!0,value:{...n,...i===0&&(n.type===void 0||n.type===T.TASK)?{type:T.MILESTONE}:{},...i===void 0?{}:{durationHours:Ye(i,t)}}}}function wt(e,t){Ca(e,t),Sa(e,t),Ta(e,t)}function bn(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 wn(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 qI(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 zI(e,t,r){let i=e.startDate;return!r||!(i instanceof Date)?{}:{endDate:r(i,t)}}function be(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,i=Number.isFinite(r),n=qI(e.promotionSnapshot)??(i?{type:fr,durationHours:r,progress:0,autoScheduling:!0,constraintType:v.ASAP,constraintDate:null,hasNewActivities:!1,...zI(t,r,e.computeEndDate)}:{type:fr});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 Fn(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 ld=200;async function dd(e,t,r){let{adapter:i,scheduler:n,customIdTracker:o,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:C.ACTIVITY_IDS_EMPTY};for(let S of e.activityIds)if(!i.getActivity(S))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let s=e.activityIds.filter(S=>{let O=i.getActivity(S);return!(O?.correlativeId===0&&O.type===T.PROJECT)}),c=bn(s,i),l=wn(c,i),d=new Set;for(let S of e.activityIds){let O=i.getActivity(S);if(!O)continue;let V=O.parentId;if(B(V))continue;let $=String(V);c.has($)||d.add($)}let u=new Set([...c,...d]),f=await Q(i,u),p=new Map;for(let S of l){let O=i.getLink(S);O&&p.set(S,{...O})}let y=new Set,g=0;for(let S of c){g+=1,g%ld===0&&await dt();let O=i.getActivity(S);if(!O)continue;let V=B(O.parentId)?null:i.getActivity(String(O.parentId)),$=V?.hasNewActivities===!0&&V.newActivityIds.some(ct=>String(ct)===String(S));(O.isNewActivity===!0||$)&&y.add(S);let et=O.customId;typeof et=="string"&&et.length>0&&o.releaseCustomId(et)}for(let S of l)i.removeLink(S);let A=li(i,c),k=0;for(let S of c)k+=1,k%ld===0&&await dt(),i.removeActivity(S);for(let S of d){let O=i.getActivity(S);if(!O)continue;JI(O,y,i);let V=i.getChildren(S),$=be({parent:O,remainingChildIds:V.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(S),computeEndDate:(et,ct)=>i.calculateEndDate({startDate:et,durationHours:ct,task:O}),idsRemoved:c});if(!$){en(S,i);continue}for(let[et,ct]of Object.entries($.fields))Ct(i,S,et,ct);if(O.customId==null||O.customId===""){let et=ae(S,i),ct=et?i.getActivity(et)?.customId:null,lt=o.generateCustomIdForRestoredChild(typeof ct=="string"&&ct?ct:null);i.setActivityField(S,x.CUSTOM_ID,lt)}}for(let S of d)wt(S,i);let _=Dt(i),{scheduledIds:L}=await X({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:Et.ROOTS,recomputeParentsFrom:d,now:r.now,options:t}),m={name:Gt.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:c.size}};e.eventSource!==void 0&&(m.properties.event_source=e.eventSource);let b=new Map;for(let[S,O]of p)b.set(S,O);let w=new Map;for(let S of c){let O=f.get(String(S));O&&w.set(String(S),O)}let E=await G(i,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:L,sirDetection:Lt.AFTER_DIFF,links:Zt(p),trackingEvents:[m],hoursPerDay:a.hoursPerDay,correlativeShifts:_});return{ok:!0,changes:A.length>0?{...E,viewState:A}:E,__beforeSnap:w,__beforeLinks:b}}function JI(e,t,r){let i=Fn({parent:e,idsRemoved:t});if(i)for(let[n,o]of Object.entries(i.fields))Ct(r,i.parentId,n,o)}function li(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 Zt(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}var Or={CREATE:"create",REPARENT:"reparent"};function XI(e){let t=e.type;if(t!==T.TASK&&t!==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 ud(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&Ae(t.type):ZI(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=_o,(e.promotionSource??Or.CREATE)===Or.CREATE&&(o.constraintType=v.ASAP,o.constraintDate=null)),{parentId:e.parentId,fields:o,promotionSnapshot:XI(t)}}function ZI(e){return Ae(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function we(e,t){let i=t.adapter.getActivity(e.parentId)?.customId??null,n=ud({...e,getParent:a=>t.adapter.getActivity(a)??null});if(!n)return{applied:!1,removedLinks:new Map};let o=n.fields.type===T.PROJECT?QI(e.parentId,t):new Map;for(let[a,s]of Object.entries(n.fields))Ct(t.adapter,n.parentId,a,s);return n.promotionSnapshot&&t.adapter.setPromotionSnapshot(n.parentId,n.promotionSnapshot),n.fields.customId===null&&t.customIdTracker.releaseCustomId(i),{applied:!0,removedLinks:o}}function QI(e,t){let r=new Map,i=new Set([...t.adapter.getIncomingLinkIds(e),...t.adapter.getOutgoingLinkIds(e)]);for(let n of i){let o=t.adapter.getLink(n);o&&(r.set(String(n),{...o}),t.adapter.removeLink(n))}return r}async function di(e,t,r={}){let{adapter:i,scheduler:n,sector:o,calendars:a,activityIdGen:s,uidGen:c}=t;r.skipCacheInvalidation||n.invalidateAllCaches();let l=tg(e,i);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=rg(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:sg(a)},numTasksInGantt:i.activityCount(),nextUniqueCorrelativeId:y,activityOverrides:e.overrides??{}},k=od(g,{getActivity:S=>i.getActivity(S),calculateEndDate:S=>i.calculateEndDate(S),getClosestWorkTime:S=>i.getClosestWorkTime(S)}).newTask;k.realWorkHours=Mt(k.workHours,k.progress),ng(k,e,t,u,d,r);let _=r.insertionCorrelativeId??Pr(i,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);k.correlativeId=_;let L=new Set([p]);d&&L.add(d.id);let m=d!==null&&i.getChildren(d.id).length===0,b=r.skipBeforeSnap?new Map:await Q(i,L);i.addActivity(k);let w=d?we({parentId:d.id,newChildId:p,isCurrentlyLeaf:m},t).removedLinks:new Map;r.skipRollupCascades||(Zl(p,i),ed(p,i),rd(p,i));let E=og(i,p,L,r);return{ok:!0,newId:p,parent:d,newActivity:k,beforeSnap:b,initialTouched:L,correlativeShifts:E,removedParentLinks:w}}function tg(e,t){let r=B(e.parentId),i=r?null:t.getActivity(e.parentId);if(!r&&!i)return{ok:!1,reason:C.PARENT_NOT_FOUND};if(i!==null&&lr(i))return{ok:!1,reason:C.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:C.ANCHOR_SIBLING_CONFLICT};let a=e.afterSiblingId??e.beforeSiblingId,s=eg(e,t,r,a);return s||{ok:!0,parent:i,anchorSiblingId:a,isRoot:r}}function eg(e,t,r,i){if(i===void 0)return null;let n=t.getActivity(i);if(!n)return{ok:!1,reason:C.ANCHOR_SIBLING_NOT_FOUND};let o=r?"0":e.parentId;return(n.parentId==null?"0":String(n.parentId))!==o?{ok:!1,reason:C.ANCHOR_SIBLING_WRONG_PARENT}:null}function rg(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 ig(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function ng(e,t,r,i,n,o){let{adapter:a,customIdTracker:s}=r,c=ig(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 og(e,t,r,i){if(i.skipCorrelativeRecompute)return[];let n=Dt(e).filter(o=>o.activityId!==String(t));for(let o of n)r.add(o.activityId);return n}async function ag(e,t,r,i,n){let{newId:o,newActivity:a,beforeSnap:s,initialTouched:c,correlativeShifts:l,removedParentLinks:d}=r,u={name:Gt.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:o,created_duration:a.durationHours}};return t.eventSource!==void 0&&(u.properties.event_source=t.eventSource),G(e,{source:t,beforeSnap:s,touchedIds:c,scheduledIds:i,correlativeShifts:l,trackingEvents:[u],links:Zt(new Map(d)),hoursPerDay:n})}async function fd(e,t,r){let{adapter:i,scheduler:n,sector:o}=r,a=Nn(e.overrides,o.hoursPerDay);if(!a.ok)return a;let s=await di({...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 X({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 ag(i,e,s,u,o.hoursPerDay),...s.removedParentLinks.size>0?{__beforeLinks:new Map(s.removedParentLinks)}:{}}}function sg(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"}async function hd(e,t,r){let i=cg(e,r);if(i)return{ok:!1,reason:i};let n=dg(e,r);if(!n.ok)return n;let o=e.mode===ht.REPLACE?new Set(r.adapter.getAllIds().map(m=>String(m))):new Set,a=e.mode===ht.REPLACE?await Q(r.adapter,o):new Map,s=e.mode===ht.REPLACE?mg(r):new Map,c=e.mode===ht.REPLACE?li(r.adapter,o):[];r.scheduler.invalidateAllCaches();let l=[];if(e.mode===ht.REPLACE){for(let m of s.keys()){let b=Ce({kind:nt.DELETE,linkId:m},{port:r.adapter});if(!b.applied)return{ok:!1,reason:b.rejected??C.INVALID};l.push({op:{kind:nt.DELETE,linkId:m},finalLinkId:m,rejected:null})}for(let m of o){let b=r.adapter.getActivity(m)?.customId;typeof b=="string"&&b.length>0&&r.customIdTracker.releaseCustomId(b),r.adapter.removeActivity(m)}}let d=await hg(e,n.plan.items,r);if(!d.ok)return d;for(let[m,b]of d.removedParentLinks)s.set(m,b),l.push({op:{kind:nt.DELETE,linkId:m},finalLinkId:m,rejected:null});let u=md(e)?[]:Dt(r.adapter),f=new Set(n.plan.items.map(m=>String(m.activityId))),p=u.filter(m=>!f.has(m.activityId)),y=e.mode===ht.REPLACE?new Set(o):new Set;Cr(r.adapter,u,f,a,y);for(let m of n.plan.items)y.add(String(m.activityId));let g=n.plan.links.map(m=>({operation:{kind:nt.CREATE,source:m.source,target:m.target,type:m.type,lag:Kt(m.lag??0,r.sector.hoursPerDay)},linkId:m.linkId})),A=Gi(g,{port:r.adapter,preserved:s,rejectParentLinkMutations:t.rejectParentLinkMutations??!1});if(!A.applied)return{ok:!1,reason:A.rejected??C.INVALID};for(let{operation:m,linkId:b}of g)l.push({op:m,finalLinkId:b,rejected:null});let k=n.plan.items.map(m=>m.activityId),{scheduledIds:_}=await X({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.items.length>0||e.links.length>0?Et.ROOTS:null,recomputeParentsFrom:k,now:r.now,options:t}),L=await G(r.adapter,{source:e,beforeSnap:a,touchedIds:y,scheduledIds:_,links:_r(l,s,r.adapter),hoursPerDay:r.sector.hoursPerDay,correlativeShifts:p,...e.mode===ht.REPLACE?{sirDetection:Lt.AFTER_DIFF}:{}});return{ok:!0,changes:c.length>0?{...L,viewState:c}:L,...e.mode===ht.REPLACE||s.size>0?{...e.mode===ht.REPLACE?{__beforeSnap:a}:{},__beforeLinks:Ig(s)}:{}}}function cg(e,t){if(e.mode!==ht.APPEND&&e.mode!==ht.REPLACE)return C.INVALID;let r=new Set,i=new Set;for(let o of e.items){if(o.batchId.length===0||r.has(o.batchId))return C.INVALID;if(r.add(o.batchId),o.index!==void 0&&(!Number.isInteger(o.index)||o.index<0))return C.INVALID;if(o.activityId!==void 0){let a=String(o.activityId);if(a.length===0||a==="0"||i.has(a))return C.INVALID;i.add(a)}}for(let o of e.items)if(!_a(o.parent,!0,e.mode,r,t))return C.PARENT_NOT_FOUND;if(lg(e.items))return C.INVALID;let n=new Set;for(let o of e.links){if(!Object.values(W).includes(o.type))return C.INVALID_LINK_TYPE;if(o.lag!==void 0&&!Number.isFinite(o.lag))return C.INVALID_LINK_LAG;if(!_a(o.source,!1,e.mode,r,t)||!_a(o.target,!1,e.mode,r,t))return C.ACTIVITY_NOT_FOUND;if(o.linkId!==void 0){let a=String(o.linkId);if(a.length===0||n.has(a))return C.INVALID;n.add(a)}}return null}function _a(e,t,r,i,n){return typeof e=="string"?e==="0"?t:r===ht.APPEND&&n.adapter.getActivity(String(e))!==null:e!==null&&e.batchId.length>0&&i.has(e.batchId)}function lg(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 dg(e,t){let r=new Map;for(let d of e.items){let u=Nn(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=ug(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=fg(d.linkId,e.mode,o,t);return o.add(String(u)),u}),s=pg(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:C.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:C.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=yd(u.source,i),p=yd(u.target,i),y=a[d];if(f===null||p===null||y===void 0)return{ok:!1,reason:C.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 ug(e,t,r,i){if(e!==void 0&&(t===ht.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===ht.APPEND&&(i.adapter.getActivity(o)!==null||i.isActivityIdReserved(String(o)));)o=i.activityIdGen.next();return o}function fg(e,t,r,i){if(e!==void 0&&(t===ht.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===ht.APPEND&&(i.adapter.getLink(o)!==null||i.isLinkIdReserved(String(o)));)o=i.linkIdGen.next();return o}function pg(e,t,r){if(md(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===ht.REPLACE||typeof s.parent!="string"&&t.has(s.parent.batchId)?[]:Ea(r.adapter,d).sort((g,A)=>Ot(g)-Ot(A)||String(g.id).localeCompare(String(A.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?pd(c[d-1],r):null,p=l<c.length?pd(c[l],r):null;for(let y=0;y<u;y+=1){let g=c[d+y],A=a.get(g);A!==void 0&&o.set(A,yg(f,p,y+1,u))}}}return o}function md(e){return e.mode===ht.APPEND&&e.items.every(t=>t.parent==="0"&&t.index===void 0)}function pd(e,t){let r=t.adapter.getActivity(e);return r?Ot(r):0}function yg(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 hg(e,t,r){let i=new Map,n=new Map,o=[];for(let s of t){if(s.parentBatchId===null){o.push(s);continue}let c=i.get(s.parentBatchId)??[];c.push(s),i.set(s.parentBatchId,c)}for(let s=0;s<o.length;s+=1){let c=o[s],l=await di({kind:h.ACTIVITY_CREATE,parentId:c.parentId,activityId:c.activityId,overrides:c.overrides,...e.eventSource===void 0?{}:{eventSource:e.eventSource}},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,skipCacheInvalidation:!0,skipRollupCascades:!0,insertionCorrelativeId:c.insertionCorrelativeId});if(!l.ok)return l;for(let[d,u]of l.removedParentLinks)n.set(d,u);for(let d of i.get(c.input.batchId)??[])o.push(d)}if(o.length!==t.length)return{ok:!1,reason:C.INVALID};let a=new Set;for(let s=o.length-1;s>=0;s-=1){let c=o[s].parentId;c==="0"||a.has(String(c))||(a.add(String(c)),wt(c,r.adapter))}return{ok:!0,removedParentLinks:n}}function yd(e,t){return typeof e=="string"?e:t.get(e.batchId)??null}function mg(e){return new Map(e.adapter.getAllLinks().map(t=>[String(t.id),{...t}]))}function Ig(e){return new Map(Array.from(e,([t,r])=>[String(t),r]))}function Id(e,t){let{adapter:r}=t,i=e.activityId,n=r.getActivity(i);if(!n)return{ok:!1,reason:C.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:C.ACTIVITY_NOT_FOUND};let c={id:i,kind:N.UPDATED,fields:{pendingRequestIds:{before:o,after:a}},after:it(s)};return{ok:!0,changes:{source:e,activities:[c],links:[],calendars:[],trackingEvents:[]}}}function gd(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 Ad(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 gg(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 vd(e,t,r,i){let n=new Set,o=new Set;for(let a of e)gg(a,t,r,i,n,o)}async function Cd(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=Zr(t.adapter,i),o=new Set(i);for(let s of n)o.add(String(s));let a=await Q(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",je(s.progress))}Ac(n,t.adapter),Ql(i,n,t.adapter)}),[...await yn(t.adapter,a,o)]}async function Sd(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=gd(a),u=gd(s);vd(r,"activity",y=>{let g=c.get(y);return{exists:g!==void 0,current:g?.proplannerId??null}},d),vd(i,"link",y=>{let g=l.get(y);return{exists:g!==void 0,current:g?.proplannerId??null}},u),Ad(a,r,"activity"),Ad(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 A=g.proplannerId;t.adapter.setActivityField(y.id,"proplannerId",y.proplannerId),f.push({id:y.id,kind:N.UPDATED,fields:{proplannerId:{before:A,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 A=g.proplannerId;t.adapter.setLinkProplannerId(y.id,y.proplannerId),p.push({id:y.id,kind:N.UPDATED,fields:{proplannerId:{before:A,after:y.proplannerId}},after:{...g,proplannerId:y.proplannerId}})}}),{ok:!0,changes:{source:e,activities:f,links:p,calendars:[],trackingEvents:[]}}}async function Td(e,t,r){if(Ag(e))return{ok:!1,reason:C.INVALID_VALUE};let i=[...new Set(e.activityIds.map(String))];if(e.acknowledgePersistedLookahead===!0&&i.some(s=>!r.isActivityIdReserved(s)))return{ok:!1,reason:C.INVALID};let o=i.map(s=>r.adapter.getActivity(s));if(o.some(s=>!s))return{ok:!1,reason:C.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 Cd([{activityId:i[0],progress:e.persistedProgress}],r)).length>0?(await X({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 G(r.adapter,{source:e,beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:r.sector.hoursPerDay})}):{ok:!0,changes:{source:e,activities:a,links:[],calendars:[],trackingEvents:[]}}}function Ag(e){let t=e.persistedProgress;return t!==void 0&&(e.activityIds.length!==1||!Number.isFinite(t)||t<0||t>100)}function Ra(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)Pg(f,r);let n=r.getVisualOrderIds().filter(f=>i.has(f)&&!Lr(f,i,r)),o=n.map(f=>vg(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=wn(d,r);return{sourceStateRevision:t.stateRevision,conversionRootIds:n,conversionGroups:a,milestoneMoves:s,activityIdsToDelete:c,linkIdsToDelete:u,formerParents:l}}async function _d(e,t,r){if(e.expectedStateRevision!==r.stateRevision)return{ok:!1,reason:C.STALE_STATE_REVISION};let i=Ra(e,r);if(!Lg(i,r.adapter))return{ok:!1,reason:C.HIERARCHY_CYCLE};let{adapter:n,scheduler:o}=r;o.invalidateAllCaches();let a=await Eg(i,n);Dg(i,r),kd(i,n),_g(i,a.deletedIds,n);let s=kg(i,n);Cr(n,s,a.deletedIds,a.beforeSnap,a.touchedIds);let{scheduledIds:c}=await X({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 G(n,{source:e,beforeSnap:a.beforeSnap,touchedIds:a.touchedIds,scheduledIds:c,sirDetection:"after-diff",links:Zt(a.beforeLinks),hoursPerDay:r.sector.hoursPerDay,correlativeShifts:s});return Rg(i,a,l)}function vg(e,t){let r=ka(e,t),i=bn([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=>ka(c,t));Dd(r);for(let c of n)Dd(c);let o=n.filter(c=>c.type!==T.MILESTONE),a=n.filter(c=>c.type===T.MILESTONE),s=Cg(r,o);return{conversionRootId:e,convertedActivities:o.map(c=>Sg(c,s)),milestoneMoves:Tg(r,a),activityIdsToDelete:o.map(c=>c.id),formerParent:{activity:it(r),hasConvertedActivities:o.length>0}}}function Cg(e,t){let r=new Map;t.length>0&&r.set(e.id,Ed(e));for(let i of t)r.set(i.id,Ed(i));return r}function Sg(e,t){let r=it(e),i=qt(e.parentId),n=t.get(i);return r.parentId=n===void 0?null:String(n),r}function Tg(e,t){let r=[],i=qt(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 Eg(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 Q(t,i),beforeLinks:Og(e.linkIdsToDelete,t),viewStateChanges:li(t,r)}}function Dg(e,t){for(let r of e.activityIdsToDelete){let i=t.adapter.getActivity(r)?.customId;i&&t.customIdTracker.releaseCustomId(i)}}function kd(e,t){for(let r of e.milestoneMoves)t.setActivityFields(r.activityId,{parentId:r.parentId,correlativeId:Pr(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,T.TASK)}function _g(e,t,r){for(let{activity:i,hasConvertedActivities:n}of e.formerParents){let o=ka(i.id,r),a=Fn({parent:o,idsRemoved:t});r.setActivityFields(i.id,{isLookahead:i.isLookahead||n,hasLookaheadTasks:i.hasLookaheadTasks||n,...a?.fields??{}})}}function kg(e,t){for(let{activity:r}of e.formerParents)wt(r.parentId,t);return Dt(t)}function Rg(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=>it(a))})),__beforeSnap:i,__beforeLinks:t.beforeLinks}}function Pg(e,t){let r=t.getActivity(e);if(!r)throw new Error(`Conversion root ${e} was not found`);if(r.type===T.PROJECT&&r.correlativeId===0)throw new Error(`Conversion root ${e} is the visual project root`)}function ka(e,t){let r=t.getActivity(e);if(!r)throw new Error(`Conversion activity ${e} is missing`);return r}function Ed(e){if(e.proplannerId==null)throw new Error(`Conversion activity ${e.id} has no persisted identifier`);return e.proplannerId}function Dd(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 Lg(e,t){let r=t.fork();return kd(e,r),ve({port:t,proposedPort:r,currentLinks:t.getAllLinks(),proposedLinks:r.getAllLinks()}).ok}function Og(e,t){let r=new Map;for(let i of e){let n=t.getLink(i);n&&r.set(i,{...n})}return r}function Nr(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)||(Rd(a,o,t)||Rd(o,a,t))&&i.push(String(n.id))}return i}function Rd(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||B(a))return!1;let s=a;if(s===t)return!0;i=s}return!1}function xn(e,t){let r=e.getAllLinks();return!ve({port:e,currentLinks:r,proposedLinks:r,proposal:{reparented:t}}).ok}function Mn(e,t){let r=new Set;if(e.length===0)return r;let i=new Map(e.map(o=>[o.activityId,o.newParentId]));if(!xn(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),xn(t,a)){r.add(o.activityId);continue}n.set(o.activityId,o.newParentId)}return r}async function Pd(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:C.ACTIVITY_NOT_FOUND};let s=B(e.parentId);if(!s&&!i.getActivity(e.parentId))return{ok:!1,reason:C.PARENT_NOT_FOUND};if(!s&&(e.parentId===e.activityId||i.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:C.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:C.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let w=i.getActivity(c);if(!w)return{ok:!1,reason:C.ANCHOR_SIBLING_NOT_FOUND};if((w.parentId===null?"0":String(w.parentId))!==e.parentId)return{ok:!1,reason:C.ANCHOR_SIBLING_WRONG_PARENT}}let l=a.parentId,d=qt(l),u=String(e.parentId),f=d!==u;if(f){let w=new Map([[e.activityId,s?null:e.parentId]]);if(xn(i,w))return{ok:!1,reason:C.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),g=new Map;f&&i.setActivityField(e.activityId,x.PARENT,u);let A=Pr(i,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(i.setActivityField(e.activityId,x.CORRELATIVE_ID,A),f){if(!s){let w=i.getActivity(e.parentId);if(w){let E=Ae(w.type)&&i.getChildren(e.parentId).filter(O=>O!==e.activityId).length===0,S=we({parentId:e.parentId,newChildId:e.activityId,isCurrentlyLeaf:E,promotionSource:Or.REPARENT},r);if(S.applied)for(let[O,V]of S.removedLinks)g.set(O,V)}}if(d!=="0"){let w=i.getActivity(d);if(w){let E=i.getChildren(d),S=be({parent:w,remainingChildIds:E.map(String),defaultDurationHours:o.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(d),computeEndDate:(O,V)=>i.calculateEndDate({startDate:O,durationHours:V,task:w}),idsRemoved:new Set([e.activityId])});if(S){for(let[ct,lt]of Object.entries(S.fields))Ct(i,d,ct,lt);let O=ae(d,i),V=O?i.getActivity(O)?.customId:null,$=typeof V=="string"&&V?V:null,et=r.customIdTracker.generateCustomIdForRestoredChild($);i.setActivityField(d,x.CUSTOM_ID,et)}}}}f&&(d!=="0"&&wt(d,i),s||wt(e.parentId,i));let k=Dt(i);for(let w of k){if(p.add(w.activityId),y.has(w.activityId))continue;let E=i.getActivity(w.activityId);if(!E)continue;let S=it(E);w.before!==void 0&&(S.correlativeId=w.before),y.set(w.activityId,S)}let _=f&&d!=="0"?i.getChildren(d).map(String):[],{scheduledIds:L}=await X({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,..._],now:r.now,options:t,recomputeParentProgress:f}),m=f?Nr([e.activityId],i):[],b={name:Gt.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:[...new Set([...m.map(String),...g.keys()])]}};return e.eventSource!==void 0&&(b.properties.event_source=e.eventSource),{ok:!0,changes:await G(i,{source:e,beforeSnap:y,touchedIds:p,scheduledIds:L,sirDetection:Lt.BEFORE_DIFF,links:Zt(g),trackingEvents:[b],hoursPerDay:o.hoursPerDay}),...g.size>0?{__beforeLinks:g}:{}}}function Un(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?Ot(f):rr,g=p?Ot(p):rr;return y-g});for(let d of s){if(!t.getActivity(d)){i.push({activityId:d,reason:C.ACTIVITY_NOT_FOUND}),a.delete(d);continue}if(Lr(d,o,t))continue;let f=Ws(d,a,t);if(f==null){i.push({activityId:d,reason:C.INDENT_NO_ELIGIBLE_SIBLING}),a.delete(d);continue}let p=t.getActivity(d)?.parentId,y=B(p)?"0":String(p);n.push({activityId:d,newParentId:f,oldParentId:y}),o.add(d)}let c=Mn(n,t);for(let d of c)i.push({activityId:d,reason:C.HIERARCHY_CYCLE});let l=n.filter(d=>!c.has(d.activityId));return{moves:n,cyclicMoveIds:c,allowedMoves:l,failed:i}}async function Ld(e,t,r){let{adapter:i,scheduler:n,sector:o}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:C.ACTIVITY_IDS_EMPTY};let a=new Set,s=[],c=Un(e.activityIds,i),l=[...c.failed];for(let m of c.moves)a.add(String(m.activityId)),a.add(String(m.newParentId)),m.oldParentId!=="0"&&a.add(String(m.oldParentId));let d=c.allowedMoves,u=await Q(i,a);for(let{activityId:m,newParentId:b}of d)i.setActivityField(m,x.PARENT,b),i.setActivityField(m,x.CORRELATIVE_ID,ad),s.push(m);let f=new Set,p=new Map;for(let{activityId:m,newParentId:b}of d){if(f.has(b))continue;f.add(b);let w=i.getActivity(b);if(!w)continue;let E=w.customId,S=Ae(w.type)&&i.getChildren(b).filter($=>!s.includes($)).length===0,O=w.hasNewActivities&&w.newActivityIds.some($=>String($)===String(m)),V=we({parentId:b,newChildId:m,isCurrentlyLeaf:S,promotionSource:Or.REPARENT},r);if(V.applied){for(let[$,et]of V.removedLinks)p.set($,et);O||(i.setActivityField(b,x.HAS_NEW_ACTIVITIES,!1),i.setActivityField(b,x.NEW_ACTIVITIES_ARRAY,[]))}i.setActivityField(b,x.CONSTRAINT_TYPE,v.ASAP),i.setActivityField(b,x.CONSTRAINT_DATE,null),i.setActivityField(b,x.CUSTOM_ID,null),V.applied||Kl(E,r.customIdTracker)}let y=new Set;for(let m of d)m.oldParentId!=="0"&&y.add(m.oldParentId),y.add(m.newParentId);for(let m of y)wt(m,i);let g=Dt(i);for(let m of g){if(a.add(m.activityId),u.has(m.activityId))continue;let b=i.getActivity(m.activityId);if(!b)continue;let w=it(b);m.before!==void 0&&(w.correlativeId=m.before),u.set(m.activityId,w)}let A=Nr(s,i);for(let m of A){let b=i.getLink(m);b&&(p.set(m,{...b}),i.removeLink(m))}let{scheduledIds:k}=await X({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:s,now:r.now,options:t}),_={name:Gt.ACTIVITY_INDENT,properties:{activity_ids:s,failed:l.map(m=>({activity_id:m.activityId,reason:m.reason})),invalid_link_ids:[...p.keys()]}};e.eventSource!==void 0&&(_.properties.event_source=e.eventSource);let L=await G(i,{source:e,beforeSnap:u,touchedIds:a,scheduledIds:k,links:Zt(p),trackingEvents:[_],hoursPerDay:o.hoursPerDay});return{ok:!0,activityVerdicts:e.activityIds.map(m=>{let b=l.find(w=>String(w.activityId)===String(m));return b?{activityId:String(m),ok:!1,reason:b.reason}:{activityId:String(m),ok:!0}}),changes:L,__beforeLinks:p}}async function Od(e,t,r){let{adapter:i,scheduler:n,sector:o}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:C.ACTIVITY_IDS_EMPTY};let a=new Set(e.activityIds),s=new Map,c=new Map;for(let E of e.activityIds){let S=E;i.getActivity(S)&&(s.set(S,vo(S,i)),c.set(S,sd(S,a,i)))}let l=new Set,d=[],u=[],f=new Set,p=[],y=new Set,g=[...e.activityIds].sort((E,S)=>{let O=i.getActivity(E),V=i.getActivity(S),$=O?Ot(O):rr,et=V?Ot(V):rr;return $-et});for(let E of g){let S=E,O=i.getActivity(S);if(!O){d.push({activityId:S,reason:C.ACTIVITY_NOT_FOUND});continue}if(Lr(S,y,i))continue;let V=O.parentId;if(B(V)){d.push({activityId:S,reason:C.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let $=String(V),et=i.getActivity($);if(!et){d.push({activityId:S,reason:C.ACTIVITY_NOT_FOUND});continue}let ct=et.parentId;if(B(ct)){d.push({activityId:S,reason:C.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let lt=String(ct),pt=vo($,i)+1,re=c.get(S);if(re!=null&&a.has(re)){let Ft=s.get(re)??-1,ar=s.get(S)??-1;Ft>=0&&ar>=0&&(pt+=ar-Ft)}p.push({activityId:S,grandparentKey:lt,oldParentKey:$,targetIndexInGrandparent:pt}),y.add(S),l.add(String(S)),l.add(String($)),lt!=="0"&&l.add(String(lt)),f.add($)}let A=Mn(p.map(E=>({activityId:E.activityId,newParentId:E.grandparentKey})),i);for(let E of A)d.push({activityId:E,reason:C.HIERARCHY_CYCLE});let k=p.filter(E=>!A.has(E.activityId)),_=await Q(i,l);for(let E of k){i.setActivityField(E.activityId,x.PARENT,E.grandparentKey);let S=cd(i,E.grandparentKey,E.targetIndexInGrandparent,E.activityId);i.setActivityField(E.activityId,x.CORRELATIVE_ID,S),u.push(E.activityId)}for(let E of f){let S=i.getActivity(E);if(!S)continue;let O=i.getChildren(E),V=be({parent:S,remainingChildIds:O.map(String),defaultDurationHours:o.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(E),computeEndDate:(pt,re)=>i.calculateEndDate({startDate:pt,durationHours:re,task:S}),idsRemoved:new Set(k.filter(pt=>pt.oldParentKey===E).map(pt=>pt.activityId))});if(!V){en(E,i);continue}for(let[pt,re]of Object.entries(V.fields))Ct(i,E,pt,re);let $=ae(E,i),et=$?i.getActivity($)?.customId:null,ct=typeof et=="string"&&et?et:null,lt=r.customIdTracker.generateCustomIdForRestoredChild(ct);i.setActivityField(E,x.CUSTOM_ID,lt)}let L=new Set;for(let E of f)L.add(String(E));for(let E of k)E.grandparentKey!=="0"&&L.add(String(E.grandparentKey));for(let E of L)wt(E,i);let m=Dt(i);for(let E of m){if(l.add(E.activityId),_.has(E.activityId))continue;let S=i.getActivity(E.activityId);if(!S)continue;let O=it(S);E.before!==void 0&&(O.correlativeId=E.before),_.set(E.activityId,O)}let{scheduledIds:b}=await X({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:u.length>0?Et.ROOTS:null,recomputeParentsFrom:u,now:r.now,options:t}),w={name:Gt.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(E=>({activity_id:String(E.activityId),reason:E.reason}))}};return e.eventSource!==void 0&&(w.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(E=>{let S=d.find(O=>String(O.activityId)===String(E));return S?{activityId:String(E),ok:!1,reason:S.reason}:{activityId:String(E),ok:!0}}),changes:await G(i,{source:e,beforeSnap:_,touchedIds:l,scheduledIds:b,trackingEvents:[w],hoursPerDay:o.hoursPerDay})}}async function Nd(e,t,r){let{adapter:i,scheduler:n,sector:o}=r,a=i.getActivity(e.activityId);if(!a)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};if(!Hr(e.type))return{ok:!1,reason:C.INVALID_VALUE};let s=i.getChildren(e.activityId),c=e.type===T.PROJECT;if(c!==s.length>0)return{ok:!1,reason:C.INVALID_VALUE};let l=new Set(i.getAllIds()),d=await Q(i,l);n.invalidateAllCaches();let u=c&&a.type!==T.PROJECT?we({parentId:e.activityId,newChildId:s[0],isCurrentlyLeaf:!0},r).removedLinks:new Map;!c&&a.type===T.PROJECT&&Ng(e.activityId,r),e.type!==T.PROJECT?(bg(e.activityId,e.type,r),wg(e.activityId,r)):wt(e.activityId,i);let f=Fg(e.activityId,r);for(let[y,g]of u)f.set(y,g);let{scheduledIds:p}=await X({adapter:i,scheduler:n,sector:o,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId],recomputeParentProgress:!0,now:r.now,options:t});return{ok:!0,changes:await G(i,{source:e,beforeSnap:d,touchedIds:l,scheduledIds:p,sirDetection:Lt.BEFORE_DIFF,links:Zt(f),hoursPerDay:o.hoursPerDay}),__beforeLinks:new Map(f)}}function Ng(e,t){let r=t.adapter.getActivity(e);if(!r)return;let i=be({parent:r,remainingChildIds:[],defaultDurationHours:t.sector.hoursPerDay,promotionSnapshot:t.adapter.getPromotionSnapshot(e),computeEndDate:(n,o)=>t.adapter.calculateEndDate({startDate:n,durationHours:o,task:r})});if(i)for(let[n,o]of Object.entries(i.fields))Ct(t.adapter,e,n,o)}function bg(e,t,r){let i=r.adapter.getActivity(e);if(!i)return;r.adapter.setActivityField(e,x.TYPE,t);let n=t===T.MILESTONE?0:i.durationHours===0?r.sector.hoursPerDay:i.durationHours;n!==i.durationHours&&r.adapter.setActivityField(e,x.DURATION_HOURS,n);let o=r.adapter.getActivity(e);if(!o)return;let a=r.adapter.calculateEndDate({startDate:o.startDate,durationHours:n,task:o});r.adapter.setActivityField(e,x.END_DATE,a)}function wg(e,t){if(t.adapter.getActivity(e)?.customId)return;let i=ae(e,t.adapter),n=i?t.adapter.getActivity(i)?.customId:null,o=t.customIdTracker.generateCustomIdForRestoredChild(n||null);t.adapter.setActivityField(e,x.CUSTOM_ID,o)}function Fg(e,t){let r=new Map;for(let i of Nr([e],t.adapter)){let n=t.adapter.getLink(i);n&&(r.set(String(i),{...n}),t.adapter.removeLink(i))}return r}async function bd(e,t,r){let{adapter:i,ctx:n,scheduler:o,sector:a}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:C.INVALID_PROGRESS_VALUE};let s=n.activityReader.getActivity(e.activityId);if(!s)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let c=Pe(D.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===dn.ACTION_BUTTON&&(l.reason===ti.HAS_LOOKAHEAD_TASKS||l.reason===ti.SUMMARY)))return{ok:!1,reason:l.reason,...l.alertKey?{alertKey:l.alertKey}:{}};let d=c.transform(s,e.newValue,n,e.newValue),u=Le(e.activityId,d),f=await Q(i,u);Oe(i,e.activityId,d),Cc(e.activityId,e.newValue,i),Ee(e.activityId,d.postProcessors??[],i);let p=d.needsAutoSchedule?n.hierarchy.hasChildren(e.activityId)?Et.ROOTS:e.activityId:null,{scheduledIds:y}=await X({adapter:i,scheduler:o,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:p,recomputeParentsFrom:[],collectDirty:A=>hn(e.activityId,u,A),now:r.now,options:t}),g=(d.trackingEvents??[]).map(A=>({name:A.name,properties:A.properties??{}}));return{ok:!0,changes:await G(i,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:y,trackingEvents:g,hoursPerDay:a.hoursPerDay})}}function xg(e){return e===D.START_DATE||e===D.END_DATE}async function wd(e,t,r){if(e.edits.some(y=>!xg(y.column)))return{ok:!1,reason:C.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=Mg(y,r);if(a.push(g.verdict),!g.verdict.ok||!g.changes)continue;let A=Le(y.activityId,g.changes);Ug(s,A,r);for(let m of A)c.add(m);let k=kr(i,y.activityId),_=pn(i,String(y.activityId));Oe(i,y.activityId,g.changes),Ee(y.activityId,g.changes.postProcessors??[],i,_),d.push(...Rr(k,i,y.activityId)),f||=!!g.changes.needsAutoSchedule;for(let m of g.changes.trackingEvents??[])l.push({name:m.name,properties:m.properties??{}});let L=Je(y.activityId,g.changes.constraintWarning);L&&u.push(L)}let{scheduledIds:p}=await X({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:f?Et.ROOTS:null,recomputeParentsFrom:c,now:r.now,options:t});return{ok:!0,verdicts:a,changes:await G(i,{source:e,beforeSnap:s,touchedIds:c,scheduledIds:p,sirDetection:Lt.BEFORE_DIFF,links:d,trackingEvents:l,warnings:u,hoursPerDay:o.hoursPerDay})}}function Mg(e,t){let{ctx:r}=t,i=e.activityId,n=Pe(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??C.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??C.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??C.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 Ug(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,it(o))}}var Pa=D.CUSTOM_ID;async function Fd(e,t,r){let{adapter:i,scheduler:n,sector:o}=r;e.edits.some(E=>E.column===D.DURATION)&&n.invalidateExpandedLinksCache();let s=[],c=new Map,l=new Map,d=new Set,u=new Set,f=[],p=[],y=[],g=new Set,A=new Map,k=new Map,_=!1;for(let E of e.edits){let S=Kg(E,r,e.eventSource);if(s.push(S.verdict),!S.verdict.ok||!S.changes)continue;let O=Je(E.activityId,S.changes.constraintWarning);O&&y.push(O);let V=Le(E.activityId,S.changes);qg(c,V,r);for(let pt of V)u.add(pt);$g(l,E,c),Dn(E.column)&&d.add(String(E.activityId)),Wg(A,E);let $=kr(i,E.activityId),et=pn(i,String(E.activityId)),ct=Yg(E,r),lt=S.changes;Oe(i,E.activityId,lt),Ee(E.activityId,S.changes.postProcessors??[],i,et),Bg(g,y,E),Hg(k,E,i.getActivity(E.activityId)),Gg(E,ct,r),p.push(...Rr($,i,E.activityId)),_||=!!S.changes.needsAutoSchedule;for(let pt of S.changes.trackingEvents??[])f.push({name:pt.name,properties:pt.properties??{}})}let L={action:e,autoscheduleFrom:_?Et.ROOTS:null,recomputeParentsFrom:u,now:r.now,options:t},m=Vg(A,k,c,y,g,r),b=l.size>0,{scheduledIds:w}=await(b?kn({adapter:i,scheduler:n,sector:o,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:L,revertTargets:[...l].filter(([E])=>!d.has(E)).map(([E,S])=>({activityId:E,priorConstraintDate:S})),revert:(E,S)=>_n(E,S,i,r.ctx.calendars)}):X({adapter:i,scheduler:n,sector:o,defaultBaseCalendarId:r.defaultBaseCalendarId},L));return{ok:!0,verdicts:s,changes:await G(i,{source:e,beforeSnap:c,touchedIds:u,scheduledIds:w,sirDetection:Lt.BEFORE_DIFF,links:p,trackingEvents:f,warnings:m,hoursPerDay:o.hoursPerDay})}}function Bg(e,t,r){if(!Dr(r.column))return;let i=String(r.activityId);for(let n of t)String(n.activityId)===i&&e.add(n)}function Hg(e,t,r){!Dr(t.column)||!r||e.set(String(t.activityId),{constraintType:r.constraintType,constraintDate:r.constraintDate?new Date(r.constraintDate.getTime()):null})}function Wg(e,t){if(t.column!==D.START_DATE&&t.column!==D.END_DATE)return;let r=String(t.activityId),i=e.get(r)??new Set;i.add(t.column),e.set(r,i)}function Vg(e,t,r,i,n,o){let a=new Set,s=[],c=new Set;for(let[l,d]of e){if(!d.has(D.START_DATE)||!d.has(D.END_DATE))continue;let u=t.get(l);if(u){o.adapter.setActivityFields(l,u);for(let A of n)String(A.activityId)===l&&c.add(A);continue}let f=r.get(l),p=o.adapter.getActivity(l);if(!f?.constraintType||!f.constraintDate||!p)continue;let y=Fe(f.constraintType,p.startDate,p.endDate),g=jg(f.constraintType,f.constraintDate,y);if(a.add(l),g){o.adapter.setActivityField(l,"constraintType",v.SNET),o.adapter.setActivityField(l,"constraintDate",new Date(p.startDate.getTime()));let A=Je(l,Ai(f.constraintType,f.constraintDate,y));A&&s.push(A);continue}o.adapter.setActivityField(l,"constraintType",f.constraintType),o.adapter.setActivityField(l,"constraintDate",f.constraintDate)}return[...i.filter(l=>!c.has(l)&&!a.has(String(l.activityId))),...s]}function jg(e,t,r){return e===v.MSO||e===v.MFO?t.getTime()!==r.getTime():gi(e,t,r).violated}function Kg(e,t,r){let{ctx:i}=t,n=e.activityId,o=Pe(e.column);if(!o)return{verdict:{activityId:n,ok:!1,reason:C.NO_PIPELINE_FOR_COLUMN},changes:null};let a=i.activityReader.getActivity(e.activityId);if(!a)return{verdict:{activityId:n,ok:!1,reason:C.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??C.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??C.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??C.INVALID,...d.notification?.messageKey?{alertKey:d.notification.messageKey}:{}},changes:null};if(e.column===Pa&&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:C.CUSTOM_ID_DUPLICATE},changes:null}}let u=o.transform(a,c.value,i,c.raw);return{verdict:{activityId:n,ok:!0},changes:u}}function Yg(e,t){if(e.column!==Pa)return null;let r=t.adapter.getActivity(e.activityId),i=r?r.customId:null;return typeof i=="string"?i:null}function Gg(e,t,r){if(e.column!==Pa)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 $g(e,t,r){if(!Dr(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 qg(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,it(o))}}var Nt={INVALID_BASELINE_POINT:"invalid_baseline_point",UNKNOWN_CONSTRAINT:"unknown_constraint",ORPHAN_ACTIVITY:"orphan_activity",INVALID_LINK:"invalid_link",DUPLICATE_LINK:"duplicate_link"},zg=[Nt.INVALID_BASELINE_POINT,Nt.UNKNOWN_CONSTRAINT,Nt.ORPHAN_ACTIVITY,Nt.INVALID_LINK,Nt.DUPLICATE_LINK],br=()=>{};function xd(){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(zg.flatMap(n=>{let o=e.get(n);return o===void 0?[]:[Object.freeze({code:n,count:o,sampleIds:Object.freeze([...t.get(n)??[]])})]}))}}function Md(e){return typeof e=="string"&&e.length>0?fe(e):e instanceof Date?e:null}function La(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 Bn(e,t,r,i=!1){let n=La(e.duration),o=La(e.cost),a=La(e.hh_work);if(n===null||o===null||a===null)return r&&r.record(Nt.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;let s=Md(e.start_date),c=Md(e.end_date),l=i&&n===0&&s!==null&&c!==null&&c<s;return l&&t.warn("[baseline] normalizing inverted zero-duration milestone to one instant"),{startDate:s,endDate:l?s:c,durationDays:n,cost:o,workHours:a,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 Ud(e,t,r,i=br){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(Nt.INVALID_BASELINE_POINT,String(c??"unknown"));continue}let l=n.get(c);if(l===void 0){i(Nt.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){let l=e.getActivity(s)?.type===T.MILESTONE;e.setActivityField(s,"baselinePoints",c.map(d=>Bn(d,r,{record:i,sampleId:s},l)).filter(d=>d!==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 Jg(e){let t=At(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function Bd(e){let t=[];return e.forEachActivity((r,i)=>{let n=Jg(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 Hn(e,t,r,i,n=null,o=br){let a=new Set;for(let s of Ud(e,t,i,o))a.add(s);if(r)for(let s of Tr(e,r,n))a.add(s);for(let s of Bd(e))a.add(s);for(let s of Er(e))a.add(s);return[...a]}function Hd(e,t){t.forEachActivity((r,i)=>{t.setActivityField(i,D.PONDERATOR,0)}),t.forEachActivity((r,i)=>{t.getChildren(i).length>0&&En(String(i),e,t)})}function Wn(e,t){Hd(t,e.adapter),Jr(e.adapter),e.now&&(Tr(e.adapter,e.now,e.defaultBaseCalendarId??null),Xe(e.adapter,e.now)),Er(e.adapter),e.now&&pe(e.adapter,e.sector.statusCriteria)}function Wd(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 Vd(e,t){let r=await Q(t.adapter,new Set(t.adapter.getAllIds())),i=Wd(t),n=Hn(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return Wd(t)!==i&&Wn(t,t.sector.activityCreter??mt.DURATION),{ok:!0,changes:await G(t.adapter,{source:e,beforeSnap:r,touchedIds:n,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function Xg(e){return Object.values(mt).includes(e)}async function jd(e,t){if(!Xg(e.criterion))return{ok:!1,reason:C.INVALID_VALUE};let r=new Set(t.adapter.getAllIds()),i=await Q(t.adapter,r);return Wn(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:await G(t.adapter,{source:e,beforeSnap:i,touchedIds:r,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function Kd(e,t){let r=mn(e.criteria),i=new Set(t.adapter.getAllIds()),n=await Q(t.adapter,i),o=pe(t.adapter,r);return t.sector.statusCriteria=r,{ok:!0,changes:await G(t.adapter,{source:e,beforeSnap:n,touchedIds:o,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function Gd(e,t,r){let i=new Map,n=new Set;for(let a of r.adapter.getAllActivities()){if(!Zg(a,r))continue;let s=r.ctx.calendars.getCalendar(a.calendarId);if(!s)continue;let c=s.isWorkTime(a.startDate,ft.HOUR)?Qg(a.startDate):a.startDate,l=s.getClosestWorkTime({date:c,direction:K.FUTURE,unit:ft.HOUR}),d=s.calculateEndDate(l,a.durationHours);if(Yd(l,a.startDate)&&Yd(d,a.endDate))continue;let u=String(a.id);i.set(u,it(a)),n.add(u),r.adapter.setActivityFields(u,{startDate:l,endDate:d})}let{scheduledIds:o}=await X({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:Et.ROOTS,recomputeParentsFrom:n,now:r.now,options:t});return{ok:!0,changes:await G(r.adapter,{source:e,beforeSnap:i,touchedIds:n,scheduledIds:o,hoursPerDay:r.sector.hoursPerDay})}}function Zg(e,t){return e.progress===0&&!zt(e.type,t.adapter.hasChildren(e.id))}function Yd(e,t){return e.getTime()===t.getTime()}function Qg(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var $d=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","cost","hasCustomPonderator","subcontractId","responsableIds","tagIds"];function tA(e){let t={};for(let r of $d)Object.assign(t,{[r]:F(e[r])});return t}function eA(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 qd(e,t){let r=new Set(t.adapter.checkedIds().map(String));if(r.size===0)return{ok:!1,reason:C.NO_ACTIVITY_SELECTION};let i=eA(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:tA(a)}}),links:t.adapter.getAllLinks().filter(o=>r.has(String(o.source))&&r.has(String(o.target))).map(o=>F(o))};let n=Si({kind:h.SELECTION_REPLACE,activityIds:[]},{adapter:t.adapter});return n.ok?{...n,changes:{...n.changes,source:e}}:n}function zd(e,t){return t.value=null,{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}}function rA(e,t){let r=t.getActivity(e);return r?r.parentId==null?t.getRootIds().length===1?{ok:!0,parentId:r.id,beforeSiblingId:t.getChildren(r.id)[0]}:{ok:!0,parentId:"0",afterSiblingId:e}:t.hasChildren(r.id)?{ok:!0,parentId:r.id,beforeSiblingId:t.getChildren(r.id)[0]}:{ok:!0,parentId:String(r.parentId),afterSiblingId:e}:{ok:!1,reason:C.ANCHOR_SIBLING_NOT_FOUND}}var Jd=()=>({ok:!1,reason:C.ACTIVITY_PASTE_INVARIANT_FAILED});async function Xd(e,t,r){let i=r.activityClipboard.value;if(i===null)return{ok:!1,reason:C.CLIPBOARD_EMPTY};let n=rA(e.destination.afterSiblingId,r.adapter);if(!n.ok)return n;let o=await Q(r.adapter,new Set),a=new Set,s=new Map,c=[],l;for(let g of i.activities){let A=s.get(g.originalParentId),k=A===void 0?l??n.afterSiblingId:void 0,_=A===void 0&&k===void 0?n.beforeSiblingId:void 0,L=await di({kind:h.ACTIVITY_CREATE,parentId:A??n.parentId,...k===void 0?{}:{afterSiblingId:k},..._===void 0?{}:{beforeSiblingId:_},overrides:F(g.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:e.destination.afterSiblingId});if(!L.ok)return L;s.set(g.originalId,L.newId),c.push(L.newId),A===void 0&&(l=L.newId)}let d=Dt(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 A=s.get(g.source),k=s.get(g.target);if(A===void 0||k===void 0)return Jd();let _={kind:St.CREATE,source:A,target:k,type:g.type,lag:g.lag},L=Ce(_,{port:r.adapter,newLinkId:r.linkIdGen.next});if(!L.applied)return Jd();f.push({op:_,finalLinkId:L.linkId,rejected:null})}let{scheduledIds:p}=await X({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=_r(f,new Map,r.adapter);return{ok:!0,changes:await G(r.adapter,{source:e,beforeSnap:o,touchedIds:a,scheduledIds:p,links:y,hoursPerDay:r.sector.hoursPerDay})}}async function Zd(e,t,r){return e.kind===h.ACTIVITY_COPY?qd(e,{adapter:r.adapter,clipboard:r.activityClipboard}):e.kind===h.CALENDAR_RECONCILE?Gd(e,t,r):e.kind===h.ACTIVITY_CLIPBOARD_CLEAR?zd(e,r.activityClipboard):e.kind===h.ACTIVITY_PASTE_COPIED?Xd(e,t,r):e.kind===me?hd(e,t,r):e.kind===h.PERSISTENCE_ACKNOWLEDGE?Sd(e,r):e.kind===h.BASELINE_APPLY?Vd(e,r):e.kind===h.PONDERATOR_CRITERION_SET?jd(e,r):e.kind===h.STATUS_CRITERIA_SET?Kd(e,r):e.kind===h.LINK_CREATE||e.kind===h.LINK_UPDATE||e.kind===h.LINK_DELETE?Gl(e,t,r):e.kind===h.LINKS_BATCH?$l(e,t,r):e.kind===h.ACTIVITY_CREATE?fd(e,t,r):e.kind===h.ACTIVITY_DELETE?dd(e,t,r):e.kind===h.ACTIVITY_MOVE?Pd(e,t,r):e.kind===h.ACTIVITY_INDENT?Ld(e,t,r):e.kind===h.ACTIVITY_OUTDENT?Od(e,t,r):e.kind===h.ACTIVITY_TYPE_SET?Nd(e,t,r):e.kind===h.ACTIVITY_SET_PROGRESS?bd(e,t,r):e.kind===h.DATES_BATCH?wd(e,t,r):e.kind===h.BULK_EDIT?Fd(e,t,r):e.kind===h.SELECTION_TOGGLE?Ss(e,Oa(r)):e.kind===h.SELECTION_REPLACE?Si(e,Oa(r)):e.kind===h.VISIBILITY_SET?Ts(e,Oa(r)):e.kind===h.FILTER_SET?Ms(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind===h.SORT_SET?js(e,{adapter:r.adapter}):e.kind===h.VIEW_ATTRIBUTES_SET?Ks(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind===h.GROUP_SET?Ys(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind===h.SIR_SYNC?Id(e,r):e.kind===h.ACTIVITY_LOOKAHEAD_SYNC?Td(e,t,r):e.kind===h.ACTIVITY_LOOKAHEAD_CONVERT?_d(e,t,r):e.kind===h.SCHEDULE_AUTO_SCHEDULE?Vl(e,t,r):e.kind===h.INLINE_EDIT&&(e.column===D.CUSTOM_PREDECESSORS||e.column===D.CUSTOM_SUCESSORS)?ql(e,t,r):e.kind!==h.INLINE_EDIT?Gs(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):Yl(e,t,r)}function Oa(e){return{adapter:e.adapter}}var iA=new Set(["startDate","endDate","constraintDate"]);function Qd(e,t){return iA.has(e)&&typeof t=="string"?new Date(t):t}function tu(e,t={}){let r=t.defaultUnit??ft.HOUR;return{getCalendar(i){let n=e.getCalendar(String(i));return n?nA(n,r):null}}}function nA(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 oA(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function ir(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function nr(e){return ir(e)&&!isNaN(e.getTime())}var aA={}.constructor.toString();function sA(e){var t=e.constructor.toString();return t!==aA}function cA(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function Qt(e){var t,r;if(e&&typeof e=="object")switch(!0){case ir(e):r=new Date(e);break;case oA(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=Qt(e[t]);break;default:if(sA(e))r=Object.create(e);else{if(cA(e))return r=e,r;r={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(r[t]=Qt(e[t]));break}return r||e}function wr(e,t,r){for(var i in t)(e[i]===void 0||r)&&(e[i]=t[i]);return e}function eu(e){return typeof e<"u"}var Vn;function Na(){return Vn||(Vn=new Date().valueOf()),Vn++,Vn}function Wt(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var dA=(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)},uA=(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)},ru={date_to_str:dA,str_to_date:uA},fA=(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}}),pA=(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])},iu={date_to_str:fA,str_to_date:pA};function nu(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=ru;return o()&&(l=iu),l.date_to_str(s,c,e)},str_to_date:function(s,c){var l=ru;return o()&&(l=iu),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 ba(e,t,r,i,n){return this.date=e,this.unit=t,this.task=r,this.id=i,this.calendar=n,this}function wa(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 Fa(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 yA(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 ou=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(ir(t)?t={date:t}:t=wr({},t),!nr(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 ba)return t;var r;if(t.date?r=new ba(t.date,t.unit,t.task,null,t.calendar):r=new ba(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!nr(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 wa)return r;var i;if(ir(r)?i=new wa(r):i=new wa(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,!nr(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=yA,i;if(t instanceof r)return t;if(ir(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,!nr(i.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!nr(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 Fa)return o;var a;if(ir(o)?a=new Fa(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):a=new Fa(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,!nr(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 au(){}au.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=Qt(e.getConfig()),i=Qt(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 xa=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}},Ma=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={}}},Ua=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 hA(){return typeof Map<"u"?new xa:new Ma}var Ba=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 Ha(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=hA(),this._largeUnitsCache=new Ua(this),this._dateDurationCache=new Ba,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}Ha.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=Wt(this._getMinutesPerDay,this):s=Wt(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 Ha))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(Wt(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(Wt(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,A=null,k=null,_=c.length-1;_>=0;_--)if(c[_].start<y-1&&c[_].end>=y-1){g=!0,A=c[_],k=c[_-1];break}if(g)if(y===A.end&&p>=A.durationMinutes)n+=A.durationMinutes,i=this.$gantt.date.add(i,-A.durationMinutes,"minute");else if(!o&&p<=y/60-A.startMinute)n+=p,i=this.$gantt.date.add(i,-p,"minute");else if(o)p<=y/60-A.startMinute?(n+=p,i=this.$gantt.date.add(i,-p,"minute")):(n+=y/60-A.startMinute,k?i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,k.end)):i=this.$gantt.date.day_start(i));else{var L=this._getMinutesPerHour(i);L<=p?(n+=L,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 m=this._getClosestWorkTimePast(i,"hour");if(m.valueOf()===i.valueOf()){var m=this.$gantt.date.add(i,-1,"day"),b=this._getWorkHours(m);if(b.length){var w=b[b.length-1];m.setUTCSeconds(w.durationSeconds)}}i=m}else i=this._getClosestWorkTimePast(new Date(i-1),"hour")}if(n<t){var E=t-n;a=this._subtractMinutesUntilHourStart(i,E),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 A=this._getMinutesPerHour(i);A<=u?(n+=A,l?i=this.$gantt.date.add(i,A,"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 k=t-n;o=this._addMinutesUntilHourEnd(i,k),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 ui={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 mA(){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 IA=mA();function su(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=ui.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))}su.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 au,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 Ha(this.$gantt,ou(this.$gantt));t.id=String(Na());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=Qt(e.getConfig()):e.worktime?t=Qt(e.worktime):t=Qt(e);var r=Qt(this.defaults.fulltime.worktime);return wr(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=ui.getResourceProperty(t),Array.isArray(e[n])&&e[n].length)t.dynamic_resource_calendars?i=IA.getCalendarIdFromMultipleResources(e[n],this):r=this.getResourceCalendar(e[n]);else if(this._legacyConfig===void 0&&(this._legacyConfig=ui.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var i=ui.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=ui.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||Na(),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 Wa(e,t){this.argumentsHelper=t,this.$gantt=e}Wa.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 Wa},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 cu(e){this.$gantt=e.$gantt,this.argumentsHelper=ou(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new Wa(this.$gantt,this.argumentsHelper)}cu.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 gA=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:Wt(e.mergeCalendars,e),createCalendar:Wt(e.createCalendar,e),addCalendar:Wt(e.addCalendar,e),getCalendar:Wt(e.getCalendar,e),getCalendars:Wt(e.getCalendars,e),getResourceCalendar:Wt(e.getResourceCalendar,e),getTaskCalendar:Wt(e.getTaskCalendar,e),deleteCalendar:Wt(e.deleteCalendar,e)}},AA={create:gA};function lu(e){var t=new su(e),r=new cu(t),i=AA.create(t,r);wr(e,i)}var du={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 uu(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||du,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:eu,mixin:wr,copy:Qt,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=nu(r),r.date.init(),lu(r),r}function vA(e={}){let t=uu(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 fu={createCalendar:vA};var hB=3600*1e3;function mu(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:CA}=fu,fi="__replay_default__";function SA(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 pu={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},yu="__main_global__",TA={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function hu(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 EA(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:SA(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function Iu(e){let t=CA({config:{work_time:!0}});t.addCalendar({id:fi,worktime:pu}),t.addCalendar({id:yu,worktime:TA});let r=new Set(e.filter(d=>!hu(d.worktime)).map(d=>String(d.id))),i=e.filter(d=>hu(d.worktime));for(let d of i)t.addCalendar({id:d.id,worktime:d.worktime?EA(d.worktime):pu});let n=tu(t),o=n.getCalendar(fi),a=n.getCalendar(yu);if(!o||!a)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let s=new Set([fi]);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 gu(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 DA(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 DA(e,t){let r=[],i=new Bt;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 jn=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=Au(t);return this.reader.getCalendar(r??fi)}getClosestWorkTime(t){let r=`${ja(t.task)}|${t.dir}|${t.date.getTime()}`;return Va(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:ft.HOUR}))}calculateEndDate(t){let r=`${ja(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return Va(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${ja(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return Va(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 Va(e,t,r){let i=e.get(t);if(i!==void 0)return i;let n=r();return e.set(t,n),n}var _A="__default__";function Au(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function ja(e){return Au(e)??_A}var Kn=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&&!B(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||B(r)?null:this.activities.get(r)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,r){if(this._dirty)return;if(B(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(B(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?ki(n,o):String(r).localeCompare(String(i))};this._roots.sort(t);for(let r of this._childrenByParent.values())r.sort(t)}};var Yn=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}};function vu(e,t,r,i,n,o){return{valueId:t,id:Oi(e,t),label:r,color:i,level:n,sequence:o,children:new Map,activities:[]}}function Cu(e){let t=e.activities.length;for(let r of e.children.values())t+=Cu(r);return t}function Su(e,t){let r=[...e.children.values()];return r.sort((i,n)=>i.valueId===Ve?1:n.valueId===Ve?-1:i.sequence!==n.sequence?i.sequence-n.sequence:i.valueId.localeCompare(n.valueId)),t===Pt.DESCENDING&&r.reverse(),r}function kA(e,t,r,i){let n=new Set(e.map(a=>String(a.id))),o=new Set(n);for(let a of n){let s=r(a);for(;s!==null;)o.add(String(s)),s=r(s)}for(let a of t)o.has(String(a.id))&&i.push({kind:We.ACTIVITY,activityId:String(a.id)})}function Tu(e,t,r,i,n){if(n.push({kind:We.GROUP,id:e.id,label:e.label,level:e.level,color:e.color,activityCount:Cu(e)}),!t.collapsedIds.has(e.id)){for(let o of Su(e,t.direction))Tu(o,t,r,i,n);if(e.activities.length!==0){if(t.includeWbs){kA(e.activities,r,i,n);return}for(let o of e.activities)n.push({kind:We.ACTIVITY,activityId:String(o.id)})}}}function Eu(e){let t=e.activitiesInVisualOrder.filter(a=>e.isVisible(a.id));if(e.group===null||e.catalog===null)return t.map(a=>({kind:We.ACTIVITY,activityId:String(a.id)}));let{group:r,catalog:i}=e,n=vu(r.attributeKey,"","",null,-1,0);for(let a of t){let s=i.assignmentByActivityId.get(String(a.id)),c=s===void 0?[Ve]:Rs(i,s,r.depth),l=n;c.forEach((d,u)=>{let f=l.children.get(d);if(f===void 0){let p=i.valueById.get(d);f=vu(r.attributeKey,d,p?.label??(d===Ve?Pi:d),p?.color??null,u,p?.sequence??Number.MAX_SAFE_INTEGER),l.children.set(d,f)}l=f}),l.activities.push(a)}let o=[];for(let a of Su(n,r.direction))Tu(a,r,e.activitiesInVisualOrder,e.parentOf,o);return o}var Gn=class e{catalogs=new Map;group=null;getCatalog(t){return this.catalogs.get(t)??null}getCatalogMap(){return this.catalogs}setCatalogs(t){let r=new Map;for(let i of t)r.set(i.key,_s(i));this.catalogs=r}getGroup(){return this.group}setGroup(t){this.group=t}clone(){let t=new e;return t.catalogs=new Map(this.catalogs),t.group=this.group===null?null:F(this.group),t}};var Fr=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,visualRows:null,orderComparator:null};_writeCapture=new Tn;_viewState=new Yn;_viewAttributes=new Gn;_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 jn(Iu(this._calendarSnapshot)),this._flags=PA(t),this._hierarchy=new Kn(this._activities),this._hierarchy.rebuild()}fork(){let t=new e({activities:this.getAllActivities().map(ue),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._viewAttributes=this._viewAttributes.clone(),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=Hs(this).map(t=>String(t.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null,this.invalidateVisualRows()}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){this._captureViewStateOnce();let i=this._viewState.setVisible(String(t),r);return i&&this.invalidateVisualRows(),i}getActiveFilter(){return this._viewState.getActiveFilter()}setActiveFilter(t){this._captureViewStateOnce(),this._viewState.setActiveFilter(t),this._filterProjection=null,this.invalidateVisualRows()}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._viewAttributes.getCatalogMap()),this._cache.orderComparator)}invalidateDerivedOrder(){this._cache.orderComparator=null,this._cache.visualOrderIds=null,this.invalidateVisualRows()}getViewAttributeCatalogMap(){return this._viewAttributes.getCatalogMap()}setViewAttributeCatalogs(t){this._viewAttributes.setCatalogs(t),this.invalidateDerivedOrder()}getGroup(){return this._viewAttributes.getGroup()}setGroup(t){this._viewAttributes.setGroup(t),this.invalidateVisualRows()}invalidateVisualRows(){this._cache.visualRows=null}getVisualRows(){if(this._cache.visualRows)return this._cache.visualRows;let t=this._viewAttributes.getGroup(),r=t===null?null:this._viewAttributes.getCatalog(t.attributeKey),i=[];for(let n of this.getVisualOrderIds()){let o=this.getActivity(n);o!==null&&i.push(o)}return this._cache.visualRows=Eu({activitiesInVisualOrder:i,isVisible:n=>this.isVisible(n),parentOf:n=>this.getParentId(n),group:t,catalog:r}),this._cache.visualRows}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))??Du}getIncomingLinkIds(t){return this._incoming.get(String(t))??Du}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,Ya(n,r),r===x.PARENT&&this._hierarchy.markDirty(),Ka(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,Qd(r,i)),Ya(n,r),r===x.PARENT&&this._hierarchy.markDirty(),Ka(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)),Ya(i,o),o===x.PARENT&&(n=!0),Ka(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){_u(this._outgoing,String(t.source),t.id),_u(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),Ga(r,t.id));let i=this._incoming.get(String(t.target));i&&this._incoming.set(String(t.target),Ga(i,t.id))}_removeLinkRef(t,r,i){let n=t.get(r);n&&t.set(r,Ga(n,i))}_insertLinkRefInOrder(t,r,i){let n=new Set;for(let s of this._links.keys()){if(String(s)===String(i))break;n.add(String(s))}let o=[...t.get(r)??[]],a=o.findIndex(s=>!n.has(String(s)));o.splice(a<0?o.length:a,0,i),t.set(r,o)}setLinkField(t,r,i){let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),n[r]=i)}setLinkEndpoints(t,r,i){let n=this.getLink(t);if(!n)return;let o=String(n.source)!==String(r),a=String(n.target)!==String(i);!o&&!a||(this._writeCapture.noteLinkField(String(t),n),o&&(this._removeLinkRef(this._outgoing,String(n.source),n.id),n.source=r,this._insertLinkRefInOrder(this._outgoing,String(r),n.id)),a&&(this._removeLinkRef(this._incoming,String(n.target),n.id),n.target=i,this._insertLinkRefInOrder(this._incoming,String(i),n.id)))}setLinkFieldDynamic(t,r,i){let n=this.getLink(t);if(n){if(r===xt.SOURCE){this.setLinkEndpoints(t,String(i),n.target);return}if(r===xt.TARGET){this.setLinkEndpoints(t,n.source,String(i));return}RA(r)&&(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===kt.LINK_ADD&&this._detachLink(r.linkId)}_undoInserts(t){for(let r of t)r.kind===kt.INSERT&&this._activities.delete(r.activityId)}_reInsertRemovedActivities(t){for(let r of t)r.kind===kt.REMOVE&&this._activities.set(r.activityId,r.before)}_reAddRemovedLinks(t){for(let r of t)r.kind===kt.LINK_REMOVE&&this._attachLink(r.before)}_restoreLinkFields(t){for(let r of t){if(r.kind!==kt.LINK_FIELD)continue;let i=this._links.get(r.linkId);if(i){this.setLinkEndpoints(r.linkId,r.before.source,r.before.target);for(let n of Object.keys(i))Object.hasOwn(r.before,n)||Reflect.deleteProperty(i,n);Object.assign(i,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))}},Du=[];function RA(e){return e===xt.LAG||e===xt.TYPE||e===xt.FREE_SLACK_HOURS||e===xt.IS_CRITICAL}function Ka(e){return e===x.PARENT||e===x.CORRELATIVE_ID}function Ya(e,t){t!==x.START_DATE&&t!==x.END_DATE&&t!==x.TYPE||(e.calendarDuration=ie(e))}function Ga(e,t){return e.filter(r=>String(r)!==String(t))}function _u(e,t,r){let i=e.get(t);i?i.push(r):e.set(t,[r])}function PA(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 $a(e,t){let r=e.getActivity(t);return r?F(r):null}function ku(e){return e.getAllActivities().map(F)}function Ru(e){return e.getAllIds().map(String)}function Pu(e,t){e.forEachActivity((r,i)=>t(i))}function Lu(e,t){let r=t==="0"?qa(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 qa(e,t){return jt(t,e)}function Ou(e){return e.checkedIds().map(String)}function Nu(e,t){if(t==="0"){let r=!1;return e.forEachActivity(i=>{r||=B(i.parentId)}),r}return e.getChildren(t).length>0}function za(e,t){let r=e.getLink(t);return r?Ut(r):null}function bu(e){return e.getAllLinks().map(t=>Ut(t))}function $n(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function LA(e){return e.reduce((t,r)=>$n(r)<$n(t)?r:t)}function OA(e){return e.reduce((t,r)=>$n(r)>$n(t)?r:t)}function NA(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function wu(e){let t=[...e].find(o=>o.is_default);if(!t)return null;let r=NA(t);if(r.length===0)return null;let i=r.map(o=>o.split("-")[0]),n=r.map(o=>o.split("-")[1]);return{startHour:LA(i),endHour:OA(n)}}function Ja(e,t){return{calendars:e.calendarReader,hierarchy:gu(e),activityReader:mu(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay}}function Fu(e){return er(e)}var bA=new Set(["freeSlackHours","isCritical"]);function wA(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 Bu(e){let t=e.activities.map(n=>({...n,after:null})),r=e.links.map(n=>wA(n,bA)).filter(n=>n!==null),i=e.source.kind===me?{...e.source,items:[],links:[]}:e.source;return F({...e,source:i,activities:t,links:r})}function Xa(e,t,r,i,n,o,a){return{changeSet:e,beforeSnap:t,beforeLinks:xu(r),afterSnap:i,afterLinks:xu(n),progressFallbackBefore:o,progressFallbackAfter:a}}function xu(e){if(e)return new Map(Array.from(e,([t,r])=>[t,{...r,freeSlackHours:null,isCritical:!1}]))}function Hu(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),it(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 Wu(e){return e.kind!==h.INLINE_EDIT||!si.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function Mu(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 Vu(e,t){if(!Mu(e)||!Mu(t))return!1;let r=e.changeSet.activities[0],i=t.changeSet.activities[0];return!!r&&!!i&&String(r.id)===String(i.id)}function ju(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 Xa(s)}var xr={RECORD:"record",SKIP:"skip",CHECKPOINT_ON_SUCCESS:"checkpoint-on-success"},ut={BEFORE:"before",AFTER:"after"};function Ku(e){return e.kind===h.PERSISTENCE_ACKNOWLEDGE?xr.CHECKPOINT_ON_SUCCESS:e.kind===h.SIR_SYNC||e.kind===h.CALENDAR_RECONCILE||e.kind===h.ACTIVITY_LOOKAHEAD_SYNC||e.kind===h.BASELINE_APPLY||e.kind===h.PONDERATOR_CRITERION_SET||e.kind===h.STATUS_CRITERIA_SET||e.kind===h.ACTIVITY_CLIPBOARD_CLEAR||e.kind===h.ACTIVITY_COPY||e.kind===h.SELECTION_TOGGLE||e.kind===h.SELECTION_REPLACE||e.kind===h.VISIBILITY_SET||e.kind===h.FILTER_SET||e.kind===h.SORT_SET||e.kind===h.VIEW_ATTRIBUTES_SET||e.kind===h.GROUP_SET?xr.SKIP:xr.RECORD}function Za(e){for(let t of e.changeSet.activities)if(t.kind===N.CREATED||t.kind===N.DELETED||t.kind===N.UPDATED&&t.fields&&D.CUSTOM_ID in t.fields)return!0;return!1}function Qa(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:Uu(a.fields,r),after:c?it(c):null})}else if(a.kind===N.DELETED)if(r===ut.BEFORE){let c=e.getActivity(s);i.push({id:s,kind:N.CREATED,after:c?it(c):null})}else i.push({id:s,kind:N.DELETED,after:null});else if(r===ut.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?it(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:Uu(a.fields,r),after:c?Ut(c):null})}else if(a.kind===N.DELETED)if(r===ut.BEFORE){let c=e.getLink(s);n.push({id:s,kind:N.CREATED,after:c?Ut(c):null})}else n.push({id:s,kind:N.DELETED,after:null});else if(r===ut.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?Ut(c):null})}}let o=(t.changeSet.viewState??[]).map(a=>r===ut.BEFORE?FA(a):a);return{source:{kind:r===ut.BEFORE?ne.UNDO:ne.REDO},activities:i,links:n,calendars:[],trackingEvents:[],effects:[],viewState:o}}function Uu(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([r,i])=>[r,t===ut.BEFORE?{before:F(i.after),after:F(i.before)}:{before:F(i.before),after:F(i.after)}]))}function FA(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 ts(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function Yu(e,t){$u(e,t,ut.BEFORE)}function Gu(e,t){$u(e,t,ut.AFTER)}function $u(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))Ct(e,o.id,a,r===ut.BEFORE?s.before:s.after)}else if(o.kind===N.DELETED)if(r===ut.BEFORE){let a=t.beforeSnap?.get(String(o.id));if(!a)throw new Error(`undo: missing beforeSnap for resurrecting activity ${o.id}`);e.addActivity(it(a))}else e.removeActivity(String(o.id));else if(r===ut.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(it(a))}for(let o of i.links)if(o.kind===N.UPDATED){if(!o.fields)continue;let a=e.getLink(String(o.id)),s=o.fields[xt.SOURCE],c=o.fields[xt.TARGET];a&&(s||c)&&e.setLinkEndpoints(String(o.id),String(s?r===ut.BEFORE?s.before:s.after:a.source),String(c?r===ut.BEFORE?c.before:c.after:a.target));for(let[l,d]of Object.entries(o.fields))l===xt.SOURCE||l===xt.TARGET||Qc(e,String(o.id),l,r===ut.BEFORE?d.before:d.after)}else if(o.kind===N.DELETED)if(r===ut.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===ut.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===ut.BEFORE?o.checked.before:o.checked.after),o.visible&&e.setVisible(o.activityId,r===ut.BEFORE?o.visible.before:o.visible.after);let n=r===ut.BEFORE?t.progressFallbackBefore:t.progressFallbackAfter;for(let[o,a]of n??[])e.setProgressFallback(o,a)}var xA=100,MA=600,qn=class e{constructor(t=xA){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<=MA&&n!==void 0&&Vu(n.entry,t)?(n.entry=ju(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 UA=["parentId","correlativeId"];function zu(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(qu(c.parentId?.before));continue}let a=n.fields;!a||!UA.some(c=>c in a)||(i(o),"parentId"in a&&r.add(qu(a.parentId?.before)))}return r}function qu(e){return e==null?"0":String(e)}function BA(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function HA(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function Ju(e){return{id:String(e.id),worktime:HA(e.worktime)}}function zn(e,t,r,i=[]){let n=t.map(BA),o=[...r.map(Ju),...i.map(Ju)];return{activities:[...e],links:n,calendars:o}}var M={TRACKED:"tracked",IGNORED:"ignored"};var Xu={id:M.IGNORED,proplannerId:M.IGNORED,parentId:M.TRACKED,name:M.TRACKED,description:M.TRACKED,type:M.TRACKED,startDate:M.TRACKED,endDate:M.TRACKED,durationHours:M.TRACKED,constraintType:M.TRACKED,constraintDate:M.TRACKED,autoScheduling:M.TRACKED,calendarId:M.TRACKED,assignedDefaultCalendar:M.IGNORED,dateOrigin:M.TRACKED,progress:M.TRACKED,cost:M.TRACKED,usedCost:M.TRACKED,realCost:M.TRACKED,workHours:M.TRACKED,realWorkHours:M.TRACKED,ponderator:M.TRACKED,hasCustomPonderator:M.TRACKED,correlativeId:M.TRACKED,uniqueCorrelativeId:M.TRACKED,customId:M.TRACKED,subcontractId:M.TRACKED,isLookahead:M.TRACKED,hasLookaheadTasks:M.IGNORED,newActivityIds:M.TRACKED,hasNewActivities:M.TRACKED,isNewActivity:M.IGNORED,pendingRequestIds:M.IGNORED,responsableIds:M.TRACKED,tagIds:M.TRACKED,baselinePoints:M.IGNORED,baselineSnapshot:M.IGNORED,recursiveDurationHours:M.IGNORED,isCritical:M.IGNORED,freeSlackHours:M.IGNORED,calendarDuration:M.IGNORED,expectedProgress:M.IGNORED,expectedProgressBaseline:M.IGNORED,status:M.IGNORED,criticalPath:M.IGNORED},Zu=Object.keys(Xu).filter(e=>Xu[e]===M.TRACKED),Qu=new Set(["startDate","endDate","constraintDate","dateOrigin"]),tf=new Set(["newActivityIds","responsableIds","tagIds"]);function ef(e){let t=Zu.map(r=>[r,WA(r,e[r])]);return Object.fromEntries(t)}function WA(e,t){return Qu.has(e)?t instanceof Date?new Date(t):null:tf.has(e)?Array.isArray(t)?[...t]:[]:t}function pi(e,t){return es(e,t).length>0}function es(e,t){return Zu.filter(r=>!VA(r,e[r],t[r]))}function VA(e,t,r){return Qu.has(e)?jA(t,r):tf.has(e)?KA(t,r):(t??null)===(r??null)}function jA(e,t){let r=e instanceof Date?e.getTime():null,i=t instanceof Date?t.getTime():null;return r===i}function KA(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 rf={id:M.IGNORED,source:M.TRACKED,target:M.TRACKED,type:M.TRACKED,lag:M.TRACKED,freeSlackHours:M.IGNORED,isCritical:M.IGNORED,ganttId:M.IGNORED,sectorId:M.IGNORED,proplannerId:M.IGNORED},YA=Object.keys(rf).filter(e=>rf[e]===M.TRACKED);function Jn(e,t){return YA.some(r=>e[r]!==t[r])}function nf(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?Jn(n,i):!1})}function te(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 of(e,t){for(let r of e)te(r.proplannerId);for(let r of t)te(r.proplannerId)}var Xn=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){of(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(of(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(!te(r.proplannerId)){this.dirtyActivityIds.add(i);continue}let n=ef(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}}),pi(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(!te(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)||!te(r.proplannerId)||i===void 0||pi(r,i.persistable)}linkIsDirty(t,r){let i=this.linksAtLastSave.get(t);return r===null?i!==void 0:!te(r.proplannerId)||i===void 0||Jn(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)||!te(s.proplannerId)||pi(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&&!te(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&&!te(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||!te(n.proplannerId))continue;let o=this.activitiesAtLastSave.get(i);(o===void 0||this.initialCalendarRepairIds.has(i)||pi(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=es(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||!te(n.proplannerId))continue;let o=this.linksAtLastSave.get(i);(o===void 0||Jn(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 af=1440*60*1e3,sf=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/,Zn=7,rs=[!1,!0,!0,!0,!0,!0,!1],cf=new Set(["1","true"]),is=mt.DURATION,lf=v.ASAP,df={ASAP:v.ASAP,ALAP:v.ALAP,SNET:v.SNET,SNLT:v.SNLT,FNET:v.FNET,FNLT:v.FNLT,MSO:v.MSO,MFO:v.MFO,"AS SOON AS POSSIBLE":v.ASAP,"AS LATE AS POSSIBLE":v.ALAP,"START NO EARLIER THAN":v.SNET,"START NO LATER THAN":v.SNLT,"FINISH NO EARLIER THAN":v.FNET,"FINISH NO LATER THAN":v.FNLT,"MUST START ON":v.MSO,"MUST FINISH ON":v.MFO};function uf(e,t){let r=[],i=e.map(o=>{let a=ev(o,t);return o.should_be_showed===!1&&r.push(a.id),a});iv(i);let n=new Set(i.map(o=>o.id));return nv(i,n,t.reporter,t.recordDiagnostic),{activities:i,activityIds:n,hiddenIds:r}}function GA(e,t,r,i){if(!e)return null;let n=df[e.toUpperCase()];return n===void 0?(r(Nt.UNKNOWN_CONSTRAINT,i),t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),lf):n}function $A(e,t,r){let i=GA(e.constraint,t,r,String(e.unique_id)),o=i!==v.ASAP&&i!==v.ALAP&&e.constraint_date?fe(e.constraint_date):null;return{constraintType:i,constraintDate:o}}function qA(e,t,r){if(e==null)return r;let i=String(e);return t.has(i)?i:r}function zA(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 JA(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function ns(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)JA(r)&&t.push(String(r.id));return t}function XA(e){return e==="0"?null:String(e)}function ZA(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 QA(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 tv(e,t,r,i,n){return Array.isArray(e)?e.map(o=>Bn(o,t,{record:r,sampleId:i},n)).filter(o=>o!==null):[]}function ev(e,t){let r=qA(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),i=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),n=Number(e.progress),{constraintType:o,constraintDate:a}=$A(e,t.reporter,t.recordDiagnostic),s=e.type===T.MILESTONE,c=fe(e.start_date),l=s?c:fe(e.end_date),d=s?0:Number(e.duration),u=QA(e,t.reporter);return{id:String(e.unique_id),proplannerId:ZA(e.id),parentId:XA(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:Ye(d,t.hoursPerDay),constraintType:o,constraintDate:a,autoScheduling:je(n),calendarId:r,assignedDefaultCalendar:r!=null&&i,dateOrigin:e.date_origin==null?null:fe(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:rv(e),subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:zA(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:ns(e.pendingRequests),responsableIds:ns(e.responsables),tagIds:ns(e.tags),baselinePoints:tv(e.baseline_points,t.reporter,t.recordDiagnostic,String(e.unique_id),s),baselineSnapshot:null,recursiveDurationHours:Ye(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),calendarDuration:ie({type:e.type,startDate:c,endDate:l}),isCritical:u,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function rv(e){return e.has_childs?null:e.custom_id}function iv(e){let t=e.find(r=>r.correlativeId===0&&r.type===T.PROJECT);t&&(t.parentId=null)}function nv(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(Nt.ORPHAN_ACTIVITY,n.id),n.parentId=null))}function hf(e,t,r,i=null){let a=(e!==void 0&&e.length>0?e:t??[]).map(c=>av(c,i)),s=(r??[]).map(c=>sv(c,i));return{calendars:a,baseCalendars:s,knownCalendarIds:new Set(a.map(c=>c.id)),defaultCalendarId:ov(a)}}function ov(e){let t=e.find(i=>i.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function mf(e,t){let r=pv(e.working_days),{days:i,hours:n}=fv(e,r),o=cv(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 av(e,t){let r=e.baseDefault,i=typeof r=="boolean"?r:void 0;return mf(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:i,exceptionsSource:e.exceptiondays,exceptionRange:t})}function sv(e,t){return mf(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function cv(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let i of e){if(!i)continue;let n=lv(i.from_date,i.to_date,t);if(n.length===0)continue;let o=dv(i);if(o!==void 0)for(let a of n)r[a]=o}return Object.keys(r).length>0?r:null}function lv(e,t,r){let i=ff(e),n=ff(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+=af;return o}function ff(e){if(typeof e!="string")return null;let t=sf.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 dv(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=uv(t);if(r.length>0)return r}}var pf=/^\d{1,2}:\d{2}$/;function uv(e){let t=[];for(let r of e){let i=Af(r?.shift_string);if(!i)continue;if(!i.startsCsv.includes(",")&&!i.endsCsv.includes(",")){let s=i.startsCsv.trim(),c=i.endsCsv.trim();!Qn(s)&&!Qn(c)&&pf.test(s)&&pf.test(c)&&t.push(`${s}-${c}`);continue}let a=gf(i.startsCsv,i.endsCsv).find(s=>s!==null);a&&t.push(a)}return t.sort(If),t}function yf(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 If(e,t){return yf(e)-yf(t)}function fv(e,t){let r=Array.from({length:7},()=>[]),i=(l,d)=>{let u=gf(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=Af(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(If);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 gf(e,t){let r=Array.from({length:Zn},()=>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<=Zn))return r;let a=[...r];for(let s=0;s<i.length;s+=1){let c=i[s],l=n[s];Qn(c)||Qn(l)||(a[s]=`${c}-${l}`)}return a}function Af(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 pv(e){if(typeof e!="string")return[...rs];let t=e.split(",").map(r=>r.trim());return t.length!==Zn?[...rs]:t.map(r=>cf.has(r))}var yv=new Set(["false","null"]);function Qn(e){return!e||yv.has(e)}function hv(e){if(typeof e!="string")return null;let t=fc(e);return t||(vi(e)?e:null)}function mv(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 Cf(e,t){let r=[];for(let i of e)try{r.push(Iv(i,t.knownActivityIds,t.hoursPerDay))}catch(n){t.recordDiagnostic(Nt.INVALID_LINK,String(i.unique_id??i.id)),t.reporter.warn("[parseFromBackend] dropping invalid link",n)}return gv(r,t.recordDiagnostic)}function Iv(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=hv(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=mv(e.id);return{id:i,source:n,target:o,type:a,lag:Kt(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 gv(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=vf(i)>vf(o),s=a?o:i;t(Nt.DUPLICATE_LINK,s.id),a&&r.set(n,i)}return[...r.values()]}function vf(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function Av(e){if(typeof e!="string")return is;switch(e.toUpperCase()){case mt.DURATION:return mt.DURATION;case mt.COST:return mt.COST;case mt.WORK_HOURS:return mt.WORK_HOURS;default:return is}}function vv(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function Cv(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function Sf(e){let t=vv(e),r=Cv(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:Av(e.activity_creter),statusCriteria:jo,ganttId:null}}function to(e,t=yr,r=br){let i=Sf(e.sector),{calendars:n,baseCalendars:o,knownCalendarIds:a,defaultCalendarId:s}=hf(e.calendars,e.sector.calendars,e.baseCalendars,Sv(e.activities)),{activities:c,activityIds:l,hiddenIds:d}=uf(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:i.hoursPerDay,reporter:t,recordDiagnostic:r}),u=Cf(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 Sv(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 os(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 os({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 as(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 as({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 ss(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 ss({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 Tf(e){return!!e&&typeof e=="string"&&e.trim().length>0}function eo(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function ro(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function Ef(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function Df(e,t){return!t&&Tf(e)}function _f(e,t){return t&&Tf(e)}function yi(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function io(e){if(!yi(e))return 0n;try{return BigInt(e)}catch{return 0n}}function Tv(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!yi(t))return r;let i=t.length;return r.padStart(i,"0")}function $t(e,t){let r=io(e),i=io(t),n=r+i;return Tv(n,e)}function no(e,t){let r=io(e),i=io(t);return r<i?-1:r>i?1:0}function oo(e,t){return no(e,t)<=0?e:t}function ao(e,t){return no(e,t)>=0?e:t}function kf(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>oo(t,r))}function Rf(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>ao(t,r))}var ye={PARENT_CONVERSION:"parentConversion",PASTE_REFERENCE:"pasteReference",NO_CONTEXT:"noContext"};function Pf(e){return{prefix:e,baseSuffix:null}}function Lf(e,t){let r=ro(e);return{prefix:eo(e),baseSuffix:$t(r,t)}}function Of(e){return{prefix:e,baseSuffix:null}}function Nf(e,t){return Df(e,t)?ye.PARENT_CONVERSION:_f(e,t)?ye.PASTE_REFERENCE:ye.NO_CONTEXT}function bf(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var so=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?bf(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=kf(i),r.max=Rf(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,bf(i));for(let r of this.processedIds)t.processedIds.add(r);return t}extractPrefix(t){return eo(t)}extractSuffix(t){return ro(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=oo(r,i.min),i.max=ao(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=oo(i,n.min),n.max=ao(i,n.max),n.quantity+=1,this._recalculateNext(r))}else this.prefixMap.set(r,{min:i,max:i,next:$t(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}${$t(r.max,this.suffixIncrement)}`.length>20}_suffixForUnknownPrefix(t,r){let i=r&&yi(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(;no(i,r.max)<0;){if(`${t}${i}`.length>20)return null;if(!r.usedSuffixes.has(i))return i;i=$t(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||!yi(r)){let s=$t(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=$t(o,n)}let a=$t(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,$t(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=Ef(r),o=Nf(n,i),{prefix:a,baseSuffix:s}=this._applyGenerationStrategy(o,n),c=null;if(o===ye.PARENT_CONVERSION&&this.prefixMap.has(a)){this._ensureFreshBounds(a);let f=this.prefixMap.get(a).max;c=$t(f,this.suffixIncrement)}o===ye.PARENT_CONVERSION&&this.releaseCustomId(n);let l=o===ye.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 ye.PARENT_CONVERSION:return Pf(this.defaultPrefix);case ye.PASTE_REFERENCE:return Lf(r,this.suffixIncrement);default:return Of(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=$t(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 Ev=1,Dv=-1;function _v(e,t){if(e===void 0&&t===void 0)return 0;if(e===void 0)return Ev;if(t===void 0)return Dv;let r=Math.min(e.length,t.length);for(let i=0;i<r;i+=1){let n=(e[i]??0)-(t[i]??0);if(n!==0)return n}return e.length-t.length}function wf(e,t,r,i){let n=r.assignmentByActivityId.get(String(e.id)),o=r.assignmentByActivityId.get(String(t.id)),a=_v(n===void 0?void 0:r.sequencePathByValueId.get(n),o===void 0?void 0:r.sequencePathByValueId.get(o));return i===Pt.DESCENDING?-a:a}var kv=1,Rv=-1;function Pv(e,t){return!e&&!t?null:e&&t?0:e?kv:Rv}function Ff(e){return e==null}function xf(e,t){let r=t.indexOf(String(e));return r===-1?t.length:r}function Lv(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 Ov(e,t,r){if(ur(e)){let n=r.get(e.key);return n===void 0?null:(o,a)=>wf(o,a,n,e.direction)}let i=Ie(e.field);return i===null?null:(n,o)=>{let a=i.extract(n,t),s=i.extract(o,t),c=Pv(Ff(a),Ff(s));if(c!==null)return c;let l=i.valueKind===P.ENUM?xf(a,i.order)-xf(s,i.order):Lv(a,s,t.locale);return e.direction===Pt.DESCENDING?-l:l}}function Mf(e,t,r=Ti){let i=e.rules.map(n=>Ov(n,t,r)).filter(n=>n!==null);return i.length===0?null:(n,o)=>{for(let a of i){let s=a(n,o);if(s!==0)return s}return 0}}function Uf(e){let t=[];e.forEachActivity((r,i)=>{r.type===T.PROJECT&&e.getChildren(String(i)).length===0&&t.push(String(i))});for(let r of t)e.setActivityField(r,x.TYPE,fr),Nv(e,r)}function Nv(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:K.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 Bf(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?Mt(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 Hf(e){let{state:t,sector:r,scheduler:i,skipAutoSchedule:n,now:o}=e;if(Dt(t),r.updateDurationForPrimaveraEndDate&&wv(t),Fv(t),Bf(t),n){Jr(t),o&&(Xe(t,o),pe(t,r.statusCriteria));return}let a=await i.schedule({});$r(t,a),xv(t),bv(t),await mr(t,void 0,!1),Jr(t),o&&(Xe(t,o),pe(t,r.statusCriteria))}function bv(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=ie(t))})}function wv(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function Fv(e){e.forEachActivity(t=>{let r=t.constraintType;if(!r||!t.constraintDate)return;let i=t.constraintDate;if(t.type===T.MILESTONE&&(i.getUTCHours()!==0||i.getUTCMinutes()!==0))return;let n=e.calendarReader.getCalendar(String(t.calendarId));n&&(t.constraintDate=de(t.constraintDate,n,r))})}function xv(e){e.forEachActivity(t=>{if(t.type!==T.MILESTONE)return;let r=t.constraintType;if(!r||!t.constraintDate)return;let i=e.calendarReader.getCalendar(String(t.calendarId));i&&(t.constraintDate=de(t.constraintDate,i,r))})}var ee={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function Wf(e){let t=e.clock??null,r=t?.()??null,i=r?on(r):null,n=e.reporter??yr,o=xd(),a=to({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},n,o.record),s=a.sector;s.statusCriteria=mn(e.statusCriteria),s.ganttId=e.ganttId??null;let c=a.calendars,l=a.baseCalendars??[],d=zn(a.activities,a.links,a.calendars,l),u=(L,m)=>Mf(L,He(s.hoursPerDay),m),f=new Fr(d,u);f.hydrateViewState({hiddenIds:a.viewStateSeed.hiddenIds});let p=new hr(f,n);Uf(f);let y=os({knownIds:a.activities.map(L=>L.id)}),g=as({seed:r?.getTime()??0,knownIds:a.links.map(L=>L.id)}),A=ss({knownIds:a.activities.map(L=>L.uniqueCorrelativeId)}),k=new so({defaultPrefix:s.customIdPrefix,suffixIncrement:s.customIdIncrement});if(k.populateFromActivities(a.activities),e.baselinePoints&&e.baselinePoints.length>0){let L=l.find(m=>m.baseDefault)?.id??null;Hn(f,e.baselinePoints,i,n,L,o.record)}let _=Hf({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:A,customIdTracker:k,calendars:c,baseCalendars:l,clock:t,reporter:n,loadDiagnostics:o.snapshot,initPromise:_}}function Mr(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(Mr)];if(e instanceof Map)return["map",Array.from(e,([t,r])=>[Mr(t),Mr(r)]).sort((t,r)=>JSON.stringify(t).localeCompare(JSON.stringify(r)))];if(e instanceof Set)return["set",Array.from(e,Mr).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,Mr(r)])];throw new TypeError(`Unsupported canonical value: ${typeof e}`)}function or(e){return JSON.stringify(Mr(e))}function cs(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=Mv(s,c);Object.keys(l).length>0&&o.push({id:a,kind:N.UPDATED,fields:l,after:F(c)})}return o}function Mv(e,t){let r={},i=[...new Set([...Object.keys(e),...Object.keys(t)])].sort();for(let n of i)or(e[n])!==or(t[n])&&(r[n]={before:F(e[n]),after:F(t[n])});return r}function Uv(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 ls(e,t){let r=or(e.order)!==or(t.order);return{source:{kind:ne.INIT},activities:cs(e.activities,t.activities),links:cs(e.links,t.links),calendars:cs(e.calendars,t.calendars),trackingEvents:[],effects:[],viewState:Uv(e,t),...r?{order:F(e.order)}:{}}}var Ur={MOVE:"move",RESIZE_START:"resize-start",RESIZE_END:"resize-end"},Bv=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),ds=(e,t)=>e===null?t:Math.min(e,t),us=(e,t)=>e===null?t:Math.max(e,t);function jf(e,t,r){let i=[...new Set(t.kind===Ur.MOVE?t.activityIds.map(String):[String(t.activityId)])];if(i.length===0)throw new Error("[ScheduleCore] date gesture has no participants");let n=Hv(e,t,i);return Wv(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=jv(s,a),l=Kv(s,a);if(c===null||l===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(o)}`);return{startTimeMs:c,endTimeMs:l}}}}function Hv(e,t,r){let i=new Map,n=t.kind===Ur.MOVE?String(t.anchorActivityId):null,o=n===null?null:Vf(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=Vf(e,a);if(t.kind===Ur.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===Ur.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 Wv(e,t,r){let i=Zr(e,new Set(t));for(let n of i){let o=Bv();for(let a of e.getChildren(n)){let s=r.get(a);if(s){Vv(o,s);continue}let c=e.getActivity(a);if(!c)throw new Error(`[ScheduleCore] missing child ${a} while previewing parent ${n}`);o.constantStart=ds(o.constantStart,c.startDate.getTime()),o.constantEnd=us(o.constantEnd,c.endDate.getTime())}r.set(n,o)}}function Vf(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 Vv(e,t){t.constantStart!==null&&(e.constantStart=ds(e.constantStart,t.constantStart)),t.variableStartOffset!==null&&(e.variableStartOffset=ds(e.variableStartOffset,t.variableStartOffset)),t.constantEnd!==null&&(e.constantEnd=us(e.constantEnd,t.constantEnd)),t.variableEndOffset!==null&&(e.variableEndOffset=us(e.variableEndOffset,t.variableEndOffset))}function jv(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 Kv(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 fs=Symbol("ScheduleCore.fork.source");function Yv(e){return{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}function Gv(e){return e.kind===h.PERSISTENCE_ACKNOWLEDGE||e.kind===h.ACTIVITY_LOOKAHEAD_SYNC&&e.acknowledgePersistedLookahead===!0}function $v(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 qv(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 zv(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 Br=class e{activities;links;calendars;selection;view;baselines;impactRequests;persistence;history;projection;criticalPath;diagnostics;_activityClipboard={value:null};_status=ee.READY;coreRuntime;_isFork;_undo=new qn;_opQueue=Promise.resolve();_scheduleRevision=0;_stateRevision=0;_pendingScheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){if(Object.assign(this,gs(this)),fs in t){this._isFork=!0;let n=t[fs],o=n.coreRuntime.state.fork();this.coreRuntime={state:o,scheduler:new hr(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=Wf(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!==ee.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({[fs]: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(),$a(this.coreRuntime.state,t)}calculateCalendarEndDate(t){this.assertReady();let r=this.coreRuntime.state.getActivity(t.activityId);return r?this.coreRuntime.state.calculateEndDate({startDate:t.startDate,durationHours:t.durationHours,task:r}):null}calculateCalendarDuration(t){this.assertReady();let r=this.coreRuntime.state.getActivity(t.activityId);return r?this.coreRuntime.state.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:r}):null}getClosestCalendarWorkTime(t){this.assertReady();let r=this.coreRuntime.state.getActivity(t.activityId);return r?this.coreRuntime.state.getClosestWorkTime({date:t.date,dir:t.direction,task:r}):null}getProgressEditability(t){this.assertReady();let r=$a(this.coreRuntime.state,t);if(!r)return null;let i=Ja(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat});return sn.canEdit(r,i.hierarchy)}createDateGesturePreview(t){this.assertReady();let r=this._scheduleRevision;return jf(this.coreRuntime.state,t,()=>{if(this.assertReady(),this._scheduleRevision!==r)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),ku(this.coreRuntime.state)}getIndentTargetParentIds(t){this.assertReady();let r=Un(t.map(i=>String(i)),this.coreRuntime.state);return[...new Set(r.allowedMoves.map(i=>String(i.newParentId)))]}getChildrenView(t){return this.assertReady(),Lu(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),za(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=za(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(),bu(this.coreRuntime.state)}auditEffectiveGraph(){this.assertReady();let t=this.coreRuntime.state,r=t.getAllLinks(),i=zr(t,r),n=Vi(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(),Ru(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),Pu(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),qa(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),Ou(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()]}getVisualRows(){return this.assertReady(),[...this.coreRuntime.state.getVisualRows()]}getActiveGroup(){return this.assertReady(),F(this.coreRuntime.state.getGroup())}hasChild(t){return this.assertReady(),Nu(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(),wu(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 or({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){return this.assertReady(),t.assertReady(),ls(this._snapshotProjection(),t._snapshotProjection())}_snapshotProjection(){return{activities:this.getAllActivitiesView(),links:this.getAllLinksView(),calendars:this.getAllCalendars(),selectedIds:this.getSelectedActivityIds(),hiddenIds:this.getHiddenActivityIds(),order:ge(this.coreRuntime.state)}}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 Sn(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 dispatchMany(t,r={}){let i=t.some(Sn)?this._admitScheduleMutation():!1;return this._enqueue(()=>this._dispatchManyInner(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(),Ra(t,{adapter:this.coreRuntime.state,stateRevision:this._stateRevision})}applyLookaheadConversion(t){return this.dispatch({...t,kind:h.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 _dispatchManyInner(t,r,i){let n=this._snapshotProjection(),o={...r,skipAutoSchedule:!0,skipCriticalPath:!0},a=[],s=[],c=[],l=!1,d=!1,u,f=!1,p=null,y=!1,g=!1;try{for(let A of t){if(A.kind===h.SCHEDULE_AUTO_SCHEDULE){if(A.activityId!==void 0&&!this.coreRuntime.state.activityExists(A.activityId)){a.push({ok:!1,reason:C.ACTIVITY_NOT_FOUND});continue}let _=Yv(A);a.push({ok:!0,changes:_}),s.push(_),c.push(A),d=!0,A.activityId===void 0||u!==void 0&&u!==A.activityId?f=!0:u=A.activityId;continue}let k=await this._runDispatch(A,o,!0);a.push(k.result),k.result.ok&&(s.push(k.result.changes),c.push(A)),k.changedState&&(l=!0,d=!0,f=!0)}if(d){let A=f||u===void 0?{kind:h.SCHEDULE_AUTO_SCHEDULE}:{kind:h.SCHEDULE_AUTO_SCHEDULE,activityId:u},k=await this._runDispatch(A,r,!0);k.result.ok&&(p=k.result.changes,s.push(k.result.changes),y=r.skipAutoSchedule!==!0),l||=k.changedState}return l&&this._recordScheduleMutation(p!==null&&r.skipAutoSchedule!==!0&&r.skipCriticalPath!==!0),g=!0,{results:a,autoScheduled:y,changeSet:this._aggregateDispatchManyChangeSets(n,s,c)}}finally{!g&&l&&this._recordScheduleMutation(!1),this._settleScheduleMutation(i,g&&l)}}_aggregateDispatchManyChangeSets(t,r,i){if(r.length===0)return null;let n=ls(this._snapshotProjection(),t),o=r.flatMap(s=>s.effects??[]),a=r.flatMap(s=>s.warnings??[]);return{...n,source:{kind:ne.DISPATCH_MANY,actions:i},trackingEvents:r.flatMap(s=>s.trackingEvents),...o.length===0?{}:{effects:o},...a.length===0?{}:{warnings:a}}}async _runDispatch(t,r,i=!1){if(this.assertReady(),this._isFork&&Gv(t))return{result:{ok:!1,reason:C.SANDBOX_PERSISTENCE_FORBIDDEN},changedState:!1};let n=Ja(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat}),o=Ku(t),a=[this.coreRuntime.activityIdGenerator.snapshot(),this.coreRuntime.linkIdGenerator.snapshot(),this.coreRuntime.uniqueCorrelativeIdGenerator.snapshot()];this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let s,c;try{s=await Zd(t,r,{adapter:this.coreRuntime.state,ctx:n,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,linkIdGen:this.coreRuntime.linkIdGenerator,isActivityIdReserved:u=>this._saveTracker.hasCheckpointActivityId(u),isLinkIdReserved:u=>this._saveTracker.hasCheckpointLinkId(u),uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,reporter:this.coreRuntime.reporter,activityClipboard:this._activityClipboard,stateRevision:this._stateRevision,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(u=>u.baseDefault)?.id??null,now:this.coreRuntime.clock?on(this.coreRuntime.clock()):null});let d=this.coreRuntime.state.peekWriteCapture()?.progressFallbackBefore;d&&d.size>0&&(c=new Map(d)),s.ok||this._rollback(a)}catch(d){throw this._rollback(a),d}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(s.ok&&o===xr.RECORD&&ts(s.changes)){let d=Hu(this.coreRuntime.state,s.changes),u=c?new Map(Array.from(c.keys(),f=>[f,this.coreRuntime.state.getProgressFallback(f)])):void 0;this._undo.record(Xa(Bu(s.changes),s.__beforeSnap,s.__beforeLinks,d.afterSnap,d.afterLinks,c,u),Wu(t),Date.now())}if(s.ok)if(o===xr.CHECKPOINT_ON_SUCCESS){if(t.kind!==h.PERSISTENCE_ACKNOWLEDGE)throw new Error("checkpoint-on-success requires persistence acknowledge");let d=this.coreRuntime.state.getAllActivities(),u=this.coreRuntime.state.getAllLinks(),f=t.checkpoint,p=f?.historyBoundary??this._undo.capturePersistenceBoundary();this._saveTracker.acknowledge(f?.activities??d,f?.links??u,t.activities,t.links,d,u),this._undo.discardThrough(p),this._undo.applyPersistedIdentities(t.activities??[],t.links??[])}else t.kind===h.ACTIVITY_LOOKAHEAD_SYNC&&t.acknowledgePersistedLookahead===!0?(this._saveTracker.acknowledgePersistedLookahead(s.changes.activities,d=>this.coreRuntime.state.getActivity(d)),t.persistedProgress!==void 0&&this._undo.clear()):this._saveTracker.recordChanges(s.changes.activities,s.changes.links,d=>this.coreRuntime.state.getActivity(d),d=>this.coreRuntime.state.getLink(d));if(s=this._withReappliedViewState(t,s),!s.ok)return{result:s,changedState:!1};let l=ts(s.changes);return l&&this._stateRevision++,Sn(t)&&l?(i||this._recordScheduleMutation(r.skipAutoSchedule!==!0&&r.skipCriticalPath!==!0&&er(t)),{result:Kf(s),changedState:!0}):{result:Kf(s),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===h.VISIBILITY_SET&&this.coreRuntime.state.setFilterProjection(null),!Fl(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=zu(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=Co(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:ge(i)};let o=new Set(r);for(let s of t.activities){if(s.kind===N.DELETED)return{...t,order:ge(i)};let c=i.getParentId(s.id);o.add(c===null?"0":String(c))}let a=Co(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=He(this.coreRuntime.sector.hoursPerDay),o=r.getFilterProjection(),a=zv(o,i,n),s=$v(t)?null:qv(t,r),c,l;if(s===null||!a){let f=_i({activities:r.getAllActivities(),parentOf:p=>r.getParentId(p),filter:i,context:n,viewAttributeCatalogs:r.getViewAttributeCatalogMap()});r.setFilterProjection(f),l=f.visibleIds,c=r.getAllIds()}else c=bs(o,s,f=>r.getParentId(f)),l=o.visibleIds;let u=Me(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===ee.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 Fr(zn(this.coreRuntime.state.getAllActivities().map(s=>it(s)),this.coreRuntime.state.getAllLinks().map(s=>({...s})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),n=()=>!r.cancelled&&this._status!==ee.DESTROYED&&this._scheduleRevision===t&&this._pendingScheduleRevision===this._scheduleRevision,o=(async()=>{let s=await ya(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)fa(this.coreRuntime.state,l,d);for(let[l,d]of s.links)pa(this.coreRuntime.state,l,d);c=await G(this.coreRuntime.state,{source:{kind:ne.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;Yu(this.coreRuntime.state,i),this._recordScheduleMutation(!1),r(!0),Za(i)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(i),this._undo.resetCoalesce();let n=Qa(this.coreRuntime.state,i,ut.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;Gu(this.coreRuntime.state,r),this._recordScheduleMutation(!1),t(!0),Za(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce();let i=Qa(this.coreRuntime.state,r,ut.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=ee.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new Xn;assertReady(){if(this._status===ee.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===ee.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=ee.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",r),r}}};function Kf(e){let{__beforeSnap:t,__beforeLinks:r,...i}=e;return i}async function Yf(e){let t=new Br(e);return await t.ready,t}var Gf=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var $f={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 qf=8;var zf={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return rp(Jv);})();
1
+ "use strict";var ScheduleCore=(()=>{var uo=Object.defineProperty;var Qf=Object.getOwnPropertyDescriptor;var tp=Object.getOwnPropertyNames;var ep=Object.prototype.hasOwnProperty;var rp=(e,t)=>{for(var r in t)uo(e,r,{get:t[r],enumerable:!0})},ip=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of tp(t))!ep.call(e,n)&&n!==r&&uo(e,n,{get:()=>t[n],enumerable:!(i=Qf(t,n))||i.enumerable});return e};var np=e=>ip(uo({},"__esModule",{value:!0}),e);var eC={};rp(eC,{ACTIVITY_BATCH_ACTION_KIND:()=>me,ACTIVITY_BATCH_MODE:()=>mt,ACTIVITY_DATE_EDGE:()=>Vr,ACTIVITY_FIELD:()=>St,ACTIVITY_PONDERATOR_CRITERION:()=>It,ACTIVITY_PROGRESS_ORIGIN:()=>dn,ACTIVITY_TYPE:()=>E,CALENDAR_UNIT:()=>pt,CHANGE_SET_SOURCE_KIND:()=>ne,COLUMN:()=>D,COMPLETED_PROGRESS:()=>Gr,CONSTRAINT_TYPE:()=>v,CONSTRAINT_TYPE_TO_LABEL:()=>qf,CONSTRAINT_WARNING_KIND:()=>qe,CREATION_KIND:()=>Xf,DATE_GESTURE_KIND:()=>Ur,DEFAULT_HOURS_PER_DAY:()=>Jf,DISPATCH_ACTION_KIND:()=>h,DISPATCH_ACTION_KINDS:()=>gs,DISPATCH_LINK_OPERATION_KIND:()=>nt,DISPATCH_TRACK_EVENT:()=>Gt,EDIT_ALERT_KEY:()=>bc,EDIT_DENIAL_REASON:()=>ti,ENTITY_CHANGE_KIND:()=>b,FILTER_FIELD:()=>z,FILTER_LOGIC:()=>dr,FILTER_OPERATOR:()=>U,FILTER_REJECTION_REASON:()=>at,FILTER_VALUE_KIND:()=>L,GROUP_ID_PREFIX:()=>To,GROUP_ID_SEPARATOR:()=>Ri,LINK_BATCH_OPERATION_KIND:()=>cr,LINK_CODE:()=>Dt,LINK_CODE_TO_TYPE:()=>Ke,LINK_REJECTION_REASON:()=>ct,LINK_RELATIONSHIP:()=>xe,LINK_TYPE:()=>W,LINK_TYPE_CODE:()=>$i,MINIMUM_GROUP_DEPTH:()=>Li,NEW_ACTIVITY_DEFAULTS:()=>Ln,NOT_STARTED_PROGRESS:()=>tc,ORDER_DIRECTION:()=>Pt,REJECTION_REASON:()=>C,ROOT_PARENT_ID:()=>V,SCHEDULE_CORE_STATUS:()=>ee,SCHEDULE_EFFECT_KIND:()=>un,SIR_AUTO_REJECT_REASON:()=>fn,STATUS:()=>Rt,STATUS_CRITERIA:()=>he,ScheduleCore:()=>Br,UNASSIGNED_GROUP_LABEL:()=>Pi,UNASSIGNED_VALUE_ID:()=>Ve,VIEW_ATTRIBUTE_KIND:()=>Ue,VISUAL_ROW_KIND:()=>We,WORK_TIME_DIRECTION:()=>Y,buildGroupRowId:()=>Oi,checkNoUpdatedLinks:()=>af,computeExpectedProgress:()=>jo,createSchedule:()=>$f,expectedProgressFromBaseline:()=>Sr,getActiveBaseline:()=>Ct,getUnsavedActivities:()=>zf,isRootParent:()=>B,isViewAttributeCriterion:()=>Be,isViewAttributeOrderRule:()=>ur,normalizeParentKey:()=>zt,parseFromBackend:()=>eo,willRunCriticalPath:()=>Mu,yieldToBrowser:()=>ut});var E={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},op=Object.values(E);function Hr(e){return op.includes(e)}var mi={CONSTRAINT:"constraint",ALERT:"alert",WARNING:"warning"},Y={FUTURE:"future",PAST:"past"},pt={HOUR:"hour",DAY:"day"},It={DURATION:"DURATION",COST:"COST",WORK_HOURS:"HH"},he={BASELINE:"Baseline",ACTUAL:"Actual"},Rt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"},b={CREATED:"created",UPDATED:"updated",DELETED:"deleted"};var v={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},ap={[v.MSO]:()=>!0,[v.MFO]:()=>!0,[v.SNLT]:(e,t)=>e<t,[v.SNET]:(e,t)=>e>t,[v.FNLT]:(e,t)=>e<t,[v.FNET]:(e,t)=>e>t};function gi(e,t,r){if(!t)return{violated:!1};let i=ap[e];return i?i(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var sp=new Set([v.MSO,v.SNET,v.SNLT]);function Fe(e,t,r){return sp.has(e)?t:r}function Ai(e,t,r){return{type:mi.CONSTRAINT,messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var cp={[v.SNET]:{startOfDay:!0,direction:Y.FUTURE},[v.SNLT]:{startOfDay:!0,direction:Y.PAST},[v.FNET]:{startOfDay:!1,direction:Y.FUTURE},[v.FNLT]:{startOfDay:!1,direction:Y.PAST},[v.MSO]:{startOfDay:!0,direction:Y.FUTURE},[v.MFO]:{startOfDay:!1,direction:Y.PAST}},Ii=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),hs=(e,t)=>new Date(e.getTime()+t*864e5),lp=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function Wr(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=cp[e.constraintType];if(!r)return e.constraintDate;let i=e.constraintDate,n=t.getClosestWorkTime({date:Ii(i),dir:Y.FUTURE,task:e});if(lp(n,i))return i.getTime()!==Ii(i).getTime()?i:r.startOfDay?n:t.getClosestWorkTime({date:hs(Ii(i),1),dir:Y.PAST,task:e});let o=Ii(t.getClosestWorkTime({date:i,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:o,dir:Y.FUTURE,task:e}):t.getClosestWorkTime({date:hs(o,1),dir:Y.PAST,task:e})}function ms(e,t){let r={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},i=e.constraintType;if(!i||i===v.ASAP||i===v.ALAP)return r;let n=Wr(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 v.SNET:return{earliestStart:n,latestStart:null,earliestEnd:o(n),latestEnd:null};case v.SNLT:return{earliestStart:null,latestStart:n,earliestEnd:null,latestEnd:o(n)};case v.FNET:return{earliestStart:a(n),latestStart:null,earliestEnd:n,latestEnd:null};case v.FNLT:return{earliestStart:null,latestStart:a(n),earliestEnd:null,latestEnd:n};case v.MSO:{let s=o(n);return{earliestStart:n,latestStart:n,earliestEnd:s,latestEnd:s}}case v.MFO:{let s=a(n);return{earliestStart:s,latestStart:s,earliestEnd:n,latestEnd:n}}default:return r}}function Is(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function fo(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var W={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"},dp=Object.values(W);function vi(e){return dp.includes(e)}var up={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"},fp={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"},D={...up,...fp};var Et={CREATE:"create",UPDATE:"update",DELETE:"delete"},ct={SELF_LINK:"self-link",CYCLE:"cycle",DUPLICATE:"duplicate",ACTIVITY_MISSING:"activity-missing",LINK_MISSING:"link-missing",HIERARCHY_LINK:"hierarchy-link"};var h={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_TYPE_SET:"activity-type-set",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",VIEW_ATTRIBUTES_SET:"view-attributes-set",GROUP_SET:"group-set",SIR_SYNC:"sir-sync",ACTIVITY_LOOKAHEAD_SYNC:"activity-lookahead-sync",SCHEDULE_AUTO_SCHEDULE:"schedule-auto-schedule"},me="activity-batch",nt=Et,gs=Object.values(h);function Ct(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isActiveVersion)??null}var St={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"},Vr={START:"start",END:"end"},xe={FINISH_TO_START:"finish-to-start",START_TO_START:"start-to-start",FINISH_TO_FINISH:"finish-to-finish",START_TO_FINISH:"start-to-finish"},cr={CREATE:"create",UPDATE:"update",REMOVE:"remove"};var pp={[St.NAME]:D.TEXT,[St.DESCRIPTION]:D.DESCRIPTION,[St.DURATION_DAYS]:D.DURATION,[St.PROGRESS]:D.PROGRESS,[St.COST]:D.COST,[St.USED_COST]:D.USED_COST,[St.WORK_HOURS]:D.HH_WORK_TIME,[St.START_DATE]:D.START_DATE,[St.END_DATE]:D.END_DATE,[St.CONSTRAINT_TYPE]:D.CONSTRAINT_TYPE,[St.CONSTRAINT_DATE]:D.CONSTRAINT_DATE,[St.CALENDAR_ID]:D.CALENDAR_ID,[St.CUSTOM_ID]:D.CUSTOM_ID,[St.SUBCONTRACT_ID]:D.SUBCONTRACT_ID,[St.RESPONSABLE_IDS]:D.RESPONSABLES,[St.TAG_IDS]:D.TAGS};function po(e,t){return{activityId:e,column:pp[t.field],newValue:t.value}}var yp={[xe.FINISH_TO_START]:W.FINISH_TO_START,[xe.START_TO_START]:W.START_TO_START,[xe.FINISH_TO_FINISH]:W.FINISH_TO_FINISH,[xe.START_TO_FINISH]:W.START_TO_FINISH};function jr(e){return yp[e]}function hp(e){return e.kind===cr.CREATE?{kind:nt.CREATE,source:e.sourceId,target:e.targetId,type:jr(e.relationship),...e.lagDays===void 0?{}:{lag:e.lagDays},...e.linkId===void 0?{}:{linkId:e.linkId}}:e.kind===cr.UPDATE?{kind:nt.UPDATE,linkId:e.linkId,...e.sourceId===void 0?{}:{source:e.sourceId},...e.targetId===void 0?{}:{target:e.targetId},...e.relationship===void 0?{}:{type:jr(e.relationship)},...e.lagDays===void 0?{}:{lag:e.lagDays}}:e.kind===cr.REMOVE?{kind:nt.DELETE,linkId:e.linkId}:e}function mp(e){return e===Vr.START?D.START_DATE:e===Vr.END?D.END_DATE:e}function Ip(e){return{kind:me,mode:e.mode,items:e.items,links:e.links.map(t=>({source:t.source,target:t.target,type:jr(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}})),...e.eventSource===void 0?{}:{eventSource:e.eventSource}}}function gp(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:h.ACTIVITY_CREATE},r),applyBatch:(t,r)=>e.applyActivityBatch(Ip(t),r),editInline:(t,r,i)=>e.dispatch({...po(t,r),kind:h.INLINE_EDIT},i),setType:(t,r,i)=>e.dispatch({kind:h.ACTIVITY_TYPE_SET,activityId:t,type:r},i),applyDragBatch:(t,r)=>e.dispatch({kind:h.DATES_BATCH,edits:t.map(i=>({activityId:i.activityId,column:mp(i.edge),newValue:i.value}))},r),editFields:(t,r)=>e.dispatch({kind:h.BULK_EDIT,edits:t.map(i=>po(i.activityId,i))},r),remove:(t,r={})=>e.dispatch({...r,kind:h.ACTIVITY_DELETE,activityIds:t}),move:(t,r)=>e.dispatch({...t,kind:h.ACTIVITY_MOVE},r),planLookaheadConversion:t=>e.planLookaheadConversion(t),applyLookaheadConversion:t=>e.applyLookaheadConversion(t),indent:(t,r={})=>e.dispatch({...r,kind:h.ACTIVITY_INDENT,activityIds:t}),outdent:(t,r={})=>e.dispatch({...r,kind:h.ACTIVITY_OUTDENT,activityIds:t}),setProgress:(t,r,i={})=>e.dispatch({...i,kind:h.ACTIVITY_SET_PROGRESS,activityId:t,newValue:r}),copy:(t={})=>e.dispatch({...t,kind:h.ACTIVITY_COPY}),paste:(t,r={})=>e.dispatch({...r,kind:h.ACTIVITY_PASTE_COPIED,destination:{afterSiblingId:t}}),clearClipboard:(t={})=>e.dispatch({...t,kind:h.ACTIVITY_CLIPBOARD_CLEAR}),lookaheadSync:t=>e.dispatch({...t,kind:h.ACTIVITY_LOOKAHEAD_SYNC}),autoSchedule:(t,r)=>e.dispatch({kind:h.SCHEDULE_AUTO_SCHEDULE,...t===void 0?{}:{activityId:t}},r),createDateGesturePreview:t=>e.createDateGesturePreview(t)}}function Ap(e){return{get:t=>e.getLinkView(t),list:()=>e.getAllLinksView(),forActivity:t=>e.getLinksForActivityView(t),create:(t,r)=>e.dispatch({kind:h.LINK_CREATE,source:t.sourceId,target:t.targetId,type:jr(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}},r),update:(t,r,i)=>e.dispatch({kind:h.LINK_UPDATE,linkId:t,...r.sourceId===void 0?{}:{source:r.sourceId},...r.targetId===void 0?{}:{target:r.targetId},...r.relationship===void 0?{}:{type:jr(r.relationship)},...r.lagDays===void 0?{}:{lag:r.lagDays}},i),remove:(t,r)=>e.dispatch({kind:h.LINK_DELETE,linkId:t},r),batch:(t,r)=>e.dispatch({kind:h.LINKS_BATCH,operations:t.map(hp)},r)}}function As(e){let t=(r,i)=>e.dispatch({kind:h.BASELINE_APPLY,points:r},i);return{activities:gp(e),links:Ap(e),calendars:{get:r=>e.getCalendar(r),list:()=>e.getAllCalendars(),listBase:()=>e.getBaseCalendars(),projectWorkHours:()=>e.getProjectWorkHours(),reconcile:r=>e.dispatch({kind:h.CALENDAR_RECONCILE},r)},selection:{ids:()=>e.getSelectedActivityIds(),toggle:({checked:r,...i})=>e.dispatch({...i,kind:h.SELECTION_TOGGLE,isChecked:r}),replace:(r,i={})=>e.dispatch({...i,kind:h.SELECTION_REPLACE,activityIds:r})},view:{hiddenActivityIds:()=>e.getHiddenActivityIds(),visibleActivityIds:()=>e.getVisibleActivityIds(),visualOrderIds:()=>e.getVisualOrderIds(),visualRows:()=>e.getVisualRows(),filter:()=>e.getActiveFilter(),setFilter:r=>e.dispatch({...r,kind:h.FILTER_SET}),order:()=>e.getActiveOrder(),setOrder:(r,i={})=>e.dispatch({...i,kind:h.SORT_SET,rules:r}),group:()=>e.getActiveGroup(),setViewAttributes:(r,i={})=>e.dispatch({...i,kind:h.VIEW_ATTRIBUTES_SET,catalogs:r}),setGroup:(r,i={})=>e.dispatch({...i,kind:h.GROUP_SET,group:r}),setVisibility:(r,i={})=>e.dispatch({...i,kind:h.VISIBILITY_SET,visibleIds:r}),setStatusCriteria:(r,i)=>e.dispatch({kind:h.STATUS_CRITERIA_SET,criteria:r},i)},baselines:{refresh:t,setVisibility:t,setPonderatorCriterion:(r,i)=>e.dispatch({kind:h.PONDERATOR_CRITERION_SET,criterion:r},i),activeFor:r=>Ct(r)},impactRequests:{sync:r=>e.dispatch({...r,kind:h.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:h.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 Bt=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 Ci=e=>String(e);function vs(e){let{clickedId:t,isChecked:r,currentSelection:i,hierarchy:n,isFrozen:o,exists:a,autoCheckParents:s}=e,c=Ci(t),l=new Set([...i].map(String)),d=new Set(l),u=vp(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||Cp({id:c,isChecked:r,autoCheckParents:s,hierarchy:n,isFrozen:o,exists:a,next:d}),{nextSelection:d,changed:Sp(l,d),parentBlocked:p}}function vp(e,t){let r=[],i=new Bt;i.enqueue(e);let n=new Set([e]);for(;!i.isEmpty();){let o=i.dequeue();for(let a of t.getChildrenIds(o)){let s=Ci(a);n.has(s)||(n.add(s),r.push(s),i.enqueue(s))}}return r}function Cp(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=Ci(c);if(o(l))return;let d=n.getChildrenIds(l).map(Ci).filter(a),u=d.some(o),f=d.filter(I=>!o(I)),y=f.length>0&&f.every(I=>s.has(I))&&!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 Sp(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 lr(e){return(e.pendingRequestIds?.length??0)>0}var C={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 Cs=(e,t)=>{let r=e.getActivity(t);return r!=null&&lr(r)},Ss=(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 Ts(e,t){let{adapter:r}=t,i=e.activityId;if(!r.getActivity(i))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let n=e.frozenIds?new Set(e.frozenIds):null,o=n?s=>n.has(s):s=>Cs(r,s),a=vs({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:Ss(e,r,a.changed)}}function Si(e,t){let{adapter:r}=t,i=new Set(e.activityIds.map(String).filter(a=>r.activityExists(a)).filter(a=>!Cs(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:Ss(e,r,o)}}function Me(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 Es(e,t){let{adapter:r}=t,i=new Set(e.visibleIds.map(String)),n=Me(r,i);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:n}}}var Ds={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var Ue="viewAttribute";var L={STRING:"string",NUMBER:"number",DATE:"date",ID_ARRAY:"id-array",ENUM:"enum",BOOLEAN:"boolean",REFERENCE:"reference"},z={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"},U={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"};function Be(e){return"kind"in e&&e.kind===Ue}var dr={AND:"and",OR:"or"};var Tp=2,Ep=[Rt.WAITING,Rt.DONE,Rt.DOING,Rt.OVERDUE,Rt.ADVANCEMENT],Dp=[v.MFO,v.MSO,v.SNLT,v.SNET,v.ALAP,v.ASAP,v.FNET,v.FNLT],_p=1e3*60*60*24;function yo(e,t){return e===null||t<=0?null:e/t}function kp(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)/_p)+1}var Rp={[z.NAME]:{valueKind:L.STRING,extract:e=>e.name},[z.DESCRIPTION]:{valueKind:L.STRING,extract:e=>e.description},[z.CUSTOM_ID]:{valueKind:L.STRING,extract:e=>e.customId},[z.CORRELATIVE_ID]:{valueKind:L.NUMBER,extract:e=>e.correlativeId},[z.UNIQUE_CORRELATIVE_ID]:{valueKind:L.NUMBER,extract:e=>{let t=Number(e.uniqueCorrelativeId);return Number.isFinite(t)?t:null}},[z.PROGRESS]:{valueKind:L.NUMBER,extract:e=>e.progress},[z.DURATION_DAYS]:{valueKind:L.NUMBER,extract:(e,t)=>yo(e.durationHours,t.hoursPerDay)},[z.CALENDAR_DURATION]:{valueKind:L.NUMBER,extract:e=>e.type===E.MILESTONE?0:kp(e.startDate,e.endDate)},[z.COST]:{valueKind:L.NUMBER,extract:e=>e.cost},[z.USED_COST]:{valueKind:L.NUMBER,extract:e=>e.usedCost},[z.REAL_COST]:{valueKind:L.NUMBER,extract:e=>e.realCost},[z.WORK_HOURS]:{valueKind:L.NUMBER,extract:e=>e.workHours},[z.REAL_WORK_HOURS]:{valueKind:L.NUMBER,extract:e=>e.realWorkHours},[z.PONDERATOR]:{valueKind:L.NUMBER,extract:e=>e.ponderator},[z.FREE_SLACK_DAYS]:{valueKind:L.NUMBER,extract:(e,t)=>yo(e.freeSlackHours,t.hoursPerDay)},[z.TOTAL_SLACK_DAYS]:{valueKind:L.NUMBER,extract:(e,t)=>yo(e.criticalPath?.totalSlackHours??null,t.hoursPerDay)},[z.EXPECTED_PROGRESS_BASELINE]:{valueKind:L.NUMBER,equalityPrecision:Tp,extract:e=>e.expectedProgressBaseline},[z.EXPECTED_PROGRESS]:{valueKind:L.NUMBER,extract:e=>e.expectedProgress},[z.BASELINE_DURATION_DAYS]:{valueKind:L.NUMBER,extract:e=>e.baselineSnapshot?.durationDays??null},[z.BASELINE_COST]:{valueKind:L.NUMBER,extract:e=>e.baselineSnapshot?.cost??null},[z.BASELINE_WORK_HOURS]:{valueKind:L.NUMBER,extract:e=>e.baselineSnapshot?.workHours??null},[z.START_DATE]:{valueKind:L.DATE,extract:e=>e.startDate},[z.END_DATE]:{valueKind:L.DATE,extract:e=>e.endDate},[z.CONSTRAINT_DATE]:{valueKind:L.DATE,extract:e=>e.constraintDate},[z.BASELINE_START_DATE]:{valueKind:L.DATE,extract:e=>e.baselineSnapshot?.startDate??null},[z.BASELINE_END_DATE]:{valueKind:L.DATE,extract:e=>e.baselineSnapshot?.endDate??null},[z.EARLY_START]:{valueKind:L.DATE,extract:e=>e.criticalPath?.earlyStart??null},[z.EARLY_FINISH]:{valueKind:L.DATE,extract:e=>e.criticalPath?.earlyFinish??null},[z.LATE_START]:{valueKind:L.DATE,extract:e=>e.criticalPath?.lateStart??null},[z.LATE_FINISH]:{valueKind:L.DATE,extract:e=>e.criticalPath?.lateFinish??null},[z.RESPONSABLE_IDS]:{valueKind:L.ID_ARRAY,extract:e=>e.responsableIds},[z.TAG_IDS]:{valueKind:L.ID_ARRAY,extract:e=>e.tagIds},[z.STATUS]:{valueKind:L.ENUM,order:Ep,extract:e=>e.status},[z.CONSTRAINT_TYPE]:{valueKind:L.ENUM,order:Dp,extract:e=>e.constraintType},[z.CALENDAR_ID]:{valueKind:L.REFERENCE,extract:e=>e.calendarId===null?null:String(e.calendarId)},[z.SUBCONTRACT_ID]:{valueKind:L.REFERENCE,extract:e=>e.subcontractId===null?null:String(e.subcontractId)},[z.IS_CRITICAL]:{valueKind:L.BOOLEAN,extract:e=>e.isCritical}};function Ie(e){return Rp[e]??null}function _s(e){return e===null?"":e}function ks(e){let t=new Map,r=new Map;for(let c of e.values){t.set(c.id,c);let l=_s(c.parentId),d=r.get(l)??[];d.push(c),r.set(l,d)}for(let c of r.values())c.sort((l,d)=>l.sequence!==d.sequence?l.sequence-d.sequence:l.id.localeCompare(d.id));let i=new Map,n=new Map,o=(c,l,d)=>{let u=r.get(_s(c))??[];for(let f of u){let p=[...l,f.id],y=[...d,f.sequence];i.set(f.id,p),n.set(f.id,y),o(f.id,p,y)}};o(null,[],[]);let a=new Map;for(let c of t.keys()){let l=new Set([c]);for(let[d,u]of i)u.includes(c)&&l.add(d);a.set(c,l)}let s=new Map;for(let c of e.assignments)t.has(c.valueId)&&s.set(String(c.activityId),c.valueId);return{key:e.key,valueById:t,pathByValueId:i,sequencePathByValueId:n,descendantIdsByValueId:a,assignmentByActivityId:s}}var Ti=new Map;function Rs(e,t){let r=new Set;for(let i of t){let n=e.descendantIdsByValueId.get(i);if(n===void 0){r.add(i);continue}for(let o of n)r.add(o)}return r}function Ps(e,t,r){let i=e.pathByValueId.get(t);return i===void 0||i.length===0?[t]:i.slice(0,Math.max(r,1))}function Ls(e,t,r){let i=r.get(t.key),n=i?.assignmentByActivityId.get(String(e.id))??null,o=i?Rs(i,t.value):new Set(t.value),a=n!==null&&o.has(n);return t.operator===U.SOME_OF?a:t.operator===U.NOT_SOME_OF?!a:!1}function ho(e){return e instanceof Date?e:typeof e=="string"||typeof e=="number"?new Date(e):new Date(Number.NaN)}function se(e){return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())}function Pp(e,t,r){let i=e===null;return r===U.INCLUDES?!i&&String(e).toLowerCase().includes(t.toLowerCase()):r===U.NOT_INCLUDES?i||!String(e).toLowerCase().includes(t.toLowerCase()):r===U.IS?!i&&String(e)===t:r===U.IS_NOT?i||String(e)!==t:!1}function Lp(e,t,r,i){if(e===null||typeof e!="number")return r===U.NOT_EQUALS;let n=i===void 0?e:Number(e.toFixed(i));return r===U.EQUALS?n===t:r===U.NOT_EQUALS?n!==t:r===U.GREATER_THAN?e>t:r===U.LESS_THAN?e<t:r===U.GREATER_OR_EQUAL?e>=t:r===U.LESS_OR_EQUAL?e<=t:!1}function Op(e,t,r){return typeof e=="number"&&e>=t&&e<=r}function Np(e,t,r){if(!(e instanceof Date))return!1;let i=se(e),n=se(t);return r===U.AFTER?i>n:r===U.BEFORE?i<n:!1}function bp(e,t,r){if(!(e instanceof Date))return!1;let i=se(e);return i>=se(t)&&i<=se(r)}function wp(e,t,r){let n=(Array.isArray(e)?e:[]).some(o=>t.has(String(o)));return r===U.SOME_OF?n:r===U.NOT_SOME_OF?!n:!1}function Fp(e,t,r){let i=e!==null&&t.has(String(e));return r===U.SOME_OF?i:r===U.NOT_SOME_OF?!i:!1}function Os(e){let t=Array.isArray(e)?e:[e];return new Set(t.map(r=>String(r)))}function Di(e){return e.viewAttributeCatalogs??Ti}function Ei(e,t,r,i){if(Be(t))return Ls(e,t,i);let n=Ie(t.field);if(n===null)return!1;let o=n.extract(e,r),{operator:a}=t;return a===U.BETWEEN?n.valueKind===L.NUMBER?Op(o,Number(t.value),Number(t.valueTo)):n.valueKind===L.DATE?bp(o,ho(t.value),ho(t.valueTo)):!1:n.valueKind===L.STRING?Pp(o,String(t.value),a):n.valueKind===L.NUMBER?Lp(o,Number(t.value),a,n.equalityPrecision):n.valueKind===L.DATE?Np(o,ho(t.value),a):n.valueKind===L.ID_ARRAY?wp(o,Os(t.value),a):Fp(o,Os(t.value),a)}function Ns(e,t,r,i){return t.criteria.length===0?!0:t.logic===dr.OR?t.criteria.some(n=>Ei(e,n,r,i)):t.criteria.every(n=>Ei(e,n,r,i))}function xp(e,t,r,i){return t.groups&&t.groups.length>0?t.logic===dr.OR?t.groups.some(n=>Ns(e,n,r,i)):t.groups.every(n=>Ns(e,n,r,i)):t.criteria.length===0?!0:t.logic===dr.OR?t.criteria.some(n=>Ei(e,n,r,i)):t.criteria.every(n=>Ei(e,n,r,i))}function Mp(e,t){let r=se(e.startDate),i=se(e.endDate),n=se(t.start),o=se(t.end),a=r>=n&&i<=o,s=r>=n&&r<=o,c=n>=r&&n<=i;return a||s||c}function mo(e,t,r,i){let n=xp(e,t,r,i),o=t.dateRange,a=o===void 0||Mp(e,o);return n&&a}function Up(e,t,r){let i=t(e);for(;i!==null&&!r.has(String(i));)r.add(String(i)),i=t(i)}function bs(e){let{activities:t,parentOf:r,filter:i,context:n}=e,o=Di(e),a=new Set,s=[];for(let c of t)mo(c,i,n,o)&&(a.add(String(c.id)),s.push(c.id));for(let c of s)Up(c,r,a);return a}function Bp(e){let{activities:t,parentOf:r,filter:i,context:n}=e,o=Di(e),a=new Set,s=new Map,c=new Map,l=new Map;for(let d of t){let u=String(d.id),f=r(u);c.set(u,f),l.set(u,l.get(u)??0),f!==null&&l.set(f,(l.get(f)??0)+1);let p=mo(d,i,n,o);s.set(u,p?1:0),p&&a.add(u)}return{matchedIds:a,visibleReferenceCounts:s,parentIds:c,remainingChildren:l}}function Hp(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 Wp(e){let t=new Set;for(let[r,i]of e)i>0&&t.add(r);return t}function _i(e){let t=Bp(e);Hp(t);let r=Wp(t.visibleReferenceCounts);return{filter:e.filter,context:e.context,matchedIds:t.matchedIds,visibleIds:r,visibleReferenceCounts:t.visibleReferenceCounts,viewAttributeCatalogs:Di(e)}}function ws(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=mo(n,e.filter,e.context,Di(e));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 He(e){return{hoursPerDay:e,locale:"en"}}var at={UNKNOWN_FIELD:"unknown_field",UNKNOWN_OPERATOR:"unknown_operator",INVALID_VALUE:"invalid_value"},Vp={[L.STRING]:new Set([U.INCLUDES,U.NOT_INCLUDES,U.IS,U.IS_NOT]),[L.NUMBER]:new Set([U.EQUALS,U.NOT_EQUALS,U.GREATER_THAN,U.LESS_THAN,U.GREATER_OR_EQUAL,U.LESS_OR_EQUAL,U.BETWEEN]),[L.DATE]:new Set([U.AFTER,U.BEFORE,U.BETWEEN]),[L.ID_ARRAY]:new Set([U.SOME_OF,U.NOT_SOME_OF]),[L.ENUM]:new Set([U.SOME_OF,U.NOT_SOME_OF]),[L.BOOLEAN]:new Set([U.SOME_OF,U.NOT_SOME_OF]),[L.REFERENCE]:new Set([U.SOME_OF,U.NOT_SOME_OF])};function Fs(e){if(e===void 0)return{ok:!0,dateRange:void 0};if(typeof e!="object"||e===null)return{ok:!1,reason:at.INVALID_VALUE};let{start:t,end:r}=e;if(!(t instanceof Date)||!(r instanceof Date))return{ok:!1,reason:at.INVALID_VALUE};let i=t.getTime(),n=r.getTime();return!Number.isFinite(i)||!Number.isFinite(n)||i>n?{ok:!1,reason:at.INVALID_VALUE}:{ok:!0,dateRange:{start:new Date(i),end:new Date(n)}}}function Ao(e){if(Be(e))return Kp(e);let t=Ie(e.field);if(t===null)return{ok:!1,reason:at.UNKNOWN_FIELD};if(!Vp[t.valueKind].has(e.operator))return{ok:!1,reason:at.UNKNOWN_OPERATOR};if(e.operator===U.BETWEEN)return jp(e,t.valueKind);if(t.valueKind===L.NUMBER){let i=Io(e.value);return i===null?{ok:!1,reason:at.INVALID_VALUE}:{ok:!0,criterion:{...e,value:i}}}if(t.valueKind===L.DATE){let i=go(e.value);return i===null?{ok:!1,reason:at.INVALID_VALUE}:{ok:!0,criterion:{...e,value:i}}}let r=Yp(e,t.valueKind);return r!==null?{ok:!1,reason:r}:t.valueKind===L.BOOLEAN?{ok:!0,criterion:{...e,value:[...new Set(e.value)]}}:t.valueKind===L.ID_ARRAY||t.valueKind===L.ENUM||t.valueKind===L.REFERENCE?{ok:!0,criterion:{...e,value:[...new Set(e.value.map(String))]}}:{ok:!0,criterion:e}}function jp(e,t){if(t===L.NUMBER){let r=Io(e.value),i=Io(e.valueTo);return r===null||i===null||r>i?{ok:!1,reason:at.INVALID_VALUE}:{ok:!0,criterion:{...e,value:r,valueTo:i}}}if(t===L.DATE){let r=go(e.value),i=go(e.valueTo);return r===null||i===null||r.getTime()>i.getTime()?{ok:!1,reason:at.INVALID_VALUE}:{ok:!0,criterion:{...e,value:r,valueTo:i}}}return{ok:!1,reason:at.UNKNOWN_OPERATOR}}function Kp(e){return Be(e)?typeof e.key!="string"||e.key.length===0?{ok:!1,reason:at.UNKNOWN_FIELD}:e.operator!==U.SOME_OF&&e.operator!==U.NOT_SOME_OF?{ok:!1,reason:at.UNKNOWN_OPERATOR}:!Array.isArray(e.value)||e.value.some(t=>typeof t!="string")?{ok:!1,reason:at.INVALID_VALUE}:{ok:!0,criterion:e}:{ok:!1,reason:at.UNKNOWN_FIELD}}function Yp(e,t){let{value:r}=e;return t===L.BOOLEAN?Array.isArray(r)&&r.every(i=>typeof i=="boolean")?null:at.INVALID_VALUE:t===L.ID_ARRAY||t===L.ENUM||t===L.REFERENCE?Array.isArray(r)&&r.every(i=>typeof i=="string"||typeof i=="number")?null:at.INVALID_VALUE:Array.isArray(r)?at.INVALID_VALUE:null}function Io(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 go(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 w(e){return structuredClone(e)}function xs(e){return!(e.groups!==void 0&&e.groups.some(r=>r.criteria.length>0))&&e.criteria.length===0&&e.dateRange===void 0}function Ms(e,t,r){let i=e.getAllActivities();if(xs(t))return{visibleIds:bs({activities:i,parentOf:o=>e.getParentId(o),filter:t,context:He(r),viewAttributeCatalogs:e.getViewAttributeCatalogMap()}),projection:null};let n=_i({activities:i,parentOf:o=>e.getParentId(o),filter:t,context:He(r),viewAttributeCatalogs:e.getViewAttributeCatalogMap()});return{visibleIds:n.visibleIds,projection:n}}function Gp(e){if(!e||e.length===0)return{ok:!0,groups:[]};let t=[];for(let r of e){let i=[];for(let n of r.criteria){let o=Ao(n);if(!o.ok)return{ok:!1,reason:o.reason};i.push(o.criterion)}t.push({criteria:i,logic:r.logic})}return{ok:!0,groups:t}}function Us(e,t){let{adapter:r,hoursPerDay:i}=t,n=[];for(let f of e.criteria){let p=Ao(f);if(!p.ok)return{ok:!1,reason:p.reason};n.push(p.criterion)}let o=Gp(e.groups);if(!o.ok)return{ok:!1,reason:o.reason};let a=Fs(e.dateRange);if(!a.ok)return{ok:!1,reason:a.reason};let s=w({criteria:n,logic:e.logic,...o.groups.length>0?{groups:o.groups}:{},...a.dateRange!==void 0?{dateRange:a.dateRange}:{}});r.setActiveFilter(xs(s)?null:s);let{visibleIds:c,projection:l}=Ms(r,s,i);r.setFilterProjection(l);let d=Me(r,c);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:d}}}function Bs(e,t){let r=e.getActiveFilter();if(r===null)return[];let{visibleIds:i,projection:n}=Ms(e,r,t);return e.setFilterProjection(n),Me(e,i)}var Pt={ASCENDING:"asc",DESCENDING:"desc"};function ur(e){return"kind"in e&&e.kind===Ue&&"key"in e&&"direction"in e&&!("operator"in e)}var V="0";function B(e){return e==null||e===0||e==="0"}function zt(e){return B(e)?"0":String(e)}var vo=Number.MAX_SAFE_INTEGER;function jt(e,t){let r=Kr(e,t),i=t.getOrderComparator?.()??null;return r.sort(i===null?ki:(n,o)=>i(n,o)||ki(n,o)),r.map(n=>String(n.id))}function Ws(e){let t=[],r=n=>{t.push(n);let o=jt(String(n.id),e);for(let a of o){let s=e.getActivity(a);s&&r(s)}},i=jt("0",e);for(let n of i){let o=e.getActivity(n);o&&r(o)}return t}function Vs(e,t,r){let i=r.getActivity(e);if(!i)return null;let n=js(i),o=jt(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&&!$p(t,c))return c}return null}function Co(e,t){let r=t.getActivity(e);if(!r)return-1;let i=js(r);return jt(i,t).findIndex(o=>String(o)===String(e))}function Kr(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 ki(e,t){let r=Hs(e),i=Hs(t);return r!==i?r-i:String(e.id).localeCompare(String(t.id))}function Hs(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:vo}function js(e){let t=e.parentId;return t===null?"0":t}function $p(e,t){return e.has(t)?!0:e.has(String(t))}function ge(e){let t=[],r=i=>{let n=jt(i,e);n.length>1&&t.push({parentId:i,childIds:n});for(let o of n)r(o)};return r("0"),t}function So(e,t){let r=[];for(let i of t){let n=jt(i,e);n.length>1&&r.push({parentId:i,childIds:n})}return r}function zp(e){return ur(e)?typeof e.key!="string"||e.key.length===0?at.UNKNOWN_FIELD:e.direction!==Pt.ASCENDING&&e.direction!==Pt.DESCENDING?at.UNKNOWN_OPERATOR:null:Ie(e.field)===null?at.UNKNOWN_FIELD:e.direction!==Pt.ASCENDING&&e.direction!==Pt.DESCENDING?at.UNKNOWN_OPERATOR:null}function Ks(e,t){let{adapter:r}=t;for(let o of e.rules){let a=zp(o);if(a!==null)return{ok:!1,reason:a}}let i=e.rules.length===0?null:w({rules:e.rules});return r.setActiveOrder(i),{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],order:ge(r)}}}var We={GROUP:"group",ACTIVITY:"activity"},Ve="unassigned",To="g",Ri=":",Pi="Unassigned",Li=1;function Oi(e,t){return`${To}${Ri}${e}${Ri}${t}`}function qp(e){return Number.isInteger(e)&&Number.isFinite(e)}function Jp(e){return typeof e.attributeKey!="string"||e.attributeKey.length===0||!qp(e.depth)||e.depth<Li||e.direction!==Pt.ASCENDING&&e.direction!==Pt.DESCENDING||typeof e.includeWbs!="boolean"||!Array.isArray(e.collapsedIds)||e.collapsedIds.some(t=>typeof t!="string")?null:{attributeKey:e.attributeKey,depth:e.depth,direction:e.direction,includeWbs:e.includeWbs,collapsedIds:new Set(e.collapsedIds)}}function Eo(e){return{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}function Ys(e,t){let{adapter:r,hoursPerDay:i}=t;if(!Array.isArray(e.catalogs))return{ok:!1,reason:at.INVALID_VALUE};r.setViewAttributeCatalogs(e.catalogs);let n=Bs(r,i),o=r.getActiveOrder();return{ok:!0,changes:{...Eo(e),viewState:n,...o===null?{}:{order:ge(r)}}}}function Gs(e,t){let{adapter:r}=t;if(e.group===null)return r.setGroup(null),{ok:!0,changes:Eo(e)};let i=Jp(e.group);return i===null?{ok:!1,reason:at.INVALID_VALUE}:(r.setGroup(i),{ok:!0,changes:Eo(e)})}function $s(e,t){throw new Error(t)}var Do={OWN_BASELINE:"own-baseline",RECURSIVE_LEAF_SUM:"recursive-leaf-sum",ZERO:"zero"},_o={[E.PROJECT]:{alwaysSummary:!0,holdsConstraint:!1,carriesCustomId:!1,forcedDuration:null,ponderatorWeight:Do.RECURSIVE_LEAF_SUM,promotesToProjectOnFirstChild:!1},[E.TASK]:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:null,ponderatorWeight:Do.OWN_BASELINE,promotesToProjectOnFirstChild:!0},[E.MILESTONE]:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:0,ponderatorWeight:Do.ZERO,promotesToProjectOnFirstChild:!0}};function qt(e,t){return t||Hr(e)&&_o[e].alwaysSummary}function ce(e){return e===E.MILESTONE}function Ae(e){return Hr(e)&&_o[e].promotesToProjectOnFirstChild}var ko=E.PROJECT,fr=E.TASK;function Yr(e,t){return t===0?E.MILESTONE:e===0&&t>0?E.TASK:null}var F={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"},xt={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 zs(e,t){return()=>t()===e}var Ro=typeof window>"u",Xp=!Ro&&typeof MessageChannel<"u";function ut(){return Xp?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 Ni(e,t){return performance.now()-e<Ds.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await ut(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function pr(e){return Ro||await ut(),e()?{aborted:!1}:{aborted:!0}}function bi(e,t){let{inDegree:r,successors:i}=Zp(e,t),n=Qp(r),o=ty(n,r,i),a=o.length<e.length,s=a?ey(e,o):[],c=[...o].reverse();return{ordered:o,reversed:c,hasCycles:a,cycleNodes:s}}function Zp(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 Qp(e){let t=new Bt;for(let[r,i]of e)i===0&&t.enqueue(r);return t}function ty(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 ey(e,t){let r=new Set(t);return e.filter(i=>!r.has(i))}var wi=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=bi(t,r),this.cached)}};function qs(e,t){let r=[];for(let i of e)t.has(i)&&r.push(i);return r}function Fi(e,t){let r=t.getActivity(e);return r?qt(r.type,t.getChildren(e).length>0):!1}function xi(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 Ui(e,t,r){let i=Fi(e,r);return Fi(t,r)&&xi(e,t,r)||i&&xi(t,e,r)}function Zs(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 ry(e){let t=new Map;for(let r of e)Js(t,String(r.source),r),Js(t,String(r.target),r);return t}function Js(e,t,r){let i=e.get(t);if(i){i.push(r);return}e.set(t,[r])}function iy(e,t,r,i){if(e.length<=1)return e;let n=new Set(e.map(String)),o=[];for(let a of e)ny(a,n,t,r,i)||o.push(a);return o.length>0?o:e}function ny(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(oy(c,o,a,t,r,n))return!0;return!1}function oy(e,t,r,i,n,o){if(ay(e)||!(o?String(e.source)===t:String(e.target)===t))return!1;let s=sy(e,t);if(!i.has(String(s)))return!1;let c=n.getActivity(s);return!!(c?.autoScheduling!==!1&&c&&cy(e,r,c))}function ay(e){return e.source===e.target}function sy(e,t){return String(e.source)===t?e.target:e.source}function cy(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 Bi(e,t){let r=[],i=ry(e),n=0;for(let o of e){let a=Fi(o.source,t),s=Fi(o.target,t);if(ly(o,a,s,t))continue;if(!a&&!s){r.push(o);continue}let c=Xs(o.source,a,t,i,!0),l=Xs(o.target,s,t,i,!1);n=my(r,c,l,o,t,n,i)}return r}function ly(e,t,r,i){return r&&xi(e.source,e.target,i)||t&&xi(e.target,e.source,i)}function Xs(e,t,r,i,n){return t?iy(Zs(e,r),r,i,n):[e]}function dy(e,t,r){let i=Zs(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 Mi(e,t){return dy(e,t,r=>{let i=t.getActivity(r);return i?{startDate:i.startDate,endDate:i.endDate}:null})}function uy(e,t,r){return e?t?r.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function fy(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 py(e,t){let r=String(e);return(t.get(r)??[]).some(n=>String(n.target)===r)}function yy(e,t,r,i,n){if(py(e,n))return 0;let o=i.getActivity(e);return!t||!o||!r?0:i.calculateDuration({startDate:t,endDate:o.startDate,task:r})}function hy(e,t){let r=t.getActivity(e.source),i=t.getActivity(e.target),n=Mi(e.source,t),o=Mi(e.target,t),a=e.type===W.START_TO_START||e.type===W.START_TO_FINISH,s=e.type===W.FINISH_TO_FINISH||e.type===W.START_TO_FINISH;return{source:r,sourceBounds:n,targetStart:o?.startDate??i?.startDate,userLag:e.lag??0,sourceEndpointIsStart:a,targetLag:s?-uy(i,o,t):0,summarySourceId:e.type===W.START_TO_START&&n?e.source:void 0,finishAnchoredSummaryTargetId:s&&o?e.target:void 0}}function my(e,t,r,i,n,o,a){let s=hy(i,n),{source:c,sourceBounds:l,targetStart:d,userLag:u}=s,{sourceEndpointIsStart:f,targetLag:p,summarySourceId:y,finishAnchoredSummaryTargetId:I}=s,g=o;for(let _ of t){let k=f?fy(_,c,l,n):0;for(let O of r){if(String(_)===String(O))continue;let T=yy(O,d,c,n,a);e.push(Iy(i,_,O,g,k,p,u+T,y,I??(T!==0&&p===0?i.target:void 0))),g+=1}}return g}function Iy(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 Hi=class{invalidate(){}get(t,r){return Bi(t,r)}};function gy(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 Ay(e,t,r){let i=new Set,n=new Map,o=new Bt;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 Qs(e,t){let r=new Map;for(let a of t)r.set(a.id,a);let i=gy(t),n=Ay(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 tc=0,Gr=100;function je(e){return e===0}function ec(e,t,r){let i=r.type===W.FINISH_TO_START,n=r.type===W.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 W.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:o,isFS:i,isFF:n,isZeroDurationCase:!1};case W.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:o,isFS:i,isFF:n,isZeroDurationCase:!1};case W.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:o,isFS:i,isFF:n,isZeroDurationCase:!1};case W.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 vy(e,t,r){if(e._summarySourceId===void 0)return null;let i=r.getActivity(e._summarySourceId);if(!i)return null;let n=Mi(e._summarySourceId,r);return n?-r.calculateDuration({startDate:n.startDate,endDate:t.endDate,task:i}):null}function Cy(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 rc(e,t,r,i){let{sourceLag:n,targetLag:o,trueLag:a,isFS:s,isFF:c}=ec(e,t,r),l=vy(r,e,i)??n,d=l+o+a;if(!(t.durationHours===0?d!==0:l!==0||o!==0||a!==0))return Cy(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 I=new Date(Date.UTC(y.getUTCFullYear(),y.getUTCMonth(),y.getUTCDate()));return{successorStart:i.getClosestWorkTime({date:I,dir:"future",task:t}),link:r}}return{successorStart:i.getClosestWorkTime({date:y,dir:"future",task:t}),link:r}}function ic(e,t,r,i){let{sourceLag:n,targetLag:o,trueLag:a}=ec(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 nc(e,t,r){for(let i of e){let n=t.getActivity(i);if(!n)continue;let o=n.constraintType;if(!o||o===v.ASAP||o===v.ALAP)continue;let a=ms(n,t);!a.earliestStart&&!a.latestStart&&!a.earliestEnd&&!a.latestEnd||r.set(i,{activityId:i,startDate:n.startDate,endDate:n.endDate,drivingLinkId:null,kind:v.ASAP,conflict:!1,earliestStart:a.earliestStart,latestStart:a.latestStart,earliestEnd:a.earliestEnd,latestEnd:a.latestEnd})}}function Wi(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=fo(e.startDate,i):Is(n,i)?o=n:o=fo(n,i),t.startDate=o,t.endDate=r.calculateEndDate({startDate:o,durationHours:e.durationHours,task:e})}function oc(e,t){if(!e||!t)return new Date;let{constraintType:r,constraintDate:i}=e;if(!r||!i)return t;switch(r){case v.MSO:case v.MFO:return new Date(i);case v.SNET:case v.FNET:return i>t?new Date(i):t;case v.SNLT:case v.FNLT:return i<t?new Date(i):t;default:return t}}function Sy(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function ac(e,t,r){return Po(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function Po(e,t,r){return t.dragWithMultiple&&Sy(e,r)}async function sc(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 Ni(d,n);if(f.aborted)return o;d=f.newSliceStart;let p=r.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||Ty(p,r))continue;let y=a.get(String(u))??[],I=null,g=null,_=!1;for(let x of y){let A=r.getActivity(x.source);if(!A)continue;let S=s(x.source),N=S.startDate.getTime()!==A.startDate.getTime()||S.endDate.getTime()!==A.endDate.getTime(),j={...A,startDate:S.startDate,endDate:S.endDate},K=ac(j,c,l),Z={...j,startDate:K.startDate,endDate:K.endDate},st=Po(x.source,c,l)?{...x,lag:0}:x,lt=rc(Z,p,st,r);(!I||lt.successorStart>I)&&(I=lt.successorStart,g=String(x.id),_=x._summaryTargetId!==void 0&&!N&&(x._targetLag===0||i.preventSummaryTargetPullback===!0))}I!==null&&_&&I<p.startDate&&(I=new Date(p.startDate));let O=o.get(u),T=O?{...O}:{activityId:u,startDate:p.startDate,endDate:p.endDate,drivingLinkId:null,kind:v.ASAP,conflict:!1},P=T.earliestStart||T.latestStart||T.earliestEnd||T.latestEnd;if(!(!I&&!P)){if(I){let x=I;p.type===E.MILESTONE&&(x=oc(p,I)),T.drivingLinkId=g,T.startDate=x,T.endDate=r.calculateEndDate({startDate:x,durationHours:p.durationHours,task:p}),T.earliestSchedulingStart=x,T.earliestSchedulingEnd=T.endDate}else p.constraintType===v.MSO?T.earliestStart&&(T.startDate=T.earliestStart,T.endDate=T.earliestEnd??r.calculateEndDate({startDate:T.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===v.MFO&&T.latestStart&&(T.startDate=T.latestStart,T.endDate=T.latestEnd??r.calculateEndDate({startDate:T.latestStart,durationHours:p.durationHours,task:p}));Wi(p,T,r),o.set(u,T)}}return o}function Ty(e,t){return qt(e.type,t.getChildren(e.id).length>0)}async function cc(e,t,r,i,n,o){let a=new Map(r),s=i.getAllActivities(),c=s.length,l=[];for(let g of s)g.constraintType===v.ALAP&&l.push(g.id);if(l.length===0)return a;let d=new Map,u=new Map;for(let g of t){let _=String(g.source);d.has(_)||d.set(_,[]),d.get(_).push(g);let k=String(g.target);u.has(k)||u.set(k,[]),u.get(k).push(g)}let f=g=>{let _=a.get(g);if(_)return{startDate:_.startDate,endDate:_.endDate};let k=i.getActivity(g);return k?{startDate:k.startDate,endDate:k.endDate}:{startDate:new Date,endDate:new Date}},p=g=>!g.parentId||B(g.parentId)?i.getProjectEnd():f(g.parentId).endDate,y=(g,_)=>{let k=g,O=0;for(;k&&!B(k)&&O++<c+1;){if(String(k)===String(_))return!0;let T=i.getActivity(k);if(!T||!T.parentId)break;k=T.parentId}return!1},I=performance.now();for(let g of e){let _=await Ni(I,o);if(_.aborted)return a;I=_.newSliceStart;let k=i.getActivity(g);if(!k||k.constraintType!==v.ALAP||!k.autoScheduling||k.progress===100||qt(k.type,i.getChildren(g).length>0))continue;let O=p(k),T=O,P=null,x=null,A=!1,S=d.get(String(g))??[];for(let Vt of S){if((Vt.lag??0)<0)continue;let sr=i.getActivity(Vt.target);if(!sr||sr.autoScheduling===!1)continue;let ys=f(Vt.target),Zf={...sr,startDate:ys.startDate,endDate:ys.endDate},hi=ic(Zf,k,Vt,i);(T===null||hi<T)&&(T=hi),(P===null||hi<P)&&(P=hi,x=Vt.type,A=k.parentId&&!B(k.parentId)?y(Vt.target,k.parentId):!1)}if(P!==null)if(A||O===null)T=P;else{let Vt=f(g).endDate,sr=Vt.getTime()>O.getTime()?Vt:O;T=P<sr?P:sr}else{if(O===null||T===null)continue;T>O&&(T=O)}if(T===null)continue;let j=(u.get(String(g))??[]).some(Vt=>Vt.type===W.FINISH_TO_START||Vt.type===W.FINISH_TO_FINISH),K=new Date(Date.UTC(T.getUTCFullYear(),T.getUTCMonth(),T.getUTCDate())),Z=()=>i.getClosestWorkTime({date:K,dir:"past",task:k}),st=i.getClosestWorkTime({date:T,dir:"future",task:k}).getTime()===T.getTime(),lt;k.durationHours===0&&P===null?lt=j&&st?Z():i.getClosestWorkTime({date:T,dir:"past",task:k}):k.durationHours===0?P!==null&&x===W.FINISH_TO_START&&T.getTime()===P.getTime()?lt=T:j?lt=Z():lt=i.getClosestWorkTime({date:T,dir:"future",task:k}):lt=i.getClosestWorkTime({date:T,dir:"future",task:k});let dt=i.calculateEndDate({startDate:lt,durationHours:-k.durationHours,task:k}),re=a.get(g),Ft=re?{...re}:{activityId:g,startDate:dt,endDate:lt,drivingLinkId:null,kind:v.ALAP,conflict:!1};Ft.startDate=dt,Ft.endDate=lt,Ft.drivingLinkId=null,Ft.kind=v.ALAP;let ar=Ft.earliestSchedulingStart??null;Ft.earliestSchedulingStart=null,Ft.earliestSchedulingEnd=null;let lo=ar!==null&&ar.getTime()>dt.getTime()?ar:dt;Ft.latestSchedulingStart=lo,Ft.latestSchedulingEnd=lo===dt?lt:i.calculateEndDate({startDate:lo,durationHours:k.durationHours,task:k}),Wi(k,Ft,i),a.set(g,Ft)}return a}var yr={warn(){},error(){}};var Ey=864e5;function ie(e){if(e.type===E.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)/Ey)+1}function $r(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=ie(n),e.updateActivity(r))}})}function Lo(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 Dy(n,i,r)}function zr(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 Bt;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 Dy(e,t,r){if(t===r)return!0;let i=new Set([t]),n=new Bt;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 Vi(e){let t=_y(e);for(let r of t.adjacency.keys())t.records.has(r)||ky(r,t);return t.components}function _y(e){let t=new Map,r=new Set;for(let i of e){let n=String(i.source),o=String(i.target),a=lc(t,n);if(lc(t,o),n===o){r.add(n);continue}a.push(o)}return{adjacency:t,selfLooped:r,records:new Map,componentStack:[],nextIndex:0,components:[]}}function lc(e,t){let r=e.get(t);if(r)return r;let i=[];return e.set(t,i),i}function ky(e,t){let r=[];for(r.push({node:e,record:dc(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;Ry(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&&Py(i.node,t)}}function Ry(e,t,r,i){let n=i.records.get(t);if(!n){r.push({node:t,record:dc(t,i),neighborCursor:0});return}n.onStack&&n.visitIndex<e.record.lowLink&&(e.record.lowLink=n.visitIndex)}function dc(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 Py(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 qr(e,t,r){let i=r?new Oo(e,r):e;return Bi([...t],i)}var Oo=class{constructor(t,r){this.base=t;for(let[i,n]of r.reparented){let o=String(i),a=n===null||B(n)?null:n,s=t.getActivity(i)?.parentId??null,c=s===null||B(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||B(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 ve(e){let{port:t,proposedPort:r,currentLinks:i,proposedLinks:n,proposal:o}=e,a=qr(r??t,n,o);if(!zr(a))return{ok:!0};let s=qr(t,i),c=uc(s),d=[...uc(a)].filter(u=>!c.has(u));return d.length===0?{ok:!0}:{ok:!1,newlyCyclicActivityIds:d}}function uc(e){let t=new Set;for(let r of Vi(e))for(let i of r)t.add(i);return t}function Ki(e,t,r){return r.getChildren(e).length>0||r.getChildren(t).length>0}function Ce(e,t){switch(e.kind){case Et.CREATE:return Ly(e,t);case Et.UPDATE:return Oy(e,t.port,t.rejectParentLinkMutations??!1);case Et.DELETE:return Ny(e,t)}}function Gi(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=Yi(l);i.has(d)||i.set(d,l.id),n.push({source:l.source,target:l.target})}let o=zr(n),a=null;for(let{operation:l,linkId:d}of e){if(String(l.source)===String(l.target)){a={applied:!1,rejected:ct.SELF_LINK};break}if(!t.port.getActivity(l.source)||!t.port.getActivity(l.target)){a={applied:!1,rejected:ct.ACTIVITY_MISSING};break}if(t.rejectParentLinkMutations&&Ki(l.source,l.target,t.port)){a={applied:!1,rejected:ct.HIERARCHY_LINK};break}if(Ui(l.source,l.target,t.port)){a={applied:!1,rejected:ct.HIERARCHY_LINK};break}let u=Yi(l),f=i.get(u);if(f!==void 0){a={applied:!1,rejected:ct.DUPLICATE,linkId:f};break}if(i.set(u,d),o&&Lo(n,{source:l.source,target:l.target}))return{applied:!1,rejected:ct.CYCLE};n.push({source:l.source,target:l.target})}if(!o&&zr(n))return{applied:!1,rejected:ct.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(!ve({port:t.port,currentLinks:r,proposedLinks:s}).ok)return{applied:!1,rejected:ct.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 Yi(e){return JSON.stringify([String(e.source),String(e.target),e.type])}function Ly(e,t){let{port:r}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:ct.SELF_LINK};let i=r.getActivity(e.source),n=r.getActivity(e.target);if(!i||!n)return{applied:!1,rejected:ct.ACTIVITY_MISSING};if(t.rejectParentLinkMutations&&Ki(e.source,e.target,r))return{applied:!1,rejected:ct.HIERARCHY_LINK};if(Ui(e.source,e.target,r))return{applied:!1,rejected:ct.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:ct.DUPLICATE,linkId:d.id};let a=o.map(d=>({source:d.source,target:d.target}));if(Lo(a,{source:e.source,target:e.target}))return{applied:!1,rejected:ct.CYCLE};let s=(t.newLinkId??by)(),c={id:s,source:e.source,target:e.target,type:e.type,lag:e.lag,freeSlackHours:null,isCritical:!1};return ve({port:r,currentLinks:o,proposedLinks:[...o,c]}).ok?(r.addLink(c),{applied:!0,linkId:s}):{applied:!1,rejected:ct.CYCLE}}function Oy(e,t,r){let i=t.getLink(e.linkId);if(!i)return{applied:!1,rejected:ct.LINK_MISSING};let n={...i,source:e.source??i.source,target:e.target??i.target,type:e.type??i.type,lag:e.lag??i.lag};if(String(n.source)===String(n.target))return{applied:!1,rejected:ct.SELF_LINK};if(!t.getActivity(n.source)||!t.getActivity(n.target))return{applied:!1,rejected:ct.ACTIVITY_MISSING};if(r&&(Ki(i.source,i.target,t)||Ki(n.source,n.target,t)))return{applied:!1,rejected:ct.HIERARCHY_LINK};if(Ui(n.source,n.target,t))return{applied:!1,rejected:ct.HIERARCHY_LINK};let o=t.getAllLinks(),a=o.find(l=>String(l.id)!==String(e.linkId)&&Yi(l)===Yi(n));if(a)return{applied:!1,rejected:ct.DUPLICATE,linkId:a.id};let s=o.map(l=>String(l.id)===String(e.linkId)?n:l);return ve({port:t,currentLinks:o,proposedLinks:s}).ok?((String(i.source)!==String(n.source)||String(i.target)!==String(n.target))&&t.setLinkEndpoints(e.linkId,n.source,n.target),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:ct.CYCLE}}function Ny(e,t){let{port:r}=t;return r.getLink(e.linkId)?(r.removeLink(e.linkId),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:ct.LINK_MISSING}}var ji=null;function by(){return ji===null&&(ji=Date.now()),ji+=1,String(ji)}var Dt={FINISH_TO_START:"fs",START_TO_START:"ss",FINISH_TO_FINISH:"ff",START_TO_FINISH:"sf"},$i={[W.FINISH_TO_START]:Dt.FINISH_TO_START,[W.START_TO_START]:Dt.START_TO_START,[W.FINISH_TO_FINISH]:Dt.FINISH_TO_FINISH,[W.START_TO_FINISH]:Dt.START_TO_FINISH},Ke={[Dt.FINISH_TO_START]:W.FINISH_TO_START,[Dt.START_TO_START]:W.START_TO_START,[Dt.FINISH_TO_FINISH]:W.FINISH_TO_FINISH,[Dt.START_TO_FINISH]:W.START_TO_FINISH},fc=Dt.FINISH_TO_START;function pc(e){if(e in Ke)return Ke[e]}var yc=";",Se={DAY:"d",WEEK:"w",WEEK_DHTMLX:"wk",MONTH:"m",MONTH_DHTMLX:"mon",YEAR:"y"},hc=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)(weeks?|wk|w|months?|mon|m|days?|d|years?|y)?)?$/i;var wy=5,zi=30,No=365,Fy={[Se.DAY]:1,day:1,days:1,[Se.MONTH]:zi,[Se.MONTH_DHTMLX]:zi,month:zi,months:zi,[Se.YEAR]:No,year:No,years:No},xy=new Set([Se.WEEK,Se.WEEK_DHTMLX,"week","weeks"]);function qi(e,t={}){let r=[],i=[],n=t.daysPerWeek!==void 0&&Number.isFinite(t.daysPerWeek)&&t.daysPerWeek>0?t.daysPerWeek:wy,o=e.replace(/\s+/g,"");if(o.length===0)return{specs:r,errors:i};for(let a of o.split(yc)){if(a.length===0)continue;let s=My(a,n);s?r.push(s):i.push(a)}return{specs:r,errors:i}}function My(e,t){let r=e.toLowerCase(),i=hc.exec(r);if(!i)return null;let[,n,o,a,s,c]=i,l=o?Ke[o]:Ke[fc],d=0;if(s!==void 0){let u=Number(s);if(Number.isNaN(u))return null;let f=c!==void 0&&xy.has(c)?t:Fy[c??Se.DAY],p=u*f;d=a==="-"?-p:p}return{correlativeId:n,type:l,lag:d}}function Xi(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=Ji(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(Ji(c.source,c.type),c);let s=[];for(let[c,l]of a)o.has(c)||s.push({kind:Et.DELETE,linkId:l.id});for(let[c,l]of o){let d=a.get(c);d&&d.lag!==l.lag&&s.push({kind:Et.UPDATE,linkId:d.id,lag:l.lag})}for(let[c,l]of o)a.has(c)||s.push({kind:Et.CREATE,source:l.source,target:t,type:l.type,lag:l.lag});return{operations:s,unresolved:n}}function Ji(e,t){return`${String(e)}::${t}`}function Zi(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=Ji(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(Ji(c.target,c.type),c);let s=[];for(let[c,l]of a)o.has(c)||s.push({kind:Et.DELETE,linkId:l.id});for(let[c,l]of o){let d=a.get(c);d&&d.lag!==l.lag&&s.push({kind:Et.UPDATE,linkId:d.id,lag:l.lag})}for(let[c,l]of o)a.has(c)||s.push({kind:Et.CREATE,source:t,target:l.target,type:l.type,lag:l.lag});return{operations:s,unresolved:n}}function Qi(e){let t=Math.sign(e)*Math.round(Math.abs(e));return Object.is(t,-0)?0:t}function Kt(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var mc={rawInputToConstraintDate(e,t){let r=new Date(e);return r.setUTCHours(0,0,0,0),r.getTime()===e.getTime()?t.getClosestWorkTime({direction:Y.FUTURE,date:e,unit:pt.HOUR}):t.isWorkTime(e,pt.HOUR)?e:r},computeLagBetweenTasks(e,t,r){return r.calculateDuration(e,t)}};function bo(e,t,r){switch(r){case W.FINISH_TO_START:return{sourceDate:e.endDate,targetDate:t.startDate};case W.START_TO_START:return{sourceDate:e.startDate,targetDate:t.startDate};case W.FINISH_TO_FINISH:return{sourceDate:e.endDate,targetDate:t.endDate};case W.START_TO_FINISH:return{sourceDate:e.startDate,targetDate:t.endDate}}}var wo=mc;var hr=class{adapter;reporter;currentCalculationId=0;topoCache=new wi;expandedLinksCache=new Hi;constructor(t,r=yr){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=zs(r,()=>this.currentCalculationId),n={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{Hy(this.adapter);let o=Te("schedule.total"),a=Te("schedule.expandParentLinks"),s=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(s,this.adapter);le(a);let l=c;if((await pr(i)).aborted)return{...n,cancelled:!0};let d=Te("schedule.scoping"),u=this.adapter.getAllIds(),f=Wy(t,l,this.adapter),p=f.links,y=f.idSet;le(d);let I=Te("schedule.topologicalSort"),g=jy(this.topoCache,u,l,y);if(le(I),g.hasCycles)return le(o),{...n,cycles:[g.cycleNodes]};if((await pr(i)).aborted)return{...n,cancelled:!0};let _=Te("schedule.processConstraints"),k=new Map;if(nc(g.ordered,this.adapter,k),le(_),(await pr(i)).aborted)return{...n,cancelled:!0};let O=Te("schedule.asapPass"),T=await sc(g.ordered,p,this.adapter,t,i,k);if(le(O),(await pr(i)).aborted)return{...n,cancelled:!0};let P=Te("schedule.alapPass"),x=await cc(g.reversed,p,T,this.adapter,t,i);if(le(P),(await pr(i)).aborted)return{...n,cancelled:!0};let A=Te("schedule.diff"),S=[];for(let[N,j]of x){let K=this.adapter.getActivity(N);if(!K)continue;let Z=K.startDate.getTime()!==j.startDate.getTime(),st=K.endDate.getTime()!==j.endDate.getTime();(Z||st)&&S.push(N)}return le(A),le(o),{plans:x,updatedIds:S,cycles:[],cancelled:!1}}catch(o){throw this.reporter.error("[AutoScheduler] Error during scheduling",o),o}}},Uy=!1;function By(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:Uy}function Te(e){return{name:e,startedAt:performance.now()}}function Hy(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function le(e){if(!By())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function Wy(e,t,r){let i=e.triggerId;if(i==null)return{idSet:null,links:t};let n=Qs(i,t);return Vy(n,t,r)}function Vy(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===v.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 jy(e,t,r,i){let n=e.get(t,r);if(n.hasCycles){let a=i?Array.from(i):t;return bi(a,r)}if(!i)return n;let o=qs(n.ordered,i);return{ordered:o,reversed:[...o].reverse(),hasCycles:!1,cycleNodes:[]}}function Ic(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===v.ALAP||ce(i.type)&&(s.type===W.START_TO_FINISH||s.type===W.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=bo(c,n,s.type),f=wo.computeLagBetweenTasks(d,u,o);f!==s.lag&&t.setLinkField(s.id,xt.LAG,f)}}function gc(e,t){let r=t.getActivity(e);r&&ce(r.type)&&(r.durationHours=0)}function tn(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 Ac(e){return Number(e.toFixed(2))}function Jr(e){for(let t of Ky(e))Cc(t,e)}function vc(e,t){for(let r of e)Cc(r,t)}function Ky(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,Yy(i,e));return[...t].sort((i,n)=>(r.get(n)??0)-(r.get(i)??0))}function Yy(e,t){let r=0,i=e;for(;i&&i!=="0"&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function Cc(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)})}Fo(e,i,t)}function Fo(e,t,r){let i=r.getActivity(e);if(!i)return;let n=tn(t);if(n===null){let o=r.getProgressFallback(e);o!==null&&r.setActivityField(e,D.PROGRESS,o);return}r.getProgressFallback(e)===null&&r.setProgressFallback(e,Number(i.progress??0)),r.setActivityField(e,D.PROGRESS,Ac(n))}function Sc(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 Mt(e,t){return(Number(e)||0)*(Number(t)||0)/100}var Xr={SKIP:"skip",FREEZE_WITHOUT_CONTRIBUTION:"freeze-when-no-contribution"};async function mr(e,t,r=!0,i={}){let n=t?Zr(e,t):Xy(e),o=r?i.progressMode??Xr.FREEZE_WITHOUT_CONTRIBUTION:Xr.SKIP;await Gy(n,e,o,{recomputeRealWork:i.recomputeRealWork??!1})}function en(e,t){Tc(e,t,Xr.SKIP)}async function Gy(e,t,r,i={recomputeRealWork:!1}){let o=0;for(let a of e)Tc(a,t,r,i.recomputeRealWork),o+=1,o%200===0&&await ut()}function Zr(e,t){let r=new Set,i=new Map;for(let a of t)$y(a,e,r,i);if(r.size===0)return[];let n=Array.from(r),o=zy(n,i);return Ec(n,o)}function $y(e,t,r,i){let n=t.getParentId(e);for(;n&&!B(n);){if(r.has(n))return;r.add(n);let o=t.getParentId(n);i.set(n,o),n=o}}function zy(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&&!B(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 qy(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+=Jy(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 Tc(e,t,r=Xr.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=qy(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!==Xr.SKIP&&Fo(e,a.weightedChildren,t),i&&t.setActivityField(e,"realWorkHours",a.realWorkSum)}function Jy(e,t){return t?Number(e.realWorkHours)||0:Mt(e.workHours,e.progress)}function Xy(e){let t=Zy(e),r=Qy(t,e);return Ec(t,r)}function Zy(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function Qy(e,t){let r=new Map;for(let i of e)r.set(i,th(i,t));return r}function th(e,t){let r=0,i=e;for(;i&&!B(i)&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function Ec(e,t){return[...e].sort((r,i)=>(t.get(i)??0)-(t.get(r)??0))}var Dc={updateActivityDuration:gc,updateTaskTiming:rh("updateTaskTiming"),adjustLinkLagOnTaskMove:Ic,recordLastStartDate:eh};function eh(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function Ee(e,t,r,i){for(let n of t){let o=n in Dc?Dc[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 rh(e){return()=>{console.debug(`[replay post-processors] ${e}: not yet ported to adapter \u2014 no-op.`)}}function G(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 rt(){return{valid:!0}}function gt(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function Q(){return{allowed:!0}}function ot(e,t){return t!==void 0?{allowed:!1,reason:e,alertKey:t}:{allowed:!1,reason:e}}function et(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 ht={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 _c={targetField:"name",canEdit(){return Q()},parseInput(e){return typeof e!="string"?J("not_a_string"):G(e)},validate(){return rt()},transform(e,t){return et({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:ht.NAME_ENTRY};var kc={targetField:"description",canEdit(){return Q()},parseInput(e){return typeof e!="string"?J("not_a_string"):G(e.trim())},validate(){return rt()},transform(e,t){return et({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:ht.DESCRIPTION_ENTRY};function Jt(e){return e.constraintType??v.ASAP}var rn=100;function De(e){return e.progress>=rn}function At(e,t){return qt(e.type,t.hasChildren(e.id))}function Rc(e){return e.progress>0}function Pc(e){return e.hasLookaheadTasks}function Ye(e,t){return Math.round(Math.ceil(e*t*60)/60)}var Ir=e=>({endDate:e});var nn="UTC";function _e(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 on(e,t){if(!t||t===nn){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 ih(e,t){let r=_e(t,nn);for(;!e.isWorkTime(r,pt.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=_e(r,nn);return r}function xo(e,t){return e.getClosestWorkTime({direction:Y.FUTURE,date:t,unit:pt.HOUR})}function Mo(e,t){let r=ih(e,t),i=new Date(r);return i.setUTCDate(i.getUTCDate()+1),i.setUTCHours(0,0,0,0),e.getClosestWorkTime({direction:Y.PAST,date:i,unit:pt.HOUR})}var Qr=new Set([v.SNET,v.SNLT,v.MSO]),Uo=new Set([v.FNET,v.FNLT,v.MFO]),ke=new Set([v.ASAP,v.ALAP]),an=v.SNET;function de(e,t,r){let i=_e(e,nn);if(!Qr.has(r)&&!Uo.has(r))return i;let n=Qr.has(r)?xo(t,i):Mo(t,i),o=new Date(i);return o.setUTCHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),o}var Re=()=>({constraintType:an});var Ge=e=>({constraintDate:e}),Lc=e=>({constraintDate:e});var Oc={UPDATE_ACTIVITY_DURATION:"updateActivityDuration",UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var Nc={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"},ti={COMPLETED:"completed",SUMMARY:"summary",HAS_PROGRESS:"has_progress",HAS_LOOKAHEAD_TASKS:"has_lookahead_tasks",SIR_START_AFTER_PROGRESS:"sir_start_after_progress"},bc={CANT_EDIT_COMPLETED:"cant_edit_completed_activity",SUMMARY_COLUMN_VALUE:"summary_column_value",CANT_EDIT_WITH_PROGRESS:"cant_edit_activity_with_progress",SIR_CANT_MOVE_START_AFTER_PROGRESS:"sir_cant_move_start_after_progress",CANT_EDIT_WITH_TASK:"cant_edit_actvity_with_task"};function gr(e,t,r){return gi(e,t,r)}function Ar(e,t,r){return Ai(e,t,r)}var Fc={targetField:"durationHours",canEdit(e,t){return De(e)?ot("completed","cant_edit_completed_activity"):At(e,t)?ot("summary","summary_column_value"):Q()},parseInput(e,t,r){let i=parseFloat(String(e));return Number.isFinite(i)?G(Ye(i,r.hoursPerDay)):J("not_a_number")},validate(e,t,r){return wc(r)?gt(Nc.NEGATIVE_DURATION):nh(t,r)?gt("unchanged"):rt()},transform(e,t,r){if(wc(t))return et({},{autoSchedule:!1,postProcessors:[]});let i=oh(e,t,r),n=ah(e,t,r,i.violated);return{...et(n,{autoSchedule:!0,postProcessors:[Oc.RECORD_LAST_START_DATE]}),...i.violated?{constraintWarning:Ar(i.constraintType,i.constraintDate,xc(e,t,r)??void 0)}:{}}},trackEvent:ht.DURATION_ENTRY};function wc(e){return Math.sign(e)===-1}function nh(e,t){return e===t}function oh(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return{violated:!1};let n=e.constraintType;if(n!==v.FNET&&n!==v.FNLT&&n!==v.MFO)return{violated:!1};let o=i.calculateEndDate(e.startDate,t);return gr(n,e.constraintDate,o)}function ah(e,t,r,i=!1){let n={};i&&Object.assign(n,Re(),Ge(e.startDate));let o=Yr(e.durationHours,t);o&&(n.type=o),n.durationHours=t;let a=xc(e,t,r);return a&&Object.assign(n,Ir(a)),n}function xc(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateEndDate(e.startDate,t):null}var vr=e=>({realWorkHours:e});var sh=0,ch=rn,sn={targetField:"progress",canEdit(e,t){return At(e,t)?ot("summary","summary_column_value"):Pc(e)?ot("has_lookahead_tasks","cant_edit_actvity_with_task"):Q()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?J("not_a_number"):G(t)},validate(e,t,r){return lh(r)?gt("out_of_range"):rt()},transform(e,t,r){let i=je(t),n=e.progress!==t&&i,o=dh(t),a=ph(e,t,r.hierarchy),s={progress:t,autoScheduling:i,...vr(a.get(e.id)??0)},c=o?uh(e,t,i,r.hierarchy,a):[],l=o?hh(e,t,r.hierarchy):[],d=c.length+l.length>0?[...c,...l]:void 0,u=[],f=o?Ih(e,t):void 0;return et(s,{autoSchedule:n,postProcessors:u,cascadeMutations:d,trackingEvents:f})},trackEvent:ht.PROGRESS_ENTRY};function lh(e){return e<sh||e>ch}function dh(e){return e===rn||je(e)}function uh(e,t,r,i,n){return i.getDescendantIds(e.id).map(a=>({activityId:a,fields:fh(t,r,n.get(a)??0)}))}function fh(e,t,r){return{progress:e,autoScheduling:t,...vr(r)}}function ph(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):Mt(c.workHours,t);i.set(c.id,l),s+=l}return s},o=r.hasChildren(e.id)?n(e.id):Mt(e.workHours,t);return i.set(e.id,o),i}function yh(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 hh(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=[...yh(e,r),...r.getAncestorIds(e.id)],o=[];for(let a of n){let s=mh(a,i,r);s!==null&&(i.set(a,s),o.push({activityId:a,fields:{progress:s}}))}return o}function mh(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=tn(i);return n===null?null:Number(n.toFixed(2))}function Ih(e,t){return[{name:ht.PROGRESS_UPDATE_RADIO_BUTTON,properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var Mc={targetField:"cost",canEdit(e,t){return At(e,t)?ot("summary","summary_column_value"):Q()},parseInput(e){if(String(e).trim()==="")return G(0);let t=parseFloat(String(e));return Number.isNaN(t)?J("not_a_number"):G(t)},validate(){return rt()},transform(e,t,r){let i=gh(e,t,r.hierarchy);return et({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:ht.COST_BUDGETED_ENTRY};function gh(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 Uc={targetField:"usedCost",canEdit(e,t){return At(e,t)?ot("summary","summary_column_value"):Q()},parseInput(e){if(String(e).trim()==="")return G(0);let t=parseFloat(String(e));return Number.isNaN(t)?J("not_a_number"):G(t)},validate(){return rt()},transform(e,t,r){let i=Ah(e,t,r.hierarchy);return et({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:ht.COST_SPENT_ENTRY};function Ah(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 Bc={targetField:"workHours",canEdit(e,t){return At(e,t)?ot("summary","summary_column_value"):Q()},parseInput(e){if(String(e).trim()==="")return G(0,e);let t=parseFloat(String(e));return Number.isNaN(t)?J("not_a_number"):G(t)},validate(){return rt()},transform(e,t,r,i){let n=Hc(t,e.progress),o=String(i).trim()===""?[]:vh(e,t,n,r.hierarchy);return et({workHours:t,...vr(n)},{autoSchedule:!1,postProcessors:[],cascadeMutations:o})},trackEvent:ht.LABOR_HOURS_BUDGETED_ENTRY};function Hc(e,t){return Mt(e,t)}function vh(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??Hc(d.workHours,d.progress);c+=u,l+=f}n.set(s,c),o.set(s,l),a.push({activityId:s,fields:{workHours:c,...vr(l)}})}return a}function ei(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function Bo(e,t){return e.getTime()<t.getTime()}function $e(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var cn=e=>({durationHours:e});var Ch="sir-apply",Wc={targetField:"startDate",canEdit(e,t,r){return At(e,t)?ot("summary","summary_column_value"):Rc(e)?r?.eventSource!==Ch?ot("has_progress","cant_edit_activity_with_progress"):De(e)?ot("completed","cant_edit_completed_activity"):$e(r.newValue)?ei(e.startDate,r.newValue)?Q():r.newValue.getTime()>e.startDate.getTime()?ot("sir_start_after_progress","sir_cant_move_start_after_progress"):Q():Q():Q()},parseInput(e,t,r){return $e(e)?G(_e(e,"UTC")):J("invalid_date")},validate(e,t,r,i){if(ei(t,r))return gt("unchanged");let n=Sh(e,r,i);return n||rt()},transform(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)throw new Error("startDatePipeline: no calendar resolved (integrity)");let n=xo(i,t),o=e.type===E.MILESTONE,a=o?n:i.calculateEndDate(n,e.durationHours),s=n;return{...et({startDate:n,...Ir(a),...o?cn(0):{},...Re(),...Ge(s)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:Th(e,n,i)}},trackEvent:ht.START_DATE_ENTRY};function Sh(e,t,r){let i=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!i)return null;let n=_e(i,"UTC");return t.getTime()<n.getTime()?gt("before_parent_start"):null}function Th(e,t,r){let i=r.calculateEndDate(t,e.durationHours),n=Fe(Jt(e),t,i),o=gr(Jt(e),e.constraintDate,n);if(o.violated)return Ar(o.constraintType,o.constraintDate,n)}var Eh=99.999,jc={targetField:"endDate",canEdit(e,t){return At(e,t)?ot("summary","summary_column_value"):Dh(e)?ot("completed","cant_edit_completed_activity"):Q()},parseInput(e,t,r){if(!$e(e))return J("invalid_date");let i=_e(e,"UTC"),n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(i,pt.DAY)?G(Mo(n,i)):G(n.getClosestWorkTime({direction:"past",date:i,unit:pt.HOUR})):G(i)},validate(e,t,r,i){if(ei(e.endDate,r))return gt("unchanged");if(_h(r,e))return gt("before_date_origin");if(kh(r,e))return gt("before_start_date");let n=Rh(r,e,i);return n||rt()},transform(e,t,r){let i=Ph(e,t),n=Lh(e,t,r,!!i);return{...et(n,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...i?{constraintWarning:i}:{}}},trackEvent:ht.END_DATE_ENTRY};function Dh(e){return e.progress>=Eh}function _h(e,t){return t.dateOrigin?Bo(e,t.dateOrigin):!1}function kh(e,t){return Bo(e,t.startDate)}function Rh(e,t,r){let i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(e,pt.DAY)?null:gt("not_working_day"):null}function Ph(e,t){if(Jt(e)===v.MSO)return;let i=Fe(Jt(e),e.startDate,t),n=gr(Jt(e),e.constraintDate,i);if(n.violated)return Ar(n.constraintType,n.constraintDate,i)}function Lh(e,t,r,i=!1){let n={};ce(e.type)&&!i&&Vc(e)?Object.assign(n,Ge(e.startDate)):(i||Vc(e))&&Object.assign(n,Re(),Ge(e.startDate));let s=Oh(e,t,r),c=Yr(e.durationHours,s);return c&&(n.type=c),Object.assign(n,cn(s)),n.endDate=t,n}function Vc(e){return ke.has(Jt(e))}function Oh(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateDuration(e.startDate,t):e.durationHours}var Nh=new Set(Object.values(v)),Kc={targetField:"constraintType",canEdit(e,t){return De(e)?ot("completed","cant_edit_completed_activity"):At(e,t)?ot("summary","summary_column_value"):Q()},parseInput(e){let t=String(e).toLowerCase();return bh(t)?G(t):J("invalid_constraint_type")},validate(){return rt()},transform(e,t,r){let i=wh(e,t,r);return et(i,{autoSchedule:!0})}};function bh(e){return Nh.has(e)}function wh(e,t,r){let i=xh(e,t);return{constraintType:t,...Lc(Fh(e,t,i,r))}}function Fh(e,t,r,i){if(e.type!==E.MILESTONE||!r||Qr.has(t))return r;let n=i.calendars.getCalendar(String(e.calendarId));return n?de(r,n,t):r}function xh(e,t){return ke.has(t)?null:Qr.has(t)?e.startDate:Uo.has(t)?e.endDate:e.constraintDate}var Yc={targetField:"constraintDate",canEdit(e,t){return De(e)?ot("completed","cant_edit_completed_activity"):At(e,t)?ot("summary","summary_column_value"):Q()},parseInput(e){return $e(e)?G(e):J("invalid_date")},validate(){return rt()},transform(e,t,r){let i=Gc(e)?an:Jt(e),n=r.calendars.getCalendar(e.calendarId);if(!n)throw new Error("constraintDatePipeline: no calendar resolved (integrity)");let o=de(t,n,i),a=Mh(e,o);return et(a,{autoSchedule:!0})}};function Mh(e,t){return{constraintDate:t,...Gc(e)?Re():{}}}function Gc(e){return ke.has(Jt(e))||!e.constraintType}var $c={targetField:"calendarId",canEdit(){return Q()},parseInput(e){let t=String(e).trim();return Uh(t)?J("empty_calendar"):G(t)},validate(e,t,r,i){return Bh(e.calendarId,r)?gt("unchanged"):i.calendars.getCalendar(r)?rt():gt("unknown_calendar")},transform(e,t,r){return et(Hh(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:ht.CALENDAR_ASSIGNMENT};function Uh(e){return e===""}function Bh(e,t){return e===t}function Hh(e,t,r){let i={calendarId:t,assignedDefaultCalendar:!1},n=r.calendars.getCalendar(t);if(n){let o=n.isWorkTime(e.startDate,"hour"),a=n.getClosestWorkTime({date:o?zc(e.startDate):e.startDate,direction:"future",unit:"hour"});i.startDate=a;let s=Wh(e,n);if(s&&(i.constraintDate=s),!e.autoScheduling)return i;Object.assign(i,Ir(n.calculateEndDate(a,e.durationHours)))}return i}function Wh(e,t){return!e.constraintDate||!e.constraintType?null:Wr({...e,constraintDate:zc(e.constraintDate)},{getClosestWorkTime:({date:r,dir:i})=>t.getClosestWorkTime({date:r,direction:i,unit:pt.HOUR})})}function zc(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var qc={targetField:"customId",canEdit(e,t){return At(e,t)?ot("summary","summary_column_value"):Q()},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"):G(t)},validate(){return rt()},transform(e,t){return et({customId:t},{autoSchedule:!1,postProcessors:[]})}};var Jc={targetField:"subcontractId",canEdit(){return Q()},parseInput(e){if(e==null)return G(null);if(typeof e=="string"){let t=e.trim();if(t.length===0)return G(null);let r=Number(t);return!Number.isFinite(r)||!Number.isInteger(r)?J("not_an_integer"):G(r)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?J("not_an_integer"):G(e):J("not_an_integer")},validate(){return rt()},transform(e,t){return et({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function ri(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 ln(e){return e.some(t=>ri(t)===null)}var Xc={targetField:"responsableIds",canEdit(){return Q()},parseInput(e){return e==null?G([]):Array.isArray(e)?G(e):J("not_an_array")},validate(e,t,r){return ln(r)?gt("missing_id"):rt()},transform(e,t){let r=t.map(ri).filter(i=>i!==null);return et({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var Zc={targetField:"tagIds",canEdit(){return Q()},parseInput(e){return e==null?G([]):Array.isArray(e)?G(e):J("not_an_array")},validate(e,t,r){return ln(r)?gt("missing_id"):rt()},transform(e,t){let r=t.map(ri).filter(i=>i!==null);return et({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var Vh=new Map([[D.TEXT,_c],[D.DESCRIPTION,kc],[D.DURATION,Fc],[D.PROGRESS,sn],[D.COST,Mc],[D.USED_COST,Uc],[D.HH_WORK_TIME,Bc],[D.START_DATE,Wc],[D.END_DATE,jc],[D.CONSTRAINT_TYPE,Kc],[D.CONSTRAINT_DATE,Yc],[D.CALENDAR_ID,$c],[D.CUSTOM_ID,qc],[D.SUBCONTRACT_ID,Jc],[D.RESPONSABLES,Xc],[D.TAGS,Zc]]);function Pe(e){return Vh.get(e)}var mt={APPEND:"append",REPLACE:"replace"},dn={ACTION_BUTTON:"action-button"},un={SIR_AUTO_REJECT:"sir-auto-reject"},fn={DATE_CHANGED:"date_changed",ACTIVITY_DELETED:"activity_deleted"},qe={VIOLATION:"constraint_violation"},ne={DISPATCH_MANY:"dispatch-many",INIT:"init",UNDO:"undo",REDO:"redo"};function Je(e,t){if(!t||t.type!==mi.CONSTRAINT)return null;let r=t.data;return!r?.constraintType||!r.constraintDate?null:{kind:qe.VIOLATION,activityId:e,constraintType:r.constraintType,constraintDate:r.constraintDate,projectedDate:r.projectedDate??r.constraintDate,messageKey:t.messageKey}}var jh=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],Qc=new Set(jh);function Tt(e,t,r,i){e.setActivityFieldDynamic(t,r,i)}function tl(e,t,r,i){e.setLinkFieldDynamic(t,r,i)}function ue(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:oe(e.constraintDate),dateOrigin:oe(e.dateOrigin),newActivityIds:[...e.newActivityIds],pendingRequestIds:[...e.pendingRequestIds],responsableIds:[...e.responsableIds],tagIds:[...e.tagIds],baselinePoints:e.baselinePoints.map(t=>({...t,startDate:oe(t.startDate),endDate:oe(t.endDate)})),baselineSnapshot:Kh(e.baselineSnapshot),criticalPath:Yh(e.criticalPath)}}function oe(e){return e===null?null:new Date(e)}function Kh(e){return e===null?null:{...e,startDate:oe(e.startDate),endDate:oe(e.endDate)}}function Yh(e){return e===null?null:{...e,earlyStart:oe(e.earlyStart),earlyFinish:oe(e.earlyFinish),lateStart:oe(e.lateStart),lateFinish:oe(e.lateFinish)}}var il=200;function Le(e,t){let r=new Set([String(e)]);for(let i of t.cascadeMutations??[])r.add(String(i.activityId));return r}async function tt(e,t){let r=new Map,i=0;for(let n of t){i+=1,i%il===0&&await ut();let o=e.getActivity(n);o&&r.set(n,it(o))}return r}function it(e){return ue(e)}function pn(e,t){let r=e.getActivity(t);return r?ue(r):null}function Oe(e,t,r){el(e,t,r.patch);for(let i of r.cascadeMutations??[])el(e,i.activityId,i.fields)}function el(e,t,r){for(let[i,n]of Object.entries(r)){if(!Qc.has(i))throw new Error(`applyFieldChanges: column write to non-writable field "${i}"`);Tt(e,t,i,n)}}async function yn(e,t,r,i){let n=[],o=0;for(let a of r){o+=1,o%il===0&&await ut();let s=Gh(e,t,a,i);s&&n.push(s)}return n}function Gh(e,t,r,i){let n=e.getActivity(r);if(!n)return{id:r,kind:b.DELETED,after:null};let o=t.get(r);if(!o&&i?.has(r))return $h(r,i.get(r),n);let a=Wo(o,n);return zh(a,i,r,n),o&&Object.keys(a).length===0?null:{id:r,kind:o?b.UPDATED:b.CREATED,fields:a,after:it(n)}}function $h(e,t,r){return t===r.correlativeId?null:{id:e,kind:b.UPDATED,fields:{correlativeId:{before:t,after:r.correlativeId}},after:it(r)}}function zh(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 Wo(e,t){let r={},i=e??{},n=t,o=new Set([...Object.keys(i),...Object.keys(n)]);o.delete(F.CALENDAR_DURATION);for(let a of o)(Object.hasOwn(i,a)!==Object.hasOwn(n,a)||!Ho(i[a],n[a]))&&(r[a]={before:rl(i[a]),after:rl(n[a])});return r}function rl(e){return e===null||typeof e!="object"?e:w(e)}function Ho(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)=>Ho(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)&&Ho(r[a],i[a]))}function hn(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 Vo(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=it(a);o.before!==void 0&&(s.correlativeId=o.before),i.set(o.activityId,s)}}var qh=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function fe(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(qh);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 Sr(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 Jh=e=>e.type===E.PROJECT,Xh=(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:fe(String(a));return Sr(o(e.startDate),o(e.endDate),t,n)};function Zh(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(!Jh(s)){let d=Xh(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)}),Zh(r,t,e)}var Qh=e=>e.type===E.PROJECT,tm=e=>Ct(e),em=(e,t,r,i)=>{let n=tm(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:Sr(n.startDate,n.endDate,t,o)};function jo(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(!Qh(c)){let u=em(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 Tr(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)=>Tt(e,o,a,s),getBaseCalendar:o=>e.calendarReader.getCalendar(o)},n=[];return e.forEachActivity((o,a)=>{o.parentId===null&&n.push(a)}),jo(n,t,i,r)}var Ko=he.BASELINE;function mn(e){return e===he.ACTUAL?he.ACTUAL:Ko}var nl=e=>Math.round(e*100)/100;function rm(e,t){return(t===he.BASELINE?e.expectedProgressBaseline:e.expectedProgress)??void 0}function im(e,t){let r=nl(e),i=nl(t);return r>99.99?Rt.DONE:i>r?Rt.OVERDUE:e>0&&r>i?Rt.ADVANCEMENT:e===0&&t===0?Rt.WAITING:e>0&&r<i?Rt.DOING:Rt.WAITING}function pe(e,t){let r=[];return e.forEachActivity((i,n)=>{let o=typeof i.progress=="number"?i.progress:0,a=im(o,rm(i,t));i.status!==a&&(Tt(e,n,D.STATUS,a),r.push(n))}),r}function Yo(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:()=>Yo(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}Yo.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var Yt=Yo;function nm(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function In(e){return nm(e)&&!isNaN(e.getTime())}function R(e,t,r,i){if(!In(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 Ht(e){if(!In(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 m=v;var H=Object.freeze({FS:Dt.FINISH_TO_START,SS:Dt.START_TO_START,FF:Dt.FINISH_TO_FINISH,SF:Dt.START_TO_FINISH});function Ze(e){return $i[String(Number(e))]??Dt.START_TO_FINISH}var q=Object.freeze({FORWARD:"forward",BACKWARD:"backward"}),Qe=Object.freeze({GREATER:"greater",LESS:"less"}),Xt=Object.freeze({SOURCE:"$source"});var om=e=>e?e.$level===1:!1,am=e=>e.type===E.PROJECT,sm=e=>e.$level!==0,cm=e=>e.type===E.TASK,lm=e=>e.type===E.TASK||e.type===E.MILESTONE,bt={byFirstLevel:om,filterByParentType:am,avoidSubproject:sm,byTaskType:cm,byTaskTypeAndMilestone:lm};function ol(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:i,linkProperty:n}=e;try{let o=dm({gantt:t,pendingParentsWithNoLinks:r});if(o.length===0)return new Set;let a=um({gantt:t,subprojectsWithNoLinks:o}),s=fm({gantt:t,childrenIds:a,linkProperty:n,getArrayOfLinkedActivities:pm,calculations:i});return new Set(s.map(c=>c.id))}catch(o){throw o}}function dm(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(bt.filterByParentType).filter(i=>r.has(i.id)).map(i=>i.id)}function um(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=bt.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(s=>i.add(s));return[...i]}function fm(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===Xt.SOURCE?"target":"source"}).every(f=>o.has(f))&&a.push(c)}return a}function pm(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 al({gantt:e,linkProperty:t,direction:r}){try{let i=ym(e,t);if(r===q.FORWARD)return{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:null};if(r===q.BACKWARD)return hm(i,e,t)}catch(i){throw console.log("Critical Path",i),i}}function ym(e,t){return e.getTaskByTime().filter(bt.avoidSubproject).filter(bt.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function hm(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!==m.FNLT&&i.push(o))}),{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:n}}function sl({gantt:e,direction:t,linkProperty:r}){try{let i=mm(e),n=new Set,o=new Set,a=new Set;t===q.BACKWARD&&Am(i).forEach(d=>{n.add(d.id)});let s=Im(i,t,r),c=gm(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 mm(e){return e.getTaskByTime().filter(bt.filterByParentType).filter(bt.avoidSubproject)}function Im(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!==m.FNLT;if(t===q.FORWARD){let c=a!==m.SNET;return!o&&s&&c}else return!o&&s})}function gm(e,t){let r=new Set(t.map(i=>i.id));return e.filter(i=>!r.has(i.id))}function Am(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function cl({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let i=new Set;return e.forEach(n=>{let o=t.getTask(n),a=vm(r),s=Cm(r),c=o[a];if(!Array.isArray(c))return;Sm(t,c,s).forEach(d=>{i.add(d)})}),i}catch(i){throw i}}function vm(e){return e===q.FORWARD?Xt.SOURCE:"$target"}function Cm(e){return e===q.FORWARD?"target":"source"}function Sm(e,t,r){return t.map(i=>{let o=e.getLink(i)[r];return Number(o)})}var ii={identifySecondLevelActivities:ol,identifyInitialActivities:al,identifyParentsWithAndWithoutLinks:sl,identifyForbiddenActivities:cl};function gn(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function Go({linkType:e,lag:t,predecessorTime:r,activityCalendar:i,activity:n}){return e===H.FS&&t===0?Ht({predecessorTime:r,activityCalendar:i,direction:"future",activity:n}):ni(r,e,i,n)}function ll({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t);return{es:R(r,n,e,i),ef:n}}function dl({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 ni(e,t,r,i){if(![H.FS,H.SS,H.FF].includes(t))return e;let o=[H.FS,H.SS].includes(t)?"future":"past";return Ht({dateBaseToCalculate:e,activityCalendar:r,direction:o,activity:i})}var $o=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=gn(t),i=this.activity.constraint_type;return i===m.SNET?this.handleSNETConstraint(r):i===m.FNLT?this.handleFNLTConstraint(r):r}calculateLinks(){let t=[];for(let r of this.linkedActivitiesData){let i=r.linkType,n=Ze(i),o=r.linkLag,a=r.es,s=r.ef,c=null;if(n===H.SS)c=this.calculateSSLink({lag:o,predecessorEs:a});else if(n===H.FF)c=this.calculateFFLink({lag:o,predecessorEf:s});else if(n===H.FS)c=this.calculateFSLink({lag:o,predecessorEf:s});else if(n===H.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=dl({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=ll({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=Go({linkType:H.SS,lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=R(this.activityCalendar,i,t,this.activity);t>0&&(n=ni(n,H.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=Go({linkType:H.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=ni(o,H.FF,this.activityCalendar,this.activity)),{es:o,ef:n}}calculateFSLink({lag:t,predecessorEf:r}){let i=r;t===0&&(i=Ht({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=ni(n,H.SF,this.activityCalendar,this.activity)),{es:n,ef:i}}},ul=$o;var zo=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=Ze(r.linkType);if(r.type===E.TASK&&Number(r.progress)>0||r.type===E.PROJECT&&Number(r.progress)===100)continue;let n=r.linkLag,o=r.ls,a=r.lf;if(i===H.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===H.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===H.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===H.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===m.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,Y.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,Y.PAST);return a=R(this.activityCalendar,l,n,this.activity),a=this.getLastWorkingHour(a,this.activityCalendar,Y.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,Y.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=Y.PAST){let n=t instanceof Date?t:new Date(t),o=Yt(n).clone();return this.isActivityInInitHour(r,n)&&i===Y.PAST&&(o=o.hours(0).minutes(0).seconds(0).milliseconds(0)),Ht({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),Yt.isMoment(r)?r.hours()===a:i.getUTCHours()===a)}},fl=zo;function pl(e){let{parent:t,linkProperty:r,linkDirection:i,calculations:n,gantt:o,direction:a,linkCandidates:s}=e,c=t[r],l=Tm(t),d=null;if(a===q.FORWARD){let u=Em(c,i,n,o);d=new ul(u,t,o,s),d=d.calculate()}else{let u=Dm(c,i,n,o);d=new fl({linksWithActivityData:u,activity:t,parentData:l,gantt:o}).calculate()}return d}function Tm(e){return{duration:e.duration,calendarId:e.calendar_id}}function Em(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 Dm(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 ml(e){let{activityData:t,calculations:r,singleParents:i,direction:n}=e;if(_m(t.id,r))return null;let o=km(t.id,i),a=Rm(o,r);return a.length===0?null:Pm(a,n)}function _m(e,t){return t.has(e)}function km(e,t){let r=t.get(e);return r?r.childrens:[]}function Rm(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function Pm(e,t){if(t===q.FORWARD){let r=yl(e,"es"),i=hl(e,"ef");return{es:r,ef:i}}else{let r=yl(e,"ls"),i=hl(e,"lf");return{ls:r,lf:i}}}function yl(e,t){return e.reduce((r,i)=>i[t]<r[t]?i:r)[t]}function hl(e,t){return e.reduce((r,i)=>i[t]>r[t]?i:r)[t]}var qo={parentWithLinks:pl,parentWithNoLinks:ml};var Jo=class{constructor(t){this.activity=t.activity,this.direction=t.direction,this.linkProperty=t.direction===q.FORWARD?"$target":Xt.SOURCE,this.linkDirection=t.direction===q.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===q.BACKWARD){let i=[m.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===q.FORWARD&&this.setDatesToParentsWithLinks(),this.direction===q.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=qo.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=qo.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)})}},Il=Jo;var Xo=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(bt.byFirstLevel).filter(bt.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===E.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}}},gl=Xo;var Zo=class{constructor(t,r){this.direction=r,this.gantt=t,this.linkProperty=this.direction===q.FORWARD?"$target":Xt.SOURCE,this.linkDirection=this.direction===q.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(bt.avoidSubproject).forEach(t=>{this.activitiesWaitingForCalculation.add(t.id)})}catch(t){throw t}}identifyParentsWithAndWithoutLinks(){try{let{parentsWithFullProgress:t,pendingParentsWithNoLinks:r,pendingParentsWithLinks:i}=ii.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=ii.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 gl({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===E.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===E.PROJECT,calculated:!1})}.bind(this),t.id),a({parentsIds:r,allTasks:i,activitiesByLevel:n,singleParents:o})})}identifySecondLevelActivities(){try{let t=ii.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}=ii.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===q.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===E.PROJECT)return;let r=this.calculateStartAndFinishOfChainOrigin(t,this.direction);if(this.direction===q.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)===q.FORWARD){let s=i.start_date,c=i.end_date;return{es:s,ef:c}}else{if(n>=100)return{ls:Yt(i.start_date).clone(),lf:Yt(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=Yt(t.start_date).clone(),n=Yt(t.end_date).clone(),o=t.duration,a=[m.ASAP,m.ALAP,m.SNET,m.FNET],s=t.constraint_type||m.ASAP;if(a.includes(s))n=this.projectDates.end_date,i=R(r,n,-o,t);else{let c=[m.SNLT,m.MSO],l=[m.FNLT,m.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||m.ASAP,o=this.projectDates.end_date,a=[m.ASAP,m.ALAP,m.SNET,m.FNET],s=[m.SNLT,m.FNLT];if(a.includes(n))i=Math.max(t.end_date,o);else if(n===m.MSO)i=t.end_date;else if(n===m.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===E.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===q.FORWARD?"es":"ls"]:i.start_date,[this.direction===q.FORWARD?"ef":"lf"]:i.end_date}),this.calculationOfParentsFromLinks.add(i.id))})}catch(t){throw t}}doCalculationForParentType(t){let r=new Il({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()}},Ne=Zo;function Lm(e,t,r){let i={es:null,ef:null};if(!e)return i;if([m.SNET,m.SNLT].includes(t)){let n=new Date(e.constraint_date);i.es=n,i.ef=R(r,n,e.duration,e)}else if([m.FNLT,m.FNET].includes(t)){let n=new Date(e.constraint_date);i.es=R(r,n,-e.duration,e),i.ef=n}else if(t===m.MSO){let n=new Date(e.constraint_date);i.es=n,i.ef=R(r,n,e.duration,e)}else if(t===m.MFO){let n=new Date(e.constraint_date);i.es=R(r,n,-e.duration,e),i.ef=n}return i}var An=Lm;var Qo=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=H.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===E.MILESTONE;return d||(o===H.FS&&n===0?s=Ht({dateBaseToCalculate:s,activityCalendar:a,direction:"future",activity:this.referenceActivity}):s=this.mutateTheDateToFutureOrPastInBaseRestriction(t,o,a)),[H.FF,H.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,H.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,H.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,H.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,H.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,r,i){if(![H.FS,H.SS,H.FF].includes(r))return t;let o=[H.FS,H.SS].includes(r)?"future":Y.PAST;return Ht({dateBaseToCalculate:t,activityCalendar:i,direction:o,activity:this.referenceActivity})}},Al=Qo;var oi=class extends Al{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Ne(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 gn(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var ta=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===E.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===q.FORWARD?i===m.FNLT||i===m.SNLT:i===m.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===q.BACKWARD&&this.activitiesStartChainButChildrenOfLinkedParents.has(t)&&!s)return;if(r.$target.length===0&&r[Xt.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===q.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}},vn=ta;var ea=(e,t)=>()=>t()===e;var ra=e=>!e?.fullyParsed;var Om=16,tr=async e=>performance.now()-e>Om?(await ut(),performance.now()):e;var ai=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 tr(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(s);if(l.size===0)break;for(let u of l){if(!a())return;c=await tr(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 ia=class extends Ne{constructor(t){super(t,q.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 vn({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 ai({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===E.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||m.ASAP,a=[m.SNET,m.SNLT,m.FNLT,m.FNET],s=[m.ASAP,m.ALAP,m.SNET,m.FNET,m.SNLT,m.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 oi({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===m.ASAP&&this.totalFloatForAsap.set(r,{es:f.es,ef:f.ef,text:i.text})):{es:d,ef:u}=new oi({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===m.ALAP&&this.alapMap.set(r,{es:i.start_date,ef:i.end_date,text:i.text});let p=An(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})),[m.MSO,m.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===m.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=Qe.GREATER){if(i===Qe.GREATER)return r.ef>t.ef?r:t;if(i===Qe.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=[m.SNET,m.FNET].includes(t)?Qe.GREATER:Qe.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===E.PROJECT)&&!(!this.gantt.getTask(o)||this.gantt.getTask(o)?.type===E.PROJECT))return r}).filter(Boolean)}},vl=ia;var na=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===m.ALAP?this.forwardPathCalculations.get(t):this.calculatedActivities.get(t)}calculateSuccessorTimes(t,r,i=0,n,o=H.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===E.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===H.FS){let{ls:d,lf:u}=this.calculateFsLink(l);return{ls:d,lf:u}}if(o===H.FF){let{ls:d,lf:u}=this.calculateFFLink(l);return{ls:d,lf:u}}if(o===H.SS){let{ls:d,lf:u}=this.calculateSSlink(l);return{ls:d,lf:u}}if(o===H.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,H.SS)}calculateFF(t,r){let i=this.getForwardOrBackwardCalculations(Number(t.target)),n=r===m.ALAP?"ef":"lf",o=i[n],a=-this.activity.duration,s=-t.lag||0,c=t.lag;return this.calculateSuccessorTimes(o,a,s,c,H.FF)}calculateFS(t,r){let i="ls";i=r===m.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,H.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,H.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=Yt(r).clone();return R(t,new Date(n),i,this.activity)}getLastWorkingHour(t,r,i=Y.PAST){let n=t instanceof Date?t:new Date(t),o=Yt(n).clone();return this.isActivityInInitHour(r,n)&&i===Y.PAST&&(o=o.hours(0).minutes(0).seconds(0).milliseconds(0)),Ht({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),Yt.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,Y.PAST);return s=R(i,d,o,this.activity),s=this.getLastWorkingHour(s,i,Y.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,Y.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,Y.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})}},Cl=na;var oa=class extends Cl{constructor(t){super(t),this.constraint=t.constraint||m.ASAP,this.parentsWithFullProgress=t.parentsWithFullProgress,this.parentsThatImpactChildrens=t.parentsThatImpactChildrens,this.projectDates=this.gantt.getSubtaskDates()}calculate(){if(this.links.length===0)return new Ne(this.gantt,q.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!==E.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===m.ALAP)return m.ALAP;if(this.constraint===m.FNET||this.constraint===m.SNET)return"snet-fnet";if(this.constraint===m.FNLT)return m.FNLT}getSpecialParamForSf(){return!![m.ALAP].includes(this.constraint)}getSpecialParamForFF(){return!![m.MFO,m.MSO].includes(this.constraint)}getMinCalculationLogic(t){if(this.constraint===m.ALAP)return this.getMinDateBasedOnConstraint(t);if(this.constraint===m.FNET)return this.getMinDateBasedOnConstraint(t);if(this.constraint===m.FNLT)return this.getMinDateBasedOnConstraint(t);if(this.constraint===m.MFO)return this.getMinDateBasedOnConstraint(t);if(this.constraint===m.SNET||this.constraint===m.SNLT||this.constraint===m.MSO)return this.SnetSnltMsoMinDate(t);if(this.constraint===m.ASAP)return this.getMinDateBasedOnConstraint(t)}getMinDateFromLinks(t){try{return this.constraint===m.ALAP||this.constraint===m.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===m.ASAP)return new Date(Math.max(i,n));if(r===m.FNET||r===m.FNLT){let a=Math.min(i,o);return new Date(Math.max(i,a))}if(r===m.ALAP)return new Date(Math.min(i,n))}},Sl=oa;function Nm(e,t,r){let i={ls:null,lf:null};return r===m.MSO&&(i.ls=t.constraint_date,i.lf=R(e,i.ls,t.duration,t)),r===m.MFO&&(i.lf=t.constraint_date,i.ls=R(e,i.lf,-t.duration,t)),i}var Tl=Nm;var aa=class extends Ne{constructor(t,r,i){super(t,q.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 vn({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 ai({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||m.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===E.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===m.MSO||o===m.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(i,o);return}if(o===m.MSO||o===m.MFO){this.recalculateInBaseRestriction(i,o);return}let{ls:s,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(n,i,o,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(o===m.SNLT||o===m.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=An(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===E.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,q.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===m.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(r===m.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 Sl({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=Tl(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===E.PROJECT)&&!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type===E.PROJECT))return r}).filter(Boolean)}doCalculationForActivitiesThatStartLinkButHisParentIsLinked(t){let r=Number(t.parent),i=this.calculationsOfParentThatImpactChildrens.get(r),n=0,o=0;if([m.ASAP,m.ALAP,m.SNET,m.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([m.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([m.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)}[m.MSO].includes(t.constraint_type)&&(n=t.constraint_date,o=R(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)),[m.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}},El=aa;function Dl(){return null}var _l=({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 sa=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=m.ASAP),t===m.ASAP||!t)return r===0?this.calculateAsap():this.calculateAsapWithProgress();if(t===m.ALAP)return r===0?this.calculateAlap():this.calculateAlapWithProgress();if(t===m.SNET||t===m.FNET)return r===0?this.calculateSnetFet():this.calculateSnetFnetSnltWithProgress();if(t===m.SNLT)return r===0?this.calculateSnltFnlt():this.calculateSnetFnetSnltWithProgress();if(t===m.FNLT)return r===0?this.calculateSnltFnlt():this.calculateFnltWithProgress();if(t===m.MSO||t===m.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===m.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===m.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)})}},kl=sa;var ca=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===m.MSO||t===m.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=m.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=m.ASAP){let r=this.getMinFloat(this.linksFreeFloatArray),i=this.calculateFreeFloatForEndOfProject(t),n=[m.SNLT,m.FNLT].includes(t)&&r===null?this.doCalculationForSnltFnlt(t,i,r):this.doGeneralCalculation(i,r);return Math.max(0,n)}getConstraintType(){let{constraint_type:t}=this.activity;return t||(t=m.ASAP),t}getDatesFromSucessorAndPredecessor(t,r,i){let n=i.constraint_type===m.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===m.ALAP?this.backwardMap.get(this.activity.id):this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===m.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===m.FNLT?r?.ef:r?.es))}getLinkData(t){let r=this.gantt.getLink(t)||{},i=Ze(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===m.ALAP?this.backwardMap:this.forwardMap).get(n),s=t===m.ALAP?a?.ls:a?.es,c=t===m.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===m.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)}},Rl=ca;var Pl=e=>({totalFloat:new kl(e.totalFloat).getTotalFloat(),freeFloat:new Rl(e.freeFloat).getFreeFloat()});var la=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=_l({forward:t,backward:r,id:l,activity:d,gantt:i,projectDates:n}),{totalFloat:f,freeFloat:p}=Pl(u);s.set(l,f),c.set(l,p),a=await tr(a)}return{totalFloatMap:s,freeFloatMap:c}};var da=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=ea(i,this.getCurrentCalculationId),o=()=>n()&&r();try{let a=t||this.gantt;if(this.gantt=a||Dl(),ra(this.gantt))return!1;let s=new vl(this.gantt);if(await s.calculateAsync(o),!o())return!1;let c=s.calculations,l=s.constraintsMap,d=new El(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 tr(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(),g=f.getTime()>=y?p.calculateDuration({start_date:u,end_date:f}):-p.calculateDuration({start_date:f,end_date:u});n.set(a,Number.isFinite(g)?Object.is(g,-0)?0:g:null)}return n}async calculateFloatsAsync(t,r,i){try{let n=this.gantt.getSubtaskDates(),o=Array.from(this.forwardPathCalculations.keys());return await la({activityIds:o,forward:t,backward:r,gantt:this.gantt,projectDates:n,isCurrent:i})}catch(n){throw this.forwardPathCalculations?.size,n}}},Ll=da;var bm=e=>e===v.FNET||e===v.FNLT||e===v.MFO,wm=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function Fm(e,t){let r=e.constraintDate;if(!r||!bm(e.constraintType))return r;let i=wm(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()?Wr(e,t):r}function xm(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 Mm(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 Um(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 Bm(e,t){let r=Mm(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:Fm(n,e)})}),i}function Hm(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 Wm(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 Ol(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=xm(f);return r.set(d,p),p},n=Wm(e);await ut();let o=Um(e),a=Bm(e,o);await ut();let s=[...a.values()].sort((l,d)=>(l.start_date?.getTime()??0)-(d.start_date?.getTime()??0));await ut();let c=Hm(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 fa=1e3,Vm=e=>typeof e!="number"||!Number.isFinite(e)?null:Object.is(e,-0)?0:e,jm=(e,t)=>typeof e!="number"||e<0?null:ua(e,t);function Km(e){let t=jm(e.freeFloatDays,e.hoursPerDay),r=Vm(e.residualHours);return{freeSlackHours:t,isCritical:r!==null&&r<=0&&e.sourceIsCritical&&e.targetIsCritical&&e.targetProgress===0}}async function Ym(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>=fa&&(i=0,await ut(),!t()))return null;r.set(String(o),n.linksFreeFloat[o])}return t()?r:null}async function Gm(e,t,r,i,n){let o=new Map,a=0;for(let s of t.forward?.keys()??[]){if(++a>=fa&&(a=0,await ut(),!n()))return null;let c=i(s);if(c===null)continue;let l=e.getActivity(c);l&&o.set(String(c),zm(s,Number(l.progress??0),t,r))}return n()?o:null}async function $m(e,t,r,i,n,o){let a=new Map,s=0;for(let c of e.getAllLinks()){if(++s>=fa&&(s=0,await ut(),!o()))return null;a.set(String(c.id),Km({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 ua=(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 zm(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=ua(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:ua(r.freeFloat.get(e)?.activityFreeFloat,i)}}var Cn=(e,t)=>e===t||e!==null&&t!==null&&e.getTime()===t.getTime();function pa(e,t,r){let i=e.getActivity(t),n=i?.criticalPath,o=r.criticalPath;i&&n&&Cn(n.earlyStart,o.earlyStart)&&Cn(n.earlyFinish,o.earlyFinish)&&Cn(n.lateStart,o.lateStart)&&Cn(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 ya(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 ha(e,t,r=()=>!0){if(!r())return null;let i=await Ol(e,t);if(!r())return null;let n=new Ll(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 Gm(e,a,t,i.getCanonicalActivityId,r);if(!s)return null;let c=await Ym(a.freeFloat,r);if(!c)return null;let l=await $m(e,c,n.linkResidualHours,s,t,r);return l?{activities:s,links:l}:null}async function Nl(e,t,r=()=>!0){let i=await ha(e,t,r);if(!i||!r())return!1;for(let[n,o]of i.activities){if(!r())return!1;pa(e,n,o)}for(let[n,o]of i.links){if(!r())return!1;ya(e,n,o)}return!0}function Er(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=Ct(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),F.REAL_COST,s),r.push(String(n)),s};for(let n of t)i(n);return r}var bl=new Set;var wl=new Set(["activity-outdent","activity-indent"]);var si=new Set([D.TEXT,D.DESCRIPTION,D.COST,D.USED_COST,D.CUSTOM_ID,D.RESPONSABLES,D.SUBCONTRACT_ID,D.TAGS]),qm=new Set([h.ACTIVITY_CLIPBOARD_CLEAR,h.ACTIVITY_COPY,h.SELECTION_TOGGLE,h.SELECTION_REPLACE,h.VISIBILITY_SET,h.FILTER_SET,h.SORT_SET,h.VIEW_ATTRIBUTES_SET,h.GROUP_SET,h.SIR_SYNC,h.ACTIVITY_LOOKAHEAD_SYNC,h.PERSISTENCE_ACKNOWLEDGE,h.BASELINE_APPLY,h.PONDERATOR_CRITERION_SET,h.STATUS_CRITERIA_SET]),Jm=new Set([h.ACTIVITY_CLIPBOARD_CLEAR,h.ACTIVITY_COPY,h.SELECTION_TOGGLE,h.SELECTION_REPLACE,h.VISIBILITY_SET,h.FILTER_SET,h.SORT_SET,h.VIEW_ATTRIBUTES_SET,h.GROUP_SET]);function xl(e){return!Jm.has(e.kind)}var Xm=new Set;function Zm(e){return e.kind===h.INLINE_EDIT?si.has(e.column):e.kind===h.BULK_EDIT?e.edits.every(t=>si.has(t.column)):!1}function ma(e,t){return!(qm.has(e.kind)||t.has(e.kind)||Zm(e))}function Sn(e){return e.kind===h.ACTIVITY_LOOKAHEAD_SYNC?e.persistedProgress!==void 0:ma(e,Xm)}function er(e){return e.kind===h.ACTIVITY_LOOKAHEAD_SYNC?e.persistedProgress!==void 0:ma(e,bl)}function Ml(e){return ma(e,wl)}function Ia(e){return e.kind===h.ACTIVITY_SET_PROGRESS?!0:e.kind===h.INLINE_EDIT?e.column===D.PROGRESS:e.kind===h.BULK_EDIT?e.edits.some(t=>t.column===D.PROGRESS):!1}function Qm(e){return Ml(e)&&Ia(e)}var Fl=new Set([D.PROGRESS,D.HH_WORK_TIME,D.DURATION,D.COST,D.USED_COST,D.REAL_COST]);function tI(e){return e.kind===h.ACTIVITY_SET_PROGRESS?!0:e.kind===h.INLINE_EDIT?Fl.has(e.column):e.kind===h.BULK_EDIT?e.edits.some(t=>Fl.has(t.column)):!1}var kt={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 Ul(e,t,r){let i=new Set;t.ran&&i.add(kt.AUTOSCHEDULE),i.add(kt.PARENT_BOUNDS),tI(e)&&i.add(kt.PARENT_PROGRESS),Ia(e)&&i.add(kt.REAL_WORK);let n=!r.skipAutoSchedule;return n&&Ml(e)&&i.add(kt.EXPECTED_PROGRESS),n&&Qm(e)&&i.add(kt.REAL_COST),n&&er(e)&&!r.skipCriticalPath&&i.add(kt.CRITICAL_PATH),i}var vt={INSERT:"insert",REMOVE:"remove",LINK_ADD:"link-add",LINK_REMOVE:"link-remove",LINK_FIELD:"link-field"},Tn=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,ue(r)),i.dirty.add(t))}noteInsert(t){this._journal?.ops.push({kind:vt.INSERT,activityId:t})}noteRemove(t,r){this._journal?.ops.push({kind:vt.REMOVE,activityId:t,before:ue(r)})}noteLinkAdd(t){this._journal?.ops.push({kind:vt.LINK_ADD,linkId:t})}noteLinkRemove(t,r){this._journal?.ops.push({kind:vt.LINK_REMOVE,linkId:t,before:Bl(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=ue(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:vt.LINK_FIELD,linkId:t,before:Bl(r)}))}noteProgressFallback(t,r){let i=this._journal;!i||i.progressFallbackBefore.has(t)||i.progressFallbackBefore.set(t,r)}};function Bl(e){return{...e}}function ga(e,t,r){let i=[];for(let n of r){let o=e.get(n);if(!o)continue;let a=o.pendingRequestIds??[];if(lr({pendingRequestIds:a})&&t.getActivity(n)==null)for(let s of a)i.push({kind:un.SIR_AUTO_REJECT,activityId:n,sirId:s,reason:fn.ACTIVITY_DELETED})}return i}function Ut(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 Lt={BEFORE_DIFF:"before-diff",AFTER_DIFF:"after-diff"};async function $(e,t){let r=nI(e,t),i=new Map(t.beforeSnap),n=e.peekWriteCapture();if(n){let f=aI(n);oI(e,n,f,i,r)}let o=t.sirDetection,a=o===Lt.BEFORE_DIFF?ga(i,e,r):[],s=iI(t.correlativeShifts,r),c=await yn(e,i,r,s),l=o===Lt.AFTER_DIFF?ga(i,e,r):a,d=t.warnings??[],u=rI(t.links??[],n?eI(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 eI(e,t){let r=[];for(let i of t.ops){if(i.kind!==vt.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:b.UPDATED,fields:o,after:Ut(n)})}return r}function rI(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===b.UPDATED||a.kind===b.CREATED)&&n.kind===b.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===b.DELETED)continue;let s=a.kind===b.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 iI(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 nI(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 oI(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(Wo(a,s)).length!==0&&(i.set(o,a),n.add(o))}}function aI(e){return new Set(e.ops.filter(t=>t.kind===vt.INSERT).map(t=>t.activityId))}function En(e,t,r){if(!e||e==="0")return;let i=r.getChildren(e);if(i.length===0)return;let n=new Map,o=new Set,a=0;for(let l of i){let d=cI(String(l),t,r);n.set(String(l),d),a+=d,Hl(String(l),r)&&o.add(String(l))}let s=a?100/a:0,c=o.size?100/o.size:0;for(let l of i){let d=r.getActivity(l);if(!d)continue;let u=sI(String(l),d,n,o,a,s,c);u!==null&&r.setActivityField(l,D.PONDERATOR,u)}}function sI(e,t,r,i,n,o,a){return t.type===E.PROJECT||Ct(t)?n?o*(r.get(e)??0):i.has(e)?a:0:!Array.isArray(t.baselinePoints)||t.baselinePoints.length===0?0:null}function Hl(e,t){let r=t.getActivity(e);return r?Ct(r)?!0:r.type!==E.PROJECT?!1:t.getChildren(e).some(i=>Hl(String(i),t)):!1}function cI(e,t,r){let i=r.getActivity(e);if(!i)return 0;if(i.type===E.PROJECT)return Wl(e,t,r);let n=Ct(i);return!n||i.type===E.MILESTONE?0:Vl(n,t)}function Wl(e,t,r){let i=0;for(let n of r.getChildren(e)){let o=r.getActivity(n);if(!o)continue;if(o.type===E.PROJECT){i+=Wl(String(n),t,r);continue}let a=Ct(o);a&&o.type!==E.MILESTONE&&(i+=Vl(a,t))}return i}function Vl(e,t){return t===It.COST?Aa(e.cost):t===It.WORK_HOURS?Aa(e.workHours):Aa(e.durationDays)}function Aa(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}var yt={ROOTS:"roots"};async function X(e,t){fI(e);let r=hI(e.adapter),i=lI(e.adapter,t),n=yI(i,r);n.has(kt.AUTOSCHEDULE)&&await SI(e.adapter,i);let o=n.has(kt.AUTOSCHEDULE)?await gI(e,i.autoscheduleFrom,i.preventSummaryTargetPullback):CI();return await TI(e.adapter,i,o.scheduledIds,n,r),await DI(e,n,t.now),o}function lI(e,t){let r=dI(e,t.autoscheduleFrom);return r===t.autoscheduleFrom?t:{...t,autoscheduleFrom:r}}function dI(e,t){if(t===yt.ROOTS)return yt.ROOTS;let r=uI(e);if(r.size===0)return t;if(t!==null&&r.add(String(t)),r.size!==1)return yt.ROOTS;let[i]=r;return i===void 0||!e.activityExists(i)||e.hasChildren(i)?yt.ROOTS:i}function uI(e){let t=new Set,r=e.peekWriteCapture();if(!r)return t;for(let i of r.ops){if(i.kind===vt.LINK_REMOVE){t.add(String(i.before.target));continue}if(i.kind===vt.LINK_ADD){let n=e.getLink(i.linkId);n&&t.add(String(n.target));continue}if(i.kind===vt.LINK_FIELD){t.add(String(i.before.target));let n=e.getLink(i.linkId);n&&t.add(String(n.target))}}return t}function fI(e){let t=e.adapter.peekWriteCapture();if(!t)return;let r=new Set,i=e.sector.activityCreter??It.DURATION;for(let[n,o]of t.before){let a=e.adapter.getActivity(n);if(o.type===E.PROJECT||a?.type!==E.PROJECT||Ct(a)||!pI(n,e.adapter))continue;let s=n;for(;s!==null&&!B(s);)r.has(s)||(En(s,i,e.adapter),r.add(s)),s=e.adapter.getParentId(s)}}function pI(e,t){let r=[...t.getChildren(e)];for(;r.length>0;){let i=r.pop();if(i===void 0)continue;let n=t.getActivity(i);if(n&&Ct(n))return!0;r.push(...t.getChildren(i))}return!1}async function jl(e,t,r){if(e.activityId!==void 0&&!r.adapter.activityExists(e.activityId))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let i=await tt(r.adapter,new Set(r.adapter.getAllIds()));r.scheduler.invalidateAllCaches();let n=e.activityId===void 0?r.adapter.getRootIds():[e.activityId],{scheduledIds:o}=await X({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId??yt.ROOTS,recomputeParentsFrom:n,now:r.now,options:t});return{ok:!0,changes:await $(r.adapter,{source:e,beforeSnap:i,touchedIds:n,scheduledIds:o,hoursPerDay:r.sector.hoursPerDay})}}function yI(e,t){let r=e.autoscheduleFrom!==null,i=!e.options.skipAutoSchedule&&r,n=new Set(Ul(e.action,{requested:r,ran:i},e.options));return(e.recomputeParentProgress||t.affectedParents.size>0)&&n.add(kt.PARENT_PROGRESS),n}function hI(e){let t=new Set,r=new Set,i=e.peekWriteCapture();if(!i)return{affectedParents:t,dirtySeeds:r};let n=o=>{if(o===null||B(o))return;let a=String(o);t.add(a);let s=e.getChildren(a)[0];s!==void 0&&r.add(s)};return mI(e,i.ops,n),II(e,i.before,r,n),{affectedParents:t,dirtySeeds:r}}function mI(e,t,r){for(let i of t)if(i.kind===vt.INSERT){let n=e.getActivity(i.activityId);n&&r(n.parentId)}else i.kind===vt.REMOVE&&r(i.before.parentId)}function II(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 gI(e,t,r=!1){let i=t===yt.ROOTS?{}:{triggerId:t};r&&(i.preventSummaryTargetPullback=!0);let n=await e.scheduler.schedule(i),o=vI(e.adapter,n.updatedIds),a=AI(e.adapter,n);return $r(e.adapter,n),{...o,warnings:a}}function AI(e,t){let r=[];for(let i of t.plans.values()){let n=i.earliestSchedulingStart;if(!n||i.startDate>=n)continue;let o=e.getActivity(i.activityId);!o?.constraintType||!o.constraintDate||r.push({kind:qe.VIOLATION,activityId:o.id,constraintType:o.constraintType,constraintDate:o.constraintDate,projectedDate:n,messageKey:qe.VIOLATION})}return r}function vI(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,warnings:[]}}function CI(){return{scheduledIds:[],warnings:[]}}async function SI(e,t){let r=t.collectDirty?t.collectDirty([]):Vo(t.recomputeParentsFrom,[]);r.size!==0&&await mr(e,r,!1)}async function TI(e,t,r,i,n){i.has(kt.PARENT_PROGRESS)&&EI(e,n.affectedParents);let o=t.collectDirty?t.collectDirty(r):Vo(t.recomputeParentsFrom,r);for(let a of n.dirtySeeds)o.add(a);await mr(e,o,i.has(kt.PARENT_PROGRESS),{recomputeRealWork:i.has(kt.REAL_WORK),progressMode:"freeze-when-no-contribution"})}function EI(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 DI(e,t,r){t.has(kt.EXPECTED_PROGRESS)&&r!==null&&(_I(e.adapter)&&Tr(e.adapter,r,e.defaultBaseCalendarId??null),Xe(e.adapter,r),pe(e.adapter,e.sector.statusCriteria)),t.has(kt.REAL_COST)&&Er(e.adapter),t.has(kt.CRITICAL_PATH)&&await Nl(e.adapter,e.sector.hoursPerDay)}function _I(e){let t=!1;return e.forEachActivity(r=>{Ct(r)&&(t=!0)}),t}var kI=new Set([D.CONSTRAINT_TYPE,D.CONSTRAINT_DATE]),RI=new Set([v.MSO,v.MFO]);function Dr(e){return kI.has(e)}function Dn(e){return e===D.CONSTRAINT_DATE}function _n(e,t,r,i){let n=r.getActivity(e);if(!n)return!1;let o=n.constraintType;if(!o||ke.has(o)||RI.has(o))return!1;let a=va(n.startDate),s=va(r.getLastStartDate(e));if(!s||!a||a.getTime()!==s.getTime())return!1;let c=PI(t,o,String(n.calendarId??""),i),l=va(n.constraintDate);return LI(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function PI(e,t,r,i){if(e===null)return null;let n=i.getCalendar(r);return n?de(e,n,t):e}function va(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 LI(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function kn(e,{postMutationArgs:t,revertTargets:r,revert:i}){let{scheduledIds:n}=await X(e,Kl(t)),o=!1;for(let{activityId:a,priorConstraintDate:s}of r){let c=i(a,s);o=o||c}if(o){let a=await X(e,Kl(t));n=NI(n,a.scheduledIds)}return er(t.action)&&await X(e,OI(t)),{scheduledIds:n}}function Kl(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function OI(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function NI(e,t){let r=new Set(e);for(let i of t)r.add(i);return[...r]}function _r(e,t,r){let i=[];for(let{op:n,finalLinkId:o,rejected:a}of e){if(a!==null)continue;if(n.kind===Et.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:b.UPDATED,fields:f,after:Ut(d)});continue}i.push({id:String(o),kind:b.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:Ut(d)});continue}if(n.kind===Et.DELETE){if(r.getLink(n.linkId))continue;let d=t.get(n.linkId);i.push({id:String(n.linkId),kind:b.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&&String(s.source)!==String(c.source)&&(l.source={before:String(s.source),after:String(c.source)}),s&&String(s.target)!==String(c.target)&&(l.target={before:String(s.target),after:String(c.target)}),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:b.UPDATED,fields:l,after:Ut(c)})}return i}function kr(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 Rr(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:b.UPDATED,fields:{lag:{before:a,after:Number(o.lag)}},after:Ut(o)})}return i}function Yl(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function Gl(e,t,r){let{adapter:i,ctx:n,scheduler:o,sector:a}=r,s=Pe(e.column);if(!s)return{ok:!1,reason:C.NO_PIPELINE_FOR_COLUMN};e.column===D.DURATION&&o.invalidateExpandedLinksCache();let c=n.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let l=s.canEdit(c,n.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??C.CANNOT_EDIT,alertKey:l.alertKey};let d=s.parseInput(e.newValue,c,n);if(!d.ok)return{ok:!1,reason:d.reason??C.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??C.INVALID,alertKey:f.notification?.messageKey};if(e.column===D.CUSTOM_ID&&d.value!==null){let S=i.getActivity(e.activityId),N=S?S.customId:null,j=typeof N=="string"?N:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),j))return{ok:!1,reason:C.CUSTOM_ID_DUPLICATE}}let p=s.transform(c,d.value,n,d.raw),y=Le(e.activityId,p),I=await tt(i,y),g=kr(i,String(e.activityId)),_=c.constraintDate;Oe(i,e.activityId,p),Ee(e.activityId,p.postProcessors??[],i,I.get(String(e.activityId))??null);let k=Rr(g,i,String(e.activityId));if(e.column===D.CUSTOM_ID){let S=I.get(String(e.activityId)),N=S?S.customId:null,j=typeof N=="string"?N:null,K=typeof d.value=="string"?d.value:null;j!==K&&r.customIdTracker.trackCustomIdChange(j,K)}let O=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:S=>hn(e.activityId,y,S),now:r.now,options:t}),T=Dr(e.column),{scheduledIds:P}=await(T?kn({adapter:i,scheduler:o,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:O(),revertTargets:Dn(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:_}],revert:(S,N)=>_n(S,N,i,n.calendars)}):X({adapter:i,scheduler:o,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},O())),x=(p.trackingEvents??[]).map(S=>({name:S.name,properties:S.properties??{}}));s.trackEvent&&!(e.column===D.PROGRESS&&Number(d.value)<=0)&&x.unshift({name:s.trackEvent,properties:{activity_name:c.name,activity_id:c.id,activity_index:c.correlativeId}});let A=Je(e.activityId,p.constraintWarning);return{ok:!0,changes:await $(i,{source:e,beforeSnap:I,touchedIds:y,scheduledIds:P,sirDetection:Lt.BEFORE_DIFF,links:k,trackingEvents:x,...A?{warnings:[A]}:{},hoursPerDay:a.hoursPerDay})}}function Rn(e){return vi(e)}function Pn(e,t){return Object.hasOwn(e,t)}function bI(e){if(e.kind===h.LINK_CREATE)return Rn(e.type)?e.lag===void 0||Number.isFinite(e.lag)?null:C.INVALID_LINK_LAG:C.INVALID_LINK_TYPE;if(e.kind===h.LINK_UPDATE){if(Pn(e,"type")&&!Rn(e.type))return C.INVALID_LINK_TYPE;if(Pn(e,"lag")&&!Number.isFinite(e.lag))return C.INVALID_LINK_LAG}return null}function wI(e){return e.kind===nt.CREATE?Rn(e.type)?e.lag===void 0||Number.isFinite(e.lag)?null:C.INVALID_LINK_LAG:C.INVALID_LINK_TYPE:e.kind===nt.UPDATE?Pn(e,"type")&&!Rn(e.type)?C.INVALID_LINK_TYPE:!Pn(e,"lag")||Number.isFinite(e.lag)?null:C.INVALID_LINK_LAG:e.kind===nt.DELETE?null:C.INVALID_VALUE}function FI(e){for(let t of e){let r=wI(t);if(r!==null)return r}return null}function xI(e,t){let r=new Set,i=new Map;for(let n of e){if(n.kind===nt.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)),n.kind===nt.UPDATE&&(n.source!==void 0&&r.add(String(n.source)),n.target!==void 0&&r.add(String(n.target))),i.set(n.linkId,{...o}))}return{activityIds:r,links:i}}function MI(e,t,r,i,n=!1){return e.map((o,a)=>{let s=o.kind===nt.CREATE?i?.get(a):void 0,c=Ce(o,{port:t,newLinkId:s?()=>s:r.next,rejectParentLinkMutations:n});return{op:o,finalLinkId:c.applied?c.linkId:null,rejected:c.applied?null:c.rejected??C.INVALID}})}function UI(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function $l(e,t,r){let i=bI(e);return i!==null?{ok:!1,reason:i}:Ca([KI(e,r.sector.hoursPerDay)],e,t,r,e.kind===h.LINK_CREATE&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function zl(e,t,r){let i=FI(e.operations);if(i!==null)return{ok:!1,reason:i};let{hoursPerDay:n}=r.sector,o=e.operations.map(s=>WI(s,n)),a=BI(e.operations);return Ca(o,e,t,r,a)}function BI(e){let t=new Map;return e.forEach((r,i)=>{r.kind===nt.CREATE&&r.linkId&&t.set(i,r.linkId)}),t.size>0?t:void 0}function HI(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 WI(e,t){return e.kind===nt.CREATE?{kind:nt.CREATE,source:e.source,target:e.target,type:e.type,lag:Kt(e.lag??0,t)}:e.kind===nt.UPDATE?{kind:nt.UPDATE,linkId:e.linkId,source:e.source,target:e.target,type:e.type,lag:e.lag===void 0?void 0:Kt(e.lag,t)}:{kind:nt.DELETE,linkId:e.linkId}}async function Ca(e,t,r,i,n){let{adapter:o,scheduler:a,sector:s,linkIdGen:c}=i;a.invalidateAllCaches();let{activityIds:l,links:d}=xI(e,o),u=await tt(o,l),f=MI(e,o,c,HI(n,i),r.rejectParentLinkMutations);if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!==h.INLINE_EDIT)return{ok:!1,reason:f[0].rejected};let p=VI(f,d,o),{scheduledIds:y,warnings:I}=await X({adapter:o,scheduler:a,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:i.now,options:r}),g=_r(f,d,o);return{ok:!0,linkVerdicts:f.map((_,k)=>_.rejected===null?{operationIndex:k,kind:_.op.kind,ok:!0,linkId:String(_.finalLinkId)}:{operationIndex:k,kind:_.op.kind,ok:!1,reason:_.rejected}),__beforeLinks:UI(d),changes:await $(o,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:y,links:g,warnings:I,hoursPerDay:s.hoursPerDay})}}function VI(e,t,r){for(let i of e){if(i.rejected!==null)continue;let n=jI(i.op,t,r);if(n!==null)return r.hasChildren(n)?yt.ROOTS:String(n)}return null}function jI(e,t,r){return e.kind===nt.CREATE?e.target:e.kind===nt.DELETE?t.get(e.linkId)?.target??null:r.getLink(e.linkId)?.target??null}function KI(e,t){return e.kind===h.LINK_CREATE?{kind:nt.CREATE,source:e.source,target:e.target,type:e.type,lag:Kt(e.lag??0,t)}:e.kind===h.LINK_UPDATE?{kind:nt.UPDATE,linkId:e.linkId,source:e.source,target:e.target,type:e.type,lag:e.lag===void 0?void 0:Kt(e.lag,t)}:{kind:nt.DELETE,linkId:e.linkId}}async function ql(e,t,r){let{adapter:i,sector:n}=r;if(typeof e.newValue!="string")return{ok:!1,reason:C.INVALID_VALUE};if(!i.getActivity(e.activityId))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let a=e.column===D.CUSTOM_PREDECESSORS,{specs:s,errors:c}=qi(e.newValue,{daysPerWeek:n.hoursPerWeek/n.hoursPerDay});if(c.length>0)return{ok:!1,reason:C.INVALID_VALUE};let l=s.map(I=>({...I,lag:Kt(Qi(I.lag),n.hoursPerDay)})),d=new Map;i.forEachActivity(I=>{I.correlativeId!=null&&d.set(String(I.correlativeId),I.id)});let u=I=>d.get(I)??null,f=a?i.getIncomingLinkIds(e.activityId):i.getOutgoingLinkIds(e.activityId),p=[];for(let I of f){let g=i.getLink(I);g&&p.push(g)}let y=a?Xi({targetActivityId:e.activityId,currentLinks:p,desiredSpecs:l,resolveActivityByCorrelative:u}):Zi({sourceActivityId:e.activityId,currentLinks:p,desiredSpecs:l,resolveActivityByCorrelative:u});return Ca(y.operations,e,t,r)}var Gt={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 _t(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(o=>{B(o.parentId)&&t.push(o)}),t.sort(Zl);let r=[];Jl(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),YI(o,n)}n+=1;let a=Kr(String(o.id),e);a.sort(Zl),Jl(r,a)}return i}function Jl(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function Xl(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:vo}var Zl=(e,t)=>Xl(e)-Xl(t);function YI(e,t){e.correlativeId=t}function Sa(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let{workHours:i,realWorkHours:n}=ed(r,t);t.setActivityField(r,F.WORK_HOURS,i),t.setActivityField(r,F.REAL_WORK_HOURS,n);let o=t.getActivity(r);if(!o)break;let a=o.parentId;if(!a||B(a))break;r=a}}function Ql(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||B(i)||Sa(i,t)}function td(e,t,r){for(let i of e){if(r.hasChildren(i))continue;let n=r.getActivity(i);n&&r.setActivityField(i,F.REAL_WORK_HOURS,Mt(ci(n,F.WORK_HOURS),ci(n,F.PROGRESS)))}for(let i of t)r.setActivityField(i,F.REAL_WORK_HOURS,ed(i,r).realWorkHours)}function ed(e,t){let r=0,i=0;for(let n of t.getChildren(e)){let o=t.getActivity(n);if(!o)continue;let a=ci(o,F.WORK_HOURS);r+=a,i+=GI(n,o,a,t)}return{workHours:r,realWorkHours:i}}function ci(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function GI(e,t,r,i){return i.hasChildren(e)?ci(t,F.REAL_WORK_HOURS):Mt(r,ci(t,F.PROGRESS))}function Ta(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+=$I(c,F.USED_COST))}t.setActivityField(r,F.USED_COST,n);let o=t.getActivity(r);if(!o)break;let a=o.parentId;if(!a||B(a))break;r=a}}function rd(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||B(i)||Ta(i,t)}function $I(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Ea(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+=zI(c,F.COST))}t.setActivityField(r,F.COST,n);let o=t.getActivity(r);if(!o)break;let a=o.parentId;if(!a||B(a))break;r=a}}function id(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||B(i)||Ea(i,t)}function zI(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var Ln=Object.freeze({proplannerId:null,description:"",type:E.TASK,progress:0,constraintType:v.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}),nd="New Master Plan",od="New Activity";var qI=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],On=new Set(qI);function JI(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"||!On.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function ad(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,i=JI(e.activityOverrides??{}),n=e.numTasksInGantt===0?nd:od,o=i.name??n,a=i.durationHours??e.sector.hoursPerDay,s=i.calendarId??e.sector.defaultCalendar,c=XI(r,e.fallbackStartDate,i.startDate),l={...Ln,...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:Y.FUTURE,task:l});if(!i.startDate&&r&&ce(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:Y.FUTURE,task:l}))}let u=t.calculateEndDate({startDate:d,durationHours:l.durationHours,task:l});return{newTask:{...l,startDate:d,endDate:u,calendarDuration:ie({type:l.type,startDate:d,endDate:u}),newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function XI(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function Pr(e,t,r,i){let n=t,o=n==="0",a=Da(e,n);if(i!==void 0){let c=a.find(l=>l.id===i);if(c){let l=Ot(c),d=a.map(Ot).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=Ot(c),d=a.map(Ot).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(Ot))+1}var rr=Number.MAX_SAFE_INTEGER,sd=Number.MAX_SAFE_INTEGER-1;function Ot(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:rr}function Da(e,t){return Kr(t,e)}function cd(e,t,r){let i=e,n=ae(e,r);for(;n!=null&&t.has(n);)i=n,n=ae(n,r);return i}function Lr(e,t,r){let i=new Set([e]),n=zt(r.getActivity(e)?.parentId);for(;n!=="0"&&!i.has(n);){if(t.has(n))return!0;i.add(n),n=zt(r.getActivity(n)?.parentId)}return!1}function ae(e,t){let r=t.getActivity(e);if(!r)return null;let i=zt(r.parentId),n=jt(i,t),o=n.findIndex(a=>String(a)===String(e));return o<=0?null:n[o-1]??null}function ld(e,t,r,i){let n=jt(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(Ot);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 ZI=new Set([...[...On].filter(e=>e!==F.DURATION_HOURS),"durationDays"]);function Nn(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:C.INVALID_VALUE};for(let o of Reflect.ownKeys(e))if(typeof o=="symbol"||!ZI.has(o))return{ok:!1,reason:C.INVALID_VALUE};let{durationDays:i,...n}=e;return i!==void 0&&(!Number.isFinite(i)||i<0)?{ok:!1,reason:C.INVALID_VALUE}:{ok:!0,value:{...n,...i===0&&(n.type===void 0||n.type===E.TASK)?{type:E.MILESTONE}:{},...i===void 0?{}:{durationHours:Ye(i,t)}}}}function wt(e,t){Sa(e,t),Ta(e,t),Ea(e,t)}function bn(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 wn(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 QI(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 tg(e,t,r){let i=e.startDate;return!r||!(i instanceof Date)?{}:{endDate:r(i,t)}}function be(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,i=Number.isFinite(r),n=QI(e.promotionSnapshot)??(i?{type:fr,durationHours:r,progress:0,autoScheduling:!0,constraintType:v.ASAP,constraintDate:null,hasNewActivities:!1,...tg(t,r,e.computeEndDate)}:{type:fr});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 Fn(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 dd=200;async function ud(e,t,r){let{adapter:i,scheduler:n,customIdTracker:o,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:C.ACTIVITY_IDS_EMPTY};for(let S of e.activityIds)if(!i.getActivity(S))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let s=e.activityIds.filter(S=>{let N=i.getActivity(S);return!(N?.correlativeId===0&&N.type===E.PROJECT)}),c=bn(s,i),l=wn(c,i),d=new Set;for(let S of e.activityIds){let N=i.getActivity(S);if(!N)continue;let j=N.parentId;if(B(j))continue;let K=String(j);c.has(K)||d.add(K)}let u=new Set([...c,...d]),f=await tt(i,u),p=new Map;for(let S of l){let N=i.getLink(S);N&&p.set(S,{...N})}let y=new Set,I=0;for(let S of c){I+=1,I%dd===0&&await ut();let N=i.getActivity(S);if(!N)continue;let j=B(N.parentId)?null:i.getActivity(String(N.parentId)),K=j?.hasNewActivities===!0&&j.newActivityIds.some(st=>String(st)===String(S));(N.isNewActivity===!0||K)&&y.add(S);let Z=N.customId;typeof Z=="string"&&Z.length>0&&o.releaseCustomId(Z)}for(let S of l)i.removeLink(S);let g=li(i,c),_=0;for(let S of c)_+=1,_%dd===0&&await ut(),i.removeActivity(S);for(let S of d){let N=i.getActivity(S);if(!N)continue;eg(N,y,i);let j=i.getChildren(S),K=be({parent:N,remainingChildIds:j.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(S),computeEndDate:(Z,st)=>i.calculateEndDate({startDate:Z,durationHours:st,task:N}),idsRemoved:c});if(!K){en(S,i);continue}for(let[Z,st]of Object.entries(K.fields))Tt(i,S,Z,st);if(N.customId==null||N.customId===""){let Z=ae(S,i),st=Z?i.getActivity(Z)?.customId:null,lt=o.generateCustomIdForRestoredChild(typeof st=="string"&&st?st:null);i.setActivityField(S,F.CUSTOM_ID,lt)}}for(let S of d)wt(S,i);let k=_t(i),{scheduledIds:O}=await X({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:yt.ROOTS,recomputeParentsFrom:d,now:r.now,options:t}),T={name:Gt.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:c.size}};e.eventSource!==void 0&&(T.properties.event_source=e.eventSource);let P=new Map;for(let[S,N]of p)P.set(S,N);let x=new Map;for(let S of c){let N=f.get(String(S));N&&x.set(String(S),N)}let A=await $(i,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:O,sirDetection:Lt.AFTER_DIFF,links:Zt(p),trackingEvents:[T],hoursPerDay:a.hoursPerDay,correlativeShifts:k});return{ok:!0,changes:g.length>0?{...A,viewState:g}:A,__beforeSnap:x,__beforeLinks:P}}function eg(e,t,r){let i=Fn({parent:e,idsRemoved:t});if(i)for(let[n,o]of Object.entries(i.fields))Tt(r,i.parentId,n,o)}function li(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 Zt(e){let t=[];for(let[r,i]of e.entries())t.push({id:r,kind:b.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}var Or={CREATE:"create",REPARENT:"reparent"};function rg(e){let t=e.type;if(t!==E.TASK&&t!==E.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 fd(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&Ae(t.type):ig(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=ko,(e.promotionSource??Or.CREATE)===Or.CREATE&&(o.constraintType=v.ASAP,o.constraintDate=null)),{parentId:e.parentId,fields:o,promotionSnapshot:rg(t)}}function ig(e){return Ae(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function we(e,t){let i=t.adapter.getActivity(e.parentId)?.customId??null,n=fd({...e,getParent:a=>t.adapter.getActivity(a)??null});if(!n)return{applied:!1,removedLinks:new Map};let o=n.fields.type===E.PROJECT?ng(e.parentId,t):new Map;for(let[a,s]of Object.entries(n.fields))Tt(t.adapter,n.parentId,a,s);return n.promotionSnapshot&&t.adapter.setPromotionSnapshot(n.parentId,n.promotionSnapshot),n.fields.customId===null&&t.customIdTracker.releaseCustomId(i),{applied:!0,removedLinks:o}}function ng(e,t){let r=new Map,i=new Set([...t.adapter.getIncomingLinkIds(e),...t.adapter.getOutgoingLinkIds(e)]);for(let n of i){let o=t.adapter.getLink(n);o&&(r.set(String(n),{...o}),t.adapter.removeLink(n))}return r}async function di(e,t,r={}){let{adapter:i,scheduler:n,sector:o,calendars:a,activityIdGen:s,uidGen:c}=t;r.skipCacheInvalidation||n.invalidateAllCaches();let l=og(e,i);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=sg(e.activityId,i,s,t.isActivityIdReserved),y=c.next(),I={id:p,parentId:f?null:e.parentId,sector:{id:o.id,hoursPerDay:o.hoursPerDay,defaultCalendar:fg(a)},numTasksInGantt:i.activityCount(),nextUniqueCorrelativeId:y,activityOverrides:e.overrides??{}},_=ad(I,{getActivity:S=>i.getActivity(S),calculateEndDate:S=>i.calculateEndDate(S),getClosestWorkTime:S=>i.getClosestWorkTime(S)}).newTask;_.realWorkHours=Mt(_.workHours,_.progress),lg(_,e,t,u,d,r);let k=r.insertionCorrelativeId??Pr(i,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);_.correlativeId=k;let O=new Set([p]);d&&O.add(d.id);let T=d!==null&&i.getChildren(d.id).length===0,P=r.skipBeforeSnap?new Map:await tt(i,O);i.addActivity(_);let x=d?we({parentId:d.id,newChildId:p,isCurrentlyLeaf:T},t).removedLinks:new Map;r.skipRollupCascades||(Ql(p,i),rd(p,i),id(p,i));let A=dg(i,p,O,r);return{ok:!0,newId:p,parent:d,newActivity:_,beforeSnap:P,initialTouched:O,correlativeShifts:A,removedParentLinks:x}}function og(e,t){let r=B(e.parentId),i=r?null:t.getActivity(e.parentId);if(!r&&!i)return{ok:!1,reason:C.PARENT_NOT_FOUND};if(i!==null&&lr(i))return{ok:!1,reason:C.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:C.ANCHOR_SIBLING_CONFLICT};let a=e.afterSiblingId??e.beforeSiblingId,s=ag(e,t,r,a);return s||{ok:!0,parent:i,anchorSiblingId:a,isRoot:r}}function ag(e,t,r,i){if(i===void 0)return null;let n=t.getActivity(i);if(!n)return{ok:!1,reason:C.ANCHOR_SIBLING_NOT_FOUND};let o=r?"0":e.parentId;return(n.parentId==null?"0":String(n.parentId))!==o?{ok:!1,reason:C.ANCHOR_SIBLING_WRONG_PARENT}:null}function sg(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 cg(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function lg(e,t,r,i,n,o){let{adapter:a,customIdTracker:s}=r,c=cg(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 dg(e,t,r,i){if(i.skipCorrelativeRecompute)return[];let n=_t(e).filter(o=>o.activityId!==String(t));for(let o of n)r.add(o.activityId);return n}async function ug(e,t,r,i,n){let{newId:o,newActivity:a,beforeSnap:s,initialTouched:c,correlativeShifts:l,removedParentLinks:d}=r,u={name:Gt.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:o,created_duration:a.durationHours}};return t.eventSource!==void 0&&(u.properties.event_source=t.eventSource),$(e,{source:t,beforeSnap:s,touchedIds:c,scheduledIds:i,correlativeShifts:l,trackingEvents:[u],links:Zt(new Map(d)),hoursPerDay:n})}async function pd(e,t,r){let{adapter:i,scheduler:n,sector:o}=r,a=Nn(e.overrides,o.hoursPerDay);if(!a.ok)return a;let s=await di({...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 X({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 ug(i,e,s,u,o.hoursPerDay),...s.removedParentLinks.size>0?{__beforeLinks:new Map(s.removedParentLinks)}:{}}}function fg(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"}async function md(e,t,r){let i=pg(e,r);if(i)return{ok:!1,reason:i};let n=hg(e,r);if(!n.ok)return n;let o=e.mode===mt.REPLACE?new Set(r.adapter.getAllIds().map(T=>String(T))):new Set,a=e.mode===mt.REPLACE?await tt(r.adapter,o):new Map,s=e.mode===mt.REPLACE?Cg(r):new Map,c=e.mode===mt.REPLACE?li(r.adapter,o):[];r.scheduler.invalidateAllCaches();let l=[];if(e.mode===mt.REPLACE){for(let T of s.keys()){let P=Ce({kind:nt.DELETE,linkId:T},{port:r.adapter});if(!P.applied)return{ok:!1,reason:P.rejected??C.INVALID};l.push({op:{kind:nt.DELETE,linkId:T},finalLinkId:T,rejected:null})}for(let T of o){let P=r.adapter.getActivity(T)?.customId;typeof P=="string"&&P.length>0&&r.customIdTracker.releaseCustomId(P),r.adapter.removeActivity(T)}}let d=await vg(e,n.plan.items,r);if(!d.ok)return d;for(let[T,P]of d.removedParentLinks)s.set(T,P),l.push({op:{kind:nt.DELETE,linkId:T},finalLinkId:T,rejected:null});let u=Id(e)?[]:_t(r.adapter),f=new Set(n.plan.items.map(T=>String(T.activityId))),p=u.filter(T=>!f.has(T.activityId)),y=e.mode===mt.REPLACE?new Set(o):new Set;Cr(r.adapter,u,f,a,y);for(let T of n.plan.items)y.add(String(T.activityId));let I=n.plan.links.map(T=>({operation:{kind:nt.CREATE,source:T.source,target:T.target,type:T.type,lag:Kt(T.lag??0,r.sector.hoursPerDay)},linkId:T.linkId})),g=Gi(I,{port:r.adapter,preserved:s,rejectParentLinkMutations:t.rejectParentLinkMutations??!1});if(!g.applied)return{ok:!1,reason:g.rejected??C.INVALID};for(let{operation:T,linkId:P}of I)l.push({op:T,finalLinkId:P,rejected:null});let _=n.plan.items.map(T=>T.activityId),{scheduledIds:k}=await X({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.items.length>0||e.links.length>0?yt.ROOTS:null,recomputeParentsFrom:_,now:r.now,options:t}),O=await $(r.adapter,{source:e,beforeSnap:a,touchedIds:y,scheduledIds:k,links:_r(l,s,r.adapter),hoursPerDay:r.sector.hoursPerDay,correlativeShifts:p,...e.mode===mt.REPLACE?{sirDetection:Lt.AFTER_DIFF}:{}});return{ok:!0,changes:c.length>0?{...O,viewState:c}:O,...e.mode===mt.REPLACE||s.size>0?{...e.mode===mt.REPLACE?{__beforeSnap:a}:{},__beforeLinks:Sg(s)}:{}}}function pg(e,t){if(e.mode!==mt.APPEND&&e.mode!==mt.REPLACE)return C.INVALID;let r=new Set,i=new Set;for(let o of e.items){if(o.batchId.length===0||r.has(o.batchId))return C.INVALID;if(r.add(o.batchId),o.index!==void 0&&(!Number.isInteger(o.index)||o.index<0))return C.INVALID;if(o.activityId!==void 0){let a=String(o.activityId);if(a.length===0||a==="0"||i.has(a))return C.INVALID;i.add(a)}}for(let o of e.items)if(!ka(o.parent,!0,e.mode,r,t))return C.PARENT_NOT_FOUND;if(yg(e.items))return C.INVALID;let n=new Set;for(let o of e.links){if(!Object.values(W).includes(o.type))return C.INVALID_LINK_TYPE;if(o.lag!==void 0&&!Number.isFinite(o.lag))return C.INVALID_LINK_LAG;if(!ka(o.source,!1,e.mode,r,t)||!ka(o.target,!1,e.mode,r,t))return C.ACTIVITY_NOT_FOUND;if(o.linkId!==void 0){let a=String(o.linkId);if(a.length===0||n.has(a))return C.INVALID;n.add(a)}}return null}function ka(e,t,r,i,n){return typeof e=="string"?e==="0"?t:r===mt.APPEND&&n.adapter.getActivity(String(e))!==null:e!==null&&e.batchId.length>0&&i.has(e.batchId)}function yg(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 hg(e,t){let r=new Map;for(let d of e.items){let u=Nn(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=mg(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=Ig(d.linkId,e.mode,o,t);return o.add(String(u)),u}),s=gg(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:C.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:C.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=hd(u.source,i),p=hd(u.target,i),y=a[d];if(f===null||p===null||y===void 0)return{ok:!1,reason:C.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 mg(e,t,r,i){if(e!==void 0&&(t===mt.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===mt.APPEND&&(i.adapter.getActivity(o)!==null||i.isActivityIdReserved(String(o)));)o=i.activityIdGen.next();return o}function Ig(e,t,r,i){if(e!==void 0&&(t===mt.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===mt.APPEND&&(i.adapter.getLink(o)!==null||i.isLinkIdReserved(String(o)));)o=i.linkIdGen.next();return o}function gg(e,t,r){if(Id(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===mt.REPLACE||typeof s.parent!="string"&&t.has(s.parent.batchId)?[]:Da(r.adapter,d).sort((I,g)=>Ot(I)-Ot(g)||String(I.id).localeCompare(String(g.id))).map(I=>String(I.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?yd(c[d-1],r):null,p=l<c.length?yd(c[l],r):null;for(let y=0;y<u;y+=1){let I=c[d+y],g=a.get(I);g!==void 0&&o.set(g,Ag(f,p,y+1,u))}}}return o}function Id(e){return e.mode===mt.APPEND&&e.items.every(t=>t.parent==="0"&&t.index===void 0)}function yd(e,t){let r=t.adapter.getActivity(e);return r?Ot(r):0}function Ag(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 vg(e,t,r){let i=new Map,n=new Map,o=[];for(let s of t){if(s.parentBatchId===null){o.push(s);continue}let c=i.get(s.parentBatchId)??[];c.push(s),i.set(s.parentBatchId,c)}for(let s=0;s<o.length;s+=1){let c=o[s],l=await di({kind:h.ACTIVITY_CREATE,parentId:c.parentId,activityId:c.activityId,overrides:c.overrides,...e.eventSource===void 0?{}:{eventSource:e.eventSource}},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,skipCacheInvalidation:!0,skipRollupCascades:!0,insertionCorrelativeId:c.insertionCorrelativeId});if(!l.ok)return l;for(let[d,u]of l.removedParentLinks)n.set(d,u);for(let d of i.get(c.input.batchId)??[])o.push(d)}if(o.length!==t.length)return{ok:!1,reason:C.INVALID};let a=new Set;for(let s=o.length-1;s>=0;s-=1){let c=o[s].parentId;c==="0"||a.has(String(c))||(a.add(String(c)),wt(c,r.adapter))}return{ok:!0,removedParentLinks:n}}function hd(e,t){return typeof e=="string"?e:t.get(e.batchId)??null}function Cg(e){return new Map(e.adapter.getAllLinks().map(t=>[String(t.id),{...t}]))}function Sg(e){return new Map(Array.from(e,([t,r])=>[String(t),r]))}function gd(e,t){let{adapter:r}=t,i=e.activityId,n=r.getActivity(i);if(!n)return{ok:!1,reason:C.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:C.ACTIVITY_NOT_FOUND};let c={id:i,kind:b.UPDATED,fields:{pendingRequestIds:{before:o,after:a}},after:it(s)};return{ok:!0,changes:{source:e,activities:[c],links:[],calendars:[],trackingEvents:[]}}}function Ad(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 vd(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 Tg(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 Cd(e,t,r,i){let n=new Set,o=new Set;for(let a of e)Tg(a,t,r,i,n,o)}async function Sd(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=Zr(t.adapter,i),o=new Set(i);for(let s of n)o.add(String(s));let a=await tt(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",je(s.progress))}vc(n,t.adapter),td(i,n,t.adapter)}),[...await yn(t.adapter,a,o)]}async function Td(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=Ad(a),u=Ad(s);Cd(r,"activity",y=>{let I=c.get(y);return{exists:I!==void 0,current:I?.proplannerId??null}},d),Cd(i,"link",y=>{let I=l.get(y);return{exists:I!==void 0,current:I?.proplannerId??null}},u),vd(a,r,"activity"),vd(s,i,"link");let f=[],p=[];return t.adapter.batchUpdate(()=>{for(let y of r){let I=t.adapter.getActivity(y.id);if(!I||I.proplannerId===y.proplannerId)continue;let g=I.proplannerId;t.adapter.setActivityField(y.id,"proplannerId",y.proplannerId),f.push({id:y.id,kind:b.UPDATED,fields:{proplannerId:{before:g,after:y.proplannerId}},after:{...I,proplannerId:y.proplannerId}})}for(let y of i){let I=t.adapter.getLink(y.id);if(!I||I.proplannerId===y.proplannerId)continue;let g=I.proplannerId;t.adapter.setLinkProplannerId(y.id,y.proplannerId),p.push({id:y.id,kind:b.UPDATED,fields:{proplannerId:{before:g,after:y.proplannerId}},after:{...I,proplannerId:y.proplannerId}})}}),{ok:!0,changes:{source:e,activities:f,links:p,calendars:[],trackingEvents:[]}}}async function Ed(e,t,r){if(Eg(e))return{ok:!1,reason:C.INVALID_VALUE};let i=[...new Set(e.activityIds.map(String))];if(e.acknowledgePersistedLookahead===!0&&i.some(s=>!r.isActivityIdReserved(s)))return{ok:!1,reason:C.INVALID};let o=i.map(s=>r.adapter.getActivity(s));if(o.some(s=>!s))return{ok:!1,reason:C.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:b.UPDATED,fields:d,after:{...l,isLookahead:e.isLookahead,hasLookaheadTasks:e.hasLookaheadTasks}})}return e.persistedProgress!==void 0&&(await Sd([{activityId:i[0],progress:e.persistedProgress}],r)).length>0?(await X({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 $(r.adapter,{source:e,beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:r.sector.hoursPerDay})}):{ok:!0,changes:{source:e,activities:a,links:[],calendars:[],trackingEvents:[]}}}function Eg(e){let t=e.persistedProgress;return t!==void 0&&(e.activityIds.length!==1||!Number.isFinite(t)||t<0||t>100)}function Pa(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)wg(f,r);let n=r.getVisualOrderIds().filter(f=>i.has(f)&&!Lr(f,i,r)),o=n.map(f=>Dg(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=wn(d,r);return{sourceStateRevision:t.stateRevision,conversionRootIds:n,conversionGroups:a,milestoneMoves:s,activityIdsToDelete:c,linkIdsToDelete:u,formerParents:l}}async function kd(e,t,r){if(e.expectedStateRevision!==r.stateRevision)return{ok:!1,reason:C.STALE_STATE_REVISION};let i=Pa(e,r);if(!Fg(i,r.adapter))return{ok:!1,reason:C.HIERARCHY_CYCLE};let{adapter:n,scheduler:o}=r;o.invalidateAllCaches();let a=await Pg(i,n);Lg(i,r),Rd(i,n),Og(i,a.deletedIds,n);let s=Ng(i,n);Cr(n,s,a.deletedIds,a.beforeSnap,a.touchedIds);let{scheduledIds:c}=await X({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 $(n,{source:e,beforeSnap:a.beforeSnap,touchedIds:a.touchedIds,scheduledIds:c,sirDetection:"after-diff",links:Zt(a.beforeLinks),hoursPerDay:r.sector.hoursPerDay,correlativeShifts:s});return bg(i,a,l)}function Dg(e,t){let r=Ra(e,t),i=bn([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=>Ra(c,t));_d(r);for(let c of n)_d(c);let o=n.filter(c=>c.type!==E.MILESTONE),a=n.filter(c=>c.type===E.MILESTONE),s=_g(r,o);return{conversionRootId:e,convertedActivities:o.map(c=>kg(c,s)),milestoneMoves:Rg(r,a),activityIdsToDelete:o.map(c=>c.id),formerParent:{activity:it(r),hasConvertedActivities:o.length>0}}}function _g(e,t){let r=new Map;t.length>0&&r.set(e.id,Dd(e));for(let i of t)r.set(i.id,Dd(i));return r}function kg(e,t){let r=it(e),i=zt(e.parentId),n=t.get(i);return r.parentId=n===void 0?null:String(n),r}function Rg(e,t){let r=[],i=zt(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 Pg(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 tt(t,i),beforeLinks:xg(e.linkIdsToDelete,t),viewStateChanges:li(t,r)}}function Lg(e,t){for(let r of e.activityIdsToDelete){let i=t.adapter.getActivity(r)?.customId;i&&t.customIdTracker.releaseCustomId(i)}}function Rd(e,t){for(let r of e.milestoneMoves)t.setActivityFields(r.activityId,{parentId:r.parentId,correlativeId:Pr(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,F.TYPE,E.TASK)}function Og(e,t,r){for(let{activity:i,hasConvertedActivities:n}of e.formerParents){let o=Ra(i.id,r),a=Fn({parent:o,idsRemoved:t});r.setActivityFields(i.id,{isLookahead:i.isLookahead||n,hasLookaheadTasks:i.hasLookaheadTasks||n,...a?.fields??{}})}}function Ng(e,t){for(let{activity:r}of e.formerParents)wt(r.parentId,t);return _t(t)}function bg(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=>it(a))})),__beforeSnap:i,__beforeLinks:t.beforeLinks}}function wg(e,t){let r=t.getActivity(e);if(!r)throw new Error(`Conversion root ${e} was not found`);if(r.type===E.PROJECT&&r.correlativeId===0)throw new Error(`Conversion root ${e} is the visual project root`)}function Ra(e,t){let r=t.getActivity(e);if(!r)throw new Error(`Conversion activity ${e} is missing`);return r}function Dd(e){if(e.proplannerId==null)throw new Error(`Conversion activity ${e.id} has no persisted identifier`);return e.proplannerId}function _d(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 Fg(e,t){let r=t.fork();return Rd(e,r),ve({port:t,proposedPort:r,currentLinks:t.getAllLinks(),proposedLinks:r.getAllLinks()}).ok}function xg(e,t){let r=new Map;for(let i of e){let n=t.getLink(i);n&&r.set(i,{...n})}return r}function Nr(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)||Ld(n,t)&&i.push(String(n.id))}return i}function Ld(e,t){let r=String(e.source),i=String(e.target);return Pd(i,r,t)||Pd(r,i,t)}function xn(e,t){return[...e].filter(([,r])=>Ld(r,t)).map(([r])=>String(r))}function Pd(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||B(a))return!1;let s=a;if(s===t)return!0;i=s}return!1}function Mn(e,t){let r=e.getAllLinks();return!ve({port:e,currentLinks:r,proposedLinks:r,proposal:{reparented:t}}).ok}function Un(e,t){let r=new Set;if(e.length===0)return r;let i=new Map(e.map(o=>[o.activityId,o.newParentId]));if(!Mn(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),Mn(t,a)){r.add(o.activityId);continue}n.set(o.activityId,o.newParentId)}return r}async function Od(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:C.ACTIVITY_NOT_FOUND};let s=B(e.parentId);if(!s&&!i.getActivity(e.parentId))return{ok:!1,reason:C.PARENT_NOT_FOUND};if(!s&&(e.parentId===e.activityId||i.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:C.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:C.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let A=i.getActivity(c);if(!A)return{ok:!1,reason:C.ANCHOR_SIBLING_NOT_FOUND};if((A.parentId===null?"0":String(A.parentId))!==e.parentId)return{ok:!1,reason:C.ANCHOR_SIBLING_WRONG_PARENT}}let l=a.parentId,d=zt(l),u=String(e.parentId),f=d!==u;if(f){let A=new Map([[e.activityId,s?null:e.parentId]]);if(Mn(i,A))return{ok:!1,reason:C.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 tt(i,p),I=new Map;f&&i.setActivityField(e.activityId,F.PARENT,u);let g=Pr(i,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(i.setActivityField(e.activityId,F.CORRELATIVE_ID,g),f){if(!s){let A=i.getActivity(e.parentId);if(A){let S=Ae(A.type)&&i.getChildren(e.parentId).filter(j=>j!==e.activityId).length===0,N=we({parentId:e.parentId,newChildId:e.activityId,isCurrentlyLeaf:S,promotionSource:Or.REPARENT},r);if(N.applied)for(let[j,K]of N.removedLinks)I.set(j,K)}}if(d!=="0"){let A=i.getActivity(d);if(A){let S=i.getChildren(d),N=be({parent:A,remainingChildIds:S.map(String),defaultDurationHours:o.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(d),computeEndDate:(j,K)=>i.calculateEndDate({startDate:j,durationHours:K,task:A}),idsRemoved:new Set([e.activityId])});if(N){for(let[lt,dt]of Object.entries(N.fields))Tt(i,d,lt,dt);let j=ae(d,i),K=j?i.getActivity(j)?.customId:null,Z=typeof K=="string"&&K?K:null,st=r.customIdTracker.generateCustomIdForRestoredChild(Z);i.setActivityField(d,F.CUSTOM_ID,st)}}}}f&&(d!=="0"&&wt(d,i),s||wt(e.parentId,i));let _=_t(i);for(let A of _){if(p.add(A.activityId),y.has(A.activityId))continue;let S=i.getActivity(A.activityId);if(!S)continue;let N=it(S);A.before!==void 0&&(N.correlativeId=A.before),y.set(A.activityId,N)}let k=f&&d!=="0"?i.getChildren(d).map(String):[],{scheduledIds:O}=await X({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,...k],now:r.now,options:t,recomputeParentProgress:f}),T=f?Nr([e.activityId],i):[],P=xn(I,i),x={name:Gt.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:[...new Set([...P,...T.map(String)])]}};return e.eventSource!==void 0&&(x.properties.event_source=e.eventSource),{ok:!0,changes:await $(i,{source:e,beforeSnap:y,touchedIds:p,scheduledIds:O,sirDetection:Lt.BEFORE_DIFF,links:Zt(I),trackingEvents:[x],hoursPerDay:o.hoursPerDay}),...I.size>0?{__beforeLinks:I}:{}}}function Bn(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?Ot(f):rr,I=p?Ot(p):rr;return y-I});for(let d of s){if(!t.getActivity(d)){i.push({activityId:d,reason:C.ACTIVITY_NOT_FOUND}),a.delete(d);continue}if(Lr(d,o,t))continue;let f=Vs(d,a,t);if(f==null){i.push({activityId:d,reason:C.INDENT_NO_ELIGIBLE_SIBLING}),a.delete(d);continue}let p=t.getActivity(d)?.parentId,y=B(p)?"0":String(p);n.push({activityId:d,newParentId:f,oldParentId:y}),o.add(d)}let c=Un(n,t);for(let d of c)i.push({activityId:d,reason:C.HIERARCHY_CYCLE});let l=n.filter(d=>!c.has(d.activityId));return{moves:n,cyclicMoveIds:c,allowedMoves:l,failed:i}}async function Nd(e,t,r){let{adapter:i,scheduler:n,sector:o}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:C.ACTIVITY_IDS_EMPTY};let a=new Set,s=[],c=Bn(e.activityIds,i),l=[...c.failed];for(let P of c.moves)a.add(String(P.activityId)),a.add(String(P.newParentId)),P.oldParentId!=="0"&&a.add(String(P.oldParentId));let d=c.allowedMoves,u=await tt(i,a);for(let{activityId:P,newParentId:x}of d)i.setActivityField(P,F.PARENT,x),i.setActivityField(P,F.CORRELATIVE_ID,sd),s.push(P);let f=new Set,p=new Map;for(let{activityId:P,newParentId:x}of d){if(f.has(x))continue;f.add(x);let A=i.getActivity(x);if(!A)continue;let S=A.customId,N=Ae(A.type)&&i.getChildren(x).filter(Z=>!s.includes(Z)).length===0,j=A.hasNewActivities&&A.newActivityIds.some(Z=>String(Z)===String(P)),K=we({parentId:x,newChildId:P,isCurrentlyLeaf:N,promotionSource:Or.REPARENT},r);if(K.applied){for(let[Z,st]of K.removedLinks)p.set(Z,st);j||(i.setActivityField(x,F.HAS_NEW_ACTIVITIES,!1),i.setActivityField(x,F.NEW_ACTIVITIES_ARRAY,[]))}i.setActivityField(x,F.CONSTRAINT_TYPE,v.ASAP),i.setActivityField(x,F.CONSTRAINT_DATE,null),i.setActivityField(x,F.CUSTOM_ID,null),K.applied||Yl(S,r.customIdTracker)}let y=new Set;for(let P of d)P.oldParentId!=="0"&&y.add(P.oldParentId),y.add(P.newParentId);for(let P of y)wt(P,i);let I=_t(i);for(let P of I){if(a.add(P.activityId),u.has(P.activityId))continue;let x=i.getActivity(P.activityId);if(!x)continue;let A=it(x);P.before!==void 0&&(A.correlativeId=P.before),u.set(P.activityId,A)}let g=xn(p,i),_=Nr(s,i);for(let P of _){let x=i.getLink(P);x&&(p.set(P,{...x}),i.removeLink(P))}let{scheduledIds:k}=await X({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:s,now:r.now,options:t}),O={name:Gt.ACTIVITY_INDENT,properties:{activity_ids:s,failed:l.map(P=>({activity_id:P.activityId,reason:P.reason})),invalid_link_ids:[...new Set([...g,..._.map(String)])]}};e.eventSource!==void 0&&(O.properties.event_source=e.eventSource);let T=await $(i,{source:e,beforeSnap:u,touchedIds:a,scheduledIds:k,links:Zt(p),trackingEvents:[O],hoursPerDay:o.hoursPerDay});return{ok:!0,activityVerdicts:e.activityIds.map(P=>{let x=l.find(A=>String(A.activityId)===String(P));return x?{activityId:String(P),ok:!1,reason:x.reason}:{activityId:String(P),ok:!0}}),changes:T,__beforeLinks:p}}async function bd(e,t,r){let{adapter:i,scheduler:n,sector:o}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:C.ACTIVITY_IDS_EMPTY};let a=new Set(e.activityIds),s=new Map,c=new Map;for(let A of e.activityIds){let S=A;i.getActivity(S)&&(s.set(S,Co(S,i)),c.set(S,cd(S,a,i)))}let l=new Set,d=[],u=[],f=new Set,p=[],y=new Set,I=[...e.activityIds].sort((A,S)=>{let N=i.getActivity(A),j=i.getActivity(S),K=N?Ot(N):rr,Z=j?Ot(j):rr;return K-Z});for(let A of I){let S=A,N=i.getActivity(S);if(!N){d.push({activityId:S,reason:C.ACTIVITY_NOT_FOUND});continue}if(Lr(S,y,i))continue;let j=N.parentId;if(B(j)){d.push({activityId:S,reason:C.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let K=String(j),Z=i.getActivity(K);if(!Z){d.push({activityId:S,reason:C.ACTIVITY_NOT_FOUND});continue}let st=Z.parentId;if(B(st)){d.push({activityId:S,reason:C.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let lt=String(st),dt=Co(K,i)+1,re=c.get(S);if(re!=null&&a.has(re)){let Ft=s.get(re)??-1,ar=s.get(S)??-1;Ft>=0&&ar>=0&&(dt+=ar-Ft)}p.push({activityId:S,grandparentKey:lt,oldParentKey:K,targetIndexInGrandparent:dt}),y.add(S),l.add(String(S)),l.add(String(K)),lt!=="0"&&l.add(String(lt)),f.add(K)}let g=Un(p.map(A=>({activityId:A.activityId,newParentId:A.grandparentKey})),i);for(let A of g)d.push({activityId:A,reason:C.HIERARCHY_CYCLE});let _=p.filter(A=>!g.has(A.activityId)),k=await tt(i,l);for(let A of _){i.setActivityField(A.activityId,F.PARENT,A.grandparentKey);let S=ld(i,A.grandparentKey,A.targetIndexInGrandparent,A.activityId);i.setActivityField(A.activityId,F.CORRELATIVE_ID,S),u.push(A.activityId)}for(let A of f){let S=i.getActivity(A);if(!S)continue;let N=i.getChildren(A),j=be({parent:S,remainingChildIds:N.map(String),defaultDurationHours:o.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(A),computeEndDate:(dt,re)=>i.calculateEndDate({startDate:dt,durationHours:re,task:S}),idsRemoved:new Set(_.filter(dt=>dt.oldParentKey===A).map(dt=>dt.activityId))});if(!j){en(A,i);continue}for(let[dt,re]of Object.entries(j.fields))Tt(i,A,dt,re);let K=ae(A,i),Z=K?i.getActivity(K)?.customId:null,st=typeof Z=="string"&&Z?Z:null,lt=r.customIdTracker.generateCustomIdForRestoredChild(st);i.setActivityField(A,F.CUSTOM_ID,lt)}let O=new Set;for(let A of f)O.add(String(A));for(let A of _)A.grandparentKey!=="0"&&O.add(String(A.grandparentKey));for(let A of O)wt(A,i);let T=_t(i);for(let A of T){if(l.add(A.activityId),k.has(A.activityId))continue;let S=i.getActivity(A.activityId);if(!S)continue;let N=it(S);A.before!==void 0&&(N.correlativeId=A.before),k.set(A.activityId,N)}let{scheduledIds:P}=await X({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:u.length>0?yt.ROOTS:null,recomputeParentsFrom:u,now:r.now,options:t}),x={name:Gt.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(A=>({activity_id:String(A.activityId),reason:A.reason}))}};return e.eventSource!==void 0&&(x.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(A=>{let S=d.find(N=>String(N.activityId)===String(A));return S?{activityId:String(A),ok:!1,reason:S.reason}:{activityId:String(A),ok:!0}}),changes:await $(i,{source:e,beforeSnap:k,touchedIds:l,scheduledIds:P,trackingEvents:[x],hoursPerDay:o.hoursPerDay})}}async function wd(e,t,r){let{adapter:i,scheduler:n,sector:o}=r,a=i.getActivity(e.activityId);if(!a)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};if(!Hr(e.type))return{ok:!1,reason:C.INVALID_VALUE};let s=i.getChildren(e.activityId),c=e.type===E.PROJECT;if(c!==s.length>0)return{ok:!1,reason:C.INVALID_VALUE};let l=new Set(i.getAllIds()),d=await tt(i,l);n.invalidateAllCaches();let u=c&&a.type!==E.PROJECT?we({parentId:e.activityId,newChildId:s[0],isCurrentlyLeaf:!0},r).removedLinks:new Map;!c&&a.type===E.PROJECT&&Mg(e.activityId,r),e.type!==E.PROJECT?(Ug(e.activityId,e.type,r),Bg(e.activityId,r)):wt(e.activityId,i);let f=Hg(e.activityId,r);for(let[y,I]of u)f.set(y,I);let{scheduledIds:p}=await X({adapter:i,scheduler:n,sector:o,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId],recomputeParentProgress:!0,now:r.now,options:t});return{ok:!0,changes:await $(i,{source:e,beforeSnap:d,touchedIds:l,scheduledIds:p,sirDetection:Lt.BEFORE_DIFF,links:Zt(f),hoursPerDay:o.hoursPerDay}),__beforeLinks:new Map(f)}}function Mg(e,t){let r=t.adapter.getActivity(e);if(!r)return;let i=be({parent:r,remainingChildIds:[],defaultDurationHours:t.sector.hoursPerDay,promotionSnapshot:t.adapter.getPromotionSnapshot(e),computeEndDate:(n,o)=>t.adapter.calculateEndDate({startDate:n,durationHours:o,task:r})});if(i)for(let[n,o]of Object.entries(i.fields))Tt(t.adapter,e,n,o)}function Ug(e,t,r){let i=r.adapter.getActivity(e);if(!i)return;r.adapter.setActivityField(e,F.TYPE,t);let n=t===E.MILESTONE?0:i.durationHours===0?r.sector.hoursPerDay:i.durationHours;n!==i.durationHours&&r.adapter.setActivityField(e,F.DURATION_HOURS,n);let o=r.adapter.getActivity(e);if(!o)return;let a=r.adapter.calculateEndDate({startDate:o.startDate,durationHours:n,task:o});r.adapter.setActivityField(e,F.END_DATE,a)}function Bg(e,t){if(t.adapter.getActivity(e)?.customId)return;let i=ae(e,t.adapter),n=i?t.adapter.getActivity(i)?.customId:null,o=t.customIdTracker.generateCustomIdForRestoredChild(n||null);t.adapter.setActivityField(e,F.CUSTOM_ID,o)}function Hg(e,t){let r=new Map;for(let i of Nr([e],t.adapter)){let n=t.adapter.getLink(i);n&&(r.set(String(i),{...n}),t.adapter.removeLink(i))}return r}async function Fd(e,t,r){let{adapter:i,ctx:n,scheduler:o,sector:a}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:C.INVALID_PROGRESS_VALUE};let s=n.activityReader.getActivity(e.activityId);if(!s)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let c=Pe(D.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===dn.ACTION_BUTTON&&(l.reason===ti.HAS_LOOKAHEAD_TASKS||l.reason===ti.SUMMARY)))return{ok:!1,reason:l.reason,...l.alertKey?{alertKey:l.alertKey}:{}};let d=c.transform(s,e.newValue,n,e.newValue),u=Le(e.activityId,d),f=await tt(i,u);Oe(i,e.activityId,d),Sc(e.activityId,e.newValue,i),Ee(e.activityId,d.postProcessors??[],i);let p=d.needsAutoSchedule?n.hierarchy.hasChildren(e.activityId)?yt.ROOTS:e.activityId:null,{scheduledIds:y}=await X({adapter:i,scheduler:o,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:p,recomputeParentsFrom:[],collectDirty:g=>hn(e.activityId,u,g),now:r.now,options:t}),I=(d.trackingEvents??[]).map(g=>({name:g.name,properties:g.properties??{}}));return{ok:!0,changes:await $(i,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:y,trackingEvents:I,hoursPerDay:a.hoursPerDay})}}function Wg(e){return e===D.START_DATE||e===D.END_DATE}async function xd(e,t,r){if(e.edits.some(y=>!Wg(y.column)))return{ok:!1,reason:C.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 I=Vg(y,r);if(a.push(I.verdict),!I.verdict.ok||!I.changes)continue;let g=Le(y.activityId,I.changes);jg(s,g,r);for(let T of g)c.add(T);let _=kr(i,y.activityId),k=pn(i,String(y.activityId));Oe(i,y.activityId,I.changes),Ee(y.activityId,I.changes.postProcessors??[],i,k),d.push(...Rr(_,i,y.activityId)),f||=!!I.changes.needsAutoSchedule;for(let T of I.changes.trackingEvents??[])l.push({name:T.name,properties:T.properties??{}});let O=Je(y.activityId,I.changes.constraintWarning);O&&u.push(O)}let{scheduledIds:p}=await X({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:f?yt.ROOTS:null,recomputeParentsFrom:c,now:r.now,options:t});return{ok:!0,verdicts:a,changes:await $(i,{source:e,beforeSnap:s,touchedIds:c,scheduledIds:p,sirDetection:Lt.BEFORE_DIFF,links:d,trackingEvents:l,warnings:u,hoursPerDay:o.hoursPerDay})}}function Vg(e,t){let{ctx:r}=t,i=e.activityId,n=Pe(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??C.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??C.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??C.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 jg(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,it(o))}}var La=D.CUSTOM_ID;async function Md(e,t,r){let{adapter:i,scheduler:n,sector:o}=r;e.edits.some(A=>A.column===D.DURATION)&&n.invalidateExpandedLinksCache();let s=[],c=new Map,l=new Map,d=new Set,u=new Set,f=[],p=[],y=[],I=new Set,g=new Map,_=new Map,k=!1;for(let A of e.edits){let S=qg(A,r,e.eventSource);if(s.push(S.verdict),!S.verdict.ok||!S.changes)continue;let N=Je(A.activityId,S.changes.constraintWarning);N&&y.push(N);let j=Le(A.activityId,S.changes);Qg(c,j,r);for(let dt of j)u.add(dt);Zg(l,A,c),Dn(A.column)&&d.add(String(A.activityId)),Gg(g,A);let K=kr(i,A.activityId),Z=pn(i,String(A.activityId)),st=Jg(A,r),lt=S.changes;Oe(i,A.activityId,lt),Ee(A.activityId,S.changes.postProcessors??[],i,Z),Kg(I,y,A),Yg(_,A,i.getActivity(A.activityId)),Xg(A,st,r),p.push(...Rr(K,i,A.activityId)),k||=!!S.changes.needsAutoSchedule;for(let dt of S.changes.trackingEvents??[])f.push({name:dt.name,properties:dt.properties??{}})}let O={action:e,autoscheduleFrom:k?yt.ROOTS:null,recomputeParentsFrom:u,now:r.now,options:t},T=$g(g,_,c,y,I,r),P=l.size>0,{scheduledIds:x}=await(P?kn({adapter:i,scheduler:n,sector:o,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:O,revertTargets:[...l].filter(([A])=>!d.has(A)).map(([A,S])=>({activityId:A,priorConstraintDate:S})),revert:(A,S)=>_n(A,S,i,r.ctx.calendars)}):X({adapter:i,scheduler:n,sector:o,defaultBaseCalendarId:r.defaultBaseCalendarId},O));return{ok:!0,verdicts:s,changes:await $(i,{source:e,beforeSnap:c,touchedIds:u,scheduledIds:x,sirDetection:Lt.BEFORE_DIFF,links:p,trackingEvents:f,warnings:T,hoursPerDay:o.hoursPerDay})}}function Kg(e,t,r){if(!Dr(r.column))return;let i=String(r.activityId);for(let n of t)String(n.activityId)===i&&e.add(n)}function Yg(e,t,r){!Dr(t.column)||!r||e.set(String(t.activityId),{constraintType:r.constraintType,constraintDate:r.constraintDate?new Date(r.constraintDate.getTime()):null})}function Gg(e,t){if(t.column!==D.START_DATE&&t.column!==D.END_DATE)return;let r=String(t.activityId),i=e.get(r)??new Set;i.add(t.column),e.set(r,i)}function $g(e,t,r,i,n,o){let a=new Set,s=[],c=new Set;for(let[l,d]of e){if(!d.has(D.START_DATE)||!d.has(D.END_DATE))continue;let u=t.get(l);if(u){o.adapter.setActivityFields(l,u);for(let g of n)String(g.activityId)===l&&c.add(g);continue}let f=r.get(l),p=o.adapter.getActivity(l);if(!f?.constraintType||!f.constraintDate||!p)continue;let y=Fe(f.constraintType,p.startDate,p.endDate),I=zg(f.constraintType,f.constraintDate,y);if(a.add(l),I){o.adapter.setActivityField(l,"constraintType",v.SNET),o.adapter.setActivityField(l,"constraintDate",new Date(p.startDate.getTime()));let g=Je(l,Ai(f.constraintType,f.constraintDate,y));g&&s.push(g);continue}o.adapter.setActivityField(l,"constraintType",f.constraintType),o.adapter.setActivityField(l,"constraintDate",f.constraintDate)}return[...i.filter(l=>!c.has(l)&&!a.has(String(l.activityId))),...s]}function zg(e,t,r){return e===v.MSO||e===v.MFO?t.getTime()!==r.getTime():gi(e,t,r).violated}function qg(e,t,r){let{ctx:i}=t,n=e.activityId,o=Pe(e.column);if(!o)return{verdict:{activityId:n,ok:!1,reason:C.NO_PIPELINE_FOR_COLUMN},changes:null};let a=i.activityReader.getActivity(e.activityId);if(!a)return{verdict:{activityId:n,ok:!1,reason:C.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??C.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??C.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??C.INVALID,...d.notification?.messageKey?{alertKey:d.notification.messageKey}:{}},changes:null};if(e.column===La&&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:C.CUSTOM_ID_DUPLICATE},changes:null}}let u=o.transform(a,c.value,i,c.raw);return{verdict:{activityId:n,ok:!0},changes:u}}function Jg(e,t){if(e.column!==La)return null;let r=t.adapter.getActivity(e.activityId),i=r?r.customId:null;return typeof i=="string"?i:null}function Xg(e,t,r){if(e.column!==La)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 Zg(e,t,r){if(!Dr(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 Qg(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,it(o))}}var Nt={INVALID_BASELINE_POINT:"invalid_baseline_point",UNKNOWN_CONSTRAINT:"unknown_constraint",ORPHAN_ACTIVITY:"orphan_activity",INVALID_LINK:"invalid_link",DUPLICATE_LINK:"duplicate_link"},tA=[Nt.INVALID_BASELINE_POINT,Nt.UNKNOWN_CONSTRAINT,Nt.ORPHAN_ACTIVITY,Nt.INVALID_LINK,Nt.DUPLICATE_LINK],br=()=>{};function Ud(){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(tA.flatMap(n=>{let o=e.get(n);return o===void 0?[]:[Object.freeze({code:n,count:o,sampleIds:Object.freeze([...t.get(n)??[]])})]}))}}function Bd(e){return typeof e=="string"&&e.length>0?fe(e):e instanceof Date?e:null}function Oa(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,i=!1){let n=Oa(e.duration),o=Oa(e.cost),a=Oa(e.hh_work);if(n===null||o===null||a===null)return r&&r.record(Nt.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;let s=Bd(e.start_date),c=Bd(e.end_date),l=i&&n===0&&s!==null&&c!==null&&c<s;return l&&t.warn("[baseline] normalizing inverted zero-duration milestone to one instant"),{startDate:s,endDate:l?s:c,durationDays:n,cost:o,workHours:a,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 Hd(e,t,r,i=br){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(Nt.INVALID_BASELINE_POINT,String(c??"unknown"));continue}let l=n.get(c);if(l===void 0){i(Nt.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){let l=e.getActivity(s)?.type===E.MILESTONE;e.setActivityField(s,"baselinePoints",c.map(d=>Hn(d,r,{record:i,sampleId:s},l)).filter(d=>d!==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 eA(e){let t=Ct(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function Wd(e){let t=[];return e.forEachActivity((r,i)=>{let n=eA(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 Wn(e,t,r,i,n=null,o=br){let a=new Set;for(let s of Hd(e,t,i,o))a.add(s);if(r)for(let s of Tr(e,r,n))a.add(s);for(let s of Wd(e))a.add(s);for(let s of Er(e))a.add(s);return[...a]}function Vd(e,t){t.forEachActivity((r,i)=>{t.setActivityField(i,D.PONDERATOR,0)}),t.forEachActivity((r,i)=>{t.getChildren(i).length>0&&En(String(i),e,t)})}function Vn(e,t){Vd(t,e.adapter),Jr(e.adapter),e.now&&(Tr(e.adapter,e.now,e.defaultBaseCalendarId??null),Xe(e.adapter,e.now)),Er(e.adapter),e.now&&pe(e.adapter,e.sector.statusCriteria)}function jd(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 Kd(e,t){let r=await tt(t.adapter,new Set(t.adapter.getAllIds())),i=jd(t),n=Wn(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return jd(t)!==i&&Vn(t,t.sector.activityCreter??It.DURATION),{ok:!0,changes:await $(t.adapter,{source:e,beforeSnap:r,touchedIds:n,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function rA(e){return Object.values(It).includes(e)}async function Yd(e,t){if(!rA(e.criterion))return{ok:!1,reason:C.INVALID_VALUE};let r=new Set(t.adapter.getAllIds()),i=await tt(t.adapter,r);return Vn(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:await $(t.adapter,{source:e,beforeSnap:i,touchedIds:r,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function Gd(e,t){let r=mn(e.criteria),i=new Set(t.adapter.getAllIds()),n=await tt(t.adapter,i),o=pe(t.adapter,r);return t.sector.statusCriteria=r,{ok:!0,changes:await $(t.adapter,{source:e,beforeSnap:n,touchedIds:o,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function zd(e,t,r){let i=new Map,n=new Set;for(let a of r.adapter.getAllActivities()){if(!iA(a,r))continue;let s=r.ctx.calendars.getCalendar(a.calendarId);if(!s)continue;let c=s.isWorkTime(a.startDate,pt.HOUR)?nA(a.startDate):a.startDate,l=s.getClosestWorkTime({date:c,direction:Y.FUTURE,unit:pt.HOUR}),d=s.calculateEndDate(l,a.durationHours);if($d(l,a.startDate)&&$d(d,a.endDate))continue;let u=String(a.id);i.set(u,it(a)),n.add(u),r.adapter.setActivityFields(u,{startDate:l,endDate:d})}let{scheduledIds:o}=await X({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:yt.ROOTS,recomputeParentsFrom:n,now:r.now,options:t});return{ok:!0,changes:await $(r.adapter,{source:e,beforeSnap:i,touchedIds:n,scheduledIds:o,hoursPerDay:r.sector.hoursPerDay})}}function iA(e,t){return e.progress===0&&!qt(e.type,t.adapter.hasChildren(e.id))}function $d(e,t){return e.getTime()===t.getTime()}function nA(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var qd=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","cost","hasCustomPonderator","subcontractId","responsableIds","tagIds"];function oA(e){let t={};for(let r of qd)Object.assign(t,{[r]:w(e[r])});return t}function aA(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 Jd(e,t){let r=new Set(t.adapter.checkedIds().map(String));if(r.size===0)return{ok:!1,reason:C.NO_ACTIVITY_SELECTION};let i=aA(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:oA(a)}}),links:t.adapter.getAllLinks().filter(o=>r.has(String(o.source))&&r.has(String(o.target))).map(o=>w(o))};let n=Si({kind:h.SELECTION_REPLACE,activityIds:[]},{adapter:t.adapter});return n.ok?{...n,changes:{...n.changes,source:e}}:n}function Xd(e,t){return t.value=null,{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}}function sA(e,t){let r=t.getActivity(e);return r?r.parentId==null?t.getRootIds().length===1?{ok:!0,parentId:r.id,beforeSiblingId:t.getChildren(r.id)[0]}:{ok:!0,parentId:"0",afterSiblingId:e}:t.hasChildren(r.id)?{ok:!0,parentId:r.id,beforeSiblingId:t.getChildren(r.id)[0]}:{ok:!0,parentId:String(r.parentId),afterSiblingId:e}:{ok:!1,reason:C.ANCHOR_SIBLING_NOT_FOUND}}var Zd=()=>({ok:!1,reason:C.ACTIVITY_PASTE_INVARIANT_FAILED});async function Qd(e,t,r){let i=r.activityClipboard.value;if(i===null)return{ok:!1,reason:C.CLIPBOARD_EMPTY};let n=sA(e.destination.afterSiblingId,r.adapter);if(!n.ok)return n;let o=await tt(r.adapter,new Set),a=new Set,s=new Map,c=[],l;for(let I of i.activities){let g=s.get(I.originalParentId),_=g===void 0?l??n.afterSiblingId:void 0,k=g===void 0&&_===void 0?n.beforeSiblingId:void 0,O=await di({kind:h.ACTIVITY_CREATE,parentId:g??n.parentId,..._===void 0?{}:{afterSiblingId:_},...k===void 0?{}:{beforeSiblingId:k},overrides:w(I.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:e.destination.afterSiblingId});if(!O.ok)return O;s.set(I.originalId,O.newId),c.push(O.newId),g===void 0&&(l=O.newId)}let d=_t(r.adapter),u=new Set(c.map(String));Cr(r.adapter,d,u,o,a);for(let I of c)a.add(String(I));let f=[];for(let I of i.links){let g=s.get(I.source),_=s.get(I.target);if(g===void 0||_===void 0)return Zd();let k={kind:Et.CREATE,source:g,target:_,type:I.type,lag:I.lag},O=Ce(k,{port:r.adapter,newLinkId:r.linkIdGen.next});if(!O.applied)return Zd();f.push({op:k,finalLinkId:O.linkId,rejected:null})}let{scheduledIds:p}=await X({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=_r(f,new Map,r.adapter);return{ok:!0,changes:await $(r.adapter,{source:e,beforeSnap:o,touchedIds:a,scheduledIds:p,links:y,hoursPerDay:r.sector.hoursPerDay})}}async function tu(e,t,r){return e.kind===h.ACTIVITY_COPY?Jd(e,{adapter:r.adapter,clipboard:r.activityClipboard}):e.kind===h.CALENDAR_RECONCILE?zd(e,t,r):e.kind===h.ACTIVITY_CLIPBOARD_CLEAR?Xd(e,r.activityClipboard):e.kind===h.ACTIVITY_PASTE_COPIED?Qd(e,t,r):e.kind===me?md(e,t,r):e.kind===h.PERSISTENCE_ACKNOWLEDGE?Td(e,r):e.kind===h.BASELINE_APPLY?Kd(e,r):e.kind===h.PONDERATOR_CRITERION_SET?Yd(e,r):e.kind===h.STATUS_CRITERIA_SET?Gd(e,r):e.kind===h.LINK_CREATE||e.kind===h.LINK_UPDATE||e.kind===h.LINK_DELETE?$l(e,t,r):e.kind===h.LINKS_BATCH?zl(e,t,r):e.kind===h.ACTIVITY_CREATE?pd(e,t,r):e.kind===h.ACTIVITY_DELETE?ud(e,t,r):e.kind===h.ACTIVITY_MOVE?Od(e,t,r):e.kind===h.ACTIVITY_INDENT?Nd(e,t,r):e.kind===h.ACTIVITY_OUTDENT?bd(e,t,r):e.kind===h.ACTIVITY_TYPE_SET?wd(e,t,r):e.kind===h.ACTIVITY_SET_PROGRESS?Fd(e,t,r):e.kind===h.DATES_BATCH?xd(e,t,r):e.kind===h.BULK_EDIT?Md(e,t,r):e.kind===h.SELECTION_TOGGLE?Ts(e,Na(r)):e.kind===h.SELECTION_REPLACE?Si(e,Na(r)):e.kind===h.VISIBILITY_SET?Es(e,Na(r)):e.kind===h.FILTER_SET?Us(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind===h.SORT_SET?Ks(e,{adapter:r.adapter}):e.kind===h.VIEW_ATTRIBUTES_SET?Ys(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind===h.GROUP_SET?Gs(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind===h.SIR_SYNC?gd(e,r):e.kind===h.ACTIVITY_LOOKAHEAD_SYNC?Ed(e,t,r):e.kind===h.ACTIVITY_LOOKAHEAD_CONVERT?kd(e,t,r):e.kind===h.SCHEDULE_AUTO_SCHEDULE?jl(e,t,r):e.kind===h.INLINE_EDIT&&(e.column===D.CUSTOM_PREDECESSORS||e.column===D.CUSTOM_SUCESSORS)?ql(e,t,r):e.kind!==h.INLINE_EDIT?$s(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):Gl(e,t,r)}function Na(e){return{adapter:e.adapter}}var cA=new Set(["startDate","endDate","constraintDate"]);function eu(e,t){return cA.has(e)&&typeof t=="string"?new Date(t):t}function ru(e,t={}){let r=t.defaultUnit??pt.HOUR;return{getCalendar(i){let n=e.getCalendar(String(i));return n?lA(n,r):null}}}function lA(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 dA(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function ir(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function nr(e){return ir(e)&&!isNaN(e.getTime())}var uA={}.constructor.toString();function fA(e){var t=e.constructor.toString();return t!==uA}function pA(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function Qt(e){var t,r;if(e&&typeof e=="object")switch(!0){case ir(e):r=new Date(e);break;case dA(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=Qt(e[t]);break;default:if(fA(e))r=Object.create(e);else{if(pA(e))return r=e,r;r={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(r[t]=Qt(e[t]));break}return r||e}function wr(e,t,r){for(var i in t)(e[i]===void 0||r)&&(e[i]=t[i]);return e}function iu(e){return typeof e<"u"}var jn;function ba(){return jn||(jn=new Date().valueOf()),jn++,jn}function Wt(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var hA=(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)},mA=(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)},nu={date_to_str:hA,str_to_date:mA},IA=(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}}),gA=(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])},ou={date_to_str:IA,str_to_date:gA};function au(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=nu;return o()&&(l=ou),l.date_to_str(s,c,e)},str_to_date:function(s,c){var l=nu;return o()&&(l=ou),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 wa(e,t,r,i,n){return this.date=e,this.unit=t,this.task=r,this.id=i,this.calendar=n,this}function Fa(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 xa(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 AA(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 su=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(ir(t)?t={date:t}:t=wr({},t),!nr(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 wa)return t;var r;if(t.date?r=new wa(t.date,t.unit,t.task,null,t.calendar):r=new wa(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!nr(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 Fa)return r;var i;if(ir(r)?i=new Fa(r):i=new Fa(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,!nr(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=AA,i;if(t instanceof r)return t;if(ir(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,!nr(i.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!nr(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 xa)return o;var a;if(ir(o)?a=new xa(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):a=new xa(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,!nr(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 cu(){}cu.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=Qt(e.getConfig()),i=Qt(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 I=Array.isArray(y)?y:d.hours;a.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,I))}}}};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 Ma=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}},Ua=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={}}},Ba=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 vA(){return typeof Map<"u"?new Ma:new Ua}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 Wa(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=vA(),this._largeUnitsCache=new Ba(this),this._dateDurationCache=new Ha,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}Wa.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),I=this.units[y-1];I&&!this._isWorkTime(o,I)&&(c=this._getClosestWorkTimeFuture(o,I))}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=Wt(this._getMinutesPerDay,this):s=Wt(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 Wa))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(Wt(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(Wt(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 I=!1,g=null,_=null,k=c.length-1;k>=0;k--)if(c[k].start<y-1&&c[k].end>=y-1){I=!0,g=c[k],_=c[k-1];break}if(I)if(y===g.end&&p>=g.durationMinutes)n+=g.durationMinutes,i=this.$gantt.date.add(i,-g.durationMinutes,"minute");else if(!o&&p<=y/60-g.startMinute)n+=p,i=this.$gantt.date.add(i,-p,"minute");else if(o)p<=y/60-g.startMinute?(n+=p,i=this.$gantt.date.add(i,-p,"minute")):(n+=y/60-g.startMinute,_?i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,_.end)):i=this.$gantt.date.day_start(i));else{var O=this._getMinutesPerHour(i);O<=p?(n+=O,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 T=this._getClosestWorkTimePast(i,"hour");if(T.valueOf()===i.valueOf()){var T=this.$gantt.date.add(i,-1,"day"),P=this._getWorkHours(T);if(P.length){var x=P[P.length-1];T.setUTCSeconds(x.durationSeconds)}}i=T}else i=this._getClosestWorkTimePast(new Date(i-1),"hour")}if(n<t){var A=t-n;a=this._subtractMinutesUntilHourStart(i,A),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,I=0;I<s.length;I++)if(s[I].start<=f&&s[I].end>f){p=!0,y=s[I];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 g=this._getMinutesPerHour(i);g<=u?(n+=g,l?i=this.$gantt.date.add(i,g,"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 _=t-n;o=this._addMinutesUntilHourEnd(i,_),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 ui={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 CA(){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 SA=CA();function lu(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=ui.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))}lu.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 cu,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 Wa(this.$gantt,su(this.$gantt));t.id=String(ba());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=Qt(e.getConfig()):e.worktime?t=Qt(e.worktime):t=Qt(e);var r=Qt(this.defaults.fulltime.worktime);return wr(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=ui.getResourceProperty(t),Array.isArray(e[n])&&e[n].length)t.dynamic_resource_calendars?i=SA.getCalendarIdFromMultipleResources(e[n],this):r=this.getResourceCalendar(e[n]);else if(this._legacyConfig===void 0&&(this._legacyConfig=ui.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var i=ui.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=ui.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||ba(),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 Va(e,t){this.argumentsHelper=t,this.$gantt=e}Va.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 Va},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 du(e){this.$gantt=e.$gantt,this.argumentsHelper=su(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new Va(this.$gantt,this.argumentsHelper)}du.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 TA=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:Wt(e.mergeCalendars,e),createCalendar:Wt(e.createCalendar,e),addCalendar:Wt(e.addCalendar,e),getCalendar:Wt(e.getCalendar,e),getCalendars:Wt(e.getCalendars,e),getResourceCalendar:Wt(e.getResourceCalendar,e),getTaskCalendar:Wt(e.getTaskCalendar,e),deleteCalendar:Wt(e.deleteCalendar,e)}},EA={create:TA};function uu(e){var t=new lu(e),r=new du(t),i=EA.create(t,r);wr(e,i)}var fu={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 pu(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||fu,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:iu,mixin:wr,copy:Qt,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=au(r),r.date.init(),uu(r),r}function DA(e={}){let t=pu(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 yu={createCalendar:DA};var vB=3600*1e3;function gu(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:_A}=yu,fi="__replay_default__";function kA(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 hu={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},mu="__main_global__",RA={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function Iu(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 PA(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:kA(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function Au(e){let t=_A({config:{work_time:!0}});t.addCalendar({id:fi,worktime:hu}),t.addCalendar({id:mu,worktime:RA});let r=new Set(e.filter(d=>!Iu(d.worktime)).map(d=>String(d.id))),i=e.filter(d=>Iu(d.worktime));for(let d of i)t.addCalendar({id:d.id,worktime:d.worktime?PA(d.worktime):hu});let n=ru(t),o=n.getCalendar(fi),a=n.getCalendar(mu);if(!o||!a)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let s=new Set([fi]);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 vu(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 LA(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 LA(e,t){let r=[],i=new Bt;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 Kn=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=Cu(t);return this.reader.getCalendar(r??fi)}getClosestWorkTime(t){let r=`${Ka(t.task)}|${t.dir}|${t.date.getTime()}`;return ja(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:pt.HOUR}))}calculateEndDate(t){let r=`${Ka(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return ja(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${Ka(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return ja(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 ja(e,t,r){let i=e.get(t);if(i!==void 0)return i;let n=r();return e.set(t,n),n}var OA="__default__";function Cu(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function Ka(e){return Cu(e)??OA}var Yn=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&&!B(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||B(r)?null:this.activities.get(r)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,r){if(this._dirty)return;if(B(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(B(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?ki(n,o):String(r).localeCompare(String(i))};this._roots.sort(t);for(let r of this._childrenByParent.values())r.sort(t)}};var Gn=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}};function Su(e,t,r,i,n,o){return{valueId:t,id:Oi(e,t),label:r,color:i,level:n,sequence:o,children:new Map,activities:[]}}function Tu(e){let t=e.activities.length;for(let r of e.children.values())t+=Tu(r);return t}function Eu(e,t){let r=[...e.children.values()];return r.sort((i,n)=>i.valueId===Ve?1:n.valueId===Ve?-1:i.sequence!==n.sequence?i.sequence-n.sequence:i.valueId.localeCompare(n.valueId)),t===Pt.DESCENDING&&r.reverse(),r}function NA(e,t,r,i){let n=new Set(e.map(a=>String(a.id))),o=new Set(n);for(let a of n){let s=r(a);for(;s!==null;)o.add(String(s)),s=r(s)}for(let a of t)o.has(String(a.id))&&i.push({kind:We.ACTIVITY,activityId:String(a.id)})}function Du(e,t,r,i,n){if(n.push({kind:We.GROUP,id:e.id,label:e.label,level:e.level,color:e.color,activityCount:Tu(e)}),!t.collapsedIds.has(e.id)){for(let o of Eu(e,t.direction))Du(o,t,r,i,n);if(e.activities.length!==0){if(t.includeWbs){NA(e.activities,r,i,n);return}for(let o of e.activities)n.push({kind:We.ACTIVITY,activityId:String(o.id)})}}}function _u(e){let t=e.activitiesInVisualOrder.filter(a=>e.isVisible(a.id));if(e.group===null||e.catalog===null)return t.map(a=>({kind:We.ACTIVITY,activityId:String(a.id)}));let{group:r,catalog:i}=e,n=Su(r.attributeKey,"","",null,-1,0);for(let a of t){let s=i.assignmentByActivityId.get(String(a.id)),c=s===void 0?[Ve]:Ps(i,s,r.depth),l=n;c.forEach((d,u)=>{let f=l.children.get(d);if(f===void 0){let p=i.valueById.get(d);f=Su(r.attributeKey,d,p?.label??(d===Ve?Pi:d),p?.color??null,u,p?.sequence??Number.MAX_SAFE_INTEGER),l.children.set(d,f)}l=f}),l.activities.push(a)}let o=[];for(let a of Eu(n,r.direction))Du(a,r,e.activitiesInVisualOrder,e.parentOf,o);return o}var $n=class e{catalogs=new Map;group=null;getCatalog(t){return this.catalogs.get(t)??null}getCatalogMap(){return this.catalogs}setCatalogs(t){let r=new Map;for(let i of t)r.set(i.key,ks(i));this.catalogs=r}getGroup(){return this.group}setGroup(t){this.group=t}clone(){let t=new e;return t.catalogs=new Map(this.catalogs),t.group=this.group===null?null:w(this.group),t}};var Fr=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,visualRows:null,orderComparator:null};_writeCapture=new Tn;_viewState=new Gn;_viewAttributes=new $n;_filterProjection=null;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_calendar;_flags;_calendarSnapshot;constructor(t,r=()=>null){this._buildOrderComparator=r,this._calendarSnapshot=w(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 Kn(Au(this._calendarSnapshot)),this._flags=wA(t),this._hierarchy=new Yn(this._activities),this._hierarchy.rebuild()}fork(){let t=new e({activities:this.getAllActivities().map(ue),links:this.getAllLinks().map(r=>({...r})),calendars:w(this._calendarSnapshot)},this._buildOrderComparator);return t._viewState.restore(w(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,w(i)])),t._progressFallback=new Map(this._progressFallback),t._flags=w(this._flags),t._filterProjection=w(this._filterProjection),t._viewAttributes=this._viewAttributes.clone(),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=Ws(this).map(t=>String(t.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null,this.invalidateVisualRows()}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){this._captureViewStateOnce();let i=this._viewState.setVisible(String(t),r);return i&&this.invalidateVisualRows(),i}getActiveFilter(){return this._viewState.getActiveFilter()}setActiveFilter(t){this._captureViewStateOnce(),this._viewState.setActiveFilter(t),this._filterProjection=null,this.invalidateVisualRows()}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._viewAttributes.getCatalogMap()),this._cache.orderComparator)}invalidateDerivedOrder(){this._cache.orderComparator=null,this._cache.visualOrderIds=null,this.invalidateVisualRows()}getViewAttributeCatalogMap(){return this._viewAttributes.getCatalogMap()}setViewAttributeCatalogs(t){this._viewAttributes.setCatalogs(t),this.invalidateDerivedOrder()}getGroup(){return this._viewAttributes.getGroup()}setGroup(t){this._viewAttributes.setGroup(t),this.invalidateVisualRows()}invalidateVisualRows(){this._cache.visualRows=null}getVisualRows(){if(this._cache.visualRows)return this._cache.visualRows;let t=this._viewAttributes.getGroup(),r=t===null?null:this._viewAttributes.getCatalog(t.attributeKey),i=[];for(let n of this.getVisualOrderIds()){let o=this.getActivity(n);o!==null&&i.push(o)}return this._cache.visualRows=_u({activitiesInVisualOrder:i,isVisible:n=>this.isVisible(n),parentOf:n=>this.getParentId(n),group:t,catalog:r}),this._cache.visualRows}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))??ku}getIncomingLinkIds(t){return this._incoming.get(String(t))??ku}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,Ga(n,r),r===F.PARENT&&this._hierarchy.markDirty(),Ya(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,eu(r,i)),Ga(n,r),r===F.PARENT&&this._hierarchy.markDirty(),Ya(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)),Ga(i,o),o===F.PARENT&&(n=!0),Ya(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){Ru(this._outgoing,String(t.source),t.id),Ru(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),$a(r,t.id));let i=this._incoming.get(String(t.target));i&&this._incoming.set(String(t.target),$a(i,t.id))}_removeLinkRef(t,r,i){let n=t.get(r);n&&t.set(r,$a(n,i))}_insertLinkRefInOrder(t,r,i){let n=new Set;for(let s of this._links.keys()){if(String(s)===String(i))break;n.add(String(s))}let o=[...t.get(r)??[]],a=o.findIndex(s=>!n.has(String(s)));o.splice(a<0?o.length:a,0,i),t.set(r,o)}setLinkField(t,r,i){let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),n[r]=i)}setLinkEndpoints(t,r,i){let n=this.getLink(t);if(!n)return;let o=String(n.source)!==String(r),a=String(n.target)!==String(i);!o&&!a||(this._writeCapture.noteLinkField(String(t),n),o&&(this._removeLinkRef(this._outgoing,String(n.source),n.id),n.source=r,this._insertLinkRefInOrder(this._outgoing,String(r),n.id)),a&&(this._removeLinkRef(this._incoming,String(n.target),n.id),n.target=i,this._insertLinkRefInOrder(this._incoming,String(i),n.id)))}setLinkFieldDynamic(t,r,i){let n=this.getLink(t);if(n){if(r===xt.SOURCE){this.setLinkEndpoints(t,String(i),n.target);return}if(r===xt.TARGET){this.setLinkEndpoints(t,n.source,String(i));return}bA(r)&&(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===vt.LINK_ADD&&this._detachLink(r.linkId)}_undoInserts(t){for(let r of t)r.kind===vt.INSERT&&this._activities.delete(r.activityId)}_reInsertRemovedActivities(t){for(let r of t)r.kind===vt.REMOVE&&this._activities.set(r.activityId,r.before)}_reAddRemovedLinks(t){for(let r of t)r.kind===vt.LINK_REMOVE&&this._attachLink(r.before)}_restoreLinkFields(t){for(let r of t){if(r.kind!==vt.LINK_FIELD)continue;let i=this._links.get(r.linkId);if(i){this.setLinkEndpoints(r.linkId,r.before.source,r.before.target);for(let n of Object.keys(i))Object.hasOwn(r.before,n)||Reflect.deleteProperty(i,n);Object.assign(i,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))}},ku=[];function bA(e){return e===xt.LAG||e===xt.TYPE||e===xt.FREE_SLACK_HOURS||e===xt.IS_CRITICAL}function Ya(e){return e===F.PARENT||e===F.CORRELATIVE_ID}function Ga(e,t){t!==F.START_DATE&&t!==F.END_DATE&&t!==F.TYPE||(e.calendarDuration=ie(e))}function $a(e,t){return e.filter(r=>String(r)!==String(t))}function Ru(e,t,r){let i=e.get(t);i?i.push(r):e.set(t,[r])}function wA(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 za(e,t){let r=e.getActivity(t);return r?w(r):null}function Pu(e){return e.getAllActivities().map(w)}function Lu(e){return e.getAllIds().map(String)}function Ou(e,t){e.forEachActivity((r,i)=>t(i))}function Nu(e,t){let r=t==="0"?qa(e,"0"):e.getChildren(t),i=[];for(let n of r){let o=e.getActivity(n);o&&i.push(w(o))}return i.sort((n,o)=>(n.correlativeId??0)-(o.correlativeId??0)),i}function qa(e,t){return jt(t,e)}function bu(e){return e.checkedIds().map(String)}function wu(e,t){if(t==="0"){let r=!1;return e.forEachActivity(i=>{r||=B(i.parentId)}),r}return e.getChildren(t).length>0}function Ja(e,t){let r=e.getLink(t);return r?Ut(r):null}function Fu(e){return e.getAllLinks().map(t=>Ut(t))}function zn(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function FA(e){return e.reduce((t,r)=>zn(r)<zn(t)?r:t)}function xA(e){return e.reduce((t,r)=>zn(r)>zn(t)?r:t)}function MA(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function xu(e){let t=[...e].find(o=>o.is_default);if(!t)return null;let r=MA(t);if(r.length===0)return null;let i=r.map(o=>o.split("-")[0]),n=r.map(o=>o.split("-")[1]);return{startHour:FA(i),endHour:xA(n)}}function Xa(e,t){return{calendars:e.calendarReader,hierarchy:vu(e),activityReader:gu(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay}}function Mu(e){return er(e)}var UA=new Set(["freeSlackHours","isCritical"]);function BA(e,t){let r=Object.fromEntries(Object.entries(e.fields??{}).filter(([i])=>!t.has(i)));return e.kind===b.UPDATED&&Object.keys(r).length===0?null:{...e,...e.fields===void 0?{}:{fields:r},after:null}}function Wu(e){let t=e.activities.map(n=>({...n,after:null})),r=e.links.map(n=>BA(n,UA)).filter(n=>n!==null),i=e.source.kind===me?{...e.source,items:[],links:[]}:e.source;return w({...e,source:i,activities:t,links:r})}function Za(e,t,r,i,n,o,a){return{changeSet:e,beforeSnap:t,beforeLinks:Uu(r),afterSnap:i,afterLinks:Uu(n),progressFallbackBefore:o,progressFallbackAfter:a}}function Uu(e){if(e)return new Map(Array.from(e,([t,r])=>[t,{...r,freeSlackHours:null,isCritical:!1}]))}function Vu(e,t){let r=new Map,i=new Map;for(let n of t.activities){if(n.kind!==b.CREATED)continue;let o=e.getActivity(String(n.id));o&&r.set(String(n.id),it(o))}for(let n of t.links){if(n.kind===b.DELETED)continue;let o=e.getLink(String(n.id));o&&i.set(String(n.id),{...o})}return{afterSnap:r,afterLinks:i}}function ju(e){return e.kind!==h.INLINE_EDIT||!si.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function Bu(e){return e.changeSet.activities.length===1&&e.changeSet.activities[0]?.kind===b.UPDATED&&e.changeSet.links.length===0&&!e.beforeSnap?.size&&!e.afterSnap?.size}function Ku(e,t){if(!Bu(e)||!Bu(t))return!1;let r=e.changeSet.activities[0],i=t.changeSet.activities[0];return!!r&&!!i&&String(r.id)===String(i.id)}function Yu(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 Za(s)}var xr={RECORD:"record",SKIP:"skip",CHECKPOINT_ON_SUCCESS:"checkpoint-on-success"},ft={BEFORE:"before",AFTER:"after"};function Gu(e){return e.kind===h.PERSISTENCE_ACKNOWLEDGE?xr.CHECKPOINT_ON_SUCCESS:e.kind===h.SIR_SYNC||e.kind===h.CALENDAR_RECONCILE||e.kind===h.ACTIVITY_LOOKAHEAD_SYNC||e.kind===h.BASELINE_APPLY||e.kind===h.PONDERATOR_CRITERION_SET||e.kind===h.STATUS_CRITERIA_SET||e.kind===h.ACTIVITY_CLIPBOARD_CLEAR||e.kind===h.ACTIVITY_COPY||e.kind===h.SELECTION_TOGGLE||e.kind===h.SELECTION_REPLACE||e.kind===h.VISIBILITY_SET||e.kind===h.FILTER_SET||e.kind===h.SORT_SET||e.kind===h.VIEW_ATTRIBUTES_SET||e.kind===h.GROUP_SET?xr.SKIP:xr.RECORD}function Qa(e){for(let t of e.changeSet.activities)if(t.kind===b.CREATED||t.kind===b.DELETED||t.kind===b.UPDATED&&t.fields&&D.CUSTOM_ID in t.fields)return!0;return!1}function ts(e,t,r){let i=[],n=[];for(let a of t.changeSet.activities){let s=String(a.id);if(a.kind===b.UPDATED){let c=e.getActivity(s);i.push({id:s,kind:b.UPDATED,fields:Hu(a.fields,r),after:c?it(c):null})}else if(a.kind===b.DELETED)if(r===ft.BEFORE){let c=e.getActivity(s);i.push({id:s,kind:b.CREATED,after:c?it(c):null})}else i.push({id:s,kind:b.DELETED,after:null});else if(r===ft.BEFORE)i.push({id:s,kind:b.DELETED,after:null});else{let c=e.getActivity(s);i.push({id:s,kind:b.CREATED,after:c?it(c):null})}}for(let a of t.changeSet.links){let s=String(a.id);if(a.kind===b.UPDATED){let c=e.getLink(s);n.push({id:s,kind:b.UPDATED,fields:Hu(a.fields,r),after:c?Ut(c):null})}else if(a.kind===b.DELETED)if(r===ft.BEFORE){let c=e.getLink(s);n.push({id:s,kind:b.CREATED,after:c?Ut(c):null})}else n.push({id:s,kind:b.DELETED,after:null});else if(r===ft.BEFORE)n.push({id:s,kind:b.DELETED,after:null});else{let c=e.getLink(s);n.push({id:s,kind:b.CREATED,after:c?Ut(c):null})}}let o=(t.changeSet.viewState??[]).map(a=>r===ft.BEFORE?HA(a):a);return{source:{kind:r===ft.BEFORE?ne.UNDO:ne.REDO},activities:i,links:n,calendars:[],trackingEvents:[],effects:[],viewState:o}}function Hu(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([r,i])=>[r,t===ft.BEFORE?{before:w(i.after),after:w(i.before)}:{before:w(i.before),after:w(i.after)}]))}function HA(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 es(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function $u(e,t){qu(e,t,ft.BEFORE)}function zu(e,t){qu(e,t,ft.AFTER)}function qu(e,t,r){let i=t.changeSet;for(let o of i.activities)if(o.kind===b.UPDATED){if(!o.fields)continue;for(let[a,s]of Object.entries(o.fields))Tt(e,o.id,a,r===ft.BEFORE?s.before:s.after)}else if(o.kind===b.DELETED)if(r===ft.BEFORE){let a=t.beforeSnap?.get(String(o.id));if(!a)throw new Error(`undo: missing beforeSnap for resurrecting activity ${o.id}`);e.addActivity(it(a))}else e.removeActivity(String(o.id));else if(r===ft.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(it(a))}for(let o of i.links)if(o.kind===b.UPDATED){if(!o.fields)continue;let a=e.getLink(String(o.id)),s=o.fields[xt.SOURCE],c=o.fields[xt.TARGET];a&&(s||c)&&e.setLinkEndpoints(String(o.id),String(s?r===ft.BEFORE?s.before:s.after:a.source),String(c?r===ft.BEFORE?c.before:c.after:a.target));for(let[l,d]of Object.entries(o.fields))l===xt.SOURCE||l===xt.TARGET||tl(e,String(o.id),l,r===ft.BEFORE?d.before:d.after)}else if(o.kind===b.DELETED)if(r===ft.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===ft.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===ft.BEFORE?o.checked.before:o.checked.after),o.visible&&e.setVisible(o.activityId,r===ft.BEFORE?o.visible.before:o.visible.after);let n=r===ft.BEFORE?t.progressFallbackBefore:t.progressFallbackAfter;for(let[o,a]of n??[])e.setProgressFallback(o,a)}var WA=100,VA=600,qn=class e{constructor(t=WA){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];sequence=0;_lastKey=null;_lastTime=0;fork(){let t=new e(this.maxDepth);return t.undoStack.push(...w(this.undoStack)),t.redoStack.push(...w(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<=VA&&n!==void 0&&Ku(n.entry,t)?(n.entry=Yu(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 jA=["parentId","correlativeId"];function Xu(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===b.CREATED){i(o);continue}if(n.kind===b.DELETED){let c=n.fields;c&&"parentId"in c&&r.add(Ju(c.parentId?.before));continue}let a=n.fields;!a||!jA.some(c=>c in a)||(i(o),"parentId"in a&&r.add(Ju(a.parentId?.before)))}return r}function Ju(e){return e==null?"0":String(e)}function KA(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function YA(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function Zu(e){return{id:String(e.id),worktime:YA(e.worktime)}}function Jn(e,t,r,i=[]){let n=t.map(KA),o=[...r.map(Zu),...i.map(Zu)];return{activities:[...e],links:n,calendars:o}}var M={TRACKED:"tracked",IGNORED:"ignored"};var Qu={id:M.IGNORED,proplannerId:M.IGNORED,parentId:M.TRACKED,name:M.TRACKED,description:M.TRACKED,type:M.TRACKED,startDate:M.TRACKED,endDate:M.TRACKED,durationHours:M.TRACKED,constraintType:M.TRACKED,constraintDate:M.TRACKED,autoScheduling:M.TRACKED,calendarId:M.TRACKED,assignedDefaultCalendar:M.IGNORED,dateOrigin:M.TRACKED,progress:M.TRACKED,cost:M.TRACKED,usedCost:M.TRACKED,realCost:M.TRACKED,workHours:M.TRACKED,realWorkHours:M.TRACKED,ponderator:M.TRACKED,hasCustomPonderator:M.TRACKED,correlativeId:M.TRACKED,uniqueCorrelativeId:M.TRACKED,customId:M.TRACKED,subcontractId:M.TRACKED,isLookahead:M.TRACKED,hasLookaheadTasks:M.IGNORED,newActivityIds:M.TRACKED,hasNewActivities:M.TRACKED,isNewActivity:M.IGNORED,pendingRequestIds:M.IGNORED,responsableIds:M.TRACKED,tagIds:M.TRACKED,baselinePoints:M.IGNORED,baselineSnapshot:M.IGNORED,recursiveDurationHours:M.IGNORED,isCritical:M.IGNORED,freeSlackHours:M.IGNORED,calendarDuration:M.IGNORED,expectedProgress:M.IGNORED,expectedProgressBaseline:M.IGNORED,status:M.IGNORED,criticalPath:M.IGNORED},tf=Object.keys(Qu).filter(e=>Qu[e]===M.TRACKED),ef=new Set(["startDate","endDate","constraintDate","dateOrigin"]),rf=new Set(["newActivityIds","responsableIds","tagIds"]);function nf(e){let t=tf.map(r=>[r,GA(r,e[r])]);return Object.fromEntries(t)}function GA(e,t){return ef.has(e)?t instanceof Date?new Date(t):null:rf.has(e)?Array.isArray(t)?[...t]:[]:t}function pi(e,t){return rs(e,t).length>0}function rs(e,t){return tf.filter(r=>!$A(r,e[r],t[r]))}function $A(e,t,r){return ef.has(e)?zA(t,r):rf.has(e)?qA(t,r):(t??null)===(r??null)}function zA(e,t){let r=e instanceof Date?e.getTime():null,i=t instanceof Date?t.getTime():null;return r===i}function qA(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 of={id:M.IGNORED,source:M.TRACKED,target:M.TRACKED,type:M.TRACKED,lag:M.TRACKED,freeSlackHours:M.IGNORED,isCritical:M.IGNORED,ganttId:M.IGNORED,sectorId:M.IGNORED,proplannerId:M.IGNORED},JA=Object.keys(of).filter(e=>of[e]===M.TRACKED);function Xn(e,t){return JA.some(r=>e[r]!==t[r])}function af(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?Xn(n,i):!1})}function te(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 sf(e,t){for(let r of e)te(r.proplannerId);for(let r of t)te(r.proplannerId)}var Zn=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,w(i));for(let[r,i]of this.activitiesAtLastSave)t.activitiesAtLastSave.set(r,w(i));return t}init(t,r){if(this.trackingEnabled){sf(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(sf(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(!te(r.proplannerId)){this.dirtyActivityIds.add(i);continue}let n=nf(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}}),pi(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(!te(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)||!te(r.proplannerId)||i===void 0||pi(r,i.persistable)}linkIsDirty(t,r){let i=this.linksAtLastSave.get(t);return r===null?i!==void 0:!te(r.proplannerId)||i===void 0||Xn(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)||!te(s.proplannerId)||pi(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&&!te(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&&!te(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||!te(n.proplannerId))continue;let o=this.activitiesAtLastSave.get(i);(o===void 0||this.initialCalendarRepairIds.has(i)||pi(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=rs(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||!te(n.proplannerId))continue;let o=this.linksAtLastSave.get(i);(o===void 0||Xn(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 cf=1440*60*1e3,lf=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/,Qn=7,is=[!1,!0,!0,!0,!0,!0,!1],df=new Set(["1","true"]),ns=It.DURATION,uf=v.ASAP,ff={ASAP:v.ASAP,ALAP:v.ALAP,SNET:v.SNET,SNLT:v.SNLT,FNET:v.FNET,FNLT:v.FNLT,MSO:v.MSO,MFO:v.MFO,"AS SOON AS POSSIBLE":v.ASAP,"AS LATE AS POSSIBLE":v.ALAP,"START NO EARLIER THAN":v.SNET,"START NO LATER THAN":v.SNLT,"FINISH NO EARLIER THAN":v.FNET,"FINISH NO LATER THAN":v.FNLT,"MUST START ON":v.MSO,"MUST FINISH ON":v.MFO};function pf(e,t){let r=[],i=e.map(o=>{let a=av(o,t);return o.should_be_showed===!1&&r.push(a.id),a});cv(i);let n=new Set(i.map(o=>o.id));return lv(i,n,t.reporter,t.recordDiagnostic),{activities:i,activityIds:n,hiddenIds:r}}function XA(e,t,r,i){if(!e)return null;let n=ff[e.toUpperCase()];return n===void 0?(r(Nt.UNKNOWN_CONSTRAINT,i),t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),uf):n}function ZA(e,t,r){let i=XA(e.constraint,t,r,String(e.unique_id)),o=i!==v.ASAP&&i!==v.ALAP&&e.constraint_date?fe(e.constraint_date):null;return{constraintType:i,constraintDate:o}}function QA(e,t,r){if(e==null)return r;let i=String(e);return t.has(i)?i:r}function tv(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 ev(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function os(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)ev(r)&&t.push(String(r.id));return t}function rv(e){return e==="0"?null:String(e)}function iv(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 nv(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 ov(e,t,r,i,n){return Array.isArray(e)?e.map(o=>Hn(o,t,{record:r,sampleId:i},n)).filter(o=>o!==null):[]}function av(e,t){let r=QA(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),i=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),n=Number(e.progress),{constraintType:o,constraintDate:a}=ZA(e,t.reporter,t.recordDiagnostic),s=e.type===E.MILESTONE,c=fe(e.start_date),l=s?c:fe(e.end_date),d=s?0:Number(e.duration),u=nv(e,t.reporter);return{id:String(e.unique_id),proplannerId:iv(e.id),parentId:rv(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:Ye(d,t.hoursPerDay),constraintType:o,constraintDate:a,autoScheduling:je(n),calendarId:r,assignedDefaultCalendar:r!=null&&i,dateOrigin:e.date_origin==null?null:fe(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:sv(e),subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:tv(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:os(e.pendingRequests),responsableIds:os(e.responsables),tagIds:os(e.tags),baselinePoints:ov(e.baseline_points,t.reporter,t.recordDiagnostic,String(e.unique_id),s),baselineSnapshot:null,recursiveDurationHours:Ye(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),calendarDuration:ie({type:e.type,startDate:c,endDate:l}),isCritical:u,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function sv(e){return e.has_childs?null:e.custom_id}function cv(e){let t=e.find(r=>r.correlativeId===0&&r.type===E.PROJECT);t&&(t.parentId=null)}function lv(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(Nt.ORPHAN_ACTIVITY,n.id),n.parentId=null))}function If(e,t,r,i=null){let a=(e!==void 0&&e.length>0?e:t??[]).map(c=>uv(c,i)),s=(r??[]).map(c=>fv(c,i));return{calendars:a,baseCalendars:s,knownCalendarIds:new Set(a.map(c=>c.id)),defaultCalendarId:dv(a)}}function dv(e){let t=e.find(i=>i.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function gf(e,t){let r=gv(e.working_days),{days:i,hours:n}=Iv(e,r),o=pv(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 uv(e,t){let r=e.baseDefault,i=typeof r=="boolean"?r:void 0;return gf(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:i,exceptionsSource:e.exceptiondays,exceptionRange:t})}function fv(e,t){return gf(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function pv(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let i of e){if(!i)continue;let n=yv(i.from_date,i.to_date,t);if(n.length===0)continue;let o=hv(i);if(o!==void 0)for(let a of n)r[a]=o}return Object.keys(r).length>0?r:null}function yv(e,t,r){let i=yf(e),n=yf(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+=cf;return o}function yf(e){if(typeof e!="string")return null;let t=lf.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 hv(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=mv(t);if(r.length>0)return r}}var hf=/^\d{1,2}:\d{2}$/;function mv(e){let t=[];for(let r of e){let i=Cf(r?.shift_string);if(!i)continue;if(!i.startsCsv.includes(",")&&!i.endsCsv.includes(",")){let s=i.startsCsv.trim(),c=i.endsCsv.trim();!to(s)&&!to(c)&&hf.test(s)&&hf.test(c)&&t.push(`${s}-${c}`);continue}let a=vf(i.startsCsv,i.endsCsv).find(s=>s!==null);a&&t.push(a)}return t.sort(Af),t}function mf(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 Af(e,t){return mf(e)-mf(t)}function Iv(e,t){let r=Array.from({length:7},()=>[]),i=(l,d)=>{let u=vf(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=Cf(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(Af);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 vf(e,t){let r=Array.from({length:Qn},()=>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<=Qn))return r;let a=[...r];for(let s=0;s<i.length;s+=1){let c=i[s],l=n[s];to(c)||to(l)||(a[s]=`${c}-${l}`)}return a}function Cf(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 gv(e){if(typeof e!="string")return[...is];let t=e.split(",").map(r=>r.trim());return t.length!==Qn?[...is]:t.map(r=>df.has(r))}var Av=new Set(["false","null"]);function to(e){return!e||Av.has(e)}function vv(e){if(typeof e!="string")return null;let t=pc(e);return t||(vi(e)?e:null)}function Cv(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 Tf(e,t){let r=[];for(let i of e)try{r.push(Sv(i,t.knownActivityIds,t.hoursPerDay))}catch(n){t.recordDiagnostic(Nt.INVALID_LINK,String(i.unique_id??i.id)),t.reporter.warn("[parseFromBackend] dropping invalid link",n)}return Tv(r,t.recordDiagnostic)}function Sv(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=vv(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=Cv(e.id);return{id:i,source:n,target:o,type:a,lag:Kt(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 Tv(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=Sf(i)>Sf(o),s=a?o:i;t(Nt.DUPLICATE_LINK,s.id),a&&r.set(n,i)}return[...r.values()]}function Sf(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function Ev(e){if(typeof e!="string")return ns;switch(e.toUpperCase()){case It.DURATION:return It.DURATION;case It.COST:return It.COST;case It.WORK_HOURS:return It.WORK_HOURS;default:return ns}}function Dv(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function _v(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function Ef(e){let t=Dv(e),r=_v(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:Ev(e.activity_creter),statusCriteria:Ko,ganttId:null}}function eo(e,t=yr,r=br){let i=Ef(e.sector),{calendars:n,baseCalendars:o,knownCalendarIds:a,defaultCalendarId:s}=If(e.calendars,e.sector.calendars,e.baseCalendars,kv(e.activities)),{activities:c,activityIds:l,hiddenIds:d}=pf(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:i.hoursPerDay,reporter:t,recordDiagnostic:r}),u=Tf(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 kv(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 as(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 as({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 ss(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 ss({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 cs(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 cs({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 Df(e){return!!e&&typeof e=="string"&&e.trim().length>0}function ro(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function io(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function _f(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function kf(e,t){return!t&&Df(e)}function Rf(e,t){return t&&Df(e)}function yi(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function no(e){if(!yi(e))return 0n;try{return BigInt(e)}catch{return 0n}}function Rv(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!yi(t))return r;let i=t.length;return r.padStart(i,"0")}function $t(e,t){let r=no(e),i=no(t),n=r+i;return Rv(n,e)}function oo(e,t){let r=no(e),i=no(t);return r<i?-1:r>i?1:0}function ao(e,t){return oo(e,t)<=0?e:t}function so(e,t){return oo(e,t)>=0?e:t}function Pf(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>ao(t,r))}function Lf(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>so(t,r))}var ye={PARENT_CONVERSION:"parentConversion",PASTE_REFERENCE:"pasteReference",NO_CONTEXT:"noContext"};function Of(e){return{prefix:e,baseSuffix:null}}function Nf(e,t){let r=io(e);return{prefix:ro(e),baseSuffix:$t(r,t)}}function bf(e){return{prefix:e,baseSuffix:null}}function wf(e,t){return kf(e,t)?ye.PARENT_CONVERSION:Rf(e,t)?ye.PASTE_REFERENCE:ye.NO_CONTEXT}function Ff(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var co=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?Ff(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=Pf(i),r.max=Lf(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,Ff(i));for(let r of this.processedIds)t.processedIds.add(r);return t}extractPrefix(t){return ro(t)}extractSuffix(t){return io(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=ao(r,i.min),i.max=so(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=ao(i,n.min),n.max=so(i,n.max),n.quantity+=1,this._recalculateNext(r))}else this.prefixMap.set(r,{min:i,max:i,next:$t(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}${$t(r.max,this.suffixIncrement)}`.length>20}_suffixForUnknownPrefix(t,r){let i=r&&yi(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(;oo(i,r.max)<0;){if(`${t}${i}`.length>20)return null;if(!r.usedSuffixes.has(i))return i;i=$t(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||!yi(r)){let s=$t(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=$t(o,n)}let a=$t(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,$t(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=_f(r),o=wf(n,i),{prefix:a,baseSuffix:s}=this._applyGenerationStrategy(o,n),c=null;if(o===ye.PARENT_CONVERSION&&this.prefixMap.has(a)){this._ensureFreshBounds(a);let f=this.prefixMap.get(a).max;c=$t(f,this.suffixIncrement)}o===ye.PARENT_CONVERSION&&this.releaseCustomId(n);let l=o===ye.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 ye.PARENT_CONVERSION:return Of(this.defaultPrefix);case ye.PASTE_REFERENCE:return Nf(r,this.suffixIncrement);default:return bf(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=$t(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 Pv=1,Lv=-1;function Ov(e,t){if(e===void 0&&t===void 0)return 0;if(e===void 0)return Pv;if(t===void 0)return Lv;let r=Math.min(e.length,t.length);for(let i=0;i<r;i+=1){let n=(e[i]??0)-(t[i]??0);if(n!==0)return n}return e.length-t.length}function xf(e,t,r,i){let n=r.assignmentByActivityId.get(String(e.id)),o=r.assignmentByActivityId.get(String(t.id)),a=Ov(n===void 0?void 0:r.sequencePathByValueId.get(n),o===void 0?void 0:r.sequencePathByValueId.get(o));return i===Pt.DESCENDING?-a:a}var Nv=1,bv=-1;function wv(e,t){return!e&&!t?null:e&&t?0:e?Nv:bv}function Mf(e){return e==null}function Uf(e,t){let r=t.indexOf(String(e));return r===-1?t.length:r}function Fv(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 xv(e,t,r){if(ur(e)){let n=r.get(e.key);return n===void 0?null:(o,a)=>xf(o,a,n,e.direction)}let i=Ie(e.field);return i===null?null:(n,o)=>{let a=i.extract(n,t),s=i.extract(o,t),c=wv(Mf(a),Mf(s));if(c!==null)return c;let l=i.valueKind===L.ENUM?Uf(a,i.order)-Uf(s,i.order):Fv(a,s,t.locale);return e.direction===Pt.DESCENDING?-l:l}}function Bf(e,t,r=Ti){let i=e.rules.map(n=>xv(n,t,r)).filter(n=>n!==null);return i.length===0?null:(n,o)=>{for(let a of i){let s=a(n,o);if(s!==0)return s}return 0}}function Hf(e){let t=[];e.forEachActivity((r,i)=>{r.type===E.PROJECT&&e.getChildren(String(i)).length===0&&t.push(String(i))});for(let r of t)e.setActivityField(r,F.TYPE,fr),Mv(e,r)}function Mv(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:Y.FUTURE,task:r});if(n.getTime()===r.startDate.getTime())return;let o=e.calculateEndDate({startDate:n,durationHours:r.durationHours,task:r});e.setActivityField(t,F.START_DATE,n),e.setActivityField(t,F.END_DATE,o)}function Wf(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?Mt(o.workHours,o.progress):a.reduce((c,l)=>c+i(String(l)),0);return e.setActivityField(n,F.REAL_WORK_HOURS,s),r.push(n),s};for(let n of t)i(n);return r}async function Vf(e){let{state:t,sector:r,scheduler:i,skipAutoSchedule:n,now:o}=e;if(_t(t),r.updateDurationForPrimaveraEndDate&&Bv(t),Hv(t),Wf(t),n){Jr(t),o&&(Xe(t,o),pe(t,r.statusCriteria));return}let a=await i.schedule({});$r(t,a),Wv(t),Uv(t),await mr(t,void 0,!1),Jr(t),o&&(Xe(t,o),pe(t,r.statusCriteria))}function Uv(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=ie(t))})}function Bv(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function Hv(e){e.forEachActivity(t=>{let r=t.constraintType;if(!r||!t.constraintDate)return;let i=t.constraintDate;if(t.type===E.MILESTONE&&(i.getUTCHours()!==0||i.getUTCMinutes()!==0))return;let n=e.calendarReader.getCalendar(String(t.calendarId));n&&(t.constraintDate=de(t.constraintDate,n,r))})}function Wv(e){e.forEachActivity(t=>{if(t.type!==E.MILESTONE)return;let r=t.constraintType;if(!r||!t.constraintDate)return;let i=e.calendarReader.getCalendar(String(t.calendarId));i&&(t.constraintDate=de(t.constraintDate,i,r))})}var ee={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function jf(e){let t=e.clock??null,r=t?.()??null,i=r?on(r):null,n=e.reporter??yr,o=Ud(),a=eo({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},n,o.record),s=a.sector;s.statusCriteria=mn(e.statusCriteria),s.ganttId=e.ganttId??null;let c=a.calendars,l=a.baseCalendars??[],d=Jn(a.activities,a.links,a.calendars,l),u=(O,T)=>Bf(O,He(s.hoursPerDay),T),f=new Fr(d,u);f.hydrateViewState({hiddenIds:a.viewStateSeed.hiddenIds});let p=new hr(f,n);Hf(f);let y=as({knownIds:a.activities.map(O=>O.id)}),I=ss({seed:r?.getTime()??0,knownIds:a.links.map(O=>O.id)}),g=cs({knownIds:a.activities.map(O=>O.uniqueCorrelativeId)}),_=new co({defaultPrefix:s.customIdPrefix,suffixIncrement:s.customIdIncrement});if(_.populateFromActivities(a.activities),e.baselinePoints&&e.baselinePoints.length>0){let O=l.find(T=>T.baseDefault)?.id??null;Wn(f,e.baselinePoints,i,n,O,o.record)}let k=Vf({state:f,sector:s,scheduler:p,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:i??void 0});return{sector:s,state:f,scheduler:p,activityIdGen:y,linkIdGen:I,uidGen:g,customIdTracker:_,calendars:c,baseCalendars:l,clock:t,reporter:n,loadDiagnostics:o.snapshot,initPromise:k}}function Mr(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(Mr)];if(e instanceof Map)return["map",Array.from(e,([t,r])=>[Mr(t),Mr(r)]).sort((t,r)=>JSON.stringify(t).localeCompare(JSON.stringify(r)))];if(e instanceof Set)return["set",Array.from(e,Mr).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,Mr(r)])];throw new TypeError(`Unsupported canonical value: ${typeof e}`)}function or(e){return JSON.stringify(Mr(e))}function ls(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:b.DELETED,after:null});continue}if(s===void 0){o.push({id:a,kind:b.CREATED,after:w(c)});continue}let l=Vv(s,c);Object.keys(l).length>0&&o.push({id:a,kind:b.UPDATED,fields:l,after:w(c)})}return o}function Vv(e,t){let r={},i=[...new Set([...Object.keys(e),...Object.keys(t)])].sort();for(let n of i)or(e[n])!==or(t[n])&&(r[n]={before:w(e[n]),after:w(t[n])});return r}function jv(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 ds(e,t){let r=or(e.order)!==or(t.order);return{source:{kind:ne.INIT},activities:ls(e.activities,t.activities),links:ls(e.links,t.links),calendars:ls(e.calendars,t.calendars),trackingEvents:[],effects:[],viewState:jv(e,t),...r?{order:w(e.order)}:{}}}var Ur={MOVE:"move",RESIZE_START:"resize-start",RESIZE_END:"resize-end"},Kv=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),us=(e,t)=>e===null?t:Math.min(e,t),fs=(e,t)=>e===null?t:Math.max(e,t);function Yf(e,t,r){let i=[...new Set(t.kind===Ur.MOVE?t.activityIds.map(String):[String(t.activityId)])];if(i.length===0)throw new Error("[ScheduleCore] date gesture has no participants");let n=Yv(e,t,i);return Gv(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=zv(s,a),l=qv(s,a);if(c===null||l===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(o)}`);return{startTimeMs:c,endTimeMs:l}}}}function Yv(e,t,r){let i=new Map,n=t.kind===Ur.MOVE?String(t.anchorActivityId):null,o=n===null?null:Kf(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=Kf(e,a);if(t.kind===Ur.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===Ur.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 Gv(e,t,r){let i=Zr(e,new Set(t));for(let n of i){let o=Kv();for(let a of e.getChildren(n)){let s=r.get(a);if(s){$v(o,s);continue}let c=e.getActivity(a);if(!c)throw new Error(`[ScheduleCore] missing child ${a} while previewing parent ${n}`);o.constantStart=us(o.constantStart,c.startDate.getTime()),o.constantEnd=fs(o.constantEnd,c.endDate.getTime())}r.set(n,o)}}function Kf(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 $v(e,t){t.constantStart!==null&&(e.constantStart=us(e.constantStart,t.constantStart)),t.variableStartOffset!==null&&(e.variableStartOffset=us(e.variableStartOffset,t.variableStartOffset)),t.constantEnd!==null&&(e.constantEnd=fs(e.constantEnd,t.constantEnd)),t.variableEndOffset!==null&&(e.variableEndOffset=fs(e.variableEndOffset,t.variableEndOffset))}function zv(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 qv(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 ps=Symbol("ScheduleCore.fork.source");function Jv(e){return{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}function Xv(e){return e.kind===h.PERSISTENCE_ACKNOWLEDGE||e.kind===h.ACTIVITY_LOOKAHEAD_SYNC&&e.acknowledgePersistedLookahead===!0}function Zv(e){for(let t of e.activities)if(t.kind===b.DELETED||t.kind===b.UPDATED&&t.fields!==void 0&&"parentId"in t.fields)return!0;return!1}function Qv(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 tC(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 Br=class e{activities;links;calendars;selection;view;baselines;impactRequests;persistence;history;projection;criticalPath;diagnostics;_activityClipboard={value:null};_status=ee.READY;coreRuntime;_isFork;_undo=new qn;_opQueue=Promise.resolve();_scheduleRevision=0;_stateRevision=0;_pendingScheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){if(Object.assign(this,As(this)),ps in t){this._isFork=!0;let n=t[ps],o=n.coreRuntime.state.fork();this.coreRuntime={state:o,scheduler:new hr(o,n.coreRuntime.reporter),sector:w(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,w(s)])),baseCalendars:w(n.coreRuntime.baseCalendars),clock:n.coreRuntime.clock,reporter:n.coreRuntime.reporter,loadDiagnostics:n.coreRuntime.loadDiagnostics},this._activityClipboard.value=w(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=jf(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!==ee.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({[ps]:this})))}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return w(this.coreRuntime.sector)}getLoadDiagnostics(){return this.assertReady(),this.coreRuntime.loadDiagnostics()}getActivityView(t){return this.assertReady(),za(this.coreRuntime.state,t)}calculateCalendarEndDate(t){this.assertReady();let r=this.coreRuntime.state.getActivity(t.activityId);return r?this.coreRuntime.state.calculateEndDate({startDate:t.startDate,durationHours:t.durationHours,task:r}):null}calculateCalendarDuration(t){this.assertReady();let r=this.coreRuntime.state.getActivity(t.activityId);return r?this.coreRuntime.state.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:r}):null}getClosestCalendarWorkTime(t){this.assertReady();let r=this.coreRuntime.state.getActivity(t.activityId);return r?this.coreRuntime.state.getClosestWorkTime({date:t.date,dir:t.direction,task:r}):null}getProgressEditability(t){this.assertReady();let r=za(this.coreRuntime.state,t);if(!r)return null;let i=Xa(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat});return sn.canEdit(r,i.hierarchy)}createDateGesturePreview(t){this.assertReady();let r=this._scheduleRevision;return Yf(this.coreRuntime.state,t,()=>{if(this.assertReady(),this._scheduleRevision!==r)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),Pu(this.coreRuntime.state)}getIndentTargetParentIds(t){this.assertReady();let r=Bn(t.map(i=>String(i)),this.coreRuntime.state);return[...new Set(r.allowedMoves.map(i=>String(i.newParentId)))]}getChildrenView(t){return this.assertReady(),Nu(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),Ja(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=Ja(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(),Fu(this.coreRuntime.state)}auditEffectiveGraph(){this.assertReady();let t=this.coreRuntime.state,r=t.getAllLinks(),i=qr(t,r),n=Vi(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?w(i[r]):null}getAllIds(){return this.assertReady(),Lu(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),Ou(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),qa(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),bu(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(),w(this.coreRuntime.state.getActiveFilter())}getActiveOrder(){return this.assertReady(),w(this.coreRuntime.state.getActiveOrder())}getVisualOrderIds(){return this.assertReady(),[...this.coreRuntime.state.getVisualOrderIds()]}getVisualRows(){return this.assertReady(),[...this.coreRuntime.state.getVisualRows()]}getActiveGroup(){return this.assertReady(),w(this.coreRuntime.state.getGroup())}hasChild(t){return this.assertReady(),wu(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let r=this.coreRuntime.calendars.get(t);return r?w(r):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),t=>w(t))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(t=>w(t))}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),xu(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(t=>this.coreRuntime.state.getLink(t)).map(w)}getNewLinks(){return this.assertReady(),this._saveTracker.newLinks(t=>this.coreRuntime.state.getLink(t)).map(w)}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(t=>this.coreRuntime.state.getActivity(t)).map(w)}getModifiedActivityFields(){return this.assertReady(),w(this._saveTracker.modifiedActivityFields(t=>this.coreRuntime.state.getActivity(t)))}getNewActivities(){return this.assertReady(),this._saveTracker.newActivities(t=>this.coreRuntime.state.getActivity(t)).map(w)}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 or({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){return this.assertReady(),t.assertReady(),ds(this._snapshotProjection(),t._snapshotProjection())}_snapshotProjection(){return{activities:this.getAllActivitiesView(),links:this.getAllLinksView(),calendars:this.getAllCalendars(),selectedIds:this.getSelectedActivityIds(),hiddenIds:this.getHiddenActivityIds(),order:ge(this.coreRuntime.state)}}getDeletedActivitiesSinceLastSave(){return this.assertReady(),this._saveTracker.deletedActivities(t=>this.coreRuntime.state.getActivity(t)).map(w)}getDeletedLinksSinceLastSave(){return this.assertReady(),this._saveTracker.deletedLinks(t=>this.coreRuntime.state.getLink(t)).map(w)}_enqueue(t){let r=this._opQueue.then(t,t);return this._opQueue=r.then(()=>{},()=>{}),r}_beginScheduleMutation(t){return Sn(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 dispatchMany(t,r={}){let i=t.some(Sn)?this._admitScheduleMutation():!1;return this._enqueue(()=>this._dispatchManyInner(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(),Pa(t,{adapter:this.coreRuntime.state,stateRevision:this._stateRevision})}applyLookaheadConversion(t){return this.dispatch({...t,kind:h.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 _dispatchManyInner(t,r,i){let n=this._snapshotProjection(),o={...r,skipAutoSchedule:!0,skipCriticalPath:!0},a=[],s=[],c=[],l=!1,d=!1,u,f=!1,p=null,y=!1,I=!1;try{for(let g of t){if(g.kind===h.SCHEDULE_AUTO_SCHEDULE){if(g.activityId!==void 0&&!this.coreRuntime.state.activityExists(g.activityId)){a.push({ok:!1,reason:C.ACTIVITY_NOT_FOUND});continue}let k=Jv(g);a.push({ok:!0,changes:k}),s.push(k),c.push(g),d=!0,g.activityId===void 0||u!==void 0&&u!==g.activityId?f=!0:u=g.activityId;continue}let _=await this._runDispatch(g,o,!0);a.push(_.result),_.result.ok&&(s.push(_.result.changes),c.push(g)),_.changedState&&(l=!0,d=!0,f=!0)}if(d){let g=f||u===void 0?{kind:h.SCHEDULE_AUTO_SCHEDULE}:{kind:h.SCHEDULE_AUTO_SCHEDULE,activityId:u},_=await this._runDispatch(g,r,!0);_.result.ok&&(p=_.result.changes,s.push(_.result.changes),y=r.skipAutoSchedule!==!0),l||=_.changedState}return l&&this._recordScheduleMutation(p!==null&&r.skipAutoSchedule!==!0&&r.skipCriticalPath!==!0),I=!0,{results:a,autoScheduled:y,changeSet:this._aggregateDispatchManyChangeSets(n,s,c)}}finally{!I&&l&&this._recordScheduleMutation(!1),this._settleScheduleMutation(i,I&&l)}}_aggregateDispatchManyChangeSets(t,r,i){if(r.length===0)return null;let n=ds(this._snapshotProjection(),t),o=r.flatMap(s=>s.effects??[]),a=r.flatMap(s=>s.warnings??[]);return{...n,source:{kind:ne.DISPATCH_MANY,actions:i},trackingEvents:r.flatMap(s=>s.trackingEvents),...o.length===0?{}:{effects:o},...a.length===0?{}:{warnings:a}}}async _runDispatch(t,r,i=!1){if(this.assertReady(),this._isFork&&Xv(t))return{result:{ok:!1,reason:C.SANDBOX_PERSISTENCE_FORBIDDEN},changedState:!1};let n=Xa(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat}),o=Gu(t),a=[this.coreRuntime.activityIdGenerator.snapshot(),this.coreRuntime.linkIdGenerator.snapshot(),this.coreRuntime.uniqueCorrelativeIdGenerator.snapshot()];this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let s,c;try{s=await tu(t,r,{adapter:this.coreRuntime.state,ctx:n,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,linkIdGen:this.coreRuntime.linkIdGenerator,isActivityIdReserved:u=>this._saveTracker.hasCheckpointActivityId(u),isLinkIdReserved:u=>this._saveTracker.hasCheckpointLinkId(u),uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,reporter:this.coreRuntime.reporter,activityClipboard:this._activityClipboard,stateRevision:this._stateRevision,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(u=>u.baseDefault)?.id??null,now:this.coreRuntime.clock?on(this.coreRuntime.clock()):null});let d=this.coreRuntime.state.peekWriteCapture()?.progressFallbackBefore;d&&d.size>0&&(c=new Map(d)),s.ok||this._rollback(a)}catch(d){throw this._rollback(a),d}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(s.ok&&o===xr.RECORD&&es(s.changes)){let d=Vu(this.coreRuntime.state,s.changes),u=c?new Map(Array.from(c.keys(),f=>[f,this.coreRuntime.state.getProgressFallback(f)])):void 0;this._undo.record(Za(Wu(s.changes),s.__beforeSnap,s.__beforeLinks,d.afterSnap,d.afterLinks,c,u),ju(t),Date.now())}if(s.ok)if(o===xr.CHECKPOINT_ON_SUCCESS){if(t.kind!==h.PERSISTENCE_ACKNOWLEDGE)throw new Error("checkpoint-on-success requires persistence acknowledge");let d=this.coreRuntime.state.getAllActivities(),u=this.coreRuntime.state.getAllLinks(),f=t.checkpoint,p=f?.historyBoundary??this._undo.capturePersistenceBoundary();this._saveTracker.acknowledge(f?.activities??d,f?.links??u,t.activities,t.links,d,u),this._undo.discardThrough(p),this._undo.applyPersistedIdentities(t.activities??[],t.links??[])}else t.kind===h.ACTIVITY_LOOKAHEAD_SYNC&&t.acknowledgePersistedLookahead===!0?(this._saveTracker.acknowledgePersistedLookahead(s.changes.activities,d=>this.coreRuntime.state.getActivity(d)),t.persistedProgress!==void 0&&this._undo.clear()):this._saveTracker.recordChanges(s.changes.activities,s.changes.links,d=>this.coreRuntime.state.getActivity(d),d=>this.coreRuntime.state.getLink(d));if(s=this._withReappliedViewState(t,s),!s.ok)return{result:s,changedState:!1};let l=es(s.changes);return l&&this._stateRevision++,Sn(t)&&l?(i||this._recordScheduleMutation(r.skipAutoSchedule!==!0&&r.skipCriticalPath!==!0&&er(t)),{result:Gf(s),changedState:!0}):{result:Gf(s),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===h.VISIBILITY_SET&&this.coreRuntime.state.setFilterProjection(null),!xl(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=Xu(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=So(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:ge(i)};let o=new Set(r);for(let s of t.activities){if(s.kind===b.DELETED)return{...t,order:ge(i)};let c=i.getParentId(s.id);o.add(c===null?"0":String(c))}let a=So(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=He(this.coreRuntime.sector.hoursPerDay),o=r.getFilterProjection(),a=tC(o,i,n),s=Zv(t)?null:Qv(t,r),c,l;if(s===null||!a){let f=_i({activities:r.getAllActivities(),parentOf:p=>r.getParentId(p),filter:i,context:n,viewAttributeCatalogs:r.getViewAttributeCatalogMap()});r.setFilterProjection(f),l=f.visibleIds,c=r.getAllIds()}else c=ws(o,s,f=>r.getParentId(f)),l=o.visibleIds;let u=Me(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===ee.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 Fr(Jn(this.coreRuntime.state.getAllActivities().map(s=>it(s)),this.coreRuntime.state.getAllLinks().map(s=>({...s})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),n=()=>!r.cancelled&&this._status!==ee.DESTROYED&&this._scheduleRevision===t&&this._pendingScheduleRevision===this._scheduleRevision,o=(async()=>{let s=await ha(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)pa(this.coreRuntime.state,l,d);for(let[l,d]of s.links)ya(this.coreRuntime.state,l,d);c=await $(this.coreRuntime.state,{source:{kind:ne.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;$u(this.coreRuntime.state,i),this._recordScheduleMutation(!1),r(!0),Qa(i)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(i),this._undo.resetCoalesce();let n=ts(this.coreRuntime.state,i,ft.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;zu(this.coreRuntime.state,r),this._recordScheduleMutation(!1),t(!0),Qa(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce();let i=ts(this.coreRuntime.state,r,ft.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=ee.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new Zn;assertReady(){if(this._status===ee.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===ee.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=ee.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",r),r}}};function Gf(e){let{__beforeSnap:t,__beforeLinks:r,...i}=e;return i}async function $f(e){let t=new Br(e);return await t.ready,t}var zf=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var qf={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 Jf=8;var Xf={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return np(eC);})();
2
2
  //# sourceMappingURL=schedule-core.global.js.map