@outbuild-company/schedule-core 1.15.9 → 1.15.11

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 qn=Object.defineProperty;var gf=Object.getOwnPropertyDescriptor;var Af=Object.getOwnPropertyNames;var vf=Object.prototype.hasOwnProperty;var Cf=(e,t)=>{for(var i in t)qn(e,i,{get:t[i],enumerable:!0})},Sf=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Af(t))!vf.call(e,n)&&n!==i&&qn(e,n,{get:()=>t[n],enumerable:!(r=gf(t,n))||r.enumerable});return e};var Tf=e=>Sf(qn({},"__esModule",{value:!0}),e);var uv={};Cf(uv,{ACTIVITY_BATCH_ACTION_KIND:()=>pe,ACTIVITY_BATCH_MODE:()=>mt,ACTIVITY_DATE_EDGE:()=>xi,ACTIVITY_FIELD:()=>At,ACTIVITY_PONDERATOR_CRITERION:()=>pt,ACTIVITY_PROGRESS_ORIGIN:()=>Jr,ACTIVITY_TYPE:()=>T,CALENDAR_UNIT:()=>ut,CHANGE_SET_SOURCE_KIND:()=>ee,COLUMN:()=>E,COMPLETED_PROGRESS:()=>Bi,CONSTRAINT_TYPE:()=>v,CONSTRAINT_TYPE_TO_LABEL:()=>yf,CONSTRAINT_WARNING_KIND:()=>We,CREATION_KIND:()=>mf,DATE_GESTURE_KIND:()=>Ni,DEFAULT_HOURS_PER_DAY:()=>hf,DISPATCH_ACTION_KIND:()=>I,DISPATCH_ACTION_KINDS:()=>ts,DISPATCH_LINK_OPERATION_KIND:()=>ot,DISPATCH_TRACK_EVENT:()=>Kt,EDIT_ALERT_KEY:()=>sc,EDIT_DENIAL_REASON:()=>zi,ENTITY_CHANGE_KIND:()=>N,FILTER_FIELD:()=>z,FILTER_LOGIC:()=>Ir,FILTER_OPERATOR:()=>W,FILTER_REJECTION_REASON:()=>Tt,FILTER_VALUE_KIND:()=>O,LINK_BATCH_OPERATION_KIND:()=>ii,LINK_CODE:()=>Dt,LINK_CODE_TO_TYPE:()=>xe,LINK_REJECTION_REASON:()=>st,LINK_RELATIONSHIP:()=>Ne,LINK_TYPE:()=>B,LINK_TYPE_CODE:()=>Fr,NEW_ACTIVITY_DEFAULTS:()=>gn,NOT_STARTED_PROGRESS:()=>Rs,ORDER_DIRECTION:()=>Fe,REJECTION_REASON:()=>S,ROOT_PARENT_ID:()=>V,SCHEDULE_CORE_STATUS:()=>Qt,SCHEDULE_EFFECT_KIND:()=>Xr,SIR_AUTO_REJECT_REASON:()=>Zr,STATUS:()=>Pt,STATUS_CRITERIA:()=>fe,ScheduleCore:()=>bi,WORK_TIME_DIRECTION:()=>j,checkNoUpdatedLinks:()=>Eu,computeExpectedProgress:()=>Eo,createSchedule:()=>ff,expectedProgressFromBaseline:()=>mi,getActiveBaseline:()=>gt,getUnsavedActivities:()=>pf,isRootParent:()=>U,normalizeParentKey:()=>$t,parseFromBackend:()=>Wn,willRunCriticalPath:()=>ru,yieldToBrowser:()=>ct});var T={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},Df=Object.values(T);function Fi(e){return Df.includes(e)}var dr={CONSTRAINT:"constraint",ALERT:"alert",WARNING:"warning"},j={FUTURE:"future",PAST:"past"},ut={HOUR:"hour",DAY:"day"},pt={DURATION:"DURATION",COST:"COST",WORK_HOURS:"HH"},fe={BASELINE:"Baseline",ACTUAL:"Actual"},Pt={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"},Ef={[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 fr(e,t,i){if(!t)return{violated:!1};let r=Ef[e];return r?r(t,i)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var _f=new Set([v.MSO,v.SNET,v.SNLT]);function Oe(e,t,i){return _f.has(e)?t:i}function pr(e,t,i){return{type:dr.CONSTRAINT,messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...i?{projectedDate:i}:{}}}}var kf={[v.SNET]:{startOfDay:!0,direction:j.FUTURE},[v.SNLT]:{startOfDay:!0,direction:j.PAST},[v.FNET]:{startOfDay:!1,direction:j.FUTURE},[v.FNLT]:{startOfDay:!1,direction:j.PAST},[v.MSO]:{startOfDay:!0,direction:j.FUTURE},[v.MFO]:{startOfDay:!1,direction:j.PAST}},ur=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),Xa=(e,t)=>new Date(e.getTime()+t*864e5),Rf=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function wi(e,t){if(!e.constraintDate||!e.constraintType)return null;let i=kf[e.constraintType];if(!i)return e.constraintDate;let r=e.constraintDate,n=t.getClosestWorkTime({date:ur(r),dir:j.FUTURE,task:e});if(Rf(n,r))return r.getTime()!==ur(r).getTime()?r:i.startOfDay?n:t.getClosestWorkTime({date:Xa(ur(r),1),dir:j.PAST,task:e});let o=ur(t.getClosestWorkTime({date:r,dir:i.direction,task:e}));return i.startOfDay?t.getClosestWorkTime({date:o,dir:j.FUTURE,task:e}):t.getClosestWorkTime({date:Xa(o,1),dir:j.PAST,task:e})}function Za(e,t){let i={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},r=e.constraintType;if(!r||r===v.ASAP||r===v.ALAP)return i;let n=wi(e,t);if(!n)return i;let o=s=>t.calculateEndDate({startDate:s,durationHours:e.durationHours,task:e}),a=s=>t.calculateEndDate({startDate:s,durationHours:-e.durationHours,task:e});switch(r){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 i}}function Qa(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function Jn(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var B={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"},Pf=Object.values(B);function yr(e){return Pf.includes(e)}var Lf={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"},Of={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"},E={...Lf,...Of};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 I={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",SIR_SYNC:"sir-sync",ACTIVITY_LOOKAHEAD_SYNC:"activity-lookahead-sync",SCHEDULE_AUTO_SCHEDULE:"schedule-auto-schedule"},pe="activity-batch",ot=St,ts=Object.values(I);function gt(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(i=>i.isActiveVersion)??null}var At={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"},xi={START:"start",END:"end"},Ne={FINISH_TO_START:"finish-to-start",START_TO_START:"start-to-start",FINISH_TO_FINISH:"finish-to-finish",START_TO_FINISH:"start-to-finish"},ii={CREATE:"create",UPDATE:"update",REMOVE:"remove"};var Nf={[At.NAME]:E.TEXT,[At.DESCRIPTION]:E.DESCRIPTION,[At.DURATION_DAYS]:E.DURATION,[At.PROGRESS]:E.PROGRESS,[At.COST]:E.COST,[At.USED_COST]:E.USED_COST,[At.WORK_HOURS]:E.HH_WORK_TIME,[At.START_DATE]:E.START_DATE,[At.END_DATE]:E.END_DATE,[At.CONSTRAINT_TYPE]:E.CONSTRAINT_TYPE,[At.CONSTRAINT_DATE]:E.CONSTRAINT_DATE,[At.CALENDAR_ID]:E.CALENDAR_ID,[At.CUSTOM_ID]:E.CUSTOM_ID,[At.SUBCONTRACT_ID]:E.SUBCONTRACT_ID,[At.RESPONSABLE_IDS]:E.RESPONSABLES,[At.TAG_IDS]:E.TAGS};function Xn(e,t){return{activityId:e,column:Nf[t.field],newValue:t.value}}var bf={[Ne.FINISH_TO_START]:B.FINISH_TO_START,[Ne.START_TO_START]:B.START_TO_START,[Ne.FINISH_TO_FINISH]:B.FINISH_TO_FINISH,[Ne.START_TO_FINISH]:B.START_TO_FINISH};function Mi(e){return bf[e]}function Ff(e){return e.kind===ii.CREATE?{kind:ot.CREATE,source:e.sourceId,target:e.targetId,type:Mi(e.relationship),...e.lagDays===void 0?{}:{lag:e.lagDays},...e.linkId===void 0?{}:{linkId:e.linkId}}:e.kind===ii.UPDATE?{kind:ot.UPDATE,linkId:e.linkId,...e.sourceId===void 0?{}:{source:e.sourceId},...e.targetId===void 0?{}:{target:e.targetId},...e.relationship===void 0?{}:{type:Mi(e.relationship)},...e.lagDays===void 0?{}:{lag:e.lagDays}}:e.kind===ii.REMOVE?{kind:ot.DELETE,linkId:e.linkId}:e}function wf(e){return e===xi.START?E.START_DATE:e===xi.END?E.END_DATE:e}function xf(e){return{kind:pe,mode:e.mode,items:e.items,links:e.links.map(t=>({source:t.source,target:t.target,type:Mi(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}})),...e.eventSource===void 0?{}:{eventSource:e.eventSource}}}function Mf(e){return{get:t=>e.getActivityView(t),list:()=>e.getAllActivitiesView(),ids:()=>e.getAllIds(),forEachId:t=>e.forEachActivityId(t),property:(t,i)=>e.getProperty(t,i),children:t=>e.getChildrenView(t),childIds:t=>e.getChildrenIds(t),hasChildren:t=>e.hasChild(t),indentTargetParentIds:t=>e.getIndentTargetParentIds(t),isCustomIdInUse:(t,i)=>e.isCustomIdInUse(t,i??null),create:(t,i)=>e.dispatch({...t,kind:I.ACTIVITY_CREATE},i),applyBatch:(t,i)=>e.applyActivityBatch(xf(t),i),editInline:(t,i,r)=>e.dispatch({...Xn(t,i),kind:I.INLINE_EDIT},r),setType:(t,i,r)=>e.dispatch({kind:I.ACTIVITY_TYPE_SET,activityId:t,type:i},r),applyDragBatch:(t,i)=>e.dispatch({kind:I.DATES_BATCH,edits:t.map(r=>({activityId:r.activityId,column:wf(r.edge),newValue:r.value}))},i),editFields:(t,i)=>e.dispatch({kind:I.BULK_EDIT,edits:t.map(r=>Xn(r.activityId,r))},i),remove:(t,i={})=>e.dispatch({...i,kind:I.ACTIVITY_DELETE,activityIds:t}),move:(t,i)=>e.dispatch({...t,kind:I.ACTIVITY_MOVE},i),planLookaheadConversion:t=>e.planLookaheadConversion(t),applyLookaheadConversion:t=>e.applyLookaheadConversion(t),indent:(t,i={})=>e.dispatch({...i,kind:I.ACTIVITY_INDENT,activityIds:t}),outdent:(t,i={})=>e.dispatch({...i,kind:I.ACTIVITY_OUTDENT,activityIds:t}),setProgress:(t,i,r={})=>e.dispatch({...r,kind:I.ACTIVITY_SET_PROGRESS,activityId:t,newValue:i}),copy:(t={})=>e.dispatch({...t,kind:I.ACTIVITY_COPY}),paste:(t,i={})=>e.dispatch({...i,kind:I.ACTIVITY_PASTE_COPIED,destination:{afterSiblingId:t}}),clearClipboard:(t={})=>e.dispatch({...t,kind:I.ACTIVITY_CLIPBOARD_CLEAR}),lookaheadSync:t=>e.dispatch({...t,kind:I.ACTIVITY_LOOKAHEAD_SYNC}),autoSchedule:(t,i)=>e.dispatch({kind:I.SCHEDULE_AUTO_SCHEDULE,...t===void 0?{}:{activityId:t}},i),createDateGesturePreview:t=>e.createDateGesturePreview(t)}}function Uf(e){return{get:t=>e.getLinkView(t),list:()=>e.getAllLinksView(),forActivity:t=>e.getLinksForActivityView(t),create:(t,i)=>e.dispatch({kind:I.LINK_CREATE,source:t.sourceId,target:t.targetId,type:Mi(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}},i),update:(t,i,r)=>e.dispatch({kind:I.LINK_UPDATE,linkId:t,...i.sourceId===void 0?{}:{source:i.sourceId},...i.targetId===void 0?{}:{target:i.targetId},...i.relationship===void 0?{}:{type:Mi(i.relationship)},...i.lagDays===void 0?{}:{lag:i.lagDays}},r),remove:(t,i)=>e.dispatch({kind:I.LINK_DELETE,linkId:t},i),batch:(t,i)=>e.dispatch({kind:I.LINKS_BATCH,operations:t.map(Ff)},i)}}function es(e){let t=(i,r)=>e.dispatch({kind:I.BASELINE_APPLY,points:i},r);return{activities:Mf(e),links:Uf(e),calendars:{get:i=>e.getCalendar(i),list:()=>e.getAllCalendars(),listBase:()=>e.getBaseCalendars(),projectWorkHours:()=>e.getProjectWorkHours(),reconcile:i=>e.dispatch({kind:I.CALENDAR_RECONCILE},i)},selection:{ids:()=>e.getSelectedActivityIds(),toggle:({checked:i,...r})=>e.dispatch({...r,kind:I.SELECTION_TOGGLE,isChecked:i}),replace:(i,r={})=>e.dispatch({...r,kind:I.SELECTION_REPLACE,activityIds:i})},view:{hiddenActivityIds:()=>e.getHiddenActivityIds(),visibleActivityIds:()=>e.getVisibleActivityIds(),visualOrderIds:()=>e.getVisualOrderIds(),filter:()=>e.getActiveFilter(),setFilter:i=>e.dispatch({...i,kind:I.FILTER_SET}),order:()=>e.getActiveOrder(),setOrder:(i,r={})=>e.dispatch({...r,kind:I.SORT_SET,rules:i}),setVisibility:(i,r={})=>e.dispatch({...r,kind:I.VISIBILITY_SET,visibleIds:i}),setStatusCriteria:(i,r)=>e.dispatch({kind:I.STATUS_CRITERIA_SET,criteria:i},r)},baselines:{refresh:t,setVisibility:t,setPonderatorCriterion:(i,r)=>e.dispatch({kind:I.PONDERATOR_CRITERION_SET,criterion:i},r),activeFor:i=>gt(i)},impactRequests:{sync:i=>e.dispatch({...i,kind:I.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:i=>e.dispatch({kind:I.PERSISTENCE_ACKNOWLEDGE,checkpoint:i})},history:{undo:i=>e.undo(i),redo:i=>e.redo(i),canUndo:()=>e.canUndo(),canRedo:()=>e.canRedo(),clear:()=>e.clearHistory(),depth:()=>e.undoDepth()},projection:{changeSetFrom:i=>e.createProjectionChangeSetFrom(i)},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 Ut=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 hr=e=>String(e);function is(e){let{clickedId:t,isChecked:i,currentSelection:r,hierarchy:n,isFrozen:o,exists:a,autoCheckParents:s}=e,c=hr(t),l=new Set([...r].map(String)),d=new Set(l),u=Hf(c,n).filter(a),f=u.filter(y=>!o(y)),p=i&&f.length<u.length;i&&!p?d.add(c):d.delete(c);for(let y of f)i?d.add(y):d.delete(y);return p||Bf({id:c,isChecked:i,autoCheckParents:s,hierarchy:n,isFrozen:o,exists:a,next:d}),{nextSelection:d,changed:Wf(l,d),parentBlocked:p}}function Hf(e,t){let i=[],r=new Ut;r.enqueue(e);let n=new Set([e]);for(;!r.isEmpty();){let o=r.dequeue();for(let a of t.getChildrenIds(o)){let s=hr(a);n.has(s)||(n.add(s),i.push(s),r.enqueue(s))}}return i}function Bf(e){let{id:t,isChecked:i,autoCheckParents:r,hierarchy:n,isFrozen:o,exists:a,next:s}=e,c=n.getParentId(t);for(;c!==null&&typeof c<"u";){let l=hr(c);if(o(l))return;let d=n.getChildrenIds(l).map(hr).filter(a),u=d.some(o),f=d.filter(g=>!o(g)),y=f.length>0&&f.every(g=>s.has(g))&&!u;if(i){if(!r||!y||s.has(l))return;s.add(l)}else{if(y||!s.has(l))return;s.delete(l)}c=n.getParentId(l)}}function Wf(e,t){let i=[],r=[];for(let n of t)e.has(n)||i.push(n);for(let n of e)t.has(n)||r.push(n);return{checked:i,unchecked:r}}function ri(e){return(e.pendingRequestIds?.length??0)>0}var S={CANNOT_EDIT:"cannot_edit",PARSE_ERROR:"parse_error",INVALID:"invalid",CUSTOM_ID_DUPLICATE:"custom_id_duplicate",INVALID_LINK_TYPE:"invalid_link_type",INVALID_LINK_LAG:"invalid_link_lag",INVALID_VALUE:"invalid_value",NO_PIPELINE_FOR_COLUMN:"no_pipeline_for_column",ACTIVITY_NOT_FOUND:"activity_not_found",PARENT_NOT_FOUND:"parent_not_found",ACTIVITY_IDS_EMPTY:"activity_ids_empty",NO_ACTIVITY_SELECTION:"no_activity_selection",CLIPBOARD_EMPTY:"clipboard_empty",ACTIVITY_PASTE_INVARIANT_FAILED:"activity_paste_invariant_failed",ANCHOR_SIBLING_CONFLICT:"anchor_sibling_conflict",ANCHOR_SIBLING_NOT_FOUND:"anchor_sibling_not_found",ANCHOR_SIBLING_WRONG_PARENT:"anchor_sibling_wrong_parent",PARENT_FROZEN_BY_SIR:"parent_frozen_by_sir",CANNOT_MOVE_INTO_OWN_DESCENDANT:"cannot_move_into_own_descendant",INDENT_NO_ELIGIBLE_SIBLING:"indent_no_eligible_sibling",OUTDENT_ROOT_LEVEL_NOT_EDITABLE:"outdent_root_level_not_editable",HIERARCHY_CYCLE:"hierarchy_cycle",SANDBOX_PERSISTENCE_FORBIDDEN:"sandbox_persistence_forbidden",STALE_STATE_REVISION:"stale-state-revision",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var rs=(e,t)=>{let i=e.getActivity(t);return i!=null&&ri(i)},ns=(e,t,i)=>{let r=[],n=(o,a)=>{let s=t.isChecked(o);t.setChecked(o,a)&&r.push({activityId:o,checked:{before:s,after:a}})};for(let o of i.checked)n(o,!0);for(let o of i.unchecked)n(o,!1);return{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:r}};function os(e,t){let{adapter:i}=t,r=e.activityId;if(!i.getActivity(r))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let n=e.frozenIds?new Set(e.frozenIds):null,o=n?s=>n.has(s):s=>rs(i,s),a=is({clickedId:r,isChecked:e.isChecked,currentSelection:new Set(i.checkedIds().map(String)),hierarchy:{getChildrenIds:s=>i.getChildren(s),getParentId:s=>{let c=i.getParentId(s);return!c||c==="0"?null:String(c)}},isFrozen:o,exists:s=>i.activityExists(s),autoCheckParents:e.autoCheckParents??!1});return{ok:!0,changes:ns(e,i,a.changed)}}function mr(e,t){let{adapter:i}=t,r=new Set(e.activityIds.map(String).filter(a=>i.activityExists(a)).filter(a=>!rs(i,a))),n=new Set(i.checkedIds().map(String)),o={checked:[...r].filter(a=>!n.has(a)),unchecked:[...n].filter(a=>!r.has(a))};return{ok:!0,changes:ns(e,i,o)}}function ni(e,t,i=e.getAllIds()){let r=[];for(let n of i){let o=String(n),a=t.has(o),s=e.isVisible(o);s!==a&&(e.setVisible(o,a),r.push({activityId:o,visible:{before:s,after:a}}))}return r}function as(e,t){let{adapter:i}=t,r=new Set(e.visibleIds.map(String)),n=ni(i,r);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:n}}}var ss={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var O={STRING:"string",NUMBER:"number",DATE:"date",ID_ARRAY:"id-array",ENUM:"enum",BOOLEAN:"boolean",REFERENCE:"reference"},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"},W={INCLUDES:"includes",NOT_INCLUDES:"notIncludes",IS:"is",IS_NOT:"isNot",EQUALS:"equals",NOT_EQUALS:"notEquals",GREATER_THAN:"greaterThan",LESS_THAN:"lessThan",GREATER_OR_EQUAL:"greaterOrEqual",LESS_OR_EQUAL:"lessOrEqual",AFTER:"after",BEFORE:"before",BETWEEN:"between",SOME_OF:"someOf",NOT_SOME_OF:"notSomeOf"},Ir={AND:"and",OR:"or"};var Vf=2,jf=[Pt.WAITING,Pt.DONE,Pt.DOING,Pt.OVERDUE,Pt.ADVANCEMENT],Kf=[v.MFO,v.MSO,v.SNLT,v.SNET,v.ALAP,v.ASAP,v.FNET,v.FNLT],Yf=1e3*60*60*24;function Zn(e,t){return e===null||t<=0?null:e/t}function Gf(e,t){let i=Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()),r=Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate());return Math.floor((r-i)/Yf)+1}var $f={[z.NAME]:{valueKind:O.STRING,extract:e=>e.name},[z.DESCRIPTION]:{valueKind:O.STRING,extract:e=>e.description},[z.CUSTOM_ID]:{valueKind:O.STRING,extract:e=>e.customId},[z.CORRELATIVE_ID]:{valueKind:O.NUMBER,extract:e=>e.correlativeId},[z.UNIQUE_CORRELATIVE_ID]:{valueKind:O.NUMBER,extract:e=>{let t=Number(e.uniqueCorrelativeId);return Number.isFinite(t)?t:null}},[z.PROGRESS]:{valueKind:O.NUMBER,extract:e=>e.progress},[z.DURATION_DAYS]:{valueKind:O.NUMBER,extract:(e,t)=>Zn(e.durationHours,t.hoursPerDay)},[z.CALENDAR_DURATION]:{valueKind:O.NUMBER,extract:e=>e.type===T.MILESTONE?0:Gf(e.startDate,e.endDate)},[z.COST]:{valueKind:O.NUMBER,extract:e=>e.cost},[z.USED_COST]:{valueKind:O.NUMBER,extract:e=>e.usedCost},[z.REAL_COST]:{valueKind:O.NUMBER,extract:e=>e.realCost},[z.WORK_HOURS]:{valueKind:O.NUMBER,extract:e=>e.workHours},[z.REAL_WORK_HOURS]:{valueKind:O.NUMBER,extract:e=>e.realWorkHours},[z.PONDERATOR]:{valueKind:O.NUMBER,extract:e=>e.ponderator},[z.FREE_SLACK_DAYS]:{valueKind:O.NUMBER,extract:(e,t)=>Zn(e.freeSlackHours,t.hoursPerDay)},[z.TOTAL_SLACK_DAYS]:{valueKind:O.NUMBER,extract:(e,t)=>Zn(e.criticalPath?.totalSlackHours??null,t.hoursPerDay)},[z.EXPECTED_PROGRESS_BASELINE]:{valueKind:O.NUMBER,equalityPrecision:Vf,extract:e=>e.expectedProgressBaseline},[z.EXPECTED_PROGRESS]:{valueKind:O.NUMBER,extract:e=>e.expectedProgress},[z.BASELINE_DURATION_DAYS]:{valueKind:O.NUMBER,extract:e=>e.baselineSnapshot?.durationDays??null},[z.BASELINE_COST]:{valueKind:O.NUMBER,extract:e=>e.baselineSnapshot?.cost??null},[z.BASELINE_WORK_HOURS]:{valueKind:O.NUMBER,extract:e=>e.baselineSnapshot?.workHours??null},[z.START_DATE]:{valueKind:O.DATE,extract:e=>e.startDate},[z.END_DATE]:{valueKind:O.DATE,extract:e=>e.endDate},[z.CONSTRAINT_DATE]:{valueKind:O.DATE,extract:e=>e.constraintDate},[z.BASELINE_START_DATE]:{valueKind:O.DATE,extract:e=>e.baselineSnapshot?.startDate??null},[z.BASELINE_END_DATE]:{valueKind:O.DATE,extract:e=>e.baselineSnapshot?.endDate??null},[z.EARLY_START]:{valueKind:O.DATE,extract:e=>e.criticalPath?.earlyStart??null},[z.EARLY_FINISH]:{valueKind:O.DATE,extract:e=>e.criticalPath?.earlyFinish??null},[z.LATE_START]:{valueKind:O.DATE,extract:e=>e.criticalPath?.lateStart??null},[z.LATE_FINISH]:{valueKind:O.DATE,extract:e=>e.criticalPath?.lateFinish??null},[z.RESPONSABLE_IDS]:{valueKind:O.ID_ARRAY,extract:e=>e.responsableIds},[z.TAG_IDS]:{valueKind:O.ID_ARRAY,extract:e=>e.tagIds},[z.STATUS]:{valueKind:O.ENUM,order:jf,extract:e=>e.status},[z.CONSTRAINT_TYPE]:{valueKind:O.ENUM,order:Kf,extract:e=>e.constraintType},[z.CALENDAR_ID]:{valueKind:O.REFERENCE,extract:e=>e.calendarId===null?null:String(e.calendarId)},[z.SUBCONTRACT_ID]:{valueKind:O.REFERENCE,extract:e=>e.subcontractId===null?null:String(e.subcontractId)},[z.IS_CRITICAL]:{valueKind:O.BOOLEAN,extract:e=>e.isCritical}};function ye(e){return $f[e]??null}function Qn(e){return e instanceof Date?e:typeof e=="string"||typeof e=="number"?new Date(e):new Date(Number.NaN)}function ne(e){return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())}function zf(e,t,i){let r=e===null;return i===W.INCLUDES?!r&&String(e).toLowerCase().includes(t.toLowerCase()):i===W.NOT_INCLUDES?r||!String(e).toLowerCase().includes(t.toLowerCase()):i===W.IS?!r&&String(e)===t:i===W.IS_NOT?r||String(e)!==t:!1}function qf(e,t,i,r){if(e===null||typeof e!="number")return i===W.NOT_EQUALS;let n=r===void 0?e:Number(e.toFixed(r));return i===W.EQUALS?n===t:i===W.NOT_EQUALS?n!==t:i===W.GREATER_THAN?e>t:i===W.LESS_THAN?e<t:i===W.GREATER_OR_EQUAL?e>=t:i===W.LESS_OR_EQUAL?e<=t:!1}function Jf(e,t,i){return typeof e=="number"&&e>=t&&e<=i}function Xf(e,t,i){if(!(e instanceof Date))return!1;let r=ne(e),n=ne(t);return i===W.AFTER?r>n:i===W.BEFORE?r<n:!1}function Zf(e,t,i){if(!(e instanceof Date))return!1;let r=ne(e);return r>=ne(t)&&r<=ne(i)}function Qf(e,t,i){let n=(Array.isArray(e)?e:[]).some(o=>t.has(String(o)));return i===W.SOME_OF?n:i===W.NOT_SOME_OF?!n:!1}function tp(e,t,i){let r=e!==null&&t.has(String(e));return i===W.SOME_OF?r:i===W.NOT_SOME_OF?!r:!1}function cs(e){let t=Array.isArray(e)?e:[e];return new Set(t.map(i=>String(i)))}function ls(e,t,i){let r=ye(t.field);if(r===null)return!1;let n=r.extract(e,i),{operator:o}=t;return o===W.BETWEEN?r.valueKind===O.NUMBER?Jf(n,Number(t.value),Number(t.valueTo)):r.valueKind===O.DATE?Zf(n,Qn(t.value),Qn(t.valueTo)):!1:r.valueKind===O.STRING?zf(n,String(t.value),o):r.valueKind===O.NUMBER?qf(n,Number(t.value),o,r.equalityPrecision):r.valueKind===O.DATE?Xf(n,Qn(t.value),o):r.valueKind===O.ID_ARRAY?Qf(n,cs(t.value),o):tp(n,cs(t.value),o)}function ep(e,t,i){return t.criteria.length===0?!0:t.logic===Ir.OR?t.criteria.some(r=>ls(e,r,i)):t.criteria.every(r=>ls(e,r,i))}function ip(e,t){let i=ne(e.startDate),r=ne(e.endDate),n=ne(t.start),o=ne(t.end),a=i>=n&&r<=o,s=i>=n&&i<=o,c=n>=i&&n<=r;return a||s||c}function to(e,t,i){let r=ep(e,t,i),n=t.dateRange,o=n===void 0||ip(e,n);return r&&o}function rp(e,t,i){let r=t(e);for(;r!==null&&!i.has(String(r));)i.add(String(r)),r=t(r)}function ds(e){let{activities:t,parentOf:i,filter:r,context:n}=e,o=new Set,a=[];for(let s of t)to(s,r,n)&&(o.add(String(s.id)),a.push(s.id));for(let s of a)rp(s,i,o);return o}function np(e){let{activities:t,parentOf:i,filter:r,context:n}=e,o=new Set,a=new Map,s=new Map,c=new Map;for(let l of t){let d=String(l.id),u=i(d);s.set(d,u),c.set(d,c.get(d)??0),u!==null&&c.set(u,(c.get(u)??0)+1);let f=to(l,r,n);a.set(d,f?1:0),f&&o.add(d)}return{matchedIds:o,visibleReferenceCounts:a,parentIds:s,remainingChildren:c}}function op(e){let{visibleReferenceCounts:t,parentIds:i,remainingChildren:r}=e,n=[];for(let o of i.keys())r.get(o)===0&&n.push(o);for(;n.length>0;){let o=n.pop();if(o===void 0)break;let a=i.get(o);if(a==null)continue;let s=t.get(o)??0;t.set(a,(t.get(a)??0)+s);let c=(r.get(a)??1)-1;r.set(a,c),c===0&&n.push(a)}}function ap(e){let t=new Set;for(let[i,r]of e)r>0&&t.add(i);return t}function gr(e){let t=np(e);op(t);let i=ap(t.visibleReferenceCounts);return{filter:e.filter,context:e.context,matchedIds:t.matchedIds,visibleIds:i,visibleReferenceCounts:t.visibleReferenceCounts}}function us(e,t,i){let r=new Set;for(let n of t){let o=String(n.id);r.add(o);let a=e.matchedIds.has(o),s=to(n,e.filter,e.context);if(a===s)continue;s?e.matchedIds.add(o):e.matchedIds.delete(o);let c=s?1:-1,l=o;for(;l!==null;){let d=e.visibleReferenceCounts.get(l)??0,u=d+c;e.visibleReferenceCounts.set(l,u);let f=d>0,p=u>0;f!==p&&(r.add(l),p?e.visibleIds.add(l):e.visibleIds.delete(l)),l=i(l)}}return r}function be(e){return{hoursPerDay:e,locale:"en"}}var Tt={UNKNOWN_FIELD:"unknown_field",UNKNOWN_OPERATOR:"unknown_operator",INVALID_VALUE:"invalid_value"},sp={[O.STRING]:new Set([W.INCLUDES,W.NOT_INCLUDES,W.IS,W.IS_NOT]),[O.NUMBER]:new Set([W.EQUALS,W.NOT_EQUALS,W.GREATER_THAN,W.LESS_THAN,W.GREATER_OR_EQUAL,W.LESS_OR_EQUAL,W.BETWEEN]),[O.DATE]:new Set([W.AFTER,W.BEFORE,W.BETWEEN]),[O.ID_ARRAY]:new Set([W.SOME_OF,W.NOT_SOME_OF]),[O.ENUM]:new Set([W.SOME_OF,W.NOT_SOME_OF]),[O.BOOLEAN]:new Set([W.SOME_OF,W.NOT_SOME_OF]),[O.REFERENCE]:new Set([W.SOME_OF,W.NOT_SOME_OF])};function fs(e){if(e===void 0)return{ok:!0,dateRange:void 0};if(typeof e!="object"||e===null)return{ok:!1,reason:Tt.INVALID_VALUE};let{start:t,end:i}=e;if(!(t instanceof Date)||!(i instanceof Date))return{ok:!1,reason:Tt.INVALID_VALUE};let r=t.getTime(),n=i.getTime();return!Number.isFinite(r)||!Number.isFinite(n)||r>n?{ok:!1,reason:Tt.INVALID_VALUE}:{ok:!0,dateRange:{start:new Date(r),end:new Date(n)}}}function ps(e){let t=ye(e.field);if(t===null)return{ok:!1,reason:Tt.UNKNOWN_FIELD};if(!sp[t.valueKind].has(e.operator))return{ok:!1,reason:Tt.UNKNOWN_OPERATOR};if(e.operator===W.BETWEEN)return cp(e,t.valueKind);if(t.valueKind===O.NUMBER){let r=eo(e.value);return r===null?{ok:!1,reason:Tt.INVALID_VALUE}:{ok:!0,criterion:{...e,value:r}}}if(t.valueKind===O.DATE){let r=io(e.value);return r===null?{ok:!1,reason:Tt.INVALID_VALUE}:{ok:!0,criterion:{...e,value:r}}}let i=lp(e,t.valueKind);return i!==null?{ok:!1,reason:i}:t.valueKind===O.BOOLEAN?{ok:!0,criterion:{...e,value:[...new Set(e.value)]}}:t.valueKind===O.ID_ARRAY||t.valueKind===O.ENUM||t.valueKind===O.REFERENCE?{ok:!0,criterion:{...e,value:[...new Set(e.value.map(String))]}}:{ok:!0,criterion:e}}function cp(e,t){if(t===O.NUMBER){let i=eo(e.value),r=eo(e.valueTo);return i===null||r===null||i>r?{ok:!1,reason:Tt.INVALID_VALUE}:{ok:!0,criterion:{...e,value:i,valueTo:r}}}if(t===O.DATE){let i=io(e.value),r=io(e.valueTo);return i===null||r===null||i.getTime()>r.getTime()?{ok:!1,reason:Tt.INVALID_VALUE}:{ok:!0,criterion:{...e,value:i,valueTo:r}}}return{ok:!1,reason:Tt.UNKNOWN_OPERATOR}}function lp(e,t){let{value:i}=e;return t===O.BOOLEAN?Array.isArray(i)&&i.every(r=>typeof r=="boolean")?null:Tt.INVALID_VALUE:t===O.ID_ARRAY||t===O.ENUM||t===O.REFERENCE?Array.isArray(i)&&i.every(r=>typeof r=="string"||typeof r=="number")?null:Tt.INVALID_VALUE:Array.isArray(i)?Tt.INVALID_VALUE:null}function eo(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 w(e){return structuredClone(e)}function ys(e){return e.criteria.length===0&&e.dateRange===void 0}function dp(e,t,i){let r=e.getAllActivities();if(ys(t))return{visibleIds:ds({activities:r,parentOf:o=>e.getParentId(o),filter:t,context:be(i)}),projection:null};let n=gr({activities:r,parentOf:o=>e.getParentId(o),filter:t,context:be(i)});return{visibleIds:n.visibleIds,projection:n}}function hs(e,t){let{adapter:i,hoursPerDay:r}=t,n=[];for(let u of e.criteria){let f=ps(u);if(!f.ok)return{ok:!1,reason:f.reason};n.push(f.criterion)}let o=fs(e.dateRange);if(!o.ok)return{ok:!1,reason:o.reason};let a=w(o.dateRange===void 0?{criteria:n,logic:e.logic}:{criteria:n,logic:e.logic,dateRange:o.dateRange});i.setActiveFilter(ys(a)?null:a);let{visibleIds:s,projection:c}=dp(i,a,r);i.setFilterProjection(c);let l=ni(i,s);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:l}}}var Fe={ASCENDING:"asc",DESCENDING:"desc"};var V="0";function U(e){return e==null||e===0||e==="0"}function $t(e){return U(e)?"0":String(e)}var ro=Number.MAX_SAFE_INTEGER;function Wt(e,t){let i=Ui(e,t),r=t.getOrderComparator?.()??null;return i.sort(r===null?Ar:(n,o)=>r(n,o)||Ar(n,o)),i.map(n=>String(n.id))}function Is(e){let t=[],i=n=>{t.push(n);let o=Wt(String(n.id),e);for(let a of o){let s=e.getActivity(a);s&&i(s)}},r=Wt("0",e);for(let n of r){let o=e.getActivity(n);o&&i(o)}return t}function gs(e,t,i){let r=i.getActivity(e);if(!r)return null;let n=As(r),o=Wt(n,i),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&&!up(t,c))return c}return null}function no(e,t){let i=t.getActivity(e);if(!i)return-1;let r=As(i);return Wt(r,t).findIndex(o=>String(o)===String(e))}function Ui(e,t){let i=String(e)==="0"?t.getRootIds?.()??t.getChildren("0"):t.getChildren(e),r=[];for(let n of i){let o=t.getActivity(n);o&&r.push(o)}return r}function Ar(e,t){let i=ms(e),r=ms(t);return i!==r?i-r:String(e.id).localeCompare(String(t.id))}function ms(e){let t=e.correlativeId,i=typeof t=="number"?t:Number(t);return Number.isFinite(i)?i:ro}function As(e){let t=e.parentId;return t===null?"0":t}function up(e,t){return e.has(t)?!0:e.has(String(t))}function oi(e){let t=[],i=r=>{let n=Wt(r,e);n.length>1&&t.push({parentId:r,childIds:n});for(let o of n)i(o)};return i("0"),t}function oo(e,t){let i=[];for(let r of t){let n=Wt(r,e);n.length>1&&i.push({parentId:r,childIds:n})}return i}function fp(e){return ye(e.field)===null?Tt.UNKNOWN_FIELD:e.direction!==Fe.ASCENDING&&e.direction!==Fe.DESCENDING?Tt.UNKNOWN_OPERATOR:null}function vs(e,t){let{adapter:i}=t;for(let o of e.rules){let a=fp(o);if(a!==null)return{ok:!1,reason:a}}let r=e.rules.length===0?null:w({rules:e.rules});return i.setActiveOrder(r),{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],order:oi(i)}}}function Cs(e,t){throw new Error(t)}var ao={OWN_BASELINE:"own-baseline",RECURSIVE_LEAF_SUM:"recursive-leaf-sum",ZERO:"zero"},so={[T.PROJECT]:{alwaysSummary:!0,holdsConstraint:!1,carriesCustomId:!1,forcedDuration:null,ponderatorWeight:ao.RECURSIVE_LEAF_SUM,promotesToProjectOnFirstChild:!1},[T.TASK]:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:null,ponderatorWeight:ao.OWN_BASELINE,promotesToProjectOnFirstChild:!0},[T.MILESTONE]:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:0,ponderatorWeight:ao.ZERO,promotesToProjectOnFirstChild:!0}};function zt(e,t){return t||Fi(e)&&so[e].alwaysSummary}function oe(e){return e===T.MILESTONE}function he(e){return Fi(e)&&so[e].promotesToProjectOnFirstChild}var co=T.PROJECT,ai=T.TASK;function Hi(e,t){return t===0?T.MILESTONE:e===0&&t>0?T.TASK:null}var b={ID:"id",PROPLANNER_ID:"proplannerId",PARENT:"parentId",NAME:"name",DESCRIPTION:"description",TYPE:"type",START_DATE:"startDate",END_DATE:"endDate",DURATION_HOURS:"durationHours",CONSTRAINT_TYPE:"constraintType",CONSTRAINT_DATE:"constraintDate",AUTO_SCHEDULING:"autoScheduling",CALENDAR_ID:"calendarId",ASSIGNED_DEFAULT_CALENDAR:"assignedDefaultCalendar",DATE_ORIGIN:"dateOrigin",PROGRESS:"progress",COST:"cost",USED_COST:"usedCost",REAL_COST:"realCost",WORK_HOURS:"workHours",REAL_WORK_HOURS:"realWorkHours",PONDERATOR:"ponderator",HAS_CUSTOM_PONDERATOR:"hasCustomPonderator",CORRELATIVE_ID:"correlativeId",UNIQUE_CORRELATIVE_ID:"uniqueCorrelativeId",CUSTOM_ID:"customId",SUBCONTRACT_ID:"subcontractId",IS_LOOKAHEAD:"isLookahead",HAS_LOOKAHEAD_TASKS:"hasLookaheadTasks",NEW_ACTIVITIES_ARRAY:"newActivityIds",HAS_NEW_ACTIVITIES:"hasNewActivities",IS_NEW_ACTIVITY:"isNewActivity",PENDING_REQUEST_IDS:"pendingRequestIds",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds",BASELINE_POINTS:"baselinePoints",BASELINE_SNAPSHOT:"baselineSnapshot",SUM_OF_DURATION_RECURSIVELY:"recursiveDurationHours",CALENDAR_DURATION:"calendarDuration",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath"},wt={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 Ss(e,t){return()=>t()===e}var lo=typeof window>"u",pp=!lo&&typeof MessageChannel<"u";function ct(){return pp?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 vr(e,t){return performance.now()-e<ss.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await ct(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function si(e){return lo||await ct(),e()?{aborted:!1}:{aborted:!0}}function Cr(e,t){let{inDegree:i,successors:r}=yp(e,t),n=hp(i),o=mp(n,i,r),a=o.length<e.length,s=a?Ip(e,o):[],c=[...o].reverse();return{ordered:o,reversed:c,hasCycles:a,cycleNodes:s}}function yp(e,t){let i=new Map,r=new Map;for(let n of e)i.set(n,0),r.set(n,[]);for(let n of t){let o=n.source,a=n.target;!i.has(o)||!i.has(a)||(r.get(o).push(a),i.set(a,(i.get(a)??0)+1))}return{inDegree:i,successors:r}}function hp(e){let t=new Ut;for(let[i,r]of e)r===0&&t.enqueue(i);return t}function mp(e,t,i){let r=[];for(;!e.isEmpty();){let n=e.dequeue();r.push(n);for(let o of i.get(n)??[]){let a=(t.get(o)??1)-1;t.set(o,a),a===0&&e.enqueue(o)}}return r}function Ip(e,t){let i=new Set(t);return e.filter(r=>!i.has(r))}var Sr=class{cached=null;invalidate(){this.cached=null}get(t,i){return this.cached?this.cached:(this.cached=Cr(t,i),this.cached)}};function Ts(e,t){let i=[];for(let r of e)t.has(r)&&i.push(r);return i}function Tr(e,t){let i=t.getActivity(e);return i?zt(i.type,t.getChildren(e).length>0):!1}function Dr(e,t,i){let r=String(t),n=i.getActivity(e);for(;n?.parentId&&String(n.parentId)!=="0";){if(String(n.parentId)===r)return!0;n=i.getActivity(n.parentId)}return!1}function _r(e,t,i){let r=Tr(e,i);return Tr(t,i)&&Dr(e,t,i)||r&&Dr(t,e,i)}function _s(e,t){let i=[],r=[e];for(;r.length>0;){let n=r.pop(),o=t.getChildren(n);if(o.length===0){String(n)!==String(e)&&i.push(n);continue}for(let a of o)r.push(a)}return i}function gp(e){let t=new Map;for(let i of e)Ds(t,String(i.source),i),Ds(t,String(i.target),i);return t}function Ds(e,t,i){let r=e.get(t);if(r){r.push(i);return}e.set(t,[i])}function Ap(e,t,i,r){if(e.length<=1)return e;let n=new Set(e.map(String)),o=[];for(let a of e)vp(a,n,t,i,r)||o.push(a);return o.length>0?o:e}function vp(e,t,i,r,n){let o=String(e),a=i.getActivity(e);if(!a||a.autoScheduling===!1)return!1;let s=r.get(o)??[];for(let c of s)if(Cp(c,o,a,t,i,n))return!0;return!1}function Cp(e,t,i,r,n,o){if(Sp(e)||!(o?String(e.source)===t:String(e.target)===t))return!1;let s=Tp(e,t);if(!r.has(String(s)))return!1;let c=n.getActivity(s);return!!(c?.autoScheduling!==!1&&c&&Dp(e,i,c))}function Sp(e){return e.source===e.target}function Tp(e,t){return String(e.source)===t?e.target:e.source}function Dp(e,t,i){let r=e.lag??0,n=Math.abs(r);return String(e.target)===String(i.id)&&n<=i.durationHours||String(e.target)===String(t.id)&&n<=t.durationHours}function kr(e,t){let i=[],r=gp(e),n=0;for(let o of e){let a=Tr(o.source,t),s=Tr(o.target,t);if(Ep(o,a,s,t))continue;if(!a&&!s){i.push(o);continue}let c=Es(o.source,a,t,r,!0),l=Es(o.target,s,t,r,!1);n=Np(i,c,l,o,t,n,r)}return i}function Ep(e,t,i,r){return i&&Dr(e.source,e.target,r)||t&&Dr(e.target,e.source,r)}function Es(e,t,i,r,n){return t?Ap(_s(e,i),i,r,n):[e]}function _p(e,t,i){let r=_s(e,t);if(r.length===0)return null;let n=null,o=null;for(let a of r){let s=i(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 Er(e,t){return _p(e,t,i=>{let r=t.getActivity(i);return r?{startDate:r.startDate,endDate:r.endDate}:null})}function kp(e,t,i){return e?t?i.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function Rp(e,t,i,r){if(!t)return 0;let n=r.getActivity(e);return!i||!n?-t.durationHours:-r.calculateDuration({startDate:i.startDate,endDate:n.endDate,task:t})}function Pp(e,t){let i=String(e);return(t.get(i)??[]).some(n=>String(n.target)===i)}function Lp(e,t,i,r,n){if(Pp(e,n))return 0;let o=r.getActivity(e);return!t||!o||!i?0:r.calculateDuration({startDate:t,endDate:o.startDate,task:i})}function Op(e,t){let i=t.getActivity(e.source),r=t.getActivity(e.target),n=Er(e.source,t),o=Er(e.target,t),a=e.type===B.START_TO_START||e.type===B.START_TO_FINISH,s=e.type===B.FINISH_TO_FINISH||e.type===B.START_TO_FINISH;return{source:i,sourceBounds:n,targetStart:o?.startDate??r?.startDate,userLag:e.lag??0,sourceEndpointIsStart:a,targetLag:s?-kp(r,o,t):0,summarySourceId:e.type===B.START_TO_START&&n?e.source:void 0,finishAnchoredSummaryTargetId:s&&o?e.target:void 0}}function Np(e,t,i,r,n,o,a){let s=Op(r,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?Rp(k,c,l,n):0;for(let F of i){if(String(k)===String(F))continue;let m=Lp(F,d,c,n,a);e.push(bp(r,k,F,A,_,p,u+m,y,g??(m!==0&&p===0?r.target:void 0))),A+=1}}return A}function bp(e,t,i,r,n,o,a,s,c){return{id:`virtual_${e.id}_${r}`,source:t,target:i,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 Rr=class{invalidate(){}get(t,i){return kr(t,i)}};function Fp(e){let t=new Map,i=r=>(t.has(r)||t.set(r,new Set),t.get(r));for(let r of e)i(r.source).add(r.id),i(r.target).add(r.id);return{neighbors:t}}function wp(e,t,i){let r=new Set,n=new Map,o=new Ut;for(o.enqueue(e);!o.isEmpty();){let a=o.dequeue(),s=String(a);if(r.has(s))continue;r.add(s);let c=i.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;r.has(String(f))||o.enqueue(f)}}return Array.from(n.values())}function ks(e,t){let i=new Map;for(let a of t)i.set(a.id,a);let r=Fp(t),n=wp(e,i,r),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 Rs=0,Bi=100;function we(e){return e===0}function Ps(e,t,i){let r=i.type===B.FINISH_TO_START,n=i.type===B.FINISH_TO_FINISH;if(i._targetLag!==void 0)return{sourceLag:i._sourceLag??0,targetLag:i._targetLag,trueLag:i._trueLag??i.lag??0,isFS:r,isFF:n,isZeroDurationCase:!1};let o=i.lag??0;switch(i.type){case B.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:o,isFS:r,isFF:n,isZeroDurationCase:!1};case B.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:o,isFS:r,isFF:n,isZeroDurationCase:!1};case B.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:o,isFS:r,isFF:n,isZeroDurationCase:!1};case B.START_TO_FINISH:return{sourceLag:-e.durationHours,targetLag:-t.durationHours,trueLag:o,isFS:r,isFF:n,isZeroDurationCase:!1};default:return{sourceLag:0,targetLag:0,trueLag:o,isFS:r,isFF:n,isZeroDurationCase:!1}}}function xp(e,t,i){if(e._summarySourceId===void 0)return null;let r=i.getActivity(e._summarySourceId);if(!r)return null;let n=Er(e._summarySourceId,i);return n?-i.calculateDuration({startDate:n.startDate,endDate:t.endDate,task:r}):null}function Mp(e,t,i,r,n){let o=t.durationHours===0&&n;return{successorStart:r.getClosestWorkTime({date:e.endDate,dir:o?"past":"future",task:t}),link:i}}function Ls(e,t,i,r){let{sourceLag:n,targetLag:o,trueLag:a,isFS:s,isFF:c}=Ps(e,t,i),l=xp(i,e,r)??n,d=l+o+a;if(!(t.durationHours===0?d!==0:l!==0||o!==0||a!==0))return Mp(e,t,i,r,s||c);let p=s?t:e,y=r.getClosestWorkTime({date:e.endDate,dir:"future",task:p});if(l!==0&&(y=r.calculateEndDate({startDate:y,durationHours:l,task:e})),o!==0&&(y=r.calculateEndDate({startDate:y,durationHours:o,task:t})),a!==0&&(y=r.calculateEndDate({startDate:y,durationHours:a,task:t})),t.durationHours===0){if(s||c)return{successorStart:r.getClosestWorkTime({date:y,dir:"past",task:t}),link:i};let g=new Date(Date.UTC(y.getUTCFullYear(),y.getUTCMonth(),y.getUTCDate()));return{successorStart:r.getClosestWorkTime({date:g,dir:"future",task:t}),link:i}}return{successorStart:r.getClosestWorkTime({date:y,dir:"future",task:t}),link:i}}function Os(e,t,i,r){let{sourceLag:n,targetLag:o,trueLag:a}=Ps(t,e,i),s=r.getClosestWorkTime({date:e.startDate,dir:"past",task:e});return a!==0&&(s=r.calculateEndDate({startDate:s,durationHours:-a,task:e})),o!==0&&(s=r.calculateEndDate({startDate:s,durationHours:-o,task:e})),n!==0&&(s=r.calculateEndDate({startDate:s,durationHours:-n,task:t})),s}function Ns(e,t,i){for(let r of e){let n=t.getActivity(r);if(!n)continue;let o=n.constraintType;if(!o||o===v.ASAP||o===v.ALAP)continue;let a=Za(n,t);!a.earliestStart&&!a.latestStart&&!a.earliestEnd&&!a.latestEnd||i.set(r,{activityId:r,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 Pr(e,t,i){let r={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=Jn(e.startDate,r):Qa(n,r)?o=n:o=Jn(n,r),t.startDate=o,t.endDate=i.calculateEndDate({startDate:o,durationHours:e.durationHours,task:e})}function bs(e,t){if(!e||!t)return new Date;let{constraintType:i,constraintDate:r}=e;if(!i||!r)return t;switch(i){case v.MSO:case v.MFO:return new Date(r);case v.SNET:case v.FNET:return r>t?new Date(r):t;case v.SNLT:case v.FNLT:return r<t?new Date(r):t;default:return t}}function Up(e,t){return t.length?t.some(i=>String(i)===String(e)):!1}function Fs(e,t,i){return uo(e.id,t,i)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function uo(e,t,i){return t.dragWithMultiple&&Up(e,i)}async function ws(e,t,i,r,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=i.getActivity(u);return p?{startDate:p.startDate,endDate:p.endDate}:{startDate:new Date,endDate:new Date}},c=i.getFlags(),l=r.draggedIds??[],d=performance.now();for(let u of e){let f=await vr(d,n);if(f.aborted)return o;d=f.newSliceStart;let p=i.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||Hp(p,i))continue;let y=a.get(String(u))??[],g=null,A=null,k=!1;for(let M of y){let D=i.getActivity(M.source);if(!D)continue;let C=s(M.source),L=C.startDate.getTime()!==D.startDate.getTime()||C.endDate.getTime()!==D.endDate.getTime(),K={...D,startDate:C.startDate,endDate:C.endDate},Y=Fs(K,c,l),it={...K,startDate:Y.startDate,endDate:Y.endDate},rt=uo(M.source,c,l)?{...M,lag:0}:M,vt=Ls(it,p,rt,i);(!g||vt.successorStart>g)&&(g=vt.successorStart,A=String(M.id),k=M._summaryTargetId!==void 0&&!L&&(M._targetLag===0||r.preventSummaryTargetPullback===!0))}g!==null&&k&&g<p.startDate&&(g=new Date(p.startDate));let F=o.get(u),m=F?{...F}:{activityId:u,startDate:p.startDate,endDate:p.endDate,drivingLinkId:null,kind:v.ASAP,conflict:!1},R=m.earliestStart||m.latestStart||m.earliestEnd||m.latestEnd;if(!(!g&&!R)){if(g){let M=g;p.type===T.MILESTONE&&(M=bs(p,g)),m.drivingLinkId=A,m.startDate=M,m.endDate=i.calculateEndDate({startDate:M,durationHours:p.durationHours,task:p}),m.earliestSchedulingStart=M,m.earliestSchedulingEnd=m.endDate}else p.constraintType===v.MSO?m.earliestStart&&(m.startDate=m.earliestStart,m.endDate=m.earliestEnd??i.calculateEndDate({startDate:m.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===v.MFO&&m.latestStart&&(m.startDate=m.latestStart,m.endDate=m.latestEnd??i.calculateEndDate({startDate:m.latestStart,durationHours:p.durationHours,task:p}));Pr(p,m,i),o.set(u,m)}}return o}function Hp(e,t){return zt(e.type,t.getChildren(e.id).length>0)}async function xs(e,t,i,r,n,o){let a=new Map(i),s=r.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 _=r.getActivity(A);return _?{startDate:_.startDate,endDate:_.endDate}:{startDate:new Date,endDate:new Date}},p=A=>!A.parentId||U(A.parentId)?r.getProjectEnd():f(A.parentId).endDate,y=(A,k)=>{let _=A,F=0;for(;_&&!U(_)&&F++<c+1;){if(String(_)===String(k))return!0;let m=r.getActivity(_);if(!m||!m.parentId)break;_=m.parentId}return!1},g=performance.now();for(let A of e){let k=await vr(g,o);if(k.aborted)return a;g=k.newSliceStart;let _=r.getActivity(A);if(!_||_.constraintType!==v.ALAP||!_.autoScheduling||_.progress===100||zt(_.type,r.getChildren(A).length>0))continue;let F=p(_);if(!F)continue;let m=F,R=null,M=!1,D=d.get(String(A))??[];for(let Gt of D){if((Gt.lag??0)<0)continue;let ei=r.getActivity(Gt.target);if(!ei||ei.autoScheduling===!1)continue;let Ja=f(Gt.target),If={...ei,startDate:Ja.startDate,endDate:Ja.endDate},lr=Os(If,_,Gt,r);lr<m&&(m=lr),(R===null||lr<R)&&(R=lr,M=_.parentId&&!U(_.parentId)?y(Gt.target,_.parentId):!1)}if(R!==null)if(M)m=R;else{let Gt=f(A).endDate,ei=Gt.getTime()>F.getTime()?Gt:F;m=R<ei?R:ei}else m>F&&(m=F);let L=(u.get(String(A))??[]).some(Gt=>Gt.type===B.FINISH_TO_START||Gt.type===B.FINISH_TO_FINISH),K=new Date(Date.UTC(m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate())),Y=()=>r.getClosestWorkTime({date:K,dir:"past",task:_}),it=r.getClosestWorkTime({date:m,dir:"future",task:_}).getTime()===m.getTime(),rt;_.durationHours===0&&R===null?rt=L&&it?Y():r.getClosestWorkTime({date:m,dir:"past",task:_}):_.durationHours===0?L?rt=Y():rt=r.getClosestWorkTime({date:m,dir:"future",task:_}):rt=r.getClosestWorkTime({date:m,dir:"future",task:_});let vt=r.calculateEndDate({startDate:rt,durationHours:-_.durationHours,task:_}),Ct=a.get(A),It=Ct?{...Ct}:{activityId:A,startDate:vt,endDate:rt,drivingLinkId:null,kind:v.ALAP,conflict:!1};It.startDate=vt,It.endDate=rt,It.drivingLinkId=null,It.kind=v.ALAP;let Qe=It.earliestSchedulingStart??null;It.earliestSchedulingStart=null,It.earliestSchedulingEnd=null;let ti=Qe!==null&&Qe.getTime()>vt.getTime()?Qe:vt;It.latestSchedulingStart=ti,It.latestSchedulingEnd=ti===vt?rt:r.calculateEndDate({startDate:ti,durationHours:_.durationHours,task:_}),Pr(_,It,r),a.set(A,It)}return a}var ci={warn(){},error(){}};var Bp=864e5;function te(e){if(e.type===T.MILESTONE)return 0;let t=e.startDate?.getTime(),i=e.endDate?.getTime();return t==null||i==null||Number.isNaN(t)||Number.isNaN(i)?null:Math.floor((i-t)/Bp)+1}function Wi(e,t){t.cancelled||t.updatedIds.length===0||e.batchUpdate(()=>{for(let i of t.updatedIds){let r=t.plans.get(i);if(!r)continue;let n=e.getLiveActivity(i);n&&(n.startDate=r.startDate,n.endDate=r.endDate,n.calendarDuration=te(n),e.updateActivity(i))}})}function fo(e,t){let i=String(t.source),r=String(t.target);if(i===r)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 Wp(n,r,i)}function Vi(e){let t=new Map,i=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),i.set(a,i.get(a)??0),i.set(s,(i.get(s)??0)+1)}let r=new Ut;for(let[o,a]of i)a===0&&r.enqueue(o);let n=0;for(;!r.isEmpty();){let o=r.dequeue();n+=1;for(let a of t.get(o)??[]){let s=i.get(a)-1;i.set(a,s),s===0&&r.enqueue(a)}}return n!==i.size}function Wp(e,t,i){if(t===i)return!0;let r=new Set([t]),n=new Ut;for(n.enqueue(t);!n.isEmpty();){let o=n.dequeue(),a=e.get(o)??[];for(let s of a){if(s===i)return!0;r.has(s)||(r.add(s),n.enqueue(s))}}return!1}function Lr(e){let t=Vp(e);for(let i of t.adjacency.keys())t.records.has(i)||jp(i,t);return t.components}function Vp(e){let t=new Map,i=new Set;for(let r of e){let n=String(r.source),o=String(r.target),a=Ms(t,n);if(Ms(t,o),n===o){i.add(n);continue}a.push(o)}return{adjacency:t,selfLooped:i,records:new Map,componentStack:[],nextIndex:0,components:[]}}function Ms(e,t){let i=e.get(t);if(i)return i;let r=[];return e.set(t,r),r}function jp(e,t){let i=[];for(i.push({node:e,record:Us(e,t),neighborCursor:0});i.length>0;){let r=i[i.length-1];if(r===void 0)break;let n=t.adjacency.get(r.node)??[];if(r.neighborCursor<n.length){let s=n[r.neighborCursor];if(r.neighborCursor+=1,s===void 0)continue;Kp(r,s,i,t);continue}i.pop();let o=i[i.length-1];o&&r.record.lowLink<o.record.lowLink&&(o.record.lowLink=r.record.lowLink),r.record.lowLink===r.record.visitIndex&&Yp(r.node,t)}}function Kp(e,t,i,r){let n=r.records.get(t);if(!n){i.push({node:t,record:Us(t,r),neighborCursor:0});return}n.onStack&&n.visitIndex<e.record.lowLink&&(e.record.lowLink=n.visitIndex)}function Us(e,t){let i={visitIndex:t.nextIndex,lowLink:t.nextIndex,onStack:!0};return t.nextIndex+=1,t.records.set(e,i),t.componentStack.push({node:e,record:i}),i}function Yp(e,t){let i=[];for(;;){let a=t.componentStack.pop();if(a===void 0||(a.record.onStack=!1,i.push(a.node),a.node===e))break}let r=i[0],n=i.length===1&&r!==void 0&&t.selfLooped.has(r);(i.length>1||n)&&t.components.push(i)}function ji(e,t,i){let r=i?new po(e,i):e;return kr([...t],r)}var po=class{constructor(t,i){this.base=t;for(let[r,n]of i.reparented){let o=String(r),a=n===null||U(n)?null:n,s=t.getActivity(r)?.parentId??null,c=s===null||U(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(r),this.movedInByParent.set(l,d)}}}}base;reparented=new Map;movedOutByParent=new Map;movedInByParent=new Map;withOverride(t){if(!t)return null;let i=this.reparented.get(String(t.id));return i===void 0?t:{...t,parentId:i}}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 i=String(t),r=this.movedOutByParent.get(i),n=this.base.getChildren(t),o=r?n.filter(s=>!r.has(String(s))):[...n],a=this.movedInByParent.get(i);return a&&o.push(...a),o}getParent(t){let i=this.reparented.get(String(t));return i===void 0?this.base.getParent(t):i===null?null:this.getActivity(i)}isChildOf(t,i){let r=String(i),n=new Set,o=this.getActivity(t);for(;o;){let a=o.parentId;if(a===null||U(a))return!1;let s=String(a);if(s===r)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 me(e){let{port:t,proposedPort:i,currentLinks:r,proposedLinks:n,proposal:o}=e,a=ji(i??t,n,o);if(!Vi(a))return{ok:!0};let s=ji(t,r),c=Hs(s),d=[...Hs(a)].filter(u=>!c.has(u));return d.length===0?{ok:!0}:{ok:!1,newlyCyclicActivityIds:d}}function Hs(e){let t=new Set;for(let i of Lr(e))for(let r of i)t.add(r);return t}function Ie(e,t){switch(e.kind){case St.CREATE:return Gp(e,t);case St.UPDATE:return $p(e,t.port);case St.DELETE:return zp(e,t)}}function br(e,t){if(e.length===0)return{applied:!0};let i=t.port.getAllLinks(),r=new Map,n=[];for(let l of i){let d=Nr(l);r.has(d)||r.set(d,l.id),n.push({source:l.source,target:l.target})}let o=Vi(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(_r(l.source,l.target,t.port)){a={applied:!1,rejected:st.HIERARCHY_LINK};break}let u=Nr(l),f=r.get(u);if(f!==void 0){a={applied:!1,rejected:st.DUPLICATE,linkId:f};break}if(r.set(u,d),o&&fo(n,{source:l.source,target:l.target}))return{applied:!1,rejected:st.CYCLE};n.push({source:l.source,target:l.target})}if(!o&&Vi(n))return{applied:!1,rejected:st.CYCLE};if(a)return a;let s=[...i,...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(!me({port:t.port,currentLinks:i,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 Nr(e){return JSON.stringify([String(e.source),String(e.target),e.type])}function Gp(e,t){let{port:i}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:st.SELF_LINK};let r=i.getActivity(e.source),n=i.getActivity(e.target);if(!r||!n)return{applied:!1,rejected:st.ACTIVITY_MISSING};if(_r(e.source,e.target,i))return{applied:!1,rejected:st.HIERARCHY_LINK};let o=i.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(fo(a,{source:e.source,target:e.target}))return{applied:!1,rejected:st.CYCLE};let s=(t.newLinkId??qp)(),c={id:s,source:e.source,target:e.target,type:e.type,lag:e.lag,freeSlackHours:null,isCritical:!1};return me({port:i,currentLinks:o,proposedLinks:[...o,c]}).ok?(i.addLink(c),{applied:!0,linkId:s}):{applied:!1,rejected:st.CYCLE}}function $p(e,t){let i=t.getLink(e.linkId);if(!i)return{applied:!1,rejected:st.LINK_MISSING};let r={...i,source:e.source??i.source,target:e.target??i.target,type:e.type??i.type,lag:e.lag??i.lag};if(String(r.source)===String(r.target))return{applied:!1,rejected:st.SELF_LINK};if(!t.getActivity(r.source)||!t.getActivity(r.target))return{applied:!1,rejected:st.ACTIVITY_MISSING};if(_r(r.source,r.target,t))return{applied:!1,rejected:st.HIERARCHY_LINK};let n=t.getAllLinks(),o=n.find(c=>String(c.id)!==String(e.linkId)&&Nr(c)===Nr(r));if(o)return{applied:!1,rejected:st.DUPLICATE,linkId:o.id};let a=n.map(c=>String(c.id)===String(e.linkId)?r:c);return me({port:t,currentLinks:n,proposedLinks:a}).ok?((String(i.source)!==String(r.source)||String(i.target)!==String(r.target))&&t.setLinkEndpoints(e.linkId,r.source,r.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 zp(e,t){let{port:i}=t;return i.getLink(e.linkId)?(i.removeLink(e.linkId),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:st.LINK_MISSING}}var Or=null;function qp(){return Or===null&&(Or=Date.now()),Or+=1,String(Or)}var Dt={FINISH_TO_START:"fs",START_TO_START:"ss",FINISH_TO_FINISH:"ff",START_TO_FINISH:"sf"},Fr={[B.FINISH_TO_START]:Dt.FINISH_TO_START,[B.START_TO_START]:Dt.START_TO_START,[B.FINISH_TO_FINISH]:Dt.FINISH_TO_FINISH,[B.START_TO_FINISH]:Dt.START_TO_FINISH},xe={[Dt.FINISH_TO_START]:B.FINISH_TO_START,[Dt.START_TO_START]:B.START_TO_START,[Dt.FINISH_TO_FINISH]:B.FINISH_TO_FINISH,[Dt.START_TO_FINISH]:B.START_TO_FINISH},Bs=Dt.FINISH_TO_START;function Ws(e){if(e in xe)return xe[e]}var Vs=";",ge={DAY:"d",WEEK:"w",WEEK_DHTMLX:"wk",MONTH:"m",MONTH_DHTMLX:"mon",YEAR:"y"},js=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)(weeks?|wk|w|months?|mon|m|days?|d|years?|y)?)?$/i;var Jp=5,wr=30,yo=365,Xp={[ge.DAY]:1,day:1,days:1,[ge.MONTH]:wr,[ge.MONTH_DHTMLX]:wr,month:wr,months:wr,[ge.YEAR]:yo,year:yo,years:yo},Zp=new Set([ge.WEEK,ge.WEEK_DHTMLX,"week","weeks"]);function xr(e,t={}){let i=[],r=[],n=t.daysPerWeek!==void 0&&Number.isFinite(t.daysPerWeek)&&t.daysPerWeek>0?t.daysPerWeek:Jp,o=e.replace(/\s+/g,"");if(o.length===0)return{specs:i,errors:r};for(let a of o.split(Vs)){if(a.length===0)continue;let s=Qp(a,n);s?i.push(s):r.push(a)}return{specs:i,errors:r}}function Qp(e,t){let i=e.toLowerCase(),r=js.exec(i);if(!r)return null;let[,n,o,a,s,c]=r,l=o?xe[o]:xe[Bs],d=0;if(s!==void 0){let u=Number(s);if(Number.isNaN(u))return null;let f=c!==void 0&&Zp.has(c)?t:Xp[c??ge.DAY],p=u*f;d=a==="-"?-p:p}return{correlativeId:n,type:l,lag:d}}function Ur(e){let{targetActivityId:t,currentLinks:i,desiredSpecs:r}=e,n=[],o=new Map;for(let c of r){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=Mr(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 i)String(c.target)===String(t)&&a.set(Mr(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 Mr(e,t){return`${String(e)}::${t}`}function Hr(e){let{sourceActivityId:t,currentLinks:i,desiredSpecs:r}=e,n=[],o=new Map;for(let c of r){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=Mr(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 i)String(c.source)===String(t)&&a.set(Mr(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 Br(e){let t=Math.sign(e)*Math.round(Math.abs(e));return Object.is(t,-0)?0:t}function Vt(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var Ks={rawInputToConstraintDate(e,t){let i=new Date(e);return i.setUTCHours(0,0,0,0),i.getTime()===e.getTime()?t.getClosestWorkTime({direction:j.FUTURE,date:e,unit:ut.HOUR}):t.isWorkTime(e,ut.HOUR)?e:i},computeLagBetweenTasks(e,t,i){return i.calculateDuration(e,t)}};function ho(e,t,i){switch(i){case B.FINISH_TO_START:return{sourceDate:e.endDate,targetDate:t.startDate};case B.START_TO_START:return{sourceDate:e.startDate,targetDate:t.startDate};case B.FINISH_TO_FINISH:return{sourceDate:e.endDate,targetDate:t.endDate};case B.START_TO_FINISH:return{sourceDate:e.startDate,targetDate:t.endDate}}}var mo=Ks;var li=class{adapter;reporter;currentCalculationId=0;topoCache=new Sr;expandedLinksCache=new Rr;constructor(t,i=ci){this.adapter=t,this.reporter=i}getCurrentCalculationId(){return this.currentCalculationId}invalidateTopoCache(){this.topoCache.invalidate()}invalidateExpandedLinksCache(){this.expandedLinksCache.invalidate()}invalidateAllCaches(){this.topoCache.invalidate(),this.expandedLinksCache.invalidate()}async schedule(t={}){let i=++this.currentCalculationId,r=Ss(i,()=>this.currentCalculationId),n={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{iy(this.adapter);let o=Ae("schedule.total"),a=Ae("schedule.expandParentLinks"),s=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(s,this.adapter);ae(a);let l=c;if((await si(r)).aborted)return{...n,cancelled:!0};let d=Ae("schedule.scoping"),u=this.adapter.getAllIds(),f=ry(t,l,this.adapter),p=f.links,y=f.idSet;ae(d);let g=Ae("schedule.topologicalSort"),A=oy(this.topoCache,u,l,y);if(ae(g),A.hasCycles)return ae(o),{...n,cycles:[A.cycleNodes]};if((await si(r)).aborted)return{...n,cancelled:!0};let k=Ae("schedule.processConstraints"),_=new Map;if(Ns(A.ordered,this.adapter,_),ae(k),(await si(r)).aborted)return{...n,cancelled:!0};let F=Ae("schedule.asapPass"),m=await ws(A.ordered,p,this.adapter,t,r,_);if(ae(F),(await si(r)).aborted)return{...n,cancelled:!0};let R=Ae("schedule.alapPass"),M=await xs(A.reversed,p,m,this.adapter,t,r);if(ae(R),(await si(r)).aborted)return{...n,cancelled:!0};let D=Ae("schedule.diff"),C=[];for(let[L,K]of M){let Y=this.adapter.getActivity(L);if(!Y)continue;let it=Y.startDate.getTime()!==K.startDate.getTime(),rt=Y.endDate.getTime()!==K.endDate.getTime();(it||rt)&&C.push(L)}return ae(D),ae(o),{plans:M,updatedIds:C,cycles:[],cancelled:!1}}catch(o){throw this.reporter.error("[AutoScheduler] Error during scheduling",o),o}}},ty=!1;function ey(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:ty}function Ae(e){return{name:e,startedAt:performance.now()}}function iy(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function ae(e){if(!ey())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function ry(e,t,i){let r=e.triggerId;if(r==null)return{idSet:null,links:t};let n=ks(r,t);return ny(n,t,i)}function ny(e,t,i){let r=new Set(e.activityIds),n=new Set;for(let a of i.getAllActivities()){let s=String(a.id);a.constraintType===v.ALAP&&!r.has(s)&&(n.add(s),r.add(s))}if(n.size===0)return{idSet:r,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:r,links:o}}function oy(e,t,i,r){let n=e.get(t,i);if(n.hasCycles){let a=r?Array.from(r):t;return Cr(a,i)}if(!r)return n;let o=Ts(n.ordered,r);return{ordered:o,reversed:[...o].reverse(),hasCycles:!1,cycleNodes:[]}}function Ys(e,t,i){let r=t.getActivity(e);if(!r)return;let n=i?{...r,endDate:i.endDate}:r,o=t.calendarReader.getCalendar(String(r.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||oe(r.type)&&(s.type===B.START_TO_FINISH||s.type===B.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=ho(c,n,s.type),f=mo.computeLagBetweenTasks(d,u,o);f!==s.lag&&t.setLinkField(s.id,wt.LAG,f)}}function Gs(e,t){let i=t.getActivity(e);i&&oe(i.type)&&(i.durationHours=0)}function Wr(e){let t=0,i=!1;for(let r of e)r.ponderator>0&&(t+=r.ponderator/100*r.progress,i=!0);return i?t:null}function $s(e){return Number(e.toFixed(2))}function Ki(e){for(let t of ay(e))qs(t,e)}function zs(e,t){for(let i of e)qs(i,t)}function ay(e){let t=new Set;e.forEachActivity((r,n)=>{e.getChildren(n).length>0&&t.add(n)});let i=new Map;for(let r of t)i.set(r,sy(r,e));return[...t].sort((r,n)=>(i.get(n)??0)-(i.get(r)??0))}function sy(e,t){let i=0,r=e;for(;r&&r!=="0"&&t.getActivity(r);)i+=1,r=t.getParentId(r);return i}function qs(e,t){let i=t.getChildren(e);if(i.length===0)return;let r=[];for(let n of i){let o=t.getActivity(n);o&&r.push({progress:Number(o.progress??0),ponderator:Number(o.ponderator??0)})}Io(e,r,t)}function Io(e,t,i){let r=i.getActivity(e);if(!r)return;let n=Wr(t);if(n===null){let o=i.getProgressFallback(e);o!==null&&i.setActivityField(e,E.PROGRESS,o);return}i.getProgressFallback(e)===null&&i.setProgressFallback(e,Number(r.progress??0)),i.setActivityField(e,E.PROGRESS,$s(n))}function Js(e,t,i){let r=[e];for(;r.length>0;){let n=r.pop();if(n===void 0)continue;let o=i.getChildren(n);o.length!==0&&(i.setProgressFallback(n,t),r.push(...o))}}function xt(e,t){return(Number(e)||0)*(Number(t)||0)/100}var Yi={SKIP:"skip",FREEZE_WITHOUT_CONTRIBUTION:"freeze-when-no-contribution"};async function di(e,t,i=!0,r={}){let n=t?Gi(e,t):py(e),o=i?r.progressMode??Yi.FREEZE_WITHOUT_CONTRIBUTION:Yi.SKIP;await cy(n,e,o,{recomputeRealWork:r.recomputeRealWork??!1})}function Vr(e,t){Xs(e,t,Yi.SKIP)}async function cy(e,t,i,r={recomputeRealWork:!1}){let o=0;for(let a of e)Xs(a,t,i,r.recomputeRealWork),o+=1,o%200===0&&await ct()}function Gi(e,t){let i=new Set,r=new Map;for(let a of t)ly(a,e,i,r);if(i.size===0)return[];let n=Array.from(i),o=dy(n,r);return Zs(n,o)}function ly(e,t,i,r){let n=t.getParentId(e);for(;n&&!U(n);){if(i.has(n))return;i.add(n);let o=t.getParentId(n);r.set(n,o),n=o}}function dy(e,t){let i=new Map;for(let r of e){if(i.has(r))continue;let n=[],o=new Set,a=r;for(;a&&!U(a)&&!i.has(a)&&!o.has(a);)n.push(a),o.add(a),a=t.get(a)??null;let s=a?i.get(a)??0:0;for(let c=n.length-1;c>=0;c-=1)s+=1,i.set(n[c],s)}return i}function uy(e,t,i){let r=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();(r===null||l<r)&&(r=l),(n===null||d>n)&&(n=d),i&&(o+=fy(c,t.getChildren(s).length>0)),a.push({progress:Number(c.progress??0),ponderator:Number(c.ponderator??0)})}return{minStart:r,maxEnd:n,realWorkSum:o,weightedChildren:a}}function Xs(e,t,i=Yi.FREEZE_WITHOUT_CONTRIBUTION,r=!1){let n=t.getActivity(e);if(!n)return;let o=t.getChildren(e);if(o.length===0)return;let a=uy(o,t,r);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),i!==Yi.SKIP&&Io(e,a.weightedChildren,t),r&&t.setActivityField(e,"realWorkHours",a.realWorkSum)}function fy(e,t){return t?Number(e.realWorkHours)||0:xt(e.workHours,e.progress)}function py(e){let t=yy(e),i=hy(t,e);return Zs(t,i)}function yy(e){let t=new Set;return e.forEachActivity(i=>{i.parentId!==null&&t.add(i.parentId)}),Array.from(t)}function hy(e,t){let i=new Map;for(let r of e)i.set(r,my(r,t));return i}function my(e,t){let i=0,r=e;for(;r&&!U(r)&&t.getActivity(r);)i+=1,r=t.getParentId(r);return i}function Zs(e,t){return[...e].sort((i,r)=>(t.get(r)??0)-(t.get(i)??0))}var Qs={updateActivityDuration:Gs,updateTaskTiming:gy("updateTaskTiming"),adjustLinkLagOnTaskMove:Ys,recordLastStartDate:Iy};function Iy(e,t){let i=t.getActivity(e);i&&t.setLastStartDate(e,i.startDate)}function ve(e,t,i,r){for(let n of t){let o=n in Qs?Qs[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,i,r??null)}}function gy(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 et(){return{valid:!0}}function yt(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function Z(){return{allowed:!0}}function at(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 ft={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 tc={targetField:"name",canEdit(){return Z()},parseInput(e){return typeof e!="string"?J("not_a_string"):G(e)},validate(){return et()},transform(e,t){return tt({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:ft.NAME_ENTRY};var ec={targetField:"description",canEdit(){return Z()},parseInput(e){return typeof e!="string"?J("not_a_string"):G(e.trim())},validate(){return et()},transform(e,t){return tt({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:ft.DESCRIPTION_ENTRY};function qt(e){return e.constraintType??v.ASAP}var jr=100;function Ce(e){return e.progress>=jr}function ht(e,t){return zt(e.type,t.hasChildren(e.id))}function ic(e){return e.progress>0}function rc(e){return e.hasLookaheadTasks}function Me(e,t){return Math.round(Math.ceil(e*t*60)/60)}var ui=e=>({endDate:e});var Kr="UTC";function Se(e,t){if(t){let i=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),r=n=>Number(i.find(o=>o.type===n)?.value);return new Date(Date.UTC(r("year"),r("month")-1,r("day")))}return new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()))}function Yr(e,t){if(!t||t===Kr){let f=new Date(e);return f.setUTCHours(23,59,0,0),f}let i=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),r=f=>Number(i.find(p=>p.type===f)?.value),n=r("year"),o=r("month"),a=r("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 Ay(e,t){let i=Se(t,Kr);for(;!e.isWorkTime(i,ut.DAY);)i=new Date(i),i.setUTCDate(i.getUTCDate()+1),i=Se(i,Kr);return i}function go(e,t){return e.getClosestWorkTime({direction:j.FUTURE,date:t,unit:ut.HOUR})}function Ao(e,t){let i=Ay(e,t),r=new Date(i);return r.setUTCDate(r.getUTCDate()+1),r.setUTCHours(0,0,0,0),e.getClosestWorkTime({direction:j.PAST,date:r,unit:ut.HOUR})}var $i=new Set([v.SNET,v.SNLT,v.MSO]),vo=new Set([v.FNET,v.FNLT,v.MFO]),Te=new Set([v.ASAP,v.ALAP]),Gr=v.SNET;function se(e,t,i){let r=Se(e,Kr);if(!$i.has(i)&&!vo.has(i))return r;let n=$i.has(i)?go(t,r):Ao(t,r),o=new Date(r);return o.setUTCHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),o}var De=()=>({constraintType:Gr});var Ue=e=>({constraintDate:e}),nc=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 ac={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"},zi={COMPLETED:"completed",SUMMARY:"summary",HAS_PROGRESS:"has_progress",HAS_LOOKAHEAD_TASKS:"has_lookahead_tasks",SIR_START_AFTER_PROGRESS:"sir_start_after_progress"},sc={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 fi(e,t,i){return fr(e,t,i)}function pi(e,t,i){return pr(e,t,i)}var lc={targetField:"durationHours",canEdit(e,t){return Ce(e)?at("completed","cant_edit_completed_activity"):ht(e,t)?at("summary","summary_column_value"):Z()},parseInput(e,t,i){let r=parseFloat(String(e));return Number.isFinite(r)?G(Me(r,i.hoursPerDay)):J("not_a_number")},validate(e,t,i){return cc(i)?yt(ac.NEGATIVE_DURATION):vy(t,i)?yt("unchanged"):et()},transform(e,t,i){if(cc(t))return tt({},{autoSchedule:!1,postProcessors:[]});let r=Cy(e,t,i),n=Sy(e,t,i,r.violated);return{...tt(n,{autoSchedule:!0,postProcessors:[oc.RECORD_LAST_START_DATE]}),...r.violated?{constraintWarning:pi(r.constraintType,r.constraintDate,dc(e,t,i)??void 0)}:{}}},trackEvent:ft.DURATION_ENTRY};function cc(e){return Math.sign(e)===-1}function vy(e,t){return e===t}function Cy(e,t,i){let r=i.calendars.getCalendar(e.calendarId);if(!r)return{violated:!1};let n=e.constraintType;if(n!==v.FNET&&n!==v.FNLT&&n!==v.MFO)return{violated:!1};let o=r.calculateEndDate(e.startDate,t);return fi(n,e.constraintDate,o)}function Sy(e,t,i,r=!1){let n={};r&&Object.assign(n,De(),Ue(e.startDate));let o=Hi(e.durationHours,t);o&&(n.type=o),n.durationHours=t;let a=dc(e,t,i);return a&&Object.assign(n,ui(a)),n}function dc(e,t,i){let r=i.calendars.getCalendar(e.calendarId);return r?r.calculateEndDate(e.startDate,t):null}var yi=e=>({realWorkHours:e});var Ty=0,Dy=jr,$r={targetField:"progress",canEdit(e,t){return ht(e,t)?at("summary","summary_column_value"):rc(e)?at("has_lookahead_tasks","cant_edit_actvity_with_task"):Z()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?J("not_a_number"):G(t)},validate(e,t,i){return Ey(i)?yt("out_of_range"):et()},transform(e,t,i){let r=we(t),n=e.progress!==t&&r,o=_y(t),a=Py(e,t,i.hierarchy),s={progress:t,autoScheduling:r,...yi(a.get(e.id)??0)},c=o?ky(e,t,r,i.hierarchy,a):[],l=o?Oy(e,t,i.hierarchy):[],d=c.length+l.length>0?[...c,...l]:void 0,u=[],f=o?by(e,t):void 0;return tt(s,{autoSchedule:n,postProcessors:u,cascadeMutations:d,trackingEvents:f})},trackEvent:ft.PROGRESS_ENTRY};function Ey(e){return e<Ty||e>Dy}function _y(e){return e===jr||we(e)}function ky(e,t,i,r,n){return r.getDescendantIds(e.id).map(a=>({activityId:a,fields:Ry(t,i,n.get(a)??0)}))}function Ry(e,t,i){return{progress:e,autoScheduling:t,...yi(i)}}function Py(e,t,i){let r=new Map,n=a=>{let s=0;for(let c of i.getChildHhInfo(a)){let l=i.hasChildren(c.id)?n(c.id):xt(c.workHours,t);r.set(c.id,l),s+=l}return s},o=i.hasChildren(e.id)?n(e.id):xt(e.workHours,t);return r.set(e.id,o),r}function Ly(e,t){let i=[e.id,...t.getDescendantIds(e.id)],r=o=>t.getChildProgressInfo(o).some(a=>t.hasChildren(a.id)),n=o=>t.getAncestorIds(o).length;return i.filter(o=>r(String(o))).map(String).sort((o,a)=>n(a)-n(o))}function Oy(e,t,i){let r=new Map;r.set(e.id,t);for(let a of i.getDescendantIds(e.id))r.set(a,t);let n=[...Ly(e,i),...i.getAncestorIds(e.id)],o=[];for(let a of n){let s=Ny(a,r,i);s!==null&&(r.set(a,s),o.push({activityId:a,fields:{progress:s}}))}return o}function Ny(e,t,i){let r=i.getChildProgressInfo(e).map(o=>({progress:t.has(o.id)?t.get(o.id):o.progress,ponderator:o.ponderator??0})),n=Wr(r);return n===null?null:Number(n.toFixed(2))}function by(e,t){return[{name:ft.PROGRESS_UPDATE_RADIO_BUTTON,properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var uc={targetField:"cost",canEdit(e,t){return ht(e,t)?at("summary","summary_column_value"):Z()},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 et()},transform(e,t,i){let r=Fy(e,t,i.hierarchy);return tt({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:r})},trackEvent:ft.COST_BUDGETED_ENTRY};function Fy(e,t,i){let r=new Map;r.set(e.id,t);let n=[];for(let o of i.getAncestorIds(e.id)){let a=0;for(let s of i.getChildCostInfo(o))a+=r.has(s.id)?r.get(s.id):s.cost;r.set(o,a),n.push({activityId:o,fields:{cost:a}})}return n}var fc={targetField:"usedCost",canEdit(e,t){return ht(e,t)?at("summary","summary_column_value"):Z()},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 et()},transform(e,t,i){let r=wy(e,t,i.hierarchy);return tt({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:r})},trackEvent:ft.COST_SPENT_ENTRY};function wy(e,t,i){let r=new Map;r.set(e.id,t);let n=[];for(let o of i.getAncestorIds(e.id)){let a=0;for(let s of i.getChildUsedCostInfo(o))a+=r.has(s.id)?r.get(s.id):s.usedCost;r.set(o,a),n.push({activityId:o,fields:{usedCost:a}})}return n}var pc={targetField:"workHours",canEdit(e,t){return ht(e,t)?at("summary","summary_column_value"):Z()},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 et()},transform(e,t,i,r){let n=yc(t,e.progress),o=String(r).trim()===""?[]:xy(e,t,n,i.hierarchy);return tt({workHours:t,...yi(n)},{autoSchedule:!1,postProcessors:[],cascadeMutations:o})},trackEvent:ft.LABOR_HOURS_BUDGETED_ENTRY};function yc(e,t){return xt(e,t)}function xy(e,t,i,r){let n=new Map,o=new Map;n.set(e.id,t),o.set(e.id,i);let a=[];for(let s of r.getAncestorIds(e.id)){let c=0,l=0;for(let d of r.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??yc(d.workHours,d.progress);c+=u,l+=f}n.set(s,c),o.set(s,l),a.push({activityId:s,fields:{workHours:c,...yi(l)}})}return a}function qi(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function Co(e,t){return e.getTime()<t.getTime()}function He(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var zr=e=>({durationHours:e});var My="sir-apply",hc={targetField:"startDate",canEdit(e,t,i){return ht(e,t)?at("summary","summary_column_value"):ic(e)?i?.eventSource!==My?at("has_progress","cant_edit_activity_with_progress"):Ce(e)?at("completed","cant_edit_completed_activity"):He(i.newValue)?qi(e.startDate,i.newValue)?Z():i.newValue.getTime()>e.startDate.getTime()?at("sir_start_after_progress","sir_cant_move_start_after_progress"):Z():Z():Z()},parseInput(e,t,i){return He(e)?G(Se(e,"UTC")):J("invalid_date")},validate(e,t,i,r){if(qi(t,i))return yt("unchanged");let n=Uy(e,i,r);return n||et()},transform(e,t,i){let r=i.calendars.getCalendar(e.calendarId);if(!r)throw new Error("startDatePipeline: no calendar resolved (integrity)");let n=go(r,t),o=e.type===T.MILESTONE,a=o?n:r.calculateEndDate(n,e.durationHours),s=n;return{...tt({startDate:n,...ui(a),...o?zr(0):{},...De(),...Ue(s)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:Hy(e,n,r)}},trackEvent:ft.START_DATE_ENTRY};function Uy(e,t,i){let r=i.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!r)return null;let n=Se(r,"UTC");return t.getTime()<n.getTime()?yt("before_parent_start"):null}function Hy(e,t,i){let r=i.calculateEndDate(t,e.durationHours),n=Oe(qt(e),t,r),o=fi(qt(e),e.constraintDate,n);if(o.violated)return pi(o.constraintType,o.constraintDate,n)}var By=99.999,Ic={targetField:"endDate",canEdit(e,t){return ht(e,t)?at("summary","summary_column_value"):Wy(e)?at("completed","cant_edit_completed_activity"):Z()},parseInput(e,t,i){if(!He(e))return J("invalid_date");let r=Se(e,"UTC"),n=i.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(r,ut.DAY)?G(Ao(n,r)):G(n.getClosestWorkTime({direction:"past",date:r,unit:ut.HOUR})):G(r)},validate(e,t,i,r){if(qi(e.endDate,i))return yt("unchanged");if(Vy(i,e))return yt("before_date_origin");if(jy(i,e))return yt("before_start_date");let n=Ky(i,e,r);return n||et()},transform(e,t,i){let r=Yy(e,t),n=Gy(e,t,i,!!r);return{...tt(n,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...r?{constraintWarning:r}:{}}},trackEvent:ft.END_DATE_ENTRY};function Wy(e){return e.progress>=By}function Vy(e,t){return t.dateOrigin?Co(e,t.dateOrigin):!1}function jy(e,t){return Co(e,t.startDate)}function Ky(e,t,i){let r=i.calendars.getCalendar(t.calendarId);return r?r.isWorkTime(e,ut.DAY)?null:yt("not_working_day"):null}function Yy(e,t){if(qt(e)===v.MSO)return;let r=Oe(qt(e),e.startDate,t),n=fi(qt(e),e.constraintDate,r);if(n.violated)return pi(n.constraintType,n.constraintDate,r)}function Gy(e,t,i,r=!1){let n={};oe(e.type)&&!r&&mc(e)?Object.assign(n,Ue(e.startDate)):(r||mc(e))&&Object.assign(n,De(),Ue(e.startDate));let s=$y(e,t,i),c=Hi(e.durationHours,s);return c&&(n.type=c),Object.assign(n,zr(s)),n.endDate=t,n}function mc(e){return Te.has(qt(e))}function $y(e,t,i){let r=i.calendars.getCalendar(e.calendarId);return r?r.calculateDuration(e.startDate,t):e.durationHours}var zy=new Set(Object.values(v)),gc={targetField:"constraintType",canEdit(e,t){return Ce(e)?at("completed","cant_edit_completed_activity"):ht(e,t)?at("summary","summary_column_value"):Z()},parseInput(e){let t=String(e).toLowerCase();return qy(t)?G(t):J("invalid_constraint_type")},validate(){return et()},transform(e,t,i){let r=Jy(e,t,i);return tt(r,{autoSchedule:!0})}};function qy(e){return zy.has(e)}function Jy(e,t,i){let r=Zy(e,t);return{constraintType:t,...nc(Xy(e,t,r,i))}}function Xy(e,t,i,r){if(e.type!==T.MILESTONE||!i||$i.has(t))return i;let n=r.calendars.getCalendar(String(e.calendarId));return n?se(i,n,t):i}function Zy(e,t){return Te.has(t)?null:$i.has(t)?e.startDate:vo.has(t)?e.endDate:e.constraintDate}var Ac={targetField:"constraintDate",canEdit(e,t){return Ce(e)?at("completed","cant_edit_completed_activity"):ht(e,t)?at("summary","summary_column_value"):Z()},parseInput(e){return He(e)?G(e):J("invalid_date")},validate(){return et()},transform(e,t,i){let r=vc(e)?Gr:qt(e),n=i.calendars.getCalendar(e.calendarId);if(!n)throw new Error("constraintDatePipeline: no calendar resolved (integrity)");let o=se(t,n,r),a=Qy(e,o);return tt(a,{autoSchedule:!0})}};function Qy(e,t){return{constraintDate:t,...vc(e)?De():{}}}function vc(e){return Te.has(qt(e))||!e.constraintType}var Cc={targetField:"calendarId",canEdit(){return Z()},parseInput(e){let t=String(e).trim();return th(t)?J("empty_calendar"):G(t)},validate(e,t,i,r){return eh(e.calendarId,i)?yt("unchanged"):r.calendars.getCalendar(i)?et():yt("unknown_calendar")},transform(e,t,i){return tt(ih(e,t,i),{autoSchedule:!0,postProcessors:[]})},trackEvent:ft.CALENDAR_ASSIGNMENT};function th(e){return e===""}function eh(e,t){return e===t}function ih(e,t,i){let r={calendarId:t,assignedDefaultCalendar:!1},n=i.calendars.getCalendar(t);if(n){let o=n.isWorkTime(e.startDate,"hour"),a=n.getClosestWorkTime({date:o?Sc(e.startDate):e.startDate,direction:"future",unit:"hour"});r.startDate=a;let s=rh(e,n);if(s&&(r.constraintDate=s),!e.autoScheduling)return r;Object.assign(r,ui(n.calculateEndDate(a,e.durationHours)))}return r}function rh(e,t){return!e.constraintDate||!e.constraintType?null:wi({...e,constraintDate:Sc(e.constraintDate)},{getClosestWorkTime:({date:i,dir:r})=>t.getClosestWorkTime({date:i,direction:r,unit:ut.HOUR})})}function Sc(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var Tc={targetField:"customId",canEdit(e,t){return ht(e,t)?at("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"):G(t)},validate(){return et()},transform(e,t){return tt({customId:t},{autoSchedule:!1,postProcessors:[]})}};var Dc={targetField:"subcontractId",canEdit(){return Z()},parseInput(e){if(e==null)return G(null);if(typeof e=="string"){let t=e.trim();if(t.length===0)return G(null);let i=Number(t);return!Number.isFinite(i)||!Number.isInteger(i)?J("not_an_integer"):G(i)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?J("not_an_integer"):G(e):J("not_an_integer")},validate(){return et()},transform(e,t){return tt({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function Ji(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 qr(e){return e.some(t=>Ji(t)===null)}var Ec={targetField:"responsableIds",canEdit(){return Z()},parseInput(e){return e==null?G([]):Array.isArray(e)?G(e):J("not_an_array")},validate(e,t,i){return qr(i)?yt("missing_id"):et()},transform(e,t){let i=t.map(Ji).filter(r=>r!==null);return tt({responsableIds:i},{autoSchedule:!1,postProcessors:[]})}};var _c={targetField:"tagIds",canEdit(){return Z()},parseInput(e){return e==null?G([]):Array.isArray(e)?G(e):J("not_an_array")},validate(e,t,i){return qr(i)?yt("missing_id"):et()},transform(e,t){let i=t.map(Ji).filter(r=>r!==null);return tt({tagIds:i},{autoSchedule:!1,postProcessors:[]})}};var nh=new Map([[E.TEXT,tc],[E.DESCRIPTION,ec],[E.DURATION,lc],[E.PROGRESS,$r],[E.COST,uc],[E.USED_COST,fc],[E.HH_WORK_TIME,pc],[E.START_DATE,hc],[E.END_DATE,Ic],[E.CONSTRAINT_TYPE,gc],[E.CONSTRAINT_DATE,Ac],[E.CALENDAR_ID,Cc],[E.CUSTOM_ID,Tc],[E.SUBCONTRACT_ID,Dc],[E.RESPONSABLES,Ec],[E.TAGS,_c]]);function Ee(e){return nh.get(e)}var mt={APPEND:"append",REPLACE:"replace"},Jr={ACTION_BUTTON:"action-button"},Xr={SIR_AUTO_REJECT:"sir-auto-reject"},Zr={DATE_CHANGED:"date_changed",ACTIVITY_DELETED:"activity_deleted"},We={VIOLATION:"constraint_violation"},ee={DISPATCH_MANY:"dispatch-many",INIT:"init",UNDO:"undo",REDO:"redo"};function Ve(e,t){if(!t||t.type!==dr.CONSTRAINT)return null;let i=t.data;return!i?.constraintType||!i.constraintDate?null:{kind:We.VIOLATION,activityId:e,constraintType:i.constraintType,constraintDate:i.constraintDate,projectedDate:i.projectedDate??i.constraintDate,messageKey:t.messageKey}}var oh=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],kc=new Set(oh);function lt(e,t,i,r){e.setActivityFieldDynamic(t,i,r)}function Rc(e,t,i,r){e.setLinkFieldDynamic(t,i,r)}function ce(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:ie(e.constraintDate),dateOrigin:ie(e.dateOrigin),newActivityIds:[...e.newActivityIds],pendingRequestIds:[...e.pendingRequestIds],responsableIds:[...e.responsableIds],tagIds:[...e.tagIds],baselinePoints:e.baselinePoints.map(t=>({...t,startDate:ie(t.startDate),endDate:ie(t.endDate)})),baselineSnapshot:ah(e.baselineSnapshot),criticalPath:sh(e.criticalPath)}}function ie(e){return e===null?null:new Date(e)}function ah(e){return e===null?null:{...e,startDate:ie(e.startDate),endDate:ie(e.endDate)}}function sh(e){return e===null?null:{...e,earlyStart:ie(e.earlyStart),earlyFinish:ie(e.earlyFinish),lateStart:ie(e.lateStart),lateFinish:ie(e.lateFinish)}}var Oc=200;function _e(e,t){let i=new Set([String(e)]);for(let r of t.cascadeMutations??[])i.add(String(r.activityId));return i}async function Q(e,t){let i=new Map,r=0;for(let n of t){r+=1,r%Oc===0&&await ct();let o=e.getActivity(n);o&&i.set(n,nt(o))}return i}function nt(e){return ce(e)}function Qr(e,t){let i=e.getActivity(t);return i?ce(i):null}function ke(e,t,i){Pc(e,t,i.patch);for(let r of i.cascadeMutations??[])Pc(e,r.activityId,r.fields)}function Pc(e,t,i){for(let[r,n]of Object.entries(i)){if(!kc.has(r))throw new Error(`applyFieldChanges: column write to non-writable field "${r}"`);lt(e,t,r,n)}}async function tn(e,t,i,r){let n=[],o=0;for(let a of i){o+=1,o%Oc===0&&await ct();let s=ch(e,t,a,r);s&&n.push(s)}return n}function ch(e,t,i,r){let n=e.getActivity(i);if(!n)return{id:i,kind:N.DELETED,after:null};let o=t.get(i);if(!o&&r?.has(i))return lh(i,r.get(i),n);let a=To(o,n);return dh(a,r,i,n),o&&Object.keys(a).length===0?null:{id:i,kind:o?N.UPDATED:N.CREATED,fields:a,after:nt(n)}}function lh(e,t,i){return t===i.correlativeId?null:{id:e,kind:N.UPDATED,fields:{correlativeId:{before:t,after:i.correlativeId}},after:nt(i)}}function dh(e,t,i,r){if(!t?.has(i)||Object.hasOwn(e,"correlativeId"))return;let n=t.get(i);n!==r.correlativeId&&(e.correlativeId={before:n,after:r.correlativeId})}function To(e,t){let i={},r=e??{},n=t,o=new Set([...Object.keys(r),...Object.keys(n)]);o.delete(b.CALENDAR_DURATION);for(let a of o)(Object.hasOwn(r,a)!==Object.hasOwn(n,a)||!So(r[a],n[a]))&&(i[a]={before:Lc(r[a]),after:Lc(n[a])});return i}function Lc(e){return e===null||typeof e!="object"?e:w(e)}function So(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)=>So(a,t[s]));if(typeof e!="object"||typeof t!="object")return!1;let i=e,r=t,n=Object.keys(i),o=Object.keys(r);return n.length!==o.length?!1:n.every(a=>Object.hasOwn(r,a)&&So(i[a],r[a]))}function en(e,t,i){let r=new Set;r.add(e);for(let n of t)r.add(n);for(let n of i)r.add(n);return r}function Do(e,t){let i=new Set;for(let r of e)i.add(String(r));for(let r of t)i.add(r);return i}function hi(e,t,i,r,n){for(let o of t){if(i.has(o.activityId)||(n.add(o.activityId),r.has(o.activityId)))continue;let a=e.getActivity(o.activityId);if(!a)continue;let s=nt(a);o.before!==void 0&&(s.correlativeId=o.before),r.set(o.activityId,s)}}var uh=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function le(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(uh);if(!t)throw new Error(`[parseFromBackend] unsupported date format "${e}" (expected "YYYY/MM/DD H:MM" or ISO)`);let[,i,r,n,o,a]=t;return new Date(Date.UTC(Number(i),Number(r)-1,Number(n),Number(o),Number(a)))}function mi(e,t,i,r){if(e.getTime()>i.getTime())return 0;if(t.getTime()<i.getTime()||e.getTime()===t.getTime())return 100;let n=r.calculateDuration(e,i),o=r.calculateDuration(e,t);return o===0?0:n*100/o}var fh=e=>e.type===T.PROJECT,ph=(e,t,i)=>{let r=e.calendarId,n=r!=null?i.calendarReader.getCalendar(String(r)):null;if(!n)return 0;let o=a=>a instanceof Date?a:le(String(a));return mi(o(e.startDate),o(e.endDate),t,n)};function yh(e,t,i){let r=[],n=(a,s)=>{let c=i.getActivity(a);c&&c.expectedProgress!==s&&(i.setActivityField(a,"expectedProgress",s),r.push(String(a)))},o=a=>{let s=i.getActivity(a);if(!s)return 0;if(!fh(s)){let d=ph(s,t,i);return n(a,d),d}let c=0;for(let d of i.getChildren(a)){let u=o(d),f=i.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 r}function je(e,t){let i=[];e.forEachActivity((r,n)=>{r.parentId===null&&i.push(n)}),yh(i,t,e)}var hh=e=>e.type===T.PROJECT,mh=e=>gt(e),Ih=(e,t,i,r)=>{let n=mh(e);if(!n)return 0;let o=(n.baseCalendarId!=null?i.getBaseCalendar(`${n.baseCalendarId}-base`):null)??(r?i.getBaseCalendar(r):null);return!o||!n.startDate||!n.endDate?0:mi(n.startDate,n.endDate,t,o)};function Eo(e,t,i,r=null){let n=[],o=(s,c)=>{let l=i.getActivity(s);l&&l.expectedProgressBaseline!==c&&(i.setActivityField(s,"expectedProgressBaseline",c),n.push(s))},a=s=>{let c=i.getActivity(s);if(!c)return 0;if(!hh(c)){let u=Ih(c,t,i,r);return o(s,u),u}let l=0;for(let u of i.getChildrenIds(s)){let f=a(u),p=i.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 Ii(e,t,i=null){let r={getChildrenIds:o=>e.getChildren(String(o)).map(a=>String(a)),getActivity:o=>e.getActivity(o),setActivityField:(o,a,s)=>lt(e,o,a,s),getBaseCalendar:o=>e.calendarReader.getCalendar(o)},n=[];return e.forEachActivity((o,a)=>{o.parentId===null&&n.push(a)}),Eo(n,t,r,i)}var _o=fe.BASELINE;function rn(e){return e===fe.ACTUAL?fe.ACTUAL:_o}var Nc=e=>Math.round(e*100)/100;function gh(e,t){return(t===fe.BASELINE?e.expectedProgressBaseline:e.expectedProgress)??void 0}function Ah(e,t){let i=Nc(e),r=Nc(t);return i>99.99?Pt.DONE:r>i?Pt.OVERDUE:e>0&&i>r?Pt.ADVANCEMENT:e===0&&t===0?Pt.WAITING:e>0&&i<r?Pt.DOING:Pt.WAITING}function de(e,t){let i=[];return e.forEachActivity((r,n)=>{let o=typeof r.progress=="number"?r.progress:0,a=Ah(o,gh(r,t));r.status!==a&&(lt(e,n,E.STATUS,a),i.push(n))}),i}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),i=(n,o)=>a=>a===void 0?t[n]():(t[o](a),r),r={__isMomentShim:!0,clone:()=>ko(t),hours:i("getUTCHours","setUTCHours"),minutes:i("getUTCMinutes","setUTCMinutes"),seconds:i("getUTCSeconds","setUTCSeconds"),milliseconds:i("getUTCMilliseconds","setUTCMilliseconds"),valueOf:()=>t.getTime(),toDate:()=>new Date(t.getTime()),getTime:()=>t.getTime()};return r}ko.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var jt=ko;function vh(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function nn(e){return vh(e)&&!isNaN(e.getTime())}function P(e,t,i,r){if(!nn(new Date(t)))throw new Error(`Invalid date argument for calculateEndDate method. Date: ${t}, Activity: ${JSON.stringify(r)}`);let n=t;return e.calculateEndDate({start_date:new Date(n),duration:i,unit:"hour",task:r})}function Ht(e){if(!nn(new Date(e.dateBaseToCalculate)))throw new Error("Invalid date argument for getClosestWorkTime method");let{dateBaseToCalculate:t,activityCalendar:i,direction:r,activity:n}=e;return i.$gantt.getClosestWorkTime({date:new Date(t),dir:r,unit:"hour",task:n})}var h=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 Ke(e){return Fr[String(Number(e))]??Dt.START_TO_FINISH}var q=Object.freeze({FORWARD:"forward",BACKWARD:"backward"}),Ye=Object.freeze({GREATER:"greater",LESS:"less"}),Jt=Object.freeze({SOURCE:"$source"});var Ch=e=>e?e.$level===1:!1,Sh=e=>e.type===T.PROJECT,Th=e=>e.$level!==0,Dh=e=>e.type===T.TASK,Eh=e=>e.type===T.TASK||e.type===T.MILESTONE,bt={byFirstLevel:Ch,filterByParentType:Sh,avoidSubproject:Th,byTaskType:Dh,byTaskTypeAndMilestone:Eh};function bc(e){let{gantt:t,pendingParentsWithNoLinks:i,calculations:r,linkProperty:n}=e;try{let o=_h({gantt:t,pendingParentsWithNoLinks:i});if(o.length===0)return new Set;let a=kh({gantt:t,subprojectsWithNoLinks:o}),s=Rh({gantt:t,childrenIds:a,linkProperty:n,getArrayOfLinkedActivities:Ph,calculations:r});return new Set(s.map(c=>c.id))}catch(o){throw o}}function _h(e){let{gantt:t,pendingParentsWithNoLinks:i}=e;return t.getTaskByTime().filter(bt.filterByParentType).filter(r=>i.has(r.id)).map(r=>r.id)}function kh(e){let{gantt:t,subprojectsWithNoLinks:i}=e,r=new Set;for(let n of i)t.getChildren(n).filter(s=>{let c=t.getTask(s),l=bt.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(s=>r.add(s));return[...r]}function Rh(e){let{gantt:t,childrenIds:i,linkProperty:r,getArrayOfLinkedActivities:n,calculations:o}=e,a=[];for(let s of i){let c=t.getTask(s),l=c[r]||[];n({gantt:t,links:l,linkDirection:r===Jt.SOURCE?"target":"source"}).every(f=>o.has(f))&&a.push(c)}return a}function Ph(e){let{gantt:t,links:i,linkDirection:r}=e,n=[];for(let o of i){let a=t.getLink(o);if(!a){`${o}`;continue}let s=Number(a[r]);n.push(s)}return n}function Fc({gantt:e,linkProperty:t,direction:i}){try{let r=Lh(e,t);if(i===q.FORWARD)return{chainStartActivities:r,activitiesStartChainButChildrenOfLinkedParents:null};if(i===q.BACKWARD)return Oh(r,e,t)}catch(r){throw console.log("Critical Path",r),r}}function Lh(e,t){return e.getTaskByTime().filter(bt.avoidSubproject).filter(bt.byTaskTypeAndMilestone).filter(i=>!i[t].length)}function Oh(e,t,i){let r=[],n=new Set;return e.forEach(o=>{let a=Number(o.parent),s=t.getTask(a);s&&(s[i].length>0?n.add(o.id):s.constraint_type!==h.FNLT&&r.push(o))}),{chainStartActivities:r,activitiesStartChainButChildrenOfLinkedParents:n}}function wc({gantt:e,direction:t,linkProperty:i}){try{let r=Nh(e),n=new Set,o=new Set,a=new Set;t===q.BACKWARD&&wh(r).forEach(d=>{n.add(d.id)});let s=bh(r,t,i),c=Fh(r,s);return s.forEach(l=>{o.add(l.id)}),c.forEach(l=>{a.add(l.id)}),{parentsWithFullProgress:n,pendingParentsWithNoLinks:o,pendingParentsWithLinks:a}}catch(r){throw r}}function Nh(e){return e.getTaskByTime().filter(bt.filterByParentType).filter(bt.avoidSubproject)}function bh(e,t,i){return e.filter(r=>{let n=r[i];if(!Array.isArray(n))return!1;let o=n.length>0,a=r.constraint_type||"",s=a!==h.FNLT;if(t===q.FORWARD){let c=a!==h.SNET;return!o&&s&&c}else return!o&&s})}function Fh(e,t){let i=new Set(t.map(r=>r.id));return e.filter(r=>!i.has(r.id))}function wh(e){return e.filter(t=>{let i=Number(t.progress);return Number.isNaN(i)?!1:i===100})}function xc({pendingParentsWithLinks:e,gantt:t,direction:i}){try{let r=new Set;return e.forEach(n=>{let o=t.getTask(n),a=xh(i),s=Mh(i),c=o[a];if(!Array.isArray(c))return;Uh(t,c,s).forEach(d=>{r.add(d)})}),r}catch(r){throw r}}function xh(e){return e===q.FORWARD?Jt.SOURCE:"$target"}function Mh(e){return e===q.FORWARD?"target":"source"}function Uh(e,t,i){return t.map(r=>{let o=e.getLink(r)[i];return Number(o)})}var Xi={identifySecondLevelActivities:bc,identifyInitialActivities:Fc,identifyParentsWithAndWithoutLinks:wc,identifyForbiddenActivities:xc};function on(e){return e.length?e.reduce((t,i)=>i.ef>t.ef?i:t):!1}function Ro({linkType:e,lag:t,predecessorTime:i,activityCalendar:r,activity:n}){return e===H.FS&&t===0?Ht({predecessorTime:i,activityCalendar:r,direction:"future",activity:n}):Zi(i,e,r,n)}function Mc({duration:e,constraintDate:t,activityCalendar:i,activity:r}){let n=new Date(t);return{es:P(i,n,e,r),ef:n}}function Uc({duration:e,constraintDate:t,activityCalendar:i,activity:r}){let n=new Date(t),o=P(i,n,e,r);return{es:n,ef:o}}function Zi(e,t,i,r){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:i,direction:o,activity:r})}var Po=class{constructor(t,i,r,n){if(this.linkedActivitiesData=t,this.activity=i,this.gantt=r,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(),i=on(t),r=this.activity.constraint_type;return r===h.SNET?this.handleSNETConstraint(i):r===h.FNLT?this.handleFNLTConstraint(i):i}calculateLinks(){let t=[];for(let i of this.linkedActivitiesData){let r=i.linkType,n=Ke(r),o=i.linkLag,a=i.es,s=i.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(i.linkId,{targetId:String(this.activity.id),...c}),t.push(c))}return t}handleSNETConstraint(t){let i=Uc({duration:this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t&&t.ef>i.ef?t:i}handleFNLTConstraint(t){let i=Mc({duration:-this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t?t.ef>i.ef?i:t:i}calculateSSLink({lag:t,predecessorEs:i}){let r=Ro({linkType:H.SS,lag:t,predecessorTime:i,activityCalendar:this.activityCalendar,activity:this.activity}),n=P(this.activityCalendar,r,t,this.activity);t>0&&(n=Zi(n,H.SS,this.activityCalendar,this.activity));let o=P(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:o}}calculateFFLink({lag:t,predecessorEf:i}){let r=Ro({linkType:H.FF,lag:t,predecessorTime:i,activityCalendar:this.activityCalendar,activity:this.activity}),n=P(this.activityCalendar,r,t,this.activity),o=P(this.activityCalendar,n,-this.activity.duration,this.activity);return t>0&&(o=Zi(o,H.FF,this.activityCalendar,this.activity)),{es:o,ef:n}}calculateFSLink({lag:t,predecessorEf:i}){let r=i;t===0&&(r=Ht({dateBaseToCalculate:i,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let n=P(this.activityCalendar,r,t,this.activity),o=P(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:o}}calculateSFLink({lag:t,predecessorEs:i}){let r=P(this.activityCalendar,i,t,this.activity),n=P(this.activityCalendar,r,-this.activity.duration,this.activity);return t>0&&(n=Zi(n,H.SF,this.activityCalendar,this.activity)),{es:n,ef:r}}},Hc=Po;var Lo=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 i of this.linkedActivitiesData){let r=Ke(i.linkType);if(i.type===T.TASK&&Number(i.progress)>0||i.type===T.PROJECT&&Number(i.progress)===100)continue;let n=i.linkLag,o=i.ls,a=i.lf;if(r===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(r===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(r===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(r===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===h.FNLT){let i=this.getMinLfFromLinks(t),r=this.calculateSfRestrictionDates();return i?this.getMinLfFromLinks([r,i]):r}else{let i=this.getMinLfFromLinks(t);if(i===!1){let r=this.gantt.getSubtaskDates();return{ls:P(this.activityCalendar,r.end_date,-this.activity.duration,this.activity),lf:r.end_date}}return i}}calculateFFLink({lag:t,workTime:i,lsDataCalculation:r,lfDataCalculation:n}){let o=null,a=null;if(t===0)return o=P(this.activityCalendar,i,n,this.activity),a=P(this.activityCalendar,o,r,this.activity),{ls:a,lf:o};let s=i;return t>0&&(s=this.getLastWorkingHour(s,this.activityCalendar,j.PAST)),o=P(this.activityCalendar,s,n,this.activity),a=P(this.activityCalendar,o,r,this.activity),{ls:a,lf:o}}calculateFsLink({lag:t,workTime:i,lsDataCalculation:r,lfDataCalculation:n,isMilestone:o=!1}){let a=null,s=null;if(t===0){let l=this.getLastWorkingHour(i,this.activityCalendar,j.PAST);return a=P(this.activityCalendar,l,n,this.activity),a=this.getLastWorkingHour(a,this.activityCalendar,j.PAST),s=P(this.activityCalendar,a,r,this.activity),{ls:s,lf:a}}let c=i;return o||(c=this.getLastWorkingHour(i,this.activityCalendar)),a=P(this.activityCalendar,c,n,this.activity),s=P(this.activityCalendar,a,r,this.activity),o||(a=this.getLastWorkingHour(a,this.activityCalendar,j.PAST)),{ls:s,lf:a}}calculateSFLink({lag:t,workTime:i,lsDataCalculation:r,lfDataCalculation:n}){let o=null,a=null,s=i;return a=P(this.activityCalendar,s,r,this.activity),o=P(this.activityCalendar,a,n,this.activity),{ls:a,lf:o}}calculateSSLink({lag:t,workTime:i,lsDataCalculation:r,lfDataCalculation:n,isMilestone:o=!1}){let a=null,s=null;if(t===0)return s=P(this.activityCalendar,i,r,this.activity),a=P(this.activityCalendar,s,n,this.activity),{ls:s,lf:a};let c=i;return t<0&&!o&&(c=this.getLastWorkingHour(c,this.activityCalendar,"future")),s=P(this.activityCalendar,c,r,this.activity),a=P(this.activityCalendar,s,n,this.activity),{ls:s,lf:a}}getMinLfFromLinks(t=[]){return t.length?t.reduce((i,r)=>r.lf<i.lf?r:i):!1}calculateSfRestrictionDates(){let t=this.activity.constraint_date,i=this.activity.duration;return{ls:P(this.activityCalendar,t,-i,this.activity),lf:t}}getLastWorkingHour(t,i,r=j.PAST){let n=t instanceof Date?t:new Date(t),o=jt(n).clone();return this.isActivityInInitHour(i,n)&&r===j.PAST&&(o=o.hours(0).minutes(0).seconds(0).milliseconds(0)),Ht({dateBaseToCalculate:new Date(o),direction:r,activityCalendar:i,activity:this.activity})}isActivityInInitHour(t,i){let r=i instanceof Date?i:new Date(i),o=t.getWorkHours(r)[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),jt.isMoment(i)?i.hours()===a:r.getUTCHours()===a)}},Bc=Lo;function Wc(e){let{parent:t,linkProperty:i,linkDirection:r,calculations:n,gantt:o,direction:a,linkCandidates:s}=e,c=t[i],l=Hh(t),d=null;if(a===q.FORWARD){let u=Bh(c,r,n,o);d=new Hc(u,t,o,s),d=d.calculate()}else{let u=Wh(c,r,n,o);d=new Bc({linksWithActivityData:u,activity:t,parentData:l,gantt:o}).calculate()}return d}function Hh(e){return{duration:e.duration,calendarId:e.calendar_id}}function Bh(e,t,i,r){return e.length===0?[]:e.map(n=>{let o=r.getLink(n);if(!o)return console.warn(`Link not found: ${n}`),null;let a=Number(o[t]),s=i.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 Wh(e,t,i,r){return e.length===0?[]:e.map(n=>{let o=r.getLink(n);if(!o)return console.warn(`Link not found: ${n}`),null;let a=Number(o[t]),s=i.get(a);if(!s)return null;let c=r.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 Kc(e){let{activityData:t,calculations:i,singleParents:r,direction:n}=e;if(Vh(t.id,i))return null;let o=jh(t.id,r),a=Kh(o,i);return a.length===0?null:Yh(a,n)}function Vh(e,t){return t.has(e)}function jh(e,t){let i=t.get(e);return i?i.childrens:[]}function Kh(e,t){return e.filter(i=>t.has(i)).map(i=>t.get(i))}function Yh(e,t){if(t===q.FORWARD){let i=Vc(e,"es"),r=jc(e,"ef");return{es:i,ef:r}}else{let i=Vc(e,"ls"),r=jc(e,"lf");return{ls:i,lf:r}}}function Vc(e,t){return e.reduce((i,r)=>r[t]<i[t]?r:i)[t]}function jc(e,t){return e.reduce((i,r)=>r[t]>i[t]?r:i)[t]}var Oo={parentWithLinks:Wc,parentWithNoLinks:Kc};var No=class{constructor(t){this.activity=t.activity,this.direction=t.direction,this.linkProperty=t.direction===q.FORWARD?"$target":Jt.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 r=[h.FNLT];if(this.shouldCalculateParentWithLinksBackward(r)){this.calculateAndStoreParentWithLinks(this.activity);return}if(this.shouldSetDatesToParentsWithLinks(r)){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 i=t.includes(this.activity.constraint_type),r=!this.calculationOfParentsFromLinks.has(this.activity.id);return i&&r}calculateAndStoreParentWithLinks(t){let i=Oo.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,i),this.calculationOfParentsFromLinks.add(t.id)}areAllLinksCalculated(t){return t.every(i=>this.calculations.has(i))}shouldSetDatesToParentsWithLinks(t){let i=t.includes(this.activity.constraint_type),r=this.calculationOfParentsFromLinks.has(this.activity.id);return i&&r}handleParentWithNoLinks(){let t=Oo.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,r=Array.from(this.calculations).filter(a=>t.includes(a[0])).map(a=>a[1]),{minEs:n,maxEf:o}=r.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(r[0].es),maxEf:new Date(r[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,r=Array.from(this.calculations).filter(a=>t.includes(a[0])).map(a=>a[1]),{minLs:n,maxLf:o}=r.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(r[0].ls),maxLf:new Date(r[0].lf)});this.calculations.set(this.activity.id,{ls:n,lf:o})}getArrayOfIdOfLinkedActivities(t,i=!1){return t.map(r=>{let o=this.gantt.getLink(r)[i||this.linkDirection];return Number(o)})}},Yc=No;var bo=class{constructor({gantt:t,linkProperty:i}){this.gantt=t,this.linkProperty=i,this.structureOfParents=new Map,this.singleParents=new Map}identifyThirdLevelActivities(){try{let t=this.getFirstLevelParents();for(let i of t){let r=this.processEachActivity(i),{activitiesByLevel:n}=r,o=this.getAllLevels(n),a=this.getDeepestLevel(o),s=this.createResult(i,r,a,o);this.structureOfParents.set(i.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 i=new Set,r=new Set,n=new Map;return this.initializeParent(t),this.gantt.eachTask(o=>{this.processActivity(o,i,r,n)},t.id),{parentsIds:i,allTasks:r,activitiesByLevel:n}}initializeParent(t){let i=Number(t.id),r=!!t[this.linkProperty]?.length,n=t.$level;this.singleParents.set(i,{level:n,hasLink:r,childrens:[]})}processActivity(t,i,r,n){let o=Number(t.id),a=Number(t.parent);r.add(o),this.isProjectActivity(t)&&this.addParentInfo(t,i);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,i){let r=Number(t.id),n=t.$level,o=this.hasLink(t),a={level:n,hasLink:o,childrens:[]};i.add(r),this.singleParents.set(r,a)}doesParentExist(t){return this.singleParents.has(t)}addChildToParent(t,i){this.singleParents.get(t).childrens.push(i)}addActivityToLevel(t,i){let r=t.$level,n=Number(t.parent);i.has(r)||i.set(r,new Map);let o=i.get(r);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,i,r,n){let{activitiesByLevel:o,parentsIds:a,allTasks:s}=i;return{parent:t.id,isALinkedParent:this.hasLink(t),levels:n,allParentChildrens:a,allChildrens:s,childrensByLevel:o,currentResolutionLevel:r,canBeCalculated:!1}}},Gc=bo;var Fo=class{constructor(t,i){this.direction=i,this.gantt=t,this.linkProperty=this.direction===q.FORWARD?"$target":Jt.SOURCE,this.linkDirection=this.direction===q.FORWARD?"source":"target",this.projectDates=t.getSubtaskDates()}tryToCalculateLastLevelChildrens(){this.structureOfParents.forEach(t=>{let{currentResolutionLevel:i,childrensByLevel:r,isALinkedParent:n}=t;if(n)return;let o=r.get(i);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:i,pendingParentsWithLinks:r}=Xi.identifyParentsWithAndWithoutLinks({gantt:this.gantt,direction:this.direction,linkProperty:this.linkProperty});this.parentsWithFullProgress=t,this.pendingParentsWithNoLinks=i,this.pendingParentsWithLinks=r}catch(t){throw t}}identifyForbiddenActivitiesLinkedToParentsWithLinks(){try{this.forbiddenActivitiesLinkedToParentsWithLinks=Xi.identifyForbiddenActivities({pendingParentsWithLinks:this.pendingParentsWithLinks,gantt:this.gantt,direction:this.direction})}catch(t){throw t}}getArrayOfIdOfLinkedActivities(t,i=!1){return t.map(r=>{let o=this.gantt.getLink(r)[i||this.linkDirection];return Number(o)})}async identifyThirdLevelActivities(){try{let{structureOfParents:t,singleParents:i}=new Gc({gantt:this.gantt,linkProperty:this.linkProperty}).identifyThirdLevelActivities();this.structureOfParents=t,this.singleParents=i}catch(t){throw t}}processEachActivity(t){let i=new Set,r=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(r.add(c.id),c.type===T.PROJECT){let u={level:c.$level,hasLink:!!c[this.linkProperty].length,childrens:[]};i.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:i,allTasks:r,activitiesByLevel:n,singleParents:o})})}identifySecondLevelActivities(){try{let t=Xi.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:i}=Xi.identifyInitialActivities({gantt:this.gantt,linkProperty:this.linkProperty,direction:this.direction});this.chainStartActivities=t,i&&(this.activitiesStartChainButChildrenOfLinkedParents=i)}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===T.PROJECT)return;let i=this.calculateStartAndFinishOfChainOrigin(t,this.direction);if(this.direction===q.FORWARD){let{es:r,ef:n}=i;this.calculations.set(t.id,{es:r,ef:n,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}else{let{ls:r,lf:n}=i;this.calculations.set(t.id,{ls:r,lf:n,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}})}catch(t){throw t}}buildDependencyGraph(t){let i=new Map,r=new Set(this.calculations.keys()),n=new Map;return t.forEach(o=>{o&&n.set(o.id,o)}),n.forEach((o,a)=>{if(r.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)||r.has(l)),i.set(a,s)}),{graph:i,activityMap:n,calculatedActivities:r}}topologicalSort(t,i){let r=new Set,n=new Set,o=[],a=s=>{if(n.has(s))throw new Error("Cyclical dependency detected",{cause:{nodeId:s}});if(!r.has(s)&&!i.has(s)){n.add(s);let c=t.get(s)||[];for(let l of c)a(l);n.delete(s),r.add(s),o.push(s)}};for(let s of t.keys())!r.has(s)&&!i.has(s)&&a(s);return o.reverse()}calculateStartAndFinishOfChainOrigin(t=null,i=null){try{let r=t,n=Number(r.progress);n==="0.00"&&(n=0);let o=this.gantt.getCalendar(r.calendar_id);if(!o)throw new Error(`Error trying to get calendar with id: ${r.calendar_id}`);if((i||this.direction)===q.FORWARD){let s=r.start_date,c=r.end_date;return{es:s,ef:c}}else{if(n>=100)return{ls:jt(r.start_date).clone(),lf:jt(r.end_date).clone()};if(n===0)return this.calculateBackwardWhenZeroProgress(r,o);if(n<100&&n>0)return this.calculateWhenProgressIsBetweenZeroAndOneHundred(r,o)}}catch(r){throw r}}calculateBackwardWhenZeroProgress(t,i){let r=jt(t.start_date).clone(),n=jt(t.end_date).clone(),o=t.duration,a=[h.ASAP,h.ALAP,h.SNET,h.FNET],s=t.constraint_type||h.ASAP;if(a.includes(s))n=this.projectDates.end_date,r=P(i,n,-o,t);else{let c=[h.SNLT,h.MSO],l=[h.FNLT,h.MFO];c.includes(s)&&(r=t.constraint_date,n=P(i,r,o,t)),l.includes(s)&&(n=t.constraint_date,r=P(i,n,-o,t))}return{ls:r,lf:n}}calculateWhenProgressIsBetweenZeroAndOneHundred(t){let i=t.start_date,r=null,n=t.constraint_type||h.ASAP,o=this.projectDates.end_date,a=[h.ASAP,h.ALAP,h.SNET,h.FNET],s=[h.SNLT,h.FNLT];if(a.includes(n))r=Math.max(t.end_date,o);else if(n===h.MSO)r=t.end_date;else if(n===h.MFO||s.includes(n)){let c=Math.min(o,t.constraint_date);r=Math.max(c,t.end_date)}return{ls:i,lf:new Date(r)}}initializeActivitiesWithFullProgress(){try{Array.from(this.activitiesWaitingForCalculation).filter(r=>Number(this.gantt.getTask(r).progress)===100).map(r=>this.gantt.getTask(r)).forEach(r=>{let n=r.type===T.PROJECT;this.setDatesForActivityWithFullProgress(r),this.activitiesWaitingForCalculation.delete(r.id),n&&this.pendingParentsWithLinks.has(r.id)&&(this.parentCalculationFromChildren.add(r.id),this.calculationsOfParentThatImpactChildrens.set(r.id,{[this.direction===q.FORWARD?"es":"ls"]:r.start_date,[this.direction===q.FORWARD?"ef":"lf"]:r.end_date}),this.calculationOfParentsFromLinks.add(r.id))})}catch(t){throw t}}doCalculationForParentType(t){let i=new Yc({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)?i.handleParentWithLinks():i.handleParentWithNoLinks()}},Re=Fo;function Gh(e,t,i){let r={es:null,ef:null};if(!e)return r;if([h.SNET,h.SNLT].includes(t)){let n=new Date(e.constraint_date);r.es=n,r.ef=P(i,n,e.duration,e)}else if([h.FNLT,h.FNET].includes(t)){let n=new Date(e.constraint_date);r.es=P(i,n,-e.duration,e),r.ef=n}else if(t===h.MSO){let n=new Date(e.constraint_date);r.es=n,r.ef=P(i,n,e.duration,e)}else if(t===h.MFO){let n=new Date(e.constraint_date);r.es=P(i,n,-e.duration,e),r.ef=n}return r}var an=Gh;var wo=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,i,r=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=P(a,s,r,this.referenceActivity),c=P(a,l,i,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,o,a))):(c=P(a,s,i,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,o,a)),l=P(a,c,r,this.referenceActivity)),{es:c,ef:l}}calculateSS(t){let i=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),r=t.lag||0,o=this.referenceActivity.duration,a=t.lag||0;return this.calculateSucessorTimes(i.es,r,o,a,H.SS)}calculateFF(t){let i=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,o=t.lag||0,a=t.lag||0;return this.calculateSucessorTimes(i.ef,n,o,a,H.FF)}calculateFS(t){let i=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),r=t.lag||0,o=this.referenceActivity.duration,a=t.lag||0;return this.calculateSucessorTimes(i.ef,r,o,a,H.FS)}calculateSF(t){let i=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,o=t.lag||0,a=t.lag||0;return this.calculateSucessorTimes(i.es,n,o,a,H.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,i,r){if(![H.FS,H.SS,H.FF].includes(i))return t;let o=[H.FS,H.SS].includes(i)?"future":j.PAST;return Ht({dateBaseToCalculate:t,activityCalendar:r,direction:o,activity:this.referenceActivity})}},$c=wo;var Qi=class extends $c{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Re(this.gantt,"forward").calculateStartAndFinishOfChainOrigin(this.referenceActivity);let t=this.links.map(r=>{let n=this.gantt.getLink(r);if(!n)throw new Error("Link data not found",{cause:{linkId:r}});let o=this.calculateLink(n);return this.linkCandidates?.set(String(n.id),{targetId:String(this.referenceActivity.id),...o}),o}),i=Number(this.referenceActivity.parent);if(this.parentsWithLinks.has(i)){let r=this.gantt.getCalendar(this.referenceActivity.calendar_id),n=this.parentsCalculations.get(i).es,o=P(r,n,this.referenceActivity.duration,this.referenceActivity);t.push({es:n,ef:o})}return on(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var xo=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 i=new Set,r=new Set(t);for(let n of t){let o=this.gantt.getTask(n);o.type===T.PROJECT?this.handleProjectActivity(n,o,i,r):this.handleNonProjectActivity(n,o,i,r)}return{activitiesThatCanBeCalculated:i,pendingActivities:r}}handleProjectActivity(t,i,r,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))&&(r.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))&&(r.add(t),n.delete(t));return}a&&!s&&this.canCalculateParentActivity(i)&&(r.add(t),n.delete(t))}canCalculateParentActivity(t){let i=(t[this.linkProperty]||[]).length===0,r=t.constraint_type;return(this.direction===q.FORWARD?r===h.FNLT||r===h.SNLT:r===h.FNLT)&&i?!0:this.getArrayOfLinkedActivities(t[this.linkProperty]).every(a=>this.calculations.has(a))}handleNonProjectActivity(t,i,r,n){let o=Number(i.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(i.$target.length===0&&i[Jt.SOURCE].length===0){r.add(t),n.delete(t);return}let c=this.getLinkedActivities(i[this.linkProperty]),l=c.every(d=>this.calculations.has(d.id));if(this.direction===q.BACKWARD&&(c.length===0||l)&&s){r.add(t),n.delete(t);return}l&&(r.add(t),n.delete(t))}getLinkedActivities(t){if(!Array.isArray(t))return[];let i=[];for(let r of t){let n=this.gantt.getLink(r);if(!n)continue;let o=n[this.linkDirection],a=this.gantt.getTask(o);a&&i.push(a)}return i}getArrayOfLinkedActivities(t){if(!Array.isArray(t))return[];let i=[];for(let r of t){let n=this.gantt.getLink(r);n&&i.push(Number(n[this.linkDirection]))}return i}},sn=xo;var Mo=(e,t)=>()=>t()===e;var Uo=e=>!e?.fullyParsed;var $h=16,Ge=async e=>performance.now()-e>$h?(await ct(),performance.now()):e;var tr=async({pending:e,activityCalculator:t,calculateFn:i,shouldKeepPending:r,isCalculated:n,onActivityProcessed:o,isCurrent:a})=>{let s=new Set(e),c=performance.now();for(;s.size>0;){if(!a())return;c=await Ge(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(s);if(l.size===0)break;for(let u of l){if(!a())return;c=await Ge(c),i([u])}for(let u of l){if(!a())return;r(u)&&d.add(u),o(u),n(u)&&d.delete(u)}s=d}};var Ho=class extends Re{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 i=new sn({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 tr({pending:this.activitiesWaitingForCalculation,activityCalculator:i,calculateFn:r=>this.calculateStartAndFinishTimes(r),shouldKeepPending:r=>this.calculationOfParentsFromLinks.has(r)&&!this.calculations.has(r),isCalculated:r=>this.calculations.has(r),onActivityProcessed:r=>this.activitiesWaitingForCalculation.delete(r),isCurrent:t})}calculateStartAndFinishTimes(t){t.forEach(i=>{let r=this.gantt.getTask(i);if(r.type===T.PROJECT)return this.doCalculationForParentType(r);if(!r)throw new Error("Error trying to get activity",{cause:{activityId:i}});let n=r.$target,o=r.constraint_type||h.ASAP,a=[h.SNET,h.SNLT,h.FNLT,h.FNET],s=[h.ASAP,h.ALAP,h.SNET,h.FNET,h.SNLT,h.FNLT],c=this.gantt.getCalendar(r.calendar_id);if(!c)throw new Error(`Error trying to get calendar with id: ${r.calendar_id}`);let l=Number(r.progress),d=null,u=null,f=null;if(l===100){this.setDatesForActivityWithFullProgress(r);return}l>0&&s.includes(o)?({es:d,ef:u}=this.getDatesForActivityWithZeroProgress(r),f=new Qi({links:n,activity:r,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:o,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),o===h.ASAP&&this.totalFloatForAsap.set(i,{es:f.es,ef:f.ef,text:r.text})):{es:d,ef:u}=new Qi({links:n,activity:r,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:o,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),o===h.ALAP&&this.alapMap.set(i,{es:r.start_date,ef:r.end_date,text:r.text});let p=an(r,o,c);if(a.includes(o)&&(this.constraintsMap.set(i,p),this.totalFloatSnltFnlt.set(i,{es:d,ef:u}),{es:d,ef:u}=this.recalculateInBaseConstraint(o,p,{es:d,ef:u})),[h.MSO,h.MFO].includes(o))if(this.totalFloatForMsoMfo.set(i,{es:d,ef:u}),this.constraintsMap.set(i,p),r.progress===0)d=p.es,u=p.ef;else{let y=r.end_date;o===h.MFO&&(y=Math.max(p.ef,r.end_date)),d=r.start_date,u=y}this.calculations.set(i,{es:d,ef:u}),this.activitiesWaitingForCalculation.delete(i)})}getTheGreatesDateBetweenRestrictionAndEsEf(t,i,r=Ye.GREATER){if(r===Ye.GREATER)return i.ef>t.ef?i:t;if(r===Ye.LESS)return i.ef<t.ef?i: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,i,r){let n=[h.SNET,h.FNET].includes(t)?Ye.GREATER:Ye.LESS,{es:o,ef:a}=this.getTheGreatesDateBetweenRestrictionAndEsEf(i,r,n);return{es:o,ef:a}}cleanAllActivityParentsFromLinks(t){return t.map(i=>{let r=this.gantt.getLink(i);if(!r)throw new Error("Error trying to get link",{cause:{linkId:i}});let n=r.source,o=r.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 i}).filter(Boolean)}},zc=Ho;var Bo=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,i=null){return i===h.ALAP?this.forwardPathCalculations.get(t):this.calculatedActivities.get(t)}calculateSuccessorTimes(t,i,r=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=P(a,s,i,this.activity),u=P(a,d,r,this.activity);return{ls:d,lf:u}}let l={lag:n,workTime:s,activityCalendar:a,lsDataCalculation:i,lfDataCalculation:r,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,i=!1){let r=this.getValueForSS(t,i),n=-t.lag||0,o=this.activity.duration,a=t.lag;return this.calculateSuccessorTimes(r,n,o,a,H.SS)}calculateFF(t,i){let r=this.getForwardOrBackwardCalculations(Number(t.target)),n=i===h.ALAP?"ef":"lf",o=r[n],a=-this.activity.duration,s=-t.lag||0,c=t.lag;return this.calculateSuccessorTimes(o,a,s,c,H.FF)}calculateFS(t,i){let r="ls";r=i===h.ALAP?"es":"ls";let n=this.getForwardOrBackwardCalculations(Number(t.target),i),o=-this.activity.duration,a=t.lag||0,s=-t.lag||0;return this.calculateSuccessorTimes(n[r],o,s,a,H.FS)}calculateSF(t,i=!1){let r=i?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(r,n,o,a,H.SF)}getEarlyStartFromForwardPath(t){return this.forwardPathCalculations.get(t)}getValueForSS(t,i){return i?this.getEarlyStartFromForwardPath(Number(t.target)).es:this.getForwardOrBackwardCalculations(Number(t.target))["ls"]}calculateDate(t,i,r){let n=jt(i).clone();return P(t,new Date(n),r,this.activity)}getLastWorkingHour(t,i,r=j.PAST){let n=t instanceof Date?t:new Date(t),o=jt(n).clone();return this.isActivityInInitHour(i,n)&&r===j.PAST&&(o=o.hours(0).minutes(0).seconds(0).milliseconds(0)),Ht({dateBaseToCalculate:new Date(o),direction:r,activityCalendar:i,activity:this.activity})}isActivityInInitHour(t,i){let r=i instanceof Date?i:new Date(i),o=t.getWorkHours(r)[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),jt.isMoment(i)?i.hours()===a:r.getUTCHours()===a)}calculateFsLink({lag:t,workTime:i,activityCalendar:r,lsDataCalculation:n,lfDataCalculation:o,isMilestone:a=!1}){let s=null,c=null;if(t===0){let d=this.getLastWorkingHour(i,r,j.PAST);return s=P(r,d,o,this.activity),s=this.getLastWorkingHour(s,r,j.PAST),c=P(r,s,n,this.activity),{ls:c,lf:s}}let l=i;return a||(l=this.getLastWorkingHour(i,r)),s=P(r,l,o,this.activity),c=P(r,s,n,this.activity),a||(s=this.getLastWorkingHour(s,r,j.PAST,!0)),{ls:c,lf:s}}calculateFFLink({lag:t,workTime:i,activityCalendar:r,lsDataCalculation:n,lfDataCalculation:o}){let a=null,s=null;if(t===0)return a=P(r,i,o,this.activity),s=P(r,a,n,this.activity),{ls:s,lf:a};let c=i;return t>0&&(c=this.getLastWorkingHour(c,r,j.PAST)),a=P(r,c,o,this.activity),s=P(r,a,n,this.activity),{ls:s,lf:a}}calculateSSlink({lag:t,workTime:i,activityCalendar:r,lsDataCalculation:n,lfDataCalculation:o,isMilestone:a=!1}){let s=null,c=null;if(t===0)return c=P(r,i,n,this.activity),s=P(r,c,o,this.activity),{ls:c,lf:s};let l=i;return t<0&&!a&&(l=this.getLastWorkingHour(l,r,"future")),c=P(r,l,n,this.activity),s=P(r,c,o,this.activity),{ls:c,lf:s}}calculateSFLink({lag:t,workTime:i,activityCalendar:r,lsDataCalculation:n,lfDataCalculation:o}){let a=null,s=null;return t===0?(s=P(r,i,n),a=P(r,s,o,this.activity),{ls:s,lf:a}):(s=P(r,i,n,this.activity),a=P(r,s,o,this.activity),{ls:s,lf:a})}},qc=Bo;var Wo=class extends qc{constructor(t){super(t),this.constraint=t.constraint||h.ASAP,this.parentsWithFullProgress=t.parentsWithFullProgress,this.parentsThatImpactChildrens=t.parentsThatImpactChildrens,this.projectDates=this.gantt.getSubtaskDates()}calculate(){if(this.links.length===0)return new Re(this.gantt,q.BACKWARD).calculateStartAndFinishOfChainOrigin(this.activity);let t=this.activity.progress>0&&this.activity.progress<100,i=this.gantt.getTask(this.activity.parent),r=!1;i&&(r=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()),r){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(r){n.push(this.calculateTheLsAndLfForTheActivity());let s=this.parentsThatImpactChildrens.get(Number(this.activity.parent)).lf,c=P(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 i=this.activity.duration,r=this.gantt.getCalendar(this.activity.calendar_id);if(!r)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:P(r,n,-i,this.activity),lf:n}}catch(i){throw Error(i.message)}}SnetSnltMsoMinDate(t){let i=Math.min(t.lf,this.projectDates.end_date);return new Date(Math.max(i,this.activity.end_date))}calculateLink(t){let i=this.gantt.getTask(t.target);if(!i||i.progress>0&&i.type!==T.PROJECT)return;let r=this.getSpecialCalculationParamForConstraintLink(),n=this.getSpecialParamForSf(),o=this.getSpecialParamForFF();return{0:()=>this.calculateFS(t,r),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t,o),3:()=>this.calculateSF(t,n)}[t.type]()}getSpecialCalculationParamForConstraintLink(){if(this.constraint===h.ALAP)return h.ALAP;if(this.constraint===h.FNET||this.constraint===h.SNET)return"snet-fnet";if(this.constraint===h.FNLT)return h.FNLT}getSpecialParamForSf(){return!![h.ALAP].includes(this.constraint)}getSpecialParamForFF(){return!![h.MFO,h.MSO].includes(this.constraint)}getMinCalculationLogic(t){if(this.constraint===h.ALAP)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.FNET)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.FNLT)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.MFO)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.SNET||this.constraint===h.SNLT||this.constraint===h.MSO)return this.SnetSnltMsoMinDate(t);if(this.constraint===h.ASAP)return this.getMinDateBasedOnConstraint(t)}getMinDateFromLinks(t){try{return this.constraint===h.ALAP||this.constraint===h.ASAP?t.reduce((r,n)=>n.lf<r.lf?n:r):t.reduce((i,r)=>r.ls<i.ls?r:i)}catch(i){throw new Error(`Function: getMinDateFromLinks in LinksConstraintCalculator - ${i.message}`)}}getMinLfFromLinks(t){return t.reduce((i,r)=>r.lf<i.lf?r:i)}getMinDateBasedOnConstraint(t,i=this.constraint){let r=Math.min(t.lf,this.projectDates.end_date),n=this.activity.end_date,o=this.activity.constraint_date;if(i===h.ASAP)return new Date(Math.max(r,n));if(i===h.FNET||i===h.FNLT){let a=Math.min(r,o);return new Date(Math.max(r,a))}if(i===h.ALAP)return new Date(Math.min(r,n))}},Jc=Wo;function zh(e,t,i){let r={ls:null,lf:null};return i===h.MSO&&(r.ls=t.constraint_date,r.lf=P(e,r.ls,t.duration,t)),i===h.MFO&&(r.lf=t.constraint_date,r.ls=P(e,r.lf,-t.duration,t)),r}var Xc=zh;var Vo=class extends Re{constructor(t,i,r){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=i,this.forwardConstraintsMap=r,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 i=new sn({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 tr({pending:this.activitiesWaitingForCalculation,activityCalculator:i,calculateFn:r=>this.calculateStartAndFinishTimes(r),shouldKeepPending:r=>this.calculationOfParentsFromLinks.has(r)&&!this.calculations.has(r),isCalculated:r=>this.calculations.has(r),onActivityProcessed:r=>this.activitiesWaitingForCalculation.delete(r),isCurrent:t})}setDatesToParentsWithLinks(t){if(!t)throw new Error("Error trying to get parent",{cause:{receivedParentData:t}});let i=this.singleParents.get(t.id).childrens,n=Array.from(this.calculations).filter(s=>i.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(i=>{let r=this.gantt.getTask(i);if(!r)throw new Error("Activity not found",{cause:{activityId:i}});let n=r.$source,o=r.constraint_type||h.ASAP,a=Number(r.progress);if(this.activitiesStartChainButChildrenOfLinkedParents.has(i)){if(this.calculationsOfParentThatImpactChildrens.has(Number(r.parent))&&this.calculationsOfParentThatImpactChildrens.get(Number(r.parent))===!1){let{ls:d,lf:u}=this.calculateStartAndFinishOfChainOrigin(r,this.direction);this.setCalculations(r,d,u);return}return this.doCalculationForActivitiesThatStartLinkButHisParentIsLinked(r)}if(r.type===T.PROJECT)return this.doCalculationForParentType(r);if(a===100){this.setDatesForActivityWithFullProgress(r);return}if(this.allLinkedActivitiesHasProgress(n,r)){this.setWhenAllLinkedActivitiesHasProgress(r);return}if(a>0&&a<100&&(o===h.MSO||o===h.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(r,o);return}if(o===h.MSO||o===h.MFO){this.recalculateInBaseRestriction(r,o);return}let{ls:s,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(n,r,o,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(o===h.SNLT||o===h.FNLT)&&({ls:s,lf:c}=this.getTheLessLateInBasEsEfConstraint(r.id,{ls:s,lf:c},o)),this.setCalculations(r,s,c),this.minFromLinks.set(r.id,{ls:l.ls,lf:l.lf})})}getTheLessLateInBasEsEfConstraint(t,i,r){let n=this.forwardConstraintsMap.get(t);if(!n){let o=this.gantt.getTask(t),a=this.gantt.getCalendar(o.calendar_id);n=an(o,r,a)}return i.lf<n.ef?i:{ls:n.es,lf:n.ef}}allLinkedActivitiesHasProgress(t){try{let i=!0;for(let r of t){let n=this.gantt.getLink(r);if(!n)continue;let o=this.gantt.getTask(n.target);o&&(o.type===T.PROJECT&&(i=!1),o.progress===0&&(i=!1))}return i}catch(i){throw new Error(i.message)}}setDatesForActivityWithFullProgress(t){this.setCalculations(t,t.start_date,t.end_date)}setWhenAllLinkedActivitiesHasProgress(t){let i=Number(t.parent),{ls:r,lf:n}=this.calculateStartAndFinishOfChainOrigin(t,q.BACKWARD);if(this.calculationsOfParentThatImpactChildrens.has(i)){r=t.start_date;let o=this.calculationsOfParentThatImpactChildrens.get(i);o&&typeof o=="object"&&o.lf!=null&&(n=new Date(Math.min(n,o.lf)))}this.setCalculations(t,r,n)}setWhenActivitiesHasProgressButLessThanOneHundred(t,i){if(i===h.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(i===h.MFO){let r=Math.min(t.constraint_date,this.projectDates.end_date),n=new Date(Math.max(r,t.end_date));this.setCalculations(t,t.start_date,n);return}}setCalculations(t,i,r){this.calculations.set(t.id,{ls:i,lf:r,text:t.text})}calculateLfandLsFromLinks(t,i,r,n,o){return new Jc({links:t,activity:i,calculatedActivitiesMap:this.calculations,calculatedForwardActivitiesMap:this.forwardPathCalculations,constraint:r,parentsWithFullProgress:n,parentsThatImpactChildrens:o,ganttInstance:this.gantt}).calculate()}recalculateInBaseRestriction(t,i){try{let r=this.gantt.getCalendar(t.calendar_id);if(!r)throw new Error(`Error trying to get calendar with id: ${t.calendar_id}`);let n=Xc(r,t,i);this.constraintMap.set(t,n),this.setCalculations(t,n.ls,n.lf)}catch(r){throw new Error(r.message)}}cleanAllActivityParentsFromLinks(t){return t.map(i=>{let r=this.gantt.getLink(i).source,n=this.gantt.getLink(i).target;if(!(!this.gantt.getTask(r)||this.gantt.getTask(r)?.type===T.PROJECT)&&!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type===T.PROJECT))return i}).filter(Boolean)}doCalculationForActivitiesThatStartLinkButHisParentIsLinked(t){let i=Number(t.parent),r=this.calculationsOfParentThatImpactChildrens.get(i),n=0,o=0;if([h.ASAP,h.ALAP,h.SNET,h.FNET].includes(t.constraint_type))if(Number(t.progress)>0){let l=this.projectDates.end_date;o=new Date(Math.min(l,r.lf)),n=t.start_date}else o=r.lf,n=P(this.gantt.getCalendar(t.calendar_id),o,-t.duration,t);if([h.SNLT].includes(t.constraint_type)){let l=this.calculationsOfParentThatImpactChildrens.get(i),d=P(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=P(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}if([h.FNLT].includes(t.constraint_type)){let l=this.calculationsOfParentThatImpactChildrens.get(i),d=t.constraint_date??l.lf;n=new Date(Math.min(d.getTime(),l.lf.getTime())),o=P(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}[h.MSO].includes(t.constraint_type)&&(n=t.constraint_date,o=P(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)),[h.MFO].includes(t.constraint_type)&&(o=t.constraint_date,n=P(this.gantt.getCalendar(t.calendar_id),o,-t.duration,t));let a=this.projectDates.end_date,s=[{ls:n,lf:o}];s.push({ls:P(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((i,r)=>r.lf<i.lf?r:i):!1}},Zc=Vo;function Qc(){return null}var tl=({forward:e,backward:t,id:i,activity:r,gantt:n,projectDates:o})=>({totalFloat:{es:e.calculations.get(i)?.es||0,ef:e.calculations.get(i)?.ef||0,ls:t.calculations.get(i)?.ls||0,lf:t.calculations.get(i)?.lf||0,constraintsMap:e.constraintsMap.get(i),totalFloatSnltFnlt:e.totalFloatSnltFnlt.get(i),totalFloatForMsoMfo:e.totalFloatForMsoMfo.get(i),minFromLinks:t.minFromLinks.get(i),activity:r,gantt:n},freeFloat:{forwardMap:e.calculations||new Map,backwardMap:t.calculations||new Map,activity:r,projectDates:o,gantt:n}});var jo=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,i=Number(this.activity.progress);if(i===100)return 0;if(t||(t=h.ASAP),t===h.ASAP||!t)return i===0?this.calculateAsap():this.calculateAsapWithProgress();if(t===h.ALAP)return i===0?this.calculateAlap():this.calculateAlapWithProgress();if(t===h.SNET||t===h.FNET)return i===0?this.calculateSnetFet():this.calculateSnetFnetSnltWithProgress();if(t===h.SNLT)return i===0?this.calculateSnltFnlt():this.calculateSnetFnetSnltWithProgress();if(t===h.FNLT)return i===0?this.calculateSnltFnlt():this.calculateFnltWithProgress();if(t===h.MSO||t===h.MFO)return i===0?this.calculateMsoMfo():this.calculateMsoMfoWithProgress()}calculateAsap(){let t=this.calculationWithCalendar(this.ls,this.es),i=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,i)/this.gantt.config.hoursPerDay}calculateAsapWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let i=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,i)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateAlap(){let t=this.calculationWithCalendar(this.ls,this.es),i=this.calculationWithCalendar(this.lf,this.ef),r=this.getMinValue(t,i),n=this.calculationWithCalendar(this.lf,this.activity.end_date);return this.getMinValue(r,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 i=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,i)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateFnltWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef),i=this.calculationWithCalendar(this.activity.constraint_date,this.ef);if(this.minFromLinks){let r=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,i,r)/this.gantt.config.hoursPerDay}return this.getMinValue(t,i)/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),i=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,i)/this.gantt.config.hoursPerDay}calculateSnltFnlt(){let t=this.calculationWithCalendar(this.ls,this.es),i=this.calculationWithCalendar(this.lf,this.ef),r=this.getMinValue(t,i);if(!this.totalFloatSnltFnlt&&!this.constrainstMap)return this.getMinValue(t,i)/this.gantt.config.hoursPerDay;let n=0;return this.activity.constraint_type===h.SNLT?n=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatSnltFnlt.es):n=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatSnltFnlt.ef),this.getMinValue(n,r)/this.gantt.config.hoursPerDay}calculateMsoMfo(){let t=this.calculationWithCalendar(this.ls,this.es),i=this.calculationWithCalendar(this.lf,this.ef),r=this.getMinValue(t,i);if(!this.totalFloatForMsoMfo&&!this.constrainstMap)return this.getMinValue(t,i)/this.gantt.config.hoursPerDay;let n=0;return this.activity.constraint_type===h.MSO?n=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatForMsoMfo.es):n=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatForMsoMfo.ef),this.getMinValue(n,r)/this.gantt.config.hoursPerDay}getMinValue(...t){return Math.min(...t)}calculationWithCalendar(t,i){return this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(i),end_date:new Date(t)})}},el=jo;var Ko=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),i=this.getConstraintType();return this.calculateFreeFloatOfLink(i),{activityFreeFloat:t===100?0:this.getFreeFloatBaseConstraint(i),linksFreeFloat:this.linksFreeFloatObject}}getFreeFloatBaseConstraint(t){return t===h.MSO||t===h.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=h.ASAP){let i=this.activity.$source.map(r=>{let{LINK:n,LINK_TYPE:o}=this.getLinkData(r),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(r=>r.freeFloat!==null&&r.freeFloat!==void 0);return this.linksFreeFloatArray=i,i}calculateGeneral(t=h.ASAP){let i=this.getMinFloat(this.linksFreeFloatArray),r=this.calculateFreeFloatForEndOfProject(t),n=[h.SNLT,h.FNLT].includes(t)&&i===null?this.doCalculationForSnltFnlt(t,r,i):this.doGeneralCalculation(r,i);return Math.max(0,n)}getConstraintType(){let{constraint_type:t}=this.activity;return t||(t=h.ASAP),t}getDatesFromSucessorAndPredecessor(t,i,r){let n=r.constraint_type===h.ALAP,o=this.getSucessorAndPredecessorDates({constraint:i,isSuscessorAlap:n,sucessorId:r.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,i){return i===null?t:this.getMinValue(i,t)}doCalculationForSnltFnlt(t,i,r){let n=this.calculateFreeFloatOfRestriction(t);return this.getMinValue(r,i,n)}calculateFreeFloatForEndOfProject(t){let i=t===h.ALAP?this.backwardMap.get(this.activity.id):this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===h.ALAP?i?.lf:i?.ef))}calculateFreeFloatOfRestriction(t){let i=this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.activity.constraint_date,t===h.FNLT?i?.ef:i?.es))}getLinkData(t){let i=this.gantt.getLink(t)||{},r=Ke(i.type);return{LINK:i,LINK_TYPE:r}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:i,sucessorId:r,predecessorId:n}){let o=(i?this.backwardMap:this.forwardMap).get(r),a=(t===h.ALAP?this.backwardMap:this.forwardMap).get(n),s=t===h.ALAP?a?.ls:a?.es,c=t===h.ALAP?a?.lf:a?.ef;return{fs:{sucessor:o?.ls??o?.es,predecessor:c},ss:{sucessor:o?.ls??o?.es,predecessor:s},ff:{sucessor:o?.lf??o?.ef,predecessor:c},sf:{sucessor:o?.lf??o?.ef,predecessor:s}}}calculateMsoMfo(t){let i=this.activity.constraint_date||new Date,r=this.forwardMap.get(this.activity.id),n=t===h.MSO?r?.es:r?.ef,o=this.calculationWithCalendar(i,n);return Math.max(0,this.parseHoursToDays(o))}getMinValue(...t){let i=t.filter(r=>r!=null);return i.length?Math.min(...i):0}calculationWithCalendar(t,i){if(!(t instanceof Date)||!(i instanceof Date)||!Number.isFinite(t.getTime())||!Number.isFinite(i.getTime()))return Number.NaN;let r=`${i.getTime()}_${t.getTime()}`;if(this.durationCache.has(r))return this.durationCache.get(r);let o=this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(i),end_date:new Date(t)});return this.durationCache.set(r,o),o}parseHoursToDays(t){return t==null?0:t/this.gantt.config.hoursPerDay}getMinFloat(t){if(!t?.length)return null;let i=t.filter(r=>!r.hasProgress).map(r=>r.freeFloat);return i.length===0?null:Math.min(...i)}},il=Ko;var rl=e=>({totalFloat:new el(e.totalFloat).getTotalFloat(),freeFloat:new il(e.freeFloat).getFreeFloat()});var Yo=async({activityIds:e,forward:t,backward:i,gantt:r,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=r.getTask(l);if(!d)continue;let u=tl({forward:t,backward:i,id:l,activity:d,gantt:r,projectDates:n}),{totalFloat:f,freeFloat:p}=rl(u);s.set(l,f),c.set(l,p),a=await Ge(a)}return{totalFloatMap:s,freeFloatMap:c}};var Go=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,i=()=>!0){let r=++this.currentCalculationId,n=Mo(r,this.getCurrentCalculationId),o=()=>n()&&i();try{let a=t||this.gantt;if(this.gantt=a||Qc(),Uo(this.gantt))return!1;let s=new zc(this.gantt);if(await s.calculateAsync(o),!o())return!1;let c=s.calculations,l=s.constraintsMap,d=new Zc(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,i,r=()=>!0){let n=new Map,o=performance.now();for(let[a,s]of t){if(o=await Ge(o),!r())return null;let c=Number(s.targetId),l=this.gantt.getTask(c),d=i.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,i,r){try{let n=this.gantt.getSubtaskDates(),o=Array.from(this.forwardPathCalculations.keys());return await Yo({activityIds:o,forward:t,backward:i,gantt:this.gantt,projectDates:n,isCurrent:r})}catch(n){throw this.forwardPathCalculations?.size,n}}},nl=Go;var qh=e=>e===v.FNET||e===v.FNLT||e===v.MFO,Jh=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function Xh(e,t){let i=e.constraintDate;if(!i||!qh(e.constraintType))return i;let r=Jh(i);if(i.getTime()!==r.getTime())return i;let n=t.getClosestWorkTime({date:r,dir:"future",task:e});return n.getUTCFullYear()===i.getUTCFullYear()&&n.getUTCMonth()===i.getUTCMonth()&&n.getUTCDate()===i.getUTCDate()?wi(e,t):i}function Zh(e){let t=new Map,i=new Map,r=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=i.get(a);if(s!==void 0)return s;let c=e.calculateDuration(n,o);return i.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=r.get(c);if(l!==void 0)return new Date(l);let d=e.getClosestWorkTime({date:n,direction:o,unit:s});return r.set(c,d.getTime()),d}}}}function Qh(e){let t=new Map;e.forEachActivity((n,o)=>t.set(String(o),n));let i=new Map,r=(n,o)=>{let a=i.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=r(String(c),o)+1),i.set(n,l),l};for(let n of t.keys())r(n,new Set);return i}function tm(e){let t=new Set;e.forEachActivity((s,c)=>{t.add(String(c)),s.parentId!==null&&t.add(String(s.parentId))});let i=new Map;for(let s of t){let c=Number(s);Number.isSafeInteger(c)&&c!==0&&i.set(c,(i.get(c)??0)+1)}let r=new Map,n=new Map;for(let s of t){let c=Number(s);Number.isSafeInteger(c)&&c!==0&&i.get(c)===1&&(r.set(s,c),n.set(c,s))}let o=1,a=s=>{let c=String(s),l=r.get(c);if(l!==void 0)return l;for(;n.has(o);)o+=1;return r.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:r.has(String(s))?String(s):null}}function em(e,t){let i=Qh(e),r=new Map;return e.forEachActivity((n,o)=>{let a=String(o);r.set(a,{id:t.toLegacy(a),parent:n.parentId===null?0:t.toLegacy(n.parentId),$level:i.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:Xh(n,e)})}),r}function im(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 i=[],r=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();r.has(a)||(r.add(a),i.push(a),o(t.get(a.id)))}if(i.length<e.size)for(let a of e.values())r.has(a)||i.push(a);return i}function rm(e){let t=null,i=null;return e.forEachActivity(r=>{if(r.startDate){let n=r.startDate.getTime();t=t==null?n:Math.min(t,n)}if(r.endDate){let n=r.endDate.getTime();i=i==null?n:Math.max(i,n)}}),{start_date:new Date(t??0),end_date:new Date(i??0)}}async function ol(e,t){let i=new Map,r=l=>{let d=l==null?"__default__":String(l),u=i.get(d);if(u)return u;let f=e.calendarReader.getCalendar(String(l)),p=Zh(f);return i.set(d,p),p},n=rm(e);await ct();let o=tm(e),a=em(e,o);await ct();let s=[...a.values()].sort((l,d)=>(l.start_date?.getTime()??0)-(d.start_date?.getTime()??0));await ct();let c=im(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:r,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 zo=1e3,nm=e=>typeof e!="number"||!Number.isFinite(e)?null:Object.is(e,-0)?0:e,om=(e,t)=>typeof e!="number"||e<0?null:$o(e,t);function am(e){let t=om(e.freeFloatDays,e.hoursPerDay),i=nm(e.residualHours);return{freeSlackHours:t,isCritical:i!==null&&i<=0&&e.sourceIsCritical&&e.targetIsCritical&&e.targetProgress===0}}async function sm(e,t){let i=new Map,r=0;for(let n of e.values())for(let o in n.linksFreeFloat)if(Object.hasOwn(n.linksFreeFloat,o)){if(++r>=zo&&(r=0,await ct(),!t()))return null;i.set(String(o),n.linksFreeFloat[o])}return t()?i:null}async function cm(e,t,i,r,n){let o=new Map,a=0;for(let s of t.forward?.keys()??[]){if(++a>=zo&&(a=0,await ct(),!n()))return null;let c=r(s);if(c===null)continue;let l=e.getActivity(c);l&&o.set(String(c),dm(s,Number(l.progress??0),t,i))}return n()?o:null}async function lm(e,t,i,r,n,o){let a=new Map,s=0;for(let c of e.getAllLinks()){if(++s>=zo&&(s=0,await ct(),!o()))return null;a.set(String(c.id),am({freeFloatDays:t.get(String(c.id)),residualHours:i.get(String(c.id)),hoursPerDay:n,sourceIsCritical:r.get(c.source)?.isCritical===!0,targetIsCritical:r.get(c.target)?.isCritical===!0,targetProgress:e.getActivity(c.target)?.progress}))}return o()?a:null}var $o=(e,t)=>{if(typeof e!="number"||!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return null;let i=e*t;return Number.isFinite(i)?Object.is(i,-0)?0:i:null};function dm(e,t,i,r){let n=c=>{if(c==null)return null;let l=new Date(c);return Number.isFinite(l.getTime())?l:null},o=i.forward?.get(e),a=i.backward?.get(e),s=$o(i.totalFloat.get(e),r);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:$o(i.freeFloat.get(e)?.activityFreeFloat,r)}}var cn=(e,t)=>e===t||e!==null&&t!==null&&e.getTime()===t.getTime();function qo(e,t,i){let r=e.getActivity(t),n=r?.criticalPath,o=i.criticalPath;r&&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(r.isCritical,i.isCritical)&&Object.is(r.freeSlackHours,i.freeSlackHours)||e.setActivityFields(t,i)}function Jo(e,t,i){let r=e.getLink(t);!r||Object.is(r.freeSlackHours,i.freeSlackHours)&&Object.is(r.isCritical,i.isCritical)||(e.setLinkField(t,"freeSlackHours",i.freeSlackHours),e.setLinkField(t,"isCritical",i.isCritical))}async function Xo(e,t,i=()=>!0){if(!i())return null;let r=await ol(e,t);if(!i())return null;let n=new nl(r);if(!await n.calculate(r,i)){if(!i())return null;throw new Error("critical path calculation aborted")}if(!i())return null;let a={forward:n.forwardPathCalculations,backward:n.backwardPathCalculations,totalFloat:n.totalFloat,freeFloat:n.freeFloat},s=await cm(e,a,t,r.getCanonicalActivityId,i);if(!s)return null;let c=await sm(a.freeFloat,i);if(!c)return null;let l=await lm(e,c,n.linkResidualHours,s,t,i);return l?{activities:s,links:l}:null}async function al(e,t,i=()=>!0){let r=await Xo(e,t,i);if(!r||!i())return!1;for(let[n,o]of r.activities){if(!i())return!1;qo(e,n,o)}for(let[n,o]of r.links){if(!i())return!1;Jo(e,n,o)}return!0}function gi(e){let t=[],i=[];e.forEachActivity((n,o)=>{n.parentId===null&&t.push(String(o))});let r=n=>{let o=e.getActivity(String(n));if(!o)return 0;let a=[...e.getChildren(String(n))],s;if(a.length===0){let c=gt(o),l=c&&Number(c.cost)||0;s=(Number(o.progress)||0)/100*l}else{let c=0;for(let l of a)c+=r(String(l));s=c}return e.setActivityField(String(n),b.REAL_COST,s),i.push(String(n)),s};for(let n of t)r(n);return i}var sl=new Set;var cl=new Set(["activity-outdent","activity-indent"]);var er=new Set([E.TEXT,E.DESCRIPTION,E.COST,E.USED_COST,E.CUSTOM_ID,E.RESPONSABLES,E.SUBCONTRACT_ID,E.TAGS]),um=new Set([I.ACTIVITY_CLIPBOARD_CLEAR,I.ACTIVITY_COPY,I.SELECTION_TOGGLE,I.SELECTION_REPLACE,I.VISIBILITY_SET,I.FILTER_SET,I.SORT_SET,I.SIR_SYNC,I.ACTIVITY_LOOKAHEAD_SYNC,I.PERSISTENCE_ACKNOWLEDGE,I.BASELINE_APPLY,I.PONDERATOR_CRITERION_SET,I.STATUS_CRITERIA_SET]),fm=new Set([I.ACTIVITY_CLIPBOARD_CLEAR,I.ACTIVITY_COPY,I.SELECTION_TOGGLE,I.SELECTION_REPLACE,I.VISIBILITY_SET,I.FILTER_SET,I.SORT_SET]);function dl(e){return!fm.has(e.kind)}var pm=new Set;function ym(e){return e.kind===I.INLINE_EDIT?er.has(e.column):e.kind===I.BULK_EDIT?e.edits.every(t=>er.has(t.column)):!1}function Zo(e,t){return!(um.has(e.kind)||t.has(e.kind)||ym(e))}function ln(e){return e.kind===I.ACTIVITY_LOOKAHEAD_SYNC?e.persistedProgress!==void 0:Zo(e,pm)}function $e(e){return e.kind===I.ACTIVITY_LOOKAHEAD_SYNC?e.persistedProgress!==void 0:Zo(e,sl)}function ul(e){return Zo(e,cl)}function Qo(e){return e.kind===I.ACTIVITY_SET_PROGRESS?!0:e.kind===I.INLINE_EDIT?e.column===E.PROGRESS:e.kind===I.BULK_EDIT?e.edits.some(t=>t.column===E.PROGRESS):!1}function hm(e){return ul(e)&&Qo(e)}var ll=new Set([E.PROGRESS,E.HH_WORK_TIME,E.DURATION,E.COST,E.USED_COST,E.REAL_COST]);function mm(e){return e.kind===I.ACTIVITY_SET_PROGRESS?!0:e.kind===I.INLINE_EDIT?ll.has(e.column):e.kind===I.BULK_EDIT?e.edits.some(t=>ll.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 fl(e,t,i){let r=new Set;t.ran&&r.add(kt.AUTOSCHEDULE),r.add(kt.PARENT_BOUNDS),mm(e)&&r.add(kt.PARENT_PROGRESS),Qo(e)&&r.add(kt.REAL_WORK);let n=!i.skipAutoSchedule;return n&&ul(e)&&r.add(kt.EXPECTED_PROGRESS),n&&hm(e)&&r.add(kt.REAL_COST),n&&$e(e)&&!i.skipCriticalPath&&r.add(kt.CRITICAL_PATH),r}var Rt={INSERT:"insert",REMOVE:"remove",LINK_ADD:"link-add",LINK_REMOVE:"link-remove",LINK_FIELD:"link-field"},dn=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,i){let r=this._journal;r&&(r.before.has(t)||r.before.set(t,ce(i)),r.dirty.add(t))}noteInsert(t){this._journal?.ops.push({kind:Rt.INSERT,activityId:t})}noteRemove(t,i){this._journal?.ops.push({kind:Rt.REMOVE,activityId:t,before:ce(i)})}noteLinkAdd(t){this._journal?.ops.push({kind:Rt.LINK_ADD,linkId:t})}noteLinkRemove(t,i){this._journal?.ops.push({kind:Rt.LINK_REMOVE,linkId:t,before:pl(i)})}noteCorrelativeBefore(t,i){let r=this._journal;if(!r||r.correlativeBefore.has(t))return;let n=r.before.get(t)?.correlativeId;r.correlativeBefore.set(t,typeof n=="number"?n:i)}noteScheduledBefore(t,i){let r=this._journal;if(!r)return;let n=ce(i);r.scheduledBefore.has(t)||r.scheduledBefore.set(t,n),r.before.has(t)||r.before.set(t,n),r.dirty.add(t)}noteLinkField(t,i){let r=this._journal;!r||r.linkFieldCaptured.has(t)||(r.linkFieldCaptured.add(t),r.ops.push({kind:Rt.LINK_FIELD,linkId:t,before:pl(i)}))}noteProgressFallback(t,i){let r=this._journal;!r||r.progressFallbackBefore.has(t)||r.progressFallbackBefore.set(t,i)}};function pl(e){return{...e}}function ta(e,t,i){let r=[];for(let n of i){let o=e.get(n);if(!o)continue;let a=o.pendingRequestIds??[];if(ri({pendingRequestIds:a})&&t.getActivity(n)==null)for(let s of a)r.push({kind:Xr.SIR_AUTO_REJECT,activityId:n,sirId:s,reason:Zr.ACTIVITY_DELETED})}return r}function Mt(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 i=vm(e,t),r=new Map(t.beforeSnap),n=e.peekWriteCapture();if(n){let f=Sm(n);Cm(e,n,f,r,i)}let o=t.sirDetection,a=o===Lt.BEFORE_DIFF?ta(r,e,i):[],s=Am(t.correlativeShifts,i),c=await tn(e,r,i,s),l=o===Lt.AFTER_DIFF?ta(r,e,i):a,d=t.warnings??[],u=gm(t.links??[],n?Im(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 Im(e,t){let i=[];for(let r of t.ops){if(r.kind!==Rt.LINK_FIELD)continue;let n=e.getLink(r.linkId);if(!n)continue;let o={};for(let a of["freeSlackHours","isCritical"])Object.is(r.before[a],n[a])||(o[a]={before:r.before[a],after:n[a]});Object.keys(o).length!==0&&i.push({id:r.linkId,kind:N.UPDATED,fields:o,after:Mt(n)})}return i}function gm(e,t){let i=[],r=new Map;for(let n of e){let o=r.get(n.id);if(o===void 0){r.set(n.id,i.length),i.push(n);continue}let a=i[o];if((a.kind===N.UPDATED||a.kind===N.CREATED)&&n.kind===N.UPDATED){i[o]={...a,fields:{...a.fields,...n.fields},after:n.after};continue}i[o]=n}for(let n of t){let o=r.get(n.id);if(o===void 0){r.set(n.id,i.length),i.push(n);continue}let a=i[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;i[o]={...a,fields:{...a.fields,...s},after:n.after}}return i}function Am(e,t){if(!e||e.length===0)return;let i=new Map;for(let r of e)i.set(r.activityId,r.before),t.add(r.activityId);return i}function vm(e,t){let i=new Set;for(let r of t.touchedIds)i.add(r);for(let r of t.scheduledIds)i.add(r);if(t.includeAllIds)for(let r of e.getAllIds())i.add(r);return i}function Cm(e,t,i,r,n){for(let o of t.dirty){if(i.has(o)||r.has(o))continue;let a=t.before.get(o),s=e.getActivity(o);!a||!s||Object.keys(To(a,s)).length!==0&&(r.set(o,a),n.add(o))}}function Sm(e){return new Set(e.ops.filter(t=>t.kind===Rt.INSERT).map(t=>t.activityId))}function un(e,t,i){if(!e||e==="0")return;let r=i.getChildren(e);if(r.length===0)return;let n=new Map,o=new Set,a=0;for(let l of r){let d=Dm(String(l),t,i);n.set(String(l),d),a+=d,yl(String(l),i)&&o.add(String(l))}let s=a?100/a:0,c=o.size?100/o.size:0;for(let l of r){let d=i.getActivity(l);if(!d)continue;let u=Tm(String(l),d,n,o,a,s,c);u!==null&&i.setActivityField(l,E.PONDERATOR,u)}}function Tm(e,t,i,r,n,o,a){return t.type===T.PROJECT||gt(t)?n?o*(i.get(e)??0):r.has(e)?a:0:!Array.isArray(t.baselinePoints)||t.baselinePoints.length===0?0:null}function yl(e,t){let i=t.getActivity(e);return i?gt(i)?!0:i.type!==T.PROJECT?!1:t.getChildren(e).some(r=>yl(String(r),t)):!1}function Dm(e,t,i){let r=i.getActivity(e);if(!r)return 0;if(r.type===T.PROJECT)return hl(e,t,i);let n=gt(r);return!n||r.type===T.MILESTONE?0:ml(n,t)}function hl(e,t,i){let r=0;for(let n of i.getChildren(e)){let o=i.getActivity(n);if(!o)continue;if(o.type===T.PROJECT){r+=hl(String(n),t,i);continue}let a=gt(o);a&&o.type!==T.MILESTONE&&(r+=ml(a,t))}return r}function ml(e,t){return t===pt.COST?ea(e.cost):t===pt.WORK_HOURS?ea(e.workHours):ea(e.durationDays)}function ea(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){Em(e);let i=Rm(e.adapter),r=km(t,i);r.has(kt.AUTOSCHEDULE)&&await wm(e.adapter,t);let n=r.has(kt.AUTOSCHEDULE)?await Om(e,t.autoscheduleFrom,t.preventSummaryTargetPullback):Fm();return await xm(e.adapter,t,n.scheduledIds,r,i),await Um(e,r,t.now),n}function Em(e){let t=e.adapter.peekWriteCapture();if(!t)return;let i=new Set,r=e.sector.activityCreter??pt.DURATION;for(let[n,o]of t.before){let a=e.adapter.getActivity(n);if(o.type===T.PROJECT||a?.type!==T.PROJECT||gt(a)||!_m(n,e.adapter))continue;let s=n;for(;s!==null&&!U(s);)i.has(s)||(un(s,r,e.adapter),i.add(s)),s=e.adapter.getParentId(s)}}function _m(e,t){let i=[...t.getChildren(e)];for(;i.length>0;){let r=i.pop();if(r===void 0)continue;let n=t.getActivity(r);if(n&&gt(n))return!0;i.push(...t.getChildren(r))}return!1}async function Il(e,t,i){if(e.activityId!==void 0&&!i.adapter.activityExists(e.activityId))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let r=await Q(i.adapter,new Set(i.adapter.getAllIds()));i.scheduler.invalidateAllCaches();let n=e.activityId===void 0?i.adapter.getRootIds():[e.activityId],{scheduledIds:o}=await X({adapter:i.adapter,scheduler:i.scheduler,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId??Et.ROOTS,recomputeParentsFrom:n,now:i.now,options:t});return{ok:!0,changes:await $(i.adapter,{source:e,beforeSnap:r,touchedIds:n,scheduledIds:o,hoursPerDay:i.sector.hoursPerDay})}}function km(e,t){let i=e.autoscheduleFrom!==null,r=!e.options.skipAutoSchedule&&i,n=new Set(fl(e.action,{requested:i,ran:r},e.options));return(e.recomputeParentProgress||t.affectedParents.size>0)&&n.add(kt.PARENT_PROGRESS),n}function Rm(e){let t=new Set,i=new Set,r=e.peekWriteCapture();if(!r)return{affectedParents:t,dirtySeeds:i};let n=o=>{if(o===null||U(o))return;let a=String(o);t.add(a);let s=e.getChildren(a)[0];s!==void 0&&i.add(s)};return Pm(e,r.ops,n),Lm(e,r.before,i,n),{affectedParents:t,dirtySeeds:i}}function Pm(e,t,i){for(let r of t)if(r.kind===Rt.INSERT){let n=e.getActivity(r.activityId);n&&i(n.parentId)}else r.kind===Rt.REMOVE&&i(r.before.parentId)}function Lm(e,t,i,r){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)&&(r(a.parentId),i.add(String(n))),l&&(r(o.parentId),r(a.parentId),i.add(String(n)))}}async function Om(e,t,i=!1){let r=t===Et.ROOTS?{}:{triggerId:t};i&&(r.preventSummaryTargetPullback=!0);let n=await e.scheduler.schedule(r),o=bm(e.adapter,n.updatedIds),a=Nm(e.adapter,n);return Wi(e.adapter,n),{...o,warnings:a}}function Nm(e,t){let i=[];for(let r of t.plans.values()){let n=r.earliestSchedulingStart;if(!n||r.startDate>=n)continue;let o=e.getActivity(r.activityId);!o?.constraintType||!o.constraintDate||i.push({kind:We.VIOLATION,activityId:o.id,constraintType:o.constraintType,constraintDate:o.constraintDate,projectedDate:n,messageKey:We.VIOLATION})}return i}function bm(e,t){let i=[];for(let r of t){let n=String(r);i.push(n);let o=e.getActivity(n);o&&e.noteScheduledBefore(n,o)}return{scheduledIds:i,warnings:[]}}function Fm(){return{scheduledIds:[],warnings:[]}}async function wm(e,t){let i=t.collectDirty?t.collectDirty([]):Do(t.recomputeParentsFrom,[]);i.size!==0&&await di(e,i,!1)}async function xm(e,t,i,r,n){r.has(kt.PARENT_PROGRESS)&&Mm(e,n.affectedParents);let o=t.collectDirty?t.collectDirty(i):Do(t.recomputeParentsFrom,i);for(let a of n.dirtySeeds)o.add(a);await di(e,o,r.has(kt.PARENT_PROGRESS),{recomputeRealWork:r.has(kt.REAL_WORK),progressMode:"freeze-when-no-contribution"})}function Mm(e,t){for(let i of t){if(e.hasChildren(i))continue;let r=e.getProgressFallback(i);r!==null&&(e.setActivityField(i,"progress",r),e.setProgressFallback(i,null))}}async function Um(e,t,i){t.has(kt.EXPECTED_PROGRESS)&&i!==null&&(Hm(e.adapter)&&Ii(e.adapter,i,e.defaultBaseCalendarId??null),je(e.adapter,i),de(e.adapter,e.sector.statusCriteria)),t.has(kt.REAL_COST)&&gi(e.adapter),t.has(kt.CRITICAL_PATH)&&await al(e.adapter,e.sector.hoursPerDay)}function Hm(e){let t=!1;return e.forEachActivity(i=>{gt(i)&&(t=!0)}),t}var Bm=new Set([E.CONSTRAINT_TYPE,E.CONSTRAINT_DATE]),Wm=new Set([v.MSO,v.MFO]);function Ai(e){return Bm.has(e)}function fn(e){return e===E.CONSTRAINT_DATE}function pn(e,t,i,r){let n=i.getActivity(e);if(!n)return!1;let o=n.constraintType;if(!o||Te.has(o)||Wm.has(o))return!1;let a=ia(n.startDate),s=ia(i.getLastStartDate(e));if(!s||!a||a.getTime()!==s.getTime())return!1;let c=Vm(t,o,String(n.calendarId??""),r),l=ia(n.constraintDate);return jm(l,c)?!1:(i.setActivityField(e,"constraintDate",c),!0)}function Vm(e,t,i,r){if(e===null)return null;let n=r.getCalendar(i);return n?se(e,n,t):e}function ia(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 jm(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function yn(e,{postMutationArgs:t,revertTargets:i,revert:r}){let{scheduledIds:n}=await X(e,gl(t)),o=!1;for(let{activityId:a,priorConstraintDate:s}of i){let c=r(a,s);o=o||c}if(o){let a=await X(e,gl(t));n=Ym(n,a.scheduledIds)}return $e(t.action)&&await X(e,Km(t)),{scheduledIds:n}}function gl(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function Km(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function Ym(e,t){let i=new Set(e);for(let r of t)i.add(r);return[...i]}function vi(e,t,i){let r=[];for(let{op:n,finalLinkId:o,rejected:a}of e){if(a!==null)continue;if(n.kind===St.CREATE){if(!o)continue;let d=i.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&&r.push({id:String(o),kind:N.UPDATED,fields:f,after:Mt(d)});continue}r.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:Mt(d)});continue}if(n.kind===St.DELETE){if(i.getLink(n.linkId))continue;let d=t.get(n.linkId);r.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=i.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)}),r.push({id:String(n.linkId),kind:N.UPDATED,fields:l,after:Mt(c)})}return r}function Ci(e,t){let i=new Map;if(!e.getActivity(t))return i;for(let r of e.getIncomingLinkIds(t)){let n=e.getLink(r);n&&i.set(String(n.id),Number(n.lag))}return i}function Si(e,t,i){let r=[];if(!t.getActivity(i))return r;for(let n of t.getIncomingLinkIds(i)){let o=t.getLink(n);if(!o)continue;let a=e.get(String(o.id));a===void 0||a===Number(o.lag)||r.push({id:String(o.id),kind:N.UPDATED,fields:{lag:{before:a,after:Number(o.lag)}},after:Mt(o)})}return r}function hn(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function Al(e,t,i){let{adapter:r,ctx:n,scheduler:o,sector:a}=i,s=Ee(e.column);if(!s)return{ok:!1,reason:S.NO_PIPELINE_FOR_COLUMN};e.column===E.DURATION&&o.invalidateExpandedLinksCache();let c=n.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let l=s.canEdit(c,n.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??S.CANNOT_EDIT,alertKey:l.alertKey};let d=s.parseInput(e.newValue,c,n);if(!d.ok)return{ok:!1,reason:d.reason??S.PARSE_ERROR};let u=Reflect.get(c,s.targetField),f=s.validate(c,u,d.value,n);if(!f.valid)return{ok:!1,reason:f.reason??S.INVALID,alertKey:f.notification?.messageKey};if(e.column===E.CUSTOM_ID&&d.value!==null){let C=r.getActivity(e.activityId),L=C?C.customId:null,K=typeof L=="string"?L:null;if(i.customIdTracker.isCustomIdInUse(String(d.value),K))return{ok:!1,reason:S.CUSTOM_ID_DUPLICATE}}let p=s.transform(c,d.value,n,d.raw),y=_e(e.activityId,p),g=await Q(r,y),A=Ci(r,String(e.activityId)),k=c.constraintDate;ke(r,e.activityId,p),ve(e.activityId,p.postProcessors??[],r,g.get(String(e.activityId))??null);let _=Si(A,r,String(e.activityId));if(e.column===E.CUSTOM_ID){let C=g.get(String(e.activityId)),L=C?C.customId:null,K=typeof L=="string"?L:null,Y=typeof d.value=="string"?d.value:null;K!==Y&&i.customIdTracker.trackCustomIdChange(K,Y)}let F=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:C=>en(e.activityId,y,C),now:i.now,options:t}),m=Ai(e.column),{scheduledIds:R}=await(m?yn({adapter:r,scheduler:o,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{postMutationArgs:F(),revertTargets:fn(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:k}],revert:(C,L)=>pn(C,L,r,n.calendars)}):X({adapter:r,scheduler:o,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},F())),M=(p.trackingEvents??[]).map(C=>({name:C.name,properties:C.properties??{}}));s.trackEvent&&!(e.column===E.PROGRESS&&Number(d.value)<=0)&&M.unshift({name:s.trackEvent,properties:{activity_name:c.name,activity_id:c.id,activity_index:c.correlativeId}});let D=Ve(e.activityId,p.constraintWarning);return{ok:!0,changes:await $(r,{source:e,beforeSnap:g,touchedIds:y,scheduledIds:R,sirDetection:Lt.BEFORE_DIFF,links:_,trackingEvents:M,...D?{warnings:[D]}:{},hoursPerDay:a.hoursPerDay})}}function mn(e){return yr(e)}function In(e,t){return Object.hasOwn(e,t)}function Gm(e){if(e.kind===I.LINK_CREATE)return mn(e.type)?e.lag===void 0||Number.isFinite(e.lag)?null:S.INVALID_LINK_LAG:S.INVALID_LINK_TYPE;if(e.kind===I.LINK_UPDATE){if(In(e,"type")&&!mn(e.type))return S.INVALID_LINK_TYPE;if(In(e,"lag")&&!Number.isFinite(e.lag))return S.INVALID_LINK_LAG}return null}function $m(e){return e.kind===ot.CREATE?mn(e.type)?e.lag===void 0||Number.isFinite(e.lag)?null:S.INVALID_LINK_LAG:S.INVALID_LINK_TYPE:e.kind===ot.UPDATE?In(e,"type")&&!mn(e.type)?S.INVALID_LINK_TYPE:!In(e,"lag")||Number.isFinite(e.lag)?null:S.INVALID_LINK_LAG:e.kind===ot.DELETE?null:S.INVALID_VALUE}function zm(e){for(let t of e){let i=$m(t);if(i!==null)return i}return null}function qm(e,t){let i=new Set,r=new Map;for(let n of e){if(n.kind===ot.CREATE){i.add(String(n.source)),i.add(String(n.target));continue}let o=t.getLink(n.linkId);o&&(i.add(String(o.source)),i.add(String(o.target)),n.kind===ot.UPDATE&&(n.source!==void 0&&i.add(String(n.source)),n.target!==void 0&&i.add(String(n.target))),r.set(n.linkId,{...o}))}return{activityIds:i,links:r}}function Jm(e,t,i,r){return e.map((n,o)=>{let a=n.kind===ot.CREATE?r?.get(o):void 0,s=Ie(n,{port:t,newLinkId:a?()=>a:i.next});return{op:n,finalLinkId:s.applied?s.linkId:null,rejected:s.applied?null:s.rejected??S.INVALID}})}function Xm(e){return new Map([...e].map(([t,i])=>[String(t),i]))}async function vl(e,t,i){let r=Gm(e);return r!==null?{ok:!1,reason:r}:ra([nI(e,i.sector.hoursPerDay)],e,t,i,e.kind===I.LINK_CREATE&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function Cl(e,t,i){let r=zm(e.operations);if(r!==null)return{ok:!1,reason:r};let{hoursPerDay:n}=i.sector,o=e.operations.map(s=>tI(s,n)),a=Zm(e.operations);return ra(o,e,t,i,a)}function Zm(e){let t=new Map;return e.forEach((i,r)=>{i.kind===ot.CREATE&&i.linkId&&t.set(r,i.linkId)}),t.size>0?t:void 0}function Qm(e,t){if(e===void 0)return;let i=new Map,r=new Set,n=()=>{let o=t.linkIdGen.next();for(;t.adapter.getLink(o)!==null||t.isLinkIdReserved(String(o))||r.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))||r.has(String(a)),c=s?n():a;s||t.linkIdGen.bump(a),r.add(String(c)),i.set(o,c)}return i}function tI(e,t){return e.kind===ot.CREATE?{kind:ot.CREATE,source:e.source,target:e.target,type:e.type,lag:Vt(e.lag??0,t)}:e.kind===ot.UPDATE?{kind:ot.UPDATE,linkId:e.linkId,source:e.source,target:e.target,type:e.type,lag:e.lag===void 0?void 0:Vt(e.lag,t)}:{kind:ot.DELETE,linkId:e.linkId}}async function ra(e,t,i,r,n){let{adapter:o,scheduler:a,sector:s,linkIdGen:c}=r;a.invalidateAllCaches();let{activityIds:l,links:d}=qm(e,o),u=await Q(o,l),f=Jm(e,o,c,Qm(n,r));if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!==I.INLINE_EDIT)return{ok:!1,reason:f[0].rejected};i.skipAutoSchedule||eI(f,d,o);let p=iI(f,d,o),{scheduledIds:y,warnings:g}=await X({adapter:o,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:r.now,options:i}),A=vi(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:Xm(d),changes:await $(o,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:y,links:A,warnings:g,hoursPerDay:s.hoursPerDay})}}function eI(e,t,i){for(let r of e){if(r.rejected!==null||r.op.kind!==ot.DELETE)continue;let n=t.get(r.op.linkId)?.target;if(!n||i.getIncomingLinkIds(n).length>0)continue;let o=i.getActivity(n);if(!o||o.type!==T.MILESTONE)continue;let a=new Date(o.startDate);i.getOutgoingLinkIds(n).length===0&&a.setUTCHours(0,0,0,0);let s=i.getClosestWorkTime({date:a,dir:j.FUTURE,task:o});s.getTime()!==o.startDate.getTime()&&i.setActivityFields(n,{startDate:s,endDate:new Date(s)})}}function iI(e,t,i){for(let r of e){if(r.rejected!==null)continue;let n=rI(r.op,t,i);if(n!==null)return i.hasChildren(n)?Et.ROOTS:String(n)}return null}function rI(e,t,i){return e.kind===ot.CREATE?e.target:e.kind===ot.DELETE?t.get(e.linkId)?.target??null:i.getLink(e.linkId)?.target??null}function nI(e,t){return e.kind===I.LINK_CREATE?{kind:ot.CREATE,source:e.source,target:e.target,type:e.type,lag:Vt(e.lag??0,t)}:e.kind===I.LINK_UPDATE?{kind:ot.UPDATE,linkId:e.linkId,source:e.source,target:e.target,type:e.type,lag:e.lag===void 0?void 0:Vt(e.lag,t)}:{kind:ot.DELETE,linkId:e.linkId}}async function Sl(e,t,i){let{adapter:r,sector:n}=i;if(typeof e.newValue!="string")return{ok:!1,reason:S.INVALID_VALUE};if(!r.getActivity(e.activityId))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let a=e.column===E.CUSTOM_PREDECESSORS,{specs:s,errors:c}=xr(e.newValue,{daysPerWeek:n.hoursPerWeek/n.hoursPerDay});if(c.length>0)return{ok:!1,reason:S.INVALID_VALUE};let l=s.map(g=>({...g,lag:Vt(Br(g.lag),n.hoursPerDay)})),d=new Map;r.forEachActivity(g=>{g.correlativeId!=null&&d.set(String(g.correlativeId),g.id)});let u=g=>d.get(g)??null,f=a?r.getIncomingLinkIds(e.activityId):r.getOutgoingLinkIds(e.activityId),p=[];for(let g of f){let A=r.getLink(g);A&&p.push(A)}let y=a?Ur({targetActivityId:e.activityId,currentLinks:p,desiredSpecs:l,resolveActivityByCorrelative:u}):Hr({sourceActivityId:e.activityId,currentLinks:p,desiredSpecs:l,resolveActivityByCorrelative:u});return ra(y.operations,e,t,i)}var Kt={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=>{U(o.parentId)&&t.push(o)}),t.sort(El);let i=[];Tl(i,t);let r=[],n=0;for(;i.length>0;){let o=i.pop();if(o.correlativeId!==n){let s=typeof o.correlativeId=="number"?o.correlativeId:void 0;r.push({activityId:String(o.id),before:s}),s!==void 0&&e.noteCorrelativeBefore?.(String(o.id),s),oI(o,n)}n+=1;let a=Ui(String(o.id),e);a.sort(El),Tl(i,a)}return r}function Tl(e,t){for(let i=t.length-1;i>=0;i-=1)e.push(t[i])}function Dl(e){let t=e.correlativeId,i=typeof t=="number"?t:Number(t);return Number.isFinite(i)?i:ro}var El=(e,t)=>Dl(e)-Dl(t);function oI(e,t){e.correlativeId=t}function na(e,t){if(!e||e==="0")return;let i=String(e);for(;i!==null;){let{workHours:r,realWorkHours:n}=Rl(i,t);t.setActivityField(i,b.WORK_HOURS,r),t.setActivityField(i,b.REAL_WORK_HOURS,n);let o=t.getActivity(i);if(!o)break;let a=o.parentId;if(!a||U(a))break;i=a}}function _l(e,t){let i=t.getActivity(e);if(!i)return;let r=i.parentId;!r||U(r)||na(r,t)}function kl(e,t,i){for(let r of e){if(i.hasChildren(r))continue;let n=i.getActivity(r);n&&i.setActivityField(r,b.REAL_WORK_HOURS,xt(ir(n,b.WORK_HOURS),ir(n,b.PROGRESS)))}for(let r of t)i.setActivityField(r,b.REAL_WORK_HOURS,Rl(r,i).realWorkHours)}function Rl(e,t){let i=0,r=0;for(let n of t.getChildren(e)){let o=t.getActivity(n);if(!o)continue;let a=ir(o,b.WORK_HOURS);i+=a,r+=aI(n,o,a,t)}return{workHours:i,realWorkHours:r}}function ir(e,t){let i=e[t];return typeof i=="number"&&Number.isFinite(i)?i:0}function aI(e,t,i,r){return r.hasChildren(e)?ir(t,b.REAL_WORK_HOURS):xt(i,ir(t,b.PROGRESS))}function oa(e,t){if(!e||e==="0")return;let i=String(e);for(;i!==null;){let r=t.getChildren(i),n=0;for(let s of r){let c=t.getActivity(s);c&&(n+=sI(c,b.USED_COST))}t.setActivityField(i,b.USED_COST,n);let o=t.getActivity(i);if(!o)break;let a=o.parentId;if(!a||U(a))break;i=a}}function Pl(e,t){let i=t.getActivity(e);if(!i)return;let r=i.parentId;!r||U(r)||oa(r,t)}function sI(e,t){let i=e[t];return typeof i=="number"&&Number.isFinite(i)?i:0}function aa(e,t){if(!e||e==="0")return;let i=String(e);for(;i!==null;){let r=t.getChildren(i),n=0;for(let s of r){let c=t.getActivity(s);c&&(n+=cI(c,b.COST))}t.setActivityField(i,b.COST,n);let o=t.getActivity(i);if(!o)break;let a=o.parentId;if(!a||U(a))break;i=a}}function Ll(e,t){let i=t.getActivity(e);if(!i)return;let r=i.parentId;!r||U(r)||aa(r,t)}function cI(e,t){let i=e[t];return typeof i=="number"&&Number.isFinite(i)?i:0}var gn=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}),Ol="New Master Plan",Nl="New Activity";var lI=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],An=new Set(lI);function dI(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 i of Reflect.ownKeys(e))if(typeof i=="symbol"||!An.has(i))throw new Error(`activity-create: rejected override key "${String(i)}" \u2014 not a creation-writable canonical field`);return e}function bl(e,t){let i=e.parentId!=null?t.getActivity(e.parentId):null,r=dI(e.activityOverrides??{}),n=e.numTasksInGantt===0?Ol:Nl,o=r.name??n,a=r.durationHours??e.sector.hoursPerDay,s=r.calendarId??e.sector.defaultCalendar,c=uI(i,e.fallbackStartDate,r.startDate),l={...gn,...r,id:e.id,parentId:e.parentId,uniqueCorrelativeId:e.nextUniqueCorrelativeId,name:o,durationHours:a,calendarId:s,startDate:c,endDate:c},d=r.startDate?new Date(l.startDate):t.getClosestWorkTime({date:l.startDate,dir:j.FUTURE,task:l});if(!r.startDate&&i&&oe(i.type)){let p=new Date(i.startDate);p.setUTCHours(0,0,0,0);let y=new Date(d);y.setUTCHours(0,0,0,0),y.getTime()!==p.getTime()&&(d=t.getClosestWorkTime({date:p,dir:j.FUTURE,task:l}))}let u=t.calculateEndDate({startDate:d,durationHours:l.durationHours,task:l});return{newTask:{...l,startDate:d,endDate:u,calendarDuration:te({type:l.type,startDate:d,endDate:u}),newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function uI(e,t,i){return i?new Date(i):e?new Date(e.startDate):t?new Date(t):new Date}var Ti={CREATE:"create",REPARENT:"reparent"};function fI(e){let t=e.type;if(t!==T.TASK&&t!==T.MILESTONE)return null;let i=e.startDate,r=e.endDate;return!(i instanceof Date)||!(r instanceof Date)?null:{type:t,startDate:new Date(i),endDate:new Date(r),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 Pe(e){let t=e.getParent(e.parentId);if(!t)return null;let i=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&he(t.type):pI(t),r=Array.isArray(t.newActivityIds)?t.newActivityIds:[],o={isLookahead:!1,hasNewActivities:!0,newActivityIds:r.some(a=>String(a)===String(e.newChildId))?[...r]:[...r,e.newChildId]};return t.customId!=null&&t.customId!==""&&(o.customId=null),i&&(o.type=co,(e.promotionSource??Ti.CREATE)===Ti.CREATE&&(o.constraintType=v.ASAP,o.constraintDate=null)),{parentId:e.parentId,fields:o,promotionSnapshot:fI(t)}}function pI(e){return he(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function Di(e,t,i,r){let n=t,o=n==="0",a=sa(e,n);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);return d.length===0?l-1:(Math.max(...d)+l)/2}}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);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 ze=Number.MAX_SAFE_INTEGER,Fl=Number.MAX_SAFE_INTEGER-1;function Ot(e){let t=e.correlativeId,i=typeof t=="number"?t:Number(t);return Number.isFinite(i)?i:ze}function sa(e,t){return Ui(t,e)}function wl(e,t,i){let r=e,n=re(e,i);for(;n!=null&&t.has(n);)r=n,n=re(n,i);return r}function Ei(e,t,i){let r=new Set([e]),n=$t(i.getActivity(e)?.parentId);for(;n!=="0"&&!r.has(n);){if(t.has(n))return!0;r.add(n),n=$t(i.getActivity(n)?.parentId)}return!1}function re(e,t){let i=t.getActivity(e);if(!i)return null;let r=$t(i.parentId),n=Wt(r,t),o=n.findIndex(a=>String(a)===String(e));return o<=0?null:n[o-1]??null}function xl(e,t,i,r){let n=Wt(t,e).filter(c=>String(c)!==String(r)).map(c=>e.getActivity(c)).filter(c=>c!==null);if(n.length===0)return 0;let o=n.map(Ot);if(i<=0)return o[0]-1;if(i>=o.length)return o[o.length-1]+1;let a=o[i-1],s=o[i];return(a+s)/2}var yI=new Set([...[...An].filter(e=>e!==b.DURATION_HOURS),"durationDays"]);function vn(e,t){if(e===void 0)return{ok:!0,value:{}};let i=Object.getPrototypeOf(e);if(i!==null&&i!==Object.prototype)return{ok:!1,reason:S.INVALID_VALUE};for(let o of Reflect.ownKeys(e))if(typeof o=="symbol"||!yI.has(o))return{ok:!1,reason:S.INVALID_VALUE};let{durationDays:r,...n}=e;return r!==void 0&&(!Number.isFinite(r)||r<0)?{ok:!1,reason:S.INVALID_VALUE}:{ok:!0,value:{...n,...r===0&&(n.type===void 0||n.type===T.TASK)?{type:T.MILESTONE}:{},...r===void 0?{}:{durationHours:Me(r,t)}}}}async function rr(e,t,i={}){let{adapter:r,scheduler:n,sector:o,calendars:a,activityIdGen:s,uidGen:c}=t;i.skipCacheInvalidation||n.invalidateAllCaches();let l=hI(e,r);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=II(e.activityId,r,s,t.isActivityIdReserved),y=c.next(),g={id:p,parentId:f?null:e.parentId,sector:{id:o.id,hoursPerDay:o.hoursPerDay,defaultCalendar:TI(a)},numTasksInGantt:r.activityCount(),nextUniqueCorrelativeId:y,activityOverrides:e.overrides??{}},k=bl(g,{getActivity:C=>r.getActivity(C),calculateEndDate:C=>r.calculateEndDate(C),getClosestWorkTime:C=>r.getClosestWorkTime(C)}).newTask;k.realWorkHours=xt(k.workHours,k.progress),AI(k,e,t,u,d,i);let _=i.insertionCorrelativeId??Di(r,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);k.correlativeId=_;let F=new Set([p]);d&&F.add(d.id);let m=d!==null&&r.getChildren(d.id).length===0,R=m?d?.customId:null,M=i.skipBeforeSnap?new Map:await Q(r,F);r.addActivity(k),vI(e,p,d,r,m),R&&t.customIdTracker.releaseCustomId(R),i.skipRollupCascades||(_l(p,r),Pl(p,r),Ll(p,r));let D=CI(r,p,F,i);return{ok:!0,newId:p,parent:d,newActivity:k,beforeSnap:M,initialTouched:F,correlativeShifts:D}}function hI(e,t){let i=U(e.parentId),r=i?null:t.getActivity(e.parentId);if(!i&&!r)return{ok:!1,reason:S.PARENT_NOT_FOUND};if(r!==null&&ri(r))return{ok:!1,reason:S.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:S.ANCHOR_SIBLING_CONFLICT};let a=e.afterSiblingId??e.beforeSiblingId,s=mI(e,t,i,a);return s||{ok:!0,parent:r,anchorSiblingId:a,isRoot:i}}function mI(e,t,i,r){if(r===void 0)return null;let n=t.getActivity(r);if(!n)return{ok:!1,reason:S.ANCHOR_SIBLING_NOT_FOUND};let o=i?"0":e.parentId;return(n.parentId==null?"0":String(n.parentId))!==o?{ok:!1,reason:S.ANCHOR_SIBLING_WRONG_PARENT}:null}function II(e,t,i,r){let n=()=>{let o=i.next();for(;t.activityExists(o)||r(String(o));)o=i.next();return o};return e===void 0||t.activityExists(e)||r(String(e))?n():(i.bump(e),e)}function gI(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function AI(e,t,i,r,n,o){let{adapter:a,customIdTracker:s}=i,c=gI(t);if(c!==void 0){if(c.length===0)return;if(!s.isCustomIdInUse(c)){s.registerCustomId(c);return}}let l=o.customIdReferenceId??r,d=l!==void 0,u=d?a.getActivity(l):n;e.customId=s.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function vI(e,t,i,r,n){if(!i)return;let o=Pe({parentId:e.parentId,newChildId:t,isCurrentlyLeaf:n,getParent:a=>r.getActivity(a)??null});if(o){for(let[a,s]of Object.entries(o.fields))lt(r,o.parentId,a,s);o.promotionSnapshot&&r.setPromotionSnapshot(o.parentId,o.promotionSnapshot)}}function CI(e,t,i,r){if(r.skipCorrelativeRecompute)return[];let n=_t(e).filter(o=>o.activityId!==String(t));for(let o of n)i.add(o.activityId);return n}async function SI(e,t,i,r,n){let{newId:o,newActivity:a,beforeSnap:s,initialTouched:c,correlativeShifts:l}=i,d={name:Kt.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:o,created_duration:a.durationHours}};return t.eventSource!==void 0&&(d.properties.event_source=t.eventSource),$(e,{source:t,beforeSnap:s,touchedIds:c,scheduledIds:r,correlativeShifts:l,trackingEvents:[d],hoursPerDay:n})}async function Ml(e,t,i){let{adapter:r,scheduler:n,sector:o}=i,a=vn(e.overrides,o.hoursPerDay);if(!a.ok)return a;let s=await rr({...e,overrides:a.value},i);if(!s.ok)return s;let{newId:c}=s,l=s.newActivity.autoScheduling;r.setActivityField(c,"autoScheduling",!1);let d;try{d=await X({adapter:r,scheduler:n,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:c,recomputeParentsFrom:[c],preventSummaryTargetPullback:!0,now:i.now,options:t})}finally{r.setActivityField(c,"autoScheduling",l)}let{scheduledIds:u}=d;return{ok:!0,changes:await SI(r,e,s,u,o.hoursPerDay)}}function TI(e){for(let i of e.values())if(i.is_default)return i.id;let t=e.values().next();return!t.done&&t.value?t.value.id:"global"}function Ft(e,t){na(e,t),oa(e,t),aa(e,t)}function Cn(e,t){let i=new Set,r=[];for(let n of e){let o=String(n);i.has(o)||(i.add(o),r.push(o))}for(;r.length>0;){let n=r.pop(),o=t.getChildren(n);for(let a of o){let s=String(a);i.has(s)||(i.add(s),r.push(s))}}return i}function Sn(e,t){let i=new Set;for(let r of e){for(let n of t.getOutgoingLinkIds(r))i.add(String(n));for(let n of t.getIncomingLinkIds(r))i.add(String(n))}return[...i]}function DI(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 EI(e,t,i){let r=e.startDate;return!i||!(r instanceof Date)?{}:{endDate:i(r,t)}}function Le(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,i=e.defaultDurationHours,r=Number.isFinite(i),n=DI(e.promotionSnapshot)??(r?{type:ai,durationHours:i,progress:0,autoScheduling:!0,constraintType:v.ASAP,constraintDate:null,hasNewActivities:!1,...EI(t,i,e.computeEndDate)}:{type:ai});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 Tn(e){if(e.idsRemoved.size===0)return null;let t=e.parent.newActivityIds;if(!Array.isArray(t)||t.length===0)return null;let i=t,r=i.filter(n=>!e.idsRemoved.has(n)&&!e.idsRemoved.has(String(n)));return r.length===i.length?null:{parentId:String(e.parent.id),fields:{newActivityIds:[...r],hasNewActivities:r.length>0}}}var Ul=200;async function Hl(e,t,i){let{adapter:r,scheduler:n,customIdTracker:o,sector:a}=i;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:S.ACTIVITY_IDS_EMPTY};for(let C of e.activityIds)if(!r.getActivity(C))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let s=e.activityIds.filter(C=>{let L=r.getActivity(C);return!(L?.correlativeId===0&&L.type===T.PROJECT)}),c=Cn(s,r),l=Sn(c,r),d=new Set;for(let C of e.activityIds){let L=r.getActivity(C);if(!L)continue;let K=L.parentId;if(U(K))continue;let Y=String(K);c.has(Y)||d.add(Y)}let u=new Set([...c,...d]),f=await Q(r,u),p=new Map;for(let C of l){let L=r.getLink(C);L&&p.set(C,{...L})}let y=new Set,g=0;for(let C of c){g+=1,g%Ul===0&&await ct();let L=r.getActivity(C);if(!L)continue;let K=U(L.parentId)?null:r.getActivity(String(L.parentId)),Y=K?.hasNewActivities===!0&&K.newActivityIds.some(rt=>String(rt)===String(C));(L.isNewActivity===!0||Y)&&y.add(C);let it=L.customId;typeof it=="string"&&it.length>0&&o.releaseCustomId(it)}for(let C of l)r.removeLink(C);let A=nr(r,c),k=0;for(let C of c)k+=1,k%Ul===0&&await ct(),r.removeActivity(C);for(let C of d){let L=r.getActivity(C);if(!L)continue;_I(L,y,r);let K=r.getChildren(C),Y=Le({parent:L,remainingChildIds:K.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:r.getPromotionSnapshot(C),computeEndDate:(it,rt)=>r.calculateEndDate({startDate:it,durationHours:rt,task:L}),idsRemoved:c});if(!Y){Vr(C,r);continue}for(let[it,rt]of Object.entries(Y.fields))lt(r,C,it,rt);if(L.customId==null||L.customId===""){let it=re(C,r),rt=it?r.getActivity(it)?.customId:null,vt=o.generateCustomIdForRestoredChild(typeof rt=="string"&&rt?rt:null);r.setActivityField(C,b.CUSTOM_ID,vt)}}for(let C of d)Ft(C,r);let _=_t(r),{scheduledIds:F}=await X({adapter:r,scheduler:n,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:Et.ROOTS,recomputeParentsFrom:d,now:i.now,options:t}),m={name:Kt.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:c.size}};e.eventSource!==void 0&&(m.properties.event_source=e.eventSource);let R=new Map;for(let[C,L]of p)R.set(C,L);let M=new Map;for(let C of c){let L=f.get(String(C));L&&M.set(String(C),L)}let D=await $(r,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:F,sirDetection:Lt.AFTER_DIFF,links:qe(p),trackingEvents:[m],hoursPerDay:a.hoursPerDay,correlativeShifts:_});return{ok:!0,changes:A.length>0?{...D,viewState:A}:D,__beforeSnap:M,__beforeLinks:R}}function _I(e,t,i){let r=Tn({parent:e,idsRemoved:t});if(r)for(let[n,o]of Object.entries(r.fields))lt(i,r.parentId,n,o)}function nr(e,t){let i=[];for(let r of t){let n=e.isChecked(r),o=e.isVisible(r);!n&&o||i.push({activityId:String(r),...n?{checked:{before:!0,after:!1}}:{},...o?{}:{visible:{before:!1,after:!0}}})}return i}function qe(e){let t=[];for(let[i,r]of e.entries())t.push({id:i,kind:N.DELETED,fields:{source:{before:String(r.source),after:void 0},target:{before:String(r.target),after:void 0},type:{before:r.type,after:void 0},lag:{before:Number(r.lag),after:void 0}},after:null});return t}async function Vl(e,t,i){let r=kI(e,i);if(r)return{ok:!1,reason:r};let n=PI(e,i);if(!n.ok)return n;let o=e.mode===mt.REPLACE?new Set(i.adapter.getAllIds().map(m=>String(m))):new Set,a=e.mode===mt.REPLACE?await Q(i.adapter,o):new Map,s=e.mode===mt.REPLACE?wI(i):new Map,c=e.mode===mt.REPLACE?nr(i.adapter,o):[];i.scheduler.invalidateAllCaches();let l=[];if(e.mode===mt.REPLACE){for(let m of s.keys()){let R=Ie({kind:ot.DELETE,linkId:m},{port:i.adapter});if(!R.applied)return{ok:!1,reason:R.rejected??S.INVALID};l.push({op:{kind:ot.DELETE,linkId:m},finalLinkId:m,rejected:null})}for(let m of o){let R=i.adapter.getActivity(m)?.customId;typeof R=="string"&&R.length>0&&i.customIdTracker.releaseCustomId(R),i.adapter.removeActivity(m)}}let d=await FI(e,n.plan.items,i);if(!d.ok)return d;let u=jl(e)?[]:_t(i.adapter),f=new Set(n.plan.items.map(m=>String(m.activityId))),p=u.filter(m=>!f.has(m.activityId)),y=e.mode===mt.REPLACE?new Set(o):new Set;hi(i.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:ot.CREATE,source:m.source,target:m.target,type:m.type,lag:Vt(m.lag??0,i.sector.hoursPerDay)},linkId:m.linkId})),A=br(g,{port:i.adapter,preserved:s});if(!A.applied)return{ok:!1,reason:A.rejected??S.INVALID};for(let{operation:m,linkId:R}of g)l.push({op:m,finalLinkId:R,rejected:null});let k=n.plan.items.map(m=>m.activityId),{scheduledIds:_}=await X({adapter:i.adapter,scheduler:i.scheduler,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.items.length>0||e.links.length>0?Et.ROOTS:null,recomputeParentsFrom:k,now:i.now,options:t}),F=await $(i.adapter,{source:e,beforeSnap:a,touchedIds:y,scheduledIds:_,links:vi(l,s,i.adapter),hoursPerDay:i.sector.hoursPerDay,correlativeShifts:p,...e.mode===mt.REPLACE?{sirDetection:Lt.AFTER_DIFF}:{}});return{ok:!0,changes:c.length>0?{...F,viewState:c}:F,...e.mode===mt.REPLACE?{__beforeSnap:a,__beforeLinks:xI(s)}:{}}}function kI(e,t){if(e.mode!==mt.APPEND&&e.mode!==mt.REPLACE)return S.INVALID;let i=new Set,r=new Set;for(let o of e.items){if(o.batchId.length===0||i.has(o.batchId))return S.INVALID;if(i.add(o.batchId),o.index!==void 0&&(!Number.isInteger(o.index)||o.index<0))return S.INVALID;if(o.activityId!==void 0){let a=String(o.activityId);if(a.length===0||a==="0"||r.has(a))return S.INVALID;r.add(a)}}for(let o of e.items)if(!la(o.parent,!0,e.mode,i,t))return S.PARENT_NOT_FOUND;if(RI(e.items))return S.INVALID;let n=new Set;for(let o of e.links){if(!Object.values(B).includes(o.type))return S.INVALID_LINK_TYPE;if(o.lag!==void 0&&!Number.isFinite(o.lag))return S.INVALID_LINK_LAG;if(!la(o.source,!1,e.mode,i,t)||!la(o.target,!1,e.mode,i,t))return S.ACTIVITY_NOT_FOUND;if(o.linkId!==void 0){let a=String(o.linkId);if(a.length===0||n.has(a))return S.INVALID;n.add(a)}}return null}function la(e,t,i,r,n){return typeof e=="string"?e==="0"?t:i===mt.APPEND&&n.adapter.getActivity(String(e))!==null:e!==null&&e.batchId.length>0&&r.has(e.batchId)}function RI(e){let t=new Map;for(let r of e)typeof r.parent!="string"&&t.set(r.batchId,r.parent.batchId);let i=new Set;for(let r of e){let n=new Set,o=r.batchId;for(;o!==void 0&&!i.has(o);){if(n.has(o))return!0;n.add(o),o=t.get(o)}for(let a of n)i.add(a)}return!1}function PI(e,t){let i=new Map;for(let d of e.items){let u=vn(d.overrides,t.sector.hoursPerDay);if(!u.ok)return u;i.set(d.batchId,u.value)}let r=new Map,n=new Set;for(let d of e.items){let u=LI(d.activityId,e.mode,n,t);n.add(String(u)),r.set(d.batchId,u)}let o=new Set,a=e.links.map(d=>{let u=OI(d.linkId,e.mode,o,t);return o.add(String(u)),u}),s=NI(e,r,t),c=[];for(let d of e.items){let u=r.get(d.batchId),f=s.get(d.batchId);if(u===void 0||f===void 0)return{ok:!1,reason:S.INVALID};let p=typeof d.parent=="string"?null:d.parent.batchId,y=typeof d.parent=="string"?d.parent:r.get(d.parent.batchId);if(y===void 0)return{ok:!1,reason:S.PARENT_NOT_FOUND};c.push({input:d,activityId:u,parentId:y,parentBatchId:p,insertionCorrelativeId:f,overrides:i.get(d.batchId)??{}})}let l=[];for(let[d,u]of e.links.entries()){let f=Wl(u.source,r),p=Wl(u.target,r),y=a[d];if(f===null||p===null||y===void 0)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};l.push({source:f,target:p,type:u.type,lag:u.lag??0,linkId:y})}return{ok:!0,plan:{items:c,links:l}}}function LI(e,t,i,r){if(e!==void 0&&(t===mt.REPLACE||r.adapter.getActivity(e)===null&&!r.isActivityIdReserved(String(e)))&&!i.has(String(e)))return r.activityIdGen.bump(e),e;let o=r.activityIdGen.next();for(;i.has(String(o))||t===mt.APPEND&&(r.adapter.getActivity(o)!==null||r.isActivityIdReserved(String(o)));)o=r.activityIdGen.next();return o}function OI(e,t,i,r){if(e!==void 0&&(t===mt.REPLACE||r.adapter.getLink(e)===null&&!r.isLinkIdReserved(String(e)))&&!i.has(String(e)))return r.linkIdGen.bump(e),e;let o=r.linkIdGen.next();for(;i.has(String(o))||t===mt.APPEND&&(r.adapter.getLink(o)!==null||r.isLinkIdReserved(String(o)));)o=r.linkIdGen.next();return o}function NI(e,t,i){if(jl(e)){let s=i.adapter.activityCount();return new Map(e.items.map((c,l)=>[c.batchId,s+l]))}let r=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)?[]:sa(i.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(!r.has(c[l])){l+=1;continue}let d=l;for(;l<c.length&&r.has(c[l]);)l+=1;let u=l-d,f=d>0?Bl(c[d-1],i):null,p=l<c.length?Bl(c[l],i):null;for(let y=0;y<u;y+=1){let g=c[d+y],A=a.get(g);A!==void 0&&o.set(A,bI(f,p,y+1,u))}}}return o}function jl(e){return e.mode===mt.APPEND&&e.items.every(t=>t.parent==="0"&&t.index===void 0)}function Bl(e,t){let i=t.adapter.getActivity(e);return i?Ot(i):0}function bI(e,t,i,r){return e!==null&&t!==null&&t>e?e+(t-e)*i/(r+1):e!==null?e+i:t!==null?t-(r-i+1):i-1}async function FI(e,t,i){let r=new Map,n=[];for(let a of t){if(a.parentBatchId===null){n.push(a);continue}let s=r.get(a.parentBatchId)??[];s.push(a),r.set(a.parentBatchId,s)}for(let a=0;a<n.length;a+=1){let s=n[a],c=await rr({kind:I.ACTIVITY_CREATE,parentId:s.parentId,activityId:s.activityId,overrides:s.overrides,...e.eventSource===void 0?{}:{eventSource:e.eventSource}},i,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,skipCacheInvalidation:!0,skipRollupCascades:!0,insertionCorrelativeId:s.insertionCorrelativeId});if(!c.ok)return c;for(let l of r.get(s.input.batchId)??[])n.push(l)}if(n.length!==t.length)return{ok:!1,reason:S.INVALID};let o=new Set;for(let a=n.length-1;a>=0;a-=1){let s=n[a].parentId;s==="0"||o.has(String(s))||(o.add(String(s)),Ft(s,i.adapter))}return{ok:!0}}function Wl(e,t){return typeof e=="string"?e:t.get(e.batchId)??null}function wI(e){return new Map(e.adapter.getAllLinks().map(t=>[String(t.id),{...t}]))}function xI(e){return new Map(Array.from(e,([t,i])=>[String(t),i]))}function Kl(e,t){let{adapter:i}=t,r=e.activityId,n=i.getActivity(r);if(!n)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let o=n.pendingRequestIds??[],a=e.pendingRequests.map(l=>l.id);i.setActivityField(e.activityId,"pendingRequestIds",a);let s=i.getActivity(r);if(!s)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let c={id:r,kind:N.UPDATED,fields:{pendingRequestIds:{before:o,after:a}},after:nt(s)};return{ok:!0,changes:{source:e,activities:[c],links:[],calendars:[],trackingEvents:[]}}}function Yl(e){let t=new Map;for(let i of e){let r=i.proplannerId;typeof r=="number"&&Number.isSafeInteger(r)&&r>0&&t.set(r,String(i.id))}return t}function Gl(e,t,i){let r=new Set(t.map(({id:n})=>String(n)));for(let n of e)if((n.proplannerId==null||n.proplannerId===0)&&!r.has(String(n.id)))throw new Error(`persistence-acknowledge: missing ${i} proplannerId for "${String(n.id)}"`)}function MI(e,t,i,r,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=i(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=r.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 $l(e,t,i,r){let n=new Set,o=new Set;for(let a of e)MI(a,t,i,r,n,o)}async function zl(e,t){let i=e.filter(s=>{let c=t.adapter.getActivity(String(s.activityId));return c!==null&&c.progress!==s.progress}),r=new Set(i.map(s=>String(s.activityId))),n=Gi(t.adapter,r),o=new Set(r);for(let s of n)o.add(String(s));let a=await Q(t.adapter,o);return t.adapter.batchUpdate(()=>{for(let s of i){let c=String(s.activityId);t.adapter.setActivityField(c,"progress",s.progress),t.adapter.setActivityField(c,"autoScheduling",we(s.progress))}zs(n,t.adapter),kl(r,n,t.adapter)}),[...await tn(t.adapter,a,o)]}async function ql(e,t){let i=e.activities??[],r=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=Yl(a),u=Yl(s);$l(i,"activity",y=>{let g=c.get(y);return{exists:g!==void 0,current:g?.proplannerId??null}},d),$l(r,"link",y=>{let g=l.get(y);return{exists:g!==void 0,current:g?.proplannerId??null}},u),Gl(a,i,"activity"),Gl(s,r,"link");let f=[],p=[];return t.adapter.batchUpdate(()=>{for(let y of i){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 r){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 Jl(e,t,i){if(UI(e))return{ok:!1,reason:S.INVALID_VALUE};let r=[...new Set(e.activityIds.map(String))];if(e.acknowledgePersistedLookahead===!0&&r.some(s=>!i.isActivityIdReserved(s)))return{ok:!1,reason:S.INVALID};let o=r.map(s=>i.adapter.getActivity(s));if(o.some(s=>!s))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let a=[];for(let[s,c]of r.entries()){let l=o[s];if(!l)continue;let d={};l.isLookahead!==e.isLookahead&&(d.isLookahead={before:l.isLookahead,after:e.isLookahead},i.adapter.setActivityField(c,"isLookahead",e.isLookahead)),l.hasLookaheadTasks!==e.hasLookaheadTasks&&(d.hasLookaheadTasks={before:l.hasLookaheadTasks,after:e.hasLookaheadTasks},i.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 zl([{activityId:r[0],progress:e.persistedProgress}],i)).length>0?(await X({adapter:i.adapter,scheduler:i.scheduler,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.persistedProgress===0?r[0]:null,recomputeParentsFrom:[],now:i.now,options:t}),{ok:!0,changes:await $(i.adapter,{source:e,beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:i.sector.hoursPerDay})}):{ok:!0,changes:{source:e,activities:a,links:[],calendars:[],trackingEvents:[]}}}function UI(e){let t=e.persistedProgress;return t!==void 0&&(e.activityIds.length!==1||!Number.isFinite(t)||t<0||t>100)}function ua(e,t){let{adapter:i}=t,r=new Set(e.conversionRootIds.map(f=>String(f)));if(r.size===0)throw new Error("Conversion requires at least one root");for(let f of r)zI(f,i);let n=i.getVisualOrderIds().filter(f=>r.has(f)&&!Ei(f,r,i)),o=n.map(f=>HI(f,i)),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=Sn(d,i);return{sourceStateRevision:t.stateRevision,conversionRootIds:n,conversionGroups:a,milestoneMoves:s,activityIdsToDelete:c,linkIdsToDelete:u,formerParents:l}}async function Ql(e,t,i){if(e.expectedStateRevision!==i.stateRevision)return{ok:!1,reason:S.STALE_STATE_REVISION};let r=ua(e,i);if(!qI(r,i.adapter))return{ok:!1,reason:S.HIERARCHY_CYCLE};let{adapter:n,scheduler:o}=i;o.invalidateAllCaches();let a=await jI(r,n);KI(r,i),td(r,n),YI(r,a.deletedIds,n);let s=GI(r,n);hi(n,s,a.deletedIds,a.beforeSnap,a.touchedIds);let{scheduledIds:c}=await X({adapter:n,scheduler:o,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:a.touchedIds,now:i.now,options:t,recomputeParentProgress:!0}),l=await $(n,{source:e,beforeSnap:a.beforeSnap,touchedIds:a.touchedIds,scheduledIds:c,sirDetection:"after-diff",links:qe(a.beforeLinks),hoursPerDay:i.sector.hoursPerDay,correlativeShifts:s});return $I(r,a,l)}function HI(e,t){let i=da(e,t),r=Cn([e],t);if(r.delete(e),r.size===0)throw new Error(`Conversion root ${e} has no descendants`);let n=t.getVisualOrderIds().filter(c=>r.has(c)).map(c=>da(c,t));Zl(i);for(let c of n)Zl(c);let o=n.filter(c=>c.type!==T.MILESTONE),a=n.filter(c=>c.type===T.MILESTONE),s=BI(i,o);return{conversionRootId:e,convertedActivities:o.map(c=>WI(c,s)),milestoneMoves:VI(i,a),activityIdsToDelete:o.map(c=>c.id),formerParent:{activity:nt(i),hasConvertedActivities:o.length>0}}}function BI(e,t){let i=new Map;t.length>0&&i.set(e.id,Xl(e));for(let r of t)i.set(r.id,Xl(r));return i}function WI(e,t){let i=nt(e),r=$t(e.parentId),n=t.get(r);return i.parentId=n===void 0?null:String(n),i}function VI(e,t){let i=[],r=$t(e.parentId),n=e.id;for(let o of t)i.push({activityId:o.id,parentId:r,afterSiblingId:n}),n=o.id;return i}async function jI(e,t){let i=new Set(e.activityIdsToDelete),r=new Set([...e.conversionRootIds,...e.activityIdsToDelete,...e.milestoneMoves.map(({activityId:n})=>n),...e.milestoneMoves.map(({parentId:n})=>n).filter(n=>n!=="0")]);return{deletedIds:i,touchedIds:r,beforeSnap:await Q(t,r),beforeLinks:JI(e.linkIdsToDelete,t),viewStateChanges:nr(t,i)}}function KI(e,t){for(let i of e.activityIdsToDelete){let r=t.adapter.getActivity(i)?.customId;r&&t.customIdTracker.releaseCustomId(r)}}function td(e,t){for(let i of e.milestoneMoves)t.setActivityFields(i.activityId,{parentId:i.parentId,correlativeId:Di(t,i.parentId,i.afterSiblingId,void 0)});for(let i of e.linkIdsToDelete)t.removeLink(i);for(let i of[...e.activityIdsToDelete].reverse())t.removeActivity(i);for(let{activity:i}of e.formerParents)t.setActivityField(i.id,b.TYPE,T.TASK)}function YI(e,t,i){for(let{activity:r,hasConvertedActivities:n}of e.formerParents){let o=da(r.id,i),a=Tn({parent:o,idsRemoved:t});i.setActivityFields(r.id,{isLookahead:r.isLookahead||n,hasLookaheadTasks:r.hasLookaheadTasks||n,...a?.fields??{}})}}function GI(e,t){for(let{activity:i}of e.formerParents)Ft(i.parentId,t);return _t(t)}function $I(e,t,i){let r=new Map;for(let n of t.deletedIds){let o=t.beforeSnap.get(n);o&&r.set(n,o)}return{ok:!0,changes:t.viewStateChanges.length===0?i:{...i,viewState:t.viewStateChanges},conversionGroups:e.conversionGroups.map(({conversionRootId:n,convertedActivities:o})=>({conversionRootId:n,convertedActivities:o.map(a=>nt(a))})),__beforeSnap:r,__beforeLinks:t.beforeLinks}}function zI(e,t){let i=t.getActivity(e);if(!i)throw new Error(`Conversion root ${e} was not found`);if(i.type===T.PROJECT&&i.correlativeId===0)throw new Error(`Conversion root ${e} is the visual project root`)}function da(e,t){let i=t.getActivity(e);if(!i)throw new Error(`Conversion activity ${e} is missing`);return i}function Xl(e){if(e.proplannerId==null)throw new Error(`Conversion activity ${e.id} has no persisted identifier`);return e.proplannerId}function Zl(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 qI(e,t){let i=t.fork();return td(e,i),me({port:t,proposedPort:i,currentLinks:t.getAllLinks(),proposedLinks:i.getAllLinks()}).ok}function JI(e,t){let i=new Map;for(let r of e){let n=t.getLink(r);n&&i.set(r,{...n})}return i}function _i(e,t){let i=new Set;for(let n of e)i.add(String(n));let r=[];for(let n of t.getAllLinks()){let o=String(n.source),a=String(n.target);!i.has(o)&&!i.has(a)||(ed(a,o,t)||ed(o,a,t))&&r.push(String(n.id))}return r}function ed(e,t,i){let r=String(e),n=new Set;for(;r!=null;){if(n.has(r))return!1;n.add(r);let o=i.getActivity(r);if(!o)return!1;let a=o.parentId;if(a===null||U(a))return!1;let s=a;if(s===t)return!0;r=s}return!1}function Dn(e,t){let i=e.getAllLinks();return!me({port:e,currentLinks:i,proposedLinks:i,proposal:{reparented:t}}).ok}function En(e,t){let i=new Set;if(e.length===0)return i;let r=new Map(e.map(o=>[o.activityId,o.newParentId]));if(!Dn(t,r))return i;let n=new Map;for(let o of e){let a=new Map(n);if(a.set(o.activityId,o.newParentId),Dn(t,a)){i.add(o.activityId);continue}n.set(o.activityId,o.newParentId)}return i}async function id(e,t,i){let{adapter:r,scheduler:n,sector:o}=i;n.invalidateAllCaches();let a=r.getActivity(e.activityId);if(!a)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let s=U(e.parentId);if(!s&&!r.getActivity(e.parentId))return{ok:!1,reason:S.PARENT_NOT_FOUND};if(!s&&(e.parentId===e.activityId||r.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:S.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:S.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let R=r.getActivity(c);if(!R)return{ok:!1,reason:S.ANCHOR_SIBLING_NOT_FOUND};if((R.parentId===null?"0":String(R.parentId))!==e.parentId)return{ok:!1,reason:S.ANCHOR_SIBLING_WRONG_PARENT}}let l=a.parentId,d=$t(l),u=String(e.parentId),f=d!==u;if(f){let R=new Map([[e.activityId,s?null:e.parentId]]);if(Dn(r,R))return{ok:!1,reason:S.HIERARCHY_CYCLE}}let p=new Set([e.activityId]);f?(d!=="0"&&p.add(d),u!=="0"&&p.add(u)):d!=="0"&&p.add(d);let y=await Q(r,p);f&&r.setActivityField(e.activityId,b.PARENT,u);let g=Di(r,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(r.setActivityField(e.activityId,b.CORRELATIVE_ID,g),f){if(!s){let R=r.getActivity(e.parentId);if(R){let M=R.customId,D=he(R.type)&&r.getChildren(e.parentId).filter(L=>L!==e.activityId).length===0,C=Pe({parentId:e.parentId,newChildId:e.activityId,getParent:L=>r.getActivity(L)??null,isCurrentlyLeaf:D,promotionSource:Ti.REPARENT});if(C){for(let[L,K]of Object.entries(C.fields))lt(r,C.parentId,L,K);C.promotionSnapshot&&r.setPromotionSnapshot(C.parentId,C.promotionSnapshot),C.fields.customId===null&&hn(M,i.customIdTracker)}}}if(d!=="0"){let R=r.getActivity(d);if(R){let M=r.getChildren(d),D=Le({parent:R,remainingChildIds:M.map(String),defaultDurationHours:o.hoursPerDay,promotionSnapshot:r.getPromotionSnapshot(d),computeEndDate:(C,L)=>r.calculateEndDate({startDate:C,durationHours:L,task:R}),idsRemoved:new Set([e.activityId])});if(D){for(let[it,rt]of Object.entries(D.fields))lt(r,d,it,rt);let C=re(d,r),L=C?r.getActivity(C)?.customId:null,K=typeof L=="string"&&L?L:null,Y=i.customIdTracker.generateCustomIdForRestoredChild(K);r.setActivityField(d,b.CUSTOM_ID,Y)}}}}f&&(d!=="0"&&Ft(d,r),s||Ft(e.parentId,r));let A=_t(r);for(let R of A){if(p.add(R.activityId),y.has(R.activityId))continue;let M=r.getActivity(R.activityId);if(!M)continue;let D=nt(M);R.before!==void 0&&(D.correlativeId=R.before),y.set(R.activityId,D)}let k=f&&d!=="0"?r.getChildren(d).map(String):[],{scheduledIds:_}=await X({adapter:r,scheduler:n,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,...k],now:i.now,options:t,recomputeParentProgress:f}),F=f?_i([e.activityId],r):[],m={name:Kt.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:F.map(String)}};return e.eventSource!==void 0&&(m.properties.event_source=e.eventSource),{ok:!0,changes:await $(r,{source:e,beforeSnap:y,touchedIds:p,scheduledIds:_,sirDetection:Lt.BEFORE_DIFF,trackingEvents:[m],hoursPerDay:o.hoursPerDay})}}function _n(e,t){let i=new Set(e),r=[],n=[],o=new Set,a=new Set(i),s=[...e].sort((d,u)=>{let f=t.getActivity(d),p=t.getActivity(u),y=f?Ot(f):ze,g=p?Ot(p):ze;return y-g});for(let d of s){if(!t.getActivity(d)){r.push({activityId:d,reason:S.ACTIVITY_NOT_FOUND}),a.delete(d);continue}if(Ei(d,o,t))continue;let f=gs(d,a,t);if(f==null){r.push({activityId:d,reason:S.INDENT_NO_ELIGIBLE_SIBLING}),a.delete(d);continue}let p=t.getActivity(d)?.parentId,y=U(p)?"0":String(p);n.push({activityId:d,newParentId:f,oldParentId:y}),o.add(d)}let c=En(n,t);for(let d of c)r.push({activityId:d,reason:S.HIERARCHY_CYCLE});let l=n.filter(d=>!c.has(d.activityId));return{moves:n,cyclicMoveIds:c,allowedMoves:l,failed:r}}async function rd(e,t,i){let{adapter:r,scheduler:n,sector:o}=i;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:S.ACTIVITY_IDS_EMPTY};let a=new Set,s=[],c=_n(e.activityIds,r),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(r,a);for(let{activityId:m,newParentId:R}of d)r.setActivityField(m,b.PARENT,R),r.setActivityField(m,b.CORRELATIVE_ID,Fl),s.push(m);let f=new Set;for(let{activityId:m,newParentId:R}of d){if(f.has(R))continue;f.add(R);let M=r.getActivity(R);if(!M)continue;let D=M.customId,C=he(M.type)&&r.getChildren(R).filter(Y=>!s.includes(Y)).length===0,L=M.hasNewActivities&&M.newActivityIds.some(Y=>String(Y)===String(m)),K=Pe({parentId:R,newChildId:m,getParent:Y=>r.getActivity(Y)??null,isCurrentlyLeaf:C,promotionSource:Ti.REPARENT});if(K){for(let[Y,it]of Object.entries(K.fields))lt(r,K.parentId,Y,it);K.promotionSnapshot&&r.setPromotionSnapshot(K.parentId,K.promotionSnapshot),L||(r.setActivityField(R,b.HAS_NEW_ACTIVITIES,!1),r.setActivityField(R,b.NEW_ACTIVITIES_ARRAY,[]))}r.setActivityField(R,b.CONSTRAINT_TYPE,v.ASAP),r.setActivityField(R,b.CONSTRAINT_DATE,null),r.setActivityField(R,b.CUSTOM_ID,null),hn(D,i.customIdTracker)}let p=new Set;for(let m of d)m.oldParentId!=="0"&&p.add(m.oldParentId),p.add(m.newParentId);for(let m of p)Ft(m,r);let y=_t(r);for(let m of y){if(a.add(m.activityId),u.has(m.activityId))continue;let R=r.getActivity(m.activityId);if(!R)continue;let M=nt(R);m.before!==void 0&&(M.correlativeId=m.before),u.set(m.activityId,M)}let g=_i(s,r),A=new Map;for(let m of g){let R=r.getLink(m);R&&(A.set(m,{...R}),r.removeLink(m))}let{scheduledIds:k}=await X({adapter:r,scheduler:n,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:s,now:i.now,options:t}),_={name:Kt.ACTIVITY_INDENT,properties:{activity_ids:s,failed:l.map(m=>({activity_id:m.activityId,reason:m.reason})),invalid_link_ids:g}};e.eventSource!==void 0&&(_.properties.event_source=e.eventSource);let F=await $(r,{source:e,beforeSnap:u,touchedIds:a,scheduledIds:k,links:qe(A),trackingEvents:[_],hoursPerDay:o.hoursPerDay});return{ok:!0,activityVerdicts:e.activityIds.map(m=>{let R=l.find(M=>String(M.activityId)===String(m));return R?{activityId:String(m),ok:!1,reason:R.reason}:{activityId:String(m),ok:!0}}),changes:F,__beforeLinks:A}}async function nd(e,t,i){let{adapter:r,scheduler:n,sector:o}=i;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:S.ACTIVITY_IDS_EMPTY};let a=new Set(e.activityIds),s=new Map,c=new Map;for(let D of e.activityIds){let C=D;r.getActivity(C)&&(s.set(C,no(C,r)),c.set(C,wl(C,a,r)))}let l=new Set,d=[],u=[],f=new Set,p=[],y=new Set,g=[...e.activityIds].sort((D,C)=>{let L=r.getActivity(D),K=r.getActivity(C),Y=L?Ot(L):ze,it=K?Ot(K):ze;return Y-it});for(let D of g){let C=D,L=r.getActivity(C);if(!L){d.push({activityId:C,reason:S.ACTIVITY_NOT_FOUND});continue}if(Ei(C,y,r))continue;let K=L.parentId;if(U(K)){d.push({activityId:C,reason:S.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let Y=String(K),it=r.getActivity(Y);if(!it){d.push({activityId:C,reason:S.ACTIVITY_NOT_FOUND});continue}let rt=it.parentId;if(U(rt)){d.push({activityId:C,reason:S.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let vt=String(rt),Ct=no(Y,r)+1,It=c.get(C);if(It!=null&&a.has(It)){let Qe=s.get(It)??-1,ti=s.get(C)??-1;Qe>=0&&ti>=0&&(Ct+=ti-Qe)}p.push({activityId:C,grandparentKey:vt,oldParentKey:Y,targetIndexInGrandparent:Ct}),y.add(C),l.add(String(C)),l.add(String(Y)),vt!=="0"&&l.add(String(vt)),f.add(Y)}let A=En(p.map(D=>({activityId:D.activityId,newParentId:D.grandparentKey})),r);for(let D of A)d.push({activityId:D,reason:S.HIERARCHY_CYCLE});let k=p.filter(D=>!A.has(D.activityId)),_=await Q(r,l);for(let D of k){r.setActivityField(D.activityId,b.PARENT,D.grandparentKey);let C=xl(r,D.grandparentKey,D.targetIndexInGrandparent,D.activityId);r.setActivityField(D.activityId,b.CORRELATIVE_ID,C),u.push(D.activityId)}for(let D of f){let C=r.getActivity(D);if(!C)continue;let L=r.getChildren(D),K=Le({parent:C,remainingChildIds:L.map(String),defaultDurationHours:o.hoursPerDay,promotionSnapshot:r.getPromotionSnapshot(D),computeEndDate:(Ct,It)=>r.calculateEndDate({startDate:Ct,durationHours:It,task:C}),idsRemoved:new Set(k.filter(Ct=>Ct.oldParentKey===D).map(Ct=>Ct.activityId))});if(!K){Vr(D,r);continue}for(let[Ct,It]of Object.entries(K.fields))lt(r,D,Ct,It);let Y=re(D,r),it=Y?r.getActivity(Y)?.customId:null,rt=typeof it=="string"&&it?it:null,vt=i.customIdTracker.generateCustomIdForRestoredChild(rt);r.setActivityField(D,b.CUSTOM_ID,vt)}let F=new Set;for(let D of f)F.add(String(D));for(let D of k)D.grandparentKey!=="0"&&F.add(String(D.grandparentKey));for(let D of F)Ft(D,r);let m=_t(r);for(let D of m){if(l.add(D.activityId),_.has(D.activityId))continue;let C=r.getActivity(D.activityId);if(!C)continue;let L=nt(C);D.before!==void 0&&(L.correlativeId=D.before),_.set(D.activityId,L)}let{scheduledIds:R}=await X({adapter:r,scheduler:n,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:u.length>0?Et.ROOTS:null,recomputeParentsFrom:u,now:i.now,options:t}),M={name:Kt.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(D=>({activity_id:String(D.activityId),reason:D.reason}))}};return e.eventSource!==void 0&&(M.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(D=>{let C=d.find(L=>String(L.activityId)===String(D));return C?{activityId:String(D),ok:!1,reason:C.reason}:{activityId:String(D),ok:!0}}),changes:await $(r,{source:e,beforeSnap:_,touchedIds:l,scheduledIds:R,trackingEvents:[M],hoursPerDay:o.hoursPerDay})}}async function od(e,t,i){let{adapter:r,scheduler:n,sector:o}=i,a=r.getActivity(e.activityId);if(!a)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};if(!Fi(e.type))return{ok:!1,reason:S.INVALID_VALUE};let s=r.getChildren(e.activityId),c=e.type===T.PROJECT;if(c!==s.length>0)return{ok:!1,reason:S.INVALID_VALUE};let l=new Set(r.getAllIds()),d=await Q(r,l);n.invalidateAllCaches(),c&&a.type!==T.PROJECT?XI(e.activityId,s[0],i):!c&&a.type===T.PROJECT&&ZI(e.activityId,i),e.type!==T.PROJECT?(QI(e.activityId,e.type,i),tg(e.activityId,i)):Ft(e.activityId,r);let u=eg(e.activityId,i),{scheduledIds:f}=await X({adapter:r,scheduler:n,sector:o,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId],recomputeParentProgress:!0,now:i.now,options:t});return{ok:!0,changes:await $(r,{source:e,beforeSnap:d,touchedIds:l,scheduledIds:f,sirDetection:Lt.BEFORE_DIFF,links:qe(u),hoursPerDay:o.hoursPerDay}),__beforeLinks:new Map(u)}}function XI(e,t,i){let n=i.adapter.getActivity(e)?.customId??null,o=Pe({parentId:e,newChildId:t,isCurrentlyLeaf:!0,getParent:a=>i.adapter.getActivity(a)??null});if(o){for(let[a,s]of Object.entries(o.fields))lt(i.adapter,e,a,s);o.promotionSnapshot&&i.adapter.setPromotionSnapshot(e,o.promotionSnapshot),o.fields.customId===null&&i.customIdTracker.releaseCustomId(n)}}function ZI(e,t){let i=t.adapter.getActivity(e);if(!i)return;let r=Le({parent:i,remainingChildIds:[],defaultDurationHours:t.sector.hoursPerDay,promotionSnapshot:t.adapter.getPromotionSnapshot(e),computeEndDate:(n,o)=>t.adapter.calculateEndDate({startDate:n,durationHours:o,task:i})});if(r)for(let[n,o]of Object.entries(r.fields))lt(t.adapter,e,n,o)}function QI(e,t,i){let r=i.adapter.getActivity(e);if(!r)return;i.adapter.setActivityField(e,b.TYPE,t);let n=t===T.MILESTONE?0:r.durationHours===0?i.sector.hoursPerDay:r.durationHours;n!==r.durationHours&&i.adapter.setActivityField(e,b.DURATION_HOURS,n);let o=i.adapter.getActivity(e);if(!o)return;let a=i.adapter.calculateEndDate({startDate:o.startDate,durationHours:n,task:o});i.adapter.setActivityField(e,b.END_DATE,a)}function tg(e,t){if(t.adapter.getActivity(e)?.customId)return;let r=re(e,t.adapter),n=r?t.adapter.getActivity(r)?.customId:null,o=t.customIdTracker.generateCustomIdForRestoredChild(n||null);t.adapter.setActivityField(e,b.CUSTOM_ID,o)}function eg(e,t){let i=new Map;for(let r of _i([e],t.adapter)){let n=t.adapter.getLink(r);n&&(i.set(String(r),{...n}),t.adapter.removeLink(r))}return i}async function ad(e,t,i){let{adapter:r,ctx:n,scheduler:o,sector:a}=i;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:S.INVALID_PROGRESS_VALUE};let s=n.activityReader.getActivity(e.activityId);if(!s)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let c=Ee(E.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===Jr.ACTION_BUTTON&&(l.reason===zi.HAS_LOOKAHEAD_TASKS||l.reason===zi.SUMMARY)))return{ok:!1,reason:l.reason,...l.alertKey?{alertKey:l.alertKey}:{}};let d=c.transform(s,e.newValue,n,e.newValue),u=_e(e.activityId,d),f=await Q(r,u);ke(r,e.activityId,d),Js(e.activityId,e.newValue,r),ve(e.activityId,d.postProcessors??[],r);let p=d.needsAutoSchedule?n.hierarchy.hasChildren(e.activityId)?Et.ROOTS:e.activityId:null,{scheduledIds:y}=await X({adapter:r,scheduler:o,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:p,recomputeParentsFrom:[],collectDirty:A=>en(e.activityId,u,A),now:i.now,options:t}),g=(d.trackingEvents??[]).map(A=>({name:A.name,properties:A.properties??{}}));return{ok:!0,changes:await $(r,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:y,trackingEvents:g,hoursPerDay:a.hoursPerDay})}}function ig(e){return e===E.START_DATE||e===E.END_DATE}async function sd(e,t,i){if(e.edits.some(y=>!ig(y.column)))return{ok:!1,reason:S.INVALID_VALUE};let{adapter:r,scheduler:n,sector:o}=i,a=[],s=new Map,c=new Set,l=[],d=[],u=[],f=!1;for(let y of e.edits){let g=rg(y,i);if(a.push(g.verdict),!g.verdict.ok||!g.changes)continue;let A=_e(y.activityId,g.changes);ng(s,A,i);for(let m of A)c.add(m);let k=Ci(r,y.activityId),_=Qr(r,String(y.activityId));ke(r,y.activityId,g.changes),ve(y.activityId,g.changes.postProcessors??[],r,_),d.push(...Si(k,r,y.activityId)),f||=!!g.changes.needsAutoSchedule;for(let m of g.changes.trackingEvents??[])l.push({name:m.name,properties:m.properties??{}});let F=Ve(y.activityId,g.changes.constraintWarning);F&&u.push(F)}let{scheduledIds:p}=await X({adapter:r,scheduler:n,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:f?Et.ROOTS:null,recomputeParentsFrom:c,now:i.now,options:t});return{ok:!0,verdicts:a,changes:await $(r,{source:e,beforeSnap:s,touchedIds:c,scheduledIds:p,sirDetection:Lt.BEFORE_DIFF,links:d,trackingEvents:l,warnings:u,hoursPerDay:o.hoursPerDay})}}function rg(e,t){let{ctx:i}=t,r=e.activityId,n=Ee(e.column);if(!n)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);let o=i.activityReader.getActivity(e.activityId);if(!o)throw new Error(`[ScheduleCore] activity "${e.activityId}" not found`);let a=n.canEdit(o,i.hierarchy);if(!a.allowed)return{verdict:{activityId:r,ok:!1,reason:a.reason??S.CANNOT_EDIT,...a.alertKey?{alertKey:a.alertKey}:{}},changes:null};let s=n.parseInput(e.newValue,o,i);if(!s.ok)return{verdict:{activityId:r,ok:!1,reason:s.reason??S.PARSE_ERROR},changes:null};let c=Reflect.get(o,n.targetField),l=n.validate(o,c,s.value,i);if(!l.valid)return{verdict:{activityId:r,ok:!1,reason:l.reason??S.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};let d=n.transform(o,s.value,i,s.raw);return{verdict:{activityId:r,ok:!0},changes:d}}function ng(e,t,i){let r=new Set;for(let n of t)e.has(n)||r.add(n);if(r.size!==0)for(let n of r){let o=i.adapter.getActivity(n);o&&e.set(n,nt(o))}}var fa=E.CUSTOM_ID;async function cd(e,t,i){let{adapter:r,scheduler:n,sector:o}=i;e.edits.some(D=>D.column===E.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 D of e.edits){let C=dg(D,i,e.eventSource);if(s.push(C.verdict),!C.verdict.ok||!C.changes)continue;let L=Ve(D.activityId,C.changes.constraintWarning);L&&y.push(L);let K=_e(D.activityId,C.changes);yg(c,K,i);for(let Ct of K)u.add(Ct);pg(l,D,c),fn(D.column)&&d.add(String(D.activityId)),sg(A,D);let Y=Ci(r,D.activityId),it=Qr(r,String(D.activityId)),rt=ug(D,i),vt=C.changes;ke(r,D.activityId,vt),ve(D.activityId,C.changes.postProcessors??[],r,it),og(g,y,D),ag(k,D,r.getActivity(D.activityId)),fg(D,rt,i),p.push(...Si(Y,r,D.activityId)),_||=!!C.changes.needsAutoSchedule;for(let Ct of C.changes.trackingEvents??[])f.push({name:Ct.name,properties:Ct.properties??{}})}let F={action:e,autoscheduleFrom:_?Et.ROOTS:null,recomputeParentsFrom:u,now:i.now,options:t},m=cg(A,k,c,y,g,i),R=l.size>0,{scheduledIds:M}=await(R?yn({adapter:r,scheduler:n,sector:o,defaultBaseCalendarId:i.defaultBaseCalendarId},{postMutationArgs:F,revertTargets:[...l].filter(([D])=>!d.has(D)).map(([D,C])=>({activityId:D,priorConstraintDate:C})),revert:(D,C)=>pn(D,C,r,i.ctx.calendars)}):X({adapter:r,scheduler:n,sector:o,defaultBaseCalendarId:i.defaultBaseCalendarId},F));return{ok:!0,verdicts:s,changes:await $(r,{source:e,beforeSnap:c,touchedIds:u,scheduledIds:M,sirDetection:Lt.BEFORE_DIFF,links:p,trackingEvents:f,warnings:m,hoursPerDay:o.hoursPerDay})}}function og(e,t,i){if(!Ai(i.column))return;let r=String(i.activityId);for(let n of t)String(n.activityId)===r&&e.add(n)}function ag(e,t,i){!Ai(t.column)||!i||e.set(String(t.activityId),{constraintType:i.constraintType,constraintDate:i.constraintDate?new Date(i.constraintDate.getTime()):null})}function sg(e,t){if(t.column!==E.START_DATE&&t.column!==E.END_DATE)return;let i=String(t.activityId),r=e.get(i)??new Set;r.add(t.column),e.set(i,r)}function cg(e,t,i,r,n,o){let a=new Set,s=[],c=new Set;for(let[l,d]of e){if(!d.has(E.START_DATE)||!d.has(E.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=i.get(l),p=o.adapter.getActivity(l);if(!f?.constraintType||!f.constraintDate||!p)continue;let y=Oe(f.constraintType,p.startDate,p.endDate),g=lg(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=Ve(l,pr(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[...r.filter(l=>!c.has(l)&&!a.has(String(l.activityId))),...s]}function lg(e,t,i){return e===v.MSO||e===v.MFO?t.getTime()!==i.getTime():fr(e,t,i).violated}function dg(e,t,i){let{ctx:r}=t,n=e.activityId,o=Ee(e.column);if(!o)return{verdict:{activityId:n,ok:!1,reason:S.NO_PIPELINE_FOR_COLUMN},changes:null};let a=r.activityReader.getActivity(e.activityId);if(!a)return{verdict:{activityId:n,ok:!1,reason:S.ACTIVITY_NOT_FOUND},changes:null};let s=o.canEdit(a,r.hierarchy,{eventSource:i,newValue:e.newValue});if(!s.allowed)return{verdict:{activityId:n,ok:!1,reason:s.reason??S.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let c=o.parseInput(e.newValue,a,r);if(!c.ok)return{verdict:{activityId:n,ok:!1,reason:c.reason??S.PARSE_ERROR},changes:null};let l=Reflect.get(a,o.targetField),d=o.validate(a,l,c.value,r);if(!d.valid)return{verdict:{activityId:n,ok:!1,reason:d.reason??S.INVALID,...d.notification?.messageKey?{alertKey:d.notification.messageKey}:{}},changes:null};if(e.column===fa&&c.value!==null){let f=t.adapter.getActivity(e.activityId),p=f?f.customId:null,y=typeof p=="string"?p:null;if(t.customIdTracker.isCustomIdInUse(String(c.value),y))return{verdict:{activityId:n,ok:!1,reason:S.CUSTOM_ID_DUPLICATE},changes:null}}let u=o.transform(a,c.value,r,c.raw);return{verdict:{activityId:n,ok:!0},changes:u}}function ug(e,t){if(e.column!==fa)return null;let i=t.adapter.getActivity(e.activityId),r=i?i.customId:null;return typeof r=="string"?r:null}function fg(e,t,i){if(e.column!==fa)return;let r=i.adapter.getActivity(e.activityId),n=r?r.customId:null,o=typeof n=="string"?n:null;t!==o&&i.customIdTracker.trackCustomIdChange(t,o)}function pg(e,t,i){if(!Ai(t.column))return;let r=String(t.activityId);if(e.has(r))return;let n=i.get(r);n&&e.set(r,n.constraintDate??null)}function yg(e,t,i){let r=new Set;for(let n of t)e.has(n)||r.add(n);if(r.size!==0)for(let n of r){let o=i.adapter.getActivity(n);o&&e.set(n,nt(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"},hg=[Nt.INVALID_BASELINE_POINT,Nt.UNKNOWN_CONSTRAINT,Nt.ORPHAN_ACTIVITY,Nt.INVALID_LINK,Nt.DUPLICATE_LINK],ki=()=>{};function ld(){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(hg.flatMap(n=>{let o=e.get(n);return o===void 0?[]:[Object.freeze({code:n,count:o,sampleIds:Object.freeze([...t.get(n)??[]])})]}))}}function dd(e){return typeof e=="string"&&e.length>0?le(e):e instanceof Date?e:null}function pa(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 kn(e,t,i,r=!1){let n=pa(e.duration),o=pa(e.cost),a=pa(e.hh_work);if(n===null||o===null||a===null)return i&&i.record(Nt.INVALID_BASELINE_POINT,i.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=dd(e.start_date),c=dd(e.end_date),l=r&&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,i,r=ki){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"){r(Nt.INVALID_BASELINE_POINT,String(c??"unknown"));continue}let l=n.get(c);if(l===void 0){r(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=>kn(d,i,{record:r,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 mg(e){let t=gt(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function fd(e){let t=[];return e.forEachActivity((i,r)=>{let n=mg(i);if(!n){i.baselineSnapshot!==null&&(e.setActivityField(r,"baselineSnapshot",null),t.push(r));return}e.setActivityField(r,"baselineSnapshot",n),t.push(r)}),t}function Rn(e,t,i,r,n=null,o=ki){let a=new Set;for(let s of ud(e,t,r,o))a.add(s);if(i)for(let s of Ii(e,i,n))a.add(s);for(let s of fd(e))a.add(s);for(let s of gi(e))a.add(s);return[...a]}function pd(e,t){t.forEachActivity((i,r)=>{t.setActivityField(r,E.PONDERATOR,0)}),t.forEachActivity((i,r)=>{t.getChildren(r).length>0&&un(String(r),e,t)})}function Pn(e,t){pd(t,e.adapter),Ki(e.adapter),e.now&&(Ii(e.adapter,e.now,e.defaultBaseCalendarId??null),je(e.adapter,e.now)),gi(e.adapter),e.now&&de(e.adapter,e.sector.statusCriteria)}function yd(e){return JSON.stringify(e.adapter.getAllIds().map(t=>{let i=e.adapter.getActivity(t)?.baselinePoints.find(r=>r.isActiveVersion);return i?[String(t),i.versionId,i.startDate?.getTime()??null,i.endDate?.getTime()??null,i.durationDays,i.cost,i.workHours,i.baseCalendarId,i.hoursPerDay,i.hoursPerWeek]:[String(t),null]}))}async function hd(e,t){let i=await Q(t.adapter,new Set(t.adapter.getAllIds())),r=yd(t),n=Rn(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return yd(t)!==r&&Pn(t,t.sector.activityCreter??pt.DURATION),{ok:!0,changes:await $(t.adapter,{source:e,beforeSnap:i,touchedIds:n,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function Ig(e){return Object.values(pt).includes(e)}async function md(e,t){if(!Ig(e.criterion))return{ok:!1,reason:S.INVALID_VALUE};let i=new Set(t.adapter.getAllIds()),r=await Q(t.adapter,i);return Pn(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:await $(t.adapter,{source:e,beforeSnap:r,touchedIds:i,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function Id(e,t){let i=rn(e.criteria),r=new Set(t.adapter.getAllIds()),n=await Q(t.adapter,r),o=de(t.adapter,i);return t.sector.statusCriteria=i,{ok:!0,changes:await $(t.adapter,{source:e,beforeSnap:n,touchedIds:o,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function Ad(e,t,i){let r=new Map,n=new Set;for(let a of i.adapter.getAllActivities()){if(!gg(a,i))continue;let s=i.ctx.calendars.getCalendar(a.calendarId);if(!s)continue;let c=s.getClosestWorkTime({date:a.startDate,direction:j.FUTURE,unit:ut.HOUR}),l=s.calculateEndDate(c,a.durationHours);if(gd(c,a.startDate)&&gd(l,a.endDate))continue;let d=String(a.id);r.set(d,nt(a)),n.add(d),i.adapter.setActivityFields(d,{startDate:c,endDate:l})}let{scheduledIds:o}=await X({adapter:i.adapter,scheduler:i.scheduler,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:Et.ROOTS,recomputeParentsFrom:n,now:i.now,options:t});return{ok:!0,changes:await $(i.adapter,{source:e,beforeSnap:r,touchedIds:n,scheduledIds:o,hoursPerDay:i.sector.hoursPerDay})}}function gg(e,t){return e.progress===0&&!zt(e.type,t.adapter.hasChildren(e.id))}function gd(e,t){return e.getTime()===t.getTime()}var vd=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","cost","hasCustomPonderator","subcontractId","responsableIds","tagIds"];function Ag(e){let t={};for(let i of vd)Object.assign(t,{[i]:w(e[i])});return t}function vg(e,t){let i=[],r=n=>{t.has(String(n))&&i.push(n);for(let o of e.getChildren(n))r(o)};for(let n of e.getRootIds())r(n);return i}function Cd(e,t){let i=new Set(t.adapter.checkedIds().map(String));if(i.size===0)return{ok:!1,reason:S.NO_ACTIVITY_SELECTION};let r=vg(t.adapter,i);t.clipboard.value={activities:r.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:Ag(a)}}),links:t.adapter.getAllLinks().filter(o=>i.has(String(o.source))&&i.has(String(o.target))).map(o=>w(o))};let n=mr({kind:I.SELECTION_REPLACE,activityIds:[]},{adapter:t.adapter});return n.ok?{...n,changes:{...n.changes,source:e}}:n}function Sd(e,t){return t.value=null,{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}}function Cg(e,t){let i=t.getActivity(e);return i?i.parentId==null?t.getRootIds().length===1?{ok:!0,parentId:i.id}:{ok:!0,parentId:"0",afterSiblingId:e}:{ok:!0,parentId:String(i.parentId),afterSiblingId:e}:{ok:!1,reason:S.ANCHOR_SIBLING_NOT_FOUND}}var Td=()=>({ok:!1,reason:S.ACTIVITY_PASTE_INVARIANT_FAILED});async function Dd(e,t,i){let r=i.activityClipboard.value;if(r===null)return{ok:!1,reason:S.CLIPBOARD_EMPTY};let n=Cg(e.destination.afterSiblingId,i.adapter);if(!n.ok)return n;let o=await Q(i.adapter,new Set),a=new Set,s=new Map,c=[],l;for(let g of r.activities){let A=s.get(g.originalParentId),k=A===void 0?l??n.afterSiblingId:void 0,_=await rr({kind:I.ACTIVITY_CREATE,parentId:A??n.parentId,...k===void 0?{}:{afterSiblingId:k},overrides:w(g.overrides),eventSource:e.eventSource},i,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:e.destination.afterSiblingId});if(!_.ok)return _;s.set(g.originalId,_.newId),c.push(_.newId),A===void 0&&(l=_.newId)}let d=_t(i.adapter),u=new Set(c.map(String));hi(i.adapter,d,u,o,a);for(let g of c)a.add(String(g));let f=[];for(let g of r.links){let A=s.get(g.source),k=s.get(g.target);if(A===void 0||k===void 0)return Td();let _={kind:St.CREATE,source:A,target:k,type:g.type,lag:g.lag},F=Ie(_,{port:i.adapter,newLinkId:i.linkIdGen.next});if(!F.applied)return Td();f.push({op:_,finalLinkId:F.linkId,rejected:null})}let{scheduledIds:p}=await X({adapter:i.adapter,scheduler:i.scheduler,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:c[0]??null,recomputeParentsFrom:c,now:i.now,options:t}),y=vi(f,new Map,i.adapter);return{ok:!0,changes:await $(i.adapter,{source:e,beforeSnap:o,touchedIds:a,scheduledIds:p,links:y,hoursPerDay:i.sector.hoursPerDay})}}async function Ed(e,t,i){return e.kind===I.ACTIVITY_COPY?Cd(e,{adapter:i.adapter,clipboard:i.activityClipboard}):e.kind===I.CALENDAR_RECONCILE?Ad(e,t,i):e.kind===I.ACTIVITY_CLIPBOARD_CLEAR?Sd(e,i.activityClipboard):e.kind===I.ACTIVITY_PASTE_COPIED?Dd(e,t,i):e.kind===pe?Vl(e,t,i):e.kind===I.PERSISTENCE_ACKNOWLEDGE?ql(e,i):e.kind===I.BASELINE_APPLY?hd(e,i):e.kind===I.PONDERATOR_CRITERION_SET?md(e,i):e.kind===I.STATUS_CRITERIA_SET?Id(e,i):e.kind===I.LINK_CREATE||e.kind===I.LINK_UPDATE||e.kind===I.LINK_DELETE?vl(e,t,i):e.kind===I.LINKS_BATCH?Cl(e,t,i):e.kind===I.ACTIVITY_CREATE?Ml(e,t,i):e.kind===I.ACTIVITY_DELETE?Hl(e,t,i):e.kind===I.ACTIVITY_MOVE?id(e,t,i):e.kind===I.ACTIVITY_INDENT?rd(e,t,i):e.kind===I.ACTIVITY_OUTDENT?nd(e,t,i):e.kind===I.ACTIVITY_TYPE_SET?od(e,t,i):e.kind===I.ACTIVITY_SET_PROGRESS?ad(e,t,i):e.kind===I.DATES_BATCH?sd(e,t,i):e.kind===I.BULK_EDIT?cd(e,t,i):e.kind===I.SELECTION_TOGGLE?os(e,ya(i)):e.kind===I.SELECTION_REPLACE?mr(e,ya(i)):e.kind===I.VISIBILITY_SET?as(e,ya(i)):e.kind===I.FILTER_SET?hs(e,{adapter:i.adapter,hoursPerDay:i.sector.hoursPerDay}):e.kind===I.SORT_SET?vs(e,{adapter:i.adapter}):e.kind===I.SIR_SYNC?Kl(e,i):e.kind===I.ACTIVITY_LOOKAHEAD_SYNC?Jl(e,t,i):e.kind===I.ACTIVITY_LOOKAHEAD_CONVERT?Ql(e,t,i):e.kind===I.SCHEDULE_AUTO_SCHEDULE?Il(e,t,i):e.kind===I.INLINE_EDIT&&(e.column===E.CUSTOM_PREDECESSORS||e.column===E.CUSTOM_SUCESSORS)?Sl(e,t,i):e.kind!==I.INLINE_EDIT?Cs(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):Al(e,t,i)}function ya(e){return{adapter:e.adapter}}var Sg=new Set(["startDate","endDate","constraintDate"]);function _d(e,t){return Sg.has(e)&&typeof t=="string"?new Date(t):t}function kd(e,t={}){let i=t.defaultUnit??ut.HOUR;return{getCalendar(r){let n=e.getCalendar(String(r));return n?Tg(n,i):null}}}function Tg(e,t){return{getClosestWorkTime(i){return e.getClosestWorkTime({date:i.date,dir:i.direction,unit:i.unit})},calculateEndDate(i,r){return e.calculateEndDate({start_date:i,duration:r,unit:t})},calculateDuration(i,r){return e.calculateDuration({start_date:i,end_date:r,unit:t})},isWorkTime(i,r){return e.isWorkTime({date:i,unit:r})},getWorkHours(i){return e.getWorkHours(i)}}}function Dg(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function Je(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function Xe(e){return Je(e)&&!isNaN(e.getTime())}var Eg={}.constructor.toString();function _g(e){var t=e.constructor.toString();return t!==Eg}function kg(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function Xt(e){var t,i;if(e&&typeof e=="object")switch(!0){case Je(e):i=new Date(e);break;case Dg(e):for(i=new Array(e.length),t=0;t<e.length;t++)i[t]=Xt(e[t]);break;default:if(_g(e))i=Object.create(e);else{if(kg(e))return i=e,i;i={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(i[t]=Xt(e[t]));break}return i||e}function Ri(e,t,i){for(var r in t)(e[r]===void 0||i)&&(e[r]=t[r]);return e}function Rd(e){return typeof e<"u"}var Ln;function ha(){return Ln||(Ln=new Date().valueOf()),Ln++,Ln}function Bt(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var Pg=(e,t,i)=>{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 r=new Function("date","to_fixed","locale","getISOWeek","getWeek",`return "${e}";`);return n=>r(n,i.date.to_fixed,i.locale,i.date.getISOWeek,i.date.getWeek)},Lg=(e,t,i)=>{let r="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":r+=`set[2]=temp[${s}]||1;`;break;case"%n":case"%m":r+=`set[1]=(temp[${s}]||1)-1;`;break;case"%y":r+=`set[0]=temp[${s}]*1+(temp[${s}]>50?1900:2000);`;break;case"%g":case"%G":case"%h":case"%H":r+=`set[3]=temp[${s}]||0;`;break;case"%i":r+=`set[4]=temp[${s}]||0;`;break;case"%Y":r+=`set[0]=temp[${s}]||0;`;break;case"%a":case"%A":r+=`set[3]=set[3]%12+((temp[${s}]||'').toLowerCase()=='am'?0:12);`;break;case"%s":r+=`set[5]=temp[${s}]||0;`;break;case"%M":r+=`set[1]=locale.date.month_short_hash[temp[${s}]]||0;`;break;case"%F":r+=`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]; ${r} return new Date(${o});`);return s=>a(s,i.locale)},Pd={date_to_str:Pg,str_to_date:Lg},Og=(e,t,i)=>r=>e.replace(/%[a-zA-Z]/g,n=>{switch(n){case"%d":return t?i.date.to_fixed(r.getUTCDate()):i.date.to_fixed(r.getDate());case"%m":return t?i.date.to_fixed(r.getUTCMonth()+1):i.date.to_fixed(r.getMonth()+1);case"%j":return t?r.getUTCDate():r.getDate();case"%n":return t?r.getUTCMonth()+1:r.getMonth()+1;case"%y":return t?i.date.to_fixed(r.getUTCFullYear()%100):i.date.to_fixed(r.getFullYear()%100);case"%Y":return t?r.getUTCFullYear():r.getFullYear();case"%D":return t?i.locale.date.day_short[r.getUTCDay()]:i.locale.date.day_short[r.getDay()];case"%l":return t?i.locale.date.day_full[r.getUTCDay()]:i.locale.date.day_full[r.getDay()];case"%M":return t?i.locale.date.month_short[r.getUTCMonth()]:i.locale.date.month_short[r.getMonth()];case"%F":return t?i.locale.date.month_full[r.getUTCMonth()]:i.locale.date.month_full[r.getMonth()];case"%h":return t?i.date.to_fixed((r.getUTCHours()+11)%12+1):i.date.to_fixed((r.getHours()+11)%12+1);case"%g":return t?(r.getUTCHours()+11)%12+1:(r.getHours()+11)%12+1;case"%G":return t?r.getUTCHours():r.getHours();case"%H":return t?i.date.to_fixed(r.getUTCHours()):i.date.to_fixed(r.getHours());case"%i":return t?i.date.to_fixed(r.getUTCMinutes()):i.date.to_fixed(r.getMinutes());case"%a":return t?r.getUTCHours()>11?"pm":"am":r.getHours()>11?"pm":"am";case"%A":return t?r.getUTCHours()>11?"PM":"AM":r.getHours()>11?"PM":"AM";case"%s":return t?i.date.to_fixed(r.getUTCSeconds()):i.date.to_fixed(r.getSeconds());case"%W":return t?i.date.to_fixed(i.date.getUTCISOWeek(r)):i.date.to_fixed(i.date.getISOWeek(r));case"%w":return i.date.to_fixed(i.date.getWeek(r));default:return n}}),Ng=(e,t,i)=>r=>{let n=[0,0,1,0,0,0],o=r.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]=i.locale.date.month_short_hash[o[s]]||0;break;case"%F":n[1]=i.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])},Ld={date_to_str:Og,str_to_date:Ng};function Od(e){var t=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function i(s){var c=new Date(s);return isNaN(c.getTime())?null:c}var r=null;function n(){try{new Function("canUseCsp = false;")}catch{r=!0}}function o(){var s=!1;return e.config.csp==="auto"?(r===null&&n(),s=r):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=Pd;return o()&&(l=Ld),l.date_to_str(s,c,e)},str_to_date:function(s,c){var l=Pd;return o()&&(l=Ld),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=i(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 ma(e,t,i,r,n){return this.date=e,this.unit=t,this.task=i,this.id=r,this.calendar=n,this}function Ia(e,t,i,r,n,o){return this.date=e,this.dir=t,this.unit=i,this.task=r,this.id=n,this.calendar=o,this}function ga(e,t,i,r,n,o,a){return this.start_date=e,this.duration=t,this.unit=i,this.step=r,this.task=n,this.id=o,this.calendar=a,this}function bg(e,t,i,r){return this.start_date=e,this.end_date=t,this.task=i,this.calendar=r,this.unit=null,this.step=null,this}var Nd=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(Je(t)?t={date:t}:t=Ri({},t),!Xe(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 ma)return t;var i;if(t.date?i=new ma(t.date,t.unit,t.task,null,t.calendar):i=new ma(arguments[0],arguments[1],arguments[2],null,arguments[3]),i.unit=i.unit||e.config.duration_unit,!Xe(i.date))throw e.assert(!1,"Invalid date argument for isWorkTime method"),new Error("Invalid date argument for isWorkTime method");return i},getClosestWorkTimeArguments:function(t){var i=arguments[0];if(i instanceof Ia)return i;var r;if(Je(i)?r=new Ia(i):r=new Ia(i.date,i.dir,i.unit,i.task,null,i.calendar),i.id&&(r.task=i),r.dir=i.dir||"any",r.unit=i.unit||e.config.duration_unit,!Xe(r.date))throw e.assert(!1,"Invalid date argument for getClosestWorkTime method"),new Error("Invalid date argument for getClosestWorkTime method");return r},_getStartEndConfig:function(t){var i=bg,r;if(t instanceof i)return t;if(Je(t)?r=new i(arguments[0],arguments[1],arguments[2],arguments[3]):(r=new i(t.start_date,t.end_date,t.task),t.id!==null&&t.id!==void 0&&(r.task=t)),r.unit=r.unit||e.config.duration_unit,r.step=r.step||e.config.duration_step,r.start_date=r.start_date||r.start||r.date,!Xe(r.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!Xe(r.end_date))throw e.assert(!1,"Invalid end_date argument for getDuration method"),new Error("Invalid end_date argument for getDuration method");return r},getDurationArguments:function(t,i,r,n){return this._getStartEndConfig.apply(this,arguments)},hasDurationArguments:function(t,i,r,n){return this._getStartEndConfig.apply(this,arguments)},calculateEndDateArguments:function(t,i,r,n){var o=arguments[0];if(o instanceof ga)return o;var a;if(Je(o)?a=new ga(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):a=new ga(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,!Xe(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 bd(){}bd.prototype={_getIntervals:function(e){for(var t=[],i=0;i<e.length;i+=2)t.push({start:e[i],end:e[i+1]});return t},_toHoursArray:function(e){var t=[];function i(o){var a=String(o);return a.length<2&&(a="0"+a),a}function r(o){var a=Math.floor(o/3600),s=o-a*60*60,c=Math.floor(s/60);return a+":"+i(c)}for(var n=0;n<e.length;n++)t.push(r(e[n].start)+"-"+r(e[n].end));return t},_intersectHourRanges:function(e,t){var n=[],i=e.length>t.length?e:t,r=e===i?t:e;i=i.slice(),r=r.slice();for(var n=[],o=0;o<i.length;o++)for(var a=i[o],s=0;s<r.length;s++){var c=r[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&&(r.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 i=t[0],r=1;r<t.length;r++){var n=t[r];n.start<=i.end?(n.end>i.end&&(i.end=n.end),t.splice(r,1),r--):i=n}return t},_mergeHoursConfig:function(e,t){return this._mergeAdjacentIntervals(this._intersectHourRanges(e,t))},merge:function(e,t){let i=Xt(e.getConfig()),r=Xt(t.getConfig()),n=i.parsed,o=r.parsed;n.customWeeks=i.customWeeks,o.customWeeks=r.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 Aa=class{constructor(){this.clear()}getItem(t,i,r){if(this._cache.has(t)){let o=this._cache.get(t)[r.getUTCFullYear()];if(o&&o.has(i))return o.get(i)}return-1}setItem(t,i,r,n){if(!t||!i)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(i,r)}clear(){this._cache=new Map}},va=class{constructor(){this.clear()}getItem(t,i,r){let n=this._cache;if(n&&n[t]){let o=n[t];if(o===void 0)return-1;let a=o[r.getUTCFullYear()];if(a&&a[i]!==void 0)return a[i]}return-1}setItem(t,i,r,n){if(!t||!i)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[i]=r}clear(){this._cache={}}},Ca=class{constructor(t){this.getMinutesPerWeek=i=>{let r=i.valueOf();if(this._weekCache.has(r))return this._weekCache.get(r);let n=this._calendar,o=this._calendar.$gantt,a=0,s=o.date.week_start(new Date(i));for(let c=0;c<7;c++)a+=n.getHoursPerDay(s)*60,s=o.date.add(s,1,"day");return this._weekCache.set(r,a),a},this.getMinutesPerMonth=i=>{let r=i.valueOf();if(this._monthCache.has(r))return this._monthCache.get(r);let n=this._calendar,o=this._calendar.$gantt,a=0,s=o.date.week_start(new Date(i)),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(r,a),a},this.clear=()=>{this._weekCache=new Map,this._monthCache=new Map},this.clear(),this._calendar=t}};function Fg(){return typeof Map<"u"?new Aa:new va}var Sa=class{constructor(){this.clear()}_getCacheObject(t,i,r){let n=this._cache;n[i]||(n[i]=[]);let o=n[i];o||(o=n[i]={});let a=o[r];a||(a=o[r]={});let s=t.getUTCFullYear(),c=a[s];return c||(c=a[s]={durations:{},endDates:{}}),c}_endDateCacheKey(t,i){return String(t)+"-"+String(i)}_durationCacheKey(t,i){return String(t)+"-"+String(i)}getEndDate(t,i,r,n,o){let a=this._getCacheObject(t,r,n),s=t.valueOf(),c=this._endDateCacheKey(s,i),l;if(a.endDates[c]===void 0){let d=o(),u=d.valueOf();a.endDates[c]=u,a.durations[this._durationCacheKey(s,u)]=i,l=d}else l=new Date(a.endDates[c]);return l}getDuration(t,i,r,n,o){let a=this._getCacheObject(t,r,n),s=t.valueOf(),c=i.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 Ta(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=Fg(),this._largeUnitsCache=new Ca(this),this._dateDurationCache=new Sa,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}Ta.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,i=this.units.length;t<i;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 i=String(e.date.valueOf());this._cached_timestamps[i]?t=this._cached_timestamps[i]:(t=Date.UTC(e.date.getUTCFullYear(),e.date.getUTCMonth(),e.date.getUTCDate()),this._cached_timestamps[i]=t,this._cached_timestamps_count++)}return t},_checkIfWorkingUnit:function(e,t){if(!this["_is_work_"+t]){let i=this.$gantt.date[`${t}_start`](new Date(e)),r=this.$gantt.date.add(i,1,t);return this.hasDuration(i,r)}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),i=e.getUTCHours(),r=0;r<t.length;r++)if(i>=t[r].startHour&&i<t[r].endHour)return!0;return!1},_getTimeOfDayStamp:function(e,t){var i=e.getUTCHours();return!e.getUTCHours()&&!e.getUTCMinutes()&&t&&(i=24),i*60*60+e.getUTCMinutes()*60},_is_work_minute:function(e){for(var t=this._getWorkHours(e),i=this._getTimeOfDayStamp(e),r=0;r<t.length;r++)if(i>=t[r].start&&i<t[r].end)return!0;return!1},_nextDate:function(e,t,i){return this.$gantt.date.add(e,i,t)},_getWorkUnitsBetweenGeneric:function(e,t,i,r){var n=this.$gantt.date,o=new Date(e),a=new Date(t);r=r||1;var s=0,c=null,l,d,u=!1;l=n[i+"_start"](new Date(o)),l.valueOf()!=o.valueOf()&&(u=!0);var f=!1;d=n[i+"_start"](new Date(t)),d.valueOf()!=t.valueOf()&&(f=!0);for(var p=!1;o.valueOf()<a.valueOf();){if(c=this._nextDate(o,i,r),p=c.valueOf()>a.valueOf(),this._isWorkTime(o,i))(u||f&&p)&&(l=n[i+"_start"](new Date(o)),d=n.add(l,r,i)),u?(u=!1,c=this._nextDate(l,i,r),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(i),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),i=this._getTimeOfDayStamp(this._nextDate(e,"hour",1));i===0&&(i=1440*60);for(var r=this._getWorkHours(e),n=0;n<r.length;n++){var o=r[n];if(t>=o.start&&i<=o.end)return 60;if(t<o.end&&i>o.start){var a=Math.min(i,o.end)-Math.max(t,o.start);return a/60}}return 0},_getMinutesPerDay:function(e){var t=this._getWorkHours(e),i=0;return t.forEach(function(r){i+=r.durationMinutes}),i},getHoursPerDay:function(e){var t=this._getWorkHours(e),i=0;return t.forEach(function(r){i+=r.durationHours}),i},_getWorkUnitsForRange:function(e,t,i,r){var n=0,o=new Date(e),a=new Date(t),s;for(i=="minute"?s=Bt(this._getMinutesPerDay,this):s=Bt(this.getHoursPerDay,this);o.valueOf()<a.valueOf();){if(a-o>1e3*60*60*24*32&&o.getUTCDate()===0){var c=this._largeUnitsCache.getMinutesPerMonth(o);i=="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);i=="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/r},_getMinutesBetweenSingleDay:function(e,t){for(var i=this._getIntervalTimestamp(e,t),r=this._getWorkHours(e),n=0,o=0;o<r.length;o++){var a=r[o];if(i.end>=a.start&&i.start<=a.end){var s=Math.max(a.start,i.start),c=Math.min(a.end,i.end);n+=(c-s)/60,i.start=c}}return Math.floor(n)},_getMinutesBetween:function(e,t,i,r){var n=new Date(e),o=new Date(t);r=r||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,i,r),p=d+f+u;return p},_getHoursBetween:function(e,t,i,r){var n=new Date(e),o=new Date(t);r=r||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,i,r)/60,u=this._getMinutesBetweenSingleDay(c,l,i,r)/60,f=this._getWorkUnitsForRange(s,c,i,r),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 i=null,r=null;for(var t in e.customWeeks){var n=e.customWeeks[t];if(n.from&&n.to){var o=n.from,a=n.to;(!i||i>o.valueOf())&&(i=o.valueOf()),(!r||r<a.valueOf())&&(r=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=i,e.parsed.customWeeksRangeEnd=r}},_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 i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0},_compareSettings:function(e,t){if(!this._arraysEqual(e.hours,t.hours))return!1;var i=Object.keys(e.dates),r=Object.keys(t.dates);if(i.sort(),r.sort(),!this._arraysEqual(i,r))return!1;for(var n=0;n<i.length;n++){var o=i[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 Ta))return!1;var t=this.getConfig(),i=e.getConfig();if(!this._compareSettings(t,i))return!1;if(t.parsed.haveCustomWeeks&&i.parsed.haveCustomWeeks){if(t.parsed.customWeeksBoundaries.length!=i.parsed.customWeeksBoundaries.length)return!1;for(var r in t.parsed.customWeeks){var n=t.parsed.customWeeks[r],o=i.parsed.customWeeks[r];if(!o||!this._compareSettings(n,o))return!1}}else if(t.parse.haveCustomWeeks!==i.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 i=this.getConfig();if(t!==!1&&(i=i.parsed),!e)return i.hours;let r=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));var n=this._timestamp({date:r});if(i.haveCustomWeeks&&i.customWeeksRangeStart<=n&&i.customWeeksRangeEnd>n){for(var o=0;o<i.customWeeksBoundaries.length;o++)if(i.customWeeksBoundaries[o].from<=n&&i.customWeeksBoundaries[o].to>n){i=i.customWeeks[i.customWeeksBoundaries[o].name];break}}var a=!0;return i.dates[n]!==void 0?a=i.dates[n]:i.dates[e.getUTCDay()]!==void 0&&(a=i.dates[e.getUTCDay()]),a===!0?i.hours:a||[]},_getIntervalTimestamp:function(e,t){var i={start:0,end:0};i.start=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds();var r=t.getUTCHours();return!r&&!t.getUTCMinutes()&&!t.getUTCSeconds()&&e.valueOf()<t.valueOf()&&(r=24),i.end=r*60*60+t.getUTCMinutes()*60+t.getUTCSeconds(),i},_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 i=[],r=0;r<t.length;r+=2){var n=t[r],o=t[r+1],a=o-n;i.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 i}else return e},setWorkTime:function(e){return this._tryChangeCalendarSettings(Bt(function(){var t=e.hours!==void 0?e.hours:!0,i=this._timestamp(e),r=this.getConfig();if(i!==null?r.dates[i]=t:e.customWeeks||(r.hours=t),e.customWeeks){if(r.customWeeks||(r.customWeeks={}),typeof e.customWeeks=="string")i!==null?r.customWeeks[e.customWeeks].dates[i]=t:e.customWeeks||(r.customWeeks[e.customWeeks].hours=t);else if(typeof e.customWeeks=="object"&&e.customWeeks.constructor===Object)for(var n in e.customWeeks)r.customWeeks[n]=e.customWeeks[n]}this._parseSettings(),this._clearCaches()},this))},unsetWorkTime:function(e){return this._tryChangeCalendarSettings(Bt(function(){if(!e)this.reset_calendar();else{var t=this._timestamp(e);t!==null&&delete this.getConfig().dates[t]}this._parseSettings(),this._clearCaches()},this))},_isWorkTime:function(e,t){var i=-1,r=null;return r=String(e.valueOf()),i=this._workingUnitsCache.getItem(t,r,e),i==-1&&(i=this._checkIfWorkingUnit(e,t),this._workingUnitsCache.setItem(t,r,i,e)),i},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,i,r){var n=0,o=1;if(e.valueOf()>t.valueOf()){var a=t;t=e,e=a,o=-1}return i=="hour"&&r==1?n=this._getHoursBetween(e,t,i,r):i=="minute"&&r==1?n=this._getMinutesBetween(e,t,i,r):n=this._getWorkUnitsBetweenGeneric(e,t,i,r),o*Math.round(n)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,i=e.end_date,r=e.unit,n=e.step;if(!r)return!1;var o=new Date(t),a=new Date(i);for(n=n||1;o.valueOf()<a.valueOf();){if(this._isWorkTime(o,r))return!0;o=this._nextDate(o,r,n)}return!1},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,i=e.duration,r=e.unit,n=e.step;if(!r)return!1;var o=e.duration>=0?1:-1;i=Math.abs(i*1);var a=this;return this._dateDurationCache.getEndDate(t,i,r,n*o,function(){return a._calculateEndDate(t,i,r,n*o)})},_calculateEndDate:function(e,t,i,r){if(!i)return!1;if(r==1&&i=="minute")return this._calculateMinuteEndDate(e,t,r);if(r==-1&&i=="minute")return this._subtractMinuteDate(e,t,r);if(r==1&&i=="hour")return this._calculateHourEndDate(e,t,r);var n=this._addInterval(e,t,i,r,null);return n.end},_addInterval:function(e,t,i,r,n){for(var o=0,a=e;o<t&&!(n&&n(a));){var s=this._nextDate(a,i,r),c=new Date(s.valueOf()+1);r>0&&(c=new Date(s.valueOf()-1));var l=this._isWorkTime(c,i);l&&o++,a=s}return{end:a,start:e,added:o}},_addHoursUntilDayEnd:function(e,t){for(var i=this.$gantt.date.add(this.$gantt.date.day_start(new Date(e)),1,"day"),r=0,n=t,o=this._getIntervalTimestamp(e,i),a=this._getWorkHours(e),s=0;s<a.length&&r<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);r+=f,n-=f,o.start=d}}var p=i;return r===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,o.start))),{added:r,end:p}},_calculateHourEndDate:function(e,t,i){var r=new Date(e),n=0;i=i||1,t=Math.abs(t*1);var o=this._addHoursUntilDayEnd(r,t);n=o.added,r=o.end;var a=t-n;if(a){for(var s=r;n<t;){var c=this._nextDate(s,"day",i);c.setUTCHours(0),c.setUTCMinutes(0),c.setUTCSeconds(0);var l=0;if(i>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}r=s}if(n<t){var a=t-n;o=this._addHoursUntilDayEnd(r,a),r=o.end}return r},_addMinutesUntilHourEnd:function(e,t){if(e.getUTCMinutes()===0)return{added:0,end:new Date(e)};for(var i=this.$gantt.date.add(this.$gantt.date.hour_start(new Date(e)),1,"hour"),r=0,n=t,o=this._getIntervalTimestamp(e,i),a=this._getWorkHours(e),s=0;s<a.length&&r<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,r+=f,o.start=d}}var p=i;return r===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,o.start))),{added:r,end:p}},_subtractMinutesUntilHourStart:function(e,t){for(var i=this.$gantt.date.hour_start(new Date(e)),r=0,n=t,o=i.getUTCHours()*60*60+i.getUTCMinutes()*60+i.getUTCSeconds(),a=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds(),s=this._getWorkHours(e),c=s.length-1;c>=0&&r<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,r+=p,a=u}}var y=i;return r===t&&(y=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a))),{added:r,end:y}},_subtractMinuteDate:function(e,t,i){var r=this.getClosestWorkTime({date:e,dir:"past",unit:"minute"}),n=0;i=i||-1,t=Math.abs(t*1),t=Math.round(t);let o=this._isMinutePrecision(r),a=this._subtractMinutesUntilHourStart(r,t);n+=a.added,r=a.end;for(var s=0,c=[],l=0;n<t;){var d=this.$gantt.date.day_start(new Date(r)),u=!1;r.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(r,u);if(!c.length||!l){r=this.$gantt.date.add(r,-1,"day");continue}if(c[c.length-1].end<=y&&p>l){n+=l,r=this.$gantt.date.add(r,-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,r=this.$gantt.date.add(r,-A.durationMinutes,"minute");else if(!o&&p<=y/60-A.startMinute)n+=p,r=this.$gantt.date.add(r,-p,"minute");else if(o)p<=y/60-A.startMinute?(n+=p,r=this.$gantt.date.add(r,-p,"minute")):(n+=y/60-A.startMinute,k?r=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,k.end)):r=this.$gantt.date.day_start(r));else{var F=this._getMinutesPerHour(r);F<=p?(n+=F,r=this._nextDate(r,"hour",i)):(a=this._subtractMinutesUntilHourStart(r,p),n+=a.added,r=a.end)}else if(r.getUTCHours()===0&&r.getUTCMinutes()===0&&r.getUTCSeconds()===0){var m=this._getClosestWorkTimePast(r,"hour");if(m.valueOf()===r.valueOf()){var m=this.$gantt.date.add(r,-1,"day"),R=this._getWorkHours(m);if(R.length){var M=R[R.length-1];m.setUTCSeconds(M.durationSeconds)}}r=m}else r=this._getClosestWorkTimePast(new Date(r-1),"hour")}if(n<t){var D=t-n;a=this._subtractMinutesUntilHourStart(r,D),n+=a.added,r=a.end}return r},_calculateMinuteEndDate:function(e,t,i){var r=new Date(e),n=0;i=i||1,t=Math.abs(t*1),t=Math.round(t);var o=this._addMinutesUntilHourEnd(r,t);n+=o.added,r=o.end;for(var a=0,s=[],c=0,l=this._isMinutePrecision(r);n<t;){var d=this.$gantt.date.day_start(new Date(r)).valueOf();d!==a&&(s=this._getWorkHours(r),c=this._getMinutesPerDay(r),a=d);var u=t-n,f=this._getTimeOfDayStamp(r);if(!s.length||!c){r=this.$gantt.date.add(this.$gantt.date.day_start(r),1,"day");continue}if(s[0].start>=f&&u>=c){if(n+=c,u==c){r=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,s[s.length-1].end));break}else r=this.$gantt.date.add(r,1,"day"),r=this.$gantt.date.day_start(r);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,r=this.$gantt.date.add(r,y.durationMinutes,"minute");else if(u<=y.endMinute-f/60)n+=u,r=this.$gantt.date.add(r,u,"minute");else{var A=this._getMinutesPerHour(r);A<=u?(n+=A,l?r=this.$gantt.date.add(r,A,"minute"):r=this._nextDate(r,"hour",i)):(o=this._addMinutesUntilHourEnd(r,u),n+=o.added,r=o.end)}else r=this._getClosestWorkTimeFuture(r,"hour")}if(n<t){var k=t-n;o=this._addMinutesUntilHourEnd(r,k),n+=o.added,r=o.end}return r},getClosestWorkTime:function(){var e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._getClosestWorkTime(e.date,e.unit,e.dir)},_getClosestWorkTime:function(e,t,i){var r=new Date(e);if(this._isWorkTime(r,t))return r;if(r=this.$gantt.date[t+"_start"](r),i=="any"||!i){var n=this._getClosestWorkTimeFuture(r,t),o=this._getClosestWorkTimePast(r,t);Math.abs(n-e)<=Math.abs(e-o)?r=n:r=o}else i=="past"?r=this._getClosestWorkTimePast(r,t):r=this._getClosestWorkTimeFuture(r,t);return r},_getClosestWorkTimeFuture:function(e,t){return this._getClosestWorkTimeGeneric(e,t,1)},_getClosestWorkTimePast:function(e,t){var i=this._getClosestWorkTimeGeneric(e,t,-1);return this.$gantt.date.add(i,1,t)},_findClosestTimeInDay:function(e,t,i){var r=new Date(e),n=null,o=!1;this._getWorkHours(r).length||(r=this._getClosestWorkTime(r,"day",t<0?"past":"future"),t<0&&(r=new Date(r.valueOf()-1),o=!0),i=this._getWorkHours(r));var a=this._getTimeOfDayStamp(r);if(o&&(a=this._getTimeOfDayStamp(new Date(r.valueOf()+1),o)),t>0){for(var s=0;s<i.length;s++)if(i[s].start>=a){n=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,i[s].start));break}}else for(var s=i.length-1;s>=0;s--)if(i[s].end<=a){n=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,i[s].end));break}else if(i[s].end>a&&i[s].start<=a){n=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,a));break}return n},_getClosestWorkMinute:function(e,t,i){var r=new Date(e),n=this._getWorkHours(r),o=this._findClosestTimeInDay(r,i,n);return o||(i>0?(r=this.calculateEndDate(r,i,t),r=this.$gantt.date.day_start(r)):(r=this.calculateEndDate(r,i,"day"),r=this.$gantt.date.day_start(r),r=this.$gantt.date.add(r,1,"day"),r=new Date(r.valueOf()-1)),n=this._getWorkHours(r),o=this._findClosestTimeInDay(r,i,n)),i<0&&(o=this.$gantt.date.add(o,-1,t)),o},_getClosestWorkTimeGeneric:function(e,t,i){if(t==="hour"||t==="minute")return this._getClosestWorkMinute(e,t,i);for(var r=this._getUnitOrder(t),n=this.units[r-1],o=e,a=3e3,s=0;!this._isWorkTime(o,t)&&!(n&&!this._isWorkTime(o,n)&&(i>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,i,t),this.$gantt.date[t+"_start"]&&(o=this.$gantt.date[t+"_start"](o))}return o},hasWorkTime:function(){var e=this.getConfig(),t=e.dates,i=[0,1,2,3,4,5,6];for(var r in e.dates);var n=this._checkWorkHours(e.hours),o=!1;return i.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,i=0;i<e.length;i+=2)e[i]!==e[i+1]&&(t=!0);return t},_isMinutePrecision:function(e){let t=!1;return this._getWorkHours(e).forEach(function(i){(i.startMinute%60||i.endMinute%60)&&(t=!0)}),t}};var or={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,i=e.resource_property;if(this.isLegacyResourceCalendarFormat(t))for(var r in e){i=r;break}return i},getCalendarIdFromLegacyConfig:function(e,t){if(t)for(var i in t){var r=t[i];if(e[i]){var n=r[e[i]];if(n)return n}}return null}};function wg(){function e(n){return n.map(function(o){return o&&o.resource_id?o.resource_id:o}).sort().join("-")}var t={};function i(n,o){return o.mergeCalendars(n.map(function(a){var s=a&&a.resource_id?a.resource_id:a;return o.getResourceCalendar(s)}))}function r(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=i(n,o);return t[a]=s,o.addCalendar(s)}else return null}return{getCalendarIdFromMultipleResources:r}}var xg=wg();function Fd(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=or.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))}Fd.prototype={_calendars:{},_convertWorkTimeSettings:function(e){let t=e.days;if(typeof t=="object"&&!Array.isArray(t)&&t!==null){let i={};if(t?.weekdays)for(let r=0;r<7;r++)i[r]=t.weekdays[r];t?.dates&&Object.entries(t.dates).forEach(([r,n])=>{i[new Date(r).valueOf()]=n}),Object.entries(i).forEach(([r,n])=>{n instanceof Array||(i[r]=!!n)}),e={...e,dates:i}}else if(t&&!e.dates){e.dates=e.dates||{};for(let i=0;i<t.length;i++)e.dates[i]=t[i],t[i]instanceof Array||(e.dates[i]=!!t[i])}return delete e.days,e},mergeCalendars:function(){var e=[],t=arguments;if(Array.isArray(t[0]))e=t[0].slice();else for(var i=0;i<arguments.length;i++)e.push(arguments[i]);var r=new bd,n;return e.forEach((function(o){n?n=this._createCalendarFromConfig(r.merge(n,o)):n=o}).bind(this)),this.createCalendar(n)},_createCalendarFromConfig:function(e){var t=new Ta(this.$gantt,Nd(this.$gantt));t.id=String(ha());var i=this._convertWorkTimeSettings(e);if(i.customWeeks)for(var r in i.customWeeks)i.customWeeks[r]=this._convertWorkTimeSettings(i.customWeeks[r]);return t._setConfig(i),t},createCalendar:function(e){var t;e||(e={}),e.getConfig?t=Xt(e.getConfig()):e.worktime?t=Xt(e.worktime):t=Xt(e);var i=Xt(this.defaults.fulltime.worktime);return Ri(t,i),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 i,r,n;if(this._legacyConfig===!1?n=t.resource_property:n=or.getResourceProperty(t),Array.isArray(e[n])&&e[n].length)t.dynamic_resource_calendars?r=xg.getCalendarIdFromMultipleResources(e[n],this):i=this.getResourceCalendar(e[n]);else if(this._legacyConfig===void 0&&(this._legacyConfig=or.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var r=or.getCalendarIdFromLegacyConfig(e,t.resource_calendars);else if(n&&e[n]&&t.resource_calendars[e[n]])var i=this.getResourceCalendar(e[n]);if(r&&(i=this.getCalendar(r)),i)return i}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 i=this.$gantt.config,r=i.resource_calendars,n=null;if(Array.isArray(e)&&e.length===1&&(typeof e[0]=="object"?t=e[0].resource_id:t=e[0]),r){if(this._legacyConfig===void 0&&(this._legacyConfig=or.isLegacyResourceCalendarFormat(i.resource_calendars)),this._legacyConfig){for(var o in r)if(r[o][t]){n=r[o][t];break}}else var n=r[t];if(n)return this.getCalendar(n)}return this.getCalendar()},getTaskCalendar:function(e){var t=this.$gantt,i;if(e==null)return this.getCalendar();if((typeof e=="number"||typeof e=="string")&&t.isTaskExists(e)?i=t.getTask(e):i=e,!i)return this.getCalendar();var r=this._getOwnCalendar(i),n=!!t.getState().group_mode;if(!r&&t.config.inherit_calendar&&t.isTaskExists(i.parent)){for(var o=i;t.isTaskExists(o.parent)&&(o=t.getTask(o.parent),!(t.isSummaryTask(o)&&(r=this._getOwnCalendar(o),r))););n&&!r&&e.$effective_calendar&&(r=this.getCalendar(e.$effective_calendar))}return r||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 i=this.$gantt.config;return e.id=e.id||ha(),this._calendars[e.id]=e,i.worktimes||(i.worktimes={}),i.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 i=e[t],r=this.createCalendar(i);r.id=t,this.addCalendar(r)}},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(i){return i instanceof Function})}};function Da(e,t){this.argumentsHelper=t,this.$gantt=e}Da.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,i=e.end_date,r=e.unit,n=e.step;return this._calculateDuration(t,i,r,n)},_calculateDuration:function(e,t,i,r){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[i])a=Math.round((t-e)/(r*o[i]));else{for(var s=new Date(e),c=new Date(t);s.valueOf()<c.valueOf();)a+=1,s=n.add(s,r,i);s.valueOf()!=t.valueOf()&&(a+=(c-s)/(n.add(s,r,i)-s))}return Math.round(a)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,i=e.end_date,r=e.unit;return r?(t=new Date(t),i=new Date(i),t.valueOf()<i.valueOf()):!1},hasWorkTime:function(){return!0},equals:function(e){return e instanceof Da},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,i=e.duration,r=e.unit,n=e.step;return this.$gantt.date.add(t,n*i,r)}};function wd(e){this.$gantt=e.$gantt,this.argumentsHelper=Nd(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new Da(this.$gantt,this.argumentsHelper)}wd.prototype={_getCalendar:function(e){var t;if(!this.$gantt.config.work_time)t=this.$disabledCalendar;else{var i=this.calendarManager;e.task?t=i.getTaskCalendar(e.task):e.id?t=i.getTaskCalendar(e):e.calendar&&(t=e.calendar),t||(t=i.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,i,r){var n=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return r=this._getCalendar(n),r.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),i=this._getCalendar(t);return i.calculateEndDate(t)}};var Mg=function(e,t){return{getWorkHours:function(i){return t.getWorkHours(i)},setWorkTime:function(i){return t.setWorkTime(i)},unsetWorkTime:function(i){t.unsetWorkTime(i)},isWorkTime:function(i,r,n){return t.isWorkTime(i,r,n)},getClosestWorkTime:function(i){return t.getClosestWorkTime(i)},calculateDuration:function(i,r,n){return t.calculateDuration(i,r,n)},_hasDuration:function(i,r,n){return t.hasDuration(i,r,n)},calculateEndDate:function(i,r,n,o){return t.calculateEndDate(i,r,n,o)},mergeCalendars:Bt(e.mergeCalendars,e),createCalendar:Bt(e.createCalendar,e),addCalendar:Bt(e.addCalendar,e),getCalendar:Bt(e.getCalendar,e),getCalendars:Bt(e.getCalendars,e),getResourceCalendar:Bt(e.getResourceCalendar,e),getTaskCalendar:Bt(e.getTaskCalendar,e),deleteCalendar:Bt(e.deleteCalendar,e)}},Ug={create:Mg};function xd(e){var t=new Fd(e),i=new wd(t),r=Ug.create(t,i);Ri(e,r)}var Md={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 Ud(e={}){let t=e.config||{},i={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||Md,templates:e.templates||{},getTask:e.getTask||function(r){return null},isTaskExists:e.isTaskExists||function(r){return!1},isSummaryTask:e.isSummaryTask||function(r){return!1},getState:function(){return{group_mode:!1}},callEvent:function(r,n){let o=e.onEvent;return o&&o(r,n),!0},attachEvent:function(){return 0},checkEvent:function(){return!1},detachEvent:function(){},defined:Rd,mixin:Ri,copy:Xt,assert:function(r,n){if(!r){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 i._correct_dst_change=function(r){return r},i.date=Od(i),i.date.init(),xd(i),i}function Hg(e={}){let t=Ud(e);return{addCalendar:function(i){return t.addCalendar(i)},deleteCalendar:function(i){return t.deleteCalendar(i)},getCalendar:function(i){return t.getCalendar(i)},getCalendars:function(){return t.getCalendars()},mergeCalendars:function(){return t.mergeCalendars.apply(t,arguments)},getTaskCalendar:function(i){return t.getTaskCalendar(i)},getResourceCalendar:function(i){return t.getResourceCalendar(i)},setWorkTime:function(i){return t.setWorkTime(i)},unsetWorkTime:function(i){return t.unsetWorkTime(i)},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 Hd={createCalendar:Hg};var l0=3600*1e3;function jd(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:Bg}=Hd,ar="__replay_default__";function Wg(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 i=t[0],r=t[t.length-1];return t.every((o,a)=>o===i+a)?[`${i}:00-${r+1}:00`]:e}var Bd={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},Wd="__main_global__",Vg={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function Vd(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 jg(e){let t={};if(Array.isArray(e.days))for(let r=0;r<e.days.length;r+=1)t[r]=e.days[r];if(e.dates)for(let[r,n]of Object.entries(e.dates))t[r]=n;let i={hours:Wg(e.hours),dates:t};return e.customWeeks&&(i.customWeeks=e.customWeeks),i}function Kd(e){let t=Bg({config:{work_time:!0}});t.addCalendar({id:ar,worktime:Bd}),t.addCalendar({id:Wd,worktime:Vg});let i=new Set(e.filter(d=>!Vd(d.worktime)).map(d=>String(d.id))),r=e.filter(d=>Vd(d.worktime));for(let d of r)t.addCalendar({id:d.id,worktime:d.worktime?jg(d.worktime):Bd});let n=kd(t),o=n.getCalendar(ar),a=n.getCalendar(Wd);if(!o||!a)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let s=new Set([ar]);for(let d of r)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:i.has(u)&&(p=a),c.set(u,p),p}}}}function Yd(e){return{hasChildren(t){return e.hasChildren(t)},getParentStartDateIfHasPredecessors(t){let i=e.getActivity(t);if(!i)return null;let r=e.getParent(i.id);return!r||e.getIncomingLinkIds(r.id).length===0?null:r.startDate},getDescendantIds(t){return Kg(e,t).map(i=>String(i))},getAncestorIds(t){let i=[],r=e.getActivity(t);for(;r;){let n=r.parentId;if(n===null)break;let o=e.getActivity(n);if(!o)break;i.push(String(n)),r=o}return i},getChildProgressInfo(t){return e.getChildren(t).map(r=>{let n=e.getActivity(r);return{id:r,progress:Number(n?.progress??0),ponderator:Number(n?.ponderator??0)}})},getChildHhInfo(t){return e.getChildren(t).map(r=>{let n=e.getActivity(r);return{id:r,workHours:Number(n?.workHours??0),progress:Number(n?.progress??0),realWorkHours:Number(n?.realWorkHours??0)}})},getChildUsedCostInfo(t){return e.getChildren(t).map(r=>{let n=e.getActivity(r);return{id:r,usedCost:Number(n?.usedCost??0)}})},getChildCostInfo(t){return e.getChildren(t).map(r=>{let n=e.getActivity(r);return{id:r,cost:Number(n?.cost??0)}})}}}function Kg(e,t){let i=[],r=new Ut;for(let n of e.getChildren(t))r.enqueue(n);for(;!r.isEmpty();){let n=r.dequeue();i.push(n);for(let o of e.getChildren(n))r.enqueue(o)}return i}var On=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let i=Gd(t);return this.reader.getCalendar(i??ar)}getClosestWorkTime(t){let i=`${_a(t.task)}|${t.dir}|${t.date.getTime()}`;return Ea(this._cache.closestWorkTime,i,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:ut.HOUR}))}calculateEndDate(t){let i=`${_a(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return Ea(this._cache.endDate,i,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let i=`${_a(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return Ea(this._cache.duration,i,()=>this.resolveCalendar(t.task).calculateDuration(t.startDate,t.endDate))}clearCache(){this._cache.closestWorkTime.clear(),this._cache.endDate.clear(),this._cache.duration.clear()}};function Ea(e,t,i){let r=e.get(t);if(r!==void 0)return r;let n=i();return e.set(t,n),n}var Yg="__default__";function Gd(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function _a(e){return Gd(e)??Yg}var Nn=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,i){let r=this.activities.get(t)?.parentId,n=0,o=this.activities.size;for(;r&&!U(r);){if(r===i)return!0;if(++n>o)return!1;r=this.activities.get(r)?.parentId}return!1}getParent(t){let i=this.activities.get(t)?.parentId;return!i||U(i)?null:this.activities.get(i)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,i){if(this._dirty)return;if(U(t)){this._roots.push(i);return}let r=String(t),n=this._childrenByParent.get(r);n?n.push(i):this._childrenByParent.set(r,[i])}rebuild(){this._childrenByParent.clear(),this._roots=[];for(let i of this.activities.values()){if(U(i.parentId)){this._roots.push(i.id);continue}let r=String(i.parentId),n=this._childrenByParent.get(r)??[];n.push(i.id),this._childrenByParent.set(r,n)}let t=(i,r)=>{let n=this.activities.get(i),o=this.activities.get(r);return n&&o?Ar(n,o):String(i).localeCompare(String(r))};this._roots.sort(t);for(let i of this._childrenByParent.values())i.sort(t)}};var bn=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,i){return i===this.checkedSet.has(t)?!1:(i?this.checkedSet.add(t):this.checkedSet.delete(t),!0)}setVisible(t,i){return i===!this.hiddenSet.has(t)?!1:(i?this.hiddenSet.delete(t):this.hiddenSet.add(t),!0)}forget(t){this.checkedSet.delete(t),this.hiddenSet.delete(t)}hydrate(t){this.checkedSet=new Set(t.checkedIds??[]),this.hiddenSet=new Set(t.hiddenIds??[]),this.activeFilter=null,this.activeOrder=null}snapshot(){return{checked:new Set(this.checkedSet),hidden:new Set(this.hiddenSet),activeFilter:this.activeFilter,activeOrder:this.activeOrder}}restore(t){this.checkedSet=new Set(t.checked),this.hiddenSet=new Set(t.hidden),this.activeFilter=t.activeFilter,this.activeOrder=t.activeOrder}};var Pi=class e{_activities=new Map;_lastStartDate=new Map;_promotionSnapshot=new Map;_progressFallback=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_buildOrderComparator;_cache={ids:null,visualOrderIds:null,orderComparator:null};_writeCapture=new dn;_viewState=new bn;_filterProjection=null;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_calendar;_flags;_calendarSnapshot;constructor(t,i=()=>null){this._buildOrderComparator=i,this._calendarSnapshot=w(t.calendars);for(let r of t.activities)this._activities.set(r.id,r);for(let r of t.links){let n={...r,freeSlackHours:r.freeSlackHours??null,isCritical:r.isCritical===!0};this._links.set(String(r.id),n),this._indexLink(n)}this._calendar=new On(Kd(this._calendarSnapshot)),this._flags=$g(t),this._hierarchy=new Nn(this._activities),this._hierarchy.rebuild()}fork(){let t=new e({activities:this.getAllActivities().map(ce),links:this.getAllLinks().map(i=>({...i})),calendars:w(this._calendarSnapshot)},this._buildOrderComparator);return t._viewState.restore(w(this._viewState.snapshot())),t._lastStartDate=new Map(Array.from(this._lastStartDate,([i,r])=>[i,new Date(r)])),t._promotionSnapshot=new Map(Array.from(this._promotionSnapshot,([i,r])=>[i,w(r)])),t._progressFallback=new Map(this._progressFallback),t._flags=w(this._flags),t._filterProjection=w(this._filterProjection),t}getAllActivities(){return Array.from(this._activities.values())}getAllLinks(){return Array.from(this._links.values())}getAllIds(){return this._cache.ids?this._cache.ids:(this._cache.ids=Array.from(this._activities.keys()),this._cache.ids)}activityCount(){return this._activities.size}getVisualOrderIds(){return this._cache.visualOrderIds?this._cache.visualOrderIds:(this._cache.visualOrderIds=Is(this).map(t=>String(t.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null}forEachActivity(t){for(let[i,r]of this._activities)t(r,i)}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,i){this._captureLastStartDateOnce(),this._lastStartDate.set(String(t),i)}getPromotionSnapshot(t){return this._promotionSnapshot.get(String(t))??null}setPromotionSnapshot(t,i){this._capturePromotionSnapshotOnce(),this._promotionSnapshot.set(String(t),i)}getProgressFallback(t){return this._progressFallback.get(String(t))??null}setProgressFallback(t,i){let r=String(t),n=this._progressFallback.get(r)??null;Object.is(n,i)||(this._writeCapture.noteProgressFallback(r,n),i===null?this._progressFallback.delete(r):this._progressFallback.set(r,i))}_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,i){return this._captureViewStateOnce(),this._viewState.setChecked(String(t),i)}setVisible(t,i){return this._captureViewStateOnce(),this._viewState.setVisible(String(t),i)}getActiveFilter(){return this._viewState.getActiveFilter()}setActiveFilter(t){this._captureViewStateOnce(),this._viewState.setActiveFilter(t),this._filterProjection=null}getFilterProjection(){return this._filterProjection}setFilterProjection(t){this._filterProjection=t}getActiveOrder(){return this._viewState.getActiveOrder()}setActiveOrder(t){this._captureViewStateOnce(),this._viewState.setActiveOrder(t),this.invalidateDerivedOrder()}getOrderComparator(){let t=this._viewState.getActiveOrder();return t===null?(this._cache.orderComparator=null,null):this._cache.orderComparator?this._cache.orderComparator:(this._cache.orderComparator=this._buildOrderComparator(t),this._cache.orderComparator)}invalidateDerivedOrder(){this._cache.orderComparator=null,this._cache.visualOrderIds=null}hydrateViewState(t){this._viewState.hydrate(t),this._filterProjection=null,this.invalidateDerivedOrder()}_captureViewStateOnce(){this._writeCapture.peek()!==null&&this._viewStateBefore===null&&(this._viewStateBefore=this._viewState.snapshot())}getOutgoingLinkIds(t){return this._outgoing.get(String(t))??$d}getIncomingLinkIds(t){return this._incoming.get(String(t))??$d}getChildren(t){return this._hierarchy.getChildren(t)}hasChildren(t){return this._hierarchy.hasChildren(t)}isChildOf(t,i){return this._hierarchy.isChildOf(t,i)}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,i,r){let n=this.getActivity(t);n&&(this._writeCapture.note(String(t),n),n[i]=r,Ra(n,i),i===b.PARENT&&this._hierarchy.markDirty(),ka(i)&&(this._cache.visualOrderIds=null))}setActivityFieldDynamic(t,i,r){let n=this.getActivity(t);if(n){if(!Object.hasOwn(n,i))throw new Error(`setActivityFieldDynamic: unknown CoreActivity field "${i}"`);this._writeCapture.note(String(t),n),Reflect.set(n,i,_d(i,r)),Ra(n,i),i===b.PARENT&&this._hierarchy.markDirty(),ka(i)&&(this._cache.visualOrderIds=null)}}setActivityFields(t,i){let r=this.getActivity(t);if(!r)return;this._writeCapture.note(String(t),r);let n=!1;for(let o of Object.keys(i))Reflect.set(r,o,Reflect.get(i,o)),Ra(r,o),o===b.PARENT&&(n=!0),ka(o)&&(this._cache.visualOrderIds=null);n&&this._hierarchy.markDirty()}addLink(t){this._writeCapture.noteLinkAdd(String(t.id));let i=this._links.get(String(t.id));i&&this._deindexLink(i);let r={...t,freeSlackHours:t.freeSlackHours??null,isCritical:t.isCritical===!0};this._links.set(String(t.id),r),this._indexLink(r)}_indexLink(t){zd(this._outgoing,String(t.source),t.id),zd(this._incoming,String(t.target),t.id)}_deindexLink(t){let i=this._outgoing.get(String(t.source));i&&this._outgoing.set(String(t.source),Pa(i,t.id));let r=this._incoming.get(String(t.target));r&&this._incoming.set(String(t.target),Pa(r,t.id))}_removeLinkRef(t,i,r){let n=t.get(i);n&&t.set(i,Pa(n,r))}_insertLinkRefInOrder(t,i,r){let n=new Set;for(let s of this._links.keys()){if(String(s)===String(r))break;n.add(String(s))}let o=[...t.get(i)??[]],a=o.findIndex(s=>!n.has(String(s)));o.splice(a<0?o.length:a,0,r),t.set(i,o)}setLinkField(t,i,r){let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),n[i]=r)}setLinkEndpoints(t,i,r){let n=this.getLink(t);if(!n)return;let o=String(n.source)!==String(i),a=String(n.target)!==String(r);!o&&!a||(this._writeCapture.noteLinkField(String(t),n),o&&(this._removeLinkRef(this._outgoing,String(n.source),n.id),n.source=i,this._insertLinkRefInOrder(this._outgoing,String(i),n.id)),a&&(this._removeLinkRef(this._incoming,String(n.target),n.id),n.target=r,this._insertLinkRefInOrder(this._incoming,String(r),n.id)))}setLinkFieldDynamic(t,i,r){let n=this.getLink(t);if(n){if(i===wt.SOURCE){this.setLinkEndpoints(t,String(r),n.target);return}if(i===wt.TARGET){this.setLinkEndpoints(t,n.source,String(r));return}Gg(i)&&(this._writeCapture.noteLinkField(String(t),n),Reflect.set(n,i,r))}}setLinkProplannerId(t,i){let r=this.getLink(t);r&&(this._writeCapture.noteLinkField(String(t),r),r.proplannerId=i)}removeLink(t){let i=this.getLink(t);i&&(this._writeCapture.noteLinkRemove(String(t),i),this._links.delete(String(t)),this._deindexLink(i))}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 i=this.getActivity(t);i&&this._writeCapture.noteRemove(String(t),i);let r=String(t);this.setProgressFallback(r,null),(this._viewState.isChecked(r)||!this._viewState.isVisible(r))&&this._captureViewStateOnce(),this._viewState.forget(r),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,i){this._writeCapture.noteCorrelativeBefore(t,i)}noteScheduledBefore(t,i){this._writeCapture.noteScheduledBefore(t,i)}restoreFromCapture(){let t=this._writeCapture.peek();if(!t)return;let{ops:i,before:r,correlativeBefore:n,scheduledBefore:o,progressFallbackBefore:a}=t;this._undoLinkAdds(i),this._undoInserts(i),this._reInsertRemovedActivities(i),this._reAddRemovedLinks(i),this._restoreLinkFields(i),this._restoreActivityFields(o),this._restoreActivityFields(r),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[i,r]of t)r===null?this._progressFallback.delete(i):this._progressFallback.set(i,r)}_restoreCorrelatives(t){for(let[i,r]of t){let n=this._activities.get(i);n&&(n.correlativeId=r)}}_undoLinkAdds(t){for(let i of t)i.kind===Rt.LINK_ADD&&this._detachLink(i.linkId)}_undoInserts(t){for(let i of t)i.kind===Rt.INSERT&&this._activities.delete(i.activityId)}_reInsertRemovedActivities(t){for(let i of t)i.kind===Rt.REMOVE&&this._activities.set(i.activityId,i.before)}_reAddRemovedLinks(t){for(let i of t)i.kind===Rt.LINK_REMOVE&&this._attachLink(i.before)}_restoreLinkFields(t){for(let i of t){if(i.kind!==Rt.LINK_FIELD)continue;let r=this._links.get(i.linkId);if(r){this.setLinkEndpoints(i.linkId,i.before.source,i.before.target);for(let n of Object.keys(r))Object.hasOwn(i.before,n)||Reflect.deleteProperty(r,n);Object.assign(r,i.before)}}}_restoreActivityFields(t){for(let[i,r]of t){let n=this._activities.get(i);n&&this._restoreScalarFields(n,r)}}_restoreScalarFields(t,i){for(let r of Object.keys(t))Object.hasOwn(i,r)||Reflect.deleteProperty(t,r);for(let r of Object.keys(i))Reflect.set(t,r,Reflect.get(i,r))}_attachLink(t){this._links.set(String(t.id),{...t}),this._indexLink(t)}_detachLink(t){let i=this.getLink(t);i&&(this._links.delete(String(t)),this._deindexLink(i))}},$d=[];function Gg(e){return e===wt.LAG||e===wt.TYPE||e===wt.FREE_SLACK_HOURS||e===wt.IS_CRITICAL}function ka(e){return e===b.PARENT||e===b.CORRELATIVE_ID}function Ra(e,t){t!==b.START_DATE&&t!==b.END_DATE&&t!==b.TYPE||(e.calendarDuration=te(e))}function Pa(e,t){return e.filter(i=>String(i)!==String(t))}function zd(e,t,i){let r=e.get(t);r?r.push(i):e.set(t,[i])}function $g(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 La(e,t){let i=e.getActivity(t);return i?w(i):null}function qd(e){return e.getAllActivities().map(w)}function Jd(e){return e.getAllIds().map(String)}function Xd(e,t){e.forEachActivity((i,r)=>t(r))}function Zd(e,t){let i=t==="0"?Oa(e,"0"):e.getChildren(t),r=[];for(let n of i){let o=e.getActivity(n);o&&r.push(w(o))}return r.sort((n,o)=>(n.correlativeId??0)-(o.correlativeId??0)),r}function Oa(e,t){return Wt(t,e)}function Qd(e){return e.checkedIds().map(String)}function tu(e,t){if(t==="0"){let i=!1;return e.forEachActivity(r=>{i||=U(r.parentId)}),i}return e.getChildren(t).length>0}function Na(e,t){let i=e.getLink(t);return i?Mt(i):null}function eu(e){return e.getAllLinks().map(t=>Mt(t))}function Fn(e){let[t,i]=e.split(":");return Number(t)*60+Number(i??0)}function zg(e){return e.reduce((t,i)=>Fn(i)<Fn(t)?i:t)}function qg(e){return e.reduce((t,i)=>Fn(i)>Fn(t)?i:t)}function Jg(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function iu(e){let t=[...e].find(o=>o.is_default);if(!t)return null;let i=Jg(t);if(i.length===0)return null;let r=i.map(o=>o.split("-")[0]),n=i.map(o=>o.split("-")[1]);return{startHour:zg(r),endHour:qg(n)}}function ba(e,t){return{calendars:e.calendarReader,hierarchy:Yd(e),activityReader:jd(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay}}function ru(e){return $e(e)}var Xg=new Set(["freeSlackHours","isCritical"]);function Zg(e,t){let i=Object.fromEntries(Object.entries(e.fields??{}).filter(([r])=>!t.has(r)));return e.kind===N.UPDATED&&Object.keys(i).length===0?null:{...e,...e.fields===void 0?{}:{fields:i},after:null}}function su(e){let t=e.activities.map(n=>({...n,after:null})),i=e.links.map(n=>Zg(n,Xg)).filter(n=>n!==null),r=e.source.kind===pe?{...e.source,items:[],links:[]}:e.source;return w({...e,source:r,activities:t,links:i})}function Fa(e,t,i,r,n,o,a){return{changeSet:e,beforeSnap:t,beforeLinks:nu(i),afterSnap:r,afterLinks:nu(n),progressFallbackBefore:o,progressFallbackAfter:a}}function nu(e){if(e)return new Map(Array.from(e,([t,i])=>[t,{...i,freeSlackHours:null,isCritical:!1}]))}function cu(e,t){let i=new Map,r=new Map;for(let n of t.activities){if(n.kind!==N.CREATED)continue;let o=e.getActivity(String(n.id));o&&i.set(String(n.id),nt(o))}for(let n of t.links){if(n.kind===N.DELETED)continue;let o=e.getLink(String(n.id));o&&r.set(String(n.id),{...o})}return{afterSnap:i,afterLinks:r}}function lu(e){return e.kind!==I.INLINE_EDIT||!er.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function ou(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 du(e,t){if(!ou(e)||!ou(t))return!1;let i=e.changeSet.activities[0],r=t.changeSet.activities[0];return!!i&&!!r&&String(i.id)===String(r.id)}function uu(e,t){let i=e.changeSet.activities[0],r=t.changeSet.activities[0];if(!i||!r)return t;let n=i.fields??{},o=r.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:[{...r,fields:a}]};return Fa(s)}var Li={RECORD:"record",SKIP:"skip",CHECKPOINT_ON_SUCCESS:"checkpoint-on-success"},dt={BEFORE:"before",AFTER:"after"};function fu(e){return e.kind===I.PERSISTENCE_ACKNOWLEDGE?Li.CHECKPOINT_ON_SUCCESS:e.kind===I.SIR_SYNC||e.kind===I.CALENDAR_RECONCILE||e.kind===I.ACTIVITY_LOOKAHEAD_SYNC||e.kind===I.BASELINE_APPLY||e.kind===I.PONDERATOR_CRITERION_SET||e.kind===I.STATUS_CRITERIA_SET||e.kind===I.ACTIVITY_CLIPBOARD_CLEAR||e.kind===I.ACTIVITY_COPY||e.kind===I.SELECTION_TOGGLE||e.kind===I.SELECTION_REPLACE||e.kind===I.VISIBILITY_SET||e.kind===I.FILTER_SET||e.kind===I.SORT_SET?Li.SKIP:Li.RECORD}function wa(e){for(let t of e.changeSet.activities)if(t.kind===N.CREATED||t.kind===N.DELETED||t.kind===N.UPDATED&&t.fields&&E.CUSTOM_ID in t.fields)return!0;return!1}function xa(e,t,i){let r=[],n=[];for(let a of t.changeSet.activities){let s=String(a.id);if(a.kind===N.UPDATED){let c=e.getActivity(s);r.push({id:s,kind:N.UPDATED,fields:au(a.fields,i),after:c?nt(c):null})}else if(a.kind===N.DELETED)if(i===dt.BEFORE){let c=e.getActivity(s);r.push({id:s,kind:N.CREATED,after:c?nt(c):null})}else r.push({id:s,kind:N.DELETED,after:null});else if(i===dt.BEFORE)r.push({id:s,kind:N.DELETED,after:null});else{let c=e.getActivity(s);r.push({id:s,kind:N.CREATED,after:c?nt(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:au(a.fields,i),after:c?Mt(c):null})}else if(a.kind===N.DELETED)if(i===dt.BEFORE){let c=e.getLink(s);n.push({id:s,kind:N.CREATED,after:c?Mt(c):null})}else n.push({id:s,kind:N.DELETED,after:null});else if(i===dt.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?Mt(c):null})}}let o=(t.changeSet.viewState??[]).map(a=>i===dt.BEFORE?Qg(a):a);return{source:{kind:i===dt.BEFORE?ee.UNDO:ee.REDO},activities:r,links:n,calendars:[],trackingEvents:[],effects:[],viewState:o}}function au(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([i,r])=>[i,t===dt.BEFORE?{before:w(r.after),after:w(r.before)}:{before:w(r.before),after:w(r.after)}]))}function Qg(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 Ma(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function pu(e,t){hu(e,t,dt.BEFORE)}function yu(e,t){hu(e,t,dt.AFTER)}function hu(e,t,i){let r=t.changeSet;for(let o of r.activities)if(o.kind===N.UPDATED){if(!o.fields)continue;for(let[a,s]of Object.entries(o.fields))lt(e,o.id,a,i===dt.BEFORE?s.before:s.after)}else if(o.kind===N.DELETED)if(i===dt.BEFORE){let a=t.beforeSnap?.get(String(o.id));if(!a)throw new Error(`undo: missing beforeSnap for resurrecting activity ${o.id}`);e.addActivity(nt(a))}else e.removeActivity(String(o.id));else if(i===dt.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(nt(a))}for(let o of r.links)if(o.kind===N.UPDATED){if(!o.fields)continue;let a=e.getLink(String(o.id)),s=o.fields[wt.SOURCE],c=o.fields[wt.TARGET];a&&(s||c)&&e.setLinkEndpoints(String(o.id),String(s?i===dt.BEFORE?s.before:s.after:a.source),String(c?i===dt.BEFORE?c.before:c.after:a.target));for(let[l,d]of Object.entries(o.fields))l===wt.SOURCE||l===wt.TARGET||Rc(e,String(o.id),l,i===dt.BEFORE?d.before:d.after)}else if(o.kind===N.DELETED)if(i===dt.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(i===dt.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 r.viewState??[])o.checked&&e.setChecked(o.activityId,i===dt.BEFORE?o.checked.before:o.checked.after),o.visible&&e.setVisible(o.activityId,i===dt.BEFORE?o.visible.before:o.visible.after);let n=i===dt.BEFORE?t.progressFallbackBefore:t.progressFallbackAfter;for(let[o,a]of n??[])e.setProgressFallback(o,a)}var tA=100,eA=600,wn=class e{constructor(t=tA){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,i=null,r=0){let n=this.undoStack[this.undoStack.length-1];i!=null&&i===this._lastKey&&r-this._lastTime<=eA&&n!==void 0&&du(n.entry,t)?(n.entry=uu(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=i,this._lastTime=r,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,i){let r=new Map(t.map(({id:o,proplannerId:a})=>[String(o),a])),n=new Map(i.map(({id:o,proplannerId:a})=>[String(o),a]));for(let o of[...this.undoStack,...this.redoStack])o.entry=this.withPersistedIdentities(o.entry,r,n)}clear(){this.undoStack.length=0,this.redoStack.length=0,this.resetCoalesce()}touch(){return this.sequence+=1,this.sequence}removeEntriesThrough(t,i){let r=t.filter(({touchedAt:n})=>n>i);t.splice(0,t.length,...r)}withPersistedIdentities(t,i,r){let n=a=>a===void 0?void 0:new Map(Array.from(a,([s,c])=>[s,i.has(s)?{...c,proplannerId:i.get(s)}:c])),o=a=>a===void 0?void 0:new Map(Array.from(a,([s,c])=>[s,r.has(s)?{...c,proplannerId:r.get(s)}:c]));return{...t,beforeSnap:n(t.beforeSnap),afterSnap:n(t.afterSnap),beforeLinks:o(t.beforeLinks),afterLinks:o(t.afterLinks)}}};var iA=["parentId","correlativeId"];function Iu(e,t){let i=new Set,r=n=>{let o=t(n);i.add(o===null?"0":String(o))};for(let n of e.activities){let o=String(n.id);if(n.kind===N.CREATED){r(o);continue}if(n.kind===N.DELETED){let c=n.fields;c&&"parentId"in c&&i.add(mu(c.parentId?.before));continue}let a=n.fields;!a||!iA.some(c=>c in a)||(r(o),"parentId"in a&&i.add(mu(a.parentId?.before)))}return i}function mu(e){return e==null?"0":String(e)}function rA(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function nA(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function gu(e){return{id:String(e.id),worktime:nA(e.worktime)}}function xn(e,t,i,r=[]){let n=t.map(rA),o=[...i.map(gu),...r.map(gu)];return{activities:[...e],links:n,calendars:o}}var x={TRACKED:"tracked",IGNORED:"ignored"};var Au={id:x.IGNORED,proplannerId:x.IGNORED,parentId:x.TRACKED,name:x.TRACKED,description:x.TRACKED,type:x.TRACKED,startDate:x.TRACKED,endDate:x.TRACKED,durationHours:x.TRACKED,constraintType:x.TRACKED,constraintDate:x.TRACKED,autoScheduling:x.TRACKED,calendarId:x.TRACKED,assignedDefaultCalendar:x.IGNORED,dateOrigin:x.TRACKED,progress:x.TRACKED,cost:x.TRACKED,usedCost:x.TRACKED,realCost:x.TRACKED,workHours:x.TRACKED,realWorkHours:x.TRACKED,ponderator:x.TRACKED,hasCustomPonderator:x.TRACKED,correlativeId:x.TRACKED,uniqueCorrelativeId:x.TRACKED,customId:x.TRACKED,subcontractId:x.TRACKED,isLookahead:x.TRACKED,hasLookaheadTasks:x.IGNORED,newActivityIds:x.TRACKED,hasNewActivities:x.TRACKED,isNewActivity:x.IGNORED,pendingRequestIds:x.IGNORED,responsableIds:x.TRACKED,tagIds:x.TRACKED,baselinePoints:x.IGNORED,baselineSnapshot:x.IGNORED,recursiveDurationHours:x.IGNORED,isCritical:x.IGNORED,freeSlackHours:x.IGNORED,calendarDuration:x.IGNORED,expectedProgress:x.IGNORED,expectedProgressBaseline:x.IGNORED,status:x.IGNORED,criticalPath:x.IGNORED},vu=Object.keys(Au).filter(e=>Au[e]===x.TRACKED),Cu=new Set(["startDate","endDate","constraintDate","dateOrigin"]),Su=new Set(["newActivityIds","responsableIds","tagIds"]);function Tu(e){let t=vu.map(i=>[i,oA(i,e[i])]);return Object.fromEntries(t)}function oA(e,t){return Cu.has(e)?t instanceof Date?new Date(t):null:Su.has(e)?Array.isArray(t)?[...t]:[]:t}function sr(e,t){return Ua(e,t).length>0}function Ua(e,t){return vu.filter(i=>!aA(i,e[i],t[i]))}function aA(e,t,i){return Cu.has(e)?sA(t,i):Su.has(e)?cA(t,i):(t??null)===(i??null)}function sA(e,t){let i=e instanceof Date?e.getTime():null,r=t instanceof Date?t.getTime():null;return i===r}function cA(e,t){let i=new Set(Array.isArray(e)?e.map(String):[]),r=new Set(Array.isArray(t)?t.map(String):[]);if(i.size!==r.size)return!1;for(let n of i)if(!r.has(n))return!1;return!0}var Du={id:x.IGNORED,source:x.TRACKED,target:x.TRACKED,type:x.TRACKED,lag:x.TRACKED,freeSlackHours:x.IGNORED,isCritical:x.IGNORED,ganttId:x.IGNORED,sectorId:x.IGNORED,proplannerId:x.IGNORED},lA=Object.keys(Du).filter(e=>Du[e]===x.TRACKED);function Mn(e,t){return lA.some(i=>e[i]!==t[i])}function Eu(e,t){let i=new Map(e.map(r=>[String(r.id),r]));return t.filter(r=>{let n=i.get(String(r.id));return n?Mn(n,r):!1})}function Zt(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 _u(e,t){for(let i of e)Zt(i.proplannerId);for(let i of t)Zt(i.proplannerId)}var Un=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[i,r]of this.linksAtLastSave)t.linksAtLastSave.set(i,w(r));for(let[i,r]of this.activitiesAtLastSave)t.activitiesAtLastSave.set(i,w(r));return t}init(t,i){if(this.trackingEnabled){_u(t,i),this.snapshotActivities(t),this.snapshotLinks(i);for(let r of t)if(r.assignedDefaultCalendar){let n=String(r.id);this.initialCalendarRepairIds.add(n),this.dirtyActivityIds.add(n)}this.initialized=!0}}acknowledge(t,i,r=[],n=[],o,a){if(!this.trackingEnabled)return;let s=new Map(r.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=i.map(p=>{let y=c.get(String(p.id));return y===void 0?{...p}:{...p,proplannerId:y}});if(_u(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 i of t){let r=String(i.id);if(!Zt(i.proplannerId)){this.dirtyActivityIds.add(r);continue}let n=Tu(i);this.activitiesAtLastSave.set(String(i.id),{persistable:n,deletedSnapshot:{id:i.id,proplannerId:i.proplannerId,parentId:i.parentId,hadBaseline:i.baselineSnapshot!==null||i.baselinePoints.length>0}}),sr(i,n)&&this.dirtyActivityIds.add(r)}}}snapshotLinks(t){if(this.trackingEnabled){this.linksAtLastSave.clear(),this.dirtyLinkIds.clear();for(let i of t){let r=String(i.id);if(!Zt(i.proplannerId)){this.dirtyLinkIds.add(r);continue}this.linksAtLastSave.set(String(i.id),{id:i.id,proplannerId:i.proplannerId,source:i.source,target:i.target,lag:i.lag,type:i.type})}}}recordChanges(t,i,r,n){if(!(!this.trackingEnabled||!this.initialized)){for(let o of t){let a=String(o.id),s=r(a);this.activityIsDirty(a,s)?this.dirtyActivityIds.add(a):this.dirtyActivityIds.delete(a)}for(let o of i){let a=String(o.id),s=n(a);this.linkIsDirty(a,s)?this.dirtyLinkIds.add(a):this.dirtyLinkIds.delete(a)}}}activityIsDirty(t,i){let r=this.activitiesAtLastSave.get(t);return i===null?r!==void 0:this.initialCalendarRepairIds.has(t)||!Zt(i.proplannerId)||r===void 0||sr(i,r.persistable)}linkIsDirty(t,i){let r=this.linksAtLastSave.get(t);return i===null?r!==void 0:!Zt(i.proplannerId)||r===void 0||Mn(r,i)}acknowledgePersistedLookahead(t,i){if(!this.trackingEnabled||!this.initialized)return;let r=t.map(n=>{let o=typeof n=="string"?n:String(n.id),a=i(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 r){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)||!Zt(s.proplannerId)||sr(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 i=[];for(let r of this.dirtyActivityIds){let n=t(r);n!==null&&!Zt(n.proplannerId)&&i.push(n)}return i}newLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let i=[];for(let r of this.dirtyLinkIds){let n=t(r);n!==null&&!Zt(n.proplannerId)&&i.push(n)}return i}deletedActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let i=[];for(let r of this.dirtyActivityIds){let n=this.activitiesAtLastSave.get(r);n&&t(r)===null&&i.push({...n.deletedSnapshot})}return i}deletedLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let i=[];for(let r of this.dirtyLinkIds){let n=this.linksAtLastSave.get(r);n&&t(r)===null&&i.push({...n})}return i}modifiedActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let i=[];for(let r of this.dirtyActivityIds){let n=t(r);if(n===null||!Zt(n.proplannerId))continue;let o=this.activitiesAtLastSave.get(r);(o===void 0||this.initialCalendarRepairIds.has(r)||sr(n,o.persistable))&&i.push(n)}return i}modifiedActivityFields(t){let i=new Map;if(!this.trackingEnabled||!this.initialized)return i;for(let r of this.dirtyActivityIds){let n=t(r),o=this.activitiesAtLastSave.get(r);if(!n||!o)continue;let a=Ua(n,o.persistable);a.length>0&&i.set(r,a)}return i}modifiedLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let i=[];for(let r of this.dirtyLinkIds){let n=t(r);if(n===null||!Zt(n.proplannerId))continue;let o=this.linksAtLastSave.get(r);(o===void 0||Mn(o,n))&&i.push(n)}return i}clear(){this.initialized=!1,this.dirtyActivityIds.clear(),this.dirtyLinkIds.clear(),this.initialCalendarRepairIds.clear(),this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear()}};var ku=1440*60*1e3,Ru=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/,Hn=7,Ha=[!1,!0,!0,!0,!0,!0,!1],Pu=new Set(["1","true"]),Ba=pt.DURATION,Lu=v.ASAP,Ou={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 Nu(e,t){let i=[],r=e.map(o=>{let a=AA(o,t);return o.should_be_showed===!1&&i.push(a.id),a});CA(r);let n=new Set(r.map(o=>o.id));return SA(r,n,t.reporter,t.recordDiagnostic),{activities:r,activityIds:n,hiddenIds:i}}function dA(e,t,i,r){if(!e)return null;let n=Ou[e.toUpperCase()];return n===void 0?(i(Nt.UNKNOWN_CONSTRAINT,r),t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),Lu):n}function uA(e,t,i){let r=dA(e.constraint,t,i,String(e.unique_id)),o=r!==v.ASAP&&r!==v.ALAP&&e.constraint_date?le(e.constraint_date):null;return{constraintType:r,constraintDate:o}}function fA(e,t,i){if(e==null)return i;let r=String(e);return t.has(r)?r:i}function pA(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 yA(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function Wa(e){if(!Array.isArray(e))return[];let t=[];for(let i of e)yA(i)&&t.push(String(i.id));return t}function hA(e){return e==="0"?null:String(e)}function mA(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 IA(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 gA(e,t,i,r,n){return Array.isArray(e)?e.map(o=>kn(o,t,{record:i,sampleId:r},n)).filter(o=>o!==null):[]}function AA(e,t){let i=fA(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),r=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),n=Number(e.progress),{constraintType:o,constraintDate:a}=uA(e,t.reporter,t.recordDiagnostic),s=e.type===T.MILESTONE,c=le(e.start_date),l=s?c:le(e.end_date),d=s?0:Number(e.duration),u=IA(e,t.reporter);return{id:String(e.unique_id),proplannerId:mA(e.id),parentId:hA(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:Me(d,t.hoursPerDay),constraintType:o,constraintDate:a,autoScheduling:we(n),calendarId:i,assignedDefaultCalendar:i!=null&&r,dateOrigin:e.date_origin==null?null:le(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:vA(e),subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:pA(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:Wa(e.pendingRequests),responsableIds:Wa(e.responsables),tagIds:Wa(e.tags),baselinePoints:gA(e.baseline_points,t.reporter,t.recordDiagnostic,String(e.unique_id),s),baselineSnapshot:null,recursiveDurationHours:Me(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),calendarDuration:te({type:e.type,startDate:c,endDate:l}),isCritical:u,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function vA(e){return e.has_childs?null:e.custom_id}function CA(e){let t=e.find(i=>i.correlativeId===0&&i.type===T.PROJECT);t&&(t.parentId=null)}function SA(e,t,i,r){for(let n of e)n.parentId!==null&&(t.has(n.parentId)||(i.warn(`[parseFromBackend] activity "${n.id}" references unknown parent "${n.parentId}" \u2014 re-parenting to root (null)`),r(Nt.ORPHAN_ACTIVITY,n.id),n.parentId=null))}function xu(e,t,i,r=null){let a=(e!==void 0&&e.length>0?e:t??[]).map(c=>DA(c,r)),s=(i??[]).map(c=>EA(c,r));return{calendars:a,baseCalendars:s,knownCalendarIds:new Set(a.map(c=>c.id)),defaultCalendarId:TA(a)}}function TA(e){let t=e.find(r=>r.is_default);if(t)return t.id;let i=e[0];return i?i.id:null}function Mu(e,t){let i=OA(e.working_days),{days:r,hours:n}=LA(e,i),o=_A(t.exceptionsSource,t.exceptionRange),a={days:r,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 DA(e,t){let i=e.baseDefault,r=typeof i=="boolean"?i:void 0;return Mu(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:r,exceptionsSource:e.exceptiondays,exceptionRange:t})}function EA(e,t){return Mu(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function _A(e,t){if(!Array.isArray(e)||e.length===0)return null;let i={};for(let r of e){if(!r)continue;let n=kA(r.from_date,r.to_date,t);if(n.length===0)continue;let o=RA(r);if(o!==void 0)for(let a of n)i[a]=o}return Object.keys(i).length>0?i:null}function kA(e,t,i){let r=bu(e),n=bu(t);if(r===null||n===null)return[];if(i&&(n<i.start||r>i.end))return[];let o=[],a=i?Math.max(r,i.start):r,s=i?Math.min(n,i.end):n;for(;a<=s;)o.push(String(a)),a+=ku;return o}function bu(e){if(typeof e!="string")return null;let t=Ru.exec(e.trim());if(!t)return null;let i=Number(t[1]),r=Number(t[2]),n=Number(t[3]);return Number.isFinite(i)&&Number.isFinite(r)&&Number.isFinite(n)?Date.UTC(i,r-1,n):null}function RA(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let i=PA(t);if(i.length>0)return i}}var Fu=/^\d{1,2}:\d{2}$/;function PA(e){let t=[];for(let i of e){let r=Bu(i?.shift_string);if(!r)continue;if(!r.startsCsv.includes(",")&&!r.endsCsv.includes(",")){let s=r.startsCsv.trim(),c=r.endsCsv.trim();!Bn(s)&&!Bn(c)&&Fu.test(s)&&Fu.test(c)&&t.push(`${s}-${c}`);continue}let a=Hu(r.startsCsv,r.endsCsv).find(s=>s!==null);a&&t.push(a)}return t.sort(Uu),t}function wu(e){let t=e.indexOf("-"),i=t>0?e.slice(0,t):e,[r,n]=i.split(":");return(Number(r)||0)*60+(Number(n)||0)}function Uu(e,t){return wu(e)-wu(t)}function LA(e,t){let i=Array.from({length:7},()=>[]),r=(l,d)=>{let u=Hu(l,d);for(let f=0;f<7;f+=1){let p=u[f],y=i[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=Bu(l?.shift_string);d&&r(d.startsCsv,d.endsCsv)}else o&&r(e.shift_start,e.shift_end);for(let l of i)l.sort(Uu);let s=i.find((l,d)=>!!t[d]&&l.length>0)??[];return{days:t.map((l,d)=>{if(!l)return!1;let u=i[d];return u&&u.length>0?u:s}),hours:s}}function Hu(e,t){let i=Array.from({length:Hn},()=>null);if(typeof e!="string"||typeof t!="string")return i;let r=e.split(",").map(s=>s.trim()),n=t.split(",").map(s=>s.trim());if(!(r.length===n.length&&r.length>0&&r.length<=Hn))return i;let a=[...i];for(let s=0;s<r.length;s+=1){let c=r[s],l=n[s];Bn(c)||Bn(l)||(a[s]=`${c}-${l}`)}return a}function Bu(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 OA(e){if(typeof e!="string")return[...Ha];let t=e.split(",").map(i=>i.trim());return t.length!==Hn?[...Ha]:t.map(i=>Pu.has(i))}var NA=new Set(["false","null"]);function Bn(e){return!e||NA.has(e)}function bA(e){if(typeof e!="string")return null;let t=Ws(e);return t||(yr(e)?e:null)}function FA(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 Vu(e,t){let i=[];for(let r of e)try{i.push(wA(r,t.knownActivityIds,t.hoursPerDay))}catch(n){t.recordDiagnostic(Nt.INVALID_LINK,String(r.unique_id??r.id)),t.reporter.warn("[parseFromBackend] dropping invalid link",n)}return xA(i,t.recordDiagnostic)}function wA(e,t,i){let r=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 "${r}" source "${n}" does not exist`);if(!t.has(o))throw new Error(`[parseFromBackend] link "${r}" target "${o}" does not exist`);let a=bA(e.type);if(a===null)throw new Error(`[parseFromBackend] link "${r}" has invalid type "${String(e.type)}"`);let s=e.ganttId,c=e.sectorId,l=FA(e.id);return{id:r,source:n,target:o,type:a,lag:Vt(Number(e.lag??0),i),freeSlackHours:null,isCritical:!1,...typeof s=="number"?{ganttId:s}:{},...typeof c=="number"?{sectorId:c}:{},...l===void 0?{}:{proplannerId:l}}}function xA(e,t){let i=new Map;for(let r of e){let n=`${r.source}-${r.target}-${r.type}`,o=i.get(n);if(!o){i.set(n,r);continue}let a=Wu(r)>Wu(o),s=a?o:r;t(Nt.DUPLICATE_LINK,s.id),a&&i.set(n,r)}return[...i.values()]}function Wu(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function MA(e){if(typeof e!="string")return Ba;switch(e.toUpperCase()){case pt.DURATION:return pt.DURATION;case pt.COST:return pt.COST;case pt.WORK_HOURS:return pt.WORK_HOURS;default:return Ba}}function UA(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function HA(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function ju(e){let t=UA(e),i=HA(e),r=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}:{},...i!==void 0?{customIdIncrement:i}:{},...r?{updateDurationForPrimaveraEndDate:!0}:{},activityCreter:MA(e.activity_creter),statusCriteria:_o,ganttId:null}}function Wn(e,t=ci,i=ki){let r=ju(e.sector),{calendars:n,baseCalendars:o,knownCalendarIds:a,defaultCalendarId:s}=xu(e.calendars,e.sector.calendars,e.baseCalendars,BA(e.activities)),{activities:c,activityIds:l,hiddenIds:d}=Nu(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t,recordDiagnostic:i}),u=Vu(e.links,{knownActivityIds:l,hoursPerDay:r.hoursPerDay,reporter:t,recordDiagnostic:i});return{sector:r,activities:c,links:u,calendars:n,baseCalendars:o,viewStateSeed:{hiddenIds:d}}}function BA(e){let t=Number.POSITIVE_INFINITY,i=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)&&(i=Math.max(i,s))}if(!Number.isFinite(t)||!Number.isFinite(i))return null;let r=new Date(t),n=new Date(i);return r.setFullYear(r.getFullYear()-1),n.setFullYear(n.getFullYear()+1),{start:r.getTime(),end:n.getTime()}}function Va(e={}){let t=e.seed??0,i=r=>{r>t&&(t=r)};if(e.knownIds)for(let r of e.knownIds){let n=typeof r=="number"?r:Number(r);Number.isFinite(n)&&i(n)}return{fork(){return Va({seed:t})},next(){return t+=1,String(t)},bump(r){let n=typeof r=="number"?r:Number(r);Number.isFinite(n)&&i(n)},snapshot(){return t},restore(r){t=r}}}function ja(e={}){let t=e.seed??0,i=r=>{r>t&&(t=r)};if(e.knownIds)for(let r of e.knownIds){let n=typeof r=="number"?r:Number(r);Number.isFinite(n)&&i(n)}return{fork(){return ja({seed:t})},next(){return t+=1,String(t)},bump(r){let n=typeof r=="number"?r:Number(r);Number.isFinite(n)&&i(n)},snapshot(){return t},restore(r){t=r}}}function Ka(e={}){let t=e.seed??0,i=r=>{Number.isFinite(r)&&r>0&&r<=9999999&&r>t&&(t=r)};if(e.knownIds)for(let r of e.knownIds){if(r==null)continue;let n=typeof r=="number"?r:Number(r);i(n)}return{fork(){return Ka({seed:t})},next(){return t+=1,String(t)},bump(r){if(r==null)return;let n=typeof r=="number"?r:Number(r);i(n)},snapshot(){return t},restore(r){t=r}}}function Ku(e){return!!e&&typeof e=="string"&&e.trim().length>0}function Vn(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function jn(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function Yu(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function Gu(e,t){return!t&&Ku(e)}function $u(e,t){return t&&Ku(e)}function cr(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function Kn(e){if(!cr(e))return 0n;try{return BigInt(e)}catch{return 0n}}function WA(e,t){if(typeof e!="bigint")return"";let i=e.toString();if(!cr(t))return i;let r=t.length;return i.padStart(r,"0")}function Yt(e,t){let i=Kn(e),r=Kn(t),n=i+r;return WA(n,e)}function Yn(e,t){let i=Kn(e),r=Kn(t);return i<r?-1:i>r?1:0}function Gn(e,t){return Yn(e,t)<=0?e:t}function $n(e,t){return Yn(e,t)>=0?e:t}function zu(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,i)=>Gn(t,i))}function qu(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,i)=>$n(t,i))}var ue={PARENT_CONVERSION:"parentConversion",PASTE_REFERENCE:"pasteReference",NO_CONTEXT:"noContext"};function Ju(e){return{prefix:e,baseSuffix:null}}function Xu(e,t){let i=jn(e);return{prefix:Vn(e),baseSuffix:Yt(i,t)}}function Zu(e){return{prefix:e,baseSuffix:null}}function Qu(e,t){return Gu(e,t)?ue.PARENT_CONVERSION:$u(e,t)?ue.PASTE_REFERENCE:ue.NO_CONTEXT}function tf(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var zn=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,i=this._journalIds;if(!(t===null||i===null)){for(let[r,n]of t)n===null?this.prefixMap.delete(r):this.prefixMap.set(r,n);for(let r of[...i].reverse())r.hadId?this.processedIds.add(r.customId):this.processedIds.delete(r.customId);this._journalPrefixBefore=null,this._journalIds=null}}_noteCustomIdBefore(t){if(this._journalPrefixBefore===null||this._journalIds===null)return;let{prefix:i}=this.analyzeCustomId(t);if(!this._journalPrefixBefore.has(i)){let r=this.prefixMap.get(i);this._journalPrefixBefore.set(i,r?tf(r):null)}this._journalIds.push({customId:t,hadId:this.processedIds.has(t)})}_ensureFreshBounds(t){let i=this.prefixMap.get(t);if(!i?.boundsDirty)return;i.boundsDirty=!1;let r=Array.from(i.usedSuffixes);i.min=zu(r),i.max=qu(r),i.quantity=r.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[i,r]of this.prefixMap)t.prefixMap.set(i,tf(r));for(let i of this.processedIds)t.processedIds.add(i);return t}extractPrefix(t){return Vn(t)}extractSuffix(t){return jn(t)}analyzeCustomId(t){return{prefix:this.extractPrefix(t),suffix:this.extractSuffix(t)}}_updatePrefixStats(t,i){if(this._ensureFreshBounds(t),!this.prefixMap.has(t)){this.prefixMap.set(t,{min:i,max:i,next:i,quantity:1,usedSuffixes:new Set([i])}),this._recalculateNext(t);return}let r=this.prefixMap.get(t);r.usedSuffixes.has(i)||(r.usedSuffixes.add(i),r.min=Gn(i,r.min),r.max=$n(i,r.max),r.quantity+=1,this._recalculateNext(t))}_recalculateNext(t){let i=this.prefixMap.get(t);if(!i)return;let r=this.getNextAvailableSuffix(t);i.next=r??this.suffixIncrement}getPrefixStats(t){this._ensureFreshBounds(t);let i=this.prefixMap.get(t);return i?{min:i.min,max:i.max,next:i.next,quantity:i.quantity}:null}getNextSuffix(t){this._ensureFreshBounds(t);let i=this.prefixMap.get(t);return i?i.next:this.suffixIncrement}getAllPrefixes(){return Array.from(this.prefixMap.keys())}registerCustomId(t){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:i,suffix:r}=this.analyzeCustomId(t);if(!i&&!r)return{prefix:i,suffix:r};if(this._noteCustomIdBefore(t),this._ensureFreshBounds(i),this.prefixMap.has(i)){let n=this.prefixMap.get(i);n.usedSuffixes.has(r)||(n.usedSuffixes.add(r),n.min=Gn(r,n.min),n.max=$n(r,n.max),n.quantity+=1,this._recalculateNext(i))}else this.prefixMap.set(i,{min:r,max:r,next:Yt(r,this.suffixIncrement),quantity:1,usedSuffixes:new Set([r])});return this.processedIds.add(t),{prefix:i,suffix:r}}releaseCustomId(t=null){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:i,suffix:r}=this.analyzeCustomId(t);if(!this.prefixMap.has(i))return{prefix:i,suffix:r};this._noteCustomIdBefore(t);let n=this.prefixMap.get(i);return n.usedSuffixes.has(r)&&(n.usedSuffixes.delete(r),n.quantity-=1,n.usedSuffixes.size===0?this.prefixMap.delete(i):n.boundsDirty=!0),this.processedIds.delete(t),{prefix:i,suffix:r}}trackCustomIdChange(t,i){let r=this.releaseCustomId(t),n=this.registerCustomId(i);return{oldPrefix:r.prefix,oldSuffix:r.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 i=this.prefixMap.get(t);return`${t}${Yt(i.max,this.suffixIncrement)}`.length>20}_suffixForUnknownPrefix(t,i){let r=i&&cr(i)?i:this.suffixIncrement;return`${t}${r}`.length>20?null:r}_findFirstAvailableGap(t){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return null;let i=this.prefixMap.get(t),r=this.suffixIncrement;for(;Yn(r,i.max)<0;){if(`${t}${r}`.length>20)return null;if(!i.usedSuffixes.has(r))return r;r=Yt(r,this.suffixIncrement)}return null}_generateDefaultCustomId(){let t=this.getNextAvailableSuffix(this.defaultPrefix);if(t===null){if(this._shouldSearchForGaps(this.defaultPrefix)){let i=this._findFirstAvailableGap(this.defaultPrefix);if(i!==null)return`${this.defaultPrefix}${i}`}return`${this.defaultPrefix}${this.suffixIncrement}`}return`${this.defaultPrefix}${t}`}getNextAvailableSuffix(t,i=null){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return this._suffixForUnknownPrefix(t,i);let r=this.prefixMap.get(t),n=this.suffixIncrement;if(!i||!cr(i)){let s=Yt(r.max,n);return`${t}${s}`.length>20?null:s}let o=i;for(let s=0;s<100;s++){if(`${t}${o}`.length>20)return null;if(!r.usedSuffixes.has(o))return o;o=Yt(o,n)}let a=Yt(r.max,n);return`${t}${a}`.length>20?null:a}generateNextCustomId(t){let i=this.getNextAvailableSuffix(t);if(i===null)return this._generateDefaultCustomId();if(this.prefixMap.has(t)){let n=this.prefixMap.get(t),o=0;for(;n.usedSuffixes.has(i)&&o<1e4;){let a=this.getNextAvailableSuffix(t,Yt(i,this.suffixIncrement));if(a===null)return this._generateDefaultCustomId();i=a,o++}}let r=`${t}${i}`;return this._exceedsMaxLength(r)&&(r=this._generateDefaultCustomId()),r}populateFromActivities(t){if(!Array.isArray(t))return this;let i=[...new Set(t.filter(r=>r&&typeof r.customId=="string"&&r.customId).map(r=>r.customId))];for(let r of i){if(this.processedIds.has(r))continue;let{prefix:n,suffix:o}=this.analyzeCustomId(r);(n||o)&&(this._updatePrefixStats(n,o),this.processedIds.add(r))}return this}getDefaults(){return{prefix:this.defaultPrefix,increment:this.suffixIncrement}}generateCustomIdForNewChild(t){let{activity:i,useActivityCustomIdAsReference:r=!1}=t,n=Yu(i),o=Qu(n,r),{prefix:a,baseSuffix:s}=this._applyGenerationStrategy(o,n),c=null;if(o===ue.PARENT_CONVERSION&&this.prefixMap.has(a)){this._ensureFreshBounds(a);let f=this.prefixMap.get(a).max;c=Yt(f,this.suffixIncrement)}o===ue.PARENT_CONVERSION&&this.releaseCustomId(n);let l=o===ue.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,i){switch(t){case ue.PARENT_CONVERSION:return Ju(this.defaultPrefix);case ue.PASTE_REFERENCE:return Xu(i,this.suffixIncrement);default:return Zu(this.defaultPrefix)}}generateCustomIdForRestoredChild(t=null){if(t){let r=t.trim();if(r.length>0){let n=this.extractPrefix(r),o=this.extractSuffix(r),a=Yt(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 i=this.generateNextCustomId(this.defaultPrefix);return this.registerCustomId(i),i}clear(){this.prefixMap.clear(),this.processedIds.clear()}getTotalPrefixes(){return this.prefixMap.size}hasPrefix(t){return this.prefixMap.has(t)}isCustomIdInUse(t,i=null){if(!t||typeof t!="string"||!t.trim())return!1;let r=t.trim();return i&&r===i.trim()?!1:this.processedIds.has(r)}};var VA=1,jA=-1;function KA(e,t){return!e&&!t?null:e&&t?0:e?VA:jA}function ef(e){return e==null}function rf(e,t){let i=t.indexOf(String(e));return i===-1?t.length:i}function YA(e,t,i){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),i,{sensitivity:"base",numeric:!0})}function GA(e,t){let i=ye(e.field);return i===null?null:(r,n)=>{let o=i.extract(r,t),a=i.extract(n,t),s=KA(ef(o),ef(a));if(s!==null)return s;let c=i.valueKind===O.ENUM?rf(o,i.order)-rf(a,i.order):YA(o,a,t.locale);return e.direction===Fe.DESCENDING?-c:c}}function nf(e,t){let i=e.rules.map(r=>GA(r,t)).filter(r=>r!==null);return i.length===0?null:(r,n)=>{for(let o of i){let a=o(r,n);if(a!==0)return a}return 0}}function of(e){let t=[];e.forEachActivity((i,r)=>{i.type===T.PROJECT&&e.getChildren(String(r)).length===0&&t.push(String(r))});for(let i of t)e.setActivityField(i,b.TYPE,ai),$A(e,i)}function $A(e,t){let i=e.getActivity(t);if(!i||!i.startDate||i.durationHours==null)return;let r=new Date(i.startDate);r.setUTCHours(0,0,0,0);let n=e.getClosestWorkTime({date:r,dir:j.FUTURE,task:i});if(n.getTime()===i.startDate.getTime())return;let o=e.calculateEndDate({startDate:n,durationHours:i.durationHours,task:i});e.setActivityField(t,b.START_DATE,n),e.setActivityField(t,b.END_DATE,o)}function af(e){let t=[],i=[];e.forEachActivity((n,o)=>{n.parentId===null&&t.push(String(o))});let r=n=>{let o=e.getActivity(n);if(!o)return 0;let a=[...e.getChildren(n)],s=a.length===0?xt(o.workHours,o.progress):a.reduce((c,l)=>c+r(String(l)),0);return e.setActivityField(n,b.REAL_WORK_HOURS,s),i.push(n),s};for(let n of t)r(n);return i}async function sf(e){let{state:t,sector:i,scheduler:r,skipAutoSchedule:n,now:o}=e;if(_t(t),i.updateDurationForPrimaveraEndDate&&qA(t),JA(t),af(t),n){Ki(t),o&&(je(t,o),de(t,i.statusCriteria));return}let a=await r.schedule({});Wi(t,a),XA(t),zA(t),await di(t,void 0,!1),Ki(t),o&&(je(t,o),de(t,i.statusCriteria))}function zA(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=te(t))})}function qA(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function JA(e){e.forEachActivity(t=>{let i=t.constraintType;if(!i||!t.constraintDate)return;let r=t.constraintDate;if(t.type===T.MILESTONE&&(r.getUTCHours()!==0||r.getUTCMinutes()!==0))return;let n=e.calendarReader.getCalendar(String(t.calendarId));n&&(t.constraintDate=se(t.constraintDate,n,i))})}function XA(e){e.forEachActivity(t=>{if(t.type!==T.MILESTONE)return;let i=t.constraintType;if(!i||!t.constraintDate)return;let r=e.calendarReader.getCalendar(String(t.calendarId));r&&(t.constraintDate=se(t.constraintDate,r,i))})}var Qt={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function cf(e){let t=e.clock??null,i=t?.()??null,r=i?Yr(i):null,n=e.reporter??ci,o=ld(),a=Wn({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},n,o.record),s=a.sector;s.statusCriteria=rn(e.statusCriteria),s.ganttId=e.ganttId??null;let c=a.calendars,l=a.baseCalendars??[],d=xn(a.activities,a.links,a.calendars,l),u=F=>nf(F,be(s.hoursPerDay)),f=new Pi(d,u);f.hydrateViewState({hiddenIds:a.viewStateSeed.hiddenIds});let p=new li(f,n);of(f);let y=Va({knownIds:a.activities.map(F=>F.id)}),g=ja({seed:i?.getTime()??0,knownIds:a.links.map(F=>F.id)}),A=Ka({knownIds:a.activities.map(F=>F.uniqueCorrelativeId)}),k=new zn({defaultPrefix:s.customIdPrefix,suffixIncrement:s.customIdIncrement});if(k.populateFromActivities(a.activities),e.baselinePoints&&e.baselinePoints.length>0){let F=l.find(m=>m.baseDefault)?.id??null;Rn(f,e.baselinePoints,r,n,F,o.record)}let _=sf({state:f,sector:s,scheduler:p,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:r??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 Oi(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(Oi)];if(e instanceof Map)return["map",Array.from(e,([t,i])=>[Oi(t),Oi(i)]).sort((t,i)=>JSON.stringify(t).localeCompare(JSON.stringify(i)))];if(e instanceof Set)return["set",Array.from(e,Oi).sort((t,i)=>JSON.stringify(t).localeCompare(JSON.stringify(i)))];if(typeof e=="object")return["object",Object.entries(e).sort(([t],[i])=>t.localeCompare(i)).map(([t,i])=>[t,Oi(i)])];throw new TypeError(`Unsupported canonical value: ${typeof e}`)}function Ze(e){return JSON.stringify(Oi(e))}function Ya(e,t){let i=new Map(e.map(a=>[String(a.id),a])),r=new Map(t.map(a=>[String(a.id),a])),n=[...new Set([...i.keys(),...r.keys()])].sort(),o=[];for(let a of n){let s=r.get(a),c=i.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:w(c)});continue}let l=ZA(s,c);Object.keys(l).length>0&&o.push({id:a,kind:N.UPDATED,fields:l,after:w(c)})}return o}function ZA(e,t){let i={},r=[...new Set([...Object.keys(e),...Object.keys(t)])].sort();for(let n of r)Ze(e[n])!==Ze(t[n])&&(i[n]={before:w(e[n]),after:w(t[n])});return i}function QA(e,t){let i=new Set(t.selectedIds.map(String)),r=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=i.has(c),d=r.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 Ga(e,t){let i=Ze(e.order)!==Ze(t.order);return{source:{kind:ee.INIT},activities:Ya(e.activities,t.activities),links:Ya(e.links,t.links),calendars:Ya(e.calendars,t.calendars),trackingEvents:[],effects:[],viewState:QA(e,t),...i?{order:w(e.order)}:{}}}var Ni={MOVE:"move",RESIZE_START:"resize-start",RESIZE_END:"resize-end"},tv=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),$a=(e,t)=>e===null?t:Math.min(e,t),za=(e,t)=>e===null?t:Math.max(e,t);function df(e,t,i){let r=[...new Set(t.kind===Ni.MOVE?t.activityIds.map(String):[String(t.activityId)])];if(r.length===0)throw new Error("[ScheduleCore] date gesture has no participants");let n=ev(e,t,r);return iv(e,r,n),{getDates(o,a){if(i(),!Number.isFinite(a))throw new Error("[ScheduleCore] invalid date gesture edge");let s=n.get(String(o));if(!s)return null;let c=nv(s,a),l=ov(s,a);if(c===null||l===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(o)}`);return{startTimeMs:c,endTimeMs:l}}}}function ev(e,t,i){let r=new Map,n=t.kind===Ni.MOVE?String(t.anchorActivityId):null,o=n===null?null:lf(e,n);if(n!==null&&!i.includes(n))throw new Error("[ScheduleCore] move anchor is not a participant");for(let a of i){let s=lf(e,a);if(t.kind===Ni.MOVE){let c=o.startDate.getTime();r.set(a,{constantStart:null,variableStartOffset:s.startDate.getTime()-c,constantEnd:null,variableEndOffset:s.endDate.getTime()-c})}else t.kind===Ni.RESIZE_START?r.set(a,{constantStart:null,variableStartOffset:0,constantEnd:s.endDate.getTime(),variableEndOffset:null}):r.set(a,{constantStart:s.startDate.getTime(),variableStartOffset:null,constantEnd:null,variableEndOffset:0})}return r}function iv(e,t,i){let r=Gi(e,new Set(t));for(let n of r){let o=tv();for(let a of e.getChildren(n)){let s=i.get(a);if(s){rv(o,s);continue}let c=e.getActivity(a);if(!c)throw new Error(`[ScheduleCore] missing child ${a} while previewing parent ${n}`);o.constantStart=$a(o.constantStart,c.startDate.getTime()),o.constantEnd=za(o.constantEnd,c.endDate.getTime())}i.set(n,o)}}function lf(e,t){let i=e.getActivity(t);if(!i)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 i}function rv(e,t){t.constantStart!==null&&(e.constantStart=$a(e.constantStart,t.constantStart)),t.variableStartOffset!==null&&(e.variableStartOffset=$a(e.variableStartOffset,t.variableStartOffset)),t.constantEnd!==null&&(e.constantEnd=za(e.constantEnd,t.constantEnd)),t.variableEndOffset!==null&&(e.variableEndOffset=za(e.variableEndOffset,t.variableEndOffset))}function nv(e,t){if(e.variableStartOffset===null)return e.constantStart;let i=t+e.variableStartOffset;return e.constantStart===null?i:Math.min(e.constantStart,i)}function ov(e,t){if(e.variableEndOffset===null)return e.constantEnd;let i=t+e.variableEndOffset;return e.constantEnd===null?i:Math.max(e.constantEnd,i)}var qa=Symbol("ScheduleCore.fork.source");function av(e){return{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}function sv(e){return e.kind===I.PERSISTENCE_ACKNOWLEDGE||e.kind===I.ACTIVITY_LOOKAHEAD_SYNC&&e.acknowledgePersistedLookahead===!0}function cv(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 lv(e,t){let i=[];for(let r of e.activities){let n=t.getActivity(r.id);if(n===null)return null;i.push(n)}return i}function dv(e,t,i){if(e===null||e.filter!==t)return!1;let r=e.context.hoursPerDay===i.hoursPerDay,n=e.context.locale===i.locale;return r&&n}var bi=class e{activities;links;calendars;selection;view;baselines;impactRequests;persistence;history;projection;criticalPath;diagnostics;_activityClipboard={value:null};_status=Qt.READY;coreRuntime;_isFork;_undo=new wn;_opQueue=Promise.resolve();_scheduleRevision=0;_stateRevision=0;_pendingScheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){if(Object.assign(this,es(this)),qa in t){this._isFork=!0;let n=t[qa],o=n.coreRuntime.state.fork();this.coreRuntime={state:o,scheduler:new li(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 i=cf(t);this.coreRuntime={state:i.state,scheduler:i.scheduler,sector:i.sector,activityIdGenerator:i.activityIdGen,linkIdGenerator:i.linkIdGen,uniqueCorrelativeIdGenerator:i.uidGen,customIdTracker:i.customIdTracker,clock:i.clock,calendars:new Map(i.calendars.map(n=>[n.id,n])),baseCalendars:i.baseCalendars,reporter:i.reporter,loadDiagnostics:i.loadDiagnostics},this._initPromise=i.initPromise.then(()=>{this._status!==Qt.DESTROYED&&this._saveTracker.init(this.coreRuntime.state.getAllActivities(),this.getAllLinksView())}),this._criticalPathReady=this._initPromise.then(()=>this._startCriticalPathForCurrentRevision());let r=t.criticalPathOnLoad===!0;this._ready=r?this._criticalPathReady.then(()=>{}):this._initPromise}get ready(){return this._ready}fork(){return this._enqueue(async()=>(await this._ready,this.assertReady(),new e({[qa]: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(),La(this.coreRuntime.state,t)}calculateCalendarEndDate(t){this.assertReady();let i=this.coreRuntime.state.getActivity(t.activityId);return i?this.coreRuntime.state.calculateEndDate({startDate:t.startDate,durationHours:t.durationHours,task:i}):null}calculateCalendarDuration(t){this.assertReady();let i=this.coreRuntime.state.getActivity(t.activityId);return i?this.coreRuntime.state.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:i}):null}getClosestCalendarWorkTime(t){this.assertReady();let i=this.coreRuntime.state.getActivity(t.activityId);return i?this.coreRuntime.state.getClosestWorkTime({date:t.date,dir:t.direction,task:i}):null}getProgressEditability(t){this.assertReady();let i=La(this.coreRuntime.state,t);if(!i)return null;let r=ba(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat});return $r.canEdit(i,r.hierarchy)}createDateGesturePreview(t){this.assertReady();let i=this._scheduleRevision;return df(this.coreRuntime.state,t,()=>{if(this.assertReady(),this._scheduleRevision!==i)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),qd(this.coreRuntime.state)}getIndentTargetParentIds(t){this.assertReady();let i=_n(t.map(r=>String(r)),this.coreRuntime.state);return[...new Set(i.allowedMoves.map(r=>String(r.newParentId)))]}getChildrenView(t){return this.assertReady(),Zd(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),Na(this.coreRuntime.state,t)}getLinksForActivityView(t){this.assertReady();let i=this.coreRuntime.state,r=[],n=new Set,o=a=>{if(n.has(a))return;n.add(a);let s=Na(i,a);s&&r.push(s)};for(let a of i.getOutgoingLinkIds(t))o(a);for(let a of i.getIncomingLinkIds(t))o(a);return r}getAllLinksView(){return this.assertReady(),eu(this.coreRuntime.state)}auditEffectiveGraph(){this.assertReady();let t=this.coreRuntime.state,i=t.getAllLinks(),r=ji(t,i),n=Lr(r),o=0;for(let a of n)a.length>o&&(o=a.length);return{activityCount:t.getAllIds().length,logicalLinkCount:i.length,effectiveEdgeCount:r.length,circularComponents:n,largestComponentSize:o}}getProperty(t,i){this.assertReady();let r=this.coreRuntime.state.getActivity(t);return r?w(r[i]):null}getAllIds(){return this.assertReady(),Jd(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),Xd(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),Oa(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),Qd(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(i=>!t.has(i))}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()]}hasChild(t){return this.assertReady(),tu(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let i=this.coreRuntime.calendars.get(t);return i?w(i):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,i=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,i)}getProjectWorkHours(){return this.assertReady(),iu(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=(i,r)=>String(i.id).localeCompare(String(r.id));return Ze({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(),Ga(this._snapshotProjection(),t._snapshotProjection())}_snapshotProjection(){return{activities:this.getAllActivitiesView(),links:this.getAllLinksView(),calendars:this.getAllCalendars(),selectedIds:this.getSelectedActivityIds(),hiddenIds:this.getHiddenActivityIds(),order:oi(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 i=this._opQueue.then(t,t);return this._opQueue=i.then(()=>{},()=>{}),i}_beginScheduleMutation(t){return ln(t)?this._admitScheduleMutation():!1}_admitScheduleMutation(){return this._pendingScheduleRevision++,this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),!0}_settleScheduleMutation(t,i){t&&(i||(this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision-1,this._scheduleRevision),this._pendingScheduleRevision===this._scheduleRevision&&this._criticalPathRevision!==this._scheduleRevision&&this.recomputeCriticalPath().catch(r=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path re-arm after a barren mutation failed",r)})))}async dispatch(t,i={}){let r=this._beginScheduleMutation(t);return this._enqueue(()=>this._dispatchInner(t,i,r))}async dispatchMany(t,i={}){let r=t.some(ln)?this._admitScheduleMutation():!1;return this._enqueue(()=>this._dispatchManyInner(t,i,r))}async applyActivityBatch(t,i={}){let r=this._beginScheduleMutation(t);return this._enqueue(()=>this._dispatchInner(t,i,r))}planLookaheadConversion(t){return this.assertReady(),ua(t,{adapter:this.coreRuntime.state,stateRevision:this._stateRevision})}applyLookaheadConversion(t){return this.dispatch({...t,kind:I.ACTIVITY_LOOKAHEAD_CONVERT})}async _dispatchInner(t,i={},r=!1){let n=!1;try{let o=await this._runDispatch(t,i);return n=o.changedState,o.result}finally{this._settleScheduleMutation(r,n)}}async _dispatchManyInner(t,i,r){let n=this._snapshotProjection(),o={...i,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===I.SCHEDULE_AUTO_SCHEDULE){if(A.activityId!==void 0&&!this.coreRuntime.state.activityExists(A.activityId)){a.push({ok:!1,reason:S.ACTIVITY_NOT_FOUND});continue}let _=av(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:I.SCHEDULE_AUTO_SCHEDULE}:{kind:I.SCHEDULE_AUTO_SCHEDULE,activityId:u},k=await this._runDispatch(A,i,!0);k.result.ok&&(p=k.result.changes,s.push(k.result.changes),y=i.skipAutoSchedule!==!0),l||=k.changedState}return l&&this._recordScheduleMutation(p!==null&&i.skipAutoSchedule!==!0&&i.skipCriticalPath!==!0),g=!0,{results:a,autoScheduled:y,changeSet:this._aggregateDispatchManyChangeSets(n,s,c)}}finally{!g&&l&&this._recordScheduleMutation(!1),this._settleScheduleMutation(r,g&&l)}}_aggregateDispatchManyChangeSets(t,i,r){if(i.length===0)return null;let n=Ga(this._snapshotProjection(),t),o=i.flatMap(s=>s.effects??[]),a=i.flatMap(s=>s.warnings??[]);return{...n,source:{kind:ee.DISPATCH_MANY,actions:r},trackingEvents:i.flatMap(s=>s.trackingEvents),...o.length===0?{}:{effects:o},...a.length===0?{}:{warnings:a}}}async _runDispatch(t,i,r=!1){if(this.assertReady(),this._isFork&&sv(t))return{result:{ok:!1,reason:S.SANDBOX_PERSISTENCE_FORBIDDEN},changedState:!1};let n=ba(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat}),o=fu(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 Ed(t,i,{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?Yr(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===Li.RECORD&&Ma(s.changes)){let d=cu(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(Fa(su(s.changes),s.__beforeSnap,s.__beforeLinks,d.afterSnap,d.afterLinks,c,u),lu(t),Date.now())}if(s.ok)if(o===Li.CHECKPOINT_ON_SUCCESS){if(t.kind!==I.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===I.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=Ma(s.changes);return l&&this._stateRevision++,ln(t)&&l?(r||this._recordScheduleMutation(i.skipAutoSchedule!==!0&&i.skipCriticalPath!==!0&&$e(t)),{result:uf(s),changedState:!0}):{result:uf(s),changedState:!1}}recomputeCriticalPath(){let t=this._enqueue(async()=>({job:this._startCriticalPathForCurrentRevision()})).then(({job:i})=>i);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,i){if(!i.ok||(t.kind===I.VISIBILITY_SET&&this.coreRuntime.state.setFilterProjection(null),!dl(t)))return i;let r=this._reapplyViewState(i.changes);return r===null?i:{...i,changes:r}}_reapplyViewState(t){let i=this._reapplyActiveFilter(t),r=this._emitTouchedBranchOrder(i??t);return this._reapplyActiveOrder(r.changes??i??t,r.touchedParents)??r.changes??i}_emitTouchedBranchOrder(t){let i=this.coreRuntime.state,r=Iu(t,o=>i.getParentId(o));if(i.getActiveOrder()!==null)return{changes:null,touchedParents:r};if(r.size===0)return{changes:null,touchedParents:r};let n=oo(i,r);return n.length===0?{changes:null,touchedParents:r}:{changes:{...t,order:n},touchedParents:r}}_reapplyActiveOrder(t,i){let r=this.coreRuntime.state;if(r.getActiveOrder()===null)return null;if(r.invalidateDerivedOrder(),t.links.length>0||t.calendars.length>0)return{...t,order:oi(r)};let o=new Set(i);for(let s of t.activities){if(s.kind===N.DELETED)return{...t,order:oi(r)};let c=r.getParentId(s.id);o.add(c===null?"0":String(c))}let a=oo(r,o);return a.length===0?null:{...t,order:a}}_reapplyActiveFilter(t){let i=this.coreRuntime.state,r=i.getActiveFilter();if(r===null)return null;let n=be(this.coreRuntime.sector.hoursPerDay),o=i.getFilterProjection(),a=dv(o,r,n),s=cv(t)?null:lv(t,i),c,l;if(s===null||!a){let f=gr({activities:i.getAllActivities(),parentOf:p=>i.getParentId(p),filter:r,context:n});i.setFilterProjection(f),l=f.visibleIds,c=i.getAllIds()}else c=us(o,s,f=>i.getParentId(f)),l=o.visibleIds;let u=ni(i,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===Qt.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 i={cancelled:!1},r=new Pi(xn(this.coreRuntime.state.getAllActivities().map(s=>nt(s)),this.coreRuntime.state.getAllLinks().map(s=>({...s})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),n=()=>!i.cancelled&&this._status!==Qt.DESTROYED&&this._scheduleRevision===t&&this._pendingScheduleRevision===this._scheduleRevision,o=(async()=>{let s=await Xo(r,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)qo(this.coreRuntime.state,l,d);for(let[l,d]of s.links)Jo(this.coreRuntime.state,l,d);c=await $(this.coreRuntime.state,{source:{kind:ee.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:i,promise:o};let a=()=>{this._activeCriticalPath?.promise===o&&(this._activeCriticalPath=null)};return o.then(a,a),o}undo(t={}){let i=this._admitScheduleMutation(),r=!1,n=this._enqueue(async()=>{try{return await this._runUndo(t,o=>{r=o})}finally{this._settleScheduleMutation(i,r)}});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,i){{if(this.assertReady(),t.expectedUndoDepth!==void 0&&this._undo.undoDepth()!==t.expectedUndoDepth)return null;let r=this._undo.takeUndo();if(!r)return null;pu(this.coreRuntime.state,r),this._recordScheduleMutation(!1),i(!0),wa(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(r),this._undo.resetCoalesce();let n=xa(this.coreRuntime.state,r,dt.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 i=this._admitScheduleMutation(),r=!1,n=this._enqueue(async()=>{try{return await this._runRedo(o=>{r=o})}finally{this._settleScheduleMutation(i,r)}});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 i=this._undo.takeRedo();if(!i)return null;yu(this.coreRuntime.state,i),this._recordScheduleMutation(!1),t(!0),wa(i)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(i),this._undo.resetCoalesce();let r=xa(this.coreRuntime.state,i,dt.AFTER);return this._saveTracker.recordChanges(r.activities,r.links,n=>this.coreRuntime.state.getActivity(n),n=>this.coreRuntime.state.getLink(n)),this._reapplyViewState(r)??r}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=Qt.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new Un;assertReady(){if(this._status===Qt.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===Qt.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(i){throw this._status=Qt.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",i),i}}};function uf(e){let{__beforeSnap:t,__beforeLinks:i,...r}=e;return r}async function ff(e){let t=new bi(e);return await t.ready,t}var pf=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var yf={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 hf=8;var mf={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return Tf(uv);})();
1
+ "use strict";var ScheduleCore=(()=>{var qn=Object.defineProperty;var gf=Object.getOwnPropertyDescriptor;var Af=Object.getOwnPropertyNames;var vf=Object.prototype.hasOwnProperty;var Cf=(e,t)=>{for(var i in t)qn(e,i,{get:t[i],enumerable:!0})},Sf=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Af(t))!vf.call(e,n)&&n!==i&&qn(e,n,{get:()=>t[n],enumerable:!(r=gf(t,n))||r.enumerable});return e};var Tf=e=>Sf(qn({},"__esModule",{value:!0}),e);var dv={};Cf(dv,{ACTIVITY_BATCH_ACTION_KIND:()=>pe,ACTIVITY_BATCH_MODE:()=>mt,ACTIVITY_DATE_EDGE:()=>xi,ACTIVITY_FIELD:()=>At,ACTIVITY_PONDERATOR_CRITERION:()=>pt,ACTIVITY_PROGRESS_ORIGIN:()=>Jr,ACTIVITY_TYPE:()=>D,CALENDAR_UNIT:()=>ut,CHANGE_SET_SOURCE_KIND:()=>ee,COLUMN:()=>E,COMPLETED_PROGRESS:()=>Bi,CONSTRAINT_TYPE:()=>v,CONSTRAINT_TYPE_TO_LABEL:()=>yf,CONSTRAINT_WARNING_KIND:()=>We,CREATION_KIND:()=>mf,DATE_GESTURE_KIND:()=>Ni,DEFAULT_HOURS_PER_DAY:()=>hf,DISPATCH_ACTION_KIND:()=>I,DISPATCH_ACTION_KINDS:()=>ts,DISPATCH_LINK_OPERATION_KIND:()=>ot,DISPATCH_TRACK_EVENT:()=>Kt,EDIT_ALERT_KEY:()=>sc,EDIT_DENIAL_REASON:()=>zi,ENTITY_CHANGE_KIND:()=>N,FILTER_FIELD:()=>z,FILTER_LOGIC:()=>Ir,FILTER_OPERATOR:()=>W,FILTER_REJECTION_REASON:()=>Tt,FILTER_VALUE_KIND:()=>O,LINK_BATCH_OPERATION_KIND:()=>ii,LINK_CODE:()=>Dt,LINK_CODE_TO_TYPE:()=>xe,LINK_REJECTION_REASON:()=>st,LINK_RELATIONSHIP:()=>Ne,LINK_TYPE:()=>B,LINK_TYPE_CODE:()=>Fr,NEW_ACTIVITY_DEFAULTS:()=>gn,NOT_STARTED_PROGRESS:()=>Rs,ORDER_DIRECTION:()=>Fe,REJECTION_REASON:()=>S,ROOT_PARENT_ID:()=>V,SCHEDULE_CORE_STATUS:()=>Qt,SCHEDULE_EFFECT_KIND:()=>Xr,SIR_AUTO_REJECT_REASON:()=>Zr,STATUS:()=>Pt,STATUS_CRITERIA:()=>fe,ScheduleCore:()=>bi,WORK_TIME_DIRECTION:()=>Y,checkNoUpdatedLinks:()=>Eu,computeExpectedProgress:()=>Eo,createSchedule:()=>ff,expectedProgressFromBaseline:()=>mi,getActiveBaseline:()=>gt,getUnsavedActivities:()=>pf,isRootParent:()=>U,normalizeParentKey:()=>$t,parseFromBackend:()=>Wn,willRunCriticalPath:()=>ru,yieldToBrowser:()=>ct});var D={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},Df=Object.values(D);function Fi(e){return Df.includes(e)}var dr={CONSTRAINT:"constraint",ALERT:"alert",WARNING:"warning"},Y={FUTURE:"future",PAST:"past"},ut={HOUR:"hour",DAY:"day"},pt={DURATION:"DURATION",COST:"COST",WORK_HOURS:"HH"},fe={BASELINE:"Baseline",ACTUAL:"Actual"},Pt={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"},Ef={[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 fr(e,t,i){if(!t)return{violated:!1};let r=Ef[e];return r?r(t,i)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var _f=new Set([v.MSO,v.SNET,v.SNLT]);function Oe(e,t,i){return _f.has(e)?t:i}function pr(e,t,i){return{type:dr.CONSTRAINT,messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...i?{projectedDate:i}:{}}}}var kf={[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}},ur=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),Xa=(e,t)=>new Date(e.getTime()+t*864e5),Rf=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function wi(e,t){if(!e.constraintDate||!e.constraintType)return null;let i=kf[e.constraintType];if(!i)return e.constraintDate;let r=e.constraintDate,n=t.getClosestWorkTime({date:ur(r),dir:Y.FUTURE,task:e});if(Rf(n,r))return r.getTime()!==ur(r).getTime()?r:i.startOfDay?n:t.getClosestWorkTime({date:Xa(ur(r),1),dir:Y.PAST,task:e});let o=ur(t.getClosestWorkTime({date:r,dir:i.direction,task:e}));return i.startOfDay?t.getClosestWorkTime({date:o,dir:Y.FUTURE,task:e}):t.getClosestWorkTime({date:Xa(o,1),dir:Y.PAST,task:e})}function Za(e,t){let i={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},r=e.constraintType;if(!r||r===v.ASAP||r===v.ALAP)return i;let n=wi(e,t);if(!n)return i;let o=s=>t.calculateEndDate({startDate:s,durationHours:e.durationHours,task:e}),a=s=>t.calculateEndDate({startDate:s,durationHours:-e.durationHours,task:e});switch(r){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 i}}function Qa(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function Jn(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var B={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"},Pf=Object.values(B);function yr(e){return Pf.includes(e)}var Lf={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"},Of={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"},E={...Lf,...Of};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 I={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",SIR_SYNC:"sir-sync",ACTIVITY_LOOKAHEAD_SYNC:"activity-lookahead-sync",SCHEDULE_AUTO_SCHEDULE:"schedule-auto-schedule"},pe="activity-batch",ot=St,ts=Object.values(I);function gt(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(i=>i.isActiveVersion)??null}var At={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"},xi={START:"start",END:"end"},Ne={FINISH_TO_START:"finish-to-start",START_TO_START:"start-to-start",FINISH_TO_FINISH:"finish-to-finish",START_TO_FINISH:"start-to-finish"},ii={CREATE:"create",UPDATE:"update",REMOVE:"remove"};var Nf={[At.NAME]:E.TEXT,[At.DESCRIPTION]:E.DESCRIPTION,[At.DURATION_DAYS]:E.DURATION,[At.PROGRESS]:E.PROGRESS,[At.COST]:E.COST,[At.USED_COST]:E.USED_COST,[At.WORK_HOURS]:E.HH_WORK_TIME,[At.START_DATE]:E.START_DATE,[At.END_DATE]:E.END_DATE,[At.CONSTRAINT_TYPE]:E.CONSTRAINT_TYPE,[At.CONSTRAINT_DATE]:E.CONSTRAINT_DATE,[At.CALENDAR_ID]:E.CALENDAR_ID,[At.CUSTOM_ID]:E.CUSTOM_ID,[At.SUBCONTRACT_ID]:E.SUBCONTRACT_ID,[At.RESPONSABLE_IDS]:E.RESPONSABLES,[At.TAG_IDS]:E.TAGS};function Xn(e,t){return{activityId:e,column:Nf[t.field],newValue:t.value}}var bf={[Ne.FINISH_TO_START]:B.FINISH_TO_START,[Ne.START_TO_START]:B.START_TO_START,[Ne.FINISH_TO_FINISH]:B.FINISH_TO_FINISH,[Ne.START_TO_FINISH]:B.START_TO_FINISH};function Mi(e){return bf[e]}function Ff(e){return e.kind===ii.CREATE?{kind:ot.CREATE,source:e.sourceId,target:e.targetId,type:Mi(e.relationship),...e.lagDays===void 0?{}:{lag:e.lagDays},...e.linkId===void 0?{}:{linkId:e.linkId}}:e.kind===ii.UPDATE?{kind:ot.UPDATE,linkId:e.linkId,...e.sourceId===void 0?{}:{source:e.sourceId},...e.targetId===void 0?{}:{target:e.targetId},...e.relationship===void 0?{}:{type:Mi(e.relationship)},...e.lagDays===void 0?{}:{lag:e.lagDays}}:e.kind===ii.REMOVE?{kind:ot.DELETE,linkId:e.linkId}:e}function wf(e){return e===xi.START?E.START_DATE:e===xi.END?E.END_DATE:e}function xf(e){return{kind:pe,mode:e.mode,items:e.items,links:e.links.map(t=>({source:t.source,target:t.target,type:Mi(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}})),...e.eventSource===void 0?{}:{eventSource:e.eventSource}}}function Mf(e){return{get:t=>e.getActivityView(t),list:()=>e.getAllActivitiesView(),ids:()=>e.getAllIds(),forEachId:t=>e.forEachActivityId(t),property:(t,i)=>e.getProperty(t,i),children:t=>e.getChildrenView(t),childIds:t=>e.getChildrenIds(t),hasChildren:t=>e.hasChild(t),indentTargetParentIds:t=>e.getIndentTargetParentIds(t),isCustomIdInUse:(t,i)=>e.isCustomIdInUse(t,i??null),create:(t,i)=>e.dispatch({...t,kind:I.ACTIVITY_CREATE},i),applyBatch:(t,i)=>e.applyActivityBatch(xf(t),i),editInline:(t,i,r)=>e.dispatch({...Xn(t,i),kind:I.INLINE_EDIT},r),setType:(t,i,r)=>e.dispatch({kind:I.ACTIVITY_TYPE_SET,activityId:t,type:i},r),applyDragBatch:(t,i)=>e.dispatch({kind:I.DATES_BATCH,edits:t.map(r=>({activityId:r.activityId,column:wf(r.edge),newValue:r.value}))},i),editFields:(t,i)=>e.dispatch({kind:I.BULK_EDIT,edits:t.map(r=>Xn(r.activityId,r))},i),remove:(t,i={})=>e.dispatch({...i,kind:I.ACTIVITY_DELETE,activityIds:t}),move:(t,i)=>e.dispatch({...t,kind:I.ACTIVITY_MOVE},i),planLookaheadConversion:t=>e.planLookaheadConversion(t),applyLookaheadConversion:t=>e.applyLookaheadConversion(t),indent:(t,i={})=>e.dispatch({...i,kind:I.ACTIVITY_INDENT,activityIds:t}),outdent:(t,i={})=>e.dispatch({...i,kind:I.ACTIVITY_OUTDENT,activityIds:t}),setProgress:(t,i,r={})=>e.dispatch({...r,kind:I.ACTIVITY_SET_PROGRESS,activityId:t,newValue:i}),copy:(t={})=>e.dispatch({...t,kind:I.ACTIVITY_COPY}),paste:(t,i={})=>e.dispatch({...i,kind:I.ACTIVITY_PASTE_COPIED,destination:{afterSiblingId:t}}),clearClipboard:(t={})=>e.dispatch({...t,kind:I.ACTIVITY_CLIPBOARD_CLEAR}),lookaheadSync:t=>e.dispatch({...t,kind:I.ACTIVITY_LOOKAHEAD_SYNC}),autoSchedule:(t,i)=>e.dispatch({kind:I.SCHEDULE_AUTO_SCHEDULE,...t===void 0?{}:{activityId:t}},i),createDateGesturePreview:t=>e.createDateGesturePreview(t)}}function Uf(e){return{get:t=>e.getLinkView(t),list:()=>e.getAllLinksView(),forActivity:t=>e.getLinksForActivityView(t),create:(t,i)=>e.dispatch({kind:I.LINK_CREATE,source:t.sourceId,target:t.targetId,type:Mi(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}},i),update:(t,i,r)=>e.dispatch({kind:I.LINK_UPDATE,linkId:t,...i.sourceId===void 0?{}:{source:i.sourceId},...i.targetId===void 0?{}:{target:i.targetId},...i.relationship===void 0?{}:{type:Mi(i.relationship)},...i.lagDays===void 0?{}:{lag:i.lagDays}},r),remove:(t,i)=>e.dispatch({kind:I.LINK_DELETE,linkId:t},i),batch:(t,i)=>e.dispatch({kind:I.LINKS_BATCH,operations:t.map(Ff)},i)}}function es(e){let t=(i,r)=>e.dispatch({kind:I.BASELINE_APPLY,points:i},r);return{activities:Mf(e),links:Uf(e),calendars:{get:i=>e.getCalendar(i),list:()=>e.getAllCalendars(),listBase:()=>e.getBaseCalendars(),projectWorkHours:()=>e.getProjectWorkHours(),reconcile:i=>e.dispatch({kind:I.CALENDAR_RECONCILE},i)},selection:{ids:()=>e.getSelectedActivityIds(),toggle:({checked:i,...r})=>e.dispatch({...r,kind:I.SELECTION_TOGGLE,isChecked:i}),replace:(i,r={})=>e.dispatch({...r,kind:I.SELECTION_REPLACE,activityIds:i})},view:{hiddenActivityIds:()=>e.getHiddenActivityIds(),visibleActivityIds:()=>e.getVisibleActivityIds(),visualOrderIds:()=>e.getVisualOrderIds(),filter:()=>e.getActiveFilter(),setFilter:i=>e.dispatch({...i,kind:I.FILTER_SET}),order:()=>e.getActiveOrder(),setOrder:(i,r={})=>e.dispatch({...r,kind:I.SORT_SET,rules:i}),setVisibility:(i,r={})=>e.dispatch({...r,kind:I.VISIBILITY_SET,visibleIds:i}),setStatusCriteria:(i,r)=>e.dispatch({kind:I.STATUS_CRITERIA_SET,criteria:i},r)},baselines:{refresh:t,setVisibility:t,setPonderatorCriterion:(i,r)=>e.dispatch({kind:I.PONDERATOR_CRITERION_SET,criterion:i},r),activeFor:i=>gt(i)},impactRequests:{sync:i=>e.dispatch({...i,kind:I.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:i=>e.dispatch({kind:I.PERSISTENCE_ACKNOWLEDGE,checkpoint:i})},history:{undo:i=>e.undo(i),redo:i=>e.redo(i),canUndo:()=>e.canUndo(),canRedo:()=>e.canRedo(),clear:()=>e.clearHistory(),depth:()=>e.undoDepth()},projection:{changeSetFrom:i=>e.createProjectionChangeSetFrom(i)},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 Ut=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 hr=e=>String(e);function is(e){let{clickedId:t,isChecked:i,currentSelection:r,hierarchy:n,isFrozen:o,exists:a,autoCheckParents:s}=e,c=hr(t),l=new Set([...r].map(String)),d=new Set(l),u=Hf(c,n).filter(a),f=u.filter(y=>!o(y)),p=i&&f.length<u.length;i&&!p?d.add(c):d.delete(c);for(let y of f)i?d.add(y):d.delete(y);return p||Bf({id:c,isChecked:i,autoCheckParents:s,hierarchy:n,isFrozen:o,exists:a,next:d}),{nextSelection:d,changed:Wf(l,d),parentBlocked:p}}function Hf(e,t){let i=[],r=new Ut;r.enqueue(e);let n=new Set([e]);for(;!r.isEmpty();){let o=r.dequeue();for(let a of t.getChildrenIds(o)){let s=hr(a);n.has(s)||(n.add(s),i.push(s),r.enqueue(s))}}return i}function Bf(e){let{id:t,isChecked:i,autoCheckParents:r,hierarchy:n,isFrozen:o,exists:a,next:s}=e,c=n.getParentId(t);for(;c!==null&&typeof c<"u";){let l=hr(c);if(o(l))return;let d=n.getChildrenIds(l).map(hr).filter(a),u=d.some(o),f=d.filter(g=>!o(g)),y=f.length>0&&f.every(g=>s.has(g))&&!u;if(i){if(!r||!y||s.has(l))return;s.add(l)}else{if(y||!s.has(l))return;s.delete(l)}c=n.getParentId(l)}}function Wf(e,t){let i=[],r=[];for(let n of t)e.has(n)||i.push(n);for(let n of e)t.has(n)||r.push(n);return{checked:i,unchecked:r}}function ri(e){return(e.pendingRequestIds?.length??0)>0}var S={CANNOT_EDIT:"cannot_edit",PARSE_ERROR:"parse_error",INVALID:"invalid",CUSTOM_ID_DUPLICATE:"custom_id_duplicate",INVALID_LINK_TYPE:"invalid_link_type",INVALID_LINK_LAG:"invalid_link_lag",INVALID_VALUE:"invalid_value",NO_PIPELINE_FOR_COLUMN:"no_pipeline_for_column",ACTIVITY_NOT_FOUND:"activity_not_found",PARENT_NOT_FOUND:"parent_not_found",ACTIVITY_IDS_EMPTY:"activity_ids_empty",NO_ACTIVITY_SELECTION:"no_activity_selection",CLIPBOARD_EMPTY:"clipboard_empty",ACTIVITY_PASTE_INVARIANT_FAILED:"activity_paste_invariant_failed",ANCHOR_SIBLING_CONFLICT:"anchor_sibling_conflict",ANCHOR_SIBLING_NOT_FOUND:"anchor_sibling_not_found",ANCHOR_SIBLING_WRONG_PARENT:"anchor_sibling_wrong_parent",PARENT_FROZEN_BY_SIR:"parent_frozen_by_sir",CANNOT_MOVE_INTO_OWN_DESCENDANT:"cannot_move_into_own_descendant",INDENT_NO_ELIGIBLE_SIBLING:"indent_no_eligible_sibling",OUTDENT_ROOT_LEVEL_NOT_EDITABLE:"outdent_root_level_not_editable",HIERARCHY_CYCLE:"hierarchy_cycle",SANDBOX_PERSISTENCE_FORBIDDEN:"sandbox_persistence_forbidden",STALE_STATE_REVISION:"stale-state-revision",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var rs=(e,t)=>{let i=e.getActivity(t);return i!=null&&ri(i)},ns=(e,t,i)=>{let r=[],n=(o,a)=>{let s=t.isChecked(o);t.setChecked(o,a)&&r.push({activityId:o,checked:{before:s,after:a}})};for(let o of i.checked)n(o,!0);for(let o of i.unchecked)n(o,!1);return{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:r}};function os(e,t){let{adapter:i}=t,r=e.activityId;if(!i.getActivity(r))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let n=e.frozenIds?new Set(e.frozenIds):null,o=n?s=>n.has(s):s=>rs(i,s),a=is({clickedId:r,isChecked:e.isChecked,currentSelection:new Set(i.checkedIds().map(String)),hierarchy:{getChildrenIds:s=>i.getChildren(s),getParentId:s=>{let c=i.getParentId(s);return!c||c==="0"?null:String(c)}},isFrozen:o,exists:s=>i.activityExists(s),autoCheckParents:e.autoCheckParents??!1});return{ok:!0,changes:ns(e,i,a.changed)}}function mr(e,t){let{adapter:i}=t,r=new Set(e.activityIds.map(String).filter(a=>i.activityExists(a)).filter(a=>!rs(i,a))),n=new Set(i.checkedIds().map(String)),o={checked:[...r].filter(a=>!n.has(a)),unchecked:[...n].filter(a=>!r.has(a))};return{ok:!0,changes:ns(e,i,o)}}function ni(e,t,i=e.getAllIds()){let r=[];for(let n of i){let o=String(n),a=t.has(o),s=e.isVisible(o);s!==a&&(e.setVisible(o,a),r.push({activityId:o,visible:{before:s,after:a}}))}return r}function as(e,t){let{adapter:i}=t,r=new Set(e.visibleIds.map(String)),n=ni(i,r);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:n}}}var ss={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var O={STRING:"string",NUMBER:"number",DATE:"date",ID_ARRAY:"id-array",ENUM:"enum",BOOLEAN:"boolean",REFERENCE:"reference"},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"},W={INCLUDES:"includes",NOT_INCLUDES:"notIncludes",IS:"is",IS_NOT:"isNot",EQUALS:"equals",NOT_EQUALS:"notEquals",GREATER_THAN:"greaterThan",LESS_THAN:"lessThan",GREATER_OR_EQUAL:"greaterOrEqual",LESS_OR_EQUAL:"lessOrEqual",AFTER:"after",BEFORE:"before",BETWEEN:"between",SOME_OF:"someOf",NOT_SOME_OF:"notSomeOf"},Ir={AND:"and",OR:"or"};var Vf=2,jf=[Pt.WAITING,Pt.DONE,Pt.DOING,Pt.OVERDUE,Pt.ADVANCEMENT],Kf=[v.MFO,v.MSO,v.SNLT,v.SNET,v.ALAP,v.ASAP,v.FNET,v.FNLT],Yf=1e3*60*60*24;function Zn(e,t){return e===null||t<=0?null:e/t}function Gf(e,t){let i=Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()),r=Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate());return Math.floor((r-i)/Yf)+1}var $f={[z.NAME]:{valueKind:O.STRING,extract:e=>e.name},[z.DESCRIPTION]:{valueKind:O.STRING,extract:e=>e.description},[z.CUSTOM_ID]:{valueKind:O.STRING,extract:e=>e.customId},[z.CORRELATIVE_ID]:{valueKind:O.NUMBER,extract:e=>e.correlativeId},[z.UNIQUE_CORRELATIVE_ID]:{valueKind:O.NUMBER,extract:e=>{let t=Number(e.uniqueCorrelativeId);return Number.isFinite(t)?t:null}},[z.PROGRESS]:{valueKind:O.NUMBER,extract:e=>e.progress},[z.DURATION_DAYS]:{valueKind:O.NUMBER,extract:(e,t)=>Zn(e.durationHours,t.hoursPerDay)},[z.CALENDAR_DURATION]:{valueKind:O.NUMBER,extract:e=>e.type===D.MILESTONE?0:Gf(e.startDate,e.endDate)},[z.COST]:{valueKind:O.NUMBER,extract:e=>e.cost},[z.USED_COST]:{valueKind:O.NUMBER,extract:e=>e.usedCost},[z.REAL_COST]:{valueKind:O.NUMBER,extract:e=>e.realCost},[z.WORK_HOURS]:{valueKind:O.NUMBER,extract:e=>e.workHours},[z.REAL_WORK_HOURS]:{valueKind:O.NUMBER,extract:e=>e.realWorkHours},[z.PONDERATOR]:{valueKind:O.NUMBER,extract:e=>e.ponderator},[z.FREE_SLACK_DAYS]:{valueKind:O.NUMBER,extract:(e,t)=>Zn(e.freeSlackHours,t.hoursPerDay)},[z.TOTAL_SLACK_DAYS]:{valueKind:O.NUMBER,extract:(e,t)=>Zn(e.criticalPath?.totalSlackHours??null,t.hoursPerDay)},[z.EXPECTED_PROGRESS_BASELINE]:{valueKind:O.NUMBER,equalityPrecision:Vf,extract:e=>e.expectedProgressBaseline},[z.EXPECTED_PROGRESS]:{valueKind:O.NUMBER,extract:e=>e.expectedProgress},[z.BASELINE_DURATION_DAYS]:{valueKind:O.NUMBER,extract:e=>e.baselineSnapshot?.durationDays??null},[z.BASELINE_COST]:{valueKind:O.NUMBER,extract:e=>e.baselineSnapshot?.cost??null},[z.BASELINE_WORK_HOURS]:{valueKind:O.NUMBER,extract:e=>e.baselineSnapshot?.workHours??null},[z.START_DATE]:{valueKind:O.DATE,extract:e=>e.startDate},[z.END_DATE]:{valueKind:O.DATE,extract:e=>e.endDate},[z.CONSTRAINT_DATE]:{valueKind:O.DATE,extract:e=>e.constraintDate},[z.BASELINE_START_DATE]:{valueKind:O.DATE,extract:e=>e.baselineSnapshot?.startDate??null},[z.BASELINE_END_DATE]:{valueKind:O.DATE,extract:e=>e.baselineSnapshot?.endDate??null},[z.EARLY_START]:{valueKind:O.DATE,extract:e=>e.criticalPath?.earlyStart??null},[z.EARLY_FINISH]:{valueKind:O.DATE,extract:e=>e.criticalPath?.earlyFinish??null},[z.LATE_START]:{valueKind:O.DATE,extract:e=>e.criticalPath?.lateStart??null},[z.LATE_FINISH]:{valueKind:O.DATE,extract:e=>e.criticalPath?.lateFinish??null},[z.RESPONSABLE_IDS]:{valueKind:O.ID_ARRAY,extract:e=>e.responsableIds},[z.TAG_IDS]:{valueKind:O.ID_ARRAY,extract:e=>e.tagIds},[z.STATUS]:{valueKind:O.ENUM,order:jf,extract:e=>e.status},[z.CONSTRAINT_TYPE]:{valueKind:O.ENUM,order:Kf,extract:e=>e.constraintType},[z.CALENDAR_ID]:{valueKind:O.REFERENCE,extract:e=>e.calendarId===null?null:String(e.calendarId)},[z.SUBCONTRACT_ID]:{valueKind:O.REFERENCE,extract:e=>e.subcontractId===null?null:String(e.subcontractId)},[z.IS_CRITICAL]:{valueKind:O.BOOLEAN,extract:e=>e.isCritical}};function ye(e){return $f[e]??null}function Qn(e){return e instanceof Date?e:typeof e=="string"||typeof e=="number"?new Date(e):new Date(Number.NaN)}function ne(e){return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())}function zf(e,t,i){let r=e===null;return i===W.INCLUDES?!r&&String(e).toLowerCase().includes(t.toLowerCase()):i===W.NOT_INCLUDES?r||!String(e).toLowerCase().includes(t.toLowerCase()):i===W.IS?!r&&String(e)===t:i===W.IS_NOT?r||String(e)!==t:!1}function qf(e,t,i,r){if(e===null||typeof e!="number")return i===W.NOT_EQUALS;let n=r===void 0?e:Number(e.toFixed(r));return i===W.EQUALS?n===t:i===W.NOT_EQUALS?n!==t:i===W.GREATER_THAN?e>t:i===W.LESS_THAN?e<t:i===W.GREATER_OR_EQUAL?e>=t:i===W.LESS_OR_EQUAL?e<=t:!1}function Jf(e,t,i){return typeof e=="number"&&e>=t&&e<=i}function Xf(e,t,i){if(!(e instanceof Date))return!1;let r=ne(e),n=ne(t);return i===W.AFTER?r>n:i===W.BEFORE?r<n:!1}function Zf(e,t,i){if(!(e instanceof Date))return!1;let r=ne(e);return r>=ne(t)&&r<=ne(i)}function Qf(e,t,i){let n=(Array.isArray(e)?e:[]).some(o=>t.has(String(o)));return i===W.SOME_OF?n:i===W.NOT_SOME_OF?!n:!1}function tp(e,t,i){let r=e!==null&&t.has(String(e));return i===W.SOME_OF?r:i===W.NOT_SOME_OF?!r:!1}function cs(e){let t=Array.isArray(e)?e:[e];return new Set(t.map(i=>String(i)))}function ls(e,t,i){let r=ye(t.field);if(r===null)return!1;let n=r.extract(e,i),{operator:o}=t;return o===W.BETWEEN?r.valueKind===O.NUMBER?Jf(n,Number(t.value),Number(t.valueTo)):r.valueKind===O.DATE?Zf(n,Qn(t.value),Qn(t.valueTo)):!1:r.valueKind===O.STRING?zf(n,String(t.value),o):r.valueKind===O.NUMBER?qf(n,Number(t.value),o,r.equalityPrecision):r.valueKind===O.DATE?Xf(n,Qn(t.value),o):r.valueKind===O.ID_ARRAY?Qf(n,cs(t.value),o):tp(n,cs(t.value),o)}function ep(e,t,i){return t.criteria.length===0?!0:t.logic===Ir.OR?t.criteria.some(r=>ls(e,r,i)):t.criteria.every(r=>ls(e,r,i))}function ip(e,t){let i=ne(e.startDate),r=ne(e.endDate),n=ne(t.start),o=ne(t.end),a=i>=n&&r<=o,s=i>=n&&i<=o,c=n>=i&&n<=r;return a||s||c}function to(e,t,i){let r=ep(e,t,i),n=t.dateRange,o=n===void 0||ip(e,n);return r&&o}function rp(e,t,i){let r=t(e);for(;r!==null&&!i.has(String(r));)i.add(String(r)),r=t(r)}function ds(e){let{activities:t,parentOf:i,filter:r,context:n}=e,o=new Set,a=[];for(let s of t)to(s,r,n)&&(o.add(String(s.id)),a.push(s.id));for(let s of a)rp(s,i,o);return o}function np(e){let{activities:t,parentOf:i,filter:r,context:n}=e,o=new Set,a=new Map,s=new Map,c=new Map;for(let l of t){let d=String(l.id),u=i(d);s.set(d,u),c.set(d,c.get(d)??0),u!==null&&c.set(u,(c.get(u)??0)+1);let f=to(l,r,n);a.set(d,f?1:0),f&&o.add(d)}return{matchedIds:o,visibleReferenceCounts:a,parentIds:s,remainingChildren:c}}function op(e){let{visibleReferenceCounts:t,parentIds:i,remainingChildren:r}=e,n=[];for(let o of i.keys())r.get(o)===0&&n.push(o);for(;n.length>0;){let o=n.pop();if(o===void 0)break;let a=i.get(o);if(a==null)continue;let s=t.get(o)??0;t.set(a,(t.get(a)??0)+s);let c=(r.get(a)??1)-1;r.set(a,c),c===0&&n.push(a)}}function ap(e){let t=new Set;for(let[i,r]of e)r>0&&t.add(i);return t}function gr(e){let t=np(e);op(t);let i=ap(t.visibleReferenceCounts);return{filter:e.filter,context:e.context,matchedIds:t.matchedIds,visibleIds:i,visibleReferenceCounts:t.visibleReferenceCounts}}function us(e,t,i){let r=new Set;for(let n of t){let o=String(n.id);r.add(o);let a=e.matchedIds.has(o),s=to(n,e.filter,e.context);if(a===s)continue;s?e.matchedIds.add(o):e.matchedIds.delete(o);let c=s?1:-1,l=o;for(;l!==null;){let d=e.visibleReferenceCounts.get(l)??0,u=d+c;e.visibleReferenceCounts.set(l,u);let f=d>0,p=u>0;f!==p&&(r.add(l),p?e.visibleIds.add(l):e.visibleIds.delete(l)),l=i(l)}}return r}function be(e){return{hoursPerDay:e,locale:"en"}}var Tt={UNKNOWN_FIELD:"unknown_field",UNKNOWN_OPERATOR:"unknown_operator",INVALID_VALUE:"invalid_value"},sp={[O.STRING]:new Set([W.INCLUDES,W.NOT_INCLUDES,W.IS,W.IS_NOT]),[O.NUMBER]:new Set([W.EQUALS,W.NOT_EQUALS,W.GREATER_THAN,W.LESS_THAN,W.GREATER_OR_EQUAL,W.LESS_OR_EQUAL,W.BETWEEN]),[O.DATE]:new Set([W.AFTER,W.BEFORE,W.BETWEEN]),[O.ID_ARRAY]:new Set([W.SOME_OF,W.NOT_SOME_OF]),[O.ENUM]:new Set([W.SOME_OF,W.NOT_SOME_OF]),[O.BOOLEAN]:new Set([W.SOME_OF,W.NOT_SOME_OF]),[O.REFERENCE]:new Set([W.SOME_OF,W.NOT_SOME_OF])};function fs(e){if(e===void 0)return{ok:!0,dateRange:void 0};if(typeof e!="object"||e===null)return{ok:!1,reason:Tt.INVALID_VALUE};let{start:t,end:i}=e;if(!(t instanceof Date)||!(i instanceof Date))return{ok:!1,reason:Tt.INVALID_VALUE};let r=t.getTime(),n=i.getTime();return!Number.isFinite(r)||!Number.isFinite(n)||r>n?{ok:!1,reason:Tt.INVALID_VALUE}:{ok:!0,dateRange:{start:new Date(r),end:new Date(n)}}}function ps(e){let t=ye(e.field);if(t===null)return{ok:!1,reason:Tt.UNKNOWN_FIELD};if(!sp[t.valueKind].has(e.operator))return{ok:!1,reason:Tt.UNKNOWN_OPERATOR};if(e.operator===W.BETWEEN)return cp(e,t.valueKind);if(t.valueKind===O.NUMBER){let r=eo(e.value);return r===null?{ok:!1,reason:Tt.INVALID_VALUE}:{ok:!0,criterion:{...e,value:r}}}if(t.valueKind===O.DATE){let r=io(e.value);return r===null?{ok:!1,reason:Tt.INVALID_VALUE}:{ok:!0,criterion:{...e,value:r}}}let i=lp(e,t.valueKind);return i!==null?{ok:!1,reason:i}:t.valueKind===O.BOOLEAN?{ok:!0,criterion:{...e,value:[...new Set(e.value)]}}:t.valueKind===O.ID_ARRAY||t.valueKind===O.ENUM||t.valueKind===O.REFERENCE?{ok:!0,criterion:{...e,value:[...new Set(e.value.map(String))]}}:{ok:!0,criterion:e}}function cp(e,t){if(t===O.NUMBER){let i=eo(e.value),r=eo(e.valueTo);return i===null||r===null||i>r?{ok:!1,reason:Tt.INVALID_VALUE}:{ok:!0,criterion:{...e,value:i,valueTo:r}}}if(t===O.DATE){let i=io(e.value),r=io(e.valueTo);return i===null||r===null||i.getTime()>r.getTime()?{ok:!1,reason:Tt.INVALID_VALUE}:{ok:!0,criterion:{...e,value:i,valueTo:r}}}return{ok:!1,reason:Tt.UNKNOWN_OPERATOR}}function lp(e,t){let{value:i}=e;return t===O.BOOLEAN?Array.isArray(i)&&i.every(r=>typeof r=="boolean")?null:Tt.INVALID_VALUE:t===O.ID_ARRAY||t===O.ENUM||t===O.REFERENCE?Array.isArray(i)&&i.every(r=>typeof r=="string"||typeof r=="number")?null:Tt.INVALID_VALUE:Array.isArray(i)?Tt.INVALID_VALUE:null}function eo(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 w(e){return structuredClone(e)}function ys(e){return e.criteria.length===0&&e.dateRange===void 0}function dp(e,t,i){let r=e.getAllActivities();if(ys(t))return{visibleIds:ds({activities:r,parentOf:o=>e.getParentId(o),filter:t,context:be(i)}),projection:null};let n=gr({activities:r,parentOf:o=>e.getParentId(o),filter:t,context:be(i)});return{visibleIds:n.visibleIds,projection:n}}function hs(e,t){let{adapter:i,hoursPerDay:r}=t,n=[];for(let u of e.criteria){let f=ps(u);if(!f.ok)return{ok:!1,reason:f.reason};n.push(f.criterion)}let o=fs(e.dateRange);if(!o.ok)return{ok:!1,reason:o.reason};let a=w(o.dateRange===void 0?{criteria:n,logic:e.logic}:{criteria:n,logic:e.logic,dateRange:o.dateRange});i.setActiveFilter(ys(a)?null:a);let{visibleIds:s,projection:c}=dp(i,a,r);i.setFilterProjection(c);let l=ni(i,s);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:l}}}var Fe={ASCENDING:"asc",DESCENDING:"desc"};var V="0";function U(e){return e==null||e===0||e==="0"}function $t(e){return U(e)?"0":String(e)}var ro=Number.MAX_SAFE_INTEGER;function Wt(e,t){let i=Ui(e,t),r=t.getOrderComparator?.()??null;return i.sort(r===null?Ar:(n,o)=>r(n,o)||Ar(n,o)),i.map(n=>String(n.id))}function Is(e){let t=[],i=n=>{t.push(n);let o=Wt(String(n.id),e);for(let a of o){let s=e.getActivity(a);s&&i(s)}},r=Wt("0",e);for(let n of r){let o=e.getActivity(n);o&&i(o)}return t}function gs(e,t,i){let r=i.getActivity(e);if(!r)return null;let n=As(r),o=Wt(n,i),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&&!up(t,c))return c}return null}function no(e,t){let i=t.getActivity(e);if(!i)return-1;let r=As(i);return Wt(r,t).findIndex(o=>String(o)===String(e))}function Ui(e,t){let i=String(e)==="0"?t.getRootIds?.()??t.getChildren("0"):t.getChildren(e),r=[];for(let n of i){let o=t.getActivity(n);o&&r.push(o)}return r}function Ar(e,t){let i=ms(e),r=ms(t);return i!==r?i-r:String(e.id).localeCompare(String(t.id))}function ms(e){let t=e.correlativeId,i=typeof t=="number"?t:Number(t);return Number.isFinite(i)?i:ro}function As(e){let t=e.parentId;return t===null?"0":t}function up(e,t){return e.has(t)?!0:e.has(String(t))}function oi(e){let t=[],i=r=>{let n=Wt(r,e);n.length>1&&t.push({parentId:r,childIds:n});for(let o of n)i(o)};return i("0"),t}function oo(e,t){let i=[];for(let r of t){let n=Wt(r,e);n.length>1&&i.push({parentId:r,childIds:n})}return i}function fp(e){return ye(e.field)===null?Tt.UNKNOWN_FIELD:e.direction!==Fe.ASCENDING&&e.direction!==Fe.DESCENDING?Tt.UNKNOWN_OPERATOR:null}function vs(e,t){let{adapter:i}=t;for(let o of e.rules){let a=fp(o);if(a!==null)return{ok:!1,reason:a}}let r=e.rules.length===0?null:w({rules:e.rules});return i.setActiveOrder(r),{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],order:oi(i)}}}function Cs(e,t){throw new Error(t)}var ao={OWN_BASELINE:"own-baseline",RECURSIVE_LEAF_SUM:"recursive-leaf-sum",ZERO:"zero"},so={[D.PROJECT]:{alwaysSummary:!0,holdsConstraint:!1,carriesCustomId:!1,forcedDuration:null,ponderatorWeight:ao.RECURSIVE_LEAF_SUM,promotesToProjectOnFirstChild:!1},[D.TASK]:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:null,ponderatorWeight:ao.OWN_BASELINE,promotesToProjectOnFirstChild:!0},[D.MILESTONE]:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:0,ponderatorWeight:ao.ZERO,promotesToProjectOnFirstChild:!0}};function zt(e,t){return t||Fi(e)&&so[e].alwaysSummary}function oe(e){return e===D.MILESTONE}function he(e){return Fi(e)&&so[e].promotesToProjectOnFirstChild}var co=D.PROJECT,ai=D.TASK;function Hi(e,t){return t===0?D.MILESTONE:e===0&&t>0?D.TASK:null}var b={ID:"id",PROPLANNER_ID:"proplannerId",PARENT:"parentId",NAME:"name",DESCRIPTION:"description",TYPE:"type",START_DATE:"startDate",END_DATE:"endDate",DURATION_HOURS:"durationHours",CONSTRAINT_TYPE:"constraintType",CONSTRAINT_DATE:"constraintDate",AUTO_SCHEDULING:"autoScheduling",CALENDAR_ID:"calendarId",ASSIGNED_DEFAULT_CALENDAR:"assignedDefaultCalendar",DATE_ORIGIN:"dateOrigin",PROGRESS:"progress",COST:"cost",USED_COST:"usedCost",REAL_COST:"realCost",WORK_HOURS:"workHours",REAL_WORK_HOURS:"realWorkHours",PONDERATOR:"ponderator",HAS_CUSTOM_PONDERATOR:"hasCustomPonderator",CORRELATIVE_ID:"correlativeId",UNIQUE_CORRELATIVE_ID:"uniqueCorrelativeId",CUSTOM_ID:"customId",SUBCONTRACT_ID:"subcontractId",IS_LOOKAHEAD:"isLookahead",HAS_LOOKAHEAD_TASKS:"hasLookaheadTasks",NEW_ACTIVITIES_ARRAY:"newActivityIds",HAS_NEW_ACTIVITIES:"hasNewActivities",IS_NEW_ACTIVITY:"isNewActivity",PENDING_REQUEST_IDS:"pendingRequestIds",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds",BASELINE_POINTS:"baselinePoints",BASELINE_SNAPSHOT:"baselineSnapshot",SUM_OF_DURATION_RECURSIVELY:"recursiveDurationHours",CALENDAR_DURATION:"calendarDuration",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath"},wt={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 Ss(e,t){return()=>t()===e}var lo=typeof window>"u",pp=!lo&&typeof MessageChannel<"u";function ct(){return pp?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 vr(e,t){return performance.now()-e<ss.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await ct(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function si(e){return lo||await ct(),e()?{aborted:!1}:{aborted:!0}}function Cr(e,t){let{inDegree:i,successors:r}=yp(e,t),n=hp(i),o=mp(n,i,r),a=o.length<e.length,s=a?Ip(e,o):[],c=[...o].reverse();return{ordered:o,reversed:c,hasCycles:a,cycleNodes:s}}function yp(e,t){let i=new Map,r=new Map;for(let n of e)i.set(n,0),r.set(n,[]);for(let n of t){let o=n.source,a=n.target;!i.has(o)||!i.has(a)||(r.get(o).push(a),i.set(a,(i.get(a)??0)+1))}return{inDegree:i,successors:r}}function hp(e){let t=new Ut;for(let[i,r]of e)r===0&&t.enqueue(i);return t}function mp(e,t,i){let r=[];for(;!e.isEmpty();){let n=e.dequeue();r.push(n);for(let o of i.get(n)??[]){let a=(t.get(o)??1)-1;t.set(o,a),a===0&&e.enqueue(o)}}return r}function Ip(e,t){let i=new Set(t);return e.filter(r=>!i.has(r))}var Sr=class{cached=null;invalidate(){this.cached=null}get(t,i){return this.cached?this.cached:(this.cached=Cr(t,i),this.cached)}};function Ts(e,t){let i=[];for(let r of e)t.has(r)&&i.push(r);return i}function Tr(e,t){let i=t.getActivity(e);return i?zt(i.type,t.getChildren(e).length>0):!1}function Dr(e,t,i){let r=String(t),n=i.getActivity(e);for(;n?.parentId&&String(n.parentId)!=="0";){if(String(n.parentId)===r)return!0;n=i.getActivity(n.parentId)}return!1}function _r(e,t,i){let r=Tr(e,i);return Tr(t,i)&&Dr(e,t,i)||r&&Dr(t,e,i)}function _s(e,t){let i=[],r=[e];for(;r.length>0;){let n=r.pop(),o=t.getChildren(n);if(o.length===0){String(n)!==String(e)&&i.push(n);continue}for(let a of o)r.push(a)}return i}function gp(e){let t=new Map;for(let i of e)Ds(t,String(i.source),i),Ds(t,String(i.target),i);return t}function Ds(e,t,i){let r=e.get(t);if(r){r.push(i);return}e.set(t,[i])}function Ap(e,t,i,r){if(e.length<=1)return e;let n=new Set(e.map(String)),o=[];for(let a of e)vp(a,n,t,i,r)||o.push(a);return o.length>0?o:e}function vp(e,t,i,r,n){let o=String(e),a=i.getActivity(e);if(!a||a.autoScheduling===!1)return!1;let s=r.get(o)??[];for(let c of s)if(Cp(c,o,a,t,i,n))return!0;return!1}function Cp(e,t,i,r,n,o){if(Sp(e)||!(o?String(e.source)===t:String(e.target)===t))return!1;let s=Tp(e,t);if(!r.has(String(s)))return!1;let c=n.getActivity(s);return!!(c?.autoScheduling!==!1&&c&&Dp(e,i,c))}function Sp(e){return e.source===e.target}function Tp(e,t){return String(e.source)===t?e.target:e.source}function Dp(e,t,i){let r=e.lag??0,n=Math.abs(r);return String(e.target)===String(i.id)&&n<=i.durationHours||String(e.target)===String(t.id)&&n<=t.durationHours}function kr(e,t){let i=[],r=gp(e),n=0;for(let o of e){let a=Tr(o.source,t),s=Tr(o.target,t);if(Ep(o,a,s,t))continue;if(!a&&!s){i.push(o);continue}let c=Es(o.source,a,t,r,!0),l=Es(o.target,s,t,r,!1);n=Np(i,c,l,o,t,n,r)}return i}function Ep(e,t,i,r){return i&&Dr(e.source,e.target,r)||t&&Dr(e.target,e.source,r)}function Es(e,t,i,r,n){return t?Ap(_s(e,i),i,r,n):[e]}function _p(e,t,i){let r=_s(e,t);if(r.length===0)return null;let n=null,o=null;for(let a of r){let s=i(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 Er(e,t){return _p(e,t,i=>{let r=t.getActivity(i);return r?{startDate:r.startDate,endDate:r.endDate}:null})}function kp(e,t,i){return e?t?i.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function Rp(e,t,i,r){if(!t)return 0;let n=r.getActivity(e);return!i||!n?-t.durationHours:-r.calculateDuration({startDate:i.startDate,endDate:n.endDate,task:t})}function Pp(e,t){let i=String(e);return(t.get(i)??[]).some(n=>String(n.target)===i)}function Lp(e,t,i,r,n){if(Pp(e,n))return 0;let o=r.getActivity(e);return!t||!o||!i?0:r.calculateDuration({startDate:t,endDate:o.startDate,task:i})}function Op(e,t){let i=t.getActivity(e.source),r=t.getActivity(e.target),n=Er(e.source,t),o=Er(e.target,t),a=e.type===B.START_TO_START||e.type===B.START_TO_FINISH,s=e.type===B.FINISH_TO_FINISH||e.type===B.START_TO_FINISH;return{source:i,sourceBounds:n,targetStart:o?.startDate??r?.startDate,userLag:e.lag??0,sourceEndpointIsStart:a,targetLag:s?-kp(r,o,t):0,summarySourceId:e.type===B.START_TO_START&&n?e.source:void 0,finishAnchoredSummaryTargetId:s&&o?e.target:void 0}}function Np(e,t,i,r,n,o,a){let s=Op(r,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?Rp(k,c,l,n):0;for(let F of i){if(String(k)===String(F))continue;let h=Lp(F,d,c,n,a);e.push(bp(r,k,F,A,_,p,u+h,y,g??(h!==0&&p===0?r.target:void 0))),A+=1}}return A}function bp(e,t,i,r,n,o,a,s,c){return{id:`virtual_${e.id}_${r}`,source:t,target:i,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 Rr=class{invalidate(){}get(t,i){return kr(t,i)}};function Fp(e){let t=new Map,i=r=>(t.has(r)||t.set(r,new Set),t.get(r));for(let r of e)i(r.source).add(r.id),i(r.target).add(r.id);return{neighbors:t}}function wp(e,t,i){let r=new Set,n=new Map,o=new Ut;for(o.enqueue(e);!o.isEmpty();){let a=o.dequeue(),s=String(a);if(r.has(s))continue;r.add(s);let c=i.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;r.has(String(f))||o.enqueue(f)}}return Array.from(n.values())}function ks(e,t){let i=new Map;for(let a of t)i.set(a.id,a);let r=Fp(t),n=wp(e,i,r),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 Rs=0,Bi=100;function we(e){return e===0}function Ps(e,t,i){let r=i.type===B.FINISH_TO_START,n=i.type===B.FINISH_TO_FINISH;if(i._targetLag!==void 0)return{sourceLag:i._sourceLag??0,targetLag:i._targetLag,trueLag:i._trueLag??i.lag??0,isFS:r,isFF:n,isZeroDurationCase:!1};let o=i.lag??0;switch(i.type){case B.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:o,isFS:r,isFF:n,isZeroDurationCase:!1};case B.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:o,isFS:r,isFF:n,isZeroDurationCase:!1};case B.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:o,isFS:r,isFF:n,isZeroDurationCase:!1};case B.START_TO_FINISH:return{sourceLag:-e.durationHours,targetLag:-t.durationHours,trueLag:o,isFS:r,isFF:n,isZeroDurationCase:!1};default:return{sourceLag:0,targetLag:0,trueLag:o,isFS:r,isFF:n,isZeroDurationCase:!1}}}function xp(e,t,i){if(e._summarySourceId===void 0)return null;let r=i.getActivity(e._summarySourceId);if(!r)return null;let n=Er(e._summarySourceId,i);return n?-i.calculateDuration({startDate:n.startDate,endDate:t.endDate,task:r}):null}function Mp(e,t,i,r,n){let o=t.durationHours===0&&n;return{successorStart:r.getClosestWorkTime({date:e.endDate,dir:o?"past":"future",task:t}),link:i}}function Ls(e,t,i,r){let{sourceLag:n,targetLag:o,trueLag:a,isFS:s,isFF:c}=Ps(e,t,i),l=xp(i,e,r)??n,d=l+o+a;if(!(t.durationHours===0?d!==0:l!==0||o!==0||a!==0))return Mp(e,t,i,r,s||c);let p=s?t:e,y=r.getClosestWorkTime({date:e.endDate,dir:"future",task:p});if(l!==0&&(y=r.calculateEndDate({startDate:y,durationHours:l,task:e})),o!==0&&(y=r.calculateEndDate({startDate:y,durationHours:o,task:t})),a!==0&&(y=r.calculateEndDate({startDate:y,durationHours:a,task:t})),t.durationHours===0){if(s||c)return{successorStart:r.getClosestWorkTime({date:y,dir:"past",task:t}),link:i};let g=new Date(Date.UTC(y.getUTCFullYear(),y.getUTCMonth(),y.getUTCDate()));return{successorStart:r.getClosestWorkTime({date:g,dir:"future",task:t}),link:i}}return{successorStart:r.getClosestWorkTime({date:y,dir:"future",task:t}),link:i}}function Os(e,t,i,r){let{sourceLag:n,targetLag:o,trueLag:a}=Ps(t,e,i),s=r.getClosestWorkTime({date:e.startDate,dir:"past",task:e});return a!==0&&(s=r.calculateEndDate({startDate:s,durationHours:-a,task:e})),o!==0&&(s=r.calculateEndDate({startDate:s,durationHours:-o,task:e})),n!==0&&(s=r.calculateEndDate({startDate:s,durationHours:-n,task:t})),s}function Ns(e,t,i){for(let r of e){let n=t.getActivity(r);if(!n)continue;let o=n.constraintType;if(!o||o===v.ASAP||o===v.ALAP)continue;let a=Za(n,t);!a.earliestStart&&!a.latestStart&&!a.earliestEnd&&!a.latestEnd||i.set(r,{activityId:r,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 Pr(e,t,i){let r={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=Jn(e.startDate,r):Qa(n,r)?o=n:o=Jn(n,r),t.startDate=o,t.endDate=i.calculateEndDate({startDate:o,durationHours:e.durationHours,task:e})}function bs(e,t){if(!e||!t)return new Date;let{constraintType:i,constraintDate:r}=e;if(!i||!r)return t;switch(i){case v.MSO:case v.MFO:return new Date(r);case v.SNET:case v.FNET:return r>t?new Date(r):t;case v.SNLT:case v.FNLT:return r<t?new Date(r):t;default:return t}}function Up(e,t){return t.length?t.some(i=>String(i)===String(e)):!1}function Fs(e,t,i){return uo(e.id,t,i)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function uo(e,t,i){return t.dragWithMultiple&&Up(e,i)}async function ws(e,t,i,r,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=i.getActivity(u);return p?{startDate:p.startDate,endDate:p.endDate}:{startDate:new Date,endDate:new Date}},c=i.getFlags(),l=r.draggedIds??[],d=performance.now();for(let u of e){let f=await vr(d,n);if(f.aborted)return o;d=f.newSliceStart;let p=i.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||Hp(p,i))continue;let y=a.get(String(u))??[],g=null,A=null,k=!1;for(let M of y){let T=i.getActivity(M.source);if(!T)continue;let C=s(M.source),L=C.startDate.getTime()!==T.startDate.getTime()||C.endDate.getTime()!==T.endDate.getTime(),j={...T,startDate:C.startDate,endDate:C.endDate},K=Fs(j,c,l),it={...j,startDate:K.startDate,endDate:K.endDate},rt=uo(M.source,c,l)?{...M,lag:0}:M,vt=Ls(it,p,rt,i);(!g||vt.successorStart>g)&&(g=vt.successorStart,A=String(M.id),k=M._summaryTargetId!==void 0&&!L&&(M._targetLag===0||r.preventSummaryTargetPullback===!0))}g!==null&&k&&g<p.startDate&&(g=new Date(p.startDate));let F=o.get(u),h=F?{...F}:{activityId:u,startDate:p.startDate,endDate:p.endDate,drivingLinkId:null,kind:v.ASAP,conflict:!1},R=h.earliestStart||h.latestStart||h.earliestEnd||h.latestEnd;if(!(!g&&!R)){if(g){let M=g;p.type===D.MILESTONE&&(M=bs(p,g)),h.drivingLinkId=A,h.startDate=M,h.endDate=i.calculateEndDate({startDate:M,durationHours:p.durationHours,task:p}),h.earliestSchedulingStart=M,h.earliestSchedulingEnd=h.endDate}else p.constraintType===v.MSO?h.earliestStart&&(h.startDate=h.earliestStart,h.endDate=h.earliestEnd??i.calculateEndDate({startDate:h.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===v.MFO&&h.latestStart&&(h.startDate=h.latestStart,h.endDate=h.latestEnd??i.calculateEndDate({startDate:h.latestStart,durationHours:p.durationHours,task:p}));Pr(p,h,i),o.set(u,h)}}return o}function Hp(e,t){return zt(e.type,t.getChildren(e.id).length>0)}async function xs(e,t,i,r,n,o){let a=new Map(i),s=r.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 _=r.getActivity(A);return _?{startDate:_.startDate,endDate:_.endDate}:{startDate:new Date,endDate:new Date}},p=A=>!A.parentId||U(A.parentId)?r.getProjectEnd():f(A.parentId).endDate,y=(A,k)=>{let _=A,F=0;for(;_&&!U(_)&&F++<c+1;){if(String(_)===String(k))return!0;let h=r.getActivity(_);if(!h||!h.parentId)break;_=h.parentId}return!1},g=performance.now();for(let A of e){let k=await vr(g,o);if(k.aborted)return a;g=k.newSliceStart;let _=r.getActivity(A);if(!_||_.constraintType!==v.ALAP||!_.autoScheduling||_.progress===100||zt(_.type,r.getChildren(A).length>0))continue;let F=p(_),h=F,R=null,M=!1,T=d.get(String(A))??[];for(let Gt of T){if((Gt.lag??0)<0)continue;let ei=r.getActivity(Gt.target);if(!ei||ei.autoScheduling===!1)continue;let Ja=f(Gt.target),If={...ei,startDate:Ja.startDate,endDate:Ja.endDate},lr=Os(If,_,Gt,r);(h===null||lr<h)&&(h=lr),(R===null||lr<R)&&(R=lr,M=_.parentId&&!U(_.parentId)?y(Gt.target,_.parentId):!1)}if(R!==null)if(M||F===null)h=R;else{let Gt=f(A).endDate,ei=Gt.getTime()>F.getTime()?Gt:F;h=R<ei?R:ei}else{if(F===null||h===null)continue;h>F&&(h=F)}if(h===null)continue;let L=(u.get(String(A))??[]).some(Gt=>Gt.type===B.FINISH_TO_START||Gt.type===B.FINISH_TO_FINISH),j=new Date(Date.UTC(h.getUTCFullYear(),h.getUTCMonth(),h.getUTCDate())),K=()=>r.getClosestWorkTime({date:j,dir:"past",task:_}),it=r.getClosestWorkTime({date:h,dir:"future",task:_}).getTime()===h.getTime(),rt;_.durationHours===0&&R===null?rt=L&&it?K():r.getClosestWorkTime({date:h,dir:"past",task:_}):_.durationHours===0?L?rt=K():rt=r.getClosestWorkTime({date:h,dir:"future",task:_}):rt=r.getClosestWorkTime({date:h,dir:"future",task:_});let vt=r.calculateEndDate({startDate:rt,durationHours:-_.durationHours,task:_}),Ct=a.get(A),It=Ct?{...Ct}:{activityId:A,startDate:vt,endDate:rt,drivingLinkId:null,kind:v.ALAP,conflict:!1};It.startDate=vt,It.endDate=rt,It.drivingLinkId=null,It.kind=v.ALAP;let Qe=It.earliestSchedulingStart??null;It.earliestSchedulingStart=null,It.earliestSchedulingEnd=null;let ti=Qe!==null&&Qe.getTime()>vt.getTime()?Qe:vt;It.latestSchedulingStart=ti,It.latestSchedulingEnd=ti===vt?rt:r.calculateEndDate({startDate:ti,durationHours:_.durationHours,task:_}),Pr(_,It,r),a.set(A,It)}return a}var ci={warn(){},error(){}};var Bp=864e5;function te(e){if(e.type===D.MILESTONE)return 0;let t=e.startDate?.getTime(),i=e.endDate?.getTime();return t==null||i==null||Number.isNaN(t)||Number.isNaN(i)?null:Math.floor((i-t)/Bp)+1}function Wi(e,t){t.cancelled||t.updatedIds.length===0||e.batchUpdate(()=>{for(let i of t.updatedIds){let r=t.plans.get(i);if(!r)continue;let n=e.getLiveActivity(i);n&&(n.startDate=r.startDate,n.endDate=r.endDate,n.calendarDuration=te(n),e.updateActivity(i))}})}function fo(e,t){let i=String(t.source),r=String(t.target);if(i===r)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 Wp(n,r,i)}function Vi(e){let t=new Map,i=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),i.set(a,i.get(a)??0),i.set(s,(i.get(s)??0)+1)}let r=new Ut;for(let[o,a]of i)a===0&&r.enqueue(o);let n=0;for(;!r.isEmpty();){let o=r.dequeue();n+=1;for(let a of t.get(o)??[]){let s=i.get(a)-1;i.set(a,s),s===0&&r.enqueue(a)}}return n!==i.size}function Wp(e,t,i){if(t===i)return!0;let r=new Set([t]),n=new Ut;for(n.enqueue(t);!n.isEmpty();){let o=n.dequeue(),a=e.get(o)??[];for(let s of a){if(s===i)return!0;r.has(s)||(r.add(s),n.enqueue(s))}}return!1}function Lr(e){let t=Vp(e);for(let i of t.adjacency.keys())t.records.has(i)||jp(i,t);return t.components}function Vp(e){let t=new Map,i=new Set;for(let r of e){let n=String(r.source),o=String(r.target),a=Ms(t,n);if(Ms(t,o),n===o){i.add(n);continue}a.push(o)}return{adjacency:t,selfLooped:i,records:new Map,componentStack:[],nextIndex:0,components:[]}}function Ms(e,t){let i=e.get(t);if(i)return i;let r=[];return e.set(t,r),r}function jp(e,t){let i=[];for(i.push({node:e,record:Us(e,t),neighborCursor:0});i.length>0;){let r=i[i.length-1];if(r===void 0)break;let n=t.adjacency.get(r.node)??[];if(r.neighborCursor<n.length){let s=n[r.neighborCursor];if(r.neighborCursor+=1,s===void 0)continue;Kp(r,s,i,t);continue}i.pop();let o=i[i.length-1];o&&r.record.lowLink<o.record.lowLink&&(o.record.lowLink=r.record.lowLink),r.record.lowLink===r.record.visitIndex&&Yp(r.node,t)}}function Kp(e,t,i,r){let n=r.records.get(t);if(!n){i.push({node:t,record:Us(t,r),neighborCursor:0});return}n.onStack&&n.visitIndex<e.record.lowLink&&(e.record.lowLink=n.visitIndex)}function Us(e,t){let i={visitIndex:t.nextIndex,lowLink:t.nextIndex,onStack:!0};return t.nextIndex+=1,t.records.set(e,i),t.componentStack.push({node:e,record:i}),i}function Yp(e,t){let i=[];for(;;){let a=t.componentStack.pop();if(a===void 0||(a.record.onStack=!1,i.push(a.node),a.node===e))break}let r=i[0],n=i.length===1&&r!==void 0&&t.selfLooped.has(r);(i.length>1||n)&&t.components.push(i)}function ji(e,t,i){let r=i?new po(e,i):e;return kr([...t],r)}var po=class{constructor(t,i){this.base=t;for(let[r,n]of i.reparented){let o=String(r),a=n===null||U(n)?null:n,s=t.getActivity(r)?.parentId??null,c=s===null||U(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(r),this.movedInByParent.set(l,d)}}}}base;reparented=new Map;movedOutByParent=new Map;movedInByParent=new Map;withOverride(t){if(!t)return null;let i=this.reparented.get(String(t.id));return i===void 0?t:{...t,parentId:i}}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 i=String(t),r=this.movedOutByParent.get(i),n=this.base.getChildren(t),o=r?n.filter(s=>!r.has(String(s))):[...n],a=this.movedInByParent.get(i);return a&&o.push(...a),o}getParent(t){let i=this.reparented.get(String(t));return i===void 0?this.base.getParent(t):i===null?null:this.getActivity(i)}isChildOf(t,i){let r=String(i),n=new Set,o=this.getActivity(t);for(;o;){let a=o.parentId;if(a===null||U(a))return!1;let s=String(a);if(s===r)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 me(e){let{port:t,proposedPort:i,currentLinks:r,proposedLinks:n,proposal:o}=e,a=ji(i??t,n,o);if(!Vi(a))return{ok:!0};let s=ji(t,r),c=Hs(s),d=[...Hs(a)].filter(u=>!c.has(u));return d.length===0?{ok:!0}:{ok:!1,newlyCyclicActivityIds:d}}function Hs(e){let t=new Set;for(let i of Lr(e))for(let r of i)t.add(r);return t}function Ie(e,t){switch(e.kind){case St.CREATE:return Gp(e,t);case St.UPDATE:return $p(e,t.port);case St.DELETE:return zp(e,t)}}function br(e,t){if(e.length===0)return{applied:!0};let i=t.port.getAllLinks(),r=new Map,n=[];for(let l of i){let d=Nr(l);r.has(d)||r.set(d,l.id),n.push({source:l.source,target:l.target})}let o=Vi(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(_r(l.source,l.target,t.port)){a={applied:!1,rejected:st.HIERARCHY_LINK};break}let u=Nr(l),f=r.get(u);if(f!==void 0){a={applied:!1,rejected:st.DUPLICATE,linkId:f};break}if(r.set(u,d),o&&fo(n,{source:l.source,target:l.target}))return{applied:!1,rejected:st.CYCLE};n.push({source:l.source,target:l.target})}if(!o&&Vi(n))return{applied:!1,rejected:st.CYCLE};if(a)return a;let s=[...i,...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(!me({port:t.port,currentLinks:i,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 Nr(e){return JSON.stringify([String(e.source),String(e.target),e.type])}function Gp(e,t){let{port:i}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:st.SELF_LINK};let r=i.getActivity(e.source),n=i.getActivity(e.target);if(!r||!n)return{applied:!1,rejected:st.ACTIVITY_MISSING};if(_r(e.source,e.target,i))return{applied:!1,rejected:st.HIERARCHY_LINK};let o=i.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(fo(a,{source:e.source,target:e.target}))return{applied:!1,rejected:st.CYCLE};let s=(t.newLinkId??qp)(),c={id:s,source:e.source,target:e.target,type:e.type,lag:e.lag,freeSlackHours:null,isCritical:!1};return me({port:i,currentLinks:o,proposedLinks:[...o,c]}).ok?(i.addLink(c),{applied:!0,linkId:s}):{applied:!1,rejected:st.CYCLE}}function $p(e,t){let i=t.getLink(e.linkId);if(!i)return{applied:!1,rejected:st.LINK_MISSING};let r={...i,source:e.source??i.source,target:e.target??i.target,type:e.type??i.type,lag:e.lag??i.lag};if(String(r.source)===String(r.target))return{applied:!1,rejected:st.SELF_LINK};if(!t.getActivity(r.source)||!t.getActivity(r.target))return{applied:!1,rejected:st.ACTIVITY_MISSING};if(_r(r.source,r.target,t))return{applied:!1,rejected:st.HIERARCHY_LINK};let n=t.getAllLinks(),o=n.find(c=>String(c.id)!==String(e.linkId)&&Nr(c)===Nr(r));if(o)return{applied:!1,rejected:st.DUPLICATE,linkId:o.id};let a=n.map(c=>String(c.id)===String(e.linkId)?r:c);return me({port:t,currentLinks:n,proposedLinks:a}).ok?((String(i.source)!==String(r.source)||String(i.target)!==String(r.target))&&t.setLinkEndpoints(e.linkId,r.source,r.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 zp(e,t){let{port:i}=t;return i.getLink(e.linkId)?(i.removeLink(e.linkId),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:st.LINK_MISSING}}var Or=null;function qp(){return Or===null&&(Or=Date.now()),Or+=1,String(Or)}var Dt={FINISH_TO_START:"fs",START_TO_START:"ss",FINISH_TO_FINISH:"ff",START_TO_FINISH:"sf"},Fr={[B.FINISH_TO_START]:Dt.FINISH_TO_START,[B.START_TO_START]:Dt.START_TO_START,[B.FINISH_TO_FINISH]:Dt.FINISH_TO_FINISH,[B.START_TO_FINISH]:Dt.START_TO_FINISH},xe={[Dt.FINISH_TO_START]:B.FINISH_TO_START,[Dt.START_TO_START]:B.START_TO_START,[Dt.FINISH_TO_FINISH]:B.FINISH_TO_FINISH,[Dt.START_TO_FINISH]:B.START_TO_FINISH},Bs=Dt.FINISH_TO_START;function Ws(e){if(e in xe)return xe[e]}var Vs=";",ge={DAY:"d",WEEK:"w",WEEK_DHTMLX:"wk",MONTH:"m",MONTH_DHTMLX:"mon",YEAR:"y"},js=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)(weeks?|wk|w|months?|mon|m|days?|d|years?|y)?)?$/i;var Jp=5,wr=30,yo=365,Xp={[ge.DAY]:1,day:1,days:1,[ge.MONTH]:wr,[ge.MONTH_DHTMLX]:wr,month:wr,months:wr,[ge.YEAR]:yo,year:yo,years:yo},Zp=new Set([ge.WEEK,ge.WEEK_DHTMLX,"week","weeks"]);function xr(e,t={}){let i=[],r=[],n=t.daysPerWeek!==void 0&&Number.isFinite(t.daysPerWeek)&&t.daysPerWeek>0?t.daysPerWeek:Jp,o=e.replace(/\s+/g,"");if(o.length===0)return{specs:i,errors:r};for(let a of o.split(Vs)){if(a.length===0)continue;let s=Qp(a,n);s?i.push(s):r.push(a)}return{specs:i,errors:r}}function Qp(e,t){let i=e.toLowerCase(),r=js.exec(i);if(!r)return null;let[,n,o,a,s,c]=r,l=o?xe[o]:xe[Bs],d=0;if(s!==void 0){let u=Number(s);if(Number.isNaN(u))return null;let f=c!==void 0&&Zp.has(c)?t:Xp[c??ge.DAY],p=u*f;d=a==="-"?-p:p}return{correlativeId:n,type:l,lag:d}}function Ur(e){let{targetActivityId:t,currentLinks:i,desiredSpecs:r}=e,n=[],o=new Map;for(let c of r){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=Mr(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 i)String(c.target)===String(t)&&a.set(Mr(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 Mr(e,t){return`${String(e)}::${t}`}function Hr(e){let{sourceActivityId:t,currentLinks:i,desiredSpecs:r}=e,n=[],o=new Map;for(let c of r){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=Mr(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 i)String(c.source)===String(t)&&a.set(Mr(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 Br(e){let t=Math.sign(e)*Math.round(Math.abs(e));return Object.is(t,-0)?0:t}function Vt(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var Ks={rawInputToConstraintDate(e,t){let i=new Date(e);return i.setUTCHours(0,0,0,0),i.getTime()===e.getTime()?t.getClosestWorkTime({direction:Y.FUTURE,date:e,unit:ut.HOUR}):t.isWorkTime(e,ut.HOUR)?e:i},computeLagBetweenTasks(e,t,i){return i.calculateDuration(e,t)}};function ho(e,t,i){switch(i){case B.FINISH_TO_START:return{sourceDate:e.endDate,targetDate:t.startDate};case B.START_TO_START:return{sourceDate:e.startDate,targetDate:t.startDate};case B.FINISH_TO_FINISH:return{sourceDate:e.endDate,targetDate:t.endDate};case B.START_TO_FINISH:return{sourceDate:e.startDate,targetDate:t.endDate}}}var mo=Ks;var li=class{adapter;reporter;currentCalculationId=0;topoCache=new Sr;expandedLinksCache=new Rr;constructor(t,i=ci){this.adapter=t,this.reporter=i}getCurrentCalculationId(){return this.currentCalculationId}invalidateTopoCache(){this.topoCache.invalidate()}invalidateExpandedLinksCache(){this.expandedLinksCache.invalidate()}invalidateAllCaches(){this.topoCache.invalidate(),this.expandedLinksCache.invalidate()}async schedule(t={}){let i=++this.currentCalculationId,r=Ss(i,()=>this.currentCalculationId),n={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{iy(this.adapter);let o=Ae("schedule.total"),a=Ae("schedule.expandParentLinks"),s=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(s,this.adapter);ae(a);let l=c;if((await si(r)).aborted)return{...n,cancelled:!0};let d=Ae("schedule.scoping"),u=this.adapter.getAllIds(),f=ry(t,l,this.adapter),p=f.links,y=f.idSet;ae(d);let g=Ae("schedule.topologicalSort"),A=oy(this.topoCache,u,l,y);if(ae(g),A.hasCycles)return ae(o),{...n,cycles:[A.cycleNodes]};if((await si(r)).aborted)return{...n,cancelled:!0};let k=Ae("schedule.processConstraints"),_=new Map;if(Ns(A.ordered,this.adapter,_),ae(k),(await si(r)).aborted)return{...n,cancelled:!0};let F=Ae("schedule.asapPass"),h=await ws(A.ordered,p,this.adapter,t,r,_);if(ae(F),(await si(r)).aborted)return{...n,cancelled:!0};let R=Ae("schedule.alapPass"),M=await xs(A.reversed,p,h,this.adapter,t,r);if(ae(R),(await si(r)).aborted)return{...n,cancelled:!0};let T=Ae("schedule.diff"),C=[];for(let[L,j]of M){let K=this.adapter.getActivity(L);if(!K)continue;let it=K.startDate.getTime()!==j.startDate.getTime(),rt=K.endDate.getTime()!==j.endDate.getTime();(it||rt)&&C.push(L)}return ae(T),ae(o),{plans:M,updatedIds:C,cycles:[],cancelled:!1}}catch(o){throw this.reporter.error("[AutoScheduler] Error during scheduling",o),o}}},ty=!1;function ey(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:ty}function Ae(e){return{name:e,startedAt:performance.now()}}function iy(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function ae(e){if(!ey())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function ry(e,t,i){let r=e.triggerId;if(r==null)return{idSet:null,links:t};let n=ks(r,t);return ny(n,t,i)}function ny(e,t,i){let r=new Set(e.activityIds),n=new Set;for(let a of i.getAllActivities()){let s=String(a.id);a.constraintType===v.ALAP&&!r.has(s)&&(n.add(s),r.add(s))}if(n.size===0)return{idSet:r,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:r,links:o}}function oy(e,t,i,r){let n=e.get(t,i);if(n.hasCycles){let a=r?Array.from(r):t;return Cr(a,i)}if(!r)return n;let o=Ts(n.ordered,r);return{ordered:o,reversed:[...o].reverse(),hasCycles:!1,cycleNodes:[]}}function Ys(e,t,i){let r=t.getActivity(e);if(!r)return;let n=i?{...r,endDate:i.endDate}:r,o=t.calendarReader.getCalendar(String(r.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||oe(r.type)&&(s.type===B.START_TO_FINISH||s.type===B.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=ho(c,n,s.type),f=mo.computeLagBetweenTasks(d,u,o);f!==s.lag&&t.setLinkField(s.id,wt.LAG,f)}}function Gs(e,t){let i=t.getActivity(e);i&&oe(i.type)&&(i.durationHours=0)}function Wr(e){let t=0,i=!1;for(let r of e)r.ponderator>0&&(t+=r.ponderator/100*r.progress,i=!0);return i?t:null}function $s(e){return Number(e.toFixed(2))}function Ki(e){for(let t of ay(e))qs(t,e)}function zs(e,t){for(let i of e)qs(i,t)}function ay(e){let t=new Set;e.forEachActivity((r,n)=>{e.getChildren(n).length>0&&t.add(n)});let i=new Map;for(let r of t)i.set(r,sy(r,e));return[...t].sort((r,n)=>(i.get(n)??0)-(i.get(r)??0))}function sy(e,t){let i=0,r=e;for(;r&&r!=="0"&&t.getActivity(r);)i+=1,r=t.getParentId(r);return i}function qs(e,t){let i=t.getChildren(e);if(i.length===0)return;let r=[];for(let n of i){let o=t.getActivity(n);o&&r.push({progress:Number(o.progress??0),ponderator:Number(o.ponderator??0)})}Io(e,r,t)}function Io(e,t,i){let r=i.getActivity(e);if(!r)return;let n=Wr(t);if(n===null){let o=i.getProgressFallback(e);o!==null&&i.setActivityField(e,E.PROGRESS,o);return}i.getProgressFallback(e)===null&&i.setProgressFallback(e,Number(r.progress??0)),i.setActivityField(e,E.PROGRESS,$s(n))}function Js(e,t,i){let r=[e];for(;r.length>0;){let n=r.pop();if(n===void 0)continue;let o=i.getChildren(n);o.length!==0&&(i.setProgressFallback(n,t),r.push(...o))}}function xt(e,t){return(Number(e)||0)*(Number(t)||0)/100}var Yi={SKIP:"skip",FREEZE_WITHOUT_CONTRIBUTION:"freeze-when-no-contribution"};async function di(e,t,i=!0,r={}){let n=t?Gi(e,t):py(e),o=i?r.progressMode??Yi.FREEZE_WITHOUT_CONTRIBUTION:Yi.SKIP;await cy(n,e,o,{recomputeRealWork:r.recomputeRealWork??!1})}function Vr(e,t){Xs(e,t,Yi.SKIP)}async function cy(e,t,i,r={recomputeRealWork:!1}){let o=0;for(let a of e)Xs(a,t,i,r.recomputeRealWork),o+=1,o%200===0&&await ct()}function Gi(e,t){let i=new Set,r=new Map;for(let a of t)ly(a,e,i,r);if(i.size===0)return[];let n=Array.from(i),o=dy(n,r);return Zs(n,o)}function ly(e,t,i,r){let n=t.getParentId(e);for(;n&&!U(n);){if(i.has(n))return;i.add(n);let o=t.getParentId(n);r.set(n,o),n=o}}function dy(e,t){let i=new Map;for(let r of e){if(i.has(r))continue;let n=[],o=new Set,a=r;for(;a&&!U(a)&&!i.has(a)&&!o.has(a);)n.push(a),o.add(a),a=t.get(a)??null;let s=a?i.get(a)??0:0;for(let c=n.length-1;c>=0;c-=1)s+=1,i.set(n[c],s)}return i}function uy(e,t,i){let r=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();(r===null||l<r)&&(r=l),(n===null||d>n)&&(n=d),i&&(o+=fy(c,t.getChildren(s).length>0)),a.push({progress:Number(c.progress??0),ponderator:Number(c.ponderator??0)})}return{minStart:r,maxEnd:n,realWorkSum:o,weightedChildren:a}}function Xs(e,t,i=Yi.FREEZE_WITHOUT_CONTRIBUTION,r=!1){let n=t.getActivity(e);if(!n)return;let o=t.getChildren(e);if(o.length===0)return;let a=uy(o,t,r);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),i!==Yi.SKIP&&Io(e,a.weightedChildren,t),r&&t.setActivityField(e,"realWorkHours",a.realWorkSum)}function fy(e,t){return t?Number(e.realWorkHours)||0:xt(e.workHours,e.progress)}function py(e){let t=yy(e),i=hy(t,e);return Zs(t,i)}function yy(e){let t=new Set;return e.forEachActivity(i=>{i.parentId!==null&&t.add(i.parentId)}),Array.from(t)}function hy(e,t){let i=new Map;for(let r of e)i.set(r,my(r,t));return i}function my(e,t){let i=0,r=e;for(;r&&!U(r)&&t.getActivity(r);)i+=1,r=t.getParentId(r);return i}function Zs(e,t){return[...e].sort((i,r)=>(t.get(r)??0)-(t.get(i)??0))}var Qs={updateActivityDuration:Gs,updateTaskTiming:gy("updateTaskTiming"),adjustLinkLagOnTaskMove:Ys,recordLastStartDate:Iy};function Iy(e,t){let i=t.getActivity(e);i&&t.setLastStartDate(e,i.startDate)}function ve(e,t,i,r){for(let n of t){let o=n in Qs?Qs[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,i,r??null)}}function gy(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 et(){return{valid:!0}}function yt(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function Z(){return{allowed:!0}}function at(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 ft={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 tc={targetField:"name",canEdit(){return Z()},parseInput(e){return typeof e!="string"?J("not_a_string"):G(e)},validate(){return et()},transform(e,t){return tt({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:ft.NAME_ENTRY};var ec={targetField:"description",canEdit(){return Z()},parseInput(e){return typeof e!="string"?J("not_a_string"):G(e.trim())},validate(){return et()},transform(e,t){return tt({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:ft.DESCRIPTION_ENTRY};function qt(e){return e.constraintType??v.ASAP}var jr=100;function Ce(e){return e.progress>=jr}function ht(e,t){return zt(e.type,t.hasChildren(e.id))}function ic(e){return e.progress>0}function rc(e){return e.hasLookaheadTasks}function Me(e,t){return Math.round(Math.ceil(e*t*60)/60)}var ui=e=>({endDate:e});var Kr="UTC";function Se(e,t){if(t){let i=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),r=n=>Number(i.find(o=>o.type===n)?.value);return new Date(Date.UTC(r("year"),r("month")-1,r("day")))}return new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()))}function Yr(e,t){if(!t||t===Kr){let f=new Date(e);return f.setUTCHours(23,59,0,0),f}let i=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),r=f=>Number(i.find(p=>p.type===f)?.value),n=r("year"),o=r("month"),a=r("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 Ay(e,t){let i=Se(t,Kr);for(;!e.isWorkTime(i,ut.DAY);)i=new Date(i),i.setUTCDate(i.getUTCDate()+1),i=Se(i,Kr);return i}function go(e,t){return e.getClosestWorkTime({direction:Y.FUTURE,date:t,unit:ut.HOUR})}function Ao(e,t){let i=Ay(e,t),r=new Date(i);return r.setUTCDate(r.getUTCDate()+1),r.setUTCHours(0,0,0,0),e.getClosestWorkTime({direction:Y.PAST,date:r,unit:ut.HOUR})}var $i=new Set([v.SNET,v.SNLT,v.MSO]),vo=new Set([v.FNET,v.FNLT,v.MFO]),Te=new Set([v.ASAP,v.ALAP]),Gr=v.SNET;function se(e,t,i){let r=Se(e,Kr);if(!$i.has(i)&&!vo.has(i))return r;let n=$i.has(i)?go(t,r):Ao(t,r),o=new Date(r);return o.setUTCHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),o}var De=()=>({constraintType:Gr});var Ue=e=>({constraintDate:e}),nc=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 ac={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"},zi={COMPLETED:"completed",SUMMARY:"summary",HAS_PROGRESS:"has_progress",HAS_LOOKAHEAD_TASKS:"has_lookahead_tasks",SIR_START_AFTER_PROGRESS:"sir_start_after_progress"},sc={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 fi(e,t,i){return fr(e,t,i)}function pi(e,t,i){return pr(e,t,i)}var lc={targetField:"durationHours",canEdit(e,t){return Ce(e)?at("completed","cant_edit_completed_activity"):ht(e,t)?at("summary","summary_column_value"):Z()},parseInput(e,t,i){let r=parseFloat(String(e));return Number.isFinite(r)?G(Me(r,i.hoursPerDay)):J("not_a_number")},validate(e,t,i){return cc(i)?yt(ac.NEGATIVE_DURATION):vy(t,i)?yt("unchanged"):et()},transform(e,t,i){if(cc(t))return tt({},{autoSchedule:!1,postProcessors:[]});let r=Cy(e,t,i),n=Sy(e,t,i,r.violated);return{...tt(n,{autoSchedule:!0,postProcessors:[oc.RECORD_LAST_START_DATE]}),...r.violated?{constraintWarning:pi(r.constraintType,r.constraintDate,dc(e,t,i)??void 0)}:{}}},trackEvent:ft.DURATION_ENTRY};function cc(e){return Math.sign(e)===-1}function vy(e,t){return e===t}function Cy(e,t,i){let r=i.calendars.getCalendar(e.calendarId);if(!r)return{violated:!1};let n=e.constraintType;if(n!==v.FNET&&n!==v.FNLT&&n!==v.MFO)return{violated:!1};let o=r.calculateEndDate(e.startDate,t);return fi(n,e.constraintDate,o)}function Sy(e,t,i,r=!1){let n={};r&&Object.assign(n,De(),Ue(e.startDate));let o=Hi(e.durationHours,t);o&&(n.type=o),n.durationHours=t;let a=dc(e,t,i);return a&&Object.assign(n,ui(a)),n}function dc(e,t,i){let r=i.calendars.getCalendar(e.calendarId);return r?r.calculateEndDate(e.startDate,t):null}var yi=e=>({realWorkHours:e});var Ty=0,Dy=jr,$r={targetField:"progress",canEdit(e,t){return ht(e,t)?at("summary","summary_column_value"):rc(e)?at("has_lookahead_tasks","cant_edit_actvity_with_task"):Z()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?J("not_a_number"):G(t)},validate(e,t,i){return Ey(i)?yt("out_of_range"):et()},transform(e,t,i){let r=we(t),n=e.progress!==t&&r,o=_y(t),a=Py(e,t,i.hierarchy),s={progress:t,autoScheduling:r,...yi(a.get(e.id)??0)},c=o?ky(e,t,r,i.hierarchy,a):[],l=o?Oy(e,t,i.hierarchy):[],d=c.length+l.length>0?[...c,...l]:void 0,u=[],f=o?by(e,t):void 0;return tt(s,{autoSchedule:n,postProcessors:u,cascadeMutations:d,trackingEvents:f})},trackEvent:ft.PROGRESS_ENTRY};function Ey(e){return e<Ty||e>Dy}function _y(e){return e===jr||we(e)}function ky(e,t,i,r,n){return r.getDescendantIds(e.id).map(a=>({activityId:a,fields:Ry(t,i,n.get(a)??0)}))}function Ry(e,t,i){return{progress:e,autoScheduling:t,...yi(i)}}function Py(e,t,i){let r=new Map,n=a=>{let s=0;for(let c of i.getChildHhInfo(a)){let l=i.hasChildren(c.id)?n(c.id):xt(c.workHours,t);r.set(c.id,l),s+=l}return s},o=i.hasChildren(e.id)?n(e.id):xt(e.workHours,t);return r.set(e.id,o),r}function Ly(e,t){let i=[e.id,...t.getDescendantIds(e.id)],r=o=>t.getChildProgressInfo(o).some(a=>t.hasChildren(a.id)),n=o=>t.getAncestorIds(o).length;return i.filter(o=>r(String(o))).map(String).sort((o,a)=>n(a)-n(o))}function Oy(e,t,i){let r=new Map;r.set(e.id,t);for(let a of i.getDescendantIds(e.id))r.set(a,t);let n=[...Ly(e,i),...i.getAncestorIds(e.id)],o=[];for(let a of n){let s=Ny(a,r,i);s!==null&&(r.set(a,s),o.push({activityId:a,fields:{progress:s}}))}return o}function Ny(e,t,i){let r=i.getChildProgressInfo(e).map(o=>({progress:t.has(o.id)?t.get(o.id):o.progress,ponderator:o.ponderator??0})),n=Wr(r);return n===null?null:Number(n.toFixed(2))}function by(e,t){return[{name:ft.PROGRESS_UPDATE_RADIO_BUTTON,properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var uc={targetField:"cost",canEdit(e,t){return ht(e,t)?at("summary","summary_column_value"):Z()},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 et()},transform(e,t,i){let r=Fy(e,t,i.hierarchy);return tt({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:r})},trackEvent:ft.COST_BUDGETED_ENTRY};function Fy(e,t,i){let r=new Map;r.set(e.id,t);let n=[];for(let o of i.getAncestorIds(e.id)){let a=0;for(let s of i.getChildCostInfo(o))a+=r.has(s.id)?r.get(s.id):s.cost;r.set(o,a),n.push({activityId:o,fields:{cost:a}})}return n}var fc={targetField:"usedCost",canEdit(e,t){return ht(e,t)?at("summary","summary_column_value"):Z()},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 et()},transform(e,t,i){let r=wy(e,t,i.hierarchy);return tt({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:r})},trackEvent:ft.COST_SPENT_ENTRY};function wy(e,t,i){let r=new Map;r.set(e.id,t);let n=[];for(let o of i.getAncestorIds(e.id)){let a=0;for(let s of i.getChildUsedCostInfo(o))a+=r.has(s.id)?r.get(s.id):s.usedCost;r.set(o,a),n.push({activityId:o,fields:{usedCost:a}})}return n}var pc={targetField:"workHours",canEdit(e,t){return ht(e,t)?at("summary","summary_column_value"):Z()},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 et()},transform(e,t,i,r){let n=yc(t,e.progress),o=String(r).trim()===""?[]:xy(e,t,n,i.hierarchy);return tt({workHours:t,...yi(n)},{autoSchedule:!1,postProcessors:[],cascadeMutations:o})},trackEvent:ft.LABOR_HOURS_BUDGETED_ENTRY};function yc(e,t){return xt(e,t)}function xy(e,t,i,r){let n=new Map,o=new Map;n.set(e.id,t),o.set(e.id,i);let a=[];for(let s of r.getAncestorIds(e.id)){let c=0,l=0;for(let d of r.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??yc(d.workHours,d.progress);c+=u,l+=f}n.set(s,c),o.set(s,l),a.push({activityId:s,fields:{workHours:c,...yi(l)}})}return a}function qi(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function Co(e,t){return e.getTime()<t.getTime()}function He(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var zr=e=>({durationHours:e});var My="sir-apply",hc={targetField:"startDate",canEdit(e,t,i){return ht(e,t)?at("summary","summary_column_value"):ic(e)?i?.eventSource!==My?at("has_progress","cant_edit_activity_with_progress"):Ce(e)?at("completed","cant_edit_completed_activity"):He(i.newValue)?qi(e.startDate,i.newValue)?Z():i.newValue.getTime()>e.startDate.getTime()?at("sir_start_after_progress","sir_cant_move_start_after_progress"):Z():Z():Z()},parseInput(e,t,i){return He(e)?G(Se(e,"UTC")):J("invalid_date")},validate(e,t,i,r){if(qi(t,i))return yt("unchanged");let n=Uy(e,i,r);return n||et()},transform(e,t,i){let r=i.calendars.getCalendar(e.calendarId);if(!r)throw new Error("startDatePipeline: no calendar resolved (integrity)");let n=go(r,t),o=e.type===D.MILESTONE,a=o?n:r.calculateEndDate(n,e.durationHours),s=n;return{...tt({startDate:n,...ui(a),...o?zr(0):{},...De(),...Ue(s)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:Hy(e,n,r)}},trackEvent:ft.START_DATE_ENTRY};function Uy(e,t,i){let r=i.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!r)return null;let n=Se(r,"UTC");return t.getTime()<n.getTime()?yt("before_parent_start"):null}function Hy(e,t,i){let r=i.calculateEndDate(t,e.durationHours),n=Oe(qt(e),t,r),o=fi(qt(e),e.constraintDate,n);if(o.violated)return pi(o.constraintType,o.constraintDate,n)}var By=99.999,Ic={targetField:"endDate",canEdit(e,t){return ht(e,t)?at("summary","summary_column_value"):Wy(e)?at("completed","cant_edit_completed_activity"):Z()},parseInput(e,t,i){if(!He(e))return J("invalid_date");let r=Se(e,"UTC"),n=i.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(r,ut.DAY)?G(Ao(n,r)):G(n.getClosestWorkTime({direction:"past",date:r,unit:ut.HOUR})):G(r)},validate(e,t,i,r){if(qi(e.endDate,i))return yt("unchanged");if(Vy(i,e))return yt("before_date_origin");if(jy(i,e))return yt("before_start_date");let n=Ky(i,e,r);return n||et()},transform(e,t,i){let r=Yy(e,t),n=Gy(e,t,i,!!r);return{...tt(n,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...r?{constraintWarning:r}:{}}},trackEvent:ft.END_DATE_ENTRY};function Wy(e){return e.progress>=By}function Vy(e,t){return t.dateOrigin?Co(e,t.dateOrigin):!1}function jy(e,t){return Co(e,t.startDate)}function Ky(e,t,i){let r=i.calendars.getCalendar(t.calendarId);return r?r.isWorkTime(e,ut.DAY)?null:yt("not_working_day"):null}function Yy(e,t){if(qt(e)===v.MSO)return;let r=Oe(qt(e),e.startDate,t),n=fi(qt(e),e.constraintDate,r);if(n.violated)return pi(n.constraintType,n.constraintDate,r)}function Gy(e,t,i,r=!1){let n={};oe(e.type)&&!r&&mc(e)?Object.assign(n,Ue(e.startDate)):(r||mc(e))&&Object.assign(n,De(),Ue(e.startDate));let s=$y(e,t,i),c=Hi(e.durationHours,s);return c&&(n.type=c),Object.assign(n,zr(s)),n.endDate=t,n}function mc(e){return Te.has(qt(e))}function $y(e,t,i){let r=i.calendars.getCalendar(e.calendarId);return r?r.calculateDuration(e.startDate,t):e.durationHours}var zy=new Set(Object.values(v)),gc={targetField:"constraintType",canEdit(e,t){return Ce(e)?at("completed","cant_edit_completed_activity"):ht(e,t)?at("summary","summary_column_value"):Z()},parseInput(e){let t=String(e).toLowerCase();return qy(t)?G(t):J("invalid_constraint_type")},validate(){return et()},transform(e,t,i){let r=Jy(e,t,i);return tt(r,{autoSchedule:!0})}};function qy(e){return zy.has(e)}function Jy(e,t,i){let r=Zy(e,t);return{constraintType:t,...nc(Xy(e,t,r,i))}}function Xy(e,t,i,r){if(e.type!==D.MILESTONE||!i||$i.has(t))return i;let n=r.calendars.getCalendar(String(e.calendarId));return n?se(i,n,t):i}function Zy(e,t){return Te.has(t)?null:$i.has(t)?e.startDate:vo.has(t)?e.endDate:e.constraintDate}var Ac={targetField:"constraintDate",canEdit(e,t){return Ce(e)?at("completed","cant_edit_completed_activity"):ht(e,t)?at("summary","summary_column_value"):Z()},parseInput(e){return He(e)?G(e):J("invalid_date")},validate(){return et()},transform(e,t,i){let r=vc(e)?Gr:qt(e),n=i.calendars.getCalendar(e.calendarId);if(!n)throw new Error("constraintDatePipeline: no calendar resolved (integrity)");let o=se(t,n,r),a=Qy(e,o);return tt(a,{autoSchedule:!0})}};function Qy(e,t){return{constraintDate:t,...vc(e)?De():{}}}function vc(e){return Te.has(qt(e))||!e.constraintType}var Cc={targetField:"calendarId",canEdit(){return Z()},parseInput(e){let t=String(e).trim();return th(t)?J("empty_calendar"):G(t)},validate(e,t,i,r){return eh(e.calendarId,i)?yt("unchanged"):r.calendars.getCalendar(i)?et():yt("unknown_calendar")},transform(e,t,i){return tt(ih(e,t,i),{autoSchedule:!0,postProcessors:[]})},trackEvent:ft.CALENDAR_ASSIGNMENT};function th(e){return e===""}function eh(e,t){return e===t}function ih(e,t,i){let r={calendarId:t,assignedDefaultCalendar:!1},n=i.calendars.getCalendar(t);if(n){let o=n.isWorkTime(e.startDate,"hour"),a=n.getClosestWorkTime({date:o?Sc(e.startDate):e.startDate,direction:"future",unit:"hour"});r.startDate=a;let s=rh(e,n);if(s&&(r.constraintDate=s),!e.autoScheduling)return r;Object.assign(r,ui(n.calculateEndDate(a,e.durationHours)))}return r}function rh(e,t){return!e.constraintDate||!e.constraintType?null:wi({...e,constraintDate:Sc(e.constraintDate)},{getClosestWorkTime:({date:i,dir:r})=>t.getClosestWorkTime({date:i,direction:r,unit:ut.HOUR})})}function Sc(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var Tc={targetField:"customId",canEdit(e,t){return ht(e,t)?at("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"):G(t)},validate(){return et()},transform(e,t){return tt({customId:t},{autoSchedule:!1,postProcessors:[]})}};var Dc={targetField:"subcontractId",canEdit(){return Z()},parseInput(e){if(e==null)return G(null);if(typeof e=="string"){let t=e.trim();if(t.length===0)return G(null);let i=Number(t);return!Number.isFinite(i)||!Number.isInteger(i)?J("not_an_integer"):G(i)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?J("not_an_integer"):G(e):J("not_an_integer")},validate(){return et()},transform(e,t){return tt({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function Ji(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 qr(e){return e.some(t=>Ji(t)===null)}var Ec={targetField:"responsableIds",canEdit(){return Z()},parseInput(e){return e==null?G([]):Array.isArray(e)?G(e):J("not_an_array")},validate(e,t,i){return qr(i)?yt("missing_id"):et()},transform(e,t){let i=t.map(Ji).filter(r=>r!==null);return tt({responsableIds:i},{autoSchedule:!1,postProcessors:[]})}};var _c={targetField:"tagIds",canEdit(){return Z()},parseInput(e){return e==null?G([]):Array.isArray(e)?G(e):J("not_an_array")},validate(e,t,i){return qr(i)?yt("missing_id"):et()},transform(e,t){let i=t.map(Ji).filter(r=>r!==null);return tt({tagIds:i},{autoSchedule:!1,postProcessors:[]})}};var nh=new Map([[E.TEXT,tc],[E.DESCRIPTION,ec],[E.DURATION,lc],[E.PROGRESS,$r],[E.COST,uc],[E.USED_COST,fc],[E.HH_WORK_TIME,pc],[E.START_DATE,hc],[E.END_DATE,Ic],[E.CONSTRAINT_TYPE,gc],[E.CONSTRAINT_DATE,Ac],[E.CALENDAR_ID,Cc],[E.CUSTOM_ID,Tc],[E.SUBCONTRACT_ID,Dc],[E.RESPONSABLES,Ec],[E.TAGS,_c]]);function Ee(e){return nh.get(e)}var mt={APPEND:"append",REPLACE:"replace"},Jr={ACTION_BUTTON:"action-button"},Xr={SIR_AUTO_REJECT:"sir-auto-reject"},Zr={DATE_CHANGED:"date_changed",ACTIVITY_DELETED:"activity_deleted"},We={VIOLATION:"constraint_violation"},ee={DISPATCH_MANY:"dispatch-many",INIT:"init",UNDO:"undo",REDO:"redo"};function Ve(e,t){if(!t||t.type!==dr.CONSTRAINT)return null;let i=t.data;return!i?.constraintType||!i.constraintDate?null:{kind:We.VIOLATION,activityId:e,constraintType:i.constraintType,constraintDate:i.constraintDate,projectedDate:i.projectedDate??i.constraintDate,messageKey:t.messageKey}}var oh=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],kc=new Set(oh);function lt(e,t,i,r){e.setActivityFieldDynamic(t,i,r)}function Rc(e,t,i,r){e.setLinkFieldDynamic(t,i,r)}function ce(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:ie(e.constraintDate),dateOrigin:ie(e.dateOrigin),newActivityIds:[...e.newActivityIds],pendingRequestIds:[...e.pendingRequestIds],responsableIds:[...e.responsableIds],tagIds:[...e.tagIds],baselinePoints:e.baselinePoints.map(t=>({...t,startDate:ie(t.startDate),endDate:ie(t.endDate)})),baselineSnapshot:ah(e.baselineSnapshot),criticalPath:sh(e.criticalPath)}}function ie(e){return e===null?null:new Date(e)}function ah(e){return e===null?null:{...e,startDate:ie(e.startDate),endDate:ie(e.endDate)}}function sh(e){return e===null?null:{...e,earlyStart:ie(e.earlyStart),earlyFinish:ie(e.earlyFinish),lateStart:ie(e.lateStart),lateFinish:ie(e.lateFinish)}}var Oc=200;function _e(e,t){let i=new Set([String(e)]);for(let r of t.cascadeMutations??[])i.add(String(r.activityId));return i}async function Q(e,t){let i=new Map,r=0;for(let n of t){r+=1,r%Oc===0&&await ct();let o=e.getActivity(n);o&&i.set(n,nt(o))}return i}function nt(e){return ce(e)}function Qr(e,t){let i=e.getActivity(t);return i?ce(i):null}function ke(e,t,i){Pc(e,t,i.patch);for(let r of i.cascadeMutations??[])Pc(e,r.activityId,r.fields)}function Pc(e,t,i){for(let[r,n]of Object.entries(i)){if(!kc.has(r))throw new Error(`applyFieldChanges: column write to non-writable field "${r}"`);lt(e,t,r,n)}}async function tn(e,t,i,r){let n=[],o=0;for(let a of i){o+=1,o%Oc===0&&await ct();let s=ch(e,t,a,r);s&&n.push(s)}return n}function ch(e,t,i,r){let n=e.getActivity(i);if(!n)return{id:i,kind:N.DELETED,after:null};let o=t.get(i);if(!o&&r?.has(i))return lh(i,r.get(i),n);let a=To(o,n);return dh(a,r,i,n),o&&Object.keys(a).length===0?null:{id:i,kind:o?N.UPDATED:N.CREATED,fields:a,after:nt(n)}}function lh(e,t,i){return t===i.correlativeId?null:{id:e,kind:N.UPDATED,fields:{correlativeId:{before:t,after:i.correlativeId}},after:nt(i)}}function dh(e,t,i,r){if(!t?.has(i)||Object.hasOwn(e,"correlativeId"))return;let n=t.get(i);n!==r.correlativeId&&(e.correlativeId={before:n,after:r.correlativeId})}function To(e,t){let i={},r=e??{},n=t,o=new Set([...Object.keys(r),...Object.keys(n)]);o.delete(b.CALENDAR_DURATION);for(let a of o)(Object.hasOwn(r,a)!==Object.hasOwn(n,a)||!So(r[a],n[a]))&&(i[a]={before:Lc(r[a]),after:Lc(n[a])});return i}function Lc(e){return e===null||typeof e!="object"?e:w(e)}function So(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)=>So(a,t[s]));if(typeof e!="object"||typeof t!="object")return!1;let i=e,r=t,n=Object.keys(i),o=Object.keys(r);return n.length!==o.length?!1:n.every(a=>Object.hasOwn(r,a)&&So(i[a],r[a]))}function en(e,t,i){let r=new Set;r.add(e);for(let n of t)r.add(n);for(let n of i)r.add(n);return r}function Do(e,t){let i=new Set;for(let r of e)i.add(String(r));for(let r of t)i.add(r);return i}function hi(e,t,i,r,n){for(let o of t){if(i.has(o.activityId)||(n.add(o.activityId),r.has(o.activityId)))continue;let a=e.getActivity(o.activityId);if(!a)continue;let s=nt(a);o.before!==void 0&&(s.correlativeId=o.before),r.set(o.activityId,s)}}var uh=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function le(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(uh);if(!t)throw new Error(`[parseFromBackend] unsupported date format "${e}" (expected "YYYY/MM/DD H:MM" or ISO)`);let[,i,r,n,o,a]=t;return new Date(Date.UTC(Number(i),Number(r)-1,Number(n),Number(o),Number(a)))}function mi(e,t,i,r){if(e.getTime()>i.getTime())return 0;if(t.getTime()<i.getTime()||e.getTime()===t.getTime())return 100;let n=r.calculateDuration(e,i),o=r.calculateDuration(e,t);return o===0?0:n*100/o}var fh=e=>e.type===D.PROJECT,ph=(e,t,i)=>{let r=e.calendarId,n=r!=null?i.calendarReader.getCalendar(String(r)):null;if(!n)return 0;let o=a=>a instanceof Date?a:le(String(a));return mi(o(e.startDate),o(e.endDate),t,n)};function yh(e,t,i){let r=[],n=(a,s)=>{let c=i.getActivity(a);c&&c.expectedProgress!==s&&(i.setActivityField(a,"expectedProgress",s),r.push(String(a)))},o=a=>{let s=i.getActivity(a);if(!s)return 0;if(!fh(s)){let d=ph(s,t,i);return n(a,d),d}let c=0;for(let d of i.getChildren(a)){let u=o(d),f=i.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 r}function je(e,t){let i=[];e.forEachActivity((r,n)=>{r.parentId===null&&i.push(n)}),yh(i,t,e)}var hh=e=>e.type===D.PROJECT,mh=e=>gt(e),Ih=(e,t,i,r)=>{let n=mh(e);if(!n)return 0;let o=(n.baseCalendarId!=null?i.getBaseCalendar(`${n.baseCalendarId}-base`):null)??(r?i.getBaseCalendar(r):null);return!o||!n.startDate||!n.endDate?0:mi(n.startDate,n.endDate,t,o)};function Eo(e,t,i,r=null){let n=[],o=(s,c)=>{let l=i.getActivity(s);l&&l.expectedProgressBaseline!==c&&(i.setActivityField(s,"expectedProgressBaseline",c),n.push(s))},a=s=>{let c=i.getActivity(s);if(!c)return 0;if(!hh(c)){let u=Ih(c,t,i,r);return o(s,u),u}let l=0;for(let u of i.getChildrenIds(s)){let f=a(u),p=i.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 Ii(e,t,i=null){let r={getChildrenIds:o=>e.getChildren(String(o)).map(a=>String(a)),getActivity:o=>e.getActivity(o),setActivityField:(o,a,s)=>lt(e,o,a,s),getBaseCalendar:o=>e.calendarReader.getCalendar(o)},n=[];return e.forEachActivity((o,a)=>{o.parentId===null&&n.push(a)}),Eo(n,t,r,i)}var _o=fe.BASELINE;function rn(e){return e===fe.ACTUAL?fe.ACTUAL:_o}var Nc=e=>Math.round(e*100)/100;function gh(e,t){return(t===fe.BASELINE?e.expectedProgressBaseline:e.expectedProgress)??void 0}function Ah(e,t){let i=Nc(e),r=Nc(t);return i>99.99?Pt.DONE:r>i?Pt.OVERDUE:e>0&&i>r?Pt.ADVANCEMENT:e===0&&t===0?Pt.WAITING:e>0&&i<r?Pt.DOING:Pt.WAITING}function de(e,t){let i=[];return e.forEachActivity((r,n)=>{let o=typeof r.progress=="number"?r.progress:0,a=Ah(o,gh(r,t));r.status!==a&&(lt(e,n,E.STATUS,a),i.push(n))}),i}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),i=(n,o)=>a=>a===void 0?t[n]():(t[o](a),r),r={__isMomentShim:!0,clone:()=>ko(t),hours:i("getUTCHours","setUTCHours"),minutes:i("getUTCMinutes","setUTCMinutes"),seconds:i("getUTCSeconds","setUTCSeconds"),milliseconds:i("getUTCMilliseconds","setUTCMilliseconds"),valueOf:()=>t.getTime(),toDate:()=>new Date(t.getTime()),getTime:()=>t.getTime()};return r}ko.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var jt=ko;function vh(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function nn(e){return vh(e)&&!isNaN(e.getTime())}function P(e,t,i,r){if(!nn(new Date(t)))throw new Error(`Invalid date argument for calculateEndDate method. Date: ${t}, Activity: ${JSON.stringify(r)}`);let n=t;return e.calculateEndDate({start_date:new Date(n),duration:i,unit:"hour",task:r})}function Ht(e){if(!nn(new Date(e.dateBaseToCalculate)))throw new Error("Invalid date argument for getClosestWorkTime method");let{dateBaseToCalculate:t,activityCalendar:i,direction:r,activity:n}=e;return i.$gantt.getClosestWorkTime({date:new Date(t),dir:r,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 Ke(e){return Fr[String(Number(e))]??Dt.START_TO_FINISH}var q=Object.freeze({FORWARD:"forward",BACKWARD:"backward"}),Ye=Object.freeze({GREATER:"greater",LESS:"less"}),Jt=Object.freeze({SOURCE:"$source"});var Ch=e=>e?e.$level===1:!1,Sh=e=>e.type===D.PROJECT,Th=e=>e.$level!==0,Dh=e=>e.type===D.TASK,Eh=e=>e.type===D.TASK||e.type===D.MILESTONE,bt={byFirstLevel:Ch,filterByParentType:Sh,avoidSubproject:Th,byTaskType:Dh,byTaskTypeAndMilestone:Eh};function bc(e){let{gantt:t,pendingParentsWithNoLinks:i,calculations:r,linkProperty:n}=e;try{let o=_h({gantt:t,pendingParentsWithNoLinks:i});if(o.length===0)return new Set;let a=kh({gantt:t,subprojectsWithNoLinks:o}),s=Rh({gantt:t,childrenIds:a,linkProperty:n,getArrayOfLinkedActivities:Ph,calculations:r});return new Set(s.map(c=>c.id))}catch(o){throw o}}function _h(e){let{gantt:t,pendingParentsWithNoLinks:i}=e;return t.getTaskByTime().filter(bt.filterByParentType).filter(r=>i.has(r.id)).map(r=>r.id)}function kh(e){let{gantt:t,subprojectsWithNoLinks:i}=e,r=new Set;for(let n of i)t.getChildren(n).filter(s=>{let c=t.getTask(s),l=bt.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(s=>r.add(s));return[...r]}function Rh(e){let{gantt:t,childrenIds:i,linkProperty:r,getArrayOfLinkedActivities:n,calculations:o}=e,a=[];for(let s of i){let c=t.getTask(s),l=c[r]||[];n({gantt:t,links:l,linkDirection:r===Jt.SOURCE?"target":"source"}).every(f=>o.has(f))&&a.push(c)}return a}function Ph(e){let{gantt:t,links:i,linkDirection:r}=e,n=[];for(let o of i){let a=t.getLink(o);if(!a){`${o}`;continue}let s=Number(a[r]);n.push(s)}return n}function Fc({gantt:e,linkProperty:t,direction:i}){try{let r=Lh(e,t);if(i===q.FORWARD)return{chainStartActivities:r,activitiesStartChainButChildrenOfLinkedParents:null};if(i===q.BACKWARD)return Oh(r,e,t)}catch(r){throw console.log("Critical Path",r),r}}function Lh(e,t){return e.getTaskByTime().filter(bt.avoidSubproject).filter(bt.byTaskTypeAndMilestone).filter(i=>!i[t].length)}function Oh(e,t,i){let r=[],n=new Set;return e.forEach(o=>{let a=Number(o.parent),s=t.getTask(a);s&&(s[i].length>0?n.add(o.id):s.constraint_type!==m.FNLT&&r.push(o))}),{chainStartActivities:r,activitiesStartChainButChildrenOfLinkedParents:n}}function wc({gantt:e,direction:t,linkProperty:i}){try{let r=Nh(e),n=new Set,o=new Set,a=new Set;t===q.BACKWARD&&wh(r).forEach(d=>{n.add(d.id)});let s=bh(r,t,i),c=Fh(r,s);return s.forEach(l=>{o.add(l.id)}),c.forEach(l=>{a.add(l.id)}),{parentsWithFullProgress:n,pendingParentsWithNoLinks:o,pendingParentsWithLinks:a}}catch(r){throw r}}function Nh(e){return e.getTaskByTime().filter(bt.filterByParentType).filter(bt.avoidSubproject)}function bh(e,t,i){return e.filter(r=>{let n=r[i];if(!Array.isArray(n))return!1;let o=n.length>0,a=r.constraint_type||"",s=a!==m.FNLT;if(t===q.FORWARD){let c=a!==m.SNET;return!o&&s&&c}else return!o&&s})}function Fh(e,t){let i=new Set(t.map(r=>r.id));return e.filter(r=>!i.has(r.id))}function wh(e){return e.filter(t=>{let i=Number(t.progress);return Number.isNaN(i)?!1:i===100})}function xc({pendingParentsWithLinks:e,gantt:t,direction:i}){try{let r=new Set;return e.forEach(n=>{let o=t.getTask(n),a=xh(i),s=Mh(i),c=o[a];if(!Array.isArray(c))return;Uh(t,c,s).forEach(d=>{r.add(d)})}),r}catch(r){throw r}}function xh(e){return e===q.FORWARD?Jt.SOURCE:"$target"}function Mh(e){return e===q.FORWARD?"target":"source"}function Uh(e,t,i){return t.map(r=>{let o=e.getLink(r)[i];return Number(o)})}var Xi={identifySecondLevelActivities:bc,identifyInitialActivities:Fc,identifyParentsWithAndWithoutLinks:wc,identifyForbiddenActivities:xc};function on(e){return e.length?e.reduce((t,i)=>i.ef>t.ef?i:t):!1}function Ro({linkType:e,lag:t,predecessorTime:i,activityCalendar:r,activity:n}){return e===H.FS&&t===0?Ht({predecessorTime:i,activityCalendar:r,direction:"future",activity:n}):Zi(i,e,r,n)}function Mc({duration:e,constraintDate:t,activityCalendar:i,activity:r}){let n=new Date(t);return{es:P(i,n,e,r),ef:n}}function Uc({duration:e,constraintDate:t,activityCalendar:i,activity:r}){let n=new Date(t),o=P(i,n,e,r);return{es:n,ef:o}}function Zi(e,t,i,r){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:i,direction:o,activity:r})}var Po=class{constructor(t,i,r,n){if(this.linkedActivitiesData=t,this.activity=i,this.gantt=r,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(),i=on(t),r=this.activity.constraint_type;return r===m.SNET?this.handleSNETConstraint(i):r===m.FNLT?this.handleFNLTConstraint(i):i}calculateLinks(){let t=[];for(let i of this.linkedActivitiesData){let r=i.linkType,n=Ke(r),o=i.linkLag,a=i.es,s=i.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(i.linkId,{targetId:String(this.activity.id),...c}),t.push(c))}return t}handleSNETConstraint(t){let i=Uc({duration:this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t&&t.ef>i.ef?t:i}handleFNLTConstraint(t){let i=Mc({duration:-this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t?t.ef>i.ef?i:t:i}calculateSSLink({lag:t,predecessorEs:i}){let r=Ro({linkType:H.SS,lag:t,predecessorTime:i,activityCalendar:this.activityCalendar,activity:this.activity}),n=P(this.activityCalendar,r,t,this.activity);t>0&&(n=Zi(n,H.SS,this.activityCalendar,this.activity));let o=P(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:o}}calculateFFLink({lag:t,predecessorEf:i}){let r=Ro({linkType:H.FF,lag:t,predecessorTime:i,activityCalendar:this.activityCalendar,activity:this.activity}),n=P(this.activityCalendar,r,t,this.activity),o=P(this.activityCalendar,n,-this.activity.duration,this.activity);return t>0&&(o=Zi(o,H.FF,this.activityCalendar,this.activity)),{es:o,ef:n}}calculateFSLink({lag:t,predecessorEf:i}){let r=i;t===0&&(r=Ht({dateBaseToCalculate:i,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let n=P(this.activityCalendar,r,t,this.activity),o=P(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:o}}calculateSFLink({lag:t,predecessorEs:i}){let r=P(this.activityCalendar,i,t,this.activity),n=P(this.activityCalendar,r,-this.activity.duration,this.activity);return t>0&&(n=Zi(n,H.SF,this.activityCalendar,this.activity)),{es:n,ef:r}}},Hc=Po;var Lo=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 i of this.linkedActivitiesData){let r=Ke(i.linkType);if(i.type===D.TASK&&Number(i.progress)>0||i.type===D.PROJECT&&Number(i.progress)===100)continue;let n=i.linkLag,o=i.ls,a=i.lf;if(r===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(r===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(r===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(r===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 i=this.getMinLfFromLinks(t),r=this.calculateSfRestrictionDates();return i?this.getMinLfFromLinks([r,i]):r}else{let i=this.getMinLfFromLinks(t);if(i===!1){let r=this.gantt.getSubtaskDates();return{ls:P(this.activityCalendar,r.end_date,-this.activity.duration,this.activity),lf:r.end_date}}return i}}calculateFFLink({lag:t,workTime:i,lsDataCalculation:r,lfDataCalculation:n}){let o=null,a=null;if(t===0)return o=P(this.activityCalendar,i,n,this.activity),a=P(this.activityCalendar,o,r,this.activity),{ls:a,lf:o};let s=i;return t>0&&(s=this.getLastWorkingHour(s,this.activityCalendar,Y.PAST)),o=P(this.activityCalendar,s,n,this.activity),a=P(this.activityCalendar,o,r,this.activity),{ls:a,lf:o}}calculateFsLink({lag:t,workTime:i,lsDataCalculation:r,lfDataCalculation:n,isMilestone:o=!1}){let a=null,s=null;if(t===0){let l=this.getLastWorkingHour(i,this.activityCalendar,Y.PAST);return a=P(this.activityCalendar,l,n,this.activity),a=this.getLastWorkingHour(a,this.activityCalendar,Y.PAST),s=P(this.activityCalendar,a,r,this.activity),{ls:s,lf:a}}let c=i;return o||(c=this.getLastWorkingHour(i,this.activityCalendar)),a=P(this.activityCalendar,c,n,this.activity),s=P(this.activityCalendar,a,r,this.activity),o||(a=this.getLastWorkingHour(a,this.activityCalendar,Y.PAST)),{ls:s,lf:a}}calculateSFLink({lag:t,workTime:i,lsDataCalculation:r,lfDataCalculation:n}){let o=null,a=null,s=i;return a=P(this.activityCalendar,s,r,this.activity),o=P(this.activityCalendar,a,n,this.activity),{ls:a,lf:o}}calculateSSLink({lag:t,workTime:i,lsDataCalculation:r,lfDataCalculation:n,isMilestone:o=!1}){let a=null,s=null;if(t===0)return s=P(this.activityCalendar,i,r,this.activity),a=P(this.activityCalendar,s,n,this.activity),{ls:s,lf:a};let c=i;return t<0&&!o&&(c=this.getLastWorkingHour(c,this.activityCalendar,"future")),s=P(this.activityCalendar,c,r,this.activity),a=P(this.activityCalendar,s,n,this.activity),{ls:s,lf:a}}getMinLfFromLinks(t=[]){return t.length?t.reduce((i,r)=>r.lf<i.lf?r:i):!1}calculateSfRestrictionDates(){let t=this.activity.constraint_date,i=this.activity.duration;return{ls:P(this.activityCalendar,t,-i,this.activity),lf:t}}getLastWorkingHour(t,i,r=Y.PAST){let n=t instanceof Date?t:new Date(t),o=jt(n).clone();return this.isActivityInInitHour(i,n)&&r===Y.PAST&&(o=o.hours(0).minutes(0).seconds(0).milliseconds(0)),Ht({dateBaseToCalculate:new Date(o),direction:r,activityCalendar:i,activity:this.activity})}isActivityInInitHour(t,i){let r=i instanceof Date?i:new Date(i),o=t.getWorkHours(r)[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),jt.isMoment(i)?i.hours()===a:r.getUTCHours()===a)}},Bc=Lo;function Wc(e){let{parent:t,linkProperty:i,linkDirection:r,calculations:n,gantt:o,direction:a,linkCandidates:s}=e,c=t[i],l=Hh(t),d=null;if(a===q.FORWARD){let u=Bh(c,r,n,o);d=new Hc(u,t,o,s),d=d.calculate()}else{let u=Wh(c,r,n,o);d=new Bc({linksWithActivityData:u,activity:t,parentData:l,gantt:o}).calculate()}return d}function Hh(e){return{duration:e.duration,calendarId:e.calendar_id}}function Bh(e,t,i,r){return e.length===0?[]:e.map(n=>{let o=r.getLink(n);if(!o)return console.warn(`Link not found: ${n}`),null;let a=Number(o[t]),s=i.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 Wh(e,t,i,r){return e.length===0?[]:e.map(n=>{let o=r.getLink(n);if(!o)return console.warn(`Link not found: ${n}`),null;let a=Number(o[t]),s=i.get(a);if(!s)return null;let c=r.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 Kc(e){let{activityData:t,calculations:i,singleParents:r,direction:n}=e;if(Vh(t.id,i))return null;let o=jh(t.id,r),a=Kh(o,i);return a.length===0?null:Yh(a,n)}function Vh(e,t){return t.has(e)}function jh(e,t){let i=t.get(e);return i?i.childrens:[]}function Kh(e,t){return e.filter(i=>t.has(i)).map(i=>t.get(i))}function Yh(e,t){if(t===q.FORWARD){let i=Vc(e,"es"),r=jc(e,"ef");return{es:i,ef:r}}else{let i=Vc(e,"ls"),r=jc(e,"lf");return{ls:i,lf:r}}}function Vc(e,t){return e.reduce((i,r)=>r[t]<i[t]?r:i)[t]}function jc(e,t){return e.reduce((i,r)=>r[t]>i[t]?r:i)[t]}var Oo={parentWithLinks:Wc,parentWithNoLinks:Kc};var No=class{constructor(t){this.activity=t.activity,this.direction=t.direction,this.linkProperty=t.direction===q.FORWARD?"$target":Jt.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 r=[m.FNLT];if(this.shouldCalculateParentWithLinksBackward(r)){this.calculateAndStoreParentWithLinks(this.activity);return}if(this.shouldSetDatesToParentsWithLinks(r)){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 i=t.includes(this.activity.constraint_type),r=!this.calculationOfParentsFromLinks.has(this.activity.id);return i&&r}calculateAndStoreParentWithLinks(t){let i=Oo.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,i),this.calculationOfParentsFromLinks.add(t.id)}areAllLinksCalculated(t){return t.every(i=>this.calculations.has(i))}shouldSetDatesToParentsWithLinks(t){let i=t.includes(this.activity.constraint_type),r=this.calculationOfParentsFromLinks.has(this.activity.id);return i&&r}handleParentWithNoLinks(){let t=Oo.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,r=Array.from(this.calculations).filter(a=>t.includes(a[0])).map(a=>a[1]),{minEs:n,maxEf:o}=r.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(r[0].es),maxEf:new Date(r[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,r=Array.from(this.calculations).filter(a=>t.includes(a[0])).map(a=>a[1]),{minLs:n,maxLf:o}=r.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(r[0].ls),maxLf:new Date(r[0].lf)});this.calculations.set(this.activity.id,{ls:n,lf:o})}getArrayOfIdOfLinkedActivities(t,i=!1){return t.map(r=>{let o=this.gantt.getLink(r)[i||this.linkDirection];return Number(o)})}},Yc=No;var bo=class{constructor({gantt:t,linkProperty:i}){this.gantt=t,this.linkProperty=i,this.structureOfParents=new Map,this.singleParents=new Map}identifyThirdLevelActivities(){try{let t=this.getFirstLevelParents();for(let i of t){let r=this.processEachActivity(i),{activitiesByLevel:n}=r,o=this.getAllLevels(n),a=this.getDeepestLevel(o),s=this.createResult(i,r,a,o);this.structureOfParents.set(i.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 i=new Set,r=new Set,n=new Map;return this.initializeParent(t),this.gantt.eachTask(o=>{this.processActivity(o,i,r,n)},t.id),{parentsIds:i,allTasks:r,activitiesByLevel:n}}initializeParent(t){let i=Number(t.id),r=!!t[this.linkProperty]?.length,n=t.$level;this.singleParents.set(i,{level:n,hasLink:r,childrens:[]})}processActivity(t,i,r,n){let o=Number(t.id),a=Number(t.parent);r.add(o),this.isProjectActivity(t)&&this.addParentInfo(t,i);let c=this.doesParentExist(a);a!=null&&c&&this.addChildToParent(a,o),this.addActivityToLevel(t,n)}isProjectActivity(t){return t.type===D.PROJECT}hasLink(t){return!!t[this.linkProperty]?.length}addParentInfo(t,i){let r=Number(t.id),n=t.$level,o=this.hasLink(t),a={level:n,hasLink:o,childrens:[]};i.add(r),this.singleParents.set(r,a)}doesParentExist(t){return this.singleParents.has(t)}addChildToParent(t,i){this.singleParents.get(t).childrens.push(i)}addActivityToLevel(t,i){let r=t.$level,n=Number(t.parent);i.has(r)||i.set(r,new Map);let o=i.get(r);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,i,r,n){let{activitiesByLevel:o,parentsIds:a,allTasks:s}=i;return{parent:t.id,isALinkedParent:this.hasLink(t),levels:n,allParentChildrens:a,allChildrens:s,childrensByLevel:o,currentResolutionLevel:r,canBeCalculated:!1}}},Gc=bo;var Fo=class{constructor(t,i){this.direction=i,this.gantt=t,this.linkProperty=this.direction===q.FORWARD?"$target":Jt.SOURCE,this.linkDirection=this.direction===q.FORWARD?"source":"target",this.projectDates=t.getSubtaskDates()}tryToCalculateLastLevelChildrens(){this.structureOfParents.forEach(t=>{let{currentResolutionLevel:i,childrensByLevel:r,isALinkedParent:n}=t;if(n)return;let o=r.get(i);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:i,pendingParentsWithLinks:r}=Xi.identifyParentsWithAndWithoutLinks({gantt:this.gantt,direction:this.direction,linkProperty:this.linkProperty});this.parentsWithFullProgress=t,this.pendingParentsWithNoLinks=i,this.pendingParentsWithLinks=r}catch(t){throw t}}identifyForbiddenActivitiesLinkedToParentsWithLinks(){try{this.forbiddenActivitiesLinkedToParentsWithLinks=Xi.identifyForbiddenActivities({pendingParentsWithLinks:this.pendingParentsWithLinks,gantt:this.gantt,direction:this.direction})}catch(t){throw t}}getArrayOfIdOfLinkedActivities(t,i=!1){return t.map(r=>{let o=this.gantt.getLink(r)[i||this.linkDirection];return Number(o)})}async identifyThirdLevelActivities(){try{let{structureOfParents:t,singleParents:i}=new Gc({gantt:this.gantt,linkProperty:this.linkProperty}).identifyThirdLevelActivities();this.structureOfParents=t,this.singleParents=i}catch(t){throw t}}processEachActivity(t){let i=new Set,r=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(r.add(c.id),c.type===D.PROJECT){let u={level:c.$level,hasLink:!!c[this.linkProperty].length,childrens:[]};i.add(c.id),this.singleParents.set(Number(c.id),u)}l&&this.singleParents.has(l)&&this.singleParents.get(l).childrens.push(c.id),n.has(c.$level)||n.set(c.$level,new Map);let d=n.get(c.$level);d.has(Number(c.parent))||d.set(Number(c.parent),[]),d.get(Number(c.parent)).push({id:c.id,isParent:c.type===D.PROJECT,calculated:!1})}.bind(this),t.id),a({parentsIds:i,allTasks:r,activitiesByLevel:n,singleParents:o})})}identifySecondLevelActivities(){try{let t=Xi.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:i}=Xi.identifyInitialActivities({gantt:this.gantt,linkProperty:this.linkProperty,direction:this.direction});this.chainStartActivities=t,i&&(this.activitiesStartChainButChildrenOfLinkedParents=i)}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===D.PROJECT)return;let i=this.calculateStartAndFinishOfChainOrigin(t,this.direction);if(this.direction===q.FORWARD){let{es:r,ef:n}=i;this.calculations.set(t.id,{es:r,ef:n,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}else{let{ls:r,lf:n}=i;this.calculations.set(t.id,{ls:r,lf:n,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}})}catch(t){throw t}}buildDependencyGraph(t){let i=new Map,r=new Set(this.calculations.keys()),n=new Map;return t.forEach(o=>{o&&n.set(o.id,o)}),n.forEach((o,a)=>{if(r.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)||r.has(l)),i.set(a,s)}),{graph:i,activityMap:n,calculatedActivities:r}}topologicalSort(t,i){let r=new Set,n=new Set,o=[],a=s=>{if(n.has(s))throw new Error("Cyclical dependency detected",{cause:{nodeId:s}});if(!r.has(s)&&!i.has(s)){n.add(s);let c=t.get(s)||[];for(let l of c)a(l);n.delete(s),r.add(s),o.push(s)}};for(let s of t.keys())!r.has(s)&&!i.has(s)&&a(s);return o.reverse()}calculateStartAndFinishOfChainOrigin(t=null,i=null){try{let r=t,n=Number(r.progress);n==="0.00"&&(n=0);let o=this.gantt.getCalendar(r.calendar_id);if(!o)throw new Error(`Error trying to get calendar with id: ${r.calendar_id}`);if((i||this.direction)===q.FORWARD){let s=r.start_date,c=r.end_date;return{es:s,ef:c}}else{if(n>=100)return{ls:jt(r.start_date).clone(),lf:jt(r.end_date).clone()};if(n===0)return this.calculateBackwardWhenZeroProgress(r,o);if(n<100&&n>0)return this.calculateWhenProgressIsBetweenZeroAndOneHundred(r,o)}}catch(r){throw r}}calculateBackwardWhenZeroProgress(t,i){let r=jt(t.start_date).clone(),n=jt(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,r=P(i,n,-o,t);else{let c=[m.SNLT,m.MSO],l=[m.FNLT,m.MFO];c.includes(s)&&(r=t.constraint_date,n=P(i,r,o,t)),l.includes(s)&&(n=t.constraint_date,r=P(i,n,-o,t))}return{ls:r,lf:n}}calculateWhenProgressIsBetweenZeroAndOneHundred(t){let i=t.start_date,r=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))r=Math.max(t.end_date,o);else if(n===m.MSO)r=t.end_date;else if(n===m.MFO||s.includes(n)){let c=Math.min(o,t.constraint_date);r=Math.max(c,t.end_date)}return{ls:i,lf:new Date(r)}}initializeActivitiesWithFullProgress(){try{Array.from(this.activitiesWaitingForCalculation).filter(r=>Number(this.gantt.getTask(r).progress)===100).map(r=>this.gantt.getTask(r)).forEach(r=>{let n=r.type===D.PROJECT;this.setDatesForActivityWithFullProgress(r),this.activitiesWaitingForCalculation.delete(r.id),n&&this.pendingParentsWithLinks.has(r.id)&&(this.parentCalculationFromChildren.add(r.id),this.calculationsOfParentThatImpactChildrens.set(r.id,{[this.direction===q.FORWARD?"es":"ls"]:r.start_date,[this.direction===q.FORWARD?"ef":"lf"]:r.end_date}),this.calculationOfParentsFromLinks.add(r.id))})}catch(t){throw t}}doCalculationForParentType(t){let i=new Yc({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)?i.handleParentWithLinks():i.handleParentWithNoLinks()}},Re=Fo;function Gh(e,t,i){let r={es:null,ef:null};if(!e)return r;if([m.SNET,m.SNLT].includes(t)){let n=new Date(e.constraint_date);r.es=n,r.ef=P(i,n,e.duration,e)}else if([m.FNLT,m.FNET].includes(t)){let n=new Date(e.constraint_date);r.es=P(i,n,-e.duration,e),r.ef=n}else if(t===m.MSO){let n=new Date(e.constraint_date);r.es=n,r.ef=P(i,n,e.duration,e)}else if(t===m.MFO){let n=new Date(e.constraint_date);r.es=P(i,n,-e.duration,e),r.ef=n}return r}var an=Gh;var wo=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,i,r=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===D.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=P(a,s,r,this.referenceActivity),c=P(a,l,i,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,o,a))):(c=P(a,s,i,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,o,a)),l=P(a,c,r,this.referenceActivity)),{es:c,ef:l}}calculateSS(t){let i=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),r=t.lag||0,o=this.referenceActivity.duration,a=t.lag||0;return this.calculateSucessorTimes(i.es,r,o,a,H.SS)}calculateFF(t){let i=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,o=t.lag||0,a=t.lag||0;return this.calculateSucessorTimes(i.ef,n,o,a,H.FF)}calculateFS(t){let i=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),r=t.lag||0,o=this.referenceActivity.duration,a=t.lag||0;return this.calculateSucessorTimes(i.ef,r,o,a,H.FS)}calculateSF(t){let i=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,o=t.lag||0,a=t.lag||0;return this.calculateSucessorTimes(i.es,n,o,a,H.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,i,r){if(![H.FS,H.SS,H.FF].includes(i))return t;let o=[H.FS,H.SS].includes(i)?"future":Y.PAST;return Ht({dateBaseToCalculate:t,activityCalendar:r,direction:o,activity:this.referenceActivity})}},$c=wo;var Qi=class extends $c{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Re(this.gantt,"forward").calculateStartAndFinishOfChainOrigin(this.referenceActivity);let t=this.links.map(r=>{let n=this.gantt.getLink(r);if(!n)throw new Error("Link data not found",{cause:{linkId:r}});let o=this.calculateLink(n);return this.linkCandidates?.set(String(n.id),{targetId:String(this.referenceActivity.id),...o}),o}),i=Number(this.referenceActivity.parent);if(this.parentsWithLinks.has(i)){let r=this.gantt.getCalendar(this.referenceActivity.calendar_id),n=this.parentsCalculations.get(i).es,o=P(r,n,this.referenceActivity.duration,this.referenceActivity);t.push({es:n,ef:o})}return on(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var xo=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 i=new Set,r=new Set(t);for(let n of t){let o=this.gantt.getTask(n);o.type===D.PROJECT?this.handleProjectActivity(n,o,i,r):this.handleNonProjectActivity(n,o,i,r)}return{activitiesThatCanBeCalculated:i,pendingActivities:r}}handleProjectActivity(t,i,r,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))&&(r.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))&&(r.add(t),n.delete(t));return}a&&!s&&this.canCalculateParentActivity(i)&&(r.add(t),n.delete(t))}canCalculateParentActivity(t){let i=(t[this.linkProperty]||[]).length===0,r=t.constraint_type;return(this.direction===q.FORWARD?r===m.FNLT||r===m.SNLT:r===m.FNLT)&&i?!0:this.getArrayOfLinkedActivities(t[this.linkProperty]).every(a=>this.calculations.has(a))}handleNonProjectActivity(t,i,r,n){let o=Number(i.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(i.$target.length===0&&i[Jt.SOURCE].length===0){r.add(t),n.delete(t);return}let c=this.getLinkedActivities(i[this.linkProperty]),l=c.every(d=>this.calculations.has(d.id));if(this.direction===q.BACKWARD&&(c.length===0||l)&&s){r.add(t),n.delete(t);return}l&&(r.add(t),n.delete(t))}getLinkedActivities(t){if(!Array.isArray(t))return[];let i=[];for(let r of t){let n=this.gantt.getLink(r);if(!n)continue;let o=n[this.linkDirection],a=this.gantt.getTask(o);a&&i.push(a)}return i}getArrayOfLinkedActivities(t){if(!Array.isArray(t))return[];let i=[];for(let r of t){let n=this.gantt.getLink(r);n&&i.push(Number(n[this.linkDirection]))}return i}},sn=xo;var Mo=(e,t)=>()=>t()===e;var Uo=e=>!e?.fullyParsed;var $h=16,Ge=async e=>performance.now()-e>$h?(await ct(),performance.now()):e;var tr=async({pending:e,activityCalculator:t,calculateFn:i,shouldKeepPending:r,isCalculated:n,onActivityProcessed:o,isCurrent:a})=>{let s=new Set(e),c=performance.now();for(;s.size>0;){if(!a())return;c=await Ge(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(s);if(l.size===0)break;for(let u of l){if(!a())return;c=await Ge(c),i([u])}for(let u of l){if(!a())return;r(u)&&d.add(u),o(u),n(u)&&d.delete(u)}s=d}};var Ho=class extends Re{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 i=new sn({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 tr({pending:this.activitiesWaitingForCalculation,activityCalculator:i,calculateFn:r=>this.calculateStartAndFinishTimes(r),shouldKeepPending:r=>this.calculationOfParentsFromLinks.has(r)&&!this.calculations.has(r),isCalculated:r=>this.calculations.has(r),onActivityProcessed:r=>this.activitiesWaitingForCalculation.delete(r),isCurrent:t})}calculateStartAndFinishTimes(t){t.forEach(i=>{let r=this.gantt.getTask(i);if(r.type===D.PROJECT)return this.doCalculationForParentType(r);if(!r)throw new Error("Error trying to get activity",{cause:{activityId:i}});let n=r.$target,o=r.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(r.calendar_id);if(!c)throw new Error(`Error trying to get calendar with id: ${r.calendar_id}`);let l=Number(r.progress),d=null,u=null,f=null;if(l===100){this.setDatesForActivityWithFullProgress(r);return}l>0&&s.includes(o)?({es:d,ef:u}=this.getDatesForActivityWithZeroProgress(r),f=new Qi({links:n,activity:r,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(i,{es:f.es,ef:f.ef,text:r.text})):{es:d,ef:u}=new Qi({links:n,activity:r,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(i,{es:r.start_date,ef:r.end_date,text:r.text});let p=an(r,o,c);if(a.includes(o)&&(this.constraintsMap.set(i,p),this.totalFloatSnltFnlt.set(i,{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(i,{es:d,ef:u}),this.constraintsMap.set(i,p),r.progress===0)d=p.es,u=p.ef;else{let y=r.end_date;o===m.MFO&&(y=Math.max(p.ef,r.end_date)),d=r.start_date,u=y}this.calculations.set(i,{es:d,ef:u}),this.activitiesWaitingForCalculation.delete(i)})}getTheGreatesDateBetweenRestrictionAndEsEf(t,i,r=Ye.GREATER){if(r===Ye.GREATER)return i.ef>t.ef?i:t;if(r===Ye.LESS)return i.ef<t.ef?i: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,i,r){let n=[m.SNET,m.FNET].includes(t)?Ye.GREATER:Ye.LESS,{es:o,ef:a}=this.getTheGreatesDateBetweenRestrictionAndEsEf(i,r,n);return{es:o,ef:a}}cleanAllActivityParentsFromLinks(t){return t.map(i=>{let r=this.gantt.getLink(i);if(!r)throw new Error("Error trying to get link",{cause:{linkId:i}});let n=r.source,o=r.target;if(!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type===D.PROJECT)&&!(!this.gantt.getTask(o)||this.gantt.getTask(o)?.type===D.PROJECT))return i}).filter(Boolean)}},zc=Ho;var Bo=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,i=null){return i===m.ALAP?this.forwardPathCalculations.get(t):this.calculatedActivities.get(t)}calculateSuccessorTimes(t,i,r=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===D.MILESTONE;if(c&&n===0){let d=P(a,s,i,this.activity),u=P(a,d,r,this.activity);return{ls:d,lf:u}}let l={lag:n,workTime:s,activityCalendar:a,lsDataCalculation:i,lfDataCalculation:r,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,i=!1){let r=this.getValueForSS(t,i),n=-t.lag||0,o=this.activity.duration,a=t.lag;return this.calculateSuccessorTimes(r,n,o,a,H.SS)}calculateFF(t,i){let r=this.getForwardOrBackwardCalculations(Number(t.target)),n=i===m.ALAP?"ef":"lf",o=r[n],a=-this.activity.duration,s=-t.lag||0,c=t.lag;return this.calculateSuccessorTimes(o,a,s,c,H.FF)}calculateFS(t,i){let r="ls";r=i===m.ALAP?"es":"ls";let n=this.getForwardOrBackwardCalculations(Number(t.target),i),o=-this.activity.duration,a=t.lag||0,s=-t.lag||0;return this.calculateSuccessorTimes(n[r],o,s,a,H.FS)}calculateSF(t,i=!1){let r=i?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(r,n,o,a,H.SF)}getEarlyStartFromForwardPath(t){return this.forwardPathCalculations.get(t)}getValueForSS(t,i){return i?this.getEarlyStartFromForwardPath(Number(t.target)).es:this.getForwardOrBackwardCalculations(Number(t.target))["ls"]}calculateDate(t,i,r){let n=jt(i).clone();return P(t,new Date(n),r,this.activity)}getLastWorkingHour(t,i,r=Y.PAST){let n=t instanceof Date?t:new Date(t),o=jt(n).clone();return this.isActivityInInitHour(i,n)&&r===Y.PAST&&(o=o.hours(0).minutes(0).seconds(0).milliseconds(0)),Ht({dateBaseToCalculate:new Date(o),direction:r,activityCalendar:i,activity:this.activity})}isActivityInInitHour(t,i){let r=i instanceof Date?i:new Date(i),o=t.getWorkHours(r)[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),jt.isMoment(i)?i.hours()===a:r.getUTCHours()===a)}calculateFsLink({lag:t,workTime:i,activityCalendar:r,lsDataCalculation:n,lfDataCalculation:o,isMilestone:a=!1}){let s=null,c=null;if(t===0){let d=this.getLastWorkingHour(i,r,Y.PAST);return s=P(r,d,o,this.activity),s=this.getLastWorkingHour(s,r,Y.PAST),c=P(r,s,n,this.activity),{ls:c,lf:s}}let l=i;return a||(l=this.getLastWorkingHour(i,r)),s=P(r,l,o,this.activity),c=P(r,s,n,this.activity),a||(s=this.getLastWorkingHour(s,r,Y.PAST,!0)),{ls:c,lf:s}}calculateFFLink({lag:t,workTime:i,activityCalendar:r,lsDataCalculation:n,lfDataCalculation:o}){let a=null,s=null;if(t===0)return a=P(r,i,o,this.activity),s=P(r,a,n,this.activity),{ls:s,lf:a};let c=i;return t>0&&(c=this.getLastWorkingHour(c,r,Y.PAST)),a=P(r,c,o,this.activity),s=P(r,a,n,this.activity),{ls:s,lf:a}}calculateSSlink({lag:t,workTime:i,activityCalendar:r,lsDataCalculation:n,lfDataCalculation:o,isMilestone:a=!1}){let s=null,c=null;if(t===0)return c=P(r,i,n,this.activity),s=P(r,c,o,this.activity),{ls:c,lf:s};let l=i;return t<0&&!a&&(l=this.getLastWorkingHour(l,r,"future")),c=P(r,l,n,this.activity),s=P(r,c,o,this.activity),{ls:c,lf:s}}calculateSFLink({lag:t,workTime:i,activityCalendar:r,lsDataCalculation:n,lfDataCalculation:o}){let a=null,s=null;return t===0?(s=P(r,i,n),a=P(r,s,o,this.activity),{ls:s,lf:a}):(s=P(r,i,n,this.activity),a=P(r,s,o,this.activity),{ls:s,lf:a})}},qc=Bo;var Wo=class extends qc{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 Re(this.gantt,q.BACKWARD).calculateStartAndFinishOfChainOrigin(this.activity);let t=this.activity.progress>0&&this.activity.progress<100,i=this.gantt.getTask(this.activity.parent),r=!1;i&&(r=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()),r){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(r){n.push(this.calculateTheLsAndLfForTheActivity());let s=this.parentsThatImpactChildrens.get(Number(this.activity.parent)).lf,c=P(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 i=this.activity.duration,r=this.gantt.getCalendar(this.activity.calendar_id);if(!r)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:P(r,n,-i,this.activity),lf:n}}catch(i){throw Error(i.message)}}SnetSnltMsoMinDate(t){let i=Math.min(t.lf,this.projectDates.end_date);return new Date(Math.max(i,this.activity.end_date))}calculateLink(t){let i=this.gantt.getTask(t.target);if(!i||i.progress>0&&i.type!==D.PROJECT)return;let r=this.getSpecialCalculationParamForConstraintLink(),n=this.getSpecialParamForSf(),o=this.getSpecialParamForFF();return{0:()=>this.calculateFS(t,r),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((r,n)=>n.lf<r.lf?n:r):t.reduce((i,r)=>r.ls<i.ls?r:i)}catch(i){throw new Error(`Function: getMinDateFromLinks in LinksConstraintCalculator - ${i.message}`)}}getMinLfFromLinks(t){return t.reduce((i,r)=>r.lf<i.lf?r:i)}getMinDateBasedOnConstraint(t,i=this.constraint){let r=Math.min(t.lf,this.projectDates.end_date),n=this.activity.end_date,o=this.activity.constraint_date;if(i===m.ASAP)return new Date(Math.max(r,n));if(i===m.FNET||i===m.FNLT){let a=Math.min(r,o);return new Date(Math.max(r,a))}if(i===m.ALAP)return new Date(Math.min(r,n))}},Jc=Wo;function zh(e,t,i){let r={ls:null,lf:null};return i===m.MSO&&(r.ls=t.constraint_date,r.lf=P(e,r.ls,t.duration,t)),i===m.MFO&&(r.lf=t.constraint_date,r.ls=P(e,r.lf,-t.duration,t)),r}var Xc=zh;var Vo=class extends Re{constructor(t,i,r){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=i,this.forwardConstraintsMap=r,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 i=new sn({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 tr({pending:this.activitiesWaitingForCalculation,activityCalculator:i,calculateFn:r=>this.calculateStartAndFinishTimes(r),shouldKeepPending:r=>this.calculationOfParentsFromLinks.has(r)&&!this.calculations.has(r),isCalculated:r=>this.calculations.has(r),onActivityProcessed:r=>this.activitiesWaitingForCalculation.delete(r),isCurrent:t})}setDatesToParentsWithLinks(t){if(!t)throw new Error("Error trying to get parent",{cause:{receivedParentData:t}});let i=this.singleParents.get(t.id).childrens,n=Array.from(this.calculations).filter(s=>i.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(i=>{let r=this.gantt.getTask(i);if(!r)throw new Error("Activity not found",{cause:{activityId:i}});let n=r.$source,o=r.constraint_type||m.ASAP,a=Number(r.progress);if(this.activitiesStartChainButChildrenOfLinkedParents.has(i)){if(this.calculationsOfParentThatImpactChildrens.has(Number(r.parent))&&this.calculationsOfParentThatImpactChildrens.get(Number(r.parent))===!1){let{ls:d,lf:u}=this.calculateStartAndFinishOfChainOrigin(r,this.direction);this.setCalculations(r,d,u);return}return this.doCalculationForActivitiesThatStartLinkButHisParentIsLinked(r)}if(r.type===D.PROJECT)return this.doCalculationForParentType(r);if(a===100){this.setDatesForActivityWithFullProgress(r);return}if(this.allLinkedActivitiesHasProgress(n,r)){this.setWhenAllLinkedActivitiesHasProgress(r);return}if(a>0&&a<100&&(o===m.MSO||o===m.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(r,o);return}if(o===m.MSO||o===m.MFO){this.recalculateInBaseRestriction(r,o);return}let{ls:s,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(n,r,o,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(o===m.SNLT||o===m.FNLT)&&({ls:s,lf:c}=this.getTheLessLateInBasEsEfConstraint(r.id,{ls:s,lf:c},o)),this.setCalculations(r,s,c),this.minFromLinks.set(r.id,{ls:l.ls,lf:l.lf})})}getTheLessLateInBasEsEfConstraint(t,i,r){let n=this.forwardConstraintsMap.get(t);if(!n){let o=this.gantt.getTask(t),a=this.gantt.getCalendar(o.calendar_id);n=an(o,r,a)}return i.lf<n.ef?i:{ls:n.es,lf:n.ef}}allLinkedActivitiesHasProgress(t){try{let i=!0;for(let r of t){let n=this.gantt.getLink(r);if(!n)continue;let o=this.gantt.getTask(n.target);o&&(o.type===D.PROJECT&&(i=!1),o.progress===0&&(i=!1))}return i}catch(i){throw new Error(i.message)}}setDatesForActivityWithFullProgress(t){this.setCalculations(t,t.start_date,t.end_date)}setWhenAllLinkedActivitiesHasProgress(t){let i=Number(t.parent),{ls:r,lf:n}=this.calculateStartAndFinishOfChainOrigin(t,q.BACKWARD);if(this.calculationsOfParentThatImpactChildrens.has(i)){r=t.start_date;let o=this.calculationsOfParentThatImpactChildrens.get(i);o&&typeof o=="object"&&o.lf!=null&&(n=new Date(Math.min(n,o.lf)))}this.setCalculations(t,r,n)}setWhenActivitiesHasProgressButLessThanOneHundred(t,i){if(i===m.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(i===m.MFO){let r=Math.min(t.constraint_date,this.projectDates.end_date),n=new Date(Math.max(r,t.end_date));this.setCalculations(t,t.start_date,n);return}}setCalculations(t,i,r){this.calculations.set(t.id,{ls:i,lf:r,text:t.text})}calculateLfandLsFromLinks(t,i,r,n,o){return new Jc({links:t,activity:i,calculatedActivitiesMap:this.calculations,calculatedForwardActivitiesMap:this.forwardPathCalculations,constraint:r,parentsWithFullProgress:n,parentsThatImpactChildrens:o,ganttInstance:this.gantt}).calculate()}recalculateInBaseRestriction(t,i){try{let r=this.gantt.getCalendar(t.calendar_id);if(!r)throw new Error(`Error trying to get calendar with id: ${t.calendar_id}`);let n=Xc(r,t,i);this.constraintMap.set(t,n),this.setCalculations(t,n.ls,n.lf)}catch(r){throw new Error(r.message)}}cleanAllActivityParentsFromLinks(t){return t.map(i=>{let r=this.gantt.getLink(i).source,n=this.gantt.getLink(i).target;if(!(!this.gantt.getTask(r)||this.gantt.getTask(r)?.type===D.PROJECT)&&!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type===D.PROJECT))return i}).filter(Boolean)}doCalculationForActivitiesThatStartLinkButHisParentIsLinked(t){let i=Number(t.parent),r=this.calculationsOfParentThatImpactChildrens.get(i),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,r.lf)),n=t.start_date}else o=r.lf,n=P(this.gantt.getCalendar(t.calendar_id),o,-t.duration,t);if([m.SNLT].includes(t.constraint_type)){let l=this.calculationsOfParentThatImpactChildrens.get(i),d=P(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=P(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}if([m.FNLT].includes(t.constraint_type)){let l=this.calculationsOfParentThatImpactChildrens.get(i),d=t.constraint_date??l.lf;n=new Date(Math.min(d.getTime(),l.lf.getTime())),o=P(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}[m.MSO].includes(t.constraint_type)&&(n=t.constraint_date,o=P(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)),[m.MFO].includes(t.constraint_type)&&(o=t.constraint_date,n=P(this.gantt.getCalendar(t.calendar_id),o,-t.duration,t));let a=this.projectDates.end_date,s=[{ls:n,lf:o}];s.push({ls:P(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((i,r)=>r.lf<i.lf?r:i):!1}},Zc=Vo;function Qc(){return null}var tl=({forward:e,backward:t,id:i,activity:r,gantt:n,projectDates:o})=>({totalFloat:{es:e.calculations.get(i)?.es||0,ef:e.calculations.get(i)?.ef||0,ls:t.calculations.get(i)?.ls||0,lf:t.calculations.get(i)?.lf||0,constraintsMap:e.constraintsMap.get(i),totalFloatSnltFnlt:e.totalFloatSnltFnlt.get(i),totalFloatForMsoMfo:e.totalFloatForMsoMfo.get(i),minFromLinks:t.minFromLinks.get(i),activity:r,gantt:n},freeFloat:{forwardMap:e.calculations||new Map,backwardMap:t.calculations||new Map,activity:r,projectDates:o,gantt:n}});var jo=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,i=Number(this.activity.progress);if(i===100)return 0;if(t||(t=m.ASAP),t===m.ASAP||!t)return i===0?this.calculateAsap():this.calculateAsapWithProgress();if(t===m.ALAP)return i===0?this.calculateAlap():this.calculateAlapWithProgress();if(t===m.SNET||t===m.FNET)return i===0?this.calculateSnetFet():this.calculateSnetFnetSnltWithProgress();if(t===m.SNLT)return i===0?this.calculateSnltFnlt():this.calculateSnetFnetSnltWithProgress();if(t===m.FNLT)return i===0?this.calculateSnltFnlt():this.calculateFnltWithProgress();if(t===m.MSO||t===m.MFO)return i===0?this.calculateMsoMfo():this.calculateMsoMfoWithProgress()}calculateAsap(){let t=this.calculationWithCalendar(this.ls,this.es),i=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,i)/this.gantt.config.hoursPerDay}calculateAsapWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let i=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,i)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateAlap(){let t=this.calculationWithCalendar(this.ls,this.es),i=this.calculationWithCalendar(this.lf,this.ef),r=this.getMinValue(t,i),n=this.calculationWithCalendar(this.lf,this.activity.end_date);return this.getMinValue(r,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 i=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,i)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateFnltWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef),i=this.calculationWithCalendar(this.activity.constraint_date,this.ef);if(this.minFromLinks){let r=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,i,r)/this.gantt.config.hoursPerDay}return this.getMinValue(t,i)/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),i=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,i)/this.gantt.config.hoursPerDay}calculateSnltFnlt(){let t=this.calculationWithCalendar(this.ls,this.es),i=this.calculationWithCalendar(this.lf,this.ef),r=this.getMinValue(t,i);if(!this.totalFloatSnltFnlt&&!this.constrainstMap)return this.getMinValue(t,i)/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,r)/this.gantt.config.hoursPerDay}calculateMsoMfo(){let t=this.calculationWithCalendar(this.ls,this.es),i=this.calculationWithCalendar(this.lf,this.ef),r=this.getMinValue(t,i);if(!this.totalFloatForMsoMfo&&!this.constrainstMap)return this.getMinValue(t,i)/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,r)/this.gantt.config.hoursPerDay}getMinValue(...t){return Math.min(...t)}calculationWithCalendar(t,i){return this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(i),end_date:new Date(t)})}},el=jo;var Ko=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),i=this.getConstraintType();return this.calculateFreeFloatOfLink(i),{activityFreeFloat:t===100?0:this.getFreeFloatBaseConstraint(i),linksFreeFloat:this.linksFreeFloatObject}}getFreeFloatBaseConstraint(t){return t===m.MSO||t===m.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=m.ASAP){let i=this.activity.$source.map(r=>{let{LINK:n,LINK_TYPE:o}=this.getLinkData(r),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(r=>r.freeFloat!==null&&r.freeFloat!==void 0);return this.linksFreeFloatArray=i,i}calculateGeneral(t=m.ASAP){let i=this.getMinFloat(this.linksFreeFloatArray),r=this.calculateFreeFloatForEndOfProject(t),n=[m.SNLT,m.FNLT].includes(t)&&i===null?this.doCalculationForSnltFnlt(t,r,i):this.doGeneralCalculation(r,i);return Math.max(0,n)}getConstraintType(){let{constraint_type:t}=this.activity;return t||(t=m.ASAP),t}getDatesFromSucessorAndPredecessor(t,i,r){let n=r.constraint_type===m.ALAP,o=this.getSucessorAndPredecessorDates({constraint:i,isSuscessorAlap:n,sucessorId:r.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,i){return i===null?t:this.getMinValue(i,t)}doCalculationForSnltFnlt(t,i,r){let n=this.calculateFreeFloatOfRestriction(t);return this.getMinValue(r,i,n)}calculateFreeFloatForEndOfProject(t){let i=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?i?.lf:i?.ef))}calculateFreeFloatOfRestriction(t){let i=this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.activity.constraint_date,t===m.FNLT?i?.ef:i?.es))}getLinkData(t){let i=this.gantt.getLink(t)||{},r=Ke(i.type);return{LINK:i,LINK_TYPE:r}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:i,sucessorId:r,predecessorId:n}){let o=(i?this.backwardMap:this.forwardMap).get(r),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 i=this.activity.constraint_date||new Date,r=this.forwardMap.get(this.activity.id),n=t===m.MSO?r?.es:r?.ef,o=this.calculationWithCalendar(i,n);return Math.max(0,this.parseHoursToDays(o))}getMinValue(...t){let i=t.filter(r=>r!=null);return i.length?Math.min(...i):0}calculationWithCalendar(t,i){if(!(t instanceof Date)||!(i instanceof Date)||!Number.isFinite(t.getTime())||!Number.isFinite(i.getTime()))return Number.NaN;let r=`${i.getTime()}_${t.getTime()}`;if(this.durationCache.has(r))return this.durationCache.get(r);let o=this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(i),end_date:new Date(t)});return this.durationCache.set(r,o),o}parseHoursToDays(t){return t==null?0:t/this.gantt.config.hoursPerDay}getMinFloat(t){if(!t?.length)return null;let i=t.filter(r=>!r.hasProgress).map(r=>r.freeFloat);return i.length===0?null:Math.min(...i)}},il=Ko;var rl=e=>({totalFloat:new el(e.totalFloat).getTotalFloat(),freeFloat:new il(e.freeFloat).getFreeFloat()});var Yo=async({activityIds:e,forward:t,backward:i,gantt:r,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=r.getTask(l);if(!d)continue;let u=tl({forward:t,backward:i,id:l,activity:d,gantt:r,projectDates:n}),{totalFloat:f,freeFloat:p}=rl(u);s.set(l,f),c.set(l,p),a=await Ge(a)}return{totalFloatMap:s,freeFloatMap:c}};var Go=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,i=()=>!0){let r=++this.currentCalculationId,n=Mo(r,this.getCurrentCalculationId),o=()=>n()&&i();try{let a=t||this.gantt;if(this.gantt=a||Qc(),Uo(this.gantt))return!1;let s=new zc(this.gantt);if(await s.calculateAsync(o),!o())return!1;let c=s.calculations,l=s.constraintsMap,d=new Zc(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,i,r=()=>!0){let n=new Map,o=performance.now();for(let[a,s]of t){if(o=await Ge(o),!r())return null;let c=Number(s.targetId),l=this.gantt.getTask(c),d=i.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,i,r){try{let n=this.gantt.getSubtaskDates(),o=Array.from(this.forwardPathCalculations.keys());return await Yo({activityIds:o,forward:t,backward:i,gantt:this.gantt,projectDates:n,isCurrent:r})}catch(n){throw this.forwardPathCalculations?.size,n}}},nl=Go;var qh=e=>e===v.FNET||e===v.FNLT||e===v.MFO,Jh=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function Xh(e,t){let i=e.constraintDate;if(!i||!qh(e.constraintType))return i;let r=Jh(i);if(i.getTime()!==r.getTime())return i;let n=t.getClosestWorkTime({date:r,dir:"future",task:e});return n.getUTCFullYear()===i.getUTCFullYear()&&n.getUTCMonth()===i.getUTCMonth()&&n.getUTCDate()===i.getUTCDate()?wi(e,t):i}function Zh(e){let t=new Map,i=new Map,r=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=i.get(a);if(s!==void 0)return s;let c=e.calculateDuration(n,o);return i.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=r.get(c);if(l!==void 0)return new Date(l);let d=e.getClosestWorkTime({date:n,direction:o,unit:s});return r.set(c,d.getTime()),d}}}}function Qh(e){let t=new Map;e.forEachActivity((n,o)=>t.set(String(o),n));let i=new Map,r=(n,o)=>{let a=i.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=r(String(c),o)+1),i.set(n,l),l};for(let n of t.keys())r(n,new Set);return i}function tm(e){let t=new Set;e.forEachActivity((s,c)=>{t.add(String(c)),s.parentId!==null&&t.add(String(s.parentId))});let i=new Map;for(let s of t){let c=Number(s);Number.isSafeInteger(c)&&c!==0&&i.set(c,(i.get(c)??0)+1)}let r=new Map,n=new Map;for(let s of t){let c=Number(s);Number.isSafeInteger(c)&&c!==0&&i.get(c)===1&&(r.set(s,c),n.set(c,s))}let o=1,a=s=>{let c=String(s),l=r.get(c);if(l!==void 0)return l;for(;n.has(o);)o+=1;return r.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:r.has(String(s))?String(s):null}}function em(e,t){let i=Qh(e),r=new Map;return e.forEachActivity((n,o)=>{let a=String(o);r.set(a,{id:t.toLegacy(a),parent:n.parentId===null?0:t.toLegacy(n.parentId),$level:i.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:Xh(n,e)})}),r}function im(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 i=[],r=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();r.has(a)||(r.add(a),i.push(a),o(t.get(a.id)))}if(i.length<e.size)for(let a of e.values())r.has(a)||i.push(a);return i}function rm(e){let t=null,i=null;return e.forEachActivity(r=>{if(r.startDate){let n=r.startDate.getTime();t=t==null?n:Math.min(t,n)}if(r.endDate){let n=r.endDate.getTime();i=i==null?n:Math.max(i,n)}}),{start_date:new Date(t??0),end_date:new Date(i??0)}}async function ol(e,t){let i=new Map,r=l=>{let d=l==null?"__default__":String(l),u=i.get(d);if(u)return u;let f=e.calendarReader.getCalendar(String(l)),p=Zh(f);return i.set(d,p),p},n=rm(e);await ct();let o=tm(e),a=em(e,o);await ct();let s=[...a.values()].sort((l,d)=>(l.start_date?.getTime()??0)-(d.start_date?.getTime()??0));await ct();let c=im(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:r,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 zo=1e3,nm=e=>typeof e!="number"||!Number.isFinite(e)?null:Object.is(e,-0)?0:e,om=(e,t)=>typeof e!="number"||e<0?null:$o(e,t);function am(e){let t=om(e.freeFloatDays,e.hoursPerDay),i=nm(e.residualHours);return{freeSlackHours:t,isCritical:i!==null&&i<=0&&e.sourceIsCritical&&e.targetIsCritical&&e.targetProgress===0}}async function sm(e,t){let i=new Map,r=0;for(let n of e.values())for(let o in n.linksFreeFloat)if(Object.hasOwn(n.linksFreeFloat,o)){if(++r>=zo&&(r=0,await ct(),!t()))return null;i.set(String(o),n.linksFreeFloat[o])}return t()?i:null}async function cm(e,t,i,r,n){let o=new Map,a=0;for(let s of t.forward?.keys()??[]){if(++a>=zo&&(a=0,await ct(),!n()))return null;let c=r(s);if(c===null)continue;let l=e.getActivity(c);l&&o.set(String(c),dm(s,Number(l.progress??0),t,i))}return n()?o:null}async function lm(e,t,i,r,n,o){let a=new Map,s=0;for(let c of e.getAllLinks()){if(++s>=zo&&(s=0,await ct(),!o()))return null;a.set(String(c.id),am({freeFloatDays:t.get(String(c.id)),residualHours:i.get(String(c.id)),hoursPerDay:n,sourceIsCritical:r.get(c.source)?.isCritical===!0,targetIsCritical:r.get(c.target)?.isCritical===!0,targetProgress:e.getActivity(c.target)?.progress}))}return o()?a:null}var $o=(e,t)=>{if(typeof e!="number"||!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return null;let i=e*t;return Number.isFinite(i)?Object.is(i,-0)?0:i:null};function dm(e,t,i,r){let n=c=>{if(c==null)return null;let l=new Date(c);return Number.isFinite(l.getTime())?l:null},o=i.forward?.get(e),a=i.backward?.get(e),s=$o(i.totalFloat.get(e),r);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:$o(i.freeFloat.get(e)?.activityFreeFloat,r)}}var cn=(e,t)=>e===t||e!==null&&t!==null&&e.getTime()===t.getTime();function qo(e,t,i){let r=e.getActivity(t),n=r?.criticalPath,o=i.criticalPath;r&&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(r.isCritical,i.isCritical)&&Object.is(r.freeSlackHours,i.freeSlackHours)||e.setActivityFields(t,i)}function Jo(e,t,i){let r=e.getLink(t);!r||Object.is(r.freeSlackHours,i.freeSlackHours)&&Object.is(r.isCritical,i.isCritical)||(e.setLinkField(t,"freeSlackHours",i.freeSlackHours),e.setLinkField(t,"isCritical",i.isCritical))}async function Xo(e,t,i=()=>!0){if(!i())return null;let r=await ol(e,t);if(!i())return null;let n=new nl(r);if(!await n.calculate(r,i)){if(!i())return null;throw new Error("critical path calculation aborted")}if(!i())return null;let a={forward:n.forwardPathCalculations,backward:n.backwardPathCalculations,totalFloat:n.totalFloat,freeFloat:n.freeFloat},s=await cm(e,a,t,r.getCanonicalActivityId,i);if(!s)return null;let c=await sm(a.freeFloat,i);if(!c)return null;let l=await lm(e,c,n.linkResidualHours,s,t,i);return l?{activities:s,links:l}:null}async function al(e,t,i=()=>!0){let r=await Xo(e,t,i);if(!r||!i())return!1;for(let[n,o]of r.activities){if(!i())return!1;qo(e,n,o)}for(let[n,o]of r.links){if(!i())return!1;Jo(e,n,o)}return!0}function gi(e){let t=[],i=[];e.forEachActivity((n,o)=>{n.parentId===null&&t.push(String(o))});let r=n=>{let o=e.getActivity(String(n));if(!o)return 0;let a=[...e.getChildren(String(n))],s;if(a.length===0){let c=gt(o),l=c&&Number(c.cost)||0;s=(Number(o.progress)||0)/100*l}else{let c=0;for(let l of a)c+=r(String(l));s=c}return e.setActivityField(String(n),b.REAL_COST,s),i.push(String(n)),s};for(let n of t)r(n);return i}var sl=new Set;var cl=new Set(["activity-outdent","activity-indent"]);var er=new Set([E.TEXT,E.DESCRIPTION,E.COST,E.USED_COST,E.CUSTOM_ID,E.RESPONSABLES,E.SUBCONTRACT_ID,E.TAGS]),um=new Set([I.ACTIVITY_CLIPBOARD_CLEAR,I.ACTIVITY_COPY,I.SELECTION_TOGGLE,I.SELECTION_REPLACE,I.VISIBILITY_SET,I.FILTER_SET,I.SORT_SET,I.SIR_SYNC,I.ACTIVITY_LOOKAHEAD_SYNC,I.PERSISTENCE_ACKNOWLEDGE,I.BASELINE_APPLY,I.PONDERATOR_CRITERION_SET,I.STATUS_CRITERIA_SET]),fm=new Set([I.ACTIVITY_CLIPBOARD_CLEAR,I.ACTIVITY_COPY,I.SELECTION_TOGGLE,I.SELECTION_REPLACE,I.VISIBILITY_SET,I.FILTER_SET,I.SORT_SET]);function dl(e){return!fm.has(e.kind)}var pm=new Set;function ym(e){return e.kind===I.INLINE_EDIT?er.has(e.column):e.kind===I.BULK_EDIT?e.edits.every(t=>er.has(t.column)):!1}function Zo(e,t){return!(um.has(e.kind)||t.has(e.kind)||ym(e))}function ln(e){return e.kind===I.ACTIVITY_LOOKAHEAD_SYNC?e.persistedProgress!==void 0:Zo(e,pm)}function $e(e){return e.kind===I.ACTIVITY_LOOKAHEAD_SYNC?e.persistedProgress!==void 0:Zo(e,sl)}function ul(e){return Zo(e,cl)}function Qo(e){return e.kind===I.ACTIVITY_SET_PROGRESS?!0:e.kind===I.INLINE_EDIT?e.column===E.PROGRESS:e.kind===I.BULK_EDIT?e.edits.some(t=>t.column===E.PROGRESS):!1}function hm(e){return ul(e)&&Qo(e)}var ll=new Set([E.PROGRESS,E.HH_WORK_TIME,E.DURATION,E.COST,E.USED_COST,E.REAL_COST]);function mm(e){return e.kind===I.ACTIVITY_SET_PROGRESS?!0:e.kind===I.INLINE_EDIT?ll.has(e.column):e.kind===I.BULK_EDIT?e.edits.some(t=>ll.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 fl(e,t,i){let r=new Set;t.ran&&r.add(kt.AUTOSCHEDULE),r.add(kt.PARENT_BOUNDS),mm(e)&&r.add(kt.PARENT_PROGRESS),Qo(e)&&r.add(kt.REAL_WORK);let n=!i.skipAutoSchedule;return n&&ul(e)&&r.add(kt.EXPECTED_PROGRESS),n&&hm(e)&&r.add(kt.REAL_COST),n&&$e(e)&&!i.skipCriticalPath&&r.add(kt.CRITICAL_PATH),r}var Rt={INSERT:"insert",REMOVE:"remove",LINK_ADD:"link-add",LINK_REMOVE:"link-remove",LINK_FIELD:"link-field"},dn=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,i){let r=this._journal;r&&(r.before.has(t)||r.before.set(t,ce(i)),r.dirty.add(t))}noteInsert(t){this._journal?.ops.push({kind:Rt.INSERT,activityId:t})}noteRemove(t,i){this._journal?.ops.push({kind:Rt.REMOVE,activityId:t,before:ce(i)})}noteLinkAdd(t){this._journal?.ops.push({kind:Rt.LINK_ADD,linkId:t})}noteLinkRemove(t,i){this._journal?.ops.push({kind:Rt.LINK_REMOVE,linkId:t,before:pl(i)})}noteCorrelativeBefore(t,i){let r=this._journal;if(!r||r.correlativeBefore.has(t))return;let n=r.before.get(t)?.correlativeId;r.correlativeBefore.set(t,typeof n=="number"?n:i)}noteScheduledBefore(t,i){let r=this._journal;if(!r)return;let n=ce(i);r.scheduledBefore.has(t)||r.scheduledBefore.set(t,n),r.before.has(t)||r.before.set(t,n),r.dirty.add(t)}noteLinkField(t,i){let r=this._journal;!r||r.linkFieldCaptured.has(t)||(r.linkFieldCaptured.add(t),r.ops.push({kind:Rt.LINK_FIELD,linkId:t,before:pl(i)}))}noteProgressFallback(t,i){let r=this._journal;!r||r.progressFallbackBefore.has(t)||r.progressFallbackBefore.set(t,i)}};function pl(e){return{...e}}function ta(e,t,i){let r=[];for(let n of i){let o=e.get(n);if(!o)continue;let a=o.pendingRequestIds??[];if(ri({pendingRequestIds:a})&&t.getActivity(n)==null)for(let s of a)r.push({kind:Xr.SIR_AUTO_REJECT,activityId:n,sirId:s,reason:Zr.ACTIVITY_DELETED})}return r}function Mt(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 i=vm(e,t),r=new Map(t.beforeSnap),n=e.peekWriteCapture();if(n){let f=Sm(n);Cm(e,n,f,r,i)}let o=t.sirDetection,a=o===Lt.BEFORE_DIFF?ta(r,e,i):[],s=Am(t.correlativeShifts,i),c=await tn(e,r,i,s),l=o===Lt.AFTER_DIFF?ta(r,e,i):a,d=t.warnings??[],u=gm(t.links??[],n?Im(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 Im(e,t){let i=[];for(let r of t.ops){if(r.kind!==Rt.LINK_FIELD)continue;let n=e.getLink(r.linkId);if(!n)continue;let o={};for(let a of["freeSlackHours","isCritical"])Object.is(r.before[a],n[a])||(o[a]={before:r.before[a],after:n[a]});Object.keys(o).length!==0&&i.push({id:r.linkId,kind:N.UPDATED,fields:o,after:Mt(n)})}return i}function gm(e,t){let i=[],r=new Map;for(let n of e){let o=r.get(n.id);if(o===void 0){r.set(n.id,i.length),i.push(n);continue}let a=i[o];if((a.kind===N.UPDATED||a.kind===N.CREATED)&&n.kind===N.UPDATED){i[o]={...a,fields:{...a.fields,...n.fields},after:n.after};continue}i[o]=n}for(let n of t){let o=r.get(n.id);if(o===void 0){r.set(n.id,i.length),i.push(n);continue}let a=i[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;i[o]={...a,fields:{...a.fields,...s},after:n.after}}return i}function Am(e,t){if(!e||e.length===0)return;let i=new Map;for(let r of e)i.set(r.activityId,r.before),t.add(r.activityId);return i}function vm(e,t){let i=new Set;for(let r of t.touchedIds)i.add(r);for(let r of t.scheduledIds)i.add(r);if(t.includeAllIds)for(let r of e.getAllIds())i.add(r);return i}function Cm(e,t,i,r,n){for(let o of t.dirty){if(i.has(o)||r.has(o))continue;let a=t.before.get(o),s=e.getActivity(o);!a||!s||Object.keys(To(a,s)).length!==0&&(r.set(o,a),n.add(o))}}function Sm(e){return new Set(e.ops.filter(t=>t.kind===Rt.INSERT).map(t=>t.activityId))}function un(e,t,i){if(!e||e==="0")return;let r=i.getChildren(e);if(r.length===0)return;let n=new Map,o=new Set,a=0;for(let l of r){let d=Dm(String(l),t,i);n.set(String(l),d),a+=d,yl(String(l),i)&&o.add(String(l))}let s=a?100/a:0,c=o.size?100/o.size:0;for(let l of r){let d=i.getActivity(l);if(!d)continue;let u=Tm(String(l),d,n,o,a,s,c);u!==null&&i.setActivityField(l,E.PONDERATOR,u)}}function Tm(e,t,i,r,n,o,a){return t.type===D.PROJECT||gt(t)?n?o*(i.get(e)??0):r.has(e)?a:0:!Array.isArray(t.baselinePoints)||t.baselinePoints.length===0?0:null}function yl(e,t){let i=t.getActivity(e);return i?gt(i)?!0:i.type!==D.PROJECT?!1:t.getChildren(e).some(r=>yl(String(r),t)):!1}function Dm(e,t,i){let r=i.getActivity(e);if(!r)return 0;if(r.type===D.PROJECT)return hl(e,t,i);let n=gt(r);return!n||r.type===D.MILESTONE?0:ml(n,t)}function hl(e,t,i){let r=0;for(let n of i.getChildren(e)){let o=i.getActivity(n);if(!o)continue;if(o.type===D.PROJECT){r+=hl(String(n),t,i);continue}let a=gt(o);a&&o.type!==D.MILESTONE&&(r+=ml(a,t))}return r}function ml(e,t){return t===pt.COST?ea(e.cost):t===pt.WORK_HOURS?ea(e.workHours):ea(e.durationDays)}function ea(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){Em(e);let i=Rm(e.adapter),r=km(t,i);r.has(kt.AUTOSCHEDULE)&&await wm(e.adapter,t);let n=r.has(kt.AUTOSCHEDULE)?await Om(e,t.autoscheduleFrom,t.preventSummaryTargetPullback):Fm();return await xm(e.adapter,t,n.scheduledIds,r,i),await Um(e,r,t.now),n}function Em(e){let t=e.adapter.peekWriteCapture();if(!t)return;let i=new Set,r=e.sector.activityCreter??pt.DURATION;for(let[n,o]of t.before){let a=e.adapter.getActivity(n);if(o.type===D.PROJECT||a?.type!==D.PROJECT||gt(a)||!_m(n,e.adapter))continue;let s=n;for(;s!==null&&!U(s);)i.has(s)||(un(s,r,e.adapter),i.add(s)),s=e.adapter.getParentId(s)}}function _m(e,t){let i=[...t.getChildren(e)];for(;i.length>0;){let r=i.pop();if(r===void 0)continue;let n=t.getActivity(r);if(n&&gt(n))return!0;i.push(...t.getChildren(r))}return!1}async function Il(e,t,i){if(e.activityId!==void 0&&!i.adapter.activityExists(e.activityId))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let r=await Q(i.adapter,new Set(i.adapter.getAllIds()));i.scheduler.invalidateAllCaches();let n=e.activityId===void 0?i.adapter.getRootIds():[e.activityId],{scheduledIds:o}=await X({adapter:i.adapter,scheduler:i.scheduler,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId??Et.ROOTS,recomputeParentsFrom:n,now:i.now,options:t});return{ok:!0,changes:await $(i.adapter,{source:e,beforeSnap:r,touchedIds:n,scheduledIds:o,hoursPerDay:i.sector.hoursPerDay})}}function km(e,t){let i=e.autoscheduleFrom!==null,r=!e.options.skipAutoSchedule&&i,n=new Set(fl(e.action,{requested:i,ran:r},e.options));return(e.recomputeParentProgress||t.affectedParents.size>0)&&n.add(kt.PARENT_PROGRESS),n}function Rm(e){let t=new Set,i=new Set,r=e.peekWriteCapture();if(!r)return{affectedParents:t,dirtySeeds:i};let n=o=>{if(o===null||U(o))return;let a=String(o);t.add(a);let s=e.getChildren(a)[0];s!==void 0&&i.add(s)};return Pm(e,r.ops,n),Lm(e,r.before,i,n),{affectedParents:t,dirtySeeds:i}}function Pm(e,t,i){for(let r of t)if(r.kind===Rt.INSERT){let n=e.getActivity(r.activityId);n&&i(n.parentId)}else r.kind===Rt.REMOVE&&i(r.before.parentId)}function Lm(e,t,i,r){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)&&(r(a.parentId),i.add(String(n))),l&&(r(o.parentId),r(a.parentId),i.add(String(n)))}}async function Om(e,t,i=!1){let r=t===Et.ROOTS?{}:{triggerId:t};i&&(r.preventSummaryTargetPullback=!0);let n=await e.scheduler.schedule(r),o=bm(e.adapter,n.updatedIds),a=Nm(e.adapter,n);return Wi(e.adapter,n),{...o,warnings:a}}function Nm(e,t){let i=[];for(let r of t.plans.values()){let n=r.earliestSchedulingStart;if(!n||r.startDate>=n)continue;let o=e.getActivity(r.activityId);!o?.constraintType||!o.constraintDate||i.push({kind:We.VIOLATION,activityId:o.id,constraintType:o.constraintType,constraintDate:o.constraintDate,projectedDate:n,messageKey:We.VIOLATION})}return i}function bm(e,t){let i=[];for(let r of t){let n=String(r);i.push(n);let o=e.getActivity(n);o&&e.noteScheduledBefore(n,o)}return{scheduledIds:i,warnings:[]}}function Fm(){return{scheduledIds:[],warnings:[]}}async function wm(e,t){let i=t.collectDirty?t.collectDirty([]):Do(t.recomputeParentsFrom,[]);i.size!==0&&await di(e,i,!1)}async function xm(e,t,i,r,n){r.has(kt.PARENT_PROGRESS)&&Mm(e,n.affectedParents);let o=t.collectDirty?t.collectDirty(i):Do(t.recomputeParentsFrom,i);for(let a of n.dirtySeeds)o.add(a);await di(e,o,r.has(kt.PARENT_PROGRESS),{recomputeRealWork:r.has(kt.REAL_WORK),progressMode:"freeze-when-no-contribution"})}function Mm(e,t){for(let i of t){if(e.hasChildren(i))continue;let r=e.getProgressFallback(i);r!==null&&(e.setActivityField(i,"progress",r),e.setProgressFallback(i,null))}}async function Um(e,t,i){t.has(kt.EXPECTED_PROGRESS)&&i!==null&&(Hm(e.adapter)&&Ii(e.adapter,i,e.defaultBaseCalendarId??null),je(e.adapter,i),de(e.adapter,e.sector.statusCriteria)),t.has(kt.REAL_COST)&&gi(e.adapter),t.has(kt.CRITICAL_PATH)&&await al(e.adapter,e.sector.hoursPerDay)}function Hm(e){let t=!1;return e.forEachActivity(i=>{gt(i)&&(t=!0)}),t}var Bm=new Set([E.CONSTRAINT_TYPE,E.CONSTRAINT_DATE]),Wm=new Set([v.MSO,v.MFO]);function Ai(e){return Bm.has(e)}function fn(e){return e===E.CONSTRAINT_DATE}function pn(e,t,i,r){let n=i.getActivity(e);if(!n)return!1;let o=n.constraintType;if(!o||Te.has(o)||Wm.has(o))return!1;let a=ia(n.startDate),s=ia(i.getLastStartDate(e));if(!s||!a||a.getTime()!==s.getTime())return!1;let c=Vm(t,o,String(n.calendarId??""),r),l=ia(n.constraintDate);return jm(l,c)?!1:(i.setActivityField(e,"constraintDate",c),!0)}function Vm(e,t,i,r){if(e===null)return null;let n=r.getCalendar(i);return n?se(e,n,t):e}function ia(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 jm(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function yn(e,{postMutationArgs:t,revertTargets:i,revert:r}){let{scheduledIds:n}=await X(e,gl(t)),o=!1;for(let{activityId:a,priorConstraintDate:s}of i){let c=r(a,s);o=o||c}if(o){let a=await X(e,gl(t));n=Ym(n,a.scheduledIds)}return $e(t.action)&&await X(e,Km(t)),{scheduledIds:n}}function gl(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function Km(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function Ym(e,t){let i=new Set(e);for(let r of t)i.add(r);return[...i]}function vi(e,t,i){let r=[];for(let{op:n,finalLinkId:o,rejected:a}of e){if(a!==null)continue;if(n.kind===St.CREATE){if(!o)continue;let d=i.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&&r.push({id:String(o),kind:N.UPDATED,fields:f,after:Mt(d)});continue}r.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:Mt(d)});continue}if(n.kind===St.DELETE){if(i.getLink(n.linkId))continue;let d=t.get(n.linkId);r.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=i.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)}),r.push({id:String(n.linkId),kind:N.UPDATED,fields:l,after:Mt(c)})}return r}function Ci(e,t){let i=new Map;if(!e.getActivity(t))return i;for(let r of e.getIncomingLinkIds(t)){let n=e.getLink(r);n&&i.set(String(n.id),Number(n.lag))}return i}function Si(e,t,i){let r=[];if(!t.getActivity(i))return r;for(let n of t.getIncomingLinkIds(i)){let o=t.getLink(n);if(!o)continue;let a=e.get(String(o.id));a===void 0||a===Number(o.lag)||r.push({id:String(o.id),kind:N.UPDATED,fields:{lag:{before:a,after:Number(o.lag)}},after:Mt(o)})}return r}function hn(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function Al(e,t,i){let{adapter:r,ctx:n,scheduler:o,sector:a}=i,s=Ee(e.column);if(!s)return{ok:!1,reason:S.NO_PIPELINE_FOR_COLUMN};e.column===E.DURATION&&o.invalidateExpandedLinksCache();let c=n.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let l=s.canEdit(c,n.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??S.CANNOT_EDIT,alertKey:l.alertKey};let d=s.parseInput(e.newValue,c,n);if(!d.ok)return{ok:!1,reason:d.reason??S.PARSE_ERROR};let u=Reflect.get(c,s.targetField),f=s.validate(c,u,d.value,n);if(!f.valid)return{ok:!1,reason:f.reason??S.INVALID,alertKey:f.notification?.messageKey};if(e.column===E.CUSTOM_ID&&d.value!==null){let C=r.getActivity(e.activityId),L=C?C.customId:null,j=typeof L=="string"?L:null;if(i.customIdTracker.isCustomIdInUse(String(d.value),j))return{ok:!1,reason:S.CUSTOM_ID_DUPLICATE}}let p=s.transform(c,d.value,n,d.raw),y=_e(e.activityId,p),g=await Q(r,y),A=Ci(r,String(e.activityId)),k=c.constraintDate;ke(r,e.activityId,p),ve(e.activityId,p.postProcessors??[],r,g.get(String(e.activityId))??null);let _=Si(A,r,String(e.activityId));if(e.column===E.CUSTOM_ID){let C=g.get(String(e.activityId)),L=C?C.customId:null,j=typeof L=="string"?L:null,K=typeof d.value=="string"?d.value:null;j!==K&&i.customIdTracker.trackCustomIdChange(j,K)}let F=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:C=>en(e.activityId,y,C),now:i.now,options:t}),h=Ai(e.column),{scheduledIds:R}=await(h?yn({adapter:r,scheduler:o,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{postMutationArgs:F(),revertTargets:fn(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:k}],revert:(C,L)=>pn(C,L,r,n.calendars)}):X({adapter:r,scheduler:o,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},F())),M=(p.trackingEvents??[]).map(C=>({name:C.name,properties:C.properties??{}}));s.trackEvent&&!(e.column===E.PROGRESS&&Number(d.value)<=0)&&M.unshift({name:s.trackEvent,properties:{activity_name:c.name,activity_id:c.id,activity_index:c.correlativeId}});let T=Ve(e.activityId,p.constraintWarning);return{ok:!0,changes:await $(r,{source:e,beforeSnap:g,touchedIds:y,scheduledIds:R,sirDetection:Lt.BEFORE_DIFF,links:_,trackingEvents:M,...T?{warnings:[T]}:{},hoursPerDay:a.hoursPerDay})}}function mn(e){return yr(e)}function In(e,t){return Object.hasOwn(e,t)}function Gm(e){if(e.kind===I.LINK_CREATE)return mn(e.type)?e.lag===void 0||Number.isFinite(e.lag)?null:S.INVALID_LINK_LAG:S.INVALID_LINK_TYPE;if(e.kind===I.LINK_UPDATE){if(In(e,"type")&&!mn(e.type))return S.INVALID_LINK_TYPE;if(In(e,"lag")&&!Number.isFinite(e.lag))return S.INVALID_LINK_LAG}return null}function $m(e){return e.kind===ot.CREATE?mn(e.type)?e.lag===void 0||Number.isFinite(e.lag)?null:S.INVALID_LINK_LAG:S.INVALID_LINK_TYPE:e.kind===ot.UPDATE?In(e,"type")&&!mn(e.type)?S.INVALID_LINK_TYPE:!In(e,"lag")||Number.isFinite(e.lag)?null:S.INVALID_LINK_LAG:e.kind===ot.DELETE?null:S.INVALID_VALUE}function zm(e){for(let t of e){let i=$m(t);if(i!==null)return i}return null}function qm(e,t){let i=new Set,r=new Map;for(let n of e){if(n.kind===ot.CREATE){i.add(String(n.source)),i.add(String(n.target));continue}let o=t.getLink(n.linkId);o&&(i.add(String(o.source)),i.add(String(o.target)),n.kind===ot.UPDATE&&(n.source!==void 0&&i.add(String(n.source)),n.target!==void 0&&i.add(String(n.target))),r.set(n.linkId,{...o}))}return{activityIds:i,links:r}}function Jm(e,t,i,r){return e.map((n,o)=>{let a=n.kind===ot.CREATE?r?.get(o):void 0,s=Ie(n,{port:t,newLinkId:a?()=>a:i.next});return{op:n,finalLinkId:s.applied?s.linkId:null,rejected:s.applied?null:s.rejected??S.INVALID}})}function Xm(e){return new Map([...e].map(([t,i])=>[String(t),i]))}async function vl(e,t,i){let r=Gm(e);return r!==null?{ok:!1,reason:r}:ra([rI(e,i.sector.hoursPerDay)],e,t,i,e.kind===I.LINK_CREATE&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function Cl(e,t,i){let r=zm(e.operations);if(r!==null)return{ok:!1,reason:r};let{hoursPerDay:n}=i.sector,o=e.operations.map(s=>tI(s,n)),a=Zm(e.operations);return ra(o,e,t,i,a)}function Zm(e){let t=new Map;return e.forEach((i,r)=>{i.kind===ot.CREATE&&i.linkId&&t.set(r,i.linkId)}),t.size>0?t:void 0}function Qm(e,t){if(e===void 0)return;let i=new Map,r=new Set,n=()=>{let o=t.linkIdGen.next();for(;t.adapter.getLink(o)!==null||t.isLinkIdReserved(String(o))||r.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))||r.has(String(a)),c=s?n():a;s||t.linkIdGen.bump(a),r.add(String(c)),i.set(o,c)}return i}function tI(e,t){return e.kind===ot.CREATE?{kind:ot.CREATE,source:e.source,target:e.target,type:e.type,lag:Vt(e.lag??0,t)}:e.kind===ot.UPDATE?{kind:ot.UPDATE,linkId:e.linkId,source:e.source,target:e.target,type:e.type,lag:e.lag===void 0?void 0:Vt(e.lag,t)}:{kind:ot.DELETE,linkId:e.linkId}}async function ra(e,t,i,r,n){let{adapter:o,scheduler:a,sector:s,linkIdGen:c}=r;a.invalidateAllCaches();let{activityIds:l,links:d}=qm(e,o),u=await Q(o,l),f=Jm(e,o,c,Qm(n,r));if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!==I.INLINE_EDIT)return{ok:!1,reason:f[0].rejected};let p=eI(f,d,o),{scheduledIds:y,warnings:g}=await X({adapter:o,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:r.now,options:i}),A=vi(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:Xm(d),changes:await $(o,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:y,links:A,warnings:g,hoursPerDay:s.hoursPerDay})}}function eI(e,t,i){for(let r of e){if(r.rejected!==null)continue;let n=iI(r.op,t,i);if(n!==null)return i.hasChildren(n)?Et.ROOTS:String(n)}return null}function iI(e,t,i){return e.kind===ot.CREATE?e.target:e.kind===ot.DELETE?t.get(e.linkId)?.target??null:i.getLink(e.linkId)?.target??null}function rI(e,t){return e.kind===I.LINK_CREATE?{kind:ot.CREATE,source:e.source,target:e.target,type:e.type,lag:Vt(e.lag??0,t)}:e.kind===I.LINK_UPDATE?{kind:ot.UPDATE,linkId:e.linkId,source:e.source,target:e.target,type:e.type,lag:e.lag===void 0?void 0:Vt(e.lag,t)}:{kind:ot.DELETE,linkId:e.linkId}}async function Sl(e,t,i){let{adapter:r,sector:n}=i;if(typeof e.newValue!="string")return{ok:!1,reason:S.INVALID_VALUE};if(!r.getActivity(e.activityId))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let a=e.column===E.CUSTOM_PREDECESSORS,{specs:s,errors:c}=xr(e.newValue,{daysPerWeek:n.hoursPerWeek/n.hoursPerDay});if(c.length>0)return{ok:!1,reason:S.INVALID_VALUE};let l=s.map(g=>({...g,lag:Vt(Br(g.lag),n.hoursPerDay)})),d=new Map;r.forEachActivity(g=>{g.correlativeId!=null&&d.set(String(g.correlativeId),g.id)});let u=g=>d.get(g)??null,f=a?r.getIncomingLinkIds(e.activityId):r.getOutgoingLinkIds(e.activityId),p=[];for(let g of f){let A=r.getLink(g);A&&p.push(A)}let y=a?Ur({targetActivityId:e.activityId,currentLinks:p,desiredSpecs:l,resolveActivityByCorrelative:u}):Hr({sourceActivityId:e.activityId,currentLinks:p,desiredSpecs:l,resolveActivityByCorrelative:u});return ra(y.operations,e,t,i)}var Kt={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=>{U(o.parentId)&&t.push(o)}),t.sort(El);let i=[];Tl(i,t);let r=[],n=0;for(;i.length>0;){let o=i.pop();if(o.correlativeId!==n){let s=typeof o.correlativeId=="number"?o.correlativeId:void 0;r.push({activityId:String(o.id),before:s}),s!==void 0&&e.noteCorrelativeBefore?.(String(o.id),s),nI(o,n)}n+=1;let a=Ui(String(o.id),e);a.sort(El),Tl(i,a)}return r}function Tl(e,t){for(let i=t.length-1;i>=0;i-=1)e.push(t[i])}function Dl(e){let t=e.correlativeId,i=typeof t=="number"?t:Number(t);return Number.isFinite(i)?i:ro}var El=(e,t)=>Dl(e)-Dl(t);function nI(e,t){e.correlativeId=t}function na(e,t){if(!e||e==="0")return;let i=String(e);for(;i!==null;){let{workHours:r,realWorkHours:n}=Rl(i,t);t.setActivityField(i,b.WORK_HOURS,r),t.setActivityField(i,b.REAL_WORK_HOURS,n);let o=t.getActivity(i);if(!o)break;let a=o.parentId;if(!a||U(a))break;i=a}}function _l(e,t){let i=t.getActivity(e);if(!i)return;let r=i.parentId;!r||U(r)||na(r,t)}function kl(e,t,i){for(let r of e){if(i.hasChildren(r))continue;let n=i.getActivity(r);n&&i.setActivityField(r,b.REAL_WORK_HOURS,xt(ir(n,b.WORK_HOURS),ir(n,b.PROGRESS)))}for(let r of t)i.setActivityField(r,b.REAL_WORK_HOURS,Rl(r,i).realWorkHours)}function Rl(e,t){let i=0,r=0;for(let n of t.getChildren(e)){let o=t.getActivity(n);if(!o)continue;let a=ir(o,b.WORK_HOURS);i+=a,r+=oI(n,o,a,t)}return{workHours:i,realWorkHours:r}}function ir(e,t){let i=e[t];return typeof i=="number"&&Number.isFinite(i)?i:0}function oI(e,t,i,r){return r.hasChildren(e)?ir(t,b.REAL_WORK_HOURS):xt(i,ir(t,b.PROGRESS))}function oa(e,t){if(!e||e==="0")return;let i=String(e);for(;i!==null;){let r=t.getChildren(i),n=0;for(let s of r){let c=t.getActivity(s);c&&(n+=aI(c,b.USED_COST))}t.setActivityField(i,b.USED_COST,n);let o=t.getActivity(i);if(!o)break;let a=o.parentId;if(!a||U(a))break;i=a}}function Pl(e,t){let i=t.getActivity(e);if(!i)return;let r=i.parentId;!r||U(r)||oa(r,t)}function aI(e,t){let i=e[t];return typeof i=="number"&&Number.isFinite(i)?i:0}function aa(e,t){if(!e||e==="0")return;let i=String(e);for(;i!==null;){let r=t.getChildren(i),n=0;for(let s of r){let c=t.getActivity(s);c&&(n+=sI(c,b.COST))}t.setActivityField(i,b.COST,n);let o=t.getActivity(i);if(!o)break;let a=o.parentId;if(!a||U(a))break;i=a}}function Ll(e,t){let i=t.getActivity(e);if(!i)return;let r=i.parentId;!r||U(r)||aa(r,t)}function sI(e,t){let i=e[t];return typeof i=="number"&&Number.isFinite(i)?i:0}var gn=Object.freeze({proplannerId:null,description:"",type:D.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}),Ol="New Master Plan",Nl="New Activity";var cI=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],An=new Set(cI);function lI(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 i of Reflect.ownKeys(e))if(typeof i=="symbol"||!An.has(i))throw new Error(`activity-create: rejected override key "${String(i)}" \u2014 not a creation-writable canonical field`);return e}function bl(e,t){let i=e.parentId!=null?t.getActivity(e.parentId):null,r=lI(e.activityOverrides??{}),n=e.numTasksInGantt===0?Ol:Nl,o=r.name??n,a=r.durationHours??e.sector.hoursPerDay,s=r.calendarId??e.sector.defaultCalendar,c=dI(i,e.fallbackStartDate,r.startDate),l={...gn,...r,id:e.id,parentId:e.parentId,uniqueCorrelativeId:e.nextUniqueCorrelativeId,name:o,durationHours:a,calendarId:s,startDate:c,endDate:c},d=r.startDate?new Date(l.startDate):t.getClosestWorkTime({date:l.startDate,dir:Y.FUTURE,task:l});if(!r.startDate&&i&&oe(i.type)){let p=new Date(i.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:te({type:l.type,startDate:d,endDate:u}),newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function dI(e,t,i){return i?new Date(i):e?new Date(e.startDate):t?new Date(t):new Date}var Ti={CREATE:"create",REPARENT:"reparent"};function uI(e){let t=e.type;if(t!==D.TASK&&t!==D.MILESTONE)return null;let i=e.startDate,r=e.endDate;return!(i instanceof Date)||!(r instanceof Date)?null:{type:t,startDate:new Date(i),endDate:new Date(r),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 Pe(e){let t=e.getParent(e.parentId);if(!t)return null;let i=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&he(t.type):fI(t),r=Array.isArray(t.newActivityIds)?t.newActivityIds:[],o={isLookahead:!1,hasNewActivities:!0,newActivityIds:r.some(a=>String(a)===String(e.newChildId))?[...r]:[...r,e.newChildId]};return t.customId!=null&&t.customId!==""&&(o.customId=null),i&&(o.type=co,(e.promotionSource??Ti.CREATE)===Ti.CREATE&&(o.constraintType=v.ASAP,o.constraintDate=null)),{parentId:e.parentId,fields:o,promotionSnapshot:uI(t)}}function fI(e){return he(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function Di(e,t,i,r){let n=t,o=n==="0",a=sa(e,n);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);return d.length===0?l-1:(Math.max(...d)+l)/2}}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);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 ze=Number.MAX_SAFE_INTEGER,Fl=Number.MAX_SAFE_INTEGER-1;function Ot(e){let t=e.correlativeId,i=typeof t=="number"?t:Number(t);return Number.isFinite(i)?i:ze}function sa(e,t){return Ui(t,e)}function wl(e,t,i){let r=e,n=re(e,i);for(;n!=null&&t.has(n);)r=n,n=re(n,i);return r}function Ei(e,t,i){let r=new Set([e]),n=$t(i.getActivity(e)?.parentId);for(;n!=="0"&&!r.has(n);){if(t.has(n))return!0;r.add(n),n=$t(i.getActivity(n)?.parentId)}return!1}function re(e,t){let i=t.getActivity(e);if(!i)return null;let r=$t(i.parentId),n=Wt(r,t),o=n.findIndex(a=>String(a)===String(e));return o<=0?null:n[o-1]??null}function xl(e,t,i,r){let n=Wt(t,e).filter(c=>String(c)!==String(r)).map(c=>e.getActivity(c)).filter(c=>c!==null);if(n.length===0)return 0;let o=n.map(Ot);if(i<=0)return o[0]-1;if(i>=o.length)return o[o.length-1]+1;let a=o[i-1],s=o[i];return(a+s)/2}var pI=new Set([...[...An].filter(e=>e!==b.DURATION_HOURS),"durationDays"]);function vn(e,t){if(e===void 0)return{ok:!0,value:{}};let i=Object.getPrototypeOf(e);if(i!==null&&i!==Object.prototype)return{ok:!1,reason:S.INVALID_VALUE};for(let o of Reflect.ownKeys(e))if(typeof o=="symbol"||!pI.has(o))return{ok:!1,reason:S.INVALID_VALUE};let{durationDays:r,...n}=e;return r!==void 0&&(!Number.isFinite(r)||r<0)?{ok:!1,reason:S.INVALID_VALUE}:{ok:!0,value:{...n,...r===0&&(n.type===void 0||n.type===D.TASK)?{type:D.MILESTONE}:{},...r===void 0?{}:{durationHours:Me(r,t)}}}}async function rr(e,t,i={}){let{adapter:r,scheduler:n,sector:o,calendars:a,activityIdGen:s,uidGen:c}=t;i.skipCacheInvalidation||n.invalidateAllCaches();let l=yI(e,r);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=mI(e.activityId,r,s,t.isActivityIdReserved),y=c.next(),g={id:p,parentId:f?null:e.parentId,sector:{id:o.id,hoursPerDay:o.hoursPerDay,defaultCalendar:SI(a)},numTasksInGantt:r.activityCount(),nextUniqueCorrelativeId:y,activityOverrides:e.overrides??{}},k=bl(g,{getActivity:C=>r.getActivity(C),calculateEndDate:C=>r.calculateEndDate(C),getClosestWorkTime:C=>r.getClosestWorkTime(C)}).newTask;k.realWorkHours=xt(k.workHours,k.progress),gI(k,e,t,u,d,i);let _=i.insertionCorrelativeId??Di(r,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);k.correlativeId=_;let F=new Set([p]);d&&F.add(d.id);let h=d!==null&&r.getChildren(d.id).length===0,R=h?d?.customId:null,M=i.skipBeforeSnap?new Map:await Q(r,F);r.addActivity(k),AI(e,p,d,r,h),R&&t.customIdTracker.releaseCustomId(R),i.skipRollupCascades||(_l(p,r),Pl(p,r),Ll(p,r));let T=vI(r,p,F,i);return{ok:!0,newId:p,parent:d,newActivity:k,beforeSnap:M,initialTouched:F,correlativeShifts:T}}function yI(e,t){let i=U(e.parentId),r=i?null:t.getActivity(e.parentId);if(!i&&!r)return{ok:!1,reason:S.PARENT_NOT_FOUND};if(r!==null&&ri(r))return{ok:!1,reason:S.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:S.ANCHOR_SIBLING_CONFLICT};let a=e.afterSiblingId??e.beforeSiblingId,s=hI(e,t,i,a);return s||{ok:!0,parent:r,anchorSiblingId:a,isRoot:i}}function hI(e,t,i,r){if(r===void 0)return null;let n=t.getActivity(r);if(!n)return{ok:!1,reason:S.ANCHOR_SIBLING_NOT_FOUND};let o=i?"0":e.parentId;return(n.parentId==null?"0":String(n.parentId))!==o?{ok:!1,reason:S.ANCHOR_SIBLING_WRONG_PARENT}:null}function mI(e,t,i,r){let n=()=>{let o=i.next();for(;t.activityExists(o)||r(String(o));)o=i.next();return o};return e===void 0||t.activityExists(e)||r(String(e))?n():(i.bump(e),e)}function II(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function gI(e,t,i,r,n,o){let{adapter:a,customIdTracker:s}=i,c=II(t);if(c!==void 0){if(c.length===0)return;if(!s.isCustomIdInUse(c)){s.registerCustomId(c);return}}let l=o.customIdReferenceId??r,d=l!==void 0,u=d?a.getActivity(l):n;e.customId=s.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function AI(e,t,i,r,n){if(!i)return;let o=Pe({parentId:e.parentId,newChildId:t,isCurrentlyLeaf:n,getParent:a=>r.getActivity(a)??null});if(o){for(let[a,s]of Object.entries(o.fields))lt(r,o.parentId,a,s);o.promotionSnapshot&&r.setPromotionSnapshot(o.parentId,o.promotionSnapshot)}}function vI(e,t,i,r){if(r.skipCorrelativeRecompute)return[];let n=_t(e).filter(o=>o.activityId!==String(t));for(let o of n)i.add(o.activityId);return n}async function CI(e,t,i,r,n){let{newId:o,newActivity:a,beforeSnap:s,initialTouched:c,correlativeShifts:l}=i,d={name:Kt.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:o,created_duration:a.durationHours}};return t.eventSource!==void 0&&(d.properties.event_source=t.eventSource),$(e,{source:t,beforeSnap:s,touchedIds:c,scheduledIds:r,correlativeShifts:l,trackingEvents:[d],hoursPerDay:n})}async function Ml(e,t,i){let{adapter:r,scheduler:n,sector:o}=i,a=vn(e.overrides,o.hoursPerDay);if(!a.ok)return a;let s=await rr({...e,overrides:a.value},i);if(!s.ok)return s;let{newId:c}=s,l=s.newActivity.autoScheduling;r.setActivityField(c,"autoScheduling",!1);let d;try{d=await X({adapter:r,scheduler:n,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:c,recomputeParentsFrom:[c],preventSummaryTargetPullback:!0,now:i.now,options:t})}finally{r.setActivityField(c,"autoScheduling",l)}let{scheduledIds:u}=d;return{ok:!0,changes:await CI(r,e,s,u,o.hoursPerDay)}}function SI(e){for(let i of e.values())if(i.is_default)return i.id;let t=e.values().next();return!t.done&&t.value?t.value.id:"global"}function Ft(e,t){na(e,t),oa(e,t),aa(e,t)}function Cn(e,t){let i=new Set,r=[];for(let n of e){let o=String(n);i.has(o)||(i.add(o),r.push(o))}for(;r.length>0;){let n=r.pop(),o=t.getChildren(n);for(let a of o){let s=String(a);i.has(s)||(i.add(s),r.push(s))}}return i}function Sn(e,t){let i=new Set;for(let r of e){for(let n of t.getOutgoingLinkIds(r))i.add(String(n));for(let n of t.getIncomingLinkIds(r))i.add(String(n))}return[...i]}function TI(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 DI(e,t,i){let r=e.startDate;return!i||!(r instanceof Date)?{}:{endDate:i(r,t)}}function Le(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,i=e.defaultDurationHours,r=Number.isFinite(i),n=TI(e.promotionSnapshot)??(r?{type:ai,durationHours:i,progress:0,autoScheduling:!0,constraintType:v.ASAP,constraintDate:null,hasNewActivities:!1,...DI(t,i,e.computeEndDate)}:{type:ai});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 Tn(e){if(e.idsRemoved.size===0)return null;let t=e.parent.newActivityIds;if(!Array.isArray(t)||t.length===0)return null;let i=t,r=i.filter(n=>!e.idsRemoved.has(n)&&!e.idsRemoved.has(String(n)));return r.length===i.length?null:{parentId:String(e.parent.id),fields:{newActivityIds:[...r],hasNewActivities:r.length>0}}}var Ul=200;async function Hl(e,t,i){let{adapter:r,scheduler:n,customIdTracker:o,sector:a}=i;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:S.ACTIVITY_IDS_EMPTY};for(let C of e.activityIds)if(!r.getActivity(C))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let s=e.activityIds.filter(C=>{let L=r.getActivity(C);return!(L?.correlativeId===0&&L.type===D.PROJECT)}),c=Cn(s,r),l=Sn(c,r),d=new Set;for(let C of e.activityIds){let L=r.getActivity(C);if(!L)continue;let j=L.parentId;if(U(j))continue;let K=String(j);c.has(K)||d.add(K)}let u=new Set([...c,...d]),f=await Q(r,u),p=new Map;for(let C of l){let L=r.getLink(C);L&&p.set(C,{...L})}let y=new Set,g=0;for(let C of c){g+=1,g%Ul===0&&await ct();let L=r.getActivity(C);if(!L)continue;let j=U(L.parentId)?null:r.getActivity(String(L.parentId)),K=j?.hasNewActivities===!0&&j.newActivityIds.some(rt=>String(rt)===String(C));(L.isNewActivity===!0||K)&&y.add(C);let it=L.customId;typeof it=="string"&&it.length>0&&o.releaseCustomId(it)}for(let C of l)r.removeLink(C);let A=nr(r,c),k=0;for(let C of c)k+=1,k%Ul===0&&await ct(),r.removeActivity(C);for(let C of d){let L=r.getActivity(C);if(!L)continue;EI(L,y,r);let j=r.getChildren(C),K=Le({parent:L,remainingChildIds:j.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:r.getPromotionSnapshot(C),computeEndDate:(it,rt)=>r.calculateEndDate({startDate:it,durationHours:rt,task:L}),idsRemoved:c});if(!K){Vr(C,r);continue}for(let[it,rt]of Object.entries(K.fields))lt(r,C,it,rt);if(L.customId==null||L.customId===""){let it=re(C,r),rt=it?r.getActivity(it)?.customId:null,vt=o.generateCustomIdForRestoredChild(typeof rt=="string"&&rt?rt:null);r.setActivityField(C,b.CUSTOM_ID,vt)}}for(let C of d)Ft(C,r);let _=_t(r),{scheduledIds:F}=await X({adapter:r,scheduler:n,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:Et.ROOTS,recomputeParentsFrom:d,now:i.now,options:t}),h={name:Kt.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:c.size}};e.eventSource!==void 0&&(h.properties.event_source=e.eventSource);let R=new Map;for(let[C,L]of p)R.set(C,L);let M=new Map;for(let C of c){let L=f.get(String(C));L&&M.set(String(C),L)}let T=await $(r,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:F,sirDetection:Lt.AFTER_DIFF,links:qe(p),trackingEvents:[h],hoursPerDay:a.hoursPerDay,correlativeShifts:_});return{ok:!0,changes:A.length>0?{...T,viewState:A}:T,__beforeSnap:M,__beforeLinks:R}}function EI(e,t,i){let r=Tn({parent:e,idsRemoved:t});if(r)for(let[n,o]of Object.entries(r.fields))lt(i,r.parentId,n,o)}function nr(e,t){let i=[];for(let r of t){let n=e.isChecked(r),o=e.isVisible(r);!n&&o||i.push({activityId:String(r),...n?{checked:{before:!0,after:!1}}:{},...o?{}:{visible:{before:!1,after:!0}}})}return i}function qe(e){let t=[];for(let[i,r]of e.entries())t.push({id:i,kind:N.DELETED,fields:{source:{before:String(r.source),after:void 0},target:{before:String(r.target),after:void 0},type:{before:r.type,after:void 0},lag:{before:Number(r.lag),after:void 0}},after:null});return t}async function Vl(e,t,i){let r=_I(e,i);if(r)return{ok:!1,reason:r};let n=RI(e,i);if(!n.ok)return n;let o=e.mode===mt.REPLACE?new Set(i.adapter.getAllIds().map(h=>String(h))):new Set,a=e.mode===mt.REPLACE?await Q(i.adapter,o):new Map,s=e.mode===mt.REPLACE?FI(i):new Map,c=e.mode===mt.REPLACE?nr(i.adapter,o):[];i.scheduler.invalidateAllCaches();let l=[];if(e.mode===mt.REPLACE){for(let h of s.keys()){let R=Ie({kind:ot.DELETE,linkId:h},{port:i.adapter});if(!R.applied)return{ok:!1,reason:R.rejected??S.INVALID};l.push({op:{kind:ot.DELETE,linkId:h},finalLinkId:h,rejected:null})}for(let h of o){let R=i.adapter.getActivity(h)?.customId;typeof R=="string"&&R.length>0&&i.customIdTracker.releaseCustomId(R),i.adapter.removeActivity(h)}}let d=await bI(e,n.plan.items,i);if(!d.ok)return d;let u=jl(e)?[]:_t(i.adapter),f=new Set(n.plan.items.map(h=>String(h.activityId))),p=u.filter(h=>!f.has(h.activityId)),y=e.mode===mt.REPLACE?new Set(o):new Set;hi(i.adapter,u,f,a,y);for(let h of n.plan.items)y.add(String(h.activityId));let g=n.plan.links.map(h=>({operation:{kind:ot.CREATE,source:h.source,target:h.target,type:h.type,lag:Vt(h.lag??0,i.sector.hoursPerDay)},linkId:h.linkId})),A=br(g,{port:i.adapter,preserved:s});if(!A.applied)return{ok:!1,reason:A.rejected??S.INVALID};for(let{operation:h,linkId:R}of g)l.push({op:h,finalLinkId:R,rejected:null});let k=n.plan.items.map(h=>h.activityId),{scheduledIds:_}=await X({adapter:i.adapter,scheduler:i.scheduler,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.items.length>0||e.links.length>0?Et.ROOTS:null,recomputeParentsFrom:k,now:i.now,options:t}),F=await $(i.adapter,{source:e,beforeSnap:a,touchedIds:y,scheduledIds:_,links:vi(l,s,i.adapter),hoursPerDay:i.sector.hoursPerDay,correlativeShifts:p,...e.mode===mt.REPLACE?{sirDetection:Lt.AFTER_DIFF}:{}});return{ok:!0,changes:c.length>0?{...F,viewState:c}:F,...e.mode===mt.REPLACE?{__beforeSnap:a,__beforeLinks:wI(s)}:{}}}function _I(e,t){if(e.mode!==mt.APPEND&&e.mode!==mt.REPLACE)return S.INVALID;let i=new Set,r=new Set;for(let o of e.items){if(o.batchId.length===0||i.has(o.batchId))return S.INVALID;if(i.add(o.batchId),o.index!==void 0&&(!Number.isInteger(o.index)||o.index<0))return S.INVALID;if(o.activityId!==void 0){let a=String(o.activityId);if(a.length===0||a==="0"||r.has(a))return S.INVALID;r.add(a)}}for(let o of e.items)if(!la(o.parent,!0,e.mode,i,t))return S.PARENT_NOT_FOUND;if(kI(e.items))return S.INVALID;let n=new Set;for(let o of e.links){if(!Object.values(B).includes(o.type))return S.INVALID_LINK_TYPE;if(o.lag!==void 0&&!Number.isFinite(o.lag))return S.INVALID_LINK_LAG;if(!la(o.source,!1,e.mode,i,t)||!la(o.target,!1,e.mode,i,t))return S.ACTIVITY_NOT_FOUND;if(o.linkId!==void 0){let a=String(o.linkId);if(a.length===0||n.has(a))return S.INVALID;n.add(a)}}return null}function la(e,t,i,r,n){return typeof e=="string"?e==="0"?t:i===mt.APPEND&&n.adapter.getActivity(String(e))!==null:e!==null&&e.batchId.length>0&&r.has(e.batchId)}function kI(e){let t=new Map;for(let r of e)typeof r.parent!="string"&&t.set(r.batchId,r.parent.batchId);let i=new Set;for(let r of e){let n=new Set,o=r.batchId;for(;o!==void 0&&!i.has(o);){if(n.has(o))return!0;n.add(o),o=t.get(o)}for(let a of n)i.add(a)}return!1}function RI(e,t){let i=new Map;for(let d of e.items){let u=vn(d.overrides,t.sector.hoursPerDay);if(!u.ok)return u;i.set(d.batchId,u.value)}let r=new Map,n=new Set;for(let d of e.items){let u=PI(d.activityId,e.mode,n,t);n.add(String(u)),r.set(d.batchId,u)}let o=new Set,a=e.links.map(d=>{let u=LI(d.linkId,e.mode,o,t);return o.add(String(u)),u}),s=OI(e,r,t),c=[];for(let d of e.items){let u=r.get(d.batchId),f=s.get(d.batchId);if(u===void 0||f===void 0)return{ok:!1,reason:S.INVALID};let p=typeof d.parent=="string"?null:d.parent.batchId,y=typeof d.parent=="string"?d.parent:r.get(d.parent.batchId);if(y===void 0)return{ok:!1,reason:S.PARENT_NOT_FOUND};c.push({input:d,activityId:u,parentId:y,parentBatchId:p,insertionCorrelativeId:f,overrides:i.get(d.batchId)??{}})}let l=[];for(let[d,u]of e.links.entries()){let f=Wl(u.source,r),p=Wl(u.target,r),y=a[d];if(f===null||p===null||y===void 0)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};l.push({source:f,target:p,type:u.type,lag:u.lag??0,linkId:y})}return{ok:!0,plan:{items:c,links:l}}}function PI(e,t,i,r){if(e!==void 0&&(t===mt.REPLACE||r.adapter.getActivity(e)===null&&!r.isActivityIdReserved(String(e)))&&!i.has(String(e)))return r.activityIdGen.bump(e),e;let o=r.activityIdGen.next();for(;i.has(String(o))||t===mt.APPEND&&(r.adapter.getActivity(o)!==null||r.isActivityIdReserved(String(o)));)o=r.activityIdGen.next();return o}function LI(e,t,i,r){if(e!==void 0&&(t===mt.REPLACE||r.adapter.getLink(e)===null&&!r.isLinkIdReserved(String(e)))&&!i.has(String(e)))return r.linkIdGen.bump(e),e;let o=r.linkIdGen.next();for(;i.has(String(o))||t===mt.APPEND&&(r.adapter.getLink(o)!==null||r.isLinkIdReserved(String(o)));)o=r.linkIdGen.next();return o}function OI(e,t,i){if(jl(e)){let s=i.adapter.activityCount();return new Map(e.items.map((c,l)=>[c.batchId,s+l]))}let r=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)?[]:sa(i.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(!r.has(c[l])){l+=1;continue}let d=l;for(;l<c.length&&r.has(c[l]);)l+=1;let u=l-d,f=d>0?Bl(c[d-1],i):null,p=l<c.length?Bl(c[l],i):null;for(let y=0;y<u;y+=1){let g=c[d+y],A=a.get(g);A!==void 0&&o.set(A,NI(f,p,y+1,u))}}}return o}function jl(e){return e.mode===mt.APPEND&&e.items.every(t=>t.parent==="0"&&t.index===void 0)}function Bl(e,t){let i=t.adapter.getActivity(e);return i?Ot(i):0}function NI(e,t,i,r){return e!==null&&t!==null&&t>e?e+(t-e)*i/(r+1):e!==null?e+i:t!==null?t-(r-i+1):i-1}async function bI(e,t,i){let r=new Map,n=[];for(let a of t){if(a.parentBatchId===null){n.push(a);continue}let s=r.get(a.parentBatchId)??[];s.push(a),r.set(a.parentBatchId,s)}for(let a=0;a<n.length;a+=1){let s=n[a],c=await rr({kind:I.ACTIVITY_CREATE,parentId:s.parentId,activityId:s.activityId,overrides:s.overrides,...e.eventSource===void 0?{}:{eventSource:e.eventSource}},i,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,skipCacheInvalidation:!0,skipRollupCascades:!0,insertionCorrelativeId:s.insertionCorrelativeId});if(!c.ok)return c;for(let l of r.get(s.input.batchId)??[])n.push(l)}if(n.length!==t.length)return{ok:!1,reason:S.INVALID};let o=new Set;for(let a=n.length-1;a>=0;a-=1){let s=n[a].parentId;s==="0"||o.has(String(s))||(o.add(String(s)),Ft(s,i.adapter))}return{ok:!0}}function Wl(e,t){return typeof e=="string"?e:t.get(e.batchId)??null}function FI(e){return new Map(e.adapter.getAllLinks().map(t=>[String(t.id),{...t}]))}function wI(e){return new Map(Array.from(e,([t,i])=>[String(t),i]))}function Kl(e,t){let{adapter:i}=t,r=e.activityId,n=i.getActivity(r);if(!n)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let o=n.pendingRequestIds??[],a=e.pendingRequests.map(l=>l.id);i.setActivityField(e.activityId,"pendingRequestIds",a);let s=i.getActivity(r);if(!s)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let c={id:r,kind:N.UPDATED,fields:{pendingRequestIds:{before:o,after:a}},after:nt(s)};return{ok:!0,changes:{source:e,activities:[c],links:[],calendars:[],trackingEvents:[]}}}function Yl(e){let t=new Map;for(let i of e){let r=i.proplannerId;typeof r=="number"&&Number.isSafeInteger(r)&&r>0&&t.set(r,String(i.id))}return t}function Gl(e,t,i){let r=new Set(t.map(({id:n})=>String(n)));for(let n of e)if((n.proplannerId==null||n.proplannerId===0)&&!r.has(String(n.id)))throw new Error(`persistence-acknowledge: missing ${i} proplannerId for "${String(n.id)}"`)}function xI(e,t,i,r,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=i(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=r.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 $l(e,t,i,r){let n=new Set,o=new Set;for(let a of e)xI(a,t,i,r,n,o)}async function zl(e,t){let i=e.filter(s=>{let c=t.adapter.getActivity(String(s.activityId));return c!==null&&c.progress!==s.progress}),r=new Set(i.map(s=>String(s.activityId))),n=Gi(t.adapter,r),o=new Set(r);for(let s of n)o.add(String(s));let a=await Q(t.adapter,o);return t.adapter.batchUpdate(()=>{for(let s of i){let c=String(s.activityId);t.adapter.setActivityField(c,"progress",s.progress),t.adapter.setActivityField(c,"autoScheduling",we(s.progress))}zs(n,t.adapter),kl(r,n,t.adapter)}),[...await tn(t.adapter,a,o)]}async function ql(e,t){let i=e.activities??[],r=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=Yl(a),u=Yl(s);$l(i,"activity",y=>{let g=c.get(y);return{exists:g!==void 0,current:g?.proplannerId??null}},d),$l(r,"link",y=>{let g=l.get(y);return{exists:g!==void 0,current:g?.proplannerId??null}},u),Gl(a,i,"activity"),Gl(s,r,"link");let f=[],p=[];return t.adapter.batchUpdate(()=>{for(let y of i){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 r){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 Jl(e,t,i){if(MI(e))return{ok:!1,reason:S.INVALID_VALUE};let r=[...new Set(e.activityIds.map(String))];if(e.acknowledgePersistedLookahead===!0&&r.some(s=>!i.isActivityIdReserved(s)))return{ok:!1,reason:S.INVALID};let o=r.map(s=>i.adapter.getActivity(s));if(o.some(s=>!s))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let a=[];for(let[s,c]of r.entries()){let l=o[s];if(!l)continue;let d={};l.isLookahead!==e.isLookahead&&(d.isLookahead={before:l.isLookahead,after:e.isLookahead},i.adapter.setActivityField(c,"isLookahead",e.isLookahead)),l.hasLookaheadTasks!==e.hasLookaheadTasks&&(d.hasLookaheadTasks={before:l.hasLookaheadTasks,after:e.hasLookaheadTasks},i.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 zl([{activityId:r[0],progress:e.persistedProgress}],i)).length>0?(await X({adapter:i.adapter,scheduler:i.scheduler,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.persistedProgress===0?r[0]:null,recomputeParentsFrom:[],now:i.now,options:t}),{ok:!0,changes:await $(i.adapter,{source:e,beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:i.sector.hoursPerDay})}):{ok:!0,changes:{source:e,activities:a,links:[],calendars:[],trackingEvents:[]}}}function MI(e){let t=e.persistedProgress;return t!==void 0&&(e.activityIds.length!==1||!Number.isFinite(t)||t<0||t>100)}function ua(e,t){let{adapter:i}=t,r=new Set(e.conversionRootIds.map(f=>String(f)));if(r.size===0)throw new Error("Conversion requires at least one root");for(let f of r)$I(f,i);let n=i.getVisualOrderIds().filter(f=>r.has(f)&&!Ei(f,r,i)),o=n.map(f=>UI(f,i)),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=Sn(d,i);return{sourceStateRevision:t.stateRevision,conversionRootIds:n,conversionGroups:a,milestoneMoves:s,activityIdsToDelete:c,linkIdsToDelete:u,formerParents:l}}async function Ql(e,t,i){if(e.expectedStateRevision!==i.stateRevision)return{ok:!1,reason:S.STALE_STATE_REVISION};let r=ua(e,i);if(!zI(r,i.adapter))return{ok:!1,reason:S.HIERARCHY_CYCLE};let{adapter:n,scheduler:o}=i;o.invalidateAllCaches();let a=await VI(r,n);jI(r,i),td(r,n),KI(r,a.deletedIds,n);let s=YI(r,n);hi(n,s,a.deletedIds,a.beforeSnap,a.touchedIds);let{scheduledIds:c}=await X({adapter:n,scheduler:o,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:a.touchedIds,now:i.now,options:t,recomputeParentProgress:!0}),l=await $(n,{source:e,beforeSnap:a.beforeSnap,touchedIds:a.touchedIds,scheduledIds:c,sirDetection:"after-diff",links:qe(a.beforeLinks),hoursPerDay:i.sector.hoursPerDay,correlativeShifts:s});return GI(r,a,l)}function UI(e,t){let i=da(e,t),r=Cn([e],t);if(r.delete(e),r.size===0)throw new Error(`Conversion root ${e} has no descendants`);let n=t.getVisualOrderIds().filter(c=>r.has(c)).map(c=>da(c,t));Zl(i);for(let c of n)Zl(c);let o=n.filter(c=>c.type!==D.MILESTONE),a=n.filter(c=>c.type===D.MILESTONE),s=HI(i,o);return{conversionRootId:e,convertedActivities:o.map(c=>BI(c,s)),milestoneMoves:WI(i,a),activityIdsToDelete:o.map(c=>c.id),formerParent:{activity:nt(i),hasConvertedActivities:o.length>0}}}function HI(e,t){let i=new Map;t.length>0&&i.set(e.id,Xl(e));for(let r of t)i.set(r.id,Xl(r));return i}function BI(e,t){let i=nt(e),r=$t(e.parentId),n=t.get(r);return i.parentId=n===void 0?null:String(n),i}function WI(e,t){let i=[],r=$t(e.parentId),n=e.id;for(let o of t)i.push({activityId:o.id,parentId:r,afterSiblingId:n}),n=o.id;return i}async function VI(e,t){let i=new Set(e.activityIdsToDelete),r=new Set([...e.conversionRootIds,...e.activityIdsToDelete,...e.milestoneMoves.map(({activityId:n})=>n),...e.milestoneMoves.map(({parentId:n})=>n).filter(n=>n!=="0")]);return{deletedIds:i,touchedIds:r,beforeSnap:await Q(t,r),beforeLinks:qI(e.linkIdsToDelete,t),viewStateChanges:nr(t,i)}}function jI(e,t){for(let i of e.activityIdsToDelete){let r=t.adapter.getActivity(i)?.customId;r&&t.customIdTracker.releaseCustomId(r)}}function td(e,t){for(let i of e.milestoneMoves)t.setActivityFields(i.activityId,{parentId:i.parentId,correlativeId:Di(t,i.parentId,i.afterSiblingId,void 0)});for(let i of e.linkIdsToDelete)t.removeLink(i);for(let i of[...e.activityIdsToDelete].reverse())t.removeActivity(i);for(let{activity:i}of e.formerParents)t.setActivityField(i.id,b.TYPE,D.TASK)}function KI(e,t,i){for(let{activity:r,hasConvertedActivities:n}of e.formerParents){let o=da(r.id,i),a=Tn({parent:o,idsRemoved:t});i.setActivityFields(r.id,{isLookahead:r.isLookahead||n,hasLookaheadTasks:r.hasLookaheadTasks||n,...a?.fields??{}})}}function YI(e,t){for(let{activity:i}of e.formerParents)Ft(i.parentId,t);return _t(t)}function GI(e,t,i){let r=new Map;for(let n of t.deletedIds){let o=t.beforeSnap.get(n);o&&r.set(n,o)}return{ok:!0,changes:t.viewStateChanges.length===0?i:{...i,viewState:t.viewStateChanges},conversionGroups:e.conversionGroups.map(({conversionRootId:n,convertedActivities:o})=>({conversionRootId:n,convertedActivities:o.map(a=>nt(a))})),__beforeSnap:r,__beforeLinks:t.beforeLinks}}function $I(e,t){let i=t.getActivity(e);if(!i)throw new Error(`Conversion root ${e} was not found`);if(i.type===D.PROJECT&&i.correlativeId===0)throw new Error(`Conversion root ${e} is the visual project root`)}function da(e,t){let i=t.getActivity(e);if(!i)throw new Error(`Conversion activity ${e} is missing`);return i}function Xl(e){if(e.proplannerId==null)throw new Error(`Conversion activity ${e.id} has no persisted identifier`);return e.proplannerId}function Zl(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 zI(e,t){let i=t.fork();return td(e,i),me({port:t,proposedPort:i,currentLinks:t.getAllLinks(),proposedLinks:i.getAllLinks()}).ok}function qI(e,t){let i=new Map;for(let r of e){let n=t.getLink(r);n&&i.set(r,{...n})}return i}function _i(e,t){let i=new Set;for(let n of e)i.add(String(n));let r=[];for(let n of t.getAllLinks()){let o=String(n.source),a=String(n.target);!i.has(o)&&!i.has(a)||(ed(a,o,t)||ed(o,a,t))&&r.push(String(n.id))}return r}function ed(e,t,i){let r=String(e),n=new Set;for(;r!=null;){if(n.has(r))return!1;n.add(r);let o=i.getActivity(r);if(!o)return!1;let a=o.parentId;if(a===null||U(a))return!1;let s=a;if(s===t)return!0;r=s}return!1}function Dn(e,t){let i=e.getAllLinks();return!me({port:e,currentLinks:i,proposedLinks:i,proposal:{reparented:t}}).ok}function En(e,t){let i=new Set;if(e.length===0)return i;let r=new Map(e.map(o=>[o.activityId,o.newParentId]));if(!Dn(t,r))return i;let n=new Map;for(let o of e){let a=new Map(n);if(a.set(o.activityId,o.newParentId),Dn(t,a)){i.add(o.activityId);continue}n.set(o.activityId,o.newParentId)}return i}async function id(e,t,i){let{adapter:r,scheduler:n,sector:o}=i;n.invalidateAllCaches();let a=r.getActivity(e.activityId);if(!a)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let s=U(e.parentId);if(!s&&!r.getActivity(e.parentId))return{ok:!1,reason:S.PARENT_NOT_FOUND};if(!s&&(e.parentId===e.activityId||r.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:S.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:S.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let R=r.getActivity(c);if(!R)return{ok:!1,reason:S.ANCHOR_SIBLING_NOT_FOUND};if((R.parentId===null?"0":String(R.parentId))!==e.parentId)return{ok:!1,reason:S.ANCHOR_SIBLING_WRONG_PARENT}}let l=a.parentId,d=$t(l),u=String(e.parentId),f=d!==u;if(f){let R=new Map([[e.activityId,s?null:e.parentId]]);if(Dn(r,R))return{ok:!1,reason:S.HIERARCHY_CYCLE}}let p=new Set([e.activityId]);f?(d!=="0"&&p.add(d),u!=="0"&&p.add(u)):d!=="0"&&p.add(d);let y=await Q(r,p);f&&r.setActivityField(e.activityId,b.PARENT,u);let g=Di(r,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(r.setActivityField(e.activityId,b.CORRELATIVE_ID,g),f){if(!s){let R=r.getActivity(e.parentId);if(R){let M=R.customId,T=he(R.type)&&r.getChildren(e.parentId).filter(L=>L!==e.activityId).length===0,C=Pe({parentId:e.parentId,newChildId:e.activityId,getParent:L=>r.getActivity(L)??null,isCurrentlyLeaf:T,promotionSource:Ti.REPARENT});if(C){for(let[L,j]of Object.entries(C.fields))lt(r,C.parentId,L,j);C.promotionSnapshot&&r.setPromotionSnapshot(C.parentId,C.promotionSnapshot),C.fields.customId===null&&hn(M,i.customIdTracker)}}}if(d!=="0"){let R=r.getActivity(d);if(R){let M=r.getChildren(d),T=Le({parent:R,remainingChildIds:M.map(String),defaultDurationHours:o.hoursPerDay,promotionSnapshot:r.getPromotionSnapshot(d),computeEndDate:(C,L)=>r.calculateEndDate({startDate:C,durationHours:L,task:R}),idsRemoved:new Set([e.activityId])});if(T){for(let[it,rt]of Object.entries(T.fields))lt(r,d,it,rt);let C=re(d,r),L=C?r.getActivity(C)?.customId:null,j=typeof L=="string"&&L?L:null,K=i.customIdTracker.generateCustomIdForRestoredChild(j);r.setActivityField(d,b.CUSTOM_ID,K)}}}}f&&(d!=="0"&&Ft(d,r),s||Ft(e.parentId,r));let A=_t(r);for(let R of A){if(p.add(R.activityId),y.has(R.activityId))continue;let M=r.getActivity(R.activityId);if(!M)continue;let T=nt(M);R.before!==void 0&&(T.correlativeId=R.before),y.set(R.activityId,T)}let k=f&&d!=="0"?r.getChildren(d).map(String):[],{scheduledIds:_}=await X({adapter:r,scheduler:n,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,...k],now:i.now,options:t,recomputeParentProgress:f}),F=f?_i([e.activityId],r):[],h={name:Kt.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:F.map(String)}};return e.eventSource!==void 0&&(h.properties.event_source=e.eventSource),{ok:!0,changes:await $(r,{source:e,beforeSnap:y,touchedIds:p,scheduledIds:_,sirDetection:Lt.BEFORE_DIFF,trackingEvents:[h],hoursPerDay:o.hoursPerDay})}}function _n(e,t){let i=new Set(e),r=[],n=[],o=new Set,a=new Set(i),s=[...e].sort((d,u)=>{let f=t.getActivity(d),p=t.getActivity(u),y=f?Ot(f):ze,g=p?Ot(p):ze;return y-g});for(let d of s){if(!t.getActivity(d)){r.push({activityId:d,reason:S.ACTIVITY_NOT_FOUND}),a.delete(d);continue}if(Ei(d,o,t))continue;let f=gs(d,a,t);if(f==null){r.push({activityId:d,reason:S.INDENT_NO_ELIGIBLE_SIBLING}),a.delete(d);continue}let p=t.getActivity(d)?.parentId,y=U(p)?"0":String(p);n.push({activityId:d,newParentId:f,oldParentId:y}),o.add(d)}let c=En(n,t);for(let d of c)r.push({activityId:d,reason:S.HIERARCHY_CYCLE});let l=n.filter(d=>!c.has(d.activityId));return{moves:n,cyclicMoveIds:c,allowedMoves:l,failed:r}}async function rd(e,t,i){let{adapter:r,scheduler:n,sector:o}=i;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:S.ACTIVITY_IDS_EMPTY};let a=new Set,s=[],c=_n(e.activityIds,r),l=[...c.failed];for(let h of c.moves)a.add(String(h.activityId)),a.add(String(h.newParentId)),h.oldParentId!=="0"&&a.add(String(h.oldParentId));let d=c.allowedMoves,u=await Q(r,a);for(let{activityId:h,newParentId:R}of d)r.setActivityField(h,b.PARENT,R),r.setActivityField(h,b.CORRELATIVE_ID,Fl),s.push(h);let f=new Set;for(let{activityId:h,newParentId:R}of d){if(f.has(R))continue;f.add(R);let M=r.getActivity(R);if(!M)continue;let T=M.customId,C=he(M.type)&&r.getChildren(R).filter(K=>!s.includes(K)).length===0,L=M.hasNewActivities&&M.newActivityIds.some(K=>String(K)===String(h)),j=Pe({parentId:R,newChildId:h,getParent:K=>r.getActivity(K)??null,isCurrentlyLeaf:C,promotionSource:Ti.REPARENT});if(j){for(let[K,it]of Object.entries(j.fields))lt(r,j.parentId,K,it);j.promotionSnapshot&&r.setPromotionSnapshot(j.parentId,j.promotionSnapshot),L||(r.setActivityField(R,b.HAS_NEW_ACTIVITIES,!1),r.setActivityField(R,b.NEW_ACTIVITIES_ARRAY,[]))}r.setActivityField(R,b.CONSTRAINT_TYPE,v.ASAP),r.setActivityField(R,b.CONSTRAINT_DATE,null),r.setActivityField(R,b.CUSTOM_ID,null),hn(T,i.customIdTracker)}let p=new Set;for(let h of d)h.oldParentId!=="0"&&p.add(h.oldParentId),p.add(h.newParentId);for(let h of p)Ft(h,r);let y=_t(r);for(let h of y){if(a.add(h.activityId),u.has(h.activityId))continue;let R=r.getActivity(h.activityId);if(!R)continue;let M=nt(R);h.before!==void 0&&(M.correlativeId=h.before),u.set(h.activityId,M)}let g=_i(s,r),A=new Map;for(let h of g){let R=r.getLink(h);R&&(A.set(h,{...R}),r.removeLink(h))}let{scheduledIds:k}=await X({adapter:r,scheduler:n,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:s,now:i.now,options:t}),_={name:Kt.ACTIVITY_INDENT,properties:{activity_ids:s,failed:l.map(h=>({activity_id:h.activityId,reason:h.reason})),invalid_link_ids:g}};e.eventSource!==void 0&&(_.properties.event_source=e.eventSource);let F=await $(r,{source:e,beforeSnap:u,touchedIds:a,scheduledIds:k,links:qe(A),trackingEvents:[_],hoursPerDay:o.hoursPerDay});return{ok:!0,activityVerdicts:e.activityIds.map(h=>{let R=l.find(M=>String(M.activityId)===String(h));return R?{activityId:String(h),ok:!1,reason:R.reason}:{activityId:String(h),ok:!0}}),changes:F,__beforeLinks:A}}async function nd(e,t,i){let{adapter:r,scheduler:n,sector:o}=i;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:S.ACTIVITY_IDS_EMPTY};let a=new Set(e.activityIds),s=new Map,c=new Map;for(let T of e.activityIds){let C=T;r.getActivity(C)&&(s.set(C,no(C,r)),c.set(C,wl(C,a,r)))}let l=new Set,d=[],u=[],f=new Set,p=[],y=new Set,g=[...e.activityIds].sort((T,C)=>{let L=r.getActivity(T),j=r.getActivity(C),K=L?Ot(L):ze,it=j?Ot(j):ze;return K-it});for(let T of g){let C=T,L=r.getActivity(C);if(!L){d.push({activityId:C,reason:S.ACTIVITY_NOT_FOUND});continue}if(Ei(C,y,r))continue;let j=L.parentId;if(U(j)){d.push({activityId:C,reason:S.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let K=String(j),it=r.getActivity(K);if(!it){d.push({activityId:C,reason:S.ACTIVITY_NOT_FOUND});continue}let rt=it.parentId;if(U(rt)){d.push({activityId:C,reason:S.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let vt=String(rt),Ct=no(K,r)+1,It=c.get(C);if(It!=null&&a.has(It)){let Qe=s.get(It)??-1,ti=s.get(C)??-1;Qe>=0&&ti>=0&&(Ct+=ti-Qe)}p.push({activityId:C,grandparentKey:vt,oldParentKey:K,targetIndexInGrandparent:Ct}),y.add(C),l.add(String(C)),l.add(String(K)),vt!=="0"&&l.add(String(vt)),f.add(K)}let A=En(p.map(T=>({activityId:T.activityId,newParentId:T.grandparentKey})),r);for(let T of A)d.push({activityId:T,reason:S.HIERARCHY_CYCLE});let k=p.filter(T=>!A.has(T.activityId)),_=await Q(r,l);for(let T of k){r.setActivityField(T.activityId,b.PARENT,T.grandparentKey);let C=xl(r,T.grandparentKey,T.targetIndexInGrandparent,T.activityId);r.setActivityField(T.activityId,b.CORRELATIVE_ID,C),u.push(T.activityId)}for(let T of f){let C=r.getActivity(T);if(!C)continue;let L=r.getChildren(T),j=Le({parent:C,remainingChildIds:L.map(String),defaultDurationHours:o.hoursPerDay,promotionSnapshot:r.getPromotionSnapshot(T),computeEndDate:(Ct,It)=>r.calculateEndDate({startDate:Ct,durationHours:It,task:C}),idsRemoved:new Set(k.filter(Ct=>Ct.oldParentKey===T).map(Ct=>Ct.activityId))});if(!j){Vr(T,r);continue}for(let[Ct,It]of Object.entries(j.fields))lt(r,T,Ct,It);let K=re(T,r),it=K?r.getActivity(K)?.customId:null,rt=typeof it=="string"&&it?it:null,vt=i.customIdTracker.generateCustomIdForRestoredChild(rt);r.setActivityField(T,b.CUSTOM_ID,vt)}let F=new Set;for(let T of f)F.add(String(T));for(let T of k)T.grandparentKey!=="0"&&F.add(String(T.grandparentKey));for(let T of F)Ft(T,r);let h=_t(r);for(let T of h){if(l.add(T.activityId),_.has(T.activityId))continue;let C=r.getActivity(T.activityId);if(!C)continue;let L=nt(C);T.before!==void 0&&(L.correlativeId=T.before),_.set(T.activityId,L)}let{scheduledIds:R}=await X({adapter:r,scheduler:n,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:u.length>0?Et.ROOTS:null,recomputeParentsFrom:u,now:i.now,options:t}),M={name:Kt.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(T=>({activity_id:String(T.activityId),reason:T.reason}))}};return e.eventSource!==void 0&&(M.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(T=>{let C=d.find(L=>String(L.activityId)===String(T));return C?{activityId:String(T),ok:!1,reason:C.reason}:{activityId:String(T),ok:!0}}),changes:await $(r,{source:e,beforeSnap:_,touchedIds:l,scheduledIds:R,trackingEvents:[M],hoursPerDay:o.hoursPerDay})}}async function od(e,t,i){let{adapter:r,scheduler:n,sector:o}=i,a=r.getActivity(e.activityId);if(!a)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};if(!Fi(e.type))return{ok:!1,reason:S.INVALID_VALUE};let s=r.getChildren(e.activityId),c=e.type===D.PROJECT;if(c!==s.length>0)return{ok:!1,reason:S.INVALID_VALUE};let l=new Set(r.getAllIds()),d=await Q(r,l);n.invalidateAllCaches(),c&&a.type!==D.PROJECT?JI(e.activityId,s[0],i):!c&&a.type===D.PROJECT&&XI(e.activityId,i),e.type!==D.PROJECT?(ZI(e.activityId,e.type,i),QI(e.activityId,i)):Ft(e.activityId,r);let u=tg(e.activityId,i),{scheduledIds:f}=await X({adapter:r,scheduler:n,sector:o,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId],recomputeParentProgress:!0,now:i.now,options:t});return{ok:!0,changes:await $(r,{source:e,beforeSnap:d,touchedIds:l,scheduledIds:f,sirDetection:Lt.BEFORE_DIFF,links:qe(u),hoursPerDay:o.hoursPerDay}),__beforeLinks:new Map(u)}}function JI(e,t,i){let n=i.adapter.getActivity(e)?.customId??null,o=Pe({parentId:e,newChildId:t,isCurrentlyLeaf:!0,getParent:a=>i.adapter.getActivity(a)??null});if(o){for(let[a,s]of Object.entries(o.fields))lt(i.adapter,e,a,s);o.promotionSnapshot&&i.adapter.setPromotionSnapshot(e,o.promotionSnapshot),o.fields.customId===null&&i.customIdTracker.releaseCustomId(n)}}function XI(e,t){let i=t.adapter.getActivity(e);if(!i)return;let r=Le({parent:i,remainingChildIds:[],defaultDurationHours:t.sector.hoursPerDay,promotionSnapshot:t.adapter.getPromotionSnapshot(e),computeEndDate:(n,o)=>t.adapter.calculateEndDate({startDate:n,durationHours:o,task:i})});if(r)for(let[n,o]of Object.entries(r.fields))lt(t.adapter,e,n,o)}function ZI(e,t,i){let r=i.adapter.getActivity(e);if(!r)return;i.adapter.setActivityField(e,b.TYPE,t);let n=t===D.MILESTONE?0:r.durationHours===0?i.sector.hoursPerDay:r.durationHours;n!==r.durationHours&&i.adapter.setActivityField(e,b.DURATION_HOURS,n);let o=i.adapter.getActivity(e);if(!o)return;let a=i.adapter.calculateEndDate({startDate:o.startDate,durationHours:n,task:o});i.adapter.setActivityField(e,b.END_DATE,a)}function QI(e,t){if(t.adapter.getActivity(e)?.customId)return;let r=re(e,t.adapter),n=r?t.adapter.getActivity(r)?.customId:null,o=t.customIdTracker.generateCustomIdForRestoredChild(n||null);t.adapter.setActivityField(e,b.CUSTOM_ID,o)}function tg(e,t){let i=new Map;for(let r of _i([e],t.adapter)){let n=t.adapter.getLink(r);n&&(i.set(String(r),{...n}),t.adapter.removeLink(r))}return i}async function ad(e,t,i){let{adapter:r,ctx:n,scheduler:o,sector:a}=i;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:S.INVALID_PROGRESS_VALUE};let s=n.activityReader.getActivity(e.activityId);if(!s)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let c=Ee(E.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===Jr.ACTION_BUTTON&&(l.reason===zi.HAS_LOOKAHEAD_TASKS||l.reason===zi.SUMMARY)))return{ok:!1,reason:l.reason,...l.alertKey?{alertKey:l.alertKey}:{}};let d=c.transform(s,e.newValue,n,e.newValue),u=_e(e.activityId,d),f=await Q(r,u);ke(r,e.activityId,d),Js(e.activityId,e.newValue,r),ve(e.activityId,d.postProcessors??[],r);let p=d.needsAutoSchedule?n.hierarchy.hasChildren(e.activityId)?Et.ROOTS:e.activityId:null,{scheduledIds:y}=await X({adapter:r,scheduler:o,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:p,recomputeParentsFrom:[],collectDirty:A=>en(e.activityId,u,A),now:i.now,options:t}),g=(d.trackingEvents??[]).map(A=>({name:A.name,properties:A.properties??{}}));return{ok:!0,changes:await $(r,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:y,trackingEvents:g,hoursPerDay:a.hoursPerDay})}}function eg(e){return e===E.START_DATE||e===E.END_DATE}async function sd(e,t,i){if(e.edits.some(y=>!eg(y.column)))return{ok:!1,reason:S.INVALID_VALUE};let{adapter:r,scheduler:n,sector:o}=i,a=[],s=new Map,c=new Set,l=[],d=[],u=[],f=!1;for(let y of e.edits){let g=ig(y,i);if(a.push(g.verdict),!g.verdict.ok||!g.changes)continue;let A=_e(y.activityId,g.changes);rg(s,A,i);for(let h of A)c.add(h);let k=Ci(r,y.activityId),_=Qr(r,String(y.activityId));ke(r,y.activityId,g.changes),ve(y.activityId,g.changes.postProcessors??[],r,_),d.push(...Si(k,r,y.activityId)),f||=!!g.changes.needsAutoSchedule;for(let h of g.changes.trackingEvents??[])l.push({name:h.name,properties:h.properties??{}});let F=Ve(y.activityId,g.changes.constraintWarning);F&&u.push(F)}let{scheduledIds:p}=await X({adapter:r,scheduler:n,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:f?Et.ROOTS:null,recomputeParentsFrom:c,now:i.now,options:t});return{ok:!0,verdicts:a,changes:await $(r,{source:e,beforeSnap:s,touchedIds:c,scheduledIds:p,sirDetection:Lt.BEFORE_DIFF,links:d,trackingEvents:l,warnings:u,hoursPerDay:o.hoursPerDay})}}function ig(e,t){let{ctx:i}=t,r=e.activityId,n=Ee(e.column);if(!n)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);let o=i.activityReader.getActivity(e.activityId);if(!o)throw new Error(`[ScheduleCore] activity "${e.activityId}" not found`);let a=n.canEdit(o,i.hierarchy);if(!a.allowed)return{verdict:{activityId:r,ok:!1,reason:a.reason??S.CANNOT_EDIT,...a.alertKey?{alertKey:a.alertKey}:{}},changes:null};let s=n.parseInput(e.newValue,o,i);if(!s.ok)return{verdict:{activityId:r,ok:!1,reason:s.reason??S.PARSE_ERROR},changes:null};let c=Reflect.get(o,n.targetField),l=n.validate(o,c,s.value,i);if(!l.valid)return{verdict:{activityId:r,ok:!1,reason:l.reason??S.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};let d=n.transform(o,s.value,i,s.raw);return{verdict:{activityId:r,ok:!0},changes:d}}function rg(e,t,i){let r=new Set;for(let n of t)e.has(n)||r.add(n);if(r.size!==0)for(let n of r){let o=i.adapter.getActivity(n);o&&e.set(n,nt(o))}}var fa=E.CUSTOM_ID;async function cd(e,t,i){let{adapter:r,scheduler:n,sector:o}=i;e.edits.some(T=>T.column===E.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 T of e.edits){let C=lg(T,i,e.eventSource);if(s.push(C.verdict),!C.verdict.ok||!C.changes)continue;let L=Ve(T.activityId,C.changes.constraintWarning);L&&y.push(L);let j=_e(T.activityId,C.changes);pg(c,j,i);for(let Ct of j)u.add(Ct);fg(l,T,c),fn(T.column)&&d.add(String(T.activityId)),ag(A,T);let K=Ci(r,T.activityId),it=Qr(r,String(T.activityId)),rt=dg(T,i),vt=C.changes;ke(r,T.activityId,vt),ve(T.activityId,C.changes.postProcessors??[],r,it),ng(g,y,T),og(k,T,r.getActivity(T.activityId)),ug(T,rt,i),p.push(...Si(K,r,T.activityId)),_||=!!C.changes.needsAutoSchedule;for(let Ct of C.changes.trackingEvents??[])f.push({name:Ct.name,properties:Ct.properties??{}})}let F={action:e,autoscheduleFrom:_?Et.ROOTS:null,recomputeParentsFrom:u,now:i.now,options:t},h=sg(A,k,c,y,g,i),R=l.size>0,{scheduledIds:M}=await(R?yn({adapter:r,scheduler:n,sector:o,defaultBaseCalendarId:i.defaultBaseCalendarId},{postMutationArgs:F,revertTargets:[...l].filter(([T])=>!d.has(T)).map(([T,C])=>({activityId:T,priorConstraintDate:C})),revert:(T,C)=>pn(T,C,r,i.ctx.calendars)}):X({adapter:r,scheduler:n,sector:o,defaultBaseCalendarId:i.defaultBaseCalendarId},F));return{ok:!0,verdicts:s,changes:await $(r,{source:e,beforeSnap:c,touchedIds:u,scheduledIds:M,sirDetection:Lt.BEFORE_DIFF,links:p,trackingEvents:f,warnings:h,hoursPerDay:o.hoursPerDay})}}function ng(e,t,i){if(!Ai(i.column))return;let r=String(i.activityId);for(let n of t)String(n.activityId)===r&&e.add(n)}function og(e,t,i){!Ai(t.column)||!i||e.set(String(t.activityId),{constraintType:i.constraintType,constraintDate:i.constraintDate?new Date(i.constraintDate.getTime()):null})}function ag(e,t){if(t.column!==E.START_DATE&&t.column!==E.END_DATE)return;let i=String(t.activityId),r=e.get(i)??new Set;r.add(t.column),e.set(i,r)}function sg(e,t,i,r,n,o){let a=new Set,s=[],c=new Set;for(let[l,d]of e){if(!d.has(E.START_DATE)||!d.has(E.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=i.get(l),p=o.adapter.getActivity(l);if(!f?.constraintType||!f.constraintDate||!p)continue;let y=Oe(f.constraintType,p.startDate,p.endDate),g=cg(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=Ve(l,pr(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[...r.filter(l=>!c.has(l)&&!a.has(String(l.activityId))),...s]}function cg(e,t,i){return e===v.MSO||e===v.MFO?t.getTime()!==i.getTime():fr(e,t,i).violated}function lg(e,t,i){let{ctx:r}=t,n=e.activityId,o=Ee(e.column);if(!o)return{verdict:{activityId:n,ok:!1,reason:S.NO_PIPELINE_FOR_COLUMN},changes:null};let a=r.activityReader.getActivity(e.activityId);if(!a)return{verdict:{activityId:n,ok:!1,reason:S.ACTIVITY_NOT_FOUND},changes:null};let s=o.canEdit(a,r.hierarchy,{eventSource:i,newValue:e.newValue});if(!s.allowed)return{verdict:{activityId:n,ok:!1,reason:s.reason??S.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let c=o.parseInput(e.newValue,a,r);if(!c.ok)return{verdict:{activityId:n,ok:!1,reason:c.reason??S.PARSE_ERROR},changes:null};let l=Reflect.get(a,o.targetField),d=o.validate(a,l,c.value,r);if(!d.valid)return{verdict:{activityId:n,ok:!1,reason:d.reason??S.INVALID,...d.notification?.messageKey?{alertKey:d.notification.messageKey}:{}},changes:null};if(e.column===fa&&c.value!==null){let f=t.adapter.getActivity(e.activityId),p=f?f.customId:null,y=typeof p=="string"?p:null;if(t.customIdTracker.isCustomIdInUse(String(c.value),y))return{verdict:{activityId:n,ok:!1,reason:S.CUSTOM_ID_DUPLICATE},changes:null}}let u=o.transform(a,c.value,r,c.raw);return{verdict:{activityId:n,ok:!0},changes:u}}function dg(e,t){if(e.column!==fa)return null;let i=t.adapter.getActivity(e.activityId),r=i?i.customId:null;return typeof r=="string"?r:null}function ug(e,t,i){if(e.column!==fa)return;let r=i.adapter.getActivity(e.activityId),n=r?r.customId:null,o=typeof n=="string"?n:null;t!==o&&i.customIdTracker.trackCustomIdChange(t,o)}function fg(e,t,i){if(!Ai(t.column))return;let r=String(t.activityId);if(e.has(r))return;let n=i.get(r);n&&e.set(r,n.constraintDate??null)}function pg(e,t,i){let r=new Set;for(let n of t)e.has(n)||r.add(n);if(r.size!==0)for(let n of r){let o=i.adapter.getActivity(n);o&&e.set(n,nt(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"},yg=[Nt.INVALID_BASELINE_POINT,Nt.UNKNOWN_CONSTRAINT,Nt.ORPHAN_ACTIVITY,Nt.INVALID_LINK,Nt.DUPLICATE_LINK],ki=()=>{};function ld(){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(yg.flatMap(n=>{let o=e.get(n);return o===void 0?[]:[Object.freeze({code:n,count:o,sampleIds:Object.freeze([...t.get(n)??[]])})]}))}}function dd(e){return typeof e=="string"&&e.length>0?le(e):e instanceof Date?e:null}function pa(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 kn(e,t,i,r=!1){let n=pa(e.duration),o=pa(e.cost),a=pa(e.hh_work);if(n===null||o===null||a===null)return i&&i.record(Nt.INVALID_BASELINE_POINT,i.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=dd(e.start_date),c=dd(e.end_date),l=r&&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,i,r=ki){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"){r(Nt.INVALID_BASELINE_POINT,String(c??"unknown"));continue}let l=n.get(c);if(l===void 0){r(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===D.MILESTONE;e.setActivityField(s,"baselinePoints",c.map(d=>kn(d,i,{record:r,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 hg(e){let t=gt(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function fd(e){let t=[];return e.forEachActivity((i,r)=>{let n=hg(i);if(!n){i.baselineSnapshot!==null&&(e.setActivityField(r,"baselineSnapshot",null),t.push(r));return}e.setActivityField(r,"baselineSnapshot",n),t.push(r)}),t}function Rn(e,t,i,r,n=null,o=ki){let a=new Set;for(let s of ud(e,t,r,o))a.add(s);if(i)for(let s of Ii(e,i,n))a.add(s);for(let s of fd(e))a.add(s);for(let s of gi(e))a.add(s);return[...a]}function pd(e,t){t.forEachActivity((i,r)=>{t.setActivityField(r,E.PONDERATOR,0)}),t.forEachActivity((i,r)=>{t.getChildren(r).length>0&&un(String(r),e,t)})}function Pn(e,t){pd(t,e.adapter),Ki(e.adapter),e.now&&(Ii(e.adapter,e.now,e.defaultBaseCalendarId??null),je(e.adapter,e.now)),gi(e.adapter),e.now&&de(e.adapter,e.sector.statusCriteria)}function yd(e){return JSON.stringify(e.adapter.getAllIds().map(t=>{let i=e.adapter.getActivity(t)?.baselinePoints.find(r=>r.isActiveVersion);return i?[String(t),i.versionId,i.startDate?.getTime()??null,i.endDate?.getTime()??null,i.durationDays,i.cost,i.workHours,i.baseCalendarId,i.hoursPerDay,i.hoursPerWeek]:[String(t),null]}))}async function hd(e,t){let i=await Q(t.adapter,new Set(t.adapter.getAllIds())),r=yd(t),n=Rn(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return yd(t)!==r&&Pn(t,t.sector.activityCreter??pt.DURATION),{ok:!0,changes:await $(t.adapter,{source:e,beforeSnap:i,touchedIds:n,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function mg(e){return Object.values(pt).includes(e)}async function md(e,t){if(!mg(e.criterion))return{ok:!1,reason:S.INVALID_VALUE};let i=new Set(t.adapter.getAllIds()),r=await Q(t.adapter,i);return Pn(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:await $(t.adapter,{source:e,beforeSnap:r,touchedIds:i,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function Id(e,t){let i=rn(e.criteria),r=new Set(t.adapter.getAllIds()),n=await Q(t.adapter,r),o=de(t.adapter,i);return t.sector.statusCriteria=i,{ok:!0,changes:await $(t.adapter,{source:e,beforeSnap:n,touchedIds:o,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function Ad(e,t,i){let r=new Map,n=new Set;for(let a of i.adapter.getAllActivities()){if(!Ig(a,i))continue;let s=i.ctx.calendars.getCalendar(a.calendarId);if(!s)continue;let c=s.getClosestWorkTime({date:a.startDate,direction:Y.FUTURE,unit:ut.HOUR}),l=s.calculateEndDate(c,a.durationHours);if(gd(c,a.startDate)&&gd(l,a.endDate))continue;let d=String(a.id);r.set(d,nt(a)),n.add(d),i.adapter.setActivityFields(d,{startDate:c,endDate:l})}let{scheduledIds:o}=await X({adapter:i.adapter,scheduler:i.scheduler,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:Et.ROOTS,recomputeParentsFrom:n,now:i.now,options:t});return{ok:!0,changes:await $(i.adapter,{source:e,beforeSnap:r,touchedIds:n,scheduledIds:o,hoursPerDay:i.sector.hoursPerDay})}}function Ig(e,t){return e.progress===0&&!zt(e.type,t.adapter.hasChildren(e.id))}function gd(e,t){return e.getTime()===t.getTime()}var vd=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","cost","hasCustomPonderator","subcontractId","responsableIds","tagIds"];function gg(e){let t={};for(let i of vd)Object.assign(t,{[i]:w(e[i])});return t}function Ag(e,t){let i=[],r=n=>{t.has(String(n))&&i.push(n);for(let o of e.getChildren(n))r(o)};for(let n of e.getRootIds())r(n);return i}function Cd(e,t){let i=new Set(t.adapter.checkedIds().map(String));if(i.size===0)return{ok:!1,reason:S.NO_ACTIVITY_SELECTION};let r=Ag(t.adapter,i);t.clipboard.value={activities:r.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:gg(a)}}),links:t.adapter.getAllLinks().filter(o=>i.has(String(o.source))&&i.has(String(o.target))).map(o=>w(o))};let n=mr({kind:I.SELECTION_REPLACE,activityIds:[]},{adapter:t.adapter});return n.ok?{...n,changes:{...n.changes,source:e}}:n}function Sd(e,t){return t.value=null,{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}}function vg(e,t){let i=t.getActivity(e);return i?i.parentId==null?t.getRootIds().length===1?{ok:!0,parentId:i.id}:{ok:!0,parentId:"0",afterSiblingId:e}:t.hasChildren(i.id)?{ok:!0,parentId:i.id}:{ok:!0,parentId:String(i.parentId),afterSiblingId:e}:{ok:!1,reason:S.ANCHOR_SIBLING_NOT_FOUND}}var Td=()=>({ok:!1,reason:S.ACTIVITY_PASTE_INVARIANT_FAILED});async function Dd(e,t,i){let r=i.activityClipboard.value;if(r===null)return{ok:!1,reason:S.CLIPBOARD_EMPTY};let n=vg(e.destination.afterSiblingId,i.adapter);if(!n.ok)return n;let o=await Q(i.adapter,new Set),a=new Set,s=new Map,c=[],l;for(let g of r.activities){let A=s.get(g.originalParentId),k=A===void 0?l??n.afterSiblingId:void 0,_=await rr({kind:I.ACTIVITY_CREATE,parentId:A??n.parentId,...k===void 0?{}:{afterSiblingId:k},overrides:w(g.overrides),eventSource:e.eventSource},i,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:e.destination.afterSiblingId});if(!_.ok)return _;s.set(g.originalId,_.newId),c.push(_.newId),A===void 0&&(l=_.newId)}let d=_t(i.adapter),u=new Set(c.map(String));hi(i.adapter,d,u,o,a);for(let g of c)a.add(String(g));let f=[];for(let g of r.links){let A=s.get(g.source),k=s.get(g.target);if(A===void 0||k===void 0)return Td();let _={kind:St.CREATE,source:A,target:k,type:g.type,lag:g.lag},F=Ie(_,{port:i.adapter,newLinkId:i.linkIdGen.next});if(!F.applied)return Td();f.push({op:_,finalLinkId:F.linkId,rejected:null})}let{scheduledIds:p}=await X({adapter:i.adapter,scheduler:i.scheduler,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:c[0]??null,recomputeParentsFrom:c,now:i.now,options:t}),y=vi(f,new Map,i.adapter);return{ok:!0,changes:await $(i.adapter,{source:e,beforeSnap:o,touchedIds:a,scheduledIds:p,links:y,hoursPerDay:i.sector.hoursPerDay})}}async function Ed(e,t,i){return e.kind===I.ACTIVITY_COPY?Cd(e,{adapter:i.adapter,clipboard:i.activityClipboard}):e.kind===I.CALENDAR_RECONCILE?Ad(e,t,i):e.kind===I.ACTIVITY_CLIPBOARD_CLEAR?Sd(e,i.activityClipboard):e.kind===I.ACTIVITY_PASTE_COPIED?Dd(e,t,i):e.kind===pe?Vl(e,t,i):e.kind===I.PERSISTENCE_ACKNOWLEDGE?ql(e,i):e.kind===I.BASELINE_APPLY?hd(e,i):e.kind===I.PONDERATOR_CRITERION_SET?md(e,i):e.kind===I.STATUS_CRITERIA_SET?Id(e,i):e.kind===I.LINK_CREATE||e.kind===I.LINK_UPDATE||e.kind===I.LINK_DELETE?vl(e,t,i):e.kind===I.LINKS_BATCH?Cl(e,t,i):e.kind===I.ACTIVITY_CREATE?Ml(e,t,i):e.kind===I.ACTIVITY_DELETE?Hl(e,t,i):e.kind===I.ACTIVITY_MOVE?id(e,t,i):e.kind===I.ACTIVITY_INDENT?rd(e,t,i):e.kind===I.ACTIVITY_OUTDENT?nd(e,t,i):e.kind===I.ACTIVITY_TYPE_SET?od(e,t,i):e.kind===I.ACTIVITY_SET_PROGRESS?ad(e,t,i):e.kind===I.DATES_BATCH?sd(e,t,i):e.kind===I.BULK_EDIT?cd(e,t,i):e.kind===I.SELECTION_TOGGLE?os(e,ya(i)):e.kind===I.SELECTION_REPLACE?mr(e,ya(i)):e.kind===I.VISIBILITY_SET?as(e,ya(i)):e.kind===I.FILTER_SET?hs(e,{adapter:i.adapter,hoursPerDay:i.sector.hoursPerDay}):e.kind===I.SORT_SET?vs(e,{adapter:i.adapter}):e.kind===I.SIR_SYNC?Kl(e,i):e.kind===I.ACTIVITY_LOOKAHEAD_SYNC?Jl(e,t,i):e.kind===I.ACTIVITY_LOOKAHEAD_CONVERT?Ql(e,t,i):e.kind===I.SCHEDULE_AUTO_SCHEDULE?Il(e,t,i):e.kind===I.INLINE_EDIT&&(e.column===E.CUSTOM_PREDECESSORS||e.column===E.CUSTOM_SUCESSORS)?Sl(e,t,i):e.kind!==I.INLINE_EDIT?Cs(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):Al(e,t,i)}function ya(e){return{adapter:e.adapter}}var Cg=new Set(["startDate","endDate","constraintDate"]);function _d(e,t){return Cg.has(e)&&typeof t=="string"?new Date(t):t}function kd(e,t={}){let i=t.defaultUnit??ut.HOUR;return{getCalendar(r){let n=e.getCalendar(String(r));return n?Sg(n,i):null}}}function Sg(e,t){return{getClosestWorkTime(i){return e.getClosestWorkTime({date:i.date,dir:i.direction,unit:i.unit})},calculateEndDate(i,r){return e.calculateEndDate({start_date:i,duration:r,unit:t})},calculateDuration(i,r){return e.calculateDuration({start_date:i,end_date:r,unit:t})},isWorkTime(i,r){return e.isWorkTime({date:i,unit:r})},getWorkHours(i){return e.getWorkHours(i)}}}function Tg(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function Je(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function Xe(e){return Je(e)&&!isNaN(e.getTime())}var Dg={}.constructor.toString();function Eg(e){var t=e.constructor.toString();return t!==Dg}function _g(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function Xt(e){var t,i;if(e&&typeof e=="object")switch(!0){case Je(e):i=new Date(e);break;case Tg(e):for(i=new Array(e.length),t=0;t<e.length;t++)i[t]=Xt(e[t]);break;default:if(Eg(e))i=Object.create(e);else{if(_g(e))return i=e,i;i={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(i[t]=Xt(e[t]));break}return i||e}function Ri(e,t,i){for(var r in t)(e[r]===void 0||i)&&(e[r]=t[r]);return e}function Rd(e){return typeof e<"u"}var Ln;function ha(){return Ln||(Ln=new Date().valueOf()),Ln++,Ln}function Bt(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var Rg=(e,t,i)=>{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 r=new Function("date","to_fixed","locale","getISOWeek","getWeek",`return "${e}";`);return n=>r(n,i.date.to_fixed,i.locale,i.date.getISOWeek,i.date.getWeek)},Pg=(e,t,i)=>{let r="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":r+=`set[2]=temp[${s}]||1;`;break;case"%n":case"%m":r+=`set[1]=(temp[${s}]||1)-1;`;break;case"%y":r+=`set[0]=temp[${s}]*1+(temp[${s}]>50?1900:2000);`;break;case"%g":case"%G":case"%h":case"%H":r+=`set[3]=temp[${s}]||0;`;break;case"%i":r+=`set[4]=temp[${s}]||0;`;break;case"%Y":r+=`set[0]=temp[${s}]||0;`;break;case"%a":case"%A":r+=`set[3]=set[3]%12+((temp[${s}]||'').toLowerCase()=='am'?0:12);`;break;case"%s":r+=`set[5]=temp[${s}]||0;`;break;case"%M":r+=`set[1]=locale.date.month_short_hash[temp[${s}]]||0;`;break;case"%F":r+=`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]; ${r} return new Date(${o});`);return s=>a(s,i.locale)},Pd={date_to_str:Rg,str_to_date:Pg},Lg=(e,t,i)=>r=>e.replace(/%[a-zA-Z]/g,n=>{switch(n){case"%d":return t?i.date.to_fixed(r.getUTCDate()):i.date.to_fixed(r.getDate());case"%m":return t?i.date.to_fixed(r.getUTCMonth()+1):i.date.to_fixed(r.getMonth()+1);case"%j":return t?r.getUTCDate():r.getDate();case"%n":return t?r.getUTCMonth()+1:r.getMonth()+1;case"%y":return t?i.date.to_fixed(r.getUTCFullYear()%100):i.date.to_fixed(r.getFullYear()%100);case"%Y":return t?r.getUTCFullYear():r.getFullYear();case"%D":return t?i.locale.date.day_short[r.getUTCDay()]:i.locale.date.day_short[r.getDay()];case"%l":return t?i.locale.date.day_full[r.getUTCDay()]:i.locale.date.day_full[r.getDay()];case"%M":return t?i.locale.date.month_short[r.getUTCMonth()]:i.locale.date.month_short[r.getMonth()];case"%F":return t?i.locale.date.month_full[r.getUTCMonth()]:i.locale.date.month_full[r.getMonth()];case"%h":return t?i.date.to_fixed((r.getUTCHours()+11)%12+1):i.date.to_fixed((r.getHours()+11)%12+1);case"%g":return t?(r.getUTCHours()+11)%12+1:(r.getHours()+11)%12+1;case"%G":return t?r.getUTCHours():r.getHours();case"%H":return t?i.date.to_fixed(r.getUTCHours()):i.date.to_fixed(r.getHours());case"%i":return t?i.date.to_fixed(r.getUTCMinutes()):i.date.to_fixed(r.getMinutes());case"%a":return t?r.getUTCHours()>11?"pm":"am":r.getHours()>11?"pm":"am";case"%A":return t?r.getUTCHours()>11?"PM":"AM":r.getHours()>11?"PM":"AM";case"%s":return t?i.date.to_fixed(r.getUTCSeconds()):i.date.to_fixed(r.getSeconds());case"%W":return t?i.date.to_fixed(i.date.getUTCISOWeek(r)):i.date.to_fixed(i.date.getISOWeek(r));case"%w":return i.date.to_fixed(i.date.getWeek(r));default:return n}}),Og=(e,t,i)=>r=>{let n=[0,0,1,0,0,0],o=r.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]=i.locale.date.month_short_hash[o[s]]||0;break;case"%F":n[1]=i.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])},Ld={date_to_str:Lg,str_to_date:Og};function Od(e){var t=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function i(s){var c=new Date(s);return isNaN(c.getTime())?null:c}var r=null;function n(){try{new Function("canUseCsp = false;")}catch{r=!0}}function o(){var s=!1;return e.config.csp==="auto"?(r===null&&n(),s=r):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=Pd;return o()&&(l=Ld),l.date_to_str(s,c,e)},str_to_date:function(s,c){var l=Pd;return o()&&(l=Ld),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=i(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 ma(e,t,i,r,n){return this.date=e,this.unit=t,this.task=i,this.id=r,this.calendar=n,this}function Ia(e,t,i,r,n,o){return this.date=e,this.dir=t,this.unit=i,this.task=r,this.id=n,this.calendar=o,this}function ga(e,t,i,r,n,o,a){return this.start_date=e,this.duration=t,this.unit=i,this.step=r,this.task=n,this.id=o,this.calendar=a,this}function Ng(e,t,i,r){return this.start_date=e,this.end_date=t,this.task=i,this.calendar=r,this.unit=null,this.step=null,this}var Nd=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(Je(t)?t={date:t}:t=Ri({},t),!Xe(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 ma)return t;var i;if(t.date?i=new ma(t.date,t.unit,t.task,null,t.calendar):i=new ma(arguments[0],arguments[1],arguments[2],null,arguments[3]),i.unit=i.unit||e.config.duration_unit,!Xe(i.date))throw e.assert(!1,"Invalid date argument for isWorkTime method"),new Error("Invalid date argument for isWorkTime method");return i},getClosestWorkTimeArguments:function(t){var i=arguments[0];if(i instanceof Ia)return i;var r;if(Je(i)?r=new Ia(i):r=new Ia(i.date,i.dir,i.unit,i.task,null,i.calendar),i.id&&(r.task=i),r.dir=i.dir||"any",r.unit=i.unit||e.config.duration_unit,!Xe(r.date))throw e.assert(!1,"Invalid date argument for getClosestWorkTime method"),new Error("Invalid date argument for getClosestWorkTime method");return r},_getStartEndConfig:function(t){var i=Ng,r;if(t instanceof i)return t;if(Je(t)?r=new i(arguments[0],arguments[1],arguments[2],arguments[3]):(r=new i(t.start_date,t.end_date,t.task),t.id!==null&&t.id!==void 0&&(r.task=t)),r.unit=r.unit||e.config.duration_unit,r.step=r.step||e.config.duration_step,r.start_date=r.start_date||r.start||r.date,!Xe(r.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!Xe(r.end_date))throw e.assert(!1,"Invalid end_date argument for getDuration method"),new Error("Invalid end_date argument for getDuration method");return r},getDurationArguments:function(t,i,r,n){return this._getStartEndConfig.apply(this,arguments)},hasDurationArguments:function(t,i,r,n){return this._getStartEndConfig.apply(this,arguments)},calculateEndDateArguments:function(t,i,r,n){var o=arguments[0];if(o instanceof ga)return o;var a;if(Je(o)?a=new ga(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):a=new ga(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,!Xe(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 bd(){}bd.prototype={_getIntervals:function(e){for(var t=[],i=0;i<e.length;i+=2)t.push({start:e[i],end:e[i+1]});return t},_toHoursArray:function(e){var t=[];function i(o){var a=String(o);return a.length<2&&(a="0"+a),a}function r(o){var a=Math.floor(o/3600),s=o-a*60*60,c=Math.floor(s/60);return a+":"+i(c)}for(var n=0;n<e.length;n++)t.push(r(e[n].start)+"-"+r(e[n].end));return t},_intersectHourRanges:function(e,t){var n=[],i=e.length>t.length?e:t,r=e===i?t:e;i=i.slice(),r=r.slice();for(var n=[],o=0;o<i.length;o++)for(var a=i[o],s=0;s<r.length;s++){var c=r[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&&(r.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 i=t[0],r=1;r<t.length;r++){var n=t[r];n.start<=i.end?(n.end>i.end&&(i.end=n.end),t.splice(r,1),r--):i=n}return t},_mergeHoursConfig:function(e,t){return this._mergeAdjacentIntervals(this._intersectHourRanges(e,t))},merge:function(e,t){let i=Xt(e.getConfig()),r=Xt(t.getConfig()),n=i.parsed,o=r.parsed;n.customWeeks=i.customWeeks,o.customWeeks=r.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 Aa=class{constructor(){this.clear()}getItem(t,i,r){if(this._cache.has(t)){let o=this._cache.get(t)[r.getUTCFullYear()];if(o&&o.has(i))return o.get(i)}return-1}setItem(t,i,r,n){if(!t||!i)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(i,r)}clear(){this._cache=new Map}},va=class{constructor(){this.clear()}getItem(t,i,r){let n=this._cache;if(n&&n[t]){let o=n[t];if(o===void 0)return-1;let a=o[r.getUTCFullYear()];if(a&&a[i]!==void 0)return a[i]}return-1}setItem(t,i,r,n){if(!t||!i)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[i]=r}clear(){this._cache={}}},Ca=class{constructor(t){this.getMinutesPerWeek=i=>{let r=i.valueOf();if(this._weekCache.has(r))return this._weekCache.get(r);let n=this._calendar,o=this._calendar.$gantt,a=0,s=o.date.week_start(new Date(i));for(let c=0;c<7;c++)a+=n.getHoursPerDay(s)*60,s=o.date.add(s,1,"day");return this._weekCache.set(r,a),a},this.getMinutesPerMonth=i=>{let r=i.valueOf();if(this._monthCache.has(r))return this._monthCache.get(r);let n=this._calendar,o=this._calendar.$gantt,a=0,s=o.date.week_start(new Date(i)),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(r,a),a},this.clear=()=>{this._weekCache=new Map,this._monthCache=new Map},this.clear(),this._calendar=t}};function bg(){return typeof Map<"u"?new Aa:new va}var Sa=class{constructor(){this.clear()}_getCacheObject(t,i,r){let n=this._cache;n[i]||(n[i]=[]);let o=n[i];o||(o=n[i]={});let a=o[r];a||(a=o[r]={});let s=t.getUTCFullYear(),c=a[s];return c||(c=a[s]={durations:{},endDates:{}}),c}_endDateCacheKey(t,i){return String(t)+"-"+String(i)}_durationCacheKey(t,i){return String(t)+"-"+String(i)}getEndDate(t,i,r,n,o){let a=this._getCacheObject(t,r,n),s=t.valueOf(),c=this._endDateCacheKey(s,i),l;if(a.endDates[c]===void 0){let d=o(),u=d.valueOf();a.endDates[c]=u,a.durations[this._durationCacheKey(s,u)]=i,l=d}else l=new Date(a.endDates[c]);return l}getDuration(t,i,r,n,o){let a=this._getCacheObject(t,r,n),s=t.valueOf(),c=i.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 Ta(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=bg(),this._largeUnitsCache=new Ca(this),this._dateDurationCache=new Sa,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}Ta.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,i=this.units.length;t<i;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 i=String(e.date.valueOf());this._cached_timestamps[i]?t=this._cached_timestamps[i]:(t=Date.UTC(e.date.getUTCFullYear(),e.date.getUTCMonth(),e.date.getUTCDate()),this._cached_timestamps[i]=t,this._cached_timestamps_count++)}return t},_checkIfWorkingUnit:function(e,t){if(!this["_is_work_"+t]){let i=this.$gantt.date[`${t}_start`](new Date(e)),r=this.$gantt.date.add(i,1,t);return this.hasDuration(i,r)}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),i=e.getUTCHours(),r=0;r<t.length;r++)if(i>=t[r].startHour&&i<t[r].endHour)return!0;return!1},_getTimeOfDayStamp:function(e,t){var i=e.getUTCHours();return!e.getUTCHours()&&!e.getUTCMinutes()&&t&&(i=24),i*60*60+e.getUTCMinutes()*60},_is_work_minute:function(e){for(var t=this._getWorkHours(e),i=this._getTimeOfDayStamp(e),r=0;r<t.length;r++)if(i>=t[r].start&&i<t[r].end)return!0;return!1},_nextDate:function(e,t,i){return this.$gantt.date.add(e,i,t)},_getWorkUnitsBetweenGeneric:function(e,t,i,r){var n=this.$gantt.date,o=new Date(e),a=new Date(t);r=r||1;var s=0,c=null,l,d,u=!1;l=n[i+"_start"](new Date(o)),l.valueOf()!=o.valueOf()&&(u=!0);var f=!1;d=n[i+"_start"](new Date(t)),d.valueOf()!=t.valueOf()&&(f=!0);for(var p=!1;o.valueOf()<a.valueOf();){if(c=this._nextDate(o,i,r),p=c.valueOf()>a.valueOf(),this._isWorkTime(o,i))(u||f&&p)&&(l=n[i+"_start"](new Date(o)),d=n.add(l,r,i)),u?(u=!1,c=this._nextDate(l,i,r),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(i),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),i=this._getTimeOfDayStamp(this._nextDate(e,"hour",1));i===0&&(i=1440*60);for(var r=this._getWorkHours(e),n=0;n<r.length;n++){var o=r[n];if(t>=o.start&&i<=o.end)return 60;if(t<o.end&&i>o.start){var a=Math.min(i,o.end)-Math.max(t,o.start);return a/60}}return 0},_getMinutesPerDay:function(e){var t=this._getWorkHours(e),i=0;return t.forEach(function(r){i+=r.durationMinutes}),i},getHoursPerDay:function(e){var t=this._getWorkHours(e),i=0;return t.forEach(function(r){i+=r.durationHours}),i},_getWorkUnitsForRange:function(e,t,i,r){var n=0,o=new Date(e),a=new Date(t),s;for(i=="minute"?s=Bt(this._getMinutesPerDay,this):s=Bt(this.getHoursPerDay,this);o.valueOf()<a.valueOf();){if(a-o>1e3*60*60*24*32&&o.getUTCDate()===0){var c=this._largeUnitsCache.getMinutesPerMonth(o);i=="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);i=="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/r},_getMinutesBetweenSingleDay:function(e,t){for(var i=this._getIntervalTimestamp(e,t),r=this._getWorkHours(e),n=0,o=0;o<r.length;o++){var a=r[o];if(i.end>=a.start&&i.start<=a.end){var s=Math.max(a.start,i.start),c=Math.min(a.end,i.end);n+=(c-s)/60,i.start=c}}return Math.floor(n)},_getMinutesBetween:function(e,t,i,r){var n=new Date(e),o=new Date(t);r=r||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,i,r),p=d+f+u;return p},_getHoursBetween:function(e,t,i,r){var n=new Date(e),o=new Date(t);r=r||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,i,r)/60,u=this._getMinutesBetweenSingleDay(c,l,i,r)/60,f=this._getWorkUnitsForRange(s,c,i,r),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 i=null,r=null;for(var t in e.customWeeks){var n=e.customWeeks[t];if(n.from&&n.to){var o=n.from,a=n.to;(!i||i>o.valueOf())&&(i=o.valueOf()),(!r||r<a.valueOf())&&(r=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=i,e.parsed.customWeeksRangeEnd=r}},_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 i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0},_compareSettings:function(e,t){if(!this._arraysEqual(e.hours,t.hours))return!1;var i=Object.keys(e.dates),r=Object.keys(t.dates);if(i.sort(),r.sort(),!this._arraysEqual(i,r))return!1;for(var n=0;n<i.length;n++){var o=i[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 Ta))return!1;var t=this.getConfig(),i=e.getConfig();if(!this._compareSettings(t,i))return!1;if(t.parsed.haveCustomWeeks&&i.parsed.haveCustomWeeks){if(t.parsed.customWeeksBoundaries.length!=i.parsed.customWeeksBoundaries.length)return!1;for(var r in t.parsed.customWeeks){var n=t.parsed.customWeeks[r],o=i.parsed.customWeeks[r];if(!o||!this._compareSettings(n,o))return!1}}else if(t.parse.haveCustomWeeks!==i.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 i=this.getConfig();if(t!==!1&&(i=i.parsed),!e)return i.hours;let r=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));var n=this._timestamp({date:r});if(i.haveCustomWeeks&&i.customWeeksRangeStart<=n&&i.customWeeksRangeEnd>n){for(var o=0;o<i.customWeeksBoundaries.length;o++)if(i.customWeeksBoundaries[o].from<=n&&i.customWeeksBoundaries[o].to>n){i=i.customWeeks[i.customWeeksBoundaries[o].name];break}}var a=!0;return i.dates[n]!==void 0?a=i.dates[n]:i.dates[e.getUTCDay()]!==void 0&&(a=i.dates[e.getUTCDay()]),a===!0?i.hours:a||[]},_getIntervalTimestamp:function(e,t){var i={start:0,end:0};i.start=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds();var r=t.getUTCHours();return!r&&!t.getUTCMinutes()&&!t.getUTCSeconds()&&e.valueOf()<t.valueOf()&&(r=24),i.end=r*60*60+t.getUTCMinutes()*60+t.getUTCSeconds(),i},_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 i=[],r=0;r<t.length;r+=2){var n=t[r],o=t[r+1],a=o-n;i.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 i}else return e},setWorkTime:function(e){return this._tryChangeCalendarSettings(Bt(function(){var t=e.hours!==void 0?e.hours:!0,i=this._timestamp(e),r=this.getConfig();if(i!==null?r.dates[i]=t:e.customWeeks||(r.hours=t),e.customWeeks){if(r.customWeeks||(r.customWeeks={}),typeof e.customWeeks=="string")i!==null?r.customWeeks[e.customWeeks].dates[i]=t:e.customWeeks||(r.customWeeks[e.customWeeks].hours=t);else if(typeof e.customWeeks=="object"&&e.customWeeks.constructor===Object)for(var n in e.customWeeks)r.customWeeks[n]=e.customWeeks[n]}this._parseSettings(),this._clearCaches()},this))},unsetWorkTime:function(e){return this._tryChangeCalendarSettings(Bt(function(){if(!e)this.reset_calendar();else{var t=this._timestamp(e);t!==null&&delete this.getConfig().dates[t]}this._parseSettings(),this._clearCaches()},this))},_isWorkTime:function(e,t){var i=-1,r=null;return r=String(e.valueOf()),i=this._workingUnitsCache.getItem(t,r,e),i==-1&&(i=this._checkIfWorkingUnit(e,t),this._workingUnitsCache.setItem(t,r,i,e)),i},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,i,r){var n=0,o=1;if(e.valueOf()>t.valueOf()){var a=t;t=e,e=a,o=-1}return i=="hour"&&r==1?n=this._getHoursBetween(e,t,i,r):i=="minute"&&r==1?n=this._getMinutesBetween(e,t,i,r):n=this._getWorkUnitsBetweenGeneric(e,t,i,r),o*Math.round(n)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,i=e.end_date,r=e.unit,n=e.step;if(!r)return!1;var o=new Date(t),a=new Date(i);for(n=n||1;o.valueOf()<a.valueOf();){if(this._isWorkTime(o,r))return!0;o=this._nextDate(o,r,n)}return!1},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,i=e.duration,r=e.unit,n=e.step;if(!r)return!1;var o=e.duration>=0?1:-1;i=Math.abs(i*1);var a=this;return this._dateDurationCache.getEndDate(t,i,r,n*o,function(){return a._calculateEndDate(t,i,r,n*o)})},_calculateEndDate:function(e,t,i,r){if(!i)return!1;if(r==1&&i=="minute")return this._calculateMinuteEndDate(e,t,r);if(r==-1&&i=="minute")return this._subtractMinuteDate(e,t,r);if(r==1&&i=="hour")return this._calculateHourEndDate(e,t,r);var n=this._addInterval(e,t,i,r,null);return n.end},_addInterval:function(e,t,i,r,n){for(var o=0,a=e;o<t&&!(n&&n(a));){var s=this._nextDate(a,i,r),c=new Date(s.valueOf()+1);r>0&&(c=new Date(s.valueOf()-1));var l=this._isWorkTime(c,i);l&&o++,a=s}return{end:a,start:e,added:o}},_addHoursUntilDayEnd:function(e,t){for(var i=this.$gantt.date.add(this.$gantt.date.day_start(new Date(e)),1,"day"),r=0,n=t,o=this._getIntervalTimestamp(e,i),a=this._getWorkHours(e),s=0;s<a.length&&r<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);r+=f,n-=f,o.start=d}}var p=i;return r===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,o.start))),{added:r,end:p}},_calculateHourEndDate:function(e,t,i){var r=new Date(e),n=0;i=i||1,t=Math.abs(t*1);var o=this._addHoursUntilDayEnd(r,t);n=o.added,r=o.end;var a=t-n;if(a){for(var s=r;n<t;){var c=this._nextDate(s,"day",i);c.setUTCHours(0),c.setUTCMinutes(0),c.setUTCSeconds(0);var l=0;if(i>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}r=s}if(n<t){var a=t-n;o=this._addHoursUntilDayEnd(r,a),r=o.end}return r},_addMinutesUntilHourEnd:function(e,t){if(e.getUTCMinutes()===0)return{added:0,end:new Date(e)};for(var i=this.$gantt.date.add(this.$gantt.date.hour_start(new Date(e)),1,"hour"),r=0,n=t,o=this._getIntervalTimestamp(e,i),a=this._getWorkHours(e),s=0;s<a.length&&r<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,r+=f,o.start=d}}var p=i;return r===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,o.start))),{added:r,end:p}},_subtractMinutesUntilHourStart:function(e,t){for(var i=this.$gantt.date.hour_start(new Date(e)),r=0,n=t,o=i.getUTCHours()*60*60+i.getUTCMinutes()*60+i.getUTCSeconds(),a=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds(),s=this._getWorkHours(e),c=s.length-1;c>=0&&r<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,r+=p,a=u}}var y=i;return r===t&&(y=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a))),{added:r,end:y}},_subtractMinuteDate:function(e,t,i){var r=this.getClosestWorkTime({date:e,dir:"past",unit:"minute"}),n=0;i=i||-1,t=Math.abs(t*1),t=Math.round(t);let o=this._isMinutePrecision(r),a=this._subtractMinutesUntilHourStart(r,t);n+=a.added,r=a.end;for(var s=0,c=[],l=0;n<t;){var d=this.$gantt.date.day_start(new Date(r)),u=!1;r.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(r,u);if(!c.length||!l){r=this.$gantt.date.add(r,-1,"day");continue}if(c[c.length-1].end<=y&&p>l){n+=l,r=this.$gantt.date.add(r,-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,r=this.$gantt.date.add(r,-A.durationMinutes,"minute");else if(!o&&p<=y/60-A.startMinute)n+=p,r=this.$gantt.date.add(r,-p,"minute");else if(o)p<=y/60-A.startMinute?(n+=p,r=this.$gantt.date.add(r,-p,"minute")):(n+=y/60-A.startMinute,k?r=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,k.end)):r=this.$gantt.date.day_start(r));else{var F=this._getMinutesPerHour(r);F<=p?(n+=F,r=this._nextDate(r,"hour",i)):(a=this._subtractMinutesUntilHourStart(r,p),n+=a.added,r=a.end)}else if(r.getUTCHours()===0&&r.getUTCMinutes()===0&&r.getUTCSeconds()===0){var h=this._getClosestWorkTimePast(r,"hour");if(h.valueOf()===r.valueOf()){var h=this.$gantt.date.add(r,-1,"day"),R=this._getWorkHours(h);if(R.length){var M=R[R.length-1];h.setUTCSeconds(M.durationSeconds)}}r=h}else r=this._getClosestWorkTimePast(new Date(r-1),"hour")}if(n<t){var T=t-n;a=this._subtractMinutesUntilHourStart(r,T),n+=a.added,r=a.end}return r},_calculateMinuteEndDate:function(e,t,i){var r=new Date(e),n=0;i=i||1,t=Math.abs(t*1),t=Math.round(t);var o=this._addMinutesUntilHourEnd(r,t);n+=o.added,r=o.end;for(var a=0,s=[],c=0,l=this._isMinutePrecision(r);n<t;){var d=this.$gantt.date.day_start(new Date(r)).valueOf();d!==a&&(s=this._getWorkHours(r),c=this._getMinutesPerDay(r),a=d);var u=t-n,f=this._getTimeOfDayStamp(r);if(!s.length||!c){r=this.$gantt.date.add(this.$gantt.date.day_start(r),1,"day");continue}if(s[0].start>=f&&u>=c){if(n+=c,u==c){r=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,s[s.length-1].end));break}else r=this.$gantt.date.add(r,1,"day"),r=this.$gantt.date.day_start(r);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,r=this.$gantt.date.add(r,y.durationMinutes,"minute");else if(u<=y.endMinute-f/60)n+=u,r=this.$gantt.date.add(r,u,"minute");else{var A=this._getMinutesPerHour(r);A<=u?(n+=A,l?r=this.$gantt.date.add(r,A,"minute"):r=this._nextDate(r,"hour",i)):(o=this._addMinutesUntilHourEnd(r,u),n+=o.added,r=o.end)}else r=this._getClosestWorkTimeFuture(r,"hour")}if(n<t){var k=t-n;o=this._addMinutesUntilHourEnd(r,k),n+=o.added,r=o.end}return r},getClosestWorkTime:function(){var e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._getClosestWorkTime(e.date,e.unit,e.dir)},_getClosestWorkTime:function(e,t,i){var r=new Date(e);if(this._isWorkTime(r,t))return r;if(r=this.$gantt.date[t+"_start"](r),i=="any"||!i){var n=this._getClosestWorkTimeFuture(r,t),o=this._getClosestWorkTimePast(r,t);Math.abs(n-e)<=Math.abs(e-o)?r=n:r=o}else i=="past"?r=this._getClosestWorkTimePast(r,t):r=this._getClosestWorkTimeFuture(r,t);return r},_getClosestWorkTimeFuture:function(e,t){return this._getClosestWorkTimeGeneric(e,t,1)},_getClosestWorkTimePast:function(e,t){var i=this._getClosestWorkTimeGeneric(e,t,-1);return this.$gantt.date.add(i,1,t)},_findClosestTimeInDay:function(e,t,i){var r=new Date(e),n=null,o=!1;this._getWorkHours(r).length||(r=this._getClosestWorkTime(r,"day",t<0?"past":"future"),t<0&&(r=new Date(r.valueOf()-1),o=!0),i=this._getWorkHours(r));var a=this._getTimeOfDayStamp(r);if(o&&(a=this._getTimeOfDayStamp(new Date(r.valueOf()+1),o)),t>0){for(var s=0;s<i.length;s++)if(i[s].start>=a){n=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,i[s].start));break}}else for(var s=i.length-1;s>=0;s--)if(i[s].end<=a){n=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,i[s].end));break}else if(i[s].end>a&&i[s].start<=a){n=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,a));break}return n},_getClosestWorkMinute:function(e,t,i){var r=new Date(e),n=this._getWorkHours(r),o=this._findClosestTimeInDay(r,i,n);return o||(i>0?(r=this.calculateEndDate(r,i,t),r=this.$gantt.date.day_start(r)):(r=this.calculateEndDate(r,i,"day"),r=this.$gantt.date.day_start(r),r=this.$gantt.date.add(r,1,"day"),r=new Date(r.valueOf()-1)),n=this._getWorkHours(r),o=this._findClosestTimeInDay(r,i,n)),i<0&&(o=this.$gantt.date.add(o,-1,t)),o},_getClosestWorkTimeGeneric:function(e,t,i){if(t==="hour"||t==="minute")return this._getClosestWorkMinute(e,t,i);for(var r=this._getUnitOrder(t),n=this.units[r-1],o=e,a=3e3,s=0;!this._isWorkTime(o,t)&&!(n&&!this._isWorkTime(o,n)&&(i>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,i,t),this.$gantt.date[t+"_start"]&&(o=this.$gantt.date[t+"_start"](o))}return o},hasWorkTime:function(){var e=this.getConfig(),t=e.dates,i=[0,1,2,3,4,5,6];for(var r in e.dates);var n=this._checkWorkHours(e.hours),o=!1;return i.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,i=0;i<e.length;i+=2)e[i]!==e[i+1]&&(t=!0);return t},_isMinutePrecision:function(e){let t=!1;return this._getWorkHours(e).forEach(function(i){(i.startMinute%60||i.endMinute%60)&&(t=!0)}),t}};var or={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,i=e.resource_property;if(this.isLegacyResourceCalendarFormat(t))for(var r in e){i=r;break}return i},getCalendarIdFromLegacyConfig:function(e,t){if(t)for(var i in t){var r=t[i];if(e[i]){var n=r[e[i]];if(n)return n}}return null}};function Fg(){function e(n){return n.map(function(o){return o&&o.resource_id?o.resource_id:o}).sort().join("-")}var t={};function i(n,o){return o.mergeCalendars(n.map(function(a){var s=a&&a.resource_id?a.resource_id:a;return o.getResourceCalendar(s)}))}function r(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=i(n,o);return t[a]=s,o.addCalendar(s)}else return null}return{getCalendarIdFromMultipleResources:r}}var wg=Fg();function Fd(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=or.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))}Fd.prototype={_calendars:{},_convertWorkTimeSettings:function(e){let t=e.days;if(typeof t=="object"&&!Array.isArray(t)&&t!==null){let i={};if(t?.weekdays)for(let r=0;r<7;r++)i[r]=t.weekdays[r];t?.dates&&Object.entries(t.dates).forEach(([r,n])=>{i[new Date(r).valueOf()]=n}),Object.entries(i).forEach(([r,n])=>{n instanceof Array||(i[r]=!!n)}),e={...e,dates:i}}else if(t&&!e.dates){e.dates=e.dates||{};for(let i=0;i<t.length;i++)e.dates[i]=t[i],t[i]instanceof Array||(e.dates[i]=!!t[i])}return delete e.days,e},mergeCalendars:function(){var e=[],t=arguments;if(Array.isArray(t[0]))e=t[0].slice();else for(var i=0;i<arguments.length;i++)e.push(arguments[i]);var r=new bd,n;return e.forEach((function(o){n?n=this._createCalendarFromConfig(r.merge(n,o)):n=o}).bind(this)),this.createCalendar(n)},_createCalendarFromConfig:function(e){var t=new Ta(this.$gantt,Nd(this.$gantt));t.id=String(ha());var i=this._convertWorkTimeSettings(e);if(i.customWeeks)for(var r in i.customWeeks)i.customWeeks[r]=this._convertWorkTimeSettings(i.customWeeks[r]);return t._setConfig(i),t},createCalendar:function(e){var t;e||(e={}),e.getConfig?t=Xt(e.getConfig()):e.worktime?t=Xt(e.worktime):t=Xt(e);var i=Xt(this.defaults.fulltime.worktime);return Ri(t,i),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 i,r,n;if(this._legacyConfig===!1?n=t.resource_property:n=or.getResourceProperty(t),Array.isArray(e[n])&&e[n].length)t.dynamic_resource_calendars?r=wg.getCalendarIdFromMultipleResources(e[n],this):i=this.getResourceCalendar(e[n]);else if(this._legacyConfig===void 0&&(this._legacyConfig=or.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var r=or.getCalendarIdFromLegacyConfig(e,t.resource_calendars);else if(n&&e[n]&&t.resource_calendars[e[n]])var i=this.getResourceCalendar(e[n]);if(r&&(i=this.getCalendar(r)),i)return i}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 i=this.$gantt.config,r=i.resource_calendars,n=null;if(Array.isArray(e)&&e.length===1&&(typeof e[0]=="object"?t=e[0].resource_id:t=e[0]),r){if(this._legacyConfig===void 0&&(this._legacyConfig=or.isLegacyResourceCalendarFormat(i.resource_calendars)),this._legacyConfig){for(var o in r)if(r[o][t]){n=r[o][t];break}}else var n=r[t];if(n)return this.getCalendar(n)}return this.getCalendar()},getTaskCalendar:function(e){var t=this.$gantt,i;if(e==null)return this.getCalendar();if((typeof e=="number"||typeof e=="string")&&t.isTaskExists(e)?i=t.getTask(e):i=e,!i)return this.getCalendar();var r=this._getOwnCalendar(i),n=!!t.getState().group_mode;if(!r&&t.config.inherit_calendar&&t.isTaskExists(i.parent)){for(var o=i;t.isTaskExists(o.parent)&&(o=t.getTask(o.parent),!(t.isSummaryTask(o)&&(r=this._getOwnCalendar(o),r))););n&&!r&&e.$effective_calendar&&(r=this.getCalendar(e.$effective_calendar))}return r||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 i=this.$gantt.config;return e.id=e.id||ha(),this._calendars[e.id]=e,i.worktimes||(i.worktimes={}),i.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 i=e[t],r=this.createCalendar(i);r.id=t,this.addCalendar(r)}},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(i){return i instanceof Function})}};function Da(e,t){this.argumentsHelper=t,this.$gantt=e}Da.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,i=e.end_date,r=e.unit,n=e.step;return this._calculateDuration(t,i,r,n)},_calculateDuration:function(e,t,i,r){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[i])a=Math.round((t-e)/(r*o[i]));else{for(var s=new Date(e),c=new Date(t);s.valueOf()<c.valueOf();)a+=1,s=n.add(s,r,i);s.valueOf()!=t.valueOf()&&(a+=(c-s)/(n.add(s,r,i)-s))}return Math.round(a)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,i=e.end_date,r=e.unit;return r?(t=new Date(t),i=new Date(i),t.valueOf()<i.valueOf()):!1},hasWorkTime:function(){return!0},equals:function(e){return e instanceof Da},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,i=e.duration,r=e.unit,n=e.step;return this.$gantt.date.add(t,n*i,r)}};function wd(e){this.$gantt=e.$gantt,this.argumentsHelper=Nd(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new Da(this.$gantt,this.argumentsHelper)}wd.prototype={_getCalendar:function(e){var t;if(!this.$gantt.config.work_time)t=this.$disabledCalendar;else{var i=this.calendarManager;e.task?t=i.getTaskCalendar(e.task):e.id?t=i.getTaskCalendar(e):e.calendar&&(t=e.calendar),t||(t=i.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,i,r){var n=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return r=this._getCalendar(n),r.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),i=this._getCalendar(t);return i.calculateEndDate(t)}};var xg=function(e,t){return{getWorkHours:function(i){return t.getWorkHours(i)},setWorkTime:function(i){return t.setWorkTime(i)},unsetWorkTime:function(i){t.unsetWorkTime(i)},isWorkTime:function(i,r,n){return t.isWorkTime(i,r,n)},getClosestWorkTime:function(i){return t.getClosestWorkTime(i)},calculateDuration:function(i,r,n){return t.calculateDuration(i,r,n)},_hasDuration:function(i,r,n){return t.hasDuration(i,r,n)},calculateEndDate:function(i,r,n,o){return t.calculateEndDate(i,r,n,o)},mergeCalendars:Bt(e.mergeCalendars,e),createCalendar:Bt(e.createCalendar,e),addCalendar:Bt(e.addCalendar,e),getCalendar:Bt(e.getCalendar,e),getCalendars:Bt(e.getCalendars,e),getResourceCalendar:Bt(e.getResourceCalendar,e),getTaskCalendar:Bt(e.getTaskCalendar,e),deleteCalendar:Bt(e.deleteCalendar,e)}},Mg={create:xg};function xd(e){var t=new Fd(e),i=new wd(t),r=Mg.create(t,i);Ri(e,r)}var Md={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 Ud(e={}){let t=e.config||{},i={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||Md,templates:e.templates||{},getTask:e.getTask||function(r){return null},isTaskExists:e.isTaskExists||function(r){return!1},isSummaryTask:e.isSummaryTask||function(r){return!1},getState:function(){return{group_mode:!1}},callEvent:function(r,n){let o=e.onEvent;return o&&o(r,n),!0},attachEvent:function(){return 0},checkEvent:function(){return!1},detachEvent:function(){},defined:Rd,mixin:Ri,copy:Xt,assert:function(r,n){if(!r){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 i._correct_dst_change=function(r){return r},i.date=Od(i),i.date.init(),xd(i),i}function Ug(e={}){let t=Ud(e);return{addCalendar:function(i){return t.addCalendar(i)},deleteCalendar:function(i){return t.deleteCalendar(i)},getCalendar:function(i){return t.getCalendar(i)},getCalendars:function(){return t.getCalendars()},mergeCalendars:function(){return t.mergeCalendars.apply(t,arguments)},getTaskCalendar:function(i){return t.getTaskCalendar(i)},getResourceCalendar:function(i){return t.getResourceCalendar(i)},setWorkTime:function(i){return t.setWorkTime(i)},unsetWorkTime:function(i){return t.unsetWorkTime(i)},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 Hd={createCalendar:Ug};var a0=3600*1e3;function jd(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:Hg}=Hd,ar="__replay_default__";function Bg(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 i=t[0],r=t[t.length-1];return t.every((o,a)=>o===i+a)?[`${i}:00-${r+1}:00`]:e}var Bd={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},Wd="__main_global__",Wg={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function Vd(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 Vg(e){let t={};if(Array.isArray(e.days))for(let r=0;r<e.days.length;r+=1)t[r]=e.days[r];if(e.dates)for(let[r,n]of Object.entries(e.dates))t[r]=n;let i={hours:Bg(e.hours),dates:t};return e.customWeeks&&(i.customWeeks=e.customWeeks),i}function Kd(e){let t=Hg({config:{work_time:!0}});t.addCalendar({id:ar,worktime:Bd}),t.addCalendar({id:Wd,worktime:Wg});let i=new Set(e.filter(d=>!Vd(d.worktime)).map(d=>String(d.id))),r=e.filter(d=>Vd(d.worktime));for(let d of r)t.addCalendar({id:d.id,worktime:d.worktime?Vg(d.worktime):Bd});let n=kd(t),o=n.getCalendar(ar),a=n.getCalendar(Wd);if(!o||!a)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let s=new Set([ar]);for(let d of r)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:i.has(u)&&(p=a),c.set(u,p),p}}}}function Yd(e){return{hasChildren(t){return e.hasChildren(t)},getParentStartDateIfHasPredecessors(t){let i=e.getActivity(t);if(!i)return null;let r=e.getParent(i.id);return!r||e.getIncomingLinkIds(r.id).length===0?null:r.startDate},getDescendantIds(t){return jg(e,t).map(i=>String(i))},getAncestorIds(t){let i=[],r=e.getActivity(t);for(;r;){let n=r.parentId;if(n===null)break;let o=e.getActivity(n);if(!o)break;i.push(String(n)),r=o}return i},getChildProgressInfo(t){return e.getChildren(t).map(r=>{let n=e.getActivity(r);return{id:r,progress:Number(n?.progress??0),ponderator:Number(n?.ponderator??0)}})},getChildHhInfo(t){return e.getChildren(t).map(r=>{let n=e.getActivity(r);return{id:r,workHours:Number(n?.workHours??0),progress:Number(n?.progress??0),realWorkHours:Number(n?.realWorkHours??0)}})},getChildUsedCostInfo(t){return e.getChildren(t).map(r=>{let n=e.getActivity(r);return{id:r,usedCost:Number(n?.usedCost??0)}})},getChildCostInfo(t){return e.getChildren(t).map(r=>{let n=e.getActivity(r);return{id:r,cost:Number(n?.cost??0)}})}}}function jg(e,t){let i=[],r=new Ut;for(let n of e.getChildren(t))r.enqueue(n);for(;!r.isEmpty();){let n=r.dequeue();i.push(n);for(let o of e.getChildren(n))r.enqueue(o)}return i}var On=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let i=Gd(t);return this.reader.getCalendar(i??ar)}getClosestWorkTime(t){let i=`${_a(t.task)}|${t.dir}|${t.date.getTime()}`;return Ea(this._cache.closestWorkTime,i,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:ut.HOUR}))}calculateEndDate(t){let i=`${_a(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return Ea(this._cache.endDate,i,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let i=`${_a(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return Ea(this._cache.duration,i,()=>this.resolveCalendar(t.task).calculateDuration(t.startDate,t.endDate))}clearCache(){this._cache.closestWorkTime.clear(),this._cache.endDate.clear(),this._cache.duration.clear()}};function Ea(e,t,i){let r=e.get(t);if(r!==void 0)return r;let n=i();return e.set(t,n),n}var Kg="__default__";function Gd(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function _a(e){return Gd(e)??Kg}var Nn=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,i){let r=this.activities.get(t)?.parentId,n=0,o=this.activities.size;for(;r&&!U(r);){if(r===i)return!0;if(++n>o)return!1;r=this.activities.get(r)?.parentId}return!1}getParent(t){let i=this.activities.get(t)?.parentId;return!i||U(i)?null:this.activities.get(i)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,i){if(this._dirty)return;if(U(t)){this._roots.push(i);return}let r=String(t),n=this._childrenByParent.get(r);n?n.push(i):this._childrenByParent.set(r,[i])}rebuild(){this._childrenByParent.clear(),this._roots=[];for(let i of this.activities.values()){if(U(i.parentId)){this._roots.push(i.id);continue}let r=String(i.parentId),n=this._childrenByParent.get(r)??[];n.push(i.id),this._childrenByParent.set(r,n)}let t=(i,r)=>{let n=this.activities.get(i),o=this.activities.get(r);return n&&o?Ar(n,o):String(i).localeCompare(String(r))};this._roots.sort(t);for(let i of this._childrenByParent.values())i.sort(t)}};var bn=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,i){return i===this.checkedSet.has(t)?!1:(i?this.checkedSet.add(t):this.checkedSet.delete(t),!0)}setVisible(t,i){return i===!this.hiddenSet.has(t)?!1:(i?this.hiddenSet.delete(t):this.hiddenSet.add(t),!0)}forget(t){this.checkedSet.delete(t),this.hiddenSet.delete(t)}hydrate(t){this.checkedSet=new Set(t.checkedIds??[]),this.hiddenSet=new Set(t.hiddenIds??[]),this.activeFilter=null,this.activeOrder=null}snapshot(){return{checked:new Set(this.checkedSet),hidden:new Set(this.hiddenSet),activeFilter:this.activeFilter,activeOrder:this.activeOrder}}restore(t){this.checkedSet=new Set(t.checked),this.hiddenSet=new Set(t.hidden),this.activeFilter=t.activeFilter,this.activeOrder=t.activeOrder}};var Pi=class e{_activities=new Map;_lastStartDate=new Map;_promotionSnapshot=new Map;_progressFallback=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_buildOrderComparator;_cache={ids:null,visualOrderIds:null,orderComparator:null};_writeCapture=new dn;_viewState=new bn;_filterProjection=null;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_calendar;_flags;_calendarSnapshot;constructor(t,i=()=>null){this._buildOrderComparator=i,this._calendarSnapshot=w(t.calendars);for(let r of t.activities)this._activities.set(r.id,r);for(let r of t.links){let n={...r,freeSlackHours:r.freeSlackHours??null,isCritical:r.isCritical===!0};this._links.set(String(r.id),n),this._indexLink(n)}this._calendar=new On(Kd(this._calendarSnapshot)),this._flags=Gg(t),this._hierarchy=new Nn(this._activities),this._hierarchy.rebuild()}fork(){let t=new e({activities:this.getAllActivities().map(ce),links:this.getAllLinks().map(i=>({...i})),calendars:w(this._calendarSnapshot)},this._buildOrderComparator);return t._viewState.restore(w(this._viewState.snapshot())),t._lastStartDate=new Map(Array.from(this._lastStartDate,([i,r])=>[i,new Date(r)])),t._promotionSnapshot=new Map(Array.from(this._promotionSnapshot,([i,r])=>[i,w(r)])),t._progressFallback=new Map(this._progressFallback),t._flags=w(this._flags),t._filterProjection=w(this._filterProjection),t}getAllActivities(){return Array.from(this._activities.values())}getAllLinks(){return Array.from(this._links.values())}getAllIds(){return this._cache.ids?this._cache.ids:(this._cache.ids=Array.from(this._activities.keys()),this._cache.ids)}activityCount(){return this._activities.size}getVisualOrderIds(){return this._cache.visualOrderIds?this._cache.visualOrderIds:(this._cache.visualOrderIds=Is(this).map(t=>String(t.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null}forEachActivity(t){for(let[i,r]of this._activities)t(r,i)}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,i){this._captureLastStartDateOnce(),this._lastStartDate.set(String(t),i)}getPromotionSnapshot(t){return this._promotionSnapshot.get(String(t))??null}setPromotionSnapshot(t,i){this._capturePromotionSnapshotOnce(),this._promotionSnapshot.set(String(t),i)}getProgressFallback(t){return this._progressFallback.get(String(t))??null}setProgressFallback(t,i){let r=String(t),n=this._progressFallback.get(r)??null;Object.is(n,i)||(this._writeCapture.noteProgressFallback(r,n),i===null?this._progressFallback.delete(r):this._progressFallback.set(r,i))}_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,i){return this._captureViewStateOnce(),this._viewState.setChecked(String(t),i)}setVisible(t,i){return this._captureViewStateOnce(),this._viewState.setVisible(String(t),i)}getActiveFilter(){return this._viewState.getActiveFilter()}setActiveFilter(t){this._captureViewStateOnce(),this._viewState.setActiveFilter(t),this._filterProjection=null}getFilterProjection(){return this._filterProjection}setFilterProjection(t){this._filterProjection=t}getActiveOrder(){return this._viewState.getActiveOrder()}setActiveOrder(t){this._captureViewStateOnce(),this._viewState.setActiveOrder(t),this.invalidateDerivedOrder()}getOrderComparator(){let t=this._viewState.getActiveOrder();return t===null?(this._cache.orderComparator=null,null):this._cache.orderComparator?this._cache.orderComparator:(this._cache.orderComparator=this._buildOrderComparator(t),this._cache.orderComparator)}invalidateDerivedOrder(){this._cache.orderComparator=null,this._cache.visualOrderIds=null}hydrateViewState(t){this._viewState.hydrate(t),this._filterProjection=null,this.invalidateDerivedOrder()}_captureViewStateOnce(){this._writeCapture.peek()!==null&&this._viewStateBefore===null&&(this._viewStateBefore=this._viewState.snapshot())}getOutgoingLinkIds(t){return this._outgoing.get(String(t))??$d}getIncomingLinkIds(t){return this._incoming.get(String(t))??$d}getChildren(t){return this._hierarchy.getChildren(t)}hasChildren(t){return this._hierarchy.hasChildren(t)}isChildOf(t,i){return this._hierarchy.isChildOf(t,i)}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,i,r){let n=this.getActivity(t);n&&(this._writeCapture.note(String(t),n),n[i]=r,Ra(n,i),i===b.PARENT&&this._hierarchy.markDirty(),ka(i)&&(this._cache.visualOrderIds=null))}setActivityFieldDynamic(t,i,r){let n=this.getActivity(t);if(n){if(!Object.hasOwn(n,i))throw new Error(`setActivityFieldDynamic: unknown CoreActivity field "${i}"`);this._writeCapture.note(String(t),n),Reflect.set(n,i,_d(i,r)),Ra(n,i),i===b.PARENT&&this._hierarchy.markDirty(),ka(i)&&(this._cache.visualOrderIds=null)}}setActivityFields(t,i){let r=this.getActivity(t);if(!r)return;this._writeCapture.note(String(t),r);let n=!1;for(let o of Object.keys(i))Reflect.set(r,o,Reflect.get(i,o)),Ra(r,o),o===b.PARENT&&(n=!0),ka(o)&&(this._cache.visualOrderIds=null);n&&this._hierarchy.markDirty()}addLink(t){this._writeCapture.noteLinkAdd(String(t.id));let i=this._links.get(String(t.id));i&&this._deindexLink(i);let r={...t,freeSlackHours:t.freeSlackHours??null,isCritical:t.isCritical===!0};this._links.set(String(t.id),r),this._indexLink(r)}_indexLink(t){zd(this._outgoing,String(t.source),t.id),zd(this._incoming,String(t.target),t.id)}_deindexLink(t){let i=this._outgoing.get(String(t.source));i&&this._outgoing.set(String(t.source),Pa(i,t.id));let r=this._incoming.get(String(t.target));r&&this._incoming.set(String(t.target),Pa(r,t.id))}_removeLinkRef(t,i,r){let n=t.get(i);n&&t.set(i,Pa(n,r))}_insertLinkRefInOrder(t,i,r){let n=new Set;for(let s of this._links.keys()){if(String(s)===String(r))break;n.add(String(s))}let o=[...t.get(i)??[]],a=o.findIndex(s=>!n.has(String(s)));o.splice(a<0?o.length:a,0,r),t.set(i,o)}setLinkField(t,i,r){let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),n[i]=r)}setLinkEndpoints(t,i,r){let n=this.getLink(t);if(!n)return;let o=String(n.source)!==String(i),a=String(n.target)!==String(r);!o&&!a||(this._writeCapture.noteLinkField(String(t),n),o&&(this._removeLinkRef(this._outgoing,String(n.source),n.id),n.source=i,this._insertLinkRefInOrder(this._outgoing,String(i),n.id)),a&&(this._removeLinkRef(this._incoming,String(n.target),n.id),n.target=r,this._insertLinkRefInOrder(this._incoming,String(r),n.id)))}setLinkFieldDynamic(t,i,r){let n=this.getLink(t);if(n){if(i===wt.SOURCE){this.setLinkEndpoints(t,String(r),n.target);return}if(i===wt.TARGET){this.setLinkEndpoints(t,n.source,String(r));return}Yg(i)&&(this._writeCapture.noteLinkField(String(t),n),Reflect.set(n,i,r))}}setLinkProplannerId(t,i){let r=this.getLink(t);r&&(this._writeCapture.noteLinkField(String(t),r),r.proplannerId=i)}removeLink(t){let i=this.getLink(t);i&&(this._writeCapture.noteLinkRemove(String(t),i),this._links.delete(String(t)),this._deindexLink(i))}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 i=this.getActivity(t);i&&this._writeCapture.noteRemove(String(t),i);let r=String(t);this.setProgressFallback(r,null),(this._viewState.isChecked(r)||!this._viewState.isVisible(r))&&this._captureViewStateOnce(),this._viewState.forget(r),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,i){this._writeCapture.noteCorrelativeBefore(t,i)}noteScheduledBefore(t,i){this._writeCapture.noteScheduledBefore(t,i)}restoreFromCapture(){let t=this._writeCapture.peek();if(!t)return;let{ops:i,before:r,correlativeBefore:n,scheduledBefore:o,progressFallbackBefore:a}=t;this._undoLinkAdds(i),this._undoInserts(i),this._reInsertRemovedActivities(i),this._reAddRemovedLinks(i),this._restoreLinkFields(i),this._restoreActivityFields(o),this._restoreActivityFields(r),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[i,r]of t)r===null?this._progressFallback.delete(i):this._progressFallback.set(i,r)}_restoreCorrelatives(t){for(let[i,r]of t){let n=this._activities.get(i);n&&(n.correlativeId=r)}}_undoLinkAdds(t){for(let i of t)i.kind===Rt.LINK_ADD&&this._detachLink(i.linkId)}_undoInserts(t){for(let i of t)i.kind===Rt.INSERT&&this._activities.delete(i.activityId)}_reInsertRemovedActivities(t){for(let i of t)i.kind===Rt.REMOVE&&this._activities.set(i.activityId,i.before)}_reAddRemovedLinks(t){for(let i of t)i.kind===Rt.LINK_REMOVE&&this._attachLink(i.before)}_restoreLinkFields(t){for(let i of t){if(i.kind!==Rt.LINK_FIELD)continue;let r=this._links.get(i.linkId);if(r){this.setLinkEndpoints(i.linkId,i.before.source,i.before.target);for(let n of Object.keys(r))Object.hasOwn(i.before,n)||Reflect.deleteProperty(r,n);Object.assign(r,i.before)}}}_restoreActivityFields(t){for(let[i,r]of t){let n=this._activities.get(i);n&&this._restoreScalarFields(n,r)}}_restoreScalarFields(t,i){for(let r of Object.keys(t))Object.hasOwn(i,r)||Reflect.deleteProperty(t,r);for(let r of Object.keys(i))Reflect.set(t,r,Reflect.get(i,r))}_attachLink(t){this._links.set(String(t.id),{...t}),this._indexLink(t)}_detachLink(t){let i=this.getLink(t);i&&(this._links.delete(String(t)),this._deindexLink(i))}},$d=[];function Yg(e){return e===wt.LAG||e===wt.TYPE||e===wt.FREE_SLACK_HOURS||e===wt.IS_CRITICAL}function ka(e){return e===b.PARENT||e===b.CORRELATIVE_ID}function Ra(e,t){t!==b.START_DATE&&t!==b.END_DATE&&t!==b.TYPE||(e.calendarDuration=te(e))}function Pa(e,t){return e.filter(i=>String(i)!==String(t))}function zd(e,t,i){let r=e.get(t);r?r.push(i):e.set(t,[i])}function Gg(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 La(e,t){let i=e.getActivity(t);return i?w(i):null}function qd(e){return e.getAllActivities().map(w)}function Jd(e){return e.getAllIds().map(String)}function Xd(e,t){e.forEachActivity((i,r)=>t(r))}function Zd(e,t){let i=t==="0"?Oa(e,"0"):e.getChildren(t),r=[];for(let n of i){let o=e.getActivity(n);o&&r.push(w(o))}return r.sort((n,o)=>(n.correlativeId??0)-(o.correlativeId??0)),r}function Oa(e,t){return Wt(t,e)}function Qd(e){return e.checkedIds().map(String)}function tu(e,t){if(t==="0"){let i=!1;return e.forEachActivity(r=>{i||=U(r.parentId)}),i}return e.getChildren(t).length>0}function Na(e,t){let i=e.getLink(t);return i?Mt(i):null}function eu(e){return e.getAllLinks().map(t=>Mt(t))}function Fn(e){let[t,i]=e.split(":");return Number(t)*60+Number(i??0)}function $g(e){return e.reduce((t,i)=>Fn(i)<Fn(t)?i:t)}function zg(e){return e.reduce((t,i)=>Fn(i)>Fn(t)?i:t)}function qg(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function iu(e){let t=[...e].find(o=>o.is_default);if(!t)return null;let i=qg(t);if(i.length===0)return null;let r=i.map(o=>o.split("-")[0]),n=i.map(o=>o.split("-")[1]);return{startHour:$g(r),endHour:zg(n)}}function ba(e,t){return{calendars:e.calendarReader,hierarchy:Yd(e),activityReader:jd(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay}}function ru(e){return $e(e)}var Jg=new Set(["freeSlackHours","isCritical"]);function Xg(e,t){let i=Object.fromEntries(Object.entries(e.fields??{}).filter(([r])=>!t.has(r)));return e.kind===N.UPDATED&&Object.keys(i).length===0?null:{...e,...e.fields===void 0?{}:{fields:i},after:null}}function su(e){let t=e.activities.map(n=>({...n,after:null})),i=e.links.map(n=>Xg(n,Jg)).filter(n=>n!==null),r=e.source.kind===pe?{...e.source,items:[],links:[]}:e.source;return w({...e,source:r,activities:t,links:i})}function Fa(e,t,i,r,n,o,a){return{changeSet:e,beforeSnap:t,beforeLinks:nu(i),afterSnap:r,afterLinks:nu(n),progressFallbackBefore:o,progressFallbackAfter:a}}function nu(e){if(e)return new Map(Array.from(e,([t,i])=>[t,{...i,freeSlackHours:null,isCritical:!1}]))}function cu(e,t){let i=new Map,r=new Map;for(let n of t.activities){if(n.kind!==N.CREATED)continue;let o=e.getActivity(String(n.id));o&&i.set(String(n.id),nt(o))}for(let n of t.links){if(n.kind===N.DELETED)continue;let o=e.getLink(String(n.id));o&&r.set(String(n.id),{...o})}return{afterSnap:i,afterLinks:r}}function lu(e){return e.kind!==I.INLINE_EDIT||!er.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function ou(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 du(e,t){if(!ou(e)||!ou(t))return!1;let i=e.changeSet.activities[0],r=t.changeSet.activities[0];return!!i&&!!r&&String(i.id)===String(r.id)}function uu(e,t){let i=e.changeSet.activities[0],r=t.changeSet.activities[0];if(!i||!r)return t;let n=i.fields??{},o=r.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:[{...r,fields:a}]};return Fa(s)}var Li={RECORD:"record",SKIP:"skip",CHECKPOINT_ON_SUCCESS:"checkpoint-on-success"},dt={BEFORE:"before",AFTER:"after"};function fu(e){return e.kind===I.PERSISTENCE_ACKNOWLEDGE?Li.CHECKPOINT_ON_SUCCESS:e.kind===I.SIR_SYNC||e.kind===I.CALENDAR_RECONCILE||e.kind===I.ACTIVITY_LOOKAHEAD_SYNC||e.kind===I.BASELINE_APPLY||e.kind===I.PONDERATOR_CRITERION_SET||e.kind===I.STATUS_CRITERIA_SET||e.kind===I.ACTIVITY_CLIPBOARD_CLEAR||e.kind===I.ACTIVITY_COPY||e.kind===I.SELECTION_TOGGLE||e.kind===I.SELECTION_REPLACE||e.kind===I.VISIBILITY_SET||e.kind===I.FILTER_SET||e.kind===I.SORT_SET?Li.SKIP:Li.RECORD}function wa(e){for(let t of e.changeSet.activities)if(t.kind===N.CREATED||t.kind===N.DELETED||t.kind===N.UPDATED&&t.fields&&E.CUSTOM_ID in t.fields)return!0;return!1}function xa(e,t,i){let r=[],n=[];for(let a of t.changeSet.activities){let s=String(a.id);if(a.kind===N.UPDATED){let c=e.getActivity(s);r.push({id:s,kind:N.UPDATED,fields:au(a.fields,i),after:c?nt(c):null})}else if(a.kind===N.DELETED)if(i===dt.BEFORE){let c=e.getActivity(s);r.push({id:s,kind:N.CREATED,after:c?nt(c):null})}else r.push({id:s,kind:N.DELETED,after:null});else if(i===dt.BEFORE)r.push({id:s,kind:N.DELETED,after:null});else{let c=e.getActivity(s);r.push({id:s,kind:N.CREATED,after:c?nt(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:au(a.fields,i),after:c?Mt(c):null})}else if(a.kind===N.DELETED)if(i===dt.BEFORE){let c=e.getLink(s);n.push({id:s,kind:N.CREATED,after:c?Mt(c):null})}else n.push({id:s,kind:N.DELETED,after:null});else if(i===dt.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?Mt(c):null})}}let o=(t.changeSet.viewState??[]).map(a=>i===dt.BEFORE?Zg(a):a);return{source:{kind:i===dt.BEFORE?ee.UNDO:ee.REDO},activities:r,links:n,calendars:[],trackingEvents:[],effects:[],viewState:o}}function au(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([i,r])=>[i,t===dt.BEFORE?{before:w(r.after),after:w(r.before)}:{before:w(r.before),after:w(r.after)}]))}function Zg(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 Ma(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function pu(e,t){hu(e,t,dt.BEFORE)}function yu(e,t){hu(e,t,dt.AFTER)}function hu(e,t,i){let r=t.changeSet;for(let o of r.activities)if(o.kind===N.UPDATED){if(!o.fields)continue;for(let[a,s]of Object.entries(o.fields))lt(e,o.id,a,i===dt.BEFORE?s.before:s.after)}else if(o.kind===N.DELETED)if(i===dt.BEFORE){let a=t.beforeSnap?.get(String(o.id));if(!a)throw new Error(`undo: missing beforeSnap for resurrecting activity ${o.id}`);e.addActivity(nt(a))}else e.removeActivity(String(o.id));else if(i===dt.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(nt(a))}for(let o of r.links)if(o.kind===N.UPDATED){if(!o.fields)continue;let a=e.getLink(String(o.id)),s=o.fields[wt.SOURCE],c=o.fields[wt.TARGET];a&&(s||c)&&e.setLinkEndpoints(String(o.id),String(s?i===dt.BEFORE?s.before:s.after:a.source),String(c?i===dt.BEFORE?c.before:c.after:a.target));for(let[l,d]of Object.entries(o.fields))l===wt.SOURCE||l===wt.TARGET||Rc(e,String(o.id),l,i===dt.BEFORE?d.before:d.after)}else if(o.kind===N.DELETED)if(i===dt.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(i===dt.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 r.viewState??[])o.checked&&e.setChecked(o.activityId,i===dt.BEFORE?o.checked.before:o.checked.after),o.visible&&e.setVisible(o.activityId,i===dt.BEFORE?o.visible.before:o.visible.after);let n=i===dt.BEFORE?t.progressFallbackBefore:t.progressFallbackAfter;for(let[o,a]of n??[])e.setProgressFallback(o,a)}var Qg=100,tA=600,wn=class e{constructor(t=Qg){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,i=null,r=0){let n=this.undoStack[this.undoStack.length-1];i!=null&&i===this._lastKey&&r-this._lastTime<=tA&&n!==void 0&&du(n.entry,t)?(n.entry=uu(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=i,this._lastTime=r,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,i){let r=new Map(t.map(({id:o,proplannerId:a})=>[String(o),a])),n=new Map(i.map(({id:o,proplannerId:a})=>[String(o),a]));for(let o of[...this.undoStack,...this.redoStack])o.entry=this.withPersistedIdentities(o.entry,r,n)}clear(){this.undoStack.length=0,this.redoStack.length=0,this.resetCoalesce()}touch(){return this.sequence+=1,this.sequence}removeEntriesThrough(t,i){let r=t.filter(({touchedAt:n})=>n>i);t.splice(0,t.length,...r)}withPersistedIdentities(t,i,r){let n=a=>a===void 0?void 0:new Map(Array.from(a,([s,c])=>[s,i.has(s)?{...c,proplannerId:i.get(s)}:c])),o=a=>a===void 0?void 0:new Map(Array.from(a,([s,c])=>[s,r.has(s)?{...c,proplannerId:r.get(s)}:c]));return{...t,beforeSnap:n(t.beforeSnap),afterSnap:n(t.afterSnap),beforeLinks:o(t.beforeLinks),afterLinks:o(t.afterLinks)}}};var eA=["parentId","correlativeId"];function Iu(e,t){let i=new Set,r=n=>{let o=t(n);i.add(o===null?"0":String(o))};for(let n of e.activities){let o=String(n.id);if(n.kind===N.CREATED){r(o);continue}if(n.kind===N.DELETED){let c=n.fields;c&&"parentId"in c&&i.add(mu(c.parentId?.before));continue}let a=n.fields;!a||!eA.some(c=>c in a)||(r(o),"parentId"in a&&i.add(mu(a.parentId?.before)))}return i}function mu(e){return e==null?"0":String(e)}function iA(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function rA(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function gu(e){return{id:String(e.id),worktime:rA(e.worktime)}}function xn(e,t,i,r=[]){let n=t.map(iA),o=[...i.map(gu),...r.map(gu)];return{activities:[...e],links:n,calendars:o}}var x={TRACKED:"tracked",IGNORED:"ignored"};var Au={id:x.IGNORED,proplannerId:x.IGNORED,parentId:x.TRACKED,name:x.TRACKED,description:x.TRACKED,type:x.TRACKED,startDate:x.TRACKED,endDate:x.TRACKED,durationHours:x.TRACKED,constraintType:x.TRACKED,constraintDate:x.TRACKED,autoScheduling:x.TRACKED,calendarId:x.TRACKED,assignedDefaultCalendar:x.IGNORED,dateOrigin:x.TRACKED,progress:x.TRACKED,cost:x.TRACKED,usedCost:x.TRACKED,realCost:x.TRACKED,workHours:x.TRACKED,realWorkHours:x.TRACKED,ponderator:x.TRACKED,hasCustomPonderator:x.TRACKED,correlativeId:x.TRACKED,uniqueCorrelativeId:x.TRACKED,customId:x.TRACKED,subcontractId:x.TRACKED,isLookahead:x.TRACKED,hasLookaheadTasks:x.IGNORED,newActivityIds:x.TRACKED,hasNewActivities:x.TRACKED,isNewActivity:x.IGNORED,pendingRequestIds:x.IGNORED,responsableIds:x.TRACKED,tagIds:x.TRACKED,baselinePoints:x.IGNORED,baselineSnapshot:x.IGNORED,recursiveDurationHours:x.IGNORED,isCritical:x.IGNORED,freeSlackHours:x.IGNORED,calendarDuration:x.IGNORED,expectedProgress:x.IGNORED,expectedProgressBaseline:x.IGNORED,status:x.IGNORED,criticalPath:x.IGNORED},vu=Object.keys(Au).filter(e=>Au[e]===x.TRACKED),Cu=new Set(["startDate","endDate","constraintDate","dateOrigin"]),Su=new Set(["newActivityIds","responsableIds","tagIds"]);function Tu(e){let t=vu.map(i=>[i,nA(i,e[i])]);return Object.fromEntries(t)}function nA(e,t){return Cu.has(e)?t instanceof Date?new Date(t):null:Su.has(e)?Array.isArray(t)?[...t]:[]:t}function sr(e,t){return Ua(e,t).length>0}function Ua(e,t){return vu.filter(i=>!oA(i,e[i],t[i]))}function oA(e,t,i){return Cu.has(e)?aA(t,i):Su.has(e)?sA(t,i):(t??null)===(i??null)}function aA(e,t){let i=e instanceof Date?e.getTime():null,r=t instanceof Date?t.getTime():null;return i===r}function sA(e,t){let i=new Set(Array.isArray(e)?e.map(String):[]),r=new Set(Array.isArray(t)?t.map(String):[]);if(i.size!==r.size)return!1;for(let n of i)if(!r.has(n))return!1;return!0}var Du={id:x.IGNORED,source:x.TRACKED,target:x.TRACKED,type:x.TRACKED,lag:x.TRACKED,freeSlackHours:x.IGNORED,isCritical:x.IGNORED,ganttId:x.IGNORED,sectorId:x.IGNORED,proplannerId:x.IGNORED},cA=Object.keys(Du).filter(e=>Du[e]===x.TRACKED);function Mn(e,t){return cA.some(i=>e[i]!==t[i])}function Eu(e,t){let i=new Map(e.map(r=>[String(r.id),r]));return t.filter(r=>{let n=i.get(String(r.id));return n?Mn(n,r):!1})}function Zt(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 _u(e,t){for(let i of e)Zt(i.proplannerId);for(let i of t)Zt(i.proplannerId)}var Un=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[i,r]of this.linksAtLastSave)t.linksAtLastSave.set(i,w(r));for(let[i,r]of this.activitiesAtLastSave)t.activitiesAtLastSave.set(i,w(r));return t}init(t,i){if(this.trackingEnabled){_u(t,i),this.snapshotActivities(t),this.snapshotLinks(i);for(let r of t)if(r.assignedDefaultCalendar){let n=String(r.id);this.initialCalendarRepairIds.add(n),this.dirtyActivityIds.add(n)}this.initialized=!0}}acknowledge(t,i,r=[],n=[],o,a){if(!this.trackingEnabled)return;let s=new Map(r.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=i.map(p=>{let y=c.get(String(p.id));return y===void 0?{...p}:{...p,proplannerId:y}});if(_u(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 i of t){let r=String(i.id);if(!Zt(i.proplannerId)){this.dirtyActivityIds.add(r);continue}let n=Tu(i);this.activitiesAtLastSave.set(String(i.id),{persistable:n,deletedSnapshot:{id:i.id,proplannerId:i.proplannerId,parentId:i.parentId,hadBaseline:i.baselineSnapshot!==null||i.baselinePoints.length>0}}),sr(i,n)&&this.dirtyActivityIds.add(r)}}}snapshotLinks(t){if(this.trackingEnabled){this.linksAtLastSave.clear(),this.dirtyLinkIds.clear();for(let i of t){let r=String(i.id);if(!Zt(i.proplannerId)){this.dirtyLinkIds.add(r);continue}this.linksAtLastSave.set(String(i.id),{id:i.id,proplannerId:i.proplannerId,source:i.source,target:i.target,lag:i.lag,type:i.type})}}}recordChanges(t,i,r,n){if(!(!this.trackingEnabled||!this.initialized)){for(let o of t){let a=String(o.id),s=r(a);this.activityIsDirty(a,s)?this.dirtyActivityIds.add(a):this.dirtyActivityIds.delete(a)}for(let o of i){let a=String(o.id),s=n(a);this.linkIsDirty(a,s)?this.dirtyLinkIds.add(a):this.dirtyLinkIds.delete(a)}}}activityIsDirty(t,i){let r=this.activitiesAtLastSave.get(t);return i===null?r!==void 0:this.initialCalendarRepairIds.has(t)||!Zt(i.proplannerId)||r===void 0||sr(i,r.persistable)}linkIsDirty(t,i){let r=this.linksAtLastSave.get(t);return i===null?r!==void 0:!Zt(i.proplannerId)||r===void 0||Mn(r,i)}acknowledgePersistedLookahead(t,i){if(!this.trackingEnabled||!this.initialized)return;let r=t.map(n=>{let o=typeof n=="string"?n:String(n.id),a=i(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 r){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)||!Zt(s.proplannerId)||sr(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 i=[];for(let r of this.dirtyActivityIds){let n=t(r);n!==null&&!Zt(n.proplannerId)&&i.push(n)}return i}newLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let i=[];for(let r of this.dirtyLinkIds){let n=t(r);n!==null&&!Zt(n.proplannerId)&&i.push(n)}return i}deletedActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let i=[];for(let r of this.dirtyActivityIds){let n=this.activitiesAtLastSave.get(r);n&&t(r)===null&&i.push({...n.deletedSnapshot})}return i}deletedLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let i=[];for(let r of this.dirtyLinkIds){let n=this.linksAtLastSave.get(r);n&&t(r)===null&&i.push({...n})}return i}modifiedActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let i=[];for(let r of this.dirtyActivityIds){let n=t(r);if(n===null||!Zt(n.proplannerId))continue;let o=this.activitiesAtLastSave.get(r);(o===void 0||this.initialCalendarRepairIds.has(r)||sr(n,o.persistable))&&i.push(n)}return i}modifiedActivityFields(t){let i=new Map;if(!this.trackingEnabled||!this.initialized)return i;for(let r of this.dirtyActivityIds){let n=t(r),o=this.activitiesAtLastSave.get(r);if(!n||!o)continue;let a=Ua(n,o.persistable);a.length>0&&i.set(r,a)}return i}modifiedLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let i=[];for(let r of this.dirtyLinkIds){let n=t(r);if(n===null||!Zt(n.proplannerId))continue;let o=this.linksAtLastSave.get(r);(o===void 0||Mn(o,n))&&i.push(n)}return i}clear(){this.initialized=!1,this.dirtyActivityIds.clear(),this.dirtyLinkIds.clear(),this.initialCalendarRepairIds.clear(),this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear()}};var ku=1440*60*1e3,Ru=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/,Hn=7,Ha=[!1,!0,!0,!0,!0,!0,!1],Pu=new Set(["1","true"]),Ba=pt.DURATION,Lu=v.ASAP,Ou={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 Nu(e,t){let i=[],r=e.map(o=>{let a=gA(o,t);return o.should_be_showed===!1&&i.push(a.id),a});vA(r);let n=new Set(r.map(o=>o.id));return CA(r,n,t.reporter,t.recordDiagnostic),{activities:r,activityIds:n,hiddenIds:i}}function lA(e,t,i,r){if(!e)return null;let n=Ou[e.toUpperCase()];return n===void 0?(i(Nt.UNKNOWN_CONSTRAINT,r),t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),Lu):n}function dA(e,t,i){let r=lA(e.constraint,t,i,String(e.unique_id)),o=r!==v.ASAP&&r!==v.ALAP&&e.constraint_date?le(e.constraint_date):null;return{constraintType:r,constraintDate:o}}function uA(e,t,i){if(e==null)return i;let r=String(e);return t.has(r)?r:i}function fA(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 pA(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function Wa(e){if(!Array.isArray(e))return[];let t=[];for(let i of e)pA(i)&&t.push(String(i.id));return t}function yA(e){return e==="0"?null:String(e)}function hA(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 mA(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 IA(e,t,i,r,n){return Array.isArray(e)?e.map(o=>kn(o,t,{record:i,sampleId:r},n)).filter(o=>o!==null):[]}function gA(e,t){let i=uA(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),r=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),n=Number(e.progress),{constraintType:o,constraintDate:a}=dA(e,t.reporter,t.recordDiagnostic),s=e.type===D.MILESTONE,c=le(e.start_date),l=s?c:le(e.end_date),d=s?0:Number(e.duration),u=mA(e,t.reporter);return{id:String(e.unique_id),proplannerId:hA(e.id),parentId:yA(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:Me(d,t.hoursPerDay),constraintType:o,constraintDate:a,autoScheduling:we(n),calendarId:i,assignedDefaultCalendar:i!=null&&r,dateOrigin:e.date_origin==null?null:le(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:AA(e),subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:fA(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:Wa(e.pendingRequests),responsableIds:Wa(e.responsables),tagIds:Wa(e.tags),baselinePoints:IA(e.baseline_points,t.reporter,t.recordDiagnostic,String(e.unique_id),s),baselineSnapshot:null,recursiveDurationHours:Me(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),calendarDuration:te({type:e.type,startDate:c,endDate:l}),isCritical:u,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function AA(e){return e.has_childs?null:e.custom_id}function vA(e){let t=e.find(i=>i.correlativeId===0&&i.type===D.PROJECT);t&&(t.parentId=null)}function CA(e,t,i,r){for(let n of e)n.parentId!==null&&(t.has(n.parentId)||(i.warn(`[parseFromBackend] activity "${n.id}" references unknown parent "${n.parentId}" \u2014 re-parenting to root (null)`),r(Nt.ORPHAN_ACTIVITY,n.id),n.parentId=null))}function xu(e,t,i,r=null){let a=(e!==void 0&&e.length>0?e:t??[]).map(c=>TA(c,r)),s=(i??[]).map(c=>DA(c,r));return{calendars:a,baseCalendars:s,knownCalendarIds:new Set(a.map(c=>c.id)),defaultCalendarId:SA(a)}}function SA(e){let t=e.find(r=>r.is_default);if(t)return t.id;let i=e[0];return i?i.id:null}function Mu(e,t){let i=LA(e.working_days),{days:r,hours:n}=PA(e,i),o=EA(t.exceptionsSource,t.exceptionRange),a={days:r,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 TA(e,t){let i=e.baseDefault,r=typeof i=="boolean"?i:void 0;return Mu(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:r,exceptionsSource:e.exceptiondays,exceptionRange:t})}function DA(e,t){return Mu(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function EA(e,t){if(!Array.isArray(e)||e.length===0)return null;let i={};for(let r of e){if(!r)continue;let n=_A(r.from_date,r.to_date,t);if(n.length===0)continue;let o=kA(r);if(o!==void 0)for(let a of n)i[a]=o}return Object.keys(i).length>0?i:null}function _A(e,t,i){let r=bu(e),n=bu(t);if(r===null||n===null)return[];if(i&&(n<i.start||r>i.end))return[];let o=[],a=i?Math.max(r,i.start):r,s=i?Math.min(n,i.end):n;for(;a<=s;)o.push(String(a)),a+=ku;return o}function bu(e){if(typeof e!="string")return null;let t=Ru.exec(e.trim());if(!t)return null;let i=Number(t[1]),r=Number(t[2]),n=Number(t[3]);return Number.isFinite(i)&&Number.isFinite(r)&&Number.isFinite(n)?Date.UTC(i,r-1,n):null}function kA(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let i=RA(t);if(i.length>0)return i}}var Fu=/^\d{1,2}:\d{2}$/;function RA(e){let t=[];for(let i of e){let r=Bu(i?.shift_string);if(!r)continue;if(!r.startsCsv.includes(",")&&!r.endsCsv.includes(",")){let s=r.startsCsv.trim(),c=r.endsCsv.trim();!Bn(s)&&!Bn(c)&&Fu.test(s)&&Fu.test(c)&&t.push(`${s}-${c}`);continue}let a=Hu(r.startsCsv,r.endsCsv).find(s=>s!==null);a&&t.push(a)}return t.sort(Uu),t}function wu(e){let t=e.indexOf("-"),i=t>0?e.slice(0,t):e,[r,n]=i.split(":");return(Number(r)||0)*60+(Number(n)||0)}function Uu(e,t){return wu(e)-wu(t)}function PA(e,t){let i=Array.from({length:7},()=>[]),r=(l,d)=>{let u=Hu(l,d);for(let f=0;f<7;f+=1){let p=u[f],y=i[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=Bu(l?.shift_string);d&&r(d.startsCsv,d.endsCsv)}else o&&r(e.shift_start,e.shift_end);for(let l of i)l.sort(Uu);let s=i.find((l,d)=>!!t[d]&&l.length>0)??[];return{days:t.map((l,d)=>{if(!l)return!1;let u=i[d];return u&&u.length>0?u:s}),hours:s}}function Hu(e,t){let i=Array.from({length:Hn},()=>null);if(typeof e!="string"||typeof t!="string")return i;let r=e.split(",").map(s=>s.trim()),n=t.split(",").map(s=>s.trim());if(!(r.length===n.length&&r.length>0&&r.length<=Hn))return i;let a=[...i];for(let s=0;s<r.length;s+=1){let c=r[s],l=n[s];Bn(c)||Bn(l)||(a[s]=`${c}-${l}`)}return a}function Bu(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 LA(e){if(typeof e!="string")return[...Ha];let t=e.split(",").map(i=>i.trim());return t.length!==Hn?[...Ha]:t.map(i=>Pu.has(i))}var OA=new Set(["false","null"]);function Bn(e){return!e||OA.has(e)}function NA(e){if(typeof e!="string")return null;let t=Ws(e);return t||(yr(e)?e:null)}function bA(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 Vu(e,t){let i=[];for(let r of e)try{i.push(FA(r,t.knownActivityIds,t.hoursPerDay))}catch(n){t.recordDiagnostic(Nt.INVALID_LINK,String(r.unique_id??r.id)),t.reporter.warn("[parseFromBackend] dropping invalid link",n)}return wA(i,t.recordDiagnostic)}function FA(e,t,i){let r=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 "${r}" source "${n}" does not exist`);if(!t.has(o))throw new Error(`[parseFromBackend] link "${r}" target "${o}" does not exist`);let a=NA(e.type);if(a===null)throw new Error(`[parseFromBackend] link "${r}" has invalid type "${String(e.type)}"`);let s=e.ganttId,c=e.sectorId,l=bA(e.id);return{id:r,source:n,target:o,type:a,lag:Vt(Number(e.lag??0),i),freeSlackHours:null,isCritical:!1,...typeof s=="number"?{ganttId:s}:{},...typeof c=="number"?{sectorId:c}:{},...l===void 0?{}:{proplannerId:l}}}function wA(e,t){let i=new Map;for(let r of e){let n=`${r.source}-${r.target}-${r.type}`,o=i.get(n);if(!o){i.set(n,r);continue}let a=Wu(r)>Wu(o),s=a?o:r;t(Nt.DUPLICATE_LINK,s.id),a&&i.set(n,r)}return[...i.values()]}function Wu(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function xA(e){if(typeof e!="string")return Ba;switch(e.toUpperCase()){case pt.DURATION:return pt.DURATION;case pt.COST:return pt.COST;case pt.WORK_HOURS:return pt.WORK_HOURS;default:return Ba}}function MA(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function UA(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function ju(e){let t=MA(e),i=UA(e),r=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}:{},...i!==void 0?{customIdIncrement:i}:{},...r?{updateDurationForPrimaveraEndDate:!0}:{},activityCreter:xA(e.activity_creter),statusCriteria:_o,ganttId:null}}function Wn(e,t=ci,i=ki){let r=ju(e.sector),{calendars:n,baseCalendars:o,knownCalendarIds:a,defaultCalendarId:s}=xu(e.calendars,e.sector.calendars,e.baseCalendars,HA(e.activities)),{activities:c,activityIds:l,hiddenIds:d}=Nu(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t,recordDiagnostic:i}),u=Vu(e.links,{knownActivityIds:l,hoursPerDay:r.hoursPerDay,reporter:t,recordDiagnostic:i});return{sector:r,activities:c,links:u,calendars:n,baseCalendars:o,viewStateSeed:{hiddenIds:d}}}function HA(e){let t=Number.POSITIVE_INFINITY,i=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)&&(i=Math.max(i,s))}if(!Number.isFinite(t)||!Number.isFinite(i))return null;let r=new Date(t),n=new Date(i);return r.setFullYear(r.getFullYear()-1),n.setFullYear(n.getFullYear()+1),{start:r.getTime(),end:n.getTime()}}function Va(e={}){let t=e.seed??0,i=r=>{r>t&&(t=r)};if(e.knownIds)for(let r of e.knownIds){let n=typeof r=="number"?r:Number(r);Number.isFinite(n)&&i(n)}return{fork(){return Va({seed:t})},next(){return t+=1,String(t)},bump(r){let n=typeof r=="number"?r:Number(r);Number.isFinite(n)&&i(n)},snapshot(){return t},restore(r){t=r}}}function ja(e={}){let t=e.seed??0,i=r=>{r>t&&(t=r)};if(e.knownIds)for(let r of e.knownIds){let n=typeof r=="number"?r:Number(r);Number.isFinite(n)&&i(n)}return{fork(){return ja({seed:t})},next(){return t+=1,String(t)},bump(r){let n=typeof r=="number"?r:Number(r);Number.isFinite(n)&&i(n)},snapshot(){return t},restore(r){t=r}}}function Ka(e={}){let t=e.seed??0,i=r=>{Number.isFinite(r)&&r>0&&r<=9999999&&r>t&&(t=r)};if(e.knownIds)for(let r of e.knownIds){if(r==null)continue;let n=typeof r=="number"?r:Number(r);i(n)}return{fork(){return Ka({seed:t})},next(){return t+=1,String(t)},bump(r){if(r==null)return;let n=typeof r=="number"?r:Number(r);i(n)},snapshot(){return t},restore(r){t=r}}}function Ku(e){return!!e&&typeof e=="string"&&e.trim().length>0}function Vn(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function jn(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function Yu(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function Gu(e,t){return!t&&Ku(e)}function $u(e,t){return t&&Ku(e)}function cr(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function Kn(e){if(!cr(e))return 0n;try{return BigInt(e)}catch{return 0n}}function BA(e,t){if(typeof e!="bigint")return"";let i=e.toString();if(!cr(t))return i;let r=t.length;return i.padStart(r,"0")}function Yt(e,t){let i=Kn(e),r=Kn(t),n=i+r;return BA(n,e)}function Yn(e,t){let i=Kn(e),r=Kn(t);return i<r?-1:i>r?1:0}function Gn(e,t){return Yn(e,t)<=0?e:t}function $n(e,t){return Yn(e,t)>=0?e:t}function zu(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,i)=>Gn(t,i))}function qu(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,i)=>$n(t,i))}var ue={PARENT_CONVERSION:"parentConversion",PASTE_REFERENCE:"pasteReference",NO_CONTEXT:"noContext"};function Ju(e){return{prefix:e,baseSuffix:null}}function Xu(e,t){let i=jn(e);return{prefix:Vn(e),baseSuffix:Yt(i,t)}}function Zu(e){return{prefix:e,baseSuffix:null}}function Qu(e,t){return Gu(e,t)?ue.PARENT_CONVERSION:$u(e,t)?ue.PASTE_REFERENCE:ue.NO_CONTEXT}function tf(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var zn=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,i=this._journalIds;if(!(t===null||i===null)){for(let[r,n]of t)n===null?this.prefixMap.delete(r):this.prefixMap.set(r,n);for(let r of[...i].reverse())r.hadId?this.processedIds.add(r.customId):this.processedIds.delete(r.customId);this._journalPrefixBefore=null,this._journalIds=null}}_noteCustomIdBefore(t){if(this._journalPrefixBefore===null||this._journalIds===null)return;let{prefix:i}=this.analyzeCustomId(t);if(!this._journalPrefixBefore.has(i)){let r=this.prefixMap.get(i);this._journalPrefixBefore.set(i,r?tf(r):null)}this._journalIds.push({customId:t,hadId:this.processedIds.has(t)})}_ensureFreshBounds(t){let i=this.prefixMap.get(t);if(!i?.boundsDirty)return;i.boundsDirty=!1;let r=Array.from(i.usedSuffixes);i.min=zu(r),i.max=qu(r),i.quantity=r.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[i,r]of this.prefixMap)t.prefixMap.set(i,tf(r));for(let i of this.processedIds)t.processedIds.add(i);return t}extractPrefix(t){return Vn(t)}extractSuffix(t){return jn(t)}analyzeCustomId(t){return{prefix:this.extractPrefix(t),suffix:this.extractSuffix(t)}}_updatePrefixStats(t,i){if(this._ensureFreshBounds(t),!this.prefixMap.has(t)){this.prefixMap.set(t,{min:i,max:i,next:i,quantity:1,usedSuffixes:new Set([i])}),this._recalculateNext(t);return}let r=this.prefixMap.get(t);r.usedSuffixes.has(i)||(r.usedSuffixes.add(i),r.min=Gn(i,r.min),r.max=$n(i,r.max),r.quantity+=1,this._recalculateNext(t))}_recalculateNext(t){let i=this.prefixMap.get(t);if(!i)return;let r=this.getNextAvailableSuffix(t);i.next=r??this.suffixIncrement}getPrefixStats(t){this._ensureFreshBounds(t);let i=this.prefixMap.get(t);return i?{min:i.min,max:i.max,next:i.next,quantity:i.quantity}:null}getNextSuffix(t){this._ensureFreshBounds(t);let i=this.prefixMap.get(t);return i?i.next:this.suffixIncrement}getAllPrefixes(){return Array.from(this.prefixMap.keys())}registerCustomId(t){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:i,suffix:r}=this.analyzeCustomId(t);if(!i&&!r)return{prefix:i,suffix:r};if(this._noteCustomIdBefore(t),this._ensureFreshBounds(i),this.prefixMap.has(i)){let n=this.prefixMap.get(i);n.usedSuffixes.has(r)||(n.usedSuffixes.add(r),n.min=Gn(r,n.min),n.max=$n(r,n.max),n.quantity+=1,this._recalculateNext(i))}else this.prefixMap.set(i,{min:r,max:r,next:Yt(r,this.suffixIncrement),quantity:1,usedSuffixes:new Set([r])});return this.processedIds.add(t),{prefix:i,suffix:r}}releaseCustomId(t=null){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:i,suffix:r}=this.analyzeCustomId(t);if(!this.prefixMap.has(i))return{prefix:i,suffix:r};this._noteCustomIdBefore(t);let n=this.prefixMap.get(i);return n.usedSuffixes.has(r)&&(n.usedSuffixes.delete(r),n.quantity-=1,n.usedSuffixes.size===0?this.prefixMap.delete(i):n.boundsDirty=!0),this.processedIds.delete(t),{prefix:i,suffix:r}}trackCustomIdChange(t,i){let r=this.releaseCustomId(t),n=this.registerCustomId(i);return{oldPrefix:r.prefix,oldSuffix:r.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 i=this.prefixMap.get(t);return`${t}${Yt(i.max,this.suffixIncrement)}`.length>20}_suffixForUnknownPrefix(t,i){let r=i&&cr(i)?i:this.suffixIncrement;return`${t}${r}`.length>20?null:r}_findFirstAvailableGap(t){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return null;let i=this.prefixMap.get(t),r=this.suffixIncrement;for(;Yn(r,i.max)<0;){if(`${t}${r}`.length>20)return null;if(!i.usedSuffixes.has(r))return r;r=Yt(r,this.suffixIncrement)}return null}_generateDefaultCustomId(){let t=this.getNextAvailableSuffix(this.defaultPrefix);if(t===null){if(this._shouldSearchForGaps(this.defaultPrefix)){let i=this._findFirstAvailableGap(this.defaultPrefix);if(i!==null)return`${this.defaultPrefix}${i}`}return`${this.defaultPrefix}${this.suffixIncrement}`}return`${this.defaultPrefix}${t}`}getNextAvailableSuffix(t,i=null){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return this._suffixForUnknownPrefix(t,i);let r=this.prefixMap.get(t),n=this.suffixIncrement;if(!i||!cr(i)){let s=Yt(r.max,n);return`${t}${s}`.length>20?null:s}let o=i;for(let s=0;s<100;s++){if(`${t}${o}`.length>20)return null;if(!r.usedSuffixes.has(o))return o;o=Yt(o,n)}let a=Yt(r.max,n);return`${t}${a}`.length>20?null:a}generateNextCustomId(t){let i=this.getNextAvailableSuffix(t);if(i===null)return this._generateDefaultCustomId();if(this.prefixMap.has(t)){let n=this.prefixMap.get(t),o=0;for(;n.usedSuffixes.has(i)&&o<1e4;){let a=this.getNextAvailableSuffix(t,Yt(i,this.suffixIncrement));if(a===null)return this._generateDefaultCustomId();i=a,o++}}let r=`${t}${i}`;return this._exceedsMaxLength(r)&&(r=this._generateDefaultCustomId()),r}populateFromActivities(t){if(!Array.isArray(t))return this;let i=[...new Set(t.filter(r=>r&&typeof r.customId=="string"&&r.customId).map(r=>r.customId))];for(let r of i){if(this.processedIds.has(r))continue;let{prefix:n,suffix:o}=this.analyzeCustomId(r);(n||o)&&(this._updatePrefixStats(n,o),this.processedIds.add(r))}return this}getDefaults(){return{prefix:this.defaultPrefix,increment:this.suffixIncrement}}generateCustomIdForNewChild(t){let{activity:i,useActivityCustomIdAsReference:r=!1}=t,n=Yu(i),o=Qu(n,r),{prefix:a,baseSuffix:s}=this._applyGenerationStrategy(o,n),c=null;if(o===ue.PARENT_CONVERSION&&this.prefixMap.has(a)){this._ensureFreshBounds(a);let f=this.prefixMap.get(a).max;c=Yt(f,this.suffixIncrement)}o===ue.PARENT_CONVERSION&&this.releaseCustomId(n);let l=o===ue.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,i){switch(t){case ue.PARENT_CONVERSION:return Ju(this.defaultPrefix);case ue.PASTE_REFERENCE:return Xu(i,this.suffixIncrement);default:return Zu(this.defaultPrefix)}}generateCustomIdForRestoredChild(t=null){if(t){let r=t.trim();if(r.length>0){let n=this.extractPrefix(r),o=this.extractSuffix(r),a=Yt(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 i=this.generateNextCustomId(this.defaultPrefix);return this.registerCustomId(i),i}clear(){this.prefixMap.clear(),this.processedIds.clear()}getTotalPrefixes(){return this.prefixMap.size}hasPrefix(t){return this.prefixMap.has(t)}isCustomIdInUse(t,i=null){if(!t||typeof t!="string"||!t.trim())return!1;let r=t.trim();return i&&r===i.trim()?!1:this.processedIds.has(r)}};var WA=1,VA=-1;function jA(e,t){return!e&&!t?null:e&&t?0:e?WA:VA}function ef(e){return e==null}function rf(e,t){let i=t.indexOf(String(e));return i===-1?t.length:i}function KA(e,t,i){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),i,{sensitivity:"base",numeric:!0})}function YA(e,t){let i=ye(e.field);return i===null?null:(r,n)=>{let o=i.extract(r,t),a=i.extract(n,t),s=jA(ef(o),ef(a));if(s!==null)return s;let c=i.valueKind===O.ENUM?rf(o,i.order)-rf(a,i.order):KA(o,a,t.locale);return e.direction===Fe.DESCENDING?-c:c}}function nf(e,t){let i=e.rules.map(r=>YA(r,t)).filter(r=>r!==null);return i.length===0?null:(r,n)=>{for(let o of i){let a=o(r,n);if(a!==0)return a}return 0}}function of(e){let t=[];e.forEachActivity((i,r)=>{i.type===D.PROJECT&&e.getChildren(String(r)).length===0&&t.push(String(r))});for(let i of t)e.setActivityField(i,b.TYPE,ai),GA(e,i)}function GA(e,t){let i=e.getActivity(t);if(!i||!i.startDate||i.durationHours==null)return;let r=new Date(i.startDate);r.setUTCHours(0,0,0,0);let n=e.getClosestWorkTime({date:r,dir:Y.FUTURE,task:i});if(n.getTime()===i.startDate.getTime())return;let o=e.calculateEndDate({startDate:n,durationHours:i.durationHours,task:i});e.setActivityField(t,b.START_DATE,n),e.setActivityField(t,b.END_DATE,o)}function af(e){let t=[],i=[];e.forEachActivity((n,o)=>{n.parentId===null&&t.push(String(o))});let r=n=>{let o=e.getActivity(n);if(!o)return 0;let a=[...e.getChildren(n)],s=a.length===0?xt(o.workHours,o.progress):a.reduce((c,l)=>c+r(String(l)),0);return e.setActivityField(n,b.REAL_WORK_HOURS,s),i.push(n),s};for(let n of t)r(n);return i}async function sf(e){let{state:t,sector:i,scheduler:r,skipAutoSchedule:n,now:o}=e;if(_t(t),i.updateDurationForPrimaveraEndDate&&zA(t),qA(t),af(t),n){Ki(t),o&&(je(t,o),de(t,i.statusCriteria));return}let a=await r.schedule({});Wi(t,a),JA(t),$A(t),await di(t,void 0,!1),Ki(t),o&&(je(t,o),de(t,i.statusCriteria))}function $A(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=te(t))})}function zA(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function qA(e){e.forEachActivity(t=>{let i=t.constraintType;if(!i||!t.constraintDate)return;let r=t.constraintDate;if(t.type===D.MILESTONE&&(r.getUTCHours()!==0||r.getUTCMinutes()!==0))return;let n=e.calendarReader.getCalendar(String(t.calendarId));n&&(t.constraintDate=se(t.constraintDate,n,i))})}function JA(e){e.forEachActivity(t=>{if(t.type!==D.MILESTONE)return;let i=t.constraintType;if(!i||!t.constraintDate)return;let r=e.calendarReader.getCalendar(String(t.calendarId));r&&(t.constraintDate=se(t.constraintDate,r,i))})}var Qt={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function cf(e){let t=e.clock??null,i=t?.()??null,r=i?Yr(i):null,n=e.reporter??ci,o=ld(),a=Wn({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},n,o.record),s=a.sector;s.statusCriteria=rn(e.statusCriteria),s.ganttId=e.ganttId??null;let c=a.calendars,l=a.baseCalendars??[],d=xn(a.activities,a.links,a.calendars,l),u=F=>nf(F,be(s.hoursPerDay)),f=new Pi(d,u);f.hydrateViewState({hiddenIds:a.viewStateSeed.hiddenIds});let p=new li(f,n);of(f);let y=Va({knownIds:a.activities.map(F=>F.id)}),g=ja({seed:i?.getTime()??0,knownIds:a.links.map(F=>F.id)}),A=Ka({knownIds:a.activities.map(F=>F.uniqueCorrelativeId)}),k=new zn({defaultPrefix:s.customIdPrefix,suffixIncrement:s.customIdIncrement});if(k.populateFromActivities(a.activities),e.baselinePoints&&e.baselinePoints.length>0){let F=l.find(h=>h.baseDefault)?.id??null;Rn(f,e.baselinePoints,r,n,F,o.record)}let _=sf({state:f,sector:s,scheduler:p,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:r??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 Oi(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(Oi)];if(e instanceof Map)return["map",Array.from(e,([t,i])=>[Oi(t),Oi(i)]).sort((t,i)=>JSON.stringify(t).localeCompare(JSON.stringify(i)))];if(e instanceof Set)return["set",Array.from(e,Oi).sort((t,i)=>JSON.stringify(t).localeCompare(JSON.stringify(i)))];if(typeof e=="object")return["object",Object.entries(e).sort(([t],[i])=>t.localeCompare(i)).map(([t,i])=>[t,Oi(i)])];throw new TypeError(`Unsupported canonical value: ${typeof e}`)}function Ze(e){return JSON.stringify(Oi(e))}function Ya(e,t){let i=new Map(e.map(a=>[String(a.id),a])),r=new Map(t.map(a=>[String(a.id),a])),n=[...new Set([...i.keys(),...r.keys()])].sort(),o=[];for(let a of n){let s=r.get(a),c=i.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:w(c)});continue}let l=XA(s,c);Object.keys(l).length>0&&o.push({id:a,kind:N.UPDATED,fields:l,after:w(c)})}return o}function XA(e,t){let i={},r=[...new Set([...Object.keys(e),...Object.keys(t)])].sort();for(let n of r)Ze(e[n])!==Ze(t[n])&&(i[n]={before:w(e[n]),after:w(t[n])});return i}function ZA(e,t){let i=new Set(t.selectedIds.map(String)),r=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=i.has(c),d=r.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 Ga(e,t){let i=Ze(e.order)!==Ze(t.order);return{source:{kind:ee.INIT},activities:Ya(e.activities,t.activities),links:Ya(e.links,t.links),calendars:Ya(e.calendars,t.calendars),trackingEvents:[],effects:[],viewState:ZA(e,t),...i?{order:w(e.order)}:{}}}var Ni={MOVE:"move",RESIZE_START:"resize-start",RESIZE_END:"resize-end"},QA=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),$a=(e,t)=>e===null?t:Math.min(e,t),za=(e,t)=>e===null?t:Math.max(e,t);function df(e,t,i){let r=[...new Set(t.kind===Ni.MOVE?t.activityIds.map(String):[String(t.activityId)])];if(r.length===0)throw new Error("[ScheduleCore] date gesture has no participants");let n=tv(e,t,r);return ev(e,r,n),{getDates(o,a){if(i(),!Number.isFinite(a))throw new Error("[ScheduleCore] invalid date gesture edge");let s=n.get(String(o));if(!s)return null;let c=rv(s,a),l=nv(s,a);if(c===null||l===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(o)}`);return{startTimeMs:c,endTimeMs:l}}}}function tv(e,t,i){let r=new Map,n=t.kind===Ni.MOVE?String(t.anchorActivityId):null,o=n===null?null:lf(e,n);if(n!==null&&!i.includes(n))throw new Error("[ScheduleCore] move anchor is not a participant");for(let a of i){let s=lf(e,a);if(t.kind===Ni.MOVE){let c=o.startDate.getTime();r.set(a,{constantStart:null,variableStartOffset:s.startDate.getTime()-c,constantEnd:null,variableEndOffset:s.endDate.getTime()-c})}else t.kind===Ni.RESIZE_START?r.set(a,{constantStart:null,variableStartOffset:0,constantEnd:s.endDate.getTime(),variableEndOffset:null}):r.set(a,{constantStart:s.startDate.getTime(),variableStartOffset:null,constantEnd:null,variableEndOffset:0})}return r}function ev(e,t,i){let r=Gi(e,new Set(t));for(let n of r){let o=QA();for(let a of e.getChildren(n)){let s=i.get(a);if(s){iv(o,s);continue}let c=e.getActivity(a);if(!c)throw new Error(`[ScheduleCore] missing child ${a} while previewing parent ${n}`);o.constantStart=$a(o.constantStart,c.startDate.getTime()),o.constantEnd=za(o.constantEnd,c.endDate.getTime())}i.set(n,o)}}function lf(e,t){let i=e.getActivity(t);if(!i)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 i}function iv(e,t){t.constantStart!==null&&(e.constantStart=$a(e.constantStart,t.constantStart)),t.variableStartOffset!==null&&(e.variableStartOffset=$a(e.variableStartOffset,t.variableStartOffset)),t.constantEnd!==null&&(e.constantEnd=za(e.constantEnd,t.constantEnd)),t.variableEndOffset!==null&&(e.variableEndOffset=za(e.variableEndOffset,t.variableEndOffset))}function rv(e,t){if(e.variableStartOffset===null)return e.constantStart;let i=t+e.variableStartOffset;return e.constantStart===null?i:Math.min(e.constantStart,i)}function nv(e,t){if(e.variableEndOffset===null)return e.constantEnd;let i=t+e.variableEndOffset;return e.constantEnd===null?i:Math.max(e.constantEnd,i)}var qa=Symbol("ScheduleCore.fork.source");function ov(e){return{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}function av(e){return e.kind===I.PERSISTENCE_ACKNOWLEDGE||e.kind===I.ACTIVITY_LOOKAHEAD_SYNC&&e.acknowledgePersistedLookahead===!0}function sv(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 cv(e,t){let i=[];for(let r of e.activities){let n=t.getActivity(r.id);if(n===null)return null;i.push(n)}return i}function lv(e,t,i){if(e===null||e.filter!==t)return!1;let r=e.context.hoursPerDay===i.hoursPerDay,n=e.context.locale===i.locale;return r&&n}var bi=class e{activities;links;calendars;selection;view;baselines;impactRequests;persistence;history;projection;criticalPath;diagnostics;_activityClipboard={value:null};_status=Qt.READY;coreRuntime;_isFork;_undo=new wn;_opQueue=Promise.resolve();_scheduleRevision=0;_stateRevision=0;_pendingScheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){if(Object.assign(this,es(this)),qa in t){this._isFork=!0;let n=t[qa],o=n.coreRuntime.state.fork();this.coreRuntime={state:o,scheduler:new li(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 i=cf(t);this.coreRuntime={state:i.state,scheduler:i.scheduler,sector:i.sector,activityIdGenerator:i.activityIdGen,linkIdGenerator:i.linkIdGen,uniqueCorrelativeIdGenerator:i.uidGen,customIdTracker:i.customIdTracker,clock:i.clock,calendars:new Map(i.calendars.map(n=>[n.id,n])),baseCalendars:i.baseCalendars,reporter:i.reporter,loadDiagnostics:i.loadDiagnostics},this._initPromise=i.initPromise.then(()=>{this._status!==Qt.DESTROYED&&this._saveTracker.init(this.coreRuntime.state.getAllActivities(),this.getAllLinksView())}),this._criticalPathReady=this._initPromise.then(()=>this._startCriticalPathForCurrentRevision());let r=t.criticalPathOnLoad===!0;this._ready=r?this._criticalPathReady.then(()=>{}):this._initPromise}get ready(){return this._ready}fork(){return this._enqueue(async()=>(await this._ready,this.assertReady(),new e({[qa]: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(),La(this.coreRuntime.state,t)}calculateCalendarEndDate(t){this.assertReady();let i=this.coreRuntime.state.getActivity(t.activityId);return i?this.coreRuntime.state.calculateEndDate({startDate:t.startDate,durationHours:t.durationHours,task:i}):null}calculateCalendarDuration(t){this.assertReady();let i=this.coreRuntime.state.getActivity(t.activityId);return i?this.coreRuntime.state.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:i}):null}getClosestCalendarWorkTime(t){this.assertReady();let i=this.coreRuntime.state.getActivity(t.activityId);return i?this.coreRuntime.state.getClosestWorkTime({date:t.date,dir:t.direction,task:i}):null}getProgressEditability(t){this.assertReady();let i=La(this.coreRuntime.state,t);if(!i)return null;let r=ba(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat});return $r.canEdit(i,r.hierarchy)}createDateGesturePreview(t){this.assertReady();let i=this._scheduleRevision;return df(this.coreRuntime.state,t,()=>{if(this.assertReady(),this._scheduleRevision!==i)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),qd(this.coreRuntime.state)}getIndentTargetParentIds(t){this.assertReady();let i=_n(t.map(r=>String(r)),this.coreRuntime.state);return[...new Set(i.allowedMoves.map(r=>String(r.newParentId)))]}getChildrenView(t){return this.assertReady(),Zd(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),Na(this.coreRuntime.state,t)}getLinksForActivityView(t){this.assertReady();let i=this.coreRuntime.state,r=[],n=new Set,o=a=>{if(n.has(a))return;n.add(a);let s=Na(i,a);s&&r.push(s)};for(let a of i.getOutgoingLinkIds(t))o(a);for(let a of i.getIncomingLinkIds(t))o(a);return r}getAllLinksView(){return this.assertReady(),eu(this.coreRuntime.state)}auditEffectiveGraph(){this.assertReady();let t=this.coreRuntime.state,i=t.getAllLinks(),r=ji(t,i),n=Lr(r),o=0;for(let a of n)a.length>o&&(o=a.length);return{activityCount:t.getAllIds().length,logicalLinkCount:i.length,effectiveEdgeCount:r.length,circularComponents:n,largestComponentSize:o}}getProperty(t,i){this.assertReady();let r=this.coreRuntime.state.getActivity(t);return r?w(r[i]):null}getAllIds(){return this.assertReady(),Jd(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),Xd(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),Oa(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),Qd(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(i=>!t.has(i))}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()]}hasChild(t){return this.assertReady(),tu(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let i=this.coreRuntime.calendars.get(t);return i?w(i):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,i=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,i)}getProjectWorkHours(){return this.assertReady(),iu(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=(i,r)=>String(i.id).localeCompare(String(r.id));return Ze({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(),Ga(this._snapshotProjection(),t._snapshotProjection())}_snapshotProjection(){return{activities:this.getAllActivitiesView(),links:this.getAllLinksView(),calendars:this.getAllCalendars(),selectedIds:this.getSelectedActivityIds(),hiddenIds:this.getHiddenActivityIds(),order:oi(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 i=this._opQueue.then(t,t);return this._opQueue=i.then(()=>{},()=>{}),i}_beginScheduleMutation(t){return ln(t)?this._admitScheduleMutation():!1}_admitScheduleMutation(){return this._pendingScheduleRevision++,this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),!0}_settleScheduleMutation(t,i){t&&(i||(this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision-1,this._scheduleRevision),this._pendingScheduleRevision===this._scheduleRevision&&this._criticalPathRevision!==this._scheduleRevision&&this.recomputeCriticalPath().catch(r=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path re-arm after a barren mutation failed",r)})))}async dispatch(t,i={}){let r=this._beginScheduleMutation(t);return this._enqueue(()=>this._dispatchInner(t,i,r))}async dispatchMany(t,i={}){let r=t.some(ln)?this._admitScheduleMutation():!1;return this._enqueue(()=>this._dispatchManyInner(t,i,r))}async applyActivityBatch(t,i={}){let r=this._beginScheduleMutation(t);return this._enqueue(()=>this._dispatchInner(t,i,r))}planLookaheadConversion(t){return this.assertReady(),ua(t,{adapter:this.coreRuntime.state,stateRevision:this._stateRevision})}applyLookaheadConversion(t){return this.dispatch({...t,kind:I.ACTIVITY_LOOKAHEAD_CONVERT})}async _dispatchInner(t,i={},r=!1){let n=!1;try{let o=await this._runDispatch(t,i);return n=o.changedState,o.result}finally{this._settleScheduleMutation(r,n)}}async _dispatchManyInner(t,i,r){let n=this._snapshotProjection(),o={...i,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===I.SCHEDULE_AUTO_SCHEDULE){if(A.activityId!==void 0&&!this.coreRuntime.state.activityExists(A.activityId)){a.push({ok:!1,reason:S.ACTIVITY_NOT_FOUND});continue}let _=ov(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:I.SCHEDULE_AUTO_SCHEDULE}:{kind:I.SCHEDULE_AUTO_SCHEDULE,activityId:u},k=await this._runDispatch(A,i,!0);k.result.ok&&(p=k.result.changes,s.push(k.result.changes),y=i.skipAutoSchedule!==!0),l||=k.changedState}return l&&this._recordScheduleMutation(p!==null&&i.skipAutoSchedule!==!0&&i.skipCriticalPath!==!0),g=!0,{results:a,autoScheduled:y,changeSet:this._aggregateDispatchManyChangeSets(n,s,c)}}finally{!g&&l&&this._recordScheduleMutation(!1),this._settleScheduleMutation(r,g&&l)}}_aggregateDispatchManyChangeSets(t,i,r){if(i.length===0)return null;let n=Ga(this._snapshotProjection(),t),o=i.flatMap(s=>s.effects??[]),a=i.flatMap(s=>s.warnings??[]);return{...n,source:{kind:ee.DISPATCH_MANY,actions:r},trackingEvents:i.flatMap(s=>s.trackingEvents),...o.length===0?{}:{effects:o},...a.length===0?{}:{warnings:a}}}async _runDispatch(t,i,r=!1){if(this.assertReady(),this._isFork&&av(t))return{result:{ok:!1,reason:S.SANDBOX_PERSISTENCE_FORBIDDEN},changedState:!1};let n=ba(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat}),o=fu(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 Ed(t,i,{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?Yr(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===Li.RECORD&&Ma(s.changes)){let d=cu(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(Fa(su(s.changes),s.__beforeSnap,s.__beforeLinks,d.afterSnap,d.afterLinks,c,u),lu(t),Date.now())}if(s.ok)if(o===Li.CHECKPOINT_ON_SUCCESS){if(t.kind!==I.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===I.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=Ma(s.changes);return l&&this._stateRevision++,ln(t)&&l?(r||this._recordScheduleMutation(i.skipAutoSchedule!==!0&&i.skipCriticalPath!==!0&&$e(t)),{result:uf(s),changedState:!0}):{result:uf(s),changedState:!1}}recomputeCriticalPath(){let t=this._enqueue(async()=>({job:this._startCriticalPathForCurrentRevision()})).then(({job:i})=>i);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,i){if(!i.ok||(t.kind===I.VISIBILITY_SET&&this.coreRuntime.state.setFilterProjection(null),!dl(t)))return i;let r=this._reapplyViewState(i.changes);return r===null?i:{...i,changes:r}}_reapplyViewState(t){let i=this._reapplyActiveFilter(t),r=this._emitTouchedBranchOrder(i??t);return this._reapplyActiveOrder(r.changes??i??t,r.touchedParents)??r.changes??i}_emitTouchedBranchOrder(t){let i=this.coreRuntime.state,r=Iu(t,o=>i.getParentId(o));if(i.getActiveOrder()!==null)return{changes:null,touchedParents:r};if(r.size===0)return{changes:null,touchedParents:r};let n=oo(i,r);return n.length===0?{changes:null,touchedParents:r}:{changes:{...t,order:n},touchedParents:r}}_reapplyActiveOrder(t,i){let r=this.coreRuntime.state;if(r.getActiveOrder()===null)return null;if(r.invalidateDerivedOrder(),t.links.length>0||t.calendars.length>0)return{...t,order:oi(r)};let o=new Set(i);for(let s of t.activities){if(s.kind===N.DELETED)return{...t,order:oi(r)};let c=r.getParentId(s.id);o.add(c===null?"0":String(c))}let a=oo(r,o);return a.length===0?null:{...t,order:a}}_reapplyActiveFilter(t){let i=this.coreRuntime.state,r=i.getActiveFilter();if(r===null)return null;let n=be(this.coreRuntime.sector.hoursPerDay),o=i.getFilterProjection(),a=lv(o,r,n),s=sv(t)?null:cv(t,i),c,l;if(s===null||!a){let f=gr({activities:i.getAllActivities(),parentOf:p=>i.getParentId(p),filter:r,context:n});i.setFilterProjection(f),l=f.visibleIds,c=i.getAllIds()}else c=us(o,s,f=>i.getParentId(f)),l=o.visibleIds;let u=ni(i,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===Qt.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 i={cancelled:!1},r=new Pi(xn(this.coreRuntime.state.getAllActivities().map(s=>nt(s)),this.coreRuntime.state.getAllLinks().map(s=>({...s})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),n=()=>!i.cancelled&&this._status!==Qt.DESTROYED&&this._scheduleRevision===t&&this._pendingScheduleRevision===this._scheduleRevision,o=(async()=>{let s=await Xo(r,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)qo(this.coreRuntime.state,l,d);for(let[l,d]of s.links)Jo(this.coreRuntime.state,l,d);c=await $(this.coreRuntime.state,{source:{kind:ee.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:i,promise:o};let a=()=>{this._activeCriticalPath?.promise===o&&(this._activeCriticalPath=null)};return o.then(a,a),o}undo(t={}){let i=this._admitScheduleMutation(),r=!1,n=this._enqueue(async()=>{try{return await this._runUndo(t,o=>{r=o})}finally{this._settleScheduleMutation(i,r)}});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,i){{if(this.assertReady(),t.expectedUndoDepth!==void 0&&this._undo.undoDepth()!==t.expectedUndoDepth)return null;let r=this._undo.takeUndo();if(!r)return null;pu(this.coreRuntime.state,r),this._recordScheduleMutation(!1),i(!0),wa(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(r),this._undo.resetCoalesce();let n=xa(this.coreRuntime.state,r,dt.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 i=this._admitScheduleMutation(),r=!1,n=this._enqueue(async()=>{try{return await this._runRedo(o=>{r=o})}finally{this._settleScheduleMutation(i,r)}});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 i=this._undo.takeRedo();if(!i)return null;yu(this.coreRuntime.state,i),this._recordScheduleMutation(!1),t(!0),wa(i)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(i),this._undo.resetCoalesce();let r=xa(this.coreRuntime.state,i,dt.AFTER);return this._saveTracker.recordChanges(r.activities,r.links,n=>this.coreRuntime.state.getActivity(n),n=>this.coreRuntime.state.getLink(n)),this._reapplyViewState(r)??r}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=Qt.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new Un;assertReady(){if(this._status===Qt.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===Qt.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(i){throw this._status=Qt.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",i),i}}};function uf(e){let{__beforeSnap:t,__beforeLinks:i,...r}=e;return r}async function ff(e){let t=new bi(e);return await t.ready,t}var pf=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var yf={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 hf=8;var mf={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return Tf(dv);})();
2
2
  //# sourceMappingURL=schedule-core.global.js.map