@outbuild-company/schedule-core 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var ScheduleCore=(()=>{var pi=Object.defineProperty;var Jl=Object.getOwnPropertyDescriptor;var Xl=Object.getOwnPropertyNames;var Zl=Object.prototype.hasOwnProperty;var Ql=(e,t)=>{for(var n in t)pi(e,n,{get:t[n],enumerable:!0})},td=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Xl(t))!Zl.call(e,r)&&r!==n&&pi(e,r,{get:()=>t[r],enumerable:!(i=Jl(t,r))||i.enumerable});return e};var ed=e=>td(pi({},"__esModule",{value:!0}),e);var Kh={};Ql(Kh,{ACTIVITY_TYPE:()=>tn,CALENDAR_UNIT:()=>at,COLUMN:()=>v,CONSTRAINT_TYPE:()=>$,CONSTRAINT_TYPE_TO_LABEL:()=>Kl,CREATION_KIND:()=>zl,DEFAULT_HOURS_PER_DAY:()=>jt,DISPATCH_ACTION_KIND:()=>z,DISPATCH_ACTION_KINDS:()=>ql,DISPATCH_TRACK_EVENT:()=>ht,LINK_CODE_TO_TYPE:()=>Ht,LINK_TYPE:()=>B,LINK_TYPE_CODE:()=>ln,NEW_ACTIVITY_DEFAULTS:()=>Wn,REJECTION_REASON:()=>E,ROOT_PARENT_ID:()=>O,ScheduleCore:()=>fi,WORK_TIME_DIRECTION:()=>q,applyBaselinePoints:()=>Gn,checkNoUpdatedLinks:()=>Vl,computeExpectedProgress:()=>yr,expectedProgressFromBaseline:()=>fe,getActiveBaseline:()=>Ct,getUnsavedActivities:()=>Gl,isRootParent:()=>b,normalizeParentKey:()=>_t,parseFromBackend:()=>Qn,recomputeAllPonderators:()=>Yn,recomputeAllProgressRollup:()=>Vn,willRunCriticalPath:()=>zc,yieldToBrowser:()=>nt});var ut=class{items=[];head=0;enqueue(t){this.items.push(t)}dequeue(){if(this.head>=this.items.length)return;let t=this.items[this.head];return this.head+=1,t}peek(){if(!(this.head>=this.items.length))return this.items[this.head]}get size(){return this.items.length-this.head}isEmpty(){return this.head>=this.items.length}};var je=e=>String(e);function Wr(e){let{clickedId:t,isChecked:n,currentSelection:i,hierarchy:r,isFrozen:s,exists:a,autoCheckParents:o}=e,c=je(t),l=new Set([...i].map(String)),d=new Set(l),u=nd(c,r).filter(a),f=u.filter(A=>!s(A)),p=n&&f.length<u.length;n&&!p?d.add(c):d.delete(c);for(let A of f)n?d.add(A):d.delete(A);return p||id({id:c,isChecked:n,autoCheckParents:o,hierarchy:r,isFrozen:s,exists:a,next:d}),{nextSelection:d,changed:rd(l,d),parentBlocked:p}}function nd(e,t){let n=[],i=new ut;i.enqueue(e);let r=new Set([e]);for(;!i.isEmpty();){let s=i.dequeue();for(let a of t.getChildrenIds(s)){let o=je(a);r.has(o)||(r.add(o),n.push(o),i.enqueue(o))}}return n}function id(e){let{id:t,isChecked:n,autoCheckParents:i,hierarchy:r,isFrozen:s,exists:a,next:o}=e,c=r.getParentId(t);for(;c!==null&&typeof c<"u";){let l=je(c);if(s(l))return;let d=r.getChildrenIds(l).map(je).filter(a),u=d.some(s),f=d.filter(I=>!s(I)),A=f.length>0&&f.every(I=>o.has(I))&&!u;if(n){if(!i||!A||o.has(l))return;o.add(l)}else{if(A||!o.has(l))return;o.delete(l)}c=r.getParentId(l)}}function rd(e,t){let n=[],i=[];for(let r of t)e.has(r)||n.push(r);for(let r of e)t.has(r)||i.push(r);return{checked:n,unchecked:i}}function Zt(e){return(e.pendingRequests?.length??0)>0}var E={CANNOT_EDIT:"cannot_edit",PARSE_ERROR:"parse_error",INVALID:"invalid",CUSTOM_ID_DUPLICATE:"custom_id_duplicate",INVALID_LINK_TYPE:"invalid_link_type",INVALID_LINK_LAG:"invalid_link_lag",INVALID_VALUE:"invalid_value",NO_PIPELINE_FOR_COLUMN:"no_pipeline_for_column",ACTIVITY_NOT_FOUND:"activity_not_found",PARENT_NOT_FOUND:"parent_not_found",ACTIVITY_IDS_EMPTY:"activity_ids_empty",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",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var sd=e=>e.checked===!0,Ur=(e,t)=>{let n=e.getActivity(t);return n!=null&&Zt(n)};function He(e){let t=[];return e.forEachActivity((n,i)=>{sd(n)&&t.push(i)}),t}var Br=(e,t,n)=>{let i=[],r=(s,a)=>{let o=t.adapter.getActivity(s);if(!o)return;let c={checked:o.checked,visibleChecked:o.visibleChecked,mustApplyVisibleChecked:o.mustApplyVisibleChecked};o.checked=a,o.visibleChecked=a,o.mustApplyVisibleChecked=a,i.push({id:s,kind:"updated",fields:{checked:{before:c.checked,after:a},visibleChecked:{before:c.visibleChecked,after:a},mustApplyVisibleChecked:{before:c.mustApplyVisibleChecked,after:a}},after:{id:s,checked:a,visibleChecked:a,mustApplyVisibleChecked:a}})};for(let s of n.checked)r(s,!0);for(let s of n.unchecked)r(s,!1);return{source:e,activities:i,links:[],calendars:[],trackingEvents:[]}};function jr(e,t){let{adapter:n}=t,i=e.activityId;if(!n.getActivity(i))return{ok:!1,reason:E.ACTIVITY_NOT_FOUND};let r=e.frozenIds?new Set(e.frozenIds):null,s=r?o=>r.has(o):o=>Ur(n,o),a=Wr({clickedId:i,isChecked:e.isChecked,currentSelection:new Set(He(n)),hierarchy:{getChildrenIds:o=>n.getChildren(o),getParentId:o=>{let c=n.getParentId(o);return!c||c==="0"?null:String(c)}},isFrozen:s,exists:o=>n.activityExists(o),autoCheckParents:e.autoCheckParents??!1});return{ok:!0,changes:Br(e,t,a.changed)}}function Hr(e,t){let{adapter:n}=t,i=new Set(e.activityIds.map(String).filter(a=>n.activityExists(a)).filter(a=>!Ur(n,a))),r=new Set(He(n)),s={checked:[...i].filter(a=>!r.has(a)),unchecked:[...r].filter(a=>!i.has(a))};return{ok:!0,changes:Br(e,t,s)}}var ad=e=>e.visible!==!1;function $r(e,t){let{adapter:n}=t,i=new Set(e.visibleIds.map(String)),r=[];return n.forEachActivity((a,o)=>{let c=i.has(String(o));if(ad(a)===c)return;let l=a.visible;a.visible=c,r.push({id:o,kind:"updated",fields:{visible:{before:l,after:c}},after:{id:o,visible:c}})}),{ok:!0,changes:{source:e,activities:r,links:[],calendars:[],trackingEvents:[]}}}var Yr="text";var Vr="description";var Qt="duration",Gr="for_disable_milestone_duration",Kr="$keep_constraints";var qr="progress",hi="progressChangedByActionButton";var zr="cost";var Jr="used_cost";var Xr="hhWorkTime";var $e="start_date",Zr="last_start_date";var te="end_date";var Ye="constraint_type",Wt="real_constraint_type",mi="constraint_type_old",Ve="last_constraint";var Ut="constraint_date",yi="last_constraint_date";var Qr="calendar_id";var ts="custom_id";var es="subcontractId";var ns="responsables";var is="tags";var rs="custom_predecessors";var ss="custom_sucessors";var Ge="real_work";var as="real_cost";var os="expected_progress";var cs="expected_progress_base";var Ke="start_base";var qe="end_base";var ze="duration_base";var Je="cost_base";var Xe="work_base";var ls="calendarDuration";var ds="is_critical",us="earlyStart",fs="earlyFinish",ps="lateStart",hs="lateFinish",ms="freeSlack",ys="totalSlack";var gs="correlative_id";var vs="unique_correlative_id";var As="ponderator";var Ze="status",Bt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"},gi="Baseline";function Qe(e){return e==="Actual"?"Actual":gi}var od={TEXT:Yr,DESCRIPTION:Vr,DURATION:Qt,PROGRESS:qr,COST:zr,USED_COST:Jr,HH_WORK_TIME:Xr,START_DATE:$e,END_DATE:te,CONSTRAINT_TYPE:Ye,CONSTRAINT_DATE:Ut,CALENDAR_ID:Qr,CUSTOM_ID:ts,SUBCONTRACT_ID:es,RESPONSABLES:ns,TAGS:is,CUSTOM_PREDECESSORS:rs,CUSTOM_SUCESSORS:ss},cd={REAL_WORK:Ge,REAL_COST:as,EXPECTED_PROGRESS:os,EXPECTED_PROGRESS_BASE:cs,START_BASE:Ke,END_BASE:qe,DURATION_BASE:ze,COST_BASE:Je,WORK_BASE:Xe,CALENDAR_DURATION:ls,IS_CRITICAL:ds,EARLY_START:us,EARLY_FINISH:fs,LATE_START:ps,LATE_FINISH:hs,FREE_SLACK:ms,TOTAL_SLACK:ys,CORRELATIVE_ID:gs,UNIQUE_CORRELATIVE_ID:vs,PONDERATOR:As,STATUS:Ze},v={...od,...cd};function Cs(e,t){throw new Error(t)}function Ss(e,t){return()=>t()===e}var q={FUTURE:"future",PAST:"past"},at={HOUR:"hour",DAY:"day"};var $={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},ld={mso:()=>!0,mfo:()=>!0,snlt:(e,t)=>e<t,snet:(e,t)=>e>t,fnlt:(e,t)=>e<t,fnet:(e,t)=>e>t};function ks(e,t,n){if(!t)return{violated:!1};let i=ld[e];return i?i(t,n)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var dd=new Set(["mso","snet","snlt"]);function Ae(e,t,n){return dd.has(e)?t:n}function Is(e,t,n){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...n?{projectedDate:n}:{}}}}var ud={snet:{startOfDay:!0,direction:q.FUTURE},snlt:{startOfDay:!0,direction:q.PAST},fnet:{startOfDay:!1,direction:q.FUTURE},fnlt:{startOfDay:!1,direction:q.PAST},mso:{startOfDay:!0,direction:q.FUTURE},mfo:{startOfDay:!1,direction:q.PAST}},_s=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),fd=(e,t)=>new Date(e.getTime()+t*864e5),pd=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function hd(e,t){if(!e.constraint_date||!e.constraint_type)return null;let n=ud[e.constraint_type];if(!n)return e.constraint_date;let i=e.constraint_date,r=t.getClosestWorkTime({date:_s(i),dir:q.FUTURE,task:e});if(pd(r,i))return i;let s=_s(t.getClosestWorkTime({date:i,dir:n.direction,task:e}));return n.startOfDay?t.getClosestWorkTime({date:s,dir:q.FUTURE,task:e}):t.getClosestWorkTime({date:fd(s,1),dir:q.PAST,task:e})}function Ts(e,t){let n={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},i=e.constraint_type;if(!i||i==="asap"||i==="alap")return n;let r=hd(e,t);if(!r)return n;let s=o=>t.calculateEndDate({start_date:o,duration:e.duration,task:e}),a=o=>t.calculateEndDate({start_date:o,duration:-e.duration,task:e});switch(i){case"snet":return{earliestStart:r,latestStart:null,earliestEnd:s(r),latestEnd:null};case"snlt":return{earliestStart:null,latestStart:r,earliestEnd:null,latestEnd:s(r)};case"fnet":return{earliestStart:a(r),latestStart:null,earliestEnd:r,latestEnd:null};case"fnlt":return{earliestStart:null,latestStart:a(r),earliestEnd:null,latestEnd:r};case"mso":{let o=s(r);return{earliestStart:r,latestStart:r,earliestEnd:o,latestEnd:o}}case"mfo":{let o=a(r);return{earliestStart:o,latestStart:o,earliestEnd:r,latestEnd:r}}default:return n}}function Ds(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function vi(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var B={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"};var tn={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},Es={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var en=typeof window>"u",Ai=!en&&typeof MessageChannel<"u"?new MessageChannel:null;function nt(){return en||!Ai?Promise.resolve():new Promise(e=>{Ai.port1.onmessage=()=>e(),Ai.port2.postMessage(null)})}async function nn(e,t){return performance.now()-e<Es.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await nt(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function ee(e){return en?{aborted:!1}:(await nt(),e()?{aborted:!1}:{aborted:!0})}function rn(e,t){let{inDegree:n,successors:i}=md(e,t),r=yd(n),s=gd(r,n,i),a=s.length<e.length,o=a?vd(e,s):[],c=[...s].reverse();return{ordered:s,reversed:c,hasCycles:a,cycleNodes:o}}function md(e,t){let n=new Map,i=new Map;for(let r of e)n.set(r,0),i.set(r,[]);for(let r of t){let s=r.source,a=r.target;!n.has(s)||!n.has(a)||(i.get(s).push(a),n.set(a,(n.get(a)??0)+1))}return{inDegree:n,successors:i}}function yd(e){let t=new ut;for(let[n,i]of e)i===0&&t.enqueue(n);return t}function gd(e,t,n){let i=[];for(;!e.isEmpty();){let r=e.dequeue();i.push(r);for(let s of n.get(r)??[]){let a=(t.get(s)??1)-1;t.set(s,a),a===0&&e.enqueue(s)}}return i}function vd(e,t){let n=new Set(t);return e.filter(i=>!n.has(i))}var sn=class{cached=null;invalidate(){this.cached=null}get(t,n){return this.cached?this.cached:(this.cached=rn(t,n),this.cached)}};function Ps(e,t){let n=[];for(let i of e)t.has(i)&&n.push(i);return n}var Ci={project:{alwaysSummary:!0,holdsConstraint:!1,carriesCustomId:!1,forcedDuration:null,ponderatorWeight:"recursive-leaf-sum",promotesToProjectOnFirstChild:!1},task:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:null,ponderatorWeight:"own-baseline",promotesToProjectOnFirstChild:!0},milestone:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:0,ponderatorWeight:"zero",promotesToProjectOnFirstChild:!0}};function Si(e){return e==="project"||e==="task"||e==="milestone"}function St(e,t){return t||Si(e)&&Ci[e].alwaysSummary}function Rt(e){return Si(e)&&Ci[e].promotesToProjectOnFirstChild}var an="project",Ce="task";function Se(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function Rs(e,t){let n=t.getActivity(e);return n?St(n.type,t.getChildren(e).length>0):!1}function Ls(e,t,n){let i=String(t),r=n.getActivity(e);for(;r?.parent&&String(r.parent)!=="0";){if(String(r.parent)===i)return!0;r=n.getActivity(r.parent)}return!1}function bs(e,t){let n=[],i=[e];for(;i.length>0;){let r=i.pop(),s=t.getChildren(r);if(s.length===0){String(r)!==String(e)&&n.push(r);continue}for(let a of s)i.push(a)}return n}function Ad(e){let t=new Map;for(let n of e)Os(t,String(n.source),n),Os(t,String(n.target),n);return t}function Os(e,t,n){let i=e.get(t);if(i){i.push(n);return}e.set(t,[n])}function Cd(e,t,n){if(e.length<=1)return e;let i=new Set(e.map(String)),r=[];for(let s of e)Sd(s,i,t,n)||r.push(s);return r.length>0?r:e}function Sd(e,t,n,i){let r=String(e),s=n.getActivity(e);if(!s||s.auto_scheduling===!1)return!1;let a=i.get(r)??[];for(let o of a){if(_d(o))continue;let c=kd(o,r);if(!t.has(String(c)))continue;let l=n.getActivity(c);if(l&&l.auto_scheduling!==!1&&Id(o,e,s,c,l))return!0}return!1}function _d(e){return e.source===e.target}function kd(e,t){return String(e.source)===t?e.target:e.source}function Id(e,t,n,i,r){let s=e.lag??0,a=Math.abs(s);return e.target===t&&a<=n.duration||e.target===i&&a<=r.duration}function Ns(e,t){let n=[],i=Ad(e),r=0;for(let s of e){let a=Rs(s.source,t),o=Rs(s.target,t);if(a&&o||o&&Ls(s.source,s.target,t)||a&&Ls(s.target,s.source,t))continue;if(!a&&!o){n.push(s);continue}let c=a?bs(s.source,t):[s.source],l=o?bs(s.target,t):[s.target];if(a&&(c=ws(c,!1,t)),o){let d=Cd(l,t,i);if(s.type===B.FINISH_TO_FINISH||s.type===B.START_TO_FINISH){r=Td(n,c,d,s,s.target,t,r);continue}l=ws(d,!0,t)}r=Dd(n,c,l,s,r)}return n}function Td(e,t,n,i,r,s,a){let o=s.getActivity(r),c=o?.start_date,l=o?.duration??0,d=i.lag??0,u=s.getActivity(i.source),f=a;for(let p of t)for(let A of n){if(String(p)===String(A))continue;let I=s.getActivity(A),S=c&&I&&u?s.calculateDuration({start_date:c,end_date:I.start_date,task:u}):0;e.push({id:`virtual_${i.id}_${f}`,source:p,target:A,type:i.type,lag:i.lag,_sourceLag:0,_targetLag:-l,_trueLag:d+S}),f+=1}return f}function ws(e,t,n){if(e.length<=1)return e;let i=null;for(let s of e){let a=n.getActivity(s),o=t?a?.start_date:a?.end_date;if(!o)continue;let c=o.getTime();(i===null||(t?c<i:c>i))&&(i=c)}if(i===null)return e;let r=e.filter(s=>{let a=n.getActivity(s),o=t?a?.start_date:a?.end_date;return o!=null&&o.getTime()===i});return r.length>0?r:e}function Dd(e,t,n,i,r){let s=r;for(let a of t)for(let o of n)String(a)!==String(o)&&(e.push({id:`virtual_${i.id}_${s}`,source:a,target:o,type:i.type,lag:i.lag}),s+=1);return s}var on=class{invalidate(){}get(t,n){return Ns(t,n)}};function Ed(e){let t=new Map,n=i=>(t.has(i)||t.set(i,new Set),t.get(i));for(let i of e)n(i.source).add(i.id),n(i.target).add(i.id);return{neighbors:t}}function Pd(e,t,n){let i=new Set,r=new Map,s=new ut;for(s.enqueue(e);!s.isEmpty();){let a=s.dequeue(),o=String(a);if(i.has(o))continue;i.add(o);let c=n.neighbors.get(a);if(c)for(let l of c){let d=t.get(l);if(!d)continue;let u=`${d.source}-${d.target}-${d.type}`;r.has(u)||r.set(u,d);let f=String(d.source)===o?d.target:d.source;i.has(String(f))||s.enqueue(f)}}return Array.from(r.values())}function xs(e,t){let n=new Map;for(let a of t)n.set(a.id,a);let i=Ed(t),r=Pd(e,n,i),s=new Set([String(e)]);for(let a of r)s.add(String(a.source)),s.add(String(a.target));return{activityIds:s,links:r}}function Fs(e,t,n){let i=n.type===B.FINISH_TO_START,r=n.type===B.FINISH_TO_FINISH;if(n._targetLag!==void 0)return{sourceLag:n._sourceLag??0,targetLag:n._targetLag,trueLag:n._trueLag??n.lag??0,isFS:i,isFF:r,isZeroDurationCase:!1};let s=n.lag??0;switch(n.type){case B.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:s,isFS:i,isFF:r,isZeroDurationCase:!1};case B.START_TO_START:return{sourceLag:-e.duration,targetLag:0,trueLag:s,isFS:i,isFF:r,isZeroDurationCase:!1};case B.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.duration,trueLag:s,isFS:i,isFF:r,isZeroDurationCase:!1};case B.START_TO_FINISH:return{sourceLag:-e.duration,targetLag:-t.duration,trueLag:s,isFS:i,isFF:r,isZeroDurationCase:!1};default:return{sourceLag:0,targetLag:0,trueLag:s,isFS:i,isFF:r,isZeroDurationCase:!1}}}function Ms(e,t,n,i){let{sourceLag:r,targetLag:s,trueLag:a,isFS:o,isFF:c}=Fs(e,t,n);if(!(r!==0||s!==0||a!==0)){let f=o||c;return t.duration===0&&f?{successorStart:i.getClosestWorkTime({date:e.end_date,dir:"past",task:t}),link:n}:{successorStart:i.getClosestWorkTime({date:e.end_date,dir:"future",task:t}),link:n}}let d=o?t:e,u=i.getClosestWorkTime({date:e.end_date,dir:"future",task:d});if(r!==0&&(u=i.calculateEndDate({start_date:u,duration:r,task:e})),s!==0&&(u=i.calculateEndDate({start_date:u,duration:s,task:t})),a!==0&&(u=i.calculateEndDate({start_date:u,duration:a,task:t})),t.duration===0){if(o||c)return{successorStart:i.getClosestWorkTime({date:u,dir:"past",task:t}),link:n};let f=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth(),u.getUTCDate()));return{successorStart:i.getClosestWorkTime({date:f,dir:"future",task:t}),link:n}}return{successorStart:i.getClosestWorkTime({date:u,dir:"future",task:t}),link:n}}function Ws(e,t,n,i){let{sourceLag:r,targetLag:s,trueLag:a}=Fs(t,e,n),o=i.getClosestWorkTime({date:e.start_date,dir:"past",task:e});return a!==0&&(o=i.calculateEndDate({start_date:o,duration:-a,task:e})),s!==0&&(o=i.calculateEndDate({start_date:o,duration:-s,task:e})),r!==0&&(o=i.calculateEndDate({start_date:o,duration:-r,task:t})),o}function Us(e,t,n){for(let i of e){let r=t.getActivity(i);if(!r)continue;let s=r.constraint_type;if(!s||s===$.ASAP||s===$.ALAP)continue;let a=Ts(r,t);!a.earliestStart&&!a.latestStart&&!a.earliestEnd&&!a.latestEnd||n.set(i,{activityId:i,start_date:r.start_date,end_date:r.end_date,drivingLinkId:null,kind:"asap",conflict:!1,earliestStart:a.earliestStart,latestStart:a.latestStart,earliestEnd:a.earliestEnd,latestEnd:a.latestEnd})}}function cn(e,t,n){let i={earliestStart:t.earliestStart??null,latestStart:t.latestStart??null,earliestEnd:t.earliestEnd??null,latestEnd:t.latestEnd??null},r=t.earliestSchedulingStart??t.latestSchedulingStart??null,s;r===null?s=vi(e.start_date,i):Ds(r,i)?s=r:s=vi(r,i),t.start_date=s,t.end_date=n.calculateEndDate({start_date:s,duration:e.duration,task:e})}function Bs(e,t){if(!e||!t)return new Date;let{constraint_type:n,constraint_date:i}=e;if(!n||!i)return t;switch(n){case $.MSO:case $.MFO:return new Date(i);case $.SNET:case $.FNET:return i>t?new Date(i):t;case $.SNLT:case $.FNLT:return i<t?new Date(i):t;default:return t}}function js(e,t){return t.length?t.some(n=>String(n)===String(e)):!1}function Hs(e,t,n){return t.dragWithMultiple&&e.dragged&&js(e.id,n)?{start_date:e.start_date,end_date:e.end_date}:{start_date:e.start_date,end_date:e.end_date}}function $s(e,t,n){return t.dragWithMultiple&&js(e,n)}async function Vs(e,t,n,i,r,s){let a=new Map;for(let u of t){let f=String(u.target);a.has(f)||a.set(f,[]),a.get(f).push(u)}let o=u=>{let f=s.get(u);if(f?.start_date&&f.end_date)return{start_date:f.start_date,end_date:f.end_date};let p=n.getActivity(u);return p?{start_date:p.start_date,end_date:p.end_date}:{start_date:new Date,end_date:new Date}},c=n.getFlags(),l=i.draggedIds??[],d=performance.now();for(let u of e){let f=await nn(d,r);if(f.aborted)return s;d=f.newSliceStart;let p=n.getActivity(u);if(!p||!p.auto_scheduling||p.progress===100||Rd(p,n))continue;let A=a.get(String(u))??[],I=null,S=null;for(let y of A){let m=n.getActivity(y.source);if(!m)continue;let _=o(y.source),P={...m,start_date:_.start_date,end_date:_.end_date},D=Hs(P,c,l),R={...P,start_date:D.start_date,end_date:D.end_date},U=$s(y.source,c,l)?{...y,lag:0}:y,W=Ms(R,p,U,n);(!I||W.successorStart>I)&&(I=W.successorStart,S=String(y.id))}let T=s.get(u),g=T?{...T}:{activityId:u,start_date:p.start_date,end_date:p.end_date,drivingLinkId:null,kind:"asap",conflict:!1},C=g.earliestStart||g.latestStart||g.earliestEnd||g.latestEnd;if(!(!I&&!C)){if(I){let y=I;p.type===tn.MILESTONE&&(y=Bs(p,I)),g.drivingLinkId=S,g.start_date=y,g.end_date=n.calculateEndDate({start_date:y,duration:p.duration,task:p}),g.earliestSchedulingStart=y,g.earliestSchedulingEnd=g.end_date}else p.constraint_type===$.MSO?g.earliestStart&&(g.start_date=g.earliestStart,g.end_date=g.earliestEnd??n.calculateEndDate({start_date:g.earliestStart,duration:p.duration,task:p})):p.constraint_type===$.MFO&&g.latestStart&&(g.start_date=g.latestStart,g.end_date=g.latestEnd??n.calculateEndDate({start_date:g.latestStart,duration:p.duration,task:p}));cn(p,g,n),s.set(u,g)}}return s}function Rd(e,t){return St(e.type,t.getChildren(e.id).length>0)}var O="0";function b(e){return e==null||e===0||e==="0"}function _t(e){return b(e)?"0":String(e)}async function Gs(e,t,n,i,r,s){let a=new Map(n),o=i.getAllActivities(),c=o.length,l=[];for(let S of o)S.constraint_type===$.ALAP&&l.push(S.id);if(l.length===0)return a;let d=new Map,u=new Map;for(let S of t){let T=String(S.source);d.has(T)||d.set(T,[]),d.get(T).push(S);let g=String(S.target);u.has(g)||u.set(g,[]),u.get(g).push(S)}let f=S=>{let T=a.get(S);if(T)return{start_date:T.start_date,end_date:T.end_date};let g=i.getActivity(S);return g?{start_date:g.start_date,end_date:g.end_date}:{start_date:new Date,end_date:new Date}},p=S=>!S.parent||b(S.parent)?i.getProjectEnd():f(S.parent).end_date,A=(S,T)=>{let g=S,C=0;for(;g&&!b(g)&&C++<c+1;){if(String(g)===String(T))return!0;let y=i.getActivity(g);if(!y||!y.parent)break;g=y.parent}return!1},I=performance.now();for(let S of e){let T=await nn(I,s);if(T.aborted)return a;I=T.newSliceStart;let g=i.getActivity(S);if(!g||g.constraint_type!==$.ALAP||!g.auto_scheduling||g.progress===100||St(g.type,i.getChildren(S).length>0))continue;let C=p(g);if(!C)continue;let y=C,m=null,_=!1,P=d.get(String(S))??[];for(let H of P){if((H.lag??0)<0)continue;let et=i.getActivity(H.target);if(!et||et.auto_scheduling===!1)continue;let ct=f(H.target),Be={...et,start_date:ct.start_date,end_date:ct.end_date},Mt=Ws(Be,g,H,i);Mt<y&&(y=Mt),(m===null||Mt<m)&&(m=Mt,_=g.parent&&!b(g.parent)?A(H.target,g.parent):!1)}if(m!==null)if(_)y=m;else{let H=f(S).end_date,et=H.getTime()>C.getTime()?H:C;y=m<et?m:et}else y>C&&(y=C);let D;if(g.duration===0&&m===null)D=i.getClosestWorkTime({date:y,dir:"past",task:g});else if(g.duration===0)if((u.get(String(S))??[]).some(ct=>ct.type===B.FINISH_TO_START||ct.type===B.FINISH_TO_FINISH)){let ct=new Date(Date.UTC(y.getUTCFullYear(),y.getUTCMonth(),y.getUTCDate()));D=i.getClosestWorkTime({date:ct,dir:"past",task:g})}else D=i.getClosestWorkTime({date:y,dir:"future",task:g});else D=i.getClosestWorkTime({date:y,dir:"future",task:g});let R=i.calculateEndDate({start_date:D,duration:-g.duration,task:g}),U=a.get(S),W=U?{...U}:{activityId:S,start_date:R,end_date:D,drivingLinkId:null,kind:"alap",conflict:!1};W.start_date=R,W.end_date=D,W.drivingLinkId=null,W.kind="alap",W.earliestSchedulingStart=null,W.earliestSchedulingEnd=null,W.latestSchedulingStart=R,W.latestSchedulingEnd=D,cn(g,W,i),a.set(S,W)}return a}var ne={warn(){},error(){}};function _e(e,t){t.cancelled||t.updatedIds.length===0||e.batchUpdate(()=>{for(let n of t.updatedIds){let i=t.plans.get(n);if(!i)continue;let r=e.getLiveActivity(n);r&&(r.start_date=i.start_date,r.end_date=i.end_date,e.updateActivity(n))}})}var jt=8;var ln={[B.FINISH_TO_START]:"fs",[B.START_TO_START]:"ss",[B.FINISH_TO_FINISH]:"ff",[B.START_TO_FINISH]:"sf"},Ht={fs:B.FINISH_TO_START,ss:B.START_TO_START,ff:B.FINISH_TO_FINISH,sf:B.START_TO_FINISH},Ks="fs";function qs(e){if(e in Ht)return Ht[e]}var zs=";",Js=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function Xs(e,t){let n=String(t.source),i=String(t.target);if(n===i)return!0;let r=new Map;for(let s of e){let a=String(s.source),o=String(s.target),c=r.get(a)??[];c.push(o),r.set(a,c)}return Ld(r,i,n)}function Ld(e,t,n){if(t===n)return!0;let i=new Set([t]),r=new ut;for(r.enqueue(t);!r.isEmpty();){let s=r.dequeue(),a=e.get(s)??[];for(let o of a){if(o===n)return!0;i.has(o)||(i.add(o),r.enqueue(o))}}return!1}function Lt(e,t){switch(e.kind){case"create":return bd(e,t);case"update":return Od(e,t);case"delete":return wd(e,t)}}function bd(e,t){let{port:n}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:"self-link"};let i=n.getActivity(e.source),r=n.getActivity(e.target);if(!i||!r)return{applied:!1,rejected:"activity-missing"};let s=n.getAllLinks();for(let l of s)if(String(l.source)===String(e.source)&&String(l.target)===String(e.target)&&l.type===e.type)return{applied:!1,rejected:"duplicate",linkId:l.id};let a=s.map(l=>({source:l.source,target:l.target}));if(Xs(a,{source:e.source,target:e.target}))return{applied:!1,rejected:"cycle"};let o=(t.newLinkId??Nd)(),c={id:o,source:e.source,target:e.target,type:e.type,lag:e.lag};return n.addLink(c),_i(n,e.target),ki(n,e.source),{applied:!0,linkId:o}}function Od(e,t){let{port:n}=t,i=n.getLink(e.linkId);return i?(n.setLinkField?(e.lag!==void 0&&n.setLinkField(e.linkId,"lag",e.lag),e.type!==void 0&&n.setLinkField(e.linkId,"type",e.type)):(n.removeLink(e.linkId),n.addLink({...i,lag:e.lag??i.lag,type:e.type??i.type})),_i(n,i.target),ki(n,i.source),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:"link-missing"}}function wd(e,t){let{port:n}=t,i=n.getLink(e.linkId);if(!i)return{applied:!1,rejected:"link-missing"};let r=i.target,s=i.source;return n.removeLink(e.linkId),_i(n,r),ki(n,s),{applied:!0,linkId:e.linkId}}function _i(e,t){let n=e.getActivity(t);if(!n)return;let i=e.getWorkingHoursPerDayForActivity?e.getWorkingHoursPerDayForActivity(t):8,r=[];for(let s of n.$target){let a=e.getLink(s);if(!a)continue;let o=e.getActivity(a.source);if(!o)continue;let c=String(o.correlative_id??o.id??a.source);r.push(Zs(c,a.type,a.lag,i))}e.setActivityField(t,v.CUSTOM_PREDECESSORS,r.join(";"))}function ki(e,t){let n=e.getActivity(t);if(!n)return;let i=[];for(let r of n.$source){let s=e.getLink(r);if(!s)continue;let a=e.getActivity(s.target);if(!a)continue;let o=String(a.correlative_id??a.id??s.target),c=e.getWorkingHoursPerDayForActivity?e.getWorkingHoursPerDayForActivity(s.target):8;i.push(Zs(o,s.type,s.lag,c))}e.setActivityField(t,v.CUSTOM_SUCESSORS,i.join(";"))}function Zs(e,t,n,i){let r=ln[t],s=i>0?n/i:0,a=s>=0?"+":"-",o=Math.abs(s),c=Number.isInteger(o)?String(o):o.toFixed(2);return`${e}${r}${a}${c}d`}var dn=null;function Nd(){return dn===null&&(dn=Date.now()),dn+=1,String(dn)}function un(e){let t=[],n=[],i=e.replace(/\s+/g,"");if(i.length===0)return{specs:t,errors:n};for(let r of i.split(zs)){if(r.length===0)continue;let s=xd(r);s?t.push(s):n.push(r)}return{specs:t,errors:n}}function xd(e){let t=e.toLowerCase(),n=Js.exec(t);if(!n)return null;let[,i,r,s,a]=n,o=r?Ht[r]:Ht[Ks],c=0;if(a!==void 0){let l=Number(a);if(Number.isNaN(l))return null;c=s==="-"?-l:l}return{correlativeId:i,type:o,lag:c}}function pn(e){let{targetActivityId:t,currentLinks:n,desiredSpecs:i}=e,r=[],s=new Map;for(let c of i){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){r.push(c);continue}let d=fn(l,c.type);s.has(d)||s.set(d,{source:l,type:c.type,lag:c.lag})}let a=new Map;for(let c of n)String(c.target)===String(t)&&a.set(fn(c.source,c.type),c);let o=[];for(let[c,l]of a)s.has(c)||o.push({kind:"delete",linkId:l.id});for(let[c,l]of s){let d=a.get(c);d&&d.lag!==l.lag&&o.push({kind:"update",linkId:d.id,lag:l.lag})}for(let[c,l]of s)a.has(c)||o.push({kind:"create",source:l.source,target:t,type:l.type,lag:l.lag});return{operations:o,unresolved:r}}function fn(e,t){return`${String(e)}::${t}`}function hn(e){let{sourceActivityId:t,currentLinks:n,desiredSpecs:i}=e,r=[],s=new Map;for(let c of i){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){r.push(c);continue}let d=fn(l,c.type);s.has(d)||s.set(d,{target:l,type:c.type,lag:c.lag})}let a=new Map;for(let c of n)String(c.source)===String(t)&&a.set(fn(c.target,c.type),c);let o=[];for(let[c,l]of a)s.has(c)||o.push({kind:"delete",linkId:l.id});for(let[c,l]of s){let d=a.get(c);d&&d.lag!==l.lag&&o.push({kind:"update",linkId:d.id,lag:l.lag})}for(let[c,l]of s)a.has(c)||o.push({kind:"create",source:t,target:l.target,type:l.type,lag:l.lag});return{operations:o,unresolved:r}}function ft(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}function ke(e,t){return t<=0?0:e/t}var Qs={rawInputToConstraintDate(e,t){let n=new Date(e);return n.setUTCHours(0,0,0,0),n.getTime()===e.getTime()?t.getClosestWorkTime({direction:q.FUTURE,date:e,unit:at.HOUR}):t.isWorkTime(e,at.HOUR)?e:n},computeLagBetweenTasks(e,t,n){return n.calculateDuration(e,t)}};function Ii(e,t,n){switch(n){case"0":return{sourceDate:e.end_date,targetDate:t.start_date};case"1":return{sourceDate:e.start_date,targetDate:t.start_date};case"2":return{sourceDate:e.end_date,targetDate:t.end_date};case"3":return{sourceDate:e.start_date,targetDate:t.end_date}}}var Ti=Qs;var mn=class{adapter;reporter;currentCalculationId=0;topoCache=new sn;expandedLinksCache=new on;constructor(t,n=ne){this.adapter=t,this.reporter=n}getCurrentCalculationId(){return this.currentCalculationId}invalidateTopoCache(){this.topoCache.invalidate()}invalidateExpandedLinksCache(){this.expandedLinksCache.invalidate()}invalidateAllCaches(){this.topoCache.invalidate(),this.expandedLinksCache.invalidate()}async schedule(t={}){let n=++this.currentCalculationId,i=Ss(n,()=>this.currentCalculationId),r={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{Wd(this.adapter);let s=bt("schedule.total"),a=bt("schedule.expandParentLinks"),o=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(o,this.adapter);kt(a);let l=c;if((await ee(i)).aborted)return{...r,cancelled:!0};let d=bt("schedule.scoping"),u=this.adapter.getAllIds(),f=l,p=u,A=null;if(t.triggerId!==void 0&&t.triggerId!==null){let R=xs(t.triggerId,l);f=R.links,p=Array.from(R.activityIds),A=new Set(p)}kt(d);let I=bt("schedule.topologicalSort"),S=Ud(this.topoCache,u,l,A);if(kt(I),S.hasCycles)return kt(s),{...r,cycles:[S.cycleNodes]};if((await ee(i)).aborted)return{...r,cancelled:!0};let T=bt("schedule.processConstraints"),g=new Map;if(Us(S.ordered,this.adapter,g),kt(T),(await ee(i)).aborted)return{...r,cancelled:!0};let C=bt("schedule.asapPass"),y=await Vs(S.ordered,f,this.adapter,t,i,g);if(kt(C),(await ee(i)).aborted)return{...r,cancelled:!0};let m=bt("schedule.alapPass"),_=await Gs(S.reversed,f,y,this.adapter,t,i);if(kt(m),(await ee(i)).aborted)return{...r,cancelled:!0};let P=bt("schedule.diff"),D=[];for(let[R,U]of _){let W=this.adapter.getActivity(R);if(!W)continue;let H=W.start_date.getTime()!==U.start_date.getTime(),et=W.end_date.getTime()!==U.end_date.getTime();(H||et)&&D.push(R)}return kt(P),kt(s),{plans:_,updatedIds:D,cycles:[],cancelled:!1}}catch(s){return this.reporter.error("[AutoScheduler] Error during scheduling",s),r}}},Fd=!1;function Md(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:Fd}function bt(e){return{name:e,startedAt:performance.now()}}function Wd(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function kt(e){if(!Md())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function Ud(e,t,n,i){let r=e.get(t,n);if(r.hasCycles){let a=i?Array.from(i):t;return rn(a,n)}if(!i)return r;let s=Ps(r.ordered,i);return{ordered:s,reversed:[...s].reverse(),hasCycles:!1,cycleNodes:[]}}function ta(e,t){let n=t.getActivity(e);if(!n)return;let i=t.calendarReader.getCalendar(String(n.calendar_id));for(let r of n.$target){let s=t.getLink(r);if(!s)continue;let a=t.getActivity(s.source);if(!a||a.constraint_type==="alap")continue;let{sourceDate:o,targetDate:c}=Ii(a,n,s.type),l=Ti.computeLagBetweenTasks(o,c,i);l!==s.lag&&Lt({kind:"update",linkId:s.id,lag:l},{port:t})}}function ea(e,t){let n=t.getActivity(e);n&&(n.progress!=(n.old_progress_registered??0)||n.duration!=(n.old_duration_registered??0)||n.hhWorkTime!=(n.old_hhWorkTime_registered??0)||n.cost!=(n.old_cost_registered??0)||n.used_cost!=(n.old_used_cost_registered??0)||n.real_cost!=(n.old_real_cost_registered??0))&&(n.old_duration_registered=n.duration??0,n.old_progress_registered=n.progress??0,n.old_hhWorkTime_registered=n.hhWorkTime??0,n.old_cost_registered=n.cost??0,n.old_used_cost_registered=n.used_cost??0,n.old_real_cost_registered=n.real_cost??0)}function na(e,t){let n=t.getActivity(e);n&&(n.is_milestone||n.type==="milestone")&&(n.duration=0,n.for_disable_milestone_duration=0)}function ie(e){let t=0,n=!1;for(let i of e)i.ponderator>0&&(t+=i.ponderator/100*i.progress,n=!0);return n?t:null}function yn(e){return Number(e.toFixed(2))}async function Ie(e,t,n=!0,i={}){let r=t?ia(e,t):Yd(e);await Bd(r,e,n,{skipMilestoneDurationStamp:i.skipMilestoneDurationStamp??!1,recomputeRealWork:i.recomputeRealWork??!1})}function Di(e,t,n=!0){let i=ia(e,t);for(let r of i)Pi(r,e,n)}function gn(e,t){Pi(e,t,!1,!0)}function Ei(e){e.forEachActivity(t=>{t.for_disable_milestone_duration!==t.duration&&e.setActivityField(String(t.id),"for_disable_milestone_duration",t.duration)})}async function Bd(e,t,n=!0,i={skipMilestoneDurationStamp:!1,recomputeRealWork:!1}){let s=0;for(let a of e)Pi(a,t,n,i.skipMilestoneDurationStamp,i.recomputeRealWork),s+=1,s%200===0&&await nt()}function ia(e,t){let n=new Set;for(let s of t)jd(s,e,n);if(n.size===0)return[];let i=Array.from(n),r=ra(i,e);return sa(i,r)}function jd(e,t,n){let i=t.getParentId(e);for(;i&&!b(i);){if(n.has(i))return;n.add(i),i=t.getParentId(i)}}function Hd(e,t,n){let i=null,r=null,s=0,a=[];for(let o of e){let c=t.getActivity(o);if(!c)continue;let l=c.start_date.getTime(),d=c.end_date.getTime();(i===null||l<i)&&(i=l),(r===null||d>r)&&(r=d),n&&(s+=$d(c)),a.push({progress:Number(c.progress??0),ponderator:Number(c.ponderator??0)})}return{minStart:i,maxEnd:r,realWorkSum:s,weightedChildren:a}}function Pi(e,t,n=!0,i=!1,r=!1){let s=t.getActivity(e);if(!s)return;let a=t.getChildren(e);if(a.length===0)return;let o=Hd(a,t,r);if(o.minStart===null||o.maxEnd===null)return;let c=String(s.calendar_id??""),l=t.calendarReader.getCalendar(c),d=new Date(o.minStart),u=new Date(o.maxEnd),f=l.calculateDuration(d,u);t.setActivityField(e,v.START_DATE,d),t.setActivityField(e,v.END_DATE,u),t.setActivityField(e,v.DURATION,f),i||t.setActivityField(e,"for_disable_milestone_duration",f);let p=ie(o.weightedChildren);n&&p!==null&&t.setActivityField(e,v.PROGRESS,yn(p)),r&&t.setActivityField(e,v.REAL_WORK,o.realWorkSum)}function $d(e){let t=Number(e.real_work);if(Number.isFinite(t)&&t!==0)return t;let i=Number(e.hhWorkTime)||0,r=Number(e.progress)||0;return i*r/100}function Yd(e){let t=Vd(e),n=ra(t,e);return sa(t,n)}function Vd(e){let t=new Set;return e.forEachActivity(n=>{n.parent&&!b(n.parent)&&t.add(n.parent)}),Array.from(t)}function ra(e,t){let n=new Map;for(let i of e)n.set(i,Gd(i,t));return n}function Gd(e,t){let n=0,i=e;for(;i&&!b(i)&&t.getActivity(i);)n+=1,i=t.getParentId(i);return n}function sa(e,t){return[...e].sort((n,i)=>(t.get(i)??0)-(t.get(n)??0))}var aa={updateParentDuration:ea,updateActivityDuration:na,updateTaskTiming:Kd("updateTaskTiming"),adjustLinkLagOnTaskMove:ta};function Ot(e,t,n){for(let i of t){let r=i in aa?aa[i]:void 0;if(!r){console.warn(`[replay post-processors] unknown: ${i} \u2014 skipping. Add an entry in POST_PROCESSORS if a fixture needs it.`);continue}r(e,n)}}function Kd(e){return()=>{console.debug(`[replay post-processors] ${e}: not yet ported to adapter \u2014 no-op.`)}}function L(e,t){return t!==void 0?{ok:!0,value:e,raw:t}:{ok:!0,value:e}}function w(e){return{ok:!1,reason:e}}function x(){return{valid:!0}}function it(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function F(){return{allowed:!0}}function Y(e,t){return t!==void 0?{allowed:!1,reason:e,alertKey:t}:{allowed:!1,reason:e}}function N(e,t={},n={}){return{primaryValue:e,extraFields:t,needsAutoSchedule:n.autoSchedule??!1,postProcessors:n.postProcessors??[],...n.cascadeMutations!==void 0?{cascadeMutations:n.cascadeMutations}:{},...n.trackingEvents!==void 0?{trackingEvents:n.trackingEvents}:{}}}var oa={canEdit(){return F()},parseInput(e){return typeof e!="string"?w("not_a_string"):L(e)},validate(){return x()},transform(e,t){return N(t,{},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var ca={canEdit(){return F()},parseInput(e){return typeof e!="string"?w("not_a_string"):L(e.trim())},validate(){return x()},transform(e,t){return N(t,{},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_description_entry"};var vn=100;function re(e){return e.progress>=vn}function J(e){return St(e.type,e.hasChildren)}function la(e){return e.progress>0}function da(e){return e.hasLookaheadTasks}function se(e,t){return Math.round(Math.ceil(e*t*60)/60)}function Ri(e,t){return t<=0?0:e/t}var ae=e=>({[te]:e});function It(e,t){if(t){let n=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=r=>Number(n.find(s=>s.type===r)?.value);return new Date(Date.UTC(i("year"),i("month")-1,i("day")))}return new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()))}function Te(e,t){if(!t||t==="UTC"){let f=new Date(e);return f.setUTCHours(23,59,0,0),f}let n=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=f=>Number(n.find(p=>p.type===f)?.value),r=i("year"),s=i("month"),a=i("day"),o=Date.UTC(r,s-1,a,23,59,0,0),c=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(new Date(o)),l=f=>Number(c.find(p=>p.type===f)?.value),u=Date.UTC(l("year"),l("month")-1,l("day"),l("hour")===24?0:l("hour"),l("minute"),l("second"))-o;return new Date(o-u)}function qd(e,t){let n=It(t);for(;!e.isWorkTime(n,at.DAY);)n=new Date(n),n.setUTCDate(n.getUTCDate()+1),n=It(n);return n}function De(e,t){return e.getClosestWorkTime({direction:q.FUTURE,date:t,unit:at.HOUR})}function Ee(e,t){let n=qd(e,t),i=new Date(n);return i.setUTCDate(i.getUTCDate()+1),i.setUTCHours(0,0,0,0),e.getClosestWorkTime({direction:q.PAST,date:i,unit:at.HOUR})}var An=new Set(["snet","snlt","mso"]),Li=new Set(["fnet","fnlt","mfo"]),Tt=new Set(["asap","alap"]),oe="snet";function $t(e,t,n){if(!An.has(n)&&!Li.has(n))return e;let i=An.has(n)?De(t,e):Ee(t,e),r=new Date(e);return r.setUTCHours(i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds()),r}var Dt=()=>({[Ye]:oe,[Wt]:oe,[mi]:oe}),ua=e=>({[Wt]:e,[mi]:e});var Yt=e=>({[Ut]:e,[yi]:e}),fa=e=>({[Ut]:e}),Cn=e=>({[yi]:e});function ce(e,t,n){return ks(e,t,n)}function le(e,t,n){return Is(e,t,n)}var pa={canEdit(e){return re(e)?Y("completed","cant_edit_completed_activity"):J(e)?Y("summary","summary_column_value"):F()},parseInput(e,t,n){let i=parseFloat(String(e));return Number.isNaN(i)?w("not_a_number"):L(n.inputUnit==="hours"?i:se(i,n.hoursPerDay))},validate(e,t,n){return zd(n)?it("negative_duration"):Jd(t,n)?it("unchanged"):x()},transform(e,t,n){let i=Xd(e,t,n),r=Zd(e,t,n,i.violated);return{...N(t,r,{autoSchedule:!0,postProcessors:["updateParentDuration"]}),...i.violated?{constraintWarning:le(i.constraintType,i.constraintDate,ha(e,t,n)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function zd(e){return Math.sign(e)===-1}function Jd(e,t){return e===t}function Xd(e,t,n){let i=n.calendars.getCalendar(e.calendar_id);if(!i)return{violated:!1};let r=e.constraint_type;if(r!=="fnet"&&r!=="fnlt"&&r!=="mfo")return{violated:!1};let s=i.calculateEndDate(e.start_date,t);return ce(r,e.constraint_date,s)}function Zd(e,t,n,i=!1){let r={};i&&Object.assign(r,Dt(),Yt(e.start_date));let s=Se(e.duration,t);r.is_milestone=s==="milestone",s&&(r.type=s),r.duration=t,r.for_disable_milestone_duration=t,r[Ve]=e.constraint_type;let a=e.constraint_date??e.last_constraint_date;a!==null&&Object.assign(r,Cn(a)),r[Zr]=e.start_date,r[Kr]=!0;let o=ha(e,t,n);return o&&Object.assign(r,ae(o)),r}function ha(e,t,n){let i=n.calendars.getCalendar(e.calendar_id);return i?i.calculateEndDate(e.start_date,t):null}var Qd=0,tu=vn,ma=0,ya={canEdit(e){return da(e)?Y("has_lookahead_tasks","cant_edit_actvity_with_task"):J(e)?Y("summary","summary_column_value"):F()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?w("not_a_number"):L(t)},validate(e,t,n){return eu(n)?it("out_of_range"):x()},transform(e,t,n){let i=nu(t),r=iu(t),s={auto_scheduling:i};r&&(s[hi]=!0);let a=r?ru(e,t,i,n.hierarchy):[],o=r?au(e,t,n.hierarchy):[],c=a.length+o.length>0?[...a,...o]:void 0,l=["updateParentDuration"],d=r?cu(e,t):void 0;return N(t,s,{autoSchedule:!1,postProcessors:l,cascadeMutations:c,trackingEvents:d})},trackEvent:"activity_progress_entry"};function eu(e){return e<Qd||e>tu}function nu(e){return e===ma}function iu(e){return e===vn||e===ma}function ru(e,t,n,i){return i.getDescendantIds(e.id).map(s=>({activityId:s,fields:su(t,n)}))}function su(e,t){return{progress:e,auto_scheduling:t,[hi]:!0}}function au(e,t,n){let i=new Map;i.set(e.id,t);for(let a of n.getDescendantIds(e.id))i.set(a,t);let r=[];for(let a of n.getAncestorIds(e.id))r.push(a);let s=[];for(let a of r){let o=ou(a,i,n);i.set(a,Number(o)),s.push({activityId:a,fields:{progress:o}})}return s}function ou(e,t,n){let i=n.getChildProgressInfo(e).map(r=>({progress:t.has(r.id)?t.get(r.id):r.progress,ponderator:r.ponderator??0}));return(ie(i)??0).toFixed(2)}function cu(e,t){return[{name:"activity_progress_update_radio_button",properties:{activity_id:e.id,activity_name:e.text,progress_updated:t}}]}var ga={canEdit(e){return J(e)?Y("summary","summary_column_value"):F()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?w("not_a_number"):L(t)},validate(){return x()},transform(e,t,n){let i=lu(e,t,n.hierarchy);return N(t,{},{autoSchedule:!1,postProcessors:["updateParentDuration"],cascadeMutations:i})},trackEvent:"activity_cost_budgeted_entry"};function lu(e,t,n){let i=new Map;i.set(e.id,t);let r=[];for(let s of n.getAncestorIds(e.id)){let a=0;for(let o of n.getChildCostInfo(s))a+=i.has(o.id)?i.get(o.id):o.cost;i.set(s,a),r.push({activityId:s,fields:{cost:a}})}return r}var va={canEdit(e){return J(e)?Y("summary","summary_column_value"):F()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?w("not_a_number"):L(t)},validate(){return x()},transform(e,t,n){let i=du(e,t,n.hierarchy);return N(t,{},{autoSchedule:!1,postProcessors:["updateParentDuration"],cascadeMutations:i})},trackEvent:"activity_cost_spent_entry"};function du(e,t,n){let i=new Map;i.set(e.id,t);let r=[];for(let s of n.getAncestorIds(e.id)){let a=0;for(let o of n.getChildUsedCostInfo(s))a+=i.has(o.id)?i.get(o.id):o.used_cost;i.set(s,a),r.push({activityId:s,fields:{used_cost:a}})}return r}var bi=e=>({[Ge]:e});var Aa={canEdit(e){return J(e)?Y("summary","summary_column_value"):F()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?w("not_a_number"):L(t)},validate(){return x()},transform(e,t,n){let i=Ca(t,e.progress),r=uu(e,t,i,n.hierarchy);return N(t,{...bi(i)},{autoSchedule:!1,postProcessors:["updateParentDuration"],cascadeMutations:r})},trackEvent:"activity_labor_hours_budgeted_entry"};function Ca(e,t){return e*t/100}function uu(e,t,n,i){let r=new Map,s=new Map;r.set(e.id,t),s.set(e.id,n);let a=[];for(let o of i.getAncestorIds(e.id)){let c=0,l=0;for(let d of i.getChildHhInfo(o)){let u=r.has(d.id)?r.get(d.id):d.hhWorkTime,f=s.has(d.id)?s.get(d.id):Ca(d.hhWorkTime,d.progress);c+=u,l+=f}r.set(o,c),s.set(o,l),a.push({activityId:o,fields:{hhWorkTime:c,...bi(l)}})}return a}function Sn(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function Oi(e,t){return e.getTime()<t.getTime()}function de(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var _n=e=>({[Qt]:e}),kn=e=>({[Gr]:e});var Sa={canEdit(e){return J(e)?Y("summary","summary_column_value"):la(e)?Y("has_progress","cant_edit_activity_with_progress"):F()},parseInput(e,t,n){return de(e)?L(It(e,"UTC")):w("invalid_date")},validate(e,t,n,i){if(Sn(t,n))return it("unchanged");let r=fu(e,n,i);return r||x()},transform(e,t,n){let i=n.calendars.getCalendar(e.calendar_id);if(!i)return N(t,{...Dt(),...Yt(t)},{autoSchedule:!0,postProcessors:["updateParentDuration","adjustLinkLagOnTaskMove"]});let r=De(i,t),s=e.type==="milestone",a=s?r:i.calculateEndDate(r,e.duration),o=r;return{...N(r,{...ae(a),...s?{..._n(0),...kn(0)}:{},...Dt(),...Yt(o)},{autoSchedule:!0,postProcessors:["updateParentDuration","adjustLinkLagOnTaskMove"]}),constraintWarning:pu(e,r,i)}},trackEvent:"activity_start_date_entry"};function fu(e,t,n){let i=n.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!i)return null;let r=It(i);return t.getTime()<r.getTime()?it("before_parent_start"):null}function pu(e,t,n){let i=n.calculateEndDate(t,e.duration),r=Ae(e.constraint_type,t,i),s=ce(e.constraint_type,e.constraint_date,r);if(s.violated)return le(s.constraintType,s.constraintDate,r)}var hu=99.999,_a={canEdit(e){return J(e)?Y("summary","summary_column_value"):mu(e)?Y("completed","cant_edit_completed_activity"):F()},parseInput(e,t,n){if(!de(e))return w("invalid_date");let i=It(e,"UTC"),r=n.calendars.getCalendar(t.calendar_id);return r?r.isWorkTime(i,at.DAY)?L(Ee(r,i)):L(i):L(i)},validate(e,t,n,i){if(Sn(e.end_date,n))return it("unchanged");if(yu(n,e))return it("before_date_origin");if(gu(n,e))return it("before_start_date");let r=vu(n,e,i);return r||x()},transform(e,t,n){let i=Au(e,t),r=Cu(e,t,n,!!i);return{...N(t,r,{autoSchedule:!0,postProcessors:["updateParentDuration","updateTaskTiming"]}),...i?{constraintWarning:i}:{}}},trackEvent:"activity_end_date_entry"};function mu(e){return e.progress>=hu}function yu(e,t){return t.date_origin?Oi(e,t.date_origin):!1}function gu(e,t){return Oi(e,t.start_date)}function vu(e,t,n){let i=n.calendars.getCalendar(t.calendar_id);return i?i.isWorkTime(e,at.DAY)?null:it("not_working_day"):null}function Au(e,t){let n=Ae(e.constraint_type,e.start_date,t),i=ce(e.constraint_type,e.constraint_date,n);if(i.violated)return le(i.constraintType,i.constraintDate,n)}function Cu(e,t,n,i=!1){let r={};(i||Su(e))&&Object.assign(r,Dt(),Yt(e.start_date));let s=_u(e,t,n),a=Se(e.duration,s);return a&&(r.type=a,r.is_milestone=a==="milestone"),Object.assign(r,_n(s),kn(s)),r.end_date=t,r}function Su(e){return Tt.has(e.constraint_type)}function _u(e,t,n){let i=n.calendars.getCalendar(e.calendar_id);return i?i.calculateDuration(e.start_date,t):e.duration}var ku=new Set(Object.values($)),ka={canEdit(e){return re(e)?Y("completed","cant_edit_completed_activity"):J(e)?Y("summary","summary_column_value"):F()},parseInput(e){let t=String(e).toLowerCase();return Iu(t)?L(t):w("invalid_constraint_type")},validate(){return x()},transform(e,t){let n=Tu(e,t);return N(t,n,{autoSchedule:!0})}};function Iu(e){return ku.has(e)}function Tu(e,t){let n={constraint_type:t,[Wt]:t,[Ve]:t,...fa(Du(e,t))};return Tt.has(t)&&e.constraint_date&&Object.assign(n,Cn(e.constraint_date)),n}function Du(e,t){return Tt.has(t)?null:An.has(t)?e.start_date:Li.has(t)?e.end_date:e.constraint_date}var Ia={canEdit(e){return re(e)?Y("completed","cant_edit_completed_activity"):J(e)?Y("summary","summary_column_value"):F()},parseInput(e){return de(e)?L(e):w("invalid_date")},validate(){return x()},transform(e,t,n){let i=Ta(e)?oe:e.constraint_type,r=n.calendars.getCalendar(e.calendar_id),s=r?$t(t,r,i):t,a=Eu(e,s);return N(s,a,{autoSchedule:!0})}};function Eu(e,t){let n=Ta(e)?Dt():ua(e.constraint_type);return{constraint_date:t,last_constraint_date:e.constraint_date,...n}}function Ta(e){return Tt.has(e.constraint_type)||!e.constraint_type}var Da={canEdit(){return F()},parseInput(e){let t=String(e).trim();return Pu(t)?w("empty_calendar"):L(t)},validate(e,t,n){return Ru(e.calendar_id,n)?it("unchanged"):x()},transform(e,t,n){let i=Lu(e,t,n);return N(t,i,{autoSchedule:!0,postProcessors:["updateParentDuration"]})},trackEvent:"activity_calendar_assignment"};function Pu(e){return e===""}function Ru(e,t){return e===t}function Lu(e,t,n){let i={calendar_id:t,assignedDefaultCalendar:!1},r=n.calendars.getCalendar(t);return r&&Object.assign(i,ae(r.calculateEndDate(e.start_date,e.duration))),i}var Ea={canEdit(){return F()},parseInput(e){if(e==null)return L(null);if(typeof e!="string")return w("not_a_string");let t=e.trim();return t.length===0?L(null):t.length>20?w("exceeds_max_length"):L(t)},validate(){return x()},transform(e,t){return N(t,{},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var Pa={canEdit(){return F()},parseInput(e){if(e==null)return L(null);if(typeof e=="string"){let t=e.trim();if(t.length===0)return L(null);let n=Number(t);return!Number.isFinite(n)||!Number.isInteger(n)?w("not_an_integer"):L(n)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?w("not_an_integer"):L(e):w("not_an_integer")},validate(){return x()},transform(e,t){return N(t,{},{autoSchedule:!1,postProcessors:[]})}};var Ra={canEdit(){return F()},parseInput(e){return e==null?L([]):Array.isArray(e)?L(e):w("not_an_array")},validate(){return x()},transform(e,t){return N(t,{},{autoSchedule:!1,postProcessors:[]})}};var La={canEdit(){return F()},parseInput(e){return e==null?L([]):Array.isArray(e)?L(e):w("not_an_array")},validate(){return x()},transform(e,t){return N(t,{},{autoSchedule:!1,postProcessors:[]})}};var bu=new Map([[v.TEXT,oa],[v.DESCRIPTION,ca],[v.DURATION,pa],[v.PROGRESS,ya],[v.COST,ga],[v.USED_COST,va],[v.HH_WORK_TIME,Aa],[v.START_DATE,Sa],[v.END_DATE,_a],[v.CONSTRAINT_TYPE,ka],[v.CONSTRAINT_DATE,Ia],[v.CALENDAR_ID,Da],[v.CUSTOM_ID,Ea],[v.SUBCONTRACT_ID,Pa],[v.RESPONSABLES,Ra],[v.TAGS,La]]);function wt(e){return bu.get(e)}function ue(e,t){if(!t||t.type!=="constraint")return null;let n=t.data;return!n?.constraintType||!n.constraintDate?null:{kind:"constraint_violation",activityId:e,constraintType:n.constraintType,constraintDate:n.constraintDate,projectedDate:n.projectedDate??n.constraintDate,messageKey:t.messageKey}}var tt={ID:"id",PARENT:"parent",TYPE:"type",AUTO_SCHEDULING:"auto_scheduling",ASSIGNED_DEFAULT_CALENDAR:"assignedDefaultCalendar",IS_LOOKAHEAD:"is_lookahead",VISIBLE:"visible",NEW_ACTIVITIES_ARRAY:"newActivitiesArray",ACTIVITY_MODIFICATIONS:"activityModifications",PROPLANNER_ID:"proplannerId",GANTT_ID:"ganttId",SECTOR_ID:"sectorId",COMPANY_ID:"companyId",SUBCONTRACT:"subcontract",HAS_CUSTOM_PONDERATOR:"hasCustomPonderator",HAS_CHILDS:"has_childs",SUM_OF_DURATION_RECURSIVELY:"sumOfDurationRecursively",HAS_NEW_ACTIVITIES:"hasNewActivities",IS_NEW_ACTIVITY:"isNewActivity"};function V(e,t,n,i){e.setActivityField(t,n,i)}function ba(e,t,n,i){e.setLinkField(t,n,i)}function Oa(e,t){let n=e.parent==="0"?0:e.parent;return{...e,id:e.id,parent:n,type:e.type,constraint_type:e.constraint_type,constraint_date:e.constraint_date,start_date:e.start_date,end_date:e.end_date,duration:se(e.duration,t),progress:e.progress,auto_scheduling:e.auto_scheduling,calendar_id:e.calendar_id,$source:[],$target:[]}}function X(e){let t=_t(e.parent);return{...e,id:e.id,parent:t,text:String(e.text??""),description:String(e.description??""),type:e.type,start_date:e.start_date,end_date:e.end_date,duration:e.duration,constraint_type:e.constraint_type??null,constraint_date:e.constraint_date,progress:e.progress,cost:Number(e.cost??0),used_cost:Number(e.used_cost??0),hhWorkTime:Number(e.hhWorkTime??0),real_work:Number(e.real_work??0),ponderator:Number(e.ponderator??0),calendar_id:e.calendar_id!=null?String(e.calendar_id):null,auto_scheduling:e.auto_scheduling}}function gt(e){let t={id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)};return e.proplannerId!=null&&(t.proplannerId=Number(e.proplannerId)),e.ganttId!=null&&(t.ganttId=Number(e.ganttId)),e.sectorId!=null&&(t.sectorId=Number(e.sectorId)),t}function Nt(e,t){let n=new Set([String(e)]);for(let i of t.cascadeMutations??[])n.add(String(i.activityId));return n}function K(e,t){let n=new Map;for(let i of t){let r=e.getActivity(i);r&&n.set(i,Z(r))}return n}function Z(e){return{...e,start_date:new Date(e.start_date),end_date:new Date(e.end_date),constraint_date:e.constraint_date?new Date(e.constraint_date):null,$source:[...e.$source],$target:[...e.$target]}}function xt(e,t,n,i){V(e,t,n,i.primaryValue);for(let[r,s]of Object.entries(i.extraFields??{}))V(e,t,r,s);for(let r of i.cascadeMutations??[]){let s=r;for(let[a,o]of Object.entries(s.fields))V(e,s.activityId,a,o)}}function wa(e,t,n){let i=[];for(let r of n){let s=e.getActivity(r);if(!s){i.push({id:r,kind:"deleted",after:null});continue}let a=t.get(r),o=wi(a,s);a?i.push({id:r,kind:"updated",fields:o,after:X(s)}):i.push({id:r,kind:"created",fields:o,after:X(s)})}return i}function wi(e,t){let n={},i=e??{},r=t,s=new Set([...Object.keys(i),...Object.keys(r)]);for(let a of s)xa(i[a],r[a])||(n[a]={before:i[a],after:r[a]});return n}function In(e,t,n){let i=new Set;i.add(e);for(let r of t)i.add(r);for(let r of n)i.add(r);return i}function Na(e,t){let n=new Set;for(let i of e)n.add(String(i));for(let i of t)n.add(i);return n}function Tn(e,t,n,i,r){for(let s of t){if(n.has(s.activityId)||(r.add(s.activityId),i.has(s.activityId)))continue;let a=e.getActivity(s.activityId);if(!a)continue;let o=Z(a);o.correlative_id=s.before,i.set(s.activityId,o)}}function xa(e,t){if(e===t)return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e==null||t==null||typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!xa(e[n],t[n]))return!1;return!0}return!1}var Ou=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function At(e){if(e==null||e==="")throw new Error(`[parseFromBackend] expected a date string, got "${e}"`);if(e.includes("T")||e.endsWith("Z")){let o=new Date(e);if(Number.isNaN(o.getTime()))throw new Error(`[parseFromBackend] invalid ISO date "${e}"`);return o}let t=e.match(Ou);if(!t)throw new Error(`[parseFromBackend] unsupported date format "${e}" (expected "YYYY/MM/DD H:MM" or ISO)`);let[,n,i,r,s,a]=t;return new Date(Date.UTC(Number(n),Number(i)-1,Number(r),Number(s),Number(a)))}function fe(e,t,n,i){if(e.getTime()>n.getTime())return 0;if(t.getTime()<n.getTime()||e.getTime()===t.getTime())return 100;let r=i.calculateDuration(e,n),s=i.calculateDuration(e,t);return s===0?0:r*100/s}var wu=e=>e.type==="project",Nu=(e,t,n)=>{let i=e.calendar_id,r=i!=null?n.calendarReader.getCalendar(String(i)):null;if(!r)return 0;let s=a=>a instanceof Date?a:At(String(a));return fe(s(e.start_date),s(e.end_date),t,r)};function Fa(e,t,n){let i=[],r=(a,o)=>{let c=n.getActivity(a);c&&c.expected_progress!==o&&(n.setActivityField(a,v.EXPECTED_PROGRESS,o),i.push(String(a)))},s=a=>{let o=n.getActivity(a);if(!o)return 0;if(!wu(o)){let d=Nu(o,t,n);return r(a,d),d}let c=0;for(let d of n.getChildren(a)){let u=s(d),f=n.getActivity(d),p=typeof f?.ponderator=="number"?f.ponderator:0;c+=u*p}let l=c/100;return r(a,l),l};for(let a of e)s(a);return i}var Ma=e=>Math.round(e*100)/100;function xu(e,t){return t==="Baseline"?e.expected_progress_base:e.expected_progress}function Fu(e,t){let n=Ma(e),i=Ma(t);return n>99.99?Bt.DONE:i>n?Bt.OVERDUE:e>0&&n>i?Bt.ADVANCEMENT:e===0&&t===0?Bt.WAITING:e>0&&n<i?Bt.DOING:Bt.WAITING}function Gt(e,t){let n=[];return e.forEachActivity((i,r)=>{let s=i,a=typeof s.progress=="number"?s.progress:0,o=Fu(a,xu(s,t));s.status!==o&&(V(e,r,Ze,o),n.push(r))}),n}var Ni=Number.MAX_SAFE_INTEGER;function Kt(e,t){let n=Fi(e,t);return n.sort(Mu),n.map(i=>String(i.id))}function Ua(e){let t=[],n=r=>{t.push(r);let s=Kt(String(r.id),e);for(let a of s){let o=e.getActivity(a);o&&n(o)}},i=Kt("0",e);for(let r of i){let s=e.getActivity(r);s&&n(s)}return t}function Ba(e,t,n){let i=n.getActivity(e);if(!i)return null;let r=ja(i),s=Kt(r,n),a=s.findIndex(o=>String(o)===String(e));if(a<=0)return null;for(let o=a-1;o>=0;o--){let c=s[o];if(c!==void 0&&!Wu(t,c))return c}return null}function xi(e,t){let n=t.getActivity(e);if(!n)return-1;let i=ja(n);return Kt(i,t).findIndex(s=>String(s)===String(e))}function Fi(e,t){if(String(e)==="0")return t.getAllActivities().filter(s=>b(s.parent));let i=t.getChildren(e),r=[];for(let s of i){let a=t.getActivity(s);a&&r.push(a)}return r}function Mu(e,t){let n=Wa(e),i=Wa(t);return n!==i?n-i:String(e.id).localeCompare(String(t.id))}function Wa(e){let t=e.correlative_id,n=typeof t=="number"?t:Number(t);return Number.isFinite(n)?n:Ni}function ja(e){let t=e.parent;return t==null||t===0||t==="0"?"0":String(t)}function Wu(e,t){return e.has(t)?!0:e.has(String(t))}function ot(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(s=>{b(s.parent)&&t.push(s)}),t.sort(Ya);let n=[];Ha(n,t);let i=[],r=0;for(;n.length>0;){let s=n.pop();if(s.correlative_id!==r){let o=typeof s.correlative_id=="number"?s.correlative_id:void 0;i.push({activityId:String(s.id),before:o}),o!==void 0&&e.noteCorrelativeBefore?.(String(s.id),o),Uu(s,r)}r+=1;let a=Fi(String(s.id),e);a.sort(Ya),Ha(n,a)}return i}function Ha(e,t){for(let n=t.length-1;n>=0;n-=1)e.push(t[n])}function $a(e){let t=e.correlative_id,n=typeof t=="number"?t:Number(t);return Number.isFinite(n)?n:Ni}var Ya=(e,t)=>$a(e)-$a(t);function Uu(e,t){e.correlative_id=t}async function Va(e){let{state:t,sector:n,scheduler:i,skipAutoSchedule:r,now:s}=e;if(ot(t),n.updateDurationForPrimaveraEndDate&&ju(t),Hu(t),r){s&&(Dn(t,s),Gt(t,n.statusCriteria));return}let a=await i.schedule({});_e(t,a),$u(t),Bu(t),await Ie(t,void 0,!1),s&&(Dn(t,s),Gt(t,n.statusCriteria))}function Dn(e,t){let n=[];e.forEachActivity((i,r)=>{(i.parent===0||i.parent==="0"||i.parent==null)&&n.push(r)}),Fa(n,t,e)}function Bu(e){e.forEachActivity(t=>{t.auto_scheduling||!t.start_date||t.duration==null||e.getChildren(t.id).length>0||(t.end_date=e.calculateEndDate({start_date:t.start_date,duration:t.duration,task:t}))})}function ju(e){e.forEachActivity(t=>{!t.start_date||!t.end_date||(t.duration=e.calculateDuration({start_date:t.start_date,end_date:t.end_date,task:t}))})}function Hu(e){e.forEachActivity(t=>{let n=t.constraint_type;if(!n||!t.constraint_date)return;let i=t.constraint_date;if(t.type==="milestone"&&(i.getUTCHours()!==0||i.getUTCMinutes()!==0))return;let r=e.calendarReader.getCalendar(String(t.calendar_id));r&&(t.constraint_date=$t(t.constraint_date,r,n))})}function $u(e){e.forEachActivity(t=>{if(t.type!=="milestone")return;let n=t.constraint_type;if(!n||!t.constraint_date)return;let i=e.calendarReader.getCalendar(String(t.calendar_id));i&&(t.constraint_date=$t(t.constraint_date,i,n))})}function Mi(e){let t=e instanceof Date?new Date(e.getTime()):e&&typeof e=="object"&&typeof e.valueOf=="function"?new Date(e.valueOf()):new Date(e),n=(r,s)=>a=>a===void 0?t[r]():(t[s](a),i),i={__isMomentShim:!0,clone:()=>Mi(t),hours:n("getUTCHours","setUTCHours"),minutes:n("getUTCMinutes","setUTCMinutes"),seconds:n("getUTCSeconds","setUTCSeconds"),milliseconds:n("getUTCMilliseconds","setUTCMilliseconds"),valueOf:()=>t.getTime(),toDate:()=>new Date(t.getTime()),getTime:()=>t.getTime()};return i}Mi.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var pt=Mi;function Yu(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function En(e){return Yu(e)&&!isNaN(e.getTime())}function k(e,t,n,i){if(!En(new Date(t)))throw new Error(`Invalid date argument for calculateEndDate method. Date: ${t}, Activity: ${JSON.stringify(i)}`);let r=t;return e.calculateEndDate({start_date:new Date(r),duration:n,unit:"hour",task:i})}function lt(e){if(!En(new Date(e.dateBaseToCalculate)))throw new Error("Invalid date argument for getClosestWorkTime method");let{dateBaseToCalculate:t,activityCalendar:n,direction:i,activity:r}=e;return n.$gantt.getClosestWorkTime({date:new Date(t),dir:i,unit:"hour",task:r})}var Vu=e=>e?e.$level===1:!1,Gu=e=>e.type==="project",Ku=e=>e.$level!==0,qu=e=>e.type==="task",zu=e=>e.type==="task"||e.type==="milestone",rt={byFirstLevel:Vu,filterByParentType:Gu,avoidSubproject:Ku,byTaskType:qu,byTaskTypeAndMilestone:zu};var h=Object.freeze({MFO:"mfo",MSO:"mso",FNLT:"fnlt",FNET:"fnet",SNET:"snet",SNLT:"snlt",ALAP:"alap",ASAP:"asap"});var M=Object.freeze({FS:"fs",SS:"ss",FF:"ff",SF:"sf"});function qt(e){return{0:"fs",1:"ss",2:"ff",3:"sf"}[Number(e)]||"sf"}function Ga(e){let{gantt:t,pendingParentsWithNoLinks:n,calculations:i,linkProperty:r}=e;try{let s=Ju({gantt:t,pendingParentsWithNoLinks:n});if(s.length===0)return new Set;let a=Xu({gantt:t,subprojectsWithNoLinks:s}),o=Zu({gantt:t,childrenIds:a,linkProperty:r,getArrayOfLinkedActivities:Qu,calculations:i});return new Set(o.map(c=>c.id))}catch(s){throw s}}function Ju(e){let{gantt:t,pendingParentsWithNoLinks:n}=e;return t.getTaskByTime().filter(rt.filterByParentType).filter(i=>n.has(i.id)).map(i=>i.id)}function Xu(e){let{gantt:t,subprojectsWithNoLinks:n}=e,i=new Set;for(let r of n)t.getChildren(r).filter(o=>{let c=t.getTask(o),l=rt.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(o=>i.add(o));return[...i]}function Zu(e){let{gantt:t,childrenIds:n,linkProperty:i,getArrayOfLinkedActivities:r,calculations:s}=e,a=[];for(let o of n){let c=t.getTask(o),l=c[i]||[];r({gantt:t,links:l,linkDirection:i==="$source"?"target":"source"}).every(f=>s.has(f))&&a.push(c)}return a}function Qu(e){let{gantt:t,links:n,linkDirection:i}=e,r=[];for(let s of n){let a=t.getLink(s);if(!a){`${s}`;continue}let o=Number(a[i]);r.push(o)}return r}function Ka({gantt:e,linkProperty:t,direction:n}){try{let i=tf(e,t);if(n==="forward")return{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:null};if(n==="backward")return ef(i,e,t)}catch(i){throw console.log("Critical Path",i),i}}function tf(e,t){return e.getTaskByTime().filter(rt.avoidSubproject).filter(rt.byTaskTypeAndMilestone).filter(n=>!n[t].length)}function ef(e,t,n){let i=[],r=new Set;return e.forEach(s=>{let a=Number(s.parent),o=t.getTask(a);o&&(o[n].length>0?r.add(s.id):o.constraint_type!=="fnlt"&&i.push(s))}),{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:r}}function qa({gantt:e,direction:t,linkProperty:n}){try{let i=nf(e),r=new Set,s=new Set,a=new Set;t==="backward"&&af(i).forEach(d=>{r.add(d.id)});let o=rf(i,t,n),c=sf(i,o);return o.forEach(l=>{s.add(l.id)}),c.forEach(l=>{a.add(l.id)}),{parentsWithFullProgress:r,pendingParentsWithNoLinks:s,pendingParentsWithLinks:a}}catch(i){throw i}}function nf(e){return e.getTaskByTime().filter(rt.filterByParentType).filter(rt.avoidSubproject)}function rf(e,t,n){return e.filter(i=>{let r=i[n];if(!Array.isArray(r))return!1;let s=r.length>0,a=i.constraint_type||"",o=a!=="fnlt";return t==="forward"?!s&&o&&a!=="snet":!s&&o})}function sf(e,t){let n=new Set(t.map(i=>i.id));return e.filter(i=>!n.has(i.id))}function af(e){return e.filter(t=>{let n=Number(t.progress);return Number.isNaN(n)?!1:n===100})}function za({pendingParentsWithLinks:e,gantt:t,direction:n}){try{let i=new Set;return e.forEach(r=>{let s=t.getTask(r),a=of(n),o=cf(n),c=s[a];if(!Array.isArray(c))return;lf(t,c,o).forEach(d=>{i.add(d)})}),i}catch(i){throw i}}function of(e){return e==="forward"?"$source":"$target"}function cf(e){return e==="forward"?"target":"source"}function lf(e,t,n){return t.map(i=>{let s=e.getLink(i)[n];return Number(s)})}var Pe={identifySecondLevelActivities:Ga,identifyInitialActivities:Ka,identifyParentsWithAndWithoutLinks:qa,identifyForbiddenActivities:za};function Pn(e){return e.length?e.reduce((t,n)=>n.ef>t.ef?n:t):!1}function Wi({linkType:e,lag:t,predecessorTime:n,activityCalendar:i,activity:r}){return e===M.FS&&t===0?lt({predecessorTime:n,activityCalendar:i,direction:"future",activity:r}):Re(n,e,i,r)}function Ja({duration:e,constraintDate:t,activityCalendar:n,activity:i}){let r=new Date(t);return{es:k(n,r,e,i),ef:r}}function Xa({duration:e,constraintDate:t,activityCalendar:n,activity:i}){let r=new Date(t),s=k(n,r,e,i);return{es:r,ef:s}}function Re(e,t,n,i){if(![M.FS,M.SS,M.FF].includes(t))return e;let s=[M.FS,M.SS].includes(t)?"future":"past";return lt({dateBaseToCalculate:e,activityCalendar:n,direction:s,activity:i})}var Ui=class{constructor(t,n,i){if(this.linkedActivitiesData=t,this.activity=n,this.gantt=i,this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`)}calculate(){let t=this.calculateLinks(),n=Pn(t),i=this.activity.constraint_type;return i==="snet"?this.handleSNETConstraint(n):i==="fnlt"?this.handleFNLTConstraint(n):n}calculateLinks(){let t=[];for(let n of this.linkedActivitiesData){let i=n.linkType,r=qt(i),s=n.linkLag,a=n.es,o=n.ef,c=null;if(r==="ss")c=this.calculateSSLink({lag:s,predecessorEs:a});else if(r==="ff")c=this.calculateFFLink({lag:s,predecessorEf:o});else if(r==="fs")c=this.calculateFSLink({lag:s,predecessorEf:o});else if(r==="sf")c=this.calculateSFLink({lag:s,predecessorEs:a,predecessorEf:o});else continue;c&&t.push(c)}return t}handleSNETConstraint(t){let n=Xa({duration:this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t&&t.ef>n.ef?t:n}handleFNLTConstraint(t){let n=Ja({duration:-this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t?t.ef>n.ef?n:t:n}calculateSSLink({lag:t,predecessorEs:n}){let i=Wi({linkType:"ss",lag:t,predecessorTime:n,activityCalendar:this.activityCalendar,activity:this.activity}),r=k(this.activityCalendar,i,t,this.activity);t>0&&(r=Re(r,"ss",this.activityCalendar,this.activity));let s=k(this.activityCalendar,r,this.activity.duration,this.activity);return{es:r,ef:s}}calculateFFLink({lag:t,predecessorEf:n}){let i=Wi({linkType:"ff",lag:t,predecessorTime:n,activityCalendar:this.activityCalendar,activity:this.activity}),r=k(this.activityCalendar,i,t,this.activity),s=k(this.activityCalendar,r,-this.activity.duration,this.activity);return t>0&&(s=Re(s,"ff",this.activityCalendar,this.activity)),{es:s,ef:r}}calculateFSLink({lag:t,predecessorEf:n}){let i=n;t===0&&(i=lt({dateBaseToCalculate:n,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let r=k(this.activityCalendar,i,t,this.activity),s=k(this.activityCalendar,r,this.activity.duration,this.activity);return{es:r,ef:s}}calculateSFLink({lag:t,predecessorEs:n}){let i=k(this.activityCalendar,n,t,this.activity),r=k(this.activityCalendar,i,-this.activity.duration,this.activity);return t>0&&(r=Re(r,"sf",this.activityCalendar,this.activity)),{es:r,ef:i}}},Za=Ui;var Bi=class{constructor(t){this.linkedActivitiesData=t.linksWithActivityData,this.activity=t.activity,this.gantt=t.gantt}calculate(){if(this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`);let t=[];for(let n of this.linkedActivitiesData){let i=qt(n.linkType);if(n.type==="task"&&Number(n.progress)>0||n.type==="project"&&Number(n.progress)===100)continue;let r=n.linkLag,s=n.ls,a=n.lf;if(i==="ss"){let o={lag:r,workTime:s,lsDataCalculation:-r,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSSLink(o);t.push({ls:c,lf:l})}if(i==="ff"){let o={lag:r,workTime:a,lsDataCalculation:-this.activity.duration,lfDataCalculation:-r},{ls:c,lf:l}=this.calculateFFLink(o);t.push({ls:c,lf:l})}if(i==="fs"){let o={lag:r,workTime:s,lsDataCalculation:-this.activity.duration,lfDataCalculation:-r},{ls:c,lf:l}=this.calculateFsLink(o);t.push({ls:c,lf:l})}if(i==="sf"){let o={lag:r,workTime:a,lsDataCalculation:-r,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSFLink(o);t.push({ls:c,lf:l})}}if(this.activity.constraint_type==="fnlt"){let n=this.getMinLfFromLinks(t),i=this.calculateSfRestrictionDates();return n?this.getMinLfFromLinks([i,n]):i}else{let n=this.getMinLfFromLinks(t);if(n===!1){let i=this.gantt.getSubtaskDates();return{ls:k(this.activityCalendar,i.end_date,-this.activity.duration,this.activity),lf:i.end_date}}return n}}calculateFFLink({lag:t,workTime:n,lsDataCalculation:i,lfDataCalculation:r}){let s=null,a=null;if(t===0)return s=k(this.activityCalendar,n,r,this.activity),a=k(this.activityCalendar,s,i,this.activity),{ls:a,lf:s};let o=n;return t>0&&(o=this.getLastWorkingHour(o,this.activityCalendar,"past")),s=k(this.activityCalendar,o,r,this.activity),a=k(this.activityCalendar,s,i,this.activity),{ls:a,lf:s}}calculateFsLink({lag:t,workTime:n,lsDataCalculation:i,lfDataCalculation:r,isMilestone:s=!1}){let a=null,o=null;if(t===0){let l=this.getLastWorkingHour(n,this.activityCalendar,"past");return a=k(this.activityCalendar,l,r,this.activity),a=this.getLastWorkingHour(a,this.activityCalendar,"past"),o=k(this.activityCalendar,a,i,this.activity),{ls:o,lf:a}}let c=n;return s||(c=this.getLastWorkingHour(n,this.activityCalendar)),a=k(this.activityCalendar,c,r,this.activity),o=k(this.activityCalendar,a,i,this.activity),s||(a=this.getLastWorkingHour(a,this.activityCalendar,"past")),{ls:o,lf:a}}calculateSFLink({lag:t,workTime:n,lsDataCalculation:i,lfDataCalculation:r}){let s=null,a=null,o=n;return a=k(this.activityCalendar,o,i,this.activity),s=k(this.activityCalendar,a,r,this.activity),{ls:a,lf:s}}calculateSSLink({lag:t,workTime:n,lsDataCalculation:i,lfDataCalculation:r,isMilestone:s=!1}){let a=null,o=null;if(t===0)return o=k(this.activityCalendar,n,i,this.activity),a=k(this.activityCalendar,o,r,this.activity),{ls:o,lf:a};let c=n;return t<0&&!s&&(c=this.getLastWorkingHour(c,this.activityCalendar,"future")),o=k(this.activityCalendar,c,i,this.activity),a=k(this.activityCalendar,o,r,this.activity),{ls:o,lf:a}}getMinLfFromLinks(t=[]){return t.length?t.reduce((n,i)=>i.lf<n.lf?i:n):!1}calculateSfRestrictionDates(){let t=this.activity.constraint_date,n=this.activity.duration;return{ls:k(this.activityCalendar,t,-n,this.activity),lf:t}}getLastWorkingHour(t,n,i="past"){let r=t instanceof Date?t:new Date(t),s=pt(r).clone();return this.isActivityInInitHour(n,r)&&i==="past"&&(s=s.hours(0).minutes(0).seconds(0).milliseconds(0)),lt({dateBaseToCalculate:new Date(s),direction:i,activityCalendar:n,activity:this.activity})}isActivityInInitHour(t,n){let i=n instanceof Date?n:new Date(n),s=t.getWorkHours(i)[0];if(!s||!s.includes("-"))return!1;let a=s.split("-")[0];if(!a.includes(":"))return!1;let o=a.split(":");return o.length<2?!1:(a=parseInt(o[0],10),pt.isMoment(n)?n.hours()===a:i.getUTCHours()===a)}},Qa=Bi;function to(e){let{parent:t,linkProperty:n,linkDirection:i,calculations:r,gantt:s,direction:a}=e,o=t[n],c=df(t),l=null;if(a==="forward"){let d=uf(o,i,r,s);l=new Za(d,t,s),l=l.calculate()}else{let d=ff(o,i,r,s);l=new Qa({linksWithActivityData:d,activity:t,parentData:c,gantt:s}).calculate()}return l}function df(e){return{duration:e.duration,calendarId:e.calendar_id}}function uf(e,t,n,i){return e.length===0?[]:e.map(r=>{let s=i.getLink(r);if(!s)return console.warn(`Link not found: ${r}`),null;let a=Number(s[t]),o=n.get(a);return o?{es:o.es,ef:o.ef,linkLag:s.lag,linkType:s.type}:(console.warn(`Calculations not found for activity: ${a}`),null)}).filter(Boolean)}function ff(e,t,n,i){return e.length===0?[]:e.map(r=>{let s=i.getLink(r);if(!s)return console.warn(`Link not found: ${r}`),null;let a=Number(s[t]),o=n.get(a);if(!o)return null;let c=i.getTask(a);return c?{ls:o.ls,lf:o.lf,linkLag:s.lag||0,linkType:s.type,progress:c.progress,type:c.type}:null}).filter(Boolean)}function io(e){let{activityData:t,calculations:n,singleParents:i,direction:r}=e;if(pf(t.id,n))return null;let s=hf(t.id,i),a=mf(s,n);return a.length===0?null:yf(a,r)}function pf(e,t){return t.has(e)}function hf(e,t){let n=t.get(e);return n?n.childrens:[]}function mf(e,t){return e.filter(n=>t.has(n)).map(n=>t.get(n))}function yf(e,t){if(t==="forward"){let n=eo(e,"es"),i=no(e,"ef");return{es:n,ef:i}}else{let n=eo(e,"ls"),i=no(e,"lf");return{ls:n,lf:i}}}function eo(e,t){return e.reduce((n,i)=>i[t]<n[t]?i:n)[t]}function no(e,t){return e.reduce((n,i)=>i[t]>n[t]?i:n)[t]}var ji={parentWithLinks:to,parentWithNoLinks:io};var Hi=class{constructor(t){this.activity=t.activity,this.direction=t.direction,this.linkProperty=t.direction==="forward"?"$target":"$source",this.linkDirection=t.direction==="forward"?"source":"target",this.calculationsOfParentThatImpactChildrens=t.calculationsOfParentThatImpactChildrens,this.calculations=t.calculations,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.parentCalculationFromChildren=t.parentCalculationFromChildren,this.gantt=t.gantt}handleParentWithLinks(){try{let t=this.getArrayOfIdOfLinkedActivities(this.activity[this.linkProperty]);if(this.direction==="backward"){let i=[h.FNLT];if(this.shouldCalculateParentWithLinksBackward(i)){this.calculateAndStoreParentWithLinks(this.activity);return}if(this.shouldSetDatesToParentsWithLinks(i)){this.setDatesToParentsWithLinksBackward();return}}if(this.areAllLinksCalculated(t)&&this.calculationsOfParentThatImpactChildrens.has(this.activity.id)){this.direction==="forward"&&this.setDatesToParentsWithLinks(),this.direction==="backward"&&this.setDatesToParentsWithLinksBackward();return}this.calculateAndStoreParentWithLinks(this.activity)}catch(t){throw t}}shouldCalculateParentWithLinksBackward(t){let n=t.includes(this.activity.constraint_type),i=!this.calculationOfParentsFromLinks.has(this.activity.id);return n&&i}calculateAndStoreParentWithLinks(t){let n=ji.parentWithLinks({parent:t,linkProperty:this.linkProperty,linkDirection:this.linkDirection,gantt:this.gantt,calculations:this.calculations,direction:this.direction});this.calculationsOfParentThatImpactChildrens.set(t.id,n),this.calculationOfParentsFromLinks.add(t.id)}areAllLinksCalculated(t){return t.every(n=>this.calculations.has(n))}shouldSetDatesToParentsWithLinks(t){let n=t.includes(this.activity.constraint_type),i=this.calculationOfParentsFromLinks.has(this.activity.id);return n&&i}handleParentWithNoLinks(){let t=ji.parentWithNoLinks({activityData:this.activity,gantt:this.gantt,singleParents:this.singleParents,calculations:this.calculations,direction:this.direction});t&&this.calculations.set(this.activity.id,t)}setDatesToParentsWithLinks(){if(!this.activity)throw new Error("Error trying to get parent",{cause:{parentActivity:this.activity}});let t=this.singleParents.get(this.activity.id)?.childrens,i=Array.from(this.calculations).filter(a=>t.includes(a[0])).map(a=>a[1]),{minEs:r,maxEf:s}=i.reduce((a,{es:o,ef:c})=>({minEs:new Date(Math.min(a.minEs.getTime(),new Date(o).getTime())),maxEf:new Date(Math.max(a.maxEf.getTime(),new Date(c).getTime()))}),{minEs:new Date(i[0].es),maxEf:new Date(i[0].ef)});this.calculations.set(this.activity.id,{es:r,ef:s}),this.parentCalculationFromChildren.add(this.activity.id)}setDatesToParentsWithLinksBackward(){if(!this.activity)throw new Error("Error trying to get parent",{cause:{parentActivity:this.activity}});let t=this.singleParents.get(this.activity.id)?.childrens,i=Array.from(this.calculations).filter(a=>t.includes(a[0])).map(a=>a[1]),{minLs:r,maxLf:s}=i.reduce((a,{ls:o,lf:c})=>({minLs:new Date(Math.min(a.minLs.getTime(),new Date(o).getTime())),maxLf:new Date(Math.max(a.maxLf.getTime(),new Date(c).getTime()))}),{minLs:new Date(i[0].ls),maxLf:new Date(i[0].lf)});this.calculations.set(this.activity.id,{ls:r,lf:s})}getArrayOfIdOfLinkedActivities(t,n=!1){return t.map(i=>{let s=this.gantt.getLink(i)[n||this.linkDirection];return Number(s)})}},ro=Hi;var $i=class{constructor({gantt:t,linkProperty:n}){this.gantt=t,this.linkProperty=n,this.structureOfParents=new Map,this.singleParents=new Map}identifyThirdLevelActivities(){try{let t=this.getFirstLevelParents();for(let n of t){let i=this.processEachActivity(n),{activitiesByLevel:r}=i,s=this.getAllLevels(r),a=this.getDeepestLevel(s),o=this.createResult(n,i,a,s);this.structureOfParents.set(n.id,o)}return{structureOfParents:this.structureOfParents,singleParents:this.singleParents}}catch(t){throw t}}getFirstLevelParents(){return this.gantt.getTaskByTime().filter(rt.byFirstLevel).filter(rt.filterByParentType)}processEachActivity(t){let n=new Set,i=new Set,r=new Map;return this.initializeParent(t),this.gantt.eachTask(s=>{this.processActivity(s,n,i,r)},t.id),{parentsIds:n,allTasks:i,activitiesByLevel:r}}initializeParent(t){let n=Number(t.id),i=!!t[this.linkProperty]?.length,r=t.$level;this.singleParents.set(n,{level:r,hasLink:i,childrens:[]})}processActivity(t,n,i,r){let s=Number(t.id),a=Number(t.parent);i.add(s),this.isProjectActivity(t)&&this.addParentInfo(t,n);let c=this.doesParentExist(a);a!=null&&c&&this.addChildToParent(a,s),this.addActivityToLevel(t,r)}isProjectActivity(t){return t.type==="project"}hasLink(t){return!!t[this.linkProperty]?.length}addParentInfo(t,n){let i=Number(t.id),r=t.$level,s=this.hasLink(t),a={level:r,hasLink:s,childrens:[]};n.add(i),this.singleParents.set(i,a)}doesParentExist(t){return this.singleParents.has(t)}addChildToParent(t,n){this.singleParents.get(t).childrens.push(n)}addActivityToLevel(t,n){let i=t.$level,r=Number(t.parent);n.has(i)||n.set(i,new Map);let s=n.get(i);s.has(r)||s.set(r,[]),s.get(r).push({id:Number(t.id),isParent:this.isProjectActivity(t),calculated:!1})}getAllLevels(t){return new Set(t.keys())}getDeepestLevel(t){return t.size===0?0:Math.max(...t)}createResult(t,n,i,r){let{activitiesByLevel:s,parentsIds:a,allTasks:o}=n;return{parent:t.id,isALinkedParent:this.hasLink(t),levels:r,allParentChildrens:a,allChildrens:o,childrensByLevel:s,currentResolutionLevel:i,canBeCalculated:!1}}},so=$i;var Yi=class{constructor(t,n){this.direction=n,this.gantt=t,this.linkProperty=this.direction==="forward"?"$target":"$source",this.linkDirection=this.direction==="forward"?"source":"target",this.projectDates=t.getSubtaskDates()}tryToCalculateLastLevelChildrens(){this.structureOfParents.forEach(t=>{let{currentResolutionLevel:n,childrensByLevel:i,isALinkedParent:r}=t;if(r)return;let s=i.get(n);for(let[a,o]of s)if(o.filter(l=>!this.calculations.has(l.id)).length===0){let l=this.gantt.getTask(a);this.calculateParentWithNoLinks(l,o);return}})}initActivitiesWaitingForCalculation(){try{this.gantt.getTaskByTime().filter(rt.avoidSubproject).forEach(t=>{this.activitiesWaitingForCalculation.add(t.id)})}catch(t){throw t}}identifyParentsWithAndWithoutLinks(){try{let{parentsWithFullProgress:t,pendingParentsWithNoLinks:n,pendingParentsWithLinks:i}=Pe.identifyParentsWithAndWithoutLinks({gantt:this.gantt,direction:this.direction,linkProperty:this.linkProperty});this.parentsWithFullProgress=t,this.pendingParentsWithNoLinks=n,this.pendingParentsWithLinks=i}catch(t){throw t}}identifyForbiddenActivitiesLinkedToParentsWithLinks(){try{this.forbiddenActivitiesLinkedToParentsWithLinks=Pe.identifyForbiddenActivities({pendingParentsWithLinks:this.pendingParentsWithLinks,gantt:this.gantt,direction:this.direction})}catch(t){throw t}}getArrayOfIdOfLinkedActivities(t,n=!1){return t.map(i=>{let s=this.gantt.getLink(i)[n||this.linkDirection];return Number(s)})}async identifyThirdLevelActivities(){try{let{structureOfParents:t,singleParents:n}=new so({gantt:this.gantt,linkProperty:this.linkProperty}).identifyThirdLevelActivities();this.structureOfParents=t,this.singleParents=n}catch(t){throw t}}processEachActivity(t){let n=new Set,i=new Set,r=new Map,s=new Map;return this.singleParents.set(Number(t.id),{level:t.$level,hasLink:!!t[this.linkProperty].length,childrens:[]}),new Promise((a,o)=>{this.gantt.eachTask(function(c){let l=Number(c.parent);if(i.add(c.id),c.type==="project"){let u={level:c.$level,hasLink:!!c[this.linkProperty].length,childrens:[]};n.add(c.id),this.singleParents.set(Number(c.id),u)}l&&this.singleParents.has(l)&&this.singleParents.get(l).childrens.push(c.id),r.has(c.$level)||r.set(c.$level,new Map);let d=r.get(c.$level);d.has(Number(c.parent))||d.set(Number(c.parent),[]),d.get(Number(c.parent)).push({id:c.id,isParent:c.type==="project",calculated:!1})}.bind(this),t.id),a({parentsIds:n,allTasks:i,activitiesByLevel:r,singleParents:s})})}identifySecondLevelActivities(){try{let t=Pe.identifySecondLevelActivities({gantt:this.gantt,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,calculations:this.calculations,linkProperty:this.linkProperty});this.secondLevelActivities=new Set([...this.secondLevelActivities,...t])}catch(t){throw t}}identifyInitialActivities(){try{let{chainStartActivities:t,activitiesStartChainButChildrenOfLinkedParents:n}=Pe.identifyInitialActivities({gantt:this.gantt,linkProperty:this.linkProperty,direction:this.direction});this.chainStartActivities=t,n&&(this.activitiesStartChainButChildrenOfLinkedParents=n)}catch(t){throw new Error("Error in identifyInitialActivities",{cause:t})}}calculateSecondLevelActivities(){try{this.direction==="forward"?this.recursiveCalculateEfAndEs(Array.from(this.secondLevelActivities),0,"secondLevel"):this.recursiveCalculateLfAndLs(Array.from(this.secondLevelActivities))}catch(t){throw t}}calculateStartAndFinishOfActivitiesThatStartChain(){try{this.chainStartActivities.forEach(t=>{if(!t||t.progress>100||t.type==="project")return;let n=this.calculateStartAndFinishOfChainOrigin(t,this.direction);if(this.direction==="forward"){let{es:i,ef:r}=n;this.calculations.set(t.id,{es:i,ef:r,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}else{let{ls:i,lf:r}=n;this.calculations.set(t.id,{ls:i,lf:r,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}})}catch(t){throw t}}buildDependencyGraph(t){let n=new Map,i=new Set(this.calculations.keys()),r=new Map;return t.forEach(s=>{s&&r.set(s.id,s)}),r.forEach((s,a)=>{if(i.has(a))return;let o=[];(s[this.linkDirection]||[]).forEach(l=>{let d=this.gantt.getLink(l);if(d){let u=Number(d[this.linkProperty]);o.push(u)}}),o=o.filter(l=>r.has(l)||i.has(l)),n.set(a,o)}),{graph:n,activityMap:r,calculatedActivities:i}}topologicalSort(t,n){let i=new Set,r=new Set,s=[],a=o=>{if(r.has(o))throw new Error("Cyclical dependency detected",{cause:{nodeId:o}});if(!i.has(o)&&!n.has(o)){r.add(o);let c=t.get(o)||[];for(let l of c)a(l);r.delete(o),i.add(o),s.push(o)}};for(let o of t.keys())!i.has(o)&&!n.has(o)&&a(o);return s.reverse()}calculateStartAndFinishOfChainOrigin(t=null,n=null){try{let i=t,r=Number(i.progress);r==="0.00"&&(r=0);let s=this.gantt.getCalendar(i.calendar_id);if(!s)throw new Error(`Error trying to get calendar with id: ${i.calendar_id}`);if((n||this.direction)==="forward"){let o=i.start_date,c=i.end_date;return{es:o,ef:c}}else{if(r>=100)return{ls:pt(i.start_date).clone(),lf:pt(i.end_date).clone()};if(r===0)return this.calculateBackwardWhenZeroProgress(i,s);if(r<100&&r>0)return this.calculateWhenProgressIsBetweenZeroAndOneHundred(i,s)}}catch(i){throw i}}calculateBackwardWhenZeroProgress(t,n){let i=pt(t.start_date).clone(),r=pt(t.end_date).clone(),s=t.duration,a=[h.ASAP,h.ALAP,h.SNET,h.FNET],o=t.constraint_type||h.ASAP;if(a.includes(o))r=this.projectDates.end_date,i=k(n,r,-s,t);else{let c=[h.SNLT,h.MSO],l=[h.FNLT,h.MFO];c.includes(o)&&(i=t.constraint_date,r=k(n,i,s,t)),l.includes(o)&&(r=t.constraint_date,i=k(n,r,-s,t))}return{ls:i,lf:r}}calculateWhenProgressIsBetweenZeroAndOneHundred(t){let n=t.start_date,i=null,r=t.constraint_type||h.ASAP,s=this.projectDates.end_date,a=[h.ASAP,h.ALAP,h.SNET,h.FNET],o=[h.SNLT,h.FNLT];if(a.includes(r))i=Math.max(t.end_date,s);else if(r===h.MSO)i=t.end_date;else if(r===h.MFO||o.includes(r)){let c=Math.min(s,t.constraint_date);i=Math.max(c,t.end_date)}return{ls:n,lf:new Date(i)}}initializeActivitiesWithFullProgress(){try{Array.from(this.activitiesWaitingForCalculation).filter(i=>Number(this.gantt.getTask(i).progress)===100).map(i=>this.gantt.getTask(i)).forEach(i=>{let r=i.type==="project";this.setDatesForActivityWithFullProgress(i),this.activitiesWaitingForCalculation.delete(i.id),r&&this.pendingParentsWithLinks.has(i.id)&&(this.parentCalculationFromChildren.add(i.id),this.calculationsOfParentThatImpactChildrens.set(i.id,{[this.direction==="forward"?"es":"ls"]:i.start_date,[this.direction==="forward"?"ef":"lf"]:i.end_date}),this.calculationOfParentsFromLinks.add(i.id))})}catch(t){throw t}}doCalculationForParentType(t){let n=new ro({activity:t,direction:this.direction,calculationsOfParentThatImpactChildrens:this.calculationsOfParentThatImpactChildrens,calculations:this.calculations,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,parentCalculationFromChildren:this.parentCalculationFromChildren,gantt:this.gantt});this.pendingParentsWithLinks.has(t.id)?n.handleParentWithLinks():n.handleParentWithNoLinks()}},Ft=Yi;function gf(e,t,n){let i={es:null,ef:null};if(!e)return i;if([h.SNET,h.SNLT].includes(t)){let r=new Date(e.constraint_date);i.es=r,i.ef=k(n,r,e.duration,e)}else if([h.FNLT,h.FNET].includes(t)){let r=new Date(e.constraint_date);i.es=k(n,r,-e.duration,e),i.ef=r}else if(t===h.MSO){let r=new Date(e.constraint_date);i.es=r,i.ef=k(n,r,e.duration,e)}else if(t===h.MFO){let r=new Date(e.constraint_date);i.es=k(n,r,-e.duration,e),i.ef=r}return i}var Rn=gf;var Vi=class{constructor(t){this.referenceActivity=t.activity,this.activityToCalculate=null,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.alapMap=t.calculatedAlapsMap,this.parentsWithLinks=t.parentsWithLinks,this.parentsCalculations=t.parentsCalculations,this.gantt=t.ganttInstance}getEsAndEfFromPreviousCalculatedActivities(t){return this.alapMap.has(t)?this.alapMap.get(Number(t)):this.calculatedActivities.get(Number(t))}calculateSucessorTimes(t,n,i=0,r,s=M.FS){let a=this.gantt.getCalendar(this.referenceActivity.calendar_id);if(!a)throw new Error(`Error trying to get calendar with id: ${this.referenceActivity.calendar_id}`);let o=t,c=null,l=null,d=this.referenceActivity.type==="milestone";return d||(s===M.FS&&r===0?o=lt({dateBaseToCalculate:o,activityCalendar:a,direction:"future",activity:this.referenceActivity}):o=this.mutateTheDateToFutureOrPastInBaseRestriction(t,s,a)),[M.FF,M.SF].includes(s)?(l=k(a,o,i,this.referenceActivity),c=k(a,l,n,this.referenceActivity),!d&&r>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,s,a))):(c=k(a,o,n,this.referenceActivity),!d&&r>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,s,a)),l=k(a,c,i,this.referenceActivity)),{es:c,ef:l}}calculateSS(t){let n=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,s=this.referenceActivity.duration,a=t.lag||0;return this.calculateSucessorTimes(n.es,i,s,a,M.SS)}calculateFF(t){let n=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),r=-this.referenceActivity.duration,s=t.lag||0,a=t.lag||0;return this.calculateSucessorTimes(n.ef,r,s,a,M.FF)}calculateFS(t){let n=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,s=this.referenceActivity.duration,a=t.lag||0;return this.calculateSucessorTimes(n.ef,i,s,a,M.FS)}calculateSF(t){let n=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),r=-this.referenceActivity.duration,s=t.lag||0,a=t.lag||0;return this.calculateSucessorTimes(n.es,r,s,a,M.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,n,i){if(![M.FS,M.SS,M.FF].includes(n))return t;let s=[M.FS,M.SS].includes(n)?"future":"past";return lt({dateBaseToCalculate:t,activityCalendar:i,direction:s,activity:this.referenceActivity})}},ao=Vi;var Le=class extends ao{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Ft(this.gantt,"forward").calculateStartAndFinishOfChainOrigin(this.referenceActivity);let t=this.links.map(i=>{let r=this.gantt.getLink(i);if(!r)throw new Error("Link data not found",{cause:{linkId:i}});return this.calculateLink(r)}),n=Number(this.referenceActivity.parent);if(this.parentsWithLinks.has(n)){let i=this.gantt.getCalendar(this.referenceActivity.calendar_id),r=this.parentsCalculations.get(n).es,s=k(i,r,this.referenceActivity.duration,this.referenceActivity);t.push({es:r,ef:s})}return Pn(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var Gi=class{constructor(t){this.gantt=t.gantt,this.direction=t.direction,this.pendingParentsWithNoLinks=t.pendingParentsWithNoLinks,this.pendingParentsWithLinks=t.pendingParentsWithLinks,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.calculations=t.calculations,this.activitiesStartChainButChildrenOfLinkedParents=t.activitiesStartChainButChildrenOfLinkedParents,this.linkProperty=t.linkProperty,this.linkDirection=t.linkDirection}checkActivitiesThatNowCanBeCalculated(t){let n=new Set,i=new Set(t);for(let r of t){let s=this.gantt.getTask(r);s.type==="project"?this.handleProjectActivity(r,s,n,i):this.handleNonProjectActivity(r,s,n,i)}return{activitiesThatCanBeCalculated:n,pendingActivities:i}}handleProjectActivity(t,n,i,r){let s=this.pendingParentsWithNoLinks.has(t),a=this.pendingParentsWithLinks.has(t),o=this.calculationOfParentsFromLinks.has(t);if(s){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(i.add(t),r.delete(t));return}if(a&&o){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(i.add(t),r.delete(t));return}a&&!o&&this.canCalculateParentActivity(n)&&(i.add(t),r.delete(t))}canCalculateParentActivity(t){let n=(t[this.linkProperty]||[]).length===0,i=t.constraint_type;return(this.direction==="forward"?i==="fnlt"||i==="snlt":i==="fnlt")&&n?!0:this.getArrayOfLinkedActivities(t[this.linkProperty]).every(a=>this.calculations.has(a))}handleNonProjectActivity(t,n,i,r){let s=Number(n.parent),a=this.pendingParentsWithLinks.has(s),o=this.calculationOfParentsFromLinks.has(s);if(a&&!o||this.direction==="backward"&&this.activitiesStartChainButChildrenOfLinkedParents.has(t)&&!o)return;if(n.$target.length===0&&n.$source.length===0){i.add(t),r.delete(t);return}let c=this.getLinkedActivities(n[this.linkProperty]),l=c.every(d=>this.calculations.has(d.id));if(this.direction==="backward"&&(c.length===0||l)&&o){i.add(t),r.delete(t);return}l&&(i.add(t),r.delete(t))}getLinkedActivities(t){if(!Array.isArray(t))return[];let n=[];for(let i of t){let r=this.gantt.getLink(i);if(!r)continue;let s=r[this.linkDirection],a=this.gantt.getTask(s);a&&n.push(a)}return n}getArrayOfLinkedActivities(t){if(!Array.isArray(t))return[];let n=[];for(let i of t){let r=this.gantt.getLink(i);r&&n.push(Number(r[this.linkDirection]))}return n}},Ln=Gi;var Ki=(e,t)=>()=>t()===e;var qi=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var vf=16,be=async e=>performance.now()-e>vf?(await nt(),performance.now()):e;var Oe=async({pending:e,activityCalculator:t,calculateFn:n,shouldKeepPending:i,isCalculated:r,onActivityProcessed:s,isCurrent:a})=>{let o=new Set(e),c=performance.now();for(;o.size>0;){if(!a())return;c=await be(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(o);if(l.size===0)break;for(let u of l){if(!a())return;c=await be(c),n([u])}for(let u of l){if(!a())return;i(u)&&d.add(u),s(u),r(u)&&d.delete(u)}o=d}};var zi=class extends Ft{constructor(t){super(t,"forward"),this.gantt=t,this.chainStartActivities=new Set,this.secondLevelActivities=new Set,this.pendingParentsWithLinks=new Set,this.pendingParentsWithNoLinks=new Set,this.structureOfParents=new Map,this.singleParents=new Map,this.calculations=new Map,this.calculationsOfParentThatImpactChildrens=new Map,this.alapMap=new Map,this.activitiesWaitingForCalculation=new Set,this.constraintsMap=new Map,this.totalFloatSnltFnlt=new Map,this.totalFloatForMsoMfo=new Map,this.totalFloatForAsap=new Map,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateEfAndEs(t))))))}async iterativeCalculateEfAndEs(t){let n=new Ln({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await Oe({pending:this.activitiesWaitingForCalculation,activityCalculator:n,calculateFn:i=>this.calculateStartAndFinishTimes(i),shouldKeepPending:i=>this.calculationOfParentsFromLinks.has(i)&&!this.calculations.has(i),isCalculated:i=>this.calculations.has(i),onActivityProcessed:i=>this.activitiesWaitingForCalculation.delete(i),isCurrent:t})}calculateStartAndFinishTimes(t){t.forEach(n=>{let i=this.gantt.getTask(n);if(i.type==="project")return this.doCalculationForParentType(i);if(!i)throw new Error("Error trying to get activity",{cause:{activityId:n}});let r=i.$target,s=i.constraint_type||h.ASAP,a=[h.SNET,h.SNLT,h.FNLT,h.FNET],o=[h.ASAP,h.ALAP,h.SNET,h.FNET,h.SNLT,h.FNLT],c=this.gantt.getCalendar(i.calendar_id);if(!c)throw new Error(`Error trying to get calendar with id: ${i.calendar_id}`);let l=Number(i.progress),d=null,u=null,f=null;if(l===100){this.setDatesForActivityWithFullProgress(i);return}l>0&&o.includes(s)?({es:d,ef:u}=this.getDatesForActivityWithZeroProgress(i),f=new Le({links:r,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:s,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),s===h.ASAP&&this.totalFloatForAsap.set(n,{es:f.es,ef:f.ef,text:i.text})):{es:d,ef:u}=new Le({links:r,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:s,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),s===h.ALAP&&this.alapMap.set(n,{es:i.start_date,ef:i.end_date,text:i.text});let p=Rn(i,s,c);if(a.includes(s)&&(this.constraintsMap.set(n,p),this.totalFloatSnltFnlt.set(n,{es:d,ef:u}),{es:d,ef:u}=this.recalculateInBaseConstraint(s,p,{es:d,ef:u})),[h.MSO,h.MFO].includes(s))if(this.totalFloatForMsoMfo.set(n,{es:d,ef:u}),this.constraintsMap.set(n,p),i.progress===0)d=p.es,u=p.ef;else{let A=i.end_date;s===h.MFO&&(A=Math.max(p.ef,i.end_date)),d=i.start_date,u=A}this.calculations.set(n,{es:d,ef:u}),this.activitiesWaitingForCalculation.delete(n)})}getTheGreatesDateBetweenRestrictionAndEsEf(t,n,i="greater"){if(i==="greater")return n.ef>t.ef?n:t;if(i==="less")return n.ef<t.ef?n:t}setDatesForActivityWithFullProgress(t){this.calculations.set(t.id,{es:t.start_date,ef:t.end_date})}getDatesForActivityWithZeroProgress(t){return{es:t.start_date,ef:t.end_date}}recalculateInBaseConstraint(t,n,i){let r=[h.SNET,h.FNET].includes(t)?"greater":"less",{es:s,ef:a}=this.getTheGreatesDateBetweenRestrictionAndEsEf(n,i,r);return{es:s,ef:a}}cleanAllActivityParentsFromLinks(t){return t.map(n=>{let i=this.gantt.getLink(n);if(!i)throw new Error("Error trying to get link",{cause:{linkId:n}});let r=i.source,s=i.target;if(!(!this.gantt.getTask(r)||this.gantt.getTask(r)?.type==="project")&&!(!this.gantt.getTask(s)||this.gantt.getTask(s)?.type==="project"))return n}).filter(Boolean)}},oo=zi;var Ji=class{constructor(t){this.activity=t.activity,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.forwardPathCalculations=t.calculatedForwardActivitiesMap,this.gantt=t.ganttInstance}getForwardOrBackwardCalculations(t,n=null){return n===h.ALAP?this.forwardPathCalculations.get(t):this.calculatedActivities.get(t)}calculateSuccessorTimes(t,n,i=0,r,s=M.FS){let a=this.gantt.getCalendar(this.activity.calendar_id);if(!a)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`);let o=t,c=this.activity.type==="milestone";if(c&&r===0){let d=k(a,o,n,this.activity),u=k(a,d,i,this.activity);return{ls:d,lf:u}}let l={lag:r,workTime:o,activityCalendar:a,lsDataCalculation:n,lfDataCalculation:i,isMilestone:c};if(s===M.FS){let{ls:d,lf:u}=this.calculateFsLink(l);return{ls:d,lf:u}}if(s===M.FF){let{ls:d,lf:u}=this.calculateFFLink(l);return{ls:d,lf:u}}if(s===M.SS){let{ls:d,lf:u}=this.calculateSSlink(l);return{ls:d,lf:u}}if(s===M.SF){let{ls:d,lf:u}=this.calculateSFLink(l);return{ls:d,lf:u}}}calculateSS(t,n=!1){let i=this.getValueForSS(t,n),r=-t.lag||0,s=this.activity.duration,a=t.lag;return this.calculateSuccessorTimes(i,r,s,a,M.SS)}calculateFF(t,n){let i=this.getForwardOrBackwardCalculations(Number(t.target)),r=n===h.ALAP?"ef":"lf",s=i[r],a=-this.activity.duration,o=-t.lag||0,c=t.lag;return this.calculateSuccessorTimes(s,a,o,c,M.FF)}calculateFS(t,n){let i="ls";i=n===h.ALAP?"es":"ls";let r=this.getForwardOrBackwardCalculations(Number(t.target),n),s=-this.activity.duration,a=t.lag||0,o=-t.lag||0;return this.calculateSuccessorTimes(r[i],s,o,a,M.FS)}calculateSF(t,n=!1){let i=n?this.getEarlyStartFromForwardPath(Number(t.target)).ef:this.getForwardOrBackwardCalculations(Number(t.target)).lf,r=-t.lag||0,s=this.activity.duration,a=t.lag;return this.calculateSuccessorTimes(i,r,s,a,M.SF)}getEarlyStartFromForwardPath(t){return this.forwardPathCalculations.get(t)}getValueForSS(t,n){return n?this.getEarlyStartFromForwardPath(Number(t.target)).es:this.getForwardOrBackwardCalculations(Number(t.target))["ls"]}calculateDate(t,n,i){let r=pt(n).clone();return k(t,new Date(r),i,this.activity)}getLastWorkingHour(t,n,i="past"){let r=t instanceof Date?t:new Date(t),s=pt(r).clone();return this.isActivityInInitHour(n,r)&&i==="past"&&(s=s.hours(0).minutes(0).seconds(0).milliseconds(0)),lt({dateBaseToCalculate:new Date(s),direction:i,activityCalendar:n,activity:this.activity})}isActivityInInitHour(t,n){let i=n instanceof Date?n:new Date(n),s=t.getWorkHours(i)[0];if(!s||!s.includes("-"))return!1;let a=s.split("-")[0];if(!a.includes(":"))return!1;let o=a.split(":");return o.length<2?!1:(a=parseInt(o[0],10),pt.isMoment(n)?n.hours()===a:i.getUTCHours()===a)}calculateFsLink({lag:t,workTime:n,activityCalendar:i,lsDataCalculation:r,lfDataCalculation:s,isMilestone:a=!1}){let o=null,c=null;if(t===0){let d=this.getLastWorkingHour(n,i,"past");return o=k(i,d,s,this.activity),o=this.getLastWorkingHour(o,i,"past"),c=k(i,o,r,this.activity),{ls:c,lf:o}}let l=n;return a||(l=this.getLastWorkingHour(n,i)),o=k(i,l,s,this.activity),c=k(i,o,r,this.activity),a||(o=this.getLastWorkingHour(o,i,"past",!0)),{ls:c,lf:o}}calculateFFLink({lag:t,workTime:n,activityCalendar:i,lsDataCalculation:r,lfDataCalculation:s}){let a=null,o=null;if(t===0)return a=k(i,n,s,this.activity),o=k(i,a,r,this.activity),{ls:o,lf:a};let c=n;return t>0&&(c=this.getLastWorkingHour(c,i,"past")),a=k(i,c,s,this.activity),o=k(i,a,r,this.activity),{ls:o,lf:a}}calculateSSlink({lag:t,workTime:n,activityCalendar:i,lsDataCalculation:r,lfDataCalculation:s,isMilestone:a=!1}){let o=null,c=null;if(t===0)return c=k(i,n,r,this.activity),o=k(i,c,s,this.activity),{ls:c,lf:o};let l=n;return t<0&&!a&&(l=this.getLastWorkingHour(l,i,"future")),c=k(i,l,r,this.activity),o=k(i,c,s,this.activity),{ls:c,lf:o}}calculateSFLink({lag:t,workTime:n,activityCalendar:i,lsDataCalculation:r,lfDataCalculation:s}){let a=null,o=null;return t===0?(o=k(i,n,r),a=k(i,o,s,this.activity),{ls:o,lf:a}):(o=k(i,n,r,this.activity),a=k(i,o,s,this.activity),{ls:o,lf:a})}},co=Ji;var Xi=class extends co{constructor(t){super(t),this.constraint=t.constraint||h.ASAP,this.parentsWithFullProgress=t.parentsWithFullProgress,this.parentsThatImpactChildrens=t.parentsThatImpactChildrens,this.projectDates=this.gantt.getSubtaskDates()}calculate(){if(this.links.length===0)return new Ft(this.gantt,"backward").calculateStartAndFinishOfChainOrigin(this.activity);let t=this.activity.progress>0&&this.activity.progress<100,n=this.gantt.getTask(this.activity.parent),i=!1;n&&(i=this.parentsThatImpactChildrens.has(Number(this.activity.parent)));let r=this.links.map(a=>{let o=this.gantt.getLink(a);if(!o)throw new Error("Link not found",{cause:{linkId:a}});if(!this.parentsWithFullProgress.has(Number(o.target)))return this.calculateLink(o)}).filter(a=>a);if(r.length!==0){let a=this.getMinLfFromLinks(r);if(r.push(this.calculateTheLsAndLfForTheActivity()),i){let d=this.parentsThatImpactChildrens.get(Number(this.activity.parent));r.push(this.calculateTheLsAndLfForTheActivity(d))}let o=this.getMinDateFromLinks(r),c=o.ls,l=o.lf;return t&&(c=this.activity.start_date,l=this.getMinCalculationLogic(o)),{ls:c,lf:l,minFromLinks:a}}if(i){r.push(this.calculateTheLsAndLfForTheActivity());let o=this.parentsThatImpactChildrens.get(Number(this.activity.parent)).lf,c=k(this.gantt.getCalendar(this.activity.calendar_id),o,-this.activity.duration,this.activity);r.push({ls:c,lf:o});let l=this.getMinDateFromLinks(r);return{ls:l.ls,lf:l.lf,minFromLinks:l}}let s=this.calculateTheLsAndLfForTheActivity();return{ls:s.ls,lf:s.lf,minFromLinks:s}}calculateTheLsAndLfForTheActivity(t=null){try{let n=this.activity.duration,i=this.gantt.getCalendar(this.activity.calendar_id);if(!i)throw new Error(`Calendar not found with id ${this.activity.calendar_id}`);let r=t?t.lf:this.projectDates.end_date;if(!r)throw new Error("End date not found for activity",{cause:{activityId:this.activity.id}});return{ls:k(i,r,-n,this.activity),lf:r}}catch(n){throw Error(n.message)}}SnetSnltMsoMinDate(t){let n=Math.min(t.lf,this.projectDates.end_date);return new Date(Math.max(n,this.activity.end_date))}calculateLink(t){let n=this.gantt.getTask(t.target);if(!n||n.progress>0&&n.type!=="project")return;let i=this.getSpecialCalculationParamForConstraintLink(),r=this.getSpecialParamForSf(),s=this.getSpecialParamForFF();return{0:()=>this.calculateFS(t,i),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t,s),3:()=>this.calculateSF(t,r)}[t.type]()}getSpecialCalculationParamForConstraintLink(){if(this.constraint===h.ALAP)return h.ALAP;if(this.constraint===h.FNET||this.constraint===h.SNET)return"snet-fnet";if(this.constraint===h.FNLT)return h.FNLT}getSpecialParamForSf(){return!![h.ALAP].includes(this.constraint)}getSpecialParamForFF(){return!![h.MFO,h.MSO].includes(this.constraint)}getMinCalculationLogic(t){if(this.constraint===h.ALAP)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.FNET)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.FNLT)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.MFO)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.SNET||this.constraint===h.SNLT||this.constraint===h.MSO)return this.SnetSnltMsoMinDate(t);if(this.constraint===h.ASAP)return this.getMinDateBasedOnConstraint(t)}getMinDateFromLinks(t){try{return this.constraint===h.ALAP||this.constraint===h.ASAP?t.reduce((i,r)=>r.lf<i.lf?r:i):t.reduce((n,i)=>i.ls<n.ls?i:n)}catch(n){throw new Error(`Function: getMinDateFromLinks in LinksConstraintCalculator - ${n.message}`)}}getMinLfFromLinks(t){return t.reduce((n,i)=>i.lf<n.lf?i:n)}getMinDateBasedOnConstraint(t,n=this.constraint){let i=Math.min(t.lf,this.projectDates.end_date),r=this.activity.end_date,s=this.activity.constraint_date;if(n===h.ASAP)return new Date(Math.max(i,r));if(n===h.FNET||n===h.FNLT){let a=Math.min(i,s);return new Date(Math.max(i,a))}if(n===h.ALAP)return new Date(Math.min(i,r))}},lo=Xi;function Af(e,t,n){let i={ls:null,lf:null};return n===h.MSO&&(i.ls=t.constraint_date,i.lf=k(e,i.ls,t.duration,t)),n===h.MFO&&(i.lf=t.constraint_date,i.ls=k(e,i.lf,-t.duration,t)),i}var uo=Af;var Zi=class extends Ft{constructor(t,n,i){super(t,"backward"),this.gantt=t,this.chainStartActivities=new Set,this.secondLevelActivities=new Set,this.pendingParentsWithLinks=new Set,this.pendingParentsWithNoLinks=new Set,this.structureOfParents=new Map,this.singleParents=new Map,this.calculationsOfParentThatImpactChildrens=new Map,this.activitiesWaitingForCalculation=new Set,this.calculations=new Map,this.mapOfRelationsWithActivitiesIds=new Map,this.activitiesWaitingForCalculation=new Set,this.forwardPathCalculations=n,this.forwardConstraintsMap=i,this.constraintMap=new Map,this.minFromLinks=new Map,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.parentsWithFullProgress=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateLfAndLs(t))))))}async iterativeCalculateLfAndLs(t){let n=new Ln({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await Oe({pending:this.activitiesWaitingForCalculation,activityCalculator:n,calculateFn:i=>this.calculateStartAndFinishTimes(i),shouldKeepPending:i=>this.calculationOfParentsFromLinks.has(i)&&!this.calculations.has(i),isCalculated:i=>this.calculations.has(i),onActivityProcessed:i=>this.activitiesWaitingForCalculation.delete(i),isCurrent:t})}setDatesToParentsWithLinks(t){if(!t)throw new Error("Error trying to get parent",{cause:{receivedParentData:t}});let n=this.singleParents.get(t.id).childrens,r=Array.from(this.calculations).filter(o=>n.includes(o[0])).map(o=>o[1]),{minLs:s,maxLf:a}=r.reduce((o,{ls:c,lf:l})=>({minLs:new Date(Math.min(o.minLs.getTime(),new Date(c).getTime())),maxLf:new Date(Math.max(o.maxLf.getTime(),new Date(l).getTime()))}),{minLs:new Date(r[0].ls),maxLf:new Date(r[0].lf)});this.calculations.set(t.id,{ls:s,lf:a})}calculateStartAndFinishTimes(t){t.forEach(n=>{let i=this.gantt.getTask(n);if(!i)throw new Error("Activity not found",{cause:{activityId:n}});let r=i.$source,s=i.constraint_type||h.ASAP,a=Number(i.progress);if(this.activitiesStartChainButChildrenOfLinkedParents.has(n)){if(this.calculationsOfParentThatImpactChildrens.has(Number(i.parent))&&this.calculationsOfParentThatImpactChildrens.get(Number(i.parent))===!1){let{ls:d,lf:u}=this.calculateStartAndFinishOfChainOrigin(i,this.direction);this.setCalculations(i,d,u);return}return this.doCalculationForActivitiesThatStartLinkButHisParentIsLinked(i)}if(i.type==="project")return this.doCalculationForParentType(i);if(a===100){this.setDatesForActivityWithFullProgress(i);return}if(this.allLinkedActivitiesHasProgress(r,i)){this.setWhenAllLinkedActivitiesHasProgress(i);return}if(a>0&&a<100&&(s===h.MSO||s===h.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(i,s);return}if(s===h.MSO||s===h.MFO){this.recalculateInBaseRestriction(i,s);return}let{ls:o,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(r,i,s,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(s===h.SNLT||s===h.FNLT)&&({ls:o,lf:c}=this.getTheLessLateInBasEsEfConstraint(i.id,{ls:o,lf:c},s)),this.setCalculations(i,o,c),this.minFromLinks.set(i.id,{ls:l.ls,lf:l.lf})})}getTheLessLateInBasEsEfConstraint(t,n,i){let r=this.forwardConstraintsMap.get(t);if(!r){let s=this.gantt.getTask(t),a=this.gantt.getCalendar(s.calendar_id);r=Rn(s,i,a)}return n.lf<r.ef?n:{ls:r.es,lf:r.ef}}allLinkedActivitiesHasProgress(t){try{let n=!0;for(let i of t){let r=this.gantt.getLink(i);if(!r)continue;let s=this.gantt.getTask(r.target);s&&(s.type==="project"&&(n=!1),s.progress===0&&(n=!1))}return n}catch(n){throw new Error(n.message)}}setDatesForActivityWithFullProgress(t){this.setCalculations(t,t.start_date,t.end_date)}setWhenAllLinkedActivitiesHasProgress(t){let n=Number(t.parent),{ls:i,lf:r}=this.calculateStartAndFinishOfChainOrigin(t,"backward");if(this.calculationsOfParentThatImpactChildrens.has(n)){i=t.start_date;let s=this.calculationsOfParentThatImpactChildrens.get(n);s&&typeof s=="object"&&s.lf!=null&&(r=new Date(Math.min(r,s.lf)))}this.setCalculations(t,i,r)}setWhenActivitiesHasProgressButLessThanOneHundred(t,n){if(n===h.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(n===h.MFO){let i=Math.min(t.constraint_date,this.projectDates.end_date),r=new Date(Math.max(i,t.end_date));this.setCalculations(t,t.start_date,r);return}}setCalculations(t,n,i){this.calculations.set(t.id,{ls:n,lf:i,text:t.text})}calculateLfandLsFromLinks(t,n,i,r,s){return new lo({links:t,activity:n,calculatedActivitiesMap:this.calculations,calculatedForwardActivitiesMap:this.forwardPathCalculations,constraint:i,parentsWithFullProgress:r,parentsThatImpactChildrens:s,ganttInstance:this.gantt}).calculate()}recalculateInBaseRestriction(t,n){try{let i=this.gantt.getCalendar(t.calendar_id);if(!i)throw new Error(`Error trying to get calendar with id: ${t.calendar_id}`);let r=uo(i,t,n);this.constraintMap.set(t,r),this.setCalculations(t,r.ls,r.lf)}catch(i){throw new Error(i.message)}}cleanAllActivityParentsFromLinks(t){return t.map(n=>{let i=this.gantt.getLink(n).source,r=this.gantt.getLink(n).target;if(!(!this.gantt.getTask(i)||this.gantt.getTask(i)?.type==="project")&&!(!this.gantt.getTask(r)||this.gantt.getTask(r)?.type==="project"))return n}).filter(Boolean)}doCalculationForActivitiesThatStartLinkButHisParentIsLinked(t){let n=Number(t.parent),i=this.calculationsOfParentThatImpactChildrens.get(n),r=0,s=0;if([h.ASAP,h.ALAP,h.SNET,h.FNET].includes(t.constraint_type))if(Number(t.progress)>0){let l=this.projectDates.end_date;s=new Date(Math.min(l,i.lf)),r=t.start_date}else s=i.lf,r=k(this.gantt.getCalendar(t.calendar_id),s,-t.duration,t);if([h.SNLT].includes(t.constraint_type)){let l=t.constraint_date,d=this.calculationsOfParentThatImpactChildrens.get(n),u=k(this.gantt.getCalendar(t.calendar_id),d.lf,-t.duration,t);r=new Date(Math.min(l.getTime(),u.getTime())),s=k(this.gantt.getCalendar(t.calendar_id),r,t.duration,t)}if([h.FNLT].includes(t.constraint_type)){let l=t.constraint_date,d=this.calculationsOfParentThatImpactChildrens.get(n);r=new Date(Math.min(l.getTime(),d.lf.getTime())),s=k(this.gantt.getCalendar(t.calendar_id),r,t.duration,t)}[h.MSO].includes(t.constraint_type)&&(r=t.constraint_date,s=k(this.gantt.getCalendar(t.calendar_id),r,t.duration,t)),[h.MFO].includes(t.constraint_type)&&(s=t.constraint_date,r=k(this.gantt.getCalendar(t.calendar_id),s,-t.duration,t));let a=this.projectDates.end_date,o=[{ls:r,lf:s}];o.push({ls:k(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t),lf:a});let c=this.getMinLfFromLinks(o);this.calculations.set(t.id,{ls:c.ls,lf:c.lf,text:t.text})}getMinLfFromLinks(t=[]){return t.length?t.reduce((n,i)=>i.lf<n.lf?i:n):!1}},fo=Zi;function po(){return null}var ho=({forward:e,backward:t,id:n,activity:i,gantt:r,projectDates:s})=>({totalFloat:{es:e.calculations.get(n)?.es||0,ef:e.calculations.get(n)?.ef||0,ls:t.calculations.get(n)?.ls||0,lf:t.calculations.get(n)?.lf||0,constraintsMap:e.constraintsMap.get(n),totalFloatSnltFnlt:e.totalFloatSnltFnlt.get(n),totalFloatForMsoMfo:e.totalFloatForMsoMfo.get(n),minFromLinks:t.minFromLinks.get(n),activity:i,gantt:r},freeFloat:{forwardMap:e.calculations||new Map,backwardMap:t.calculations||new Map,activity:i,projectDates:s,gantt:r}});var Qi=class{constructor(t){this.gantt=t.gantt,this.activity=t.activity,this.es=t.es,this.ef=t.ef,this.ls=t.ls,this.lf=t.lf,this.constrainstMap=t.constraintsMap,this.totalFloatSnltFnlt=t.totalFloatSnltFnlt,this.totalFloatForMsoMfo=t.totalFloatForMsoMfo,this.minFromLinks=t.minFromLinks}getTotalFloat(){let{constraint_type:t}=this.activity,n=Number(this.activity.progress);if(n===100)return 0;if(t||(t=h.ASAP),t===h.ASAP||!t)return n===0?this.calculateAsap():this.calculateAsapWithProgress();if(t===h.ALAP)return n===0?this.calculateAlap():this.calculateAlapWithProgress();if(t===h.SNET||t===h.FNET)return n===0?this.calculateSnetFet():this.calculateSnetFnetSnltWithProgress();if(t===h.SNLT)return n===0?this.calculateSnltFnlt():this.calculateSnetFnetSnltWithProgress();if(t===h.FNLT)return n===0?this.calculateSnltFnlt():this.calculateFnltWithProgress();if(t===h.MSO||t===h.MFO)return n===0?this.calculateMsoMfo():this.calculateMsoMfoWithProgress()}calculateAsap(){let t=this.calculationWithCalendar(this.ls,this.es),n=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,n)/this.gantt.config.hoursPerDay}calculateAsapWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let n=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,n)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateAlap(){let t=this.calculationWithCalendar(this.ls,this.es),n=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,n),r=this.calculationWithCalendar(this.lf,this.activity.end_date);return this.getMinValue(i,r)/this.gantt.config.hoursPerDay}calculateAlapWithProgress(){return this.calculationWithCalendar(this.lf,this.ef)/this.gantt.config.hoursPerDay}calculateSnetFnetSnltWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let n=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,n)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateFnltWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef),n=this.calculationWithCalendar(this.activity.constraint_date,this.ef);if(this.minFromLinks){let i=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,n,i)/this.gantt.config.hoursPerDay}return this.getMinValue(t,n)/this.gantt.config.hoursPerDay}calculateMsoMfoWithProgress(){return this.calculationWithCalendar(this.lf,this.ef)/this.gantt.config.hoursPerDay}calculateSnetFet(){let t=this.calculationWithCalendar(this.ls,this.es),n=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,n)/this.gantt.config.hoursPerDay}calculateSnltFnlt(){let t=this.calculationWithCalendar(this.ls,this.es),n=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,n);if(!this.totalFloatSnltFnlt&&!this.constrainstMap)return this.getMinValue(t,n)/this.gantt.config.hoursPerDay;let r=0;return this.activity.constraint_type===h.SNLT?r=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatSnltFnlt.es):r=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatSnltFnlt.ef),this.getMinValue(r,i)/this.gantt.config.hoursPerDay}calculateMsoMfo(){let t=this.calculationWithCalendar(this.ls,this.es),n=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,n);if(!this.totalFloatForMsoMfo&&!this.constrainstMap)return this.getMinValue(t,n)/this.gantt.config.hoursPerDay;let r=0;return this.activity.constraint_type===h.MSO?r=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatForMsoMfo.es):r=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatForMsoMfo.ef),this.getMinValue(r,i)/this.gantt.config.hoursPerDay}getMinValue(...t){return Math.min(...t)}calculationWithCalendar(t,n){return this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(n),end_date:new Date(t)})}},mo=Qi;var tr=class{constructor(t){this.gantt=t.gantt,this.activity=t.activity,this.forwardMap=t.forwardMap,this.backwardMap=t.backwardMap,this.projectDates=t.projectDates,this.linksFreeFloatArray=[],this.linksFreeFloatObject={},this.durationCache=new Map}getFreeFloat(){let t=Number(this.activity.progress),n=this.getConstraintType();return this.calculateFreeFloatOfLink(n),{activityFreeFloat:t===100?0:this.getFreeFloatBaseConstraint(n),linksFreeFloat:this.linksFreeFloatObject}}getFreeFloatBaseConstraint(t){return t===h.MSO||t===h.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=h.ASAP){let n=this.activity.$source.map(i=>{let{LINK:r,LINK_TYPE:s}=this.getLinkData(i),a=this.gantt.getTask(r.target);if(!a)return{linkId:r.id,freeFloat:null,hasProgress:!1};let o=Number(a.progress)>0,{sucessorDateToCalculate:c,predecessorDateToCalculate:l}=this.getDatesFromSucessorAndPredecessor(s,t,a),d=this.calculationWithCalendar(c,l),u=this.parseHoursToDays(d)-this.parseHoursToDays(r.lag),f=Math.max(0,u);return this.linksFreeFloatObject[r.id]=f,{linkId:r.id,freeFloat:f,hasProgress:o}}).filter(i=>i.freeFloat!==null&&i.freeFloat!==void 0);return this.linksFreeFloatArray=n,n}calculateGeneral(t=h.ASAP){let n=this.getMinFloat(this.linksFreeFloatArray),i=this.calculateFreeFloatForEndOfProject(t),r=0;return[h.SNLT,h.FNLT].includes(t)?r=this.doCalculationForSnltFnlt(t,i,n):r=this.doGeneralCalculation(i,n),Math.max(0,r)}getConstraintType(){let{constraint_type:t}=this.activity;return t||(t=h.ASAP),t}getDatesFromSucessorAndPredecessor(t,n,i){let r=i.constraint_type===h.ALAP,s=this.getSucessorAndPredecessorDates({constraint:n,isSuscessorAlap:r,sucessorId:i.id,predecessorId:this.activity.id}),a=new Date,o=new Date;return a=s[t].sucessor,o=s[t].predecessor,{sucessorDateToCalculate:a,predecessorDateToCalculate:o}}doGeneralCalculation(t,n){return n===null?t:this.getMinValue(n,t)}doCalculationForSnltFnlt(t,n,i){let r=this.calculateFreeFloatOfRestriction(t);return this.getMinValue(i,n,r)}calculateFreeFloatForEndOfProject(t){return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===h.ALAP?this.backwardMap.get(this.activity.id).lf:this.forwardMap.get(this.activity.id).ef))}calculateFreeFloatOfRestriction(t){return this.parseHoursToDays(this.calculationWithCalendar(this.activity.constraint_date,t===h.FNLT?this.forwardMap.get(this.activity.id).ef:this.forwardMap.get(this.activity.id).es))}getLinkData(t){let n=this.gantt.getLink(t)||{},i=qt(n.type);return{LINK:n,LINK_TYPE:i}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:n,sucessorId:i,predecessorId:r}){let s=({direction:a,constraint:o=h.ASAP})=>o===h.ALAP?this.backwardMap.get(r)[a]:this.forwardMap.get(r)[a];if(t===h.ASAP||t===h.SNET||t===h.FNET||t===h.MSO||t===h.MFO)return{fs:{sucessor:n?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:s({direction:"ef"})},ss:{sucessor:n?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:s({direction:"es"})},ff:{sucessor:n?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:s({direction:"ef"})},sf:{sucessor:n?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:s({direction:"es"})}};if(t===h.ALAP)return{fs:{sucessor:n?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:s({constraint:h.ALAP,direction:"lf"})},ss:{sucessor:n?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:s({constraint:h.ALAP,direction:"ls"})},ff:{sucessor:n?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:s({constraint:h.ALAP,direction:"lf"})},sf:{sucessor:n?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:s({constraint:h.ALAP,direction:"ls"})}};if(t===h.SNLT)return{fs:{sucessor:n?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:s({direction:"ef"})},ss:{sucessor:n?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:s({direction:"es"})},ff:{sucessor:n?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:s({direction:"ef"})},sf:{sucessor:n?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:s({direction:"es"})}};if(t===h.FNLT)return{fs:{sucessor:n?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:s({direction:"ef"})},ss:{sucessor:n?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:s({direction:"es"})},ff:{sucessor:n?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:s({direction:"ef"})},sf:{sucessor:n?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:s({direction:"es"})}}}calculateMsoMfo(t){let n=this.activity.constraint_date||new Date,i=t===h.MSO?this.forwardMap.get(this.activity.id).es:this.forwardMap.get(this.activity.id).ef,r=this.calculationWithCalendar(n,i);return Math.max(0,this.parseHoursToDays(r))}getMinValue(...t){let n=t.filter(i=>i!=null);return n.length?Math.min(...n):0}calculationWithCalendar(t,n){let i=`${n.getTime()}_${t.getTime()}`;if(this.durationCache.has(i))return this.durationCache.get(i);let s=this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(n),end_date:new Date(t)});return this.durationCache.set(i,s),s}parseHoursToDays(t){return t?t/this.gantt.config.hoursPerDay:0}getMinFloat(t){if(!t?.length)return null;let n=t.filter(i=>!i.hasProgress).map(i=>i.freeFloat);return n.length===0?null:Math.min(...n)}},yo=tr;var go=e=>({totalFloat:new mo(e.totalFloat).getTotalFloat(),freeFloat:new yo(e.freeFloat).getFreeFloat()});var er=async({activityIds:e,forward:t,backward:n,gantt:i,projectDates:r,isCurrent:s})=>{let a=performance.now(),o=new Map,c=new Map;for(let l of e){if(s&&!s())return{totalFloatMap:o,freeFloatMap:c};let d=i.getTask(l);if(!d)continue;let u=ho({forward:t,backward:n,id:l,activity:d,gantt:i,projectDates:r}),{totalFloat:f,freeFloat:p}=go(u);o.set(l,f),c.set(l,p),a=await be(a)}return{totalFloatMap:o,freeFloatMap:c}};var nr=class{constructor(t){this.gantt=t,this.forwardPathCalculations=null,this.backwardPathCalculations=null,this.totalFloat=new Map,this.freeFloat=new Map,this.currentCalculationId=0}getCurrentCalculationId=()=>this.currentCalculationId;async calculate(t){let n=++this.currentCalculationId,i=Ki(n,this.getCurrentCalculationId);try{let r=t||this.gantt;if(this.gantt=r||po(),qi(this.gantt))return!1;let s=new oo(this.gantt);if(await s.calculateAsync(i),!i())return!1;let a=s.calculations,o=s.constraintsMap,c=new fo(this.gantt,a,o);if(await c.calculateAsync(i),!i())return!1;this.forwardPathCalculations=a,this.backwardPathCalculations=c.calculations;let{totalFloatMap:l,freeFloatMap:d}=await this.calculateFloatsAsync(s,c,i);return i()?(this.totalFloat=l,this.freeFloat=d,this.gantt.refreshData(),!0):!1}catch(r){return this.forwardPathCalculations?.size,!1}}async calculateFloatsAsync(t,n,i){try{let r=this.gantt.getSubtaskDates(),s=Array.from(this.forwardPathCalculations.keys());return await er({activityIds:s,forward:t,backward:n,gantt:this.gantt,projectDates:r,isCurrent:i})}catch(r){return this.forwardPathCalculations?.size,{totalFloatMap:new Map,freeFloatMap:new Map}}}},vo=nr;function Cf(e){return{calculateEndDate:({start_date:t,duration:n})=>e.calculateEndDate(t,n),calculateDuration:({start_date:t,end_date:n})=>e.calculateDuration(t,n),getWorkHours:t=>e.getWorkHours(t),$gantt:{getClosestWorkTime:({date:t,dir:n,unit:i})=>e.getClosestWorkTime({date:t,direction:n,unit:i??"hour"})}}}function Sf(e){let t=new Map;e.forEachActivity((r,s)=>t.set(String(s),r));let n=new Map,i=(r,s)=>{let a=n.get(r);if(a!=null)return a;let o=t.get(r),c=o?o.parent:0,l=c===0||c==="0"||c==null,d=0;return!l&&!s.has(r)&&(s.add(r),d=i(String(c),s)+1),n.set(r,d),d};for(let r of t.keys())i(r,new Set);return n}function _f(e){let t=Sf(e),n=new Map;return e.forEachActivity((i,r)=>{let s=String(r);n.set(s,{...i,id:Number(r),parent:Number(i.parent),$level:t.get(s)??0})}),n}function kf(e){let t=new Map;for(let a of e.values()){let o=t.get(a.parent);o?o.push(a):t.set(a.parent,[a])}let n=[],i=new Set,r=[],s=a=>{if(a)for(let o=a.length-1;o>=0;o-=1)r.push(a[o])};for(s(t.get(0));r.length>0;){let a=r.pop();i.has(a)||(i.add(a),n.push(a),s(t.get(a.id)))}if(n.length<e.size)for(let a of e.values())i.has(a)||n.push(a);return n}function If(e){let t=null,n=null;return e.forEachActivity(i=>{if(i.start_date){let r=i.start_date.getTime();t=t==null?r:Math.min(t,r)}if(i.end_date){let r=i.end_date.getTime();n=n==null?r:Math.max(n,r)}}),{start_date:new Date(t??0),end_date:new Date(n??0)}}async function Ao(e,t){let n=new Map,i=c=>{let l=c==null?"__default__":String(c),d=n.get(l);if(d)return d;let u=e.calendarReader.getCalendar(String(c)),f=Cf(u);return n.set(l,f),f},r=If(e);await nt();let s=_f(e);await nt();let a=[...s.values()].sort((c,l)=>(c.start_date?.getTime()??0)-(l.start_date?.getTime()??0));await nt();let o=kf(s);return{fullyParsed:!0,config:{hoursPerDay:t},getTask:c=>s.get(String(c))??null,getLink:c=>{let l=e.getLink(c);return l?{...l,source:Number(l.source),target:Number(l.target)}:null},getCalendar:i,getChildren:c=>e.getChildren(c).map(l=>Number(l)),eachTask:c=>{for(let l of o)c(l)},getTaskByTime:()=>a,getSubtaskDates:()=>r,refreshData:()=>{}}}var Tf=1e3;async function bn(e,t){let n=await Ao(e,t),i=new vo(n),r=await i.calculate(n),s=new Map;if(!r)return s;let a=i.forwardPathCalculations,o=i.backwardPathCalculations,c=i.totalFloat,l=i.freeFloat,d=p=>p==null?null:new Date(p),u=new Set([...a?.keys()??[]]),f=0;for(let p of u){++f>=Tf&&(f=0,await nt());let A=e.getActivity(p);if(!A)continue;let I=a?.get(p),S=o?.get(p),T=c.get(p),g=Number(A.progress??0),C={earlyStart:d(I?.es),earlyFinish:d(I?.ef),lateStart:d(S?.ls),lateFinish:d(S?.lf),totalSlack:T??null,freeSlack:l.get(p)?.activityFreeFloat??null,isCritical:g<100&&T!=null&&T<=0},y=String(p);s.set(y,C),e.setActivityFields(y,{earlyStart:C.earlyStart,earlyFinish:C.earlyFinish,lateStart:C.lateStart,lateFinish:C.lateFinish,totalSlack:C.totalSlack,freeSlack:C.freeSlack,is_critical:C.isCritical?"Si":"No"})}return s}function Ct(e){let t=e?.baseline_points;return!Array.isArray(t)||t.length===0?null:t.find(n=>!!n?.sectorbaselineversion?.active)??null}function On(e){let t=[],n=[];e.forEachActivity((r,s)=>{(r.parent===0||r.parent==="0"||r.parent==null)&&t.push(String(s))});let i=r=>{let s=e.getActivity(String(r));if(!s)return 0;let a=[...e.getChildren(String(r))],o;if(a.length===0){let c=Ct(s),l=c&&Number(c.cost)||0;o=(Number(s.progress)||0)/100*l}else{let c=0;for(let l of a)c+=i(String(l));o=c}return e.setActivityField(String(r),v.REAL_COST,o),n.push(String(r)),o};for(let r of t)i(r);return n}var Co=new Set(["activity-outdent","activity-indent"]);var So=new Set(["activity-outdent","activity-indent"]);var we=new Set([v.TEXT,v.DESCRIPTION,v.COST,v.USED_COST,v.CUSTOM_ID,v.RESPONSABLES,v.SUBCONTRACT_ID,v.TAGS]),Df=new Set(["selection-toggle","selection-replace","visibility-set","sir-sync"]);function Ef(e){return e.kind==="inline-edit"?we.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>we.has(t.column)):!1}function ko(e,t){return!(Df.has(e.kind)||t.has(e.kind)||Ef(e))}function Ne(e){return ko(e,Co)}function ir(e){return ko(e,So)}function rr(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?e.column===v.PROGRESS:e.kind==="bulk-edit"?e.edits.some(t=>t.column===v.PROGRESS):!1}function Pf(e){return ir(e)&&rr(e)}var _o=new Set([v.PROGRESS,v.HH_WORK_TIME,v.DURATION,v.COST,v.USED_COST,v.REAL_COST]);function Rf(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?_o.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>_o.has(t.column)):!1}var Lf=new Set([v.CUSTOM_PREDECESSORS,v.CUSTOM_SUCESSORS]);function Io(e){return e.kind==="inline-edit"&&Lf.has(e.column)}var Q={AUTOSCHEDULE:"autoschedule",PARENT_BOUNDS:"parent-bounds",PARENT_PROGRESS:"parent-progress",REAL_WORK:"real-work",MILESTONE_MIRROR_ANCESTORS:"milestone-mirror-ancestors",MILESTONE_MIRROR_GLOBAL:"milestone-mirror-global",EXPECTED_PROGRESS:"expected-progress",REAL_COST:"real-cost",CRITICAL_PATH:"critical-path"};function bf(e,t){return Io(e)?!0:e.kind==="activity-indent"?!1:e.kind==="inline-edit"||e.kind==="bulk-edit"?t.requested:!0}function Of(e,t){return Io(e)?!1:(e.kind==="activity-delete"||e.kind==="activity-set-progress"||e.kind==="inline-edit"||e.kind==="bulk-edit")&&t.ran}function To(e,t,n){let i=new Set;t.ran&&i.add(Q.AUTOSCHEDULE),i.add(Q.PARENT_BOUNDS),Rf(e)&&i.add(Q.PARENT_PROGRESS),rr(e)&&i.add(Q.REAL_WORK),bf(e,t)&&i.add(Q.MILESTONE_MIRROR_ANCESTORS),Of(e,t)&&i.add(Q.MILESTONE_MIRROR_GLOBAL);let r=!n.skipAutoSchedule;return r&&ir(e)&&i.add(Q.EXPECTED_PROGRESS),r&&Pf(e)&&i.add(Q.REAL_COST),r&&ir(e)&&Ne(e)&&!n.skipCriticalPath&&i.add(Q.CRITICAL_PATH),i}async function j(e,t){let n=wf(t),i=n.has(Q.AUTOSCHEDULE)?await Nf(e,t.autoscheduleFrom):Ff();return await Mf(e.adapter,t,i.scheduledIds,n),n.has(Q.MILESTONE_MIRROR_GLOBAL)&&Ei(e.adapter),await Wf(e,n,t.now),i}function wf(e){let t=e.autoscheduleFrom!==null,n=!e.options.skipAutoSchedule&&t;return To(e.action,{requested:t,ran:n},e.options)}async function Nf(e,t){let n=t==="roots"?{}:{triggerId:t},i=await e.scheduler.schedule(n),r=xf(e.adapter,i.updatedIds);return _e(e.adapter,i),r}function xf(e,t){let n=[],i=new Map;for(let r of t){let s=String(r);n.push(s);let a=e.getActivity(s);a&&(i.set(s,Z(a)),e.noteScheduledBefore(s,a))}return{scheduledIds:n,scheduledBeforeImages:i}}function Ff(){return{scheduledIds:[],scheduledBeforeImages:new Map}}async function Mf(e,t,n,i){let r=t.collectDirty?t.collectDirty(n):Na(t.recomputeParentsFrom,n);await Ie(e,r,i.has(Q.PARENT_PROGRESS),{skipMilestoneDurationStamp:!i.has(Q.MILESTONE_MIRROR_ANCESTORS),recomputeRealWork:i.has(Q.REAL_WORK)})}async function Wf(e,t,n){t.has(Q.EXPECTED_PROGRESS)&&n!==null&&(Dn(e.adapter,n),Gt(e.adapter,e.sector.statusCriteria)),t.has(Q.REAL_COST)&&On(e.adapter),t.has(Q.CRITICAL_PATH)&&await bn(e.adapter,e.sector.hoursPerDay)}var Uf=new Set([v.CONSTRAINT_TYPE,v.CONSTRAINT_DATE]),Bf=new Set(["mso","mfo"]);function wn(e){return Uf.has(e)}function Nn(e,t,n,i){let r=n.getActivity(e);if(!r)return!1;let s=r.constraint_type??null;if(!s||Tt.has(s)||Bf.has(s))return!1;let a=sr(r.last_start_date),o=sr(r.start_date);if(!a||!o||o.getTime()!==a.getTime())return!1;let c=jf(t,s,String(r.calendar_id??""),i),l=sr(r.constraint_date);return Hf(l,c)?!1:(n.setActivityField(e,v.CONSTRAINT_DATE,c),!0)}function jf(e,t,n,i){if(e===null)return null;let r=i.getCalendar(n);return r?$t(e,r,t):e}function sr(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function Hf(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function xn(e,{postMutationArgs:t,revertTargets:n,revert:i}){let{scheduledIds:r,scheduledBeforeImages:s}=await j(e,Do(t)),a=!1;for(let{activityId:o,priorConstraintDate:c}of n){let l=i(o,c);a=a||l}if(a){let o=await j(e,Do(t));r=Yf(r,o.scheduledIds),s=Vf(s,o.scheduledBeforeImages)}return Ne(t.action)&&await j(e,$f(t)),{scheduledIds:r,scheduledBeforeImages:s}}function Do(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function $f(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function Yf(e,t){let n=new Set(e);for(let i of t)n.add(i);return[...n]}function Vf(e,t){let n=new Map(e);for(let[i,r]of t)n.has(i)||n.set(i,r);return n}function Gf(e,t){let n=i=>i.getTime();return n(e.start_date)!==n(t.start_date)||n(e.end_date)!==n(t.end_date)||e.duration!==t.duration}function ar(e,t,n){let i=[];for(let r of n){let s=e.get(r);if(!s)continue;let a=s.pendingRequests??[];if(!Zt({pendingRequests:a}))continue;let o=t.getActivity(r),c=o==null;if(!c&&!Gf(s,o))continue;let l=c?"activity_deleted":"date_changed";for(let d of a)i.push({kind:"sir-auto-reject",activityId:r,sirId:d.id,reason:l});c||t.setActivityField(r,"pendingRequests",[])}return i}function G(e,t){let n=new Set;for(let l of t.touchedIds)n.add(l);for(let l of t.scheduledIds)n.add(l);if(t.includeAllIds)for(let l of e.getAllIds())n.add(l);let i=new Map(t.beforeSnap),r=e.peekWriteCapture();if(r)for(let l of r.dirty){if(n.has(l))continue;let d=r.before.get(l),u=e.getActivity(l);!d||!u||Object.keys(wi(d,u)).length!==0&&(i.set(l,d),n.add(l))}if(t.scheduledBeforeImages)for(let[l,d]of t.scheduledBeforeImages){let u=String(l);i.has(u)||(i.set(u,d),n.add(u))}let s=t.sirDetection==="before-diff"?ar(i,e,n):[],a=wa(e,i,n),o=t.sirDetection==="after-diff"?ar(i,e,n):s,c=t.warnings??[];return{source:t.source,activities:a,links:t.links??[],calendars:[],trackingEvents:t.trackingEvents??[],...o.length>0?{effects:o}:{},...c.length>0?{warnings:c}:{}}}function Fn(e,t,n){let i=[];for(let{op:r,finalLinkId:s,rejected:a}of e){if(a!==null)continue;if(r.kind==="create"){if(!s)continue;let d=n.getLink(s);if(!d)continue;i.push({id:String(s),kind:"created",fields:{source:{before:void 0,after:String(d.source)},target:{before:void 0,after:String(d.target)},type:{before:void 0,after:d.type},lag:{before:void 0,after:Number(d.lag)}},after:gt(d)});continue}if(r.kind==="delete"){let d=t.get(r.linkId);i.push({id:String(r.linkId),kind:"deleted",fields:d?{source:{before:String(d.source),after:void 0},target:{before:String(d.target),after:void 0},type:{before:d.type,after:void 0},lag:{before:Number(d.lag),after:void 0}}:void 0,after:null});continue}let o=t.get(r.linkId),c=n.getLink(r.linkId);if(!c)continue;let l={};o&&o.type!==c.type&&(l.type={before:o.type,after:c.type}),o&&Number(o.lag)!==Number(c.lag)&&(l.lag={before:Number(o.lag),after:Number(c.lag)}),i.push({id:String(r.linkId),kind:"updated",fields:l,after:gt(c)})}return i}function pe(e,t){let n=new Map,i=e.getActivity(t);if(!i)return n;for(let r of i.$target){let s=e.getLink(r);s&&n.set(String(s.id),Number(s.lag))}return n}function he(e,t,n){let i=[],r=t.getActivity(n);if(!r)return i;for(let s of r.$target){let a=t.getLink(s);if(!a)continue;let o=e.get(String(a.id));o===void 0||o===Number(a.lag)||i.push({id:String(a.id),kind:"updated",fields:{lag:{before:o,after:Number(a.lag)}},after:gt(a)})}return i}function Mn(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function Eo(e,t,n){let{adapter:i,ctx:r,scheduler:s,sector:a}=n,o=wt(e.column);if(!o)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);Kf(e.column)&&s.invalidateExpandedLinksCache(),e.column===tt.PARENT&&s.invalidateAllCaches();let c=r.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:E.ACTIVITY_NOT_FOUND};let l=o.canEdit(c);if(!l.allowed)return{ok:!1,reason:l.reason??E.CANNOT_EDIT,alertKey:l.alertKey};let d=o.parseInput(e.newValue,c,r);if(!d.ok)return{ok:!1,reason:d.reason??E.PARSE_ERROR};let u=Reflect.get(c,e.column),f=o.validate(c,u,d.value,r);if(!f.valid)return{ok:!1,reason:f.reason??E.INVALID,alertKey:f.notification?.messageKey};if(e.column===v.CUSTOM_ID&&d.value!==null){let D=i.getActivity(e.activityId),R=D?D.custom_id:null,U=typeof R=="string"?R:null;if(n.customIdTracker.isCustomIdInUse(String(d.value),U))return{ok:!1,reason:E.CUSTOM_ID_DUPLICATE}}let p=o.transform(c,d.value,r,d.raw),A=Nt(e.activityId,p),I=K(i,A),S=pe(i,String(e.activityId));xt(i,e.activityId,e.column,p),Ot(e.activityId,p.postProcessors??[],i);let T=he(S,i,String(e.activityId));if(e.column===v.CUSTOM_ID){let D=I.get(String(e.activityId)),R=D?D.custom_id:null,U=typeof R=="string"?R:null,W=typeof d.value=="string"?d.value:null;U!==W&&n.customIdTracker.trackCustomIdChange(U,W)}let g=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:D=>In(e.activityId,A,D),now:n.now,options:t}),C=wn(e.column),{scheduledIds:y,scheduledBeforeImages:m}=await(C?xn({adapter:i,scheduler:s,sector:n.sector},{postMutationArgs:g(),revertTargets:[{activityId:e.activityId,priorConstraintDate:c.constraint_date}],revert:(D,R)=>Nn(D,R,i,r.calendars)}):j({adapter:i,scheduler:s,sector:n.sector},g())),_=(p.trackingEvents??[]).map(D=>({name:D.name,properties:D.properties??{}})),P=ue(e.activityId,p.constraintWarning);return{ok:!0,changes:G(i,{source:e,beforeSnap:I,touchedIds:A,scheduledIds:y,scheduledBeforeImages:m,sirDetection:"before-diff",links:T,trackingEvents:_,...P?{warnings:[P]}:{},hoursPerDay:a.hoursPerDay})}}function Kf(e){return e===v.DURATION||e===tt.AUTO_SCHEDULING}async function Po(e,t,n){if(e.kind==="link-create"||e.kind==="link-update"){let i=e.type;if(i!==void 0&&!Object.values(B).some(s=>s===i))return{ok:!1,reason:E.INVALID_LINK_TYPE};let r=e.lag;if(r!==void 0&&!Number.isFinite(r))return{ok:!1,reason:E.INVALID_LINK_LAG}}return or([Xf(e,n.sector.hoursPerDay)],e,t,n,e.kind==="link-create"&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function Ro(e,t,n){let{hoursPerDay:i}=n.sector,r=e.operations.map(a=>zf(a,i)),s=qf(e.operations);return or(r,e,t,n,s)}function qf(e){let t=new Map;return e.forEach((n,i)=>{n.kind==="create"&&n.linkId&&t.set(i,n.linkId)}),t.size>0?t:void 0}function zf(e,t){return e.kind==="create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:ft(e.lag??0,t)}:e.kind==="update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:ft(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function or(e,t,n,i,r){let{adapter:s,scheduler:a,sector:o,linkIdGen:c}=i;a.invalidateAllCaches();let l=new Set,d=new Map;for(let T of e)if(T.kind==="create")l.add(String(T.source)),l.add(String(T.target));else{let g=s.getLink(T.linkId);g&&(l.add(String(g.source)),l.add(String(g.target)),d.set(T.linkId,{...g}))}let u=K(s,l),f=[];for(let T=0;T<e.length;T++){let g=e[T],C=g.kind==="create"&&r?r.get(T):void 0,y=Lt(g,{port:s,newLinkId:C?()=>C:c.next});f.push({op:g,finalLinkId:y.applied?y.linkId:null,rejected:y.applied?null:y.rejected??"link_op_rejected"})}if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!=="inline-edit")return{ok:!1,reason:f[0].rejected};let p=Jf(f,d,s),{scheduledIds:A}=await j({adapter:s,scheduler:a,sector:i.sector},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:i.now,options:n});for(let T of A)if(!u.has(T)){let g=s.getActivity(T);g&&u.set(T,Z(g))}let I=Fn(f,d,s),S=new Map;for(let[T,g]of d)S.set(String(T),g);return{ok:!0,__beforeLinks:S,changes:G(s,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:A,links:I,hoursPerDay:o.hoursPerDay})}}function Jf(e,t,n){for(let i of e)if(i.rejected===null){if(i.op.kind==="create")return String(i.op.target);if(i.op.kind==="delete"){let r=t.get(i.op.linkId);if(r)return String(r.target)}if(i.op.kind==="update"){let r=n.getLink(i.op.linkId);if(r)return String(r.target)}}return null}function Xf(e,t){return e.kind==="link-create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:ft(e.lag,t)}:e.kind==="link-update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:ft(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function Lo(e,t,n){let{adapter:i,sector:r}=n;if(typeof e.newValue!="string")return{ok:!1,reason:E.INVALID_VALUE};let s=i.getActivity(e.activityId);if(!s)return{ok:!1,reason:E.ACTIVITY_NOT_FOUND};let a=e.column===v.CUSTOM_PREDECESSORS,{specs:o}=un(e.newValue),c=o.map(A=>({...A,lag:ft(A.lag,r.hoursPerDay)})),l=new Map;i.forEachActivity(A=>{A.correlative_id!=null&&l.set(String(A.correlative_id),A.id)});let d=A=>l.get(A)??null,u=a?s.$target:s.$source,f=[];for(let A of u){let I=i.getLink(A);I&&f.push(I)}let p=a?pn({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):hn({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return or(p.operations,e,t,n)}var ht={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 cr(e,t){if(!e||e==="0")return;let n=String(e);for(;n!==null;){let i=t.getChildren(n),r=0,s=0;for(let c of i){let l=t.getActivity(c);if(!l)continue;let d=bo(l,v.HH_WORK_TIME),u=Zf(l,v.REAL_WORK),f=u!==void 0?u:d*bo(l,v.PROGRESS)/100;r+=d,s+=f}t.setActivityField(n,v.HH_WORK_TIME,r),t.setActivityField(n,v.REAL_WORK,s);let a=t.getActivity(n);if(!a)break;let o=a.parent;if(!o||o==="0")break;n=String(o)}}function Oo(e,t){let n=t.getActivity(e);if(!n)return;let i=n.parent;!i||b(i)||cr(String(i),t)}function bo(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:0}function Zf(e,t){let n=e[t];if(typeof n=="number"&&Number.isFinite(n))return n}function lr(e,t){if(!e||e==="0")return;let n=String(e);for(;n!==null;){let i=t.getChildren(n),r=0;for(let o of i){let c=t.getActivity(o);c&&(r+=Qf(c,v.USED_COST))}t.setActivityField(n,v.USED_COST,r);let s=t.getActivity(n);if(!s)break;let a=s.parent;if(!a||a==="0")break;n=String(a)}}function wo(e,t){let n=t.getActivity(e);if(!n)return;let i=n.parent;!i||b(i)||lr(String(i),t)}function Qf(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:0}function dr(e,t){if(!e||e==="0")return;let n=String(e);for(;n!==null;){let i=t.getChildren(n),r=0;for(let o of i){let c=t.getActivity(o);c&&(r+=tp(c,v.COST))}t.setActivityField(n,v.COST,r);let s=t.getActivity(n);if(!s)break;let a=s.parent;if(!a||a==="0")break;n=String(a)}}function No(e,t){let n=t.getActivity(e);if(!n)return;let i=n.parent;!i||b(i)||dr(String(i),t)}function tp(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:0}var Wn=Object.freeze({description:"",type:"task",progress:0,constraint_type:"asap",constraint_date:null,auto_scheduling:!0,cost:0,used_cost:0,real_cost:0,hhWorkTime:0,real_work:0,ponderator:0,responsables:[],tags:[],subcontractId:null,real_constraint_type:"asap",should_be_showed:!0,visible:!0,activityModifications:[],pendingRequests:[],new_task:!0,isNewActivity:!0,$source:[],$target:[]}),ep=new Set(["name","old_type","old_duration","on_open_lightbox_type","for_disable_milestone_duration","last_constraint","constraint_type_old"]);function xo(e){return e==="$source"||e==="$target"?!1:e.startsWith("$")||ep.has(e)}var Fo="New Master Plan",Mo="New Activity";function np(e){let t={};for(let n of Object.keys(e))xo(n)||(t[n]=e[n]);return t}function Wo(e,t){let n=e.parentId!=null?t.getActivity(e.parentId):null,i=e.activityOverrides??{},r=e.numTasksInGantt===0?Fo:Mo,s=i.name,a=i.text??(typeof s=="string"?s:void 0)??r,o=i.duration??e.sector.hoursPerDay??8,c=i.calendar_id??e.sector.defaultCalendar,l={calendar_id:c},d=ip(n,e.fallbackStartDate,i.start_date),u=t.getClosestWorkTime({date:d,dir:q.FUTURE,task:l}),f=t.calculateEndDate({start_date:u,duration:o,task:l}),p={...Wn,text:a,start_date:u,end_date:f,duration:o,calendar_id:c,parent:e.parentId==null?"0":String(e.parentId),unique_correlative_id:e.nextUniqueCorrelativeId,...np(i)};for(let[I,S]of Object.entries(p))Array.isArray(S)&&(p[I]=[...S]);p.$source=[],p.$target=[],p.real_constraint_type=p.constraint_type;let A=p.type==="milestone";return p.for_disable_milestone_duration=A?0:Math.round(p.duration),{newTask:p}}function ip(e,t,n){return n?new Date(n):e?new Date(e.start_date):t?new Date(t):new Date}function me(e){let t=e.getParent(e.parentId);if(!t)return null;let n=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&Rt(t.type):rp(t),i=t.type==="milestone",r=Array.isArray(t.newActivitiesArray)?t.newActivitiesArray:[],a={is_lookahead:!1,hasNewActivities:!0,newActivitiesArray:r.some(o=>String(o)===String(e.newChildId))?[...r]:[...r,e.newChildId],old_type:t.type};return t.custom_id!=null&&t.custom_id!==""&&(a.custom_id=null),n&&(a.type=an,a.$rendered_type=an,i&&(a.is_milestone=!1),a.$no_start=!0,a.$no_end=!0,a.constraint_type=$.ASAP,a.constraint_date=null,a.real_constraint_type=t.constraint_type??$.ASAP,(e.promotionSource??"create")==="create"&&(a.progress=0)),{parentId:e.parentId,fields:a}}function rp(e){return Rt(e.type)&&(!Array.isArray(e.newActivitiesArray)||e.newActivitiesArray.length===0)}function Un(e,t,n,i){let r=t,s=r==="0",a=ur(e,r);if(i!==void 0){let c=a.find(l=>l.id===i);if(c){let l=st(c),d=a.map(st).filter(f=>f<l);return d.length===0?l-1:(Math.max(...d)+l)/2}}if(n!==void 0){let c=a.find(l=>l.id===n);if(c){let l=st(c),d=a.map(st).filter(f=>f>l);if(d.length===0)return l+1;let u=Math.min(...d);return(l+u)/2}}return a.length===0?0:Math.max(...a.map(st))+1}var zt=Number.MAX_SAFE_INTEGER,Uo=Number.MAX_SAFE_INTEGER-1;function st(e){let t=e.correlative_id,n=typeof t=="number"?t:Number(t);return Number.isFinite(n)?n:zt}function ur(e,t){let n=[];return e.forEachActivity(i=>{_t(i.parent)===t&&n.push(i)}),n}function Bo(e,t,n){let i=e,r=ye(e,n);for(;r!=null&&t.has(r);)i=r,r=ye(r,n);return i}function ye(e,t){let n=t.getActivity(e);if(!n)return null;let i=_t(n.parent),r=Kt(i,t),s=r.findIndex(a=>String(a)===String(e));return s<=0?null:r[s-1]??null}function jo(e,t,n,i){let r=Kt(t,e).filter(c=>String(c)!==String(i)).map(c=>e.getActivity(c)).filter(c=>c!==null);if(r.length===0)return 0;let s=r.map(st);if(n<=0)return s[0]-1;if(n>=s.length)return s[s.length-1]+1;let a=s[n-1],o=s[n];return(a+o)/2}function Bn(e,t,n={}){let{adapter:i,scheduler:r,sector:s,calendars:a,activityIdGen:o,uidGen:c}=t;r.invalidateAllCaches();let l=sp(e,i);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=op(e.activityId,i,o),A=c.next(),I={parentId:f?null:e.parentId,sector:{id:s.id,hoursPerDay:s.hoursPerDay,defaultCalendar:fp(a)},numTasksInGantt:i.activityCount(),nextUniqueCorrelativeId:A,activityOverrides:e.overrides??{}},T={...Wo(I,{getActivity:m=>i.getActivity(m),calculateEndDate:m=>i.calculateEndDate(m),getClosestWorkTime:m=>i.getClosestWorkTime(m)}).newTask,id:p};lp(T,e,t,u,d,n);let g=Un(i,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);T.correlative_id=g;let C=new Set([p]);d&&C.add(d.id);let y=n.skipBeforeSnap?new Map:K(i,C);return i.addActivity(T),dp(e,p,d,i,n.preserveParentCustomId??!1),Oo(p,i),wo(p,i),No(p,i),up(i,p,y,C,n),{ok:!0,newId:p,parent:d,newActivity:T,beforeSnap:y,initialTouched:C}}function sp(e,t){let n=b(e.parentId),i=n?null:t.getActivity(e.parentId);if(!n&&!i)return{ok:!1,reason:E.PARENT_NOT_FOUND};if(i!==null&&Zt({pendingRequests:i.pendingRequests}))return{ok:!1,reason:E.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:E.ANCHOR_SIBLING_CONFLICT};let a=e.afterSiblingId??e.beforeSiblingId,o=ap(e,t,n,a);return o||{ok:!0,parent:i,anchorSiblingId:a,isRoot:n}}function ap(e,t,n,i){if(i===void 0)return null;let r=t.getActivity(i);if(!r)return{ok:!1,reason:E.ANCHOR_SIBLING_NOT_FOUND};let s=n?"0":e.parentId;return(r.parent==null||r.parent===0?"0":String(r.parent))!==s?{ok:!1,reason:E.ANCHOR_SIBLING_WRONG_PARENT}:null}function op(e,t,n){return e===void 0||t.activityExists(e)?n.next():(n.bump(e),e)}function cp(e){if(e.overrides===void 0||!(v.CUSTOM_ID in e.overrides))return;let t=e.overrides.custom_id;return typeof t=="string"?t:void 0}function lp(e,t,n,i,r,s){let{adapter:a,customIdTracker:o}=n,c=cp(t);if(c!==void 0){if(c.length===0)return;if(!o.isCustomIdInUse(c)){o.registerCustomId(c);return}}let l=i??s.customIdReferenceId,d=l!==void 0,u=d?a.getActivity(l):r;e.custom_id=o.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function dp(e,t,n,i,r){if(!n)return;let s=me({parentId:e.parentId,newChildId:t,getParent:a=>i.getActivity(a)??null});if(s)for(let[a,o]of Object.entries(s.fields))a===v.CUSTOM_ID&&r||V(i,s.parentId,a,o)}function up(e,t,n,i,r){if(r.skipCorrelativeRecompute)return;let s=ot(e);r.skipBeforeSnap||Tn(e,s,new Set([String(t)]),n,i)}function Ho(e,t,n,i,r,s){let{newId:a,newActivity:o,beforeSnap:c,initialTouched:l}=n,d={name:ht.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:a,created_duration:o.duration}};t.eventSource!==void 0&&(d.properties.event_source=t.eventSource);let u=s?new Map([...s].filter(([f])=>String(f)!==String(a))):void 0;return G(e,{source:t,beforeSnap:c,touchedIds:l,scheduledIds:i,scheduledBeforeImages:u,trackingEvents:[d],hoursPerDay:r})}function $o(e,t){let n=Bn(e,t);if(!n.ok)return{ok:!1,reason:n.reason};Di(t.adapter,new Set([n.newId]));let i=t.adapter.getActivity(n.newId);if(!i)throw new Error(`[ScheduleCore] createActivity: new activity ${n.newId} missing after commit`);let r=Ho(t.adapter,e,n,[],t.sector.hoursPerDay);return{ok:!0,activity:X(i),changes:r}}async function Yo(e,t,n){let{adapter:i,scheduler:r,sector:s}=n,a=Bn(e,n);if(!a.ok)return a;let{newId:o}=a,{scheduledIds:c,scheduledBeforeImages:l}=await j({adapter:i,scheduler:r,sector:n.sector},{action:e,autoscheduleFrom:String(o),recomputeParentsFrom:[o],now:n.now,options:t});return{ok:!0,changes:Ho(i,e,a,c,s.hoursPerDay,l)}}function fp(e){for(let n of e.values())if(n.is_default)return n.id;let t=e.values().next();return!t.done&&t.value?t.value.id:"global"}function pp(e,t){if("afterSiblingId"in e){let s=t.getActivity(e.afterSiblingId);return s?{ok:!0,parentId:s.parent==null||s.parent===0?"0":String(s.parent),firstAfter:e.afterSiblingId}:{ok:!1,reason:E.ANCHOR_SIBLING_NOT_FOUND}}let n=e.parentId,r=ur(t,n).sort((s,a)=>st(s)-st(a))[e.index]?.id;return{ok:!0,parentId:n,firstBefore:r}}function hp(e,t){let n=e,{parent:i,unique_correlative_id:r,correlative_id:s,custom_id:a,...o}=n,c=o.duration,l=typeof c=="number"&&Number.isFinite(c)?se(c,t):void 0;return{...o,...l!==void 0?{duration:l}:{},progress:0,ponderator:0,used_cost:0,expected_progress_base:0,hhWorkTime:0,checked:!1,visibleChecked:!1,comesFromCopy:!0,is_lookahead:!1,should_correct_start_date:!1,is_critical:!1,constraint_type_backup:n.constraint_type}}async function Vo(e,t,n){let{adapter:i,scheduler:r,sector:s}=n,a=pp(e.destination,i);if(!a.ok)return a;let o=K(i,new Set),c=new Set,l=new Map,d=[],u;for(let g of e.activities){let C=l.get(g.originalParentId),y,m,_;C!==void 0?y=C:(y=a.parentId,u===void 0?(m=a.firstAfter,_=a.firstBefore):m=u);let P=Bn({kind:"activity-create",parentId:y,afterSiblingId:m,beforeSiblingId:_,overrides:hp(g.overrides,s.hoursPerDay),eventSource:e.eventSource},n,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,...C!==void 0?{customIdReferenceId:e.referenceActivityId,preserveParentCustomId:!0}:{}});if(!P.ok)return P;l.set(g.originalId,P.newId),d.push(P.newId),C===void 0&&(u=P.newId)}let f=ot(i),p=new Set(d.map(String));Tn(i,f,p,o,c);for(let g of d)c.add(String(g));let A=[];for(let g of e.links){let C=l.get(g.source),y=l.get(g.target);if(C===void 0||y===void 0)continue;let m={kind:"create",source:C,target:y,type:g.type,lag:ft(g.lag,s.hoursPerDay)},_=Lt(m,{port:i,newLinkId:n.linkIdGen.next});A.push({op:m,finalLinkId:_.applied?_.linkId:null,rejected:_.applied?null:_.rejected??"link_op_rejected"})}let{scheduledIds:I,scheduledBeforeImages:S}=await j({adapter:i,scheduler:r,sector:n.sector},{action:e,autoscheduleFrom:d[0]??null,recomputeParentsFrom:d,now:n.now,options:t}),T=Fn(A,new Map,i);return{ok:!0,changes:G(i,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:I,scheduledBeforeImages:new Map([...S].filter(([g])=>!p.has(String(g)))),links:T,hoursPerDay:s.hoursPerDay})}}function Go(e,t){let{adapter:n}=t,i=e.activityId,r=n.getActivity(i);if(!r)return{ok:!1,reason:E.ACTIVITY_NOT_FOUND};let s=r.pendingRequests??[],a=e.pendingRequests.map(c=>({id:c.id}));return n.setActivityField(e.activityId,"pendingRequests",a),{ok:!0,changes:{source:e,activities:[{id:i,kind:"updated",fields:{pendingRequests:{before:s,after:a}},after:{id:i,pendingRequests:a}}],links:[],calendars:[],trackingEvents:[]}}}function Et(e,t){cr(e,t),lr(e,t),dr(e,t)}function Ko(e,t){let n=new Set,i=[];for(let r of e){let s=String(r);n.has(s)||(n.add(s),i.push(s))}for(;i.length>0;){let r=i.pop(),s=t.getChildren(r);for(let a of s){let o=String(a);n.has(o)||(n.add(o),i.push(o))}}return n}function qo(e,t){let n=[];for(let i of t.getAllLinks()){let r=String(i.source),s=String(i.target);(e.has(r)||e.has(s))&&n.push(String(i.id))}return n}function ge(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,n={type:Ce,$no_start:!1,$no_end:!1,$rendered_type:void 0,originalMetadata:void 0};if(e.idsRemoved&&e.idsRemoved.size>0){let r=Array.isArray(t.newActivitiesArray)?t.newActivitiesArray:[];if(r.length>0){let s=r.filter(a=>!e.idsRemoved.has(a)&&!e.idsRemoved.has(String(a)));s.length!==r.length&&(n.newActivitiesArray=s)}}let i=t.tasks;return Array.isArray(i)&&i.length>0&&(n.is_lookahead=!0),{parentId:String(t.id),fields:n}}function zo(e){if(e.idsRemoved.size===0)return null;let t=e.parent.newActivitiesArray;if(!Array.isArray(t)||t.length===0)return null;let n=t,i=n.filter(r=>!e.idsRemoved.has(r)&&!e.idsRemoved.has(String(r)));return i.length===n.length?null:{parentId:String(e.parent.id),fields:{newActivitiesArray:[...i],hasNewActivities:i.length>0}}}async function Jo(e,t,n){let{adapter:i,scheduler:r,customIdTracker:s,sector:a}=n;if(r.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:E.ACTIVITY_IDS_EMPTY};for(let C of e.activityIds)if(!i.getActivity(C))return{ok:!1,reason:E.ACTIVITY_NOT_FOUND};let o=Ko(e.activityIds,i),c=qo(o,i),l=new Set;for(let C of e.activityIds){let y=i.getActivity(C);if(!y)continue;let m=y.parent;if(b(m))continue;let _=String(m);o.has(_)||l.add(_)}let d=new Set([...o,...l]),u=K(i,d),f=new Map;for(let C of c){let y=i.getLink(C);y&&f.set(C,{...y})}for(let C of o){let y=i.getActivity(C);if(!y)continue;let m=y.custom_id;typeof m=="string"&&m.length>0&&s.releaseCustomId(m)}for(let C of c)i.removeLink(C);for(let C of o)i.removeActivity(C);for(let C of l){let y=i.getActivity(C);if(!y)continue;let m=zo({parent:y,idsRemoved:o});if(m)for(let[_,P]of Object.entries(m.fields))V(i,C,_,P)}for(let C of l){let y=i.getActivity(C);if(!y)continue;let m=i.getChildren(C),_=ge({parent:y,remainingChildIds:m.map(String),idsRemoved:o});if(!_){gn(C,i);continue}for(let[P,D]of Object.entries(_.fields))V(i,C,P,D)}for(let C of l)Et(C,i);let p=ot(i);for(let C of p){if(d.add(C.activityId),u.has(C.activityId))continue;let y=i.getActivity(C.activityId);if(!y)continue;let m=Z(y);m.correlative_id=C.before,u.set(C.activityId,m)}let{scheduledIds:A,scheduledBeforeImages:I}=await j({adapter:i,scheduler:r,sector:n.sector},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:l,now:n.now,options:t}),S={name:ht.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:o.size}};e.eventSource!==void 0&&(S.properties.event_source=e.eventSource);let T=new Map;for(let[C,y]of f)T.set(C,y);let g=new Map;for(let C of o){let y=u.get(String(C));y&&g.set(String(C),y)}return{ok:!0,changes:G(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:A,scheduledBeforeImages:I,sirDetection:"after-diff",links:mp(f),trackingEvents:[S],hoursPerDay:a.hoursPerDay}),__beforeSnap:g,__beforeLinks:T}}function mp(e){let t=[];for(let[n,i]of e.entries())t.push({id:n,kind:"deleted",fields:{source:{before:String(i.source),after:void 0},target:{before:String(i.target),after:void 0},type:{before:i.type,after:void 0},lag:{before:Number(i.lag),after:void 0}},after:null});return t}function jn(e,t){let n=new Set;for(let r of e)n.add(String(r));let i=[];for(let r of t.getAllLinks()){let s=String(r.source),a=String(r.target);!n.has(s)&&!n.has(a)||(Xo(a,s,t)||Xo(s,a,t))&&i.push(String(r.id))}return i}function Xo(e,t,n){let i=String(e),r=new Set;for(;i!=null;){if(r.has(i))return!1;r.add(i);let s=n.getActivity(i);if(!s)return!1;let a=s.parent;if(b(a))return!1;let o=String(a);if(o===t)return!0;i=o}return!1}async function Zo(e,t,n){let{adapter:i,scheduler:r,sector:s}=n;r.invalidateAllCaches();let a=i.getActivity(e.activityId);if(!a)return{ok:!1,reason:E.ACTIVITY_NOT_FOUND};let o=b(e.parentId);if(!o&&!i.getActivity(e.parentId))return{ok:!1,reason:E.PARENT_NOT_FOUND};if(!o&&(e.parentId===e.activityId||i.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:E.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0){let y=i.getActivity(e.afterSiblingId);if(!y)return{ok:!1,reason:E.ANCHOR_SIBLING_NOT_FOUND};if((y.parent==null||y.parent===0?"0":String(y.parent))!==e.parentId)return{ok:!1,reason:E.ANCHOR_SIBLING_WRONG_PARENT}}let c=a.parent,l=_t(c),d=String(e.parentId),u=l!==d,f=new Set([e.activityId]);u?(l!=="0"&&f.add(l),d!=="0"&&f.add(d)):l!=="0"&&f.add(l);let p=K(i,f);u&&i.setActivityField(e.activityId,tt.PARENT,d);let A=Un(i,e.parentId,e.afterSiblingId,void 0);if(i.setActivityField(e.activityId,v.CORRELATIVE_ID,A),u){if(!o){let y=i.getActivity(e.parentId);if(y){let m=y.custom_id,_=Rt(y.type)&&i.getChildren(e.parentId).filter(D=>D!==e.activityId).length===0,P=me({parentId:e.parentId,newChildId:e.activityId,getParent:D=>i.getActivity(D)??null,isCurrentlyLeaf:_,promotionSource:"reparent"});if(P){for(let[D,R]of Object.entries(P.fields))V(i,P.parentId,D,R);P.fields.custom_id===null&&Mn(m,n.customIdTracker)}}}if(l!=="0"){let y=i.getActivity(l);if(y){let m=i.getChildren(l),_=ge({parent:y,remainingChildIds:m.map(String),idsRemoved:new Set([e.activityId])});if(_){for(let[W,H]of Object.entries(_.fields))V(i,l,W,H);let P=ye(l,i),D=P?i.getActivity(P)?.custom_id:null,R=typeof D=="string"&&D?D:null,U=n.customIdTracker.generateCustomIdForRestoredChild(R);i.setActivityField(l,v.CUSTOM_ID,U)}}}}u&&(l!=="0"&&Et(l,i),o||Et(e.parentId,i));let I=ot(i);for(let y of I){if(f.add(y.activityId),p.has(y.activityId))continue;let m=i.getActivity(y.activityId);if(!m)continue;let _=Z(m);_.correlative_id=y.before,p.set(y.activityId,_)}let{scheduledIds:S,scheduledBeforeImages:T}=await j({adapter:i,scheduler:r,sector:n.sector},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId],now:n.now,options:t}),g=u?jn([e.activityId],i):[],C={name:ht.ACTIVITY_MOVE,properties:{activity_id:e.activityId,new_parent_id:e.parentId,after_sibling_id:e.afterSiblingId??null,invalid_link_ids:g.map(String)}};return e.eventSource!==void 0&&(C.properties.event_source=e.eventSource),{ok:!0,changes:G(i,{source:e,beforeSnap:p,touchedIds:f,scheduledIds:S,scheduledBeforeImages:T,sirDetection:"before-diff",trackingEvents:[C],hoursPerDay:s.hoursPerDay})}}async function Qo(e,t,n){let{adapter:i,scheduler:r,sector:s}=n;if(r.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:E.ACTIVITY_IDS_EMPTY};let a=new Set(e.activityIds),o=new Set,c=[],l=[],d=[],u=new Set(a),f=[...e.activityIds].sort((m,_)=>{let P=i.getActivity(m),D=i.getActivity(_),R=P?st(P):zt,U=D?st(D):zt;return R-U});for(let m of f){if(!i.getActivity(m)){c.push({activityId:m,reason:E.ACTIVITY_NOT_FOUND}),u.delete(m);continue}let P=Ba(m,u,i);if(P==null){c.push({activityId:m,reason:E.INDENT_NO_ELIGIBLE_SIBLING}),u.delete(m);continue}let D=i.getActivity(m)?.parent,R=D==null||D===0?"0":String(D);d.push({activityId:m,newParentId:P,oldParentId:R}),o.add(m),o.add(P),R!=="0"&&o.add(R)}let p=K(i,o);for(let{activityId:m,newParentId:_}of d)i.setActivityField(m,tt.PARENT,_),i.setActivityField(m,v.CORRELATIVE_ID,Uo),l.push(m);let A=new Set;for(let{activityId:m,newParentId:_}of d){if(A.has(_))continue;A.add(_);let P=i.getActivity(_);if(!P)continue;let D=P.custom_id,R=P.constraint_type??"asap",U=Rt(P.type)&&i.getChildren(_).filter(H=>!l.includes(H)).length===0,W=me({parentId:_,newChildId:m,getParent:H=>i.getActivity(H)??null,isCurrentlyLeaf:U,promotionSource:"reparent"});if(W){for(let[H,et]of Object.entries(W.fields))V(i,W.parentId,H,et);i.setActivityField(_,tt.HAS_NEW_ACTIVITIES,!1),i.setActivityField(_,tt.NEW_ACTIVITIES_ARRAY,[])}i.setActivityField(_,v.CONSTRAINT_TYPE,"asap"),i.setActivityField(_,v.CONSTRAINT_DATE,null),i.setActivityField(_,Wt,R),i.setActivityField(_,v.CUSTOM_ID,null),Mn(D,n.customIdTracker)}let I=new Set;for(let m of d)m.oldParentId!=="0"&&I.add(m.oldParentId),I.add(m.newParentId);for(let m of I)Et(m,i);let S=ot(i);for(let m of S){if(o.add(m.activityId),p.has(m.activityId))continue;let _=i.getActivity(m.activityId);if(!_)continue;let P=Z(_);P.correlative_id=m.before,p.set(m.activityId,P)}let{scheduledIds:T,scheduledBeforeImages:g}=await j({adapter:i,scheduler:r,sector:n.sector},{action:e,autoscheduleFrom:null,recomputeParentsFrom:l,now:n.now,options:t}),C=jn(l,i),y={name:ht.ACTIVITY_INDENT,properties:{activity_ids:l,failed:c.map(m=>({activity_id:m.activityId,reason:m.reason})),invalid_link_ids:C}};return e.eventSource!==void 0&&(y.properties.event_source=e.eventSource),{ok:!0,changes:G(i,{source:e,beforeSnap:p,touchedIds:o,scheduledIds:T,scheduledBeforeImages:g,trackingEvents:[y],hoursPerDay:s.hoursPerDay})}}async function tc(e,t,n){let{adapter:i,scheduler:r,sector:s}=n;if(r.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:E.ACTIVITY_IDS_EMPTY};let a=new Set(e.activityIds),o=new Map,c=new Map;for(let m of e.activityIds){let _=m;i.getActivity(_)&&(o.set(_,xi(_,i)),c.set(_,Bo(_,a,i)))}let l=new Set,d=[],u=[],f=new Set,p=[],A=[...e.activityIds].sort((m,_)=>{let P=i.getActivity(m),D=i.getActivity(_),R=P?st(P):zt,U=D?st(D):zt;return R-U});for(let m of A){let _=m,P=i.getActivity(_);if(!P){d.push({activityId:_,reason:E.ACTIVITY_NOT_FOUND});continue}let D=P.parent;if(b(D)){d.push({activityId:_,reason:E.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let R=String(D),U=i.getActivity(R);if(!U){d.push({activityId:_,reason:E.ACTIVITY_NOT_FOUND});continue}let W=U.parent;if(b(W)){d.push({activityId:_,reason:E.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let H=String(W),et=xi(R,i)+1,ct=c.get(_);if(ct!=null&&a.has(ct)){let Be=o.get(ct)??-1,Mt=o.get(_)??-1;Be>=0&&Mt>=0&&(et+=Mt-Be)}p.push({activityId:_,grandparentKey:H,oldParentKey:R,targetIndexInGrandparent:et}),l.add(String(_)),l.add(String(R)),H!=="0"&&l.add(String(H)),f.add(R)}let I=K(i,l);for(let m of p){i.setActivityField(m.activityId,tt.PARENT,m.grandparentKey);let _=jo(i,m.grandparentKey,m.targetIndexInGrandparent,m.activityId);i.setActivityField(m.activityId,v.CORRELATIVE_ID,_),u.push(m.activityId)}for(let m of f){let _=i.getActivity(m);if(!_)continue;let P=i.getChildren(m),D=ge({parent:_,remainingChildIds:P.map(String),idsRemoved:new Set(u)});if(!D){gn(m,i);continue}for(let[et,ct]of Object.entries(D.fields))V(i,m,et,ct);let R=ye(m,i),U=R?i.getActivity(R)?.custom_id:null,W=typeof U=="string"&&U?U:null,H=n.customIdTracker.generateCustomIdForRestoredChild(W);i.setActivityField(m,v.CUSTOM_ID,H)}let S=new Set;for(let m of f)S.add(String(m));for(let m of p)m.grandparentKey!=="0"&&S.add(String(m.grandparentKey));for(let m of S)Et(m,i);let T=ot(i);for(let m of T){if(l.add(m.activityId),I.has(m.activityId))continue;let _=i.getActivity(m.activityId);if(!_)continue;let P=Z(_);P.correlative_id=m.before,I.set(m.activityId,P)}let{scheduledIds:g,scheduledBeforeImages:C}=await j({adapter:i,scheduler:r,sector:n.sector},{action:e,autoscheduleFrom:u.length>0?"roots":null,recomputeParentsFrom:u,now:n.now,options:t}),y={name:ht.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(m=>({activity_id:String(m.activityId),reason:m.reason}))}};return e.eventSource!==void 0&&(y.properties.event_source=e.eventSource),{ok:!0,changes:G(i,{source:e,beforeSnap:I,touchedIds:l,scheduledIds:g,scheduledBeforeImages:C,trackingEvents:[y],hoursPerDay:s.hoursPerDay})}}async function ec(e,t,n){let{adapter:i,ctx:r,scheduler:s,sector:a}=n;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:E.INVALID_PROGRESS_VALUE};let o=r.activityReader.getActivity(e.activityId);if(!o)return{ok:!1,reason:E.ACTIVITY_NOT_FOUND};let c=wt(v.PROGRESS);if(!c)throw new Error("[ScheduleCore] progressPipeline not registered \u2014 cannot dispatch activity-set-progress");let l=c.transform(o,e.newValue,r,e.newValue),d=Nt(e.activityId,l),u=K(i,d);xt(i,e.activityId,v.PROGRESS,l),Ot(e.activityId,l.postProcessors??[],i);let{scheduledIds:f}=await j({adapter:i,scheduler:s,sector:n.sector},{action:e,autoscheduleFrom:l.needsAutoSchedule?e.activityId:null,recomputeParentsFrom:[],collectDirty:A=>In(e.activityId,d,A),now:n.now,options:t}),p=(l.trackingEvents??[]).map(A=>({name:A.name,properties:A.properties??{}}));return{ok:!0,changes:G(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:f,trackingEvents:p,hoursPerDay:a.hoursPerDay})}}async function nc(e,t,n){let{adapter:i,scheduler:r,sector:s}=n,a=[],o=new Map,c=new Set,l=[],d=[],u=[],f=!1;for(let A of e.edits){let I=yp(A,n);if(a.push(I.verdict),!I.verdict.ok||!I.changes)continue;let S=Nt(A.activityId,I.changes);gp(o,S,n);for(let C of S)c.add(C);let T=pe(i,A.activityId);xt(i,A.activityId,A.column,I.changes),Ot(A.activityId,I.changes.postProcessors??[],i),d.push(...he(T,i,A.activityId)),f||=!!I.changes.needsAutoSchedule;for(let C of I.changes.trackingEvents??[])l.push({name:C.name,properties:C.properties??{}});let g=ue(A.activityId,I.changes.constraintWarning);g&&u.push(g)}let{scheduledIds:p}=await j({adapter:i,scheduler:r,sector:n.sector},{action:e,autoscheduleFrom:f?"roots":null,recomputeParentsFrom:c,now:n.now,options:t});return{ok:!0,verdicts:a,changes:G(i,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:p,sirDetection:"before-diff",links:d,trackingEvents:l,warnings:u,hoursPerDay:s.hoursPerDay})}}function yp(e,t){let{ctx:n}=t,i=e.activityId,r=wt(e.column);if(!r)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);let s=n.activityReader.getActivity(e.activityId);if(!s)throw new Error(`[ScheduleCore] activity "${e.activityId}" not found`);let a=r.canEdit(s);if(!a.allowed)return{verdict:{activityId:i,ok:!1,reason:a.reason??E.CANNOT_EDIT,...a.alertKey?{alertKey:a.alertKey}:{}},changes:null};let o=r.parseInput(e.newValue,s,n);if(!o.ok)return{verdict:{activityId:i,ok:!1,reason:o.reason??E.PARSE_ERROR},changes:null};let c=Reflect.get(s,e.column),l=r.validate(s,c,o.value,n);if(!l.valid)return{verdict:{activityId:i,ok:!1,reason:l.reason??E.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};let d=r.transform(s,o.value,n,o.raw);return{verdict:{activityId:i,ok:!0},changes:d}}function gp(e,t,n){let i=new Set;for(let r of t)e.has(r)||i.add(r);if(i.size!==0)for(let[r,s]of K(n.adapter,i))e.set(r,s)}var fr=v.CUSTOM_ID;async function ic(e,t,n){let{adapter:i,scheduler:r,sector:s}=n;e.edits.some(C=>C.column===v.DURATION)&&r.invalidateExpandedLinksCache();let o=[],c=new Map,l=new Map,d=new Set,u=[],f=[],p=[],A=!1;for(let C of e.edits){let y=vp(C,n);if(o.push(y.verdict),!y.verdict.ok||!y.changes)continue;let m=ue(C.activityId,y.changes.constraintWarning);m&&p.push(m);let _=Nt(C.activityId,y.changes);_p(c,_,n);for(let R of _)d.add(R);Sp(l,C,c);let P=pe(i,C.activityId),D=Ap(C,n);xt(i,C.activityId,C.column,y.changes),Ot(C.activityId,y.changes.postProcessors??[],i),Cp(C,D,n),f.push(...he(P,i,C.activityId)),A||=!!y.changes.needsAutoSchedule;for(let R of y.changes.trackingEvents??[])u.push({name:R.name,properties:R.properties??{}})}let I={action:e,autoscheduleFrom:A?"roots":null,recomputeParentsFrom:d,now:n.now,options:t},S=l.size>0,{scheduledIds:T,scheduledBeforeImages:g}=await(S?xn({adapter:i,scheduler:r,sector:s},{postMutationArgs:I,revertTargets:[...l].map(([C,y])=>({activityId:C,priorConstraintDate:y})),revert:(C,y)=>Nn(C,y,i,n.ctx.calendars)}):j({adapter:i,scheduler:r,sector:s},I));return{ok:!0,verdicts:o,changes:G(i,{source:e,beforeSnap:c,touchedIds:d,scheduledIds:T,scheduledBeforeImages:g,sirDetection:"before-diff",links:f,trackingEvents:u,warnings:p,hoursPerDay:s.hoursPerDay})}}function vp(e,t){let{ctx:n}=t,i=e.activityId,r=wt(e.column);if(!r)return{verdict:{activityId:i,ok:!1,reason:E.NO_PIPELINE_FOR_COLUMN},changes:null};let s=n.activityReader.getActivity(e.activityId);if(!s)return{verdict:{activityId:i,ok:!1,reason:E.ACTIVITY_NOT_FOUND},changes:null};let a=r.canEdit(s);if(!a.allowed)return{verdict:{activityId:i,ok:!1,reason:a.reason??E.CANNOT_EDIT,...a.alertKey?{alertKey:a.alertKey}:{}},changes:null};let o=r.parseInput(e.newValue,s,n);if(!o.ok)return{verdict:{activityId:i,ok:!1,reason:o.reason??E.PARSE_ERROR},changes:null};let c=Reflect.get(s,e.column),l=r.validate(s,c,o.value,n);if(!l.valid)return{verdict:{activityId:i,ok:!1,reason:l.reason??E.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};if(e.column===fr&&o.value!==null){let u=t.adapter.getActivity(e.activityId),f=u?u.custom_id:null,p=typeof f=="string"?f:null;if(t.customIdTracker.isCustomIdInUse(String(o.value),p))return{verdict:{activityId:i,ok:!1,reason:E.CUSTOM_ID_DUPLICATE},changes:null}}let d=r.transform(s,o.value,n,o.raw);return{verdict:{activityId:i,ok:!0},changes:d}}function Ap(e,t){if(e.column!==fr)return null;let n=t.adapter.getActivity(e.activityId),i=n?n.custom_id:null;return typeof i=="string"?i:null}function Cp(e,t,n){if(e.column!==fr)return;let i=n.adapter.getActivity(e.activityId),r=i?i.custom_id:null,s=typeof r=="string"?r:null;t!==s&&n.customIdTracker.trackCustomIdChange(t,s)}function Sp(e,t,n){if(!wn(t.column))return;let i=String(t.activityId);if(e.has(i))return;let r=n.get(i);r&&e.set(i,r.constraint_date??null)}function _p(e,t,n){let i=new Set;for(let r of t)e.has(r)||i.add(r);if(i.size!==0)for(let[r,s]of K(n.adapter,i))e.set(r,s)}async function rc(e,t,n){return e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?Po(e,t,n):e.kind==="links-batch"?Ro(e,t,n):e.kind==="activity-create"?Yo(e,t,n):e.kind==="activity-paste"?Vo(e,t,n):e.kind==="activity-delete"?Jo(e,t,n):e.kind==="activity-move"?Zo(e,t,n):e.kind==="activity-indent"?Qo(e,t,n):e.kind==="activity-outdent"?tc(e,t,n):e.kind==="activity-set-progress"?ec(e,t,n):e.kind==="dates-batch"?nc(e,t,n):e.kind==="bulk-edit"?ic(e,t,n):e.kind==="selection-toggle"?jr(e,pr(n)):e.kind==="selection-replace"?Hr(e,pr(n)):e.kind==="visibility-set"?$r(e,pr(n)):e.kind==="sir-sync"?Go(e,n):e.kind==="inline-edit"&&(e.column===v.CUSTOM_PREDECESSORS||e.column===v.CUSTOM_SUCESSORS)?Lo(e,t,n):e.kind!=="inline-edit"?Cs(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):Eo(e,t,n)}function pr(e){return{adapter:e.adapter}}function hr(e,t,n){return n==="hours"?e:Ri(e,t)}function kp(e,t,n){return n==="hours"?e:ke(e,t)}function mt(e,t,n){return n==="hours"?e:{...e,duration:Ri(e.duration,t)}}function Hn(e,t,n){return n==="hours"?e:{...e,lag:ke(e.lag,t)}}function xe(e,t,n){return n==="hours"?e:{...e,activities:e.activities.map(i=>({...i,after:i.after?mt(i.after,t,n):i.after,fields:sc(i.fields,v.DURATION,t,n,hr)})),links:e.links.map(i=>({...i,after:i.after?Hn(i.after,t,n):i.after,fields:sc(i.fields,"lag",t,n,kp)}))}}function sc(e,t,n,i,r){if(!e||!(t in e))return e;let s=e[t];return s?{...e,[t]:{before:typeof s.before=="number"?r(s.before,n,i):s.before,after:typeof s.after=="number"?r(s.after,n,i):s.after}}:e}function ac(e,t,n,i="days"){let r=e.getActivity(n);return r?mt(X(r),t,i):null}function oc(e,t,n="days"){return e.getAllActivities().map(i=>mt(X(i),t,n))}function cc(e){return e.getAllIds().map(String)}function lc(e,t){e.forEachActivity((n,i)=>t(i))}function dc(e,t,n,i="days"){let r=n==="0"?mr(e,"0"):e.getChildren(n),s=[];for(let a of r){let o=e.getActivity(a);o&&s.push(mt(X(o),t,i))}return s.sort((a,o)=>Number(a.correlative_id??0)-Number(o.correlative_id??0)),s}function mr(e,t){let n=t;if(n==="0"){let i=[];return e.forEachActivity((r,s)=>{b(r.parent)&&i.push(s)}),i}return[...e.getChildren(n)].map(String)}function uc(e){return He(e)}function fc(e,t){return e.getChildren(t).length>0}function pc(e,t,n,i="days"){let r=e.getLink(n);return r?Hn(gt(r),t,i):null}function hc(e,t,n="days"){return e.getAllLinks().map(i=>Hn(gt(i),t,n))}function mc(e,t,n){if(!e||e==="0")return;let i=n.getChildren(e);if(i.length===0)return;let r=new Map,s=0;for(let o of i){let c=Ip(String(o),t,n);r.set(String(o),c),s+=c}let a=s?100/s:0;for(let o of i){let c=n.getActivity(o);if(!c)continue;let l=c.baseline_points;if(Ct(c)){let u=r.get(String(o))??0;n.setActivityField(o,v.PONDERATOR,a*u)}else(!Array.isArray(l)||l.length===0)&&n.setActivityField(o,v.PONDERATOR,0)}}function Ip(e,t,n){let i=n.getActivity(e);if(!i)return 0;let r=Ct(i);if(!r)return 0;if(t==="COST")return $n(r.cost);if(t==="HH")return $n(r.hh_work);let s=i.type;return s==="project"?yc(e,n):s==="milestone"?0:$n(r.duration)}function yc(e,t){let n=0;for(let i of t.getChildren(e)){let r=t.getActivity(i);if(!r)continue;let s=Ct(r);if(!s)continue;let a=r.type;a==="project"?n+=yc(String(i),t):a!=="milestone"&&(n+=$n(s.duration))}return n}function $n(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function Yn(e,t){t.forEachActivity((n,i)=>{t.setActivityField(i,v.PONDERATOR,0)}),t.forEachActivity((n,i)=>{t.getChildren(i).length>0&&mc(String(i),e,t)})}function Vn(e){for(let t of Tp(e))Ep(t,e)}function Tp(e){let t=new Set;e.forEachActivity((i,r)=>{e.getChildren(r).length>0&&t.add(r)});let n=new Map;for(let i of t)n.set(i,Dp(i,e));return[...t].sort((i,r)=>(n.get(r)??0)-(n.get(i)??0))}function Dp(e,t){let n=0,i=e;for(;i&&i!=="0"&&t.getActivity(i);)n+=1,i=t.getParentId(i);return n}function Ep(e,t){let n=t.getChildren(e);if(n.length===0)return;let i=[];for(let o of n){let c=t.getActivity(o);c&&i.push({progress:Number(c.progress??0),ponderator:Number(c.ponderator??0)})}let r=ie(i),a=t.getActivity(e)?.duration;a!==void 0&&t.setActivityField(e,"for_disable_milestone_duration",a),r!==null&&t.setActivityField(e,v.PROGRESS,yn(r))}var Pp=e=>e.type==="project",Rp=e=>{let t=e.baseline_points;return Array.isArray(t)?t.find(n=>n?.sectorbaselineversion?.active)??null:null},Lp=(e,t,n,i)=>{let r=Rp(e);if(!r)return 0;let s=(r.baseCalendarId!=null?n.getBaseCalendar(`${r.baseCalendarId}-base`):null)??(i?n.getBaseCalendar(i):null);return s?fe(At(String(r.start_date)),At(String(r.end_date)),t,s):0};function yr(e,t,n,i=null){let r=[],s=(o,c)=>{let l=n.getActivity(o);l&&l.expected_progress_base!==c&&(n.setActivityField(o,v.EXPECTED_PROGRESS_BASE,c),r.push(o))},a=o=>{let c=n.getActivity(o);if(!c)return 0;if(!Pp(c)){let u=Lp(c,t,n,i);return s(o,u),u}let l=0;for(let u of n.getChildrenIds(o)){let f=a(u),p=n.getActivity(u),A=typeof p?.ponderator=="number"?p.ponderator:0;l+=f*A}let d=l/100;return s(o,d),d};for(let o of e)a(o);return r}function gc(e,t,n=null){let i={getChildrenIds:s=>e.getChildren(String(s)).map(a=>String(a)),getActivity:s=>e.getActivity(s),setActivityField:(s,a,o)=>V(e,s,a,o),getBaseCalendar:s=>e.calendarReader.getCalendar(s)},r=[];return e.forEachActivity((s,a)=>{(s.parent===0||s.parent==="0"||s.parent==null)&&r.push(a)}),yr(r,t,i,n)}function Gn(e,t){let n=new Map;e.forEachActivity((s,a)=>{let o=s.proplannerId;typeof o=="number"&&n.set(o,a)});let i=new Map;for(let s of t){let a=s.activityId;if(typeof a!="number")continue;let o=n.get(a);if(o===void 0)continue;let c=i.get(o);c?c.push(s):i.set(o,[s])}let r=[];for(let[s,a]of i)e.setActivityField(s,"baseline_points",a),r.push(s);return e.forEachActivity((s,a)=>{if(i.has(a))return;let o=s.baseline_points;Array.isArray(o)&&o.length>0&&(e.setActivityField(a,"baseline_points",[]),r.push(a))}),r}var vc=e=>({[Ke]:e.start_date});var Ac=e=>({[qe]:e.end_date});var Cc=e=>({[ze]:e.duration});var Sc=e=>({[Je]:e.cost});var _c=e=>({[Xe]:e.hh_work});function kc(e){let t=[];return e.forEachActivity((n,i)=>{let r=Ct(n);if(!r)return;let s={...vc(r),...Ac(r),...Cc(r),...Sc(r),..._c(r)};for(let[a,o]of Object.entries(s))V(e,i,a,o);t.push(i)}),t}function Kn(e,t,n,i=null){if(t.length===0)return[];let r=new Set;for(let s of Gn(e,t))r.add(s);if(n)for(let s of gc(e,n,i))r.add(s);for(let s of kc(e))r.add(s);for(let s of On(e))r.add(s);return[...r]}function Ic(e){let t=e.ponderator;return typeof t=="number"&&Number.isFinite(t)?t:0}function Tc(e){let t=e.progress;return typeof t=="number"&&Number.isFinite(t)?t:0}function Dc(e,t,n){let i=new Map;e.forEachActivity((s,a)=>{i.set(a,Ic(s))}),Yn(n,e);let r=[];return e.forEachActivity((s,a)=>{Ic(s)!==(i.get(a)??0)&&r.push(mt(X(s),t,"days"))}),r}function Ec(e,t){let n=new Map;e.forEachActivity((r,s)=>{n.set(s,Tc(r))}),Vn(e);let i=[];return e.forEachActivity((r,s)=>{Tc(r)!==(n.get(s)??0)&&i.push(mt(X(r),t,"days"))}),i}function Pc(e,t,n,i,r=null){let s=Kn(e,n,i,r),a=[];for(let o of s){let c=e.getActivity(o);c&&a.push(mt(X(c),t,"days"))}return a}function Rc(e,t,n){let i=[];for(let r of Gt(e,n)){let s=e.getActivity(r);s&&i.push(mt(X(s),t,"days"))}return i}function qn(e){let[t,n]=e.split(":");return Number(t)*60+Number(n??0)}function bp(e){return e.reduce((t,n)=>qn(n)<qn(t)?n:t)}function Op(e){return e.reduce((t,n)=>qn(n)>qn(t)?n:t)}function wp(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function Lc(e){let t=[...e].find(s=>s.is_default);if(!t)return null;let n=wp(t);if(n.length===0)return null;let i=n.map(s=>s.split("-")[0]),r=n.map(s=>s.split("-")[1]);return{startHour:bp(i),endHour:Op(r)}}function bc(e,t={}){let n=t.defaultUnit??"hour";return{getCalendar(i){let r=e.getCalendar(String(i));return r?Np(r,n):null}}}function Np(e,t){return{getClosestWorkTime(n){return e.getClosestWorkTime({date:n.date,dir:n.direction,unit:n.unit})},calculateEndDate(n,i){return e.calculateEndDate({start_date:n,duration:i,unit:t})},calculateDuration(n,i){return e.calculateDuration({start_date:n,end_date:i,unit:t})},isWorkTime(n,i){return e.isWorkTime({date:n,unit:i})},getWorkHours(n){return e.getWorkHours(n)}}}function xp(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function Jt(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function Xt(e){return Jt(e)&&!isNaN(e.getTime())}var Fp={}.constructor.toString();function Mp(e){var t=e.constructor.toString();return t!==Fp}function Wp(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function vt(e){var t,n;if(e&&typeof e=="object")switch(!0){case Jt(e):n=new Date(e);break;case xp(e):for(n=new Array(e.length),t=0;t<e.length;t++)n[t]=vt(e[t]);break;default:if(Mp(e))n=Object.create(e);else{if(Wp(e))return n=e,n;n={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(n[t]=vt(e[t]));break}return n||e}function ve(e,t,n){for(var i in t)(e[i]===void 0||n)&&(e[i]=t[i]);return e}function Oc(e){return typeof e<"u"}var zn;function gr(){return zn||(zn=new Date().valueOf()),zn++,zn}function dt(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var Bp=(e,t,n)=>{e=e.replace(/%[a-zA-Z]/g,r=>{switch(r){case"%d":return`"+to_fixed(date.get${t?"UTC":""}Date())+"`;case"%m":return`"+to_fixed((date.get${t?"UTC":""}Month()+1))+"`;case"%j":return`"+date.get${t?"UTC":""}Date()+"`;case"%n":return`"+(date.get${t?"UTC":""}Month()+1)+"`;case"%y":return`"+to_fixed(date.get${t?"UTC":""}FullYear()%100)+"`;case"%Y":return`"+date.get${t?"UTC":""}FullYear()+"`;case"%D":return`"+locale.date.day_short[date.get${t?"UTC":""}Day()]+"`;case"%l":return`"+locale.date.day_full[date.get${t?"UTC":""}Day()]+"`;case"%M":return`"+locale.date.month_short[date.get${t?"UTC":""}Month()]+"`;case"%F":return`"+locale.date.month_full[date.get${t?"UTC":""}Month()]+"`;case"%h":return`"+to_fixed((date.get${t?"UTC":""}Hours()+11)%12+1)+"`;case"%g":return`"+((date.get${t?"UTC":""}Hours()+11)%12+1)+"`;case"%G":return`"+date.get${t?"UTC":""}Hours()+"`;case"%H":return`"+to_fixed(date.get${t?"UTC":""}Hours())+"`;case"%i":return`"+to_fixed(date.get${t?"UTC":""}Minutes())+"`;case"%a":return`"+(date.get${t?"UTC":""}Hours()>11?"pm":"am")+"`;case"%A":return`"+(date.get${t?"UTC":""}Hours()>11?"PM":"AM")+"`;case"%s":return`"+to_fixed(date.get${t?"UTC":""}Seconds())+"`;case"%W":return'"+to_fixed(getISOWeek(date))+"';case"%w":return'"+to_fixed(getWeek(date))+"';default:return r}});let i=new Function("date","to_fixed","locale","getISOWeek","getWeek",`return "${e}";`);return r=>i(r,n.date.to_fixed,n.locale,n.date.getISOWeek,n.date.getWeek)},jp=(e,t,n)=>{let i="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);",r=e.match(/%[a-zA-Z]/g);for(let o=0;o<r.length;o++)switch(r[o]){case"%j":case"%d":i+=`set[2]=temp[${o}]||1;`;break;case"%n":case"%m":i+=`set[1]=(temp[${o}]||1)-1;`;break;case"%y":i+=`set[0]=temp[${o}]*1+(temp[${o}]>50?1900:2000);`;break;case"%g":case"%G":case"%h":case"%H":i+=`set[3]=temp[${o}]||0;`;break;case"%i":i+=`set[4]=temp[${o}]||0;`;break;case"%Y":i+=`set[0]=temp[${o}]||0;`;break;case"%a":case"%A":i+=`set[3]=set[3]%12+((temp[${o}]||'').toLowerCase()=='am'?0:12);`;break;case"%s":i+=`set[5]=temp[${o}]||0;`;break;case"%M":i+=`set[1]=locale.date.month_short_hash[temp[${o}]]||0;`;break;case"%F":i+=`set[1]=locale.date.month_full_hash[temp[${o}]]||0;`;break}let s="set[0],set[1],set[2],set[3],set[4],set[5]";t&&(s=` Date.UTC(${s})`);let a=new Function("date","locale",`var set=[0,0,1,0,0,0]; ${i} return new Date(${s});`);return o=>a(o,n.locale)},wc={date_to_str:Bp,str_to_date:jp},Hp=(e,t,n)=>i=>e.replace(/%[a-zA-Z]/g,r=>{switch(r){case"%d":return t?n.date.to_fixed(i.getUTCDate()):n.date.to_fixed(i.getDate());case"%m":return t?n.date.to_fixed(i.getUTCMonth()+1):n.date.to_fixed(i.getMonth()+1);case"%j":return t?i.getUTCDate():i.getDate();case"%n":return t?i.getUTCMonth()+1:i.getMonth()+1;case"%y":return t?n.date.to_fixed(i.getUTCFullYear()%100):n.date.to_fixed(i.getFullYear()%100);case"%Y":return t?i.getUTCFullYear():i.getFullYear();case"%D":return t?n.locale.date.day_short[i.getUTCDay()]:n.locale.date.day_short[i.getDay()];case"%l":return t?n.locale.date.day_full[i.getUTCDay()]:n.locale.date.day_full[i.getDay()];case"%M":return t?n.locale.date.month_short[i.getUTCMonth()]:n.locale.date.month_short[i.getMonth()];case"%F":return t?n.locale.date.month_full[i.getUTCMonth()]:n.locale.date.month_full[i.getMonth()];case"%h":return t?n.date.to_fixed((i.getUTCHours()+11)%12+1):n.date.to_fixed((i.getHours()+11)%12+1);case"%g":return t?(i.getUTCHours()+11)%12+1:(i.getHours()+11)%12+1;case"%G":return t?i.getUTCHours():i.getHours();case"%H":return t?n.date.to_fixed(i.getUTCHours()):n.date.to_fixed(i.getHours());case"%i":return t?n.date.to_fixed(i.getUTCMinutes()):n.date.to_fixed(i.getMinutes());case"%a":return t?i.getUTCHours()>11?"pm":"am":i.getHours()>11?"pm":"am";case"%A":return t?i.getUTCHours()>11?"PM":"AM":i.getHours()>11?"PM":"AM";case"%s":return t?n.date.to_fixed(i.getUTCSeconds()):n.date.to_fixed(i.getSeconds());case"%W":return t?n.date.to_fixed(n.date.getUTCISOWeek(i)):n.date.to_fixed(n.date.getISOWeek(i));case"%w":return n.date.to_fixed(n.date.getWeek(i));default:return r}}),$p=(e,t,n)=>i=>{let r=[0,0,1,0,0,0],s=i.match(/[a-zA-Z]+|[0-9]+/g),a=e.match(/%[a-zA-Z]/g);for(let o=0;o<a.length;o++)switch(a[o]){case"%j":case"%d":r[2]=s[o]||1;break;case"%n":case"%m":r[1]=(s[o]||1)-1;break;case"%y":r[0]=s[o]*1+(s[o]>50?1900:2e3);break;case"%g":case"%G":case"%h":case"%H":r[3]=s[o]||0;break;case"%i":r[4]=s[o]||0;break;case"%Y":r[0]=s[o]||0;break;case"%a":case"%A":r[3]=r[3]%12+((s[o]||"").toLowerCase()==="am"?0:12);break;case"%s":r[5]=s[o]||0;break;case"%M":r[1]=n.locale.date.month_short_hash[s[o]]||0;break;case"%F":r[1]=n.locale.date.month_full_hash[s[o]]||0;break}return t?new Date(Date.UTC(r[0],r[1],r[2],r[3],r[4],r[5])):new Date(r[0],r[1],r[2],r[3],r[4],r[5])},Nc={date_to_str:Hp,str_to_date:$p};function xc(e){var t=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function n(o){var c=new Date(o);return isNaN(c.getTime())?null:c}var i=null;function r(){try{new Function("canUseCsp = false;")}catch{i=!0}}function s(){var o=!1;return e.config.csp==="auto"?(i===null&&r(),o=i):o=e.config.csp,o}var a={_isoDateDetected:!1,_isoDateOnly:!1,formatISODate:function(o){return o.toISOString()},formatISODateOnly:function(o){return o.getUTCFullYear()+"-"+e.date.to_fixed(o.getUTCMonth()+1)+"-"+e.date.to_fixed(o.getUTCDate())},init:function(){for(var o=e.locale,l=o.date.month_short,d=o.date.month_short_hash={},c=0;c<l.length;c++)d[l[c]]=c;for(var l=o.date.month_full,d=o.date.month_full_hash={},c=0;c<l.length;c++)d[l[c]]=c},date_part:function(o){return o.setUTCHours(0,0,0,0),o},time_part:function(o){return o.valueOf()/1e3%86400},week_start:function(o){var c=o.getUTCDay();return e.config.start_on_monday&&(c===0?c=6:c--),this.date_part(this.add(o,-1*c,"day"))},month_start:function(o){return o.setUTCDate(1),this.date_part(o)},quarter_start:function(o){this.month_start(o);var c=o.getUTCMonth(),l;return c>=9?l=9:c>=6?l=6:c>=3?l=3:l=0,o.setUTCMonth(l),o},year_start:function(o){return o.setUTCMonth(0),this.month_start(o)},day_start:function(o){return this.date_part(o)},hour_start:function(o){return o.getUTCMinutes()&&o.setUTCMinutes(0),this.minute_start(o),o},minute_start:function(o){return o.getUTCSeconds()&&o.setUTCSeconds(0),o.getUTCMilliseconds()&&o.setUTCMilliseconds(0),o},_add_days:function(o,c,l){return o.setUTCDate(o.getUTCDate()+c),o},add:function(o,c,l){var d=new Date(o.valueOf());switch(l){case"day":d=this._add_days(d,c,o);break;case"week":d=this._add_days(d,c*7,o);break;case"month":d.setUTCMonth(d.getUTCMonth()+c);break;case"year":d.setUTCFullYear(d.getUTCFullYear()+c);break;case"hour":d.setTime(d.getTime()+c*60*60*1e3);break;case"minute":d.setTime(d.getTime()+c*60*1e3);break;default:return this["add_"+l](o,c,l)}return d},add_quarter:function(o,c){return this.add(o,c*3,"month")},to_fixed:function(o){return o<10?"0"+o:o},copy:function(o){return new Date(o.valueOf())},date_to_str:function(o,c){var l=wc;return s()&&(l=Nc),l.date_to_str(o,c,e)},str_to_date:function(o,c){var l=wc;return s()&&(l=Nc),l.str_to_date(o,c,e)},getISOWeek:function(o){return e.date._getWeekNumber(o,!0)},_getWeekNumber:function(o,c){if(!o)return!1;var l=o.getUTCDay();c&&l===0&&(l=7);var d=new Date(o.valueOf());d.setUTCDate(o.getUTCDate()+(4-l));var u=d.getUTCFullYear(),f=Math.round((d.getTime()-Date.UTC(u,0,1))/864e5),p=1+Math.floor(f/7);return p},getWeek:function(o){return e.date._getWeekNumber(o,e.config.start_on_monday)},getUTCISOWeek:function(o){return e.date.getISOWeek(o)},parseDate:function(o,c){if(o&&!o.getFullYear){var l=!c||c==="parse_date"||c==="xml_date",d=l&&(e.defined(e.templates.xml_date)||e.templates.parse_date&&!e.templates.parse_date._ganttAuto);if(!d&&typeof o=="string"&&t.test(o)){var u=o.indexOf("T")!==-1,f=n(o);if(f)return a._isoDateDetected?u&&(a._isoDateOnly=!1):(a._isoDateDetected=!0,a._isoDateOnly=!u),f}typeof c!="function"&&(typeof c=="string"?c==="parse_date"||c==="xml_date"?c=e.defined(e.templates.xml_date)?e.templates.xml_date:e.templates.parse_date:c=e.defined(e.templates[c])?e.templates[c]:e.date.str_to_date(c,!0):c=e.defined(e.templates.xml_date)?e.templates.xml_date:e.templates.parse_date),o?o=c(o):o=null}return o}};return a}function vr(e,t,n,i,r){return this.date=e,this.unit=t,this.task=n,this.id=i,this.calendar=r,this}function Ar(e,t,n,i,r,s){return this.date=e,this.dir=t,this.unit=n,this.task=i,this.id=r,this.calendar=s,this}function Cr(e,t,n,i,r,s,a){return this.start_date=e,this.duration=t,this.unit=n,this.step=i,this.task=r,this.id=s,this.calendar=a,this}function Yp(e,t,n,i){return this.start_date=e,this.end_date=t,this.task=n,this.calendar=i,this.unit=null,this.step=null,this}var Fc=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(Jt(t)?t={date:t}:t=ve({},t),!Xt(t.date))throw e.assert(!1,"Invalid date argument for getWorkHours method"),new Error("Invalid date argument for getWorkHours method");return t},setWorkTimeArguments:function(){return arguments[0]},unsetWorkTimeArguments:function(){return arguments[0]},isWorkTimeArguments:function(){var t=arguments[0];if(t instanceof vr)return t;var n;if(t.date?n=new vr(t.date,t.unit,t.task,null,t.calendar):n=new vr(arguments[0],arguments[1],arguments[2],null,arguments[3]),n.unit=n.unit||e.config.duration_unit,!Xt(n.date))throw e.assert(!1,"Invalid date argument for isWorkTime method"),new Error("Invalid date argument for isWorkTime method");return n},getClosestWorkTimeArguments:function(t){var n=arguments[0];if(n instanceof Ar)return n;var i;if(Jt(n)?i=new Ar(n):i=new Ar(n.date,n.dir,n.unit,n.task,null,n.calendar),n.id&&(i.task=n),i.dir=n.dir||"any",i.unit=n.unit||e.config.duration_unit,!Xt(i.date))throw e.assert(!1,"Invalid date argument for getClosestWorkTime method"),new Error("Invalid date argument for getClosestWorkTime method");return i},_getStartEndConfig:function(t){var n=Yp,i;if(t instanceof n)return t;if(Jt(t)?i=new n(arguments[0],arguments[1],arguments[2],arguments[3]):(i=new n(t.start_date,t.end_date,t.task),t.id!==null&&t.id!==void 0&&(i.task=t)),i.unit=i.unit||e.config.duration_unit,i.step=i.step||e.config.duration_step,i.start_date=i.start_date||i.start||i.date,!Xt(i.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!Xt(i.end_date))throw e.assert(!1,"Invalid end_date argument for getDuration method"),new Error("Invalid end_date argument for getDuration method");return i},getDurationArguments:function(t,n,i,r){return this._getStartEndConfig.apply(this,arguments)},hasDurationArguments:function(t,n,i,r){return this._getStartEndConfig.apply(this,arguments)},calculateEndDateArguments:function(t,n,i,r){var s=arguments[0];if(s instanceof Cr)return s;var a;if(Jt(s)?a=new Cr(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):a=new Cr(s.start_date,s.duration,s.unit,s.step,s.task,null,s.calendar),s.id!==null&&s.id!==void 0&&(a.task=s,a.unit=null,a.step=null),a.unit=a.unit||e.config.duration_unit,a.step=a.step||e.config.duration_step,!Xt(a.start_date))throw e.assert(!1,"Invalid start_date argument for calculateEndDate method"),new Error("Invalid start_date argument for calculateEndDate method");return a}}};function Mc(){}Mc.prototype={_getIntervals:function(e){for(var t=[],n=0;n<e.length;n+=2)t.push({start:e[n],end:e[n+1]});return t},_toHoursArray:function(e){var t=[];function n(s){var a=String(s);return a.length<2&&(a="0"+a),a}function i(s){var a=Math.floor(s/3600),o=s-a*60*60,c=Math.floor(o/60);return a+":"+n(c)}for(var r=0;r<e.length;r++)t.push(i(e[r].start)+"-"+i(e[r].end));return t},_intersectHourRanges:function(e,t){var r=[],n=e.length>t.length?e:t,i=e===n?t:e;n=n.slice(),i=i.slice();for(var r=[],s=0;s<n.length;s++)for(var a=n[s],o=0;o<i.length;o++){var c=i[o];c.start<a.end&&c.end>a.start&&(r.push({start:Math.max(a.start,c.start),end:Math.min(a.end,c.end)}),a.end>c.end&&(i.splice(o,1),o--,s--))}return r},_mergeAdjacentIntervals:function(e){var t=e.slice();t.sort(function(s,a){return s.start-a.start});for(var n=t[0],i=1;i<t.length;i++){var r=t[i];r.start<=n.end?(r.end>n.end&&(n.end=r.end),t.splice(i,1),i--):n=r}return t},_mergeHoursConfig:function(e,t){return this._mergeAdjacentIntervals(this._intersectHourRanges(e,t))},merge:function(e,t){let n=vt(e.getConfig()),i=vt(t.getConfig()),r=n.parsed,s=i.parsed;r.customWeeks=n.customWeeks,s.customWeeks=i.customWeeks;var a={hours:this._toHoursArray(this._mergeHoursConfig(r.hours,s.hours)),dates:{},customWeeks:{}};let o=(l,d)=>{for(let u in l.dates){let f=l.dates[u];+u>1e3&&(a.dates[u]=!1);for(let p in d.dates){let A=d.dates[p];if(p==u&&(a.dates[u]=!!(f&&A)),Array.isArray(f)){let I=Array.isArray(A)?A:d.hours;a.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,I))}}}};if(o(r,s),o(s,r),r.customWeeks)for(var c in r.customWeeks)a.customWeeks[c]=r.customWeeks[c];if(s.customWeeks)for(var c in s.customWeeks)a.customWeeks[c]?a.customWeeks[c+"_second"]=s.customWeeks[c]:a.customWeeks[c]=s.customWeeks[c];return a}};var Sr=class{constructor(){this.clear()}getItem(t,n,i){if(this._cache.has(t)){let s=this._cache.get(t)[i.getUTCFullYear()];if(s&&s.has(n))return s.get(n)}return-1}setItem(t,n,i,r){if(!t||!n)return;let s=this._cache,a=r.getUTCFullYear(),o;s.has(t)?o=s.get(t):(o=[],s.set(t,o));let c=o[a];c||(c=o[a]=new Map),c.set(n,i)}clear(){this._cache=new Map}},_r=class{constructor(){this.clear()}getItem(t,n,i){let r=this._cache;if(r&&r[t]){let s=r[t];if(s===void 0)return-1;let a=s[i.getUTCFullYear()];if(a&&a[n]!==void 0)return a[n]}return-1}setItem(t,n,i,r){if(!t||!n)return;let s=this._cache;if(!s)return;s[t]||(s[t]=[]);let a=s[t],o=r.getUTCFullYear(),c=a[o];c||(c=a[o]={}),c[n]=i}clear(){this._cache={}}},kr=class{constructor(t){this.getMinutesPerWeek=n=>{let i=n.valueOf();if(this._weekCache.has(i))return this._weekCache.get(i);let r=this._calendar,s=this._calendar.$gantt,a=0,o=s.date.week_start(new Date(n));for(let c=0;c<7;c++)a+=r.getHoursPerDay(o)*60,o=s.date.add(o,1,"day");return this._weekCache.set(i,a),a},this.getMinutesPerMonth=n=>{let i=n.valueOf();if(this._monthCache.has(i))return this._monthCache.get(i);let r=this._calendar,s=this._calendar.$gantt,a=0,o=s.date.week_start(new Date(n)),c=s.date.add(o,1,"month").valueOf();for(;o.valueOf()<c;)a+=r.getHoursPerDay(o)*60,o=s.date.add(o,1,"day");return this._monthCache.set(i,a),a},this.clear=()=>{this._weekCache=new Map,this._monthCache=new Map},this.clear(),this._calendar=t}};function Vp(){return typeof Map<"u"?new Sr:new _r}var Ir=class{constructor(){this.clear()}_getCacheObject(t,n,i){let r=this._cache;r[n]||(r[n]=[]);let s=r[n];s||(s=r[n]={});let a=s[i];a||(a=s[i]={});let o=t.getUTCFullYear(),c=a[o];return c||(c=a[o]={durations:{},endDates:{}}),c}_endDateCacheKey(t,n){return String(t)+"-"+String(n)}_durationCacheKey(t,n){return String(t)+"-"+String(n)}getEndDate(t,n,i,r,s){let a=this._getCacheObject(t,i,r),o=t.valueOf(),c=this._endDateCacheKey(o,n),l;if(a.endDates[c]===void 0){let d=s(),u=d.valueOf();a.endDates[c]=u,a.durations[this._durationCacheKey(o,u)]=n,l=d}else l=new Date(a.endDates[c]);return l}getDuration(t,n,i,r,s){let a=this._getCacheObject(t,i,r),o=t.valueOf(),c=n.valueOf(),l=this._durationCacheKey(o,c),d;if(a.durations[l]===void 0){let u=s();a.durations[l]=u.valueOf(),d=u}else d=a.durations[l];return d}clear(){this._cache={}}};function Tr(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=Vp(),this._largeUnitsCache=new kr(this),this._dateDurationCache=new Ir,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}Tr.prototype={units:["year","month","week","day","hour","minute"],_clearCaches:function(){this._workingUnitsCache.clear(),this._largeUnitsCache.clear(),this._dateDurationCache.clear()},_getUnitOrder:function(e){for(var t=0,n=this.units.length;t<n;t++)if(this.units[t]==e)return t},_resetTimestampCache:function(){this._cached_timestamps={},this._cached_timestamps_count=0},_timestamp:function(e){this._cached_timestamps_count>1e6&&this._resetTimestampCache();var t=null;if(e.day||e.day===0)t=e.day;else if(e.date){var n=String(e.date.valueOf());this._cached_timestamps[n]?t=this._cached_timestamps[n]:(t=Date.UTC(e.date.getUTCFullYear(),e.date.getUTCMonth(),e.date.getUTCDate()),this._cached_timestamps[n]=t,this._cached_timestamps_count++)}return t},_checkIfWorkingUnit:function(e,t){if(!this["_is_work_"+t]){let n=this.$gantt.date[`${t}_start`](new Date(e)),i=this.$gantt.date.add(n,1,t);return this.hasDuration(n,i)}return this["_is_work_"+t](e)},_is_work_day:function(e){var t=this._getWorkHours(e);return Array.isArray(t)?t.length>0:!1},_is_work_hour:function(e){for(var t=this._getWorkHours(e),n=e.getUTCHours(),i=0;i<t.length;i++)if(n>=t[i].startHour&&n<t[i].endHour)return!0;return!1},_getTimeOfDayStamp:function(e,t){var n=e.getUTCHours();return!e.getUTCHours()&&!e.getUTCMinutes()&&t&&(n=24),n*60*60+e.getUTCMinutes()*60},_is_work_minute:function(e){for(var t=this._getWorkHours(e),n=this._getTimeOfDayStamp(e),i=0;i<t.length;i++)if(n>=t[i].start&&n<t[i].end)return!0;return!1},_nextDate:function(e,t,n){return this.$gantt.date.add(e,n,t)},_getWorkUnitsBetweenGeneric:function(e,t,n,i){var r=this.$gantt.date,s=new Date(e),a=new Date(t);i=i||1;var o=0,c=null,l,d,u=!1;l=r[n+"_start"](new Date(s)),l.valueOf()!=s.valueOf()&&(u=!0);var f=!1;d=r[n+"_start"](new Date(t)),d.valueOf()!=t.valueOf()&&(f=!0);for(var p=!1;s.valueOf()<a.valueOf();){if(c=this._nextDate(s,n,i),p=c.valueOf()>a.valueOf(),this._isWorkTime(s,n))(u||f&&p)&&(l=r[n+"_start"](new Date(s)),d=r.add(l,i,n)),u?(u=!1,c=this._nextDate(l,n,i),o+=(d.valueOf()-s.valueOf())/(d.valueOf()-l.valueOf())):f&&p?(f=!1,o+=(a.valueOf()-s.valueOf())/(d.valueOf()-l.valueOf())):o++;else{var A=this._getUnitOrder(n),I=this.units[A-1];I&&!this._isWorkTime(s,I)&&(c=this._getClosestWorkTimeFuture(s,I))}s=c}return o},_getMinutesPerHour:function(e){var t=this._getTimeOfDayStamp(e),n=this._getTimeOfDayStamp(this._nextDate(e,"hour",1));n===0&&(n=1440*60);for(var i=this._getWorkHours(e),r=0;r<i.length;r++){var s=i[r];if(t>=s.start&&n<=s.end)return 60;if(t<s.end&&n>s.start){var a=Math.min(n,s.end)-Math.max(t,s.start);return a/60}}return 0},_getMinutesPerDay:function(e){var t=this._getWorkHours(e),n=0;return t.forEach(function(i){n+=i.durationMinutes}),n},getHoursPerDay:function(e){var t=this._getWorkHours(e),n=0;return t.forEach(function(i){n+=i.durationHours}),n},_getWorkUnitsForRange:function(e,t,n,i){var r=0,s=new Date(e),a=new Date(t),o;for(n=="minute"?o=dt(this._getMinutesPerDay,this):o=dt(this.getHoursPerDay,this);s.valueOf()<a.valueOf();){if(a-s>1e3*60*60*24*32&&s.getUTCDate()===0){var c=this._largeUnitsCache.getMinutesPerMonth(s);n=="hour"&&(c=c/60),r+=c,s=this.$gantt.date.add(s,1,"month");continue}else if(a-s>1e3*60*60*24*16){var l=this.$gantt.date.week_start(new Date(s));if(s.valueOf()===l.valueOf()){var c=this._largeUnitsCache.getMinutesPerWeek(s);n=="hour"&&(c=c/60),r+=c,s=this.$gantt.date.add(s,7,"day");continue}}r+=o(s),s=this._nextDate(s,"day",1)}return r/i},_getMinutesBetweenSingleDay:function(e,t){for(var n=this._getIntervalTimestamp(e,t),i=this._getWorkHours(e),r=0,s=0;s<i.length;s++){var a=i[s];if(n.end>=a.start&&n.start<=a.end){var o=Math.max(a.start,n.start),c=Math.min(a.end,n.end);r+=(c-o)/60,n.start=c}}return Math.floor(r)},_getMinutesBetween:function(e,t,n,i){var r=new Date(e),s=new Date(t);i=i||1;var a=new Date(r),o=this.$gantt.date.add(this.$gantt.date.day_start(new Date(r)),1,"day");if(s.valueOf()<=o.valueOf())return this._getMinutesBetweenSingleDay(e,t);var c=this.$gantt.date.day_start(new Date(s)),l=s,d=this._getMinutesBetweenSingleDay(a,o),u=this._getMinutesBetweenSingleDay(c,l),f=this._getWorkUnitsForRange(o,c,n,i),p=d+f+u;return p},_getHoursBetween:function(e,t,n,i){var r=new Date(e),s=new Date(t);i=i||1;var a=new Date(r),o=this.$gantt.date.add(this.$gantt.date.day_start(new Date(r)),1,"day");if(s.valueOf()<=o.valueOf())return Math.round(this._getMinutesBetweenSingleDay(e,t)/60);var c=this.$gantt.date.day_start(new Date(s)),l=s,d=this._getMinutesBetweenSingleDay(a,o,n,i)/60,u=this._getMinutesBetweenSingleDay(c,l,n,i)/60,f=this._getWorkUnitsForRange(o,c,n,i),p=d+f+u;return Math.round(p)},getConfig:function(){return this._worktime},_setConfig:function(e){this._worktime=e,this._parseSettings(),this._clearCaches()},_parseSettings:function(){var e=this.getConfig();e.parsed={dates:{},hours:null,haveCustomWeeks:!1,customWeeks:{},customWeeksRangeStart:null,customWeeksRangeEnd:null,customWeeksBoundaries:[]},e.parsed.hours=this._parseHours(e.hours);for(var t in e.dates)e.parsed.dates[t]=this._parseHours(e.dates[t]);if(e.customWeeks){var n=null,i=null;for(var t in e.customWeeks){var r=e.customWeeks[t];if(r.from&&r.to){var s=r.from,a=r.to;(!n||n>s.valueOf())&&(n=s.valueOf()),(!i||i<a.valueOf())&&(i=a.valueOf()),e.parsed.customWeeksBoundaries.push({from:s.valueOf(),fromReadable:new Date(s),to:a.valueOf(),toReadable:new Date(a),name:t}),e.parsed.haveCustomWeeks=!0;var o=e.parsed.customWeeks[t]={from:r.from,to:r.to,hours:this._parseHours(r.hours),dates:{}};if(r.days&&!r.dates){r.dates=r.dates||{};for(var t=0;t<r.days.length;t++)r.dates[t]=r.days[t],r.days[t]instanceof Array||(r.dates[t]=!!r.days[t]);delete r.days}for(var c in r.dates)o.dates[c]=this._parseHours(r.dates[c])}}e.parsed.customWeeksRangeStart=n,e.parsed.customWeeksRangeEnd=i}},_tryChangeCalendarSettings:function(e){var t=JSON.stringify(this.getConfig());return e(),this.hasWorkTime()?!0:(this._setConfig(JSON.parse(t)),this._clearCaches(),!1)},_arraysEqual:function(e,t){if(e===t)return!0;if(!e||!t||e.length!=t.length)return!1;for(var n=0;n<e.length;++n)if(e[n]!==t[n])return!1;return!0},_compareSettings:function(e,t){if(!this._arraysEqual(e.hours,t.hours))return!1;var n=Object.keys(e.dates),i=Object.keys(t.dates);if(n.sort(),i.sort(),!this._arraysEqual(n,i))return!1;for(var r=0;r<n.length;r++){var s=n[r],a=e.dates[s],o=t.dates[s];if(a!==o&&!(Array.isArray(a)&&Array.isArray(o)&&this._arraysEqual(a,o)))return!1}return!0},equals:function(e){if(!(e instanceof Tr))return!1;var t=this.getConfig(),n=e.getConfig();if(!this._compareSettings(t,n))return!1;if(t.parsed.haveCustomWeeks&&n.parsed.haveCustomWeeks){if(t.parsed.customWeeksBoundaries.length!=n.parsed.customWeeksBoundaries.length)return!1;for(var i in t.parsed.customWeeks){var r=t.parsed.customWeeks[i],s=n.parsed.customWeeks[i];if(!s||!this._compareSettings(r,s))return!1}}else if(t.parse.haveCustomWeeks!==n.parsed.haveCustomWeeks)return!1;return!0},getWorkHours:function(){var e=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);return this._getWorkHours(e.date,!1)},_getWorkHours:function(e,t){var n=this.getConfig();if(t!==!1&&(n=n.parsed),!e)return n.hours;let i=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));var r=this._timestamp({date:i});if(n.haveCustomWeeks&&n.customWeeksRangeStart<=r&&n.customWeeksRangeEnd>r){for(var s=0;s<n.customWeeksBoundaries.length;s++)if(n.customWeeksBoundaries[s].from<=r&&n.customWeeksBoundaries[s].to>r){n=n.customWeeks[n.customWeeksBoundaries[s].name];break}}var a=!0;return n.dates[r]!==void 0?a=n.dates[r]:n.dates[e.getUTCDay()]!==void 0&&(a=n.dates[e.getUTCDay()]),a===!0?n.hours:a||[]},_getIntervalTimestamp:function(e,t){var n={start:0,end:0};n.start=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds();var i=t.getUTCHours();return!i&&!t.getUTCMinutes()&&!t.getUTCSeconds()&&e.valueOf()<t.valueOf()&&(i=24),n.end=i*60*60+t.getUTCMinutes()*60+t.getUTCSeconds(),n},_parseHours:function(e){if(Array.isArray(e)){var t=[];e.forEach(function(o){typeof o=="number"?t.push(o*60*60):typeof o=="string"&&o.split("-").map(function(c){return c.trim()}).forEach(function(c){var l=c.split(":").map(function(u){return u.trim()}),d=parseInt(l[0]*60*60);l[1]&&(d+=parseInt(l[1]*60)),l[2]&&(d+=parseInt(l[2])),t.push(d)})});for(var n=[],i=0;i<t.length;i+=2){var r=t[i],s=t[i+1],a=s-r;n.push({start:r,end:s,startHour:Math.floor(r/3600),startMinute:Math.floor(r/60),endHour:Math.ceil(s/3600),endMinute:Math.ceil(s/60),durationSeconds:a,durationMinutes:a/60,durationHours:a/3600})}return n}else return e},setWorkTime:function(e){return this._tryChangeCalendarSettings(dt(function(){var t=e.hours!==void 0?e.hours:!0,n=this._timestamp(e),i=this.getConfig();if(n!==null?i.dates[n]=t:e.customWeeks||(i.hours=t),e.customWeeks){if(i.customWeeks||(i.customWeeks={}),typeof e.customWeeks=="string")n!==null?i.customWeeks[e.customWeeks].dates[n]=t:e.customWeeks||(i.customWeeks[e.customWeeks].hours=t);else if(typeof e.customWeeks=="object"&&e.customWeeks.constructor===Object)for(var r in e.customWeeks)i.customWeeks[r]=e.customWeeks[r]}this._parseSettings(),this._clearCaches()},this))},unsetWorkTime:function(e){return this._tryChangeCalendarSettings(dt(function(){if(!e)this.reset_calendar();else{var t=this._timestamp(e);t!==null&&delete this.getConfig().dates[t]}this._parseSettings(),this._clearCaches()},this))},_isWorkTime:function(e,t){var n=-1,i=null;return i=String(e.valueOf()),n=this._workingUnitsCache.getItem(t,i,e),n==-1&&(n=this._checkIfWorkingUnit(e,t),this._workingUnitsCache.setItem(t,i,n,e)),n},isWorkTime:function(){var e=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._isWorkTime(e.date,e.unit)},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments);if(!e.unit)return!1;var t=this;return this._dateDurationCache.getDuration(e.start_date,e.end_date,e.unit,e.step,function(){return t._calculateDuration(e.start_date,e.end_date,e.unit,e.step)})},_calculateDuration:function(e,t,n,i){var r=0,s=1;if(e.valueOf()>t.valueOf()){var a=t;t=e,e=a,s=-1}return n=="hour"&&i==1?r=this._getHoursBetween(e,t,n,i):n=="minute"&&i==1?r=this._getMinutesBetween(e,t,n,i):r=this._getWorkUnitsBetweenGeneric(e,t,n,i),s*Math.round(r)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,n=e.end_date,i=e.unit,r=e.step;if(!i)return!1;var s=new Date(t),a=new Date(n);for(r=r||1;s.valueOf()<a.valueOf();){if(this._isWorkTime(s,i))return!0;s=this._nextDate(s,i,r)}return!1},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,n=e.duration,i=e.unit,r=e.step;if(!i)return!1;var s=e.duration>=0?1:-1;n=Math.abs(n*1);var a=this;return this._dateDurationCache.getEndDate(t,n,i,r*s,function(){return a._calculateEndDate(t,n,i,r*s)})},_calculateEndDate:function(e,t,n,i){if(!n)return!1;if(i==1&&n=="minute")return this._calculateMinuteEndDate(e,t,i);if(i==-1&&n=="minute")return this._subtractMinuteDate(e,t,i);if(i==1&&n=="hour")return this._calculateHourEndDate(e,t,i);var r=this._addInterval(e,t,n,i,null);return r.end},_addInterval:function(e,t,n,i,r){for(var s=0,a=e;s<t&&!(r&&r(a));){var o=this._nextDate(a,n,i),c=new Date(o.valueOf()+1);i>0&&(c=new Date(o.valueOf()-1));var l=this._isWorkTime(c,n);l&&s++,a=o}return{end:a,start:e,added:s}},_addHoursUntilDayEnd:function(e,t){for(var n=this.$gantt.date.add(this.$gantt.date.day_start(new Date(e)),1,"day"),i=0,r=t,s=this._getIntervalTimestamp(e,n),a=this._getWorkHours(e),o=0;o<a.length&&i<t;o++){var c=a[o];if(s.end>=c.start&&s.start<=c.end){var l=Math.max(c.start,s.start),d=Math.min(c.end,s.end),u=(d-l)/3600;u>r&&(u=r,d=l+r*60*60);var f=Math.round((d-l)/3600);i+=f,r-=f,s.start=d}}var p=n;return i===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,s.start))),{added:i,end:p}},_calculateHourEndDate:function(e,t,n){var i=new Date(e),r=0;n=n||1,t=Math.abs(t*1);var s=this._addHoursUntilDayEnd(i,t);r=s.added,i=s.end;var a=t-r;if(a){for(var o=i;r<t;){var c=this._nextDate(o,"day",n);c.setUTCHours(0),c.setUTCMinutes(0),c.setUTCSeconds(0);var l=0;if(n>0?l=this.getHoursPerDay(new Date(c.valueOf()-1)):l=this.getHoursPerDay(new Date(c.valueOf()+1)),r+l>=t)break;r+=l,o=c}i=o}if(r<t){var a=t-r;s=this._addHoursUntilDayEnd(i,a),i=s.end}return i},_addMinutesUntilHourEnd:function(e,t){if(e.getUTCMinutes()===0)return{added:0,end:new Date(e)};for(var n=this.$gantt.date.add(this.$gantt.date.hour_start(new Date(e)),1,"hour"),i=0,r=t,s=this._getIntervalTimestamp(e,n),a=this._getWorkHours(e),o=0;o<a.length&&i<t;o++){var c=a[o];if(s.end>=c.start&&s.start<=c.end){var l=Math.max(c.start,s.start),d=Math.min(c.end,s.end),u=(d-l)/60;u>r&&(u=r,d=l+r*60);var f=Math.round((d-l)/60);r-=f,i+=f,s.start=d}}var p=n;return i===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,s.start))),{added:i,end:p}},_subtractMinutesUntilHourStart:function(e,t){for(var n=this.$gantt.date.hour_start(new Date(e)),i=0,r=t,s=n.getUTCHours()*60*60+n.getUTCMinutes()*60+n.getUTCSeconds(),a=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds(),o=this._getWorkHours(e),c=o.length-1;c>=0&&i<t;c--){var l=o[c];if(a>l.start&&s<=l.end){var d=Math.min(a,l.end),u=Math.max(s,l.start),f=(d-u)/60;f>r&&(f=r,u=d-r*60);var p=Math.abs(Math.round((d-u)/60));r-=p,i+=p,a=u}}var A=n;return i===t&&(A=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a))),{added:i,end:A}},_subtractMinuteDate:function(e,t,n){var i=this.getClosestWorkTime({date:e,dir:"past",unit:"minute"}),r=0;n=n||-1,t=Math.abs(t*1),t=Math.round(t);let s=this._isMinutePrecision(i),a=this._subtractMinutesUntilHourStart(i,t);r+=a.added,i=a.end;for(var o=0,c=[],l=0;r<t;){var d=this.$gantt.date.day_start(new Date(i)),u=!1;i.valueOf()===d.valueOf()&&(d=this.$gantt.date.add(d,-1,"day"),u=!0);var f=new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),23,59,59,999)).valueOf();f!==o&&(c=this._getWorkHours(d),l=this._getMinutesPerDay(d),o=f);var p=t-r,A=this._getTimeOfDayStamp(i,u);if(!c.length||!l){i=this.$gantt.date.add(i,-1,"day");continue}if(c[c.length-1].end<=A&&p>l){r+=l,i=this.$gantt.date.add(i,-1,"day");continue}for(var I=!1,S=null,T=null,g=c.length-1;g>=0;g--)if(c[g].start<A-1&&c[g].end>=A-1){I=!0,S=c[g],T=c[g-1];break}if(I)if(A===S.end&&p>=S.durationMinutes)r+=S.durationMinutes,i=this.$gantt.date.add(i,-S.durationMinutes,"minute");else if(!s&&p<=A/60-S.startMinute)r+=p,i=this.$gantt.date.add(i,-p,"minute");else if(s)p<=A/60-S.startMinute?(r+=p,i=this.$gantt.date.add(i,-p,"minute")):(r+=A/60-S.startMinute,T?i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,T.end)):i=this.$gantt.date.day_start(i));else{var C=this._getMinutesPerHour(i);C<=p?(r+=C,i=this._nextDate(i,"hour",n)):(a=this._subtractMinutesUntilHourStart(i,p),r+=a.added,i=a.end)}else if(i.getUTCHours()===0&&i.getUTCMinutes()===0&&i.getUTCSeconds()===0){var y=this._getClosestWorkTimePast(i,"hour");if(y.valueOf()===i.valueOf()){var y=this.$gantt.date.add(i,-1,"day"),m=this._getWorkHours(y);if(m.length){var _=m[m.length-1];y.setUTCSeconds(_.durationSeconds)}}i=y}else i=this._getClosestWorkTimePast(new Date(i-1),"hour")}if(r<t){var P=t-r;a=this._subtractMinutesUntilHourStart(i,P),r+=a.added,i=a.end}return i},_calculateMinuteEndDate:function(e,t,n){var i=new Date(e),r=0;n=n||1,t=Math.abs(t*1),t=Math.round(t);var s=this._addMinutesUntilHourEnd(i,t);r+=s.added,i=s.end;for(var a=0,o=[],c=0,l=this._isMinutePrecision(i);r<t;){var d=this.$gantt.date.day_start(new Date(i)).valueOf();d!==a&&(o=this._getWorkHours(i),c=this._getMinutesPerDay(i),a=d);var u=t-r,f=this._getTimeOfDayStamp(i);if(!o.length||!c){i=this.$gantt.date.add(this.$gantt.date.day_start(i),1,"day");continue}if(o[0].start>=f&&u>=c){if(r+=c,u==c){i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,o[o.length-1].end));break}else i=this.$gantt.date.add(i,1,"day"),i=this.$gantt.date.day_start(i);continue}for(var p=!1,A=null,I=0;I<o.length;I++)if(o[I].start<=f&&o[I].end>f){p=!0,A=o[I];break}if(p)if(f===A.start&&u>=A.durationMinutes)r+=A.durationMinutes,i=this.$gantt.date.add(i,A.durationMinutes,"minute");else if(u<=A.endMinute-f/60)r+=u,i=this.$gantt.date.add(i,u,"minute");else{var S=this._getMinutesPerHour(i);S<=u?(r+=S,l?i=this.$gantt.date.add(i,S,"minute"):i=this._nextDate(i,"hour",n)):(s=this._addMinutesUntilHourEnd(i,u),r+=s.added,i=s.end)}else i=this._getClosestWorkTimeFuture(i,"hour")}if(r<t){var T=t-r;s=this._addMinutesUntilHourEnd(i,T),r+=s.added,i=s.end}return i},getClosestWorkTime:function(){var e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._getClosestWorkTime(e.date,e.unit,e.dir)},_getClosestWorkTime:function(e,t,n){var i=new Date(e);if(this._isWorkTime(i,t))return i;if(i=this.$gantt.date[t+"_start"](i),n=="any"||!n){var r=this._getClosestWorkTimeFuture(i,t),s=this._getClosestWorkTimePast(i,t);Math.abs(r-e)<=Math.abs(e-s)?i=r:i=s}else n=="past"?i=this._getClosestWorkTimePast(i,t):i=this._getClosestWorkTimeFuture(i,t);return i},_getClosestWorkTimeFuture:function(e,t){return this._getClosestWorkTimeGeneric(e,t,1)},_getClosestWorkTimePast:function(e,t){var n=this._getClosestWorkTimeGeneric(e,t,-1);return this.$gantt.date.add(n,1,t)},_findClosestTimeInDay:function(e,t,n){var i=new Date(e),r=null,s=!1;this._getWorkHours(i).length||(i=this._getClosestWorkTime(i,"day",t<0?"past":"future"),t<0&&(i=new Date(i.valueOf()-1),s=!0),n=this._getWorkHours(i));var a=this._getTimeOfDayStamp(i);if(s&&(a=this._getTimeOfDayStamp(new Date(i.valueOf()+1),s)),t>0){for(var o=0;o<n.length;o++)if(n[o].start>=a){r=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,n[o].start));break}}else for(var o=n.length-1;o>=0;o--)if(n[o].end<=a){r=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,n[o].end));break}else if(n[o].end>a&&n[o].start<=a){r=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,a));break}return r},_getClosestWorkMinute:function(e,t,n){var i=new Date(e),r=this._getWorkHours(i),s=this._findClosestTimeInDay(i,n,r);return s||(n>0?(i=this.calculateEndDate(i,n,t),i=this.$gantt.date.day_start(i)):(i=this.calculateEndDate(i,n,"day"),i=this.$gantt.date.day_start(i),i=this.$gantt.date.add(i,1,"day"),i=new Date(i.valueOf()-1)),r=this._getWorkHours(i),s=this._findClosestTimeInDay(i,n,r)),n<0&&(s=this.$gantt.date.add(s,-1,t)),s},_getClosestWorkTimeGeneric:function(e,t,n){if(t==="hour"||t==="minute")return this._getClosestWorkMinute(e,t,n);for(var i=this._getUnitOrder(t),r=this.units[i-1],s=e,a=3e3,o=0;!this._isWorkTime(s,t)&&!(r&&!this._isWorkTime(s,r)&&(n>0?s=this._getClosestWorkTimeFuture(s,r):s=this._getClosestWorkTimePast(s,r),this._isWorkTime(s,t)));){if(o++,o>a)return this.$gantt.assert(!1,"Invalid working time check"),!1;s=this.$gantt.date.add(s,n,t),this.$gantt.date[t+"_start"]&&(s=this.$gantt.date[t+"_start"](s))}return s},hasWorkTime:function(){var e=this.getConfig(),t=e.dates,n=[0,1,2,3,4,5,6];for(var i in e.dates);var r=this._checkWorkHours(e.hours),s=!1;return n.forEach((function(a){if(!s){var o=t[a];o===!0?s=r:Array.isArray(o)&&(s=this._checkWorkHours(o))}}).bind(this)),s},_checkWorkHours:function(e){if(e.length===0)return!1;for(var t=!1,n=0;n<e.length;n+=2)e[n]!==e[n+1]&&(t=!0);return t},_isMinutePrecision:function(e){let t=!1;return this._getWorkHours(e).forEach(function(n){(n.startMinute%60||n.endMinute%60)&&(t=!0)}),t}};var Fe={isLegacyResourceCalendarFormat:function(e){if(!e)return!1;for(var t in e)if(e[t]&&typeof e[t]=="object")return!0;return!1},getResourceProperty:function(e){var t=e.resource_calendars,n=e.resource_property;if(this.isLegacyResourceCalendarFormat(t))for(var i in e){n=i;break}return n},getCalendarIdFromLegacyConfig:function(e,t){if(t)for(var n in t){var i=t[n];if(e[n]){var r=i[e[n]];if(r)return r}}return null}};function Gp(){function e(r){return r.map(function(s){return s&&s.resource_id?s.resource_id:s}).sort().join("-")}var t={};function n(r,s){return s.mergeCalendars(r.map(function(a){var o=a&&a.resource_id?a.resource_id:a;return s.getResourceCalendar(o)}))}function i(r,s){var a=e(r);if(r.length){if(r.length===1)return s.getResourceCalendar(a).id;if(t[a])return t[a].id;var o=n(r,s);return t[a]=o,s.addCalendar(o)}else return null}return{getCalendarIdFromMultipleResources:i}}var Kp=Gp();function Wc(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=Fe.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))}Wc.prototype={_calendars:{},_convertWorkTimeSettings:function(e){let t=e.days;if(typeof t=="object"&&!Array.isArray(t)&&t!==null){let n={};if(t?.weekdays)for(let i=0;i<7;i++)n[i]=t.weekdays[i];t?.dates&&Object.entries(t.dates).forEach(([i,r])=>{n[new Date(i).valueOf()]=r}),Object.entries(n).forEach(([i,r])=>{r instanceof Array||(n[i]=!!r)}),e={...e,dates:n}}else if(t&&!e.dates){e.dates=e.dates||{};for(let n=0;n<t.length;n++)e.dates[n]=t[n],t[n]instanceof Array||(e.dates[n]=!!t[n])}return delete e.days,e},mergeCalendars:function(){var e=[],t=arguments;if(Array.isArray(t[0]))e=t[0].slice();else for(var n=0;n<arguments.length;n++)e.push(arguments[n]);var i=new Mc,r;return e.forEach((function(s){r?r=this._createCalendarFromConfig(i.merge(r,s)):r=s}).bind(this)),this.createCalendar(r)},_createCalendarFromConfig:function(e){var t=new Tr(this.$gantt,Fc(this.$gantt));t.id=String(gr());var n=this._convertWorkTimeSettings(e);if(n.customWeeks)for(var i in n.customWeeks)n.customWeeks[i]=this._convertWorkTimeSettings(n.customWeeks[i]);return t._setConfig(n),t},createCalendar:function(e){var t;e||(e={}),e.getConfig?t=vt(e.getConfig()):e.worktime?t=vt(e.worktime):t=vt(e);var n=vt(this.defaults.fulltime.worktime);return ve(t,n),this._createCalendarFromConfig(t)},getCalendar:function(e){e=e||"global";var t=this._calendars[e];return t||(this.createDefaultCalendars(),t=this._calendars[e]),t},getCalendars:function(){var e=[];for(var t in this._calendars)e.push(this.getCalendar(t));return e},_getOwnCalendar:function(e){var t=this.$gantt.config;if(e[t.calendar_property])return this.getCalendar(e[t.calendar_property]);if(t.resource_calendars){var n,i,r;if(this._legacyConfig===!1?r=t.resource_property:r=Fe.getResourceProperty(t),Array.isArray(e[r])&&e[r].length)t.dynamic_resource_calendars?i=Kp.getCalendarIdFromMultipleResources(e[r],this):n=this.getResourceCalendar(e[r]);else if(this._legacyConfig===void 0&&(this._legacyConfig=Fe.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var i=Fe.getCalendarIdFromLegacyConfig(e,t.resource_calendars);else if(r&&e[r]&&t.resource_calendars[e[r]])var n=this.getResourceCalendar(e[r]);if(i&&(n=this.getCalendar(i)),n)return n}return null},getResourceCalendar:function(e){if(e==null)return this.getCalendar();var t=null;typeof e=="number"||typeof e=="string"?t=e:t=e.id||e.key;var n=this.$gantt.config,i=n.resource_calendars,r=null;if(Array.isArray(e)&&e.length===1&&(typeof e[0]=="object"?t=e[0].resource_id:t=e[0]),i){if(this._legacyConfig===void 0&&(this._legacyConfig=Fe.isLegacyResourceCalendarFormat(n.resource_calendars)),this._legacyConfig){for(var s in i)if(i[s][t]){r=i[s][t];break}}else var r=i[t];if(r)return this.getCalendar(r)}return this.getCalendar()},getTaskCalendar:function(e){var t=this.$gantt,n;if(e==null)return this.getCalendar();if((typeof e=="number"||typeof e=="string")&&t.isTaskExists(e)?n=t.getTask(e):n=e,!n)return this.getCalendar();var i=this._getOwnCalendar(n),r=!!t.getState().group_mode;if(!i&&t.config.inherit_calendar&&t.isTaskExists(n.parent)){for(var s=n;t.isTaskExists(s.parent)&&(s=t.getTask(s.parent),!(t.isSummaryTask(s)&&(i=this._getOwnCalendar(s),i))););r&&!i&&e.$effective_calendar&&(i=this.getCalendar(e.$effective_calendar))}return i||this.getCalendar()},addCalendar:function(e){if(!this.isCalendar(e)){var t=e.id;e=this.createCalendar(e),e.id=t}if(e._tryChangeCalendarSettings(function(){})){var n=this.$gantt.config;return e.id=e.id||gr(),this._calendars[e.id]=e,n.worktimes||(n.worktimes={}),n.worktimes[e.id]=e.getConfig(),e.id}else return this.$gantt.callEvent("onCalendarError",[{message:"Invalid calendar settings, no worktime available"},e]),null},deleteCalendar:function(e){var t=this.$gantt.config;return e&&this._calendars[e]?(delete this._calendars[e],t.worktimes&&t.worktimes[e]&&delete t.worktimes[e],!0):!1},restoreConfigCalendars:function(e){for(var t in e)if(!this._calendars[t]){var n=e[t],i=this.createCalendar(n);i.id=t,this.addCalendar(i)}},defaults:{global:{id:"global",worktime:{hours:[8,12,13,17],days:[0,1,1,1,1,1,0]}},fulltime:{id:"fulltime",worktime:{hours:[0,24],days:[1,1,1,1,1,1,1]}}},createDefaultCalendars:function(){var e=this.$gantt.config;this.restoreConfigCalendars(this.defaults),this.restoreConfigCalendars(e.worktimes)},isCalendar:function(e){var t=[e.isWorkTime,e.setWorkTime,e.getWorkHours,e.unsetWorkTime,e.getClosestWorkTime,e.calculateDuration,e.hasDuration,e.calculateEndDate];return t.every(function(n){return n instanceof Function})}};function Dr(e,t){this.argumentsHelper=t,this.$gantt=e}Dr.prototype={getWorkHours:function(){return[0,24]},setWorkTime:function(){return!0},unsetWorkTime:function(){return!0},isWorkTime:function(){return!0},getClosestWorkTime:function(t){var t=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return t.date},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,n=e.end_date,i=e.unit,r=e.step;return this._calculateDuration(t,n,i,r)},_calculateDuration:function(e,t,n,i){var r=this.$gantt.date,s={week:1e3*60*60*24*7,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60},a=0;if(s[n])a=Math.round((t-e)/(i*s[n]));else{for(var o=new Date(e),c=new Date(t);o.valueOf()<c.valueOf();)a+=1,o=r.add(o,i,n);o.valueOf()!=t.valueOf()&&(a+=(c-o)/(r.add(o,i,n)-o))}return Math.round(a)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,n=e.end_date,i=e.unit;return i?(t=new Date(t),n=new Date(n),t.valueOf()<n.valueOf()):!1},hasWorkTime:function(){return!0},equals:function(e){return e instanceof Dr},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,n=e.duration,i=e.unit,r=e.step;return this.$gantt.date.add(t,r*n,i)}};function Uc(e){this.$gantt=e.$gantt,this.argumentsHelper=Fc(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new Dr(this.$gantt,this.argumentsHelper)}Uc.prototype={_getCalendar:function(e){var t;if(!this.$gantt.config.work_time)t=this.$disabledCalendar;else{var n=this.calendarManager;e.task?t=n.getTaskCalendar(e.task):e.id?t=n.getTaskCalendar(e):e.calendar&&(t=e.calendar),t||(t=n.getTaskCalendar())}return t},getWorkHours:function(e){e=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);var t=this._getCalendar(e);return t.getWorkHours(e.date)},setWorkTime:function(e,t){return e=this.argumentsHelper.setWorkTimeArguments.apply(this.argumentsHelper,arguments),t||(t=this.calendarManager.getCalendar()),t.setWorkTime(e)},unsetWorkTime:function(e,t){return e=this.argumentsHelper.unsetWorkTimeArguments.apply(this.argumentsHelper,arguments),t||(t=this.calendarManager.getCalendar()),t.unsetWorkTime(e)},isWorkTime:function(e,t,n,i){var r=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return i=this._getCalendar(r),i.isWorkTime(r)},getClosestWorkTime:function(e){e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);var t=this._getCalendar(e);return t.getClosestWorkTime(e)},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=this._getCalendar(e);return t.calculateDuration(e)},hasDuration:function(){var e=this.argumentsHelper.hasDurationArguments.apply(this.argumentsHelper,arguments),t=this._getCalendar(e);return t.hasDuration(e)},calculateEndDate:function(t){var t=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),n=this._getCalendar(t);return n.calculateEndDate(t)}};var qp=function(e,t){return{getWorkHours:function(n){return t.getWorkHours(n)},setWorkTime:function(n){return t.setWorkTime(n)},unsetWorkTime:function(n){t.unsetWorkTime(n)},isWorkTime:function(n,i,r){return t.isWorkTime(n,i,r)},getClosestWorkTime:function(n){return t.getClosestWorkTime(n)},calculateDuration:function(n,i,r){return t.calculateDuration(n,i,r)},_hasDuration:function(n,i,r){return t.hasDuration(n,i,r)},calculateEndDate:function(n,i,r,s){return t.calculateEndDate(n,i,r,s)},mergeCalendars:dt(e.mergeCalendars,e),createCalendar:dt(e.createCalendar,e),addCalendar:dt(e.addCalendar,e),getCalendar:dt(e.getCalendar,e),getCalendars:dt(e.getCalendars,e),getResourceCalendar:dt(e.getResourceCalendar,e),getTaskCalendar:dt(e.getTaskCalendar,e),deleteCalendar:dt(e.deleteCalendar,e)}},zp={create:qp};function Bc(e){var t=new Wc(e),n=new Uc(t),i=zp.create(t,n);ve(e,i)}var jc={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 Hc(e={}){let t=e.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},t),locale:e.locale||jc,templates:e.templates||{},getTask:e.getTask||function(i){return null},isTaskExists:e.isTaskExists||function(i){return!1},isSummaryTask:e.isSummaryTask||function(i){return!1},getState:function(){return{group_mode:!1}},callEvent:function(i,r){let s=e.onEvent;return s&&s(i,r),!0},attachEvent:function(){return 0},checkEvent:function(){return!1},detachEvent:function(){},defined:Oc,mixin:ve,copy:vt,assert:function(i,r){if(!i){if(e.throwOnAssert)throw new Error("[calendar] "+r);e.silent!==!0&&console.error("[calendar]",r)}},$services:{getService:function(){return null}},$ui:{getView:function(){return null}}};return n._correct_dst_change=function(i){return i},n.date=xc(n),n.date.init(),Bc(n),n}function Jp(e={}){let t=Hc(e);return{addCalendar:function(n){return t.addCalendar(n)},deleteCalendar:function(n){return t.deleteCalendar(n)},getCalendar:function(n){return t.getCalendar(n)},getCalendars:function(){return t.getCalendars()},mergeCalendars:function(){return t.mergeCalendars.apply(t,arguments)},getTaskCalendar:function(n){return t.getTaskCalendar(n)},getResourceCalendar:function(n){return t.getResourceCalendar(n)},setWorkTime:function(n){return t.setWorkTime(n)},unsetWorkTime:function(n){return t.unsetWorkTime(n)},isWorkTime:function(){return t.isWorkTime.apply(t,arguments)},getClosestWorkTime:function(){return t.getClosestWorkTime.apply(t,arguments)},getWorkHours:function(){return t.getWorkHours.apply(t,arguments)},calculateDuration:function(){return t.calculateDuration.apply(t,arguments)},calculateEndDate:function(){return t.calculateEndDate.apply(t,arguments)},_internals:t}}var $c={createCalendar:Jp};var nL=3600*1e3;function Vc(e){return{getActivity(t){let n=e.getActivity(t);return n?Xp(n,e):null}}}function Xp(e,t){let n=t.getChildren(e.id).length>0;return{id:String(e.id),text:String(e.text??""),description:String(e.description??""),type:e.type??"task",start_date:e.start_date,end_date:e.end_date,duration:Number(e.duration??0),progress:Number(e.progress??0),constraint_type:e.constraint_type??"asap",constraint_date:e.constraint_date??null,calendar_id:String(e.calendar_id??""),cost:Number(e.cost??0),used_cost:Number(e.used_cost??0),hhWorkTime:Number(e.hhWorkTime??0),ponderator:Number(e.ponderator??0),auto_scheduling:!!(e.auto_scheduling??!0),hasChildren:n,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,isMilestone:e.type==="milestone",real_constraint_type:e.real_constraint_type??null,last_constraint:e.last_constraint??null,last_constraint_date:e.last_constraint_date??null,last_start_date:e.last_start_date??null,date_origin:e.date_origin??null}}var{createCalendar:Zp}=$c,Me="__replay_default__";function Qp(e){if(!e||e.length===0||typeof e[0]=="string")return e;let t=e.map(Number);if(t.some(s=>Number.isNaN(s)))return e;let n=t[0],i=t[t.length-1];return t.every((s,a)=>s===n+a)?[`${n}:00-${i+1}:00`]:e}var Yc={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function th(e){let t={};if(Array.isArray(e.days))for(let i=0;i<e.days.length;i+=1)t[i]=e.days[i];if(e.dates)for(let[i,r]of Object.entries(e.dates))t[i]=r;let n={hours:Qp(e.hours),dates:t};return e.customWeeks&&(n.customWeeks=e.customWeeks),n}function Gc(e){let t=Zp({config:{work_time:!0}});t.addCalendar({id:Me,worktime:Yc});for(let o of e)t.addCalendar({id:o.id,worktime:o.worktime?th(o.worktime):Yc});let n=bc(t),i=n.getCalendar(Me);if(!i)throw new Error("[replay-calendar] default calendar failed to register in work-calendar instance");let r=new Set([Me]);for(let o of e)r.add(String(o.id));let s=new Map;return{reader:{getCalendar(o){let c=String(o),l=s.get(c);if(l)return l;let d=r.has(c)?n.getCalendar(o)??i:i;return s.set(c,d),d}}}}function Kc(e){return{getParentStartDateIfHasPredecessors(t){let n=e.getActivity(t);if(!n)return null;let i=e.getParent(n.id);return!i||i.$target.length===0?null:i.start_date},getDescendantIds(t){return eh(e,t).map(n=>String(n))},getAncestorIds(t){let n=[],i=e.getActivity(t);for(;i;){let r=i.parent;if(!r||r==="0")break;let s=e.getActivity(r);if(!s)break;n.push(String(r)),i=s}return n},getChildProgressInfo(t){return e.getChildren(t).map(i=>{let r=e.getActivity(i);return{id:i,progress:Number(r?.progress??0),ponderator:Number(r?.ponderator??0)}})},getChildHhInfo(t){return e.getChildren(t).map(i=>{let r=e.getActivity(i);return{id:i,hhWorkTime:Number(r?.hhWorkTime??0),progress:Number(r?.progress??0)}})},getChildUsedCostInfo(t){return e.getChildren(t).map(i=>{let r=e.getActivity(i);return{id:i,used_cost:Number(r?.used_cost??0)}})},getChildCostInfo(t){return e.getChildren(t).map(i=>{let r=e.getActivity(i);return{id:i,cost:Number(r?.cost??0)}})}}}function eh(e,t){let n=[],i=new ut;for(let r of e.getChildren(t))i.enqueue(r);for(;!i.isEmpty();){let r=i.dequeue();n.push(r);for(let s of e.getChildren(r))i.enqueue(s)}return n}function qc(e,t={}){return{calendars:e.calendarReader,hierarchy:Kc(e),activityReader:Vc(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay??8,inputUnit:t.inputUnit??"days"}}function zc(e){return Ne(e)}function Er(e,t,n,i,r){return{changeSet:e,beforeSnap:t,beforeLinks:n,afterSnap:i,afterLinks:r}}function Xc(e,t){let n=new Map,i=new Map;for(let r of t.activities){if(r.kind!=="created")continue;let s=e.getActivity(String(r.id));s&&n.set(String(r.id),Z(s))}for(let r of t.links){if(r.kind!=="created")continue;let s=e.getLink(String(r.id));s&&i.set(String(r.id),{...s})}return{afterSnap:n,afterLinks:i}}function Zc(e){return e.kind!=="inline-edit"||!we.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function Jc(e){return e.changeSet.activities.length===1&&e.changeSet.activities[0]?.kind==="updated"&&e.changeSet.links.length===0&&!e.beforeSnap?.size&&!e.afterSnap?.size}function Qc(e,t){if(!Jc(e)||!Jc(t))return!1;let n=e.changeSet.activities[0],i=t.changeSet.activities[0];return!!n&&!!i&&String(n.id)===String(i.id)}function tl(e,t){let n=e.changeSet.activities[0],i=t.changeSet.activities[0];if(!n||!i)return t;let r=n.fields??{},s=i.fields??{},a={};for(let c of new Set([...Object.keys(r),...Object.keys(s)])){let l=r[c],d=s[c];a[c]={before:l?l.before:d?.before,after:d?d.after:l?.after}}let o={...t.changeSet,activities:[{...i,fields:a}]};return Er(o)}function el(e){return e.kind!=="selection-toggle"&&e.kind!=="selection-replace"&&e.kind!=="visibility-set"&&e.kind!=="sir-sync"}function Pr(e){for(let t of e.changeSet.activities)if(t.kind==="created"||t.kind==="deleted"||t.kind==="updated"&&t.fields&&v.CUSTOM_ID in t.fields)return!0;return!1}function Rr(e,t,n){let i=[],r=[];for(let s of t.changeSet.activities){let a=String(s.id);if(s.kind==="updated"){let o=e.getActivity(a);i.push({id:a,kind:"updated",after:o?X(o):null})}else if(s.kind==="deleted")if(n==="before"){let o=e.getActivity(a);i.push({id:a,kind:"created",after:o?X(o):null})}else i.push({id:a,kind:"deleted",after:null});else if(n==="before")i.push({id:a,kind:"deleted",after:null});else{let o=e.getActivity(a);i.push({id:a,kind:"created",after:o?X(o):null})}}for(let s of t.changeSet.links){let a=String(s.id);if(s.kind==="updated"){let o=e.getLink(a);r.push({id:a,kind:"updated",after:o?gt(o):null})}else if(s.kind==="deleted")if(n==="before"){let o=e.getLink(a);r.push({id:a,kind:"created",after:o?gt(o):null})}else r.push({id:a,kind:"deleted",after:null});else if(n==="before")r.push({id:a,kind:"deleted",after:null});else{let o=e.getLink(a);r.push({id:a,kind:"created",after:o?gt(o):null})}}return{source:{kind:n==="before"?"undo":"redo"},activities:i,links:r,calendars:[],trackingEvents:[],effects:[]}}function nl(e){return e.activities.length>0||e.links.length>0||(e.effects?.length??0)>0}function il(e,t){sl(e,t,"before")}function rl(e,t){sl(e,t,"after")}function sl(e,t,n){let i=t.changeSet;for(let r of i.activities)if(r.kind==="updated"){if(!r.fields)continue;for(let[s,a]of Object.entries(r.fields))V(e,r.id,s,n==="before"?a.before:a.after)}else if(r.kind==="deleted")if(n==="before"){let s=t.beforeSnap?.get(String(r.id));if(!s)throw new Error(`undo: missing beforeSnap for resurrecting activity ${r.id}`);e.addActivity(Z(s))}else e.removeActivity(String(r.id));else if(n==="before")e.removeActivity(String(r.id));else{let s=t.afterSnap?.get(String(r.id));if(!s)throw new Error(`redo: missing afterSnap for re-creating activity ${r.id}`);e.addActivity(Z(s))}for(let r of i.links)if(r.kind==="updated"){if(!r.fields)continue;for(let[s,a]of Object.entries(r.fields))ba(e,String(r.id),s,n==="before"?a.before:a.after)}else if(r.kind==="deleted")if(n==="before"){let s=t.beforeLinks?.get(String(r.id));if(!s)throw new Error(`undo: missing beforeLinks for re-adding link ${r.id}`);e.addLink(s)}else e.removeLink(String(r.id));else if(n==="before")e.removeLink(String(r.id));else{let s=t.afterLinks?.get(String(r.id));if(!s)throw new Error(`redo: missing afterLinks for re-creating link ${r.id}`);e.addLink(s)}}var nh=100,ih=600,Jn=class{constructor(t=nh){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];_lastKey=null;_lastTime=0;record(t,n=null,i=0){let r=this.undoStack[this.undoStack.length-1];n!=null&&n===this._lastKey&&i-this._lastTime<=ih&&r!==void 0&&Qc(r,t)?this.undoStack[this.undoStack.length-1]=tl(r,t):(this.undoStack.push(t),this.undoStack.length>this.maxDepth&&this.undoStack.shift()),this._lastKey=n,this._lastTime=i,this.redoStack.length=0}resetCoalesce(){this._lastKey=null}takeUndo(){return this.undoStack.pop()??null}takeRedo(){return this.redoStack.pop()??null}pushRedo(t){this.redoStack.push(t)}pushUndo(t){this.undoStack.push(t)}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undoDepth(){return this.undoStack.length}clear(){this.undoStack.length=0,this.redoStack.length=0}};var rh=new Set(["baseline_points","tasks","baselineObject","activityModifications","color","freeSlack","totalSlack","custom_predecessors","custom_sucessors","start_base","work_base","cost_base","duration_base","$effective_calendar","checked","visibleChecked","mustApplyVisibleChecked","earlyStart","earlyFinish","lateStart","lateFinish","is_critical"]);function al(e,t){if(e.assignedDefaultCalendar)return!0;for(let[n,i]of Object.entries(e)){if(rh.has(n))continue;let r=t[n];if(i instanceof Date){if(!(r instanceof Date)||i.getTime()!==r.getTime())return!0}else if(i!==r)return!0}return!1}var Xn=class{initialized=!1;linksAtLastSave=new Map;activitiesAtLastSave=new Map;init(t,n){this.snapshotActivities(t),this.snapshotLinks(n),this.initialized=!0}snapshotActivities(t){this.activitiesAtLastSave.clear();for(let n of t)n.proplannerId!=null&&this.activitiesAtLastSave.set(String(n.id),n)}snapshotLinks(t){this.linksAtLastSave.clear();for(let n of t)n.proplannerId!=null&&this.linksAtLastSave.set(String(n.id),{lag:n.lag,type:n.type})}modifiedActivities(t){return this.initialized?t.filter(n=>{if(n.proplannerId==null)return!1;if(n.assignedDefaultCalendar)return!0;let i=this.activitiesAtLastSave.get(String(n.id));return i?al(n,i):!0}):[]}modifiedLinks(t){return this.initialized?t.filter(n=>{if(n.proplannerId==null)return!1;let i=this.linksAtLastSave.get(String(n.id));return i?n.lag!==i.lag||n.type!==i.type:!0}):[]}clear(){this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear()}};var ol=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;var cl="9:00-17:00",Lr=[!1,!0,!0,!0,!0,!0,!1],ll=new Set(["1","true"]),br="DURATION",dl="asap",ul={"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 fl(e,t){let n=e.map(r=>mh(r,t));yh(n);let i=new Set(n.map(r=>r.id));return gh(n,i,t.reporter),{activities:n,activityIds:i}}function sh(e){return typeof e.id=="number"?{proplannerId:e.id}:{}}function ah(e){return e===0}function oh(e,t){if(!e)return null;let n=ul[e.toUpperCase()];return n===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),dl):n}function ch(e,t){let n=oh(e.constraint,t),r=n!=="asap"&&n!=="alap"&&e.constraint_date?At(e.constraint_date):null;return{constraint_type:n,constraint_date:r}}function lh(e){let t=At(e.start_date),n=e.type==="milestone";return{start_date:t,end_date:n?t:At(e.end_date),duration:n?0:Number(e.duration)}}function dh(e){let t=e.type==="milestone";return{old_progress_registered:Number(e.progress),old_duration_registered:t?0:Number(e.duration),old_cost_registered:Number(e.cost),old_used_cost_registered:Number(e.used_cost??0),old_real_cost_registered:Number(e.real_cost??0),old_hhWorkTime_registered:Number(e.hhWorkTime)}}function uh(e,t,n){if(e==null)return n;let i=String(e);return t.has(i)?i:n}function fh(e){if(e==null||e==="")return[];if(Array.isArray(e))return e.map(String);if(typeof e!="string")return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.map(String):[]}catch{return[]}}function ph(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function hh(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)ph(n)&&t.push({id:String(n.id)});return t}function mh(e,t){let n=String(e.unique_id),i=e.parent_id==="0"?"0":String(e.parent_id),r=uh(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),s=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),a=r!=null&&s,o=Number(e.progress),{constraint_type:c,constraint_date:l}=ch(e,t.reporter),{start_date:d,end_date:u,duration:f}=lh(e);return{...sh(e),id:n,parent:i,text:e.name,description:e.description??"",type:e.type,start_date:d,end_date:u,duration:f,constraint_type:c,constraint_date:l,auto_scheduling:ah(o),calendar_id:r,assignedDefaultCalendar:a,progress:o,cost:Number(e.cost),used_cost:Number(e.used_cost??0),real_cost:Number(e.real_cost??0),hhWorkTime:Number(e.hhWorkTime),real_work:Number(e.real_work??0),ponderator:Number(e.ponderator),correlative_id:e.correlative_id,is_lookahead:e.isOnLookahead,visible:e.should_be_showed!==!1,newActivitiesArray:fh(e.newActivitiesArray),activityModifications:e.activitymodifications,unique_correlative_id:e.unique_correlative_id,ganttId:e.ganttId,sectorId:e.sectorId,companyId:e.companyId,subcontractId:e.subcontractId,subcontract:e.subcontract,custom_id:e.custom_id,hasCustomPonderator:e.hasCustomPonderator,has_childs:e.has_childs,sumOfDurationRecursively:e.sumOfDurationRecursively,freeSlack:e.freeSlack,is_critical:e.is_critical,hasNewActivities:e.hasNewActivities,isNewActivity:e.isNewActivity,tasks:e.tasks,responsables:e.responsables,tags:e.tags,createdAt:e.createdAt,updatedAt:e.updatedAt,pendingRequests:hh(e.pendingRequests),for_disable_milestone_duration:Math.round(f*t.hoursPerDay),...dh(e),...e.date_origin!==void 0?{date_origin:e.date_origin===null?null:At(e.date_origin)}:{},...e.baseline_points!==void 0?{baseline_points:e.baseline_points}:{}}}function yh(e){let t=e.find(n=>n.correlative_id===0&&n.type==="project");t&&(t.parent="0")}function gh(e,t,n){for(let i of e)i.parent!=="0"&&(t.has(i.parent)||(n.warn(`[parseFromBackend] activity "${i.id}" references unknown parent "${i.parent}" \u2014 re-parenting to root ('0')`),i.parent="0"))}function yl(e,t,n){let s=(e!==void 0&&e.length>0?e:t??[]).map(Ch),a=(n??[]).map(Sh);return{calendars:s,baseCalendars:a,knownCalendarIds:new Set(s.map(o=>o.id)),defaultCalendarId:Ah(s)}}function Ah(e){let t=e.find(i=>i.is_default);if(t)return t.id;let n=e[0];return n?n.id:null}function gl(e,t){let n=Eh(e.working_days),{days:i,hours:r}=Dh(e,n),s=_h(t.exceptionsSource),a={days:i,hours:r};return s&&(a.dates=s),{id:`${String(e.id)}${t.idSuffix}`,name:e.name,is_default:t.isDefault,...t.baseDefault!==void 0?{baseDefault:t.baseDefault}:{},worktime:a}}function Ch(e){let t=e.baseDefault,n=typeof t=="boolean"?t:void 0;return gl(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:n,exceptionsSource:e.exceptiondays})}function Sh(e){return gl(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays})}function _h(e){if(!Array.isArray(e)||e.length===0)return null;let t={};for(let n of e){if(!n)continue;let i=kh(n.from_date,n.to_date);if(i.length===0)continue;let r=Ih(n);if(r!==void 0)for(let s of i)t[s]=r}return Object.keys(t).length>0?t:null}function kh(e,t){let n=pl(e),i=pl(t);if(n===null||i===null)return[];let r=[],s=n;for(;s<=i;)r.push(String(s)),s+=864e5;return r}function pl(e){if(typeof e!="string")return null;let t=ol.exec(e.trim());if(!t)return null;let n=Number(t[1]),i=Number(t[2]),r=Number(t[3]);return Number.isFinite(n)&&Number.isFinite(i)&&Number.isFinite(r)?Date.UTC(n,i-1,r):null}function Ih(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let n=Th(t);if(n.length>0)return n}}var hl=/^\d{1,2}:\d{2}$/;function Th(e){let t=[];for(let n of e){let i=Cl(n?.shift_string);if(!i)continue;if(!i.startsCsv.includes(",")&&!i.endsCsv.includes(",")){let o=i.startsCsv.trim(),c=i.endsCsv.trim();!Zn(o)&&!Zn(c)&&hl.test(o)&&hl.test(c)&&t.push(`${o}-${c}`);continue}let a=Al(i.startsCsv,i.endsCsv).find(o=>o!==null);a&&t.push(a)}return t.sort(vl),t}function ml(e){let t=e.indexOf("-"),n=t>0?e.slice(0,t):e,[i,r]=n.split(":");return(Number(i)||0)*60+(Number(r)||0)}function vl(e,t){return ml(e)-ml(t)}function Dh(e,t){let n=Array.from({length:7},()=>[]),i=(l,d)=>{let u=Al(l,d);for(let f=0;f<7;f+=1){let p=u[f],A=n[f];p&&A&&A.push(p)}},r=Array.isArray(e.shifts)&&e.shifts.length>0,s=typeof e.shift_start=="string"&&typeof e.shift_end=="string";if(r)for(let l of e.shifts){let d=Cl(l?.shift_string);d&&i(d.startsCsv,d.endsCsv)}else s&&i(e.shift_start,e.shift_end);for(let l of n)l.sort(vl);let a=n.find((l,d)=>!!t[d]&&l.length>0),o=a&&a.length>0?a:[cl];return{days:t.map((l,d)=>{if(!l)return!1;let u=n[d];return u&&u.length>0?u:o}),hours:o}}function Al(e,t){let n=Array.from({length:7},()=>null);if(typeof e!="string"||typeof t!="string")return n;let i=e.split(",").map(o=>o.trim()),r=t.split(",").map(o=>o.trim());if(!(i.length===r.length&&i.length>0&&i.length<=7))return n;let a=[...n];for(let o=0;o<i.length;o+=1){let c=i[o],l=r[o];Zn(c)||Zn(l)||(a[o]=`${c}-${l}`)}return a}function Cl(e){if(typeof e!="string")return null;let t=e.indexOf("-");return t<=0?null:{startsCsv:e.slice(0,t),endsCsv:e.slice(t+1)}}function Eh(e){if(typeof e!="string")return[...Lr];let t=e.split(",").map(n=>n.trim());return t.length!==7?[...Lr]:t.map(n=>ll.has(n))}var Ph=new Set(["false","null"]);function Zn(e){return!e||Ph.has(e)}function Rh(e){return e==="0"||e==="1"||e==="2"||e==="3"}function Lh(e){if(typeof e!="string")return null;let t=qs(e);return t||(Rh(e)?e:null)}function _l(e,t){let n=[];for(let i of e)try{n.push(bh(i,t.knownActivityIds,t.hoursPerDay))}catch(r){t.reporter.warn("[parseFromBackend] dropping invalid link",r)}return Oh(n)}function bh(e,t,n){let i=String(e.unique_id??e.id),r=String(e.source_id??e.source??""),s=String(e.target_id??e.target??"");if(!t.has(r))throw new Error(`[parseFromBackend] link "${i}" source "${r}" does not exist`);if(!t.has(s))throw new Error(`[parseFromBackend] link "${i}" target "${s}" does not exist`);let a=Lh(e.type);if(a===null)throw new Error(`[parseFromBackend] link "${i}" has invalid type "${String(e.type)}"`);let o=e.ganttId,c=e.sectorId,l=e.id;return{id:i,source:r,target:s,type:a,lag:ft(Number(e.lag??0),n),...typeof o=="number"?{ganttId:o}:{},...typeof c=="number"?{sectorId:c}:{},...typeof l=="number"?{proplannerId:l}:{}}}function Oh(e){let t=new Map;for(let n of e){let i=`${n.source}-${n.target}-${n.type}`,r=t.get(i);(!r||Sl(n)>Sl(r))&&t.set(i,n)}return[...t.values()]}function Sl(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function wh(e){if(typeof e!="string")return br;switch(e.toUpperCase()){case"DURATION":return"DURATION";case"COST":return"COST";case"HH":return"HH";default:return br}}function Nh(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function xh(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function kl(e){let t=Nh(e),n=xh(e),i=e.update_duration_for_primavera_for_end_date===!0;return{id:String(e.id),name:e.name,hoursPerDay:e.hoursPerDay,hoursPerWeek:e.hoursPerWeek,dateFormat:e.dateFormat,projectId:e.projectId,companyId:e.companyId,...t!==void 0?{customIdPrefix:t}:{},...n!==void 0?{customIdIncrement:n}:{},...i?{updateDurationForPrimaveraEndDate:!0}:{},activityCreter:wh(e.activity_creter),statusCriteria:gi}}function Qn(e,t=ne){let n=kl(e.sector),{calendars:i,baseCalendars:r,knownCalendarIds:s,defaultCalendarId:a}=yl(e.calendars,e.sector.calendars,e.baseCalendars),{activities:o,activityIds:c}=fl(e.activities,{knownCalendarIds:s,defaultCalendarId:a,hoursPerDay:n.hoursPerDay,reporter:t}),l=_l(e.links,{knownActivityIds:c,hoursPerDay:n.hoursPerDay,reporter:t});return{sector:n,activities:o,links:l,calendars:i,baseCalendars:r}}function Il(e={}){let t=e.seed??0,n=i=>{i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){let r=typeof i=="number"?i:Number(i);Number.isFinite(r)&&n(r)}return{next(){return t+=1,String(t)},bump(i){let r=typeof i=="number"?i:Number(i);Number.isFinite(r)&&n(r)}}}function Tl(e={}){let t=e.seed??Date.now(),n=i=>{i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){let r=typeof i=="number"?i:Number(i);Number.isFinite(r)&&n(r)}return{next(){return t+=1,String(t)},bump(i){let r=typeof i=="number"?i:Number(i);Number.isFinite(r)&&n(r)}}}function Dl(e={}){let t=e.seed??0,n=i=>{Number.isFinite(i)&&i>0&&i<=9999999&&i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){if(i==null)continue;let r=typeof i=="number"?i:Number(i);n(r)}return{next(){return t+=1,String(t)},bump(i){if(i==null)return;let r=typeof i=="number"?i:Number(i);n(r)}}}function El(e){return!!e&&typeof e=="string"&&e.trim().length>0}function ti(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function ei(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function Pl(e){if(!e||typeof e!="object")return"";let t=e.custom_id;return typeof t=="string"?t:""}function Rl(e,t){return!t&&El(e)}function Ll(e,t){return t&&El(e)}function Ue(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function We(e){if(!Ue(e))return 0n;try{return BigInt(e)}catch{return 0n}}function Fh(e,t){if(typeof e!="bigint")return"";let n=e.toString();if(!Ue(t))return n;let i=t.length;return n.padStart(i,"0")}function yt(e,t){let n=We(e),i=We(t),r=n+i;return Fh(r,e)}function ni(e,t){let n=We(e),i=We(t);return n<i?-1:n>i?1:0}function ii(e,t){return ni(e,t)<=0?e:t}function ri(e,t){return ni(e,t)>=0?e:t}function bl(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,n)=>ii(t,n))}function Ol(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,n)=>ri(t,n))}function wl(e){return{prefix:e,baseSuffix:null}}function Nl(e,t){let n=ei(e);return{prefix:ti(e),baseSuffix:yt(n,t)}}function xl(e){return{prefix:e,baseSuffix:null}}function Fl(e,t){return Rl(e,t)?"parentConversion":Ll(e,t)?"pasteReference":"noContext"}var si=class{prefixMap=new Map;processedIds=new Set;defaultPrefix;suffixIncrement;constructor(t={}){this.defaultPrefix=t.defaultPrefix??"A",this.suffixIncrement=t.suffixIncrement??"10"}extractPrefix(t){return ti(t)}extractSuffix(t){return ei(t)}analyzeCustomId(t){return{prefix:this.extractPrefix(t),suffix:this.extractSuffix(t)}}_updatePrefixStats(t,n){if(!this.prefixMap.has(t)){this.prefixMap.set(t,{min:n,max:n,next:n,quantity:1,usedSuffixes:new Set([n])}),this._recalculateNext(t);return}let i=this.prefixMap.get(t);i.usedSuffixes.has(n)||(i.usedSuffixes.add(n),i.min=ii(n,i.min),i.max=ri(n,i.max),i.quantity+=1,this._recalculateNext(t))}_recalculateNext(t){let n=this.prefixMap.get(t);if(!n)return;let i=this.getNextAvailableSuffix(t);n.next=i??this.suffixIncrement}getPrefixStats(t){let n=this.prefixMap.get(t);return n?{min:n.min,max:n.max,next:n.next,quantity:n.quantity}:null}getNextSuffix(t){let n=this.prefixMap.get(t);return n?n.next:this.suffixIncrement}getAllPrefixes(){return Array.from(this.prefixMap.keys())}registerCustomId(t){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:n,suffix:i}=this.analyzeCustomId(t);if(!n&&!i)return{prefix:n,suffix:i};if(this.prefixMap.has(n)){let r=this.prefixMap.get(n);r.usedSuffixes.has(i)||(r.usedSuffixes.add(i),r.min=ii(i,r.min),r.max=ri(i,r.max),r.quantity+=1,this._recalculateNext(n))}else this.prefixMap.set(n,{min:i,max:i,next:yt(i,this.suffixIncrement),quantity:1,usedSuffixes:new Set([i])});return this.processedIds.add(t),{prefix:n,suffix:i}}releaseCustomId(t=null){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:n,suffix:i}=this.analyzeCustomId(t);if(!this.prefixMap.has(n))return{prefix:n,suffix:i};let r=this.prefixMap.get(n);if(r.usedSuffixes.has(i)){let s=r.quantity-1;if(s===0)this.prefixMap.delete(n);else{let a=new Set(r.usedSuffixes);a.delete(i);let o=Array.from(a);o.length===0?this.prefixMap.delete(n):(r.usedSuffixes=a,r.min=bl(o),r.max=Ol(o),r.quantity=s,this._recalculateNext(n))}}return this.processedIds.delete(t),{prefix:n,suffix:i}}trackCustomIdChange(t,n){let i=this.releaseCustomId(t),r=this.registerCustomId(n);return{oldPrefix:i.prefix,oldSuffix:i.suffix,newPrefix:r.prefix,newSuffix:r.suffix}}_exceedsMaxLength(t){return t.length>20}_shouldSearchForGaps(t){if(!this.prefixMap.has(t))return!1;let n=this.prefixMap.get(t);return`${t}${yt(n.max,this.suffixIncrement)}`.length>20}_findFirstAvailableGap(t){if(!this.prefixMap.has(t))return null;let n=this.prefixMap.get(t),i=this.suffixIncrement;for(;ni(i,n.max)<0;){if(`${t}${i}`.length>20)return null;if(!n.usedSuffixes.has(i))return i;i=yt(i,this.suffixIncrement)}return null}_generateDefaultCustomId(){let t=this.getNextAvailableSuffix(this.defaultPrefix);if(t===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}${t}`}getNextAvailableSuffix(t,n=null){if(!this.prefixMap.has(t)){let o=n&&Ue(n)?n:this.suffixIncrement;return`${t}${o}`.length>20?null:o}let i=this.prefixMap.get(t),r=this.suffixIncrement;if(!n||!Ue(n)){let o=yt(i.max,r);return`${t}${o}`.length>20?null:o}let s=n;for(let o=0;o<100;o++){if(`${t}${s}`.length>20)return null;if(!i.usedSuffixes.has(s))return s;s=yt(s,r)}let a=yt(i.max,r);return`${t}${a}`.length>20?null:a}generateNextCustomId(t){let n=this.getNextAvailableSuffix(t);if(n===null)return this._generateDefaultCustomId();if(this.prefixMap.has(t)){let r=this.prefixMap.get(t),s=0;for(;r.usedSuffixes.has(n)&&s<1e4;){let a=this.getNextAvailableSuffix(t,yt(n,this.suffixIncrement));if(a===null)return this._generateDefaultCustomId();n=a,s++}}let i=`${t}${n}`;return this._exceedsMaxLength(i)&&(i=this._generateDefaultCustomId()),i}populateFromActivities(t){if(!Array.isArray(t))return this;let n=[...new Set(t.filter(i=>i&&typeof i.custom_id=="string"&&i.custom_id).map(i=>i.custom_id))];for(let i of n){if(this.processedIds.has(i))continue;let{prefix:r,suffix:s}=this.analyzeCustomId(i);(r||s)&&(this._updatePrefixStats(r,s),this.processedIds.add(i))}return this}getDefaults(){return{prefix:this.defaultPrefix,increment:this.suffixIncrement}}generateCustomIdForNewChild(t){let{activity:n,useActivityCustomIdAsReference:i=!1}=t,r=Pl(n),s=Fl(r,i),{prefix:a,baseSuffix:o}=this._applyGenerationStrategy(s,r),c=null;if(s==="parentConversion"&&this.prefixMap.has(a)){let f=this.prefixMap.get(a).max;c=yt(f,this.suffixIncrement)}s==="parentConversion"&&this.releaseCustomId(r);let l=s==="parentConversion"&&c?c:o,d=this.getNextAvailableSuffix(a,l);if(d===null){let f=this._generateDefaultCustomId();return this.registerCustomId(f),f}let u=`${a}${d}`;return this._exceedsMaxLength(u)&&(u=this._generateDefaultCustomId()),this.registerCustomId(u),u}_applyGenerationStrategy(t,n){switch(t){case"parentConversion":return wl(this.defaultPrefix);case"pasteReference":return Nl(n,this.suffixIncrement);default:return xl(this.defaultPrefix)}}generateCustomIdForRestoredChild(t=null){if(t){let i=t.trim();if(i.length>0){let r=this.extractPrefix(i),s=this.extractSuffix(i),a=yt(s,this.suffixIncrement),o=this.getNextAvailableSuffix(r,a);if(o===null){let l=this._generateDefaultCustomId();return this.registerCustomId(l),l}let c=`${r}${o}`;return this._exceedsMaxLength(c)&&(c=this._generateDefaultCustomId()),this.registerCustomId(c),c}}let n=this.generateNextCustomId(this.defaultPrefix);return this.registerCustomId(n),n}clear(){this.prefixMap.clear(),this.processedIds.clear()}getTotalPrefixes(){return this.prefixMap.size}hasPrefix(t){return this.prefixMap.has(t)}isCustomIdInUse(t,n=null){if(!t||typeof t!="string"||!t.trim())return!1;let i=t.trim();return n&&i===n.trim()?!1:this.processedIds.has(i)}};var Mh=new Set([$e,te,Ut]);function wr(e,t){return Mh.has(e)&&typeof t=="string"?new Date(t):t}var ai=class{_journal=null;begin(){this._journal={dirty:new Set,before:new Map,ops:[],linkFieldCaptured:new Set,correlativeBefore:new Map,scheduledBefore:new Map}}peek(){return this._journal}end(){this._journal=null}note(t,n){let i=this._journal;i&&(i.before.has(t)||i.before.set(t,Nr(n)),i.dirty.add(t))}noteInsert(t){this._journal?.ops.push({kind:"insert",activityId:t})}noteRemove(t,n){this._journal?.ops.push({kind:"remove",activityId:t,before:Nr(n)})}noteLinkAdd(t){this._journal?.ops.push({kind:"link-add",linkId:t})}noteLinkRemove(t,n){this._journal?.ops.push({kind:"link-remove",linkId:t,before:Ml(n)})}noteCorrelativeBefore(t,n){let i=this._journal;!i||i.correlativeBefore.has(t)||i.correlativeBefore.set(t,n)}noteScheduledBefore(t,n){let i=this._journal;!i||i.scheduledBefore.has(t)||i.scheduledBefore.set(t,Nr(n))}noteLinkField(t,n){let i=this._journal;!i||i.linkFieldCaptured.has(t)||(i.linkFieldCaptured.add(t),i.ops.push({kind:"link-field",linkId:t,before:Ml(n)}))}};function Nr(e){return{...e,start_date:new Date(e.start_date),end_date:new Date(e.end_date),constraint_date:e.constraint_date?new Date(e.constraint_date):null,$source:[...e.$source],$target:[...e.$target]}}function Ml(e){return{...e}}var oi=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let n=Wl(t);return this.reader.getCalendar(n??Me)}getClosestWorkTime(t){let n=`${Fr(t.task)}|${t.dir}|${t.date.getTime()}`;return xr(this._cache.closestWorkTime,n,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:at.HOUR}))}calculateEndDate(t){let n=`${Fr(t.task)}|${t.start_date.getTime()}|${t.duration}`;return xr(this._cache.endDate,n,()=>this.resolveCalendar(t.task).calculateEndDate(t.start_date,t.duration))}calculateDuration(t){let n=`${Fr(t.task)}|${t.start_date.getTime()}|${t.end_date.getTime()}`;return xr(this._cache.duration,n,()=>this.resolveCalendar(t.task).calculateDuration(t.start_date,t.end_date))}clearCache(){this._cache.closestWorkTime.clear(),this._cache.endDate.clear(),this._cache.duration.clear()}};function xr(e,t,n){let i=e.get(t);if(i!==void 0)return i;let r=n();return e.set(t,r),r}var Wh="__default__";function Wl(e){if(!e)return null;let t=e.calendar_id;return t==null?null:String(t)}function Fr(e){return Wl(e)??Wh}var ci=class{constructor(t){this.activities=t}activities;_childrenByParent=new Map;_dirty=!1;markDirty(){this._dirty=!0}getChildren(t){return this._dirty&&(this.rebuild(),this._dirty=!1),this._childrenByParent.get(String(t))??[]}isChildOf(t,n){let i=this.activities.get(t)?.parent,r=0,s=this.activities.size;for(;i&&!b(i);){if(i===n)return!0;if(++r>s)return!1;i=this.activities.get(i)?.parent}return!1}getParent(t){let n=this.activities.get(t)?.parent;return!n||b(n)?null:this.activities.get(n)??null}getParentId(t){let n=this.activities.get(t);return n?n.parent??0:0}addChild(t,n){if(this._dirty||b(t))return;let i=String(t),r=this._childrenByParent.get(i);r?r.includes(n)||r.push(n):this._childrenByParent.set(i,[n])}rebuild(){this._childrenByParent.clear();for(let t of this.activities.values()){if(b(t.parent))continue;let n=String(t.parent),i=this._childrenByParent.get(n)??[];i.push(t.id),this._childrenByParent.set(n,i)}}};var ui=class{_activities=new Map;_links=new Map;_hierarchy;_cache={ids:null,visualOrderIds:null};_writeCapture=new ai;_calendar;_flags;constructor(t){for(let n of t.activities)this._activities.set(n.id,n);for(let n of t.links)this._links.set(String(n.id),n);this._calendar=new oi(Gc(t.calendars)),this._flags=Bh(t),this._hierarchy=new ci(this._activities),this._hierarchy.rebuild()}getAllActivities(){return Array.from(this._activities.values())}getAllLinks(){return Array.from(this._links.values())}getAllIds(){return this._cache.ids?this._cache.ids:(this._cache.ids=Array.from(this._activities.keys()),this._cache.ids)}activityCount(){return this._activities.size}getVisualOrderIds(){return this._cache.visualOrderIds?this._cache.visualOrderIds:(this._cache.visualOrderIds=Ua(this).map(t=>String(t.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null}forEachActivity(t){for(let[n,i]of this._activities)t(i,n)}getParentId(t){return this._hierarchy.getParentId(t)}getActivity(t){return this._activities.get(String(t))??null}getLink(t){return this._links.get(String(t))??null}activityExists(t){return this._activities.has(String(t))}getChildren(t){return this._hierarchy.getChildren(t)}isChildOf(t,n){return this._hierarchy.isChildOf(t,n)}getParent(t){return this._hierarchy.getParent(t)}getClosestWorkTime(t){return this._calendar.getClosestWorkTime(t)}calculateEndDate(t){return this._calendar.calculateEndDate(t)}calculateDuration(t){return this._calendar.calculateDuration(t)}clearCalendarCache(){this._calendar.clearCache()}get calendarReader(){return this._calendar.reader}batchUpdate(t){t()}updateActivity(t){}getLiveActivity(t){return this.getActivity(t)}getFlags(){return{...this._flags,allCheckedTaskIds:[...this._flags.allCheckedTaskIds]}}getProjectEnd(){return null}beginWriteCapture(){this._writeCapture.begin()}peekWriteCapture(){return this._writeCapture.peek()}endWriteCapture(){this._writeCapture.end()}setActivityField(t,n,i){let r=this.getActivity(t);r&&(this._writeCapture.note(String(t),r),r[n]=wr(n,i),n===tt.PARENT&&this._hierarchy.markDirty(),Ul(n)&&(this._cache.visualOrderIds=null))}setActivityFields(t,n){let i=this.getActivity(t);if(!i)return;this._writeCapture.note(String(t),i);let r=!1;for(let s of Object.keys(n))Reflect.set(i,s,wr(s,n[s])),s===tt.PARENT&&(r=!0),Ul(s)&&(this._cache.visualOrderIds=null);r&&this._hierarchy.markDirty()}addLink(t){this._writeCapture.noteLinkAdd(String(t.id)),this._links.set(String(t.id),{...t});let n=this.getActivity(t.source);n&&(n.$source=di(n.$source,t.id));let i=this.getActivity(t.target);i&&(i.$target=di(i.$target,t.id))}getWorkingHoursPerDayForActivity(t){let n=this.getActivity(t);if(!n)return Mr;let i=this.calendarReader.getCalendar(String(n.calendar_id));return i?Uh(i,n.start_date):Mr}setLinkField(t,n,i){let r=this.getLink(t);r&&(this._writeCapture.noteLinkField(String(t),r),r[n]=i)}removeLink(t){let n=this.getLink(t);if(!n)return;this._writeCapture.noteLinkRemove(String(t),n),this._links.delete(String(t));let i=this.getActivity(n.source);i&&(i.$source=li(i.$source,n.id));let r=this.getActivity(n.target);r&&(r.$target=li(r.$target,n.id))}addActivity(t){this._writeCapture.noteInsert(String(t.id)),this._activities.set(t.id,t),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.addChild(t.parent,t.id)}removeActivity(t){let n=this.getActivity(t);n&&this._writeCapture.noteRemove(String(t),n),this._activities.delete(t),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}noteCorrelativeBefore(t,n){this._writeCapture.noteCorrelativeBefore(t,n)}noteScheduledBefore(t,n){this._writeCapture.noteScheduledBefore(t,n)}restoreFromCapture(){let t=this._writeCapture.peek();if(!t)return;let{ops:n,before:i,correlativeBefore:r,scheduledBefore:s}=t;this._undoLinkAdds(n),this._undoInserts(n),this._reInsertRemovedActivities(n),this._reAddRemovedLinks(n),this._restoreLinkFields(n),this._restoreCorrelatives(r),this._restoreActivityFields(s),this._restoreActivityFields(i),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}_restoreCorrelatives(t){for(let[n,i]of t){let r=this._activities.get(n);r&&(r.correlative_id=i)}}_undoLinkAdds(t){for(let n of t)n.kind==="link-add"&&this._detachLink(n.linkId)}_undoInserts(t){for(let n of t)n.kind==="insert"&&this._activities.delete(n.activityId)}_reInsertRemovedActivities(t){for(let n of t)n.kind==="remove"&&this._activities.set(n.activityId,n.before)}_reAddRemovedLinks(t){for(let n of t)n.kind==="link-remove"&&this._attachLink(n.before)}_restoreLinkFields(t){for(let n of t)n.kind==="link-field"&&this._links.has(n.linkId)&&this._links.set(n.linkId,n.before)}_restoreActivityFields(t){for(let[n,i]of t){let r=this._activities.get(n);r&&this._restoreScalarFields(r,i)}}_restoreScalarFields(t,n){for(let i of Object.keys(t))i==="$source"||i==="$target"||Object.hasOwn(n,i)||Reflect.deleteProperty(t,i);for(let i of Object.keys(n))i==="$source"||i==="$target"||Reflect.set(t,i,Reflect.get(n,i))}_attachLink(t){this._links.set(String(t.id),{...t});let n=this.getActivity(t.source);n&&(n.$source=di(n.$source,t.id));let i=this.getActivity(t.target);i&&(i.$target=di(i.$target,t.id))}_detachLink(t){let n=this.getLink(t);if(!n)return;this._links.delete(String(t));let i=this.getActivity(n.source);i&&(i.$source=li(i.$source,n.id));let r=this.getActivity(n.target);r&&(r.$target=li(r.$target,n.id))}},Mr=8;function Ul(e){return e===tt.PARENT||e===v.CORRELATIVE_ID}function Uh(e,t){let n=De(e,It(t)),i=Ee(e,n),r=e.calculateDuration(n,i);return r>0?r:Mr}function li(e,t){return e.filter(n=>String(n)!==String(t))}function di(e,t){return e.includes(t)?e:[...e,t]}function Bh(e){let t=e.runtimeFlags??{};return{isPasting:!!t.isPasting,isBulkOperation:!!t.isBulkOperation,dragWithMultiple:!!t.dragWithMultiple,draggingSingleMilestone:!!t.draggingSingleMilestone,creatingActivity:!1,avoidAutoScheduleBeforeDrag:!1,maxPerformance:!!t.maxPerformance,allCheckedTaskIds:[]}}function Bl(e){let t=[];e.forEachActivity((n,i)=>{n.type==="project"&&e.getChildren(String(i)).length===0&&t.push(String(i))});for(let n of t)e.setActivityField(n,tt.TYPE,Ce),jh(e,n)}function jh(e,t){let n=e.getActivity(t);if(!n||!n.start_date||n.duration==null)return;let i=new Date(n.start_date);i.setUTCHours(0,0,0,0);let r=e.getClosestWorkTime({date:i,dir:q.FUTURE,task:n});if(r.getTime()===n.start_date.getTime())return;let s=e.calculateEndDate({start_date:r,duration:n.duration,task:n});e.setActivityField(t,v.START_DATE,r),e.setActivityField(t,v.END_DATE,s)}function jl(e,t,n){let i=e.get(t);i?i.push(n):e.set(t,[n])}function Hh(e){let t=new Map,n=new Map;for(let i of e)jl(t,String(i.source),String(i.id)),jl(n,String(i.target),String(i.id));return{sourceByActivity:t,targetByActivity:n}}function $h(e,t,n){let i=Oa(e,t);return i.$source=n.sourceByActivity.get(e.id)??[],i.$target=n.targetByActivity.get(e.id)??[],i}function Yh(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function Vh(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function Hl(e){return{id:String(e.id),worktime:Vh(e.worktime)}}function $l(e,t,n,i,r=[]){let s=Hh(t),a=e.map(l=>$h(l,i,s)),o=t.map(Yh),c=[...n.map(Hl),...r.map(Hl)];return{activities:a,links:o,calendars:c}}var Pt={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function Yl(e){let t=e.clock??null,n=t?Te(t()):null,i=e.reporter??ne,r=Qn({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},i),s=r.sector;s.statusCriteria=Qe(e.statusCriteria);let a=r.calendars,o=r.baseCalendars??[],c=$l(r.activities,r.links,r.calendars,s.hoursPerDay,o),l=new ui(c),d=new mn(l,i);Bl(l);let u=Il({knownIds:r.activities.map(S=>S.id)}),f=Tl({knownIds:r.links.map(S=>S.id)}),p=Dl({knownIds:r.activities.map(S=>S.unique_correlative_id)}),A=new si({defaultPrefix:s.customIdPrefix,suffixIncrement:s.customIdIncrement});if(A.populateFromActivities(r.activities),e.baselinePoints&&e.baselinePoints.length>0){let S=o.find(T=>T.baseDefault)?.id??null;Kn(l,e.baselinePoints,n,S)}let I=Va({state:l,sector:s,scheduler:d,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:n??void 0});return{sector:s,state:l,scheduler:d,activityIdGen:u,linkIdGen:f,uidGen:p,customIdTracker:A,calendars:a,baseCalendars:o,clock:t,reporter:i,initPromise:I}}var fi=class{_status=Pt.READY;_dispatchInFlight=!1;coreRuntime;_undo=new Jn;_opQueue=Promise.resolve();_mutationEpoch=0;_cpComputedEpoch=0;constructor(t){let n=Yl(t);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(r=>[r.id,r])),baseCalendars:n.baseCalendars,reporter:n.reporter},this._initPromise=n.initPromise.then(()=>{this._status!==Pt.DESTROYED&&this._saveTracker.init(this.getAllActivitiesView(),this.getAllLinksView())}),this._criticalPathReady=this._initPromise.then(()=>this._enqueue(()=>this._runCriticalPathAndCapture()));let i=t.criticalPathOnLoad===!0;this._ready=i?this._criticalPathReady.then(()=>{}):this._initPromise}get ready(){return this._ready}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return this.coreRuntime.sector}getActivityView(t,n="days"){return this.assertReady(),ac(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay,t,n)}getAllActivitiesView(t="days"){return this.assertReady(),oc(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay,t)}getChildrenView(t,n="days"){return this.assertReady(),dc(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay,t,n)}getLinkView(t,n="days"){return this.assertReady(),pc(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay,t,n)}getAllLinksView(t="days"){return this.assertReady(),hc(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay,t)}getProperty(t,n,i){this.assertReady();let r=this.coreRuntime.state.getActivity(t);if(!r)return null;let s=Reflect.get(r,n);return n===Qt?hr(s,this.coreRuntime.sector.hoursPerDay,i?.unit??"days"):s}getAllIds(){return this.assertReady(),cc(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),lc(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),mr(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),uc(this.coreRuntime.state)}getVisualOrderIds(){return this.assertReady(),this.coreRuntime.state.getVisualOrderIds()}hasChild(t){return this.assertReady(),fc(this.coreRuntime.state,t)}getCalendar(t){return this.assertReady(),this.coreRuntime.calendars.get(t)??null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values())}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars}isCustomIdInUse(t,n=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,n)}getProjectWorkHours(){return this.assertReady(),Lc(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(this.getAllLinksView())}markLinksPersisted(){this._saveTracker.snapshotLinks(this.getAllLinksView())}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(this.getAllActivitiesView())}markActivitiesPersisted(){this._saveTracker.snapshotActivities(this.getAllActivitiesView())}applyBaselines(t){this.assertReady();let n=this.coreRuntime.clock?Te(this.coreRuntime.clock()):null,i=this.coreRuntime.baseCalendars.find(r=>r.baseDefault)?.id??null;return Pc(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay,t,n,i)}recomputeAllPonderators(t){return this.assertReady(),Dc(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay,t)}recomputeAllProgressRollup(){return this.assertReady(),Ec(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay)}setStatusCriteria(t){this.assertReady();let n=Qe(t);return this.coreRuntime.sector.statusCriteria=n,Rc(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay,n)}allocateActivityId(){return this.assertReady(),this.coreRuntime.activityIdGenerator.next()}createActivity(t,n="days"){if(this.assertReady(),this._dispatchInFlight)throw new Error("[ScheduleCore] createActivity called during an in-flight dispatch");let i={kind:"activity-create",...t};this.coreRuntime.state.beginWriteCapture();let r;try{r=$o(i,{adapter:this.coreRuntime.state,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker}),r.ok||this._rollback()}catch(a){throw this._rollback(),a}finally{this.coreRuntime.state.endWriteCapture()}if(!r.ok)return r;let s=this.coreRuntime.sector.hoursPerDay;return{ok:!0,activity:mt(r.activity,s,n),changes:xe(r.changes,s,n)}}_enqueue(t){let n=this._opQueue.then(t,t);return this._opQueue=n.then(()=>{},()=>{}),n}async dispatch(t,n={}){return this._enqueue(()=>this._dispatchInner(t,n))}async _dispatchInner(t,n={}){this.assertReady();let i=qc(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,inputUnit:n.inputUnit??"days"}),r=el(t);this.coreRuntime.state.beginWriteCapture(),this._dispatchInFlight=!0;let s;try{s=await rc(t,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,uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,now:this.coreRuntime.clock?Te(this.coreRuntime.clock()):null}),s.ok||this._rollback()}catch(a){throw this._rollback(),a}finally{this._dispatchInFlight=!1,this.coreRuntime.state.endWriteCapture()}if(s.ok&&r&&nl(s.changes)){let a=Xc(this.coreRuntime.state,s.changes);this._undo.record(Er(s.changes,s.__beforeSnap,s.__beforeLinks,a.afterSnap,a.afterLinks),Zc(t),Date.now())}return s.ok?(n.skipCriticalPath&&this._mutationEpoch++,{...s,changes:xe(s.changes,this.coreRuntime.sector.hoursPerDay,n.outputUnit??"days")}):s}recomputeCriticalPath(){return this._enqueue(()=>this._recomputeCriticalPathIfStale())}async _recomputeCriticalPathIfStale(){if(this._status===Pt.DESTROYED)return null;let t=this._mutationEpoch;if(this._cpComputedEpoch===t)return null;let n=await this._runCriticalPathAndCapture();return this._cpComputedEpoch=t,n}async _runCriticalPathAndCapture(){if(this._status===Pt.DESTROYED)return{changes:{source:{kind:"init"},activities:[],links:[],calendars:[],trackingEvents:[]}};this.coreRuntime.state.beginWriteCapture();let t;try{await bn(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay),t=G(this.coreRuntime.state,{source:{kind:"init"},beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay})}finally{this.coreRuntime.state.endWriteCapture()}return{changes:t}}undo(t){return this._enqueue(async()=>{this.assertReady();let n=this._undo.takeUndo();if(!n)return null;il(this.coreRuntime.state,n),this._mutationEpoch++,Pr(n)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(n),this._undo.resetCoalesce();let i=Rr(this.coreRuntime.state,n,"before");return xe(i,this.coreRuntime.sector.hoursPerDay,t?.outputUnit??"days")})}redo(t){return this._enqueue(async()=>{this.assertReady();let n=this._undo.takeRedo();if(!n)return null;rl(this.coreRuntime.state,n),this._mutationEpoch++,Pr(n)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(n),this._undo.resetCoalesce();let i=Rr(this.coreRuntime.state,n,"after");return xe(i,this.coreRuntime.sector.hoursPerDay,t?.outputUnit??"days")})}clearHistory(){this._undo.clear()}canUndo(){return this._undo.canUndo()}canRedo(){return this._undo.canRedo()}undoDepth(){return this._undo.undoDepth()}_resyncCustomIdTrackerFromModel(){this.coreRuntime.customIdTracker.clear(),this.coreRuntime.customIdTracker.populateFromActivities(this.coreRuntime.state.getAllActivities())}destroy(){this.coreRuntime.calendars.clear(),this._saveTracker.clear(),this._status=Pt.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new Xn;assertReady(){if(this._status===Pt.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===Pt.POISONED)throw new Error("[ScheduleCore] instance is poisoned (a rollback failed) \u2014 reload from backend")}_rollback(){try{this.coreRuntime.state.restoreFromCapture()}catch(t){throw this._status=Pt.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",t),t}}};function Vl(e,t){let n=new Map(e.map(i=>[String(i.id),i]));return t.filter(i=>{let r=n.get(String(i.id));return r?r.lag!==i.lag||r.type!==i.type:!1})}var Gl=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var Kl={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 z={INLINE_EDIT:"inline-edit",DATES_BATCH:"dates-batch",BULK_EDIT:"bulk-edit",LINK_CREATE:"link-create",LINK_UPDATE:"link-update",LINK_DELETE:"link-delete",LINKS_BATCH:"links-batch",ACTIVITY_CREATE:"activity-create",ACTIVITY_DELETE:"activity-delete",ACTIVITY_MOVE:"activity-move",ACTIVITY_INDENT:"activity-indent",ACTIVITY_OUTDENT:"activity-outdent",ACTIVITY_SET_PROGRESS:"activity-set-progress",ACTIVITY_PASTE:"activity-paste",SELECTION_TOGGLE:"selection-toggle",SELECTION_REPLACE:"selection-replace",VISIBILITY_SET:"visibility-set",SIR_SYNC:"sir-sync"},Gh={[z.INLINE_EDIT]:!0,[z.DATES_BATCH]:!0,[z.BULK_EDIT]:!0,[z.LINK_CREATE]:!0,[z.LINK_UPDATE]:!0,[z.LINK_DELETE]:!0,[z.LINKS_BATCH]:!0,[z.ACTIVITY_CREATE]:!0,[z.ACTIVITY_DELETE]:!0,[z.ACTIVITY_MOVE]:!0,[z.ACTIVITY_INDENT]:!0,[z.ACTIVITY_OUTDENT]:!0,[z.ACTIVITY_SET_PROGRESS]:!0,[z.ACTIVITY_PASTE]:!0,[z.SELECTION_TOGGLE]:!0,[z.SELECTION_REPLACE]:!0,[z.VISIBILITY_SET]:!0,[z.SIR_SYNC]:!0},ql=Object.keys(Gh);var zl={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return ed(Kh);})();
1
+ "use strict";var ScheduleCore=(()=>{var zr=Object.defineProperty;var jl=Object.getOwnPropertyDescriptor;var Vl=Object.getOwnPropertyNames;var Yl=Object.prototype.hasOwnProperty;var $l=(e,t)=>{for(var r in t)zr(e,r,{get:t[r],enumerable:!0})},Gl=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Vl(t))!Yl.call(e,n)&&n!==r&&zr(e,n,{get:()=>t[n],enumerable:!(i=jl(t,n))||i.enumerable});return e};var Kl=e=>Gl(zr({},"__esModule",{value:!0}),e);var Gh={};$l(Gh,{ACTIVITY_TYPE:()=>We,CALENDAR_UNIT:()=>et,COLUMN:()=>E,CONSTRAINT_TYPE:()=>$,CONSTRAINT_TYPE_TO_LABEL:()=>Wl,CREATION_KIND:()=>Hl,DEFAULT_HOURS_PER_DAY:()=>Ul,DISPATCH_ACTION_KIND:()=>X,DISPATCH_ACTION_KINDS:()=>Bl,DISPATCH_TRACK_EVENT:()=>yt,LINK_CODE_TO_TYPE:()=>Ht,LINK_TYPE:()=>V,LINK_TYPE_CODE:()=>Na,NEW_ACTIVITY_DEFAULTS:()=>Cr,REJECTION_REASON:()=>R,ROOT_PARENT_ID:()=>H,ScheduleCore:()=>Kr,WORK_TIME_DIRECTION:()=>q,applyBaselinePoints:()=>Er,checkNoUpdatedLinks:()=>Fl,computeExpectedProgress:()=>mi,expectedProgressFromBaseline:()=>ce,getActiveBaseline:()=>pt,getUnsavedActivities:()=>Ml,isRootParent:()=>O,normalizeParentKey:()=>Bt,parseFromBackend:()=>Nr,recomputeAllPonderators:()=>Tr,recomputeAllProgressRollup:()=>_r,willRunCriticalPath:()=>xc,yieldToBrowser:()=>rt});var ut=class{items=[];head=0;enqueue(t){this.items.push(t)}dequeue(){if(this.head>=this.items.length)return;let t=this.items[this.head];return this.head+=1,t}peek(){if(!(this.head>=this.items.length))return this.items[this.head]}get size(){return this.items.length-this.head}isEmpty(){return this.head>=this.items.length}};var xe=e=>String(e);function An(e){let{clickedId:t,isChecked:r,currentSelection:i,hierarchy:n,isFrozen:a,exists:s,autoCheckParents:o}=e,c=xe(t),l=new Set([...i].map(String)),d=new Set(l),u=zl(c,n).filter(s),f=u.filter(v=>!a(v)),p=r&&f.length<u.length;r&&!p?d.add(c):d.delete(c);for(let v of f)r?d.add(v):d.delete(v);return p||ql({id:c,isChecked:r,autoCheckParents:o,hierarchy:n,isFrozen:a,exists:s,next:d}),{nextSelection:d,changed:Jl(l,d),parentBlocked:p}}function zl(e,t){let r=[],i=new ut;i.enqueue(e);let n=new Set([e]);for(;!i.isEmpty();){let a=i.dequeue();for(let s of t.getChildrenIds(a)){let o=xe(s);n.has(o)||(n.add(o),r.push(o),i.enqueue(o))}}return r}function ql(e){let{id:t,isChecked:r,autoCheckParents:i,hierarchy:n,isFrozen:a,exists:s,next:o}=e,c=n.getParentId(t);for(;c!==null&&typeof c<"u";){let l=xe(c);if(a(l))return;let d=n.getChildrenIds(l).map(xe).filter(s),u=d.some(a),f=d.filter(S=>!a(S)),v=f.length>0&&f.every(S=>o.has(S))&&!u;if(r){if(!i||!v||o.has(l))return;o.add(l)}else{if(v||!o.has(l))return;o.delete(l)}c=n.getParentId(l)}}function Jl(e,t){let r=[],i=[];for(let n of t)e.has(n)||r.push(n);for(let n of e)t.has(n)||i.push(n);return{checked:r,unchecked:i}}function Jt(e){return(e.pendingRequestIds?.length??0)>0}var R={CANNOT_EDIT:"cannot_edit",PARSE_ERROR:"parse_error",INVALID:"invalid",CUSTOM_ID_DUPLICATE:"custom_id_duplicate",INVALID_LINK_TYPE:"invalid_link_type",INVALID_LINK_LAG:"invalid_link_lag",INVALID_VALUE:"invalid_value",NO_PIPELINE_FOR_COLUMN:"no_pipeline_for_column",ACTIVITY_NOT_FOUND:"activity_not_found",PARENT_NOT_FOUND:"parent_not_found",ACTIVITY_IDS_EMPTY:"activity_ids_empty",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",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var Cn=(e,t)=>{let r=e.getActivity(t);return r!=null&&Jt(r)},In=(e,t,r)=>{let i=[],n=(a,s)=>{let o=t.isChecked(a);t.setChecked(a,s)&&i.push({activityId:a,checked:{before:o,after:s}})};for(let a of r.checked)n(a,!0);for(let a of r.unchecked)n(a,!1);return{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:i}};function kn(e,t){let{adapter:r}=t,i=e.activityId;if(!r.getActivity(i))return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let n=e.frozenIds?new Set(e.frozenIds):null,a=n?o=>n.has(o):o=>Cn(r,o),s=An({clickedId:i,isChecked:e.isChecked,currentSelection:new Set(r.checkedIds().map(String)),hierarchy:{getChildrenIds:o=>r.getChildren(o),getParentId:o=>{let c=r.getParentId(o);return!c||c==="0"?null:String(c)}},isFrozen:a,exists:o=>r.activityExists(o),autoCheckParents:e.autoCheckParents??!1});return{ok:!0,changes:In(e,r,s.changed)}}function Sn(e,t){let{adapter:r}=t,i=new Set(e.activityIds.map(String).filter(s=>r.activityExists(s)).filter(s=>!Cn(r,s))),n=new Set(r.checkedIds().map(String)),a={checked:[...i].filter(s=>!n.has(s)),unchecked:[...n].filter(s=>!i.has(s))};return{ok:!0,changes:In(e,r,a)}}function Dn(e,t){let{adapter:r}=t,i=new Set(e.visibleIds.map(String)),n=[];return r.forEachActivity((s,o)=>{let c=String(o),l=i.has(c),d=r.isVisible(c);d!==l&&(r.setVisible(c,l),n.push({activityId:c,visible:{before:d,after:l}}))}),{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:n}}}var Tn="text";var _n="description";var Pn="duration";var En="progress";var Rn="cost";var Ln="used_cost";var bn="hhWorkTime";var wn="start_date";var On="end_date";var xn="constraint_type";var Nn="constraint_date";var Fn="calendar_id";var Mn="custom_id";var Wn="subcontractId";var Un="responsables";var Bn="tags";var Hn="custom_predecessors";var jn="custom_sucessors";var Vn="real_work";var Yn="real_cost";var $n="expected_progress";var Gn="expected_progress_base";var Kn="start_base";var zn="end_base";var qn="duration_base";var Jn="cost_base";var Xn="work_base";var Zn="calendarDuration";var Qn="is_critical",ta="earlyStart",ea="earlyFinish",ra="lateStart",ia="lateFinish",na="freeSlack",aa="totalSlack";var sa="correlative_id";var oa="unique_correlative_id";var ca="ponderator";var q={FUTURE:"future",PAST:"past"},et={HOUR:"hour",DAY:"day"},Pt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var Ne="status";var qr="Baseline";function Fe(e){return e==="Actual"?"Actual":qr}var Xl={TEXT:Tn,DESCRIPTION:_n,DURATION:Pn,PROGRESS:En,COST:Rn,USED_COST:Ln,HH_WORK_TIME:bn,START_DATE:wn,END_DATE:On,CONSTRAINT_TYPE:xn,CONSTRAINT_DATE:Nn,CALENDAR_ID:Fn,CUSTOM_ID:Mn,SUBCONTRACT_ID:Wn,RESPONSABLES:Un,TAGS:Bn,CUSTOM_PREDECESSORS:Hn,CUSTOM_SUCESSORS:jn},Zl={REAL_WORK:Vn,REAL_COST:Yn,EXPECTED_PROGRESS:$n,EXPECTED_PROGRESS_BASE:Gn,START_BASE:Kn,END_BASE:zn,DURATION_BASE:qn,COST_BASE:Jn,WORK_BASE:Xn,CALENDAR_DURATION:Zn,IS_CRITICAL:Qn,EARLY_START:ta,EARLY_FINISH:ea,LATE_START:ra,LATE_FINISH:ia,FREE_SLACK:na,TOTAL_SLACK:aa,CORRELATIVE_ID:sa,UNIQUE_CORRELATIVE_ID:oa,PONDERATOR:ca,STATUS:Ne},E={...Xl,...Zl};function la(e,t){throw new Error(t)}function da(e,t){return()=>t()===e}var $={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},Ql={mso:()=>!0,mfo:()=>!0,snlt:(e,t)=>e<t,snet:(e,t)=>e>t,fnlt:(e,t)=>e<t,fnet:(e,t)=>e>t};function fa(e,t,r){if(!t)return{violated:!1};let i=Ql[e];return i?i(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var td=new Set(["mso","snet","snlt"]);function he(e,t,r){return td.has(e)?t:r}function pa(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var ed={snet:{startOfDay:!0,direction:q.FUTURE},snlt:{startOfDay:!0,direction:q.PAST},fnet:{startOfDay:!1,direction:q.FUTURE},fnlt:{startOfDay:!1,direction:q.PAST},mso:{startOfDay:!0,direction:q.FUTURE},mfo:{startOfDay:!1,direction:q.PAST}},Me=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),ua=(e,t)=>new Date(e.getTime()+t*864e5),rd=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function Jr(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=ed[e.constraintType];if(!r)return e.constraintDate;let i=e.constraintDate,n=t.getClosestWorkTime({date:Me(i),dir:q.FUTURE,task:e});if(rd(n,i))return i.getTime()!==Me(i).getTime()?i:r.startOfDay?n:t.getClosestWorkTime({date:ua(Me(i),1),dir:q.PAST,task:e});let a=Me(t.getClosestWorkTime({date:i,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:a,dir:q.FUTURE,task:e}):t.getClosestWorkTime({date:ua(a,1),dir:q.PAST,task:e})}function ha(e,t){let r={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},i=e.constraintType;if(!i||i==="asap"||i==="alap")return r;let n=Jr(e,t);if(!n)return r;let a=o=>t.calculateEndDate({startDate:o,durationHours:e.durationHours,task:e}),s=o=>t.calculateEndDate({startDate:o,durationHours:-e.durationHours,task:e});switch(i){case"snet":return{earliestStart:n,latestStart:null,earliestEnd:a(n),latestEnd:null};case"snlt":return{earliestStart:null,latestStart:n,earliestEnd:null,latestEnd:a(n)};case"fnet":return{earliestStart:s(n),latestStart:null,earliestEnd:n,latestEnd:null};case"fnlt":return{earliestStart:null,latestStart:s(n),earliestEnd:null,latestEnd:n};case"mso":{let o=a(n);return{earliestStart:n,latestStart:n,earliestEnd:o,latestEnd:o}}case"mfo":{let o=s(n);return{earliestStart:o,latestStart:o,earliestEnd:n,latestEnd:n}}default:return r}}function ya(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function Xr(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var V={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"};var We={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},ma={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var Ue=typeof window>"u",Zr=!Ue&&typeof MessageChannel<"u"?new MessageChannel:null;function rt(){return Ue||!Zr?Promise.resolve():new Promise(e=>{Zr.port1.onmessage=()=>e(),Zr.port2.postMessage(null)})}async function Be(e,t){return performance.now()-e<ma.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await rt(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function Xt(e){return Ue||await rt(),e()?{aborted:!1}:{aborted:!0}}function He(e,t){let{inDegree:r,successors:i}=id(e,t),n=nd(r),a=ad(n,r,i),s=a.length<e.length,o=s?sd(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:s,cycleNodes:o}}function id(e,t){let r=new Map,i=new Map;for(let n of e)r.set(n,0),i.set(n,[]);for(let n of t){let a=n.source,s=n.target;!r.has(a)||!r.has(s)||(i.get(a).push(s),r.set(s,(r.get(s)??0)+1))}return{inDegree:r,successors:i}}function nd(e){let t=new ut;for(let[r,i]of e)i===0&&t.enqueue(r);return t}function ad(e,t,r){let i=[];for(;!e.isEmpty();){let n=e.dequeue();i.push(n);for(let a of r.get(n)??[]){let s=(t.get(a)??1)-1;t.set(a,s),s===0&&e.enqueue(a)}}return i}function sd(e,t){let r=new Set(t);return e.filter(i=>!r.has(i))}var je=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=He(t,r),this.cached)}};function ga(e,t){let r=[];for(let i of e)t.has(i)&&r.push(i);return r}var Qr={project:{alwaysSummary:!0,holdsConstraint:!1,carriesCustomId:!1,forcedDuration:null,ponderatorWeight:"recursive-leaf-sum",promotesToProjectOnFirstChild:!1},task:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:null,ponderatorWeight:"own-baseline",promotesToProjectOnFirstChild:!0},milestone:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:0,ponderatorWeight:"zero",promotesToProjectOnFirstChild:!0}};function ti(e){return e==="project"||e==="task"||e==="milestone"}function Ct(e,t){return t||ti(e)&&Qr[e].alwaysSummary}function ye(e){return e==="milestone"}function Et(e){return ti(e)&&Qr[e].promotesToProjectOnFirstChild}var ei="project",Zt="task";function me(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function va(e,t){let r=t.getActivity(e);return r?Ct(r.type,t.getChildren(e).length>0):!1}function Aa(e,t,r){let i=String(t),n=r.getActivity(e);for(;n?.parentId&&String(n.parentId)!=="0";){if(String(n.parentId)===i)return!0;n=r.getActivity(n.parentId)}return!1}function Ca(e,t){let r=[],i=[e];for(;i.length>0;){let n=i.pop(),a=t.getChildren(n);if(a.length===0){String(n)!==String(e)&&r.push(n);continue}for(let s of a)i.push(s)}return r}function od(e){let t=new Map;for(let r of e)Ia(t,String(r.source),r),Ia(t,String(r.target),r);return t}function Ia(e,t,r){let i=e.get(t);if(i){i.push(r);return}e.set(t,[r])}function cd(e,t,r){if(e.length<=1)return e;let i=new Set(e.map(String)),n=[];for(let a of e)ld(a,i,t,r)||n.push(a);return n.length>0?n:e}function ld(e,t,r,i){let n=String(e),a=r.getActivity(e);if(!a||a.autoScheduling===!1)return!1;let s=i.get(n)??[];for(let o of s){if(dd(o))continue;let c=ud(o,n);if(!t.has(String(c)))continue;let l=r.getActivity(c);if(l&&l.autoScheduling!==!1&&fd(o,e,a,c,l))return!0}return!1}function dd(e){return e.source===e.target}function ud(e,t){return String(e.source)===t?e.target:e.source}function fd(e,t,r,i,n){let a=e.lag??0,s=Math.abs(a);return e.target===t&&s<=r.durationHours||e.target===i&&s<=n.durationHours}function Sa(e,t){let r=[],i=od(e),n=0;for(let a of e){let s=va(a.source,t),o=va(a.target,t);if(s&&o||o&&Aa(a.source,a.target,t)||s&&Aa(a.target,a.source,t))continue;if(!s&&!o){r.push(a);continue}let c=s?Ca(a.source,t):[a.source],l=o?Ca(a.target,t):[a.target];if(s&&(c=ka(c,!1,t)),o){let d=cd(l,t,i);if(a.type===V.FINISH_TO_FINISH||a.type===V.START_TO_FINISH){n=pd(r,c,d,a,a.target,t,n);continue}l=ka(d,!0,t)}n=hd(r,c,l,a,n)}return r}function pd(e,t,r,i,n,a,s){let o=a.getActivity(n),c=o?.startDate,l=o?.durationHours??0,d=i.lag??0,u=a.getActivity(i.source),f=s;for(let p of t)for(let v of r){if(String(p)===String(v))continue;let S=a.getActivity(v),A=c&&S&&u?a.calculateDuration({startDate:c,endDate:S.startDate,task:u}):0;e.push({id:`virtual_${i.id}_${f}`,source:p,target:v,type:i.type,lag:i.lag,_sourceLag:0,_targetLag:-l,_trueLag:d+A}),f+=1}return f}function ka(e,t,r){if(e.length<=1)return e;let i=null;for(let a of e){let s=r.getActivity(a),o=t?s?.startDate:s?.endDate;if(!o)continue;let c=o.getTime();(i===null||(t?c<i:c>i))&&(i=c)}if(i===null)return e;let n=e.filter(a=>{let s=r.getActivity(a),o=t?s?.startDate:s?.endDate;return o!=null&&o.getTime()===i});return n.length>0?n:e}function hd(e,t,r,i,n){let a=n;for(let s of t)for(let o of r)String(s)!==String(o)&&(e.push({id:`virtual_${i.id}_${a}`,source:s,target:o,type:i.type,lag:i.lag}),a+=1);return a}var Ve=class{invalidate(){}get(t,r){return Sa(t,r)}};function yd(e){let t=new Map,r=i=>(t.has(i)||t.set(i,new Set),t.get(i));for(let i of e)r(i.source).add(i.id),r(i.target).add(i.id);return{neighbors:t}}function md(e,t,r){let i=new Set,n=new Map,a=new ut;for(a.enqueue(e);!a.isEmpty();){let s=a.dequeue(),o=String(s);if(i.has(o))continue;i.add(o);let c=r.neighbors.get(s);if(c)for(let l of c){let d=t.get(l);if(!d)continue;let u=`${d.source}-${d.target}-${d.type}`;n.has(u)||n.set(u,d);let f=String(d.source)===o?d.target:d.source;i.has(String(f))||a.enqueue(f)}}return Array.from(n.values())}function Da(e,t){let r=new Map;for(let s of t)r.set(s.id,s);let i=yd(t),n=md(e,r,i),a=new Set([String(e)]);for(let s of n)a.add(String(s.source)),a.add(String(s.target));return{activityIds:a,links:n}}function Ta(e,t,r){let i=r.type===V.FINISH_TO_START,n=r.type===V.FINISH_TO_FINISH;if(r._targetLag!==void 0)return{sourceLag:r._sourceLag??0,targetLag:r._targetLag,trueLag:r._trueLag??r.lag??0,isFS:i,isFF:n,isZeroDurationCase:!1};let a=r.lag??0;switch(r.type){case V.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case V.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case V.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case V.START_TO_FINISH:return{sourceLag:-e.durationHours,targetLag:-t.durationHours,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};default:return{sourceLag:0,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1}}}function _a(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:s,isFS:o,isFF:c}=Ta(e,t,r);if(!(n!==0||a!==0||s!==0)){let f=o||c;return t.durationHours===0&&f?{successorStart:i.getClosestWorkTime({date:e.endDate,dir:"past",task:t}),link:r}:{successorStart:i.getClosestWorkTime({date:e.endDate,dir:"future",task:t}),link:r}}let d=o?t:e,u=i.getClosestWorkTime({date:e.endDate,dir:"future",task:d});if(n!==0&&(u=i.calculateEndDate({startDate:u,durationHours:n,task:e})),a!==0&&(u=i.calculateEndDate({startDate:u,durationHours:a,task:t})),s!==0&&(u=i.calculateEndDate({startDate:u,durationHours:s,task:t})),t.durationHours===0){if(o||c)return{successorStart:i.getClosestWorkTime({date:u,dir:"past",task:t}),link:r};let f=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth(),u.getUTCDate()));return{successorStart:i.getClosestWorkTime({date:f,dir:"future",task:t}),link:r}}return{successorStart:i.getClosestWorkTime({date:u,dir:"future",task:t}),link:r}}function Pa(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:s}=Ta(t,e,r),o=i.getClosestWorkTime({date:e.startDate,dir:"past",task:e});return s!==0&&(o=i.calculateEndDate({startDate:o,durationHours:-s,task:e})),a!==0&&(o=i.calculateEndDate({startDate:o,durationHours:-a,task:e})),n!==0&&(o=i.calculateEndDate({startDate:o,durationHours:-n,task:t})),o}function Ea(e,t,r){for(let i of e){let n=t.getActivity(i);if(!n)continue;let a=n.constraintType;if(!a||a===$.ASAP||a===$.ALAP)continue;let s=ha(n,t);!s.earliestStart&&!s.latestStart&&!s.earliestEnd&&!s.latestEnd||r.set(i,{activityId:i,startDate:n.startDate,endDate:n.endDate,drivingLinkId:null,kind:"asap",conflict:!1,earliestStart:s.earliestStart,latestStart:s.latestStart,earliestEnd:s.earliestEnd,latestEnd:s.latestEnd})}}function Ye(e,t,r){let i={earliestStart:t.earliestStart??null,latestStart:t.latestStart??null,earliestEnd:t.earliestEnd??null,latestEnd:t.latestEnd??null},n=t.earliestSchedulingStart??t.latestSchedulingStart??null,a;n===null?a=Xr(e.startDate,i):ya(n,i)?a=n:a=Xr(n,i),t.startDate=a,t.endDate=r.calculateEndDate({startDate:a,durationHours:e.durationHours,task:e})}function Ra(e,t){if(!e||!t)return new Date;let{constraintType:r,constraintDate:i}=e;if(!r||!i)return t;switch(r){case $.MSO:case $.MFO:return new Date(i);case $.SNET:case $.FNET:return i>t?new Date(i):t;case $.SNLT:case $.FNLT:return i<t?new Date(i):t;default:return t}}function gd(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function La(e,t,r){return ri(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function ri(e,t,r){return t.dragWithMultiple&&gd(e,r)}async function wa(e,t,r,i,n,a){let s=new Map;for(let u of t){let f=String(u.target);s.has(f)||s.set(f,[]),s.get(f).push(u)}let o=u=>{let f=a.get(u);if(f?.startDate&&f.endDate)return{startDate:f.startDate,endDate:f.endDate};let p=r.getActivity(u);return p?{startDate:p.startDate,endDate:p.endDate}:{startDate:new Date,endDate:new Date}},c=r.getFlags(),l=i.draggedIds??[],d=performance.now();for(let u of e){let f=await Be(d,n);if(f.aborted)return a;d=f.newSliceStart;let p=r.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||vd(p,r))continue;let v=s.get(String(u))??[],S=null,A=null;for(let k of v){let y=r.getActivity(k.source);if(!y)continue;let g=o(k.source),C={...y,startDate:g.startDate,endDate:g.endDate},P=La(C,c,l),_={...C,startDate:P.startDate,endDate:P.endDate},b=ri(k.source,c,l)?{...k,lag:0}:k,x=_a(_,p,b,r);(!S||x.successorStart>S)&&(S=x.successorStart,A=String(k.id))}let D=a.get(u),m=D?{...D}:{activityId:u,startDate:p.startDate,endDate:p.endDate,drivingLinkId:null,kind:"asap",conflict:!1},T=m.earliestStart||m.latestStart||m.earliestEnd||m.latestEnd;if(!(!S&&!T)){if(S){let k=S;p.type===We.MILESTONE&&(k=Ra(p,S)),m.drivingLinkId=A,m.startDate=k,m.endDate=r.calculateEndDate({startDate:k,durationHours:p.durationHours,task:p}),m.earliestSchedulingStart=k,m.earliestSchedulingEnd=m.endDate}else p.constraintType===$.MSO?m.earliestStart&&(m.startDate=m.earliestStart,m.endDate=m.earliestEnd??r.calculateEndDate({startDate:m.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===$.MFO&&m.latestStart&&(m.startDate=m.latestStart,m.endDate=m.latestEnd??r.calculateEndDate({startDate:m.latestStart,durationHours:p.durationHours,task:p}));Ye(p,m,r),a.set(u,m)}}return a}function vd(e,t){return Ct(e.type,t.getChildren(e.id).length>0)}var H="0";function O(e){return e==null||e===0||e==="0"}function Bt(e){return O(e)?"0":String(e)}async function Oa(e,t,r,i,n,a){let s=new Map(r),o=i.getAllActivities(),c=o.length,l=[];for(let A of o)A.constraintType===$.ALAP&&l.push(A.id);if(l.length===0)return s;let d=new Map,u=new Map;for(let A of t){let D=String(A.source);d.has(D)||d.set(D,[]),d.get(D).push(A);let m=String(A.target);u.has(m)||u.set(m,[]),u.get(m).push(A)}let f=A=>{let D=s.get(A);if(D)return{startDate:D.startDate,endDate:D.endDate};let m=i.getActivity(A);return m?{startDate:m.startDate,endDate:m.endDate}:{startDate:new Date,endDate:new Date}},p=A=>!A.parentId||O(A.parentId)?i.getProjectEnd():f(A.parentId).endDate,v=(A,D)=>{let m=A,T=0;for(;m&&!O(m)&&T++<c+1;){if(String(m)===String(D))return!0;let k=i.getActivity(m);if(!k||!k.parentId)break;m=k.parentId}return!1},S=performance.now();for(let A of e){let D=await Be(S,a);if(D.aborted)return s;S=D.newSliceStart;let m=i.getActivity(A);if(!m||m.constraintType!==$.ALAP||!m.autoScheduling||m.progress===100||Ct(m.type,i.getChildren(A).length>0))continue;let T=p(m);if(!T)continue;let k=T,y=null,g=!1,C=d.get(String(A))??[];for(let M of C){if((M.lag??0)<0)continue;let z=i.getActivity(M.target);if(!z||z.autoScheduling===!1)continue;let ot=f(M.target),Oe={...z,startDate:ot.startDate,endDate:ot.endDate},Ut=Pa(Oe,m,M,i);Ut<k&&(k=Ut),(y===null||Ut<y)&&(y=Ut,g=m.parentId&&!O(m.parentId)?v(M.target,m.parentId):!1)}if(y!==null)if(g)k=y;else{let M=f(A).endDate,z=M.getTime()>T.getTime()?M:T;k=y<z?y:z}else k>T&&(k=T);let P;if(m.durationHours===0&&y===null)P=i.getClosestWorkTime({date:k,dir:"past",task:m});else if(m.durationHours===0)if((u.get(String(A))??[]).some(ot=>ot.type===V.FINISH_TO_START||ot.type===V.FINISH_TO_FINISH)){let ot=new Date(Date.UTC(k.getUTCFullYear(),k.getUTCMonth(),k.getUTCDate()));P=i.getClosestWorkTime({date:ot,dir:"past",task:m})}else P=i.getClosestWorkTime({date:k,dir:"future",task:m});else P=i.getClosestWorkTime({date:k,dir:"future",task:m});let _=i.calculateEndDate({startDate:P,durationHours:-m.durationHours,task:m}),b=s.get(A),x=b?{...b}:{activityId:A,startDate:_,endDate:P,drivingLinkId:null,kind:"alap",conflict:!1};x.startDate=_,x.endDate=P,x.drivingLinkId=null,x.kind="alap",x.earliestSchedulingStart=null,x.earliestSchedulingEnd=null,x.latestSchedulingStart=_,x.latestSchedulingEnd=P,Ye(m,x,i),s.set(A,x)}return s}var Qt={warn(){},error(){}};function ge(e,t){t.cancelled||t.updatedIds.length===0||e.batchUpdate(()=>{for(let r of t.updatedIds){let i=t.plans.get(r);if(!i)continue;let n=e.getLiveActivity(r);n&&(n.startDate=i.startDate,n.endDate=i.endDate,e.updateActivity(r))}})}function xa(e,t){let r=String(t.source),i=String(t.target);if(r===i)return!0;let n=new Map;for(let a of e){let s=String(a.source),o=String(a.target),c=n.get(s)??[];c.push(o),n.set(s,c)}return Ad(n,i,r)}function Ad(e,t,r){if(t===r)return!0;let i=new Set([t]),n=new ut;for(n.enqueue(t);!n.isEmpty();){let a=n.dequeue(),s=e.get(a)??[];for(let o of s){if(o===r)return!0;i.has(o)||(i.add(o),n.enqueue(o))}}return!1}function Rt(e,t){switch(e.kind){case"create":return Cd(e,t);case"update":return Id(e,t);case"delete":return kd(e,t)}}function Cd(e,t){let{port:r}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:"self-link"};let i=r.getActivity(e.source),n=r.getActivity(e.target);if(!i||!n)return{applied:!1,rejected:"activity-missing"};let a=r.getAllLinks();for(let l of a)if(String(l.source)===String(e.source)&&String(l.target)===String(e.target)&&l.type===e.type)return{applied:!1,rejected:"duplicate",linkId:l.id};let s=a.map(l=>({source:l.source,target:l.target}));if(xa(s,{source:e.source,target:e.target}))return{applied:!1,rejected:"cycle"};let o=(t.newLinkId??Sd)(),c={id:o,source:e.source,target:e.target,type:e.type,lag:e.lag};return r.addLink(c),{applied:!0,linkId:o}}function Id(e,t){let{port:r}=t;return r.getLink(e.linkId)?(e.lag!==void 0&&r.setLinkField(e.linkId,"lag",e.lag),e.type!==void 0&&r.setLinkField(e.linkId,"type",e.type),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:"link-missing"}}function kd(e,t){let{port:r}=t;return r.getLink(e.linkId)?(r.removeLink(e.linkId),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:"link-missing"}}var $e=null;function Sd(){return $e===null&&($e=Date.now()),$e+=1,String($e)}var Na={[V.FINISH_TO_START]:"fs",[V.START_TO_START]:"ss",[V.FINISH_TO_FINISH]:"ff",[V.START_TO_FINISH]:"sf"},Ht={fs:V.FINISH_TO_START,ss:V.START_TO_START,ff:V.FINISH_TO_FINISH,sf:V.START_TO_FINISH},Fa="fs";function Ma(e){if(e in Ht)return Ht[e]}var Wa=";",Ua=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function Ge(e){let t=[],r=[],i=e.replace(/\s+/g,"");if(i.length===0)return{specs:t,errors:r};for(let n of i.split(Wa)){if(n.length===0)continue;let a=Dd(n);a?t.push(a):r.push(n)}return{specs:t,errors:r}}function Dd(e){let t=e.toLowerCase(),r=Ua.exec(t);if(!r)return null;let[,i,n,a,s]=r,o=n?Ht[n]:Ht[Fa],c=0;if(s!==void 0){let l=Number(s);if(Number.isNaN(l))return null;c=a==="-"?-l:l}return{correlativeId:i,type:o,lag:c}}function ze(e){let{targetActivityId:t,currentLinks:r,desiredSpecs:i}=e,n=[],a=new Map;for(let c of i){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=Ke(l,c.type);a.has(d)||a.set(d,{source:l,type:c.type,lag:c.lag})}let s=new Map;for(let c of r)String(c.target)===String(t)&&s.set(Ke(c.source,c.type),c);let o=[];for(let[c,l]of s)a.has(c)||o.push({kind:"delete",linkId:l.id});for(let[c,l]of a){let d=s.get(c);d&&d.lag!==l.lag&&o.push({kind:"update",linkId:d.id,lag:l.lag})}for(let[c,l]of a)s.has(c)||o.push({kind:"create",source:l.source,target:t,type:l.type,lag:l.lag});return{operations:o,unresolved:n}}function Ke(e,t){return`${String(e)}::${t}`}function qe(e){let{sourceActivityId:t,currentLinks:r,desiredSpecs:i}=e,n=[],a=new Map;for(let c of i){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=Ke(l,c.type);a.has(d)||a.set(d,{target:l,type:c.type,lag:c.lag})}let s=new Map;for(let c of r)String(c.source)===String(t)&&s.set(Ke(c.target,c.type),c);let o=[];for(let[c,l]of s)a.has(c)||o.push({kind:"delete",linkId:l.id});for(let[c,l]of a){let d=s.get(c);d&&d.lag!==l.lag&&o.push({kind:"update",linkId:d.id,lag:l.lag})}for(let[c,l]of a)s.has(c)||o.push({kind:"create",source:t,target:l.target,type:l.type,lag:l.lag});return{operations:o,unresolved:n}}function ft(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var Ba={rawInputToConstraintDate(e,t){let r=new Date(e);return r.setUTCHours(0,0,0,0),r.getTime()===e.getTime()?t.getClosestWorkTime({direction:q.FUTURE,date:e,unit:et.HOUR}):t.isWorkTime(e,et.HOUR)?e:r},computeLagBetweenTasks(e,t,r){return r.calculateDuration(e,t)}};function ii(e,t,r){switch(r){case"0":return{sourceDate:e.endDate,targetDate:t.startDate};case"1":return{sourceDate:e.startDate,targetDate:t.startDate};case"2":return{sourceDate:e.endDate,targetDate:t.endDate};case"3":return{sourceDate:e.startDate,targetDate:t.endDate}}}var ni=Ba;var Je=class{adapter;reporter;currentCalculationId=0;topoCache=new je;expandedLinksCache=new Ve;constructor(t,r=Qt){this.adapter=t,this.reporter=r}getCurrentCalculationId(){return this.currentCalculationId}invalidateTopoCache(){this.topoCache.invalidate()}invalidateExpandedLinksCache(){this.expandedLinksCache.invalidate()}invalidateAllCaches(){this.topoCache.invalidate(),this.expandedLinksCache.invalidate()}async schedule(t={}){let r=++this.currentCalculationId,i=da(r,()=>this.currentCalculationId),n={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{Ed(this.adapter);let a=Lt("schedule.total"),s=Lt("schedule.expandParentLinks"),o=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(o,this.adapter);It(s);let l=c;if((await Xt(i)).aborted)return{...n,cancelled:!0};let d=Lt("schedule.scoping"),u=this.adapter.getAllIds(),f=l,p=u,v=null;if(t.triggerId!==void 0&&t.triggerId!==null){let _=Da(t.triggerId,l);f=_.links,p=Array.from(_.activityIds),v=new Set(p)}It(d);let S=Lt("schedule.topologicalSort"),A=Rd(this.topoCache,u,l,v);if(It(S),A.hasCycles)return It(a),{...n,cycles:[A.cycleNodes]};if((await Xt(i)).aborted)return{...n,cancelled:!0};let D=Lt("schedule.processConstraints"),m=new Map;if(Ea(A.ordered,this.adapter,m),It(D),(await Xt(i)).aborted)return{...n,cancelled:!0};let T=Lt("schedule.asapPass"),k=await wa(A.ordered,f,this.adapter,t,i,m);if(It(T),(await Xt(i)).aborted)return{...n,cancelled:!0};let y=Lt("schedule.alapPass"),g=await Oa(A.reversed,f,k,this.adapter,t,i);if(It(y),(await Xt(i)).aborted)return{...n,cancelled:!0};let C=Lt("schedule.diff"),P=[];for(let[_,b]of g){let x=this.adapter.getActivity(_);if(!x)continue;let M=x.startDate.getTime()!==b.startDate.getTime(),z=x.endDate.getTime()!==b.endDate.getTime();(M||z)&&P.push(_)}return It(C),It(a),{plans:g,updatedIds:P,cycles:[],cancelled:!1}}catch(a){return this.reporter.error("[AutoScheduler] Error during scheduling",a),n}}},_d=!1;function Pd(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:_d}function Lt(e){return{name:e,startedAt:performance.now()}}function Ed(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function It(e){if(!Pd())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function Rd(e,t,r,i){let n=e.get(t,r);if(n.hasCycles){let s=i?Array.from(i):t;return He(s,r)}if(!i)return n;let a=ga(n.ordered,i);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function Ha(e,t){let r=t.getActivity(e);if(!r)return;let i=t.calendarReader.getCalendar(String(r.calendarId));for(let n of t.getIncomingLinkIds(e)){let a=t.getLink(n);if(!a)continue;let s=t.getActivity(a.source);if(!s||s.constraintType==="alap")continue;let{sourceDate:o,targetDate:c}=ii(s,r,a.type),l=ni.computeLagBetweenTasks(o,c,i);l!==a.lag&&Rt({kind:"update",linkId:a.id,lag:l},{port:t})}}function ja(e,t){let r=t.getActivity(e);r&&ye(r.type)&&(r.durationHours=0)}function te(e){let t=0,r=!1;for(let i of e)i.ponderator>0&&(t+=i.ponderator/100*i.progress,r=!0);return r?t:null}function Xe(e){return Number(e.toFixed(2))}function ct(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function ve(e,t,r=!0,i={}){let n=t?Va(e,t):xd(e);await Ld(n,e,r,{recomputeRealWork:i.recomputeRealWork??!1})}function ai(e,t,r=!0){let i=Va(e,t);for(let n of i)si(n,e,r)}function Ze(e,t){si(e,t,!1)}async function Ld(e,t,r=!0,i={recomputeRealWork:!1}){let a=0;for(let s of e)si(s,t,r,i.recomputeRealWork),a+=1,a%200===0&&await rt()}function Va(e,t){let r=new Set;for(let a of t)bd(a,e,r);if(r.size===0)return[];let i=Array.from(r),n=Ya(i,e);return $a(i,n)}function bd(e,t,r){let i=t.getParentId(e);for(;i&&!O(i);){if(r.has(i))return;r.add(i),i=t.getParentId(i)}}function wd(e,t,r){let i=null,n=null,a=0,s=[];for(let o of e){let c=t.getActivity(o);if(!c)continue;let l=c.startDate.getTime(),d=c.endDate.getTime();(i===null||l<i)&&(i=l),(n===null||d>n)&&(n=d),r&&(a+=Od(c,t.getChildren(o).length>0)),s.push({progress:Number(c.progress??0),ponderator:Number(c.ponderator??0)})}return{minStart:i,maxEnd:n,realWorkSum:a,weightedChildren:s}}function si(e,t,r=!0,i=!1){let n=t.getActivity(e);if(!n)return;let a=t.getChildren(e);if(a.length===0)return;let s=wd(a,t,i);if(s.minStart===null||s.maxEnd===null)return;let o=String(n.calendarId??""),c=t.calendarReader.getCalendar(o),l=new Date(s.minStart),d=new Date(s.maxEnd),u=c.calculateDuration(l,d);t.setActivityField(e,"startDate",l),t.setActivityField(e,"endDate",d),t.setActivityField(e,"durationHours",u);let f=te(s.weightedChildren);r&&f!==null&&t.setActivityField(e,"progress",Xe(f)),i&&t.setActivityField(e,"realWorkHours",s.realWorkSum)}function Od(e,t){return t?Number(e.realWorkHours)||0:ct(e.workHours,e.progress)}function xd(e){let t=Nd(e),r=Ya(t,e);return $a(t,r)}function Nd(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function Ya(e,t){let r=new Map;for(let i of e)r.set(i,Fd(i,t));return r}function Fd(e,t){let r=0,i=e;for(;i&&!O(i)&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function $a(e,t){return[...e].sort((r,i)=>(t.get(i)??0)-(t.get(r)??0))}var Ga={updateActivityDuration:ja,updateTaskTiming:Wd("updateTaskTiming"),adjustLinkLagOnTaskMove:Ha,recordLastStartDate:Md};function Md(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function bt(e,t,r){for(let i of t){let n=i in Ga?Ga[i]:void 0;if(!n){console.warn(`[replay post-processors] unknown: ${i} \u2014 skipping. Add an entry in POST_PROCESSORS if a fixture needs it.`);continue}n(e,r)}}function Wd(e){return()=>{console.debug(`[replay post-processors] ${e}: not yet ported to adapter \u2014 no-op.`)}}function w(e,t){return t!==void 0?{ok:!0,value:e,raw:t}:{ok:!0,value:e}}function N(e){return{ok:!1,reason:e}}function W(){return{valid:!0}}function Q(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function U(){return{allowed:!0}}function G(e,t){return t!==void 0?{allowed:!1,reason:e,alertKey:t}:{allowed:!1,reason:e}}function F(e,t={}){return{patch:e,needsAutoSchedule:t.autoSchedule??!1,postProcessors:t.postProcessors??[],...t.cascadeMutations!==void 0?{cascadeMutations:t.cascadeMutations}:{},...t.trackingEvents!==void 0?{trackingEvents:t.trackingEvents}:{}}}var Ka={targetField:"name",canEdit(){return U()},parseInput(e){return typeof e!="string"?N("not_a_string"):w(e)},validate(){return W()},transform(e,t){return F({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var za={targetField:"description",canEdit(){return U()},parseInput(e){return typeof e!="string"?N("not_a_string"):w(e.trim())},validate(){return W()},transform(e,t){return F({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_description_entry"};function At(e){return e.constraintType??$.ASAP}var Qe=100;function ee(e){return e.progress>=Qe}function tt(e,t){return Ct(e.type,t.hasChildren(e.id))}function qa(e){return e.progress>0}function Ja(e){return e.hasLookaheadTasks}function Ae(e,t){return Math.round(Math.ceil(e*t*60)/60)}var re=e=>({endDate:e});function jt(e,t){if(t){let r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=n=>Number(r.find(a=>a.type===n)?.value);return new Date(Date.UTC(i("year"),i("month")-1,i("day")))}return new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()))}function Ce(e,t){if(!t||t==="UTC"){let f=new Date(e);return f.setUTCHours(23,59,0,0),f}let r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=f=>Number(r.find(p=>p.type===f)?.value),n=i("year"),a=i("month"),s=i("day"),o=Date.UTC(n,a-1,s,23,59,0,0),c=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(new Date(o)),l=f=>Number(c.find(p=>p.type===f)?.value),u=Date.UTC(l("year"),l("month")-1,l("day"),l("hour")===24?0:l("hour"),l("minute"),l("second"))-o;return new Date(o-u)}function Ud(e,t){let r=jt(t);for(;!e.isWorkTime(r,et.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=jt(r);return r}function oi(e,t){return e.getClosestWorkTime({direction:q.FUTURE,date:t,unit:et.HOUR})}function ci(e,t){let r=Ud(e,t),i=new Date(r);return i.setUTCDate(i.getUTCDate()+1),i.setUTCHours(0,0,0,0),e.getClosestWorkTime({direction:q.PAST,date:i,unit:et.HOUR})}var tr=new Set(["snet","snlt","mso"]),li=new Set(["fnet","fnlt","mfo"]),wt=new Set(["asap","alap"]),er="snet";function kt(e,t,r){if(!tr.has(r)&&!li.has(r))return e;let i=tr.has(r)?oi(t,e):ci(t,e),n=new Date(e);return n.setUTCHours(i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds()),n}var St=()=>({constraintType:er});var Ot=e=>({constraintDate:e}),Xa=e=>({constraintDate:e});var Za={UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var Qa={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"};function ie(e,t,r){return fa(e,t,r)}function ne(e,t,r){return pa(e,t,r)}var es={targetField:"durationHours",canEdit(e,t){return ee(e)?G("completed","cant_edit_completed_activity"):tt(e,t)?G("summary","summary_column_value"):U()},parseInput(e,t,r){let i=parseFloat(String(e));return Number.isNaN(i)?N("not_a_number"):w(r.inputUnit==="hours"?i:Ae(i,r.hoursPerDay))},validate(e,t,r){return ts(r)?Q(Qa.NEGATIVE_DURATION):Bd(t,r)?Q("unchanged"):W()},transform(e,t,r){if(ts(t))return F({},{autoSchedule:!1,postProcessors:[]});let i=Hd(e,t,r),n=jd(e,t,r,i.violated);return{...F(n,{autoSchedule:e.constraintType!=="alap",postProcessors:[Za.RECORD_LAST_START_DATE]}),...i.violated?{constraintWarning:ne(i.constraintType,i.constraintDate,rs(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function ts(e){return Math.sign(e)===-1}function Bd(e,t){return e===t}function Hd(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return{violated:!1};let n=e.constraintType;if(n!=="fnet"&&n!=="fnlt"&&n!=="mfo")return{violated:!1};let a=i.calculateEndDate(e.startDate,t);return ie(n,e.constraintDate,a)}function jd(e,t,r,i=!1){let n={};i&&Object.assign(n,St(),Ot(e.startDate));let a=me(e.durationHours,t);a&&(n.type=a),n.durationHours=t;let s=rs(e,t,r);return s&&Object.assign(n,re(s)),n}function rs(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateEndDate(e.startDate,t):null}var ae=e=>({realWorkHours:e});var Vd=0,Yd=Qe,is=0,ns={targetField:"progress",canEdit(e,t){return Ja(e)?G("has_lookahead_tasks","cant_edit_actvity_with_task"):tt(e,t)?G("summary","summary_column_value"):U()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?N("not_a_number"):w(t)},validate(e,t,r){return $d(r)?Q("out_of_range"):W()},transform(e,t,r){let i=Gd(t),n=Kd(t),a=Jd(e,t,r.hierarchy),s={progress:t,autoScheduling:i,...ae(a.get(e.id)??0)},o=n?zd(e,t,i,r.hierarchy,a):[],c=n?Xd(e,t,r.hierarchy):[],l=o.length+c.length>0?[...o,...c]:void 0,d=[],u=n?Qd(e,t):void 0;return F(s,{autoSchedule:!1,postProcessors:d,cascadeMutations:l,trackingEvents:u})},trackEvent:"activity_progress_entry"};function $d(e){return e<Vd||e>Yd}function Gd(e){return e===is}function Kd(e){return e===Qe||e===is}function zd(e,t,r,i,n){return i.getDescendantIds(e.id).map(s=>({activityId:s,fields:qd(t,r,n.get(s)??0)}))}function qd(e,t,r){return{progress:e,autoScheduling:t,...ae(r)}}function Jd(e,t,r){let i=new Map,n=s=>{let o=0;for(let c of r.getChildHhInfo(s)){let l=r.hasChildren(c.id)?n(c.id):ct(c.workHours,t);i.set(c.id,l),o+=l}return o},a=r.hasChildren(e.id)?n(e.id):ct(e.workHours,t);return i.set(e.id,a),i}function Xd(e,t,r){let i=new Map;i.set(e.id,t);for(let s of r.getDescendantIds(e.id))i.set(s,t);let n=[];for(let s of r.getAncestorIds(e.id))n.push(s);let a=[];for(let s of n){let o=Zd(s,i,r);i.set(s,o),a.push({activityId:s,fields:{progress:o}})}return a}function Zd(e,t,r){let i=r.getChildProgressInfo(e).map(n=>({progress:t.has(n.id)?t.get(n.id):n.progress,ponderator:n.ponderator??0}));return Number((te(i)??0).toFixed(2))}function Qd(e,t){return[{name:"activity_progress_update_radio_button",properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var as={targetField:"cost",canEdit(e,t){return tt(e,t)?G("summary","summary_column_value"):U()},parseInput(e,t){if(String(e).trim()==="")return w(t.cost);let r=parseFloat(String(e));return Number.isNaN(r)?N("not_a_number"):w(r)},validate(){return W()},transform(e,t,r){let i=tu(e,t,r.hierarchy);return F({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_budgeted_entry"};function tu(e,t,r){let i=new Map;i.set(e.id,t);let n=[];for(let a of r.getAncestorIds(e.id)){let s=0;for(let o of r.getChildCostInfo(a))s+=i.has(o.id)?i.get(o.id):o.cost;i.set(a,s),n.push({activityId:a,fields:{cost:s}})}return n}var ss={targetField:"usedCost",canEdit(e,t){return tt(e,t)?G("summary","summary_column_value"):U()},parseInput(e,t){if(String(e).trim()==="")return w(t.usedCost);let r=parseFloat(String(e));return Number.isNaN(r)?N("not_a_number"):w(r)},validate(){return W()},transform(e,t,r){let i=eu(e,t,r.hierarchy);return F({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_spent_entry"};function eu(e,t,r){let i=new Map;i.set(e.id,t);let n=[];for(let a of r.getAncestorIds(e.id)){let s=0;for(let o of r.getChildUsedCostInfo(a))s+=i.has(o.id)?i.get(o.id):o.usedCost;i.set(a,s),n.push({activityId:a,fields:{usedCost:s}})}return n}var os={targetField:"workHours",canEdit(e,t){return tt(e,t)?G("summary","summary_column_value"):U()},parseInput(e){if(String(e).trim()==="")return w(0,e);let t=parseFloat(String(e));return Number.isNaN(t)?N("not_a_number"):w(t)},validate(){return W()},transform(e,t,r,i){let n=cs(t,e.progress),a=String(i).trim()===""?[]:ru(e,t,n,r.hierarchy);return F({workHours:t,...ae(n)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function cs(e,t){return ct(e,t)}function ru(e,t,r,i){let n=new Map,a=new Map;n.set(e.id,t),a.set(e.id,r);let s=[];for(let o of i.getAncestorIds(e.id)){let c=0,l=0;for(let d of i.getChildHhInfo(o)){let u=n.has(d.id)?n.get(d.id):d.workHours,f=a.has(d.id)?a.get(d.id):d.realWorkHours??cs(d.workHours,d.progress);c+=u,l+=f}n.set(o,c),a.set(o,l),s.push({activityId:o,fields:{workHours:c,...ae(l)}})}return s}function rr(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function di(e,t){return e.getTime()<t.getTime()}function se(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var ir=e=>({durationHours:e});var ls={targetField:"startDate",canEdit(e,t){return tt(e,t)?G("summary","summary_column_value"):qa(e)?G("has_progress","cant_edit_activity_with_progress"):U()},parseInput(e,t,r){return se(e)?w(jt(e,"UTC")):N("invalid_date")},validate(e,t,r,i){if(rr(t,r))return Q("unchanged");let n=iu(e,r,i);return n||W()},transform(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return F({startDate:t,...St(),...Ot(t)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]});let n=oi(i,t),a=e.type==="milestone",s=a?n:i.calculateEndDate(n,e.durationHours),o=n;return{...F({startDate:n,...re(s),...a?ir(0):{},...St(),...Ot(o)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:nu(e,n,i)}},trackEvent:"activity_start_date_entry"};function iu(e,t,r){let i=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!i)return null;let n=jt(i);return t.getTime()<n.getTime()?Q("before_parent_start"):null}function nu(e,t,r){let i=r.calculateEndDate(t,e.durationHours),n=he(At(e),t,i),a=ie(At(e),e.constraintDate,n);if(a.violated)return ne(a.constraintType,a.constraintDate,n)}var au=99.999,ds={targetField:"endDate",canEdit(e,t){return tt(e,t)?G("summary","summary_column_value"):su(e)?G("completed","cant_edit_completed_activity"):U()},parseInput(e,t,r){if(!se(e))return N("invalid_date");let i=jt(e,"UTC"),n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(i,et.DAY)?w(ci(n,i)):r.dateFormat.split(" ").length>1?w(i):w(n.getClosestWorkTime({direction:"past",date:i,unit:et.HOUR})):w(i)},validate(e,t,r,i){if(rr(e.endDate,r))return Q("unchanged");if(ou(r,e))return Q("before_date_origin");if(cu(r,e))return Q("before_start_date");let n=lu(r,e,i);return n||W()},transform(e,t,r){let i=du(e,t),n=uu(e,t,r,!!i);return{...F(n,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...i?{constraintWarning:i}:{}}},trackEvent:"activity_end_date_entry"};function su(e){return e.progress>=au}function ou(e,t){return t.dateOrigin?di(e,t.dateOrigin):!1}function cu(e,t){return di(e,t.startDate)}function lu(e,t,r){let i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(e,et.DAY)?null:Q("not_working_day"):null}function du(e,t){let r=he(At(e),e.startDate,t),i=ie(At(e),e.constraintDate,r);if(i.violated)return ne(i.constraintType,i.constraintDate,r)}function uu(e,t,r,i=!1){let n={},a=ye(e.type);a&&!i?Object.assign(n,Ot(e.startDate)):(i||fu(e))&&Object.assign(n,St(),Ot(e.startDate));let s=pu(e,t,r);if(!a){let o=me(e.durationHours,s);o&&(n.type=o)}return Object.assign(n,ir(s)),n.endDate=t,n}function fu(e){return wt.has(At(e))}function pu(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateDuration(e.startDate,t):e.durationHours}var hu=new Set(Object.values($)),us={targetField:"constraintType",canEdit(e,t){return ee(e)?G("completed","cant_edit_completed_activity"):tt(e,t)?G("summary","summary_column_value"):U()},parseInput(e){let t=String(e).toLowerCase();return yu(t)?w(t):N("invalid_constraint_type")},validate(){return W()},transform(e,t,r){let i=mu(e,t,r);return F(i,{autoSchedule:!0})}};function yu(e){return hu.has(e)}function mu(e,t,r){let i=vu(e,t);return{constraintType:t,...Xa(gu(e,t,i,r))}}function gu(e,t,r,i){if(e.type!=="milestone"||!r)return r;let n=i.calendars.getCalendar(String(e.calendarId));return n?kt(r,n,t):r}function vu(e,t){return wt.has(t)?null:tr.has(t)?e.startDate:li.has(t)?e.endDate:e.constraintDate}var fs={targetField:"constraintDate",canEdit(e,t){return ee(e)?G("completed","cant_edit_completed_activity"):tt(e,t)?G("summary","summary_column_value"):U()},parseInput(e){return se(e)?w(e):N("invalid_date")},validate(){return W()},transform(e,t,r){let i=ps(e)?er:At(e),n=r.calendars.getCalendar(e.calendarId),a=n?kt(t,n,i):t,s=Au(e,a);return F(s,{autoSchedule:!0})}};function Au(e,t){return{constraintDate:t,...ps(e)?St():{}}}function ps(e){return wt.has(At(e))||!e.constraintType}var hs={targetField:"calendarId",canEdit(){return U()},parseInput(e){let t=String(e).trim();return Cu(t)?N("empty_calendar"):w(t)},validate(e,t,r){return Iu(e.calendarId,r)?Q("unchanged"):W()},transform(e,t,r){return F(ku(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function Cu(e){return e===""}function Iu(e,t){return e===t}function ku(e,t,r){let i={calendarId:t,assignedDefaultCalendar:!1},n=r.calendars.getCalendar(t);if(n){let a=e.durationHours===0,s=a?Su(e.startDate):e.startDate,o=n.getClosestWorkTime({date:s,direction:"future",unit:"hour"});if((!e.autoScheduling||a||n.getWorkHours(e.startDate).length===0)&&(i.startDate=o),!e.autoScheduling)return i;let c=i.startDate??e.startDate;Object.assign(i,re(n.calculateEndDate(c,e.durationHours)))}return i}function Su(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var ys={targetField:"customId",canEdit(){return U()},parseInput(e){if(e==null)return N("empty_custom_id");if(typeof e!="string")return N("not_a_string");let t=e.trim();return t.length===0?N("empty_custom_id"):t.length>20?N("exceeds_max_length"):w(t)},validate(){return W()},transform(e,t){return F({customId:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var ms={targetField:"subcontractId",canEdit(){return U()},parseInput(e){if(e==null)return w(null);if(typeof e=="string"){let t=e.trim();if(t.length===0)return w(null);let r=Number(t);return!Number.isFinite(r)||!Number.isInteger(r)?N("not_an_integer"):w(r)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?N("not_an_integer"):w(e):N("not_an_integer")},validate(){return W()},transform(e,t){return F({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function Ie(e){if(e==null)return null;if(typeof e=="object"){if(!("id"in e))return null;let t=e.id;return t==null?null:String(t)}return String(e)}function nr(e){return e.some(t=>Ie(t)===null)}var gs={targetField:"responsableIds",canEdit(){return U()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):N("not_an_array")},validate(e,t,r){return nr(r)?Q("missing_id"):W()},transform(e,t){let r=t.map(Ie).filter(i=>i!==null);return F({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var vs={targetField:"tagIds",canEdit(){return U()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):N("not_an_array")},validate(e,t,r){return nr(r)?Q("missing_id"):W()},transform(e,t){let r=t.map(Ie).filter(i=>i!==null);return F({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var Du=new Map([[E.TEXT,Ka],[E.DESCRIPTION,za],[E.DURATION,es],[E.PROGRESS,ns],[E.COST,as],[E.USED_COST,ss],[E.HH_WORK_TIME,os],[E.START_DATE,ls],[E.END_DATE,ds],[E.CONSTRAINT_TYPE,us],[E.CONSTRAINT_DATE,fs],[E.CALENDAR_ID,hs],[E.CUSTOM_ID,ys],[E.SUBCONTRACT_ID,ms],[E.RESPONSABLES,gs],[E.TAGS,vs]]);function xt(e){return Du.get(e)}function oe(e,t){if(!t||t.type!=="constraint")return null;let r=t.data;return!r?.constraintType||!r.constraintDate?null:{kind:"constraint_violation",activityId:e,constraintType:r.constraintType,constraintDate:r.constraintDate,projectedDate:r.projectedDate??r.constraintDate,messageKey:t.messageKey}}var L={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",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath",PROMOTION_RESTORE:"promotionRestore"},ui={ID:"id",SOURCE:"source",TARGET:"target",TYPE:"type",LAG:"lag",SOURCE_LAG:"_sourceLag",TARGET_LAG:"_targetLag",TRUE_LAG:"_trueLag",GANTT_ID:"ganttId",SECTOR_ID:"sectorId",PROPLANNER_ID:"proplannerId"};var Tu=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],As=new Set(Tu);function Z(e,t,r,i){e.setActivityFieldDynamic(t,r,i)}function Cs(e,t,r,i){e.setLinkFieldDynamic(t,r,i)}function Nt(e,t){let r=new Set([String(e)]);for(let i of t.cascadeMutations??[])r.add(String(i.activityId));return r}function J(e,t){let r=new Map;for(let i of t){let n=e.getActivity(i);n&&r.set(i,j(n))}return r}function j(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:e.constraintDate?new Date(e.constraintDate):null,dateOrigin:e.dateOrigin?new Date(e.dateOrigin):null}}function Ft(e,t,r){Is(e,t,r.patch);for(let i of r.cascadeMutations??[])Is(e,i.activityId,i.fields)}function Is(e,t,r){for(let[i,n]of Object.entries(r)){if(!As.has(i))throw new Error(`applyFieldChanges: column write to non-writable field "${i}"`);Z(e,t,i,n)}}function ks(e,t,r){let i=[];for(let n of r){let a=e.getActivity(n);if(!a){i.push({id:n,kind:"deleted",after:null});continue}let s=t.get(n),o=fi(s,a);s?i.push({id:n,kind:"updated",fields:o,after:j(a)}):i.push({id:n,kind:"created",fields:o,after:j(a)})}return i}function fi(e,t){let r={},i=e??{},n=t,a=new Set([...Object.keys(i),...Object.keys(n)]);for(let s of a)Ds(i[s],n[s])||(r[s]={before:i[s],after:n[s]});return r}function ar(e,t,r){let i=new Set;i.add(e);for(let n of t)i.add(n);for(let n of r)i.add(n);return i}function Ss(e,t){let r=new Set;for(let i of e)r.add(String(i));for(let i of t)r.add(i);return r}function sr(e,t,r,i,n){for(let a of t){if(r.has(a.activityId)||(n.add(a.activityId),i.has(a.activityId)))continue;let s=e.getActivity(a.activityId);if(!s)continue;let o=j(s);a.before!==void 0&&(o.correlativeId=a.before),i.set(a.activityId,o)}}function Ds(e,t){if(e===t)return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e==null||t==null||typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Ds(e[r],t[r]))return!1;return!0}return!1}var _u=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function Dt(e){if(e==null||e==="")throw new Error(`[parseFromBackend] expected a date string, got "${e}"`);if(e.includes("T")||e.endsWith("Z")){let o=new Date(e);if(Number.isNaN(o.getTime()))throw new Error(`[parseFromBackend] invalid ISO date "${e}"`);return o}let t=e.match(_u);if(!t)throw new Error(`[parseFromBackend] unsupported date format "${e}" (expected "YYYY/MM/DD H:MM" or ISO)`);let[,r,i,n,a,s]=t;return new Date(Date.UTC(Number(r),Number(i)-1,Number(n),Number(a),Number(s)))}function ce(e,t,r,i){if(e.getTime()>r.getTime())return 0;if(t.getTime()<r.getTime()||e.getTime()===t.getTime())return 100;let n=i.calculateDuration(e,r),a=i.calculateDuration(e,t);return a===0?0:n*100/a}var Pu=e=>e.type==="project",Eu=(e,t,r)=>{let i=e.calendarId,n=i!=null?r.calendarReader.getCalendar(String(i)):null;if(!n)return 0;let a=s=>s instanceof Date?s:Dt(String(s));return ce(a(e.startDate),a(e.endDate),t,n)};function Ts(e,t,r){let i=[],n=(s,o)=>{let c=r.getActivity(s);c&&c.expectedProgress!==o&&(r.setActivityField(s,"expectedProgress",o),i.push(String(s)))},a=s=>{let o=r.getActivity(s);if(!o)return 0;if(!Pu(o)){let d=Eu(o,t,r);return n(s,d),d}let c=0;for(let d of r.getChildren(s)){let u=a(d),f=r.getActivity(d),p=typeof f?.ponderator=="number"?f.ponderator:0;c+=u*p}let l=c/100;return n(s,l),l};for(let s of e)a(s);return i}var _s=e=>Math.round(e*100)/100;function Ru(e,t){return(t==="Baseline"?e.expectedProgressBaseline:e.expectedProgress)??void 0}function Lu(e,t){let r=_s(e),i=_s(t);return r>99.99?Pt.DONE:i>r?Pt.OVERDUE:e>0&&r>i?Pt.ADVANCEMENT:e===0&&t===0?Pt.WAITING:e>0&&r<i?Pt.DOING:Pt.WAITING}function Yt(e,t){let r=[];return e.forEachActivity((i,n)=>{let a=typeof i.progress=="number"?i.progress:0,s=Lu(a,Ru(i,t));i.status!==s&&(Z(e,n,Ne,s),r.push(n))}),r}var pi=Number.MAX_SAFE_INTEGER;function $t(e,t){let r=yi(e,t);return r.sort(bu),r.map(i=>String(i.id))}function Es(e){let t=[],r=n=>{t.push(n);let a=$t(String(n.id),e);for(let s of a){let o=e.getActivity(s);o&&r(o)}},i=$t("0",e);for(let n of i){let a=e.getActivity(n);a&&r(a)}return t}function Rs(e,t,r){let i=r.getActivity(e);if(!i)return null;let n=Ls(i),a=$t(n,r),s=a.findIndex(o=>String(o)===String(e));if(s<=0)return null;for(let o=s-1;o>=0;o--){let c=a[o];if(c!==void 0&&!wu(t,c))return c}return null}function hi(e,t){let r=t.getActivity(e);if(!r)return-1;let i=Ls(r);return $t(i,t).findIndex(a=>String(a)===String(e))}function yi(e,t){if(String(e)==="0")return t.getAllActivities().filter(a=>a.parentId===null);let i=t.getChildren(e),n=[];for(let a of i){let s=t.getActivity(a);s&&n.push(s)}return n}function bu(e,t){let r=Ps(e),i=Ps(t);return r!==i?r-i:String(e.id).localeCompare(String(t.id))}function Ps(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:pi}function Ls(e){let t=e.parentId;return t===null?"0":t}function wu(e,t){return e.has(t)?!0:e.has(String(t))}function at(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(a=>{O(a.parentId)&&t.push(a)}),t.sort(Os);let r=[];bs(r,t);let i=[],n=0;for(;r.length>0;){let a=r.pop();if(a.correlativeId!==n){let o=typeof a.correlativeId=="number"?a.correlativeId:void 0;i.push({activityId:String(a.id),before:o}),o!==void 0&&e.noteCorrelativeBefore?.(String(a.id),o),Ou(a,n)}n+=1;let s=yi(String(a.id),e);s.sort(Os),bs(r,s)}return i}function bs(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function ws(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:pi}var Os=(e,t)=>ws(e)-ws(t);function Ou(e,t){e.correlativeId=t}function xs(e){let t=[],r=[];e.forEachActivity((n,a)=>{n.parentId===null&&t.push(String(a))});let i=n=>{let a=e.getActivity(n);if(!a)return 0;let s=[...e.getChildren(n)],o=s.length===0?ct(a.workHours,a.progress):s.reduce((c,l)=>c+i(String(l)),0);return e.setActivityField(n,L.REAL_WORK_HOURS,o),r.push(n),o};for(let n of t)i(n);return r}async function Ns(e){let{state:t,sector:r,scheduler:i,skipAutoSchedule:n,now:a}=e;if(at(t),r.updateDurationForPrimaveraEndDate&&Nu(t),Fu(t),xs(t),n){a&&(or(t,a),Yt(t,r.statusCriteria));return}let s=await i.schedule({});ge(t,s),Mu(t),xu(t),await ve(t,void 0,!1),a&&(or(t,a),Yt(t,r.statusCriteria))}function or(e,t){let r=[];e.forEachActivity((i,n)=>{i.parentId===null&&r.push(n)}),Ts(r,t,e)}function xu(e){e.forEachActivity(t=>{t.autoScheduling||!t.startDate||t.durationHours==null||e.getChildren(t.id).length>0||(t.endDate=e.calculateEndDate({startDate:t.startDate,durationHours:t.durationHours,task:t}))})}function Nu(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function Fu(e){e.forEachActivity(t=>{let r=t.constraintType;if(!r||!t.constraintDate)return;let i=t.constraintDate;if(t.type==="milestone"&&(i.getUTCHours()!==0||i.getUTCMinutes()!==0))return;let n=e.calendarReader.getCalendar(String(t.calendarId));n&&(t.constraintDate=kt(t.constraintDate,n,r))})}function Mu(e){e.forEachActivity(t=>{if(t.type!=="milestone")return;let r=t.constraintType;if(!r||!t.constraintDate)return;let i=e.calendarReader.getCalendar(String(t.calendarId));i&&(t.constraintDate=kt(t.constraintDate,i,r))})}function pt(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isActiveVersion)??null}var Wu=e=>e.type==="project",Uu=e=>pt(e),Bu=(e,t,r,i)=>{let n=Uu(e);if(!n)return 0;let a=(n.baseCalendarId!=null?r.getBaseCalendar(`${n.baseCalendarId}-base`):null)??(i?r.getBaseCalendar(i):null);return!a||!n.startDate||!n.endDate?0:ce(n.startDate,n.endDate,t,a)};function mi(e,t,r,i=null){let n=[],a=(o,c)=>{let l=r.getActivity(o);l&&l.expectedProgressBaseline!==c&&(r.setActivityField(o,"expectedProgressBaseline",c),n.push(o))},s=o=>{let c=r.getActivity(o);if(!c)return 0;if(!Wu(c)){let u=Bu(c,t,r,i);return a(o,u),u}let l=0;for(let u of r.getChildrenIds(o)){let f=s(u),p=r.getActivity(u),v=typeof p?.ponderator=="number"?p.ponderator:0;l+=f*v}let d=l/100;return a(o,d),d};for(let o of e)s(o);return n}function cr(e,t,r=null){let i={getChildrenIds:a=>e.getChildren(String(a)).map(s=>String(s)),getActivity:a=>e.getActivity(a),setActivityField:(a,s,o)=>Z(e,a,s,o),getBaseCalendar:a=>e.calendarReader.getCalendar(a)},n=[];return e.forEachActivity((a,s)=>{a.parentId===null&&n.push(s)}),mi(n,t,i,r)}function gi(e){let t=e instanceof Date?new Date(e.getTime()):e&&typeof e=="object"&&typeof e.valueOf=="function"?new Date(e.valueOf()):new Date(e),r=(n,a)=>s=>s===void 0?t[n]():(t[a](s),i),i={__isMomentShim:!0,clone:()=>gi(t),hours:r("getUTCHours","setUTCHours"),minutes:r("getUTCMinutes","setUTCMinutes"),seconds:r("getUTCSeconds","setUTCSeconds"),milliseconds:r("getUTCMilliseconds","setUTCMilliseconds"),valueOf:()=>t.getTime(),toDate:()=>new Date(t.getTime()),getTime:()=>t.getTime()};return i}gi.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var ht=gi;function Hu(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function lr(e){return Hu(e)&&!isNaN(e.getTime())}function I(e,t,r,i){if(!lr(new Date(t)))throw new Error(`Invalid date argument for calculateEndDate method. Date: ${t}, Activity: ${JSON.stringify(i)}`);let n=t;return e.calculateEndDate({start_date:new Date(n),duration:r,unit:"hour",task:i})}function lt(e){if(!lr(new Date(e.dateBaseToCalculate)))throw new Error("Invalid date argument for getClosestWorkTime method");let{dateBaseToCalculate:t,activityCalendar:r,direction:i,activity:n}=e;return r.$gantt.getClosestWorkTime({date:new Date(t),dir:i,unit:"hour",task:n})}var ju=e=>e?e.$level===1:!1,Vu=e=>e.type==="project",Yu=e=>e.$level!==0,$u=e=>e.type==="task",Gu=e=>e.type==="task"||e.type==="milestone",it={byFirstLevel:ju,filterByParentType:Vu,avoidSubproject:Yu,byTaskType:$u,byTaskTypeAndMilestone:Gu};var h=Object.freeze({MFO:"mfo",MSO:"mso",FNLT:"fnlt",FNET:"fnet",SNET:"snet",SNLT:"snlt",ALAP:"alap",ASAP:"asap"});var B=Object.freeze({FS:"fs",SS:"ss",FF:"ff",SF:"sf"});function Gt(e){return{0:"fs",1:"ss",2:"ff",3:"sf"}[Number(e)]||"sf"}function Fs(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:i,linkProperty:n}=e;try{let a=Ku({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let s=zu({gantt:t,subprojectsWithNoLinks:a}),o=qu({gantt:t,childrenIds:s,linkProperty:n,getArrayOfLinkedActivities:Ju,calculations:i});return new Set(o.map(c=>c.id))}catch(a){throw a}}function Ku(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(it.filterByParentType).filter(i=>r.has(i.id)).map(i=>i.id)}function zu(e){let{gantt:t,subprojectsWithNoLinks:r}=e,i=new Set;for(let n of r)t.getChildren(n).filter(o=>{let c=t.getTask(o),l=it.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(o=>i.add(o));return[...i]}function qu(e){let{gantt:t,childrenIds:r,linkProperty:i,getArrayOfLinkedActivities:n,calculations:a}=e,s=[];for(let o of r){let c=t.getTask(o),l=c[i]||[];n({gantt:t,links:l,linkDirection:i==="$source"?"target":"source"}).every(f=>a.has(f))&&s.push(c)}return s}function Ju(e){let{gantt:t,links:r,linkDirection:i}=e,n=[];for(let a of r){let s=t.getLink(a);if(!s){`${a}`;continue}let o=Number(s[i]);n.push(o)}return n}function Ms({gantt:e,linkProperty:t,direction:r}){try{let i=Xu(e,t);if(r==="forward")return{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return Zu(i,e,t)}catch(i){throw console.log("Critical Path",i),i}}function Xu(e,t){return e.getTaskByTime().filter(it.avoidSubproject).filter(it.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function Zu(e,t,r){let i=[],n=new Set;return e.forEach(a=>{let s=Number(a.parent),o=t.getTask(s);o&&(o[r].length>0?n.add(a.id):o.constraint_type!=="fnlt"&&i.push(a))}),{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:n}}function Ws({gantt:e,direction:t,linkProperty:r}){try{let i=Qu(e),n=new Set,a=new Set,s=new Set;t==="backward"&&rf(i).forEach(d=>{n.add(d.id)});let o=tf(i,t,r),c=ef(i,o);return o.forEach(l=>{a.add(l.id)}),c.forEach(l=>{s.add(l.id)}),{parentsWithFullProgress:n,pendingParentsWithNoLinks:a,pendingParentsWithLinks:s}}catch(i){throw i}}function Qu(e){return e.getTaskByTime().filter(it.filterByParentType).filter(it.avoidSubproject)}function tf(e,t,r){return e.filter(i=>{let n=i[r];if(!Array.isArray(n))return!1;let a=n.length>0,s=i.constraint_type||"",o=s!=="fnlt";return t==="forward"?!a&&o&&s!=="snet":!a&&o})}function ef(e,t){let r=new Set(t.map(i=>i.id));return e.filter(i=>!r.has(i.id))}function rf(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function Us({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let i=new Set;return e.forEach(n=>{let a=t.getTask(n),s=nf(r),o=af(r),c=a[s];if(!Array.isArray(c))return;sf(t,c,o).forEach(d=>{i.add(d)})}),i}catch(i){throw i}}function nf(e){return e==="forward"?"$source":"$target"}function af(e){return e==="forward"?"target":"source"}function sf(e,t,r){return t.map(i=>{let a=e.getLink(i)[r];return Number(a)})}var ke={identifySecondLevelActivities:Fs,identifyInitialActivities:Ms,identifyParentsWithAndWithoutLinks:Ws,identifyForbiddenActivities:Us};function dr(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function vi({linkType:e,lag:t,predecessorTime:r,activityCalendar:i,activity:n}){return e===B.FS&&t===0?lt({predecessorTime:r,activityCalendar:i,direction:"future",activity:n}):Se(r,e,i,n)}function Bs({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t);return{es:I(r,n,e,i),ef:n}}function Hs({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t),a=I(r,n,e,i);return{es:n,ef:a}}function Se(e,t,r,i){if(![B.FS,B.SS,B.FF].includes(t))return e;let a=[B.FS,B.SS].includes(t)?"future":"past";return lt({dateBaseToCalculate:e,activityCalendar:r,direction:a,activity:i})}var Ai=class{constructor(t,r,i){if(this.linkedActivitiesData=t,this.activity=r,this.gantt=i,this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`)}calculate(){let t=this.calculateLinks(),r=dr(t),i=this.activity.constraint_type;return i==="snet"?this.handleSNETConstraint(r):i==="fnlt"?this.handleFNLTConstraint(r):r}calculateLinks(){let t=[];for(let r of this.linkedActivitiesData){let i=r.linkType,n=Gt(i),a=r.linkLag,s=r.es,o=r.ef,c=null;if(n==="ss")c=this.calculateSSLink({lag:a,predecessorEs:s});else if(n==="ff")c=this.calculateFFLink({lag:a,predecessorEf:o});else if(n==="fs")c=this.calculateFSLink({lag:a,predecessorEf:o});else if(n==="sf")c=this.calculateSFLink({lag:a,predecessorEs:s,predecessorEf:o});else continue;c&&t.push(c)}return t}handleSNETConstraint(t){let r=Hs({duration:this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t&&t.ef>r.ef?t:r}handleFNLTConstraint(t){let r=Bs({duration:-this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t?t.ef>r.ef?r:t:r}calculateSSLink({lag:t,predecessorEs:r}){let i=vi({linkType:"ss",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=I(this.activityCalendar,i,t,this.activity);t>0&&(n=Se(n,"ss",this.activityCalendar,this.activity));let a=I(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:a}}calculateFFLink({lag:t,predecessorEf:r}){let i=vi({linkType:"ff",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=I(this.activityCalendar,i,t,this.activity),a=I(this.activityCalendar,n,-this.activity.duration,this.activity);return t>0&&(a=Se(a,"ff",this.activityCalendar,this.activity)),{es:a,ef:n}}calculateFSLink({lag:t,predecessorEf:r}){let i=r;t===0&&(i=lt({dateBaseToCalculate:r,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let n=I(this.activityCalendar,i,t,this.activity),a=I(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:a}}calculateSFLink({lag:t,predecessorEs:r}){let i=I(this.activityCalendar,r,t,this.activity),n=I(this.activityCalendar,i,-this.activity.duration,this.activity);return t>0&&(n=Se(n,"sf",this.activityCalendar,this.activity)),{es:n,ef:i}}},js=Ai;var Ci=class{constructor(t){this.linkedActivitiesData=t.linksWithActivityData,this.activity=t.activity,this.gantt=t.gantt}calculate(){if(this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`);let t=[];for(let r of this.linkedActivitiesData){let i=Gt(r.linkType);if(r.type==="task"&&Number(r.progress)>0||r.type==="project"&&Number(r.progress)===100)continue;let n=r.linkLag,a=r.ls,s=r.lf;if(i==="ss"){let o={lag:n,workTime:a,lsDataCalculation:-n,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSSLink(o);t.push({ls:c,lf:l})}if(i==="ff"){let o={lag:n,workTime:s,lsDataCalculation:-this.activity.duration,lfDataCalculation:-n},{ls:c,lf:l}=this.calculateFFLink(o);t.push({ls:c,lf:l})}if(i==="fs"){let o={lag:n,workTime:a,lsDataCalculation:-this.activity.duration,lfDataCalculation:-n},{ls:c,lf:l}=this.calculateFsLink(o);t.push({ls:c,lf:l})}if(i==="sf"){let o={lag:n,workTime:s,lsDataCalculation:-n,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSFLink(o);t.push({ls:c,lf:l})}}if(this.activity.constraint_type==="fnlt"){let r=this.getMinLfFromLinks(t),i=this.calculateSfRestrictionDates();return r?this.getMinLfFromLinks([i,r]):i}else{let r=this.getMinLfFromLinks(t);if(r===!1){let i=this.gantt.getSubtaskDates();return{ls:I(this.activityCalendar,i.end_date,-this.activity.duration,this.activity),lf:i.end_date}}return r}}calculateFFLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n}){let a=null,s=null;if(t===0)return a=I(this.activityCalendar,r,n,this.activity),s=I(this.activityCalendar,a,i,this.activity),{ls:s,lf:a};let o=r;return t>0&&(o=this.getLastWorkingHour(o,this.activityCalendar,"past")),a=I(this.activityCalendar,o,n,this.activity),s=I(this.activityCalendar,a,i,this.activity),{ls:s,lf:a}}calculateFsLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n,isMilestone:a=!1}){let s=null,o=null;if(t===0){let l=this.getLastWorkingHour(r,this.activityCalendar,"past");return s=I(this.activityCalendar,l,n,this.activity),s=this.getLastWorkingHour(s,this.activityCalendar,"past"),o=I(this.activityCalendar,s,i,this.activity),{ls:o,lf:s}}let c=r;return a||(c=this.getLastWorkingHour(r,this.activityCalendar)),s=I(this.activityCalendar,c,n,this.activity),o=I(this.activityCalendar,s,i,this.activity),a||(s=this.getLastWorkingHour(s,this.activityCalendar,"past")),{ls:o,lf:s}}calculateSFLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n}){let a=null,s=null,o=r;return s=I(this.activityCalendar,o,i,this.activity),a=I(this.activityCalendar,s,n,this.activity),{ls:s,lf:a}}calculateSSLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n,isMilestone:a=!1}){let s=null,o=null;if(t===0)return o=I(this.activityCalendar,r,i,this.activity),s=I(this.activityCalendar,o,n,this.activity),{ls:o,lf:s};let c=r;return t<0&&!a&&(c=this.getLastWorkingHour(c,this.activityCalendar,"future")),o=I(this.activityCalendar,c,i,this.activity),s=I(this.activityCalendar,o,n,this.activity),{ls:o,lf:s}}getMinLfFromLinks(t=[]){return t.length?t.reduce((r,i)=>i.lf<r.lf?i:r):!1}calculateSfRestrictionDates(){let t=this.activity.constraint_date,r=this.activity.duration;return{ls:I(this.activityCalendar,t,-r,this.activity),lf:t}}getLastWorkingHour(t,r,i="past"){let n=t instanceof Date?t:new Date(t),a=ht(n).clone();return this.isActivityInInitHour(r,n)&&i==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),lt({dateBaseToCalculate:new Date(a),direction:i,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let i=r instanceof Date?r:new Date(r),a=t.getWorkHours(i)[0];if(!a||!a.includes("-"))return!1;let s=a.split("-")[0];if(!s.includes(":"))return!1;let o=s.split(":");return o.length<2?!1:(s=parseInt(o[0],10),ht.isMoment(r)?r.hours()===s:i.getUTCHours()===s)}},Vs=Ci;function Ys(e){let{parent:t,linkProperty:r,linkDirection:i,calculations:n,gantt:a,direction:s}=e,o=t[r],c=of(t),l=null;if(s==="forward"){let d=cf(o,i,n,a);l=new js(d,t,a),l=l.calculate()}else{let d=lf(o,i,n,a);l=new Vs({linksWithActivityData:d,activity:t,parentData:c,gantt:a}).calculate()}return l}function of(e){return{duration:e.duration,calendarId:e.calendar_id}}function cf(e,t,r,i){return e.length===0?[]:e.map(n=>{let a=i.getLink(n);if(!a)return console.warn(`Link not found: ${n}`),null;let s=Number(a[t]),o=r.get(s);return o?{es:o.es,ef:o.ef,linkLag:a.lag,linkType:a.type}:(console.warn(`Calculations not found for activity: ${s}`),null)}).filter(Boolean)}function lf(e,t,r,i){return e.length===0?[]:e.map(n=>{let a=i.getLink(n);if(!a)return console.warn(`Link not found: ${n}`),null;let s=Number(a[t]),o=r.get(s);if(!o)return null;let c=i.getTask(s);return c?{ls:o.ls,lf:o.lf,linkLag:a.lag||0,linkType:a.type,progress:c.progress,type:c.type}:null}).filter(Boolean)}function Ks(e){let{activityData:t,calculations:r,singleParents:i,direction:n}=e;if(df(t.id,r))return null;let a=uf(t.id,i),s=ff(a,r);return s.length===0?null:pf(s,n)}function df(e,t){return t.has(e)}function uf(e,t){let r=t.get(e);return r?r.childrens:[]}function ff(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function pf(e,t){if(t==="forward"){let r=$s(e,"es"),i=Gs(e,"ef");return{es:r,ef:i}}else{let r=$s(e,"ls"),i=Gs(e,"lf");return{ls:r,lf:i}}}function $s(e,t){return e.reduce((r,i)=>i[t]<r[t]?i:r)[t]}function Gs(e,t){return e.reduce((r,i)=>i[t]>r[t]?i:r)[t]}var Ii={parentWithLinks:Ys,parentWithNoLinks:Ks};var ki=class{constructor(t){this.activity=t.activity,this.direction=t.direction,this.linkProperty=t.direction==="forward"?"$target":"$source",this.linkDirection=t.direction==="forward"?"source":"target",this.calculationsOfParentThatImpactChildrens=t.calculationsOfParentThatImpactChildrens,this.calculations=t.calculations,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.parentCalculationFromChildren=t.parentCalculationFromChildren,this.gantt=t.gantt}handleParentWithLinks(){try{let t=this.getArrayOfIdOfLinkedActivities(this.activity[this.linkProperty]);if(this.direction==="backward"){let i=[h.FNLT];if(this.shouldCalculateParentWithLinksBackward(i)){this.calculateAndStoreParentWithLinks(this.activity);return}if(this.shouldSetDatesToParentsWithLinks(i)){this.setDatesToParentsWithLinksBackward();return}}if(this.areAllLinksCalculated(t)&&this.calculationsOfParentThatImpactChildrens.has(this.activity.id)){this.direction==="forward"&&this.setDatesToParentsWithLinks(),this.direction==="backward"&&this.setDatesToParentsWithLinksBackward();return}this.calculateAndStoreParentWithLinks(this.activity)}catch(t){throw t}}shouldCalculateParentWithLinksBackward(t){let r=t.includes(this.activity.constraint_type),i=!this.calculationOfParentsFromLinks.has(this.activity.id);return r&&i}calculateAndStoreParentWithLinks(t){let r=Ii.parentWithLinks({parent:t,linkProperty:this.linkProperty,linkDirection:this.linkDirection,gantt:this.gantt,calculations:this.calculations,direction:this.direction});this.calculationsOfParentThatImpactChildrens.set(t.id,r),this.calculationOfParentsFromLinks.add(t.id)}areAllLinksCalculated(t){return t.every(r=>this.calculations.has(r))}shouldSetDatesToParentsWithLinks(t){let r=t.includes(this.activity.constraint_type),i=this.calculationOfParentsFromLinks.has(this.activity.id);return r&&i}handleParentWithNoLinks(){let t=Ii.parentWithNoLinks({activityData:this.activity,gantt:this.gantt,singleParents:this.singleParents,calculations:this.calculations,direction:this.direction});t&&this.calculations.set(this.activity.id,t)}setDatesToParentsWithLinks(){if(!this.activity)throw new Error("Error trying to get parent",{cause:{parentActivity:this.activity}});let t=this.singleParents.get(this.activity.id)?.childrens,i=Array.from(this.calculations).filter(s=>t.includes(s[0])).map(s=>s[1]),{minEs:n,maxEf:a}=i.reduce((s,{es:o,ef:c})=>({minEs:new Date(Math.min(s.minEs.getTime(),new Date(o).getTime())),maxEf:new Date(Math.max(s.maxEf.getTime(),new Date(c).getTime()))}),{minEs:new Date(i[0].es),maxEf:new Date(i[0].ef)});this.calculations.set(this.activity.id,{es:n,ef:a}),this.parentCalculationFromChildren.add(this.activity.id)}setDatesToParentsWithLinksBackward(){if(!this.activity)throw new Error("Error trying to get parent",{cause:{parentActivity:this.activity}});let t=this.singleParents.get(this.activity.id)?.childrens,i=Array.from(this.calculations).filter(s=>t.includes(s[0])).map(s=>s[1]),{minLs:n,maxLf:a}=i.reduce((s,{ls:o,lf:c})=>({minLs:new Date(Math.min(s.minLs.getTime(),new Date(o).getTime())),maxLf:new Date(Math.max(s.maxLf.getTime(),new Date(c).getTime()))}),{minLs:new Date(i[0].ls),maxLf:new Date(i[0].lf)});this.calculations.set(this.activity.id,{ls:n,lf:a})}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(i=>{let a=this.gantt.getLink(i)[r||this.linkDirection];return Number(a)})}},zs=ki;var Si=class{constructor({gantt:t,linkProperty:r}){this.gantt=t,this.linkProperty=r,this.structureOfParents=new Map,this.singleParents=new Map}identifyThirdLevelActivities(){try{let t=this.getFirstLevelParents();for(let r of t){let i=this.processEachActivity(r),{activitiesByLevel:n}=i,a=this.getAllLevels(n),s=this.getDeepestLevel(a),o=this.createResult(r,i,s,a);this.structureOfParents.set(r.id,o)}return{structureOfParents:this.structureOfParents,singleParents:this.singleParents}}catch(t){throw t}}getFirstLevelParents(){return this.gantt.getTaskByTime().filter(it.byFirstLevel).filter(it.filterByParentType)}processEachActivity(t){let r=new Set,i=new Set,n=new Map;return this.initializeParent(t),this.gantt.eachTask(a=>{this.processActivity(a,r,i,n)},t.id),{parentsIds:r,allTasks:i,activitiesByLevel:n}}initializeParent(t){let r=Number(t.id),i=!!t[this.linkProperty]?.length,n=t.$level;this.singleParents.set(r,{level:n,hasLink:i,childrens:[]})}processActivity(t,r,i,n){let a=Number(t.id),s=Number(t.parent);i.add(a),this.isProjectActivity(t)&&this.addParentInfo(t,r);let c=this.doesParentExist(s);s!=null&&c&&this.addChildToParent(s,a),this.addActivityToLevel(t,n)}isProjectActivity(t){return t.type==="project"}hasLink(t){return!!t[this.linkProperty]?.length}addParentInfo(t,r){let i=Number(t.id),n=t.$level,a=this.hasLink(t),s={level:n,hasLink:a,childrens:[]};r.add(i),this.singleParents.set(i,s)}doesParentExist(t){return this.singleParents.has(t)}addChildToParent(t,r){this.singleParents.get(t).childrens.push(r)}addActivityToLevel(t,r){let i=t.$level,n=Number(t.parent);r.has(i)||r.set(i,new Map);let a=r.get(i);a.has(n)||a.set(n,[]),a.get(n).push({id:Number(t.id),isParent:this.isProjectActivity(t),calculated:!1})}getAllLevels(t){return new Set(t.keys())}getDeepestLevel(t){return t.size===0?0:Math.max(...t)}createResult(t,r,i,n){let{activitiesByLevel:a,parentsIds:s,allTasks:o}=r;return{parent:t.id,isALinkedParent:this.hasLink(t),levels:n,allParentChildrens:s,allChildrens:o,childrensByLevel:a,currentResolutionLevel:i,canBeCalculated:!1}}},qs=Si;var Di=class{constructor(t,r){this.direction=r,this.gantt=t,this.linkProperty=this.direction==="forward"?"$target":"$source",this.linkDirection=this.direction==="forward"?"source":"target",this.projectDates=t.getSubtaskDates()}tryToCalculateLastLevelChildrens(){this.structureOfParents.forEach(t=>{let{currentResolutionLevel:r,childrensByLevel:i,isALinkedParent:n}=t;if(n)return;let a=i.get(r);for(let[s,o]of a)if(o.filter(l=>!this.calculations.has(l.id)).length===0){let l=this.gantt.getTask(s);this.calculateParentWithNoLinks(l,o);return}})}initActivitiesWaitingForCalculation(){try{this.gantt.getTaskByTime().filter(it.avoidSubproject).forEach(t=>{this.activitiesWaitingForCalculation.add(t.id)})}catch(t){throw t}}identifyParentsWithAndWithoutLinks(){try{let{parentsWithFullProgress:t,pendingParentsWithNoLinks:r,pendingParentsWithLinks:i}=ke.identifyParentsWithAndWithoutLinks({gantt:this.gantt,direction:this.direction,linkProperty:this.linkProperty});this.parentsWithFullProgress=t,this.pendingParentsWithNoLinks=r,this.pendingParentsWithLinks=i}catch(t){throw t}}identifyForbiddenActivitiesLinkedToParentsWithLinks(){try{this.forbiddenActivitiesLinkedToParentsWithLinks=ke.identifyForbiddenActivities({pendingParentsWithLinks:this.pendingParentsWithLinks,gantt:this.gantt,direction:this.direction})}catch(t){throw t}}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(i=>{let a=this.gantt.getLink(i)[r||this.linkDirection];return Number(a)})}async identifyThirdLevelActivities(){try{let{structureOfParents:t,singleParents:r}=new qs({gantt:this.gantt,linkProperty:this.linkProperty}).identifyThirdLevelActivities();this.structureOfParents=t,this.singleParents=r}catch(t){throw t}}processEachActivity(t){let r=new Set,i=new Set,n=new Map,a=new Map;return this.singleParents.set(Number(t.id),{level:t.$level,hasLink:!!t[this.linkProperty].length,childrens:[]}),new Promise((s,o)=>{this.gantt.eachTask(function(c){let l=Number(c.parent);if(i.add(c.id),c.type==="project"){let u={level:c.$level,hasLink:!!c[this.linkProperty].length,childrens:[]};r.add(c.id),this.singleParents.set(Number(c.id),u)}l&&this.singleParents.has(l)&&this.singleParents.get(l).childrens.push(c.id),n.has(c.$level)||n.set(c.$level,new Map);let d=n.get(c.$level);d.has(Number(c.parent))||d.set(Number(c.parent),[]),d.get(Number(c.parent)).push({id:c.id,isParent:c.type==="project",calculated:!1})}.bind(this),t.id),s({parentsIds:r,allTasks:i,activitiesByLevel:n,singleParents:a})})}identifySecondLevelActivities(){try{let t=ke.identifySecondLevelActivities({gantt:this.gantt,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,calculations:this.calculations,linkProperty:this.linkProperty});this.secondLevelActivities=new Set([...this.secondLevelActivities,...t])}catch(t){throw t}}identifyInitialActivities(){try{let{chainStartActivities:t,activitiesStartChainButChildrenOfLinkedParents:r}=ke.identifyInitialActivities({gantt:this.gantt,linkProperty:this.linkProperty,direction:this.direction});this.chainStartActivities=t,r&&(this.activitiesStartChainButChildrenOfLinkedParents=r)}catch(t){throw new Error("Error in identifyInitialActivities",{cause:t})}}calculateSecondLevelActivities(){try{this.direction==="forward"?this.recursiveCalculateEfAndEs(Array.from(this.secondLevelActivities),0,"secondLevel"):this.recursiveCalculateLfAndLs(Array.from(this.secondLevelActivities))}catch(t){throw t}}calculateStartAndFinishOfActivitiesThatStartChain(){try{this.chainStartActivities.forEach(t=>{if(!t||t.progress>100||t.type==="project")return;let r=this.calculateStartAndFinishOfChainOrigin(t,this.direction);if(this.direction==="forward"){let{es:i,ef:n}=r;this.calculations.set(t.id,{es:i,ef:n,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}else{let{ls:i,lf:n}=r;this.calculations.set(t.id,{ls:i,lf:n,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}})}catch(t){throw t}}buildDependencyGraph(t){let r=new Map,i=new Set(this.calculations.keys()),n=new Map;return t.forEach(a=>{a&&n.set(a.id,a)}),n.forEach((a,s)=>{if(i.has(s))return;let o=[];(a[this.linkDirection]||[]).forEach(l=>{let d=this.gantt.getLink(l);if(d){let u=Number(d[this.linkProperty]);o.push(u)}}),o=o.filter(l=>n.has(l)||i.has(l)),r.set(s,o)}),{graph:r,activityMap:n,calculatedActivities:i}}topologicalSort(t,r){let i=new Set,n=new Set,a=[],s=o=>{if(n.has(o))throw new Error("Cyclical dependency detected",{cause:{nodeId:o}});if(!i.has(o)&&!r.has(o)){n.add(o);let c=t.get(o)||[];for(let l of c)s(l);n.delete(o),i.add(o),a.push(o)}};for(let o of t.keys())!i.has(o)&&!r.has(o)&&s(o);return a.reverse()}calculateStartAndFinishOfChainOrigin(t=null,r=null){try{let i=t,n=Number(i.progress);n==="0.00"&&(n=0);let a=this.gantt.getCalendar(i.calendar_id);if(!a)throw new Error(`Error trying to get calendar with id: ${i.calendar_id}`);if((r||this.direction)==="forward"){let o=i.start_date,c=i.end_date;return{es:o,ef:c}}else{if(n>=100)return{ls:ht(i.start_date).clone(),lf:ht(i.end_date).clone()};if(n===0)return this.calculateBackwardWhenZeroProgress(i,a);if(n<100&&n>0)return this.calculateWhenProgressIsBetweenZeroAndOneHundred(i,a)}}catch(i){throw i}}calculateBackwardWhenZeroProgress(t,r){let i=ht(t.start_date).clone(),n=ht(t.end_date).clone(),a=t.duration,s=[h.ASAP,h.ALAP,h.SNET,h.FNET],o=t.constraint_type||h.ASAP;if(s.includes(o))n=this.projectDates.end_date,i=I(r,n,-a,t);else{let c=[h.SNLT,h.MSO],l=[h.FNLT,h.MFO];c.includes(o)&&(i=t.constraint_date,n=I(r,i,a,t)),l.includes(o)&&(n=t.constraint_date,i=I(r,n,-a,t))}return{ls:i,lf:n}}calculateWhenProgressIsBetweenZeroAndOneHundred(t){let r=t.start_date,i=null,n=t.constraint_type||h.ASAP,a=this.projectDates.end_date,s=[h.ASAP,h.ALAP,h.SNET,h.FNET],o=[h.SNLT,h.FNLT];if(s.includes(n))i=Math.max(t.end_date,a);else if(n===h.MSO)i=t.end_date;else if(n===h.MFO||o.includes(n)){let c=Math.min(a,t.constraint_date);i=Math.max(c,t.end_date)}return{ls:r,lf:new Date(i)}}initializeActivitiesWithFullProgress(){try{Array.from(this.activitiesWaitingForCalculation).filter(i=>Number(this.gantt.getTask(i).progress)===100).map(i=>this.gantt.getTask(i)).forEach(i=>{let n=i.type==="project";this.setDatesForActivityWithFullProgress(i),this.activitiesWaitingForCalculation.delete(i.id),n&&this.pendingParentsWithLinks.has(i.id)&&(this.parentCalculationFromChildren.add(i.id),this.calculationsOfParentThatImpactChildrens.set(i.id,{[this.direction==="forward"?"es":"ls"]:i.start_date,[this.direction==="forward"?"ef":"lf"]:i.end_date}),this.calculationOfParentsFromLinks.add(i.id))})}catch(t){throw t}}doCalculationForParentType(t){let r=new zs({activity:t,direction:this.direction,calculationsOfParentThatImpactChildrens:this.calculationsOfParentThatImpactChildrens,calculations:this.calculations,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,parentCalculationFromChildren:this.parentCalculationFromChildren,gantt:this.gantt});this.pendingParentsWithLinks.has(t.id)?r.handleParentWithLinks():r.handleParentWithNoLinks()}},Mt=Di;function hf(e,t,r){let i={es:null,ef:null};if(!e)return i;if([h.SNET,h.SNLT].includes(t)){let n=new Date(e.constraint_date);i.es=n,i.ef=I(r,n,e.duration,e)}else if([h.FNLT,h.FNET].includes(t)){let n=new Date(e.constraint_date);i.es=I(r,n,-e.duration,e),i.ef=n}else if(t===h.MSO){let n=new Date(e.constraint_date);i.es=n,i.ef=I(r,n,e.duration,e)}else if(t===h.MFO){let n=new Date(e.constraint_date);i.es=I(r,n,-e.duration,e),i.ef=n}return i}var ur=hf;var Ti=class{constructor(t){this.referenceActivity=t.activity,this.activityToCalculate=null,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.alapMap=t.calculatedAlapsMap,this.parentsWithLinks=t.parentsWithLinks,this.parentsCalculations=t.parentsCalculations,this.gantt=t.ganttInstance}getEsAndEfFromPreviousCalculatedActivities(t){return this.alapMap.has(t)?this.alapMap.get(Number(t)):this.calculatedActivities.get(Number(t))}calculateSucessorTimes(t,r,i=0,n,a=B.FS){let s=this.gantt.getCalendar(this.referenceActivity.calendar_id);if(!s)throw new Error(`Error trying to get calendar with id: ${this.referenceActivity.calendar_id}`);let o=t,c=null,l=null,d=this.referenceActivity.type==="milestone";return d||(a===B.FS&&n===0?o=lt({dateBaseToCalculate:o,activityCalendar:s,direction:"future",activity:this.referenceActivity}):o=this.mutateTheDateToFutureOrPastInBaseRestriction(t,a,s)),[B.FF,B.SF].includes(a)?(l=I(s,o,i,this.referenceActivity),c=I(s,l,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s))):(c=I(s,o,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s)),l=I(s,c,i,this.referenceActivity)),{es:c,ef:l}}calculateSS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,a=this.referenceActivity.duration,s=t.lag||0;return this.calculateSucessorTimes(r.es,i,a,s,B.SS)}calculateFF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,a=t.lag||0,s=t.lag||0;return this.calculateSucessorTimes(r.ef,n,a,s,B.FF)}calculateFS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,a=this.referenceActivity.duration,s=t.lag||0;return this.calculateSucessorTimes(r.ef,i,a,s,B.FS)}calculateSF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,a=t.lag||0,s=t.lag||0;return this.calculateSucessorTimes(r.es,n,a,s,B.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,r,i){if(![B.FS,B.SS,B.FF].includes(r))return t;let a=[B.FS,B.SS].includes(r)?"future":"past";return lt({dateBaseToCalculate:t,activityCalendar:i,direction:a,activity:this.referenceActivity})}},Js=Ti;var De=class extends Js{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Mt(this.gantt,"forward").calculateStartAndFinishOfChainOrigin(this.referenceActivity);let t=this.links.map(i=>{let n=this.gantt.getLink(i);if(!n)throw new Error("Link data not found",{cause:{linkId:i}});return this.calculateLink(n)}),r=Number(this.referenceActivity.parent);if(this.parentsWithLinks.has(r)){let i=this.gantt.getCalendar(this.referenceActivity.calendar_id),n=this.parentsCalculations.get(r).es,a=I(i,n,this.referenceActivity.duration,this.referenceActivity);t.push({es:n,ef:a})}return dr(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var _i=class{constructor(t){this.gantt=t.gantt,this.direction=t.direction,this.pendingParentsWithNoLinks=t.pendingParentsWithNoLinks,this.pendingParentsWithLinks=t.pendingParentsWithLinks,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.calculations=t.calculations,this.activitiesStartChainButChildrenOfLinkedParents=t.activitiesStartChainButChildrenOfLinkedParents,this.linkProperty=t.linkProperty,this.linkDirection=t.linkDirection}checkActivitiesThatNowCanBeCalculated(t){let r=new Set,i=new Set(t);for(let n of t){let a=this.gantt.getTask(n);a.type==="project"?this.handleProjectActivity(n,a,r,i):this.handleNonProjectActivity(n,a,r,i)}return{activitiesThatCanBeCalculated:r,pendingActivities:i}}handleProjectActivity(t,r,i,n){let a=this.pendingParentsWithNoLinks.has(t),s=this.pendingParentsWithLinks.has(t),o=this.calculationOfParentsFromLinks.has(t);if(a){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(i.add(t),n.delete(t));return}if(s&&o){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(i.add(t),n.delete(t));return}s&&!o&&this.canCalculateParentActivity(r)&&(i.add(t),n.delete(t))}canCalculateParentActivity(t){let r=(t[this.linkProperty]||[]).length===0,i=t.constraint_type;return(this.direction==="forward"?i==="fnlt"||i==="snlt":i==="fnlt")&&r?!0:this.getArrayOfLinkedActivities(t[this.linkProperty]).every(s=>this.calculations.has(s))}handleNonProjectActivity(t,r,i,n){let a=Number(r.parent),s=this.pendingParentsWithLinks.has(a),o=this.calculationOfParentsFromLinks.has(a);if(s&&!o||this.direction==="backward"&&this.activitiesStartChainButChildrenOfLinkedParents.has(t)&&!o)return;if(r.$target.length===0&&r.$source.length===0){i.add(t),n.delete(t);return}let c=this.getLinkedActivities(r[this.linkProperty]),l=c.every(d=>this.calculations.has(d.id));if(this.direction==="backward"&&(c.length===0||l)&&o){i.add(t),n.delete(t);return}l&&(i.add(t),n.delete(t))}getLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let i of t){let n=this.gantt.getLink(i);if(!n)continue;let a=n[this.linkDirection],s=this.gantt.getTask(a);s&&r.push(s)}return r}getArrayOfLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let i of t){let n=this.gantt.getLink(i);n&&r.push(Number(n[this.linkDirection]))}return r}},fr=_i;var Pi=(e,t)=>()=>t()===e;var Ei=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var yf=16,Te=async e=>performance.now()-e>yf?(await rt(),performance.now()):e;var _e=async({pending:e,activityCalculator:t,calculateFn:r,shouldKeepPending:i,isCalculated:n,onActivityProcessed:a,isCurrent:s})=>{let o=new Set(e),c=performance.now();for(;o.size>0;){if(!s())return;c=await Te(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(o);if(l.size===0)break;for(let u of l){if(!s())return;c=await Te(c),r([u])}for(let u of l){if(!s())return;i(u)&&d.add(u),a(u),n(u)&&d.delete(u)}o=d}};var Ri=class extends Mt{constructor(t){super(t,"forward"),this.gantt=t,this.chainStartActivities=new Set,this.secondLevelActivities=new Set,this.pendingParentsWithLinks=new Set,this.pendingParentsWithNoLinks=new Set,this.structureOfParents=new Map,this.singleParents=new Map,this.calculations=new Map,this.calculationsOfParentThatImpactChildrens=new Map,this.alapMap=new Map,this.activitiesWaitingForCalculation=new Set,this.constraintsMap=new Map,this.totalFloatSnltFnlt=new Map,this.totalFloatForMsoMfo=new Map,this.totalFloatForAsap=new Map,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateEfAndEs(t))))))}async iterativeCalculateEfAndEs(t){let r=new fr({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await _e({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:i=>this.calculateStartAndFinishTimes(i),shouldKeepPending:i=>this.calculationOfParentsFromLinks.has(i)&&!this.calculations.has(i),isCalculated:i=>this.calculations.has(i),onActivityProcessed:i=>this.activitiesWaitingForCalculation.delete(i),isCurrent:t})}calculateStartAndFinishTimes(t){t.forEach(r=>{let i=this.gantt.getTask(r);if(i.type==="project")return this.doCalculationForParentType(i);if(!i)throw new Error("Error trying to get activity",{cause:{activityId:r}});let n=i.$target,a=i.constraint_type||h.ASAP,s=[h.SNET,h.SNLT,h.FNLT,h.FNET],o=[h.ASAP,h.ALAP,h.SNET,h.FNET,h.SNLT,h.FNLT],c=this.gantt.getCalendar(i.calendar_id);if(!c)throw new Error(`Error trying to get calendar with id: ${i.calendar_id}`);let l=Number(i.progress),d=null,u=null,f=null;if(l===100){this.setDatesForActivityWithFullProgress(i);return}l>0&&o.includes(a)?({es:d,ef:u}=this.getDatesForActivityWithZeroProgress(i),f=new De({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),a===h.ASAP&&this.totalFloatForAsap.set(r,{es:f.es,ef:f.ef,text:i.text})):{es:d,ef:u}=new De({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),a===h.ALAP&&this.alapMap.set(r,{es:i.start_date,ef:i.end_date,text:i.text});let p=ur(i,a,c);if(s.includes(a)&&(this.constraintsMap.set(r,p),this.totalFloatSnltFnlt.set(r,{es:d,ef:u}),{es:d,ef:u}=this.recalculateInBaseConstraint(a,p,{es:d,ef:u})),[h.MSO,h.MFO].includes(a))if(this.totalFloatForMsoMfo.set(r,{es:d,ef:u}),this.constraintsMap.set(r,p),i.progress===0)d=p.es,u=p.ef;else{let v=i.end_date;a===h.MFO&&(v=Math.max(p.ef,i.end_date)),d=i.start_date,u=v}this.calculations.set(r,{es:d,ef:u}),this.activitiesWaitingForCalculation.delete(r)})}getTheGreatesDateBetweenRestrictionAndEsEf(t,r,i="greater"){if(i==="greater")return r.ef>t.ef?r:t;if(i==="less")return r.ef<t.ef?r:t}setDatesForActivityWithFullProgress(t){this.calculations.set(t.id,{es:t.start_date,ef:t.end_date})}getDatesForActivityWithZeroProgress(t){return{es:t.start_date,ef:t.end_date}}recalculateInBaseConstraint(t,r,i){let n=[h.SNET,h.FNET].includes(t)?"greater":"less",{es:a,ef:s}=this.getTheGreatesDateBetweenRestrictionAndEsEf(r,i,n);return{es:a,ef:s}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let i=this.gantt.getLink(r);if(!i)throw new Error("Error trying to get link",{cause:{linkId:r}});let n=i.source,a=i.target;if(!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type==="project")&&!(!this.gantt.getTask(a)||this.gantt.getTask(a)?.type==="project"))return r}).filter(Boolean)}},Xs=Ri;var Li=class{constructor(t){this.activity=t.activity,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.forwardPathCalculations=t.calculatedForwardActivitiesMap,this.gantt=t.ganttInstance}getForwardOrBackwardCalculations(t,r=null){return r===h.ALAP?this.forwardPathCalculations.get(t):this.calculatedActivities.get(t)}calculateSuccessorTimes(t,r,i=0,n,a=B.FS){let s=this.gantt.getCalendar(this.activity.calendar_id);if(!s)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`);let o=t,c=this.activity.type==="milestone";if(c&&n===0){let d=I(s,o,r,this.activity),u=I(s,d,i,this.activity);return{ls:d,lf:u}}let l={lag:n,workTime:o,activityCalendar:s,lsDataCalculation:r,lfDataCalculation:i,isMilestone:c};if(a===B.FS){let{ls:d,lf:u}=this.calculateFsLink(l);return{ls:d,lf:u}}if(a===B.FF){let{ls:d,lf:u}=this.calculateFFLink(l);return{ls:d,lf:u}}if(a===B.SS){let{ls:d,lf:u}=this.calculateSSlink(l);return{ls:d,lf:u}}if(a===B.SF){let{ls:d,lf:u}=this.calculateSFLink(l);return{ls:d,lf:u}}}calculateSS(t,r=!1){let i=this.getValueForSS(t,r),n=-t.lag||0,a=this.activity.duration,s=t.lag;return this.calculateSuccessorTimes(i,n,a,s,B.SS)}calculateFF(t,r){let i=this.getForwardOrBackwardCalculations(Number(t.target)),n=r===h.ALAP?"ef":"lf",a=i[n],s=-this.activity.duration,o=-t.lag||0,c=t.lag;return this.calculateSuccessorTimes(a,s,o,c,B.FF)}calculateFS(t,r){let i="ls";i=r===h.ALAP?"es":"ls";let n=this.getForwardOrBackwardCalculations(Number(t.target),r),a=-this.activity.duration,s=t.lag||0,o=-t.lag||0;return this.calculateSuccessorTimes(n[i],a,o,s,B.FS)}calculateSF(t,r=!1){let i=r?this.getEarlyStartFromForwardPath(Number(t.target)).ef:this.getForwardOrBackwardCalculations(Number(t.target)).lf,n=-t.lag||0,a=this.activity.duration,s=t.lag;return this.calculateSuccessorTimes(i,n,a,s,B.SF)}getEarlyStartFromForwardPath(t){return this.forwardPathCalculations.get(t)}getValueForSS(t,r){return r?this.getEarlyStartFromForwardPath(Number(t.target)).es:this.getForwardOrBackwardCalculations(Number(t.target))["ls"]}calculateDate(t,r,i){let n=ht(r).clone();return I(t,new Date(n),i,this.activity)}getLastWorkingHour(t,r,i="past"){let n=t instanceof Date?t:new Date(t),a=ht(n).clone();return this.isActivityInInitHour(r,n)&&i==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),lt({dateBaseToCalculate:new Date(a),direction:i,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let i=r instanceof Date?r:new Date(r),a=t.getWorkHours(i)[0];if(!a||!a.includes("-"))return!1;let s=a.split("-")[0];if(!s.includes(":"))return!1;let o=s.split(":");return o.length<2?!1:(s=parseInt(o[0],10),ht.isMoment(r)?r.hours()===s:i.getUTCHours()===s)}calculateFsLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a,isMilestone:s=!1}){let o=null,c=null;if(t===0){let d=this.getLastWorkingHour(r,i,"past");return o=I(i,d,a,this.activity),o=this.getLastWorkingHour(o,i,"past"),c=I(i,o,n,this.activity),{ls:c,lf:o}}let l=r;return s||(l=this.getLastWorkingHour(r,i)),o=I(i,l,a,this.activity),c=I(i,o,n,this.activity),s||(o=this.getLastWorkingHour(o,i,"past",!0)),{ls:c,lf:o}}calculateFFLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a}){let s=null,o=null;if(t===0)return s=I(i,r,a,this.activity),o=I(i,s,n,this.activity),{ls:o,lf:s};let c=r;return t>0&&(c=this.getLastWorkingHour(c,i,"past")),s=I(i,c,a,this.activity),o=I(i,s,n,this.activity),{ls:o,lf:s}}calculateSSlink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a,isMilestone:s=!1}){let o=null,c=null;if(t===0)return c=I(i,r,n,this.activity),o=I(i,c,a,this.activity),{ls:c,lf:o};let l=r;return t<0&&!s&&(l=this.getLastWorkingHour(l,i,"future")),c=I(i,l,n,this.activity),o=I(i,c,a,this.activity),{ls:c,lf:o}}calculateSFLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a}){let s=null,o=null;return t===0?(o=I(i,r,n),s=I(i,o,a,this.activity),{ls:o,lf:s}):(o=I(i,r,n,this.activity),s=I(i,o,a,this.activity),{ls:o,lf:s})}},Zs=Li;var bi=class extends Zs{constructor(t){super(t),this.constraint=t.constraint||h.ASAP,this.parentsWithFullProgress=t.parentsWithFullProgress,this.parentsThatImpactChildrens=t.parentsThatImpactChildrens,this.projectDates=this.gantt.getSubtaskDates()}calculate(){if(this.links.length===0)return new Mt(this.gantt,"backward").calculateStartAndFinishOfChainOrigin(this.activity);let t=this.activity.progress>0&&this.activity.progress<100,r=this.gantt.getTask(this.activity.parent),i=!1;r&&(i=this.parentsThatImpactChildrens.has(Number(this.activity.parent)));let n=this.links.map(s=>{let o=this.gantt.getLink(s);if(!o)throw new Error("Link not found",{cause:{linkId:s}});if(!this.parentsWithFullProgress.has(Number(o.target)))return this.calculateLink(o)}).filter(s=>s);if(n.length!==0){let s=this.getMinLfFromLinks(n);if(n.push(this.calculateTheLsAndLfForTheActivity()),i){let d=this.parentsThatImpactChildrens.get(Number(this.activity.parent));n.push(this.calculateTheLsAndLfForTheActivity(d))}let o=this.getMinDateFromLinks(n),c=o.ls,l=o.lf;return t&&(c=this.activity.start_date,l=this.getMinCalculationLogic(o)),{ls:c,lf:l,minFromLinks:s}}if(i){n.push(this.calculateTheLsAndLfForTheActivity());let o=this.parentsThatImpactChildrens.get(Number(this.activity.parent)).lf,c=I(this.gantt.getCalendar(this.activity.calendar_id),o,-this.activity.duration,this.activity);n.push({ls:c,lf:o});let l=this.getMinDateFromLinks(n);return{ls:l.ls,lf:l.lf,minFromLinks:l}}let a=this.calculateTheLsAndLfForTheActivity();return{ls:a.ls,lf:a.lf,minFromLinks:a}}calculateTheLsAndLfForTheActivity(t=null){try{let r=this.activity.duration,i=this.gantt.getCalendar(this.activity.calendar_id);if(!i)throw new Error(`Calendar not found with id ${this.activity.calendar_id}`);let n=t?t.lf:this.projectDates.end_date;if(!n)throw new Error("End date not found for activity",{cause:{activityId:this.activity.id}});return{ls:I(i,n,-r,this.activity),lf:n}}catch(r){throw Error(r.message)}}SnetSnltMsoMinDate(t){let r=Math.min(t.lf,this.projectDates.end_date);return new Date(Math.max(r,this.activity.end_date))}calculateLink(t){let r=this.gantt.getTask(t.target);if(!r||r.progress>0&&r.type!=="project")return;let i=this.getSpecialCalculationParamForConstraintLink(),n=this.getSpecialParamForSf(),a=this.getSpecialParamForFF();return{0:()=>this.calculateFS(t,i),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t,a),3:()=>this.calculateSF(t,n)}[t.type]()}getSpecialCalculationParamForConstraintLink(){if(this.constraint===h.ALAP)return h.ALAP;if(this.constraint===h.FNET||this.constraint===h.SNET)return"snet-fnet";if(this.constraint===h.FNLT)return h.FNLT}getSpecialParamForSf(){return!![h.ALAP].includes(this.constraint)}getSpecialParamForFF(){return!![h.MFO,h.MSO].includes(this.constraint)}getMinCalculationLogic(t){if(this.constraint===h.ALAP)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.FNET)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.FNLT)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.MFO)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.SNET||this.constraint===h.SNLT||this.constraint===h.MSO)return this.SnetSnltMsoMinDate(t);if(this.constraint===h.ASAP)return this.getMinDateBasedOnConstraint(t)}getMinDateFromLinks(t){try{return this.constraint===h.ALAP||this.constraint===h.ASAP?t.reduce((i,n)=>n.lf<i.lf?n:i):t.reduce((r,i)=>i.ls<r.ls?i:r)}catch(r){throw new Error(`Function: getMinDateFromLinks in LinksConstraintCalculator - ${r.message}`)}}getMinLfFromLinks(t){return t.reduce((r,i)=>i.lf<r.lf?i:r)}getMinDateBasedOnConstraint(t,r=this.constraint){let i=Math.min(t.lf,this.projectDates.end_date),n=this.activity.end_date,a=this.activity.constraint_date;if(r===h.ASAP)return new Date(Math.max(i,n));if(r===h.FNET||r===h.FNLT){let s=Math.min(i,a);return new Date(Math.max(i,s))}if(r===h.ALAP)return new Date(Math.min(i,n))}},Qs=bi;function mf(e,t,r){let i={ls:null,lf:null};return r===h.MSO&&(i.ls=t.constraint_date,i.lf=I(e,i.ls,t.duration,t)),r===h.MFO&&(i.lf=t.constraint_date,i.ls=I(e,i.lf,-t.duration,t)),i}var to=mf;var wi=class extends Mt{constructor(t,r,i){super(t,"backward"),this.gantt=t,this.chainStartActivities=new Set,this.secondLevelActivities=new Set,this.pendingParentsWithLinks=new Set,this.pendingParentsWithNoLinks=new Set,this.structureOfParents=new Map,this.singleParents=new Map,this.calculationsOfParentThatImpactChildrens=new Map,this.activitiesWaitingForCalculation=new Set,this.calculations=new Map,this.mapOfRelationsWithActivitiesIds=new Map,this.activitiesWaitingForCalculation=new Set,this.forwardPathCalculations=r,this.forwardConstraintsMap=i,this.constraintMap=new Map,this.minFromLinks=new Map,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.parentsWithFullProgress=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateLfAndLs(t))))))}async iterativeCalculateLfAndLs(t){let r=new fr({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await _e({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:i=>this.calculateStartAndFinishTimes(i),shouldKeepPending:i=>this.calculationOfParentsFromLinks.has(i)&&!this.calculations.has(i),isCalculated:i=>this.calculations.has(i),onActivityProcessed:i=>this.activitiesWaitingForCalculation.delete(i),isCurrent:t})}setDatesToParentsWithLinks(t){if(!t)throw new Error("Error trying to get parent",{cause:{receivedParentData:t}});let r=this.singleParents.get(t.id).childrens,n=Array.from(this.calculations).filter(o=>r.includes(o[0])).map(o=>o[1]),{minLs:a,maxLf:s}=n.reduce((o,{ls:c,lf:l})=>({minLs:new Date(Math.min(o.minLs.getTime(),new Date(c).getTime())),maxLf:new Date(Math.max(o.maxLf.getTime(),new Date(l).getTime()))}),{minLs:new Date(n[0].ls),maxLf:new Date(n[0].lf)});this.calculations.set(t.id,{ls:a,lf:s})}calculateStartAndFinishTimes(t){t.forEach(r=>{let i=this.gantt.getTask(r);if(!i)throw new Error("Activity not found",{cause:{activityId:r}});let n=i.$source,a=i.constraint_type||h.ASAP,s=Number(i.progress);if(this.activitiesStartChainButChildrenOfLinkedParents.has(r)){if(this.calculationsOfParentThatImpactChildrens.has(Number(i.parent))&&this.calculationsOfParentThatImpactChildrens.get(Number(i.parent))===!1){let{ls:d,lf:u}=this.calculateStartAndFinishOfChainOrigin(i,this.direction);this.setCalculations(i,d,u);return}return this.doCalculationForActivitiesThatStartLinkButHisParentIsLinked(i)}if(i.type==="project")return this.doCalculationForParentType(i);if(s===100){this.setDatesForActivityWithFullProgress(i);return}if(this.allLinkedActivitiesHasProgress(n,i)){this.setWhenAllLinkedActivitiesHasProgress(i);return}if(s>0&&s<100&&(a===h.MSO||a===h.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(i,a);return}if(a===h.MSO||a===h.MFO){this.recalculateInBaseRestriction(i,a);return}let{ls:o,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(n,i,a,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(a===h.SNLT||a===h.FNLT)&&({ls:o,lf:c}=this.getTheLessLateInBasEsEfConstraint(i.id,{ls:o,lf:c},a)),this.setCalculations(i,o,c),this.minFromLinks.set(i.id,{ls:l.ls,lf:l.lf})})}getTheLessLateInBasEsEfConstraint(t,r,i){let n=this.forwardConstraintsMap.get(t);if(!n){let a=this.gantt.getTask(t),s=this.gantt.getCalendar(a.calendar_id);n=ur(a,i,s)}return r.lf<n.ef?r:{ls:n.es,lf:n.ef}}allLinkedActivitiesHasProgress(t){try{let r=!0;for(let i of t){let n=this.gantt.getLink(i);if(!n)continue;let a=this.gantt.getTask(n.target);a&&(a.type==="project"&&(r=!1),a.progress===0&&(r=!1))}return r}catch(r){throw new Error(r.message)}}setDatesForActivityWithFullProgress(t){this.setCalculations(t,t.start_date,t.end_date)}setWhenAllLinkedActivitiesHasProgress(t){let r=Number(t.parent),{ls:i,lf:n}=this.calculateStartAndFinishOfChainOrigin(t,"backward");if(this.calculationsOfParentThatImpactChildrens.has(r)){i=t.start_date;let a=this.calculationsOfParentThatImpactChildrens.get(r);a&&typeof a=="object"&&a.lf!=null&&(n=new Date(Math.min(n,a.lf)))}this.setCalculations(t,i,n)}setWhenActivitiesHasProgressButLessThanOneHundred(t,r){if(r===h.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(r===h.MFO){let i=Math.min(t.constraint_date,this.projectDates.end_date),n=new Date(Math.max(i,t.end_date));this.setCalculations(t,t.start_date,n);return}}setCalculations(t,r,i){this.calculations.set(t.id,{ls:r,lf:i,text:t.text})}calculateLfandLsFromLinks(t,r,i,n,a){return new Qs({links:t,activity:r,calculatedActivitiesMap:this.calculations,calculatedForwardActivitiesMap:this.forwardPathCalculations,constraint:i,parentsWithFullProgress:n,parentsThatImpactChildrens:a,ganttInstance:this.gantt}).calculate()}recalculateInBaseRestriction(t,r){try{let i=this.gantt.getCalendar(t.calendar_id);if(!i)throw new Error(`Error trying to get calendar with id: ${t.calendar_id}`);let n=to(i,t,r);this.constraintMap.set(t,n),this.setCalculations(t,n.ls,n.lf)}catch(i){throw new Error(i.message)}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let i=this.gantt.getLink(r).source,n=this.gantt.getLink(r).target;if(!(!this.gantt.getTask(i)||this.gantt.getTask(i)?.type==="project")&&!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type==="project"))return r}).filter(Boolean)}doCalculationForActivitiesThatStartLinkButHisParentIsLinked(t){let r=Number(t.parent),i=this.calculationsOfParentThatImpactChildrens.get(r),n=0,a=0;if([h.ASAP,h.ALAP,h.SNET,h.FNET].includes(t.constraint_type))if(Number(t.progress)>0){let l=this.projectDates.end_date;a=new Date(Math.min(l,i.lf)),n=t.start_date}else a=i.lf,n=I(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t);if([h.SNLT].includes(t.constraint_type)){let l=t.constraint_date,d=this.calculationsOfParentThatImpactChildrens.get(r),u=I(this.gantt.getCalendar(t.calendar_id),d.lf,-t.duration,t);n=new Date(Math.min(l.getTime(),u.getTime())),a=I(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}if([h.FNLT].includes(t.constraint_type)){let l=t.constraint_date,d=this.calculationsOfParentThatImpactChildrens.get(r);n=new Date(Math.min(l.getTime(),d.lf.getTime())),a=I(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}[h.MSO].includes(t.constraint_type)&&(n=t.constraint_date,a=I(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)),[h.MFO].includes(t.constraint_type)&&(a=t.constraint_date,n=I(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t));let s=this.projectDates.end_date,o=[{ls:n,lf:a}];o.push({ls:I(this.gantt.getCalendar(t.calendar_id),s,-t.duration,t),lf:s});let c=this.getMinLfFromLinks(o);this.calculations.set(t.id,{ls:c.ls,lf:c.lf,text:t.text})}getMinLfFromLinks(t=[]){return t.length?t.reduce((r,i)=>i.lf<r.lf?i:r):!1}},eo=wi;function ro(){return null}var io=({forward:e,backward:t,id:r,activity:i,gantt:n,projectDates:a})=>({totalFloat:{es:e.calculations.get(r)?.es||0,ef:e.calculations.get(r)?.ef||0,ls:t.calculations.get(r)?.ls||0,lf:t.calculations.get(r)?.lf||0,constraintsMap:e.constraintsMap.get(r),totalFloatSnltFnlt:e.totalFloatSnltFnlt.get(r),totalFloatForMsoMfo:e.totalFloatForMsoMfo.get(r),minFromLinks:t.minFromLinks.get(r),activity:i,gantt:n},freeFloat:{forwardMap:e.calculations||new Map,backwardMap:t.calculations||new Map,activity:i,projectDates:a,gantt:n}});var Oi=class{constructor(t){this.gantt=t.gantt,this.activity=t.activity,this.es=t.es,this.ef=t.ef,this.ls=t.ls,this.lf=t.lf,this.constrainstMap=t.constraintsMap,this.totalFloatSnltFnlt=t.totalFloatSnltFnlt,this.totalFloatForMsoMfo=t.totalFloatForMsoMfo,this.minFromLinks=t.minFromLinks}getTotalFloat(){let{constraint_type:t}=this.activity,r=Number(this.activity.progress);if(r===100)return 0;if(t||(t=h.ASAP),t===h.ASAP||!t)return r===0?this.calculateAsap():this.calculateAsapWithProgress();if(t===h.ALAP)return r===0?this.calculateAlap():this.calculateAlapWithProgress();if(t===h.SNET||t===h.FNET)return r===0?this.calculateSnetFet():this.calculateSnetFnetSnltWithProgress();if(t===h.SNLT)return r===0?this.calculateSnltFnlt():this.calculateSnetFnetSnltWithProgress();if(t===h.FNLT)return r===0?this.calculateSnltFnlt():this.calculateFnltWithProgress();if(t===h.MSO||t===h.MFO)return r===0?this.calculateMsoMfo():this.calculateMsoMfoWithProgress()}calculateAsap(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateAsapWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let r=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateAlap(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r),n=this.calculationWithCalendar(this.lf,this.activity.end_date);return this.getMinValue(i,n)/this.gantt.config.hoursPerDay}calculateAlapWithProgress(){return this.calculationWithCalendar(this.lf,this.ef)/this.gantt.config.hoursPerDay}calculateSnetFnetSnltWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let r=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateFnltWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef),r=this.calculationWithCalendar(this.activity.constraint_date,this.ef);if(this.minFromLinks){let i=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r,i)/this.gantt.config.hoursPerDay}return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateMsoMfoWithProgress(){return this.calculationWithCalendar(this.lf,this.ef)/this.gantt.config.hoursPerDay}calculateSnetFet(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateSnltFnlt(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r);if(!this.totalFloatSnltFnlt&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let n=0;return this.activity.constraint_type===h.SNLT?n=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatSnltFnlt.es):n=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatSnltFnlt.ef),this.getMinValue(n,i)/this.gantt.config.hoursPerDay}calculateMsoMfo(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r);if(!this.totalFloatForMsoMfo&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let n=0;return this.activity.constraint_type===h.MSO?n=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatForMsoMfo.es):n=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatForMsoMfo.ef),this.getMinValue(n,i)/this.gantt.config.hoursPerDay}getMinValue(...t){return Math.min(...t)}calculationWithCalendar(t,r){return this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)})}},no=Oi;var xi=class{constructor(t){this.gantt=t.gantt,this.activity=t.activity,this.forwardMap=t.forwardMap,this.backwardMap=t.backwardMap,this.projectDates=t.projectDates,this.linksFreeFloatArray=[],this.linksFreeFloatObject={},this.durationCache=new Map}getFreeFloat(){let t=Number(this.activity.progress),r=this.getConstraintType();return this.calculateFreeFloatOfLink(r),{activityFreeFloat:t===100?0:this.getFreeFloatBaseConstraint(r),linksFreeFloat:this.linksFreeFloatObject}}getFreeFloatBaseConstraint(t){return t===h.MSO||t===h.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=h.ASAP){let r=this.activity.$source.map(i=>{let{LINK:n,LINK_TYPE:a}=this.getLinkData(i),s=this.gantt.getTask(n.target);if(!s)return{linkId:n.id,freeFloat:null,hasProgress:!1};let o=Number(s.progress)>0,{sucessorDateToCalculate:c,predecessorDateToCalculate:l}=this.getDatesFromSucessorAndPredecessor(a,t,s),d=this.calculationWithCalendar(c,l),u=this.parseHoursToDays(d)-this.parseHoursToDays(n.lag),f=Math.max(0,u);return this.linksFreeFloatObject[n.id]=f,{linkId:n.id,freeFloat:f,hasProgress:o}}).filter(i=>i.freeFloat!==null&&i.freeFloat!==void 0);return this.linksFreeFloatArray=r,r}calculateGeneral(t=h.ASAP){let r=this.getMinFloat(this.linksFreeFloatArray),i=this.calculateFreeFloatForEndOfProject(t),n=0;return[h.SNLT,h.FNLT].includes(t)?n=this.doCalculationForSnltFnlt(t,i,r):n=this.doGeneralCalculation(i,r),Math.max(0,n)}getConstraintType(){let{constraint_type:t}=this.activity;return t||(t=h.ASAP),t}getDatesFromSucessorAndPredecessor(t,r,i){let n=i.constraint_type===h.ALAP,a=this.getSucessorAndPredecessorDates({constraint:r,isSuscessorAlap:n,sucessorId:i.id,predecessorId:this.activity.id}),s=new Date,o=new Date;return s=a[t].sucessor,o=a[t].predecessor,{sucessorDateToCalculate:s,predecessorDateToCalculate:o}}doGeneralCalculation(t,r){return r===null?t:this.getMinValue(r,t)}doCalculationForSnltFnlt(t,r,i){let n=this.calculateFreeFloatOfRestriction(t);return this.getMinValue(i,r,n)}calculateFreeFloatForEndOfProject(t){return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===h.ALAP?this.backwardMap.get(this.activity.id).lf:this.forwardMap.get(this.activity.id).ef))}calculateFreeFloatOfRestriction(t){return this.parseHoursToDays(this.calculationWithCalendar(this.activity.constraint_date,t===h.FNLT?this.forwardMap.get(this.activity.id).ef:this.forwardMap.get(this.activity.id).es))}getLinkData(t){let r=this.gantt.getLink(t)||{},i=Gt(r.type);return{LINK:r,LINK_TYPE:i}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:r,sucessorId:i,predecessorId:n}){let a=({direction:s,constraint:o=h.ASAP})=>o===h.ALAP?this.backwardMap.get(n)[s]:this.forwardMap.get(n)[s];if(t===h.ASAP||t===h.SNET||t===h.FNET||t===h.MSO||t===h.MFO)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"es"})}};if(t===h.ALAP)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({constraint:h.ALAP,direction:"lf"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({constraint:h.ALAP,direction:"ls"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({constraint:h.ALAP,direction:"lf"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({constraint:h.ALAP,direction:"ls"})}};if(t===h.SNLT)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"es"})}};if(t===h.FNLT)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"es"})}}}calculateMsoMfo(t){let r=this.activity.constraint_date||new Date,i=t===h.MSO?this.forwardMap.get(this.activity.id).es:this.forwardMap.get(this.activity.id).ef,n=this.calculationWithCalendar(r,i);return Math.max(0,this.parseHoursToDays(n))}getMinValue(...t){let r=t.filter(i=>i!=null);return r.length?Math.min(...r):0}calculationWithCalendar(t,r){let i=`${r.getTime()}_${t.getTime()}`;if(this.durationCache.has(i))return this.durationCache.get(i);let a=this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)});return this.durationCache.set(i,a),a}parseHoursToDays(t){return t?t/this.gantt.config.hoursPerDay:0}getMinFloat(t){if(!t?.length)return null;let r=t.filter(i=>!i.hasProgress).map(i=>i.freeFloat);return r.length===0?null:Math.min(...r)}},ao=xi;var so=e=>({totalFloat:new no(e.totalFloat).getTotalFloat(),freeFloat:new ao(e.freeFloat).getFreeFloat()});var Ni=async({activityIds:e,forward:t,backward:r,gantt:i,projectDates:n,isCurrent:a})=>{let s=performance.now(),o=new Map,c=new Map;for(let l of e){if(a&&!a())return{totalFloatMap:o,freeFloatMap:c};let d=i.getTask(l);if(!d)continue;let u=io({forward:t,backward:r,id:l,activity:d,gantt:i,projectDates:n}),{totalFloat:f,freeFloat:p}=so(u);o.set(l,f),c.set(l,p),s=await Te(s)}return{totalFloatMap:o,freeFloatMap:c}};var Fi=class{constructor(t){this.gantt=t,this.forwardPathCalculations=null,this.backwardPathCalculations=null,this.totalFloat=new Map,this.freeFloat=new Map,this.currentCalculationId=0}getCurrentCalculationId=()=>this.currentCalculationId;async calculate(t){let r=++this.currentCalculationId,i=Pi(r,this.getCurrentCalculationId);try{let n=t||this.gantt;if(this.gantt=n||ro(),Ei(this.gantt))return!1;let a=new Xs(this.gantt);if(await a.calculateAsync(i),!i())return!1;let s=a.calculations,o=a.constraintsMap,c=new eo(this.gantt,s,o);if(await c.calculateAsync(i),!i())return!1;this.forwardPathCalculations=s,this.backwardPathCalculations=c.calculations;let{totalFloatMap:l,freeFloatMap:d}=await this.calculateFloatsAsync(a,c,i);return i()?(this.totalFloat=l,this.freeFloat=d,this.gantt.refreshData(),!0):!1}catch(n){return this.forwardPathCalculations?.size,!1}}async calculateFloatsAsync(t,r,i){try{let n=this.gantt.getSubtaskDates(),a=Array.from(this.forwardPathCalculations.keys());return await Ni({activityIds:a,forward:t,backward:r,gantt:this.gantt,projectDates:n,isCurrent:i})}catch(n){return this.forwardPathCalculations?.size,{totalFloatMap:new Map,freeFloatMap:new Map}}}},oo=Fi;var gf=e=>e==="fnet"||e==="fnlt"||e==="mfo",vf=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function Af(e,t){let r=e.constraintDate;if(!r||!gf(e.constraintType))return r;let i=vf(r);if(r.getTime()!==i.getTime())return r;let n=t.getClosestWorkTime({date:i,dir:"future",task:e});return n.getUTCFullYear()===r.getUTCFullYear()&&n.getUTCMonth()===r.getUTCMonth()&&n.getUTCDate()===r.getUTCDate()?Jr(e,t):r}function Cf(e){return{calculateEndDate:({start_date:t,duration:r})=>e.calculateEndDate(t,r),calculateDuration:({start_date:t,end_date:r})=>e.calculateDuration(t,r),getWorkHours:t=>e.getWorkHours(t),$gantt:{getClosestWorkTime:({date:t,dir:r,unit:i})=>e.getClosestWorkTime({date:t,direction:r,unit:i??"hour"})}}}function If(e){let t=new Map;e.forEachActivity((n,a)=>t.set(String(a),n));let r=new Map,i=(n,a)=>{let s=r.get(n);if(s!=null)return s;let c=t.get(n)?.parentId??null,l=0;return c!==null&&!a.has(n)&&(a.add(n),l=i(String(c),a)+1),r.set(n,l),l};for(let n of t.keys())i(n,new Set);return r}function kf(e){let t=If(e),r=new Map;return e.forEachActivity((i,n)=>{let a=String(n);r.set(a,{id:Number(n),parent:i.parentId===null?0:Number(i.parentId),$level:t.get(a)??0,$source:e.getOutgoingLinkIds(a),$target:e.getIncomingLinkIds(a),start_date:i.startDate,end_date:i.endDate,duration:i.durationHours,progress:i.progress,type:i.type,calendar_id:i.calendarId,constraint_type:i.constraintType,constraint_date:Af(i,e)})}),r}function Sf(e){let t=new Map;for(let s of e.values()){let o=t.get(s.parent);o?o.push(s):t.set(s.parent,[s])}let r=[],i=new Set,n=[],a=s=>{if(s)for(let o=s.length-1;o>=0;o-=1)n.push(s[o])};for(a(t.get(0));n.length>0;){let s=n.pop();i.has(s)||(i.add(s),r.push(s),a(t.get(s.id)))}if(r.length<e.size)for(let s of e.values())i.has(s)||r.push(s);return r}function Df(e){let t=null,r=null;return e.forEachActivity(i=>{if(i.startDate){let n=i.startDate.getTime();t=t==null?n:Math.min(t,n)}if(i.endDate){let n=i.endDate.getTime();r=r==null?n:Math.max(r,n)}}),{start_date:new Date(t??0),end_date:new Date(r??0)}}async function co(e,t){let r=new Map,i=c=>{let l=c==null?"__default__":String(c),d=r.get(l);if(d)return d;let u=e.calendarReader.getCalendar(String(c)),f=Cf(u);return r.set(l,f),f},n=Df(e);await rt();let a=kf(e);await rt();let s=[...a.values()].sort((c,l)=>(c.start_date?.getTime()??0)-(l.start_date?.getTime()??0));await rt();let o=Sf(a);return{fullyParsed:!0,config:{hoursPerDay:t},getTask:c=>a.get(String(c))??null,getLink:c=>{let l=e.getLink(c);return l?{...l,source:Number(l.source),target:Number(l.target),lag:l.lag}:null},getCalendar:i,getChildren:c=>e.getChildren(c).map(l=>Number(l)),eachTask:c=>{for(let l of o)c(l)},getTaskByTime:()=>s,getSubtaskDates:()=>n,refreshData:()=>{}}}var Tf=1e3;async function pr(e,t){let r=await co(e,t),i=new oo(r);if(!await i.calculate(r))return;let a=i.forwardPathCalculations,s=i.backwardPathCalculations,o=i.totalFloat,c=i.freeFloat,l=f=>f==null?null:new Date(f),d=new Set([...a?.keys()??[]]),u=0;for(let f of d){++u>=Tf&&(u=0,await rt());let p=e.getActivity(f);if(!p)continue;let v=a?.get(f),S=s?.get(f),A=o.get(f)??null,D=Number(p.progress??0),m={earlyStart:l(v?.es),earlyFinish:l(v?.ef),lateStart:l(S?.ls),lateFinish:l(S?.lf),totalSlackHours:A},T=String(f);e.setActivityFields(T,{criticalPath:m,isCritical:D<100&&A!=null&&A<=0,freeSlackHours:c.get(f)?.activityFreeFloat??null})}}function hr(e){let t=[],r=[];e.forEachActivity((n,a)=>{n.parentId===null&&t.push(String(a))});let i=n=>{let a=e.getActivity(String(n));if(!a)return 0;let s=[...e.getChildren(String(n))],o;if(s.length===0){let c=pt(a),l=c&&Number(c.cost)||0;o=(Number(a.progress)||0)/100*l}else{let c=0;for(let l of s)c+=i(String(l));o=c}return e.setActivityField(String(n),L.REAL_COST,o),r.push(String(n)),o};for(let n of t)i(n);return r}var lo=new Set(["activity-outdent","activity-indent"]);var uo=new Set(["activity-outdent","activity-indent"]);var Pe=new Set([E.TEXT,E.DESCRIPTION,E.COST,E.USED_COST,E.CUSTOM_ID,E.RESPONSABLES,E.SUBCONTRACT_ID,E.TAGS]),_f=new Set(["selection-toggle","selection-replace","visibility-set","sir-sync","activity-lookahead-sync"]);function Pf(e){return e.kind==="inline-edit"?Pe.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>Pe.has(t.column)):!1}function po(e,t){return!(_f.has(e.kind)||t.has(e.kind)||Pf(e))}function Ee(e){return po(e,lo)}function Mi(e){return po(e,uo)}function Wi(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?e.column===E.PROGRESS:e.kind==="bulk-edit"?e.edits.some(t=>t.column===E.PROGRESS):!1}function Ef(e){return Mi(e)&&Wi(e)}var fo=new Set([E.PROGRESS,E.HH_WORK_TIME,E.DURATION,E.COST,E.USED_COST,E.REAL_COST]);function Rf(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?fo.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>fo.has(t.column)):!1}var st={AUTOSCHEDULE:"autoschedule",PARENT_BOUNDS:"parent-bounds",PARENT_PROGRESS:"parent-progress",REAL_WORK:"real-work",EXPECTED_PROGRESS:"expected-progress",REAL_COST:"real-cost",CRITICAL_PATH:"critical-path"};function ho(e,t,r){let i=new Set;t.ran&&i.add(st.AUTOSCHEDULE),i.add(st.PARENT_BOUNDS),Rf(e)&&i.add(st.PARENT_PROGRESS),Wi(e)&&i.add(st.REAL_WORK);let n=!r.skipAutoSchedule;return n&&Mi(e)&&i.add(st.EXPECTED_PROGRESS),n&&Ef(e)&&i.add(st.REAL_COST),n&&Mi(e)&&Ee(e)&&!r.skipCriticalPath&&i.add(st.CRITICAL_PATH),i}async function Y(e,t){let r=Lf(t),i=r.has(st.AUTOSCHEDULE)?await bf(e,t.autoscheduleFrom):Of();return await xf(e.adapter,t,i.scheduledIds,r),await Nf(e,r,t.now),i}function Lf(e){let t=e.autoscheduleFrom!==null,r=!e.options.skipAutoSchedule&&t;return ho(e.action,{requested:t,ran:r},e.options)}async function bf(e,t){let r=t==="roots"?{}:{triggerId:t},i=await e.scheduler.schedule(r),n=wf(e.adapter,i.updatedIds);return ge(e.adapter,i),n}function wf(e,t){let r=[],i=new Map;for(let n of t){let a=String(n);r.push(a);let s=e.getActivity(a);s&&(i.set(a,j(s)),e.noteScheduledBefore(a,s))}return{scheduledIds:r,scheduledBeforeImages:i}}function Of(){return{scheduledIds:[],scheduledBeforeImages:new Map}}async function xf(e,t,r,i){let n=t.collectDirty?t.collectDirty(r):Ss(t.recomputeParentsFrom,r);await ve(e,n,i.has(st.PARENT_PROGRESS),{recomputeRealWork:i.has(st.REAL_WORK)})}async function Nf(e,t,r){t.has(st.EXPECTED_PROGRESS)&&r!==null&&(cr(e.adapter,r,e.defaultBaseCalendarId??null),or(e.adapter,r),Yt(e.adapter,e.sector.statusCriteria)),t.has(st.REAL_COST)&&hr(e.adapter),t.has(st.CRITICAL_PATH)&&await pr(e.adapter,e.sector.hoursPerDay)}var Ff=new Set([E.CONSTRAINT_TYPE,E.CONSTRAINT_DATE]),Mf=new Set(["mso","mfo"]);function yr(e){return Ff.has(e)}function mr(e,t,r,i){let n=r.getActivity(e);if(!n)return!1;let a=n.constraintType;if(!a||wt.has(a)||Mf.has(a))return!1;let s=Ui(n.startDate),o=Ui(r.getLastStartDate(e));if(!o||!s||s.getTime()!==o.getTime())return!1;let c=Wf(t,a,String(n.calendarId??""),i),l=Ui(n.constraintDate);return Uf(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function Wf(e,t,r,i){if(e===null)return null;let n=i.getCalendar(r);return n?kt(e,n,t):e}function Ui(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function Uf(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function gr(e,{postMutationArgs:t,revertTargets:r,revert:i}){let{scheduledIds:n,scheduledBeforeImages:a}=await Y(e,yo(t)),s=!1;for(let{activityId:o,priorConstraintDate:c}of r){let l=i(o,c);s=s||l}if(s){let o=await Y(e,yo(t));n=Hf(n,o.scheduledIds),a=jf(a,o.scheduledBeforeImages)}return Ee(t.action)&&await Y(e,Bf(t)),{scheduledIds:n,scheduledBeforeImages:a}}function yo(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function Bf(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function Hf(e,t){let r=new Set(e);for(let i of t)r.add(i);return[...r]}function jf(e,t){let r=new Map(e);for(let[i,n]of t)r.has(i)||r.set(i,n);return r}function Vf(e,t){let r=i=>i.getTime();return r(e.startDate)!==r(t.startDate)||r(e.endDate)!==r(t.endDate)||e.durationHours!==t.durationHours}function Bi(e,t,r){let i=[];for(let n of r){let a=e.get(n);if(!a)continue;let s=a.pendingRequestIds??[];if(!Jt({pendingRequestIds:s}))continue;let o=t.getActivity(n),c=o==null;if(!c&&!Vf(a,o))continue;let l=c?"activity_deleted":"date_changed";for(let d of s)i.push({kind:"sir-auto-reject",activityId:n,sirId:d,reason:l});c||t.setActivityField(n,"pendingRequestIds",[])}return i}function K(e,t){let r=new Set;for(let l of t.touchedIds)r.add(l);for(let l of t.scheduledIds)r.add(l);if(t.includeAllIds)for(let l of e.getAllIds())r.add(l);let i=new Map(t.beforeSnap),n=e.peekWriteCapture();if(n)for(let l of n.dirty){if(r.has(l))continue;let d=n.before.get(l),u=e.getActivity(l);!d||!u||Object.keys(fi(d,u)).length!==0&&(i.set(l,d),r.add(l))}if(t.scheduledBeforeImages)for(let[l,d]of t.scheduledBeforeImages){let u=String(l);i.has(u)||(i.set(u,d),r.add(u))}let a=t.sirDetection==="before-diff"?Bi(i,e,r):[],s=ks(e,i,r),o=t.sirDetection==="after-diff"?Bi(i,e,r):a,c=t.warnings??[];return{source:t.source,activities:s,links:t.links??[],calendars:[],trackingEvents:t.trackingEvents??[],...o.length>0?{effects:o}:{},...c.length>0?{warnings:c}:{}}}function gt(e){let t={id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)};return e.proplannerId!=null&&(t.proplannerId=Number(e.proplannerId)),e.ganttId!=null&&(t.ganttId=Number(e.ganttId)),e.sectorId!=null&&(t.sectorId=Number(e.sectorId)),t}function vr(e,t,r){let i=[];for(let{op:n,finalLinkId:a,rejected:s}of e){if(s!==null)continue;if(n.kind==="create"){if(!a)continue;let d=r.getLink(a);if(!d)continue;i.push({id:String(a),kind:"created",fields:{source:{before:void 0,after:String(d.source)},target:{before:void 0,after:String(d.target)},type:{before:void 0,after:d.type},lag:{before:void 0,after:Number(d.lag)}},after:gt(d)});continue}if(n.kind==="delete"){let d=t.get(n.linkId);i.push({id:String(n.linkId),kind:"deleted",fields:d?{source:{before:String(d.source),after:void 0},target:{before:String(d.target),after:void 0},type:{before:d.type,after:void 0},lag:{before:Number(d.lag),after:void 0}}:void 0,after:null});continue}let o=t.get(n.linkId),c=r.getLink(n.linkId);if(!c)continue;let l={};o&&o.type!==c.type&&(l.type={before:o.type,after:c.type}),o&&Number(o.lag)!==Number(c.lag)&&(l.lag={before:Number(o.lag),after:Number(c.lag)}),i.push({id:String(n.linkId),kind:"updated",fields:l,after:gt(c)})}return i}function le(e,t){let r=new Map;if(!e.getActivity(t))return r;for(let i of e.getIncomingLinkIds(t)){let n=e.getLink(i);n&&r.set(String(n.id),Number(n.lag))}return r}function de(e,t,r){let i=[];if(!t.getActivity(r))return i;for(let n of t.getIncomingLinkIds(r)){let a=t.getLink(n);if(!a)continue;let s=e.get(String(a.id));s===void 0||s===Number(a.lag)||i.push({id:String(a.id),kind:"updated",fields:{lag:{before:s,after:Number(a.lag)}},after:gt(a)})}return i}function Ar(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function mo(e,t,r){let{adapter:i,ctx:n,scheduler:a,sector:s}=r,o=xt(e.column);if(!o)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);Yf(e.column)&&a.invalidateExpandedLinksCache(),e.column===L.PARENT&&a.invalidateAllCaches();let c=n.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let l=o.canEdit(c,n.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??R.CANNOT_EDIT,alertKey:l.alertKey};let d=o.parseInput(e.newValue,c,n);if(!d.ok)return{ok:!1,reason:d.reason??R.PARSE_ERROR};let u=Reflect.get(c,o.targetField),f=o.validate(c,u,d.value,n);if(!f.valid)return{ok:!1,reason:f.reason??R.INVALID,alertKey:f.notification?.messageKey};if(e.column===E.CUSTOM_ID&&d.value!==null){let _=i.getActivity(e.activityId),b=_?_.customId:null,x=typeof b=="string"?b:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),x))return{ok:!1,reason:R.CUSTOM_ID_DUPLICATE}}let p=o.transform(c,d.value,n,d.raw),v=Nt(e.activityId,p),S=J(i,v),A=le(i,String(e.activityId)),D=c.constraintDate;Ft(i,e.activityId,p),bt(e.activityId,p.postProcessors??[],i);let m=de(A,i,String(e.activityId));if(e.column===E.CUSTOM_ID){let _=S.get(String(e.activityId)),b=_?_.customId:null,x=typeof b=="string"?b:null,M=typeof d.value=="string"?d.value:null;x!==M&&r.customIdTracker.trackCustomIdChange(x,M)}let T=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:_=>ar(e.activityId,v,_),now:r.now,options:t}),k=yr(e.column),{scheduledIds:y,scheduledBeforeImages:g}=await(k?gr({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:T(),revertTargets:[{activityId:e.activityId,priorConstraintDate:D}],revert:(_,b)=>mr(_,b,i,n.calendars)}):Y({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},T())),C=(p.trackingEvents??[]).map(_=>({name:_.name,properties:_.properties??{}})),P=oe(e.activityId,p.constraintWarning);return{ok:!0,changes:K(i,{source:e,beforeSnap:S,touchedIds:v,scheduledIds:y,scheduledBeforeImages:g,sirDetection:"before-diff",links:m,trackingEvents:C,...P?{warnings:[P]}:{},hoursPerDay:s.hoursPerDay})}}function Yf(e){return e===E.DURATION||e===L.AUTO_SCHEDULING}async function go(e,t,r){if(e.kind==="link-create"||e.kind==="link-update"){let i=e.type;if(i!==void 0&&!Object.values(V).some(a=>a===i))return{ok:!1,reason:R.INVALID_LINK_TYPE};let n=e.lag;if(n!==void 0&&!Number.isFinite(n))return{ok:!1,reason:R.INVALID_LINK_LAG}}return Hi([zf(e,r.sector.hoursPerDay)],e,t,r,e.kind==="link-create"&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function vo(e,t,r){let{hoursPerDay:i}=r.sector,n=e.operations.map(s=>Gf(s,i)),a=$f(e.operations);return Hi(n,e,t,r,a)}function $f(e){let t=new Map;return e.forEach((r,i)=>{r.kind==="create"&&r.linkId&&t.set(i,r.linkId)}),t.size>0?t:void 0}function Gf(e,t){return e.kind==="create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:ft(e.lag??0,t)}:e.kind==="update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:ft(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function Hi(e,t,r,i,n){let{adapter:a,scheduler:s,sector:o,linkIdGen:c}=i;s.invalidateAllCaches();let l=new Set,d=new Map;for(let D of e)if(D.kind==="create")l.add(String(D.source)),l.add(String(D.target));else{let m=a.getLink(D.linkId);m&&(l.add(String(m.source)),l.add(String(m.target)),d.set(D.linkId,{...m}))}let u=J(a,l),f=[];for(let D=0;D<e.length;D++){let m=e[D],T=m.kind==="create"&&n?n.get(D):void 0,k=Rt(m,{port:a,newLinkId:T?()=>T:c.next});f.push({op:m,finalLinkId:k.applied?k.linkId:null,rejected:k.applied?null:k.rejected??"link_op_rejected"})}if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!=="inline-edit")return{ok:!1,reason:f[0].rejected};let p=Kf(f,d,a),{scheduledIds:v}=await Y({adapter:a,scheduler:s,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:i.now,options:r});for(let D of v)if(!u.has(D)){let m=a.getActivity(D);m&&u.set(D,j(m))}let S=vr(f,d,a),A=new Map;for(let[D,m]of d)A.set(String(D),m);return{ok:!0,__beforeLinks:A,changes:K(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:v,links:S,hoursPerDay:o.hoursPerDay})}}function Kf(e,t,r){for(let i of e)if(i.rejected===null){if(i.op.kind==="create")return r.hasChildren(i.op.target)?"roots":String(i.op.target);if(i.op.kind==="delete"){let n=t.get(i.op.linkId);if(n)return r.hasChildren(n.target)?"roots":String(n.target)}if(i.op.kind==="update"){let n=r.getLink(i.op.linkId);if(n)return r.hasChildren(n.target)?"roots":String(n.target)}}return null}function zf(e,t){return e.kind==="link-create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:ft(e.lag,t)}:e.kind==="link-update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:ft(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function Ao(e,t,r){let{adapter:i,sector:n}=r;if(typeof e.newValue!="string")return{ok:!1,reason:R.INVALID_VALUE};if(!i.getActivity(e.activityId))return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let s=e.column===E.CUSTOM_PREDECESSORS,{specs:o}=Ge(e.newValue),c=o.map(v=>({...v,lag:ft(v.lag,n.hoursPerDay)})),l=new Map;i.forEachActivity(v=>{v.correlativeId!=null&&l.set(String(v.correlativeId),v.id)});let d=v=>l.get(v)??null,u=s?i.getIncomingLinkIds(e.activityId):i.getOutgoingLinkIds(e.activityId),f=[];for(let v of u){let S=i.getLink(v);S&&f.push(S)}let p=s?ze({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):qe({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return Hi(p.operations,e,t,r)}var yt={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 Vi(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0,a=0;for(let c of i){let l=t.getActivity(c);if(!l)continue;let d=ji(l,L.WORK_HOURS),u=qf(c,l,d,t);n+=d,a+=u}t.setActivityField(r,L.WORK_HOURS,n),t.setActivityField(r,L.REAL_WORK_HOURS,a);let s=t.getActivity(r);if(!s)break;let o=s.parentId;if(!o||O(o))break;r=o}}function Co(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||O(i)||Vi(i,t)}function ji(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function qf(e,t,r,i){return i.hasChildren(e)?ji(t,L.REAL_WORK_HOURS):ct(r,ji(t,L.PROGRESS))}function Yi(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0;for(let o of i){let c=t.getActivity(o);c&&(n+=Jf(c,L.USED_COST))}t.setActivityField(r,L.USED_COST,n);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||O(s))break;r=s}}function Io(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||O(i)||Yi(i,t)}function Jf(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function $i(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0;for(let o of i){let c=t.getActivity(o);c&&(n+=Xf(c,L.COST))}t.setActivityField(r,L.COST,n);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||O(s))break;r=s}}function ko(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||O(i)||$i(i,t)}function Xf(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var Cr=Object.freeze({proplannerId:null,description:"",type:"task",progress:0,constraintType:"asap",constraintDate:null,autoScheduling:!0,assignedDefaultCalendar:!1,dateOrigin:null,cost:0,usedCost:0,realCost:0,workHours:0,realWorkHours:0,ponderator:0,hasCustomPonderator:!1,correlativeId:0,customId:null,subcontractId:null,isLookahead:!1,hasLookaheadTasks:!1,newActivityIds:[],hasNewActivities:!1,pendingRequestIds:[],responsableIds:[],tagIds:[],baselinePoints:[],baselineSnapshot:null,recursiveDurationHours:0,isCritical:!1,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null,promotionRestore:null}),So="New Master Plan",Do="New Activity";var Zf=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],To=new Set(Zf);function Qf(e){let t=Object.getPrototypeOf(e);if(t!==null&&t!==Object.prototype)throw new Error("activity-create: override bag must be a plain object with no custom prototype");for(let r of Reflect.ownKeys(e))if(typeof r=="symbol"||!To.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function _o(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,i=Qf(e.activityOverrides??{}),n=e.numTasksInGantt===0?So:Do,a=i.name??n,s=i.durationHours??e.sector.hoursPerDay,o=i.calendarId??e.sector.defaultCalendar,c=tp(r,e.fallbackStartDate,i.startDate),l={...Cr,...i,id:e.id,parentId:e.parentId,uniqueCorrelativeId:e.nextUniqueCorrelativeId,name:a,durationHours:s,calendarId:o,startDate:c,endDate:c},d=i.startDate?new Date(l.startDate):t.getClosestWorkTime({date:l.startDate,dir:q.FUTURE,task:l}),u=t.calculateEndDate({startDate:d,durationHours:l.durationHours,task:l});return{newTask:{...l,startDate:d,endDate:u,newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function tp(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function ue(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&Et(t.type):ep(t),i=Array.isArray(t.newActivityIds)?t.newActivityIds:[],a={isLookahead:!1,hasNewActivities:!0,newActivityIds:i.some(s=>String(s)===String(e.newChildId))?[...i]:[...i,e.newChildId]};return t.customId!=null&&t.customId!==""&&(a.customId=null),r&&(a.type=ei,a.constraintType=$.ASAP,a.constraintDate=null,(e.promotionSource??"create")==="create"&&(a.progress=0,a.expectedProgressBaseline=0)),{parentId:e.parentId,fields:a}}function ep(e){return Et(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function Ir(e,t,r,i){let n=t,a=n==="0",s=Gi(e,n);if(i!==void 0){let c=s.find(l=>l.id===i);if(c){let l=nt(c),d=s.map(nt).filter(f=>f<l);return d.length===0?l-1:(Math.max(...d)+l)/2}}if(r!==void 0){let c=s.find(l=>l.id===r);if(c){let l=nt(c),d=s.map(nt).filter(f=>f>l);if(d.length===0)return l+1;let u=Math.min(...d);return(l+u)/2}}return s.length===0?0:Math.max(...s.map(nt))+1}var Kt=Number.MAX_SAFE_INTEGER,Po=Number.MAX_SAFE_INTEGER-1;function nt(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Kt}function Gi(e,t){let r=[];return e.forEachActivity(i=>{Bt(i.parentId)===t&&r.push(i)}),r}function Eo(e,t,r){let i=e,n=Wt(e,r);for(;n!=null&&t.has(n);)i=n,n=Wt(n,r);return i}function Wt(e,t){let r=t.getActivity(e);if(!r)return null;let i=Bt(r.parentId),n=$t(i,t),a=n.findIndex(s=>String(s)===String(e));return a<=0?null:n[a-1]??null}function Ro(e,t,r,i){let n=$t(t,e).filter(c=>String(c)!==String(i)).map(c=>e.getActivity(c)).filter(c=>c!==null);if(n.length===0)return 0;let a=n.map(nt);if(r<=0)return a[0]-1;if(r>=a.length)return a[a.length-1]+1;let s=a[r-1],o=a[r];return(s+o)/2}function kr(e,t,r={}){let{adapter:i,scheduler:n,sector:a,calendars:s,activityIdGen:o,uidGen:c}=t;n.invalidateAllCaches();let l=rp(e,i);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=np(e.activityId,i,o),v=c.next(),S={id:p,parentId:f?null:e.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:lp(s)},numTasksInGantt:i.activityCount(),nextUniqueCorrelativeId:v,activityOverrides:e.overrides??{}},D=_o(S,{getActivity:g=>i.getActivity(g),calculateEndDate:g=>i.calculateEndDate(g),getClosestWorkTime:g=>i.getClosestWorkTime(g)}).newTask;D.realWorkHours=ct(D.workHours,D.progress),sp(D,e,t,u,d,r);let m=Ir(i,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);D.correlativeId=m;let T=new Set([p]);d&&T.add(d.id);let k=d!==null&&i.getChildren(d.id).length===0,y=r.skipBeforeSnap?new Map:J(i,T);return i.addActivity(D),op(e,p,d,i,r.preserveParentCustomId??!1,k),Co(p,i),Io(p,i),ko(p,i),cp(i,p,y,T,r),{ok:!0,newId:p,parent:d,newActivity:D,beforeSnap:y,initialTouched:T}}function rp(e,t){let r=O(e.parentId),i=r?null:t.getActivity(e.parentId);if(!r&&!i)return{ok:!1,reason:R.PARENT_NOT_FOUND};if(i!==null&&Jt(i))return{ok:!1,reason:R.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:R.ANCHOR_SIBLING_CONFLICT};let s=e.afterSiblingId??e.beforeSiblingId,o=ip(e,t,r,s);return o||{ok:!0,parent:i,anchorSiblingId:s,isRoot:r}}function ip(e,t,r,i){if(i===void 0)return null;let n=t.getActivity(i);if(!n)return{ok:!1,reason:R.ANCHOR_SIBLING_NOT_FOUND};let a=r?"0":e.parentId;return(n.parentId==null?"0":String(n.parentId))!==a?{ok:!1,reason:R.ANCHOR_SIBLING_WRONG_PARENT}:null}function np(e,t,r){return e===void 0||t.activityExists(e)?r.next():(r.bump(e),e)}function ap(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function sp(e,t,r,i,n,a){let{adapter:s,customIdTracker:o}=r,c=ap(t);if(c!==void 0){if(c.length===0)return;if(!o.isCustomIdInUse(c)){o.registerCustomId(c);return}}let l=i??a.customIdReferenceId,d=l!==void 0,u=d?s.getActivity(l):n;e.customId=o.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function op(e,t,r,i,n,a){if(!r)return;let s=ue({parentId:e.parentId,newChildId:t,isCurrentlyLeaf:a,getParent:o=>i.getActivity(o)??null});if(s)for(let[o,c]of Object.entries(s.fields))o===L.CUSTOM_ID&&n||Z(i,s.parentId,o,c)}function cp(e,t,r,i,n){if(n.skipCorrelativeRecompute)return;let a=at(e);n.skipBeforeSnap||sr(e,a,new Set([String(t)]),r,i)}function Lo(e,t,r,i,n,a){let{newId:s,newActivity:o,beforeSnap:c,initialTouched:l}=r,d={name:yt.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:s,created_duration:o.durationHours}};t.eventSource!==void 0&&(d.properties.event_source=t.eventSource);let u=a?new Map([...a].filter(([f])=>String(f)!==String(s))):void 0;return K(e,{source:t,beforeSnap:c,touchedIds:l,scheduledIds:i,scheduledBeforeImages:u,trackingEvents:[d],hoursPerDay:n})}function bo(e,t){let r=kr(e,t);if(!r.ok)return{ok:!1,reason:r.reason};ai(t.adapter,new Set([r.newId]));let i=t.adapter.getActivity(r.newId);if(!i)throw new Error(`[ScheduleCore] createActivity: new activity ${r.newId} missing after commit`);let n=Lo(t.adapter,e,r,[],t.sector.hoursPerDay);return{ok:!0,activity:i,changes:n}}async function wo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=kr(e,r);if(!s.ok)return s;let{newId:o}=s,c=s.newActivity.autoScheduling;i.setActivityField(o,"autoScheduling",!1);let l;try{l=await Y({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:[o],now:r.now,options:t})}finally{i.setActivityField(o,"autoScheduling",c)}let{scheduledIds:d,scheduledBeforeImages:u}=l;return{ok:!0,changes:Lo(i,e,s,d,a.hoursPerDay,u)}}function lp(e){for(let r of e.values())if(r.is_default)return r.id;let t=e.values().next();return!t.done&&t.value?t.value.id:"global"}function dp(e,t){if("afterSiblingId"in e){let a=t.getActivity(e.afterSiblingId);return a?{ok:!0,parentId:a.parentId==null?"0":String(a.parentId),firstAfter:e.afterSiblingId}:{ok:!1,reason:R.ANCHOR_SIBLING_NOT_FOUND}}let r=e.parentId,n=Gi(t,r).sort((a,s)=>nt(a)-nt(s))[e.index]?.id;return{ok:!0,parentId:r,firstBefore:n}}function up(e){let{customId:t,...r}=e;return{...r,progress:0,ponderator:0,usedCost:0,workHours:0,isLookahead:!1}}async function Oo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=dp(e.destination,i);if(!s.ok)return s;let o=J(i,new Set),c=new Set,l=new Map,d=[],u;for(let m of e.activities){let T=l.get(m.originalParentId),k,y,g;T!==void 0?k=T:(k=s.parentId,u===void 0?(y=s.firstAfter,g=s.firstBefore):y=u);let C=kr({kind:"activity-create",parentId:k,afterSiblingId:y,beforeSiblingId:g,...m.activityId?{activityId:m.activityId}:{},overrides:up(m.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,...T!==void 0?{customIdReferenceId:e.referenceActivityId,preserveParentCustomId:!0}:{}});if(!C.ok)return C;if(m.baselineSnapshot!==void 0){let P=m.baselineSnapshot;i.setActivityField(C.newId,"baselineSnapshot",P?{...P,startDate:P.startDate?new Date(P.startDate):null,endDate:P.endDate?new Date(P.endDate):null}:null)}l.set(m.originalId,C.newId),d.push(C.newId),T===void 0&&(u=C.newId)}let f=at(i),p=new Set(d.map(String));sr(i,f,p,o,c);for(let m of d)c.add(String(m));let v=[];for(let m of e.links){let T=l.get(m.source),k=l.get(m.target);if(T===void 0||k===void 0)continue;let y={kind:"create",source:T,target:k,type:m.type,lag:ft(m.lag,a.hoursPerDay)},g=Rt(y,{port:i,newLinkId:m.linkId?()=>m.linkId:r.linkIdGen.next});v.push({op:y,finalLinkId:g.applied?g.linkId:null,rejected:g.applied?null:g.rejected??"link_op_rejected"})}let{scheduledIds:S,scheduledBeforeImages:A}=await Y({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:d[0]??null,recomputeParentsFrom:d,now:r.now,options:t}),D=vr(v,new Map,i);return{ok:!0,changes:K(i,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:S,scheduledBeforeImages:new Map([...A].filter(([m])=>!p.has(String(m)))),links:D,hoursPerDay:a.hoursPerDay})}}function xo(e,t){let{adapter:r}=t,i=e.activityId,n=r.getActivity(i);if(!n)return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let a=n.pendingRequestIds??[],s=e.pendingRequests.map(c=>c.id);return r.setActivityField(e.activityId,"pendingRequestIds",s),{ok:!0,changes:{source:e,activities:[{id:i,kind:"updated",fields:{pendingRequestIds:{before:a,after:s}},after:{id:i,pendingRequestIds:s}}],links:[],calendars:[],trackingEvents:[]}}}function No(e,t){let r=[...new Set(e.activityIds.map(String))],i=r.map(a=>t.adapter.getActivity(a));if(i.some(a=>!a))return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let n=[];for(let[a,s]of r.entries()){let o=i[a];if(!o)continue;let c={};o.isLookahead!==e.isLookahead&&(c.isLookahead={before:o.isLookahead,after:e.isLookahead},t.adapter.setActivityField(s,"isLookahead",e.isLookahead)),o.hasLookaheadTasks!==e.hasLookaheadTasks&&(c.hasLookaheadTasks={before:o.hasLookaheadTasks,after:e.hasLookaheadTasks},t.adapter.setActivityField(s,"hasLookaheadTasks",e.hasLookaheadTasks)),Object.keys(c).length!==0&&n.push({id:s,kind:"updated",fields:c,after:{...o,isLookahead:e.isLookahead,hasLookaheadTasks:e.hasLookaheadTasks}})}return{ok:!0,changes:{source:e,activities:n,links:[],calendars:[],trackingEvents:[]}}}function Tt(e,t){Vi(e,t),Yi(e,t),$i(e,t)}function Fo(e,t){let r=new Set,i=[];for(let n of e){let a=String(n);r.has(a)||(r.add(a),i.push(a))}for(;i.length>0;){let n=i.pop(),a=t.getChildren(n);for(let s of a){let o=String(s);r.has(o)||(r.add(o),i.push(o))}}return r}function Mo(e,t){let r=new Set;for(let i of e){for(let n of t.getOutgoingLinkIds(i))r.add(String(n));for(let n of t.getIncomingLinkIds(i))r.add(String(n))}return[...r]}function fp(e){let t=e.promotionRestore;return typeof t!="object"||t===null||t.type!=="task"&&t.type!=="milestone"?null:{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,promotionRestore:null}}function fe(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,i=Number.isFinite(r),n=fp(t)??(i?{type:Zt,durationHours:r,progress:0,autoScheduling:!0,constraintType:"asap",constraintDate:null,hasNewActivities:!1,promotionRestore:null}:{type:Zt});if(e.idsRemoved&&e.idsRemoved.size>0){let a=Array.isArray(t.newActivityIds)?t.newActivityIds:[];if(a.length>0){let s=a.filter(o=>!e.idsRemoved.has(o)&&!e.idsRemoved.has(String(o)));s.length!==a.length&&(n.newActivityIds=s)}}return t.hasLookaheadTasks&&(n.isLookahead=!0),{parentId:String(t.id),fields:n}}function Wo(e){if(e.idsRemoved.size===0)return null;let t=e.parent.newActivityIds;if(!Array.isArray(t)||t.length===0)return null;let r=t,i=r.filter(n=>!e.idsRemoved.has(n)&&!e.idsRemoved.has(String(n)));return i.length===r.length?null:{parentId:String(e.parent.id),fields:{newActivityIds:[...i],hasNewActivities:i.length>0}}}async function Uo(e,t,r){let{adapter:i,scheduler:n,customIdTracker:a,sector:s}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:R.ACTIVITY_IDS_EMPTY};for(let g of e.activityIds)if(!i.getActivity(g))return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let o=Fo(e.activityIds,i),c=Mo(o,i),l=new Set;for(let g of e.activityIds){let C=i.getActivity(g);if(!C)continue;let P=C.parentId;if(O(P))continue;let _=String(P);o.has(_)||l.add(_)}let d=new Set([...o,...l]),u=J(i,d),f=new Map;for(let g of c){let C=i.getLink(g);C&&f.set(g,{...C})}let p=new Set;for(let g of o){let C=i.getActivity(g);if(!C)continue;let P=O(C.parentId)?null:i.getActivity(String(C.parentId)),_=P?.hasNewActivities===!0&&P.newActivityIds.some(x=>String(x)===String(g));(C.isNewActivity===!0||_)&&p.add(g);let b=C.customId;typeof b=="string"&&b.length>0&&a.releaseCustomId(b)}for(let g of c)i.removeLink(g);let v=hp(i,o);for(let g of o)i.removeActivity(g);for(let g of l){let C=i.getActivity(g);if(!C)continue;pp(C,p,i);let P=i.getChildren(g),_=fe({parent:C,remainingChildIds:P.map(String),defaultDurationHours:s.hoursPerDay,idsRemoved:o});if(!_){Ze(g,i);continue}for(let[b,x]of Object.entries(_.fields))Z(i,g,b,x);if(C.customId==null||C.customId===""){let b=Wt(g,i),x=b?i.getActivity(b)?.customId:null,M=a.generateCustomIdForRestoredChild(typeof x=="string"&&x?x:null);i.setActivityField(g,L.CUSTOM_ID,M)}}for(let g of l)Tt(g,i);let S=at(i);for(let g of S){if(d.add(g.activityId),u.has(g.activityId))continue;let C=i.getActivity(g.activityId);if(!C)continue;let P=j(C);g.before!==void 0&&(P.correlativeId=g.before),u.set(g.activityId,P)}let{scheduledIds:A,scheduledBeforeImages:D}=await Y({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:l,now:r.now,options:t}),m={name:yt.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:o.size}};e.eventSource!==void 0&&(m.properties.event_source=e.eventSource);let T=new Map;for(let[g,C]of f)T.set(g,C);let k=new Map;for(let g of o){let C=u.get(String(g));C&&k.set(String(g),C)}let y=K(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:A,scheduledBeforeImages:D,sirDetection:"after-diff",links:yp(f),trackingEvents:[m],hoursPerDay:s.hoursPerDay});return{ok:!0,changes:v.length>0?{...y,viewState:v}:y,__beforeSnap:k,__beforeLinks:T}}function pp(e,t,r){let i=Wo({parent:e,idsRemoved:t});if(i)for(let[n,a]of Object.entries(i.fields))Z(r,i.parentId,n,a)}function hp(e,t){let r=[];for(let i of t){let n=e.isChecked(i),a=e.isVisible(i);!n&&a||r.push({activityId:String(i),...n?{checked:{before:!0,after:!1}}:{},...a?{}:{visible:{before:!1,after:!0}}})}return r}function yp(e){let t=[];for(let[r,i]of e.entries())t.push({id:r,kind:"deleted",fields:{source:{before:String(i.source),after:void 0},target:{before:String(i.target),after:void 0},type:{before:i.type,after:void 0},lag:{before:Number(i.lag),after:void 0}},after:null});return t}function Sr(e,t){let r=new Set;for(let n of e)r.add(String(n));let i=[];for(let n of t.getAllLinks()){let a=String(n.source),s=String(n.target);!r.has(a)&&!r.has(s)||(Bo(s,a,t)||Bo(a,s,t))&&i.push(String(n.id))}return i}function Bo(e,t,r){let i=String(e),n=new Set;for(;i!=null;){if(n.has(i))return!1;n.add(i);let a=r.getActivity(i);if(!a)return!1;let s=a.parentId;if(s===null||O(s))return!1;let o=s;if(o===t)return!0;i=o}return!1}async function Ho(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;n.invalidateAllCaches();let s=i.getActivity(e.activityId);if(!s)return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let o=O(e.parentId);if(!o&&!i.getActivity(e.parentId))return{ok:!1,reason:R.PARENT_NOT_FOUND};if(!o&&(e.parentId===e.activityId||i.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:R.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:R.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let y=i.getActivity(c);if(!y)return{ok:!1,reason:R.ANCHOR_SIBLING_NOT_FOUND};if((y.parentId===null?"0":String(y.parentId))!==e.parentId)return{ok:!1,reason:R.ANCHOR_SIBLING_WRONG_PARENT}}let l=s.parentId,d=Bt(l),u=String(e.parentId),f=d!==u,p=new Set([e.activityId]);f?(d!=="0"&&p.add(d),u!=="0"&&p.add(u)):d!=="0"&&p.add(d);let v=J(i,p);f&&i.setActivityField(e.activityId,L.PARENT,u);let S=Ir(i,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(i.setActivityField(e.activityId,L.CORRELATIVE_ID,S),f){if(!o){let y=i.getActivity(e.parentId);if(y){let g=y.customId,C=Et(y.type)&&i.getChildren(e.parentId).filter(_=>_!==e.activityId).length===0,P=ue({parentId:e.parentId,newChildId:e.activityId,getParent:_=>i.getActivity(_)??null,isCurrentlyLeaf:C,promotionSource:"reparent"});if(P){for(let[_,b]of Object.entries(P.fields))Z(i,P.parentId,_,b);P.fields.customId===null&&Ar(g,r.customIdTracker)}}}if(d!=="0"){let y=i.getActivity(d);if(y){let g=i.getChildren(d),C=fe({parent:y,remainingChildIds:g.map(String),defaultDurationHours:a.hoursPerDay,idsRemoved:new Set([e.activityId])});if(C){for(let[M,z]of Object.entries(C.fields))Z(i,d,M,z);let P=Wt(d,i),_=P?i.getActivity(P)?.customId:null,b=typeof _=="string"&&_?_:null,x=r.customIdTracker.generateCustomIdForRestoredChild(b);i.setActivityField(d,L.CUSTOM_ID,x)}}}}f&&(d!=="0"&&Tt(d,i),o||Tt(e.parentId,i));let A=at(i);for(let y of A){if(p.add(y.activityId),v.has(y.activityId))continue;let g=i.getActivity(y.activityId);if(!g)continue;let C=j(g);y.before!==void 0&&(C.correlativeId=y.before),v.set(y.activityId,C)}let{scheduledIds:D,scheduledBeforeImages:m}=await Y({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId],now:r.now,options:t}),T=f?Sr([e.activityId],i):[],k={name:yt.ACTIVITY_MOVE,properties:{activity_id:e.activityId,new_parent_id:e.parentId,after_sibling_id:e.afterSiblingId??null,before_sibling_id:e.beforeSiblingId??null,invalid_link_ids:T.map(String)}};return e.eventSource!==void 0&&(k.properties.event_source=e.eventSource),{ok:!0,changes:K(i,{source:e,beforeSnap:v,touchedIds:p,scheduledIds:D,scheduledBeforeImages:m,sirDetection:"before-diff",trackingEvents:[k],hoursPerDay:a.hoursPerDay})}}async function jo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:R.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Set,c=[],l=[],d=[],u=new Set(s),f=[...e.activityIds].sort((y,g)=>{let C=i.getActivity(y),P=i.getActivity(g),_=C?nt(C):Kt,b=P?nt(P):Kt;return _-b});for(let y of f){if(!i.getActivity(y)){c.push({activityId:y,reason:R.ACTIVITY_NOT_FOUND}),u.delete(y);continue}let C=Rs(y,u,i);if(C==null){c.push({activityId:y,reason:R.INDENT_NO_ELIGIBLE_SIBLING}),u.delete(y);continue}let P=i.getActivity(y)?.parentId,_=O(P)?"0":String(P);d.push({activityId:y,newParentId:C,oldParentId:_}),o.add(y),o.add(C),_!=="0"&&o.add(_)}let p=J(i,o);for(let{activityId:y,newParentId:g}of d)i.setActivityField(y,L.PARENT,g),i.setActivityField(y,L.CORRELATIVE_ID,Po),l.push(y);let v=new Set;for(let{activityId:y,newParentId:g}of d){if(v.has(g))continue;v.add(g);let C=i.getActivity(g);if(!C)continue;let P=C.customId,_=Et(C.type)&&i.getChildren(g).filter(M=>!l.includes(M)).length===0,b=C.hasNewActivities&&C.newActivityIds.some(M=>String(M)===String(y)),x=ue({parentId:g,newChildId:y,getParent:M=>i.getActivity(M)??null,isCurrentlyLeaf:_,promotionSource:"reparent"});if(x){for(let[M,z]of Object.entries(x.fields))Z(i,x.parentId,M,z);b||(i.setActivityField(g,L.HAS_NEW_ACTIVITIES,!1),i.setActivityField(g,L.NEW_ACTIVITIES_ARRAY,[]))}i.setActivityField(g,L.CONSTRAINT_TYPE,"asap"),i.setActivityField(g,L.CONSTRAINT_DATE,null),i.setActivityField(g,L.CUSTOM_ID,null),Ar(P,r.customIdTracker)}let S=new Set;for(let y of d)y.oldParentId!=="0"&&S.add(y.oldParentId),S.add(y.newParentId);for(let y of S)Tt(y,i);let A=at(i);for(let y of A){if(o.add(y.activityId),p.has(y.activityId))continue;let g=i.getActivity(y.activityId);if(!g)continue;let C=j(g);y.before!==void 0&&(C.correlativeId=y.before),p.set(y.activityId,C)}let{scheduledIds:D,scheduledBeforeImages:m}=await Y({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:l,now:r.now,options:t}),T=Sr(l,i),k={name:yt.ACTIVITY_INDENT,properties:{activity_ids:l,failed:c.map(y=>({activity_id:y.activityId,reason:y.reason})),invalid_link_ids:T}};return e.eventSource!==void 0&&(k.properties.event_source=e.eventSource),{ok:!0,changes:K(i,{source:e,beforeSnap:p,touchedIds:o,scheduledIds:D,scheduledBeforeImages:m,trackingEvents:[k],hoursPerDay:a.hoursPerDay})}}async function Vo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:R.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Map,c=new Map;for(let y of e.activityIds){let g=y;i.getActivity(g)&&(o.set(g,hi(g,i)),c.set(g,Eo(g,s,i)))}let l=new Set,d=[],u=[],f=new Set,p=[],v=[...e.activityIds].sort((y,g)=>{let C=i.getActivity(y),P=i.getActivity(g),_=C?nt(C):Kt,b=P?nt(P):Kt;return _-b});for(let y of v){let g=y,C=i.getActivity(g);if(!C){d.push({activityId:g,reason:R.ACTIVITY_NOT_FOUND});continue}let P=C.parentId;if(O(P)){d.push({activityId:g,reason:R.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let _=String(P),b=i.getActivity(_);if(!b){d.push({activityId:g,reason:R.ACTIVITY_NOT_FOUND});continue}let x=b.parentId;if(O(x)){d.push({activityId:g,reason:R.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let M=String(x),z=hi(_,i)+1,ot=c.get(g);if(ot!=null&&s.has(ot)){let Oe=o.get(ot)??-1,Ut=o.get(g)??-1;Oe>=0&&Ut>=0&&(z+=Ut-Oe)}p.push({activityId:g,grandparentKey:M,oldParentKey:_,targetIndexInGrandparent:z}),l.add(String(g)),l.add(String(_)),M!=="0"&&l.add(String(M)),f.add(_)}let S=J(i,l);for(let y of p){i.setActivityField(y.activityId,L.PARENT,y.grandparentKey);let g=Ro(i,y.grandparentKey,y.targetIndexInGrandparent,y.activityId);i.setActivityField(y.activityId,L.CORRELATIVE_ID,g),u.push(y.activityId)}for(let y of f){let g=i.getActivity(y);if(!g)continue;let C=i.getChildren(y),P=fe({parent:g,remainingChildIds:C.map(String),defaultDurationHours:a.hoursPerDay,idsRemoved:new Set(p.filter(z=>z.oldParentKey===y).map(z=>z.activityId))});if(!P){Ze(y,i);continue}for(let[z,ot]of Object.entries(P.fields))Z(i,y,z,ot);let _=Wt(y,i),b=_?i.getActivity(_)?.customId:null,x=typeof b=="string"&&b?b:null,M=r.customIdTracker.generateCustomIdForRestoredChild(x);i.setActivityField(y,L.CUSTOM_ID,M)}let A=new Set;for(let y of f)A.add(String(y));for(let y of p)y.grandparentKey!=="0"&&A.add(String(y.grandparentKey));for(let y of A)Tt(y,i);let D=at(i);for(let y of D){if(l.add(y.activityId),S.has(y.activityId))continue;let g=i.getActivity(y.activityId);if(!g)continue;let C=j(g);y.before!==void 0&&(C.correlativeId=y.before),S.set(y.activityId,C)}let{scheduledIds:m,scheduledBeforeImages:T}=await Y({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:u.length>0?"roots":null,recomputeParentsFrom:u,now:r.now,options:t}),k={name:yt.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(y=>({activity_id:String(y.activityId),reason:y.reason}))}};return e.eventSource!==void 0&&(k.properties.event_source=e.eventSource),{ok:!0,changes:K(i,{source:e,beforeSnap:S,touchedIds:l,scheduledIds:m,scheduledBeforeImages:T,trackingEvents:[k],hoursPerDay:a.hoursPerDay})}}async function Yo(e,t,r){let{adapter:i,ctx:n,scheduler:a,sector:s}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:R.INVALID_PROGRESS_VALUE};let o=n.activityReader.getActivity(e.activityId);if(!o)return{ok:!1,reason:R.ACTIVITY_NOT_FOUND};let c=xt(E.PROGRESS);if(!c)throw new Error("[ScheduleCore] progressPipeline not registered \u2014 cannot dispatch activity-set-progress");let l=c.transform(o,e.newValue,n,e.newValue),d=Nt(e.activityId,l),u=J(i,d);Ft(i,e.activityId,l),bt(e.activityId,l.postProcessors??[],i);let{scheduledIds:f}=await Y({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:l.needsAutoSchedule?e.activityId:null,recomputeParentsFrom:[],collectDirty:v=>ar(e.activityId,d,v),now:r.now,options:t}),p=(l.trackingEvents??[]).map(v=>({name:v.name,properties:v.properties??{}}));return{ok:!0,changes:K(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:f,trackingEvents:p,hoursPerDay:s.hoursPerDay})}}async function $o(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=[],o=new Map,c=new Set,l=[],d=[],u=[],f=!1;for(let v of e.edits){let S=mp(v,r);if(s.push(S.verdict),!S.verdict.ok||!S.changes)continue;let A=Nt(v.activityId,S.changes);gp(o,A,r);for(let T of A)c.add(T);let D=le(i,v.activityId);Ft(i,v.activityId,S.changes),bt(v.activityId,S.changes.postProcessors??[],i),d.push(...de(D,i,v.activityId)),f||=!!S.changes.needsAutoSchedule;for(let T of S.changes.trackingEvents??[])l.push({name:T.name,properties:T.properties??{}});let m=oe(v.activityId,S.changes.constraintWarning);m&&u.push(m)}let{scheduledIds:p}=await Y({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:f?"roots":null,recomputeParentsFrom:c,now:r.now,options:t});return{ok:!0,verdicts:s,changes:K(i,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:p,sirDetection:"before-diff",links:d,trackingEvents:l,warnings:u,hoursPerDay:a.hoursPerDay})}}function mp(e,t){let{ctx:r}=t,i=e.activityId,n=xt(e.column);if(!n)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);let a=r.activityReader.getActivity(e.activityId);if(!a)throw new Error(`[ScheduleCore] activity "${e.activityId}" not found`);let s=n.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:i,ok:!1,reason:s.reason??R.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let o=n.parseInput(e.newValue,a,r);if(!o.ok)return{verdict:{activityId:i,ok:!1,reason:o.reason??R.PARSE_ERROR},changes:null};let c=Reflect.get(a,n.targetField),l=n.validate(a,c,o.value,r);if(!l.valid)return{verdict:{activityId:i,ok:!1,reason:l.reason??R.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};let d=n.transform(a,o.value,r,o.raw);return{verdict:{activityId:i,ok:!0},changes:d}}function gp(e,t,r){let i=new Set;for(let n of t)e.has(n)||i.add(n);if(i.size!==0)for(let[n,a]of J(r.adapter,i))e.set(n,a)}var Ki=E.CUSTOM_ID;async function Go(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;e.edits.some(T=>T.column===E.DURATION)&&n.invalidateExpandedLinksCache();let o=[],c=new Map,l=new Map,d=new Set,u=[],f=[],p=[],v=!1;for(let T of e.edits){let k=vp(T,r);if(o.push(k.verdict),!k.verdict.ok||!k.changes)continue;let y=oe(T.activityId,k.changes.constraintWarning);y&&p.push(y);let g=Nt(T.activityId,k.changes);kp(c,g,r);for(let b of g)d.add(b);Ip(l,T,c);let C=le(i,T.activityId),P=Ap(T,r),_=k.changes;Ft(i,T.activityId,_),bt(T.activityId,k.changes.postProcessors??[],i),Cp(T,P,r),f.push(...de(C,i,T.activityId)),v||=!!k.changes.needsAutoSchedule;for(let b of k.changes.trackingEvents??[])u.push({name:b.name,properties:b.properties??{}})}let S={action:e,autoscheduleFrom:v?"roots":null,recomputeParentsFrom:d,now:r.now,options:t},A=l.size>0,{scheduledIds:D,scheduledBeforeImages:m}=await(A?gr({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:S,revertTargets:[...l].map(([T,k])=>({activityId:T,priorConstraintDate:k})),revert:(T,k)=>mr(T,k,i,r.ctx.calendars)}):Y({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},S));return{ok:!0,verdicts:o,changes:K(i,{source:e,beforeSnap:c,touchedIds:d,scheduledIds:D,scheduledBeforeImages:m,sirDetection:"before-diff",links:f,trackingEvents:u,warnings:p,hoursPerDay:a.hoursPerDay})}}function vp(e,t){let{ctx:r}=t,i=e.activityId,n=xt(e.column);if(!n)return{verdict:{activityId:i,ok:!1,reason:R.NO_PIPELINE_FOR_COLUMN},changes:null};let a=r.activityReader.getActivity(e.activityId);if(!a)return{verdict:{activityId:i,ok:!1,reason:R.ACTIVITY_NOT_FOUND},changes:null};let s=n.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:i,ok:!1,reason:s.reason??R.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let o=n.parseInput(e.newValue,a,r);if(!o.ok)return{verdict:{activityId:i,ok:!1,reason:o.reason??R.PARSE_ERROR},changes:null};let c=Reflect.get(a,n.targetField),l=n.validate(a,c,o.value,r);if(!l.valid)return{verdict:{activityId:i,ok:!1,reason:l.reason??R.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};if(e.column===Ki&&o.value!==null){let u=t.adapter.getActivity(e.activityId),f=u?u.customId:null,p=typeof f=="string"?f:null;if(t.customIdTracker.isCustomIdInUse(String(o.value),p))return{verdict:{activityId:i,ok:!1,reason:R.CUSTOM_ID_DUPLICATE},changes:null}}let d=n.transform(a,o.value,r,o.raw);return{verdict:{activityId:i,ok:!0},changes:d}}function Ap(e,t){if(e.column!==Ki)return null;let r=t.adapter.getActivity(e.activityId),i=r?r.customId:null;return typeof i=="string"?i:null}function Cp(e,t,r){if(e.column!==Ki)return;let i=r.adapter.getActivity(e.activityId),n=i?i.customId:null,a=typeof n=="string"?n:null;t!==a&&r.customIdTracker.trackCustomIdChange(t,a)}function Ip(e,t,r){if(!yr(t.column))return;let i=String(t.activityId);if(e.has(i))return;let n=r.get(i);n&&e.set(i,n.constraintDate??null)}function kp(e,t,r){let i=new Set;for(let n of t)e.has(n)||i.add(n);if(i.size!==0)for(let[n,a]of J(r.adapter,i))e.set(n,a)}async function Ko(e,t,r){return e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?go(e,t,r):e.kind==="links-batch"?vo(e,t,r):e.kind==="activity-create"?wo(e,t,r):e.kind==="activity-paste"?Oo(e,t,r):e.kind==="activity-delete"?Uo(e,t,r):e.kind==="activity-move"?Ho(e,t,r):e.kind==="activity-indent"?jo(e,t,r):e.kind==="activity-outdent"?Vo(e,t,r):e.kind==="activity-set-progress"?Yo(e,t,r):e.kind==="dates-batch"?$o(e,t,r):e.kind==="bulk-edit"?Go(e,t,r):e.kind==="selection-toggle"?kn(e,zi(r)):e.kind==="selection-replace"?Sn(e,zi(r)):e.kind==="visibility-set"?Dn(e,zi(r)):e.kind==="sir-sync"?xo(e,r):e.kind==="activity-lookahead-sync"?No(e,r):e.kind==="inline-edit"&&(e.column===E.CUSTOM_PREDECESSORS||e.column===E.CUSTOM_SUCESSORS)?Ao(e,t,r):e.kind!=="inline-edit"?la(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):mo(e,t,r)}function zi(e){return{adapter:e.adapter}}function zo(e,t){return e.getActivity(t)}function qo(e){return e.getAllActivities()}function Jo(e){return e.getAllIds().map(String)}function Xo(e,t){e.forEachActivity((r,i)=>t(i))}function Zo(e,t){let r=t==="0"?qi(e,"0"):e.getChildren(t),i=[];for(let n of r){let a=e.getActivity(n);a&&i.push(a)}return i.sort((n,a)=>(n.correlativeId??0)-(a.correlativeId??0)),i}function qi(e,t){let r=t;if(r==="0"){let i=[];return e.forEachActivity((n,a)=>{O(n.parentId)&&i.push(a)}),i}return[...e.getChildren(r)].map(String)}function Qo(e){return e.checkedIds().map(String)}function tc(e,t){return e.getChildren(t).length>0}function ec(e,t){let r=e.getLink(t);return r?gt(r):null}function rc(e){return e.getAllLinks().map(t=>gt(t))}function ic(e,t,r){if(!e||e==="0")return;let i=r.getChildren(e);if(i.length===0)return;let n=new Map,a=0;for(let o of i){let c=Sp(String(o),t,r);n.set(String(o),c),a+=c}let s=a?100/a:0;for(let o of i){let c=r.getActivity(o);if(!c)continue;let l=c.baselinePoints;if(pt(c)){let u=n.get(String(o))??0;r.setActivityField(o,E.PONDERATOR,s*u)}else(!Array.isArray(l)||l.length===0)&&r.setActivityField(o,E.PONDERATOR,0)}}function Sp(e,t,r){let i=r.getActivity(e);if(!i)return 0;let n=pt(i);if(!n)return 0;if(t==="COST")return Dr(n.cost);if(t==="HH")return Dr(n.workHours);let a=i.type;return a==="project"?nc(e,r):a==="milestone"?0:Dr(n.durationDays)}function nc(e,t){let r=0;for(let i of t.getChildren(e)){let n=t.getActivity(i);if(!n)continue;let a=pt(n);if(!a)continue;let s=n.type;s==="project"?r+=nc(String(i),t):s!=="milestone"&&(r+=Dr(a.durationDays))}return r}function Dr(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function Tr(e,t){t.forEachActivity((r,i)=>{t.setActivityField(i,E.PONDERATOR,0)}),t.forEachActivity((r,i)=>{t.getChildren(i).length>0&&ic(String(i),e,t)})}function _r(e){for(let t of Dp(e))_p(t,e)}function Dp(e){let t=new Set;e.forEachActivity((i,n)=>{e.getChildren(n).length>0&&t.add(n)});let r=new Map;for(let i of t)r.set(i,Tp(i,e));return[...t].sort((i,n)=>(r.get(n)??0)-(r.get(i)??0))}function Tp(e,t){let r=0,i=e;for(;i&&i!=="0"&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function _p(e,t){let r=t.getChildren(e);if(r.length===0)return;let i=[];for(let a of r){let s=t.getActivity(a);s&&i.push({progress:Number(s.progress??0),ponderator:Number(s.ponderator??0)})}let n=te(i);n!==null&&t.setActivityField(e,E.PROGRESS,Xe(n))}function ac(e){return typeof e=="string"&&e.length>0?Dt(e):e instanceof Date?e:null}function Ji(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):Number.NaN;return!Number.isFinite(t)||t<0?null:t}function Pr(e,t){let r=Ji(e.duration),i=Ji(e.cost),n=Ji(e.hh_work);return r===null||i===null||n===null?(t.warn(`[baseline] dropping point with non-finite/negative magnitude \u2014 duration=${JSON.stringify(e.duration)}, cost=${JSON.stringify(e.cost)}, hh_work=${JSON.stringify(e.hh_work)}`),null):{startDate:ac(e.start_date),endDate:ac(e.end_date),durationDays:r,cost:i,workHours:n,versionId:typeof e.sectorbaselineversionId=="number"?e.sectorbaselineversionId:null,isActiveVersion:!!e.sectorbaselineversion?.active,baseCalendarId:e.baseCalendarId!=null?String(e.baseCalendarId):null,hoursPerDay:typeof e.hoursPerDay=="number"?e.hoursPerDay:null,hoursPerWeek:typeof e.hoursPerWeek=="number"?e.hoursPerWeek:null}}function Er(e,t,r){let i=new Map;e.forEachActivity((s,o)=>{let c=s.proplannerId;typeof c=="number"&&i.set(c,o)});let n=new Map;for(let s of t){let o=s.activityId;if(typeof o!="number")continue;let c=i.get(o);if(c===void 0)continue;let l=n.get(c);l?l.push(s):n.set(c,[s])}let a=[];for(let[s,o]of n)e.setActivityField(s,"baselinePoints",o.map(c=>Pr(c,r)).filter(c=>c!==null)),a.push(s);return e.forEachActivity((s,o)=>{if(n.has(o))return;let c=s.baselinePoints;Array.isArray(c)&&c.length>0&&(e.setActivityField(o,"baselinePoints",[]),a.push(o))}),a}function Pp(e){let t=pt(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function sc(e){let t=[];return e.forEachActivity((r,i)=>{let n=Pp(r);n&&(e.setActivityField(i,"baselineSnapshot",n),t.push(i))}),t}function Rr(e,t,r,i,n=null){if(t.length===0)return[];let a=new Set;for(let s of Er(e,t,i))a.add(s);if(r)for(let s of cr(e,r,n))a.add(s);for(let s of sc(e))a.add(s);for(let s of hr(e))a.add(s);return[...a]}function oc(e){let t=e.ponderator;return typeof t=="number"&&Number.isFinite(t)?t:0}function cc(e){let t=e.progress;return typeof t=="number"&&Number.isFinite(t)?t:0}function lc(e,t,r){let i=new Map;e.forEachActivity((a,s)=>{i.set(s,oc(a))}),Tr(r,e);let n=[];return e.forEachActivity((a,s)=>{oc(a)!==(i.get(s)??0)&&n.push(j(a))}),n}function dc(e,t){let r=new Map;e.forEachActivity((n,a)=>{r.set(a,cc(n))}),_r(e);let i=[];return e.forEachActivity((n,a)=>{cc(n)!==(r.get(a)??0)&&i.push(j(n))}),i}function uc(e,t,r,i,n,a=null){let s=Rr(e,r,i,n,a),o=[];for(let c of s){let l=e.getActivity(c);l&&o.push(j(l))}return o}function fc(e,t,r){let i=[];for(let n of Yt(e,r)){let a=e.getActivity(n);a&&i.push(j(a))}return i}function Lr(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function Ep(e){return e.reduce((t,r)=>Lr(r)<Lr(t)?r:t)}function Rp(e){return e.reduce((t,r)=>Lr(r)>Lr(t)?r:t)}function Lp(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function pc(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=Lp(t);if(r.length===0)return null;let i=r.map(a=>a.split("-")[0]),n=r.map(a=>a.split("-")[1]);return{startHour:Ep(i),endHour:Rp(n)}}function hc(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(i){let n=e.getCalendar(String(i));return n?bp(n,r):null}}}function bp(e,t){return{getClosestWorkTime(r){return e.getClosestWorkTime({date:r.date,dir:r.direction,unit:r.unit})},calculateEndDate(r,i){return e.calculateEndDate({start_date:r,duration:i,unit:t})},calculateDuration(r,i){return e.calculateDuration({start_date:r,end_date:i,unit:t})},isWorkTime(r,i){return e.isWorkTime({date:r,unit:i})},getWorkHours(r){return e.getWorkHours(r)}}}function wp(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function zt(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function qt(e){return zt(e)&&!isNaN(e.getTime())}var Op={}.constructor.toString();function xp(e){var t=e.constructor.toString();return t!==Op}function Np(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function vt(e){var t,r;if(e&&typeof e=="object")switch(!0){case zt(e):r=new Date(e);break;case wp(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=vt(e[t]);break;default:if(xp(e))r=Object.create(e);else{if(Np(e))return r=e,r;r={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(r[t]=vt(e[t]));break}return r||e}function pe(e,t,r){for(var i in t)(e[i]===void 0||r)&&(e[i]=t[i]);return e}function yc(e){return typeof e<"u"}var br;function Xi(){return br||(br=new Date().valueOf()),br++,br}function dt(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var Mp=(e,t,r)=>{e=e.replace(/%[a-zA-Z]/g,n=>{switch(n){case"%d":return`"+to_fixed(date.get${t?"UTC":""}Date())+"`;case"%m":return`"+to_fixed((date.get${t?"UTC":""}Month()+1))+"`;case"%j":return`"+date.get${t?"UTC":""}Date()+"`;case"%n":return`"+(date.get${t?"UTC":""}Month()+1)+"`;case"%y":return`"+to_fixed(date.get${t?"UTC":""}FullYear()%100)+"`;case"%Y":return`"+date.get${t?"UTC":""}FullYear()+"`;case"%D":return`"+locale.date.day_short[date.get${t?"UTC":""}Day()]+"`;case"%l":return`"+locale.date.day_full[date.get${t?"UTC":""}Day()]+"`;case"%M":return`"+locale.date.month_short[date.get${t?"UTC":""}Month()]+"`;case"%F":return`"+locale.date.month_full[date.get${t?"UTC":""}Month()]+"`;case"%h":return`"+to_fixed((date.get${t?"UTC":""}Hours()+11)%12+1)+"`;case"%g":return`"+((date.get${t?"UTC":""}Hours()+11)%12+1)+"`;case"%G":return`"+date.get${t?"UTC":""}Hours()+"`;case"%H":return`"+to_fixed(date.get${t?"UTC":""}Hours())+"`;case"%i":return`"+to_fixed(date.get${t?"UTC":""}Minutes())+"`;case"%a":return`"+(date.get${t?"UTC":""}Hours()>11?"pm":"am")+"`;case"%A":return`"+(date.get${t?"UTC":""}Hours()>11?"PM":"AM")+"`;case"%s":return`"+to_fixed(date.get${t?"UTC":""}Seconds())+"`;case"%W":return'"+to_fixed(getISOWeek(date))+"';case"%w":return'"+to_fixed(getWeek(date))+"';default:return n}});let i=new Function("date","to_fixed","locale","getISOWeek","getWeek",`return "${e}";`);return n=>i(n,r.date.to_fixed,r.locale,r.date.getISOWeek,r.date.getWeek)},Wp=(e,t,r)=>{let i="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);",n=e.match(/%[a-zA-Z]/g);for(let o=0;o<n.length;o++)switch(n[o]){case"%j":case"%d":i+=`set[2]=temp[${o}]||1;`;break;case"%n":case"%m":i+=`set[1]=(temp[${o}]||1)-1;`;break;case"%y":i+=`set[0]=temp[${o}]*1+(temp[${o}]>50?1900:2000);`;break;case"%g":case"%G":case"%h":case"%H":i+=`set[3]=temp[${o}]||0;`;break;case"%i":i+=`set[4]=temp[${o}]||0;`;break;case"%Y":i+=`set[0]=temp[${o}]||0;`;break;case"%a":case"%A":i+=`set[3]=set[3]%12+((temp[${o}]||'').toLowerCase()=='am'?0:12);`;break;case"%s":i+=`set[5]=temp[${o}]||0;`;break;case"%M":i+=`set[1]=locale.date.month_short_hash[temp[${o}]]||0;`;break;case"%F":i+=`set[1]=locale.date.month_full_hash[temp[${o}]]||0;`;break}let a="set[0],set[1],set[2],set[3],set[4],set[5]";t&&(a=` Date.UTC(${a})`);let s=new Function("date","locale",`var set=[0,0,1,0,0,0]; ${i} return new Date(${a});`);return o=>s(o,r.locale)},mc={date_to_str:Mp,str_to_date:Wp},Up=(e,t,r)=>i=>e.replace(/%[a-zA-Z]/g,n=>{switch(n){case"%d":return t?r.date.to_fixed(i.getUTCDate()):r.date.to_fixed(i.getDate());case"%m":return t?r.date.to_fixed(i.getUTCMonth()+1):r.date.to_fixed(i.getMonth()+1);case"%j":return t?i.getUTCDate():i.getDate();case"%n":return t?i.getUTCMonth()+1:i.getMonth()+1;case"%y":return t?r.date.to_fixed(i.getUTCFullYear()%100):r.date.to_fixed(i.getFullYear()%100);case"%Y":return t?i.getUTCFullYear():i.getFullYear();case"%D":return t?r.locale.date.day_short[i.getUTCDay()]:r.locale.date.day_short[i.getDay()];case"%l":return t?r.locale.date.day_full[i.getUTCDay()]:r.locale.date.day_full[i.getDay()];case"%M":return t?r.locale.date.month_short[i.getUTCMonth()]:r.locale.date.month_short[i.getMonth()];case"%F":return t?r.locale.date.month_full[i.getUTCMonth()]:r.locale.date.month_full[i.getMonth()];case"%h":return t?r.date.to_fixed((i.getUTCHours()+11)%12+1):r.date.to_fixed((i.getHours()+11)%12+1);case"%g":return t?(i.getUTCHours()+11)%12+1:(i.getHours()+11)%12+1;case"%G":return t?i.getUTCHours():i.getHours();case"%H":return t?r.date.to_fixed(i.getUTCHours()):r.date.to_fixed(i.getHours());case"%i":return t?r.date.to_fixed(i.getUTCMinutes()):r.date.to_fixed(i.getMinutes());case"%a":return t?i.getUTCHours()>11?"pm":"am":i.getHours()>11?"pm":"am";case"%A":return t?i.getUTCHours()>11?"PM":"AM":i.getHours()>11?"PM":"AM";case"%s":return t?r.date.to_fixed(i.getUTCSeconds()):r.date.to_fixed(i.getSeconds());case"%W":return t?r.date.to_fixed(r.date.getUTCISOWeek(i)):r.date.to_fixed(r.date.getISOWeek(i));case"%w":return r.date.to_fixed(r.date.getWeek(i));default:return n}}),Bp=(e,t,r)=>i=>{let n=[0,0,1,0,0,0],a=i.match(/[a-zA-Z]+|[0-9]+/g),s=e.match(/%[a-zA-Z]/g);for(let o=0;o<s.length;o++)switch(s[o]){case"%j":case"%d":n[2]=a[o]||1;break;case"%n":case"%m":n[1]=(a[o]||1)-1;break;case"%y":n[0]=a[o]*1+(a[o]>50?1900:2e3);break;case"%g":case"%G":case"%h":case"%H":n[3]=a[o]||0;break;case"%i":n[4]=a[o]||0;break;case"%Y":n[0]=a[o]||0;break;case"%a":case"%A":n[3]=n[3]%12+((a[o]||"").toLowerCase()==="am"?0:12);break;case"%s":n[5]=a[o]||0;break;case"%M":n[1]=r.locale.date.month_short_hash[a[o]]||0;break;case"%F":n[1]=r.locale.date.month_full_hash[a[o]]||0;break}return t?new Date(Date.UTC(n[0],n[1],n[2],n[3],n[4],n[5])):new Date(n[0],n[1],n[2],n[3],n[4],n[5])},gc={date_to_str:Up,str_to_date:Bp};function vc(e){var t=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function r(o){var c=new Date(o);return isNaN(c.getTime())?null:c}var i=null;function n(){try{new Function("canUseCsp = false;")}catch{i=!0}}function a(){var o=!1;return e.config.csp==="auto"?(i===null&&n(),o=i):o=e.config.csp,o}var s={_isoDateDetected:!1,_isoDateOnly:!1,formatISODate:function(o){return o.toISOString()},formatISODateOnly:function(o){return o.getUTCFullYear()+"-"+e.date.to_fixed(o.getUTCMonth()+1)+"-"+e.date.to_fixed(o.getUTCDate())},init:function(){for(var o=e.locale,l=o.date.month_short,d=o.date.month_short_hash={},c=0;c<l.length;c++)d[l[c]]=c;for(var l=o.date.month_full,d=o.date.month_full_hash={},c=0;c<l.length;c++)d[l[c]]=c},date_part:function(o){return o.setUTCHours(0,0,0,0),o},time_part:function(o){return o.valueOf()/1e3%86400},week_start:function(o){var c=o.getUTCDay();return e.config.start_on_monday&&(c===0?c=6:c--),this.date_part(this.add(o,-1*c,"day"))},month_start:function(o){return o.setUTCDate(1),this.date_part(o)},quarter_start:function(o){this.month_start(o);var c=o.getUTCMonth(),l;return c>=9?l=9:c>=6?l=6:c>=3?l=3:l=0,o.setUTCMonth(l),o},year_start:function(o){return o.setUTCMonth(0),this.month_start(o)},day_start:function(o){return this.date_part(o)},hour_start:function(o){return o.getUTCMinutes()&&o.setUTCMinutes(0),this.minute_start(o),o},minute_start:function(o){return o.getUTCSeconds()&&o.setUTCSeconds(0),o.getUTCMilliseconds()&&o.setUTCMilliseconds(0),o},_add_days:function(o,c,l){return o.setUTCDate(o.getUTCDate()+c),o},add:function(o,c,l){var d=new Date(o.valueOf());switch(l){case"day":d=this._add_days(d,c,o);break;case"week":d=this._add_days(d,c*7,o);break;case"month":d.setUTCMonth(d.getUTCMonth()+c);break;case"year":d.setUTCFullYear(d.getUTCFullYear()+c);break;case"hour":d.setTime(d.getTime()+c*60*60*1e3);break;case"minute":d.setTime(d.getTime()+c*60*1e3);break;default:return this["add_"+l](o,c,l)}return d},add_quarter:function(o,c){return this.add(o,c*3,"month")},to_fixed:function(o){return o<10?"0"+o:o},copy:function(o){return new Date(o.valueOf())},date_to_str:function(o,c){var l=mc;return a()&&(l=gc),l.date_to_str(o,c,e)},str_to_date:function(o,c){var l=mc;return a()&&(l=gc),l.str_to_date(o,c,e)},getISOWeek:function(o){return e.date._getWeekNumber(o,!0)},_getWeekNumber:function(o,c){if(!o)return!1;var l=o.getUTCDay();c&&l===0&&(l=7);var d=new Date(o.valueOf());d.setUTCDate(o.getUTCDate()+(4-l));var u=d.getUTCFullYear(),f=Math.round((d.getTime()-Date.UTC(u,0,1))/864e5),p=1+Math.floor(f/7);return p},getWeek:function(o){return e.date._getWeekNumber(o,e.config.start_on_monday)},getUTCISOWeek:function(o){return e.date.getISOWeek(o)},parseDate:function(o,c){if(o&&!o.getFullYear){var l=!c||c==="parse_date"||c==="xml_date",d=l&&(e.defined(e.templates.xml_date)||e.templates.parse_date&&!e.templates.parse_date._ganttAuto);if(!d&&typeof o=="string"&&t.test(o)){var u=o.indexOf("T")!==-1,f=r(o);if(f)return s._isoDateDetected?u&&(s._isoDateOnly=!1):(s._isoDateDetected=!0,s._isoDateOnly=!u),f}typeof c!="function"&&(typeof c=="string"?c==="parse_date"||c==="xml_date"?c=e.defined(e.templates.xml_date)?e.templates.xml_date:e.templates.parse_date:c=e.defined(e.templates[c])?e.templates[c]:e.date.str_to_date(c,!0):c=e.defined(e.templates.xml_date)?e.templates.xml_date:e.templates.parse_date),o?o=c(o):o=null}return o}};return s}function Zi(e,t,r,i,n){return this.date=e,this.unit=t,this.task=r,this.id=i,this.calendar=n,this}function Qi(e,t,r,i,n,a){return this.date=e,this.dir=t,this.unit=r,this.task=i,this.id=n,this.calendar=a,this}function tn(e,t,r,i,n,a,s){return this.start_date=e,this.duration=t,this.unit=r,this.step=i,this.task=n,this.id=a,this.calendar=s,this}function Hp(e,t,r,i){return this.start_date=e,this.end_date=t,this.task=r,this.calendar=i,this.unit=null,this.step=null,this}var Ac=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(zt(t)?t={date:t}:t=pe({},t),!qt(t.date))throw e.assert(!1,"Invalid date argument for getWorkHours method"),new Error("Invalid date argument for getWorkHours method");return t},setWorkTimeArguments:function(){return arguments[0]},unsetWorkTimeArguments:function(){return arguments[0]},isWorkTimeArguments:function(){var t=arguments[0];if(t instanceof Zi)return t;var r;if(t.date?r=new Zi(t.date,t.unit,t.task,null,t.calendar):r=new Zi(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!qt(r.date))throw e.assert(!1,"Invalid date argument for isWorkTime method"),new Error("Invalid date argument for isWorkTime method");return r},getClosestWorkTimeArguments:function(t){var r=arguments[0];if(r instanceof Qi)return r;var i;if(zt(r)?i=new Qi(r):i=new Qi(r.date,r.dir,r.unit,r.task,null,r.calendar),r.id&&(i.task=r),i.dir=r.dir||"any",i.unit=r.unit||e.config.duration_unit,!qt(i.date))throw e.assert(!1,"Invalid date argument for getClosestWorkTime method"),new Error("Invalid date argument for getClosestWorkTime method");return i},_getStartEndConfig:function(t){var r=Hp,i;if(t instanceof r)return t;if(zt(t)?i=new r(arguments[0],arguments[1],arguments[2],arguments[3]):(i=new r(t.start_date,t.end_date,t.task),t.id!==null&&t.id!==void 0&&(i.task=t)),i.unit=i.unit||e.config.duration_unit,i.step=i.step||e.config.duration_step,i.start_date=i.start_date||i.start||i.date,!qt(i.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!qt(i.end_date))throw e.assert(!1,"Invalid end_date argument for getDuration method"),new Error("Invalid end_date argument for getDuration method");return i},getDurationArguments:function(t,r,i,n){return this._getStartEndConfig.apply(this,arguments)},hasDurationArguments:function(t,r,i,n){return this._getStartEndConfig.apply(this,arguments)},calculateEndDateArguments:function(t,r,i,n){var a=arguments[0];if(a instanceof tn)return a;var s;if(zt(a)?s=new tn(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):s=new tn(a.start_date,a.duration,a.unit,a.step,a.task,null,a.calendar),a.id!==null&&a.id!==void 0&&(s.task=a,s.unit=null,s.step=null),s.unit=s.unit||e.config.duration_unit,s.step=s.step||e.config.duration_step,!qt(s.start_date))throw e.assert(!1,"Invalid start_date argument for calculateEndDate method"),new Error("Invalid start_date argument for calculateEndDate method");return s}}};function Cc(){}Cc.prototype={_getIntervals:function(e){for(var t=[],r=0;r<e.length;r+=2)t.push({start:e[r],end:e[r+1]});return t},_toHoursArray:function(e){var t=[];function r(a){var s=String(a);return s.length<2&&(s="0"+s),s}function i(a){var s=Math.floor(a/3600),o=a-s*60*60,c=Math.floor(o/60);return s+":"+r(c)}for(var n=0;n<e.length;n++)t.push(i(e[n].start)+"-"+i(e[n].end));return t},_intersectHourRanges:function(e,t){var n=[],r=e.length>t.length?e:t,i=e===r?t:e;r=r.slice(),i=i.slice();for(var n=[],a=0;a<r.length;a++)for(var s=r[a],o=0;o<i.length;o++){var c=i[o];c.start<s.end&&c.end>s.start&&(n.push({start:Math.max(s.start,c.start),end:Math.min(s.end,c.end)}),s.end>c.end&&(i.splice(o,1),o--,a--))}return n},_mergeAdjacentIntervals:function(e){var t=e.slice();t.sort(function(a,s){return a.start-s.start});for(var r=t[0],i=1;i<t.length;i++){var n=t[i];n.start<=r.end?(n.end>r.end&&(r.end=n.end),t.splice(i,1),i--):r=n}return t},_mergeHoursConfig:function(e,t){return this._mergeAdjacentIntervals(this._intersectHourRanges(e,t))},merge:function(e,t){let r=vt(e.getConfig()),i=vt(t.getConfig()),n=r.parsed,a=i.parsed;n.customWeeks=r.customWeeks,a.customWeeks=i.customWeeks;var s={hours:this._toHoursArray(this._mergeHoursConfig(n.hours,a.hours)),dates:{},customWeeks:{}};let o=(l,d)=>{for(let u in l.dates){let f=l.dates[u];+u>1e3&&(s.dates[u]=!1);for(let p in d.dates){let v=d.dates[p];if(p==u&&(s.dates[u]=!!(f&&v)),Array.isArray(f)){let S=Array.isArray(v)?v:d.hours;s.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,S))}}}};if(o(n,a),o(a,n),n.customWeeks)for(var c in n.customWeeks)s.customWeeks[c]=n.customWeeks[c];if(a.customWeeks)for(var c in a.customWeeks)s.customWeeks[c]?s.customWeeks[c+"_second"]=a.customWeeks[c]:s.customWeeks[c]=a.customWeeks[c];return s}};var en=class{constructor(){this.clear()}getItem(t,r,i){if(this._cache.has(t)){let a=this._cache.get(t)[i.getUTCFullYear()];if(a&&a.has(r))return a.get(r)}return-1}setItem(t,r,i,n){if(!t||!r)return;let a=this._cache,s=n.getUTCFullYear(),o;a.has(t)?o=a.get(t):(o=[],a.set(t,o));let c=o[s];c||(c=o[s]=new Map),c.set(r,i)}clear(){this._cache=new Map}},rn=class{constructor(){this.clear()}getItem(t,r,i){let n=this._cache;if(n&&n[t]){let a=n[t];if(a===void 0)return-1;let s=a[i.getUTCFullYear()];if(s&&s[r]!==void 0)return s[r]}return-1}setItem(t,r,i,n){if(!t||!r)return;let a=this._cache;if(!a)return;a[t]||(a[t]=[]);let s=a[t],o=n.getUTCFullYear(),c=s[o];c||(c=s[o]={}),c[r]=i}clear(){this._cache={}}},nn=class{constructor(t){this.getMinutesPerWeek=r=>{let i=r.valueOf();if(this._weekCache.has(i))return this._weekCache.get(i);let n=this._calendar,a=this._calendar.$gantt,s=0,o=a.date.week_start(new Date(r));for(let c=0;c<7;c++)s+=n.getHoursPerDay(o)*60,o=a.date.add(o,1,"day");return this._weekCache.set(i,s),s},this.getMinutesPerMonth=r=>{let i=r.valueOf();if(this._monthCache.has(i))return this._monthCache.get(i);let n=this._calendar,a=this._calendar.$gantt,s=0,o=a.date.week_start(new Date(r)),c=a.date.add(o,1,"month").valueOf();for(;o.valueOf()<c;)s+=n.getHoursPerDay(o)*60,o=a.date.add(o,1,"day");return this._monthCache.set(i,s),s},this.clear=()=>{this._weekCache=new Map,this._monthCache=new Map},this.clear(),this._calendar=t}};function jp(){return typeof Map<"u"?new en:new rn}var an=class{constructor(){this.clear()}_getCacheObject(t,r,i){let n=this._cache;n[r]||(n[r]=[]);let a=n[r];a||(a=n[r]={});let s=a[i];s||(s=a[i]={});let o=t.getUTCFullYear(),c=s[o];return c||(c=s[o]={durations:{},endDates:{}}),c}_endDateCacheKey(t,r){return String(t)+"-"+String(r)}_durationCacheKey(t,r){return String(t)+"-"+String(r)}getEndDate(t,r,i,n,a){let s=this._getCacheObject(t,i,n),o=t.valueOf(),c=this._endDateCacheKey(o,r),l;if(s.endDates[c]===void 0){let d=a(),u=d.valueOf();s.endDates[c]=u,s.durations[this._durationCacheKey(o,u)]=r,l=d}else l=new Date(s.endDates[c]);return l}getDuration(t,r,i,n,a){let s=this._getCacheObject(t,i,n),o=t.valueOf(),c=r.valueOf(),l=this._durationCacheKey(o,c),d;if(s.durations[l]===void 0){let u=a();s.durations[l]=u.valueOf(),d=u}else d=s.durations[l];return d}clear(){this._cache={}}};function sn(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=jp(),this._largeUnitsCache=new nn(this),this._dateDurationCache=new an,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}sn.prototype={units:["year","month","week","day","hour","minute"],_clearCaches:function(){this._workingUnitsCache.clear(),this._largeUnitsCache.clear(),this._dateDurationCache.clear()},_getUnitOrder:function(e){for(var t=0,r=this.units.length;t<r;t++)if(this.units[t]==e)return t},_resetTimestampCache:function(){this._cached_timestamps={},this._cached_timestamps_count=0},_timestamp:function(e){this._cached_timestamps_count>1e6&&this._resetTimestampCache();var t=null;if(e.day||e.day===0)t=e.day;else if(e.date){var r=String(e.date.valueOf());this._cached_timestamps[r]?t=this._cached_timestamps[r]:(t=Date.UTC(e.date.getUTCFullYear(),e.date.getUTCMonth(),e.date.getUTCDate()),this._cached_timestamps[r]=t,this._cached_timestamps_count++)}return t},_checkIfWorkingUnit:function(e,t){if(!this["_is_work_"+t]){let r=this.$gantt.date[`${t}_start`](new Date(e)),i=this.$gantt.date.add(r,1,t);return this.hasDuration(r,i)}return this["_is_work_"+t](e)},_is_work_day:function(e){var t=this._getWorkHours(e);return Array.isArray(t)?t.length>0:!1},_is_work_hour:function(e){for(var t=this._getWorkHours(e),r=e.getUTCHours(),i=0;i<t.length;i++)if(r>=t[i].startHour&&r<t[i].endHour)return!0;return!1},_getTimeOfDayStamp:function(e,t){var r=e.getUTCHours();return!e.getUTCHours()&&!e.getUTCMinutes()&&t&&(r=24),r*60*60+e.getUTCMinutes()*60},_is_work_minute:function(e){for(var t=this._getWorkHours(e),r=this._getTimeOfDayStamp(e),i=0;i<t.length;i++)if(r>=t[i].start&&r<t[i].end)return!0;return!1},_nextDate:function(e,t,r){return this.$gantt.date.add(e,r,t)},_getWorkUnitsBetweenGeneric:function(e,t,r,i){var n=this.$gantt.date,a=new Date(e),s=new Date(t);i=i||1;var o=0,c=null,l,d,u=!1;l=n[r+"_start"](new Date(a)),l.valueOf()!=a.valueOf()&&(u=!0);var f=!1;d=n[r+"_start"](new Date(t)),d.valueOf()!=t.valueOf()&&(f=!0);for(var p=!1;a.valueOf()<s.valueOf();){if(c=this._nextDate(a,r,i),p=c.valueOf()>s.valueOf(),this._isWorkTime(a,r))(u||f&&p)&&(l=n[r+"_start"](new Date(a)),d=n.add(l,i,r)),u?(u=!1,c=this._nextDate(l,r,i),o+=(d.valueOf()-a.valueOf())/(d.valueOf()-l.valueOf())):f&&p?(f=!1,o+=(s.valueOf()-a.valueOf())/(d.valueOf()-l.valueOf())):o++;else{var v=this._getUnitOrder(r),S=this.units[v-1];S&&!this._isWorkTime(a,S)&&(c=this._getClosestWorkTimeFuture(a,S))}a=c}return o},_getMinutesPerHour:function(e){var t=this._getTimeOfDayStamp(e),r=this._getTimeOfDayStamp(this._nextDate(e,"hour",1));r===0&&(r=1440*60);for(var i=this._getWorkHours(e),n=0;n<i.length;n++){var a=i[n];if(t>=a.start&&r<=a.end)return 60;if(t<a.end&&r>a.start){var s=Math.min(r,a.end)-Math.max(t,a.start);return s/60}}return 0},_getMinutesPerDay:function(e){var t=this._getWorkHours(e),r=0;return t.forEach(function(i){r+=i.durationMinutes}),r},getHoursPerDay:function(e){var t=this._getWorkHours(e),r=0;return t.forEach(function(i){r+=i.durationHours}),r},_getWorkUnitsForRange:function(e,t,r,i){var n=0,a=new Date(e),s=new Date(t),o;for(r=="minute"?o=dt(this._getMinutesPerDay,this):o=dt(this.getHoursPerDay,this);a.valueOf()<s.valueOf();){if(s-a>1e3*60*60*24*32&&a.getUTCDate()===0){var c=this._largeUnitsCache.getMinutesPerMonth(a);r=="hour"&&(c=c/60),n+=c,a=this.$gantt.date.add(a,1,"month");continue}else if(s-a>1e3*60*60*24*16){var l=this.$gantt.date.week_start(new Date(a));if(a.valueOf()===l.valueOf()){var c=this._largeUnitsCache.getMinutesPerWeek(a);r=="hour"&&(c=c/60),n+=c,a=this.$gantt.date.add(a,7,"day");continue}}n+=o(a),a=this._nextDate(a,"day",1)}return n/i},_getMinutesBetweenSingleDay:function(e,t){for(var r=this._getIntervalTimestamp(e,t),i=this._getWorkHours(e),n=0,a=0;a<i.length;a++){var s=i[a];if(r.end>=s.start&&r.start<=s.end){var o=Math.max(s.start,r.start),c=Math.min(s.end,r.end);n+=(c-o)/60,r.start=c}}return Math.floor(n)},_getMinutesBetween:function(e,t,r,i){var n=new Date(e),a=new Date(t);i=i||1;var s=new Date(n),o=this.$gantt.date.add(this.$gantt.date.day_start(new Date(n)),1,"day");if(a.valueOf()<=o.valueOf())return this._getMinutesBetweenSingleDay(e,t);var c=this.$gantt.date.day_start(new Date(a)),l=a,d=this._getMinutesBetweenSingleDay(s,o),u=this._getMinutesBetweenSingleDay(c,l),f=this._getWorkUnitsForRange(o,c,r,i),p=d+f+u;return p},_getHoursBetween:function(e,t,r,i){var n=new Date(e),a=new Date(t);i=i||1;var s=new Date(n),o=this.$gantt.date.add(this.$gantt.date.day_start(new Date(n)),1,"day");if(a.valueOf()<=o.valueOf())return Math.round(this._getMinutesBetweenSingleDay(e,t)/60);var c=this.$gantt.date.day_start(new Date(a)),l=a,d=this._getMinutesBetweenSingleDay(s,o,r,i)/60,u=this._getMinutesBetweenSingleDay(c,l,r,i)/60,f=this._getWorkUnitsForRange(o,c,r,i),p=d+f+u;return Math.round(p)},getConfig:function(){return this._worktime},_setConfig:function(e){this._worktime=e,this._parseSettings(),this._clearCaches()},_parseSettings:function(){var e=this.getConfig();e.parsed={dates:{},hours:null,haveCustomWeeks:!1,customWeeks:{},customWeeksRangeStart:null,customWeeksRangeEnd:null,customWeeksBoundaries:[]},e.parsed.hours=this._parseHours(e.hours);for(var t in e.dates)e.parsed.dates[t]=this._parseHours(e.dates[t]);if(e.customWeeks){var r=null,i=null;for(var t in e.customWeeks){var n=e.customWeeks[t];if(n.from&&n.to){var a=n.from,s=n.to;(!r||r>a.valueOf())&&(r=a.valueOf()),(!i||i<s.valueOf())&&(i=s.valueOf()),e.parsed.customWeeksBoundaries.push({from:a.valueOf(),fromReadable:new Date(a),to:s.valueOf(),toReadable:new Date(s),name:t}),e.parsed.haveCustomWeeks=!0;var o=e.parsed.customWeeks[t]={from:n.from,to:n.to,hours:this._parseHours(n.hours),dates:{}};if(n.days&&!n.dates){n.dates=n.dates||{};for(var t=0;t<n.days.length;t++)n.dates[t]=n.days[t],n.days[t]instanceof Array||(n.dates[t]=!!n.days[t]);delete n.days}for(var c in n.dates)o.dates[c]=this._parseHours(n.dates[c])}}e.parsed.customWeeksRangeStart=r,e.parsed.customWeeksRangeEnd=i}},_tryChangeCalendarSettings:function(e){var t=JSON.stringify(this.getConfig());return e(),this.hasWorkTime()?!0:(this._setConfig(JSON.parse(t)),this._clearCaches(),!1)},_arraysEqual:function(e,t){if(e===t)return!0;if(!e||!t||e.length!=t.length)return!1;for(var r=0;r<e.length;++r)if(e[r]!==t[r])return!1;return!0},_compareSettings:function(e,t){if(!this._arraysEqual(e.hours,t.hours))return!1;var r=Object.keys(e.dates),i=Object.keys(t.dates);if(r.sort(),i.sort(),!this._arraysEqual(r,i))return!1;for(var n=0;n<r.length;n++){var a=r[n],s=e.dates[a],o=t.dates[a];if(s!==o&&!(Array.isArray(s)&&Array.isArray(o)&&this._arraysEqual(s,o)))return!1}return!0},equals:function(e){if(!(e instanceof sn))return!1;var t=this.getConfig(),r=e.getConfig();if(!this._compareSettings(t,r))return!1;if(t.parsed.haveCustomWeeks&&r.parsed.haveCustomWeeks){if(t.parsed.customWeeksBoundaries.length!=r.parsed.customWeeksBoundaries.length)return!1;for(var i in t.parsed.customWeeks){var n=t.parsed.customWeeks[i],a=r.parsed.customWeeks[i];if(!a||!this._compareSettings(n,a))return!1}}else if(t.parse.haveCustomWeeks!==r.parsed.haveCustomWeeks)return!1;return!0},getWorkHours:function(){var e=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);return this._getWorkHours(e.date,!1)},_getWorkHours:function(e,t){var r=this.getConfig();if(t!==!1&&(r=r.parsed),!e)return r.hours;let i=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));var n=this._timestamp({date:i});if(r.haveCustomWeeks&&r.customWeeksRangeStart<=n&&r.customWeeksRangeEnd>n){for(var a=0;a<r.customWeeksBoundaries.length;a++)if(r.customWeeksBoundaries[a].from<=n&&r.customWeeksBoundaries[a].to>n){r=r.customWeeks[r.customWeeksBoundaries[a].name];break}}var s=!0;return r.dates[n]!==void 0?s=r.dates[n]:r.dates[e.getUTCDay()]!==void 0&&(s=r.dates[e.getUTCDay()]),s===!0?r.hours:s||[]},_getIntervalTimestamp:function(e,t){var r={start:0,end:0};r.start=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds();var i=t.getUTCHours();return!i&&!t.getUTCMinutes()&&!t.getUTCSeconds()&&e.valueOf()<t.valueOf()&&(i=24),r.end=i*60*60+t.getUTCMinutes()*60+t.getUTCSeconds(),r},_parseHours:function(e){if(Array.isArray(e)){var t=[];e.forEach(function(o){typeof o=="number"?t.push(o*60*60):typeof o=="string"&&o.split("-").map(function(c){return c.trim()}).forEach(function(c){var l=c.split(":").map(function(u){return u.trim()}),d=parseInt(l[0]*60*60);l[1]&&(d+=parseInt(l[1]*60)),l[2]&&(d+=parseInt(l[2])),t.push(d)})});for(var r=[],i=0;i<t.length;i+=2){var n=t[i],a=t[i+1],s=a-n;r.push({start:n,end:a,startHour:Math.floor(n/3600),startMinute:Math.floor(n/60),endHour:Math.ceil(a/3600),endMinute:Math.ceil(a/60),durationSeconds:s,durationMinutes:s/60,durationHours:s/3600})}return r}else return e},setWorkTime:function(e){return this._tryChangeCalendarSettings(dt(function(){var t=e.hours!==void 0?e.hours:!0,r=this._timestamp(e),i=this.getConfig();if(r!==null?i.dates[r]=t:e.customWeeks||(i.hours=t),e.customWeeks){if(i.customWeeks||(i.customWeeks={}),typeof e.customWeeks=="string")r!==null?i.customWeeks[e.customWeeks].dates[r]=t:e.customWeeks||(i.customWeeks[e.customWeeks].hours=t);else if(typeof e.customWeeks=="object"&&e.customWeeks.constructor===Object)for(var n in e.customWeeks)i.customWeeks[n]=e.customWeeks[n]}this._parseSettings(),this._clearCaches()},this))},unsetWorkTime:function(e){return this._tryChangeCalendarSettings(dt(function(){if(!e)this.reset_calendar();else{var t=this._timestamp(e);t!==null&&delete this.getConfig().dates[t]}this._parseSettings(),this._clearCaches()},this))},_isWorkTime:function(e,t){var r=-1,i=null;return i=String(e.valueOf()),r=this._workingUnitsCache.getItem(t,i,e),r==-1&&(r=this._checkIfWorkingUnit(e,t),this._workingUnitsCache.setItem(t,i,r,e)),r},isWorkTime:function(){var e=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._isWorkTime(e.date,e.unit)},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments);if(!e.unit)return!1;var t=this;return this._dateDurationCache.getDuration(e.start_date,e.end_date,e.unit,e.step,function(){return t._calculateDuration(e.start_date,e.end_date,e.unit,e.step)})},_calculateDuration:function(e,t,r,i){var n=0,a=1;if(e.valueOf()>t.valueOf()){var s=t;t=e,e=s,a=-1}return r=="hour"&&i==1?n=this._getHoursBetween(e,t,r,i):r=="minute"&&i==1?n=this._getMinutesBetween(e,t,r,i):n=this._getWorkUnitsBetweenGeneric(e,t,r,i),a*Math.round(n)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit,n=e.step;if(!i)return!1;var a=new Date(t),s=new Date(r);for(n=n||1;a.valueOf()<s.valueOf();){if(this._isWorkTime(a,i))return!0;a=this._nextDate(a,i,n)}return!1},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,i=e.unit,n=e.step;if(!i)return!1;var a=e.duration>=0?1:-1;r=Math.abs(r*1);var s=this;return this._dateDurationCache.getEndDate(t,r,i,n*a,function(){return s._calculateEndDate(t,r,i,n*a)})},_calculateEndDate:function(e,t,r,i){if(!r)return!1;if(i==1&&r=="minute")return this._calculateMinuteEndDate(e,t,i);if(i==-1&&r=="minute")return this._subtractMinuteDate(e,t,i);if(i==1&&r=="hour")return this._calculateHourEndDate(e,t,i);var n=this._addInterval(e,t,r,i,null);return n.end},_addInterval:function(e,t,r,i,n){for(var a=0,s=e;a<t&&!(n&&n(s));){var o=this._nextDate(s,r,i),c=new Date(o.valueOf()+1);i>0&&(c=new Date(o.valueOf()-1));var l=this._isWorkTime(c,r);l&&a++,s=o}return{end:s,start:e,added:a}},_addHoursUntilDayEnd:function(e,t){for(var r=this.$gantt.date.add(this.$gantt.date.day_start(new Date(e)),1,"day"),i=0,n=t,a=this._getIntervalTimestamp(e,r),s=this._getWorkHours(e),o=0;o<s.length&&i<t;o++){var c=s[o];if(a.end>=c.start&&a.start<=c.end){var l=Math.max(c.start,a.start),d=Math.min(c.end,a.end),u=(d-l)/3600;u>n&&(u=n,d=l+n*60*60);var f=Math.round((d-l)/3600);i+=f,n-=f,a.start=d}}var p=r;return i===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:i,end:p}},_calculateHourEndDate:function(e,t,r){var i=new Date(e),n=0;r=r||1,t=Math.abs(t*1);var a=this._addHoursUntilDayEnd(i,t);n=a.added,i=a.end;var s=t-n;if(s){for(var o=i;n<t;){var c=this._nextDate(o,"day",r);c.setUTCHours(0),c.setUTCMinutes(0),c.setUTCSeconds(0);var l=0;if(r>0?l=this.getHoursPerDay(new Date(c.valueOf()-1)):l=this.getHoursPerDay(new Date(c.valueOf()+1)),n+l>=t)break;n+=l,o=c}i=o}if(n<t){var s=t-n;a=this._addHoursUntilDayEnd(i,s),i=a.end}return i},_addMinutesUntilHourEnd:function(e,t){if(e.getUTCMinutes()===0)return{added:0,end:new Date(e)};for(var r=this.$gantt.date.add(this.$gantt.date.hour_start(new Date(e)),1,"hour"),i=0,n=t,a=this._getIntervalTimestamp(e,r),s=this._getWorkHours(e),o=0;o<s.length&&i<t;o++){var c=s[o];if(a.end>=c.start&&a.start<=c.end){var l=Math.max(c.start,a.start),d=Math.min(c.end,a.end),u=(d-l)/60;u>n&&(u=n,d=l+n*60);var f=Math.round((d-l)/60);n-=f,i+=f,a.start=d}}var p=r;return i===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:i,end:p}},_subtractMinutesUntilHourStart:function(e,t){for(var r=this.$gantt.date.hour_start(new Date(e)),i=0,n=t,a=r.getUTCHours()*60*60+r.getUTCMinutes()*60+r.getUTCSeconds(),s=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds(),o=this._getWorkHours(e),c=o.length-1;c>=0&&i<t;c--){var l=o[c];if(s>l.start&&a<=l.end){var d=Math.min(s,l.end),u=Math.max(a,l.start),f=(d-u)/60;f>n&&(f=n,u=d-n*60);var p=Math.abs(Math.round((d-u)/60));n-=p,i+=p,s=u}}var v=r;return i===t&&(v=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,s))),{added:i,end:v}},_subtractMinuteDate:function(e,t,r){var i=this.getClosestWorkTime({date:e,dir:"past",unit:"minute"}),n=0;r=r||-1,t=Math.abs(t*1),t=Math.round(t);let a=this._isMinutePrecision(i),s=this._subtractMinutesUntilHourStart(i,t);n+=s.added,i=s.end;for(var o=0,c=[],l=0;n<t;){var d=this.$gantt.date.day_start(new Date(i)),u=!1;i.valueOf()===d.valueOf()&&(d=this.$gantt.date.add(d,-1,"day"),u=!0);var f=new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),23,59,59,999)).valueOf();f!==o&&(c=this._getWorkHours(d),l=this._getMinutesPerDay(d),o=f);var p=t-n,v=this._getTimeOfDayStamp(i,u);if(!c.length||!l){i=this.$gantt.date.add(i,-1,"day");continue}if(c[c.length-1].end<=v&&p>l){n+=l,i=this.$gantt.date.add(i,-1,"day");continue}for(var S=!1,A=null,D=null,m=c.length-1;m>=0;m--)if(c[m].start<v-1&&c[m].end>=v-1){S=!0,A=c[m],D=c[m-1];break}if(S)if(v===A.end&&p>=A.durationMinutes)n+=A.durationMinutes,i=this.$gantt.date.add(i,-A.durationMinutes,"minute");else if(!a&&p<=v/60-A.startMinute)n+=p,i=this.$gantt.date.add(i,-p,"minute");else if(a)p<=v/60-A.startMinute?(n+=p,i=this.$gantt.date.add(i,-p,"minute")):(n+=v/60-A.startMinute,D?i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,D.end)):i=this.$gantt.date.day_start(i));else{var T=this._getMinutesPerHour(i);T<=p?(n+=T,i=this._nextDate(i,"hour",r)):(s=this._subtractMinutesUntilHourStart(i,p),n+=s.added,i=s.end)}else if(i.getUTCHours()===0&&i.getUTCMinutes()===0&&i.getUTCSeconds()===0){var k=this._getClosestWorkTimePast(i,"hour");if(k.valueOf()===i.valueOf()){var k=this.$gantt.date.add(i,-1,"day"),y=this._getWorkHours(k);if(y.length){var g=y[y.length-1];k.setUTCSeconds(g.durationSeconds)}}i=k}else i=this._getClosestWorkTimePast(new Date(i-1),"hour")}if(n<t){var C=t-n;s=this._subtractMinutesUntilHourStart(i,C),n+=s.added,i=s.end}return i},_calculateMinuteEndDate:function(e,t,r){var i=new Date(e),n=0;r=r||1,t=Math.abs(t*1),t=Math.round(t);var a=this._addMinutesUntilHourEnd(i,t);n+=a.added,i=a.end;for(var s=0,o=[],c=0,l=this._isMinutePrecision(i);n<t;){var d=this.$gantt.date.day_start(new Date(i)).valueOf();d!==s&&(o=this._getWorkHours(i),c=this._getMinutesPerDay(i),s=d);var u=t-n,f=this._getTimeOfDayStamp(i);if(!o.length||!c){i=this.$gantt.date.add(this.$gantt.date.day_start(i),1,"day");continue}if(o[0].start>=f&&u>=c){if(n+=c,u==c){i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,o[o.length-1].end));break}else i=this.$gantt.date.add(i,1,"day"),i=this.$gantt.date.day_start(i);continue}for(var p=!1,v=null,S=0;S<o.length;S++)if(o[S].start<=f&&o[S].end>f){p=!0,v=o[S];break}if(p)if(f===v.start&&u>=v.durationMinutes)n+=v.durationMinutes,i=this.$gantt.date.add(i,v.durationMinutes,"minute");else if(u<=v.endMinute-f/60)n+=u,i=this.$gantt.date.add(i,u,"minute");else{var A=this._getMinutesPerHour(i);A<=u?(n+=A,l?i=this.$gantt.date.add(i,A,"minute"):i=this._nextDate(i,"hour",r)):(a=this._addMinutesUntilHourEnd(i,u),n+=a.added,i=a.end)}else i=this._getClosestWorkTimeFuture(i,"hour")}if(n<t){var D=t-n;a=this._addMinutesUntilHourEnd(i,D),n+=a.added,i=a.end}return i},getClosestWorkTime:function(){var e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._getClosestWorkTime(e.date,e.unit,e.dir)},_getClosestWorkTime:function(e,t,r){var i=new Date(e);if(this._isWorkTime(i,t))return i;if(i=this.$gantt.date[t+"_start"](i),r=="any"||!r){var n=this._getClosestWorkTimeFuture(i,t),a=this._getClosestWorkTimePast(i,t);Math.abs(n-e)<=Math.abs(e-a)?i=n:i=a}else r=="past"?i=this._getClosestWorkTimePast(i,t):i=this._getClosestWorkTimeFuture(i,t);return i},_getClosestWorkTimeFuture:function(e,t){return this._getClosestWorkTimeGeneric(e,t,1)},_getClosestWorkTimePast:function(e,t){var r=this._getClosestWorkTimeGeneric(e,t,-1);return this.$gantt.date.add(r,1,t)},_findClosestTimeInDay:function(e,t,r){var i=new Date(e),n=null,a=!1;this._getWorkHours(i).length||(i=this._getClosestWorkTime(i,"day",t<0?"past":"future"),t<0&&(i=new Date(i.valueOf()-1),a=!0),r=this._getWorkHours(i));var s=this._getTimeOfDayStamp(i);if(a&&(s=this._getTimeOfDayStamp(new Date(i.valueOf()+1),a)),t>0){for(var o=0;o<r.length;o++)if(r[o].start>=s){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,r[o].start));break}}else for(var o=r.length-1;o>=0;o--)if(r[o].end<=s){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,r[o].end));break}else if(r[o].end>s&&r[o].start<=s){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,s));break}return n},_getClosestWorkMinute:function(e,t,r){var i=new Date(e),n=this._getWorkHours(i),a=this._findClosestTimeInDay(i,r,n);return a||(r>0?(i=this.calculateEndDate(i,r,t),i=this.$gantt.date.day_start(i)):(i=this.calculateEndDate(i,r,"day"),i=this.$gantt.date.day_start(i),i=this.$gantt.date.add(i,1,"day"),i=new Date(i.valueOf()-1)),n=this._getWorkHours(i),a=this._findClosestTimeInDay(i,r,n)),r<0&&(a=this.$gantt.date.add(a,-1,t)),a},_getClosestWorkTimeGeneric:function(e,t,r){if(t==="hour"||t==="minute")return this._getClosestWorkMinute(e,t,r);for(var i=this._getUnitOrder(t),n=this.units[i-1],a=e,s=3e3,o=0;!this._isWorkTime(a,t)&&!(n&&!this._isWorkTime(a,n)&&(r>0?a=this._getClosestWorkTimeFuture(a,n):a=this._getClosestWorkTimePast(a,n),this._isWorkTime(a,t)));){if(o++,o>s)return this.$gantt.assert(!1,"Invalid working time check"),!1;a=this.$gantt.date.add(a,r,t),this.$gantt.date[t+"_start"]&&(a=this.$gantt.date[t+"_start"](a))}return a},hasWorkTime:function(){var e=this.getConfig(),t=e.dates,r=[0,1,2,3,4,5,6];for(var i in e.dates);var n=this._checkWorkHours(e.hours),a=!1;return r.forEach((function(s){if(!a){var o=t[s];o===!0?a=n:Array.isArray(o)&&(a=this._checkWorkHours(o))}}).bind(this)),a},_checkWorkHours:function(e){if(e.length===0)return!1;for(var t=!1,r=0;r<e.length;r+=2)e[r]!==e[r+1]&&(t=!0);return t},_isMinutePrecision:function(e){let t=!1;return this._getWorkHours(e).forEach(function(r){(r.startMinute%60||r.endMinute%60)&&(t=!0)}),t}};var Re={isLegacyResourceCalendarFormat:function(e){if(!e)return!1;for(var t in e)if(e[t]&&typeof e[t]=="object")return!0;return!1},getResourceProperty:function(e){var t=e.resource_calendars,r=e.resource_property;if(this.isLegacyResourceCalendarFormat(t))for(var i in e){r=i;break}return r},getCalendarIdFromLegacyConfig:function(e,t){if(t)for(var r in t){var i=t[r];if(e[r]){var n=i[e[r]];if(n)return n}}return null}};function Vp(){function e(n){return n.map(function(a){return a&&a.resource_id?a.resource_id:a}).sort().join("-")}var t={};function r(n,a){return a.mergeCalendars(n.map(function(s){var o=s&&s.resource_id?s.resource_id:s;return a.getResourceCalendar(o)}))}function i(n,a){var s=e(n);if(n.length){if(n.length===1)return a.getResourceCalendar(s).id;if(t[s])return t[s].id;var o=r(n,a);return t[s]=o,a.addCalendar(o)}else return null}return{getCalendarIdFromMultipleResources:i}}var Yp=Vp();function Ic(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=Re.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))}Ic.prototype={_calendars:{},_convertWorkTimeSettings:function(e){let t=e.days;if(typeof t=="object"&&!Array.isArray(t)&&t!==null){let r={};if(t?.weekdays)for(let i=0;i<7;i++)r[i]=t.weekdays[i];t?.dates&&Object.entries(t.dates).forEach(([i,n])=>{r[new Date(i).valueOf()]=n}),Object.entries(r).forEach(([i,n])=>{n instanceof Array||(r[i]=!!n)}),e={...e,dates:r}}else if(t&&!e.dates){e.dates=e.dates||{};for(let r=0;r<t.length;r++)e.dates[r]=t[r],t[r]instanceof Array||(e.dates[r]=!!t[r])}return delete e.days,e},mergeCalendars:function(){var e=[],t=arguments;if(Array.isArray(t[0]))e=t[0].slice();else for(var r=0;r<arguments.length;r++)e.push(arguments[r]);var i=new Cc,n;return e.forEach((function(a){n?n=this._createCalendarFromConfig(i.merge(n,a)):n=a}).bind(this)),this.createCalendar(n)},_createCalendarFromConfig:function(e){var t=new sn(this.$gantt,Ac(this.$gantt));t.id=String(Xi());var r=this._convertWorkTimeSettings(e);if(r.customWeeks)for(var i in r.customWeeks)r.customWeeks[i]=this._convertWorkTimeSettings(r.customWeeks[i]);return t._setConfig(r),t},createCalendar:function(e){var t;e||(e={}),e.getConfig?t=vt(e.getConfig()):e.worktime?t=vt(e.worktime):t=vt(e);var r=vt(this.defaults.fulltime.worktime);return pe(t,r),this._createCalendarFromConfig(t)},getCalendar:function(e){e=e||"global";var t=this._calendars[e];return t||(this.createDefaultCalendars(),t=this._calendars[e]),t},getCalendars:function(){var e=[];for(var t in this._calendars)e.push(this.getCalendar(t));return e},_getOwnCalendar:function(e){var t=this.$gantt.config;if(e[t.calendar_property])return this.getCalendar(e[t.calendar_property]);if(t.resource_calendars){var r,i,n;if(this._legacyConfig===!1?n=t.resource_property:n=Re.getResourceProperty(t),Array.isArray(e[n])&&e[n].length)t.dynamic_resource_calendars?i=Yp.getCalendarIdFromMultipleResources(e[n],this):r=this.getResourceCalendar(e[n]);else if(this._legacyConfig===void 0&&(this._legacyConfig=Re.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var i=Re.getCalendarIdFromLegacyConfig(e,t.resource_calendars);else if(n&&e[n]&&t.resource_calendars[e[n]])var r=this.getResourceCalendar(e[n]);if(i&&(r=this.getCalendar(i)),r)return r}return null},getResourceCalendar:function(e){if(e==null)return this.getCalendar();var t=null;typeof e=="number"||typeof e=="string"?t=e:t=e.id||e.key;var r=this.$gantt.config,i=r.resource_calendars,n=null;if(Array.isArray(e)&&e.length===1&&(typeof e[0]=="object"?t=e[0].resource_id:t=e[0]),i){if(this._legacyConfig===void 0&&(this._legacyConfig=Re.isLegacyResourceCalendarFormat(r.resource_calendars)),this._legacyConfig){for(var a in i)if(i[a][t]){n=i[a][t];break}}else var n=i[t];if(n)return this.getCalendar(n)}return this.getCalendar()},getTaskCalendar:function(e){var t=this.$gantt,r;if(e==null)return this.getCalendar();if((typeof e=="number"||typeof e=="string")&&t.isTaskExists(e)?r=t.getTask(e):r=e,!r)return this.getCalendar();var i=this._getOwnCalendar(r),n=!!t.getState().group_mode;if(!i&&t.config.inherit_calendar&&t.isTaskExists(r.parent)){for(var a=r;t.isTaskExists(a.parent)&&(a=t.getTask(a.parent),!(t.isSummaryTask(a)&&(i=this._getOwnCalendar(a),i))););n&&!i&&e.$effective_calendar&&(i=this.getCalendar(e.$effective_calendar))}return i||this.getCalendar()},addCalendar:function(e){if(!this.isCalendar(e)){var t=e.id;e=this.createCalendar(e),e.id=t}if(e._tryChangeCalendarSettings(function(){})){var r=this.$gantt.config;return e.id=e.id||Xi(),this._calendars[e.id]=e,r.worktimes||(r.worktimes={}),r.worktimes[e.id]=e.getConfig(),e.id}else return this.$gantt.callEvent("onCalendarError",[{message:"Invalid calendar settings, no worktime available"},e]),null},deleteCalendar:function(e){var t=this.$gantt.config;return e&&this._calendars[e]?(delete this._calendars[e],t.worktimes&&t.worktimes[e]&&delete t.worktimes[e],!0):!1},restoreConfigCalendars:function(e){for(var t in e)if(!this._calendars[t]){var r=e[t],i=this.createCalendar(r);i.id=t,this.addCalendar(i)}},defaults:{global:{id:"global",worktime:{hours:[8,12,13,17],days:[0,1,1,1,1,1,0]}},fulltime:{id:"fulltime",worktime:{hours:[0,24],days:[1,1,1,1,1,1,1]}}},createDefaultCalendars:function(){var e=this.$gantt.config;this.restoreConfigCalendars(this.defaults),this.restoreConfigCalendars(e.worktimes)},isCalendar:function(e){var t=[e.isWorkTime,e.setWorkTime,e.getWorkHours,e.unsetWorkTime,e.getClosestWorkTime,e.calculateDuration,e.hasDuration,e.calculateEndDate];return t.every(function(r){return r instanceof Function})}};function on(e,t){this.argumentsHelper=t,this.$gantt=e}on.prototype={getWorkHours:function(){return[0,24]},setWorkTime:function(){return!0},unsetWorkTime:function(){return!0},isWorkTime:function(){return!0},getClosestWorkTime:function(t){var t=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return t.date},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit,n=e.step;return this._calculateDuration(t,r,i,n)},_calculateDuration:function(e,t,r,i){var n=this.$gantt.date,a={week:1e3*60*60*24*7,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60},s=0;if(a[r])s=Math.round((t-e)/(i*a[r]));else{for(var o=new Date(e),c=new Date(t);o.valueOf()<c.valueOf();)s+=1,o=n.add(o,i,r);o.valueOf()!=t.valueOf()&&(s+=(c-o)/(n.add(o,i,r)-o))}return Math.round(s)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit;return i?(t=new Date(t),r=new Date(r),t.valueOf()<r.valueOf()):!1},hasWorkTime:function(){return!0},equals:function(e){return e instanceof on},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,i=e.unit,n=e.step;return this.$gantt.date.add(t,n*r,i)}};function kc(e){this.$gantt=e.$gantt,this.argumentsHelper=Ac(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new on(this.$gantt,this.argumentsHelper)}kc.prototype={_getCalendar:function(e){var t;if(!this.$gantt.config.work_time)t=this.$disabledCalendar;else{var r=this.calendarManager;e.task?t=r.getTaskCalendar(e.task):e.id?t=r.getTaskCalendar(e):e.calendar&&(t=e.calendar),t||(t=r.getTaskCalendar())}return t},getWorkHours:function(e){e=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);var t=this._getCalendar(e);return t.getWorkHours(e.date)},setWorkTime:function(e,t){return e=this.argumentsHelper.setWorkTimeArguments.apply(this.argumentsHelper,arguments),t||(t=this.calendarManager.getCalendar()),t.setWorkTime(e)},unsetWorkTime:function(e,t){return e=this.argumentsHelper.unsetWorkTimeArguments.apply(this.argumentsHelper,arguments),t||(t=this.calendarManager.getCalendar()),t.unsetWorkTime(e)},isWorkTime:function(e,t,r,i){var n=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return i=this._getCalendar(n),i.isWorkTime(n)},getClosestWorkTime:function(e){e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);var t=this._getCalendar(e);return t.getClosestWorkTime(e)},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=this._getCalendar(e);return t.calculateDuration(e)},hasDuration:function(){var e=this.argumentsHelper.hasDurationArguments.apply(this.argumentsHelper,arguments),t=this._getCalendar(e);return t.hasDuration(e)},calculateEndDate:function(t){var t=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),r=this._getCalendar(t);return r.calculateEndDate(t)}};var $p=function(e,t){return{getWorkHours:function(r){return t.getWorkHours(r)},setWorkTime:function(r){return t.setWorkTime(r)},unsetWorkTime:function(r){t.unsetWorkTime(r)},isWorkTime:function(r,i,n){return t.isWorkTime(r,i,n)},getClosestWorkTime:function(r){return t.getClosestWorkTime(r)},calculateDuration:function(r,i,n){return t.calculateDuration(r,i,n)},_hasDuration:function(r,i,n){return t.hasDuration(r,i,n)},calculateEndDate:function(r,i,n,a){return t.calculateEndDate(r,i,n,a)},mergeCalendars:dt(e.mergeCalendars,e),createCalendar:dt(e.createCalendar,e),addCalendar:dt(e.addCalendar,e),getCalendar:dt(e.getCalendar,e),getCalendars:dt(e.getCalendars,e),getResourceCalendar:dt(e.getResourceCalendar,e),getTaskCalendar:dt(e.getTaskCalendar,e),deleteCalendar:dt(e.deleteCalendar,e)}},Gp={create:$p};function Sc(e){var t=new Ic(e),r=new kc(t),i=Gp.create(t,r);pe(e,i)}var Dc={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 Tc(e={}){let t=e.config||{},r={config:Object.assign({duration_unit:"hour",duration_step:1,work_time:!1,worktimes:{},work_days:null,inherit_calendar:!1,calendar_property:"calendar_id",resource_property:"resource_id",resource_calendars:{},dynamic_resource_calendars:!1,start_on_monday:!0,server_utc:!0,csp:"auto",show_errors:!1},t),locale:e.locale||Dc,templates:e.templates||{},getTask:e.getTask||function(i){return null},isTaskExists:e.isTaskExists||function(i){return!1},isSummaryTask:e.isSummaryTask||function(i){return!1},getState:function(){return{group_mode:!1}},callEvent:function(i,n){let a=e.onEvent;return a&&a(i,n),!0},attachEvent:function(){return 0},checkEvent:function(){return!1},detachEvent:function(){},defined:yc,mixin:pe,copy:vt,assert:function(i,n){if(!i){if(e.throwOnAssert)throw new Error("[calendar] "+n);e.silent!==!0&&console.error("[calendar]",n)}},$services:{getService:function(){return null}},$ui:{getView:function(){return null}}};return r._correct_dst_change=function(i){return i},r.date=vc(r),r.date.init(),Sc(r),r}function Kp(e={}){let t=Tc(e);return{addCalendar:function(r){return t.addCalendar(r)},deleteCalendar:function(r){return t.deleteCalendar(r)},getCalendar:function(r){return t.getCalendar(r)},getCalendars:function(){return t.getCalendars()},mergeCalendars:function(){return t.mergeCalendars.apply(t,arguments)},getTaskCalendar:function(r){return t.getTaskCalendar(r)},getResourceCalendar:function(r){return t.getResourceCalendar(r)},setWorkTime:function(r){return t.setWorkTime(r)},unsetWorkTime:function(r){return t.unsetWorkTime(r)},isWorkTime:function(){return t.isWorkTime.apply(t,arguments)},getClosestWorkTime:function(){return t.getClosestWorkTime.apply(t,arguments)},getWorkHours:function(){return t.getWorkHours.apply(t,arguments)},calculateDuration:function(){return t.calculateDuration.apply(t,arguments)},calculateEndDate:function(){return t.calculateEndDate.apply(t,arguments)},_internals:t}}var _c={createCalendar:Kp};var UR=3600*1e3;function Lc(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:zp}=_c,Le="__replay_default__";function qp(e){if(!e||e.length===0||typeof e[0]=="string")return e;let t=e.map(Number);if(t.some(a=>Number.isNaN(a)))return e;let r=t[0],i=t[t.length-1];return t.every((a,s)=>a===r+s)?[`${r}:00-${i+1}:00`]:e}var Pc={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},Ec="__main_global__",Jp={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function Rc(e){return!e||e.hours===void 0||e.hours.length>0||e.days?.some(t=>Array.isArray(t)&&t.length>0)===!0?!0:Object.values(e.dates??{}).some(t=>Array.isArray(t)&&t.length>0)}function Xp(e){let t={};if(Array.isArray(e.days))for(let i=0;i<e.days.length;i+=1)t[i]=e.days[i];if(e.dates)for(let[i,n]of Object.entries(e.dates))t[i]=n;let r={hours:qp(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function bc(e){let t=zp({config:{work_time:!0}});t.addCalendar({id:Le,worktime:Pc}),t.addCalendar({id:Ec,worktime:Jp});let r=new Set(e.filter(d=>!Rc(d.worktime)).map(d=>String(d.id))),i=e.filter(d=>Rc(d.worktime));for(let d of i)t.addCalendar({id:d.id,worktime:d.worktime?Xp(d.worktime):Pc});let n=hc(t),a=n.getCalendar(Le),s=n.getCalendar(Ec);if(!a||!s)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let o=new Set([Le]);for(let d of i)o.add(String(d.id));let c=new Map;return{reader:{getCalendar(d){let u=String(d),f=c.get(u);if(f)return f;let p=a;return o.has(u)?p=n.getCalendar(d)??a:r.has(u)&&(p=s),c.set(u,p),p}}}}function wc(e){return{hasChildren(t){return e.hasChildren(t)},getParentStartDateIfHasPredecessors(t){let r=e.getActivity(t);if(!r)return null;let i=e.getParent(r.id);return!i||e.getIncomingLinkIds(i.id).length===0?null:i.startDate},getDescendantIds(t){return Zp(e,t).map(r=>String(r))},getAncestorIds(t){let r=[],i=e.getActivity(t);for(;i;){let n=i.parentId;if(n===null)break;let a=e.getActivity(n);if(!a)break;r.push(String(n)),i=a}return r},getChildProgressInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,progress:Number(n?.progress??0),ponderator:Number(n?.ponderator??0)}})},getChildHhInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,workHours:Number(n?.workHours??0),progress:Number(n?.progress??0),realWorkHours:Number(n?.realWorkHours??0)}})},getChildUsedCostInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,usedCost:Number(n?.usedCost??0)}})},getChildCostInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,cost:Number(n?.cost??0)}})}}}function Zp(e,t){let r=[],i=new ut;for(let n of e.getChildren(t))i.enqueue(n);for(;!i.isEmpty();){let n=i.dequeue();r.push(n);for(let a of e.getChildren(n))i.enqueue(a)}return r}function Oc(e,t){return{calendars:e.calendarReader,hierarchy:wc(e),activityReader:Lc(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay,inputUnit:t.inputUnit??"days"}}function xc(e){return Ee(e)}function cn(e,t,r,i,n){return{changeSet:e,beforeSnap:t,beforeLinks:r,afterSnap:i,afterLinks:n}}function Fc(e,t){let r=new Map,i=new Map;for(let n of t.activities){if(n.kind!=="created")continue;let a=e.getActivity(String(n.id));a&&r.set(String(n.id),j(a))}for(let n of t.links){if(n.kind!=="created")continue;let a=e.getLink(String(n.id));a&&i.set(String(n.id),{...a})}return{afterSnap:r,afterLinks:i}}function Mc(e){return e.kind!=="inline-edit"||!Pe.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function Nc(e){return e.changeSet.activities.length===1&&e.changeSet.activities[0]?.kind==="updated"&&e.changeSet.links.length===0&&!e.beforeSnap?.size&&!e.afterSnap?.size}function Wc(e,t){if(!Nc(e)||!Nc(t))return!1;let r=e.changeSet.activities[0],i=t.changeSet.activities[0];return!!r&&!!i&&String(r.id)===String(i.id)}function Uc(e,t){let r=e.changeSet.activities[0],i=t.changeSet.activities[0];if(!r||!i)return t;let n=r.fields??{},a=i.fields??{},s={};for(let c of new Set([...Object.keys(n),...Object.keys(a)])){let l=n[c],d=a[c];s[c]={before:l?l.before:d?.before,after:d?d.after:l?.after}}let o={...t.changeSet,activities:[{...i,fields:s}]};return cn(o)}function Bc(e){return e.kind!=="sir-sync"&&e.kind!=="activity-lookahead-sync"}function ln(e){for(let t of e.changeSet.activities)if(t.kind==="created"||t.kind==="deleted"||t.kind==="updated"&&t.fields&&E.CUSTOM_ID in t.fields)return!0;return!1}function dn(e,t,r){let i=[],n=[];for(let s of t.changeSet.activities){let o=String(s.id);if(s.kind==="updated"){let c=e.getActivity(o);i.push({id:o,kind:"updated",after:c?j(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getActivity(o);i.push({id:o,kind:"created",after:c?j(c):null})}else i.push({id:o,kind:"deleted",after:null});else if(r==="before")i.push({id:o,kind:"deleted",after:null});else{let c=e.getActivity(o);i.push({id:o,kind:"created",after:c?j(c):null})}}for(let s of t.changeSet.links){let o=String(s.id);if(s.kind==="updated"){let c=e.getLink(o);n.push({id:o,kind:"updated",after:c?gt(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getLink(o);n.push({id:o,kind:"created",after:c?gt(c):null})}else n.push({id:o,kind:"deleted",after:null});else if(r==="before")n.push({id:o,kind:"deleted",after:null});else{let c=e.getLink(o);n.push({id:o,kind:"created",after:c?gt(c):null})}}let a=(t.changeSet.viewState??[]).map(s=>r==="before"?Qp(s):s);return{source:{kind:r==="before"?"undo":"redo"},activities:i,links:n,calendars:[],trackingEvents:[],effects:[],viewState:a}}function Qp(e){return{activityId:e.activityId,...e.checked?{checked:{before:e.checked.after,after:e.checked.before}}:{},...e.visible?{visible:{before:e.visible.after,after:e.visible.before}}:{}}}function Hc(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function jc(e,t){Yc(e,t,"before")}function Vc(e,t){Yc(e,t,"after")}function Yc(e,t,r){let i=t.changeSet;for(let n of i.activities)if(n.kind==="updated"){if(!n.fields)continue;for(let[a,s]of Object.entries(n.fields))Z(e,n.id,a,r==="before"?s.before:s.after)}else if(n.kind==="deleted")if(r==="before"){let a=t.beforeSnap?.get(String(n.id));if(!a)throw new Error(`undo: missing beforeSnap for resurrecting activity ${n.id}`);e.addActivity(j(a))}else e.removeActivity(String(n.id));else if(r==="before")e.removeActivity(String(n.id));else{let a=t.afterSnap?.get(String(n.id));if(!a)throw new Error(`redo: missing afterSnap for re-creating activity ${n.id}`);e.addActivity(j(a))}for(let n of i.links)if(n.kind==="updated"){if(!n.fields)continue;for(let[a,s]of Object.entries(n.fields))Cs(e,String(n.id),a,r==="before"?s.before:s.after)}else if(n.kind==="deleted")if(r==="before"){let a=t.beforeLinks?.get(String(n.id));if(!a)throw new Error(`undo: missing beforeLinks for re-adding link ${n.id}`);e.addLink(a)}else e.removeLink(String(n.id));else if(r==="before")e.removeLink(String(n.id));else{let a=t.afterLinks?.get(String(n.id));if(!a)throw new Error(`redo: missing afterLinks for re-creating link ${n.id}`);e.addLink(a)}for(let n of i.viewState??[])n.checked&&e.setChecked(n.activityId,r==="before"?n.checked.before:n.checked.after),n.visible&&e.setVisible(n.activityId,r==="before"?n.visible.before:n.visible.after)}var th=100,eh=600,wr=class{constructor(t=th){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];_lastKey=null;_lastTime=0;record(t,r=null,i=0){let n=this.undoStack[this.undoStack.length-1];r!=null&&r===this._lastKey&&i-this._lastTime<=eh&&n!==void 0&&Wc(n,t)?this.undoStack[this.undoStack.length-1]=Uc(n,t):(this.undoStack.push(t),this.undoStack.length>this.maxDepth&&this.undoStack.shift()),this._lastKey=r,this._lastTime=i,this.redoStack.length=0}resetCoalesce(){this._lastKey=null}takeUndo(){return this.undoStack.pop()??null}takeRedo(){return this.redoStack.pop()??null}pushRedo(t){this.redoStack.push(t)}pushUndo(t){this.undoStack.push(t)}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undoDepth(){return this.undoStack.length}clear(){this.undoStack.length=0,this.redoStack.length=0}};var $c=["id","proplannerId","parentId","name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","autoScheduling","calendarId","assignedDefaultCalendar","dateOrigin","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","correlativeId","uniqueCorrelativeId","customId","subcontractId","isLookahead","newActivityIds","hasNewActivities","pendingRequestIds","responsableIds","tagIds"],Gc=new Set(["startDate","endDate","constraintDate","dateOrigin"]),Kc=new Set(["newActivityIds","pendingRequestIds","responsableIds","tagIds"]);function zc(e){let t=$c.map(r=>[r,rh(r,e[r])]);return Object.fromEntries(t)}function rh(e,t){return Gc.has(e)?t instanceof Date?new Date(t):null:Kc.has(e)?Array.isArray(t)?[...t]:[]:t}function qc(e,t){if(e.assignedDefaultCalendar)return!0;for(let r of $c)if(!ih(r,e[r],t[r]))return!0;return!1}function ih(e,t,r){return Gc.has(e)?nh(t,r):Kc.has(e)?ah(t,r):(t??null)===(r??null)}function nh(e,t){let r=e instanceof Date?e.getTime():null,i=t instanceof Date?t.getTime():null;return r===i}function ah(e,t){let r=Array.isArray(e)?[...e].map(String).sort():[],i=Array.isArray(t)?[...t].map(String).sort():[];return r.length!==i.length?!1:r.every((n,a)=>n===i[a])}var Or=class{initialized=!1;linksAtLastSave=new Map;activitiesAtLastSave=new Map;init(t,r){this.snapshotActivities(t),this.snapshotLinks(r),this.initialized=!0}snapshotActivities(t){this.activitiesAtLastSave.clear();for(let r of t)r.proplannerId!=null&&this.activitiesAtLastSave.set(String(r.id),zc(r))}snapshotLinks(t){this.linksAtLastSave.clear();for(let r of t)r.proplannerId!=null&&this.linksAtLastSave.set(String(r.id),{lag:r.lag,type:r.type})}modifiedActivities(t){return this.initialized?t.filter(r=>{if(r.proplannerId==null)return!1;if(r.assignedDefaultCalendar)return!0;let i=this.activitiesAtLastSave.get(String(r.id));return i?qc(r,i):!0}):[]}modifiedLinks(t){return this.initialized?t.filter(r=>{if(r.proplannerId==null)return!1;let i=this.linksAtLastSave.get(String(r.id));return i?r.lag!==i.lag||r.type!==i.type:!0}):[]}clear(){this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear()}};var Jc=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;var un=[!1,!0,!0,!0,!0,!0,!1],Xc=new Set(["1","true"]),fn="DURATION",Zc="asap",Qc={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 tl(e,t){let r=[],i=e.map(a=>{let s=hh(a,t);return a.should_be_showed===!1&&r.push(s.id),s});yh(i);let n=new Set(i.map(a=>a.id));return mh(i,n,t.reporter),{activities:i,activityIds:n,hiddenIds:r}}function sh(e){return e===0}function oh(e,t){if(!e)return null;let r=Qc[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),Zc):r}function ch(e,t){let r=oh(e.constraint,t),n=r!=="asap"&&r!=="alap"&&e.constraint_date?Dt(e.constraint_date):null;return{constraintType:r,constraintDate:n}}function lh(e,t,r){if(e==null)return r;let i=String(e);return t.has(i)?i:r}function dh(e){if(e==null||e==="")return[];if(Array.isArray(e))return e.map(String);if(typeof e!="string")return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.map(String):[]}catch{return[]}}function uh(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function pn(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)uh(r)&&t.push(String(r.id));return t}function fh(e){return e==="0"?null:String(e)}function ph(e,t){return Array.isArray(e)?e.map(r=>Pr(r,t)).filter(r=>r!==null):[]}function hh(e,t){let r=lh(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),i=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),n=Number(e.progress),{constraintType:a,constraintDate:s}=ch(e,t.reporter),o=e.type==="milestone",c=Dt(e.start_date),l=o?c:Dt(e.end_date),d=o?0:Number(e.duration);return{id:String(e.unique_id),proplannerId:typeof e.id=="number"?e.id:null,parentId:fh(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:Ae(d,t.hoursPerDay),constraintType:a,constraintDate:s,autoScheduling:sh(n),calendarId:r,assignedDefaultCalendar:r!=null&&i,dateOrigin:e.date_origin==null?null:Dt(e.date_origin),progress:n,cost:Number(e.cost),usedCost:Number(e.used_cost??0),realCost:Number(e.real_cost??0),workHours:Number(e.hhWorkTime),realWorkHours:Number(e.real_work??0),ponderator:Number(e.ponderator??0),hasCustomPonderator:e.hasCustomPonderator,correlativeId:e.correlative_id,uniqueCorrelativeId:e.unique_correlative_id,customId:e.custom_id,subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:dh(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:pn(e.pendingRequests),responsableIds:pn(e.responsables),tagIds:pn(e.tags),baselinePoints:ph(e.baseline_points,t.reporter),baselineSnapshot:null,recursiveDurationHours:Ae(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),isCritical:!!e.is_critical,freeSlackHours:e.freeSlack,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null,promotionRestore:null}}function yh(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function mh(e,t,r){for(let i of e)i.parentId!==null&&(t.has(i.parentId)||(r.warn(`[parseFromBackend] activity "${i.id}" references unknown parent "${i.parentId}" \u2014 re-parenting to root (null)`),i.parentId=null))}function nl(e,t,r,i=null){let s=(e!==void 0&&e.length>0?e:t??[]).map(c=>Ah(c,i)),o=(r??[]).map(c=>Ch(c,i));return{calendars:s,baseCalendars:o,knownCalendarIds:new Set(s.map(c=>c.id)),defaultCalendarId:vh(s)}}function vh(e){let t=e.find(i=>i.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function al(e,t){let r=_h(e.working_days),{days:i,hours:n}=Th(e,r),a=Ih(t.exceptionsSource,t.exceptionRange),s={days:i,hours:n};return a&&(s.dates=a),{id:`${String(e.id)}${t.idSuffix}`,name:e.name,is_default:t.isDefault,...t.baseDefault!==void 0?{baseDefault:t.baseDefault}:{},worktime:s}}function Ah(e,t){let r=e.baseDefault,i=typeof r=="boolean"?r:void 0;return al(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:i,exceptionsSource:e.exceptiondays,exceptionRange:t})}function Ch(e,t){return al(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function Ih(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let i of e){if(!i)continue;let n=kh(i.from_date,i.to_date,t);if(n.length===0)continue;let a=Sh(i);if(a!==void 0)for(let s of n)r[s]=a}return Object.keys(r).length>0?r:null}function kh(e,t,r){let i=el(e),n=el(t);if(i===null||n===null)return[];if(r&&(n<r.start||i>r.end))return[];let a=[],s=r?Math.max(i,r.start):i,o=r?Math.min(n,r.end):n;for(;s<=o;)a.push(String(s)),s+=864e5;return a}function el(e){if(typeof e!="string")return null;let t=Jc.exec(e.trim());if(!t)return null;let r=Number(t[1]),i=Number(t[2]),n=Number(t[3]);return Number.isFinite(r)&&Number.isFinite(i)&&Number.isFinite(n)?Date.UTC(r,i-1,n):null}function Sh(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=Dh(t);if(r.length>0)return r}}var rl=/^\d{1,2}:\d{2}$/;function Dh(e){let t=[];for(let r of e){let i=cl(r?.shift_string);if(!i)continue;if(!i.startsCsv.includes(",")&&!i.endsCsv.includes(",")){let o=i.startsCsv.trim(),c=i.endsCsv.trim();!xr(o)&&!xr(c)&&rl.test(o)&&rl.test(c)&&t.push(`${o}-${c}`);continue}let s=ol(i.startsCsv,i.endsCsv).find(o=>o!==null);s&&t.push(s)}return t.sort(sl),t}function il(e){let t=e.indexOf("-"),r=t>0?e.slice(0,t):e,[i,n]=r.split(":");return(Number(i)||0)*60+(Number(n)||0)}function sl(e,t){return il(e)-il(t)}function Th(e,t){let r=Array.from({length:7},()=>[]),i=(l,d)=>{let u=ol(l,d);for(let f=0;f<7;f+=1){let p=u[f],v=r[f];p&&v&&v.push(p)}},n=Array.isArray(e.shifts)&&e.shifts.length>0,a=typeof e.shift_start=="string"&&typeof e.shift_end=="string";if(n)for(let l of e.shifts){let d=cl(l?.shift_string);d&&i(d.startsCsv,d.endsCsv)}else a&&i(e.shift_start,e.shift_end);for(let l of r)l.sort(sl);let o=r.find((l,d)=>!!t[d]&&l.length>0)??[];return{days:t.map((l,d)=>{if(!l)return!1;let u=r[d];return u&&u.length>0?u:o}),hours:o}}function ol(e,t){let r=Array.from({length:7},()=>null);if(typeof e!="string"||typeof t!="string")return r;let i=e.split(",").map(o=>o.trim()),n=t.split(",").map(o=>o.trim());if(!(i.length===n.length&&i.length>0&&i.length<=7))return r;let s=[...r];for(let o=0;o<i.length;o+=1){let c=i[o],l=n[o];xr(c)||xr(l)||(s[o]=`${c}-${l}`)}return s}function cl(e){if(typeof e!="string")return null;let t=e.indexOf("-");return t<=0?null:{startsCsv:e.slice(0,t),endsCsv:e.slice(t+1)}}function _h(e){if(typeof e!="string")return[...un];let t=e.split(",").map(r=>r.trim());return t.length!==7?[...un]:t.map(r=>Xc.has(r))}var Ph=new Set(["false","null"]);function xr(e){return!e||Ph.has(e)}function Eh(e){return e==="0"||e==="1"||e==="2"||e==="3"}function Rh(e){if(typeof e!="string")return null;let t=Ma(e);return t||(Eh(e)?e:null)}function dl(e,t){let r=[];for(let i of e)try{r.push(Lh(i,t.knownActivityIds,t.hoursPerDay))}catch(n){t.reporter.warn("[parseFromBackend] dropping invalid link",n)}return bh(r)}function Lh(e,t,r){let i=String(e.unique_id??e.id),n=String(e.source_id??e.source??""),a=String(e.target_id??e.target??"");if(!t.has(n))throw new Error(`[parseFromBackend] link "${i}" source "${n}" does not exist`);if(!t.has(a))throw new Error(`[parseFromBackend] link "${i}" target "${a}" does not exist`);let s=Rh(e.type);if(s===null)throw new Error(`[parseFromBackend] link "${i}" has invalid type "${String(e.type)}"`);let o=e.ganttId,c=e.sectorId,l=e.id;return{id:i,source:n,target:a,type:s,lag:ft(Number(e.lag??0),r),...typeof o=="number"?{ganttId:o}:{},...typeof c=="number"?{sectorId:c}:{},...typeof l=="number"?{proplannerId:l}:{}}}function bh(e){let t=new Map;for(let r of e){let i=`${r.source}-${r.target}-${r.type}`,n=t.get(i);(!n||ll(r)>ll(n))&&t.set(i,r)}return[...t.values()]}function ll(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function wh(e){if(typeof e!="string")return fn;switch(e.toUpperCase()){case"DURATION":return"DURATION";case"COST":return"COST";case"HH":return"HH";default:return fn}}function Oh(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function xh(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function ul(e){let t=Oh(e),r=xh(e),i=e.update_duration_for_primavera_for_end_date===!0;return{id:String(e.id),name:e.name,hoursPerDay:e.hoursPerDay,hoursPerWeek:e.hoursPerWeek,dateFormat:e.dateFormat,projectId:e.projectId,companyId:e.companyId,...t!==void 0?{customIdPrefix:t}:{},...r!==void 0?{customIdIncrement:r}:{},...i?{updateDurationForPrimaveraEndDate:!0}:{},activityCreter:wh(e.activity_creter),statusCriteria:qr}}function Nr(e,t=Qt){let r=ul(e.sector),{calendars:i,baseCalendars:n,knownCalendarIds:a,defaultCalendarId:s}=nl(e.calendars,e.sector.calendars,e.baseCalendars,Nh(e.activities)),{activities:o,activityIds:c,hiddenIds:l}=tl(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t}),d=dl(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:o,links:d,calendars:i,baseCalendars:n,viewStateSeed:{hiddenIds:l}}}function Nh(e){let t=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let a of e){let s=new Date(a.start_date).getTime(),o=new Date(a.end_date).getTime();Number.isFinite(s)&&(t=Math.min(t,s)),Number.isFinite(o)&&(r=Math.max(r,o))}if(!Number.isFinite(t)||!Number.isFinite(r))return null;let i=new Date(t),n=new Date(r);return i.setFullYear(i.getFullYear()-1),n.setFullYear(n.getFullYear()+1),{start:i.getTime(),end:n.getTime()}}function fl(e={}){let t=e.seed??0,r=i=>{i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}return{next(){return t+=1,String(t)},bump(i){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}}}function pl(e={}){let t=e.seed??Date.now(),r=i=>{i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}return{next(){return t+=1,String(t)},bump(i){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}}}function hl(e={}){let t=e.seed??0,r=i=>{Number.isFinite(i)&&i>0&&i<=9999999&&i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){if(i==null)continue;let n=typeof i=="number"?i:Number(i);r(n)}return{next(){return t+=1,String(t)},bump(i){if(i==null)return;let n=typeof i=="number"?i:Number(i);r(n)}}}function yl(e){return!!e&&typeof e=="string"&&e.trim().length>0}function Fr(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function Mr(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function ml(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function gl(e,t){return!t&&yl(e)}function vl(e,t){return t&&yl(e)}function we(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function be(e){if(!we(e))return 0n;try{return BigInt(e)}catch{return 0n}}function Fh(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!we(t))return r;let i=t.length;return r.padStart(i,"0")}function mt(e,t){let r=be(e),i=be(t),n=r+i;return Fh(n,e)}function Wr(e,t){let r=be(e),i=be(t);return r<i?-1:r>i?1:0}function Ur(e,t){return Wr(e,t)<=0?e:t}function Br(e,t){return Wr(e,t)>=0?e:t}function Al(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Ur(t,r))}function Cl(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Br(t,r))}function Il(e){return{prefix:e,baseSuffix:null}}function kl(e,t){let r=Mr(e);return{prefix:Fr(e),baseSuffix:mt(r,t)}}function Sl(e){return{prefix:e,baseSuffix:null}}function Dl(e,t){return gl(e,t)?"parentConversion":vl(e,t)?"pasteReference":"noContext"}function Mh(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var Hr=class{prefixMap=new Map;processedIds=new Set;_journal=null;beginCustomIdTransaction(){this._journal=[]}commitCustomIdTransaction(){this._journal=null}rollbackCustomIdTransaction(){let t=this._journal;if(t!==null){for(let r of[...t].reverse()){let{prefix:i}=this.analyzeCustomId(r.customId);r.prefixBefore===null?this.prefixMap.delete(i):this.prefixMap.set(i,r.prefixBefore),r.hadId?this.processedIds.add(r.customId):this.processedIds.delete(r.customId)}this._journal=null}}_noteCustomIdBefore(t){if(this._journal===null)return;let{prefix:r}=this.analyzeCustomId(t),i=this.prefixMap.get(r);this._journal.push({customId:t,prefixBefore:i?Mh(i):null,hadId:this.processedIds.has(t)})}defaultPrefix;suffixIncrement;constructor(t={}){this.defaultPrefix=t.defaultPrefix??"A",this.suffixIncrement=t.suffixIncrement??"10"}extractPrefix(t){return Fr(t)}extractSuffix(t){return Mr(t)}analyzeCustomId(t){return{prefix:this.extractPrefix(t),suffix:this.extractSuffix(t)}}_updatePrefixStats(t,r){if(!this.prefixMap.has(t)){this.prefixMap.set(t,{min:r,max:r,next:r,quantity:1,usedSuffixes:new Set([r])}),this._recalculateNext(t);return}let i=this.prefixMap.get(t);i.usedSuffixes.has(r)||(i.usedSuffixes.add(r),i.min=Ur(r,i.min),i.max=Br(r,i.max),i.quantity+=1,this._recalculateNext(t))}_recalculateNext(t){let r=this.prefixMap.get(t);if(!r)return;let i=this.getNextAvailableSuffix(t);r.next=i??this.suffixIncrement}getPrefixStats(t){let r=this.prefixMap.get(t);return r?{min:r.min,max:r.max,next:r.next,quantity:r.quantity}:null}getNextSuffix(t){let r=this.prefixMap.get(t);return r?r.next:this.suffixIncrement}getAllPrefixes(){return Array.from(this.prefixMap.keys())}registerCustomId(t){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:i}=this.analyzeCustomId(t);if(!r&&!i)return{prefix:r,suffix:i};if(this._noteCustomIdBefore(t),this.prefixMap.has(r)){let n=this.prefixMap.get(r);n.usedSuffixes.has(i)||(n.usedSuffixes.add(i),n.min=Ur(i,n.min),n.max=Br(i,n.max),n.quantity+=1,this._recalculateNext(r))}else this.prefixMap.set(r,{min:i,max:i,next:mt(i,this.suffixIncrement),quantity:1,usedSuffixes:new Set([i])});return this.processedIds.add(t),{prefix:r,suffix:i}}releaseCustomId(t=null){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:i}=this.analyzeCustomId(t);if(!this.prefixMap.has(r))return{prefix:r,suffix:i};this._noteCustomIdBefore(t);let n=this.prefixMap.get(r);if(n.usedSuffixes.has(i)){let a=n.quantity-1;if(a===0)this.prefixMap.delete(r);else{let s=new Set(n.usedSuffixes);s.delete(i);let o=Array.from(s);o.length===0?this.prefixMap.delete(r):(n.usedSuffixes=s,n.min=Al(o),n.max=Cl(o),n.quantity=a,this._recalculateNext(r))}}return this.processedIds.delete(t),{prefix:r,suffix:i}}trackCustomIdChange(t,r){let i=this.releaseCustomId(t),n=this.registerCustomId(r);return{oldPrefix:i.prefix,oldSuffix:i.suffix,newPrefix:n.prefix,newSuffix:n.suffix}}_exceedsMaxLength(t){return t.length>20}_shouldSearchForGaps(t){if(!this.prefixMap.has(t))return!1;let r=this.prefixMap.get(t);return`${t}${mt(r.max,this.suffixIncrement)}`.length>20}_findFirstAvailableGap(t){if(!this.prefixMap.has(t))return null;let r=this.prefixMap.get(t),i=this.suffixIncrement;for(;Wr(i,r.max)<0;){if(`${t}${i}`.length>20)return null;if(!r.usedSuffixes.has(i))return i;i=mt(i,this.suffixIncrement)}return null}_generateDefaultCustomId(){let t=this.getNextAvailableSuffix(this.defaultPrefix);if(t===null){if(this._shouldSearchForGaps(this.defaultPrefix)){let r=this._findFirstAvailableGap(this.defaultPrefix);if(r!==null)return`${this.defaultPrefix}${r}`}return`${this.defaultPrefix}${this.suffixIncrement}`}return`${this.defaultPrefix}${t}`}getNextAvailableSuffix(t,r=null){if(!this.prefixMap.has(t)){let o=r&&we(r)?r:this.suffixIncrement;return`${t}${o}`.length>20?null:o}let i=this.prefixMap.get(t),n=this.suffixIncrement;if(!r||!we(r)){let o=mt(i.max,n);return`${t}${o}`.length>20?null:o}let a=r;for(let o=0;o<100;o++){if(`${t}${a}`.length>20)return null;if(!i.usedSuffixes.has(a))return a;a=mt(a,n)}let s=mt(i.max,n);return`${t}${s}`.length>20?null:s}generateNextCustomId(t){let r=this.getNextAvailableSuffix(t);if(r===null)return this._generateDefaultCustomId();if(this.prefixMap.has(t)){let n=this.prefixMap.get(t),a=0;for(;n.usedSuffixes.has(r)&&a<1e4;){let s=this.getNextAvailableSuffix(t,mt(r,this.suffixIncrement));if(s===null)return this._generateDefaultCustomId();r=s,a++}}let i=`${t}${r}`;return this._exceedsMaxLength(i)&&(i=this._generateDefaultCustomId()),i}populateFromActivities(t){if(!Array.isArray(t))return this;let r=[...new Set(t.filter(i=>i&&typeof i.customId=="string"&&i.customId).map(i=>i.customId))];for(let i of r){if(this.processedIds.has(i))continue;let{prefix:n,suffix:a}=this.analyzeCustomId(i);(n||a)&&(this._updatePrefixStats(n,a),this.processedIds.add(i))}return this}getDefaults(){return{prefix:this.defaultPrefix,increment:this.suffixIncrement}}generateCustomIdForNewChild(t){let{activity:r,useActivityCustomIdAsReference:i=!1}=t,n=ml(r),a=Dl(n,i),{prefix:s,baseSuffix:o}=this._applyGenerationStrategy(a,n),c=null;if(a==="parentConversion"&&this.prefixMap.has(s)){let f=this.prefixMap.get(s).max;c=mt(f,this.suffixIncrement)}a==="parentConversion"&&this.releaseCustomId(n);let l=a==="parentConversion"&&c?c:o,d=this.getNextAvailableSuffix(s,l);if(d===null){let f=this._generateDefaultCustomId();return this.registerCustomId(f),f}let u=`${s}${d}`;return this._exceedsMaxLength(u)&&(u=this._generateDefaultCustomId()),this.registerCustomId(u),u}_applyGenerationStrategy(t,r){switch(t){case"parentConversion":return Il(this.defaultPrefix);case"pasteReference":return kl(r,this.suffixIncrement);default:return Sl(this.defaultPrefix)}}generateCustomIdForRestoredChild(t=null){if(t){let i=t.trim();if(i.length>0){let n=this.extractPrefix(i),a=this.extractSuffix(i),s=mt(a,this.suffixIncrement),o=this.getNextAvailableSuffix(n,s);if(o===null){let l=this._generateDefaultCustomId();return this.registerCustomId(l),l}let c=`${n}${o}`;return this._exceedsMaxLength(c)&&(c=this._generateDefaultCustomId()),this.registerCustomId(c),c}}let r=this.generateNextCustomId(this.defaultPrefix);return this.registerCustomId(r),r}clear(){this.prefixMap.clear(),this.processedIds.clear()}getTotalPrefixes(){return this.prefixMap.size}hasPrefix(t){return this.prefixMap.has(t)}isCustomIdInUse(t,r=null){if(!t||typeof t!="string"||!t.trim())return!1;let i=t.trim();return r&&i===r.trim()?!1:this.processedIds.has(i)}};var Wh=new Set(["startDate","endDate","constraintDate"]);function Tl(e,t){return Wh.has(e)&&typeof t=="string"?new Date(t):t}var jr=class{_journal=null;begin(){this._journal={dirty:new Set,before:new Map,ops:[],linkFieldCaptured:new Set,correlativeBefore:new Map,scheduledBefore:new Map}}peek(){return this._journal}end(){this._journal=null}note(t,r){let i=this._journal;i&&(i.before.has(t)||i.before.set(t,yn(r)),i.dirty.add(t))}noteInsert(t){this._journal?.ops.push({kind:"insert",activityId:t})}noteRemove(t,r){this._journal?.ops.push({kind:"remove",activityId:t,before:yn(r)})}noteLinkAdd(t){this._journal?.ops.push({kind:"link-add",linkId:t})}noteLinkRemove(t,r){this._journal?.ops.push({kind:"link-remove",linkId:t,before:_l(r)})}noteCorrelativeBefore(t,r){let i=this._journal;!i||i.correlativeBefore.has(t)||i.correlativeBefore.set(t,r)}noteScheduledBefore(t,r){let i=this._journal;!i||i.scheduledBefore.has(t)||i.scheduledBefore.set(t,yn(r))}noteLinkField(t,r){let i=this._journal;!i||i.linkFieldCaptured.has(t)||(i.linkFieldCaptured.add(t),i.ops.push({kind:"link-field",linkId:t,before:_l(r)}))}};function yn(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:e.constraintDate?new Date(e.constraintDate):null,dateOrigin:e.dateOrigin?new Date(e.dateOrigin):null,newActivityIds:[...e.newActivityIds],pendingRequestIds:[...e.pendingRequestIds],responsableIds:[...e.responsableIds],tagIds:[...e.tagIds],baselinePoints:[...e.baselinePoints]}}function _l(e){return{...e}}var Vr=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=Pl(t);return this.reader.getCalendar(r??Le)}getClosestWorkTime(t){let r=`${gn(t.task)}|${t.dir}|${t.date.getTime()}`;return mn(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:et.HOUR}))}calculateEndDate(t){let r=`${gn(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return mn(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${gn(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return mn(this._cache.duration,r,()=>this.resolveCalendar(t.task).calculateDuration(t.startDate,t.endDate))}clearCache(){this._cache.closestWorkTime.clear(),this._cache.endDate.clear(),this._cache.duration.clear()}};function mn(e,t,r){let i=e.get(t);if(i!==void 0)return i;let n=r();return e.set(t,n),n}var Uh="__default__";function Pl(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function gn(e){return Pl(e)??Uh}var Yr=class{constructor(t){this.activities=t}activities;_childrenByParent=new Map;_roots=[];_dirty=!1;markDirty(){this._dirty=!0}getChildren(t){return this._dirty&&(this.rebuild(),this._dirty=!1),this._childrenByParent.get(String(t))??[]}hasChildren(t){return this._dirty&&(this.rebuild(),this._dirty=!1),(this._childrenByParent.get(String(t))?.length??0)>0}getRootIds(){return this._dirty&&(this.rebuild(),this._dirty=!1),[...this._roots]}isChildOf(t,r){let i=this.activities.get(t)?.parentId,n=0,a=this.activities.size;for(;i&&!O(i);){if(i===r)return!0;if(++n>a)return!1;i=this.activities.get(i)?.parentId}return!1}getParent(t){let r=this.activities.get(t)?.parentId;return!r||O(r)?null:this.activities.get(r)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,r){if(this._dirty)return;if(O(t)){this._roots.push(r);return}let i=String(t),n=this._childrenByParent.get(i);n?n.push(r):this._childrenByParent.set(i,[r])}rebuild(){this._childrenByParent.clear(),this._roots=[];for(let t of this.activities.values()){if(O(t.parentId)){this._roots.push(t.id);continue}let r=String(t.parentId),i=this._childrenByParent.get(r)??[];i.push(t.id),this._childrenByParent.set(r,i)}}};var $r=class{checkedSet=new Set;hiddenSet=new Set;isChecked(t){return this.checkedSet.has(t)}isVisible(t){return!this.hiddenSet.has(t)}checkedIds(){return[...this.checkedSet]}checkedCount(){return this.checkedSet.size}setChecked(t,r){return r===this.checkedSet.has(t)?!1:(r?this.checkedSet.add(t):this.checkedSet.delete(t),!0)}setVisible(t,r){return r===!this.hiddenSet.has(t)?!1:(r?this.hiddenSet.delete(t):this.hiddenSet.add(t),!0)}forget(t){this.checkedSet.delete(t),this.hiddenSet.delete(t)}hydrate(t){this.checkedSet=new Set(t.checkedIds??[]),this.hiddenSet=new Set(t.hiddenIds??[])}snapshot(){return{checked:new Set(this.checkedSet),hidden:new Set(this.hiddenSet)}}restore(t){this.checkedSet=new Set(t.checked),this.hiddenSet=new Set(t.hidden)}};var Gr=class{_activities=new Map;_lastStartDate=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_cache={ids:null,visualOrderIds:null};_writeCapture=new jr;_viewState=new $r;_viewStateBefore=null;_lastStartDateBefore=null;_calendar;_flags;constructor(t){for(let r of t.activities)this._activities.set(r.id,r);for(let r of t.links)this._links.set(String(r.id),r),this._indexLink(r);this._calendar=new Vr(bc(t.calendars)),this._flags=Hh(t),this._hierarchy=new Yr(this._activities),this._hierarchy.rebuild()}getAllActivities(){return Array.from(this._activities.values())}getAllLinks(){return Array.from(this._links.values())}getAllIds(){return this._cache.ids?this._cache.ids:(this._cache.ids=Array.from(this._activities.keys()),this._cache.ids)}activityCount(){return this._activities.size}getVisualOrderIds(){return this._cache.visualOrderIds?this._cache.visualOrderIds:(this._cache.visualOrderIds=Es(this).map(t=>String(t.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null}forEachActivity(t){for(let[r,i]of this._activities)t(i,r)}getParentId(t){return this._hierarchy.getParentId(t)}getActivity(t){return this._activities.get(String(t))??null}getLastStartDate(t){return this._lastStartDate.get(String(t))??null}setLastStartDate(t,r){this._captureLastStartDateOnce(),this._lastStartDate.set(String(t),r)}_captureLastStartDateOnce(){this._writeCapture.peek()!==null&&this._lastStartDateBefore===null&&(this._lastStartDateBefore=new Map(this._lastStartDate))}getLink(t){return this._links.get(String(t))??null}activityExists(t){return this._activities.has(String(t))}isChecked(t){return this._viewState.isChecked(String(t))}isVisible(t){return this._viewState.isVisible(String(t))}checkedIds(){return this._viewState.checkedIds()}setChecked(t,r){return this._captureViewStateOnce(),this._viewState.setChecked(String(t),r)}setVisible(t,r){return this._captureViewStateOnce(),this._viewState.setVisible(String(t),r)}hydrateViewState(t){this._viewState.hydrate(t)}_captureViewStateOnce(){this._writeCapture.peek()!==null&&this._viewStateBefore===null&&(this._viewStateBefore=this._viewState.snapshot())}getOutgoingLinkIds(t){return this._outgoing.get(String(t))??El}getIncomingLinkIds(t){return this._incoming.get(String(t))??El}getChildren(t){return this._hierarchy.getChildren(t)}hasChildren(t){return this._hierarchy.hasChildren(t)}isChildOf(t,r){return this._hierarchy.isChildOf(t,r)}getParent(t){return this._hierarchy.getParent(t)}getRootIds(){return this._hierarchy.getRootIds()}getClosestWorkTime(t){return this._calendar.getClosestWorkTime(t)}calculateEndDate(t){return this._calendar.calculateEndDate(t)}calculateDuration(t){return this._calendar.calculateDuration(t)}clearCalendarCache(){this._calendar.clearCache()}get calendarReader(){return this._calendar.reader}batchUpdate(t){t()}updateActivity(t){}getLiveActivity(t){return this.getActivity(t)}getFlags(){return{...this._flags,allCheckedTaskIds:this._viewState.checkedIds()}}getProjectEnd(){return null}beginWriteCapture(){this._writeCapture.begin(),this._viewStateBefore=null,this._lastStartDateBefore=null}peekWriteCapture(){return this._writeCapture.peek()}endWriteCapture(){this._writeCapture.end(),this._viewStateBefore=null,this._lastStartDateBefore=null}setActivityField(t,r,i){let n=this.getActivity(t);n&&(this._writeCapture.note(String(t),n),n[r]=i,r===L.PARENT&&this._hierarchy.markDirty(),vn(r)&&(this._cache.visualOrderIds=null))}setActivityFieldDynamic(t,r,i){let n=this.getActivity(t);if(n){if(!Object.hasOwn(n,r))throw new Error(`setActivityFieldDynamic: unknown CoreActivity field "${r}"`);this._writeCapture.note(String(t),n),Reflect.set(n,r,Tl(r,i)),r===L.PARENT&&this._hierarchy.markDirty(),vn(r)&&(this._cache.visualOrderIds=null)}}setActivityFields(t,r){let i=this.getActivity(t);if(!i)return;this._writeCapture.note(String(t),i);let n=!1;for(let a of Object.keys(r))Reflect.set(i,a,Reflect.get(r,a)),a===L.PARENT&&(n=!0),vn(a)&&(this._cache.visualOrderIds=null);n&&this._hierarchy.markDirty()}addLink(t){this._writeCapture.noteLinkAdd(String(t.id));let r=this._links.get(String(t.id));r&&this._deindexLink(r),this._links.set(String(t.id),{...t}),this._indexLink(t)}_indexLink(t){Ll(this._outgoing,String(t.source),t.id),Ll(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),Rl(r,t.id));let i=this._incoming.get(String(t.target));i&&this._incoming.set(String(t.target),Rl(i,t.id))}setLinkField(t,r,i){let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),n[r]=i)}setLinkFieldDynamic(t,r,i){if(!Bh(r))return;let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),Reflect.set(n,r,i))}setLinkProplannerId(t,r){let i=this.getLink(t);i&&(this._writeCapture.noteLinkField(String(t),i),i.proplannerId=r)}removeLink(t){let r=this.getLink(t);r&&(this._writeCapture.noteLinkRemove(String(t),r),this._links.delete(String(t)),this._deindexLink(r))}addActivity(t){this._writeCapture.noteInsert(String(t.id)),this._activities.set(t.id,t),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.addChild(t.parentId,t.id)}removeActivity(t){let r=this.getActivity(t);r&&this._writeCapture.noteRemove(String(t),r);let i=String(t);(this._viewState.isChecked(i)||!this._viewState.isVisible(i))&&(this._captureViewStateOnce(),this._viewState.forget(i)),this._activities.delete(t),this._lastStartDate.has(String(t))&&(this._captureLastStartDateOnce(),this._lastStartDate.delete(String(t))),this._outgoing.delete(String(t)),this._incoming.delete(String(t)),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}noteCorrelativeBefore(t,r){this._writeCapture.noteCorrelativeBefore(t,r)}noteScheduledBefore(t,r){this._writeCapture.noteScheduledBefore(t,r)}restoreFromCapture(){let t=this._writeCapture.peek();if(!t)return;let{ops:r,before:i,correlativeBefore:n,scheduledBefore:a}=t;this._undoLinkAdds(r),this._undoInserts(r),this._reInsertRemovedActivities(r),this._reAddRemovedLinks(r),this._restoreLinkFields(r),this._restoreCorrelatives(n),this._restoreActivityFields(a),this._restoreActivityFields(i),this._viewStateBefore!==null&&this._viewState.restore(this._viewStateBefore),this._lastStartDateBefore!==null&&(this._lastStartDate=this._lastStartDateBefore),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}_restoreCorrelatives(t){for(let[r,i]of t){let n=this._activities.get(r);n&&(n.correlativeId=i)}}_undoLinkAdds(t){for(let r of t)r.kind==="link-add"&&this._detachLink(r.linkId)}_undoInserts(t){for(let r of t)r.kind==="insert"&&this._activities.delete(r.activityId)}_reInsertRemovedActivities(t){for(let r of t)r.kind==="remove"&&this._activities.set(r.activityId,r.before)}_reAddRemovedLinks(t){for(let r of t)r.kind==="link-remove"&&this._attachLink(r.before)}_restoreLinkFields(t){for(let r of t)r.kind==="link-field"&&this._links.has(r.linkId)&&this._links.set(r.linkId,r.before)}_restoreActivityFields(t){for(let[r,i]of t){let n=this._activities.get(r);n&&this._restoreScalarFields(n,i)}}_restoreScalarFields(t,r){for(let i of Object.keys(t))Object.hasOwn(r,i)||Reflect.deleteProperty(t,i);for(let i of Object.keys(r))Reflect.set(t,i,Reflect.get(r,i))}_attachLink(t){this._links.set(String(t.id),{...t}),this._indexLink(t)}_detachLink(t){let r=this.getLink(t);r&&(this._links.delete(String(t)),this._deindexLink(r))}},El=[];function Bh(e){return e===ui.LAG||e===ui.TYPE}function vn(e){return e===L.PARENT||e===L.CORRELATIVE_ID}function Rl(e,t){return e.filter(r=>String(r)!==String(t))}function Ll(e,t,r){let i=e.get(t);i?i.push(r):e.set(t,[r])}function Hh(e){let t=e.runtimeFlags??{};return{isPasting:!!t.isPasting,isBulkOperation:!!t.isBulkOperation,dragWithMultiple:!!t.dragWithMultiple,draggingSingleMilestone:!!t.draggingSingleMilestone,creatingActivity:!1,avoidAutoScheduleBeforeDrag:!1,maxPerformance:!!t.maxPerformance,allCheckedTaskIds:[]}}function bl(e){let t=[];e.forEachActivity((r,i)=>{r.type==="project"&&e.getChildren(String(i)).length===0&&t.push(String(i))});for(let r of t)e.setActivityField(r,L.TYPE,Zt),jh(e,r)}function jh(e,t){let r=e.getActivity(t);if(!r||!r.startDate||r.durationHours==null)return;let i=new Date(r.startDate);i.setUTCHours(0,0,0,0);let n=e.getClosestWorkTime({date:i,dir:q.FUTURE,task:r});if(n.getTime()===r.startDate.getTime())return;let a=e.calculateEndDate({startDate:n,durationHours:r.durationHours,task:r});e.setActivityField(t,L.START_DATE,n),e.setActivityField(t,L.END_DATE,a)}function Vh(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function Yh(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function wl(e){return{id:String(e.id),worktime:Yh(e.worktime)}}function Ol(e,t,r,i=[]){let n=t.map(Vh),a=[...r.map(wl),...i.map(wl)];return{activities:[...e],links:n,calendars:a}}var _t={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function xl(e){let t=e.clock??null,r=t?Ce(t()):null,i=e.reporter??Qt,n=Nr({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},i),a=n.sector;a.statusCriteria=Fe(e.statusCriteria);let s=n.calendars,o=n.baseCalendars??[],c=Ol(n.activities,n.links,n.calendars,o),l=new Gr(c);l.hydrateViewState({hiddenIds:n.viewStateSeed.hiddenIds});let d=new Je(l,i);bl(l);let u=fl({knownIds:n.activities.map(A=>A.id)}),f=pl({knownIds:n.links.map(A=>A.id)}),p=hl({knownIds:n.activities.map(A=>A.uniqueCorrelativeId)}),v=new Hr({defaultPrefix:a.customIdPrefix,suffixIncrement:a.customIdIncrement});if(v.populateFromActivities(n.activities),e.baselinePoints&&e.baselinePoints.length>0){let A=o.find(D=>D.baseDefault)?.id??null;Rr(l,e.baselinePoints,r,i,A)}let S=Ns({state:l,sector:a,scheduler:d,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:r??void 0});return{sector:a,state:l,scheduler:d,activityIdGen:u,linkIdGen:f,uidGen:p,customIdTracker:v,calendars:s,baseCalendars:o,clock:t,reporter:i,initPromise:S}}function Nl(e,t,r,i){let n=new Set,a=new Set;for(let s of e){let o=String(s.id);if(o.length===0||n.has(o))throw new Error(`acknowledgePersistence: duplicate or empty ${t} id "${o}"`);if(!Number.isSafeInteger(s.proplannerId)||s.proplannerId<=0||a.has(s.proplannerId))throw new Error(`acknowledgePersistence: invalid or duplicate ${t} proplannerId ${String(s.proplannerId)}`);let c=r(o);if(!c.exists)throw new Error(`acknowledgePersistence: unknown ${t} id "${o}"`);if(c.current!==null&&c.current!==s.proplannerId)throw new Error(`acknowledgePersistence: ${t} "${o}" already has proplannerId ${String(c.current)}`);let l=i.get(s.proplannerId);if(l!==void 0&&l!==o)throw new Error(`acknowledgePersistence: ${t} proplannerId ${String(s.proplannerId)} already belongs to "${l}"`);n.add(o),a.add(s.proplannerId)}}var Kr=class{_status=_t.READY;_dispatchInFlight=!1;coreRuntime;_undo=new wr;_opQueue=Promise.resolve();_mutationEpoch=0;_cpComputedEpoch=0;constructor(t){let r=xl(t);this.coreRuntime={state:r.state,scheduler:r.scheduler,sector:r.sector,activityIdGenerator:r.activityIdGen,linkIdGenerator:r.linkIdGen,uniqueCorrelativeIdGenerator:r.uidGen,customIdTracker:r.customIdTracker,clock:r.clock,calendars:new Map(r.calendars.map(n=>[n.id,n])),baseCalendars:r.baseCalendars,reporter:r.reporter},this._initPromise=r.initPromise.then(()=>{this._status!==_t.DESTROYED&&this._saveTracker.init(this.coreRuntime.state.getAllActivities(),this.getAllLinksView())}),this._criticalPathReady=this._initPromise.then(()=>this._enqueue(()=>this._runCriticalPathAndCapture()));let i=t.criticalPathOnLoad===!0;this._ready=i?this._criticalPathReady.then(()=>{}):this._initPromise}get ready(){return this._ready}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return this.coreRuntime.sector}getActivityView(t){return this.assertReady(),zo(this.coreRuntime.state,t)}getAllActivitiesView(){return this.assertReady(),qo(this.coreRuntime.state)}getChildrenView(t){return this.assertReady(),Zo(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),ec(this.coreRuntime.state,t)}getAllLinksView(){return this.assertReady(),rc(this.coreRuntime.state)}getProperty(t,r){this.assertReady();let i=this.coreRuntime.state.getActivity(t);return i?i[r]:null}getAllIds(){return this.assertReady(),Jo(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),Xo(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),qi(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),Qo(this.coreRuntime.state)}getVisualOrderIds(){return this.assertReady(),this.coreRuntime.state.getVisualOrderIds()}hasChild(t){return this.assertReady(),tc(this.coreRuntime.state,t)}getCalendar(t){return this.assertReady(),this.coreRuntime.calendars.get(t)??null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values())}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),pc(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(this.getAllLinksView())}markLinksPersisted(){this._saveTracker.snapshotLinks(this.getAllLinksView())}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(this.coreRuntime.state.getAllActivities())}markActivitiesPersisted(){this._saveTracker.snapshotActivities(this.coreRuntime.state.getAllActivities())}acknowledgePersistence(t){this.assertReady();let r=t.activities??[],i=t.links??[],n=new Map;for(let s of this.coreRuntime.state.getAllActivities())s.proplannerId!=null&&n.set(s.proplannerId,String(s.id));let a=new Map;for(let s of this.coreRuntime.state.getAllLinks())s.proplannerId!=null&&a.set(s.proplannerId,String(s.id));Nl(r,"activity",s=>{let o=this.coreRuntime.state.getActivity(s);return{exists:o!==null,current:o?.proplannerId??null}},n),Nl(i,"link",s=>{let o=this.coreRuntime.state.getLink(s);return{exists:o!==null,current:o?.proplannerId??null}},a),this.coreRuntime.state.batchUpdate(()=>{for(let s of r)this.coreRuntime.state.setActivityField(s.id,"proplannerId",s.proplannerId);for(let s of i)this.coreRuntime.state.setLinkProplannerId(s.id,s.proplannerId)}),this.markActivitiesPersisted(),this.markLinksPersisted()}applyBaselines(t){this.assertReady();let r=this.coreRuntime.clock?Ce(this.coreRuntime.clock()):null,i=this.coreRuntime.baseCalendars.find(n=>n.baseDefault)?.id??null;return uc(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay,t,r,this.coreRuntime.reporter,i)}recomputeAllPonderators(t){return this.assertReady(),lc(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay,t)}recomputeAllProgressRollup(){return this.assertReady(),dc(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay)}setStatusCriteria(t){this.assertReady();let r=Fe(t);return this.coreRuntime.sector.statusCriteria=r,fc(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay,r)}allocateActivityId(){return this.assertReady(),this.coreRuntime.activityIdGenerator.next()}createActivity(t){if(this.assertReady(),this._dispatchInFlight)throw new Error("[ScheduleCore] createActivity called during an in-flight dispatch");let r={kind:"activity-create",...t};this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let i;try{i=bo(r,{adapter:this.coreRuntime.state,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker}),i.ok||this._rollback()}catch(n){throw this._rollback(),n}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return i.ok?{ok:!0,activity:i.activity,changes:i.changes}:i}_enqueue(t){let r=this._opQueue.then(t,t);return this._opQueue=r.then(()=>{},()=>{}),r}async dispatch(t,r={}){return this._enqueue(()=>this._dispatchInner(t,r))}async _dispatchInner(t,r={}){this.assertReady();let i=Oc(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat,inputUnit:r.inputUnit??"days"}),n=Bc(t);this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction(),this._dispatchInFlight=!0;let a;try{a=await Ko(t,r,{adapter:this.coreRuntime.state,ctx:i,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,linkIdGen:this.coreRuntime.linkIdGenerator,uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(s=>s.baseDefault)?.id??null,now:this.coreRuntime.clock?Ce(this.coreRuntime.clock()):null}),a.ok||this._rollback()}catch(s){throw this._rollback(),s}finally{this._dispatchInFlight=!1,this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(a.ok&&n&&Hc(a.changes)){let s=Fc(this.coreRuntime.state,a.changes);this._undo.record(cn(a.changes,a.__beforeSnap,a.__beforeLinks,s.afterSnap,s.afterLinks),Mc(t),Date.now())}return a.ok?(r.skipCriticalPath&&this._mutationEpoch++,{...a,changes:a.changes}):a}recomputeCriticalPath(){return this._enqueue(()=>this._recomputeCriticalPathIfStale())}async _recomputeCriticalPathIfStale(){if(this._status===_t.DESTROYED)return null;let t=this._mutationEpoch;if(this._cpComputedEpoch===t)return null;let r=await this._runCriticalPathAndCapture();return this._cpComputedEpoch=t,r}async _runCriticalPathAndCapture(){if(this._status===_t.DESTROYED)return{changes:{source:{kind:"init"},activities:[],links:[],calendars:[],trackingEvents:[]}};this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let t;try{await pr(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay),t=K(this.coreRuntime.state,{source:{kind:"init"},beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay})}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return{changes:t}}undo(){return this._enqueue(async()=>{this.assertReady();let t=this._undo.takeUndo();return t?(jc(this.coreRuntime.state,t),this._mutationEpoch++,ln(t)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(t),this._undo.resetCoalesce(),dn(this.coreRuntime.state,t,"before")):null})}redo(){return this._enqueue(async()=>{this.assertReady();let t=this._undo.takeRedo();return t?(Vc(this.coreRuntime.state,t),this._mutationEpoch++,ln(t)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(t),this._undo.resetCoalesce(),dn(this.coreRuntime.state,t,"after")):null})}clearHistory(){this._undo.clear()}canUndo(){return this._undo.canUndo()}canRedo(){return this._undo.canRedo()}undoDepth(){return this._undo.undoDepth()}_resyncCustomIdTrackerFromModel(){this.coreRuntime.customIdTracker.clear(),this.coreRuntime.customIdTracker.populateFromActivities(this.coreRuntime.state.getAllActivities())}destroy(){this.coreRuntime.calendars.clear(),this._saveTracker.clear(),this._status=_t.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new Or;assertReady(){if(this._status===_t.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===_t.POISONED)throw new Error("[ScheduleCore] instance is poisoned (a rollback failed) \u2014 reload from backend")}_rollback(){try{this.coreRuntime.state.restoreFromCapture(),this.coreRuntime.customIdTracker.rollbackCustomIdTransaction()}catch(t){throw this._status=_t.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",t),t}}};function Fl(e,t){let r=new Map(e.map(i=>[String(i.id),i]));return t.filter(i=>{let n=r.get(String(i.id));return n?n.lag!==i.lag||n.type!==i.type:!1})}var Ml=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var Wl={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 Ul=8;var X={INLINE_EDIT:"inline-edit",DATES_BATCH:"dates-batch",BULK_EDIT:"bulk-edit",LINK_CREATE:"link-create",LINK_UPDATE:"link-update",LINK_DELETE:"link-delete",LINKS_BATCH:"links-batch",ACTIVITY_CREATE:"activity-create",ACTIVITY_DELETE:"activity-delete",ACTIVITY_MOVE:"activity-move",ACTIVITY_INDENT:"activity-indent",ACTIVITY_OUTDENT:"activity-outdent",ACTIVITY_SET_PROGRESS:"activity-set-progress",ACTIVITY_PASTE:"activity-paste",SELECTION_TOGGLE:"selection-toggle",SELECTION_REPLACE:"selection-replace",VISIBILITY_SET:"visibility-set",SIR_SYNC:"sir-sync",ACTIVITY_LOOKAHEAD_SYNC:"activity-lookahead-sync"},$h={[X.INLINE_EDIT]:!0,[X.DATES_BATCH]:!0,[X.BULK_EDIT]:!0,[X.LINK_CREATE]:!0,[X.LINK_UPDATE]:!0,[X.LINK_DELETE]:!0,[X.LINKS_BATCH]:!0,[X.ACTIVITY_CREATE]:!0,[X.ACTIVITY_DELETE]:!0,[X.ACTIVITY_MOVE]:!0,[X.ACTIVITY_INDENT]:!0,[X.ACTIVITY_OUTDENT]:!0,[X.ACTIVITY_SET_PROGRESS]:!0,[X.ACTIVITY_PASTE]:!0,[X.SELECTION_TOGGLE]:!0,[X.SELECTION_REPLACE]:!0,[X.VISIBILITY_SET]:!0,[X.SIR_SYNC]:!0,[X.ACTIVITY_LOOKAHEAD_SYNC]:!0},Bl=Object.keys($h);var Hl={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return Kl(Gh);})();
2
2
  //# sourceMappingURL=schedule-core.global.js.map