@outbuild-company/schedule-core 1.34.0 → 1.35.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var ScheduleCore=(()=>{var fc=Object.defineProperty;var iD=Object.getOwnPropertyDescriptor;var aD=Object.getOwnPropertyNames;var oD=Object.prototype.hasOwnProperty;var sD=(t,e)=>{for(var n in e)fc(t,n,{get:e[n],enumerable:!0})},lD=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of aD(e))!oD.call(t,i)&&i!==n&&fc(t,i,{get:()=>e[i],enumerable:!(r=iD(e,i))||r.enumerable});return t};var cD=t=>lD(fc({},"__esModule",{value:!0}),t);var N0={};sD(N0,{ACTIVITY_BATCH_ACTION_KIND:()=>Ye,ACTIVITY_BATCH_MODE:()=>Mt,ACTIVITY_DATE_EDGE:()=>ca,ACTIVITY_FIELD:()=>Zt,ACTIVITY_PONDERATOR_CRITERION:()=>Dt,ACTIVITY_PROGRESS_ORIGIN:()=>fs,ACTIVITY_TYPE:()=>U,BASELINE_ROLE:()=>sa,CALENDAR_UNIT:()=>mt,CHANGE_SET_SOURCE_KIND:()=>ce,COLUMN:()=>R,COMPLETED_PROGRESS:()=>Lt,CONFIRMATION_KIND:()=>re,CONSTRAINT_TYPE:()=>_,CONSTRAINT_TYPE_TO_LABEL:()=>tD,CONSTRAINT_WARNING_KIND:()=>Cr,CREATION_KIND:()=>nD,DATA_DATE_PROPERTY_CONTRACT:()=>QC,DATE_GESTURE_KIND:()=>Ae,DEFAULT_HOURS_PER_DAY:()=>eD,DISPATCH_ACTION_KIND:()=>I,DISPATCH_ACTION_KINDS:()=>Dp,DISPATCH_LINK_OPERATION_KIND:()=>Pt,DISPATCH_TRACK_EVENT:()=>ke,DataDateCapabilityError:()=>Ce,EDIT_ALERT_KEY:()=>cs,EDIT_DENIAL_REASON:()=>Me,ENTITY_CHANGE_KIND:()=>W,FILTER_FIELD:()=>lt,FILTER_LOGIC:()=>Jr,FILTER_OPERATOR:()=>nt,FILTER_REJECTION_REASON:()=>bt,FILTER_VALUE_KIND:()=>Y,FLAT_WBS_DEPTH:()=>Po,GROUP_ID_PREFIX:()=>Ac,GROUP_ID_SEPARATOR:()=>Xr,LINK_BATCH_OPERATION_KIND:()=>zr,LINK_CODE:()=>we,LINK_CODE_TO_TYPE:()=>mr,LINK_REJECTION_REASON:()=>kt,LINK_RELATIONSHIP:()=>cr,LINK_TYPE:()=>G,LINK_TYPE_CODE:()=>ts,LOOKAHEAD_CONFIRMATION_KIND:()=>ol,LookaheadActualTransitionError:()=>go,MINIMUM_GROUP_DEPTH:()=>Ro,MINIMUM_GROUP_LEVEL:()=>En,NEW_ACTIVITY_DEFAULTS:()=>nl,NOT_STARTED_PROGRESS:()=>oe,ORDER_DIRECTION:()=>le,ORDER_MODE:()=>rn,PASTE_PLACEMENT:()=>il,PERSISTENCE_REBASE_CONFLICT_KIND:()=>Gt,PERSISTENCE_REBASE_ENTITY:()=>Kt,REJECTION_REASON:()=>C,RESTORABLE_ACTIVITY_FIELDS:()=>Dd,ROOT_PARENT_ID:()=>Q,SCHEDULE_CORE_STATUS:()=>Ve,SCHEDULE_EFFECT_KIND:()=>hs,SIR_AUTO_REJECT_REASON:()=>ms,STATUS:()=>se,STATUS_CRITERIA:()=>Dn,STRUCTURE_ACTIVITY_FIELDS:()=>Td,ScheduleCore:()=>ra,UNASSIGNED_GROUP_LABEL:()=>Eo,UNASSIGNED_VALUE_ID:()=>yr,VIEW_ATTRIBUTE_KIND:()=>ur,VISUAL_ROW_KIND:()=>Zr,WORK_TIME_DIRECTION:()=>yt,activityBackendRow:()=>HC,allowedSecondaryConstraintTypes:()=>$c,appendGroupRowId:()=>bo,buildGroupRowId:()=>ko,checkNoUpdatedLinks:()=>qg,computeExpectedProgress:()=>Zc,createCalendarReader:()=>ZC,createLookaheadDerivedFields:()=>XC,createOutbuildDataDateScheduleSettings:()=>ta,createSchedule:()=>NC,dataDateInputFromDto:()=>GC,decodeWireValue:()=>Yr,encodeWireValue:()=>Kr,expectedProgressFromBaseline:()=>vi,formatUtcAsP6WallDate:()=>ov,getActiveBaseline:()=>jt,getUnsavedActivities:()=>$C,hostScheduleInput:()=>wC,isRestorableActivityField:()=>js,isRevertibleActivityField:()=>Bs,isRootParent:()=>q,isViewAttributeCriterion:()=>pr,isViewAttributeOrderRule:()=>Qr,linkBackendRow:()=>BC,loadTimeWork:()=>xC,mapDataDateScheduleOptions:()=>cv,movedToAnotherUtcDay:()=>Si,normalizeParentKey:()=>de,parseFromBackend:()=>nc,parseP6DayAsCalendarStart:()=>Jl,parseP6WallDateAsUtc:()=>zl,planLookaheadProgressActuals:()=>Ap,prepareLookaheadProgressActuals:()=>zC,rescheduledOnLoad:()=>MC,resolveExpectedFinishDateSelection:()=>JC,resolveLookaheadActualDateSelection:()=>pc,serializeDataDateActivity:()=>mp,serializeDataDateSettings:()=>uc,serializeDataDateState:()=>qC,willRunCriticalPath:()=>tC,yieldToBrowser:()=>Ot});var Io={CONSTRAINT:"constraint",ALERT:"alert",WARNING:"warning"},yt={FUTURE:"future",PAST:"past"},mt={MINUTE:"minute",HOUR:"hour",DAY:"day"},Dt={DURATION:"DURATION",COST:"COST",WORK_HOURS:"HH"},Dn={BASELINE:"Baseline",ACTUAL:"Actual"},sa={PROJECT:1,PRIMARY:2},se={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"},W={CREATED:"created",UPDATED:"updated",DELETED:"deleted"};var _={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},dD={[_.MSO]:()=>!0,[_.MFO]:()=>!0,[_.SNLT]:(t,e)=>t<e,[_.SNET]:(t,e)=>t>e,[_.FNLT]:(t,e)=>t<e,[_.FNET]:(t,e)=>t>e};function vo(t,e,n){if(!e)return{violated:!1};let r=dD[t];return r?r(e,n)?{violated:!0,constraintType:t,constraintDate:e}:{violated:!1}:{violated:!1}}var uD=new Set([_.MSO,_.SNET,_.SNLT]);function lr(t,e,n){return uD.has(t)?e:n}function Co(t,e,n){return{type:Io.CONSTRAINT,messageKey:"constraint_violation",data:{constraintType:t,constraintDate:e,...n?{projectedDate:n}:{}}}}var pD={[_.SNET]:{startOfDay:!0,direction:yt.FUTURE},[_.SNLT]:{startOfDay:!0,direction:yt.PAST},[_.FNET]:{startOfDay:!1,direction:yt.FUTURE},[_.FNLT]:{startOfDay:!1,direction:yt.PAST},[_.MSO]:{startOfDay:!0,direction:yt.FUTURE},[_.MFO]:{startOfDay:!1,direction:yt.PAST}},So=t=>new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())),vp=(t,e)=>new Date(t.getTime()+e*864e5),yD=(t,e)=>t.getUTCFullYear()===e.getUTCFullYear()&&t.getUTCMonth()===e.getUTCMonth()&&t.getUTCDate()===e.getUTCDate();function la(t,e){if(!t.constraintDate||!t.constraintType)return null;let n=pD[t.constraintType];if(!n)return t.constraintDate;let r=t.constraintDate,i=e.getClosestWorkTime({date:So(r),dir:yt.FUTURE,task:t});if(yD(i,r))return r.getTime()!==So(r).getTime()?r:n.startOfDay?i:e.getClosestWorkTime({date:vp(So(r),1),dir:yt.PAST,task:t});let a=So(e.getClosestWorkTime({date:r,dir:n.direction,task:t}));return n.startOfDay?e.getClosestWorkTime({date:a,dir:yt.FUTURE,task:t}):e.getClosestWorkTime({date:vp(a,1),dir:yt.PAST,task:t})}function Tn(t,e){let n={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},r=t.constraintType;if(!r||r===_.ASAP||r===_.ALAP)return n;let i=la(t,e);if(!i)return n;let a=s=>e.calculateEndDate({startDate:s,durationHours:t.durationHours,task:t}),o=s=>e.calculateEndDate({startDate:s,durationHours:-t.durationHours,task:t});switch(r){case _.SNET:return{earliestStart:i,latestStart:null,earliestEnd:a(i),latestEnd:null};case _.SNLT:return{earliestStart:null,latestStart:i,earliestEnd:null,latestEnd:a(i)};case _.FNET:return{earliestStart:o(i),latestStart:null,earliestEnd:i,latestEnd:null};case _.FNLT:return{earliestStart:null,latestStart:o(i),earliestEnd:null,latestEnd:i};case _.MSO:{let s=a(i);return{earliestStart:i,latestStart:i,earliestEnd:s,latestEnd:s}}case _.MFO:{let s=o(i);return{earliestStart:s,latestStart:s,earliestEnd:i,latestEnd:i}}default:return n}}function Cp(t,e){return!(e.earliestStart&&t<e.earliestStart||e.latestStart&&t>e.latestStart)}function hc(t,e){return e.latestStart&&t>e.latestStart?e.latestStart:e.earliestStart&&t<e.earliestStart?e.earliestStart:t}var G={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"},fD=Object.values(G);function Do(t){return fD.includes(t)}var $r={ACTUAL_START:"actualStart",ACTUAL_FINISH:"actualFinish",PLANNED_START:"plannedStart",PLANNED_FINISH:"plannedFinish",REMAINING_DURATION_HOURS:"remainingDurationHours",EXECUTION_STATUS:"executionStatus",EXPECTED_FINISH:"expectedFinish",SUSPEND_DATE:"suspendDate",RESUME_DATE:"resumeDate",SECONDARY_CONSTRAINT_TYPE:"secondaryConstraintType",SECONDARY_CONSTRAINT_DATE:"secondaryConstraintDate",PERCENT_COMPLETE_TYPE:"percentCompleteType",PHYSICAL_PERCENT_COMPLETE:"physicalPercentComplete"},hD={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",...$r},mD={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",BASELINE_VARIANCE:"baseline_variance",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"},R={...hD,...mD};var xt={CREATE:"create",UPDATE:"update",DELETE:"delete"},kt={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_CLIPBOARD_IMPORT:"activity-clipboard-import",ACTIVITY_COPY:"activity-copy",CALENDAR_RECONCILE:"calendar-reconcile",ACTIVITY_PASTE_COPIED:"activity-paste-copied",ACTIVITY_DUPLICATE:"activity-duplicate",CELL_COPY:"cell-copy",CELL_CLIPBOARD_CLEAR:"cell-clipboard-clear",CELL_PASTE_COPIED:"cell-paste-copied",PERSISTENCE_ACKNOWLEDGE:"persistence-acknowledge",PERSISTENCE_REBASE:"persistence-rebase",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_FIELDS_RESTORE:"activity-fields-restore",HISTORY_REVERT:"history-revert",ACTIVITY_SET_PROGRESS:"activity-set-progress",ACTIVITY_LOOKAHEAD_CONVERT:"activity-lookahead-convert",SELECTION_TOGGLE:"selection-toggle",SELECTION_REPLACE:"selection-replace",VISIBILITY_SET:"visibility-set",FILTER_SET:"filter-set",SORT_SET:"sort-set",VIEW_ATTRIBUTES_SET:"view-attributes-set",GROUP_SET:"group-set",WBS_DEPTH_SET:"wbs-depth-set",SIR_SYNC:"sir-sync",ACTIVITY_LOOKAHEAD_SYNC:"activity-lookahead-sync",SCHEDULE_AUTO_SCHEDULE:"schedule-auto-schedule"},Ye="activity-batch",Pt=xt,Dp=Object.values(I);function jt(t){let e=t?.baselinePoints;return!Array.isArray(e)||e.length===0?null:e.find(n=>n.isActiveVersion)??null}var Zt={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"},ca={START:"start",END:"end"},cr={FINISH_TO_START:"finish-to-start",START_TO_START:"start-to-start",FINISH_TO_FINISH:"finish-to-finish",START_TO_FINISH:"start-to-finish"},zr={CREATE:"create",UPDATE:"update",REMOVE:"remove"};var gD={[Zt.NAME]:R.TEXT,[Zt.DESCRIPTION]:R.DESCRIPTION,[Zt.DURATION_DAYS]:R.DURATION,[Zt.PROGRESS]:R.PROGRESS,[Zt.COST]:R.COST,[Zt.USED_COST]:R.USED_COST,[Zt.WORK_HOURS]:R.HH_WORK_TIME,[Zt.START_DATE]:R.START_DATE,[Zt.END_DATE]:R.END_DATE,[Zt.CONSTRAINT_TYPE]:R.CONSTRAINT_TYPE,[Zt.CONSTRAINT_DATE]:R.CONSTRAINT_DATE,[Zt.CALENDAR_ID]:R.CALENDAR_ID,[Zt.CUSTOM_ID]:R.CUSTOM_ID,[Zt.SUBCONTRACT_ID]:R.SUBCONTRACT_ID,[Zt.RESPONSABLE_IDS]:R.RESPONSABLES,[Zt.TAG_IDS]:R.TAGS};function mc(t,e){return{activityId:t,column:gD[e.field],newValue:e.value}}var AD={[cr.FINISH_TO_START]:G.FINISH_TO_START,[cr.START_TO_START]:G.START_TO_START,[cr.FINISH_TO_FINISH]:G.FINISH_TO_FINISH,[cr.START_TO_FINISH]:G.START_TO_FINISH};function da(t){return AD[t]}function ID(t){return t.kind===zr.CREATE?{kind:Pt.CREATE,source:t.sourceId,target:t.targetId,type:da(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}}:t.kind===zr.UPDATE?{kind:Pt.UPDATE,linkId:t.linkId,...t.sourceId===void 0?{}:{source:t.sourceId},...t.targetId===void 0?{}:{target:t.targetId},...t.relationship===void 0?{}:{type:da(t.relationship)},...t.lagDays===void 0?{}:{lag:t.lagDays}}:t.kind===zr.REMOVE?{kind:Pt.DELETE,linkId:t.linkId}:t}function SD(t){return t===ca.START?R.START_DATE:t===ca.END?R.END_DATE:t}function vD(t){return{kind:Ye,mode:t.mode,items:t.items,links:t.links.map(e=>({source:e.source,target:e.target,type:da(e.relationship),...e.lagDays===void 0?{}:{lag:e.lagDays},...e.linkId===void 0?{}:{linkId:e.linkId}})),...t.eventSource===void 0?{}:{eventSource:t.eventSource}}}function CD(t){return{get:e=>t.getActivityView(e),list:()=>t.getAllActivitiesView(),ids:()=>t.getAllIds(),forEachId:e=>t.forEachActivityId(e),property:(e,n)=>t.getProperty(e,n),children:e=>t.getChildrenView(e),childIds:e=>t.getChildrenIds(e),hasChildren:e=>t.hasChild(e),indentTargetParentIds:e=>t.getIndentTargetParentIds(e),leafParentIdsPromotedBy:e=>t.getLeafParentIdsPromotedBy(e),lookaheadConfirmationFor:(e,n)=>t.getLookaheadConfirmation(e,n),isCustomIdInUse:(e,n)=>t.isCustomIdInUse(e,n??null),clipboard:()=>t.getActivityClipboardView(),create:(e,n)=>t.dispatch({...e,kind:I.ACTIVITY_CREATE},n),applyBatch:(e,n)=>t.applyActivityBatch(vD(e),n),editInline:(e,n,r)=>t.dispatch({...mc(e,n),kind:I.INLINE_EDIT},r),setType:(e,n,r)=>t.dispatch({kind:I.ACTIVITY_TYPE_SET,activityId:e,type:n},r),applyDragBatch:(e,n)=>t.dispatch({kind:I.DATES_BATCH,edits:e.map(r=>({activityId:r.activityId,column:SD(r.edge),newValue:r.value}))},n),editFields:(e,n)=>t.dispatch({kind:I.BULK_EDIT,edits:e.map(r=>mc(r.activityId,r))},n),remove:(e,n={},r)=>{let i={...n,kind:I.ACTIVITY_DELETE,activityIds:e};return r===void 0?t.dispatch(i):t.dispatch(i,r)},move:(e,n)=>t.dispatch({...e,kind:I.ACTIVITY_MOVE},n),planLookaheadConversion:e=>t.planLookaheadConversion(e),applyLookaheadConversion:e=>t.applyLookaheadConversion(e),indent:(e,n={})=>t.dispatch({...n,kind:I.ACTIVITY_INDENT,activityIds:e}),outdent:(e,n={})=>t.dispatch({...n,kind:I.ACTIVITY_OUTDENT,activityIds:e}),setProgress:(e,n,r={})=>t.dispatch({...r,kind:I.ACTIVITY_SET_PROGRESS,activityId:e,newValue:n}),copy:(e={})=>t.dispatch({...e,kind:I.ACTIVITY_COPY}),paste:(e,n={},r)=>{let i={...n,kind:I.ACTIVITY_PASTE_COPIED,destination:{afterSiblingId:e}};return r===void 0?t.dispatch(i):t.dispatch(i,r)},duplicate:(e,n={})=>t.dispatch({...n,kind:I.ACTIVITY_DUPLICATE,activityIds:e}),clearClipboard:(e={})=>t.dispatch({...e,kind:I.ACTIVITY_CLIPBOARD_CLEAR}),importClipboard:(e,n,r={})=>t.dispatch({...r,kind:I.ACTIVITY_CLIPBOARD_IMPORT,snapshot:e,...n===void 0?{}:{references:n}}),lookaheadSync:e=>t.dispatch({...e,kind:I.ACTIVITY_LOOKAHEAD_SYNC}),restoreFields:e=>t.dispatch({...e,kind:I.ACTIVITY_FIELDS_RESTORE}),revert:e=>t.dispatch({...e,kind:I.HISTORY_REVERT}),autoSchedule:(e,n)=>t.dispatch({kind:I.SCHEDULE_AUTO_SCHEDULE,...e===void 0?{}:{activityId:e}},n),createDateGesturePreview:e=>t.createDateGesturePreview(e)}}function DD(t){return{copy:(e,n,r,i={})=>t.dispatch({...i,kind:I.CELL_COPY,activityId:e,column:n,...r===void 0?{}:{copiedText:r}}),paste:(e,n,r,i={})=>t.dispatch({...i,kind:I.CELL_PASTE_COPIED,activityIds:e,column:n,...r===void 0?{}:{clipboardText:r}}),clearClipboard:(e={})=>t.dispatch({...e,kind:I.CELL_CLIPBOARD_CLEAR})}}function TD(t){return{get:e=>t.getLinkView(e),list:()=>t.getAllLinksView(),forActivity:e=>t.getLinksForActivityView(e),create:(e,n)=>t.dispatch({kind:I.LINK_CREATE,source:e.sourceId,target:e.targetId,type:da(e.relationship),...e.lagDays===void 0?{}:{lag:e.lagDays},...e.linkId===void 0?{}:{linkId:e.linkId}},n),update:(e,n,r)=>t.dispatch({kind:I.LINK_UPDATE,linkId:e,...n.sourceId===void 0?{}:{source:n.sourceId},...n.targetId===void 0?{}:{target:n.targetId},...n.relationship===void 0?{}:{type:da(n.relationship)},...n.lagDays===void 0?{}:{lag:n.lagDays}},r),remove:(e,n)=>t.dispatch({kind:I.LINK_DELETE,linkId:e},n),batch:(e,n)=>t.dispatch({kind:I.LINKS_BATCH,operations:e.map(ID)},n)}}function Tp(t){let e=(n,r)=>t.dispatch({kind:I.BASELINE_APPLY,points:n},r);return{activities:CD(t),cells:DD(t),links:TD(t),calendars:{get:n=>t.getCalendar(n),list:()=>t.getAllCalendars(),listBase:()=>t.getBaseCalendars(),projectWorkHours:()=>t.getProjectWorkHours(),reconcile:n=>t.dispatch({kind:I.CALENDAR_RECONCILE},n)},selection:{ids:()=>t.getSelectedActivityIds(),toggle:({checked:n,...r})=>t.dispatch({...r,kind:I.SELECTION_TOGGLE,isChecked:n}),replace:(n,r={})=>t.dispatch({...r,kind:I.SELECTION_REPLACE,activityIds:n})},view:{hiddenActivityIds:()=>t.getHiddenActivityIds(),visibleActivityIds:()=>t.getVisibleActivityIds(),visualOrderIds:()=>t.getVisualOrderIds(),visualRows:()=>t.getVisualRows(),filter:()=>t.getActiveFilter(),setFilter:n=>t.dispatch({...n,kind:I.FILTER_SET}),order:()=>t.getActiveOrder(),setOrder:(n,r={})=>t.dispatch({...r,kind:I.SORT_SET,rules:n}),group:()=>t.getActiveGroup(),setViewAttributes:(n,r={})=>t.dispatch({...r,kind:I.VIEW_ATTRIBUTES_SET,catalogs:n}),setGroup:(n,r={})=>t.dispatch({...r,kind:I.GROUP_SET,group:n}),wbsDepth:()=>t.getWbsDepth(),setWbsDepth:(n,r={})=>t.dispatch({...r,kind:I.WBS_DEPTH_SET,wbsDepth:n}),setVisibility:(n,r={})=>t.dispatch({...r,kind:I.VISIBILITY_SET,visibleIds:n}),setStatusCriteria:(n,r)=>t.dispatch({kind:I.STATUS_CRITERIA_SET,criteria:n},r)},baselines:{refresh:e,setVisibility:e,setPonderatorCriterion:(n,r)=>t.dispatch({kind:I.PONDERATOR_CRITERION_SET,criterion:n},r),activeFor:n=>jt(n)},impactRequests:{sync:n=>t.dispatch({...n,kind:I.SIR_SYNC})},persistence:{hasChanges:()=>t.hasUnsavedChanges(),modifiedActivities:()=>t.getModifiedActivities(),modifiedActivityFields:()=>t.getModifiedActivityFields(),modifiedActivityChanges:()=>t.getModifiedActivityChanges(),newActivities:()=>t.getNewActivities(),deletedActivities:()=>t.getDeletedActivitiesSinceLastSave(),modifiedLinks:()=>t.getModifiedLinks(),newLinks:()=>t.getNewLinks(),deletedLinks:()=>t.getDeletedLinksSinceLastSave(),captureHistoryBoundary:()=>t.capturePersistenceHistoryBoundary(),readSnapshot:()=>t.readPersistenceCheckpoint(),acknowledge:n=>t.dispatch({kind:I.PERSISTENCE_ACKNOWLEDGE,checkpoint:n}),rebase:n=>t.dispatch({kind:I.PERSISTENCE_REBASE,remote:n})},history:{undo:n=>t.undo(n),redo:n=>t.redo(n),canUndo:()=>t.canUndo(),canRedo:()=>t.canRedo(),clear:()=>t.clearHistory(),depth:()=>t.undoDepth()},projection:{changeSetFrom:n=>t.createProjectionChangeSetFrom(n)},criticalPath:{get ready(){return t.criticalPathReady},recompute:()=>t.recomputeCriticalPath(),isSettled:()=>t.isCriticalPathSettled(),whenSettled:()=>t.whenCriticalPathSettled()},diagnostics:{auditEffectiveGraph:()=>t.auditEffectiveGraph(),revision:()=>t.getScheduleRevision(),stateRevision:()=>t.getStateRevision(),canonicalDigest:()=>t.getCanonicalDigest(),canonicalFingerprint:()=>t.getCanonicalFingerprint()}}}var De=class{items=[];head=0;enqueue(e){this.items.push(e)}dequeue(){if(this.head>=this.items.length)return;let e=this.items[this.head];return this.head+=1,e}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 To=t=>String(t);function _p(t){let{clickedId:e,isChecked:n,currentSelection:r,hierarchy:i,isFrozen:a,exists:o,autoCheckParents:s}=t,l=To(e),c=new Set([...r].map(String)),d=new Set(c),u=_D(l,i).filter(o),p=u.filter(f=>!a(f)),y=n&&p.length<u.length;n&&!y?d.add(l):d.delete(l);for(let f of p)n?d.add(f):d.delete(f);return y||ED({id:l,isChecked:n,autoCheckParents:s,hierarchy:i,isFrozen:a,exists:o,next:d}),{nextSelection:d,changed:RD(c,d),parentBlocked:y}}function _D(t,e){let n=[],r=new De;r.enqueue(t);let i=new Set([t]);for(;!r.isEmpty();){let a=r.dequeue();for(let o of e.getChildrenIds(a)){let s=To(o);i.has(s)||(i.add(s),n.push(s),r.enqueue(s))}}return n}function ED(t){let{id:e,isChecked:n,autoCheckParents:r,hierarchy:i,isFrozen:a,exists:o,next:s}=t,l=i.getParentId(e);for(;l!==null&&typeof l<"u";){let c=To(l);if(a(c))return;let d=i.getChildrenIds(c).map(To).filter(o),u=d.some(a),p=d.filter(m=>!a(m)),f=p.length>0&&p.every(m=>s.has(m))&&!u;if(n){if(!r||!f||s.has(c))return;s.add(c)}else{if(f||!s.has(c))return;s.delete(c)}l=i.getParentId(c)}}function RD(t,e){let n=[],r=[];for(let i of e)t.has(i)||n.push(i);for(let i of t)e.has(i)||r.push(i);return{checked:n,unchecked:r}}var C={CANNOT_EDIT:"cannot_edit",PARSE_ERROR:"parse_error",INVALID:"invalid",CUSTOM_ID_DUPLICATE:"custom_id_duplicate",INVALID_LINK_TYPE:"invalid_link_type",INVALID_LINK_LAG:"invalid_link_lag",INVALID_VALUE:"invalid_value",CONFIRMATION_REQUIRED:"confirmation_required",DATA_DATE_ACTUAL_START_LOCKED:"data_date_actual_start_locked",DATA_DATE_ACTIVITY_COMPLETED:"data_date_activity_completed",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",CLIPBOARD_SNAPSHOT_INVALID:"clipboard_snapshot_invalid",CELL_PASTE_COLUMN_MISMATCH:"cell_paste_column_mismatch",ACTIVITY_PASTE_INVARIANT_FAILED:"activity_paste_invariant_failed",SOLE_SCHEDULE_ROOT:"sole_schedule_root",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",MANUAL_SCHEDULING_ACTIVE:"manual_scheduling_active",SANDBOX_PERSISTENCE_FORBIDDEN:"sandbox_persistence_forbidden",PERSISTENCE_TRACKING_DISABLED:"persistence_tracking_disabled",STALE_STATE_REVISION:"stale-state-revision",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var Ep=(t,e,n)=>{let r=[],i=(a,o)=>{let s=e.isChecked(a);e.setChecked(a,o)&&r.push({activityId:a,checked:{before:s,after:o}})};for(let a of n.checked)i(a,!0);for(let a of n.unchecked)i(a,!1);return{source:t,activities:[],links:[],calendars:[],trackingEvents:[],viewState:r}};function Rp(t,e){let{adapter:n}=e,r=t.activityId;if(!n.getActivity(r))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let i=new Set((t.frozenIds??[]).map(String)),a=s=>i.has(s),o=_p({clickedId:r,isChecked:t.isChecked,currentSelection:new Set(n.checkedIds().map(String)),hierarchy:{getChildrenIds:s=>n.getChildren(s),getParentId:s=>{let l=n.getParentId(s);return!l||l==="0"?null:String(l)}},isFrozen:a,exists:s=>n.activityExists(s),autoCheckParents:t.autoCheckParents??!1});return{ok:!0,changes:Ep(t,n,o.changed)}}function _o(t,e){let{adapter:n}=e,r=new Set(t.activityIds.map(String).filter(o=>n.activityExists(o))),i=new Set(n.checkedIds().map(String)),a={checked:[...r].filter(o=>!i.has(o)),unchecked:[...i].filter(o=>!r.has(o))};return{ok:!0,changes:Ep(t,n,a)}}function dr(t,e,n=t.getAllIds()){let r=[];for(let i of n){let a=String(i),o=e.has(a),s=t.isVisible(a);s!==o&&(t.setVisible(a,o),r.push({activityId:a,visible:{before:s,after:o}}))}return r}function Pp(t,e){let{adapter:n}=e,r=new Set(t.visibleIds.map(String)),i=dr(n,r);return{ok:!0,changes:{source:t,activities:[],links:[],calendars:[],trackingEvents:[],viewState:i}}}var U={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},PD=Object.values(U);function ua(t){return PD.includes(t)}var kp={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var ur="viewAttribute";var Y={STRING:"string",NUMBER:"number",DATE:"date",ID_ARRAY:"id-array",ENUM:"enum",BOOLEAN:"boolean",REFERENCE:"reference"},lt={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_VARIANCE_DAYS:"baselineVarianceDays",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",FLOAT_PATH:"floatPath",FLOAT_PATH_ORDER:"floatPathOrder"},nt={INCLUDES:"includes",NOT_INCLUDES:"notIncludes",IS:"is",IS_NOT:"isNot",EQUALS:"equals",NOT_EQUALS:"notEquals",GREATER_THAN:"greaterThan",LESS_THAN:"lessThan",GREATER_OR_EQUAL:"greaterOrEqual",LESS_OR_EQUAL:"lessOrEqual",AFTER:"after",BEFORE:"before",BETWEEN:"between",SOME_OF:"someOf",NOT_SOME_OF:"notSomeOf"};function pr(t){return"kind"in t&&t.kind===ur}var Jr={AND:"and",OR:"or"};var kD=2,bD=[se.WAITING,se.DONE,se.DOING,se.OVERDUE,se.ADVANCEMENT],LD=[_.MFO,_.MSO,_.SNLT,_.SNET,_.ALAP,_.ASAP,_.FNET,_.FNLT],OD=1e3*60*60*24;function gc(t,e){return t===null||e<=0?null:t/e}function ND(t,e){let n=Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()),r=Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate());return Math.floor((r-n)/OD)+1}var FD={[lt.NAME]:{valueKind:Y.STRING,extract:t=>t.name},[lt.DESCRIPTION]:{valueKind:Y.STRING,extract:t=>t.description},[lt.CUSTOM_ID]:{valueKind:Y.STRING,extract:t=>t.customId},[lt.CORRELATIVE_ID]:{valueKind:Y.NUMBER,extract:t=>t.correlativeId},[lt.UNIQUE_CORRELATIVE_ID]:{valueKind:Y.NUMBER,extract:t=>{let e=Number(t.uniqueCorrelativeId);return Number.isFinite(e)?e:null}},[lt.PROGRESS]:{valueKind:Y.NUMBER,extract:t=>t.progress},[lt.DURATION_DAYS]:{valueKind:Y.NUMBER,extract:(t,e)=>gc(t.durationHours,e.hoursPerDay)},[lt.CALENDAR_DURATION]:{valueKind:Y.NUMBER,extract:t=>t.type===U.MILESTONE?0:ND(t.startDate,t.endDate)},[lt.COST]:{valueKind:Y.NUMBER,extract:t=>t.cost},[lt.USED_COST]:{valueKind:Y.NUMBER,extract:t=>t.usedCost},[lt.REAL_COST]:{valueKind:Y.NUMBER,extract:t=>t.realCost},[lt.WORK_HOURS]:{valueKind:Y.NUMBER,extract:t=>t.workHours},[lt.REAL_WORK_HOURS]:{valueKind:Y.NUMBER,extract:t=>t.realWorkHours},[lt.PONDERATOR]:{valueKind:Y.NUMBER,extract:t=>t.ponderator},[lt.FREE_SLACK_DAYS]:{valueKind:Y.NUMBER,extract:(t,e)=>gc(t.freeSlackHours,e.hoursPerDay)},[lt.TOTAL_SLACK_DAYS]:{valueKind:Y.NUMBER,extract:(t,e)=>gc(t.criticalPath?.totalSlackHours??null,e.hoursPerDay)},[lt.EXPECTED_PROGRESS_BASELINE]:{valueKind:Y.NUMBER,equalityPrecision:kD,extract:t=>t.expectedProgressBaseline},[lt.EXPECTED_PROGRESS]:{valueKind:Y.NUMBER,extract:t=>t.expectedProgress},[lt.BASELINE_DURATION_DAYS]:{valueKind:Y.NUMBER,extract:t=>t.baselineSnapshot?.durationDays??null},[lt.BASELINE_VARIANCE_DAYS]:{valueKind:Y.NUMBER,extract:t=>t.baselineVarianceDays},[lt.BASELINE_COST]:{valueKind:Y.NUMBER,extract:t=>t.baselineSnapshot?.cost??null},[lt.BASELINE_WORK_HOURS]:{valueKind:Y.NUMBER,extract:t=>t.baselineSnapshot?.workHours??null},[lt.START_DATE]:{valueKind:Y.DATE,extract:t=>t.startDate},[lt.END_DATE]:{valueKind:Y.DATE,extract:t=>t.endDate},[lt.CONSTRAINT_DATE]:{valueKind:Y.DATE,extract:t=>t.constraintDate},[lt.BASELINE_START_DATE]:{valueKind:Y.DATE,extract:t=>t.baselineSnapshot?.startDate??null},[lt.BASELINE_END_DATE]:{valueKind:Y.DATE,extract:t=>t.baselineSnapshot?.endDate??null},[lt.EARLY_START]:{valueKind:Y.DATE,extract:t=>t.criticalPath?.earlyStart??null},[lt.EARLY_FINISH]:{valueKind:Y.DATE,extract:t=>t.criticalPath?.earlyFinish??null},[lt.LATE_START]:{valueKind:Y.DATE,extract:t=>t.criticalPath?.lateStart??null},[lt.LATE_FINISH]:{valueKind:Y.DATE,extract:t=>t.criticalPath?.lateFinish??null},[lt.RESPONSABLE_IDS]:{valueKind:Y.ID_ARRAY,extract:t=>t.responsableIds},[lt.TAG_IDS]:{valueKind:Y.ID_ARRAY,extract:t=>t.tagIds},[lt.STATUS]:{valueKind:Y.ENUM,order:bD,extract:t=>t.status},[lt.CONSTRAINT_TYPE]:{valueKind:Y.ENUM,order:LD,extract:t=>t.constraintType},[lt.CALENDAR_ID]:{valueKind:Y.REFERENCE,extract:t=>t.calendarId===null?null:String(t.calendarId)},[lt.SUBCONTRACT_ID]:{valueKind:Y.REFERENCE,extract:t=>t.subcontractId===null?null:String(t.subcontractId)},[lt.IS_CRITICAL]:{valueKind:Y.BOOLEAN,extract:t=>t.isCritical},[lt.FLOAT_PATH]:{valueKind:Y.NUMBER,extract:t=>t.p6?.floatPath??null},[lt.FLOAT_PATH_ORDER]:{valueKind:Y.NUMBER,extract:t=>t.p6?.floatPathOrder??null}};function _n(t){return FD[t]??null}var Zr={GROUP:"group",ACTIVITY:"activity"},yr="unassigned",Ac="g",Xr=":",Eo="Unassigned",Ro=1,En=1,Po=0;function ko(t,e){return`${Ac}${Xr}${t}${Xr}${e}`}function bo(t,e,n){return`${t}${Xr}${e}${Xr}${n}`}var Lp=null;function bp(t){return t===Lp?"":t}function Op(t){let e=new Map,n=new Map;for(let l of t.values){e.set(l.id,l);let c=bp(l.parentId),d=n.get(c)??[];d.push(l),n.set(c,d)}for(let l of n.values())l.sort((c,d)=>c.sequence!==d.sequence?c.sequence-d.sequence:c.id.localeCompare(d.id));let r=new Map,i=new Map,a=(l,c,d)=>{let u=n.get(bp(l))??[];for(let p of u){let y=[...c,p.id],f=[...d,p.sequence];r.set(p.id,y),i.set(p.id,f),a(p.id,y,f)}};a(Lp,[],[]);let o=new Map;for(let l of e.keys()){let c=new Set([l]);for(let[d,u]of r)u.includes(l)&&c.add(d);o.set(l,c)}let s=new Map;for(let l of t.assignments)e.has(l.valueId)&&s.set(String(l.activityId),l.valueId);return{key:t.key,valueById:e,pathByValueId:r,sequencePathByValueId:i,descendantIdsByValueId:o,assignmentByActivityId:s}}var Lo=new Map;function Np(t,e){let n=new Set;for(let r of e){let i=t.descendantIdsByValueId.get(r);if(i===void 0){n.add(r);continue}for(let a of i)n.add(a)}return n}function Fp(t,e,n,r){let i=Math.max(n,En),a=t.pathByValueId.get(e);return a===void 0||a.length===0?i>En?[]:[e]:a.slice(i-1,Math.max(r,i))}function wp(t,e,n){let r=n.get(e.key),i=r?.assignmentByActivityId.get(String(t.id))??null,a=r?Np(r,e.value):new Set(e.value),o=i!==null&&a.has(i);return e.operator===nt.SOME_OF?o:e.operator===nt.NOT_SOME_OF?!o:!1}function Ic(t){return t instanceof Date?t:typeof t=="string"||typeof t=="number"?new Date(t):new Date(Number.NaN)}function nn(t){return Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())}function wD(t,e,n){let r=t===null;return n===nt.INCLUDES?!r&&String(t).toLowerCase().includes(e.toLowerCase()):n===nt.NOT_INCLUDES?r||!String(t).toLowerCase().includes(e.toLowerCase()):n===nt.IS?!r&&String(t)===e:n===nt.IS_NOT?r||String(t)!==e:!1}function xD(t,e,n,r){if(t===null||typeof t!="number")return n===nt.NOT_EQUALS;let i=r===void 0?t:Number(t.toFixed(r));return n===nt.EQUALS?i===e:n===nt.NOT_EQUALS?i!==e:n===nt.GREATER_THAN?t>e:n===nt.LESS_THAN?t<e:n===nt.GREATER_OR_EQUAL?t>=e:n===nt.LESS_OR_EQUAL?t<=e:!1}function MD(t,e,n){return typeof t=="number"&&t>=e&&t<=n}function UD(t,e,n){if(!(t instanceof Date))return!1;let r=nn(t),i=nn(e);return n===nt.AFTER?r>i:n===nt.BEFORE?r<i:!1}function HD(t,e,n){if(!(t instanceof Date))return!1;let r=nn(t);return r>=nn(e)&&r<=nn(n)}function BD(t,e,n){let i=(Array.isArray(t)?t:[]).some(a=>e.has(String(a)));return n===nt.SOME_OF?i:n===nt.NOT_SOME_OF?!i:!1}function jD(t,e,n){let r=t!==null&&e.has(String(t));return n===nt.SOME_OF?r:n===nt.NOT_SOME_OF?!r:!1}function xp(t){let e=Array.isArray(t)?t:[t];return new Set(e.map(n=>String(n)))}function No(t){return t.viewAttributeCatalogs??Lo}function Oo(t,e,n,r){if(pr(e))return wp(t,e,r);let i=_n(e.field);if(i===null)return!1;let a=i.extract(t,n),{operator:o}=e;return o===nt.BETWEEN?i.valueKind===Y.NUMBER?MD(a,Number(e.value),Number(e.valueTo)):i.valueKind===Y.DATE?HD(a,Ic(e.value),Ic(e.valueTo)):!1:i.valueKind===Y.STRING?wD(a,String(e.value),o):i.valueKind===Y.NUMBER?xD(a,Number(e.value),o,i.equalityPrecision):i.valueKind===Y.DATE?UD(a,Ic(e.value),o):i.valueKind===Y.ID_ARRAY?BD(a,xp(e.value),o):jD(a,xp(e.value),o)}function Mp(t,e,n,r){return e.criteria.length===0?!0:e.logic===Jr.OR?e.criteria.some(i=>Oo(t,i,n,r)):e.criteria.every(i=>Oo(t,i,n,r))}function VD(t,e,n,r){return e.groups&&e.groups.length>0?e.logic===Jr.OR?e.groups.some(i=>Mp(t,i,n,r)):e.groups.every(i=>Mp(t,i,n,r)):e.criteria.length===0?!0:e.logic===Jr.OR?e.criteria.some(i=>Oo(t,i,n,r)):e.criteria.every(i=>Oo(t,i,n,r))}function WD(t,e){let n=nn(t.startDate),r=nn(t.endDate),i=nn(e.start),a=nn(e.end),o=n>=i&&r<=a,s=n>=i&&n<=a,l=i>=n&&i<=r;return o||s||l}function Sc(t,e,n,r){let i=VD(t,e,n,r),a=e.dateRange,o=a===void 0||WD(t,a);return i&&o}function KD(t,e,n){let r=e(t);for(;r!==null&&!n.has(String(r));)n.add(String(r)),r=e(r)}function Up(t){let{activities:e,parentOf:n,filter:r,context:i}=t,a=No(t),o=new Set,s=[];for(let l of e)Sc(l,r,i,a)&&(o.add(String(l.id)),s.push(l.id));for(let l of s)KD(l,n,o);return o}function YD(t){let{activities:e,parentOf:n,filter:r,context:i}=t,a=No(t),o=new Set,s=new Map,l=new Map,c=new Map;for(let d of e){let u=String(d.id),p=n(u);l.set(u,p),c.set(u,c.get(u)??0),p!==null&&c.set(p,(c.get(p)??0)+1);let y=Sc(d,r,i,a);s.set(u,y?1:0),y&&o.add(u)}return{matchedIds:o,visibleReferenceCounts:s,parentIds:l,remainingChildren:c}}function GD(t){let{visibleReferenceCounts:e,parentIds:n,remainingChildren:r}=t,i=[];for(let a of n.keys())r.get(a)===0&&i.push(a);for(;i.length>0;){let a=i.pop();if(a===void 0)break;let o=n.get(a);if(o==null)continue;let s=e.get(a)??0;e.set(o,(e.get(o)??0)+s);let l=(r.get(o)??1)-1;r.set(o,l),l===0&&i.push(o)}}function qD(t){let e=new Set;for(let[n,r]of t)r>0&&e.add(n);return e}function Fo(t){let e=YD(t);GD(e);let n=qD(e.visibleReferenceCounts);return{filter:t.filter,context:t.context,matchedIds:e.matchedIds,visibleIds:n,visibleReferenceCounts:e.visibleReferenceCounts,viewAttributeCatalogs:No(t)}}function Hp(t,e,n){let r=new Set;for(let i of e){let a=String(i.id);r.add(a);let o=t.matchedIds.has(a),s=Sc(i,t.filter,t.context,No(t));if(o===s)continue;s?t.matchedIds.add(a):t.matchedIds.delete(a);let l=s?1:-1,c=a;for(;c!==null;){let d=t.visibleReferenceCounts.get(c)??0,u=d+l;t.visibleReferenceCounts.set(c,u);let p=d>0,y=u>0;p!==y&&(r.add(c),y?t.visibleIds.add(c):t.visibleIds.delete(c)),c=n(c)}}return r}function fr(t){return{hoursPerDay:t,locale:"en"}}var bt={UNKNOWN_FIELD:"unknown_field",UNKNOWN_OPERATOR:"unknown_operator",INVALID_VALUE:"invalid_value"},$D={[Y.STRING]:new Set([nt.INCLUDES,nt.NOT_INCLUDES,nt.IS,nt.IS_NOT]),[Y.NUMBER]:new Set([nt.EQUALS,nt.NOT_EQUALS,nt.GREATER_THAN,nt.LESS_THAN,nt.GREATER_OR_EQUAL,nt.LESS_OR_EQUAL,nt.BETWEEN]),[Y.DATE]:new Set([nt.AFTER,nt.BEFORE,nt.BETWEEN]),[Y.ID_ARRAY]:new Set([nt.SOME_OF,nt.NOT_SOME_OF]),[Y.ENUM]:new Set([nt.SOME_OF,nt.NOT_SOME_OF]),[Y.BOOLEAN]:new Set([nt.SOME_OF,nt.NOT_SOME_OF]),[Y.REFERENCE]:new Set([nt.SOME_OF,nt.NOT_SOME_OF])};function Bp(t){if(t===void 0)return{ok:!0,dateRange:void 0};if(typeof t!="object"||t===null)return{ok:!1,reason:bt.INVALID_VALUE};let{start:e,end:n}=t;if(!(e instanceof Date)||!(n instanceof Date))return{ok:!1,reason:bt.INVALID_VALUE};let r=e.getTime(),i=n.getTime();return!Number.isFinite(r)||!Number.isFinite(i)||r>i?{ok:!1,reason:bt.INVALID_VALUE}:{ok:!0,dateRange:{start:new Date(r),end:new Date(i)}}}function Dc(t){if(pr(t))return JD(t);let e=_n(t.field);if(e===null)return{ok:!1,reason:bt.UNKNOWN_FIELD};if(!$D[e.valueKind].has(t.operator))return{ok:!1,reason:bt.UNKNOWN_OPERATOR};if(t.operator===nt.BETWEEN)return zD(t,e.valueKind);if(e.valueKind===Y.NUMBER){let r=vc(t.value);return r===null?{ok:!1,reason:bt.INVALID_VALUE}:{ok:!0,criterion:{...t,value:r}}}if(e.valueKind===Y.DATE){let r=Cc(t.value);return r===null?{ok:!1,reason:bt.INVALID_VALUE}:{ok:!0,criterion:{...t,value:r}}}let n=XD(t,e.valueKind);return n!==null?{ok:!1,reason:n}:e.valueKind===Y.BOOLEAN?{ok:!0,criterion:{...t,value:[...new Set(t.value)]}}:e.valueKind===Y.ID_ARRAY||e.valueKind===Y.ENUM||e.valueKind===Y.REFERENCE?{ok:!0,criterion:{...t,value:[...new Set(t.value.map(String))]}}:{ok:!0,criterion:t}}function zD(t,e){if(e===Y.NUMBER){let n=vc(t.value),r=vc(t.valueTo);return n===null||r===null||n>r?{ok:!1,reason:bt.INVALID_VALUE}:{ok:!0,criterion:{...t,value:n,valueTo:r}}}if(e===Y.DATE){let n=Cc(t.value),r=Cc(t.valueTo);return n===null||r===null||n.getTime()>r.getTime()?{ok:!1,reason:bt.INVALID_VALUE}:{ok:!0,criterion:{...t,value:n,valueTo:r}}}return{ok:!1,reason:bt.UNKNOWN_OPERATOR}}function JD(t){return pr(t)?typeof t.key!="string"||t.key.length===0?{ok:!1,reason:bt.UNKNOWN_FIELD}:t.operator!==nt.SOME_OF&&t.operator!==nt.NOT_SOME_OF?{ok:!1,reason:bt.UNKNOWN_OPERATOR}:!Array.isArray(t.value)||t.value.some(e=>typeof e!="string")?{ok:!1,reason:bt.INVALID_VALUE}:{ok:!0,criterion:t}:{ok:!1,reason:bt.UNKNOWN_FIELD}}function XD(t,e){let{value:n}=t;return e===Y.BOOLEAN?Array.isArray(n)&&n.every(r=>typeof r=="boolean")?null:bt.INVALID_VALUE:e===Y.ID_ARRAY||e===Y.ENUM||e===Y.REFERENCE?Array.isArray(n)&&n.every(r=>typeof r=="string"||typeof r=="number")?null:bt.INVALID_VALUE:Array.isArray(n)?bt.INVALID_VALUE:null}function vc(t){if(typeof t=="string"&&t.trim()===""||typeof t!="string"&&typeof t!="number")return null;let e=typeof t=="number"?t:Number(t);return Number.isFinite(e)?e:null}function Cc(t){let e;if(t instanceof Date)e=new Date(t.getTime());else if(typeof t=="string")e=new Date(t);else if(typeof t=="number")e=new Date(t);else return null;return Number.isFinite(e.getTime())?e:null}function v(t){return structuredClone(t)}function jp(t){return!(t.groups!==void 0&&t.groups.some(n=>n.criteria.length>0))&&t.criteria.length===0&&t.dateRange===void 0}function Vp(t,e,n){let r=t.getAllActivities();if(jp(e))return{visibleIds:Up({activities:r,parentOf:a=>t.getParentId(a),filter:e,context:fr(n),viewAttributeCatalogs:t.getViewAttributeCatalogMap()}),projection:null};let i=Fo({activities:r,parentOf:a=>t.getParentId(a),filter:e,context:fr(n),viewAttributeCatalogs:t.getViewAttributeCatalogMap()});return{visibleIds:i.visibleIds,projection:i}}function ZD(t){if(!t||t.length===0)return{ok:!0,groups:[]};let e=[];for(let n of t){let r=[];for(let i of n.criteria){let a=Dc(i);if(!a.ok)return{ok:!1,reason:a.reason};r.push(a.criterion)}e.push({criteria:r,logic:n.logic})}return{ok:!0,groups:e}}function Wp(t,e){let{adapter:n,hoursPerDay:r}=e,i=[];for(let p of t.criteria){let y=Dc(p);if(!y.ok)return{ok:!1,reason:y.reason};i.push(y.criterion)}let a=ZD(t.groups);if(!a.ok)return{ok:!1,reason:a.reason};let o=Bp(t.dateRange);if(!o.ok)return{ok:!1,reason:o.reason};let s=v({criteria:i,logic:t.logic,...a.groups.length>0?{groups:a.groups}:{},...o.dateRange!==void 0?{dateRange:o.dateRange}:{}});n.setActiveFilter(jp(s)?null:s);let{visibleIds:l,projection:c}=Vp(n,s,r);n.setFilterProjection(c);let d=dr(n,l);return{ok:!0,changes:{source:t,activities:[],links:[],calendars:[],trackingEvents:[],viewState:d}}}function Kp(t,e){let n=t.getActiveFilter();if(n===null)return[];let{visibleIds:r,projection:i}=Vp(t,n,e);return t.setFilterProjection(i),dr(t,r)}var le={ASCENDING:"asc",DESCENDING:"desc"};function Qr(t){return"kind"in t&&t.kind===ur&&"key"in t&&"direction"in t&&!("operator"in t)}var rn={STANDARD:"standard",KEEP_WBS_IN_PLACE:"keepWbsInPlace"};var Q="0";function q(t){return t==null||t===0||t==="0"}function de(t){return q(t)?"0":String(t)}var Tc=Number.MAX_SAFE_INTEGER;function Te(t,e){let n=hr(t,e);return wo(n,e.getOrderComparator?.()??null,e.getOrderMode?.()??rn.STANDARD,i=>e.hasChildren(i)).map(i=>String(i.id))}function wo(t,e,n,r){return e===null?(t.sort(Rn),t):n===rn.KEEP_WBS_IN_PLACE?QD(t,e,r):(t.sort((i,a)=>e(i,a)||Rn(i,a)),t)}function QD(t,e,n){let r=[],i=[];for(let a of t)n(a.id)?i.push(a):r.push(a);return r.sort((a,o)=>e(a,o)||Rn(a,o)),i.sort(Rn),t.length=0,t.push(...r,...i),t}function Gp(t){let e=[],n=i=>{e.push(i);let a=Te(String(i.id),t);for(let o of a){let s=t.getActivity(o);s&&n(s)}},r=Te("0",t);for(let i of r){let a=t.getActivity(i);a&&n(a)}return e}function qp(t,e,n){let r=n.getActivity(t);if(!r)return null;let i=$p(r),a=Te(i,n),o=a.findIndex(s=>String(s)===String(t));if(o<=0)return null;for(let s=o-1;s>=0;s--){let l=a[s];if(l!==void 0&&!tT(e,l))return l}return null}function _c(t,e){let n=e.getActivity(t);if(!n)return-1;let r=$p(n);return Te(r,e).findIndex(a=>String(a)===String(t))}function hr(t,e){let n=String(t)==="0"?e.getRootIds?.()??e.getChildren("0"):e.getChildren(t),r=[];for(let i of n){let a=e.getActivity(i);a&&r.push(a)}return r}function Rn(t,e){let n=Yp(t),r=Yp(e);return n!==r?n-r:String(t.id).localeCompare(String(e.id))}function Yp(t){let e=t.correlativeId,n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?n:Tc}function $p(t){let e=t.parentId;return e===null?"0":e}function tT(t,e){return t.has(e)?!0:t.has(String(e))}function Pn(t){let e=[],n=r=>{let i=Te(r,t);i.length>1&&e.push({parentId:r,childIds:i});for(let a of i)n(a)};return n("0"),e}function Ec(t,e){let n=[];for(let r of e){let i=Te(r,t);i.length>1&&n.push({parentId:r,childIds:i})}return n}function eT(t){return Qr(t)?typeof t.key!="string"||t.key.length===0?bt.UNKNOWN_FIELD:t.direction!==le.ASCENDING&&t.direction!==le.DESCENDING?bt.UNKNOWN_OPERATOR:null:_n(t.field)===null?bt.UNKNOWN_FIELD:t.direction!==le.ASCENDING&&t.direction!==le.DESCENDING?bt.UNKNOWN_OPERATOR:null}function zp(t,e){let{adapter:n}=e;for(let o of t.rules){let s=eT(o);if(s!==null)return{ok:!1,reason:s}}let r=t.mode??rn.STANDARD,i=t.rules.length===0?null:v({rules:t.rules,mode:r});return n.setActiveOrder(i),{ok:!0,changes:{source:t,activities:[],links:[],calendars:[],trackingEvents:[],order:Pn(n)}}}function Rc(t){return Number.isInteger(t)&&Number.isFinite(t)}function Jp(t){return t===le.ASCENDING||t===le.DESCENDING}function Xp(t){let e=t.startLevel??En;return!Rc(e)||e<En||!Rc(t.depth)||t.depth<Ro||t.depth<e?null:{startLevel:e,depth:t.depth}}var ti=Symbol("invalid-group-criterion");function nT(t){let e=t.secondary;if(e==null)return null;if(typeof e!="object"||typeof e.attributeKey!="string"||e.attributeKey.length===0||e.attributeKey===t.attributeKey)return ti;let n=Xp(e);return n===null||!Jp(e.direction)?ti:{attributeKey:e.attributeKey,startLevel:n.startLevel,depth:n.depth,direction:e.direction}}function rT(t){if(typeof t.attributeKey!="string"||t.attributeKey.length===0)return null;let e=Xp(t);if(e===null||!Jp(t.direction)||typeof t.includeWbs!="boolean"||!Array.isArray(t.collapsedIds)||t.collapsedIds.some(r=>typeof r!="string"))return null;let n=nT(t);return n===ti?null:{attributeKey:t.attributeKey,startLevel:e.startLevel,depth:e.depth,direction:t.direction,includeWbs:t.includeWbs,collapsedIds:new Set(t.collapsedIds),secondary:n}}function xo(t){return{source:t,activities:[],links:[],calendars:[],trackingEvents:[]}}function Zp(t,e){let{adapter:n,hoursPerDay:r}=e;if(!Array.isArray(t.catalogs))return{ok:!1,reason:bt.INVALID_VALUE};n.setViewAttributeCatalogs(t.catalogs);let i=Kp(n,r),a=n.getActiveOrder();return{ok:!0,changes:{...xo(t),viewState:i,...a===null?{}:{order:Pn(n)}}}}function Qp(t,e){let{adapter:n}=e;if(t.group===null)return n.setGroup(null),{ok:!0,changes:xo(t)};let r=rT(t.group);return r===null?{ok:!1,reason:bt.INVALID_VALUE}:(n.setGroup(r),{ok:!0,changes:xo(t)})}function ty(t,e){let{adapter:n}=e,{wbsDepth:r}=t;return r!==null&&(!Rc(r)||r<Po)?{ok:!1,reason:bt.INVALID_VALUE}:(n.setWbsDepth(r),{ok:!0,changes:xo(t)})}function ey(t,e){throw new Error(e)}var Pc={OWN_BASELINE:"own-baseline",RECURSIVE_LEAF_SUM:"recursive-leaf-sum",ZERO:"zero"},kc={[U.PROJECT]:{alwaysSummary:!0,holdsConstraint:!1,carriesCustomId:!1,forcedDuration:null,ponderatorWeight:Pc.RECURSIVE_LEAF_SUM,promotesToProjectOnFirstChild:!1},[U.TASK]:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:null,ponderatorWeight:Pc.OWN_BASELINE,promotesToProjectOnFirstChild:!0},[U.MILESTONE]:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:0,ponderatorWeight:Pc.ZERO,promotesToProjectOnFirstChild:!0}};function Fe(t,e){return e||ua(t)&&kc[t].alwaysSummary}function an(t){return t===U.MILESTONE}function kn(t){return ua(t)&&kc[t].promotesToProjectOnFirstChild}var bc=U.PROJECT,ei=U.TASK;function pa(t,e){return e===0?U.MILESTONE:t===0&&e>0?U.TASK:null}var O={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",BASELINE_VARIANCE_DAYS:"baselineVarianceDays",PROJECT_BASELINE_VARIANCE_DAYS:"projectBaselineVarianceDays",PRIMARY_BASELINE_VARIANCE_DAYS:"primaryBaselineVarianceDays",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath",P6:"p6"},Vt={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",LAG_ACTIVITY_ID:"_lagActivityId",GANTT_ID:"ganttId",SECTOR_ID:"sectorId",PROPLANNER_ID:"proplannerId"};function ny(t,e){return()=>e()===t}var Mo=typeof window>"u",iT=!Mo&&typeof MessageChannel<"u";function Ot(){return Mo?new Promise(t=>setImmediate(t)):iT?new Promise(t=>{let e=new MessageChannel;e.port1.onmessage=()=>{e.port1.close(),e.port2.close(),t()},e.port2.postMessage(null)}):Promise.resolve()}function ya(t){return performance.now()-t>=kp.YIELD_SLICE_MS}async function Uo(t,e){return ya(t)?(await Ot(),e()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()}):{aborted:!1,newSliceStart:t}}async function ni(t){return Mo||await Ot(),t()?{aborted:!1}:{aborted:!0}}function h(t,e){let n=t[e];if(n===void 0)throw new RangeError(`Index ${e} is out of range`);return n}function bn(t,e){return Lc(t,e).result}function Lc(t,e){let n=aT(t,e),{ordered:r,sourceCount:i}=oT(n),a=r.length<t.length,o=a?lT(t,r):[],s=[...r].reverse();return{result:{ordered:r,reversed:s,hasCycles:a,cycleNodes:o},sourceCount:i,unknownEndpointIds:n.unknownEndpointIds}}function aT(t,e){let n=new Map,r=[];for(let y of t)n.has(y)||(n.set(y,r.length),r.push(y));let i=r.length,a=new Int32Array(e.length),o=new Int32Array(e.length),s=new Int32Array(i+1),l=new Int32Array(i),c=0,d=new Set;for(let y of e){let f=n.get(y.source),m=n.get(y.target);f===void 0&&d.add(String(y.source)),m===void 0&&d.add(String(y.target)),!(f===void 0||m===void 0)&&(a[c]=f,o[c]=m,c+=1,s[f+1]=h(s,f+1)+1,l[m]=h(l,m)+1)}for(let y=0;y<i;y+=1)s[y+1]=h(s,y+1)+h(s,y);let u=s.slice(0,i),p=new Int32Array(c);for(let y=0;y<c;y+=1){let f=h(a,y),m=h(u,f);p[m]=h(o,y),u[f]=m+1}return{unknownEndpointIds:d,nodeIds:r,inDegree:l,successorStart:s,successorList:p}}function oT(t){let{nodeIds:e,inDegree:n,successorStart:r,successorList:i}=t,a=new Int32Array(e.length),o=0;for(let c=0;c<e.length;c+=1)n[c]===0&&(a[o]=c,o+=1);let s=o,l=[];for(let c=0;c<o;c+=1){let d=h(a,c);l.push(sT(e,d));let u=h(r,d+1);for(let p=h(r,d);p<u;p+=1){let y=h(i,p),f=h(n,y)-1;n[y]=f,f===0&&(a[o]=y,o+=1)}}return{ordered:l,sourceCount:s}}function sT(t,e){let n=t[e];if(n===void 0)throw new RangeError(`Node ${e} is out of range`);return n}function lT(t,e){let n=new Set(e);return t.filter(r=>!n.has(r))}function cT(t,e,n){if(!(n===t.links&&e.length>=t.activityIds.length))return null;for(let o=0;o<t.activityIds.length;o+=1)if(e[o]!==t.activityIds[o])return null;let i=e.slice(t.activityIds.length);return i.every(o=>!t.sorted.unknownEndpointIds.has(String(o)))?i:null}function dT(t,e){let{ordered:n}=t.result,r=[...n.slice(0,t.sourceCount),...e,...n.slice(t.sourceCount)];return{...t,result:{...t.result,ordered:r,reversed:[...r].reverse()},sourceCount:t.sourceCount+e.length}}var Ho=class{cached=null;isStale=!0;invalidate(){this.isStale=!0}get(e,n){let r=this.cached;if(r!==null&&!this.isStale)return r.sorted.result;let i=r===null?null:cT(r,e,n),a=r!==null&&i!==null?dT(r.sorted,i):Lc(e,n);return this.cached={activityIds:[...e],links:n,sorted:a},this.isStale=!1,a.result}};function ry(t,e){let n=[];for(let r of t)e.has(r)&&n.push(r);return n}function Bo(t,e,n){let r=t.get(e);r?r.push(n):t.set(e,[n])}function jo(t,e,n){let r=t.get(e),i=r?r.indexOf(n):-1;r&&i>=0&&r.splice(i,1)}function iy(t){let e=[];for(let n of[t._summarySourceId,t._summaryTargetId,t._lagActivityId])n!==void 0&&e.push(String(n));return e}function Vo(t,e){Bo(t.outgoing,String(e.source),e),t.alapIds.has(String(e.source))&&Bo(t.incomingFromAlap,String(e.target),e);for(let n of iy(e))Bo(t.bySummary,n,e)}function Oc(t,e){jo(t.outgoing,String(e.source),e),jo(t.incomingFromAlap,String(e.target),e);for(let n of iy(e))jo(t.bySummary,n,e)}function ay(t,e,n){let r=n.getActivity(e)?.constraintType===_.ALAP;if(r!==t.alapIds.has(e)){r?t.alapIds.add(e):t.alapIds.delete(e);for(let i of t.outgoing.get(e)??[])r?Bo(t.incomingFromAlap,String(i.target),i):jo(t.incomingFromAlap,String(i.target),i)}}function oy(t,e){let n={outgoing:new Map,incomingFromAlap:new Map,bySummary:new Map,alapIds:new Set};for(let r of e.getAllActivities())r.constraintType===_.ALAP&&n.alapIds.add(String(r.id));for(let r of t)Vo(n,r);return n}function uT(t,e){let n=[],r=new Set,i=t;for(;i!==null&&!r.has(i);){r.add(i),n.push(i);let a=e.getActivity(i)?.parentId;i=a==null?null:String(a)}return n}function pT(t,e,n){return n.getChildren(t).map(String).filter(r=>e.alapIds.has(r))}function yT(t,e,n,r,i){for(let o of e.outgoing.get(t)??[])i(String(o.target));for(let o of e.incomingFromAlap.get(t)??[])i(String(o.source));let a=t;for(;a!==null&&!r.has(a);){r.add(a);for(let s of e.bySummary.get(a)??[])i(String(s.target));for(let s of pT(a,e,n))i(s);let o=n.getActivity(a)?.parentId;a=o==null?null:String(o)}}function sy(t,e,n,r){let i=new Set,a=new Set,o=[],s=c=>{i.has(c)||!r.activityExists(c)||(i.add(c),o.push(c))};for(let c of t)for(let d of uT(String(c),r))s(d);for(;o.length>0;){let c=o.pop();yT(c,n,r,a,s)}let l=e.filter(c=>i.has(String(c.source))||i.has(String(c.target)));return{idSet:i,links:l}}var oe=0,Lt=100,Nc=100+Number.EPSILON*100*2;function ri(t){return t>=100&&t<=Nc}function ue(t){return t===0}function Wo(t,e){let n=e.getActivity(t);return n?Fe(n.type,e.getChildren(t).length>0):!1}function Ko(t,e,n){let r=String(e),i=n.getActivity(t);for(;i?.parentId&&String(i.parentId)!=="0";){if(String(i.parentId)===r)return!0;i=n.getActivity(i.parentId)}return!1}function Yo(t,e,n){let r=Wo(t,n);return Wo(e,n)&&Ko(t,e,n)||r&&Ko(e,t,n)}function dy(t,e){let n=[],r=[t];for(;r.length>0;){let i=r.pop(),a=e.getChildren(i);if(a.length===0){String(i)!==String(t)&&n.push(i);continue}for(let o of a)r.push(o)}return n}function Fc(t){let e=new Map;for(let n of t)wc(e,n);return e}function wc(t,e){ly(t,String(e.source),e),ly(t,String(e.target),e)}function ly(t,e,n){let r=t.get(e);if(r){r.push(n);return}t.set(e,[n])}function fT(t,e,n,r){if(t.length<=1)return t;let i=new Set(t.map(String)),a=[];for(let o of t)hT(o,i,e,n,r)||a.push(o);return a.length>0?a:t}function hT(t,e,n,r,i){let a=String(t),o=n.getActivity(t);if(!o||o.autoScheduling===!1)return!1;let s=r.get(a)??[];for(let l of s)if(mT(l,a,o,e,n,i))return!0;return!1}function mT(t,e,n,r,i,a){if(gT(t)||!(a?String(t.source)===e:String(t.target)===e))return!1;let s=AT(t,e);if(!r.has(String(s)))return!1;let l=i.getActivity(s);return!!(l?.autoScheduling!==!1&&l&&IT(t,n,l))}function gT(t){return t.source===t.target}function AT(t,e){return String(t.source)===e?t.target:t.source}function IT(t,e,n){let r=t.lag??0,i=Math.abs(r);return String(t.target)===String(n.id)&&i<=n.durationHours||String(t.target)===String(e.id)&&i<=e.durationHours}function uy(t,e){let n=[],r=Fc(t);for(let i of t)Go(n,i,e,r,0);return n}function Go(t,e,n,r,i){let a=Wo(e.source,n),o=Wo(e.target,n);if(ST(e,a,o,n))return i;if(!a&&!o)return t.push(e),i;let s=cy(e.source,a,n,r,!0),l=cy(e.target,o,n,r,!1);return ET(t,s,l,e,n,i,r)}function ST(t,e,n,r){return n&&Ko(t.source,t.target,r)||e&&Ko(t.target,t.source,r)}function cy(t,e,n,r,i){return e?fT(dy(t,n),n,r,i):[t]}function py(t,e,n){let r=dy(t,e);if(r.length===0)return null;let i=null,a=null;for(let o of r){let s=n(o);if(!s)continue;(i===null||s.startDate<i)&&(i=s.startDate),(a===null||s.endDate>a)&&(a=s.endDate)}return i===null||a===null?null:{startDate:i,endDate:a}}function ii(t,e,n=r=>e.getActivity(r)){return py(t,e,n)}function vT(t,e,n){return t?e?n.calculateDuration({startDate:e.startDate,endDate:e.endDate,task:t}):t.durationHours:0}function CT(t,e,n,r){if(!e)return 0;let i=r.getActivity(t);return!n||!i?-e.durationHours:-r.calculateDuration({startDate:n.startDate,endDate:i.endDate,task:e})}function DT(t,e){let n=String(t);return(e.get(n)??[]).some(i=>String(i.target)===n)}function TT(t,e,n,r,i){if(!i&&DT(t,r))return 0;let a=n.getActivity(t);return!e||!a?0:n.calculateDuration({startDate:e,endDate:a.startDate,task:a})}function _T(t,e){let n=e.getActivity(t.source),r=e.getActivity(t.target),i=ii(t.source,e),a=ii(t.target,e),o=py(t.target,e,c=>{let d=e.getActivity(c);if(!d)return null;let u=d.constraintDate!==null&&(d.constraintType===_.MSO||d.constraintType===_.MFO);return d.autoScheduling&&d.progress!==100&&!u?{startDate:d.startDate,endDate:d.endDate}:null}),s=t.type===G.START_TO_START||t.type===G.START_TO_FINISH,l=t.type===G.FINISH_TO_FINISH||t.type===G.START_TO_FINISH;return{source:n,sourceBounds:i,targetStart:o?.startDate??r?.startDate,targetBounds:o,hasFrozenTargetStart:!!(a&&o&&a.startDate<o.startDate),targetEndpointIsFinish:l,userLag:t.lag??0,sourceEndpointIsStart:s,summarySourceId:s&&i?t.source:void 0,finishAnchoredSummaryTargetId:l&&o?t.target:void 0}}function ET(t,e,n,r,i,a,o){let s=_T(r,i),{source:l,sourceBounds:c,targetStart:d,userLag:u}=s,{sourceEndpointIsStart:p,targetBounds:y,targetEndpointIsFinish:f,hasFrozenTargetStart:m,summarySourceId:A,finishAnchoredSummaryTargetId:g}=s,P=a;for(let L of e){let F=p?CT(L,l,c,i):0;for(let T of n){if(String(L)===String(T))continue;let x=f?-vT(i.getActivity(T),y,i):0,S=TT(T,d,i,o,f);t.push(RT(r,L,T,P,F,x,u+S,A,g??((S!==0||m)&&x===0?r.target:void 0),y?r.target:void 0)),P+=1}}return P}function RT(t,e,n,r,i,a,o,s,l,c){return{id:`virtual_${t.id}_${r}`,source:e,target:n,type:t.type,lag:t.lag,freeSlackHours:null,isCritical:!1,...c===void 0?{}:{_lagActivityId:c},_sourceLag:i,_targetLag:a,_trueLag:o,...s===void 0?{}:{_summarySourceId:s},...l===void 0?{}:{_summaryTargetId:l}}}var PT=new Set(["startDate","endDate","durationHours","constraintType","constraintDate","autoScheduling","calendarId","progress"]),kT={patchesHierarchy:!0,ignoresLinks:!1,patchesLinkAppends:!0,patchesLinkRemovals:!0};function bT(t,e){if(t.length<e.length)return!1;for(let n=0;n<e.length;n+=1)if(t[n]!==e[n])return!1;return!0}function LT(t,e,n){if(!(t.length===e.length+n.length&&bT(t,e)))return null;let i=t.slice(e.length);return i.every((o,s)=>String(o.id)===n[s])?i:null}function qo(t,e,n){let r=t.get(e);r?r.includes(n)||r.push(n):t.set(e,[n])}function fy(t,e,n,r){r.length===1&&r[0]===e||(qo(t,String(e.source),n),qo(t,String(e.target),n))}function Mc(t,e,n){let r=[];return Go(r,t,e,n,0),r}function OT(t,e,n,r){for(let s of n)wc(t.linksByActivity,s);let i=t.expanded.slice(),a=new Int32Array(e.length),o=new Int32Array(e.length);return a.set(t.offsets),o.set(t.counts),n.forEach((s,l)=>{let c=t.rawLinks.length+l,d=Mc(s,r,t.linksByActivity);a[c]=i.length,o[c]=d.length,fy(t.groupsByEndpoint,s,c,d),t.groupOfLink?.set(s,c);for(let u of d)i.push(u),t.coneIndex!==null&&Vo(t.coneIndex,u)}),{...t,rawLinks:e,offsets:a,counts:o,expanded:i}}function NT(t,e){for(let n of[String(e.source),String(e.target)]){let r=t.get(n),i=r?r.indexOf(e):-1;r&&i>=0&&r.splice(i,1)}}function FT(t,e){for(let[n,r]of t){let i=[];for(let a of r){let o=e[a]??-1;o>=0&&i.push(o)}i.length===0?t.delete(n):t.set(n,i)}}function wT(t,e){if(e.length===0)return{expansion:t,removed:[]};let n=new Set(e),r=t.rawLinks.length;if(n.size>r)return null;let i=new Int32Array(r),a=[],o=new Int32Array(r-n.size),s=new Int32Array(r-n.size),l=[],c=[];return t.rawLinks.forEach((d,u)=>{let p=t.offsets[u]??0,y=t.counts[u]??0;if(n.has(String(d.id))){i[u]=-1,c.push(d),xT(t,d,p,y);return}i[u]=a.length,o[a.length]=l.length,s[a.length]=y,a.push(d);for(let f=p;f<p+y;f+=1)l.push(t.expanded[f])}),c.length!==n.size?null:(FT(t.groupsByEndpoint,i),{expansion:{...t,rawLinks:a,offsets:o,counts:s,expanded:l,groupOfLink:null},removed:c})}function xT(t,e,n,r){NT(t.linksByActivity,e);let i=t.coneIndex;if(i!==null)for(let a=n;a<n+r;a+=1)Oc(i,t.expanded[a])}function MT(t,e){let n=Fc(t),r=[],i=new Int32Array(t.length),a=new Int32Array(t.length),o=new Map;return t.forEach((s,l)=>{let c=r.length;i[l]=c,Go(r,s,e,n,0),a[l]=r.length-c,!(r.length-c===1&&r[c]===s)&&(qo(o,String(s.source),l),qo(o,String(s.target),l))}),{rawLinks:t,linksByActivity:n,offsets:i,counts:a,groupsByEndpoint:o,expanded:r,groupOfLink:null,coneIndex:null}}function UT(t,e,n){let r=new Set,i=new Set;for(let a of e){let o=a;for(;o!==null&&!i.has(o);){i.add(o);for(let l of t.groupsByEndpoint.get(o)??[])r.add(l);let s=n.getActivity(o)?.parentId;o=s==null?null:String(s)}}return[...r]}function HT(t){return t.groupOfLink??=new Map(t.rawLinks.map((e,n)=>[e,n])),t.groupOfLink}function BT(t,e){let n=new Set,r=[];for(let a of t){r.push(a);let o=a;for(;o!==null&&!n.has(o);){n.add(o);let s=e.getActivity(o)?.parentId;o=s==null?null:String(s)}}let i=new Set;for(let a=r.pop();a!==void 0;){if(!i.has(a)){i.add(a);for(let o of e.getChildren(a))n.add(String(o)),r.push(String(o))}a=r.pop()}return n}function xc(t,e,n){let r=HT(t),i=new Set;for(let a of BT(e,n))for(let o of t.linksByActivity.get(a)??[]){let s=r.get(o);s!==void 0&&i.add(s)}return[...i]}function jT(t,e){if(t===e)return!0;let n=Object.entries(t);return n.length===Object.keys(e).length&&n.every(([r,i])=>Object.is(i,Reflect.get(e,r)))}function VT(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(!jT(t[n],e[n]))return!1;return!0}function hy(t,e){let n=t.counts.slice();for(let[a,o]of e)n[a]=o.length;let r=new Int32Array(n.length),i=[];return n.forEach((a,o)=>{r[o]=i.length;let s=e.get(o);if(s!==void 0){for(let c of s)i.push(c);return}let l=t.offsets[o]??0;for(let c=0;c<a;c+=1)i.push(t.expanded[l+c])}),{...t,offsets:r,counts:n,expanded:i}}function yy(t,e,n){let r=new Map;for(let i of e){let a=t.rawLinks[i],o=t.offsets[i]??0,s=t.expanded.slice(o,o+(t.counts[i]??0)),l=Mc(a,n,t.linksByActivity);if(VT(s,l))continue;r.set(i,l),fy(t.groupsByEndpoint,a,i,l);let c=t.coneIndex;if(c!==null){for(let d of s)Oc(c,d);for(let d of l)Vo(c,d)}}return r.size===0?t:hy(t,r)}var ai=class{expansion=null;writeLog=null;get(e,n){this.writeLog??=n.openSchedulingWriteLog(PT,kT);let r=this.writeLog.take(),i=this.expansion;if(i===null||r.structural)return this.rebuild(e,n);let a=wT(i,r.removedLinkIds);if(a===null)return this.rebuild(e,n);let o=a.expansion,s=LT(e,o.rawLinks,r.appendedLinkIds);if(s===null)return this.rebuild(e,n);let l=s.length===0?o:OT(o,e,s,n),c=l.coneIndex;if(c!==null)for(let u of[...r.touchedIds,...r.reshapedIds])ay(c,u,n);r.reshapedIds.size>0&&(l=yy(l,xc(l,r.reshapedIds,n),n));let d=[...r.touchedIds,...[...a.removed,...s].flatMap(u=>[String(u.source),String(u.target)])];return d.length>0&&(l=yy(l,UT(l,d,n),n)),this.expansion=l,l.expanded}projectHierarchy(e,n,r,i){this.get(e,n);let a=this.expansion;if(a===null)return[];let o=new Set([...xc(a,i,n),...xc(a,i,r)]),s=new Map;for(let l of o)s.set(l,Mc(a.rawLinks[l],r,a.linksByActivity));return hy(a,s).expanded}coneIndex(e){let n=this.expansion;if(n===null)throw new Error("ExpandedLinksCache: cone index read before get");return n.coneIndex??=oy(n.expanded,e),n.coneIndex}rebuild(e,n){return this.expansion=MT(e,n),this.expansion.expanded}};function WT(t){let e=new Map,n=r=>(e.has(r)||e.set(r,new Set),e.get(r));for(let r of t)n(r.source).add(r.id),n(r.target).add(r.id);return{neighbors:e}}function KT(t,e,n){let r=new Set,i=new Map,a=new De;for(a.enqueue(t);!a.isEmpty();){let o=a.dequeue(),s=String(o);if(r.has(s))continue;r.add(s);let l=n.neighbors.get(o);if(l)for(let c of l){let d=e.get(c);if(!d)continue;let u=`${d.source}-${d.target}-${d.type}`;i.has(u)||i.set(u,d);let p=String(d.source)===s?d.target:d.source;r.has(String(p))||a.enqueue(p)}}return Array.from(i.values())}function my(t,e){let n=new Map;for(let o of e)n.set(o.id,o);let r=WT(e),i=KT(t,n,r),a=new Set([String(t)]);for(let o of i)a.add(String(o.source)),a.add(String(o.target));return{activityIds:a,links:i}}var gy=36e5,Ay=1;function Ln(t,e){return new Date(t.getTime()+e*gy)}function fa(t){return new Date(t.getTime()+Ay)}function oi(t){return new Date(t.getTime()-Ay)}function Iy(t,e){return(e.getTime()-t.getTime())/gy}function Sy(t,e,n){let r=n.type===G.FINISH_TO_START,i=n.type===G.FINISH_TO_FINISH;if(n._targetLag!==void 0)return{sourceLag:n._sourceLag??0,targetLag:n._targetLag,trueLag:n._trueLag??n.lag??0,isFS:r,isFF:i,isZeroDurationCase:!1};let a=n.lag??0;switch(n.type){case G.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:a,isFS:r,isFF:i,isZeroDurationCase:!1};case G.START_TO_START:return{sourceLag:-t.durationHours,targetLag:0,trueLag:a,isFS:r,isFF:i,isZeroDurationCase:!1};case G.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-e.durationHours,trueLag:a,isFS:r,isFF:i,isZeroDurationCase:!1};case G.START_TO_FINISH:return{sourceLag:-t.durationHours,targetLag:-e.durationHours,trueLag:a,isFS:r,isFF:i,isZeroDurationCase:!1};default:return{sourceLag:0,targetLag:0,trueLag:a,isFS:r,isFF:i,isZeroDurationCase:!1}}}function YT(t,e,n,r){if(t._summarySourceId===void 0)return null;let i=n.getActivity(t._summarySourceId);if(!i)return null;let a=ii(t._summarySourceId,n,r);return a?-n.calculateDuration({startDate:a.startDate,endDate:e.endDate,task:i}):null}function GT(t,e,n,r,i){let a=e.durationHours===0&&i;return{successorStart:r.getClosestWorkTime({date:t.endDate,dir:a?"past":"future",task:e}),link:n}}function qT(t,e,n,r){return n===null?new Date(t.endDate):r.getClosestWorkTime({date:t.endDate,dir:"future",task:e})}function $o(t,e,n,r){return n===null?Ln(t,e):r.calculateEndDate({startDate:t,durationHours:e,task:n})}function $T(t,e,n){return e===null?new Date(t.startDate):n.getClosestWorkTime({date:t.startDate,dir:"past",task:e})}function ha(t,e,n,r,i=e,a){let{sourceLag:o,targetLag:s,trueLag:l,isFS:c,isFF:d}=Sy(t,e,n),u=YT(n,t,r,a)??o,p=n._lagActivityId===void 0?null:r.getActivity(n._lagActivityId),y=u+s+l,f=e.durationHours===0;if(!(f?y!==0:u!==0||s!==0||l!==0)&&(!p||f&&u===0&&s===0&&l===0))return GT(t,e,n,r,c||d);let g=qT(t,c?p??e:t,i,r);if(u!==0&&(g=r.calculateEndDate({startDate:g,durationHours:u,task:t})),p){g=$o(g,n.lag??0,p,r),g=r.getClosestWorkTime({date:g,dir:c||n.type===G.START_TO_START?"future":"past",task:p});let P=s+l-(n.lag??0);P!==0&&(g=r.calculateEndDate({startDate:g,durationHours:P,task:e}))}else s!==0&&(g=r.calculateEndDate({startDate:g,durationHours:s,task:e})),l!==0&&(g=$o(g,l,i,r));if(e.durationHours===0){if(c||d)return{successorStart:r.getClosestWorkTime({date:g,dir:"past",task:e}),link:n};let P=new Date(Date.UTC(g.getUTCFullYear(),g.getUTCMonth(),g.getUTCDate()));return{successorStart:r.getClosestWorkTime({date:P,dir:"future",task:e}),link:n}}return{successorStart:r.getClosestWorkTime({date:g,dir:"future",task:e}),link:n}}function zo(t,e,n,r,i=t){let{sourceLag:a,targetLag:o,trueLag:s}=Sy(e,t,n),l=n._lagActivityId===void 0?null:r.getActivity(n._lagActivityId),c=l?new Date(t.startDate):$T(t,i,r);if(l){let d=o+s-(n.lag??0);d!==0&&(c=r.calculateEndDate({startDate:c,durationHours:-d,task:t})),c=$o(c,-(n.lag??0),l,r)}else s!==0&&(c=$o(c,-s,i,r)),o!==0&&(c=r.calculateEndDate({startDate:c,durationHours:-o,task:t}));return a!==0&&(c=r.calculateEndDate({startDate:c,durationHours:-a,task:e})),c}function vy(t,e,n){for(let r of t){let i=e.getActivity(r);if(!i)continue;let a=i.constraintType;if(!a||a===_.ASAP||a===_.ALAP)continue;let o=Tn(i,e);!o.earliestStart&&!o.latestStart&&!o.earliestEnd&&!o.latestEnd||n.set(r,{activityId:r,startDate:i.startDate,endDate:i.endDate,drivingLinkId:null,kind:_.ASAP,conflict:!1,earliestStart:o.earliestStart,latestStart:o.latestStart,earliestEnd:o.earliestEnd,latestEnd:o.latestEnd})}}function si(t,e,n){let r={earliestStart:e.earliestStart??null,latestStart:e.latestStart??null,earliestEnd:e.earliestEnd??null,latestEnd:e.latestEnd??null},i=e.earliestSchedulingStart??e.latestSchedulingStart??null,a;i===null?a=hc(t.startDate,r):Cp(i,r)?a=i:a=hc(i,r),e.startDate=a,e.endDate=n.calculateEndDate({startDate:a,durationHours:t.durationHours,task:t})}function Cy(t,e){if(!t||!e)return new Date;let{constraintType:n,constraintDate:r}=t;if(!n||!r)return e;switch(n){case _.MSO:case _.MFO:return new Date(r);case _.SNET:case _.FNET:return r>e?new Date(r):e;case _.SNLT:case _.FNLT:return r<e?new Date(r):e;default:return e}}function zT(t,e){return e.length?e.some(n=>String(n)===String(t)):!1}function Dy(t,e,n){return e.dragWithMultiple&&zT(t,n)}function Ty(t,e,n){let r=new Map;for(let i of t){if(i.type!==G.FINISH_TO_FINISH&&i.type!==G.START_TO_FINISH)continue;let a=i._summaryTargetId;if(a===void 0||r.has(a))continue;let o=!1,s=new Map,l=null,c=null,d=ii(a,e,y=>{let f=e.getActivity(y);if(!f)return null;let m=n(y);s.set(y,m.startDate),(!f.autoScheduling||f.progress===100||f.constraintType!==_.ASAP)&&(o=!0);for(let P of e.getIncomingLinkIds(y)){let L=e.getLink(P);L&&String(L.source)!==String(a)&&!e.isChildOf(L.source,a)&&(o=!0)}let A=f.constraintDate!==null&&(f.constraintType===_.MSO||f.constraintType===_.MFO);return f.autoScheduling&&f.progress!==100&&!A&&(l===null||m.endDate>l||m.endDate.getTime()===l.getTime()&&y<(c??y))&&(l=m.endDate,c=y),m}),u=new Set,p=c===null?[]:[c];for(;p.length>0;){let y=p.pop();if(!u.has(y)){u.add(y);for(let f of[...e.getIncomingLinkIds(y),...e.getOutgoingLinkIds(y)]){let m=e.getLink(f);if(!m)continue;let A=String(m.source)===String(y)?m.target:m.source;s.has(A)&&!u.has(A)&&p.push(A)}}}r.set(a,o&&d?{endDate:d.endDate,movableEnd:l,starts:s,drivingLeafIds:u}:null)}return r}async function Uc(t,e,n,r,i,a,o=!1){let s=new Map;for(let y of e){let f=String(y.target),m=s.get(f);m?m.push(y):s.set(f,[y])}let l=y=>{let f=a.get(y);if(f?.startDate&&f.endDate)return{startDate:f.startDate,endDate:f.endDate};let m=n.getActivity(y);return m?{startDate:m.startDate,endDate:m.endDate}:{startDate:new Date,endDate:new Date}},c=Ty(e,n,l),d=n.getFlags(),u=r.draggedIds??[],p=performance.now();for(let y of t){if(ya(p)){let S=await Uo(p,i);if(S.aborted)return a;p=S.newSliceStart}let f=n.getActivity(y);if(!f||!f.autoScheduling||f.progress===100||JT(f,n))continue;let m=s.get(String(y))??[],A=null,g=null,P=!1;for(let S of m){let k=n.getActivity(S.source);if(!k)continue;let E=l(S.source),j=E.startDate.getTime()!==k.startDate.getTime()||E.endDate.getTime()!==k.endDate.getTime(),w=j?{...k,startDate:E.startDate,endDate:E.endDate}:k,B=Dy(S.source,d,u)?{...S,lag:0}:S,$=B._summaryTargetId===void 0||B.type!==G.FINISH_TO_FINISH&&B.type!==G.START_TO_FINISH?null:c.get(B._summaryTargetId);if($){if(o)continue;let St=ha(w,{...f,durationHours:0},{...B,_targetLag:0,_trueLag:B.lag},n,f,l).successorStart,N=n.getActivity(B._summaryTargetId)??f;if($.endDate>=St||n.calculateDuration({startDate:$.endDate,endDate:St,task:N})===0||$.movableEnd===null||!$.drivingLeafIds.has(y))continue;B={...B,_targetLag:-n.calculateDuration({startDate:$.starts.get(y)??f.startDate,endDate:$.movableEnd,task:f}),_trueLag:B.lag}}let ft=!1,at=ha(w,f,B,n,f,St=>{let N=l(St),K=n.getActivity(St);return K&&(N.startDate.getTime()!==K.startDate.getTime()||N.endDate.getTime()!==K.endDate.getTime())&&(ft=!0),N});(!A||at.successorStart.getTime()>A.getTime())&&(A=at.successorStart,g=String(S.id),P=S._summaryTargetId!==void 0&&!j&&!ft&&(S._targetLag===0||r.preventSummaryTargetPullback===!0))}A!==null&&P&&A<f.startDate&&(A=new Date(f.startDate));let F=a.get(y),T=F?{...F}:{activityId:y,startDate:f.startDate,endDate:f.endDate,drivingLinkId:null,kind:_.ASAP,conflict:!1},x=T.earliestStart||T.latestStart||T.earliestEnd||T.latestEnd;if(!(!A&&!x)){if(A){let S=A;f.type===U.MILESTONE&&(S=Cy(f,A)),T.drivingLinkId=g,T.startDate=S,T.endDate=n.calculateEndDate({startDate:S,durationHours:f.durationHours,task:f}),T.earliestSchedulingStart=S,T.earliestSchedulingEnd=T.endDate}else f.constraintType===_.MSO?T.earliestStart&&(T.startDate=T.earliestStart,T.endDate=T.earliestEnd??n.calculateEndDate({startDate:T.earliestStart,durationHours:f.durationHours,task:f})):f.constraintType===_.MFO&&T.latestStart&&(T.startDate=T.latestStart,T.endDate=T.latestEnd??n.calculateEndDate({startDate:T.latestStart,durationHours:f.durationHours,task:f}));si(f,T,n),a.set(y,T)}}return a}function JT(t,e){return Fe(t.type,e.getChildren(t.id).length>0)}function On(t,e){return t.getUTCFullYear()===e.getUTCFullYear()&&t.getUTCMonth()===e.getUTCMonth()&&t.getUTCDate()===e.getUTCDate()}function Hc(t,e){return t.getTime()<e.getTime()}function Nn(t){return t instanceof Date&&!Number.isNaN(t.getTime())}async function Ey(t,e,n,r,i,a){let o=new Map(n),s=new Set;for(let f of t)r.getActivity(f)?.constraintType===_.ALAP&&s.add(String(f));if(s.size===0)return o;let l=new Map,c=new Map;for(let f of e){let m=String(f.source);s.has(m)&&_y(l,m,f);let A=String(f.target);s.has(A)&&_y(c,A,f)}let d=f=>{let m=o.get(f);if(m)return{startDate:m.startDate,endDate:m.endDate};let A=r.getActivity(f);return A?{startDate:A.startDate,endDate:A.endDate}:{startDate:new Date,endDate:new Date}},u=f=>!f.parentId||q(f.parentId)?r.getProjectEnd():d(f.parentId).endDate,p=(f,m)=>{let A=f,g=new Set;for(;A&&!q(A)&&!g.has(String(A));){if(g.add(String(A)),String(A)===String(m))return!0;let P=r.getActivity(A);if(!P||!P.parentId)break;A=P.parentId}return!1},y=performance.now();for(let f of t){if(ya(y)){let b=await Uo(y,a);if(b.aborted)return o;y=b.newSliceStart}let m=r.getActivity(f);if(!m||m.constraintType!==_.ALAP||!m.autoScheduling||m.progress===100||Fe(m.type,r.getChildren(f).length>0))continue;let A=u(m),g=A,P=null,L=null,F=!1,T=l.get(String(f))??[];for(let b of T){if((b.lag??0)<0)continue;let M=r.getActivity(b.target);if(!M||M.autoScheduling===!1)continue;let H=d(b.target),z={...M,startDate:H.startDate,endDate:H.endDate},Z=zo(z,m,b,r);(g===null||Z<g)&&(g=Z),(P===null||Z<P)&&(P=Z,L=b.type,F=m.parentId&&!q(m.parentId)?p(b.target,m.parentId):!1)}if(P!==null)if(F||A===null)g=P;else{let b=d(f).endDate,M=b.getTime()>A.getTime()?b:A;g=P<M?P:M}else{if(A===null||g===null)continue;g>A&&(g=A)}if(g===null)continue;let S=(c.get(String(f))??[]).some(b=>b.type===G.FINISH_TO_START||b.type===G.FINISH_TO_FINISH),k=new Date(Date.UTC(g.getUTCFullYear(),g.getUTCMonth(),g.getUTCDate())),E=m.endDate,j=r.getClosestWorkTime({date:new Date(Date.UTC(E.getUTCFullYear(),E.getUTCMonth(),E.getUTCDate()+1)),dir:"past",task:m}).getTime()===E.getTime(),w=A!==null&&g.getTime()===A.getTime()&&A.getTime()===E.getTime(),B=()=>w&&j?new Date(E):r.getClosestWorkTime({date:k,dir:"past",task:m}),$=()=>{let b=r.getClosestWorkTime({date:g,dir:"past",task:m});return r.getClosestWorkTime({date:new Date(Date.UTC(b.getUTCFullYear(),b.getUTCMonth(),b.getUTCDate())),dir:"future",task:m})},ft=r.getClosestWorkTime({date:g,dir:"future",task:m}).getTime()===g.getTime(),at;if(m.durationHours===0&&P===null)at=S&&ft?B():r.getClosestWorkTime({date:g,dir:"past",task:m});else if(m.durationHours===0)if(P!==null&&L===G.FINISH_TO_START&&g.getTime()===P.getTime())at=g;else if(S)at=B();else{let b=r.getClosestWorkTime({date:g,dir:"future",task:m});at=b.getTime()>g.getTime()&&!On(b,g)?$():b}else at=r.getClosestWorkTime({date:g,dir:"future",task:m});let St=r.calculateEndDate({startDate:at,durationHours:-m.durationHours,task:m}),N=o.get(f),K=N?{...N}:{activityId:f,startDate:St,endDate:at,drivingLinkId:null,kind:_.ALAP,conflict:!1};K.startDate=St,K.endDate=at,K.drivingLinkId=null,K.kind=_.ALAP;let it=K.earliestSchedulingStart??null;K.earliestSchedulingStart=null,K.earliestSchedulingEnd=null;let D=it!==null&&it.getTime()>St.getTime()?it:St;K.latestSchedulingStart=D,K.latestSchedulingEnd=D===St?at:r.calculateEndDate({startDate:D,durationHours:m.durationHours,task:m}),si(m,K,r),o.set(f,K)}return o}function _y(t,e,n){let r=t.get(e);r?r.push(n):t.set(e,[n])}var _e={warn(){},error(){}};var XT=864e5;function Ge(t){if(t.type===U.MILESTONE)return 0;let e=t.startDate?.getTime(),n=t.endDate?.getTime();return e==null||n==null||Number.isNaN(e)||Number.isNaN(n)?null:Math.floor((n-e)/XT)+1}function ma(t,e){e.cancelled||e.updatedIds.length===0||t.batchUpdate(()=>{for(let n of e.updatedIds){let r=e.plans.get(n);if(!r)continue;let i=t.getLiveActivity(n);i&&(i.startDate=r.startDate,i.endDate=r.endDate,i.calendarDuration=Ge(i),t.updateActivity(n))}})}function Bc(t,e){let n=String(e.source),r=String(e.target);if(n===r)return!0;let i=new Map;for(let a of t){let o=String(a.source),s=String(a.target),l=i.get(o)??[];l.push(s),i.set(o,l)}return ZT(i,r,n)}function ga(t){let e=new Map,n=p=>{let y=String(p),f=e.get(y);return f!==void 0?f:(e.set(y,e.size),e.size-1)},r=new Int32Array(t.length),i=new Int32Array(t.length);t.forEach((p,y)=>{r[y]=n(p.source),i[y]=n(p.target)});let a=e.size,o=new Int32Array(a+1),s=new Int32Array(a);for(let p=0;p<t.length;p+=1){let y=h(r,p);o[y+1]=h(o,y+1)+1;let f=h(i,p);s[f]=h(s,f)+1}for(let p=0;p<a;p+=1)o[p+1]=h(o,p+1)+h(o,p);let l=o.slice(0,a),c=new Int32Array(t.length);for(let p=0;p<t.length;p+=1){let y=h(r,p);c[h(l,y)]=h(i,p),l[y]=h(l,y)+1}let d=new Int32Array(a),u=0;for(let p=0;p<a;p+=1)h(s,p)===0&&(d[u++]=p);for(let p=0;p<u;p+=1){let y=h(d,p),f=h(o,y+1);for(let m=h(o,y);m<f;m+=1){let A=h(c,m),g=h(s,A)-1;s[A]=g,g===0&&(d[u++]=A)}}return u!==a}function ZT(t,e,n){if(e===n)return!0;let r=new Set([e]),i=new De;for(i.enqueue(e);!i.isEmpty();){let a=i.dequeue(),o=t.get(a)??[];for(let s of o){if(s===n)return!0;r.has(s)||(r.add(s),i.enqueue(s))}}return!1}function li(t){let e=QT(t);for(let n of e.adjacency.keys())e.records.has(n)||t_(n,e);return e.components}function QT(t){let e=new Map,n=new Set;for(let r of t){let i=String(r.source),a=String(r.target),o=Ry(e,i);if(Ry(e,a),i===a){n.add(i);continue}o.push(a)}return{adjacency:e,selfLooped:n,records:new Map,componentStack:[],nextIndex:0,components:[]}}function Ry(t,e){let n=t.get(e);if(n)return n;let r=[];return t.set(e,r),r}function t_(t,e){let n=[];for(n.push({node:t,record:Py(t,e),neighborCursor:0});n.length>0;){let r=n[n.length-1];if(r===void 0)break;let i=e.adjacency.get(r.node)??[];if(r.neighborCursor<i.length){let s=i[r.neighborCursor];if(r.neighborCursor+=1,s===void 0)continue;e_(r,s,n,e);continue}n.pop();let a=n[n.length-1];a&&r.record.lowLink<a.record.lowLink&&(a.record.lowLink=r.record.lowLink),r.record.lowLink===r.record.visitIndex&&n_(r.node,e)}}function e_(t,e,n,r){let i=r.records.get(e);if(!i){n.push({node:e,record:Py(e,r),neighborCursor:0});return}i.onStack&&i.visitIndex<t.record.lowLink&&(t.record.lowLink=i.visitIndex)}function Py(t,e){let n={visitIndex:e.nextIndex,lowLink:e.nextIndex,onStack:!0};return e.nextIndex+=1,e.records.set(t,n),e.componentStack.push({node:t,record:n}),n}function n_(t,e){let n=[];for(;;){let o=e.componentStack.pop();if(o===void 0||(o.record.onStack=!1,n.push(o.node),o.node===t))break}let r=n[0],i=n.length===1&&r!==void 0&&e.selfLooped.has(r);(n.length>1||i)&&e.components.push(n)}var ky=new WeakMap;function by(t,e,n){let r=ky.get(t)??new ai;ky.set(t,r);let i=new Set;for(let[a,o]of n.reparented){i.add(String(a)),o!==null&&i.add(String(o));let s=t.getActivity(a)?.parentId;s!=null&&i.add(String(s))}return r.projectHierarchy(e,t,new Jo(t,n),i)}function Fn(t,e,n){let r=n?new Jo(t,n):t;return uy([...e],r)}var Jo=class{constructor(e,n){this.base=e;e.isWorkTime!==void 0&&(this.isWorkTime=e.isWorkTime.bind(e));for(let[r,i]of n.reparented){let a=String(r),o=i===null||q(i)?null:i,s=e.getActivity(r)?.parentId??null,l=s===null||q(s)?null:String(s),c=o===null?null:String(o);if(l!==c){if(this.reparented.set(a,o),l!==null){let d=this.movedOutByParent.get(l)??new Set;d.add(a),this.movedOutByParent.set(l,d)}if(c!==null){let d=this.movedInByParent.get(c)??[];d.push(r),this.movedInByParent.set(c,d)}}}}base;isWorkTime;reparented=new Map;movedOutByParent=new Map;movedInByParent=new Map;withOverride(e){if(!e)return null;let n=this.reparented.get(String(e.id));return n===void 0?e:{...e,parentId:n}}getActivity(e){return this.withOverride(this.base.getActivity(e))}getLiveActivity(e){return this.withOverride(this.base.getLiveActivity(e))}getAllActivities(){return this.base.getAllActivities().map(e=>this.withOverride(e)??e)}getChildren(e){let n=String(e),r=this.movedOutByParent.get(n),i=this.base.getChildren(e),a=r?i.filter(s=>!r.has(String(s))):[...i],o=this.movedInByParent.get(n);return o&&a.push(...o),a}getParent(e){let n=this.reparented.get(String(e));return n===void 0?this.base.getParent(e):n===null?null:this.getActivity(n)}isChildOf(e,n){let r=String(n),i=new Set,a=this.getActivity(e);for(;a;){let o=a.parentId;if(o===null||q(o))return!1;let s=String(o);if(s===r)return!0;if(i.has(s))return!1;i.add(s),a=this.getActivity(o)}return!1}getAllLinks(){return this.base.getAllLinks()}getAllIds(){return this.base.getAllIds()}getLink(e){return this.base.getLink(e)}activityExists(e){return this.base.activityExists(e)}getOutgoingLinkIds(e){return this.base.getOutgoingLinkIds(e)}getIncomingLinkIds(e){return this.base.getIncomingLinkIds(e)}getClosestWorkTime(e){return this.base.getClosestWorkTime(e)}calculateEndDate(e){return this.base.calculateEndDate(e)}calculateDuration(e){return this.base.calculateDuration(e)}batchUpdate(e){this.base.batchUpdate(e)}updateActivity(e){this.base.updateActivity(e)}getFlags(){return this.base.getFlags()}getProjectEnd(){return this.base.getProjectEnd()}};function ci(t){let{port:e,proposedPort:n,currentLinks:r,proposedLinks:i,proposal:a}=t,o=Fn(n??e,i,a);return Ny(o,()=>Fn(e,r))}function Oy(t,e){let n=t.getAllLinks();return Ny(by(t,n,e),()=>Fn(t,n))}function Ny(t,e){if(!ga(t))return{ok:!0};let n=e(),r=Ly(n),a=[...Ly(t)].filter(o=>!r.has(o));return a.length===0?{ok:!0}:{ok:!1,newlyCyclicActivityIds:a}}function Ly(t){let e=new Set;for(let n of li(t))for(let r of n)e.add(r);return e}function Xo(t,e,n){return n.getChildren(t).length>0||n.getChildren(e).length>0}function qe(t,e){switch(t.kind){case xt.CREATE:return r_(t,e);case xt.UPDATE:return i_(t,e.port,e.rejectParentLinkMutations??!1);case xt.DELETE:return a_(t,e)}}function Aa(t,e){if(t.length===0)return{applied:!0};let n=e.port.getAllLinks(),r=new Map,i=[];for(let c of n){let d=Zo(c);r.has(d)||r.set(d,c.id),i.push({source:c.source,target:c.target})}let a=ga(i),o=null;for(let{operation:c,linkId:d}of t){if(String(c.source)===String(c.target)){o={applied:!1,rejected:kt.SELF_LINK};break}if(!e.port.getActivity(c.source)||!e.port.getActivity(c.target)){o={applied:!1,rejected:kt.ACTIVITY_MISSING};break}if(e.rejectParentLinkMutations&&Xo(c.source,c.target,e.port)){o={applied:!1,rejected:kt.HIERARCHY_LINK};break}if(Yo(c.source,c.target,e.port)){o={applied:!1,rejected:kt.HIERARCHY_LINK};break}let u=Zo(c),p=r.get(u);if(p!==void 0){o={applied:!1,rejected:kt.DUPLICATE,linkId:p};break}if(r.set(u,d),a&&Bc(i,{source:c.source,target:c.target}))return{applied:!1,rejected:kt.CYCLE};i.push({source:c.source,target:c.target})}if(!a&&ga(i))return{applied:!1,rejected:kt.CYCLE};if(o)return o;let s=[...n,...t.map(({operation:c,linkId:d})=>({id:d,source:c.source,target:c.target,type:c.type,lag:c.lag,freeSlackHours:null,isCritical:!1}))];return ci({port:e.port,currentLinks:n,proposedLinks:s}).ok?{applied:!0}:{applied:!1,rejected:kt.CYCLE}}function Qo(t,e){if(t.length===0)return{applied:!0};let n=Aa(t,e);if(!n.applied)return n;for(let{operation:r,linkId:i}of t){let a=e.preserved?.get(i);e.port.addLink({id:i,source:r.source,target:r.target,type:r.type,lag:r.lag,freeSlackHours:null,isCritical:!1,...a?.ganttId===void 0?{}:{ganttId:a.ganttId},...a?.sectorId===void 0?{}:{sectorId:a.sectorId},...a?.proplannerId===void 0?{}:{proplannerId:a.proplannerId}})}return{applied:!0}}function Zo(t){return JSON.stringify([String(t.source),String(t.target),t.type])}function r_(t,e){let{port:n}=e;if(String(t.source)===String(t.target))return{applied:!1,rejected:kt.SELF_LINK};let r=n.getActivity(t.source),i=n.getActivity(t.target);if(!r||!i)return{applied:!1,rejected:kt.ACTIVITY_MISSING};if(e.rejectParentLinkMutations&&Xo(t.source,t.target,n))return{applied:!1,rejected:kt.HIERARCHY_LINK};if(Yo(t.source,t.target,n))return{applied:!1,rejected:kt.HIERARCHY_LINK};let a=n.getAllLinks();for(let d of a)if(String(d.source)===String(t.source)&&String(d.target)===String(t.target)&&d.type===t.type)return{applied:!1,rejected:kt.DUPLICATE,linkId:d.id};let o=a.map(d=>({source:d.source,target:d.target}));if(Bc(o,{source:t.source,target:t.target}))return{applied:!1,rejected:kt.CYCLE};if(!e.newLinkId)throw new Error("creating a link requires newLinkId");let s=e.newLinkId(),l={id:s,source:t.source,target:t.target,type:t.type,lag:t.lag,freeSlackHours:null,isCritical:!1};return ci({port:n,currentLinks:a,proposedLinks:[...a,l]}).ok?(n.addLink(l),{applied:!0,linkId:s}):{applied:!1,rejected:kt.CYCLE}}function i_(t,e,n){let r=e.getLink(t.linkId);if(!r)return{applied:!1,rejected:kt.LINK_MISSING};let i={...r,source:t.source??r.source,target:t.target??r.target,type:t.type??r.type,lag:t.lag??r.lag};if(String(i.source)===String(i.target))return{applied:!1,rejected:kt.SELF_LINK};if(!e.getActivity(i.source)||!e.getActivity(i.target))return{applied:!1,rejected:kt.ACTIVITY_MISSING};if(n&&(Xo(r.source,r.target,e)||Xo(i.source,i.target,e)))return{applied:!1,rejected:kt.HIERARCHY_LINK};if(Yo(i.source,i.target,e))return{applied:!1,rejected:kt.HIERARCHY_LINK};let a=e.getAllLinks(),o=a.find(c=>String(c.id)!==String(t.linkId)&&Zo(c)===Zo(i));if(o)return{applied:!1,rejected:kt.DUPLICATE,linkId:o.id};let s=a.map(c=>String(c.id)===String(t.linkId)?i:c);return ci({port:e,currentLinks:a,proposedLinks:s}).ok?((String(r.source)!==String(i.source)||String(r.target)!==String(i.target))&&e.setLinkEndpoints(t.linkId,i.source,i.target),t.lag!==void 0&&e.setLinkField(t.linkId,"lag",t.lag),t.type!==void 0&&e.setLinkField(t.linkId,"type",t.type),{applied:!0,linkId:t.linkId}):{applied:!1,rejected:kt.CYCLE}}function a_(t,e){let{port:n}=e;return n.getLink(t.linkId)?(n.removeLink(t.linkId),{applied:!0,linkId:t.linkId}):{applied:!1,rejected:kt.LINK_MISSING}}var we={FINISH_TO_START:"fs",START_TO_START:"ss",FINISH_TO_FINISH:"ff",START_TO_FINISH:"sf"},ts={[G.FINISH_TO_START]:we.FINISH_TO_START,[G.START_TO_START]:we.START_TO_START,[G.FINISH_TO_FINISH]:we.FINISH_TO_FINISH,[G.START_TO_FINISH]:we.START_TO_FINISH},mr={[we.FINISH_TO_START]:G.FINISH_TO_START,[we.START_TO_START]:G.START_TO_START,[we.FINISH_TO_FINISH]:G.FINISH_TO_FINISH,[we.START_TO_FINISH]:G.START_TO_FINISH},Fy=we.FINISH_TO_START;function wy(t){if(t in mr)return mr[t]}var xy=";",wn={DAY:"d",WEEK:"w",WEEK_DHTMLX:"wk",MONTH:"m",MONTH_DHTMLX:"mon",YEAR:"y"},My=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)(weeks?|wk|w|months?|mon|m|days?|d|years?|y)?)?$/i;var o_=5,es=30,jc=365,s_={[wn.DAY]:1,day:1,days:1,[wn.MONTH]:es,[wn.MONTH_DHTMLX]:es,month:es,months:es,[wn.YEAR]:jc,year:jc,years:jc},l_=new Set([wn.WEEK,wn.WEEK_DHTMLX,"week","weeks"]);function ns(t,e={}){let n=[],r=[],i=e.daysPerWeek!==void 0&&Number.isFinite(e.daysPerWeek)&&e.daysPerWeek>0?e.daysPerWeek:o_,a=t.replace(/\s+/g,"");if(a.length===0)return{specs:n,errors:r};for(let o of a.split(xy)){if(o.length===0)continue;let s=c_(o,i);s?n.push(s):r.push(o)}return{specs:n,errors:r}}function c_(t,e){let n=t.toLowerCase(),r=My.exec(n);if(!r)return null;let[,i,a,o,s,l]=r,c=a?mr[a]:mr[Fy],d=0;if(s!==void 0){let u=Number(s);if(Number.isNaN(u))return null;let p=l!==void 0&&l_.has(l)?e:s_[l??wn.DAY],y=u*p;d=o==="-"?-y:y}return{correlativeId:i,type:c,lag:d}}function di(t){let{targetActivityId:e,currentLinks:n,desiredSpecs:r}=t,i=[],a=new Map;for(let c of r){let d=t.resolveActivityByCorrelative(c.correlativeId);if(d==null){i.push(c);continue}let u=rs(d,c.type);a.has(u)||a.set(u,{source:d,type:c.type,lag:c.lag})}let o=new Map;for(let c of n)String(c.target)===String(e)&&o.set(rs(c.source,c.type),c);let s=[],l=Uy(o,a,c=>c.source);for(let[c,d]of a){if(o.has(c))continue;let u=l.get(String(d.source))?.pop();if(!u)continue;let[p,y]=u;s.push({kind:xt.UPDATE,linkId:y.id,type:d.type,lag:d.lag}),o.delete(p),a.delete(c)}for(let[c,d]of o)a.has(c)||s.push({kind:xt.DELETE,linkId:d.id});for(let[c,d]of a){let u=o.get(c);u&&u.lag!==d.lag&&s.push({kind:xt.UPDATE,linkId:u.id,lag:d.lag})}for(let[c,d]of a)o.has(c)||s.push({kind:xt.CREATE,source:d.source,target:e,type:d.type,lag:d.lag});return{operations:s,unresolved:i}}function rs(t,e){return`${String(t)}::${e}`}function Uy(t,e,n){let r=new Map;for(let i of t){if(e.has(i[0]))continue;let a=String(n(i[1])),o=r.get(a)??[];o.push(i),r.set(a,o)}return r}function ui(t){let{sourceActivityId:e,currentLinks:n,desiredSpecs:r}=t,i=[],a=new Map;for(let c of r){let d=t.resolveActivityByCorrelative(c.correlativeId);if(d==null){i.push(c);continue}let u=rs(d,c.type);a.has(u)||a.set(u,{target:d,type:c.type,lag:c.lag})}let o=new Map;for(let c of n)String(c.source)===String(e)&&o.set(rs(c.target,c.type),c);let s=[],l=Uy(o,a,c=>c.target);for(let[c,d]of a){if(o.has(c))continue;let u=l.get(String(d.target))?.pop();if(!u)continue;let[p,y]=u;s.push({kind:xt.UPDATE,linkId:y.id,type:d.type,lag:d.lag}),o.delete(p),a.delete(c)}for(let[c,d]of o)a.has(c)||s.push({kind:xt.DELETE,linkId:d.id});for(let[c,d]of a){let u=o.get(c);u&&u.lag!==d.lag&&s.push({kind:xt.UPDATE,linkId:u.id,lag:d.lag})}for(let[c,d]of a)o.has(c)||s.push({kind:xt.CREATE,source:e,target:d.target,type:d.type,lag:d.lag});return{operations:s,unresolved:i}}function is(t){let e=Math.sign(t)*Math.round(Math.abs(t));return Object.is(e,-0)?0:e}function Ee(t,e){return Math.sign(t)*Math.round(Math.abs(t)*e)}var Hy={rawInputToConstraintDate(t,e){let n=new Date(t);return n.setUTCHours(0,0,0,0),n.getTime()===t.getTime()?e.getClosestWorkTime({direction:yt.FUTURE,date:t,unit:mt.HOUR}):e.isWorkTime(t,mt.HOUR)?t:n},computeLagBetweenTasks(t,e,n){return n.calculateDuration(t,e)}};function Vc(t,e,n){switch(n){case G.FINISH_TO_START:return{sourceDate:t.endDate,targetDate:e.startDate};case G.START_TO_START:return{sourceDate:t.startDate,targetDate:e.startDate};case G.FINISH_TO_FINISH:return{sourceDate:t.endDate,targetDate:e.endDate};case G.START_TO_FINISH:return{sourceDate:t.startDate,targetDate:e.endDate}}}var Wc=Hy;var Mn=class{adapter;reporter;currentCalculationId=0;topoCache=new Ho;expandedLinksCache=new ai;constructor(e,n=_e){this.adapter=e,this.reporter=n}getCurrentCalculationId(){return this.currentCalculationId}invalidateTopoCache(){this.topoCache.invalidate()}invalidateAllCaches(){this.topoCache.invalidate()}async schedule(e={}){let n=++this.currentCalculationId,r=ny(n,()=>this.currentCalculationId),i={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{By(this.adapter);let a=xn("schedule.total"),o=xn("schedule.expandParentLinks"),s=this.adapter.getAllLinks(),l=this.expandedLinksCache.get(s,this.adapter);on(o);let c=l;if((await ni(r)).aborted)return{...i,cancelled:!0};let d=xn("schedule.scoping"),u=this.adapter.getAllIds(),p=p_(e,c,this.adapter,this.expandedLinksCache),y=p.links,f=p.idSet;on(d);let m=xn("schedule.topologicalSort"),A=f_(this.topoCache,u,c,f,e.seedIds!==void 0);if(on(m),A.hasCycles)return on(a),{...i,cycles:[A.cycleNodes]};if((await ni(r)).aborted)return{...i,cancelled:!0};let g=xn("schedule.processConstraints"),P=new Map;if(vy(A.ordered,this.adapter,P),on(g),(await ni(r)).aborted)return{...i,cancelled:!0};let L=xn("schedule.asapPass"),F=y.some(w=>w._summaryTargetId!==void 0&&(w.type===G.FINISH_TO_FINISH||w.type===G.START_TO_FINISH)),T=await Uc(A.ordered,y,this.adapter,e,r,P,F),x=F?await Uc(A.ordered,y,this.adapter,e,r,T):T;if(on(L),(await ni(r)).aborted)return{...i,cancelled:!0};let S=xn("schedule.alapPass"),k=await Ey(A.reversed,y,x,this.adapter,e,r);if(on(S),(await ni(r)).aborted)return{...i,cancelled:!0};let E=xn("schedule.diff"),j=[];for(let[w,B]of k){let $=this.adapter.getActivity(w);if(!$)continue;let ft=$.startDate.getTime()!==B.startDate.getTime(),at=$.endDate.getTime()!==B.endDate.getTime();(ft||at)&&j.push(w)}return on(E),on(a),{plans:k,updatedIds:j,cycles:[],cancelled:!1}}catch(a){throw this.reporter.error("[AutoScheduler] Error during scheduling",a),a}finally{By(this.adapter)}}},d_=!1;function u_(){let t=globalThis.__SCHEDULER_PHASE_LOG__;return typeof t=="boolean"?t:d_}function xn(t){return{name:t,startedAt:performance.now()}}function By(t){let e=t;typeof e.clearCalendarCache=="function"&&e.clearCalendarCache()}function on(t){if(!u_())return;let e=performance.now()-t.startedAt;console.log(`[scheduler] ${t.name} ${e.toFixed(1)}ms`)}function p_(t,e,n,r){if(t.seedIds!==void 0)return sy(t.seedIds,e,r.coneIndex(n),n);let i=t.triggerId;if(i==null)return{idSet:null,links:e};let a=my(i,e);return y_(a,e,n)}function y_(t,e,n){let r=new Set(t.activityIds),i=new Set;for(let o of n.getAllActivities()){let s=String(o.id);o.constraintType===_.ALAP&&!r.has(s)&&(i.add(s),r.add(s))}if(i.size===0)return{idSet:r,links:t.links};let a=[...t.links];for(let o of e)(i.has(String(o.source))||i.has(String(o.target)))&&a.push(o);return{idSet:r,links:a}}function f_(t,e,n,r,i=!1){let a=t.get(e,n);if(a.hasCycles&&i)return a;if(a.hasCycles){let s=r?Array.from(r):e;return bn(s,n)}if(!r)return a;let o=ry(a.ordered,r);return{ordered:o,reversed:[...o].reverse(),hasCycles:!1,cycleNodes:[]}}function jy(t,e,n){let r=e.getActivity(t);if(!r)return;let i=n?{...r,endDate:n.endDate}:r,a=e.calendarReader.getCalendar(String(r.calendarId));for(let o of e.getIncomingLinkIds(t)){let s=e.getLink(o);if(!s)continue;let l=e.getActivity(s.source);if(!l||l.constraintType===_.ALAP||an(r.type)&&(s.type===G.START_TO_FINISH||s.type===G.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=Vc(l,i,s.type),p=Wc.computeLagBetweenTasks(d,u,a);p!==s.lag&&e.setLinkField(s.id,Vt.LAG,p)}}function Vy(t,e){let n=e.getActivity(t);n&&an(n.type)&&(n.durationHours=0)}function pi(t){let e=0,n=!1;for(let r of t)r.ponderator>0&&(e+=r.ponderator/100*r.progress,n=!0);return n?e:null}function as(t){return Number(t.toFixed(2))}function Ia(t,e){let n=new Map;for(let r of h_(t))Yy(r,t,e,n)}function Ky(t,e,n){let r=new Map;for(let i of t)Yy(i,e,n,r)}function h_(t){let e=new Set;t.forEachActivity((r,i)=>{t.getChildren(i).length>0&&e.add(i)});let n=new Map;for(let r of e)n.set(r,m_(r,t));return[...e].sort((r,i)=>(n.get(i)??0)-(n.get(r)??0))}function m_(t,e){let n=0,r=t;for(;r&&r!=="0"&&e.getActivity(r);)n+=1,r=e.getParentId(r);return n}function Yy(t,e,n,r){let i=e.getChildren(t);if(i.length===0)return;let a=[];for(let o of i){let s=e.getActivity(o);s&&a.push({progress:Number(s.progress??0),ponderator:Number(s.ponderator??0)})}Kc(t,a,e,n,r)}function Kc(t,e,n,r,i=new Map){let a=n.getActivity(t);if(!a)return;let o=pi(e),l=o===null&&r===Dt.COST&&g_(t,n,i)===!0?0:o;if(l===null){let c=n.getProgressFallback(t);c!==null&&Wy(t,c,n);return}n.getProgressFallback(t)===null&&n.setProgressFallback(t,Number(a.progress??0)),Wy(t,as(l),n)}function Wy(t,e,n){n.setActivityField(t,R.PROGRESS,e),n.setActivityField(t,"autoScheduling",ue(e))}function g_(t,e,n){let r=[...e.getChildren(t)],i=!1;for(;r.length>0;){let o=r.pop(),s=n.get(o);if(s===!1)return n.set(t,!1),!1;if(s!==void 0){i||=s===!0;continue}let l=e.getActivity(o);if(!l)continue;let c=e.getChildren(o);if(c.length>0){r.push(...c);continue}let d=A_(l);if(i||=d!==null,d===!1)return n.set(t,!1),!1}let a=i?!0:null;return n.set(t,a),a}function A_(t){let e=jt(t);return e?t.type===U.MILESTONE||e.cost===0:null}function Gy(t,e,n){let r=[t];for(;r.length>0;){let i=r.pop();if(i===void 0)continue;let a=n.getChildren(i);a.length!==0&&(n.setProgressFallback(i,e),r.push(...a))}}function ye(t,e){return(Number(t)||0)*(Number(e)||0)/100}var Sa={SKIP:"skip",FREEZE_WITHOUT_CONTRIBUTION:"freeze-when-no-contribution"};async function sn(t,e,n=!0,r={}){let i=e?va(t,e):T_(t),a=n?r.progressMode??Sa.FREEZE_WITHOUT_CONTRIBUTION:Sa.SKIP;await I_(i,t,a,{recomputeRealWork:r.recomputeRealWork??!1,criterion:r.criterion})}function os(t,e){qy(t,e,Sa.SKIP)}async function I_(t,e,n,r={recomputeRealWork:!1}){let i=new Map,a=200,o=0;for(let s of t)qy(s,e,n,r.recomputeRealWork,r.criterion,i),o+=1,o%a===0&&await Ot()}function va(t,e){let n=new Set,r=new Map;for(let o of e)S_(o,t,n,r);if(n.size===0)return[];let i=Array.from(n),a=v_(i,r);return $y(i,a)}function S_(t,e,n,r){let i=e.getParentId(t);for(;i&&!q(i);){if(n.has(i))return;n.add(i);let a=e.getParentId(i);r.set(i,a),i=a}}function v_(t,e){let n=new Map;for(let r of t){if(n.has(r))continue;let i=[],a=new Set,o=r;for(;o&&!q(o)&&!n.has(o)&&!a.has(o);)i.push(o),a.add(o),o=e.get(o)??null;let s=o?n.get(o)??0:0;for(let l=i.length-1;l>=0;l-=1)s+=1,n.set(i[l],s)}return n}function C_(t,e,n){let r=null,i=null,a=0,o=[];for(let s of t){let l=e.getActivity(s);if(!l)continue;let c=l.startDate.getTime(),d=l.endDate.getTime();(r===null||c<r)&&(r=c),(i===null||d>i)&&(i=d),n&&(a+=D_(l,e.getChildren(s).length>0)),o.push({progress:Number(l.progress??0),ponderator:Number(l.ponderator??0)})}return{minStart:r,maxEnd:i,realWorkSum:a,weightedChildren:o}}function qy(t,e,n=Sa.FREEZE_WITHOUT_CONTRIBUTION,r=!1,i,a=new Map){let o=e.getActivity(t);if(!o)return;let s=e.getChildren(t);if(s.length===0)return;let l=C_(s,e,r);if(l.minStart===null||l.maxEnd===null)return;let c=String(o.calendarId??""),d=e.calendarReader.getCalendar(c),u=new Date(l.minStart),p=new Date(l.maxEnd),y=d.calculateDuration(u,p);e.setActivityField(t,"startDate",u),e.setActivityField(t,"endDate",p),e.setActivityField(t,"durationHours",y),n!==Sa.SKIP&&Kc(t,l.weightedChildren,e,i,a),r&&e.setActivityField(t,"realWorkHours",l.realWorkSum)}function D_(t,e){return e?Number(t.realWorkHours)||0:ye(t.workHours,t.progress)}function T_(t){let e=__(t),n=E_(e,t);return $y(e,n)}function __(t){let e=new Set;return t.forEachActivity(n=>{n.parentId!==null&&e.add(n.parentId)}),Array.from(e)}function E_(t,e){let n=new Map;for(let r of t)n.set(r,R_(r,e));return n}function R_(t,e){let n=0,r=t;for(;r&&!q(r)&&e.getActivity(r);)n+=1,r=e.getParentId(r);return n}function $y(t,e){return[...t].sort((n,r)=>(e.get(r)??0)-(e.get(n)??0))}var zy={updateActivityDuration:Vy,updateTaskTiming:k_("updateTaskTiming"),adjustLinkLagOnTaskMove:jy,recordLastStartDate:P_};function P_(t,e){let n=e.getActivity(t);n&&e.setLastStartDate(t,n.startDate)}function Un(t,e,n,r){for(let i of e){let a=i in zy?zy[i]:void 0;if(!a){console.warn(`[replay post-processors] unknown: ${i} \u2014 skipping. Add an entry in POST_PROCESSORS if a fixture needs it.`);continue}a(t,n,r??null)}}function k_(t){return()=>{console.debug(`[replay post-processors] ${t}: not yet ported to adapter \u2014 no-op.`)}}function rt(t,e){return e!==void 0?{ok:!0,value:t,raw:e}:{ok:!0,value:t}}function ut(t){return{ok:!1,reason:t}}function gt(){return{valid:!0}}function Ht(t,e){return e!==void 0?{valid:!1,reason:t,notification:e}:{valid:!1,reason:t}}function ct(){return{allowed:!0}}function vt(t,e){return e!==void 0?{allowed:!1,reason:t,alertKey:e}:{allowed:!1,reason:t}}function It(t,e={}){return{patch:t,needsAutoSchedule:e.autoSchedule??!1,postProcessors:e.postProcessors??[],...e.cascadeMutations!==void 0?{cascadeMutations:e.cascadeMutations}:{},...e.trackingEvents!==void 0?{trackingEvents:e.trackingEvents}:{}}}var Yt={PROGRESS_ENTRY:"activity_progress_entry",PROGRESS_UPDATE_RADIO_BUTTON:"activity_progress_update_radio_button",DURATION_ENTRY:"activity_duration_entry",START_DATE_ENTRY:"activity_start_date_entry",END_DATE_ENTRY:"activity_end_date_entry",NAME_ENTRY:"activity_name_entry",DESCRIPTION_ENTRY:"activity_description_entry",CALENDAR_ASSIGNMENT:"activity_calendar_assignment",COST_BUDGETED_ENTRY:"activity_cost_budgeted_entry",COST_SPENT_ENTRY:"activity_cost_spent_entry",LABOR_HOURS_BUDGETED_ENTRY:"activity_labor_hours_budgeted_entry"};var Jy={targetField:"name",canEdit(){return ct()},parseInput(t){return typeof t!="string"?ut("not_a_string"):rt(t)},validate(){return gt()},transform(t,e){return It({name:e},{autoSchedule:!1,postProcessors:[]})},trackEvent:Yt.NAME_ENTRY};var Xy={targetField:"description",canEdit(){return ct()},parseInput(t){return typeof t!="string"?ut("not_a_string"):rt(t.trim())},validate(){return gt()},transform(t,e){return It({description:e},{autoSchedule:!1,postProcessors:[]})},trackEvent:Yt.DESCRIPTION_ENTRY};function xe(t){return t.constraintType??_.ASAP}var ss=100;function Hn(t){return t.progress>=ss}function Wt(t,e){return Fe(t.type,e.hasChildren(t.id))}function Zy(t){return t.progress>0}function Qy(t){return t.hasLookaheadTasks}function gr(t,e){return Math.round(Math.ceil(t*e*60)/60)}var yi=t=>({endDate:t});var Ca="UTC",b_=1,L_=9999;function O_(t){let e=t.getUTCFullYear();return e>=b_&&e<=L_}function Bn(t,e){if(e===Ca&&O_(t))return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()));if(e){let n=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(t),r=i=>Number(n.find(a=>a.type===i)?.value);return new Date(Date.UTC(r("year"),r("month")-1,r("day")))}return new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate()))}function Ta(t,e){if(!e||e===Ca){let p=new Date(t);return p.setUTCHours(23,59,0,0),p}let n=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(t),r=p=>Number(n.find(y=>y.type===p)?.value),i=r("year"),a=r("month"),o=r("day"),s=Date.UTC(i,a-1,o,23,59,0,0),l=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(new Date(s)),c=p=>Number(l.find(y=>y.type===p)?.value),u=Date.UTC(c("year"),c("month")-1,c("day"),c("hour")===24?0:c("hour"),c("minute"),c("second"))-s;return new Date(s-u)}function N_(t,e){let n=Bn(e,Ca);for(;!t.isWorkTime(n,mt.DAY);)n=new Date(n),n.setUTCDate(n.getUTCDate()+1),n=Bn(n,Ca);return n}function _a(t,e){return t.getClosestWorkTime({direction:yt.FUTURE,date:e,unit:mt.HOUR})}function Yc(t,e){let n=N_(t,e),r=new Date(n);return r.setUTCDate(r.getUTCDate()+1),r.setUTCHours(0,0,0,0),t.getClosestWorkTime({direction:yt.PAST,date:r,unit:mt.HOUR})}function tf(t,e){return e.isWorkTime(t,mt.HOUR)?new Date(t):e.getClosestWorkTime({direction:yt.FUTURE,date:t,unit:mt.HOUR})}function ef(t,e){if(e.isWorkTime(t,mt.HOUR))return new Date(t);let n=Gc(t)?F_(t):t;return e.getClosestWorkTime({direction:yt.PAST,date:n,unit:mt.HOUR})}function Gc(t){return t.getUTCHours()===0&&t.getUTCMinutes()===0&&t.getUTCSeconds()===0&&t.getUTCMilliseconds()===0}function F_(t){let e=new Date(t);return e.setUTCDate(e.getUTCDate()+1),e}var Da=new Set([_.SNET,_.SNLT,_.MSO]),qc=new Set([_.FNET,_.FNLT,_.MFO]),jn=new Set([_.ASAP,_.ALAP]),ls=_.SNET;function $e(t,e,n){let r=Bn(t,Ca);return!Da.has(n)&&!qc.has(n)?r:Da.has(n)?nf(r,e):rf(r,e)}function nf(t,e){return sf(t,_a(e,t))}function rf(t,e){return sf(t,Yc(e,t))}function af(t,e){return Gc(t)?nf(t,e):new Date(t)}function of(t,e){return Gc(t)?rf(t,e):new Date(t)}function sf(t,e){let n=new Date(t);return n.setUTCHours(e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds()),n}var Vn=()=>({constraintType:ls});var Ar=t=>({constraintDate:t}),lf=t=>({constraintDate:t});var cf={UPDATE_ACTIVITY_DURATION:"updateActivityDuration",UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var df={NOT_A_NUMBER:"not_a_number",NOT_A_STRING:"not_a_string",NOT_AN_ARRAY:"not_an_array",NOT_AN_INTEGER:"not_an_integer",INVALID_DATE:"invalid_date",INVALID_CONSTRAINT_TYPE:"invalid_constraint_type",EMPTY_CALENDAR:"empty_calendar",EMPTY_CUSTOM_ID:"empty_custom_id",EXCEEDS_MAX_LENGTH:"exceeds_max_length"},Ir={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"},Me={COMPLETED:"completed",SUMMARY:"summary",HAS_PROGRESS:"has_progress",HAS_LOOKAHEAD_TASKS:"has_lookahead_tasks",SIR_START_AFTER_PROGRESS:"sir_start_after_progress",DATA_DATE_UNAVAILABLE:"data_date_unavailable",DATA_DATE_ACTUAL_START_LOCKED:"data_date_actual_start_locked",DATA_DATE_ACTIVITY_COMPLETED:"data_date_activity_completed",DATA_DATE_UNITS_PERCENT_READ_ONLY:"data_date_units_percent_read_only",SECONDARY_CONSTRAINT_TYPE_REQUIRED:"secondary_constraint_type_required"},cs={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",DATA_DATE_EDIT_REJECTED:"data_date_edit_rejected",DATA_DATE_UNITS_PERCENT_READ_ONLY:"data_date_units_percent_read_only"};function fi(t,e,n){return vo(t,e,n)}function hi(t,e,n){return Co(t,e,n)}var pf={targetField:"durationHours",canEdit(t,e){return Hn(t)?vt("completed","cant_edit_completed_activity"):Wt(t,e)?vt("summary","summary_column_value"):ct()},parseInput(t,e,n){let r=parseFloat(String(t));return Number.isFinite(r)?rt(gr(r,n.hoursPerDay)):ut("not_a_number")},validate(t,e,n){return uf(n)?Ht(Ir.NEGATIVE_DURATION):w_(e,n)?Ht("unchanged"):gt()},transform(t,e,n){if(uf(e))return It({},{autoSchedule:!1,postProcessors:[]});let r=x_(t,e,n),i=M_(t,e,n,r.violated);return{...It(i,{autoSchedule:!0,postProcessors:[cf.RECORD_LAST_START_DATE]}),...r.violated?{constraintWarning:hi(r.constraintType,r.constraintDate,yf(t,e,n)??void 0)}:{}}},trackEvent:Yt.DURATION_ENTRY};function uf(t){return Math.sign(t)===-1}function w_(t,e){return t===e}function x_(t,e,n){let r=n.calendars.getCalendar(t.calendarId);if(!r)return{violated:!1};let i=t.constraintType;if(i!==_.FNET&&i!==_.FNLT&&i!==_.MFO)return{violated:!1};let a=r.calculateEndDate(t.startDate,e);return fi(i,t.constraintDate,a)}function M_(t,e,n,r=!1){let i={};r&&Object.assign(i,Vn(),Ar(t.startDate));let a=pa(t.durationHours,e);a&&(i.type=a),i.durationHours=e;let o=yf(t,e,n);return o&&Object.assign(i,yi(o)),i}function yf(t,e,n){let r=n.calendars.getCalendar(t.calendarId);return r?r.calculateEndDate(t.startDate,e):null}var mi=t=>({realWorkHours:t});var U_=0,H_=ss,gi={targetField:"progress",canEdit(t,e){return Wt(t,e)?vt("summary","summary_column_value"):Qy(t)?vt("has_lookahead_tasks","cant_edit_actvity_with_task"):ct()},parseInput(t){let e=parseFloat(String(t));return Number.isNaN(e)?ut("not_a_number"):rt(e)},validate(t,e,n){return B_(n)?Ht("out_of_range"):gt()},transform(t,e,n){let r=ue(e),i=t.progress!==e&&r,a=j_(e),o=K_(t,e,n.hierarchy),s={progress:e,autoScheduling:r,...mi(o.get(t.id)??0)},l=a?V_(t,e,r,n.hierarchy,o):[],c=a?G_(t,e,n.hierarchy):[],d=l.length+c.length>0?[...l,...c]:void 0,u=[],p=a?$_(t,e):void 0;return It(s,{autoSchedule:i,postProcessors:u,cascadeMutations:d,trackingEvents:p})},trackEvent:Yt.PROGRESS_ENTRY};function B_(t){return t<U_||t>H_}function j_(t){return t===ss||ue(t)}function V_(t,e,n,r,i){return r.getDescendantIds(t.id).map(o=>({activityId:o,fields:W_(e,n,i.get(o)??0)}))}function W_(t,e,n){return{progress:t,autoScheduling:e,...mi(n)}}function K_(t,e,n){let r=new Map,i=o=>{let s=0;for(let l of n.getChildHhInfo(o)){let c=n.hasChildren(l.id)?i(l.id):ye(l.workHours,e);r.set(l.id,c),s+=c}return s},a=n.hasChildren(t.id)?i(t.id):ye(t.workHours,e);return r.set(t.id,a),r}function Y_(t,e){let n=[t.id,...e.getDescendantIds(t.id)],r=a=>e.getChildProgressInfo(a).some(o=>e.hasChildren(o.id)),i=a=>e.getAncestorIds(a).length;return n.filter(a=>r(String(a))).map(String).sort((a,o)=>i(o)-i(a))}function G_(t,e,n){let r=new Map;r.set(t.id,e);for(let o of n.getDescendantIds(t.id))r.set(o,e);let i=[...Y_(t,n),...n.getAncestorIds(t.id)],a=[];for(let o of i){let s=q_(o,r,n);s!==null&&(r.set(o,s),a.push({activityId:o,fields:{progress:s}}))}return a}function q_(t,e,n){let r=n.getChildProgressInfo(t).map(a=>({progress:e.has(a.id)?e.get(a.id):a.progress,ponderator:a.ponderator??0})),i=pi(r);return i===null?null:Number(i.toFixed(2))}function $_(t,e){return[{name:Yt.PROGRESS_UPDATE_RADIO_BUTTON,properties:{activity_id:t.id,activity_name:t.name,progress_updated:e}}]}var ff={targetField:"cost",canEdit(t,e){return Wt(t,e)?vt("summary","summary_column_value"):ct()},parseInput(t){if(String(t).trim()==="")return rt(0);let e=parseFloat(String(t));return Number.isFinite(e)?rt(e):ut("not_a_number")},validate(){return gt()},transform(t,e,n){let r=z_(t,e,n.hierarchy);return It({cost:e},{autoSchedule:!1,postProcessors:[],cascadeMutations:r})},trackEvent:Yt.COST_BUDGETED_ENTRY};function z_(t,e,n){let r=new Map;r.set(t.id,e);let i=[];for(let a of n.getAncestorIds(t.id)){let o=0;for(let s of n.getChildCostInfo(a))o+=r.has(s.id)?r.get(s.id):s.cost;r.set(a,o),i.push({activityId:a,fields:{cost:o}})}return i}var hf={targetField:"usedCost",canEdit(t,e){return Wt(t,e)?vt("summary","summary_column_value"):ct()},parseInput(t){if(String(t).trim()==="")return rt(0);let e=parseFloat(String(t));return Number.isFinite(e)?rt(e):ut("not_a_number")},validate(){return gt()},transform(t,e,n){let r=J_(t,e,n.hierarchy);return It({usedCost:e},{autoSchedule:!1,postProcessors:[],cascadeMutations:r})},trackEvent:Yt.COST_SPENT_ENTRY};function J_(t,e,n){let r=new Map;r.set(t.id,e);let i=[];for(let a of n.getAncestorIds(t.id)){let o=0;for(let s of n.getChildUsedCostInfo(a))o+=r.has(s.id)?r.get(s.id):s.usedCost;r.set(a,o),i.push({activityId:a,fields:{usedCost:o}})}return i}var mf={targetField:"workHours",canEdit(t,e){return Wt(t,e)?vt("summary","summary_column_value"):ct()},parseInput(t){if(String(t).trim()==="")return rt(0,t);let e=parseFloat(String(t));return Number.isFinite(e)?rt(e):ut("not_a_number")},validate(){return gt()},transform(t,e,n,r){let i=gf(e,t.progress),a=String(r).trim()===""?[]:X_(t,e,i,n.hierarchy);return It({workHours:e,...mi(i)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:Yt.LABOR_HOURS_BUDGETED_ENTRY};function gf(t,e){return ye(t,e)}function X_(t,e,n,r){let i=new Map,a=new Map;i.set(t.id,e),a.set(t.id,n);let o=[];for(let s of r.getAncestorIds(t.id)){let l=0,c=0;for(let d of r.getChildHhInfo(s)){let u=i.has(d.id)?i.get(d.id):d.workHours,p=a.has(d.id)?a.get(d.id):d.realWorkHours??gf(d.workHours,d.progress);l+=u,c+=p}i.set(s,l),a.set(s,c),o.push({activityId:s,fields:{workHours:l,...mi(c)}})}return o}var ds=t=>({durationHours:t});var Z_="sir-apply",Af={targetField:"startDate",canEdit(t,e,n){return Wt(t,e)?vt("summary","summary_column_value"):Zy(t)?n?.eventSource!==Z_?vt("has_progress","cant_edit_activity_with_progress"):Nn(n.newValue)?On(t.startDate,n.newValue)?ct():Hn(t)?vt("completed","cant_edit_completed_activity"):ct():ct():ct()},parseInput(t,e,n){return Nn(t)?rt(Bn(t,"UTC")):ut("invalid_date")},validate(t,e,n,r){if(On(e,n))return Ht("unchanged");let i=Q_(t,n,r);return i||gt()},transform(t,e,n){let r=n.calendars.getCalendar(t.calendarId);if(!r)throw new Error("startDatePipeline: no calendar resolved (integrity)");let i=_a(r,e),a=t.type===U.MILESTONE,o=a?i:r.calculateEndDate(i,t.durationHours),s=i;return{...It({startDate:i,...yi(o),...a?ds(0):{},...Vn(),...Ar(s)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:tE(t,i,r)}},trackEvent:Yt.START_DATE_ENTRY};function Q_(t,e,n){let r=n.hierarchy.getParentStartDateIfHasPredecessors(t.id);if(!r)return null;let i=Bn(r,"UTC");return e.getTime()<i.getTime()?Ht("before_parent_start"):null}function tE(t,e,n){let r=n.calculateEndDate(e,t.durationHours),i=lr(xe(t),e,r),a=fi(xe(t),t.constraintDate,i);if(a.violated)return hi(a.constraintType,a.constraintDate,i)}var eE=99.999,nE="sir-apply",Sf={targetField:"endDate",canEdit(t,e,n){return Wt(t,e)?vt("summary","summary_column_value"):iE(t)&&!rE(t.endDate,n)?vt("completed","cant_edit_completed_activity"):ct()},parseInput(t,e,n){if(!Nn(t))return ut("invalid_date");let r=Bn(t,"UTC"),i=n.calendars.getCalendar(e.calendarId);return i?i.isWorkTime(r,mt.DAY)?rt(Yc(i,r)):rt(i.getClosestWorkTime({direction:"past",date:r,unit:mt.HOUR})):rt(r)},validate(t,e,n,r){if(On(t.endDate,n))return Ht("unchanged");if(aE(n,t))return Ht("before_date_origin");if(oE(n,t))return Ht("before_start_date");let i=sE(n,t,r);return i||gt()},transform(t,e,n){let r=lE(t,e),i=cE(t,e,n,!!r);return{...It(i,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...r?{constraintWarning:r}:{}}},trackEvent:Yt.END_DATE_ENTRY};function rE(t,e){return e?.eventSource===nE&&Nn(e.newValue)&&On(t,e.newValue)}function iE(t){return t.progress>=eE}function aE(t,e){return e.dateOrigin?Hc(t,e.dateOrigin):!1}function oE(t,e){return Hc(t,e.startDate)}function sE(t,e,n){let r=n.calendars.getCalendar(e.calendarId);return r?r.isWorkTime(t,mt.DAY)?null:Ht("not_working_day"):null}function lE(t,e){if(xe(t)===_.MSO)return;let r=lr(xe(t),t.startDate,e),i=fi(xe(t),t.constraintDate,r);if(i.violated)return hi(i.constraintType,i.constraintDate,r)}function cE(t,e,n,r=!1){let i={};an(t.type)&&!r&&If(t)?Object.assign(i,Ar(t.startDate)):(r||If(t))&&Object.assign(i,Vn(),Ar(t.startDate));let s=dE(t,e,n),l=pa(t.durationHours,s);return l&&(i.type=l),Object.assign(i,ds(s)),i.endDate=e,i}function If(t){return jn.has(xe(t))}function dE(t,e,n){let r=n.calendars.getCalendar(t.calendarId);return r?r.calculateDuration(t.startDate,e):t.durationHours}var uE=new Set(Object.values(_)),vf={targetField:"constraintType",canEdit(t,e){return Hn(t)?vt("completed","cant_edit_completed_activity"):Wt(t,e)?vt("summary","summary_column_value"):ct()},parseInput(t){let e=String(t).toLowerCase();return pE(e)?rt(e):ut("invalid_constraint_type")},validate(){return gt()},transform(t,e,n){let r=yE(t,e,n);return It(r,{autoSchedule:!0})}};function pE(t){return uE.has(t)}function yE(t,e,n){let r=hE(t,e);return{constraintType:e,...lf(fE(t,e,r,n))}}function fE(t,e,n,r){if(t.type!==U.MILESTONE||!n||Da.has(e))return n;let i=r.calendars.getCalendar(String(t.calendarId));return i?$e(n,i,e):n}function hE(t,e){return jn.has(e)?null:Da.has(e)?t.startDate:qc.has(e)?t.endDate:t.constraintDate}var Cf={targetField:"constraintDate",canEdit(t,e){return Hn(t)?vt("completed","cant_edit_completed_activity"):Wt(t,e)?vt("summary","summary_column_value"):ct()},parseInput(t){return Nn(t)?rt(t):ut("invalid_date")},validate(){return gt()},transform(t,e,n){let r=Df(t)?ls:xe(t),i=n.calendars.getCalendar(t.calendarId);if(!i)throw new Error("constraintDatePipeline: no calendar resolved (integrity)");let a=$e(e,i,r),o=mE(t,a);return It(o,{autoSchedule:!0})}};function mE(t,e){return{constraintDate:e,...Df(t)?Vn():{}}}function Df(t){return jn.has(xe(t))||!t.constraintType}var Tf={targetField:O.CALENDAR_ID,canEdit(){return ct()},parseInput(t){if(t===null)return rt(null);let e=String(t).trim();return gE(e)?ut(df.EMPTY_CALENDAR):rt(e)},validate(t,e,n,r){let i=n===null?r.getDefaultCalendarId():n;return AE(t.calendarId,i)&&(n!==null||t.assignedDefaultCalendar)?Ht(Ir.UNCHANGED):i===null||!r.hasCalendar(i)?Ht(Ir.UNKNOWN_CALENDAR):gt()},transform(t,e,n){let r=e===null?n.getDefaultCalendarId():e;return It(IE(t,r,e===null,n),{autoSchedule:!0,postProcessors:[]})},trackEvent:Yt.CALENDAR_ASSIGNMENT};function gE(t){return t===""}function AE(t,e){return t===e}function IE(t,e,n,r){let i={calendarId:e,assignedDefaultCalendar:n},a=e===null?null:r.calendars.getCalendar(e);if(a){let o=a.isWorkTime(t.startDate,"hour"),s=a.getClosestWorkTime({date:o?_f(t.startDate):t.startDate,direction:"future",unit:"hour"});i.startDate=s;let l=SE(t,a);if(l&&(i.constraintDate=l),!t.autoScheduling)return i;Object.assign(i,yi(a.calculateEndDate(s,t.durationHours)))}return i}function SE(t,e){return!t.constraintDate||!t.constraintType?null:la({...t,constraintDate:_f(t.constraintDate)},{getClosestWorkTime:({date:n,dir:r})=>e.getClosestWorkTime({date:n,direction:r,unit:mt.HOUR})})}function _f(t){return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()))}var Ef={targetField:"customId",canEdit(t,e){return Wt(t,e)?vt("summary","summary_column_value"):ct()},parseInput(t){if(t==null)return ut("empty_custom_id");if(typeof t!="string")return ut("not_a_string");let e=t.trim();return e.length===0?ut("empty_custom_id"):e.length>20?ut("exceeds_max_length"):rt(e)},validate(){return gt()},transform(t,e){return It({customId:e},{autoSchedule:!1,postProcessors:[]})}};var Rf={targetField:"subcontractId",canEdit(){return ct()},parseInput(t){if(t==null)return rt(null);if(typeof t=="string"){let e=t.trim();if(e.length===0)return rt(null);let n=Number(e);return!Number.isFinite(n)||!Number.isInteger(n)?ut("not_an_integer"):rt(n)}return typeof t=="number"?!Number.isFinite(t)||!Number.isInteger(t)?ut("not_an_integer"):rt(t):ut("not_an_integer")},validate(){return gt()},transform(t,e){return It({subcontractId:e},{autoSchedule:!1,postProcessors:[]})}};function Ea(t){if(t==null)return null;if(typeof t=="object"){if(!("id"in t))return null;let e=t.id;return e==null?null:String(e)}return String(t)}function us(t){return t.some(e=>Ea(e)===null)}var Pf={targetField:"responsableIds",canEdit(){return ct()},parseInput(t){return t==null?rt([]):Array.isArray(t)?rt(t):ut("not_an_array")},validate(t,e,n){return us(n)?Ht("missing_id"):gt()},transform(t,e){let n=e.map(Ea).filter(r=>r!==null);return It({responsableIds:n},{autoSchedule:!1,postProcessors:[]})}};var kf={targetField:"tagIds",canEdit(){return ct()},parseInput(t){return t==null?rt([]):Array.isArray(t)?rt(t):ut("not_an_array")},validate(t,e,n){return us(n)?Ht("missing_id"):gt()},transform(t,e){let n=e.map(Ea).filter(r=>r!==null);return It({tagIds:n},{autoSchedule:!1,postProcessors:[]})}};var vr={TOTAL_FLOAT:"total_float",LONGEST_PATH:"longest_path"},Nt={DURATION:"duration",UNITS:"units",PHYSICAL:"physical"},ne={TASK:"task",LEVEL_OF_EFFORT:"level_of_effort",START_MILESTONE:"start_milestone",FINISH_MILESTONE:"finish_milestone",WBS_SUMMARY:"wbs_summary",RESOURCE_DEPENDENT:"resource_dependent"},et={NOT_STARTED:"not_started",IN_PROGRESS:"in_progress",COMPLETED:"completed"},Re={FIXED_DURATION_AND_UNITS:"fixed_duration_and_units",FIXED_DURATION_AND_UNITS_PER_TIME:"fixed_duration_and_units_per_time"};function ps(t){return t==="start_on"||t==="mandatory_start"?"mso":t==="finish_on"||t==="mandatory_finish"?"mfo":t}function ln(t){return t.remainingDurationHours!==null}var re={UNSTART:"unstart",UNCOMPLETE:"uncomplete",START_ON_PROGRESS:"start_on_progress",COMPLETE_ON_PROGRESS:"complete_on_progress",KEEP_IN_PROGRESS:"keep_in_progress",CLEAR_SECONDARY_CONSTRAINT:"clear_secondary_constraint"};function Ra(t,e){return e?.includes(t)??!1}var vE={asap:[],alap:["fnlt","snlt"],snet:["fnlt","snlt"],fnet:["fnlt","snlt"],snlt:["fnet","snet"],fnlt:["fnet","snet"],mso:[],mfo:[]};function $c(t){return t===null?[]:vE[t]}function Ai(t,e){return e===null||$c(t).includes(e)}var fe=(t,e)=>({...It({}),dataDatePatch:{[t]:e}}),ys=t=>({...It({}),dataDatePatch:t}),Pa=(t,e)=>({...ys(t),confirmation:e}),ka=t=>t.p6===void 0?vt("data_date_unavailable"):ct(),Wn=t=>({targetField:t,canEdit:ka,parseInput(e){return e===null?rt(null):!(e instanceof Date)||!Number.isFinite(e.getTime())?ut("invalid_date"):rt(e)},validate(){return gt()},transform(e,n){return fe(t,n)}}),Of=(t,e=Number.POSITIVE_INFINITY)=>({targetField:t,canEdit:ka,parseInput(n){let r=typeof n=="number"||typeof n=="string"&&n.trim()!==""?Number(n):Number.NaN;return Number.isFinite(r)?rt(r):ut("not_a_number")},validate(n,r,i){return i<0||i>e?Ht("out_of_range"):gt()},transform(n,r){return fe(t,r)}}),Nf=(t,e)=>({targetField:t,canEdit:ka,parseInput(n){return typeof n=="string"&&e.has(n)?rt(n):ut("not_a_string")},validate(){return gt()},transform(n,r){return fe(t,r)}}),CE=new Set(["not_started","in_progress","completed"]),DE=new Set(["duration","units","physical"]),TE=new Set(["snet","snlt","fnet","fnlt"]),_E=(t,e)=>{let n=t.p6?.executionStatus;return n===e||n===void 0?fe("executionStatus",e):n===et.NOT_STARTED?ys(e===et.IN_PROGRESS?{actualStart:t.startDate}:{actualStart:t.startDate,actualFinish:t.endDate}):n===et.IN_PROGRESS?e===et.COMPLETED?fe("actualFinish",t.endDate):Pa({actualStart:null},re.UNSTART):e===et.IN_PROGRESS?Pa({actualFinish:null},re.UNCOMPLETE):Pa({actualStart:null,actualFinish:null},re.UNSTART)},bf=(t,e)=>{if(e!==null||t.p6?.actualStart==null)return fe("actualStart",e);let r=t.p6?.actualFinish!=null;return Pa(r?{actualStart:null,actualFinish:null}:{actualStart:null},re.UNSTART)},Lf=(t,e)=>e!==null||t.p6?.actualFinish==null?fe("actualFinish",e):Pa({actualFinish:null},re.UNCOMPLETE),ba=(t,e)=>{let n=e.calendars.getCalendar(t.calendarId);if(!n)throw new Error("dataDatePipelines: no calendar resolved (integrity)");return n},Ff={...Wn("actualStart"),transform(t,e,n){if(e===null)return bf(t,null);let r=ba(t,n),i=t.p6?.actualStart==null;return bf(t,i?af(e,r):new Date(e))}},wf={...Wn("actualFinish"),transform(t,e,n){if(e===null)return Lf(t,null);let r=ba(t,n),i=t.p6?.actualFinish==null;return Lf(t,i?of(e,r):new Date(e))}},xf={...Wn("plannedStart"),transform(t,e,n){if(e===null)return fe("plannedStart",null);let r=ba(t,n);return fe("plannedStart",tf(e,r))}},Mf={...Wn("plannedFinish"),transform(t,e,n){if(e===null)return fe("plannedFinish",null);let r=ba(t,n);return fe("plannedFinish",ef(e,r))}},Uf=Of("remainingDurationHours"),Hf={...Nf("executionStatus",CE),transform(t,e){return _E(t,e)}},Bf=Wn("expectedFinish"),jf=Wn("suspendDate"),Vf=Wn("resumeDate"),Wf={targetField:"secondaryConstraintType",canEdit:ka,parseInput(t){return t===null||t===""?rt(null):typeof t=="string"&&TE.has(t)?rt(t):ut("not_a_string")},validate(t,e,n){return Ai(t.constraintType,n)?gt():Ht("constraint_violation")},transform(t,e){return e===null?ys({secondaryConstraintType:null,secondaryConstraintDate:null}):t.p6?.secondaryConstraintType!=null?fe("secondaryConstraintType",e):ys({secondaryConstraintType:e,secondaryConstraintDate:e.startsWith("s")?t.startDate:t.endDate})}},Kf={...Wn("secondaryConstraintDate"),canEdit(t,e){let n=ka(t,e);return n.allowed?t.p6?.secondaryConstraintType==null?vt("secondary_constraint_type_required"):ct():n},transform(t,e,n){let r=t.p6?.secondaryConstraintType??null;if(e===null||r===null)return fe("secondaryConstraintDate",e);let i=ba(t,n);return fe("secondaryConstraintDate",$e(e,i,r))}},Yf=Nf("percentCompleteType",DE),Gf=Of("physicalPercentComplete",100);var EE=new Map([[R.TEXT,Jy],[R.DESCRIPTION,Xy],[R.DURATION,pf],[R.PROGRESS,gi],[R.COST,ff],[R.USED_COST,hf],[R.HH_WORK_TIME,mf],[R.START_DATE,Af],[R.END_DATE,Sf],[R.CONSTRAINT_TYPE,vf],[R.CONSTRAINT_DATE,Cf],[R.CALENDAR_ID,Tf],[R.CUSTOM_ID,Ef],[R.SUBCONTRACT_ID,Rf],[R.RESPONSABLES,Pf],[R.TAGS,kf],[R.ACTUAL_START,Ff],[R.ACTUAL_FINISH,wf],[R.PLANNED_START,xf],[R.PLANNED_FINISH,Mf],[R.REMAINING_DURATION_HOURS,Uf],[R.EXECUTION_STATUS,Hf],[R.EXPECTED_FINISH,Bf],[R.SUSPEND_DATE,jf],[R.RESUME_DATE,Vf],[R.SECONDARY_CONSTRAINT_TYPE,Wf],[R.SECONDARY_CONSTRAINT_DATE,Kf],[R.PERCENT_COMPLETE_TYPE,Yf],[R.PHYSICAL_PERCENT_COMPLETE,Gf]]);function he(t){return EE.get(t)}var Gt={FIELD:"field",DELETED_REMOTELY:"deleted-remotely",DELETED_LOCALLY:"deleted-locally",PARENT_REMOVED:"parent-removed",BECAME_PARENT_REMOTELY:"became-parent-remotely",BECAME_PARENT_LOCALLY:"became-parent-locally",DUPLICATE_LINK:"duplicate-link",ORDER:"order",LINK_CYCLE:"link-cycle"},Kt={ACTIVITY:"activity",LINK:"link"},Mt={APPEND:"append",REPLACE:"replace"},fs={ACTION_BUTTON:"action-button"},hs={SIR_AUTO_REJECT:"sir-auto-reject"},ms={DATE_CHANGED:"date_changed",ACTIVITY_DELETED:"activity_deleted"},Cr={VIOLATION:"constraint_violation"},ce={DISPATCH_MANY:"dispatch-many",INIT:"init",UNDO:"undo",REDO:"redo",P6_SETTINGS_UPDATE:"p6-settings-update",P6_ACTIVITY_UPDATE:"p6-activity-update",P6_SCHEDULE:"p6-schedule"};function Dr(t,e){if(!e||e.type!==Io.CONSTRAINT)return null;let n=e.data;return!n?.constraintType||!n.constraintDate?null:{kind:Cr.VIOLATION,activityId:t,constraintType:n.constraintType,constraintDate:n.constraintDate,projectedDate:n.projectedDate??n.constraintDate,messageKey:e.messageKey}}var qf=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],$f=new Set(qf),OG=new Set([...qf,...Object.values($r)]),zf=new Set(Object.values($r));function Se(t,e,n,r){t.setActivityFieldDynamic(e,n,r)}function Jf(t,e,n,r){t.setLinkFieldDynamic(e,n,r)}var RE=Object.freeze([]);function me(t){return t.length===0?RE:t}function cn(t){return Xf(t,me)}function La(t){return Xf(t,PE)}function Xf(t,e){return{...t,startDate:new Date(t.startDate),endDate:new Date(t.endDate),constraintDate:ze(t.constraintDate),dateOrigin:ze(t.dateOrigin),newActivityIds:e([...t.newActivityIds]),pendingRequestIds:e([...t.pendingRequestIds]),responsableIds:e([...t.responsableIds]),tagIds:e([...t.tagIds]),baselinePoints:e(t.baselinePoints.map(n=>({...n,startDate:ze(n.startDate),endDate:ze(n.endDate)}))),baselineSnapshot:kE(t.baselineSnapshot),criticalPath:gs(t.criticalPath),...t.p6===void 0?{}:{p6:v(t.p6)}}}function PE(t){return t}function ze(t){return t===null?null:new Date(t)}function kE(t){return t===null?null:{...t,startDate:ze(t.startDate),endDate:ze(t.endDate)}}function gs(t){return t===null?null:{...t,earlyStart:ze(t.earlyStart),earlyFinish:ze(t.earlyFinish),lateStart:ze(t.lateStart),lateFinish:ze(t.lateFinish)}}var th=200;function Kn(t,e){let n=new Set([String(t)]);for(let r of e.cascadeMutations??[])n.add(String(r.activityId));return n}async function dt(t,e){let n=new Map,r=0;for(let i of e){r+=1,r%th===0&&await Ot();let a=t.getActivity(i);a&&n.set(i,st(a))}return n}function st(t){return cn(t)}function Is(t,e){let n=t.getActivity(e);return n?cn(n):null}function Yn(t,e,n){Zf(t,e,n.patch),n.dataDateState!==void 0&&t.setActivityField(e,"p6",n.dataDateState);for(let r of n.cascadeMutations??[])Zf(t,r.activityId,r.fields)}function Zf(t,e,n){for(let[r,i]of Object.entries(n)){if(!$f.has(r))throw new Error(`applyFieldChanges: column write to non-writable field "${r}"`);Se(t,e,r,i)}}async function Ss(t,e,n,r){let i=[],a=0;for(let o of n){a+=1,a%th===0&&await Ot();let s=bE(t,e,o,r);s&&i.push(s)}return i}function bE(t,e,n,r){let i=t.getActivity(n),a=e.get(n);if(!i)return{id:n,kind:W.DELETED,after:null,...a?{before:st(a)}:{}};if(!a&&r?.has(n))return LE(n,r.get(n),i);let o=wE(a,i);return OE(o,r,n,i),a&&Object.keys(o).length===0?null:{id:n,kind:a?W.UPDATED:W.CREATED,fields:o,after:st(i)}}function LE(t,e,n){return e===n.correlativeId?null:{id:t,kind:W.UPDATED,fields:{correlativeId:{before:e,after:n.correlativeId}},after:st(n)}}function OE(t,e,n,r){if(!e?.has(n)||Object.hasOwn(t,"correlativeId"))return;let i=e.get(n);i!==r.correlativeId&&(t.correlativeId={before:i,after:r.correlativeId})}var NE=new Set([O.CALENDAR_DURATION,O.BASELINE_VARIANCE_DAYS,O.PROJECT_BASELINE_VARIANCE_DAYS,O.PRIMARY_BASELINE_VARIANCE_DAYS]),FE={},As=t=>t===void 0?FE:t;function Qf(t,e,n){return!NE.has(n)&&(Object.hasOwn(t,n)!==Object.hasOwn(e,n)||!Na(t[n],e[n]))}function eh(t,e,n){let r=As(t),i=As(e);for(let a in r)if(Qf(r,i,a)&&n(a))return;for(let a in i)if(!Object.hasOwn(r,a)&&Qf(r,i,a)&&n(a))return}function nh(t,e){let n=!1;return eh(t,e,()=>(n=!0,!0)),n}function wE(t,e){let n={},r=As(t),i=As(e);return eh(t,e,a=>(n[a]={before:Oa(r[a]),after:Oa(i[a])},!1)),n}function Oa(t){return t===null||typeof t!="object"?t:t instanceof Date?new Date(t.getTime()):v(t)}function Na(t,e){if(Object.is(t,e))return!0;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(t==null||e==null)return!1;if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((o,s)=>Na(o,e[s]));if(typeof t!="object"||typeof e!="object")return!1;let n=t,r=e,i=Object.keys(n),a=Object.keys(r);return i.length!==a.length?!1:i.every(o=>Object.hasOwn(r,o)&&Na(n[o],r[o]))}function vs(t,e,n){let r=new Set;r.add(t);for(let i of e)r.add(i);for(let i of n)r.add(i);return r}function zc(t,e){let n=new Set;for(let r of t)n.add(String(r));for(let r of e)n.add(r);return n}var Ii=new Set;function ge(t,e,n,r,i){let a=new Map,o=t.peekWriteCapture()?.dirty;for(let s of e){if(n.has(s.activityId)||(i.add(s.activityId),r.has(s.activityId)))continue;let l=t.getActivity(s.activityId);if(!l)continue;if(s.before!==void 0&&!o?.has(s.activityId)){a.set(s.activityId,s.before);continue}let d=st(l);s.before!==void 0&&(d.correlativeId=s.before),r.set(s.activityId,d)}return a}var ih=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function dn(t){if(t==null||t==="")throw new Error(`[parseFromBackend] expected a date string, got "${t}"`);if(t.includes("T")||t.endsWith("Z")){let s=new Date(t);if(Number.isNaN(s.getTime()))throw new Error(`[parseFromBackend] invalid ISO date "${t}"`);return s}let e=t.match(ih);if(!e)throw new Error(`[parseFromBackend] unsupported date format "${t}" (expected "YYYY/MM/DD H:MM" or ISO)`);let[,n,r,i,a,o]=e;return new Date(Date.UTC(Number(n),Number(r)-1,Number(i),Number(a),Number(o)))}function rh(t){if(t instanceof Date)return Number.isNaN(t.getTime())?null:t.toISOString().slice(0,10);if(typeof t!="string"||t==="")return null;let e=t.match(ih);if(e){let[,r,i="",a=""]=e;return`${r}-${i.padStart(2,"0")}-${a.padStart(2,"0")}`}if(!t.includes("T")&&!t.endsWith("Z"))return null;let n=new Date(t);return Number.isNaN(n.getTime())?null:n.toISOString().slice(0,10)}function Si(t,e){let n=rh(t);if(n===null)return!1;let r=rh(e);return r!==null&&r!==n}function vi(t,e,n,r){if(t.getTime()>n.getTime())return 0;if(e.getTime()<n.getTime()||t.getTime()===e.getTime())return 100;let i=r.calculateDuration(t,n),a=r.calculateDuration(t,e);return a===0?0:i*100/a}var Xc=t=>t.type===U.PROJECT,oh=(t,e,n)=>{let r=t.calendarId,i=r!=null?n.calendarReader.getCalendar(String(r)):null;if(!i)return 0;let a=o=>o instanceof Date?o:dn(String(o));return vi(a(t.startDate),a(t.endDate),e,i)},ah=new WeakMap,xE={patchesHierarchy:!0,ignoresLinks:!0,patchesLinkAppends:!1,patchesLinkRemovals:!1},ME=new Set(["startDate","endDate","calendarId","ponderator","expectedProgress"]);function Jc(t,e,n){let r=t.getActivity(e);r&&r.expectedProgress!==n&&t.setActivityField(e,"expectedProgress",n)}function UE(t,e,n){let r={reachable:new Set,descendable:new Set},i=a=>{let o=n.getActivity(a);if(!o)return 0;if(r.reachable.add(String(a)),!Xc(o)){let c=oh(o,e,n);return Jc(n,a,c),c}r.descendable.add(String(a));let s=0;for(let c of n.getChildren(a)){let d=i(c),u=n.getActivity(c),p=typeof u?.ponderator=="number"?u.ponderator:0;s+=d*p}let l=s/100;return Jc(n,a,l),l};for(let a of t)i(a);return r}function HE(t,e,n){if(!Xc(t))return oh(t,e,n);let r=0;for(let i of n.getChildren(t.id)){let a=n.getActivity(i),o=typeof a?.ponderator=="number"?a.ponderator:0;r+=(a?.expectedProgress??0)*o}return r/100}function BE(t,e){return t.parentId===null||e.descendable.has(String(t.parentId))}function jE(t,e,n){let r=[],i=[...t];for(let a=i.pop();a!==void 0;){let o=n.getActivity(a),s=o!==null&&BE(o,e),l=s&&o!==null&&Xc(o),c=e.reachable.has(a),d=e.descendable.has(a);if(s&&!c&&r.push(a),s?e.reachable.add(a):e.reachable.delete(a),l?e.descendable.add(a):e.descendable.delete(a),s!==c||l!==d)for(let p of n.getChildren(a))i.push(String(p));a=i.pop()}return r}function VE(t,e){let n=[];for(let r=t;r!==null;r=e.getParentId(r))n.push(String(r));return n.reverse()}function WE(t,e,n){let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];)r+=1;if(r===t.length)return 1;if(r===e.length)return-1;let i=n(r===0?null:t[r-1]??null);return i.indexOf(t[r]??"")-i.indexOf(e[r]??"")}function KE(t,e){let n=null,r=i=>i!==null?e.getChildren(i).map(String):(n??=sh(e),n);return[...t].map(i=>VE(i,e)).sort((i,a)=>WE(i,a,r)).map(i=>i[i.length-1]??"")}function sh(t){let e=[];return t.forEachActivity((n,r)=>{n.parentId===null&&e.push(r)}),e}function YE(t,e,n,r){let i=new Set;for(let a of t){let o=a;for(;o!==null&&e.has(o)&&!i.has(o);)i.add(o),o=r.getParentId(o)}for(let a of KE(i,r)){let o=r.getActivity(a);o&&Jc(r,a,HE(o,n,r))}}function GE(t){let e=ah.get(t);if(e)return e;let n={writes:t.openSchedulingWriteLog(ME,xE),nowMs:null,reachability:{reachable:new Set,descendable:new Set}};return ah.set(t,n),n}function Tr(t,e){let n=GE(t),r=n.writes.take();if(!r.structural&&n.nowMs===e.getTime()){let a=[...r.touchedIds,...r.reshapedIds,...jE(r.reshapedIds,n.reachability,t)];YE(a,n.reachability.reachable,e,t),n.writes.take();return}n.reachability=UE(sh(t),e,t),n.nowMs=e.getTime(),n.writes.take()}var qE=t=>t.type===U.PROJECT,$E=t=>jt(t),zE=(t,e,n,r)=>{let i=$E(t);if(!i)return null;let a=(i.baseCalendarId!=null?n.getBaseCalendar(`${i.baseCalendarId}-base`):null)??(r?n.getBaseCalendar(r):null);return!a||!i.startDate||!i.endDate?null:vi(i.startDate,i.endDate,e,a)};function Zc(t,e,n,r=null){let i=[],a=(s,l)=>{let c=n.getActivity(s);c&&c.expectedProgressBaseline!==l&&(n.setActivityField(s,"expectedProgressBaseline",l),i.push(s))},o=s=>{let l=n.getActivity(s);if(!l)return null;if(!qE(l)){let u=zE(l,e,n,r);return a(s,u),u}let c=0;for(let u of n.getChildrenIds(s)){let p=o(u),y=n.getActivity(u),f=typeof y?.ponderator=="number"?y.ponderator:0;c+=(p??0)*f}let d=c/100;return a(s,d),d};for(let s of t)o(s);return i}function Fa(t,e,n=null){let r={getChildrenIds:a=>t.getChildren(String(a)).map(o=>String(o)),getActivity:a=>t.getActivity(a),setActivityField:(a,o,s)=>Se(t,a,o,s),getBaseCalendar:a=>t.calendarReader.getCalendar(a)},i=[];return t.forEachActivity((a,o)=>{a.parentId===null&&i.push(o)}),Zc(i,e,r,n)}function Qc(t){let e=!1;return t.forEachActivity(n=>{jt(n)&&(e=!0)}),e}function lh(t,e,n=null){if(Qc(t))return Fa(t,e,n);let r=[];return t.forEachActivity((i,a)=>{i.expectedProgressBaseline!=null&&(Se(t,a,"expectedProgressBaseline",null),r.push(a))}),r}var td=Dn.BASELINE;function Cs(t){return t===Dn.ACTUAL?Dn.ACTUAL:td}var ch=t=>Math.round(t*100)/100;function JE(t,e){return(e===Dn.BASELINE?t.expectedProgressBaseline:t.expectedProgress)??void 0}function XE(t,e){let n=ch(t),r=ch(e);return n>99.99?se.DONE:r>n?se.OVERDUE:t>0&&n>r?se.ADVANCEMENT:t===0&&e===0?se.WAITING:t>0&&n<r?se.DOING:se.WAITING}function un(t,e){let n=[];return t.forEachActivity((r,i)=>{let a=typeof r.progress=="number"?r.progress:0,o=XE(a,JE(r,e));r.status!==o&&(Se(t,i,R.STATUS,o),n.push(i))}),n}function dh(t){let e=t?.baselinePoints;return!Array.isArray(e)||e.length===0?null:e.find(n=>n.isPrimaryVersion)??null}function uh(t){let e=t?.baselinePoints;return!Array.isArray(e)||e.length===0?null:e.find(n=>n.isProjectVersion)??null}function ph(t){let e=t?.baselinePoints;return!Array.isArray(e)||e.length===0?null:e.find(n=>n.isVisibleVersion)??null}var yh=100,ZE=t=>Math.round(t*yh)/yh;function ed(t,e,n,r){if(r<=0)return null;let i=t.endDate;if(!e||!i)return null;let a=i.getTime()>e.getTime(),o=e.getTime()>i.getTime();if(!a&&!o)return 0;let s=n.calculateDuration({startDate:a?e:i,endDate:a?i:e,task:t}),l=ZE(s/r);return l===0?0:a?l:-l}function QE(t,e,n){return ed(t,ph(t)?.endDate??null,e,n)}function _r(t,e){let n=[];return t.forEachActivity((r,i)=>{let a=QE(r,t,e);r.baselineVarianceDays!==a&&(r.baselineVarianceDays=a,n.push(String(i)))}),n}function Er(t,e){let n=[];return t.forEachActivity((r,i)=>{let a=ed(r,uh(r)?.endDate??null,t,e),o=ed(r,dh(r)?.endDate??null,t,e),s=r.projectBaselineVarianceDays!==a,l=r.primaryBaselineVarianceDays!==o;!s&&!l||(s&&(r.projectBaselineVarianceDays=a),l&&(r.primaryBaselineVarianceDays=o),n.push(String(i)))}),n}var nd=60*1e3,Ds=1440*nd,tR=60,fh=3660,eR=Ds-nd,nR="-",rR=":";function mh(t,e,n){if(t.isWorkTime({date:e,unit:n}))return e;let r=iR(e);if(n!==mt.DAY){let a=e.getTime()-r,o=hh(t,r,a);if(o!==null)return new Date(r+o)}let i=t.getWorkHours(e).length>0;for(let a=1;a<=fh;a++){let o=r-a*Ds,s=hh(t,o,Ds);if(s!==null){if(n!==mt.DAY){let l=i?Math.min(s,eR):s;return new Date(o+l)}return new Date(o+Ds)}}throw new Error(`No working day found within ${fh} days before ${e.toISOString()}`)}function iR(t){return Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())}function hh(t,e,n){let r=t.getWorkHours(new Date(e)).map(aR).filter(i=>i<=n);return r.length?Math.max(...r):null}function aR(t){let e=t.split(nR)[1]??"",[n="0",r="0"]=e.split(rR);return(Number(n)*tR+Number(r))*nd}var Ts=6e4,Ci=36e5,pn=864e5,rd=60,gh=4*365*pn,Ah=400*pn,oR=200*365*pn,sR=/^(\d{1,2}):00-(\d{1,2}):00$/,Rr={BEFORE:"before",AFTER:"after"},_s=class{constructor(e){this.source=e}source;isBuilt=!1;isUsable=!0;firstDayMs=0;lastDayMs=0;starts=new Float64Array(0);ends=new Float64Array(0);prefixMinutes=new Int32Array(1);nextWorkTime(e){return this.resolve(e,Rr.AFTER,()=>{let n=this.firstIntervalEndingAfter(e);return n>=this.starts.length?null:Math.max(this.startAt(n),e)})}workingHoursBetween(e,n){if(!this.prepare(e)||!this.prepare(n))return null;let r=this.workingMinutesBefore(n)-this.workingMinutesBefore(e),i=Math.round(Math.abs(r)/rd);return e>n?-i:i}addWorkingHours(e,n){return n===0?e:n<0?this.resolve(e,Rr.BEFORE,()=>this.stepBackWorkingHours(e,-n)):this.resolve(e,Rr.AFTER,()=>this.addPositiveWorkingHours(e,n))}addWorkingMinutes(e,n){return this.isInsideWorkInterval(e)?n<0?this.resolve(e,Rr.BEFORE,()=>this.instantAtWorkingMinute(this.workingMinutesBefore(e)+n)):this.resolve(e,Rr.AFTER,()=>this.instantEndingWorkingMinute(this.workingMinutesBefore(e)+n)):null}addPositiveWorkingHours(e,n){let r=this.firstIntervalEndingAfter(e);if(r>=this.starts.length)return null;let i=Math.max(this.startAt(r),e),a=(this.endAt(r)-i)/Ci;if(a>n)return i+n*Ci;let o=n-Math.round(a);if(o<=0)return this.endAt(r);let s=o*rd;return this.instantEndingWorkingMinute(this.prefixAt(r+1)+s)}stepBackWorkingHours(e,n){let r=Math.floor(e/Ci)*Ci,i=this.workingMinutesBefore(r)-n*rd,a=this.instantAtWorkingMinute(i);return a===null?null:e-r+a}instantEndingWorkingMinute(e){let n=this.prefixAt(this.starts.length);if(e>n)return null;let r=dR(this.prefixMinutes,e,1,this.starts.length+1)-1;return this.startAt(r)+(e-this.prefixAt(r))*Ts}instantAtWorkingMinute(e){if(e<0)return null;let n=Ih(this.prefixMinutes,e,1,this.starts.length+1)-1;return n>=this.starts.length?null:this.startAt(n)+(e-this.prefixAt(n))*Ts}workingMinutesBefore(e){let n=this.firstIntervalEndingAfter(e);if(n>=this.starts.length)return this.prefixAt(n);let r=Math.max(0,e-this.startAt(n));return this.prefixAt(n)+r/Ts}isInsideWorkInterval(e){if(!this.prepare(e))return!1;let n=this.firstIntervalEndingAfter(e);return n<this.starts.length&&this.startAt(n)<=e}startAt(e){return h(this.starts,e)}endAt(e){return h(this.ends,e)}prefixAt(e){return h(this.prefixMinutes,e)}firstIntervalEndingAfter(e){return Ih(this.ends,e,0,this.ends.length)}resolve(e,n,r){if(!this.prepare(e))return null;let i=r();for(;i===null&&this.growHorizon(n);)i=r();return i}prepare(e){if(!this.isUsable||!this.isBuilt&&!this.rebuild(e-gh,e+gh))return!1;let r=this.lastDayMs-this.firstDayMs,i=e-Ah<this.firstDayMs,a=e+Ah>this.lastDayMs;return!i&&!a?!0:this.rebuild(i?Math.min(this.firstDayMs,e-r):this.firstDayMs,a?Math.max(this.lastDayMs,e+r):this.lastDayMs)}growHorizon(e){if(!this.isUsable)return!1;let n=this.lastDayMs-this.firstDayMs;return this.rebuild(e===Rr.BEFORE?this.firstDayMs-n:this.firstDayMs,e===Rr.AFTER?this.lastDayMs+n:this.lastDayMs)}rebuild(e,n){let r=Math.floor(e/pn)*pn,i=Math.ceil(n/pn)*pn;if(i-r>oR)return!1;let a=this.collectIntervals(r,i);return a===null||a.length===0?(this.isUsable=!1,!1):(this.isBuilt=!0,this.firstDayMs=r,this.lastDayMs=i,this.starts=Float64Array.from(a,o=>o.startMs),this.ends=Float64Array.from(a,o=>o.endMs),this.prefixMinutes=cR(a.map(o=>(o.endMs-o.startMs)/Ts)),!0)}collectIntervals(e,n){let r=[];for(let i=e;i<n;i+=pn){let a=lR(this.source.getWorkHours(new Date(i)),i);if(a===null)return null;r.push(...a)}return r}};function lR(t,e){let n=[],r=e;for(let i of t){let a=sR.exec(i);if(a===null)return null;let o=e+Number(a[1])*Ci,s=e+Number(a[2])*Ci,l=o>=r&&s>o,c=s<=e+pn;if(!l||!c)return null;n.push({startMs:o,endMs:s}),r=s}return n}function cR(t){let e=new Int32Array(t.length+1);return t.forEach((n,r)=>{e[r+1]=h(e,r)+n}),e}function Ih(t,e,n,r){let i=n,a=r;for(;i<a;){let o=i+a>>>1;h(t,o)>e?a=o:i=o+1}return i}function dR(t,e,n,r){let i=n,a=r;for(;i<a;){let o=i+a>>>1;h(t,o)>=e?a=o:i=o+1}return i}var Je={MINUTE:"minute"},Sh=6e4,uR=60,vh=new WeakMap;function Ch(t){return vh.get(t)??Dh(t)}function Dh(t){return{closestWorkTimeMs:(e,n)=>t.getClosestWorkTime({date:new Date(e),direction:n,unit:mt.HOUR}).getTime(),endDateMs:(e,n)=>t.calculateEndDate(new Date(e),n).getTime(),durationHours:(e,n)=>t.calculateDuration(new Date(e),new Date(n))}}function pR(t,e){let n=Dh(e);return{closestWorkTimeMs(r,i){return i!==yt.FUTURE||!wa(r)?n.closestWorkTimeMs(r,i):t.nextWorkTime(r)??n.closestWorkTimeMs(r,i)},endDateMs(r,i){return(Number.isInteger(i)&&wa(r)?t.addWorkingHours(r,i):null)??n.endDateMs(r,i)},durationHours(r,i){return(wa(r)&&wa(i)?t.workingHoursBetween(r,i):null)??n.durationHours(r,i)}}}function Th(t,e={}){let n=e.defaultUnit??mt.HOUR,r=new WeakMap;return{getCalendar(i){let a=t.getCalendar(String(i));if(!a)return null;let o=r.get(a);if(o)return o;let s=yR(a,n);return r.set(a,s),s}}}function yR(t,e){let n=e===mt.HOUR?new _s(t):null,r={getClosestWorkTime(i){if(i.direction===yt.PAST)return mh(t,i.date,i.unit);let a=n?fR(n,i):null;return a||t.getClosestWorkTime({date:i.date,dir:i.direction,unit:i.unit})},calculateEndDate(i,a){let o=e===mt.HOUR&&!Number.isInteger(a),s=i.getUTCSeconds()*1e3+i.getUTCMilliseconds(),l=o&&s!==0&&t.isWorkTime({date:i,unit:Je.MINUTE}),c=l?new Date(i.getTime()-s):i,u=(n?hR(n,c,a):null)??(o?AR(t,c,a):t.calculateEndDate({start_date:c,duration:a,unit:e}));if(!l)return u;let p=Eh(t,u);return new Date(p.getTime()+s)},calculateDuration(i,a){let o=n?gR(n,i,a):null;return o!==null?o:t.calculateDuration({start_date:i,end_date:a,unit:e})},isWorkTime(i,a){return t.isWorkTime({date:i,unit:a})},getWorkHours(i){return t.getWorkHours(i)}};return n&&vh.set(r,pR(n,r)),r}function wa(t){return t-Math.trunc(t/Sh)*Sh===0}function Es(t){return wa(t.getTime())}function _h(t){return Math.round(Math.abs(t)*uR)}function fR(t,e){if(e.unit!==mt.HOUR||!Es(e.date))return null;let n=t.nextWorkTime(e.date.getTime());return n===null?null:new Date(n)}function hR(t,e,n){if(!Es(e))return null;let r=e.getTime(),i=Number.isInteger(n)?t.addWorkingHours(r,n):mR(t,r,n);return i===null?null:new Date(i)}function mR(t,e,n){let r=_h(n);if(!(r>0))return null;let i=n<0?-r:r;return t.addWorkingMinutes(e,i)}function gR(t,e,n){return!Es(e)||!Es(n)?null:t.workingHoursBetween(e.getTime(),n.getTime())}function AR(t,e,n){let r=_h(n);if(!(r>0&&t.isWorkTime({date:e,unit:Je.MINUTE})))return t.calculateEndDate({start_date:e,duration:n*60,unit:Je.MINUTE});let a=e,o=r,s=n<0?-1:1;for(;o>0;){let l=s<0?new Date(a.getTime()-1):a;t.isWorkTime({date:l,unit:Je.MINUTE})||(a=s<0?t.getClosestWorkTime({date:l,dir:yt.PAST,unit:Je.MINUTE}):Eh(t,a));let c=IR(t,a,Math.min(o,60),s);a=c.end,o-=c.minutes}return a}function IR(t,e,n,r){let i=t.calculateEndDate({start_date:e,duration:r*n,unit:Je.MINUTE});if(i.getTime()===e.getTime()+r*n*6e4)return{end:i,minutes:n};let o=0,s=n-1,l=e;for(;o<s;){let c=Math.ceil((o+s)/2),d=t.calculateEndDate({start_date:e,duration:r*c,unit:Je.MINUTE});d.getTime()===e.getTime()+r*c*6e4?(o=c,l=d):s=c-1}if(o===0)throw new Error("Calendar cannot calculate a working-minute prefix");return{end:l,minutes:o}}function Eh(t,e){if(t.isWorkTime({date:e,unit:Je.MINUTE}))return e;let n=t.calculateEndDate({start_date:e,duration:1,unit:mt.DAY}),r=new Date(n);r.setUTCHours(0,0,0,0);let i=t.getClosestWorkTime({date:r,dir:yt.FUTURE,unit:Je.MINUTE}),a=t.getClosestWorkTime({date:e,dir:yt.FUTURE,unit:Je.MINUTE});return new Date(Math.min(a.getTime(),i.getTime()))}var SR=864e5,Rh="-",vR=":",CR=10;function id(t){let e=new Map;return n=>{let r=e.get(n);if(r!==void 0)return r;let i=t(n);return e.set(n,i),i}}function Ph(t){let e=new Map;return(n,r)=>{let i=e.get(n);i===void 0&&(i=new Map,e.set(n,i));let a=i.get(r);if(a!==void 0)return a;let o=t(n,r);return i.set(r,o),o}}function DR(t){let e=t[0];if(!e?.includes(Rh))return null;let[n=""]=e.split(Rh),[r=""]=n.split(vR);return Number.parseInt(r,CR)}function kh(t){let e=Ch(t),n=id(s=>e.closestWorkTimeMs(s,yt.FUTURE)),r=id(s=>e.closestWorkTimeMs(s,yt.PAST)),i=Ph((s,l)=>e.endDateMs(l,s)),a=new Map,o=s=>{let l=Math.floor(s/SR),c=a.get(l);if(c!==void 0)return c;let d=DR(t.getWorkHours(new Date(s)));return a.set(l,d),d};return{nextWorkMs:n,previousWorkMs:r,addHours:(s,l)=>l===0?e.endDateMs(s,l):i(l,s),durationHours:Ph(e.durationHours),lastWorkingHourBeforeMs:id(s=>{let l=new Date(s),c=o(s),u=c!==null&&l.getUTCHours()===c?Date.UTC(l.getUTCFullYear(),l.getUTCMonth(),l.getUTCDate()):s;return r(u)})}}var V={ASAP:0,ALAP:1,SNET:2,SNLT:3,FNET:4,FNLT:5,MSO:6,MFO:7,OTHER:8},_t={FINISH_TO_START:0,START_TO_START:1,FINISH_TO_FINISH:2,START_TO_FINISH:3,OTHER:4},TR=new Map([[_.ASAP,V.ASAP],[_.ALAP,V.ALAP],[_.SNET,V.SNET],[_.SNLT,V.SNLT],[_.FNET,V.FNET],[_.FNLT,V.FNLT],[_.MSO,V.MSO],[_.MFO,V.MFO]]),_R=new Map([[0,_t.FINISH_TO_START],[1,_t.START_TO_START],[2,_t.FINISH_TO_FINISH],[3,_t.START_TO_FINISH]]),ER=t=>t===_.FNET||t===_.FNLT||t===_.MFO,RR=t=>new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()));function PR(t,e){let n=t.constraintDate;if(!n||!ER(t.constraintType))return n;let r=RR(n);if(n.getTime()!==r.getTime())return n;let i=e.getClosestWorkTime({date:r,dir:yt.FUTURE,task:t});return i.getUTCFullYear()===n.getUTCFullYear()&&i.getUTCMonth()===n.getUTCMonth()&&i.getUTCDate()===n.getUTCDate()?la(t,e):n}function kR(t){return TR.get(t??_.ASAP)??V.OTHER}function bR(t){return _R.get(Number(t))??_t.OTHER}function LR(t){let e=new Map;return n=>{let r=String(n.calendarId),i=e.get(r);if(i)return i;let a=t.getCalendar(r);if(!a)throw new Error(`critical path calendar ${r} is not registered`);let o=kh(a);return e.set(r,o),o}}function bh(t,e,n){let r=e.activityCount,i=new Float64Array(r),a=new Float64Array(r),o=new Float64Array(r),s=new Float64Array(r),l=new Uint8Array(r),c=new Float64Array(r),d=new Uint8Array(r),u=new Uint8Array(r),p=[],y=LR(t.calendarReader),f=0;return t.forEachActivity(m=>{let A=f;f+=1,i[A]=m.startDate.getTime(),a[A]=m.endDate.getTime(),o[A]=m.durationHours,s[A]=m.progress,l[A]=kR(m.constraintType),u[A]=m.type===U.MILESTONE?1:0;let g=PR(m,t);g&&(d[A]=1,c[A]=g.getTime()),p.push(y(m))}),{startMs:i,endMs:a,durationHours:o,progress:s,constraint:l,constraintMs:c,hasConstraintDate:d,isMilestone:u,calendarOf:p,...OR(n),projectEndMs:NR(a)}}function OR(t){let e=new Uint8Array(t.length),n=new Float64Array(t.length);return t.forEach((r,i)=>{e[i]=bR(r.type),n[i]=r.lag??0}),{linkType:e,linkLagHours:n}}function NR(t){let e=t.length===0?0:h(t,0);for(let n of t)e=Math.max(e,n);return e}var pt=-1,Di=t=>2*t,sd=t=>2*t+1,Pr=t=>t>>1,kr=t=>(t&1)===1;function Fh(t,e){return h(t,e+1)>h(t,e)}function Pe(t,e){return Fh(t.childStart,e)}function FR(t){let e=[],n=[],r=new Map;return t.forEachActivity((i,a)=>{r.set(String(a),e.length),e.push(String(a)),n.push(i.parentId)}),{activityIds:e,parentIds:n,indexOfActivity:r}}function Rs(t,e){let n=new Int32Array(e+1);for(let a of t)a!==pt&&(n[a+1]=h(n,a+1)+1);for(let a=0;a<e;a+=1)n[a+1]=h(n,a+1)+h(n,a);let r=new Int32Array(h(n,e)),i=n.slice(0,e);return t.forEach((a,o)=>{a!==pt&&(r[h(i,a)]=o,i[a]=h(i,a)+1)}),{start:n,list:r}}function wh(t,e,n,r){let i=h(e.start,n);if(t.length!==h(e.start,n+1)-i)return!1;for(let a=0;a<t.length;a+=1){let o=h(e.list,i+a);if(t[a]!==r[o])return!1}return!0}function wR(t,e,n){let r=t.map(o=>[...e(o)]),i=new Int32Array(t.length+1),a=[];return r.forEach((o,s)=>{for(let l of o){let c=n.get(String(l));c!==void 0&&a.push(c)}i[s+1]=a.length}),{recordedIds:r,start:i,list:Int32Array.from(a)}}function Lh(t,e,n,r,i){let a=Rs(n,t.length);return t.every((s,l)=>wh(e(s),a,l,r))?{...a,recordedIds:null}:wR(t,e,i())}function xR(t,e,n){let r=t.activityIds.length,i=new Uint8Array(r),a=[],o=c=>{i[c]=1,Fh(e,c)?a.push(Di(c),sd(c)):a.push(Di(c))},s=[],l=c=>{let d=h(e,c);for(let u=h(e,c+1)-1;u>=d;u-=1)s.push(h(n,u))};for(let c=r-1;c>=0;c-=1)t.parentIds[c]===null&&s.push(c);for(let c=s.pop();c!==void 0;c=s.pop())i[c]!==1&&(o(c),l(c));for(let c=0;c<r;c+=1)i[c]===0&&o(c);return Int32Array.from(a)}function MR(t){return xh(FR(t))}function xh(t){let{activityIds:e,parentIds:n,indexOfActivity:r}=t,i=e.length,a=new Int32Array(i),o=new Uint8Array(i);n.forEach((l,c)=>{o[c]=(l??null)===null?1:0,a[c]=l===null?pt:r.get(String(l))??pt});let s=Rs(a,i);return{activityCount:i,activityIds:e,parentIds:n,indexOfActivity:r,parentIndex:a,isTopLevel:o,childStart:s.start,childList:s.list,treeKeys:xR(t,s.start,s.list)}}function Mh(t,e,n){return e!==void 0&&String(e.id)===t.linkIds[n]&&e.source===t.linkSourceIds[n]&&e.target===t.linkTargetIds[n]}function Uh(t,e){let n=Math.min(e.length,t.linkCount),r=0;for(;r<n&&Mh(t,e[r],r);)r+=1;return r}function UR(t,e,n){let r=Math.min(e.length,t.linkCount)-n,i=0;for(;i<r&&Mh(t,e[e.length-1-i],t.linkCount-1-i);)i+=1;return i}function Oh(t,e,n,r,i){let a=new Int32Array(e.length),o=i===null?0:Uh(i,e),s=i===null?0:UR(i,e,o),l=e.length-s,c=(i?.linkCount??0)-e.length;return e.forEach((d,u)=>{let p=u<o||u>=l;a[u]=p&&r!==null?h(r,u<o?u:u+c):t.indexOfActivity.get(String(n(d)))??pt}),a}function Hh(t,e,n,r){let{activityIds:i}=t,a=n.map(u=>String(u.id)),o=Oh(t,n,u=>u.source,r?.linkSource??null,r),s=Oh(t,n,u=>u.target,r?.linkTarget??null,r),l=()=>new Map(a.map((u,p)=>[u,p])),c=Lh(i,u=>e.getIncomingLinkIds(u),s,a,l),d=Lh(i,u=>e.getOutgoingLinkIds(u),o,a,l);return{...t,linkCount:n.length,linkIds:a,linkSourceIds:n.map(u=>u.source),linkTargetIds:n.map(u=>u.target),linkSource:o,linkTarget:s,recordedIncomingIds:c.recordedIds,recordedOutgoingIds:d.recordedIds,incomingStart:c.start,incomingList:c.list,outgoingStart:d.start,outgoingList:d.list}}function HR(t,e){return Hh(MR(t),t,e,null)}var ad=new WeakMap,BR={patchesHierarchy:!0,ignoresLinks:!1,patchesLinkAppends:!0,patchesLinkRemovals:!0};function jR(t,e){if(e.length<t.activityCount)return!1;for(let n=0;n<t.activityCount;n+=1)if(e[n]!==t.activityIds[n])return!1;return!0}function VR(t,e){if(e.length===t.activityCount)return new Map(t.indexOfActivity);let n=new Map(t.indexOfActivity);for(let r=t.activityCount;r<e.length;r+=1)n.set(e[r],r);return n}function WR(t,e){let n=[],r=[];e.forEachActivity((s,l)=>{n.push(String(l)),r.push(s.parentId)});let i=jR(t,n),a=i?VR(t,n):new Map(n.map((s,l)=>[s,l])),o=i?null:Int32Array.from(t.activityIds,s=>a.get(s)??pt);return{activityIds:n,parentIds:r,indexOfActivity:a,nextIndex:o}}function KR(t,e){for(let n=0;n<t.linkCount;n+=1){let r=h(t.linkSource,n)===pt&&e.has(t.linkSourceIds[n]),i=h(t.linkTarget,n)===pt&&e.has(t.linkTargetIds[n]);if(r||i)return!0}return!1}var od=class{linkIds=[];linkSourceIds=[];linkTargetIds=[];linkSource=[];linkTarget=[];push(e,n,r,i,a){this.linkIds.push(e),this.linkSourceIds.push(n),this.linkTargetIds.push(r),this.linkSource.push(i),this.linkTarget.push(a)}build(){return{linkCount:this.linkIds.length,linkIds:this.linkIds,linkSourceIds:this.linkSourceIds,linkTargetIds:this.linkTargetIds,linkSource:Int32Array.from(this.linkSource),linkTarget:Int32Array.from(this.linkTarget)}}},Ps=(t,e)=>t===pt||e===null?t:h(e,t);function YR(t,e,n){let r=new Set(e),i=new od;return t.linkIds.forEach((a,o)=>{r.has(a)||i.push(a,t.linkSourceIds[o],t.linkTargetIds[o],Ps(h(t.linkSource,o),n),Ps(h(t.linkTarget,o),n))}),i}function GR(t,e){return{linkCount:t.linkCount,linkIds:t.linkIds,linkSourceIds:t.linkSourceIds,linkTargetIds:t.linkTargetIds,linkSource:e===null?t.linkSource:t.linkSource.map(n=>Ps(n,e)),linkTarget:e===null?t.linkTarget:t.linkTarget.map(n=>Ps(n,e))}}function qR(t,e,n,r,i){if(n.removedLinkIds.length===0&&n.appendedLinkIds.length===0&&e.length===t.linkCount)return GR(t,i);let o=YR(t,n.removedLinkIds,i),s=o.linkIds.length,l=n.appendedLinkIds;if(s+l.length!==e.length)return null;for(let c=0;c<s;c+=1)if(String(e[c]?.id)!==o.linkIds[c])return null;for(let c=s;c<e.length;c+=1){let d=e[c];if(String(d.id)!==l[c-s])return null;o.push(String(d.id),d.source,d.target,r.get(String(d.source))??pt,r.get(String(d.target))??pt)}return o.build()}function $R(t,e,n,r){if(!(t.recordedIncomingIds===null&&t.recordedOutgoingIds===null))return null;let a=r.reshapedIds.size>0?WR(t,e):null,o=a?.indexOfActivity??t.indexOfActivity;if(a!==null&&KR(t,o))return null;let s=qR(t,n,r,o,a?.nextIndex??null);if(s===null)return null;let l=a===null?t:xh(a),c=Rs(s.linkTarget,l.activityCount),d=Rs(s.linkSource,l.activityCount);return{activityCount:l.activityCount,activityIds:l.activityIds,parentIds:l.parentIds,indexOfActivity:l.indexOfActivity,parentIndex:l.parentIndex,isTopLevel:l.isTopLevel,childStart:l.childStart,childList:l.childList,treeKeys:l.treeKeys,...s,recordedIncomingIds:null,recordedOutgoingIds:null,incomingStart:c.start,incomingList:c.list,outgoingStart:d.start,outgoingList:d.list}}var zR=new Set;function JR(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n]!==e[n])return!1;return!0}function XR(t,e){return e.length===t.linkCount&&Uh(t,e)===e.length}function ZR(t,e){let n=0,r=!0;return e.forEachActivity((i,a)=>{r=r&&n<t.activityCount&&t.activityIds[n]===String(a)&&t.parentIds[n]===i.parentId,n+=1}),r&&n===t.activityCount}function Nh(t,e,n,r,i){return n===null?wh(e,r,i,t.linkIds):JR(e,n[i]??[])}function QR(t,e){let n={start:t.incomingStart,list:t.incomingList},r={start:t.outgoingStart,list:t.outgoingList};return t.activityIds.every((i,a)=>Nh(t,e.getIncomingLinkIds(i),t.recordedIncomingIds,n,a)&&Nh(t,e.getOutgoingLinkIds(i),t.recordedOutgoingIds,r,a))}function Bh(t,e){let n=ad.get(t)??null,r=n?.writes??t.openSchedulingWriteLog(zR,BR),i=r.take(),a=n!==null&&!i.structural,o=n?.graph??null,s=a&&o!==null;if(s&&i.reshapedIds.size===0&&i.appendedLinkIds.length===0&&i.removedLinkIds.length===0&&e.length===o.linkCount)return o;let c=s?$R(o,t,e,i):null;if(c!==null)return ad.set(t,{graph:c,writes:r}),c;let d=o!==null&&ZR(o,t);if(d&&XR(o,e)&&QR(o,t))return o;let p=d?Hh(o,t,e,o):HR(t,e);return ad.set(t,{graph:p,writes:r}),p}var tP=100,Os=(t,e)=>{if(!(typeof t=="number"&&Number.isFinite(t)&&Number.isFinite(e)&&e>0))return null;let r=t*e;return Number.isFinite(r)?Object.is(r,-0)?0:r:null},eP=t=>typeof t!="number"||!Number.isFinite(t)?null:Object.is(t,-0)?0:t,nP=(t,e)=>typeof t!="number"||t<0?null:Os(t,e);function jh(t){let e=nP(t.freeFloatDays,t.hoursPerDay),n=eP(t.residualHours);return{freeSlackHours:e,isCritical:n!==null&&n<=0&&t.sourceIsCritical&&t.targetIsCritical&&t.targetProgress===0}}var ld=t=>t??Number.NaN,ks=t=>Number.isFinite(t)?t:Number.NaN,Ti=t=>Number.isNaN(t)?null:t;function rP(t,e){let n=new Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=String(t.activityIds[h(e,r)]);return n}function Vh(t,e){let{graph:n,inputs:r,forward:i,backward:a,floats:o}=t,s=i.calculationOrder,l=s.length,c={activityIds:rP(n,s),activityRows:Int32Array.from(s),earlyStartMs:new Float64Array(l),earlyFinishMs:new Float64Array(l),lateStartMs:new Float64Array(l),lateFinishMs:new Float64Array(l),totalSlackHours:new Float64Array(l),freeSlackHours:new Float64Array(l),isCritical:new Uint8Array(l),linkIds:n.linkIds,linkFreeSlackHours:new Float64Array(n.linkCount),linkIsCritical:new Uint8Array(n.linkCount)},d=new Uint8Array(n.activityCount);s.forEach((u,p)=>{let y=h(a.hasLate,u)===1,f=Os(h(o.totalFloatDays,u),e),m=h(r.progress,u)<tP&&f!==null&&f<=0;m&&(d[u]=1),c.earlyStartMs[p]=ks(h(i.earlyStartMs,u)),c.earlyFinishMs[p]=ks(h(i.earlyFinishMs,u)),c.lateStartMs[p]=y?ks(h(a.lateStartMs,u)):Number.NaN,c.lateFinishMs[p]=y?ks(h(a.lateFinishMs,u)):Number.NaN,c.totalSlackHours[p]=ld(f),c.freeSlackHours[p]=ld(Os(h(o.freeFloatDays,u),e)),c.isCritical[p]=m?1:0});for(let u=0;u<n.linkCount;u+=1){let p=h(n.linkSource,u),y=h(n.linkTarget,u),f=h(o.hasLinkFreeFloat,u)===1,m=jh({freeFloatDays:f?h(o.linkFreeFloatDays,u):void 0,residualHours:h(o.linkResidualHours,u),hoursPerDay:e,sourceIsCritical:p!==pt&&h(d,p)===1,targetIsCritical:y!==pt&&h(d,y)===1,targetProgress:y===pt?void 0:h(r.progress,y)});c.linkFreeSlackHours[u]=ld(m.freeSlackHours),c.linkIsCritical[u]=m.isCritical?1:0}return c}function bs(t,e){if(Number.isNaN(t))return null;let n=e.get(t);return n===void 0&&(n=new Date(t),e.set(t,n)),n}function cd(t,e,n){return{criticalPath:{earlyStart:bs(h(t.earlyStartMs,e),n),earlyFinish:bs(h(t.earlyFinishMs,e),n),lateStart:bs(h(t.lateStartMs,e),n),lateFinish:bs(h(t.lateFinishMs,e),n),totalSlackHours:Ti(h(t.totalSlackHours,e))},isCritical:h(t.isCritical,e)===1,freeSlackHours:Ti(h(t.freeSlackHours,e))}}function dd(t,e){return{freeSlackHours:Ti(h(t.linkFreeSlackHours,e)),isCritical:h(t.linkIsCritical,e)===1}}var Ls=(t,e)=>Number.isNaN(e)?t===null:t!==null&&t.getTime()===e;function ud(t,e,n){let r=t.criticalPath;return!(r!=null&&Ls(r.earlyStart,h(e.earlyStartMs,n))&&Ls(r.earlyFinish,h(e.earlyFinishMs,n))&&Ls(r.lateStart,h(e.lateStartMs,n))&&Ls(r.lateFinish,h(e.lateFinishMs,n))&&Object.is(r.totalSlackHours,Ti(h(e.totalSlackHours,n)))&&Object.is(t.isCritical,h(e.isCritical,n)===1)&&Object.is(t.freeSlackHours,Ti(h(e.freeSlackHours,n))))}function pd(t,e,n){return!(Object.is(t.freeSlackHours,Ti(h(e.linkFreeSlackHours,n)))&&Object.is(t.isCritical,h(e.linkIsCritical,n)===1))}function yd(t,e,n){t.setLinkField(e,"freeSlackHours",n.freeSlackHours),t.setLinkField(e,"isCritical",n.isCritical)}function fd(t,e,n,r){let i=String(n.activityIds[r]),a=e[h(n.activityRows,r)];return a!==void 0&&String(a.id)===i?a:t.getActivity(i)}function hd(t,e,n,r){let i=String(n.linkIds[r]),a=e[r];return a!==void 0&&String(a.id)===i?a:t.getLink(i)}function Wh(t,e){let n=new Map,r=t.getAllActivities();e.activityIds.forEach((a,o)=>{let s=fd(t,r,e,o);!s||!ud(s,e,o)||t.setActivityFields(a,cd(e,o,n))});let i=t.getAllLinks();e.linkIds.forEach((a,o)=>{let s=hd(t,i,e,o);!s||!pd(s,e,o)||yd(t,a,dd(e,o))})}var zt=100;function Gh(t,e){return Pe(t,e)?sd(e):Di(e)}function Ns(t,e){return h(t.incomingStart,e+1)>h(t.incomingStart,e)}function xa(t,e){return h(t.outgoingStart,e+1)>h(t.outgoingStart,e)}function Fs(t,e,n){let r=h(e.constraint,n);return Ns(t,n)||r===V.FNLT||r===V.SNET}function ws(t,e,n){return xa(t,n)||h(e.constraint,n)===V.FNLT}function qh(t,e,n){let r=h(t.childStart,e+1);for(let i=h(t.childStart,e);i<r;i+=1)n(Gh(t,h(t.childList,i)))}function gd(t,e,n,r){let i=n?t.incomingStart:t.outgoingStart,a=n?t.incomingList:t.outgoingList,o=n?t.linkSource:t.linkTarget,s=h(i,e+1);for(let l=h(i,e);l<s;l+=1){let c=h(o,h(a,l));c!==pt&&r(Gh(t,c))}}function iP(t,e){return(n,r)=>{let i=Pr(n);if(h(e.progress,i)===zt)return;if(kr(n)){qh(t,i,r);return}if(gd(t,i,!0,r),Pe(t,i))return;let a=h(t.parentIndex,i);a!==pt&&Ns(t,i)&&Fs(t,e,a)&&r(Di(a))}}function aP(t,e){return(n,r)=>{let i=Pr(n),a=h(e.progress,i)===zt,o=Pe(t,i);if(o&&a)return;if(kr(n)){qh(t,i,r);return}if(o){gd(t,i,!1,r);return}if(a&&xa(t,i))return;gd(t,i,!1,r);let s=h(t.parentIndex,i);s!==pt&&ws(t,e,s)&&r(Di(s))}}function Kh(t,e,n){let r=new Int32Array(e),i=new Int32Array(e+1),a=[],o=[];for(let u of t)n(u,p=>{r[u]=h(r,u)+1,i[p+1]=h(i,p+1)+1,a.push(p),o.push(u)});for(let u=0;u<e;u+=1)i[u+1]=h(i,u+1)+h(i,u);let s=new Int32Array(h(i,e)),l=i.slice(0,e);a.forEach((u,p)=>{s[h(l,u)]=h(o,p),l[u]=h(l,u)+1});let c=new Int32Array(t.length),d=0;for(let u of t)h(r,u)===0&&(c[d++]=u);for(let u=0;u<d;u+=1){let p=h(c,u),y=h(i,p+1);for(let f=h(i,p);f<y;f+=1){let m=h(s,f),A=h(r,m)-1;r[m]=A,A===0&&(c[d++]=m)}}return c.subarray(0,d)}var md={DONE:1,FNLT:2,SNET:4},Yh=new WeakMap;function oP(t,e){let n=new Uint8Array(e.progress.length);return e.progress.forEach((r,i)=>{let a=r===zt,o=Pe(t,i),s=h(e.constraint,i),l=o&&s===V.FNLT,c=o&&s===V.SNET;n[i]=(a?md.DONE:0)|(l?md.FNLT:0)|(c?md.SNET:0)}),n}function sP(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n]!==e[n])return!1;return!0}function lP(t,e){let n=2*t.activityCount;return{forward:Kh(t.treeKeys,n,iP(t,e)),backward:Kh(t.treeKeys,n,aP(t,e))}}function $h(t,e){let n=oP(t,e),r=Yh.get(t);if(r&&sP(r.dependencyMask,n))return r;let i={...lP(t,e),dependencyMask:n};return Yh.set(t,i),i}var Ma=4e3,cP=t=>t<=V.FNLT,zh=t=>t>=V.SNET&&t<=V.FNLT,xs=t=>t===V.MSO||t===V.MFO,dP=t=>t===V.SNET||t===V.SNLT||t===V.MSO,uP=t=>t===V.FNET||t===V.FNLT||t===V.MFO;function Ad(t,e){let n=h(t.constraint,e),r=dP(n);if(!r&&!uP(n))return null;let i=h(t.constraintMs,e);if(Number.isNaN(i))throw new Error("Invalid date argument for calculateEndDate method");let a=Ue(t,e),o=h(t.durationHours,e);return r?{startMs:i,finishMs:a.addHours(i,o)}:{startMs:a.addHours(i,-o),finishMs:i}}function Ue(t,e){let n=t.calendarOf[e];if(n===void 0)throw new RangeError("missing activity calendar");return n}async function Jh(t,e,n,r){let i=t.activityCount,a=t.linkCount,{startMs:o,endMs:s,durationHours:l,progress:c,constraint:d}=e,u={hasEarly:new Uint8Array(i),earlyStartMs:new Float64Array(i),earlyFinishMs:new Float64Array(i),earlyFinishIsNumber:new Uint8Array(i),calculationOrder:new Int32Array(i),hasLinkCandidate:new Uint8Array(a),linkCandidateFinishMs:new Float64Array(a),linkCandidateTarget:new Int32Array(a).fill(pt),hasRestriction:new Uint8Array(i),restrictionStartMs:new Float64Array(i),restrictionFinishMs:new Float64Array(i),linkedStartMs:new Float64Array(i),linkedFinishMs:new Float64Array(i)},p=0,y=new Uint8Array(i),f=new Float64Array(i),m=new Float64Array(i),A={startMs:0,finishMs:0},g={isSet:!1,startMs:0,finishMs:0},P=()=>{g.isSet=!1,g.startMs=0,g.finishMs=0},L=(N,K)=>{g.isSet&&!(K>g.finishMs)||(g.isSet=!0,g.startMs=N,g.finishMs=K)},F=(N,K,it,D)=>{u.hasEarly[N]=1,u.earlyStartMs[N]=K,u.earlyFinishMs[N]=it,u.earlyFinishIsNumber[N]=D?1:0,u.calculationOrder[p]=N,p+=1},T=(N,K,it)=>{u.hasLinkCandidate[N]=1,u.linkCandidateFinishMs[N]=it,u.linkCandidateTarget[N]=K},x=(N,K,it,D)=>{let b=h(e.linkLagHours,it),M=h(e.linkType,it),H=h(u.earlyStartMs,D),z=h(u.earlyFinishMs,D);if(M===_t.START_TO_START){let J=N.addHours(N.nextWorkMs(H),b);b>0&&(J=N.nextWorkMs(J)),A.startMs=J,A.finishMs=N.addHours(J,K);return}if(M===_t.FINISH_TO_FINISH){let J=N.addHours(N.previousWorkMs(z),b),ht=N.addHours(J,-K);b>0&&(ht=N.previousWorkMs(ht)),A.startMs=ht,A.finishMs=J;return}if(M===_t.FINISH_TO_START){let J=b===0?N.nextWorkMs(z):z,ht=N.addHours(J,b);A.startMs=ht,A.finishMs=N.addHours(ht,K);return}let Z=N.addHours(H,b);A.startMs=N.addHours(Z,-K),A.finishMs=Z},S=(N,K,it)=>{let D=h(t.incomingStart,N+1),b=h(t.incomingStart,N);for(let M=b;M<D;M+=1){let H=h(t.incomingList,M),z=h(t.linkSource,H);z===pt||h(u.hasEarly,z)===0||(x(K,it,H,z),T(H,N,A.finishMs),L(A.startMs,A.finishMs))}},k=(N,K,it)=>{if(!(h(e.hasConstraintDate,N)===1))return;let b=h(d,N),M=h(e.constraintMs,N);if(b===V.SNET){let Z=K.addHours(M,it);g.isSet&&g.finishMs>Z||(g.startMs=M,g.finishMs=Z),g.isSet=!0;return}if(b!==V.FNLT)return;let H=K.addHours(M,-it);(!g.isSet||g.finishMs>M)&&(g.startMs=H,g.finishMs=M),g.isSet=!0},E=N=>{if(h(c,N)===zt){Fs(t,e,N)&&(y[N]=1,f[N]=h(o,N),m[N]=h(s,N));return}let K=Ue(e,N),it=h(l,N);P(),S(N,K,it),k(N,K,it),g.isSet&&(y[N]=1,f[N]=g.startMs,m[N]=g.finishMs)},j=N=>{if(h(c,N)===zt){F(N,h(o,N),h(s,N),!1);return}let K=pt,it=pt,D=h(t.childStart,N+1);for(let M=h(t.childStart,N);M<D;M+=1){let H=h(t.childList,M);if(h(u.hasEarly,H)===0)continue;(K===pt||h(u.earlyStartMs,H)<h(u.earlyStartMs,K))&&(K=H),(it===pt||h(u.earlyFinishMs,H)>h(u.earlyFinishMs,it))&&(it=H)}if(K===pt)return;let b=!Fs(t,e,N);F(N,h(u.earlyStartMs,K),h(u.earlyFinishMs,it),b&&h(u.earlyFinishIsNumber,it)===1)},w=(N,K,it,D,b,M)=>{let H=h(e.linkLagHours,D),z=h(e.linkType,D),J=z===_t.FINISH_TO_START||z===_t.FINISH_TO_FINISH?M:b;if(K||(z===_t.FINISH_TO_START||z===_t.START_TO_START?J=N.nextWorkMs(J):z===_t.FINISH_TO_FINISH&&(J=N.previousWorkMs(J))),z===_t.FINISH_TO_FINISH||z===_t.START_TO_FINISH){let ee=N.addHours(J,H),wt=N.addHours(ee,-it);!K&&H>0&&z===_t.FINISH_TO_FINISH&&(wt=N.previousWorkMs(wt)),A.startMs=wt,A.finishMs=ee;return}let Ct=N.addHours(J,H);!K&&H>0&&(Ct=N.nextWorkMs(Ct)),A.startMs=Ct,A.finishMs=N.addHours(Ct,it)},B=(N,K,it)=>{let D=h(e.isMilestone,N)===1,b=h(t.incomingStart,N+1),M=h(t.incomingStart,N);for(let H=M;H<b;H+=1){let z=h(t.incomingList,H),Z=h(t.linkSource,z);if(Z===pt)continue;let J=h(d,Z)===V.ALAP&&!Pe(t,Z);if(!(J||h(u.hasEarly,Z)===1))continue;let Ct=J?o:u.earlyStartMs,ee=J?s:u.earlyFinishMs;w(K,D,it,z,h(Ct,Z),h(ee,Z)),T(z,N,A.finishMs),L(A.startMs,A.finishMs)}},$=(N,K,it)=>{let D=h(t.parentIndex,N);if(!(D!==pt&&h(y,D)===1))return;let M=h(f,D);L(M,K.addHours(M,it))},ft=(N,K,it)=>{let D=Ad(e,N);if(D===null)throw new RangeError("missing restriction");if(u.hasRestriction[N]=1,u.restrictionStartMs[N]=D.startMs,u.restrictionFinishMs[N]=D.finishMs,u.linkedStartMs[N]=g.startMs,u.linkedFinishMs[N]=g.finishMs,zh(K)){if(K===V.SNET||K===V.FNET?g.finishMs>D.finishMs:g.finishMs<D.finishMs)return;g.startMs=D.startMs,g.finishMs=D.finishMs;return}if(it===0){g.startMs=D.startMs,g.finishMs=D.finishMs;return}let b=h(s,N);g.startMs=h(o,N),g.finishMs=K===V.MFO?Math.max(D.finishMs,b):b},at=N=>{let K=h(c,N),it=!Ns(t,N)&&K<=zt;if(K===zt||it){F(N,h(o,N),h(s,N),!1);return}let D=Ue(e,N),b=h(l,N);P(),B(N,D,b),$(N,D,b);let M=h(d,N);(!g.isSet||K>0&&cP(M))&&(g.startMs=h(o,N),g.finishMs=h(s,N));let z=zh(M)||xs(M);z&&ft(N,M,K);let Z=z&&M===V.MFO&&K!==0;F(N,g.startMs,g.finishMs,Z)},St=0;for(let N of n){if(St+=1,St>=Ma&&(St=0,await Ot(),!r()))return null;let K=Pr(N);h(t.isTopLevel,K)!==1&&(kr(N)?j(K):Pe(t,K)?E(K):at(K))}return{...u,calculationOrder:u.calculationOrder.subarray(0,p)}}var Id=t=>t===V.ASAP||t===V.ALAP||t===V.SNET||t===V.FNET,Xh=t=>t===V.ASAP||t===V.ALAP;async function Zh(t,e,n,r,i){let a=t.activityCount,{startMs:o,endMs:s,durationHours:l,progress:c,constraint:d,projectEndMs:u}=e,p={hasLate:new Uint8Array(a),lateStartMs:new Float64Array(a),lateFinishMs:new Float64Array(a),lateStartIsMoment:new Uint8Array(a),lateFinishIsMoment:new Uint8Array(a),hasMinimumFromLinks:new Uint8Array(a),minimumFromLinksFinishMs:new Float64Array(a)},y=new Uint8Array(a),f=new Float64Array(a),m={startMs:0,finishMs:0},A=(D,b,M,H)=>{p.hasLate[D]=1,p.lateStartMs[D]=b,p.lateFinishMs[D]=M,p.lateStartIsMoment[D]=H?1:0,p.lateFinishIsMoment[D]=H?1:0},g=(D,b)=>{m.startMs=D,m.finishMs=b},P=(D,b,M,H,z)=>{(D?z<M:H<b)?g(H,z):g(b,M)},L=(D,b)=>h(e.hasConstraintDate,D)===1?h(e.constraintMs,D):b,F=D=>Pe(t,D)?h(c,D)!==zt:h(c,D)<=0,T=(D,b,M,H,z,Z)=>{let J=h(e.linkLagHours,z),ht=h(e.linkType,z),Ct=h(l,D),ee=H===V.ALAP,wt;ht===_t.FINISH_TO_START?wt=ee?x(Z,!0):h(p.lateStartMs,Z):ht===_t.START_TO_START?wt=h(p.lateStartMs,Z):ht===_t.FINISH_TO_FINISH?wt=h(p.lateFinishMs,Z):wt=ee?x(Z,!1):h(p.lateFinishMs,Z);let Ie=ht===_t.FINISH_TO_START||ht===_t.FINISH_TO_FINISH,en=Ie?-Ct:-J,qr=Ie?-J:Ct;if(M&&J===0){let sr=b.addHours(wt,en);g(sr,b.addHours(sr,qr));return}if(ht===_t.FINISH_TO_START){if(J===0){let rD=b.lastWorkingHourBeforeMs(wt),Sp=b.lastWorkingHourBeforeMs(b.addHours(rD,qr));g(b.addHours(Sp,en),Sp);return}let sr=M?wt:b.lastWorkingHourBeforeMs(wt),Cn=b.addHours(sr,qr),Ao=b.addHours(Cn,en);g(Ao,M?Cn:b.lastWorkingHourBeforeMs(Cn));return}if(ht===_t.FINISH_TO_FINISH){let sr=J>0?b.lastWorkingHourBeforeMs(wt):wt,Cn=b.addHours(sr,qr);g(b.addHours(Cn,en),Cn);return}if(ht===_t.START_TO_START){let Cn=J!==0&&J<0&&!M?b.nextWorkMs(wt):wt,Ao=b.addHours(Cn,en);g(Ao,b.addHours(Ao,qr));return}let Ip=b.addHours(wt,en);g(Ip,b.addHours(Ip,qr))};function x(D,b){if(h(n.hasEarly,D)===0)throw new TypeError(`critical path successor ${t.activityIds[D]} has no early dates`);return b?h(n.earlyStartMs,D):h(n.earlyFinishMs,D)}let S=(D,b)=>{let M=h(o,D),H=h(s,D),z=h(c,D),Z=h(l,D),J=h(d,D),ht=h(e.hasConstraintDate,D)===1,Ct=h(e.constraintMs,D);if(z>=zt){g(M,H);return}if(z===0){let ee=J===V.SNLT||J===V.MSO,wt=J===V.FNLT||J===V.MFO;Id(J)?g(b.addHours(u,-Z),u):ee&&ht?g(Ct,b.addHours(Ct,Z)):wt&&ht?g(b.addHours(Ct,-Z),Ct):g(M,H);return}if(Id(J)){g(M,Math.max(H,u));return}if(J===V.MSO){g(M,H);return}g(M,Math.max(Math.min(u,L(D,u)),H))},k=D=>{if(!ws(t,e,D))return;if(y[D]=1,h(c,D)===zt){f[D]=h(s,D);return}let b=Ue(e,D),M=!1,H=0,z=h(t.outgoingStart,D+1);for(let J=h(t.outgoingStart,D);J<z;J+=1){let ht=h(t.outgoingList,J),Ct=h(t.linkTarget,ht);Ct!==pt&&h(p.hasLate,Ct)===1&&F(Ct)&&(T(D,b,!1,V.ASAP,ht,Ct),(!M||m.finishMs<H)&&(M=!0,H=m.finishMs))}if(h(d,D)===V.FNLT&&h(e.hasConstraintDate,D)===1){let J=h(e.constraintMs,D);(!M||J<H)&&(H=J),M=!0}f[D]=M?H:u},E=D=>{if(h(c,D)===zt){A(D,h(o,D),h(s,D),!1);return}let b=pt,M=pt,H=h(t.childStart,D+1);for(let z=h(t.childStart,D);z<H;z+=1){let Z=h(t.childList,z);if(h(p.hasLate,Z)===0)continue;(b===pt||h(p.lateStartMs,Z)<h(p.lateStartMs,b))&&(b=Z),(M===pt||h(p.lateFinishMs,Z)>h(p.lateFinishMs,M))&&(M=Z)}b!==pt&&(A(D,h(p.lateStartMs,b),h(p.lateFinishMs,M),!1),!ws(t,e,D)&&(p.lateStartIsMoment[D]=h(p.lateStartIsMoment,b),p.lateFinishIsMoment[D]=h(p.lateFinishIsMoment,M)))},j=(D,b,M)=>{let H=h(d,D),z=h(l,D),Z=0,J=0;if(Id(H))h(c,D)>0?(J=Math.min(u,M),Z=h(o,D)):(J=M,Z=b.addHours(J,-z));else if(H===V.SNLT){let Ct=b.addHours(M,-z);Z=Math.min(L(D,Ct),Ct),J=b.addHours(Z,z)}else H===V.FNLT?(Z=Math.min(L(D,M),M),J=b.addHours(Z,z)):H===V.MSO?(Z=h(e.constraintMs,D),J=b.addHours(Z,z)):H===V.MFO&&(J=h(e.constraintMs,D),Z=b.addHours(J,-z));let ht=b.addHours(u,-z);u<J?g(ht,u):g(Z,J)},w={hasCandidates:!1,minimumFinish:0,pickedStart:0,pickedFinish:0},B=D=>{if(!w.hasCandidates){w.hasCandidates=!0,w.minimumFinish=m.finishMs,w.pickedStart=m.startMs,w.pickedFinish=m.finishMs;return}m.finishMs<w.minimumFinish&&(w.minimumFinish=m.finishMs),(D?m.finishMs<w.pickedFinish:m.startMs<w.pickedStart)&&(w.pickedStart=m.startMs,w.pickedFinish=m.finishMs)},$=(D,b,M)=>{let H=Xh(M),z=h(e.isMilestone,D)===1;w.hasCandidates=!1;let Z=h(t.outgoingStart,D+1),J=h(t.outgoingStart,D);for(let ht=J;ht<Z;ht+=1){let Ct=h(t.outgoingList,ht),ee=h(t.linkTarget,Ct);ee!==pt&&h(p.hasLate,ee)===1&&F(ee)&&(T(D,b,z,M,Ct,ee),B(H))}},ft=(D,b,M)=>{let H=Math.min(M,u),z=h(s,D);return b===V.ASAP?Math.max(H,z):b===V.FNET||b===V.FNLT?Math.max(H,Math.min(H,L(D,H))):b===V.ALAP?Math.min(H,z):Math.max(H,z)},at=(D,b)=>{if(!(b===V.SNLT||b===V.FNLT))return;let H=h(n.hasRestriction,D)===1?{startMs:h(n.restrictionStartMs,D),finishMs:h(n.restrictionFinishMs,D)}:Ad(e,D);H!==null&&!(m.finishMs<H.finishMs)&&g(H.startMs,H.finishMs)},St=(D,b,M,H)=>{let z=h(d,D),Z=Xh(z),J=h(l,D);$(D,b,z);let ht=b.addHours(u,-J),Ct=w.hasCandidates;Ct?P(Z,w.pickedStart,w.pickedFinish,ht,u):g(ht,u),M&&P(Z,m.startMs,m.finishMs,b.addHours(H,-J),H);let ee=Ct?w.minimumFinish:m.finishMs,wt=h(c,D),Ie=wt>0&&wt<zt;Ct&&Ie&&g(h(o,D),ft(D,z,m.finishMs)),at(D,z),p.hasMinimumFromLinks[D]=1,p.minimumFromLinksFinishMs[D]=ee,A(D,m.startMs,m.finishMs,!1)},N=D=>{let b=Ue(e,D),M=h(t.parentIndex,D),H=M!==pt&&h(y,M)===1,z=H?h(f,M):0,Z=h(d,D),J=h(c,D),ht=h(o,D),Ct=h(s,D);if(!xa(t,D)){if(H&&xa(t,M)){j(D,b,z),A(D,m.startMs,m.finishMs,!1);return}S(D,b),A(D,m.startMs,m.finishMs,J>=zt);return}if(J===zt){A(D,ht,Ct,!1);return}if(K(D)){S(D,b),H?A(D,ht,Math.min(m.finishMs,z),!1):A(D,m.startMs,m.finishMs,!1);return}if(J>0&&J<zt&&xs(Z)){let Ie=Z===V.MSO?Ct:Math.max(Math.min(L(D,u),u),Ct);A(D,ht,Ie,!1);return}let wt=h(e.hasConstraintDate,D)===1;if(xs(Z)&&wt){let Ie=h(e.constraintMs,D),en=h(l,D);Z===V.MSO?A(D,Ie,b.addHours(Ie,en),!1):A(D,b.addHours(Ie,-en),Ie,!1);return}St(D,b,H,z)};function K(D){let b=h(t.outgoingStart,D+1);for(let M=h(t.outgoingStart,D);M<b;M+=1){let H=h(t.linkTarget,h(t.outgoingList,M));if(!(H!==pt&&!Pe(t,H)&&h(c,H)!==0))return!1}return!0}let it=0;for(let D of r){if(it+=1,it>=Ma&&(it=0,await Ot(),!i()))return null;let b=Pr(D);h(t.isTopLevel,b)!==1&&(kr(D)?E(b):Pe(t,b)?k(b):N(b))}return p}var pP=(t,e,n)=>n>=e?t.durationHours(e,n):-t.durationHours(n,e);function yP(t){let{graph:e,inputs:n,forward:r}=t,i=new Float64Array(e.linkCount).fill(Number.NaN);for(let a=0;a<e.linkCount;a+=1){if(h(r.hasLinkCandidate,a)===0)continue;let o=h(r.linkCandidateTarget,a),s=h(r.linkCandidateFinishMs,a),l=h(r.earlyFinishMs,o);if(!(h(r.hasEarly,o)===1&&h(r.earlyFinishIsNumber,o)===0&&Number.isFinite(s)&&Number.isFinite(l)))continue;let d=pP(Ue(n,o),s,l);i[a]=Object.is(d,-0)?0:d}return i}var Gn=(t,e,n)=>t.durationHours(n,e),Us=t=>Math.min(Gn(t.calendar,t.lateStart,t.earlyStart),Gn(t.calendar,t.lateFinish,t.earlyFinish)),Ua=t=>Gn(t.calendar,t.lateFinish,t.earlyFinish);function vd(t,e,n,r){let{backward:i}=t;return h(i.hasMinimumFromLinks,e)===0?r:Math.min(r,Gn(n.calendar,h(i.minimumFromLinksFinishMs,e),n.earlyFinish))}function fP(t,e,n,r){let{forward:i}=t;return r?Gn(n.calendar,h(i.restrictionStartMs,e),h(i.linkedStartMs,e)):Gn(n.calendar,h(i.restrictionFinishMs,e),h(i.linkedFinishMs,e))}function Sd(t,e,n,r){return h(t.forward.hasRestriction,e)===0?Us(n):Math.min(fP(t,e,n,r),Us(n))}function hP(t,e,n){let{inputs:r}=t,i=h(r.hasConstraintDate,e)===1?h(r.constraintMs,e):0;return vd(t,e,n,Math.min(Ua(n),Gn(n.calendar,i,n.earlyFinish)))}function mP(t,e,n,r){let i=h(t.inputs.constraint,e);switch(i){case V.ASAP:case V.SNET:case V.FNET:return r?Us(n):vd(t,e,n,Ua(n));case V.ALAP:return r?Math.min(Us(n),Gn(n.calendar,n.lateFinish,h(t.inputs.endMs,e))):Ua(n);case V.SNLT:return r?Sd(t,e,n,!0):vd(t,e,n,Ua(n));case V.FNLT:return r?Sd(t,e,n,!1):hP(t,e,n);case V.MSO:case V.MFO:return r?Sd(t,e,n,i===V.MSO):Ua(n);default:return Number.NaN}}function gP(t,e){let{inputs:n,forward:r,backward:i,hoursPerDay:a}=t,o=h(n.progress,e);if(o===zt)return 0;let s=h(i.hasLate,e)===1,l={calendar:Ue(n,e),earlyStart:h(r.earlyStartMs,e),earlyFinish:h(r.earlyFinishMs,e),lateStart:s?h(i.lateStartMs,e):0,lateFinish:s?h(i.lateFinishMs,e):0};return mP(t,e,l,o===0)/a}function AP(t,e,n){let{inputs:r,forward:i,backward:a}=t;if(h(r.constraint,e)===V.ALAP){let l=h(n?a.lateStartIsMoment:a.lateFinishIsMoment,e);return h(a.hasLate,e)===1&&l===0?h(n?a.lateStartMs:a.lateFinishMs,e):Number.NaN}return h(i.hasEarly,e)===1&&(n||h(i.earlyFinishIsNumber,e)===0)?h(n?i.earlyStartMs:i.earlyFinishMs,e):Number.NaN}function IP(t,e,n){let{inputs:r,forward:i,backward:a}=t;if(h(r.constraint,e)===V.ALAP){let s=h(n?a.lateFinishIsMoment:a.lateStartIsMoment,e);return h(a.hasLate,e)===1&&s===0?h(n?a.lateFinishMs:a.lateStartMs,e):Number.NaN}return n?h(i.earlyFinishIsNumber,e)===0?h(i.earlyFinishMs,e):Number.NaN:h(i.earlyStartMs,e)}function SP(t,e,n,r){let{graph:i,inputs:a,hoursPerDay:o}=t,s=Ue(a,e);r.hasUnstartedSuccessor=!1,r.minimumDays=Number.POSITIVE_INFINITY;let l=h(i.outgoingStart,e+1),c=h(i.outgoingStart,e);for(let d=c;d<l;d+=1){let u=h(i.outgoingList,d),p=h(i.linkTarget,u);if(p===pt)continue;let y=h(a.linkType,u),f=y===_t.FINISH_TO_START||y===_t.START_TO_START,m=y===_t.FINISH_TO_START||y===_t.FINISH_TO_FINISH,A=AP(t,p,f),g=IP(t,e,m),L=Number.isFinite(A)&&Number.isFinite(g)?s.durationHours(g,A):Number.NaN,F=h(a.linkLagHours,u),T=Math.max(0,L/o-F/o);n.hasLinkFreeFloat[u]=1,n.linkFreeFloatDays[u]=T,!(h(a.progress,p)>0)&&(r.hasUnstartedSuccessor=!0,r.minimumDays=Math.min(r.minimumDays,T))}}function Ms(t,e,n,r,i){return i&&Number.isFinite(n)&&Number.isFinite(r)?t.durationHours(n,r)/e:Number.NaN}function vP(t,e,n){let{inputs:r,forward:i,backward:a,hoursPerDay:o}=t,s=Ue(r,e);if(h(r.progress,e)===zt)return 0;let l=h(r.constraint,e),c=h(r.hasConstraintDate,e)===1,d=h(r.constraintMs,e),u=h(i.earlyStartMs,e),p=h(i.earlyFinishMs,e),y=h(i.earlyFinishIsNumber,e)===0;if(l===V.MSO||l===V.MFO){let P=l===V.MSO,L=c?d:t.referenceNowMs();return Math.max(0,Ms(s,o,P?u:p,L,P||y))}let m=l===V.ALAP?Ms(s,o,h(a.lateFinishMs,e),r.projectEndMs,h(a.hasLate,e)===1&&h(a.lateFinishIsMoment,e)===0):Ms(s,o,p,r.projectEndMs,y);if((l===V.SNLT||l===V.FNLT)&&!n.hasUnstartedSuccessor){let P=l===V.FNLT,L=Ms(s,o,P?p:u,d,c&&(!P||y));return Math.max(0,Math.min(m,L))}let g=n.hasUnstartedSuccessor?Math.min(n.minimumDays,m):m;return Math.max(0,g)}async function Qh(t,e){let{graph:n,forward:r}=t,i=n.activityCount,a={totalFloatDays:new Float64Array(i).fill(Number.NaN),freeFloatDays:new Float64Array(i).fill(Number.NaN),hasLinkFreeFloat:new Uint8Array(n.linkCount),linkFreeFloatDays:new Float64Array(n.linkCount).fill(Number.NaN),linkResidualHours:yP(t)},o={hasUnstartedSuccessor:!1,minimumDays:Number.POSITIVE_INFINITY},s=0;for(let l of r.calculationOrder){if(s+=1,s>=Ma&&(s=0,await Ot(),!e()))return null;a.totalFloatDays[l]=gP(t,l),SP(t,l,a,o),a.freeFloatDays[l]=vP(t,l,o)}return a}async function tm(t,e,n,r){let i=t.getAllLinks(),a=Bh(t,i),o=bh(t,a,i),s=$h(a,o);if(await Ot(),!n())return null;let l=await Jh(a,o,s.forward,n);if(!l)return null;let c=await Zh(a,o,l,s.backward,n);if(!c)return null;let d=await Qh({graph:a,inputs:o,forward:l,backward:c,hoursPerDay:e,referenceNowMs:()=>r?new Date(r).getTime():Date.now()},n);return d?{graph:a,inputs:o,links:i,forward:l,backward:c,floats:d}:null}async function Cd(t,e,n=()=>!0,r){if(!n())return null;let i=await tm(t,e,n,r);return!i||!n()?null:Vh(i,e)}async function em(t,e,n=()=>!0,r){let i=await Cd(t,e,n,r);return!i||!n()?!1:(Wh(t,i),!0)}function _i(t){let e=[],n=[];t.forEachActivity((i,a)=>{i.parentId===null&&e.push(String(a))});let r=i=>{let a=t.getActivity(String(i));if(!a)return 0;let o=[...t.getChildren(String(i))],s;if(o.length===0){let l=jt(a),c=l&&Number(l.cost)||0;s=(Number(a.progress)||0)/100*c}else{let l=0;for(let c of o)l+=r(String(c));s=l}return t.setActivityField(String(i),O.REAL_COST,s),n.push(String(i)),s};for(let i of e)r(i);return n}var nm=new Set;var rm=new Set(["activity-outdent","activity-indent"]);var Dd=["name","description","startDate","endDate","durationHours","constraintType","constraintDate","autoScheduling","calendarId","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","p6"],im=new Set(Dd),CP=new Set(["name","description","customId","subcontractId","responsableIds","tagIds"]);function Hs(t){return t.every(e=>Object.keys(e.fields).every(n=>CP.has(n)))}var Td=["parentId","type","correlativeId"],DP=new Set(Td);function Bs(t){return im.has(t)||DP.has(t)}function js(t){return im.has(t)}function Vs(t,e){let n="type"in e?e.type:t.type,r="durationHours"in e?e.durationHours:t.durationHours;return n===U.MILESTONE&&Number(r)!==0}function Ws(t){let e=t.progress;return typeof e=="number"?{...t,autoScheduling:ue(e)}:t}function Ks(t,e){return e.flatMap(n=>[n,...t.getChildren(n)])}function Ys(t,{adapter:e,customIdTracker:n}){for(let r of t){let i=e.getActivity(r)?.customId??null;i===null||!e.hasChildren(r)||(n.releaseCustomId(i),e.setActivityFields(r,{customId:null}))}}var Ha=new Set([R.TEXT,R.DESCRIPTION,R.COST,R.USED_COST,R.CUSTOM_ID,R.RESPONSABLES,R.SUBCONTRACT_ID,R.TAGS]),TP=new Set([I.ACTIVITY_CLIPBOARD_CLEAR,I.ACTIVITY_CLIPBOARD_IMPORT,I.ACTIVITY_COPY,I.CELL_CLIPBOARD_CLEAR,I.CELL_COPY,I.SELECTION_TOGGLE,I.SELECTION_REPLACE,I.VISIBILITY_SET,I.FILTER_SET,I.SORT_SET,I.VIEW_ATTRIBUTES_SET,I.GROUP_SET,I.WBS_DEPTH_SET,I.SIR_SYNC,I.ACTIVITY_LOOKAHEAD_SYNC,I.PERSISTENCE_ACKNOWLEDGE,I.BASELINE_APPLY,I.PONDERATOR_CRITERION_SET,I.STATUS_CRITERIA_SET]),_P=new Set([I.ACTIVITY_CLIPBOARD_CLEAR,I.ACTIVITY_CLIPBOARD_IMPORT,I.ACTIVITY_COPY,I.CELL_CLIPBOARD_CLEAR,I.CELL_COPY,I.SELECTION_TOGGLE,I.SELECTION_REPLACE,I.VISIBILITY_SET,I.FILTER_SET,I.SORT_SET,I.VIEW_ATTRIBUTES_SET,I.GROUP_SET,I.WBS_DEPTH_SET]),am=new Set(Object.values($r));function sm(t){return!_P.has(t.kind)}var EP=new Set;function RP(t){return t.kind===I.INLINE_EDIT||t.kind===I.CELL_PASTE_COPIED?Ha.has(t.column):t.kind===I.BULK_EDIT?t.edits.every(e=>Ha.has(e.column)):t.kind===I.ACTIVITY_FIELDS_RESTORE?Hs(t.activities):!1}function _d(t){return t.kind===I.INLINE_EDIT||t.kind===I.CELL_PASTE_COPIED?am.has(t.column):t.kind===I.BULK_EDIT&&t.edits.every(e=>am.has(e.column))}function Ed(t,e){return!(TP.has(t.kind)||e.has(t.kind)||RP(t))}function Ba(t){return t.kind===I.ACTIVITY_LOOKAHEAD_SYNC?t.persistedProgress!==void 0:Ed(t,EP)}function br(t){return _d(t)?!1:t.kind===I.ACTIVITY_LOOKAHEAD_SYNC?t.persistedProgress!==void 0:Ed(t,nm)}function lm(t){return _d(t)?!1:Ed(t,rm)}function Rd(t){return t.kind===I.ACTIVITY_SET_PROGRESS?!0:t.kind===I.INLINE_EDIT?t.column===R.PROGRESS:t.kind===I.BULK_EDIT?t.edits.some(e=>e.column===R.PROGRESS):t.kind===I.CELL_PASTE_COPIED?t.column===R.PROGRESS:!1}function PP(t){return lm(t)&&Rd(t)}var om=new Set([R.PROGRESS,R.HH_WORK_TIME,R.DURATION,R.COST,R.USED_COST,R.REAL_COST]);function kP(t){return t.kind===I.ACTIVITY_SET_PROGRESS?!0:t.kind===I.INLINE_EDIT||t.kind===I.CELL_PASTE_COPIED?om.has(t.column):t.kind===I.BULK_EDIT?t.edits.some(e=>om.has(e.column)):!1}var Jt={AUTOSCHEDULE:"autoschedule",PARENT_BOUNDS:"parent-bounds",PARENT_PROGRESS:"parent-progress",REAL_WORK:"real-work",EXPECTED_PROGRESS:"expected-progress",REAL_COST:"real-cost",BASELINE_VARIANCE:"baseline-variance",CRITICAL_PATH:"critical-path"};function cm(t,e,n){let r=new Set;if(e.ran&&r.add(Jt.AUTOSCHEDULE),r.add(Jt.PARENT_BOUNDS),_d(t))return r;kP(t)&&r.add(Jt.PARENT_PROGRESS),Rd(t)&&r.add(Jt.REAL_WORK);let i=!n.skipAutoSchedule;return i&&lm(t)&&r.add(Jt.EXPECTED_PROGRESS),i&&PP(t)&&r.add(Jt.REAL_COST),Ba(t)&&r.add(Jt.BASELINE_VARIANCE),i&&br(t)&&!n.skipCriticalPath&&r.add(Jt.CRITICAL_PATH),r}function At(t,e=!0){return e&&t?.dataDate!=null}var Gs=(t,e)=>{if(!(t instanceof Date)||!Number.isFinite(t.getTime()))throw new TypeError(`Outbuild P6 ${e} must be a valid Date`);return new Date(t.getTime())};function bP(t){if(t.type==="project")return;if(!Number.isFinite(t.durationHours)||t.durationHours<0)throw new TypeError("Outbuild P6 durationHours must be a non-negative finite number");let e=Gs(t.startDate,"plannedStart"),n=Gs(t.endDate,"plannedFinish"),r=t.durationHours;return{activityType:"task",actualStart:null,actualFinish:null,plannedStart:e,plannedFinish:n,remainingDurationHours:r,executionStatus:"not_started",expectedFinish:null,suspendDate:null,resumeDate:null,secondaryConstraintType:null,secondaryConstraintDate:null,percentCompleteType:Nt.PHYSICAL,physicalPercentComplete:0,actualDurationHours:0,atCompletionDurationHours:r,durationPercentComplete:0,unitsPercentComplete:0,schedulePercentComplete:0,remainingFloatHours:null,remainingEarlyStart:null,remainingEarlyFinish:null,remainingLateStart:null,remainingLateFinish:null,earlyStart:null,earlyFinish:null,lateStart:null,lateFinish:null,floatPath:null,floatPathOrder:null,longestPath:!1,originalDurationHours:r,actualLaborUnits:0,remainingLaborUnits:0,actualNonlaborUnits:0,remainingNonlaborUnits:0,primaryBaselineStart:null,primaryBaselineFinish:null,freeFloatHours:null}}function Ei(t){let e=bP(t);if(e!==void 0)return{...e,...qs(t,t.durationHours)}}var dm=100,um=0;function qs(t,e){if(t.progress===0)return{executionStatus:et.NOT_STARTED,actualStart:null,actualFinish:null,remainingDurationHours:e,physicalPercentComplete:um,actualDurationHours:0,atCompletionDurationHours:e,durationPercentComplete:0};let n=Gs(t.startDate,"actualStart");if(ri(t.progress)){let r=e>0;return{executionStatus:et.COMPLETED,actualStart:n,actualFinish:Gs(t.endDate,"actualFinish"),remainingDurationHours:0,physicalPercentComplete:dm,actualDurationHours:e,atCompletionDurationHours:e,durationPercentComplete:r?dm:um}}return{executionStatus:et.IN_PROGRESS,actualStart:n,actualFinish:null,remainingDurationHours:e,physicalPercentComplete:t.progress,actualDurationHours:0,atCompletionDurationHours:e,durationPercentComplete:0}}function Pd(t){return t.executionStatus===et.NOT_STARTED&&t.actualStart===null}function pm(t,e){if(!(t.progress!==0)||!Pd(e))return e;let r=qs(t,e.originalDurationHours),i=r.executionStatus===et.IN_PROGRESS&&e.remainingDurationHours!==null;return{...e,...r,...i?{remainingDurationHours:e.remainingDurationHours}:{}}}function ym(t,e){let n=e??void 0,r=LP(t,n);return()=>OP(t,n,r)}function LP(t,e){return e===void 0||At(e.settings,t.isDataDateEnabled())?new Map:new Map(t.getAllActivities().filter(n=>n.p6!==void 0&&Object.hasOwn(e.activities,n.id)).map(n=>[n.id,st(n)]))}function OP(t,e,n){if(!(e===void 0||At(e.settings,t.isDataDateEnabled())))for(let r of t.getAllActivities()){if(!Object.hasOwn(e.activities,r.id)){let o=Ei(r);o!==void 0&&t.setActivityField(r.id,"p6",o);continue}let i=n.get(r.id);if(i?.p6===void 0||r.p6===void 0)continue;let a=hm(i,r);Object.keys(a).length!==0&&t.setActivityField(r.id,"p6",{...r.p6,...a})}}function fm(t){if(t.dataDateSettings()===null||At(t.dataDateSettings(),t.isDataDateEnabled()))return;let e=t.peekWriteCapture();if(e!==null)for(let[n,r]of e.before){let i=t.getActivity(n);if(i?.p6===void 0||r.p6===void 0)continue;let a=hm(r,i);Object.keys(a).length!==0&&t.setActivityField(i.id,"p6",{...i.p6,...a})}}function hm(t,e){let n=t.durationHours!==e.durationHours;return{...t.startDate.getTime()!==e.startDate.getTime()?{plannedStart:new Date(e.startDate)}:{},...t.endDate.getTime()!==e.endDate.getTime()?{plannedFinish:new Date(e.endDate)}:{},...n?{originalDurationHours:e.durationHours}:{},...n||t.progress!==e.progress?NP(t,e,n):{}}}function NP(t,e,n){let r=e.p6;if(r.remainingDurationHours!==t.p6.remainingDurationHours)return{};let a=t.progress!==e.progress,o=a&&e.progress===0;if(Pd(r)||o){let l=n?e.durationHours:r.originalDurationHours;return qs(e,l)}return!(r.actualStart!==null)||!a?{}:FP(r,e)}function FP(t,e){let n=t.percentCompleteType===Nt.PHYSICAL;if(!ri(e.progress))return{...t.actualFinish===null?{}:{executionStatus:et.IN_PROGRESS,actualFinish:null},...n?{physicalPercentComplete:e.progress}:{}};let r=t.actualStart!==null&&e.endDate.getTime()>=t.actualStart.getTime();return t.actualFinish!==null||!r?{}:{executionStatus:et.COMPLETED,actualFinish:new Date(e.endDate),remainingDurationHours:0,physicalPercentComplete:100}}var Tt={INSERT:"insert",REMOVE:"remove",LINK_ADD:"link-add",LINK_REMOVE:"link-remove",LINK_FIELD:"link-field"},$s=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(e,n){let r=this._journal;r&&(r.before.has(e)||r.before.set(e,cn(n)),r.dirty.add(e))}noteInsert(e){this._journal?.ops.push({kind:Tt.INSERT,activityId:e})}noteRemove(e,n){this._journal?.ops.push({kind:Tt.REMOVE,activityId:e,before:cn(n)})}noteLinkAdd(e){this._journal?.ops.push({kind:Tt.LINK_ADD,linkId:e})}noteLinkRemove(e,n){this._journal?.ops.push({kind:Tt.LINK_REMOVE,linkId:e,before:mm(n)})}noteCorrelativeBefore(e,n){let r=this._journal;if(!r||r.correlativeBefore.has(e))return;let i=r.before.get(e)?.correlativeId;r.correlativeBefore.set(e,typeof i=="number"?i:n)}noteScheduledBefore(e,n){let r=this._journal;if(!r)return;let i=cn(n);r.scheduledBefore.has(e)||r.scheduledBefore.set(e,i),r.before.has(e)||r.before.set(e,i),r.dirty.add(e)}noteLinkField(e,n){let r=this._journal;!r||r.linkFieldCaptured.has(e)||(r.linkFieldCaptured.add(e),r.ops.push({kind:Tt.LINK_FIELD,linkId:e,before:mm(n)}))}noteProgressFallback(e,n){let r=this._journal;!r||r.progressFallbackBefore.has(e)||r.progressFallbackBefore.set(e,n)}};function mm(t){return{...t}}function Ri(t){return(t.pendingRequestIds?.length??0)>0}function kd(t,e,n){let r=[];for(let i of n){let a=t.get(i);if(!a)continue;let o=a.pendingRequestIds??[];if(Ri({pendingRequestIds:o})&&e.getActivity(i)==null)for(let s of o)r.push({kind:hs.SIR_AUTO_REJECT,activityId:i,sirId:s,reason:ms.ACTIVITY_DELETED})}return r}function Ft(t){let e={id:String(t.id),source:String(t.source),target:String(t.target),type:t.type,lag:Number(t.lag),freeSlackHours:typeof t.freeSlackHours=="number"&&Number.isFinite(t.freeSlackHours)?t.freeSlackHours:null,isCritical:t.isCritical===!0};return t.proplannerId!=null&&(e.proplannerId=Number(t.proplannerId)),t.ganttId!=null&&(e.ganttId=Number(t.ganttId)),t.sectorId!=null&&(e.sectorId=Number(t.sectorId)),e}var Xt={BEFORE_DIFF:"before-diff",AFTER_DIFF:"after-diff"};async function tt(t,e){let n=HP(t,e),r=new Map(e.beforeSnap),i=t.peekWriteCapture(),a=UP(e.deferredCorrelatives,i,r);if(i){let y=jP(i);BP(t,i,y,r,n)}let o=e.sirDetection,s=o===Xt.BEFORE_DIFF?kd(r,t,n):[],l=MP(e.correlativeShifts,a,n),c=await Ss(t,r,n,l),d=o===Xt.AFTER_DIFF?kd(r,t,n):s,u=e.warnings??[],p=xP(e.links??[],i?wP(t,i):[]);return{source:e.source,activities:c,links:p,calendars:[],trackingEvents:e.trackingEvents??[],...d.length>0?{effects:d}:{},...u.length>0?{warnings:u}:{}}}function wP(t,e){let n=[];for(let r of e.ops){if(r.kind!==Tt.LINK_FIELD)continue;let i=t.getLink(r.linkId);if(!i)continue;let a={};for(let o of["freeSlackHours","isCritical"])Object.is(r.before[o],i[o])||(a[o]={before:r.before[o],after:i[o]});Object.keys(a).length!==0&&n.push({id:r.linkId,kind:W.UPDATED,fields:a,after:Ft(i)})}return n}function xP(t,e){let n=[],r=new Map;for(let i of t){let a=r.get(i.id);if(a===void 0){r.set(i.id,n.length),n.push(i);continue}let o=n[a];if((o.kind===W.UPDATED||o.kind===W.CREATED)&&i.kind===W.UPDATED){n[a]={...o,fields:{...o.fields,...i.fields},after:i.after};continue}n[a]=i}for(let i of e){let a=r.get(i.id);if(a===void 0){r.set(i.id,n.length),n.push(i);continue}let o=n[a];if(o.kind===W.DELETED)continue;let s=o.kind===W.CREATED?Object.fromEntries(Object.entries(i.fields??{}).map(([l,c])=>[l,{before:void 0,after:c.after}])):i.fields;n[a]={...o,fields:{...o.fields,...s},after:i.after}}return n}function MP(t,e,n){if(!(t!==void 0&&t.length>0)&&e.size===0)return;let i=new Map;for(let a of t??[])i.set(a.activityId,a.before),n.add(a.activityId);for(let[a,o]of e)i.set(a,o),n.add(a);return i}function UP(t,e,n){let r=new Map;for(let[i,a]of t??[]){if(n.has(i))continue;let o=e?.before.get(i);o?n.set(i,{...o,correlativeId:a}):r.set(i,a)}return r}function HP(t,e){let n=new Set;for(let r of e.touchedIds)n.add(r);for(let r of e.scheduledIds)n.add(r);if(e.includeAllIds)for(let r of t.getAllIds())n.add(r);return n}function BP(t,e,n,r,i){for(let a of e.dirty){if(n.has(a)||r.has(a))continue;let o=e.before.get(a),s=t.getActivity(a);!o||!s||nh(o,s)&&(r.set(a,o),i.add(a))}}function jP(t){return new Set(t.ops.filter(e=>e.kind===Tt.INSERT).map(e=>e.activityId))}function zs(t,e,n,r=new Map){if(!t||t==="0")return;let i=n.getChildren(t);if(i.length===0)return;let a=new Map,o=new Set,s=0;for(let u of i){let p=WP(String(u),e,n,r);a.set(String(u),p.magnitude),s+=p.magnitude,p.hasActiveBaseline&&o.add(String(u))}let l=s?100/s:0,d=e!==Dt.COST&&o.size>0?100/o.size:0;for(let u of i){let p=n.getActivity(u);if(!p)continue;let y=VP(String(u),p,a,o,s,l,d);y!==null&&n.setActivityField(u,R.PONDERATOR,y)}}function VP(t,e,n,r,i,a,o){return e.type===U.PROJECT||jt(e)?i?a*(n.get(t)??0):r.has(t)?o:0:!Array.isArray(e.baselinePoints)||e.baselinePoints.length===0?0:null}function WP(t,e,n,r){let i=[{id:t,expanded:!1}];for(;i.length>0;){let{id:a,expanded:o}=i.pop();if(r.has(a))continue;let s=n.getActivity(a),l=jt(s);if(s?.type!==U.PROJECT){r.set(a,{magnitude:l&&s?.type!==U.MILESTONE?KP(l,e):0,hasActiveBaseline:l!==null});continue}let c=n.getChildren(a);if(!o){i.push({id:a,expanded:!0}),c.forEach(u=>{i.push({id:String(u),expanded:!1})});continue}let d={magnitude:0,hasActiveBaseline:l!==null};for(let u of c){let p=r.get(String(u));d.magnitude+=p.magnitude,d.hasActiveBaseline||=p.hasActiveBaseline}r.set(a,d)}return r.get(t)}function KP(t,e){return e===Dt.COST?bd(t.cost):e===Dt.WORK_HOURS?bd(t.workHours):bd(t.durationDays)}function bd(t){let e=typeof t=="string"?parseFloat(t):t;return typeof e=="number"&&Number.isFinite(e)?e:0}function gm(t,e){let n=t.peekWriteCapture();if(!n)return;let r=new Set,i=new Map,a=new Map;for(let s of n.ops)s.kind===Tt.REMOVE&&a.set(s.activityId,s.before.parentId);let o=(s,l)=>{let c=s;for(;c!==null&&!q(c);){let d=i.get(c);if(d===!0||d===l)break;i.set(c,l),c=a.has(c)?a.get(c)??null:t.getParentId(c)}};for(let[s,l]of n.before){let c=t.getActivity(s);if(!(c&&l.parentId!==c.parentId)||!c)continue;let u=jt(l)!==null||Ld(s,t,r);o(l.parentId,u),o(c.parentId,!1)}for(let s of n.ops)if(s.kind===Tt.REMOVE)jt(s.before)&&o(s.before.parentId,!0);else if(s.kind===Tt.INSERT){let l=t.getActivity(s.activityId);l&&Ld(l.id,t,r)&&o(l.parentId,!1)}for(let[s,l]of i)(l||Ld(s,t,r))&&zs(s,e,t)}function Ld(t,e,n){let r=[],i=[t];for(;i.length>0;){let a=i.pop();if(a===void 0||n.has(a))continue;let o=e.getActivity(a);if(o&&jt(o))return!0;r.push(a),i.push(...e.getChildren(a))}for(let a of r)n.add(a);return!1}function Am(t){let e=t.peekWriteCapture();if(!e)return null;let n=new Set(e.dirty),r=i=>{n.add(String(i.source)),n.add(String(i.target))};for(let[i,a]of e.before)n.add(i),a.parentId!==null&&n.add(String(a.parentId));for(let i of e.ops)switch(i.kind){case Tt.INSERT:n.add(i.activityId);break;case Tt.REMOVE:i.before.parentId!==null&&n.add(String(i.before.parentId));break;case Tt.LINK_ADD:{let a=t.getLink(i.linkId);a&&r(a);break}case Tt.LINK_REMOVE:case Tt.LINK_FIELD:{r(i.before);let a=t.getLink(i.linkId);a&&r(a);break}}return[...n]}var Et={ROOTS:"roots"};async function ot(t,e){e.action.kind===I.ACTIVITY_LOOKAHEAD_CONVERT||gm(t.adapter,t.sector.activityCreter??Dt.DURATION);let r=ZP(t.adapter),i=YP(t.adapter,e),a=zP(t.adapter,i),o=XP(i,r,Sm(t.adapter));a&&o.add(Jt.AUTOSCHEDULE),o.has(Jt.AUTOSCHEDULE)&&await ak(t.adapter,i);let s=a?await JP(t):o.has(Jt.AUTOSCHEDULE)?await ek(t,i.autoscheduleFrom,i.preventSummaryTargetPullback,i.action.kind===I.CALENDAR_RECONCILE):ik();return await ok(t.adapter,i,s.scheduledIds,o,r,t.sector.activityCreter??Dt.DURATION),await lk(t,o,e.now,e.options.at),fm(t.adapter),s}function YP(t,e){let n=GP(t,e.autoscheduleFrom);return n===e.autoscheduleFrom?e:{...e,autoscheduleFrom:n}}function GP(t,e){if(e===Et.ROOTS)return Et.ROOTS;let n=qP(t);if(n.size===0)return e;if(e!==null&&n.add(String(e)),n.size!==1)return Et.ROOTS;let[r]=n;return r===void 0||!t.activityExists(r)||t.hasChildren(r)?Et.ROOTS:r}function qP(t){let e=new Set,n=t.peekWriteCapture();if(!n)return e;for(let r of n.ops){if(r.kind===Tt.LINK_REMOVE){e.add(String(r.before.target));continue}if(r.kind===Tt.LINK_ADD){let i=t.getLink(r.linkId);i&&e.add(String(i.target));continue}if(r.kind===Tt.LINK_FIELD){e.add(String(r.before.target));let i=t.getLink(r.linkId);i&&e.add(String(i.target))}}return e}async function Im(t,e,n){if(t.activityId!==void 0&&!n.adapter.activityExists(t.activityId))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};if(Sm(n.adapter)&&!$P(n.adapter))return{ok:!1,reason:C.MANUAL_SCHEDULING_ACTIVE};let r=await dt(n.adapter,new Set(n.adapter.getAllIds()));n.scheduler.invalidateAllCaches();let i=t.activityId===void 0?n.adapter.getRootIds():[t.activityId],{scheduledIds:a}=await ot({adapter:n.adapter,scheduler:n.scheduler,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:t.activityId??Et.ROOTS,recomputeParentsFrom:i,now:n.now,options:e});return{ok:!0,changes:await tt(n.adapter,{source:t,beforeSnap:r,touchedIds:i,scheduledIds:a,hoursPerDay:n.sector.hoursPerDay})}}function Sm(t){return At(t.dataDateSettings(),t.isDataDateEnabled())}function $P(t){return t.dataDateSettings()?.scheduleAutomaticallyOnDateChange===!0}function zP(t,e){let n=t.dataDateSettings();return At(n,t.isDataDateEnabled())&&n?.scheduleAutomaticallyOnDateChange===!0&&e.autoscheduleFrom!==null&&e.options.skipAutoSchedule!==!0}async function JP(t){if(t.runAutomaticP6Schedule===void 0)throw new Error("Automatic P6 scheduling is not configured");return{scheduledIds:[...await t.runAutomaticP6Schedule()],warnings:[]}}function XP(t,e,n){let r=t.autoscheduleFrom!==null,i=!t.options.skipAutoSchedule&&r&&!n,a=n?{...t.options,skipCriticalPath:!0}:t.options,o=new Set(cm(t.action,{requested:r,ran:i},a));return(t.recomputeParentProgress||e.affectedParents.size>0)&&o.add(Jt.PARENT_PROGRESS),o}function ZP(t){let e=new Set,n=new Set,r=t.peekWriteCapture();if(!r)return{affectedParents:e,dirtySeeds:n};let i=a=>{if(a===null||q(a))return;let o=String(a);e.add(o);let s=t.getChildren(o)[0];s!==void 0&&n.add(s)};return QP(t,r.ops,i),tk(t,r.before,n,i),{affectedParents:e,dirtySeeds:n}}function QP(t,e,n){for(let r of e)if(r.kind===Tt.INSERT){let i=t.getActivity(r.activityId);i&&n(i.parentId)}else r.kind===Tt.REMOVE&&n(r.before.parentId)}function tk(t,e,n,r){for(let[i,a]of e){let o=t.getActivity(i);if(!o)continue;let s=!Object.is(a.progress,o.progress),l=!Object.is(a.ponderator,o.ponderator),c=!Object.is(a.parentId,o.parentId);(s||l)&&(r(o.parentId),n.add(String(i))),c&&(r(a.parentId),r(o.parentId),n.add(String(i)))}}async function ek(t,e,n=!1,r=!1){let i=r||!t.adapter.isScheduleSettled()?null:Am(t.adapter),a=e===Et.ROOTS||e===null?[]:[e],o=i!==null?{seedIds:[...i,...a]}:e===Et.ROOTS?{}:{triggerId:e};n&&(o.preventSummaryTargetPullback=!0);let s=await t.scheduler.schedule(o);s.cycles.length===0&&!s.cancelled&&t.adapter.markScheduleSettled();let l=rk(t.adapter,s.updatedIds),c=nk(t.adapter,s);return ma(t.adapter,s),{...l,warnings:c}}function nk(t,e){let n=[];for(let r of e.plans.values()){let i=r.earliestSchedulingStart;if(!i||r.startDate>=i)continue;let a=t.getActivity(r.activityId);!a?.constraintType||!a.constraintDate||n.push({kind:Cr.VIOLATION,activityId:a.id,constraintType:a.constraintType,constraintDate:a.constraintDate,projectedDate:i,messageKey:Cr.VIOLATION})}return n}function rk(t,e){let n=[];for(let r of e){let i=String(r);n.push(i);let a=t.getActivity(i);a&&t.noteScheduledBefore(i,a)}return{scheduledIds:n,warnings:[]}}function ik(){return{scheduledIds:[],warnings:[]}}async function ak(t,e){let n=e.collectDirty?e.collectDirty([]):zc(e.recomputeParentsFrom,[]);n.size!==0&&await sn(t,n,!1)}async function ok(t,e,n,r,i,a){r.has(Jt.PARENT_PROGRESS)&&sk(t,i.affectedParents);let o=e.collectDirty?e.collectDirty(n):zc(e.recomputeParentsFrom,n);for(let s of i.dirtySeeds)o.add(s);await sn(t,o,r.has(Jt.PARENT_PROGRESS),{recomputeRealWork:r.has(Jt.REAL_WORK),criterion:a,progressMode:"freeze-when-no-contribution"})}function sk(t,e){for(let n of e){if(t.hasChildren(n))continue;let r=t.getProgressFallback(n);r!==null&&(t.setActivityField(n,"progress",r),t.setProgressFallback(n,null))}}async function lk(t,e,n,r){e.has(Jt.EXPECTED_PROGRESS)&&n!==null&&(Qc(t.adapter)&&Fa(t.adapter,n,t.defaultBaseCalendarId??null),Tr(t.adapter,n),un(t.adapter,t.sector.statusCriteria)),e.has(Jt.REAL_COST)&&_i(t.adapter),e.has(Jt.BASELINE_VARIANCE)&&(_r(t.adapter,t.sector.hoursPerDay),Er(t.adapter,t.sector.hoursPerDay)),e.has(Jt.CRITICAL_PATH)&&await em(t.adapter,t.sector.hoursPerDay,void 0,r)}var ck=new Set([R.CONSTRAINT_TYPE,R.CONSTRAINT_DATE]),dk=new Set([_.MSO,_.MFO]);function Pi(t){return ck.has(t)}function Js(t){return t===R.CONSTRAINT_DATE}function Xs(t,e,n,r){let i=n.getActivity(t);if(!i)return!1;let a=i.constraintType;if(!a||jn.has(a)||dk.has(a))return!1;let o=Od(i.startDate),s=Od(n.getLastStartDate(t));if(!s||!o||o.getTime()!==s.getTime())return!1;let l=uk(e,a,String(i.calendarId??""),r),c=Od(i.constraintDate);return pk(c,l)?!1:(n.setActivityField(t,"constraintDate",l),!0)}function uk(t,e,n,r){if(t===null)return null;let i=r.getCalendar(n);return i?$e(t,i,e):t}function Od(t){if(t instanceof Date)return t;if(typeof t=="string"||typeof t=="number"){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null}function pk(t,e){return t===null&&e===null?!0:t===null||e===null?!1:t.getTime()===e.getTime()}async function Zs(t,{postMutationArgs:e,revertTargets:n,revert:r}){let{scheduledIds:i}=await ot(t,vm(e)),a=!1;for(let{activityId:o,priorConstraintDate:s}of n){let l=r(o,s);a=a||l}if(a){let o=await ot(t,vm(e));i=fk(i,o.scheduledIds)}return br(e.action)&&await ot(t,yk(e)),{scheduledIds:i}}function vm(t){return{...t,options:{...t.options,skipCriticalPath:!0}}}function yk(t){return{action:t.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:t.options}}function fk(t,e){let n=new Set(t);for(let r of e)n.add(r);return[...n]}function ki(t,e,n){let r=n?t.getIncomingLinkIds(e):t.getOutgoingLinkIds(e),i=[];for(let a of r){let o=t.getLink(a);o&&i.push(o)}return i}function qn(t,e,n){let r=[];for(let{op:i,finalLinkId:a,rejected:o}of t){if(o!==null)continue;if(i.kind===xt.CREATE){if(!a)continue;let u=n.getLink(a);if(!u)continue;let p=e.get(a);if(p){let y={};String(p.source)!==String(u.source)&&(y.source={before:String(p.source),after:String(u.source)}),String(p.target)!==String(u.target)&&(y.target={before:String(p.target),after:String(u.target)}),p.type!==u.type&&(y.type={before:p.type,after:u.type}),Number(p.lag)!==Number(u.lag)&&(y.lag={before:Number(p.lag),after:Number(u.lag)}),Object.keys(y).length>0&&r.push({id:String(a),kind:W.UPDATED,fields:y,after:Ft(u)});continue}r.push({id:String(a),kind:W.CREATED,fields:{source:{before:void 0,after:String(u.source)},target:{before:void 0,after:String(u.target)},type:{before:void 0,after:u.type},lag:{before:void 0,after:Number(u.lag)}},after:Ft(u)});continue}if(i.kind===xt.DELETE){if(n.getLink(i.linkId))continue;let u=e.get(i.linkId);r.push({id:String(i.linkId),kind:W.DELETED,fields:u?{source:{before:String(u.source),after:void 0},target:{before:String(u.target),after:void 0},type:{before:u.type,after:void 0},lag:{before:Number(u.lag),after:void 0}}:void 0,after:null});continue}let s=e.get(i.linkId),l=n.getLink(i.linkId);if(!l)continue;let c={};s&&String(s.source)!==String(l.source)&&(c.source={before:String(s.source),after:String(l.source)}),s&&String(s.target)!==String(l.target)&&(c.target={before:String(s.target),after:String(l.target)}),s&&s.type!==l.type&&(c.type={before:s.type,after:l.type}),s&&Number(s.lag)!==Number(l.lag)&&(c.lag={before:Number(s.lag),after:Number(l.lag)}),!(s!==void 0&&Object.keys(c).length===0)&&r.push({id:String(i.linkId),kind:W.UPDATED,fields:c,after:Ft(l)})}return r}function bi(t,e){let n=new Map;if(!t.getActivity(e))return n;for(let r of t.getIncomingLinkIds(e)){let i=t.getLink(r);i&&n.set(String(i.id),Number(i.lag))}return n}function Li(t,e,n){let r=[];if(!e.getActivity(n))return r;for(let i of e.getIncomingLinkIds(n)){let a=e.getLink(i);if(!a)continue;let o=t.get(String(a.id));o===void 0||o===Number(a.lag)||r.push({id:String(a.id),kind:W.UPDATED,fields:{lag:{before:o,after:Number(a.lag)}},after:Ft(a)})}return r}function Cm(t,e){typeof t=="string"&&t.length>0&&e.releaseCustomId(t)}function Oi(t,e){return zf.has(e)?t.p6?.[e]:Reflect.get(t,e)}var Ae={MOVE:"move",RESIZE_START:"resize-start",RESIZE_END:"resize-end"},hk=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),Nd=(t,e)=>t===null?e:Math.min(t,e),Fd=(t,e)=>t===null?e:Math.max(t,e);function Tm(t,e,n){let r=[...new Set(e.kind===Ae.MOVE?e.activityIds.map(String):[String(e.activityId)])];if(r.length===0)throw new Error("[ScheduleCore] date gesture has no participants");let i=mk(t,e,r);return gk(t,r,i),{getDates(a,o){if(n(),!Number.isFinite(o))throw new Error("[ScheduleCore] invalid date gesture edge");let s=i.get(String(a));if(!s)return null;let l=Ik(s,o),c=Sk(s,o);if(l===null||c===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(a)}`);return{startTimeMs:l,endTimeMs:c}}}}function mk(t,e,n){let r=new Map,i=e.kind===Ae.MOVE?String(e.anchorActivityId):null,a=i===null?null:Dm(t,i);if(i!==null&&!n.includes(i))throw new Error("[ScheduleCore] move anchor is not a participant");for(let o of n){let s=Dm(t,o);if(e.kind===Ae.MOVE){let l=a.startDate.getTime();r.set(o,{constantStart:null,variableStartOffset:s.startDate.getTime()-l,constantEnd:null,variableEndOffset:s.endDate.getTime()-l})}else e.kind===Ae.RESIZE_START?r.set(o,{constantStart:null,variableStartOffset:0,constantEnd:s.endDate.getTime(),variableEndOffset:null}):r.set(o,{constantStart:s.startDate.getTime(),variableStartOffset:null,constantEnd:null,variableEndOffset:0})}return r}function gk(t,e,n){let r=va(t,new Set(e));for(let i of r){let a=hk();for(let o of t.getChildren(i)){let s=n.get(o);if(s){Ak(a,s);continue}let l=t.getActivity(o);if(!l)throw new Error(`[ScheduleCore] missing child ${o} while previewing parent ${i}`);a.constantStart=Nd(a.constantStart,l.startDate.getTime()),a.constantEnd=Fd(a.constantEnd,l.endDate.getTime())}n.set(i,a)}}function Dm(t,e){let n=t.getActivity(e);if(!n)throw new Error(`[ScheduleCore] missing date gesture activity ${e}`);if(t.hasChildren(e))throw new Error(`[ScheduleCore] summary activity ${e} cannot be dragged directly`);return n}function Ak(t,e){e.constantStart!==null&&(t.constantStart=Nd(t.constantStart,e.constantStart)),e.variableStartOffset!==null&&(t.variableStartOffset=Nd(t.variableStartOffset,e.variableStartOffset)),e.constantEnd!==null&&(t.constantEnd=Fd(t.constantEnd,e.constantEnd)),e.variableEndOffset!==null&&(t.variableEndOffset=Fd(t.variableEndOffset,e.variableEndOffset))}function Ik(t,e){if(t.variableStartOffset===null)return t.constantStart;let n=e+t.variableStartOffset;return t.constantStart===null?n:Math.min(t.constantStart,n)}function Sk(t,e){if(t.variableEndOffset===null)return t.constantEnd;let n=e+t.variableEndOffset;return t.constantEnd===null?n:Math.max(t.constantEnd,n)}function Lr(t,e,n,r=!0){return t!==void 0&&At(e,r)?n===Ae.RESIZE_END?t.executionStatus===et.COMPLETED?vt("data_date_activity_completed","data_date_edit_rejected"):ct():t.actualStart===null?ct():vt("data_date_actual_start_locked","data_date_edit_rejected"):ct()}var vk=new Set([Me.HAS_PROGRESS,Me.COMPLETED]),Ck={[R.START_DATE]:Ae.MOVE,[R.END_DATE]:Ae.RESIZE_END};function Qs(t,e,n,r,i=!0){let a=e.p6;if(!(a!==void 0&&At(n,i))||!t.allowed&&!vk.has(t.reason))return t;if(r===R.PROGRESS&&a.percentCompleteType===Nt.UNITS)return vt(Me.DATA_DATE_UNITS_PERCENT_READ_ONLY,cs.DATA_DATE_UNITS_PERCENT_READ_ONLY);let s=Ck[r];return s===void 0?ct():Lr(a,n,s,i)}var Dk=100,Tk=2;function Em(t,e,n,r,i){let{progress:a}=r,o=r.writesProgress?{activityPercentComplete:a}:{};if(e.executionStatus===et.COMPLETED)return a>=100?n:Ni(n,{actualFinish:null,...o},re.UNCOMPLETE);if(e.executionStatus===et.IN_PROGRESS)return a<100?Ni(n,o):_m(n,{actualFinish:t.endDate,...o},o,r,i);if(a===0)return n;let s={actualStart:t.startDate};return a<100?Ni(n,{...s,...o},re.START_ON_PROGRESS):_m(n,{...s,actualFinish:t.endDate,...o},{...s,...o},r,i)}function _m(t,e,n,r,i){return r.explicitCompletion||Ra(re.COMPLETE_ON_PROGRESS,i)?Ni(t,e):Ra(re.KEEP_IN_PROGRESS,i)?Ni(t,n):{...Ni(t,e,re.COMPLETE_ON_PROGRESS),confirmationAlternative:{kind:re.KEEP_IN_PROGRESS,effects:n}}}function Ni(t,e,n){return Object.keys(e).length===0?t:{...t,dataDatePatch:e,...n===void 0?{}:{confirmation:n}}}function xd(t){switch(t.percentCompleteType){case Nt.PHYSICAL:return wd(t.physicalPercentComplete);case Nt.UNITS:return wd(t.unitsPercentComplete);default:return _k(t)}}function _k(t){if(t.remainingDurationHours===null)return null;if(t.originalDurationHours===0)return t.executionStatus===et.COMPLETED?100:0;let e=(t.originalDurationHours-t.remainingDurationHours)/t.originalDurationHours;return wd(Math.min(100,Math.max(0,e*Dk)))}function wd(t){return Number(t.toFixed(Tk))}function Fi(t,e,n,r,i){let a=t.canEdit(e,n.ctx.hierarchy,i);return n.dataDateCapability===null?a:Qs(a,e,n.dataDateSettings,r,n.dataDateEnabled)}function Pm(t,e){return e?{...t,dataDatePatch:{...t.dataDatePatch,...e.dataDatePatch}}:t}function Ek(t){return t.eventSource==="sir-apply"&&t.edits.some(e=>e.column==="actualStart"||e.column==="actualFinish")}function km(t){if(!Ek(t))return t.edits.map(r=>[r]);let e=new Map;for(let r of t.edits){if(r.column!=="actualStart"&&r.column!=="actualFinish")continue;let i=String(r.activityId),a=e.get(i)??[];a.push(r),e.set(i,a)}let n=new Map;for(let r of e.values())r.length!==2||r[0].column===r[1].column||r.every(i=>i.newValue instanceof Date)&&(n.set(r[0],r),n.set(r[1],[]));return t.edits.flatMap(r=>{let i=n.get(r);return i?.length===0?[]:[i??[r]]})}function bm(t,e){let n=new Map;for(let r of Rk(t)){let i=e.ctx.activityReader.getActivity(r);if(!i)continue;let a=Lr(i.p6,e.dataDateSettings,Ae.RESIZE_START,e.dataDateEnabled);a.allowed||n.set(r,Ud(a))}return n}function Rk(t){let e=new Map;for(let r of t){let i=String(r.activityId),a=e.get(i)??new Set;a.add(r.column),e.set(i,a)}let n=new Set;for(let[r,i]of e)i.has(R.START_DATE)&&i.has(R.END_DATE)&&n.add(r);return n}function Ud(t){return{accepted:!1,reason:t.reason,...t.alertKey?{alertKey:t.alertKey}:{}}}var Pk={patch:{},needsAutoSchedule:!1,postProcessors:[]};function Lm(t,e,n,r,i){return r.dataDateCapability!==null&&At(r.dataDateSettings,r.dataDateEnabled)?Wt(t,r.ctx.hierarchy)?{accepted:!1,reason:Me.SUMMARY,alertKey:"summary_column_value"}:t.p6===void 0?null:Or(t,n??Pk,r,R.PROGRESS,i,{progress:e,explicitCompletion:!0,writesProgress:n!==null}):null}function Or(t,e,n,r,i,a){let o=Lk(t,bk(t,e,r),n,r,i,a);if(o===null)return Md(C.INVALID_VALUE);if("accepted"in o)return o;if(o.dataDatePatch===void 0)return Rm(o);if(t.p6===void 0||n.dataDateCapability===null)return Md(C.INVALID_VALUE);if(o.confirmation!==void 0&&!Ra(o.confirmation,i))return{accepted:!1,reason:C.CONFIRMATION_REQUIRED,confirmation:{kind:o.confirmation,activityId:t.id,effects:o.dataDatePatch,...o.confirmationAlternative===void 0?{}:{alternative:o.confirmationAlternative}}};try{let l=n.dataDateCapability.prepareActivityUpdate(t.p6,o.dataDatePatch,o.patch.constraintType??t.constraintType),c=Uk(t,l.next,n),d=kk(t,{...o,patch:{...o.patch,...c.patch},dataDateState:c.p6},l.next,n,r);return Rm(At(n.dataDateSettings,n.dataDateEnabled)?{...d,needsAutoSchedule:!0}:d)}catch{return Md(C.INVALID_VALUE)}}function kk(t,e,n,r,i){if(i===R.PROGRESS||t.p6===void 0||!At(r.dataDateSettings,r.dataDateEnabled))return e;let a=xd(n);return a===null||a===t.progress||a===xd(t.p6)||!gi.canEdit(t,r.ctx.hierarchy).allowed?e:{...e,patch:{...e.patch,progress:a}}}function Rm(t){return{accepted:!0,changes:t}}function Md(t){return{accepted:!1,reason:t}}function bk(t,e,n){let r=t.p6,i=e.patch.constraintType;return!(n===R.CONSTRAINT_TYPE&&r!==void 0&&i!==void 0)||Ai(i,r.secondaryConstraintType)?e:{...e,dataDatePatch:{secondaryConstraintType:null,secondaryConstraintDate:null},confirmation:re.CLEAR_SECONDARY_CONSTRAINT}}function Lk(t,e,n,r,i,a){let o=t.p6;return o!==void 0&&n.dataDateCapability!==null&&At(n.dataDateSettings,n.dataDateEnabled)?r===R.PHYSICAL_PERCENT_COMPLETE?Nk(t,o,e):r===R.PROGRESS?Ok(t,o,e,i,a):r===R.DURATION?Fk(o,e):r===R.END_DATE?wk(t,o,e,n):r===R.START_DATE?Mk(o,e,n):e:e}function Ok(t,e,n,r,i){let a=n.patch.progress,o=i??(typeof a=="number"?{progress:a,explicitCompletion:!1,writesProgress:!0}:void 0);return o===void 0?n:Em(t,e,n,o,r)}function Nk(t,e,n){let r=n.dataDatePatch?.physicalPercentComplete;return e.executionStatus!==et.NOT_STARTED||r===void 0||r<=0?n:{...n,dataDatePatch:{actualStart:t.startDate,physicalPercentComplete:r},confirmation:re.START_ON_PROGRESS}}function Fk(t,e){let n=e.patch.durationHours;return typeof n!="number"?null:t.executionStatus===et.NOT_STARTED?{...e,dataDatePatch:{originalDurationHours:n,remainingDurationHours:n}}:{...e,patch:{durationHours:n},dataDatePatch:{originalDurationHours:n}}}function wk(t,e,n,r){let i=Lr(e,r.dataDateSettings,Ae.RESIZE_END,r.dataDateEnabled);if(!i.allowed)return Ud(i);let a=n.patch.endDate,o=r.ctx.calendars.getCalendar(t.calendarId);if(!(a instanceof Date)||o===null)return null;let s=r.dataDateCapability?.prepareFinishEdit(e,a,o);return s==null?null:{...n,patch:xk(n.patch),dataDatePatch:s}}function xk(t){let{constraintType:e,constraintDate:n,...r}=t;return r}function Mk(t,e,n){let r=Lr(t,n.dataDateSettings,Ae.MOVE,n.dataDateEnabled);return r.allowed?e:Ud(r)}function Uk(t,e,n){let r=n.dataDateSettings,i=n.ctx.calendars.getCalendar(t.calendarId);if(!At(r,n.dataDateEnabled)||i===null)return{p6:e,patch:{}};let a=n.dataDateCapability.projectLocalActivity(t.p6,e,{calendar:i,dataDate:r.dataDate,totalFloatMethod:r.totalFloatMethod});return{p6:a.p6,patch:{...a.startDate===void 0?{}:{startDate:a.startDate},...a.endDate===void 0?{}:{endDate:a.endDate}}}}async function Om(t,e,n){let{adapter:r,ctx:i,scheduler:a,sector:o}=n,s=he(t.column);if(!s)return{ok:!1,reason:C.NO_PIPELINE_FOR_COLUMN};let l=i.activityReader.getActivity(t.activityId);if(!l)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let c=Fi(s,l,n,t.column);if(!c.allowed)return{ok:!1,reason:c.reason??C.CANNOT_EDIT,alertKey:c.alertKey};let d=s.parseInput(t.newValue,l,i);if(!d.ok)return{ok:!1,reason:d.reason??C.PARSE_ERROR};let u=Oi(l,s.targetField),p=s.validate(l,u,d.value,i);if(!p.valid)return{ok:!1,reason:p.reason??C.INVALID,alertKey:p.notification?.messageKey};if(t.column===R.CUSTOM_ID&&d.value!==null){let j=r.getActivity(t.activityId),w=j?j.customId:null,B=typeof w=="string"?w:null;if(n.customIdTracker.isCustomIdInUse(String(d.value),B))return{ok:!1,reason:C.CUSTOM_ID_DUPLICATE}}let y=s.transform(l,d.value,i,d.raw),f=Or(l,y,n,t.column,e.confirmations);if(!f.accepted)return{ok:!1,reason:f.reason,...f.alertKey?{alertKey:f.alertKey}:{},...f.confirmation?{confirmation:f.confirmation}:{}};let m=f.changes,A=Kn(t.activityId,m),g=await dt(r,A),P=bi(r,String(t.activityId)),L=l.constraintDate;Yn(r,t.activityId,m),Un(t.activityId,m.postProcessors??[],r,g.get(String(t.activityId))??null);let F=Li(P,r,String(t.activityId));if(t.column===R.CUSTOM_ID){let j=g.get(String(t.activityId)),w=j?j.customId:null,B=typeof w=="string"?w:null,$=typeof d.value=="string"?d.value:null;B!==$&&n.customIdTracker.trackCustomIdChange(B,$)}let T=()=>({action:t,autoscheduleFrom:m.needsAutoSchedule?String(t.activityId):null,recomputeParentsFrom:[],collectDirty:j=>vs(t.activityId,A,j),now:n.now,options:e}),x=Pi(t.column),{scheduledIds:S}=await(x?Zs({adapter:r,scheduler:a,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{postMutationArgs:T(),revertTargets:Js(t.column)?[]:[{activityId:t.activityId,priorConstraintDate:L}],revert:(j,w)=>Xs(j,w,r,i.calendars)}):ot({adapter:r,scheduler:a,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},T())),k=(m.trackingEvents??[]).map(j=>({name:j.name,properties:j.properties??{}}));s.trackEvent&&!(t.column===R.PROGRESS&&Number(d.value)<=0)&&k.unshift({name:s.trackEvent,properties:{activity_name:l.name,activity_id:l.id,activity_index:l.correlativeId}});let E=Dr(t.activityId,m.constraintWarning);return{ok:!0,changes:await tt(r,{source:t,beforeSnap:g,touchedIds:A,scheduledIds:S,sirDetection:Xt.BEFORE_DIFF,links:F,trackingEvents:k,...E?{warnings:[E]}:{},hoursPerDay:o.hoursPerDay})}}function tl(t){return Do(t)}function el(t,e){return Object.hasOwn(t,e)}function Hk(t){if(t.kind===I.LINK_CREATE)return tl(t.type)?t.lag===void 0||Number.isFinite(t.lag)?null:C.INVALID_LINK_LAG:C.INVALID_LINK_TYPE;if(t.kind===I.LINK_UPDATE){if(el(t,"type")&&!tl(t.type))return C.INVALID_LINK_TYPE;if(el(t,"lag")&&!Number.isFinite(t.lag))return C.INVALID_LINK_LAG}return null}function Bk(t){return t.kind===Pt.CREATE?tl(t.type)?t.lag===void 0||Number.isFinite(t.lag)?null:C.INVALID_LINK_LAG:C.INVALID_LINK_TYPE:t.kind===Pt.UPDATE?el(t,"type")&&!tl(t.type)?C.INVALID_LINK_TYPE:!el(t,"lag")||Number.isFinite(t.lag)?null:C.INVALID_LINK_LAG:t.kind===Pt.DELETE?null:C.INVALID_VALUE}function jk(t){for(let e of t){let n=Bk(e);if(n!==null)return n}return null}function Vk(t,e){let n=new Set,r=new Map;for(let i of t){if(i.kind===Pt.CREATE){n.add(String(i.source)),n.add(String(i.target));continue}let a=e.getLink(i.linkId);a&&(n.add(String(a.source)),n.add(String(a.target)),i.kind===Pt.UPDATE&&(i.source!==void 0&&n.add(String(i.source)),i.target!==void 0&&n.add(String(i.target))),r.set(i.linkId,{...a}))}return{activityIds:n,links:r}}function Wk(t,e,n,r,i=!1){return t.map((a,o)=>{let s=a.kind===Pt.CREATE?r?.get(o):void 0,l=qe(a,{port:e,newLinkId:s?()=>s:n.next,rejectParentLinkMutations:i});return{op:a,finalLinkId:l.applied?l.linkId:null,rejected:l.applied?null:l.rejected??C.INVALID}})}function Kk(t){return new Map([...t].map(([e,n])=>[String(e),n]))}async function Nm(t,e,n){let r=Hk(t);return r!==null?{ok:!1,reason:r}:ja([Jk(t,n.sector.hoursPerDay)],t,e,n,t.kind===I.LINK_CREATE&&t.linkId?new Map([[0,t.linkId]]):void 0)}async function Fm(t,e,n){let r=jk(t.operations);if(r!==null)return{ok:!1,reason:r};let{hoursPerDay:i}=n.sector,a=t.operations.map(s=>qk(s,i)),o=Yk(t.operations);return ja(a,t,e,n,o)}function Yk(t){let e=new Map;return t.forEach((n,r)=>{n.kind===Pt.CREATE&&n.linkId&&e.set(r,n.linkId)}),e.size>0?e:void 0}function Gk(t,e){if(t===void 0)return;let n=new Map,r=new Set,i=()=>{let a=e.linkIdGen.next();for(;e.adapter.getLink(a)!==null||e.isLinkIdReserved(String(a))||r.has(String(a));)a=e.linkIdGen.next();return a};for(let[a,o]of t){let s=e.adapter.getLink(o)!==null||e.isLinkIdReserved(String(o))||r.has(String(o)),l=s?i():o;s||e.linkIdGen.bump(o),r.add(String(l)),n.set(a,l)}return n}function qk(t,e){return t.kind===Pt.CREATE?{kind:Pt.CREATE,source:t.source,target:t.target,type:t.type,lag:Ee(t.lag??0,e)}:t.kind===Pt.UPDATE?{kind:Pt.UPDATE,linkId:t.linkId,source:t.source,target:t.target,type:t.type,lag:t.lag===void 0?void 0:Ee(t.lag,e)}:{kind:Pt.DELETE,linkId:t.linkId}}async function ja(t,e,n,r,i){let{adapter:a,scheduler:o,sector:s,linkIdGen:l}=r;o.invalidateAllCaches();let{activityIds:c,links:d}=Vk(t,a),u=await dt(a,c),p=Wk(t,a,l,Gk(i,r),n.rejectParentLinkMutations);if(t.length===1&&p[0]&&p[0].rejected!==null&&e.kind!==I.INLINE_EDIT)return{ok:!1,reason:p[0].rejected};let y=$k(p,d,a),{scheduledIds:f,warnings:m}=await ot({adapter:a,scheduler:o,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId,runAutomaticP6Schedule:r.runAutomaticP6Schedule},{action:e,autoscheduleFrom:y,recomputeParentsFrom:c,now:r.now,options:n}),A=qn(p,d,a);return{ok:!0,linkVerdicts:p.map((g,P)=>g.rejected===null?{operationIndex:P,kind:g.op.kind,ok:!0,linkId:String(g.finalLinkId)}:{operationIndex:P,kind:g.op.kind,ok:!1,reason:g.rejected}),__beforeLinks:Kk(d),changes:await tt(a,{source:e,beforeSnap:u,touchedIds:c,scheduledIds:f,links:A,warnings:m,hoursPerDay:s.hoursPerDay})}}function $k(t,e,n){for(let r of t){if(r.rejected!==null)continue;let i=zk(r.op,e,n);if(i!==null)return n.hasChildren(i)?Et.ROOTS:String(i)}return null}function zk(t,e,n){return t.kind===Pt.CREATE?t.target:t.kind===Pt.DELETE?e.get(t.linkId)?.target??null:n.getLink(t.linkId)?.target??null}function Jk(t,e){return t.kind===I.LINK_CREATE?{kind:Pt.CREATE,source:t.source,target:t.target,type:t.type,lag:Ee(t.lag??0,e)}:t.kind===I.LINK_UPDATE?{kind:Pt.UPDATE,linkId:t.linkId,source:t.source,target:t.target,type:t.type,lag:t.lag===void 0?void 0:Ee(t.lag,e)}:{kind:Pt.DELETE,linkId:t.linkId}}async function wm(t,e,n){let{adapter:r,sector:i}=n;if(typeof t.newValue!="string")return{ok:!1,reason:C.INVALID_VALUE};if(!r.getActivity(t.activityId))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let o=t.column===R.CUSTOM_PREDECESSORS,{specs:s,errors:l}=ns(t.newValue,{daysPerWeek:i.hoursPerWeek/i.hoursPerDay});if(l.length>0)return{ok:!1,reason:C.INVALID_VALUE};let c=s.map(f=>({...f,lag:Ee(is(f.lag),i.hoursPerDay)})),d=new Map;r.forEachActivity(f=>{f.correlativeId!=null&&d.set(String(f.correlativeId),f.id)});let u=f=>d.get(f)??null,p=ki(r,t.activityId,o),y=o?di({targetActivityId:t.activityId,currentLinks:p,desiredSpecs:c,resolveActivityByCorrelative:u}):ui({sourceActivityId:t.activityId,currentLinks:p,desiredSpecs:c,resolveActivityByCorrelative:u});return ja(y.operations,t,e,n)}var ke={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 Ut(t){t.invalidateVisualOrderIds?.();let e=[];t.forEachActivity(a=>{q(a.parentId)&&e.push(a)}),e.sort(Um);let n=[];xm(n,e);let r=[],i=0;for(;n.length>0;){let a=n.pop();if(a.correlativeId!==i){let s=typeof a.correlativeId=="number"?a.correlativeId:void 0;r.push({activityId:String(a.id),before:s}),s!==void 0&&t.noteCorrelativeBefore?.(String(a.id),s),Xk(a,i)}i+=1;let o=hr(String(a.id),t);o.sort(Um),xm(n,o)}return r}function xm(t,e){for(let n=e.length-1;n>=0;n-=1)t.push(e[n])}function Mm(t){let e=t.correlativeId,n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?n:Tc}var Um=(t,e)=>Mm(t)-Mm(e);function Xk(t,e){t.correlativeId=e}function Hd(t,e){if(!t||t==="0")return;let n=String(t);for(;n!==null;){let{workHours:r,realWorkHours:i}=jm(n,e);e.setActivityField(n,O.WORK_HOURS,r),e.setActivityField(n,O.REAL_WORK_HOURS,i);let a=e.getActivity(n);if(!a)break;let o=a.parentId;if(!o||q(o))break;n=o}}function Hm(t,e){let n=e.getActivity(t);if(!n)return;let r=n.parentId;!r||q(r)||Hd(r,e)}function Bm(t,e,n){for(let r of t){if(n.hasChildren(r))continue;let i=n.getActivity(r);i&&n.setActivityField(r,O.REAL_WORK_HOURS,ye(Va(i,O.WORK_HOURS),Va(i,O.PROGRESS)))}for(let r of e)n.setActivityField(r,O.REAL_WORK_HOURS,jm(r,n).realWorkHours)}function jm(t,e){let n=0,r=0;for(let i of e.getChildren(t)){let a=e.getActivity(i);if(!a)continue;let o=Va(a,O.WORK_HOURS);n+=o,r+=Zk(i,a,o,e)}return{workHours:n,realWorkHours:r}}function Va(t,e){let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:0}function Zk(t,e,n,r){return r.hasChildren(t)?Va(e,O.REAL_WORK_HOURS):ye(n,Va(e,O.PROGRESS))}function Bd(t,e){if(!t||t==="0")return;let n=String(t);for(;n!==null;){let r=e.getChildren(n),i=0;for(let s of r){let l=e.getActivity(s);l&&(i+=Qk(l,O.USED_COST))}e.setActivityField(n,O.USED_COST,i);let a=e.getActivity(n);if(!a)break;let o=a.parentId;if(!o||q(o))break;n=o}}function Vm(t,e){let n=e.getActivity(t);if(!n)return;let r=n.parentId;!r||q(r)||Bd(r,e)}function Qk(t,e){let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:0}function jd(t,e){if(!t||t==="0")return;let n=String(t);for(;n!==null;){let r=e.getChildren(n),i=0;for(let s of r){let l=e.getActivity(s);l&&(i+=tb(l,O.COST))}e.setActivityField(n,O.COST,i);let a=e.getActivity(n);if(!a)break;let o=a.parentId;if(!o||q(o))break;n=o}}function Wm(t,e){let n=e.getActivity(t);if(!n)return;let r=n.parentId;!r||q(r)||jd(r,e)}function tb(t,e){let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:0}var nl=Object.freeze({proplannerId:null,description:"",type:U.TASK,progress:0,constraintType:_.ASAP,constraintDate:null,autoScheduling:!0,assignedDefaultCalendar:!1,dateOrigin:null,cost:0,usedCost:0,realCost:0,workHours:0,realWorkHours:0,ponderator:0,hasCustomPonderator:!1,correlativeId:0,customId:null,subcontractId:null,isLookahead:!1,hasLookaheadTasks:!1,newActivityIds:me([]),hasNewActivities:!1,pendingRequestIds:me([]),responsableIds:me([]),tagIds:me([]),baselinePoints:me([]),baselineSnapshot:null,baselineVarianceDays:null,projectBaselineVarianceDays:null,primaryBaselineVarianceDays:null,recursiveDurationHours:0,isCritical:!1,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}),Km="New Master Plan",Ym="New Activity";var eb=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],rl=new Set(eb);function nb(t){let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype)throw new Error("activity-create: override bag must be a plain object with no custom prototype");for(let n of Reflect.ownKeys(t))if(typeof n=="symbol"||!rl.has(n))throw new Error(`activity-create: rejected override key "${String(n)}" \u2014 not a creation-writable canonical field`);return t}function Gm(t,e){let n=t.parentId!=null?e.getActivity(t.parentId):null,r=nb(t.activityOverrides??{}),i=t.numTasksInGantt===0?Km:Ym,a=r.name??i,o=r.durationHours??t.sector.hoursPerDay,s=r.calendarId??t.sector.defaultCalendar,l=rb(n,t.fallbackStartDate,r.startDate),c={...nl,...r,id:t.id,parentId:t.parentId,uniqueCorrelativeId:t.nextUniqueCorrelativeId,name:a,durationHours:o,calendarId:s,startDate:l,endDate:l},d=r.startDate?new Date(c.startDate):e.getClosestWorkTime({date:c.startDate,dir:yt.FUTURE,task:c});if(!r.startDate&&n&&an(n.type)){let y=new Date(n.startDate);y.setUTCHours(0,0,0,0);let f=new Date(d);f.setUTCHours(0,0,0,0),f.getTime()!==y.getTime()&&(d=e.getClosestWorkTime({date:y,dir:yt.FUTURE,task:c}))}let u=e.calculateEndDate({startDate:d,durationHours:c.durationHours,task:c});return{newTask:{...c,startDate:d,endDate:u,calendarDuration:Ge({type:c.type,startDate:d,endDate:u}),newActivityIds:[...c.newActivityIds],pendingRequestIds:[...c.pendingRequestIds],responsableIds:[...c.responsableIds],tagIds:[...c.tagIds],baselinePoints:[...c.baselinePoints]}}}function rb(t,e,n){return n?new Date(n):t?new Date(t.startDate):e?new Date(e):new Date}var il={END:"end"};function al(t,e){return hr(t,e).sort(Rn).map(n=>n.id)}function ib(t){let e=al("0",t),[n]=e;if(e.length===1&&n!==void 0){let i=al(n,t).at(-1);return i===void 0?{ok:!0,parentId:n}:{ok:!0,parentId:n,afterSiblingId:i}}let r=e.at(-1);return r===void 0?{ok:!0,parentId:"0"}:{ok:!0,parentId:"0",afterSiblingId:r}}function Vd(t,e){if("placement"in t)return t.placement===il.END?ib(e):{ok:!1,reason:C.INVALID};let{afterSiblingId:n}=t,r=e.getActivity(n);return r?r.parentId==null?e.getRootIds().length===1?{ok:!0,parentId:r.id,beforeSiblingId:al(r.id,e)[0]}:{ok:!0,parentId:"0",afterSiblingId:n}:e.hasChildren(r.id)?{ok:!0,parentId:r.id,beforeSiblingId:al(r.id,e)[0]}:{ok:!0,parentId:String(r.parentId),afterSiblingId:n}:{ok:!1,reason:C.ANCHOR_SIBLING_NOT_FOUND}}function ab(t,e){let n="placement"in t?e.afterSiblingId:t.afterSiblingId;return{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,...n===void 0?{}:{customIdReferenceId:n}}}var qm=()=>({ok:!1,reason:C.ACTIVITY_PASTE_INVARIANT_FAILED});async function $m(t,e,n){let r=n.activityClipboard.value;if(r===null)return{ok:!1,reason:C.CLIPBOARD_EMPTY};let i=Vd(t.destination,n.adapter);if(!i.ok)return i;let a=ab(t.destination,i),o=await dt(n.adapter,new Set),s=new Set,l=new Map,c=[],d;for(let g of r.activities){let P=l.get(g.originalParentId),L=P===void 0?d??i.afterSiblingId:void 0,F=P===void 0&&L===void 0?i.beforeSiblingId:void 0,T=await $n({kind:I.ACTIVITY_CREATE,parentId:P??i.parentId,...L===void 0?{}:{afterSiblingId:L},...F===void 0?{}:{beforeSiblingId:F},overrides:v(g.overrides),eventSource:t.eventSource},n,{...a,confirmedLookaheadParentIds:e.confirmedLookaheadParentIds,lookaheadTasksByActivityId:e.lookaheadTasksByActivityId});if(!T.ok)return T;l.set(g.originalId,T.newId),c.push(T.newId),P===void 0&&(d=T.newId)}let u=Ut(n.adapter),p=new Set(c.map(String)),y=ge(n.adapter,u,p,o,s);for(let g of c)s.add(String(g));let f=[];for(let g of r.links){let P=l.get(g.source),L=l.get(g.target);if(P===void 0||L===void 0)return qm();let F={kind:xt.CREATE,source:P,target:L,type:g.type,lag:g.lag},T=qe(F,{port:n.adapter,newLinkId:n.linkIdGen.next});if(!T.applied)return qm();f.push({op:F,finalLinkId:T.linkId,rejected:null})}let{scheduledIds:m}=await ot({adapter:n.adapter,scheduler:n.scheduler,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:c[0]??null,recomputeParentsFrom:c,now:n.now,options:e}),A=qn(f,new Map,n.adapter);return{ok:!0,changes:await tt(n.adapter,{source:t,beforeSnap:o,deferredCorrelatives:y,touchedIds:s,scheduledIds:m,links:A,hoursPerDay:n.sector.hoursPerDay})}}var ol={HAS_LOOKAHEAD_TASKS:"has_lookahead_tasks"};function wi(t,e){return!Oy(t,{reparented:e}).ok}function sl(t,e){let n=new Set;if(t.length===0)return n;let r=new Map(t.map(a=>[a.activityId,a.newParentId]));if(!wi(e,r))return n;let i=new Map;for(let a of t){let o=new Map(i);if(o.set(a.activityId,a.newParentId),wi(e,o)){n.add(a.activityId);continue}i.set(a.activityId,a.newParentId)}return n}function xi(t,e,n,r){let i=e,a=i==="0",o=Wa(t,i);if(r!==void 0){let l=o.find(c=>c.id===r);if(l){let c=Qt(l),d=o.map(Qt).filter(p=>p<c);return d.length===0?c-1:(Math.max(...d)+c)/2}}if(n!==void 0){let l=o.find(c=>c.id===n);if(l){let c=Qt(l),d=o.map(Qt).filter(p=>p>c);if(d.length===0)return c+1;let u=Math.min(...d);return(c+u)/2}}return o.length===0?0:Math.max(...o.map(Qt))+1}var Nr=Number.MAX_SAFE_INTEGER,zm=Number.MAX_SAFE_INTEGER-1;function Qt(t){let e=t.correlativeId,n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?n:Nr}function Wa(t,e){return hr(e,t)}function Jm(t,e,n){let r=t,i=be(t,n);for(;i!=null&&e.has(i);)r=i,i=be(i,n);return r}function zn(t,e,n){let r=new Set([t]),i=de(n.getActivity(t)?.parentId);for(;i!=="0"&&!r.has(i);){if(e.has(i))return!0;r.add(i),i=de(n.getActivity(i)?.parentId)}return!1}function be(t,e){let n=e.getActivity(t);if(!n)return null;let r=de(n.parentId),i=Te(r,e),a=i.findIndex(o=>String(o)===String(t));return a<=0?null:i[a-1]??null}function Xm(t,e,n,r){let i=Te(e,t).filter(l=>String(l)!==String(r)).map(l=>t.getActivity(l)).filter(l=>l!==null);if(i.length===0)return 0;let a=i.map(Qt);if(n<=0)return a[0]-1;if(n>=a.length)return a[a.length-1]+1;let o=a[n-1],s=a[n];return(o+s)/2}function Mi(t,e){let n=new Set(t),r=[],i=[],a=new Set,o=new Set(n),s=[...t].sort((d,u)=>{let p=e.getActivity(d),y=e.getActivity(u),f=p?Qt(p):Nr,m=y?Qt(y):Nr;return f-m});for(let d of s){if(!e.getActivity(d)){r.push({activityId:d,reason:C.ACTIVITY_NOT_FOUND}),o.delete(d);continue}if(zn(d,a,e))continue;let p=qp(d,o,e);if(p==null){r.push({activityId:d,reason:C.INDENT_NO_ELIGIBLE_SIBLING}),o.delete(d);continue}let y=e.getActivity(d)?.parentId,f=q(y)?"0":String(y);i.push({activityId:d,newParentId:p,oldParentId:f}),a.add(d)}let l=sl(i,e);for(let d of l)r.push({activityId:d,reason:C.HIERARCHY_CYCLE});let c=i.filter(d=>!l.has(d.activityId));return{moves:i,cyclicMoveIds:l,allowedMoves:c,failed:r}}function yn(t,e){let n=new Set(e.confirmedLookaheadParentIds),r=e.lookaheadTasksByActivityId,i=[...new Set(t.filter(o=>!n.has(String(o.id))&&(r?.[String(o.id)]??o.hasLookaheadTasks)).map(o=>String(o.id)))],[a]=i;return a===void 0?null:{ok:!1,reason:C.CONFIRMATION_REQUIRED,confirmation:{kind:ol.HAS_LOOKAHEAD_TASKS,activityId:a,...i.length>1?{activityIds:i}:{}}}}function fn(t,e){let n=new Map;for(let r of t){let i=e.getActivity(r);i&&e.getChildren(r).length===0&&n.set(String(i.id),i)}return[...n.values()]}function Zm(t,e,n){return tg(t,e,n).map(r=>String(r.id))}function Qm(t,e,n,r){let i=yn(tg(t,n,r),e);return i===null?null:i.confirmation}function tg(t,e,n){let r=[];for(let i of t)r.push(...ob(i,e,n).map(String));return fn(r,e)}function ob(t,e,n){switch(t.kind){case I.ACTIVITY_CREATE:return[t.parentId];case I.ACTIVITY_MOVE:{let r=e.getActivity(t.activityId);return r?de(r.parentId)===String(t.parentId)?[]:sb(t,e)?[]:[t.parentId]:[]}case I.ACTIVITY_INDENT:return Mi(t.activityIds,e).allowedMoves.map(r=>r.newParentId);case I.ACTIVITY_PASTE_COPIED:{if(!n)return[];let r=Vd(t.destination,e);return r.ok?[r.parentId]:[]}case Ye:return t.mode===Mt.APPEND?t.items.flatMap(r=>typeof r.parent=="string"?[r.parent]:[]):[];default:return[]}}function sb(t,e){return q(t.parentId)?!1:t.parentId===t.activityId||e.isChildOf(t.parentId,t.activityId)?!0:wi(e,new Map([[t.activityId,t.parentId]]))}var lb=new Set([...[...rl].filter(t=>t!==O.DURATION_HOURS),"durationDays"]);function ll(t,e){if(t===void 0)return{ok:!0,value:{}};let n=Object.getPrototypeOf(t);if(n!==null&&n!==Object.prototype)return{ok:!1,reason:C.INVALID_VALUE};for(let a of Reflect.ownKeys(t))if(typeof a=="symbol"||!lb.has(a))return{ok:!1,reason:C.INVALID_VALUE};let{durationDays:r,...i}=t;return r!==void 0&&(!Number.isFinite(r)||r<0)?{ok:!1,reason:C.INVALID_VALUE}:{ok:!0,value:{...i,...r===0&&(i.type===void 0||i.type===U.TASK)?{type:U.MILESTONE}:{},...r===void 0?{}:{durationHours:gr(r,e)}}}}function qt(t,e){Hd(t,e),Bd(t,e),jd(t,e)}function Ui(t,e){let n=new Set,r=[];for(let i of t){let a=String(i);n.has(a)||(n.add(a),r.push(a))}for(;r.length>0;){let i=r.pop(),a=e.getChildren(i);for(let o of a){let s=String(o);n.has(s)||(n.add(s),r.push(s))}}return n}function Jn(t,e){let n=new Set;for(let r of t){for(let i of e.getOutgoingLinkIds(r))n.add(String(i));for(let i of e.getIncomingLinkIds(r))n.add(String(i))}return[...n]}function cb(t){return t?{type:t.type,startDate:new Date(t.startDate),endDate:new Date(t.endDate),durationHours:t.durationHours,expectedProgressBaseline:t.expectedProgressBaseline,constraintType:t.constraintType,constraintDate:t.constraintDate?new Date(t.constraintDate):null,progress:t.progress}:null}function db(t,e,n){let r=t.startDate;return!n||!(r instanceof Date)?{}:{endDate:n(r,e)}}function Xe(t){if(t.remainingChildIds.length>0)return null;let e=t.parent,n=t.defaultDurationHours,r=Number.isFinite(n),i=cb(t.promotionSnapshot)??(r?{type:ei,durationHours:n,progress:0,autoScheduling:!0,constraintType:_.ASAP,constraintDate:null,hasNewActivities:!1,...db(e,n,t.computeEndDate)}:{type:ei});if(t.idsRemoved&&t.idsRemoved.size>0){let o=Array.isArray(e.newActivityIds)?e.newActivityIds:[];if(o.length>0){let s=o.filter(l=>!t.idsRemoved.has(l)&&!t.idsRemoved.has(String(l)));s.length!==o.length&&(i.newActivityIds=s)}}e.hasLookaheadTasks&&(i.isLookahead=!0);let a=ub(e,i);return t.dataDateCapability&&a&&Object.assign(i,t.dataDateCapability.parentDemoted({activity:a,hasCompleteSchedulingState:t.hasCompleteSchedulingState===!0,promotionSnapshot:t.promotionSnapshot})),{parentId:String(e.id),fields:i}}function ub(t,e){let n=e.startDate??t.startDate,r=e.endDate??t.endDate,i=e.durationHours??t.durationHours,a=e.progress??t.progress,o=e.type??t.type;return!(n instanceof Date)||!(r instanceof Date)||typeof i!="number"||typeof a!="number"?null:{type:o,startDate:n,endDate:r,durationHours:i,progress:a}}function cl(t){if(t.idsRemoved.size===0)return null;let e=t.parent.newActivityIds;if(!Array.isArray(e)||e.length===0)return null;let n=e,r=n.filter(i=>!t.idsRemoved.has(i)&&!t.idsRemoved.has(String(i)));return r.length===n.length?null:{parentId:String(t.parent.id),fields:{newActivityIds:[...r],hasNewActivities:r.length>0}}}var eg=200;async function ng(t,e,n){let{adapter:r,scheduler:i,customIdTracker:a,sector:o}=n;if(i.invalidateAllCaches(),t.activityIds.length===0)return{ok:!1,reason:C.ACTIVITY_IDS_EMPTY};for(let k of t.activityIds)if(!r.getActivity(k))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let s=t.activityIds.filter(k=>{let E=r.getActivity(k);return!(E?.correlativeId===0&&E.type===U.PROJECT)}),l=Ui(s,r),c=Jn(l,r),d=new Set;for(let k of t.activityIds){let E=r.getActivity(k);if(!E)continue;let j=E.parentId;if(q(j))continue;let w=String(j);l.has(w)||d.add(w)}let u=new Set([...l,...d]),p=await dt(r,u),y=new Map;for(let k of c){let E=r.getLink(k);E&&y.set(k,{...E})}let f=new Set,m=0;for(let k of l){m+=1,m%eg===0&&await Ot();let E=r.getActivity(k);if(!E)continue;let j=q(E.parentId)?null:r.getActivity(String(E.parentId)),w=j?.hasNewActivities===!0&&j.newActivityIds.some($=>String($)===String(k));(E.isNewActivity===!0||w)&&f.add(k);let B=E.customId;typeof B=="string"&&B.length>0&&a.releaseCustomId(B)}for(let k of c)r.removeLink(k);let A=Fr(r,l),g=0;for(let k of l)g+=1,g%eg===0&&await Ot(),r.removeActivity(k);for(let k of d){let E=r.getActivity(k);if(!E)continue;pb(E,f,r);let j=r.getChildren(k),w=Xe({parent:E,remainingChildIds:j.map(String),defaultDurationHours:o.hoursPerDay,promotionSnapshot:r.getPromotionSnapshot(k),computeEndDate:(B,$)=>r.calculateEndDate({startDate:B,durationHours:$,task:E}),idsRemoved:l,dataDateCapability:n.dataDateCapability,hasCompleteSchedulingState:n.hasCompleteSchedulingState});if(!w){os(k,r);continue}if(r.setActivityFields(k,w.fields),E.customId==null||E.customId===""){let B=be(k,r),$=B?r.getActivity(B)?.customId:null,ft=a.generateCustomIdForRestoredChild(typeof $=="string"&&$?$:null);r.setActivityField(k,O.CUSTOM_ID,ft)}}for(let k of d)qt(k,r);let P=Ut(r),{scheduledIds:L}=await ot({adapter:r,scheduler:i,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:Et.ROOTS,recomputeParentsFrom:d,now:n.now,options:e}),F={name:ke.ACTIVITY_DELETION,properties:{activity_ids:[...t.activityIds],cascade_count:l.size}};t.eventSource!==void 0&&(F.properties.event_source=t.eventSource);let T=new Map;for(let[k,E]of y)T.set(k,E);let x=new Map;for(let k of l){let E=p.get(String(k));E&&x.set(String(k),E)}let S=await tt(r,{source:t,beforeSnap:p,touchedIds:u,scheduledIds:L,sirDetection:Xt.AFTER_DIFF,links:te(y),trackingEvents:[F],hoursPerDay:o.hoursPerDay,correlativeShifts:P});return{ok:!0,changes:A.length>0?{...S,viewState:A}:S,__beforeSnap:x,__beforeLinks:T}}function pb(t,e,n){let r=cl({parent:t,idsRemoved:e});if(r)for(let[i,a]of Object.entries(r.fields))Se(n,r.parentId,i,a)}function Fr(t,e){let n=[];for(let r of e){let i=t.isChecked(r),a=t.isVisible(r);!i&&a||n.push({activityId:String(r),...i?{checked:{before:!0,after:!1}}:{},...a?{}:{visible:{before:!1,after:!0}}})}return n}function te(t){let e=[];for(let[n,r]of t.entries())e.push({id:n,kind:W.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 e}var Hi={CREATE:"create",REPARENT:"reparent"};function yb(t,e={}){let n=t.type;if(n!==U.TASK&&n!==U.MILESTONE)return null;let r=t.startDate,i=t.endDate;return!(r instanceof Date)||!(i instanceof Date)?null:{type:n,startDate:new Date(r),endDate:new Date(i),durationHours:Number(t.durationHours??0),expectedProgressBaseline:typeof t.expectedProgressBaseline=="number"?t.expectedProgressBaseline:null,constraintType:t.constraintType??null,constraintDate:t.constraintDate instanceof Date?new Date(t.constraintDate):null,progress:Number(t.progress??0),...e}}function rg(t){let e=t.getParent(t.parentId);if(!e)return null;let n=t.isCurrentlyLeaf!==void 0?t.isCurrentlyLeaf&&kn(e.type):fb(e),r=Array.isArray(e.newActivityIds)?e.newActivityIds:[],a={isLookahead:!1,hasNewActivities:!0,newActivityIds:r.some(s=>String(s)===String(t.newChildId))?[...r]:[...r,t.newChildId]},o=n?t.dataDateCapability?.parentPromoted(e):void 0;return e.customId!=null&&e.customId!==""&&(a.customId=null),n&&(a.type=bc,o&&Object.assign(a,o.activityPatch),(t.promotionSource??Hi.CREATE)===Hi.CREATE&&(a.constraintType=_.ASAP,a.constraintDate=null)),{parentId:t.parentId,fields:a,promotionSnapshot:yb(e,o?.snapshotPatch)}}function fb(t){return kn(t.type)&&(!Array.isArray(t.newActivityIds)||t.newActivityIds.length===0)}function Xn(t,e){let r=e.adapter.getActivity(t.parentId)?.customId??null,i=rg({...t,getParent:o=>e.adapter.getActivity(o)??null,dataDateCapability:e.dataDateCapability});if(!i)return{applied:!1,removedLinks:new Map};let a=i.fields.type===U.PROJECT?hb(t.parentId,e):new Map;for(let[o,s]of Object.entries(i.fields))Se(e.adapter,i.parentId,o,s);return i.promotionSnapshot&&e.adapter.setPromotionSnapshot(i.parentId,i.promotionSnapshot),i.fields.customId===null&&e.customIdTracker.releaseCustomId(r),{applied:!0,removedLinks:a}}function hb(t,e){let n=new Map,r=new Set([...e.adapter.getIncomingLinkIds(t),...e.adapter.getOutgoingLinkIds(t)]);for(let i of r){let a=e.adapter.getLink(i);a&&(n.set(String(i),{...a}),e.adapter.removeLink(i))}return n}async function $n(t,e,n={}){let{adapter:r,scheduler:i,sector:a,calendars:o,activityIdGen:s,uidGen:l}=e;n.skipCacheInvalidation||i.invalidateAllCaches();let c=mb(t,r,n);if(!c.ok)return c;let{parent:d,anchorSiblingId:u,isRoot:p}=c,y=Ab(t.activityId,r,s,e.isActivityIdReserved),f=l.next(),m={id:y,parentId:p?null:t.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:Db(o)},numTasksInGantt:r.activityCount(),nextUniqueCorrelativeId:f,activityOverrides:t.overrides??{},...e.actionAt?{fallbackStartDate:e.actionAt}:{}},g=Gm(m,{getActivity:k=>r.getActivity(k),calculateEndDate:k=>r.calculateEndDate(k),getClosestWorkTime:k=>r.getClosestWorkTime(k)}).newTask;e.dataDateCapability!==null&&Object.assign(g,e.dataDateCapability.activityCreated({activity:g,hasCompleteSchedulingState:e.hasCompleteSchedulingState})),g.realWorkHours=ye(g.workHours,g.progress),Sb(g,t,e,u,d,n);let P=n.insertionCorrelativeId??xi(r,p?"0":t.parentId,t.afterSiblingId,t.beforeSiblingId);g.correlativeId=P;let L=new Set([y]);d&&L.add(d.id);let F=d!==null&&r.getChildren(d.id).length===0,T=n.skipBeforeSnap?new Map:await dt(r,L);r.addActivity(g);let x=d?Xn({parentId:d.id,newChildId:y,isCurrentlyLeaf:F},e).removedLinks:new Map;n.skipRollupCascades||(Hm(y,r),Vm(y,r),Wm(y,r));let S=vb(r,y,L,n);return{ok:!0,newId:y,parent:d,newActivity:g,beforeSnap:T,initialTouched:L,correlativeShifts:S,removedParentLinks:x}}function mb(t,e,n){let r=q(t.parentId),i=r?null:e.getActivity(t.parentId);if(!r&&!i)return{ok:!1,reason:C.PARENT_NOT_FOUND};if(i!==null&&Ri(i))return{ok:!1,reason:C.PARENT_FROZEN_BY_SIR};if(t.afterSiblingId!==void 0&&t.beforeSiblingId!==void 0)return{ok:!1,reason:C.ANCHOR_SIBLING_CONFLICT};let s=t.afterSiblingId??t.beforeSiblingId,l=gb(t,e,r,s);if(l)return l;if(i!==null&&!n.parentsAlreadyChecked){let c=yn(fn([t.parentId],e),n);if(c)return c}return{ok:!0,parent:i,anchorSiblingId:s,isRoot:r}}function gb(t,e,n,r){if(r===void 0)return null;let i=e.getActivity(r);if(!i)return{ok:!1,reason:C.ANCHOR_SIBLING_NOT_FOUND};let a=n?"0":t.parentId;return(i.parentId==null?"0":String(i.parentId))!==a?{ok:!1,reason:C.ANCHOR_SIBLING_WRONG_PARENT}:null}function Ab(t,e,n,r){let i=()=>{let a=n.next();for(;e.activityExists(a)||r(String(a));)a=n.next();return a};return t===void 0||e.activityExists(t)||r(String(t))?i():(n.bump(t),t)}function Ib(t){let e=t.overrides?.customId;return typeof e=="string"?e:void 0}function Sb(t,e,n,r,i,a){let{adapter:o,customIdTracker:s}=n,l=Ib(e);if(l!==void 0){if(l.length===0)return;if(!s.isCustomIdInUse(l)){s.registerCustomId(l);return}}let c=a.customIdReferenceId??r,d=c!==void 0,u=d?o.getActivity(c):i;t.customId=s.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function vb(t,e,n,r){if(r.skipCorrelativeRecompute)return[];let i=Ut(t).filter(a=>a.activityId!==String(e));for(let a of i)n.add(a.activityId);return i}async function Cb(t,e,n,r,i){let{newId:a,newActivity:o,beforeSnap:s,initialTouched:l,correlativeShifts:c,removedParentLinks:d}=n,u={name:ke.ACTIVITY_CREATION,properties:{parent_id:e.parentId,activity_id:a,created_duration:o.durationHours}};return e.eventSource!==void 0&&(u.properties.event_source=e.eventSource),tt(t,{source:e,beforeSnap:s,touchedIds:l,scheduledIds:r,correlativeShifts:c,trackingEvents:[u],links:te(new Map(d)),hoursPerDay:i})}async function ig(t,e,n){let{adapter:r,scheduler:i,sector:a}=n,o=ll(t.overrides,a.hoursPerDay);if(!o.ok)return o;let s=await $n({...t,overrides:o.value},n,{confirmedLookaheadParentIds:e.confirmedLookaheadParentIds,lookaheadTasksByActivityId:e.lookaheadTasksByActivityId});if(!s.ok)return s;let{newId:l}=s,c=s.newActivity.autoScheduling;r.setActivityField(l,"autoScheduling",!1);let d;try{d=await ot({adapter:r,scheduler:i,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:l,recomputeParentsFrom:[l],preventSummaryTargetPullback:!0,now:n.now,options:e})}finally{r.setActivityField(l,"autoScheduling",c)}let{scheduledIds:u}=d;return{ok:!0,changes:await Cb(r,t,s,u,a.hoursPerDay),...s.removedParentLinks.size>0?{__beforeLinks:new Map(s.removedParentLinks)}:{}}}function Db(t){for(let n of t.values())if(n.is_default)return n.id;let e=t.values().next();return!e.done&&e.value?e.value.id:"global"}async function sg(t,e,n){let r=_b(t,n);if(r)return{ok:!1,reason:r};let i=Rb(t,n);if(!i.ok)return i;if(t.mode===Mt.APPEND){let T=yn(fn(Tb(i.plan.items),n.adapter),e);if(T)return T}let a=t.mode===Mt.REPLACE?new Set(n.adapter.getAllIds().map(T=>String(T))):new Set,o=t.mode===Mt.REPLACE?await dt(n.adapter,a):new Map,s=t.mode===Mt.REPLACE?Nb(n):new Map,l=t.mode===Mt.REPLACE?Fr(n.adapter,a):[];n.scheduler.invalidateAllCaches();let c=[];if(t.mode===Mt.REPLACE){for(let T of s.keys()){let x=qe({kind:Pt.DELETE,linkId:T},{port:n.adapter});if(!x.applied)return{ok:!1,reason:x.rejected??C.INVALID};c.push({op:{kind:Pt.DELETE,linkId:T},finalLinkId:T,rejected:null})}for(let T of a){let x=n.adapter.getActivity(T)?.customId;typeof x=="string"&&x.length>0&&n.customIdTracker.releaseCustomId(x),n.adapter.removeActivity(T)}}let d=await Ob(t,i.plan.items,n);if(!d.ok)return d;for(let[T,x]of d.removedParentLinks)s.set(T,x),c.push({op:{kind:Pt.DELETE,linkId:T},finalLinkId:T,rejected:null});let u=lg(t)?[]:Ut(n.adapter),p=new Set(i.plan.items.map(T=>String(T.activityId))),y=u.filter(T=>!p.has(T.activityId)),f=t.mode===Mt.REPLACE?new Set(a):new Set,m=ge(n.adapter,u,p,o,f);for(let T of i.plan.items)f.add(String(T.activityId));let A=i.plan.links.map(T=>({operation:{kind:Pt.CREATE,source:T.source,target:T.target,type:T.type,lag:Ee(T.lag??0,n.sector.hoursPerDay)},linkId:T.linkId})),g=Qo(A,{port:n.adapter,preserved:s,rejectParentLinkMutations:e.rejectParentLinkMutations??!1});if(!g.applied)return{ok:!1,reason:g.rejected??C.INVALID};for(let{operation:T,linkId:x}of A)c.push({op:T,finalLinkId:x,rejected:null});let P=i.plan.items.map(T=>T.activityId),{scheduledIds:L}=await ot({adapter:n.adapter,scheduler:n.scheduler,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:t.items.length>0||t.links.length>0?Et.ROOTS:null,recomputeParentsFrom:P,now:n.now,options:e}),F=await tt(n.adapter,{source:t,beforeSnap:o,touchedIds:f,scheduledIds:L,links:qn(c,s,n.adapter),hoursPerDay:n.sector.hoursPerDay,correlativeShifts:y,deferredCorrelatives:m,...t.mode===Mt.REPLACE?{sirDetection:Xt.AFTER_DIFF}:{}});return{ok:!0,changes:l.length>0?{...F,viewState:l}:F,...t.mode===Mt.REPLACE||s.size>0?{...t.mode===Mt.REPLACE?{__beforeSnap:o}:{},__beforeLinks:Fb(s)}:{}}}function Tb(t){return t.filter(e=>e.parentBatchId===null&&e.parentId!=="0").map(e=>String(e.parentId))}function _b(t,e){if(t.mode!==Mt.APPEND&&t.mode!==Mt.REPLACE)return C.INVALID;let n=new Set,r=new Set;for(let a of t.items){if(a.batchId.length===0||n.has(a.batchId))return C.INVALID;if(n.add(a.batchId),a.index!==void 0&&(!Number.isInteger(a.index)||a.index<0))return C.INVALID;if(a.activityId!==void 0){let o=String(a.activityId);if(o.length===0||o==="0"||r.has(o))return C.INVALID;r.add(o)}}for(let a of t.items)if(!Kd(a.parent,!0,t.mode,n,e))return C.PARENT_NOT_FOUND;if(Eb(t.items))return C.INVALID;let i=new Set;for(let a of t.links){if(!Object.values(G).includes(a.type))return C.INVALID_LINK_TYPE;if(a.lag!==void 0&&!Number.isFinite(a.lag))return C.INVALID_LINK_LAG;if(!Kd(a.source,!1,t.mode,n,e)||!Kd(a.target,!1,t.mode,n,e))return C.ACTIVITY_NOT_FOUND;if(a.linkId!==void 0){let o=String(a.linkId);if(o.length===0||i.has(o))return C.INVALID;i.add(o)}}return null}function Kd(t,e,n,r,i){return typeof t=="string"?t==="0"?e:n===Mt.APPEND&&i.adapter.getActivity(String(t))!==null:t!==null&&t.batchId.length>0&&r.has(t.batchId)}function Eb(t){let e=new Map;for(let r of t)typeof r.parent!="string"&&e.set(r.batchId,r.parent.batchId);let n=new Set;for(let r of t){let i=new Set,a=r.batchId;for(;a!==void 0&&!n.has(a);){if(i.has(a))return!0;i.add(a),a=e.get(a)}for(let o of i)n.add(o)}return!1}function Rb(t,e){let n=new Map;for(let d of t.items){let u=ll(d.overrides,e.sector.hoursPerDay);if(!u.ok)return u;n.set(d.batchId,u.value)}let r=new Map,i=new Set;for(let d of t.items){let u=Pb(d.activityId,t.mode,i,e);i.add(String(u)),r.set(d.batchId,u)}let a=new Set,o=t.links.map(d=>{let u=kb(d.linkId,t.mode,a,e);return a.add(String(u)),u}),s=bb(t,r,e),l=[];for(let d of t.items){let u=r.get(d.batchId),p=s.get(d.batchId);if(u===void 0||p===void 0)return{ok:!1,reason:C.INVALID};let y=typeof d.parent=="string"?null:d.parent.batchId,f=typeof d.parent=="string"?d.parent:r.get(d.parent.batchId);if(f===void 0)return{ok:!1,reason:C.PARENT_NOT_FOUND};l.push({input:d,activityId:u,parentId:f,parentBatchId:y,insertionCorrelativeId:p,overrides:n.get(d.batchId)??{}})}let c=[];for(let[d,u]of t.links.entries()){let p=og(u.source,r),y=og(u.target,r),f=o[d];if(p===null||y===null||f===void 0)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};c.push({source:p,target:y,type:u.type,lag:u.lag??0,linkId:f})}return{ok:!0,plan:{items:l,links:c}}}function Pb(t,e,n,r){if(t!==void 0&&(e===Mt.REPLACE||r.adapter.getActivity(t)===null&&!r.isActivityIdReserved(String(t)))&&!n.has(String(t)))return r.activityIdGen.bump(t),t;let a=r.activityIdGen.next();for(;n.has(String(a))||e===Mt.APPEND&&(r.adapter.getActivity(a)!==null||r.isActivityIdReserved(String(a)));)a=r.activityIdGen.next();return a}function kb(t,e,n,r){if(t!==void 0&&(e===Mt.REPLACE||r.adapter.getLink(t)===null&&!r.isLinkIdReserved(String(t)))&&!n.has(String(t)))return r.linkIdGen.bump(t),t;let a=r.linkIdGen.next();for(;n.has(String(a))||e===Mt.APPEND&&(r.adapter.getLink(a)!==null||r.isLinkIdReserved(String(a)));)a=r.linkIdGen.next();return a}function bb(t,e,n){if(lg(t)){let s=n.adapter.activityCount();return new Map(t.items.map((l,c)=>[l.batchId,s+c]))}let r=new Set(Array.from(e.values(),s=>String(s))),i=new Map;for(let s of t.items){let l=e.get(s.batchId);if(l===void 0)continue;let c=typeof s.parent=="string"?s.parent:e.get(s.parent.batchId);if(c===void 0)continue;let d=String(c),u=i.get(d);u||(u={existing:t.mode===Mt.REPLACE||typeof s.parent!="string"&&e.has(s.parent.batchId)?[]:Wa(n.adapter,d).sort((m,A)=>Qt(m)-Qt(A)||String(m.id).localeCompare(String(A.id))).map(m=>String(m.id)),newIdsByTarget:new Map},i.set(d,u));let p=s.index===void 0?u.existing.length:Math.min(s.index,u.existing.length),y=u.newIdsByTarget.get(p)??[];y.push(String(l)),u.newIdsByTarget.set(p,y)}let a=new Map,o=new Map(Array.from(e,([s,l])=>[String(l),s]));for(let s of i.values()){let l=[];for(let d=0;d<=s.existing.length;d+=1){for(let p of s.newIdsByTarget.get(d)??[])l.push(p);let u=s.existing[d];u!==void 0&&l.push(u)}let c=0;for(;c<l.length;){if(!r.has(l[c])){c+=1;continue}let d=c;for(;c<l.length&&r.has(l[c]);)c+=1;let u=c-d,p=d>0?ag(l[d-1],n):null,y=c<l.length?ag(l[c],n):null;for(let f=0;f<u;f+=1){let m=l[d+f],A=o.get(m);A!==void 0&&a.set(A,Lb(p,y,f+1,u))}}}return a}function lg(t){return t.mode===Mt.APPEND&&t.items.every(e=>e.parent==="0"&&e.index===void 0)}function ag(t,e){let n=e.adapter.getActivity(t);return n?Qt(n):0}function Lb(t,e,n,r){return t!==null&&e!==null&&e>t?t+(e-t)*n/(r+1):t!==null?t+n:e!==null?e-(r-n+1):n-1}async function Ob(t,e,n){let r=new Map,i=new Map,a=[];for(let s of e){if(s.parentBatchId===null){a.push(s);continue}let l=r.get(s.parentBatchId)??[];l.push(s),r.set(s.parentBatchId,l)}for(let s=0;s<a.length;s+=1){let l=a[s],c=await $n({kind:I.ACTIVITY_CREATE,parentId:l.parentId,activityId:l.activityId,overrides:l.overrides,...t.eventSource===void 0?{}:{eventSource:t.eventSource}},n,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,skipCacheInvalidation:!0,skipRollupCascades:!0,insertionCorrelativeId:l.insertionCorrelativeId,parentsAlreadyChecked:!0});if(!c.ok)return c;for(let[d,u]of c.removedParentLinks)i.set(d,u);for(let d of r.get(l.input.batchId)??[])a.push(d)}if(a.length!==e.length)return{ok:!1,reason:C.INVALID};let o=new Set;for(let s=a.length-1;s>=0;s-=1){let l=a[s].parentId;l==="0"||o.has(String(l))||(o.add(String(l)),qt(l,n.adapter))}return{ok:!0,removedParentLinks:i}}function og(t,e){return typeof t=="string"?t:e.get(t.batchId)??null}function Nb(t){return new Map(t.adapter.getAllLinks().map(e=>[String(e.id),{...e}]))}function Fb(t){return new Map(Array.from(t,([e,n])=>[String(e),n]))}function cg(t,e){let{adapter:n}=e,r=t.activityId,i=n.getActivity(r);if(!i)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let a=i.pendingRequestIds??[],o=t.pendingRequests.map(c=>c.id);n.setActivityField(t.activityId,"pendingRequestIds",o);let s=n.getActivity(r);if(!s)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let l={id:r,kind:W.UPDATED,fields:{pendingRequestIds:{before:a,after:o}},after:st(s)};return{ok:!0,changes:{source:t,activities:[l],links:[],calendars:[],trackingEvents:[]}}}function wb(t,e){if(t.activities.length===0)return C.INVALID_VALUE;for(let n of t.activities){let r=e.adapter.getActivity(n.activityId);if(!r)return C.ACTIVITY_NOT_FOUND;let i=Object.keys(n.fields);if(i.length===0||!i.every(js)||Vs(r,n.fields))return C.INVALID_VALUE}return null}function xb(t,e){return Hs(t.activities)?null:e.length===1?e[0]:Et.ROOTS}function Mb(t,e){for(let n of e.dirty){let r=e.before.get(n);r&&!t.has(n)&&t.set(n,r)}}async function dg(t,e,n){let r=wb(t,n);if(r!==null)return{ok:!1,reason:r};let{adapter:i,scheduler:a,sector:o}=n,s=t.activities.map(u=>String(u.activityId)),l=i.peekWriteCapture(),c=await dt(i,new Set(l?[...s,...l.dirty]:i.getAllIds()));for(let u of t.activities)i.setActivityFields(u.activityId,Ws(u.fields));Ys(s,n);let{scheduledIds:d}=await ot({adapter:i,scheduler:a,sector:o,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:xb(t,s),recomputeParentsFrom:Ks(i,s),recomputeParentProgress:!0,now:n.now,options:e});return l&&Mb(c,l),{ok:!0,changes:await tt(i,{source:t,beforeSnap:c,touchedIds:i.getAllIds().filter(u=>c.has(u)),scheduledIds:d,sirDetection:Xt.BEFORE_DIFF,links:[],hoursPerDay:o.hoursPerDay})}}function Ub(t){return t.restoreActivities.length===0&&t.removeActivityIds.length===0&&t.activityFields.length===0&&t.restoreLinks.length===0&&t.removeLinkIds.length===0}function Hb(t,e){if(Ub(t))return C.INVALID_VALUE;let n=new Set(t.restoreActivities.map(r=>String(r.id)));for(let r of t.restoreActivities){if(e.adapter.getActivity(r.id))return C.INVALID_VALUE;let i=r.parentId;if(!q(i)&&!n.has(String(i))&&!e.adapter.getActivity(String(i)))return C.PARENT_NOT_FOUND}for(let r of t.activityFields){let i=e.adapter.getActivity(r.activityId);if(!i)return C.ACTIVITY_NOT_FOUND;let a=Object.keys(r.fields);if(a.length===0||!a.every(Bs)||Vs(i,r.fields))return C.INVALID_VALUE}return null}function Bb(t){let e=new Map(t.map(r=>[String(r.id),r])),n=[];for(;e.size>0;){let r=[...e.values()].filter(i=>!e.has(String(i.parentId)));if(r.length===0)return[...n,...e.values()];for(let i of r)n.push(i),e.delete(String(i.id))}return n}function jb(t){return{id:t.linkId,source:t.source,target:t.target,type:t.type,lag:t.lagHours,freeSlackHours:null,isCritical:!1}}function Vb(t){return{id:String(t.id),kind:W.CREATED,fields:{source:{before:void 0,after:String(t.source)},target:{before:void 0,after:String(t.target)},type:{before:void 0,after:t.type},lag:{before:void 0,after:Number(t.lag)}},after:Ft(t)}}function Wb(t){return q(t)?null:String(t)}function Kb(t,e,n){let r=new Set,i=a=>{let o=Wb(a);o!==null&&r.add(o)};for(let a of e)i(n.getActivity(a)?.parentId);for(let a of t.restoreActivities)i(a.parentId);for(let a of t.activityFields)i(n.getActivity(a.activityId)?.parentId),"parentId"in a.fields&&i(a.fields.parentId);return r}function Yb(t,e){let n=new Map;for(let r of t){let i=e.getLink(r);i&&(n.set(r,{...i}),e.removeLink(r))}return n}function Gb(t,{adapter:e,customIdTracker:n}){for(let r of t){let i=e.getActivity(r)?.customId;typeof i=="string"&&i.length>0&&n.releaseCustomId(i),e.removeActivity(r)}}function qb(t,{adapter:e,customIdTracker:n}){for(let r of Bb(t))e.addActivity({...st(r),proplannerId:null}),n.registerCustomId(r.customId)}function $b(t,{adapter:e,customIdTracker:n}){for(let r of t)"customId"in r.fields&&n.trackCustomIdChange(e.getActivity(r.activityId)?.customId??null,r.fields.customId??null),e.setActivityFields(r.activityId,Ws(r.fields))}function zb(t,e){let n=t.filter(r=>!e.getLink(r.linkId)&&e.getActivity(r.source)&&e.getActivity(r.target)).map(jb);for(let r of n)e.addLink(r);return n}function Jb(t,e,n){for(let r of Ut(t)){if(e.add(r.activityId),n.has(r.activityId))continue;let i=t.getActivity(r.activityId);if(!i)continue;let a=st(i);r.before!==void 0&&(a.correlativeId=r.before),n.set(r.activityId,a)}}async function ug(t,e,n){let r=Hb(t,n);if(r!==null)return{ok:!1,reason:r};let{adapter:i,scheduler:a,sector:o}=n;a.invalidateAllCaches();let s=Ui(t.removeActivityIds.filter(m=>i.getActivity(m)),i),l=Kb(t,s,i),c=new Set([...s,...t.activityFields.map(m=>String(m.activityId)),...[...l].filter(m=>i.getActivity(m))]),d=await dt(i,c),u=Yb(new Set([...t.removeLinkIds,...Jn(s,i)]),i);Gb(s,n),qb(t.restoreActivities,n);for(let m of t.restoreActivities)c.add(String(m.id));$b(t.activityFields,n),Ys(t.activityFields.map(m=>String(m.activityId)),n);let p=zb(t.restoreLinks,i),y=[...l].filter(m=>i.getActivity(m));for(let m of y)qt(m,i);Jb(i,c,d);let{scheduledIds:f}=await ot({adapter:i,scheduler:a,sector:o,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:Et.ROOTS,recomputeParentsFrom:[...y,...Ks(i,t.activityFields.map(m=>String(m.activityId)))],recomputeParentProgress:!0,now:n.now,options:e});return{ok:!0,changes:await tt(i,{source:t,beforeSnap:d,touchedIds:c,scheduledIds:f,sirDetection:Xt.BEFORE_DIFF,links:[...te(u),...p.map(Vb)],hoursPerDay:o.hoursPerDay})}}var pg=new Map;function yg(t){let e=new Map;for(let n of t){let r=n.proplannerId;typeof r=="number"&&Number.isSafeInteger(r)&&r>0&&e.set(r,String(n.id))}return e}function fg(t,e,n){let r=new Set(e.map(({id:i})=>String(i)));for(let i of t)if((i.proplannerId==null||i.proplannerId===0)&&!r.has(String(i.id)))throw new Error(`persistence-acknowledge: missing ${n} proplannerId for "${String(i.id)}"`)}function Xb(t,e,n,r,i,a){let o=String(t.id);if(o.length===0||i.has(o))throw new Error(`persistence-acknowledge: duplicate or empty ${e} id "${o}"`);if(!Number.isSafeInteger(t.proplannerId)||t.proplannerId<=0)throw new Error(`persistence-acknowledge: invalid ${e} proplannerId ${String(t.proplannerId)}`);if(a.has(t.proplannerId))throw new Error(`persistence-acknowledge: duplicate ${e} proplannerId ${String(t.proplannerId)}`);let s=n(o);if(!s.exists)throw new Error(`persistence-acknowledge: unknown ${e} id "${o}"`);if(s.current!==null&&s.current!==0&&s.current!==t.proplannerId)throw new Error(`persistence-acknowledge: ${e} "${o}" already has proplannerId ${String(s.current)}`);let l=r.get(t.proplannerId);if(l!==void 0&&l!==o)throw new Error(`persistence-acknowledge: ${e} proplannerId ${String(t.proplannerId)} already belongs to "${l}"`);i.add(o),a.add(t.proplannerId)}function hg(t,e,n,r){let i=new Set,a=new Set;for(let o of t)Xb(o,e,n,r,i,a)}async function mg(t,e){let n=t.filter(s=>{let l=e.adapter.getActivity(String(s.activityId));return l!==null&&l.progress!==s.progress}),r=new Set(n.map(s=>String(s.activityId))),i=va(e.adapter,r),a=new Set(r);for(let s of i)a.add(String(s));let o=await dt(e.adapter,a);return e.adapter.batchUpdate(()=>{for(let s of n){let l=String(s.activityId);e.adapter.setActivityField(l,"progress",s.progress),e.adapter.setActivityField(l,"autoScheduling",ue(s.progress))}Ky(i,e.adapter),Bm(r,i,e.adapter)}),[...await Ss(e.adapter,o,a)]}async function gg(t,e){let n=t.activities??[],r=t.links??[],i=t.checkpoint?.activities??e.adapter.getAllActivities(),a=t.checkpoint?.links??e.adapter.getAllLinks(),o=new Map(i.map(y=>[String(y.id),y])),s=new Map(a.map(y=>[String(y.id),y])),l=t.checkpoint?.pending!==void 0,c=n.length===0?pg:yg(l?e.adapter.getAllActivities():i),d=r.length===0?pg:yg(l?e.adapter.getAllLinks():a);hg(n,"activity",y=>{let f=o.get(y);return{exists:f!==void 0,current:f?.proplannerId??null}},c),hg(r,"link",y=>{let f=s.get(y);return{exists:f!==void 0,current:f?.proplannerId??null}},d),fg(i,n,"activity"),fg(a,r,"link");let u=[],p=[];return e.adapter.batchUpdate(()=>{for(let y of n){let f=e.adapter.getActivity(y.id);if(!f||f.proplannerId===y.proplannerId)continue;let m=f.proplannerId;e.adapter.setActivityField(y.id,"proplannerId",y.proplannerId),u.push({id:y.id,kind:W.UPDATED,fields:{proplannerId:{before:m,after:y.proplannerId}},after:{...f,proplannerId:y.proplannerId}})}for(let y of r){let f=e.adapter.getLink(y.id);if(!f||f.proplannerId===y.proplannerId)continue;let m=f.proplannerId;e.adapter.setLinkProplannerId(y.id,y.proplannerId),p.push({id:y.id,kind:W.UPDATED,fields:{proplannerId:{before:m,after:y.proplannerId}},after:{...f,proplannerId:y.proplannerId}})}}),{ok:!0,changes:{source:t,activities:u,links:p,calendars:[],trackingEvents:[]}}}async function Ag(t,e,n){if(Zb(t))return{ok:!1,reason:C.INVALID_VALUE};let r=[...new Set(t.activityIds.map(String))];if(t.acknowledgePersistedLookahead===!0&&r.some(s=>!n.isActivityPersisted(s)))return{ok:!1,reason:C.INVALID};let a=r.map(s=>n.adapter.getActivity(s));if(a.some(s=>!s))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let o=[];for(let[s,l]of r.entries()){let c=a[s];if(!c)continue;let d={};c.isLookahead!==t.isLookahead&&(d.isLookahead={before:c.isLookahead,after:t.isLookahead},n.adapter.setActivityField(l,"isLookahead",t.isLookahead)),c.hasLookaheadTasks!==t.hasLookaheadTasks&&(d.hasLookaheadTasks={before:c.hasLookaheadTasks,after:t.hasLookaheadTasks},n.adapter.setActivityField(l,"hasLookaheadTasks",t.hasLookaheadTasks)),Object.keys(d).length!==0&&o.push({id:l,kind:W.UPDATED,fields:d,after:{...c,isLookahead:t.isLookahead,hasLookaheadTasks:t.hasLookaheadTasks}})}return t.persistedProgress!==void 0&&(await mg([{activityId:r[0],progress:t.persistedProgress}],n)).length>0?(await ot({adapter:n.adapter,scheduler:n.scheduler,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:t.persistedProgress===0?r[0]:null,recomputeParentsFrom:[],now:n.now,options:e}),{ok:!0,changes:await tt(n.adapter,{source:t,beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:n.sector.hoursPerDay})}):{ok:!0,changes:{source:t,activities:o,links:[],calendars:[],trackingEvents:[]}}}function Zb(t){let e=t.persistedProgress;return e!==void 0&&(t.activityIds.length!==1||!Number.isFinite(e)||e<0||e>100)}function Sg(t,e){let n=new Map(t.map(a=>[a.id,st(a)])),r=new Map;for(let a of t){if(a.parentId===null)continue;let o=r.get(a.parentId)??[];o.push(a),r.set(a.parentId,o)}let i=new Map;for(let a of[...t].reverse()){let o=r.get(a.id)??[],s=o.length>0,l=s?o.reduce((f,m)=>f+Ig(i,m.id),0):Qb(a,e);if(i.set(a.id,l),!s)continue;let c=l>0,d=e!==Dt.COST;for(let f of o){let m=Yd(n,f.id),A=c?100*Ig(i,f.id)/l:d?100/o.length:0;n.set(f.id,{...m,ponderator:A})}let u=o.map(f=>Yd(n,f.id)),p=pi(u),y=Yd(n,a.id);n.set(a.id,{...y,progress:as(p??0)})}return n}function Qb(t,e){return t.type===U.PROJECT?0:e===Dt.COST?t.cost:e===Dt.WORK_HOURS?t.workHours:t.durationHours}function Ig(t,e){let n=t.get(e);if(n===void 0)throw new Error(`Missing conversion magnitude ${e}`);return n}function Yd(t,e){let n=t.get(e);if(!n)throw new Error(`Missing conversion snapshot ${e}`);return n}function qd(t,e){let{adapter:n}=e,r=new Set(t.conversionRootIds.map(p=>String(p)));if(r.size===0)throw new Error("Conversion requires at least one root");for(let p of r)cL(p,n);let i=n.getVisualOrderIds().filter(p=>r.has(p)&&!zn(p,r,n)),a=i.map(p=>tL(p,n,t.criterion??e.sector.activityCreter??Dt.DURATION)),o=a.map(({conversionRootId:p,convertedActivities:y})=>({conversionRootId:p,convertedActivities:y})),s=a.flatMap(p=>p.milestoneMoves),l=a.flatMap(p=>p.activityIdsToDelete),c=a.map(p=>p.formerParent),d=new Set(l),u=Jn(d,n);return{sourceStateRevision:e.stateRevision,conversionRootIds:i,conversionGroups:o,milestoneMoves:s,activityIdsToDelete:l,linkIdsToDelete:u,formerParents:c}}async function Dg(t,e,n){if(t.expectedStateRevision!==n.stateRevision)return{ok:!1,reason:C.STALE_STATE_REVISION};let r=qd(t,n);if(!dL(r,n.adapter))return{ok:!1,reason:C.HIERARCHY_CYCLE};let{adapter:i,scheduler:a}=n;a.invalidateAllCaches();let o=await iL(r,i);aL(r,n),Tg(r,i),oL(r,o.deletedIds,i);let s=sL(r,i),l=ge(i,s,o.deletedIds,o.beforeSnap,o.touchedIds),{scheduledIds:c}=await ot({adapter:i,scheduler:a,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:"roots",recomputeParentsFrom:o.touchedIds,now:n.now,options:e,recomputeParentProgress:!0}),d=await tt(i,{source:t,beforeSnap:o.beforeSnap,touchedIds:o.touchedIds,scheduledIds:c,sirDetection:"after-diff",links:te(o.beforeLinks),hoursPerDay:n.sector.hoursPerDay,correlativeShifts:s,deferredCorrelatives:l});return lL(r,o,d)}function tL(t,e,n){let r=Gd(t,e),i=Ui([t],e);if(i.delete(t),i.size===0)throw new Error(`Conversion root ${t} has no descendants`);let a=e.getVisualOrderIds().filter(u=>i.has(u)).map(u=>Gd(u,e));Cg(r);for(let u of a)Cg(u);let o=a.filter(u=>u.type!==U.MILESTONE),s=a.filter(u=>u.type===U.MILESTONE),l=eL(r,o),c=Sg([r,...o],n),d=c.get(r.id);if(!d)throw new Error(`Missing conversion snapshot ${r.id}`);return{conversionRootId:t,convertedActivities:[...c.values()].filter(u=>u.id!==t).map(u=>nL(u,l)),milestoneMoves:rL(r,s),activityIdsToDelete:o.map(u=>u.id),formerParent:{activity:d,hasConvertedActivities:o.length>0}}}function eL(t,e){let n=new Map;e.length>0&&n.set(t.id,vg(t));for(let r of e)n.set(r.id,vg(r));return n}function nL(t,e){let n=st(t),r=de(t.parentId),i=e.get(r);return n.parentId=i===void 0?null:String(i),n}function rL(t,e){let n=[],r=de(t.parentId),i=t.id;for(let a of e)n.push({activityId:a.id,parentId:r,afterSiblingId:i}),i=a.id;return n}async function iL(t,e){let n=new Set(t.activityIdsToDelete),r=new Set([...t.conversionRootIds,...t.activityIdsToDelete,...t.milestoneMoves.map(({activityId:i})=>i),...t.milestoneMoves.map(({parentId:i})=>i).filter(i=>i!=="0")]);return{deletedIds:n,touchedIds:r,beforeSnap:await dt(e,r),beforeLinks:uL(t.linkIdsToDelete,e),viewStateChanges:Fr(e,n)}}function aL(t,e){for(let n of t.activityIdsToDelete){let r=e.adapter.getActivity(n)?.customId;r&&e.customIdTracker.releaseCustomId(r)}}function Tg(t,e){for(let n of t.milestoneMoves)e.setActivityFields(n.activityId,{parentId:n.parentId,correlativeId:xi(e,n.parentId,n.afterSiblingId,void 0)});for(let n of t.linkIdsToDelete)e.removeLink(n);for(let n of[...t.activityIdsToDelete].reverse())e.removeActivity(n);for(let{activity:n}of t.formerParents)e.setActivityField(n.id,O.TYPE,U.TASK)}function oL(t,e,n){for(let{activity:r,hasConvertedActivities:i}of t.formerParents){let a=Gd(r.id,n),o=cl({parent:a,idsRemoved:e});n.setActivityFields(r.id,{progress:r.progress,isLookahead:r.isLookahead||i,hasLookaheadTasks:r.hasLookaheadTasks||i,...o?.fields??{}}),n.setProgressFallback(r.id,null)}}function sL(t,e){for(let{activity:n}of t.formerParents)qt(n.parentId,e);return Ut(e)}function lL(t,e,n){let r=new Map;for(let i of e.deletedIds){let a=e.beforeSnap.get(i);a&&r.set(i,a)}return{ok:!0,changes:e.viewStateChanges.length===0?n:{...n,viewState:e.viewStateChanges},conversionGroups:t.conversionGroups.map(({conversionRootId:i,convertedActivities:a})=>({conversionRootId:i,convertedActivities:a.map(o=>st(o))})),__beforeSnap:r,__beforeLinks:e.beforeLinks}}function cL(t,e){let n=e.getActivity(t);if(!n)throw new Error(`Conversion root ${t} was not found`);if(n.type===U.PROJECT&&n.correlativeId===0)throw new Error(`Conversion root ${t} is the visual project root`)}function Gd(t,e){let n=e.getActivity(t);if(!n)throw new Error(`Conversion activity ${t} is missing`);return n}function vg(t){if(t.proplannerId==null)throw new Error(`Conversion activity ${t.id} has no persisted identifier`);return t.proplannerId}function Cg(t){if(!Number.isFinite(t.startDate.getTime()))throw new Error(`Conversion activity ${t.id} has invalid startDate`);if(!Number.isFinite(t.endDate.getTime()))throw new Error(`Conversion activity ${t.id} has invalid endDate`)}function dL(t,e){let n=e.fork();return Tg(t,n),ci({port:e,proposedPort:n,currentLinks:e.getAllLinks(),proposedLinks:n.getAllLinks()}).ok}function uL(t,e){let n=new Map;for(let r of t){let i=e.getLink(r);i&&n.set(r,{...i})}return n}function Bi(t,e){let n=new Set;for(let i of t)n.add(String(i));let r=[];for(let i of e.getAllLinks()){let a=String(i.source),o=String(i.target);!n.has(a)&&!n.has(o)||Eg(i,e)&&r.push(String(i.id))}return r}function Eg(t,e){let n=String(t.source),r=String(t.target);return _g(r,n,e)||_g(n,r,e)}function dl(t,e){return[...t].filter(([,n])=>Eg(n,e)).map(([n])=>String(n))}function _g(t,e,n){let r=String(t),i=new Set;for(;r!=null;){if(i.has(r))return!1;i.add(r);let a=n.getActivity(r);if(!a)return!1;let o=a.parentId;if(o===null||q(o))return!1;let s=o;if(s===e)return!0;r=s}return!1}async function Rg(t,e,n){let{adapter:r,scheduler:i,sector:a}=n;i.invalidateAllCaches();let o=r.getActivity(t.activityId);if(!o)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let s=q(t.parentId);if(!s&&!r.getActivity(t.parentId))return{ok:!1,reason:C.PARENT_NOT_FOUND};if(!s&&(t.parentId===t.activityId||r.isChildOf(t.parentId,t.activityId)))return{ok:!1,reason:C.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(t.afterSiblingId!==void 0&&t.beforeSiblingId!==void 0)return{ok:!1,reason:C.ANCHOR_SIBLING_CONFLICT};let l=t.afterSiblingId??t.beforeSiblingId;if(l!==void 0){let S=r.getActivity(l);if(!S)return{ok:!1,reason:C.ANCHOR_SIBLING_NOT_FOUND};if((S.parentId===null?"0":String(S.parentId))!==t.parentId)return{ok:!1,reason:C.ANCHOR_SIBLING_WRONG_PARENT}}let c=o.parentId,d=de(c),u=String(t.parentId),p=d!==u;if(p){let S=new Map([[t.activityId,s?null:t.parentId]]);if(wi(r,S))return{ok:!1,reason:C.HIERARCHY_CYCLE}}if(p&&!s){let S=yn(fn([t.parentId],r),e);if(S)return S}let y=new Set([t.activityId]);p?(d!=="0"&&y.add(d),u!=="0"&&y.add(u)):d!=="0"&&y.add(d);let f=await dt(r,y),m=new Map;p&&r.setActivityField(t.activityId,O.PARENT,u);let A=xi(r,t.parentId,t.afterSiblingId,t.beforeSiblingId);if(r.setActivityField(t.activityId,O.CORRELATIVE_ID,A),p){if(!s){let S=r.getActivity(t.parentId);if(S){let k=kn(S.type)&&r.getChildren(t.parentId).filter(j=>j!==t.activityId).length===0,E=Xn({parentId:t.parentId,newChildId:t.activityId,isCurrentlyLeaf:k,promotionSource:Hi.REPARENT},n);if(E.applied)for(let[j,w]of E.removedLinks)m.set(j,w)}}if(d!=="0"){let S=r.getActivity(d);if(S){let k=r.getChildren(d),E=Xe({parent:S,remainingChildIds:k.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:r.getPromotionSnapshot(d),computeEndDate:(j,w)=>r.calculateEndDate({startDate:j,durationHours:w,task:S}),idsRemoved:new Set([t.activityId]),dataDateCapability:n.dataDateCapability,hasCompleteSchedulingState:n.hasCompleteSchedulingState});if(E){r.setActivityFields(d,E.fields);let j=be(d,r),w=j?r.getActivity(j)?.customId:null,B=typeof w=="string"&&w?w:null,$=n.customIdTracker.generateCustomIdForRestoredChild(B);r.setActivityField(d,O.CUSTOM_ID,$)}}}}p&&(d!=="0"&&qt(d,r),s||qt(t.parentId,r));let g=ge(r,Ut(r),Ii,f,y),P=p&&d!=="0"?r.getChildren(d).map(String):[],{scheduledIds:L}=await ot({adapter:r,scheduler:i,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:t.activityId,recomputeParentsFrom:[t.activityId,t.parentId,...P],now:n.now,options:e,recomputeParentProgress:p}),F=p?Bi([t.activityId],r):[],T=dl(m,r),x={name:ke.ACTIVITY_MOVE,properties:{activity_id:t.activityId,new_parent_id:t.parentId,after_sibling_id:t.afterSiblingId??null,before_sibling_id:t.beforeSiblingId??null,invalid_link_ids:[...new Set([...T,...F.map(String)])]}};return t.eventSource!==void 0&&(x.properties.event_source=t.eventSource),{ok:!0,changes:await tt(r,{source:t,beforeSnap:f,deferredCorrelatives:g,touchedIds:y,scheduledIds:L,sirDetection:Xt.BEFORE_DIFF,links:te(m),trackingEvents:[x],hoursPerDay:a.hoursPerDay}),...m.size>0?{__beforeLinks:m}:{}}}async function Pg(t,e,n){let{adapter:r,scheduler:i,sector:a}=n;if(i.invalidateAllCaches(),t.activityIds.length===0)return{ok:!1,reason:C.ACTIVITY_IDS_EMPTY};let o=new Set,s=[],l=Mi(t.activityIds,r),c=[...l.failed];for(let x of l.moves)o.add(String(x.activityId)),o.add(String(x.newParentId)),x.oldParentId!=="0"&&o.add(String(x.oldParentId));let d=l.allowedMoves,u=yn(fn(d.map(x=>x.newParentId),r),e);if(u)return u;let p=await dt(r,o);for(let{activityId:x,newParentId:S}of d)r.setActivityField(x,O.PARENT,S),r.setActivityField(x,O.CORRELATIVE_ID,zm),s.push(x);let y=new Set,f=new Map;for(let{activityId:x,newParentId:S}of d){if(y.has(S))continue;y.add(S);let k=r.getActivity(S);if(!k)continue;let E=k.customId,j=kn(k.type)&&r.getChildren(S).filter($=>!s.includes($)).length===0,w=k.hasNewActivities&&k.newActivityIds.some($=>String($)===String(x)),B=Xn({parentId:S,newChildId:x,isCurrentlyLeaf:j,promotionSource:Hi.REPARENT},n);if(B.applied){for(let[$,ft]of B.removedLinks)f.set($,ft);w||(r.setActivityField(S,O.HAS_NEW_ACTIVITIES,!1),r.setActivityField(S,O.NEW_ACTIVITIES_ARRAY,[]))}r.setActivityField(S,O.CONSTRAINT_TYPE,_.ASAP),r.setActivityField(S,O.CONSTRAINT_DATE,null),r.setActivityField(S,O.CUSTOM_ID,null),B.applied||Cm(E,n.customIdTracker)}let m=new Set;for(let x of d)x.oldParentId!=="0"&&m.add(x.oldParentId),m.add(x.newParentId);for(let x of m)qt(x,r);let A=ge(r,Ut(r),Ii,p,o),g=dl(f,r),P=Bi(s,r);for(let x of P){let S=r.getLink(x);S&&(f.set(x,{...S}),r.removeLink(x))}let{scheduledIds:L}=await ot({adapter:r,scheduler:i,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:null,recomputeParentsFrom:s,now:n.now,options:e}),F={name:ke.ACTIVITY_INDENT,properties:{activity_ids:s,failed:c.map(x=>({activity_id:x.activityId,reason:x.reason})),invalid_link_ids:[...new Set([...g,...P.map(String)])]}};t.eventSource!==void 0&&(F.properties.event_source=t.eventSource);let T=await tt(r,{source:t,beforeSnap:p,deferredCorrelatives:A,touchedIds:o,scheduledIds:L,links:te(f),trackingEvents:[F],hoursPerDay:a.hoursPerDay});return{ok:!0,activityVerdicts:t.activityIds.map(x=>{let S=c.find(k=>String(k.activityId)===String(x));return S?{activityId:String(x),ok:!1,reason:S.reason}:{activityId:String(x),ok:!0}}),changes:T,__beforeLinks:f}}async function kg(t,e,n){let{adapter:r,scheduler:i,sector:a}=n;if(i.invalidateAllCaches(),t.activityIds.length===0)return{ok:!1,reason:C.ACTIVITY_IDS_EMPTY};let o=new Set(t.activityIds),s=new Map,l=new Map;for(let S of t.activityIds){let k=S;r.getActivity(k)&&(s.set(k,_c(k,r)),l.set(k,Jm(k,o,r)))}let c=new Set,d=[],u=[],p=new Set,y=[],f=new Set,m=[...t.activityIds].sort((S,k)=>{let E=r.getActivity(S),j=r.getActivity(k),w=E?Qt(E):Nr,B=j?Qt(j):Nr;return w-B});for(let S of m){let k=S,E=r.getActivity(k);if(!E){d.push({activityId:k,reason:C.ACTIVITY_NOT_FOUND});continue}if(zn(k,f,r))continue;let j=E.parentId;if(q(j)){d.push({activityId:k,reason:C.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let w=String(j),B=r.getActivity(w);if(!B){d.push({activityId:k,reason:C.ACTIVITY_NOT_FOUND});continue}let $=B.parentId;if(q($)){d.push({activityId:k,reason:C.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let ft=String($),at=_c(w,r)+1,St=l.get(k);if(St!=null&&o.has(St)){let N=s.get(St)??-1,K=s.get(k)??-1;N>=0&&K>=0&&(at+=K-N)}y.push({activityId:k,grandparentKey:ft,oldParentKey:w,targetIndexInGrandparent:at}),f.add(k),c.add(String(k)),c.add(String(w)),ft!=="0"&&c.add(String(ft)),p.add(w)}let A=sl(y.map(S=>({activityId:S.activityId,newParentId:S.grandparentKey})),r);for(let S of A)d.push({activityId:S,reason:C.HIERARCHY_CYCLE});let g=y.filter(S=>!A.has(S.activityId)),P=await dt(r,c);for(let S of g){r.setActivityField(S.activityId,O.PARENT,S.grandparentKey);let k=Xm(r,S.grandparentKey,S.targetIndexInGrandparent,S.activityId);r.setActivityField(S.activityId,O.CORRELATIVE_ID,k),u.push(S.activityId)}for(let S of p){let k=r.getActivity(S);if(!k)continue;let E=r.getChildren(S),j=Xe({parent:k,remainingChildIds:E.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:r.getPromotionSnapshot(S),computeEndDate:(at,St)=>r.calculateEndDate({startDate:at,durationHours:St,task:k}),idsRemoved:new Set(g.filter(at=>at.oldParentKey===S).map(at=>at.activityId)),dataDateCapability:n.dataDateCapability,hasCompleteSchedulingState:n.hasCompleteSchedulingState});if(!j){os(S,r);continue}r.setActivityFields(S,j.fields);let w=be(S,r),B=w?r.getActivity(w)?.customId:null,$=typeof B=="string"&&B?B:null,ft=n.customIdTracker.generateCustomIdForRestoredChild($);r.setActivityField(S,O.CUSTOM_ID,ft)}let L=new Set;for(let S of p)L.add(String(S));for(let S of g)S.grandparentKey!=="0"&&L.add(String(S.grandparentKey));for(let S of L)qt(S,r);let F=ge(r,Ut(r),Ii,P,c),{scheduledIds:T}=await ot({adapter:r,scheduler:i,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:u.length>0?Et.ROOTS:null,recomputeParentsFrom:u,now:n.now,options:e}),x={name:ke.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(S=>({activity_id:String(S.activityId),reason:S.reason}))}};return t.eventSource!==void 0&&(x.properties.event_source=t.eventSource),{ok:!0,activityVerdicts:t.activityIds.map(S=>{let k=d.find(E=>String(E.activityId)===String(S));return k?{activityId:String(S),ok:!1,reason:k.reason}:{activityId:String(S),ok:!0}}),changes:await tt(r,{source:t,beforeSnap:P,deferredCorrelatives:F,touchedIds:c,scheduledIds:T,trackingEvents:[x],hoursPerDay:a.hoursPerDay})}}async function bg(t,e,n){let{adapter:r,scheduler:i,sector:a}=n,o=r.getActivity(t.activityId);if(!o)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};if(!ua(t.type))return{ok:!1,reason:C.INVALID_VALUE};let s=r.getChildren(t.activityId),l=t.type===U.PROJECT;if(l!==s.length>0)return{ok:!1,reason:C.INVALID_VALUE};let c=new Set(r.getAllIds()),d=await dt(r,c);i.invalidateAllCaches();let u=l&&o.type!==U.PROJECT?Xn({parentId:t.activityId,newChildId:s[0],isCurrentlyLeaf:!0},n).removedLinks:new Map;!l&&o.type===U.PROJECT&&pL(t.activityId,n),t.type!==U.PROJECT?(yL(t.activityId,t.type,n),fL(t.activityId,n)):qt(t.activityId,r);let p=hL(t.activityId,n);for(let[f,m]of u)p.set(f,m);let{scheduledIds:y}=await ot({adapter:r,scheduler:i,sector:a,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:t.activityId,recomputeParentsFrom:[t.activityId],recomputeParentProgress:!0,now:n.now,options:e});return{ok:!0,changes:await tt(r,{source:t,beforeSnap:d,touchedIds:c,scheduledIds:y,sirDetection:Xt.BEFORE_DIFF,links:te(p),hoursPerDay:a.hoursPerDay}),__beforeLinks:new Map(p)}}function pL(t,e){let n=e.adapter.getActivity(t);if(!n)return;let r=Xe({parent:n,remainingChildIds:[],defaultDurationHours:e.sector.hoursPerDay,promotionSnapshot:e.adapter.getPromotionSnapshot(t),computeEndDate:(i,a)=>e.adapter.calculateEndDate({startDate:i,durationHours:a,task:n}),dataDateCapability:e.dataDateCapability,hasCompleteSchedulingState:e.hasCompleteSchedulingState});r&&e.adapter.setActivityFields(t,r.fields)}function yL(t,e,n){let r=n.adapter.getActivity(t);if(!r)return;n.adapter.setActivityField(t,O.TYPE,e);let i=e===U.MILESTONE?0:r.durationHours===0?n.sector.hoursPerDay:r.durationHours;i!==r.durationHours&&n.adapter.setActivityField(t,O.DURATION_HOURS,i);let a=n.adapter.getActivity(t);if(!a)return;let o=n.adapter.calculateEndDate({startDate:a.startDate,durationHours:i,task:a});n.adapter.setActivityField(t,O.END_DATE,o)}function fL(t,e){if(e.adapter.getActivity(t)?.customId)return;let r=be(t,e.adapter),i=r?e.adapter.getActivity(r)?.customId:null,a=e.customIdTracker.generateCustomIdForRestoredChild(i||null);e.adapter.setActivityField(t,O.CUSTOM_ID,a)}function hL(t,e){let n=new Map;for(let r of Bi([t],e.adapter)){let i=e.adapter.getLink(r);i&&(n.set(String(r),{...i}),e.adapter.removeLink(r))}return n}async function Lg(t,e,n){let{adapter:r,ctx:i,scheduler:a,sector:o}=n;if(t.newValue!==0&&t.newValue!==100)return{ok:!1,reason:C.INVALID_PROGRESS_VALUE};let s=i.activityReader.getActivity(t.activityId);if(!s)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let l=he(R.PROGRESS);if(!l)throw new Error("[ScheduleCore] progressPipeline not registered \u2014 cannot dispatch activity-set-progress");let c=l.canEdit(s,i.hierarchy);if(!c.allowed&&!AL(t,c))return{ok:!1,reason:c.reason,...c.alertKey?{alertKey:c.alertKey}:{}};let d=l.transform(s,t.newValue,i,t.newValue),u=Lm(s,t.newValue,c.allowed?d:null,n,e.confirmations);if(u!==null&&!u.accepted)return IL(u);let p=u===null?d:u.changes,y=u===null||c.allowed,f=Kn(t.activityId,p),m=await dt(r,f);Yn(r,t.activityId,p),y&&Gy(t.activityId,t.newValue,r),Un(t.activityId,p.postProcessors??[],r);let A=mL(t.activityId,p,n),{scheduledIds:g}=await ot({adapter:r,scheduler:a,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:A,recomputeParentsFrom:[],collectDirty:P=>vs(t.activityId,f,P),now:n.now,options:e});return{ok:!0,changes:await tt(r,{source:t,beforeSnap:m,touchedIds:f,scheduledIds:g,trackingEvents:gL(p),hoursPerDay:o.hoursPerDay})}}function mL(t,e,n){return e.needsAutoSchedule?n.ctx.hierarchy.hasChildren(t)?Et.ROOTS:t:null}function gL(t){return(t.trackingEvents??[]).map(e=>({name:e.name,properties:e.properties??{}}))}function AL(t,e){return t.origin===fs.ACTION_BUTTON&&(e.reason===Me.HAS_LOOKAHEAD_TASKS||e.reason===Me.SUMMARY)}function IL(t){return{ok:!1,reason:t.reason,...t.alertKey?{alertKey:t.alertKey}:{},...t.confirmation?{confirmation:t.confirmation}:{}}}function SL(t){return t===R.START_DATE||t===R.END_DATE}async function Og(t,e,n){let r=vL(t,n);if(r!==null)return{ok:!1,reason:r};let{adapter:i,scheduler:a,sector:o}=n,s=[],l=new Map,c=new Set,d=[],u=[],p=[],y=!1;for(let m of t.edits){let A=CL(m,n,e);if(s.push(A.verdict),!A.verdict.ok||!A.changes)continue;let g=Kn(m.activityId,A.changes);DL(l,g,n);for(let T of g)c.add(T);let P=bi(i,m.activityId),L=Is(i,String(m.activityId));Yn(i,m.activityId,A.changes),Un(m.activityId,A.changes.postProcessors??[],i,L),u.push(...Li(P,i,m.activityId)),y||=!!A.changes.needsAutoSchedule;for(let T of A.changes.trackingEvents??[])d.push({name:T.name,properties:T.properties??{}});let F=Dr(m.activityId,A.changes.constraintWarning);F&&p.push(F)}let{scheduledIds:f}=await ot({adapter:i,scheduler:a,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:y?Et.ROOTS:null,recomputeParentsFrom:c,now:n.now,options:e});return{ok:!0,verdicts:s,changes:await tt(i,{source:t,beforeSnap:l,touchedIds:c,scheduledIds:f,sirDetection:Xt.BEFORE_DIFF,links:u,trackingEvents:d,warnings:p,hoursPerDay:o.hoursPerDay})}}function vL(t,e){return t.edits.some(i=>!SL(i.column))?C.INVALID_VALUE:t.edits.some(i=>e.ctx.activityReader.getActivity(i.activityId)===null)?C.ACTIVITY_NOT_FOUND:null}function CL(t,e,n){let{ctx:r}=e,i=t.activityId,a=he(t.column);if(!a)throw new Error(`[ScheduleCore] no pipeline registered for column "${t.column}"`);let o=r.activityReader.getActivity(t.activityId);if(!o)throw new Error(`[ScheduleCore] activity "${t.activityId}" not found`);let s=Fi(a,o,e,t.column);if(!s.allowed)return{verdict:{activityId:i,ok:!1,reason:s.reason??C.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let l=a.parseInput(t.newValue,o,r);if(!l.ok)return{verdict:{activityId:i,ok:!1,reason:l.reason??C.PARSE_ERROR},changes:null};let c=Reflect.get(o,a.targetField),d=a.validate(o,c,l.value,r);if(!d.valid)return{verdict:{activityId:i,ok:!1,reason:d.reason??C.INVALID,...d.notification?.messageKey?{alertKey:d.notification.messageKey}:{}},changes:null};let u=a.transform(o,l.value,r,l.raw),p=Or(o,u,e,t.column,n.confirmations);return p.accepted?{verdict:{activityId:i,ok:!0},changes:p.changes}:{verdict:{activityId:i,ok:!1,reason:p.reason,...p.alertKey?{alertKey:p.alertKey}:{},...p.confirmation?{confirmation:p.confirmation}:{}},changes:null}}function DL(t,e,n){let r=new Set;for(let i of e)t.has(i)||r.add(i);if(r.size!==0)for(let i of r){let a=n.adapter.getActivity(i);a&&t.set(i,st(a))}}var $d=R.CUSTOM_ID,TL="sir-apply";async function ul(t,e,n){let{adapter:r,scheduler:i,sector:a}=n,o=[],s=new Map,l=new Map,c=new Set,d=new Set,u=[],p=[],y=[],f=new Set,m=new Map,A=new Map,g=!1,P=bm(t.edits,n);for(let k of km(t)){let E=k[0],j=P.get(String(E.activityId));if(j!==void 0&&(E.column===R.START_DATE||E.column===R.END_DATE)){o.push({activityId:E.activityId,ok:!1,reason:j.reason,...j.alertKey?{alertKey:j.alertKey}:{}});continue}let B=LL(k,n,t.eventSource,e);for(let it of k)o.push(B.verdict);if(!B.verdict.ok||!B.changes)continue;let $=Dr(E.activityId,B.changes.constraintWarning);$&&y.push($);let ft=Kn(E.activityId,B.changes);wL(s,ft,n);for(let it of ft)d.add(it);FL(l,E,s),Js(E.column)&&c.add(String(E.activityId)),RL(m,E);let at=bi(r,E.activityId),St=Is(r,String(E.activityId)),N=OL(E,n),K=B.changes;Yn(r,E.activityId,K),Un(E.activityId,B.changes.postProcessors??[],r,St),_L(f,y,E),EL(A,E,r.getActivity(E.activityId)),NL(E,N,n),p.push(...Li(at,r,E.activityId)),g||=!!B.changes.needsAutoSchedule;for(let it of B.changes.trackingEvents??[])u.push({name:it.name,properties:it.properties??{}})}let L=t.eventSource===TL?o.find(k=>!k.ok&&k.reason!==Ir.UNCHANGED):void 0;if(L&&!L.ok)return{ok:!1,reason:L.reason??C.INVALID,...L.alertKey?{alertKey:L.alertKey}:{}};let F={action:t,autoscheduleFrom:g?Et.ROOTS:null,recomputeParentsFrom:d,now:n.now,options:e},T=PL(m,A,s,y,f,n),x=l.size>0,{scheduledIds:S}=await(x?Zs({adapter:r,scheduler:i,sector:a,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{postMutationArgs:F,revertTargets:[...l].filter(([k])=>!c.has(k)).map(([k,E])=>({activityId:k,priorConstraintDate:E})),revert:(k,E)=>Xs(k,E,r,n.ctx.calendars)}):ot({adapter:r,scheduler:i,sector:a,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},F));return{ok:!0,verdicts:o,changes:await tt(r,{source:t,beforeSnap:s,touchedIds:d,scheduledIds:S,sirDetection:Xt.BEFORE_DIFF,links:p,trackingEvents:u,warnings:T,hoursPerDay:a.hoursPerDay})}}function _L(t,e,n){if(!Pi(n.column))return;let r=String(n.activityId);for(let i of e)String(i.activityId)===r&&t.add(i)}function EL(t,e,n){!Pi(e.column)||!n||t.set(String(e.activityId),{constraintType:n.constraintType,constraintDate:n.constraintDate?new Date(n.constraintDate.getTime()):null})}function RL(t,e){if(e.column!==R.START_DATE&&e.column!==R.END_DATE)return;let n=String(e.activityId),r=t.get(n)??new Set;r.add(e.column),t.set(n,r)}function PL(t,e,n,r,i,a){let o=new Set,s=[],l=new Set;for(let[c,d]of t){if(!d.has(R.START_DATE)||!d.has(R.END_DATE))continue;let u=e.get(c);if(u){a.adapter.setActivityFields(c,u);for(let A of i)String(A.activityId)===c&&l.add(A);continue}let p=n.get(c),y=a.adapter.getActivity(c);if(!p?.constraintType||!p.constraintDate||!y)continue;let f=lr(p.constraintType,y.startDate,y.endDate),m=kL(p.constraintType,p.constraintDate,f);if(o.add(c),m){a.adapter.setActivityField(c,"constraintType",_.SNET),a.adapter.setActivityField(c,"constraintDate",new Date(y.startDate.getTime()));let A=Dr(c,Co(p.constraintType,p.constraintDate,f));A&&s.push(A);continue}a.adapter.setActivityField(c,"constraintType",p.constraintType),a.adapter.setActivityField(c,"constraintDate",p.constraintDate)}return[...r.filter(c=>!l.has(c)&&!o.has(String(c.activityId))),...s]}function kL(t,e,n){return t===_.MSO||t===_.MFO?e.getTime()!==n.getTime():vo(t,e,n).violated}function bL(t,e,n){let{ctx:r}=e,i=t.activityId,a=he(t.column);if(!a)return{verdict:{activityId:i,ok:!1,reason:C.NO_PIPELINE_FOR_COLUMN},changes:null};let o=r.activityReader.getActivity(t.activityId);if(!o)return{verdict:{activityId:i,ok:!1,reason:C.ACTIVITY_NOT_FOUND},changes:null};let s=Fi(a,o,e,t.column,{eventSource:n,newValue:t.newValue});if(!s.allowed)return{verdict:{activityId:i,ok:!1,reason:s.reason??C.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let l=a.parseInput(t.newValue,o,r);if(!l.ok)return{verdict:{activityId:i,ok:!1,reason:l.reason??C.PARSE_ERROR},changes:null};let c=Oi(o,a.targetField),d=a.validate(o,c,l.value,r);if(!d.valid)return{verdict:{activityId:i,ok:!1,reason:d.reason??C.INVALID,...d.notification?.messageKey?{alertKey:d.notification.messageKey}:{}},changes:null};if(t.column===$d&&l.value!==null){let p=e.adapter.getActivity(t.activityId),y=p?p.customId:null,f=typeof y=="string"?y:null;if(e.customIdTracker.isCustomIdInUse(String(l.value),f))return{verdict:{activityId:i,ok:!1,reason:C.CUSTOM_ID_DUPLICATE},changes:null}}let u=a.transform(o,l.value,r,l.raw);return{verdict:{activityId:i,ok:!0},changes:u}}function LL(t,e,n,r){let i=t[0],a=t.map(d=>bL(d,e,n)),o=a.find(d=>!d.verdict.ok);if(o)return o;let s=a[0].changes,l=Pm(s,a[1]?.changes),c=Or(e.ctx.activityReader.getActivity(i.activityId),l,e,i.column,r.confirmations);return c.accepted?{verdict:{activityId:i.activityId,ok:!0},changes:c.changes}:{verdict:{activityId:i.activityId,ok:!1,reason:c.reason,...c.alertKey?{alertKey:c.alertKey}:{},...c.confirmation?{confirmation:c.confirmation}:{}},changes:null}}function OL(t,e){if(t.column!==$d)return null;let n=e.adapter.getActivity(t.activityId),r=n?n.customId:null;return typeof r=="string"?r:null}function NL(t,e,n){if(t.column!==$d)return;let r=n.adapter.getActivity(t.activityId),i=r?r.customId:null,a=typeof i=="string"?i:null;e!==a&&n.customIdTracker.trackCustomIdChange(e,a)}function FL(t,e,n){if(!Pi(e.column))return;let r=String(e.activityId);if(t.has(r))return;let i=n.get(r);i&&t.set(r,i.constraintDate??null)}function wL(t,e,n){let r=new Set;for(let i of e)t.has(i)||r.add(i);if(r.size!==0)for(let i of r){let a=n.adapter.getActivity(i);a&&t.set(i,st(a))}}var ie={INVALID_BASELINE_POINT:"invalid_baseline_point",UNKNOWN_CONSTRAINT:"unknown_constraint",PROGRESS_OUT_OF_RANGE:"progress_out_of_range",ORPHAN_ACTIVITY:"orphan_activity",INVALID_LINK:"invalid_link",DUPLICATE_LINK:"duplicate_link"},xL=[ie.INVALID_BASELINE_POINT,ie.UNKNOWN_CONSTRAINT,ie.PROGRESS_OUT_OF_RANGE,ie.ORPHAN_ACTIVITY,ie.INVALID_LINK,ie.DUPLICATE_LINK],hn=()=>{};function Ng(){let t=new Map,e=new Map;return{record:(i,a)=>{t.set(i,(t.get(i)??0)+1);let o=e.get(i)??[];o.length<10&&!o.includes(a)&&(o.push(a),e.set(i,o))},snapshot:()=>Object.freeze(xL.flatMap(i=>{let a=t.get(i);return a===void 0?[]:[Object.freeze({code:i,count:a,sampleIds:Object.freeze([...e.get(i)??[]])})]}))}}function Fg(t){return typeof t=="string"&&t.length>0?dn(t):t instanceof Date?t:null}function zd(t){let e=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):Number.NaN;return!Number.isFinite(e)||e<0?null:e}function pl(t,e,n,r=!1){let i=zd(t.duration),a=zd(t.cost),o=zd(t.hh_work);if(i===null||a===null||o===null)return n&&n.record(ie.INVALID_BASELINE_POINT,n.sampleId),e.warn(`[baseline] dropping point with non-finite/negative magnitude \u2014 duration=${JSON.stringify(t.duration)}, cost=${JSON.stringify(t.cost)}, hh_work=${JSON.stringify(t.hh_work)}`),null;let s=Fg(t.start_date),l=Fg(t.end_date),c=r&&i===0&&s!==null&&l!==null&&l<s;return c&&e.warn("[baseline] normalizing inverted zero-duration milestone to one instant"),{startDate:s,endDate:c?s:l,durationDays:i,cost:a,workHours:o,versionId:typeof t.sectorbaselineversionId=="number"?t.sectorbaselineversionId:null,isActiveVersion:!!t.sectorbaselineversion?.active,isVisibleVersion:!!t.sectorbaselineversion?.visible,isProjectVersion:t.sectorbaselineversion?.role===sa.PROJECT,isPrimaryVersion:t.sectorbaselineversion?.role===sa.PRIMARY,baseCalendarId:t.baseCalendarId!=null?String(t.baseCalendarId):null,hoursPerDay:typeof t.hoursPerDay=="number"?t.hoursPerDay:null,hoursPerWeek:typeof t.hoursPerWeek=="number"?t.hoursPerWeek:null}}var Jd=1440*60*1e3,wg=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/,xg=/^\d{4}[/-]\d{1,2}[/-]\d{1,2}[ T](\d{1,2}):(\d{2})/,Ka=7,Ya={DAILY:"DAILY",WEEKLY:"WEEKLY",MONTHLY:"MONTHLY",YEARLY:"YEARLY"},ji=12,Xd=[!1,!0,!0,!0,!0,!0,!1],Mg=new Set(["1","true"]),Zd=Dt.DURATION,Ug=_.ASAP,Hg={ASAP:_.ASAP,ALAP:_.ALAP,SNET:_.SNET,SNLT:_.SNLT,FNET:_.FNET,FNLT:_.FNLT,MSO:_.MSO,MFO:_.MFO,"AS SOON AS POSSIBLE":_.ASAP,"AS LATE AS POSSIBLE":_.ALAP,"START NO EARLIER THAN":_.SNET,"START NO LATER THAN":_.SNLT,"FINISH NO EARLIER THAN":_.FNET,"FINISH NO LATER THAN":_.FNLT,"MUST START ON":_.MSO,"MUST FINISH ON":_.MFO};function yl(t,e){let n=[],r=t.map(a=>{let o=qL(a,e);return a.should_be_showed===!1&&n.push(o.id),o});zL(r);let i=new Set(r.map(a=>a.id));return JL(r,i,e.reporter,e.recordDiagnostic),{activities:r,activityIds:i,hiddenIds:n}}function ML(t,e,n,r){if(!t)return null;let i=Hg[t.toUpperCase()];return i===void 0?(n(ie.UNKNOWN_CONSTRAINT,r),e.warn(`[parseFromBackend] unknown constraint label "${t}" \u2014 defaulting to "asap"`),Ug):i}function UL(t,e,n){let r=ML(t.constraint,e,n,String(t.unique_id)),a=r!==_.ASAP&&r!==_.ALAP&&t.constraint_date?dn(t.constraint_date):null;return{constraintType:r,constraintDate:a}}function HL(t,e,n){if(t==null)return n;let r=String(t);return e.has(r)?r:n}function BL(t){if(t==null||t==="")return[];if(Array.isArray(t))return t.map(String);if(typeof t!="string")return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.map(String):[]}catch{return[]}}function jL(t){if(typeof t!="object"||t===null||!("id"in t))return!1;let e=t.id;return typeof e=="string"||typeof e=="number"}function Qd(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)jL(n)&&e.push(String(n.id));return e}function VL(t){return t==="0"?null:String(t)}function WL(t){if(t==null)return null;if(!(typeof t=="number"&&(t===0||Number.isSafeInteger(t)&&t>0)))throw new Error(`invalid activity proplannerId ${String(t)}`);return t}function KL(t,e,n,r){let i=Number(t);if(!Number.isFinite(i))throw new TypeError(`invalid activity progress ${String(t)}`);let a=i<0,o=i>Nc;if(!a&&!o)return i;let l=a?0:100;return n(ie.PROGRESS_OUT_OF_RANGE,r),e.warn(`[parseFromBackend] activity "${r}" progress ${String(t)} is out of range \u2014 clamping to ${l}`),l}function YL(t,e){return typeof t.is_critical=="boolean"?t.is_critical:(e.error("[parseFromBackend] invalid activity is_critical \u2014 defaulting to false",new TypeError(`activity "${t.unique_id}" received ${typeof t.is_critical}`)),!1)}function GL(t,e,n,r,i){return Array.isArray(t)?t.map(a=>pl(a,e,{record:n,sampleId:r},i)).filter(a=>a!==null):[]}function qL(t,e){let n=HL(t.calendarId,e.knownCalendarIds,e.defaultCalendarId),r=t.calendarId==null||!e.knownCalendarIds.has(String(t.calendarId)),i=KL(t.progress,e.reporter,e.recordDiagnostic,String(t.unique_id)),{constraintType:a,constraintDate:o}=UL(t,e.reporter,e.recordDiagnostic),s=t.type===U.MILESTONE,l=dn(t.start_date),c=s?l:dn(t.end_date),d=s?0:Number(t.duration),u=YL(t,e.reporter);return{id:String(t.unique_id),proplannerId:WL(t.id),parentId:VL(t.parent_id),name:t.name,description:t.description??"",type:t.type,startDate:l,endDate:c,durationHours:gr(d,e.hoursPerDay),constraintType:a,constraintDate:o,autoScheduling:ue(i),calendarId:n,assignedDefaultCalendar:n!=null&&r,dateOrigin:t.date_origin==null?null:dn(t.date_origin),progress:i,cost:Number(t.cost),usedCost:Number(t.used_cost??0),realCost:Number(t.real_cost??0),workHours:Number(t.hhWorkTime),realWorkHours:Number(t.real_work??0),ponderator:Number(t.ponderator??0),hasCustomPonderator:t.hasCustomPonderator,correlativeId:t.correlative_id,uniqueCorrelativeId:t.unique_correlative_id,customId:$L(t),subcontractId:t.subcontractId,isLookahead:t.isOnLookahead,hasLookaheadTasks:Array.isArray(t.tasks)&&t.tasks.length>0,newActivityIds:me(BL(t.newActivitiesArray)),hasNewActivities:t.hasNewActivities??!1,...t.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:me(Qd(t.pendingRequests)),responsableIds:me(Qd(t.responsables)),tagIds:me(Qd(t.tags)),baselinePoints:me(GL(t.baseline_points,e.reporter,e.recordDiagnostic,String(t.unique_id),s)),baselineSnapshot:null,baselineVarianceDays:null,projectBaselineVarianceDays:null,primaryBaselineVarianceDays:null,recursiveDurationHours:gr(Number(t.sumOfDurationRecursively??0),e.hoursPerDay),calendarDuration:Ge({type:t.type,startDate:l,endDate:c}),isCritical:u,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function $L(t){return t.has_childs?null:t.custom_id}function zL(t){let e=t.find(n=>n.correlativeId===0&&n.type===U.PROJECT);e&&(e.parentId=null)}function JL(t,e,n,r){for(let i of t)i.parentId!==null&&(e.has(i.parentId)||(n.warn(`[parseFromBackend] activity "${i.id}" references unknown parent "${i.parentId}" \u2014 re-parenting to root (null)`),r(ie.ORPHAN_ACTIVITY,i.id),i.parentId=null))}function XL(t){if(typeof t!="string")return null;let e=wy(t);return e||(Do(t)?t:null)}function ZL(t){if(t==null)return;if(!(typeof t=="number"&&(t===0||Number.isSafeInteger(t)&&t>0)))throw new Error(`invalid link proplannerId ${String(t)}`);return t}function fl(t,e){let n=[];for(let r of t)try{n.push(QL(r,e.knownActivityIds,e.hoursPerDay))}catch(i){e.recordDiagnostic(ie.INVALID_LINK,String(r.unique_id??r.id)),e.reporter.warn("[parseFromBackend] dropping invalid link",i)}return tO(n,e.recordDiagnostic)}function QL(t,e,n){let r=String(t.unique_id??t.id),i=String(t.source_id??t.source??""),a=String(t.target_id??t.target??"");if(!e.has(i))throw new Error(`[parseFromBackend] link "${r}" source "${i}" does not exist`);if(!e.has(a))throw new Error(`[parseFromBackend] link "${r}" target "${a}" does not exist`);let o=XL(t.type);if(o===null)throw new Error(`[parseFromBackend] link "${r}" has invalid type "${String(t.type)}"`);let s=t.ganttId,l=t.sectorId,c=ZL(t.id);return{id:r,source:i,target:a,type:o,lag:Ee(Number(t.lag??0),n),freeSlackHours:null,isCritical:!1,...typeof s=="number"?{ganttId:s}:{},...typeof l=="number"?{sectorId:l}:{},...c===void 0?{}:{proplannerId:c}}}function tO(t,e){let n=new Map;for(let r of t){let i=`${r.source}-${r.target}-${r.type}`,a=n.get(i);if(!a){n.set(i,r);continue}let o=Bg(r)>Bg(a),s=o?a:r;e(ie.DUPLICATE_LINK,s.id),o&&n.set(i,r)}return[...n.values()]}function Bg(t){let e=Number(t.id);return Number.isFinite(e)?e:-1/0}var X={TRACKED:"tracked",IGNORED:"ignored"};var jg={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,baselineVarianceDays:X.IGNORED,projectBaselineVarianceDays:X.IGNORED,primaryBaselineVarianceDays:X.IGNORED,expectedProgress:X.IGNORED,expectedProgressBaseline:X.IGNORED,status:X.IGNORED,criticalPath:X.IGNORED,p6:X.IGNORED},eO=Object.keys(jg).filter(t=>jg[t]===X.TRACKED),nO=["startDate","endDate","constraintDate","dateOrigin"],rO=new Set(nO),iO=new Set(["newActivityIds","responsableIds","tagIds"]),Wg=Object.freeze([]),qa={DATE:0,ID_ARRAY:1,SCALAR:2},aO=t=>rO.has(t)?qa.DATE:iO.has(t)?qa.ID_ARRAY:qa.SCALAR,Kg=eO.map(t=>({field:t,kind:aO(t)}));function wr(t){return{parentId:t.parentId,name:t.name,description:t.description,type:t.type,startDate:Ga(t.startDate),endDate:Ga(t.endDate),durationHours:t.durationHours,constraintType:t.constraintType,constraintDate:Ga(t.constraintDate),autoScheduling:t.autoScheduling,calendarId:t.calendarId,dateOrigin:Ga(t.dateOrigin),progress:t.progress,cost:t.cost,usedCost:t.usedCost,realCost:t.realCost,workHours:t.workHours,realWorkHours:t.realWorkHours,ponderator:t.ponderator,hasCustomPonderator:t.hasCustomPonderator,correlativeId:t.correlativeId,uniqueCorrelativeId:t.uniqueCorrelativeId,customId:t.customId,subcontractId:t.subcontractId,isLookahead:t.isLookahead,newActivityIds:tu(t.newActivityIds),hasNewActivities:t.hasNewActivities,responsableIds:tu(t.responsableIds),tagIds:tu(t.tagIds)}}var Ga=t=>typeof t?.getTime=="function"?t.getTime():null;function tu(t){return Array.isArray(t)&&t.length>0?[...t]:Wg}function $a(t,e){for(let{field:n,kind:r}of Kg)if(!Yg(r,t[n],e[n]))return!0;return!1}function He(t,e){let n=[];for(let{field:r,kind:i}of Kg)Yg(i,t[r],e[r])||n.push(r);return n}function Yg(t,e,n){return t===qa.DATE?oO(e,n):t===qa.ID_ARRAY?lO(e,n):(e??null)===(n??null)}function oO(t,e){return Ga(t)===(typeof e=="number"?e:null)}var Vg=t=>Array.isArray(t)?t:Wg;function sO(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(String(t[n])!==String(e[n]))return!1;return!0}function lO(t,e){let n=Vg(t),r=Vg(e);if(sO(n,r))return!0;let i=new Set(n.map(String)),a=new Set(r.map(String));if(i.size!==a.size)return!1;for(let o of i)if(!a.has(o))return!1;return!0}var Gg={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},eu=Object.keys(Gg).filter(t=>Gg[t]===X.TRACKED);function hl(t,e){return eu.some(n=>t[n]!==e[n])}function qg(t,e){let n=new Map(t.map(r=>[String(r.id),r]));return e.filter(r=>{let i=n.get(String(r.id));return i?hl(i,r):!1})}var za=t=>q(t)?null:String(t);function $g(t){let e=new Map;for(let n of t.localActivities)e.set(String(n.id),za(n.parentId));for(let n of t.createActivities)e.set(String(n.id),za(n.parentId));for(let n of t.updateActivities)n.fields.parentId!==void 0&&e.set(n.activityId,za(n.fields.parentId));for(let n of t.removeActivityIds)e.delete(n);return e}function zg(t){let e=new Set;for(let n of t.keys()){let r=[],i=new Set,a=n;for(;a!=null&&!e.has(a);){if(i.has(a))return r.slice(r.indexOf(a));i.add(a),r.push(a),a=t.get(a)}for(let o of r)e.add(o)}return null}function cO(t,e,n){let r=n.updateActivities.find(i=>i.activityId===t);if(r){let i=n.updateActivities.indexOf(r);n.updateActivities[i]={activityId:t,fields:{...r.fields,parentId:e.parentId}};return}n.updateActivities.push({activityId:t,fields:{parentId:e.parentId}})}function Jg(t){let e=new Map(t.remoteActivities.map(a=>[String(a.id),a])),n=[],r=$g(t),i=zg(r);for(;i!==null;){let a=i.find(s=>{let l=e.get(s);return l!==void 0&&za(l.parentId)!==r.get(s)}),o=a===void 0?void 0:e.get(a);if(a===void 0||o===void 0)break;n.push({entity:Kt.ACTIVITY,id:a,kind:Gt.FIELD,field:O.PARENT,mine:r.get(a)??null,theirs:za(o.parentId)}),cO(a,o,t),r=$g(t),i=zg(r)}return n}function nu(t){let e=Fn(t,t.getAllLinks());return li(e).reduce((n,r)=>n+r.length,0)}function Xg(t,e,n){let r=new Map,i=[];if(nu(t)===0)return{conflicts:i,removed:r};let a=[];for(let s of e){let l=t.getLink(s);l&&(a.push({...l}),t.removeLink(s))}let o=nu(t);for(let s of a){t.addLink(s);let l=nu(t);if(l<=o){o=l;continue}t.removeLink(String(s.id)),r.set(String(s.id),s),i.push({entity:Kt.LINK,id:String(s.id),kind:Gt.LINK_CYCLE,field:null,mine:Ft(s),theirs:null})}return n.push(...te(new Map(r))),{conflicts:i,removed:r}}var dO=new Set([O.CORRELATIVE_ID,O.UNIQUE_CORRELATIVE_ID]),uO=new Set([O.END_DATE]),aA=new Set([O.START_DATE,O.DURATION_HOURS,O.COST,O.USED_COST,O.WORK_HOURS]),oA=new Set([O.REAL_WORK_HOURS,O.HAS_NEW_ACTIVITIES]),ru=new Set([...aA,O.PROGRESS,O.TYPE,O.REAL_COST,O.PONDERATOR,O.AUTO_SCHEDULING]),pO=new Set([O.NEW_ACTIVITIES_ARRAY]);function sA(t){let e={createActivities:[],updateActivities:[],removeActivityIds:[],createLinks:[],updateLinks:[],removeLinkIds:[],remoteChanges:[],conflicts:[]};return mO(t,e),e.conflicts.push(...Jg({localActivities:t.localActivities,remoteActivities:t.remoteActivities,createActivities:e.createActivities,removeActivityIds:e.removeActivityIds,updateActivities:e.updateActivities})),RO(t,e),e}function Zg(t){let e=new Set;for(let n of t)q(n.parentId)||e.add(String(n.parentId));return e}function Qg(t){return new Set(t.map(e=>String(e.target)))}function yO(t){return{localParentIds:Zg(t.localActivities),remoteParentIds:Zg(t.remoteActivities),localTargetIds:Qg(t.localLinks),remoteTargetIds:Qg(t.remoteLinks)}}function fO(t,e){return{local:{isParent:e.localParentIds.has(t),hasPredecessors:e.localTargetIds.has(t)},remote:{isParent:e.remoteParentIds.has(t),hasPredecessors:e.remoteTargetIds.has(t)}}}function lA(t,e,n){return uO.has(t)||e.isParent&&aA.has(t)||t===O.START_DATE&&e.hasPredecessors&&n.autoScheduling?!0:t===O.PONDERATOR&&!n.hasCustomPonderator}function hO(t,e,n){return lA(t,e,n)||oA.has(t)?!0:e.isParent&&ru.has(t)}function tA(t,e,n){return e===null?new Set:new Set(He(t,e).filter(r=>!hO(r,n,t)))}function mO(t,e){let n=yO(t),r=new Map(t.localActivities.map(a=>[String(a.id),a])),i=new Set;for(let a of t.remoteActivities){let o=String(a.id);i.add(o);let s=t.checkpoint.checkpointActivity(o),l=r.get(o)??null,c=fO(o,n);gO(o,a,s,l,c,e)}for(let a of t.checkpoint.checkpointActivityIds()){if(i.has(a))continue;let o=r.get(a);if(!o)continue;let s=t.checkpoint.checkpointActivity(a);EO(a,s,o,e)}}function gO(t,e,n,r,i,a){if(n===null){if(r===null){a.createActivities.push(e);return}eA(t,e,null,r,i,a);return}let o=He(e,n);if(r===null){if(o.length===0)return;a.createActivities.push(e),a.conflicts.push({entity:Kt.ACTIVITY,id:t,kind:Gt.DELETED_LOCALLY,field:null,mine:null,theirs:wr(e)});return}eA(t,e,n,r,i,a)}var Be={LOCAL:"local",REMOTE:"remote"};function AO(t){return t.local.isParent?Be.LOCAL:t.remote.isParent?Be.REMOTE:null}function IO(t,e){let n=t.remoteFields.includes(e),r=t.localChangedFields.has(e);if(e===O.TYPE)return r?n?AO(t.context)??Be.REMOTE:Be.LOCAL:Be.REMOTE;if(lA(e,t.context.local,t.local)||!r||t.remoteSourceFields.has(e))return Be.REMOTE;let i=t.context.local.isParent&&t.context.remote.isParent,a=oA.has(e)||i&&ru.has(e);return n&&a?Be.REMOTE:Be.LOCAL}function eA(t,e,n,r,i,a){let o=wr(r),s=wr(e),l=He(e,o);if(l.length===0)return;let c=n===null?l:He(e,n),d={activityId:t,remote:e,local:r,remotePersistable:s,localPersistable:o,remoteFields:c,localFields:tA(r,n,i.local),localChangedFields:new Set(n===null?[]:He(r,n)),remoteSourceFields:n===null?new Set(l):tA(e,n,i.remote),context:i};_O(d,a);let u=SO(d,l,a);Object.keys(u).length!==0&&a.updateActivities.push({activityId:t,fields:u})}function SO(t,e,n){let r={};for(let i of e)if(!(dO.has(i)||i===O.AUTO_SCHEDULING)){if(pO.has(i)){vO(t,i,r);continue}i===O.HAS_NEW_ACTIVITIES&&r.hasNewActivities!==void 0||IO(t,i)!==Be.LOCAL&&(Reflect.set(r,i,t.remote[i]),t.remoteSourceFields.has(i)&&DO(t,i,n))}return r.progress!==void 0&&!t.context.local.isParent&&(r.autoScheduling=ue(r.progress)),CO(t,r,n),r}function vO(t,e,n){let{localPersistable:r,remotePersistable:i}=t,a=TO(r[e],i[e]);Reflect.set(n,e,a),Reflect.set(n,O.HAS_NEW_ACTIVITIES,a.length>0||r.hasNewActivities||i.hasNewActivities)}function CO(t,e,n){let r=e.type??t.local.type,i=e.durationHours??t.local.durationHours;if(r!==U.MILESTONE||i===0)return;let a=e.durationHours!==void 0,o=a?O.TYPE:O.DURATION_HOURS;a?e.type=t.remote.type:e.durationHours=0,n.conflicts.push({entity:Kt.ACTIVITY,id:t.activityId,kind:Gt.FIELD,field:o,mine:t.localPersistable[o],theirs:a?t.remote.type:0})}function DO(t,e,n){let r=t.local[e],i=t.remote[e];if(t.localFields.has(e)){n.conflicts.push({entity:Kt.ACTIVITY,id:t.activityId,kind:Gt.FIELD,field:e,mine:r,theirs:i});return}n.remoteChanges.push({entity:Kt.ACTIVITY,id:t.activityId,field:e,before:r,after:i})}function TO(t,e){let n=new Set;for(let r of Array.isArray(t)?t:[])n.add(String(r));for(let r of Array.isArray(e)?e:[])n.add(String(r));return[...n]}function nA(t,e){let n={};for(let r of t)ru.has(r)&&r!==O.TYPE&&Reflect.set(n,r,e[r]);return n}function _O(t,e){let{context:n,localPersistable:r,remotePersistable:i}=t;if(n.local.isParent===n.remote.isParent)return;let a=n.remote.isParent?nA(t.localFields,r):nA(t.remoteFields,i);if(Object.keys(a).length===0)return;let o=n.remote.isParent?{kind:Gt.BECAME_PARENT_REMOTELY,mine:a,theirs:i}:{kind:Gt.BECAME_PARENT_LOCALLY,mine:r,theirs:a};e.conflicts.push({entity:Kt.ACTIVITY,id:t.activityId,field:null,...o})}function EO(t,e,n,r){r.removeActivityIds.push(t),e!==null&&He(n,e).length>0&&r.conflicts.push({entity:Kt.ACTIVITY,id:t,kind:Gt.DELETED_REMOTELY,field:null,mine:wr(n),theirs:null})}function RO(t,e){let n=new Map(t.localLinks.map(a=>[String(a.id),a])),r=new Set,i=[];for(let a of t.remoteLinks){let o=String(a.id);r.add(o);let s=t.checkpoint.checkpointLink(o),l=n.get(o)??null;s===null&&l===null&&i.push(a),kO(o,a,s,l,e)}for(let a of t.checkpoint.checkpointLinkIds()){if(r.has(a))continue;let o=n.get(a);if(!o)continue;let s=t.checkpoint.checkpointLink(a);bO(a,s,o,e)}PO(t,i,r,e)}function rA(t){return[String(t.source),String(t.target)].sort().join("|")}function PO(t,e,n,r){if(e.length===0)return;let i=new Map(e.map(a=>[rA(a),a]));for(let a of t.localLinks){let o=String(a.id);if(!(!n.has(o)&&t.checkpoint.checkpointLink(o)===null))continue;let l=i.get(rA(a));if(!l)continue;r.removeLinkIds.push(o);let c=Mr(a),d=Mr(l);xr(c,d).length!==0&&r.conflicts.push({entity:Kt.LINK,id:String(l.id),kind:Gt.DUPLICATE_LINK,field:null,mine:c,theirs:d})}}function xr(t,e){return eu.filter(n=>t[n]!==e[n])}function kO(t,e,n,r,i){if(n===null){if(r===null){i.createLinks.push(e);return}iA(t,e,null,r,i);return}if(r===null){if(xr(e,n).length===0)return;i.createLinks.push(e),i.conflicts.push({entity:Kt.LINK,id:t,kind:Gt.DELETED_LOCALLY,field:null,mine:null,theirs:Mr(e)});return}iA(t,e,n,r,i)}function Mr(t){return{source:String(t.source),target:String(t.target),type:t.type,lag:Number(t.lag)}}function iA(t,e,n,r,i){let a=Mr(e),o=Mr(r),s=n===null?xr(a,o):xr(a,n);if(s.length===0)return;let l=new Set(n===null?[]:xr(o,n)),c=new Set(xr(a,o)),d={};for(let u of s)if(c.has(u)){if(Reflect.set(d,u,a[u]),l.has(u)){i.conflicts.push({entity:Kt.LINK,id:t,kind:Gt.FIELD,field:u,mine:o[u],theirs:a[u]});continue}i.remoteChanges.push({entity:Kt.LINK,id:t,field:u,before:o[u],after:a[u]})}Object.keys(d).length!==0&&i.updateLinks.push({linkId:t,fields:d})}function bO(t,e,n,r){r.removeLinkIds.push(t),e!==null&&xr(Mr(n),e).length>0&&r.conflicts.push({entity:Kt.LINK,id:t,kind:Gt.DELETED_REMOTELY,field:null,mine:Mr(n),theirs:null})}var LO=t=>q(t)?"0":String(t),cA=t=>{let e=Number(t);return Number.isFinite(e)?e:Number.MAX_SAFE_INTEGER};function ml(t){let e=new Map;for(let r of t){let i=LO(r.parentId),a=e.get(i)??[];a.push(r),e.set(i,a)}let n=new Map;for(let[r,i]of e)i.sort((a,o)=>cA(a.correlativeId)-cA(o.correlativeId)||a.id.localeCompare(o.id)),n.set(r,i.map(a=>a.id));return n}var au=t=>({id:String(t.id),parentId:t.parentId,correlativeId:t.correlativeId});function uA(t,e,n){let r=[];for(let i of n.checkpointActivityIds()){let a=n.checkpointActivity(i);a!==null&&r.push({id:i,parentId:a.parentId,correlativeId:a.correlativeId})}return{local:ml(t.map(au)),remote:ml(e.map(au)),base:ml(r)}}function iu(t,e){let n=new Set(e),r=new Set(t),i=t.filter(o=>n.has(o)),a=e.filter(o=>r.has(o));return i.some((o,s)=>a[s]!==o)}function dA(t,e,n){let r=t.filter(a=>n.has(a)),i=-1;for(let a of e){let o=r.indexOf(a);if(o!==-1){i=o;continue}n.has(a)&&(r.splice(i+1,0,a),i+=1)}for(let a of n)r.includes(a)||r.push(a);return r}function OO(t,e,n){let r=n.local.get(t)??[],i=n.remote.get(t)??[],a=n.base.get(t)??[],o=iu(r,a),s=iu(i,a),c=o&&!s?dA(r,i,e):dA(i,r,e),d=o&&s&&iu(r,c);return{order:c,conflict:d?{entity:Kt.ACTIVITY,id:t,kind:Gt.ORDER,field:O.CORRELATIVE_ID,mine:r.filter(u=>e.has(u)),theirs:c}:null}}function NO(t){return ml(t.getAllActivities().map(au))}function pA(t,e){let{orders:n,conflicts:r}=FO(t,e);return{shifts:wO(t,n),conflicts:r}}function FO(t,e){let n=new Map,r=[];for(let[i,a]of NO(t)){let o=OO(i,new Set(a),e);n.set(i,o.order),o.conflict!==null&&r.push(o.conflict)}return{orders:n,conflicts:r}}function wO(t,e){let n=[],r=0,i=[...e.get("0")??[]].reverse();for(;i.length>0;){let a=i.pop();if(a===void 0)break;let o=xO(t,a,r);o!==null&&n.push(o),r+=1,MO(i,e.get(a)??[])}return n}function xO(t,e,n){let r=t.getActivity(e);if(!r||r.correlativeId===n)return null;let i=Number(r.correlativeId);return t.setActivityField(e,O.CORRELATIVE_ID,n),{activityId:e,before:Number.isFinite(i)?i:void 0}}function MO(t,e){for(let n=e.length-1;n>=0;n-=1){let r=e[n];r!==void 0&&t.push(r)}}var yA=t=>t==null||t===0,fA=t=>yA(t.proplannerId);function UO(t,e){let n=t.linkIdGen.next(),r=i=>t.adapter.getLink(i)!==null||t.isLinkIdReserved(String(i))||e.has(String(i));for(;r(n);)n=t.linkIdGen.next();return n}function HO(t,e){let n=new Set;for(let a of t)n.add(String(a.id)),e.linkIdGen.bump(a.id);let r=new Set(n),i=[];for(let a of e.adapter.getAllLinks()){let o=String(a.id);if(!n.has(o)||!yA(a.proplannerId))continue;let s=String(UO(e,r));r.add(s),i.push({from:o,to:s})}return i}function BO(t){let e=new Map;for(let n of t)n.customId&&e.set(n.customId,String(n.id));return e}function jO(t,e){let n=e.persistenceCheckpoint.checkpointActivity(String(t.id));return n===null||n.customId!==t.customId}function VO(t,e){let n=BO(t);e.customIdTracker.populateFromActivities(t);let r=[];for(let i of e.adapter.getVisualOrderIds()){let a=e.adapter.getActivity(i);if(!a?.customId)continue;let o=n.get(a.customId);o===void 0||o===String(a.id)&&!fA(a)||jO(a,e)&&r.push({activityId:a.id,nextCustomId:e.customIdTracker.generateCustomIdForRestoredChild(a.customId)})}return r}function WO(t,e){let n=t.activityIdGen.next(),r=i=>t.adapter.activityExists(i)||t.isActivityIdReserved(String(i))||e.has(String(i));for(;r(n);)n=t.activityIdGen.next();return n}function hA(t,e){let n=t.activities,r=new Set,i=new Set;for(let l of n)r.add(String(l.id)),i.add(String(l.uniqueCorrelativeId)),e.activityIdGen.bump(l.id),e.uidGen.bump(l.uniqueCorrelativeId);let a=new Set,o=[],s=[];for(let l of e.adapter.getAllActivities()){if(!fA(l))continue;let c=String(l.id);if(r.has(c)){let d=WO(e,a);a.add(String(d)),o.push({from:c,to:String(d),parentId:e.adapter.getParent(l.id)?.id??null,childIds:[...e.adapter.getChildren(l.id)],outgoingLinkIds:[...e.adapter.getOutgoingLinkIds(l.id)],incomingLinkIds:[...e.adapter.getIncomingLinkIds(l.id)]})}i.has(String(l.uniqueCorrelativeId))&&s.push({activityId:l.id,nextUniqueCorrelativeId:e.uidGen.next()})}return{activities:o,links:HO(t.links,e),uniqueCorrelativeIds:s,customIds:VO(n,e)}}function mA(t){let e=new Set;for(let n of t.activities){e.add(n.from),e.add(n.to),n.parentId!==null&&e.add(String(n.parentId));for(let r of n.childIds)e.add(String(r))}for(let n of t.uniqueCorrelativeIds)e.add(String(n.activityId));for(let n of t.customIds)e.add(String(n.activityId));return e}function KO(t,e,n){return t.map(r=>String(r)===e?n:r)}function YO(t,e){let n=e.getActivity(t.from);if(!n)return;let r=st(n);r.id=t.to;let i=e.isChecked(t.from),a=e.isVisible(t.from),o=e.getLastStartDate(t.from),s=e.getPromotionSnapshot(t.from),l=e.getProgressFallback(t.from);e.removeActivity(t.from),e.addActivity(r),i&&e.setChecked(t.to,!0),a||e.setVisible(t.to,!1),o&&e.setLastStartDate(t.to,o),s&&e.setPromotionSnapshot(t.to,s),l!==null&&e.setProgressFallback(t.to,l);for(let u of t.childIds)e.setActivityFields(u,{parentId:t.to});for(let u of t.outgoingLinkIds){let p=e.getLink(u);p&&e.setLinkEndpoints(u,t.to,p.target)}for(let u of t.incomingLinkIds){let p=e.getLink(u);p&&e.setLinkEndpoints(u,p.source,t.to)}let c=e.getParent(t.to);!c||!c.newActivityIds.some(u=>String(u)===t.from)||e.setActivityFields(c.id,{newActivityIds:KO(c.newActivityIds,t.from,t.to)})}function GO(t,e){let n=new Map,r=[];for(let i of t){let a=e.getLink(i.from);if(!a)continue;n.set(i.from,{...a}),e.removeLink(i.from);let o={...a,id:i.to};e.addLink(o),r.push(o)}return{before:n,after:r}}function gA(t,e){for(let n of t.uniqueCorrelativeIds)e.setActivityField(n.activityId,O.UNIQUE_CORRELATIVE_ID,n.nextUniqueCorrelativeId);for(let n of t.customIds)e.setActivityField(n.activityId,O.CUSTOM_ID,n.nextCustomId);for(let n of t.activities)YO(n,e);return GO(t.links,e)}function qO(t){for(let e of t.values())if(e.is_default)return String(e.id);return null}function $O(t,e){return t.remote.activities.some(n=>n.calendarId!=null&&!e.has(String(n.calendarId)))}function zO(t,e){let{activities:n,activityIds:r}=yl([...t.remote.activities],{knownCalendarIds:new Set(e.calendars.keys()),defaultCalendarId:qO(e.calendars),hoursPerDay:e.sector.hoursPerDay,reporter:e.reporter,recordDiagnostic:hn}),i=fl([...t.remote.links],{knownActivityIds:r,hoursPerDay:e.sector.hoursPerDay,reporter:e.reporter,recordDiagnostic:hn});return{activities:n,links:i}}function JO(t){return t.activities.every(e=>typeof e.proplannerId=="number"&&e.proplannerId>0)}async function AA(t,e,n){let{adapter:r,scheduler:i,sector:a}=n;if($O(t,n.calendars))return{ok:!1,reason:C.INVALID};let o=zO(t,n);if(!JO(o))return{ok:!1,reason:C.INVALID};i.invalidateAllCaches();let s=nN(r),l=await ZO(o,n),c=sA({remoteActivities:o.activities,remoteLinks:o.links,localActivities:r.getAllActivities(),localLinks:r.getAllLinks(),checkpoint:n.persistenceCheckpoint}),d=uA(r.getAllActivities(),o.activities,n.persistenceCheckpoint),u=new Set(c.removeActivityIds),p=cN(c,r),y=await tN(r,p,l);for(let w of l.touchedIds)p.add(w);let f=dN(c,u,r),m=Fr(r,u);for(let w of f.keys())r.removeLink(w);for(let w of u)r.removeActivity(w);for(let w of c.createActivities)r.addActivity(st(w)),n.uidGen.bump(w.uniqueCorrelativeId),n.customIdTracker.populateFromActivities([w]);for(let w of c.updateActivities)r.setActivityFields(w.activityId,w.fields);eN(c,r);let A=pN(r,n.persistenceCheckpoint,p);oN(n,p),aN(r,p),sN(r,p);let g=[...QO(l.links),...yN(c,f,r)],P=fN(r,g),L=Xg(r,rN(s,l.plan.links),g),F=new Set(c.createActivities.map(w=>String(w.id))),T=new Set([...F,...l.plan.activities.map(w=>w.to)]),x=pA(r,d),S=[...x.shifts,...Ut(r)].filter(w=>!T.has(w.activityId)),{scheduledIds:k}=await ot({adapter:r,scheduler:i,sector:a,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:Et.ROOTS,recomputeParentsFrom:lN(p,r),recomputeParentProgress:!0,now:n.now,options:e});iN(r,p);let E=await tt(r,{source:t,beforeSnap:y,touchedIds:p,scheduledIds:k,links:g,hoursPerDay:a.hoursPerDay,correlativeShifts:S}),j={remoteChanges:c.remoteChanges,conflicts:[...c.conflicts,...A,...x.conflicts,...P,...L.conflicts],createdActivityIds:[...F],removedActivityIds:[...u],rekeyedActivities:l.plan.activities.map(({from:w,to:B})=>({from:w,to:B})),rekeyedLinks:l.plan.links,createdLinkIds:c.createLinks.map(w=>String(w.id)),removedLinkIds:XO(g,r)};return{ok:!0,changes:m.length>0?{...E,viewState:m}:E,rebase:j,__beforeSnap:y,__beforeLinks:new Map([...l.links.before,...f,...L.removed]),__rebaseCheckpoint:{activities:o.activities,links:o.links}}}function XO(t,e){return t.filter(n=>n.kind===W.DELETED).map(n=>String(n.id)).filter(n=>!e.getLink(n))}async function ZO(t,e){let n=hA(t,e),r=mA(n),i=await dt(e.adapter,r),a=gA(n,e.adapter);return{plan:n,touchedIds:r,beforeSnap:i,links:a}}function QO(t){let e=[...te(new Map(t.before))];for(let n of t.after)e.push({id:String(n.id),kind:W.CREATED,fields:{source:{before:void 0,after:String(n.source)},target:{before:void 0,after:String(n.target)},type:{before:void 0,after:n.type},lag:{before:void 0,after:Number(n.lag)}},after:Ft(n)});return e}async function tN(t,e,n){let r=new Set([...e].filter(i=>!n.touchedIds.has(i)));return new Map([...await dt(t,r),...n.beforeSnap])}function eN(t,e){for(let n of t.updateActivities){let r=e.getActivity(n.activityId);!r||e.hasChildren(r.id)||e.setActivityField(r.id,O.END_DATE,e.calculateEndDate({startDate:r.startDate,durationHours:r.durationHours,task:r}))}}function nN(t){return t.getAllLinks().filter(e=>{let n=e.proplannerId;return n==null||n===0}).map(e=>String(e.id)).sort((e,n)=>Number(e)-Number(n))}function rN(t,e){let n=new Map(e.map(({from:r,to:i})=>[r,i]));return t.map(r=>n.get(r)??r)}function iN(t,e){for(let n of e){if(!t.hasChildren(n))continue;let r=t.getActivity(n);if(!r)continue;let i=ue(r.progress);r.autoScheduling!==i&&t.setActivityField(n,O.AUTO_SCHEDULING,i)}}function aN(t,e){for(let n of e){if(!t.hasChildren(n))continue;let r=t.getActivity(n);r&&(r.type!==U.PROJECT&&t.setActivityField(n,O.TYPE,U.PROJECT),r.customId&&t.setActivityField(n,O.CUSTOM_ID,null))}}function oN(t,e){let{adapter:n}=t;for(let r of e){let i=n.getActivity(r);if(!i||i.type!==U.PROJECT||q(i.parentId)||n.hasChildren(r))continue;let a=Xe({parent:i,remainingChildIds:[],defaultDurationHours:t.sector.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(r),computeEndDate:(l,c)=>n.calculateEndDate({startDate:l,durationHours:c,task:i}),dataDateCapability:t.dataDateCapability,hasCompleteSchedulingState:t.hasCompleteSchedulingState});if(!a)continue;n.setActivityFields(r,a.fields);let o=be(r,n),s=o?n.getActivity(o)?.customId:null;n.setActivityField(r,O.CUSTOM_ID,t.customIdTracker.generateCustomIdForRestoredChild(s||null))}}function sN(t,e){let n=new Set;for(let r of e){let i=t.getActivity(r);i&&(t.hasChildren(r)&&n.add(r),q(i.parentId)||n.add(String(i.parentId)))}for(let r of n)qt(r,t)}function lN(t,e){let n=new Set(t);for(let r of t)for(let i of e.getChildren(r))n.add(String(i));return n}function cN(t,e){let n=new Set,r=i=>{i!=null&&(q(i)||n.add(String(i)))};for(let i of t.removeActivityIds)n.add(i),r(e.getActivity(i)?.parentId);for(let i of t.createActivities)n.add(String(i.id)),r(i.parentId);for(let i of t.updateActivities)n.add(i.activityId),r(e.getActivity(i.activityId)?.parentId),i.fields.parentId!==void 0&&r(i.fields.parentId);return n}function dN(t,e,n){let r=new Map,i=Jn(e,n);for(let a of[...t.removeLinkIds,...i]){let o=n.getLink(a);o&&r.set(String(a),{...o})}return r}function uN(t,e,n){let r=new Set,i=t;for(;i!==null&&!r.has(i);){if(e.activityExists(i))return i;r.add(i);let a=n.checkpointActivity(i);if(!a||q(a.parentId))return null;i=String(a.parentId)}return null}function pN(t,e,n){let r=[];for(let i of t.getAllActivities()){if(q(i.parentId)||t.activityExists(String(i.parentId)))continue;let a=String(i.parentId),o=uN(a,t,e);t.setActivityField(i.id,O.PARENT,o),n.add(String(i.id)),o!==null&&n.add(o),r.push({entity:Kt.ACTIVITY,id:String(i.id),kind:Gt.PARENT_REMOVED,field:O.PARENT,mine:a,theirs:o??"0"})}return r}function yN(t,e,n){let r=[...te(new Map(e))];for(let i of t.createLinks){if(n.getLink(i.id))continue;n.addLink({...i,freeSlackHours:null,isCritical:!1});let a=n.getLink(i.id);a&&r.push({id:String(i.id),kind:W.CREATED,fields:{source:{before:void 0,after:String(a.source)},target:{before:void 0,after:String(a.target)},type:{before:void 0,after:a.type},lag:{before:void 0,after:Number(a.lag)}},after:Ft(a)})}for(let i of t.updateLinks){let a=n.getLink(i.linkId);if(!a)continue;let o=Ft(a),s={};for(let[c,d]of Object.entries(i.fields))n.setLinkFieldDynamic(i.linkId,c,d),s[c]={before:Reflect.get(o,c),after:d};let l=n.getLink(i.linkId);l&&r.push({id:String(i.linkId),kind:W.UPDATED,fields:s,after:Ft(l)})}return r}function fN(t,e){let n=[];for(let r of t.getAllLinks()){let i=[r.source,r.target].find(l=>!t.activityExists(String(l)));if(i===void 0)continue;let a=String(r.id),o={...r},s=String(r.source)===String(i);t.removeLink(a),e.push(...te(new Map([[a,o]]))),n.push({entity:Kt.LINK,id:a,kind:Gt.DELETED_REMOTELY,field:s?Vt.SOURCE:Vt.TARGET,mine:Ft(o),theirs:null})}return n}function IA(t,e,n,r=hn){let i=new Map;t.forEachActivity((s,l)=>{let c=s.proplannerId;typeof c=="number"&&i.set(c,l)});let a=new Map;for(let s of e){let l=s.activityId;if(typeof l!="number"){r(ie.INVALID_BASELINE_POINT,String(l??"unknown"));continue}let c=i.get(l);if(c===void 0){r(ie.INVALID_BASELINE_POINT,String(l));continue}let d=a.get(c);d?d.push(s):a.set(c,[s])}let o=[];for(let[s,l]of a){let c=t.getActivity(s)?.type===U.MILESTONE;t.setActivityField(s,"baselinePoints",l.map(d=>pl(d,n,{record:r,sampleId:s},c)).filter(d=>d!==null)),o.push(s)}return t.forEachActivity((s,l)=>{if(a.has(l))return;let c=s.baselinePoints;Array.isArray(c)&&c.length>0&&(t.setActivityField(l,"baselinePoints",[]),o.push(l))}),o}function hN(t){let e=jt(t);return e?{startDate:e.startDate,endDate:e.endDate,durationDays:e.durationDays,cost:e.cost,workHours:e.workHours}:null}function SA(t){let e=[];return t.forEachActivity((n,r)=>{let i=hN(n);if(!i){n.baselineSnapshot!==null&&(t.setActivityField(r,"baselineSnapshot",null),e.push(r));return}t.setActivityField(r,"baselineSnapshot",i),e.push(r)}),e}function gl(t,e,n,r,i=null,a=hn){let o=new Set;for(let s of IA(t,e,r,a))o.add(s);if(n)for(let s of Fa(t,n,i))o.add(s);for(let s of SA(t))o.add(s);for(let s of _i(t))o.add(s);return[...o]}function Al(t,e){let n=new Map;e.forEachActivity((r,i)=>{e.setActivityField(i,R.PONDERATOR,0)}),e.forEachActivity((r,i)=>{e.getChildren(i).length>0&&zs(String(i),t,e,n)})}function Il(t,e){Al(e,t.adapter),Ia(t.adapter,e),t.now&&(lh(t.adapter,t.now,t.defaultBaseCalendarId??null),Tr(t.adapter,t.now)),_i(t.adapter),t.now&&un(t.adapter,t.sector.statusCriteria)}function vA(t){return JSON.stringify(t.adapter.getAllIds().map(e=>{let n=t.adapter.getActivity(e)?.baselinePoints.find(r=>r.isActiveVersion);return n?[String(e),n.versionId,n.startDate?.getTime()??null,n.endDate?.getTime()??null,n.durationDays,n.cost,n.workHours,n.baseCalendarId,n.hoursPerDay,n.hoursPerWeek]:[String(e),null]}))}async function CA(t,e){let n=await dt(e.adapter,new Set(e.adapter.getAllIds())),r=vA(e),i=gl(e.adapter,t.points,e.now,e.reporter,e.defaultBaseCalendarId??null,void 0);return _r(e.adapter,e.sector.hoursPerDay),Er(e.adapter,e.sector.hoursPerDay),vA(e)!==r&&Il(e,e.sector.activityCreter??Dt.DURATION),{ok:!0,changes:await tt(e.adapter,{source:t,beforeSnap:n,touchedIds:i,scheduledIds:[],hoursPerDay:e.sector.hoursPerDay})}}function mN(t){return Object.values(Dt).includes(t)}async function DA(t,e){if(!mN(t.criterion))return{ok:!1,reason:C.INVALID_VALUE};let n=new Set(e.adapter.getAllIds()),r=await dt(e.adapter,n);return Il(e,t.criterion),e.sector.activityCreter=t.criterion,{ok:!0,changes:await tt(e.adapter,{source:t,beforeSnap:r,touchedIds:n,scheduledIds:[],hoursPerDay:e.sector.hoursPerDay})}}async function TA(t,e){let n=Cs(t.criteria),r=new Set(e.adapter.getAllIds()),i=await dt(e.adapter,r),a=un(e.adapter,n);return e.sector.statusCriteria=n,{ok:!0,changes:await tt(e.adapter,{source:t,beforeSnap:i,touchedIds:a,scheduledIds:[],hoursPerDay:e.sector.hoursPerDay})}}async function EA(t,e,n){let r=new Map,i=new Set;for(let o of n.adapter.getAllActivities()){if(!gN(o,n))continue;let s=n.ctx.calendars.getCalendar(o.calendarId);if(!s)continue;let l=s.isWorkTime(o.startDate,mt.HOUR)?AN(o.startDate):o.startDate,c=s.getClosestWorkTime({date:l,direction:yt.FUTURE,unit:mt.HOUR}),d=s.calculateEndDate(c,o.durationHours);if(_A(c,o.startDate)&&_A(d,o.endDate))continue;let u=String(o.id);r.set(u,st(o)),i.add(u),n.adapter.setActivityFields(u,{startDate:c,endDate:d})}let{scheduledIds:a}=await ot({adapter:n.adapter,scheduler:n.scheduler,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:Et.ROOTS,recomputeParentsFrom:i,now:n.now,options:e});return{ok:!0,changes:await tt(n.adapter,{source:t,beforeSnap:r,touchedIds:i,scheduledIds:a,hoursPerDay:n.sector.hoursPerDay})}}function gN(t,e){return!Fe(t.type,e.adapter.hasChildren(t.id))}function _A(t,e){return t.getTime()===e.getTime()}function AN(t){return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()))}var RA=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","cost","hasCustomPonderator","subcontractId","responsableIds","tagIds"];function Sl(t){let e={};for(let n of RA)Object.assign(e,{[n]:v(t[n])});return e}function IN(t,e){let n=[],r=i=>{e.has(String(i))&&n.push(i);for(let a of t.getChildren(i))r(a)};for(let i of t.getRootIds())r(i);return n}function kA(t,e){let n=new Set(e.adapter.checkedIds().map(String));if(n.size===0)return{ok:!1,reason:C.NO_ACTIVITY_SELECTION};let r=IN(e.adapter,n);e.clipboard.value={activities:r.map(a=>{let o=e.adapter.getActivity(a);if(o===null)throw new Error(`Selected activity ${a} is missing`);return{originalId:a,originalParentId:o.parentId??"0",overrides:Sl(o)}}),links:e.adapter.getAllLinks().filter(a=>n.has(String(a.source))&&n.has(String(a.target))).map(a=>v(a))};let i=_o({kind:I.SELECTION_REPLACE,activityIds:[]},{adapter:e.adapter});return i.ok?{...i,changes:{...i.changes,source:t}}:i}function bA(t){return{ok:!0,changes:{source:t,activities:[],links:[],calendars:[],trackingEvents:[]}}}function LA(t,e){return e.value=null,bA(t)}function PA(t,e){if(t===void 0||e===void 0)return t;let n=new Set(e);return t.filter(r=>n.has(r))}function SN(t,e,n){let r=v(t);r.calendarId!=null&&!e.calendars.has(r.calendarId)&&delete r.calendarId,n?.subcontractIds!==void 0&&r.subcontractId!=null&&!n.subcontractIds.includes(r.subcontractId)&&(r.subcontractId=null);let o=PA(r.responsableIds,n?.responsableIds);o!==void 0&&(r.responsableIds=[...o]);let s=PA(r.tagIds,n?.tagIds);return s!==void 0&&(r.tagIds=[...s]),r}function vN(t){let e=new Set(t.activities.map(n=>String(n.originalId)));return t.links.some(n=>!e.has(String(n.source))||!e.has(String(n.target)))}function OA(t,e){let{snapshot:n,references:r}=t;return n.activities.length===0?{ok:!1,reason:C.CLIPBOARD_EMPTY}:vN(n)?{ok:!1,reason:C.CLIPBOARD_SNAPSHOT_INVALID}:(e.clipboard.value={activities:n.activities.map(i=>({originalId:i.originalId,originalParentId:i.originalParentId,overrides:SN(i.overrides,e,r)})),links:n.links.map(i=>v(i))},bA(t))}var CN=200,NA={skipCorrelativeRecompute:!0,skipBeforeSnap:!0,skipCacheInvalidation:!0,skipRollupCascades:!0};async function FA(t,e,n){let r=DN(t.activityIds,n.adapter);if(!r.ok)return r;if(TN(r.runs,n.adapter))return{ok:!1,reason:C.PARENT_FROZEN_BY_SIR};n.scheduler.invalidateAllCaches();let a=await dt(n.adapter,new Set),o={originalToNew:new Map,createdIds:[],createdParentIds:[]};for(let y of r.runs){let f=y.originals.at(-1);if(!f)continue;let m=f.id;for(let A of y.originals)m=await PN(A,y.parentId,m,t,n,o)}bN(o,n);let s=Ut(n.adapter),l=new Set(o.createdIds.map(String)),c=new Set;RN(n.adapter,s,l,a);let d=ge(n.adapter,s,l,a,c);for(let y of o.createdIds)c.add(String(y));let u=LN(o,n),{scheduledIds:p}=await ot({adapter:n.adapter,scheduler:n.scheduler,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:o.createdIds.length>0?Et.ROOTS:null,recomputeParentsFrom:o.createdIds,preventSummaryTargetPullback:!0,now:n.now,options:e});return{ok:!0,changes:await tt(n.adapter,{source:t,beforeSnap:a,deferredCorrelatives:d,touchedIds:c,scheduledIds:p,links:qn(u,new Map,n.adapter),hoursPerDay:n.sector.hoursPerDay})}}function DN(t,e){if(t.length===0)return{ok:!1,reason:C.ACTIVITY_IDS_EMPTY};let n=new Set,r=[];for(let o of t){let s=String(o);if(n.has(s))continue;let l=e.getActivity(s);if(!l)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};n.add(s),r.push(l)}let i=r.filter(o=>!zn(o.id,n,e));return e.getRootIds().length===1&&i.some(o=>o.parentId==null)?{ok:!1,reason:C.SOLE_SCHEDULE_ROOT}:{ok:!0,runs:_N(i,e)}}function TN(t,e){let n=new Set;for(let r of t){if(r.parentId==="0"||n.has(String(r.parentId)))continue;n.add(String(r.parentId));let i=e.getActivity(r.parentId);if(i&&Ri(i))return i}return null}function _N(t,e){let n=new Map;for(let i of t){let a=de(i.parentId),o=n.get(a)??[];o.push(i),n.set(a,o)}let r=[];for(let[i,a]of n){let o=i==="0"?"0":i,s=new Map(wA(e,i).map((d,u)=>[String(d.id),u])),l=d=>s.get(String(d.id))??-1,c=[...a].sort((d,u)=>l(d)-l(u));for(let d of EN(c,l))r.push({parentId:o,originals:d})}return r}function EN(t,e){let n=[],r=null;for(let i of t){let a=e(i),o=n.at(-1);o&&r!==null&&a===r+1?o.push(i):n.push([i]),r=a}return n}function RN(t,e,n,r){let i=t.peekWriteCapture();if(i)for(let a of e){if(n.has(a.activityId)||r.has(a.activityId))continue;let o=i.before.get(a.activityId);o&&r.set(a.activityId,o)}}function wA(t,e){return Wa(t,e).sort((n,r)=>Qt(n)-Qt(r)||String(n.id).localeCompare(String(r.id)))}async function PN(t,e,n,r,i,a){let o=await $n({kind:I.ACTIVITY_CREATE,parentId:e,afterSiblingId:n,overrides:Sl(t),...r.eventSource===void 0?{}:{eventSource:r.eventSource}},i,{...NA,customIdReferenceId:t.id});if(!o.ok)throw ou("create",o.reason);return xA(a,t,o.newId,e),await kN(t,o.newId,r,i,a),o.newId}async function kN(t,e,n,r,i){let a=new De;a.enqueue({original:t,newParentId:e});let o=0;for(;!a.isEmpty();){let{original:s,newParentId:l}=a.dequeue();for(let c of wA(r.adapter,String(s.id))){let d=await $n({kind:I.ACTIVITY_CREATE,parentId:l,overrides:Sl(c),...n.eventSource===void 0?{}:{eventSource:n.eventSource}},r,NA);if(!d.ok)throw ou("create",d.reason);xA(i,c,d.newId,l),a.enqueue({original:c,newParentId:d.newId}),o+=1,o%CN===0&&await Ot()}}}function ou(t,e){return new Error(`[ScheduleCore] activity-duplicate: unexpected ${t} rejection after preflight passed (${e})`)}function xA(t,e,n,r){t.originalToNew.set(String(e.id),n),t.createdIds.push(n),t.createdParentIds.push(r)}function bN(t,e){let n=new Set;for(let r of[...t.createdParentIds].reverse())r==="0"||n.has(String(r))||(n.add(String(r)),qt(r,e.adapter))}function LN(t,e){let n=[];for(let r of t.originalToNew.keys())for(let i of e.adapter.getOutgoingLinkIds(r)){let a=e.adapter.getLink(i);if(!a)continue;let o=t.originalToNew.get(String(a.source)),s=t.originalToNew.get(String(a.target));if(o===void 0||s===void 0)continue;let l={kind:xt.CREATE,source:o,target:s,type:a.type,lag:a.lag},c=qe(l,{port:e.adapter,newLinkId:e.linkIdGen.next});if(!c.applied)throw ou("link",c.rejected??C.INVALID);n.push({op:l,finalLinkId:c.linkId,rejected:null})}return n}var Vi={FIELD:"field",LINKS:"links"};function ON(t,e,n){return ki(t,e,n).map(r=>({otherActivityId:n?r.source:r.target,type:r.type,lag:r.lag}))}function su(t){return{ok:!0,changes:{source:t,activities:[],links:[],calendars:[],trackingEvents:[]}}}function MA(t,e){let n=e.adapter.getActivity(t.activityId);if(!n)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};if(t.column===R.CUSTOM_PREDECESSORS||t.column===R.CUSTOM_SUCESSORS)return e.clipboard.value={kind:Vi.LINKS,specs:ON(e.adapter,t.activityId,t.column===R.CUSTOM_PREDECESSORS)},su(t);let r=he(t.column);if(!r)return{ok:!1,reason:C.NO_PIPELINE_FOR_COLUMN};let i=Oi(n,r.targetField);if(t.column===R.DURATION&&!Number.isFinite(i))return{ok:!1,reason:C.INVALID_VALUE};let a=t.column===R.DURATION?i/e.hoursPerDay:v(i);return e.clipboard.value={kind:Vi.FIELD,raw:a,sourceColumn:t.column,text:t.copiedText??null},su(t)}function UA(t,e){return e.value=null,su(t)}var HA=new Set([R.TAGS,R.RESPONSABLES,R.SUBCONTRACT_ID,R.CONSTRAINT_TYPE,R.CALENDAR_ID]);function NN(t,e){return t===e?!1:HA.has(t)||HA.has(e)}function FN(t,e){return e===void 0||t!==null&&(t.text===null||t.text===e)?null:e}function wN(t,e,n){let r=t!==null&&t.kind===Vi.FIELD?t:null,i=FN(r,n);return i!==null?{ok:!0,newValue:i}:t!==null&&t.kind!==Vi.FIELD?{ok:!1,reason:C.INVALID_VALUE}:r===null?{ok:!1,reason:C.CLIPBOARD_EMPTY}:NN(r.sourceColumn,e)?{ok:!1,reason:C.CELL_PASTE_COLUMN_MISMATCH}:{ok:!0,newValue:r.raw}}function xN(t){return String(t)}function MN(t,e){let n=e;return t.activityExists(n)?n:null}function UN(t,e,n,r){let i=n.specs.map(l=>({correlativeId:xN(l.otherActivityId),type:l.type,lag:l.lag})),a=ki(r.adapter,t,e),o=l=>MN(r.adapter,l);return(e?di({targetActivityId:t,currentLinks:a,desiredSpecs:i,resolveActivityByCorrelative:o}):ui({sourceActivityId:t,currentLinks:a,desiredSpecs:i,resolveActivityByCorrelative:o})).operations}async function HN(t,e,n,r){if(e===null)return{ok:!1,reason:C.CLIPBOARD_EMPTY};if(e.kind!==Vi.LINKS)return{ok:!1,reason:C.INVALID_VALUE};if(t.activityIds.some(c=>e.specs.some(d=>String(d.otherActivityId)===String(c))))return{ok:!1,reason:kt.SELF_LINK};let a=t.column===R.CUSTOM_PREDECESSORS,o=t.activityIds.flatMap(c=>UN(c,a,e,r)),s=o.filter(c=>c.kind===xt.CREATE).map(c=>({operation:c,linkId:r.linkIdGen.next()})),l=Aa(s,{port:r.adapter,rejectParentLinkMutations:n.rejectParentLinkMutations??!1});return l.applied?ja(o,t,n,r):{ok:!1,reason:l.rejected??C.INVALID}}async function BA(t,e,n){let r=n.cellClipboard.value;if(t.activityIds.length===0)return{ok:!1,reason:C.ACTIVITY_IDS_EMPTY};if(t.activityIds.some(l=>!n.adapter.activityExists(l)))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};if(t.column===R.CUSTOM_PREDECESSORS||t.column===R.CUSTOM_SUCESSORS)return HN(t,r,e,n);if(!he(t.column))return{ok:!1,reason:C.NO_PIPELINE_FOR_COLUMN};let a=t.column,o=wN(r,a,t.clipboardText);if(!o.ok)return o;let s=await ul({kind:I.BULK_EDIT,edits:t.activityIds.map(l=>({activityId:l,column:a,newValue:o.newValue})),...t.eventSource===void 0?{}:{eventSource:t.eventSource}},e,n);return s.ok?{...s,changes:{...s.changes,source:t}}:s}async function jA(t,e,n){return t.kind===I.ACTIVITY_COPY?kA(t,{adapter:n.adapter,clipboard:n.activityClipboard}):t.kind===I.CALENDAR_RECONCILE?EA(t,e,n):t.kind===I.ACTIVITY_CLIPBOARD_CLEAR?LA(t,n.activityClipboard):t.kind===I.ACTIVITY_CLIPBOARD_IMPORT?OA(t,{clipboard:n.activityClipboard,calendars:n.calendars}):t.kind===I.ACTIVITY_PASTE_COPIED?$m(t,e,n):t.kind===I.ACTIVITY_DUPLICATE?FA(t,e,n):t.kind===I.CELL_COPY?MA(t,{adapter:n.adapter,clipboard:n.cellClipboard,hoursPerDay:n.sector.hoursPerDay}):t.kind===I.CELL_CLIPBOARD_CLEAR?UA(t,n.cellClipboard):t.kind===I.CELL_PASTE_COPIED?BA(t,e,n):t.kind===Ye?sg(t,e,n):t.kind===I.PERSISTENCE_ACKNOWLEDGE?gg(t,n):t.kind===I.PERSISTENCE_REBASE?AA(t,e,n):t.kind===I.BASELINE_APPLY?CA(t,n):t.kind===I.PONDERATOR_CRITERION_SET?DA(t,n):t.kind===I.STATUS_CRITERIA_SET?TA(t,n):t.kind===I.LINK_CREATE||t.kind===I.LINK_UPDATE||t.kind===I.LINK_DELETE?Nm(t,e,n):t.kind===I.LINKS_BATCH?Fm(t,e,n):t.kind===I.ACTIVITY_CREATE?ig(t,e,n):t.kind===I.ACTIVITY_DELETE?ng(t,e,n):t.kind===I.ACTIVITY_MOVE?Rg(t,e,n):t.kind===I.ACTIVITY_INDENT?Pg(t,e,n):t.kind===I.ACTIVITY_OUTDENT?kg(t,e,n):t.kind===I.ACTIVITY_TYPE_SET?bg(t,e,n):t.kind===I.ACTIVITY_FIELDS_RESTORE?dg(t,e,n):t.kind===I.HISTORY_REVERT?ug(t,e,n):t.kind===I.ACTIVITY_SET_PROGRESS?Lg(t,e,n):t.kind===I.DATES_BATCH?Og(t,e,n):t.kind===I.BULK_EDIT?ul(t,e,n):t.kind===I.SELECTION_TOGGLE?Rp(t,lu(n)):t.kind===I.SELECTION_REPLACE?_o(t,lu(n)):t.kind===I.VISIBILITY_SET?Pp(t,lu(n)):t.kind===I.FILTER_SET?Wp(t,{adapter:n.adapter,hoursPerDay:n.sector.hoursPerDay}):t.kind===I.SORT_SET?zp(t,{adapter:n.adapter}):t.kind===I.VIEW_ATTRIBUTES_SET?Zp(t,{adapter:n.adapter,hoursPerDay:n.sector.hoursPerDay}):t.kind===I.GROUP_SET?Qp(t,{adapter:n.adapter,hoursPerDay:n.sector.hoursPerDay}):t.kind===I.WBS_DEPTH_SET?ty(t,{adapter:n.adapter,hoursPerDay:n.sector.hoursPerDay}):t.kind===I.SIR_SYNC?cg(t,n):t.kind===I.ACTIVITY_LOOKAHEAD_SYNC?Ag(t,e,n):t.kind===I.ACTIVITY_LOOKAHEAD_CONVERT?Dg(t,e,n):t.kind===I.SCHEDULE_AUTO_SCHEDULE?Im(t,e,n):t.kind===I.INLINE_EDIT&&(t.column===R.CUSTOM_PREDECESSORS||t.column===R.CUSTOM_SUCESSORS)?wm(t,e,n):t.kind!==I.INLINE_EDIT?ey(t,`[ScheduleCore] dispatch kind "${t.kind}" not supported yet`):Om(t,e,n)}function lu(t){return{adapter:t.adapter}}function Ja(t={}){let e=t.seed??0,n=r=>{r>e&&(e=r)};if(t.knownIds)for(let r of t.knownIds){let i=typeof r=="number"?r:Number(r);Number.isFinite(i)&&n(i)}return{fork(){return Ja({seed:e})},next(){return e+=1,String(e)},bump(r){let i=typeof r=="number"?r:Number(r);Number.isFinite(i)&&n(i)},snapshot(){return e},restore(r){e=r}}}function VA(t){return!!t&&typeof t=="string"&&t.trim().length>0}function vl(t){if(!t||typeof t!="string"||t.trim().length===0)return"";let e=t.match(/^(.*?)(\d+)$/);return e?e[1]??"":t}function Cl(t){if(!t||typeof t!="string"||t.trim().length===0)return"";let e=t.match(/(\d+)$/);return e?e[1]??"":""}function WA(t){if(!t||typeof t!="object")return"";let e=t.customId;return typeof e=="string"?e:""}function KA(t,e){return!e&&VA(t)}function YA(t,e){return e&&VA(t)}function Xa(t){return typeof t=="string"&&t.length>0&&/^\d+$/.test(t)}function Dl(t){if(!Xa(t))return 0n;try{return BigInt(t)}catch{return 0n}}function BN(t,e){if(typeof t!="bigint")return"";let n=t.toString();if(!Xa(e))return n;let r=e.length;return n.padStart(r,"0")}function Le(t,e){let n=Dl(t),r=Dl(e),i=n+r;return BN(i,t)}function Tl(t,e){let n=Dl(t),r=Dl(e);return n<r?-1:n>r?1:0}function _l(t,e){return Tl(t,e)<=0?t:e}function El(t,e){return Tl(t,e)>=0?t:e}function GA(t){if(!t||t.length===0)throw new Error("minSuffixFromArray requires non-empty array");return t.reduce((e,n)=>_l(e,n))}function qA(t){if(!t||t.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return t.reduce((e,n)=>El(e,n))}var mn={PARENT_CONVERSION:"parentConversion",PASTE_REFERENCE:"pasteReference",NO_CONTEXT:"noContext"};function $A(t){return{prefix:t,baseSuffix:null}}function zA(t,e){let n=Cl(t);return{prefix:vl(t),baseSuffix:Le(n,e)}}function JA(t){return{prefix:t,baseSuffix:null}}function XA(t,e){return KA(t,e)?mn.PARENT_CONVERSION:YA(t,e)?mn.PASTE_REFERENCE:mn.NO_CONTEXT}function ZA(t){return{...t,usedSuffixes:new Set(t.usedSuffixes)}}var Wi=class t{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 e=this._journalPrefixBefore,n=this._journalIds;if(!(e===null||n===null)){for(let[r,i]of e)i===null?this.prefixMap.delete(r):this.prefixMap.set(r,i);for(let r of[...n].reverse())r.hadId?this.processedIds.add(r.customId):this.processedIds.delete(r.customId);this._journalPrefixBefore=null,this._journalIds=null}}_noteCustomIdBefore(e){if(this._journalPrefixBefore===null||this._journalIds===null)return;let{prefix:n}=this.analyzeCustomId(e);if(!this._journalPrefixBefore.has(n)){let r=this.prefixMap.get(n);this._journalPrefixBefore.set(n,r?ZA(r):null)}this._journalIds.push({customId:e,hadId:this.processedIds.has(e)})}_ensureFreshBounds(e){let n=this.prefixMap.get(e);if(!n?.boundsDirty)return;n.boundsDirty=!1;let r=Array.from(n.usedSuffixes);n.min=GA(r),n.max=qA(r),n.quantity=r.length,this._recalculateNext(e)}defaultPrefix;suffixIncrement;constructor(e={}){this.defaultPrefix=e.defaultPrefix??"A",this.suffixIncrement=e.suffixIncrement??"10"}captureRestorePoint(){let e=this.fork();return()=>{this.prefixMap.clear();for(let[n,r]of e.prefixMap)this.prefixMap.set(n,r);this.processedIds.clear();for(let n of e.processedIds)this.processedIds.add(n)}}fork(){let e=new t({defaultPrefix:this.defaultPrefix,suffixIncrement:this.suffixIncrement});for(let[n,r]of this.prefixMap)e.prefixMap.set(n,ZA(r));for(let n of this.processedIds)e.processedIds.add(n);return e}snapshot(){let e=this.fork();return{defaultPrefix:this.defaultPrefix,suffixIncrement:this.suffixIncrement,prefixes:e.prefixMap,processedIds:e.processedIds}}static fromSnapshot(e){let n=new t({defaultPrefix:e.defaultPrefix,suffixIncrement:e.suffixIncrement});for(let[r,i]of e.prefixes)n.prefixMap.set(r,i);for(let r of e.processedIds)n.processedIds.add(r);return n}extractPrefix(e){return vl(e)}extractSuffix(e){return Cl(e)}analyzeCustomId(e){return{prefix:this.extractPrefix(e),suffix:this.extractSuffix(e)}}_updatePrefixStats(e,n){if(this._ensureFreshBounds(e),!this.prefixMap.has(e)){this.prefixMap.set(e,{min:n,max:n,next:n,quantity:1,usedSuffixes:new Set([n])}),this._recalculateNext(e);return}let r=this.prefixMap.get(e);r.usedSuffixes.has(n)||(r.usedSuffixes.add(n),r.min=_l(n,r.min),r.max=El(n,r.max),r.quantity+=1,this._recalculateNext(e))}_recalculateNext(e){let n=this.prefixMap.get(e);if(!n)return;let r=this.getNextAvailableSuffix(e);n.next=r??this.suffixIncrement}getPrefixStats(e){this._ensureFreshBounds(e);let n=this.prefixMap.get(e);return n?{min:n.min,max:n.max,next:n.next,quantity:n.quantity}:null}getNextSuffix(e){this._ensureFreshBounds(e);let n=this.prefixMap.get(e);return n?n.next:this.suffixIncrement}getAllPrefixes(){return Array.from(this.prefixMap.keys())}registerCustomId(e){if(!e||typeof e!="string")return{prefix:"",suffix:""};let{prefix:n,suffix:r}=this.analyzeCustomId(e);if(!n&&!r)return{prefix:n,suffix:r};if(this._noteCustomIdBefore(e),this._ensureFreshBounds(n),this.prefixMap.has(n)){let i=this.prefixMap.get(n);i.usedSuffixes.has(r)||(i.usedSuffixes.add(r),i.min=_l(r,i.min),i.max=El(r,i.max),i.quantity+=1,this._recalculateNext(n))}else this.prefixMap.set(n,{min:r,max:r,next:Le(r,this.suffixIncrement),quantity:1,usedSuffixes:new Set([r])});return this.processedIds.add(e),{prefix:n,suffix:r}}releaseCustomId(e=null){if(!e||typeof e!="string")return{prefix:"",suffix:""};let{prefix:n,suffix:r}=this.analyzeCustomId(e);if(!this.prefixMap.has(n))return{prefix:n,suffix:r};this._noteCustomIdBefore(e);let i=this.prefixMap.get(n);return i.usedSuffixes.has(r)&&(i.usedSuffixes.delete(r),i.quantity-=1,i.usedSuffixes.size===0?this.prefixMap.delete(n):i.boundsDirty=!0),this.processedIds.delete(e),{prefix:n,suffix:r}}trackCustomIdChange(e,n){let r=this.releaseCustomId(e),i=this.registerCustomId(n);return{oldPrefix:r.prefix,oldSuffix:r.suffix,newPrefix:i.prefix,newSuffix:i.suffix}}_exceedsMaxLength(e){return e.length>20}_shouldSearchForGaps(e){if(this._ensureFreshBounds(e),!this.prefixMap.has(e))return!1;let n=this.prefixMap.get(e);return`${e}${Le(n.max,this.suffixIncrement)}`.length>20}_suffixForUnknownPrefix(e,n){let r=n&&Xa(n)?n:this.suffixIncrement;return`${e}${r}`.length>20?null:r}_findFirstAvailableGap(e){if(this._ensureFreshBounds(e),!this.prefixMap.has(e))return null;let n=this.prefixMap.get(e),r=this.suffixIncrement;for(;Tl(r,n.max)<0;){if(`${e}${r}`.length>20)return null;if(!n.usedSuffixes.has(r))return r;r=Le(r,this.suffixIncrement)}return null}_generateDefaultCustomId(){let e=this.getNextAvailableSuffix(this.defaultPrefix);if(e===null){if(this._shouldSearchForGaps(this.defaultPrefix)){let n=this._findFirstAvailableGap(this.defaultPrefix);if(n!==null)return`${this.defaultPrefix}${n}`}return`${this.defaultPrefix}${this.suffixIncrement}`}return`${this.defaultPrefix}${e}`}getNextAvailableSuffix(e,n=null){if(this._ensureFreshBounds(e),!this.prefixMap.has(e))return this._suffixForUnknownPrefix(e,n);let r=this.prefixMap.get(e),i=this.suffixIncrement;if(!n||!Xa(n)){let s=Le(r.max,i);return`${e}${s}`.length>20?null:s}let a=n;for(let s=0;s<100;s++){if(`${e}${a}`.length>20)return null;if(!r.usedSuffixes.has(a))return a;a=Le(a,i)}let o=Le(r.max,i);return`${e}${o}`.length>20?null:o}generateNextCustomId(e){let n=this.getNextAvailableSuffix(e);if(n===null)return this._generateDefaultCustomId();if(this.prefixMap.has(e)){let i=this.prefixMap.get(e),a=0;for(;i.usedSuffixes.has(n)&&a<1e4;){let o=this.getNextAvailableSuffix(e,Le(n,this.suffixIncrement));if(o===null)return this._generateDefaultCustomId();n=o,a++}}let r=`${e}${n}`;return this._exceedsMaxLength(r)&&(r=this._generateDefaultCustomId()),r}populateFromActivities(e){if(!Array.isArray(e))return this;let n=[...new Set(e.filter(r=>r&&typeof r.customId=="string"&&r.customId).map(r=>r.customId))];for(let r of n){if(this.processedIds.has(r))continue;let{prefix:i,suffix:a}=this.analyzeCustomId(r);(i||a)&&(this._updatePrefixStats(i,a),this.processedIds.add(r))}return this}getDefaults(){return{prefix:this.defaultPrefix,increment:this.suffixIncrement}}generateCustomIdForNewChild(e){let{activity:n,useActivityCustomIdAsReference:r=!1}=e,i=WA(n),a=XA(i,r),{prefix:o,baseSuffix:s}=this._applyGenerationStrategy(a,i),l=null;if(a===mn.PARENT_CONVERSION&&this.prefixMap.has(o)){this._ensureFreshBounds(o);let p=this.prefixMap.get(o).max;l=Le(p,this.suffixIncrement)}a===mn.PARENT_CONVERSION&&this.releaseCustomId(i);let c=a===mn.PARENT_CONVERSION&&l?l:s,d=this.getNextAvailableSuffix(o,c);if(d===null){let p=this._generateDefaultCustomId();return this.registerCustomId(p),p}let u=`${o}${d}`;return this._exceedsMaxLength(u)&&(u=this._generateDefaultCustomId()),this.registerCustomId(u),u}_applyGenerationStrategy(e,n){switch(e){case mn.PARENT_CONVERSION:return $A(this.defaultPrefix);case mn.PASTE_REFERENCE:return zA(n,this.suffixIncrement);default:return JA(this.defaultPrefix)}}generateCustomIdForRestoredChild(e=null){if(e){let r=e.trim();if(r.length>0){let i=this.extractPrefix(r),a=this.extractSuffix(r),o=Le(a,this.suffixIncrement),s=this.getNextAvailableSuffix(i,o);if(s===null){let c=this._generateDefaultCustomId();return this.registerCustomId(c),c}let l=`${i}${s}`;return this._exceedsMaxLength(l)&&(l=this._generateDefaultCustomId()),this.registerCustomId(l),l}}let n=this.generateNextCustomId(this.defaultPrefix);return this.registerCustomId(n),n}clear(){this.prefixMap.clear(),this.processedIds.clear()}getTotalPrefixes(){return this.prefixMap.size}hasPrefix(e){return this.prefixMap.has(e)}isCustomIdInUse(e,n=null){if(!e||typeof e!="string"||!e.trim())return!1;let r=e.trim();return n&&r===n.trim()?!1:this.processedIds.has(r)}};function Za(t={}){let e=t.seed??0,n=r=>{r>e&&(e=r)};if(t.knownIds)for(let r of t.knownIds){let i=typeof r=="number"?r:Number(r);Number.isFinite(i)&&n(i)}return{fork(){return Za({seed:e})},next(){return e+=1,String(e)},bump(r){let i=typeof r=="number"?r:Number(r);Number.isFinite(i)&&n(i)},snapshot(){return e},restore(r){e=r}}}function Qa(t={}){let e=t.seed??0,n=r=>{Number.isFinite(r)&&r>0&&r<=9999999&&r>e&&(e=r)};if(t.knownIds)for(let r of t.knownIds){if(r==null)continue;let i=typeof r=="number"?r:Number(r);n(i)}return{fork(){return Qa({seed:e})},next(){return e+=1,String(e)},bump(r){if(r==null)return;let i=typeof r=="number"?r:Number(r);n(i)},snapshot(){return e},restore(r){e=r}}}var jN=new Set(["startDate","endDate","constraintDate"]);function QA(t,e){return jN.has(t)&&typeof e=="string"?new Date(e):e}var VN=/^\s*(\d{1,2}):(\d{2})\s*-\s*(\d{1,2}):(\d{2})\s*$/,tI="24:00",WN="0:00";function eI(t){let e=VN.exec(t);return e===null?null:{start:Number(e[1])*60+Number(e[2]),end:Number(e[3])*60+Number(e[4])}}function to(t){let e=Math.floor(t/60),n=String(t%60).padStart(2,"0");return`${e}:${n}`}function KN(t){let e=eI(t),n={windows:[t],overflow:[],isSplit:!1};return e===null||e.start<e.end&&e.end<=1440?n:e.end===0?{...n,windows:[`${to(e.start)}-${tI}`]}:e.end>1440?n:{windows:[`${to(e.start)}-${tI}`],overflow:[`${WN}-${to(e.end)}`],isSplit:!0}}function cu(t,e,n){let r=[],i=[];for(let a of t){if(typeof a!="string"){r.push(a);continue}let o=KN(a);r.push(...o.windows),i.push(...o.overflow),o.isSplit&&n("Calendar shift window crosses midnight and was split",{window:a,scope:e})}return{windows:r,overflow:i}}function nI(t,e){return Array.isArray(t)?t:t===!0?e:[]}function rI(t,e){let n=[],r=[];for(let a of[...t,...e]){let o=typeof a=="string"?eI(a):null;o===null?r.push(a):n.push(o)}n.sort((a,o)=>a.start-o.start);let i=[];for(let a of n){let o=i[i.length-1];o!==void 0&&a.start<=o.end?o.end=Math.max(o.end,a.end):i.push({...a})}return[...i.map(a=>`${to(a.start)}-${to(a.end)}`),...r]}function YN(t,e,n){let r=t.map((i,a)=>Array.isArray(i)?cu(i,`weekday ${a}`,n):null);return t.map((i,a)=>{let o=r[a]??null,s=r[(a+7-1)%7]?.overflow??[];return s.length>0?rI(o?.windows??nI(i,e),s):o===null?i:o.windows})}function GN(t){let e=Number(t);return Number.isInteger(e)&&e%864e5===0?String(e+864e5):null}function qN(t,e,n,r){let i={},a=new Map;for(let[o,s]of Object.entries(t)){if(!Array.isArray(s)){i[o]=s;continue}let l=cu(s,`date ${o}`,r);i[o]=l.windows;let c=GN(o);l.overflow.length===0||c===null||c in t||a.set(c,[...a.get(c)??[],...l.overflow])}for(let[o,s]of a){let l=new Date(Number(o)).getUTCDay();i[o]=rI(nI(e[l],n),s)}return i}function iI(t,e){let n=t.hours===void 0?void 0:cu(t.hours,"hours",e).windows,r=n??[],i=t.days&&YN(t.days,r,e),a=t.dates&&qN(t.dates,i??[],r,e);return{hours:n,days:i,dates:a}}function $N(t){return Array.isArray?Array.isArray(t):t&&t.length!==void 0&&t.pop&&t.push}function Ur(t){return t&&typeof t=="object"?!!(t.getFullYear&&t.getMonth&&t.getDate):!1}function Hr(t){return Ur(t)&&!isNaN(t.getTime())}var zN={}.constructor.toString();function JN(t){var e=t.constructor.toString();return e!==zN}function XN(t){return t.$$typeof&&t.$$typeof.toString().includes("react.")}function je(t){var e,n;if(t&&typeof t=="object")switch(!0){case Ur(t):n=new Date(t);break;case $N(t):for(n=new Array(t.length),e=0;e<t.length;e++)n[e]=je(t[e]);break;default:if(JN(t))n=Object.create(t);else{if(XN(t))return n=t,n;n={}}for(e in t)Object.prototype.hasOwnProperty.apply(t,[e])&&(n[e]=je(t[e]));break}return n||t}function Ki(t,e,n){for(var r in e)(t[r]===void 0||n)&&(t[r]=e[r]);return t}function aI(t){return typeof t<"u"}var Rl;function du(){return Rl||(Rl=new Date().valueOf()),Rl++,Rl}function ve(t,e){return t.bind?t.bind(e):function(){return t.apply(e,arguments)}}var QN=(t,e,n)=>{t=t.replace(/%[a-zA-Z]/g,i=>{switch(i){case"%d":return`"+to_fixed(date.get${e?"UTC":""}Date())+"`;case"%m":return`"+to_fixed((date.get${e?"UTC":""}Month()+1))+"`;case"%j":return`"+date.get${e?"UTC":""}Date()+"`;case"%n":return`"+(date.get${e?"UTC":""}Month()+1)+"`;case"%y":return`"+to_fixed(date.get${e?"UTC":""}FullYear()%100)+"`;case"%Y":return`"+date.get${e?"UTC":""}FullYear()+"`;case"%D":return`"+locale.date.day_short[date.get${e?"UTC":""}Day()]+"`;case"%l":return`"+locale.date.day_full[date.get${e?"UTC":""}Day()]+"`;case"%M":return`"+locale.date.month_short[date.get${e?"UTC":""}Month()]+"`;case"%F":return`"+locale.date.month_full[date.get${e?"UTC":""}Month()]+"`;case"%h":return`"+to_fixed((date.get${e?"UTC":""}Hours()+11)%12+1)+"`;case"%g":return`"+((date.get${e?"UTC":""}Hours()+11)%12+1)+"`;case"%G":return`"+date.get${e?"UTC":""}Hours()+"`;case"%H":return`"+to_fixed(date.get${e?"UTC":""}Hours())+"`;case"%i":return`"+to_fixed(date.get${e?"UTC":""}Minutes())+"`;case"%a":return`"+(date.get${e?"UTC":""}Hours()>11?"pm":"am")+"`;case"%A":return`"+(date.get${e?"UTC":""}Hours()>11?"PM":"AM")+"`;case"%s":return`"+to_fixed(date.get${e?"UTC":""}Seconds())+"`;case"%W":return'"+to_fixed(getISOWeek(date))+"';case"%w":return'"+to_fixed(getWeek(date))+"';default:return i}});let r=new Function("date","to_fixed","locale","getISOWeek","getWeek",`return "${t}";`);return i=>r(i,n.date.to_fixed,n.locale,n.date.getISOWeek,n.date.getWeek)},tF=(t,e,n)=>{let r="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);",i=t.match(/%[a-zA-Z]/g);for(let s=0;s<i.length;s++)switch(i[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 a="set[0],set[1],set[2],set[3],set[4],set[5]";e&&(a=` Date.UTC(${a})`);let o=new Function("date","locale",`var set=[0,0,1,0,0,0]; ${r} return new Date(${a});`);return s=>o(s,n.locale)},oI={date_to_str:QN,str_to_date:tF},eF=(t,e,n)=>r=>t.replace(/%[a-zA-Z]/g,i=>{switch(i){case"%d":return e?n.date.to_fixed(r.getUTCDate()):n.date.to_fixed(r.getDate());case"%m":return e?n.date.to_fixed(r.getUTCMonth()+1):n.date.to_fixed(r.getMonth()+1);case"%j":return e?r.getUTCDate():r.getDate();case"%n":return e?r.getUTCMonth()+1:r.getMonth()+1;case"%y":return e?n.date.to_fixed(r.getUTCFullYear()%100):n.date.to_fixed(r.getFullYear()%100);case"%Y":return e?r.getUTCFullYear():r.getFullYear();case"%D":return e?n.locale.date.day_short[r.getUTCDay()]:n.locale.date.day_short[r.getDay()];case"%l":return e?n.locale.date.day_full[r.getUTCDay()]:n.locale.date.day_full[r.getDay()];case"%M":return e?n.locale.date.month_short[r.getUTCMonth()]:n.locale.date.month_short[r.getMonth()];case"%F":return e?n.locale.date.month_full[r.getUTCMonth()]:n.locale.date.month_full[r.getMonth()];case"%h":return e?n.date.to_fixed((r.getUTCHours()+11)%12+1):n.date.to_fixed((r.getHours()+11)%12+1);case"%g":return e?(r.getUTCHours()+11)%12+1:(r.getHours()+11)%12+1;case"%G":return e?r.getUTCHours():r.getHours();case"%H":return e?n.date.to_fixed(r.getUTCHours()):n.date.to_fixed(r.getHours());case"%i":return e?n.date.to_fixed(r.getUTCMinutes()):n.date.to_fixed(r.getMinutes());case"%a":return e?r.getUTCHours()>11?"pm":"am":r.getHours()>11?"pm":"am";case"%A":return e?r.getUTCHours()>11?"PM":"AM":r.getHours()>11?"PM":"AM";case"%s":return e?n.date.to_fixed(r.getUTCSeconds()):n.date.to_fixed(r.getSeconds());case"%W":return e?n.date.to_fixed(n.date.getUTCISOWeek(r)):n.date.to_fixed(n.date.getISOWeek(r));case"%w":return n.date.to_fixed(n.date.getWeek(r));default:return i}}),nF=(t,e,n)=>r=>{let i=[0,0,1,0,0,0],a=r.match(/[a-zA-Z]+|[0-9]+/g),o=t.match(/%[a-zA-Z]/g);for(let s=0;s<o.length;s++)switch(o[s]){case"%j":case"%d":i[2]=a[s]||1;break;case"%n":case"%m":i[1]=(a[s]||1)-1;break;case"%y":i[0]=a[s]*1+(a[s]>50?1900:2e3);break;case"%g":case"%G":case"%h":case"%H":i[3]=a[s]||0;break;case"%i":i[4]=a[s]||0;break;case"%Y":i[0]=a[s]||0;break;case"%a":case"%A":i[3]=i[3]%12+((a[s]||"").toLowerCase()==="am"?0:12);break;case"%s":i[5]=a[s]||0;break;case"%M":i[1]=n.locale.date.month_short_hash[a[s]]||0;break;case"%F":i[1]=n.locale.date.month_full_hash[a[s]]||0;break}return e?new Date(Date.UTC(i[0],i[1],i[2],i[3],i[4],i[5])):new Date(i[0],i[1],i[2],i[3],i[4],i[5])},sI={date_to_str:eF,str_to_date:nF};function lI(t){var e=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function n(s){var l=new Date(s);return isNaN(l.getTime())?null:l}var r=null;function i(){try{new Function("canUseCsp = false;")}catch{r=!0}}function a(){var s=!1;return t.config.csp==="auto"?(r===null&&i(),s=r):s=t.config.csp,s}var o={_isoDateDetected:!1,_isoDateOnly:!1,formatISODate:function(s){return s.toISOString()},formatISODateOnly:function(s){return s.getUTCFullYear()+"-"+t.date.to_fixed(s.getUTCMonth()+1)+"-"+t.date.to_fixed(s.getUTCDate())},init:function(){for(var s=t.locale,c=s.date.month_short,d=s.date.month_short_hash={},l=0;l<c.length;l++)d[c[l]]=l;for(var c=s.date.month_full,d=s.date.month_full_hash={},l=0;l<c.length;l++)d[c[l]]=l},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 l=s.getUTCDay();return t.config.start_on_monday&&(l===0?l=6:l--),this.date_part(this.add(s,-1*l,"day"))},month_start:function(s){return s.setUTCDate(1),this.date_part(s)},quarter_start:function(s){this.month_start(s);var l=s.getUTCMonth(),c;return l>=9?c=9:l>=6?c=6:l>=3?c=3:c=0,s.setUTCMonth(c),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,l,c){return s.setUTCDate(s.getUTCDate()+l),s},add:function(s,l,c){var d=new Date(s.valueOf());switch(c){case"day":d=this._add_days(d,l,s);break;case"week":d=this._add_days(d,l*7,s);break;case"month":d.setUTCMonth(d.getUTCMonth()+l);break;case"year":d.setUTCFullYear(d.getUTCFullYear()+l);break;case"hour":d.setTime(d.getTime()+l*60*60*1e3);break;case"minute":d.setTime(d.getTime()+l*60*1e3);break;default:return this["add_"+c](s,l,c)}return d},add_quarter:function(s,l){return this.add(s,l*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,l){var c=oI;return a()&&(c=sI),c.date_to_str(s,l,t)},str_to_date:function(s,l){var c=oI;return a()&&(c=sI),c.str_to_date(s,l,t)},getISOWeek:function(s){return t.date._getWeekNumber(s,!0)},_getWeekNumber:function(s,l){if(!s)return!1;var c=s.getUTCDay();l&&c===0&&(c=7);var d=new Date(s.valueOf());d.setUTCDate(s.getUTCDate()+(4-c));var u=d.getUTCFullYear(),p=Math.round((d.getTime()-Date.UTC(u,0,1))/864e5),y=1+Math.floor(p/7);return y},getWeek:function(s){return t.date._getWeekNumber(s,t.config.start_on_monday)},getUTCISOWeek:function(s){return t.date.getISOWeek(s)},parseDate:function(s,l){if(s&&!s.getFullYear){var c=!l||l==="parse_date"||l==="xml_date",d=c&&(t.defined(t.templates.xml_date)||t.templates.parse_date&&!t.templates.parse_date._ganttAuto);if(!d&&typeof s=="string"&&e.test(s)){var u=s.indexOf("T")!==-1,p=n(s);if(p)return o._isoDateDetected?u&&(o._isoDateOnly=!1):(o._isoDateDetected=!0,o._isoDateOnly=!u),p}typeof l!="function"&&(typeof l=="string"?l==="parse_date"||l==="xml_date"?l=t.defined(t.templates.xml_date)?t.templates.xml_date:t.templates.parse_date:l=t.defined(t.templates[l])?t.templates[l]:t.date.str_to_date(l,!0):l=t.defined(t.templates.xml_date)?t.templates.xml_date:t.templates.parse_date),s?s=l(s):s=null}return s}};return o}function uu(t,e,n,r,i){return this.date=t,this.unit=e,this.task=n,this.id=r,this.calendar=i,this}function pu(t,e,n,r,i,a){return this.date=t,this.dir=e,this.unit=n,this.task=r,this.id=i,this.calendar=a,this}function yu(t,e,n,r,i,a,o){return this.start_date=t,this.duration=e,this.unit=n,this.step=r,this.task=i,this.id=a,this.calendar=o,this}function rF(t,e,n,r){return this.start_date=t,this.end_date=e,this.task=n,this.calendar=r,this.unit=null,this.step=null,this}var cI=function(t){return{getWorkHoursArguments:function(){var e=arguments[0];if(Ur(e)?e={date:e}:e=Ki({},e),!Hr(e.date))throw t.assert(!1,"Invalid date argument for getWorkHours method"),new Error("Invalid date argument for getWorkHours method");return e},setWorkTimeArguments:function(){return arguments[0]},unsetWorkTimeArguments:function(){return arguments[0]},isWorkTimeArguments:function(){var e=arguments[0];if(e instanceof uu)return e;var n;if(e.date?n=new uu(e.date,e.unit,e.task,null,e.calendar):n=new uu(arguments[0],arguments[1],arguments[2],null,arguments[3]),n.unit=n.unit||t.config.duration_unit,!Hr(n.date))throw t.assert(!1,"Invalid date argument for isWorkTime method"),new Error("Invalid date argument for isWorkTime method");return n},getClosestWorkTimeArguments:function(e){var n=arguments[0];if(n instanceof pu)return n;var r;if(Ur(n)?r=new pu(n):r=new pu(n.date,n.dir,n.unit,n.task,null,n.calendar),n.id&&(r.task=n),r.dir=n.dir||"any",r.unit=n.unit||t.config.duration_unit,!Hr(r.date))throw t.assert(!1,"Invalid date argument for getClosestWorkTime method"),new Error("Invalid date argument for getClosestWorkTime method");return r},_getStartEndConfig:function(e){var n=rF,r;if(e instanceof n)return e;if(Ur(e)?r=new n(arguments[0],arguments[1],arguments[2],arguments[3]):(r=new n(e.start_date,e.end_date,e.task),e.id!==null&&e.id!==void 0&&(r.task=e)),r.unit=r.unit||t.config.duration_unit,r.step=r.step||t.config.duration_step,r.start_date=r.start_date||r.start||r.date,!Hr(r.start_date))throw t.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!Hr(r.end_date))throw t.assert(!1,"Invalid end_date argument for getDuration method"),new Error("Invalid end_date argument for getDuration method");return r},getDurationArguments:function(e,n,r,i){return this._getStartEndConfig.apply(this,arguments)},hasDurationArguments:function(e,n,r,i){return this._getStartEndConfig.apply(this,arguments)},calculateEndDateArguments:function(e,n,r,i){var a=arguments[0];if(a instanceof yu)return a;var o;if(Ur(a)?o=new yu(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):o=new yu(a.start_date,a.duration,a.unit,a.step,a.task,null,a.calendar),a.id!==null&&a.id!==void 0&&(o.task=a,o.unit=null,o.step=null),o.unit=o.unit||t.config.duration_unit,o.step=o.step||t.config.duration_step,!Hr(o.start_date))throw t.assert(!1,"Invalid start_date argument for calculateEndDate method"),new Error("Invalid start_date argument for calculateEndDate method");return o}}};function dI(){}dI.prototype={_getIntervals:function(t){for(var e=[],n=0;n<t.length;n+=2)e.push({start:t[n],end:t[n+1]});return e},_toHoursArray:function(t){var e=[];function n(a){var o=String(a);return o.length<2&&(o="0"+o),o}function r(a){var o=Math.floor(a/3600),s=a-o*60*60,l=Math.floor(s/60);return o+":"+n(l)}for(var i=0;i<t.length;i++)e.push(r(t[i].start)+"-"+r(t[i].end));return e},_intersectHourRanges:function(t,e){var i=[],n=t.length>e.length?t:e,r=t===n?e:t;n=n.slice(),r=r.slice();for(var i=[],a=0;a<n.length;a++)for(var o=n[a],s=0;s<r.length;s++){var l=r[s];l.start<o.end&&l.end>o.start&&(i.push({start:Math.max(o.start,l.start),end:Math.min(o.end,l.end)}),o.end>l.end&&(r.splice(s,1),s--,a--))}return i},_mergeAdjacentIntervals:function(t){var e=t.slice();e.sort(function(a,o){return a.start-o.start});for(var n=e[0],r=1;r<e.length;r++){var i=e[r];i.start<=n.end?(i.end>n.end&&(n.end=i.end),e.splice(r,1),r--):n=i}return e},_mergeHoursConfig:function(t,e){return this._mergeAdjacentIntervals(this._intersectHourRanges(t,e))},merge:function(t,e){let n=je(t.getConfig()),r=je(e.getConfig()),i=n.parsed,a=r.parsed;i.customWeeks=n.customWeeks,a.customWeeks=r.customWeeks;var o={hours:this._toHoursArray(this._mergeHoursConfig(i.hours,a.hours)),dates:{},customWeeks:{}};let s=(c,d)=>{for(let u in c.dates){let p=c.dates[u];+u>1e3&&(o.dates[u]=!1);for(let y in d.dates){let f=d.dates[y];if(y==u&&(o.dates[u]=!!(p&&f)),Array.isArray(p)){let m=Array.isArray(f)?f:d.hours;o.dates[u]=this._toHoursArray(this._mergeHoursConfig(p,m))}}}};if(s(i,a),s(a,i),i.customWeeks)for(var l in i.customWeeks)o.customWeeks[l]=i.customWeeks[l];if(a.customWeeks)for(var l in a.customWeeks)o.customWeeks[l]?o.customWeeks[l+"_second"]=a.customWeeks[l]:o.customWeeks[l]=a.customWeeks[l];return o}};var fu=class{constructor(){this.clear()}getItem(e,n,r){if(this._cache.has(e)){let a=this._cache.get(e)[r.getUTCFullYear()];if(a&&a.has(n))return a.get(n)}return-1}setItem(e,n,r,i){if(!e||!n)return;let a=this._cache,o=i.getUTCFullYear(),s;a.has(e)?s=a.get(e):(s=[],a.set(e,s));let l=s[o];l||(l=s[o]=new Map),l.set(n,r)}clear(){this._cache=new Map}},hu=class{constructor(){this.clear()}getItem(e,n,r){let i=this._cache;if(i&&i[e]){let a=i[e];if(a===void 0)return-1;let o=a[r.getUTCFullYear()];if(o&&o[n]!==void 0)return o[n]}return-1}setItem(e,n,r,i){if(!e||!n)return;let a=this._cache;if(!a)return;a[e]||(a[e]=[]);let o=a[e],s=i.getUTCFullYear(),l=o[s];l||(l=o[s]={}),l[n]=r}clear(){this._cache={}}},mu=class{constructor(e){this.getMinutesPerWeek=n=>{let r=n.valueOf();if(this._weekCache.has(r))return this._weekCache.get(r);let i=this._calendar,a=this._calendar.$gantt,o=0,s=a.date.week_start(new Date(n));for(let l=0;l<7;l++)o+=i.getHoursPerDay(s)*60,s=a.date.add(s,1,"day");return this._weekCache.set(r,o),o},this.getMinutesPerMonth=n=>{let r=n.valueOf();if(this._monthCache.has(r))return this._monthCache.get(r);let i=this._calendar,a=this._calendar.$gantt,o=0,s=a.date.week_start(new Date(n)),l=a.date.add(s,1,"month").valueOf();for(;s.valueOf()<l;)o+=i.getHoursPerDay(s)*60,s=a.date.add(s,1,"day");return this._monthCache.set(r,o),o},this.clear=()=>{this._weekCache=new Map,this._monthCache=new Map},this.clear(),this._calendar=e}};function iF(){return typeof Map<"u"?new fu:new hu}var gu=class{constructor(){this.clear()}_getCacheObject(e,n,r){let i=this._cache;i[n]||(i[n]=[]);let a=i[n];a||(a=i[n]={});let o=a[r];o||(o=a[r]={});let s=e.getUTCFullYear(),l=o[s];return l||(l=o[s]={durations:{},endDates:{}}),l}_endDateCacheKey(e,n){return String(e)+"-"+String(n)}_durationCacheKey(e,n){return String(e)+"-"+String(n)}getEndDate(e,n,r,i,a){let o=this._getCacheObject(e,r,i),s=e.valueOf(),l=this._endDateCacheKey(s,n),c;if(o.endDates[l]===void 0){let d=a(),u=d.valueOf();o.endDates[l]=u,o.durations[this._durationCacheKey(s,u)]=n,c=d}else c=new Date(o.endDates[l]);return c}getDuration(e,n,r,i,a){let o=this._getCacheObject(e,r,i),s=e.valueOf(),l=n.valueOf(),c=this._durationCacheKey(s,l),d;if(o.durations[c]===void 0){let u=a();o.durations[c]=u.valueOf(),d=u}else d=o.durations[c];return d}clear(){this._cache={}}};function Au(t,e){this.argumentsHelper=e,this.$gantt=t,this._workingUnitsCache=iF(),this._largeUnitsCache=new mu(this),this._dateDurationCache=new gu,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}Au.prototype={units:["year","month","week","day","hour","minute"],_clearCaches:function(){this._workingUnitsCache.clear(),this._largeUnitsCache.clear(),this._dateDurationCache.clear()},_getUnitOrder:function(t){for(var e=0,n=this.units.length;e<n;e++)if(this.units[e]==t)return e},_resetTimestampCache:function(){this._cached_timestamps={},this._cached_timestamps_count=0},_timestamp:function(t){this._cached_timestamps_count>1e6&&this._resetTimestampCache();var e=null;if(t.day||t.day===0)e=t.day;else if(t.date){var n=String(t.date.valueOf());this._cached_timestamps[n]?e=this._cached_timestamps[n]:(e=Date.UTC(t.date.getUTCFullYear(),t.date.getUTCMonth(),t.date.getUTCDate()),this._cached_timestamps[n]=e,this._cached_timestamps_count++)}return e},_checkIfWorkingUnit:function(t,e){if(!this["_is_work_"+e]){let n=this.$gantt.date[`${e}_start`](new Date(t)),r=this.$gantt.date.add(n,1,e);return this.hasDuration(n,r)}return this["_is_work_"+e](t)},_is_work_day:function(t){var e=this._getWorkHours(t);return Array.isArray(e)?e.length>0:!1},_is_work_hour:function(t){for(var e=this._getWorkHours(t),n=t.getUTCHours(),r=0;r<e.length;r++)if(n>=e[r].startHour&&n<e[r].endHour)return!0;return!1},_getTimeOfDayStamp:function(t,e){var n=t.getUTCHours();return!t.getUTCHours()&&!t.getUTCMinutes()&&e&&(n=24),n*60*60+t.getUTCMinutes()*60},_is_work_minute:function(t){for(var e=this._getWorkHours(t),n=this._getTimeOfDayStamp(t),r=0;r<e.length;r++)if(n>=e[r].start&&n<e[r].end)return!0;return!1},_nextDate:function(t,e,n){return this.$gantt.date.add(t,n,e)},_getWorkUnitsBetweenGeneric:function(t,e,n,r){var i=this.$gantt.date,a=new Date(t),o=new Date(e);r=r||1;var s=0,l=null,c,d,u=!1;c=i[n+"_start"](new Date(a)),c.valueOf()!=a.valueOf()&&(u=!0);var p=!1;d=i[n+"_start"](new Date(e)),d.valueOf()!=e.valueOf()&&(p=!0);for(var y=!1;a.valueOf()<o.valueOf();){if(l=this._nextDate(a,n,r),y=l.valueOf()>o.valueOf(),this._isWorkTime(a,n))(u||p&&y)&&(c=i[n+"_start"](new Date(a)),d=i.add(c,r,n)),u?(u=!1,l=this._nextDate(c,n,r),s+=(d.valueOf()-a.valueOf())/(d.valueOf()-c.valueOf())):p&&y?(p=!1,s+=(o.valueOf()-a.valueOf())/(d.valueOf()-c.valueOf())):s++;else{var f=this._getUnitOrder(n),m=this.units[f-1];m&&!this._isWorkTime(a,m)&&(l=this._getClosestWorkTimeFuture(a,m))}a=l}return s},_getMinutesPerHour:function(t){var e=this._getTimeOfDayStamp(t),n=this._getTimeOfDayStamp(this._nextDate(t,"hour",1));n===0&&(n=1440*60);for(var r=this._getWorkHours(t),i=0;i<r.length;i++){var a=r[i];if(e>=a.start&&n<=a.end)return 60;if(e<a.end&&n>a.start){var o=Math.min(n,a.end)-Math.max(e,a.start);return o/60}}return 0},_getMinutesPerDay:function(t){var e=this._getWorkHours(t),n=0;return e.forEach(function(r){n+=r.durationMinutes}),n},getHoursPerDay:function(t){var e=this._getWorkHours(t),n=0;return e.forEach(function(r){n+=r.durationHours}),n},_getWorkUnitsForRange:function(t,e,n,r){var i=0,a=new Date(t),o=new Date(e),s;for(n=="minute"?s=ve(this._getMinutesPerDay,this):s=ve(this.getHoursPerDay,this);a.valueOf()<o.valueOf();){if(o-a>1e3*60*60*24*32&&a.getUTCDate()===0){var l=this._largeUnitsCache.getMinutesPerMonth(a);n=="hour"&&(l=l/60),i+=l,a=this.$gantt.date.add(a,1,"month");continue}else if(o-a>1e3*60*60*24*16){var c=this.$gantt.date.week_start(new Date(a));if(a.valueOf()===c.valueOf()){var l=this._largeUnitsCache.getMinutesPerWeek(a);n=="hour"&&(l=l/60),i+=l,a=this.$gantt.date.add(a,7,"day");continue}}i+=s(a),a=this._nextDate(a,"day",1)}return i/r},_getMinutesBetweenSingleDay:function(t,e){for(var n=this._getIntervalTimestamp(t,e),r=this._getWorkHours(t),i=0,a=0;a<r.length;a++){var o=r[a];if(n.end>=o.start&&n.start<=o.end){var s=Math.max(o.start,n.start),l=Math.min(o.end,n.end);i+=(l-s)/60,n.start=l}}return Math.floor(i)},_getMinutesBetween:function(t,e,n,r){var i=new Date(t),a=new Date(e);r=r||1;var o=new Date(i),s=this.$gantt.date.add(this.$gantt.date.day_start(new Date(i)),1,"day");if(a.valueOf()<=s.valueOf())return this._getMinutesBetweenSingleDay(t,e);var l=this.$gantt.date.day_start(new Date(a)),c=a,d=this._getMinutesBetweenSingleDay(o,s),u=this._getMinutesBetweenSingleDay(l,c),p=this._getWorkUnitsForRange(s,l,n,r),y=d+p+u;return y},_getHoursBetween:function(t,e,n,r){var i=new Date(t),a=new Date(e);r=r||1;var o=new Date(i),s=this.$gantt.date.add(this.$gantt.date.day_start(new Date(i)),1,"day");if(a.valueOf()<=s.valueOf())return Math.round(this._getMinutesBetweenSingleDay(t,e)/60);var l=this.$gantt.date.day_start(new Date(a)),c=a,d=this._getMinutesBetweenSingleDay(o,s,n,r)/60,u=this._getMinutesBetweenSingleDay(l,c,n,r)/60,p=this._getWorkUnitsForRange(s,l,n,r),y=d+p+u;return Math.round(y)},getConfig:function(){return this._worktime},_setConfig:function(t){this._worktime=t,this._parseSettings(),this._clearCaches()},_parseSettings:function(){var t=this.getConfig();t.parsed={dates:{},hours:null,haveCustomWeeks:!1,customWeeks:{},customWeeksRangeStart:null,customWeeksRangeEnd:null,customWeeksBoundaries:[]},t.parsed.hours=this._parseHours(t.hours);for(var e in t.dates)t.parsed.dates[e]=this._parseHours(t.dates[e]);if(t.customWeeks){var n=null,r=null;for(var e in t.customWeeks){var i=t.customWeeks[e];if(i.from&&i.to){var a=i.from,o=i.to;(!n||n>a.valueOf())&&(n=a.valueOf()),(!r||r<o.valueOf())&&(r=o.valueOf()),t.parsed.customWeeksBoundaries.push({from:a.valueOf(),fromReadable:new Date(a),to:o.valueOf(),toReadable:new Date(o),name:e}),t.parsed.haveCustomWeeks=!0;var s=t.parsed.customWeeks[e]={from:i.from,to:i.to,hours:this._parseHours(i.hours),dates:{}};if(i.days&&!i.dates){i.dates=i.dates||{};for(var e=0;e<i.days.length;e++)i.dates[e]=i.days[e],i.days[e]instanceof Array||(i.dates[e]=!!i.days[e]);delete i.days}for(var l in i.dates)s.dates[l]=this._parseHours(i.dates[l])}}t.parsed.customWeeksRangeStart=n,t.parsed.customWeeksRangeEnd=r}},_tryChangeCalendarSettings:function(t){var e=JSON.stringify(this.getConfig());return t(),this.hasWorkTime()?!0:(this._setConfig(JSON.parse(e)),this._clearCaches(),!1)},_arraysEqual:function(t,e){if(t===e)return!0;if(!t||!e||t.length!=e.length)return!1;for(var n=0;n<t.length;++n)if(t[n]!==e[n])return!1;return!0},_compareSettings:function(t,e){if(!this._arraysEqual(t.hours,e.hours))return!1;var n=Object.keys(t.dates),r=Object.keys(e.dates);if(n.sort(),r.sort(),!this._arraysEqual(n,r))return!1;for(var i=0;i<n.length;i++){var a=n[i],o=t.dates[a],s=e.dates[a];if(o!==s&&!(Array.isArray(o)&&Array.isArray(s)&&this._arraysEqual(o,s)))return!1}return!0},equals:function(t){if(!(t instanceof Au))return!1;var e=this.getConfig(),n=t.getConfig();if(!this._compareSettings(e,n))return!1;if(e.parsed.haveCustomWeeks&&n.parsed.haveCustomWeeks){if(e.parsed.customWeeksBoundaries.length!=n.parsed.customWeeksBoundaries.length)return!1;for(var r in e.parsed.customWeeks){var i=e.parsed.customWeeks[r],a=n.parsed.customWeeks[r];if(!a||!this._compareSettings(i,a))return!1}}else if(e.parse.haveCustomWeeks!==n.parsed.haveCustomWeeks)return!1;return!0},getWorkHours:function(){var t=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);return this._getWorkHours(t.date,!1)},_getWorkHours:function(t,e){var n=this.getConfig();if(e!==!1&&(n=n.parsed),!t)return n.hours;let r=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()));var i=this._timestamp({date:r});if(n.haveCustomWeeks&&n.customWeeksRangeStart<=i&&n.customWeeksRangeEnd>i){for(var a=0;a<n.customWeeksBoundaries.length;a++)if(n.customWeeksBoundaries[a].from<=i&&n.customWeeksBoundaries[a].to>i){n=n.customWeeks[n.customWeeksBoundaries[a].name];break}}var o=!0;return n.dates[i]!==void 0?o=n.dates[i]:n.dates[t.getUTCDay()]!==void 0&&(o=n.dates[t.getUTCDay()]),o===!0?n.hours:o||[]},_getIntervalTimestamp:function(t,e){var n={start:0,end:0};n.start=t.getUTCHours()*60*60+t.getUTCMinutes()*60+t.getUTCSeconds();var r=e.getUTCHours();return!r&&!e.getUTCMinutes()&&!e.getUTCSeconds()&&t.valueOf()<e.valueOf()&&(r=24),n.end=r*60*60+e.getUTCMinutes()*60+e.getUTCSeconds(),n},_parseHours:function(t){if(Array.isArray(t)){var e=[];t.forEach(function(s){typeof s=="number"?e.push(s*60*60):typeof s=="string"&&s.split("-").map(function(l){return l.trim()}).forEach(function(l){var c=l.split(":").map(function(u){return u.trim()}),d=parseInt(c[0]*60*60);c[1]&&(d+=parseInt(c[1]*60)),c[2]&&(d+=parseInt(c[2])),e.push(d)})});for(var n=[],r=0;r<e.length;r+=2){var i=e[r],a=e[r+1],o=a-i;n.push({start:i,end:a,startHour:Math.floor(i/3600),startMinute:Math.floor(i/60),endHour:Math.ceil(a/3600),endMinute:Math.ceil(a/60),durationSeconds:o,durationMinutes:o/60,durationHours:o/3600})}return n}else return t},setWorkTime:function(t){return this._tryChangeCalendarSettings(ve(function(){var e=t.hours!==void 0?t.hours:!0,n=this._timestamp(t),r=this.getConfig();if(n!==null?r.dates[n]=e:t.customWeeks||(r.hours=e),t.customWeeks){if(r.customWeeks||(r.customWeeks={}),typeof t.customWeeks=="string")n!==null?r.customWeeks[t.customWeeks].dates[n]=e:t.customWeeks||(r.customWeeks[t.customWeeks].hours=e);else if(typeof t.customWeeks=="object"&&t.customWeeks.constructor===Object)for(var i in t.customWeeks)r.customWeeks[i]=t.customWeeks[i]}this._parseSettings(),this._clearCaches()},this))},unsetWorkTime:function(t){return this._tryChangeCalendarSettings(ve(function(){if(!t)this.reset_calendar();else{var e=this._timestamp(t);e!==null&&delete this.getConfig().dates[e]}this._parseSettings(),this._clearCaches()},this))},_isWorkTime:function(t,e){var n=-1,r=null;return r=String(t.valueOf()),n=this._workingUnitsCache.getItem(e,r,t),n==-1&&(n=this._checkIfWorkingUnit(t,e),this._workingUnitsCache.setItem(e,r,n,t)),n},isWorkTime:function(){var t=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._isWorkTime(t.date,t.unit)},calculateDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments);if(!t.unit)return!1;var e=this;return this._dateDurationCache.getDuration(t.start_date,t.end_date,t.unit,t.step,function(){return e._calculateDuration(t.start_date,t.end_date,t.unit,t.step)})},_calculateDuration:function(t,e,n,r){var i=0,a=1;if(t.valueOf()>e.valueOf()){var o=e;e=t,t=o,a=-1}return n=="hour"&&r==1?i=this._getHoursBetween(t,e,n,r):n=="minute"&&r==1?i=this._getMinutesBetween(t,e,n,r):i=this._getWorkUnitsBetweenGeneric(t,e,n,r),a*Math.round(i)},hasDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.end_date,r=t.unit,i=t.step;if(!r)return!1;var a=new Date(e),o=new Date(n);for(i=i||1;a.valueOf()<o.valueOf();){if(this._isWorkTime(a,r))return!0;a=this._nextDate(a,r,i)}return!1},calculateEndDate:function(){var t=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.duration,r=t.unit,i=t.step;if(!r)return!1;var a=t.duration>=0?1:-1;n=Math.abs(n*1);var o=this;return this._dateDurationCache.getEndDate(e,n,r,i*a,function(){return o._calculateEndDate(e,n,r,i*a)})},_calculateEndDate:function(t,e,n,r){if(!n)return!1;if(r==1&&n=="minute")return this._calculateMinuteEndDate(t,e,r);if(r==-1&&n=="minute")return this._subtractMinuteDate(t,e,r);if(r==1&&n=="hour")return this._calculateHourEndDate(t,e,r);var i=this._addInterval(t,e,n,r,null);return i.end},_addInterval:function(t,e,n,r,i){for(var a=0,o=t;a<e&&!(i&&i(o));){var s=this._nextDate(o,n,r),l=new Date(s.valueOf()+1);r>0&&(l=new Date(s.valueOf()-1));var c=this._isWorkTime(l,n);c&&a++,o=s}return{end:o,start:t,added:a}},_addHoursUntilDayEnd:function(t,e){for(var n=this.$gantt.date.add(this.$gantt.date.day_start(new Date(t)),1,"day"),r=0,i=e,a=this._getIntervalTimestamp(t,n),o=this._getWorkHours(t),s=0;s<o.length&&r<e;s++){var l=o[s];if(a.end>=l.start&&a.start<=l.end){var c=Math.max(l.start,a.start),d=Math.min(l.end,a.end),u=(d-c)/3600;u>i&&(u=i,d=c+i*60*60);var p=Math.round((d-c)/3600);r+=p,i-=p,a.start=d}}var y=n;return r===e&&(y=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),0,0,a.start))),{added:r,end:y}},_calculateHourEndDate:function(t,e,n){var r=new Date(t),i=0;n=n||1,e=Math.abs(e*1);var a=this._addHoursUntilDayEnd(r,e);i=a.added,r=a.end;var o=e-i;if(o){for(var s=r;i<e;){var l=this._nextDate(s,"day",n);l.setUTCHours(0),l.setUTCMinutes(0),l.setUTCSeconds(0);var c=0;if(n>0?c=this.getHoursPerDay(new Date(l.valueOf()-1)):c=this.getHoursPerDay(new Date(l.valueOf()+1)),i+c>=e)break;i+=c,s=l}r=s}if(i<e){var o=e-i;a=this._addHoursUntilDayEnd(r,o),r=a.end}return r},_addMinutesUntilHourEnd:function(t,e){if(t.getUTCMinutes()===0)return{added:0,end:new Date(t)};for(var n=this.$gantt.date.add(this.$gantt.date.hour_start(new Date(t)),1,"hour"),r=0,i=e,a=this._getIntervalTimestamp(t,n),o=this._getWorkHours(t),s=0;s<o.length&&r<e;s++){var l=o[s];if(a.end>=l.start&&a.start<=l.end){var c=Math.max(l.start,a.start),d=Math.min(l.end,a.end),u=(d-c)/60;u>i&&(u=i,d=c+i*60);var p=Math.round((d-c)/60);i-=p,r+=p,a.start=d}}var y=n;return r===e&&(y=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),0,0,a.start))),{added:r,end:y}},_subtractMinutesUntilHourStart:function(t,e){for(var n=this.$gantt.date.hour_start(new Date(t)),r=0,i=e,a=n.getUTCHours()*60*60+n.getUTCMinutes()*60+n.getUTCSeconds(),o=t.getUTCHours()*60*60+t.getUTCMinutes()*60+t.getUTCSeconds(),s=this._getWorkHours(t),l=s.length-1;l>=0&&r<e;l--){var c=s[l];if(o>c.start&&a<=c.end){var d=Math.min(o,c.end),u=Math.max(a,c.start),p=(d-u)/60;p>i&&(p=i,u=d-i*60);var y=Math.abs(Math.round((d-u)/60));i-=y,r+=y,o=u}}var f=n;return r===e&&(f=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),0,0,o))),{added:r,end:f}},_subtractMinuteDate:function(t,e,n){var r=this.getClosestWorkTime({date:t,dir:"past",unit:"minute"}),i=0;n=n||-1,e=Math.abs(e*1),e=Math.round(e);let a=this._isMinutePrecision(r),o=this._subtractMinutesUntilHourStart(r,e);i+=o.added,r=o.end;for(var s=0,l=[],c=0;i<e;){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 p=new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),23,59,59,999)).valueOf();p!==s&&(l=this._getWorkHours(d),c=this._getMinutesPerDay(d),s=p);var y=e-i,f=this._getTimeOfDayStamp(r,u);if(!l.length||!c){r=this.$gantt.date.add(r,-1,"day");continue}if(l[l.length-1].end<=f&&y>c){i+=c,r=this.$gantt.date.add(r,-1,"day");continue}for(var m=!1,A=null,g=null,P=l.length-1;P>=0;P--)if(l[P].start<f-1&&l[P].end>=f-1){m=!0,A=l[P],g=l[P-1];break}if(m)if(f===A.end&&y>=A.durationMinutes)i+=A.durationMinutes,r=this.$gantt.date.add(r,-A.durationMinutes,"minute");else if(!a&&y<=f/60-A.startMinute)i+=y,r=this.$gantt.date.add(r,-y,"minute");else if(a)y<=f/60-A.startMinute?(i+=y,r=this.$gantt.date.add(r,-y,"minute")):(i+=f/60-A.startMinute,g?r=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,g.end)):r=this.$gantt.date.day_start(r));else{var L=this._getMinutesPerHour(r);L<=y?(i+=L,r=this._nextDate(r,"hour",n)):(o=this._subtractMinutesUntilHourStart(r,y),i+=o.added,r=o.end)}else if(r.getUTCHours()===0&&r.getUTCMinutes()===0&&r.getUTCSeconds()===0){var F=this._getClosestWorkTimePast(r,"hour");if(F.valueOf()===r.valueOf()){var F=this.$gantt.date.add(r,-1,"day"),T=this._getWorkHours(F);if(T.length){var x=T[T.length-1];F.setUTCSeconds(x.durationSeconds)}}r=F}else r=this._getClosestWorkTimePast(new Date(r-1),"hour")}if(i<e){var S=e-i;o=this._subtractMinutesUntilHourStart(r,S),i+=o.added,r=o.end}return r},_calculateMinuteEndDate:function(t,e,n){var r=new Date(t),i=0;n=n||1,e=Math.abs(e*1),e=Math.round(e);var a=this._addMinutesUntilHourEnd(r,e);i+=a.added,r=a.end;for(var o=0,s=[],l=0,c=this._isMinutePrecision(r);i<e;){var d=this.$gantt.date.day_start(new Date(r)).valueOf();d!==o&&(s=this._getWorkHours(r),l=this._getMinutesPerDay(r),o=d);var u=e-i,p=this._getTimeOfDayStamp(r);if(!s.length||!l){r=this.$gantt.date.add(this.$gantt.date.day_start(r),1,"day");continue}if(s[0].start>=p&&u>=l){if(i+=l,u==l){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 y=!1,f=null,m=0;m<s.length;m++)if(s[m].start<=p&&s[m].end>p){y=!0,f=s[m];break}if(y)if(p===f.start&&u>=f.durationMinutes)i+=f.durationMinutes,r=this.$gantt.date.add(r,f.durationMinutes,"minute");else if(u<=f.endMinute-p/60)i+=u,r=this.$gantt.date.add(r,u,"minute");else{var A=this._getMinutesPerHour(r);A<=u?(i+=A,c?r=this.$gantt.date.add(r,A,"minute"):r=this._nextDate(r,"hour",n)):(a=this._addMinutesUntilHourEnd(r,u),i+=a.added,r=a.end)}else r=this._getClosestWorkTimeFuture(r,"hour")}if(i<e){var g=e-i;a=this._addMinutesUntilHourEnd(r,g),i+=a.added,r=a.end}return r},getClosestWorkTime:function(){var t=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._getClosestWorkTime(t.date,t.unit,t.dir)},_getClosestWorkTime:function(t,e,n){var r=new Date(t);if(this._isWorkTime(r,e))return r;if(r=this.$gantt.date[e+"_start"](r),n=="any"||!n){var i=this._getClosestWorkTimeFuture(r,e),a=this._getClosestWorkTimePast(r,e);Math.abs(i-t)<=Math.abs(t-a)?r=i:r=a}else n=="past"?r=this._getClosestWorkTimePast(r,e):r=this._getClosestWorkTimeFuture(r,e);return r},_getClosestWorkTimeFuture:function(t,e){return this._getClosestWorkTimeGeneric(t,e,1)},_getClosestWorkTimePast:function(t,e){var n=this._getClosestWorkTimeGeneric(t,e,-1);return this.$gantt.date.add(n,1,e)},_findClosestTimeInDay:function(t,e,n){var r=new Date(t),i=null,a=!1;this._getWorkHours(r).length||(r=this._getClosestWorkTime(r,"day",e<0?"past":"future"),e<0&&(r=new Date(r.valueOf()-1),a=!0),n=this._getWorkHours(r));var o=this._getTimeOfDayStamp(r);if(a&&(o=this._getTimeOfDayStamp(new Date(r.valueOf()+1),a)),e>0){for(var s=0;s<n.length;s++)if(n[s].start>=o){i=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,n[s].start));break}}else for(var s=n.length-1;s>=0;s--)if(n[s].end<=o){i=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,n[s].end));break}else if(n[s].end>o&&n[s].start<=o){i=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,o));break}return i},_getClosestWorkMinute:function(t,e,n){var r=new Date(t),i=this._getWorkHours(r),a=this._findClosestTimeInDay(r,n,i);return a||(n>0?(r=this.calculateEndDate(r,n,e),r=this.$gantt.date.day_start(r)):(r=this.calculateEndDate(r,n,"day"),r=this.$gantt.date.day_start(r),r=this.$gantt.date.add(r,1,"day"),r=new Date(r.valueOf()-1)),i=this._getWorkHours(r),a=this._findClosestTimeInDay(r,n,i)),n<0&&(a=this.$gantt.date.add(a,-1,e)),a},_getClosestWorkTimeGeneric:function(t,e,n){if(e==="hour"||e==="minute")return this._getClosestWorkMinute(t,e,n);for(var r=this._getUnitOrder(e),i=this.units[r-1],a=t,o=3e3,s=0;!this._isWorkTime(a,e)&&!(i&&!this._isWorkTime(a,i)&&(n>0?a=this._getClosestWorkTimeFuture(a,i):a=this._getClosestWorkTimePast(a,i),this._isWorkTime(a,e)));){if(s++,s>o)return this.$gantt.assert(!1,"Invalid working time check"),!1;a=this.$gantt.date.add(a,n,e),this.$gantt.date[e+"_start"]&&(a=this.$gantt.date[e+"_start"](a))}return a},hasWorkTime:function(){var t=this.getConfig(),e=t.dates,n=[0,1,2,3,4,5,6];for(var r in t.dates);var i=this._checkWorkHours(t.hours),a=!1;return n.forEach((function(o){if(!a){var s=e[o];s===!0?a=i:Array.isArray(s)&&(a=this._checkWorkHours(s))}}).bind(this)),a},_checkWorkHours:function(t){if(t.length===0)return!1;for(var e=!1,n=0;n<t.length;n+=2)t[n]!==t[n+1]&&(e=!0);return e},_isMinutePrecision:function(t){let e=!1;return this._getWorkHours(t).forEach(function(n){(n.startMinute%60||n.endMinute%60)&&(e=!0)}),e}};var eo={isLegacyResourceCalendarFormat:function(t){if(!t)return!1;for(var e in t)if(t[e]&&typeof t[e]=="object")return!0;return!1},getResourceProperty:function(t){var e=t.resource_calendars,n=t.resource_property;if(this.isLegacyResourceCalendarFormat(e))for(var r in t){n=r;break}return n},getCalendarIdFromLegacyConfig:function(t,e){if(e)for(var n in e){var r=e[n];if(t[n]){var i=r[t[n]];if(i)return i}}return null}};function aF(){function t(i){return i.map(function(a){return a&&a.resource_id?a.resource_id:a}).sort().join("-")}var e={};function n(i,a){return a.mergeCalendars(i.map(function(o){var s=o&&o.resource_id?o.resource_id:o;return a.getResourceCalendar(s)}))}function r(i,a){var o=t(i);if(i.length){if(i.length===1)return a.getResourceCalendar(o).id;if(e[o])return e[o].id;var s=n(i,a);return e[o]=s,a.addCalendar(s)}else return null}return{getCalendarIdFromMultipleResources:r}}var oF=aF();function uI(t){this.$gantt=t,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=eo.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))}uI.prototype={_calendars:{},_convertWorkTimeSettings:function(t){let e=t.days;if(typeof e=="object"&&!Array.isArray(e)&&e!==null){let n={};if(e?.weekdays)for(let r=0;r<7;r++)n[r]=e.weekdays[r];e?.dates&&Object.entries(e.dates).forEach(([r,i])=>{n[new Date(r).valueOf()]=i}),Object.entries(n).forEach(([r,i])=>{i instanceof Array||(n[r]=!!i)}),t={...t,dates:n}}else if(e&&!t.dates){t.dates=t.dates||{};for(let n=0;n<e.length;n++)t.dates[n]=e[n],e[n]instanceof Array||(t.dates[n]=!!e[n])}return delete t.days,t},mergeCalendars:function(){var t=[],e=arguments;if(Array.isArray(e[0]))t=e[0].slice();else for(var n=0;n<arguments.length;n++)t.push(arguments[n]);var r=new dI,i;return t.forEach((function(a){i?i=this._createCalendarFromConfig(r.merge(i,a)):i=a}).bind(this)),this.createCalendar(i)},_createCalendarFromConfig:function(t){var e=new Au(this.$gantt,cI(this.$gantt));e.id=String(du());var n=this._convertWorkTimeSettings(t);if(n.customWeeks)for(var r in n.customWeeks)n.customWeeks[r]=this._convertWorkTimeSettings(n.customWeeks[r]);return e._setConfig(n),e},createCalendar:function(t){var e;t||(t={}),t.getConfig?e=je(t.getConfig()):t.worktime?e=je(t.worktime):e=je(t);var n=je(this.defaults.fulltime.worktime);return Ki(e,n),this._createCalendarFromConfig(e)},getCalendar:function(t){t=t||"global";var e=this._calendars[t];return e||(this.createDefaultCalendars(),e=this._calendars[t]),e},getCalendars:function(){var t=[];for(var e in this._calendars)t.push(this.getCalendar(e));return t},_getOwnCalendar:function(t){var e=this.$gantt.config;if(t[e.calendar_property])return this.getCalendar(t[e.calendar_property]);if(e.resource_calendars){var n,r,i;if(this._legacyConfig===!1?i=e.resource_property:i=eo.getResourceProperty(e),Array.isArray(t[i])&&t[i].length)e.dynamic_resource_calendars?r=oF.getCalendarIdFromMultipleResources(t[i],this):n=this.getResourceCalendar(t[i]);else if(this._legacyConfig===void 0&&(this._legacyConfig=eo.isLegacyResourceCalendarFormat(e.resource_calendars)),this._legacyConfig)var r=eo.getCalendarIdFromLegacyConfig(t,e.resource_calendars);else if(i&&t[i]&&e.resource_calendars[t[i]])var n=this.getResourceCalendar(t[i]);if(r&&(n=this.getCalendar(r)),n)return n}return null},getResourceCalendar:function(t){if(t==null)return this.getCalendar();var e=null;typeof t=="number"||typeof t=="string"?e=t:e=t.id||t.key;var n=this.$gantt.config,r=n.resource_calendars,i=null;if(Array.isArray(t)&&t.length===1&&(typeof t[0]=="object"?e=t[0].resource_id:e=t[0]),r){if(this._legacyConfig===void 0&&(this._legacyConfig=eo.isLegacyResourceCalendarFormat(n.resource_calendars)),this._legacyConfig){for(var a in r)if(r[a][e]){i=r[a][e];break}}else var i=r[e];if(i)return this.getCalendar(i)}return this.getCalendar()},getTaskCalendar:function(t){var e=this.$gantt,n;if(t==null)return this.getCalendar();if((typeof t=="number"||typeof t=="string")&&e.isTaskExists(t)?n=e.getTask(t):n=t,!n)return this.getCalendar();var r=this._getOwnCalendar(n),i=!!e.getState().group_mode;if(!r&&e.config.inherit_calendar&&e.isTaskExists(n.parent)){for(var a=n;e.isTaskExists(a.parent)&&(a=e.getTask(a.parent),!(e.isSummaryTask(a)&&(r=this._getOwnCalendar(a),r))););i&&!r&&t.$effective_calendar&&(r=this.getCalendar(t.$effective_calendar))}return r||this.getCalendar()},addCalendar:function(t){if(!this.isCalendar(t)){var e=t.id;t=this.createCalendar(t),t.id=e}if(t._tryChangeCalendarSettings(function(){})){var n=this.$gantt.config;return t.id=t.id||du(),this._calendars[t.id]=t,n.worktimes||(n.worktimes={}),n.worktimes[t.id]=t.getConfig(),t.id}else return this.$gantt.callEvent("onCalendarError",[{message:"Invalid calendar settings, no worktime available"},t]),null},deleteCalendar:function(t){var e=this.$gantt.config;return t&&this._calendars[t]?(delete this._calendars[t],e.worktimes&&e.worktimes[t]&&delete e.worktimes[t],!0):!1},restoreConfigCalendars:function(t){for(var e in t)if(!this._calendars[e]){var n=t[e],r=this.createCalendar(n);r.id=e,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 t=this.$gantt.config;this.restoreConfigCalendars(this.defaults),this.restoreConfigCalendars(t.worktimes)},isCalendar:function(t){var e=[t.isWorkTime,t.setWorkTime,t.getWorkHours,t.unsetWorkTime,t.getClosestWorkTime,t.calculateDuration,t.hasDuration,t.calculateEndDate];return e.every(function(n){return n instanceof Function})}};function Iu(t,e){this.argumentsHelper=e,this.$gantt=t}Iu.prototype={getWorkHours:function(){return[0,24]},setWorkTime:function(){return!0},unsetWorkTime:function(){return!0},isWorkTime:function(){return!0},getClosestWorkTime:function(e){var e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return e.date},calculateDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.end_date,r=t.unit,i=t.step;return this._calculateDuration(e,n,r,i)},_calculateDuration:function(t,e,n,r){var i=this.$gantt.date,a={week:1e3*60*60*24*7,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60},o=0;if(a[n])o=Math.round((e-t)/(r*a[n]));else{for(var s=new Date(t),l=new Date(e);s.valueOf()<l.valueOf();)o+=1,s=i.add(s,r,n);s.valueOf()!=e.valueOf()&&(o+=(l-s)/(i.add(s,r,n)-s))}return Math.round(o)},hasDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.end_date,r=t.unit;return r?(e=new Date(e),n=new Date(n),e.valueOf()<n.valueOf()):!1},hasWorkTime:function(){return!0},equals:function(t){return t instanceof Iu},calculateEndDate:function(){var t=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.duration,r=t.unit,i=t.step;return this.$gantt.date.add(e,i*n,r)}};function pI(t){this.$gantt=t.$gantt,this.argumentsHelper=cI(this.$gantt),this.calendarManager=t,this.$disabledCalendar=new Iu(this.$gantt,this.argumentsHelper)}pI.prototype={_getCalendar:function(t){var e;if(!this.$gantt.config.work_time)e=this.$disabledCalendar;else{var n=this.calendarManager;t.task?e=n.getTaskCalendar(t.task):t.id?e=n.getTaskCalendar(t):t.calendar&&(e=t.calendar),e||(e=n.getTaskCalendar())}return e},getWorkHours:function(t){t=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);var e=this._getCalendar(t);return e.getWorkHours(t.date)},setWorkTime:function(t,e){return t=this.argumentsHelper.setWorkTimeArguments.apply(this.argumentsHelper,arguments),e||(e=this.calendarManager.getCalendar()),e.setWorkTime(t)},unsetWorkTime:function(t,e){return t=this.argumentsHelper.unsetWorkTimeArguments.apply(this.argumentsHelper,arguments),e||(e=this.calendarManager.getCalendar()),e.unsetWorkTime(t)},isWorkTime:function(t,e,n,r){var i=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return r=this._getCalendar(i),r.isWorkTime(i)},getClosestWorkTime:function(t){t=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);var e=this._getCalendar(t);return e.getClosestWorkTime(t)},calculateDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),e=this._getCalendar(t);return e.calculateDuration(t)},hasDuration:function(){var t=this.argumentsHelper.hasDurationArguments.apply(this.argumentsHelper,arguments),e=this._getCalendar(t);return e.hasDuration(t)},calculateEndDate:function(e){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),n=this._getCalendar(e);return n.calculateEndDate(e)}};var sF=function(t,e){return{getWorkHours:function(n){return e.getWorkHours(n)},setWorkTime:function(n){return e.setWorkTime(n)},unsetWorkTime:function(n){e.unsetWorkTime(n)},isWorkTime:function(n,r,i){return e.isWorkTime(n,r,i)},getClosestWorkTime:function(n){return e.getClosestWorkTime(n)},calculateDuration:function(n,r,i){return e.calculateDuration(n,r,i)},_hasDuration:function(n,r,i){return e.hasDuration(n,r,i)},calculateEndDate:function(n,r,i,a){return e.calculateEndDate(n,r,i,a)},mergeCalendars:ve(t.mergeCalendars,t),createCalendar:ve(t.createCalendar,t),addCalendar:ve(t.addCalendar,t),getCalendar:ve(t.getCalendar,t),getCalendars:ve(t.getCalendars,t),getResourceCalendar:ve(t.getResourceCalendar,t),getTaskCalendar:ve(t.getTaskCalendar,t),deleteCalendar:ve(t.deleteCalendar,t)}},lF={create:sF};function yI(t){var e=new uI(t),n=new pI(e),r=lF.create(e,n);Ki(t,r)}var fI={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 hI(t={}){let e=t.config||{},n={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},e),locale:t.locale||fI,templates:t.templates||{},getTask:t.getTask||function(r){return null},isTaskExists:t.isTaskExists||function(r){return!1},isSummaryTask:t.isSummaryTask||function(r){return!1},getState:function(){return{group_mode:!1}},callEvent:function(r,i){let a=t.onEvent;return a&&a(r,i),!0},attachEvent:function(){return 0},checkEvent:function(){return!1},detachEvent:function(){},defined:aI,mixin:Ki,copy:je,assert:function(r,i){if(!r){if(t.throwOnAssert)throw new Error("[calendar] "+i);t.silent!==!0&&console.error("[calendar]",i)}},$services:{getService:function(){return null}},$ui:{getView:function(){return null}}};return n._correct_dst_change=function(r){return r},n.date=lI(n),n.date.init(),yI(n),n}function cF(t={}){let e=hI(t);return{addCalendar:function(n){return e.addCalendar(n)},deleteCalendar:function(n){return e.deleteCalendar(n)},getCalendar:function(n){return e.getCalendar(n)},getCalendars:function(){return e.getCalendars()},mergeCalendars:function(){return e.mergeCalendars.apply(e,arguments)},getTaskCalendar:function(n){return e.getTaskCalendar(n)},getResourceCalendar:function(n){return e.getResourceCalendar(n)},setWorkTime:function(n){return e.setWorkTime(n)},unsetWorkTime:function(n){return e.unsetWorkTime(n)},isWorkTime:function(){return e.isWorkTime.apply(e,arguments)},getClosestWorkTime:function(){return e.getClosestWorkTime.apply(e,arguments)},getWorkHours:function(){return e.getWorkHours.apply(e,arguments)},calculateDuration:function(){return e.calculateDuration.apply(e,arguments)},calculateEndDate:function(){return e.calculateEndDate.apply(e,arguments)},_internals:e}}var mI={createCalendar:cF};var o7=3600*1e3;function SI(t){return{getActivity(e){return t.getActivity(e)}}}var{createCalendar:dF}=mI,no="__replay_default__";function uF(t){if(!t||t.length===0||typeof t[0]=="string")return t;let e=t.map(Number);if(e.some(a=>Number.isNaN(a)))return t;let n=e[0],r=e[e.length-1];return e.every((a,o)=>a===n+o)?[`${n}:00-${r+1}:00`]:t}var gI={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},AI="__main_global__",pF={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function yF(){}function II(t){return!t||t.hours===void 0||t.hours.length>0||t.days?.some(e=>Array.isArray(e)&&e.length>0)===!0?!0:Object.values(t.dates??{}).some(e=>Array.isArray(e)&&e.length>0)}function fF(t,e=yF){let n=iI({hours:uF(t.hours),days:t.days,dates:t.dates},e),r={};if(Array.isArray(n.days))for(let a=0;a<n.days.length;a+=1)r[a]=n.days[a];if(n.dates)for(let[a,o]of Object.entries(n.dates))r[a]=o;let i={hours:n.hours,dates:r};return t.customWeeks&&(i.customWeeks=t.customWeeks),i}function Pl(t,e=_e){let n=dF({config:{work_time:!0}});n.addCalendar({id:no,worktime:gI}),n.addCalendar({id:AI,worktime:pF});let r=new Set(t.filter(u=>!II(u.worktime)).map(u=>String(u.id))),i=t.filter(u=>II(u.worktime));for(let u of i)n.addCalendar({id:u.id,worktime:u.worktime?fF(u.worktime,(p,y)=>e.warn(p,{calendarId:u.id,...y})):gI});let a=Th(n),o=a.getCalendar(no),s=a.getCalendar(AI);if(!o||!s)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let l=new Set([no]);for(let u of i)l.add(String(u.id));let c=new Map;return{reader:{getCalendar(u){let p=String(u),y=c.get(p);if(y)return y;let f=o;return l.has(p)?f=a.getCalendar(u)??o:r.has(p)&&(f=s),c.set(p,f),f}}}}function vI(t){return{hasChildren(e){return t.hasChildren(e)},getParentStartDateIfHasPredecessors(e){let n=t.getActivity(e);if(!n)return null;let r=t.getParent(n.id);return!r||t.getIncomingLinkIds(r.id).length===0?null:r.startDate},getDescendantIds(e){return hF(t,e).map(n=>String(n))},getAncestorIds(e){let n=[],r=t.getActivity(e);for(;r;){let i=r.parentId;if(i===null)break;let a=t.getActivity(i);if(!a)break;n.push(String(i)),r=a}return n},getChildProgressInfo(e){return t.getChildren(e).map(r=>{let i=t.getActivity(r);return{id:r,progress:Number(i?.progress??0),ponderator:Number(i?.ponderator??0)}})},getChildHhInfo(e){return t.getChildren(e).map(r=>{let i=t.getActivity(r);return{id:r,workHours:Number(i?.workHours??0),progress:Number(i?.progress??0),realWorkHours:Number(i?.realWorkHours??0)}})},getChildUsedCostInfo(e){return t.getChildren(e).map(r=>{let i=t.getActivity(r);return{id:r,usedCost:Number(i?.usedCost??0)}})},getChildCostInfo(e){return t.getChildren(e).map(r=>{let i=t.getActivity(r);return{id:r,cost:Number(i?.cost??0)}})}}}function hF(t,e){let n=[],r=new De;for(let i of t.getChildren(e))r.enqueue(i);for(;!r.isEmpty();){let i=r.dequeue();n.push(i);for(let a of t.getChildren(i))r.enqueue(a)}return n}var mF=["startDate","endDate","durationHours","constraintType","constraintDate","autoScheduling","calendarId","parentId","type","progress"],gF=["source","target","type","lag"];function CI(t,e){return t instanceof Date&&e instanceof Date?t.getTime()===e.getTime():Object.is(t,e)}function AF(t,e){if(t.kind!==Tt.LINK_FIELD)return!0;let n=e(t.linkId);return n===null?!0:gF.some(r=>!CI(t.before[r],n[r]))}function DI(t,e,n){if(t.ops.some(r=>AF(r,n)))return!0;for(let[r,i]of t.before){let a=e(r);if(a===null||mF.some(s=>!CI(i[s],a[s])))return!0}return!1}var kl=class{constructor(e,n,r){this._fields=e;this._scope=n;this._settle=r}_fields;_scope;_settle;_structural=!0;_touchedIds=new Set;_reshapedIds=new Set;_appendedLinkIds=[];_removedLinkIds=[];touch(e,n){!this._structural&&this._fields.has(n)&&this._touchedIds.add(e)}reshape(e){this._scope.patchesHierarchy?this._structural||this._reshapedIds.add(e):this.markStructural()}changeLinks(){this._scope.ignoresLinks||this.markStructural()}appendLink(e){this._scope.patchesLinkAppends?this._structural||this._appendedLinkIds.push(e):this.changeLinks()}removeLink(e){this._scope.patchesLinkRemovals?this._appendedLinkIds.includes(e)?this.markStructural():this._structural||this._removedLinkIds.push(e):this.changeLinks()}markStructural(){this._structural=!0,this._touchedIds.clear(),this._reshapedIds.clear(),this._appendedLinkIds=[],this._removedLinkIds=[]}take(){this._settle();let e={structural:this._structural,touchedIds:this._touchedIds,reshapedIds:this._reshapedIds,appendedLinkIds:this._appendedLinkIds,removedLinkIds:this._removedLinkIds};return this._structural=!1,this._touchedIds=new Set,this._reshapedIds=new Set,this._appendedLinkIds=[],this._removedLinkIds=[],e}};var bl=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(e){this.reader=e.reader}resolveCalendar(e){let n=TI(e);return this.reader.getCalendar(n??no)}getClosestWorkTime(e){let n=Yi(Yi(this._cache.closestWorkTime,vu(e.task)),e.dir);return Su(n,e.date.getTime(),()=>this.resolveCalendar(e.task).getClosestWorkTime({direction:e.dir,date:e.date,unit:mt.HOUR}))}isWorkTime(e){return this.resolveCalendar(e.task).isWorkTime(e.date,mt.MINUTE)}calculateEndDate(e){let n=Yi(Yi(this._cache.endDate,vu(e.task)),e.startDate.getTime());return Su(n,e.durationHours,()=>this.resolveCalendar(e.task).calculateEndDate(e.startDate,e.durationHours))}calculateDuration(e){let n=Yi(Yi(this._cache.duration,vu(e.task)),e.startDate.getTime());return Su(n,e.endDate.getTime(),()=>this.resolveCalendar(e.task).calculateDuration(e.startDate,e.endDate))}clearCache(){this._cache.closestWorkTime.clear(),this._cache.endDate.clear(),this._cache.duration.clear()}};function Su(t,e,n){let r=t.get(e);if(r!==void 0)return r;let i=n();return t.set(e,i),i}function Yi(t,e){let n=t.get(e);if(n)return n;let r=new Map;return t.set(e,r),r}var IF="__default__";function TI(t){if(!t)return null;let e=t.calendarId;return e==null?null:String(e)}function vu(t){return TI(t)??IF}var Ll=class{constructor(e){this.activities=e}activities;_childrenByParent=new Map;_roots=[];_dirty=!1;reportReorderedParent=()=>{};markDirty(){this._dirty=!0}settle(){this._dirty&&(this.rebuild(),this._dirty=!1)}getChildren(e){return this._dirty&&(this.rebuild(),this._dirty=!1),this._childrenByParent.get(String(e))??[]}hasChildren(e){return this._dirty&&(this.rebuild(),this._dirty=!1),(this._childrenByParent.get(String(e))?.length??0)>0}getRootIds(){return this._dirty&&(this.rebuild(),this._dirty=!1),[...this._roots]}isChildOf(e,n){let r=this.activities.get(e)?.parentId,i=0,a=this.activities.size;for(;r&&!q(r);){if(r===n)return!0;if(++i>a)return!1;r=this.activities.get(r)?.parentId}return!1}getParent(e){let n=this.activities.get(e)?.parentId;return!n||q(n)?null:this.activities.get(n)??null}getParentId(e){return this.activities.get(e)?.parentId??null}addChild(e,n){if(this._dirty)return;if(q(e)){this._roots.push(n);return}let r=String(e),i=this._childrenByParent.get(r);i?i.push(n):this._childrenByParent.set(r,[n])}rebuild(){let e=this._childrenByParent,n=[],r=new Map;for(let i of this.activities.values()){if(q(i.parentId)){n.push(i);continue}let a=String(i.parentId),o=r.get(a);o?o.push(i):r.set(a,[i])}this._roots=_I(n),this._childrenByParent=new Map;for(let[i,a]of r)this._childrenByParent.set(i,_I(a));this.reportReorderedParents(e)}reportReorderedParents(e){for(let[n,r]of this._childrenByParent)SF(e.get(n),r)||this.reportReorderedParent(n);for(let n of e.keys())this._childrenByParent.has(n)||this.reportReorderedParent(n)}};function SF(t,e){if(t===void 0||t.length!==e.length)return!1;for(let n=0;n<e.length;n+=1)if(t[n]!==e[n])return!1;return!0}function _I(t){return t.sort(Rn).map(e=>e.id)}var Ol=class{checkedSet=new Set;hiddenSet=new Set;activeFilter=null;activeOrder=null;isChecked(e){return this.checkedSet.has(e)}isVisible(e){return!this.hiddenSet.has(e)}hiddenIds(){return[...this.hiddenSet]}getActiveFilter(){return this.activeFilter}setActiveFilter(e){this.activeFilter=e}getActiveOrder(){return this.activeOrder}setActiveOrder(e){this.activeOrder=e}checkedIds(){return[...this.checkedSet]}checkedCount(){return this.checkedSet.size}setChecked(e,n){return n===this.checkedSet.has(e)?!1:(n?this.checkedSet.add(e):this.checkedSet.delete(e),!0)}setVisible(e,n){return n===!this.hiddenSet.has(e)?!1:(n?this.hiddenSet.delete(e):this.hiddenSet.add(e),!0)}forget(e){this.checkedSet.delete(e),this.hiddenSet.delete(e)}hydrate(e){this.checkedSet=new Set(e.checkedIds??[]),this.hiddenSet=new Set(e.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(e){this.checkedSet=new Set(e.checked),this.hiddenSet=new Set(e.hidden),this.activeFilter=e.activeFilter,this.activeOrder=e.activeOrder}};function _u(t,e,n,r,i,a){return{valueId:e,id:t,label:n,color:r,level:i,sequence:a,children:new Map,activities:[]}}function EI(t,e,n,r,i){let{attributeKey:a,startLevel:o,depth:s}=e;for(let l of t){let c=n.assignmentByActivityId.get(String(l.id)),d=c===void 0?[]:Fp(n,c,o,s),u=d.length===0?[yr]:d,p=r;u.forEach((y,f)=>{let m=p.children.get(y);if(m===void 0){let A=n.valueById.get(y);m=_u(i?bo(p.id,a,y):ko(a,y),y,A?.label??(y===yr?Eo:y),A?.color??null,r.level+1+f,A?.sequence??Number.MAX_SAFE_INTEGER),p.children.set(y,m)}p=m}),p.activities.push(l)}return r}function RI(t){let e=t.activities.length;for(let n of t.children.values())e+=RI(n);return e}function Cu(t,e){let n=[...t.children.values()];return n.sort((r,i)=>r.valueId===yr?1:i.valueId===yr?-1:r.sequence!==i.sequence?r.sequence-i.sequence:r.valueId.localeCompare(i.valueId)),e===le.DESCENDING&&n.reverse(),n}var vF=1,CF=Number.POSITIVE_INFINITY;function Du(t){return{kind:Zr.ACTIVITY,activityId:String(t.id)}}function DF(t,e,n){let r=[],i=new Map;for(let a of e){if(!t.has(String(a.id)))continue;let o=n(a.id),s=o===null?null:String(o);if(s===null||!t.has(s)){r.push(a);continue}let l=i.get(s);l===void 0?i.set(s,[a]):l.push(a)}return{roots:r,childrenOf:i}}function PI(t,e){let{roots:n,childrenOf:r}=DF(t,e.activitiesInVisualOrder,e.parentOf),i=e.wbsDepth??CF,a=l=>r.get(String(l.id))??[],o=l=>{let c=[],d=u=>{for(let p of u){let y=a(p);y.length===0?c.push(p):d(y)}};return d(l),c},s=(l,c)=>{if(c>i){let d=o(l),u=e.comparator===null?d:wo(d,e.comparator,e.orderMode,()=>!1);for(let p of u)e.rows.push(Du(p));return}for(let d of l){e.rows.push(Du(d));let u=a(d);u.length>0&&s(u,c+1)}};s(n,vF)}function TF(t,e){let n=new Set(t.map(r=>String(r.id)));for(let r of t){let i=e.parentOf(r.id);for(;i!==null;)n.add(String(i)),i=e.parentOf(i)}PI(n,e)}function _F(t,e){let{rows:n}=e;if(e.group.includeWbs){TF(t.activities,{activitiesInVisualOrder:e.activitiesInVisualOrder,parentOf:e.parentOf,wbsDepth:e.wbsDepth,comparator:e.comparator,orderMode:e.orderMode,rows:n});return}for(let r of wo([...t.activities],e.comparator,e.orderMode,e.hasChildren))n.push({kind:Zr.ACTIVITY,activityId:String(r.id)})}function Tu(t,e,n,r){let{group:i,rows:a}=r;if(a.push({kind:Zr.GROUP,id:t.id,label:t.label,level:t.level,color:t.color,activityCount:RI(t)}),i.collapsedIds.has(t.id))return;for(let s of Cu(t,e))Tu(s,e,n,r);if(t.activities.length===0)return;let o=i.secondary;if(n&&o!=null&&r.secondaryCatalog!=null){let s=EI(t.activities,o,r.secondaryCatalog,_u(t.id,"","",null,t.level,0),!0);for(let l of Cu(s,o.direction))Tu(l,o.direction,!1,r);return}_F(t,r)}function kI(t){let e=t.activitiesInVisualOrder.filter(s=>t.isVisible(s.id));if(t.group===null||t.catalog===null){if(t.wbsDepth===null)return e.map(Du);let s=[];return PI(new Set(e.map(l=>String(l.id))),{activitiesInVisualOrder:e,parentOf:t.parentOf,wbsDepth:t.wbsDepth,comparator:t.comparator,orderMode:t.orderMode,rows:s}),s}let{group:n,catalog:r}=t,i=EI(e,n,r,_u("","","",null,-1,0),!1),a=[],o={group:n,activitiesInVisualOrder:t.activitiesInVisualOrder,parentOf:t.parentOf,hasChildren:t.hasChildren,comparator:t.comparator,orderMode:t.orderMode,wbsDepth:t.wbsDepth,secondaryCatalog:t.secondaryCatalog,rows:a};for(let s of Cu(i,n.direction))Tu(s,n.direction,!0,o);return a}var Nl=class t{catalogs=new Map;group=null;wbsDepth=null;getCatalog(e){return this.catalogs.get(e)??null}getCatalogMap(){return this.catalogs}setCatalogs(e){let n=new Map;for(let r of e)n.set(r.key,Op(r));this.catalogs=n}getGroup(){return this.group}setGroup(e){this.group=e}getWbsDepth(){return this.wbsDepth}setWbsDepth(e){this.wbsDepth=e}clone(){let e=new t;return e.catalogs=new Map(this.catalogs),e.group=this.group===null?null:v(this.group),e.wbsDepth=this.wbsDepth,e}};var EF={settings:null,projectState:null,latestRunLog:null},Gi=class t{_activities=new Map;_missingSchedulingStateCount=0;_lastStartDate=new Map;_promotionSnapshot=new Map;_progressFallback=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_buildOrderComparator;_cache={ids:null,visualOrderIds:null,visualRows:null,orderComparator:null};_writeCapture=new $s;_schedulingWriteLogs=[];_scheduleSettled=!1;_settledByPassInCapture=!1;_viewState=new Ol;_viewAttributes=new Nl;_filterProjection=null;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_missingSchedulingStateCountBefore=null;_dataDate=EF;_dataDateBefore=null;_calendar;_flags;_calendarSnapshot;_isDataDateEnabled;constructor(e,n=()=>null,r=()=>!0,i=_e,a){this._buildOrderComparator=n,this._isDataDateEnabled=r,this._calendarSnapshot=v(e.calendars);for(let o of e.activities)this._activities.set(o.id,o);for(let o of this._activities.values())Zn(o)&&(this._missingSchedulingStateCount+=1);for(let o of e.links){let s={...o,freeSlackHours:o.freeSlackHours??null,isCritical:o.isCritical===!0};this._links.set(String(o.id),s),this._indexLink(s)}this._calendar=new bl(a??Pl(this._calendarSnapshot,i)),this._flags=PF(e),this._hierarchy=new Ll(this._activities),this._hierarchy.rebuild(),this._hierarchy.reportReorderedParent=o=>this._noteSchedulingReshape(o)}fork(){let e=t.fromSnapshot(this.exportSnapshot(),this._buildOrderComparator,this._isDataDateEnabled);return e._filterProjection=v(this._filterProjection),e._viewAttributes=this._viewAttributes.clone(),e._dataDate=v(this._dataDate),e}exportSnapshot(){return{activities:this.getAllActivities().map(cn),links:this.getAllLinks().map(e=>({...e})),calendars:v(this._calendarSnapshot),viewState:v(this._viewState.snapshot()),lastStartDate:new Map(Array.from(this._lastStartDate,([e,n])=>[e,new Date(n)])),promotionSnapshot:new Map(Array.from(this._promotionSnapshot,([e,n])=>[e,v(n)])),progressFallback:new Map(this._progressFallback),flags:v(this._flags),scheduleSettled:this._scheduleSettled}}static fromSnapshot(e,n,r,i){let a=new t({activities:e.activities,links:e.links,calendars:e.calendars},n,r,i);return a._viewState.restore(e.viewState),a._lastStartDate=e.lastStartDate,a._promotionSnapshot=e.promotionSnapshot,a._progressFallback=e.progressFallback,a._flags=e.flags,a._scheduleSettled=e.scheduleSettled,a}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}hasCompleteSchedulingState(){return this._missingSchedulingStateCount===0}restoreFork(e){this._activities=e._activities,this._missingSchedulingStateCount=e._missingSchedulingStateCount,this._lastStartDate=e._lastStartDate,this._promotionSnapshot=e._promotionSnapshot,this._progressFallback=e._progressFallback,this._links=e._links,this._outgoing=e._outgoing,this._incoming=e._incoming,this._hierarchy=e._hierarchy,this._hierarchy.reportReorderedParent=n=>this._noteSchedulingReshape(n),this._cache=e._cache,this._calendar=e._calendar,this._flags=e._flags,this._viewState=e._viewState,this._viewAttributes=e._viewAttributes,this._filterProjection=e._filterProjection,this._dataDate=e._dataDate,this._scheduleSettled=e._scheduleSettled,this._noteSchedulingStructure()}dataDateSettings(){return this._dataDate.settings}isDataDateEnabled(){return this._isDataDateEnabled()}dataDateProjectState(){return this._dataDate.projectState}dataDateLatestRunLog(){return this._dataDate.latestRunLog}setDataDateSettings(e){this._captureDataDateOnce(),this._dataDate={...this._dataDate,settings:v(e)}}setDataDateProjectState(e){this._captureDataDateOnce(),this._dataDate={...this._dataDate,projectState:v(e)}}setDataDateLatestRunLog(e){this._captureDataDateOnce(),this._dataDate={...this._dataDate,latestRunLog:v(e)}}_captureDataDateOnce(){this._writeCapture.peek()!==null&&this._dataDateBefore===null&&(this._dataDateBefore=this._dataDate)}getVisualOrderIds(){return this._cache.visualOrderIds?this._cache.visualOrderIds:(this._cache.visualOrderIds=Gp(this).map(e=>String(e.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null,this.invalidateVisualRows()}forEachActivity(e){for(let[n,r]of this._activities)e(r,n)}getParentId(e){return this._hierarchy.getParentId(e)}getActivity(e){return this._activities.get(String(e))??null}getLastStartDate(e){return this._lastStartDate.get(String(e))??null}setLastStartDate(e,n){this._captureLastStartDateOnce(),this._lastStartDate.set(String(e),n)}getPromotionSnapshot(e){return this._promotionSnapshot.get(String(e))??null}setPromotionSnapshot(e,n){this._capturePromotionSnapshotOnce(),this._promotionSnapshot.set(String(e),n)}getProgressFallback(e){return this._progressFallback.get(String(e))??null}setProgressFallback(e,n){let r=String(e),i=this._progressFallback.get(r)??null;Object.is(i,n)||(this._writeCapture.noteProgressFallback(r,i),n===null?this._progressFallback.delete(r):this._progressFallback.set(r,n))}_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(e){return this._links.get(String(e))??null}activityExists(e){return this._activities.has(String(e))}isChecked(e){return this._viewState.isChecked(String(e))}isVisible(e){return this._viewState.isVisible(String(e))}checkedIds(){return this._viewState.checkedIds()}hiddenIds(){return this._viewState.hiddenIds()}setChecked(e,n){return this._captureViewStateOnce(),this._viewState.setChecked(String(e),n)}setVisible(e,n){this._captureViewStateOnce();let r=this._viewState.setVisible(String(e),n);return r&&this.invalidateVisualRows(),r}getActiveFilter(){return this._viewState.getActiveFilter()}setActiveFilter(e){this._captureViewStateOnce(),this._viewState.setActiveFilter(e),this._filterProjection=null,this.invalidateVisualRows()}getFilterProjection(){return this._filterProjection}setFilterProjection(e){this._filterProjection=e}getActiveOrder(){return this._viewState.getActiveOrder()}setActiveOrder(e){this._captureViewStateOnce(),this._viewState.setActiveOrder(e),this.invalidateDerivedOrder()}getOrderComparator(){let e=this._viewState.getActiveOrder();return e===null?(this._cache.orderComparator=null,null):this._cache.orderComparator?this._cache.orderComparator:(this._cache.orderComparator=this._buildOrderComparator(e,this._viewAttributes.getCatalogMap()),this._cache.orderComparator)}getOrderMode(){return this._viewState.getActiveOrder()?.mode??rn.STANDARD}invalidateDerivedOrder(){this._cache.orderComparator=null,this._cache.visualOrderIds=null,this.invalidateVisualRows()}getViewAttributeCatalogMap(){return this._viewAttributes.getCatalogMap()}setViewAttributeCatalogs(e){this._viewAttributes.setCatalogs(e),this.invalidateDerivedOrder()}getGroup(){return this._viewAttributes.getGroup()}setGroup(e){this._viewAttributes.setGroup(e),this.invalidateVisualRows()}getWbsDepth(){return this._viewAttributes.getWbsDepth()}setWbsDepth(e){this._viewAttributes.setWbsDepth(e),this.invalidateVisualRows()}invalidateVisualRows(){this._cache.visualRows=null}getVisualRows(){if(this._cache.visualRows)return this._cache.visualRows;let e=this._viewAttributes.getGroup(),n=e===null?null:this._viewAttributes.getCatalog(e.attributeKey),r=e?.secondary==null?null:this._viewAttributes.getCatalog(e.secondary.attributeKey),i=[];for(let a of this.getVisualOrderIds()){let o=this.getActivity(a);o!==null&&i.push(o)}return this._cache.visualRows=kI({activitiesInVisualOrder:i,isVisible:a=>this.isVisible(a),parentOf:a=>this.getParentId(a),hasChildren:a=>this.hasChildren(a),group:e,catalog:n,secondaryCatalog:r,comparator:this.getOrderComparator(),orderMode:this.getOrderMode(),wbsDepth:this._viewAttributes.getWbsDepth()}),this._cache.visualRows}hydrateViewState(e){this._viewState.hydrate(e),this._filterProjection=null,this.invalidateDerivedOrder()}_captureViewStateOnce(){this._writeCapture.peek()!==null&&this._viewStateBefore===null&&(this._viewStateBefore=this._viewState.snapshot())}getOutgoingLinkIds(e){return this._outgoing.get(String(e))??bI}getIncomingLinkIds(e){return this._incoming.get(String(e))??bI}getChildren(e){return this._hierarchy.getChildren(e)}hasChildren(e){return this._hierarchy.hasChildren(e)}isChildOf(e,n){return this._hierarchy.isChildOf(e,n)}getParent(e){return this._hierarchy.getParent(e)}getRootIds(){return this._hierarchy.getRootIds()}getClosestWorkTime(e){return this._calendar.getClosestWorkTime(e)}isWorkTime(e){return this._calendar.isWorkTime(e)}calculateEndDate(e){return this._calendar.calculateEndDate(e)}calculateDuration(e){return this._calendar.calculateDuration(e)}clearCalendarCache(){this._calendar.clearCache()}get calendarReader(){return this._calendar.reader}batchUpdate(e){e()}updateActivity(e){this._noteSchedulingField(e,O.START_DATE,null),this._noteSchedulingField(e,O.END_DATE,null)}getLiveActivity(e){return this.getActivity(e)}getFlags(){return{...this._flags,allCheckedTaskIds:this._viewState.checkedIds()}}getProjectEnd(){return null}isScheduleSettled(){return this._scheduleSettled}markScheduleSettled(){this._writeCapture.peek()===null?this._scheduleSettled=!0:this._settledByPassInCapture=!0}openSchedulingWriteLog(e,n){let r=new kl(e,n,()=>this._hierarchy.settle());return this._schedulingWriteLogs.push(r),r}_noteSchedulingStructure(){for(let e of this._schedulingWriteLogs)e.markStructural()}_noteSchedulingReshape(e){if(e!==null)for(let n of this._schedulingWriteLogs)n.reshape(String(e))}_noteSchedulingLinks(){for(let e of this._schedulingWriteLogs)e.changeLinks()}_noteSchedulingField(e,n,r){if(this._schedulingWriteLogs.length!==0){if(n===O.PARENT||n===O.TYPE){this._noteSchedulingReshape(e),n===O.PARENT&&this._noteSchedulingReshape(r);return}for(let i of this._schedulingWriteLogs)i.touch(String(e),n)}}_noteSchedulingLinkField(e){(e===Vt.LAG||e===Vt.TYPE)&&this._noteSchedulingLinks()}beginWriteCapture(){this._writeCapture.begin(),this._settledByPassInCapture=!1,this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=null,this._missingSchedulingStateCountBefore=this._missingSchedulingStateCount,this._dataDateBefore=null}peekWriteCapture(){return this._writeCapture.peek()}endWriteCapture(){let e=this._writeCapture.peek();this._settledByPassInCapture?this._scheduleSettled=!0:e!==null&&DI(e,n=>this.getActivity(n),n=>this.getLink(n))&&(this._scheduleSettled=!1),this._settledByPassInCapture=!1,this._writeCapture.end(),this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=null,this._missingSchedulingStateCountBefore=null,this._dataDateBefore=null}setActivityField(e,n,r){let i=this.getActivity(e);if(!i)return;let a=Zn(i);this._writeCapture.note(String(e),i);let o=i.parentId;i[n]=r,this._noteSchedulingField(e,n,o),this._updateSchedulingStateCount(a,i),Ru(i,n),n===O.PARENT&&this._hierarchy.markDirty(),Eu(n)&&(this._cache.visualOrderIds=null)}setActivityFieldDynamic(e,n,r){let i=this.getActivity(e);if(!i)return;if(!Object.hasOwn(i,n))throw new Error(`setActivityFieldDynamic: unknown CoreActivity field "${n}"`);let a=Zn(i);this._writeCapture.note(String(e),i);let o=i.parentId;Reflect.set(i,n,QA(n,r)),this._noteSchedulingField(e,n,o),this._updateSchedulingStateCount(a,i),Ru(i,n),n===O.PARENT&&this._hierarchy.markDirty(),Eu(n)&&(this._cache.visualOrderIds=null)}setActivityFields(e,n){let r=this.getActivity(e);if(!r)return;let i=Zn(r);this._writeCapture.note(String(e),r);let a=!1;for(let o of Object.keys(n)){let s=r.parentId;Reflect.set(r,o,Reflect.get(n,o)),this._noteSchedulingField(e,o,s),Ru(r,o),o===O.PARENT&&(a=!0),Eu(o)&&(this._cache.visualOrderIds=null)}this._updateSchedulingStateCount(i,r),a&&this._hierarchy.markDirty()}addLink(e){this._writeCapture.noteLinkAdd(String(e.id));let n=this._links.get(String(e.id));if(n)this._noteSchedulingLinks();else for(let i of this._schedulingWriteLogs)i.appendLink(String(e.id));n&&this._deindexLink(n);let r={...e,freeSlackHours:e.freeSlackHours??null,isCritical:e.isCritical===!0};this._links.set(String(e.id),r),this._indexLink(r)}_indexLink(e){LI(this._outgoing,String(e.source),e.id),LI(this._incoming,String(e.target),e.id)}_deindexLink(e){let n=this._outgoing.get(String(e.source));n&&this._outgoing.set(String(e.source),Pu(n,e.id));let r=this._incoming.get(String(e.target));r&&this._incoming.set(String(e.target),Pu(r,e.id))}_removeLinkRef(e,n,r){let i=e.get(n);i&&e.set(n,Pu(i,r))}_insertLinkRefInOrder(e,n,r){let i=new Set;for(let s of this._links.keys()){if(String(s)===String(r))break;i.add(String(s))}let a=[...e.get(n)??[]],o=a.findIndex(s=>!i.has(String(s)));a.splice(o<0?a.length:o,0,r),e.set(n,a)}setLinkField(e,n,r){let i=this.getLink(e);i&&(this._writeCapture.noteLinkField(String(e),i),i[n]=r,this._noteSchedulingLinkField(n))}setLinkEndpoints(e,n,r){let i=this.getLink(e);if(!i)return;let a=String(i.source)!==String(n),o=String(i.target)!==String(r);!a&&!o||(this._writeCapture.noteLinkField(String(e),i),this._noteSchedulingLinks(),a&&(this._removeLinkRef(this._outgoing,String(i.source),i.id),i.source=n,this._insertLinkRefInOrder(this._outgoing,String(n),i.id)),o&&(this._removeLinkRef(this._incoming,String(i.target),i.id),i.target=r,this._insertLinkRefInOrder(this._incoming,String(r),i.id)))}setLinkFieldDynamic(e,n,r){let i=this.getLink(e);if(i){if(n===Vt.SOURCE){this.setLinkEndpoints(e,String(r),i.target);return}if(n===Vt.TARGET){this.setLinkEndpoints(e,i.source,String(r));return}RF(n)&&(this._writeCapture.noteLinkField(String(e),i),Reflect.set(i,n,r),this._noteSchedulingLinkField(n))}}setLinkProplannerId(e,n){let r=this.getLink(e);r&&(this._writeCapture.noteLinkField(String(e),r),r.proplannerId=n)}removeLink(e){let n=this.getLink(e);if(n){this._writeCapture.noteLinkRemove(String(e),n);for(let r of this._schedulingWriteLogs)r.removeLink(String(e));this._links.delete(String(e)),this._deindexLink(n)}}addActivity(e){this._writeCapture.noteInsert(String(e.id)),this._noteSchedulingReshape(e.id);let n=this._activities.get(e.id);n&&Zn(n)&&(this._missingSchedulingStateCount-=1),this._activities.set(e.id,e),Zn(e)&&(this._missingSchedulingStateCount+=1),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.addChild(e.parentId,e.id)}removeActivity(e){let n=this.getActivity(e);n&&this._writeCapture.noteRemove(String(e),n),this._noteSchedulingReshape(e),this._noteSchedulingReshape(n?.parentId??null),n&&Zn(n)&&(this._missingSchedulingStateCount-=1);let r=String(e);this.setProgressFallback(r,null),(this._viewState.isChecked(r)||!this._viewState.isVisible(r))&&this._captureViewStateOnce(),this._viewState.forget(r),this._activities.delete(e),this._lastStartDate.has(String(e))&&(this._captureLastStartDateOnce(),this._lastStartDate.delete(String(e))),this._outgoing.delete(String(e)),this._incoming.delete(String(e)),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}noteCorrelativeBefore(e,n){this._writeCapture.noteCorrelativeBefore(e,n)}noteScheduledBefore(e,n){this._writeCapture.noteScheduledBefore(e,n)}restoreFromCapture(){let e=this._writeCapture.peek();if(!e)return;this._noteSchedulingStructure();let{ops:n,before:r,correlativeBefore:i,scheduledBefore:a,progressFallbackBefore:o}=e;this._undoLinkAdds(n),this._undoInserts(n),this._reInsertRemovedActivities(n),this._reAddRemovedLinks(n),this._restoreLinkFields(n),this._restoreActivityFields(a),this._restoreActivityFields(r),this._restoreCorrelatives(i),this._restoreProgressFallbacks(o),this._missingSchedulingStateCountBefore!==null&&(this._missingSchedulingStateCount=this._missingSchedulingStateCountBefore),this._dataDateBefore!==null&&(this._dataDate=this._dataDateBefore),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(e){for(let[n,r]of e)r===null?this._progressFallback.delete(n):this._progressFallback.set(n,r)}_restoreCorrelatives(e){for(let[n,r]of e){let i=this._activities.get(n);i&&(i.correlativeId=r)}}_undoLinkAdds(e){for(let n of e)n.kind===Tt.LINK_ADD&&this._detachLink(n.linkId)}_undoInserts(e){for(let n of e)n.kind===Tt.INSERT&&this._activities.delete(n.activityId)}_reInsertRemovedActivities(e){for(let n of e)n.kind===Tt.REMOVE&&this._activities.set(n.activityId,n.before)}_reAddRemovedLinks(e){for(let n of e)n.kind===Tt.LINK_REMOVE&&this._attachLink(n.before)}_restoreLinkFields(e){for(let n of e){if(n.kind!==Tt.LINK_FIELD)continue;let r=this._links.get(n.linkId);if(r){this.setLinkEndpoints(n.linkId,n.before.source,n.before.target);for(let i of Object.keys(r))Object.hasOwn(n.before,i)||Reflect.deleteProperty(r,i);Object.assign(r,n.before)}}}_restoreActivityFields(e){for(let[n,r]of e){let i=this._activities.get(n);i&&this._restoreScalarFields(i,r)}}_restoreScalarFields(e,n){for(let r of Object.keys(e))Object.hasOwn(n,r)||Reflect.deleteProperty(e,r);for(let r of Object.keys(n))Reflect.set(e,r,Reflect.get(n,r))}_updateSchedulingStateCount(e,n){let r=Zn(n);e!==r&&(this._missingSchedulingStateCount+=r?1:-1)}_attachLink(e){this._links.set(String(e.id),{...e}),this._indexLink(e)}_detachLink(e){let n=this.getLink(e);n&&(this._links.delete(String(e)),this._deindexLink(n))}},bI=[];function RF(t){return t===Vt.LAG||t===Vt.TYPE||t===Vt.FREE_SLACK_HOURS||t===Vt.IS_CRITICAL}function Eu(t){return t===O.PARENT||t===O.CORRELATIVE_ID}function Zn(t){return t.type!==U.PROJECT&&t.p6===void 0}function Ru(t,e){e!==O.START_DATE&&e!==O.END_DATE&&e!==O.TYPE||(t.calendarDuration=Ge(t))}function Pu(t,e){return t.filter(n=>String(n)!==String(e))}function LI(t,e,n){let r=t.get(e);r?r.push(n):t.set(e,[n])}function PF(t){let e=t.runtimeFlags??{};return{isPasting:!!e.isPasting,isBulkOperation:!!e.isBulkOperation,dragWithMultiple:!!e.dragWithMultiple,draggingSingleMilestone:!!e.draggingSingleMilestone,creatingActivity:!1,avoidAutoScheduleBeforeDrag:!1,maxPerformance:!!e.maxPerformance,allCheckedTaskIds:[]}}function OI(t){if(t.p6===void 0)return t;let e=t.p6,n={...e,activityType:e.activityType??ne.TASK,durationType:e.durationType??Re.FIXED_DURATION_AND_UNITS,primaryConstraintType:e.primaryConstraintType??null,primaryConstraintDate:e.primaryConstraintDate??null,sourcePrimaryConstraintToken:e.sourcePrimaryConstraintToken??null,sourceSecondaryConstraintToken:Reflect.get(e,"sourceSecondaryConstraintToken")??null,resourceAssignments:e.resourceAssignments??[]};return delete n.sourceActivityTypeToken,delete n.sourceDurationTypeToken,{...t,p6:n}}function ku(t){if(!t.hasCompleteSchedulingState)return{};let e=Ei(t.activity);return e===void 0?{}:{p6:e}}function NI(t){return{activityPatch:t.p6===void 0?{}:{p6:void 0},snapshotPatch:t.p6===void 0?{}:{p6:v(t.p6)}}}function FI(t){let e=t.promotionSnapshot?.p6;return e===void 0?ku(t):{p6:v(e)}}function xI(t,e){let n=e==="before";return{...t.p6Settings===void 0?{}:{p6Settings:n?wI(t.p6Settings):v(t.p6Settings)},...t.p6ProjectPlannedStart===void 0?{}:{p6ProjectPlannedStart:n?wI(t.p6ProjectPlannedStart):v(t.p6ProjectPlannedStart)}}}function MI(t,e,n){t.p6Settings!==void 0&&n.setSettings(v(t.p6Settings[e])),t.p6ProjectPlannedStart!==void 0&&n.setProjectPlannedStart(v(t.p6ProjectPlannedStart[e]))}function UI(t){return t.p6Settings!==void 0||t.p6ProjectPlannedStart!==void 0}function wI(t){return{before:v(t.after),after:v(t.before)}}function qi(t){if(t===void 0)return["undefined"];if(t===null)return["null"];if(typeof t=="string")return["string",t];if(typeof t=="boolean")return["boolean",t];if(typeof t=="number")return["number",Object.is(t,-0)?"-0":String(t)];if(typeof t=="bigint")return["bigint",String(t)];if(t instanceof Date)return["date",String(t.getTime())];if(Array.isArray(t))return["array",t.map(qi)];if(t instanceof Map)return["map",Array.from(t,([e,n])=>[qi(e),qi(n)]).sort((e,n)=>JSON.stringify(e).localeCompare(JSON.stringify(n)))];if(t instanceof Set)return["set",Array.from(t,qi).sort((e,n)=>JSON.stringify(e).localeCompare(JSON.stringify(n)))];if(typeof t=="object")return["object",Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,qi(n)])];throw new TypeError(`Unsupported canonical value: ${typeof t}`)}function $t(t){return JSON.stringify(qi(t))}var Fl=t=>(t>>>0).toString(16).padStart(8,"0");function bu(t){let e=1779033703,n=3144134277,r=1013904242,i=2773480762;for(let a=0;a<t.length;a+=1){let o=t.charCodeAt(a);e=n^Math.imul(e^o,597399067),n=r^Math.imul(n^o,2869860233),r=i^Math.imul(r^o,951274213),i=e^Math.imul(i^o,2716044179)}return e=Math.imul(r^e>>>18,597399067),n=Math.imul(i^n>>>22,2869860233),r=Math.imul(e^r>>>17,951274213),i=Math.imul(n^i>>>19,2716044179),`${Fl(e^n^r^i)}${Fl(n^e)}${Fl(r^e)}${Fl(i^e)}`}function HI(t,e){return{p6Settings:v(t),p6ProjectState:v(e)}}function Qn(t,e){return $t(t)!==$t(e)}function BI(t,e){t.clear();for(let n of e)n.p6!==void 0&&t.set(String(n.id),v(n.p6))}function jI(t,e){let n=e?.p6;return t===void 0&&n===void 0?!1:Qn(t,n)}function VI(t,e){let n=new Map;for(let r of t){let i=e(r)?.p6;i!==void 0&&n.set(r,v(i))}return n}function KI(t,e){let n=e.projectState?.plannedStart??null,r=t.projectState?.plannedStart??null;return{...WI(e.settings,t.settings)?{p6Settings:{before:v(e.settings),after:v(t.settings)}}:{},...WI(n,r)?{p6ProjectPlannedStart:{before:v(n),after:v(r)}}:{}}}function WI(t,e){return $t(t)!==$t(e)}var YI="Invalid P6 activity status",Lu=class extends Error{constructor(n,r){super(`${YI}: ${r}`);this.code=n;this.name="P6ActivityStatusError"}code},kF=100,bF=0;function GI(t){qI(t.remainingDurationHours),$I(t),OF(t),zI(t)}function ro(t){LF(t.remainingDurationHours),$I(t),NF(t),zI(t)}function wl(t,e){if(e.actualStart===void 0&&e.actualFinish===void 0)return e;let n=e.actualStart!==void 0?e.actualStart:t.actualStart,r=e.actualFinish!==void 0?e.actualFinish:t.actualFinish,i=r!==null?"completed":n!==null?"in_progress":"not_started",a=n===null&&r===null&&t.actualStart!==null,o={...e,executionStatus:i,...r!==null?{remainingDurationHours:0,physicalPercentComplete:kF}:{},...a?{remainingDurationHours:t.originalDurationHours,physicalPercentComplete:bF}:{}};return ro({...t,...o}),o}function qI(t){(!Number.isFinite(t)||t<0)&&pe("Remaining Duration must be finite and non-negative")}function LF(t){t!==null&&qI(t)}function $I(t){[t.actualStart,t.actualFinish,t.suspendDate,t.resumeDate].some(n=>n!==null&&Number.isNaN(n.getTime()))&&pe("actual, suspend and resume dates must be valid")}function OF(t){let e=t.actualStart!==null,n=t.actualFinish!==null;if(t.executionStatus==="not_started"){(e||n)&&pe("not_started cannot have actual dates");return}if(t.executionStatus==="in_progress"){(!e||n)&&pe("in_progress requires Actual Start and no Actual Finish");return}(!e||!n||t.remainingDurationHours!==0)&&pe("completed requires Actual Start, Actual Finish and zero Remaining Duration")}function NF(t){let e=t.actualStart!==null,n=t.actualFinish!==null;n&&!e&&pe("Actual Finish requires Actual Start"),t.executionStatus==="not_started"&&e&&pe("not_started cannot have actual dates"),t.executionStatus==="in_progress"&&n&&pe("in_progress cannot have Actual Finish"),t.executionStatus==="completed"&&t.remainingDurationHours!==null&&t.remainingDurationHours!==0&&pe("completed requires zero Remaining Duration")}function zI(t){let{actualStart:e,actualFinish:n,suspendDate:r,resumeDate:i}=t;if(e!==null&&n!==null&&e.getTime()>n.getTime())throw new Lu("ACTUAL_FINISH_BEFORE_START","Actual Start must not be after Actual Finish");r!==null&&(e===null&&pe("Suspend requires Actual Start"),e.getTime()>r.getTime()&&pe("Suspend must not be before Actual Start"),n!==null&&r.getTime()>n.getTime()&&pe("Suspend must not be after Actual Finish")),i!==null&&(r===null&&pe("Resume requires Suspend"),r.getTime()>i.getTime()&&pe("Suspend must not be after Resume"),n!==null&&i.getTime()>n.getTime()&&pe("Resume must not be after Actual Finish"))}function pe(t){throw new Error(`${YI}: ${t}`)}var Ou="Invalid P6 derived input",Fu=100,io=0,$i=100,FF=16,wF=8,xF="178",wu=Date.parse("2026-10-07T12:00:00.000Z"),MF=Date.parse("2026-10-08T12:00:00.000Z"),UF=Date.parse("2026-10-12T12:00:00.000Z"),HF=Date.parse("2026-10-06T08:00:00.000Z"),BF=wu,jF=wu,VF=Date.parse("2026-10-08T12:00:00.000Z"),WF=Date.parse("2026-10-05T08:00:00.000Z"),KF=Date.parse("2026-10-06T08:00:00.000Z");function ao(t,e){return GI(t),YF(t,e.dataDate),{actualDurationHours:XI(t,e),atCompletionDurationHours:GF(t,e),durationPercentComplete:qF(t),unitsPercentComplete:$F(t,e),schedulePercentComplete:xu(t,e),remainingFloatHours:XF(t,e.calendar,e.totalFloatMethod??"finish_float")}}function JI(t,e){return XI(t,e)}function YF(t,e){let n=[t.originalDurationHours,t.remainingDurationHours],r=[t.actualLaborUnits,t.remainingLaborUnits,t.actualNonlaborUnits,t.remainingNonlaborUnits];if(n.some(i=>!Number.isFinite(i)||i<0))throw new Error(`${Ou}: expected finite non-negative durations`);if(r.some(i=>!Number.isFinite(i)))throw new Error(`${Ou}: expected finite unit scalars`);if(Number.isNaN(e.getTime()))throw new Error(`${Ou}: invalid Data Date`)}function XI(t,e){if(t.executionStatus==="not_started"||t.actualStart===null)return 0;let n=t.executionStatus==="completed"?t.actualFinish:e.dataDate;return n===null?0:Nu(e.calendar,t.actualStart,n)}function GF(t,e){return t.executionStatus==="not_started"?ZF(e.calendar,t.plannedStart,t.plannedFinish):t.executionStatus==="in_progress"?t.actualStart===null||t.remainingEarlyFinish===null?0:Nu(e.calendar,t.actualStart,t.remainingEarlyFinish):t.actualStart===null||t.actualFinish===null?0:Nu(e.calendar,t.actualStart,t.actualFinish)}function Nu(t,e,n){return e.getTime()>=n.getTime()?0:zi(t,e,n)}function qF(t){return t.originalDurationHours===0?0:ZI((t.originalDurationHours-t.remainingDurationHours)/t.originalDurationHours*Fu)}function $F(t,e){let n=t.actualLaborUnits+t.actualNonlaborUnits,r=t.remainingLaborUnits+t.remainingNonlaborUnits,i=n+r;return i===0?zF(t,e)?$i:io:n/i*Fu}function zF(t,e){return t.executionStatus!==et.COMPLETED||t.actualStart===null||t.actualFinish===null||t.remainingDurationHours!==0||t.percentCompleteType!==Nt.DURATION||e.dataDate.getTime()!==wu||e.calendarId!==xF||!JF(t)?!1:t.activityType===ne.TASK?t.durationType===Re.FIXED_DURATION_AND_UNITS&&t.originalDurationHours===wF&&t.physicalPercentComplete===$i&&tr(t.plannedStart,jF)&&tr(t.plannedFinish,VF)&&tr(t.actualStart,WF)&&tr(t.actualFinish,KF):t.activityType===ne.LEVEL_OF_EFFORT&&t.durationType===Re.FIXED_DURATION_AND_UNITS_PER_TIME&&t.originalDurationHours===FF&&t.physicalPercentComplete===$i&&tr(t.plannedStart,MF)&&tr(t.plannedFinish,UF)&&tr(t.actualStart,HF)&&tr(t.actualFinish,BF)}function JF(t){return t.expectedFinish===null&&t.suspendDate===null&&t.resumeDate===null&&t.secondaryConstraintType===null&&t.secondaryConstraintDate===null&&t.primaryBaselineStart===null&&t.primaryBaselineFinish===null&&(t.resourceAssignments?.length??0)===0}function tr(t,e){return t?.getTime()===e}function xu(t,e){let n=t.primaryBaselineStart!==null,r=t.primaryBaselineFinish!==null;if(n!==r)return null;let i=t.primaryBaselineStart??t.plannedStart,a=t.primaryBaselineFinish??t.plannedFinish;if(i===null||a===null)return null;if(i.getTime()===a.getTime())return e.dataDate.getTime()<i.getTime()?io:$i;if(e.dataDate.getTime()<=i.getTime())return io;if(e.dataDate.getTime()>=a.getTime())return $i;let o=zi(e.calendar,i,a);if(o<=0)return io;let s=zi(e.calendar,i,e.dataDate);return ZI(s/o*Fu)}function XF(t,e,n){if(t.remainingEarlyFinish===null||t.lateFinish===null)return null;let r=zi(e,t.remainingEarlyFinish,t.lateFinish);if(n==="finish_float")return Object.is(r,-0)?0:r;if(t.remainingEarlyStart===null||t.lateStart===null)return null;let i=zi(e,t.remainingEarlyStart,t.lateStart),a=n==="start_float"?i:Math.min(i,r);return Object.is(a,-0)?0:a}function ZF(t,e,n){return e===null||n===null?0:zi(t,e,n)}function zi(t,e,n){if(e.getTime()<=n.getTime())return t.calculateDuration(e,n);let r=-t.calculateDuration(n,e);return Object.is(r,-0)?0:r}function ZI(t){return Math.min($i,Math.max(io,t))}var QF=new Set([ne.TASK,ne.RESOURCE_DEPENDENT]),tw=new Map;function xl(t){if(!(t.settings.useExpectedFinishDates&&ew(t.previousSettings,t.settings)))return tw;let n=new Map;for(let[r,i]of t.activities){let a=i.remainingEarlyFinish;a!==null&&nw(i)&&n.set(r,new Date(a))}return n}function ew(t,e){let n=t.dataDate,r=e.dataDate;return n===null||r===null?!1:r.getTime()>n.getTime()}function nw(t){return t.executionStatus===et.IN_PROGRESS&&t.expectedFinish===null&&rw(t)}function rw(t){let{activityType:e}=t;return e===void 0?!0:QF.has(e)}function Ml(t,e){return{freeSlackHours:t.freeFloatHours,criticalPath:{earlyStart:v(t.earlyStart),earlyFinish:v(t.earlyFinish),lateStart:v(t.lateStart),lateFinish:v(t.lateFinish),totalSlackHours:t.remainingFloatHours},isCritical:e.criticalActivityMethod===vr.LONGEST_PATH?t.longestPath:t.remainingFloatHours!==null&&t.remainingFloatHours<=e.criticalFloatThresholdHours}}function QI(t){let e=new Set(t.criticalPath);return new Map([...t.activities].map(([n,r])=>{let i=r.actualStart??r.remainingEarlyStart,a=r.actualFinish??r.remainingEarlyFinish;return[n,{p6:v(r),...i===null?{}:{startDate:v(i)},...a===null?{}:{endDate:v(a)},isCritical:e.has(n),freeSlackHours:r.freeFloatHours,criticalPath:{earlyStart:v(r.earlyStart),earlyFinish:v(r.earlyFinish),lateStart:v(r.lateStart),lateFinish:v(r.lateFinish),totalSlackHours:r.remainingFloatHours}}]}))}function tS(t,e,n,r={}){if(!ow(e.dataDate,n.dataDate))return new Map;if(!At(n,r.enabled))return new Map;let i=!At(e,r.enabled),a=t.getAllActivities(),o=iw(a,e,n,r.adoptExpectedFinish),s=new Map;for(let l of a){let c=l.p6;if(c===void 0)continue;let d=t.calendarReader.getCalendar(l.calendarId);if(d===null)throw new Error(`Missing calendar for Data Date activity ${l.id}`);let u=aw(c,n.dataDate,d,o.get(l.id)),p=!Object.is(u.expectedFinish,c.expectedFinish)||!Object.is(u.schedulePercentComplete,c.schedulePercentComplete)||!Object.is(u.actualDurationHours,c.actualDurationHours);!i&&!p||s.set(l.id,{...p?{p6:u}:{},...i?Ml(u,n):{}})}return s}function iw(t,e,n,r=!1){if(!r)return new Map;if(n.setDataDateAndPlannedStartToForecastStart&&n.projectForecastStart!==null)return new Map;let a=new Map(t.flatMap(o=>{let s=o.p6,l=s!==void 0&&ln(s);return o.type===U.PROJECT||!l?[]:[[o.id,s]]}));return xl({previousSettings:e,settings:n,activities:a})}function eS(t,e){for(let[n,r]of e)t.setActivityFields(n,r)}function aw(t,e,n,r){let i={dataDate:e,calendar:n},a=xu(t,i),o=ln(t)&&t.executionStatus===et.IN_PROGRESS;return{...t,expectedFinish:r??t.expectedFinish,schedulePercentComplete:a,...o?{actualDurationHours:JI(t,i)}:{}}}function ow(t,e){return t?.getTime()!==e?.getTime()}var sw=["remainingDurationHours","originalDurationHours","actualStart","actualFinish","suspendDate","resumeDate"];function Hl(t,e,n){if(!lw(t,e))return{p6:{...e}};if(!ln(e))return{p6:{...e},...nS(t,e),...rS(t,e,null)};let r=cw(e,n.calendar),i=ao(r===null?e:{...e,remainingEarlyFinish:r},{dataDate:n.dataDate,calendar:n.calendar,...n.totalFloatMethod===void 0?{}:{totalFloatMethod:n.totalFloatMethod}});return{p6:{...e,...i,remainingFloatHours:e.remainingFloatHours},...nS(t,e),...rS(t,e,r)}}function lw(t,e){return sw.some(n=>!Ul(t[n],e[n]))}function cw(t,e){return t.executionStatus==="completed"||t.remainingEarlyStart===null?null:e.calculateEndDate(t.remainingEarlyStart,t.remainingDurationHours)}function nS(t,e){if(Ul(t.actualStart,e.actualStart))return{};let n=e.actualStart??e.remainingEarlyStart;return n===null?{}:{startDate:v(n)}}function rS(t,e,n){if(!(!Ul(t.remainingDurationHours,e.remainingDurationHours)||!Ul(t.actualFinish,e.actualFinish)))return{};let i=e.actualFinish??n??e.remainingEarlyFinish;return i===null?{}:{endDate:v(i)}}function Ul(t,e){return t instanceof Date||e instanceof Date?t instanceof Date&&e instanceof Date&&t.getTime()===e.getTime():Object.is(t,e)}var Ce=class extends Error{constructor(n,r,i=[],a=0,o=[]){super(r);this.code=n;this.relationshipIds=i;this.count=a;this.sampleActivityIds=o;this.name="P6CapabilityError"}code;relationshipIds;count;sampleActivityIds};function iS(t){return Object.freeze({getSettings:t.getSettings,getProjectState:t.getProjectState,getLatestRunLog:t.getLatestRunLog,getScheduleStateFingerprint:t.getScheduleStateFingerprint,getDefaultSettings:t.getDefaultSettings,getScheduleReadiness:t.getScheduleReadiness,searchEndingActivities:t.searchEndingActivities,getEndingActivityOption:t.getEndingActivityOption,resolveMustFinishByDefault:t.resolveMustFinishByDefault,updateSettings:t.updateSettings,updateActivity:t.updateActivity,schedule:t.schedule})}function Bl(t){return t.outOfSequencePolicy!=="progress_override"||t.successorExecution!=="in_progress"?!0:t.linkType==="2"||t.linkType==="3"}function gn(t){return t.actualFinish!==null?{execution:"completed",hasRemaining:!1}:t.actualStart!==null?{execution:"in_progress",hasRemaining:!0}:{execution:"not_started",hasRemaining:!0}}function oo(t){return t.outOfSequencePolicy==="retained_logic"&&t.linkType==="1"&&t.actualStart!==null}function Uu(t,e,n){let r=oS(e);if(r.length===0)return null;let i=r.map(a=>{let o=sS(e,a),s=t.getClosestWorkTime({date:n,dir:"future",task:o}),l=t.calculateEndDate({startDate:s,durationHours:Mu(a),task:o});return{start:s,finish:l}});return lS(i)}function aS(t,e,n){let r=oS(e);if(r.length===0)return null;let i=r.map(a=>{let o=sS(e,a),s=t.getClosestWorkTime({date:n,dir:"past",task:o}),l=t.calculateEndDate({startDate:s,durationHours:-Mu(a),task:o}),c=t.calculateEndDate({startDate:l,durationHours:Mu(a),task:o});return{start:l,finish:c}});return lS(i)}function oS(t){if(t.p6?.activityType!=="resource_dependent")return[];let e=t.p6.resourceAssignments??[];for(let n of e)dw(n);return e}function dw(t){for(let e of[t.actualUnits,t.remainingUnits,t.unitsPerHour])if(!Number.isFinite(e)||e<0)throw new Error(`Invalid P6 resource assignment ${t.id}`);if(t.remainingUnits>0&&t.unitsPerHour<=0)throw new Error(`Invalid P6 resource assignment rate ${t.id}`)}function Mu(t){let e=t.remainingUnits===0?0:t.remainingUnits/t.unitsPerHour;return uw(e)}function uw(t){let e=Math.round(t),n=Number.EPSILON*Math.max(1,Math.abs(t))*32;return Math.abs(t-e)<=n?e:t}function sS(t,e){return{...t,calendarId:e.calendarId}}function lS(t){let e=new Date(Math.min(...t.map(r=>r.start.getTime()))),n=new Date(Math.max(...t.map(r=>r.finish.getTime())));return{start:e,finish:n}}var pw=4;function jl(t){let e=yw(t);if(e!==null)return e;let n=fw(t);if(n!==null)return n;let r=hw(t);if(r!==null)return r;let i=mw(t);if(i!==null)return i;if(t.link.type===G.START_TO_FINISH&&Br(t.link)&&t.successor.p6?.activityType==="finish_milestone")return gw(t);let a=ha(t.predecessor,t.successor,t.link,t.adapter,t.lagTask).successorStart;return!vw(t)||a.getTime()===t.predecessor.endDate.getTime()?a:t.adapter.getClosestWorkTime({date:t.predecessor.endDate,dir:"future",task:t.successor})}function yw(t){let e=t.link._trueLag??t.link.lag??0;if(t.link.type!==G.FINISH_TO_FINISH||!Br(t.link)||t.successor.durationHours===0||t.lagTask!==null||e<=0)return null;let n=Ln(t.predecessor.endDate,e);return t.adapter.calculateEndDate({startDate:n,durationHours:-t.successor.durationHours,task:t.successor})}function fw(t){let e=t.link._trueLag??t.link.lag??0;return t.link.type!==G.START_TO_START||!Br(t.link)||t.successor.p6?.activityType!=="finish_milestone"||t.successor.durationHours!==0||t.lagTask!==null||e===0?null:t.adapter.getClosestWorkTime({date:Ln(t.predecessor.startDate,e),dir:"future",task:t.successor})}function hw(t){let e=(t.link._trueLag??t.link.lag??0)===0;if(t.link.type!==G.FINISH_TO_START||t.predecessor.p6?.activityType!=="resource_dependent"||t.successor.p6?.activityType!=="level_of_effort"||t.successor.durationHours!==0||!e)return null;let n=fa(t.predecessor.endDate),r=t.adapter.getClosestWorkTime({date:n,dir:"future",task:t.successor});return r.getTime()===n.getTime()?t.predecessor.endDate:r}function mw(t){let e=t.link._trueLag??t.link.lag??0;return!(t.link.type===G.FINISH_TO_START||t.link.type===G.FINISH_TO_FINISH)||!Br(t.link)||t.successor.p6?.activityType!=="finish_milestone"||e>=0||t.lagTask!==null?null:t.adapter.getClosestWorkTime({date:Ln(t.predecessor.endDate,e),dir:"future",task:t.successor})}function gw(t){let e=t.link._trueLag??t.link.lag??0,n=t.lagTask===null?Ln(t.predecessor.startDate,e):t.adapter.calculateEndDate({startDate:t.predecessor.startDate,durationHours:e,task:t.lagTask});return t.adapter.getClosestWorkTime({date:n,dir:"future",task:t.successor})}function so(t){let e=Aw(t);if(e!==null)return e;let n=Iw(t);if(n!==null)return n;let r=t.link.type===G.FINISH_TO_FINISH&&Br(t.link)&&t.lagTask!==null&&t.lagTask.id!==t.successor.id?Sw(t):zo(t.successor,t.predecessor,t.link,t.adapter,t.lagTask);return Cw(t)?Dw(r,t.lagTask,t.adapter):r}function Aw(t){let e=t.link._trueLag??t.link.lag??0;if(t.link.type!==G.START_TO_FINISH||!Br(t.link)||t.lagTask!==null||e<=0)return null;let n=Ln(t.successor.endDate,-e);return t.adapter.calculateEndDate({startDate:n,durationHours:t.predecessor.durationHours,task:t.predecessor})}function Iw(t){let e=t.link._trueLag??t.link.lag??0,n=t.adapter.isWorkTime?.({date:t.successor.startDate,task:t.predecessor});return t.link.type!==G.FINISH_TO_START||!Br(t.link)||t.predecessor.p6?.activityType!=="finish_milestone"||e!==0||t.lagTask!==null||n!==!1?null:t.adapter.getClosestWorkTime({date:t.successor.startDate,dir:"past",task:t.predecessor})}function Br(t){return t._sourceLag===void 0&&t._targetLag===void 0}function Sw(t){let e=t.link._trueLag??t.link.lag??0;if(t.lagTask===null)return Ln(t.successor.endDate,-e);let n=t.adapter.getClosestWorkTime({date:t.successor.endDate,dir:"past",task:t.lagTask});return t.adapter.calculateEndDate({startDate:n,durationHours:-e,task:t.lagTask})}function vw(t){let e=t.link.type===G.FINISH_TO_START||t.link.type===G.FINISH_TO_FINISH,n=(t.link.lag??0)===0&&(t.link._sourceLag??0)===0&&(t.link._targetLag??0)===0;return t.successor.durationHours===0&&e&&n}function Cw(t){return t.link.type===G.FINISH_TO_FINISH&&(t.link._trueLag??t.link.lag??0)>0&&t.lagTask!==null}function Dw(t,e,n){if(e===null)return t;let r=fa(t),i=n.getClosestWorkTime({date:r,dir:"future",task:e}),a=Iy(r,i);return i.getTime()>r.getTime()&&a<=pw?i:t}function dS(t){let e=Fw(t.links),n={...t,projectEarlyFinish:bw(t.activities)};for(let r of[...t.orderedIds].reverse())Tw(r,e.get(r)??[],n)}function Tw(t,e,n){let r=n.adapter.getActivity(t),i=n.activities.get(t);if(!Ow(r)||i===void 0)return;let a=Nw(r,i),o=kw(a,e,n);if(!Rw(i,o))return;let s=Pw(a,o,n.adapter),l={...i,...s};n.activities.set(t,l),_w(a,l,e,n)}function _w(t,e,n,r){let i=cS(t,e);for(let a of n){let o=r.adapter.getActivity(a.target),s=r.activities.get(a.target);if(o?.p6?.activityType!=="level_of_effort"||!s)continue;let l=cS(o,s),c=jl({predecessor:i,successor:l,link:a,adapter:r.adapter,lagTask:r.resolveLagTask(i,l)});s.earlyStart!==null&&c<=s.earlyStart||r.activities.set(a.target,Ew(s,l,c,r.adapter))}}function Ew(t,e,n,r){let i=r.calculateEndDate({startDate:n,durationHours:t.scheduledRemainingDurationHours,task:e});return{...t,remainingEarlyStart:n,remainingEarlyFinish:i,earlyStart:new Date(n),earlyFinish:new Date(i)}}function cS(t,e){return{...t,startDate:e.remainingEarlyStart??e.earlyStart??t.startDate,endDate:e.remainingEarlyFinish??e.earlyFinish??t.endDate,durationHours:e.scheduledRemainingDurationHours}}function Rw(t,e){return e!==null&&t.remainingEarlyFinish!==null&&e>t.remainingEarlyFinish}function Pw(t,e,n){let r=n.calculateEndDate({startDate:e,durationHours:-t.durationHours,task:t}),i=n.calculateEndDate({startDate:r,durationHours:t.durationHours,task:t});return{remainingEarlyStart:r,remainingEarlyFinish:i,earlyStart:new Date(r),earlyFinish:new Date(i)}}function kw(t,e,n){let r=null;for(let i of e){let a=Lw(i.target,n);if(a===null)continue;let o=so({successor:a,predecessor:t,link:i,adapter:n.adapter,lagTask:n.resolveLagTask(t,a)});(r===null||o<r)&&(r=o)}return r??n.projectEarlyFinish}function bw(t){let e=null;for(let n of t.values()){let r=n.remainingEarlyFinish??n.earlyFinish;r!==null&&(e===null||r>e)&&(e=r)}return e}function Lw(t,e){let n=e.adapter.getActivity(t),r=e.activities.get(t);if(n?.p6===void 0||n.p6.activityType==="level_of_effort"||r===void 0)return null;let i=r.remainingEarlyStart??r.earlyStart,a=r.remainingEarlyFinish??r.earlyFinish;return i===null||a===null?null:{...n,startDate:i,endDate:a,durationHours:r.scheduledRemainingDurationHours}}function Ow(t){return t?.p6?.executionStatus==="not_started"&&t.p6.primaryConstraintType==="alap"}function Nw(t,e){return{...t,durationHours:e.scheduledRemainingDurationHours}}function Fw(t){let e=new Map;for(let n of t){let r=e.get(n.source)??[];r.push(n),e.set(n.source,r)}return e}var er="CS_MSO",Hu="CS_MEO";function An(t){return t?.p6?.primaryConstraintType==="mandatory_start"&&t.p6.sourcePrimaryConstraintToken!==er}function In(t){return t?.p6?.primaryConstraintType==="mandatory_finish"&&t.p6.sourcePrimaryConstraintToken!==Hu}var ww=60*1e3,xw=3600*1e3,Mw=64;function hS(t){let{adapter:e,settings:n}=t;if(n.dataDate===null)throw new Error("P6 forward pass requires Data Date");let r=e.getAllActivities().filter(p=>p.p6!==void 0&&p.p6.activityType!=="wbs_summary").map(p=>p.id),i=new Set(r),a=e.getAllLinks().filter(p=>i.has(p.source)&&i.has(p.target)).filter(p=>{let y=e.getActivity(p.source),f=e.getActivity(p.target);return n.outOfSequencePolicy!=="progress_override"&&Uw(y)?!1:f?.p6!==void 0&&Bl({outOfSequencePolicy:n.outOfSequencePolicy,successorExecution:gn(f.p6).execution,linkType:p.type})}),o=a.filter(p=>{let y=e.getActivity(p.target);return y?.p6!==void 0&&gn(y.p6).execution!=="completed"}),s=bn(r,o);if(s.hasCycles)return{activities:new Map,cycles:s.cycleNodes};let l=$w(a),c=ju(n,e),d=new Map,u=new Set;for(let p of s.ordered){let y=e.getActivity(p);if(y?.p6===void 0)continue;let f=gn(y.p6);if(f.execution==="completed"){let B=n.outOfSequencePolicy==="actual_dates";B&&u.add(p);let $=n.outOfSequencePolicy==="retained_logic"&&y.p6.activityType!=="level_of_effort"?new Date(n.dataDate):null,ft=B?y.p6.actualStart:$,at=B?y.p6.actualFinish:$;d.set(p,{activityId:p,scheduledRemainingDurationHours:0,remainingEarlyStart:null,remainingEarlyFinish:null,earlyStart:fS(ft),earlyFinish:fS(at),drivingLinkId:null});continue}let m=[...l.get(p)??[]].sort((B,$)=>B.source.localeCompare($.source)||B.id.localeCompare($.id)),A=zw(y),g=uS({successor:A,incomingLinks:m,activities:d,settings:n,adapter:e,resolveLagTask:c}),P=yS({activity:A,earliestStart:g.earliestStart,settings:n,adapter:e}),L=0;for(;!Object.is(A.durationHours,P)&&L<Mw;)A={...A,durationHours:P},g=uS({successor:A,incomingLinks:m,activities:d,settings:n,adapter:e,resolveLagTask:c}),P=yS({activity:A,earliestStart:g.earliestStart,settings:n,adapter:e}),L+=1;if(!Object.is(A.durationHours,P))throw new Error(`P6_EXPECTED_FINISH_DID_NOT_SETTLE: ${String(p)}`);let{earliestStart:F,drivingLinkId:T,drivingLinkIds:x}=g,S=Uu(e,A,F),k=f.execution==="in_progress"?{earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null}:Yw(A,e),E=jw({activity:A,bounds:k,settings:n,adapter:e}),j={activityId:p,startDate:S?.start??F,endDate:S?.finish??e.calculateEndDate({startDate:F,durationHours:P,task:A}),drivingLinkId:T,kind:"asap",conflict:!1,earliestStart:E.earliestStart,latestStart:E.latestStart,earliestEnd:E.earliestEnd,latestEnd:E.latestEnd,earliestSchedulingStart:S?.start??F};if(si(A,j,e),S!==null){let B=Uu(e,A,j.startDate);B!==null&&(j.startDate=B.start,j.endDate=B.finish)}let w=j.startDate.getTime()===F.getTime();d.set(p,{activityId:p,scheduledRemainingDurationHours:P,remainingEarlyStart:new Date(j.startDate),remainingEarlyFinish:new Date(j.endDate),earlyStart:new Date(j.startDate),earlyFinish:new Date(j.endDate),drivingLinkId:w?T:null,drivingLinkIds:w?x:[]})}dS({adapter:e,orderedIds:s.ordered,links:a,activities:d,resolveLagTask:c});for(let p of u){let y=d.get(p);d.set(p,{...y,earlyStart:null,earlyFinish:null})}return{activities:d,cycles:[]}}function Uw(t){return t?.p6?.activityType==="level_of_effort"&&t.p6.executionStatus==="not_started"&&t.p6.remainingDurationHours===0}function uS(t){let{successor:e,incomingLinks:n,activities:r,settings:i,adapter:a,resolveLagTask:o}=t,s=a.getClosestWorkTime({date:new Date(i.dataDate),dir:"future",task:e}),l=e.p6?.resumeDate??null;l!==null&&l.getTime()>s.getTime()&&(s=a.getClosestWorkTime({date:new Date(l),dir:"future",task:e}));let c=null,d=[];for(let u of n){let p=a.getActivity(u.source),y=r.get(u.source);if(p?.p6===void 0||y===void 0)continue;let f=y.remainingEarlyStart??y.earlyStart,m=y.remainingEarlyFinish??y.earlyFinish;if(f===null||m===null)continue;let A=Hw({link:u,predecessor:p,predecessorDates:y,successor:e,settings:i}),g=Jw(u,p,y,i),P={...p,startDate:g,endDate:m,durationHours:a.calculateDuration({startDate:g,endDate:m,task:p})},L=A??jl({predecessor:P,successor:e,link:u,adapter:a,lagTask:o(P,e)}),F=u.type==="0"&&e.durationHours===0&&e.type!=="milestone"?Bw(e,L,a):L;F>s?(s=F,c=u.id,d=[u.id]):d.length>0&&F.getTime()===s.getTime()&&d.push(u.id)}return{earliestStart:s,drivingLinkId:c,drivingLinkIds:d}}function mS(t){return t.p6?.activityType==="task"&&t.p6.executionStatus==="not_started"&&t.p6.originalDurationHours===0}function Hw(t){let e=t.settings.outOfSequencePolicy==="retained_logic"&&t.settings.startToStartLagBasis==="early_start"&&t.link.type==="1"&&t.predecessor.p6?.executionStatus==="in_progress"&&t.predecessor.p6?.actualStart!==null&&mS(t.successor),n=t.predecessorDates.remainingEarlyStart??t.predecessorDates.earlyStart;return e&&n!==null?new Date(n):null}function Bw(t,e,n){if(t.p6?.activityType==="level_of_effort")return e;let r=fa(e),i=n.getClosestWorkTime({date:r,dir:"future",task:t});if(!mS(t))return i;let a=new Date(e.getTime()+ww);if(n.isWorkTime?.({date:a,task:t}))return e;if(n.isWorkTime===void 0)return i.getTime()===r.getTime()?e:i;let o=new Date(e.getTime()+xw);return n.getClosestWorkTime({date:o,dir:"future",task:t})}function jw(t){let{activity:e,bounds:n,settings:r,adapter:i}=t,a=An(e);if(Vw(t,a)){let s=Ww(t,a);return{...n,earliestStart:s,latestStart:s}}let o=In(e);if(Kw(t,o)){let s=r.dataDate;if(s===null)return n;let l=o?i.getClosestWorkTime({date:s,dir:"future",task:e}):s;return{...n,earliestStart:l,latestStart:l,latestEnd:null}}return e.constraintType==="mfo"?n:{...n,latestStart:null,latestEnd:null}}function Vw(t,e){let{activity:n,bounds:r,settings:i}=t;return n.p6?.executionStatus!=="not_started"?!1:e?!0:n.constraintType!=="mso"?!1:i.outOfSequencePolicy!=="retained_logic"?!0:r.earliestStart!==null&&i.dataDate!==null&&r.earliestStart>=i.dataDate}function Ww(t,e){let{activity:n,bounds:r,settings:i,adapter:a}=t,o=Bu(r.earliestStart,i.dataDate);return!e||o===null?i.outOfSequencePolicy==="retained_logic"?r.earliestStart:o:a.getClosestWorkTime({date:o,dir:"future",task:n})}function Kw(t,e){let{activity:n,bounds:r,settings:i}=t;return n.p6?.executionStatus!=="not_started"||r.latestStart===null||i.dataDate===null||r.latestStart>=i.dataDate?!1:e||n.constraintType==="mfo"&&i.outOfSequencePolicy==="actual_dates"}function Yw(t,e){let n=Gw(t,e),r=t.p6?.secondaryConstraintType??null,i=t.p6?.secondaryConstraintDate??null;if(r===null||i===null)return n;let a=Tn({...t,constraintType:r,constraintDate:i},e);return qw(n,a)}function Gw(t,e){let n=t.p6?.primaryConstraintType,r=t.p6?.primaryConstraintDate;return n==null||r===null||r===void 0?Tn(t,e):Tn({...t,constraintType:ps(n),constraintDate:r},e)}function qw(t,e){return{earliestStart:Bu(t.earliestStart,e.earliestStart),latestStart:pS(t.latestStart,e.latestStart),earliestEnd:Bu(t.earliestEnd,e.earliestEnd),latestEnd:pS(t.latestEnd,e.latestEnd)}}function Bu(t,e){return t===null?e:e===null||t>e?t:e}function pS(t,e){return t===null?e:e===null||t<e?t:e}function yS(t){let{activity:e,earliestStart:n,settings:r,adapter:i}=t,a=e.p6?.expectedFinish??null;return!r.useExpectedFinishDates||a===null||e.p6===void 0?e.p6?.remainingDurationHours??e.durationHours:a<=n?0:i.calculateDuration({startDate:n,endDate:a,task:e})}function ju(t,e){let n=null,r=()=>{if(n??=e.getAllActivities().find(i=>i.type==="project")??null,n===null)throw new Error("P6 schedule requires a project activity for Project Default relationship lag calendar");return n};switch(t.relationshipLagCalendar){case"predecessor":return i=>i;case"successor":return(i,a)=>a;case"project_default":return()=>r();case"twenty_four_hour":return()=>null}}function $w(t){let e=new Map;for(let n of t){let r=e.get(n.target)??[];r.push(n),e.set(n.target,r)}return e}function zw(t){return t.p6===void 0?t:{...t,durationHours:t.p6.remainingDurationHours}}function Jw(t,e,n,r){return!(t.type==="1"||t.type==="3")||e.p6===void 0?new Date(n.remainingEarlyStart??n.earlyStart??e.startDate):(r.outOfSequencePolicy==="actual_dates"||oo({outOfSequencePolicy:r.outOfSequencePolicy,linkType:t.type,actualStart:e.p6.actualStart})||r.startToStartLagBasis==="actual_start")&&e.p6.actualStart!==null?new Date(e.p6.actualStart):new Date(n.earlyStart??n.remainingEarlyStart??e.startDate)}function fS(t){return t===null?null:new Date(t)}function Xw(t,e){let n=t==="start_float"?e.startFloatHours:t==="finish_float"?e.finishFloatHours:Math.min(e.startFloatHours,e.finishFloatHours);return Object.is(n,-0)?0:n}function SS(t){let{adapter:e,settings:n,forward:r}=t,i=[...r.activities.keys()],a=new Set(i),o=e.getAllLinks().filter(g=>a.has(g.source)&&a.has(g.target)),s=o.filter(g=>{let P=e.getActivity(g.source),L=e.getActivity(g.target);return n.outOfSequencePolicy!=="progress_override"&&Zw(L)||Qw(g,P,L)?!1:L?.p6!==void 0&&Bl({outOfSequencePolicy:n.outOfSequencePolicy,successorExecution:gn(L.p6).execution,linkType:g.type})}),l=s.filter(g=>{let P=e.getActivity(g.source);return!(P?.p6?.activityType==="level_of_effort"&&gn(P.p6).execution==="completed")}),c=bn(i,l);if(c.hasCycles)throw new Error(`P6 backward pass cannot calculate cycles: ${c.cycleNodes.join(", ")}`);let d=cx(e,r,i),u=n.projectMustFinishBy??d;if(u===null)return{activities:rx(i)};let p=d??u,y=gS(s),f=gS(o),m=ju(n,e),A=new Map;for(let g of c.reversed){let P=e.getActivity(g),L=r.activities.get(g);if(P?.p6===void 0||L===void 0)continue;let F=dx(P,L.scheduledRemainingDurationHours??P.p6.remainingDurationHours),T=new Date(u);for(let at of y.get(g)??[]){let St=e.getActivity(at.target),N=A.get(at.target),K=r.activities.get(at.target);if(St?.p6===void 0||N===void 0)continue;let it=lx(St,N,n,at.type);if(it===null)continue;let D={...St,startDate:it.startDate,endDate:it.endDate,durationHours:K?.scheduledRemainingDurationHours??St.p6.remainingDurationHours},b=oo({outOfSequencePolicy:n.outOfSequencePolicy,linkType:at.type,actualStart:P.p6.actualStart})||vS(P,at,n)?{...at,lag:0}:at,M=n.outOfSequencePolicy==="actual_dates"&&at.type==="0"&&St.p6.executionStatus==="in_progress"&&St.p6.primaryConstraintType==="mandatory_start"&&St.p6.sourcePrimaryConstraintToken!==er,H=so({successor:D,predecessor:F,link:b,adapter:e,lagTask:M?D:m(F,D)});H<T&&(T=H)}if(L.remainingEarlyStart===null||L.remainingEarlyFinish===null){if(n.outOfSequencePolicy!=="retained_logic"||P.p6.activityType==="level_of_effort"){A.set(g,{activityId:g,remainingLateStart:null,remainingLateFinish:null,lateStart:null,lateFinish:null,totalFloatHours:null,freeFloatHours:null,isCritical:!1});continue}A.set(g,{activityId:g,remainingLateStart:null,remainingLateFinish:null,lateStart:new Date(T),lateFinish:new Date(T),totalFloatHours:null,freeFloatHours:null,isCritical:!1});continue}T=ux(F,T,e),F.durationHours===0&&P.p6.activityType!=="level_of_effort"&&CS(P,y.get(g)??[],e,T)&&(T=e.getClosestWorkTime({date:oi(T),dir:"past",task:F}));let x=(f.get(g)??[]).length===0,S=nx(n,P,x),k=aS(e,F,T),E=k?.start??e.calculateEndDate({startDate:T,durationHours:-F.durationHours,task:F});if(P.p6.activityType==="level_of_effort")E=sx(e,T,F,y.get(g)??[]),F.durationHours===0&&(T=new Date(E));else if(k!==null)T=k.finish;else{let at=n.outOfSequencePolicy==="actual_dates"&&ex(y.get(g)??[],e)||P.p6.secondaryConstraintType==="fnlt";E=tx(P,E,at),T=e.calculateEndDate({startDate:E,durationHours:F.durationHours,task:F})}S&&(E=new Date(L.remainingEarlyStart),T=new Date(L.remainingEarlyFinish));let j=Wu(e,L.remainingEarlyStart,E,F),w=Wu(e,L.remainingEarlyFinish,T,F),B=Xw(n.totalFloatMethod,{startFloatHours:j,finishFloatHours:w}),$=ix({activity:P,effectivePredecessor:F,early:L,outgoingLinks:y.get(g)??[],boundary:p,forward:r,settings:n,adapter:e,resolveLagTask:m}),ft=n.criticalActivityMethod==="total_float"&&B<=n.criticalFloatThresholdHours||S;A.set(g,{activityId:g,remainingLateStart:new Date(E),remainingLateFinish:new Date(T),lateStart:new Date(E),lateFinish:new Date(T),totalFloatHours:B,freeFloatHours:$,isCritical:ft})}return{activities:A}}function Zw(t){return t?.p6?.activityType==="level_of_effort"&&t.p6.executionStatus==="not_started"&&t.p6.remainingDurationHours===0}function Vu(t,e,n){return n.isWorkTime?.({date:oi(e),task:t})===!1}function Qw(t,e,n){return t.type==="0"&&t.lag===0?!1:e?.p6?.executionStatus==="completed"&&n?.p6?.executionStatus==="completed"}function tx(t,e,n){let r=t.p6;return n||r?.executionStatus!=="in_progress"||r.primaryConstraintType!=="snet"||r.actualStart===null||e>=r.actualStart?e:new Date(r.actualStart)}function ex(t,e){return t.some(n=>{let r=e.getActivity(n.target)?.p6;return r?.executionStatus==="in_progress"&&r.primaryConstraintType==="mandatory_start"&&r.sourcePrimaryConstraintToken!==er})}function nx(t,e,n){return t.makeOpenEndedActivitiesCritical&&n&&e.type!=="milestone"&&t.multipleFloatPaths.endingActivityId!==e.id&&gn(e.p6).execution==="not_started"}function rx(t){return new Map(t.map(e=>[e,{activityId:e,remainingLateStart:null,remainingLateFinish:null,lateStart:null,lateFinish:null,totalFloatHours:null,freeFloatHours:null,isCritical:!1}]))}function ix(t){let{activity:e,effectivePredecessor:n,early:r,outgoingLinks:i,boundary:a,forward:o,settings:s,adapter:l,resolveLagTask:c}=t;if(r.remainingEarlyStart===null||r.remainingEarlyFinish===null)return null;if(e.p6?.executionStatus==="not_started"&&In(e)&&i.length>0||e.p6?.executionStatus==="not_started"&&An(e)&&ax(i,l))return 0;let d=null;for(let p of i){if(vS(e,p,s))continue;let y=l.getActivity(p.target),f=o.activities.get(p.target);if(y?.p6===void 0||f===void 0)continue;let m=ox({successor:y,early:f,settings:s,linkType:p.type});if(m===null)continue;let A={...y,startDate:m.startDate,endDate:m.endDate,durationHours:f.scheduledRemainingDurationHours},g=oo({outOfSequencePolicy:s.outOfSequencePolicy,linkType:p.type,actualStart:e.p6?.actualStart??null})?{...p,lag:0}:p,P=so({successor:A,predecessor:n,link:g,adapter:l,lagTask:c(n,A)});(d===null||P<d)&&(d=P)}d??=new Date(a),n.durationHours===0&&CS(e,i,l,d)&&(d=l.getClosestWorkTime({date:oi(d),dir:"past",task:n}));let u=Wu(l,r.remainingEarlyFinish,d,n);return Math.max(0,Object.is(u,-0)?0:u)}function ax(t,e){return t.some(n=>{let r=e.getActivity(n.target)?.p6;return r?.activityType==="task"&&r.executionStatus==="not_started"&&r.originalDurationHours===0})}function vS(t,e,n){return n.outOfSequencePolicy==="progress_override"&&e.type==="1"&&t.p6?.actualStart!==null&&t.p6?.actualStart!==void 0}function ox(t){let{successor:e,early:n,settings:r,linkType:i}=t,a=n.remainingEarlyStart??n.earlyStart,o=n.remainingEarlyFinish??n.earlyFinish,s=e.p6;return r.outOfSequencePolicy==="actual_dates"&&s!==void 0&&(i==="0"||i==="1"||s.actualFinish!==null)&&(a=s.actualStart??a,o=s.actualFinish??o),a===null||o===null?null:{startDate:new Date(a),endDate:new Date(o)}}function CS(t,e,n,r){if(t.p6?.executionStatus==="completed")return!1;if(t.p6?.activityType==="task"&&t.p6.executionStatus==="not_started"&&t.p6.originalDurationHours===0){let o=oi(r);return n.getClosestWorkTime({date:o,dir:"past",task:t})<o}if(t.p6?.activityType==="start_milestone"&&e.length===0)return Vu(t,r,n);if(e.length===0)return!1;if(t.type!=="milestone")return!0;let i=t.p6?.activityType;if(i!=="start_milestone"&&i!=="finish_milestone")return!1;let a=i==="finish_milestone";return e.every(o=>{let s=n.getActivity(o.target),c=s?.p6?.activityType==="resource_dependent"?s?.calendarId===t.calendarId:s?.calendarId!==t.calendarId&&Vu(t,r,n);return s?.p6!==void 0&&(!a||c)&&gn(s.p6).execution!=="completed"})}function sx(t,e,n,r){if(n.durationHours===0){let o=r.some(s=>{let l=t.getActivity(s.target);return l!==null&&l.calendarId!==n.calendarId})&&Vu(n,e,t)?oi(e):e;return t.getClosestWorkTime({date:o,dir:"past",task:n})}let i=new Date(e);return i.setUTCHours(0,0,0,0),t.getClosestWorkTime({date:i,dir:"future",task:n})}function lx(t,e,n,r){if(t.p6===void 0)return null;let i=e.remainingLateStart??e.lateStart,a=e.remainingLateFinish??e.lateFinish;if(n.outOfSequencePolicy==="actual_dates"){let o=t.p6.actualStart,s=t.p6.actualFinish;if(r==="0"||r==="1"||s!==null){let l=o??i,c=s??a;return l===null||c===null?null:{startDate:new Date(l),endDate:new Date(c)}}}return i===null||a===null?null:n.outOfSequencePolicy==="actual_dates"?{startDate:new Date(i),endDate:new Date(a)}:{startDate:new Date(i),endDate:new Date(a)}}function cx(t,e,n){let r=n.filter(o=>t.getActivity(o)?.p6?.executionStatus!=="completed"),i=r.length>0?r:n,a=null;for(let o of i){let s=e.activities.get(o),l=s?.remainingEarlyFinish??s?.earlyFinish;l!=null&&(a===null||l>a)&&(a=l)}return a===null?null:new Date(a)}function gS(t){let e=new Map;for(let n of t){let r=e.get(n.source)??[];r.push(n),e.set(n.source,r)}return e}function dx(t,e=t.p6?.remainingDurationHours??t.durationHours){return t.p6===void 0?t:{...t,durationHours:e}}function ux(t,e,n){let r=t.p6?.primaryConstraintType,i=t.p6?.primaryConstraintDate,a=t.p6?.sourcePrimaryConstraintToken,o=a===Hu?"fnlt":a===er?"snlt":r,l=r==="start_on"?{...t,constraintType:null,constraintDate:null}:o!=null&&i!==null&&i!==void 0?AS(t,o,i,n):t,d=t.p6?.actualStart===null||o==="fnlt"||o==="finish_on"?IS(l,e,n):new Date(e);if(t.p6?.secondaryConstraintType===null||t.p6?.secondaryConstraintDate===null||t.p6===void 0||t.p6.actualStart!==null&&t.p6.secondaryConstraintType!=="fnlt")return d;let u=AS(t,t.p6.secondaryConstraintType,t.p6.secondaryConstraintDate,n);return d=IS(u,d,n),new Date(d)}function AS(t,e,n,r){let i=ps(e),a=px({activity:t,constraintType:i,constraintDate:n,adapter:r});return{...t,constraintType:i,constraintDate:a}}function px(t){let{activity:e,constraintType:n,constraintDate:r,adapter:i}=t,a=e.p6?.sourcePrimaryConstraintToken===er&&n==="snlt"?"future":yx(n,r)?"past":null;return a===null?new Date(r):i.getClosestWorkTime({date:r,dir:a,task:e})}function yx(t,e){return e.getUTCHours()===0&&e.getUTCMinutes()===0&&e.getUTCSeconds()===0&&e.getUTCMilliseconds()===0&&(t==="fnlt"||t==="mfo")}function IS(t,e,n){let r=Tn(t,n);if((t.constraintType==="mso"||t.constraintType==="mfo")&&r.latestEnd!==null)return new Date(r.latestEnd);let i=e;if(r.latestEnd!==null&&r.latestEnd<i&&(i=r.latestEnd),r.latestStart!==null){let a=n.calculateEndDate({startDate:r.latestStart,durationHours:t.durationHours,task:t});a<i&&(i=a)}return t.constraintType==="snet"&&r.earliestEnd!==null&&r.earliestEnd<i&&(i=r.earliestEnd),new Date(i)}function Wu(t,e,n,r){return e<=n?t.calculateDuration({startDate:e,endDate:n,task:r}):-t.calculateDuration({startDate:n,endDate:e,task:r})}var fx=3600*1e3,DS=["P6_NO_PREDECESSOR","P6_NO_SUCCESSOR","P6_OUT_OF_SEQUENCE","P6_ACTUAL_AFTER_DATA_DATE","P6_INVALID_MILESTONE_RELATIONSHIP"],hx={P6_NO_PREDECESSOR:"open_ended",P6_NO_SUCCESSOR:"open_ended",P6_OUT_OF_SEQUENCE:"out_of_sequence",P6_ACTUAL_AFTER_DATA_DATE:"actual_after_data_date",P6_INVALID_MILESTONE_RELATIONSHIP:"milestone_relationship",P6_UNSATISFIED_CONSTRAINT:"unsatisfied_constraint"},mx={0:"finish_to_start",1:"start_to_start",2:"finish_to_finish",3:"start_to_finish"};function PS(t){let{adapter:e,dataDate:n,project:r,outOfSequencePolicy:i}=t;Tx(i);let a=e.getAllActivities().filter(Ku).sort(LS),o=new Map;for(let s of DS)o.set(s,[]);for(let s of a){e.getIncomingLinkIds(s.id).length===0&&lo(o,Ji(s,r,n,{code:"P6_NO_PREDECESSOR",rule:"activity_has_no_predecessor"})),e.getOutgoingLinkIds(s.id).length===0&&lo(o,Ji(s,r,n,{code:"P6_NO_SUCCESSOR",rule:"activity_has_no_successor"})),Ax(s,n)&&lo(o,Ji(s,r,n,{code:"P6_ACTUAL_AFTER_DATA_DATE",rule:"actual_date_is_after_data_date"}));let l=Ix(e,s);l!==null&&lo(o,Ji(s,r,n,{code:"P6_INVALID_MILESTONE_RELATIONSHIP",rule:"milestone_endpoint_is_not_available",relationship:_S(e,l)}))}for(let s of Dx(e.getAllLinks())){if(!Sx(e,s))continue;let l=e.getActivity(s.target);l===null||!Ku(l)||lo(o,Ji(l,r,n,{code:"P6_OUT_OF_SEQUENCE",rule:"successor_progress_precedes_required_logic",relationship:_S(e,s)}))}return DS.flatMap(s=>o.get(s)??[])}function kS(t){let e=[],n=t.adapter.getAllActivities().filter(Ku).sort(LS);for(let r of n){let i=t.calculated.get(r.id);i===void 0||i.actualFinish!==null||gx(r,i)&&e.push(Ji({...r,p6:i},t.project,t.dataDate,{code:"P6_UNSATISFIED_CONSTRAINT",rule:"constraint_could_not_be_satisfied"}))}return e}function gx(t,e){let n=t.constraintDate??null,r=t.constraintType??null;if(n===null||r===null)return!1;let i=n.getTime(),a=e.remainingEarlyStart??e.earlyStart,o=e.remainingEarlyFinish??e.earlyFinish;switch(r){case _.MSO:return a!==null&&a.getTime()!==i;case _.MFO:return o!==null&&o.getTime()!==i;case _.SNET:return a!==null&&a.getTime()<i;case _.FNET:return o!==null&&o.getTime()<i;case _.SNLT:return a!==null&&a.getTime()>i;case _.FNLT:return o!==null&&o.getTime()>i;default:return!1}}function Ji(t,e,n,r){return{kind:"diagnostic",code:r.code,category:hx[r.code],severity:"warning",project:{...e},activityId:t.id,activityCode:t.customId??t.id,activityName:t.name,activityStatus:t.p6.executionStatus,dataDate:new Date(n),dates:{actualStart:RS(t.p6.actualStart),actualFinish:RS(t.p6.actualFinish)},relationship:r.relationship??null,explanation:{rule:r.rule}}}function lo(t,e){t.get(e.code).push(e)}function Ax(t,e){let n=t.p6;return n!==void 0&&(ES(n.actualStart,e)||ES(n.actualFinish,e))}function Ix(t,e){return e.p6?.activityType==="start_milestone"?TS(t,e,"incoming",n=>n.type==="2"||n.type==="3"):e.p6?.activityType==="finish_milestone"?TS(t,e,"outgoing",n=>n.type==="1"||n.type==="3"):null}function TS(t,e,n,r){return(n==="incoming"?t.getIncomingLinkIds(e.id):t.getOutgoingLinkIds(e.id)).map(a=>t.getLink(a)).filter(a=>a!==null).sort(bS).find(r)??null}function Sx(t,e){let n=t.getActivity(e.source),r=t.getActivity(e.target);if(n?.p6===void 0||r?.p6===void 0)return!1;let i=Cx(r,e.type);if(i===null)return!1;let a=vx(n,e.type);return a===null?!0:i.getTime()<a.getTime()+e.lag*fx}function vx(t,e){return t.p6===void 0?null:e==="1"||e==="3"?t.p6.actualStart:t.p6.actualFinish}function Cx(t,e){return t.p6===void 0?null:e==="0"||e==="1"?t.p6.actualStart:t.p6.actualFinish}function _S(t,e){let n=t.getActivity(e.source),r=t.getActivity(e.target);return{id:e.id,predecessorActivityId:e.source,predecessorActivityCode:n===null?null:n.customId??n.id,successorActivityId:e.target,successorActivityCode:r===null?null:r.customId??r.id,type:mx[e.type],lagHours:e.lag}}function Dx(t){return[...t].sort(bS)}function bS(t,e){return String(t.id).localeCompare(String(e.id))}function LS(t,e){let n=t.correlativeId-e.correlativeId;return n!==0?n:(t.customId??String(t.id)).localeCompare(e.customId??String(e.id))}function ES(t,e){return t!==null&&t.getTime()>e.getTime()}function RS(t){return t===null?null:new Date(t)}function Ku(t){return t.p6!==void 0}function Tx(t){if(t!=="retained_logic"&&t!=="progress_override"&&t!=="actual_dates")throw new Error(`Unsupported P6 out-of-sequence policy: ${String(t)}`)}function jr(t){let e=null;for(let n of t){if(n===null)continue;let r=n.getTime();(e===null||r<e)&&(e=r)}return e===null?null:new Date(e)}function nr(t){let e=null;for(let n of t){if(n===null)continue;let r=n.getTime();(e===null||r>e)&&(e=r)}return e===null?null:new Date(e)}function Yu(t){let e=null;for(let n of t)n!==null&&(e===null||n<e)&&(e=n);return e}function co(t){let e=0;for(let n of t)e+=n;return e}function NS(t){let{adapter:e,settings:n,forward:r,backward:i}=t,a=new Map;for(let u of i.activities.keys())a.set(u,{longestPath:!1,floatPath:null,floatPathOrder:null});let o=Bx(r);for(let u of o)Vx(u,e,r,a,n);if(!n.multipleFloatPaths.enabled)return{activities:a};let s=jx(n,r,o);if(s===null)return{activities:a};let l=n.multipleFloatPaths.limitEnabled?n.multipleFloatPaths.maximum:Number.POSITIVE_INFINITY,c={emittedPaths:0,numberingBudget:n.multipleFloatPaths.limitEnabled?n.multipleFloatPaths.maximum:Number.POSITIVE_INFINITY,numberableActivityIds:wx(e,r,n),activities:a},d=Rx({adapter:e,backward:i,settings:n,endingActivityId:s,state:c});if(!d&&n.multipleFloatPaths.useTotalFloat)Yx(s,e,r,i,n,l,c);else if(!d){let u=zx(s,e,r,n);Wl(n)&&(Xi(u[0]??[],c),_x({adapter:e,backward:i,settings:n,state:c}));let p=Wl(n)?u.slice(1):u;for(let y of p)Xi(y,c)}return n.multipleFloatPaths.limitEnabled&&!d&&(n.multipleFloatPaths.useTotalFloat?Qx(e,r,i,n,c):Jx(e,r,n,c)),d||eM(n,i,c.activities,e),{activities:a}}function _x(t){let{adapter:e,backward:n,settings:r,state:i}=t,a=[...i.numberableActivityIds].filter(o=>Ex(e.getActivity(o))).sort((o,s)=>{let l=n.activities.get(o)?.freeFloatHours??1/0,c=n.activities.get(s)?.freeFloatHours??1/0;return l-c||qu(o,s,e,r)});for(let o of a)Xi([o],i)}function Ex(t){if(t?.p6?.executionStatus!=="in_progress")return!1;let e=t.p6.primaryConstraintType;return e==="alap"||e==="mandatory_start"||e==="start_on"||e==="snet"||e==="snlt"}function Rx(t){if(!kx(t.settings))return!1;let e=bx(t.adapter,t.state);if(e===null||e.length===0||e.length!==t.state.numberingBudget||e.some((r,i)=>r[0].path!==i+1))return!1;let n=Nx(t.endingActivityId,t.adapter);if(e.some(r=>!Lx(r,t,n))||Px(e,t))return!1;for(let r of e)Fx(r,t.state);return!0}function Px(t,e){if(!e.settings.multipleFloatPaths.useTotalFloat)return[...e.state.numberableActivityIds].some(i=>!FS(i,e));let n=new Set(t.flat().map(i=>i.id)),r=Math.max(...t.map(i=>Math.min(...i.map(a=>e.backward.activities.get(a.id)?.totalFloatHours??1/0))));return[...e.state.numberableActivityIds].some(i=>{if(n.has(i))return!1;let a=e.backward.activities.get(i)?.totalFloatHours;return a!=null&&a<=r})}function kx(t){return t.multipleFloatPaths.limitEnabled&&(t.outOfSequencePolicy==="actual_dates"&&t.multipleFloatPaths.useTotalFloat||t.outOfSequencePolicy==="retained_logic"&&!t.multipleFloatPaths.useTotalFloat&&t.multipleFloatPaths.endingActivityId!==null)}function bx(t,e){let n=[...e.numberableActivityIds].map(a=>{let o=t.getActivity(a)?.p6;return{id:a,path:o?.floatPath,order:o?.floatPathOrder}});if(n.some(a=>a.path===null!=(a.order===null)))return null;let r=n.filter(a=>typeof a.path=="number"&&typeof a.order=="number"),i=new Map;for(let a of r){let o=i.get(a.path);o===void 0?i.set(a.path,[a]):o.push(a)}return[...i].sort(([a],[o])=>a-o).map(([,a])=>a.sort((o,s)=>o.order-s.order))}function Lx(t,e,n){return t.length===0||t[0].path>e.state.numberingBudget||t.some((r,i)=>r.order!==i+1)||t.some(r=>!FS(r.id,e))||t.slice(1).some((r,i)=>Ox(t[i].id,r.id,e.adapter).length===0)?!1:n.has(t.at(-1).id)}function FS(t,e){let n=e.adapter.getActivity(t)?.p6,r=e.backward.activities.get(t),i=e.settings.multipleFloatPaths.useTotalFloat,a=i?n?.remainingFloatHours:n?.freeFloatHours,o=i?r?.totalFloatHours:r?.freeFloatHours;return a!=null&&a===o}function Ox(t,e,n){return n.getOutgoingLinkIds(t).map(r=>n.getLink(r)).filter(r=>r?.target===e)}function Nx(t,e){let n=[t],r=new Set;for(;n.length>0;){let i=n.pop();if(!r.has(i)){r.add(i);for(let a of e.getIncomingLinkIds(i)){let o=e.getLink(a)?.source;o!==void 0&&n.push(o)}}}return r}function Fx(t,e){for(let n of t){let r=e.activities.get(n.id);e.activities.set(n.id,{...r,floatPath:n.path,floatPathOrder:n.order})}}function wx(t,e,n){return new Set([...e.activities.keys()].filter(r=>xx(t.getActivity(r),n)))}function xx(t,e){return t?.p6?.executionStatus==="completed"?!1:Mx(e)?An(t)?!1:t?.p6?.executionStatus==="in_progress"?t.p6.primaryConstraintType!==null:!0:e.multipleFloatPaths.useTotalFloat?!HS(t):e.outOfSequencePolicy!=="progress_override"?!0:Wl(e)?t?.p6?.executionStatus==="not_started"||Ux(t):t?.p6?.executionStatus==="not_started"&&!Hx(t)}function Mx(t){return t.multipleFloatPaths.useTotalFloat&&t.outOfSequencePolicy==="progress_override"}function Ux(t){return t?.p6?.executionStatus==="in_progress"&&t.p6.primaryConstraintType!==null&&t.p6.primaryConstraintType!==void 0}function Wl(t){return t.outOfSequencePolicy==="progress_override"&&!t.multipleFloatPaths.useTotalFloat&&t.multipleFloatPaths.endingActivityId!==null}function Hx(t){return An(t)||In(t)}function Xi(t,e){if(!t.some(i=>e.activities.get(i)?.floatPath===null&&e.numberableActivityIds.has(i))||(e.emittedPaths+=1,e.emittedPaths>e.numberingBudget))return;let r=0;for(let i=t.length-1;i>=0;i--){let a=t[i],o=e.activities.get(a);o===void 0||o.floatPath!==null||!e.numberableActivityIds.has(a)||(r+=1,e.activities.set(a,{...o,floatPath:e.emittedPaths,floatPathOrder:r}))}}function Bx(t){let e=[...t.activities].filter(([,r])=>r.earlyFinish!==null),n=e.reduce((r,[,i])=>Math.max(r,i.earlyFinish.getTime()),Number.NEGATIVE_INFINITY);return e.filter(([,r])=>r.earlyFinish.getTime()===n).map(([r])=>r).sort((r,i)=>r.localeCompare(i))}function jx(t,e,n){let r=t.multipleFloatPaths.endingActivityId;return r!==null&&e.activities.has(r)?r:n[0]??null}function Vx(t,e,n,r,i){let a=[t],o=new Set;for(;a.length>0;){let s=a.pop();if(o.has(s))continue;o.add(s);let l=r.get(s);l!==void 0&&r.set(s,{...l,longestPath:!0}),a.push(...wS(s,e,n,i))}}function wS(t,e,n,r){let i=e.getActivity(t),a=n.activities.get(t),o=a?.drivingLinkIds??(a?.drivingLinkId===null||a?.drivingLinkId===void 0?[]:[a.drivingLinkId]),s=i?.p6?.primaryConstraintType==="alap"&&r.outOfSequencePolicy==="retained_logic"?o.filter(y=>e.getLink(y)?.type==="2"):[],l=Wx(i,r);if(An(i)||In(i)||l&&s.length===0)return[];let c=l?s:o;if(c.length>0)return c.map(y=>e.getLink(y)?.source??null).filter(y=>y!==null);let d=e.getIncomingLinkIds(t).map(y=>e.getLink(y)).filter(y=>y!==null).sort((y,f)=>y.source.localeCompare(f.source)),u=d.filter(y=>Kx(y,n.activities.get(y.source),a)).map(y=>y.source);if(u.length>0)return u;let p=r.outOfSequencePolicy==="actual_dates"?d.find(y=>{if(y.type!=="0")return!1;let f=e.getActivity(t),m=e.getActivity(y.source);return f?.p6?.executionStatus==="completed"||m?.p6?.executionStatus==="completed"}):void 0;return p===void 0?[]:[p.source]}function Wx(t,e){return e.outOfSequencePolicy==="progress_override"&&t?.p6?.primaryConstraintType==="alap"?!1:MS(t)}function Kx(t,e,n){return t.lag!==0||e===void 0||n===void 0?!1:t.type==="0"?Vl(e.earlyFinish,n.earlyStart):t.type==="1"?Vl(e.earlyStart,n.earlyStart):t.type==="2"?Vl(e.earlyFinish,n.earlyFinish):Vl(e.earlyStart,n.earlyFinish)}function Vl(t,e){return t!==null&&e!==null&&t.getTime()===e.getTime()}function Yx(t,e,n,r,i,a,o){let s=E=>o.numberableActivityIds.has(E.source)&&o.numberableActivityIds.has(E.target)&&!xS(E.target,e,i)&&!US(E.source,e,i),l=new Map,c=E=>{let j=l.get(E);if(j!==void 0)return j;let w=BS(E,e,n,r,i,s);return l.set(E,w),w},d=qx(t,e,s),u=bn(d.activityIds,d.links);if(u.hasCycles){Gx(t,c,a,o);return}let p=$x(u.ordered,d.links),y=[],f=[],m=new Set,A=new Set,g=0n,P=o.numberingBudget,L=P!==Number.POSITIVE_INFINITY,F=L?BigInt(P):0n,T=a!==Number.POSITIVE_INFINITY,x=T?BigInt(a):0n,S=()=>{g+=1n,!(L&&g>F)&&OS(f,Number(g),o)},k=E=>{if(m.has(E))return;if(A.has(E)){let w=p.get(E);if(w===void 0)throw new Error(`P6 float path count missing for activity ${String(E)}`);let B=g+1n;(!L||B<=F)&&OS(f,Number(B),o),g+=w;return}A.add(E),f.push(E),m.add(E);let j=c(E);if(j.length===0){S(),f.pop(),m.delete(E);return}y.push({links:j,nextIndex:0})};for(k(t);y.length>0&&(!T||g<x);){let E=y[y.length-1];if(E.nextIndex<E.links.length){let j=E.links[E.nextIndex];E.nextIndex+=1,k(j.source);continue}y.pop(),m.delete(f.pop())}o.emittedPaths=Number(g>BigInt(Number.MAX_SAFE_INTEGER)?BigInt(Number.MAX_SAFE_INTEGER):g)}function xS(t,e,n){let r=e.getActivity(t);return n.outOfSequencePolicy==="progress_override"&&n.multipleFloatPaths.useTotalFloat&&r?.p6?.executionStatus==="in_progress"?r.p6.primaryConstraintType!==null:MS(r)}function MS(t){if(t?.p6?.executionStatus!=="not_started")return!1;let e=t?.p6?.primaryConstraintType;return e==="alap"||e==="start_on"||An(t)}function US(t,e,n){let r=e.getActivity(t);return n.outOfSequencePolicy==="progress_override"&&n.multipleFloatPaths.useTotalFloat&&r?.p6?.executionStatus==="in_progress"&&r.p6.primaryConstraintType!==null?!0:HS(r)}function HS(t){return t?.p6?.executionStatus==="not_started"&&In(t)}function Gx(t,e,n,r){let i=[],a=[],o=new Set,s=l=>{if(o.has(l))return;a.push(l),o.add(l);let c=e(l);if(c.length===0){Xi(a,r),a.pop(),o.delete(l);return}i.push({links:c,nextIndex:0})};for(s(t);i.length>0&&r.emittedPaths<n;){let l=i[i.length-1];if(l.nextIndex<l.links.length){let c=l.links[l.nextIndex];l.nextIndex+=1,s(c.source);continue}i.pop(),o.delete(a.pop())}}function OS(t,e,n){let r=0;for(let i=t.length-1;i>=0;i--){let a=t[i],o=n.activities.get(a);o===void 0||o.floatPath!==null||!n.numberableActivityIds.has(a)||(r+=1,n.activities.set(a,{...o,floatPath:e,floatPathOrder:r}))}}function qx(t,e,n){let r=new Set([t]),i=[t],a=[],o=[t];for(;o.length>0;){let s=o.pop(),l=e.getIncomingLinkIds(s).map(c=>e.getLink(c)).filter(c=>c!==null&&n(c));for(let c of l)a.push(c),r.has(c.source)||(r.add(c.source),i.push(c.source),o.push(c.source))}return{activityIds:i,links:a}}function $x(t,e){let n=new Map;for(let i of e){let a=n.get(i.target);a===void 0?n.set(i.target,[i]):a.push(i)}let r=new Map;for(let i of t){let a=n.get(i);if(a===void 0||a.length===0){r.set(i,1n);continue}let o=0n;for(let s of a){let l=r.get(s.source);if(l===void 0)throw new Error(`P6 float path count missing for activity ${String(s.source)}`);o+=l}r.set(i,o)}return r}function BS(t,e,n,r,i,a){let o=n.activities.get(t)?.drivingLinkId;return e.getIncomingLinkIds(t).map(s=>e.getLink(s)).filter(s=>s!==null&&a(s)).sort((s,l)=>{let c=s.id===o?0:1,d=l.id===o?0:1;if(c!==d)return c-d;let u=r.activities.get(s.source)?.totalFloatHours??1/0,p=r.activities.get(l.source)?.totalFloatHours??1/0;return u-p||qu(l.source,s.source,e,i)||l.id.localeCompare(s.id)})}function qu(t,e,n,r){let i=n.getActivity(t),a=n.getActivity(e);if(r.dependencyReference==="custom_id")return(i?.customId??t).localeCompare(a?.customId??e);let o=i?.correlativeId,s=a?.correlativeId;return o!==void 0&&s!==void 0&&o!==s?o-s:t.localeCompare(e)}function zx(t,e,n,r){let i=[],a=new Set,o=[t];for(let s=o.pop();s!==void 0;s=o.pop()){let l=[],c=s;for(;c!==null&&!a.has(c)&&e.getActivity(c)?.p6?.executionStatus!=="completed";)a.add(c),l.push(c),c=Kl(c,e,r)?null:Gu(c,e,n,r);if(l.length===0)continue;i.push(l);let d=[...l].reverse().flatMap(u=>{let p=Kl(u,e,r)?null:Gu(u,e,n,r);return e.getIncomingLinkIds(u).map(y=>e.getLink(y)).filter(y=>y!==null&&y.source!==p).sort((y,f)=>f.source.localeCompare(y.source)||f.id.localeCompare(y.id))});for(let u of d)o.push(u.source)}return i}function Kl(t,e,n){let r=e.getActivity(t)?.p6;return Wl(n)?r?.executionStatus==="in_progress"&&r.primaryConstraintType!==null:r?.executionStatus!=="not_started"?!1:r?.primaryConstraintType==="alap"||r?.primaryConstraintType==="start_on"||r?.sourcePrimaryConstraintToken===er}function Jx(t,e,n,r){let i=new Set([...r.activities].filter(([,o])=>o.floatPath!==null).map(([o])=>o)),a=[...e.activities.keys()].filter(o=>!i.has(o)&&Xx(o,t)&&Zx(o,t,n)).sort((o,s)=>o.localeCompare(s));for(let o of a){let s=[],l=o;for(;l!==null&&!i.has(l);)i.add(l),s.push(l),l=Kl(l,t,n)?null:Gu(l,t,e,n);s.length>0&&Xi(s,r)}}function Xx(t,e){return e.getIncomingLinkIds(t).length>0||e.getOutgoingLinkIds(t).length>0}function Zx(t,e,n){return!e.getOutgoingLinkIds(t).map(r=>e.getLink(r)).some(r=>r!==null&&!Kl(r.target,e,n))}function Qx(t,e,n,r,i){i.emittedPaths=nM(i.activities);let a=rM(i),o=d=>i.numberableActivityIds.has(d.source)&&i.numberableActivityIds.has(d.target)&&!xS(d.target,t,r)&&!US(d.source,t,r),s=d=>o(d)&&a.has(d.source)&&a.has(d.target),l=[...a].filter(d=>iM(d,t,o)).sort((d,u)=>aM(d,u,t,n,r)),c=new Set;for(let d of l){let u=oM(d,t,e,n,r,s,c);Xi(u,i)}}function tM(t,e,n,r){let i=new Map,a=new Set;for(let[s,l]of n){if(l.floatPath===null)continue;let c=e.activities.get(s)?.totalFloatHours??1/0,d=i.get(l.floatPath)??1/0;i.set(l.floatPath,Math.min(d,c)),In(r.getActivity(s))&&a.add(l.floatPath)}let o=new Map([...i].sort(([s,l],[c,d])=>l-d||(t.outOfSequencePolicy==="progress_override"?+!a.has(s)-+!a.has(c):0)||s-c).map(([s],l)=>[s,l+1]));for(let[s,l]of n)l.floatPath!==null&&n.set(s,{...l,floatPath:o.get(l.floatPath)})}function eM(t,e,n,r){!t.multipleFloatPaths.useTotalFloat||!t.multipleFloatPaths.limitEnabled||tM(t,e,n,r)}function nM(t){return Math.max(0,...[...t.values()].map(e=>e.floatPath??0))}function rM(t){return new Set([...t.numberableActivityIds].filter(e=>t.activities.get(e)?.floatPath===null))}function iM(t,e,n){return!e.getOutgoingLinkIds(t).map(r=>e.getLink(r)).some(r=>r!==null&&n(r))}function aM(t,e,n,r,i){let a=r.activities.get(t)?.totalFloatHours??1/0,o=r.activities.get(e)?.totalFloatHours??1/0,s=qu(t,e,n,i);return a-o||(i.outOfSequencePolicy==="progress_override"?-s:s)}function oM(t,e,n,r,i,a,o){let s=[],l=t;for(;l!==null&&!o.has(l);)o.add(l),s.push(l),l=BS(l,e,n,r,i,a)[0]?.source??null;return s}function Gu(t,e,n,r){let i=n.activities.get(t)?.drivingLinkId;return i!=null?e.getLink(i)?.source??null:wS(t,e,n,r)[0]??null}function jS(t){Vr(t.outOfSequencePolicy,"outOfSequencePolicy",["retained_logic","progress_override","actual_dates"]),Vr(t.dependencyReference,"dependencyReference",["correlative_id","custom_id"]),Vr(t.startToStartLagBasis,"startToStartLagBasis",["actual_start","early_start"]),Vr(t.relationshipLagCalendar,"relationshipLagCalendar",["predecessor","successor","project_default","twenty_four_hour"]),Vr(t.totalFloatMethod,"totalFloatMethod",["start_float","finish_float","smallest"]),Vr(t.criticalActivityMethod,"criticalActivityMethod",Object.values(vr)),Vr(t.calculateFloatBasedOn,"calculateFloatBasedOn",["each_project","opened_projects"])}function Vr(t,e,n){if(!n.includes(t))throw new Error(`Invalid P6 schedule settings: ${e}`)}function VS(t,e,n){return n.has(t)?{ancestorId:t,next:e}:e}function sM(t,e,n,r){let i=t.slice(e).reverse(),a=null;for(let o of i)a=VS(o,a,n);for(let o of i)r.set(o,a);return a}function lM(t,e,n,r){let i=[],a=new Map,o=t;for(;o!==null&&!r.has(o)&&!a.has(o);)a.set(o,i.length),i.push(o),o=e.get(o)?.parentId??null;let s=o===null?null:r.get(o)??null,l=o===null?void 0:a.get(o),c=i.length-1;l!==void 0&&(s=sM(i,l,n,r),c=l-1);for(let d=c;d>=0;d-=1){let u=i[d];if(u===void 0)throw new Error("Missing WBS ancestor");s=VS(u,s,n),r.set(u,s)}return r.get(t)??null}function WS(t,e,n){let r=new Map;if(n.size===0)return r;let i=new Map;for(let a of t){if(!(a.p6!==void 0&&a.p6.activityType!==ne.WBS_SUMMARY))continue;let s=a.parentId;if(s===null)continue;let l=lM(s,e,n,i);for(;l!==null;){let c=r.get(l.ancestorId);c===void 0?r.set(l.ancestorId,[a]):c.push(a),l=l.next}}return r}var cM={remainingEarlyStart:null,remainingEarlyFinish:null,remainingLateStart:null,remainingLateFinish:null,lateStart:null,lateFinish:null,remainingFloatHours:null,freeFloatHours:null,floatPath:null,floatPathOrder:null,longestPath:!1},dM=8,Qi="178",uM=Date.parse("2026-10-07T12:00:00.000Z"),pM=3,yM=12,fM=0,hM=Date.parse("2026-10-07T12:00:00.000Z"),mM=Date.parse("2026-10-08T12:00:00.000Z"),gM=Date.parse("2026-10-06T08:00:00.000Z"),AM=-52,IM=-28,SM=Date.parse("2026-10-08T12:00:00.000Z"),vM=Date.parse("2026-10-12T12:00:00.000Z"),CM=24,DM=0,$S=120,TM=8,$u=16,KS=24,_M=10,YS="5330",GS="P6 Oracle Certification 24.12",zS=null,JS="A200",EM=Date.parse("2026-10-05T00:00:00.000Z"),qS=24,RM=8,PM=8,kM=16,XS=3600*1e3;function ZS(t){let{adapter:e,project:n,settings:r}=t;if(po(r),r.dataDate===null)throw new Error("P6 schedule requires Data Date");let i=hS({adapter:e,settings:r});if(i.cycles.length>0)throw new Error(`P6 schedule cannot calculate cycles: ${i.cycles.join(", ")}`);let a=SS({adapter:e,settings:r,forward:i}),o=NS({adapter:e,settings:r,forward:i,backward:a}),s=zM({adapter:e,settings:r}),l=ZM({adapter:e,levelOfEffortActualStarts:s,lateActivities:a.activities}),c=new Map,d=[];for(let p of ev(e.getAllActivities())){let y=p.p6,f=i.activities.get(p.id),m=a.activities.get(p.id),A=o.activities.get(p.id);if(f===void 0||m===void 0||A===void 0)continue;let g=s.get(p.id),P=l.get(p.id),L=LM({current:y,early:f,late:m,path:A,levelOfEffortActualStart:g,completedPredecessorLateFinish:P}),F=NM({activity:p,adapter:e,project:n,settings:r}),T=F?QM(y,L,r.dataDate):L,x=e.calendarReader.getCalendar(p.calendarId);if(x===null)throw new Error(`P6 schedule requires calendar for activity ${p.id}`);let S=ao(T,{dataDate:r.dataDate,calendar:x,calendarId:p.calendarId,totalFloatMethod:r.totalFloatMethod}),k=MM(T,S,F);c.set(p.id,k),UM({excludesLevelOfEffort:F||g!==void 0,method:r.criticalActivityMethod,longestPath:k.longestPath,totalFloatCritical:m.isCritical})&&d.push(p.id)}t6({adapter:e,settings:r,activities:c});let u=[...PS({adapter:e,dataDate:r.dataDate,project:n,outOfSequencePolicy:r.outOfSequencePolicy}),...kS({adapter:e,dataDate:r.dataDate,project:n,calculated:c})];return{activities:c,criticalPath:d,warnings:u}}function bM(t){return(t??_.ASAP)===_.ASAP}function LM(t){let e=t.levelOfEffortActualStart,n=t.completedPredecessorLateFinish;return{...t.current,...OM(t.current,t.early),...e===void 0?{}:{actualStart:new Date(e),executionStatus:et.IN_PROGRESS},remainingDurationHours:t.early.scheduledRemainingDurationHours,remainingEarlyStart:Ze(t.early.remainingEarlyStart),remainingEarlyFinish:Ze(t.early.remainingEarlyFinish),remainingLateStart:Ze(e??t.late.remainingLateStart),remainingLateFinish:Ze(t.late.remainingLateFinish),earlyStart:Ze(t.early.earlyStart),earlyFinish:Ze(t.early.earlyFinish),lateStart:Ze(e??n??t.late.lateStart),lateFinish:Ze(n??t.late.lateFinish),remainingFloatHours:t.late.totalFloatHours,floatPath:t.path.floatPath,floatPathOrder:t.path.floatPathOrder,longestPath:e===void 0&&n===void 0?t.path.longestPath:!0,freeFloatHours:t.late.freeFloatHours}}function OM(t,e){let n=t.activityType===ne.START_MILESTONE&&t.plannedStart!==null&&e.remainingEarlyStart!==null&&t.plannedStart<e.remainingEarlyStart;return t.executionStatus!==et.NOT_STARTED||t.activityType!==ne.TASK&&!n?{plannedStart:t.plannedStart,plannedFinish:t.plannedFinish}:{plannedStart:Ze(e.remainingEarlyStart),plannedFinish:Ze(e.remainingEarlyFinish)}}function NM(t){let{activity:e,adapter:n,project:r,settings:i}=t,a=e.p6,o=i.dataDate;return a===void 0||o===null||!FM({adapter:n,project:r,settings:i})||!wM(e)?!1:xM(a,o)}function FM(t){return GM(t.project)&&t.settings.dataDate?.getTime()===uM&&QS(t.settings)&&qM(t.adapter)&&tv(t.adapter.calendarReader)}function wM(t){let e=t.p6;return e===void 0?!1:t.id===JS&&t.type===U.TASK&&t.calendarId===Qi&&ql(t)&&e.activityType===ne.LEVEL_OF_EFFORT&&e.durationType===Re.FIXED_DURATION_AND_UNITS_PER_TIME&&e.percentCompleteType===Nt.DURATION&&e.originalDurationHours===$u&&uo(e.plannedStart,SM)&&uo(e.plannedFinish,vM)&&uo(e.actualStart,gM)&&Yl(e)&&Gl(e)}function xM(t,e){let n=t.executionStatus===et.IN_PROGRESS&&t.actualFinish===null&&t.remainingDurationHours===$u&&t.physicalPercentComplete===0&&t.unitsPercentComplete===0,r=t.executionStatus===et.COMPLETED&&t.actualFinish?.getTime()===e.getTime()&&t.remainingDurationHours===0&&t.physicalPercentComplete===100&&t.unitsPercentComplete===100;return n||r}function MM(t,e,n){return n?{...t,...e,physicalPercentComplete:100,unitsPercentComplete:100}:{...t,...e}}function UM(t){return t.excludesLevelOfEffort&&t.method===vr.TOTAL_FLOAT?!1:t.method===vr.LONGEST_PATH?t.longestPath:t.totalFloatCritical}function HM(t){let{link:e,adapter:n,dataDate:r}=t;if(e.type!==G.FINISH_TO_START||e.lag!==0)return null;let i=n.getActivity(e.source),a=n.getActivity(e.target);if(!BM(i,r)||a?.calendarId!==Qi)return null;let o=i?.p6;if(o===void 0)return null;let s=o?.actualFinish;return s==null||s>=r?null:new Date(s)}function BM(t,e){let n=t?.p6;return t===null||n===void 0?!1:t.calendarId===Qi&&ql(t)&&n.activityType===ne.TASK&&n.durationType===Re.FIXED_DURATION_AND_UNITS&&n.executionStatus===et.COMPLETED&&n.percentCompleteType===Nt.DURATION&&n.originalDurationHours===TM&&n.remainingDurationHours===0&&n.physicalPercentComplete===100&&uo(n.plannedStart,hM)&&uo(n.plannedFinish,mM)&&Zi(n.actualStart,e,AM)&&Zi(n.actualFinish,e,IM)&&Yl(n)&&Gl(n)}function QS(t){return jM(t.dataDate)&&t.outOfSequencePolicy==="retained_logic"&&t.dependencyReference==="custom_id"&&t.useExpectedFinishDates&&t.startToStartLagBasis==="early_start"&&t.relationshipLagCalendar==="successor"&&t.totalFloatMethod==="finish_float"&&t.criticalActivityMethod==="total_float"&&t.criticalFloatThresholdHours===0&&!t.makeOpenEndedActivitiesCritical&&t.externalRelationshipPolicy==="SD_Both"&&t.calculateFloatBasedOn==="each_project"&&!t.setDataDateAndPlannedStartToForecastStart&&t.projectMustFinishBy===null&&t.projectForecastStart===null&&!t.multipleFloatPaths.enabled&&!t.multipleFloatPaths.limitEnabled&&t.multipleFloatPaths.maximum===_M&&t.multipleFloatPaths.useTotalFloat&&t.multipleFloatPaths.endingActivityId===null}function jM(t){return t!==null&&t.getUTCDay()===pM&&t.getUTCHours()===yM&&t.getUTCMinutes()===fM}function VM(t){let{adapter:e,dataDate:n,levelOfEffort:r,link:i}=t,a=e.getActivity(i.target),o=a?.p6;return i.type===G.FINISH_TO_FINISH&&i.lag===dM&&a?.calendarId===Qi&&a.calendarId===r.calendarId&&ql(a)&&o?.activityType===ne.TASK&&o.durationType===Re.FIXED_DURATION_AND_UNITS&&o.executionStatus===et.NOT_STARTED&&o.percentCompleteType===Nt.DURATION&&o.actualStart===null&&o.actualFinish===null&&o.originalDurationHours===KS&&o.remainingDurationHours===KS&&o.physicalPercentComplete===0&&Zi(o.plannedStart,n,DM)&&Zi(o.plannedFinish,n,$S)&&Yl(o)&&Gl(o)}function WM(t){let{activity:e,boundary:n,settings:r}=t,i=e.p6,a=r.dataDate;return i?.activityType!==ne.LEVEL_OF_EFFORT||a===null||i.durationType!==Re.FIXED_DURATION_AND_UNITS_PER_TIME||i.percentCompleteType!==Nt.DURATION||!QS(r)||!ql(e)||e.calendarId!==Qi||!YM(i)||!Yl(i)||!Gl(i)||i.physicalPercentComplete!==0||i.originalDurationHours!==$u||!KM(i,a)?!1:i.actualStart===null?i.executionStatus===et.NOT_STARTED:i.executionStatus===et.IN_PROGRESS&&i.actualStart.getTime()===n.getTime()}function KM(t,e){return Zi(t.plannedStart,e,CM)&&Zi(t.plannedFinish,e,$S)}function YM(t){return t.actualFinish===null&&t.remainingDurationHours>0&&t.originalDurationHours===t.remainingDurationHours&&t.suspendDate===null&&t.resumeDate===null}function Yl(t){return t.suspendDate===null&&t.resumeDate===null&&t.expectedFinish===null&&t.secondaryConstraintType===null&&t.secondaryConstraintDate===null&&(t.resourceAssignments?.length??0)===0}function Gl(t){return t.actualLaborUnits===0&&t.remainingLaborUnits===0&&t.actualNonlaborUnits===0&&t.remainingNonlaborUnits===0}function uo(t,e){return t?.getTime()===e}function Zi(t,e,n){return t?.getTime()===e.getTime()+n*XS}function ql(t){return bM(t.constraintType)&&t.constraintDate===null}function GM(t){return t.projectId===YS&&t.scheduleId===YS&&t.scheduleCode===GS&&t.scheduleName===GS}function qM(t){let e=t.getAllActivities();return e.length===1&&e[0]?.id===JS&&e[0].parentId===zS&&t.getAllLinks().length===0}function tv(t){let e=t.getCalendar(Qi);if(e===null)return!1;for(let n=0;n<RM;n+=1)for(let r=0;r<qS;r+=1){let i=new Date(EM+(n*qS+r)*XS),a=i.getUTCDay(),o=a>=1&&a<=5&&r>=PM&&r<kM;if(e.isWorkTime(i,mt.HOUR)!==o)return!1}return!0}function $M(t){let e=t.getAllActivities(),n=t.getAllLinks();return e.length===3&&e.every(r=>r.type===U.TASK&&r.parentId===zS)&&n.length===2}function zM(t){let e=t.settings.dataDate;if(e===null)return new Map;if(!$M(t.adapter))return new Map;if(!tv(t.adapter.calendarReader))return new Map;let n=JM(t,e),r=new Map;for(let[i,a]of n.candidates){let o=XM({...t,activityId:i,boundaries:a,index:n});o!==null&&r.set(i,o)}return r}function JM(t,e){let n=new Map,r=new Map,i=new Map;for(let a of t.adapter.getAllLinks()){n.set(a.target,(n.get(a.target)??0)+1);let o=r.get(a.source)??[];o.push(a),r.set(a.source,o);let s=HM({...t,link:a,dataDate:e});if(s===null)continue;let l=i.get(a.target)??[];l.push(s),i.set(a.target,l)}return{incomingCounts:n,outgoing:r,candidates:i}}function XM(t){let e=t.adapter.getActivity(t.activityId),n=t.boundaries[0];if(e===null||n===void 0||t.boundaries.length!==1||t.index.incomingCounts.get(t.activityId)!==1)return null;let r=t.index.outgoing.get(t.activityId)??[];if(r.length!==1)return null;let i=t.settings.dataDate;return i===null||!VM({link:r[0],adapter:t.adapter,levelOfEffort:e,dataDate:i})?null:WM({activity:e,boundary:n,settings:t.settings})?n:null}function ZM(t){let e=new Map,n=new Map;for(let i of t.adapter.getAllLinks())t.levelOfEffortActualStarts.has(i.source)&&e.set(i.source,i.target),t.levelOfEffortActualStarts.has(i.target)&&n.set(i.target,i.source);let r=new Map;for(let[i,a]of n){let o=e.get(i);if(o===void 0)continue;let s=t.lateActivities.get(o)?.lateFinish;s!=null&&r.set(a,new Date(s))}return r}function QM(t,e,n){let i=t.executionStatus===et.IN_PROGRESS?new Date(n):null;return{...e,...cM,actualFinish:t.actualFinish??new Date(n),executionStatus:et.COMPLETED,remainingDurationHours:0,earlyStart:i,earlyFinish:i}}function t6(t){let{adapter:e,settings:n,activities:r}=t,i=e.getAllActivities(),a=ev(i.filter(c=>c.p6?.activityType===ne.WBS_SUMMARY)),o=new Set(a.flatMap(c=>c.parentId===null?[]:[c.parentId]));if(o.size===0)return;let s=new Map(i.map(c=>[c.id,c])),l=WS(i,s,o);for(let c of a){if(c.parentId===null)continue;let d=l.get(c.parentId)??[];if(d.length===0)continue;let u=d.map(S=>r.get(S.id)).filter(S=>S!==void 0);if(u.length===0)continue;let p=e.calendarReader.getCalendar(c.calendarId);if(p===null)throw new Error(`P6 schedule requires calendar for activity ${c.id}`);let y=jr(u.map(S=>S.remainingEarlyStart)),f=nr(u.map(S=>S.remainingEarlyFinish)),m=jr(u.map(S=>S.remainingLateStart)),A=nr(u.map(S=>S.remainingLateFinish)),g=jr(u.map(S=>S.actualStart)),P=u.every(S=>S.executionStatus==="completed"),L=P?"completed":g!==null||u.some(S=>S.executionStatus==="in_progress")?"in_progress":"not_started",F=y===null||f===null?0:p.calculateDuration(y,f),T=g===null?0:p.calculateDuration(g,P?nr(u.map(S=>S.actualFinish))??n.dataDate:n.dataDate),x={...c.p6,actualStart:g,actualFinish:P?nr(u.map(S=>S.actualFinish)):null,plannedStart:jr(u.map(S=>S.plannedStart)),plannedFinish:nr(u.map(S=>S.plannedFinish)),executionStatus:L,remainingDurationHours:F,actualDurationHours:T,atCompletionDurationHours:T+F,originalDurationHours:c.p6.originalDurationHours,actualLaborUnits:co(u.map(S=>S.actualLaborUnits)),remainingLaborUnits:co(u.map(S=>S.remainingLaborUnits)),actualNonlaborUnits:co(u.map(S=>S.actualNonlaborUnits)),remainingNonlaborUnits:co(u.map(S=>S.remainingNonlaborUnits)),remainingEarlyStart:y,remainingEarlyFinish:f,remainingLateStart:m,remainingLateFinish:A,earlyStart:jr(u.map(S=>S.earlyStart)),earlyFinish:nr(u.map(S=>S.earlyFinish)),lateStart:jr(u.map(S=>S.lateStart)),lateFinish:nr(u.map(S=>S.lateFinish)),remainingFloatHours:Yu(u.map(S=>S.remainingFloatHours)),freeFloatHours:Yu(u.map(S=>S.freeFloatHours)),floatPath:null,floatPathOrder:null,longestPath:u.some(S=>S.longestPath)};r.set(c.id,{...x,...ao(x,{dataDate:n.dataDate,calendar:p,totalFloatMethod:n.totalFloatMethod})})}}function po(t){for(let n of[t.dataDate,t.projectMustFinishBy,t.projectForecastStart])if(n!==null&&Number.isNaN(n.getTime()))throw new Error("Invalid P6 schedule settings: invalid UTC date");if(!Number.isFinite(t.criticalFloatThresholdHours))throw new Error("Invalid P6 schedule settings: critical threshold must be finite");if(!Number.isInteger(t.multipleFloatPaths.maximum)||t.multipleFloatPaths.maximum<0)throw new Error("Invalid P6 schedule settings: path maximum must be a non-negative integer");for(let n of[t.scheduleAutomaticallyOnDateChange,t.useExpectedFinishDates,t.makeOpenEndedActivitiesCritical,t.setDataDateAndPlannedStartToForecastStart,t.multipleFloatPaths.enabled,t.multipleFloatPaths.limitEnabled,t.multipleFloatPaths.useTotalFloat])if(typeof n!="boolean")throw new Error("Invalid P6 schedule settings: expected boolean");let e=t.multipleFloatPaths.endingActivityId;if(e!==null&&typeof e!="string"&&(typeof e!="number"||!Number.isFinite(e)))throw new Error("Invalid P6 schedule settings: ending activity ID");jS(t)}function ev(t){return t.filter(e=>e.p6!==void 0).sort((e,n)=>String(e.id).localeCompare(String(n.id)))}function Ze(t){return t===null?null:new Date(t)}var e6="P6 capability is not enabled for this Schedule",n6="F9 is not certified for imported cross-project relationships",r6="P6 Schedule requires a Data Date",nv="P6 Schedule requires scheduling state for every programmable activity",i6="P6 Schedule invariant failed: programmable activity is missing P6 state",a6=10,o6=new Set(Object.values(Re));function s6(t){let e=t.setDataDateAndPlannedStartToForecastStart&&t.projectForecastStart!==null?{...t,dataDate:new Date(t.projectForecastStart)}:t;return!e.multipleFloatPaths.enabled||e.multipleFloatPaths.limitEnabled?e:{...e,multipleFloatPaths:{...e.multipleFloatPaths,limitEnabled:!0}}}function zu(t){if(t.settings===null)return{ready:!1,code:"capability_not_enabled",message:e6,relationshipIds:[],count:0,sampleActivityIds:[],missingInputs:[]};let e=v(t.settings),n=v({...e,...t.patch});po(n);let r=s6(n);if(t.externalRelationshipIds.length>0&&r.externalRelationshipPolicy!=="SD_None")return{ready:!1,code:"EXTERNAL_RELATIONSHIP_F9_NOT_CERTIFIED",message:n6,relationshipIds:v(t.externalRelationshipIds),count:t.externalRelationshipIds.length,sampleActivityIds:[],missingInputs:[]};if(!At(r))return{ready:!1,code:"data_date_required",message:r6,relationshipIds:[],count:0,sampleActivityIds:[],missingInputs:[]};let i=c6(t.activities),{missingInputs:a,schedulableActivities:o,unsupportedActivityIds:s}=i;return s.length>0?rv("activity_scheduling_state_required",nv,s):a.length>0?rv("activity_scheduling_state_required",nv,a.map(({activityId:l})=>l),a):{ready:!0,previousSettings:e,settings:r,activities:o}}function l6(t){return t.type!=="project"}function c6(t){let e=[],n=[],r=new Map;for(let i of t){if(!l6(i))continue;let a=i.p6;if(a===void 0&&f6(i.id),!y6(a)){n.push(i.id);continue}let o=d6(i.progress,a);o.length>0?e.push({activityId:i.id,fields:o}):ln(a)&&r.set(i.id,a)}return{missingInputs:e,schedulableActivities:r,unsupportedActivityIds:n}}function d6(t,e){let n=[];return u6(t,e)&&e.actualStart===null&&n.push("actualStart"),p6(t,e)&&e.actualFinish===null&&n.push("actualFinish"),e.remainingDurationHours===null&&n.push("remainingDurationHours"),n}function u6(t,e){return e.executionStatus!=="not_started"||t!==0}function p6(t,e){return e.executionStatus==="completed"?!0:e.executionStatus==="in_progress"?!1:ri(t)}function y6(t){let{durationType:e}=t;return e===void 0||o6.has(e)}function f6(t){throw new Ce("P6_ACTIVITY_STATE_INVARIANT",i6,[],1,[t])}function rv(t,e,n,r=[]){return{ready:!1,code:t,message:e,relationshipIds:[],count:n.length,sampleActivityIds:n.slice(0,a6),missingInputs:r}}var h6=/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2}) (?<hour>\d{2}):(?<minute>\d{2})$/,m6=/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/,iv="Invalid P6 wall date",av="Invalid P6 day",g6="Invalid UTC date",Ju=1,A6=2;function zl(t){if(t===null)return null;let e=sv(t,h6);if(e===null)throw new Error(`${iv}: "${t}"`);return lv(t,e,iv)}function ov(t){if(t===null)return null;if(Number.isNaN(t.getTime()))throw new Error(g6);return`${t.getUTCFullYear()}-${$l(t.getUTCMonth()+Ju)}-${$l(t.getUTCDate())} ${$l(t.getUTCHours())}:${$l(t.getUTCMinutes())}`}function Jl(t,e){if(t===null)return null;let n=sv(t,m6);if(n===null)throw new Error(`${av}: "${t}"`);let r=lv(t,n,av);return _a(e,r)}function sv(t,e){let n=t.match(e)?.groups;return n===void 0?null:{year:Number(n.year),month:Number(n.month),day:Number(n.day),hour:Number(n.hour??0),minute:Number(n.minute??0)}}function lv(t,e,n){let r=new Date(Date.UTC(e.year,e.month-Ju,e.day,e.hour,e.minute));if(!(r.getUTCFullYear()===e.year&&r.getUTCMonth()+Ju===e.month&&r.getUTCDate()===e.day&&r.getUTCHours()===e.hour&&r.getUTCMinutes()===e.minute))throw new Error(`${n}: "${t}"`);return r}function $l(t){return String(t).padStart(A6,"0")}var I6="Invalid P6 schedule options",S6=10,v6={CT_TotFloat:"total_float",CT_DrivPath:"longest_path"},C6={FT_SS:"start_float",FT_FF:"finish_float",FT_Min:"smallest"},D6={rcal_Predecessor:"predecessor",rcal_Successor:"successor",rcal_ProjDefault:"project_default",rcal_24Hour:"twenty_four_hour"};function cv(t,e,n){return{projectPlannedStart:Xl(t.plan_start_date),settings:{dataDate:Xl(t.last_recalc_date),scheduleAutomaticallyOnDateChange:!1,outOfSequencePolicy:T6(e),dependencyReference:"custom_id",useExpectedFinishDates:Qe(e.sched_use_expect_end_flag),startToStartLagBasis:Qe(e.sched_lag_early_start_flag)?"early_start":"actual_start",relationshipLagCalendar:Xu(D6,e.sched_calendar_on_relationship_lag),totalFloatMethod:Xu(C6,e.sched_float_type),criticalActivityMethod:Xu(v6,t.critical_path_type),criticalFloatThresholdHours:dv(t.critical_drtn_hr_cnt,"critical_drtn_hr_cnt"),makeOpenEndedActivitiesCritical:Qe(e.sched_open_critical_flag),externalRelationshipPolicy:e.sched_outer_depend_type,calculateFloatBasedOn:Qe(e.sched_use_project_end_date_for_float)?"each_project":"opened_projects",setDataDateAndPlannedStartToForecastStart:Qe(e.sched_setplantoforecast),projectMustFinishBy:Xl(t.plan_end_date),projectForecastStart:Xl(t.fcst_start_date),multipleFloatPaths:{enabled:Qe(e.enable_multiple_longest_path_calc),limitEnabled:Qe(e.limit_multiple_longest_path_calc),maximum:E6(e.max_multiple_longest_path,"max_multiple_longest_path"),useTotalFloat:Qe(e.use_total_float_multiple_longest_paths),endingActivityId:R6(e.key_activity_for_multiple_longest_paths,n)}}}}function ta(){return{dataDate:null,scheduleAutomaticallyOnDateChange:!1,outOfSequencePolicy:"retained_logic",dependencyReference:"correlative_id",useExpectedFinishDates:!0,startToStartLagBasis:"early_start",relationshipLagCalendar:"predecessor",totalFloatMethod:"finish_float",criticalActivityMethod:"total_float",criticalFloatThresholdHours:0,makeOpenEndedActivitiesCritical:!1,externalRelationshipPolicy:"SD_Both",calculateFloatBasedOn:"each_project",setDataDateAndPlannedStartToForecastStart:!1,projectMustFinishBy:null,projectForecastStart:null,multipleFloatPaths:{enabled:!1,limitEnabled:!1,maximum:S6,useTotalFloat:!0,endingActivityId:null}}}function Zl(t){return{...t,scheduleAutomaticallyOnDateChange:t.scheduleAutomaticallyOnDateChange??!1}}function Xl(t){return t===void 0||t===""?null:zl(t)}function Qe(t){if(t==="Y")return!0;if(t==="N")return!1;rr(`expected Y/N, got "${t}"`)}function Xu(t,e){return Object.hasOwn(t,e)||rr(`unknown enum "${e}"`),t[e]}function T6(t){let e=Qe(t.sched_retained_logic),n=Qe(t.sched_progress_override);return e&&n&&rr("retained logic and progress override conflict"),e?"retained_logic":n?"progress_override":"actual_dates"}function _6(t,e){let n=dv(t,e);return n<0&&rr(`${e} must be a non-negative number`),n}function dv(t,e){let n=Number(t);return(t===""||!Number.isFinite(n))&&rr(`${e} must be a finite number`),n}function E6(t,e){let n=_6(t,e);return Number.isInteger(n)||rr(`${e} must be an integer`),n}function R6(t,e){if(t==="")return null;e===void 0&&rr("ending activity requires an ID resolver");let n=e(t);return n===null&&rr(`unknown ending activity "${t}"`),n}function rr(t){throw new Error(`${I6}: ${t}`)}function yv(t){let e=zu({settings:t.settings,externalRelationshipIds:t.externalRelationshipIds,patch:t.patch,activities:t.activities});return e.ready?{ready:!0}:{ready:!1,code:e.code,count:e.count,sampleActivityIds:e.sampleActivityIds,missingInputs:v(e.missingInputs)}}function fv(t,e){let n=Sv(t),r=v({...n,...e});return po(r),{before:n,after:r,changed:$t(n)!==$t(r)}}function hv(t,e,n){let r=b6(t,e);x6(r),M6(r,n);let i=P6(t,k6(t,r)),a=v({...t,...i,...wl(t,i)});return ro(a),{next:a,changed:$t(t)!==$t(a)}}function P6(t,e){return t.executionStatus!==et.NOT_STARTED||e.remainingDurationHours===void 0||e.originalDurationHours!==void 0?e:{...e,originalDurationHours:e.remainingDurationHours}}var uv=100;function k6(t,e){if(e.physicalPercentComplete===void 0)return e;let n=e.actualStart!==void 0?e.actualStart:t.actualStart,r=e.actualFinish!==void 0?e.actualFinish:t.actualFinish;if(n!==null&&r===null)return e;let{physicalPercentComplete:a,...o}=e;return o}function mv(t,e,n){if(!Number.isFinite(e.getTime())||t.executionStatus==="completed")return null;let r=t.remainingEarlyStart??t.plannedStart;if(r===null||e.getTime()<=r.getTime())return null;let i=n.calculateDuration(r,e);return!Number.isFinite(i)||i<=0?null:t.executionStatus==="not_started"?{originalDurationHours:i,remainingDurationHours:i}:{remainingDurationHours:i}}function b6(t,e){let{activityPercentComplete:n,...r}=e;if(n===void 0)return r;if(!Number.isFinite(n)||n<0||n>uv)throw new Error("Invalid P6 activity input: Activity % Complete must be within 0..100");switch(r.percentCompleteType??t.percentCompleteType){case Nt.PHYSICAL:return{...r,physicalPercentComplete:n};case Nt.DURATION:return{...r,remainingDurationHours:t.originalDurationHours*(1-n/uv)};case Nt.UNITS:throw new Error("Invalid P6 activity input: Units % Complete is read-only")}}function gv(t){let e=t.state.getAllActivities(),n=zu({settings:t.settings,externalRelationshipIds:t.externalRelationshipIds,patch:t.patch,activities:e});n.ready||w6(n);let r=L6(t.projectState),i=N6(n.settings,r),a=xl({previousSettings:n.previousSettings,settings:n.settings,activities:n.activities}),o=ZS({adapter:O6(t.state,n.activities,a),settings:n.settings,project:{projectId:String(t.sector.projectId),scheduleId:String(t.sector.id),scheduleCode:t.sector.name,scheduleName:t.sector.name}}),s=t.transactionBaseline?.beforeSettings??n.previousSettings,l=t.transactionBaseline?.beforeProjectState??r;return{beforeSettings:s,settings:n.settings,beforeProjectState:l,projectState:i,calculated:o,projection:QI(o),changeSetContribution:F6(s,n.settings,l,i)}}function Av(t,e){for(let[n,r]of e)t.setActivityFields(n,r)}function Iv(t){return Sv(t)}function Sv(t){if(t!==null)return Zl(v(t));throw new Ce("capability_not_enabled","P6 capability is not enabled for this Schedule")}function L6(t){if(t!==null)return v(t);throw new Ce("capability_not_enabled","P6 capability is not enabled for this Schedule")}function O6(t,e,n){let r=t.fork();return r.forEachActivity(i=>{if(!e.has(i.id)){r.setActivityField(i.id,"p6",void 0);return}let a=n.get(i.id);a===void 0||i.p6===void 0||r.setActivityField(i.id,"p6",{...i.p6,expectedFinish:a})}),r}function N6(t,e){let n=t.setDataDateAndPlannedStartToForecastStart&&t.projectForecastStart!==null?new Date(t.projectForecastStart):e.plannedStart;return{...e,plannedStart:n}}function F6(t,e,n,r){return{...pv(t,e)?{p6Settings:{before:t,after:e}}:{},...pv(n.plannedStart,r.plannedStart)?{p6ProjectPlannedStart:{before:v(n.plannedStart),after:v(r.plannedStart)}}:{}}}function pv(t,e){return $t(t)!==$t(e)}function w6(t){throw new Ce(t.code,t.message,t.relationshipIds,t.count,t.sampleActivityIds)}function x6(t){U6(t);let e=t.executionStatus;if("executionStatus"in t&&e!==et.NOT_STARTED&&e!==et.IN_PROGRESS&&e!==et.COMPLETED)throw new Error("Invalid P6 activity input: execution status");for(let r of[t.remainingDurationHours,t.originalDurationHours,t.physicalPercentComplete])if(r!==void 0&&(!Number.isFinite(r)||r<0))throw new Error("Invalid P6 activity input: expected non-negative number");if((t.physicalPercentComplete??0)>100)throw new Error("Invalid P6 activity input: percentage exceeds 100");let n=t.percentCompleteType;if(n!==void 0&&n!==Nt.DURATION&&n!==Nt.UNITS&&n!==Nt.PHYSICAL)throw new Error("Invalid P6 activity input: percent complete type")}function M6(t,e){let n=t.secondaryConstraintType??null;if(!Ai(e,n))throw new Error("Invalid P6 activity input: secondary constraint incompatible with the primary constraint")}function U6(t){for(let e of[t.actualStart,t.actualFinish,t.plannedStart,t.plannedFinish,t.expectedFinish,t.suspendDate,t.resumeDate,t.secondaryConstraintDate])if(e!=null&&Number.isNaN(e.getTime()))throw new Error("Invalid P6 activity input: invalid UTC date")}function Ql(){return Object.freeze({fingerprintActivity:OI,activityCreated:ku,parentPromoted:NI,parentDemoted:FI,scheduleReadiness:yv,prepareSettingsUpdate:fv,prepareLiveDerived:tS,applyLiveDerived:eS,prepareActivityUpdate:hv,prepareFinishEdit:mv,projectLocalActivity:Hl,prepareSchedule:gv,applyScheduleProjection:Av,requireSettings:Iv,historyContribution:xI,applyChangeSet:MI,changeSetIsSubstantive:UI,checkpoint:HI,reconcile:KI})}function vv(t,e){return{settings:v(t.dataDateSettings()),projectState:v(t.dataDateProjectState()),latestRunLog:v(t.dataDateLatestRunLog()),externalRelationshipIds:[...e]}}function Cv(t,e){return t.setDataDateSettings(e.settings),t.setDataDateProjectState(e.projectState),t.setDataDateLatestRunLog(e.latestRunLog),Ql()}function ec(t,e,n,r=null){let o=(t!==void 0&&t.length>0?t:e??[]).map(l=>H6(l,r)),s=(n??[]).map(l=>B6(l,r));return{calendars:o,baseCalendars:s,knownCalendarIds:new Set(o.map(l=>l.id)),defaultCalendarId:Qu(o)}}function Qu(t){let e=null;for(let n of t)if(e??=n.id,n.is_default)return n.id;return e}function Pv(t,e){let n=$6(t.working_days),{days:r,hours:i}=q6(t,n),a=j6(e.exceptionsSource,e.exceptionRange),o={days:r,hours:i};return a&&(o.dates=a),{id:`${String(t.id)}${e.idSuffix}`,name:t.name,is_default:e.isDefault,...e.baseDefault!==void 0?{baseDefault:e.baseDefault}:{},worktime:o}}function H6(t,e){let n=t.baseDefault,r=typeof n=="boolean"?n:void 0;return Pv(t,{idSuffix:"",isDefault:!!t.is_default,baseDefault:r,exceptionsSource:t.exceptiondays,exceptionRange:e})}function B6(t,e){return Pv(t,{idSuffix:"-base",isDefault:!1,baseDefault:!!t.is_default,exceptionsSource:t.baseexceptiondays??t.exceptiondays,exceptionRange:e})}function j6(t,e){if(!Array.isArray(t)||t.length===0)return null;let n={};for(let r of t){if(!r)continue;let i=V6(r.from_date,r.to_date,e,r.every_type);if(i.length===0)continue;let a=Y6(r);if(a!==void 0)for(let o of i)n[o]=a}return Object.keys(n).length>0?n:null}function V6(t,e,n,r){let i=_v(t),a=_v(e);if(i===null||a===null)return[];let o=W6(t,e,i,a)?a-Jd:a;if(n&&(o<n.start||i>n.end))return[];let s=n?Math.max(i,n.start):i,l=n?Math.min(o,n.end):o;return K6(i,s,l,r).map(String)}function W6(t,e,n,r){return r<=n?!1:Dv(e)&&!Dv(t)}function Dv(t){if(typeof t!="string")return!1;let e=xg.exec(t.trim());return e!==null&&Number(e[1])===0&&Number(e[2])===0}function K6(t,e,n,r){switch(r){case Ya.DAILY:return Zu(t,e,n,1);case Ya.WEEKLY:return Zu(t,e,n,Ka);case Ya.MONTHLY:return Tv(t,e,n,1);case Ya.YEARLY:return Tv(t,e,n,ji);default:return Zu(t,e,n,1)}}function Zu(t,e,n,r){let i=r*Jd,a=Math.max(0,Math.ceil((e-t)/i)),o=[];for(let s=t+a*i;s<=n;s+=i)o.push(s);return o}function Tv(t,e,n,r){let i=new Date(t),a=i.getUTCFullYear()*ji+i.getUTCMonth(),o=new Date(e),s=o.getUTCFullYear()*ji+o.getUTCMonth(),l=i.getUTCDate(),c=Math.max(0,Math.floor((s-a)/r)),d=[];for(let u=c;;u+=1){let p=a+u*r,y=Math.floor(p/ji),f=p%ji,m=Date.UTC(y,f,l);if(m>n)return d;new Date(m).getUTCMonth()===f&&m>=e&&d.push(m)}}function _v(t){if(typeof t!="string")return null;let e=wg.exec(t.trim());if(!e)return null;let n=Number(e[1]),r=Number(e[2]),i=Number(e[3]);return Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(i)?Date.UTC(n,r-1,i):null}function Y6(t){if(t.workable===!1)return!1;let e=t.shifts;if(Array.isArray(e)&&e.length>0){let n=G6(e);if(n.length>0)return n}}var Ev=/^\d{1,2}:\d{2}$/;function G6(t){let e=[];for(let n of t){let r=Lv(n?.shift_string);if(!r)continue;if(!r.startsCsv.includes(",")&&!r.endsCsv.includes(",")){let s=r.startsCsv.trim(),l=r.endsCsv.trim();!tc(s)&&!tc(l)&&Ev.test(s)&&Ev.test(l)&&e.push(`${s}-${l}`);continue}let o=bv(r.startsCsv,r.endsCsv).find(s=>s!==null);o&&e.push(o)}return e.sort(kv),e}function Rv(t){let e=t.indexOf("-"),n=e>0?t.slice(0,e):t,[r,i]=n.split(":");return(Number(r)||0)*60+(Number(i)||0)}function kv(t,e){return Rv(t)-Rv(e)}function q6(t,e){let n=Array.from({length:7},()=>[]),r=(c,d)=>{let u=bv(c,d);for(let p=0;p<7;p+=1){let y=u[p],f=n[p];y&&f&&f.push(y)}},i=Array.isArray(t.shifts)&&t.shifts.length>0,a=typeof t.shift_start=="string"&&typeof t.shift_end=="string";if(i)for(let c of t.shifts){let d=Lv(c?.shift_string);d&&r(d.startsCsv,d.endsCsv)}else a&&r(t.shift_start,t.shift_end);for(let c of n)c.sort(kv);let s=n.find((c,d)=>!!e[d]&&c.length>0)??[];return{days:e.map((c,d)=>{if(!c)return!1;let u=n[d];return u&&u.length>0?u:s}),hours:s}}function bv(t,e){let n=Array.from({length:Ka},()=>null);if(typeof t!="string"||typeof e!="string")return n;let r=t.split(",").map(s=>s.trim()),i=e.split(",").map(s=>s.trim());if(!(r.length===i.length&&r.length>0&&r.length<=Ka))return n;let o=[...n];for(let s=0;s<r.length;s+=1){let l=r[s],c=i[s];tc(l)||tc(c)||(o[s]=`${l}-${c}`)}return o}function Lv(t){if(typeof t!="string")return null;let e=t.indexOf("-");return e<=0?null:{startsCsv:t.slice(0,e),endsCsv:t.slice(e+1)}}function $6(t){if(typeof t!="string")return[...Xd];let e=t.split(",").map(n=>n.trim());return e.length!==Ka?[...Xd]:e.map(n=>Mg.has(n))}var z6=new Set(["false","null"]);function tc(t){return!t||z6.has(t)}function J6(t){if(typeof t!="string")return Zd;switch(t.toUpperCase()){case Dt.DURATION:return Dt.DURATION;case Dt.COST:return Dt.COST;case Dt.WORK_HOURS:return Dt.WORK_HOURS;default:return Zd}}function X6(t){let e=t.custom_id_prefix;return typeof e=="string"&&e.length>0?e:void 0}function Z6(t){let e=t.custom_id_increment;return typeof e=="string"?e:typeof e=="number"&&Number.isFinite(e)?String(e):void 0}function Ov(t){let e=X6(t),n=Z6(t),r=t.update_duration_for_primavera_for_end_date===!0;return{id:String(t.id),name:t.name,hoursPerDay:t.hoursPerDay,hoursPerWeek:t.hoursPerWeek,dateFormat:t.dateFormat,projectId:t.projectId,companyId:t.companyId,...e!==void 0?{customIdPrefix:e}:{},...n!==void 0?{customIdIncrement:n}:{},...r?{updateDurationForPrimaveraEndDate:!0}:{},activityCreter:J6(t.activity_creter),statusCriteria:td,ganttId:null}}function nc(t,e=_e,n=hn){let r=Ov(t.sector),{calendars:i,baseCalendars:a,knownCalendarIds:o,defaultCalendarId:s}=ec(t.calendars,t.sector.calendars,t.baseCalendars,Q6(t.activities)),{activities:l,activityIds:c,hiddenIds:d}=yl(t.activities,{knownCalendarIds:o,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:e,recordDiagnostic:n}),u=fl(t.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:e,recordDiagnostic:n});return tU(l,u,o),{sector:r,activities:l,links:u,calendars:i,baseCalendars:a,viewStateSeed:{hiddenIds:d}}}function Q6(t){let e=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(let a of t){let o=new Date(a.start_date).getTime(),s=new Date(a.end_date).getTime();Number.isFinite(o)&&(e=Math.min(e,o)),Number.isFinite(s)&&(n=Math.max(n,s))}if(!Number.isFinite(e)||!Number.isFinite(n))return null;let r=new Date(e),i=new Date(n);return r.setFullYear(r.getFullYear()-1),i.setFullYear(i.getFullYear()+1),{start:r.getTime(),end:i.getTime()}}function tU(t,e,n){let r=new Map(t.map(o=>[o.id,o.id])),i=new Map(Array.from(n,o=>[o,o])),a=new Map(Object.values(U).map(o=>[o,o]));for(let o of t)o.type=a.get(o.type)??o.type,o.parentId!==null&&(o.parentId=r.get(o.parentId)??o.parentId),o.calendarId!==null&&(o.calendarId=i.get(o.calendarId)??o.calendarId);for(let o of e)o.source=r.get(o.source)??o.source,o.target=r.get(o.target)??o.target}var eU=1,nU=-1;function rU(t,e){if(t===void 0&&e===void 0)return 0;if(t===void 0)return eU;if(e===void 0)return nU;let n=Math.min(t.length,e.length);for(let r=0;r<n;r+=1){let i=(t[r]??0)-(e[r]??0);if(i!==0)return i}return t.length-e.length}function Nv(t,e,n,r){let i=n.assignmentByActivityId.get(String(t.id)),a=n.assignmentByActivityId.get(String(e.id)),o=rU(i===void 0?void 0:n.sequencePathByValueId.get(i),a===void 0?void 0:n.sequencePathByValueId.get(a));return r===le.DESCENDING?-o:o}var iU=1,aU=-1;function oU(t,e){return!t&&!e?null:t&&e?0:t?iU:aU}function Fv(t){return t==null}function wv(t,e){let n=e.indexOf(String(t));return n===-1?e.length:n}function sU(t,e,n){return t instanceof Date&&e instanceof Date?t.getTime()-e.getTime():typeof t=="number"&&typeof e=="number"?t-e:typeof t=="boolean"&&typeof e=="boolean"?Number(t)-Number(e):Array.isArray(t)&&Array.isArray(e)?t.length-e.length:String(t).localeCompare(String(e),n,{sensitivity:"base",numeric:!0})}function lU(t,e,n){if(Qr(t)){let i=n.get(t.key);return i===void 0?null:(a,o)=>Nv(a,o,i,t.direction)}let r=_n(t.field);return r===null?null:(i,a)=>{let o=r.extract(i,e),s=r.extract(a,e),l=oU(Fv(o),Fv(s));if(l!==null)return l;let c=r.valueKind===Y.ENUM?wv(o,r.order)-wv(s,r.order):sU(o,s,e.locale);return t.direction===le.DESCENDING?-c:c}}function xv(t,e,n=Lo){let r=t.rules.map(i=>lU(i,e,n)).filter(i=>i!==null);return r.length===0?null:(i,a)=>{for(let o of r){let s=o(i,a);if(s!==0)return s}return 0}}function Mv(t){let e=[];t.forEachActivity((n,r)=>{n.type===U.PROJECT&&t.getChildren(String(r)).length===0&&e.push(String(r))});for(let n of e)t.setActivityField(n,O.TYPE,ei),cU(t,n);return e}function cU(t,e){let n=t.getActivity(e);if(!n||!n.startDate||n.durationHours==null)return;let r=new Date(n.startDate);r.setUTCHours(0,0,0,0);let i=t.getClosestWorkTime({date:r,dir:yt.FUTURE,task:n});if(i.getTime()===n.startDate.getTime())return;let a=t.calculateEndDate({startDate:i,durationHours:n.durationHours,task:n});t.setActivityField(e,O.START_DATE,i),t.setActivityField(e,O.END_DATE,a)}function dU(t){return{...t,id:String(t.id),source:String(t.source),target:String(t.target),type:t.type,lag:Number(t.lag)}}function uU(t){return{days:t.days,hours:t.hours,...t.dates?{dates:t.dates}:{},...t.customWeeks?{customWeeks:t.customWeeks}:{}}}function Uv(t){return{id:String(t.id),worktime:uU(t.worktime)}}function tp(t,e=[]){return[...t.map(Uv),...e.map(Uv)]}function Hv(t,e,n,r=[]){return{activities:[...t],links:e.map(dU),calendars:tp(n,r)}}function Bv(t){let e=[],n=[];t.forEachActivity((i,a)=>{i.parentId===null&&e.push(String(a))});let r=e.map(i=>({activityId:i,parent:null,childIds:null,realWork:0})).reverse();for(let i=r.pop();i;i=r.pop()){if(i.childIds===null){let s=t.getActivity(i.activityId);if(!s)continue;let l=[...t.getChildren(i.activityId)],c=l.length===0;i.childIds=l.values(),i.realWork=c?ye(s.workHours,s.progress):0}let a=i.childIds.next();if(!a.done){r.push(i,{activityId:String(a.value),parent:i,childIds:null,realWork:0});continue}t.setActivityField(i.activityId,O.REAL_WORK_HOURS,i.realWork),n.push(i.activityId),i.parent&&(i.parent.realWork+=i.realWork)}return n}async function jv(t){let{state:e,sector:n,scheduler:r,skipAutoSchedule:i,now:a}=t;if(Ut(e),n.updateDurationForPrimaveraEndDate&&yU(e),fU(e),Bv(e),n.activityCreter===Dt.COST){let s=!1;e.forEachActivity(l=>{s||=jt(l)!==null}),s&&Al(Dt.COST,e)}if(i){Ia(e,n.activityCreter),a&&(Tr(e,a),un(e,n.statusCriteria)),_r(e,n.hoursPerDay),Er(e,n.hoursPerDay);return}pU(e);let o=await r.schedule({});ma(e,o),await sn(e,void 0,!1),e.markScheduleSettled(),Ia(e,n.activityCreter),a&&(Tr(e,a),un(e,n.statusCriteria)),_r(e,n.hoursPerDay),Er(e,n.hoursPerDay)}function pU(t){t.forEachActivity(e=>{e.autoScheduling||!e.startDate||e.durationHours==null||t.getChildren(e.id).length>0||(e.endDate=t.calculateEndDate({startDate:e.startDate,durationHours:e.durationHours,task:e}),e.calendarDuration=Ge(e))})}function yU(t){t.forEachActivity(e=>{!e.startDate||!e.endDate||(e.durationHours=t.calculateDuration({startDate:e.startDate,endDate:e.endDate,task:e}))})}function fU(t){t.forEachActivity(e=>{let n=e.constraintType;if(!n||!e.constraintDate)return;let r=t.calendarReader.getCalendar(String(e.calendarId));r&&(e.constraintDate=$e(e.constraintDate,r,n))})}function Vv(t,e,n=!0){if(t===void 0)return null;let r=v(t),i=Zl(r.settings);for(let a of Object.values(r.activities))ro(a);return hU(e,r.activities,i,n),{capability:Ql(),settings:i,projectState:{plannedStart:r.projectPlannedStart},latestRunLog:r.latestRunLog??null,externalRelationshipIds:r.externalRelationshipIds??[]}}function hU(t,e,n,r){for(let i of t){let a=Object.hasOwn(e,i.id)?e[i.id]:void 0,o=a===void 0?Ei(i):pm(i,a);o!==void 0&&(i.p6=o,At(n,r)&&Object.assign(i,Ml(o,n)))}}var Ve={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function ep(t){return(e,n)=>xv(e,fr(t.hoursPerDay),n)}function Wv(t){let e=t.clock??null,n=e?.()??null,r=n?Ta(n):null,i=t.reporter??_e,a=Ng(),o=nc({sector:t.sector,activities:t.activities,links:t.links,calendars:t.calendars,baseCalendars:t.baseCalendars},i,a.record),s=t.isDataDateEnabled??(()=>!0),l=Vv(t.p6??void 0,o.activities,s()),c=o.sector;c.statusCriteria=Cs(t.statusCriteria),c.ganttId=t.ganttId??null;let d=o.calendars,u=o.baseCalendars??[],p=Hv(o.activities,o.links,o.calendars,u),y=ep(c),f=new Gi(p,y,s,i);f.hydrateViewState({hiddenIds:o.viewStateSeed.hiddenIds});let m=new Mn(f,i),A=Mv(f);gU(f,l?.capability??null,A),mU(f,l);let g=Ja({knownIds:o.activities.map(S=>S.id)}),P=Za({seed:n?.getTime()??0,knownIds:o.links.map(S=>S.id)}),L=Qa({knownIds:o.activities.map(S=>S.uniqueCorrelativeId)}),F=new Wi({defaultPrefix:c.customIdPrefix,suffixIncrement:c.customIdIncrement});if(F.populateFromActivities(o.activities),t.baselinePoints&&t.baselinePoints.length>0){let S=u.find(k=>k.baseDefault)?.id??null;gl(f,t.baselinePoints,r,i,S,a.record)}let T=ym(f,t.p6),x=jv({state:f,sector:c,scheduler:m,skipAutoSchedule:t.skipInitialAutoSchedule===!0,now:r??void 0}).then(T);return{dataDateCapability:l?.capability??null,sector:c,state:f,scheduler:m,activityIdGen:g,linkIdGen:P,uidGen:L,customIdTracker:F,calendars:d,baseCalendars:u,clock:e,reporter:i,loadDiagnostics:a.snapshot,externalRelationshipIds:l?.externalRelationshipIds??[],initPromise:x}}function mU(t,e){e!==null&&(t.setDataDateSettings(e.settings),t.setDataDateProjectState(e.projectState),t.setDataDateLatestRunLog(e.latestRunLog))}function gU(t,e,n){if(e!==null)for(let r of n){let i=t.getActivity(r);if(i===null||i.p6!==void 0)continue;let a=e.activityCreated({activity:i,hasCompleteSchedulingState:!0});a.p6!==void 0&&t.setActivityField(r,"p6",a.p6)}}var np=1;function Kv(t){return{sector:v(t.sector),calendars:v([...t.calendars.values()]),baseCalendars:v([...t.baseCalendars]),state:t.state.exportSnapshot(),activityIdCounter:t.activityIdGenerator.snapshot(),linkIdCounter:t.linkIdGenerator.snapshot(),uniqueCorrelativeIdCounter:t.uniqueCorrelativeIdGenerator.snapshot(),customIds:t.customIdTracker.snapshot(),dataDate:t.dataDateCapability===null?null:vv(t.state,t.externalRelationshipIds)}}function Yv(t,e){if(t.version!==np)throw new Error(`[ScheduleCore] unsupported snapshot version ${String(t.version)}`);let n=e.reporter??_e,r=Gi.fromSnapshot(t.state,ep(t.sector),e.isDataDateEnabled??(()=>!0),n),i=t.dataDate;return{state:r,scheduler:new Mn(r,n),sector:t.sector,activityIdGenerator:Ja({seed:t.activityIdCounter}),linkIdGenerator:Za({seed:t.linkIdCounter}),uniqueCorrelativeIdGenerator:Qa({seed:t.uniqueCorrelativeIdCounter}),customIdTracker:Wi.fromSnapshot(t.customIds),calendars:new Map(t.calendars.map(a=>[a.id,a])),baseCalendars:t.baseCalendars,clock:e.clock??null,reporter:n,loadDiagnostics:()=>[],externalRelationshipIds:[...i?.externalRelationshipIds??[]],dataDateCapability:i?Cv(r,i):null}}function yo(t,e){let n=t.getActivity(e);return n?v(n):null}function Gv(t){return t.getAllActivities().map(v)}function qv(t){return t.getAllIds().map(String)}function $v(t,e){t.forEachActivity((n,r)=>e(r))}function zv(t,e){let n=e==="0"?rp(t,"0"):t.getChildren(e),r=[];for(let i of n){let a=t.getActivity(i);a&&r.push(v(a))}return r.sort((i,a)=>(i.correlativeId??0)-(a.correlativeId??0)),r}function rp(t,e){return Te(e,t)}function Jv(t){return t.checkedIds().map(String)}function Xv(t,e){if(e==="0"){let n=!1;return t.forEachActivity(r=>{n||=q(r.parentId)}),n}return t.getChildren(e).length>0}function ip(t,e){let n=t.getLink(e);return n?Ft(n):null}function Zv(t){return t.getAllLinks().map(e=>Ft(e))}function rc(t){let[e,n]=t.split(":");return Number(e)*60+Number(n??0)}function AU(t){return t.reduce((e,n)=>rc(n)<rc(e)?n:e)}function IU(t){return t.reduce((e,n)=>rc(n)>rc(e)?n:e)}function SU(t){return t.worktime.days.flatMap(e=>Array.isArray(e)?e:e===!0?t.worktime.hours:[])}function Qv(t){let e=[...t].find(a=>a.is_default);if(!e)return null;let n=SU(e);if(n.length===0)return null;let r=n.map(a=>a.split("-")[0]),i=n.map(a=>a.split("-")[1]);return{startHour:AU(r),endHour:IU(i)}}function ic(t,e){return{calendars:t.calendarReader,hasCalendar:n=>e.calendars.has(n),getDefaultCalendarId:()=>Qu(e.calendars.values()),hierarchy:vI(t),activityReader:SI(t),dateFormat:e.dateFormat??"YYYY-MM-DD",customHours:e.customHours??{},hoursPerDay:e.hoursPerDay}}function tC(t){return br(t)}var vU=new Set(["freeSlackHours","isCritical"]);function CU(t,e){let n=Object.fromEntries(Object.entries(t.fields??{}).filter(([r])=>!e.has(r)));return t.kind===W.UPDATED&&Object.keys(n).length===0?null:{...t,...t.fields===void 0?{}:{fields:n},after:null}}function DU(t){let e={};for(let[n,r]of Object.entries(t))e[n]={before:Oa(r.before),after:Oa(r.after)};return e}function TU(t){return{...t,...t.fields===void 0?{}:{fields:DU(t.fields)},...t.before===void 0?{}:{before:st(t.before)},after:null}}function fo(t){let e=t.links.map(i=>CU(i,vU)).filter(i=>i!==null),n=t.source.kind===Ye?{...t.source,items:[],links:[]}:t.source;return{...v({...t,source:n,activities:[],links:e}),activities:t.activities.map(TU)}}function ea(t,e,n,r,i,a,o){return{changeSet:t,beforeSnap:e,beforeLinks:eC(n),afterSnap:r,afterLinks:eC(i),progressFallbackBefore:a,progressFallbackAfter:o}}function eC(t){if(t)return new Map(Array.from(t,([e,n])=>[e,{...n,freeSlackHours:null,isCritical:!1}]))}function iC(t,e){let n=new Map,r=new Map;for(let i of e.activities){if(i.kind!==W.CREATED)continue;let a=t.getActivity(String(i.id));a&&n.set(String(i.id),st(a))}for(let i of e.links){if(i.kind===W.DELETED)continue;let a=t.getLink(String(i.id));a&&r.set(String(i.id),{...a})}return{afterSnap:n,afterLinks:r}}function aC(t){return t.kind!==I.INLINE_EDIT||!Ha.has(t.column)?null:`inline-edit:${String(t.activityId)}:${t.column}`}function nC(t){return t.changeSet.activities.length===1&&t.changeSet.activities[0]?.kind===W.UPDATED&&t.changeSet.links.length===0&&!t.beforeSnap?.size&&!t.afterSnap?.size}function oC(t,e){if(!nC(t)||!nC(e))return!1;let n=t.changeSet.activities[0],r=e.changeSet.activities[0];return!!n&&!!r&&String(n.id)===String(r.id)}function sC(t,e){let n=t.changeSet.activities[0],r=e.changeSet.activities[0];if(!n||!r)return e;let i=n.fields??{},a=r.fields??{},o={};for(let l of new Set([...Object.keys(i),...Object.keys(a)])){let c=i[l],d=a[l];o[l]={before:c?c.before:d?.before,after:d?d.after:c?.after}}let s={...e.changeSet,activities:[{...r,fields:o}]};return ea(s)}var ir={RECORD:"record",SKIP:"skip",CHECKPOINT_ON_SUCCESS:"checkpoint-on-success",REBASE_ON_SUCCESS:"rebase-on-success"},Bt={BEFORE:"before",AFTER:"after"};function lC(t){return t.kind===I.PERSISTENCE_ACKNOWLEDGE?ir.CHECKPOINT_ON_SUCCESS:t.kind===I.PERSISTENCE_REBASE?ir.REBASE_ON_SUCCESS:t.kind===I.SIR_SYNC||t.kind===I.CALENDAR_RECONCILE||t.kind===I.ACTIVITY_LOOKAHEAD_SYNC||t.kind===I.BASELINE_APPLY||t.kind===I.PONDERATOR_CRITERION_SET||t.kind===I.STATUS_CRITERIA_SET||t.kind===I.ACTIVITY_CLIPBOARD_CLEAR||t.kind===I.ACTIVITY_CLIPBOARD_IMPORT||t.kind===I.ACTIVITY_COPY||t.kind===I.SELECTION_TOGGLE||t.kind===I.SELECTION_REPLACE||t.kind===I.VISIBILITY_SET||t.kind===I.FILTER_SET||t.kind===I.SORT_SET||t.kind===I.VIEW_ATTRIBUTES_SET||t.kind===I.GROUP_SET||t.kind===I.WBS_DEPTH_SET?ir.SKIP:ir.RECORD}function ap(t){for(let e of t.changeSet.activities)if(e.kind===W.CREATED||e.kind===W.DELETED||e.kind===W.UPDATED&&e.fields&&R.CUSTOM_ID in e.fields)return!0;return!1}function op(t,e,n,r=()=>({})){let i=[],a=[];for(let s of e.changeSet.activities){let l=String(s.id);if(s.kind===W.UPDATED){let c=t.getActivity(l);i.push({id:l,kind:W.UPDATED,fields:rC(s.fields,n),after:c?st(c):null})}else if(s.kind===W.DELETED)if(n===Bt.BEFORE){let c=t.getActivity(l);i.push({id:l,kind:W.CREATED,after:c?st(c):null})}else i.push({id:l,kind:W.DELETED,after:null});else if(n===Bt.BEFORE)i.push({id:l,kind:W.DELETED,after:null});else{let c=t.getActivity(l);i.push({id:l,kind:W.CREATED,after:c?st(c):null})}}for(let s of e.changeSet.links){let l=String(s.id);if(s.kind===W.UPDATED){let c=t.getLink(l);a.push({id:l,kind:W.UPDATED,fields:rC(s.fields,n),after:c?Ft(c):null})}else if(s.kind===W.DELETED)if(n===Bt.BEFORE){let c=t.getLink(l);a.push({id:l,kind:W.CREATED,after:c?Ft(c):null})}else a.push({id:l,kind:W.DELETED,after:null});else if(n===Bt.BEFORE)a.push({id:l,kind:W.DELETED,after:null});else{let c=t.getLink(l);a.push({id:l,kind:W.CREATED,after:c?Ft(c):null})}}let o=(e.changeSet.viewState??[]).map(s=>n===Bt.BEFORE?_U(s):s);return{source:{kind:n===Bt.BEFORE?ce.UNDO:ce.REDO},activities:i,links:a,calendars:[],trackingEvents:[],effects:[],viewState:o,...r(n)}}function rC(t,e){if(t!=null)return Object.fromEntries(Object.entries(t).map(([n,r])=>[n,e===Bt.BEFORE?{before:v(r.after),after:v(r.before)}:{before:v(r.before),after:v(r.after)}]))}function _U(t){return{activityId:t.activityId,...t.checked?{checked:{before:t.checked.after,after:t.checked.before}}:{},...t.visible?{visible:{before:t.visible.after,after:t.visible.before}}:{}}}function cC(t,e=!1){return t.activities.length>0||t.links.length>0||e||(t.viewState?.length??0)>0||(t.effects?.length??0)>0}function sp(t,e,n){dC(t,e,Bt.BEFORE,n)}function lp(t,e,n){dC(t,e,Bt.AFTER,n)}function dC(t,e,n,r){let i=e.changeSet;for(let o of i.activities)if(o.kind===W.UPDATED){if(!o.fields)continue;for(let[s,l]of Object.entries(o.fields))Se(t,o.id,s,n===Bt.BEFORE?l.before:l.after)}else if(o.kind===W.DELETED)if(n===Bt.BEFORE){let s=e.beforeSnap?.get(String(o.id));if(!s)throw new Error(`undo: missing beforeSnap for resurrecting activity ${o.id}`);t.addActivity(st(s))}else t.removeActivity(String(o.id));else if(n===Bt.BEFORE)t.removeActivity(String(o.id));else{let s=e.afterSnap?.get(String(o.id));if(!s)throw new Error(`redo: missing afterSnap for re-creating activity ${o.id}`);t.addActivity(st(s))}for(let o of i.links)if(o.kind===W.UPDATED){if(!o.fields)continue;let s=t.getLink(String(o.id)),l=o.fields[Vt.SOURCE],c=o.fields[Vt.TARGET];s&&(l||c)&&t.setLinkEndpoints(String(o.id),String(l?n===Bt.BEFORE?l.before:l.after:s.source),String(c?n===Bt.BEFORE?c.before:c.after:s.target));for(let[d,u]of Object.entries(o.fields))d===Vt.SOURCE||d===Vt.TARGET||Jf(t,String(o.id),d,n===Bt.BEFORE?u.before:u.after)}else if(o.kind===W.DELETED)if(n===Bt.BEFORE){let s=e.beforeLinks?.get(String(o.id));if(!s)throw new Error(`undo: missing beforeLinks for re-adding link ${o.id}`);t.addLink(s)}else t.removeLink(String(o.id));else if(n===Bt.BEFORE)t.removeLink(String(o.id));else{let s=e.afterLinks?.get(String(o.id));if(!s)throw new Error(`redo: missing afterLinks for re-creating link ${o.id}`);t.addLink(s)}for(let o of i.viewState??[])o.checked&&t.setChecked(o.activityId,n===Bt.BEFORE?o.checked.before:o.checked.after),o.visible&&t.setVisible(o.activityId,n===Bt.BEFORE?o.visible.before:o.visible.after);let a=n===Bt.BEFORE?e.progressFallbackBefore:e.progressFallbackAfter;for(let[o,s]of a??[])t.setProgressFallback(o,s);r?.(i,n)}var cp=["earlyStart","earlyFinish","lateStart","lateFinish","totalSlackHours"],uC=cp.slice(0,4),pC=t=>t instanceof Date?t.getTime():t,ho=t=>typeof t=="number"?new Date(t):t,ac={encode:pC,decode:ho};function EU(t){if(t===null||typeof t!="object")return!1;let e=Object.keys(t);if(e.length!==cp.length||e.some((a,o)=>a!==cp[o]))return!1;let n=t,r=uC.every(a=>n[a]===null||n[a]instanceof Date),i=n.totalSlackHours;return r&&(i===null||typeof i=="number")}var RU={encode:t=>EU(t)?[...uC.map(e=>pC(t[e])),t.totalSlackHours]:t,decode:t=>{if(!Array.isArray(t))return t;let[e,n,r,i,a]=t;return{earlyStart:ho(e),earlyFinish:ho(n),lateStart:ho(r),lateFinish:ho(i),totalSlackHours:a}}},PU=new Map([["startDate",ac],["endDate",ac],["constraintDate",ac],["dateOrigin",ac],["criticalPath",RU]]);function kU(t,e){if(t.fields===void 0)return t;let n={};for(let[r,i]of Object.entries(t.fields)){let a=PU.get(r);n[r]=a?{before:e(a)(i.before),after:e(a)(i.after)}:i}return{...t,fields:n}}function yC(t,e){let n={...t.changeSet,activities:t.changeSet.activities.map(r=>kU(r,e))};return{...t,changeSet:n}}function Wr(t){return yC(t,e=>e.encode)}function oc(t){return yC(t,e=>e.decode)}var bU=100,LU=600,sc=class t{constructor(e=bU){this.maxDepth=e}maxDepth;undoStack=[];redoStack=[];sequence=0;_lastKey=null;_lastTime=0;fork(){let e=new t(this.maxDepth);return e.undoStack.push(...v(this.undoStack)),e.redoStack.push(...v(this.redoStack)),e.sequence=this.sequence,e._lastKey=this._lastKey,e._lastTime=this._lastTime,e}record(e,n=null,r=0){let i=this.undoStack[this.undoStack.length-1];n!=null&&n===this._lastKey&&r-this._lastTime<=LU&&i!==void 0&&oC(i.entry,e)?(i.entry=Wr(sC(oc(i.entry),e)),i.touchedAt=this.touch()):(this.undoStack.push({entry:Wr(e),touchedAt:this.touch()}),this.undoStack.length>this.maxDepth&&this.undoStack.splice(0,this.undoStack.length-this.maxDepth)),this._lastKey=n,this._lastTime=r,this.redoStack.length=0}resetCoalesce(){this._lastKey=null}takeUndo(){let e=this.undoStack.pop();return e?oc(e.entry):null}takeRedo(){let e=this.redoStack.pop();return e?oc(e.entry):null}pushRedo(e){this.redoStack.push({entry:Wr(e),touchedAt:this.touch()})}pushUndo(e){this.undoStack.push({entry:Wr(e),touchedAt:this.touch()})}restoreTakenUndo(e){this.undoStack.push({entry:Wr(e),touchedAt:this.sequence})}restoreTakenRedo(e){this.redoStack.push({entry:Wr(e),touchedAt:this.sequence})}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undoDepth(){return this.undoStack.length}capturePersistenceBoundary(){return this.resetCoalesce(),this.sequence}discardThrough(e){this.removeEntriesThrough(this.undoStack,e),this.removeEntriesThrough(this.redoStack,e),this.resetCoalesce()}applyPersistedIdentities(e,n){let r=new Map(e.map(({id:a,proplannerId:o})=>[String(a),o])),i=new Map(n.map(({id:a,proplannerId:o})=>[String(a),o]));for(let a of[...this.undoStack,...this.redoStack])a.entry=this.withPersistedIdentities(a.entry,r,i)}clear(){this.undoStack.length=0,this.redoStack.length=0,this.resetCoalesce()}touch(){return this.sequence+=1,this.sequence}removeEntriesThrough(e,n){let r=e.filter(({touchedAt:i})=>i>n);e.splice(0,e.length,...r)}withPersistedIdentities(e,n,r){let i=o=>o===void 0?void 0:new Map(Array.from(o,([s,l])=>[s,n.has(s)?{...l,proplannerId:n.get(s)}:l])),a=o=>o===void 0?void 0:new Map(Array.from(o,([s,l])=>[s,r.has(s)?{...l,proplannerId:r.get(s)}:l]));return{...e,beforeSnap:i(e.beforeSnap),afterSnap:i(e.afterSnap),beforeLinks:a(e.beforeLinks),afterLinks:a(e.afterLinks)}}};var lc=t=>(t>>>0).toString(16).padStart(8,"0"),Oe={undefined:1,null:2,string:3,true:4,false:5,number:6,bigint:7,date:8,array:9,object:10,end:11,other:12},hC=new Float64Array(1),fC=new Uint32Array(hC.buffer),OU=(t,e)=>{if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n]!==e[n])return!1;return!0},cc=class{keyCodes=new Map;keyOrders=new Map;first=1779033703;second=3144134277;third=1013904242;fourth=2773480762;mix(e){this.first=this.second^Math.imul(this.first^e,597399067),this.second=this.third^Math.imul(this.second^e,2869860233),this.third=this.fourth^Math.imul(this.third^e,951274213),this.fourth=this.first^Math.imul(this.fourth^e,2716044179)}float(e){hC[0]=e,this.mix(fC[0]),this.mix(fC[1])}key(e){let n=this.keyCodes.get(e);if(n===void 0){n=2166136261;for(let r=0;r<e.length;r+=1)n=Math.imul(n^e.charCodeAt(r),16777619);this.keyCodes.set(e,n)}this.mix(n)}sortedKeys(e){let n=Object.keys(e),r=`${n.length}:${n[0]??""}:${n[n.length-1]??""}`,i=this.keyOrders.get(r);if(i&&OU(i.raw,n))return i.sorted;let a=[...n].sort();return this.keyOrders.set(r,{raw:n,sorted:a}),a}text(e){this.mix(e.length);for(let n=0;n<e.length;n+=1)this.mix(e.charCodeAt(n))}add(e,n){this.addScalar(e)||this.addComposite(e,n)}addScalar(e){if(e===void 0)this.mix(Oe.undefined);else if(e===null)this.mix(Oe.null);else if(typeof e=="string")this.mix(Oe.string),this.text(e);else if(typeof e=="boolean")this.mix(e?Oe.true:Oe.false);else if(typeof e=="number")this.mix(Oe.number),this.float(e);else if(typeof e=="bigint")this.mix(Oe.bigint),this.text(String(e));else if(e instanceof Date)this.mix(Oe.date),this.float(e.getTime());else return!1;return!0}addComposite(e,n){if(Array.isArray(e)){this.mix(Oe.array),this.mix(e.length);for(let r of e)this.add(r)}else if(e instanceof Map||e instanceof Set)this.mix(Oe.other),this.text(JSON.stringify(mC(e)));else if(typeof e=="object"&&e!==null){this.mix(Oe.object);for(let r of this.sortedKeys(e))r!==n&&(this.key(r),this.add(e[r]));this.mix(Oe.end)}else throw new TypeError(`Unsupported canonical value: ${typeof e}`)}digest(){let e=Math.imul(this.third^this.first>>>18,597399067),n=Math.imul(this.fourth^this.second>>>22,2869860233),r=Math.imul(e^this.third>>>17,951274213),i=Math.imul(n^this.fourth>>>19,2716044179);return`${lc(e^n^r^i)}${lc(n^e)}${lc(r^e)}${lc(i^e)}`}},mC=t=>Array.from(t instanceof Map?t:t.values(),e=>JSON.stringify(e,(n,r)=>r instanceof Map||r instanceof Set?mC(r):r)).sort();var NU=["parentId","correlativeId"];function AC(t,e){let n=new Set,r=i=>{let a=e(i);n.add(a===null?"0":String(a))};for(let i of t.activities){let a=String(i.id);if(i.kind===W.CREATED){r(a);continue}if(i.kind===W.DELETED){let l=i.fields;l&&"parentId"in l&&n.add(gC(l.parentId?.before));continue}let o=i.fields;!o||!NU.some(l=>l in o)||(r(a),"parentId"in o&&n.add(gC(o.parentId?.before)))}return n}function gC(t){return t==null?"0":String(t)}var IC=8e3,SC=16,FU=t=>t===O.CRITICAL_PATH||t===O.IS_CRITICAL||t===O.FREE_SLACK_HOURS;function wU(t){return{hasCriticalPath:Object.hasOwn(t,O.CRITICAL_PATH),criticalPath:t.criticalPath,hasIsCritical:Object.hasOwn(t,O.IS_CRITICAL),isCritical:t.isCritical,hasFreeSlackHours:Object.hasOwn(t,O.FREE_SLACK_HOURS),freeSlackHours:t.freeSlackHours}}function xU(t,e){return!t.hasCriticalPath||!Na(t.criticalPath,e.criticalPath)?{before:t.hasCriticalPath?gs(t.criticalPath):void 0,after:gs(e.criticalPath)}:null}function vC(t,e,n){return!t||!Object.is(e,n)?{before:t?e:void 0,after:n}:null}function MU(t,e,n){return t===O.CRITICAL_PATH?xU(e,n):t===O.IS_CRITICAL?vC(e.hasIsCritical,e.isCritical,n.isCritical):vC(e.hasFreeSlackHours,e.freeSlackHours,n.freeSlackHours)}function UU(t,e,n){let r={},i=0;for(let a of Object.keys(n)){if(!FU(a))continue;let o=MU(a,e,n);o!==null&&(r[a]=o,i+=1)}return i===0?null:{id:t,kind:W.UPDATED,fields:r,after:st(n)}}function HU(t,e,n,r){let i=r.getLink(t);if(!i)return null;let a={};return Object.is(e,i.freeSlackHours)||(a[Vt.FREE_SLACK_HOURS]={before:e,after:i.freeSlackHours}),Object.is(n,i.isCritical)||(a[Vt.IS_CRITICAL]={before:n,after:i.isCritical}),Object.keys(a).length===0?null:{id:t,kind:W.UPDATED,fields:a,after:Ft(i)}}async function CC(t,e,n){let r=[],i=[],a=new Map,o=t.getAllActivities(),s=t.getAllLinks(),l=0;for(let c=0;c<e.activityIds.length;c+=1){l>=IC&&(l=0,await Ot()),l+=1;let d=String(e.activityIds[c]),u=fd(t,o,e,c);if(!u||!ud(u,e,c))continue;let p=wU(u);t.setActivityFields(d,cd(e,c,a)),l+=SC;let y=UU(d,p,u);y&&r.push(y)}for(let c=0;c<e.linkIds.length;c+=1){l>=IC&&(l=0,await Ot()),l+=1;let d=String(e.linkIds[c]),u=hd(t,s,e,c);if(!u||!pd(u,e,c))continue;let p=u.freeSlackHours,y=u.isCritical;l+=SC,yd(t,d,dd(e,c));let f=HU(d,p,y,t);f&&i.push(f)}return{source:n,activities:r,links:i,calendars:[],trackingEvents:[]}}function ae(t){if(t==null||t===0)return!1;if(!(typeof t=="number"&&Number.isSafeInteger(t)&&t>0))throw new Error(`invalid proplannerId ${String(t)}`);return!0}function DC(t,e){for(let n of t)ae(n.proplannerId);for(let n of e)ae(n.proplannerId)}function BU(t,e){return{id:t.id,proplannerId:e,parentId:t.parentId,hadBaseline:RC(t)}}function TC(t,e){return{persistable:wr(t),deletedSnapshot:BU(t,e)}}function jU(t,e,n){let r=t.persistable;r.correlativeId=e;let i=t.deletedSnapshot;return i.hadBaseline=n,t}var RC=t=>t.baselineSnapshot!==null||t.baselinePoints.length>0,VU=Object.freeze(["correlativeId"]),PC="correlativeId",_C=t=>t.length===1&&t[0]===PC,WU=t=>{if(t.kind!==W.UPDATED)return!1;let e=0;for(let n in t.fields){if(n!==PC)return!1;e+=1}return e===1};function EC(t){return{id:t.id,proplannerId:t.proplannerId,source:t.source,target:t.target,lag:t.lag,type:t.type}}var dp=class{activityIds=[];wholeActivityIds=[];renumbered=[];saved=[];hadBaseline=[];addWhole(e){this.activityIds.push(e),this.wholeActivityIds.push(e)}addRenumbered(e,n,r,i){this.activityIds.push(e),this.renumbered.push({id:e,proplannerId:r,correlativeId:n.correlativeId}),this.saved.push(i),this.hadBaseline.push(RC(n))}},na=class t{trackingEnabled;initialized=!1;p6TrackingEnabled=!1;dirtyActivityIds=new Set;renumberedActivityIds=new Set;pendingRenumberings=new WeakMap;savedGeneration={};dirtyLinkIds=new Set;dirtyP6ActivityIds=new Set;p6SettingsDirty=!1;p6ProjectStateDirty=!1;initialCalendarRepairIds=new Set;linksAtLastSave=new Map;activitiesAtLastSave=new Map;p6SettingsAtLastSave=null;currentP6Settings=null;p6ProjectStateAtLastSave=null;currentP6ProjectState=null;p6LatestRunLogAtLastSave=null;currentP6LatestRunLog=null;p6LatestRunLogDirty=!1;p6ActivitiesAtLastSave=new Map;constructor(e=!0){this.trackingEnabled=e}fork(){let e=new t(!1);return e.initialized=this.initialized,e}clone(){let e=new t(this.trackingEnabled);for(let n of this.dirtyActivityIds)e.dirtyActivityIds.add(n);for(let n of this.renumberedActivityIds)e.renumberedActivityIds.add(n);e.pendingRenumberings=this.pendingRenumberings,e.savedGeneration=this.savedGeneration;for(let n of this.dirtyLinkIds)e.dirtyLinkIds.add(n);for(let n of this.dirtyP6ActivityIds)e.dirtyP6ActivityIds.add(n);for(let n of this.initialCalendarRepairIds)e.initialCalendarRepairIds.add(n);for(let[n,r]of this.linksAtLastSave)e.linksAtLastSave.set(n,v(r));for(let[n,r]of this.activitiesAtLastSave)e.activitiesAtLastSave.set(n,v(r));for(let[n,r]of this.p6ActivitiesAtLastSave)e.p6ActivitiesAtLastSave.set(n,v(r));return e.initialized=this.initialized,e.p6TrackingEnabled=this.p6TrackingEnabled,e.p6SettingsDirty=this.p6SettingsDirty,e.p6ProjectStateDirty=this.p6ProjectStateDirty,e.p6LatestRunLogDirty=this.p6LatestRunLogDirty,e.p6SettingsAtLastSave=v(this.p6SettingsAtLastSave),e.currentP6Settings=v(this.currentP6Settings),e.p6ProjectStateAtLastSave=v(this.p6ProjectStateAtLastSave),e.currentP6ProjectState=v(this.currentP6ProjectState),e.p6LatestRunLogAtLastSave=v(this.p6LatestRunLogAtLastSave),e.currentP6LatestRunLog=v(this.currentP6LatestRunLog),e}init(e,n,r=null,i=null,a=null){if(this.trackingEnabled){DC(e,n),this.snapshotActivities(e),this.snapshotLinks(n),this.p6SettingsAtLastSave=v(r),this.currentP6Settings=v(r),this.p6SettingsDirty=!1,this.p6ProjectStateAtLastSave=v(i),this.currentP6ProjectState=v(i),this.p6ProjectStateDirty=!1,this.p6LatestRunLogAtLastSave=v(a),this.currentP6LatestRunLog=v(a),this.p6LatestRunLogDirty=!1,this.p6TrackingEnabled=r!==null,this.p6TrackingEnabled&&this.snapshotP6Activities(e);for(let o of e)if(o.assignedDefaultCalendar){let s=String(o.id);this.initialCalendarRepairIds.add(s),this.dirtyActivityIds.add(s)}this.initialized=!0}}acknowledge(e,n,r=[],i=[],a,o,s=this.currentP6Settings,l=this.currentP6ProjectState,c=this.currentP6LatestRunLog){if(!this.trackingEnabled)return;let d=new Map(r.map(({id:A,proplannerId:g})=>[String(A),g])),u=new Map(i.map(({id:A,proplannerId:g})=>[String(A),g])),p=e.map(A=>({...A,proplannerId:d.get(String(A.id))??A.proplannerId})),y=n.map(A=>{let g=u.get(String(A.id));return g===void 0?{...A}:{...A,proplannerId:g}});if(DC(p,y),this.snapshotActivities(p),this.snapshotLinks(y),this.acknowledgeDataDateState(s,l,c),this.p6TrackingEnabled&&this.snapshotP6Activities(p),!a||!o)return;let f=new Map(a.map(A=>[String(A.id),A])),m=new Map(o.map(A=>[String(A.id),A]));for(let A of p){let g=String(A.id);this.activityIsDirty(g,f.get(g)??null)&&this.dirtyActivityIds.add(g)}for(let A of a){let g=String(A.id);this.activityIsDirty(g,A)&&this.dirtyActivityIds.add(g),this.p6TrackingEnabled&&this.p6ActivityIsDirty(g,A)&&this.dirtyP6ActivityIds.add(g)}if(this.p6TrackingEnabled)for(let A of p){let g=String(A.id);this.p6ActivityIsDirty(g,f.get(g)??null)&&this.dirtyP6ActivityIds.add(g)}for(let A of y){let g=String(A.id);this.linkIsDirty(g,m.get(g)??null)&&this.dirtyLinkIds.add(g)}for(let A of o){let g=String(A.id);this.linkIsDirty(g,A)&&this.dirtyLinkIds.add(g)}}pendingCheckpoint(e){let n=new dp;for(let i of this.dirtyActivityIds)this.collectPending(n,i,e);for(let i of this.dirtyP6ActivityIds)this.dirtyActivityIds.has(i)||n.addWhole(i);let r={activityIds:n.activityIds,linkIds:[...this.dirtyLinkIds],...n.renumbered.length>0?{renumbered:n.renumbered}:{}};return n.renumbered.length>0&&this.pendingRenumberings.set(r,{savedGeneration:this.savedGeneration,wholeActivityIds:n.wholeActivityIds,saved:n.saved,hadBaseline:n.hadBaseline}),{pending:r,wholeActivityIds:n.wholeActivityIds}}collectPending(e,n,r){let i=this.renumberedActivityIds.has(n)?r(n):null,a=this.activitiesAtLastSave.get(n),o=i?.proplannerId;!this.dirtyP6ActivityIds.has(n)&&i!==null&&a!==void 0&&ae(o)?e.addRenumbered(n,i,o,a):e.addWhole(n)}renumberingOf(e){if(e.renumbered===void 0)return null;let n=this.pendingRenumberings.get(e);if(n===void 0)throw new Error("persistence checkpoint with renumbered activities was not read from this schedule");return n}acknowledgePending(e,n,r,i,a,o,s,l,c){if(!this.trackingEnabled)return;let d=new Map(i.map(({id:L,proplannerId:F})=>[String(L),F])),u=new Map(a.map(({id:L,proplannerId:F})=>[String(L),F])),p=new Map(n.map(L=>{let F=String(L.id),T=d.get(F);return[F,T===void 0?L:{...L,proplannerId:T}]})),y=new Map(r.map(L=>{let F=u.get(String(L.id));return[String(L.id),F===void 0?{...L}:{...L,proplannerId:F}]}));for(let L of p.values())ae(L.proplannerId);for(let L of y.values())ae(L.proplannerId);let f=new Set(this.dirtyActivityIds);for(let L of this.dirtyP6ActivityIds)f.add(L);for(let L of e.activityIds)f.add(L);let m=new Set([...this.dirtyLinkIds,...e.linkIds]),A=this.renumberingOf(e),g=A?.savedGeneration===this.savedGeneration,P=this.replaceSavedActivities(A?.wholeActivityIds??e.activityIds,p);A!==null&&this.replaceRenumberedSaves(e.renumbered??[],A,g?null:P),this.replaceSavedLinks(e.linkIds,y),this.acknowledgeDataDateState(s,l,c),this.recheckDirty(f,m,o,P)}replaceSavedActivities(e,n){let r=new Set;for(let i of e){this.initialCalendarRepairIds.delete(i),r.add(i);let a=n.get(i);if(!a||!ae(a.proplannerId)){this.activitiesAtLastSave.delete(i),this.p6ActivitiesAtLastSave.delete(i);continue}this.activitiesAtLastSave.set(i,TC(a,a.proplannerId)),this.p6TrackingEnabled&&this.replaceSavedP6(i,a)}return this.savedGeneration={},r}replaceRenumberedSaves(e,n,r){e.forEach((i,a)=>{let o=n.saved[a];o!==void 0&&(this.initialCalendarRepairIds.delete(i.id),this.activitiesAtLastSave.set(i.id,jU(o,i.correlativeId,n.hadBaseline[a]===!0)),r?.add(i.id))})}replaceSavedP6(e,n){if(n.p6===void 0){this.p6ActivitiesAtLastSave.delete(e);return}this.p6ActivitiesAtLastSave.set(e,v(n.p6))}replaceSavedLinks(e,n){for(let r of e){let i=n.get(r);i&&ae(i.proplannerId)?this.linksAtLastSave.set(r,EC(i)):this.linksAtLastSave.delete(r)}}recheckDirty(e,n,r,i){let a=this.renumberedActivityIds;this.renumberedActivityIds=new Set,this.dirtyActivityIds.clear(),this.dirtyP6ActivityIds.clear(),this.dirtyLinkIds.clear();for(let o of e){let s=r.activity(o);a.has(o)&&!i.has(o)&&this.recordRenumbering(o,s)||this.recheckActivity(o,s),this.p6TrackingEnabled&&this.p6ActivityIsDirty(o,s)&&this.dirtyP6ActivityIds.add(o)}for(let o of n)this.linkIsDirty(o,r.link(o))&&this.dirtyLinkIds.add(o)}recheckActivity(e,n){let r=this.activitiesAtLastSave.get(e);if(!(n!==null&&r!==void 0&&!this.initialCalendarRepairIds.has(e)&&ae(n.proplannerId))){this.activityIsDirty(e,n)&&this.dirtyActivityIds.add(e);return}let a=He(n,r.persistable);a.length!==0&&(this.dirtyActivityIds.add(e),_C(a)&&this.renumberedActivityIds.add(e))}acknowledgeDataDateState(e,n,r){this.p6SettingsAtLastSave=v(e),this.p6SettingsDirty=Qn(this.currentP6Settings,this.p6SettingsAtLastSave),this.p6ProjectStateAtLastSave=v(n),this.p6ProjectStateDirty=Qn(this.currentP6ProjectState,this.p6ProjectStateAtLastSave),this.p6LatestRunLogAtLastSave=v(r),this.p6LatestRunLogDirty=Qn(this.currentP6LatestRunLog,this.p6LatestRunLogAtLastSave)}snapshotActivities(e){if(this.trackingEnabled){this.savedGeneration={},this.activitiesAtLastSave.clear(),this.dirtyActivityIds.clear(),this.renumberedActivityIds.clear(),this.initialCalendarRepairIds.clear();for(let n of e){let r=String(n.id);if(!ae(n.proplannerId)){this.dirtyActivityIds.add(r);continue}let i=TC(n,n.proplannerId);this.activitiesAtLastSave.set(String(n.id),i),$a(n,i.persistable)&&this.dirtyActivityIds.add(r)}}}snapshotLinks(e){if(this.trackingEnabled){this.linksAtLastSave.clear(),this.dirtyLinkIds.clear();for(let n of e){let r=String(n.id);if(!ae(n.proplannerId)){this.dirtyLinkIds.add(r);continue}this.linksAtLastSave.set(String(n.id),EC(n))}}}recordChanges(e,n,r,i,a){if(!(!this.trackingEnabled||!this.initialized)){for(let o of e){let s=String(o.id),l=r(s);a!==void 0&&!a.has(s)&&WU(o)&&this.recordRenumbering(s,l)||this.recordActivityChange(s,l)}for(let o of n){let s=String(o.id),l=i(s);this.linkIsDirty(s,l)?this.dirtyLinkIds.add(s):this.dirtyLinkIds.delete(s)}}}recordActivityChange(e,n){this.renumberedActivityIds.delete(e),this.activityIsDirty(e,n)?this.dirtyActivityIds.add(e):this.dirtyActivityIds.delete(e),this.p6TrackingEnabled&&(this.p6ActivityIsDirty(e,n)?this.dirtyP6ActivityIds.add(e):this.dirtyP6ActivityIds.delete(e))}recordRenumbering(e,n){let r=!this.dirtyActivityIds.has(e)||this.renumberedActivityIds.has(e),i=this.activitiesAtLastSave.get(e);return!r||n===null||i===void 0?!1:(n.correlativeId??null)===(i.persistable.correlativeId??null)?(this.dirtyActivityIds.delete(e),this.renumberedActivityIds.delete(e),!0):(this.dirtyActivityIds.add(e),this.renumberedActivityIds.add(e),!0)}recordP6Settings(e){!this.trackingEnabled||!this.initialized||(this.currentP6Settings=v(e),this.p6SettingsDirty=Qn(this.currentP6Settings,this.p6SettingsAtLastSave))}recordP6ProjectState(e){!this.trackingEnabled||!this.initialized||(this.currentP6ProjectState=v(e),this.p6ProjectStateDirty=Qn(this.currentP6ProjectState,this.p6ProjectStateAtLastSave))}recordP6LatestRunLog(e){!this.trackingEnabled||!this.initialized||(this.currentP6LatestRunLog=v(e),this.p6LatestRunLogDirty=Qn(this.currentP6LatestRunLog,this.p6LatestRunLogAtLastSave))}modifiedP6Settings(){return this.p6SettingsIsDirty()?v(this.currentP6Settings):null}modifiedP6LatestRunLog(){return this.p6LatestRunLogDirty?{latestRunLog:v(this.currentP6LatestRunLog)}:null}modifiedP6Activities(e){return!this.trackingEnabled||!this.initialized?new Map:VI(this.dirtyP6ActivityIds,e)}activityIsDirty(e,n){let r=this.activitiesAtLastSave.get(e);return n===null?r!==void 0:this.initialCalendarRepairIds.has(e)||!ae(n.proplannerId)||r===void 0||$a(n,r.persistable)}linkIsDirty(e,n){let r=this.linksAtLastSave.get(e);return n===null?r!==void 0:!ae(n.proplannerId)||r===void 0||hl(r,n)}acknowledgePersistedLookahead(e,n){if(!this.trackingEnabled||!this.initialized)return;let r=e.map(i=>{let a=typeof i=="string"?i:String(i.id),o=n(a),s=this.activitiesAtLastSave.get(a);if(o===null||s===void 0)throw new Error(`unknown persisted activity "${a}"`);return{activityId:a,acknowledgesLookahead:typeof i=="string"||!!i.fields?.isLookahead,acknowledgesProgress:typeof i!="string"&&!!i.fields?.progress,current:o,saved:s}});for(let{activityId:i,acknowledgesLookahead:a,acknowledgesProgress:o,current:s,saved:l}of r){let c={...l.persistable,...a?{isLookahead:s.isLookahead}:{},...o?{progress:s.progress,autoScheduling:s.autoScheduling}:{}};this.activitiesAtLastSave.set(i,{...l,persistable:c}),this.savedGeneration={},this.renumberedActivityIds.delete(i),this.initialCalendarRepairIds.has(i)||!ae(s.proplannerId)||$a(s,c)?this.dirtyActivityIds.add(i):this.dirtyActivityIds.delete(i)}}hasCheckpointActivityId(e){return this.activitiesAtLastSave.has(e)}knowsPersistedActivity(e){return!this.trackingEnabled||this.activitiesAtLastSave.has(e)}hasCheckpointLinkId(e){return this.linksAtLastSave.has(e)}rebaseBaseline(e,n){return{activities:e.map(r=>{let i=this.p6ActivitiesAtLastSave.get(String(r.id));return i===void 0?r:{...r,p6:v(i)}}),links:n,p6Settings:v(this.p6SettingsAtLastSave),p6ProjectState:v(this.p6ProjectStateAtLastSave),p6LatestRunLog:v(this.p6LatestRunLogAtLastSave)}}checkpointActivity(e){return this.activitiesAtLastSave.get(e)?.persistable??null}checkpointLink(e){return this.linksAtLastSave.get(e)??null}checkpointActivityIds(){return[...this.activitiesAtLastSave.keys()]}checkpointLinkIds(){return[...this.linksAtLastSave.keys()]}tracksPersistence(){return this.trackingEnabled}hasUnsavedChanges(){return this.trackingEnabled&&this.initialized&&(this.dirtyActivityIds.size>0||this.dirtyLinkIds.size>0||this.p6TrackingEnabled&&(this.dirtyP6ActivityIds.size>0||this.p6SettingsIsDirty()||this.p6ProjectStateDirty||this.p6LatestRunLogDirty))}p6SettingsIsDirty(){return this.p6SettingsDirty}snapshotP6Activities(e){this.dirtyP6ActivityIds.clear(),BI(this.p6ActivitiesAtLastSave,e)}p6ActivityIsDirty(e,n){return jI(this.p6ActivitiesAtLastSave.get(e),n)}newActivities(e){if(!this.trackingEnabled||!this.initialized)return[];let n=[];for(let r of this.dirtyActivityIds){let i=e(r);i!==null&&!ae(i.proplannerId)&&n.push(i)}return n}newLinks(e){if(!this.trackingEnabled||!this.initialized)return[];let n=[];for(let r of this.dirtyLinkIds){let i=e(r);i!==null&&!ae(i.proplannerId)&&n.push(i)}return n}deletedActivities(e){if(!this.trackingEnabled||!this.initialized)return[];let n=[];for(let r of this.dirtyActivityIds){let i=this.activitiesAtLastSave.get(r);i&&e(r)===null&&n.push({...i.deletedSnapshot})}return n}deletedLinks(e){if(!this.trackingEnabled||!this.initialized)return[];let n=[];for(let r of this.dirtyLinkIds){let i=this.linksAtLastSave.get(r);i&&e(r)===null&&n.push({...i})}return n}modifiedActivities(e){if(!this.trackingEnabled||!this.initialized)return[];let n=[];for(let r of this.dirtyActivityIds){let i=e(r);if(i===null||!ae(i.proplannerId))continue;let a=this.activitiesAtLastSave.get(r);(a===void 0||this.initialCalendarRepairIds.has(r)||$a(i,a.persistable))&&n.push(i)}return n}modifiedActivityFields(e){let n=new Map;if(!this.trackingEnabled||!this.initialized)return n;for(let r of this.dirtyActivityIds){let i=e(r),a=this.activitiesAtLastSave.get(r);if(!i||!a)continue;let o=He(i,a.persistable);o.length>0&&n.set(r,o)}return n}isModifiedSince(e,n,r){return n===void 0||this.initialCalendarRepairIds.has(e)||r.length>0}changedFieldsSinceSave(e,n,r){return this.renumberedActivityIds.has(e)?VU:r===void 0?[]:He(n,r.persistable)}modifiedActivityChanges(e){let n=[],r=new Map,i=[];if(!this.trackingEnabled||!this.initialized)return{activities:n,fields:r,renumbered:i};for(let a of this.dirtyActivityIds){let o=e(a);if(o===null)continue;let s=this.activitiesAtLastSave.get(a),l=this.changedFieldsSinceSave(a,o,s),c=o.proplannerId,d=ae(c);if(d&&_C(l)){i.push({id:a,proplannerId:c,correlativeId:o.correlativeId});continue}l.length>0&&r.set(a,l),d&&this.isModifiedSince(a,s,l)&&n.push(o)}return{activities:n,fields:r,renumbered:i}}modifiedLinks(e){if(!this.trackingEnabled||!this.initialized)return[];let n=[];for(let r of this.dirtyLinkIds){let i=e(r);if(i===null||!ae(i.proplannerId))continue;let a=this.linksAtLastSave.get(r);(a===void 0||hl(a,i))&&n.push(i)}return n}clear(){this.initialized=!1,this.savedGeneration={},this.p6TrackingEnabled=!1,this.dirtyActivityIds.clear(),this.renumberedActivityIds.clear(),this.dirtyLinkIds.clear(),this.dirtyP6ActivityIds.clear(),this.initialCalendarRepairIds.clear(),this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear(),this.p6ActivitiesAtLastSave.clear(),this.p6SettingsAtLastSave=null,this.currentP6Settings=null,this.p6SettingsDirty=!1,this.p6ProjectStateAtLastSave=null,this.currentP6ProjectState=null,this.p6ProjectStateDirty=!1}};function up(t,e){let n=new Map(t.map(o=>[String(o.id),o])),r=new Map(e.map(o=>[String(o.id),o])),i=[...new Set([...n.keys(),...r.keys()])].sort(),a=[];for(let o of i){let s=r.get(o),l=n.get(o);if(l===void 0){a.push({id:o,kind:W.DELETED,after:null});continue}if(s===void 0){a.push({id:o,kind:W.CREATED,after:v(l)});continue}let c=KU(s,l);Object.keys(c).length>0&&a.push({id:o,kind:W.UPDATED,fields:c,after:v(l)})}return a}function KU(t,e){let n={},r=[...new Set([...Object.keys(t),...Object.keys(e)])].sort();for(let i of r)$t(t[i])!==$t(e[i])&&(n[i]={before:v(t[i]),after:v(e[i])});return n}function YU(t,e){let n=new Set(e.selectedIds.map(String)),r=new Set(t.selectedIds.map(String)),i=new Set(e.hiddenIds.map(String)),a=new Set(t.hiddenIds.map(String)),o=t.activities.map(({id:l})=>String(l)).sort(),s=[];for(let l of o){let c=n.has(l),d=r.has(l),u=!i.has(l),p=!a.has(l);c===d&&u===p||s.push({activityId:l,...c===d?{}:{checked:{before:c,after:d}},...u===p?{}:{visible:{before:u,after:p}}})}return s}function pp(t,e){let n=$t(t.order)!==$t(e.order);return{source:{kind:ce.INIT},activities:up(t.activities,e.activities),links:up(t.links,e.links),calendars:up(t.calendars,e.calendars),trackingEvents:[],effects:[],viewState:YU(t,e),...n?{order:v(t.order)}:{}}}function kC(t){let e=t.state.fork(),n=v(t.sector),r=t.history.fork(),i=t.persistence.clone(),a=t.activityIds.snapshot(),o=t.linkIds.snapshot(),s=t.correlatives.snapshot(),l=t.customIds.captureRestorePoint();return{history:r,persistence:i,restore:()=>{t.state.restoreFork(e);for(let c of Object.keys(t.sector))Object.hasOwn(n,c)||Reflect.deleteProperty(t.sector,c);Object.assign(t.sector,n),t.scheduler.invalidateAllCaches(),t.activityIds.restore(a),t.linkIds.restore(o),t.correlatives.restore(s),l()}}}function bC(t,e){let n=t.find(r=>r.type===U.PROJECT);if(n!==void 0)return n.calendarId;for(let r of e)if(r.is_default)return r.id;return null}function LC(t,e,n){let r=n.getCalendar(e);return r===null?null:Jl(t,r)}var yp=Symbol("ScheduleCore.fork.source"),GU=100;function qU(t){if(!Number.isInteger(t.offset)||t.offset<0)throw new RangeError("Ending activity offset must be a non-negative integer");if(!Number.isInteger(t.limit)||t.limit<1||t.limit>GU)throw new RangeError("Ending activity limit must be an integer from 1 to 100")}var fp=Symbol("ScheduleCore.snapshot.source");function $U(t){return{source:t,activities:[],links:[],calendars:[],trackingEvents:[]}}function zU(t,e,n){if(t.kind===I.PERSISTENCE_ACKNOWLEDGE)return{checkpoint:t.checkpoint,historyBoundary:t.checkpoint?.historyBoundary,persistedActivities:t.activities,persistedLinks:t.links,clearsHistory:!1,retainsHistory:t.retainHistory===!0};if(t.kind===I.PERSISTENCE_REBASE){let r=e.__rebaseCheckpoint;if(r===void 0)throw new Error("rebase-on-success requires a rebase checkpoint");return{checkpoint:n.rebaseBaseline(r.activities,r.links),historyBoundary:void 0,persistedActivities:void 0,persistedLinks:void 0,clearsHistory:!0,retainsHistory:!1}}throw new Error("checkpoint-on-success requires persistence acknowledge")}function JU(t){return t.kind===I.PERSISTENCE_ACKNOWLEDGE||t.kind===I.PERSISTENCE_REBASE||t.kind===I.ACTIVITY_LOOKAHEAD_SYNC&&t.acknowledgePersistedLookahead===!0}function XU(t){for(let e of t.activities)if(e.kind===W.DELETED||e.kind===W.UPDATED&&e.fields!==void 0&&"parentId"in e.fields)return!0;return!1}function ZU(t,e){let n=[];for(let r of t.activities){let i=e.getActivity(r.id);if(i===null)return null;n.push(i)}return n}function QU(t,e,n){if(t===null||t.filter!==e)return!1;let r=t.context.hoursPerDay===n.hoursPerDay,i=t.context.locale===n.locale;return r&&i}var ra=class t{activities;cells;links;calendars;selection;view;baselines;impactRequests;persistence;history;projection;criticalPath;diagnostics;dataDates=iS({getSettings:()=>this._getP6Settings(),getProjectState:()=>this._getP6ProjectState(),getLatestRunLog:()=>this._getP6LatestRunLog(),getScheduleStateFingerprint:()=>this._getP6ScheduleStateFingerprint(),getDefaultSettings:()=>v(ta()),getScheduleReadiness:e=>this._getP6ScheduleReadiness(e),searchEndingActivities:e=>this._searchP6EndingActivities(e),getEndingActivityOption:e=>this._getP6EndingActivityOption(e),resolveMustFinishByDefault:e=>this._resolveP6MustFinishByDefault(e),updateSettings:e=>this._updateP6Settings(e),updateActivity:(e,n,r)=>this._updateP6Activity(e,n,r?.at),schedule:(e,n)=>this._scheduleP6(e,n?.at)});_activityClipboard={value:null};_cellClipboard={value:null};_status=Ve.READY;coreRuntime;_isFork;_undo=new sc;_opQueue=Promise.resolve();_scheduleRevision=0;_stateRevision=0;_canonicalFingerprintCache=null;_p6ScheduleStateFingerprintCache=null;_pendingScheduleRevision=0;_criticalPathRevision=-1;_criticalPathUsesDataDate=!1;_activeCriticalPath=null;constructor(e){if(Object.assign(this,Tp(this)),fp in e){let{snapshot:i,options:a}=e[fp];this._isFork=!1,this.coreRuntime=Yv(i,a),this._saveTracker=new na(a.trackPersistence!==!1),this._retainCriticalPathResult=a.retainCriticalPathResult!==!1,this._lastOperationAt=i.lastOperationAt,i.criticalPathSettled&&(this._criticalPathRevision=this._scheduleRevision),this._initPromise=Promise.resolve().then(()=>this._initSaveTracker()),this._criticalPathReady=this._trackCriticalPathJob(this._initPromise.then(()=>this._startCriticalPathForCurrentRevision())),this._ready=this._initPromise;return}if(yp in e){this._isFork=!0;let i=e[yp],a=i.coreRuntime.state.fork();this.coreRuntime={state:a,scheduler:new Mn(a,i.coreRuntime.reporter),sector:v(i.coreRuntime.sector),activityIdGenerator:i.coreRuntime.activityIdGenerator.fork(),linkIdGenerator:i.coreRuntime.linkIdGenerator.fork(),uniqueCorrelativeIdGenerator:i.coreRuntime.uniqueCorrelativeIdGenerator.fork(),customIdTracker:i.coreRuntime.customIdTracker.fork(),calendars:new Map(Array.from(i.coreRuntime.calendars,([o,s])=>[o,v(s)])),baseCalendars:v(i.coreRuntime.baseCalendars),clock:i.coreRuntime.clock,reporter:i.coreRuntime.reporter,loadDiagnostics:i.coreRuntime.loadDiagnostics,externalRelationshipIds:v(i.coreRuntime.externalRelationshipIds),dataDateCapability:i.coreRuntime.dataDateCapability},this._activityClipboard.value=v(i._activityClipboard.value),this._cellClipboard.value=v(i._cellClipboard.value),this._undo=i._undo.fork(),this._saveTracker=i._saveTracker.fork(),this._retainCriticalPathResult=i._retainCriticalPathResult,this._lastOperationAt=i._lastOperationAt,this._scheduleRevision=i._scheduleRevision,this._stateRevision=i._stateRevision,this._canonicalFingerprintCache=i._canonicalFingerprintCache,this._p6ScheduleStateFingerprintCache=i._p6ScheduleStateFingerprintCache,this._pendingScheduleRevision=i._scheduleRevision,this._criticalPathRevision=i._criticalPathRevision,this._criticalPathUsesDataDate=i._criticalPathUsesDataDate,this._initPromise=Promise.resolve(),this._criticalPathReady=Promise.resolve(null),this._ready=this._initPromise;return}this._isFork=!1,this._saveTracker=new na(e.trackPersistence!==!1),this._retainCriticalPathResult=e.retainCriticalPathResult!==!1;let n=Wv(e);this.coreRuntime={state:n.state,scheduler:n.scheduler,sector:n.sector,activityIdGenerator:n.activityIdGen,linkIdGenerator:n.linkIdGen,uniqueCorrelativeIdGenerator:n.uidGen,customIdTracker:n.customIdTracker,clock:n.clock,calendars:new Map(n.calendars.map(i=>[i.id,i])),baseCalendars:n.baseCalendars,reporter:n.reporter,loadDiagnostics:n.loadDiagnostics,externalRelationshipIds:v(n.externalRelationshipIds),dataDateCapability:n.dataDateCapability},this._initPromise=n.initPromise.then(()=>this._initSaveTracker()),this._criticalPathReady=this._trackCriticalPathJob(this._initPromise.then(()=>this._startCriticalPathForCurrentRevision()));let r=e.criticalPathOnLoad===!0;this._ready=r?this._criticalPathReady.then(()=>{}):this._initPromise}_initSaveTracker(){this._status!==Ve.DESTROYED&&this._saveTracker.init(this.coreRuntime.state.getAllActivities(),this.getAllLinksView(),this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.dataDateProjectState(),this.coreRuntime.state.dataDateLatestRunLog())}exportSnapshot(){return this._enqueue(async()=>(this.assertReady(),{version:np,...Kv(this.coreRuntime),criticalPathSettled:this.isCriticalPathSettled(),lastOperationAt:this._lastOperationAt?new Date(this._lastOperationAt):null}))}static fromSnapshot(e,n={}){return new t({[fp]:{snapshot:e,options:n}})}get ready(){return this._ready}fork(){return this._enqueue(async()=>(await this._ready,this.assertReady(),new t({[yp]:this})))}get criticalPathReady(){let e=this._criticalPathReady;return e.then(()=>this._releaseCriticalPathResult(e),()=>{}),e}_trackCriticalPathJob(e){return e.then(()=>{this._criticalPathReady===e&&(this._retainCriticalPathResult?this._settledCriticalPathJob=e:this._criticalPathReady=Promise.resolve(null))},()=>{}),e}_releaseCriticalPathResult(e){this._criticalPathReady===e&&(this._criticalPathReady=Promise.resolve(null),this._settledCriticalPathJob=null)}get status(){return this._status}getSector(){return v(this.coreRuntime.sector)}getLoadDiagnostics(){return this.assertReady(),this.coreRuntime.loadDiagnostics()}getActivityView(e){return this.assertReady(),yo(this.coreRuntime.state,e)}calculateCalendarEndDate(e){this.assertReady();let n=this.coreRuntime.state.getActivity(e.activityId);return n?this.coreRuntime.state.calculateEndDate({startDate:e.startDate,durationHours:e.durationHours,task:n}):null}calculateCalendarDuration(e){this.assertReady();let n=this.coreRuntime.state.getActivity(e.activityId);return n?this.coreRuntime.state.calculateDuration({startDate:e.startDate,endDate:e.endDate,task:n}):null}getClosestCalendarWorkTime(e){this.assertReady();let n=this.coreRuntime.state.getActivity(e.activityId);return n?this.coreRuntime.state.getClosestWorkTime({date:e.date,dir:e.direction,task:n}):null}getProgressEditability(e){this.assertReady();let n=yo(this.coreRuntime.state,e);if(!n)return null;let r=ic(this.coreRuntime.state,{calendars:this.coreRuntime.calendars,hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat});return gi.canEdit(n,r.hierarchy)}getDateGestureEditability(e,n){this.assertReady();let r=yo(this.coreRuntime.state,e);return r?Lr(r.p6,this.coreRuntime.state.dataDateSettings(),n,this.coreRuntime.state.isDataDateEnabled()):null}getColumnEditability(e,n){this.assertReady();let r=yo(this.coreRuntime.state,e),i=he(n);if(!r||!i)return null;let a=ic(this.coreRuntime.state,{calendars:this.coreRuntime.calendars,hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat});return Qs(i.canEdit(r,a.hierarchy),r,this._getP6Settings(),n,this.coreRuntime.state.isDataDateEnabled())}createDateGesturePreview(e){this.assertReady();let n=this._scheduleRevision;return Tm(this.coreRuntime.state,e,()=>{if(this.assertReady(),this._scheduleRevision!==n)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),Gv(this.coreRuntime.state)}getIndentTargetParentIds(e){this.assertReady();let n=Mi(e.map(r=>String(r)),this.coreRuntime.state);return[...new Set(n.allowedMoves.map(r=>String(r.newParentId)))]}getLeafParentIdsPromotedBy(e){return this.assertReady(),Zm(e,this.coreRuntime.state,this._activityClipboard.value!==null)}getLookaheadConfirmation(e,n={}){return this.assertReady(),Qm(e,n,this.coreRuntime.state,this._activityClipboard.value!==null)}getChildrenView(e){return this.assertReady(),zv(this.coreRuntime.state,e)}getLinkView(e){return this.assertReady(),ip(this.coreRuntime.state,e)}getLinksForActivityView(e){this.assertReady();let n=this.coreRuntime.state,r=[],i=new Set,a=o=>{if(i.has(o))return;i.add(o);let s=ip(n,o);s&&r.push(s)};for(let o of n.getOutgoingLinkIds(e))a(o);for(let o of n.getIncomingLinkIds(e))a(o);return r}getAllLinksView(){return this.assertReady(),Zv(this.coreRuntime.state)}auditEffectiveGraph(){this.assertReady();let e=this.coreRuntime.state,n=e.getAllLinks(),r=Fn(e,n),i=li(r),a=0;for(let o of i)o.length>a&&(a=o.length);return{activityCount:e.getAllIds().length,logicalLinkCount:n.length,effectiveEdgeCount:r.length,circularComponents:i,largestComponentSize:a}}getProperty(e,n){this.assertReady();let r=this.coreRuntime.state.getActivity(e);return r?v(r[n]):null}getAllIds(){return this.assertReady(),qv(this.coreRuntime.state)}forEachActivityId(e){this.assertReady(),$v(this.coreRuntime.state,e)}getChildrenIds(e){return this.assertReady(),rp(this.coreRuntime.state,e)}getSelectedActivityIds(){return this.assertReady(),Jv(this.coreRuntime.state)}getActivityClipboardView(){return this.assertReady(),v(this._activityClipboard.value)}getHiddenActivityIds(){return this.assertReady(),this.coreRuntime.state.hiddenIds().map(String)}getVisibleActivityIds(){this.assertReady();let e=new Set(this.coreRuntime.state.hiddenIds().map(String));return this.coreRuntime.state.getAllIds().map(String).filter(n=>!e.has(n))}getActiveFilter(){return this.assertReady(),v(this.coreRuntime.state.getActiveFilter())}getActiveOrder(){return this.assertReady(),v(this.coreRuntime.state.getActiveOrder())}getVisualOrderIds(){return this.assertReady(),[...this.coreRuntime.state.getVisualOrderIds()]}getVisualRows(){return this.assertReady(),[...this.coreRuntime.state.getVisualRows()]}getActiveGroup(){return this.assertReady(),v(this.coreRuntime.state.getGroup())}getWbsDepth(){return this.assertReady(),this.coreRuntime.state.getWbsDepth()}hasChild(e){return this.assertReady(),Xv(this.coreRuntime.state,e)}getCalendar(e){this.assertReady();let n=this.coreRuntime.calendars.get(e);return n?v(n):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),e=>v(e))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(e=>v(e))}isCustomIdInUse(e,n=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(e,n)}getProjectWorkHours(){return this.assertReady(),Qv(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(e=>this.coreRuntime.state.getLink(e)).map(v)}getNewLinks(){return this.assertReady(),this._saveTracker.newLinks(e=>this.coreRuntime.state.getLink(e)).map(v)}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(e=>this.coreRuntime.state.getActivity(e)).map(La)}getModifiedActivityFields(){return this.assertReady(),this._saveTracker.modifiedActivityFields(e=>this.coreRuntime.state.getActivity(e))}getModifiedActivityChanges(){this.assertReady();let e=this._saveTracker.modifiedActivityChanges(n=>this.coreRuntime.state.getActivity(n));return{...e,activities:e.activities.map(La)}}getNewActivities(){return this.assertReady(),this._saveTracker.newActivities(e=>this.coreRuntime.state.getActivity(e)).map(La)}hasUnsavedChanges(){return this.assertReady(),this._saveTracker.hasUnsavedChanges()}getModifiedDataDateSettings(){return this.assertReady(),this._saveTracker.modifiedP6Settings()}getModifiedDataDateLatestRunLog(){return this.assertReady(),this._saveTracker.modifiedP6LatestRunLog()}getModifiedDataDateActivities(){return this.assertReady(),this._saveTracker.modifiedP6Activities(e=>this.coreRuntime.state.getActivity(e))}getScheduleRevision(){return this._scheduleRevision}getStateRevision(){return this._stateRevision}capturePersistenceHistoryBoundary(){return this.assertReady(),this._undo.capturePersistenceBoundary()}readPersistenceCheckpoint(e={}){this.assertReady();let n=e.pendingOnly?this._saveTracker.pendingCheckpoint(r=>this.coreRuntime.state.getActivity(r)):null;return{...n?{activities:n.wholeActivityIds.flatMap(r=>{let i=this.coreRuntime.state.getActivity(r);return i?[La(i)]:[]}),links:n.pending.linkIds.flatMap(r=>{let i=this.getLinkView(r);return i?[i]:[]}),pending:n.pending}:{activities:this.getAllActivitiesView(),links:this.getAllLinksView()},historyBoundary:this.capturePersistenceHistoryBoundary(),...this.coreRuntime.dataDateCapability?.checkpoint(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.dataDateProjectState()),...this.coreRuntime.dataDateCapability===null?{}:{p6LatestRunLog:v(this.coreRuntime.state.dataDateLatestRunLog())}}}getCanonicalDigest(){this.assertReady();let e=(i,a)=>String(i.id).localeCompare(String(a.id)),n=this._getP6Settings(),r=this._getP6ProjectState();return $t({sector:this.getSector(),activities:[...this.coreRuntime.state.getAllActivities()].sort(e),links:[...this.getAllLinksView()].sort(e),calendars:[...this.getAllCalendars()].sort(e),baseCalendars:[...this.getBaseCalendars()].sort(e),...n===null?{}:{p6Settings:n,p6ProjectState:r}})}getReplicaFingerprint(){this.assertReady();let e=new cc,n=(i,a)=>{let o=[...i].sort((s,l)=>{let c=String(s.id),d=String(l.id);return c<d?-1:c>d?1:0});e.add(o.length);for(let s of o)e.add(s,a)};e.add(this.getSector()),n(this.coreRuntime.state.getAllActivities(),"proplannerId"),n(this.getAllLinksView(),"proplannerId"),n(this.getAllCalendars()),n(this.getBaseCalendars());let r=this._getP6Settings();return e.add(r),r!==null&&e.add(this._getP6ProjectState()),e.digest()}getCanonicalFingerprint(){if(this._canonicalFingerprintCache?.stateRevision===this._stateRevision)return this._canonicalFingerprintCache.value;let e=bu(this.getCanonicalDigest());return this._canonicalFingerprintCache={stateRevision:this._stateRevision,value:e},e}_getP6ScheduleStateFingerprint(){if(this._p6ScheduleStateFingerprintCache?.stateRevision===this._stateRevision)return this._p6ScheduleStateFingerprintCache.value;let e=this._computeP6ScheduleStateFingerprint();return this._p6ScheduleStateFingerprintCache={stateRevision:this._stateRevision,value:e},e}_computeP6ScheduleStateFingerprint(){let e=(i,a)=>String(i.id).localeCompare(String(a.id)),n=[...this.getAllActivitiesView()].sort(e).map(({criticalPath:i,freeSlackHours:a,isCritical:o,...s})=>this.coreRuntime.dataDateCapability?.fingerprintActivity(s)??s);return bu($t({sector:this.getSector(),activities:n,links:[...this.getAllLinksView()].sort(e).map(({freeSlackHours:i,isCritical:a,...o})=>o),calendars:[...this.getAllCalendars()].sort(e),baseCalendars:[...this.getBaseCalendars()].sort(e),p6Settings:this._getP6Settings(),p6ProjectState:this._getP6ProjectState()}))}createProjectionChangeSetFrom(e){this.assertReady(),e.assertReady();let n=pp(this._snapshotProjection(),e._snapshotProjection()),r=this.coreRuntime.dataDateCapability??e.coreRuntime.dataDateCapability;return{...n,...r?.reconcile({settings:this.coreRuntime.state.dataDateSettings(),projectState:this.coreRuntime.state.dataDateProjectState()},{settings:e.coreRuntime.state.dataDateSettings(),projectState:e.coreRuntime.state.dataDateProjectState()})}}_snapshotProjection(){return{activities:this.getAllActivitiesView(),links:this.getAllLinksView(),calendars:this.getAllCalendars(),selectedIds:this.getSelectedActivityIds(),hiddenIds:this.getHiddenActivityIds(),order:Pn(this.coreRuntime.state)}}getDeletedActivitiesSinceLastSave(){return this.assertReady(),this._saveTracker.deletedActivities(e=>this.coreRuntime.state.getActivity(e)).map(v)}getDeletedLinksSinceLastSave(){return this.assertReady(),this._saveTracker.deletedLinks(e=>this.coreRuntime.state.getLink(e)).map(v)}_enqueue(e){let n=this._opQueue.then(e,e);return this._opQueue=n.then(()=>{},()=>{}),n}_getP6Settings(){return this.assertReady(),v(this.coreRuntime.state.dataDateSettings())}_getP6ProjectState(){return this.assertReady(),v(this.coreRuntime.state.dataDateProjectState())}_getP6LatestRunLog(){return this.assertReady(),v(this.coreRuntime.state.dataDateLatestRunLog())}_resolveP6MustFinishByDefault(e){this.assertReady();let n=bC(this.coreRuntime.state.getAllActivities(),this.coreRuntime.calendars.values());return LC(e,n,this.coreRuntime.state.calendarReader)}_searchP6EndingActivities(e){this.assertReady(),qU(e);let n=e.query.trim().toLowerCase(),r=[],i=0;for(let a of this.coreRuntime.state.getVisualOrderIds()){let o=this._getP6EndingActivityOption(a);if(!(!o||!o.label.toLowerCase().includes(n))&&!(i++<e.offset)){if(r.length===e.limit)return{items:r,hasMore:!0};r.push(o)}}return{items:r,hasMore:!1}}_getP6EndingActivityOption(e){this.assertReady();let n=this.coreRuntime.state.getActivity(e);if(!n)return null;let r=n.customId?.trim()||n.uniqueCorrelativeId||String(n.correlativeId);return{id:n.id,label:`${r} \u2014 ${n.name}`}}_getP6ScheduleReadiness(e){this.assertReady();let n=this.coreRuntime.dataDateCapability;return n===null||!this.coreRuntime.state.isDataDateEnabled()?{ready:!1,code:"capability_not_enabled",count:0,sampleActivityIds:[],missingInputs:[]}:n.scheduleReadiness({settings:this.coreRuntime.state.dataDateSettings(),externalRelationshipIds:this.coreRuntime.externalRelationshipIds,patch:e,activities:this.coreRuntime.state.getAllActivities(),projectState:this.coreRuntime.state.dataDateProjectState()})}_updateP6Settings(e){let n=this._admitScheduleMutation(),r=!1,i=!1,a=this._enqueue(async()=>{try{this.assertReady();let o=this._requireDataDateCapability().prepareSettingsUpdate(this.coreRuntime.state.dataDateSettings(),e),{before:s,after:l}=o,c={kind:ce.P6_SETTINGS_UPDATE};if(!o.changed)return{changes:{source:c,activities:[],links:[],calendars:[],trackingEvents:[]}};let d=this._requireDataDateCapability(),u=d.prepareLiveDerived(this.coreRuntime.state,s,l,{adoptExpectedFinish:!0,enabled:this.coreRuntime.state.isDataDateEnabled()}),p=[...u.keys()],y=new Map(p.flatMap(m=>{let A=this.coreRuntime.state.getActivity(m);return A===null?[]:[[m,st(A)]]}));this.coreRuntime.state.beginWriteCapture();let f;try{this.coreRuntime.state.setDataDateSettings(l),d.applyLiveDerived(this.coreRuntime.state,u),f={...await tt(this.coreRuntime.state,{source:c,beforeSnap:y,touchedIds:p,scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay}),p6Settings:{before:s,after:l}}}catch(m){throw this._rollback(),m}finally{this.coreRuntime.state.endWriteCapture()}return this._undo.record(ea(fo(f))),this._saveTracker.recordChanges(f.activities,f.links,m=>this.coreRuntime.state.getActivity(m),m=>this.coreRuntime.state.getLink(m)),this._saveTracker.recordP6Settings(l),i=At(s)&&l.dataDate===null,this._recordDirectScheduleMutation(!i&&this.coreRuntime.state.isDataDateEnabled()),r=!0,{changes:f}}finally{this._settleScheduleMutation(n,r)}});return a.then(()=>{i&&this.recomputeCriticalPath().catch(o=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after Data Date deactivation failed",o)})},()=>{}),a}_updateP6Activity(e,n,r){let i=this._admitScheduleMutation(),a=!1;return this._enqueue(async()=>{try{this.assertReady();let o=this._requireDataDateCapability(),s=o.requireSettings(this.coreRuntime.state.dataDateSettings()),l=this.coreRuntime.state.getActivity(e);if(l?.p6===void 0)throw new Error(`P6 activity ${e} does not exist`);let c=o.prepareActivityUpdate(l.p6,n,l.constraintType),d=this.coreRuntime.state.calendarReader.getCalendar(l.calendarId),u=At(s,this.coreRuntime.state.isDataDateEnabled())&&d!==null?o.projectLocalActivity(l.p6,c.next,{calendar:d,dataDate:s.dataDate,totalFloatMethod:s.totalFloatMethod}):{p6:c.next};if(!c.changed)return{changes:{source:{kind:ce.P6_ACTIVITY_UPDATE},activities:[],links:[],calendars:[],trackingEvents:[]}};let p=new Map([[e,st(l)]]);this.coreRuntime.state.beginWriteCapture();let y,f=null,m=null;try{if(this.coreRuntime.state.setActivityField(e,"p6",u.p6),u.startDate!==void 0&&this.coreRuntime.state.setActivityField(e,"startDate",u.startDate),u.endDate!==void 0&&this.coreRuntime.state.setActivityField(e,"endDate",u.endDate),At(s,this.coreRuntime.state.isDataDateEnabled())&&s.scheduleAutomaticallyOnDateChange){f=o.prepareSchedule({state:this.coreRuntime.state,settings:this.coreRuntime.state.dataDateSettings(),projectState:this.coreRuntime.state.dataDateProjectState(),externalRelationshipIds:this.coreRuntime.externalRelationshipIds,patch:void 0,sector:this.coreRuntime.sector});for(let F of f.calculated.activities.keys()){if(p.has(F))continue;let T=this.coreRuntime.state.getActivity(F);T!==null&&p.set(F,st(T))}this._applyPreparedP6Schedule(f)}let g=f===null?[e]:[...f.calculated.activities.keys()];(f!==null||u.startDate!==void 0||u.endDate!==void 0)&&await sn(this.coreRuntime.state,new Set(g),!1);let L=await tt(this.coreRuntime.state,{source:{kind:ce.P6_ACTIVITY_UPDATE},beforeSnap:p,touchedIds:g,scheduledIds:f===null?[]:g,hoursPerDay:this.coreRuntime.sector.hoursPerDay});y=f===null?L:{...L,...f.changeSetContribution},f!==null&&(m=this._buildP6ScheduleRunLog(f,r),this.coreRuntime.state.setDataDateLatestRunLog(m))}catch(A){throw this._rollback(),A}finally{this.coreRuntime.state.endWriteCapture()}return this._undo.record(ea(fo(y))),this._saveTracker.recordChanges(y.activities,y.links,A=>this.coreRuntime.state.getActivity(A),A=>this.coreRuntime.state.getLink(A)),f!==null&&m!==null&&(this._saveTracker.recordP6Settings(f.settings),this._saveTracker.recordP6ProjectState(f.projectState),this._saveTracker.recordP6LatestRunLog(m)),this._recordDirectScheduleMutation(this.coreRuntime.state.isDataDateEnabled()),a=!0,m!==null&&(this._p6ScheduleStateFingerprintCache={stateRevision:this._stateRevision,value:m.scheduleDigest}),{changes:y}}finally{this._settleScheduleMutation(i,a)}})}_scheduleP6(e,n){let r=this._admitScheduleMutation(),i=!1;return this._enqueue(async()=>{try{let a=await this._runP6Schedule(e,n);return i=this._changeSetIsSubstantive(a.changes),a}finally{this._settleScheduleMutation(r,i)}})}async _runP6Schedule(e,n){if(this.assertReady(),!this.coreRuntime.state.isDataDateEnabled())throw new Ce("capability_not_enabled","Data Date is disabled for this Schedule");let r=this._requireDataDateCapability().prepareSchedule({state:this.coreRuntime.state,settings:this.coreRuntime.state.dataDateSettings(),projectState:this.coreRuntime.state.dataDateProjectState(),externalRelationshipIds:this.coreRuntime.externalRelationshipIds,patch:e,sector:this.coreRuntime.sector}),{settings:i,projectState:a,calculated:o,changeSetContribution:s}=r,l=new Map;for(let p of o.activities.keys()){let y=this.coreRuntime.state.getActivity(p);y!==null&&l.set(p,st(y))}this.coreRuntime.state.beginWriteCapture();let c,d,u;try{this._applyPreparedP6Schedule(r),await sn(this.coreRuntime.state,new Set(o.activities.keys()),!1),c={...await tt(this.coreRuntime.state,{source:{kind:ce.P6_SCHEDULE},beforeSnap:l,touchedIds:o.activities.keys(),scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay}),...s},d=[...o.activities.keys()].flatMap(y=>{let f=this.coreRuntime.state.getActivity(y);return f===null?[]:[st(f)]}),u=this._buildP6ScheduleRunLog(r,n),this.coreRuntime.state.setDataDateLatestRunLog(u)}catch(p){throw this._rollback(),p}finally{this.coreRuntime.state.endWriteCapture()}return this._changeSetIsSubstantive(c)&&(this._undo.record(ea(fo(c))),this._saveTracker.recordChanges(c.activities,c.links,p=>this.coreRuntime.state.getActivity(p),p=>this.coreRuntime.state.getLink(p)),this._saveTracker.recordP6Settings(i),this._saveTracker.recordP6ProjectState(a),this._recordDirectScheduleMutation(!0)),this._p6ScheduleStateFingerprintCache={stateRevision:this._stateRevision,value:u.scheduleDigest},this._saveTracker.recordP6LatestRunLog(u),{changes:c,calculatedActivities:d,criticalPath:[...o.criticalPath],warnings:[...o.warnings],log:u}}_applyPreparedP6Schedule(e){this.coreRuntime.state.setDataDateSettings(e.settings),this.coreRuntime.state.setDataDateProjectState(e.projectState),this._requireDataDateCapability().applyScheduleProjection(this.coreRuntime.state,e.projection)}_operationNow(e){return e?Ta(e):this.coreRuntime.clock?Ta(this.coreRuntime.clock()):null}_buildP6ScheduleRunLog(e,n){return{schemaVersion:1,calculatedAt:n?new Date(n):this.coreRuntime.clock?.()??null,dataDate:v(e.settings.dataDate),project:{projectId:String(this.coreRuntime.sector.projectId),scheduleId:String(this.coreRuntime.sector.id),scheduleCode:this.coreRuntime.sector.name,scheduleName:this.coreRuntime.sector.name},settings:v(e.settings),statistics:{calculatedActivityCount:e.calculated.activities.size,criticalActivityCount:e.calculated.criticalPath.length,warningCount:e.calculated.warnings.length},warnings:v(e.calculated.warnings),scheduleDigest:this._computeP6ScheduleStateFingerprint()}}_requireDataDateCapability(){let e=this.coreRuntime.dataDateCapability;if(e===null)throw new Ce("capability_not_enabled","P6 capability is not enabled for this Schedule");return e}_changeSetIsSubstantive(e){return cC(e,this._hasDataDateChanges(e))}_hasDataDateChanges(e){return this.coreRuntime.dataDateCapability?.changeSetIsSubstantive(e)??!1}_applyDataDateChangeSet(e,n){this.coreRuntime.dataDateCapability?.applyChangeSet(e,n,{setSettings:r=>{this.coreRuntime.state.setDataDateSettings(r)},setProjectPlannedStart:r=>{this._setP6ProjectPlannedStart(r)}})}async _applyDataDateActivationProjection(e,n){let r=this.coreRuntime.dataDateCapability,i=this.coreRuntime.state.dataDateSettings();if(r===null||e===null||i===null)return[];let a=r.prepareLiveDerived(this.coreRuntime.state,e,i,{enabled:this.coreRuntime.state.isDataDateEnabled()});return a.size===0?[]:this._assembleDataDateActivationProjection(r,a,n)}async _assembleDataDateActivationProjection(e,n,r){let i=[...n.keys()],a=this._snapshotActivities(i);this.coreRuntime.state.beginWriteCapture();try{return e.applyLiveDerived(this.coreRuntime.state,n),(await tt(this.coreRuntime.state,{source:{kind:r},beforeSnap:a,touchedIds:i,scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay})).activities}catch(o){throw this._rollback(),o}finally{this.coreRuntime.state.endWriteCapture()}}_snapshotActivities(e){return new Map(e.flatMap(n=>{let r=this.coreRuntime.state.getActivity(n);return r===null?[]:[[n,st(r)]]}))}_setP6ProjectPlannedStart(e){let n=this.coreRuntime.state.dataDateProjectState();n!==null&&this.coreRuntime.state.setDataDateProjectState({...n,plannedStart:e})}_beginScheduleMutation(e){return Ba(e)?this._admitScheduleMutation():!1}_admitScheduleMutation(){return this._pendingScheduleRevision++,this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),!0}_settleScheduleMutation(e,n){e&&(n||(this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision-1,this._scheduleRevision),this._pendingScheduleRevision===this._scheduleRevision&&(this.isCriticalPathSettled()||this.recomputeCriticalPath().catch(r=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path re-arm after a barren mutation failed",r)}))))}async dispatch(e,n={}){let r=this._beginScheduleMutation(e);return this._enqueue(()=>this._dispatchInner(e,n,r))}async dispatchMany(e,n={}){let r=e.some(Ba)?this._admitScheduleMutation():!1;return this._enqueue(()=>this._dispatchManyInner(e,n,r))}async applyActivityBatch(e,n={}){let r=this._beginScheduleMutation(e);return this._enqueue(()=>this._dispatchInner(e,n,r))}planLookaheadConversion(e){return this.assertReady(),qd(e,{adapter:this.coreRuntime.state,sector:this.getSector(),stateRevision:this._stateRevision})}applyLookaheadConversion(e){return this.dispatch({...e,kind:I.ACTIVITY_LOOKAHEAD_CONVERT})}async _dispatchInner(e,n={},r=!1){let i=!1;try{let a=await this._runDispatch(e,n);return i=a.changedState,a.result}finally{this._settleScheduleMutation(r,i)}}async _dispatchManyInner(e,n,r){let i=this._snapshotProjection(),a=this.coreRuntime.state.dataDateSettings(),s=a?.dataDate!=null&&a.scheduleAutomaticallyOnDateChange?kC({state:this.coreRuntime.state,history:this._undo,sector:this.coreRuntime.sector,persistence:this._saveTracker,scheduler:this.coreRuntime.scheduler,activityIds:this.coreRuntime.activityIdGenerator,linkIds:this.coreRuntime.linkIdGenerator,correlatives:this.coreRuntime.uniqueCorrelativeIdGenerator,customIds:this.coreRuntime.customIdTracker}):null,l=v(this._activityClipboard.value),c=v(this._cellClipboard.value),d=this._stateRevision,u=this._scheduleRevision,p=this._criticalPathRevision,y=this._criticalPathReady,f=this._settledCriticalPathJob,m=this._criticalPathUsesDataDate,A=this._canonicalFingerprintCache,g=this._p6ScheduleStateFingerprintCache,P={...n,skipAutoSchedule:!0,skipCriticalPath:!0},L=[],F=[],T=[],x=!1,S=!1,k,E=!1,j=null,w=!1,B=!1;try{for(let $ of e){if($.kind===I.SCHEDULE_AUTO_SCHEDULE){if($.activityId!==void 0&&!this.coreRuntime.state.activityExists($.activityId)){L.push({ok:!1,reason:C.ACTIVITY_NOT_FOUND});continue}let at=this.coreRuntime.state.dataDateSettings();if(At(at,this.coreRuntime.state.isDataDateEnabled())&&at.scheduleAutomaticallyOnDateChange!==!0){L.push({ok:!1,reason:C.MANUAL_SCHEDULING_ACTIVE});continue}let N=$U($);L.push({ok:!0,changes:N}),F.push(N),T.push($),S=!0,$.activityId===void 0||k!==void 0&&k!==$.activityId?E=!0:k=$.activityId;continue}let ft=await this._runDispatch($,P,!0);L.push(ft.result),ft.result.ok&&(F.push(ft.result.changes),T.push($)),ft.changedState&&(x=!0,S=!0,E=!0)}if(S){let $=E||k===void 0?{kind:I.SCHEDULE_AUTO_SCHEDULE}:{kind:I.SCHEDULE_AUTO_SCHEDULE,activityId:k},ft=await this._runDispatch($,n,!0);ft.result.ok&&(j=ft.result.changes,F.push(ft.result.changes),w=n.skipAutoSchedule!==!0),x||=ft.changedState}return x&&this._recordScheduleMutation(j!==null&&n.skipAutoSchedule!==!0&&n.skipCriticalPath!==!0),B=!0,{results:L,autoScheduled:w,changeSet:this._aggregateDispatchManyChangeSets(i,F,T)}}catch($){throw s!==null&&(s.restore(),this._activityClipboard.value=l,this._cellClipboard.value=c,this._undo=s.history,this._saveTracker=s.persistence,this._stateRevision=d,this._scheduleRevision=u,this._criticalPathRevision=p,this._criticalPathReady=y,this._settledCriticalPathJob=f,this._criticalPathUsesDataDate=m,this._canonicalFingerprintCache=A,this._p6ScheduleStateFingerprintCache=g,x=!1),$}finally{!B&&x&&this._recordScheduleMutation(!1),this._settleScheduleMutation(r,B&&x)}}_aggregateDispatchManyChangeSets(e,n,r){if(n.length===0)return null;let i=pp(this._snapshotProjection(),e),a=n.flatMap(s=>s.effects??[]),o=n.flatMap(s=>s.warnings??[]);return{...i,source:{kind:ce.DISPATCH_MANY,actions:r},trackingEvents:n.flatMap(s=>s.trackingEvents),...a.length===0?{}:{effects:a},...o.length===0?{}:{warnings:o}}}async _runDispatch(e,n,r=!1){if(this.assertReady(),n.at&&(this._lastOperationAt=new Date(n.at)),this._isFork&&JU(e))return{result:{ok:!1,reason:C.SANDBOX_PERSISTENCE_FORBIDDEN},changedState:!1};if(e.kind===I.PERSISTENCE_REBASE&&!this._saveTracker.tracksPersistence())return{result:{ok:!1,reason:C.PERSISTENCE_TRACKING_DISABLED},changedState:!1};let i=ic(this.coreRuntime.state,{calendars:this.coreRuntime.calendars,hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat}),a=lC(e),o=[this.coreRuntime.activityIdGenerator.snapshot(),this.coreRuntime.linkIdGenerator.snapshot(),this.coreRuntime.uniqueCorrelativeIdGenerator.snapshot()];this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let s,l={prepared:null},c=null,d,u;try{s=await jA(e,n,{adapter:this.coreRuntime.state,ctx:i,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,linkIdGen:this.coreRuntime.linkIdGenerator,isActivityIdReserved:m=>this._saveTracker.hasCheckpointActivityId(m),isActivityPersisted:m=>this._saveTracker.knowsPersistedActivity(m),isLinkIdReserved:m=>this._saveTracker.hasCheckpointLinkId(m),persistenceCheckpoint:this._saveTracker,uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,reporter:this.coreRuntime.reporter,activityClipboard:this._activityClipboard,cellClipboard:this._cellClipboard,stateRevision:this._stateRevision,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(m=>m.baseDefault)?.id??null,hasCompleteSchedulingState:this.coreRuntime.state.dataDateSettings()!==null&&this.coreRuntime.state.hasCompleteSchedulingState(),dataDateCapability:this.coreRuntime.dataDateCapability,dataDateSettings:this.coreRuntime.state.dataDateSettings(),dataDateEnabled:this.coreRuntime.state.isDataDateEnabled(),runAutomaticP6Schedule:async()=>(l.prepared=this._requireDataDateCapability().prepareSchedule({state:this.coreRuntime.state,settings:this.coreRuntime.state.dataDateSettings(),projectState:this.coreRuntime.state.dataDateProjectState(),externalRelationshipIds:this.coreRuntime.externalRelationshipIds,patch:void 0,sector:this.coreRuntime.sector,...l.prepared===null?{}:{transactionBaseline:l.prepared}}),this._applyPreparedP6Schedule(l.prepared),[...l.prepared.calculated.activities.keys()]),now:this._operationNow(n.at),actionAt:n.at});let y=l.prepared;s.ok&&y!==null&&(s={...s,changes:{...s.changes,...y.changeSetContribution}},c=this._buildP6ScheduleRunLog(y,n.at),this.coreRuntime.state.setDataDateLatestRunLog(c)),u=this.coreRuntime.state.peekWriteCapture()?.dirty;let f=this.coreRuntime.state.peekWriteCapture()?.progressFallbackBefore;f&&f.size>0&&(d=new Map(f)),s.ok||this._rollback(o)}catch(y){throw this._rollback(o),y}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(s.ok&&a===ir.RECORD&&this._changeSetIsSubstantive(s.changes)){let y=iC(this.coreRuntime.state,s.changes),f=d?new Map(Array.from(d.keys(),m=>[m,this.coreRuntime.state.getProgressFallback(m)])):void 0;this._undo.record({...ea(fo(s.changes),s.__beforeSnap,s.__beforeLinks,y.afterSnap,y.afterLinks,d,f),...At(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.isDataDateEnabled())?{beforeLinks:v(s.__beforeLinks),afterLinks:v(y.afterLinks)}:{}},aC(e),n.at?.getTime()??Date.now())}if(s.ok)if(a===ir.CHECKPOINT_ON_SUCCESS||a===ir.REBASE_ON_SUCCESS){let y=zU(e,s,this._saveTracker),f=y.checkpoint,m={settings:f?.p6Settings??this.coreRuntime.state.dataDateSettings(),projectState:f?.p6ProjectState===void 0?this.coreRuntime.state.dataDateProjectState():f.p6ProjectState,latestRunLog:f?.p6LatestRunLog===void 0?this.coreRuntime.state.dataDateLatestRunLog():f.p6LatestRunLog};if(f?.pending)this._saveTracker.acknowledgePending(f.pending,f.activities,f.links,y.persistedActivities??[],y.persistedLinks??[],{activity:A=>this.coreRuntime.state.getActivity(A),link:A=>this.coreRuntime.state.getLink(A)},m.settings,m.projectState,m.latestRunLog);else{let A=this.coreRuntime.state.getAllActivities(),g=this.coreRuntime.state.getAllLinks();this._saveTracker.acknowledge(f?.activities??A,f?.links??g,y.persistedActivities,y.persistedLinks,A,g,m.settings,m.projectState,m.latestRunLog)}y.clearsHistory?this._undo.clear():(y.retainsHistory||this._undo.discardThrough(y.historyBoundary??this._undo.capturePersistenceBoundary()),this._undo.applyPersistedIdentities(y.persistedActivities??[],y.persistedLinks??[]))}else if(e.kind===I.ACTIVITY_LOOKAHEAD_SYNC&&e.acknowledgePersistedLookahead===!0)this._saveTracker.acknowledgePersistedLookahead(s.changes.activities,y=>this.coreRuntime.state.getActivity(y)),e.persistedProgress!==void 0&&this._undo.clear();else{this._saveTracker.recordChanges(s.changes.activities,s.changes.links,f=>this.coreRuntime.state.getActivity(f),f=>this.coreRuntime.state.getLink(f),u);let y=l.prepared;y!==null&&c!==null&&(this._saveTracker.recordP6Settings(y.settings),this._saveTracker.recordP6ProjectState(y.projectState),this._saveTracker.recordP6LatestRunLog(c))}if(s=this._withReappliedViewState(e,s),!s.ok)return{result:s,changedState:!1};let p=this._changeSetIsSubstantive(s.changes);return p&&this._stateRevision++,c!==null&&(this._p6ScheduleStateFingerprintCache={stateRevision:this._stateRevision,value:c.scheduleDigest}),Ba(e)&&p?(r||this._recordScheduleMutation(n.skipAutoSchedule!==!0&&n.skipCriticalPath!==!0&&br(e)),{result:OC(s),changedState:!0}):{result:OC(s),changedState:!1}}recomputeCriticalPath(){let e=this._enqueue(async()=>({job:this._startCriticalPathForCurrentRevision()})).then(({job:n})=>n);return this._criticalPathReady=this._trackCriticalPathJob(e),e}isCriticalPathSettled(){return this._criticalPathRevision===this._scheduleRevision&&this._criticalPathUsesDataDate===At(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.isDataDateEnabled())&&this._pendingScheduleRevision===this._scheduleRevision&&this._activeCriticalPath===null}async whenCriticalPathSettled(){for(;!this.isCriticalPathSettled();){let e=this._activeCriticalPath?.promise;e?await e:await this.recomputeCriticalPath()}}_withReappliedViewState(e,n){if(!n.ok||(e.kind===I.VISIBILITY_SET&&this.coreRuntime.state.setFilterProjection(null),!sm(e)))return n;let r=this._reapplyViewState(n.changes);return r===null?n:{...n,changes:r}}_reapplyViewState(e){let n=this._reapplyActiveFilter(e),r=this._emitTouchedBranchOrder(n??e);return this._reapplyActiveOrder(r.changes??n??e,r.touchedParents)??r.changes??n}_emitTouchedBranchOrder(e){let n=this.coreRuntime.state,r=AC(e,a=>n.getParentId(a));if(n.getActiveOrder()!==null)return{changes:null,touchedParents:r};if(r.size===0)return{changes:null,touchedParents:r};let i=Ec(n,r);return i.length===0?{changes:null,touchedParents:r}:{changes:{...e,order:i},touchedParents:r}}_reapplyActiveOrder(e,n){let r=this.coreRuntime.state;if(r.getActiveOrder()===null)return null;if(r.invalidateDerivedOrder(),e.links.length>0||e.calendars.length>0)return{...e,order:Pn(r)};let a=new Set(n);for(let s of e.activities){if(s.kind===W.DELETED)return{...e,order:Pn(r)};let l=r.getParentId(s.id);a.add(l===null?"0":String(l))}let o=Ec(r,a);return o.length===0?null:{...e,order:o}}_reapplyActiveFilter(e){let n=this.coreRuntime.state,r=n.getActiveFilter();if(r===null)return null;let i=fr(this.coreRuntime.sector.hoursPerDay),a=n.getFilterProjection(),o=QU(a,r,i),s=XU(e)?null:ZU(e,n),l,c;if(s===null||!o){let p=Fo({activities:n.getAllActivities(),parentOf:y=>n.getParentId(y),filter:r,context:i,viewAttributeCatalogs:n.getViewAttributeCatalogMap()});n.setFilterProjection(p),c=p.visibleIds,l=n.getAllIds()}else l=Hp(a,s,p=>n.getParentId(p)),c=a.visibleIds;let u=dr(n,c,l);return u.length===0?null:{...e,viewState:[...e.viewState??[],...u]}}_recordScheduleMutation(e){this._scheduleRevision++,this._settledCriticalPathJob!==null&&this._releaseCriticalPathResult(this._settledCriticalPathJob),this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision,this._scheduleRevision),this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),e&&(this._criticalPathUsesDataDate=At(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.isDataDateEnabled()),this._criticalPathRevision=this._scheduleRevision)}_recordDirectScheduleMutation(e){this.coreRuntime.dataDateCapability!==null&&this._stateRevision++,this._recordScheduleMutation(e)}_startCriticalPathForCurrentRevision(){if(this._status===Ve.DESTROYED)return Promise.resolve(null);if(At(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.isDataDateEnabled()))return this._criticalPathUsesDataDate=!0,this._criticalPathRevision=this._scheduleRevision,Promise.resolve(null);let e=this._scheduleRevision;if(this._criticalPathRevision===e&&!this._criticalPathUsesDataDate)return Promise.resolve(null);if(this._activeCriticalPath?.revision===e)return this._activeCriticalPath.promise;this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0);let n={cancelled:!1},r=()=>!At(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.isDataDateEnabled())&&!n.cancelled&&this._status!==Ve.DESTROYED&&this._scheduleRevision===e&&this._pendingScheduleRevision===this._scheduleRevision,i=this._lastOperationAt??void 0,a=(async()=>{let s=await Cd(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay,r,i);return!r()||s===null?null:this._enqueue(async()=>{if(!r())return null;this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let l;try{l=await CC(this.coreRuntime.state,s,{kind:ce.INIT}),this._criticalPathUsesDataDate=!1,this._criticalPathRevision=e}catch(c){throw this._rollback(),c}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return{changes:l}})})();this._activeCriticalPath={revision:e,cancellation:n,promise:a};let o=()=>{this._activeCriticalPath?.promise===a&&(this._activeCriticalPath=null)};return a.then(o,o),a}undo(e={}){let n=this._admitScheduleMutation(),r=!1,i=this._enqueue(async()=>{try{return await this._runUndo(e,a=>{r=a})}finally{this._settleScheduleMutation(n,r)}});return i.then(a=>{let o=a!==null&&this._hasDataDateChanges(a)&&At(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.isDataDateEnabled());a&&!o&&e.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(s=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after undo failed",s)})},()=>{}),i}async _runUndo(e,n){{if(this.assertReady(),e.expectedUndoDepth!==void 0&&this._undo.undoDepth()!==e.expectedUndoDepth)return null;let r=this._undo.takeUndo();if(!r)return null;let i=v(this.coreRuntime.state.dataDateSettings()),a;try{sp(this.coreRuntime.state,r,(l,c)=>this._applyDataDateChangeSet(l,c)),a=await this._applyDataDateActivationProjection(i,ce.UNDO)}catch(l){throw lp(this.coreRuntime.state,r,(c,d)=>this._applyDataDateChangeSet(c,d)),this._undo.restoreTakenUndo(r),l}this._recordDirectScheduleMutation(this._hasDataDateChanges(r.changeSet)&&At(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.isDataDateEnabled())),n(!0),ap(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(r),this._undo.resetCoalesce();let o=op(this.coreRuntime.state,r,Bt.BEFORE,l=>this.coreRuntime.dataDateCapability?.historyContribution(r.changeSet,l)??{}),s={...o,activities:[...o.activities,...a]};return this._saveTracker.recordChanges(s.activities,s.links,l=>this.coreRuntime.state.getActivity(l),l=>this.coreRuntime.state.getLink(l)),this._saveTracker.recordP6Settings(this.coreRuntime.state.dataDateSettings()),this._saveTracker.recordP6ProjectState(this.coreRuntime.state.dataDateProjectState()),this._reapplyViewState(s)??s}}redo(e={}){let n=this._admitScheduleMutation(),r=!1,i=this._enqueue(async()=>{try{return await this._runRedo(a=>{r=a})}finally{this._settleScheduleMutation(n,r)}});return i.then(a=>{let o=a!==null&&this._hasDataDateChanges(a)&&At(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.isDataDateEnabled());a&&!o&&e.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(s=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after redo failed",s)})},()=>{}),i}async _runRedo(e){this.assertReady();let n=this._undo.takeRedo();if(!n)return null;let r=v(this.coreRuntime.state.dataDateSettings()),i;try{lp(this.coreRuntime.state,n,(s,l)=>this._applyDataDateChangeSet(s,l)),i=await this._applyDataDateActivationProjection(r,ce.REDO)}catch(s){throw sp(this.coreRuntime.state,n,(l,c)=>this._applyDataDateChangeSet(l,c)),this._undo.restoreTakenRedo(n),s}this._recordDirectScheduleMutation(this._hasDataDateChanges(n.changeSet)&&At(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.isDataDateEnabled())),e(!0),ap(n)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(n),this._undo.resetCoalesce();let a=op(this.coreRuntime.state,n,Bt.AFTER,s=>this.coreRuntime.dataDateCapability?.historyContribution(n.changeSet,s)??{}),o={...a,activities:[...a.activities,...i]};return this._saveTracker.recordChanges(o.activities,o.links,s=>this.coreRuntime.state.getActivity(s),s=>this.coreRuntime.state.getLink(s)),this._saveTracker.recordP6Settings(this.coreRuntime.state.dataDateSettings()),this._saveTracker.recordP6ProjectState(this.coreRuntime.state.dataDateProjectState()),this._reapplyViewState(o)??o}canUndo(){return this._undo.canUndo()}canRedo(){return this._undo.canRedo()}readIdCounters(){return{activity:this.coreRuntime.activityIdGenerator.snapshot(),link:this.coreRuntime.linkIdGenerator.snapshot(),uniqueCorrelative:this.coreRuntime.uniqueCorrelativeIdGenerator.snapshot()}}restoreIdCounters(e){this.coreRuntime.activityIdGenerator.restore(e.activity),this.coreRuntime.linkIdGenerator.restore(e.link),this.coreRuntime.uniqueCorrelativeIdGenerator.restore(e.uniqueCorrelative)}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=Ve.DESTROYED}_initPromise;_criticalPathReady;_settledCriticalPathJob=null;_ready;_saveTracker=new na;_retainCriticalPathResult=!0;_lastOperationAt=null;assertReady(){if(this._status===Ve.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===Ve.POISONED)throw new Error("[ScheduleCore] instance is poisoned (a rollback failed) \u2014 reload from backend")}_rollback(e){try{this.coreRuntime.state.restoreFromCapture(),this.coreRuntime.scheduler.invalidateAllCaches(),this.coreRuntime.customIdTracker.rollbackCustomIdTransaction(),e&&(this.coreRuntime.activityIdGenerator.restore(e[0]),this.coreRuntime.linkIdGenerator.restore(e[1]),this.coreRuntime.uniqueCorrelativeIdGenerator.restore(e[2]))}catch(n){throw this._status=Ve.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",n),n}}};function OC(t){let{__beforeSnap:e,__beforeLinks:n,__rebaseCheckpoint:r,...i}=t;return i}async function NC(t){let e=new ra(t);return await e.ready,e}var t0=(t,e)=>{if(!t.resourceAssignments)return t;let n=!1,r=t.resourceAssignments.map(i=>{let a=i.sourceCalendarId,o=e.get(String(a??i.calendarId))??i.calendarId;return o===i.calendarId?i:(n=!0,{...i,calendarId:o})});return n?{...t,resourceAssignments:r}:t},e0=(t,e)=>{if(!t?.activities||e.length===0)return t;let n=new Map(e.map(i=>[String(i.unique_id),String(i.id)])),r=t.activities;for(let[i,a]of Object.entries(t.activities)){let o=t0(a,n);o!==a&&(r===t.activities&&(r={...t.activities}),r[i]=o)}return r===t.activities?t:{...t,activities:r}};function FC(t){let e=e0(t.p6,t.calendars)??(t.isDataDateEnabled?.()?{settings:ta(),projectPlannedStart:null,activities:{}}:void 0),n=e?.settings.dataDate!=null;return{...t.isDataDateEnabled?{isDataDateEnabled:t.isDataDateEnabled}:{},...e?{p6:e}:{},...n&&(t.isDataDateEnabled?.()??!0)?{skipInitialAutoSchedule:!0}:{}}}var n0=["DURATION","COST","HH"];function wC(t){let e=t.projectActivityCriterion==null?t.sector:{...t.sector,activity_creter:t.projectActivityCriterion},n=t.calendars??[];return{sector:e,activities:t.activities,links:t.links??[],calendars:n,baseCalendars:t.baseCalendars??[],baselinePoints:t.baselinePoints??[],statusCriteria:t.statusCriteria??"Baseline",...t.ganttId!==void 0?{ganttId:t.ganttId}:{},clock:t.clock,...t.reporter?{reporter:t.reporter}:{},...FC({...t.p6?{p6:t.p6}:{},...t.isDataDateEnabled?{isDataDateEnabled:t.isDataDateEnabled}:{},calendars:n})}}function xC(t){let e=t.update_save_handle_for_calendar_update===!0,n=t.update_ponderators_masterplan===!0,r=t.activity_creter?.toUpperCase(),i=n?n0.find(a=>a===r)??null:null;return{actions:[...e?[{kind:I.CALENDAR_RECONCILE}]:[],...i?[{kind:I.PONDERATOR_CRITERION_SET,criterion:i}]:[]],calendar:e,ponderators:i!==null,...n&&i===null?{unresolvedPonderatorCriterion:String(t.activity_creter)}:{}}}function MC(t,e){return t.some(n=>n.unique_id!=null&&Si(n.start_date,e(String(n.unique_id))))}var r0={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"},i0=/^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i,dc=t=>typeof t=="string"&&t.trim()!=="",UC=t=>typeof t=="number"&&Number.isFinite(t)||typeof t=="string"&&i0.test(t.trim())&&Number.isFinite(Number(t)),a0=[["start_date","startDate",dc],["end_date","endDate",dc],["duration","durationHours",UC],["constraint","constraintType",dc],["constraint_date","constraintDate",t=>t===null||dc(t)],["progress","progress",UC]],o0=["startDate","endDate"],mo=t=>{let e=Number(t);return Number.isSafeInteger(e)?e:t},s0=(t,e,n)=>{let r=new Set(n.changedFields??[]);if(n.persistCalendarAlignedDates===!0||Si(e.start_date,t.startDate))for(let i of o0)r.add(i);return r},l0=(t,e,n)=>{let r={...t};for(let[i,a,o]of a0){let s=e[i];!n.has(a)&&Object.hasOwn(e,i)&&o(s)&&(r[i]=s)}return r};function HC(t,e,n={}){let r=a=>a/e.hoursPerDay,i={name:t.name,unique_id:mo(t.id),parent_id:mo(t.parentId??"0"),description:t.description,cost:t.cost,progress:t.progress,progressChangedByActionButton:!!n.progressChangedByActionButton,progressModifiedBySDK:!!n.progressModifiedBySDK,constraint:r0[t.constraintType??"asap"],start_date:t.startDate,custom_id:t.customId,end_date:t.endDate,constraint_date:t.constraintDate,type:t.type,correlative_id:t.correlativeId,unique_correlative_id:t.uniqueCorrelativeId,hhWorkTime:t.workHours,ponderator:t.ponderator,hasCustomPonderator:t.hasCustomPonderator,used_cost:t.usedCost,real_cost:t.realCost,real_work:t.realWorkHours,responsables:t.responsableIds.map(a=>({id:a})),tags:t.tagIds.map(a=>({id:a})),subcontractId:t.subcontractId,...t.freeSlackHours==null?{}:{freeSlack:r(t.freeSlackHours)},isOnLookahead:t.isLookahead,is_critical:t.isCritical,hasNewActivities:t.hasNewActivities,newActivitiesArray:JSON.stringify(t.newActivityIds),isNewActivity:t.isNewActivity,...t.calendarId==null?{}:{calendarId:t.calendarId},duration:r(t.durationHours),sumOfDurationRecursively:r(t.recursiveDurationHours),expected_progress:t.expectedProgress,sectorId:e.sectorId,ganttId:e.ganttId,has_childs:e.hasChildren(String(t.id)),...t.proplannerId==null?{}:{id:t.proplannerId}};return t.proplannerId==null||!n.origin?i:l0(i,n.origin,s0(t,n.origin,n))}function BC(t,e){return{unique_id:mo(t.id),source_id:mo(t.source),target_id:mo(t.target),type:ts[t.type],lag:(t.lag??0)/e.hoursPerDay,sectorId:e.sectorId,ganttId:e.ganttId,...t.proplannerId==null?{}:{id:t.proplannerId}}}var Gr="__wire",ia={DATE:"date",MAP:"map",SET:"set"},hp={DATE:"[object Date]",MAP:"[object Map]",SET:"[object Set]"},c0=t=>Object.prototype.toString.call(t),d0=new Set(Object.values(ia));function u0(t){return typeof t=="object"&&t!==null&&Gr in t&&d0.has(t[Gr])}function p0(t){let e=t.getTime();return{[Gr]:ia.DATE,value:Number.isNaN(e)?null:t.toISOString()}}function Kr(t){let e=c0(t);if(e===hp.DATE)return p0(t);if(e===hp.MAP)return{[Gr]:ia.MAP,value:Array.from(t.entries(),([n,r])=>[Kr(n),Kr(r)])};if(e===hp.SET)return{[Gr]:ia.SET,value:Array.from(t,Kr)};if(Array.isArray(t))return t.map(Kr);if(typeof t=="object"&&t!==null){let n={};for(let[r,i]of Object.entries(t))i!==void 0&&(n[r]=Kr(i));return n}return t}function y0(t){if(t[Gr]===ia.DATE)return t.value===null?new Date(Number.NaN):new Date(t.value);let e=t.value;return t[Gr]===ia.MAP?new Map(e.map(([n,r])=>[Yr(n),Yr(r)])):new Set(e.map(Yr))}function Yr(t){if(u0(t))return y0(t);if(Array.isArray(t))return t.map(Yr);if(typeof t=="object"&&t!==null){let e={};for(let[n,r]of Object.entries(t))e[n]=Yr(r);return e}return t}var WC=["actualStart","actualFinish","plannedStart","plannedFinish","expectedFinish","suspendDate","resumeDate","primaryConstraintDate","secondaryConstraintDate","remainingEarlyStart","remainingEarlyFinish","remainingLateStart","remainingLateFinish","earlyStart","earlyFinish","lateStart","lateFinish","primaryBaselineStart","primaryBaselineFinish"],KC=new Set(["primaryConstraintDate"]),jC=Object.freeze({fixed_duration_and_units:"fixed_units_time",fixed_duration_and_units_per_time:"fixed_duration_units",fixed_units_time:"fixed_units_time",fixed_duration_units:"fixed_duration_units",fixed_units:"fixed_units",fixed_duration_units_time:"fixed_duration_units_time"}),VC=Object.freeze({fixed_units_time:"fixed_duration_and_units",fixed_duration_units:"fixed_duration_and_units_per_time"}),Ne=(t,e)=>{if(t===null)return null;let n=new Date(t);if(!Number.isFinite(n.getTime())||n.toISOString()!==t)throw new TypeError(`${e} must be a valid UTC timestamp or null`);return n},tn=t=>t===null?null:t.toISOString(),YC=(t,e)=>({...t,dataDate:Ne(t.dataDate,`${e}.dataDate`),projectMustFinishBy:Ne(t.projectMustFinishBy,`${e}.projectMustFinishBy`),projectForecastStart:Ne(t.projectForecastStart,`${e}.projectForecastStart`),multipleFloatPaths:{...t.multipleFloatPaths}}),f0=t=>t!==void 0&&Object.hasOwn(VC,t)?VC[t]:t,h0=(t,e)=>{let{resourceAssignments:n,...r}=t,i=`activities.${e}`,a=Object.fromEntries(WC.map(o=>{let s=t[o];return[o,Ne(KC.has(o)?s??null:s,`${i}.${o}`)]}));return{...r,...t.durationType===void 0?{}:{durationType:f0(t.durationType)},...n===void 0?{}:{resourceAssignments:n.map(o=>({...o,actualStart:Ne(o.actualStart,`${i}.resourceAssignments.${o.id}.actualStart`),actualFinish:Ne(o.actualFinish,`${i}.resourceAssignments.${o.id}.actualFinish`)}))},...a}},m0=t=>({...t,calculatedAt:Ne(t.calculatedAt,"latestRunLog.calculatedAt"),dataDate:Ne(t.dataDate,"latestRunLog.dataDate"),settings:YC(t.settings,"latestRunLog.settings"),warnings:t.warnings.map((e,n)=>({...e,dataDate:Ne(e.dataDate,`latestRunLog.warnings.${n}.dataDate`),dates:{actualStart:Ne(e.dates.actualStart,`latestRunLog.warnings.${n}.dates.actualStart`),actualFinish:Ne(e.dates.actualFinish,`latestRunLog.warnings.${n}.dates.actualFinish`)}}))});function GC(t){return{settings:YC(t.settings,"settings"),projectPlannedStart:Ne(t.projectPlannedStart,"projectPlannedStart"),activities:Object.fromEntries(Object.entries(t.activities).map(([e,n])=>[e,h0(n,e)])),externalRelationshipIds:[...t.externalRelationshipIds??[]],latestRunLog:t.latestRunLog===void 0||t.latestRunLog===null?null:m0(t.latestRunLog)}}var g0=t=>{if(!Object.hasOwn(jC,t))throw new Error(`Unknown P6 duration type "${String(t)}"`);return jC[t]};function uc(t){return{...t,dataDate:tn(t.dataDate),projectMustFinishBy:tn(t.projectMustFinishBy),projectForecastStart:tn(t.projectForecastStart),multipleFloatPaths:{...t.multipleFloatPaths}}}function mp(t){let{resourceAssignments:e,...n}=t,r=Object.fromEntries(WC.map(i=>[i,tn(KC.has(i)?t[i]??null:t[i])]));return{...n,...t.durationType===void 0?{}:{durationType:g0(t.durationType)},...e===void 0?{}:{resourceAssignments:e.map(i=>({...i,actualStart:tn(i.actualStart),actualFinish:tn(i.actualFinish)}))},...r}}var A0=t=>({...t,calculatedAt:tn(t.calculatedAt),dataDate:t.dataDate.toISOString(),settings:uc(t.settings),warnings:t.warnings.map(e=>({...e,dataDate:e.dataDate.toISOString(),dates:{actualStart:tn(e.dates.actualStart),actualFinish:tn(e.dates.actualFinish)}}))});function qC(t){if(t.settings===null)return null;if(t.projectState===null)throw new Error("P6 project state is required when P6 settings exist");return{settings:uc(t.settings),projectPlannedStart:tn(t.projectState.plannedStart),activities:Object.fromEntries(t.activities.flatMap(e=>e.p6===null||e.p6===void 0?[]:[[String(e.id),mp(e.p6)]])),...t.latestRunLog===void 0?{}:{latestRunLog:t.latestRunLog===null?null:A0(t.latestRunLog)},...t.externalRelationshipIds?.length?{externalRelationshipIds:[...t.externalRelationshipIds]}:{}}}var $C=(t=[])=>(t??[]).filter(e=>!e.proplannerId);var go=class extends Error{constructor(n){super(n);this.code=n;this.name="LookaheadActualTransitionError"}code},I0=/^(\d{4})-(\d{2})-(\d{2})$/;function pc(t){gp(t.timeSource)||We("INVALID_ACTUAL_TIME_SOURCE");let e=S0(t.selectedDay),[n,r,i]=e,a=new Date(t.timeSource);return a.setUTCFullYear(n,r-1,i),D0(a,e)||We("INVALID_ACTUAL_DAY"),a}function S0(t){let e=I0.exec(t);return e||We("INVALID_ACTUAL_DAY"),[Number(e[1]),Number(e[2]),Number(e[3])]}function Ap(t){if(C0(t),t.dataDate===null)return{start:null,finish:null,uncomplete:null};let e=t.activity.executionStatus===et.NOT_STARTED&&t.nextProgress>0?{required:!0,suggestedAt:new Date(t.dataDate)}:null,n=t.activity.executionStatus!==et.COMPLETED&&t.nextProgress===100?{optional:!0,suggestedAt:t.displayedFinish?new Date(t.displayedFinish):null}:null,r=t.activity.executionStatus===et.COMPLETED&&t.activity.actualFinish!==null&&t.nextProgress<100?{required:!0,removes:new Date(t.activity.actualFinish)}:null;return{start:e,finish:n,uncomplete:r}}function zC(t){let e=Ap(t);t.dataDate===null&&T0(t.intent)&&We("DATA_DATE_INACTIVE"),e.start&&t.intent?.actualStart===void 0&&We("ACTUAL_START_REQUIRED"),t.intent?.actualFinish instanceof Date&&t.nextProgress!==100&&We("ACTUAL_FINISH_REQUIRES_100"),e.uncomplete&&t.intent?.actualFinish!==null&&We("ACTUAL_FINISH_REMOVAL_REQUIRED"),!e.uncomplete&&t.intent?.actualFinish===null&&We("ACTUAL_FINISH_REMOVAL_NOT_APPLICABLE");let n=wl(t.activity,t.intent??{});return t.dataDate===null?n:v0(t.activity,n,t.nextProgress)}function v0(t,e,n){if((e.executionStatus??t.executionStatus)!==et.IN_PROGRESS)return e;switch(t.percentCompleteType){case Nt.PHYSICAL:return{...e,physicalPercentComplete:n};case Nt.DURATION:return{...e,remainingDurationHours:t.originalDurationHours*(1-n/100)};default:return e}}function C0(t){(!Number.isFinite(t.nextProgress)||t.nextProgress<0||t.nextProgress>100)&&We("INVALID_PROGRESS"),t.dataDate!==null&&!gp(t.dataDate)&&We("INVALID_DATA_DATE"),t.displayedFinish!=null&&!gp(t.displayedFinish)&&We("INVALID_DISPLAYED_FINISH")}function gp(t){return t instanceof Date&&Number.isFinite(t.getTime())}function D0(t,[e,n,r]){return t.getUTCFullYear()===e&&t.getUTCMonth()===n-1&&t.getUTCDate()===r}function T0(t){return t?.actualStart!==void 0||t?.actualFinish!==void 0}function We(t){throw new go(t)}function JC(t){return pc({selectedDay:t.selectedDay,timeSource:t.expectedFinish??t.displayedFinish})}function yc(t){let e=ec([...t.calendars],void 0,t.baseCalendars===void 0?void 0:[...t.baseCalendars]),{reader:n}=Pl(tp(e.calendars,e.baseCalendars));return{defaultCalendarId:e.defaultCalendarId,resolveCalendar(r){let i=r!==null&&e.knownCalendarIds.has(r)?r:e.defaultCalendarId;return n.getCalendar(i)}}}function XC(t){let{resolveCalendar:e}=yc(t);return{derive({previous:n,next:r,calendarId:i,dataDate:a,totalFloatMethod:o}){if(!ln(r))return null;let s=e(i);if(!s)return null;let{p6:l}=Hl(n,r,{calendar:s,dataDate:a,...o===void 0?{}:{totalFloatMethod:o}});return{actualDurationHours:l.actualDurationHours,atCompletionDurationHours:l.atCompletionDurationHours,durationPercentComplete:l.durationPercentComplete,unitsPercentComplete:l.unitsPercentComplete,schedulePercentComplete:l.schedulePercentComplete}}}}function ZC(t){let{defaultCalendarId:e,resolveCalendar:n}=yc(t);if(e===null)throw new Error("Calendar reader requires at least one calendar");return{getCalendar(r){let i=n(r);if(!i)throw new Error("Resolved calendar missing after normalization");return i}}}var Rt=t=>{let e=t.lifecycle??(t.classification==="f9_output"?"f9":"explicit_edit");return{...t,lifecycle:e,changesWhen:_0(e),f9Behavior:E0(e),persistence:"Persist exact null/zero/signed scalar or exact UTC instant; save/reload is lossless.",nullAndZero:t.typeAndUnit.includes("UTC")?"null means absent; midnight is a real exact UTC instant.":t.typeAndUnit.includes("boolean")?"false is a real value and is never normalized to null.":"null means unavailable when allowed; numeric zero and signed values are preserved.",calendarRule:t.typeAndUnit.includes("working hours")||t.classification==="derived"?"Use the activity calendar, including shifts and exceptions; never local wall-clock subtraction.":"No calendar arithmetic; date values cross boundaries as exact UTC components.",status:t.status??(e==="open"?"PARTIAL":"VERIFIED"),edgeCases:t.edgeCases??{}}};function _0(t){return t==="f9"?"Changes only during explicit P6 F9 and its atomic Undo/Redo replay.":t==="dependency_change"?"Changes when Data Date moves from one valid instant to another in the same canonical mutation, without running F9.":t==="open"?"Formula is known; immediate pre-F9 refresh timing remains open pending a discriminant P6 observation.":"Changes on an authorized import or explicit user edit; open/save/reload do not calculate it."}function E0(t){return t==="explicit_edit"?"Preserved as scheduling reality/input unless the documented P6 algorithm consumes the input without rewriting it.":t==="open"?"Recalculated by F9; whether dependency edits refresh it earlier is not yet certified.":"Recalculated by Schedule Core; no frontend or backend formula is authoritative."}var ar="src/p6/api.test.ts; src/p6/testing/p6-data-date/property-coverage.test.ts",Sn="src/p6/testing/p6-data-date/fixtures/obdd-math/obdd-math-before-f9.xer",aa="src/p6/testing/p6-floats/obdd-floats.schedule.test.ts",oa="src/p6/testing/p6-floats/fixtures/obdd-floats-smallest.xer",vn="src/p6/derived.test.ts",or="src/p6/testing/p6-derived/fixtures/obdd-derived-edges.p6.json",R0={notStarted:"0 hours.",inProgress:"Working time from Actual Start to Data Date, excluding a valid Suspend/Resume interval.",completed:"Working time from Actual Start to Actual Finish.",zeroDuration:"0 hours.",zeroDenominator:"Not applicable; no division.",suspendResume:"Subtract only the overlap of Suspend..Resume with the measured actual interval.",calendarException:"Exception time contributes only when the activity calendar marks it workable.",signedValues:"Invalid negative duration inputs are rejected; P6 clamps a reversed Actual Start/end interval to 0 hours.",nullValue:"Missing required actual endpoint yields 0 under the P6 status contract.",milestone:"0 hours when the actual endpoints coincide."},P0={notStarted:"Working duration Planned Start..Planned Finish.",inProgress:"Working duration Actual Start..Remaining Early Finish, excluding Suspend/Resume.",completed:"Working duration Actual Start..Actual Finish.",zeroDuration:"0 hours.",zeroDenominator:"Not applicable; no division.",suspendResume:"Subtract the suspended overlap from the selected endpoint interval.",calendarException:"Measured with shifts and exceptions from the activity calendar.",signedValues:"P6 clamps a chronologically reversed Actual Start/selected finish interval to 0 hours.",nullValue:"Missing required endpoints yields 0 for the matching status branch.",milestone:"0 hours for coincident endpoints."},k0={notStarted:"(Original - Remaining) / Original \xD7 100, normally 0.",inProgress:"(Original - Remaining) / Original \xD7 100, clamped to 0..100.",completed:"Same formula; P6 completed input normally has zero Remaining.",zeroDuration:"0%, including a zero-duration milestone.",zeroDenominator:"0%, never NaN or Infinity.",suspendResume:"No direct effect; only duration inputs affect the percentage.",calendarException:"No direct effect after durations are canonical working hours.",signedValues:"Negative/non-finite duration inputs are rejected.",nullValue:"Duration inputs are required canonical scalars, not nullable.",milestone:"0% for zero Original Duration under the certified P6 golden."},b0={notStarted:"Actual units are normally zero; result is 0%.",inProgress:"100 \xD7 (actual labor + actual nonlabor) / (actual + remaining units).",completed:"100% when remaining units are zero and actual units are positive.",zeroDuration:"Independent of duration; units still control the result.",zeroDenominator:"0%, never NaN or Infinity.",suspendResume:"No direct effect.",calendarException:"No direct effect on already canonical assignment scalars.",signedValues:"Finite negative unit scalars are preserved; P6 can produce percentages below 0% or above 100%. Non-finite inputs are rejected.",nullValue:"Canonical TASK unit scalars are required; missing assignment totals hydrate as zero.",milestone:"0% with no units; otherwise the same units formula."},L0={notStarted:"0% when Data Date is at or before primary baseline start.",inProgress:"Baseline working time elapsed through Data Date divided by total baseline working time.",completed:"100% when Data Date is at or after primary baseline finish.",zeroDuration:"0% before the coincident endpoint and 100% at or after it.",zeroDenominator:"0% when signed baseline working duration is non-positive.",suspendResume:"No direct effect; baseline dates and Data Date are authoritative.",calendarException:"Elapsed and total durations use the activity calendar exception set.",signedValues:"Result is clamped to 0..100; P6 UI does not allow an inverted assigned baseline.",nullValue:"When neither primary baseline endpoint is assigned, P6 uses Current Project planned dates; one missing endpoint or missing effective planned dates returns null.",milestone:"Boundary result is determined by Data Date relative to the coincident baseline endpoints."},O0={notStarted:"Calculated from remaining early and late endpoints.",inProgress:"Same remaining endpoint formula after the selected OOS policy forward/backward passes.",completed:"null when no remaining endpoints exist.",zeroDuration:"Can be positive, zero or negative; milestone duration does not erase float.",zeroDenominator:"Not applicable; no division.",suspendResume:"Affects scheduled endpoints before float is measured.",calendarException:"Start and finish float use signed working time on the activity calendar.",signedValues:"Negative float is preserved exactly; -0 normalizes to numeric 0.",nullValue:"null when required start/finish endpoints for the selected method are absent.",milestone:"Measured between coincident remaining endpoint and its late endpoint."},Ke=(t,e)=>`Input: canonical activities, relationships, Data Date and settings; phase: ${t}; policy: retained logic/progress override/actual dates relation classification; constraint: primary, secondary and project bounds; calendar: activity and configured lag calendars with exceptions; result: ${e}.`,QC=Object.freeze([Rt({uiName:"Actual Start",property:"actualStart",xerField:"TASK.act_start_date",xmlField:"Activity.ActualStart",classification:"reality",typeAndUnit:"Date | null, exact UTC instant",editability:"controlled",authority:"Imported/user-confirmed actual reality",phase:"input",algorithm:"Input only; status validation may infer status but F9 never moves it.",interactions:"Activity Status, Actual Finish, Actual Duration and OOS policy.",unitTest:ar,p6Golden:Sn}),Rt({uiName:"Actual Finish",property:"actualFinish",xerField:"TASK.act_end_date",xmlField:"Activity.ActualFinish",classification:"reality",typeAndUnit:"Date | null, exact UTC instant",editability:"controlled",authority:"Imported/user-confirmed actual reality",phase:"input",algorithm:"Input only; completed status requires a consistent actual endpoint; F9 never moves it.",interactions:"Activity Status, Actual Start and Actual Duration.",unitTest:ar,p6Golden:Sn}),Rt({uiName:"Planned Start",property:"plannedStart",xerField:"TASK.target_start_date",xmlField:"Activity.PlannedStart",classification:"editable_input",typeAndUnit:"Date | null, exact UTC instant",editability:"editable",authority:"Imported/user input",phase:"input",algorithm:"Initial planning input; never replaced by projected Start.",interactions:"At Completion Duration and not-started fallback.",unitTest:ar,p6Golden:Sn}),Rt({uiName:"Planned Finish",property:"plannedFinish",xerField:"TASK.target_end_date",xmlField:"Activity.PlannedFinish",classification:"editable_input",typeAndUnit:"Date | null, exact UTC instant",editability:"editable",authority:"Imported/user input",phase:"input",algorithm:"Initial planning input; never replaced by projected Finish.",interactions:"At Completion Duration and not-started fallback.",unitTest:ar,p6Golden:Sn}),Rt({uiName:"Remaining Duration",property:"remainingDurationHours",xerField:"TASK.remain_drtn_hr_cnt",xmlField:"Activity.RemainingDuration",classification:"editable_input",typeAndUnit:"number, working hours",editability:"editable",authority:"Imported/user input consumed by explicit F9",phase:"input",algorithm:"Forward pass consumes/preserves remaining working hours according to status and OOS policy.",interactions:"Remaining Early Finish, Actual/At Completion Duration and Duration %.",unitTest:ar,p6Golden:Sn}),Rt({uiName:"Activity Status",property:"executionStatus",xerField:"TASK.status_code",xmlField:"Activity.Status",classification:"reality",typeAndUnit:"not_started | in_progress | completed",editability:"controlled",authority:"Actual-date/status invariant",phase:"input",algorithm:"Validated before F9; scheduling never invents actual dates.",interactions:"Actual endpoints, Remaining Duration and all derived duration fields.",unitTest:"src/p6/status.test.ts",p6Golden:Sn}),Rt({uiName:"Expected Finish",property:"expectedFinish",xerField:"TASK.expect_end_date",xmlField:"Activity.ExpectedFinish",classification:"editable_input",typeAndUnit:"Date | null, exact UTC instant",editability:"editable",authority:"Imported/user input plus useExpectedFinishDates setting",phase:"input",algorithm:"Forward bound only when the project setting enables Expected Finish dates.",interactions:"Use Expected Finish Dates and Remaining Early Finish.",unitTest:"src/p6/testing/p6-native/obdd-native.schedule.test.ts",p6Golden:"src/p6/testing/p6-native/fixtures/obdd-native-step24-expected-finish-calendar-exception.xer"}),Rt({uiName:"Suspend Date",property:"suspendDate",xerField:"TASK.suspend_date",xmlField:"Activity.SuspendDate",classification:"reality",typeAndUnit:"Date | null, exact UTC instant",editability:"editable",authority:"Imported/user actual reality",phase:"input",algorithm:"Preserved; duration derivation subtracts the valid Suspend..Resume overlap.",interactions:"Resume Date, Actual Duration and At Completion Duration.",unitTest:vn,p6Golden:or}),Rt({uiName:"Resume Date",property:"resumeDate",xerField:"TASK.resume_date",xmlField:"Activity.ResumeDate",classification:"reality",typeAndUnit:"Date | null, exact UTC instant",editability:"editable",authority:"Imported/user actual reality",phase:"input",algorithm:"Preserved; duration derivation subtracts the valid Suspend..Resume overlap.",interactions:"Suspend Date, Actual Duration and At Completion Duration.",unitTest:vn,p6Golden:or}),Rt({uiName:"Secondary Constraint",property:"secondaryConstraintType",xerField:"TASK.cstr_type2",xmlField:"Activity.SecondaryConstraintType",classification:"editable_input",typeAndUnit:"canonical P6 constraint enum | null",editability:"editable",authority:"Imported/user input",phase:"input",algorithm:"Constraint classifier applies the declared start/finish lower/upper bound during forward/backward passes.",interactions:"Secondary Constraint Date, primary constraint and calendars.",unitTest:ar,p6Golden:"src/p6/testing/p6-native/fixtures/obdd-native-step18-secondary-finish-on-or-after.xer"}),Rt({uiName:"Secondary Constraint Date",property:"secondaryConstraintDate",xerField:"TASK.cstr_date2",xmlField:"Activity.SecondaryConstraintDate",classification:"editable_input",typeAndUnit:"Date | null, exact UTC instant",editability:"editable",authority:"Imported/user input",phase:"input",algorithm:"Provides the exact bound for Secondary Constraint Type; ignored when type is null.",interactions:"Secondary Constraint Type and early/late passes.",unitTest:ar,p6Golden:"src/p6/testing/p6-native/fixtures/obdd-native-step18-secondary-finish-on-or-after.xer"}),Rt({uiName:"Percent Complete Type",property:"percentCompleteType",xerField:"TASK.complete_pct_type",xmlField:"Activity.PercentCompleteType",classification:"editable_input",typeAndUnit:"duration | units | physical",editability:"editable",authority:"Imported/user input",phase:"input",algorithm:"Selects displayed progress authority; individual derived percentages remain independently calculated.",interactions:"Physical %, Duration %, Units % and progress projection.",unitTest:vn,p6Golden:or}),Rt({uiName:"Physical % Complete",property:"physicalPercentComplete",xerField:"TASK.phys_complete_pct",xmlField:"Activity.PhysicalPercentComplete",classification:"editable_input",typeAndUnit:"number, percentage points 0..100",editability:"editable",authority:"Imported/user physical-progress input",phase:"input",algorithm:"Preserved by F9 and used only when Percent Complete Type is physical.",interactions:"Percent Complete Type and visible progress.",unitTest:ar,p6Golden:Sn}),Rt({uiName:"Actual Duration",property:"actualDurationHours",xerField:"TASK.act_drtn_hr_cnt or actual endpoints",xmlField:"Activity.ActualDuration",classification:"derived",lifecycle:"open",typeAndUnit:"number, working hours",editability:"readonly",authority:"Schedule Core deriveP6ActivityFields",phase:"derived",algorithm:"Status-specific non-negative working duration using actual endpoints/Data Date minus suspended overlap; reversed endpoints clamp to zero.",interactions:"Status, Actual Start/Finish, Data Date, Suspend/Resume and activity calendar.",unitTest:vn,p6Golden:or,status:"PARTIAL",edgeCases:R0}),Rt({uiName:"At Completion Duration",property:"atCompletionDurationHours",xerField:"TASK.total_drtn_hr_cnt or planned/actual/remaining endpoints",xmlField:"Activity.AtCompletionDuration",classification:"derived",lifecycle:"open",typeAndUnit:"number, working hours",editability:"readonly",authority:"Schedule Core deriveP6ActivityFields",phase:"derived",algorithm:"Not started: planned interval; in progress: Actual Start..Remaining Early Finish; completed: actual interval.",interactions:"Status, planned/actual/remaining endpoints, Suspend/Resume and calendar.",unitTest:vn,p6Golden:or,status:"PARTIAL",edgeCases:P0}),Rt({uiName:"Duration % Complete",property:"durationPercentComplete",xerField:"TASK.target_drtn_hr_cnt + remain_drtn_hr_cnt",xmlField:"Activity.DurationPercentComplete",classification:"derived",lifecycle:"open",typeAndUnit:"number, percentage points",editability:"readonly",authority:"Schedule Core deriveP6ActivityFields",phase:"derived",algorithm:"100 \xD7 (Original Duration - Remaining Duration) / Original Duration, clamped to 0..100.",interactions:"Original and Remaining Duration; independent of Percent Complete Type selection.",unitTest:vn,p6Golden:or,status:"PARTIAL",edgeCases:k0}),Rt({uiName:"Units % Complete",property:"unitsPercentComplete",xerField:"TASKRSRC actual and remaining unit scalars",xmlField:"Activity.ResourceAssignment.ActualUnits/RemainingUnits",classification:"derived",lifecycle:"open",typeAndUnit:"number, percentage points",editability:"readonly",authority:"Schedule Core deriveP6ActivityFields over canonical TASK scalars",phase:"derived",algorithm:"100 \xD7 total actual labor/nonlabor units / (actual + remaining units); zero denominator returns 0; finite signed values are not clamped.",interactions:"TASK unit scalars and Percent Complete Type; no full assignment subsystem.",unitTest:vn,p6Golden:or,status:"PARTIAL",edgeCases:b0}),Rt({uiName:"Schedule % Complete",property:"schedulePercentComplete",xerField:"PROJECT.last_recalc_date + assigned baseline TASK dates, otherwise current TASK planned dates",xmlField:"Activity.SchedulePercentComplete",classification:"derived",lifecycle:"dependency_change",typeAndUnit:"number | null, percentage points",editability:"readonly",authority:"Schedule Core deriveP6ActivityFields",phase:"derived",algorithm:"Working effective-baseline time elapsed at Data Date / total working time, clamped to 0..100; a coincident milestone is 100% at its timestamp.",interactions:"Data Date, assigned baseline/current planned dates and activity calendar.",unitTest:vn,p6Golden:or,status:"VERIFIED",edgeCases:L0}),Rt({uiName:"Remaining Float",property:"remainingFloatHours",xerField:"TASK remaining early/late endpoints",xmlField:"Activity.RemainingFloat",classification:"derived",lifecycle:"f9",typeAndUnit:"number | null, signed working hours",editability:"readonly",authority:"Schedule Core deriveP6ActivityFields",phase:"derived",algorithm:"Start Float, Finish Float or their minimum as selected, using signed working duration.",interactions:"Total Float method, remaining early/late endpoints and activity calendar.",unitTest:vn,p6Golden:"src/p6/testing/p6-float-method/fixtures/obdd-float-method-smallest.xer",status:"VERIFIED",edgeCases:O0}),Rt({uiName:"Remaining Early Start",property:"remainingEarlyStart",xerField:"TASK.restart_date",xmlField:"Activity.RemainingEarlyStart",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 forward pass",phase:"forward",algorithm:Ke("forward","earliest start of remaining work"),interactions:"Data Date, predecessors, OOS policy, constraints and calendar.",unitTest:"src/p6/testing/p6-data-date/obdd-math.schedule.test.ts",p6Golden:Sn,status:"VERIFIED"}),Rt({uiName:"Remaining Early Finish",property:"remainingEarlyFinish",xerField:"TASK.reend_date",xmlField:"Activity.RemainingEarlyFinish",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 forward pass",phase:"forward",algorithm:Ke("forward","calendar finish after remaining duration"),interactions:"Remaining Early Start, Remaining Duration, OOS policy and calendar.",unitTest:"src/p6/testing/p6-data-date/obdd-math.schedule.test.ts",p6Golden:Sn,status:"VERIFIED"}),Rt({uiName:"Remaining Late Start",property:"remainingLateStart",xerField:"TASK.rem_late_start_date",xmlField:"Activity.RemainingLateStart",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 backward pass",phase:"backward",algorithm:Ke("backward","latest remaining start without violating successor/project bounds"),interactions:"Remaining Late Finish, constraints, successors and calendar.",unitTest:aa,p6Golden:oa,status:"VERIFIED"}),Rt({uiName:"Remaining Late Finish",property:"remainingLateFinish",xerField:"TASK.rem_late_end_date",xmlField:"Activity.RemainingLateFinish",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 backward pass",phase:"backward",algorithm:Ke("backward","latest remaining finish without violating successor/project bounds"),interactions:"Successors, Must Finish By, constraints and calendar.",unitTest:aa,p6Golden:oa,status:"VERIFIED"}),Rt({uiName:"Early Start",property:"earlyStart",xerField:"TASK.early_start_date",xmlField:"Activity.EarlyStart",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 forward pass",phase:"forward",algorithm:Ke("forward","projected early start respecting immutable actuals"),interactions:"Actual Start, Remaining Early Start and OOS policy.",unitTest:aa,p6Golden:oa,status:"VERIFIED"}),Rt({uiName:"Early Finish",property:"earlyFinish",xerField:"TASK.early_end_date",xmlField:"Activity.EarlyFinish",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 forward pass",phase:"forward",algorithm:Ke("forward","projected early finish respecting immutable actuals"),interactions:"Actual Finish, Remaining Early Finish and OOS policy.",unitTest:aa,p6Golden:oa,status:"VERIFIED"}),Rt({uiName:"Late Start",property:"lateStart",xerField:"TASK.late_start_date",xmlField:"Activity.LateStart",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 backward pass",phase:"backward",algorithm:Ke("backward","projected late start"),interactions:"Remaining Late Start, constraints, float and immutable actuals.",unitTest:aa,p6Golden:oa,status:"VERIFIED"}),Rt({uiName:"Late Finish",property:"lateFinish",xerField:"TASK.late_end_date",xmlField:"Activity.LateFinish",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 backward pass",phase:"backward",algorithm:Ke("backward","projected late finish"),interactions:"Remaining Late Finish, Must Finish By, constraints and float.",unitTest:aa,p6Golden:oa,status:"VERIFIED"}),Rt({uiName:"Float Path",property:"floatPath",xerField:"TASK.float_path",xmlField:"Activity.FloatPath",classification:"f9_output",typeAndUnit:"number | null, path number",editability:"readonly",authority:"Schedule Core P6 float-path pass",phase:"float_path",algorithm:Ke("float_path","selected multiple-float-path identifier"),interactions:"Ending Activity, Total/Free Float selection, enabled and path limit settings.",unitTest:"src/p6/paths.test.ts",p6Golden:"src/p6/testing/p6-floats/fixtures/obdd-floats-multiple-paths-limit-2.xer",status:"VERIFIED"}),Rt({uiName:"Float Path Order",property:"floatPathOrder",xerField:"TASK.float_path_order",xmlField:"Activity.FloatPathOrder",classification:"f9_output",typeAndUnit:"number | null, ordinal",editability:"readonly",authority:"Schedule Core P6 float-path pass",phase:"float_path",algorithm:Ke("float_path","stable order inside the selected float path"),interactions:"Float Path, relationship topology and deterministic tie-breaking.",unitTest:"src/p6/paths.test.ts",p6Golden:"src/p6/testing/p6-floats/fixtures/obdd-floats-multiple-paths-limit-2.xer",status:"VERIFIED"}),Rt({uiName:"Longest Path",property:"longestPath",xerField:"TASK.driving_path_flag",xmlField:"Activity.IsLongestPath",classification:"f9_output",typeAndUnit:"boolean",editability:"readonly",authority:"Schedule Core P6 float-path pass",phase:"float_path",algorithm:Ke("float_path","true for activities on the selected longest path"),interactions:"Critical Activity Method, Ending Activity and deterministic path topology.",unitTest:"src/p6/paths.test.ts",p6Golden:"src/p6/testing/p6-floats/fixtures/obdd-floats-longest-path.xer",status:"VERIFIED"})]);var tD={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 eD=8;var nD={CHILD:"child",LINE:"line",ROOT:"root"};return cD(N0);})();
1
+ "use strict";var ScheduleCore=(()=>{var Dc=Object.defineProperty;var uD=Object.getOwnPropertyDescriptor;var pD=Object.getOwnPropertyNames;var yD=Object.prototype.hasOwnProperty;var fD=(t,e)=>{for(var n in e)Dc(t,n,{get:e[n],enumerable:!0})},hD=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of pD(e))!yD.call(t,i)&&i!==n&&Dc(t,i,{get:()=>e[i],enumerable:!(r=uD(e,i))||r.enumerable});return t};var mD=t=>hD(Dc({},"__esModule",{value:!0}),t);var Z0={};fD(Z0,{ACTIVITY_BATCH_ACTION_KIND:()=>qe,ACTIVITY_BATCH_MODE:()=>Ht,ACTIVITY_DATE_EDGE:()=>fa,ACTIVITY_FIELD:()=>te,ACTIVITY_PONDERATOR_CRITERION:()=>Tt,ACTIVITY_PROGRESS_ORIGIN:()=>ns,ACTIVITY_TYPE:()=>H,BASELINE_ROLE:()=>pa,CALENDAR_UNIT:()=>gt,CHANGE_SET_SOURCE_KIND:()=>de,COLUMN:()=>E,COMPLETED_PROGRESS:()=>Ft,CONFIRMATION_KIND:()=>ie,CONSTRAINT_TYPE:()=>_,CONSTRAINT_TYPE_TO_LABEL:()=>sD,CONSTRAINT_WARNING_KIND:()=>Dr,CREATION_KIND:()=>cD,DATA_DATE_PROPERTY_CONTRACT:()=>oD,DATE_GESTURE_KIND:()=>Se,DEFAULT_HOURS_PER_DAY:()=>lD,DISPATCH_ACTION_KIND:()=>I,DISPATCH_ACTION_KINDS:()=>Op,DISPATCH_LINK_OPERATION_KIND:()=>Lt,DISPATCH_TRACK_EVENT:()=>Le,DataDateCapabilityError:()=>Te,EDIT_ALERT_KEY:()=>Xo,EDIT_DENIAL_REASON:()=>He,ENTITY_CHANGE_KIND:()=>W,FILTER_FIELD:()=>ut,FILTER_LOGIC:()=>ni,FILTER_OPERATOR:()=>nt,FILTER_REJECTION_REASON:()=>Nt,FILTER_VALUE_KIND:()=>Y,FLAT_WBS_DEPTH:()=>wo,GROUP_ID_PREFIX:()=>Rc,GROUP_ID_SEPARATOR:()=>ri,LINK_BATCH_OPERATION_KIND:()=>ei,LINK_CODE:()=>Be,LINK_CODE_TO_TYPE:()=>_r,LINK_REJECTION_REASON:()=>Ot,LINK_RELATIONSHIP:()=>cr,LINK_TYPE:()=>q,LINK_TYPE_CODE:()=>Ts,LOOKAHEAD_CONFIRMATION_KIND:()=>fl,LookaheadActualTransitionError:()=>Jr,MINIMUM_GROUP_DEPTH:()=>Fo,MINIMUM_GROUP_LEVEL:()=>En,NEW_ACTIVITY_DEFAULTS:()=>dl,NOT_STARTED_PROGRESS:()=>se,ORDER_DIRECTION:()=>ce,ORDER_MODE:()=>an,PASTE_PLACEMENT:()=>pl,PERSISTENCE_REBASE_CONFLICT_KIND:()=>$t,PERSISTENCE_REBASE_ENTITY:()=>Gt,REJECTION_REASON:()=>D,RESTORABLE_ACTIVITY_FIELDS:()=>kd,ROOT_PARENT_ID:()=>Z,SCHEDULE_CORE_STATUS:()=>Ke,SCHEDULE_EFFECT_KIND:()=>ba,SIR_AUTO_REJECT_REASON:()=>La,STATUS:()=>le,STATUS_CRITERIA:()=>Dn,STRUCTURE_ACTIVITY_FIELDS:()=>bd,ScheduleCore:()=>la,UNASSIGNED_GROUP_LABEL:()=>No,UNASSIGNED_VALUE_ID:()=>yr,VIEW_ATTRIBUTE_KIND:()=>ur,VISUAL_ROW_KIND:()=>ii,WORK_TIME_DIRECTION:()=>mt,activityBackendRow:()=>GC,allowedSecondaryConstraintTypes:()=>Yc,appendGroupRowId:()=>Mo,buildGroupRowId:()=>xo,checkNoUpdatedLinks:()=>tA,computeExpectedProgress:()=>id,createCalendarReader:()=>aD,createLookaheadDerivedFields:()=>iD,createOutbuildDataDateScheduleSettings:()=>aa,createSchedule:()=>BC,dataDateInputFromDto:()=>QC,decodeWireValue:()=>$r,encodeWireValue:()=>qr,expectedProgressFromBaseline:()=>Ri,formatUtcAsP6WallDate:()=>yv,getActiveBaseline:()=>Kt,getUnsavedActivities:()=>eD,hostScheduleInput:()=>VC,isRestorableActivityField:()=>$s,isRevertibleActivityField:()=>qs,isRootParent:()=>G,isViewAttributeCriterion:()=>pr,isViewAttributeOrderRule:()=>ai,linkBackendRow:()=>qC,loadTimeWork:()=>WC,mapDataDateScheduleOptions:()=>mv,movedToAnotherUtcDay:()=>Ei,normalizeParentKey:()=>pe,parseFromBackend:()=>dc,parseP6DayAsCalendarStart:()=>ic,parseP6WallDateAsUtc:()=>rc,planLookaheadProgressActuals:()=>Rp,prepareLookaheadProgressActuals:()=>Sc,prepareLookaheadProgressActualsForPersistence:()=>nD,rescheduledOnLoad:()=>KC,resolveExpectedFinishDateSelection:()=>rD,resolveLookaheadActualDateSelection:()=>vc,serializeDataDateActivity:()=>_p,serializeDataDateSettings:()=>Ic,serializeDataDateState:()=>tD,willRunCriticalPath:()=>sC,yieldToBrowser:()=>wt});var Eo={CONSTRAINT:"constraint",ALERT:"alert",WARNING:"warning"},mt={FUTURE:"future",PAST:"past"},gt={MINUTE:"minute",HOUR:"hour",DAY:"day"},Tt={DURATION:"DURATION",COST:"COST",WORK_HOURS:"HH"},Dn={BASELINE:"Baseline",ACTUAL:"Actual"},pa={PROJECT:1,PRIMARY:2},le={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"},W={CREATED:"created",UPDATED:"updated",DELETED:"deleted"};var _={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},gD={[_.MSO]:()=>!0,[_.MFO]:()=>!0,[_.SNLT]:(t,e)=>t<e,[_.SNET]:(t,e)=>t>e,[_.FNLT]:(t,e)=>t<e,[_.FNET]:(t,e)=>t>e};function Po(t,e,n){if(!e)return{violated:!1};let r=gD[t];return r?r(e,n)?{violated:!0,constraintType:t,constraintDate:e}:{violated:!1}:{violated:!1}}var AD=new Set([_.MSO,_.SNET,_.SNLT]);function lr(t,e,n){return AD.has(t)?e:n}function ko(t,e,n){return{type:Eo.CONSTRAINT,messageKey:"constraint_violation",data:{constraintType:t,constraintDate:e,...n?{projectedDate:n}:{}}}}var ID={[_.SNET]:{startOfDay:!0,direction:mt.FUTURE},[_.SNLT]:{startOfDay:!0,direction:mt.PAST},[_.FNET]:{startOfDay:!1,direction:mt.FUTURE},[_.FNLT]:{startOfDay:!1,direction:mt.PAST},[_.MSO]:{startOfDay:!0,direction:mt.FUTURE},[_.MFO]:{startOfDay:!1,direction:mt.PAST}},Ro=t=>new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())),bp=(t,e)=>new Date(t.getTime()+e*864e5),SD=(t,e)=>t.getUTCFullYear()===e.getUTCFullYear()&&t.getUTCMonth()===e.getUTCMonth()&&t.getUTCDate()===e.getUTCDate();function ya(t,e){if(!t.constraintDate||!t.constraintType)return null;let n=ID[t.constraintType];if(!n)return t.constraintDate;let r=t.constraintDate,i=e.getClosestWorkTime({date:Ro(r),dir:mt.FUTURE,task:t});if(SD(i,r))return r.getTime()!==Ro(r).getTime()?r:n.startOfDay?i:e.getClosestWorkTime({date:bp(Ro(r),1),dir:mt.PAST,task:t});let a=Ro(e.getClosestWorkTime({date:r,dir:n.direction,task:t}));return n.startOfDay?e.getClosestWorkTime({date:a,dir:mt.FUTURE,task:t}):e.getClosestWorkTime({date:bp(a,1),dir:mt.PAST,task:t})}function Tn(t,e){let n={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},r=t.constraintType;if(!r||r===_.ASAP||r===_.ALAP)return n;let i=ya(t,e);if(!i)return n;let a=s=>e.calculateEndDate({startDate:s,durationHours:t.durationHours,task:t}),o=s=>e.calculateEndDate({startDate:s,durationHours:-t.durationHours,task:t});switch(r){case _.SNET:return{earliestStart:i,latestStart:null,earliestEnd:a(i),latestEnd:null};case _.SNLT:return{earliestStart:null,latestStart:i,earliestEnd:null,latestEnd:a(i)};case _.FNET:return{earliestStart:o(i),latestStart:null,earliestEnd:i,latestEnd:null};case _.FNLT:return{earliestStart:null,latestStart:o(i),earliestEnd:null,latestEnd:i};case _.MSO:{let s=a(i);return{earliestStart:i,latestStart:i,earliestEnd:s,latestEnd:s}}case _.MFO:{let s=o(i);return{earliestStart:s,latestStart:s,earliestEnd:i,latestEnd:i}}default:return n}}function Lp(t,e){return!(e.earliestStart&&t<e.earliestStart||e.latestStart&&t>e.latestStart)}function Tc(t,e){return e.latestStart&&t>e.latestStart?e.latestStart:e.earliestStart&&t<e.earliestStart?e.earliestStart:t}var q={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"},vD=Object.values(q);function bo(t){return vD.includes(t)}var ti={ACTUAL_START:"actualStart",ACTUAL_FINISH:"actualFinish",PLANNED_START:"plannedStart",PLANNED_FINISH:"plannedFinish",REMAINING_DURATION_HOURS:"remainingDurationHours",EXECUTION_STATUS:"executionStatus",EXPECTED_FINISH:"expectedFinish",SUSPEND_DATE:"suspendDate",RESUME_DATE:"resumeDate",SECONDARY_CONSTRAINT_TYPE:"secondaryConstraintType",SECONDARY_CONSTRAINT_DATE:"secondaryConstraintDate",PERCENT_COMPLETE_TYPE:"percentCompleteType",PHYSICAL_PERCENT_COMPLETE:"physicalPercentComplete"},CD={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",...ti},DD={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",BASELINE_VARIANCE:"baseline_variance",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={...CD,...DD};var Ut={CREATE:"create",UPDATE:"update",DELETE:"delete"},Ot={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_CLIPBOARD_IMPORT:"activity-clipboard-import",ACTIVITY_COPY:"activity-copy",CALENDAR_RECONCILE:"calendar-reconcile",ACTIVITY_PASTE_COPIED:"activity-paste-copied",ACTIVITY_DUPLICATE:"activity-duplicate",CELL_COPY:"cell-copy",CELL_CLIPBOARD_CLEAR:"cell-clipboard-clear",CELL_PASTE_COPIED:"cell-paste-copied",PERSISTENCE_ACKNOWLEDGE:"persistence-acknowledge",PERSISTENCE_REBASE:"persistence-rebase",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_FIELDS_RESTORE:"activity-fields-restore",HISTORY_REVERT:"history-revert",ACTIVITY_SET_PROGRESS:"activity-set-progress",ACTIVITY_LOOKAHEAD_CONVERT:"activity-lookahead-convert",SELECTION_TOGGLE:"selection-toggle",SELECTION_REPLACE:"selection-replace",VISIBILITY_SET:"visibility-set",FILTER_SET:"filter-set",SORT_SET:"sort-set",VIEW_ATTRIBUTES_SET:"view-attributes-set",GROUP_SET:"group-set",WBS_DEPTH_SET:"wbs-depth-set",SIR_SYNC:"sir-sync",ACTIVITY_LOOKAHEAD_SYNC:"activity-lookahead-sync",SCHEDULE_AUTO_SCHEDULE:"schedule-auto-schedule"},qe="activity-batch",Lt=Ut,Op=Object.values(I);function Kt(t){let e=t?.baselinePoints;return!Array.isArray(e)||e.length===0?null:e.find(n=>n.isActiveVersion)??null}var te={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"},fa={START:"start",END:"end"},cr={FINISH_TO_START:"finish-to-start",START_TO_START:"start-to-start",FINISH_TO_FINISH:"finish-to-finish",START_TO_FINISH:"start-to-finish"},ei={CREATE:"create",UPDATE:"update",REMOVE:"remove"};var TD={[te.NAME]:E.TEXT,[te.DESCRIPTION]:E.DESCRIPTION,[te.DURATION_DAYS]:E.DURATION,[te.PROGRESS]:E.PROGRESS,[te.COST]:E.COST,[te.USED_COST]:E.USED_COST,[te.WORK_HOURS]:E.HH_WORK_TIME,[te.START_DATE]:E.START_DATE,[te.END_DATE]:E.END_DATE,[te.CONSTRAINT_TYPE]:E.CONSTRAINT_TYPE,[te.CONSTRAINT_DATE]:E.CONSTRAINT_DATE,[te.CALENDAR_ID]:E.CALENDAR_ID,[te.CUSTOM_ID]:E.CUSTOM_ID,[te.SUBCONTRACT_ID]:E.SUBCONTRACT_ID,[te.RESPONSABLE_IDS]:E.RESPONSABLES,[te.TAG_IDS]:E.TAGS};function _c(t,e){return{activityId:t,column:TD[e.field],newValue:e.value}}var _D={[cr.FINISH_TO_START]:q.FINISH_TO_START,[cr.START_TO_START]:q.START_TO_START,[cr.FINISH_TO_FINISH]:q.FINISH_TO_FINISH,[cr.START_TO_FINISH]:q.START_TO_FINISH};function ha(t){return _D[t]}function ED(t){return t.kind===ei.CREATE?{kind:Lt.CREATE,source:t.sourceId,target:t.targetId,type:ha(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}}:t.kind===ei.UPDATE?{kind:Lt.UPDATE,linkId:t.linkId,...t.sourceId===void 0?{}:{source:t.sourceId},...t.targetId===void 0?{}:{target:t.targetId},...t.relationship===void 0?{}:{type:ha(t.relationship)},...t.lagDays===void 0?{}:{lag:t.lagDays}}:t.kind===ei.REMOVE?{kind:Lt.DELETE,linkId:t.linkId}:t}function RD(t){return t===fa.START?E.START_DATE:t===fa.END?E.END_DATE:t}function PD(t){return{kind:qe,mode:t.mode,items:t.items,links:t.links.map(e=>({source:e.source,target:e.target,type:ha(e.relationship),...e.lagDays===void 0?{}:{lag:e.lagDays},...e.linkId===void 0?{}:{linkId:e.linkId}})),...t.eventSource===void 0?{}:{eventSource:t.eventSource}}}function kD(t){return{get:e=>t.getActivityView(e),list:()=>t.getAllActivitiesView(),ids:()=>t.getAllIds(),forEachId:e=>t.forEachActivityId(e),property:(e,n)=>t.getProperty(e,n),children:e=>t.getChildrenView(e),childIds:e=>t.getChildrenIds(e),hasChildren:e=>t.hasChild(e),indentTargetParentIds:e=>t.getIndentTargetParentIds(e),leafParentIdsPromotedBy:e=>t.getLeafParentIdsPromotedBy(e),lookaheadConfirmationFor:(e,n)=>t.getLookaheadConfirmation(e,n),isCustomIdInUse:(e,n)=>t.isCustomIdInUse(e,n??null),clipboard:()=>t.getActivityClipboardView(),create:(e,n)=>t.dispatch({...e,kind:I.ACTIVITY_CREATE},n),applyBatch:(e,n)=>t.applyActivityBatch(PD(e),n),editInline:(e,n,r)=>t.dispatch({..._c(e,n),kind:I.INLINE_EDIT},r),setType:(e,n,r)=>t.dispatch({kind:I.ACTIVITY_TYPE_SET,activityId:e,type:n},r),applyDragBatch:(e,n)=>t.dispatch({kind:I.DATES_BATCH,edits:e.map(r=>({activityId:r.activityId,column:RD(r.edge),newValue:r.value}))},n),editFields:(e,n)=>t.dispatch({kind:I.BULK_EDIT,edits:e.map(r=>_c(r.activityId,r))},n),remove:(e,n={},r)=>{let i={...n,kind:I.ACTIVITY_DELETE,activityIds:e};return r===void 0?t.dispatch(i):t.dispatch(i,r)},move:(e,n)=>t.dispatch({...e,kind:I.ACTIVITY_MOVE},n),planLookaheadConversion:e=>t.planLookaheadConversion(e),applyLookaheadConversion:e=>t.applyLookaheadConversion(e),indent:(e,n={})=>t.dispatch({...n,kind:I.ACTIVITY_INDENT,activityIds:e}),outdent:(e,n={})=>t.dispatch({...n,kind:I.ACTIVITY_OUTDENT,activityIds:e}),setProgress:(e,n,r={})=>t.dispatch({...r,kind:I.ACTIVITY_SET_PROGRESS,activityId:e,newValue:n}),copy:(e={})=>t.dispatch({...e,kind:I.ACTIVITY_COPY}),paste:(e,n={},r)=>{let i={...n,kind:I.ACTIVITY_PASTE_COPIED,destination:{afterSiblingId:e}};return r===void 0?t.dispatch(i):t.dispatch(i,r)},duplicate:(e,n={})=>t.dispatch({...n,kind:I.ACTIVITY_DUPLICATE,activityIds:e}),clearClipboard:(e={})=>t.dispatch({...e,kind:I.ACTIVITY_CLIPBOARD_CLEAR}),importClipboard:(e,n,r={})=>t.dispatch({...r,kind:I.ACTIVITY_CLIPBOARD_IMPORT,snapshot:e,...n===void 0?{}:{references:n}}),lookaheadSync:e=>t.dispatch({...e,kind:I.ACTIVITY_LOOKAHEAD_SYNC}),restoreFields:e=>t.dispatch({...e,kind:I.ACTIVITY_FIELDS_RESTORE}),revert:e=>t.dispatch({...e,kind:I.HISTORY_REVERT}),autoSchedule:(e,n)=>t.dispatch({kind:I.SCHEDULE_AUTO_SCHEDULE,...e===void 0?{}:{activityId:e}},n),createDateGesturePreview:e=>t.createDateGesturePreview(e)}}function bD(t){return{copy:(e,n,r,i={})=>t.dispatch({...i,kind:I.CELL_COPY,activityId:e,column:n,...r===void 0?{}:{copiedText:r}}),paste:(e,n,r,i={})=>t.dispatch({...i,kind:I.CELL_PASTE_COPIED,activityIds:e,column:n,...r===void 0?{}:{clipboardText:r}}),clearClipboard:(e={})=>t.dispatch({...e,kind:I.CELL_CLIPBOARD_CLEAR})}}function LD(t){return{get:e=>t.getLinkView(e),list:()=>t.getAllLinksView(),forActivity:e=>t.getLinksForActivityView(e),create:(e,n)=>t.dispatch({kind:I.LINK_CREATE,source:e.sourceId,target:e.targetId,type:ha(e.relationship),...e.lagDays===void 0?{}:{lag:e.lagDays},...e.linkId===void 0?{}:{linkId:e.linkId}},n),update:(e,n,r)=>t.dispatch({kind:I.LINK_UPDATE,linkId:e,...n.sourceId===void 0?{}:{source:n.sourceId},...n.targetId===void 0?{}:{target:n.targetId},...n.relationship===void 0?{}:{type:ha(n.relationship)},...n.lagDays===void 0?{}:{lag:n.lagDays}},r),remove:(e,n)=>t.dispatch({kind:I.LINK_DELETE,linkId:e},n),batch:(e,n)=>t.dispatch({kind:I.LINKS_BATCH,operations:e.map(ED)},n)}}function Np(t){let e=(n,r)=>t.dispatch({kind:I.BASELINE_APPLY,points:n},r);return{activities:kD(t),cells:bD(t),links:LD(t),calendars:{get:n=>t.getCalendar(n),list:()=>t.getAllCalendars(),listBase:()=>t.getBaseCalendars(),projectWorkHours:()=>t.getProjectWorkHours(),reconcile:n=>t.dispatch({kind:I.CALENDAR_RECONCILE},n)},selection:{ids:()=>t.getSelectedActivityIds(),toggle:({checked:n,...r})=>t.dispatch({...r,kind:I.SELECTION_TOGGLE,isChecked:n}),replace:(n,r={})=>t.dispatch({...r,kind:I.SELECTION_REPLACE,activityIds:n})},view:{hiddenActivityIds:()=>t.getHiddenActivityIds(),visibleActivityIds:()=>t.getVisibleActivityIds(),visualOrderIds:()=>t.getVisualOrderIds(),visualRows:()=>t.getVisualRows(),filter:()=>t.getActiveFilter(),setFilter:n=>t.dispatch({...n,kind:I.FILTER_SET}),order:()=>t.getActiveOrder(),setOrder:(n,r={})=>t.dispatch({...r,kind:I.SORT_SET,rules:n}),group:()=>t.getActiveGroup(),setViewAttributes:(n,r={})=>t.dispatch({...r,kind:I.VIEW_ATTRIBUTES_SET,catalogs:n}),setGroup:(n,r={})=>t.dispatch({...r,kind:I.GROUP_SET,group:n}),wbsDepth:()=>t.getWbsDepth(),setWbsDepth:(n,r={})=>t.dispatch({...r,kind:I.WBS_DEPTH_SET,wbsDepth:n}),setVisibility:(n,r={})=>t.dispatch({...r,kind:I.VISIBILITY_SET,visibleIds:n}),setStatusCriteria:(n,r)=>t.dispatch({kind:I.STATUS_CRITERIA_SET,criteria:n},r)},baselines:{refresh:e,setVisibility:e,setPonderatorCriterion:(n,r)=>t.dispatch({kind:I.PONDERATOR_CRITERION_SET,criterion:n},r),activeFor:n=>Kt(n)},impactRequests:{sync:n=>t.dispatch({...n,kind:I.SIR_SYNC})},persistence:{hasChanges:()=>t.hasUnsavedChanges(),modifiedActivities:()=>t.getModifiedActivities(),modifiedActivityFields:()=>t.getModifiedActivityFields(),modifiedActivityChanges:()=>t.getModifiedActivityChanges(),newActivities:()=>t.getNewActivities(),deletedActivities:()=>t.getDeletedActivitiesSinceLastSave(),modifiedLinks:()=>t.getModifiedLinks(),newLinks:()=>t.getNewLinks(),deletedLinks:()=>t.getDeletedLinksSinceLastSave(),captureHistoryBoundary:()=>t.capturePersistenceHistoryBoundary(),readSnapshot:()=>t.readPersistenceCheckpoint(),acknowledge:n=>t.dispatch({kind:I.PERSISTENCE_ACKNOWLEDGE,checkpoint:n}),rebase:n=>t.dispatch({kind:I.PERSISTENCE_REBASE,remote:n})},history:{undo:n=>t.undo(n),redo:n=>t.redo(n),canUndo:()=>t.canUndo(),canRedo:()=>t.canRedo(),clear:()=>t.clearHistory(),depth:()=>t.undoDepth()},projection:{changeSetFrom:n=>t.createProjectionChangeSetFrom(n)},criticalPath:{get ready(){return t.criticalPathReady},recompute:()=>t.recomputeCriticalPath(),isSettled:()=>t.isCriticalPathSettled(),whenSettled:()=>t.whenCriticalPathSettled()},diagnostics:{auditEffectiveGraph:()=>t.auditEffectiveGraph(),revision:()=>t.getScheduleRevision(),stateRevision:()=>t.getStateRevision(),canonicalDigest:()=>t.getCanonicalDigest(),canonicalFingerprint:()=>t.getCanonicalFingerprint()}}}var _e=class{items=[];head=0;enqueue(e){this.items.push(e)}dequeue(){if(this.head>=this.items.length)return;let e=this.items[this.head];return this.head+=1,e}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 Lo=t=>String(t);function Fp(t){let{clickedId:e,isChecked:n,currentSelection:r,hierarchy:i,isFrozen:a,exists:o,autoCheckParents:s}=t,l=Lo(e),c=new Set([...r].map(String)),d=new Set(c),u=OD(l,i).filter(o),p=u.filter(f=>!a(f)),y=n&&p.length<u.length;n&&!y?d.add(l):d.delete(l);for(let f of p)n?d.add(f):d.delete(f);return y||ND({id:l,isChecked:n,autoCheckParents:s,hierarchy:i,isFrozen:a,exists:o,next:d}),{nextSelection:d,changed:FD(c,d),parentBlocked:y}}function OD(t,e){let n=[],r=new _e;r.enqueue(t);let i=new Set([t]);for(;!r.isEmpty();){let a=r.dequeue();for(let o of e.getChildrenIds(a)){let s=Lo(o);i.has(s)||(i.add(s),n.push(s),r.enqueue(s))}}return n}function ND(t){let{id:e,isChecked:n,autoCheckParents:r,hierarchy:i,isFrozen:a,exists:o,next:s}=t,l=i.getParentId(e);for(;l!==null&&typeof l<"u";){let c=Lo(l);if(a(c))return;let d=i.getChildrenIds(c).map(Lo).filter(o),u=d.some(a),p=d.filter(m=>!a(m)),f=p.length>0&&p.every(m=>s.has(m))&&!u;if(n){if(!r||!f||s.has(c))return;s.add(c)}else{if(f||!s.has(c))return;s.delete(c)}l=i.getParentId(c)}}function FD(t,e){let n=[],r=[];for(let i of e)t.has(i)||n.push(i);for(let i of t)e.has(i)||r.push(i);return{checked:n,unchecked:r}}var D={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",CONFIRMATION_REQUIRED:"confirmation_required",DATA_DATE_ACTUAL_START_LOCKED:"data_date_actual_start_locked",DATA_DATE_ACTIVITY_COMPLETED:"data_date_activity_completed",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",CLIPBOARD_SNAPSHOT_INVALID:"clipboard_snapshot_invalid",CELL_PASTE_COLUMN_MISMATCH:"cell_paste_column_mismatch",ACTIVITY_PASTE_INVARIANT_FAILED:"activity_paste_invariant_failed",SOLE_SCHEDULE_ROOT:"sole_schedule_root",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",MANUAL_SCHEDULING_ACTIVE:"manual_scheduling_active",SANDBOX_PERSISTENCE_FORBIDDEN:"sandbox_persistence_forbidden",PERSISTENCE_TRACKING_DISABLED:"persistence_tracking_disabled",STALE_STATE_REVISION:"stale-state-revision",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var wp=(t,e,n)=>{let r=[],i=(a,o)=>{let s=e.isChecked(a);e.setChecked(a,o)&&r.push({activityId:a,checked:{before:s,after:o}})};for(let a of n.checked)i(a,!0);for(let a of n.unchecked)i(a,!1);return{source:t,activities:[],links:[],calendars:[],trackingEvents:[],viewState:r}};function xp(t,e){let{adapter:n}=e,r=t.activityId;if(!n.getActivity(r))return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};let i=new Set((t.frozenIds??[]).map(String)),a=s=>i.has(s),o=Fp({clickedId:r,isChecked:t.isChecked,currentSelection:new Set(n.checkedIds().map(String)),hierarchy:{getChildrenIds:s=>n.getChildren(s),getParentId:s=>{let l=n.getParentId(s);return!l||l==="0"?null:String(l)}},isFrozen:a,exists:s=>n.activityExists(s),autoCheckParents:t.autoCheckParents??!1});return{ok:!0,changes:wp(t,n,o.changed)}}function Oo(t,e){let{adapter:n}=e,r=new Set(t.activityIds.map(String).filter(o=>n.activityExists(o))),i=new Set(n.checkedIds().map(String)),a={checked:[...r].filter(o=>!i.has(o)),unchecked:[...i].filter(o=>!r.has(o))};return{ok:!0,changes:wp(t,n,a)}}function dr(t,e,n=t.getAllIds()){let r=[];for(let i of n){let a=String(i),o=e.has(a),s=t.isVisible(a);s!==o&&(t.setVisible(a,o),r.push({activityId:a,visible:{before:s,after:o}}))}return r}function Mp(t,e){let{adapter:n}=e,r=new Set(t.visibleIds.map(String)),i=dr(n,r);return{ok:!0,changes:{source:t,activities:[],links:[],calendars:[],trackingEvents:[],viewState:i}}}var H={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},wD=Object.values(H);function ma(t){return wD.includes(t)}var Up={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var ur="viewAttribute";var Y={STRING:"string",NUMBER:"number",DATE:"date",ID_ARRAY:"id-array",ENUM:"enum",BOOLEAN:"boolean",REFERENCE:"reference"},ut={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_VARIANCE_DAYS:"baselineVarianceDays",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",FLOAT_PATH:"floatPath",FLOAT_PATH_ORDER:"floatPathOrder"},nt={INCLUDES:"includes",NOT_INCLUDES:"notIncludes",IS:"is",IS_NOT:"isNot",EQUALS:"equals",NOT_EQUALS:"notEquals",GREATER_THAN:"greaterThan",LESS_THAN:"lessThan",GREATER_OR_EQUAL:"greaterOrEqual",LESS_OR_EQUAL:"lessOrEqual",AFTER:"after",BEFORE:"before",BETWEEN:"between",SOME_OF:"someOf",NOT_SOME_OF:"notSomeOf"};function pr(t){return"kind"in t&&t.kind===ur}var ni={AND:"and",OR:"or"};var xD=2,MD=[le.WAITING,le.DONE,le.DOING,le.OVERDUE,le.ADVANCEMENT],UD=[_.MFO,_.MSO,_.SNLT,_.SNET,_.ALAP,_.ASAP,_.FNET,_.FNLT],HD=1e3*60*60*24;function Ec(t,e){return t===null||e<=0?null:t/e}function BD(t,e){let n=Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()),r=Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate());return Math.floor((r-n)/HD)+1}var jD={[ut.NAME]:{valueKind:Y.STRING,extract:t=>t.name},[ut.DESCRIPTION]:{valueKind:Y.STRING,extract:t=>t.description},[ut.CUSTOM_ID]:{valueKind:Y.STRING,extract:t=>t.customId},[ut.CORRELATIVE_ID]:{valueKind:Y.NUMBER,extract:t=>t.correlativeId},[ut.UNIQUE_CORRELATIVE_ID]:{valueKind:Y.NUMBER,extract:t=>{let e=Number(t.uniqueCorrelativeId);return Number.isFinite(e)?e:null}},[ut.PROGRESS]:{valueKind:Y.NUMBER,extract:t=>t.progress},[ut.DURATION_DAYS]:{valueKind:Y.NUMBER,extract:(t,e)=>Ec(t.durationHours,e.hoursPerDay)},[ut.CALENDAR_DURATION]:{valueKind:Y.NUMBER,extract:t=>t.type===H.MILESTONE?0:BD(t.startDate,t.endDate)},[ut.COST]:{valueKind:Y.NUMBER,extract:t=>t.cost},[ut.USED_COST]:{valueKind:Y.NUMBER,extract:t=>t.usedCost},[ut.REAL_COST]:{valueKind:Y.NUMBER,extract:t=>t.realCost},[ut.WORK_HOURS]:{valueKind:Y.NUMBER,extract:t=>t.workHours},[ut.REAL_WORK_HOURS]:{valueKind:Y.NUMBER,extract:t=>t.realWorkHours},[ut.PONDERATOR]:{valueKind:Y.NUMBER,extract:t=>t.ponderator},[ut.FREE_SLACK_DAYS]:{valueKind:Y.NUMBER,extract:(t,e)=>Ec(t.freeSlackHours,e.hoursPerDay)},[ut.TOTAL_SLACK_DAYS]:{valueKind:Y.NUMBER,extract:(t,e)=>Ec(t.criticalPath?.totalSlackHours??null,e.hoursPerDay)},[ut.EXPECTED_PROGRESS_BASELINE]:{valueKind:Y.NUMBER,equalityPrecision:xD,extract:t=>t.expectedProgressBaseline},[ut.EXPECTED_PROGRESS]:{valueKind:Y.NUMBER,extract:t=>t.expectedProgress},[ut.BASELINE_DURATION_DAYS]:{valueKind:Y.NUMBER,extract:t=>t.baselineSnapshot?.durationDays??null},[ut.BASELINE_VARIANCE_DAYS]:{valueKind:Y.NUMBER,extract:t=>t.baselineVarianceDays},[ut.BASELINE_COST]:{valueKind:Y.NUMBER,extract:t=>t.baselineSnapshot?.cost??null},[ut.BASELINE_WORK_HOURS]:{valueKind:Y.NUMBER,extract:t=>t.baselineSnapshot?.workHours??null},[ut.START_DATE]:{valueKind:Y.DATE,extract:t=>t.startDate},[ut.END_DATE]:{valueKind:Y.DATE,extract:t=>t.endDate},[ut.CONSTRAINT_DATE]:{valueKind:Y.DATE,extract:t=>t.constraintDate},[ut.BASELINE_START_DATE]:{valueKind:Y.DATE,extract:t=>t.baselineSnapshot?.startDate??null},[ut.BASELINE_END_DATE]:{valueKind:Y.DATE,extract:t=>t.baselineSnapshot?.endDate??null},[ut.EARLY_START]:{valueKind:Y.DATE,extract:t=>t.criticalPath?.earlyStart??null},[ut.EARLY_FINISH]:{valueKind:Y.DATE,extract:t=>t.criticalPath?.earlyFinish??null},[ut.LATE_START]:{valueKind:Y.DATE,extract:t=>t.criticalPath?.lateStart??null},[ut.LATE_FINISH]:{valueKind:Y.DATE,extract:t=>t.criticalPath?.lateFinish??null},[ut.RESPONSABLE_IDS]:{valueKind:Y.ID_ARRAY,extract:t=>t.responsableIds},[ut.TAG_IDS]:{valueKind:Y.ID_ARRAY,extract:t=>t.tagIds},[ut.STATUS]:{valueKind:Y.ENUM,order:MD,extract:t=>t.status},[ut.CONSTRAINT_TYPE]:{valueKind:Y.ENUM,order:UD,extract:t=>t.constraintType},[ut.CALENDAR_ID]:{valueKind:Y.REFERENCE,extract:t=>t.calendarId===null?null:String(t.calendarId)},[ut.SUBCONTRACT_ID]:{valueKind:Y.REFERENCE,extract:t=>t.subcontractId===null?null:String(t.subcontractId)},[ut.IS_CRITICAL]:{valueKind:Y.BOOLEAN,extract:t=>t.isCritical},[ut.FLOAT_PATH]:{valueKind:Y.NUMBER,extract:t=>t.p6?.floatPath??null},[ut.FLOAT_PATH_ORDER]:{valueKind:Y.NUMBER,extract:t=>t.p6?.floatPathOrder??null}};function _n(t){return jD[t]??null}var ii={GROUP:"group",ACTIVITY:"activity"},yr="unassigned",Rc="g",ri=":",No="Unassigned",Fo=1,En=1,wo=0;function xo(t,e){return`${Rc}${ri}${t}${ri}${e}`}function Mo(t,e,n){return`${t}${ri}${e}${ri}${n}`}var Bp=null;function Hp(t){return t===Bp?"":t}function jp(t){let e=new Map,n=new Map;for(let l of t.values){e.set(l.id,l);let c=Hp(l.parentId),d=n.get(c)??[];d.push(l),n.set(c,d)}for(let l of n.values())l.sort((c,d)=>c.sequence!==d.sequence?c.sequence-d.sequence:c.id.localeCompare(d.id));let r=new Map,i=new Map,a=(l,c,d)=>{let u=n.get(Hp(l))??[];for(let p of u){let y=[...c,p.id],f=[...d,p.sequence];r.set(p.id,y),i.set(p.id,f),a(p.id,y,f)}};a(Bp,[],[]);let o=new Map;for(let l of e.keys()){let c=new Set([l]);for(let[d,u]of r)u.includes(l)&&c.add(d);o.set(l,c)}let s=new Map;for(let l of t.assignments)e.has(l.valueId)&&s.set(String(l.activityId),l.valueId);return{key:t.key,valueById:e,pathByValueId:r,sequencePathByValueId:i,descendantIdsByValueId:o,assignmentByActivityId:s}}var Uo=new Map;function Vp(t,e){let n=new Set;for(let r of e){let i=t.descendantIdsByValueId.get(r);if(i===void 0){n.add(r);continue}for(let a of i)n.add(a)}return n}function Wp(t,e,n,r){let i=Math.max(n,En),a=t.pathByValueId.get(e);return a===void 0||a.length===0?i>En?[]:[e]:a.slice(i-1,Math.max(r,i))}function Kp(t,e,n){let r=n.get(e.key),i=r?.assignmentByActivityId.get(String(t.id))??null,a=r?Vp(r,e.value):new Set(e.value),o=i!==null&&a.has(i);return e.operator===nt.SOME_OF?o:e.operator===nt.NOT_SOME_OF?!o:!1}function Pc(t){return t instanceof Date?t:typeof t=="string"||typeof t=="number"?new Date(t):new Date(Number.NaN)}function rn(t){return Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())}function VD(t,e,n){let r=t===null;return n===nt.INCLUDES?!r&&String(t).toLowerCase().includes(e.toLowerCase()):n===nt.NOT_INCLUDES?r||!String(t).toLowerCase().includes(e.toLowerCase()):n===nt.IS?!r&&String(t)===e:n===nt.IS_NOT?r||String(t)!==e:!1}function WD(t,e,n,r){if(t===null||typeof t!="number")return n===nt.NOT_EQUALS;let i=r===void 0?t:Number(t.toFixed(r));return n===nt.EQUALS?i===e:n===nt.NOT_EQUALS?i!==e:n===nt.GREATER_THAN?t>e:n===nt.LESS_THAN?t<e:n===nt.GREATER_OR_EQUAL?t>=e:n===nt.LESS_OR_EQUAL?t<=e:!1}function KD(t,e,n){return typeof t=="number"&&t>=e&&t<=n}function YD(t,e,n){if(!(t instanceof Date))return!1;let r=rn(t),i=rn(e);return n===nt.AFTER?r>i:n===nt.BEFORE?r<i:!1}function GD(t,e,n){if(!(t instanceof Date))return!1;let r=rn(t);return r>=rn(e)&&r<=rn(n)}function qD(t,e,n){let i=(Array.isArray(t)?t:[]).some(a=>e.has(String(a)));return n===nt.SOME_OF?i:n===nt.NOT_SOME_OF?!i:!1}function $D(t,e,n){let r=t!==null&&e.has(String(t));return n===nt.SOME_OF?r:n===nt.NOT_SOME_OF?!r:!1}function Yp(t){let e=Array.isArray(t)?t:[t];return new Set(e.map(n=>String(n)))}function Bo(t){return t.viewAttributeCatalogs??Uo}function Ho(t,e,n,r){if(pr(e))return Kp(t,e,r);let i=_n(e.field);if(i===null)return!1;let a=i.extract(t,n),{operator:o}=e;return o===nt.BETWEEN?i.valueKind===Y.NUMBER?KD(a,Number(e.value),Number(e.valueTo)):i.valueKind===Y.DATE?GD(a,Pc(e.value),Pc(e.valueTo)):!1:i.valueKind===Y.STRING?VD(a,String(e.value),o):i.valueKind===Y.NUMBER?WD(a,Number(e.value),o,i.equalityPrecision):i.valueKind===Y.DATE?YD(a,Pc(e.value),o):i.valueKind===Y.ID_ARRAY?qD(a,Yp(e.value),o):$D(a,Yp(e.value),o)}function Gp(t,e,n,r){return e.criteria.length===0?!0:e.logic===ni.OR?e.criteria.some(i=>Ho(t,i,n,r)):e.criteria.every(i=>Ho(t,i,n,r))}function zD(t,e,n,r){return e.groups&&e.groups.length>0?e.logic===ni.OR?e.groups.some(i=>Gp(t,i,n,r)):e.groups.every(i=>Gp(t,i,n,r)):e.criteria.length===0?!0:e.logic===ni.OR?e.criteria.some(i=>Ho(t,i,n,r)):e.criteria.every(i=>Ho(t,i,n,r))}function JD(t,e){let n=rn(t.startDate),r=rn(t.endDate),i=rn(e.start),a=rn(e.end),o=n>=i&&r<=a,s=n>=i&&n<=a,l=i>=n&&i<=r;return o||s||l}function kc(t,e,n,r){let i=zD(t,e,n,r),a=e.dateRange,o=a===void 0||JD(t,a);return i&&o}function XD(t,e,n){let r=e(t);for(;r!==null&&!n.has(String(r));)n.add(String(r)),r=e(r)}function qp(t){let{activities:e,parentOf:n,filter:r,context:i}=t,a=Bo(t),o=new Set,s=[];for(let l of e)kc(l,r,i,a)&&(o.add(String(l.id)),s.push(l.id));for(let l of s)XD(l,n,o);return o}function ZD(t){let{activities:e,parentOf:n,filter:r,context:i}=t,a=Bo(t),o=new Set,s=new Map,l=new Map,c=new Map;for(let d of e){let u=String(d.id),p=n(u);l.set(u,p),c.set(u,c.get(u)??0),p!==null&&c.set(p,(c.get(p)??0)+1);let y=kc(d,r,i,a);s.set(u,y?1:0),y&&o.add(u)}return{matchedIds:o,visibleReferenceCounts:s,parentIds:l,remainingChildren:c}}function QD(t){let{visibleReferenceCounts:e,parentIds:n,remainingChildren:r}=t,i=[];for(let a of n.keys())r.get(a)===0&&i.push(a);for(;i.length>0;){let a=i.pop();if(a===void 0)break;let o=n.get(a);if(o==null)continue;let s=e.get(a)??0;e.set(o,(e.get(o)??0)+s);let l=(r.get(o)??1)-1;r.set(o,l),l===0&&i.push(o)}}function tT(t){let e=new Set;for(let[n,r]of t)r>0&&e.add(n);return e}function jo(t){let e=ZD(t);QD(e);let n=tT(e.visibleReferenceCounts);return{filter:t.filter,context:t.context,matchedIds:e.matchedIds,visibleIds:n,visibleReferenceCounts:e.visibleReferenceCounts,viewAttributeCatalogs:Bo(t)}}function $p(t,e,n){let r=new Set;for(let i of e){let a=String(i.id);r.add(a);let o=t.matchedIds.has(a),s=kc(i,t.filter,t.context,Bo(t));if(o===s)continue;s?t.matchedIds.add(a):t.matchedIds.delete(a);let l=s?1:-1,c=a;for(;c!==null;){let d=t.visibleReferenceCounts.get(c)??0,u=d+l;t.visibleReferenceCounts.set(c,u);let p=d>0,y=u>0;p!==y&&(r.add(c),y?t.visibleIds.add(c):t.visibleIds.delete(c)),c=n(c)}}return r}function fr(t){return{hoursPerDay:t,locale:"en"}}var Nt={UNKNOWN_FIELD:"unknown_field",UNKNOWN_OPERATOR:"unknown_operator",INVALID_VALUE:"invalid_value"},eT={[Y.STRING]:new Set([nt.INCLUDES,nt.NOT_INCLUDES,nt.IS,nt.IS_NOT]),[Y.NUMBER]:new Set([nt.EQUALS,nt.NOT_EQUALS,nt.GREATER_THAN,nt.LESS_THAN,nt.GREATER_OR_EQUAL,nt.LESS_OR_EQUAL,nt.BETWEEN]),[Y.DATE]:new Set([nt.AFTER,nt.BEFORE,nt.BETWEEN]),[Y.ID_ARRAY]:new Set([nt.SOME_OF,nt.NOT_SOME_OF]),[Y.ENUM]:new Set([nt.SOME_OF,nt.NOT_SOME_OF]),[Y.BOOLEAN]:new Set([nt.SOME_OF,nt.NOT_SOME_OF]),[Y.REFERENCE]:new Set([nt.SOME_OF,nt.NOT_SOME_OF])};function zp(t){if(t===void 0)return{ok:!0,dateRange:void 0};if(typeof t!="object"||t===null)return{ok:!1,reason:Nt.INVALID_VALUE};let{start:e,end:n}=t;if(!(e instanceof Date)||!(n instanceof Date))return{ok:!1,reason:Nt.INVALID_VALUE};let r=e.getTime(),i=n.getTime();return!Number.isFinite(r)||!Number.isFinite(i)||r>i?{ok:!1,reason:Nt.INVALID_VALUE}:{ok:!0,dateRange:{start:new Date(r),end:new Date(i)}}}function Oc(t){if(pr(t))return rT(t);let e=_n(t.field);if(e===null)return{ok:!1,reason:Nt.UNKNOWN_FIELD};if(!eT[e.valueKind].has(t.operator))return{ok:!1,reason:Nt.UNKNOWN_OPERATOR};if(t.operator===nt.BETWEEN)return nT(t,e.valueKind);if(e.valueKind===Y.NUMBER){let r=bc(t.value);return r===null?{ok:!1,reason:Nt.INVALID_VALUE}:{ok:!0,criterion:{...t,value:r}}}if(e.valueKind===Y.DATE){let r=Lc(t.value);return r===null?{ok:!1,reason:Nt.INVALID_VALUE}:{ok:!0,criterion:{...t,value:r}}}let n=iT(t,e.valueKind);return n!==null?{ok:!1,reason:n}:e.valueKind===Y.BOOLEAN?{ok:!0,criterion:{...t,value:[...new Set(t.value)]}}:e.valueKind===Y.ID_ARRAY||e.valueKind===Y.ENUM||e.valueKind===Y.REFERENCE?{ok:!0,criterion:{...t,value:[...new Set(t.value.map(String))]}}:{ok:!0,criterion:t}}function nT(t,e){if(e===Y.NUMBER){let n=bc(t.value),r=bc(t.valueTo);return n===null||r===null||n>r?{ok:!1,reason:Nt.INVALID_VALUE}:{ok:!0,criterion:{...t,value:n,valueTo:r}}}if(e===Y.DATE){let n=Lc(t.value),r=Lc(t.valueTo);return n===null||r===null||n.getTime()>r.getTime()?{ok:!1,reason:Nt.INVALID_VALUE}:{ok:!0,criterion:{...t,value:n,valueTo:r}}}return{ok:!1,reason:Nt.UNKNOWN_OPERATOR}}function rT(t){return pr(t)?typeof t.key!="string"||t.key.length===0?{ok:!1,reason:Nt.UNKNOWN_FIELD}:t.operator!==nt.SOME_OF&&t.operator!==nt.NOT_SOME_OF?{ok:!1,reason:Nt.UNKNOWN_OPERATOR}:!Array.isArray(t.value)||t.value.some(e=>typeof e!="string")?{ok:!1,reason:Nt.INVALID_VALUE}:{ok:!0,criterion:t}:{ok:!1,reason:Nt.UNKNOWN_FIELD}}function iT(t,e){let{value:n}=t;return e===Y.BOOLEAN?Array.isArray(n)&&n.every(r=>typeof r=="boolean")?null:Nt.INVALID_VALUE:e===Y.ID_ARRAY||e===Y.ENUM||e===Y.REFERENCE?Array.isArray(n)&&n.every(r=>typeof r=="string"||typeof r=="number")?null:Nt.INVALID_VALUE:Array.isArray(n)?Nt.INVALID_VALUE:null}function bc(t){if(typeof t=="string"&&t.trim()===""||typeof t!="string"&&typeof t!="number")return null;let e=typeof t=="number"?t:Number(t);return Number.isFinite(e)?e:null}function Lc(t){let e;if(t instanceof Date)e=new Date(t.getTime());else if(typeof t=="string")e=new Date(t);else if(typeof t=="number")e=new Date(t);else return null;return Number.isFinite(e.getTime())?e:null}function C(t){return structuredClone(t)}function Jp(t){return!(t.groups!==void 0&&t.groups.some(n=>n.criteria.length>0))&&t.criteria.length===0&&t.dateRange===void 0}function Xp(t,e,n){let r=t.getAllActivities();if(Jp(e))return{visibleIds:qp({activities:r,parentOf:a=>t.getParentId(a),filter:e,context:fr(n),viewAttributeCatalogs:t.getViewAttributeCatalogMap()}),projection:null};let i=jo({activities:r,parentOf:a=>t.getParentId(a),filter:e,context:fr(n),viewAttributeCatalogs:t.getViewAttributeCatalogMap()});return{visibleIds:i.visibleIds,projection:i}}function aT(t){if(!t||t.length===0)return{ok:!0,groups:[]};let e=[];for(let n of t){let r=[];for(let i of n.criteria){let a=Oc(i);if(!a.ok)return{ok:!1,reason:a.reason};r.push(a.criterion)}e.push({criteria:r,logic:n.logic})}return{ok:!0,groups:e}}function Zp(t,e){let{adapter:n,hoursPerDay:r}=e,i=[];for(let p of t.criteria){let y=Oc(p);if(!y.ok)return{ok:!1,reason:y.reason};i.push(y.criterion)}let a=aT(t.groups);if(!a.ok)return{ok:!1,reason:a.reason};let o=zp(t.dateRange);if(!o.ok)return{ok:!1,reason:o.reason};let s=C({criteria:i,logic:t.logic,...a.groups.length>0?{groups:a.groups}:{},...o.dateRange!==void 0?{dateRange:o.dateRange}:{}});n.setActiveFilter(Jp(s)?null:s);let{visibleIds:l,projection:c}=Xp(n,s,r);n.setFilterProjection(c);let d=dr(n,l);return{ok:!0,changes:{source:t,activities:[],links:[],calendars:[],trackingEvents:[],viewState:d}}}function Qp(t,e){let n=t.getActiveFilter();if(n===null)return[];let{visibleIds:r,projection:i}=Xp(t,n,e);return t.setFilterProjection(i),dr(t,r)}var ce={ASCENDING:"asc",DESCENDING:"desc"};function ai(t){return"kind"in t&&t.kind===ur&&"key"in t&&"direction"in t&&!("operator"in t)}var an={STANDARD:"standard",KEEP_WBS_IN_PLACE:"keepWbsInPlace"};var Z="0";function G(t){return t==null||t===0||t==="0"}function pe(t){return G(t)?"0":String(t)}var Nc=Number.MAX_SAFE_INTEGER;function Ee(t,e){let n=hr(t,e);return Vo(n,e.getOrderComparator?.()??null,e.getOrderMode?.()??an.STANDARD,i=>e.hasChildren(i)).map(i=>String(i.id))}function Vo(t,e,n,r){return e===null?(t.sort(Rn),t):n===an.KEEP_WBS_IN_PLACE?oT(t,e,r):(t.sort((i,a)=>e(i,a)||Rn(i,a)),t)}function oT(t,e,n){let r=[],i=[];for(let a of t)n(a.id)?i.push(a):r.push(a);return r.sort((a,o)=>e(a,o)||Rn(a,o)),i.sort(Rn),t.length=0,t.push(...r,...i),t}function ey(t){let e=[],n=i=>{e.push(i);let a=Ee(String(i.id),t);for(let o of a){let s=t.getActivity(o);s&&n(s)}},r=Ee("0",t);for(let i of r){let a=t.getActivity(i);a&&n(a)}return e}function ny(t,e,n){let r=n.getActivity(t);if(!r)return null;let i=ry(r),a=Ee(i,n),o=a.findIndex(s=>String(s)===String(t));if(o<=0)return null;for(let s=o-1;s>=0;s--){let l=a[s];if(l!==void 0&&!sT(e,l))return l}return null}function Fc(t,e){let n=e.getActivity(t);if(!n)return-1;let r=ry(n);return Ee(r,e).findIndex(a=>String(a)===String(t))}function hr(t,e){let n=String(t)==="0"?e.getRootIds?.()??e.getChildren("0"):e.getChildren(t),r=[];for(let i of n){let a=e.getActivity(i);a&&r.push(a)}return r}function Rn(t,e){let n=ty(t),r=ty(e);return n!==r?n-r:String(t.id).localeCompare(String(e.id))}function ty(t){let e=t.correlativeId,n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?n:Nc}function ry(t){let e=t.parentId;return e===null?"0":e}function sT(t,e){return t.has(e)?!0:t.has(String(e))}function Pn(t){let e=[],n=r=>{let i=Ee(r,t);i.length>1&&e.push({parentId:r,childIds:i});for(let a of i)n(a)};return n("0"),e}function wc(t,e){let n=[];for(let r of e){let i=Ee(r,t);i.length>1&&n.push({parentId:r,childIds:i})}return n}function lT(t){return ai(t)?typeof t.key!="string"||t.key.length===0?Nt.UNKNOWN_FIELD:t.direction!==ce.ASCENDING&&t.direction!==ce.DESCENDING?Nt.UNKNOWN_OPERATOR:null:_n(t.field)===null?Nt.UNKNOWN_FIELD:t.direction!==ce.ASCENDING&&t.direction!==ce.DESCENDING?Nt.UNKNOWN_OPERATOR:null}function iy(t,e){let{adapter:n}=e;for(let o of t.rules){let s=lT(o);if(s!==null)return{ok:!1,reason:s}}let r=t.mode??an.STANDARD,i=t.rules.length===0?null:C({rules:t.rules,mode:r});return n.setActiveOrder(i),{ok:!0,changes:{source:t,activities:[],links:[],calendars:[],trackingEvents:[],order:Pn(n)}}}function xc(t){return Number.isInteger(t)&&Number.isFinite(t)}function ay(t){return t===ce.ASCENDING||t===ce.DESCENDING}function oy(t){let e=t.startLevel??En;return!xc(e)||e<En||!xc(t.depth)||t.depth<Fo||t.depth<e?null:{startLevel:e,depth:t.depth}}var oi=Symbol("invalid-group-criterion");function cT(t){let e=t.secondary;if(e==null)return null;if(typeof e!="object"||typeof e.attributeKey!="string"||e.attributeKey.length===0||e.attributeKey===t.attributeKey)return oi;let n=oy(e);return n===null||!ay(e.direction)?oi:{attributeKey:e.attributeKey,startLevel:n.startLevel,depth:n.depth,direction:e.direction}}function dT(t){if(typeof t.attributeKey!="string"||t.attributeKey.length===0)return null;let e=oy(t);if(e===null||!ay(t.direction)||typeof t.includeWbs!="boolean"||!Array.isArray(t.collapsedIds)||t.collapsedIds.some(r=>typeof r!="string"))return null;let n=cT(t);return n===oi?null:{attributeKey:t.attributeKey,startLevel:e.startLevel,depth:e.depth,direction:t.direction,includeWbs:t.includeWbs,collapsedIds:new Set(t.collapsedIds),secondary:n}}function Wo(t){return{source:t,activities:[],links:[],calendars:[],trackingEvents:[]}}function sy(t,e){let{adapter:n,hoursPerDay:r}=e;if(!Array.isArray(t.catalogs))return{ok:!1,reason:Nt.INVALID_VALUE};n.setViewAttributeCatalogs(t.catalogs);let i=Qp(n,r),a=n.getActiveOrder();return{ok:!0,changes:{...Wo(t),viewState:i,...a===null?{}:{order:Pn(n)}}}}function ly(t,e){let{adapter:n}=e;if(t.group===null)return n.setGroup(null),{ok:!0,changes:Wo(t)};let r=dT(t.group);return r===null?{ok:!1,reason:Nt.INVALID_VALUE}:(n.setGroup(r),{ok:!0,changes:Wo(t)})}function cy(t,e){let{adapter:n}=e,{wbsDepth:r}=t;return r!==null&&(!xc(r)||r<wo)?{ok:!1,reason:Nt.INVALID_VALUE}:(n.setWbsDepth(r),{ok:!0,changes:Wo(t)})}function dy(t,e){throw new Error(e)}var Mc={OWN_BASELINE:"own-baseline",RECURSIVE_LEAF_SUM:"recursive-leaf-sum",ZERO:"zero"},Uc={[H.PROJECT]:{alwaysSummary:!0,holdsConstraint:!1,carriesCustomId:!1,forcedDuration:null,ponderatorWeight:Mc.RECURSIVE_LEAF_SUM,promotesToProjectOnFirstChild:!1},[H.TASK]:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:null,ponderatorWeight:Mc.OWN_BASELINE,promotesToProjectOnFirstChild:!0},[H.MILESTONE]:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:0,ponderatorWeight:Mc.ZERO,promotesToProjectOnFirstChild:!0}};function Me(t,e){return e||ma(t)&&Uc[t].alwaysSummary}function mr(t){return t===H.MILESTONE}function kn(t){return ma(t)&&Uc[t].promotesToProjectOnFirstChild}var Hc=H.PROJECT,si=H.TASK;function ga(t,e){return e===0?H.MILESTONE:t===0&&e>0?H.TASK:null}function uy(t,e){let n=e.getActivity(t);n&&mr(n.type)&&(n.durationHours=0)}var se=0,Ft=100,Bc=100+Number.EPSILON*100*2;function gr(t){return t>=100&&t<=Bc}function ye(t){return t===0}function li(t){let e=0,n=!1;for(let r of t)r.ponderator>0&&(e+=r.ponderator/100*r.progress,n=!0);return n?e:null}function Ko(t){return Number(t.toFixed(2))}function Aa(t,e){let n=new Map;for(let r of uT(t))fy(r,t,e,n)}function yy(t,e,n){let r=new Map;for(let i of t)fy(i,e,n,r)}function uT(t){let e=new Set;t.forEachActivity((r,i)=>{t.getChildren(i).length>0&&e.add(i)});let n=new Map;for(let r of e)n.set(r,pT(r,t));return[...e].sort((r,i)=>(n.get(i)??0)-(n.get(r)??0))}function pT(t,e){let n=0,r=t;for(;r&&r!=="0"&&e.getActivity(r);)n+=1,r=e.getParentId(r);return n}function fy(t,e,n,r){let i=e.getChildren(t);if(i.length===0)return;let a=[];for(let o of i){let s=e.getActivity(o);s&&a.push({progress:Number(s.progress??0),ponderator:Number(s.ponderator??0)})}jc(t,a,e,n,r)}function jc(t,e,n,r,i=new Map){let a=n.getActivity(t);if(!a)return;let o=li(e),l=o===null&&r===Tt.COST&&yT(t,n,i)===!0?0:o;if(l===null){let c=n.getProgressFallback(t);c!==null&&py(t,c,n);return}n.getProgressFallback(t)===null&&n.setProgressFallback(t,Number(a.progress??0)),py(t,Ko(l),n)}function py(t,e,n){n.setActivityField(t,E.PROGRESS,e),n.setActivityField(t,"autoScheduling",ye(e))}function yT(t,e,n){let r=[...e.getChildren(t)],i=!1;for(;r.length>0;){let o=r.pop(),s=n.get(o);if(s===!1)return n.set(t,!1),!1;if(s!==void 0){i||=s===!0;continue}let l=e.getActivity(o);if(!l)continue;let c=e.getChildren(o);if(c.length>0){r.push(...c);continue}let d=fT(l);if(i||=d!==null,d===!1)return n.set(t,!1),!1}let a=i?!0:null;return n.set(t,a),a}function fT(t){let e=Kt(t);return e?t.type===H.MILESTONE||e.cost===0:null}function hy(t,e,n){let r=[t];for(;r.length>0;){let i=r.pop();if(i===void 0)continue;let a=n.getChildren(i);a.length!==0&&(n.setProgressFallback(i,e),r.push(...a))}}var Yo=typeof window>"u",hT=!Yo&&typeof MessageChannel<"u";function wt(){return Yo?new Promise(t=>setImmediate(t)):hT?new Promise(t=>{let e=new MessageChannel;e.port1.onmessage=()=>{e.port1.close(),e.port2.close(),t()},e.port2.postMessage(null)}):Promise.resolve()}function he(t,e){return(Number(t)||0)*(Number(e)||0)/100}var Ia={SKIP:"skip",FREEZE_WITHOUT_CONTRIBUTION:"freeze-when-no-contribution"};async function on(t,e,n=!0,r={}){let i=e?Sa(t,e):vT(t),a=n?r.progressMode??Ia.FREEZE_WITHOUT_CONTRIBUTION:Ia.SKIP;await mT(i,t,a,{recomputeRealWork:r.recomputeRealWork??!1,criterion:r.criterion})}function Go(t,e){my(t,e,Ia.SKIP)}async function mT(t,e,n,r={recomputeRealWork:!1}){let i=new Map,a=200,o=0;for(let s of t)my(s,e,n,r.recomputeRealWork,r.criterion,i),o+=1,o%a===0&&await wt()}function Sa(t,e){let n=new Set,r=new Map;for(let o of e)gT(o,t,n,r);if(n.size===0)return[];let i=Array.from(n),a=AT(i,r);return gy(i,a)}function gT(t,e,n,r){let i=e.getParentId(t);for(;i&&!G(i);){if(n.has(i))return;n.add(i);let a=e.getParentId(i);r.set(i,a),i=a}}function AT(t,e){let n=new Map;for(let r of t){if(n.has(r))continue;let i=[],a=new Set,o=r;for(;o&&!G(o)&&!n.has(o)&&!a.has(o);)i.push(o),a.add(o),o=e.get(o)??null;let s=o?n.get(o)??0:0;for(let l=i.length-1;l>=0;l-=1)s+=1,n.set(i[l],s)}return n}function IT(t,e,n){let r=null,i=null,a=0,o=[];for(let s of t){let l=e.getActivity(s);if(!l)continue;let c=l.startDate.getTime(),d=l.endDate.getTime();(r===null||c<r)&&(r=c),(i===null||d>i)&&(i=d),n&&(a+=ST(l,e.getChildren(s).length>0)),o.push({progress:Number(l.progress??0),ponderator:Number(l.ponderator??0)})}return{minStart:r,maxEnd:i,realWorkSum:a,weightedChildren:o}}function my(t,e,n=Ia.FREEZE_WITHOUT_CONTRIBUTION,r=!1,i,a=new Map){let o=e.getActivity(t);if(!o)return;let s=e.getChildren(t);if(s.length===0)return;let l=IT(s,e,r);if(l.minStart===null||l.maxEnd===null)return;let c=String(o.calendarId??""),d=e.calendarReader.getCalendar(c),u=new Date(l.minStart),p=new Date(l.maxEnd),y=d.calculateDuration(u,p);e.setActivityField(t,"startDate",u),e.setActivityField(t,"endDate",p),e.setActivityField(t,"durationHours",y),n!==Ia.SKIP&&jc(t,l.weightedChildren,e,i,a),r&&e.setActivityField(t,"realWorkHours",l.realWorkSum)}function ST(t,e){return e?Number(t.realWorkHours)||0:he(t.workHours,t.progress)}function vT(t){let e=CT(t),n=DT(e,t);return gy(e,n)}function CT(t){let e=new Set;return t.forEachActivity(n=>{n.parentId!==null&&e.add(n.parentId)}),Array.from(e)}function DT(t,e){let n=new Map;for(let r of t)n.set(r,TT(r,e));return n}function TT(t,e){let n=0,r=t;for(;r&&!G(r)&&e.getActivity(r);)n+=1,r=e.getParentId(r);return n}function gy(t,e){return[...t].sort((n,r)=>(e.get(r)??0)-(e.get(n)??0))}var Ay={updateActivityDuration:uy,updateTaskTiming:ET("updateTaskTiming"),recordLastStartDate:_T};function _T(t,e){let n=e.getActivity(t);n&&e.setLastStartDate(t,n.startDate)}function bn(t,e,n,r){for(let i of e){let a=i in Ay?Ay[i]:void 0;if(!a){console.warn(`[replay post-processors] unknown: ${i} \u2014 skipping. Add an entry in POST_PROCESSORS if a fixture needs it.`);continue}a(t,n,r??null)}}function ET(t){return()=>{console.debug(`[replay post-processors] ${t}: not yet ported to adapter \u2014 no-op.`)}}function rt(t,e){return e!==void 0?{ok:!0,value:t,raw:e}:{ok:!0,value:t}}function ft(t){return{ok:!1,reason:t}}function St(){return{valid:!0}}function jt(t,e){return e!==void 0?{valid:!1,reason:t,notification:e}:{valid:!1,reason:t}}function pt(){return{allowed:!0}}function Dt(t,e){return e!==void 0?{allowed:!1,reason:t,alertKey:e}:{allowed:!1,reason:t}}function vt(t,e={}){return{patch:t,needsAutoSchedule:e.autoSchedule??!1,postProcessors:e.postProcessors??[],...e.cascadeMutations!==void 0?{cascadeMutations:e.cascadeMutations}:{},...e.trackingEvents!==void 0?{trackingEvents:e.trackingEvents}:{}}}var qt={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 Iy={targetField:"name",canEdit(){return pt()},parseInput(t){return typeof t!="string"?ft("not_a_string"):rt(t)},validate(){return St()},transform(t,e){return vt({name:e},{autoSchedule:!1,postProcessors:[]})},trackEvent:qt.NAME_ENTRY};var Sy={targetField:"description",canEdit(){return pt()},parseInput(t){return typeof t!="string"?ft("not_a_string"):rt(t.trim())},validate(){return St()},transform(t,e){return vt({description:e},{autoSchedule:!1,postProcessors:[]})},trackEvent:qt.DESCRIPTION_ENTRY};function Ue(t){return t.constraintType??_.ASAP}var qo=100;function Ln(t){return t.progress>=qo}function Yt(t,e){return Me(t.type,e.hasChildren(t.id))}function vy(t){return t.progress>0}function Cy(t){return t.hasLookaheadTasks}function Ar(t,e){return Math.round(Math.ceil(t*e*60)/60)}var ci=t=>({endDate:t});var va="UTC",RT=1,PT=9999;function kT(t){let e=t.getUTCFullYear();return e>=RT&&e<=PT}function On(t,e){if(e===va&&kT(t))return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()));if(e){let n=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(t),r=i=>Number(n.find(a=>a.type===i)?.value);return new Date(Date.UTC(r("year"),r("month")-1,r("day")))}return new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate()))}function $o(t){return new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds()))}function Da(t,e){if(!e||e===va){let p=new Date(t);return p.setUTCHours(23,59,0,0),p}let n=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(t),r=p=>Number(n.find(y=>y.type===p)?.value),i=r("year"),a=r("month"),o=r("day"),s=Date.UTC(i,a-1,o,23,59,0,0),l=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(new Date(s)),c=p=>Number(l.find(y=>y.type===p)?.value),u=Date.UTC(c("year"),c("month")-1,c("day"),c("hour")===24?0:c("hour"),c("minute"),c("second"))-s;return new Date(s-u)}function bT(t,e){let n=On(e,va);for(;!t.isWorkTime(n,gt.DAY);)n=new Date(n),n.setUTCDate(n.getUTCDate()+1),n=On(n,va);return n}function Ta(t,e){return t.getClosestWorkTime({direction:mt.FUTURE,date:e,unit:gt.HOUR})}function Vc(t,e){let n=bT(t,e),r=new Date(n);return r.setUTCDate(r.getUTCDate()+1),r.setUTCHours(0,0,0,0),t.getClosestWorkTime({direction:mt.PAST,date:r,unit:gt.HOUR})}function Dy(t,e){return e.isWorkTime(t,gt.HOUR)?new Date(t):e.getClosestWorkTime({direction:mt.FUTURE,date:t,unit:gt.HOUR})}function Ty(t,e){if(e.isWorkTime(t,gt.HOUR))return new Date(t);let n=di(t)?LT(t):t;return e.getClosestWorkTime({direction:mt.PAST,date:n,unit:gt.HOUR})}function di(t){return t.getUTCHours()===0&&t.getUTCMinutes()===0&&t.getUTCSeconds()===0&&t.getUTCMilliseconds()===0}function LT(t){let e=new Date(t);return e.setUTCDate(e.getUTCDate()+1),e}var Ca=new Set([_.SNET,_.SNLT,_.MSO]),Wc=new Set([_.FNET,_.FNLT,_.MFO]),Nn=new Set([_.ASAP,_.ALAP]),zo=_.SNET;function $e(t,e,n){let r=On(t,va);return!Ca.has(n)&&!Wc.has(n)?r:Ca.has(n)?_y(r,e):Ey(r,e)}function _y(t,e){return Py(t,Ta(e,t))}function Ey(t,e){return Py(t,Vc(e,t))}function Jo(t,e){return di(t)?_y(t,e):new Date(t)}function Ry(t,e){return di(t)?Ey(t,e):new Date(t)}function Py(t,e){let n=new Date(t);return n.setUTCHours(e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds()),n}var Fn=()=>({constraintType:zo});var Ir=t=>({constraintDate:t}),ky=t=>({constraintDate:t});var by={UPDATE_ACTIVITY_DURATION:"updateActivityDuration",UPDATE_TASK_TIMING:"updateTaskTiming",RECORD_LAST_START_DATE:"recordLastStartDate"};var Ly={NOT_A_NUMBER:"not_a_number",NOT_A_STRING:"not_a_string",NOT_AN_ARRAY:"not_an_array",NOT_AN_INTEGER:"not_an_integer",INVALID_DATE:"invalid_date",INVALID_CONSTRAINT_TYPE:"invalid_constraint_type",EMPTY_CALENDAR:"empty_calendar",EMPTY_CUSTOM_ID:"empty_custom_id",EXCEEDS_MAX_LENGTH:"exceeds_max_length"},Sr={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"},He={COMPLETED:"completed",SUMMARY:"summary",HAS_PROGRESS:"has_progress",HAS_LOOKAHEAD_TASKS:"has_lookahead_tasks",SIR_START_AFTER_PROGRESS:"sir_start_after_progress",DATA_DATE_UNAVAILABLE:"data_date_unavailable",DATA_DATE_ACTUAL_START_LOCKED:"data_date_actual_start_locked",DATA_DATE_ACTIVITY_COMPLETED:"data_date_activity_completed",DATA_DATE_UNITS_PERCENT_READ_ONLY:"data_date_units_percent_read_only",SECONDARY_CONSTRAINT_TYPE_REQUIRED:"secondary_constraint_type_required"},Xo={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",DATA_DATE_EDIT_REJECTED:"data_date_edit_rejected",DATA_DATE_UNITS_PERCENT_READ_ONLY:"data_date_units_percent_read_only"};function ui(t,e,n){return Po(t,e,n)}function pi(t,e,n){return ko(t,e,n)}var Ny={targetField:"durationHours",canEdit(t,e){return Ln(t)?Dt("completed","cant_edit_completed_activity"):Yt(t,e)?Dt("summary","summary_column_value"):pt()},parseInput(t,e,n){let r=parseFloat(String(t));return Number.isFinite(r)?rt(Ar(r,n.hoursPerDay)):ft("not_a_number")},validate(t,e,n){return Oy(n)?jt(Sr.NEGATIVE_DURATION):OT(e,n)?jt("unchanged"):St()},transform(t,e,n){if(Oy(e))return vt({},{autoSchedule:!1,postProcessors:[]});let r=NT(t,e,n),i=FT(t,e,n,r.violated);return{...vt(i,{autoSchedule:!0,postProcessors:[by.RECORD_LAST_START_DATE]}),...r.violated?{constraintWarning:pi(r.constraintType,r.constraintDate,Fy(t,e,n)??void 0)}:{}}},trackEvent:qt.DURATION_ENTRY};function Oy(t){return Math.sign(t)===-1}function OT(t,e){return t===e}function NT(t,e,n){let r=n.calendars.getCalendar(t.calendarId);if(!r)return{violated:!1};let i=t.constraintType;if(i!==_.FNET&&i!==_.FNLT&&i!==_.MFO)return{violated:!1};let a=r.calculateEndDate(t.startDate,e);return ui(i,t.constraintDate,a)}function FT(t,e,n,r=!1){let i={};r&&Object.assign(i,Fn(),Ir(t.startDate));let a=ga(t.durationHours,e);a&&(i.type=a),i.durationHours=e;let o=Fy(t,e,n);return o&&Object.assign(i,ci(o)),i}function Fy(t,e,n){let r=n.calendars.getCalendar(t.calendarId);return r?r.calculateEndDate(t.startDate,e):null}var yi=t=>({realWorkHours:t});var wT=0,xT=qo,fi={targetField:"progress",canEdit(t,e){return Yt(t,e)?Dt("summary","summary_column_value"):Cy(t)?Dt("has_lookahead_tasks","cant_edit_actvity_with_task"):pt()},parseInput(t){let e=parseFloat(String(t));return Number.isNaN(e)?ft("not_a_number"):rt(e)},validate(t,e,n){return MT(n)?jt("out_of_range"):St()},transform(t,e,n){let r=ye(e),i=t.progress!==e&&r,a=UT(e),o=jT(t,e,n.hierarchy),s={progress:e,autoScheduling:r,...yi(o.get(t.id)??0)},l=a?HT(t,e,r,n.hierarchy,o):[],c=a?WT(t,e,n.hierarchy):[],d=l.length+c.length>0?[...l,...c]:void 0,u=[],p=a?YT(t,e):void 0;return vt(s,{autoSchedule:i,postProcessors:u,cascadeMutations:d,trackingEvents:p})},trackEvent:qt.PROGRESS_ENTRY};function MT(t){return t<wT||t>xT}function UT(t){return t===qo||ye(t)}function HT(t,e,n,r,i){return r.getDescendantIds(t.id).map(o=>({activityId:o,fields:BT(e,n,i.get(o)??0)}))}function BT(t,e,n){return{progress:t,autoScheduling:e,...yi(n)}}function jT(t,e,n){let r=new Map,i=o=>{let s=0;for(let l of n.getChildHhInfo(o)){let c=n.hasChildren(l.id)?i(l.id):he(l.workHours,e);r.set(l.id,c),s+=c}return s},a=n.hasChildren(t.id)?i(t.id):he(t.workHours,e);return r.set(t.id,a),r}function VT(t,e){let n=[t.id,...e.getDescendantIds(t.id)],r=a=>e.getChildProgressInfo(a).some(o=>e.hasChildren(o.id)),i=a=>e.getAncestorIds(a).length;return n.filter(a=>r(String(a))).map(String).sort((a,o)=>i(o)-i(a))}function WT(t,e,n){let r=new Map;r.set(t.id,e);for(let o of n.getDescendantIds(t.id))r.set(o,e);let i=[...VT(t,n),...n.getAncestorIds(t.id)],a=[];for(let o of i){let s=KT(o,r,n);s!==null&&(r.set(o,s),a.push({activityId:o,fields:{progress:s}}))}return a}function KT(t,e,n){let r=n.getChildProgressInfo(t).map(a=>({progress:e.has(a.id)?e.get(a.id):a.progress,ponderator:a.ponderator??0})),i=li(r);return i===null?null:Number(i.toFixed(2))}function YT(t,e){return[{name:qt.PROGRESS_UPDATE_RADIO_BUTTON,properties:{activity_id:t.id,activity_name:t.name,progress_updated:e}}]}var wy={targetField:"cost",canEdit(t,e){return Yt(t,e)?Dt("summary","summary_column_value"):pt()},parseInput(t){if(String(t).trim()==="")return rt(0);let e=parseFloat(String(t));return Number.isFinite(e)?rt(e):ft("not_a_number")},validate(){return St()},transform(t,e,n){let r=GT(t,e,n.hierarchy);return vt({cost:e},{autoSchedule:!1,postProcessors:[],cascadeMutations:r})},trackEvent:qt.COST_BUDGETED_ENTRY};function GT(t,e,n){let r=new Map;r.set(t.id,e);let i=[];for(let a of n.getAncestorIds(t.id)){let o=0;for(let s of n.getChildCostInfo(a))o+=r.has(s.id)?r.get(s.id):s.cost;r.set(a,o),i.push({activityId:a,fields:{cost:o}})}return i}var xy={targetField:"usedCost",canEdit(t,e){return Yt(t,e)?Dt("summary","summary_column_value"):pt()},parseInput(t){if(String(t).trim()==="")return rt(0);let e=parseFloat(String(t));return Number.isFinite(e)?rt(e):ft("not_a_number")},validate(){return St()},transform(t,e,n){let r=qT(t,e,n.hierarchy);return vt({usedCost:e},{autoSchedule:!1,postProcessors:[],cascadeMutations:r})},trackEvent:qt.COST_SPENT_ENTRY};function qT(t,e,n){let r=new Map;r.set(t.id,e);let i=[];for(let a of n.getAncestorIds(t.id)){let o=0;for(let s of n.getChildUsedCostInfo(a))o+=r.has(s.id)?r.get(s.id):s.usedCost;r.set(a,o),i.push({activityId:a,fields:{usedCost:o}})}return i}var My={targetField:"workHours",canEdit(t,e){return Yt(t,e)?Dt("summary","summary_column_value"):pt()},parseInput(t){if(String(t).trim()==="")return rt(0,t);let e=parseFloat(String(t));return Number.isFinite(e)?rt(e):ft("not_a_number")},validate(){return St()},transform(t,e,n,r){let i=Uy(e,t.progress),a=String(r).trim()===""?[]:$T(t,e,i,n.hierarchy);return vt({workHours:e,...yi(i)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:qt.LABOR_HOURS_BUDGETED_ENTRY};function Uy(t,e){return he(t,e)}function $T(t,e,n,r){let i=new Map,a=new Map;i.set(t.id,e),a.set(t.id,n);let o=[];for(let s of r.getAncestorIds(t.id)){let l=0,c=0;for(let d of r.getChildHhInfo(s)){let u=i.has(d.id)?i.get(d.id):d.workHours,p=a.has(d.id)?a.get(d.id):d.realWorkHours??Uy(d.workHours,d.progress);l+=u,c+=p}i.set(s,l),a.set(s,c),o.push({activityId:s,fields:{workHours:l,...yi(c)}})}return o}function wn(t,e){return t.getUTCFullYear()===e.getUTCFullYear()&&t.getUTCMonth()===e.getUTCMonth()&&t.getUTCDate()===e.getUTCDate()}function Kc(t,e){return t.getTime()<e.getTime()}function xn(t){return t instanceof Date&&!Number.isNaN(t.getTime())}var Zo=t=>({durationHours:t});var zT="sir-apply",Hy={targetField:"startDate",canEdit(t,e,n){return Yt(t,e)?Dt("summary","summary_column_value"):vy(t)?n?.eventSource!==zT?Dt("has_progress","cant_edit_activity_with_progress"):xn(n.newValue)?wn(t.startDate,n.newValue)?pt():Ln(t)?Dt("completed","cant_edit_completed_activity"):pt():pt():pt()},parseInput(t,e,n){return xn(t)?rt(On(t,"UTC")):ft("invalid_date")},validate(t,e,n,r){if(wn(e,n))return jt("unchanged");let i=JT(t,n,r);return i||St()},transform(t,e,n){let r=n.calendars.getCalendar(t.calendarId);if(!r)throw new Error("startDatePipeline: no calendar resolved (integrity)");let i=Ta(r,e),a=t.type===H.MILESTONE,o=a?i:r.calculateEndDate(i,t.durationHours),s=i;return{...vt({startDate:i,...ci(o),...a?Zo(0):{},...Fn(),...Ir(s)},{autoSchedule:!0}),constraintWarning:XT(t,i,r)}},trackEvent:qt.START_DATE_ENTRY};function JT(t,e,n){let r=n.hierarchy.getParentStartDateIfHasPredecessors(t.id);if(!r)return null;let i=On(r,"UTC");return e.getTime()<i.getTime()?jt("before_parent_start"):null}function XT(t,e,n){let r=n.calculateEndDate(e,t.durationHours),i=lr(Ue(t),e,r),a=ui(Ue(t),t.constraintDate,i);if(a.violated)return pi(a.constraintType,a.constraintDate,i)}var ZT=99.999,QT="sir-apply",jy={targetField:"endDate",canEdit(t,e,n){return Yt(t,e)?Dt("summary","summary_column_value"):e_(t)&&!t_(t.endDate,n)?Dt("completed","cant_edit_completed_activity"):pt()},parseInput(t,e,n){if(!xn(t))return ft("invalid_date");let r=On(t,"UTC"),i=n.calendars.getCalendar(e.calendarId);return i?i.isWorkTime(r,gt.DAY)?rt(Vc(i,r)):rt(i.getClosestWorkTime({direction:"past",date:r,unit:gt.HOUR})):rt(r)},validate(t,e,n,r){if(wn(t.endDate,n))return jt("unchanged");if(n_(n,t))return jt("before_date_origin");if(r_(n,t))return jt("before_start_date");let i=i_(n,t,r);return i||St()},transform(t,e,n){let r=a_(t,e),i=o_(t,e,n,!!r);return{...vt(i,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...r?{constraintWarning:r}:{}}},trackEvent:qt.END_DATE_ENTRY};function t_(t,e){return e?.eventSource===QT&&xn(e.newValue)&&wn(t,e.newValue)}function e_(t){return t.progress>=ZT}function n_(t,e){return e.dateOrigin?Kc(t,e.dateOrigin):!1}function r_(t,e){return Kc(t,e.startDate)}function i_(t,e,n){let r=n.calendars.getCalendar(e.calendarId);return r?r.isWorkTime(t,gt.DAY)?null:jt("not_working_day"):null}function a_(t,e){if(Ue(t)===_.MSO)return;let r=lr(Ue(t),t.startDate,e),i=ui(Ue(t),t.constraintDate,r);if(i.violated)return pi(i.constraintType,i.constraintDate,r)}function o_(t,e,n,r=!1){let i={};mr(t.type)&&!r&&By(t)?Object.assign(i,Ir(t.startDate)):(r||By(t))&&Object.assign(i,Fn(),Ir(t.startDate));let s=s_(t,e,n),l=ga(t.durationHours,s);return l&&(i.type=l),Object.assign(i,Zo(s)),i.endDate=e,i}function By(t){return Nn.has(Ue(t))}function s_(t,e,n){let r=n.calendars.getCalendar(t.calendarId);return r?r.calculateDuration(t.startDate,e):t.durationHours}var l_=new Set(Object.values(_)),Vy={targetField:"constraintType",canEdit(t,e){return Ln(t)?Dt("completed","cant_edit_completed_activity"):Yt(t,e)?Dt("summary","summary_column_value"):pt()},parseInput(t){let e=String(t).toLowerCase();return c_(e)?rt(e):ft("invalid_constraint_type")},validate(){return St()},transform(t,e,n){let r=d_(t,e,n);return vt(r,{autoSchedule:!0})}};function c_(t){return l_.has(t)}function d_(t,e,n){let r=p_(t,e);return{constraintType:e,...ky(u_(t,e,r,n))}}function u_(t,e,n,r){if(t.type!==H.MILESTONE||!n||Ca.has(e))return n;let i=r.calendars.getCalendar(String(t.calendarId));return i?$e(n,i,e):n}function p_(t,e){return Nn.has(e)?null:Ca.has(e)?t.startDate:Wc.has(e)?t.endDate:t.constraintDate}var Wy={targetField:"constraintDate",canEdit(t,e){return Ln(t)?Dt("completed","cant_edit_completed_activity"):Yt(t,e)?Dt("summary","summary_column_value"):pt()},parseInput(t){return xn(t)?rt(t):ft("invalid_date")},validate(){return St()},transform(t,e,n){let r=Ky(t)?zo:Ue(t),i=n.calendars.getCalendar(t.calendarId);if(!i)throw new Error("constraintDatePipeline: no calendar resolved (integrity)");let a=$e(e,i,r),o=y_(t,a);return vt(o,{autoSchedule:!0})}};function y_(t,e){return{constraintDate:e,...Ky(t)?Fn():{}}}function Ky(t){return Nn.has(Ue(t))||!t.constraintType}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",BASELINE_VARIANCE_DAYS:"baselineVarianceDays",PROJECT_BASELINE_VARIANCE_DAYS:"projectBaselineVarianceDays",PRIMARY_BASELINE_VARIANCE_DAYS:"primaryBaselineVarianceDays",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath",P6:"p6"},Xt={ID:"id",SOURCE:"source",TARGET:"target",TYPE:"type",LAG:"lag",FREE_SLACK_HOURS:"freeSlackHours",IS_CRITICAL:"isCritical",SOURCE_LAG:"_sourceLag",TARGET_LAG:"_targetLag",TRUE_LAG:"_trueLag",SUMMARY_SOURCE_ID:"_summarySourceId",SUMMARY_TARGET_ID:"_summaryTargetId",LAG_ACTIVITY_ID:"_lagActivityId",GANTT_ID:"ganttId",SECTOR_ID:"sectorId",PROPLANNER_ID:"proplannerId"};var Yy={targetField:b.CALENDAR_ID,canEdit(){return pt()},parseInput(t){if(t===null)return rt(null);let e=String(t).trim();return f_(e)?ft(Ly.EMPTY_CALENDAR):rt(e)},validate(t,e,n,r){let i=n===null?r.getDefaultCalendarId():n;return h_(t.calendarId,i)&&(n!==null||t.assignedDefaultCalendar)?jt(Sr.UNCHANGED):i===null||!r.hasCalendar(i)?jt(Sr.UNKNOWN_CALENDAR):St()},transform(t,e,n){let r=e===null?n.getDefaultCalendarId():e;return vt(m_(t,r,e===null,n),{autoSchedule:!0,postProcessors:[]})},trackEvent:qt.CALENDAR_ASSIGNMENT};function f_(t){return t===""}function h_(t,e){return t===e}function m_(t,e,n,r){let i={calendarId:e,assignedDefaultCalendar:n},a=e===null?null:r.calendars.getCalendar(e);if(a){let o=a.isWorkTime(t.startDate,"hour"),s=a.getClosestWorkTime({date:o?Gy(t.startDate):t.startDate,direction:"future",unit:"hour"});i.startDate=s;let l=g_(t,a);if(l&&(i.constraintDate=l),!t.autoScheduling)return i;Object.assign(i,ci(a.calculateEndDate(s,t.durationHours)))}return i}function g_(t,e){return!t.constraintDate||!t.constraintType?null:ya({...t,constraintDate:Gy(t.constraintDate)},{getClosestWorkTime:({date:n,dir:r})=>e.getClosestWorkTime({date:n,direction:r,unit:gt.HOUR})})}function Gy(t){return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()))}var qy={targetField:"customId",canEdit(t,e){return Yt(t,e)?Dt("summary","summary_column_value"):pt()},parseInput(t){if(t==null)return ft("empty_custom_id");if(typeof t!="string")return ft("not_a_string");let e=t.trim();return e.length===0?ft("empty_custom_id"):e.length>20?ft("exceeds_max_length"):rt(e)},validate(){return St()},transform(t,e){return vt({customId:e},{autoSchedule:!1,postProcessors:[]})}};var $y={targetField:"subcontractId",canEdit(){return pt()},parseInput(t){if(t==null)return rt(null);if(typeof t=="string"){let e=t.trim();if(e.length===0)return rt(null);let n=Number(e);return!Number.isFinite(n)||!Number.isInteger(n)?ft("not_an_integer"):rt(n)}return typeof t=="number"?!Number.isFinite(t)||!Number.isInteger(t)?ft("not_an_integer"):rt(t):ft("not_an_integer")},validate(){return St()},transform(t,e){return vt({subcontractId:e},{autoSchedule:!1,postProcessors:[]})}};function _a(t){if(t==null)return null;if(typeof t=="object"){if(!("id"in t))return null;let e=t.id;return e==null?null:String(e)}return String(t)}function Qo(t){return t.some(e=>_a(e)===null)}var zy={targetField:"responsableIds",canEdit(){return pt()},parseInput(t){return t==null?rt([]):Array.isArray(t)?rt(t):ft("not_an_array")},validate(t,e,n){return Qo(n)?jt("missing_id"):St()},transform(t,e){let n=e.map(_a).filter(r=>r!==null);return vt({responsableIds:n},{autoSchedule:!1,postProcessors:[]})}};var Jy={targetField:"tagIds",canEdit(){return pt()},parseInput(t){return t==null?rt([]):Array.isArray(t)?rt(t):ft("not_an_array")},validate(t,e,n){return Qo(n)?jt("missing_id"):St()},transform(t,e){let n=e.map(_a).filter(r=>r!==null);return vt({tagIds:n},{autoSchedule:!1,postProcessors:[]})}};var Cr={TOTAL_FLOAT:"total_float",LONGEST_PATH:"longest_path"},xt={DURATION:"duration",UNITS:"units",PHYSICAL:"physical"},re={TASK:"task",LEVEL_OF_EFFORT:"level_of_effort",START_MILESTONE:"start_milestone",FINISH_MILESTONE:"finish_milestone",WBS_SUMMARY:"wbs_summary",RESOURCE_DEPENDENT:"resource_dependent"},tt={NOT_STARTED:"not_started",IN_PROGRESS:"in_progress",COMPLETED:"completed"},Re={FIXED_DURATION_AND_UNITS:"fixed_duration_and_units",FIXED_DURATION_AND_UNITS_PER_TIME:"fixed_duration_and_units_per_time"};function ts(t){return t==="start_on"||t==="mandatory_start"?"mso":t==="finish_on"||t==="mandatory_finish"?"mfo":t}function sn(t){return t.remainingDurationHours!==null}var ie={UNSTART:"unstart",UNCOMPLETE:"uncomplete",START_ON_PROGRESS:"start_on_progress",COMPLETE_ON_PROGRESS:"complete_on_progress",KEEP_IN_PROGRESS:"keep_in_progress",CLEAR_SECONDARY_CONSTRAINT:"clear_secondary_constraint"};function Ea(t,e){return e?.includes(t)??!1}var A_={asap:[],alap:["fnlt","snlt"],snet:["fnlt","snlt"],fnet:["fnlt","snlt"],snlt:["fnet","snet"],fnlt:["fnet","snet"],mso:[],mfo:[]};function Yc(t){return t===null?[]:A_[t]}function hi(t,e){return e===null||Yc(t).includes(e)}var me=(t,e)=>({...vt({}),dataDatePatch:{[t]:e}}),es=t=>({...vt({}),dataDatePatch:t}),Ra=(t,e)=>({...es(t),confirmation:e}),Pa=t=>t.p6===void 0?Dt("data_date_unavailable"):pt(),Mn=t=>({targetField:t,canEdit:Pa,parseInput(e){return e===null?rt(null):!(e instanceof Date)||!Number.isFinite(e.getTime())?ft("invalid_date"):rt(e)},validate(){return St()},transform(e,n){return me(t,n)}}),Qy=(t,e=Number.POSITIVE_INFINITY)=>({targetField:t,canEdit:Pa,parseInput(n){let r=typeof n=="number"||typeof n=="string"&&n.trim()!==""?Number(n):Number.NaN;return Number.isFinite(r)?rt(r):ft("not_a_number")},validate(n,r,i){return i<0||i>e?jt("out_of_range"):St()},transform(n,r){return me(t,r)}}),tf=(t,e)=>({targetField:t,canEdit:Pa,parseInput(n){return typeof n=="string"&&e.has(n)?rt(n):ft("not_a_string")},validate(){return St()},transform(n,r){return me(t,r)}}),I_=new Set(["not_started","in_progress","completed"]),S_=new Set(["duration","units","physical"]),v_=new Set(["snet","snlt","fnet","fnlt"]),C_=(t,e)=>{let n=t.p6?.executionStatus;return n===e||n===void 0?me("executionStatus",e):n===tt.NOT_STARTED?es(e===tt.IN_PROGRESS?{actualStart:t.startDate}:{actualStart:t.startDate,actualFinish:t.endDate}):n===tt.IN_PROGRESS?e===tt.COMPLETED?me("actualFinish",t.endDate):Ra({actualStart:null},ie.UNSTART):e===tt.IN_PROGRESS?Ra({actualFinish:null},ie.UNCOMPLETE):Ra({actualStart:null,actualFinish:null},ie.UNSTART)},Xy=(t,e)=>{if(e!==null||t.p6?.actualStart==null)return me("actualStart",e);let r=t.p6?.actualFinish!=null;return Ra(r?{actualStart:null,actualFinish:null}:{actualStart:null},ie.UNSTART)},Zy=(t,e)=>e!==null||t.p6?.actualFinish==null?me("actualFinish",e):Ra({actualFinish:null},ie.UNCOMPLETE),ka=(t,e)=>{let n=e.calendars.getCalendar(t.calendarId);if(!n)throw new Error("dataDatePipelines: no calendar resolved (integrity)");return n},ef={...Mn("actualStart"),transform(t,e,n){if(e===null)return Xy(t,null);let r=ka(t,n),i=t.p6?.actualStart==null;return Xy(t,i?Jo(e,r):new Date(e))}},nf={...Mn("actualFinish"),transform(t,e,n){if(e===null)return Zy(t,null);let r=ka(t,n),i=t.p6?.actualFinish==null;return Zy(t,i?Ry(e,r):new Date(e))}},rf={...Mn("plannedStart"),transform(t,e,n){if(e===null)return me("plannedStart",null);let r=ka(t,n);return me("plannedStart",Dy(e,r))}},af={...Mn("plannedFinish"),transform(t,e,n){if(e===null)return me("plannedFinish",null);let r=ka(t,n);return me("plannedFinish",Ty(e,r))}},of=Qy("remainingDurationHours"),sf={...tf("executionStatus",I_),transform(t,e){return C_(t,e)}},lf=Mn("expectedFinish"),cf=Mn("suspendDate"),df=Mn("resumeDate"),uf={targetField:"secondaryConstraintType",canEdit:Pa,parseInput(t){return t===null||t===""?rt(null):typeof t=="string"&&v_.has(t)?rt(t):ft("not_a_string")},validate(t,e,n){return hi(t.constraintType,n)?St():jt("constraint_violation")},transform(t,e){return e===null?es({secondaryConstraintType:null,secondaryConstraintDate:null}):t.p6?.secondaryConstraintType!=null?me("secondaryConstraintType",e):es({secondaryConstraintType:e,secondaryConstraintDate:e.startsWith("s")?t.startDate:t.endDate})}},pf={...Mn("secondaryConstraintDate"),canEdit(t,e){let n=Pa(t,e);return n.allowed?t.p6?.secondaryConstraintType==null?Dt("secondary_constraint_type_required"):pt():n},transform(t,e,n){let r=t.p6?.secondaryConstraintType??null;if(e===null||r===null)return me("secondaryConstraintDate",e);let i=ka(t,n);return me("secondaryConstraintDate",$e(e,i,r))}},yf=tf("percentCompleteType",S_),ff=Qy("physicalPercentComplete",100);var D_=new Map([[E.TEXT,Iy],[E.DESCRIPTION,Sy],[E.DURATION,Ny],[E.PROGRESS,fi],[E.COST,wy],[E.USED_COST,xy],[E.HH_WORK_TIME,My],[E.START_DATE,Hy],[E.END_DATE,jy],[E.CONSTRAINT_TYPE,Vy],[E.CONSTRAINT_DATE,Wy],[E.CALENDAR_ID,Yy],[E.CUSTOM_ID,qy],[E.SUBCONTRACT_ID,$y],[E.RESPONSABLES,zy],[E.TAGS,Jy],[E.ACTUAL_START,ef],[E.ACTUAL_FINISH,nf],[E.PLANNED_START,rf],[E.PLANNED_FINISH,af],[E.REMAINING_DURATION_HOURS,of],[E.EXECUTION_STATUS,sf],[E.EXPECTED_FINISH,lf],[E.SUSPEND_DATE,cf],[E.RESUME_DATE,df],[E.SECONDARY_CONSTRAINT_TYPE,uf],[E.SECONDARY_CONSTRAINT_DATE,pf],[E.PERCENT_COMPLETE_TYPE,yf],[E.PHYSICAL_PERCENT_COMPLETE,ff]]);function ge(t){return D_.get(t)}var $t={FIELD:"field",DELETED_REMOTELY:"deleted-remotely",DELETED_LOCALLY:"deleted-locally",PARENT_REMOVED:"parent-removed",BECAME_PARENT_REMOTELY:"became-parent-remotely",BECAME_PARENT_LOCALLY:"became-parent-locally",DUPLICATE_LINK:"duplicate-link",ORDER:"order",LINK_CYCLE:"link-cycle"},Gt={ACTIVITY:"activity",LINK:"link"},Ht={APPEND:"append",REPLACE:"replace"},ns={ACTION_BUTTON:"action-button"},ba={SIR_AUTO_REJECT:"sir-auto-reject"},La={DATE_CHANGED:"date_changed",ACTIVITY_DELETED:"activity_deleted",ACTIVITY_COMPLETED:"activity_completed"},Dr={VIOLATION:"constraint_violation"},de={DISPATCH_MANY:"dispatch-many",INIT:"init",UNDO:"undo",REDO:"redo",P6_SETTINGS_UPDATE:"p6-settings-update",P6_ACTIVITY_UPDATE:"p6-activity-update",P6_SCHEDULE:"p6-schedule"};function Tr(t,e){if(!e||e.type!==Eo.CONSTRAINT)return null;let n=e.data;return!n?.constraintType||!n.constraintDate?null:{kind:Dr.VIOLATION,activityId:t,constraintType:n.constraintType,constraintDate:n.constraintDate,projectedDate:n.projectedDate??n.constraintDate,messageKey:e.messageKey}}var hf=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],mf=new Set(hf),JK=new Set([...hf,...Object.values(ti)]),gf=new Set(Object.values(ti));function ve(t,e,n,r){t.setActivityFieldDynamic(e,n,r)}function Af(t,e,n,r){t.setLinkFieldDynamic(e,n,r)}var T_=Object.freeze([]);function Ae(t){return t.length===0?T_:t}function ln(t){return If(t,Ae)}function Oa(t){return If(t,__)}function If(t,e){return{...t,startDate:new Date(t.startDate),endDate:new Date(t.endDate),constraintDate:ze(t.constraintDate),dateOrigin:ze(t.dateOrigin),newActivityIds:e([...t.newActivityIds]),pendingRequestIds:e([...t.pendingRequestIds]),responsableIds:e([...t.responsableIds]),tagIds:e([...t.tagIds]),baselinePoints:e(t.baselinePoints.map(n=>({...n,startDate:ze(n.startDate),endDate:ze(n.endDate)}))),baselineSnapshot:E_(t.baselineSnapshot),criticalPath:rs(t.criticalPath),...t.p6===void 0?{}:{p6:C(t.p6)}}}function __(t){return t}function ze(t){return t===null?null:new Date(t)}function E_(t){return t===null?null:{...t,startDate:ze(t.startDate),endDate:ze(t.endDate)}}function rs(t){return t===null?null:{...t,earlyStart:ze(t.earlyStart),earlyFinish:ze(t.earlyFinish),lateStart:ze(t.lateStart),lateFinish:ze(t.lateFinish)}}var Cf=200;function Un(t,e){let n=new Set([String(t)]);for(let r of e.cascadeMutations??[])n.add(String(r.activityId));return n}async function yt(t,e){let n=new Map,r=0;for(let i of e){r+=1,r%Cf===0&&await wt();let a=t.getActivity(i);a&&n.set(i,ct(a))}return n}function ct(t){return ln(t)}function as(t,e){let n=t.getActivity(e);return n?ln(n):null}function Hn(t,e,n){Sf(t,e,n.patch),n.dataDateState!==void 0&&t.setActivityField(e,"p6",n.dataDateState);for(let r of n.cascadeMutations??[])Sf(t,r.activityId,r.fields)}function Sf(t,e,n){for(let[r,i]of Object.entries(n)){if(!mf.has(r))throw new Error(`applyFieldChanges: column write to non-writable field "${r}"`);ve(t,e,r,i)}}async function os(t,e,n,r){let i=[],a=0;for(let o of n){a+=1,a%Cf===0&&await wt();let s=R_(t,e,o,r);s&&i.push(s)}return i}function R_(t,e,n,r){let i=t.getActivity(n),a=e.get(n);if(!i)return{id:n,kind:W.DELETED,after:null,...a?{before:ct(a)}:{}};if(!a&&r?.has(n))return P_(n,r.get(n),i);let o=O_(a,i);return k_(o,r,n,i),a&&Object.keys(o).length===0?null:{id:n,kind:a?W.UPDATED:W.CREATED,fields:o,after:ct(i)}}function P_(t,e,n){return e===n.correlativeId?null:{id:t,kind:W.UPDATED,fields:{correlativeId:{before:e,after:n.correlativeId}},after:ct(n)}}function k_(t,e,n,r){if(!e?.has(n)||Object.hasOwn(t,"correlativeId"))return;let i=e.get(n);i!==r.correlativeId&&(t.correlativeId={before:i,after:r.correlativeId})}var b_=new Set([b.CALENDAR_DURATION,b.BASELINE_VARIANCE_DAYS,b.PROJECT_BASELINE_VARIANCE_DAYS,b.PRIMARY_BASELINE_VARIANCE_DAYS]),L_={},is=t=>t===void 0?L_:t;function vf(t,e,n){return!b_.has(n)&&(Object.hasOwn(t,n)!==Object.hasOwn(e,n)||!Fa(t[n],e[n]))}function Df(t,e,n){let r=is(t),i=is(e);for(let a in r)if(vf(r,i,a)&&n(a))return;for(let a in i)if(!Object.hasOwn(r,a)&&vf(r,i,a)&&n(a))return}function Tf(t,e){let n=!1;return Df(t,e,()=>(n=!0,!0)),n}function O_(t,e){let n={},r=is(t),i=is(e);return Df(t,e,a=>(n[a]={before:Na(r[a]),after:Na(i[a])},!1)),n}function Na(t){return t===null||typeof t!="object"?t:t instanceof Date?new Date(t.getTime()):C(t)}function Fa(t,e){if(Object.is(t,e))return!0;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(t==null||e==null)return!1;if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((o,s)=>Fa(o,e[s]));if(typeof t!="object"||typeof e!="object")return!1;let n=t,r=e,i=Object.keys(n),a=Object.keys(r);return i.length!==a.length?!1:i.every(o=>Object.hasOwn(r,o)&&Fa(n[o],r[o]))}function ss(t,e,n){let r=new Set;r.add(t);for(let i of e)r.add(i);for(let i of n)r.add(i);return r}function Gc(t,e){let n=new Set;for(let r of t)n.add(String(r));for(let r of e)n.add(r);return n}var mi=new Set;function Ie(t,e,n,r,i){let a=new Map,o=t.peekWriteCapture()?.dirty;for(let s of e){if(n.has(s.activityId)||(i.add(s.activityId),r.has(s.activityId)))continue;let l=t.getActivity(s.activityId);if(!l)continue;if(s.before!==void 0&&!o?.has(s.activityId)){a.set(s.activityId,s.before);continue}let d=ct(l);s.before!==void 0&&(d.correlativeId=s.before),r.set(s.activityId,d)}return a}function _f(t,e){return()=>e()===t}function wa(t){return performance.now()-t>=Up.YIELD_SLICE_MS}async function ls(t,e){return wa(t)?(await wt(),e()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()}):{aborted:!1,newSliceStart:t}}async function gi(t){return Yo||await wt(),t()?{aborted:!1}:{aborted:!0}}function h(t,e){let n=t[e];if(n===void 0)throw new RangeError(`Index ${e} is out of range`);return n}function Bn(t,e){return qc(t,e).result}function qc(t,e){let n=N_(t,e),{ordered:r,sourceCount:i}=F_(n),a=r.length<t.length,o=a?x_(t,r):[],s=[...r].reverse();return{result:{ordered:r,reversed:s,hasCycles:a,cycleNodes:o},sourceCount:i,unknownEndpointIds:n.unknownEndpointIds}}function N_(t,e){let n=new Map,r=[];for(let y of t)n.has(y)||(n.set(y,r.length),r.push(y));let i=r.length,a=new Int32Array(e.length),o=new Int32Array(e.length),s=new Int32Array(i+1),l=new Int32Array(i),c=0,d=new Set;for(let y of e){let f=n.get(y.source),m=n.get(y.target);f===void 0&&d.add(String(y.source)),m===void 0&&d.add(String(y.target)),!(f===void 0||m===void 0)&&(a[c]=f,o[c]=m,c+=1,s[f+1]=h(s,f+1)+1,l[m]=h(l,m)+1)}for(let y=0;y<i;y+=1)s[y+1]=h(s,y+1)+h(s,y);let u=s.slice(0,i),p=new Int32Array(c);for(let y=0;y<c;y+=1){let f=h(a,y),m=h(u,f);p[m]=h(o,y),u[f]=m+1}return{unknownEndpointIds:d,nodeIds:r,inDegree:l,successorStart:s,successorList:p}}function F_(t){let{nodeIds:e,inDegree:n,successorStart:r,successorList:i}=t,a=new Int32Array(e.length),o=0;for(let c=0;c<e.length;c+=1)n[c]===0&&(a[o]=c,o+=1);let s=o,l=[];for(let c=0;c<o;c+=1){let d=h(a,c);l.push(w_(e,d));let u=h(r,d+1);for(let p=h(r,d);p<u;p+=1){let y=h(i,p),f=h(n,y)-1;n[y]=f,f===0&&(a[o]=y,o+=1)}}return{ordered:l,sourceCount:s}}function w_(t,e){let n=t[e];if(n===void 0)throw new RangeError(`Node ${e} is out of range`);return n}function x_(t,e){let n=new Set(e);return t.filter(r=>!n.has(r))}function M_(t,e,n){if(!(n===t.links&&e.length>=t.activityIds.length))return null;for(let o=0;o<t.activityIds.length;o+=1)if(e[o]!==t.activityIds[o])return null;let i=e.slice(t.activityIds.length);return i.every(o=>!t.sorted.unknownEndpointIds.has(String(o)))?i:null}function U_(t,e){let{ordered:n}=t.result,r=[...n.slice(0,t.sourceCount),...e,...n.slice(t.sourceCount)];return{...t,result:{...t.result,ordered:r,reversed:[...r].reverse()},sourceCount:t.sourceCount+e.length}}var cs=class{cached=null;isStale=!0;invalidate(){this.isStale=!0}get(e,n){let r=this.cached;if(r!==null&&!this.isStale)return r.sorted.result;let i=r===null?null:M_(r,e,n),a=r!==null&&i!==null?U_(r.sorted,i):qc(e,n);return this.cached={activityIds:[...e],links:n,sorted:a},this.isStale=!1,a.result}};function Ef(t,e){let n=[];for(let r of t)e.has(r)&&n.push(r);return n}function ds(t,e,n){let r=t.get(e);r?r.push(n):t.set(e,[n])}function us(t,e,n){let r=t.get(e),i=r?r.indexOf(n):-1;r&&i>=0&&r.splice(i,1)}function Rf(t){let e=[];for(let n of[t._summarySourceId,t._summaryTargetId,t._lagActivityId])n!==void 0&&e.push(String(n));return e}function ps(t,e){ds(t.outgoing,String(e.source),e),t.alapIds.has(String(e.source))&&ds(t.incomingFromAlap,String(e.target),e);for(let n of Rf(e))ds(t.bySummary,n,e)}function $c(t,e){us(t.outgoing,String(e.source),e),us(t.incomingFromAlap,String(e.target),e);for(let n of Rf(e))us(t.bySummary,n,e)}function Pf(t,e,n){let r=n.getActivity(e)?.constraintType===_.ALAP;if(r!==t.alapIds.has(e)){r?t.alapIds.add(e):t.alapIds.delete(e);for(let i of t.outgoing.get(e)??[])r?ds(t.incomingFromAlap,String(i.target),i):us(t.incomingFromAlap,String(i.target),i)}}function kf(t,e){let n={outgoing:new Map,incomingFromAlap:new Map,bySummary:new Map,alapIds:new Set};for(let r of e.getAllActivities())r.constraintType===_.ALAP&&n.alapIds.add(String(r.id));for(let r of t)ps(n,r);return n}function H_(t,e){let n=[],r=new Set,i=t;for(;i!==null&&!r.has(i);){r.add(i),n.push(i);let a=e.getActivity(i)?.parentId;i=a==null?null:String(a)}return n}function B_(t,e,n){return n.getChildren(t).map(String).filter(r=>e.alapIds.has(r))}function j_(t,e,n,r,i){for(let o of e.outgoing.get(t)??[])i(String(o.target));for(let o of e.incomingFromAlap.get(t)??[])i(String(o.source));let a=t;for(;a!==null&&!r.has(a);){r.add(a);for(let s of e.bySummary.get(a)??[])i(String(s.target));for(let s of B_(a,e,n))i(s);let o=n.getActivity(a)?.parentId;a=o==null?null:String(o)}}function bf(t,e,n,r){let i=new Set,a=new Set,o=[],s=c=>{i.has(c)||!r.activityExists(c)||(i.add(c),o.push(c))};for(let c of t)for(let d of H_(String(c),r))s(d);for(;o.length>0;){let c=o.pop();j_(c,n,r,a,s)}let l=e.filter(c=>i.has(String(c.source))||i.has(String(c.target)));return{idSet:i,links:l}}function ys(t,e){let n=e.getActivity(t);return n?Me(n.type,e.getChildren(t).length>0):!1}function fs(t,e,n){let r=String(e),i=n.getActivity(t);for(;i?.parentId&&String(i.parentId)!=="0";){if(String(i.parentId)===r)return!0;i=n.getActivity(i.parentId)}return!1}function hs(t,e,n){let r=ys(t,n);return ys(e,n)&&fs(t,e,n)||r&&fs(e,t,n)}function Nf(t,e){let n=[],r=[t];for(;r.length>0;){let i=r.pop(),a=e.getChildren(i);if(a.length===0){String(i)!==String(t)&&n.push(i);continue}for(let o of a)r.push(o)}return n}function zc(t){let e=new Map;for(let n of t)Jc(e,n);return e}function Jc(t,e){Lf(t,String(e.source),e),Lf(t,String(e.target),e)}function Lf(t,e,n){let r=t.get(e);if(r){r.push(n);return}t.set(e,[n])}function V_(t,e,n,r){if(t.length<=1)return t;let i=new Set(t.map(String)),a=[];for(let o of t)W_(o,i,e,n,r)||a.push(o);return a.length>0?a:t}function W_(t,e,n,r,i){let a=String(t),o=n.getActivity(t);if(!o||o.autoScheduling===!1)return!1;let s=r.get(a)??[];for(let l of s)if(K_(l,a,o,e,n,i))return!0;return!1}function K_(t,e,n,r,i,a){if(Y_(t)||!(a?String(t.source)===e:String(t.target)===e))return!1;let s=G_(t,e);if(!r.has(String(s)))return!1;let l=i.getActivity(s);return!!(l?.autoScheduling!==!1&&l&&q_(t,n,l))}function Y_(t){return t.source===t.target}function G_(t,e){return String(t.source)===e?t.target:t.source}function q_(t,e,n){let r=t.lag??0,i=Math.abs(r);return String(t.target)===String(n.id)&&i<=n.durationHours||String(t.target)===String(e.id)&&i<=e.durationHours}function Ff(t,e){let n=[],r=zc(t);for(let i of t)ms(n,i,e,r,0);return n}function ms(t,e,n,r,i){let a=ys(e.source,n),o=ys(e.target,n);if($_(e,a,o,n))return i;if(!a&&!o)return t.push(e),i;let s=Of(e.source,a,n,r,!0),l=Of(e.target,o,n,r,!1);return tE(t,s,l,e,n,i,r)}function $_(t,e,n,r){return n&&fs(t.source,t.target,r)||e&&fs(t.target,t.source,r)}function Of(t,e,n,r,i){return e?V_(Nf(t,n),n,r,i):[t]}function wf(t,e,n){let r=Nf(t,e);if(r.length===0)return null;let i=null,a=null;for(let o of r){let s=n(o);if(!s)continue;(i===null||s.startDate<i)&&(i=s.startDate),(a===null||s.endDate>a)&&(a=s.endDate)}return i===null||a===null?null:{startDate:i,endDate:a}}function Ai(t,e,n=r=>e.getActivity(r)){return wf(t,e,n)}function z_(t,e,n){return t?e?n.calculateDuration({startDate:e.startDate,endDate:e.endDate,task:t}):t.durationHours:0}function J_(t,e,n,r){if(!e)return 0;let i=r.getActivity(t);return!n||!i?-e.durationHours:-r.calculateDuration({startDate:n.startDate,endDate:i.endDate,task:e})}function X_(t,e){let n=String(t);return(e.get(n)??[]).some(i=>String(i.target)===n)}function Z_(t,e,n,r,i){if(!i&&X_(t,r))return 0;let a=n.getActivity(t);return!e||!a?0:n.calculateDuration({startDate:e,endDate:a.startDate,task:a})}function Q_(t,e){let n=e.getActivity(t.source),r=e.getActivity(t.target),i=Ai(t.source,e),a=Ai(t.target,e),o=wf(t.target,e,c=>{let d=e.getActivity(c);if(!d)return null;let u=d.constraintDate!==null&&(d.constraintType===_.MSO||d.constraintType===_.MFO);return d.autoScheduling&&d.progress!==100&&!u?{startDate:d.startDate,endDate:d.endDate}:null}),s=t.type===q.START_TO_START||t.type===q.START_TO_FINISH,l=t.type===q.FINISH_TO_FINISH||t.type===q.START_TO_FINISH;return{source:n,sourceBounds:i,targetStart:o?.startDate??r?.startDate,targetBounds:o,hasFrozenTargetStart:!!(a&&o&&a.startDate<o.startDate),targetEndpointIsFinish:l,userLag:t.lag??0,sourceEndpointIsStart:s,summarySourceId:s&&i?t.source:void 0,finishAnchoredSummaryTargetId:l&&o?t.target:void 0}}function tE(t,e,n,r,i,a,o){let s=Q_(r,i),{source:l,sourceBounds:c,targetStart:d,userLag:u}=s,{sourceEndpointIsStart:p,targetBounds:y,targetEndpointIsFinish:f,hasFrozenTargetStart:m,summarySourceId:A,finishAnchoredSummaryTargetId:g}=s,R=a;for(let P of e){let N=p?J_(P,l,c,i):0;for(let T of n){if(String(P)===String(T))continue;let x=f?-z_(i.getActivity(T),y,i):0,S=Z_(T,d,i,o,f);t.push(eE(r,P,T,R,N,x,u+S,A,g??((S!==0||m)&&x===0?r.target:void 0),y?r.target:void 0)),R+=1}}return R}function eE(t,e,n,r,i,a,o,s,l,c){return{id:`virtual_${t.id}_${r}`,source:e,target:n,type:t.type,lag:t.lag,freeSlackHours:null,isCritical:!1,...c===void 0?{}:{_lagActivityId:c},_sourceLag:i,_targetLag:a,_trueLag:o,...s===void 0?{}:{_summarySourceId:s},...l===void 0?{}:{_summaryTargetId:l}}}var nE=new Set(["startDate","endDate","durationHours","constraintType","constraintDate","autoScheduling","calendarId","progress"]),rE={patchesHierarchy:!0,ignoresLinks:!1,patchesLinkAppends:!0,patchesLinkRemovals:!0};function iE(t,e){if(t.length<e.length)return!1;for(let n=0;n<e.length;n+=1)if(t[n]!==e[n])return!1;return!0}function aE(t,e,n){if(!(t.length===e.length+n.length&&iE(t,e)))return null;let i=t.slice(e.length);return i.every((o,s)=>String(o.id)===n[s])?i:null}function gs(t,e,n){let r=t.get(e);r?r.includes(n)||r.push(n):t.set(e,[n])}function Mf(t,e,n,r){r.length===1&&r[0]===e||(gs(t,String(e.source),n),gs(t,String(e.target),n))}function Zc(t,e,n){let r=[];return ms(r,t,e,n,0),r}function oE(t,e,n,r){for(let s of n)Jc(t.linksByActivity,s);let i=t.expanded.slice(),a=new Int32Array(e.length),o=new Int32Array(e.length);return a.set(t.offsets),o.set(t.counts),n.forEach((s,l)=>{let c=t.rawLinks.length+l,d=Zc(s,r,t.linksByActivity);a[c]=i.length,o[c]=d.length,Mf(t.groupsByEndpoint,s,c,d),t.groupOfLink?.set(s,c);for(let u of d)i.push(u),t.coneIndex!==null&&ps(t.coneIndex,u)}),{...t,rawLinks:e,offsets:a,counts:o,expanded:i}}function sE(t,e){for(let n of[String(e.source),String(e.target)]){let r=t.get(n),i=r?r.indexOf(e):-1;r&&i>=0&&r.splice(i,1)}}function lE(t,e){for(let[n,r]of t){let i=[];for(let a of r){let o=e[a]??-1;o>=0&&i.push(o)}i.length===0?t.delete(n):t.set(n,i)}}function cE(t,e){if(e.length===0)return{expansion:t,removed:[]};let n=new Set(e),r=t.rawLinks.length;if(n.size>r)return null;let i=new Int32Array(r),a=[],o=new Int32Array(r-n.size),s=new Int32Array(r-n.size),l=[],c=[];return t.rawLinks.forEach((d,u)=>{let p=t.offsets[u]??0,y=t.counts[u]??0;if(n.has(String(d.id))){i[u]=-1,c.push(d),dE(t,d,p,y);return}i[u]=a.length,o[a.length]=l.length,s[a.length]=y,a.push(d);for(let f=p;f<p+y;f+=1)l.push(t.expanded[f])}),c.length!==n.size?null:(lE(t.groupsByEndpoint,i),{expansion:{...t,rawLinks:a,offsets:o,counts:s,expanded:l,groupOfLink:null},removed:c})}function dE(t,e,n,r){sE(t.linksByActivity,e);let i=t.coneIndex;if(i!==null)for(let a=n;a<n+r;a+=1)$c(i,t.expanded[a])}function uE(t,e){let n=zc(t),r=[],i=new Int32Array(t.length),a=new Int32Array(t.length),o=new Map;return t.forEach((s,l)=>{let c=r.length;i[l]=c,ms(r,s,e,n,0),a[l]=r.length-c,!(r.length-c===1&&r[c]===s)&&(gs(o,String(s.source),l),gs(o,String(s.target),l))}),{rawLinks:t,linksByActivity:n,offsets:i,counts:a,groupsByEndpoint:o,expanded:r,groupOfLink:null,coneIndex:null}}function pE(t,e,n){let r=new Set,i=new Set;for(let a of e){let o=a;for(;o!==null&&!i.has(o);){i.add(o);for(let l of t.groupsByEndpoint.get(o)??[])r.add(l);let s=n.getActivity(o)?.parentId;o=s==null?null:String(s)}}return[...r]}function yE(t){return t.groupOfLink??=new Map(t.rawLinks.map((e,n)=>[e,n])),t.groupOfLink}function fE(t,e){let n=new Set,r=[];for(let a of t){r.push(a);let o=a;for(;o!==null&&!n.has(o);){n.add(o);let s=e.getActivity(o)?.parentId;o=s==null?null:String(s)}}let i=new Set;for(let a=r.pop();a!==void 0;){if(!i.has(a)){i.add(a);for(let o of e.getChildren(a))n.add(String(o)),r.push(String(o))}a=r.pop()}return n}function Xc(t,e,n){let r=yE(t),i=new Set;for(let a of fE(e,n))for(let o of t.linksByActivity.get(a)??[]){let s=r.get(o);s!==void 0&&i.add(s)}return[...i]}function hE(t,e){if(t===e)return!0;let n=Object.entries(t);return n.length===Object.keys(e).length&&n.every(([r,i])=>Object.is(i,Reflect.get(e,r)))}function mE(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(!hE(t[n],e[n]))return!1;return!0}function Uf(t,e){let n=t.counts.slice();for(let[a,o]of e)n[a]=o.length;let r=new Int32Array(n.length),i=[];return n.forEach((a,o)=>{r[o]=i.length;let s=e.get(o);if(s!==void 0){for(let c of s)i.push(c);return}let l=t.offsets[o]??0;for(let c=0;c<a;c+=1)i.push(t.expanded[l+c])}),{...t,offsets:r,counts:n,expanded:i}}function xf(t,e,n){let r=new Map;for(let i of e){let a=t.rawLinks[i],o=t.offsets[i]??0,s=t.expanded.slice(o,o+(t.counts[i]??0)),l=Zc(a,n,t.linksByActivity);if(mE(s,l))continue;r.set(i,l),Mf(t.groupsByEndpoint,a,i,l);let c=t.coneIndex;if(c!==null){for(let d of s)$c(c,d);for(let d of l)ps(c,d)}}return r.size===0?t:Uf(t,r)}var Ii=class{expansion=null;writeLog=null;get(e,n){this.writeLog??=n.openSchedulingWriteLog(nE,rE);let r=this.writeLog.take(),i=this.expansion;if(i===null||r.structural)return this.rebuild(e,n);let a=cE(i,r.removedLinkIds);if(a===null)return this.rebuild(e,n);let o=a.expansion,s=aE(e,o.rawLinks,r.appendedLinkIds);if(s===null)return this.rebuild(e,n);let l=s.length===0?o:oE(o,e,s,n),c=l.coneIndex;if(c!==null)for(let u of[...r.touchedIds,...r.reshapedIds])Pf(c,u,n);r.reshapedIds.size>0&&(l=xf(l,Xc(l,r.reshapedIds,n),n));let d=[...r.touchedIds,...[...a.removed,...s].flatMap(u=>[String(u.source),String(u.target)])];return d.length>0&&(l=xf(l,pE(l,d,n),n)),this.expansion=l,l.expanded}projectHierarchy(e,n,r,i){this.get(e,n);let a=this.expansion;if(a===null)return[];let o=new Set([...Xc(a,i,n),...Xc(a,i,r)]),s=new Map;for(let l of o)s.set(l,Zc(a.rawLinks[l],r,a.linksByActivity));return Uf(a,s).expanded}coneIndex(e){let n=this.expansion;if(n===null)throw new Error("ExpandedLinksCache: cone index read before get");return n.coneIndex??=kf(n.expanded,e),n.coneIndex}rebuild(e,n){return this.expansion=uE(e,n),this.expansion.expanded}};function gE(t){let e=new Map,n=r=>(e.has(r)||e.set(r,new Set),e.get(r));for(let r of t)n(r.source).add(r.id),n(r.target).add(r.id);return{neighbors:e}}function AE(t,e,n){let r=new Set,i=new Map,a=new _e;for(a.enqueue(t);!a.isEmpty();){let o=a.dequeue(),s=String(o);if(r.has(s))continue;r.add(s);let l=n.neighbors.get(o);if(l)for(let c of l){let d=e.get(c);if(!d)continue;let u=`${d.source}-${d.target}-${d.type}`;i.has(u)||i.set(u,d);let p=String(d.source)===s?d.target:d.source;r.has(String(p))||a.enqueue(p)}}return Array.from(i.values())}function Hf(t,e){let n=new Map;for(let o of e)n.set(o.id,o);let r=gE(e),i=AE(t,n,r),a=new Set([String(t)]);for(let o of i)a.add(String(o.source)),a.add(String(o.target));return{activityIds:a,links:i}}var Bf=36e5,jf=1;function jn(t,e){return new Date(t.getTime()+e*Bf)}function xa(t){return new Date(t.getTime()+jf)}function Si(t){return new Date(t.getTime()-jf)}function Vf(t,e){return(e.getTime()-t.getTime())/Bf}function Wf(t,e,n){let r=n.type===q.FINISH_TO_START,i=n.type===q.FINISH_TO_FINISH;if(n._targetLag!==void 0)return{sourceLag:n._sourceLag??0,targetLag:n._targetLag,trueLag:n._trueLag??n.lag??0,isFS:r,isFF:i,isZeroDurationCase:!1};let a=n.lag??0;switch(n.type){case q.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:a,isFS:r,isFF:i,isZeroDurationCase:!1};case q.START_TO_START:return{sourceLag:-t.durationHours,targetLag:0,trueLag:a,isFS:r,isFF:i,isZeroDurationCase:!1};case q.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-e.durationHours,trueLag:a,isFS:r,isFF:i,isZeroDurationCase:!1};case q.START_TO_FINISH:return{sourceLag:-t.durationHours,targetLag:-e.durationHours,trueLag:a,isFS:r,isFF:i,isZeroDurationCase:!1};default:return{sourceLag:0,targetLag:0,trueLag:a,isFS:r,isFF:i,isZeroDurationCase:!1}}}function IE(t,e,n,r){if(t._summarySourceId===void 0)return null;let i=n.getActivity(t._summarySourceId);if(!i)return null;let a=Ai(t._summarySourceId,n,r);return a?-n.calculateDuration({startDate:a.startDate,endDate:e.endDate,task:i}):null}function SE(t,e,n,r,i){let a=e.durationHours===0&&i;return{successorStart:r.getClosestWorkTime({date:t.endDate,dir:a?"past":"future",task:e}),link:n}}function vE(t,e,n,r){return n===null?new Date(t.endDate):r.getClosestWorkTime({date:t.endDate,dir:"future",task:e})}function As(t,e,n,r){return n===null?jn(t,e):r.calculateEndDate({startDate:t,durationHours:e,task:n})}function CE(t,e,n){return e===null?new Date(t.startDate):n.getClosestWorkTime({date:t.startDate,dir:"past",task:e})}function Ma(t,e,n,r,i=e,a){let{sourceLag:o,targetLag:s,trueLag:l,isFS:c,isFF:d}=Wf(t,e,n),u=IE(n,t,r,a)??o,p=n._lagActivityId===void 0?null:r.getActivity(n._lagActivityId),y=u+s+l,f=e.durationHours===0;if(!(f?y!==0:u!==0||s!==0||l!==0)&&(!p||f&&u===0&&s===0&&l===0))return SE(t,e,n,r,c||d);let g=vE(t,c?p??e:t,i,r);if(u!==0&&(g=r.calculateEndDate({startDate:g,durationHours:u,task:t})),p){g=As(g,n.lag??0,p,r),g=r.getClosestWorkTime({date:g,dir:c||n.type===q.START_TO_START?"future":"past",task:p});let R=s+l-(n.lag??0);R!==0&&(g=r.calculateEndDate({startDate:g,durationHours:R,task:e}))}else s!==0&&(g=r.calculateEndDate({startDate:g,durationHours:s,task:e})),l!==0&&(g=As(g,l,i,r));if(e.durationHours===0){if(c||d)return{successorStart:r.getClosestWorkTime({date:g,dir:"past",task:e}),link:n};let R=new Date(Date.UTC(g.getUTCFullYear(),g.getUTCMonth(),g.getUTCDate()));return{successorStart:r.getClosestWorkTime({date:R,dir:"future",task:e}),link:n}}return{successorStart:r.getClosestWorkTime({date:g,dir:"future",task:e}),link:n}}function Is(t,e,n,r,i=t){let{sourceLag:a,targetLag:o,trueLag:s}=Wf(e,t,n),l=n._lagActivityId===void 0?null:r.getActivity(n._lagActivityId),c=l?new Date(t.startDate):CE(t,i,r);if(l){let d=o+s-(n.lag??0);d!==0&&(c=r.calculateEndDate({startDate:c,durationHours:-d,task:t})),c=As(c,-(n.lag??0),l,r)}else s!==0&&(c=As(c,-s,i,r)),o!==0&&(c=r.calculateEndDate({startDate:c,durationHours:-o,task:t}));return a!==0&&(c=r.calculateEndDate({startDate:c,durationHours:-a,task:e})),c}function Kf(t,e,n){for(let r of t){let i=e.getActivity(r);if(!i)continue;let a=i.constraintType;if(!a||a===_.ASAP||a===_.ALAP)continue;let o=Tn(i,e);!o.earliestStart&&!o.latestStart&&!o.earliestEnd&&!o.latestEnd||n.set(r,{activityId:r,startDate:i.startDate,endDate:i.endDate,drivingLinkId:null,kind:_.ASAP,conflict:!1,earliestStart:o.earliestStart,latestStart:o.latestStart,earliestEnd:o.earliestEnd,latestEnd:o.latestEnd})}}function vi(t,e,n){let r={earliestStart:e.earliestStart??null,latestStart:e.latestStart??null,earliestEnd:e.earliestEnd??null,latestEnd:e.latestEnd??null},i=e.earliestSchedulingStart??e.latestSchedulingStart??null,a;i===null?a=Tc(t.startDate,r):Lp(i,r)?a=i:a=Tc(i,r),e.startDate=a,e.endDate=n.calculateEndDate({startDate:a,durationHours:t.durationHours,task:t})}function Yf(t,e){if(!t||!e)return new Date;let{constraintType:n,constraintDate:r}=t;if(!n||!r)return e;switch(n){case _.MSO:case _.MFO:return new Date(r);case _.SNET:case _.FNET:return r>e?new Date(r):e;case _.SNLT:case _.FNLT:return r<e?new Date(r):e;default:return e}}function DE(t,e){return e.length?e.some(n=>String(n)===String(t)):!1}function Gf(t,e,n){return e.dragWithMultiple&&DE(t,n)}function qf(t,e,n){let r=new Map;for(let i of t){if(i.type!==q.FINISH_TO_FINISH&&i.type!==q.START_TO_FINISH)continue;let a=i._summaryTargetId;if(a===void 0||r.has(a))continue;let o=!1,s=new Map,l=null,c=null,d=Ai(a,e,y=>{let f=e.getActivity(y);if(!f)return null;let m=n(y);s.set(y,m.startDate),(!f.autoScheduling||f.progress===100||f.constraintType!==_.ASAP)&&(o=!0);for(let R of e.getIncomingLinkIds(y)){let P=e.getLink(R);P&&String(P.source)!==String(a)&&!e.isChildOf(P.source,a)&&(o=!0)}let A=f.constraintDate!==null&&(f.constraintType===_.MSO||f.constraintType===_.MFO);return f.autoScheduling&&f.progress!==100&&!A&&(l===null||m.endDate>l||m.endDate.getTime()===l.getTime()&&y<(c??y))&&(l=m.endDate,c=y),m}),u=new Set,p=c===null?[]:[c];for(;p.length>0;){let y=p.pop();if(!u.has(y)){u.add(y);for(let f of[...e.getIncomingLinkIds(y),...e.getOutgoingLinkIds(y)]){let m=e.getLink(f);if(!m)continue;let A=String(m.source)===String(y)?m.target:m.source;s.has(A)&&!u.has(A)&&p.push(A)}}}r.set(a,o&&d?{endDate:d.endDate,movableEnd:l,starts:s,drivingLeafIds:u}:null)}return r}async function Qc(t,e,n,r,i,a,o=!1){let s=new Map;for(let y of e){let f=String(y.target),m=s.get(f);m?m.push(y):s.set(f,[y])}let l=y=>{let f=a.get(y);if(f?.startDate&&f.endDate)return{startDate:f.startDate,endDate:f.endDate};let m=n.getActivity(y);return m?{startDate:m.startDate,endDate:m.endDate}:{startDate:new Date,endDate:new Date}},c=qf(e,n,l),d=n.getFlags(),u=r.draggedIds??[],p=performance.now();for(let y of t){if(wa(p)){let S=await ls(p,i);if(S.aborted)return a;p=S.newSliceStart}let f=n.getActivity(y);if(!f||!f.autoScheduling||f.progress===100||TE(f,n))continue;let m=s.get(String(y))??[],A=null,g=null,R=!1;for(let S of m){let k=n.getActivity(S.source);if(!k)continue;let F=l(S.source),U=F.startDate.getTime()!==k.startDate.getTime()||F.endDate.getTime()!==k.endDate.getTime(),w=U?{...k,startDate:F.startDate,endDate:F.endDate}:k,M=Gf(S.source,d,u)?{...S,lag:0}:S,$=M._summaryTargetId===void 0||M.type!==q.FINISH_TO_FINISH&&M.type!==q.START_TO_FINISH?null:c.get(M._summaryTargetId);if($){if(o)continue;let Ct=Ma(w,{...f,durationHours:0},{...M,_targetLag:0,_trueLag:M.lag},n,f,l).successorStart,L=n.getActivity(M._summaryTargetId)??f;if($.endDate>=Ct||n.calculateDuration({startDate:$.endDate,endDate:Ct,task:L})===0||$.movableEnd===null||!$.drivingLeafIds.has(y))continue;M={...M,_targetLag:-n.calculateDuration({startDate:$.starts.get(y)??f.startDate,endDate:$.movableEnd,task:f}),_trueLag:M.lag}}let st=!1,at=Ma(w,f,M,n,f,Ct=>{let L=l(Ct),K=n.getActivity(Ct);return K&&(L.startDate.getTime()!==K.startDate.getTime()||L.endDate.getTime()!==K.endDate.getTime())&&(st=!0),L});(!A||at.successorStart.getTime()>A.getTime())&&(A=at.successorStart,g=String(S.id),R=S._summaryTargetId!==void 0&&!U&&!st&&(S._targetLag===0||r.preventSummaryTargetPullback===!0))}A!==null&&R&&A<f.startDate&&(A=new Date(f.startDate));let N=a.get(y),T=N?{...N}:{activityId:y,startDate:f.startDate,endDate:f.endDate,drivingLinkId:null,kind:_.ASAP,conflict:!1},x=T.earliestStart||T.latestStart||T.earliestEnd||T.latestEnd;if(!(!A&&!x)){if(A){let S=A;f.type===H.MILESTONE&&(S=Yf(f,A)),T.drivingLinkId=g,T.startDate=S,T.endDate=n.calculateEndDate({startDate:S,durationHours:f.durationHours,task:f}),T.earliestSchedulingStart=S,T.earliestSchedulingEnd=T.endDate}else f.constraintType===_.MSO?T.earliestStart&&(T.startDate=T.earliestStart,T.endDate=T.earliestEnd??n.calculateEndDate({startDate:T.earliestStart,durationHours:f.durationHours,task:f})):f.constraintType===_.MFO&&T.latestStart&&(T.startDate=T.latestStart,T.endDate=T.latestEnd??n.calculateEndDate({startDate:T.latestStart,durationHours:f.durationHours,task:f}));vi(f,T,n),a.set(y,T)}}return a}function TE(t,e){return Me(t.type,e.getChildren(t.id).length>0)}async function zf(t,e,n,r,i,a){let o=new Map(n),s=new Set;for(let f of t)r.getActivity(f)?.constraintType===_.ALAP&&s.add(String(f));if(s.size===0)return o;let l=new Map,c=new Map;for(let f of e){let m=String(f.source);s.has(m)&&$f(l,m,f);let A=String(f.target);s.has(A)&&$f(c,A,f)}let d=f=>{let m=o.get(f);if(m)return{startDate:m.startDate,endDate:m.endDate};let A=r.getActivity(f);return A?{startDate:A.startDate,endDate:A.endDate}:{startDate:new Date,endDate:new Date}},u=f=>!f.parentId||G(f.parentId)?r.getProjectEnd():d(f.parentId).endDate,p=(f,m)=>{let A=f,g=new Set;for(;A&&!G(A)&&!g.has(String(A));){if(g.add(String(A)),String(A)===String(m))return!0;let R=r.getActivity(A);if(!R||!R.parentId)break;A=R.parentId}return!1},y=performance.now();for(let f of t){if(wa(y)){let X=await ls(y,a);if(X.aborted)return o;y=X.newSliceStart}let m=r.getActivity(f);if(!m||m.constraintType!==_.ALAP||!m.autoScheduling||m.progress===100||Me(m.type,r.getChildren(f).length>0))continue;let A=u(m),g=A,R=null,P=null,N=!1,T=l.get(String(f))??[];for(let X of T){if((X.lag??0)<0)continue;let v=r.getActivity(X.target);if(!v||v.autoScheduling===!1)continue;let O=d(X.target),B={...v,startDate:O.startDate,endDate:O.endDate},V=Is(B,m,X,r);(g===null||V<g)&&(g=V),(R===null||V<R)&&(R=V,P=X.type,N=m.parentId&&!G(m.parentId)?p(X.target,m.parentId):!1)}if(R!==null)if(N||A===null)g=R;else{let X=d(f).endDate,v=X.getTime()>A.getTime()?X:A;g=R<v?R:v}else{if(A===null||g===null)continue;g>A&&(g=A)}if(g===null)continue;let S=(c.get(String(f))??[]).some(X=>X.type===q.FINISH_TO_START||X.type===q.FINISH_TO_FINISH),k=new Date(Date.UTC(g.getUTCFullYear(),g.getUTCMonth(),g.getUTCDate())),F=m.endDate,U=r.getClosestWorkTime({date:new Date(Date.UTC(F.getUTCFullYear(),F.getUTCMonth(),F.getUTCDate()+1)),dir:"past",task:m}).getTime()===F.getTime(),w=A!==null&&g.getTime()===A.getTime()&&A.getTime()===F.getTime(),M=()=>w&&U?new Date(F):r.getClosestWorkTime({date:k,dir:"past",task:m}),$=()=>{let X=r.getClosestWorkTime({date:g,dir:"past",task:m});return r.getClosestWorkTime({date:new Date(Date.UTC(X.getUTCFullYear(),X.getUTCMonth(),X.getUTCDate())),dir:"future",task:m})},st=r.getClosestWorkTime({date:g,dir:"future",task:m}).getTime()===g.getTime(),at;if(m.durationHours===0&&R===null)at=S&&st?M():r.getClosestWorkTime({date:g,dir:"past",task:m});else if(m.durationHours===0)if(R!==null&&P===q.FINISH_TO_START&&g.getTime()===R.getTime())at=g;else if(S)at=M();else{let X=r.getClosestWorkTime({date:g,dir:"future",task:m});at=X.getTime()>g.getTime()&&!wn(X,g)?$():X}else at=r.getClosestWorkTime({date:g,dir:"future",task:m});let Ct=r.calculateEndDate({startDate:at,durationHours:-m.durationHours,task:m}),L=o.get(f),K=L?{...L}:{activityId:f,startDate:Ct,endDate:at,drivingLinkId:null,kind:_.ALAP,conflict:!1};K.startDate=Ct,K.endDate=at,K.drivingLinkId=null,K.kind=_.ALAP;let dt=K.earliestSchedulingStart??null;K.earliestSchedulingStart=null,K.earliestSchedulingEnd=null;let lt=dt!==null&&dt.getTime()>Ct.getTime()?dt:Ct;K.latestSchedulingStart=lt,K.latestSchedulingEnd=lt===Ct?at:r.calculateEndDate({startDate:lt,durationHours:m.durationHours,task:m}),vi(m,K,r),o.set(f,K)}return o}function $f(t,e,n){let r=t.get(e);r?r.push(n):t.set(e,[n])}var Pe={warn(){},error(){}};var _E=864e5;function Je(t){if(t.type===H.MILESTONE)return 0;let e=t.startDate?.getTime(),n=t.endDate?.getTime();return e==null||n==null||Number.isNaN(e)||Number.isNaN(n)?null:Math.floor((n-e)/_E)+1}function Ua(t,e){e.cancelled||e.updatedIds.length===0||t.batchUpdate(()=>{for(let n of e.updatedIds){let r=e.plans.get(n);if(!r)continue;let i=t.getLiveActivity(n);i&&(i.startDate=r.startDate,i.endDate=r.endDate,i.calendarDuration=Je(i),t.updateActivity(n))}})}function td(t,e){let n=String(e.source),r=String(e.target);if(n===r)return!0;let i=new Map;for(let a of t){let o=String(a.source),s=String(a.target),l=i.get(o)??[];l.push(s),i.set(o,l)}return EE(i,r,n)}function Ha(t){let e=new Map,n=p=>{let y=String(p),f=e.get(y);return f!==void 0?f:(e.set(y,e.size),e.size-1)},r=new Int32Array(t.length),i=new Int32Array(t.length);t.forEach((p,y)=>{r[y]=n(p.source),i[y]=n(p.target)});let a=e.size,o=new Int32Array(a+1),s=new Int32Array(a);for(let p=0;p<t.length;p+=1){let y=h(r,p);o[y+1]=h(o,y+1)+1;let f=h(i,p);s[f]=h(s,f)+1}for(let p=0;p<a;p+=1)o[p+1]=h(o,p+1)+h(o,p);let l=o.slice(0,a),c=new Int32Array(t.length);for(let p=0;p<t.length;p+=1){let y=h(r,p);c[h(l,y)]=h(i,p),l[y]=h(l,y)+1}let d=new Int32Array(a),u=0;for(let p=0;p<a;p+=1)h(s,p)===0&&(d[u++]=p);for(let p=0;p<u;p+=1){let y=h(d,p),f=h(o,y+1);for(let m=h(o,y);m<f;m+=1){let A=h(c,m),g=h(s,A)-1;s[A]=g,g===0&&(d[u++]=A)}}return u!==a}function EE(t,e,n){if(e===n)return!0;let r=new Set([e]),i=new _e;for(i.enqueue(e);!i.isEmpty();){let a=i.dequeue(),o=t.get(a)??[];for(let s of o){if(s===n)return!0;r.has(s)||(r.add(s),i.enqueue(s))}}return!1}function Ci(t){let e=RE(t);for(let n of e.adjacency.keys())e.records.has(n)||PE(n,e);return e.components}function RE(t){let e=new Map,n=new Set;for(let r of t){let i=String(r.source),a=String(r.target),o=Jf(e,i);if(Jf(e,a),i===a){n.add(i);continue}o.push(a)}return{adjacency:e,selfLooped:n,records:new Map,componentStack:[],nextIndex:0,components:[]}}function Jf(t,e){let n=t.get(e);if(n)return n;let r=[];return t.set(e,r),r}function PE(t,e){let n=[];for(n.push({node:t,record:Xf(t,e),neighborCursor:0});n.length>0;){let r=n[n.length-1];if(r===void 0)break;let i=e.adjacency.get(r.node)??[];if(r.neighborCursor<i.length){let s=i[r.neighborCursor];if(r.neighborCursor+=1,s===void 0)continue;kE(r,s,n,e);continue}n.pop();let a=n[n.length-1];a&&r.record.lowLink<a.record.lowLink&&(a.record.lowLink=r.record.lowLink),r.record.lowLink===r.record.visitIndex&&bE(r.node,e)}}function kE(t,e,n,r){let i=r.records.get(e);if(!i){n.push({node:e,record:Xf(e,r),neighborCursor:0});return}i.onStack&&i.visitIndex<t.record.lowLink&&(t.record.lowLink=i.visitIndex)}function Xf(t,e){let n={visitIndex:e.nextIndex,lowLink:e.nextIndex,onStack:!0};return e.nextIndex+=1,e.records.set(t,n),e.componentStack.push({node:t,record:n}),n}function bE(t,e){let n=[];for(;;){let o=e.componentStack.pop();if(o===void 0||(o.record.onStack=!1,n.push(o.node),o.node===t))break}let r=n[0],i=n.length===1&&r!==void 0&&e.selfLooped.has(r);(n.length>1||i)&&e.components.push(n)}var Zf=new WeakMap;function Qf(t,e,n){let r=Zf.get(t)??new Ii;Zf.set(t,r);let i=new Set;for(let[a,o]of n.reparented){i.add(String(a)),o!==null&&i.add(String(o));let s=t.getActivity(a)?.parentId;s!=null&&i.add(String(s))}return r.projectHierarchy(e,t,new Ss(t,n),i)}function Vn(t,e,n){let r=n?new Ss(t,n):t;return Ff([...e],r)}var Ss=class{constructor(e,n){this.base=e;e.isWorkTime!==void 0&&(this.isWorkTime=e.isWorkTime.bind(e));for(let[r,i]of n.reparented){let a=String(r),o=i===null||G(i)?null:i,s=e.getActivity(r)?.parentId??null,l=s===null||G(s)?null:String(s),c=o===null?null:String(o);if(l!==c){if(this.reparented.set(a,o),l!==null){let d=this.movedOutByParent.get(l)??new Set;d.add(a),this.movedOutByParent.set(l,d)}if(c!==null){let d=this.movedInByParent.get(c)??[];d.push(r),this.movedInByParent.set(c,d)}}}}base;isWorkTime;reparented=new Map;movedOutByParent=new Map;movedInByParent=new Map;withOverride(e){if(!e)return null;let n=this.reparented.get(String(e.id));return n===void 0?e:{...e,parentId:n}}getActivity(e){return this.withOverride(this.base.getActivity(e))}getLiveActivity(e){return this.withOverride(this.base.getLiveActivity(e))}getAllActivities(){return this.base.getAllActivities().map(e=>this.withOverride(e)??e)}getChildren(e){let n=String(e),r=this.movedOutByParent.get(n),i=this.base.getChildren(e),a=r?i.filter(s=>!r.has(String(s))):[...i],o=this.movedInByParent.get(n);return o&&a.push(...o),a}getParent(e){let n=this.reparented.get(String(e));return n===void 0?this.base.getParent(e):n===null?null:this.getActivity(n)}isChildOf(e,n){let r=String(n),i=new Set,a=this.getActivity(e);for(;a;){let o=a.parentId;if(o===null||G(o))return!1;let s=String(o);if(s===r)return!0;if(i.has(s))return!1;i.add(s),a=this.getActivity(o)}return!1}getAllLinks(){return this.base.getAllLinks()}getAllIds(){return this.base.getAllIds()}getLink(e){return this.base.getLink(e)}activityExists(e){return this.base.activityExists(e)}getOutgoingLinkIds(e){return this.base.getOutgoingLinkIds(e)}getIncomingLinkIds(e){return this.base.getIncomingLinkIds(e)}getClosestWorkTime(e){return this.base.getClosestWorkTime(e)}calculateEndDate(e){return this.base.calculateEndDate(e)}calculateDuration(e){return this.base.calculateDuration(e)}batchUpdate(e){this.base.batchUpdate(e)}updateActivity(e){this.base.updateActivity(e)}getFlags(){return this.base.getFlags()}getProjectEnd(){return this.base.getProjectEnd()}};function Di(t){let{port:e,proposedPort:n,currentLinks:r,proposedLinks:i,proposal:a}=t,o=Vn(n??e,i,a);return nh(o,()=>Vn(e,r))}function eh(t,e){let n=t.getAllLinks();return nh(Qf(t,n,e),()=>Vn(t,n))}function nh(t,e){if(!Ha(t))return{ok:!0};let n=e(),r=th(n),a=[...th(t)].filter(o=>!r.has(o));return a.length===0?{ok:!0}:{ok:!1,newlyCyclicActivityIds:a}}function th(t){let e=new Set;for(let n of Ci(t))for(let r of n)e.add(r);return e}function vs(t,e,n){return n.getChildren(t).length>0||n.getChildren(e).length>0}function Xe(t,e){switch(t.kind){case Ut.CREATE:return LE(t,e);case Ut.UPDATE:return OE(t,e.port,e.rejectParentLinkMutations??!1);case Ut.DELETE:return NE(t,e)}}function Ba(t,e){if(t.length===0)return{applied:!0};let n=e.port.getAllLinks(),r=new Map,i=[];for(let c of n){let d=Cs(c);r.has(d)||r.set(d,c.id),i.push({source:c.source,target:c.target})}let a=Ha(i),o=null;for(let{operation:c,linkId:d}of t){if(String(c.source)===String(c.target)){o={applied:!1,rejected:Ot.SELF_LINK};break}if(!e.port.getActivity(c.source)||!e.port.getActivity(c.target)){o={applied:!1,rejected:Ot.ACTIVITY_MISSING};break}if(e.rejectParentLinkMutations&&vs(c.source,c.target,e.port)){o={applied:!1,rejected:Ot.HIERARCHY_LINK};break}if(hs(c.source,c.target,e.port)){o={applied:!1,rejected:Ot.HIERARCHY_LINK};break}let u=Cs(c),p=r.get(u);if(p!==void 0){o={applied:!1,rejected:Ot.DUPLICATE,linkId:p};break}if(r.set(u,d),a&&td(i,{source:c.source,target:c.target}))return{applied:!1,rejected:Ot.CYCLE};i.push({source:c.source,target:c.target})}if(!a&&Ha(i))return{applied:!1,rejected:Ot.CYCLE};if(o)return o;let s=[...n,...t.map(({operation:c,linkId:d})=>({id:d,source:c.source,target:c.target,type:c.type,lag:c.lag,freeSlackHours:null,isCritical:!1}))];return Di({port:e.port,currentLinks:n,proposedLinks:s}).ok?{applied:!0}:{applied:!1,rejected:Ot.CYCLE}}function Ds(t,e){if(t.length===0)return{applied:!0};let n=Ba(t,e);if(!n.applied)return n;for(let{operation:r,linkId:i}of t){let a=e.preserved?.get(i);e.port.addLink({id:i,source:r.source,target:r.target,type:r.type,lag:r.lag,freeSlackHours:null,isCritical:!1,...a?.ganttId===void 0?{}:{ganttId:a.ganttId},...a?.sectorId===void 0?{}:{sectorId:a.sectorId},...a?.proplannerId===void 0?{}:{proplannerId:a.proplannerId}})}return{applied:!0}}function Cs(t){return JSON.stringify([String(t.source),String(t.target),t.type])}function LE(t,e){let{port:n}=e;if(String(t.source)===String(t.target))return{applied:!1,rejected:Ot.SELF_LINK};let r=n.getActivity(t.source),i=n.getActivity(t.target);if(!r||!i)return{applied:!1,rejected:Ot.ACTIVITY_MISSING};if(e.rejectParentLinkMutations&&vs(t.source,t.target,n))return{applied:!1,rejected:Ot.HIERARCHY_LINK};if(hs(t.source,t.target,n))return{applied:!1,rejected:Ot.HIERARCHY_LINK};let a=n.getAllLinks();for(let d of a)if(String(d.source)===String(t.source)&&String(d.target)===String(t.target)&&d.type===t.type)return{applied:!1,rejected:Ot.DUPLICATE,linkId:d.id};let o=a.map(d=>({source:d.source,target:d.target}));if(td(o,{source:t.source,target:t.target}))return{applied:!1,rejected:Ot.CYCLE};if(!e.newLinkId)throw new Error("creating a link requires newLinkId");let s=e.newLinkId(),l={id:s,source:t.source,target:t.target,type:t.type,lag:t.lag,freeSlackHours:null,isCritical:!1};return Di({port:n,currentLinks:a,proposedLinks:[...a,l]}).ok?(n.addLink(l),{applied:!0,linkId:s}):{applied:!1,rejected:Ot.CYCLE}}function OE(t,e,n){let r=e.getLink(t.linkId);if(!r)return{applied:!1,rejected:Ot.LINK_MISSING};let i={...r,source:t.source??r.source,target:t.target??r.target,type:t.type??r.type,lag:t.lag??r.lag};if(String(i.source)===String(i.target))return{applied:!1,rejected:Ot.SELF_LINK};if(!e.getActivity(i.source)||!e.getActivity(i.target))return{applied:!1,rejected:Ot.ACTIVITY_MISSING};if(n&&(vs(r.source,r.target,e)||vs(i.source,i.target,e)))return{applied:!1,rejected:Ot.HIERARCHY_LINK};if(hs(i.source,i.target,e))return{applied:!1,rejected:Ot.HIERARCHY_LINK};let a=e.getAllLinks(),o=a.find(c=>String(c.id)!==String(t.linkId)&&Cs(c)===Cs(i));if(o)return{applied:!1,rejected:Ot.DUPLICATE,linkId:o.id};let s=a.map(c=>String(c.id)===String(t.linkId)?i:c);return Di({port:e,currentLinks:a,proposedLinks:s}).ok?((String(r.source)!==String(i.source)||String(r.target)!==String(i.target))&&e.setLinkEndpoints(t.linkId,i.source,i.target),t.lag!==void 0&&e.setLinkField(t.linkId,"lag",t.lag),t.type!==void 0&&e.setLinkField(t.linkId,"type",t.type),{applied:!0,linkId:t.linkId}):{applied:!1,rejected:Ot.CYCLE}}function NE(t,e){let{port:n}=e;return n.getLink(t.linkId)?(n.removeLink(t.linkId),{applied:!0,linkId:t.linkId}):{applied:!1,rejected:Ot.LINK_MISSING}}var Be={FINISH_TO_START:"fs",START_TO_START:"ss",FINISH_TO_FINISH:"ff",START_TO_FINISH:"sf"},Ts={[q.FINISH_TO_START]:Be.FINISH_TO_START,[q.START_TO_START]:Be.START_TO_START,[q.FINISH_TO_FINISH]:Be.FINISH_TO_FINISH,[q.START_TO_FINISH]:Be.START_TO_FINISH},_r={[Be.FINISH_TO_START]:q.FINISH_TO_START,[Be.START_TO_START]:q.START_TO_START,[Be.FINISH_TO_FINISH]:q.FINISH_TO_FINISH,[Be.START_TO_FINISH]:q.START_TO_FINISH},rh=Be.FINISH_TO_START;function ih(t){if(t in _r)return _r[t]}var ah=";",Wn={DAY:"d",WEEK:"w",WEEK_DHTMLX:"wk",MONTH:"m",MONTH_DHTMLX:"mon",YEAR:"y"},oh=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)(weeks?|wk|w|months?|mon|m|days?|d|years?|y)?)?$/i;var FE=5,_s=30,ed=365,wE={[Wn.DAY]:1,day:1,days:1,[Wn.MONTH]:_s,[Wn.MONTH_DHTMLX]:_s,month:_s,months:_s,[Wn.YEAR]:ed,year:ed,years:ed},xE=new Set([Wn.WEEK,Wn.WEEK_DHTMLX,"week","weeks"]);function Es(t,e={}){let n=[],r=[],i=e.daysPerWeek!==void 0&&Number.isFinite(e.daysPerWeek)&&e.daysPerWeek>0?e.daysPerWeek:FE,a=t.replace(/\s+/g,"");if(a.length===0)return{specs:n,errors:r};for(let o of a.split(ah)){if(o.length===0)continue;let s=ME(o,i);s?n.push(s):r.push(o)}return{specs:n,errors:r}}function ME(t,e){let n=t.toLowerCase(),r=oh.exec(n);if(!r)return null;let[,i,a,o,s,l]=r,c=a?_r[a]:_r[rh],d=0;if(s!==void 0){let u=Number(s);if(Number.isNaN(u))return null;let p=l!==void 0&&xE.has(l)?e:wE[l??Wn.DAY],y=u*p;d=o==="-"?-y:y}return{correlativeId:i,type:c,lag:d}}function Ti(t){let{targetActivityId:e,currentLinks:n,desiredSpecs:r}=t,i=[],a=new Map;for(let c of r){let d=t.resolveActivityByCorrelative(c.correlativeId);if(d==null){i.push(c);continue}let u=Rs(d,c.type);a.has(u)||a.set(u,{source:d,type:c.type,lag:c.lag})}let o=new Map;for(let c of n)String(c.target)===String(e)&&o.set(Rs(c.source,c.type),c);let s=[],l=sh(o,a,c=>c.source);for(let[c,d]of a){if(o.has(c))continue;let u=l.get(String(d.source))?.pop();if(!u)continue;let[p,y]=u;s.push({kind:Ut.UPDATE,linkId:y.id,type:d.type,lag:d.lag}),o.delete(p),a.delete(c)}for(let[c,d]of o)a.has(c)||s.push({kind:Ut.DELETE,linkId:d.id});for(let[c,d]of a){let u=o.get(c);u&&u.lag!==d.lag&&s.push({kind:Ut.UPDATE,linkId:u.id,lag:d.lag})}for(let[c,d]of a)o.has(c)||s.push({kind:Ut.CREATE,source:d.source,target:e,type:d.type,lag:d.lag});return{operations:s,unresolved:i}}function Rs(t,e){return`${String(t)}::${e}`}function sh(t,e,n){let r=new Map;for(let i of t){if(e.has(i[0]))continue;let a=String(n(i[1])),o=r.get(a)??[];o.push(i),r.set(a,o)}return r}function _i(t){let{sourceActivityId:e,currentLinks:n,desiredSpecs:r}=t,i=[],a=new Map;for(let c of r){let d=t.resolveActivityByCorrelative(c.correlativeId);if(d==null){i.push(c);continue}let u=Rs(d,c.type);a.has(u)||a.set(u,{target:d,type:c.type,lag:c.lag})}let o=new Map;for(let c of n)String(c.source)===String(e)&&o.set(Rs(c.target,c.type),c);let s=[],l=sh(o,a,c=>c.target);for(let[c,d]of a){if(o.has(c))continue;let u=l.get(String(d.target))?.pop();if(!u)continue;let[p,y]=u;s.push({kind:Ut.UPDATE,linkId:y.id,type:d.type,lag:d.lag}),o.delete(p),a.delete(c)}for(let[c,d]of o)a.has(c)||s.push({kind:Ut.DELETE,linkId:d.id});for(let[c,d]of a){let u=o.get(c);u&&u.lag!==d.lag&&s.push({kind:Ut.UPDATE,linkId:u.id,lag:d.lag})}for(let[c,d]of a)o.has(c)||s.push({kind:Ut.CREATE,source:e,target:d.target,type:d.type,lag:d.lag});return{operations:s,unresolved:i}}function Ps(t){let e=Math.sign(t)*Math.round(Math.abs(t));return Object.is(e,-0)?0:e}function ke(t,e){return Math.sign(t)*Math.round(Math.abs(t)*e)}var Yn=class{adapter;reporter;currentCalculationId=0;topoCache=new cs;expandedLinksCache=new Ii;constructor(e,n=Pe){this.adapter=e,this.reporter=n}getCurrentCalculationId(){return this.currentCalculationId}invalidateTopoCache(){this.topoCache.invalidate()}invalidateAllCaches(){this.topoCache.invalidate()}async schedule(e={}){let n=++this.currentCalculationId,r=_f(n,()=>this.currentCalculationId),i={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{lh(this.adapter);let a=Kn("schedule.total"),o=Kn("schedule.expandParentLinks"),s=this.adapter.getAllLinks(),l=this.expandedLinksCache.get(s,this.adapter);cn(o);let c=l;if((await gi(r)).aborted)return{...i,cancelled:!0};let d=Kn("schedule.scoping"),u=this.adapter.getAllIds(),p=BE(e,c,this.adapter,this.expandedLinksCache),y=p.links,f=p.idSet;cn(d);let m=Kn("schedule.topologicalSort"),A=VE(this.topoCache,u,c,f,e.seedIds!==void 0);if(cn(m),A.hasCycles)return cn(a),{...i,cycles:[A.cycleNodes]};if((await gi(r)).aborted)return{...i,cancelled:!0};let g=Kn("schedule.processConstraints"),R=new Map;if(Kf(A.ordered,this.adapter,R),cn(g),(await gi(r)).aborted)return{...i,cancelled:!0};let P=Kn("schedule.asapPass"),N=y.some(w=>w._summaryTargetId!==void 0&&(w.type===q.FINISH_TO_FINISH||w.type===q.START_TO_FINISH)),T=await Qc(A.ordered,y,this.adapter,e,r,R,N),x=N?await Qc(A.ordered,y,this.adapter,e,r,T):T;if(cn(P),(await gi(r)).aborted)return{...i,cancelled:!0};let S=Kn("schedule.alapPass"),k=await zf(A.reversed,y,x,this.adapter,e,r);if(cn(S),(await gi(r)).aborted)return{...i,cancelled:!0};let F=Kn("schedule.diff"),U=[];for(let[w,M]of k){let $=this.adapter.getActivity(w);if(!$)continue;let st=$.startDate.getTime()!==M.startDate.getTime(),at=$.endDate.getTime()!==M.endDate.getTime();(st||at)&&U.push(w)}return cn(F),cn(a),{plans:k,updatedIds:U,cycles:[],cancelled:!1}}catch(a){throw this.reporter.error("[AutoScheduler] Error during scheduling",a),a}finally{lh(this.adapter)}}},UE=!1;function HE(){let t=globalThis.__SCHEDULER_PHASE_LOG__;return typeof t=="boolean"?t:UE}function Kn(t){return{name:t,startedAt:performance.now()}}function lh(t){let e=t;typeof e.clearCalendarCache=="function"&&e.clearCalendarCache()}function cn(t){if(!HE())return;let e=performance.now()-t.startedAt;console.log(`[scheduler] ${t.name} ${e.toFixed(1)}ms`)}function BE(t,e,n,r){if(t.seedIds!==void 0)return bf(t.seedIds,e,r.coneIndex(n),n);let i=t.triggerId;if(i==null)return{idSet:null,links:e};let a=Hf(i,e);return jE(a,e,n)}function jE(t,e,n){let r=new Set(t.activityIds),i=new Set;for(let o of n.getAllActivities()){let s=String(o.id);o.constraintType===_.ALAP&&!r.has(s)&&(i.add(s),r.add(s))}if(i.size===0)return{idSet:r,links:t.links};let a=[...t.links];for(let o of e)(i.has(String(o.source))||i.has(String(o.target)))&&a.push(o);return{idSet:r,links:a}}function VE(t,e,n,r,i=!1){let a=t.get(e,n);if(a.hasCycles&&i)return a;if(a.hasCycles){let s=r?Array.from(r):e;return Bn(s,n)}if(!r)return a;let o=Ef(a.ordered,r);return{ordered:o,reversed:[...o].reverse(),hasCycles:!1,cycleNodes:[]}}var dh=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function dn(t){if(t==null||t==="")throw new Error(`[parseFromBackend] expected a date string, got "${t}"`);if(t.includes("T")||t.endsWith("Z")){let s=new Date(t);if(Number.isNaN(s.getTime()))throw new Error(`[parseFromBackend] invalid ISO date "${t}"`);return s}let e=t.match(dh);if(!e)throw new Error(`[parseFromBackend] unsupported date format "${t}" (expected "YYYY/MM/DD H:MM" or ISO)`);let[,n,r,i,a,o]=e;return new Date(Date.UTC(Number(n),Number(r)-1,Number(i),Number(a),Number(o)))}function ch(t){if(t instanceof Date)return Number.isNaN(t.getTime())?null:t.toISOString().slice(0,10);if(typeof t!="string"||t==="")return null;let e=t.match(dh);if(e){let[,r,i="",a=""]=e;return`${r}-${i.padStart(2,"0")}-${a.padStart(2,"0")}`}if(!t.includes("T")&&!t.endsWith("Z"))return null;let n=new Date(t);return Number.isNaN(n.getTime())?null:n.toISOString().slice(0,10)}function Ei(t,e){let n=ch(t);if(n===null)return!1;let r=ch(e);return r!==null&&r!==n}function Ri(t,e,n,r){if(t.getTime()>n.getTime())return 0;if(e.getTime()<n.getTime()||t.getTime()===e.getTime())return 100;let i=r.calculateDuration(t,n),a=r.calculateDuration(t,e);return a===0?0:i*100/a}var rd=t=>t.type===H.PROJECT,ph=(t,e,n)=>{let r=t.calendarId,i=r!=null?n.calendarReader.getCalendar(String(r)):null;if(!i)return 0;let a=o=>o instanceof Date?o:dn(String(o));return Ri(a(t.startDate),a(t.endDate),e,i)},uh=new WeakMap,WE={patchesHierarchy:!0,ignoresLinks:!0,patchesLinkAppends:!1,patchesLinkRemovals:!1},KE=new Set(["startDate","endDate","calendarId","ponderator","expectedProgress"]);function nd(t,e,n){let r=t.getActivity(e);r&&r.expectedProgress!==n&&t.setActivityField(e,"expectedProgress",n)}function YE(t,e,n){let r={reachable:new Set,descendable:new Set},i=a=>{let o=n.getActivity(a);if(!o)return 0;if(r.reachable.add(String(a)),!rd(o)){let c=ph(o,e,n);return nd(n,a,c),c}r.descendable.add(String(a));let s=0;for(let c of n.getChildren(a)){let d=i(c),u=n.getActivity(c),p=typeof u?.ponderator=="number"?u.ponderator:0;s+=d*p}let l=s/100;return nd(n,a,l),l};for(let a of t)i(a);return r}function GE(t,e,n){if(!rd(t))return ph(t,e,n);let r=0;for(let i of n.getChildren(t.id)){let a=n.getActivity(i),o=typeof a?.ponderator=="number"?a.ponderator:0;r+=(a?.expectedProgress??0)*o}return r/100}function qE(t,e){return t.parentId===null||e.descendable.has(String(t.parentId))}function $E(t,e,n){let r=[],i=[...t];for(let a=i.pop();a!==void 0;){let o=n.getActivity(a),s=o!==null&&qE(o,e),l=s&&o!==null&&rd(o),c=e.reachable.has(a),d=e.descendable.has(a);if(s&&!c&&r.push(a),s?e.reachable.add(a):e.reachable.delete(a),l?e.descendable.add(a):e.descendable.delete(a),s!==c||l!==d)for(let p of n.getChildren(a))i.push(String(p));a=i.pop()}return r}function zE(t,e){let n=[];for(let r=t;r!==null;r=e.getParentId(r))n.push(String(r));return n.reverse()}function JE(t,e,n){let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];)r+=1;if(r===t.length)return 1;if(r===e.length)return-1;let i=n(r===0?null:t[r-1]??null);return i.indexOf(t[r]??"")-i.indexOf(e[r]??"")}function XE(t,e){let n=null,r=i=>i!==null?e.getChildren(i).map(String):(n??=yh(e),n);return[...t].map(i=>zE(i,e)).sort((i,a)=>JE(i,a,r)).map(i=>i[i.length-1]??"")}function yh(t){let e=[];return t.forEachActivity((n,r)=>{n.parentId===null&&e.push(r)}),e}function ZE(t,e,n,r){let i=new Set;for(let a of t){let o=a;for(;o!==null&&e.has(o)&&!i.has(o);)i.add(o),o=r.getParentId(o)}for(let a of XE(i,r)){let o=r.getActivity(a);o&&nd(r,a,GE(o,n,r))}}function QE(t){let e=uh.get(t);if(e)return e;let n={writes:t.openSchedulingWriteLog(KE,WE),nowMs:null,reachability:{reachable:new Set,descendable:new Set}};return uh.set(t,n),n}function Er(t,e){let n=QE(t),r=n.writes.take();if(!r.structural&&n.nowMs===e.getTime()){let a=[...r.touchedIds,...r.reshapedIds,...$E(r.reshapedIds,n.reachability,t)];ZE(a,n.reachability.reachable,e,t),n.writes.take();return}n.reachability=YE(yh(t),e,t),n.nowMs=e.getTime(),n.writes.take()}var tR=t=>t.type===H.PROJECT,eR=t=>Kt(t),nR=(t,e,n,r)=>{let i=eR(t);if(!i)return null;let a=(i.baseCalendarId!=null?n.getBaseCalendar(`${i.baseCalendarId}-base`):null)??(r?n.getBaseCalendar(r):null);return!a||!i.startDate||!i.endDate?null:Ri(i.startDate,i.endDate,e,a)};function id(t,e,n,r=null){let i=[],a=(s,l)=>{let c=n.getActivity(s);c&&c.expectedProgressBaseline!==l&&(n.setActivityField(s,"expectedProgressBaseline",l),i.push(s))},o=s=>{let l=n.getActivity(s);if(!l)return null;if(!tR(l)){let u=nR(l,e,n,r);return a(s,u),u}let c=0;for(let u of n.getChildrenIds(s)){let p=o(u),y=n.getActivity(u),f=typeof y?.ponderator=="number"?y.ponderator:0;c+=(p??0)*f}let d=c/100;return a(s,d),d};for(let s of t)o(s);return i}function ja(t,e,n=null){let r={getChildrenIds:a=>t.getChildren(String(a)).map(o=>String(o)),getActivity:a=>t.getActivity(a),setActivityField:(a,o,s)=>ve(t,a,o,s),getBaseCalendar:a=>t.calendarReader.getCalendar(a)},i=[];return t.forEachActivity((a,o)=>{a.parentId===null&&i.push(o)}),id(i,e,r,n)}function ad(t){let e=!1;return t.forEachActivity(n=>{Kt(n)&&(e=!0)}),e}function fh(t,e,n=null){if(ad(t))return ja(t,e,n);let r=[];return t.forEachActivity((i,a)=>{i.expectedProgressBaseline!=null&&(ve(t,a,"expectedProgressBaseline",null),r.push(a))}),r}var od=Dn.BASELINE;function ks(t){return t===Dn.ACTUAL?Dn.ACTUAL:od}var hh=t=>Math.round(t*100)/100;function rR(t,e){return(e===Dn.BASELINE?t.expectedProgressBaseline:t.expectedProgress)??void 0}function iR(t,e){let n=hh(t),r=hh(e);return n>99.99?le.DONE:r>n?le.OVERDUE:t>0&&n>r?le.ADVANCEMENT:t===0&&e===0?le.WAITING:t>0&&n<r?le.DOING:le.WAITING}function un(t,e){let n=[];return t.forEachActivity((r,i)=>{let a=typeof r.progress=="number"?r.progress:0,o=iR(a,rR(r,e));r.status!==o&&(ve(t,i,E.STATUS,o),n.push(i))}),n}function mh(t){let e=t?.baselinePoints;return!Array.isArray(e)||e.length===0?null:e.find(n=>n.isPrimaryVersion)??null}function gh(t){let e=t?.baselinePoints;return!Array.isArray(e)||e.length===0?null:e.find(n=>n.isProjectVersion)??null}function Ah(t){let e=t?.baselinePoints;return!Array.isArray(e)||e.length===0?null:e.find(n=>n.isVisibleVersion)??null}var Ih=100,aR=t=>Math.round(t*Ih)/Ih;function sd(t,e,n,r){if(r<=0)return null;let i=t.endDate;if(!e||!i)return null;let a=i.getTime()>e.getTime(),o=e.getTime()>i.getTime();if(!a&&!o)return 0;let s=n.calculateDuration({startDate:a?e:i,endDate:a?i:e,task:t}),l=aR(s/r);return l===0?0:a?l:-l}function oR(t,e,n){return sd(t,Ah(t)?.endDate??null,e,n)}function Rr(t,e){let n=[];return t.forEachActivity((r,i)=>{let a=oR(r,t,e);r.baselineVarianceDays!==a&&(r.baselineVarianceDays=a,n.push(String(i)))}),n}function Pr(t,e){let n=[];return t.forEachActivity((r,i)=>{let a=sd(r,gh(r)?.endDate??null,t,e),o=sd(r,mh(r)?.endDate??null,t,e),s=r.projectBaselineVarianceDays!==a,l=r.primaryBaselineVarianceDays!==o;!s&&!l||(s&&(r.projectBaselineVarianceDays=a),l&&(r.primaryBaselineVarianceDays=o),n.push(String(i)))}),n}var ld=60*1e3,bs=1440*ld,sR=60,Sh=3660,lR=bs-ld,cR="-",dR=":";function Ch(t,e,n){if(t.isWorkTime({date:e,unit:n}))return e;let r=uR(e);if(n!==gt.DAY){let a=e.getTime()-r,o=vh(t,r,a);if(o!==null)return new Date(r+o)}let i=t.getWorkHours(e).length>0;for(let a=1;a<=Sh;a++){let o=r-a*bs,s=vh(t,o,bs);if(s!==null){if(n!==gt.DAY){let l=i?Math.min(s,lR):s;return new Date(o+l)}return new Date(o+bs)}}throw new Error(`No working day found within ${Sh} days before ${e.toISOString()}`)}function uR(t){return Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())}function vh(t,e,n){let r=t.getWorkHours(new Date(e)).map(pR).filter(i=>i<=n);return r.length?Math.max(...r):null}function pR(t){let e=t.split(cR)[1]??"",[n="0",r="0"]=e.split(dR);return(Number(n)*sR+Number(r))*ld}var Ls=6e4,Pi=36e5,pn=864e5,cd=60,Dh=4*365*pn,Th=400*pn,yR=200*365*pn,fR=/^(\d{1,2}):00-(\d{1,2}):00$/,kr={BEFORE:"before",AFTER:"after"},Os=class{constructor(e){this.source=e}source;isBuilt=!1;isUsable=!0;firstDayMs=0;lastDayMs=0;starts=new Float64Array(0);ends=new Float64Array(0);prefixMinutes=new Int32Array(1);nextWorkTime(e){return this.resolve(e,kr.AFTER,()=>{let n=this.firstIntervalEndingAfter(e);return n>=this.starts.length?null:Math.max(this.startAt(n),e)})}workingHoursBetween(e,n){if(!this.prepare(e)||!this.prepare(n))return null;let r=this.workingMinutesBefore(n)-this.workingMinutesBefore(e),i=Math.round(Math.abs(r)/cd);return e>n?-i:i}addWorkingHours(e,n){return n===0?e:n<0?this.resolve(e,kr.BEFORE,()=>this.stepBackWorkingHours(e,-n)):this.resolve(e,kr.AFTER,()=>this.addPositiveWorkingHours(e,n))}addWorkingMinutes(e,n){return this.isInsideWorkInterval(e)?n<0?this.resolve(e,kr.BEFORE,()=>this.instantAtWorkingMinute(this.workingMinutesBefore(e)+n)):this.resolve(e,kr.AFTER,()=>this.instantEndingWorkingMinute(this.workingMinutesBefore(e)+n)):null}addPositiveWorkingHours(e,n){let r=this.firstIntervalEndingAfter(e);if(r>=this.starts.length)return null;let i=Math.max(this.startAt(r),e),a=(this.endAt(r)-i)/Pi;if(a>n)return i+n*Pi;let o=n-Math.round(a);if(o<=0)return this.endAt(r);let s=o*cd;return this.instantEndingWorkingMinute(this.prefixAt(r+1)+s)}stepBackWorkingHours(e,n){let r=Math.floor(e/Pi)*Pi,i=this.workingMinutesBefore(r)-n*cd,a=this.instantAtWorkingMinute(i);return a===null?null:e-r+a}instantEndingWorkingMinute(e){let n=this.prefixAt(this.starts.length);if(e>n)return null;let r=gR(this.prefixMinutes,e,1,this.starts.length+1)-1;return this.startAt(r)+(e-this.prefixAt(r))*Ls}instantAtWorkingMinute(e){if(e<0)return null;let n=_h(this.prefixMinutes,e,1,this.starts.length+1)-1;return n>=this.starts.length?null:this.startAt(n)+(e-this.prefixAt(n))*Ls}workingMinutesBefore(e){let n=this.firstIntervalEndingAfter(e);if(n>=this.starts.length)return this.prefixAt(n);let r=Math.max(0,e-this.startAt(n));return this.prefixAt(n)+r/Ls}isInsideWorkInterval(e){if(!this.prepare(e))return!1;let n=this.firstIntervalEndingAfter(e);return n<this.starts.length&&this.startAt(n)<=e}startAt(e){return h(this.starts,e)}endAt(e){return h(this.ends,e)}prefixAt(e){return h(this.prefixMinutes,e)}firstIntervalEndingAfter(e){return _h(this.ends,e,0,this.ends.length)}resolve(e,n,r){if(!this.prepare(e))return null;let i=r();for(;i===null&&this.growHorizon(n);)i=r();return i}prepare(e){if(!this.isUsable||!this.isBuilt&&!this.rebuild(e-Dh,e+Dh))return!1;let r=this.lastDayMs-this.firstDayMs,i=e-Th<this.firstDayMs,a=e+Th>this.lastDayMs;return!i&&!a?!0:this.rebuild(i?Math.min(this.firstDayMs,e-r):this.firstDayMs,a?Math.max(this.lastDayMs,e+r):this.lastDayMs)}growHorizon(e){if(!this.isUsable)return!1;let n=this.lastDayMs-this.firstDayMs;return this.rebuild(e===kr.BEFORE?this.firstDayMs-n:this.firstDayMs,e===kr.AFTER?this.lastDayMs+n:this.lastDayMs)}rebuild(e,n){let r=Math.floor(e/pn)*pn,i=Math.ceil(n/pn)*pn;if(i-r>yR)return!1;let a=this.collectIntervals(r,i);return a===null||a.length===0?(this.isUsable=!1,!1):(this.isBuilt=!0,this.firstDayMs=r,this.lastDayMs=i,this.starts=Float64Array.from(a,o=>o.startMs),this.ends=Float64Array.from(a,o=>o.endMs),this.prefixMinutes=mR(a.map(o=>(o.endMs-o.startMs)/Ls)),!0)}collectIntervals(e,n){let r=[];for(let i=e;i<n;i+=pn){let a=hR(this.source.getWorkHours(new Date(i)),i);if(a===null)return null;r.push(...a)}return r}};function hR(t,e){let n=[],r=e;for(let i of t){let a=fR.exec(i);if(a===null)return null;let o=e+Number(a[1])*Pi,s=e+Number(a[2])*Pi,l=o>=r&&s>o,c=s<=e+pn;if(!l||!c)return null;n.push({startMs:o,endMs:s}),r=s}return n}function mR(t){let e=new Int32Array(t.length+1);return t.forEach((n,r)=>{e[r+1]=h(e,r)+n}),e}function _h(t,e,n,r){let i=n,a=r;for(;i<a;){let o=i+a>>>1;h(t,o)>e?a=o:i=o+1}return i}function gR(t,e,n,r){let i=n,a=r;for(;i<a;){let o=i+a>>>1;h(t,o)>=e?a=o:i=o+1}return i}var Ze={MINUTE:"minute"},Eh=6e4,AR=60,Rh=new WeakMap;function Ph(t){return Rh.get(t)??kh(t)}function kh(t){return{closestWorkTimeMs:(e,n)=>t.getClosestWorkTime({date:new Date(e),direction:n,unit:gt.HOUR}).getTime(),endDateMs:(e,n)=>t.calculateEndDate(new Date(e),n).getTime(),durationHours:(e,n)=>t.calculateDuration(new Date(e),new Date(n))}}function IR(t,e){let n=kh(e);return{closestWorkTimeMs(r,i){return i!==mt.FUTURE||!Va(r)?n.closestWorkTimeMs(r,i):t.nextWorkTime(r)??n.closestWorkTimeMs(r,i)},endDateMs(r,i){return(Number.isInteger(i)&&Va(r)?t.addWorkingHours(r,i):null)??n.endDateMs(r,i)},durationHours(r,i){return(Va(r)&&Va(i)?t.workingHoursBetween(r,i):null)??n.durationHours(r,i)}}}function bh(t,e={}){let n=e.defaultUnit??gt.HOUR,r=new WeakMap;return{getCalendar(i){let a=t.getCalendar(String(i));if(!a)return null;let o=r.get(a);if(o)return o;let s=SR(a,n);return r.set(a,s),s}}}function SR(t,e){let n=e===gt.HOUR?new Os(t):null,r={getClosestWorkTime(i){if(i.direction===mt.PAST)return Ch(t,i.date,i.unit);let a=n?vR(n,i):null;return a||t.getClosestWorkTime({date:i.date,dir:i.direction,unit:i.unit})},calculateEndDate(i,a){let o=e===gt.HOUR&&!Number.isInteger(a),s=i.getUTCSeconds()*1e3+i.getUTCMilliseconds(),l=o&&s!==0&&t.isWorkTime({date:i,unit:Ze.MINUTE}),c=l?new Date(i.getTime()-s):i,u=(n?CR(n,c,a):null)??(o?_R(t,c,a):t.calculateEndDate({start_date:c,duration:a,unit:e}));if(!l)return u;let p=Oh(t,u);return new Date(p.getTime()+s)},calculateDuration(i,a){let o=n?TR(n,i,a):null;return o!==null?o:t.calculateDuration({start_date:i,end_date:a,unit:e})},isWorkTime(i,a){return t.isWorkTime({date:i,unit:a})},getWorkHours(i){return t.getWorkHours(i)}};return n&&Rh.set(r,IR(n,r)),r}function Va(t){return t-Math.trunc(t/Eh)*Eh===0}function Ns(t){return Va(t.getTime())}function Lh(t){return Math.round(Math.abs(t)*AR)}function vR(t,e){if(e.unit!==gt.HOUR||!Ns(e.date))return null;let n=t.nextWorkTime(e.date.getTime());return n===null?null:new Date(n)}function CR(t,e,n){if(!Ns(e))return null;let r=e.getTime(),i=Number.isInteger(n)?t.addWorkingHours(r,n):DR(t,r,n);return i===null?null:new Date(i)}function DR(t,e,n){let r=Lh(n);if(!(r>0))return null;let i=n<0?-r:r;return t.addWorkingMinutes(e,i)}function TR(t,e,n){return!Ns(e)||!Ns(n)?null:t.workingHoursBetween(e.getTime(),n.getTime())}function _R(t,e,n){let r=Lh(n);if(!(r>0&&t.isWorkTime({date:e,unit:Ze.MINUTE})))return t.calculateEndDate({start_date:e,duration:n*60,unit:Ze.MINUTE});let a=e,o=r,s=n<0?-1:1;for(;o>0;){let l=s<0?new Date(a.getTime()-1):a;t.isWorkTime({date:l,unit:Ze.MINUTE})||(a=s<0?t.getClosestWorkTime({date:l,dir:mt.PAST,unit:Ze.MINUTE}):Oh(t,a));let c=ER(t,a,Math.min(o,60),s);a=c.end,o-=c.minutes}return a}function ER(t,e,n,r){let i=t.calculateEndDate({start_date:e,duration:r*n,unit:Ze.MINUTE});if(i.getTime()===e.getTime()+r*n*6e4)return{end:i,minutes:n};let o=0,s=n-1,l=e;for(;o<s;){let c=Math.ceil((o+s)/2),d=t.calculateEndDate({start_date:e,duration:r*c,unit:Ze.MINUTE});d.getTime()===e.getTime()+r*c*6e4?(o=c,l=d):s=c-1}if(o===0)throw new Error("Calendar cannot calculate a working-minute prefix");return{end:l,minutes:o}}function Oh(t,e){if(t.isWorkTime({date:e,unit:Ze.MINUTE}))return e;let n=t.calculateEndDate({start_date:e,duration:1,unit:gt.DAY}),r=new Date(n);r.setUTCHours(0,0,0,0);let i=t.getClosestWorkTime({date:r,dir:mt.FUTURE,unit:Ze.MINUTE}),a=t.getClosestWorkTime({date:e,dir:mt.FUTURE,unit:Ze.MINUTE});return new Date(Math.min(a.getTime(),i.getTime()))}var RR=864e5,Nh="-",PR=":",kR=10;function dd(t){let e=new Map;return n=>{let r=e.get(n);if(r!==void 0)return r;let i=t(n);return e.set(n,i),i}}function Fh(t){let e=new Map;return(n,r)=>{let i=e.get(n);i===void 0&&(i=new Map,e.set(n,i));let a=i.get(r);if(a!==void 0)return a;let o=t(n,r);return i.set(r,o),o}}function bR(t){let e=t[0];if(!e?.includes(Nh))return null;let[n=""]=e.split(Nh),[r=""]=n.split(PR);return Number.parseInt(r,kR)}function wh(t){let e=Ph(t),n=dd(s=>e.closestWorkTimeMs(s,mt.FUTURE)),r=dd(s=>e.closestWorkTimeMs(s,mt.PAST)),i=Fh((s,l)=>e.endDateMs(l,s)),a=new Map,o=s=>{let l=Math.floor(s/RR),c=a.get(l);if(c!==void 0)return c;let d=bR(t.getWorkHours(new Date(s)));return a.set(l,d),d};return{nextWorkMs:n,previousWorkMs:r,addHours:(s,l)=>l===0?e.endDateMs(s,l):i(l,s),durationHours:Fh(e.durationHours),lastWorkingHourBeforeMs:dd(s=>{let l=new Date(s),c=o(s),u=c!==null&&l.getUTCHours()===c?Date.UTC(l.getUTCFullYear(),l.getUTCMonth(),l.getUTCDate()):s;return r(u)})}}var j={ASAP:0,ALAP:1,SNET:2,SNLT:3,FNET:4,FNLT:5,MSO:6,MFO:7,OTHER:8},Rt={FINISH_TO_START:0,START_TO_START:1,FINISH_TO_FINISH:2,START_TO_FINISH:3,OTHER:4},LR=new Map([[_.ASAP,j.ASAP],[_.ALAP,j.ALAP],[_.SNET,j.SNET],[_.SNLT,j.SNLT],[_.FNET,j.FNET],[_.FNLT,j.FNLT],[_.MSO,j.MSO],[_.MFO,j.MFO]]),OR=new Map([[0,Rt.FINISH_TO_START],[1,Rt.START_TO_START],[2,Rt.FINISH_TO_FINISH],[3,Rt.START_TO_FINISH]]),NR=t=>t===_.FNET||t===_.FNLT||t===_.MFO,FR=t=>new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()));function wR(t,e){let n=t.constraintDate;if(!n||!NR(t.constraintType))return n;let r=FR(n);if(n.getTime()!==r.getTime())return n;let i=e.getClosestWorkTime({date:r,dir:mt.FUTURE,task:t});return i.getUTCFullYear()===n.getUTCFullYear()&&i.getUTCMonth()===n.getUTCMonth()&&i.getUTCDate()===n.getUTCDate()?ya(t,e):n}function xR(t){return LR.get(t??_.ASAP)??j.OTHER}function MR(t){return OR.get(Number(t))??Rt.OTHER}function UR(t){let e=new Map;return n=>{let r=String(n.calendarId),i=e.get(r);if(i)return i;let a=t.getCalendar(r);if(!a)throw new Error(`critical path calendar ${r} is not registered`);let o=wh(a);return e.set(r,o),o}}function xh(t,e,n){let r=e.activityCount,i=new Float64Array(r),a=new Float64Array(r),o=new Float64Array(r),s=new Float64Array(r),l=new Uint8Array(r),c=new Float64Array(r),d=new Uint8Array(r),u=new Uint8Array(r),p=[],y=UR(t.calendarReader),f=0;return t.forEachActivity(m=>{let A=f;f+=1,i[A]=m.startDate.getTime(),a[A]=m.endDate.getTime(),o[A]=m.durationHours,s[A]=m.progress,l[A]=xR(m.constraintType),u[A]=m.type===H.MILESTONE?1:0;let g=wR(m,t);g&&(d[A]=1,c[A]=g.getTime()),p.push(y(m))}),{startMs:i,endMs:a,durationHours:o,progress:s,constraint:l,constraintMs:c,hasConstraintDate:d,isMilestone:u,calendarOf:p,...HR(n),projectEndMs:BR(a)}}function HR(t){let e=new Uint8Array(t.length),n=new Float64Array(t.length);return t.forEach((r,i)=>{e[i]=MR(r.type),n[i]=r.lag??0}),{linkType:e,linkLagHours:n}}function BR(t){let e=t.length===0?0:h(t,0);for(let n of t)e=Math.max(e,n);return e}var ht=-1,ki=t=>2*t,yd=t=>2*t+1,br=t=>t>>1,Lr=t=>(t&1)===1;function Bh(t,e){return h(t,e+1)>h(t,e)}function Ce(t,e){return Bh(t.childStart,e)}function jR(t){let e=[],n=[],r=new Map;return t.forEachActivity((i,a)=>{r.set(String(a),e.length),e.push(String(a)),n.push(i.parentId)}),{activityIds:e,parentIds:n,indexOfActivity:r}}function Fs(t,e){let n=new Int32Array(e+1);for(let a of t)a!==ht&&(n[a+1]=h(n,a+1)+1);for(let a=0;a<e;a+=1)n[a+1]=h(n,a+1)+h(n,a);let r=new Int32Array(h(n,e)),i=n.slice(0,e);return t.forEach((a,o)=>{a!==ht&&(r[h(i,a)]=o,i[a]=h(i,a)+1)}),{start:n,list:r}}function jh(t,e,n,r){let i=h(e.start,n);if(t.length!==h(e.start,n+1)-i)return!1;for(let a=0;a<t.length;a+=1){let o=h(e.list,i+a);if(t[a]!==r[o])return!1}return!0}function VR(t,e,n){let r=t.map(o=>[...e(o)]),i=new Int32Array(t.length+1),a=[];return r.forEach((o,s)=>{for(let l of o){let c=n.get(String(l));c!==void 0&&a.push(c)}i[s+1]=a.length}),{recordedIds:r,start:i,list:Int32Array.from(a)}}function Mh(t,e,n,r,i){let a=Fs(n,t.length);return t.every((s,l)=>jh(e(s),a,l,r))?{...a,recordedIds:null}:VR(t,e,i())}function WR(t,e,n){let r=t.activityIds.length,i=new Uint8Array(r),a=[],o=c=>{i[c]=1,Bh(e,c)?a.push(ki(c),yd(c)):a.push(ki(c))},s=[],l=c=>{let d=h(e,c);for(let u=h(e,c+1)-1;u>=d;u-=1)s.push(h(n,u))};for(let c=r-1;c>=0;c-=1)t.parentIds[c]===null&&s.push(c);for(let c=s.pop();c!==void 0;c=s.pop())i[c]!==1&&(o(c),l(c));for(let c=0;c<r;c+=1)i[c]===0&&o(c);return Int32Array.from(a)}function KR(t){return Vh(jR(t))}function Vh(t){let{activityIds:e,parentIds:n,indexOfActivity:r}=t,i=e.length,a=new Int32Array(i),o=new Uint8Array(i);n.forEach((l,c)=>{o[c]=(l??null)===null?1:0,a[c]=l===null?ht:r.get(String(l))??ht});let s=Fs(a,i);return{activityCount:i,activityIds:e,parentIds:n,indexOfActivity:r,parentIndex:a,isTopLevel:o,childStart:s.start,childList:s.list,treeKeys:WR(t,s.start,s.list)}}function Wh(t,e,n){return e!==void 0&&String(e.id)===t.linkIds[n]&&e.source===t.linkSourceIds[n]&&e.target===t.linkTargetIds[n]}function Kh(t,e){let n=Math.min(e.length,t.linkCount),r=0;for(;r<n&&Wh(t,e[r],r);)r+=1;return r}function YR(t,e,n){let r=Math.min(e.length,t.linkCount)-n,i=0;for(;i<r&&Wh(t,e[e.length-1-i],t.linkCount-1-i);)i+=1;return i}function Uh(t,e,n,r,i){let a=new Int32Array(e.length),o=i===null?0:Kh(i,e),s=i===null?0:YR(i,e,o),l=e.length-s,c=(i?.linkCount??0)-e.length;return e.forEach((d,u)=>{let p=u<o||u>=l;a[u]=p&&r!==null?h(r,u<o?u:u+c):t.indexOfActivity.get(String(n(d)))??ht}),a}function Yh(t,e,n,r){let{activityIds:i}=t,a=n.map(u=>String(u.id)),o=Uh(t,n,u=>u.source,r?.linkSource??null,r),s=Uh(t,n,u=>u.target,r?.linkTarget??null,r),l=()=>new Map(a.map((u,p)=>[u,p])),c=Mh(i,u=>e.getIncomingLinkIds(u),s,a,l),d=Mh(i,u=>e.getOutgoingLinkIds(u),o,a,l);return{...t,linkCount:n.length,linkIds:a,linkSourceIds:n.map(u=>u.source),linkTargetIds:n.map(u=>u.target),linkSource:o,linkTarget:s,recordedIncomingIds:c.recordedIds,recordedOutgoingIds:d.recordedIds,incomingStart:c.start,incomingList:c.list,outgoingStart:d.start,outgoingList:d.list}}function GR(t,e){return Yh(KR(t),t,e,null)}var ud=new WeakMap,qR={patchesHierarchy:!0,ignoresLinks:!1,patchesLinkAppends:!0,patchesLinkRemovals:!0};function $R(t,e){if(e.length<t.activityCount)return!1;for(let n=0;n<t.activityCount;n+=1)if(e[n]!==t.activityIds[n])return!1;return!0}function zR(t,e){if(e.length===t.activityCount)return new Map(t.indexOfActivity);let n=new Map(t.indexOfActivity);for(let r=t.activityCount;r<e.length;r+=1)n.set(e[r],r);return n}function JR(t,e){let n=[],r=[];e.forEachActivity((s,l)=>{n.push(String(l)),r.push(s.parentId)});let i=$R(t,n),a=i?zR(t,n):new Map(n.map((s,l)=>[s,l])),o=i?null:Int32Array.from(t.activityIds,s=>a.get(s)??ht);return{activityIds:n,parentIds:r,indexOfActivity:a,nextIndex:o}}function XR(t,e){for(let n=0;n<t.linkCount;n+=1){let r=h(t.linkSource,n)===ht&&e.has(t.linkSourceIds[n]),i=h(t.linkTarget,n)===ht&&e.has(t.linkTargetIds[n]);if(r||i)return!0}return!1}var pd=class{linkIds=[];linkSourceIds=[];linkTargetIds=[];linkSource=[];linkTarget=[];push(e,n,r,i,a){this.linkIds.push(e),this.linkSourceIds.push(n),this.linkTargetIds.push(r),this.linkSource.push(i),this.linkTarget.push(a)}build(){return{linkCount:this.linkIds.length,linkIds:this.linkIds,linkSourceIds:this.linkSourceIds,linkTargetIds:this.linkTargetIds,linkSource:Int32Array.from(this.linkSource),linkTarget:Int32Array.from(this.linkTarget)}}},ws=(t,e)=>t===ht||e===null?t:h(e,t);function ZR(t,e,n){let r=new Set(e),i=new pd;return t.linkIds.forEach((a,o)=>{r.has(a)||i.push(a,t.linkSourceIds[o],t.linkTargetIds[o],ws(h(t.linkSource,o),n),ws(h(t.linkTarget,o),n))}),i}function QR(t,e){return{linkCount:t.linkCount,linkIds:t.linkIds,linkSourceIds:t.linkSourceIds,linkTargetIds:t.linkTargetIds,linkSource:e===null?t.linkSource:t.linkSource.map(n=>ws(n,e)),linkTarget:e===null?t.linkTarget:t.linkTarget.map(n=>ws(n,e))}}function tP(t,e,n,r,i){if(n.removedLinkIds.length===0&&n.appendedLinkIds.length===0&&e.length===t.linkCount)return QR(t,i);let o=ZR(t,n.removedLinkIds,i),s=o.linkIds.length,l=n.appendedLinkIds;if(s+l.length!==e.length)return null;for(let c=0;c<s;c+=1)if(String(e[c]?.id)!==o.linkIds[c])return null;for(let c=s;c<e.length;c+=1){let d=e[c];if(String(d.id)!==l[c-s])return null;o.push(String(d.id),d.source,d.target,r.get(String(d.source))??ht,r.get(String(d.target))??ht)}return o.build()}function eP(t,e,n,r){if(!(t.recordedIncomingIds===null&&t.recordedOutgoingIds===null))return null;let a=r.reshapedIds.size>0?JR(t,e):null,o=a?.indexOfActivity??t.indexOfActivity;if(a!==null&&XR(t,o))return null;let s=tP(t,n,r,o,a?.nextIndex??null);if(s===null)return null;let l=a===null?t:Vh(a),c=Fs(s.linkTarget,l.activityCount),d=Fs(s.linkSource,l.activityCount);return{activityCount:l.activityCount,activityIds:l.activityIds,parentIds:l.parentIds,indexOfActivity:l.indexOfActivity,parentIndex:l.parentIndex,isTopLevel:l.isTopLevel,childStart:l.childStart,childList:l.childList,treeKeys:l.treeKeys,...s,recordedIncomingIds:null,recordedOutgoingIds:null,incomingStart:c.start,incomingList:c.list,outgoingStart:d.start,outgoingList:d.list}}var nP=new Set;function rP(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n]!==e[n])return!1;return!0}function iP(t,e){return e.length===t.linkCount&&Kh(t,e)===e.length}function aP(t,e){let n=0,r=!0;return e.forEachActivity((i,a)=>{r=r&&n<t.activityCount&&t.activityIds[n]===String(a)&&t.parentIds[n]===i.parentId,n+=1}),r&&n===t.activityCount}function Hh(t,e,n,r,i){return n===null?jh(e,r,i,t.linkIds):rP(e,n[i]??[])}function oP(t,e){let n={start:t.incomingStart,list:t.incomingList},r={start:t.outgoingStart,list:t.outgoingList};return t.activityIds.every((i,a)=>Hh(t,e.getIncomingLinkIds(i),t.recordedIncomingIds,n,a)&&Hh(t,e.getOutgoingLinkIds(i),t.recordedOutgoingIds,r,a))}function Gh(t,e){let n=ud.get(t)??null,r=n?.writes??t.openSchedulingWriteLog(nP,qR),i=r.take(),a=n!==null&&!i.structural,o=n?.graph??null,s=a&&o!==null;if(s&&i.reshapedIds.size===0&&i.appendedLinkIds.length===0&&i.removedLinkIds.length===0&&e.length===o.linkCount)return o;let c=s?eP(o,t,e,i):null;if(c!==null)return ud.set(t,{graph:c,writes:r}),c;let d=o!==null&&aP(o,t);if(d&&iP(o,e)&&oP(o,t))return o;let p=d?Yh(o,t,e,o):GR(t,e);return ud.set(t,{graph:p,writes:r}),p}var sP=100,Hs=(t,e)=>{if(!(typeof t=="number"&&Number.isFinite(t)&&Number.isFinite(e)&&e>0))return null;let r=t*e;return Number.isFinite(r)?Object.is(r,-0)?0:r:null},lP=t=>typeof t!="number"||!Number.isFinite(t)?null:Object.is(t,-0)?0:t,cP=(t,e)=>typeof t!="number"||t<0?null:Hs(t,e);function qh(t){let e=cP(t.freeFloatDays,t.hoursPerDay),n=lP(t.residualHours);return{freeSlackHours:e,isCritical:n!==null&&n<=0&&t.sourceIsCritical&&t.targetIsCritical&&t.targetProgress===0}}var fd=t=>t??Number.NaN,xs=t=>Number.isFinite(t)?t:Number.NaN,bi=t=>Number.isNaN(t)?null:t;function dP(t,e){let n=new Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=String(t.activityIds[h(e,r)]);return n}function $h(t,e){let{graph:n,inputs:r,forward:i,backward:a,floats:o}=t,s=i.calculationOrder,l=s.length,c={activityIds:dP(n,s),activityRows:Int32Array.from(s),earlyStartMs:new Float64Array(l),earlyFinishMs:new Float64Array(l),lateStartMs:new Float64Array(l),lateFinishMs:new Float64Array(l),totalSlackHours:new Float64Array(l),freeSlackHours:new Float64Array(l),isCritical:new Uint8Array(l),linkIds:n.linkIds,linkFreeSlackHours:new Float64Array(n.linkCount),linkIsCritical:new Uint8Array(n.linkCount)},d=new Uint8Array(n.activityCount);s.forEach((u,p)=>{let y=h(a.hasLate,u)===1,f=Hs(h(o.totalFloatDays,u),e),m=h(r.progress,u)<sP&&f!==null&&f<=0;m&&(d[u]=1),c.earlyStartMs[p]=xs(h(i.earlyStartMs,u)),c.earlyFinishMs[p]=xs(h(i.earlyFinishMs,u)),c.lateStartMs[p]=y?xs(h(a.lateStartMs,u)):Number.NaN,c.lateFinishMs[p]=y?xs(h(a.lateFinishMs,u)):Number.NaN,c.totalSlackHours[p]=fd(f),c.freeSlackHours[p]=fd(Hs(h(o.freeFloatDays,u),e)),c.isCritical[p]=m?1:0});for(let u=0;u<n.linkCount;u+=1){let p=h(n.linkSource,u),y=h(n.linkTarget,u),f=h(o.hasLinkFreeFloat,u)===1,m=qh({freeFloatDays:f?h(o.linkFreeFloatDays,u):void 0,residualHours:h(o.linkResidualHours,u),hoursPerDay:e,sourceIsCritical:p!==ht&&h(d,p)===1,targetIsCritical:y!==ht&&h(d,y)===1,targetProgress:y===ht?void 0:h(r.progress,y)});c.linkFreeSlackHours[u]=fd(m.freeSlackHours),c.linkIsCritical[u]=m.isCritical?1:0}return c}function Ms(t,e){if(Number.isNaN(t))return null;let n=e.get(t);return n===void 0&&(n=new Date(t),e.set(t,n)),n}function hd(t,e,n){return{criticalPath:{earlyStart:Ms(h(t.earlyStartMs,e),n),earlyFinish:Ms(h(t.earlyFinishMs,e),n),lateStart:Ms(h(t.lateStartMs,e),n),lateFinish:Ms(h(t.lateFinishMs,e),n),totalSlackHours:bi(h(t.totalSlackHours,e))},isCritical:h(t.isCritical,e)===1,freeSlackHours:bi(h(t.freeSlackHours,e))}}function md(t,e){return{freeSlackHours:bi(h(t.linkFreeSlackHours,e)),isCritical:h(t.linkIsCritical,e)===1}}var Us=(t,e)=>Number.isNaN(e)?t===null:t!==null&&t.getTime()===e;function gd(t,e,n){let r=t.criticalPath;return!(r!=null&&Us(r.earlyStart,h(e.earlyStartMs,n))&&Us(r.earlyFinish,h(e.earlyFinishMs,n))&&Us(r.lateStart,h(e.lateStartMs,n))&&Us(r.lateFinish,h(e.lateFinishMs,n))&&Object.is(r.totalSlackHours,bi(h(e.totalSlackHours,n)))&&Object.is(t.isCritical,h(e.isCritical,n)===1)&&Object.is(t.freeSlackHours,bi(h(e.freeSlackHours,n))))}function Ad(t,e,n){return!(Object.is(t.freeSlackHours,bi(h(e.linkFreeSlackHours,n)))&&Object.is(t.isCritical,h(e.linkIsCritical,n)===1))}function Id(t,e,n){t.setLinkField(e,"freeSlackHours",n.freeSlackHours),t.setLinkField(e,"isCritical",n.isCritical)}function Sd(t,e,n,r){let i=String(n.activityIds[r]),a=e[h(n.activityRows,r)];return a!==void 0&&String(a.id)===i?a:t.getActivity(i)}function vd(t,e,n,r){let i=String(n.linkIds[r]),a=e[r];return a!==void 0&&String(a.id)===i?a:t.getLink(i)}function zh(t,e){let n=new Map,r=t.getAllActivities();e.activityIds.forEach((a,o)=>{let s=Sd(t,r,e,o);!s||!gd(s,e,o)||t.setActivityFields(a,hd(e,o,n))});let i=t.getAllLinks();e.linkIds.forEach((a,o)=>{let s=vd(t,i,e,o);!s||!Ad(s,e,o)||Id(t,a,md(e,o))})}var Vt=100;function Zh(t,e){return Ce(t,e)?yd(e):ki(e)}function Bs(t,e){return h(t.incomingStart,e+1)>h(t.incomingStart,e)}function Wa(t,e){return h(t.outgoingStart,e+1)>h(t.outgoingStart,e)}function js(t,e,n){let r=h(e.constraint,n);return Bs(t,n)||r===j.FNLT||r===j.SNET}function Vs(t,e,n){return Wa(t,n)||h(e.constraint,n)===j.FNLT}function Qh(t,e,n){let r=h(t.childStart,e+1);for(let i=h(t.childStart,e);i<r;i+=1)n(Zh(t,h(t.childList,i)))}function Dd(t,e,n,r){let i=n?t.incomingStart:t.outgoingStart,a=n?t.incomingList:t.outgoingList,o=n?t.linkSource:t.linkTarget,s=h(i,e+1);for(let l=h(i,e);l<s;l+=1){let c=h(o,h(a,l));c!==ht&&r(Zh(t,c))}}function uP(t,e){return(n,r)=>{let i=br(n);if(h(e.progress,i)===Vt)return;if(Lr(n)){Qh(t,i,r);return}if(Dd(t,i,!0,r),Ce(t,i))return;let a=h(t.parentIndex,i);a!==ht&&Bs(t,i)&&js(t,e,a)&&r(ki(a))}}function pP(t,e){return(n,r)=>{let i=br(n),a=h(e.progress,i)===Vt,o=Ce(t,i);if(o&&a)return;if(Lr(n)){Qh(t,i,r);return}if(o){Dd(t,i,!1,r);return}if(a&&Wa(t,i))return;Dd(t,i,!1,r);let s=h(t.parentIndex,i);s!==ht&&Vs(t,e,s)&&r(ki(s))}}function Jh(t,e,n){let r=new Int32Array(e),i=new Int32Array(e+1),a=[],o=[];for(let u of t)n(u,p=>{r[u]=h(r,u)+1,i[p+1]=h(i,p+1)+1,a.push(p),o.push(u)});for(let u=0;u<e;u+=1)i[u+1]=h(i,u+1)+h(i,u);let s=new Int32Array(h(i,e)),l=i.slice(0,e);a.forEach((u,p)=>{s[h(l,u)]=h(o,p),l[u]=h(l,u)+1});let c=new Int32Array(t.length),d=0;for(let u of t)h(r,u)===0&&(c[d++]=u);for(let u=0;u<d;u+=1){let p=h(c,u),y=h(i,p+1);for(let f=h(i,p);f<y;f+=1){let m=h(s,f),A=h(r,m)-1;r[m]=A,A===0&&(c[d++]=m)}}return c.subarray(0,d)}var Cd={DONE:1,FNLT:2,SNET:4},Xh=new WeakMap;function yP(t,e){let n=new Uint8Array(e.progress.length);return e.progress.forEach((r,i)=>{let a=r===Vt,o=Ce(t,i),s=h(e.constraint,i),l=o&&s===j.FNLT,c=o&&s===j.SNET;n[i]=(a?Cd.DONE:0)|(l?Cd.FNLT:0)|(c?Cd.SNET:0)}),n}function fP(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n]!==e[n])return!1;return!0}function hP(t,e){let n=2*t.activityCount;return{forward:Jh(t.treeKeys,n,uP(t,e)),backward:Jh(t.treeKeys,n,pP(t,e))}}function tm(t,e){let n=yP(t,e),r=Xh.get(t);if(r&&fP(r.dependencyMask,n))return r;let i={...hP(t,e),dependencyMask:n};return Xh.set(t,i),i}var Ka=4e3,mP=t=>t<=j.FNLT,em=t=>t>=j.SNET&&t<=j.FNLT,Ws=t=>t===j.MSO||t===j.MFO,gP=t=>t===j.SNET||t===j.SNLT||t===j.MSO,AP=t=>t===j.FNET||t===j.FNLT||t===j.MFO;function Td(t,e){let n=h(t.constraint,e),r=gP(n);if(!r&&!AP(n))return null;let i=h(t.constraintMs,e);if(Number.isNaN(i))throw new Error("Invalid date argument for calculateEndDate method");let a=be(t,e),o=h(t.durationHours,e);return r?{startMs:i,finishMs:a.addHours(i,o)}:{startMs:a.addHours(i,-o),finishMs:i}}function be(t,e){let n=t.calendarOf[e];if(n===void 0)throw new RangeError("missing activity calendar");return n}async function nm(t,e,n,r){let i=t.activityCount,a=t.linkCount,{startMs:o,endMs:s,durationHours:l,progress:c,constraint:d}=e,u={hasEarly:new Uint8Array(i),earlyStartMs:new Float64Array(i),earlyFinishMs:new Float64Array(i),earlyFinishIsNumber:new Uint8Array(i),calculationOrder:new Int32Array(i),hasLinkCandidate:new Uint8Array(a),linkCandidateFinishMs:new Float64Array(a),linkCandidateTarget:new Int32Array(a).fill(ht),hasRestriction:new Uint8Array(i),restrictionStartMs:new Float64Array(i),restrictionFinishMs:new Float64Array(i),linkedStartMs:new Float64Array(i),linkedFinishMs:new Float64Array(i)},p=0,y=new Uint8Array(i),f=new Float64Array(i),m=new Float64Array(i),A={startMs:0,finishMs:0},g={isSet:!1,startMs:0,finishMs:0},R=()=>{g.isSet=!1,g.startMs=0,g.finishMs=0},P=(L,K)=>{g.isSet&&!(K>g.finishMs)||(g.isSet=!0,g.startMs=L,g.finishMs=K)},N=(L,K,dt,lt)=>{u.hasEarly[L]=1,u.earlyStartMs[L]=K,u.earlyFinishMs[L]=dt,u.earlyFinishIsNumber[L]=lt?1:0,u.calculationOrder[p]=L,p+=1},T=(L,K,dt)=>{u.hasLinkCandidate[L]=1,u.linkCandidateFinishMs[L]=dt,u.linkCandidateTarget[L]=K},x=(L,K,dt,lt)=>{let X=h(e.linkLagHours,dt),v=h(e.linkType,dt),O=h(u.earlyStartMs,lt),B=h(u.earlyFinishMs,lt);if(v===Rt.START_TO_START){let z=L.addHours(L.nextWorkMs(O),X);X>0&&(z=L.nextWorkMs(z)),A.startMs=z,A.finishMs=L.addHours(z,K);return}if(v===Rt.FINISH_TO_FINISH){let z=L.addHours(L.previousWorkMs(B),X),Q=L.addHours(z,-K);X>0&&(Q=L.previousWorkMs(Q)),A.startMs=Q,A.finishMs=z;return}if(v===Rt.FINISH_TO_START){let z=X===0?L.nextWorkMs(B):B,Q=L.addHours(z,X);A.startMs=Q,A.finishMs=L.addHours(Q,K);return}let V=L.addHours(O,X);A.startMs=L.addHours(V,-K),A.finishMs=V},S=(L,K,dt)=>{let lt=h(t.incomingStart,L+1),X=h(t.incomingStart,L);for(let v=X;v<lt;v+=1){let O=h(t.incomingList,v),B=h(t.linkSource,O);B===ht||h(u.hasEarly,B)===0||(x(K,dt,O,B),T(O,L,A.finishMs),P(A.startMs,A.finishMs))}},k=(L,K,dt)=>{if(!(h(e.hasConstraintDate,L)===1))return;let X=h(d,L),v=h(e.constraintMs,L);if(X===j.SNET){let V=K.addHours(v,dt);g.isSet&&g.finishMs>V||(g.startMs=v,g.finishMs=V),g.isSet=!0;return}if(X!==j.FNLT)return;let O=K.addHours(v,-dt);(!g.isSet||g.finishMs>v)&&(g.startMs=O,g.finishMs=v),g.isSet=!0},F=L=>{if(h(c,L)===Vt){js(t,e,L)&&(y[L]=1,f[L]=h(o,L),m[L]=h(s,L));return}let K=be(e,L),dt=h(l,L);R(),S(L,K,dt),k(L,K,dt),g.isSet&&(y[L]=1,f[L]=g.startMs,m[L]=g.finishMs)},U=L=>{if(h(c,L)===Vt){N(L,h(o,L),h(s,L),!1);return}let K=ht,dt=ht,lt=h(t.childStart,L+1);for(let v=h(t.childStart,L);v<lt;v+=1){let O=h(t.childList,v);if(h(u.hasEarly,O)===0)continue;(K===ht||h(u.earlyStartMs,O)<h(u.earlyStartMs,K))&&(K=O),(dt===ht||h(u.earlyFinishMs,O)>h(u.earlyFinishMs,dt))&&(dt=O)}if(K===ht)return;let X=!js(t,e,L);N(L,h(u.earlyStartMs,K),h(u.earlyFinishMs,dt),X&&h(u.earlyFinishIsNumber,dt)===1)},w=(L,K,dt,lt,X,v)=>{let O=h(e.linkLagHours,lt),B=h(e.linkType,lt),z=B===Rt.FINISH_TO_START||B===Rt.FINISH_TO_FINISH?v:X;if(K||(B===Rt.FINISH_TO_START||B===Rt.START_TO_START?z=L.nextWorkMs(z):B===Rt.FINISH_TO_FINISH&&(z=L.previousWorkMs(z))),B===Rt.FINISH_TO_FINISH||B===Rt.START_TO_FINISH){let _t=L.addHours(z,O),It=L.addHours(_t,-dt);!K&&O>0&&B===Rt.FINISH_TO_FINISH&&(It=L.previousWorkMs(It)),A.startMs=It,A.finishMs=_t;return}let it=L.addHours(z,O);!K&&O>0&&(it=L.nextWorkMs(it)),A.startMs=it,A.finishMs=L.addHours(it,dt)},M=(L,K,dt)=>{let lt=h(e.isMilestone,L)===1,X=h(t.incomingStart,L+1),v=h(t.incomingStart,L);for(let O=v;O<X;O+=1){let B=h(t.incomingList,O),V=h(t.linkSource,B);if(V===ht)continue;let z=h(d,V)===j.ALAP&&!Ce(t,V);if(!(z||h(u.hasEarly,V)===1))continue;let it=z?o:u.earlyStartMs,_t=z?s:u.earlyFinishMs;w(K,lt,dt,B,h(it,V),h(_t,V)),T(B,L,A.finishMs),P(A.startMs,A.finishMs)}},$=(L,K,dt)=>{let lt=h(t.parentIndex,L);if(!(lt!==ht&&h(y,lt)===1))return;let v=h(f,lt);P(v,K.addHours(v,dt))},st=(L,K,dt)=>{let lt=Td(e,L);if(lt===null)throw new RangeError("missing restriction");if(u.hasRestriction[L]=1,u.restrictionStartMs[L]=lt.startMs,u.restrictionFinishMs[L]=lt.finishMs,u.linkedStartMs[L]=g.startMs,u.linkedFinishMs[L]=g.finishMs,em(K)){if(K===j.SNET||K===j.FNET?g.finishMs>lt.finishMs:g.finishMs<lt.finishMs)return;g.startMs=lt.startMs,g.finishMs=lt.finishMs;return}if(dt===0){g.startMs=lt.startMs,g.finishMs=lt.finishMs;return}let X=h(s,L);g.startMs=h(o,L),g.finishMs=K===j.MFO?Math.max(lt.finishMs,X):X},at=L=>{let K=h(c,L),dt=!Bs(t,L)&&K<=Vt;if(K===Vt||dt){N(L,h(o,L),h(s,L),!1);return}let lt=be(e,L),X=h(l,L);R(),M(L,lt,X),$(L,lt,X);let v=h(d,L);(!g.isSet||K>0&&mP(v))&&(g.startMs=h(o,L),g.finishMs=h(s,L));let B=em(v)||Ws(v);B&&st(L,v,K);let V=B&&v===j.MFO&&K!==0;N(L,g.startMs,g.finishMs,V)},Ct=0;for(let L of n){if(Ct+=1,Ct>=Ka&&(Ct=0,await wt(),!r()))return null;let K=br(L);h(t.isTopLevel,K)!==1&&(Lr(L)?U(K):Ce(t,K)?F(K):at(K))}return{...u,calculationOrder:u.calculationOrder.subarray(0,p)}}var _d=t=>t===j.ASAP||t===j.ALAP||t===j.SNET||t===j.FNET,rm=t=>t===j.ASAP||t===j.ALAP;async function im(t,e,n,r,i){let a=t.activityCount,{startMs:o,endMs:s,durationHours:l,progress:c,constraint:d,projectEndMs:u}=e,p={hasLate:new Uint8Array(a),lateStartMs:new Float64Array(a),lateFinishMs:new Float64Array(a),lateStartIsMoment:new Uint8Array(a),lateFinishIsMoment:new Uint8Array(a),hasMinimumFromLinks:new Uint8Array(a),minimumFromLinksFinishMs:new Float64Array(a)},y=new Uint8Array(a),f=new Float64Array(a),m={startMs:0,finishMs:0},A=(v,O,B,V)=>{p.hasLate[v]=1,p.lateStartMs[v]=O,p.lateFinishMs[v]=B,p.lateStartIsMoment[v]=V?1:0,p.lateFinishIsMoment[v]=V?1:0},g=(v,O)=>{m.startMs=v,m.finishMs=O},R=(v,O,B,V,z)=>{(v?z<B:V<O)?g(V,z):g(O,B)},P=(v,O)=>h(e.hasConstraintDate,v)===1?h(e.constraintMs,v):O,N=v=>Ce(t,v)?h(c,v)!==Vt:h(c,v)<=0,T=v=>!Ce(t,v)&&h(c,v)>0&&h(c,v)<Vt,x=(v,O,B,V,z,Q,it=h(p.lateStartMs,Q))=>{let _t=h(e.linkLagHours,z),It=h(e.linkType,z),ue=h(l,v),Ge=V===j.ALAP,bt;It===Rt.FINISH_TO_START?bt=Ge?S(Q,!0):it:It===Rt.START_TO_START?bt=it:It===Rt.FINISH_TO_FINISH?bt=h(p.lateFinishMs,Q):bt=Ge?S(Q,!1):h(p.lateFinishMs,Q);let Xr=It===Rt.FINISH_TO_START||It===Rt.FINISH_TO_FINISH,Zr=Xr?-ue:-_t,Qr=Xr?-_t:ue;if(B&&_t===0){let sr=O.addHours(bt,Zr);g(sr,O.addHours(sr,Qr));return}if(It===Rt.FINISH_TO_START){if(_t===0){let dD=O.lastWorkingHourBeforeMs(bt),kp=O.lastWorkingHourBeforeMs(O.addHours(dD,Qr));g(O.addHours(kp,Zr),kp);return}let sr=B?bt:O.lastWorkingHourBeforeMs(bt),Cn=O.addHours(sr,Qr),_o=O.addHours(Cn,Zr);g(_o,B?Cn:O.lastWorkingHourBeforeMs(Cn));return}if(It===Rt.FINISH_TO_FINISH){let sr=_t>0?O.lastWorkingHourBeforeMs(bt):bt,Cn=O.addHours(sr,Qr);g(O.addHours(Cn,Zr),Cn);return}if(It===Rt.START_TO_START){let Cn=_t!==0&&_t<0&&!B?O.nextWorkMs(bt):bt,_o=O.addHours(Cn,Zr);g(_o,O.addHours(_o,Qr));return}let Pp=O.addHours(bt,Zr);g(Pp,O.addHours(Pp,Qr))};function S(v,O){if(h(n.hasEarly,v)===0)throw new TypeError(`critical path successor ${t.activityIds[v]} has no early dates`);return O?h(n.earlyStartMs,v):h(n.earlyFinishMs,v)}let k=(v,O)=>{let B=h(o,v),V=h(s,v),z=h(c,v),Q=h(l,v),it=h(d,v),_t=h(e.hasConstraintDate,v)===1,It=h(e.constraintMs,v);if(z>=Vt){g(B,V);return}if(z===0){let ue=it===j.SNLT||it===j.MSO,Ge=it===j.FNLT||it===j.MFO;if(_d(it))g(O.addHours(u,-Q),u);else if(ue&&_t){let bt=O.addHours(It,Q);it===j.SNLT&&bt>u?g(O.addHours(u,-Q),u):g(It,bt)}else if(Ge&&_t){let bt=it===j.FNLT?Math.min(It,u):It;g(O.addHours(bt,-Q),bt)}else g(B,V);return}if(_d(it)){g(B,Math.max(V,u));return}if(it===j.MSO){g(B,V);return}g(B,Math.max(Math.min(u,P(v,u)),V))},F=v=>{if(!Vs(t,e,v))return;if(y[v]=1,h(c,v)===Vt){f[v]=h(s,v);return}let O=be(e,v),B=!1,V=0,z=h(t.outgoingStart,v+1);for(let it=h(t.outgoingStart,v);it<z;it+=1){let _t=h(t.outgoingList,it),It=h(t.linkTarget,_t);It!==ht&&h(p.hasLate,It)===1&&N(It)&&(x(v,O,!1,j.ASAP,_t,It),(!B||m.finishMs<V)&&(B=!0,V=m.finishMs))}if(h(d,v)===j.FNLT&&h(e.hasConstraintDate,v)===1){let it=h(e.constraintMs,v);(!B||it<V)&&(V=it),B=!0}f[v]=B?V:u},U=v=>{if(h(c,v)===Vt){A(v,h(o,v),h(s,v),!1);return}let O=ht,B=ht,V=h(t.childStart,v+1);for(let z=h(t.childStart,v);z<V;z+=1){let Q=h(t.childList,z);if(h(p.hasLate,Q)===0)continue;(O===ht||h(p.lateStartMs,Q)<h(p.lateStartMs,O))&&(O=Q),(B===ht||h(p.lateFinishMs,Q)>h(p.lateFinishMs,B))&&(B=Q)}O!==ht&&(A(v,h(p.lateStartMs,O),h(p.lateFinishMs,B),!1),!Vs(t,e,v)&&(p.lateStartIsMoment[v]=h(p.lateStartIsMoment,O),p.lateFinishIsMoment[v]=h(p.lateFinishIsMoment,B)))},w=(v,O,B)=>{let V=h(d,v),z=h(l,v),Q=0,it=0;if(_d(V))h(c,v)>0?(it=Math.min(u,B),Q=h(o,v)):(it=B,Q=O.addHours(it,-z));else if(V===j.SNLT){let It=O.addHours(B,-z);Q=Math.min(P(v,It),It),it=O.addHours(Q,z)}else V===j.FNLT?(Q=Math.min(P(v,B),B),it=O.addHours(Q,z)):V===j.MSO?(Q=h(e.constraintMs,v),it=O.addHours(Q,z)):V===j.MFO&&(it=h(e.constraintMs,v),Q=O.addHours(it,-z));let _t=O.addHours(u,-z);u<it?g(_t,u):g(Q,it)},M={hasCandidates:!1,minimumFinish:0,pickedStart:0,pickedFinish:0},$=v=>{if(!M.hasCandidates){M.hasCandidates=!0,M.minimumFinish=m.finishMs,M.pickedStart=m.startMs,M.pickedFinish=m.finishMs;return}m.finishMs<M.minimumFinish&&(M.minimumFinish=m.finishMs),(v?m.finishMs<M.pickedFinish:m.startMs<M.pickedStart)&&(M.pickedStart=m.startMs,M.pickedFinish=m.finishMs)},st=(v,O,B,V,z,Q)=>!T(Q)||(x(v,O,B,V,z,Q),h(n.hasEarly,v)===1&&m.finishMs<h(n.earlyFinishMs,v))?!1:(x(v,O,B,V,z,Q,be(e,Q).addHours(h(p.lateFinishMs,Q),-h(l,Q))),!0),at=(v,O,B)=>{let V=rm(B),z=h(e.isMilestone,v)===1;M.hasCandidates=!1;let Q=h(t.outgoingStart,v+1),it=h(t.outgoingStart,v);for(let _t=it;_t<Q;_t+=1){let It=h(t.outgoingList,_t),ue=h(t.linkTarget,It);if(ue!==ht&&h(p.hasLate,ue)===1){if(N(ue))x(v,O,z,B,It,ue);else if(!st(v,O,z,B,It,ue))continue;$(V)}}},Ct=(v,O,B)=>{let V=Math.min(B,u),z=h(s,v);return O===j.ASAP?Math.max(V,z):O===j.FNET||O===j.FNLT?Math.max(V,Math.min(V,P(v,V))):O===j.ALAP?Math.min(V,z):Math.max(V,z)},L=(v,O)=>{if(!(O===j.SNLT||O===j.FNLT))return;let V=h(n.hasRestriction,v)===1?{startMs:h(n.restrictionStartMs,v),finishMs:h(n.restrictionFinishMs,v)}:Td(e,v);V!==null&&!(m.finishMs<V.finishMs)&&g(V.startMs,V.finishMs)},K=(v,O,B,V)=>{let z=h(d,v),Q=rm(z),it=h(l,v);at(v,O,z);let _t=O.addHours(u,-it),It=M.hasCandidates;It?R(Q,M.pickedStart,M.pickedFinish,_t,u):g(_t,u),B&&R(Q,m.startMs,m.finishMs,O.addHours(V,-it),V);let ue=It?M.minimumFinish:m.finishMs,Ge=h(c,v),bt=Ge>0&&Ge<Vt;It&&bt&&g(h(o,v),Ct(v,z,m.finishMs)),L(v,z),p.hasMinimumFromLinks[v]=1,p.minimumFromLinksFinishMs[v]=ue,A(v,m.startMs,m.finishMs,!1)},dt=v=>{let O=be(e,v),B=h(t.parentIndex,v),V=B!==ht&&h(y,B)===1,z=V?h(f,B):0,Q=h(d,v),it=h(c,v),_t=h(o,v),It=h(s,v);if(!Wa(t,v)){if(V&&Wa(t,B)){w(v,O,z),A(v,m.startMs,m.finishMs,!1);return}k(v,O),A(v,m.startMs,m.finishMs,it>=Vt);return}if(it===Vt){A(v,_t,It,!1);return}if(lt(v)){k(v,O),V?A(v,_t,Math.min(m.finishMs,z),!1):A(v,m.startMs,m.finishMs,!1);return}if(it>0&&it<Vt&&Ws(Q)){let bt=Q===j.MSO?It:Math.max(Math.min(P(v,u),u),It);A(v,_t,bt,!1);return}let Ge=h(e.hasConstraintDate,v)===1;if(Ws(Q)&&Ge){let bt=h(e.constraintMs,v),Xr=h(l,v);Q===j.MSO?A(v,bt,O.addHours(bt,Xr),!1):A(v,O.addHours(bt,-Xr),bt,!1);return}K(v,O,V,z)};function lt(v){let O=h(t.outgoingStart,v+1);for(let B=h(t.outgoingStart,v);B<O;B+=1){let V=h(t.linkTarget,h(t.outgoingList,B));if(!(V!==ht&&!Ce(t,V)&&h(c,V)>=Vt))return!1}return!0}let X=0;for(let v of r){if(X+=1,X>=Ka&&(X=0,await wt(),!i()))return null;let O=br(v);h(t.isTopLevel,O)!==1&&(Lr(v)?U(O):Ce(t,O)?F(O):dt(O))}return p}var IP=(t,e,n)=>n>=e?t.durationHours(e,n):-t.durationHours(n,e);function SP(t){let{graph:e,inputs:n,forward:r}=t,i=new Float64Array(e.linkCount).fill(Number.NaN);for(let a=0;a<e.linkCount;a+=1){if(h(r.hasLinkCandidate,a)===0)continue;let o=h(r.linkCandidateTarget,a),s=h(r.linkCandidateFinishMs,a),l=h(r.earlyFinishMs,o);if(!(h(r.hasEarly,o)===1&&h(r.earlyFinishIsNumber,o)===0&&Number.isFinite(s)&&Number.isFinite(l)))continue;let d=IP(be(n,o),s,l);i[a]=Object.is(d,-0)?0:d}return i}var Gn=(t,e,n)=>t.durationHours(n,e),Ys=t=>Math.min(Gn(t.calendar,t.lateStart,t.earlyStart),Gn(t.calendar,t.lateFinish,t.earlyFinish)),Ya=t=>Gn(t.calendar,t.lateFinish,t.earlyFinish);function Rd(t,e,n,r){let{backward:i}=t;return h(i.hasMinimumFromLinks,e)===0?r:Math.min(r,Gn(n.calendar,h(i.minimumFromLinksFinishMs,e),n.earlyFinish))}function vP(t,e,n,r){let{forward:i}=t;return r?Gn(n.calendar,h(i.restrictionStartMs,e),h(i.linkedStartMs,e)):Gn(n.calendar,h(i.restrictionFinishMs,e),h(i.linkedFinishMs,e))}function Ed(t,e,n,r){return h(t.forward.hasRestriction,e)===0?Ys(n):Math.min(vP(t,e,n,r),Ys(n))}function CP(t,e,n){let{inputs:r}=t,i=h(r.hasConstraintDate,e)===1?h(r.constraintMs,e):0;return Rd(t,e,n,Math.min(Ya(n),Gn(n.calendar,i,n.earlyFinish)))}function DP(t,e,n,r){let i=h(t.inputs.constraint,e);switch(i){case j.ASAP:case j.SNET:case j.FNET:return r?Ys(n):Rd(t,e,n,Ya(n));case j.ALAP:return r?Math.min(Ys(n),Gn(n.calendar,n.lateFinish,h(t.inputs.endMs,e))):Ya(n);case j.SNLT:return r?Ed(t,e,n,!0):Rd(t,e,n,Ya(n));case j.FNLT:return r?Ed(t,e,n,!1):CP(t,e,n);case j.MSO:case j.MFO:return r?Ed(t,e,n,i===j.MSO):Ya(n);default:return Number.NaN}}function TP(t,e){let{inputs:n,forward:r,backward:i,hoursPerDay:a}=t,o=h(n.progress,e);if(o===Vt)return 0;let s=h(i.hasLate,e)===1,l={calendar:be(n,e),earlyStart:h(r.earlyStartMs,e),earlyFinish:h(r.earlyFinishMs,e),lateStart:s?h(i.lateStartMs,e):0,lateFinish:s?h(i.lateFinishMs,e):0};return DP(t,e,l,o===0)/a}function _P(t,e,n){let{inputs:r,forward:i,backward:a}=t;if(h(r.constraint,e)===j.ALAP){let l=h(n?a.lateStartIsMoment:a.lateFinishIsMoment,e);return h(a.hasLate,e)===1&&l===0?h(n?a.lateStartMs:a.lateFinishMs,e):Number.NaN}return h(i.hasEarly,e)===1&&(n||h(i.earlyFinishIsNumber,e)===0)?h(n?i.earlyStartMs:i.earlyFinishMs,e):Number.NaN}function EP(t,e,n){let{inputs:r,forward:i,backward:a}=t;if(h(r.constraint,e)===j.ALAP){let s=h(n?a.lateFinishIsMoment:a.lateStartIsMoment,e);return h(a.hasLate,e)===1&&s===0?h(n?a.lateFinishMs:a.lateStartMs,e):Number.NaN}return n?h(i.earlyFinishIsNumber,e)===0?h(i.earlyFinishMs,e):Number.NaN:h(i.earlyStartMs,e)}function RP(t,e,n,r){let{graph:i,inputs:a,hoursPerDay:o}=t,s=be(a,e);r.hasUnstartedSuccessor=!1,r.minimumDays=Number.POSITIVE_INFINITY;let l=h(i.outgoingStart,e+1),c=h(i.outgoingStart,e);for(let d=c;d<l;d+=1){let u=h(i.outgoingList,d),p=h(i.linkTarget,u);if(p===ht)continue;let y=h(a.linkType,u),f=y===Rt.FINISH_TO_START||y===Rt.START_TO_START,m=y===Rt.FINISH_TO_START||y===Rt.FINISH_TO_FINISH,A=_P(t,p,f),g=EP(t,e,m),P=Number.isFinite(A)&&Number.isFinite(g)?s.durationHours(g,A):Number.NaN,N=h(a.linkLagHours,u),T=P/o-N/o,x=Math.max(0,T);n.hasLinkFreeFloat[u]=1,n.linkFreeFloatDays[u]=x;let S=h(a.progress,p);S>=Vt||S>0&&T<0||(r.hasUnstartedSuccessor=!0,r.minimumDays=Math.min(r.minimumDays,x))}}function Ks(t,e,n,r,i){return i&&Number.isFinite(n)&&Number.isFinite(r)?t.durationHours(n,r)/e:Number.NaN}function PP(t,e,n){let{inputs:r,forward:i,backward:a,hoursPerDay:o}=t,s=be(r,e);if(h(r.progress,e)===Vt)return 0;let l=h(r.constraint,e),c=h(r.hasConstraintDate,e)===1,d=h(r.constraintMs,e),u=h(i.earlyStartMs,e),p=h(i.earlyFinishMs,e),y=h(i.earlyFinishIsNumber,e)===0;if(l===j.MSO||l===j.MFO){let R=l===j.MSO,P=c?d:t.referenceNowMs();return Math.max(0,Ks(s,o,R?u:p,P,R||y))}let m=l===j.ALAP?Ks(s,o,h(a.lateFinishMs,e),r.projectEndMs,h(a.hasLate,e)===1&&h(a.lateFinishIsMoment,e)===0):Ks(s,o,p,r.projectEndMs,y);if((l===j.SNLT||l===j.FNLT)&&!n.hasUnstartedSuccessor){let R=l===j.FNLT,P=Ks(s,o,R?p:u,d,c&&(!R||y));return Math.max(0,Math.min(m,P))}let g=n.hasUnstartedSuccessor?Math.min(n.minimumDays,m):m;return Math.max(0,g)}async function am(t,e){let{graph:n,forward:r}=t,i=n.activityCount,a={totalFloatDays:new Float64Array(i).fill(Number.NaN),freeFloatDays:new Float64Array(i).fill(Number.NaN),hasLinkFreeFloat:new Uint8Array(n.linkCount),linkFreeFloatDays:new Float64Array(n.linkCount).fill(Number.NaN),linkResidualHours:SP(t)},o={hasUnstartedSuccessor:!1,minimumDays:Number.POSITIVE_INFINITY},s=0;for(let l of r.calculationOrder){if(s+=1,s>=Ka&&(s=0,await wt(),!e()))return null;a.totalFloatDays[l]=TP(t,l),RP(t,l,a,o),a.freeFloatDays[l]=PP(t,l,o)}return a}async function om(t,e,n,r){let i=t.getAllLinks(),a=Gh(t,i),o=xh(t,a,i),s=tm(a,o);if(await wt(),!n())return null;let l=await nm(a,o,s.forward,n);if(!l)return null;let c=await im(a,o,l,s.backward,n);if(!c)return null;let d=await am({graph:a,inputs:o,forward:l,backward:c,hoursPerDay:e,referenceNowMs:()=>r?new Date(r).getTime():Date.now()},n);return d?{graph:a,inputs:o,links:i,forward:l,backward:c,floats:d}:null}async function Pd(t,e,n=()=>!0,r){if(!n())return null;let i=await om(t,e,n,r);return!i||!n()?null:$h(i,e)}async function sm(t,e,n=()=>!0,r){let i=await Pd(t,e,n,r);return!i||!n()?!1:(zh(t,i),!0)}function Li(t){let e=[],n=[];t.forEachActivity((i,a)=>{i.parentId===null&&e.push(String(a))});let r=i=>{let a=t.getActivity(String(i));if(!a)return 0;let o=[...t.getChildren(String(i))],s;if(o.length===0){let l=Kt(a),c=l&&Number(l.cost)||0;s=(Number(a.progress)||0)/100*c}else{let l=0;for(let c of o)l+=r(String(c));s=l}return t.setActivityField(String(i),b.REAL_COST,s),n.push(String(i)),s};for(let i of e)r(i);return n}var lm=new Set;var cm=new Set(["activity-outdent","activity-indent"]);var kd=["name","description","startDate","endDate","durationHours","constraintType","constraintDate","autoScheduling","calendarId","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","p6"],dm=new Set(kd),kP=new Set(["name","description","customId","subcontractId","responsableIds","tagIds"]);function Gs(t){return t.every(e=>Object.keys(e.fields).every(n=>kP.has(n)))}var bd=["parentId","type","correlativeId"],bP=new Set(bd);function qs(t){return dm.has(t)||bP.has(t)}function $s(t){return dm.has(t)}function zs(t,e){let n="type"in e?e.type:t.type,r="durationHours"in e?e.durationHours:t.durationHours;return n===H.MILESTONE&&Number(r)!==0}function Js(t){let e=t.progress;return typeof e=="number"?{...t,autoScheduling:ye(e)}:t}function Xs(t,e){return e.flatMap(n=>[n,...t.getChildren(n)])}function Zs(t,{adapter:e,customIdTracker:n}){for(let r of t){let i=e.getActivity(r)?.customId??null;i===null||!e.hasChildren(r)||(n.releaseCustomId(i),e.setActivityFields(r,{customId:null}))}}var Ga=new Set([E.TEXT,E.DESCRIPTION,E.COST,E.USED_COST,E.CUSTOM_ID,E.RESPONSABLES,E.SUBCONTRACT_ID,E.TAGS]),LP=new Set([I.ACTIVITY_CLIPBOARD_CLEAR,I.ACTIVITY_CLIPBOARD_IMPORT,I.ACTIVITY_COPY,I.CELL_CLIPBOARD_CLEAR,I.CELL_COPY,I.SELECTION_TOGGLE,I.SELECTION_REPLACE,I.VISIBILITY_SET,I.FILTER_SET,I.SORT_SET,I.VIEW_ATTRIBUTES_SET,I.GROUP_SET,I.WBS_DEPTH_SET,I.SIR_SYNC,I.ACTIVITY_LOOKAHEAD_SYNC,I.PERSISTENCE_ACKNOWLEDGE,I.BASELINE_APPLY,I.PONDERATOR_CRITERION_SET,I.STATUS_CRITERIA_SET]),OP=new Set([I.ACTIVITY_CLIPBOARD_CLEAR,I.ACTIVITY_CLIPBOARD_IMPORT,I.ACTIVITY_COPY,I.CELL_CLIPBOARD_CLEAR,I.CELL_COPY,I.SELECTION_TOGGLE,I.SELECTION_REPLACE,I.VISIBILITY_SET,I.FILTER_SET,I.SORT_SET,I.VIEW_ATTRIBUTES_SET,I.GROUP_SET,I.WBS_DEPTH_SET]),um=new Set(Object.values(ti));function ym(t){return!OP.has(t.kind)}var NP=new Set;function FP(t){return t.kind===I.INLINE_EDIT||t.kind===I.CELL_PASTE_COPIED?Ga.has(t.column):t.kind===I.BULK_EDIT?t.edits.every(e=>Ga.has(e.column)):t.kind===I.ACTIVITY_FIELDS_RESTORE?Gs(t.activities):!1}function Ld(t){return t.kind===I.INLINE_EDIT||t.kind===I.CELL_PASTE_COPIED?um.has(t.column):t.kind===I.BULK_EDIT&&t.edits.every(e=>um.has(e.column))}function Od(t,e){return!(LP.has(t.kind)||e.has(t.kind)||FP(t))}function qa(t){return t.kind===I.ACTIVITY_LOOKAHEAD_SYNC?t.persistedProgress!==void 0:Od(t,NP)}function Or(t){return Ld(t)?!1:t.kind===I.ACTIVITY_LOOKAHEAD_SYNC?t.persistedProgress!==void 0:Od(t,lm)}function fm(t){return Ld(t)?!1:Od(t,cm)}function Nd(t){return t.kind===I.ACTIVITY_SET_PROGRESS?!0:t.kind===I.INLINE_EDIT?t.column===E.PROGRESS:t.kind===I.BULK_EDIT?t.edits.some(e=>e.column===E.PROGRESS):t.kind===I.CELL_PASTE_COPIED?t.column===E.PROGRESS:!1}function wP(t){return fm(t)&&Nd(t)}var pm=new Set([E.PROGRESS,E.HH_WORK_TIME,E.DURATION,E.COST,E.USED_COST,E.REAL_COST]);function xP(t){return t.kind===I.ACTIVITY_SET_PROGRESS?!0:t.kind===I.INLINE_EDIT||t.kind===I.CELL_PASTE_COPIED?pm.has(t.column):t.kind===I.BULK_EDIT?t.edits.some(e=>pm.has(e.column)):!1}var Zt={AUTOSCHEDULE:"autoschedule",PARENT_BOUNDS:"parent-bounds",PARENT_PROGRESS:"parent-progress",REAL_WORK:"real-work",EXPECTED_PROGRESS:"expected-progress",REAL_COST:"real-cost",BASELINE_VARIANCE:"baseline-variance",CRITICAL_PATH:"critical-path"};function hm(t,e,n){let r=new Set;if(e.ran&&r.add(Zt.AUTOSCHEDULE),r.add(Zt.PARENT_BOUNDS),Ld(t))return r;xP(t)&&r.add(Zt.PARENT_PROGRESS),Nd(t)&&r.add(Zt.REAL_WORK);let i=!n.skipAutoSchedule;return i&&fm(t)&&r.add(Zt.EXPECTED_PROGRESS),i&&wP(t)&&r.add(Zt.REAL_COST),qa(t)&&r.add(Zt.BASELINE_VARIANCE),i&&Or(t)&&!n.skipCriticalPath&&r.add(Zt.CRITICAL_PATH),r}function At(t,e=!0){return e&&t?.dataDate!=null}var Fd=(t,e)=>new Date(Math.min(t.getTime(),e.getTime())),MP=(t,e)=>t?new Date(Math.max(t.getTime(),e.getTime())):e,UP=6e4;function Qs(t,e){let n=new Date(t.getTime()-UP),r=e.isWorkTime(n,gt.HOUR)?new Date(t):e.getClosestWorkTime({direction:mt.PAST,date:n,unit:gt.HOUR}),i=new Date(r);i.setUTCHours(0,0,0,0);let a=e.getClosestWorkTime({direction:mt.FUTURE,date:i,unit:gt.HOUR});return{start:Fd(a,r),finish:r}}function $a(t,e,n){let r=t.actualStart?Fd(t.actualStart,n.start):void 0;return{...t,...r===void 0?{}:{actualStart:r},...t.actualFinish?{actualFinish:MP(r??e,Fd(t.actualFinish,n.finish))}:{}}}var tl=(t,e)=>{if(!(t instanceof Date)||!Number.isFinite(t.getTime()))throw new TypeError(`Outbuild P6 ${e} must be a valid Date`);return new Date(t.getTime())};function HP(t){if(t.type==="project")return;if(!Number.isFinite(t.durationHours)||t.durationHours<0)throw new TypeError("Outbuild P6 durationHours must be a non-negative finite number");let e=tl(t.startDate,"plannedStart"),n=tl(t.endDate,"plannedFinish"),r=t.durationHours;return{activityType:"task",actualStart:null,actualFinish:null,plannedStart:e,plannedFinish:n,remainingDurationHours:r,executionStatus:"not_started",expectedFinish:null,suspendDate:null,resumeDate:null,secondaryConstraintType:null,secondaryConstraintDate:null,percentCompleteType:xt.PHYSICAL,physicalPercentComplete:0,actualDurationHours:0,atCompletionDurationHours:r,durationPercentComplete:0,unitsPercentComplete:0,schedulePercentComplete:0,remainingFloatHours:null,remainingEarlyStart:null,remainingEarlyFinish:null,remainingLateStart:null,remainingLateFinish:null,earlyStart:null,earlyFinish:null,lateStart:null,lateFinish:null,floatPath:null,floatPathOrder:null,longestPath:!1,originalDurationHours:r,actualLaborUnits:0,remainingLaborUnits:0,actualNonlaborUnits:0,remainingNonlaborUnits:0,primaryBaselineStart:null,primaryBaselineFinish:null,freeFloatHours:null}}function Oi(t){let e=HP(t);if(e!==void 0)return{...e,...el(t,t.durationHours)}}var mm=100,gm=0;function el(t,e){if(t.progress===0)return{executionStatus:tt.NOT_STARTED,actualStart:null,actualFinish:null,remainingDurationHours:e,physicalPercentComplete:gm,actualDurationHours:0,atCompletionDurationHours:e,durationPercentComplete:0};let n=tl(t.startDate,"actualStart");if(gr(t.progress)){let r=e>0;return{executionStatus:tt.COMPLETED,actualStart:n,actualFinish:tl(t.endDate,"actualFinish"),remainingDurationHours:0,physicalPercentComplete:mm,actualDurationHours:e,atCompletionDurationHours:e,durationPercentComplete:r?mm:gm}}return{executionStatus:tt.IN_PROGRESS,actualStart:n,actualFinish:null,remainingDurationHours:e,physicalPercentComplete:t.progress,actualDurationHours:0,atCompletionDurationHours:e,durationPercentComplete:0}}function wd(t){return t.p6===void 0?gr(t.progress):t.p6.executionStatus===tt.COMPLETED}function xd(t){return t.executionStatus===tt.NOT_STARTED&&t.actualStart===null}function Am(t,e){if(!(t.progress!==0)||!xd(e))return e;let r=el(t,e.originalDurationHours),i=r.executionStatus===tt.IN_PROGRESS&&e.remainingDurationHours!==null;return{...e,...r,...i?{remainingDurationHours:e.remainingDurationHours}:{}}}function Im(t,e){let n=e??void 0,r=BP(t,n);return()=>jP(t,n,r)}function BP(t,e){return e===void 0||At(e.settings,t.isDataDateEnabled())?new Map:new Map(t.getAllActivities().filter(n=>n.p6!==void 0&&Object.hasOwn(e.activities,n.id)).map(n=>[n.id,ct(n)]))}function jP(t,e,n){if(!(e===void 0||At(e.settings,t.isDataDateEnabled())))for(let r of t.getAllActivities()){if(!Object.hasOwn(e.activities,r.id)){let o=Oi(r);o!==void 0&&t.setActivityField(r.id,"p6",o);continue}let i=n.get(r.id);if(i?.p6===void 0||r.p6===void 0)continue;let a=vm(i,r);Object.keys(a).length!==0&&t.setActivityField(r.id,"p6",{...r.p6,...a})}}function Sm(t){if(t.dataDateSettings()===null||At(t.dataDateSettings(),t.isDataDateEnabled()))return;let e=t.peekWriteCapture();if(e!==null)for(let[n,r]of e.before){let i=t.getActivity(n);if(i?.p6===void 0||r.p6===void 0)continue;let a=vm(r,i,VP(t,i));Object.keys(a).length!==0&&t.setActivityField(i.id,"p6",{...i.p6,...a})}}function VP(t,e){let n=t.currentTime(),r=t.calendarReader.getCalendar(e.calendarId);return n===null||r===null?null:Qs(n,r)}function vm(t,e,n=null){let r=t.durationHours!==e.durationHours;return{...t.startDate.getTime()!==e.startDate.getTime()?{plannedStart:new Date(e.startDate)}:{},...t.endDate.getTime()!==e.endDate.getTime()?{plannedFinish:new Date(e.endDate)}:{},...r?{originalDurationHours:e.durationHours}:{},...r||t.progress!==e.progress?WP(KP(t,e,r),e.p6.actualStart,n):{}}}function WP(t,e,n){return n===null?t:$a(t,e,n)}function KP(t,e,n){let r=e.p6;if(r.remainingDurationHours!==t.p6.remainingDurationHours)return{};let a=t.progress!==e.progress,o=a&&e.progress===0;if(xd(r)||o){let l=n?e.durationHours:r.originalDurationHours;return el(e,l)}return!(r.actualStart!==null)||!a?{}:YP(r,e)}function YP(t,e){let n=t.percentCompleteType===xt.PHYSICAL;if(!gr(e.progress))return{...t.actualFinish===null?{}:{executionStatus:tt.IN_PROGRESS,actualFinish:null},...n?{physicalPercentComplete:e.progress}:{}};let r=t.actualStart!==null&&e.endDate.getTime()>=t.actualStart.getTime();return t.actualFinish!==null||!r?{}:{executionStatus:tt.COMPLETED,actualFinish:new Date(e.endDate),remainingDurationHours:0,physicalPercentComplete:100}}var Et={INSERT:"insert",REMOVE:"remove",LINK_ADD:"link-add",LINK_REMOVE:"link-remove",LINK_FIELD:"link-field"},nl=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(e,n){let r=this._journal;r&&(r.before.has(e)||r.before.set(e,ln(n)),r.dirty.add(e))}noteInsert(e){this._journal?.ops.push({kind:Et.INSERT,activityId:e})}noteRemove(e,n){this._journal?.ops.push({kind:Et.REMOVE,activityId:e,before:ln(n)})}noteLinkAdd(e){this._journal?.ops.push({kind:Et.LINK_ADD,linkId:e})}noteLinkRemove(e,n){this._journal?.ops.push({kind:Et.LINK_REMOVE,linkId:e,before:Cm(n)})}noteCorrelativeBefore(e,n){let r=this._journal;if(!r||r.correlativeBefore.has(e))return;let i=r.before.get(e)?.correlativeId;r.correlativeBefore.set(e,typeof i=="number"?i:n)}noteScheduledBefore(e,n){let r=this._journal;if(!r)return;let i=ln(n);r.scheduledBefore.has(e)||r.scheduledBefore.set(e,i),r.before.has(e)||r.before.set(e,i),r.dirty.add(e)}noteLinkField(e,n){let r=this._journal;!r||r.linkFieldCaptured.has(e)||(r.linkFieldCaptured.add(e),r.ops.push({kind:Et.LINK_FIELD,linkId:e,before:Cm(n)}))}noteProgressFallback(e,n){let r=this._journal;!r||r.progressFallbackBefore.has(e)||r.progressFallbackBefore.set(e,n)}};function Cm(t){return{...t}}function Nr(t){return(t.pendingRequestIds?.length??0)>0}var GP="sir-apply";function Md(t,e,n){let r=[];for(let i of n){let a=t.get(i);if(!a)continue;let o=a.pendingRequestIds??[];if(Nr({pendingRequestIds:o})&&e.getActivity(i)==null)for(let s of o)r.push({kind:ba.SIR_AUTO_REJECT,activityId:i,sirId:s,reason:La.ACTIVITY_DELETED})}return r}function Dm(t,e,n,r){if(r===GP)return[];let i=[];for(let a of n){let o=t.get(a);if(!o||!Nr(o)||wd(o))continue;let s=e.getActivity(a);if(!(s==null||!wd(s)))for(let l of o.pendingRequestIds??[])i.push({kind:ba.SIR_AUTO_REJECT,activityId:a,sirId:l,reason:La.ACTIVITY_COMPLETED})}return i}function Mt(t){let e={id:String(t.id),source:String(t.source),target:String(t.target),type:t.type,lag:Number(t.lag),freeSlackHours:typeof t.freeSlackHours=="number"&&Number.isFinite(t.freeSlackHours)?t.freeSlackHours:null,isCritical:t.isCritical===!0};return t.proplannerId!=null&&(e.proplannerId=Number(t.proplannerId)),t.ganttId!=null&&(e.ganttId=Number(t.ganttId)),t.sectorId!=null&&(e.sectorId=Number(t.sectorId)),e}var Qt={BEFORE_DIFF:"before-diff",AFTER_DIFF:"after-diff"};async function et(t,e){let n=XP(t,e),r=new Map(e.beforeSnap),i=t.peekWriteCapture(),a=JP(e.deferredCorrelatives,i,r);if(i){let y=QP(i);ZP(t,i,y,r,n)}let o=e.sirDetection,s=o===Qt.BEFORE_DIFF?Md(r,t,n):[],l=zP(e.correlativeShifts,a,n),c=await os(t,r,n,l),d=[...o===Qt.AFTER_DIFF?Md(r,t,n):s,...Dm(r,t,n,"eventSource"in e.source?e.source.eventSource:void 0)],u=e.warnings??[],p=$P(e.links??[],i?qP(t,i):[]);return{source:e.source,activities:c,links:p,calendars:[],trackingEvents:e.trackingEvents??[],...d.length>0?{effects:d}:{},...u.length>0?{warnings:u}:{}}}function qP(t,e){let n=[];for(let r of e.ops){if(r.kind!==Et.LINK_FIELD)continue;let i=t.getLink(r.linkId);if(!i)continue;let a={};for(let o of["freeSlackHours","isCritical"])Object.is(r.before[o],i[o])||(a[o]={before:r.before[o],after:i[o]});Object.keys(a).length!==0&&n.push({id:r.linkId,kind:W.UPDATED,fields:a,after:Mt(i)})}return n}function $P(t,e){let n=[],r=new Map;for(let i of t){let a=r.get(i.id);if(a===void 0){r.set(i.id,n.length),n.push(i);continue}let o=n[a];if((o.kind===W.UPDATED||o.kind===W.CREATED)&&i.kind===W.UPDATED){n[a]={...o,fields:{...o.fields,...i.fields},after:i.after};continue}n[a]=i}for(let i of e){let a=r.get(i.id);if(a===void 0){r.set(i.id,n.length),n.push(i);continue}let o=n[a];if(o.kind===W.DELETED)continue;let s=o.kind===W.CREATED?Object.fromEntries(Object.entries(i.fields??{}).map(([l,c])=>[l,{before:void 0,after:c.after}])):i.fields;n[a]={...o,fields:{...o.fields,...s},after:i.after}}return n}function zP(t,e,n){if(!(t!==void 0&&t.length>0)&&e.size===0)return;let i=new Map;for(let a of t??[])i.set(a.activityId,a.before),n.add(a.activityId);for(let[a,o]of e)i.set(a,o),n.add(a);return i}function JP(t,e,n){let r=new Map;for(let[i,a]of t??[]){if(n.has(i))continue;let o=e?.before.get(i);o?n.set(i,{...o,correlativeId:a}):r.set(i,a)}return r}function XP(t,e){let n=new Set;for(let r of e.touchedIds)n.add(r);for(let r of e.scheduledIds)n.add(r);if(e.includeAllIds)for(let r of t.getAllIds())n.add(r);return n}function ZP(t,e,n,r,i){for(let a of e.dirty){if(n.has(a)||r.has(a))continue;let o=e.before.get(a),s=t.getActivity(a);!o||!s||Tf(o,s)&&(r.set(a,o),i.add(a))}}function QP(t){return new Set(t.ops.filter(e=>e.kind===Et.INSERT).map(e=>e.activityId))}function rl(t,e,n,r=new Map){if(!t||t==="0")return;let i=n.getChildren(t);if(i.length===0)return;let a=new Map,o=new Set,s=0;for(let u of i){let p=ek(String(u),e,n,r);a.set(String(u),p.magnitude),s+=p.magnitude,p.hasActiveBaseline&&o.add(String(u))}let l=s?100/s:0,d=e!==Tt.COST&&o.size>0?100/o.size:0;for(let u of i){let p=n.getActivity(u);if(!p)continue;let y=tk(String(u),p,a,o,s,l,d);y!==null&&n.setActivityField(u,E.PONDERATOR,y)}}function tk(t,e,n,r,i,a,o){return e.type===H.PROJECT||Kt(e)?i?a*(n.get(t)??0):r.has(t)?o:0:!Array.isArray(e.baselinePoints)||e.baselinePoints.length===0?0:null}function ek(t,e,n,r){let i=[{id:t,expanded:!1}];for(;i.length>0;){let{id:a,expanded:o}=i.pop();if(r.has(a))continue;let s=n.getActivity(a),l=Kt(s);if(s?.type!==H.PROJECT){r.set(a,{magnitude:l&&s?.type!==H.MILESTONE?nk(l,e):0,hasActiveBaseline:l!==null});continue}let c=n.getChildren(a);if(!o){i.push({id:a,expanded:!0}),c.forEach(u=>{i.push({id:String(u),expanded:!1})});continue}let d={magnitude:0,hasActiveBaseline:l!==null};for(let u of c){let p=r.get(String(u));d.magnitude+=p.magnitude,d.hasActiveBaseline||=p.hasActiveBaseline}r.set(a,d)}return r.get(t)}function nk(t,e){return e===Tt.COST?Ud(t.cost):e===Tt.WORK_HOURS?Ud(t.workHours):Ud(t.durationDays)}function Ud(t){let e=typeof t=="string"?parseFloat(t):t;return typeof e=="number"&&Number.isFinite(e)?e:0}function Tm(t,e){let n=t.peekWriteCapture();if(!n)return;let r=new Set,i=new Map,a=new Map;for(let s of n.ops)s.kind===Et.REMOVE&&a.set(s.activityId,s.before.parentId);let o=(s,l)=>{let c=s;for(;c!==null&&!G(c);){let d=i.get(c);if(d===!0||d===l)break;i.set(c,l),c=a.has(c)?a.get(c)??null:t.getParentId(c)}};for(let[s,l]of n.before){let c=t.getActivity(s);if(!(c&&l.parentId!==c.parentId)||!c)continue;let u=Kt(l)!==null||Hd(s,t,r);o(l.parentId,u),o(c.parentId,!1)}for(let s of n.ops)if(s.kind===Et.REMOVE)Kt(s.before)&&o(s.before.parentId,!0);else if(s.kind===Et.INSERT){let l=t.getActivity(s.activityId);l&&Hd(l.id,t,r)&&o(l.parentId,!1)}for(let[s,l]of i)(l||Hd(s,t,r))&&rl(s,e,t)}function Hd(t,e,n){let r=[],i=[t];for(;i.length>0;){let a=i.pop();if(a===void 0||n.has(a))continue;let o=e.getActivity(a);if(o&&Kt(o))return!0;r.push(a),i.push(...e.getChildren(a))}for(let a of r)n.add(a);return!1}function _m(t){let e=t.peekWriteCapture();if(!e)return null;let n=new Set(e.dirty),r=i=>{n.add(String(i.source)),n.add(String(i.target))};for(let[i,a]of e.before)n.add(i),a.parentId!==null&&n.add(String(a.parentId));for(let i of e.ops)switch(i.kind){case Et.INSERT:n.add(i.activityId);break;case Et.REMOVE:i.before.parentId!==null&&n.add(String(i.before.parentId));break;case Et.LINK_ADD:{let a=t.getLink(i.linkId);a&&r(a);break}case Et.LINK_REMOVE:case Et.LINK_FIELD:{r(i.before);let a=t.getLink(i.linkId);a&&r(a);break}}return[...n]}var Pt={ROOTS:"roots"};async function ot(t,e){e.action.kind===I.ACTIVITY_LOOKAHEAD_CONVERT||Tm(t.adapter,t.sector.activityCreter??Tt.DURATION);let r=dk(t.adapter),i=rk(t.adapter,e),a=sk(t.adapter,i),o=ck(i,r,Rm(t.adapter));a&&o.add(Zt.AUTOSCHEDULE),o.has(Zt.AUTOSCHEDULE)&&await gk(t.adapter,i);let s=a?await lk(t):o.has(Zt.AUTOSCHEDULE)?await yk(t,i.autoscheduleFrom,i.preventSummaryTargetPullback,i.action.kind===I.CALENDAR_RECONCILE):mk();return await Ak(t.adapter,i,s.scheduledIds,o,r,t.sector.activityCreter??Tt.DURATION),await Sk(t,o,e.now,e.options.at),Sm(t.adapter),s}function rk(t,e){let n=ik(t,e.autoscheduleFrom);return n===e.autoscheduleFrom?e:{...e,autoscheduleFrom:n}}function ik(t,e){if(e===Pt.ROOTS)return Pt.ROOTS;let n=ak(t);if(n.size===0)return e;if(e!==null&&n.add(String(e)),n.size!==1)return Pt.ROOTS;let[r]=n;return r===void 0||!t.activityExists(r)||t.hasChildren(r)?Pt.ROOTS:r}function ak(t){let e=new Set,n=t.peekWriteCapture();if(!n)return e;for(let r of n.ops){if(r.kind===Et.LINK_REMOVE){e.add(String(r.before.target));continue}if(r.kind===Et.LINK_ADD){let i=t.getLink(r.linkId);i&&e.add(String(i.target));continue}if(r.kind===Et.LINK_FIELD){e.add(String(r.before.target));let i=t.getLink(r.linkId);i&&e.add(String(i.target))}}return e}async function Em(t,e,n){if(t.activityId!==void 0&&!n.adapter.activityExists(t.activityId))return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};if(Rm(n.adapter)&&!ok(n.adapter))return{ok:!1,reason:D.MANUAL_SCHEDULING_ACTIVE};let r=await yt(n.adapter,new Set(n.adapter.getAllIds()));n.scheduler.invalidateAllCaches();let i=t.activityId===void 0?n.adapter.getRootIds():[t.activityId],{scheduledIds:a}=await ot({adapter:n.adapter,scheduler:n.scheduler,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:t.activityId??Pt.ROOTS,recomputeParentsFrom:i,now:n.now,options:e});return{ok:!0,changes:await et(n.adapter,{source:t,beforeSnap:r,touchedIds:i,scheduledIds:a,hoursPerDay:n.sector.hoursPerDay})}}function Rm(t){return At(t.dataDateSettings(),t.isDataDateEnabled())}function ok(t){return t.dataDateSettings()?.scheduleAutomaticallyOnDateChange===!0}function sk(t,e){let n=t.dataDateSettings();return At(n,t.isDataDateEnabled())&&n?.scheduleAutomaticallyOnDateChange===!0&&e.autoscheduleFrom!==null&&e.options.skipAutoSchedule!==!0}async function lk(t){if(t.runAutomaticP6Schedule===void 0)throw new Error("Automatic P6 scheduling is not configured");return{scheduledIds:[...await t.runAutomaticP6Schedule()],warnings:[]}}function ck(t,e,n){let r=t.autoscheduleFrom!==null,i=!t.options.skipAutoSchedule&&r&&!n,a=n?{...t.options,skipCriticalPath:!0}:t.options,o=new Set(hm(t.action,{requested:r,ran:i},a));return(t.recomputeParentProgress||e.affectedParents.size>0)&&o.add(Zt.PARENT_PROGRESS),o}function dk(t){let e=new Set,n=new Set,r=t.peekWriteCapture();if(!r)return{affectedParents:e,dirtySeeds:n};let i=a=>{if(a===null||G(a))return;let o=String(a);e.add(o);let s=t.getChildren(o)[0];s!==void 0&&n.add(s)};return uk(t,r.ops,i),pk(t,r.before,n,i),{affectedParents:e,dirtySeeds:n}}function uk(t,e,n){for(let r of e)if(r.kind===Et.INSERT){let i=t.getActivity(r.activityId);i&&n(i.parentId)}else r.kind===Et.REMOVE&&n(r.before.parentId)}function pk(t,e,n,r){for(let[i,a]of e){let o=t.getActivity(i);if(!o)continue;let s=!Object.is(a.progress,o.progress),l=!Object.is(a.ponderator,o.ponderator),c=!Object.is(a.parentId,o.parentId);(s||l)&&(r(o.parentId),n.add(String(i))),c&&(r(a.parentId),r(o.parentId),n.add(String(i)))}}async function yk(t,e,n=!1,r=!1){let i=r||!t.adapter.isScheduleSettled()?null:_m(t.adapter),a=e===Pt.ROOTS||e===null?[]:[e],o=i!==null?{seedIds:[...i,...a]}:e===Pt.ROOTS?{}:{triggerId:e};n&&(o.preventSummaryTargetPullback=!0);let s=await t.scheduler.schedule(o);s.cycles.length===0&&!s.cancelled&&t.adapter.markScheduleSettled();let l=hk(t.adapter,s.updatedIds),c=fk(t.adapter,s);return Ua(t.adapter,s),{...l,warnings:c}}function fk(t,e){let n=[];for(let r of e.plans.values()){let i=r.earliestSchedulingStart;if(!i||r.startDate>=i)continue;let a=t.getActivity(r.activityId);!a?.constraintType||!a.constraintDate||n.push({kind:Dr.VIOLATION,activityId:a.id,constraintType:a.constraintType,constraintDate:a.constraintDate,projectedDate:i,messageKey:Dr.VIOLATION})}return n}function hk(t,e){let n=[];for(let r of e){let i=String(r);n.push(i);let a=t.getActivity(i);a&&t.noteScheduledBefore(i,a)}return{scheduledIds:n,warnings:[]}}function mk(){return{scheduledIds:[],warnings:[]}}async function gk(t,e){let n=e.collectDirty?e.collectDirty([]):Gc(e.recomputeParentsFrom,[]);n.size!==0&&await on(t,n,!1)}async function Ak(t,e,n,r,i,a){r.has(Zt.PARENT_PROGRESS)&&Ik(t,i.affectedParents);let o=e.collectDirty?e.collectDirty(n):Gc(e.recomputeParentsFrom,n);for(let s of i.dirtySeeds)o.add(s);await on(t,o,r.has(Zt.PARENT_PROGRESS),{recomputeRealWork:r.has(Zt.REAL_WORK),criterion:a,progressMode:"freeze-when-no-contribution"})}function Ik(t,e){for(let n of e){if(t.hasChildren(n))continue;let r=t.getProgressFallback(n);r!==null&&(t.setActivityField(n,"progress",r),t.setProgressFallback(n,null))}}async function Sk(t,e,n,r){e.has(Zt.EXPECTED_PROGRESS)&&n!==null&&(ad(t.adapter)&&ja(t.adapter,n,t.defaultBaseCalendarId??null),Er(t.adapter,n),un(t.adapter,t.sector.statusCriteria)),e.has(Zt.REAL_COST)&&Li(t.adapter),e.has(Zt.BASELINE_VARIANCE)&&(Rr(t.adapter,t.sector.hoursPerDay),Pr(t.adapter,t.sector.hoursPerDay)),e.has(Zt.CRITICAL_PATH)&&await sm(t.adapter,t.sector.hoursPerDay,void 0,r)}var vk=new Set([E.CONSTRAINT_TYPE,E.CONSTRAINT_DATE]),Ck=new Set([_.MSO,_.MFO]);function Ni(t){return vk.has(t)}function il(t){return t===E.CONSTRAINT_DATE}function al(t,e,n,r){let i=n.getActivity(t);if(!i)return!1;let a=i.constraintType;if(!a||Nn.has(a)||Ck.has(a))return!1;let o=Bd(i.startDate),s=Bd(n.getLastStartDate(t));if(!s||!o||o.getTime()!==s.getTime())return!1;let l=Dk(e,a,String(i.calendarId??""),r),c=Bd(i.constraintDate);return Tk(c,l)?!1:(n.setActivityField(t,"constraintDate",l),!0)}function Dk(t,e,n,r){if(t===null)return null;let i=r.getCalendar(n);return i?$e(t,i,e):t}function Bd(t){if(t instanceof Date)return t;if(typeof t=="string"||typeof t=="number"){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null}function Tk(t,e){return t===null&&e===null?!0:t===null||e===null?!1:t.getTime()===e.getTime()}async function ol(t,{postMutationArgs:e,revertTargets:n,revert:r}){let{scheduledIds:i}=await ot(t,Pm(e)),a=!1;for(let{activityId:o,priorConstraintDate:s}of n){let l=r(o,s);a=a||l}if(a){let o=await ot(t,Pm(e));i=Ek(i,o.scheduledIds)}return Or(e.action)&&await ot(t,_k(e)),{scheduledIds:i}}function Pm(t){return{...t,options:{...t.options,skipCriticalPath:!0}}}function _k(t){return{action:t.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:t.options}}function Ek(t,e){let n=new Set(t);for(let r of e)n.add(r);return[...n]}function Fi(t,e,n){let r=n?t.getIncomingLinkIds(e):t.getOutgoingLinkIds(e),i=[];for(let a of r){let o=t.getLink(a);o&&i.push(o)}return i}function qn(t,e,n){let r=[];for(let{op:i,finalLinkId:a,rejected:o}of t){if(o!==null)continue;if(i.kind===Ut.CREATE){if(!a)continue;let u=n.getLink(a);if(!u)continue;let p=e.get(a);if(p){let y={};String(p.source)!==String(u.source)&&(y.source={before:String(p.source),after:String(u.source)}),String(p.target)!==String(u.target)&&(y.target={before:String(p.target),after:String(u.target)}),p.type!==u.type&&(y.type={before:p.type,after:u.type}),Number(p.lag)!==Number(u.lag)&&(y.lag={before:Number(p.lag),after:Number(u.lag)}),Object.keys(y).length>0&&r.push({id:String(a),kind:W.UPDATED,fields:y,after:Mt(u)});continue}r.push({id:String(a),kind:W.CREATED,fields:{source:{before:void 0,after:String(u.source)},target:{before:void 0,after:String(u.target)},type:{before:void 0,after:u.type},lag:{before:void 0,after:Number(u.lag)}},after:Mt(u)});continue}if(i.kind===Ut.DELETE){if(n.getLink(i.linkId))continue;let u=e.get(i.linkId);r.push({id:String(i.linkId),kind:W.DELETED,fields:u?{source:{before:String(u.source),after:void 0},target:{before:String(u.target),after:void 0},type:{before:u.type,after:void 0},lag:{before:Number(u.lag),after:void 0}}:void 0,after:null});continue}let s=e.get(i.linkId),l=n.getLink(i.linkId);if(!l)continue;let c={};s&&String(s.source)!==String(l.source)&&(c.source={before:String(s.source),after:String(l.source)}),s&&String(s.target)!==String(l.target)&&(c.target={before:String(s.target),after:String(l.target)}),s&&s.type!==l.type&&(c.type={before:s.type,after:l.type}),s&&Number(s.lag)!==Number(l.lag)&&(c.lag={before:Number(s.lag),after:Number(l.lag)}),!(s!==void 0&&Object.keys(c).length===0)&&r.push({id:String(i.linkId),kind:W.UPDATED,fields:c,after:Mt(l)})}return r}function wi(t,e){let n=new Map;if(!t.getActivity(e))return n;for(let r of t.getIncomingLinkIds(e)){let i=t.getLink(r);i&&n.set(String(i.id),Number(i.lag))}return n}function xi(t,e,n){let r=[];if(!e.getActivity(n))return r;for(let i of e.getIncomingLinkIds(n)){let a=e.getLink(i);if(!a)continue;let o=t.get(String(a.id));o===void 0||o===Number(a.lag)||r.push({id:String(a.id),kind:W.UPDATED,fields:{lag:{before:o,after:Number(a.lag)}},after:Mt(a)})}return r}function km(t,e){typeof t=="string"&&t.length>0&&e.releaseCustomId(t)}function Mi(t,e){return gf.has(e)?t.p6?.[e]:Reflect.get(t,e)}var Se={MOVE:"move",RESIZE_START:"resize-start",RESIZE_END:"resize-end"},Rk=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),jd=(t,e)=>t===null?e:Math.min(t,e),Vd=(t,e)=>t===null?e:Math.max(t,e);function Lm(t,e,n){let r=[...new Set(e.kind===Se.MOVE?e.activityIds.map(String):[String(e.activityId)])];if(r.length===0)throw new Error("[ScheduleCore] date gesture has no participants");let i=Pk(t,e,r);return kk(t,r,i),{getDates(a,o){if(n(),!Number.isFinite(o))throw new Error("[ScheduleCore] invalid date gesture edge");let s=i.get(String(a));if(!s)return null;let l=Lk(s,o),c=Ok(s,o);if(l===null||c===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(a)}`);return{startTimeMs:l,endTimeMs:c}}}}function Pk(t,e,n){let r=new Map,i=e.kind===Se.MOVE?String(e.anchorActivityId):null,a=i===null?null:bm(t,i);if(i!==null&&!n.includes(i))throw new Error("[ScheduleCore] move anchor is not a participant");for(let o of n){let s=bm(t,o);if(e.kind===Se.MOVE){let l=a.startDate.getTime();r.set(o,{constantStart:null,variableStartOffset:s.startDate.getTime()-l,constantEnd:null,variableEndOffset:s.endDate.getTime()-l})}else e.kind===Se.RESIZE_START?r.set(o,{constantStart:null,variableStartOffset:0,constantEnd:s.endDate.getTime(),variableEndOffset:null}):r.set(o,{constantStart:s.startDate.getTime(),variableStartOffset:null,constantEnd:null,variableEndOffset:0})}return r}function kk(t,e,n){let r=Sa(t,new Set(e));for(let i of r){let a=Rk();for(let o of t.getChildren(i)){let s=n.get(o);if(s){bk(a,s);continue}let l=t.getActivity(o);if(!l)throw new Error(`[ScheduleCore] missing child ${o} while previewing parent ${i}`);a.constantStart=jd(a.constantStart,l.startDate.getTime()),a.constantEnd=Vd(a.constantEnd,l.endDate.getTime())}n.set(i,a)}}function bm(t,e){let n=t.getActivity(e);if(!n)throw new Error(`[ScheduleCore] missing date gesture activity ${e}`);if(t.hasChildren(e))throw new Error(`[ScheduleCore] summary activity ${e} cannot be dragged directly`);return n}function bk(t,e){e.constantStart!==null&&(t.constantStart=jd(t.constantStart,e.constantStart)),e.variableStartOffset!==null&&(t.variableStartOffset=jd(t.variableStartOffset,e.variableStartOffset)),e.constantEnd!==null&&(t.constantEnd=Vd(t.constantEnd,e.constantEnd)),e.variableEndOffset!==null&&(t.variableEndOffset=Vd(t.variableEndOffset,e.variableEndOffset))}function Lk(t,e){if(t.variableStartOffset===null)return t.constantStart;let n=e+t.variableStartOffset;return t.constantStart===null?n:Math.min(t.constantStart,n)}function Ok(t,e){if(t.variableEndOffset===null)return t.constantEnd;let n=e+t.variableEndOffset;return t.constantEnd===null?n:Math.max(t.constantEnd,n)}function Fr(t,e,n,r=!0){return t!==void 0&&At(e,r)?n===Se.RESIZE_END?t.executionStatus===tt.COMPLETED?Dt("data_date_activity_completed","data_date_edit_rejected"):pt():t.actualStart===null?pt():Dt("data_date_actual_start_locked","data_date_edit_rejected"):pt()}var Nk=new Set([He.HAS_PROGRESS,He.COMPLETED]),Fk={[E.START_DATE]:Se.MOVE,[E.END_DATE]:Se.RESIZE_END};function sl(t,e,n,r,i=!0){let a=e.p6;if(!(a!==void 0&&At(n,i))||!t.allowed&&!Nk.has(t.reason))return t;if(r===E.PROGRESS&&a.percentCompleteType===xt.UNITS)return Dt(He.DATA_DATE_UNITS_PERCENT_READ_ONLY,Xo.DATA_DATE_UNITS_PERCENT_READ_ONLY);let s=Fk[r];return s===void 0?pt():Fr(a,n,s,i)}var wk=100,xk=2;function Nm(t,e,n,r,i){let{progress:a}=r,o=r.writesProgress?{activityPercentComplete:a}:{};if(e.executionStatus===tt.COMPLETED)return a>=100?n:Ui(n,{actualFinish:null,...o},ie.UNCOMPLETE);if(e.executionStatus===tt.IN_PROGRESS)return a<100?Ui(n,o):Om(n,{actualFinish:t.endDate,...o},o,r,i);if(a===0)return n;let s={actualStart:t.startDate};return a<100?Ui(n,{...s,...o},ie.START_ON_PROGRESS):Om(n,{...s,actualFinish:t.endDate,...o},{...s,...o},r,i)}function Om(t,e,n,r,i){return r.explicitCompletion||Ea(ie.COMPLETE_ON_PROGRESS,i)?Ui(t,e):Ea(ie.KEEP_IN_PROGRESS,i)?Ui(t,n):{...Ui(t,e,ie.COMPLETE_ON_PROGRESS),confirmationAlternative:{kind:ie.KEEP_IN_PROGRESS,effects:n}}}function Ui(t,e,n){return Object.keys(e).length===0?t:{...t,dataDatePatch:e,...n===void 0?{}:{confirmation:n}}}function Kd(t){switch(t.percentCompleteType){case xt.PHYSICAL:return Wd(t.physicalPercentComplete);case xt.UNITS:return Wd(t.unitsPercentComplete);default:return Mk(t)}}function Mk(t){if(t.remainingDurationHours===null)return null;if(t.originalDurationHours===0)return t.executionStatus===tt.COMPLETED?100:0;let e=(t.originalDurationHours-t.remainingDurationHours)/t.originalDurationHours;return Wd(Math.min(100,Math.max(0,e*wk)))}function Wd(t){return Number(t.toFixed(xk))}function Hi(t,e,n,r,i){let a=t.canEdit(e,n.ctx.hierarchy,i);return n.dataDateCapability===null?a:sl(a,e,n.dataDateSettings,r,n.dataDateEnabled)}function wm(t,e){return e?{...t,dataDatePatch:{...t.dataDatePatch,...e.dataDatePatch}}:t}function Uk(t){return t.eventSource==="sir-apply"&&t.edits.some(e=>e.column==="actualStart"||e.column==="actualFinish")}function xm(t){if(!Uk(t))return t.edits.map(r=>[r]);let e=new Map;for(let r of t.edits){if(r.column!=="actualStart"&&r.column!=="actualFinish")continue;let i=String(r.activityId),a=e.get(i)??[];a.push(r),e.set(i,a)}let n=new Map;for(let r of e.values())r.length!==2||r[0].column===r[1].column||r.every(i=>i.newValue instanceof Date)&&(n.set(r[0],r),n.set(r[1],[]));return t.edits.flatMap(r=>{let i=n.get(r);return i?.length===0?[]:[i??[r]]})}function Mm(t,e){let n=new Map;for(let r of Gd(t)){let i=e.ctx.activityReader.getActivity(r);if(!i)continue;let a=Fr(i.p6,e.dataDateSettings,Se.RESIZE_START,e.dataDateEnabled);a.allowed||n.set(r,qd(a))}return n}function Gd(t){let e=new Map;for(let r of t){let i=String(r.activityId),a=e.get(i)??new Set;a.add(r.column),e.set(i,a)}let n=new Set;for(let[r,i]of e)i.has(E.START_DATE)&&i.has(E.END_DATE)&&n.add(r);return n}function qd(t){return{accepted:!1,reason:t.reason,...t.alertKey?{alertKey:t.alertKey}:{}}}var Hk={patch:{},needsAutoSchedule:!1,postProcessors:[]};function Um(t,e,n,r,i){return r.dataDateCapability!==null&&At(r.dataDateSettings,r.dataDateEnabled)?Yt(t,r.ctx.hierarchy)?{accepted:!1,reason:He.SUMMARY,alertKey:"summary_column_value"}:t.p6===void 0?null:wr(t,n??Hk,r,E.PROGRESS,i,{progress:e,explicitCompletion:!0,writesProgress:n!==null}):null}function wr(t,e,n,r,i,a,o=null){let s=Kk(t,Wk(t,e,r),n,r,i,a,o);if(s===null)return Yd(D.INVALID_VALUE);if("accepted"in s)return s;let l=Vk(t,s,n,r);if(l.dataDatePatch===void 0)return Fm(l);if(t.p6===void 0||n.dataDateCapability===null)return Yd(D.INVALID_VALUE);if(l.confirmation!==void 0&&!Ea(l.confirmation,i))return{accepted:!1,reason:D.CONFIRMATION_REQUIRED,confirmation:{kind:l.confirmation,activityId:t.id,effects:l.dataDatePatch,...l.confirmationAlternative===void 0?{}:{alternative:l.confirmationAlternative}}};try{let d=n.dataDateCapability.prepareActivityUpdate(t.p6,l.dataDatePatch,l.patch.constraintType??t.constraintType),u=Zk(t,d.next,n),p=Bk(t,{...l,patch:{...l.patch,...u.patch,...zk(t,l,r)},dataDateState:u.p6},d.next,n,r);return Fm(At(n.dataDateSettings,n.dataDateEnabled)?{...p,needsAutoSchedule:!0}:p)}catch{return Yd(D.INVALID_VALUE)}}function Bk(t,e,n,r,i){if(i===E.PROGRESS||t.p6===void 0||!At(r.dataDateSettings,r.dataDateEnabled))return e;let a=Kd(n);return a===null||a===t.progress||a===Kd(t.p6)||!fi.canEdit(t,r.ctx.hierarchy).allowed?e:{...e,patch:{...e.patch,progress:a}}}var jk=new Set([E.PROGRESS,E.EXECUTION_STATUS,E.PHYSICAL_PERCENT_COMPLETE]);function Vk(t,e,n,r){let i=n.dataDateSettings?.dataDate??null;if(!jk.has(r)||i===null||e.dataDatePatch===void 0||!At(n.dataDateSettings,n.dataDateEnabled))return e;let a=n.ctx.calendars.getCalendar(t.calendarId),o=a===null?{start:i,finish:i}:Qs(i,a),s=t.p6?.actualStart??null,l=s!==null&&s<=i?s:null,c=e.confirmationAlternative;return{...e,dataDatePatch:$a(e.dataDatePatch,l,o),...c===void 0?{}:{confirmationAlternative:{...c,effects:$a(c.effects,l,o)}}}}function Fm(t){return{accepted:!0,changes:t}}function Yd(t){return{accepted:!1,reason:t}}function Wk(t,e,n){let r=t.p6,i=e.patch.constraintType;return!(n===E.CONSTRAINT_TYPE&&r!==void 0&&i!==void 0)||hi(i,r.secondaryConstraintType)?e:{...e,dataDatePatch:{secondaryConstraintType:null,secondaryConstraintDate:null},confirmation:ie.CLEAR_SECONDARY_CONSTRAINT}}function Kk(t,e,n,r,i,a,o){let s=t.p6;return s!==void 0&&n.dataDateCapability!==null&&At(n.dataDateSettings,n.dataDateEnabled)?r===E.PHYSICAL_PERCENT_COMPLETE?Gk(t,s,e):r===E.PROGRESS?Yk(t,s,e,i,a):r===E.DURATION?qk(s,e):r===E.END_DATE?$k(t,s,e,n,o):r===E.START_DATE?Xk(s,e,n):e:e}function Yk(t,e,n,r,i){let a=n.patch.progress,o=i??(typeof a=="number"?{progress:a,explicitCompletion:!1,writesProgress:!0}:void 0);return o===void 0?n:Nm(t,e,n,o,r)}function Gk(t,e,n){let r=n.dataDatePatch?.physicalPercentComplete;return e.executionStatus!==tt.NOT_STARTED||r===void 0||r<=0?n:{...n,dataDatePatch:{actualStart:t.startDate,physicalPercentComplete:r},confirmation:ie.START_ON_PROGRESS}}function qk(t,e){let n=e.patch.durationHours;return typeof n!="number"?null:t.executionStatus===tt.NOT_STARTED?{...e,dataDatePatch:{originalDurationHours:n,remainingDurationHours:n}}:{...e,patch:{durationHours:n},dataDatePatch:{originalDurationHours:n}}}function $k(t,e,n,r,i){let a=Fr(e,r.dataDateSettings,Se.RESIZE_END,r.dataDateEnabled);if(!a.allowed)return qd(a);let o=n.patch.endDate,s=r.ctx.calendars.getCalendar(t.calendarId);if(!(o instanceof Date)||s===null)return null;let l=i??(e.executionStatus===tt.NOT_STARTED?t.startDate:null),c=r.dataDateCapability?.prepareFinishEdit(e,o,s,l);return c==null?null:{...n,patch:Jk(n.patch),dataDatePatch:c}}function zk(t,e,n){let r=e.patch.endDate;return n!==E.END_DATE||t.p6?.executionStatus!==tt.NOT_STARTED||!(r instanceof Date)?{}:{endDate:r}}function Jk(t){let{constraintType:e,constraintDate:n,...r}=t;return r}function Xk(t,e,n){let r=Fr(t,n.dataDateSettings,Se.MOVE,n.dataDateEnabled);return r.allowed?e:qd(r)}function Zk(t,e,n){let r=n.dataDateSettings,i=n.ctx.calendars.getCalendar(t.calendarId);if(!At(r,n.dataDateEnabled)||i===null)return{p6:e,patch:{}};let a=n.dataDateCapability.projectLocalActivity(t.p6,e,{calendar:i,dataDate:r.dataDate,totalFloatMethod:r.totalFloatMethod});return{p6:a.p6,patch:{...a.startDate===void 0?{}:{startDate:a.startDate},...a.endDate===void 0?{}:{endDate:a.endDate}}}}async function Hm(t,e,n){let{adapter:r,ctx:i,scheduler:a,sector:o}=n,s=ge(t.column);if(!s)return{ok:!1,reason:D.NO_PIPELINE_FOR_COLUMN};let l=i.activityReader.getActivity(t.activityId);if(!l)return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};let c=Hi(s,l,n,t.column);if(!c.allowed)return{ok:!1,reason:c.reason??D.CANNOT_EDIT,alertKey:c.alertKey};let d=s.parseInput(t.newValue,l,i);if(!d.ok)return{ok:!1,reason:d.reason??D.PARSE_ERROR};let u=Mi(l,s.targetField),p=s.validate(l,u,d.value,i);if(!p.valid)return{ok:!1,reason:p.reason??D.INVALID,alertKey:p.notification?.messageKey};if(t.column===E.CUSTOM_ID&&d.value!==null){let U=r.getActivity(t.activityId),w=U?U.customId:null,M=typeof w=="string"?w:null;if(n.customIdTracker.isCustomIdInUse(String(d.value),M))return{ok:!1,reason:D.CUSTOM_ID_DUPLICATE}}let y=s.transform(l,d.value,i,d.raw),f=wr(l,y,n,t.column,e.confirmations);if(!f.accepted)return{ok:!1,reason:f.reason,...f.alertKey?{alertKey:f.alertKey}:{},...f.confirmation?{confirmation:f.confirmation}:{}};let m=f.changes,A=Un(t.activityId,m),g=await yt(r,A),R=wi(r,String(t.activityId)),P=l.constraintDate;Hn(r,t.activityId,m),bn(t.activityId,m.postProcessors??[],r,g.get(String(t.activityId))??null);let N=xi(R,r,String(t.activityId));if(t.column===E.CUSTOM_ID){let U=g.get(String(t.activityId)),w=U?U.customId:null,M=typeof w=="string"?w:null,$=typeof d.value=="string"?d.value:null;M!==$&&n.customIdTracker.trackCustomIdChange(M,$)}let T=()=>({action:t,autoscheduleFrom:m.needsAutoSchedule?String(t.activityId):null,recomputeParentsFrom:[],collectDirty:U=>ss(t.activityId,A,U),now:n.now,options:e}),x=Ni(t.column),{scheduledIds:S}=await(x?ol({adapter:r,scheduler:a,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{postMutationArgs:T(),revertTargets:il(t.column)?[]:[{activityId:t.activityId,priorConstraintDate:P}],revert:(U,w)=>al(U,w,r,i.calendars)}):ot({adapter:r,scheduler:a,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},T())),k=(m.trackingEvents??[]).map(U=>({name:U.name,properties:U.properties??{}}));s.trackEvent&&!(t.column===E.PROGRESS&&Number(d.value)<=0)&&k.unshift({name:s.trackEvent,properties:{activity_name:l.name,activity_id:l.id,activity_index:l.correlativeId}});let F=Tr(t.activityId,m.constraintWarning);return{ok:!0,changes:await et(r,{source:t,beforeSnap:g,touchedIds:A,scheduledIds:S,sirDetection:Qt.BEFORE_DIFF,links:N,trackingEvents:k,...F?{warnings:[F]}:{},hoursPerDay:o.hoursPerDay})}}function ll(t){return bo(t)}function cl(t,e){return Object.hasOwn(t,e)}function Qk(t){if(t.kind===I.LINK_CREATE)return ll(t.type)?t.lag===void 0||Number.isFinite(t.lag)?null:D.INVALID_LINK_LAG:D.INVALID_LINK_TYPE;if(t.kind===I.LINK_UPDATE){if(cl(t,"type")&&!ll(t.type))return D.INVALID_LINK_TYPE;if(cl(t,"lag")&&!Number.isFinite(t.lag))return D.INVALID_LINK_LAG}return null}function tb(t){return t.kind===Lt.CREATE?ll(t.type)?t.lag===void 0||Number.isFinite(t.lag)?null:D.INVALID_LINK_LAG:D.INVALID_LINK_TYPE:t.kind===Lt.UPDATE?cl(t,"type")&&!ll(t.type)?D.INVALID_LINK_TYPE:!cl(t,"lag")||Number.isFinite(t.lag)?null:D.INVALID_LINK_LAG:t.kind===Lt.DELETE?null:D.INVALID_VALUE}function eb(t){for(let e of t){let n=tb(e);if(n!==null)return n}return null}function nb(t,e){let n=new Set,r=new Map;for(let i of t){if(i.kind===Lt.CREATE){n.add(String(i.source)),n.add(String(i.target));continue}let a=e.getLink(i.linkId);a&&(n.add(String(a.source)),n.add(String(a.target)),i.kind===Lt.UPDATE&&(i.source!==void 0&&n.add(String(i.source)),i.target!==void 0&&n.add(String(i.target))),r.set(i.linkId,{...a}))}return{activityIds:n,links:r}}function rb(t,e,n,r,i=!1){return t.map((a,o)=>{let s=a.kind===Lt.CREATE?r?.get(o):void 0,l=Xe(a,{port:e,newLinkId:s?()=>s:n.next,rejectParentLinkMutations:i});return{op:a,finalLinkId:l.applied?l.linkId:null,rejected:l.applied?null:l.rejected??D.INVALID}})}function ib(t){return new Map([...t].map(([e,n])=>[String(e),n]))}async function Bm(t,e,n){let r=Qk(t);return r!==null?{ok:!1,reason:r}:za([db(t,n.sector.hoursPerDay)],t,e,n,t.kind===I.LINK_CREATE&&t.linkId?new Map([[0,t.linkId]]):void 0)}async function jm(t,e,n){let r=eb(t.operations);if(r!==null)return{ok:!1,reason:r};let{hoursPerDay:i}=n.sector,a=t.operations.map(s=>sb(s,i)),o=ab(t.operations);return za(a,t,e,n,o)}function ab(t){let e=new Map;return t.forEach((n,r)=>{n.kind===Lt.CREATE&&n.linkId&&e.set(r,n.linkId)}),e.size>0?e:void 0}function ob(t,e){if(t===void 0)return;let n=new Map,r=new Set,i=()=>{let a=e.linkIdGen.next();for(;e.adapter.getLink(a)!==null||e.isLinkIdReserved(String(a))||r.has(String(a));)a=e.linkIdGen.next();return a};for(let[a,o]of t){let s=e.adapter.getLink(o)!==null||e.isLinkIdReserved(String(o))||r.has(String(o)),l=s?i():o;s||e.linkIdGen.bump(o),r.add(String(l)),n.set(a,l)}return n}function sb(t,e){return t.kind===Lt.CREATE?{kind:Lt.CREATE,source:t.source,target:t.target,type:t.type,lag:ke(t.lag??0,e)}:t.kind===Lt.UPDATE?{kind:Lt.UPDATE,linkId:t.linkId,source:t.source,target:t.target,type:t.type,lag:t.lag===void 0?void 0:ke(t.lag,e)}:{kind:Lt.DELETE,linkId:t.linkId}}async function za(t,e,n,r,i){let{adapter:a,scheduler:o,sector:s,linkIdGen:l}=r;o.invalidateAllCaches();let{activityIds:c,links:d}=nb(t,a),u=await yt(a,c),p=rb(t,a,l,ob(i,r),n.rejectParentLinkMutations);if(t.length===1&&p[0]&&p[0].rejected!==null&&e.kind!==I.INLINE_EDIT)return{ok:!1,reason:p[0].rejected};let y=lb(p,d,a),{scheduledIds:f,warnings:m}=await ot({adapter:a,scheduler:o,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId,runAutomaticP6Schedule:r.runAutomaticP6Schedule},{action:e,autoscheduleFrom:y,recomputeParentsFrom:c,now:r.now,options:n}),A=qn(p,d,a);return{ok:!0,linkVerdicts:p.map((g,R)=>g.rejected===null?{operationIndex:R,kind:g.op.kind,ok:!0,linkId:String(g.finalLinkId)}:{operationIndex:R,kind:g.op.kind,ok:!1,reason:g.rejected}),__beforeLinks:ib(d),changes:await et(a,{source:e,beforeSnap:u,touchedIds:c,scheduledIds:f,links:A,warnings:m,hoursPerDay:s.hoursPerDay})}}function lb(t,e,n){for(let r of t){if(r.rejected!==null)continue;let i=cb(r.op,e,n);if(i!==null)return n.hasChildren(i)?Pt.ROOTS:String(i)}return null}function cb(t,e,n){return t.kind===Lt.CREATE?t.target:t.kind===Lt.DELETE?e.get(t.linkId)?.target??null:n.getLink(t.linkId)?.target??null}function db(t,e){return t.kind===I.LINK_CREATE?{kind:Lt.CREATE,source:t.source,target:t.target,type:t.type,lag:ke(t.lag??0,e)}:t.kind===I.LINK_UPDATE?{kind:Lt.UPDATE,linkId:t.linkId,source:t.source,target:t.target,type:t.type,lag:t.lag===void 0?void 0:ke(t.lag,e)}:{kind:Lt.DELETE,linkId:t.linkId}}async function Vm(t,e,n){let{adapter:r,sector:i}=n;if(typeof t.newValue!="string")return{ok:!1,reason:D.INVALID_VALUE};if(!r.getActivity(t.activityId))return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};let o=t.column===E.CUSTOM_PREDECESSORS,{specs:s,errors:l}=Es(t.newValue,{daysPerWeek:i.hoursPerWeek/i.hoursPerDay});if(l.length>0)return{ok:!1,reason:D.INVALID_VALUE};let c=s.map(f=>({...f,lag:ke(Ps(f.lag),i.hoursPerDay)})),d=new Map;r.forEachActivity(f=>{f.correlativeId!=null&&d.set(String(f.correlativeId),f.id)});let u=f=>d.get(f)??null,p=Fi(r,t.activityId,o),y=o?Ti({targetActivityId:t.activityId,currentLinks:p,desiredSpecs:c,resolveActivityByCorrelative:u}):_i({sourceActivityId:t.activityId,currentLinks:p,desiredSpecs:c,resolveActivityByCorrelative:u});return za(y.operations,t,e,n)}var Le={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 Bt(t){t.invalidateVisualOrderIds?.();let e=[];t.forEachActivity(a=>{G(a.parentId)&&e.push(a)}),e.sort(Ym);let n=[];Wm(n,e);let r=[],i=0;for(;n.length>0;){let a=n.pop();if(a.correlativeId!==i){let s=typeof a.correlativeId=="number"?a.correlativeId:void 0;r.push({activityId:String(a.id),before:s}),s!==void 0&&t.noteCorrelativeBefore?.(String(a.id),s),ub(a,i)}i+=1;let o=hr(String(a.id),t);o.sort(Ym),Wm(n,o)}return r}function Wm(t,e){for(let n=e.length-1;n>=0;n-=1)t.push(e[n])}function Km(t){let e=t.correlativeId,n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?n:Nc}var Ym=(t,e)=>Km(t)-Km(e);function ub(t,e){t.correlativeId=e}function $d(t,e){if(!t||t==="0")return;let n=String(t);for(;n!==null;){let{workHours:r,realWorkHours:i}=$m(n,e);e.setActivityField(n,b.WORK_HOURS,r),e.setActivityField(n,b.REAL_WORK_HOURS,i);let a=e.getActivity(n);if(!a)break;let o=a.parentId;if(!o||G(o))break;n=o}}function Gm(t,e){let n=e.getActivity(t);if(!n)return;let r=n.parentId;!r||G(r)||$d(r,e)}function qm(t,e,n){for(let r of t){if(n.hasChildren(r))continue;let i=n.getActivity(r);i&&n.setActivityField(r,b.REAL_WORK_HOURS,he(Ja(i,b.WORK_HOURS),Ja(i,b.PROGRESS)))}for(let r of e)n.setActivityField(r,b.REAL_WORK_HOURS,$m(r,n).realWorkHours)}function $m(t,e){let n=0,r=0;for(let i of e.getChildren(t)){let a=e.getActivity(i);if(!a)continue;let o=Ja(a,b.WORK_HOURS);n+=o,r+=pb(i,a,o,e)}return{workHours:n,realWorkHours:r}}function Ja(t,e){let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:0}function pb(t,e,n,r){return r.hasChildren(t)?Ja(e,b.REAL_WORK_HOURS):he(n,Ja(e,b.PROGRESS))}function zd(t,e){if(!t||t==="0")return;let n=String(t);for(;n!==null;){let r=e.getChildren(n),i=0;for(let s of r){let l=e.getActivity(s);l&&(i+=yb(l,b.USED_COST))}e.setActivityField(n,b.USED_COST,i);let a=e.getActivity(n);if(!a)break;let o=a.parentId;if(!o||G(o))break;n=o}}function zm(t,e){let n=e.getActivity(t);if(!n)return;let r=n.parentId;!r||G(r)||zd(r,e)}function yb(t,e){let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:0}function Jd(t,e){if(!t||t==="0")return;let n=String(t);for(;n!==null;){let r=e.getChildren(n),i=0;for(let s of r){let l=e.getActivity(s);l&&(i+=fb(l,b.COST))}e.setActivityField(n,b.COST,i);let a=e.getActivity(n);if(!a)break;let o=a.parentId;if(!o||G(o))break;n=o}}function Jm(t,e){let n=e.getActivity(t);if(!n)return;let r=n.parentId;!r||G(r)||Jd(r,e)}function fb(t,e){let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:0}var dl=Object.freeze({proplannerId:null,description:"",type:H.TASK,progress:0,constraintType:_.ASAP,constraintDate:null,autoScheduling:!0,assignedDefaultCalendar:!1,dateOrigin:null,cost:0,usedCost:0,realCost:0,workHours:0,realWorkHours:0,ponderator:0,hasCustomPonderator:!1,correlativeId:0,customId:null,subcontractId:null,isLookahead:!1,hasLookaheadTasks:!1,newActivityIds:Ae([]),hasNewActivities:!1,pendingRequestIds:Ae([]),responsableIds:Ae([]),tagIds:Ae([]),baselinePoints:Ae([]),baselineSnapshot:null,baselineVarianceDays:null,projectBaselineVarianceDays:null,primaryBaselineVarianceDays:null,recursiveDurationHours:0,isCritical:!1,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}),Xm="New Master Plan",Zm="New Activity";var hb=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],ul=new Set(hb);function mb(t){let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype)throw new Error("activity-create: override bag must be a plain object with no custom prototype");for(let n of Reflect.ownKeys(t))if(typeof n=="symbol"||!ul.has(n))throw new Error(`activity-create: rejected override key "${String(n)}" \u2014 not a creation-writable canonical field`);return t}function Qm(t,e){let n=t.parentId!=null?e.getActivity(t.parentId):null,r=mb(t.activityOverrides??{}),i=t.numTasksInGantt===0?Xm:Zm,a=r.name??i,o=r.durationHours??t.sector.hoursPerDay,s=r.calendarId??t.sector.defaultCalendar,l=gb(n,t.fallbackStartDate,r.startDate),c={...dl,...r,id:t.id,parentId:t.parentId,uniqueCorrelativeId:t.nextUniqueCorrelativeId,name:a,durationHours:o,calendarId:s,startDate:l,endDate:l},d=r.startDate?new Date(c.startDate):e.getClosestWorkTime({date:c.startDate,dir:mt.FUTURE,task:c});if(!r.startDate&&n&&mr(n.type)){let y=new Date(n.startDate);y.setUTCHours(0,0,0,0);let f=new Date(d);f.setUTCHours(0,0,0,0),f.getTime()!==y.getTime()&&(d=e.getClosestWorkTime({date:y,dir:mt.FUTURE,task:c}))}let u=e.calculateEndDate({startDate:d,durationHours:c.durationHours,task:c});return{newTask:{...c,startDate:d,endDate:u,calendarDuration:Je({type:c.type,startDate:d,endDate:u}),newActivityIds:[...c.newActivityIds],pendingRequestIds:[...c.pendingRequestIds],responsableIds:[...c.responsableIds],tagIds:[...c.tagIds],baselinePoints:[...c.baselinePoints]}}}function gb(t,e,n){return n?new Date(n):t?new Date(t.startDate):e?new Date(e):new Date}var pl={END:"end"};function yl(t,e){return hr(t,e).sort(Rn).map(n=>n.id)}function Ab(t){let e=yl("0",t),[n]=e;if(e.length===1&&n!==void 0){let i=yl(n,t).at(-1);return i===void 0?{ok:!0,parentId:n}:{ok:!0,parentId:n,afterSiblingId:i}}let r=e.at(-1);return r===void 0?{ok:!0,parentId:"0"}:{ok:!0,parentId:"0",afterSiblingId:r}}function Xd(t,e){if("placement"in t)return t.placement===pl.END?Ab(e):{ok:!1,reason:D.INVALID};let{afterSiblingId:n}=t,r=e.getActivity(n);return r?r.parentId==null?e.getRootIds().length===1?{ok:!0,parentId:r.id,beforeSiblingId:yl(r.id,e)[0]}:{ok:!0,parentId:"0",afterSiblingId:n}:e.hasChildren(r.id)?{ok:!0,parentId:r.id,beforeSiblingId:yl(r.id,e)[0]}:{ok:!0,parentId:String(r.parentId),afterSiblingId:n}:{ok:!1,reason:D.ANCHOR_SIBLING_NOT_FOUND}}function Ib(t,e){let n="placement"in t?e.afterSiblingId:t.afterSiblingId;return{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,...n===void 0?{}:{customIdReferenceId:n}}}var tg=()=>({ok:!1,reason:D.ACTIVITY_PASTE_INVARIANT_FAILED});async function eg(t,e,n){let r=n.activityClipboard.value;if(r===null)return{ok:!1,reason:D.CLIPBOARD_EMPTY};let i=Xd(t.destination,n.adapter);if(!i.ok)return i;let a=Ib(t.destination,i),o=await yt(n.adapter,new Set),s=new Set,l=new Map,c=[],d;for(let g of r.activities){let R=l.get(g.originalParentId),P=R===void 0?d??i.afterSiblingId:void 0,N=R===void 0&&P===void 0?i.beforeSiblingId:void 0,T=await $n({kind:I.ACTIVITY_CREATE,parentId:R??i.parentId,...P===void 0?{}:{afterSiblingId:P},...N===void 0?{}:{beforeSiblingId:N},overrides:C(g.overrides),eventSource:t.eventSource},n,{...a,confirmedLookaheadParentIds:e.confirmedLookaheadParentIds,lookaheadTasksByActivityId:e.lookaheadTasksByActivityId});if(!T.ok)return T;l.set(g.originalId,T.newId),c.push(T.newId),R===void 0&&(d=T.newId)}let u=Bt(n.adapter),p=new Set(c.map(String)),y=Ie(n.adapter,u,p,o,s);for(let g of c)s.add(String(g));let f=[];for(let g of r.links){let R=l.get(g.source),P=l.get(g.target);if(R===void 0||P===void 0)return tg();let N={kind:Ut.CREATE,source:R,target:P,type:g.type,lag:g.lag},T=Xe(N,{port:n.adapter,newLinkId:n.linkIdGen.next});if(!T.applied)return tg();f.push({op:N,finalLinkId:T.linkId,rejected:null})}let{scheduledIds:m}=await ot({adapter:n.adapter,scheduler:n.scheduler,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:c[0]??null,recomputeParentsFrom:c,now:n.now,options:e}),A=qn(f,new Map,n.adapter);return{ok:!0,changes:await et(n.adapter,{source:t,beforeSnap:o,deferredCorrelatives:y,touchedIds:s,scheduledIds:m,links:A,hoursPerDay:n.sector.hoursPerDay})}}var fl={HAS_LOOKAHEAD_TASKS:"has_lookahead_tasks"};function Bi(t,e){return!eh(t,{reparented:e}).ok}function hl(t,e){let n=new Set;if(t.length===0)return n;let r=new Map(t.map(a=>[a.activityId,a.newParentId]));if(!Bi(e,r))return n;let i=new Map;for(let a of t){let o=new Map(i);if(o.set(a.activityId,a.newParentId),Bi(e,o)){n.add(a.activityId);continue}i.set(a.activityId,a.newParentId)}return n}function ji(t,e,n,r){let i=e,a=i==="0",o=Xa(t,i);if(r!==void 0){let l=o.find(c=>c.id===r);if(l){let c=ee(l),d=o.map(ee).filter(p=>p<c);return d.length===0?c-1:(Math.max(...d)+c)/2}}if(n!==void 0){let l=o.find(c=>c.id===n);if(l){let c=ee(l),d=o.map(ee).filter(p=>p>c);if(d.length===0)return c+1;let u=Math.min(...d);return(c+u)/2}}return o.length===0?0:Math.max(...o.map(ee))+1}var xr=Number.MAX_SAFE_INTEGER,ng=Number.MAX_SAFE_INTEGER-1;function ee(t){let e=t.correlativeId,n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?n:xr}function Xa(t,e){return hr(e,t)}function rg(t,e,n){let r=t,i=Oe(t,n);for(;i!=null&&e.has(i);)r=i,i=Oe(i,n);return r}function zn(t,e,n){let r=new Set([t]),i=pe(n.getActivity(t)?.parentId);for(;i!=="0"&&!r.has(i);){if(e.has(i))return!0;r.add(i),i=pe(n.getActivity(i)?.parentId)}return!1}function Oe(t,e){let n=e.getActivity(t);if(!n)return null;let r=pe(n.parentId),i=Ee(r,e),a=i.findIndex(o=>String(o)===String(t));return a<=0?null:i[a-1]??null}function ig(t,e,n,r){let i=Ee(e,t).filter(l=>String(l)!==String(r)).map(l=>t.getActivity(l)).filter(l=>l!==null);if(i.length===0)return 0;let a=i.map(ee);if(n<=0)return a[0]-1;if(n>=a.length)return a[a.length-1]+1;let o=a[n-1],s=a[n];return(o+s)/2}function Vi(t,e){let n=new Set(t),r=[],i=[],a=new Set,o=new Set(n),s=[...t].sort((d,u)=>{let p=e.getActivity(d),y=e.getActivity(u),f=p?ee(p):xr,m=y?ee(y):xr;return f-m});for(let d of s){if(!e.getActivity(d)){r.push({activityId:d,reason:D.ACTIVITY_NOT_FOUND}),o.delete(d);continue}if(zn(d,a,e))continue;let p=ny(d,o,e);if(p==null){r.push({activityId:d,reason:D.INDENT_NO_ELIGIBLE_SIBLING}),o.delete(d);continue}let y=e.getActivity(d)?.parentId,f=G(y)?"0":String(y);i.push({activityId:d,newParentId:p,oldParentId:f}),a.add(d)}let l=hl(i,e);for(let d of l)r.push({activityId:d,reason:D.HIERARCHY_CYCLE});let c=i.filter(d=>!l.has(d.activityId));return{moves:i,cyclicMoveIds:l,allowedMoves:c,failed:r}}function yn(t,e){let n=new Set(e.confirmedLookaheadParentIds),r=e.lookaheadTasksByActivityId,i=[...new Set(t.filter(o=>!n.has(String(o.id))&&(r?.[String(o.id)]??o.hasLookaheadTasks)).map(o=>String(o.id)))],[a]=i;return a===void 0?null:{ok:!1,reason:D.CONFIRMATION_REQUIRED,confirmation:{kind:fl.HAS_LOOKAHEAD_TASKS,activityId:a,...i.length>1?{activityIds:i}:{}}}}function fn(t,e){let n=new Map;for(let r of t){let i=e.getActivity(r);i&&e.getChildren(r).length===0&&n.set(String(i.id),i)}return[...n.values()]}function ag(t,e,n){return sg(t,e,n).map(r=>String(r.id))}function og(t,e,n,r){let i=yn(sg(t,n,r),e);return i===null?null:i.confirmation}function sg(t,e,n){let r=[];for(let i of t)r.push(...Sb(i,e,n).map(String));return fn(r,e)}function Sb(t,e,n){switch(t.kind){case I.ACTIVITY_CREATE:return[t.parentId];case I.ACTIVITY_MOVE:{let r=e.getActivity(t.activityId);return r?pe(r.parentId)===String(t.parentId)?[]:vb(t,e)?[]:[t.parentId]:[]}case I.ACTIVITY_INDENT:return Vi(t.activityIds,e).allowedMoves.map(r=>r.newParentId);case I.ACTIVITY_PASTE_COPIED:{if(!n)return[];let r=Xd(t.destination,e);return r.ok?[r.parentId]:[]}case qe:return t.mode===Ht.APPEND?t.items.flatMap(r=>typeof r.parent=="string"?[r.parent]:[]):[];default:return[]}}function vb(t,e){return G(t.parentId)?!1:t.parentId===t.activityId||e.isChildOf(t.parentId,t.activityId)?!0:Bi(e,new Map([[t.activityId,t.parentId]]))}var Cb=new Set([...[...ul].filter(t=>t!==b.DURATION_HOURS),"durationDays"]);function ml(t,e){if(t===void 0)return{ok:!0,value:{}};let n=Object.getPrototypeOf(t);if(n!==null&&n!==Object.prototype)return{ok:!1,reason:D.INVALID_VALUE};for(let a of Reflect.ownKeys(t))if(typeof a=="symbol"||!Cb.has(a))return{ok:!1,reason:D.INVALID_VALUE};let{durationDays:r,...i}=t;return r!==void 0&&(!Number.isFinite(r)||r<0)?{ok:!1,reason:D.INVALID_VALUE}:{ok:!0,value:{...i,...r===0&&(i.type===void 0||i.type===H.TASK)?{type:H.MILESTONE}:{},...r===void 0?{}:{durationHours:Ar(r,e)}}}}function zt(t,e){$d(t,e),zd(t,e),Jd(t,e)}function Wi(t,e){let n=new Set,r=[];for(let i of t){let a=String(i);n.has(a)||(n.add(a),r.push(a))}for(;r.length>0;){let i=r.pop(),a=e.getChildren(i);for(let o of a){let s=String(o);n.has(s)||(n.add(s),r.push(s))}}return n}function Jn(t,e){let n=new Set;for(let r of t){for(let i of e.getOutgoingLinkIds(r))n.add(String(i));for(let i of e.getIncomingLinkIds(r))n.add(String(i))}return[...n]}function Db(t){return t?{type:t.type,startDate:new Date(t.startDate),endDate:new Date(t.endDate),durationHours:t.durationHours,expectedProgressBaseline:t.expectedProgressBaseline,constraintType:t.constraintType,constraintDate:t.constraintDate?new Date(t.constraintDate):null,progress:t.progress}:null}function Tb(t,e,n){let r=t.startDate;return!n||!(r instanceof Date)?{}:{endDate:n(r,e)}}function Qe(t){if(t.remainingChildIds.length>0)return null;let e=t.parent,n=t.defaultDurationHours,r=Number.isFinite(n),i=Db(t.promotionSnapshot)??(r?{type:si,durationHours:n,progress:0,autoScheduling:!0,constraintType:_.ASAP,constraintDate:null,hasNewActivities:!1,...Tb(e,n,t.computeEndDate)}:{type:si});if(t.idsRemoved&&t.idsRemoved.size>0){let o=Array.isArray(e.newActivityIds)?e.newActivityIds:[];if(o.length>0){let s=o.filter(l=>!t.idsRemoved.has(l)&&!t.idsRemoved.has(String(l)));s.length!==o.length&&(i.newActivityIds=s)}}e.hasLookaheadTasks&&(i.isLookahead=!0);let a=_b(e,i);return t.dataDateCapability&&a&&Object.assign(i,t.dataDateCapability.parentDemoted({activity:a,hasCompleteSchedulingState:t.hasCompleteSchedulingState===!0,promotionSnapshot:t.promotionSnapshot})),{parentId:String(e.id),fields:i}}function _b(t,e){let n=e.startDate??t.startDate,r=e.endDate??t.endDate,i=e.durationHours??t.durationHours,a=e.progress??t.progress,o=e.type??t.type;return!(n instanceof Date)||!(r instanceof Date)||typeof i!="number"||typeof a!="number"?null:{type:o,startDate:n,endDate:r,durationHours:i,progress:a}}function gl(t){if(t.idsRemoved.size===0)return null;let e=t.parent.newActivityIds;if(!Array.isArray(e)||e.length===0)return null;let n=e,r=n.filter(i=>!t.idsRemoved.has(i)&&!t.idsRemoved.has(String(i)));return r.length===n.length?null:{parentId:String(t.parent.id),fields:{newActivityIds:[...r],hasNewActivities:r.length>0}}}var lg=200;async function cg(t,e,n){let{adapter:r,scheduler:i,customIdTracker:a,sector:o}=n;if(i.invalidateAllCaches(),t.activityIds.length===0)return{ok:!1,reason:D.ACTIVITY_IDS_EMPTY};for(let k of t.activityIds)if(!r.getActivity(k))return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};let s=t.activityIds.filter(k=>{let F=r.getActivity(k);return!(F?.correlativeId===0&&F.type===H.PROJECT)}),l=Wi(s,r),c=Jn(l,r),d=new Set;for(let k of t.activityIds){let F=r.getActivity(k);if(!F)continue;let U=F.parentId;if(G(U))continue;let w=String(U);l.has(w)||d.add(w)}let u=new Set([...l,...d]),p=await yt(r,u),y=new Map;for(let k of c){let F=r.getLink(k);F&&y.set(k,{...F})}let f=new Set,m=0;for(let k of l){m+=1,m%lg===0&&await wt();let F=r.getActivity(k);if(!F)continue;let U=G(F.parentId)?null:r.getActivity(String(F.parentId)),w=U?.hasNewActivities===!0&&U.newActivityIds.some($=>String($)===String(k));(F.isNewActivity===!0||w)&&f.add(k);let M=F.customId;typeof M=="string"&&M.length>0&&a.releaseCustomId(M)}for(let k of c)r.removeLink(k);let A=Mr(r,l),g=0;for(let k of l)g+=1,g%lg===0&&await wt(),r.removeActivity(k);for(let k of d){let F=r.getActivity(k);if(!F)continue;Eb(F,f,r);let U=r.getChildren(k),w=Qe({parent:F,remainingChildIds:U.map(String),defaultDurationHours:o.hoursPerDay,promotionSnapshot:r.getPromotionSnapshot(k),computeEndDate:(M,$)=>r.calculateEndDate({startDate:M,durationHours:$,task:F}),idsRemoved:l,dataDateCapability:n.dataDateCapability,hasCompleteSchedulingState:n.hasCompleteSchedulingState});if(!w){Go(k,r);continue}if(r.setActivityFields(k,w.fields),F.customId==null||F.customId===""){let M=Oe(k,r),$=M?r.getActivity(M)?.customId:null,st=a.generateCustomIdForRestoredChild(typeof $=="string"&&$?$:null);r.setActivityField(k,b.CUSTOM_ID,st)}}for(let k of d)zt(k,r);let R=Bt(r),{scheduledIds:P}=await ot({adapter:r,scheduler:i,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:Pt.ROOTS,recomputeParentsFrom:d,now:n.now,options:e}),N={name:Le.ACTIVITY_DELETION,properties:{activity_ids:[...t.activityIds],cascade_count:l.size}};t.eventSource!==void 0&&(N.properties.event_source=t.eventSource);let T=new Map;for(let[k,F]of y)T.set(k,F);let x=new Map;for(let k of l){let F=p.get(String(k));F&&x.set(String(k),F)}let S=await et(r,{source:t,beforeSnap:p,touchedIds:u,scheduledIds:P,sirDetection:Qt.AFTER_DIFF,links:ne(y),trackingEvents:[N],hoursPerDay:o.hoursPerDay,correlativeShifts:R});return{ok:!0,changes:A.length>0?{...S,viewState:A}:S,__beforeSnap:x,__beforeLinks:T}}function Eb(t,e,n){let r=gl({parent:t,idsRemoved:e});if(r)for(let[i,a]of Object.entries(r.fields))ve(n,r.parentId,i,a)}function Mr(t,e){let n=[];for(let r of e){let i=t.isChecked(r),a=t.isVisible(r);!i&&a||n.push({activityId:String(r),...i?{checked:{before:!0,after:!1}}:{},...a?{}:{visible:{before:!1,after:!0}}})}return n}function ne(t){let e=[];for(let[n,r]of t.entries())e.push({id:n,kind:W.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 e}var Ki={CREATE:"create",REPARENT:"reparent"};function Rb(t,e={}){let n=t.type;if(n!==H.TASK&&n!==H.MILESTONE)return null;let r=t.startDate,i=t.endDate;return!(r instanceof Date)||!(i instanceof Date)?null:{type:n,startDate:new Date(r),endDate:new Date(i),durationHours:Number(t.durationHours??0),expectedProgressBaseline:typeof t.expectedProgressBaseline=="number"?t.expectedProgressBaseline:null,constraintType:t.constraintType??null,constraintDate:t.constraintDate instanceof Date?new Date(t.constraintDate):null,progress:Number(t.progress??0),...e}}function dg(t){let e=t.getParent(t.parentId);if(!e)return null;let n=t.isCurrentlyLeaf!==void 0?t.isCurrentlyLeaf&&kn(e.type):Pb(e),r=Array.isArray(e.newActivityIds)?e.newActivityIds:[],a={isLookahead:!1,hasNewActivities:!0,newActivityIds:r.some(s=>String(s)===String(t.newChildId))?[...r]:[...r,t.newChildId]},o=n?t.dataDateCapability?.parentPromoted(e):void 0;return e.customId!=null&&e.customId!==""&&(a.customId=null),n&&(a.type=Hc,o&&Object.assign(a,o.activityPatch),(t.promotionSource??Ki.CREATE)===Ki.CREATE&&(a.constraintType=_.ASAP,a.constraintDate=null)),{parentId:t.parentId,fields:a,promotionSnapshot:Rb(e,o?.snapshotPatch)}}function Pb(t){return kn(t.type)&&(!Array.isArray(t.newActivityIds)||t.newActivityIds.length===0)}function Xn(t,e){let r=e.adapter.getActivity(t.parentId)?.customId??null,i=dg({...t,getParent:o=>e.adapter.getActivity(o)??null,dataDateCapability:e.dataDateCapability});if(!i)return{applied:!1,removedLinks:new Map};let a=i.fields.type===H.PROJECT?kb(t.parentId,e):new Map;for(let[o,s]of Object.entries(i.fields))ve(e.adapter,i.parentId,o,s);return i.promotionSnapshot&&e.adapter.setPromotionSnapshot(i.parentId,i.promotionSnapshot),i.fields.customId===null&&e.customIdTracker.releaseCustomId(r),{applied:!0,removedLinks:a}}function kb(t,e){let n=new Map,r=new Set([...e.adapter.getIncomingLinkIds(t),...e.adapter.getOutgoingLinkIds(t)]);for(let i of r){let a=e.adapter.getLink(i);a&&(n.set(String(i),{...a}),e.adapter.removeLink(i))}return n}async function $n(t,e,n={}){let{adapter:r,scheduler:i,sector:a,calendars:o,activityIdGen:s,uidGen:l}=e;n.skipCacheInvalidation||i.invalidateAllCaches();let c=bb(t,r,n);if(!c.ok)return c;let{parent:d,anchorSiblingId:u,isRoot:p}=c,y=Ob(t.activityId,r,s,e.isActivityIdReserved),f=l.next(),m={id:y,parentId:p?null:t.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:Mb(o)},numTasksInGantt:r.activityCount(),nextUniqueCorrelativeId:f,activityOverrides:t.overrides??{},...e.actionAt?{fallbackStartDate:e.actionAt}:{}},g=Qm(m,{getActivity:k=>r.getActivity(k),calculateEndDate:k=>r.calculateEndDate(k),getClosestWorkTime:k=>r.getClosestWorkTime(k)}).newTask;e.dataDateCapability!==null&&Object.assign(g,e.dataDateCapability.activityCreated({activity:g,hasCompleteSchedulingState:e.hasCompleteSchedulingState})),g.realWorkHours=he(g.workHours,g.progress),Fb(g,t,e,u,d,n);let R=n.insertionCorrelativeId??ji(r,p?"0":t.parentId,t.afterSiblingId,t.beforeSiblingId);g.correlativeId=R;let P=new Set([y]);d&&P.add(d.id);let N=d!==null&&r.getChildren(d.id).length===0,T=n.skipBeforeSnap?new Map:await yt(r,P);r.addActivity(g);let x=d?Xn({parentId:d.id,newChildId:y,isCurrentlyLeaf:N},e).removedLinks:new Map;n.skipRollupCascades||(Gm(y,r),zm(y,r),Jm(y,r));let S=wb(r,y,P,n);return{ok:!0,newId:y,parent:d,newActivity:g,beforeSnap:T,initialTouched:P,correlativeShifts:S,removedParentLinks:x}}function bb(t,e,n){let r=G(t.parentId),i=r?null:e.getActivity(t.parentId);if(!r&&!i)return{ok:!1,reason:D.PARENT_NOT_FOUND};if(i!==null&&Nr(i))return{ok:!1,reason:D.PARENT_FROZEN_BY_SIR};if(t.afterSiblingId!==void 0&&t.beforeSiblingId!==void 0)return{ok:!1,reason:D.ANCHOR_SIBLING_CONFLICT};let s=t.afterSiblingId??t.beforeSiblingId,l=Lb(t,e,r,s);if(l)return l;if(i!==null&&!n.parentsAlreadyChecked){let c=yn(fn([t.parentId],e),n);if(c)return c}return{ok:!0,parent:i,anchorSiblingId:s,isRoot:r}}function Lb(t,e,n,r){if(r===void 0)return null;let i=e.getActivity(r);if(!i)return{ok:!1,reason:D.ANCHOR_SIBLING_NOT_FOUND};let a=n?"0":t.parentId;return(i.parentId==null?"0":String(i.parentId))!==a?{ok:!1,reason:D.ANCHOR_SIBLING_WRONG_PARENT}:null}function Ob(t,e,n,r){let i=()=>{let a=n.next();for(;e.activityExists(a)||r(String(a));)a=n.next();return a};return t===void 0||e.activityExists(t)||r(String(t))?i():(n.bump(t),t)}function Nb(t){let e=t.overrides?.customId;return typeof e=="string"?e:void 0}function Fb(t,e,n,r,i,a){let{adapter:o,customIdTracker:s}=n,l=Nb(e);if(l!==void 0){if(l.length===0)return;if(!s.isCustomIdInUse(l)){s.registerCustomId(l);return}}let c=a.customIdReferenceId??r,d=c!==void 0,u=d?o.getActivity(c):i;t.customId=s.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function wb(t,e,n,r){if(r.skipCorrelativeRecompute)return[];let i=Bt(t).filter(a=>a.activityId!==String(e));for(let a of i)n.add(a.activityId);return i}async function xb(t,e,n,r,i){let{newId:a,newActivity:o,beforeSnap:s,initialTouched:l,correlativeShifts:c,removedParentLinks:d}=n,u={name:Le.ACTIVITY_CREATION,properties:{parent_id:e.parentId,activity_id:a,created_duration:o.durationHours}};return e.eventSource!==void 0&&(u.properties.event_source=e.eventSource),et(t,{source:e,beforeSnap:s,touchedIds:l,scheduledIds:r,correlativeShifts:c,trackingEvents:[u],links:ne(new Map(d)),hoursPerDay:i})}async function ug(t,e,n){let{adapter:r,scheduler:i,sector:a}=n,o=ml(t.overrides,a.hoursPerDay);if(!o.ok)return o;let s=await $n({...t,overrides:o.value},n,{confirmedLookaheadParentIds:e.confirmedLookaheadParentIds,lookaheadTasksByActivityId:e.lookaheadTasksByActivityId});if(!s.ok)return s;let{newId:l}=s,c=s.newActivity.autoScheduling;r.setActivityField(l,"autoScheduling",!1);let d;try{d=await ot({adapter:r,scheduler:i,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:l,recomputeParentsFrom:[l],preventSummaryTargetPullback:!0,now:n.now,options:e})}finally{r.setActivityField(l,"autoScheduling",c)}let{scheduledIds:u}=d;return{ok:!0,changes:await xb(r,t,s,u,a.hoursPerDay),...s.removedParentLinks.size>0?{__beforeLinks:new Map(s.removedParentLinks)}:{}}}function Mb(t){for(let n of t.values())if(n.is_default)return n.id;let e=t.values().next();return!e.done&&e.value?e.value.id:"global"}async function fg(t,e,n){let r=Hb(t,n);if(r)return{ok:!1,reason:r};let i=jb(t,n);if(!i.ok)return i;if(t.mode===Ht.APPEND){let T=yn(fn(Ub(i.plan.items),n.adapter),e);if(T)return T}let a=t.mode===Ht.REPLACE?new Set(n.adapter.getAllIds().map(T=>String(T))):new Set,o=t.mode===Ht.REPLACE?await yt(n.adapter,a):new Map,s=t.mode===Ht.REPLACE?qb(n):new Map,l=t.mode===Ht.REPLACE?Mr(n.adapter,a):[];n.scheduler.invalidateAllCaches();let c=[];if(t.mode===Ht.REPLACE){for(let T of s.keys()){let x=Xe({kind:Lt.DELETE,linkId:T},{port:n.adapter});if(!x.applied)return{ok:!1,reason:x.rejected??D.INVALID};c.push({op:{kind:Lt.DELETE,linkId:T},finalLinkId:T,rejected:null})}for(let T of a){let x=n.adapter.getActivity(T)?.customId;typeof x=="string"&&x.length>0&&n.customIdTracker.releaseCustomId(x),n.adapter.removeActivity(T)}}let d=await Gb(t,i.plan.items,n);if(!d.ok)return d;for(let[T,x]of d.removedParentLinks)s.set(T,x),c.push({op:{kind:Lt.DELETE,linkId:T},finalLinkId:T,rejected:null});let u=hg(t)?[]:Bt(n.adapter),p=new Set(i.plan.items.map(T=>String(T.activityId))),y=u.filter(T=>!p.has(T.activityId)),f=t.mode===Ht.REPLACE?new Set(a):new Set,m=Ie(n.adapter,u,p,o,f);for(let T of i.plan.items)f.add(String(T.activityId));let A=i.plan.links.map(T=>({operation:{kind:Lt.CREATE,source:T.source,target:T.target,type:T.type,lag:ke(T.lag??0,n.sector.hoursPerDay)},linkId:T.linkId})),g=Ds(A,{port:n.adapter,preserved:s,rejectParentLinkMutations:e.rejectParentLinkMutations??!1});if(!g.applied)return{ok:!1,reason:g.rejected??D.INVALID};for(let{operation:T,linkId:x}of A)c.push({op:T,finalLinkId:x,rejected:null});let R=i.plan.items.map(T=>T.activityId),{scheduledIds:P}=await ot({adapter:n.adapter,scheduler:n.scheduler,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:t.items.length>0||t.links.length>0?Pt.ROOTS:null,recomputeParentsFrom:R,now:n.now,options:e}),N=await et(n.adapter,{source:t,beforeSnap:o,touchedIds:f,scheduledIds:P,links:qn(c,s,n.adapter),hoursPerDay:n.sector.hoursPerDay,correlativeShifts:y,deferredCorrelatives:m,...t.mode===Ht.REPLACE?{sirDetection:Qt.AFTER_DIFF}:{}});return{ok:!0,changes:l.length>0?{...N,viewState:l}:N,...t.mode===Ht.REPLACE||s.size>0?{...t.mode===Ht.REPLACE?{__beforeSnap:o}:{},__beforeLinks:$b(s)}:{}}}function Ub(t){return t.filter(e=>e.parentBatchId===null&&e.parentId!=="0").map(e=>String(e.parentId))}function Hb(t,e){if(t.mode!==Ht.APPEND&&t.mode!==Ht.REPLACE)return D.INVALID;let n=new Set,r=new Set;for(let a of t.items){if(a.batchId.length===0||n.has(a.batchId))return D.INVALID;if(n.add(a.batchId),a.index!==void 0&&(!Number.isInteger(a.index)||a.index<0))return D.INVALID;if(a.activityId!==void 0){let o=String(a.activityId);if(o.length===0||o==="0"||r.has(o))return D.INVALID;r.add(o)}}for(let a of t.items)if(!Qd(a.parent,!0,t.mode,n,e))return D.PARENT_NOT_FOUND;if(Bb(t.items))return D.INVALID;let i=new Set;for(let a of t.links){if(!Object.values(q).includes(a.type))return D.INVALID_LINK_TYPE;if(a.lag!==void 0&&!Number.isFinite(a.lag))return D.INVALID_LINK_LAG;if(!Qd(a.source,!1,t.mode,n,e)||!Qd(a.target,!1,t.mode,n,e))return D.ACTIVITY_NOT_FOUND;if(a.linkId!==void 0){let o=String(a.linkId);if(o.length===0||i.has(o))return D.INVALID;i.add(o)}}return null}function Qd(t,e,n,r,i){return typeof t=="string"?t==="0"?e:n===Ht.APPEND&&i.adapter.getActivity(String(t))!==null:t!==null&&t.batchId.length>0&&r.has(t.batchId)}function Bb(t){let e=new Map;for(let r of t)typeof r.parent!="string"&&e.set(r.batchId,r.parent.batchId);let n=new Set;for(let r of t){let i=new Set,a=r.batchId;for(;a!==void 0&&!n.has(a);){if(i.has(a))return!0;i.add(a),a=e.get(a)}for(let o of i)n.add(o)}return!1}function jb(t,e){let n=new Map;for(let d of t.items){let u=ml(d.overrides,e.sector.hoursPerDay);if(!u.ok)return u;n.set(d.batchId,u.value)}let r=new Map,i=new Set;for(let d of t.items){let u=Vb(d.activityId,t.mode,i,e);i.add(String(u)),r.set(d.batchId,u)}let a=new Set,o=t.links.map(d=>{let u=Wb(d.linkId,t.mode,a,e);return a.add(String(u)),u}),s=Kb(t,r,e),l=[];for(let d of t.items){let u=r.get(d.batchId),p=s.get(d.batchId);if(u===void 0||p===void 0)return{ok:!1,reason:D.INVALID};let y=typeof d.parent=="string"?null:d.parent.batchId,f=typeof d.parent=="string"?d.parent:r.get(d.parent.batchId);if(f===void 0)return{ok:!1,reason:D.PARENT_NOT_FOUND};l.push({input:d,activityId:u,parentId:f,parentBatchId:y,insertionCorrelativeId:p,overrides:n.get(d.batchId)??{}})}let c=[];for(let[d,u]of t.links.entries()){let p=yg(u.source,r),y=yg(u.target,r),f=o[d];if(p===null||y===null||f===void 0)return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};c.push({source:p,target:y,type:u.type,lag:u.lag??0,linkId:f})}return{ok:!0,plan:{items:l,links:c}}}function Vb(t,e,n,r){if(t!==void 0&&(e===Ht.REPLACE||r.adapter.getActivity(t)===null&&!r.isActivityIdReserved(String(t)))&&!n.has(String(t)))return r.activityIdGen.bump(t),t;let a=r.activityIdGen.next();for(;n.has(String(a))||e===Ht.APPEND&&(r.adapter.getActivity(a)!==null||r.isActivityIdReserved(String(a)));)a=r.activityIdGen.next();return a}function Wb(t,e,n,r){if(t!==void 0&&(e===Ht.REPLACE||r.adapter.getLink(t)===null&&!r.isLinkIdReserved(String(t)))&&!n.has(String(t)))return r.linkIdGen.bump(t),t;let a=r.linkIdGen.next();for(;n.has(String(a))||e===Ht.APPEND&&(r.adapter.getLink(a)!==null||r.isLinkIdReserved(String(a)));)a=r.linkIdGen.next();return a}function Kb(t,e,n){if(hg(t)){let s=n.adapter.activityCount();return new Map(t.items.map((l,c)=>[l.batchId,s+c]))}let r=new Set(Array.from(e.values(),s=>String(s))),i=new Map;for(let s of t.items){let l=e.get(s.batchId);if(l===void 0)continue;let c=typeof s.parent=="string"?s.parent:e.get(s.parent.batchId);if(c===void 0)continue;let d=String(c),u=i.get(d);u||(u={existing:t.mode===Ht.REPLACE||typeof s.parent!="string"&&e.has(s.parent.batchId)?[]:Xa(n.adapter,d).sort((m,A)=>ee(m)-ee(A)||String(m.id).localeCompare(String(A.id))).map(m=>String(m.id)),newIdsByTarget:new Map},i.set(d,u));let p=s.index===void 0?u.existing.length:Math.min(s.index,u.existing.length),y=u.newIdsByTarget.get(p)??[];y.push(String(l)),u.newIdsByTarget.set(p,y)}let a=new Map,o=new Map(Array.from(e,([s,l])=>[String(l),s]));for(let s of i.values()){let l=[];for(let d=0;d<=s.existing.length;d+=1){for(let p of s.newIdsByTarget.get(d)??[])l.push(p);let u=s.existing[d];u!==void 0&&l.push(u)}let c=0;for(;c<l.length;){if(!r.has(l[c])){c+=1;continue}let d=c;for(;c<l.length&&r.has(l[c]);)c+=1;let u=c-d,p=d>0?pg(l[d-1],n):null,y=c<l.length?pg(l[c],n):null;for(let f=0;f<u;f+=1){let m=l[d+f],A=o.get(m);A!==void 0&&a.set(A,Yb(p,y,f+1,u))}}}return a}function hg(t){return t.mode===Ht.APPEND&&t.items.every(e=>e.parent==="0"&&e.index===void 0)}function pg(t,e){let n=e.adapter.getActivity(t);return n?ee(n):0}function Yb(t,e,n,r){return t!==null&&e!==null&&e>t?t+(e-t)*n/(r+1):t!==null?t+n:e!==null?e-(r-n+1):n-1}async function Gb(t,e,n){let r=new Map,i=new Map,a=[];for(let s of e){if(s.parentBatchId===null){a.push(s);continue}let l=r.get(s.parentBatchId)??[];l.push(s),r.set(s.parentBatchId,l)}for(let s=0;s<a.length;s+=1){let l=a[s],c=await $n({kind:I.ACTIVITY_CREATE,parentId:l.parentId,activityId:l.activityId,overrides:l.overrides,...t.eventSource===void 0?{}:{eventSource:t.eventSource}},n,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,skipCacheInvalidation:!0,skipRollupCascades:!0,insertionCorrelativeId:l.insertionCorrelativeId,parentsAlreadyChecked:!0});if(!c.ok)return c;for(let[d,u]of c.removedParentLinks)i.set(d,u);for(let d of r.get(l.input.batchId)??[])a.push(d)}if(a.length!==e.length)return{ok:!1,reason:D.INVALID};let o=new Set;for(let s=a.length-1;s>=0;s-=1){let l=a[s].parentId;l==="0"||o.has(String(l))||(o.add(String(l)),zt(l,n.adapter))}return{ok:!0,removedParentLinks:i}}function yg(t,e){return typeof t=="string"?t:e.get(t.batchId)??null}function qb(t){return new Map(t.adapter.getAllLinks().map(e=>[String(e.id),{...e}]))}function $b(t){return new Map(Array.from(t,([e,n])=>[String(e),n]))}function mg(t,e){let{adapter:n}=e,r=t.activityId,i=n.getActivity(r);if(!i)return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};let a=i.pendingRequestIds??[],o=t.pendingRequests.map(c=>c.id);n.setActivityField(t.activityId,"pendingRequestIds",o);let s=n.getActivity(r);if(!s)return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};let l={id:r,kind:W.UPDATED,fields:{pendingRequestIds:{before:a,after:o}},after:ct(s)};return{ok:!0,changes:{source:t,activities:[l],links:[],calendars:[],trackingEvents:[]}}}function zb(t,e){if(t.activities.length===0)return D.INVALID_VALUE;for(let n of t.activities){let r=e.adapter.getActivity(n.activityId);if(!r)return D.ACTIVITY_NOT_FOUND;let i=Object.keys(n.fields);if(i.length===0||!i.every($s)||zs(r,n.fields))return D.INVALID_VALUE}return null}function Jb(t,e){return Gs(t.activities)?null:e.length===1?e[0]:Pt.ROOTS}function Xb(t,e){for(let n of e.dirty){let r=e.before.get(n);r&&!t.has(n)&&t.set(n,r)}}async function gg(t,e,n){let r=zb(t,n);if(r!==null)return{ok:!1,reason:r};let{adapter:i,scheduler:a,sector:o}=n,s=t.activities.map(u=>String(u.activityId)),l=i.peekWriteCapture(),c=await yt(i,new Set(l?[...s,...l.dirty]:i.getAllIds()));for(let u of t.activities)i.setActivityFields(u.activityId,Js(u.fields));Zs(s,n);let{scheduledIds:d}=await ot({adapter:i,scheduler:a,sector:o,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:Jb(t,s),recomputeParentsFrom:Xs(i,s),recomputeParentProgress:!0,now:n.now,options:e});return l&&Xb(c,l),{ok:!0,changes:await et(i,{source:t,beforeSnap:c,touchedIds:i.getAllIds().filter(u=>c.has(u)),scheduledIds:d,sirDetection:Qt.BEFORE_DIFF,links:[],hoursPerDay:o.hoursPerDay})}}function Zb(t){return t.restoreActivities.length===0&&t.removeActivityIds.length===0&&t.activityFields.length===0&&t.restoreLinks.length===0&&t.removeLinkIds.length===0}function Qb(t,e){if(Zb(t))return D.INVALID_VALUE;let n=new Set(t.restoreActivities.map(r=>String(r.id)));for(let r of t.restoreActivities){if(e.adapter.getActivity(r.id))return D.INVALID_VALUE;let i=r.parentId;if(!G(i)&&!n.has(String(i))&&!e.adapter.getActivity(String(i)))return D.PARENT_NOT_FOUND}for(let r of t.activityFields){let i=e.adapter.getActivity(r.activityId);if(!i)return D.ACTIVITY_NOT_FOUND;let a=Object.keys(r.fields);if(a.length===0||!a.every(qs)||zs(i,r.fields))return D.INVALID_VALUE}return null}function tL(t){let e=new Map(t.map(r=>[String(r.id),r])),n=[];for(;e.size>0;){let r=[...e.values()].filter(i=>!e.has(String(i.parentId)));if(r.length===0)return[...n,...e.values()];for(let i of r)n.push(i),e.delete(String(i.id))}return n}function eL(t){return{id:t.linkId,source:t.source,target:t.target,type:t.type,lag:t.lagHours,freeSlackHours:null,isCritical:!1}}function nL(t){return{id:String(t.id),kind:W.CREATED,fields:{source:{before:void 0,after:String(t.source)},target:{before:void 0,after:String(t.target)},type:{before:void 0,after:t.type},lag:{before:void 0,after:Number(t.lag)}},after:Mt(t)}}function rL(t){return G(t)?null:String(t)}function iL(t,e,n){let r=new Set,i=a=>{let o=rL(a);o!==null&&r.add(o)};for(let a of e)i(n.getActivity(a)?.parentId);for(let a of t.restoreActivities)i(a.parentId);for(let a of t.activityFields)i(n.getActivity(a.activityId)?.parentId),"parentId"in a.fields&&i(a.fields.parentId);return r}function aL(t,e){let n=new Map;for(let r of t){let i=e.getLink(r);i&&(n.set(r,{...i}),e.removeLink(r))}return n}function oL(t,{adapter:e,customIdTracker:n}){for(let r of t){let i=e.getActivity(r)?.customId;typeof i=="string"&&i.length>0&&n.releaseCustomId(i),e.removeActivity(r)}}function sL(t,{adapter:e,customIdTracker:n}){for(let r of tL(t))e.addActivity({...ct(r),proplannerId:null}),n.registerCustomId(r.customId)}function lL(t,{adapter:e,customIdTracker:n}){for(let r of t)"customId"in r.fields&&n.trackCustomIdChange(e.getActivity(r.activityId)?.customId??null,r.fields.customId??null),e.setActivityFields(r.activityId,Js(r.fields))}function cL(t,e){let n=t.filter(r=>!e.getLink(r.linkId)&&e.getActivity(r.source)&&e.getActivity(r.target)).map(eL);for(let r of n)e.addLink(r);return n}function dL(t,e,n){for(let r of Bt(t)){if(e.add(r.activityId),n.has(r.activityId))continue;let i=t.getActivity(r.activityId);if(!i)continue;let a=ct(i);r.before!==void 0&&(a.correlativeId=r.before),n.set(r.activityId,a)}}async function Ag(t,e,n){let r=Qb(t,n);if(r!==null)return{ok:!1,reason:r};let{adapter:i,scheduler:a,sector:o}=n;a.invalidateAllCaches();let s=Wi(t.removeActivityIds.filter(m=>i.getActivity(m)),i),l=iL(t,s,i),c=new Set([...s,...t.activityFields.map(m=>String(m.activityId)),...[...l].filter(m=>i.getActivity(m))]),d=await yt(i,c),u=aL(new Set([...t.removeLinkIds,...Jn(s,i)]),i);oL(s,n),sL(t.restoreActivities,n);for(let m of t.restoreActivities)c.add(String(m.id));lL(t.activityFields,n),Zs(t.activityFields.map(m=>String(m.activityId)),n);let p=cL(t.restoreLinks,i),y=[...l].filter(m=>i.getActivity(m));for(let m of y)zt(m,i);dL(i,c,d);let{scheduledIds:f}=await ot({adapter:i,scheduler:a,sector:o,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:Pt.ROOTS,recomputeParentsFrom:[...y,...Xs(i,t.activityFields.map(m=>String(m.activityId)))],recomputeParentProgress:!0,now:n.now,options:e});return{ok:!0,changes:await et(i,{source:t,beforeSnap:d,touchedIds:c,scheduledIds:f,sirDetection:Qt.BEFORE_DIFF,links:[...ne(u),...p.map(nL)],hoursPerDay:o.hoursPerDay})}}var Ig=new Map;function Sg(t){let e=new Map;for(let n of t){let r=n.proplannerId;typeof r=="number"&&Number.isSafeInteger(r)&&r>0&&e.set(r,String(n.id))}return e}function vg(t,e,n){let r=new Set(e.map(({id:i})=>String(i)));for(let i of t)if((i.proplannerId==null||i.proplannerId===0)&&!r.has(String(i.id)))throw new Error(`persistence-acknowledge: missing ${n} proplannerId for "${String(i.id)}"`)}function uL(t,e,n,r,i,a){let o=String(t.id);if(o.length===0||i.has(o))throw new Error(`persistence-acknowledge: duplicate or empty ${e} id "${o}"`);if(!Number.isSafeInteger(t.proplannerId)||t.proplannerId<=0)throw new Error(`persistence-acknowledge: invalid ${e} proplannerId ${String(t.proplannerId)}`);if(a.has(t.proplannerId))throw new Error(`persistence-acknowledge: duplicate ${e} proplannerId ${String(t.proplannerId)}`);let s=n(o);if(!s.exists)throw new Error(`persistence-acknowledge: unknown ${e} id "${o}"`);if(s.current!==null&&s.current!==0&&s.current!==t.proplannerId)throw new Error(`persistence-acknowledge: ${e} "${o}" already has proplannerId ${String(s.current)}`);let l=r.get(t.proplannerId);if(l!==void 0&&l!==o)throw new Error(`persistence-acknowledge: ${e} proplannerId ${String(t.proplannerId)} already belongs to "${l}"`);i.add(o),a.add(t.proplannerId)}function Cg(t,e,n,r){let i=new Set,a=new Set;for(let o of t)uL(o,e,n,r,i,a)}async function Dg(t,e){let n=t.filter(s=>{let l=e.adapter.getActivity(String(s.activityId));return l!==null&&l.progress!==s.progress}),r=new Set(n.map(s=>String(s.activityId))),i=Sa(e.adapter,r),a=new Set(r);for(let s of i)a.add(String(s));let o=await yt(e.adapter,a);return e.adapter.batchUpdate(()=>{for(let s of n){let l=String(s.activityId);e.adapter.setActivityField(l,"progress",s.progress),e.adapter.setActivityField(l,"autoScheduling",ye(s.progress))}yy(i,e.adapter),qm(r,i,e.adapter)}),[...await os(e.adapter,o,a)]}async function Tg(t,e){let n=t.activities??[],r=t.links??[],i=t.checkpoint?.activities??e.adapter.getAllActivities(),a=t.checkpoint?.links??e.adapter.getAllLinks(),o=new Map(i.map(y=>[String(y.id),y])),s=new Map(a.map(y=>[String(y.id),y])),l=t.checkpoint?.pending!==void 0,c=n.length===0?Ig:Sg(l?e.adapter.getAllActivities():i),d=r.length===0?Ig:Sg(l?e.adapter.getAllLinks():a);Cg(n,"activity",y=>{let f=o.get(y);return{exists:f!==void 0,current:f?.proplannerId??null}},c),Cg(r,"link",y=>{let f=s.get(y);return{exists:f!==void 0,current:f?.proplannerId??null}},d),vg(i,n,"activity"),vg(a,r,"link");let u=[],p=[];return e.adapter.batchUpdate(()=>{for(let y of n){let f=e.adapter.getActivity(y.id);if(!f||f.proplannerId===y.proplannerId)continue;let m=f.proplannerId;e.adapter.setActivityField(y.id,"proplannerId",y.proplannerId),u.push({id:y.id,kind:W.UPDATED,fields:{proplannerId:{before:m,after:y.proplannerId}},after:{...f,proplannerId:y.proplannerId}})}for(let y of r){let f=e.adapter.getLink(y.id);if(!f||f.proplannerId===y.proplannerId)continue;let m=f.proplannerId;e.adapter.setLinkProplannerId(y.id,y.proplannerId),p.push({id:y.id,kind:W.UPDATED,fields:{proplannerId:{before:m,after:y.proplannerId}},after:{...f,proplannerId:y.proplannerId}})}}),{ok:!0,changes:{source:t,activities:u,links:p,calendars:[],trackingEvents:[]}}}async function _g(t,e,n){if(pL(t))return{ok:!1,reason:D.INVALID_VALUE};let r=[...new Set(t.activityIds.map(String))];if(t.acknowledgePersistedLookahead===!0&&r.some(s=>!n.isActivityPersisted(s)))return{ok:!1,reason:D.INVALID};let a=r.map(s=>n.adapter.getActivity(s));if(a.some(s=>!s))return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};let o=[];for(let[s,l]of r.entries()){let c=a[s];if(!c)continue;let d={};c.isLookahead!==t.isLookahead&&(d.isLookahead={before:c.isLookahead,after:t.isLookahead},n.adapter.setActivityField(l,"isLookahead",t.isLookahead)),c.hasLookaheadTasks!==t.hasLookaheadTasks&&(d.hasLookaheadTasks={before:c.hasLookaheadTasks,after:t.hasLookaheadTasks},n.adapter.setActivityField(l,"hasLookaheadTasks",t.hasLookaheadTasks)),Object.keys(d).length!==0&&o.push({id:l,kind:W.UPDATED,fields:d,after:{...c,isLookahead:t.isLookahead,hasLookaheadTasks:t.hasLookaheadTasks}})}return t.persistedProgress!==void 0&&(await Dg([{activityId:r[0],progress:t.persistedProgress}],n)).length>0?(await ot({adapter:n.adapter,scheduler:n.scheduler,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:t.persistedProgress===0?r[0]:null,recomputeParentsFrom:[],now:n.now,options:e}),{ok:!0,changes:await et(n.adapter,{source:t,beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:n.sector.hoursPerDay})}):{ok:!0,changes:{source:t,activities:o,links:[],calendars:[],trackingEvents:[]}}}function pL(t){let e=t.persistedProgress;return e!==void 0&&(t.activityIds.length!==1||!Number.isFinite(e)||e<0||e>100)}function Rg(t,e){let n=new Map(t.map(a=>[a.id,ct(a)])),r=new Map;for(let a of t){if(a.parentId===null)continue;let o=r.get(a.parentId)??[];o.push(a),r.set(a.parentId,o)}let i=new Map;for(let a of[...t].reverse()){let o=r.get(a.id)??[],s=o.length>0,l=s?o.reduce((f,m)=>f+Eg(i,m.id),0):yL(a,e);if(i.set(a.id,l),!s)continue;let c=l>0,d=e!==Tt.COST;for(let f of o){let m=tu(n,f.id),A=c?100*Eg(i,f.id)/l:d?100/o.length:0;n.set(f.id,{...m,ponderator:A})}let u=o.map(f=>tu(n,f.id)),p=li(u),y=tu(n,a.id);n.set(a.id,{...y,progress:Ko(p??0)})}return n}function yL(t,e){return t.type===H.PROJECT?0:e===Tt.COST?t.cost:e===Tt.WORK_HOURS?t.workHours:t.durationHours}function Eg(t,e){let n=t.get(e);if(n===void 0)throw new Error(`Missing conversion magnitude ${e}`);return n}function tu(t,e){let n=t.get(e);if(!n)throw new Error(`Missing conversion snapshot ${e}`);return n}function nu(t,e){let{adapter:n}=e,r=new Set(t.conversionRootIds.map(p=>String(p)));if(r.size===0)throw new Error("Conversion requires at least one root");for(let p of r)DL(p,n);let i=n.getVisualOrderIds().filter(p=>r.has(p)&&!zn(p,r,n)),a=i.map(p=>fL(p,n,t.criterion??e.sector.activityCreter??Tt.DURATION)),o=a.map(({conversionRootId:p,convertedActivities:y})=>({conversionRootId:p,convertedActivities:y})),s=a.flatMap(p=>p.milestoneMoves),l=a.flatMap(p=>p.activityIdsToDelete),c=a.map(p=>p.formerParent),d=new Set(l),u=Jn(d,n);return{sourceStateRevision:e.stateRevision,conversionRootIds:i,conversionGroups:o,milestoneMoves:s,activityIdsToDelete:l,linkIdsToDelete:u,formerParents:c}}async function bg(t,e,n){if(t.expectedStateRevision!==n.stateRevision)return{ok:!1,reason:D.STALE_STATE_REVISION};let r=nu(t,n);if(!TL(r,n.adapter))return{ok:!1,reason:D.HIERARCHY_CYCLE};let{adapter:i,scheduler:a}=n;a.invalidateAllCaches();let o=await AL(r,i);IL(r,n),Lg(r,i),SL(r,o.deletedIds,i);let s=vL(r,i),l=Ie(i,s,o.deletedIds,o.beforeSnap,o.touchedIds),{scheduledIds:c}=await ot({adapter:i,scheduler:a,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:"roots",recomputeParentsFrom:o.touchedIds,now:n.now,options:e,recomputeParentProgress:!0}),d=await et(i,{source:t,beforeSnap:o.beforeSnap,touchedIds:o.touchedIds,scheduledIds:c,sirDetection:"after-diff",links:ne(o.beforeLinks),hoursPerDay:n.sector.hoursPerDay,correlativeShifts:s,deferredCorrelatives:l});return CL(r,o,d)}function fL(t,e,n){let r=eu(t,e),i=Wi([t],e);if(i.delete(t),i.size===0)throw new Error(`Conversion root ${t} has no descendants`);let a=e.getVisualOrderIds().filter(u=>i.has(u)).map(u=>eu(u,e));kg(r);for(let u of a)kg(u);let o=a.filter(u=>u.type!==H.MILESTONE),s=a.filter(u=>u.type===H.MILESTONE),l=hL(r,o),c=Rg([r,...o],n),d=c.get(r.id);if(!d)throw new Error(`Missing conversion snapshot ${r.id}`);return{conversionRootId:t,convertedActivities:[...c.values()].filter(u=>u.id!==t).map(u=>mL(u,l)),milestoneMoves:gL(r,s),activityIdsToDelete:o.map(u=>u.id),formerParent:{activity:d,hasConvertedActivities:o.length>0}}}function hL(t,e){let n=new Map;e.length>0&&n.set(t.id,Pg(t));for(let r of e)n.set(r.id,Pg(r));return n}function mL(t,e){let n=ct(t),r=pe(t.parentId),i=e.get(r);return n.parentId=i===void 0?null:String(i),n}function gL(t,e){let n=[],r=pe(t.parentId),i=t.id;for(let a of e)n.push({activityId:a.id,parentId:r,afterSiblingId:i}),i=a.id;return n}async function AL(t,e){let n=new Set(t.activityIdsToDelete),r=new Set([...t.conversionRootIds,...t.activityIdsToDelete,...t.milestoneMoves.map(({activityId:i})=>i),...t.milestoneMoves.map(({parentId:i})=>i).filter(i=>i!=="0")]);return{deletedIds:n,touchedIds:r,beforeSnap:await yt(e,r),beforeLinks:_L(t.linkIdsToDelete,e),viewStateChanges:Mr(e,n)}}function IL(t,e){for(let n of t.activityIdsToDelete){let r=e.adapter.getActivity(n)?.customId;r&&e.customIdTracker.releaseCustomId(r)}}function Lg(t,e){for(let n of t.milestoneMoves)e.setActivityFields(n.activityId,{parentId:n.parentId,correlativeId:ji(e,n.parentId,n.afterSiblingId,void 0)});for(let n of t.linkIdsToDelete)e.removeLink(n);for(let n of[...t.activityIdsToDelete].reverse())e.removeActivity(n);for(let{activity:n}of t.formerParents)e.setActivityField(n.id,b.TYPE,H.TASK)}function SL(t,e,n){for(let{activity:r,hasConvertedActivities:i}of t.formerParents){let a=eu(r.id,n),o=gl({parent:a,idsRemoved:e});n.setActivityFields(r.id,{progress:r.progress,isLookahead:r.isLookahead||i,hasLookaheadTasks:r.hasLookaheadTasks||i,...o?.fields??{}}),n.setProgressFallback(r.id,null)}}function vL(t,e){for(let{activity:n}of t.formerParents)zt(n.parentId,e);return Bt(e)}function CL(t,e,n){let r=new Map;for(let i of e.deletedIds){let a=e.beforeSnap.get(i);a&&r.set(i,a)}return{ok:!0,changes:e.viewStateChanges.length===0?n:{...n,viewState:e.viewStateChanges},conversionGroups:t.conversionGroups.map(({conversionRootId:i,convertedActivities:a})=>({conversionRootId:i,convertedActivities:a.map(o=>ct(o))})),__beforeSnap:r,__beforeLinks:e.beforeLinks}}function DL(t,e){let n=e.getActivity(t);if(!n)throw new Error(`Conversion root ${t} was not found`);if(n.type===H.PROJECT&&n.correlativeId===0)throw new Error(`Conversion root ${t} is the visual project root`)}function eu(t,e){let n=e.getActivity(t);if(!n)throw new Error(`Conversion activity ${t} is missing`);return n}function Pg(t){if(t.proplannerId==null)throw new Error(`Conversion activity ${t.id} has no persisted identifier`);return t.proplannerId}function kg(t){if(!Number.isFinite(t.startDate.getTime()))throw new Error(`Conversion activity ${t.id} has invalid startDate`);if(!Number.isFinite(t.endDate.getTime()))throw new Error(`Conversion activity ${t.id} has invalid endDate`)}function TL(t,e){let n=e.fork();return Lg(t,n),Di({port:e,proposedPort:n,currentLinks:e.getAllLinks(),proposedLinks:n.getAllLinks()}).ok}function _L(t,e){let n=new Map;for(let r of t){let i=e.getLink(r);i&&n.set(r,{...i})}return n}function Yi(t,e){let n=new Set;for(let i of t)n.add(String(i));let r=[];for(let i of e.getAllLinks()){let a=String(i.source),o=String(i.target);!n.has(a)&&!n.has(o)||Ng(i,e)&&r.push(String(i.id))}return r}function Ng(t,e){let n=String(t.source),r=String(t.target);return Og(r,n,e)||Og(n,r,e)}function Al(t,e){return[...t].filter(([,n])=>Ng(n,e)).map(([n])=>String(n))}function Og(t,e,n){let r=String(t),i=new Set;for(;r!=null;){if(i.has(r))return!1;i.add(r);let a=n.getActivity(r);if(!a)return!1;let o=a.parentId;if(o===null||G(o))return!1;let s=o;if(s===e)return!0;r=s}return!1}async function Fg(t,e,n){let{adapter:r,scheduler:i,sector:a}=n;i.invalidateAllCaches();let o=r.getActivity(t.activityId);if(!o)return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};let s=G(t.parentId);if(!s&&!r.getActivity(t.parentId))return{ok:!1,reason:D.PARENT_NOT_FOUND};if(!s&&(t.parentId===t.activityId||r.isChildOf(t.parentId,t.activityId)))return{ok:!1,reason:D.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(t.afterSiblingId!==void 0&&t.beforeSiblingId!==void 0)return{ok:!1,reason:D.ANCHOR_SIBLING_CONFLICT};let l=t.afterSiblingId??t.beforeSiblingId;if(l!==void 0){let S=r.getActivity(l);if(!S)return{ok:!1,reason:D.ANCHOR_SIBLING_NOT_FOUND};if((S.parentId===null?"0":String(S.parentId))!==t.parentId)return{ok:!1,reason:D.ANCHOR_SIBLING_WRONG_PARENT}}let c=o.parentId,d=pe(c),u=String(t.parentId),p=d!==u;if(p){let S=new Map([[t.activityId,s?null:t.parentId]]);if(Bi(r,S))return{ok:!1,reason:D.HIERARCHY_CYCLE}}if(p&&!s){let S=yn(fn([t.parentId],r),e);if(S)return S}let y=new Set([t.activityId]);p?(d!=="0"&&y.add(d),u!=="0"&&y.add(u)):d!=="0"&&y.add(d);let f=await yt(r,y),m=new Map;p&&r.setActivityField(t.activityId,b.PARENT,u);let A=ji(r,t.parentId,t.afterSiblingId,t.beforeSiblingId);if(r.setActivityField(t.activityId,b.CORRELATIVE_ID,A),p){if(!s){let S=r.getActivity(t.parentId);if(S){let k=kn(S.type)&&r.getChildren(t.parentId).filter(U=>U!==t.activityId).length===0,F=Xn({parentId:t.parentId,newChildId:t.activityId,isCurrentlyLeaf:k,promotionSource:Ki.REPARENT},n);if(F.applied)for(let[U,w]of F.removedLinks)m.set(U,w)}}if(d!=="0"){let S=r.getActivity(d);if(S){let k=r.getChildren(d),F=Qe({parent:S,remainingChildIds:k.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:r.getPromotionSnapshot(d),computeEndDate:(U,w)=>r.calculateEndDate({startDate:U,durationHours:w,task:S}),idsRemoved:new Set([t.activityId]),dataDateCapability:n.dataDateCapability,hasCompleteSchedulingState:n.hasCompleteSchedulingState});if(F){r.setActivityFields(d,F.fields);let U=Oe(d,r),w=U?r.getActivity(U)?.customId:null,M=typeof w=="string"&&w?w:null,$=n.customIdTracker.generateCustomIdForRestoredChild(M);r.setActivityField(d,b.CUSTOM_ID,$)}}}}p&&(d!=="0"&&zt(d,r),s||zt(t.parentId,r));let g=Ie(r,Bt(r),mi,f,y),R=p&&d!=="0"?r.getChildren(d).map(String):[],{scheduledIds:P}=await ot({adapter:r,scheduler:i,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:t.activityId,recomputeParentsFrom:[t.activityId,t.parentId,...R],now:n.now,options:e,recomputeParentProgress:p}),N=p?Yi([t.activityId],r):[],T=Al(m,r),x={name:Le.ACTIVITY_MOVE,properties:{activity_id:t.activityId,new_parent_id:t.parentId,after_sibling_id:t.afterSiblingId??null,before_sibling_id:t.beforeSiblingId??null,invalid_link_ids:[...new Set([...T,...N.map(String)])]}};return t.eventSource!==void 0&&(x.properties.event_source=t.eventSource),{ok:!0,changes:await et(r,{source:t,beforeSnap:f,deferredCorrelatives:g,touchedIds:y,scheduledIds:P,sirDetection:Qt.BEFORE_DIFF,links:ne(m),trackingEvents:[x],hoursPerDay:a.hoursPerDay}),...m.size>0?{__beforeLinks:m}:{}}}async function wg(t,e,n){let{adapter:r,scheduler:i,sector:a}=n;if(i.invalidateAllCaches(),t.activityIds.length===0)return{ok:!1,reason:D.ACTIVITY_IDS_EMPTY};let o=new Set,s=[],l=Vi(t.activityIds,r),c=[...l.failed];for(let x of l.moves)o.add(String(x.activityId)),o.add(String(x.newParentId)),x.oldParentId!=="0"&&o.add(String(x.oldParentId));let d=l.allowedMoves,u=yn(fn(d.map(x=>x.newParentId),r),e);if(u)return u;let p=await yt(r,o);for(let{activityId:x,newParentId:S}of d)r.setActivityField(x,b.PARENT,S),r.setActivityField(x,b.CORRELATIVE_ID,ng),s.push(x);let y=new Set,f=new Map;for(let{activityId:x,newParentId:S}of d){if(y.has(S))continue;y.add(S);let k=r.getActivity(S);if(!k)continue;let F=k.customId,U=kn(k.type)&&r.getChildren(S).filter($=>!s.includes($)).length===0,w=k.hasNewActivities&&k.newActivityIds.some($=>String($)===String(x)),M=Xn({parentId:S,newChildId:x,isCurrentlyLeaf:U,promotionSource:Ki.REPARENT},n);if(M.applied){for(let[$,st]of M.removedLinks)f.set($,st);w||(r.setActivityField(S,b.HAS_NEW_ACTIVITIES,!1),r.setActivityField(S,b.NEW_ACTIVITIES_ARRAY,[]))}r.setActivityField(S,b.CONSTRAINT_TYPE,_.ASAP),r.setActivityField(S,b.CONSTRAINT_DATE,null),r.setActivityField(S,b.CUSTOM_ID,null),M.applied||km(F,n.customIdTracker)}let m=new Set;for(let x of d)x.oldParentId!=="0"&&m.add(x.oldParentId),m.add(x.newParentId);for(let x of m)zt(x,r);let A=Ie(r,Bt(r),mi,p,o),g=Al(f,r),R=Yi(s,r);for(let x of R){let S=r.getLink(x);S&&(f.set(x,{...S}),r.removeLink(x))}let{scheduledIds:P}=await ot({adapter:r,scheduler:i,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:null,recomputeParentsFrom:s,now:n.now,options:e}),N={name:Le.ACTIVITY_INDENT,properties:{activity_ids:s,failed:c.map(x=>({activity_id:x.activityId,reason:x.reason})),invalid_link_ids:[...new Set([...g,...R.map(String)])]}};t.eventSource!==void 0&&(N.properties.event_source=t.eventSource);let T=await et(r,{source:t,beforeSnap:p,deferredCorrelatives:A,touchedIds:o,scheduledIds:P,links:ne(f),trackingEvents:[N],hoursPerDay:a.hoursPerDay});return{ok:!0,activityVerdicts:t.activityIds.map(x=>{let S=c.find(k=>String(k.activityId)===String(x));return S?{activityId:String(x),ok:!1,reason:S.reason}:{activityId:String(x),ok:!0}}),changes:T,__beforeLinks:f}}async function xg(t,e,n){let{adapter:r,scheduler:i,sector:a}=n;if(i.invalidateAllCaches(),t.activityIds.length===0)return{ok:!1,reason:D.ACTIVITY_IDS_EMPTY};let o=new Set(t.activityIds),s=new Map,l=new Map;for(let S of t.activityIds){let k=S;r.getActivity(k)&&(s.set(k,Fc(k,r)),l.set(k,rg(k,o,r)))}let c=new Set,d=[],u=[],p=new Set,y=[],f=new Set,m=[...t.activityIds].sort((S,k)=>{let F=r.getActivity(S),U=r.getActivity(k),w=F?ee(F):xr,M=U?ee(U):xr;return w-M});for(let S of m){let k=S,F=r.getActivity(k);if(!F){d.push({activityId:k,reason:D.ACTIVITY_NOT_FOUND});continue}if(zn(k,f,r))continue;let U=F.parentId;if(G(U)){d.push({activityId:k,reason:D.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let w=String(U),M=r.getActivity(w);if(!M){d.push({activityId:k,reason:D.ACTIVITY_NOT_FOUND});continue}let $=M.parentId;if(G($)){d.push({activityId:k,reason:D.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let st=String($),at=Fc(w,r)+1,Ct=l.get(k);if(Ct!=null&&o.has(Ct)){let L=s.get(Ct)??-1,K=s.get(k)??-1;L>=0&&K>=0&&(at+=K-L)}y.push({activityId:k,grandparentKey:st,oldParentKey:w,targetIndexInGrandparent:at}),f.add(k),c.add(String(k)),c.add(String(w)),st!=="0"&&c.add(String(st)),p.add(w)}let A=hl(y.map(S=>({activityId:S.activityId,newParentId:S.grandparentKey})),r);for(let S of A)d.push({activityId:S,reason:D.HIERARCHY_CYCLE});let g=y.filter(S=>!A.has(S.activityId)),R=await yt(r,c);for(let S of g){r.setActivityField(S.activityId,b.PARENT,S.grandparentKey);let k=ig(r,S.grandparentKey,S.targetIndexInGrandparent,S.activityId);r.setActivityField(S.activityId,b.CORRELATIVE_ID,k),u.push(S.activityId)}for(let S of p){let k=r.getActivity(S);if(!k)continue;let F=r.getChildren(S),U=Qe({parent:k,remainingChildIds:F.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:r.getPromotionSnapshot(S),computeEndDate:(at,Ct)=>r.calculateEndDate({startDate:at,durationHours:Ct,task:k}),idsRemoved:new Set(g.filter(at=>at.oldParentKey===S).map(at=>at.activityId)),dataDateCapability:n.dataDateCapability,hasCompleteSchedulingState:n.hasCompleteSchedulingState});if(!U){Go(S,r);continue}r.setActivityFields(S,U.fields);let w=Oe(S,r),M=w?r.getActivity(w)?.customId:null,$=typeof M=="string"&&M?M:null,st=n.customIdTracker.generateCustomIdForRestoredChild($);r.setActivityField(S,b.CUSTOM_ID,st)}let P=new Set;for(let S of p)P.add(String(S));for(let S of g)S.grandparentKey!=="0"&&P.add(String(S.grandparentKey));for(let S of P)zt(S,r);let N=Ie(r,Bt(r),mi,R,c),{scheduledIds:T}=await ot({adapter:r,scheduler:i,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:u.length>0?Pt.ROOTS:null,recomputeParentsFrom:u,now:n.now,options:e}),x={name:Le.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(S=>({activity_id:String(S.activityId),reason:S.reason}))}};return t.eventSource!==void 0&&(x.properties.event_source=t.eventSource),{ok:!0,activityVerdicts:t.activityIds.map(S=>{let k=d.find(F=>String(F.activityId)===String(S));return k?{activityId:String(S),ok:!1,reason:k.reason}:{activityId:String(S),ok:!0}}),changes:await et(r,{source:t,beforeSnap:R,deferredCorrelatives:N,touchedIds:c,scheduledIds:T,trackingEvents:[x],hoursPerDay:a.hoursPerDay})}}async function Mg(t,e,n){let{adapter:r,scheduler:i,sector:a}=n,o=r.getActivity(t.activityId);if(!o)return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};if(!ma(t.type))return{ok:!1,reason:D.INVALID_VALUE};let s=r.getChildren(t.activityId),l=t.type===H.PROJECT;if(l!==s.length>0)return{ok:!1,reason:D.INVALID_VALUE};let c=new Set(r.getAllIds()),d=await yt(r,c);i.invalidateAllCaches();let u=l&&o.type!==H.PROJECT?Xn({parentId:t.activityId,newChildId:s[0],isCurrentlyLeaf:!0},n).removedLinks:new Map;!l&&o.type===H.PROJECT&&EL(t.activityId,n),t.type!==H.PROJECT?(RL(t.activityId,t.type,n),PL(t.activityId,n)):zt(t.activityId,r);let p=kL(t.activityId,n);for(let[f,m]of u)p.set(f,m);let{scheduledIds:y}=await ot({adapter:r,scheduler:i,sector:a,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:t.activityId,recomputeParentsFrom:[t.activityId],recomputeParentProgress:!0,now:n.now,options:e});return{ok:!0,changes:await et(r,{source:t,beforeSnap:d,touchedIds:c,scheduledIds:y,sirDetection:Qt.BEFORE_DIFF,links:ne(p),hoursPerDay:a.hoursPerDay}),__beforeLinks:new Map(p)}}function EL(t,e){let n=e.adapter.getActivity(t);if(!n)return;let r=Qe({parent:n,remainingChildIds:[],defaultDurationHours:e.sector.hoursPerDay,promotionSnapshot:e.adapter.getPromotionSnapshot(t),computeEndDate:(i,a)=>e.adapter.calculateEndDate({startDate:i,durationHours:a,task:n}),dataDateCapability:e.dataDateCapability,hasCompleteSchedulingState:e.hasCompleteSchedulingState});r&&e.adapter.setActivityFields(t,r.fields)}function RL(t,e,n){let r=n.adapter.getActivity(t);if(!r)return;n.adapter.setActivityField(t,b.TYPE,e);let i=e===H.MILESTONE?0:r.durationHours===0?n.sector.hoursPerDay:r.durationHours;i!==r.durationHours&&n.adapter.setActivityField(t,b.DURATION_HOURS,i);let a=n.adapter.getActivity(t);if(!a)return;let o=n.adapter.calculateEndDate({startDate:a.startDate,durationHours:i,task:a});n.adapter.setActivityField(t,b.END_DATE,o)}function PL(t,e){if(e.adapter.getActivity(t)?.customId)return;let r=Oe(t,e.adapter),i=r?e.adapter.getActivity(r)?.customId:null,a=e.customIdTracker.generateCustomIdForRestoredChild(i||null);e.adapter.setActivityField(t,b.CUSTOM_ID,a)}function kL(t,e){let n=new Map;for(let r of Yi([t],e.adapter)){let i=e.adapter.getLink(r);i&&(n.set(String(r),{...i}),e.adapter.removeLink(r))}return n}async function Ug(t,e,n){let{adapter:r,ctx:i,scheduler:a,sector:o}=n;if(t.newValue!==0&&t.newValue!==100)return{ok:!1,reason:D.INVALID_PROGRESS_VALUE};let s=i.activityReader.getActivity(t.activityId);if(!s)return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};let l=ge(E.PROGRESS);if(!l)throw new Error("[ScheduleCore] progressPipeline not registered \u2014 cannot dispatch activity-set-progress");let c=l.canEdit(s,i.hierarchy);if(!c.allowed&&!OL(t,c))return{ok:!1,reason:c.reason,...c.alertKey?{alertKey:c.alertKey}:{}};let d=l.transform(s,t.newValue,i,t.newValue),u=Um(s,t.newValue,c.allowed?d:null,n,e.confirmations);if(u!==null&&!u.accepted)return NL(u);let p=u===null?d:u.changes,y=u===null||c.allowed,f=Un(t.activityId,p),m=await yt(r,f);Hn(r,t.activityId,p),y&&hy(t.activityId,t.newValue,r),bn(t.activityId,p.postProcessors??[],r);let A=bL(t.activityId,p,n),{scheduledIds:g}=await ot({adapter:r,scheduler:a,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:A,recomputeParentsFrom:[],collectDirty:R=>ss(t.activityId,f,R),now:n.now,options:e});return{ok:!0,changes:await et(r,{source:t,beforeSnap:m,touchedIds:f,scheduledIds:g,trackingEvents:LL(p),hoursPerDay:o.hoursPerDay})}}function bL(t,e,n){return e.needsAutoSchedule?n.ctx.hierarchy.hasChildren(t)?Pt.ROOTS:t:null}function LL(t){return(t.trackingEvents??[]).map(e=>({name:e.name,properties:e.properties??{}}))}function OL(t,e){return t.origin===ns.ACTION_BUTTON&&(e.reason===He.HAS_LOOKAHEAD_TASKS||e.reason===He.SUMMARY)}function NL(t){return{ok:!1,reason:t.reason,...t.alertKey?{alertKey:t.alertKey}:{},...t.confirmation?{confirmation:t.confirmation}:{}}}function FL(t){return t===E.START_DATE||t===E.END_DATE}async function Hg(t,e,n){let r=wL(t,n);if(r!==null)return{ok:!1,reason:r};let{adapter:i,scheduler:a,sector:o}=n,s=[],l=new Map,c=new Set,d=[],u=[],p=[],y=!1;for(let m of t.edits){let A=xL(m,n,e);if(s.push(A.verdict),!A.verdict.ok||!A.changes)continue;let g=Un(m.activityId,A.changes);ML(l,g,n);for(let T of g)c.add(T);let R=wi(i,m.activityId),P=as(i,String(m.activityId));Hn(i,m.activityId,A.changes),bn(m.activityId,A.changes.postProcessors??[],i,P),u.push(...xi(R,i,m.activityId)),y||=!!A.changes.needsAutoSchedule;for(let T of A.changes.trackingEvents??[])d.push({name:T.name,properties:T.properties??{}});let N=Tr(m.activityId,A.changes.constraintWarning);N&&p.push(N)}let{scheduledIds:f}=await ot({adapter:i,scheduler:a,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:y?Pt.ROOTS:null,recomputeParentsFrom:c,now:n.now,options:e});return{ok:!0,verdicts:s,changes:await et(i,{source:t,beforeSnap:l,touchedIds:c,scheduledIds:f,sirDetection:Qt.BEFORE_DIFF,links:u,trackingEvents:d,warnings:p,hoursPerDay:o.hoursPerDay})}}function wL(t,e){return t.edits.some(i=>!FL(i.column))?D.INVALID_VALUE:t.edits.some(i=>e.ctx.activityReader.getActivity(i.activityId)===null)?D.ACTIVITY_NOT_FOUND:null}function xL(t,e,n){let{ctx:r}=e,i=t.activityId,a=ge(t.column);if(!a)throw new Error(`[ScheduleCore] no pipeline registered for column "${t.column}"`);let o=r.activityReader.getActivity(t.activityId);if(!o)throw new Error(`[ScheduleCore] activity "${t.activityId}" not found`);let s=Hi(a,o,e,t.column);if(!s.allowed)return{verdict:{activityId:i,ok:!1,reason:s.reason??D.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let l=a.parseInput(t.newValue,o,r);if(!l.ok)return{verdict:{activityId:i,ok:!1,reason:l.reason??D.PARSE_ERROR},changes:null};let c=Reflect.get(o,a.targetField),d=a.validate(o,c,l.value,r);if(!d.valid)return{verdict:{activityId:i,ok:!1,reason:d.reason??D.INVALID,...d.notification?.messageKey?{alertKey:d.notification.messageKey}:{}},changes:null};let u=a.transform(o,l.value,r,l.raw),p=wr(o,u,e,t.column,n.confirmations);return p.accepted?{verdict:{activityId:i,ok:!0},changes:p.changes}:{verdict:{activityId:i,ok:!1,reason:p.reason,...p.alertKey?{alertKey:p.alertKey}:{},...p.confirmation?{confirmation:p.confirmation}:{}},changes:null}}function ML(t,e,n){let r=new Set;for(let i of e)t.has(i)||r.add(i);if(r.size!==0)for(let i of r){let a=n.adapter.getActivity(i);a&&t.set(i,ct(a))}}var ru=E.CUSTOM_ID,UL="sir-apply";async function Il(t,e,n){let{adapter:r,scheduler:i,sector:a}=n,o=[],s=new Map,l=new Map,c=new Set,d=new Set,u=[],p=[],y=[],f=new Set,m=new Map,A=new Map,g=!1,R=Mm(t.edits,n),P=Gd(t.edits),N=JL(t.edits);for(let U of xm(t)){let w=U[0],M=R.get(String(w.activityId));if(M!==void 0&&(w.column===E.START_DATE||w.column===E.END_DATE)){o.push({activityId:w.activityId,ok:!1,reason:M.reason,...M.alertKey?{alertKey:M.alertKey}:{}});continue}let st=GL(U,n,t.eventSource,e,P,N);for(let X of U)o.push(st.verdict);if(!st.verdict.ok||!st.changes)continue;let at=Tr(w.activityId,st.changes.constraintWarning);at&&y.push(at);let Ct=Un(w.activityId,st.changes);XL(s,Ct,n);for(let X of Ct)d.add(X);zL(l,w,s),il(w.column)&&c.add(String(w.activityId)),jL(m,w);let L=wi(r,w.activityId),K=as(r,String(w.activityId)),dt=qL(w,n),lt=st.changes;Hn(r,w.activityId,lt),bn(w.activityId,st.changes.postProcessors??[],r,K),HL(f,y,w),BL(A,w,r.getActivity(w.activityId)),$L(w,dt,n),p.push(...xi(L,r,w.activityId)),g||=!!st.changes.needsAutoSchedule;for(let X of st.changes.trackingEvents??[])u.push({name:X.name,properties:X.properties??{}})}let T=t.eventSource===UL?o.find(U=>!U.ok&&U.reason!==Sr.UNCHANGED):void 0;if(T&&!T.ok)return{ok:!1,reason:T.reason??D.INVALID,...T.alertKey?{alertKey:T.alertKey}:{}};let x={action:t,autoscheduleFrom:g?Pt.ROOTS:null,recomputeParentsFrom:d,now:n.now,options:e},S=VL(m,A,s,y,f,n),k=l.size>0,{scheduledIds:F}=await(k?ol({adapter:r,scheduler:i,sector:a,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{postMutationArgs:x,revertTargets:[...l].filter(([U])=>!c.has(U)).map(([U,w])=>({activityId:U,priorConstraintDate:w})),revert:(U,w)=>al(U,w,r,n.ctx.calendars)}):ot({adapter:r,scheduler:i,sector:a,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},x));return{ok:!0,verdicts:o,changes:await et(r,{source:t,beforeSnap:s,touchedIds:d,scheduledIds:F,sirDetection:Qt.BEFORE_DIFF,links:p,trackingEvents:u,warnings:S,hoursPerDay:a.hoursPerDay})}}function HL(t,e,n){if(!Ni(n.column))return;let r=String(n.activityId);for(let i of e)String(i.activityId)===r&&t.add(i)}function BL(t,e,n){!Ni(e.column)||!n||t.set(String(e.activityId),{constraintType:n.constraintType,constraintDate:n.constraintDate?new Date(n.constraintDate.getTime()):null})}function jL(t,e){if(e.column!==E.START_DATE&&e.column!==E.END_DATE)return;let n=String(e.activityId),r=t.get(n)??new Set;r.add(e.column),t.set(n,r)}function VL(t,e,n,r,i,a){let o=new Set,s=[],l=new Set;for(let[c,d]of t){if(!d.has(E.START_DATE)||!d.has(E.END_DATE))continue;let u=e.get(c);if(u){a.adapter.setActivityFields(c,u);for(let A of i)String(A.activityId)===c&&l.add(A);continue}let p=n.get(c),y=a.adapter.getActivity(c);if(!p?.constraintType||!p.constraintDate||!y||WL(c,p,y,a))continue;let f=lr(p.constraintType,y.startDate,y.endDate),m=KL(p.constraintType,p.constraintDate,f);if(o.add(c),m){a.adapter.setActivityField(c,"constraintType",_.SNET),a.adapter.setActivityField(c,"constraintDate",new Date(y.startDate.getTime()));let A=Tr(c,ko(p.constraintType,p.constraintDate,f));A&&s.push(A);continue}a.adapter.setActivityField(c,"constraintType",p.constraintType),a.adapter.setActivityField(c,"constraintDate",p.constraintDate)}return[...r.filter(c=>!l.has(c)&&!o.has(String(c.activityId))),...s]}function WL(t,e,n,r){return n.startDate.getTime()!==e.startDate.getTime()?r.adapter.getIncomingLinkIds(t).some(a=>{let o=r.adapter.getLink(a)?.type;return o===q.FINISH_TO_START||o===q.START_TO_START}):!1}function KL(t,e,n){return t===_.MSO||t===_.MFO?e.getTime()!==n.getTime():Po(t,e,n).violated}function YL(t,e,n){let{ctx:r}=e,i=t.activityId,a=ge(t.column);if(!a)return{verdict:{activityId:i,ok:!1,reason:D.NO_PIPELINE_FOR_COLUMN},changes:null};let o=r.activityReader.getActivity(t.activityId);if(!o)return{verdict:{activityId:i,ok:!1,reason:D.ACTIVITY_NOT_FOUND},changes:null};let s=Hi(a,o,e,t.column,{eventSource:n,newValue:t.newValue});if(!s.allowed)return{verdict:{activityId:i,ok:!1,reason:s.reason??D.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let l=a.parseInput(t.newValue,o,r);if(!l.ok)return{verdict:{activityId:i,ok:!1,reason:l.reason??D.PARSE_ERROR},changes:null};let c=Mi(o,a.targetField),d=a.validate(o,c,l.value,r);if(!d.valid)return{verdict:{activityId:i,ok:!1,reason:d.reason??D.INVALID,...d.notification?.messageKey?{alertKey:d.notification.messageKey}:{}},changes:null};if(t.column===ru&&l.value!==null){let p=e.adapter.getActivity(t.activityId),y=p?p.customId:null,f=typeof y=="string"?y:null;if(e.customIdTracker.isCustomIdInUse(String(l.value),f))return{verdict:{activityId:i,ok:!1,reason:D.CUSTOM_ID_DUPLICATE},changes:null}}let u=a.transform(o,l.value,r,l.raw);return{verdict:{activityId:i,ok:!0},changes:u}}function GL(t,e,n,r,i,a){let o=t[0],s=t.map(f=>YL(f,e,n)),l=s.find(f=>!f.verdict.ok);if(l)return l;let c=s[0].changes,d=wm(c,s[1]?.changes),u=e.ctx.activityReader.getActivity(o.activityId),p=o.column===E.END_DATE&&i.has(String(o.activityId))?a.get(String(o.activityId))??u.startDate:null,y=wr(u,d,e,o.column,r.confirmations,void 0,p);return y.accepted?{verdict:{activityId:o.activityId,ok:!0},changes:y.changes}:{verdict:{activityId:o.activityId,ok:!1,reason:y.reason,...y.alertKey?{alertKey:y.alertKey}:{},...y.confirmation?{confirmation:y.confirmation}:{}},changes:null}}function qL(t,e){if(t.column!==ru)return null;let n=e.adapter.getActivity(t.activityId),r=n?n.customId:null;return typeof r=="string"?r:null}function $L(t,e,n){if(t.column!==ru)return;let r=n.adapter.getActivity(t.activityId),i=r?r.customId:null,a=typeof i=="string"?i:null;e!==a&&n.customIdTracker.trackCustomIdChange(e,a)}function zL(t,e,n){if(!Ni(e.column))return;let r=String(e.activityId);if(t.has(r))return;let i=n.get(r);i&&t.set(r,i.constraintDate??null)}function JL(t){let e=new Map;for(let n of t)n.column===E.START_DATE&&n.newValue instanceof Date&&e.set(String(n.activityId),n.newValue);return e}function XL(t,e,n){let r=new Set;for(let i of e)t.has(i)||r.add(i);if(r.size!==0)for(let i of r){let a=n.adapter.getActivity(i);a&&t.set(i,ct(a))}}var ae={INVALID_BASELINE_POINT:"invalid_baseline_point",UNKNOWN_CONSTRAINT:"unknown_constraint",PROGRESS_OUT_OF_RANGE:"progress_out_of_range",ORPHAN_ACTIVITY:"orphan_activity",INVALID_LINK:"invalid_link",DUPLICATE_LINK:"duplicate_link"},ZL=[ae.INVALID_BASELINE_POINT,ae.UNKNOWN_CONSTRAINT,ae.PROGRESS_OUT_OF_RANGE,ae.ORPHAN_ACTIVITY,ae.INVALID_LINK,ae.DUPLICATE_LINK],hn=()=>{};function Bg(){let t=new Map,e=new Map;return{record:(i,a)=>{t.set(i,(t.get(i)??0)+1);let o=e.get(i)??[];o.length<10&&!o.includes(a)&&(o.push(a),e.set(i,o))},snapshot:()=>Object.freeze(ZL.flatMap(i=>{let a=t.get(i);return a===void 0?[]:[Object.freeze({code:i,count:a,sampleIds:Object.freeze([...e.get(i)??[]])})]}))}}function jg(t){return typeof t=="string"&&t.length>0?dn(t):t instanceof Date?t:null}function iu(t){let e=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):Number.NaN;return!Number.isFinite(e)||e<0?null:e}function Sl(t,e,n,r=!1){let i=iu(t.duration),a=iu(t.cost),o=iu(t.hh_work);if(i===null||a===null||o===null)return n&&n.record(ae.INVALID_BASELINE_POINT,n.sampleId),e.warn(`[baseline] dropping point with non-finite/negative magnitude \u2014 duration=${JSON.stringify(t.duration)}, cost=${JSON.stringify(t.cost)}, hh_work=${JSON.stringify(t.hh_work)}`),null;let s=jg(t.start_date),l=jg(t.end_date),c=r&&i===0&&s!==null&&l!==null&&l<s;return c&&e.warn("[baseline] normalizing inverted zero-duration milestone to one instant"),{startDate:s,endDate:c?s:l,durationDays:i,cost:a,workHours:o,versionId:typeof t.sectorbaselineversionId=="number"?t.sectorbaselineversionId:null,isActiveVersion:!!t.sectorbaselineversion?.active,isVisibleVersion:!!t.sectorbaselineversion?.visible,isProjectVersion:t.sectorbaselineversion?.role===pa.PROJECT,isPrimaryVersion:t.sectorbaselineversion?.role===pa.PRIMARY,baseCalendarId:t.baseCalendarId!=null?String(t.baseCalendarId):null,hoursPerDay:typeof t.hoursPerDay=="number"?t.hoursPerDay:null,hoursPerWeek:typeof t.hoursPerWeek=="number"?t.hoursPerWeek:null}}var au=1440*60*1e3,Vg=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/,Wg=/^\d{4}[/-]\d{1,2}[/-]\d{1,2}[ T](\d{1,2}):(\d{2})/,Za=7,Qa={DAILY:"DAILY",WEEKLY:"WEEKLY",MONTHLY:"MONTHLY",YEARLY:"YEARLY"},Gi=12,ou=[!1,!0,!0,!0,!0,!0,!1],Kg=new Set(["1","true"]),su=Tt.DURATION,Yg=_.ASAP,Gg={ASAP:_.ASAP,ALAP:_.ALAP,SNET:_.SNET,SNLT:_.SNLT,FNET:_.FNET,FNLT:_.FNLT,MSO:_.MSO,MFO:_.MFO,"AS SOON AS POSSIBLE":_.ASAP,"AS LATE AS POSSIBLE":_.ALAP,"START NO EARLIER THAN":_.SNET,"START NO LATER THAN":_.SNLT,"FINISH NO EARLIER THAN":_.FNET,"FINISH NO LATER THAN":_.FNLT,"MUST START ON":_.MSO,"MUST FINISH ON":_.MFO};function vl(t,e){let n=[],r=t.map(a=>{let o=cO(a,e);return a.should_be_showed===!1&&n.push(o.id),o});uO(r);let i=new Set(r.map(a=>a.id));return pO(r,i,e.reporter,e.recordDiagnostic),{activities:r,activityIds:i,hiddenIds:n}}function QL(t,e,n,r){if(!t)return null;let i=Gg[t.toUpperCase()];return i===void 0?(n(ae.UNKNOWN_CONSTRAINT,r),e.warn(`[parseFromBackend] unknown constraint label "${t}" \u2014 defaulting to "asap"`),Yg):i}function tO(t,e,n){let r=QL(t.constraint,e,n,String(t.unique_id)),a=r!==_.ASAP&&r!==_.ALAP&&t.constraint_date?dn(t.constraint_date):null;return{constraintType:r,constraintDate:a}}function eO(t,e,n){if(t==null)return n;let r=String(t);return e.has(r)?r:n}function nO(t){if(t==null||t==="")return[];if(Array.isArray(t))return t.map(String);if(typeof t!="string")return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.map(String):[]}catch{return[]}}function rO(t){if(typeof t!="object"||t===null||!("id"in t))return!1;let e=t.id;return typeof e=="string"||typeof e=="number"}function lu(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)rO(n)&&e.push(String(n.id));return e}function iO(t){return t==="0"?null:String(t)}function aO(t){if(t==null)return null;if(!(typeof t=="number"&&(t===0||Number.isSafeInteger(t)&&t>0)))throw new Error(`invalid activity proplannerId ${String(t)}`);return t}function oO(t,e,n,r){let i=Number(t);if(!Number.isFinite(i))throw new TypeError(`invalid activity progress ${String(t)}`);let a=i<0,o=i>Bc;if(!a&&!o)return i;let l=a?0:100;return n(ae.PROGRESS_OUT_OF_RANGE,r),e.warn(`[parseFromBackend] activity "${r}" progress ${String(t)} is out of range \u2014 clamping to ${l}`),l}function sO(t,e){return typeof t.is_critical=="boolean"?t.is_critical:(e.error("[parseFromBackend] invalid activity is_critical \u2014 defaulting to false",new TypeError(`activity "${t.unique_id}" received ${typeof t.is_critical}`)),!1)}function lO(t,e,n,r,i){return Array.isArray(t)?t.map(a=>Sl(a,e,{record:n,sampleId:r},i)).filter(a=>a!==null):[]}function cO(t,e){let n=eO(t.calendarId,e.knownCalendarIds,e.defaultCalendarId),r=t.calendarId==null||!e.knownCalendarIds.has(String(t.calendarId)),i=oO(t.progress,e.reporter,e.recordDiagnostic,String(t.unique_id)),{constraintType:a,constraintDate:o}=tO(t,e.reporter,e.recordDiagnostic),s=t.type===H.MILESTONE,l=dn(t.start_date),c=s?l:dn(t.end_date),d=s?0:Number(t.duration),u=sO(t,e.reporter);return{id:String(t.unique_id),proplannerId:aO(t.id),parentId:iO(t.parent_id),name:t.name,description:t.description??"",type:t.type,startDate:l,endDate:c,durationHours:Ar(d,e.hoursPerDay),constraintType:a,constraintDate:o,autoScheduling:ye(i),calendarId:n,assignedDefaultCalendar:n!=null&&r,dateOrigin:t.date_origin==null?null:dn(t.date_origin),progress:i,cost:Number(t.cost),usedCost:Number(t.used_cost??0),realCost:Number(t.real_cost??0),workHours:Number(t.hhWorkTime),realWorkHours:Number(t.real_work??0),ponderator:Number(t.ponderator??0),hasCustomPonderator:t.hasCustomPonderator,correlativeId:t.correlative_id,uniqueCorrelativeId:t.unique_correlative_id,customId:dO(t),subcontractId:t.subcontractId,isLookahead:t.isOnLookahead,hasLookaheadTasks:Array.isArray(t.tasks)&&t.tasks.length>0,newActivityIds:Ae(nO(t.newActivitiesArray)),hasNewActivities:t.hasNewActivities??!1,...t.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:Ae(lu(t.pendingRequests)),responsableIds:Ae(lu(t.responsables)),tagIds:Ae(lu(t.tags)),baselinePoints:Ae(lO(t.baseline_points,e.reporter,e.recordDiagnostic,String(t.unique_id),s)),baselineSnapshot:null,baselineVarianceDays:null,projectBaselineVarianceDays:null,primaryBaselineVarianceDays:null,recursiveDurationHours:Ar(Number(t.sumOfDurationRecursively??0),e.hoursPerDay),calendarDuration:Je({type:t.type,startDate:l,endDate:c}),isCritical:u,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function dO(t){return t.has_childs?null:t.custom_id}function uO(t){let e=t.find(n=>n.correlativeId===0&&n.type===H.PROJECT);e&&(e.parentId=null)}function pO(t,e,n,r){for(let i of t)i.parentId!==null&&(e.has(i.parentId)||(n.warn(`[parseFromBackend] activity "${i.id}" references unknown parent "${i.parentId}" \u2014 re-parenting to root (null)`),r(ae.ORPHAN_ACTIVITY,i.id),i.parentId=null))}function yO(t){if(typeof t!="string")return null;let e=ih(t);return e||(bo(t)?t:null)}function fO(t){if(t==null)return;if(!(typeof t=="number"&&(t===0||Number.isSafeInteger(t)&&t>0)))throw new Error(`invalid link proplannerId ${String(t)}`);return t}function Cl(t,e){let n=[];for(let r of t)try{n.push(hO(r,e.knownActivityIds,e.hoursPerDay))}catch(i){e.recordDiagnostic(ae.INVALID_LINK,String(r.unique_id??r.id)),e.reporter.warn("[parseFromBackend] dropping invalid link",i)}return mO(n,e.recordDiagnostic)}function hO(t,e,n){let r=String(t.unique_id??t.id),i=String(t.source_id??t.source??""),a=String(t.target_id??t.target??"");if(!e.has(i))throw new Error(`[parseFromBackend] link "${r}" source "${i}" does not exist`);if(!e.has(a))throw new Error(`[parseFromBackend] link "${r}" target "${a}" does not exist`);let o=yO(t.type);if(o===null)throw new Error(`[parseFromBackend] link "${r}" has invalid type "${String(t.type)}"`);let s=t.ganttId,l=t.sectorId,c=fO(t.id);return{id:r,source:i,target:a,type:o,lag:ke(Number(t.lag??0),n),freeSlackHours:null,isCritical:!1,...typeof s=="number"?{ganttId:s}:{},...typeof l=="number"?{sectorId:l}:{},...c===void 0?{}:{proplannerId:c}}}function mO(t,e){let n=new Map;for(let r of t){let i=`${r.source}-${r.target}-${r.type}`,a=n.get(i);if(!a){n.set(i,r);continue}let o=qg(r)>qg(a),s=o?a:r;e(ae.DUPLICATE_LINK,s.id),o&&n.set(i,r)}return[...n.values()]}function qg(t){let e=Number(t.id);return Number.isFinite(e)?e:-1/0}var J={TRACKED:"tracked",IGNORED:"ignored"};var $g={id:J.IGNORED,proplannerId:J.IGNORED,parentId:J.TRACKED,name:J.TRACKED,description:J.TRACKED,type:J.TRACKED,startDate:J.TRACKED,endDate:J.TRACKED,durationHours:J.TRACKED,constraintType:J.TRACKED,constraintDate:J.TRACKED,autoScheduling:J.TRACKED,calendarId:J.TRACKED,assignedDefaultCalendar:J.IGNORED,dateOrigin:J.TRACKED,progress:J.TRACKED,cost:J.TRACKED,usedCost:J.TRACKED,realCost:J.TRACKED,workHours:J.TRACKED,realWorkHours:J.TRACKED,ponderator:J.TRACKED,hasCustomPonderator:J.TRACKED,correlativeId:J.TRACKED,uniqueCorrelativeId:J.TRACKED,customId:J.TRACKED,subcontractId:J.TRACKED,isLookahead:J.TRACKED,hasLookaheadTasks:J.IGNORED,newActivityIds:J.TRACKED,hasNewActivities:J.TRACKED,isNewActivity:J.IGNORED,pendingRequestIds:J.IGNORED,responsableIds:J.TRACKED,tagIds:J.TRACKED,baselinePoints:J.IGNORED,baselineSnapshot:J.IGNORED,recursiveDurationHours:J.IGNORED,isCritical:J.IGNORED,freeSlackHours:J.IGNORED,calendarDuration:J.IGNORED,baselineVarianceDays:J.IGNORED,projectBaselineVarianceDays:J.IGNORED,primaryBaselineVarianceDays:J.IGNORED,expectedProgress:J.IGNORED,expectedProgressBaseline:J.IGNORED,status:J.IGNORED,criticalPath:J.IGNORED,p6:J.IGNORED},gO=Object.keys($g).filter(t=>$g[t]===J.TRACKED),AO=["startDate","endDate","constraintDate","dateOrigin"],IO=new Set(AO),SO=new Set(["newActivityIds","responsableIds","tagIds"]),Jg=Object.freeze([]),eo={DATE:0,ID_ARRAY:1,SCALAR:2},vO=t=>IO.has(t)?eo.DATE:SO.has(t)?eo.ID_ARRAY:eo.SCALAR,Xg=gO.map(t=>({field:t,kind:vO(t)}));function Ur(t){return{parentId:t.parentId,name:t.name,description:t.description,type:t.type,startDate:to(t.startDate),endDate:to(t.endDate),durationHours:t.durationHours,constraintType:t.constraintType,constraintDate:to(t.constraintDate),autoScheduling:t.autoScheduling,calendarId:t.calendarId,dateOrigin:to(t.dateOrigin),progress:t.progress,cost:t.cost,usedCost:t.usedCost,realCost:t.realCost,workHours:t.workHours,realWorkHours:t.realWorkHours,ponderator:t.ponderator,hasCustomPonderator:t.hasCustomPonderator,correlativeId:t.correlativeId,uniqueCorrelativeId:t.uniqueCorrelativeId,customId:t.customId,subcontractId:t.subcontractId,isLookahead:t.isLookahead,newActivityIds:cu(t.newActivityIds),hasNewActivities:t.hasNewActivities,responsableIds:cu(t.responsableIds),tagIds:cu(t.tagIds)}}var to=t=>typeof t?.getTime=="function"?t.getTime():null;function cu(t){return Array.isArray(t)&&t.length>0?[...t]:Jg}function no(t,e){for(let{field:n,kind:r}of Xg)if(!Zg(r,t[n],e[n]))return!0;return!1}function je(t,e){let n=[];for(let{field:r,kind:i}of Xg)Zg(i,t[r],e[r])||n.push(r);return n}function Zg(t,e,n){return t===eo.DATE?CO(e,n):t===eo.ID_ARRAY?TO(e,n):(e??null)===(n??null)}function CO(t,e){return to(t)===(typeof e=="number"?e:null)}var zg=t=>Array.isArray(t)?t:Jg;function DO(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(String(t[n])!==String(e[n]))return!1;return!0}function TO(t,e){let n=zg(t),r=zg(e);if(DO(n,r))return!0;let i=new Set(n.map(String)),a=new Set(r.map(String));if(i.size!==a.size)return!1;for(let o of i)if(!a.has(o))return!1;return!0}var Qg={id:J.IGNORED,source:J.TRACKED,target:J.TRACKED,type:J.TRACKED,lag:J.TRACKED,freeSlackHours:J.IGNORED,isCritical:J.IGNORED,ganttId:J.IGNORED,sectorId:J.IGNORED,proplannerId:J.IGNORED},du=Object.keys(Qg).filter(t=>Qg[t]===J.TRACKED);function Dl(t,e){return du.some(n=>t[n]!==e[n])}function tA(t,e){let n=new Map(t.map(r=>[String(r.id),r]));return e.filter(r=>{let i=n.get(String(r.id));return i?Dl(i,r):!1})}var ro=t=>G(t)?null:String(t);function eA(t){let e=new Map;for(let n of t.localActivities)e.set(String(n.id),ro(n.parentId));for(let n of t.createActivities)e.set(String(n.id),ro(n.parentId));for(let n of t.updateActivities)n.fields.parentId!==void 0&&e.set(n.activityId,ro(n.fields.parentId));for(let n of t.removeActivityIds)e.delete(n);return e}function nA(t){let e=new Set;for(let n of t.keys()){let r=[],i=new Set,a=n;for(;a!=null&&!e.has(a);){if(i.has(a))return r.slice(r.indexOf(a));i.add(a),r.push(a),a=t.get(a)}for(let o of r)e.add(o)}return null}function _O(t,e,n){let r=n.updateActivities.find(i=>i.activityId===t);if(r){let i=n.updateActivities.indexOf(r);n.updateActivities[i]={activityId:t,fields:{...r.fields,parentId:e.parentId}};return}n.updateActivities.push({activityId:t,fields:{parentId:e.parentId}})}function rA(t){let e=new Map(t.remoteActivities.map(a=>[String(a.id),a])),n=[],r=eA(t),i=nA(r);for(;i!==null;){let a=i.find(s=>{let l=e.get(s);return l!==void 0&&ro(l.parentId)!==r.get(s)}),o=a===void 0?void 0:e.get(a);if(a===void 0||o===void 0)break;n.push({entity:Gt.ACTIVITY,id:a,kind:$t.FIELD,field:b.PARENT,mine:r.get(a)??null,theirs:ro(o.parentId)}),_O(a,o,t),r=eA(t),i=nA(r)}return n}function uu(t){let e=Vn(t,t.getAllLinks());return Ci(e).reduce((n,r)=>n+r.length,0)}function iA(t,e,n){let r=new Map,i=[];if(uu(t)===0)return{conflicts:i,removed:r};let a=[];for(let s of e){let l=t.getLink(s);l&&(a.push({...l}),t.removeLink(s))}let o=uu(t);for(let s of a){t.addLink(s);let l=uu(t);if(l<=o){o=l;continue}t.removeLink(String(s.id)),r.set(String(s.id),s),i.push({entity:Gt.LINK,id:String(s.id),kind:$t.LINK_CYCLE,field:null,mine:Mt(s),theirs:null})}return n.push(...ne(new Map(r))),{conflicts:i,removed:r}}var EO=new Set([b.CORRELATIVE_ID,b.UNIQUE_CORRELATIVE_ID]),RO=new Set([b.END_DATE]),pA=new Set([b.START_DATE,b.DURATION_HOURS,b.COST,b.USED_COST,b.WORK_HOURS]),yA=new Set([b.REAL_WORK_HOURS,b.HAS_NEW_ACTIVITIES]),pu=new Set([...pA,b.PROGRESS,b.TYPE,b.REAL_COST,b.PONDERATOR,b.AUTO_SCHEDULING]),PO=new Set([b.NEW_ACTIVITIES_ARRAY]);function fA(t){let e={createActivities:[],updateActivities:[],removeActivityIds:[],createLinks:[],updateLinks:[],removeLinkIds:[],remoteChanges:[],conflicts:[]};return OO(t,e),e.conflicts.push(...rA({localActivities:t.localActivities,remoteActivities:t.remoteActivities,createActivities:e.createActivities,removeActivityIds:e.removeActivityIds,updateActivities:e.updateActivities})),WO(t,e),e}function aA(t){let e=new Set;for(let n of t)G(n.parentId)||e.add(String(n.parentId));return e}function oA(t){return new Set(t.map(e=>String(e.target)))}function kO(t){return{localParentIds:aA(t.localActivities),remoteParentIds:aA(t.remoteActivities),localTargetIds:oA(t.localLinks),remoteTargetIds:oA(t.remoteLinks)}}function bO(t,e){return{local:{isParent:e.localParentIds.has(t),hasPredecessors:e.localTargetIds.has(t)},remote:{isParent:e.remoteParentIds.has(t),hasPredecessors:e.remoteTargetIds.has(t)}}}function hA(t,e,n){return RO.has(t)||e.isParent&&pA.has(t)||t===b.START_DATE&&e.hasPredecessors&&n.autoScheduling?!0:t===b.PONDERATOR&&!n.hasCustomPonderator}function LO(t,e,n){return hA(t,e,n)||yA.has(t)?!0:e.isParent&&pu.has(t)}function sA(t,e,n){return e===null?new Set:new Set(je(t,e).filter(r=>!LO(r,n,t)))}function OO(t,e){let n=kO(t),r=new Map(t.localActivities.map(a=>[String(a.id),a])),i=new Set;for(let a of t.remoteActivities){let o=String(a.id);i.add(o);let s=t.checkpoint.checkpointActivity(o),l=r.get(o)??null,c=bO(o,n);NO(o,a,s,l,c,e)}for(let a of t.checkpoint.checkpointActivityIds()){if(i.has(a))continue;let o=r.get(a);if(!o)continue;let s=t.checkpoint.checkpointActivity(a);VO(a,s,o,e)}}function NO(t,e,n,r,i,a){if(n===null){if(r===null){a.createActivities.push(e);return}lA(t,e,null,r,i,a);return}let o=je(e,n);if(r===null){if(o.length===0)return;a.createActivities.push(e),a.conflicts.push({entity:Gt.ACTIVITY,id:t,kind:$t.DELETED_LOCALLY,field:null,mine:null,theirs:Ur(e)});return}lA(t,e,n,r,i,a)}var Ve={LOCAL:"local",REMOTE:"remote"};function FO(t){return t.local.isParent?Ve.LOCAL:t.remote.isParent?Ve.REMOTE:null}function wO(t,e){let n=t.remoteFields.includes(e),r=t.localChangedFields.has(e);if(e===b.TYPE)return r?n?FO(t.context)??Ve.REMOTE:Ve.LOCAL:Ve.REMOTE;if(hA(e,t.context.local,t.local)||!r||t.remoteSourceFields.has(e))return Ve.REMOTE;let i=t.context.local.isParent&&t.context.remote.isParent,a=yA.has(e)||i&&pu.has(e);return n&&a?Ve.REMOTE:Ve.LOCAL}function lA(t,e,n,r,i,a){let o=Ur(r),s=Ur(e),l=je(e,o);if(l.length===0)return;let c=n===null?l:je(e,n),d={activityId:t,remote:e,local:r,remotePersistable:s,localPersistable:o,remoteFields:c,localFields:sA(r,n,i.local),localChangedFields:new Set(n===null?[]:je(r,n)),remoteSourceFields:n===null?new Set(l):sA(e,n,i.remote),context:i};jO(d,a);let u=xO(d,l,a);Object.keys(u).length!==0&&a.updateActivities.push({activityId:t,fields:u})}function xO(t,e,n){let r={};for(let i of e)if(!(EO.has(i)||i===b.AUTO_SCHEDULING)){if(PO.has(i)){MO(t,i,r);continue}i===b.HAS_NEW_ACTIVITIES&&r.hasNewActivities!==void 0||wO(t,i)!==Ve.LOCAL&&(Reflect.set(r,i,t.remote[i]),t.remoteSourceFields.has(i)&&HO(t,i,n))}return r.progress!==void 0&&!t.context.local.isParent&&(r.autoScheduling=ye(r.progress)),UO(t,r,n),r}function MO(t,e,n){let{localPersistable:r,remotePersistable:i}=t,a=BO(r[e],i[e]);Reflect.set(n,e,a),Reflect.set(n,b.HAS_NEW_ACTIVITIES,a.length>0||r.hasNewActivities||i.hasNewActivities)}function UO(t,e,n){let r=e.type??t.local.type,i=e.durationHours??t.local.durationHours;if(r!==H.MILESTONE||i===0)return;let a=e.durationHours!==void 0,o=a?b.TYPE:b.DURATION_HOURS;a?e.type=t.remote.type:e.durationHours=0,n.conflicts.push({entity:Gt.ACTIVITY,id:t.activityId,kind:$t.FIELD,field:o,mine:t.localPersistable[o],theirs:a?t.remote.type:0})}function HO(t,e,n){let r=t.local[e],i=t.remote[e];if(t.localFields.has(e)){n.conflicts.push({entity:Gt.ACTIVITY,id:t.activityId,kind:$t.FIELD,field:e,mine:r,theirs:i});return}n.remoteChanges.push({entity:Gt.ACTIVITY,id:t.activityId,field:e,before:r,after:i})}function BO(t,e){let n=new Set;for(let r of Array.isArray(t)?t:[])n.add(String(r));for(let r of Array.isArray(e)?e:[])n.add(String(r));return[...n]}function cA(t,e){let n={};for(let r of t)pu.has(r)&&r!==b.TYPE&&Reflect.set(n,r,e[r]);return n}function jO(t,e){let{context:n,localPersistable:r,remotePersistable:i}=t;if(n.local.isParent===n.remote.isParent)return;let a=n.remote.isParent?cA(t.localFields,r):cA(t.remoteFields,i);if(Object.keys(a).length===0)return;let o=n.remote.isParent?{kind:$t.BECAME_PARENT_REMOTELY,mine:a,theirs:i}:{kind:$t.BECAME_PARENT_LOCALLY,mine:r,theirs:a};e.conflicts.push({entity:Gt.ACTIVITY,id:t.activityId,field:null,...o})}function VO(t,e,n,r){r.removeActivityIds.push(t),e!==null&&je(n,e).length>0&&r.conflicts.push({entity:Gt.ACTIVITY,id:t,kind:$t.DELETED_REMOTELY,field:null,mine:Ur(n),theirs:null})}function WO(t,e){let n=new Map(t.localLinks.map(a=>[String(a.id),a])),r=new Set,i=[];for(let a of t.remoteLinks){let o=String(a.id);r.add(o);let s=t.checkpoint.checkpointLink(o),l=n.get(o)??null;s===null&&l===null&&i.push(a),YO(o,a,s,l,e)}for(let a of t.checkpoint.checkpointLinkIds()){if(r.has(a))continue;let o=n.get(a);if(!o)continue;let s=t.checkpoint.checkpointLink(a);GO(a,s,o,e)}KO(t,i,r,e)}function dA(t){return[String(t.source),String(t.target)].sort().join("|")}function KO(t,e,n,r){if(e.length===0)return;let i=new Map(e.map(a=>[dA(a),a]));for(let a of t.localLinks){let o=String(a.id);if(!(!n.has(o)&&t.checkpoint.checkpointLink(o)===null))continue;let l=i.get(dA(a));if(!l)continue;r.removeLinkIds.push(o);let c=Br(a),d=Br(l);Hr(c,d).length!==0&&r.conflicts.push({entity:Gt.LINK,id:String(l.id),kind:$t.DUPLICATE_LINK,field:null,mine:c,theirs:d})}}function Hr(t,e){return du.filter(n=>t[n]!==e[n])}function YO(t,e,n,r,i){if(n===null){if(r===null){i.createLinks.push(e);return}uA(t,e,null,r,i);return}if(r===null){if(Hr(e,n).length===0)return;i.createLinks.push(e),i.conflicts.push({entity:Gt.LINK,id:t,kind:$t.DELETED_LOCALLY,field:null,mine:null,theirs:Br(e)});return}uA(t,e,n,r,i)}function Br(t){return{source:String(t.source),target:String(t.target),type:t.type,lag:Number(t.lag)}}function uA(t,e,n,r,i){let a=Br(e),o=Br(r),s=n===null?Hr(a,o):Hr(a,n);if(s.length===0)return;let l=new Set(n===null?[]:Hr(o,n)),c=new Set(Hr(a,o)),d={};for(let u of s)if(c.has(u)){if(Reflect.set(d,u,a[u]),l.has(u)){i.conflicts.push({entity:Gt.LINK,id:t,kind:$t.FIELD,field:u,mine:o[u],theirs:a[u]});continue}i.remoteChanges.push({entity:Gt.LINK,id:t,field:u,before:o[u],after:a[u]})}Object.keys(d).length!==0&&i.updateLinks.push({linkId:t,fields:d})}function GO(t,e,n,r){r.removeLinkIds.push(t),e!==null&&Hr(Br(n),e).length>0&&r.conflicts.push({entity:Gt.LINK,id:t,kind:$t.DELETED_REMOTELY,field:null,mine:Br(n),theirs:null})}var qO=t=>G(t)?"0":String(t),mA=t=>{let e=Number(t);return Number.isFinite(e)?e:Number.MAX_SAFE_INTEGER};function Tl(t){let e=new Map;for(let r of t){let i=qO(r.parentId),a=e.get(i)??[];a.push(r),e.set(i,a)}let n=new Map;for(let[r,i]of e)i.sort((a,o)=>mA(a.correlativeId)-mA(o.correlativeId)||a.id.localeCompare(o.id)),n.set(r,i.map(a=>a.id));return n}var fu=t=>({id:String(t.id),parentId:t.parentId,correlativeId:t.correlativeId});function AA(t,e,n){let r=[];for(let i of n.checkpointActivityIds()){let a=n.checkpointActivity(i);a!==null&&r.push({id:i,parentId:a.parentId,correlativeId:a.correlativeId})}return{local:Tl(t.map(fu)),remote:Tl(e.map(fu)),base:Tl(r)}}function yu(t,e){let n=new Set(e),r=new Set(t),i=t.filter(o=>n.has(o)),a=e.filter(o=>r.has(o));return i.some((o,s)=>a[s]!==o)}function gA(t,e,n){let r=t.filter(a=>n.has(a)),i=-1;for(let a of e){let o=r.indexOf(a);if(o!==-1){i=o;continue}n.has(a)&&(r.splice(i+1,0,a),i+=1)}for(let a of n)r.includes(a)||r.push(a);return r}function $O(t,e,n){let r=n.local.get(t)??[],i=n.remote.get(t)??[],a=n.base.get(t)??[],o=yu(r,a),s=yu(i,a),c=o&&!s?gA(r,i,e):gA(i,r,e),d=o&&s&&yu(r,c);return{order:c,conflict:d?{entity:Gt.ACTIVITY,id:t,kind:$t.ORDER,field:b.CORRELATIVE_ID,mine:r.filter(u=>e.has(u)),theirs:c}:null}}function zO(t){return Tl(t.getAllActivities().map(fu))}function IA(t,e){let{orders:n,conflicts:r}=JO(t,e);return{shifts:XO(t,n),conflicts:r}}function JO(t,e){let n=new Map,r=[];for(let[i,a]of zO(t)){let o=$O(i,new Set(a),e);n.set(i,o.order),o.conflict!==null&&r.push(o.conflict)}return{orders:n,conflicts:r}}function XO(t,e){let n=[],r=0,i=[...e.get("0")??[]].reverse();for(;i.length>0;){let a=i.pop();if(a===void 0)break;let o=ZO(t,a,r);o!==null&&n.push(o),r+=1,QO(i,e.get(a)??[])}return n}function ZO(t,e,n){let r=t.getActivity(e);if(!r||r.correlativeId===n)return null;let i=Number(r.correlativeId);return t.setActivityField(e,b.CORRELATIVE_ID,n),{activityId:e,before:Number.isFinite(i)?i:void 0}}function QO(t,e){for(let n=e.length-1;n>=0;n-=1){let r=e[n];r!==void 0&&t.push(r)}}var SA=t=>t==null||t===0,vA=t=>SA(t.proplannerId);function tN(t,e){let n=t.linkIdGen.next(),r=i=>t.adapter.getLink(i)!==null||t.isLinkIdReserved(String(i))||e.has(String(i));for(;r(n);)n=t.linkIdGen.next();return n}function eN(t,e){let n=new Set;for(let a of t)n.add(String(a.id)),e.linkIdGen.bump(a.id);let r=new Set(n),i=[];for(let a of e.adapter.getAllLinks()){let o=String(a.id);if(!n.has(o)||!SA(a.proplannerId))continue;let s=String(tN(e,r));r.add(s),i.push({from:o,to:s})}return i}function nN(t){let e=new Map;for(let n of t)n.customId&&e.set(n.customId,String(n.id));return e}function rN(t,e){let n=e.persistenceCheckpoint.checkpointActivity(String(t.id));return n===null||n.customId!==t.customId}function iN(t,e){let n=nN(t);e.customIdTracker.populateFromActivities(t);let r=[];for(let i of e.adapter.getVisualOrderIds()){let a=e.adapter.getActivity(i);if(!a?.customId)continue;let o=n.get(a.customId);o===void 0||o===String(a.id)&&!vA(a)||rN(a,e)&&r.push({activityId:a.id,nextCustomId:e.customIdTracker.generateCustomIdForRestoredChild(a.customId)})}return r}function aN(t,e){let n=t.activityIdGen.next(),r=i=>t.adapter.activityExists(i)||t.isActivityIdReserved(String(i))||e.has(String(i));for(;r(n);)n=t.activityIdGen.next();return n}function CA(t,e){let n=t.activities,r=new Set,i=new Set;for(let l of n)r.add(String(l.id)),i.add(String(l.uniqueCorrelativeId)),e.activityIdGen.bump(l.id),e.uidGen.bump(l.uniqueCorrelativeId);let a=new Set,o=[],s=[];for(let l of e.adapter.getAllActivities()){if(!vA(l))continue;let c=String(l.id);if(r.has(c)){let d=aN(e,a);a.add(String(d)),o.push({from:c,to:String(d),parentId:e.adapter.getParent(l.id)?.id??null,childIds:[...e.adapter.getChildren(l.id)],outgoingLinkIds:[...e.adapter.getOutgoingLinkIds(l.id)],incomingLinkIds:[...e.adapter.getIncomingLinkIds(l.id)]})}i.has(String(l.uniqueCorrelativeId))&&s.push({activityId:l.id,nextUniqueCorrelativeId:e.uidGen.next()})}return{activities:o,links:eN(t.links,e),uniqueCorrelativeIds:s,customIds:iN(n,e)}}function DA(t){let e=new Set;for(let n of t.activities){e.add(n.from),e.add(n.to),n.parentId!==null&&e.add(String(n.parentId));for(let r of n.childIds)e.add(String(r))}for(let n of t.uniqueCorrelativeIds)e.add(String(n.activityId));for(let n of t.customIds)e.add(String(n.activityId));return e}function oN(t,e,n){return t.map(r=>String(r)===e?n:r)}function sN(t,e){let n=e.getActivity(t.from);if(!n)return;let r=ct(n);r.id=t.to;let i=e.isChecked(t.from),a=e.isVisible(t.from),o=e.getLastStartDate(t.from),s=e.getPromotionSnapshot(t.from),l=e.getProgressFallback(t.from);e.removeActivity(t.from),e.addActivity(r),i&&e.setChecked(t.to,!0),a||e.setVisible(t.to,!1),o&&e.setLastStartDate(t.to,o),s&&e.setPromotionSnapshot(t.to,s),l!==null&&e.setProgressFallback(t.to,l);for(let u of t.childIds)e.setActivityFields(u,{parentId:t.to});for(let u of t.outgoingLinkIds){let p=e.getLink(u);p&&e.setLinkEndpoints(u,t.to,p.target)}for(let u of t.incomingLinkIds){let p=e.getLink(u);p&&e.setLinkEndpoints(u,p.source,t.to)}let c=e.getParent(t.to);!c||!c.newActivityIds.some(u=>String(u)===t.from)||e.setActivityFields(c.id,{newActivityIds:oN(c.newActivityIds,t.from,t.to)})}function lN(t,e){let n=new Map,r=[];for(let i of t){let a=e.getLink(i.from);if(!a)continue;n.set(i.from,{...a}),e.removeLink(i.from);let o={...a,id:i.to};e.addLink(o),r.push(o)}return{before:n,after:r}}function TA(t,e){for(let n of t.uniqueCorrelativeIds)e.setActivityField(n.activityId,b.UNIQUE_CORRELATIVE_ID,n.nextUniqueCorrelativeId);for(let n of t.customIds)e.setActivityField(n.activityId,b.CUSTOM_ID,n.nextCustomId);for(let n of t.activities)sN(n,e);return lN(t.links,e)}function cN(t){for(let e of t.values())if(e.is_default)return String(e.id);return null}function dN(t,e){return t.remote.activities.some(n=>n.calendarId!=null&&!e.has(String(n.calendarId)))}function uN(t,e){let{activities:n,activityIds:r}=vl([...t.remote.activities],{knownCalendarIds:new Set(e.calendars.keys()),defaultCalendarId:cN(e.calendars),hoursPerDay:e.sector.hoursPerDay,reporter:e.reporter,recordDiagnostic:hn}),i=Cl([...t.remote.links],{knownActivityIds:r,hoursPerDay:e.sector.hoursPerDay,reporter:e.reporter,recordDiagnostic:hn});return{activities:n,links:i}}function pN(t){return t.activities.every(e=>typeof e.proplannerId=="number"&&e.proplannerId>0)}async function _A(t,e,n){let{adapter:r,scheduler:i,sector:a}=n;if(dN(t,n.calendars))return{ok:!1,reason:D.INVALID};let o=uN(t,n);if(!pN(o))return{ok:!1,reason:D.INVALID};i.invalidateAllCaches();let s=AN(r),l=await fN(o,n),c=fA({remoteActivities:o.activities,remoteLinks:o.links,localActivities:r.getAllActivities(),localLinks:r.getAllLinks(),checkpoint:n.persistenceCheckpoint}),d=AA(r.getAllActivities(),o.activities,n.persistenceCheckpoint),u=new Set(c.removeActivityIds),p=_N(c,r),y=await mN(r,p,l);for(let w of l.touchedIds)p.add(w);let f=EN(c,u,r),m=Mr(r,u);for(let w of f.keys())r.removeLink(w);for(let w of u)r.removeActivity(w);for(let w of c.createActivities)r.addActivity(ct(w)),n.uidGen.bump(w.uniqueCorrelativeId),n.customIdTracker.populateFromActivities([w]);for(let w of c.updateActivities)r.setActivityFields(w.activityId,w.fields);gN(c,r);let A=PN(r,n.persistenceCheckpoint,p);CN(n,p),vN(r,p),DN(r,p);let g=[...hN(l.links),...kN(c,f,r)],R=bN(r,g),P=iA(r,IN(s,l.plan.links),g),N=new Set(c.createActivities.map(w=>String(w.id))),T=new Set([...N,...l.plan.activities.map(w=>w.to)]),x=IA(r,d),S=[...x.shifts,...Bt(r)].filter(w=>!T.has(w.activityId)),{scheduledIds:k}=await ot({adapter:r,scheduler:i,sector:a,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:Pt.ROOTS,recomputeParentsFrom:TN(p,r),recomputeParentProgress:!0,now:n.now,options:e});SN(r,p);let F=await et(r,{source:t,beforeSnap:y,touchedIds:p,scheduledIds:k,links:g,hoursPerDay:a.hoursPerDay,correlativeShifts:S}),U={remoteChanges:c.remoteChanges,conflicts:[...c.conflicts,...A,...x.conflicts,...R,...P.conflicts],createdActivityIds:[...N],removedActivityIds:[...u],rekeyedActivities:l.plan.activities.map(({from:w,to:M})=>({from:w,to:M})),rekeyedLinks:l.plan.links,createdLinkIds:c.createLinks.map(w=>String(w.id)),removedLinkIds:yN(g,r)};return{ok:!0,changes:m.length>0?{...F,viewState:m}:F,rebase:U,__beforeSnap:y,__beforeLinks:new Map([...l.links.before,...f,...P.removed]),__rebaseCheckpoint:{activities:o.activities,links:o.links}}}function yN(t,e){return t.filter(n=>n.kind===W.DELETED).map(n=>String(n.id)).filter(n=>!e.getLink(n))}async function fN(t,e){let n=CA(t,e),r=DA(n),i=await yt(e.adapter,r),a=TA(n,e.adapter);return{plan:n,touchedIds:r,beforeSnap:i,links:a}}function hN(t){let e=[...ne(new Map(t.before))];for(let n of t.after)e.push({id:String(n.id),kind:W.CREATED,fields:{source:{before:void 0,after:String(n.source)},target:{before:void 0,after:String(n.target)},type:{before:void 0,after:n.type},lag:{before:void 0,after:Number(n.lag)}},after:Mt(n)});return e}async function mN(t,e,n){let r=new Set([...e].filter(i=>!n.touchedIds.has(i)));return new Map([...await yt(t,r),...n.beforeSnap])}function gN(t,e){for(let n of t.updateActivities){let r=e.getActivity(n.activityId);!r||e.hasChildren(r.id)||e.setActivityField(r.id,b.END_DATE,e.calculateEndDate({startDate:r.startDate,durationHours:r.durationHours,task:r}))}}function AN(t){return t.getAllLinks().filter(e=>{let n=e.proplannerId;return n==null||n===0}).map(e=>String(e.id)).sort((e,n)=>Number(e)-Number(n))}function IN(t,e){let n=new Map(e.map(({from:r,to:i})=>[r,i]));return t.map(r=>n.get(r)??r)}function SN(t,e){for(let n of e){if(!t.hasChildren(n))continue;let r=t.getActivity(n);if(!r)continue;let i=ye(r.progress);r.autoScheduling!==i&&t.setActivityField(n,b.AUTO_SCHEDULING,i)}}function vN(t,e){for(let n of e){if(!t.hasChildren(n))continue;let r=t.getActivity(n);r&&(r.type!==H.PROJECT&&t.setActivityField(n,b.TYPE,H.PROJECT),r.customId&&t.setActivityField(n,b.CUSTOM_ID,null))}}function CN(t,e){let{adapter:n}=t;for(let r of e){let i=n.getActivity(r);if(!i||i.type!==H.PROJECT||G(i.parentId)||n.hasChildren(r))continue;let a=Qe({parent:i,remainingChildIds:[],defaultDurationHours:t.sector.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(r),computeEndDate:(l,c)=>n.calculateEndDate({startDate:l,durationHours:c,task:i}),dataDateCapability:t.dataDateCapability,hasCompleteSchedulingState:t.hasCompleteSchedulingState});if(!a)continue;n.setActivityFields(r,a.fields);let o=Oe(r,n),s=o?n.getActivity(o)?.customId:null;n.setActivityField(r,b.CUSTOM_ID,t.customIdTracker.generateCustomIdForRestoredChild(s||null))}}function DN(t,e){let n=new Set;for(let r of e){let i=t.getActivity(r);i&&(t.hasChildren(r)&&n.add(r),G(i.parentId)||n.add(String(i.parentId)))}for(let r of n)zt(r,t)}function TN(t,e){let n=new Set(t);for(let r of t)for(let i of e.getChildren(r))n.add(String(i));return n}function _N(t,e){let n=new Set,r=i=>{i!=null&&(G(i)||n.add(String(i)))};for(let i of t.removeActivityIds)n.add(i),r(e.getActivity(i)?.parentId);for(let i of t.createActivities)n.add(String(i.id)),r(i.parentId);for(let i of t.updateActivities)n.add(i.activityId),r(e.getActivity(i.activityId)?.parentId),i.fields.parentId!==void 0&&r(i.fields.parentId);return n}function EN(t,e,n){let r=new Map,i=Jn(e,n);for(let a of[...t.removeLinkIds,...i]){let o=n.getLink(a);o&&r.set(String(a),{...o})}return r}function RN(t,e,n){let r=new Set,i=t;for(;i!==null&&!r.has(i);){if(e.activityExists(i))return i;r.add(i);let a=n.checkpointActivity(i);if(!a||G(a.parentId))return null;i=String(a.parentId)}return null}function PN(t,e,n){let r=[];for(let i of t.getAllActivities()){if(G(i.parentId)||t.activityExists(String(i.parentId)))continue;let a=String(i.parentId),o=RN(a,t,e);t.setActivityField(i.id,b.PARENT,o),n.add(String(i.id)),o!==null&&n.add(o),r.push({entity:Gt.ACTIVITY,id:String(i.id),kind:$t.PARENT_REMOVED,field:b.PARENT,mine:a,theirs:o??"0"})}return r}function kN(t,e,n){let r=[...ne(new Map(e))];for(let i of t.createLinks){if(n.getLink(i.id))continue;n.addLink({...i,freeSlackHours:null,isCritical:!1});let a=n.getLink(i.id);a&&r.push({id:String(i.id),kind:W.CREATED,fields:{source:{before:void 0,after:String(a.source)},target:{before:void 0,after:String(a.target)},type:{before:void 0,after:a.type},lag:{before:void 0,after:Number(a.lag)}},after:Mt(a)})}for(let i of t.updateLinks){let a=n.getLink(i.linkId);if(!a)continue;let o=Mt(a),s={};for(let[c,d]of Object.entries(i.fields))n.setLinkFieldDynamic(i.linkId,c,d),s[c]={before:Reflect.get(o,c),after:d};let l=n.getLink(i.linkId);l&&r.push({id:String(i.linkId),kind:W.UPDATED,fields:s,after:Mt(l)})}return r}function bN(t,e){let n=[];for(let r of t.getAllLinks()){let i=[r.source,r.target].find(l=>!t.activityExists(String(l)));if(i===void 0)continue;let a=String(r.id),o={...r},s=String(r.source)===String(i);t.removeLink(a),e.push(...ne(new Map([[a,o]]))),n.push({entity:Gt.LINK,id:a,kind:$t.DELETED_REMOTELY,field:s?Xt.SOURCE:Xt.TARGET,mine:Mt(o),theirs:null})}return n}function EA(t,e,n,r=hn){let i=new Map;t.forEachActivity((s,l)=>{let c=s.proplannerId;typeof c=="number"&&i.set(c,l)});let a=new Map;for(let s of e){let l=s.activityId;if(typeof l!="number"){r(ae.INVALID_BASELINE_POINT,String(l??"unknown"));continue}let c=i.get(l);if(c===void 0){r(ae.INVALID_BASELINE_POINT,String(l));continue}let d=a.get(c);d?d.push(s):a.set(c,[s])}let o=[];for(let[s,l]of a){let c=t.getActivity(s)?.type===H.MILESTONE;t.setActivityField(s,"baselinePoints",l.map(d=>Sl(d,n,{record:r,sampleId:s},c)).filter(d=>d!==null)),o.push(s)}return t.forEachActivity((s,l)=>{if(a.has(l))return;let c=s.baselinePoints;Array.isArray(c)&&c.length>0&&(t.setActivityField(l,"baselinePoints",[]),o.push(l))}),o}function LN(t){let e=Kt(t);return e?{startDate:e.startDate,endDate:e.endDate,durationDays:e.durationDays,cost:e.cost,workHours:e.workHours}:null}function RA(t){let e=[];return t.forEachActivity((n,r)=>{let i=LN(n);if(!i){n.baselineSnapshot!==null&&(t.setActivityField(r,"baselineSnapshot",null),e.push(r));return}t.setActivityField(r,"baselineSnapshot",i),e.push(r)}),e}function _l(t,e,n,r,i=null,a=hn){let o=new Set;for(let s of EA(t,e,r,a))o.add(s);if(n)for(let s of ja(t,n,i))o.add(s);for(let s of RA(t))o.add(s);for(let s of Li(t))o.add(s);return[...o]}function El(t,e){let n=new Map;e.forEachActivity((r,i)=>{e.setActivityField(i,E.PONDERATOR,0)}),e.forEachActivity((r,i)=>{e.getChildren(i).length>0&&rl(String(i),t,e,n)})}function Rl(t,e){El(e,t.adapter),Aa(t.adapter,e),t.now&&(fh(t.adapter,t.now,t.defaultBaseCalendarId??null),Er(t.adapter,t.now)),Li(t.adapter),t.now&&un(t.adapter,t.sector.statusCriteria)}function PA(t){return JSON.stringify(t.adapter.getAllIds().map(e=>{let n=t.adapter.getActivity(e)?.baselinePoints.find(r=>r.isActiveVersion);return n?[String(e),n.versionId,n.startDate?.getTime()??null,n.endDate?.getTime()??null,n.durationDays,n.cost,n.workHours,n.baseCalendarId,n.hoursPerDay,n.hoursPerWeek]:[String(e),null]}))}async function kA(t,e){let n=await yt(e.adapter,new Set(e.adapter.getAllIds())),r=PA(e),i=_l(e.adapter,t.points,e.now,e.reporter,e.defaultBaseCalendarId??null,void 0);return Rr(e.adapter,e.sector.hoursPerDay),Pr(e.adapter,e.sector.hoursPerDay),PA(e)!==r&&Rl(e,e.sector.activityCreter??Tt.DURATION),{ok:!0,changes:await et(e.adapter,{source:t,beforeSnap:n,touchedIds:i,scheduledIds:[],hoursPerDay:e.sector.hoursPerDay})}}function ON(t){return Object.values(Tt).includes(t)}async function bA(t,e){if(!ON(t.criterion))return{ok:!1,reason:D.INVALID_VALUE};let n=new Set(e.adapter.getAllIds()),r=await yt(e.adapter,n);return Rl(e,t.criterion),e.sector.activityCreter=t.criterion,{ok:!0,changes:await et(e.adapter,{source:t,beforeSnap:r,touchedIds:n,scheduledIds:[],hoursPerDay:e.sector.hoursPerDay})}}async function LA(t,e){let n=ks(t.criteria),r=new Set(e.adapter.getAllIds()),i=await yt(e.adapter,r),a=un(e.adapter,n);return e.sector.statusCriteria=n,{ok:!0,changes:await et(e.adapter,{source:t,beforeSnap:i,touchedIds:a,scheduledIds:[],hoursPerDay:e.sector.hoursPerDay})}}async function NA(t,e,n){let r=new Map,i=new Set;for(let o of n.adapter.getAllActivities()){if(!NN(o,n))continue;let s=n.ctx.calendars.getCalendar(o.calendarId);if(!s)continue;let l=s.isWorkTime(o.startDate,gt.HOUR)?FN(o.startDate):o.startDate,c=s.getClosestWorkTime({date:l,direction:mt.FUTURE,unit:gt.HOUR}),d=s.calculateEndDate(c,o.durationHours);if(OA(c,o.startDate)&&OA(d,o.endDate))continue;let u=String(o.id);r.set(u,ct(o)),i.add(u),n.adapter.setActivityFields(u,{startDate:c,endDate:d})}let{scheduledIds:a}=await ot({adapter:n.adapter,scheduler:n.scheduler,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:Pt.ROOTS,recomputeParentsFrom:i,now:n.now,options:e});return{ok:!0,changes:await et(n.adapter,{source:t,beforeSnap:r,touchedIds:i,scheduledIds:a,hoursPerDay:n.sector.hoursPerDay})}}function NN(t,e){return!Me(t.type,e.adapter.hasChildren(t.id))}function OA(t,e){return t.getTime()===e.getTime()}function FN(t){return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()))}var FA=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","cost","hasCustomPonderator","subcontractId","responsableIds","tagIds"];function Pl(t){let e={};for(let n of FA)Object.assign(e,{[n]:C(t[n])});return e}function wN(t,e){let n=[],r=i=>{e.has(String(i))&&n.push(i);for(let a of t.getChildren(i))r(a)};for(let i of t.getRootIds())r(i);return n}function xA(t,e){let n=new Set(e.adapter.checkedIds().map(String));if(n.size===0)return{ok:!1,reason:D.NO_ACTIVITY_SELECTION};let r=wN(e.adapter,n);e.clipboard.value={activities:r.map(a=>{let o=e.adapter.getActivity(a);if(o===null)throw new Error(`Selected activity ${a} is missing`);return{originalId:a,originalParentId:o.parentId??"0",overrides:Pl(o)}}),links:e.adapter.getAllLinks().filter(a=>n.has(String(a.source))&&n.has(String(a.target))).map(a=>C(a))};let i=Oo({kind:I.SELECTION_REPLACE,activityIds:[]},{adapter:e.adapter});return i.ok?{...i,changes:{...i.changes,source:t}}:i}function MA(t){return{ok:!0,changes:{source:t,activities:[],links:[],calendars:[],trackingEvents:[]}}}function UA(t,e){return e.value=null,MA(t)}function wA(t,e){if(t===void 0||e===void 0)return t;let n=new Set(e);return t.filter(r=>n.has(r))}function xN(t,e,n){let r=C(t);r.calendarId!=null&&!e.calendars.has(r.calendarId)&&delete r.calendarId,n?.subcontractIds!==void 0&&r.subcontractId!=null&&!n.subcontractIds.includes(r.subcontractId)&&(r.subcontractId=null);let o=wA(r.responsableIds,n?.responsableIds);o!==void 0&&(r.responsableIds=[...o]);let s=wA(r.tagIds,n?.tagIds);return s!==void 0&&(r.tagIds=[...s]),r}function MN(t){let e=new Set(t.activities.map(n=>String(n.originalId)));return t.links.some(n=>!e.has(String(n.source))||!e.has(String(n.target)))}function HA(t,e){let{snapshot:n,references:r}=t;return n.activities.length===0?{ok:!1,reason:D.CLIPBOARD_EMPTY}:MN(n)?{ok:!1,reason:D.CLIPBOARD_SNAPSHOT_INVALID}:(e.clipboard.value={activities:n.activities.map(i=>({originalId:i.originalId,originalParentId:i.originalParentId,overrides:xN(i.overrides,e,r)})),links:n.links.map(i=>C(i))},MA(t))}var UN=200,BA={skipCorrelativeRecompute:!0,skipBeforeSnap:!0,skipCacheInvalidation:!0,skipRollupCascades:!0};async function jA(t,e,n){let r=HN(t.activityIds,n.adapter);if(!r.ok)return r;if(BN(r.runs,n.adapter))return{ok:!1,reason:D.PARENT_FROZEN_BY_SIR};n.scheduler.invalidateAllCaches();let a=await yt(n.adapter,new Set),o={originalToNew:new Map,createdIds:[],createdParentIds:[]};for(let y of r.runs){let f=y.originals.at(-1);if(!f)continue;let m=f.id;for(let A of y.originals)m=await KN(A,y.parentId,m,t,n,o)}GN(o,n);let s=Bt(n.adapter),l=new Set(o.createdIds.map(String)),c=new Set;WN(n.adapter,s,l,a);let d=Ie(n.adapter,s,l,a,c);for(let y of o.createdIds)c.add(String(y));let u=qN(o,n),{scheduledIds:p}=await ot({adapter:n.adapter,scheduler:n.scheduler,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId,runAutomaticP6Schedule:n.runAutomaticP6Schedule},{action:t,autoscheduleFrom:o.createdIds.length>0?Pt.ROOTS:null,recomputeParentsFrom:o.createdIds,preventSummaryTargetPullback:!0,now:n.now,options:e});return{ok:!0,changes:await et(n.adapter,{source:t,beforeSnap:a,deferredCorrelatives:d,touchedIds:c,scheduledIds:p,links:qn(u,new Map,n.adapter),hoursPerDay:n.sector.hoursPerDay})}}function HN(t,e){if(t.length===0)return{ok:!1,reason:D.ACTIVITY_IDS_EMPTY};let n=new Set,r=[];for(let o of t){let s=String(o);if(n.has(s))continue;let l=e.getActivity(s);if(!l)return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};n.add(s),r.push(l)}let i=r.filter(o=>!zn(o.id,n,e));return e.getRootIds().length===1&&i.some(o=>o.parentId==null)?{ok:!1,reason:D.SOLE_SCHEDULE_ROOT}:{ok:!0,runs:jN(i,e)}}function BN(t,e){let n=new Set;for(let r of t){if(r.parentId==="0"||n.has(String(r.parentId)))continue;n.add(String(r.parentId));let i=e.getActivity(r.parentId);if(i&&Nr(i))return i}return null}function jN(t,e){let n=new Map;for(let i of t){let a=pe(i.parentId),o=n.get(a)??[];o.push(i),n.set(a,o)}let r=[];for(let[i,a]of n){let o=i==="0"?"0":i,s=new Map(VA(e,i).map((d,u)=>[String(d.id),u])),l=d=>s.get(String(d.id))??-1,c=[...a].sort((d,u)=>l(d)-l(u));for(let d of VN(c,l))r.push({parentId:o,originals:d})}return r}function VN(t,e){let n=[],r=null;for(let i of t){let a=e(i),o=n.at(-1);o&&r!==null&&a===r+1?o.push(i):n.push([i]),r=a}return n}function WN(t,e,n,r){let i=t.peekWriteCapture();if(i)for(let a of e){if(n.has(a.activityId)||r.has(a.activityId))continue;let o=i.before.get(a.activityId);o&&r.set(a.activityId,o)}}function VA(t,e){return Xa(t,e).sort((n,r)=>ee(n)-ee(r)||String(n.id).localeCompare(String(r.id)))}async function KN(t,e,n,r,i,a){let o=await $n({kind:I.ACTIVITY_CREATE,parentId:e,afterSiblingId:n,overrides:Pl(t),...r.eventSource===void 0?{}:{eventSource:r.eventSource}},i,{...BA,customIdReferenceId:t.id});if(!o.ok)throw hu("create",o.reason);return WA(a,t,o.newId,e),await YN(t,o.newId,r,i,a),o.newId}async function YN(t,e,n,r,i){let a=new _e;a.enqueue({original:t,newParentId:e});let o=0;for(;!a.isEmpty();){let{original:s,newParentId:l}=a.dequeue();for(let c of VA(r.adapter,String(s.id))){let d=await $n({kind:I.ACTIVITY_CREATE,parentId:l,overrides:Pl(c),...n.eventSource===void 0?{}:{eventSource:n.eventSource}},r,BA);if(!d.ok)throw hu("create",d.reason);WA(i,c,d.newId,l),a.enqueue({original:c,newParentId:d.newId}),o+=1,o%UN===0&&await wt()}}}function hu(t,e){return new Error(`[ScheduleCore] activity-duplicate: unexpected ${t} rejection after preflight passed (${e})`)}function WA(t,e,n,r){t.originalToNew.set(String(e.id),n),t.createdIds.push(n),t.createdParentIds.push(r)}function GN(t,e){let n=new Set;for(let r of[...t.createdParentIds].reverse())r==="0"||n.has(String(r))||(n.add(String(r)),zt(r,e.adapter))}function qN(t,e){let n=[];for(let r of t.originalToNew.keys())for(let i of e.adapter.getOutgoingLinkIds(r)){let a=e.adapter.getLink(i);if(!a)continue;let o=t.originalToNew.get(String(a.source)),s=t.originalToNew.get(String(a.target));if(o===void 0||s===void 0)continue;let l={kind:Ut.CREATE,source:o,target:s,type:a.type,lag:a.lag},c=Xe(l,{port:e.adapter,newLinkId:e.linkIdGen.next});if(!c.applied)throw hu("link",c.rejected??D.INVALID);n.push({op:l,finalLinkId:c.linkId,rejected:null})}return n}var qi={FIELD:"field",LINKS:"links"};function $N(t,e,n){return Fi(t,e,n).map(r=>({otherActivityId:n?r.source:r.target,type:r.type,lag:r.lag}))}function mu(t){return{ok:!0,changes:{source:t,activities:[],links:[],calendars:[],trackingEvents:[]}}}function KA(t,e){let n=e.adapter.getActivity(t.activityId);if(!n)return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};if(t.column===E.CUSTOM_PREDECESSORS||t.column===E.CUSTOM_SUCESSORS)return e.clipboard.value={kind:qi.LINKS,specs:$N(e.adapter,t.activityId,t.column===E.CUSTOM_PREDECESSORS)},mu(t);let r=ge(t.column);if(!r)return{ok:!1,reason:D.NO_PIPELINE_FOR_COLUMN};let i=Mi(n,r.targetField);if(t.column===E.DURATION&&!Number.isFinite(i))return{ok:!1,reason:D.INVALID_VALUE};let a=t.column===E.DURATION?i/e.hoursPerDay:C(i);return e.clipboard.value={kind:qi.FIELD,raw:a,sourceColumn:t.column,text:t.copiedText??null},mu(t)}function YA(t,e){return e.value=null,mu(t)}var GA=new Set([E.TAGS,E.RESPONSABLES,E.SUBCONTRACT_ID,E.CONSTRAINT_TYPE,E.CALENDAR_ID]);function zN(t,e){return t===e?!1:GA.has(t)||GA.has(e)}function JN(t,e){return e===void 0||t!==null&&(t.text===null||t.text===e)?null:e}function XN(t,e,n){let r=t!==null&&t.kind===qi.FIELD?t:null,i=JN(r,n);return i!==null?{ok:!0,newValue:i}:t!==null&&t.kind!==qi.FIELD?{ok:!1,reason:D.INVALID_VALUE}:r===null?{ok:!1,reason:D.CLIPBOARD_EMPTY}:zN(r.sourceColumn,e)?{ok:!1,reason:D.CELL_PASTE_COLUMN_MISMATCH}:{ok:!0,newValue:r.raw}}function ZN(t){return String(t)}function QN(t,e){let n=e;return t.activityExists(n)?n:null}function tF(t,e,n,r){let i=n.specs.map(l=>({correlativeId:ZN(l.otherActivityId),type:l.type,lag:l.lag})),a=Fi(r.adapter,t,e),o=l=>QN(r.adapter,l);return(e?Ti({targetActivityId:t,currentLinks:a,desiredSpecs:i,resolveActivityByCorrelative:o}):_i({sourceActivityId:t,currentLinks:a,desiredSpecs:i,resolveActivityByCorrelative:o})).operations}async function eF(t,e,n,r){if(e===null)return{ok:!1,reason:D.CLIPBOARD_EMPTY};if(e.kind!==qi.LINKS)return{ok:!1,reason:D.INVALID_VALUE};if(t.activityIds.some(c=>e.specs.some(d=>String(d.otherActivityId)===String(c))))return{ok:!1,reason:Ot.SELF_LINK};let a=t.column===E.CUSTOM_PREDECESSORS,o=t.activityIds.flatMap(c=>tF(c,a,e,r)),s=o.filter(c=>c.kind===Ut.CREATE).map(c=>({operation:c,linkId:r.linkIdGen.next()})),l=Ba(s,{port:r.adapter,rejectParentLinkMutations:n.rejectParentLinkMutations??!1});return l.applied?za(o,t,n,r):{ok:!1,reason:l.rejected??D.INVALID}}async function qA(t,e,n){let r=n.cellClipboard.value;if(t.activityIds.length===0)return{ok:!1,reason:D.ACTIVITY_IDS_EMPTY};if(t.activityIds.some(l=>!n.adapter.activityExists(l)))return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};if(t.column===E.CUSTOM_PREDECESSORS||t.column===E.CUSTOM_SUCESSORS)return eF(t,r,e,n);if(!ge(t.column))return{ok:!1,reason:D.NO_PIPELINE_FOR_COLUMN};let a=t.column,o=XN(r,a,t.clipboardText);if(!o.ok)return o;let s=await Il({kind:I.BULK_EDIT,edits:t.activityIds.map(l=>({activityId:l,column:a,newValue:o.newValue})),...t.eventSource===void 0?{}:{eventSource:t.eventSource}},e,n);return s.ok?{...s,changes:{...s.changes,source:t}}:s}async function $A(t,e,n){return t.kind===I.ACTIVITY_COPY?xA(t,{adapter:n.adapter,clipboard:n.activityClipboard}):t.kind===I.CALENDAR_RECONCILE?NA(t,e,n):t.kind===I.ACTIVITY_CLIPBOARD_CLEAR?UA(t,n.activityClipboard):t.kind===I.ACTIVITY_CLIPBOARD_IMPORT?HA(t,{clipboard:n.activityClipboard,calendars:n.calendars}):t.kind===I.ACTIVITY_PASTE_COPIED?eg(t,e,n):t.kind===I.ACTIVITY_DUPLICATE?jA(t,e,n):t.kind===I.CELL_COPY?KA(t,{adapter:n.adapter,clipboard:n.cellClipboard,hoursPerDay:n.sector.hoursPerDay}):t.kind===I.CELL_CLIPBOARD_CLEAR?YA(t,n.cellClipboard):t.kind===I.CELL_PASTE_COPIED?qA(t,e,n):t.kind===qe?fg(t,e,n):t.kind===I.PERSISTENCE_ACKNOWLEDGE?Tg(t,n):t.kind===I.PERSISTENCE_REBASE?_A(t,e,n):t.kind===I.BASELINE_APPLY?kA(t,n):t.kind===I.PONDERATOR_CRITERION_SET?bA(t,n):t.kind===I.STATUS_CRITERIA_SET?LA(t,n):t.kind===I.LINK_CREATE||t.kind===I.LINK_UPDATE||t.kind===I.LINK_DELETE?Bm(t,e,n):t.kind===I.LINKS_BATCH?jm(t,e,n):t.kind===I.ACTIVITY_CREATE?ug(t,e,n):t.kind===I.ACTIVITY_DELETE?cg(t,e,n):t.kind===I.ACTIVITY_MOVE?Fg(t,e,n):t.kind===I.ACTIVITY_INDENT?wg(t,e,n):t.kind===I.ACTIVITY_OUTDENT?xg(t,e,n):t.kind===I.ACTIVITY_TYPE_SET?Mg(t,e,n):t.kind===I.ACTIVITY_FIELDS_RESTORE?gg(t,e,n):t.kind===I.HISTORY_REVERT?Ag(t,e,n):t.kind===I.ACTIVITY_SET_PROGRESS?Ug(t,e,n):t.kind===I.DATES_BATCH?Hg(t,e,n):t.kind===I.BULK_EDIT?Il(t,e,n):t.kind===I.SELECTION_TOGGLE?xp(t,gu(n)):t.kind===I.SELECTION_REPLACE?Oo(t,gu(n)):t.kind===I.VISIBILITY_SET?Mp(t,gu(n)):t.kind===I.FILTER_SET?Zp(t,{adapter:n.adapter,hoursPerDay:n.sector.hoursPerDay}):t.kind===I.SORT_SET?iy(t,{adapter:n.adapter}):t.kind===I.VIEW_ATTRIBUTES_SET?sy(t,{adapter:n.adapter,hoursPerDay:n.sector.hoursPerDay}):t.kind===I.GROUP_SET?ly(t,{adapter:n.adapter,hoursPerDay:n.sector.hoursPerDay}):t.kind===I.WBS_DEPTH_SET?cy(t,{adapter:n.adapter,hoursPerDay:n.sector.hoursPerDay}):t.kind===I.SIR_SYNC?mg(t,n):t.kind===I.ACTIVITY_LOOKAHEAD_SYNC?_g(t,e,n):t.kind===I.ACTIVITY_LOOKAHEAD_CONVERT?bg(t,e,n):t.kind===I.SCHEDULE_AUTO_SCHEDULE?Em(t,e,n):t.kind===I.INLINE_EDIT&&(t.column===E.CUSTOM_PREDECESSORS||t.column===E.CUSTOM_SUCESSORS)?Vm(t,e,n):t.kind!==I.INLINE_EDIT?dy(t,`[ScheduleCore] dispatch kind "${t.kind}" not supported yet`):Hm(t,e,n)}function gu(t){return{adapter:t.adapter}}function io(t={}){let e=t.seed??0,n=r=>{r>e&&(e=r)};if(t.knownIds)for(let r of t.knownIds){let i=typeof r=="number"?r:Number(r);Number.isFinite(i)&&n(i)}return{fork(){return io({seed:e})},next(){return e+=1,String(e)},bump(r){let i=typeof r=="number"?r:Number(r);Number.isFinite(i)&&n(i)},snapshot(){return e},restore(r){e=r}}}function zA(t){return!!t&&typeof t=="string"&&t.trim().length>0}function kl(t){if(!t||typeof t!="string"||t.trim().length===0)return"";let e=t.match(/^(.*?)(\d+)$/);return e?e[1]??"":t}function bl(t){if(!t||typeof t!="string"||t.trim().length===0)return"";let e=t.match(/(\d+)$/);return e?e[1]??"":""}function JA(t){if(!t||typeof t!="object")return"";let e=t.customId;return typeof e=="string"?e:""}function XA(t,e){return!e&&zA(t)}function ZA(t,e){return e&&zA(t)}function ao(t){return typeof t=="string"&&t.length>0&&/^\d+$/.test(t)}function Ll(t){if(!ao(t))return 0n;try{return BigInt(t)}catch{return 0n}}function nF(t,e){if(typeof t!="bigint")return"";let n=t.toString();if(!ao(e))return n;let r=e.length;return n.padStart(r,"0")}function Ne(t,e){let n=Ll(t),r=Ll(e),i=n+r;return nF(i,t)}function Ol(t,e){let n=Ll(t),r=Ll(e);return n<r?-1:n>r?1:0}function Nl(t,e){return Ol(t,e)<=0?t:e}function Fl(t,e){return Ol(t,e)>=0?t:e}function QA(t){if(!t||t.length===0)throw new Error("minSuffixFromArray requires non-empty array");return t.reduce((e,n)=>Nl(e,n))}function tI(t){if(!t||t.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return t.reduce((e,n)=>Fl(e,n))}var mn={PARENT_CONVERSION:"parentConversion",PASTE_REFERENCE:"pasteReference",NO_CONTEXT:"noContext"};function eI(t){return{prefix:t,baseSuffix:null}}function nI(t,e){let n=bl(t);return{prefix:kl(t),baseSuffix:Ne(n,e)}}function rI(t){return{prefix:t,baseSuffix:null}}function iI(t,e){return XA(t,e)?mn.PARENT_CONVERSION:ZA(t,e)?mn.PASTE_REFERENCE:mn.NO_CONTEXT}function aI(t){return{...t,usedSuffixes:new Set(t.usedSuffixes)}}var $i=class t{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 e=this._journalPrefixBefore,n=this._journalIds;if(!(e===null||n===null)){for(let[r,i]of e)i===null?this.prefixMap.delete(r):this.prefixMap.set(r,i);for(let r of[...n].reverse())r.hadId?this.processedIds.add(r.customId):this.processedIds.delete(r.customId);this._journalPrefixBefore=null,this._journalIds=null}}_noteCustomIdBefore(e){if(this._journalPrefixBefore===null||this._journalIds===null)return;let{prefix:n}=this.analyzeCustomId(e);if(!this._journalPrefixBefore.has(n)){let r=this.prefixMap.get(n);this._journalPrefixBefore.set(n,r?aI(r):null)}this._journalIds.push({customId:e,hadId:this.processedIds.has(e)})}_ensureFreshBounds(e){let n=this.prefixMap.get(e);if(!n?.boundsDirty)return;n.boundsDirty=!1;let r=Array.from(n.usedSuffixes);n.min=QA(r),n.max=tI(r),n.quantity=r.length,this._recalculateNext(e)}defaultPrefix;suffixIncrement;constructor(e={}){this.defaultPrefix=e.defaultPrefix??"A",this.suffixIncrement=e.suffixIncrement??"10"}captureRestorePoint(){let e=this.fork();return()=>{this.prefixMap.clear();for(let[n,r]of e.prefixMap)this.prefixMap.set(n,r);this.processedIds.clear();for(let n of e.processedIds)this.processedIds.add(n)}}fork(){let e=new t({defaultPrefix:this.defaultPrefix,suffixIncrement:this.suffixIncrement});for(let[n,r]of this.prefixMap)e.prefixMap.set(n,aI(r));for(let n of this.processedIds)e.processedIds.add(n);return e}snapshot(){let e=this.fork();return{defaultPrefix:this.defaultPrefix,suffixIncrement:this.suffixIncrement,prefixes:e.prefixMap,processedIds:e.processedIds}}static fromSnapshot(e){let n=new t({defaultPrefix:e.defaultPrefix,suffixIncrement:e.suffixIncrement});for(let[r,i]of e.prefixes)n.prefixMap.set(r,i);for(let r of e.processedIds)n.processedIds.add(r);return n}extractPrefix(e){return kl(e)}extractSuffix(e){return bl(e)}analyzeCustomId(e){return{prefix:this.extractPrefix(e),suffix:this.extractSuffix(e)}}_updatePrefixStats(e,n){if(this._ensureFreshBounds(e),!this.prefixMap.has(e)){this.prefixMap.set(e,{min:n,max:n,next:n,quantity:1,usedSuffixes:new Set([n])}),this._recalculateNext(e);return}let r=this.prefixMap.get(e);r.usedSuffixes.has(n)||(r.usedSuffixes.add(n),r.min=Nl(n,r.min),r.max=Fl(n,r.max),r.quantity+=1,this._recalculateNext(e))}_recalculateNext(e){let n=this.prefixMap.get(e);if(!n)return;let r=this.getNextAvailableSuffix(e);n.next=r??this.suffixIncrement}getPrefixStats(e){this._ensureFreshBounds(e);let n=this.prefixMap.get(e);return n?{min:n.min,max:n.max,next:n.next,quantity:n.quantity}:null}getNextSuffix(e){this._ensureFreshBounds(e);let n=this.prefixMap.get(e);return n?n.next:this.suffixIncrement}getAllPrefixes(){return Array.from(this.prefixMap.keys())}registerCustomId(e){if(!e||typeof e!="string")return{prefix:"",suffix:""};let{prefix:n,suffix:r}=this.analyzeCustomId(e);if(!n&&!r)return{prefix:n,suffix:r};if(this._noteCustomIdBefore(e),this._ensureFreshBounds(n),this.prefixMap.has(n)){let i=this.prefixMap.get(n);i.usedSuffixes.has(r)||(i.usedSuffixes.add(r),i.min=Nl(r,i.min),i.max=Fl(r,i.max),i.quantity+=1,this._recalculateNext(n))}else this.prefixMap.set(n,{min:r,max:r,next:Ne(r,this.suffixIncrement),quantity:1,usedSuffixes:new Set([r])});return this.processedIds.add(e),{prefix:n,suffix:r}}releaseCustomId(e=null){if(!e||typeof e!="string")return{prefix:"",suffix:""};let{prefix:n,suffix:r}=this.analyzeCustomId(e);if(!this.prefixMap.has(n))return{prefix:n,suffix:r};this._noteCustomIdBefore(e);let i=this.prefixMap.get(n);return i.usedSuffixes.has(r)&&(i.usedSuffixes.delete(r),i.quantity-=1,i.usedSuffixes.size===0?this.prefixMap.delete(n):i.boundsDirty=!0),this.processedIds.delete(e),{prefix:n,suffix:r}}trackCustomIdChange(e,n){let r=this.releaseCustomId(e),i=this.registerCustomId(n);return{oldPrefix:r.prefix,oldSuffix:r.suffix,newPrefix:i.prefix,newSuffix:i.suffix}}_exceedsMaxLength(e){return e.length>20}_shouldSearchForGaps(e){if(this._ensureFreshBounds(e),!this.prefixMap.has(e))return!1;let n=this.prefixMap.get(e);return`${e}${Ne(n.max,this.suffixIncrement)}`.length>20}_suffixForUnknownPrefix(e,n){let r=n&&ao(n)?n:this.suffixIncrement;return`${e}${r}`.length>20?null:r}_findFirstAvailableGap(e){if(this._ensureFreshBounds(e),!this.prefixMap.has(e))return null;let n=this.prefixMap.get(e),r=this.suffixIncrement;for(;Ol(r,n.max)<0;){if(`${e}${r}`.length>20)return null;if(!n.usedSuffixes.has(r))return r;r=Ne(r,this.suffixIncrement)}return null}_generateDefaultCustomId(){let e=this.getNextAvailableSuffix(this.defaultPrefix);if(e===null){if(this._shouldSearchForGaps(this.defaultPrefix)){let n=this._findFirstAvailableGap(this.defaultPrefix);if(n!==null)return`${this.defaultPrefix}${n}`}return`${this.defaultPrefix}${this.suffixIncrement}`}return`${this.defaultPrefix}${e}`}getNextAvailableSuffix(e,n=null){if(this._ensureFreshBounds(e),!this.prefixMap.has(e))return this._suffixForUnknownPrefix(e,n);let r=this.prefixMap.get(e),i=this.suffixIncrement;if(!n||!ao(n)){let s=Ne(r.max,i);return`${e}${s}`.length>20?null:s}let a=n;for(let s=0;s<100;s++){if(`${e}${a}`.length>20)return null;if(!r.usedSuffixes.has(a))return a;a=Ne(a,i)}let o=Ne(r.max,i);return`${e}${o}`.length>20?null:o}generateNextCustomId(e){let n=this.getNextAvailableSuffix(e);if(n===null)return this._generateDefaultCustomId();if(this.prefixMap.has(e)){let i=this.prefixMap.get(e),a=0;for(;i.usedSuffixes.has(n)&&a<1e4;){let o=this.getNextAvailableSuffix(e,Ne(n,this.suffixIncrement));if(o===null)return this._generateDefaultCustomId();n=o,a++}}let r=`${e}${n}`;return this._exceedsMaxLength(r)&&(r=this._generateDefaultCustomId()),r}populateFromActivities(e){if(!Array.isArray(e))return this;let n=[...new Set(e.filter(r=>r&&typeof r.customId=="string"&&r.customId).map(r=>r.customId))];for(let r of n){if(this.processedIds.has(r))continue;let{prefix:i,suffix:a}=this.analyzeCustomId(r);(i||a)&&(this._updatePrefixStats(i,a),this.processedIds.add(r))}return this}getDefaults(){return{prefix:this.defaultPrefix,increment:this.suffixIncrement}}generateCustomIdForNewChild(e){let{activity:n,useActivityCustomIdAsReference:r=!1}=e,i=JA(n),a=iI(i,r),{prefix:o,baseSuffix:s}=this._applyGenerationStrategy(a,i),l=null;if(a===mn.PARENT_CONVERSION&&this.prefixMap.has(o)){this._ensureFreshBounds(o);let p=this.prefixMap.get(o).max;l=Ne(p,this.suffixIncrement)}a===mn.PARENT_CONVERSION&&this.releaseCustomId(i);let c=a===mn.PARENT_CONVERSION&&l?l:s,d=this.getNextAvailableSuffix(o,c);if(d===null){let p=this._generateDefaultCustomId();return this.registerCustomId(p),p}let u=`${o}${d}`;return this._exceedsMaxLength(u)&&(u=this._generateDefaultCustomId()),this.registerCustomId(u),u}_applyGenerationStrategy(e,n){switch(e){case mn.PARENT_CONVERSION:return eI(this.defaultPrefix);case mn.PASTE_REFERENCE:return nI(n,this.suffixIncrement);default:return rI(this.defaultPrefix)}}generateCustomIdForRestoredChild(e=null){if(e){let r=e.trim();if(r.length>0){let i=this.extractPrefix(r),a=this.extractSuffix(r),o=Ne(a,this.suffixIncrement),s=this.getNextAvailableSuffix(i,o);if(s===null){let c=this._generateDefaultCustomId();return this.registerCustomId(c),c}let l=`${i}${s}`;return this._exceedsMaxLength(l)&&(l=this._generateDefaultCustomId()),this.registerCustomId(l),l}}let n=this.generateNextCustomId(this.defaultPrefix);return this.registerCustomId(n),n}clear(){this.prefixMap.clear(),this.processedIds.clear()}getTotalPrefixes(){return this.prefixMap.size}hasPrefix(e){return this.prefixMap.has(e)}isCustomIdInUse(e,n=null){if(!e||typeof e!="string"||!e.trim())return!1;let r=e.trim();return n&&r===n.trim()?!1:this.processedIds.has(r)}};function oo(t={}){let e=t.seed??0,n=r=>{r>e&&(e=r)};if(t.knownIds)for(let r of t.knownIds){let i=typeof r=="number"?r:Number(r);Number.isFinite(i)&&n(i)}return{fork(){return oo({seed:e})},next(){return e+=1,String(e)},bump(r){let i=typeof r=="number"?r:Number(r);Number.isFinite(i)&&n(i)},snapshot(){return e},restore(r){e=r}}}function so(t={}){let e=t.seed??0,n=r=>{Number.isFinite(r)&&r>0&&r<=9999999&&r>e&&(e=r)};if(t.knownIds)for(let r of t.knownIds){if(r==null)continue;let i=typeof r=="number"?r:Number(r);n(i)}return{fork(){return so({seed:e})},next(){return e+=1,String(e)},bump(r){if(r==null)return;let i=typeof r=="number"?r:Number(r);n(i)},snapshot(){return e},restore(r){e=r}}}var rF=new Set(["startDate","endDate","constraintDate"]);function oI(t,e){return rF.has(t)&&typeof e=="string"?new Date(e):e}var iF=/^\s*(\d{1,2}):(\d{2})\s*-\s*(\d{1,2}):(\d{2})\s*$/,sI="24:00",aF="0:00";function lI(t){let e=iF.exec(t);return e===null?null:{start:Number(e[1])*60+Number(e[2]),end:Number(e[3])*60+Number(e[4])}}function lo(t){let e=Math.floor(t/60),n=String(t%60).padStart(2,"0");return`${e}:${n}`}function oF(t){let e=lI(t),n={windows:[t],overflow:[],isSplit:!1};return e===null||e.start<e.end&&e.end<=1440?n:e.end===0?{...n,windows:[`${lo(e.start)}-${sI}`]}:e.end>1440?n:{windows:[`${lo(e.start)}-${sI}`],overflow:[`${aF}-${lo(e.end)}`],isSplit:!0}}function Au(t,e,n){let r=[],i=[];for(let a of t){if(typeof a!="string"){r.push(a);continue}let o=oF(a);r.push(...o.windows),i.push(...o.overflow),o.isSplit&&n("Calendar shift window crosses midnight and was split",{window:a,scope:e})}return{windows:r,overflow:i}}function cI(t,e){return Array.isArray(t)?t:t===!0?e:[]}function dI(t,e){let n=[],r=[];for(let a of[...t,...e]){let o=typeof a=="string"?lI(a):null;o===null?r.push(a):n.push(o)}n.sort((a,o)=>a.start-o.start);let i=[];for(let a of n){let o=i[i.length-1];o!==void 0&&a.start<=o.end?o.end=Math.max(o.end,a.end):i.push({...a})}return[...i.map(a=>`${lo(a.start)}-${lo(a.end)}`),...r]}function sF(t,e,n){let r=t.map((i,a)=>Array.isArray(i)?Au(i,`weekday ${a}`,n):null);return t.map((i,a)=>{let o=r[a]??null,s=r[(a+7-1)%7]?.overflow??[];return s.length>0?dI(o?.windows??cI(i,e),s):o===null?i:o.windows})}function lF(t){let e=Number(t);return Number.isInteger(e)&&e%864e5===0?String(e+864e5):null}function cF(t,e,n,r){let i={},a=new Map;for(let[o,s]of Object.entries(t)){if(!Array.isArray(s)){i[o]=s;continue}let l=Au(s,`date ${o}`,r);i[o]=l.windows;let c=lF(o);l.overflow.length===0||c===null||c in t||a.set(c,[...a.get(c)??[],...l.overflow])}for(let[o,s]of a){let l=new Date(Number(o)).getUTCDay();i[o]=dI(cI(e[l],n),s)}return i}function uI(t,e){let n=t.hours===void 0?void 0:Au(t.hours,"hours",e).windows,r=n??[],i=t.days&&sF(t.days,r,e),a=t.dates&&cF(t.dates,i??[],r,e);return{hours:n,days:i,dates:a}}function dF(t){return Array.isArray?Array.isArray(t):t&&t.length!==void 0&&t.pop&&t.push}function jr(t){return t&&typeof t=="object"?!!(t.getFullYear&&t.getMonth&&t.getDate):!1}function Vr(t){return jr(t)&&!isNaN(t.getTime())}var uF={}.constructor.toString();function pF(t){var e=t.constructor.toString();return e!==uF}function yF(t){return t.$$typeof&&t.$$typeof.toString().includes("react.")}function We(t){var e,n;if(t&&typeof t=="object")switch(!0){case jr(t):n=new Date(t);break;case dF(t):for(n=new Array(t.length),e=0;e<t.length;e++)n[e]=We(t[e]);break;default:if(pF(t))n=Object.create(t);else{if(yF(t))return n=t,n;n={}}for(e in t)Object.prototype.hasOwnProperty.apply(t,[e])&&(n[e]=We(t[e]));break}return n||t}function zi(t,e,n){for(var r in e)(t[r]===void 0||n)&&(t[r]=e[r]);return t}function pI(t){return typeof t<"u"}var wl;function Iu(){return wl||(wl=new Date().valueOf()),wl++,wl}function De(t,e){return t.bind?t.bind(e):function(){return t.apply(e,arguments)}}var hF=(t,e,n)=>{t=t.replace(/%[a-zA-Z]/g,i=>{switch(i){case"%d":return`"+to_fixed(date.get${e?"UTC":""}Date())+"`;case"%m":return`"+to_fixed((date.get${e?"UTC":""}Month()+1))+"`;case"%j":return`"+date.get${e?"UTC":""}Date()+"`;case"%n":return`"+(date.get${e?"UTC":""}Month()+1)+"`;case"%y":return`"+to_fixed(date.get${e?"UTC":""}FullYear()%100)+"`;case"%Y":return`"+date.get${e?"UTC":""}FullYear()+"`;case"%D":return`"+locale.date.day_short[date.get${e?"UTC":""}Day()]+"`;case"%l":return`"+locale.date.day_full[date.get${e?"UTC":""}Day()]+"`;case"%M":return`"+locale.date.month_short[date.get${e?"UTC":""}Month()]+"`;case"%F":return`"+locale.date.month_full[date.get${e?"UTC":""}Month()]+"`;case"%h":return`"+to_fixed((date.get${e?"UTC":""}Hours()+11)%12+1)+"`;case"%g":return`"+((date.get${e?"UTC":""}Hours()+11)%12+1)+"`;case"%G":return`"+date.get${e?"UTC":""}Hours()+"`;case"%H":return`"+to_fixed(date.get${e?"UTC":""}Hours())+"`;case"%i":return`"+to_fixed(date.get${e?"UTC":""}Minutes())+"`;case"%a":return`"+(date.get${e?"UTC":""}Hours()>11?"pm":"am")+"`;case"%A":return`"+(date.get${e?"UTC":""}Hours()>11?"PM":"AM")+"`;case"%s":return`"+to_fixed(date.get${e?"UTC":""}Seconds())+"`;case"%W":return'"+to_fixed(getISOWeek(date))+"';case"%w":return'"+to_fixed(getWeek(date))+"';default:return i}});let r=new Function("date","to_fixed","locale","getISOWeek","getWeek",`return "${t}";`);return i=>r(i,n.date.to_fixed,n.locale,n.date.getISOWeek,n.date.getWeek)},mF=(t,e,n)=>{let r="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);",i=t.match(/%[a-zA-Z]/g);for(let s=0;s<i.length;s++)switch(i[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 a="set[0],set[1],set[2],set[3],set[4],set[5]";e&&(a=` Date.UTC(${a})`);let o=new Function("date","locale",`var set=[0,0,1,0,0,0]; ${r} return new Date(${a});`);return s=>o(s,n.locale)},yI={date_to_str:hF,str_to_date:mF},gF=(t,e,n)=>r=>t.replace(/%[a-zA-Z]/g,i=>{switch(i){case"%d":return e?n.date.to_fixed(r.getUTCDate()):n.date.to_fixed(r.getDate());case"%m":return e?n.date.to_fixed(r.getUTCMonth()+1):n.date.to_fixed(r.getMonth()+1);case"%j":return e?r.getUTCDate():r.getDate();case"%n":return e?r.getUTCMonth()+1:r.getMonth()+1;case"%y":return e?n.date.to_fixed(r.getUTCFullYear()%100):n.date.to_fixed(r.getFullYear()%100);case"%Y":return e?r.getUTCFullYear():r.getFullYear();case"%D":return e?n.locale.date.day_short[r.getUTCDay()]:n.locale.date.day_short[r.getDay()];case"%l":return e?n.locale.date.day_full[r.getUTCDay()]:n.locale.date.day_full[r.getDay()];case"%M":return e?n.locale.date.month_short[r.getUTCMonth()]:n.locale.date.month_short[r.getMonth()];case"%F":return e?n.locale.date.month_full[r.getUTCMonth()]:n.locale.date.month_full[r.getMonth()];case"%h":return e?n.date.to_fixed((r.getUTCHours()+11)%12+1):n.date.to_fixed((r.getHours()+11)%12+1);case"%g":return e?(r.getUTCHours()+11)%12+1:(r.getHours()+11)%12+1;case"%G":return e?r.getUTCHours():r.getHours();case"%H":return e?n.date.to_fixed(r.getUTCHours()):n.date.to_fixed(r.getHours());case"%i":return e?n.date.to_fixed(r.getUTCMinutes()):n.date.to_fixed(r.getMinutes());case"%a":return e?r.getUTCHours()>11?"pm":"am":r.getHours()>11?"pm":"am";case"%A":return e?r.getUTCHours()>11?"PM":"AM":r.getHours()>11?"PM":"AM";case"%s":return e?n.date.to_fixed(r.getUTCSeconds()):n.date.to_fixed(r.getSeconds());case"%W":return e?n.date.to_fixed(n.date.getUTCISOWeek(r)):n.date.to_fixed(n.date.getISOWeek(r));case"%w":return n.date.to_fixed(n.date.getWeek(r));default:return i}}),AF=(t,e,n)=>r=>{let i=[0,0,1,0,0,0],a=r.match(/[a-zA-Z]+|[0-9]+/g),o=t.match(/%[a-zA-Z]/g);for(let s=0;s<o.length;s++)switch(o[s]){case"%j":case"%d":i[2]=a[s]||1;break;case"%n":case"%m":i[1]=(a[s]||1)-1;break;case"%y":i[0]=a[s]*1+(a[s]>50?1900:2e3);break;case"%g":case"%G":case"%h":case"%H":i[3]=a[s]||0;break;case"%i":i[4]=a[s]||0;break;case"%Y":i[0]=a[s]||0;break;case"%a":case"%A":i[3]=i[3]%12+((a[s]||"").toLowerCase()==="am"?0:12);break;case"%s":i[5]=a[s]||0;break;case"%M":i[1]=n.locale.date.month_short_hash[a[s]]||0;break;case"%F":i[1]=n.locale.date.month_full_hash[a[s]]||0;break}return e?new Date(Date.UTC(i[0],i[1],i[2],i[3],i[4],i[5])):new Date(i[0],i[1],i[2],i[3],i[4],i[5])},fI={date_to_str:gF,str_to_date:AF};function hI(t){var e=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function n(s){var l=new Date(s);return isNaN(l.getTime())?null:l}var r=null;function i(){try{new Function("canUseCsp = false;")}catch{r=!0}}function a(){var s=!1;return t.config.csp==="auto"?(r===null&&i(),s=r):s=t.config.csp,s}var o={_isoDateDetected:!1,_isoDateOnly:!1,formatISODate:function(s){return s.toISOString()},formatISODateOnly:function(s){return s.getUTCFullYear()+"-"+t.date.to_fixed(s.getUTCMonth()+1)+"-"+t.date.to_fixed(s.getUTCDate())},init:function(){for(var s=t.locale,c=s.date.month_short,d=s.date.month_short_hash={},l=0;l<c.length;l++)d[c[l]]=l;for(var c=s.date.month_full,d=s.date.month_full_hash={},l=0;l<c.length;l++)d[c[l]]=l},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 l=s.getUTCDay();return t.config.start_on_monday&&(l===0?l=6:l--),this.date_part(this.add(s,-1*l,"day"))},month_start:function(s){return s.setUTCDate(1),this.date_part(s)},quarter_start:function(s){this.month_start(s);var l=s.getUTCMonth(),c;return l>=9?c=9:l>=6?c=6:l>=3?c=3:c=0,s.setUTCMonth(c),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,l,c){return s.setUTCDate(s.getUTCDate()+l),s},add:function(s,l,c){var d=new Date(s.valueOf());switch(c){case"day":d=this._add_days(d,l,s);break;case"week":d=this._add_days(d,l*7,s);break;case"month":d.setUTCMonth(d.getUTCMonth()+l);break;case"year":d.setUTCFullYear(d.getUTCFullYear()+l);break;case"hour":d.setTime(d.getTime()+l*60*60*1e3);break;case"minute":d.setTime(d.getTime()+l*60*1e3);break;default:return this["add_"+c](s,l,c)}return d},add_quarter:function(s,l){return this.add(s,l*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,l){var c=yI;return a()&&(c=fI),c.date_to_str(s,l,t)},str_to_date:function(s,l){var c=yI;return a()&&(c=fI),c.str_to_date(s,l,t)},getISOWeek:function(s){return t.date._getWeekNumber(s,!0)},_getWeekNumber:function(s,l){if(!s)return!1;var c=s.getUTCDay();l&&c===0&&(c=7);var d=new Date(s.valueOf());d.setUTCDate(s.getUTCDate()+(4-c));var u=d.getUTCFullYear(),p=Math.round((d.getTime()-Date.UTC(u,0,1))/864e5),y=1+Math.floor(p/7);return y},getWeek:function(s){return t.date._getWeekNumber(s,t.config.start_on_monday)},getUTCISOWeek:function(s){return t.date.getISOWeek(s)},parseDate:function(s,l){if(s&&!s.getFullYear){var c=!l||l==="parse_date"||l==="xml_date",d=c&&(t.defined(t.templates.xml_date)||t.templates.parse_date&&!t.templates.parse_date._ganttAuto);if(!d&&typeof s=="string"&&e.test(s)){var u=s.indexOf("T")!==-1,p=n(s);if(p)return o._isoDateDetected?u&&(o._isoDateOnly=!1):(o._isoDateDetected=!0,o._isoDateOnly=!u),p}typeof l!="function"&&(typeof l=="string"?l==="parse_date"||l==="xml_date"?l=t.defined(t.templates.xml_date)?t.templates.xml_date:t.templates.parse_date:l=t.defined(t.templates[l])?t.templates[l]:t.date.str_to_date(l,!0):l=t.defined(t.templates.xml_date)?t.templates.xml_date:t.templates.parse_date),s?s=l(s):s=null}return s}};return o}function Su(t,e,n,r,i){return this.date=t,this.unit=e,this.task=n,this.id=r,this.calendar=i,this}function vu(t,e,n,r,i,a){return this.date=t,this.dir=e,this.unit=n,this.task=r,this.id=i,this.calendar=a,this}function Cu(t,e,n,r,i,a,o){return this.start_date=t,this.duration=e,this.unit=n,this.step=r,this.task=i,this.id=a,this.calendar=o,this}function IF(t,e,n,r){return this.start_date=t,this.end_date=e,this.task=n,this.calendar=r,this.unit=null,this.step=null,this}var mI=function(t){return{getWorkHoursArguments:function(){var e=arguments[0];if(jr(e)?e={date:e}:e=zi({},e),!Vr(e.date))throw t.assert(!1,"Invalid date argument for getWorkHours method"),new Error("Invalid date argument for getWorkHours method");return e},setWorkTimeArguments:function(){return arguments[0]},unsetWorkTimeArguments:function(){return arguments[0]},isWorkTimeArguments:function(){var e=arguments[0];if(e instanceof Su)return e;var n;if(e.date?n=new Su(e.date,e.unit,e.task,null,e.calendar):n=new Su(arguments[0],arguments[1],arguments[2],null,arguments[3]),n.unit=n.unit||t.config.duration_unit,!Vr(n.date))throw t.assert(!1,"Invalid date argument for isWorkTime method"),new Error("Invalid date argument for isWorkTime method");return n},getClosestWorkTimeArguments:function(e){var n=arguments[0];if(n instanceof vu)return n;var r;if(jr(n)?r=new vu(n):r=new vu(n.date,n.dir,n.unit,n.task,null,n.calendar),n.id&&(r.task=n),r.dir=n.dir||"any",r.unit=n.unit||t.config.duration_unit,!Vr(r.date))throw t.assert(!1,"Invalid date argument for getClosestWorkTime method"),new Error("Invalid date argument for getClosestWorkTime method");return r},_getStartEndConfig:function(e){var n=IF,r;if(e instanceof n)return e;if(jr(e)?r=new n(arguments[0],arguments[1],arguments[2],arguments[3]):(r=new n(e.start_date,e.end_date,e.task),e.id!==null&&e.id!==void 0&&(r.task=e)),r.unit=r.unit||t.config.duration_unit,r.step=r.step||t.config.duration_step,r.start_date=r.start_date||r.start||r.date,!Vr(r.start_date))throw t.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!Vr(r.end_date))throw t.assert(!1,"Invalid end_date argument for getDuration method"),new Error("Invalid end_date argument for getDuration method");return r},getDurationArguments:function(e,n,r,i){return this._getStartEndConfig.apply(this,arguments)},hasDurationArguments:function(e,n,r,i){return this._getStartEndConfig.apply(this,arguments)},calculateEndDateArguments:function(e,n,r,i){var a=arguments[0];if(a instanceof Cu)return a;var o;if(jr(a)?o=new Cu(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):o=new Cu(a.start_date,a.duration,a.unit,a.step,a.task,null,a.calendar),a.id!==null&&a.id!==void 0&&(o.task=a,o.unit=null,o.step=null),o.unit=o.unit||t.config.duration_unit,o.step=o.step||t.config.duration_step,!Vr(o.start_date))throw t.assert(!1,"Invalid start_date argument for calculateEndDate method"),new Error("Invalid start_date argument for calculateEndDate method");return o}}};function gI(){}gI.prototype={_getIntervals:function(t){for(var e=[],n=0;n<t.length;n+=2)e.push({start:t[n],end:t[n+1]});return e},_toHoursArray:function(t){var e=[];function n(a){var o=String(a);return o.length<2&&(o="0"+o),o}function r(a){var o=Math.floor(a/3600),s=a-o*60*60,l=Math.floor(s/60);return o+":"+n(l)}for(var i=0;i<t.length;i++)e.push(r(t[i].start)+"-"+r(t[i].end));return e},_intersectHourRanges:function(t,e){var i=[],n=t.length>e.length?t:e,r=t===n?e:t;n=n.slice(),r=r.slice();for(var i=[],a=0;a<n.length;a++)for(var o=n[a],s=0;s<r.length;s++){var l=r[s];l.start<o.end&&l.end>o.start&&(i.push({start:Math.max(o.start,l.start),end:Math.min(o.end,l.end)}),o.end>l.end&&(r.splice(s,1),s--,a--))}return i},_mergeAdjacentIntervals:function(t){var e=t.slice();e.sort(function(a,o){return a.start-o.start});for(var n=e[0],r=1;r<e.length;r++){var i=e[r];i.start<=n.end?(i.end>n.end&&(n.end=i.end),e.splice(r,1),r--):n=i}return e},_mergeHoursConfig:function(t,e){return this._mergeAdjacentIntervals(this._intersectHourRanges(t,e))},merge:function(t,e){let n=We(t.getConfig()),r=We(e.getConfig()),i=n.parsed,a=r.parsed;i.customWeeks=n.customWeeks,a.customWeeks=r.customWeeks;var o={hours:this._toHoursArray(this._mergeHoursConfig(i.hours,a.hours)),dates:{},customWeeks:{}};let s=(c,d)=>{for(let u in c.dates){let p=c.dates[u];+u>1e3&&(o.dates[u]=!1);for(let y in d.dates){let f=d.dates[y];if(y==u&&(o.dates[u]=!!(p&&f)),Array.isArray(p)){let m=Array.isArray(f)?f:d.hours;o.dates[u]=this._toHoursArray(this._mergeHoursConfig(p,m))}}}};if(s(i,a),s(a,i),i.customWeeks)for(var l in i.customWeeks)o.customWeeks[l]=i.customWeeks[l];if(a.customWeeks)for(var l in a.customWeeks)o.customWeeks[l]?o.customWeeks[l+"_second"]=a.customWeeks[l]:o.customWeeks[l]=a.customWeeks[l];return o}};var Du=class{constructor(){this.clear()}getItem(e,n,r){if(this._cache.has(e)){let a=this._cache.get(e)[r.getUTCFullYear()];if(a&&a.has(n))return a.get(n)}return-1}setItem(e,n,r,i){if(!e||!n)return;let a=this._cache,o=i.getUTCFullYear(),s;a.has(e)?s=a.get(e):(s=[],a.set(e,s));let l=s[o];l||(l=s[o]=new Map),l.set(n,r)}clear(){this._cache=new Map}},Tu=class{constructor(){this.clear()}getItem(e,n,r){let i=this._cache;if(i&&i[e]){let a=i[e];if(a===void 0)return-1;let o=a[r.getUTCFullYear()];if(o&&o[n]!==void 0)return o[n]}return-1}setItem(e,n,r,i){if(!e||!n)return;let a=this._cache;if(!a)return;a[e]||(a[e]=[]);let o=a[e],s=i.getUTCFullYear(),l=o[s];l||(l=o[s]={}),l[n]=r}clear(){this._cache={}}},_u=class{constructor(e){this.getMinutesPerWeek=n=>{let r=n.valueOf();if(this._weekCache.has(r))return this._weekCache.get(r);let i=this._calendar,a=this._calendar.$gantt,o=0,s=a.date.week_start(new Date(n));for(let l=0;l<7;l++)o+=i.getHoursPerDay(s)*60,s=a.date.add(s,1,"day");return this._weekCache.set(r,o),o},this.getMinutesPerMonth=n=>{let r=n.valueOf();if(this._monthCache.has(r))return this._monthCache.get(r);let i=this._calendar,a=this._calendar.$gantt,o=0,s=a.date.week_start(new Date(n)),l=a.date.add(s,1,"month").valueOf();for(;s.valueOf()<l;)o+=i.getHoursPerDay(s)*60,s=a.date.add(s,1,"day");return this._monthCache.set(r,o),o},this.clear=()=>{this._weekCache=new Map,this._monthCache=new Map},this.clear(),this._calendar=e}};function SF(){return typeof Map<"u"?new Du:new Tu}var Eu=class{constructor(){this.clear()}_getCacheObject(e,n,r){let i=this._cache;i[n]||(i[n]=[]);let a=i[n];a||(a=i[n]={});let o=a[r];o||(o=a[r]={});let s=e.getUTCFullYear(),l=o[s];return l||(l=o[s]={durations:{},endDates:{}}),l}_endDateCacheKey(e,n){return String(e)+"-"+String(n)}_durationCacheKey(e,n){return String(e)+"-"+String(n)}getEndDate(e,n,r,i,a){let o=this._getCacheObject(e,r,i),s=e.valueOf(),l=this._endDateCacheKey(s,n),c;if(o.endDates[l]===void 0){let d=a(),u=d.valueOf();o.endDates[l]=u,o.durations[this._durationCacheKey(s,u)]=n,c=d}else c=new Date(o.endDates[l]);return c}getDuration(e,n,r,i,a){let o=this._getCacheObject(e,r,i),s=e.valueOf(),l=n.valueOf(),c=this._durationCacheKey(s,l),d;if(o.durations[c]===void 0){let u=a();o.durations[c]=u.valueOf(),d=u}else d=o.durations[c];return d}clear(){this._cache={}}};function Ru(t,e){this.argumentsHelper=e,this.$gantt=t,this._workingUnitsCache=SF(),this._largeUnitsCache=new _u(this),this._dateDurationCache=new Eu,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}Ru.prototype={units:["year","month","week","day","hour","minute"],_clearCaches:function(){this._workingUnitsCache.clear(),this._largeUnitsCache.clear(),this._dateDurationCache.clear()},_getUnitOrder:function(t){for(var e=0,n=this.units.length;e<n;e++)if(this.units[e]==t)return e},_resetTimestampCache:function(){this._cached_timestamps={},this._cached_timestamps_count=0},_timestamp:function(t){this._cached_timestamps_count>1e6&&this._resetTimestampCache();var e=null;if(t.day||t.day===0)e=t.day;else if(t.date){var n=String(t.date.valueOf());this._cached_timestamps[n]?e=this._cached_timestamps[n]:(e=Date.UTC(t.date.getUTCFullYear(),t.date.getUTCMonth(),t.date.getUTCDate()),this._cached_timestamps[n]=e,this._cached_timestamps_count++)}return e},_checkIfWorkingUnit:function(t,e){if(!this["_is_work_"+e]){let n=this.$gantt.date[`${e}_start`](new Date(t)),r=this.$gantt.date.add(n,1,e);return this.hasDuration(n,r)}return this["_is_work_"+e](t)},_is_work_day:function(t){var e=this._getWorkHours(t);return Array.isArray(e)?e.length>0:!1},_is_work_hour:function(t){for(var e=this._getWorkHours(t),n=t.getUTCHours(),r=0;r<e.length;r++)if(n>=e[r].startHour&&n<e[r].endHour)return!0;return!1},_getTimeOfDayStamp:function(t,e){var n=t.getUTCHours();return!t.getUTCHours()&&!t.getUTCMinutes()&&e&&(n=24),n*60*60+t.getUTCMinutes()*60},_is_work_minute:function(t){for(var e=this._getWorkHours(t),n=this._getTimeOfDayStamp(t),r=0;r<e.length;r++)if(n>=e[r].start&&n<e[r].end)return!0;return!1},_nextDate:function(t,e,n){return this.$gantt.date.add(t,n,e)},_getWorkUnitsBetweenGeneric:function(t,e,n,r){var i=this.$gantt.date,a=new Date(t),o=new Date(e);r=r||1;var s=0,l=null,c,d,u=!1;c=i[n+"_start"](new Date(a)),c.valueOf()!=a.valueOf()&&(u=!0);var p=!1;d=i[n+"_start"](new Date(e)),d.valueOf()!=e.valueOf()&&(p=!0);for(var y=!1;a.valueOf()<o.valueOf();){if(l=this._nextDate(a,n,r),y=l.valueOf()>o.valueOf(),this._isWorkTime(a,n))(u||p&&y)&&(c=i[n+"_start"](new Date(a)),d=i.add(c,r,n)),u?(u=!1,l=this._nextDate(c,n,r),s+=(d.valueOf()-a.valueOf())/(d.valueOf()-c.valueOf())):p&&y?(p=!1,s+=(o.valueOf()-a.valueOf())/(d.valueOf()-c.valueOf())):s++;else{var f=this._getUnitOrder(n),m=this.units[f-1];m&&!this._isWorkTime(a,m)&&(l=this._getClosestWorkTimeFuture(a,m))}a=l}return s},_getMinutesPerHour:function(t){var e=this._getTimeOfDayStamp(t),n=this._getTimeOfDayStamp(this._nextDate(t,"hour",1));n===0&&(n=1440*60);for(var r=this._getWorkHours(t),i=0;i<r.length;i++){var a=r[i];if(e>=a.start&&n<=a.end)return 60;if(e<a.end&&n>a.start){var o=Math.min(n,a.end)-Math.max(e,a.start);return o/60}}return 0},_getMinutesPerDay:function(t){var e=this._getWorkHours(t),n=0;return e.forEach(function(r){n+=r.durationMinutes}),n},getHoursPerDay:function(t){var e=this._getWorkHours(t),n=0;return e.forEach(function(r){n+=r.durationHours}),n},_getWorkUnitsForRange:function(t,e,n,r){var i=0,a=new Date(t),o=new Date(e),s;for(n=="minute"?s=De(this._getMinutesPerDay,this):s=De(this.getHoursPerDay,this);a.valueOf()<o.valueOf();){if(o-a>1e3*60*60*24*32&&a.getUTCDate()===0){var l=this._largeUnitsCache.getMinutesPerMonth(a);n=="hour"&&(l=l/60),i+=l,a=this.$gantt.date.add(a,1,"month");continue}else if(o-a>1e3*60*60*24*16){var c=this.$gantt.date.week_start(new Date(a));if(a.valueOf()===c.valueOf()){var l=this._largeUnitsCache.getMinutesPerWeek(a);n=="hour"&&(l=l/60),i+=l,a=this.$gantt.date.add(a,7,"day");continue}}i+=s(a),a=this._nextDate(a,"day",1)}return i/r},_getMinutesBetweenSingleDay:function(t,e){for(var n=this._getIntervalTimestamp(t,e),r=this._getWorkHours(t),i=0,a=0;a<r.length;a++){var o=r[a];if(n.end>=o.start&&n.start<=o.end){var s=Math.max(o.start,n.start),l=Math.min(o.end,n.end);i+=(l-s)/60,n.start=l}}return Math.floor(i)},_getMinutesBetween:function(t,e,n,r){var i=new Date(t),a=new Date(e);r=r||1;var o=new Date(i),s=this.$gantt.date.add(this.$gantt.date.day_start(new Date(i)),1,"day");if(a.valueOf()<=s.valueOf())return this._getMinutesBetweenSingleDay(t,e);var l=this.$gantt.date.day_start(new Date(a)),c=a,d=this._getMinutesBetweenSingleDay(o,s),u=this._getMinutesBetweenSingleDay(l,c),p=this._getWorkUnitsForRange(s,l,n,r),y=d+p+u;return y},_getHoursBetween:function(t,e,n,r){var i=new Date(t),a=new Date(e);r=r||1;var o=new Date(i),s=this.$gantt.date.add(this.$gantt.date.day_start(new Date(i)),1,"day");if(a.valueOf()<=s.valueOf())return Math.round(this._getMinutesBetweenSingleDay(t,e)/60);var l=this.$gantt.date.day_start(new Date(a)),c=a,d=this._getMinutesBetweenSingleDay(o,s,n,r)/60,u=this._getMinutesBetweenSingleDay(l,c,n,r)/60,p=this._getWorkUnitsForRange(s,l,n,r),y=d+p+u;return Math.round(y)},getConfig:function(){return this._worktime},_setConfig:function(t){this._worktime=t,this._parseSettings(),this._clearCaches()},_parseSettings:function(){var t=this.getConfig();t.parsed={dates:{},hours:null,haveCustomWeeks:!1,customWeeks:{},customWeeksRangeStart:null,customWeeksRangeEnd:null,customWeeksBoundaries:[]},t.parsed.hours=this._parseHours(t.hours);for(var e in t.dates)t.parsed.dates[e]=this._parseHours(t.dates[e]);if(t.customWeeks){var n=null,r=null;for(var e in t.customWeeks){var i=t.customWeeks[e];if(i.from&&i.to){var a=i.from,o=i.to;(!n||n>a.valueOf())&&(n=a.valueOf()),(!r||r<o.valueOf())&&(r=o.valueOf()),t.parsed.customWeeksBoundaries.push({from:a.valueOf(),fromReadable:new Date(a),to:o.valueOf(),toReadable:new Date(o),name:e}),t.parsed.haveCustomWeeks=!0;var s=t.parsed.customWeeks[e]={from:i.from,to:i.to,hours:this._parseHours(i.hours),dates:{}};if(i.days&&!i.dates){i.dates=i.dates||{};for(var e=0;e<i.days.length;e++)i.dates[e]=i.days[e],i.days[e]instanceof Array||(i.dates[e]=!!i.days[e]);delete i.days}for(var l in i.dates)s.dates[l]=this._parseHours(i.dates[l])}}t.parsed.customWeeksRangeStart=n,t.parsed.customWeeksRangeEnd=r}},_tryChangeCalendarSettings:function(t){var e=JSON.stringify(this.getConfig());return t(),this.hasWorkTime()?!0:(this._setConfig(JSON.parse(e)),this._clearCaches(),!1)},_arraysEqual:function(t,e){if(t===e)return!0;if(!t||!e||t.length!=e.length)return!1;for(var n=0;n<t.length;++n)if(t[n]!==e[n])return!1;return!0},_compareSettings:function(t,e){if(!this._arraysEqual(t.hours,e.hours))return!1;var n=Object.keys(t.dates),r=Object.keys(e.dates);if(n.sort(),r.sort(),!this._arraysEqual(n,r))return!1;for(var i=0;i<n.length;i++){var a=n[i],o=t.dates[a],s=e.dates[a];if(o!==s&&!(Array.isArray(o)&&Array.isArray(s)&&this._arraysEqual(o,s)))return!1}return!0},equals:function(t){if(!(t instanceof Ru))return!1;var e=this.getConfig(),n=t.getConfig();if(!this._compareSettings(e,n))return!1;if(e.parsed.haveCustomWeeks&&n.parsed.haveCustomWeeks){if(e.parsed.customWeeksBoundaries.length!=n.parsed.customWeeksBoundaries.length)return!1;for(var r in e.parsed.customWeeks){var i=e.parsed.customWeeks[r],a=n.parsed.customWeeks[r];if(!a||!this._compareSettings(i,a))return!1}}else if(e.parse.haveCustomWeeks!==n.parsed.haveCustomWeeks)return!1;return!0},getWorkHours:function(){var t=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);return this._getWorkHours(t.date,!1)},_getWorkHours:function(t,e){var n=this.getConfig();if(e!==!1&&(n=n.parsed),!t)return n.hours;let r=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()));var i=this._timestamp({date:r});if(n.haveCustomWeeks&&n.customWeeksRangeStart<=i&&n.customWeeksRangeEnd>i){for(var a=0;a<n.customWeeksBoundaries.length;a++)if(n.customWeeksBoundaries[a].from<=i&&n.customWeeksBoundaries[a].to>i){n=n.customWeeks[n.customWeeksBoundaries[a].name];break}}var o=!0;return n.dates[i]!==void 0?o=n.dates[i]:n.dates[t.getUTCDay()]!==void 0&&(o=n.dates[t.getUTCDay()]),o===!0?n.hours:o||[]},_getIntervalTimestamp:function(t,e){var n={start:0,end:0};n.start=t.getUTCHours()*60*60+t.getUTCMinutes()*60+t.getUTCSeconds();var r=e.getUTCHours();return!r&&!e.getUTCMinutes()&&!e.getUTCSeconds()&&t.valueOf()<e.valueOf()&&(r=24),n.end=r*60*60+e.getUTCMinutes()*60+e.getUTCSeconds(),n},_parseHours:function(t){if(Array.isArray(t)){var e=[];t.forEach(function(s){typeof s=="number"?e.push(s*60*60):typeof s=="string"&&s.split("-").map(function(l){return l.trim()}).forEach(function(l){var c=l.split(":").map(function(u){return u.trim()}),d=parseInt(c[0]*60*60);c[1]&&(d+=parseInt(c[1]*60)),c[2]&&(d+=parseInt(c[2])),e.push(d)})});for(var n=[],r=0;r<e.length;r+=2){var i=e[r],a=e[r+1],o=a-i;n.push({start:i,end:a,startHour:Math.floor(i/3600),startMinute:Math.floor(i/60),endHour:Math.ceil(a/3600),endMinute:Math.ceil(a/60),durationSeconds:o,durationMinutes:o/60,durationHours:o/3600})}return n}else return t},setWorkTime:function(t){return this._tryChangeCalendarSettings(De(function(){var e=t.hours!==void 0?t.hours:!0,n=this._timestamp(t),r=this.getConfig();if(n!==null?r.dates[n]=e:t.customWeeks||(r.hours=e),t.customWeeks){if(r.customWeeks||(r.customWeeks={}),typeof t.customWeeks=="string")n!==null?r.customWeeks[t.customWeeks].dates[n]=e:t.customWeeks||(r.customWeeks[t.customWeeks].hours=e);else if(typeof t.customWeeks=="object"&&t.customWeeks.constructor===Object)for(var i in t.customWeeks)r.customWeeks[i]=t.customWeeks[i]}this._parseSettings(),this._clearCaches()},this))},unsetWorkTime:function(t){return this._tryChangeCalendarSettings(De(function(){if(!t)this.reset_calendar();else{var e=this._timestamp(t);e!==null&&delete this.getConfig().dates[e]}this._parseSettings(),this._clearCaches()},this))},_isWorkTime:function(t,e){var n=-1,r=null;return r=String(t.valueOf()),n=this._workingUnitsCache.getItem(e,r,t),n==-1&&(n=this._checkIfWorkingUnit(t,e),this._workingUnitsCache.setItem(e,r,n,t)),n},isWorkTime:function(){var t=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._isWorkTime(t.date,t.unit)},calculateDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments);if(!t.unit)return!1;var e=this;return this._dateDurationCache.getDuration(t.start_date,t.end_date,t.unit,t.step,function(){return e._calculateDuration(t.start_date,t.end_date,t.unit,t.step)})},_calculateDuration:function(t,e,n,r){var i=0,a=1;if(t.valueOf()>e.valueOf()){var o=e;e=t,t=o,a=-1}return n=="hour"&&r==1?i=this._getHoursBetween(t,e,n,r):n=="minute"&&r==1?i=this._getMinutesBetween(t,e,n,r):i=this._getWorkUnitsBetweenGeneric(t,e,n,r),a*Math.round(i)},hasDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.end_date,r=t.unit,i=t.step;if(!r)return!1;var a=new Date(e),o=new Date(n);for(i=i||1;a.valueOf()<o.valueOf();){if(this._isWorkTime(a,r))return!0;a=this._nextDate(a,r,i)}return!1},calculateEndDate:function(){var t=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.duration,r=t.unit,i=t.step;if(!r)return!1;var a=t.duration>=0?1:-1;n=Math.abs(n*1);var o=this;return this._dateDurationCache.getEndDate(e,n,r,i*a,function(){return o._calculateEndDate(e,n,r,i*a)})},_calculateEndDate:function(t,e,n,r){if(!n)return!1;if(r==1&&n=="minute")return this._calculateMinuteEndDate(t,e,r);if(r==-1&&n=="minute")return this._subtractMinuteDate(t,e,r);if(r==1&&n=="hour")return this._calculateHourEndDate(t,e,r);var i=this._addInterval(t,e,n,r,null);return i.end},_addInterval:function(t,e,n,r,i){for(var a=0,o=t;a<e&&!(i&&i(o));){var s=this._nextDate(o,n,r),l=new Date(s.valueOf()+1);r>0&&(l=new Date(s.valueOf()-1));var c=this._isWorkTime(l,n);c&&a++,o=s}return{end:o,start:t,added:a}},_addHoursUntilDayEnd:function(t,e){for(var n=this.$gantt.date.add(this.$gantt.date.day_start(new Date(t)),1,"day"),r=0,i=e,a=this._getIntervalTimestamp(t,n),o=this._getWorkHours(t),s=0;s<o.length&&r<e;s++){var l=o[s];if(a.end>=l.start&&a.start<=l.end){var c=Math.max(l.start,a.start),d=Math.min(l.end,a.end),u=(d-c)/3600;u>i&&(u=i,d=c+i*60*60);var p=Math.round((d-c)/3600);r+=p,i-=p,a.start=d}}var y=n;return r===e&&(y=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),0,0,a.start))),{added:r,end:y}},_calculateHourEndDate:function(t,e,n){var r=new Date(t),i=0;n=n||1,e=Math.abs(e*1);var a=this._addHoursUntilDayEnd(r,e);i=a.added,r=a.end;var o=e-i;if(o){for(var s=r;i<e;){var l=this._nextDate(s,"day",n);l.setUTCHours(0),l.setUTCMinutes(0),l.setUTCSeconds(0);var c=0;if(n>0?c=this.getHoursPerDay(new Date(l.valueOf()-1)):c=this.getHoursPerDay(new Date(l.valueOf()+1)),i+c>=e)break;i+=c,s=l}r=s}if(i<e){var o=e-i;a=this._addHoursUntilDayEnd(r,o),r=a.end}return r},_addMinutesUntilHourEnd:function(t,e){if(t.getUTCMinutes()===0)return{added:0,end:new Date(t)};for(var n=this.$gantt.date.add(this.$gantt.date.hour_start(new Date(t)),1,"hour"),r=0,i=e,a=this._getIntervalTimestamp(t,n),o=this._getWorkHours(t),s=0;s<o.length&&r<e;s++){var l=o[s];if(a.end>=l.start&&a.start<=l.end){var c=Math.max(l.start,a.start),d=Math.min(l.end,a.end),u=(d-c)/60;u>i&&(u=i,d=c+i*60);var p=Math.round((d-c)/60);i-=p,r+=p,a.start=d}}var y=n;return r===e&&(y=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),0,0,a.start))),{added:r,end:y}},_subtractMinutesUntilHourStart:function(t,e){for(var n=this.$gantt.date.hour_start(new Date(t)),r=0,i=e,a=n.getUTCHours()*60*60+n.getUTCMinutes()*60+n.getUTCSeconds(),o=t.getUTCHours()*60*60+t.getUTCMinutes()*60+t.getUTCSeconds(),s=this._getWorkHours(t),l=s.length-1;l>=0&&r<e;l--){var c=s[l];if(o>c.start&&a<=c.end){var d=Math.min(o,c.end),u=Math.max(a,c.start),p=(d-u)/60;p>i&&(p=i,u=d-i*60);var y=Math.abs(Math.round((d-u)/60));i-=y,r+=y,o=u}}var f=n;return r===e&&(f=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),0,0,o))),{added:r,end:f}},_subtractMinuteDate:function(t,e,n){var r=this.getClosestWorkTime({date:t,dir:"past",unit:"minute"}),i=0;n=n||-1,e=Math.abs(e*1),e=Math.round(e);let a=this._isMinutePrecision(r),o=this._subtractMinutesUntilHourStart(r,e);i+=o.added,r=o.end;for(var s=0,l=[],c=0;i<e;){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 p=new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),23,59,59,999)).valueOf();p!==s&&(l=this._getWorkHours(d),c=this._getMinutesPerDay(d),s=p);var y=e-i,f=this._getTimeOfDayStamp(r,u);if(!l.length||!c){r=this.$gantt.date.add(r,-1,"day");continue}if(l[l.length-1].end<=f&&y>c){i+=c,r=this.$gantt.date.add(r,-1,"day");continue}for(var m=!1,A=null,g=null,R=l.length-1;R>=0;R--)if(l[R].start<f-1&&l[R].end>=f-1){m=!0,A=l[R],g=l[R-1];break}if(m)if(f===A.end&&y>=A.durationMinutes)i+=A.durationMinutes,r=this.$gantt.date.add(r,-A.durationMinutes,"minute");else if(!a&&y<=f/60-A.startMinute)i+=y,r=this.$gantt.date.add(r,-y,"minute");else if(a)y<=f/60-A.startMinute?(i+=y,r=this.$gantt.date.add(r,-y,"minute")):(i+=f/60-A.startMinute,g?r=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,g.end)):r=this.$gantt.date.day_start(r));else{var P=this._getMinutesPerHour(r);P<=y?(i+=P,r=this._nextDate(r,"hour",n)):(o=this._subtractMinutesUntilHourStart(r,y),i+=o.added,r=o.end)}else if(r.getUTCHours()===0&&r.getUTCMinutes()===0&&r.getUTCSeconds()===0){var N=this._getClosestWorkTimePast(r,"hour");if(N.valueOf()===r.valueOf()){var N=this.$gantt.date.add(r,-1,"day"),T=this._getWorkHours(N);if(T.length){var x=T[T.length-1];N.setUTCSeconds(x.durationSeconds)}}r=N}else r=this._getClosestWorkTimePast(new Date(r-1),"hour")}if(i<e){var S=e-i;o=this._subtractMinutesUntilHourStart(r,S),i+=o.added,r=o.end}return r},_calculateMinuteEndDate:function(t,e,n){var r=new Date(t),i=0;n=n||1,e=Math.abs(e*1),e=Math.round(e);var a=this._addMinutesUntilHourEnd(r,e);i+=a.added,r=a.end;for(var o=0,s=[],l=0,c=this._isMinutePrecision(r);i<e;){var d=this.$gantt.date.day_start(new Date(r)).valueOf();d!==o&&(s=this._getWorkHours(r),l=this._getMinutesPerDay(r),o=d);var u=e-i,p=this._getTimeOfDayStamp(r);if(!s.length||!l){r=this.$gantt.date.add(this.$gantt.date.day_start(r),1,"day");continue}if(s[0].start>=p&&u>=l){if(i+=l,u==l){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 y=!1,f=null,m=0;m<s.length;m++)if(s[m].start<=p&&s[m].end>p){y=!0,f=s[m];break}if(y)if(p===f.start&&u>=f.durationMinutes)i+=f.durationMinutes,r=this.$gantt.date.add(r,f.durationMinutes,"minute");else if(u<=f.endMinute-p/60)i+=u,r=this.$gantt.date.add(r,u,"minute");else{var A=this._getMinutesPerHour(r);A<=u?(i+=A,c?r=this.$gantt.date.add(r,A,"minute"):r=this._nextDate(r,"hour",n)):(a=this._addMinutesUntilHourEnd(r,u),i+=a.added,r=a.end)}else r=this._getClosestWorkTimeFuture(r,"hour")}if(i<e){var g=e-i;a=this._addMinutesUntilHourEnd(r,g),i+=a.added,r=a.end}return r},getClosestWorkTime:function(){var t=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._getClosestWorkTime(t.date,t.unit,t.dir)},_getClosestWorkTime:function(t,e,n){var r=new Date(t);if(this._isWorkTime(r,e))return r;if(r=this.$gantt.date[e+"_start"](r),n=="any"||!n){var i=this._getClosestWorkTimeFuture(r,e),a=this._getClosestWorkTimePast(r,e);Math.abs(i-t)<=Math.abs(t-a)?r=i:r=a}else n=="past"?r=this._getClosestWorkTimePast(r,e):r=this._getClosestWorkTimeFuture(r,e);return r},_getClosestWorkTimeFuture:function(t,e){return this._getClosestWorkTimeGeneric(t,e,1)},_getClosestWorkTimePast:function(t,e){var n=this._getClosestWorkTimeGeneric(t,e,-1);return this.$gantt.date.add(n,1,e)},_findClosestTimeInDay:function(t,e,n){var r=new Date(t),i=null,a=!1;this._getWorkHours(r).length||(r=this._getClosestWorkTime(r,"day",e<0?"past":"future"),e<0&&(r=new Date(r.valueOf()-1),a=!0),n=this._getWorkHours(r));var o=this._getTimeOfDayStamp(r);if(a&&(o=this._getTimeOfDayStamp(new Date(r.valueOf()+1),a)),e>0){for(var s=0;s<n.length;s++)if(n[s].start>=o){i=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,n[s].start));break}}else for(var s=n.length-1;s>=0;s--)if(n[s].end<=o){i=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,n[s].end));break}else if(n[s].end>o&&n[s].start<=o){i=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,o));break}return i},_getClosestWorkMinute:function(t,e,n){var r=new Date(t),i=this._getWorkHours(r),a=this._findClosestTimeInDay(r,n,i);return a||(n>0?(r=this.calculateEndDate(r,n,e),r=this.$gantt.date.day_start(r)):(r=this.calculateEndDate(r,n,"day"),r=this.$gantt.date.day_start(r),r=this.$gantt.date.add(r,1,"day"),r=new Date(r.valueOf()-1)),i=this._getWorkHours(r),a=this._findClosestTimeInDay(r,n,i)),n<0&&(a=this.$gantt.date.add(a,-1,e)),a},_getClosestWorkTimeGeneric:function(t,e,n){if(e==="hour"||e==="minute")return this._getClosestWorkMinute(t,e,n);for(var r=this._getUnitOrder(e),i=this.units[r-1],a=t,o=3e3,s=0;!this._isWorkTime(a,e)&&!(i&&!this._isWorkTime(a,i)&&(n>0?a=this._getClosestWorkTimeFuture(a,i):a=this._getClosestWorkTimePast(a,i),this._isWorkTime(a,e)));){if(s++,s>o)return this.$gantt.assert(!1,"Invalid working time check"),!1;a=this.$gantt.date.add(a,n,e),this.$gantt.date[e+"_start"]&&(a=this.$gantt.date[e+"_start"](a))}return a},hasWorkTime:function(){var t=this.getConfig(),e=t.dates,n=[0,1,2,3,4,5,6];for(var r in t.dates);var i=this._checkWorkHours(t.hours),a=!1;return n.forEach((function(o){if(!a){var s=e[o];s===!0?a=i:Array.isArray(s)&&(a=this._checkWorkHours(s))}}).bind(this)),a},_checkWorkHours:function(t){if(t.length===0)return!1;for(var e=!1,n=0;n<t.length;n+=2)t[n]!==t[n+1]&&(e=!0);return e},_isMinutePrecision:function(t){let e=!1;return this._getWorkHours(t).forEach(function(n){(n.startMinute%60||n.endMinute%60)&&(e=!0)}),e}};var co={isLegacyResourceCalendarFormat:function(t){if(!t)return!1;for(var e in t)if(t[e]&&typeof t[e]=="object")return!0;return!1},getResourceProperty:function(t){var e=t.resource_calendars,n=t.resource_property;if(this.isLegacyResourceCalendarFormat(e))for(var r in t){n=r;break}return n},getCalendarIdFromLegacyConfig:function(t,e){if(e)for(var n in e){var r=e[n];if(t[n]){var i=r[t[n]];if(i)return i}}return null}};function vF(){function t(i){return i.map(function(a){return a&&a.resource_id?a.resource_id:a}).sort().join("-")}var e={};function n(i,a){return a.mergeCalendars(i.map(function(o){var s=o&&o.resource_id?o.resource_id:o;return a.getResourceCalendar(s)}))}function r(i,a){var o=t(i);if(i.length){if(i.length===1)return a.getResourceCalendar(o).id;if(e[o])return e[o].id;var s=n(i,a);return e[o]=s,a.addCalendar(s)}else return null}return{getCalendarIdFromMultipleResources:r}}var CF=vF();function AI(t){this.$gantt=t,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=co.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))}AI.prototype={_calendars:{},_convertWorkTimeSettings:function(t){let e=t.days;if(typeof e=="object"&&!Array.isArray(e)&&e!==null){let n={};if(e?.weekdays)for(let r=0;r<7;r++)n[r]=e.weekdays[r];e?.dates&&Object.entries(e.dates).forEach(([r,i])=>{n[new Date(r).valueOf()]=i}),Object.entries(n).forEach(([r,i])=>{i instanceof Array||(n[r]=!!i)}),t={...t,dates:n}}else if(e&&!t.dates){t.dates=t.dates||{};for(let n=0;n<e.length;n++)t.dates[n]=e[n],e[n]instanceof Array||(t.dates[n]=!!e[n])}return delete t.days,t},mergeCalendars:function(){var t=[],e=arguments;if(Array.isArray(e[0]))t=e[0].slice();else for(var n=0;n<arguments.length;n++)t.push(arguments[n]);var r=new gI,i;return t.forEach((function(a){i?i=this._createCalendarFromConfig(r.merge(i,a)):i=a}).bind(this)),this.createCalendar(i)},_createCalendarFromConfig:function(t){var e=new Ru(this.$gantt,mI(this.$gantt));e.id=String(Iu());var n=this._convertWorkTimeSettings(t);if(n.customWeeks)for(var r in n.customWeeks)n.customWeeks[r]=this._convertWorkTimeSettings(n.customWeeks[r]);return e._setConfig(n),e},createCalendar:function(t){var e;t||(t={}),t.getConfig?e=We(t.getConfig()):t.worktime?e=We(t.worktime):e=We(t);var n=We(this.defaults.fulltime.worktime);return zi(e,n),this._createCalendarFromConfig(e)},getCalendar:function(t){t=t||"global";var e=this._calendars[t];return e||(this.createDefaultCalendars(),e=this._calendars[t]),e},getCalendars:function(){var t=[];for(var e in this._calendars)t.push(this.getCalendar(e));return t},_getOwnCalendar:function(t){var e=this.$gantt.config;if(t[e.calendar_property])return this.getCalendar(t[e.calendar_property]);if(e.resource_calendars){var n,r,i;if(this._legacyConfig===!1?i=e.resource_property:i=co.getResourceProperty(e),Array.isArray(t[i])&&t[i].length)e.dynamic_resource_calendars?r=CF.getCalendarIdFromMultipleResources(t[i],this):n=this.getResourceCalendar(t[i]);else if(this._legacyConfig===void 0&&(this._legacyConfig=co.isLegacyResourceCalendarFormat(e.resource_calendars)),this._legacyConfig)var r=co.getCalendarIdFromLegacyConfig(t,e.resource_calendars);else if(i&&t[i]&&e.resource_calendars[t[i]])var n=this.getResourceCalendar(t[i]);if(r&&(n=this.getCalendar(r)),n)return n}return null},getResourceCalendar:function(t){if(t==null)return this.getCalendar();var e=null;typeof t=="number"||typeof t=="string"?e=t:e=t.id||t.key;var n=this.$gantt.config,r=n.resource_calendars,i=null;if(Array.isArray(t)&&t.length===1&&(typeof t[0]=="object"?e=t[0].resource_id:e=t[0]),r){if(this._legacyConfig===void 0&&(this._legacyConfig=co.isLegacyResourceCalendarFormat(n.resource_calendars)),this._legacyConfig){for(var a in r)if(r[a][e]){i=r[a][e];break}}else var i=r[e];if(i)return this.getCalendar(i)}return this.getCalendar()},getTaskCalendar:function(t){var e=this.$gantt,n;if(t==null)return this.getCalendar();if((typeof t=="number"||typeof t=="string")&&e.isTaskExists(t)?n=e.getTask(t):n=t,!n)return this.getCalendar();var r=this._getOwnCalendar(n),i=!!e.getState().group_mode;if(!r&&e.config.inherit_calendar&&e.isTaskExists(n.parent)){for(var a=n;e.isTaskExists(a.parent)&&(a=e.getTask(a.parent),!(e.isSummaryTask(a)&&(r=this._getOwnCalendar(a),r))););i&&!r&&t.$effective_calendar&&(r=this.getCalendar(t.$effective_calendar))}return r||this.getCalendar()},addCalendar:function(t){if(!this.isCalendar(t)){var e=t.id;t=this.createCalendar(t),t.id=e}if(t._tryChangeCalendarSettings(function(){})){var n=this.$gantt.config;return t.id=t.id||Iu(),this._calendars[t.id]=t,n.worktimes||(n.worktimes={}),n.worktimes[t.id]=t.getConfig(),t.id}else return this.$gantt.callEvent("onCalendarError",[{message:"Invalid calendar settings, no worktime available"},t]),null},deleteCalendar:function(t){var e=this.$gantt.config;return t&&this._calendars[t]?(delete this._calendars[t],e.worktimes&&e.worktimes[t]&&delete e.worktimes[t],!0):!1},restoreConfigCalendars:function(t){for(var e in t)if(!this._calendars[e]){var n=t[e],r=this.createCalendar(n);r.id=e,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 t=this.$gantt.config;this.restoreConfigCalendars(this.defaults),this.restoreConfigCalendars(t.worktimes)},isCalendar:function(t){var e=[t.isWorkTime,t.setWorkTime,t.getWorkHours,t.unsetWorkTime,t.getClosestWorkTime,t.calculateDuration,t.hasDuration,t.calculateEndDate];return e.every(function(n){return n instanceof Function})}};function Pu(t,e){this.argumentsHelper=e,this.$gantt=t}Pu.prototype={getWorkHours:function(){return[0,24]},setWorkTime:function(){return!0},unsetWorkTime:function(){return!0},isWorkTime:function(){return!0},getClosestWorkTime:function(e){var e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return e.date},calculateDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.end_date,r=t.unit,i=t.step;return this._calculateDuration(e,n,r,i)},_calculateDuration:function(t,e,n,r){var i=this.$gantt.date,a={week:1e3*60*60*24*7,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60},o=0;if(a[n])o=Math.round((e-t)/(r*a[n]));else{for(var s=new Date(t),l=new Date(e);s.valueOf()<l.valueOf();)o+=1,s=i.add(s,r,n);s.valueOf()!=e.valueOf()&&(o+=(l-s)/(i.add(s,r,n)-s))}return Math.round(o)},hasDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.end_date,r=t.unit;return r?(e=new Date(e),n=new Date(n),e.valueOf()<n.valueOf()):!1},hasWorkTime:function(){return!0},equals:function(t){return t instanceof Pu},calculateEndDate:function(){var t=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.duration,r=t.unit,i=t.step;return this.$gantt.date.add(e,i*n,r)}};function II(t){this.$gantt=t.$gantt,this.argumentsHelper=mI(this.$gantt),this.calendarManager=t,this.$disabledCalendar=new Pu(this.$gantt,this.argumentsHelper)}II.prototype={_getCalendar:function(t){var e;if(!this.$gantt.config.work_time)e=this.$disabledCalendar;else{var n=this.calendarManager;t.task?e=n.getTaskCalendar(t.task):t.id?e=n.getTaskCalendar(t):t.calendar&&(e=t.calendar),e||(e=n.getTaskCalendar())}return e},getWorkHours:function(t){t=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);var e=this._getCalendar(t);return e.getWorkHours(t.date)},setWorkTime:function(t,e){return t=this.argumentsHelper.setWorkTimeArguments.apply(this.argumentsHelper,arguments),e||(e=this.calendarManager.getCalendar()),e.setWorkTime(t)},unsetWorkTime:function(t,e){return t=this.argumentsHelper.unsetWorkTimeArguments.apply(this.argumentsHelper,arguments),e||(e=this.calendarManager.getCalendar()),e.unsetWorkTime(t)},isWorkTime:function(t,e,n,r){var i=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return r=this._getCalendar(i),r.isWorkTime(i)},getClosestWorkTime:function(t){t=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);var e=this._getCalendar(t);return e.getClosestWorkTime(t)},calculateDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),e=this._getCalendar(t);return e.calculateDuration(t)},hasDuration:function(){var t=this.argumentsHelper.hasDurationArguments.apply(this.argumentsHelper,arguments),e=this._getCalendar(t);return e.hasDuration(t)},calculateEndDate:function(e){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),n=this._getCalendar(e);return n.calculateEndDate(e)}};var DF=function(t,e){return{getWorkHours:function(n){return e.getWorkHours(n)},setWorkTime:function(n){return e.setWorkTime(n)},unsetWorkTime:function(n){e.unsetWorkTime(n)},isWorkTime:function(n,r,i){return e.isWorkTime(n,r,i)},getClosestWorkTime:function(n){return e.getClosestWorkTime(n)},calculateDuration:function(n,r,i){return e.calculateDuration(n,r,i)},_hasDuration:function(n,r,i){return e.hasDuration(n,r,i)},calculateEndDate:function(n,r,i,a){return e.calculateEndDate(n,r,i,a)},mergeCalendars:De(t.mergeCalendars,t),createCalendar:De(t.createCalendar,t),addCalendar:De(t.addCalendar,t),getCalendar:De(t.getCalendar,t),getCalendars:De(t.getCalendars,t),getResourceCalendar:De(t.getResourceCalendar,t),getTaskCalendar:De(t.getTaskCalendar,t),deleteCalendar:De(t.deleteCalendar,t)}},TF={create:DF};function SI(t){var e=new AI(t),n=new II(e),r=TF.create(e,n);zi(t,r)}var vI={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 CI(t={}){let e=t.config||{},n={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},e),locale:t.locale||vI,templates:t.templates||{},getTask:t.getTask||function(r){return null},isTaskExists:t.isTaskExists||function(r){return!1},isSummaryTask:t.isSummaryTask||function(r){return!1},getState:function(){return{group_mode:!1}},callEvent:function(r,i){let a=t.onEvent;return a&&a(r,i),!0},attachEvent:function(){return 0},checkEvent:function(){return!1},detachEvent:function(){},defined:pI,mixin:zi,copy:We,assert:function(r,i){if(!r){if(t.throwOnAssert)throw new Error("[calendar] "+i);t.silent!==!0&&console.error("[calendar]",i)}},$services:{getService:function(){return null}},$ui:{getView:function(){return null}}};return n._correct_dst_change=function(r){return r},n.date=hI(n),n.date.init(),SI(n),n}function _F(t={}){let e=CI(t);return{addCalendar:function(n){return e.addCalendar(n)},deleteCalendar:function(n){return e.deleteCalendar(n)},getCalendar:function(n){return e.getCalendar(n)},getCalendars:function(){return e.getCalendars()},mergeCalendars:function(){return e.mergeCalendars.apply(e,arguments)},getTaskCalendar:function(n){return e.getTaskCalendar(n)},getResourceCalendar:function(n){return e.getResourceCalendar(n)},setWorkTime:function(n){return e.setWorkTime(n)},unsetWorkTime:function(n){return e.unsetWorkTime(n)},isWorkTime:function(){return e.isWorkTime.apply(e,arguments)},getClosestWorkTime:function(){return e.getClosestWorkTime.apply(e,arguments)},getWorkHours:function(){return e.getWorkHours.apply(e,arguments)},calculateDuration:function(){return e.calculateDuration.apply(e,arguments)},calculateEndDate:function(){return e.calculateEndDate.apply(e,arguments)},_internals:e}}var DI={createCalendar:_F};var m7=3600*1e3;function RI(t){return{getActivity(e){return t.getActivity(e)}}}var{createCalendar:EF}=DI,uo="__replay_default__";function RF(t){if(!t||t.length===0||typeof t[0]=="string")return t;let e=t.map(Number);if(e.some(a=>Number.isNaN(a)))return t;let n=e[0],r=e[e.length-1];return e.every((a,o)=>a===n+o)?[`${n}:00-${r+1}:00`]:t}var TI={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},_I="__main_global__",PF={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function kF(){}function EI(t){return!t||t.hours===void 0||t.hours.length>0||t.days?.some(e=>Array.isArray(e)&&e.length>0)===!0?!0:Object.values(t.dates??{}).some(e=>Array.isArray(e)&&e.length>0)}function bF(t,e=kF){let n=uI({hours:RF(t.hours),days:t.days,dates:t.dates},e),r={};if(Array.isArray(n.days))for(let a=0;a<n.days.length;a+=1)r[a]=n.days[a];if(n.dates)for(let[a,o]of Object.entries(n.dates))r[a]=o;let i={hours:n.hours,dates:r};return t.customWeeks&&(i.customWeeks=t.customWeeks),i}function xl(t,e=Pe){let n=EF({config:{work_time:!0}});n.addCalendar({id:uo,worktime:TI}),n.addCalendar({id:_I,worktime:PF});let r=new Set(t.filter(u=>!EI(u.worktime)).map(u=>String(u.id))),i=t.filter(u=>EI(u.worktime));for(let u of i)n.addCalendar({id:u.id,worktime:u.worktime?bF(u.worktime,(p,y)=>e.warn(p,{calendarId:u.id,...y})):TI});let a=bh(n),o=a.getCalendar(uo),s=a.getCalendar(_I);if(!o||!s)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let l=new Set([uo]);for(let u of i)l.add(String(u.id));let c=new Map;return{reader:{getCalendar(u){let p=String(u),y=c.get(p);if(y)return y;let f=o;return l.has(p)?f=a.getCalendar(u)??o:r.has(p)&&(f=s),c.set(p,f),f}}}}function PI(t){return{hasChildren(e){return t.hasChildren(e)},getParentStartDateIfHasPredecessors(e){let n=t.getActivity(e);if(!n)return null;let r=t.getParent(n.id);return!r||t.getIncomingLinkIds(r.id).length===0?null:r.startDate},getDescendantIds(e){return LF(t,e).map(n=>String(n))},getAncestorIds(e){let n=[],r=t.getActivity(e);for(;r;){let i=r.parentId;if(i===null)break;let a=t.getActivity(i);if(!a)break;n.push(String(i)),r=a}return n},getChildProgressInfo(e){return t.getChildren(e).map(r=>{let i=t.getActivity(r);return{id:r,progress:Number(i?.progress??0),ponderator:Number(i?.ponderator??0)}})},getChildHhInfo(e){return t.getChildren(e).map(r=>{let i=t.getActivity(r);return{id:r,workHours:Number(i?.workHours??0),progress:Number(i?.progress??0),realWorkHours:Number(i?.realWorkHours??0)}})},getChildUsedCostInfo(e){return t.getChildren(e).map(r=>{let i=t.getActivity(r);return{id:r,usedCost:Number(i?.usedCost??0)}})},getChildCostInfo(e){return t.getChildren(e).map(r=>{let i=t.getActivity(r);return{id:r,cost:Number(i?.cost??0)}})}}}function LF(t,e){let n=[],r=new _e;for(let i of t.getChildren(e))r.enqueue(i);for(;!r.isEmpty();){let i=r.dequeue();n.push(i);for(let a of t.getChildren(i))r.enqueue(a)}return n}var OF=["startDate","endDate","durationHours","constraintType","constraintDate","autoScheduling","calendarId","parentId","type","progress"],NF=["source","target","type","lag"];function kI(t,e){return t instanceof Date&&e instanceof Date?t.getTime()===e.getTime():Object.is(t,e)}function FF(t,e){if(t.kind!==Et.LINK_FIELD)return!0;let n=e(t.linkId);return n===null?!0:NF.some(r=>!kI(t.before[r],n[r]))}function bI(t,e,n){if(t.ops.some(r=>FF(r,n)))return!0;for(let[r,i]of t.before){let a=e(r);if(a===null||OF.some(s=>!kI(i[s],a[s])))return!0}return!1}var Ml=class{constructor(e,n,r){this._fields=e;this._scope=n;this._settle=r}_fields;_scope;_settle;_structural=!0;_touchedIds=new Set;_reshapedIds=new Set;_appendedLinkIds=[];_removedLinkIds=[];touch(e,n){!this._structural&&this._fields.has(n)&&this._touchedIds.add(e)}reshape(e){this._scope.patchesHierarchy?this._structural||this._reshapedIds.add(e):this.markStructural()}changeLinks(){this._scope.ignoresLinks||this.markStructural()}appendLink(e){this._scope.patchesLinkAppends?this._structural||this._appendedLinkIds.push(e):this.changeLinks()}removeLink(e){this._scope.patchesLinkRemovals?this._appendedLinkIds.includes(e)?this.markStructural():this._structural||this._removedLinkIds.push(e):this.changeLinks()}markStructural(){this._structural=!0,this._touchedIds.clear(),this._reshapedIds.clear(),this._appendedLinkIds=[],this._removedLinkIds=[]}take(){this._settle();let e={structural:this._structural,touchedIds:this._touchedIds,reshapedIds:this._reshapedIds,appendedLinkIds:this._appendedLinkIds,removedLinkIds:this._removedLinkIds};return this._structural=!1,this._touchedIds=new Set,this._reshapedIds=new Set,this._appendedLinkIds=[],this._removedLinkIds=[],e}};var Ul=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(e){this.reader=e.reader}resolveCalendar(e){let n=LI(e);return this.reader.getCalendar(n??uo)}getClosestWorkTime(e){let n=Ji(Ji(this._cache.closestWorkTime,bu(e.task)),e.dir);return ku(n,e.date.getTime(),()=>this.resolveCalendar(e.task).getClosestWorkTime({direction:e.dir,date:e.date,unit:gt.HOUR}))}isWorkTime(e){return this.resolveCalendar(e.task).isWorkTime(e.date,gt.MINUTE)}calculateEndDate(e){let n=Ji(Ji(this._cache.endDate,bu(e.task)),e.startDate.getTime());return ku(n,e.durationHours,()=>this.resolveCalendar(e.task).calculateEndDate(e.startDate,e.durationHours))}calculateDuration(e){let n=Ji(Ji(this._cache.duration,bu(e.task)),e.startDate.getTime());return ku(n,e.endDate.getTime(),()=>this.resolveCalendar(e.task).calculateDuration(e.startDate,e.endDate))}clearCache(){this._cache.closestWorkTime.clear(),this._cache.endDate.clear(),this._cache.duration.clear()}};function ku(t,e,n){let r=t.get(e);if(r!==void 0)return r;let i=n();return t.set(e,i),i}function Ji(t,e){let n=t.get(e);if(n)return n;let r=new Map;return t.set(e,r),r}var wF="__default__";function LI(t){if(!t)return null;let e=t.calendarId;return e==null?null:String(e)}function bu(t){return LI(t)??wF}var Hl=class{constructor(e){this.activities=e}activities;_childrenByParent=new Map;_roots=[];_dirty=!1;reportReorderedParent=()=>{};markDirty(){this._dirty=!0}settle(){this._dirty&&(this.rebuild(),this._dirty=!1)}getChildren(e){return this._dirty&&(this.rebuild(),this._dirty=!1),this._childrenByParent.get(String(e))??[]}hasChildren(e){return this._dirty&&(this.rebuild(),this._dirty=!1),(this._childrenByParent.get(String(e))?.length??0)>0}getRootIds(){return this._dirty&&(this.rebuild(),this._dirty=!1),[...this._roots]}isChildOf(e,n){let r=this.activities.get(e)?.parentId,i=0,a=this.activities.size;for(;r&&!G(r);){if(r===n)return!0;if(++i>a)return!1;r=this.activities.get(r)?.parentId}return!1}getParent(e){let n=this.activities.get(e)?.parentId;return!n||G(n)?null:this.activities.get(n)??null}getParentId(e){return this.activities.get(e)?.parentId??null}addChild(e,n){if(this._dirty)return;if(G(e)){this._roots.push(n);return}let r=String(e),i=this._childrenByParent.get(r);i?i.push(n):this._childrenByParent.set(r,[n])}rebuild(){let e=this._childrenByParent,n=[],r=new Map;for(let i of this.activities.values()){if(G(i.parentId)){n.push(i);continue}let a=String(i.parentId),o=r.get(a);o?o.push(i):r.set(a,[i])}this._roots=OI(n),this._childrenByParent=new Map;for(let[i,a]of r)this._childrenByParent.set(i,OI(a));this.reportReorderedParents(e)}reportReorderedParents(e){for(let[n,r]of this._childrenByParent)xF(e.get(n),r)||this.reportReorderedParent(n);for(let n of e.keys())this._childrenByParent.has(n)||this.reportReorderedParent(n)}};function xF(t,e){if(t===void 0||t.length!==e.length)return!1;for(let n=0;n<e.length;n+=1)if(t[n]!==e[n])return!1;return!0}function OI(t){return t.sort(Rn).map(e=>e.id)}var Bl=class{checkedSet=new Set;hiddenSet=new Set;activeFilter=null;activeOrder=null;isChecked(e){return this.checkedSet.has(e)}isVisible(e){return!this.hiddenSet.has(e)}hiddenIds(){return[...this.hiddenSet]}getActiveFilter(){return this.activeFilter}setActiveFilter(e){this.activeFilter=e}getActiveOrder(){return this.activeOrder}setActiveOrder(e){this.activeOrder=e}checkedIds(){return[...this.checkedSet]}checkedCount(){return this.checkedSet.size}setChecked(e,n){return n===this.checkedSet.has(e)?!1:(n?this.checkedSet.add(e):this.checkedSet.delete(e),!0)}setVisible(e,n){return n===!this.hiddenSet.has(e)?!1:(n?this.hiddenSet.delete(e):this.hiddenSet.add(e),!0)}forget(e){this.checkedSet.delete(e),this.hiddenSet.delete(e)}hydrate(e){this.checkedSet=new Set(e.checkedIds??[]),this.hiddenSet=new Set(e.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(e){this.checkedSet=new Set(e.checked),this.hiddenSet=new Set(e.hidden),this.activeFilter=e.activeFilter,this.activeOrder=e.activeOrder}};function Fu(t,e,n,r,i,a){return{valueId:e,id:t,label:n,color:r,level:i,sequence:a,children:new Map,activities:[]}}function NI(t,e,n,r,i){let{attributeKey:a,startLevel:o,depth:s}=e;for(let l of t){let c=n.assignmentByActivityId.get(String(l.id)),d=c===void 0?[]:Wp(n,c,o,s),u=d.length===0?[yr]:d,p=r;u.forEach((y,f)=>{let m=p.children.get(y);if(m===void 0){let A=n.valueById.get(y);m=Fu(i?Mo(p.id,a,y):xo(a,y),y,A?.label??(y===yr?No:y),A?.color??null,r.level+1+f,A?.sequence??Number.MAX_SAFE_INTEGER),p.children.set(y,m)}p=m}),p.activities.push(l)}return r}function FI(t){let e=t.activities.length;for(let n of t.children.values())e+=FI(n);return e}function Lu(t,e){let n=[...t.children.values()];return n.sort((r,i)=>r.valueId===yr?1:i.valueId===yr?-1:r.sequence!==i.sequence?r.sequence-i.sequence:r.valueId.localeCompare(i.valueId)),e===ce.DESCENDING&&n.reverse(),n}var MF=1,UF=Number.POSITIVE_INFINITY;function Ou(t){return{kind:ii.ACTIVITY,activityId:String(t.id)}}function HF(t,e,n){let r=[],i=new Map;for(let a of e){if(!t.has(String(a.id)))continue;let o=n(a.id),s=o===null?null:String(o);if(s===null||!t.has(s)){r.push(a);continue}let l=i.get(s);l===void 0?i.set(s,[a]):l.push(a)}return{roots:r,childrenOf:i}}function wI(t,e){let{roots:n,childrenOf:r}=HF(t,e.activitiesInVisualOrder,e.parentOf),i=e.wbsDepth??UF,a=l=>r.get(String(l.id))??[],o=l=>{let c=[],d=u=>{for(let p of u){let y=a(p);y.length===0?c.push(p):d(y)}};return d(l),c},s=(l,c)=>{if(c>i){let d=o(l),u=e.comparator===null?d:Vo(d,e.comparator,e.orderMode,()=>!1);for(let p of u)e.rows.push(Ou(p));return}for(let d of l){e.rows.push(Ou(d));let u=a(d);u.length>0&&s(u,c+1)}};s(n,MF)}function BF(t,e){let n=new Set(t.map(r=>String(r.id)));for(let r of t){let i=e.parentOf(r.id);for(;i!==null;)n.add(String(i)),i=e.parentOf(i)}wI(n,e)}function jF(t,e){let{rows:n}=e;if(e.group.includeWbs){BF(t.activities,{activitiesInVisualOrder:e.activitiesInVisualOrder,parentOf:e.parentOf,wbsDepth:e.wbsDepth,comparator:e.comparator,orderMode:e.orderMode,rows:n});return}for(let r of Vo([...t.activities],e.comparator,e.orderMode,e.hasChildren))n.push({kind:ii.ACTIVITY,activityId:String(r.id)})}function Nu(t,e,n,r){let{group:i,rows:a}=r;if(a.push({kind:ii.GROUP,id:t.id,label:t.label,level:t.level,color:t.color,activityCount:FI(t)}),i.collapsedIds.has(t.id))return;for(let s of Lu(t,e))Nu(s,e,n,r);if(t.activities.length===0)return;let o=i.secondary;if(n&&o!=null&&r.secondaryCatalog!=null){let s=NI(t.activities,o,r.secondaryCatalog,Fu(t.id,"","",null,t.level,0),!0);for(let l of Lu(s,o.direction))Nu(l,o.direction,!1,r);return}jF(t,r)}function xI(t){let e=t.activitiesInVisualOrder.filter(s=>t.isVisible(s.id));if(t.group===null||t.catalog===null){if(t.wbsDepth===null)return e.map(Ou);let s=[];return wI(new Set(e.map(l=>String(l.id))),{activitiesInVisualOrder:e,parentOf:t.parentOf,wbsDepth:t.wbsDepth,comparator:t.comparator,orderMode:t.orderMode,rows:s}),s}let{group:n,catalog:r}=t,i=NI(e,n,r,Fu("","","",null,-1,0),!1),a=[],o={group:n,activitiesInVisualOrder:t.activitiesInVisualOrder,parentOf:t.parentOf,hasChildren:t.hasChildren,comparator:t.comparator,orderMode:t.orderMode,wbsDepth:t.wbsDepth,secondaryCatalog:t.secondaryCatalog,rows:a};for(let s of Lu(i,n.direction))Nu(s,n.direction,!0,o);return a}var jl=class t{catalogs=new Map;group=null;wbsDepth=null;getCatalog(e){return this.catalogs.get(e)??null}getCatalogMap(){return this.catalogs}setCatalogs(e){let n=new Map;for(let r of e)n.set(r.key,jp(r));this.catalogs=n}getGroup(){return this.group}setGroup(e){this.group=e}getWbsDepth(){return this.wbsDepth}setWbsDepth(e){this.wbsDepth=e}clone(){let e=new t;return e.catalogs=new Map(this.catalogs),e.group=this.group===null?null:C(this.group),e.wbsDepth=this.wbsDepth,e}};var VF={settings:null,projectState:null,latestRunLog:null},Xi=class t{_activities=new Map;_missingSchedulingStateCount=0;_lastStartDate=new Map;_promotionSnapshot=new Map;_progressFallback=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_buildOrderComparator;_cache={ids:null,visualOrderIds:null,visualRows:null,orderComparator:null};_writeCapture=new nl;_schedulingWriteLogs=[];_scheduleSettled=!1;_settledByPassInCapture=!1;_viewState=new Bl;_viewAttributes=new jl;_filterProjection=null;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_missingSchedulingStateCountBefore=null;_dataDate=VF;_dataDateBefore=null;_calendar;_flags;_calendarSnapshot;_isDataDateEnabled;_clock;constructor(e,n=()=>null,r=()=>!0,i=Pe,a,o=null){this._buildOrderComparator=n,this._isDataDateEnabled=r,this._clock=o,this._calendarSnapshot=C(e.calendars);for(let s of e.activities)this._activities.set(s.id,s);for(let s of this._activities.values())Zn(s)&&(this._missingSchedulingStateCount+=1);for(let s of e.links){let l={...s,freeSlackHours:s.freeSlackHours??null,isCritical:s.isCritical===!0};this._links.set(String(s.id),l),this._indexLink(l)}this._calendar=new Ul(a??xl(this._calendarSnapshot,i)),this._flags=KF(e),this._hierarchy=new Hl(this._activities),this._hierarchy.rebuild(),this._hierarchy.reportReorderedParent=s=>this._noteSchedulingReshape(s)}fork(){let e=t.fromSnapshot(this.exportSnapshot(),this._buildOrderComparator,this._isDataDateEnabled,void 0,this._clock);return e._filterProjection=C(this._filterProjection),e._viewAttributes=this._viewAttributes.clone(),e._dataDate=C(this._dataDate),e}exportSnapshot(){return{activities:this.getAllActivities().map(ln),links:this.getAllLinks().map(e=>({...e})),calendars:C(this._calendarSnapshot),viewState:C(this._viewState.snapshot()),lastStartDate:new Map(Array.from(this._lastStartDate,([e,n])=>[e,new Date(n)])),promotionSnapshot:new Map(Array.from(this._promotionSnapshot,([e,n])=>[e,C(n)])),progressFallback:new Map(this._progressFallback),flags:C(this._flags),scheduleSettled:this._scheduleSettled}}static fromSnapshot(e,n,r,i,a=null){let o=new t({activities:e.activities,links:e.links,calendars:e.calendars},n,r,i,void 0,a);return o._viewState.restore(e.viewState),o._lastStartDate=e.lastStartDate,o._promotionSnapshot=e.promotionSnapshot,o._progressFallback=e.progressFallback,o._flags=e.flags,o._scheduleSettled=e.scheduleSettled,o}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}hasCompleteSchedulingState(){return this._missingSchedulingStateCount===0}restoreFork(e){this._activities=e._activities,this._missingSchedulingStateCount=e._missingSchedulingStateCount,this._lastStartDate=e._lastStartDate,this._promotionSnapshot=e._promotionSnapshot,this._progressFallback=e._progressFallback,this._links=e._links,this._outgoing=e._outgoing,this._incoming=e._incoming,this._hierarchy=e._hierarchy,this._hierarchy.reportReorderedParent=n=>this._noteSchedulingReshape(n),this._cache=e._cache,this._calendar=e._calendar,this._flags=e._flags,this._viewState=e._viewState,this._viewAttributes=e._viewAttributes,this._filterProjection=e._filterProjection,this._dataDate=e._dataDate,this._scheduleSettled=e._scheduleSettled,this._noteSchedulingStructure()}dataDateSettings(){return this._dataDate.settings}isDataDateEnabled(){return this._isDataDateEnabled()}currentTime(){return this._clock?.()??null}dataDateProjectState(){return this._dataDate.projectState}dataDateLatestRunLog(){return this._dataDate.latestRunLog}setDataDateSettings(e){this._captureDataDateOnce(),this._dataDate={...this._dataDate,settings:C(e)}}setDataDateProjectState(e){this._captureDataDateOnce(),this._dataDate={...this._dataDate,projectState:C(e)}}setDataDateLatestRunLog(e){this._captureDataDateOnce(),this._dataDate={...this._dataDate,latestRunLog:C(e)}}_captureDataDateOnce(){this._writeCapture.peek()!==null&&this._dataDateBefore===null&&(this._dataDateBefore=this._dataDate)}getVisualOrderIds(){return this._cache.visualOrderIds?this._cache.visualOrderIds:(this._cache.visualOrderIds=ey(this).map(e=>String(e.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null,this.invalidateVisualRows()}forEachActivity(e){for(let[n,r]of this._activities)e(r,n)}getParentId(e){return this._hierarchy.getParentId(e)}getActivity(e){return this._activities.get(String(e))??null}getLastStartDate(e){return this._lastStartDate.get(String(e))??null}setLastStartDate(e,n){this._captureLastStartDateOnce(),this._lastStartDate.set(String(e),n)}getPromotionSnapshot(e){return this._promotionSnapshot.get(String(e))??null}setPromotionSnapshot(e,n){this._capturePromotionSnapshotOnce(),this._promotionSnapshot.set(String(e),n)}getProgressFallback(e){return this._progressFallback.get(String(e))??null}setProgressFallback(e,n){let r=String(e),i=this._progressFallback.get(r)??null;Object.is(i,n)||(this._writeCapture.noteProgressFallback(r,i),n===null?this._progressFallback.delete(r):this._progressFallback.set(r,n))}_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(e){return this._links.get(String(e))??null}activityExists(e){return this._activities.has(String(e))}isChecked(e){return this._viewState.isChecked(String(e))}isVisible(e){return this._viewState.isVisible(String(e))}checkedIds(){return this._viewState.checkedIds()}hiddenIds(){return this._viewState.hiddenIds()}setChecked(e,n){return this._captureViewStateOnce(),this._viewState.setChecked(String(e),n)}setVisible(e,n){this._captureViewStateOnce();let r=this._viewState.setVisible(String(e),n);return r&&this.invalidateVisualRows(),r}getActiveFilter(){return this._viewState.getActiveFilter()}setActiveFilter(e){this._captureViewStateOnce(),this._viewState.setActiveFilter(e),this._filterProjection=null,this.invalidateVisualRows()}getFilterProjection(){return this._filterProjection}setFilterProjection(e){this._filterProjection=e}getActiveOrder(){return this._viewState.getActiveOrder()}setActiveOrder(e){this._captureViewStateOnce(),this._viewState.setActiveOrder(e),this.invalidateDerivedOrder()}getOrderComparator(){let e=this._viewState.getActiveOrder();return e===null?(this._cache.orderComparator=null,null):this._cache.orderComparator?this._cache.orderComparator:(this._cache.orderComparator=this._buildOrderComparator(e,this._viewAttributes.getCatalogMap()),this._cache.orderComparator)}getOrderMode(){return this._viewState.getActiveOrder()?.mode??an.STANDARD}invalidateDerivedOrder(){this._cache.orderComparator=null,this._cache.visualOrderIds=null,this.invalidateVisualRows()}getViewAttributeCatalogMap(){return this._viewAttributes.getCatalogMap()}setViewAttributeCatalogs(e){this._viewAttributes.setCatalogs(e),this.invalidateDerivedOrder()}getGroup(){return this._viewAttributes.getGroup()}setGroup(e){this._viewAttributes.setGroup(e),this.invalidateVisualRows()}getWbsDepth(){return this._viewAttributes.getWbsDepth()}setWbsDepth(e){this._viewAttributes.setWbsDepth(e),this.invalidateVisualRows()}invalidateVisualRows(){this._cache.visualRows=null}getVisualRows(){if(this._cache.visualRows)return this._cache.visualRows;let e=this._viewAttributes.getGroup(),n=e===null?null:this._viewAttributes.getCatalog(e.attributeKey),r=e?.secondary==null?null:this._viewAttributes.getCatalog(e.secondary.attributeKey),i=[];for(let a of this.getVisualOrderIds()){let o=this.getActivity(a);o!==null&&i.push(o)}return this._cache.visualRows=xI({activitiesInVisualOrder:i,isVisible:a=>this.isVisible(a),parentOf:a=>this.getParentId(a),hasChildren:a=>this.hasChildren(a),group:e,catalog:n,secondaryCatalog:r,comparator:this.getOrderComparator(),orderMode:this.getOrderMode(),wbsDepth:this._viewAttributes.getWbsDepth()}),this._cache.visualRows}hydrateViewState(e){this._viewState.hydrate(e),this._filterProjection=null,this.invalidateDerivedOrder()}_captureViewStateOnce(){this._writeCapture.peek()!==null&&this._viewStateBefore===null&&(this._viewStateBefore=this._viewState.snapshot())}getOutgoingLinkIds(e){return this._outgoing.get(String(e))??MI}getIncomingLinkIds(e){return this._incoming.get(String(e))??MI}getChildren(e){return this._hierarchy.getChildren(e)}hasChildren(e){return this._hierarchy.hasChildren(e)}isChildOf(e,n){return this._hierarchy.isChildOf(e,n)}getParent(e){return this._hierarchy.getParent(e)}getRootIds(){return this._hierarchy.getRootIds()}getClosestWorkTime(e){return this._calendar.getClosestWorkTime(e)}isWorkTime(e){return this._calendar.isWorkTime(e)}calculateEndDate(e){return this._calendar.calculateEndDate(e)}calculateDuration(e){return this._calendar.calculateDuration(e)}clearCalendarCache(){this._calendar.clearCache()}get calendarReader(){return this._calendar.reader}batchUpdate(e){e()}updateActivity(e){this._noteSchedulingField(e,b.START_DATE,null),this._noteSchedulingField(e,b.END_DATE,null)}getLiveActivity(e){return this.getActivity(e)}getFlags(){return{...this._flags,allCheckedTaskIds:this._viewState.checkedIds()}}getProjectEnd(){return null}isScheduleSettled(){return this._scheduleSettled}markScheduleSettled(){this._writeCapture.peek()===null?this._scheduleSettled=!0:this._settledByPassInCapture=!0}openSchedulingWriteLog(e,n){let r=new Ml(e,n,()=>this._hierarchy.settle());return this._schedulingWriteLogs.push(r),r}_noteSchedulingStructure(){for(let e of this._schedulingWriteLogs)e.markStructural()}_noteSchedulingReshape(e){if(e!==null)for(let n of this._schedulingWriteLogs)n.reshape(String(e))}_noteSchedulingLinks(){for(let e of this._schedulingWriteLogs)e.changeLinks()}_noteSchedulingField(e,n,r){if(this._schedulingWriteLogs.length!==0){if(n===b.PARENT||n===b.TYPE){this._noteSchedulingReshape(e),n===b.PARENT&&this._noteSchedulingReshape(r);return}for(let i of this._schedulingWriteLogs)i.touch(String(e),n)}}_noteSchedulingLinkField(e){(e===Xt.LAG||e===Xt.TYPE)&&this._noteSchedulingLinks()}beginWriteCapture(){this._writeCapture.begin(),this._settledByPassInCapture=!1,this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=null,this._missingSchedulingStateCountBefore=this._missingSchedulingStateCount,this._dataDateBefore=null}peekWriteCapture(){return this._writeCapture.peek()}endWriteCapture(){let e=this._writeCapture.peek();this._settledByPassInCapture?this._scheduleSettled=!0:e!==null&&bI(e,n=>this.getActivity(n),n=>this.getLink(n))&&(this._scheduleSettled=!1),this._settledByPassInCapture=!1,this._writeCapture.end(),this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=null,this._missingSchedulingStateCountBefore=null,this._dataDateBefore=null}setActivityField(e,n,r){let i=this.getActivity(e);if(!i)return;let a=Zn(i);this._writeCapture.note(String(e),i);let o=i.parentId;i[n]=r,this._noteSchedulingField(e,n,o),this._updateSchedulingStateCount(a,i),xu(i,n),n===b.PARENT&&this._hierarchy.markDirty(),wu(n)&&(this._cache.visualOrderIds=null)}setActivityFieldDynamic(e,n,r){let i=this.getActivity(e);if(!i)return;if(!Object.hasOwn(i,n))throw new Error(`setActivityFieldDynamic: unknown CoreActivity field "${n}"`);let a=Zn(i);this._writeCapture.note(String(e),i);let o=i.parentId;Reflect.set(i,n,oI(n,r)),this._noteSchedulingField(e,n,o),this._updateSchedulingStateCount(a,i),xu(i,n),n===b.PARENT&&this._hierarchy.markDirty(),wu(n)&&(this._cache.visualOrderIds=null)}setActivityFields(e,n){let r=this.getActivity(e);if(!r)return;let i=Zn(r);this._writeCapture.note(String(e),r);let a=!1;for(let o of Object.keys(n)){let s=r.parentId;Reflect.set(r,o,Reflect.get(n,o)),this._noteSchedulingField(e,o,s),xu(r,o),o===b.PARENT&&(a=!0),wu(o)&&(this._cache.visualOrderIds=null)}this._updateSchedulingStateCount(i,r),a&&this._hierarchy.markDirty()}addLink(e){this._writeCapture.noteLinkAdd(String(e.id));let n=this._links.get(String(e.id));if(n)this._noteSchedulingLinks();else for(let i of this._schedulingWriteLogs)i.appendLink(String(e.id));n&&this._deindexLink(n);let r={...e,freeSlackHours:e.freeSlackHours??null,isCritical:e.isCritical===!0};this._links.set(String(e.id),r),this._indexLink(r)}_indexLink(e){UI(this._outgoing,String(e.source),e.id),UI(this._incoming,String(e.target),e.id)}_deindexLink(e){let n=this._outgoing.get(String(e.source));n&&this._outgoing.set(String(e.source),Mu(n,e.id));let r=this._incoming.get(String(e.target));r&&this._incoming.set(String(e.target),Mu(r,e.id))}_removeLinkRef(e,n,r){let i=e.get(n);i&&e.set(n,Mu(i,r))}_insertLinkRefInOrder(e,n,r){let i=new Set;for(let s of this._links.keys()){if(String(s)===String(r))break;i.add(String(s))}let a=[...e.get(n)??[]],o=a.findIndex(s=>!i.has(String(s)));a.splice(o<0?a.length:o,0,r),e.set(n,a)}setLinkField(e,n,r){let i=this.getLink(e);i&&(this._writeCapture.noteLinkField(String(e),i),i[n]=r,this._noteSchedulingLinkField(n))}setLinkEndpoints(e,n,r){let i=this.getLink(e);if(!i)return;let a=String(i.source)!==String(n),o=String(i.target)!==String(r);!a&&!o||(this._writeCapture.noteLinkField(String(e),i),this._noteSchedulingLinks(),a&&(this._removeLinkRef(this._outgoing,String(i.source),i.id),i.source=n,this._insertLinkRefInOrder(this._outgoing,String(n),i.id)),o&&(this._removeLinkRef(this._incoming,String(i.target),i.id),i.target=r,this._insertLinkRefInOrder(this._incoming,String(r),i.id)))}setLinkFieldDynamic(e,n,r){let i=this.getLink(e);if(i){if(n===Xt.SOURCE){this.setLinkEndpoints(e,String(r),i.target);return}if(n===Xt.TARGET){this.setLinkEndpoints(e,i.source,String(r));return}WF(n)&&(this._writeCapture.noteLinkField(String(e),i),Reflect.set(i,n,r),this._noteSchedulingLinkField(n))}}setLinkProplannerId(e,n){let r=this.getLink(e);r&&(this._writeCapture.noteLinkField(String(e),r),r.proplannerId=n)}removeLink(e){let n=this.getLink(e);if(n){this._writeCapture.noteLinkRemove(String(e),n);for(let r of this._schedulingWriteLogs)r.removeLink(String(e));this._links.delete(String(e)),this._deindexLink(n)}}addActivity(e){this._writeCapture.noteInsert(String(e.id)),this._noteSchedulingReshape(e.id);let n=this._activities.get(e.id);n&&Zn(n)&&(this._missingSchedulingStateCount-=1),this._activities.set(e.id,e),Zn(e)&&(this._missingSchedulingStateCount+=1),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.addChild(e.parentId,e.id)}removeActivity(e){let n=this.getActivity(e);n&&this._writeCapture.noteRemove(String(e),n),this._noteSchedulingReshape(e),this._noteSchedulingReshape(n?.parentId??null),n&&Zn(n)&&(this._missingSchedulingStateCount-=1);let r=String(e);this.setProgressFallback(r,null),(this._viewState.isChecked(r)||!this._viewState.isVisible(r))&&this._captureViewStateOnce(),this._viewState.forget(r),this._activities.delete(e),this._lastStartDate.has(String(e))&&(this._captureLastStartDateOnce(),this._lastStartDate.delete(String(e))),this._outgoing.delete(String(e)),this._incoming.delete(String(e)),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}noteCorrelativeBefore(e,n){this._writeCapture.noteCorrelativeBefore(e,n)}noteScheduledBefore(e,n){this._writeCapture.noteScheduledBefore(e,n)}restoreFromCapture(){let e=this._writeCapture.peek();if(!e)return;this._noteSchedulingStructure();let{ops:n,before:r,correlativeBefore:i,scheduledBefore:a,progressFallbackBefore:o}=e;this._undoLinkAdds(n),this._undoInserts(n),this._reInsertRemovedActivities(n),this._reAddRemovedLinks(n),this._restoreLinkFields(n),this._restoreActivityFields(a),this._restoreActivityFields(r),this._restoreCorrelatives(i),this._restoreProgressFallbacks(o),this._missingSchedulingStateCountBefore!==null&&(this._missingSchedulingStateCount=this._missingSchedulingStateCountBefore),this._dataDateBefore!==null&&(this._dataDate=this._dataDateBefore),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(e){for(let[n,r]of e)r===null?this._progressFallback.delete(n):this._progressFallback.set(n,r)}_restoreCorrelatives(e){for(let[n,r]of e){let i=this._activities.get(n);i&&(i.correlativeId=r)}}_undoLinkAdds(e){for(let n of e)n.kind===Et.LINK_ADD&&this._detachLink(n.linkId)}_undoInserts(e){for(let n of e)n.kind===Et.INSERT&&this._activities.delete(n.activityId)}_reInsertRemovedActivities(e){for(let n of e)n.kind===Et.REMOVE&&this._activities.set(n.activityId,n.before)}_reAddRemovedLinks(e){for(let n of e)n.kind===Et.LINK_REMOVE&&this._attachLink(n.before)}_restoreLinkFields(e){for(let n of e){if(n.kind!==Et.LINK_FIELD)continue;let r=this._links.get(n.linkId);if(r){this.setLinkEndpoints(n.linkId,n.before.source,n.before.target);for(let i of Object.keys(r))Object.hasOwn(n.before,i)||Reflect.deleteProperty(r,i);Object.assign(r,n.before)}}}_restoreActivityFields(e){for(let[n,r]of e){let i=this._activities.get(n);i&&this._restoreScalarFields(i,r)}}_restoreScalarFields(e,n){for(let r of Object.keys(e))Object.hasOwn(n,r)||Reflect.deleteProperty(e,r);for(let r of Object.keys(n))Reflect.set(e,r,Reflect.get(n,r))}_updateSchedulingStateCount(e,n){let r=Zn(n);e!==r&&(this._missingSchedulingStateCount+=r?1:-1)}_attachLink(e){this._links.set(String(e.id),{...e}),this._indexLink(e)}_detachLink(e){let n=this.getLink(e);n&&(this._links.delete(String(e)),this._deindexLink(n))}},MI=[];function WF(t){return t===Xt.LAG||t===Xt.TYPE||t===Xt.FREE_SLACK_HOURS||t===Xt.IS_CRITICAL}function wu(t){return t===b.PARENT||t===b.CORRELATIVE_ID}function Zn(t){return t.type!==H.PROJECT&&t.p6===void 0}function xu(t,e){e!==b.START_DATE&&e!==b.END_DATE&&e!==b.TYPE||(t.calendarDuration=Je(t))}function Mu(t,e){return t.filter(n=>String(n)!==String(e))}function UI(t,e,n){let r=t.get(e);r?r.push(n):t.set(e,[n])}function KF(t){let e=t.runtimeFlags??{};return{isPasting:!!e.isPasting,isBulkOperation:!!e.isBulkOperation,dragWithMultiple:!!e.dragWithMultiple,draggingSingleMilestone:!!e.draggingSingleMilestone,creatingActivity:!1,avoidAutoScheduleBeforeDrag:!1,maxPerformance:!!e.maxPerformance,allCheckedTaskIds:[]}}var YF=["id","parentId","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","progress"],GF=["remainingEarlyStart","remainingEarlyFinish","remainingLateStart","remainingLateFinish","earlyStart","earlyFinish","lateStart","lateFinish","remainingFloatHours","floatPath","floatPathOrder","longestPath"];function HI(t){let e=Object.fromEntries(YF.map(i=>[i,t[i]]));if(t.p6===void 0)return e;let n=t.p6,r={...n,activityType:n.activityType??re.TASK,durationType:n.durationType??Re.FIXED_DURATION_AND_UNITS,primaryConstraintType:n.primaryConstraintType??null,primaryConstraintDate:n.primaryConstraintDate??null,sourcePrimaryConstraintToken:n.sourcePrimaryConstraintToken??null,sourceSecondaryConstraintToken:Reflect.get(n,"sourceSecondaryConstraintToken")??null,resourceAssignments:n.resourceAssignments??[]};delete r.sourceActivityTypeToken,delete r.sourceDurationTypeToken;for(let i of GF)delete r[i];return{...e,p6:r}}function Uu(t){if(!t.hasCompleteSchedulingState)return{};let e=Oi(t.activity);return e===void 0?{}:{p6:e}}function BI(t){return{activityPatch:t.p6===void 0?{}:{p6:void 0},snapshotPatch:t.p6===void 0?{}:{p6:C(t.p6)}}}function jI(t){let e=t.promotionSnapshot?.p6;return e===void 0?Uu(t):{p6:C(e)}}function WI(t,e){let n=e==="before";return{...t.p6Settings===void 0?{}:{p6Settings:n?VI(t.p6Settings):C(t.p6Settings)},...t.p6ProjectPlannedStart===void 0?{}:{p6ProjectPlannedStart:n?VI(t.p6ProjectPlannedStart):C(t.p6ProjectPlannedStart)}}}function KI(t,e,n){t.p6Settings!==void 0&&n.setSettings(C(t.p6Settings[e])),t.p6ProjectPlannedStart!==void 0&&n.setProjectPlannedStart(C(t.p6ProjectPlannedStart[e]))}function YI(t){return t.p6Settings!==void 0||t.p6ProjectPlannedStart!==void 0}function VI(t){return{before:C(t.after),after:C(t.before)}}function Zi(t){if(t===void 0)return["undefined"];if(t===null)return["null"];if(typeof t=="string")return["string",t];if(typeof t=="boolean")return["boolean",t];if(typeof t=="number")return["number",Object.is(t,-0)?"-0":String(t)];if(typeof t=="bigint")return["bigint",String(t)];if(t instanceof Date)return["date",String(t.getTime())];if(Array.isArray(t))return["array",t.map(Zi)];if(t instanceof Map)return["map",Array.from(t,([e,n])=>[Zi(e),Zi(n)]).sort((e,n)=>JSON.stringify(e).localeCompare(JSON.stringify(n)))];if(t instanceof Set)return["set",Array.from(t,Zi).sort((e,n)=>JSON.stringify(e).localeCompare(JSON.stringify(n)))];if(typeof t=="object")return["object",Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,Zi(n)])];throw new TypeError(`Unsupported canonical value: ${typeof t}`)}function Jt(t){return JSON.stringify(Zi(t))}var Vl=t=>(t>>>0).toString(16).padStart(8,"0");function Hu(t){let e=1779033703,n=3144134277,r=1013904242,i=2773480762;for(let a=0;a<t.length;a+=1){let o=t.charCodeAt(a);e=n^Math.imul(e^o,597399067),n=r^Math.imul(n^o,2869860233),r=i^Math.imul(r^o,951274213),i=e^Math.imul(i^o,2716044179)}return e=Math.imul(r^e>>>18,597399067),n=Math.imul(i^n>>>22,2869860233),r=Math.imul(e^r>>>17,951274213),i=Math.imul(n^i>>>19,2716044179),`${Vl(e^n^r^i)}${Vl(n^e)}${Vl(r^e)}${Vl(i^e)}`}function GI(t,e){return{p6Settings:C(t),p6ProjectState:C(e)}}function Qn(t,e){return Jt(t)!==Jt(e)}function qI(t,e){t.clear();for(let n of e)n.p6!==void 0&&t.set(String(n.id),C(n.p6))}function $I(t,e){let n=e?.p6;return t===void 0&&n===void 0?!1:Qn(t,n)}function zI(t,e){let n=new Map;for(let r of t){let i=e(r)?.p6;i!==void 0&&n.set(r,C(i))}return n}function XI(t,e){let n=e.projectState?.plannedStart??null,r=t.projectState?.plannedStart??null;return{...JI(e.settings,t.settings)?{p6Settings:{before:C(e.settings),after:C(t.settings)}}:{},...JI(n,r)?{p6ProjectPlannedStart:{before:C(n),after:C(r)}}:{}}}function JI(t,e){return Jt(t)!==Jt(e)}var ZI="Invalid P6 activity status",Bu=class extends Error{constructor(n,r){super(`${ZI}: ${r}`);this.code=n;this.name="P6ActivityStatusError"}code},qF=100,$F=0;function QI(t){tS(t.remainingDurationHours),eS(t),JF(t),nS(t)}function po(t){zF(t.remainingDurationHours),eS(t),XF(t),nS(t)}function Wl(t,e){if(e.actualStart===void 0&&e.actualFinish===void 0)return e;let n=e.actualStart!==void 0?e.actualStart:t.actualStart,r=e.actualFinish!==void 0?e.actualFinish:t.actualFinish,i=r!==null?"completed":n!==null?"in_progress":"not_started",a=n===null&&r===null&&t.actualStart!==null,o={...e,executionStatus:i,...r!==null?{remainingDurationHours:0,physicalPercentComplete:qF}:{},...a?{remainingDurationHours:t.originalDurationHours,physicalPercentComplete:$F}:{}};return po({...t,...o}),o}function tS(t){(!Number.isFinite(t)||t<0)&&fe("Remaining Duration must be finite and non-negative")}function zF(t){t!==null&&tS(t)}function eS(t){[t.actualStart,t.actualFinish,t.suspendDate,t.resumeDate].some(n=>n!==null&&Number.isNaN(n.getTime()))&&fe("actual, suspend and resume dates must be valid")}function JF(t){let e=t.actualStart!==null,n=t.actualFinish!==null;if(t.executionStatus==="not_started"){(e||n)&&fe("not_started cannot have actual dates");return}if(t.executionStatus==="in_progress"){(!e||n)&&fe("in_progress requires Actual Start and no Actual Finish");return}(!e||!n||t.remainingDurationHours!==0)&&fe("completed requires Actual Start, Actual Finish and zero Remaining Duration")}function XF(t){let e=t.actualStart!==null,n=t.actualFinish!==null;n&&!e&&fe("Actual Finish requires Actual Start"),t.executionStatus==="not_started"&&e&&fe("not_started cannot have actual dates"),t.executionStatus==="in_progress"&&n&&fe("in_progress cannot have Actual Finish"),t.executionStatus==="completed"&&t.remainingDurationHours!==null&&t.remainingDurationHours!==0&&fe("completed requires zero Remaining Duration")}function nS(t){let{actualStart:e,actualFinish:n,suspendDate:r,resumeDate:i}=t;if(e!==null&&n!==null&&e.getTime()>n.getTime())throw new Bu("ACTUAL_FINISH_BEFORE_START","Actual Start must not be after Actual Finish");r!==null&&(e===null&&fe("Suspend requires Actual Start"),e.getTime()>r.getTime()&&fe("Suspend must not be before Actual Start"),n!==null&&r.getTime()>n.getTime()&&fe("Suspend must not be after Actual Finish")),i!==null&&(r===null&&fe("Resume requires Suspend"),r.getTime()>i.getTime()&&fe("Suspend must not be after Resume"),n!==null&&i.getTime()>n.getTime()&&fe("Resume must not be after Actual Finish"))}function fe(t){throw new Error(`${ZI}: ${t}`)}var ju="Invalid P6 derived input",Wu=100,yo=0,Qi=100,ZF=16,QF=8,tw="178",Ku=Date.parse("2026-10-07T12:00:00.000Z"),ew=Date.parse("2026-10-08T12:00:00.000Z"),nw=Date.parse("2026-10-12T12:00:00.000Z"),rw=Date.parse("2026-10-06T08:00:00.000Z"),iw=Ku,aw=Ku,ow=Date.parse("2026-10-08T12:00:00.000Z"),sw=Date.parse("2026-10-05T08:00:00.000Z"),lw=Date.parse("2026-10-06T08:00:00.000Z");function fo(t,e){return QI(t),cw(t,e.dataDate),{actualDurationHours:iS(t,e),atCompletionDurationHours:dw(t,e),durationPercentComplete:uw(t),unitsPercentComplete:pw(t,e),schedulePercentComplete:Yu(t,e),remainingFloatHours:hw(t,e.calendar,e.totalFloatMethod??"finish_float")}}function rS(t,e){return iS(t,e)}function cw(t,e){let n=[t.originalDurationHours,t.remainingDurationHours],r=[t.actualLaborUnits,t.remainingLaborUnits,t.actualNonlaborUnits,t.remainingNonlaborUnits];if(n.some(i=>!Number.isFinite(i)||i<0))throw new Error(`${ju}: expected finite non-negative durations`);if(r.some(i=>!Number.isFinite(i)))throw new Error(`${ju}: expected finite unit scalars`);if(Number.isNaN(e.getTime()))throw new Error(`${ju}: invalid Data Date`)}function iS(t,e){if(t.executionStatus==="not_started"||t.actualStart===null)return 0;let n=t.executionStatus==="completed"?t.actualFinish:e.dataDate;return n===null?0:Vu(e.calendar,t.actualStart,n)}function dw(t,e){return t.executionStatus==="not_started"?mw(e.calendar,t.plannedStart,t.plannedFinish):t.executionStatus==="in_progress"?t.actualStart===null||t.remainingEarlyFinish===null?0:Vu(e.calendar,t.actualStart,t.remainingEarlyFinish):t.actualStart===null||t.actualFinish===null?0:Vu(e.calendar,t.actualStart,t.actualFinish)}function Vu(t,e,n){return e.getTime()>=n.getTime()?0:ta(t,e,n)}function uw(t){return t.originalDurationHours===0?0:aS((t.originalDurationHours-t.remainingDurationHours)/t.originalDurationHours*Wu)}function pw(t,e){let n=t.actualLaborUnits+t.actualNonlaborUnits,r=t.remainingLaborUnits+t.remainingNonlaborUnits,i=n+r;return i===0?yw(t,e)?Qi:yo:n/i*Wu}function yw(t,e){return t.executionStatus!==tt.COMPLETED||t.actualStart===null||t.actualFinish===null||t.remainingDurationHours!==0||t.percentCompleteType!==xt.DURATION||e.dataDate.getTime()!==Ku||e.calendarId!==tw||!fw(t)?!1:t.activityType===re.TASK?t.durationType===Re.FIXED_DURATION_AND_UNITS&&t.originalDurationHours===QF&&t.physicalPercentComplete===Qi&&tr(t.plannedStart,aw)&&tr(t.plannedFinish,ow)&&tr(t.actualStart,sw)&&tr(t.actualFinish,lw):t.activityType===re.LEVEL_OF_EFFORT&&t.durationType===Re.FIXED_DURATION_AND_UNITS_PER_TIME&&t.originalDurationHours===ZF&&t.physicalPercentComplete===Qi&&tr(t.plannedStart,ew)&&tr(t.plannedFinish,nw)&&tr(t.actualStart,rw)&&tr(t.actualFinish,iw)}function fw(t){return t.expectedFinish===null&&t.suspendDate===null&&t.resumeDate===null&&t.secondaryConstraintType===null&&t.secondaryConstraintDate===null&&t.primaryBaselineStart===null&&t.primaryBaselineFinish===null&&(t.resourceAssignments?.length??0)===0}function tr(t,e){return t?.getTime()===e}function Yu(t,e){let n=t.primaryBaselineStart!==null,r=t.primaryBaselineFinish!==null;if(n!==r)return null;let i=t.primaryBaselineStart??t.plannedStart,a=t.primaryBaselineFinish??t.plannedFinish;if(i===null||a===null)return null;if(i.getTime()===a.getTime())return e.dataDate.getTime()<i.getTime()?yo:Qi;if(e.dataDate.getTime()<=i.getTime())return yo;if(e.dataDate.getTime()>=a.getTime())return Qi;let o=ta(e.calendar,i,a);if(o<=0)return yo;let s=ta(e.calendar,i,e.dataDate);return aS(s/o*Wu)}function hw(t,e,n){if(t.remainingEarlyFinish===null||t.lateFinish===null)return null;let r=ta(e,t.remainingEarlyFinish,t.lateFinish);if(n==="finish_float")return Object.is(r,-0)?0:r;if(t.remainingEarlyStart===null||t.lateStart===null)return null;let i=ta(e,t.remainingEarlyStart,t.lateStart),a=n==="start_float"?i:Math.min(i,r);return Object.is(a,-0)?0:a}function mw(t,e,n){return e===null||n===null?0:ta(t,e,n)}function ta(t,e,n){if(e.getTime()<=n.getTime())return t.calculateDuration(e,n);let r=-t.calculateDuration(n,e);return Object.is(r,-0)?0:r}function aS(t){return Math.min(Qi,Math.max(yo,t))}var gw=new Set([re.TASK,re.RESOURCE_DEPENDENT]),Aw=new Map;function Kl(t){if(!(t.settings.useExpectedFinishDates&&Iw(t.previousSettings,t.settings)))return Aw;let n=new Map;for(let[r,i]of t.activities){let a=i.remainingEarlyFinish;a!==null&&Sw(i)&&n.set(r,new Date(a))}return n}function Iw(t,e){let n=t.dataDate,r=e.dataDate;return n===null||r===null?!1:r.getTime()>n.getTime()}function Sw(t){return t.executionStatus===tt.IN_PROGRESS&&t.expectedFinish===null&&vw(t)}function vw(t){let{activityType:e}=t;return e===void 0?!0:gw.has(e)}function Yl(t,e){return{freeSlackHours:t.freeFloatHours,criticalPath:{earlyStart:C(t.earlyStart),earlyFinish:C(t.earlyFinish),lateStart:C(t.lateStart),lateFinish:C(t.lateFinish),totalSlackHours:t.remainingFloatHours},isCritical:e.criticalActivityMethod===Cr.LONGEST_PATH?t.longestPath:t.remainingFloatHours!==null&&t.remainingFloatHours<=e.criticalFloatThresholdHours}}function oS(t){let e=new Set(t.criticalPath);return new Map([...t.activities].map(([n,r])=>{let i=r.actualStart??r.remainingEarlyStart,a=r.actualFinish??r.remainingEarlyFinish;return[n,{p6:C(r),...i===null?{}:{startDate:C(i)},...a===null?{}:{endDate:C(a)},isCritical:e.has(n),freeSlackHours:r.freeFloatHours,criticalPath:{earlyStart:C(r.earlyStart),earlyFinish:C(r.earlyFinish),lateStart:C(r.lateStart),lateFinish:C(r.lateFinish),totalSlackHours:r.remainingFloatHours}}]}))}function sS(t,e,n,r={}){if(!Tw(e.dataDate,n.dataDate))return new Map;if(!At(n,r.enabled))return new Map;let i=!At(e,r.enabled),a=t.getAllActivities(),o=Cw(a,e,n,r.adoptExpectedFinish),s=new Map;for(let l of a){let c=l.p6;if(c===void 0)continue;let d=t.calendarReader.getCalendar(l.calendarId);if(d===null)throw new Error(`Missing calendar for Data Date activity ${l.id}`);let u=Dw(c,n.dataDate,d,o.get(l.id)),p=!Object.is(u.expectedFinish,c.expectedFinish)||!Object.is(u.schedulePercentComplete,c.schedulePercentComplete)||!Object.is(u.actualDurationHours,c.actualDurationHours);!i&&!p||s.set(l.id,{...p?{p6:u}:{},...i?Yl(u,n):{}})}return s}function Cw(t,e,n,r=!1){if(!r)return new Map;if(n.setDataDateAndPlannedStartToForecastStart&&n.projectForecastStart!==null)return new Map;let a=new Map(t.flatMap(o=>{let s=o.p6,l=s!==void 0&&sn(s);return o.type===H.PROJECT||!l?[]:[[o.id,s]]}));return Kl({previousSettings:e,settings:n,activities:a})}function lS(t,e){for(let[n,r]of e)t.setActivityFields(n,r)}function Dw(t,e,n,r){let i={dataDate:e,calendar:n},a=Yu(t,i),o=sn(t)&&t.executionStatus===tt.IN_PROGRESS;return{...t,expectedFinish:r??t.expectedFinish,schedulePercentComplete:a,...o?{actualDurationHours:rS(t,i)}:{}}}function Tw(t,e){return t?.getTime()!==e?.getTime()}var _w=["remainingDurationHours","originalDurationHours","actualStart","actualFinish","suspendDate","resumeDate"];function ql(t,e,n){if(!Ew(t,e))return{p6:{...e}};if(!sn(e))return{p6:{...e},...cS(t,e),...dS(t,e,null)};let r=Rw(e,n.calendar),i=fo(r===null?e:{...e,remainingEarlyFinish:r},{dataDate:n.dataDate,calendar:n.calendar,...n.totalFloatMethod===void 0?{}:{totalFloatMethod:n.totalFloatMethod}});return{p6:{...e,...i,remainingFloatHours:e.remainingFloatHours},...cS(t,e),...dS(t,e,r)}}function Ew(t,e){return _w.some(n=>!Gl(t[n],e[n]))}function Rw(t,e){return t.executionStatus==="completed"||t.remainingEarlyStart===null?null:e.calculateEndDate(t.remainingEarlyStart,t.remainingDurationHours)}function cS(t,e){if(Gl(t.actualStart,e.actualStart))return{};let n=e.actualStart??e.remainingEarlyStart;return n===null?{}:{startDate:C(n)}}function dS(t,e,n){if(!(!Gl(t.remainingDurationHours,e.remainingDurationHours)||!Gl(t.actualFinish,e.actualFinish)))return{};let i=e.actualFinish??n??e.remainingEarlyFinish;return i===null?{}:{endDate:C(i)}}function Gl(t,e){return t instanceof Date||e instanceof Date?t instanceof Date&&e instanceof Date&&t.getTime()===e.getTime():Object.is(t,e)}var Te=class extends Error{constructor(n,r,i=[],a=0,o=[]){super(r);this.code=n;this.relationshipIds=i;this.count=a;this.sampleActivityIds=o;this.name="P6CapabilityError"}code;relationshipIds;count;sampleActivityIds};function uS(t){return Object.freeze({getSettings:t.getSettings,getProjectState:t.getProjectState,getLatestRunLog:t.getLatestRunLog,getScheduleStateFingerprint:t.getScheduleStateFingerprint,getDefaultSettings:t.getDefaultSettings,getScheduleReadiness:t.getScheduleReadiness,searchEndingActivities:t.searchEndingActivities,getEndingActivityOption:t.getEndingActivityOption,resolveMustFinishByDefault:t.resolveMustFinishByDefault,updateSettings:t.updateSettings,updateActivity:t.updateActivity,schedule:t.schedule})}function $l(t){return t.outOfSequencePolicy!=="progress_override"||t.successorExecution!=="in_progress"?!0:t.linkType==="2"||t.linkType==="3"}function gn(t){return t.actualFinish!==null?{execution:"completed",hasRemaining:!1}:t.actualStart!==null?{execution:"in_progress",hasRemaining:!0}:{execution:"not_started",hasRemaining:!0}}function ho(t){return t.outOfSequencePolicy==="retained_logic"&&t.linkType==="1"&&t.actualStart!==null}function qu(t,e,n){let r=yS(e);if(r.length===0)return null;let i=r.map(a=>{let o=fS(e,a),s=t.getClosestWorkTime({date:n,dir:"future",task:o}),l=t.calculateEndDate({startDate:s,durationHours:Gu(a),task:o});return{start:s,finish:l}});return hS(i)}function pS(t,e,n){let r=yS(e);if(r.length===0)return null;let i=r.map(a=>{let o=fS(e,a),s=t.getClosestWorkTime({date:n,dir:"past",task:o}),l=t.calculateEndDate({startDate:s,durationHours:-Gu(a),task:o}),c=t.calculateEndDate({startDate:l,durationHours:Gu(a),task:o});return{start:l,finish:c}});return hS(i)}function yS(t){if(t.p6?.activityType!=="resource_dependent")return[];let e=t.p6.resourceAssignments??[];for(let n of e)Pw(n);return e}function Pw(t){for(let e of[t.actualUnits,t.remainingUnits,t.unitsPerHour])if(!Number.isFinite(e)||e<0)throw new Error(`Invalid P6 resource assignment ${t.id}`);if(t.remainingUnits>0&&t.unitsPerHour<=0)throw new Error(`Invalid P6 resource assignment rate ${t.id}`)}function Gu(t){let e=t.remainingUnits===0?0:t.remainingUnits/t.unitsPerHour;return kw(e)}function kw(t){let e=Math.round(t),n=Number.EPSILON*Math.max(1,Math.abs(t))*32;return Math.abs(t-e)<=n?e:t}function fS(t,e){return{...t,calendarId:e.calendarId}}function hS(t){let e=new Date(Math.min(...t.map(r=>r.start.getTime()))),n=new Date(Math.max(...t.map(r=>r.finish.getTime())));return{start:e,finish:n}}var bw=4;function zl(t){let e=Lw(t);if(e!==null)return e;let n=Ow(t);if(n!==null)return n;let r=Nw(t);if(r!==null)return r;let i=Fw(t);if(i!==null)return i;if(t.link.type===q.START_TO_FINISH&&Wr(t.link)&&t.successor.p6?.activityType==="finish_milestone")return ww(t);let a=Ma(t.predecessor,t.successor,t.link,t.adapter,t.lagTask).successorStart;return!Hw(t)||a.getTime()===t.predecessor.endDate.getTime()?a:t.adapter.getClosestWorkTime({date:t.predecessor.endDate,dir:"future",task:t.successor})}function Lw(t){let e=t.link._trueLag??t.link.lag??0;if(t.link.type!==q.FINISH_TO_FINISH||!Wr(t.link)||t.successor.durationHours===0||t.lagTask!==null||e<=0)return null;let n=jn(t.predecessor.endDate,e);return t.adapter.calculateEndDate({startDate:n,durationHours:-t.successor.durationHours,task:t.successor})}function Ow(t){let e=t.link._trueLag??t.link.lag??0;return t.link.type!==q.START_TO_START||!Wr(t.link)||t.successor.p6?.activityType!=="finish_milestone"||t.successor.durationHours!==0||t.lagTask!==null||e===0?null:t.adapter.getClosestWorkTime({date:jn(t.predecessor.startDate,e),dir:"future",task:t.successor})}function Nw(t){let e=(t.link._trueLag??t.link.lag??0)===0;if(t.link.type!==q.FINISH_TO_START||t.predecessor.p6?.activityType!=="resource_dependent"||t.successor.p6?.activityType!=="level_of_effort"||t.successor.durationHours!==0||!e)return null;let n=xa(t.predecessor.endDate),r=t.adapter.getClosestWorkTime({date:n,dir:"future",task:t.successor});return r.getTime()===n.getTime()?t.predecessor.endDate:r}function Fw(t){let e=t.link._trueLag??t.link.lag??0;return!(t.link.type===q.FINISH_TO_START||t.link.type===q.FINISH_TO_FINISH)||!Wr(t.link)||t.successor.p6?.activityType!=="finish_milestone"||e>=0||t.lagTask!==null?null:t.adapter.getClosestWorkTime({date:jn(t.predecessor.endDate,e),dir:"future",task:t.successor})}function ww(t){let e=t.link._trueLag??t.link.lag??0,n=t.lagTask===null?jn(t.predecessor.startDate,e):t.adapter.calculateEndDate({startDate:t.predecessor.startDate,durationHours:e,task:t.lagTask});return t.adapter.getClosestWorkTime({date:n,dir:"future",task:t.successor})}function mo(t){let e=xw(t);if(e!==null)return e;let n=Mw(t);if(n!==null)return n;let r=t.link.type===q.FINISH_TO_FINISH&&Wr(t.link)&&t.lagTask!==null&&t.lagTask.id!==t.successor.id?Uw(t):Is(t.successor,t.predecessor,t.link,t.adapter,t.lagTask);return Bw(t)?jw(r,t.lagTask,t.adapter):r}function xw(t){let e=t.link._trueLag??t.link.lag??0;if(t.link.type!==q.START_TO_FINISH||!Wr(t.link)||t.lagTask!==null||e<=0)return null;let n=jn(t.successor.endDate,-e);return t.adapter.calculateEndDate({startDate:n,durationHours:t.predecessor.durationHours,task:t.predecessor})}function Mw(t){let e=t.link._trueLag??t.link.lag??0,n=t.adapter.isWorkTime?.({date:t.successor.startDate,task:t.predecessor});return t.link.type!==q.FINISH_TO_START||!Wr(t.link)||t.predecessor.p6?.activityType!=="finish_milestone"||e!==0||t.lagTask!==null||n!==!1?null:t.adapter.getClosestWorkTime({date:t.successor.startDate,dir:"past",task:t.predecessor})}function Wr(t){return t._sourceLag===void 0&&t._targetLag===void 0}function Uw(t){let e=t.link._trueLag??t.link.lag??0;if(t.lagTask===null)return jn(t.successor.endDate,-e);let n=t.adapter.getClosestWorkTime({date:t.successor.endDate,dir:"past",task:t.lagTask});return t.adapter.calculateEndDate({startDate:n,durationHours:-e,task:t.lagTask})}function Hw(t){let e=t.link.type===q.FINISH_TO_START||t.link.type===q.FINISH_TO_FINISH,n=(t.link.lag??0)===0&&(t.link._sourceLag??0)===0&&(t.link._targetLag??0)===0;return t.successor.durationHours===0&&e&&n}function Bw(t){return t.link.type===q.FINISH_TO_FINISH&&(t.link._trueLag??t.link.lag??0)>0&&t.lagTask!==null}function jw(t,e,n){if(e===null)return t;let r=xa(t),i=n.getClosestWorkTime({date:r,dir:"future",task:e}),a=Vf(r,i);return i.getTime()>r.getTime()&&a<=bw?i:t}function gS(t){let e=Zw(t.links),n={...t,projectEarlyFinish:$w(t.activities)};for(let r of[...t.orderedIds].reverse())Vw(r,e.get(r)??[],n)}function Vw(t,e,n){let r=n.adapter.getActivity(t),i=n.activities.get(t);if(!Jw(r)||i===void 0)return;let a=Xw(r,i),o=qw(a,e,n);if(!Yw(i,o))return;let s=Gw(a,o,n.adapter),l={...i,...s};n.activities.set(t,l),Ww(a,l,e,n)}function Ww(t,e,n,r){let i=mS(t,e);for(let a of n){let o=r.adapter.getActivity(a.target),s=r.activities.get(a.target);if(o?.p6?.activityType!=="level_of_effort"||!s)continue;let l=mS(o,s),c=zl({predecessor:i,successor:l,link:a,adapter:r.adapter,lagTask:r.resolveLagTask(i,l)});s.earlyStart!==null&&c<=s.earlyStart||r.activities.set(a.target,Kw(s,l,c,r.adapter))}}function Kw(t,e,n,r){let i=r.calculateEndDate({startDate:n,durationHours:t.scheduledRemainingDurationHours,task:e});return{...t,remainingEarlyStart:n,remainingEarlyFinish:i,earlyStart:new Date(n),earlyFinish:new Date(i)}}function mS(t,e){return{...t,startDate:e.remainingEarlyStart??e.earlyStart??t.startDate,endDate:e.remainingEarlyFinish??e.earlyFinish??t.endDate,durationHours:e.scheduledRemainingDurationHours}}function Yw(t,e){return e!==null&&t.remainingEarlyFinish!==null&&e>t.remainingEarlyFinish}function Gw(t,e,n){let r=n.calculateEndDate({startDate:e,durationHours:-t.durationHours,task:t}),i=n.calculateEndDate({startDate:r,durationHours:t.durationHours,task:t});return{remainingEarlyStart:r,remainingEarlyFinish:i,earlyStart:new Date(r),earlyFinish:new Date(i)}}function qw(t,e,n){let r=null;for(let i of e){let a=zw(i.target,n);if(a===null)continue;let o=mo({successor:a,predecessor:t,link:i,adapter:n.adapter,lagTask:n.resolveLagTask(t,a)});(r===null||o<r)&&(r=o)}return r??n.projectEarlyFinish}function $w(t){let e=null;for(let n of t.values()){let r=n.remainingEarlyFinish??n.earlyFinish;r!==null&&(e===null||r>e)&&(e=r)}return e}function zw(t,e){let n=e.adapter.getActivity(t),r=e.activities.get(t);if(n?.p6===void 0||n.p6.activityType==="level_of_effort"||r===void 0)return null;let i=r.remainingEarlyStart??r.earlyStart,a=r.remainingEarlyFinish??r.earlyFinish;return i===null||a===null?null:{...n,startDate:i,endDate:a,durationHours:r.scheduledRemainingDurationHours}}function Jw(t){return t?.p6?.executionStatus==="not_started"&&t.p6.primaryConstraintType==="alap"}function Xw(t,e){return{...t,durationHours:e.scheduledRemainingDurationHours}}function Zw(t){let e=new Map;for(let n of t){let r=e.get(n.source)??[];r.push(n),e.set(n.source,r)}return e}var er="CS_MSO",$u="CS_MEO";function An(t){return t?.p6?.primaryConstraintType==="mandatory_start"&&t.p6.sourcePrimaryConstraintToken!==er}function In(t){return t?.p6?.primaryConstraintType==="mandatory_finish"&&t.p6.sourcePrimaryConstraintToken!==$u}var Qw=60*1e3,tx=3600*1e3,ex=64;function CS(t){let{adapter:e,settings:n}=t;if(n.dataDate===null)throw new Error("P6 forward pass requires Data Date");let r=e.getAllActivities().filter(p=>p.p6!==void 0&&p.p6.activityType!=="wbs_summary").map(p=>p.id),i=new Set(r),a=e.getAllLinks().filter(p=>i.has(p.source)&&i.has(p.target)).filter(p=>{let y=e.getActivity(p.source),f=e.getActivity(p.target);return n.outOfSequencePolicy!=="progress_override"&&nx(y)?!1:f?.p6!==void 0&&$l({outOfSequencePolicy:n.outOfSequencePolicy,successorExecution:gn(f.p6).execution,linkType:p.type})}),o=a.filter(p=>{let y=e.getActivity(p.target);return y?.p6!==void 0&&gn(y.p6).execution!=="completed"}),s=Bn(r,o);if(s.hasCycles)return{activities:new Map,cycles:s.cycleNodes};let l=px(a),c=Ju(n,e),d=new Map,u=new Set;for(let p of s.ordered){let y=e.getActivity(p);if(y?.p6===void 0)continue;let f=gn(y.p6);if(f.execution==="completed"){let M=n.outOfSequencePolicy==="actual_dates";M&&u.add(p);let $=n.outOfSequencePolicy==="retained_logic"&&y.p6.activityType!=="level_of_effort"?new Date(n.dataDate):null,st=M?y.p6.actualStart:$,at=M?y.p6.actualFinish:$;d.set(p,{activityId:p,scheduledRemainingDurationHours:0,remainingEarlyStart:null,remainingEarlyFinish:null,earlyStart:vS(st),earlyFinish:vS(at),drivingLinkId:null});continue}let m=[...l.get(p)??[]].sort((M,$)=>M.source.localeCompare($.source)||M.id.localeCompare($.id)),A=yx(y),g=AS({successor:A,incomingLinks:m,activities:d,settings:n,adapter:e,resolveLagTask:c}),R=SS({activity:A,earliestStart:g.earliestStart,settings:n,adapter:e}),P=0;for(;!Object.is(A.durationHours,R)&&P<ex;)A={...A,durationHours:R},g=AS({successor:A,incomingLinks:m,activities:d,settings:n,adapter:e,resolveLagTask:c}),R=SS({activity:A,earliestStart:g.earliestStart,settings:n,adapter:e}),P+=1;if(!Object.is(A.durationHours,R))throw new Error(`P6_EXPECTED_FINISH_DID_NOT_SETTLE: ${String(p)}`);let{earliestStart:N,drivingLinkId:T,drivingLinkIds:x}=g,S=qu(e,A,N),k=f.execution==="in_progress"?{earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null}:cx(A,e),F=ax({activity:A,bounds:k,settings:n,adapter:e}),U={activityId:p,startDate:S?.start??N,endDate:S?.finish??e.calculateEndDate({startDate:N,durationHours:R,task:A}),drivingLinkId:T,kind:"asap",conflict:!1,earliestStart:F.earliestStart,latestStart:F.latestStart,earliestEnd:F.earliestEnd,latestEnd:F.latestEnd,earliestSchedulingStart:S?.start??N};if(vi(A,U,e),S!==null){let M=qu(e,A,U.startDate);M!==null&&(U.startDate=M.start,U.endDate=M.finish)}let w=U.startDate.getTime()===N.getTime();d.set(p,{activityId:p,scheduledRemainingDurationHours:R,remainingEarlyStart:new Date(U.startDate),remainingEarlyFinish:new Date(U.endDate),earlyStart:new Date(U.startDate),earlyFinish:new Date(U.endDate),drivingLinkId:w?T:null,drivingLinkIds:w?x:[]})}gS({adapter:e,orderedIds:s.ordered,links:a,activities:d,resolveLagTask:c});for(let p of u){let y=d.get(p);d.set(p,{...y,earlyStart:null,earlyFinish:null})}return{activities:d,cycles:[]}}function nx(t){return t?.p6?.activityType==="level_of_effort"&&t.p6.executionStatus==="not_started"&&t.p6.remainingDurationHours===0}function AS(t){let{successor:e,incomingLinks:n,activities:r,settings:i,adapter:a,resolveLagTask:o}=t,s=a.getClosestWorkTime({date:new Date(i.dataDate),dir:"future",task:e}),l=e.p6?.resumeDate??null;l!==null&&l.getTime()>s.getTime()&&(s=a.getClosestWorkTime({date:new Date(l),dir:"future",task:e}));let c=null,d=[];for(let u of n){let p=a.getActivity(u.source),y=r.get(u.source);if(p?.p6===void 0||y===void 0)continue;let f=y.remainingEarlyStart??y.earlyStart,m=y.remainingEarlyFinish??y.earlyFinish;if(f===null||m===null)continue;let A=rx({link:u,predecessor:p,predecessorDates:y,successor:e,settings:i}),g=fx(u,p,y,i),R={...p,startDate:g,endDate:m,durationHours:a.calculateDuration({startDate:g,endDate:m,task:p})},P=A??zl({predecessor:R,successor:e,link:u,adapter:a,lagTask:o(R,e)}),N=u.type==="0"&&e.durationHours===0&&e.type!=="milestone"?ix(e,P,a):P;N>s?(s=N,c=u.id,d=[u.id]):d.length>0&&N.getTime()===s.getTime()&&d.push(u.id)}return{earliestStart:s,drivingLinkId:c,drivingLinkIds:d}}function DS(t){return t.p6?.activityType==="task"&&t.p6.executionStatus==="not_started"&&t.p6.originalDurationHours===0}function rx(t){let e=t.settings.outOfSequencePolicy==="retained_logic"&&t.settings.startToStartLagBasis==="early_start"&&t.link.type==="1"&&t.predecessor.p6?.executionStatus==="in_progress"&&t.predecessor.p6?.actualStart!==null&&DS(t.successor),n=t.predecessorDates.remainingEarlyStart??t.predecessorDates.earlyStart;return e&&n!==null?new Date(n):null}function ix(t,e,n){if(t.p6?.activityType==="level_of_effort")return e;let r=xa(e),i=n.getClosestWorkTime({date:r,dir:"future",task:t});if(!DS(t))return i;let a=new Date(e.getTime()+Qw);if(n.isWorkTime?.({date:a,task:t}))return e;if(n.isWorkTime===void 0)return i.getTime()===r.getTime()?e:i;let o=new Date(e.getTime()+tx);return n.getClosestWorkTime({date:o,dir:"future",task:t})}function ax(t){let{activity:e,bounds:n,settings:r,adapter:i}=t,a=An(e);if(ox(t,a)){let s=sx(t,a);return{...n,earliestStart:s,latestStart:s}}let o=In(e);if(lx(t,o)){let s=r.dataDate;if(s===null)return n;let l=o?i.getClosestWorkTime({date:s,dir:"future",task:e}):s;return{...n,earliestStart:l,latestStart:l,latestEnd:null}}return e.constraintType==="mfo"?n:{...n,latestStart:null,latestEnd:null}}function ox(t,e){let{activity:n,bounds:r,settings:i}=t;return n.p6?.executionStatus!=="not_started"?!1:e?!0:n.constraintType!=="mso"?!1:i.outOfSequencePolicy!=="retained_logic"?!0:r.earliestStart!==null&&i.dataDate!==null&&r.earliestStart>=i.dataDate}function sx(t,e){let{activity:n,bounds:r,settings:i,adapter:a}=t,o=zu(r.earliestStart,i.dataDate);return!e||o===null?i.outOfSequencePolicy==="retained_logic"?r.earliestStart:o:a.getClosestWorkTime({date:o,dir:"future",task:n})}function lx(t,e){let{activity:n,bounds:r,settings:i}=t;return n.p6?.executionStatus!=="not_started"||r.latestStart===null||i.dataDate===null||r.latestStart>=i.dataDate?!1:e||n.constraintType==="mfo"&&i.outOfSequencePolicy==="actual_dates"}function cx(t,e){let n=dx(t,e),r=t.p6?.secondaryConstraintType??null,i=t.p6?.secondaryConstraintDate??null;if(r===null||i===null)return n;let a=Tn({...t,constraintType:r,constraintDate:i},e);return ux(n,a)}function dx(t,e){let n=t.p6?.primaryConstraintType,r=t.p6?.primaryConstraintDate;return n==null||r===null||r===void 0?Tn(t,e):Tn({...t,constraintType:ts(n),constraintDate:r},e)}function ux(t,e){return{earliestStart:zu(t.earliestStart,e.earliestStart),latestStart:IS(t.latestStart,e.latestStart),earliestEnd:zu(t.earliestEnd,e.earliestEnd),latestEnd:IS(t.latestEnd,e.latestEnd)}}function zu(t,e){return t===null?e:e===null||t>e?t:e}function IS(t,e){return t===null?e:e===null||t<e?t:e}function SS(t){let{activity:e,earliestStart:n,settings:r,adapter:i}=t,a=e.p6?.expectedFinish??null;return!r.useExpectedFinishDates||a===null||e.p6===void 0?e.p6?.remainingDurationHours??e.durationHours:a<=n?0:i.calculateDuration({startDate:n,endDate:a,task:e})}function Ju(t,e){let n=null,r=()=>{if(n??=e.getAllActivities().find(i=>i.type==="project")??null,n===null)throw new Error("P6 schedule requires a project activity for Project Default relationship lag calendar");return n};switch(t.relationshipLagCalendar){case"predecessor":return i=>i;case"successor":return(i,a)=>a;case"project_default":return()=>r();case"twenty_four_hour":return()=>null}}function px(t){let e=new Map;for(let n of t){let r=e.get(n.target)??[];r.push(n),e.set(n.target,r)}return e}function yx(t){return t.p6===void 0?t:{...t,durationHours:t.p6.remainingDurationHours}}function fx(t,e,n,r){return!(t.type==="1"||t.type==="3")||e.p6===void 0?new Date(n.remainingEarlyStart??n.earlyStart??e.startDate):(r.outOfSequencePolicy==="actual_dates"||ho({outOfSequencePolicy:r.outOfSequencePolicy,linkType:t.type,actualStart:e.p6.actualStart})||r.startToStartLagBasis==="actual_start")&&e.p6.actualStart!==null?new Date(e.p6.actualStart):new Date(n.earlyStart??n.remainingEarlyStart??e.startDate)}function vS(t){return t===null?null:new Date(t)}function hx(t,e){let n=t==="start_float"?e.startFloatHours:t==="finish_float"?e.finishFloatHours:Math.min(e.startFloatHours,e.finishFloatHours);return Object.is(n,-0)?0:n}function RS(t){let{adapter:e,settings:n,forward:r}=t,i=[...r.activities.keys()],a=new Set(i),o=e.getAllLinks().filter(g=>a.has(g.source)&&a.has(g.target)),s=o.filter(g=>{let R=e.getActivity(g.source),P=e.getActivity(g.target);return n.outOfSequencePolicy!=="progress_override"&&mx(P)||gx(g,R,P)?!1:P?.p6!==void 0&&$l({outOfSequencePolicy:n.outOfSequencePolicy,successorExecution:gn(P.p6).execution,linkType:g.type})}),l=s.filter(g=>{let R=e.getActivity(g.source);return!(R?.p6?.activityType==="level_of_effort"&&gn(R.p6).execution==="completed")}),c=Bn(i,l);if(c.hasCycles)throw new Error(`P6 backward pass cannot calculate cycles: ${c.cycleNodes.join(", ")}`);let d=Rx(e,r,i),u=n.projectMustFinishBy??d;if(u===null)return{activities:vx(i)};let p=d??u,y=TS(s),f=TS(o),m=Ju(n,e),A=new Map;for(let g of c.reversed){let R=e.getActivity(g),P=r.activities.get(g);if(R?.p6===void 0||P===void 0)continue;let N=Px(R,P.scheduledRemainingDurationHours??R.p6.remainingDurationHours),T=new Date(u);for(let at of y.get(g)??[]){let Ct=e.getActivity(at.target),L=A.get(at.target),K=r.activities.get(at.target);if(Ct?.p6===void 0||L===void 0)continue;let dt=Ex(Ct,L,n,at.type);if(dt===null)continue;let lt={...Ct,startDate:dt.startDate,endDate:dt.endDate,durationHours:K?.scheduledRemainingDurationHours??Ct.p6.remainingDurationHours},X=ho({outOfSequencePolicy:n.outOfSequencePolicy,linkType:at.type,actualStart:R.p6.actualStart})||PS(R,at,n)?{...at,lag:0}:at,v=n.outOfSequencePolicy==="actual_dates"&&at.type==="0"&&Ct.p6.executionStatus==="in_progress"&&Ct.p6.primaryConstraintType==="mandatory_start"&&Ct.p6.sourcePrimaryConstraintToken!==er,O=mo({successor:lt,predecessor:N,link:X,adapter:e,lagTask:v?lt:m(N,lt)});O<T&&(T=O)}if(P.remainingEarlyStart===null||P.remainingEarlyFinish===null){if(n.outOfSequencePolicy!=="retained_logic"||R.p6.activityType==="level_of_effort"){A.set(g,{activityId:g,remainingLateStart:null,remainingLateFinish:null,lateStart:null,lateFinish:null,totalFloatHours:null,freeFloatHours:null,isCritical:!1});continue}A.set(g,{activityId:g,remainingLateStart:null,remainingLateFinish:null,lateStart:new Date(T),lateFinish:new Date(T),totalFloatHours:null,freeFloatHours:null,isCritical:!1});continue}T=kx(N,T,e),N.durationHours===0&&R.p6.activityType!=="level_of_effort"&&kS(R,y.get(g)??[],e,T)&&(T=e.getClosestWorkTime({date:Si(T),dir:"past",task:N}));let x=(f.get(g)??[]).length===0,S=Sx(n,R,x),k=pS(e,N,T),F=k?.start??e.calculateEndDate({startDate:T,durationHours:-N.durationHours,task:N});if(R.p6.activityType==="level_of_effort")F=_x(e,T,N,y.get(g)??[]),N.durationHours===0&&(T=new Date(F));else if(k!==null)T=k.finish;else{let at=n.outOfSequencePolicy==="actual_dates"&&Ix(y.get(g)??[],e)||R.p6.secondaryConstraintType==="fnlt";F=Ax(R,F,at),T=e.calculateEndDate({startDate:F,durationHours:N.durationHours,task:N})}S&&(F=new Date(P.remainingEarlyStart),T=new Date(P.remainingEarlyFinish));let U=Zu(e,P.remainingEarlyStart,F,N),w=Zu(e,P.remainingEarlyFinish,T,N),M=hx(n.totalFloatMethod,{startFloatHours:U,finishFloatHours:w}),$=Cx({activity:R,effectivePredecessor:N,early:P,outgoingLinks:y.get(g)??[],boundary:p,forward:r,settings:n,adapter:e,resolveLagTask:m}),st=n.criticalActivityMethod==="total_float"&&M<=n.criticalFloatThresholdHours||S;A.set(g,{activityId:g,remainingLateStart:new Date(F),remainingLateFinish:new Date(T),lateStart:new Date(F),lateFinish:new Date(T),totalFloatHours:M,freeFloatHours:$,isCritical:st})}return{activities:A}}function mx(t){return t?.p6?.activityType==="level_of_effort"&&t.p6.executionStatus==="not_started"&&t.p6.remainingDurationHours===0}function Xu(t,e,n){return n.isWorkTime?.({date:Si(e),task:t})===!1}function gx(t,e,n){return t.type==="0"&&t.lag===0?!1:e?.p6?.executionStatus==="completed"&&n?.p6?.executionStatus==="completed"}function Ax(t,e,n){let r=t.p6;return n||r?.executionStatus!=="in_progress"||r.primaryConstraintType!=="snet"||r.actualStart===null||e>=r.actualStart?e:new Date(r.actualStart)}function Ix(t,e){return t.some(n=>{let r=e.getActivity(n.target)?.p6;return r?.executionStatus==="in_progress"&&r.primaryConstraintType==="mandatory_start"&&r.sourcePrimaryConstraintToken!==er})}function Sx(t,e,n){return t.makeOpenEndedActivitiesCritical&&n&&e.type!=="milestone"&&t.multipleFloatPaths.endingActivityId!==e.id&&gn(e.p6).execution==="not_started"}function vx(t){return new Map(t.map(e=>[e,{activityId:e,remainingLateStart:null,remainingLateFinish:null,lateStart:null,lateFinish:null,totalFloatHours:null,freeFloatHours:null,isCritical:!1}]))}function Cx(t){let{activity:e,effectivePredecessor:n,early:r,outgoingLinks:i,boundary:a,forward:o,settings:s,adapter:l,resolveLagTask:c}=t;if(r.remainingEarlyStart===null||r.remainingEarlyFinish===null)return null;if(e.p6?.executionStatus==="not_started"&&In(e)&&i.length>0||e.p6?.executionStatus==="not_started"&&An(e)&&Dx(i,l))return 0;let d=null;for(let p of i){if(PS(e,p,s))continue;let y=l.getActivity(p.target),f=o.activities.get(p.target);if(y?.p6===void 0||f===void 0)continue;let m=Tx({successor:y,early:f,settings:s,linkType:p.type});if(m===null)continue;let A={...y,startDate:m.startDate,endDate:m.endDate,durationHours:f.scheduledRemainingDurationHours},g=ho({outOfSequencePolicy:s.outOfSequencePolicy,linkType:p.type,actualStart:e.p6?.actualStart??null})?{...p,lag:0}:p,R=mo({successor:A,predecessor:n,link:g,adapter:l,lagTask:c(n,A)});(d===null||R<d)&&(d=R)}d??=new Date(a),n.durationHours===0&&kS(e,i,l,d)&&(d=l.getClosestWorkTime({date:Si(d),dir:"past",task:n}));let u=Zu(l,r.remainingEarlyFinish,d,n);return Math.max(0,Object.is(u,-0)?0:u)}function Dx(t,e){return t.some(n=>{let r=e.getActivity(n.target)?.p6;return r?.activityType==="task"&&r.executionStatus==="not_started"&&r.originalDurationHours===0})}function PS(t,e,n){return n.outOfSequencePolicy==="progress_override"&&e.type==="1"&&t.p6?.actualStart!==null&&t.p6?.actualStart!==void 0}function Tx(t){let{successor:e,early:n,settings:r,linkType:i}=t,a=n.remainingEarlyStart??n.earlyStart,o=n.remainingEarlyFinish??n.earlyFinish,s=e.p6;return r.outOfSequencePolicy==="actual_dates"&&s!==void 0&&(i==="0"||i==="1"||s.actualFinish!==null)&&(a=s.actualStart??a,o=s.actualFinish??o),a===null||o===null?null:{startDate:new Date(a),endDate:new Date(o)}}function kS(t,e,n,r){if(t.p6?.executionStatus==="completed")return!1;if(t.p6?.activityType==="task"&&t.p6.executionStatus==="not_started"&&t.p6.originalDurationHours===0){let o=Si(r);return n.getClosestWorkTime({date:o,dir:"past",task:t})<o}if(t.p6?.activityType==="start_milestone"&&e.length===0)return Xu(t,r,n);if(e.length===0)return!1;if(t.type!=="milestone")return!0;let i=t.p6?.activityType;if(i!=="start_milestone"&&i!=="finish_milestone")return!1;let a=i==="finish_milestone";return e.every(o=>{let s=n.getActivity(o.target),c=s?.p6?.activityType==="resource_dependent"?s?.calendarId===t.calendarId:s?.calendarId!==t.calendarId&&Xu(t,r,n);return s?.p6!==void 0&&(!a||c)&&gn(s.p6).execution!=="completed"})}function _x(t,e,n,r){if(n.durationHours===0){let o=r.some(s=>{let l=t.getActivity(s.target);return l!==null&&l.calendarId!==n.calendarId})&&Xu(n,e,t)?Si(e):e;return t.getClosestWorkTime({date:o,dir:"past",task:n})}let i=new Date(e);return i.setUTCHours(0,0,0,0),t.getClosestWorkTime({date:i,dir:"future",task:n})}function Ex(t,e,n,r){if(t.p6===void 0)return null;let i=e.remainingLateStart??e.lateStart,a=e.remainingLateFinish??e.lateFinish;if(n.outOfSequencePolicy==="actual_dates"){let o=t.p6.actualStart,s=t.p6.actualFinish;if(r==="0"||r==="1"||s!==null){let l=o??i,c=s??a;return l===null||c===null?null:{startDate:new Date(l),endDate:new Date(c)}}}return i===null||a===null?null:n.outOfSequencePolicy==="actual_dates"?{startDate:new Date(i),endDate:new Date(a)}:{startDate:new Date(i),endDate:new Date(a)}}function Rx(t,e,n){let r=n.filter(o=>t.getActivity(o)?.p6?.executionStatus!=="completed"),i=r.length>0?r:n,a=null;for(let o of i){let s=e.activities.get(o),l=s?.remainingEarlyFinish??s?.earlyFinish;l!=null&&(a===null||l>a)&&(a=l)}return a===null?null:new Date(a)}function TS(t){let e=new Map;for(let n of t){let r=e.get(n.source)??[];r.push(n),e.set(n.source,r)}return e}function Px(t,e=t.p6?.remainingDurationHours??t.durationHours){return t.p6===void 0?t:{...t,durationHours:e}}function kx(t,e,n){let r=t.p6?.primaryConstraintType,i=t.p6?.primaryConstraintDate,a=t.p6?.sourcePrimaryConstraintToken,o=a===$u?"fnlt":a===er?"snlt":r,l=r==="start_on"?{...t,constraintType:null,constraintDate:null}:o!=null&&i!==null&&i!==void 0?_S(t,o,i,n):t,d=t.p6?.actualStart===null||o==="fnlt"||o==="finish_on"?ES(l,e,n):new Date(e);if(t.p6?.secondaryConstraintType===null||t.p6?.secondaryConstraintDate===null||t.p6===void 0||t.p6.actualStart!==null&&t.p6.secondaryConstraintType!=="fnlt")return d;let u=_S(t,t.p6.secondaryConstraintType,t.p6.secondaryConstraintDate,n);return d=ES(u,d,n),new Date(d)}function _S(t,e,n,r){let i=ts(e),a=bx({activity:t,constraintType:i,constraintDate:n,adapter:r});return{...t,constraintType:i,constraintDate:a}}function bx(t){let{activity:e,constraintType:n,constraintDate:r,adapter:i}=t,a=e.p6?.sourcePrimaryConstraintToken===er&&n==="snlt"?"future":Lx(n,r)?"past":null;return a===null?new Date(r):i.getClosestWorkTime({date:r,dir:a,task:e})}function Lx(t,e){return e.getUTCHours()===0&&e.getUTCMinutes()===0&&e.getUTCSeconds()===0&&e.getUTCMilliseconds()===0&&(t==="fnlt"||t==="mfo")}function ES(t,e,n){let r=Tn(t,n);if((t.constraintType==="mso"||t.constraintType==="mfo")&&r.latestEnd!==null)return new Date(r.latestEnd);let i=e;if(r.latestEnd!==null&&r.latestEnd<i&&(i=r.latestEnd),r.latestStart!==null){let a=n.calculateEndDate({startDate:r.latestStart,durationHours:t.durationHours,task:t});a<i&&(i=a)}return t.constraintType==="snet"&&r.earliestEnd!==null&&r.earliestEnd<i&&(i=r.earliestEnd),new Date(i)}function Zu(t,e,n,r){return e<=n?t.calculateDuration({startDate:e,endDate:n,task:r}):-t.calculateDuration({startDate:n,endDate:e,task:r})}var Ox=3600*1e3,bS=["P6_NO_PREDECESSOR","P6_NO_SUCCESSOR","P6_OUT_OF_SEQUENCE","P6_ACTUAL_AFTER_DATA_DATE","P6_INVALID_MILESTONE_RELATIONSHIP"],Nx={P6_NO_PREDECESSOR:"open_ended",P6_NO_SUCCESSOR:"open_ended",P6_OUT_OF_SEQUENCE:"out_of_sequence",P6_ACTUAL_AFTER_DATA_DATE:"actual_after_data_date",P6_INVALID_MILESTONE_RELATIONSHIP:"milestone_relationship",P6_UNSATISFIED_CONSTRAINT:"unsatisfied_constraint"},Fx={0:"finish_to_start",1:"start_to_start",2:"finish_to_finish",3:"start_to_finish"};function wS(t){let{adapter:e,dataDate:n,project:r,outOfSequencePolicy:i}=t;Vx(i);let a=e.getAllActivities().filter(Qu).sort(US),o=new Map;for(let s of bS)o.set(s,[]);for(let s of a){e.getIncomingLinkIds(s.id).length===0&&go(o,ea(s,r,n,{code:"P6_NO_PREDECESSOR",rule:"activity_has_no_predecessor"})),e.getOutgoingLinkIds(s.id).length===0&&go(o,ea(s,r,n,{code:"P6_NO_SUCCESSOR",rule:"activity_has_no_successor"})),xx(s,n)&&go(o,ea(s,r,n,{code:"P6_ACTUAL_AFTER_DATA_DATE",rule:"actual_date_is_after_data_date"}));let l=Mx(e,s);l!==null&&go(o,ea(s,r,n,{code:"P6_INVALID_MILESTONE_RELATIONSHIP",rule:"milestone_endpoint_is_not_available",relationship:OS(e,l)}))}for(let s of jx(e.getAllLinks())){if(!Ux(e,s))continue;let l=e.getActivity(s.target);l===null||!Qu(l)||go(o,ea(l,r,n,{code:"P6_OUT_OF_SEQUENCE",rule:"successor_progress_precedes_required_logic",relationship:OS(e,s)}))}return bS.flatMap(s=>o.get(s)??[])}function xS(t){let e=[],n=t.adapter.getAllActivities().filter(Qu).sort(US);for(let r of n){let i=t.calculated.get(r.id);i===void 0||i.actualFinish!==null||wx(r,i)&&e.push(ea({...r,p6:i},t.project,t.dataDate,{code:"P6_UNSATISFIED_CONSTRAINT",rule:"constraint_could_not_be_satisfied"}))}return e}function wx(t,e){let n=t.constraintDate??null,r=t.constraintType??null;if(n===null||r===null)return!1;let i=n.getTime(),a=e.remainingEarlyStart??e.earlyStart,o=e.remainingEarlyFinish??e.earlyFinish;switch(r){case _.MSO:return a!==null&&a.getTime()!==i;case _.MFO:return o!==null&&o.getTime()!==i;case _.SNET:return a!==null&&a.getTime()<i;case _.FNET:return o!==null&&o.getTime()<i;case _.SNLT:return a!==null&&a.getTime()>i;case _.FNLT:return o!==null&&o.getTime()>i;default:return!1}}function ea(t,e,n,r){return{kind:"diagnostic",code:r.code,category:Nx[r.code],severity:"warning",project:{...e},activityId:t.id,activityCode:t.customId??t.id,activityName:t.name,activityStatus:t.p6.executionStatus,dataDate:new Date(n),dates:{actualStart:FS(t.p6.actualStart),actualFinish:FS(t.p6.actualFinish)},relationship:r.relationship??null,explanation:{rule:r.rule}}}function go(t,e){t.get(e.code).push(e)}function xx(t,e){let n=t.p6;return n!==void 0&&(NS(n.actualStart,e)||NS(n.actualFinish,e))}function Mx(t,e){return e.p6?.activityType==="start_milestone"?LS(t,e,"incoming",n=>n.type==="2"||n.type==="3"):e.p6?.activityType==="finish_milestone"?LS(t,e,"outgoing",n=>n.type==="1"||n.type==="3"):null}function LS(t,e,n,r){return(n==="incoming"?t.getIncomingLinkIds(e.id):t.getOutgoingLinkIds(e.id)).map(a=>t.getLink(a)).filter(a=>a!==null).sort(MS).find(r)??null}function Ux(t,e){let n=t.getActivity(e.source),r=t.getActivity(e.target);if(n?.p6===void 0||r?.p6===void 0)return!1;let i=Bx(r,e.type);if(i===null)return!1;let a=Hx(n,e.type);return a===null?!0:i.getTime()<a.getTime()+e.lag*Ox}function Hx(t,e){return t.p6===void 0?null:e==="1"||e==="3"?t.p6.actualStart:t.p6.actualFinish}function Bx(t,e){return t.p6===void 0?null:e==="0"||e==="1"?t.p6.actualStart:t.p6.actualFinish}function OS(t,e){let n=t.getActivity(e.source),r=t.getActivity(e.target);return{id:e.id,predecessorActivityId:e.source,predecessorActivityCode:n===null?null:n.customId??n.id,successorActivityId:e.target,successorActivityCode:r===null?null:r.customId??r.id,type:Fx[e.type],lagHours:e.lag}}function jx(t){return[...t].sort(MS)}function MS(t,e){return String(t.id).localeCompare(String(e.id))}function US(t,e){let n=t.correlativeId-e.correlativeId;return n!==0?n:(t.customId??String(t.id)).localeCompare(e.customId??String(e.id))}function NS(t,e){return t!==null&&t.getTime()>e.getTime()}function FS(t){return t===null?null:new Date(t)}function Qu(t){return t.p6!==void 0}function Vx(t){if(t!=="retained_logic"&&t!=="progress_override"&&t!=="actual_dates")throw new Error(`Unsupported P6 out-of-sequence policy: ${String(t)}`)}function Kr(t){let e=null;for(let n of t){if(n===null)continue;let r=n.getTime();(e===null||r<e)&&(e=r)}return e===null?null:new Date(e)}function nr(t){let e=null;for(let n of t){if(n===null)continue;let r=n.getTime();(e===null||r>e)&&(e=r)}return e===null?null:new Date(e)}function tp(t){let e=null;for(let n of t)n!==null&&(e===null||n<e)&&(e=n);return e}function Ao(t){let e=0;for(let n of t)e+=n;return e}function BS(t){let{adapter:e,settings:n,forward:r,backward:i}=t,a=new Map;for(let u of i.activities.keys())a.set(u,{longestPath:!1,floatPath:null,floatPathOrder:null});let o=iM(r);for(let u of o)oM(u,e,r,a,n);if(!n.multipleFloatPaths.enabled)return{activities:a};let s=aM(n,r,o);if(s===null)return{activities:a};let l=n.multipleFloatPaths.limitEnabled?n.multipleFloatPaths.maximum:Number.POSITIVE_INFINITY,c={emittedPaths:0,numberingBudget:n.multipleFloatPaths.limitEnabled?n.multipleFloatPaths.maximum:Number.POSITIVE_INFINITY,numberableActivityIds:Qx(e,r,n),activities:a},d=Yx({adapter:e,backward:i,settings:n,endingActivityId:s,state:c});if(!d&&n.multipleFloatPaths.useTotalFloat)cM(s,e,r,i,n,l,c);else if(!d){let u=yM(s,e,r,n);Xl(n)&&(na(u[0]??[],c),Wx({adapter:e,backward:i,settings:n,state:c}));let p=Xl(n)?u.slice(1):u;for(let y of p)na(y,c)}return n.multipleFloatPaths.limitEnabled&&!d&&(n.multipleFloatPaths.useTotalFloat?gM(e,r,i,n,c):fM(e,r,n,c)),d||IM(n,i,c.activities,e),{activities:a}}function Wx(t){let{adapter:e,backward:n,settings:r,state:i}=t,a=[...i.numberableActivityIds].filter(o=>Kx(e.getActivity(o))).sort((o,s)=>{let l=n.activities.get(o)?.freeFloatHours??1/0,c=n.activities.get(s)?.freeFloatHours??1/0;return l-c||np(o,s,e,r)});for(let o of a)na([o],i)}function Kx(t){if(t?.p6?.executionStatus!=="in_progress")return!1;let e=t.p6.primaryConstraintType;return e==="alap"||e==="mandatory_start"||e==="start_on"||e==="snet"||e==="snlt"}function Yx(t){if(!qx(t.settings))return!1;let e=$x(t.adapter,t.state);if(e===null||e.length===0||e.length!==t.state.numberingBudget||e.some((r,i)=>r[0].path!==i+1))return!1;let n=Xx(t.endingActivityId,t.adapter);if(e.some(r=>!zx(r,t,n))||Gx(e,t))return!1;for(let r of e)Zx(r,t.state);return!0}function Gx(t,e){if(!e.settings.multipleFloatPaths.useTotalFloat)return[...e.state.numberableActivityIds].some(i=>!jS(i,e));let n=new Set(t.flat().map(i=>i.id)),r=Math.max(...t.map(i=>Math.min(...i.map(a=>e.backward.activities.get(a.id)?.totalFloatHours??1/0))));return[...e.state.numberableActivityIds].some(i=>{if(n.has(i))return!1;let a=e.backward.activities.get(i)?.totalFloatHours;return a!=null&&a<=r})}function qx(t){return t.multipleFloatPaths.limitEnabled&&(t.outOfSequencePolicy==="actual_dates"&&t.multipleFloatPaths.useTotalFloat||t.outOfSequencePolicy==="retained_logic"&&!t.multipleFloatPaths.useTotalFloat&&t.multipleFloatPaths.endingActivityId!==null)}function $x(t,e){let n=[...e.numberableActivityIds].map(a=>{let o=t.getActivity(a)?.p6;return{id:a,path:o?.floatPath,order:o?.floatPathOrder}});if(n.some(a=>a.path===null!=(a.order===null)))return null;let r=n.filter(a=>typeof a.path=="number"&&typeof a.order=="number"),i=new Map;for(let a of r){let o=i.get(a.path);o===void 0?i.set(a.path,[a]):o.push(a)}return[...i].sort(([a],[o])=>a-o).map(([,a])=>a.sort((o,s)=>o.order-s.order))}function zx(t,e,n){return t.length===0||t[0].path>e.state.numberingBudget||t.some((r,i)=>r.order!==i+1)||t.some(r=>!jS(r.id,e))||t.slice(1).some((r,i)=>Jx(t[i].id,r.id,e.adapter).length===0)?!1:n.has(t.at(-1).id)}function jS(t,e){let n=e.adapter.getActivity(t)?.p6,r=e.backward.activities.get(t),i=e.settings.multipleFloatPaths.useTotalFloat,a=i?n?.remainingFloatHours:n?.freeFloatHours,o=i?r?.totalFloatHours:r?.freeFloatHours;return a!=null&&a===o}function Jx(t,e,n){return n.getOutgoingLinkIds(t).map(r=>n.getLink(r)).filter(r=>r?.target===e)}function Xx(t,e){let n=[t],r=new Set;for(;n.length>0;){let i=n.pop();if(!r.has(i)){r.add(i);for(let a of e.getIncomingLinkIds(i)){let o=e.getLink(a)?.source;o!==void 0&&n.push(o)}}}return r}function Zx(t,e){for(let n of t){let r=e.activities.get(n.id);e.activities.set(n.id,{...r,floatPath:n.path,floatPathOrder:n.order})}}function Qx(t,e,n){return new Set([...e.activities.keys()].filter(r=>tM(t.getActivity(r),n)))}function tM(t,e){return t?.p6?.executionStatus==="completed"?!1:eM(e)?An(t)?!1:t?.p6?.executionStatus==="in_progress"?t.p6.primaryConstraintType!==null:!0:e.multipleFloatPaths.useTotalFloat?!GS(t):e.outOfSequencePolicy!=="progress_override"?!0:Xl(e)?t?.p6?.executionStatus==="not_started"||nM(t):t?.p6?.executionStatus==="not_started"&&!rM(t)}function eM(t){return t.multipleFloatPaths.useTotalFloat&&t.outOfSequencePolicy==="progress_override"}function nM(t){return t?.p6?.executionStatus==="in_progress"&&t.p6.primaryConstraintType!==null&&t.p6.primaryConstraintType!==void 0}function Xl(t){return t.outOfSequencePolicy==="progress_override"&&!t.multipleFloatPaths.useTotalFloat&&t.multipleFloatPaths.endingActivityId!==null}function rM(t){return An(t)||In(t)}function na(t,e){if(!t.some(i=>e.activities.get(i)?.floatPath===null&&e.numberableActivityIds.has(i))||(e.emittedPaths+=1,e.emittedPaths>e.numberingBudget))return;let r=0;for(let i=t.length-1;i>=0;i--){let a=t[i],o=e.activities.get(a);o===void 0||o.floatPath!==null||!e.numberableActivityIds.has(a)||(r+=1,e.activities.set(a,{...o,floatPath:e.emittedPaths,floatPathOrder:r}))}}function iM(t){let e=[...t.activities].filter(([,r])=>r.earlyFinish!==null),n=e.reduce((r,[,i])=>Math.max(r,i.earlyFinish.getTime()),Number.NEGATIVE_INFINITY);return e.filter(([,r])=>r.earlyFinish.getTime()===n).map(([r])=>r).sort((r,i)=>r.localeCompare(i))}function aM(t,e,n){let r=t.multipleFloatPaths.endingActivityId;return r!==null&&e.activities.has(r)?r:n[0]??null}function oM(t,e,n,r,i){let a=[t],o=new Set;for(;a.length>0;){let s=a.pop();if(o.has(s))continue;o.add(s);let l=r.get(s);l!==void 0&&r.set(s,{...l,longestPath:!0}),a.push(...VS(s,e,n,i))}}function VS(t,e,n,r){let i=e.getActivity(t),a=n.activities.get(t),o=a?.drivingLinkIds??(a?.drivingLinkId===null||a?.drivingLinkId===void 0?[]:[a.drivingLinkId]),s=i?.p6?.primaryConstraintType==="alap"&&r.outOfSequencePolicy==="retained_logic"?o.filter(y=>e.getLink(y)?.type==="2"):[],l=sM(i,r);if(An(i)||In(i)||l&&s.length===0)return[];let c=l?s:o;if(c.length>0)return c.map(y=>e.getLink(y)?.source??null).filter(y=>y!==null);let d=e.getIncomingLinkIds(t).map(y=>e.getLink(y)).filter(y=>y!==null).sort((y,f)=>y.source.localeCompare(f.source)),u=d.filter(y=>lM(y,n.activities.get(y.source),a)).map(y=>y.source);if(u.length>0)return u;let p=r.outOfSequencePolicy==="actual_dates"?d.find(y=>{if(y.type!=="0")return!1;let f=e.getActivity(t),m=e.getActivity(y.source);return f?.p6?.executionStatus==="completed"||m?.p6?.executionStatus==="completed"}):void 0;return p===void 0?[]:[p.source]}function sM(t,e){return e.outOfSequencePolicy==="progress_override"&&t?.p6?.primaryConstraintType==="alap"?!1:KS(t)}function lM(t,e,n){return t.lag!==0||e===void 0||n===void 0?!1:t.type==="0"?Jl(e.earlyFinish,n.earlyStart):t.type==="1"?Jl(e.earlyStart,n.earlyStart):t.type==="2"?Jl(e.earlyFinish,n.earlyFinish):Jl(e.earlyStart,n.earlyFinish)}function Jl(t,e){return t!==null&&e!==null&&t.getTime()===e.getTime()}function cM(t,e,n,r,i,a,o){let s=F=>o.numberableActivityIds.has(F.source)&&o.numberableActivityIds.has(F.target)&&!WS(F.target,e,i)&&!YS(F.source,e,i),l=new Map,c=F=>{let U=l.get(F);if(U!==void 0)return U;let w=qS(F,e,n,r,i,s);return l.set(F,w),w},d=uM(t,e,s),u=Bn(d.activityIds,d.links);if(u.hasCycles){dM(t,c,a,o);return}let p=pM(u.ordered,d.links),y=[],f=[],m=new Set,A=new Set,g=0n,R=o.numberingBudget,P=R!==Number.POSITIVE_INFINITY,N=P?BigInt(R):0n,T=a!==Number.POSITIVE_INFINITY,x=T?BigInt(a):0n,S=()=>{g+=1n,!(P&&g>N)&&HS(f,Number(g),o)},k=F=>{if(m.has(F))return;if(A.has(F)){let w=p.get(F);if(w===void 0)throw new Error(`P6 float path count missing for activity ${String(F)}`);let M=g+1n;(!P||M<=N)&&HS(f,Number(M),o),g+=w;return}A.add(F),f.push(F),m.add(F);let U=c(F);if(U.length===0){S(),f.pop(),m.delete(F);return}y.push({links:U,nextIndex:0})};for(k(t);y.length>0&&(!T||g<x);){let F=y[y.length-1];if(F.nextIndex<F.links.length){let U=F.links[F.nextIndex];F.nextIndex+=1,k(U.source);continue}y.pop(),m.delete(f.pop())}o.emittedPaths=Number(g>BigInt(Number.MAX_SAFE_INTEGER)?BigInt(Number.MAX_SAFE_INTEGER):g)}function WS(t,e,n){let r=e.getActivity(t);return n.outOfSequencePolicy==="progress_override"&&n.multipleFloatPaths.useTotalFloat&&r?.p6?.executionStatus==="in_progress"?r.p6.primaryConstraintType!==null:KS(r)}function KS(t){if(t?.p6?.executionStatus!=="not_started")return!1;let e=t?.p6?.primaryConstraintType;return e==="alap"||e==="start_on"||An(t)}function YS(t,e,n){let r=e.getActivity(t);return n.outOfSequencePolicy==="progress_override"&&n.multipleFloatPaths.useTotalFloat&&r?.p6?.executionStatus==="in_progress"&&r.p6.primaryConstraintType!==null?!0:GS(r)}function GS(t){return t?.p6?.executionStatus==="not_started"&&In(t)}function dM(t,e,n,r){let i=[],a=[],o=new Set,s=l=>{if(o.has(l))return;a.push(l),o.add(l);let c=e(l);if(c.length===0){na(a,r),a.pop(),o.delete(l);return}i.push({links:c,nextIndex:0})};for(s(t);i.length>0&&r.emittedPaths<n;){let l=i[i.length-1];if(l.nextIndex<l.links.length){let c=l.links[l.nextIndex];l.nextIndex+=1,s(c.source);continue}i.pop(),o.delete(a.pop())}}function HS(t,e,n){let r=0;for(let i=t.length-1;i>=0;i--){let a=t[i],o=n.activities.get(a);o===void 0||o.floatPath!==null||!n.numberableActivityIds.has(a)||(r+=1,n.activities.set(a,{...o,floatPath:e,floatPathOrder:r}))}}function uM(t,e,n){let r=new Set([t]),i=[t],a=[],o=[t];for(;o.length>0;){let s=o.pop(),l=e.getIncomingLinkIds(s).map(c=>e.getLink(c)).filter(c=>c!==null&&n(c));for(let c of l)a.push(c),r.has(c.source)||(r.add(c.source),i.push(c.source),o.push(c.source))}return{activityIds:i,links:a}}function pM(t,e){let n=new Map;for(let i of e){let a=n.get(i.target);a===void 0?n.set(i.target,[i]):a.push(i)}let r=new Map;for(let i of t){let a=n.get(i);if(a===void 0||a.length===0){r.set(i,1n);continue}let o=0n;for(let s of a){let l=r.get(s.source);if(l===void 0)throw new Error(`P6 float path count missing for activity ${String(s.source)}`);o+=l}r.set(i,o)}return r}function qS(t,e,n,r,i,a){let o=n.activities.get(t)?.drivingLinkId;return e.getIncomingLinkIds(t).map(s=>e.getLink(s)).filter(s=>s!==null&&a(s)).sort((s,l)=>{let c=s.id===o?0:1,d=l.id===o?0:1;if(c!==d)return c-d;let u=r.activities.get(s.source)?.totalFloatHours??1/0,p=r.activities.get(l.source)?.totalFloatHours??1/0;return u-p||np(l.source,s.source,e,i)||l.id.localeCompare(s.id)})}function np(t,e,n,r){let i=n.getActivity(t),a=n.getActivity(e);if(r.dependencyReference==="custom_id")return(i?.customId??t).localeCompare(a?.customId??e);let o=i?.correlativeId,s=a?.correlativeId;return o!==void 0&&s!==void 0&&o!==s?o-s:t.localeCompare(e)}function yM(t,e,n,r){let i=[],a=new Set,o=[t];for(let s=o.pop();s!==void 0;s=o.pop()){let l=[],c=s;for(;c!==null&&!a.has(c)&&e.getActivity(c)?.p6?.executionStatus!=="completed";)a.add(c),l.push(c),c=Zl(c,e,r)?null:ep(c,e,n,r);if(l.length===0)continue;i.push(l);let d=[...l].reverse().flatMap(u=>{let p=Zl(u,e,r)?null:ep(u,e,n,r);return e.getIncomingLinkIds(u).map(y=>e.getLink(y)).filter(y=>y!==null&&y.source!==p).sort((y,f)=>f.source.localeCompare(y.source)||f.id.localeCompare(y.id))});for(let u of d)o.push(u.source)}return i}function Zl(t,e,n){let r=e.getActivity(t)?.p6;return Xl(n)?r?.executionStatus==="in_progress"&&r.primaryConstraintType!==null:r?.executionStatus!=="not_started"?!1:r?.primaryConstraintType==="alap"||r?.primaryConstraintType==="start_on"||r?.sourcePrimaryConstraintToken===er}function fM(t,e,n,r){let i=new Set([...r.activities].filter(([,o])=>o.floatPath!==null).map(([o])=>o)),a=[...e.activities.keys()].filter(o=>!i.has(o)&&hM(o,t)&&mM(o,t,n)).sort((o,s)=>o.localeCompare(s));for(let o of a){let s=[],l=o;for(;l!==null&&!i.has(l);)i.add(l),s.push(l),l=Zl(l,t,n)?null:ep(l,t,e,n);s.length>0&&na(s,r)}}function hM(t,e){return e.getIncomingLinkIds(t).length>0||e.getOutgoingLinkIds(t).length>0}function mM(t,e,n){return!e.getOutgoingLinkIds(t).map(r=>e.getLink(r)).some(r=>r!==null&&!Zl(r.target,e,n))}function gM(t,e,n,r,i){i.emittedPaths=SM(i.activities);let a=vM(i),o=d=>i.numberableActivityIds.has(d.source)&&i.numberableActivityIds.has(d.target)&&!WS(d.target,t,r)&&!YS(d.source,t,r),s=d=>o(d)&&a.has(d.source)&&a.has(d.target),l=[...a].filter(d=>CM(d,t,o)).sort((d,u)=>DM(d,u,t,n,r)),c=new Set;for(let d of l){let u=TM(d,t,e,n,r,s,c);na(u,i)}}function AM(t,e,n,r){let i=new Map,a=new Set;for(let[s,l]of n){if(l.floatPath===null)continue;let c=e.activities.get(s)?.totalFloatHours??1/0,d=i.get(l.floatPath)??1/0;i.set(l.floatPath,Math.min(d,c)),In(r.getActivity(s))&&a.add(l.floatPath)}let o=new Map([...i].sort(([s,l],[c,d])=>l-d||(t.outOfSequencePolicy==="progress_override"?+!a.has(s)-+!a.has(c):0)||s-c).map(([s],l)=>[s,l+1]));for(let[s,l]of n)l.floatPath!==null&&n.set(s,{...l,floatPath:o.get(l.floatPath)})}function IM(t,e,n,r){!t.multipleFloatPaths.useTotalFloat||!t.multipleFloatPaths.limitEnabled||AM(t,e,n,r)}function SM(t){return Math.max(0,...[...t.values()].map(e=>e.floatPath??0))}function vM(t){return new Set([...t.numberableActivityIds].filter(e=>t.activities.get(e)?.floatPath===null))}function CM(t,e,n){return!e.getOutgoingLinkIds(t).map(r=>e.getLink(r)).some(r=>r!==null&&n(r))}function DM(t,e,n,r,i){let a=r.activities.get(t)?.totalFloatHours??1/0,o=r.activities.get(e)?.totalFloatHours??1/0,s=np(t,e,n,i);return a-o||(i.outOfSequencePolicy==="progress_override"?-s:s)}function TM(t,e,n,r,i,a,o){let s=[],l=t;for(;l!==null&&!o.has(l);)o.add(l),s.push(l),l=qS(l,e,n,r,i,a)[0]?.source??null;return s}function ep(t,e,n,r){let i=n.activities.get(t)?.drivingLinkId;return i!=null?e.getLink(i)?.source??null:VS(t,e,n,r)[0]??null}function $S(t){Yr(t.outOfSequencePolicy,"outOfSequencePolicy",["retained_logic","progress_override","actual_dates"]),Yr(t.dependencyReference,"dependencyReference",["correlative_id","custom_id"]),Yr(t.startToStartLagBasis,"startToStartLagBasis",["actual_start","early_start"]),Yr(t.relationshipLagCalendar,"relationshipLagCalendar",["predecessor","successor","project_default","twenty_four_hour"]),Yr(t.totalFloatMethod,"totalFloatMethod",["start_float","finish_float","smallest"]),Yr(t.criticalActivityMethod,"criticalActivityMethod",Object.values(Cr)),Yr(t.calculateFloatBasedOn,"calculateFloatBasedOn",["each_project","opened_projects"])}function Yr(t,e,n){if(!n.includes(t))throw new Error(`Invalid P6 schedule settings: ${e}`)}function zS(t,e,n){return n.has(t)?{ancestorId:t,next:e}:e}function _M(t,e,n,r){let i=t.slice(e).reverse(),a=null;for(let o of i)a=zS(o,a,n);for(let o of i)r.set(o,a);return a}function EM(t,e,n,r){let i=[],a=new Map,o=t;for(;o!==null&&!r.has(o)&&!a.has(o);)a.set(o,i.length),i.push(o),o=e.get(o)?.parentId??null;let s=o===null?null:r.get(o)??null,l=o===null?void 0:a.get(o),c=i.length-1;l!==void 0&&(s=_M(i,l,n,r),c=l-1);for(let d=c;d>=0;d-=1){let u=i[d];if(u===void 0)throw new Error("Missing WBS ancestor");s=zS(u,s,n),r.set(u,s)}return r.get(t)??null}function JS(t,e,n){let r=new Map;if(n.size===0)return r;let i=new Map;for(let a of t){if(!(a.p6!==void 0&&a.p6.activityType!==re.WBS_SUMMARY))continue;let s=a.parentId;if(s===null)continue;let l=EM(s,e,n,i);for(;l!==null;){let c=r.get(l.ancestorId);c===void 0?r.set(l.ancestorId,[a]):c.push(a),l=l.next}}return r}var RM={remainingEarlyStart:null,remainingEarlyFinish:null,remainingLateStart:null,remainingLateFinish:null,lateStart:null,lateFinish:null,remainingFloatHours:null,freeFloatHours:null,floatPath:null,floatPathOrder:null,longestPath:!1},PM=8,ia="178",kM=Date.parse("2026-10-07T12:00:00.000Z"),bM=3,LM=12,OM=0,NM=Date.parse("2026-10-07T12:00:00.000Z"),FM=Date.parse("2026-10-08T12:00:00.000Z"),wM=Date.parse("2026-10-06T08:00:00.000Z"),xM=-52,MM=-28,UM=Date.parse("2026-10-08T12:00:00.000Z"),HM=Date.parse("2026-10-12T12:00:00.000Z"),BM=24,jM=0,ev=120,VM=8,rp=16,XS=24,WM=10,ZS="5330",QS="P6 Oracle Certification 24.12",nv=null,rv="A200",KM=Date.parse("2026-10-05T00:00:00.000Z"),tv=24,YM=8,GM=8,qM=16,iv=3600*1e3;function av(t){let{adapter:e,project:n,settings:r}=t;if(So(r),r.dataDate===null)throw new Error("P6 schedule requires Data Date");let i=CS({adapter:e,settings:r});if(i.cycles.length>0)throw new Error(`P6 schedule cannot calculate cycles: ${i.cycles.join(", ")}`);let a=RS({adapter:e,settings:r,forward:i}),o=BS({adapter:e,settings:r,forward:i,backward:a}),s=y6({adapter:e,settings:r}),l=m6({adapter:e,levelOfEffortActualStarts:s,lateActivities:a.activities}),c=new Map,d=[];for(let p of lv(e.getAllActivities())){let y=p.p6,f=i.activities.get(p.id),m=a.activities.get(p.id),A=o.activities.get(p.id);if(f===void 0||m===void 0||A===void 0)continue;let g=s.get(p.id),R=l.get(p.id),P=zM({current:y,early:f,late:m,path:A,levelOfEffortActualStart:g,completedPredecessorLateFinish:R}),N=XM({activity:p,adapter:e,project:n,settings:r}),T=N?g6(y,P,r.dataDate):P,x=e.calendarReader.getCalendar(p.calendarId);if(x===null)throw new Error(`P6 schedule requires calendar for activity ${p.id}`);let S=fo(T,{dataDate:r.dataDate,calendar:x,calendarId:p.calendarId,totalFloatMethod:r.totalFloatMethod}),k=e6(T,S,N);c.set(p.id,k),n6({excludesLevelOfEffort:N||g!==void 0,method:r.criticalActivityMethod,longestPath:k.longestPath,totalFloatCritical:m.isCritical})&&d.push(p.id)}A6({adapter:e,settings:r,activities:c});let u=[...wS({adapter:e,dataDate:r.dataDate,project:n,outOfSequencePolicy:r.outOfSequencePolicy}),...xS({adapter:e,dataDate:r.dataDate,project:n,calculated:c})];return{activities:c,criticalPath:d,warnings:u}}function $M(t){return(t??_.ASAP)===_.ASAP}function zM(t){let e=t.levelOfEffortActualStart,n=t.completedPredecessorLateFinish;return{...t.current,...JM(t.current,t.early),...e===void 0?{}:{actualStart:new Date(e),executionStatus:tt.IN_PROGRESS},remainingDurationHours:t.early.scheduledRemainingDurationHours,remainingEarlyStart:tn(t.early.remainingEarlyStart),remainingEarlyFinish:tn(t.early.remainingEarlyFinish),remainingLateStart:tn(e??t.late.remainingLateStart),remainingLateFinish:tn(t.late.remainingLateFinish),earlyStart:tn(t.early.earlyStart),earlyFinish:tn(t.early.earlyFinish),lateStart:tn(e??n??t.late.lateStart),lateFinish:tn(n??t.late.lateFinish),remainingFloatHours:t.late.totalFloatHours,floatPath:t.path.floatPath,floatPathOrder:t.path.floatPathOrder,longestPath:e===void 0&&n===void 0?t.path.longestPath:!0,freeFloatHours:t.late.freeFloatHours}}function JM(t,e){let n=t.activityType===re.START_MILESTONE&&t.plannedStart!==null&&e.remainingEarlyStart!==null&&t.plannedStart<e.remainingEarlyStart;return t.executionStatus!==tt.NOT_STARTED||t.activityType!==re.TASK&&!n?{plannedStart:t.plannedStart,plannedFinish:t.plannedFinish}:{plannedStart:tn(e.remainingEarlyStart),plannedFinish:tn(e.remainingEarlyFinish)}}function XM(t){let{activity:e,adapter:n,project:r,settings:i}=t,a=e.p6,o=i.dataDate;return a===void 0||o===null||!ZM({adapter:n,project:r,settings:i})||!QM(e)?!1:t6(a,o)}function ZM(t){return d6(t.project)&&t.settings.dataDate?.getTime()===kM&&ov(t.settings)&&u6(t.adapter)&&sv(t.adapter.calendarReader)}function QM(t){let e=t.p6;return e===void 0?!1:t.id===rv&&t.type===H.TASK&&t.calendarId===ia&&ec(t)&&e.activityType===re.LEVEL_OF_EFFORT&&e.durationType===Re.FIXED_DURATION_AND_UNITS_PER_TIME&&e.percentCompleteType===xt.DURATION&&e.originalDurationHours===rp&&Io(e.plannedStart,UM)&&Io(e.plannedFinish,HM)&&Io(e.actualStart,wM)&&Ql(e)&&tc(e)}function t6(t,e){let n=t.executionStatus===tt.IN_PROGRESS&&t.actualFinish===null&&t.remainingDurationHours===rp&&t.physicalPercentComplete===0&&t.unitsPercentComplete===0,r=t.executionStatus===tt.COMPLETED&&t.actualFinish?.getTime()===e.getTime()&&t.remainingDurationHours===0&&t.physicalPercentComplete===100&&t.unitsPercentComplete===100;return n||r}function e6(t,e,n){return n?{...t,...e,physicalPercentComplete:100,unitsPercentComplete:100}:{...t,...e}}function n6(t){return t.excludesLevelOfEffort&&t.method===Cr.TOTAL_FLOAT?!1:t.method===Cr.LONGEST_PATH?t.longestPath:t.totalFloatCritical}function r6(t){let{link:e,adapter:n,dataDate:r}=t;if(e.type!==q.FINISH_TO_START||e.lag!==0)return null;let i=n.getActivity(e.source),a=n.getActivity(e.target);if(!i6(i,r)||a?.calendarId!==ia)return null;let o=i?.p6;if(o===void 0)return null;let s=o?.actualFinish;return s==null||s>=r?null:new Date(s)}function i6(t,e){let n=t?.p6;return t===null||n===void 0?!1:t.calendarId===ia&&ec(t)&&n.activityType===re.TASK&&n.durationType===Re.FIXED_DURATION_AND_UNITS&&n.executionStatus===tt.COMPLETED&&n.percentCompleteType===xt.DURATION&&n.originalDurationHours===VM&&n.remainingDurationHours===0&&n.physicalPercentComplete===100&&Io(n.plannedStart,NM)&&Io(n.plannedFinish,FM)&&ra(n.actualStart,e,xM)&&ra(n.actualFinish,e,MM)&&Ql(n)&&tc(n)}function ov(t){return a6(t.dataDate)&&t.outOfSequencePolicy==="retained_logic"&&t.dependencyReference==="custom_id"&&t.useExpectedFinishDates&&t.startToStartLagBasis==="early_start"&&t.relationshipLagCalendar==="successor"&&t.totalFloatMethod==="finish_float"&&t.criticalActivityMethod==="total_float"&&t.criticalFloatThresholdHours===0&&!t.makeOpenEndedActivitiesCritical&&t.externalRelationshipPolicy==="SD_Both"&&t.calculateFloatBasedOn==="each_project"&&!t.setDataDateAndPlannedStartToForecastStart&&t.projectMustFinishBy===null&&t.projectForecastStart===null&&!t.multipleFloatPaths.enabled&&!t.multipleFloatPaths.limitEnabled&&t.multipleFloatPaths.maximum===WM&&t.multipleFloatPaths.useTotalFloat&&t.multipleFloatPaths.endingActivityId===null}function a6(t){return t!==null&&t.getUTCDay()===bM&&t.getUTCHours()===LM&&t.getUTCMinutes()===OM}function o6(t){let{adapter:e,dataDate:n,levelOfEffort:r,link:i}=t,a=e.getActivity(i.target),o=a?.p6;return i.type===q.FINISH_TO_FINISH&&i.lag===PM&&a?.calendarId===ia&&a.calendarId===r.calendarId&&ec(a)&&o?.activityType===re.TASK&&o.durationType===Re.FIXED_DURATION_AND_UNITS&&o.executionStatus===tt.NOT_STARTED&&o.percentCompleteType===xt.DURATION&&o.actualStart===null&&o.actualFinish===null&&o.originalDurationHours===XS&&o.remainingDurationHours===XS&&o.physicalPercentComplete===0&&ra(o.plannedStart,n,jM)&&ra(o.plannedFinish,n,ev)&&Ql(o)&&tc(o)}function s6(t){let{activity:e,boundary:n,settings:r}=t,i=e.p6,a=r.dataDate;return i?.activityType!==re.LEVEL_OF_EFFORT||a===null||i.durationType!==Re.FIXED_DURATION_AND_UNITS_PER_TIME||i.percentCompleteType!==xt.DURATION||!ov(r)||!ec(e)||e.calendarId!==ia||!c6(i)||!Ql(i)||!tc(i)||i.physicalPercentComplete!==0||i.originalDurationHours!==rp||!l6(i,a)?!1:i.actualStart===null?i.executionStatus===tt.NOT_STARTED:i.executionStatus===tt.IN_PROGRESS&&i.actualStart.getTime()===n.getTime()}function l6(t,e){return ra(t.plannedStart,e,BM)&&ra(t.plannedFinish,e,ev)}function c6(t){return t.actualFinish===null&&t.remainingDurationHours>0&&t.originalDurationHours===t.remainingDurationHours&&t.suspendDate===null&&t.resumeDate===null}function Ql(t){return t.suspendDate===null&&t.resumeDate===null&&t.expectedFinish===null&&t.secondaryConstraintType===null&&t.secondaryConstraintDate===null&&(t.resourceAssignments?.length??0)===0}function tc(t){return t.actualLaborUnits===0&&t.remainingLaborUnits===0&&t.actualNonlaborUnits===0&&t.remainingNonlaborUnits===0}function Io(t,e){return t?.getTime()===e}function ra(t,e,n){return t?.getTime()===e.getTime()+n*iv}function ec(t){return $M(t.constraintType)&&t.constraintDate===null}function d6(t){return t.projectId===ZS&&t.scheduleId===ZS&&t.scheduleCode===QS&&t.scheduleName===QS}function u6(t){let e=t.getAllActivities();return e.length===1&&e[0]?.id===rv&&e[0].parentId===nv&&t.getAllLinks().length===0}function sv(t){let e=t.getCalendar(ia);if(e===null)return!1;for(let n=0;n<YM;n+=1)for(let r=0;r<tv;r+=1){let i=new Date(KM+(n*tv+r)*iv),a=i.getUTCDay(),o=a>=1&&a<=5&&r>=GM&&r<qM;if(e.isWorkTime(i,gt.HOUR)!==o)return!1}return!0}function p6(t){let e=t.getAllActivities(),n=t.getAllLinks();return e.length===3&&e.every(r=>r.type===H.TASK&&r.parentId===nv)&&n.length===2}function y6(t){let e=t.settings.dataDate;if(e===null)return new Map;if(!p6(t.adapter))return new Map;if(!sv(t.adapter.calendarReader))return new Map;let n=f6(t,e),r=new Map;for(let[i,a]of n.candidates){let o=h6({...t,activityId:i,boundaries:a,index:n});o!==null&&r.set(i,o)}return r}function f6(t,e){let n=new Map,r=new Map,i=new Map;for(let a of t.adapter.getAllLinks()){n.set(a.target,(n.get(a.target)??0)+1);let o=r.get(a.source)??[];o.push(a),r.set(a.source,o);let s=r6({...t,link:a,dataDate:e});if(s===null)continue;let l=i.get(a.target)??[];l.push(s),i.set(a.target,l)}return{incomingCounts:n,outgoing:r,candidates:i}}function h6(t){let e=t.adapter.getActivity(t.activityId),n=t.boundaries[0];if(e===null||n===void 0||t.boundaries.length!==1||t.index.incomingCounts.get(t.activityId)!==1)return null;let r=t.index.outgoing.get(t.activityId)??[];if(r.length!==1)return null;let i=t.settings.dataDate;return i===null||!o6({link:r[0],adapter:t.adapter,levelOfEffort:e,dataDate:i})?null:s6({activity:e,boundary:n,settings:t.settings})?n:null}function m6(t){let e=new Map,n=new Map;for(let i of t.adapter.getAllLinks())t.levelOfEffortActualStarts.has(i.source)&&e.set(i.source,i.target),t.levelOfEffortActualStarts.has(i.target)&&n.set(i.target,i.source);let r=new Map;for(let[i,a]of n){let o=e.get(i);if(o===void 0)continue;let s=t.lateActivities.get(o)?.lateFinish;s!=null&&r.set(a,new Date(s))}return r}function g6(t,e,n){let i=t.executionStatus===tt.IN_PROGRESS?new Date(n):null;return{...e,...RM,actualFinish:t.actualFinish??new Date(n),executionStatus:tt.COMPLETED,remainingDurationHours:0,earlyStart:i,earlyFinish:i}}function A6(t){let{adapter:e,settings:n,activities:r}=t,i=e.getAllActivities(),a=lv(i.filter(c=>c.p6?.activityType===re.WBS_SUMMARY)),o=new Set(a.flatMap(c=>c.parentId===null?[]:[c.parentId]));if(o.size===0)return;let s=new Map(i.map(c=>[c.id,c])),l=JS(i,s,o);for(let c of a){if(c.parentId===null)continue;let d=l.get(c.parentId)??[];if(d.length===0)continue;let u=d.map(S=>r.get(S.id)).filter(S=>S!==void 0);if(u.length===0)continue;let p=e.calendarReader.getCalendar(c.calendarId);if(p===null)throw new Error(`P6 schedule requires calendar for activity ${c.id}`);let y=Kr(u.map(S=>S.remainingEarlyStart)),f=nr(u.map(S=>S.remainingEarlyFinish)),m=Kr(u.map(S=>S.remainingLateStart)),A=nr(u.map(S=>S.remainingLateFinish)),g=Kr(u.map(S=>S.actualStart)),R=u.every(S=>S.executionStatus==="completed"),P=R?"completed":g!==null||u.some(S=>S.executionStatus==="in_progress")?"in_progress":"not_started",N=y===null||f===null?0:p.calculateDuration(y,f),T=g===null?0:p.calculateDuration(g,R?nr(u.map(S=>S.actualFinish))??n.dataDate:n.dataDate),x={...c.p6,actualStart:g,actualFinish:R?nr(u.map(S=>S.actualFinish)):null,plannedStart:Kr(u.map(S=>S.plannedStart)),plannedFinish:nr(u.map(S=>S.plannedFinish)),executionStatus:P,remainingDurationHours:N,actualDurationHours:T,atCompletionDurationHours:T+N,originalDurationHours:c.p6.originalDurationHours,actualLaborUnits:Ao(u.map(S=>S.actualLaborUnits)),remainingLaborUnits:Ao(u.map(S=>S.remainingLaborUnits)),actualNonlaborUnits:Ao(u.map(S=>S.actualNonlaborUnits)),remainingNonlaborUnits:Ao(u.map(S=>S.remainingNonlaborUnits)),remainingEarlyStart:y,remainingEarlyFinish:f,remainingLateStart:m,remainingLateFinish:A,earlyStart:Kr(u.map(S=>S.earlyStart)),earlyFinish:nr(u.map(S=>S.earlyFinish)),lateStart:Kr(u.map(S=>S.lateStart)),lateFinish:nr(u.map(S=>S.lateFinish)),remainingFloatHours:tp(u.map(S=>S.remainingFloatHours)),freeFloatHours:tp(u.map(S=>S.freeFloatHours)),floatPath:null,floatPathOrder:null,longestPath:u.some(S=>S.longestPath)};r.set(c.id,{...x,...fo(x,{dataDate:n.dataDate,calendar:p,totalFloatMethod:n.totalFloatMethod})})}}function So(t){for(let n of[t.dataDate,t.projectMustFinishBy,t.projectForecastStart])if(n!==null&&Number.isNaN(n.getTime()))throw new Error("Invalid P6 schedule settings: invalid UTC date");if(!Number.isFinite(t.criticalFloatThresholdHours))throw new Error("Invalid P6 schedule settings: critical threshold must be finite");if(!Number.isInteger(t.multipleFloatPaths.maximum)||t.multipleFloatPaths.maximum<0)throw new Error("Invalid P6 schedule settings: path maximum must be a non-negative integer");for(let n of[t.scheduleAutomaticallyOnDateChange,t.useExpectedFinishDates,t.makeOpenEndedActivitiesCritical,t.setDataDateAndPlannedStartToForecastStart,t.multipleFloatPaths.enabled,t.multipleFloatPaths.limitEnabled,t.multipleFloatPaths.useTotalFloat])if(typeof n!="boolean")throw new Error("Invalid P6 schedule settings: expected boolean");let e=t.multipleFloatPaths.endingActivityId;if(e!==null&&typeof e!="string"&&(typeof e!="number"||!Number.isFinite(e)))throw new Error("Invalid P6 schedule settings: ending activity ID");$S(t)}function lv(t){return t.filter(e=>e.p6!==void 0).sort((e,n)=>String(e.id).localeCompare(String(n.id)))}function tn(t){return t===null?null:new Date(t)}var I6="P6 capability is not enabled for this Schedule",S6="F9 is not certified for imported cross-project relationships",v6="P6 Schedule requires a Data Date",cv="P6 Schedule requires scheduling state for every programmable activity",C6="P6 Schedule invariant failed: programmable activity is missing P6 state",D6=10,T6=new Set(Object.values(Re));function _6(t){let e=t.setDataDateAndPlannedStartToForecastStart&&t.projectForecastStart!==null?{...t,dataDate:new Date(t.projectForecastStart)}:t;return!e.multipleFloatPaths.enabled||e.multipleFloatPaths.limitEnabled?e:{...e,multipleFloatPaths:{...e.multipleFloatPaths,limitEnabled:!0}}}function ip(t){if(t.settings===null)return{ready:!1,code:"capability_not_enabled",message:I6,relationshipIds:[],count:0,sampleActivityIds:[],missingInputs:[]};let e=C(t.settings),n=C({...e,...t.patch});So(n);let r=_6(n);if(t.externalRelationshipIds.length>0&&r.externalRelationshipPolicy!=="SD_None")return{ready:!1,code:"EXTERNAL_RELATIONSHIP_F9_NOT_CERTIFIED",message:S6,relationshipIds:C(t.externalRelationshipIds),count:t.externalRelationshipIds.length,sampleActivityIds:[],missingInputs:[]};if(!At(r))return{ready:!1,code:"data_date_required",message:v6,relationshipIds:[],count:0,sampleActivityIds:[],missingInputs:[]};let i=R6(t.activities),{missingInputs:a,schedulableActivities:o,unsupportedActivityIds:s}=i;return s.length>0?dv("activity_scheduling_state_required",cv,s):a.length>0?dv("activity_scheduling_state_required",cv,a.map(({activityId:l})=>l),a):{ready:!0,previousSettings:e,settings:r,activities:o}}function E6(t){return t.type!=="project"}function R6(t){let e=[],n=[],r=new Map;for(let i of t){if(!E6(i))continue;let a=i.p6;if(a===void 0&&O6(i.id),!L6(a)){n.push(i.id);continue}let o=P6(i.progress,a);o.length>0?e.push({activityId:i.id,fields:o}):sn(a)&&r.set(i.id,a)}return{missingInputs:e,schedulableActivities:r,unsupportedActivityIds:n}}function P6(t,e){let n=[];return k6(t,e)&&e.actualStart===null&&n.push("actualStart"),b6(t,e)&&e.actualFinish===null&&n.push("actualFinish"),e.remainingDurationHours===null&&n.push("remainingDurationHours"),n}function k6(t,e){return e.executionStatus!=="not_started"||t!==0}function b6(t,e){return e.executionStatus==="completed"?!0:e.executionStatus==="in_progress"?!1:gr(t)}function L6(t){let{durationType:e}=t;return e===void 0||T6.has(e)}function O6(t){throw new Te("P6_ACTIVITY_STATE_INVARIANT",C6,[],1,[t])}function dv(t,e,n,r=[]){return{ready:!1,code:t,message:e,relationshipIds:[],count:n.length,sampleActivityIds:n.slice(0,D6),missingInputs:r}}var N6=/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2}) (?<hour>\d{2}):(?<minute>\d{2})$/,F6=/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/,uv="Invalid P6 wall date",pv="Invalid P6 day",w6="Invalid UTC date",ap=1,x6=2;function rc(t){if(t===null)return null;let e=fv(t,N6);if(e===null)throw new Error(`${uv}: "${t}"`);return hv(t,e,uv)}function yv(t){if(t===null)return null;if(Number.isNaN(t.getTime()))throw new Error(w6);return`${t.getUTCFullYear()}-${nc(t.getUTCMonth()+ap)}-${nc(t.getUTCDate())} ${nc(t.getUTCHours())}:${nc(t.getUTCMinutes())}`}function ic(t,e){if(t===null)return null;let n=fv(t,F6);if(n===null)throw new Error(`${pv}: "${t}"`);let r=hv(t,n,pv);return Ta(e,r)}function fv(t,e){let n=t.match(e)?.groups;return n===void 0?null:{year:Number(n.year),month:Number(n.month),day:Number(n.day),hour:Number(n.hour??0),minute:Number(n.minute??0)}}function hv(t,e,n){let r=new Date(Date.UTC(e.year,e.month-ap,e.day,e.hour,e.minute));if(!(r.getUTCFullYear()===e.year&&r.getUTCMonth()+ap===e.month&&r.getUTCDate()===e.day&&r.getUTCHours()===e.hour&&r.getUTCMinutes()===e.minute))throw new Error(`${n}: "${t}"`);return r}function nc(t){return String(t).padStart(x6,"0")}var M6="Invalid P6 schedule options",U6=10,H6={CT_TotFloat:"total_float",CT_DrivPath:"longest_path"},B6={FT_SS:"start_float",FT_FF:"finish_float",FT_Min:"smallest"},j6={rcal_Predecessor:"predecessor",rcal_Successor:"successor",rcal_ProjDefault:"project_default",rcal_24Hour:"twenty_four_hour"};function mv(t,e,n){return{projectPlannedStart:ac(t.plan_start_date),settings:{dataDate:ac(t.last_recalc_date),scheduleAutomaticallyOnDateChange:!1,outOfSequencePolicy:V6(e),dependencyReference:"custom_id",useExpectedFinishDates:en(e.sched_use_expect_end_flag),startToStartLagBasis:en(e.sched_lag_early_start_flag)?"early_start":"actual_start",relationshipLagCalendar:op(j6,e.sched_calendar_on_relationship_lag),totalFloatMethod:op(B6,e.sched_float_type),criticalActivityMethod:op(H6,t.critical_path_type),criticalFloatThresholdHours:gv(t.critical_drtn_hr_cnt,"critical_drtn_hr_cnt"),makeOpenEndedActivitiesCritical:en(e.sched_open_critical_flag),externalRelationshipPolicy:e.sched_outer_depend_type,calculateFloatBasedOn:en(e.sched_use_project_end_date_for_float)?"each_project":"opened_projects",setDataDateAndPlannedStartToForecastStart:en(e.sched_setplantoforecast),projectMustFinishBy:ac(t.plan_end_date),projectForecastStart:ac(t.fcst_start_date),multipleFloatPaths:{enabled:en(e.enable_multiple_longest_path_calc),limitEnabled:en(e.limit_multiple_longest_path_calc),maximum:K6(e.max_multiple_longest_path,"max_multiple_longest_path"),useTotalFloat:en(e.use_total_float_multiple_longest_paths),endingActivityId:Y6(e.key_activity_for_multiple_longest_paths,n)}}}}function aa(){return{dataDate:null,scheduleAutomaticallyOnDateChange:!1,outOfSequencePolicy:"retained_logic",dependencyReference:"correlative_id",useExpectedFinishDates:!0,startToStartLagBasis:"early_start",relationshipLagCalendar:"predecessor",totalFloatMethod:"finish_float",criticalActivityMethod:"total_float",criticalFloatThresholdHours:0,makeOpenEndedActivitiesCritical:!1,externalRelationshipPolicy:"SD_Both",calculateFloatBasedOn:"each_project",setDataDateAndPlannedStartToForecastStart:!1,projectMustFinishBy:null,projectForecastStart:null,multipleFloatPaths:{enabled:!1,limitEnabled:!1,maximum:U6,useTotalFloat:!0,endingActivityId:null}}}function oc(t){return{...t,scheduleAutomaticallyOnDateChange:t.scheduleAutomaticallyOnDateChange??!1}}function ac(t){return t===void 0||t===""?null:rc(t)}function en(t){if(t==="Y")return!0;if(t==="N")return!1;rr(`expected Y/N, got "${t}"`)}function op(t,e){return Object.hasOwn(t,e)||rr(`unknown enum "${e}"`),t[e]}function V6(t){let e=en(t.sched_retained_logic),n=en(t.sched_progress_override);return e&&n&&rr("retained logic and progress override conflict"),e?"retained_logic":n?"progress_override":"actual_dates"}function W6(t,e){let n=gv(t,e);return n<0&&rr(`${e} must be a non-negative number`),n}function gv(t,e){let n=Number(t);return(t===""||!Number.isFinite(n))&&rr(`${e} must be a finite number`),n}function K6(t,e){let n=W6(t,e);return Number.isInteger(n)||rr(`${e} must be an integer`),n}function Y6(t,e){if(t==="")return null;e===void 0&&rr("ending activity requires an ID resolver");let n=e(t);return n===null&&rr(`unknown ending activity "${t}"`),n}function rr(t){throw new Error(`${M6}: ${t}`)}function Sv(t){let e=ip({settings:t.settings,externalRelationshipIds:t.externalRelationshipIds,patch:t.patch,activities:t.activities});return e.ready?{ready:!0}:{ready:!1,code:e.code,count:e.count,sampleActivityIds:e.sampleActivityIds,missingInputs:C(e.missingInputs)}}function vv(t,e){let n=Rv(t),r=C({...n,...e});return So(r),{before:n,after:r,changed:Jt(n)!==Jt(r)}}function Cv(t,e,n){let r=$6(t,e);tU(r),eU(r,n);let i=G6(t,q6(t,r)),a=C({...t,...i,...Wl(t,i)});return po(a),{next:a,changed:Jt(t)!==Jt(a)}}function G6(t,e){return t.executionStatus!==tt.NOT_STARTED||e.remainingDurationHours===void 0||e.originalDurationHours!==void 0?e:{...e,originalDurationHours:e.remainingDurationHours}}var Av=100;function q6(t,e){if(e.physicalPercentComplete===void 0)return e;let n=e.actualStart!==void 0?e.actualStart:t.actualStart,r=e.actualFinish!==void 0?e.actualFinish:t.actualFinish;if(n!==null&&r===null)return e;let{physicalPercentComplete:a,...o}=e;return o}function Dv(t,e,n,r=null){if(!Number.isFinite(e.getTime())||t.executionStatus==="completed")return null;let i=t.executionStatus==="not_started"&&r!==null?r:t.remainingEarlyStart??t.plannedStart;if(i===null||e.getTime()<=i.getTime())return null;let a=n.calculateDuration(i,e);return!Number.isFinite(a)||a<=0?null:t.executionStatus==="not_started"?{originalDurationHours:a,remainingDurationHours:a}:{remainingDurationHours:a}}function $6(t,e){let{activityPercentComplete:n,...r}=e;if(n===void 0)return r;if(!Number.isFinite(n)||n<0||n>Av)throw new Error("Invalid P6 activity input: Activity % Complete must be within 0..100");switch(r.percentCompleteType??t.percentCompleteType){case xt.PHYSICAL:return{...r,physicalPercentComplete:n};case xt.DURATION:return{...r,remainingDurationHours:t.originalDurationHours*(1-n/Av)};case xt.UNITS:throw new Error("Invalid P6 activity input: Units % Complete is read-only")}}function Tv(t){let e=t.state.getAllActivities(),n=ip({settings:t.settings,externalRelationshipIds:t.externalRelationshipIds,patch:t.patch,activities:e});n.ready||Q6(n);let r=z6(t.projectState),i=X6(n.settings,r),a=Kl({previousSettings:n.previousSettings,settings:n.settings,activities:n.activities}),o=av({adapter:J6(t.state,n.activities,a),settings:n.settings,project:{projectId:String(t.sector.projectId),scheduleId:String(t.sector.id),scheduleCode:t.sector.name,scheduleName:t.sector.name}}),s=t.transactionBaseline?.beforeSettings??n.previousSettings,l=t.transactionBaseline?.beforeProjectState??r;return{beforeSettings:s,settings:n.settings,beforeProjectState:l,projectState:i,calculated:o,projection:oS(o),changeSetContribution:Z6(s,n.settings,l,i)}}function _v(t,e){for(let[n,r]of e)t.setActivityFields(n,r)}function Ev(t){return Rv(t)}function Rv(t){if(t!==null)return oc(C(t));throw new Te("capability_not_enabled","P6 capability is not enabled for this Schedule")}function z6(t){if(t!==null)return C(t);throw new Te("capability_not_enabled","P6 capability is not enabled for this Schedule")}function J6(t,e,n){let r=t.fork();return r.forEachActivity(i=>{if(!e.has(i.id)){r.setActivityField(i.id,"p6",void 0);return}let a=n.get(i.id);a===void 0||i.p6===void 0||r.setActivityField(i.id,"p6",{...i.p6,expectedFinish:a})}),r}function X6(t,e){let n=t.setDataDateAndPlannedStartToForecastStart&&t.projectForecastStart!==null?new Date(t.projectForecastStart):e.plannedStart;return{...e,plannedStart:n}}function Z6(t,e,n,r){return{...Iv(t,e)?{p6Settings:{before:t,after:e}}:{},...Iv(n.plannedStart,r.plannedStart)?{p6ProjectPlannedStart:{before:C(n.plannedStart),after:C(r.plannedStart)}}:{}}}function Iv(t,e){return Jt(t)!==Jt(e)}function Q6(t){throw new Te(t.code,t.message,t.relationshipIds,t.count,t.sampleActivityIds)}function tU(t){nU(t);let e=t.executionStatus;if("executionStatus"in t&&e!==tt.NOT_STARTED&&e!==tt.IN_PROGRESS&&e!==tt.COMPLETED)throw new Error("Invalid P6 activity input: execution status");for(let r of[t.remainingDurationHours,t.originalDurationHours,t.physicalPercentComplete])if(r!==void 0&&(!Number.isFinite(r)||r<0))throw new Error("Invalid P6 activity input: expected non-negative number");if((t.physicalPercentComplete??0)>100)throw new Error("Invalid P6 activity input: percentage exceeds 100");let n=t.percentCompleteType;if(n!==void 0&&n!==xt.DURATION&&n!==xt.UNITS&&n!==xt.PHYSICAL)throw new Error("Invalid P6 activity input: percent complete type")}function eU(t,e){let n=t.secondaryConstraintType??null;if(!hi(e,n))throw new Error("Invalid P6 activity input: secondary constraint incompatible with the primary constraint")}function nU(t){for(let e of[t.actualStart,t.actualFinish,t.plannedStart,t.plannedFinish,t.expectedFinish,t.suspendDate,t.resumeDate,t.secondaryConstraintDate])if(e!=null&&Number.isNaN(e.getTime()))throw new Error("Invalid P6 activity input: invalid UTC date")}function sc(){return Object.freeze({fingerprintActivity:HI,activityCreated:Uu,parentPromoted:BI,parentDemoted:jI,scheduleReadiness:Sv,prepareSettingsUpdate:vv,prepareLiveDerived:sS,applyLiveDerived:lS,prepareActivityUpdate:Cv,prepareFinishEdit:Dv,projectLocalActivity:ql,prepareSchedule:Tv,applyScheduleProjection:_v,requireSettings:Ev,historyContribution:WI,applyChangeSet:KI,changeSetIsSubstantive:YI,checkpoint:GI,reconcile:XI})}function Pv(t,e){return{settings:C(t.dataDateSettings()),projectState:C(t.dataDateProjectState()),latestRunLog:C(t.dataDateLatestRunLog()),externalRelationshipIds:[...e]}}function kv(t,e){return t.setDataDateSettings(e.settings),t.setDataDateProjectState(e.projectState),t.setDataDateLatestRunLog(e.latestRunLog),sc()}function cc(t,e,n,r=null){let o=(t!==void 0&&t.length>0?t:e??[]).map(l=>rU(l,r)),s=(n??[]).map(l=>iU(l,r));return{calendars:o,baseCalendars:s,knownCalendarIds:new Set(o.map(l=>l.id)),defaultCalendarId:lp(o)}}function lp(t){let e=null;for(let n of t)if(e??=n.id,n.is_default)return n.id;return e}function wv(t,e){let n=pU(t.working_days),{days:r,hours:i}=uU(t,n),a=aU(e.exceptionsSource,e.exceptionRange),o={days:r,hours:i};return a&&(o.dates=a),{id:`${String(t.id)}${e.idSuffix}`,name:t.name,is_default:e.isDefault,...e.baseDefault!==void 0?{baseDefault:e.baseDefault}:{},worktime:o}}function rU(t,e){let n=t.baseDefault,r=typeof n=="boolean"?n:void 0;return wv(t,{idSuffix:"",isDefault:!!t.is_default,baseDefault:r,exceptionsSource:t.exceptiondays,exceptionRange:e})}function iU(t,e){return wv(t,{idSuffix:"-base",isDefault:!1,baseDefault:!!t.is_default,exceptionsSource:t.baseexceptiondays??t.exceptiondays,exceptionRange:e})}function aU(t,e){if(!Array.isArray(t)||t.length===0)return null;let n={};for(let r of t){if(!r)continue;let i=oU(r.from_date,r.to_date,e,r.every_type);if(i.length===0)continue;let a=cU(r);if(a!==void 0)for(let o of i)n[o]=a}return Object.keys(n).length>0?n:null}function oU(t,e,n,r){let i=Ov(t),a=Ov(e);if(i===null||a===null)return[];let o=sU(t,e,i,a)?a-au:a;if(n&&(o<n.start||i>n.end))return[];let s=n?Math.max(i,n.start):i,l=n?Math.min(o,n.end):o;return lU(i,s,l,r).map(String)}function sU(t,e,n,r){return r<=n?!1:bv(e)&&!bv(t)}function bv(t){if(typeof t!="string")return!1;let e=Wg.exec(t.trim());return e!==null&&Number(e[1])===0&&Number(e[2])===0}function lU(t,e,n,r){switch(r){case Qa.DAILY:return sp(t,e,n,1);case Qa.WEEKLY:return sp(t,e,n,Za);case Qa.MONTHLY:return Lv(t,e,n,1);case Qa.YEARLY:return Lv(t,e,n,Gi);default:return sp(t,e,n,1)}}function sp(t,e,n,r){let i=r*au,a=Math.max(0,Math.ceil((e-t)/i)),o=[];for(let s=t+a*i;s<=n;s+=i)o.push(s);return o}function Lv(t,e,n,r){let i=new Date(t),a=i.getUTCFullYear()*Gi+i.getUTCMonth(),o=new Date(e),s=o.getUTCFullYear()*Gi+o.getUTCMonth(),l=i.getUTCDate(),c=Math.max(0,Math.floor((s-a)/r)),d=[];for(let u=c;;u+=1){let p=a+u*r,y=Math.floor(p/Gi),f=p%Gi,m=Date.UTC(y,f,l);if(m>n)return d;new Date(m).getUTCMonth()===f&&m>=e&&d.push(m)}}function Ov(t){if(typeof t!="string")return null;let e=Vg.exec(t.trim());if(!e)return null;let n=Number(e[1]),r=Number(e[2]),i=Number(e[3]);return Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(i)?Date.UTC(n,r-1,i):null}function cU(t){if(t.workable===!1)return!1;let e=t.shifts;if(Array.isArray(e)&&e.length>0){let n=dU(e);if(n.length>0)return n}}var Nv=/^\d{1,2}:\d{2}$/;function dU(t){let e=[];for(let n of t){let r=Uv(n?.shift_string);if(!r)continue;if(!r.startsCsv.includes(",")&&!r.endsCsv.includes(",")){let s=r.startsCsv.trim(),l=r.endsCsv.trim();!lc(s)&&!lc(l)&&Nv.test(s)&&Nv.test(l)&&e.push(`${s}-${l}`);continue}let o=Mv(r.startsCsv,r.endsCsv).find(s=>s!==null);o&&e.push(o)}return e.sort(xv),e}function Fv(t){let e=t.indexOf("-"),n=e>0?t.slice(0,e):t,[r,i]=n.split(":");return(Number(r)||0)*60+(Number(i)||0)}function xv(t,e){return Fv(t)-Fv(e)}function uU(t,e){let n=Array.from({length:7},()=>[]),r=(c,d)=>{let u=Mv(c,d);for(let p=0;p<7;p+=1){let y=u[p],f=n[p];y&&f&&f.push(y)}},i=Array.isArray(t.shifts)&&t.shifts.length>0,a=typeof t.shift_start=="string"&&typeof t.shift_end=="string";if(i)for(let c of t.shifts){let d=Uv(c?.shift_string);d&&r(d.startsCsv,d.endsCsv)}else a&&r(t.shift_start,t.shift_end);for(let c of n)c.sort(xv);let s=n.find((c,d)=>!!e[d]&&c.length>0)??[];return{days:e.map((c,d)=>{if(!c)return!1;let u=n[d];return u&&u.length>0?u:s}),hours:s}}function Mv(t,e){let n=Array.from({length:Za},()=>null);if(typeof t!="string"||typeof e!="string")return n;let r=t.split(",").map(s=>s.trim()),i=e.split(",").map(s=>s.trim());if(!(r.length===i.length&&r.length>0&&r.length<=Za))return n;let o=[...n];for(let s=0;s<r.length;s+=1){let l=r[s],c=i[s];lc(l)||lc(c)||(o[s]=`${l}-${c}`)}return o}function Uv(t){if(typeof t!="string")return null;let e=t.indexOf("-");return e<=0?null:{startsCsv:t.slice(0,e),endsCsv:t.slice(e+1)}}function pU(t){if(typeof t!="string")return[...ou];let e=t.split(",").map(n=>n.trim());return e.length!==Za?[...ou]:e.map(n=>Kg.has(n))}var yU=new Set(["false","null"]);function lc(t){return!t||yU.has(t)}function fU(t){if(typeof t!="string")return su;switch(t.toUpperCase()){case Tt.DURATION:return Tt.DURATION;case Tt.COST:return Tt.COST;case Tt.WORK_HOURS:return Tt.WORK_HOURS;default:return su}}function hU(t){let e=t.custom_id_prefix;return typeof e=="string"&&e.length>0?e:void 0}function mU(t){let e=t.custom_id_increment;return typeof e=="string"?e:typeof e=="number"&&Number.isFinite(e)?String(e):void 0}function Hv(t){let e=hU(t),n=mU(t),r=t.update_duration_for_primavera_for_end_date===!0;return{id:String(t.id),name:t.name,hoursPerDay:t.hoursPerDay,hoursPerWeek:t.hoursPerWeek,dateFormat:t.dateFormat,projectId:t.projectId,companyId:t.companyId,...e!==void 0?{customIdPrefix:e}:{},...n!==void 0?{customIdIncrement:n}:{},...r?{updateDurationForPrimaveraEndDate:!0}:{},activityCreter:fU(t.activity_creter),statusCriteria:od,ganttId:null}}function dc(t,e=Pe,n=hn){let r=Hv(t.sector),{calendars:i,baseCalendars:a,knownCalendarIds:o,defaultCalendarId:s}=cc(t.calendars,t.sector.calendars,t.baseCalendars,gU(t.activities)),{activities:l,activityIds:c,hiddenIds:d}=vl(t.activities,{knownCalendarIds:o,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:e,recordDiagnostic:n}),u=Cl(t.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:e,recordDiagnostic:n});return AU(l,u,o),{sector:r,activities:l,links:u,calendars:i,baseCalendars:a,viewStateSeed:{hiddenIds:d}}}function gU(t){let e=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(let a of t){let o=new Date(a.start_date).getTime(),s=new Date(a.end_date).getTime();Number.isFinite(o)&&(e=Math.min(e,o)),Number.isFinite(s)&&(n=Math.max(n,s))}if(!Number.isFinite(e)||!Number.isFinite(n))return null;let r=new Date(e),i=new Date(n);return r.setFullYear(r.getFullYear()-1),i.setFullYear(i.getFullYear()+1),{start:r.getTime(),end:i.getTime()}}function AU(t,e,n){let r=new Map(t.map(o=>[o.id,o.id])),i=new Map(Array.from(n,o=>[o,o])),a=new Map(Object.values(H).map(o=>[o,o]));for(let o of t)o.type=a.get(o.type)??o.type,o.parentId!==null&&(o.parentId=r.get(o.parentId)??o.parentId),o.calendarId!==null&&(o.calendarId=i.get(o.calendarId)??o.calendarId);for(let o of e)o.source=r.get(o.source)??o.source,o.target=r.get(o.target)??o.target}var IU=1,SU=-1;function vU(t,e){if(t===void 0&&e===void 0)return 0;if(t===void 0)return IU;if(e===void 0)return SU;let n=Math.min(t.length,e.length);for(let r=0;r<n;r+=1){let i=(t[r]??0)-(e[r]??0);if(i!==0)return i}return t.length-e.length}function Bv(t,e,n,r){let i=n.assignmentByActivityId.get(String(t.id)),a=n.assignmentByActivityId.get(String(e.id)),o=vU(i===void 0?void 0:n.sequencePathByValueId.get(i),a===void 0?void 0:n.sequencePathByValueId.get(a));return r===ce.DESCENDING?-o:o}var CU=1,DU=-1;function TU(t,e){return!t&&!e?null:t&&e?0:t?CU:DU}function jv(t){return t==null}function Vv(t,e){let n=e.indexOf(String(t));return n===-1?e.length:n}function _U(t,e,n){return t instanceof Date&&e instanceof Date?t.getTime()-e.getTime():typeof t=="number"&&typeof e=="number"?t-e:typeof t=="boolean"&&typeof e=="boolean"?Number(t)-Number(e):Array.isArray(t)&&Array.isArray(e)?t.length-e.length:String(t).localeCompare(String(e),n,{sensitivity:"base",numeric:!0})}function EU(t,e,n){if(ai(t)){let i=n.get(t.key);return i===void 0?null:(a,o)=>Bv(a,o,i,t.direction)}let r=_n(t.field);return r===null?null:(i,a)=>{let o=r.extract(i,e),s=r.extract(a,e),l=TU(jv(o),jv(s));if(l!==null)return l;let c=r.valueKind===Y.ENUM?Vv(o,r.order)-Vv(s,r.order):_U(o,s,e.locale);return t.direction===ce.DESCENDING?-c:c}}function Wv(t,e,n=Uo){let r=t.rules.map(i=>EU(i,e,n)).filter(i=>i!==null);return r.length===0?null:(i,a)=>{for(let o of r){let s=o(i,a);if(s!==0)return s}return 0}}function Kv(t){let e=[];t.forEachActivity((n,r)=>{n.type===H.PROJECT&&t.getChildren(String(r)).length===0&&e.push(String(r))});for(let n of e)t.setActivityField(n,b.TYPE,si),RU(t,n);return e}function RU(t,e){let n=t.getActivity(e);if(!n||!n.startDate||n.durationHours==null)return;let r=new Date(n.startDate);r.setUTCHours(0,0,0,0);let i=t.getClosestWorkTime({date:r,dir:mt.FUTURE,task:n});if(i.getTime()===n.startDate.getTime())return;let a=t.calculateEndDate({startDate:i,durationHours:n.durationHours,task:n});t.setActivityField(e,b.START_DATE,i),t.setActivityField(e,b.END_DATE,a)}function PU(t){return{...t,id:String(t.id),source:String(t.source),target:String(t.target),type:t.type,lag:Number(t.lag)}}function kU(t){return{days:t.days,hours:t.hours,...t.dates?{dates:t.dates}:{},...t.customWeeks?{customWeeks:t.customWeeks}:{}}}function Yv(t){return{id:String(t.id),worktime:kU(t.worktime)}}function cp(t,e=[]){return[...t.map(Yv),...e.map(Yv)]}function Gv(t,e,n,r=[]){return{activities:[...t],links:e.map(PU),calendars:cp(n,r)}}function qv(t){let e=[],n=[];t.forEachActivity((i,a)=>{i.parentId===null&&e.push(String(a))});let r=e.map(i=>({activityId:i,parent:null,childIds:null,realWork:0})).reverse();for(let i=r.pop();i;i=r.pop()){if(i.childIds===null){let s=t.getActivity(i.activityId);if(!s)continue;let l=[...t.getChildren(i.activityId)],c=l.length===0;i.childIds=l.values(),i.realWork=c?he(s.workHours,s.progress):0}let a=i.childIds.next();if(!a.done){r.push(i,{activityId:String(a.value),parent:i,childIds:null,realWork:0});continue}t.setActivityField(i.activityId,b.REAL_WORK_HOURS,i.realWork),n.push(i.activityId),i.parent&&(i.parent.realWork+=i.realWork)}return n}async function $v(t){let{state:e,sector:n,scheduler:r,skipAutoSchedule:i,now:a}=t;if(Bt(e),n.updateDurationForPrimaveraEndDate&&LU(e),OU(e),qv(e),n.activityCreter===Tt.COST){let s=!1;e.forEachActivity(l=>{s||=Kt(l)!==null}),s&&El(Tt.COST,e)}if(i){Aa(e,n.activityCreter),a&&(Er(e,a),un(e,n.statusCriteria)),Rr(e,n.hoursPerDay),Pr(e,n.hoursPerDay);return}bU(e);let o=await r.schedule({});Ua(e,o),await on(e,void 0,!1),e.markScheduleSettled(),Aa(e,n.activityCreter),a&&(Er(e,a),un(e,n.statusCriteria)),Rr(e,n.hoursPerDay),Pr(e,n.hoursPerDay)}function bU(t){t.forEachActivity(e=>{e.autoScheduling||!e.startDate||e.durationHours==null||t.getChildren(e.id).length>0||(e.endDate=t.calculateEndDate({startDate:e.startDate,durationHours:e.durationHours,task:e}),e.calendarDuration=Je(e))})}function LU(t){t.forEachActivity(e=>{!e.startDate||!e.endDate||(e.durationHours=t.calculateDuration({startDate:e.startDate,endDate:e.endDate,task:e}))})}function OU(t){t.forEachActivity(e=>{let n=e.constraintType;if(!n||!e.constraintDate)return;let r=t.calendarReader.getCalendar(String(e.calendarId));r&&(e.constraintDate=$e(e.constraintDate,r,n))})}function zv(t,e,n=!0){if(t===void 0)return null;let r=C(t),i=oc(r.settings);for(let a of Object.values(r.activities))po(a);return NU(e,r.activities,i,n),{capability:sc(),settings:i,projectState:{plannedStart:r.projectPlannedStart},latestRunLog:r.latestRunLog??null,externalRelationshipIds:r.externalRelationshipIds??[]}}function NU(t,e,n,r){for(let i of t){let a=Object.hasOwn(e,i.id)?e[i.id]:void 0,o=a===void 0?Oi(i):Am(i,a);o!==void 0&&(i.p6=o,At(n,r)&&Object.assign(i,Yl(o,n)))}}var Ke={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function dp(t){return(e,n)=>Wv(e,fr(t.hoursPerDay),n)}function Jv(t){let e=t.clock??null,n=e?.()??null,r=n?Da(n):null,i=t.reporter??Pe,a=Bg(),o=dc({sector:t.sector,activities:t.activities,links:t.links,calendars:t.calendars,baseCalendars:t.baseCalendars},i,a.record),s=t.isDataDateEnabled??(()=>!0),l=zv(t.p6??void 0,o.activities,s()),c=o.sector;c.statusCriteria=ks(t.statusCriteria),c.ganttId=t.ganttId??null;let d=o.calendars,u=o.baseCalendars??[],p=Gv(o.activities,o.links,o.calendars,u),y=dp(c),f=new Xi(p,y,s,i,void 0,e&&(()=>$o(e())));f.hydrateViewState({hiddenIds:o.viewStateSeed.hiddenIds});let m=new Yn(f,i),A=Kv(f);wU(f,l?.capability??null,A),FU(f,l);let g=io({knownIds:o.activities.map(S=>S.id)}),R=oo({seed:n?.getTime()??0,knownIds:o.links.map(S=>S.id)}),P=so({knownIds:o.activities.map(S=>S.uniqueCorrelativeId)}),N=new $i({defaultPrefix:c.customIdPrefix,suffixIncrement:c.customIdIncrement});if(N.populateFromActivities(o.activities),t.baselinePoints&&t.baselinePoints.length>0){let S=u.find(k=>k.baseDefault)?.id??null;_l(f,t.baselinePoints,r,i,S,a.record)}let T=Im(f,t.p6),x=$v({state:f,sector:c,scheduler:m,skipAutoSchedule:t.skipInitialAutoSchedule===!0,now:r??void 0}).then(T);return{dataDateCapability:l?.capability??null,sector:c,state:f,scheduler:m,activityIdGen:g,linkIdGen:R,uidGen:P,customIdTracker:N,calendars:d,baseCalendars:u,clock:e,reporter:i,loadDiagnostics:a.snapshot,externalRelationshipIds:l?.externalRelationshipIds??[],initPromise:x}}function FU(t,e){e!==null&&(t.setDataDateSettings(e.settings),t.setDataDateProjectState(e.projectState),t.setDataDateLatestRunLog(e.latestRunLog))}function wU(t,e,n){if(e!==null)for(let r of n){let i=t.getActivity(r);if(i===null||i.p6!==void 0)continue;let a=e.activityCreated({activity:i,hasCompleteSchedulingState:!0});a.p6!==void 0&&t.setActivityField(r,"p6",a.p6)}}var up=1;function Xv(t){return{sector:C(t.sector),calendars:C([...t.calendars.values()]),baseCalendars:C([...t.baseCalendars]),state:t.state.exportSnapshot(),activityIdCounter:t.activityIdGenerator.snapshot(),linkIdCounter:t.linkIdGenerator.snapshot(),uniqueCorrelativeIdCounter:t.uniqueCorrelativeIdGenerator.snapshot(),customIds:t.customIdTracker.snapshot(),dataDate:t.dataDateCapability===null?null:Pv(t.state,t.externalRelationshipIds)}}function Zv(t,e){if(t.version!==up)throw new Error(`[ScheduleCore] unsupported snapshot version ${String(t.version)}`);let n=e.reporter??Pe,{clock:r}=e,i=Xi.fromSnapshot(t.state,dp(t.sector),e.isDataDateEnabled??(()=>!0),n,r?()=>$o(r()):null),a=t.dataDate;return{state:i,scheduler:new Yn(i,n),sector:t.sector,activityIdGenerator:io({seed:t.activityIdCounter}),linkIdGenerator:oo({seed:t.linkIdCounter}),uniqueCorrelativeIdGenerator:so({seed:t.uniqueCorrelativeIdCounter}),customIdTracker:$i.fromSnapshot(t.customIds),calendars:new Map(t.calendars.map(o=>[o.id,o])),baseCalendars:t.baseCalendars,clock:e.clock??null,reporter:n,loadDiagnostics:()=>[],externalRelationshipIds:[...a?.externalRelationshipIds??[]],dataDateCapability:a?kv(i,a):null}}function vo(t,e){let n=t.getActivity(e);return n?C(n):null}function Qv(t){return t.getAllActivities().map(C)}function tC(t){return t.getAllIds().map(String)}function eC(t,e){t.forEachActivity((n,r)=>e(r))}function nC(t,e){let n=e==="0"?pp(t,"0"):t.getChildren(e),r=[];for(let i of n){let a=t.getActivity(i);a&&r.push(C(a))}return r.sort((i,a)=>(i.correlativeId??0)-(a.correlativeId??0)),r}function pp(t,e){return Ee(e,t)}function rC(t){return t.checkedIds().map(String)}function iC(t,e){if(e==="0"){let n=!1;return t.forEachActivity(r=>{n||=G(r.parentId)}),n}return t.getChildren(e).length>0}function yp(t,e){let n=t.getLink(e);return n?Mt(n):null}function aC(t){return t.getAllLinks().map(e=>Mt(e))}function uc(t){let[e,n]=t.split(":");return Number(e)*60+Number(n??0)}function xU(t){return t.reduce((e,n)=>uc(n)<uc(e)?n:e)}function MU(t){return t.reduce((e,n)=>uc(n)>uc(e)?n:e)}function UU(t){return t.worktime.days.flatMap(e=>Array.isArray(e)?e:e===!0?t.worktime.hours:[])}function oC(t){let e=[...t].find(a=>a.is_default);if(!e)return null;let n=UU(e);if(n.length===0)return null;let r=n.map(a=>a.split("-")[0]),i=n.map(a=>a.split("-")[1]);return{startHour:xU(r),endHour:MU(i)}}function pc(t,e){return{calendars:t.calendarReader,hasCalendar:n=>e.calendars.has(n),getDefaultCalendarId:()=>lp(e.calendars.values()),hierarchy:PI(t),activityReader:RI(t),dateFormat:e.dateFormat??"YYYY-MM-DD",customHours:e.customHours??{},hoursPerDay:e.hoursPerDay}}function sC(t){return Or(t)}var HU=new Set(["freeSlackHours","isCritical"]);function BU(t,e){let n=Object.fromEntries(Object.entries(t.fields??{}).filter(([r])=>!e.has(r)));return t.kind===W.UPDATED&&Object.keys(n).length===0?null:{...t,...t.fields===void 0?{}:{fields:n},after:null}}function jU(t){let e={};for(let[n,r]of Object.entries(t))e[n]={before:Na(r.before),after:Na(r.after)};return e}function VU(t){return{...t,...t.fields===void 0?{}:{fields:jU(t.fields)},...t.before===void 0?{}:{before:ct(t.before)},after:null}}function Co(t){let e=t.links.map(i=>BU(i,HU)).filter(i=>i!==null),n=t.source.kind===qe?{...t.source,items:[],links:[]}:t.source;return{...C({...t,source:n,activities:[],links:e}),activities:t.activities.map(VU)}}function oa(t,e,n,r,i,a,o){return{changeSet:t,beforeSnap:e,beforeLinks:lC(n),afterSnap:r,afterLinks:lC(i),progressFallbackBefore:a,progressFallbackAfter:o}}function lC(t){if(t)return new Map(Array.from(t,([e,n])=>[e,{...n,freeSlackHours:null,isCritical:!1}]))}function uC(t,e){let n=new Map,r=new Map;for(let i of e.activities){if(i.kind!==W.CREATED)continue;let a=t.getActivity(String(i.id));a&&n.set(String(i.id),ct(a))}for(let i of e.links){if(i.kind===W.DELETED)continue;let a=t.getLink(String(i.id));a&&r.set(String(i.id),{...a})}return{afterSnap:n,afterLinks:r}}function pC(t){return t.kind!==I.INLINE_EDIT||!Ga.has(t.column)?null:`inline-edit:${String(t.activityId)}:${t.column}`}function cC(t){return t.changeSet.activities.length===1&&t.changeSet.activities[0]?.kind===W.UPDATED&&t.changeSet.links.length===0&&!t.beforeSnap?.size&&!t.afterSnap?.size}function yC(t,e){if(!cC(t)||!cC(e))return!1;let n=t.changeSet.activities[0],r=e.changeSet.activities[0];return!!n&&!!r&&String(n.id)===String(r.id)}function fC(t,e){let n=t.changeSet.activities[0],r=e.changeSet.activities[0];if(!n||!r)return e;let i=n.fields??{},a=r.fields??{},o={};for(let l of new Set([...Object.keys(i),...Object.keys(a)])){let c=i[l],d=a[l];o[l]={before:c?c.before:d?.before,after:d?d.after:c?.after}}let s={...e.changeSet,activities:[{...r,fields:o}]};return oa(s)}var ir={RECORD:"record",SKIP:"skip",CHECKPOINT_ON_SUCCESS:"checkpoint-on-success",REBASE_ON_SUCCESS:"rebase-on-success"},Wt={BEFORE:"before",AFTER:"after"};function hC(t){return t.kind===I.PERSISTENCE_ACKNOWLEDGE?ir.CHECKPOINT_ON_SUCCESS:t.kind===I.PERSISTENCE_REBASE?ir.REBASE_ON_SUCCESS:t.kind===I.SIR_SYNC||t.kind===I.CALENDAR_RECONCILE||t.kind===I.ACTIVITY_LOOKAHEAD_SYNC||t.kind===I.BASELINE_APPLY||t.kind===I.PONDERATOR_CRITERION_SET||t.kind===I.STATUS_CRITERIA_SET||t.kind===I.ACTIVITY_CLIPBOARD_CLEAR||t.kind===I.ACTIVITY_CLIPBOARD_IMPORT||t.kind===I.ACTIVITY_COPY||t.kind===I.SELECTION_TOGGLE||t.kind===I.SELECTION_REPLACE||t.kind===I.VISIBILITY_SET||t.kind===I.FILTER_SET||t.kind===I.SORT_SET||t.kind===I.VIEW_ATTRIBUTES_SET||t.kind===I.GROUP_SET||t.kind===I.WBS_DEPTH_SET?ir.SKIP:ir.RECORD}function fp(t){for(let e of t.changeSet.activities)if(e.kind===W.CREATED||e.kind===W.DELETED||e.kind===W.UPDATED&&e.fields&&E.CUSTOM_ID in e.fields)return!0;return!1}function hp(t,e,n,r=()=>({})){let i=[],a=[];for(let s of e.changeSet.activities){let l=String(s.id);if(s.kind===W.UPDATED){let c=t.getActivity(l);i.push({id:l,kind:W.UPDATED,fields:dC(s.fields,n),after:c?ct(c):null})}else if(s.kind===W.DELETED)if(n===Wt.BEFORE){let c=t.getActivity(l);i.push({id:l,kind:W.CREATED,after:c?ct(c):null})}else i.push({id:l,kind:W.DELETED,after:null});else if(n===Wt.BEFORE)i.push({id:l,kind:W.DELETED,after:null});else{let c=t.getActivity(l);i.push({id:l,kind:W.CREATED,after:c?ct(c):null})}}for(let s of e.changeSet.links){let l=String(s.id);if(s.kind===W.UPDATED){let c=t.getLink(l);a.push({id:l,kind:W.UPDATED,fields:dC(s.fields,n),after:c?Mt(c):null})}else if(s.kind===W.DELETED)if(n===Wt.BEFORE){let c=t.getLink(l);a.push({id:l,kind:W.CREATED,after:c?Mt(c):null})}else a.push({id:l,kind:W.DELETED,after:null});else if(n===Wt.BEFORE)a.push({id:l,kind:W.DELETED,after:null});else{let c=t.getLink(l);a.push({id:l,kind:W.CREATED,after:c?Mt(c):null})}}let o=(e.changeSet.viewState??[]).map(s=>n===Wt.BEFORE?WU(s):s);return{source:{kind:n===Wt.BEFORE?de.UNDO:de.REDO},activities:i,links:a,calendars:[],trackingEvents:[],effects:[],viewState:o,...r(n)}}function dC(t,e){if(t!=null)return Object.fromEntries(Object.entries(t).map(([n,r])=>[n,e===Wt.BEFORE?{before:C(r.after),after:C(r.before)}:{before:C(r.before),after:C(r.after)}]))}function WU(t){return{activityId:t.activityId,...t.checked?{checked:{before:t.checked.after,after:t.checked.before}}:{},...t.visible?{visible:{before:t.visible.after,after:t.visible.before}}:{}}}function mC(t,e=!1){return t.activities.length>0||t.links.length>0||e||(t.viewState?.length??0)>0||(t.effects?.length??0)>0}function mp(t,e,n){gC(t,e,Wt.BEFORE,n)}function gp(t,e,n){gC(t,e,Wt.AFTER,n)}function gC(t,e,n,r){let i=e.changeSet;for(let o of i.activities)if(o.kind===W.UPDATED){if(!o.fields)continue;for(let[s,l]of Object.entries(o.fields))ve(t,o.id,s,n===Wt.BEFORE?l.before:l.after)}else if(o.kind===W.DELETED)if(n===Wt.BEFORE){let s=e.beforeSnap?.get(String(o.id));if(!s)throw new Error(`undo: missing beforeSnap for resurrecting activity ${o.id}`);t.addActivity(ct(s))}else t.removeActivity(String(o.id));else if(n===Wt.BEFORE)t.removeActivity(String(o.id));else{let s=e.afterSnap?.get(String(o.id));if(!s)throw new Error(`redo: missing afterSnap for re-creating activity ${o.id}`);t.addActivity(ct(s))}for(let o of i.links)if(o.kind===W.UPDATED){if(!o.fields)continue;let s=t.getLink(String(o.id)),l=o.fields[Xt.SOURCE],c=o.fields[Xt.TARGET];s&&(l||c)&&t.setLinkEndpoints(String(o.id),String(l?n===Wt.BEFORE?l.before:l.after:s.source),String(c?n===Wt.BEFORE?c.before:c.after:s.target));for(let[d,u]of Object.entries(o.fields))d===Xt.SOURCE||d===Xt.TARGET||Af(t,String(o.id),d,n===Wt.BEFORE?u.before:u.after)}else if(o.kind===W.DELETED)if(n===Wt.BEFORE){let s=e.beforeLinks?.get(String(o.id));if(!s)throw new Error(`undo: missing beforeLinks for re-adding link ${o.id}`);t.addLink(s)}else t.removeLink(String(o.id));else if(n===Wt.BEFORE)t.removeLink(String(o.id));else{let s=e.afterLinks?.get(String(o.id));if(!s)throw new Error(`redo: missing afterLinks for re-creating link ${o.id}`);t.addLink(s)}for(let o of i.viewState??[])o.checked&&t.setChecked(o.activityId,n===Wt.BEFORE?o.checked.before:o.checked.after),o.visible&&t.setVisible(o.activityId,n===Wt.BEFORE?o.visible.before:o.visible.after);let a=n===Wt.BEFORE?e.progressFallbackBefore:e.progressFallbackAfter;for(let[o,s]of a??[])t.setProgressFallback(o,s);r?.(i,n)}var Ap=["earlyStart","earlyFinish","lateStart","lateFinish","totalSlackHours"],AC=Ap.slice(0,4),IC=t=>t instanceof Date?t.getTime():t,Do=t=>typeof t=="number"?new Date(t):t,yc={encode:IC,decode:Do};function KU(t){if(t===null||typeof t!="object")return!1;let e=Object.keys(t);if(e.length!==Ap.length||e.some((a,o)=>a!==Ap[o]))return!1;let n=t,r=AC.every(a=>n[a]===null||n[a]instanceof Date),i=n.totalSlackHours;return r&&(i===null||typeof i=="number")}var YU={encode:t=>KU(t)?[...AC.map(e=>IC(t[e])),t.totalSlackHours]:t,decode:t=>{if(!Array.isArray(t))return t;let[e,n,r,i,a]=t;return{earlyStart:Do(e),earlyFinish:Do(n),lateStart:Do(r),lateFinish:Do(i),totalSlackHours:a}}},GU=new Map([["startDate",yc],["endDate",yc],["constraintDate",yc],["dateOrigin",yc],["criticalPath",YU]]);function qU(t,e){if(t.fields===void 0)return t;let n={};for(let[r,i]of Object.entries(t.fields)){let a=GU.get(r);n[r]=a?{before:e(a)(i.before),after:e(a)(i.after)}:i}return{...t,fields:n}}function SC(t,e){let n={...t.changeSet,activities:t.changeSet.activities.map(r=>qU(r,e))};return{...t,changeSet:n}}function Gr(t){return SC(t,e=>e.encode)}function fc(t){return SC(t,e=>e.decode)}var $U=100,zU=600,hc=class t{constructor(e=$U){this.maxDepth=e}maxDepth;undoStack=[];redoStack=[];sequence=0;_lastKey=null;_lastTime=0;fork(){let e=new t(this.maxDepth);return e.undoStack.push(...C(this.undoStack)),e.redoStack.push(...C(this.redoStack)),e.sequence=this.sequence,e._lastKey=this._lastKey,e._lastTime=this._lastTime,e}record(e,n=null,r=0){let i=this.undoStack[this.undoStack.length-1];n!=null&&n===this._lastKey&&r-this._lastTime<=zU&&i!==void 0&&yC(i.entry,e)?(i.entry=Gr(fC(fc(i.entry),e)),i.touchedAt=this.touch()):(this.undoStack.push({entry:Gr(e),touchedAt:this.touch()}),this.undoStack.length>this.maxDepth&&this.undoStack.splice(0,this.undoStack.length-this.maxDepth)),this._lastKey=n,this._lastTime=r,this.redoStack.length=0}resetCoalesce(){this._lastKey=null}takeUndo(){let e=this.undoStack.pop();return e?fc(e.entry):null}takeRedo(){let e=this.redoStack.pop();return e?fc(e.entry):null}pushRedo(e){this.redoStack.push({entry:Gr(e),touchedAt:this.touch()})}pushUndo(e){this.undoStack.push({entry:Gr(e),touchedAt:this.touch()})}restoreTakenUndo(e){this.undoStack.push({entry:Gr(e),touchedAt:this.sequence})}restoreTakenRedo(e){this.redoStack.push({entry:Gr(e),touchedAt:this.sequence})}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undoDepth(){return this.undoStack.length}capturePersistenceBoundary(){return this.resetCoalesce(),this.sequence}discardThrough(e){this.removeEntriesThrough(this.undoStack,e),this.removeEntriesThrough(this.redoStack,e),this.resetCoalesce()}applyPersistedIdentities(e,n){let r=new Map(e.map(({id:a,proplannerId:o})=>[String(a),o])),i=new Map(n.map(({id:a,proplannerId:o})=>[String(a),o]));for(let a of[...this.undoStack,...this.redoStack])a.entry=this.withPersistedIdentities(a.entry,r,i)}clear(){this.undoStack.length=0,this.redoStack.length=0,this.resetCoalesce()}touch(){return this.sequence+=1,this.sequence}removeEntriesThrough(e,n){let r=e.filter(({touchedAt:i})=>i>n);e.splice(0,e.length,...r)}withPersistedIdentities(e,n,r){let i=o=>o===void 0?void 0:new Map(Array.from(o,([s,l])=>[s,n.has(s)?{...l,proplannerId:n.get(s)}:l])),a=o=>o===void 0?void 0:new Map(Array.from(o,([s,l])=>[s,r.has(s)?{...l,proplannerId:r.get(s)}:l]));return{...e,beforeSnap:i(e.beforeSnap),afterSnap:i(e.afterSnap),beforeLinks:a(e.beforeLinks),afterLinks:a(e.afterLinks)}}};var mc=t=>(t>>>0).toString(16).padStart(8,"0"),Fe={undefined:1,null:2,string:3,true:4,false:5,number:6,bigint:7,date:8,array:9,object:10,end:11,other:12},CC=new Float64Array(1),vC=new Uint32Array(CC.buffer),JU=(t,e)=>{if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n]!==e[n])return!1;return!0},gc=class{keyCodes=new Map;keyOrders=new Map;first=1779033703;second=3144134277;third=1013904242;fourth=2773480762;mix(e){this.first=this.second^Math.imul(this.first^e,597399067),this.second=this.third^Math.imul(this.second^e,2869860233),this.third=this.fourth^Math.imul(this.third^e,951274213),this.fourth=this.first^Math.imul(this.fourth^e,2716044179)}float(e){CC[0]=e,this.mix(vC[0]),this.mix(vC[1])}key(e){let n=this.keyCodes.get(e);if(n===void 0){n=2166136261;for(let r=0;r<e.length;r+=1)n=Math.imul(n^e.charCodeAt(r),16777619);this.keyCodes.set(e,n)}this.mix(n)}sortedKeys(e){let n=Object.keys(e),r=`${n.length}:${n[0]??""}:${n[n.length-1]??""}`,i=this.keyOrders.get(r);if(i&&JU(i.raw,n))return i.sorted;let a=[...n].sort();return this.keyOrders.set(r,{raw:n,sorted:a}),a}text(e){this.mix(e.length);for(let n=0;n<e.length;n+=1)this.mix(e.charCodeAt(n))}add(e,n){this.addScalar(e)||this.addComposite(e,n)}addScalar(e){if(e===void 0)this.mix(Fe.undefined);else if(e===null)this.mix(Fe.null);else if(typeof e=="string")this.mix(Fe.string),this.text(e);else if(typeof e=="boolean")this.mix(e?Fe.true:Fe.false);else if(typeof e=="number")this.mix(Fe.number),this.float(e);else if(typeof e=="bigint")this.mix(Fe.bigint),this.text(String(e));else if(e instanceof Date)this.mix(Fe.date),this.float(e.getTime());else return!1;return!0}addComposite(e,n){if(Array.isArray(e)){this.mix(Fe.array),this.mix(e.length);for(let r of e)this.add(r)}else if(e instanceof Map||e instanceof Set)this.mix(Fe.other),this.text(JSON.stringify(DC(e)));else if(typeof e=="object"&&e!==null){this.mix(Fe.object);for(let r of this.sortedKeys(e))r!==n&&(this.key(r),this.add(e[r]));this.mix(Fe.end)}else throw new TypeError(`Unsupported canonical value: ${typeof e}`)}digest(){let e=Math.imul(this.third^this.first>>>18,597399067),n=Math.imul(this.fourth^this.second>>>22,2869860233),r=Math.imul(e^this.third>>>17,951274213),i=Math.imul(n^this.fourth>>>19,2716044179);return`${mc(e^n^r^i)}${mc(n^e)}${mc(r^e)}${mc(i^e)}`}},DC=t=>Array.from(t instanceof Map?t:t.values(),e=>JSON.stringify(e,(n,r)=>r instanceof Map||r instanceof Set?DC(r):r)).sort();var XU=["parentId","correlativeId"];function _C(t,e){let n=new Set,r=i=>{let a=e(i);n.add(a===null?"0":String(a))};for(let i of t.activities){let a=String(i.id);if(i.kind===W.CREATED){r(a);continue}if(i.kind===W.DELETED){let l=i.fields;l&&"parentId"in l&&n.add(TC(l.parentId?.before));continue}let o=i.fields;!o||!XU.some(l=>l in o)||(r(a),"parentId"in o&&n.add(TC(o.parentId?.before)))}return n}function TC(t){return t==null?"0":String(t)}var EC=8e3,RC=16,ZU=t=>t===b.CRITICAL_PATH||t===b.IS_CRITICAL||t===b.FREE_SLACK_HOURS;function QU(t){return{hasCriticalPath:Object.hasOwn(t,b.CRITICAL_PATH),criticalPath:t.criticalPath,hasIsCritical:Object.hasOwn(t,b.IS_CRITICAL),isCritical:t.isCritical,hasFreeSlackHours:Object.hasOwn(t,b.FREE_SLACK_HOURS),freeSlackHours:t.freeSlackHours}}function t0(t,e){return!t.hasCriticalPath||!Fa(t.criticalPath,e.criticalPath)?{before:t.hasCriticalPath?rs(t.criticalPath):void 0,after:rs(e.criticalPath)}:null}function PC(t,e,n){return!t||!Object.is(e,n)?{before:t?e:void 0,after:n}:null}function e0(t,e,n){return t===b.CRITICAL_PATH?t0(e,n):t===b.IS_CRITICAL?PC(e.hasIsCritical,e.isCritical,n.isCritical):PC(e.hasFreeSlackHours,e.freeSlackHours,n.freeSlackHours)}function n0(t,e,n){let r={},i=0;for(let a of Object.keys(n)){if(!ZU(a))continue;let o=e0(a,e,n);o!==null&&(r[a]=o,i+=1)}return i===0?null:{id:t,kind:W.UPDATED,fields:r,after:ct(n)}}function r0(t,e,n,r){let i=r.getLink(t);if(!i)return null;let a={};return Object.is(e,i.freeSlackHours)||(a[Xt.FREE_SLACK_HOURS]={before:e,after:i.freeSlackHours}),Object.is(n,i.isCritical)||(a[Xt.IS_CRITICAL]={before:n,after:i.isCritical}),Object.keys(a).length===0?null:{id:t,kind:W.UPDATED,fields:a,after:Mt(i)}}async function kC(t,e,n){let r=[],i=[],a=new Map,o=t.getAllActivities(),s=t.getAllLinks(),l=0;for(let c=0;c<e.activityIds.length;c+=1){l>=EC&&(l=0,await wt()),l+=1;let d=String(e.activityIds[c]),u=Sd(t,o,e,c);if(!u||!gd(u,e,c))continue;let p=QU(u);t.setActivityFields(d,hd(e,c,a)),l+=RC;let y=n0(d,p,u);y&&r.push(y)}for(let c=0;c<e.linkIds.length;c+=1){l>=EC&&(l=0,await wt()),l+=1;let d=String(e.linkIds[c]),u=vd(t,s,e,c);if(!u||!Ad(u,e,c))continue;let p=u.freeSlackHours,y=u.isCritical;l+=RC,Id(t,d,md(e,c));let f=r0(d,p,y,t);f&&i.push(f)}return{source:n,activities:r,links:i,calendars:[],trackingEvents:[]}}function oe(t){if(t==null||t===0)return!1;if(!(typeof t=="number"&&Number.isSafeInteger(t)&&t>0))throw new Error(`invalid proplannerId ${String(t)}`);return!0}function bC(t,e){for(let n of t)oe(n.proplannerId);for(let n of e)oe(n.proplannerId)}function i0(t,e){return{id:t.id,proplannerId:e,parentId:t.parentId,hadBaseline:FC(t)}}function LC(t,e){return{persistable:Ur(t),deletedSnapshot:i0(t,e)}}function a0(t,e,n){let r=t.persistable;r.correlativeId=e;let i=t.deletedSnapshot;return i.hadBaseline=n,t}var FC=t=>t.baselineSnapshot!==null||t.baselinePoints.length>0,o0=Object.freeze(["correlativeId"]),wC="correlativeId",OC=t=>t.length===1&&t[0]===wC,s0=t=>{if(t.kind!==W.UPDATED)return!1;let e=0;for(let n in t.fields){if(n!==wC)return!1;e+=1}return e===1};function NC(t){return{id:t.id,proplannerId:t.proplannerId,source:t.source,target:t.target,lag:t.lag,type:t.type}}var Ip=class{activityIds=[];wholeActivityIds=[];renumbered=[];saved=[];hadBaseline=[];addWhole(e){this.activityIds.push(e),this.wholeActivityIds.push(e)}addRenumbered(e,n,r,i){this.activityIds.push(e),this.renumbered.push({id:e,proplannerId:r,correlativeId:n.correlativeId}),this.saved.push(i),this.hadBaseline.push(FC(n))}},sa=class t{trackingEnabled;initialized=!1;p6TrackingEnabled=!1;dirtyActivityIds=new Set;renumberedActivityIds=new Set;pendingRenumberings=new WeakMap;savedGeneration={};dirtyLinkIds=new Set;dirtyP6ActivityIds=new Set;p6SettingsDirty=!1;p6ProjectStateDirty=!1;initialCalendarRepairIds=new Set;linksAtLastSave=new Map;activitiesAtLastSave=new Map;p6SettingsAtLastSave=null;currentP6Settings=null;p6ProjectStateAtLastSave=null;currentP6ProjectState=null;p6LatestRunLogAtLastSave=null;currentP6LatestRunLog=null;p6LatestRunLogDirty=!1;p6ActivitiesAtLastSave=new Map;constructor(e=!0){this.trackingEnabled=e}fork(){let e=new t(!1);return e.initialized=this.initialized,e}clone(){let e=new t(this.trackingEnabled);for(let n of this.dirtyActivityIds)e.dirtyActivityIds.add(n);for(let n of this.renumberedActivityIds)e.renumberedActivityIds.add(n);e.pendingRenumberings=this.pendingRenumberings,e.savedGeneration=this.savedGeneration;for(let n of this.dirtyLinkIds)e.dirtyLinkIds.add(n);for(let n of this.dirtyP6ActivityIds)e.dirtyP6ActivityIds.add(n);for(let n of this.initialCalendarRepairIds)e.initialCalendarRepairIds.add(n);for(let[n,r]of this.linksAtLastSave)e.linksAtLastSave.set(n,C(r));for(let[n,r]of this.activitiesAtLastSave)e.activitiesAtLastSave.set(n,C(r));for(let[n,r]of this.p6ActivitiesAtLastSave)e.p6ActivitiesAtLastSave.set(n,C(r));return e.initialized=this.initialized,e.p6TrackingEnabled=this.p6TrackingEnabled,e.p6SettingsDirty=this.p6SettingsDirty,e.p6ProjectStateDirty=this.p6ProjectStateDirty,e.p6LatestRunLogDirty=this.p6LatestRunLogDirty,e.p6SettingsAtLastSave=C(this.p6SettingsAtLastSave),e.currentP6Settings=C(this.currentP6Settings),e.p6ProjectStateAtLastSave=C(this.p6ProjectStateAtLastSave),e.currentP6ProjectState=C(this.currentP6ProjectState),e.p6LatestRunLogAtLastSave=C(this.p6LatestRunLogAtLastSave),e.currentP6LatestRunLog=C(this.currentP6LatestRunLog),e}init(e,n,r=null,i=null,a=null){if(this.trackingEnabled){bC(e,n),this.snapshotActivities(e),this.snapshotLinks(n),this.p6SettingsAtLastSave=C(r),this.currentP6Settings=C(r),this.p6SettingsDirty=!1,this.p6ProjectStateAtLastSave=C(i),this.currentP6ProjectState=C(i),this.p6ProjectStateDirty=!1,this.p6LatestRunLogAtLastSave=C(a),this.currentP6LatestRunLog=C(a),this.p6LatestRunLogDirty=!1,this.p6TrackingEnabled=r!==null,this.p6TrackingEnabled&&this.snapshotP6Activities(e);for(let o of e)if(o.assignedDefaultCalendar){let s=String(o.id);this.initialCalendarRepairIds.add(s),this.dirtyActivityIds.add(s)}this.initialized=!0}}acknowledge(e,n,r=[],i=[],a,o,s=this.currentP6Settings,l=this.currentP6ProjectState,c=this.currentP6LatestRunLog){if(!this.trackingEnabled)return;let d=new Map(r.map(({id:A,proplannerId:g})=>[String(A),g])),u=new Map(i.map(({id:A,proplannerId:g})=>[String(A),g])),p=e.map(A=>({...A,proplannerId:d.get(String(A.id))??A.proplannerId})),y=n.map(A=>{let g=u.get(String(A.id));return g===void 0?{...A}:{...A,proplannerId:g}});if(bC(p,y),this.snapshotActivities(p),this.snapshotLinks(y),this.acknowledgeDataDateState(s,l,c),this.p6TrackingEnabled&&this.snapshotP6Activities(p),!a||!o)return;let f=new Map(a.map(A=>[String(A.id),A])),m=new Map(o.map(A=>[String(A.id),A]));for(let A of p){let g=String(A.id);this.activityIsDirty(g,f.get(g)??null)&&this.dirtyActivityIds.add(g)}for(let A of a){let g=String(A.id);this.activityIsDirty(g,A)&&this.dirtyActivityIds.add(g),this.p6TrackingEnabled&&this.p6ActivityIsDirty(g,A)&&this.dirtyP6ActivityIds.add(g)}if(this.p6TrackingEnabled)for(let A of p){let g=String(A.id);this.p6ActivityIsDirty(g,f.get(g)??null)&&this.dirtyP6ActivityIds.add(g)}for(let A of y){let g=String(A.id);this.linkIsDirty(g,m.get(g)??null)&&this.dirtyLinkIds.add(g)}for(let A of o){let g=String(A.id);this.linkIsDirty(g,A)&&this.dirtyLinkIds.add(g)}}pendingCheckpoint(e){let n=new Ip;for(let i of this.dirtyActivityIds)this.collectPending(n,i,e);for(let i of this.dirtyP6ActivityIds)this.dirtyActivityIds.has(i)||n.addWhole(i);let r={activityIds:n.activityIds,linkIds:[...this.dirtyLinkIds],...n.renumbered.length>0?{renumbered:n.renumbered}:{}};return n.renumbered.length>0&&this.pendingRenumberings.set(r,{savedGeneration:this.savedGeneration,wholeActivityIds:n.wholeActivityIds,saved:n.saved,hadBaseline:n.hadBaseline}),{pending:r,wholeActivityIds:n.wholeActivityIds}}collectPending(e,n,r){let i=this.renumberedActivityIds.has(n)?r(n):null,a=this.activitiesAtLastSave.get(n),o=i?.proplannerId;!this.dirtyP6ActivityIds.has(n)&&i!==null&&a!==void 0&&oe(o)?e.addRenumbered(n,i,o,a):e.addWhole(n)}renumberingOf(e){if(e.renumbered===void 0)return null;let n=this.pendingRenumberings.get(e);if(n===void 0)throw new Error("persistence checkpoint with renumbered activities was not read from this schedule");return n}acknowledgePending(e,n,r,i,a,o,s,l,c){if(!this.trackingEnabled)return;let d=new Map(i.map(({id:P,proplannerId:N})=>[String(P),N])),u=new Map(a.map(({id:P,proplannerId:N})=>[String(P),N])),p=new Map(n.map(P=>{let N=String(P.id),T=d.get(N);return[N,T===void 0?P:{...P,proplannerId:T}]})),y=new Map(r.map(P=>{let N=u.get(String(P.id));return[String(P.id),N===void 0?{...P}:{...P,proplannerId:N}]}));for(let P of p.values())oe(P.proplannerId);for(let P of y.values())oe(P.proplannerId);let f=new Set(this.dirtyActivityIds);for(let P of this.dirtyP6ActivityIds)f.add(P);for(let P of e.activityIds)f.add(P);let m=new Set([...this.dirtyLinkIds,...e.linkIds]),A=this.renumberingOf(e),g=A?.savedGeneration===this.savedGeneration,R=this.replaceSavedActivities(A?.wholeActivityIds??e.activityIds,p);A!==null&&this.replaceRenumberedSaves(e.renumbered??[],A,g?null:R),this.replaceSavedLinks(e.linkIds,y),this.acknowledgeDataDateState(s,l,c),this.recheckDirty(f,m,o,R)}replaceSavedActivities(e,n){let r=new Set;for(let i of e){this.initialCalendarRepairIds.delete(i),r.add(i);let a=n.get(i);if(!a||!oe(a.proplannerId)){this.activitiesAtLastSave.delete(i),this.p6ActivitiesAtLastSave.delete(i);continue}this.activitiesAtLastSave.set(i,LC(a,a.proplannerId)),this.p6TrackingEnabled&&this.replaceSavedP6(i,a)}return this.savedGeneration={},r}replaceRenumberedSaves(e,n,r){e.forEach((i,a)=>{let o=n.saved[a];o!==void 0&&(this.initialCalendarRepairIds.delete(i.id),this.activitiesAtLastSave.set(i.id,a0(o,i.correlativeId,n.hadBaseline[a]===!0)),r?.add(i.id))})}replaceSavedP6(e,n){if(n.p6===void 0){this.p6ActivitiesAtLastSave.delete(e);return}this.p6ActivitiesAtLastSave.set(e,C(n.p6))}replaceSavedLinks(e,n){for(let r of e){let i=n.get(r);i&&oe(i.proplannerId)?this.linksAtLastSave.set(r,NC(i)):this.linksAtLastSave.delete(r)}}recheckDirty(e,n,r,i){let a=this.renumberedActivityIds;this.renumberedActivityIds=new Set,this.dirtyActivityIds.clear(),this.dirtyP6ActivityIds.clear(),this.dirtyLinkIds.clear();for(let o of e){let s=r.activity(o);a.has(o)&&!i.has(o)&&this.recordRenumbering(o,s)||this.recheckActivity(o,s),this.p6TrackingEnabled&&this.p6ActivityIsDirty(o,s)&&this.dirtyP6ActivityIds.add(o)}for(let o of n)this.linkIsDirty(o,r.link(o))&&this.dirtyLinkIds.add(o)}recheckActivity(e,n){let r=this.activitiesAtLastSave.get(e);if(!(n!==null&&r!==void 0&&!this.initialCalendarRepairIds.has(e)&&oe(n.proplannerId))){this.activityIsDirty(e,n)&&this.dirtyActivityIds.add(e);return}let a=je(n,r.persistable);a.length!==0&&(this.dirtyActivityIds.add(e),OC(a)&&this.renumberedActivityIds.add(e))}acknowledgeDataDateState(e,n,r){this.p6SettingsAtLastSave=C(e),this.p6SettingsDirty=Qn(this.currentP6Settings,this.p6SettingsAtLastSave),this.p6ProjectStateAtLastSave=C(n),this.p6ProjectStateDirty=Qn(this.currentP6ProjectState,this.p6ProjectStateAtLastSave),this.p6LatestRunLogAtLastSave=C(r),this.p6LatestRunLogDirty=Qn(this.currentP6LatestRunLog,this.p6LatestRunLogAtLastSave)}snapshotActivities(e){if(this.trackingEnabled){this.savedGeneration={},this.activitiesAtLastSave.clear(),this.dirtyActivityIds.clear(),this.renumberedActivityIds.clear(),this.initialCalendarRepairIds.clear();for(let n of e){let r=String(n.id);if(!oe(n.proplannerId)){this.dirtyActivityIds.add(r);continue}let i=LC(n,n.proplannerId);this.activitiesAtLastSave.set(String(n.id),i),no(n,i.persistable)&&this.dirtyActivityIds.add(r)}}}snapshotLinks(e){if(this.trackingEnabled){this.linksAtLastSave.clear(),this.dirtyLinkIds.clear();for(let n of e){let r=String(n.id);if(!oe(n.proplannerId)){this.dirtyLinkIds.add(r);continue}this.linksAtLastSave.set(String(n.id),NC(n))}}}recordChanges(e,n,r,i,a){if(!(!this.trackingEnabled||!this.initialized)){for(let o of e){let s=String(o.id),l=r(s);a!==void 0&&!a.has(s)&&s0(o)&&this.recordRenumbering(s,l)||this.recordActivityChange(s,l)}for(let o of n){let s=String(o.id),l=i(s);this.linkIsDirty(s,l)?this.dirtyLinkIds.add(s):this.dirtyLinkIds.delete(s)}}}recordActivityChange(e,n){this.renumberedActivityIds.delete(e),this.activityIsDirty(e,n)?this.dirtyActivityIds.add(e):this.dirtyActivityIds.delete(e),this.p6TrackingEnabled&&(this.p6ActivityIsDirty(e,n)?this.dirtyP6ActivityIds.add(e):this.dirtyP6ActivityIds.delete(e))}recordRenumbering(e,n){let r=!this.dirtyActivityIds.has(e)||this.renumberedActivityIds.has(e),i=this.activitiesAtLastSave.get(e);return!r||n===null||i===void 0?!1:(n.correlativeId??null)===(i.persistable.correlativeId??null)?(this.dirtyActivityIds.delete(e),this.renumberedActivityIds.delete(e),!0):(this.dirtyActivityIds.add(e),this.renumberedActivityIds.add(e),!0)}recordP6Settings(e){!this.trackingEnabled||!this.initialized||(this.currentP6Settings=C(e),this.p6SettingsDirty=Qn(this.currentP6Settings,this.p6SettingsAtLastSave))}recordP6ProjectState(e){!this.trackingEnabled||!this.initialized||(this.currentP6ProjectState=C(e),this.p6ProjectStateDirty=Qn(this.currentP6ProjectState,this.p6ProjectStateAtLastSave))}recordP6LatestRunLog(e){!this.trackingEnabled||!this.initialized||(this.currentP6LatestRunLog=C(e),this.p6LatestRunLogDirty=Qn(this.currentP6LatestRunLog,this.p6LatestRunLogAtLastSave))}modifiedP6Settings(){return this.p6SettingsIsDirty()?C(this.currentP6Settings):null}modifiedP6LatestRunLog(){return this.p6LatestRunLogDirty?{latestRunLog:C(this.currentP6LatestRunLog)}:null}modifiedP6Activities(e){return!this.trackingEnabled||!this.initialized?new Map:zI(this.dirtyP6ActivityIds,e)}activityIsDirty(e,n){let r=this.activitiesAtLastSave.get(e);return n===null?r!==void 0:this.initialCalendarRepairIds.has(e)||!oe(n.proplannerId)||r===void 0||no(n,r.persistable)}linkIsDirty(e,n){let r=this.linksAtLastSave.get(e);return n===null?r!==void 0:!oe(n.proplannerId)||r===void 0||Dl(r,n)}acknowledgePersistedLookahead(e,n){if(!this.trackingEnabled||!this.initialized)return;let r=e.map(i=>{let a=typeof i=="string"?i:String(i.id),o=n(a),s=this.activitiesAtLastSave.get(a);if(o===null||s===void 0)throw new Error(`unknown persisted activity "${a}"`);return{activityId:a,acknowledgesLookahead:typeof i=="string"||!!i.fields?.isLookahead,acknowledgesProgress:typeof i!="string"&&!!i.fields?.progress,current:o,saved:s}});for(let{activityId:i,acknowledgesLookahead:a,acknowledgesProgress:o,current:s,saved:l}of r){let c={...l.persistable,...a?{isLookahead:s.isLookahead}:{},...o?{progress:s.progress,autoScheduling:s.autoScheduling}:{}};this.activitiesAtLastSave.set(i,{...l,persistable:c}),this.savedGeneration={},this.renumberedActivityIds.delete(i),this.initialCalendarRepairIds.has(i)||!oe(s.proplannerId)||no(s,c)?this.dirtyActivityIds.add(i):this.dirtyActivityIds.delete(i)}}hasCheckpointActivityId(e){return this.activitiesAtLastSave.has(e)}knowsPersistedActivity(e){return!this.trackingEnabled||this.activitiesAtLastSave.has(e)}hasCheckpointLinkId(e){return this.linksAtLastSave.has(e)}rebaseBaseline(e,n){return{activities:e.map(r=>{let i=this.p6ActivitiesAtLastSave.get(String(r.id));return i===void 0?r:{...r,p6:C(i)}}),links:n,p6Settings:C(this.p6SettingsAtLastSave),p6ProjectState:C(this.p6ProjectStateAtLastSave),p6LatestRunLog:C(this.p6LatestRunLogAtLastSave)}}checkpointActivity(e){return this.activitiesAtLastSave.get(e)?.persistable??null}checkpointLink(e){return this.linksAtLastSave.get(e)??null}checkpointActivityIds(){return[...this.activitiesAtLastSave.keys()]}checkpointLinkIds(){return[...this.linksAtLastSave.keys()]}tracksPersistence(){return this.trackingEnabled}hasUnsavedChanges(){return this.trackingEnabled&&this.initialized&&(this.dirtyActivityIds.size>0||this.dirtyLinkIds.size>0||this.p6TrackingEnabled&&(this.dirtyP6ActivityIds.size>0||this.p6SettingsIsDirty()||this.p6ProjectStateDirty||this.p6LatestRunLogDirty))}p6SettingsIsDirty(){return this.p6SettingsDirty}snapshotP6Activities(e){this.dirtyP6ActivityIds.clear(),qI(this.p6ActivitiesAtLastSave,e)}p6ActivityIsDirty(e,n){return $I(this.p6ActivitiesAtLastSave.get(e),n)}newActivities(e){if(!this.trackingEnabled||!this.initialized)return[];let n=[];for(let r of this.dirtyActivityIds){let i=e(r);i!==null&&!oe(i.proplannerId)&&n.push(i)}return n}newLinks(e){if(!this.trackingEnabled||!this.initialized)return[];let n=[];for(let r of this.dirtyLinkIds){let i=e(r);i!==null&&!oe(i.proplannerId)&&n.push(i)}return n}deletedActivities(e){if(!this.trackingEnabled||!this.initialized)return[];let n=[];for(let r of this.dirtyActivityIds){let i=this.activitiesAtLastSave.get(r);i&&e(r)===null&&n.push({...i.deletedSnapshot})}return n}deletedLinks(e){if(!this.trackingEnabled||!this.initialized)return[];let n=[];for(let r of this.dirtyLinkIds){let i=this.linksAtLastSave.get(r);i&&e(r)===null&&n.push({...i})}return n}modifiedActivities(e){if(!this.trackingEnabled||!this.initialized)return[];let n=[];for(let r of this.dirtyActivityIds){let i=e(r);if(i===null||!oe(i.proplannerId))continue;let a=this.activitiesAtLastSave.get(r);(a===void 0||this.initialCalendarRepairIds.has(r)||no(i,a.persistable))&&n.push(i)}return n}modifiedActivityFields(e){let n=new Map;if(!this.trackingEnabled||!this.initialized)return n;for(let r of this.dirtyActivityIds){let i=e(r),a=this.activitiesAtLastSave.get(r);if(!i||!a)continue;let o=je(i,a.persistable);o.length>0&&n.set(r,o)}return n}isModifiedSince(e,n,r){return n===void 0||this.initialCalendarRepairIds.has(e)||r.length>0}changedFieldsSinceSave(e,n,r){return this.renumberedActivityIds.has(e)?o0:r===void 0?[]:je(n,r.persistable)}modifiedActivityChanges(e){let n=[],r=new Map,i=[];if(!this.trackingEnabled||!this.initialized)return{activities:n,fields:r,renumbered:i};for(let a of this.dirtyActivityIds){let o=e(a);if(o===null)continue;let s=this.activitiesAtLastSave.get(a),l=this.changedFieldsSinceSave(a,o,s),c=o.proplannerId,d=oe(c);if(d&&OC(l)){i.push({id:a,proplannerId:c,correlativeId:o.correlativeId});continue}l.length>0&&r.set(a,l),d&&this.isModifiedSince(a,s,l)&&n.push(o)}return{activities:n,fields:r,renumbered:i}}modifiedLinks(e){if(!this.trackingEnabled||!this.initialized)return[];let n=[];for(let r of this.dirtyLinkIds){let i=e(r);if(i===null||!oe(i.proplannerId))continue;let a=this.linksAtLastSave.get(r);(a===void 0||Dl(a,i))&&n.push(i)}return n}clear(){this.initialized=!1,this.savedGeneration={},this.p6TrackingEnabled=!1,this.dirtyActivityIds.clear(),this.renumberedActivityIds.clear(),this.dirtyLinkIds.clear(),this.dirtyP6ActivityIds.clear(),this.initialCalendarRepairIds.clear(),this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear(),this.p6ActivitiesAtLastSave.clear(),this.p6SettingsAtLastSave=null,this.currentP6Settings=null,this.p6SettingsDirty=!1,this.p6ProjectStateAtLastSave=null,this.currentP6ProjectState=null,this.p6ProjectStateDirty=!1}};function Sp(t,e){let n=new Map(t.map(o=>[String(o.id),o])),r=new Map(e.map(o=>[String(o.id),o])),i=[...new Set([...n.keys(),...r.keys()])].sort(),a=[];for(let o of i){let s=r.get(o),l=n.get(o);if(l===void 0){a.push({id:o,kind:W.DELETED,after:null});continue}if(s===void 0){a.push({id:o,kind:W.CREATED,after:C(l)});continue}let c=l0(s,l);Object.keys(c).length>0&&a.push({id:o,kind:W.UPDATED,fields:c,after:C(l)})}return a}function l0(t,e){let n={},r=[...new Set([...Object.keys(t),...Object.keys(e)])].sort();for(let i of r)Jt(t[i])!==Jt(e[i])&&(n[i]={before:C(t[i]),after:C(e[i])});return n}function c0(t,e){let n=new Set(e.selectedIds.map(String)),r=new Set(t.selectedIds.map(String)),i=new Set(e.hiddenIds.map(String)),a=new Set(t.hiddenIds.map(String)),o=t.activities.map(({id:l})=>String(l)).sort(),s=[];for(let l of o){let c=n.has(l),d=r.has(l),u=!i.has(l),p=!a.has(l);c===d&&u===p||s.push({activityId:l,...c===d?{}:{checked:{before:c,after:d}},...u===p?{}:{visible:{before:u,after:p}}})}return s}function vp(t,e){let n=Jt(t.order)!==Jt(e.order);return{source:{kind:de.INIT},activities:Sp(t.activities,e.activities),links:Sp(t.links,e.links),calendars:Sp(t.calendars,e.calendars),trackingEvents:[],effects:[],viewState:c0(t,e),...n?{order:C(t.order)}:{}}}function xC(t){let e=t.state.fork(),n=C(t.sector),r=t.history.fork(),i=t.persistence.clone(),a=t.activityIds.snapshot(),o=t.linkIds.snapshot(),s=t.correlatives.snapshot(),l=t.customIds.captureRestorePoint();return{history:r,persistence:i,restore:()=>{t.state.restoreFork(e);for(let c of Object.keys(t.sector))Object.hasOwn(n,c)||Reflect.deleteProperty(t.sector,c);Object.assign(t.sector,n),t.scheduler.invalidateAllCaches(),t.activityIds.restore(a),t.linkIds.restore(o),t.correlatives.restore(s),l()}}}function MC(t,e){let n=t.find(r=>r.type===H.PROJECT);if(n!==void 0)return n.calendarId;for(let r of e)if(r.is_default)return r.id;return null}function UC(t,e,n){let r=n.getCalendar(e);return r===null?null:ic(t,r)}var Cp=Symbol("ScheduleCore.fork.source"),d0=100;function u0(t){if(!Number.isInteger(t.offset)||t.offset<0)throw new RangeError("Ending activity offset must be a non-negative integer");if(!Number.isInteger(t.limit)||t.limit<1||t.limit>d0)throw new RangeError("Ending activity limit must be an integer from 1 to 100")}var Dp=Symbol("ScheduleCore.snapshot.source");function p0(t){return{source:t,activities:[],links:[],calendars:[],trackingEvents:[]}}function y0(t,e,n){if(t.kind===I.PERSISTENCE_ACKNOWLEDGE)return{checkpoint:t.checkpoint,historyBoundary:t.checkpoint?.historyBoundary,persistedActivities:t.activities,persistedLinks:t.links,clearsHistory:!1,retainsHistory:t.retainHistory===!0};if(t.kind===I.PERSISTENCE_REBASE){let r=e.__rebaseCheckpoint;if(r===void 0)throw new Error("rebase-on-success requires a rebase checkpoint");return{checkpoint:n.rebaseBaseline(r.activities,r.links),historyBoundary:void 0,persistedActivities:void 0,persistedLinks:void 0,clearsHistory:!0,retainsHistory:!1}}throw new Error("checkpoint-on-success requires persistence acknowledge")}function f0(t){return t.kind===I.PERSISTENCE_ACKNOWLEDGE||t.kind===I.PERSISTENCE_REBASE||t.kind===I.ACTIVITY_LOOKAHEAD_SYNC&&t.acknowledgePersistedLookahead===!0}function h0(t){for(let e of t.activities)if(e.kind===W.DELETED||e.kind===W.UPDATED&&e.fields!==void 0&&"parentId"in e.fields)return!0;return!1}function m0(t,e){let n=[];for(let r of t.activities){let i=e.getActivity(r.id);if(i===null)return null;n.push(i)}return n}function g0(t,e,n){if(t===null||t.filter!==e)return!1;let r=t.context.hoursPerDay===n.hoursPerDay,i=t.context.locale===n.locale;return r&&i}var la=class t{activities;cells;links;calendars;selection;view;baselines;impactRequests;persistence;history;projection;criticalPath;diagnostics;dataDates=uS({getSettings:()=>this._getP6Settings(),getProjectState:()=>this._getP6ProjectState(),getLatestRunLog:()=>this._getP6LatestRunLog(),getScheduleStateFingerprint:()=>this._getP6ScheduleStateFingerprint(),getDefaultSettings:()=>C(aa()),getScheduleReadiness:e=>this._getP6ScheduleReadiness(e),searchEndingActivities:e=>this._searchP6EndingActivities(e),getEndingActivityOption:e=>this._getP6EndingActivityOption(e),resolveMustFinishByDefault:e=>this._resolveP6MustFinishByDefault(e),updateSettings:e=>this._updateP6Settings(e),updateActivity:(e,n,r)=>this._updateP6Activity(e,n,r?.at),schedule:(e,n)=>this._scheduleP6(e,n?.at)});_activityClipboard={value:null};_cellClipboard={value:null};_status=Ke.READY;coreRuntime;_isFork;_undo=new hc;_opQueue=Promise.resolve();_scheduleRevision=0;_stateRevision=0;_canonicalFingerprintCache=null;_p6ScheduleStateFingerprintCache=null;_pendingScheduleRevision=0;_criticalPathRevision=-1;_criticalPathUsesDataDate=!1;_activeCriticalPath=null;constructor(e){if(Object.assign(this,Np(this)),Dp in e){let{snapshot:i,options:a}=e[Dp];this._isFork=!1,this.coreRuntime=Zv(i,a),this._saveTracker=new sa(a.trackPersistence!==!1),this._retainCriticalPathResult=a.retainCriticalPathResult!==!1,this._lastOperationAt=i.lastOperationAt,i.criticalPathSettled&&(this._criticalPathRevision=this._scheduleRevision),this._initPromise=Promise.resolve().then(()=>this._initSaveTracker()),this._criticalPathReady=this._trackCriticalPathJob(this._initPromise.then(()=>this._startCriticalPathForCurrentRevision())),this._ready=this._initPromise;return}if(Cp in e){this._isFork=!0;let i=e[Cp],a=i.coreRuntime.state.fork();this.coreRuntime={state:a,scheduler:new Yn(a,i.coreRuntime.reporter),sector:C(i.coreRuntime.sector),activityIdGenerator:i.coreRuntime.activityIdGenerator.fork(),linkIdGenerator:i.coreRuntime.linkIdGenerator.fork(),uniqueCorrelativeIdGenerator:i.coreRuntime.uniqueCorrelativeIdGenerator.fork(),customIdTracker:i.coreRuntime.customIdTracker.fork(),calendars:new Map(Array.from(i.coreRuntime.calendars,([o,s])=>[o,C(s)])),baseCalendars:C(i.coreRuntime.baseCalendars),clock:i.coreRuntime.clock,reporter:i.coreRuntime.reporter,loadDiagnostics:i.coreRuntime.loadDiagnostics,externalRelationshipIds:C(i.coreRuntime.externalRelationshipIds),dataDateCapability:i.coreRuntime.dataDateCapability},this._activityClipboard.value=C(i._activityClipboard.value),this._cellClipboard.value=C(i._cellClipboard.value),this._undo=i._undo.fork(),this._saveTracker=i._saveTracker.fork(),this._retainCriticalPathResult=i._retainCriticalPathResult,this._lastOperationAt=i._lastOperationAt,this._scheduleRevision=i._scheduleRevision,this._stateRevision=i._stateRevision,this._canonicalFingerprintCache=i._canonicalFingerprintCache,this._p6ScheduleStateFingerprintCache=i._p6ScheduleStateFingerprintCache,this._pendingScheduleRevision=i._scheduleRevision,this._criticalPathRevision=i._criticalPathRevision,this._criticalPathUsesDataDate=i._criticalPathUsesDataDate,this._initPromise=Promise.resolve(),this._criticalPathReady=Promise.resolve(null),this._ready=this._initPromise;return}this._isFork=!1,this._saveTracker=new sa(e.trackPersistence!==!1),this._retainCriticalPathResult=e.retainCriticalPathResult!==!1;let n=Jv(e);this.coreRuntime={state:n.state,scheduler:n.scheduler,sector:n.sector,activityIdGenerator:n.activityIdGen,linkIdGenerator:n.linkIdGen,uniqueCorrelativeIdGenerator:n.uidGen,customIdTracker:n.customIdTracker,clock:n.clock,calendars:new Map(n.calendars.map(i=>[i.id,i])),baseCalendars:n.baseCalendars,reporter:n.reporter,loadDiagnostics:n.loadDiagnostics,externalRelationshipIds:C(n.externalRelationshipIds),dataDateCapability:n.dataDateCapability},this._initPromise=n.initPromise.then(()=>this._initSaveTracker()),this._criticalPathReady=this._trackCriticalPathJob(this._initPromise.then(()=>this._startCriticalPathForCurrentRevision()));let r=e.criticalPathOnLoad===!0;this._ready=r?this._criticalPathReady.then(()=>{}):this._initPromise}_initSaveTracker(){this._status!==Ke.DESTROYED&&this._saveTracker.init(this.coreRuntime.state.getAllActivities(),this.getAllLinksView(),this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.dataDateProjectState(),this.coreRuntime.state.dataDateLatestRunLog())}exportSnapshot(){return this._enqueue(async()=>(this.assertReady(),{version:up,...Xv(this.coreRuntime),criticalPathSettled:this.isCriticalPathSettled(),lastOperationAt:this._lastOperationAt?new Date(this._lastOperationAt):null}))}static fromSnapshot(e,n={}){return new t({[Dp]:{snapshot:e,options:n}})}get ready(){return this._ready}fork(){return this._enqueue(async()=>(await this._ready,this.assertReady(),new t({[Cp]:this})))}get criticalPathReady(){let e=this._criticalPathReady;return e.then(()=>this._releaseCriticalPathResult(e),()=>{}),e}_trackCriticalPathJob(e){return e.then(()=>{this._criticalPathReady===e&&(this._retainCriticalPathResult?this._settledCriticalPathJob=e:this._criticalPathReady=Promise.resolve(null))},()=>{}),e}_releaseCriticalPathResult(e){this._criticalPathReady===e&&(this._criticalPathReady=Promise.resolve(null),this._settledCriticalPathJob=null)}get status(){return this._status}getSector(){return C(this.coreRuntime.sector)}getLoadDiagnostics(){return this.assertReady(),this.coreRuntime.loadDiagnostics()}getActivityView(e){return this.assertReady(),vo(this.coreRuntime.state,e)}calculateCalendarEndDate(e){this.assertReady();let n=this.coreRuntime.state.getActivity(e.activityId);return n?this.coreRuntime.state.calculateEndDate({startDate:e.startDate,durationHours:e.durationHours,task:n}):null}calculateCalendarDuration(e){this.assertReady();let n=this.coreRuntime.state.getActivity(e.activityId);return n?this.coreRuntime.state.calculateDuration({startDate:e.startDate,endDate:e.endDate,task:n}):null}getClosestCalendarWorkTime(e){this.assertReady();let n=this.coreRuntime.state.getActivity(e.activityId);return n?this.coreRuntime.state.getClosestWorkTime({date:e.date,dir:e.direction,task:n}):null}getProgressEditability(e){this.assertReady();let n=vo(this.coreRuntime.state,e);if(!n)return null;let r=pc(this.coreRuntime.state,{calendars:this.coreRuntime.calendars,hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat});return fi.canEdit(n,r.hierarchy)}getDateGestureEditability(e,n){this.assertReady();let r=vo(this.coreRuntime.state,e);return r?Fr(r.p6,this.coreRuntime.state.dataDateSettings(),n,this.coreRuntime.state.isDataDateEnabled()):null}getColumnEditability(e,n){this.assertReady();let r=vo(this.coreRuntime.state,e),i=ge(n);if(!r||!i)return null;let a=pc(this.coreRuntime.state,{calendars:this.coreRuntime.calendars,hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat});return sl(i.canEdit(r,a.hierarchy),r,this._getP6Settings(),n,this.coreRuntime.state.isDataDateEnabled())}createDateGesturePreview(e){this.assertReady();let n=this._scheduleRevision;return Lm(this.coreRuntime.state,e,()=>{if(this.assertReady(),this._scheduleRevision!==n)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),Qv(this.coreRuntime.state)}getIndentTargetParentIds(e){this.assertReady();let n=Vi(e.map(r=>String(r)),this.coreRuntime.state);return[...new Set(n.allowedMoves.map(r=>String(r.newParentId)))]}getLeafParentIdsPromotedBy(e){return this.assertReady(),ag(e,this.coreRuntime.state,this._activityClipboard.value!==null)}getLookaheadConfirmation(e,n={}){return this.assertReady(),og(e,n,this.coreRuntime.state,this._activityClipboard.value!==null)}getChildrenView(e){return this.assertReady(),nC(this.coreRuntime.state,e)}getLinkView(e){return this.assertReady(),yp(this.coreRuntime.state,e)}getLinksForActivityView(e){this.assertReady();let n=this.coreRuntime.state,r=[],i=new Set,a=o=>{if(i.has(o))return;i.add(o);let s=yp(n,o);s&&r.push(s)};for(let o of n.getOutgoingLinkIds(e))a(o);for(let o of n.getIncomingLinkIds(e))a(o);return r}getAllLinksView(){return this.assertReady(),aC(this.coreRuntime.state)}auditEffectiveGraph(){this.assertReady();let e=this.coreRuntime.state,n=e.getAllLinks(),r=Vn(e,n),i=Ci(r),a=0;for(let o of i)o.length>a&&(a=o.length);return{activityCount:e.getAllIds().length,logicalLinkCount:n.length,effectiveEdgeCount:r.length,circularComponents:i,largestComponentSize:a}}getProperty(e,n){this.assertReady();let r=this.coreRuntime.state.getActivity(e);return r?C(r[n]):null}getAllIds(){return this.assertReady(),tC(this.coreRuntime.state)}forEachActivityId(e){this.assertReady(),eC(this.coreRuntime.state,e)}getChildrenIds(e){return this.assertReady(),pp(this.coreRuntime.state,e)}getSelectedActivityIds(){return this.assertReady(),rC(this.coreRuntime.state)}getActivityClipboardView(){return this.assertReady(),C(this._activityClipboard.value)}getHiddenActivityIds(){return this.assertReady(),this.coreRuntime.state.hiddenIds().map(String)}getVisibleActivityIds(){this.assertReady();let e=new Set(this.coreRuntime.state.hiddenIds().map(String));return this.coreRuntime.state.getAllIds().map(String).filter(n=>!e.has(n))}getActiveFilter(){return this.assertReady(),C(this.coreRuntime.state.getActiveFilter())}getActiveOrder(){return this.assertReady(),C(this.coreRuntime.state.getActiveOrder())}getVisualOrderIds(){return this.assertReady(),[...this.coreRuntime.state.getVisualOrderIds()]}getVisualRows(){return this.assertReady(),[...this.coreRuntime.state.getVisualRows()]}getActiveGroup(){return this.assertReady(),C(this.coreRuntime.state.getGroup())}getWbsDepth(){return this.assertReady(),this.coreRuntime.state.getWbsDepth()}hasChild(e){return this.assertReady(),iC(this.coreRuntime.state,e)}getCalendar(e){this.assertReady();let n=this.coreRuntime.calendars.get(e);return n?C(n):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),e=>C(e))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(e=>C(e))}isCustomIdInUse(e,n=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(e,n)}getProjectWorkHours(){return this.assertReady(),oC(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(e=>this.coreRuntime.state.getLink(e)).map(C)}getNewLinks(){return this.assertReady(),this._saveTracker.newLinks(e=>this.coreRuntime.state.getLink(e)).map(C)}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(e=>this.coreRuntime.state.getActivity(e)).map(Oa)}getModifiedActivityFields(){return this.assertReady(),this._saveTracker.modifiedActivityFields(e=>this.coreRuntime.state.getActivity(e))}getModifiedActivityChanges(){this.assertReady();let e=this._saveTracker.modifiedActivityChanges(n=>this.coreRuntime.state.getActivity(n));return{...e,activities:e.activities.map(Oa)}}getNewActivities(){return this.assertReady(),this._saveTracker.newActivities(e=>this.coreRuntime.state.getActivity(e)).map(Oa)}hasUnsavedChanges(){return this.assertReady(),this._saveTracker.hasUnsavedChanges()}getModifiedDataDateSettings(){return this.assertReady(),this._saveTracker.modifiedP6Settings()}getModifiedDataDateLatestRunLog(){return this.assertReady(),this._saveTracker.modifiedP6LatestRunLog()}getModifiedDataDateActivities(){return this.assertReady(),this._saveTracker.modifiedP6Activities(e=>this.coreRuntime.state.getActivity(e))}getScheduleRevision(){return this._scheduleRevision}getStateRevision(){return this._stateRevision}capturePersistenceHistoryBoundary(){return this.assertReady(),this._undo.capturePersistenceBoundary()}readPersistenceCheckpoint(e={}){this.assertReady();let n=e.pendingOnly?this._saveTracker.pendingCheckpoint(r=>this.coreRuntime.state.getActivity(r)):null;return{...n?{activities:n.wholeActivityIds.flatMap(r=>{let i=this.coreRuntime.state.getActivity(r);return i?[Oa(i)]:[]}),links:n.pending.linkIds.flatMap(r=>{let i=this.getLinkView(r);return i?[i]:[]}),pending:n.pending}:{activities:this.getAllActivitiesView(),links:this.getAllLinksView()},historyBoundary:this.capturePersistenceHistoryBoundary(),...this.coreRuntime.dataDateCapability?.checkpoint(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.dataDateProjectState()),...this.coreRuntime.dataDateCapability===null?{}:{p6LatestRunLog:C(this.coreRuntime.state.dataDateLatestRunLog())}}}getCanonicalDigest(){this.assertReady();let e=(i,a)=>String(i.id).localeCompare(String(a.id)),n=this._getP6Settings(),r=this._getP6ProjectState();return Jt({sector:this.getSector(),activities:[...this.coreRuntime.state.getAllActivities()].sort(e),links:[...this.getAllLinksView()].sort(e),calendars:[...this.getAllCalendars()].sort(e),baseCalendars:[...this.getBaseCalendars()].sort(e),...n===null?{}:{p6Settings:n,p6ProjectState:r}})}getReplicaFingerprint(){this.assertReady();let e=new gc,n=(i,a)=>{let o=[...i].sort((s,l)=>{let c=String(s.id),d=String(l.id);return c<d?-1:c>d?1:0});e.add(o.length);for(let s of o)e.add(s,a)};e.add(this.getSector()),n(this.coreRuntime.state.getAllActivities(),"proplannerId"),n(this.getAllLinksView(),"proplannerId"),n(this.getAllCalendars()),n(this.getBaseCalendars());let r=this._getP6Settings();return e.add(r),r!==null&&e.add(this._getP6ProjectState()),e.digest()}getCanonicalFingerprint(){if(this._canonicalFingerprintCache?.stateRevision===this._stateRevision)return this._canonicalFingerprintCache.value;let e=Hu(this.getCanonicalDigest());return this._canonicalFingerprintCache={stateRevision:this._stateRevision,value:e},e}_getP6ScheduleStateFingerprint(){if(this._p6ScheduleStateFingerprintCache?.stateRevision===this._stateRevision)return this._p6ScheduleStateFingerprintCache.value;let e=this._computeP6ScheduleStateFingerprint();return this._p6ScheduleStateFingerprintCache={stateRevision:this._stateRevision,value:e},e}_computeP6ScheduleStateFingerprint(){let e=(i,a)=>String(i.id).localeCompare(String(a.id)),n=[...this.getAllActivitiesView()].sort(e).map(({criticalPath:i,freeSlackHours:a,isCritical:o,...s})=>this.coreRuntime.dataDateCapability?.fingerprintActivity(s)??s);return Hu(Jt({sector:this.getSector(),activities:n,links:[...this.getAllLinksView()].sort(e).map(({freeSlackHours:i,isCritical:a,...o})=>o),calendars:[...this.getAllCalendars()].sort(e),baseCalendars:[...this.getBaseCalendars()].sort(e),p6Settings:this._getP6Settings(),p6ProjectState:this._getP6ProjectState()}))}createProjectionChangeSetFrom(e){this.assertReady(),e.assertReady();let n=vp(this._snapshotProjection(),e._snapshotProjection()),r=this.coreRuntime.dataDateCapability??e.coreRuntime.dataDateCapability;return{...n,...r?.reconcile({settings:this.coreRuntime.state.dataDateSettings(),projectState:this.coreRuntime.state.dataDateProjectState()},{settings:e.coreRuntime.state.dataDateSettings(),projectState:e.coreRuntime.state.dataDateProjectState()})}}_snapshotProjection(){return{activities:this.getAllActivitiesView(),links:this.getAllLinksView(),calendars:this.getAllCalendars(),selectedIds:this.getSelectedActivityIds(),hiddenIds:this.getHiddenActivityIds(),order:Pn(this.coreRuntime.state)}}getDeletedActivitiesSinceLastSave(){return this.assertReady(),this._saveTracker.deletedActivities(e=>this.coreRuntime.state.getActivity(e)).map(C)}getDeletedLinksSinceLastSave(){return this.assertReady(),this._saveTracker.deletedLinks(e=>this.coreRuntime.state.getLink(e)).map(C)}_enqueue(e){let n=this._opQueue.then(e,e);return this._opQueue=n.then(()=>{},()=>{}),n}_getP6Settings(){return this.assertReady(),C(this.coreRuntime.state.dataDateSettings())}_getP6ProjectState(){return this.assertReady(),C(this.coreRuntime.state.dataDateProjectState())}_getP6LatestRunLog(){return this.assertReady(),C(this.coreRuntime.state.dataDateLatestRunLog())}_resolveP6MustFinishByDefault(e){this.assertReady();let n=MC(this.coreRuntime.state.getAllActivities(),this.coreRuntime.calendars.values());return UC(e,n,this.coreRuntime.state.calendarReader)}_searchP6EndingActivities(e){this.assertReady(),u0(e);let n=e.query.trim().toLowerCase(),r=[],i=0;for(let a of this.coreRuntime.state.getVisualOrderIds()){let o=this._getP6EndingActivityOption(a);if(!(!o||!o.label.toLowerCase().includes(n))&&!(i++<e.offset)){if(r.length===e.limit)return{items:r,hasMore:!0};r.push(o)}}return{items:r,hasMore:!1}}_getP6EndingActivityOption(e){this.assertReady();let n=this.coreRuntime.state.getActivity(e);if(!n)return null;let r=n.customId?.trim()||n.uniqueCorrelativeId||String(n.correlativeId);return{id:n.id,label:`${r} \u2014 ${n.name}`}}_getP6ScheduleReadiness(e){this.assertReady();let n=this.coreRuntime.dataDateCapability;return n===null||!this.coreRuntime.state.isDataDateEnabled()?{ready:!1,code:"capability_not_enabled",count:0,sampleActivityIds:[],missingInputs:[]}:n.scheduleReadiness({settings:this.coreRuntime.state.dataDateSettings(),externalRelationshipIds:this.coreRuntime.externalRelationshipIds,patch:e,activities:this.coreRuntime.state.getAllActivities(),projectState:this.coreRuntime.state.dataDateProjectState()})}_updateP6Settings(e){let n=this._admitScheduleMutation(),r=!1,i=!1,a=this._enqueue(async()=>{try{this.assertReady();let o=this._requireDataDateCapability().prepareSettingsUpdate(this.coreRuntime.state.dataDateSettings(),e),{before:s,after:l}=o,c={kind:de.P6_SETTINGS_UPDATE};if(!o.changed)return{changes:{source:c,activities:[],links:[],calendars:[],trackingEvents:[]}};let d=this._requireDataDateCapability(),u=d.prepareLiveDerived(this.coreRuntime.state,s,l,{adoptExpectedFinish:!0,enabled:this.coreRuntime.state.isDataDateEnabled()}),p=[...u.keys()],y=new Map(p.flatMap(m=>{let A=this.coreRuntime.state.getActivity(m);return A===null?[]:[[m,ct(A)]]}));this.coreRuntime.state.beginWriteCapture();let f;try{this.coreRuntime.state.setDataDateSettings(l),d.applyLiveDerived(this.coreRuntime.state,u),f={...await et(this.coreRuntime.state,{source:c,beforeSnap:y,touchedIds:p,scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay}),p6Settings:{before:s,after:l}}}catch(m){throw this._rollback(),m}finally{this.coreRuntime.state.endWriteCapture()}return this._undo.record(oa(Co(f))),this._saveTracker.recordChanges(f.activities,f.links,m=>this.coreRuntime.state.getActivity(m),m=>this.coreRuntime.state.getLink(m)),this._saveTracker.recordP6Settings(l),i=At(s)&&l.dataDate===null,this._recordDirectScheduleMutation(!i&&this.coreRuntime.state.isDataDateEnabled()),r=!0,{changes:f}}finally{this._settleScheduleMutation(n,r)}});return a.then(()=>{i&&this.recomputeCriticalPath().catch(o=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after Data Date deactivation failed",o)})},()=>{}),a}_updateP6Activity(e,n,r){let i=this._admitScheduleMutation(),a=!1;return this._enqueue(async()=>{try{this.assertReady();let o=this._requireDataDateCapability(),s=o.requireSettings(this.coreRuntime.state.dataDateSettings()),l=this.coreRuntime.state.getActivity(e);if(l?.p6===void 0)throw new Error(`P6 activity ${e} does not exist`);let c=o.prepareActivityUpdate(l.p6,n,l.constraintType),d=this.coreRuntime.state.calendarReader.getCalendar(l.calendarId),u=At(s,this.coreRuntime.state.isDataDateEnabled())&&d!==null?o.projectLocalActivity(l.p6,c.next,{calendar:d,dataDate:s.dataDate,totalFloatMethod:s.totalFloatMethod}):{p6:c.next};if(!c.changed)return{changes:{source:{kind:de.P6_ACTIVITY_UPDATE},activities:[],links:[],calendars:[],trackingEvents:[]}};let p=new Map([[e,ct(l)]]);this.coreRuntime.state.beginWriteCapture();let y,f=null,m=null;try{if(this.coreRuntime.state.setActivityField(e,"p6",u.p6),u.startDate!==void 0&&this.coreRuntime.state.setActivityField(e,"startDate",u.startDate),u.endDate!==void 0&&this.coreRuntime.state.setActivityField(e,"endDate",u.endDate),At(s,this.coreRuntime.state.isDataDateEnabled())&&s.scheduleAutomaticallyOnDateChange){f=o.prepareSchedule({state:this.coreRuntime.state,settings:this.coreRuntime.state.dataDateSettings(),projectState:this.coreRuntime.state.dataDateProjectState(),externalRelationshipIds:this.coreRuntime.externalRelationshipIds,patch:void 0,sector:this.coreRuntime.sector});for(let N of f.calculated.activities.keys()){if(p.has(N))continue;let T=this.coreRuntime.state.getActivity(N);T!==null&&p.set(N,ct(T))}this._applyPreparedP6Schedule(f)}let g=f===null?[e]:[...f.calculated.activities.keys()];(f!==null||u.startDate!==void 0||u.endDate!==void 0)&&await on(this.coreRuntime.state,new Set(g),!1);let P=await et(this.coreRuntime.state,{source:{kind:de.P6_ACTIVITY_UPDATE},beforeSnap:p,touchedIds:g,scheduledIds:f===null?[]:g,hoursPerDay:this.coreRuntime.sector.hoursPerDay});y=f===null?P:{...P,...f.changeSetContribution},f!==null&&(m=this._buildP6ScheduleRunLog(f,r),this.coreRuntime.state.setDataDateLatestRunLog(m))}catch(A){throw this._rollback(),A}finally{this.coreRuntime.state.endWriteCapture()}return this._undo.record(oa(Co(y))),this._saveTracker.recordChanges(y.activities,y.links,A=>this.coreRuntime.state.getActivity(A),A=>this.coreRuntime.state.getLink(A)),f!==null&&m!==null&&(this._saveTracker.recordP6Settings(f.settings),this._saveTracker.recordP6ProjectState(f.projectState),this._saveTracker.recordP6LatestRunLog(m)),this._recordDirectScheduleMutation(this.coreRuntime.state.isDataDateEnabled()),a=!0,m!==null&&(this._p6ScheduleStateFingerprintCache={stateRevision:this._stateRevision,value:m.scheduleDigest}),{changes:y}}finally{this._settleScheduleMutation(i,a)}})}_scheduleP6(e,n){let r=this._admitScheduleMutation(),i=!1;return this._enqueue(async()=>{try{let a=await this._runP6Schedule(e,n);return i=this._changeSetIsSubstantive(a.changes),a}finally{this._settleScheduleMutation(r,i)}})}async _runP6Schedule(e,n){if(this.assertReady(),!this.coreRuntime.state.isDataDateEnabled())throw new Te("capability_not_enabled","Data Date is disabled for this Schedule");let r=this._requireDataDateCapability().prepareSchedule({state:this.coreRuntime.state,settings:this.coreRuntime.state.dataDateSettings(),projectState:this.coreRuntime.state.dataDateProjectState(),externalRelationshipIds:this.coreRuntime.externalRelationshipIds,patch:e,sector:this.coreRuntime.sector}),{settings:i,projectState:a,calculated:o,changeSetContribution:s}=r,l=new Map;for(let p of o.activities.keys()){let y=this.coreRuntime.state.getActivity(p);y!==null&&l.set(p,ct(y))}this.coreRuntime.state.beginWriteCapture();let c,d,u;try{this._applyPreparedP6Schedule(r),await on(this.coreRuntime.state,new Set(o.activities.keys()),!1),c={...await et(this.coreRuntime.state,{source:{kind:de.P6_SCHEDULE},beforeSnap:l,touchedIds:o.activities.keys(),scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay}),...s},d=[...o.activities.keys()].flatMap(y=>{let f=this.coreRuntime.state.getActivity(y);return f===null?[]:[ct(f)]}),u=this._buildP6ScheduleRunLog(r,n),this.coreRuntime.state.setDataDateLatestRunLog(u)}catch(p){throw this._rollback(),p}finally{this.coreRuntime.state.endWriteCapture()}return this._changeSetIsSubstantive(c)&&(this._undo.record(oa(Co(c))),this._saveTracker.recordChanges(c.activities,c.links,p=>this.coreRuntime.state.getActivity(p),p=>this.coreRuntime.state.getLink(p)),this._saveTracker.recordP6Settings(i),this._saveTracker.recordP6ProjectState(a),this._recordDirectScheduleMutation(!0)),this._p6ScheduleStateFingerprintCache={stateRevision:this._stateRevision,value:u.scheduleDigest},this._saveTracker.recordP6LatestRunLog(u),{changes:c,calculatedActivities:d,criticalPath:[...o.criticalPath],warnings:[...o.warnings],log:u}}_applyPreparedP6Schedule(e){this.coreRuntime.state.setDataDateSettings(e.settings),this.coreRuntime.state.setDataDateProjectState(e.projectState),this._requireDataDateCapability().applyScheduleProjection(this.coreRuntime.state,e.projection)}_operationNow(e){return e?Da(e):this.coreRuntime.clock?Da(this.coreRuntime.clock()):null}_buildP6ScheduleRunLog(e,n){return{schemaVersion:1,calculatedAt:n?new Date(n):this.coreRuntime.clock?.()??null,dataDate:C(e.settings.dataDate),project:{projectId:String(this.coreRuntime.sector.projectId),scheduleId:String(this.coreRuntime.sector.id),scheduleCode:this.coreRuntime.sector.name,scheduleName:this.coreRuntime.sector.name},settings:C(e.settings),statistics:{calculatedActivityCount:e.calculated.activities.size,criticalActivityCount:e.calculated.criticalPath.length,warningCount:e.calculated.warnings.length},warnings:C(e.calculated.warnings),scheduleDigest:this._computeP6ScheduleStateFingerprint()}}_requireDataDateCapability(){let e=this.coreRuntime.dataDateCapability;if(e===null)throw new Te("capability_not_enabled","P6 capability is not enabled for this Schedule");return e}_changeSetIsSubstantive(e){return mC(e,this._hasDataDateChanges(e))}_hasDataDateChanges(e){return this.coreRuntime.dataDateCapability?.changeSetIsSubstantive(e)??!1}_applyDataDateChangeSet(e,n){this.coreRuntime.dataDateCapability?.applyChangeSet(e,n,{setSettings:r=>{this.coreRuntime.state.setDataDateSettings(r)},setProjectPlannedStart:r=>{this._setP6ProjectPlannedStart(r)}})}async _applyDataDateActivationProjection(e,n){let r=this.coreRuntime.dataDateCapability,i=this.coreRuntime.state.dataDateSettings();if(r===null||e===null||i===null)return[];let a=r.prepareLiveDerived(this.coreRuntime.state,e,i,{enabled:this.coreRuntime.state.isDataDateEnabled()});return a.size===0?[]:this._assembleDataDateActivationProjection(r,a,n)}async _assembleDataDateActivationProjection(e,n,r){let i=[...n.keys()],a=this._snapshotActivities(i);this.coreRuntime.state.beginWriteCapture();try{return e.applyLiveDerived(this.coreRuntime.state,n),(await et(this.coreRuntime.state,{source:{kind:r},beforeSnap:a,touchedIds:i,scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay})).activities}catch(o){throw this._rollback(),o}finally{this.coreRuntime.state.endWriteCapture()}}_snapshotActivities(e){return new Map(e.flatMap(n=>{let r=this.coreRuntime.state.getActivity(n);return r===null?[]:[[n,ct(r)]]}))}_setP6ProjectPlannedStart(e){let n=this.coreRuntime.state.dataDateProjectState();n!==null&&this.coreRuntime.state.setDataDateProjectState({...n,plannedStart:e})}_beginScheduleMutation(e){return qa(e)?this._admitScheduleMutation():!1}_admitScheduleMutation(){return this._pendingScheduleRevision++,this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),!0}_settleScheduleMutation(e,n){e&&(n||(this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision-1,this._scheduleRevision),this._pendingScheduleRevision===this._scheduleRevision&&(this.isCriticalPathSettled()||this.recomputeCriticalPath().catch(r=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path re-arm after a barren mutation failed",r)}))))}async dispatch(e,n={}){let r=this._beginScheduleMutation(e);return this._enqueue(()=>this._dispatchInner(e,n,r))}async dispatchMany(e,n={}){let r=e.some(qa)?this._admitScheduleMutation():!1;return this._enqueue(()=>this._dispatchManyInner(e,n,r))}async applyActivityBatch(e,n={}){let r=this._beginScheduleMutation(e);return this._enqueue(()=>this._dispatchInner(e,n,r))}planLookaheadConversion(e){return this.assertReady(),nu(e,{adapter:this.coreRuntime.state,sector:this.getSector(),stateRevision:this._stateRevision})}applyLookaheadConversion(e){return this.dispatch({...e,kind:I.ACTIVITY_LOOKAHEAD_CONVERT})}async _dispatchInner(e,n={},r=!1){let i=!1;try{let a=await this._runDispatch(e,n);return i=a.changedState,a.result}finally{this._settleScheduleMutation(r,i)}}async _dispatchManyInner(e,n,r){let i=this._snapshotProjection(),a=this.coreRuntime.state.dataDateSettings(),s=a?.dataDate!=null&&a.scheduleAutomaticallyOnDateChange?xC({state:this.coreRuntime.state,history:this._undo,sector:this.coreRuntime.sector,persistence:this._saveTracker,scheduler:this.coreRuntime.scheduler,activityIds:this.coreRuntime.activityIdGenerator,linkIds:this.coreRuntime.linkIdGenerator,correlatives:this.coreRuntime.uniqueCorrelativeIdGenerator,customIds:this.coreRuntime.customIdTracker}):null,l=C(this._activityClipboard.value),c=C(this._cellClipboard.value),d=this._stateRevision,u=this._scheduleRevision,p=this._criticalPathRevision,y=this._criticalPathReady,f=this._settledCriticalPathJob,m=this._criticalPathUsesDataDate,A=this._canonicalFingerprintCache,g=this._p6ScheduleStateFingerprintCache,R={...n,skipAutoSchedule:!0,skipCriticalPath:!0},P=[],N=[],T=[],x=!1,S=!1,k,F=!1,U=null,w=!1,M=!1;try{for(let $ of e){if($.kind===I.SCHEDULE_AUTO_SCHEDULE){if($.activityId!==void 0&&!this.coreRuntime.state.activityExists($.activityId)){P.push({ok:!1,reason:D.ACTIVITY_NOT_FOUND});continue}let at=this.coreRuntime.state.dataDateSettings();if(At(at,this.coreRuntime.state.isDataDateEnabled())&&at.scheduleAutomaticallyOnDateChange!==!0){P.push({ok:!1,reason:D.MANUAL_SCHEDULING_ACTIVE});continue}let L=p0($);P.push({ok:!0,changes:L}),N.push(L),T.push($),S=!0,$.activityId===void 0||k!==void 0&&k!==$.activityId?F=!0:k=$.activityId;continue}let st=await this._runDispatch($,R,!0);P.push(st.result),st.result.ok&&(N.push(st.result.changes),T.push($)),st.changedState&&(x=!0,S=!0,F=!0)}if(S){let $=F||k===void 0?{kind:I.SCHEDULE_AUTO_SCHEDULE}:{kind:I.SCHEDULE_AUTO_SCHEDULE,activityId:k},st=await this._runDispatch($,n,!0);st.result.ok&&(U=st.result.changes,N.push(st.result.changes),w=n.skipAutoSchedule!==!0),x||=st.changedState}return x&&this._recordScheduleMutation(U!==null&&n.skipAutoSchedule!==!0&&n.skipCriticalPath!==!0),M=!0,{results:P,autoScheduled:w,changeSet:this._aggregateDispatchManyChangeSets(i,N,T)}}catch($){throw s!==null&&(s.restore(),this._activityClipboard.value=l,this._cellClipboard.value=c,this._undo=s.history,this._saveTracker=s.persistence,this._stateRevision=d,this._scheduleRevision=u,this._criticalPathRevision=p,this._criticalPathReady=y,this._settledCriticalPathJob=f,this._criticalPathUsesDataDate=m,this._canonicalFingerprintCache=A,this._p6ScheduleStateFingerprintCache=g,x=!1),$}finally{!M&&x&&this._recordScheduleMutation(!1),this._settleScheduleMutation(r,M&&x)}}_aggregateDispatchManyChangeSets(e,n,r){if(n.length===0)return null;let i=vp(this._snapshotProjection(),e),a=n.flatMap(s=>s.effects??[]),o=n.flatMap(s=>s.warnings??[]);return{...i,source:{kind:de.DISPATCH_MANY,actions:r},trackingEvents:n.flatMap(s=>s.trackingEvents),...a.length===0?{}:{effects:a},...o.length===0?{}:{warnings:o}}}async _runDispatch(e,n,r=!1){if(this.assertReady(),n.at&&(this._lastOperationAt=new Date(n.at)),this._isFork&&f0(e))return{result:{ok:!1,reason:D.SANDBOX_PERSISTENCE_FORBIDDEN},changedState:!1};if(e.kind===I.PERSISTENCE_REBASE&&!this._saveTracker.tracksPersistence())return{result:{ok:!1,reason:D.PERSISTENCE_TRACKING_DISABLED},changedState:!1};let i=pc(this.coreRuntime.state,{calendars:this.coreRuntime.calendars,hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat}),a=hC(e),o=[this.coreRuntime.activityIdGenerator.snapshot(),this.coreRuntime.linkIdGenerator.snapshot(),this.coreRuntime.uniqueCorrelativeIdGenerator.snapshot()];this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let s,l={prepared:null},c=null,d,u;try{s=await $A(e,n,{adapter:this.coreRuntime.state,ctx:i,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,linkIdGen:this.coreRuntime.linkIdGenerator,isActivityIdReserved:m=>this._saveTracker.hasCheckpointActivityId(m),isActivityPersisted:m=>this._saveTracker.knowsPersistedActivity(m),isLinkIdReserved:m=>this._saveTracker.hasCheckpointLinkId(m),persistenceCheckpoint:this._saveTracker,uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,reporter:this.coreRuntime.reporter,activityClipboard:this._activityClipboard,cellClipboard:this._cellClipboard,stateRevision:this._stateRevision,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(m=>m.baseDefault)?.id??null,hasCompleteSchedulingState:this.coreRuntime.state.dataDateSettings()!==null&&this.coreRuntime.state.hasCompleteSchedulingState(),dataDateCapability:this.coreRuntime.dataDateCapability,dataDateSettings:this.coreRuntime.state.dataDateSettings(),dataDateEnabled:this.coreRuntime.state.isDataDateEnabled(),runAutomaticP6Schedule:async()=>(l.prepared=this._requireDataDateCapability().prepareSchedule({state:this.coreRuntime.state,settings:this.coreRuntime.state.dataDateSettings(),projectState:this.coreRuntime.state.dataDateProjectState(),externalRelationshipIds:this.coreRuntime.externalRelationshipIds,patch:void 0,sector:this.coreRuntime.sector,...l.prepared===null?{}:{transactionBaseline:l.prepared}}),this._applyPreparedP6Schedule(l.prepared),[...l.prepared.calculated.activities.keys()]),now:this._operationNow(n.at),actionAt:n.at});let y=l.prepared;s.ok&&y!==null&&(s={...s,changes:{...s.changes,...y.changeSetContribution}},c=this._buildP6ScheduleRunLog(y,n.at),this.coreRuntime.state.setDataDateLatestRunLog(c)),u=this.coreRuntime.state.peekWriteCapture()?.dirty;let f=this.coreRuntime.state.peekWriteCapture()?.progressFallbackBefore;f&&f.size>0&&(d=new Map(f)),s.ok||this._rollback(o)}catch(y){throw this._rollback(o),y}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(s.ok&&a===ir.RECORD&&this._changeSetIsSubstantive(s.changes)){let y=uC(this.coreRuntime.state,s.changes),f=d?new Map(Array.from(d.keys(),m=>[m,this.coreRuntime.state.getProgressFallback(m)])):void 0;this._undo.record({...oa(Co(s.changes),s.__beforeSnap,s.__beforeLinks,y.afterSnap,y.afterLinks,d,f),...At(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.isDataDateEnabled())?{beforeLinks:C(s.__beforeLinks),afterLinks:C(y.afterLinks)}:{}},pC(e),n.at?.getTime()??Date.now())}if(s.ok)if(a===ir.CHECKPOINT_ON_SUCCESS||a===ir.REBASE_ON_SUCCESS){let y=y0(e,s,this._saveTracker),f=y.checkpoint,m={settings:f?.p6Settings??this.coreRuntime.state.dataDateSettings(),projectState:f?.p6ProjectState===void 0?this.coreRuntime.state.dataDateProjectState():f.p6ProjectState,latestRunLog:f?.p6LatestRunLog===void 0?this.coreRuntime.state.dataDateLatestRunLog():f.p6LatestRunLog};if(f?.pending)this._saveTracker.acknowledgePending(f.pending,f.activities,f.links,y.persistedActivities??[],y.persistedLinks??[],{activity:A=>this.coreRuntime.state.getActivity(A),link:A=>this.coreRuntime.state.getLink(A)},m.settings,m.projectState,m.latestRunLog);else{let A=this.coreRuntime.state.getAllActivities(),g=this.coreRuntime.state.getAllLinks();this._saveTracker.acknowledge(f?.activities??A,f?.links??g,y.persistedActivities,y.persistedLinks,A,g,m.settings,m.projectState,m.latestRunLog)}y.clearsHistory?this._undo.clear():(y.retainsHistory||this._undo.discardThrough(y.historyBoundary??this._undo.capturePersistenceBoundary()),this._undo.applyPersistedIdentities(y.persistedActivities??[],y.persistedLinks??[]))}else if(e.kind===I.ACTIVITY_LOOKAHEAD_SYNC&&e.acknowledgePersistedLookahead===!0)this._saveTracker.acknowledgePersistedLookahead(s.changes.activities,y=>this.coreRuntime.state.getActivity(y)),e.persistedProgress!==void 0&&this._undo.clear();else{this._saveTracker.recordChanges(s.changes.activities,s.changes.links,f=>this.coreRuntime.state.getActivity(f),f=>this.coreRuntime.state.getLink(f),u);let y=l.prepared;y!==null&&c!==null&&(this._saveTracker.recordP6Settings(y.settings),this._saveTracker.recordP6ProjectState(y.projectState),this._saveTracker.recordP6LatestRunLog(c))}if(s=this._withReappliedViewState(e,s),!s.ok)return{result:s,changedState:!1};let p=this._changeSetIsSubstantive(s.changes);return p&&this._stateRevision++,c!==null&&(this._p6ScheduleStateFingerprintCache={stateRevision:this._stateRevision,value:c.scheduleDigest}),qa(e)&&p?(r||this._recordScheduleMutation(n.skipAutoSchedule!==!0&&n.skipCriticalPath!==!0&&Or(e)),{result:HC(s),changedState:!0}):{result:HC(s),changedState:!1}}recomputeCriticalPath(){let e=this._enqueue(async()=>({job:this._startCriticalPathForCurrentRevision()})).then(({job:n})=>n);return this._criticalPathReady=this._trackCriticalPathJob(e),e}isCriticalPathSettled(){return this._criticalPathRevision===this._scheduleRevision&&this._criticalPathUsesDataDate===At(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.isDataDateEnabled())&&this._pendingScheduleRevision===this._scheduleRevision&&this._activeCriticalPath===null}async whenCriticalPathSettled(){for(;!this.isCriticalPathSettled();){let e=this._activeCriticalPath?.promise;e?await e:await this.recomputeCriticalPath()}}_withReappliedViewState(e,n){if(!n.ok||(e.kind===I.VISIBILITY_SET&&this.coreRuntime.state.setFilterProjection(null),!ym(e)))return n;let r=this._reapplyViewState(n.changes);return r===null?n:{...n,changes:r}}_reapplyViewState(e){let n=this._reapplyActiveFilter(e),r=this._emitTouchedBranchOrder(n??e);return this._reapplyActiveOrder(r.changes??n??e,r.touchedParents)??r.changes??n}_emitTouchedBranchOrder(e){let n=this.coreRuntime.state,r=_C(e,a=>n.getParentId(a));if(n.getActiveOrder()!==null)return{changes:null,touchedParents:r};if(r.size===0)return{changes:null,touchedParents:r};let i=wc(n,r);return i.length===0?{changes:null,touchedParents:r}:{changes:{...e,order:i},touchedParents:r}}_reapplyActiveOrder(e,n){let r=this.coreRuntime.state;if(r.getActiveOrder()===null)return null;if(r.invalidateDerivedOrder(),e.links.length>0||e.calendars.length>0)return{...e,order:Pn(r)};let a=new Set(n);for(let s of e.activities){if(s.kind===W.DELETED)return{...e,order:Pn(r)};let l=r.getParentId(s.id);a.add(l===null?"0":String(l))}let o=wc(r,a);return o.length===0?null:{...e,order:o}}_reapplyActiveFilter(e){let n=this.coreRuntime.state,r=n.getActiveFilter();if(r===null)return null;let i=fr(this.coreRuntime.sector.hoursPerDay),a=n.getFilterProjection(),o=g0(a,r,i),s=h0(e)?null:m0(e,n),l,c;if(s===null||!o){let p=jo({activities:n.getAllActivities(),parentOf:y=>n.getParentId(y),filter:r,context:i,viewAttributeCatalogs:n.getViewAttributeCatalogMap()});n.setFilterProjection(p),c=p.visibleIds,l=n.getAllIds()}else l=$p(a,s,p=>n.getParentId(p)),c=a.visibleIds;let u=dr(n,c,l);return u.length===0?null:{...e,viewState:[...e.viewState??[],...u]}}_recordScheduleMutation(e){this._scheduleRevision++,this._settledCriticalPathJob!==null&&this._releaseCriticalPathResult(this._settledCriticalPathJob),this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision,this._scheduleRevision),this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),e&&(this._criticalPathUsesDataDate=At(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.isDataDateEnabled()),this._criticalPathRevision=this._scheduleRevision)}_recordDirectScheduleMutation(e){this.coreRuntime.dataDateCapability!==null&&this._stateRevision++,this._recordScheduleMutation(e)}_startCriticalPathForCurrentRevision(){if(this._status===Ke.DESTROYED)return Promise.resolve(null);if(At(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.isDataDateEnabled()))return this._criticalPathUsesDataDate=!0,this._criticalPathRevision=this._scheduleRevision,Promise.resolve(null);let e=this._scheduleRevision;if(this._criticalPathRevision===e&&!this._criticalPathUsesDataDate)return Promise.resolve(null);if(this._activeCriticalPath?.revision===e)return this._activeCriticalPath.promise;this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0);let n={cancelled:!1},r=()=>!At(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.isDataDateEnabled())&&!n.cancelled&&this._status!==Ke.DESTROYED&&this._scheduleRevision===e&&this._pendingScheduleRevision===this._scheduleRevision,i=this._lastOperationAt??void 0,a=(async()=>{let s=await Pd(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay,r,i);return!r()||s===null?null:this._enqueue(async()=>{if(!r())return null;this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let l;try{l=await kC(this.coreRuntime.state,s,{kind:de.INIT}),this._criticalPathUsesDataDate=!1,this._criticalPathRevision=e}catch(c){throw this._rollback(),c}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return{changes:l}})})();this._activeCriticalPath={revision:e,cancellation:n,promise:a};let o=()=>{this._activeCriticalPath?.promise===a&&(this._activeCriticalPath=null)};return a.then(o,o),a}undo(e={}){let n=this._admitScheduleMutation(),r=!1,i=this._enqueue(async()=>{try{return await this._runUndo(e,a=>{r=a})}finally{this._settleScheduleMutation(n,r)}});return i.then(a=>{let o=a!==null&&this._hasDataDateChanges(a)&&At(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.isDataDateEnabled());a&&!o&&e.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(s=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after undo failed",s)})},()=>{}),i}async _runUndo(e,n){{if(this.assertReady(),e.expectedUndoDepth!==void 0&&this._undo.undoDepth()!==e.expectedUndoDepth)return null;let r=this._undo.takeUndo();if(!r)return null;let i=C(this.coreRuntime.state.dataDateSettings()),a;try{mp(this.coreRuntime.state,r,(l,c)=>this._applyDataDateChangeSet(l,c)),a=await this._applyDataDateActivationProjection(i,de.UNDO)}catch(l){throw gp(this.coreRuntime.state,r,(c,d)=>this._applyDataDateChangeSet(c,d)),this._undo.restoreTakenUndo(r),l}this._recordDirectScheduleMutation(this._hasDataDateChanges(r.changeSet)&&At(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.isDataDateEnabled())),n(!0),fp(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(r),this._undo.resetCoalesce();let o=hp(this.coreRuntime.state,r,Wt.BEFORE,l=>this.coreRuntime.dataDateCapability?.historyContribution(r.changeSet,l)??{}),s={...o,activities:[...o.activities,...a]};return this._saveTracker.recordChanges(s.activities,s.links,l=>this.coreRuntime.state.getActivity(l),l=>this.coreRuntime.state.getLink(l)),this._saveTracker.recordP6Settings(this.coreRuntime.state.dataDateSettings()),this._saveTracker.recordP6ProjectState(this.coreRuntime.state.dataDateProjectState()),this._reapplyViewState(s)??s}}redo(e={}){let n=this._admitScheduleMutation(),r=!1,i=this._enqueue(async()=>{try{return await this._runRedo(a=>{r=a})}finally{this._settleScheduleMutation(n,r)}});return i.then(a=>{let o=a!==null&&this._hasDataDateChanges(a)&&At(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.isDataDateEnabled());a&&!o&&e.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(s=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after redo failed",s)})},()=>{}),i}async _runRedo(e){this.assertReady();let n=this._undo.takeRedo();if(!n)return null;let r=C(this.coreRuntime.state.dataDateSettings()),i;try{gp(this.coreRuntime.state,n,(s,l)=>this._applyDataDateChangeSet(s,l)),i=await this._applyDataDateActivationProjection(r,de.REDO)}catch(s){throw mp(this.coreRuntime.state,n,(l,c)=>this._applyDataDateChangeSet(l,c)),this._undo.restoreTakenRedo(n),s}this._recordDirectScheduleMutation(this._hasDataDateChanges(n.changeSet)&&At(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.isDataDateEnabled())),e(!0),fp(n)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(n),this._undo.resetCoalesce();let a=hp(this.coreRuntime.state,n,Wt.AFTER,s=>this.coreRuntime.dataDateCapability?.historyContribution(n.changeSet,s)??{}),o={...a,activities:[...a.activities,...i]};return this._saveTracker.recordChanges(o.activities,o.links,s=>this.coreRuntime.state.getActivity(s),s=>this.coreRuntime.state.getLink(s)),this._saveTracker.recordP6Settings(this.coreRuntime.state.dataDateSettings()),this._saveTracker.recordP6ProjectState(this.coreRuntime.state.dataDateProjectState()),this._reapplyViewState(o)??o}canUndo(){return this._undo.canUndo()}canRedo(){return this._undo.canRedo()}readIdCounters(){return{activity:this.coreRuntime.activityIdGenerator.snapshot(),link:this.coreRuntime.linkIdGenerator.snapshot(),uniqueCorrelative:this.coreRuntime.uniqueCorrelativeIdGenerator.snapshot()}}restoreIdCounters(e){this.coreRuntime.activityIdGenerator.restore(e.activity),this.coreRuntime.linkIdGenerator.restore(e.link),this.coreRuntime.uniqueCorrelativeIdGenerator.restore(e.uniqueCorrelative)}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=Ke.DESTROYED}_initPromise;_criticalPathReady;_settledCriticalPathJob=null;_ready;_saveTracker=new sa;_retainCriticalPathResult=!0;_lastOperationAt=null;assertReady(){if(this._status===Ke.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===Ke.POISONED)throw new Error("[ScheduleCore] instance is poisoned (a rollback failed) \u2014 reload from backend")}_rollback(e){try{this.coreRuntime.state.restoreFromCapture(),this.coreRuntime.scheduler.invalidateAllCaches(),this.coreRuntime.customIdTracker.rollbackCustomIdTransaction(),e&&(this.coreRuntime.activityIdGenerator.restore(e[0]),this.coreRuntime.linkIdGenerator.restore(e[1]),this.coreRuntime.uniqueCorrelativeIdGenerator.restore(e[2]))}catch(n){throw this._status=Ke.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",n),n}}};function HC(t){let{__beforeSnap:e,__beforeLinks:n,__rebaseCheckpoint:r,...i}=t;return i}async function BC(t){let e=new la(t);return await e.ready,e}var A0=(t,e)=>{if(!t.resourceAssignments)return t;let n=!1,r=t.resourceAssignments.map(i=>{let a=i.sourceCalendarId,o=e.get(String(a??i.calendarId))??i.calendarId;return o===i.calendarId?i:(n=!0,{...i,calendarId:o})});return n?{...t,resourceAssignments:r}:t},I0=(t,e)=>{if(!t?.activities||e.length===0)return t;let n=new Map(e.map(i=>[String(i.unique_id),String(i.id)])),r=t.activities;for(let[i,a]of Object.entries(t.activities)){let o=A0(a,n);o!==a&&(r===t.activities&&(r={...t.activities}),r[i]=o)}return r===t.activities?t:{...t,activities:r}};function jC(t){let e=I0(t.p6,t.calendars)??(t.isDataDateEnabled?.()?{settings:aa(),projectPlannedStart:null,activities:{}}:void 0),n=e?.settings.dataDate!=null;return{...t.isDataDateEnabled?{isDataDateEnabled:t.isDataDateEnabled}:{},...e?{p6:e}:{},...n&&(t.isDataDateEnabled?.()??!0)?{skipInitialAutoSchedule:!0}:{}}}var S0=["DURATION","COST","HH"];function VC(t){let e=t.projectActivityCriterion==null?t.sector:{...t.sector,activity_creter:t.projectActivityCriterion},n=t.calendars??[];return{sector:e,activities:t.activities,links:t.links??[],calendars:n,baseCalendars:t.baseCalendars??[],baselinePoints:t.baselinePoints??[],statusCriteria:t.statusCriteria??"Baseline",...t.ganttId!==void 0?{ganttId:t.ganttId}:{},clock:t.clock,...t.reporter?{reporter:t.reporter}:{},...jC({...t.p6?{p6:t.p6}:{},...t.isDataDateEnabled?{isDataDateEnabled:t.isDataDateEnabled}:{},calendars:n})}}function WC(t){let e=t.update_save_handle_for_calendar_update===!0,n=t.update_ponderators_masterplan===!0,r=t.activity_creter?.toUpperCase(),i=n?S0.find(a=>a===r)??null:null;return{actions:[...e?[{kind:I.CALENDAR_RECONCILE}]:[],...i?[{kind:I.PONDERATOR_CRITERION_SET,criterion:i}]:[]],calendar:e,ponderators:i!==null,...n&&i===null?{unresolvedPonderatorCriterion:String(t.activity_creter)}:{}}}function KC(t,e){return t.some(n=>n.unique_id!=null&&Ei(n.start_date,e(String(n.unique_id))))}var v0={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"},C0=/^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i,Ac=t=>typeof t=="string"&&t.trim()!=="",YC=t=>typeof t=="number"&&Number.isFinite(t)||typeof t=="string"&&C0.test(t.trim())&&Number.isFinite(Number(t)),D0=[["start_date","startDate",Ac],["end_date","endDate",Ac],["duration","durationHours",YC],["constraint","constraintType",Ac],["constraint_date","constraintDate",t=>t===null||Ac(t)],["progress","progress",YC]],T0=["startDate","endDate"],To=t=>{let e=Number(t);return Number.isSafeInteger(e)?e:t},_0=(t,e,n)=>{let r=new Set(n.changedFields??[]);if(n.persistCalendarAlignedDates===!0||Ei(e.start_date,t.startDate))for(let i of T0)r.add(i);return r},E0=(t,e,n)=>{let r={...t};for(let[i,a,o]of D0){let s=e[i];!n.has(a)&&Object.hasOwn(e,i)&&o(s)&&(r[i]=s)}return r};function GC(t,e,n={}){let r=a=>a/e.hoursPerDay,i={name:t.name,unique_id:To(t.id),parent_id:To(t.parentId??"0"),description:t.description,cost:t.cost,progress:t.progress,progressChangedByActionButton:!!n.progressChangedByActionButton,progressModifiedBySDK:!!n.progressModifiedBySDK,constraint:v0[t.constraintType??"asap"],start_date:t.startDate,custom_id:t.customId,end_date:t.endDate,constraint_date:t.constraintDate,type:t.type,correlative_id:t.correlativeId,unique_correlative_id:t.uniqueCorrelativeId,hhWorkTime:t.workHours,ponderator:t.ponderator,hasCustomPonderator:t.hasCustomPonderator,used_cost:t.usedCost,real_cost:t.realCost,real_work:t.realWorkHours,responsables:t.responsableIds.map(a=>({id:a})),tags:t.tagIds.map(a=>({id:a})),subcontractId:t.subcontractId,...t.freeSlackHours==null?{}:{freeSlack:r(t.freeSlackHours)},isOnLookahead:t.isLookahead,is_critical:t.isCritical,hasNewActivities:t.hasNewActivities,newActivitiesArray:JSON.stringify(t.newActivityIds),isNewActivity:t.isNewActivity,...t.calendarId==null?{}:{calendarId:t.calendarId},duration:r(t.durationHours),sumOfDurationRecursively:r(t.recursiveDurationHours),expected_progress:t.expectedProgress,sectorId:e.sectorId,ganttId:e.ganttId,has_childs:e.hasChildren(String(t.id)),...t.proplannerId==null?{}:{id:t.proplannerId}};return t.proplannerId==null||!n.origin?i:E0(i,n.origin,_0(t,n.origin,n))}function qC(t,e){return{unique_id:To(t.id),source_id:To(t.source),target_id:To(t.target),type:Ts[t.type],lag:(t.lag??0)/e.hoursPerDay,sectorId:e.sectorId,ganttId:e.ganttId,...t.proplannerId==null?{}:{id:t.proplannerId}}}var zr="__wire",ca={DATE:"date",MAP:"map",SET:"set"},Tp={DATE:"[object Date]",MAP:"[object Map]",SET:"[object Set]"},R0=t=>Object.prototype.toString.call(t),P0=new Set(Object.values(ca));function k0(t){return typeof t=="object"&&t!==null&&zr in t&&P0.has(t[zr])}function b0(t){let e=t.getTime();return{[zr]:ca.DATE,value:Number.isNaN(e)?null:t.toISOString()}}function qr(t){let e=R0(t);if(e===Tp.DATE)return b0(t);if(e===Tp.MAP)return{[zr]:ca.MAP,value:Array.from(t.entries(),([n,r])=>[qr(n),qr(r)])};if(e===Tp.SET)return{[zr]:ca.SET,value:Array.from(t,qr)};if(Array.isArray(t))return t.map(qr);if(typeof t=="object"&&t!==null){let n={};for(let[r,i]of Object.entries(t))i!==void 0&&(n[r]=qr(i));return n}return t}function L0(t){if(t[zr]===ca.DATE)return t.value===null?new Date(Number.NaN):new Date(t.value);let e=t.value;return t[zr]===ca.MAP?new Map(e.map(([n,r])=>[$r(n),$r(r)])):new Set(e.map($r))}function $r(t){if(k0(t))return L0(t);if(Array.isArray(t))return t.map($r);if(typeof t=="object"&&t!==null){let e={};for(let[n,r]of Object.entries(t))e[n]=$r(r);return e}return t}var JC=["actualStart","actualFinish","plannedStart","plannedFinish","expectedFinish","suspendDate","resumeDate","primaryConstraintDate","secondaryConstraintDate","remainingEarlyStart","remainingEarlyFinish","remainingLateStart","remainingLateFinish","earlyStart","earlyFinish","lateStart","lateFinish","primaryBaselineStart","primaryBaselineFinish"],XC=new Set(["primaryConstraintDate"]),$C=Object.freeze({fixed_duration_and_units:"fixed_units_time",fixed_duration_and_units_per_time:"fixed_duration_units",fixed_units_time:"fixed_units_time",fixed_duration_units:"fixed_duration_units",fixed_units:"fixed_units",fixed_duration_units_time:"fixed_duration_units_time"}),zC=Object.freeze({fixed_units_time:"fixed_duration_and_units",fixed_duration_units:"fixed_duration_and_units_per_time"}),we=(t,e)=>{if(t===null)return null;let n=new Date(t);if(!Number.isFinite(n.getTime())||n.toISOString()!==t)throw new TypeError(`${e} must be a valid UTC timestamp or null`);return n},nn=t=>t===null?null:t.toISOString(),ZC=(t,e)=>({...t,dataDate:we(t.dataDate,`${e}.dataDate`),projectMustFinishBy:we(t.projectMustFinishBy,`${e}.projectMustFinishBy`),projectForecastStart:we(t.projectForecastStart,`${e}.projectForecastStart`),multipleFloatPaths:{...t.multipleFloatPaths}}),O0=t=>t!==void 0&&Object.hasOwn(zC,t)?zC[t]:t,N0=(t,e)=>{let{resourceAssignments:n,...r}=t,i=`activities.${e}`,a=Object.fromEntries(JC.map(o=>{let s=t[o];return[o,we(XC.has(o)?s??null:s,`${i}.${o}`)]}));return{...r,...t.durationType===void 0?{}:{durationType:O0(t.durationType)},...n===void 0?{}:{resourceAssignments:n.map(o=>({...o,actualStart:we(o.actualStart,`${i}.resourceAssignments.${o.id}.actualStart`),actualFinish:we(o.actualFinish,`${i}.resourceAssignments.${o.id}.actualFinish`)}))},...a}},F0=t=>({...t,calculatedAt:we(t.calculatedAt,"latestRunLog.calculatedAt"),dataDate:we(t.dataDate,"latestRunLog.dataDate"),settings:ZC(t.settings,"latestRunLog.settings"),warnings:t.warnings.map((e,n)=>({...e,dataDate:we(e.dataDate,`latestRunLog.warnings.${n}.dataDate`),dates:{actualStart:we(e.dates.actualStart,`latestRunLog.warnings.${n}.dates.actualStart`),actualFinish:we(e.dates.actualFinish,`latestRunLog.warnings.${n}.dates.actualFinish`)}}))});function QC(t){return{settings:ZC(t.settings,"settings"),projectPlannedStart:we(t.projectPlannedStart,"projectPlannedStart"),activities:Object.fromEntries(Object.entries(t.activities).map(([e,n])=>[e,N0(n,e)])),externalRelationshipIds:[...t.externalRelationshipIds??[]],latestRunLog:t.latestRunLog===void 0||t.latestRunLog===null?null:F0(t.latestRunLog)}}var w0=t=>{if(!Object.hasOwn($C,t))throw new Error(`Unknown P6 duration type "${String(t)}"`);return $C[t]};function Ic(t){return{...t,dataDate:nn(t.dataDate),projectMustFinishBy:nn(t.projectMustFinishBy),projectForecastStart:nn(t.projectForecastStart),multipleFloatPaths:{...t.multipleFloatPaths}}}function _p(t){let{resourceAssignments:e,...n}=t,r=Object.fromEntries(JC.map(i=>[i,nn(XC.has(i)?t[i]??null:t[i])]));return{...n,...t.durationType===void 0?{}:{durationType:w0(t.durationType)},...e===void 0?{}:{resourceAssignments:e.map(i=>({...i,actualStart:nn(i.actualStart),actualFinish:nn(i.actualFinish)}))},...r}}var x0=t=>({...t,calculatedAt:nn(t.calculatedAt),dataDate:t.dataDate.toISOString(),settings:Ic(t.settings),warnings:t.warnings.map(e=>({...e,dataDate:e.dataDate.toISOString(),dates:{actualStart:nn(e.dates.actualStart),actualFinish:nn(e.dates.actualFinish)}}))});function tD(t){if(t.settings===null)return null;if(t.projectState===null)throw new Error("P6 project state is required when P6 settings exist");return{settings:Ic(t.settings),projectPlannedStart:nn(t.projectState.plannedStart),activities:Object.fromEntries(t.activities.flatMap(e=>e.p6===null||e.p6===void 0?[]:[[String(e.id),_p(e.p6)]])),...t.latestRunLog===void 0?{}:{latestRunLog:t.latestRunLog===null?null:x0(t.latestRunLog)},...t.externalRelationshipIds?.length?{externalRelationshipIds:[...t.externalRelationshipIds]}:{}}}var eD=(t=[])=>(t??[]).filter(e=>!e.proplannerId);var Jr=class extends Error{constructor(n){super(n);this.code=n;this.name="LookaheadActualTransitionError"}code},M0=/^(\d{4})-(\d{2})-(\d{2})$/;function vc(t){Ep(t.timeSource)||xe("INVALID_ACTUAL_TIME_SOURCE");let e=U0(t.selectedDay),[n,r,i]=e,a=new Date(t.timeSource);return a.setUTCFullYear(n,r-1,i),V0(a,e)||xe("INVALID_ACTUAL_DAY"),a}function U0(t){let e=M0.exec(t);return e||xe("INVALID_ACTUAL_DAY"),[Number(e[1]),Number(e[2]),Number(e[3])]}function Rp(t){if(j0(t),t.dataDate===null)return{start:null,finish:null,uncomplete:null};let e=t.activity.executionStatus===tt.NOT_STARTED&&t.nextProgress>0?{required:!0,suggestedAt:new Date(t.dataDate)}:null,n=t.activity.executionStatus!==tt.COMPLETED&&t.nextProgress===100?{optional:!0,suggestedAt:t.displayedFinish?new Date(t.displayedFinish):null}:null,r=t.activity.executionStatus===tt.COMPLETED&&t.activity.actualFinish!==null&&t.nextProgress<100?{required:!0,removes:new Date(t.activity.actualFinish)}:null;return{start:e,finish:n,uncomplete:r}}function Sc(t){let e=Rp(t);t.dataDate===null&&W0(t.intent)&&xe("DATA_DATE_INACTIVE"),e.start&&t.intent?.actualStart===void 0&&xe("ACTUAL_START_REQUIRED"),t.intent?.actualFinish instanceof Date&&t.nextProgress!==100&&xe("ACTUAL_FINISH_REQUIRES_100"),e.uncomplete&&t.intent?.actualFinish!==null&&xe("ACTUAL_FINISH_REMOVAL_REQUIRED"),!e.uncomplete&&t.intent?.actualFinish===null&&xe("ACTUAL_FINISH_REMOVAL_NOT_APPLICABLE");let n=Wl(t.activity,t.intent??{});return t.dataDate===null?n:B0(t.activity,n,t.nextProgress)}function nD(t){let{resolveCalendar:e,...n}=t,r=Sc(n);if(t.dataDate===null)return r;let i=t.intent?.actualStart;if(!(i!==void 0&&di(i)))return r;let o=H0(t.intent,e);return o===void 0?r:Sc({...n,intent:o})}function H0(t,e){if(t?.actualStart===void 0||!di(t.actualStart))return t;let n=e();return n===null&&xe("ACTIVITY_CALENDAR_REQUIRED"),{...t,actualStart:Jo(t.actualStart,n)}}function B0(t,e,n){if((e.executionStatus??t.executionStatus)!==tt.IN_PROGRESS)return e;switch(t.percentCompleteType){case xt.PHYSICAL:return{...e,physicalPercentComplete:n};case xt.DURATION:return{...e,remainingDurationHours:t.originalDurationHours*(1-n/100)};default:return e}}function j0(t){(!Number.isFinite(t.nextProgress)||t.nextProgress<0||t.nextProgress>100)&&xe("INVALID_PROGRESS"),t.dataDate!==null&&!Ep(t.dataDate)&&xe("INVALID_DATA_DATE"),t.displayedFinish!=null&&!Ep(t.displayedFinish)&&xe("INVALID_DISPLAYED_FINISH")}function Ep(t){return t instanceof Date&&Number.isFinite(t.getTime())}function V0(t,[e,n,r]){return t.getUTCFullYear()===e&&t.getUTCMonth()===n-1&&t.getUTCDate()===r}function W0(t){return t?.actualStart!==void 0||t?.actualFinish!==void 0}function xe(t){throw new Jr(t)}function rD(t){return vc({selectedDay:t.selectedDay,timeSource:t.expectedFinish??t.displayedFinish})}function Cc(t){let e=cc([...t.calendars],void 0,t.baseCalendars===void 0?void 0:[...t.baseCalendars]),{reader:n}=xl(cp(e.calendars,e.baseCalendars));return{defaultCalendarId:e.defaultCalendarId,resolveCalendar(r){let i=r!==null&&e.knownCalendarIds.has(r)?r:e.defaultCalendarId;return n.getCalendar(i)}}}function iD(t){let{resolveCalendar:e}=Cc(t);return{getCalendar(n){let r=e(n);if(!r)throw new Jr("ACTIVITY_CALENDAR_REQUIRED");return r},derive({previous:n,next:r,calendarId:i,dataDate:a,totalFloatMethod:o}){if(!sn(r))return null;let s=e(i);if(!s)return null;let{p6:l}=ql(n,r,{calendar:s,dataDate:a,...o===void 0?{}:{totalFloatMethod:o}});return{actualDurationHours:l.actualDurationHours,atCompletionDurationHours:l.atCompletionDurationHours,durationPercentComplete:l.durationPercentComplete,unitsPercentComplete:l.unitsPercentComplete,schedulePercentComplete:l.schedulePercentComplete}}}}function aD(t){let{defaultCalendarId:e,resolveCalendar:n}=Cc(t);if(e===null)throw new Error("Calendar reader requires at least one calendar");return{getCalendar(r){let i=n(r);if(!i)throw new Error("Resolved calendar missing after normalization");return i}}}var kt=t=>{let e=t.lifecycle??(t.classification==="f9_output"?"f9":"explicit_edit");return{...t,lifecycle:e,changesWhen:K0(e),f9Behavior:Y0(e),persistence:"Persist exact null/zero/signed scalar or exact UTC instant; save/reload is lossless.",nullAndZero:t.typeAndUnit.includes("UTC")?"null means absent; midnight is a real exact UTC instant.":t.typeAndUnit.includes("boolean")?"false is a real value and is never normalized to null.":"null means unavailable when allowed; numeric zero and signed values are preserved.",calendarRule:t.typeAndUnit.includes("working hours")||t.classification==="derived"?"Use the activity calendar, including shifts and exceptions; never local wall-clock subtraction.":"No calendar arithmetic; date values cross boundaries as exact UTC components.",status:t.status??(e==="open"?"PARTIAL":"VERIFIED"),edgeCases:t.edgeCases??{}}};function K0(t){return t==="f9"?"Changes only during explicit P6 F9 and its atomic Undo/Redo replay.":t==="dependency_change"?"Changes when Data Date moves from one valid instant to another in the same canonical mutation, without running F9.":t==="open"?"Formula is known; immediate pre-F9 refresh timing remains open pending a discriminant P6 observation.":"Changes on an authorized import or explicit user edit; open/save/reload do not calculate it."}function Y0(t){return t==="explicit_edit"?"Preserved as scheduling reality/input unless the documented P6 algorithm consumes the input without rewriting it.":t==="open"?"Recalculated by F9; whether dependency edits refresh it earlier is not yet certified.":"Recalculated by Schedule Core; no frontend or backend formula is authoritative."}var ar="src/p6/api.test.ts; src/p6/testing/p6-data-date/property-coverage.test.ts",Sn="src/p6/testing/p6-data-date/fixtures/obdd-math/obdd-math-before-f9.xer",da="src/p6/testing/p6-floats/obdd-floats.schedule.test.ts",ua="src/p6/testing/p6-floats/fixtures/obdd-floats-smallest.xer",vn="src/p6/derived.test.ts",or="src/p6/testing/p6-derived/fixtures/obdd-derived-edges.p6.json",G0={notStarted:"0 hours.",inProgress:"Working time from Actual Start to Data Date, excluding a valid Suspend/Resume interval.",completed:"Working time from Actual Start to Actual Finish.",zeroDuration:"0 hours.",zeroDenominator:"Not applicable; no division.",suspendResume:"Subtract only the overlap of Suspend..Resume with the measured actual interval.",calendarException:"Exception time contributes only when the activity calendar marks it workable.",signedValues:"Invalid negative duration inputs are rejected; P6 clamps a reversed Actual Start/end interval to 0 hours.",nullValue:"Missing required actual endpoint yields 0 under the P6 status contract.",milestone:"0 hours when the actual endpoints coincide."},q0={notStarted:"Working duration Planned Start..Planned Finish.",inProgress:"Working duration Actual Start..Remaining Early Finish, excluding Suspend/Resume.",completed:"Working duration Actual Start..Actual Finish.",zeroDuration:"0 hours.",zeroDenominator:"Not applicable; no division.",suspendResume:"Subtract the suspended overlap from the selected endpoint interval.",calendarException:"Measured with shifts and exceptions from the activity calendar.",signedValues:"P6 clamps a chronologically reversed Actual Start/selected finish interval to 0 hours.",nullValue:"Missing required endpoints yields 0 for the matching status branch.",milestone:"0 hours for coincident endpoints."},$0={notStarted:"(Original - Remaining) / Original \xD7 100, normally 0.",inProgress:"(Original - Remaining) / Original \xD7 100, clamped to 0..100.",completed:"Same formula; P6 completed input normally has zero Remaining.",zeroDuration:"0%, including a zero-duration milestone.",zeroDenominator:"0%, never NaN or Infinity.",suspendResume:"No direct effect; only duration inputs affect the percentage.",calendarException:"No direct effect after durations are canonical working hours.",signedValues:"Negative/non-finite duration inputs are rejected.",nullValue:"Duration inputs are required canonical scalars, not nullable.",milestone:"0% for zero Original Duration under the certified P6 golden."},z0={notStarted:"Actual units are normally zero; result is 0%.",inProgress:"100 \xD7 (actual labor + actual nonlabor) / (actual + remaining units).",completed:"100% when remaining units are zero and actual units are positive.",zeroDuration:"Independent of duration; units still control the result.",zeroDenominator:"0%, never NaN or Infinity.",suspendResume:"No direct effect.",calendarException:"No direct effect on already canonical assignment scalars.",signedValues:"Finite negative unit scalars are preserved; P6 can produce percentages below 0% or above 100%. Non-finite inputs are rejected.",nullValue:"Canonical TASK unit scalars are required; missing assignment totals hydrate as zero.",milestone:"0% with no units; otherwise the same units formula."},J0={notStarted:"0% when Data Date is at or before primary baseline start.",inProgress:"Baseline working time elapsed through Data Date divided by total baseline working time.",completed:"100% when Data Date is at or after primary baseline finish.",zeroDuration:"0% before the coincident endpoint and 100% at or after it.",zeroDenominator:"0% when signed baseline working duration is non-positive.",suspendResume:"No direct effect; baseline dates and Data Date are authoritative.",calendarException:"Elapsed and total durations use the activity calendar exception set.",signedValues:"Result is clamped to 0..100; P6 UI does not allow an inverted assigned baseline.",nullValue:"When neither primary baseline endpoint is assigned, P6 uses Current Project planned dates; one missing endpoint or missing effective planned dates returns null.",milestone:"Boundary result is determined by Data Date relative to the coincident baseline endpoints."},X0={notStarted:"Calculated from remaining early and late endpoints.",inProgress:"Same remaining endpoint formula after the selected OOS policy forward/backward passes.",completed:"null when no remaining endpoints exist.",zeroDuration:"Can be positive, zero or negative; milestone duration does not erase float.",zeroDenominator:"Not applicable; no division.",suspendResume:"Affects scheduled endpoints before float is measured.",calendarException:"Start and finish float use signed working time on the activity calendar.",signedValues:"Negative float is preserved exactly; -0 normalizes to numeric 0.",nullValue:"null when required start/finish endpoints for the selected method are absent.",milestone:"Measured between coincident remaining endpoint and its late endpoint."},Ye=(t,e)=>`Input: canonical activities, relationships, Data Date and settings; phase: ${t}; policy: retained logic/progress override/actual dates relation classification; constraint: primary, secondary and project bounds; calendar: activity and configured lag calendars with exceptions; result: ${e}.`,oD=Object.freeze([kt({uiName:"Actual Start",property:"actualStart",xerField:"TASK.act_start_date",xmlField:"Activity.ActualStart",classification:"reality",typeAndUnit:"Date | null, exact UTC instant",editability:"controlled",authority:"Imported/user-confirmed actual reality",phase:"input",algorithm:"Input only; status validation may infer status but F9 never moves it.",interactions:"Activity Status, Actual Finish, Actual Duration and OOS policy.",unitTest:ar,p6Golden:Sn}),kt({uiName:"Actual Finish",property:"actualFinish",xerField:"TASK.act_end_date",xmlField:"Activity.ActualFinish",classification:"reality",typeAndUnit:"Date | null, exact UTC instant",editability:"controlled",authority:"Imported/user-confirmed actual reality",phase:"input",algorithm:"Input only; completed status requires a consistent actual endpoint; F9 never moves it.",interactions:"Activity Status, Actual Start and Actual Duration.",unitTest:ar,p6Golden:Sn}),kt({uiName:"Planned Start",property:"plannedStart",xerField:"TASK.target_start_date",xmlField:"Activity.PlannedStart",classification:"editable_input",typeAndUnit:"Date | null, exact UTC instant",editability:"editable",authority:"Imported/user input",phase:"input",algorithm:"Initial planning input; never replaced by projected Start.",interactions:"At Completion Duration and not-started fallback.",unitTest:ar,p6Golden:Sn}),kt({uiName:"Planned Finish",property:"plannedFinish",xerField:"TASK.target_end_date",xmlField:"Activity.PlannedFinish",classification:"editable_input",typeAndUnit:"Date | null, exact UTC instant",editability:"editable",authority:"Imported/user input",phase:"input",algorithm:"Initial planning input; never replaced by projected Finish.",interactions:"At Completion Duration and not-started fallback.",unitTest:ar,p6Golden:Sn}),kt({uiName:"Remaining Duration",property:"remainingDurationHours",xerField:"TASK.remain_drtn_hr_cnt",xmlField:"Activity.RemainingDuration",classification:"editable_input",typeAndUnit:"number, working hours",editability:"editable",authority:"Imported/user input consumed by explicit F9",phase:"input",algorithm:"Forward pass consumes/preserves remaining working hours according to status and OOS policy.",interactions:"Remaining Early Finish, Actual/At Completion Duration and Duration %.",unitTest:ar,p6Golden:Sn}),kt({uiName:"Activity Status",property:"executionStatus",xerField:"TASK.status_code",xmlField:"Activity.Status",classification:"reality",typeAndUnit:"not_started | in_progress | completed",editability:"controlled",authority:"Actual-date/status invariant",phase:"input",algorithm:"Validated before F9; scheduling never invents actual dates.",interactions:"Actual endpoints, Remaining Duration and all derived duration fields.",unitTest:"src/p6/status.test.ts",p6Golden:Sn}),kt({uiName:"Expected Finish",property:"expectedFinish",xerField:"TASK.expect_end_date",xmlField:"Activity.ExpectedFinish",classification:"editable_input",typeAndUnit:"Date | null, exact UTC instant",editability:"editable",authority:"Imported/user input plus useExpectedFinishDates setting",phase:"input",algorithm:"Forward bound only when the project setting enables Expected Finish dates.",interactions:"Use Expected Finish Dates and Remaining Early Finish.",unitTest:"src/p6/testing/p6-native/obdd-native.schedule.test.ts",p6Golden:"src/p6/testing/p6-native/fixtures/obdd-native-step24-expected-finish-calendar-exception.xer"}),kt({uiName:"Suspend Date",property:"suspendDate",xerField:"TASK.suspend_date",xmlField:"Activity.SuspendDate",classification:"reality",typeAndUnit:"Date | null, exact UTC instant",editability:"editable",authority:"Imported/user actual reality",phase:"input",algorithm:"Preserved; duration derivation subtracts the valid Suspend..Resume overlap.",interactions:"Resume Date, Actual Duration and At Completion Duration.",unitTest:vn,p6Golden:or}),kt({uiName:"Resume Date",property:"resumeDate",xerField:"TASK.resume_date",xmlField:"Activity.ResumeDate",classification:"reality",typeAndUnit:"Date | null, exact UTC instant",editability:"editable",authority:"Imported/user actual reality",phase:"input",algorithm:"Preserved; duration derivation subtracts the valid Suspend..Resume overlap.",interactions:"Suspend Date, Actual Duration and At Completion Duration.",unitTest:vn,p6Golden:or}),kt({uiName:"Secondary Constraint",property:"secondaryConstraintType",xerField:"TASK.cstr_type2",xmlField:"Activity.SecondaryConstraintType",classification:"editable_input",typeAndUnit:"canonical P6 constraint enum | null",editability:"editable",authority:"Imported/user input",phase:"input",algorithm:"Constraint classifier applies the declared start/finish lower/upper bound during forward/backward passes.",interactions:"Secondary Constraint Date, primary constraint and calendars.",unitTest:ar,p6Golden:"src/p6/testing/p6-native/fixtures/obdd-native-step18-secondary-finish-on-or-after.xer"}),kt({uiName:"Secondary Constraint Date",property:"secondaryConstraintDate",xerField:"TASK.cstr_date2",xmlField:"Activity.SecondaryConstraintDate",classification:"editable_input",typeAndUnit:"Date | null, exact UTC instant",editability:"editable",authority:"Imported/user input",phase:"input",algorithm:"Provides the exact bound for Secondary Constraint Type; ignored when type is null.",interactions:"Secondary Constraint Type and early/late passes.",unitTest:ar,p6Golden:"src/p6/testing/p6-native/fixtures/obdd-native-step18-secondary-finish-on-or-after.xer"}),kt({uiName:"Percent Complete Type",property:"percentCompleteType",xerField:"TASK.complete_pct_type",xmlField:"Activity.PercentCompleteType",classification:"editable_input",typeAndUnit:"duration | units | physical",editability:"editable",authority:"Imported/user input",phase:"input",algorithm:"Selects displayed progress authority; individual derived percentages remain independently calculated.",interactions:"Physical %, Duration %, Units % and progress projection.",unitTest:vn,p6Golden:or}),kt({uiName:"Physical % Complete",property:"physicalPercentComplete",xerField:"TASK.phys_complete_pct",xmlField:"Activity.PhysicalPercentComplete",classification:"editable_input",typeAndUnit:"number, percentage points 0..100",editability:"editable",authority:"Imported/user physical-progress input",phase:"input",algorithm:"Preserved by F9 and used only when Percent Complete Type is physical.",interactions:"Percent Complete Type and visible progress.",unitTest:ar,p6Golden:Sn}),kt({uiName:"Actual Duration",property:"actualDurationHours",xerField:"TASK.act_drtn_hr_cnt or actual endpoints",xmlField:"Activity.ActualDuration",classification:"derived",lifecycle:"open",typeAndUnit:"number, working hours",editability:"readonly",authority:"Schedule Core deriveP6ActivityFields",phase:"derived",algorithm:"Status-specific non-negative working duration using actual endpoints/Data Date minus suspended overlap; reversed endpoints clamp to zero.",interactions:"Status, Actual Start/Finish, Data Date, Suspend/Resume and activity calendar.",unitTest:vn,p6Golden:or,status:"PARTIAL",edgeCases:G0}),kt({uiName:"At Completion Duration",property:"atCompletionDurationHours",xerField:"TASK.total_drtn_hr_cnt or planned/actual/remaining endpoints",xmlField:"Activity.AtCompletionDuration",classification:"derived",lifecycle:"open",typeAndUnit:"number, working hours",editability:"readonly",authority:"Schedule Core deriveP6ActivityFields",phase:"derived",algorithm:"Not started: planned interval; in progress: Actual Start..Remaining Early Finish; completed: actual interval.",interactions:"Status, planned/actual/remaining endpoints, Suspend/Resume and calendar.",unitTest:vn,p6Golden:or,status:"PARTIAL",edgeCases:q0}),kt({uiName:"Duration % Complete",property:"durationPercentComplete",xerField:"TASK.target_drtn_hr_cnt + remain_drtn_hr_cnt",xmlField:"Activity.DurationPercentComplete",classification:"derived",lifecycle:"open",typeAndUnit:"number, percentage points",editability:"readonly",authority:"Schedule Core deriveP6ActivityFields",phase:"derived",algorithm:"100 \xD7 (Original Duration - Remaining Duration) / Original Duration, clamped to 0..100.",interactions:"Original and Remaining Duration; independent of Percent Complete Type selection.",unitTest:vn,p6Golden:or,status:"PARTIAL",edgeCases:$0}),kt({uiName:"Units % Complete",property:"unitsPercentComplete",xerField:"TASKRSRC actual and remaining unit scalars",xmlField:"Activity.ResourceAssignment.ActualUnits/RemainingUnits",classification:"derived",lifecycle:"open",typeAndUnit:"number, percentage points",editability:"readonly",authority:"Schedule Core deriveP6ActivityFields over canonical TASK scalars",phase:"derived",algorithm:"100 \xD7 total actual labor/nonlabor units / (actual + remaining units); zero denominator returns 0; finite signed values are not clamped.",interactions:"TASK unit scalars and Percent Complete Type; no full assignment subsystem.",unitTest:vn,p6Golden:or,status:"PARTIAL",edgeCases:z0}),kt({uiName:"Schedule % Complete",property:"schedulePercentComplete",xerField:"PROJECT.last_recalc_date + assigned baseline TASK dates, otherwise current TASK planned dates",xmlField:"Activity.SchedulePercentComplete",classification:"derived",lifecycle:"dependency_change",typeAndUnit:"number | null, percentage points",editability:"readonly",authority:"Schedule Core deriveP6ActivityFields",phase:"derived",algorithm:"Working effective-baseline time elapsed at Data Date / total working time, clamped to 0..100; a coincident milestone is 100% at its timestamp.",interactions:"Data Date, assigned baseline/current planned dates and activity calendar.",unitTest:vn,p6Golden:or,status:"VERIFIED",edgeCases:J0}),kt({uiName:"Remaining Float",property:"remainingFloatHours",xerField:"TASK remaining early/late endpoints",xmlField:"Activity.RemainingFloat",classification:"derived",lifecycle:"f9",typeAndUnit:"number | null, signed working hours",editability:"readonly",authority:"Schedule Core deriveP6ActivityFields",phase:"derived",algorithm:"Start Float, Finish Float or their minimum as selected, using signed working duration.",interactions:"Total Float method, remaining early/late endpoints and activity calendar.",unitTest:vn,p6Golden:"src/p6/testing/p6-float-method/fixtures/obdd-float-method-smallest.xer",status:"VERIFIED",edgeCases:X0}),kt({uiName:"Remaining Early Start",property:"remainingEarlyStart",xerField:"TASK.restart_date",xmlField:"Activity.RemainingEarlyStart",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 forward pass",phase:"forward",algorithm:Ye("forward","earliest start of remaining work"),interactions:"Data Date, predecessors, OOS policy, constraints and calendar.",unitTest:"src/p6/testing/p6-data-date/obdd-math.schedule.test.ts",p6Golden:Sn,status:"VERIFIED"}),kt({uiName:"Remaining Early Finish",property:"remainingEarlyFinish",xerField:"TASK.reend_date",xmlField:"Activity.RemainingEarlyFinish",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 forward pass",phase:"forward",algorithm:Ye("forward","calendar finish after remaining duration"),interactions:"Remaining Early Start, Remaining Duration, OOS policy and calendar.",unitTest:"src/p6/testing/p6-data-date/obdd-math.schedule.test.ts",p6Golden:Sn,status:"VERIFIED"}),kt({uiName:"Remaining Late Start",property:"remainingLateStart",xerField:"TASK.rem_late_start_date",xmlField:"Activity.RemainingLateStart",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 backward pass",phase:"backward",algorithm:Ye("backward","latest remaining start without violating successor/project bounds"),interactions:"Remaining Late Finish, constraints, successors and calendar.",unitTest:da,p6Golden:ua,status:"VERIFIED"}),kt({uiName:"Remaining Late Finish",property:"remainingLateFinish",xerField:"TASK.rem_late_end_date",xmlField:"Activity.RemainingLateFinish",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 backward pass",phase:"backward",algorithm:Ye("backward","latest remaining finish without violating successor/project bounds"),interactions:"Successors, Must Finish By, constraints and calendar.",unitTest:da,p6Golden:ua,status:"VERIFIED"}),kt({uiName:"Early Start",property:"earlyStart",xerField:"TASK.early_start_date",xmlField:"Activity.EarlyStart",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 forward pass",phase:"forward",algorithm:Ye("forward","projected early start respecting immutable actuals"),interactions:"Actual Start, Remaining Early Start and OOS policy.",unitTest:da,p6Golden:ua,status:"VERIFIED"}),kt({uiName:"Early Finish",property:"earlyFinish",xerField:"TASK.early_end_date",xmlField:"Activity.EarlyFinish",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 forward pass",phase:"forward",algorithm:Ye("forward","projected early finish respecting immutable actuals"),interactions:"Actual Finish, Remaining Early Finish and OOS policy.",unitTest:da,p6Golden:ua,status:"VERIFIED"}),kt({uiName:"Late Start",property:"lateStart",xerField:"TASK.late_start_date",xmlField:"Activity.LateStart",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 backward pass",phase:"backward",algorithm:Ye("backward","projected late start"),interactions:"Remaining Late Start, constraints, float and immutable actuals.",unitTest:da,p6Golden:ua,status:"VERIFIED"}),kt({uiName:"Late Finish",property:"lateFinish",xerField:"TASK.late_end_date",xmlField:"Activity.LateFinish",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 backward pass",phase:"backward",algorithm:Ye("backward","projected late finish"),interactions:"Remaining Late Finish, Must Finish By, constraints and float.",unitTest:da,p6Golden:ua,status:"VERIFIED"}),kt({uiName:"Float Path",property:"floatPath",xerField:"TASK.float_path",xmlField:"Activity.FloatPath",classification:"f9_output",typeAndUnit:"number | null, path number",editability:"readonly",authority:"Schedule Core P6 float-path pass",phase:"float_path",algorithm:Ye("float_path","selected multiple-float-path identifier"),interactions:"Ending Activity, Total/Free Float selection, enabled and path limit settings.",unitTest:"src/p6/paths.test.ts",p6Golden:"src/p6/testing/p6-floats/fixtures/obdd-floats-multiple-paths-limit-2.xer",status:"VERIFIED"}),kt({uiName:"Float Path Order",property:"floatPathOrder",xerField:"TASK.float_path_order",xmlField:"Activity.FloatPathOrder",classification:"f9_output",typeAndUnit:"number | null, ordinal",editability:"readonly",authority:"Schedule Core P6 float-path pass",phase:"float_path",algorithm:Ye("float_path","stable order inside the selected float path"),interactions:"Float Path, relationship topology and deterministic tie-breaking.",unitTest:"src/p6/paths.test.ts",p6Golden:"src/p6/testing/p6-floats/fixtures/obdd-floats-multiple-paths-limit-2.xer",status:"VERIFIED"}),kt({uiName:"Longest Path",property:"longestPath",xerField:"TASK.driving_path_flag",xmlField:"Activity.IsLongestPath",classification:"f9_output",typeAndUnit:"boolean",editability:"readonly",authority:"Schedule Core P6 float-path pass",phase:"float_path",algorithm:Ye("float_path","true for activities on the selected longest path"),interactions:"Critical Activity Method, Ending Activity and deterministic path topology.",unitTest:"src/p6/paths.test.ts",p6Golden:"src/p6/testing/p6-floats/fixtures/obdd-floats-longest-path.xer",status:"VERIFIED"})]);var sD={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 lD=8;var cD={CHILD:"child",LINE:"line",ROOT:"root"};return mD(Z0);})();
2
2
  //# sourceMappingURL=schedule-core.global.js.map